blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
616
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 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
sequencelengths 1
1
| author_id
stringlengths 1
132
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
edd042f5b2d0fa90c43f9451ea0b8549a7e1d32b | 7bededcada9271d92f34da6dae7088f3faf61c02 | /pypureclient/flashblade/FB_2_10/models/object_store_access_policy_action_response.py | 2a0764dd2f2a1eec8de689c8e0f360a56fadcca5 | [
"BSD-2-Clause"
] | permissive | PureStorage-OpenConnect/py-pure-client | a5348c6a153f8c809d6e3cf734d95d6946c5f659 | 7e3c3ec1d639fb004627e94d3d63a6fdc141ae1e | refs/heads/master | 2023-09-04T10:59:03.009972 | 2023-08-25T07:40:41 | 2023-08-25T07:40:41 | 160,391,444 | 18 | 29 | BSD-2-Clause | 2023-09-08T09:08:30 | 2018-12-04T17:02:51 | Python | UTF-8 | Python | false | false | 3,268 | py | # coding: utf-8
"""
FlashBlade REST API
A lightweight client for FlashBlade REST API 2.10, developed by Pure Storage, Inc. (http://www.purestorage.com/).
OpenAPI spec version: 2.10
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re
import six
import typing
from ....properties import Property
if typing.TYPE_CHECKING:
from pypureclient.flashblade.FB_2_10 import models
class ObjectStoreAccessPolicyActionResponse(object):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'items': 'list[ObjectStoreAccessPolicyAction]'
}
attribute_map = {
'items': 'items'
}
required_args = {
}
def __init__(
self,
items=None, # type: List[models.ObjectStoreAccessPolicyAction]
):
"""
Keyword args:
items (list[ObjectStoreAccessPolicyAction])
"""
if items is not None:
self.items = items
def __setattr__(self, key, value):
if key not in self.attribute_map:
raise KeyError("Invalid key `{}` for `ObjectStoreAccessPolicyActionResponse`".format(key))
self.__dict__[key] = value
def __getattribute__(self, item):
value = object.__getattribute__(self, item)
if isinstance(value, Property):
return None
else:
return value
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
if hasattr(self, attr):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(ObjectStoreAccessPolicyActionResponse, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ObjectStoreAccessPolicyActionResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"[email protected]"
] | |
08bfeae2350ed1c651b3c15cf39558ddead399b8 | f810836bea801f2fa85418ac7f5f5ffb0f3e0bda | /abc/abc237/D - LR insertion.py | b87e8c318a6bc75b348e71e58c1c21e407f300c6 | [] | no_license | cocoinit23/atcoder | 0afac334233e5f8c75d447f6adf0ddf3942c3b2c | 39f6f6f4cc893e794d99c514f2e5adc9009ee8ca | refs/heads/master | 2022-08-29T06:01:22.443764 | 2022-07-29T07:20:05 | 2022-07-29T07:20:05 | 226,030,199 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 384 | py | """
from collections import deque
n = int(input())
s = input()
ans = deque([n])
for i in range(n - 1, -1, -1):
if s[i] == 'R':
ans.appendleft(i)
else:
ans.append(i)
print(*ans)
"""
n = int(input())
s = input()
l = []
r = []
for i, c in enumerate(s):
if c == 'L':
r.append(i)
else:
l.append(i)
ans = l + [n] + r[::-1]
print(*ans)
| [
"[email protected]"
] | |
5c7375b81cad282b805c1d33d481cec56fd46b9d | 4f83471a669772731a7b1781d46be6c4eba7ef33 | /脚本化爬虫/购物类/Frys/get_Frys_info.py | a162ac5428aa36b14676fd4ff1170924dfb7a137 | [] | no_license | odtu945/LiuFan_Spider | 19a5eb08ebafc5865931bdf96aea2b9dd436a614 | 848b3aff4754c102491b201684858c3f116ff90b | refs/heads/master | 2022-01-05T10:12:32.085245 | 2019-03-24T02:30:38 | 2019-03-24T02:30:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,779 | py | import codecs
import re
from Tools import get_html
import time
import pytz
import random
from datetime import datetime,timedelta
from multiprocessing import Pool,Lock
# #把list洗乱
# def shuffle_list(list_name):
#
# from random import shuffle
# shuffle(list_name)
# # 返回随机排序后的序列
# return list_name
#
# #传入商品页面的html和商品的id
# def get_info(html):
#
# items_info = []
# print ('------------itemsId------------')
# itemsId_list = re.findall(r'<div id="ProductAttributes">.*?<li style=.*?>(.*?)</li>.*?</div>',html,re.S)
#
# itemsId = str(itemsId_list[0]).split('#')[1]
# print (itemsId)
# # items_info.append(str(itemsId))
#
# # print ' ------------title------------'
# title = itemsId_list[1]
# print (title)
# # items_info.append(str(title))
#
# # print ' ------------Price------------'
# price = re.findall(r'<label id="l_price1_value.*?>(.*?)</label>', html,re.S)
# print (price[0])
# # items_info.append(str(price[0]))
#
# # print '------------Stock------------'
# stock = re.findall(r'<div style="width:90%; float: left;">(.*?)</div>',html,re.S)
#
# items_info.append(str(stock))
#
# # print ' ------------brand------------'
#
# brand = result_response['brand']
# items_info.append(str(brand))
#
#
#
# # ------------Reviews------------
# # review = ''
# # review_count = re.findall(r'<span id="acrCustomerReviewText" class="a-size-base">(.*?)</span>',html,re.S)
# # print review_count+'======'
# # review = str(review_count).split(' ')[0]
# # items_info['reviews'] = review
#
# # print ' ------------image------------'
# image_list = result_response['image_list']
# if image_list == []:
# image_list = ['','','','','']
# while len(image_list) < 5:
# image_list.append("")
#
# # print type(image_list)
# images = image_list[:5] # 最多取5张图片
# items_info += images
#
# #------------details------------
# # 前有\xe2\x9c\x94 \xc2\xa0
# details_Feature = result_response['detail']
# details_list = details_Feature['Feature']
#
# if isinstance(details_list, str):
# details_list = [details_list]
# print details_list
#
# while len(details_list)<4:
# details_list.append("")
#
# details_list = details_list[:4]
# for i in range(0,4):
# details_list[i] = str(details_list[i]).replace('\n','').replace('\xe2\x9c\x94','').replace('\xc2\xa0','').replace('<br>','.').replace('</br>','')
#
# if str(details_list[i]).find("Refurbished") == -1 or str(details_list[i]).find("used") == -1:
# is_Refurbished = False
# else:
# is_Refurbished = True
#
# items_info += details_list
#
# # ------------Specification------------
# Specification = result_response['description']
# if Specification == None or len(Specification)>5000:
# Specification = '\n'
# if len(Specification) <5000:
# Specification = Specification[:1000]
# Specification = ''.join(Specification)
# Specification = Specification.replace('\n','').replace('\xe2\x9c\x94','').replace('\xc2\xa0','').replace('<b>','').replace('</b>','').replace('<br>','').replace('</br>','').replace('<br/>','')
#
# items_info.append(str(Specification))
# if str(Specification).find("Refurbished") == -1 or str(Specification).find("used") == -1:
# is_Refurbished = False
# else:
# is_Refurbished = True
#
# print '=====================END==================================='
# print items_info
#
#
# result_file.write("\t".join(items_info) + "\n")
#
# print '============='
# # f.flush()
# item_file.flush()
# result_file.flush()
#
#
# #把itemsId页面的html传入get_info函数中,把失败的id重新存一个文件
# def handle(itemsurl):
# try:
# #商品详情页
# #获取每一个商品页面的html
# html = get_html.get_PhantomJS_html(itemsurl)
# # print html
# # 获取每一个商品的asin
# print html
#
# if html:
# #调用get_info函数,传入html
# get_info(html)
# else:
# with open('./Result/get_html_fail.txt', 'aw') as h:
# h.write(itemsurl + '\n')
#
# except Exception, e:
# # print itemsurl, ":", e
# with open('./Result/fail_url.txt','aw') as fail_url:
# fail_url.write(itemsurl+'\n')
# # with open('./Result/no_except.txt', 'aw') as f:
# # f.write(itemsurl + '\n')
#
# #把items_last.txt文件中的字段制成表格
# def create_titles(filename, titles):
# f = open(filename, "w")
# f.write("\t".join(titles) + "\n")
# #清除内部缓冲区
# f.flush()
# #关闭文件
# f.close()
#
# #去重后的items的id文件
# def start(items_file,file_name):
#
# global result_file, lock, titles,fr,ferr,item_file
# titles = ['itemsId', 'price', 'stock', 'brand', 'title', 'img1', 'img2', 'img3', 'img4',
# 'img5', 'detail1', 'detail2', 'detail3', 'detail4', 'Specification']
# item_file = open(items_file, 'r')
#
# #调用函数create_titles
# create_titles(file_name, titles)
# result_file = open(file_name, 'aw')
# items_list = item_file.readlines()
# #把获取的url依次传入handle
# items = []
# for item in items_list:
# item = item.split('\n')[0]
# items.append(item)
# lock = Lock()
# pool = Pool(10)
# #调用函数把items的url依次传入handle函数中爬虫
# pool.map(handle, items)
# pool.close()
# pool.join()
#
# item_file.close()
# result_file.close()
def get_asin(base_url,page):
#Electronics : Computers & Accessories : Monitors : Prime Eligible : New
for i in range(0, page): # 页码
start_num = i*25
url = base_url.replace("[page]", str(i)).replace('[start]',str(start_num))
print (url)
# time.sleep(2)
html = get_html.get_html(url)
url_list_re = re.findall(r'<td colspan="2">(.*?)</td>', html, re.S)
print (url_list_re)
url_list = re.findall(r'<A HREF="(.*?)">',str(url_list_re),re.S)
print (url_list)
print (len(url_list))
for goods_url in url_list:
with open("./Result/items_url.txt", "aw") as f:
f.write('http://www.frys.com/'+goods_url + "\n")
print (goods_url)
if __name__ == "__main__":
url = '''http://www.frys.com/search?cat=-68332&pType=pDisplay&resultpage=[page]&start=[start]&rows=25'''
page = 5
file_name = './Result/tablets.xls'
get_asin(url, page)
# start('./Result/items_url.txt',file_name)
| [
"[email protected]"
] | |
07d65e5a9c7180d039cc8a63759cfb25a4047fa9 | 2473c916422a0b517596c70206603d7b0161ef84 | /src/radical/pilot/worker/update.py | 42f9813bd9df1c108aa4d7632e723926049220fd | [
"MIT"
] | permissive | jerome-labbe-sb/radical.pilot | a8bf679ba943505779ecac2f3c06864710dd54af | a911e97c61262e07055a0f11db5a8157e981f8fb | refs/heads/master | 2021-01-14T13:21:34.564661 | 2016-09-09T21:42:02 | 2016-09-09T21:42:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,226 | py |
__copyright__ = "Copyright 2016, http://radical.rutgers.edu"
__license__ = "MIT"
import time
import threading
import radical.utils as ru
from .. import utils as rpu
from .. import states as rps
from .. import constants as rpc
# ==============================================================================
#
class Update(rpu.Worker):
"""
An UpdateWorker pushes CU and Pilot state updates to mongodb. Its instances
compete for update requests on the update_queue. Those requests will be
triplets of collection name, query dict, and update dict. Update requests
will be collected into bulks over some time (BULK_COLLECTION_TIME), to
reduce number of roundtrips.
"""
# --------------------------------------------------------------------------
#
def __init__(self, cfg):
rpu.Worker.__init__(self, 'AgentUpdateWorker', cfg)
# --------------------------------------------------------------------------
#
@classmethod
def create(cls, cfg):
return cls(cfg)
# --------------------------------------------------------------------------
#
def initialize_child(self):
self._session_id = self._cfg['session_id']
self._mongodb_url = self._cfg['mongodb_url']
self._pilot_id = self._cfg['pilot_id']
_, db, _, _, _ = ru.mongodb_connect(self._mongodb_url)
self._mongo_db = db
self._cinfo = dict() # collection cache
self._lock = threading.RLock() # protect _cinfo
self._state_cache = dict() # used to preserve state ordering
self.declare_subscriber('state', 'agent_state_pubsub', self.state_cb)
self.declare_idle_cb(self.idle_cb, self._cfg.get('bulk_collection_time'))
# all components use the command channel for control messages
self.declare_publisher ('command', rpc.AGENT_COMMAND_PUBSUB)
# communicate successful startup
self.publish('command', {'cmd' : 'alive',
'arg' : self.cname})
# --------------------------------------------------------------------------
#
def finalize_child(self):
# communicate finalization
self.publish('command', {'cmd' : 'final',
'arg' : self.cname})
# --------------------------------------------------------------------------
#
def _ordered_update(self, cu, state, timestamp=None):
"""
The update worker can receive states for a specific unit in any order.
If states are pushed straight to the DB, the state attribute of a unit
may not reflect the actual state. This should be avoided by re-ordering
on the client side DB consumption -- but until that is implemented we
enforce ordered state pushes to MongoDB. We do it like this:
- for each unit arriving in the update worker
- check if new state is final
- yes: push update, but never push any update again (only update
state history)
- no:
check if all expected earlier states are pushed already
- yes: push this state also
- no: only update state history
"""
s2i = {rps.NEW : 0,
rps.PENDING : 1,
rps.PENDING_LAUNCH : 2,
rps.LAUNCHING : 3,
rps.PENDING_ACTIVE : 4,
rps.ACTIVE : 5,
rps.UNSCHEDULED : 6,
rps.SCHEDULING : 7,
rps.PENDING_INPUT_STAGING : 8,
rps.STAGING_INPUT : 9,
rps.AGENT_STAGING_INPUT_PENDING : 10,
rps.AGENT_STAGING_INPUT : 11,
rps.ALLOCATING_PENDING : 12,
rps.ALLOCATING : 13,
rps.EXECUTING_PENDING : 14,
rps.EXECUTING : 15,
rps.AGENT_STAGING_OUTPUT_PENDING : 16,
rps.AGENT_STAGING_OUTPUT : 17,
rps.PENDING_OUTPUT_STAGING : 18,
rps.STAGING_OUTPUT : 19,
rps.DONE : 20,
rps.CANCELING : 21,
rps.CANCELED : 22,
rps.FAILED : 23
}
i2s = {v:k for k,v in s2i.items()}
s_max = rps.FAILED
if not timestamp:
timestamp = rpu.timestamp()
# we always push state history
update_dict = {'$push': {
'statehistory': {
'state' : state,
'timestamp': timestamp}}}
uid = cu['_id']
# self._log.debug(" === inp %s: %s" % (uid, state))
if uid not in self._state_cache:
self._state_cache[uid] = {'unsent' : list(),
'final' : False,
'last' : rps.AGENT_STAGING_INPUT_PENDING} # we get the cu in this state
cache = self._state_cache[uid]
# if unit is already final, we don't push state
if cache['final']:
# self._log.debug(" === fin %s: %s" % (uid, state))
return update_dict
# if unit becomes final, push state and remember it
if state in [rps.DONE, rps.FAILED, rps.CANCELED]:
cache['final'] = True
cache['last'] = state
update_dict['$set'] = {'state': state}
# self._log.debug(" === Fin %s: %s" % (uid, state))
return update_dict
# check if we have any consecutive list beyond 'last' in unsent
cache['unsent'].append(state)
# self._log.debug(" === lst %s: %s %s" % (uid, cache['last'], cache['unsent']))
new_state = None
for i in range(s2i[cache['last']]+1, s2i[s_max]):
# self._log.debug(" === chk %s: %s in %s" % (uid, i2s[i], cache['unsent']))
if i2s[i] in cache['unsent']:
new_state = i2s[i]
cache['unsent'].remove(i2s[i])
# self._log.debug(" === uns %s: %s" % (uid, new_state))
else:
# self._log.debug(" === brk %s: %s" % (uid, new_state))
break
if new_state:
# self._log.debug(" === new %s: %s" % (uid, new_state))
state = new_state
cache['last'] = state
# self._log.debug(" === set %s: %s" % (uid, state))
update_dict['$set'] = {'state': state}
# record if final state is sent
if state in [rps.DONE, rps.FAILED, rps.CANCELED]:
# self._log.debug(" === FIN %s: %s" % (uid, state))
cache['final'] = True
return update_dict
# --------------------------------------------------------------------------
#
def _timed_bulk_execute(self, cinfo):
# is there any bulk to look at?
if not cinfo['bulk']:
return False
now = time.time()
age = now - cinfo['last']
# only push if collection time has been exceeded
if not age > self._cfg['bulk_collection_time']:
return False
res = cinfo['bulk'].execute()
self._log.debug("bulk update result: %s", res)
self._prof.prof('unit update bulk pushed (%d)' % len(cinfo['uids']), uid=self._pilot_id)
for entry in cinfo['uids']:
uid = entry[0]
state = entry[1]
if state:
self._prof.prof('update', msg='unit update pushed (%s)' % state, uid=uid)
else:
self._prof.prof('update', msg='unit update pushed', uid=uid)
cinfo['last'] = now
cinfo['bulk'] = None
cinfo['uids'] = list()
return True
# --------------------------------------------------------------------------
#
def idle_cb(self):
action = 0
with self._lock:
for cname in self._cinfo:
action += self._timed_bulk_execute(self._cinfo[cname])
return bool(action)
# --------------------------------------------------------------------------
#
def state_cb(self, topic, msg):
cu = msg
# FIXME: we don't have any error recovery -- any failure to update unit
# state in the DB will thus result in an exception here and tear
# down the pilot.
#
# FIXME: at the moment, the update worker only operates on units.
# Should it accept other updates, eg. for pilot states?
#
# got a new request. Add to bulk (create as needed),
# and push bulk if time is up.
uid = cu['_id']
state = cu.get('state')
timestamp = cu.get('state_timestamp', rpu.timestamp())
if 'clone' in uid:
return
self._prof.prof('get', msg="update unit state to %s" % state, uid=uid)
cbase = cu.get('cbase', '.cu')
query_dict = cu.get('query')
update_dict = cu.get('update')
if not query_dict:
query_dict = {'_id' : uid} # make sure unit is not final?
if not update_dict:
update_dict = self._ordered_update (cu, state, timestamp)
# when the unit is about to leave the agent, we also update stdout,
# stderr exit code etc
# FIXME: this probably should be a parameter ('FULL') on 'msg'
if state in [rps.DONE, rps.FAILED, rps.CANCELED, rps.PENDING_OUTPUT_STAGING]:
if not '$set' in update_dict:
update_dict['$set'] = dict()
update_dict['$set']['stdout' ] = cu.get('stdout')
update_dict['$set']['stderr' ] = cu.get('stderr')
update_dict['$set']['exit_code'] = cu.get('exit_code')
# check if we handled the collection before. If not, initialize
cname = self._session_id + cbase
with self._lock:
if not cname in self._cinfo:
self._cinfo[cname] = {
'coll' : self._mongo_db[cname],
'bulk' : None,
'last' : time.time(), # time of last push
'uids' : list()
}
# check if we have an active bulk for the collection. If not,
# create one.
cinfo = self._cinfo[cname]
if not cinfo['bulk']:
cinfo['bulk'] = cinfo['coll'].initialize_ordered_bulk_op()
# push the update request onto the bulk
cinfo['uids'].append([uid, state])
cinfo['bulk'].find (query_dict) \
.update(update_dict)
self._prof.prof('bulk', msg='bulked (%s)' % state, uid=uid)
# attempt a timed update
self._timed_bulk_execute(cinfo)
# ------------------------------------------------------------------------------
| [
"[email protected]"
] | |
9bde53a4965ad421599d521020416e1db9e0916f | c50e7eb190802d7849c0d0cea02fb4d2f0021777 | /src/amg/azext_amg/vendored_sdks/_dashboard_management_client.py | 673cde0f190c519ac78730831c000fed3d99e2f4 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | Azure/azure-cli-extensions | c1615b19930bba7166c282918f166cd40ff6609c | b8c2cf97e991adf0c0a207d810316b8f4686dc29 | refs/heads/main | 2023-08-24T12:40:15.528432 | 2023-08-24T09:17:25 | 2023-08-24T09:17:25 | 106,580,024 | 336 | 1,226 | MIT | 2023-09-14T10:48:57 | 2017-10-11T16:27:31 | Python | UTF-8 | Python | false | false | 5,405 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, TYPE_CHECKING
from azure.core.rest import HttpRequest, HttpResponse
from azure.mgmt.core import ARMPipelineClient
from . import models as _models
from ._configuration import DashboardManagementClientConfiguration
from ._serialization import Deserializer, Serializer
from .operations import (
EnterpriseDetailsOperations,
GrafanaOperations,
Operations,
PrivateEndpointConnectionsOperations,
PrivateLinkResourcesOperations,
)
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential
class DashboardManagementClient: # pylint: disable=client-accepts-api-version-keyword
"""The Microsoft.Dashboard Rest API spec.
:ivar operations: Operations operations
:vartype operations: azure.mgmt.dashboard.operations.Operations
:ivar grafana: GrafanaOperations operations
:vartype grafana: azure.mgmt.dashboard.operations.GrafanaOperations
:ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations
:vartype private_endpoint_connections:
azure.mgmt.dashboard.operations.PrivateEndpointConnectionsOperations
:ivar private_link_resources: PrivateLinkResourcesOperations operations
:vartype private_link_resources: azure.mgmt.dashboard.operations.PrivateLinkResourcesOperations
:ivar enterprise_details: EnterpriseDetailsOperations operations
:vartype enterprise_details: azure.mgmt.dashboard.operations.EnterpriseDetailsOperations
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: The ID of the target subscription. Required.
:type subscription_id: str
:param base_url: Service URL. Default value is "https://management.azure.com".
:type base_url: str
:keyword api_version: Api Version. Default value is "2022-10-01-preview". Note that overriding
this default value may result in unsupported behavior.
:paramtype api_version: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "TokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = DashboardManagementClientConfiguration(
credential=credential, subscription_id=subscription_id, **kwargs
)
self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.grafana = GrafanaOperations(self._client, self._config, self._serialize, self._deserialize)
self.private_endpoint_connections = PrivateEndpointConnectionsOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.private_link_resources = PrivateLinkResourcesOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.enterprise_details = EnterpriseDetailsOperations(
self._client, self._config, self._serialize, self._deserialize
)
def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = client._send_request(request)
<HttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.HttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
def close(self) -> None:
self._client.close()
def __enter__(self) -> "DashboardManagementClient":
self._client.__enter__()
return self
def __exit__(self, *exc_details) -> None:
self._client.__exit__(*exc_details)
| [
"[email protected]"
] | |
6b3b6c712d369e9de58b67fd7edfeb5615cd37e1 | a5e6ce10ff98539a94a5f29abbc053de9b957cc6 | /competition/20181125/d.py | da13b71ffe3d2ec5a7d23f0f506885ff52d138b9 | [] | no_license | shimaw28/atcoder_practice | 5097a8ec636a9c2e9d6c417dda5c6a515f1abd9c | 808cdc0f2c1519036908118c418c8a6da7ae513e | refs/heads/master | 2020-07-26T10:59:51.927217 | 2020-06-13T11:53:19 | 2020-06-13T11:53:19 | 208,622,939 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 140 | py | s = input()
#%%
# s = "codethanksfes"
#%%
a = s[0]
ans = 0
for l in s:
if l<=a:
a = l
ans += 1
print(ans)
#%%
| [
"[email protected]"
] | |
b6d4e1e3a30fef69db367420cab731baab417ab0 | 28053d2ad657d2e6d29396a3b4138cf3946511d0 | /libreco/algorithms/youtube_ranking.py | 3f8f3a810af24728415e4269766015d240d2d43c | [
"MIT"
] | permissive | RaRedmer/LibRecommender | 94a3f52b2f0c331bd70d5f0a99db867a3d742ad6 | 117b84e3deeb7157e62f464ff84ff9fab63f00ed | refs/heads/master | 2023-02-11T05:40:34.112189 | 2021-01-16T17:05:50 | 2021-01-16T17:05:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,396 | py | """
Reference: Paul Covington et al. "Deep Neural Networks for YouTube Recommendations"
(https://static.googleusercontent.com/media/research.google.com/zh-CN//pubs/archive/45530.pdf)
author: massquantity
"""
import os
from itertools import islice
import numpy as np
import tensorflow as tf2
from tensorflow.keras.initializers import (
truncated_normal as tf_truncated_normal
)
from .base import Base, TfMixin
from ..evaluate.evaluate import EvalMixin
from ..utils.tf_ops import (
reg_config,
dropout_config,
dense_nn,
lr_decay_config
)
from ..data.data_generator import DataGenSequence
from ..data.sequence import user_last_interacted
from ..utils.misc import time_block, colorize
from ..feature import (
get_predict_indices_and_values,
get_recommend_indices_and_values
)
tf = tf2.compat.v1
tf.disable_v2_behavior()
class YouTubeRanking(Base, TfMixin, EvalMixin):
"""
The model implemented mainly corresponds to the ranking phase
based on the original paper.
"""
def __init__(
self,
task="ranking",
data_info=None,
embed_size=16,
n_epochs=20,
lr=0.01,
lr_decay=False,
reg=None,
batch_size=256,
num_neg=1,
use_bn=True,
dropout_rate=None,
hidden_units="128,64,32",
recent_num=10,
random_num=None,
seed=42,
lower_upper_bound=None,
tf_sess_config=None
):
Base.__init__(self, task, data_info, lower_upper_bound)
TfMixin.__init__(self, tf_sess_config)
EvalMixin.__init__(self, task, data_info)
self.task = task
self.data_info = data_info
self.embed_size = embed_size
self.n_epochs = n_epochs
self.lr = lr
self.lr_decay = lr_decay
self.reg = reg_config(reg)
self.batch_size = batch_size
self.num_neg = num_neg
self.use_bn = use_bn
self.dropout_rate = dropout_config(dropout_rate)
self.hidden_units = list(map(int, hidden_units.split(",")))
self.n_users = data_info.n_users
self.n_items = data_info.n_items
(
self.interaction_mode,
self.interaction_num
) = self._check_interaction_mode(recent_num, random_num)
self.seed = seed
self.user_consumed = data_info.user_consumed
self.sparse = self._decide_sparse_indices(data_info)
self.dense = self._decide_dense_values(data_info)
if self.sparse:
self.sparse_feature_size = self._sparse_feat_size(data_info)
self.sparse_field_size = self._sparse_field_size(data_info)
if self.dense:
self.dense_field_size = self._dense_field_size(data_info)
self.user_last_interacted = None
self.last_interacted_len = None
self.all_args = locals()
self.user_variables = ["user_features"]
self.item_variables = ["item_features"]
def _build_model(self):
tf.set_random_seed(self.seed)
self.user_indices = tf.placeholder(tf.int32, shape=[None])
self.item_indices = tf.placeholder(tf.int32, shape=[None])
self.user_interacted_seq = tf.placeholder(
tf.int32, shape=[None, self.interaction_num])
self.user_interacted_len = tf.placeholder(tf.float32, shape=[None])
self.labels = tf.placeholder(tf.float32, shape=[None])
self.is_training = tf.placeholder_with_default(False, shape=[])
self.concat_embed = []
user_features = tf.get_variable(
name="user_features",
shape=[self.n_users + 1, self.embed_size],
initializer=tf_truncated_normal(0.0, 0.01),
regularizer=self.reg)
item_features = tf.get_variable(
name="item_features",
shape=[self.n_items + 1, self.embed_size],
initializer=tf_truncated_normal(0.0, 0.01),
regularizer=self.reg)
user_embed = tf.nn.embedding_lookup(user_features, self.user_indices)
item_embed = tf.nn.embedding_lookup(item_features, self.item_indices)
# unknown items are padded to 0-vector
zero_padding_op = tf.scatter_update(
item_features, self.n_items,
tf.zeros([self.embed_size], dtype=tf.float32)
)
with tf.control_dependencies([zero_padding_op]):
multi_item_embed = tf.nn.embedding_lookup(
item_features, self.user_interacted_seq) # B * seq * K
pooled_embed = tf.div_no_nan(
tf.reduce_sum(multi_item_embed, axis=1),
tf.expand_dims(tf.sqrt(self.user_interacted_len), axis=1))
self.concat_embed.extend([user_embed, item_embed, pooled_embed])
if self.sparse:
self._build_sparse()
if self.dense:
self._build_dense()
concat_embed = tf.concat(self.concat_embed, axis=1)
mlp_layer = dense_nn(concat_embed,
self.hidden_units,
use_bn=self.use_bn,
dropout_rate=self.dropout_rate,
is_training=self.is_training)
self.output = tf.reshape(
tf.layers.dense(inputs=mlp_layer, units=1), [-1])
def _build_sparse(self):
self.sparse_indices = tf.placeholder(
tf.int32, shape=[None, self.sparse_field_size])
sparse_features = tf.get_variable(
name="sparse_features",
shape=[self.sparse_feature_size, self.embed_size],
initializer=tf_truncated_normal(0.0, 0.01),
regularizer=self.reg)
sparse_embed = tf.nn.embedding_lookup(
sparse_features, self.sparse_indices)
sparse_embed = tf.reshape(
sparse_embed, [-1, self.sparse_field_size * self.embed_size])
self.concat_embed.append(sparse_embed)
def _build_dense(self):
self.dense_values = tf.placeholder(
tf.float32, shape=[None, self.dense_field_size])
dense_values_reshape = tf.reshape(
self.dense_values, [-1, self.dense_field_size, 1])
batch_size = tf.shape(self.dense_values)[0]
dense_features = tf.get_variable(
name="dense_features",
shape=[self.dense_field_size, self.embed_size],
initializer=tf_truncated_normal(0.0, 0.01),
regularizer=self.reg)
dense_embed = tf.tile(dense_features, [batch_size, 1])
dense_embed = tf.reshape(
dense_embed, [-1, self.dense_field_size, self.embed_size])
dense_embed = tf.multiply(dense_embed, dense_values_reshape)
dense_embed = tf.reshape(
dense_embed, [-1, self.dense_field_size * self.embed_size])
self.concat_embed.append(dense_embed)
def _build_train_ops(self, global_steps=None):
self.loss = tf.reduce_mean(
tf.nn.sigmoid_cross_entropy_with_logits(labels=self.labels,
logits=self.output)
)
if self.reg is not None:
reg_keys = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
total_loss = self.loss + tf.add_n(reg_keys)
else:
total_loss = self.loss
optimizer = tf.train.AdamOptimizer(self.lr)
optimizer_op = optimizer.minimize(total_loss, global_step=global_steps)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
self.training_op = tf.group([optimizer_op, update_ops])
self.sess.run(tf.global_variables_initializer())
def fit(self, train_data, verbose=1, shuffle=True,
eval_data=None, metrics=None, **kwargs):
assert self.task == "ranking", (
"YouTube models is only suitable for ranking")
self.show_start_time()
if self.lr_decay:
n_batches = int(len(train_data) / self.batch_size)
self.lr, global_steps = lr_decay_config(self.lr, n_batches,
**kwargs)
else:
global_steps = None
self._build_model()
self._build_train_ops(global_steps)
data_generator = DataGenSequence(train_data, self.data_info,
self.sparse, self.dense,
mode=self.interaction_mode,
num=self.interaction_num,
padding_idx=self.n_items)
for epoch in range(1, self.n_epochs + 1):
if self.lr_decay:
print(f"With lr_decay, epoch {epoch} learning rate: "
f"{self.sess.run(self.lr)}")
with time_block(f"Epoch {epoch}", verbose):
train_total_loss = []
for (u_seq, u_len, user, item, label, sparse_idx, dense_val
) in data_generator(shuffle, self.batch_size):
feed_dict = self._get_seq_feed_dict(
u_seq, u_len, user, item, label,
sparse_idx, dense_val, True)
train_loss, _ = self.sess.run(
[self.loss, self.training_op], feed_dict)
train_total_loss.append(train_loss)
if verbose > 1:
train_loss_str = "train_loss: " + str(
round(float(np.mean(train_total_loss)), 4)
)
print(f"\t {colorize(train_loss_str, 'green')}")
# for evaluation
self._set_last_interacted()
self.print_metrics(eval_data=eval_data, metrics=metrics,
**kwargs)
print("=" * 30)
# for prediction and recommendation
self._set_last_interacted()
def predict(self, user, item, inner_id=False):
user, item = self.convert_id(user, item, inner_id)
unknown_num, unknown_index, user, item = self._check_unknown(user, item)
(user_indices,
item_indices,
sparse_indices,
dense_values) = get_predict_indices_and_values(
self.data_info, user, item, self.n_items, self.sparse, self.dense)
feed_dict = self._get_seq_feed_dict(self.user_last_interacted[user],
self.last_interacted_len[user],
user_indices, item_indices,
None, sparse_indices,
dense_values, False)
preds = self.sess.run(self.output, feed_dict)
preds = 1 / (1 + np.exp(-preds))
if unknown_num > 0:
preds[unknown_index] = self.default_prediction
return preds[0] if len(user) == 1 else preds
def recommend_user(self, user, n_rec, inner_id=False, **kwargs):
if not inner_id:
user = self.data_info.user2id[user]
user = self._check_unknown_user(user)
if user is None: ####################
return # popular ?
(user_indices,
item_indices,
sparse_indices,
dense_values) = get_recommend_indices_and_values(
self.data_info, user, self.n_items, self.sparse, self.dense)
u_last_interacted = np.tile(self.user_last_interacted[user],
(self.n_items, 1))
u_interacted_len = np.repeat(self.last_interacted_len[user],
self.n_items)
feed_dict = self._get_seq_feed_dict(u_last_interacted, u_interacted_len,
user_indices, item_indices, None,
sparse_indices, dense_values, False)
recos = self.sess.run(self.output, feed_dict)
recos = 1 / (1 + np.exp(-recos))
consumed = set(self.user_consumed[user])
count = n_rec + len(consumed)
ids = np.argpartition(recos, -count)[-count:]
rank = sorted(zip(ids, recos[ids]), key=lambda x: -x[1])
recs_and_scores = islice(
(rec if inner_id else (self.data_info.id2item[rec[0]], rec[1])
for rec in rank if rec[0] not in consumed),
n_rec
)
return list(recs_and_scores)
def _set_last_interacted(self):
if (self.user_last_interacted is None
and self.last_interacted_len is None):
user_indices = np.arange(self.n_users)
(self.user_last_interacted,
self.last_interacted_len) = user_last_interacted(
user_indices, self.user_consumed, self.n_items,
self.interaction_num)
def save(self, path, model_name, manual=False):
if not os.path.isdir(path):
print(f"file folder {path} doesn't exists, creating a new one...")
os.makedirs(path)
self.save_params(path)
if manual:
self.save_variables(path, model_name)
else:
self.save_tf_model(path, model_name)
@classmethod
def load(cls, path, model_name, data_info, manual=False):
tf.reset_default_graph()
if manual:
return cls.load_variables(path, model_name, data_info)
else:
return cls.load_tf_model(path, model_name, data_info)
| [
"[email protected]"
] | |
f7584add9a4108166a191f7f63b755d5aec39a5a | a2ff77ac12c8c8313ebb9d82b0afe0229ac065c6 | /packages/desktop/gnome/addon/gitg/actions.py | a4af4b04586a3f92f2c96f7a1bee230ec0e17431 | [] | no_license | ademirel/COMAK | 80966cffc1833c0d41dbe36514ef2480f4b87ead | 311d8d572c0ed5fe429bb4b2748e509dab7a6785 | refs/heads/master | 2020-12-25T17:23:27.553490 | 2012-09-11T08:58:30 | 2012-09-11T08:58:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 675 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU General Public License, version 2.
# See the file http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
from pisi.actionsapi import autotools
from pisi.actionsapi import pisitools
from pisi.actionsapi import shelltools
from pisi.actionsapi import get
def setup():
autotools.autoreconf("-fiv")
shelltools.system("intltoolize --force --copy --automake")
autotools.configure("--disable-static")
def build():
autotools.make()
def install():
autotools.rawInstall("DESTDIR=%s" % get.installDIR())
#autotools.install()
pisitools.dodoc("COPYING", "README", "AUTHORS", "ChangeLog")
| [
"[email protected]"
] | |
d77c2989f52c9c5aa6a273abb52368e4bac985f3 | 2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02 | /PyTorch/contrib/cv/detection/FSAF_for_Pytorch/mmdetection/configs/faster_rcnn/faster_rcnn_r50_caffe_c4_1x_coco.py | c686bcec7c76d3324cacaf69abb51bd7dc5b59f5 | [
"GPL-1.0-or-later",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Ascend/ModelZoo-PyTorch | 4c89414b9e2582cef9926d4670108a090c839d2d | 92acc188d3a0f634de58463b6676e70df83ef808 | refs/heads/master | 2023-07-19T12:40:00.512853 | 2023-07-17T02:48:18 | 2023-07-17T02:48:18 | 483,502,469 | 23 | 6 | Apache-2.0 | 2022-10-15T09:29:12 | 2022-04-20T04:11:18 | Python | UTF-8 | Python | false | false | 1,981 | py | # Copyright 2021 Huawei Technologies Co., Ltd
#
# 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.
#
_base_ = [
'../_base_/models/faster_rcnn_r50_caffe_c4.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
# use caffe img_norm
img_norm_cfg = dict(
mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(1333, 800),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
data = dict(
train=dict(pipeline=train_pipeline),
val=dict(pipeline=test_pipeline),
test=dict(pipeline=test_pipeline))
# optimizer
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
| [
"[email protected]"
] | |
0f99ffc01cdb6537622d04736cfb2054589fd8e2 | 306baa2ad596e3962e427d587e7b0d4175a1e48e | /configs/eftnet/R2_ttf53_whh_beta01_1lr_log_2x.py | 74a897aa9dbdab0f29a9de33d0dedb6950f47d88 | [
"Apache-2.0"
] | permissive | mrsempress/mmdetection | 9c7ed7ed0c9f1d6200f79a2ab14fc0c8fe32c18a | cb650560c97a2fe56a9b369a1abc8ec17e06583a | refs/heads/master | 2022-04-24T04:34:30.959082 | 2020-04-26T07:52:23 | 2020-04-26T07:52:23 | 258,957,856 | 0 | 0 | Apache-2.0 | 2020-04-26T06:33:32 | 2020-04-26T06:33:32 | null | UTF-8 | Python | false | false | 3,060 | py | # model settings
model = dict(
type='CenterNet',
pretrained='./pretrain/darknet53.pth',
backbone=dict(
type='DarknetV3',
layers=[1, 2, 8, 8, 4],
inplanes=[3, 32, 64, 128, 256, 512],
planes=[32, 64, 128, 256, 512, 1024],
norm_cfg=dict(type='BN'),
out_indices=(1, 2, 3, 4),
frozen_stages=1,
norm_eval=False),
neck=dict(type='None'),
bbox_head=dict(
type='CXTHead',
inplanes=(128, 256, 512, 1024),
head_conv=128,
wh_conv=64,
use_deconv=False,
norm_after_upsample=False,
hm_head_conv_num=2,
wh_head_conv_num=2,
ct_head_conv_num=1,
fovea_hm=False,
num_classes=81,
use_exp_wh=False,
wh_offset_base=16,
wh_agnostic=True,
wh_heatmap=True,
shortcut_cfg=(1, 2, 3),
shortcut_attention=(False, False, False),
norm_cfg=dict(type='BN'),
norm_wh=False,
hm_center_ratio=0.27,
center_ratio=0.1,
hm_init_value=None,
giou_weight=5.,
merge_weight=1.,
hm_weight=1.,
ct_weight=1.))
cudnn_benchmark = True
# training and testing settings
train_cfg = dict(
vis_every_n_iters=100,
debug=False)
test_cfg = dict(
score_thr=0.01,
max_per_img=100)
# dataset settings
dataset_type = 'CocoDataset'
data_root = 'data/coco/'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
data = dict(
imgs_per_gpu=12,
workers_per_gpu=4,
train=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_train2017.json',
img_prefix=data_root + 'train2017/',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_val2017.json',
img_prefix=data_root + 'val2017/',
pipeline=test_pipeline),
test=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_val2017.json',
img_prefix=data_root + 'val2017/',
pipeline=test_pipeline))
# optimizer
optimizer = dict(type='SGD', lr=0.001, momentum=0.9, weight_decay=0.0004,
paramwise_options=dict(bias_lr_mult=2., bias_decay_mult=0.))
optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=500,
warmup_ratio=1.0 / 5,
step=[18, 22])
checkpoint_config = dict(save_every_n_steps=200, max_to_keep=1, keep_every_n_epochs=18)
bbox_head_hist_config = dict(
model_type=['ConvModule', 'DeformConvPack'],
sub_modules=['bbox_head'],
save_every_n_steps=200)
# yapf:disable
log_config = dict(interval=20)
# yapf:enable
# runtime settings
total_epochs = 24
dist_params = dict(backend='nccl')
log_level = 'INFO'
work_dir = 'ttf53_whh_beta01_1lr_log_2x'
load_from = None
resume_from = 'work_dirs/1908/0813_R2_ttf53_WHH_BETA01_1LR/ttf53_whh_beta01_1lr_log_1x_0813_2257/epoch_9.pth'
workflow = [('train', 1)]
| [
"[email protected]"
] | |
dfc80722741ebb1da00c6319fc894fde464117fc | 1625128b5452d1894847caa9b5266a535b6247c6 | /tests/signin_amazon.py | 3de30299e29f75a20884fd230ca1bed1483de424 | [] | no_license | garou93/inspiration-mission-haithem-CI-CD-python-shell | bb84e99cc3967728b2a06eadb0761800ead04881 | d45ee7609dcf90dea0751a2bfa3ce51130983567 | refs/heads/master | 2023-07-24T22:12:28.496584 | 2021-09-05T08:06:50 | 2021-09-05T08:06:50 | 378,758,122 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16,272 | py | # -*- coding: utf-8 -*-
"""
Title:
Description:
Author: haithem ben abdelaziz
Date:
Version:
Environment:
"""
import sc_stbt
import stbts
import stbt
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import ui
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import os
project = os.environ.get('STBT_PROJECT')
amazon_path_template = sc_stbt.get_generic_template_path() + "/../../../trunk/tests/templates/templates_amazon/"
any_frame = amazon_path_template + "/sign_in/any_frame/any_frame.png"
amazon_path_template_is_menu = "/../../../trunk/tests/templates/templates_amazon/"
menu = sc_stbt.menu()
amazon_keyboard = sc_stbt.amazon_keyboard()
def is_amazon_signin():
"""
is_amazon_signin:: check if the sign in page is displayed
:return:
"""
if stbts.match_text("prime video",
region=stbt.Region(x=47, y=39, width=190, height=38),
timeout_secs=30).match:
sc_stbt.debug("AMAZON APP IS DISPLAYED")
return True
else :
sc_stbt.debug("AMAZON APP IS NOT DISPLAYED")
return False
def sign_in_amazon(callable=None):
"""
this function is used to sign in amazon
:return:
"""
login = stbt.get_config("amazon", "login")
password = stbt.get_config("amazon", "password")
if is_amazon_signin():
sc_stbt.press('KEY_OK')
sc_stbt.wait(5)
if stbts.match_any_text(text=['Sign', 'Connectez', 'Identificate'],
region=stbt.Region(x=32, y=41, width=116, height=32)).match:
sc_stbt.debug("MENU SIGNIN IS DISPLAYED")
if stbts.match_text(text="Search",region=stbt.Region(x=44, y=36, width=58, height=20)).match:
sc_stbt.debug("AMAZON ALREADY SIGNIN")
else:
if not menu.is_menu_template(perf=False,
region_frame=stbt.Region(x=644, y=163, width=40, height=47),
path=amazon_path_template + "sign_in/cursor/",
timeout=3):
list = ["KEY_UP", "KEY_UP", "KEY_UP", "KEY_OK"]
sc_stbt.combo_press(list)
else:
sc_stbt.press("KEY_OK")
check_keyboard()
# enter login
sc_stbt.wait(3)
amazon_keyboard.enter_text(login)
if menu.is_menu_template(perf=False,
region_frame=stbt.Region(x=644, y=232, width=40, height=47),
path=amazon_path_template + "sign_in/cursor/",
timeout=3):
if stbts.match_text(login,
region=stbt.Region(x=298, y=176, width=350, height=22),
threshold=0.8,
timeout_secs=5).match:
sc_stbt.press("KEY_OK")
check_keyboard()
sc_stbt.wait(3)
else:
sc_stbt.debug("verify your email")
amazon_keyboard.enter_text(password)
sc_stbt.wait(2)
if menu.is_menu_template(perf=False,
region_frame=stbt.Region(x=286, y=272, width=392, height=31),
path=amazon_path_template + "sign_in/cursor",
timeout=3):
sc_stbt.press("KEY_OK")
sc_stbt.wait(10)
if stbts.match_text("Success!",
region=stbt.Region(x=252, y=179, width=450, height=88),
threshold=0.9,
timeout_secs=5).match:
sc_stbt.debug("Success! Your device is registred")
if sc_stbt.is_amazon(press="KEY_OK"):
sc_stbt.debug("login succeeded")
else:
sc_stbt.debug("verify your password")
else :
if sc_stbt.is_amazon(press="KEY_BACK"):
sc_stbt.debug("login succeeded")
else:
sc_stbt.debug("verify your password")
def check_keyboard():
"""
this function is used to identify the keyboard (email keyboard or password keyboard)
:return:
"""
if menu.is_menu_template(perf=False,
region_frame=stbt.Region(x=265, y=232, width=29, height=30),
path=amazon_path_template + "sign_in/keyboard/",
timeout=10):
sc_stbt.debug("keyboard is displayed")
elif menu.is_menu_template(perf=False,
region_frame =stbt.Region(x=659, y=173, width=9, height=26),
path=amazon_path_template + "sign_in/cursor/",
timeout=10):
sc_stbt.press("KEY_OK")
sc_stbt.debug("keyboard is displayed")
else:
assert False, "Keyboard is not Displayed"
def write_text(text, callable):
"""
write_text: this function is used to write text in input by keyboard
:param text:
:return:
"""
special = 0
for i in range(len(text)):
if i == 0:
if (text[i]).isupper():
goto_cord('*',callable)
if not ((text[i]).isalpha() or (text[i]).isalnum()):
special = 1
goto_cord('&')
goto_cord(text[i].lower(), callable)
if i != 0:
if not ((text[i]).isalpha() or (text[i]).isalnum()):
special = 1
goto_cord(text[i].lower(),callable)
if i < len(text) - 1:
if special == 1:
if (text[i + 1]).isalpha() or (text[i + 1]).isalnum():
special = 0
goto_cord('*')
if (text[i + 1]).isupper():
goto_cord('*')
if (text[i]).isalnum():
if (text[i + 1]).isupper():
goto_cord('*')
if (text[i]).isupper() and ((text[i + 1]).islower() or (text[i + 1]).isalnum()):
goto_cord('*')
if not ((text[i + 1]).isalpha() or (text[i + 1]).isalnum()):
goto_cord('&')
def goto_cord(char, callable = None):
"""
:param char:
:return:
"""
target = matrix_amazon[char]
if callable is not None :
final_dict = callable()
target = final_dict[char]
target_x = target[0]
target_y = target[1]
source = stbt.match(any_frame).position
source_x = source.x
source_y = source.y
global tolerance
tolerance = 18
start_time = time.time()
while time.time() - start_time < 300:
if source_x in range((target_x - tolerance), (target_x + tolerance)) and source_y in range(
(target_y - tolerance), (target_y + tolerance)):
sc_stbt.press("KEY_OK")
sc_stbt.wait(1)
return True
else:
sc_stbt.press(_next_key(source_x, source_y, target_x, target_y, tolerance))
sc_stbt.wait(1)
source = stbt.match(any_frame).position
source_x = source.x
source_y = source.y
def _next_key(source_x, source_y, target_x, target_y, tolerance):
if (source_y < target_y - tolerance):
return "KEY_DOWN"
if (source_y - tolerance > target_y):
return "KEY_UP"
if (source_x < target_x - tolerance):
return "KEY_RIGHT"
if (source_x - tolerance > target_x):
return "KEY_LEFT"
########################################"SIGN IN WITH AMAZON WEBSITE ####################################
def open_amazon_website():
"""
OPEn the amazon website (www.amazon.com)
:return:
"""
fp = webdriver.FirefoxProfile()
fp.set_preference('network.proxy.type', 2)
fp.set_preference("network.proxy.autoconfig_url", "http://pac.comon/scomproxy.pac")
global browser
browser = webdriver.Firefox(firefox_profile=fp,
executable_path=sc_stbt.get_generic_template_path() + "/../../../trunk/scripts/geckodriver")
# maximize window
browser.maximize_window()
# open web page with a url
browser.get("https://www.amazon.com/ap/signin?_encoding=UTF8&ignoreAuthState=1&openid.assoc_handle=usflex&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.ns.pape=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Fpape%2F1.0&openid.pape.max_auth_age=0&openid.return_to=https%3A%2F%2Fwww.amazon.com%2F%3Fref_%3Dnav_custrec_signin&switch_account=")
browser.save_screenshot('screenshot_web.png')
try:
ui.WebDriverWait(browser, 20).until(EC.title_is("Amazon Sign-In"))
browser.save_screenshot('screenshot_web.png')
sc_stbt.debug("Sign In Window is Displayed")
except:
browser.save_screenshot('screenshot_web.png')
browser.quit()
assert False, "Sign In Window is not Displayed"
def sign_in_website():
"""
sign_in_amazon_website :: get the username and the password from the config file and registre in the amazon website
:return:
"""
username= stbt.get_config("amazon","login")
password= stbt.get_config("amazon","password")
browser.save_screenshot('screenshot_web.png')
browser.find_element_by_name("email").send_keys(username)
inputElement = browser.find_element_by_css_selector('.a-button-input')
inputElement.click()
browser.save_screenshot('screenshot_web.png')
browser.find_element_by_name("password").send_keys(password)
ui.WebDriverWait(browser, 20).until(
EC.element_to_be_clickable((By.CSS_SELECTOR,"#signInSubmit"))).click()
browser.save_screenshot('screenshot_web.png')
try:
ui.WebDriverWait(browser, 20).until(EC.title_is("Amazon.com: Online Shopping for Electronics, Apparel, Computers, Books, DVDs & more"))
browser.save_screenshot('screenshot_web.png')
sc_stbt.debug("LOGIN successful")
except:
browser.save_screenshot('screenshot_web.png')
browser.quit()
assert False, "LOGIN Failed"
def register_device_window():
"""
go_to_your_prime_video :: API that Take u from the Amazon website to Ur Prime VIdeo Account after Sign in
:return:
"""
browser.get("https://www.amazon.com/gp/video/ontv/code/ref=atv_set_rd_reg")
browser.save_screenshot('screenshot_web.png')
try:
ui.WebDriverWait(browser, 20).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "#av-cbl-code")))
browser.save_screenshot('screenshot_web.png')
sc_stbt.debug("Register STB by code")
except:
browser.save_screenshot('screenshot_web.png')
assert False, "menu register with code is not displayed "
def generate_signin_code(lang="fra"):
"""
signin_stb_with_website : Api that select the website signin methode in STB menu
:param lang:
:return:
"""
if is_amazon_signin():
menu.is_menu(press=["KEY_DOWN"],
path= amazon_path_template_is_menu + "/Settings/register_on_the_amazon_website/",
region_frame=stbt.Region(x=59, y=400, width=299, height=45),
timeout=4,
timeout_is_menu=8)
if lang =="eng":
menu.is_menu(press=["KEY_OK"],
text="Register Your Device",
region_text=stbt.Region(x=33, y=37, width=201, height=40),
timeout=4,
timeout_is_menu=8)
sc_stbt.debug("MENU SIGNIN IS DISPLAYED")
elif lang =="fra":
menu.is_menu(press=["KEY_OK"],
text="Enregistrez votre appareil",
region_text=stbt.Region(x=33, y=37, width=254, height=40),
timeout=4,
timeout_is_menu=8)
sc_stbt.debug("MENU enregistement est affiche")
else:
assert False , ("lang selected is not supported")
sc_stbt.wait(5)
else:
assert False, ("MENU SIGNIN NOT DISPLAYED")
def get_code_stb_to_website():
"""
get_code_stb_to_website :: API that grep the code from Stb and set it in the amazon website than it press on signin button to confirm registration
:return:
"""
code = sc_stbt.get_signin_code()
element = browser.find_element_by_css_selector("#av-cbl-code")
element.send_keys(code)
browser.save_screenshot('screenshot_web.png')
ui.WebDriverWait(browser,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"._2V-I1s"))).click()
browser.save_screenshot('screenshot_web.png')
signin = False
while not signin :
try :
ui.WebDriverWait(browser,20).until(EC.presence_of_element_located((By.CSS_SELECTOR,"._2yAJYN > span:nth-child(2)")))
browser.save_screenshot('screenshot_web.png')
sc_stbt.debug("That's an invalid code")
sc_stbt.get_new_signin_code()
code1 = sc_stbt.get_signin_code()
open_amazon_website()
sign_in_website()
register_device_window()
browser.save_screenshot('screenshot_web.png')
browser.find_element_by_css_selector("#av-cbl-code").send_keys(code1)
browser.save_screenshot('screenshot_web.png')
sc_stbt.wait(2)
ui.WebDriverWait(browser,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"._2V-I1s"))).click()
browser.save_screenshot('screenshot_web.png')
signin = False
except:
sc_stbt.debug("Success! Your device is registered to your Prime Video account")
if stbts.match_text(text="Success!",
region=stbt.Region(x=318, y=155, width=85, height=36),
threshold=0.8,
timeout_secs=5).match:
sc_stbt.press("KEY_OK")
sc_stbt.is_amazon()
else :
assert False, "Problem Occurred"
signin = True
def close_interface():
"""
close_interface :: quit the web interface
:return:
"""
browser.quit()
def signin_by_web():
generate_signin_code(lang="fra")
open_amazon_website()
sign_in_website()
register_device_window()
get_code_stb_to_website()
close_interface()
matrix_amazon = {}
#1234567890
matrix_amazon["1"] = [264, 231]
matrix_amazon["2"] = [300, 231]
matrix_amazon["3"] = [336, 231]
matrix_amazon["4"] = [372, 231]
matrix_amazon["5"] = [408, 231]
matrix_amazon["6"] = [444, 231]
matrix_amazon["7"] = [480, 231]
matrix_amazon["8"] = [516, 231]
matrix_amazon["9"] = [552, 231]
matrix_amazon["0"] = [588, 231]
#qwertyuiop
matrix_amazon["q"] = [264, 267]
matrix_amazon["w"] = [300, 267]
matrix_amazon["e"] = [336, 267]
matrix_amazon["r"] = [372, 267]
matrix_amazon["t"] = [408, 267]
matrix_amazon["y"] = [444, 267]
matrix_amazon["u"] = [480, 267]
matrix_amazon["i"] = [516, 267]
matrix_amazon["o"] = [552, 267]
matrix_amazon["p"] = [588, 267]
#asdfghjkl
matrix_amazon["a"] = [264, 303]
matrix_amazon["s"] = [300, 303]
matrix_amazon["d"] = [336, 303]
matrix_amazon["f"] = [372, 303]
matrix_amazon["g"] = [408, 303]
matrix_amazon["h"] = [444, 303]
matrix_amazon["j"] = [480, 303]
matrix_amazon["k"] = [516, 303]
matrix_amazon["l"] = [552, 303]
#zxcvbnm
matrix_amazon["z"] = [264, 339]
matrix_amazon["x"] = [300, 339]
matrix_amazon["c"] = [336, 339]
matrix_amazon["v"] = [372, 339]
matrix_amazon["b"] = [408, 339]
matrix_amazon["n"] = [444, 339]
matrix_amazon["m"] = [480, 339]
# ABC
matrix_amazon["*"] = [624, 267]
# space
matrix_amazon["#"] = [336, 375]
# Entrer
matrix_amazon["/"] = [624, 375]
# char special
matrix_amazon["&"] = [624, 339]
# -$$=_.@+
matrix_amazon["-"] = [408, 267]
matrix_amazon["$"] = [372, 231]
matrix_amazon["="] = [552, 267]
matrix_amazon["_"] = [480, 303]
matrix_amazon["."] = [444, 267]
matrix_amazon["@"] = [300, 303]
matrix_amazon["+"] = [588, 231]
| [
"[email protected]"
] | |
c5fbfda6f64d0654fdb0f07855f20d2db1e8bb6a | a86287b997aceb02b836a951a188fff5c98cdca8 | /train_cnn_multilabel/ckpt_pb.py | 06334157fbd692e76b7ced2ca00fbe72a9410251 | [] | no_license | wonqiao/train_arch | fbdd9ee59ed67ad2a71e638fbcdaadafedc68759 | f78aabffdfb65dd1d40ede40dde81de3b04f2144 | refs/heads/master | 2023-01-29T20:21:24.977626 | 2020-12-09T03:54:00 | 2020-12-09T03:54:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,402 | py | # coding = utf-8
"""
Created on 2017 10.17
@author: liupeng
wechat: lp9628
blog: http://blog.csdn.net/u014365862/article/details/78422372
"""
import tensorflow as tf
from tensorflow.python.framework import graph_util
from lib.utils.multi_label_utils import get_next_batch_from_path, shuffle_train_data
from lib.utils.multi_label_utils import input_placeholder, build_net_multi_label, cost, train_op, model_mAP
import cv2
import numpy as np
import os
import sys
import config
MODEL_DIR = "model/"
MODEL_NAME = "frozen_model.pb"
if not tf.gfile.Exists(MODEL_DIR): #创建目录
tf.gfile.MakeDirs(MODEL_DIR)
height, width = config.height, config.width
num_classes = config.num_classes
arch_model = config.arch_model
X = tf.placeholder(tf.float32, [None, height, width, 3], name = "inputs_placeholder")
net, net_vis = build_net_multi_label(X, num_classes, 1.0, False, arch_model)
net = tf.nn.sigmoid(net)
predict = tf.reshape(net, [-1, num_classes], name='predictions')
def freeze_graph(model_folder):
#checkpoint = tf.train.get_checkpoint_state(model_folder) #检查目录下ckpt文件状态是否可用
#input_checkpoint = checkpoint.model_checkpoint_path #得ckpt文件路径
input_checkpoint = model_folder
output_graph = os.path.join(MODEL_DIR, MODEL_NAME) #PB模型保存路径
output_node_names = "predictions" #原模型输出操作节点的名字
#saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=True) #得到图、clear_devices :Whether or not to clear the device field for an `Operation` or `Tensor` during import.
saver = tf.train.Saver()
graph = tf.get_default_graph() #获得默认的图
input_graph_def = graph.as_graph_def() #返回一个序列化的图代表当前的图
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
saver.restore(sess, input_checkpoint) #恢复图并得到数据
#print "predictions : ", sess.run("predictions:0", feed_dict={"input_holder:0": [10.0]}) # 测试读出来的模型是否正确,注意这里传入的是输出 和输入 节点的 tensor的名字,不是操作节点的名字
output_graph_def = graph_util.convert_variables_to_constants( #模型持久化,将变量值固定
sess,
input_graph_def,
output_node_names.split(",") #如果有多个输出节点,以逗号隔开
)
with tf.gfile.GFile(output_graph, "wb") as f: #保存模型
f.write(output_graph_def.SerializeToString()) #序列化输出
print("%d ops in the final graph." % len(output_graph_def.node)) #得到当前图有几个操作节点
for op in graph.get_operations():
#print(op.name, op.values())
print("name:",op.name)
print ("success!")
#下面是用于测试, 读取pd模型,答应每个变量的名字。
graph = load_graph("model/frozen_model.pb")
for op in graph.get_operations():
#print(op.name, op.values())
print("name111111111111:",op.name)
pred = graph.get_tensor_by_name('prefix/inputs_placeholder:0')
print (pred)
temp = graph.get_tensor_by_name('prefix/predictions:0')
print (temp)
def load_graph(frozen_graph_filename):
# We load the protobuf file from the disk and parse it to retrieve the
# unserialized graph_def
with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
# Then, we can use again a convenient built-in function to import a graph_def into the
# current default Graph
with tf.Graph().as_default() as graph:
tf.import_graph_def(
graph_def,
input_map=None,
return_elements=None,
name="prefix",
op_dict=None,
producer_op_list=None
)
return graph
if __name__ == '__main__':
train_dir = 'model'
latest = tf.train.latest_checkpoint(train_dir)
if not latest:
print ("No checkpoint to continue from in", train_dir)
sys.exit(1)
print ("resume", latest)
# saver2.restore(sess, latest)
# model_folder = './model/model.ckpt-0'
model_folder = latest
freeze_graph(model_folder)
| [
"[email protected]"
] | |
1545b59188024f52bdd1c764d1b8ef97983fa250 | 3365e4d4fc67bbefe4e8c755af289c535437c6f4 | /.history/src/core/dialogs/waterfall_dialog_20170814145942.py | 6513d4211f297e41a9975f46c661f2308b482d5c | [] | no_license | kiranhegde/OncoPlotter | f3ab9cdf193e87c7be78b16501ad295ac8f7d2f1 | b79ac6aa9c6c2ca8173bc8992ba3230aa3880636 | refs/heads/master | 2021-05-21T16:23:45.087035 | 2017-09-07T01:13:16 | 2017-09-07T01:13:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,976 | py | '''
Refs:
Embedding plot: https://sukhbinder.wordpress.com/2013/12/16/simple-pyqt-and-matplotlib-example-with-zoompan/
'''
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
from PyQt5.QtWidgets import (QApplication, QDialog, QWidget, QPushButton, QVBoxLayout, QTreeWidget, QTreeWidgetItem)
from PyQt5 import QtCore, QtGui
import core.gui.waterfall as waterfall
import numpy as np
from pprint import pprint
class Waterfall(QWidget, waterfall.Ui_Waterfall):
general_settings_signal = QtCore.pyqtSignal(list) #send list of plotting params
updated_rectangles_signal = QtCore.pyqtSignal(list) #send list of updated artists for redrawing
def __init__(self, parent):
super(Waterfall,self).__init__(parent)
self.setupUi(self)
#Button functions
self.btn_apply_general_settings.clicked.connect(self.send_settings)
self.patient_tree = self.create_patient_tree()
self.data_viewer_container.addWidget(self.patient_tree)
def on_waterfall_data_signal(self,signal):
self.waterfall_data = signal['waterfall_data'] #pandas dataframe
def on_generated_rectangles_signal(self,signal):
self.rectangles_received = signal[0]
self.add_items() #display in table
#print(self.rectangles_received)
def send_settings(self,signal):
self.list_general_settings = [
self.plot_title.text(),
self.x_label.text(),
self.y_label.text(),
self.twenty_percent_line.isChecked(),
self.thirty_percent_line.isChecked(),
self.zero_percent_line.isChecked(),
self.display_responses_as_text.isChecked()
]
self.general_settings_signal.emit(self.list_general_settings)
def create_patient_tree(self):
'''
Create QTreeWidget populated with a patient's data for the DataEntry dialog.
Assumes that self.temp_patient is the patient of interest and that the variable belongs to the dialog.
'''
self.tree = QTreeWidget()
self.root = self.tree.invisibleRootItem()
self.headers = [
'Patient #',
'Best response %',
'Overall response',
'Cancer type',
'Color coding key',
'Color'
]
self.headers_item = QTreeWidgetItem(self.headers)
self.tree.setColumnCount(len(self.headers))
self.tree.setHeaderItem(self.headers_item)
self.root.setExpanded(True)
#self.addItems()
#self.tree.header().setResizeMode(QtGui.QHeaderView.ResizeToContents)
#self.tree.header().setStretchLastSection(False)
return self.tree
def add_items(self):
'''
Populate viewing tree
'''
i=0
for rect in self.rectangles_received:
#populate editable tree with rect data
self.rect_item = QTreeWidgetItem(self.root)
self.rect_params = [
self.waterfall_data['Patient number'][i],
rect.get_height(),
self.waterfall_data['Overall response'][i],
self.waterfall_data['Cancer'][i]
]
for col in range(0,4):
self.rect_item.setText(col,str(self.rect_params[col]))
self.rect_item.setTextAlignment(col,4)
self.rect_item.setFlags(self.rect_item.flags() | QtCore.Qt.ItemIsEditable)
i+=1
class WaterfallPlotter(QWidget):
generated_rectangles_signal = QtCore.pyqtSignal(list) #send list of rects for data display in tree
def __init__(self,parent):
super(WaterfallPlotter,self).__init__(parent)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas,self)
self.btn_plot = QPushButton('Default Plot')
self.btn_plot.clicked.connect(self.default_plot)
self.layout = QVBoxLayout()
self.layout.addWidget(self.toolbar)
self.layout.addWidget(self.canvas)
self.layout.addWidget(self.btn_plot)
self.setLayout(self.layout)
def on_waterfall_data_signal(self,signal):
self.waterfall_data = signal['waterfall_data'] #pandas dataframe
self.btn_plot.setEnabled(True)
def on_general_settings_signal(self,signal):
try:
hasattr(self,'ax')
self.ax.set_title(signal[0])
self.ax.set_xlabel(signal[1])
self.ax.set_ylabel(signal[2])
self.canvas.draw()
except Exception as e:
print(e)
def default_plot(self):
'''
Plot waterfall data
'''
self.figure.clear()
self.rect_locations = np.arange(len(self.waterfall_data['Best response percent change']))
self.ax = self.figure.add_subplot(111)
self.ax.axhline(y=20, linestyle='--', c='k', alpha=0.5, lw=2.0, label='twenty_percent')
self.ax.axhline(y=-30, linestyle='--', c='k', alpha=0.5, lw=2.0, label='thirty_percent')
self.ax.axhline(y=0, c='k', alpha=1, lw=2.0, label='zero_percent')
self.ax.grid(color = 'k', axis = 'y', alpha=0.25)
self.rects = self.ax.bar(self.rect_locations,self.waterfall_data['Best response percent change'])
self.auto_label_responses(self.ax, self.rects, self.waterfall_data)
#self.plot_table()
self.canvas.draw()
self.ax.hold(False) #rewrite the plot when plot() called
self.generated_rectangles_signal.emit([self.rects])
def plot_table(self):
rows = ['%s' % x for x in self.waterfall_data.keys()]
rows = rows[4:] #skip first three, they are the 4 standard headers, rest are table rows
columns = self.waterfall_data['Patient number'] #patient numbers
cell_text = []
for row in rows:
cell_text_temp = []
for col in range(len(columns)):
cell_text_temp.append(self.waterfall_data[row][col])
cell_text.append(cell_text_temp)
the_table = plt.table(cellText=cell_text, rowLabels=rows, colLabels=columns, loc='bottom', cellLoc='center')
plt.subplots_adjust(bottom=0.15,left=0.5)
self.ax.set_xlim(-0.5,len(columns)-0.5)
plt.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom='off', # ticks along the bottom edge are off
top='off', # ticks along the top edge are off
labelbottom='off'
) # labels along the bottom edge are off
def update_plot(self):
'''
TODO
'''
pass
def auto_label_responses(self, ax, rects, waterfall_data):
'''Add labels above/below bars'''
i = 0
for rect in rects:
height = rect.get_height()
if height >= 0:
valign = 'bottom'
else:
valign = 'top'
ax.text(rect.get_x() + rect.get_width()/2., height,
'%s' % waterfall_data['Overall response'][i], ha='center', va=valign)
i+=1
| [
"[email protected]"
] | |
b125adb354a67fab41cbad0382a1d9a0b1ebf676 | 2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02 | /PyTorch/contrib/audio/tdnn/templates/speaker_id/train.py | 7045f05974af4d3db27f4b724fd12f685a1eff52 | [
"GPL-1.0-or-later",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Ascend/ModelZoo-PyTorch | 4c89414b9e2582cef9926d4670108a090c839d2d | 92acc188d3a0f634de58463b6676e70df83ef808 | refs/heads/master | 2023-07-19T12:40:00.512853 | 2023-07-17T02:48:18 | 2023-07-17T02:48:18 | 483,502,469 | 23 | 6 | Apache-2.0 | 2022-10-15T09:29:12 | 2022-04-20T04:11:18 | Python | UTF-8 | Python | false | false | 13,107 | py | # Copyright 2021 Huawei Technologies Co., Ltd
#
# 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.
#
#!/usr/bin/env python3
"""Recipe for training a speaker-id system. The template can use used as a
basic example for any signal classification task such as language_id,
emotion recognition, command classification, etc. The proposed task classifies
28 speakers using Mini Librispeech. This task is very easy. In a real
scenario, you need to use datasets with a larger number of speakers such as
the voxceleb one (see recipes/VoxCeleb). Speechbrain has already some built-in
models for signal classifications (see the ECAPA one in
speechbrain.lobes.models.ECAPA_TDNN.py or the xvector in
speechbrain/lobes/models/Xvector.py)
To run this recipe, do the following:
> python train.py train.yaml
To read the code, first scroll to the bottom to see the "main" code.
This gives a high-level overview of what is going on, while the
Brain class definition provides the details of what happens
for each batch during training.
The first time you run it, this script should automatically download
and prepare the Mini Librispeech dataset for computation. Noise and
reverberation are automatically added to each sample from OpenRIR.
Authors
* Mirco Ravanelli 2021
"""
import os
import sys
import torch
import speechbrain as sb
from hyperpyyaml import load_hyperpyyaml
from mini_librispeech_prepare import prepare_mini_librispeech
import torch_npu
from torch_npu.contrib import transfer_to_npu
# Brain class for speech enhancement training
class SpkIdBrain(sb.Brain):
"""Class that manages the training loop. See speechbrain.core.Brain."""
def compute_forward(self, batch, stage):
"""Runs all the computation of that transforms the input into the
output probabilities over the N classes.
Arguments
---------
batch : PaddedBatch
This batch object contains all the relevant tensors for computation.
stage : sb.Stage
One of sb.Stage.TRAIN, sb.Stage.VALID, or sb.Stage.TEST.
Returns
-------
predictions : Tensor
Tensor that contains the posterior probabilities over the N classes.
"""
# We first move the batch to the appropriate device.
batch = batch.to(self.device)
# Compute features, embeddings, and predictions
feats, lens = self.prepare_features(batch.sig, stage)
embeddings = self.modules.embedding_model(feats, lens)
predictions = self.modules.classifier(embeddings)
return predictions
def prepare_features(self, wavs, stage):
"""Prepare the features for computation, including augmentation.
Arguments
---------
wavs : tuple
Input signals (tensor) and their relative lengths (tensor).
stage : sb.Stage
The current stage of training.
"""
wavs, lens = wavs
# Add augmentation if specified. In this version of augmentation, we
# concatenate the original and the augment batches in a single bigger
# batch. This is more memory-demanding, but helps to improve the
# performance. Change it if you run OOM.
if stage == sb.Stage.TRAIN:
if hasattr(self.modules, "env_corrupt"):
wavs_noise = self.modules.env_corrupt(wavs, lens)
wavs = torch.cat([wavs, wavs_noise], dim=0)
lens = torch.cat([lens, lens])
if hasattr(self.hparams, "augmentation"):
wavs = self.hparams.augmentation(wavs, lens)
# Feature extraction and normalization
feats = self.modules.compute_features(wavs)
feats = self.modules.mean_var_norm(feats, lens)
return feats, lens
def compute_objectives(self, predictions, batch, stage):
"""Computes the loss given the predicted and targeted outputs.
Arguments
---------
predictions : tensor
The output tensor from `compute_forward`.
batch : PaddedBatch
This batch object contains all the relevant tensors for computation.
stage : sb.Stage
One of sb.Stage.TRAIN, sb.Stage.VALID, or sb.Stage.TEST.
Returns
-------
loss : torch.Tensor
A one-element tensor used for backpropagating the gradient.
"""
_, lens = batch.sig
spkid, _ = batch.spk_id_encoded
# Concatenate labels (due to data augmentation)
if stage == sb.Stage.TRAIN and hasattr(self.modules, "env_corrupt"):
spkid = torch.cat([spkid, spkid], dim=0)
lens = torch.cat([lens, lens])
# Compute the cost function
loss = sb.nnet.losses.nll_loss(predictions, spkid, lens)
# Append this batch of losses to the loss metric for easy
self.loss_metric.append(
batch.id, predictions, spkid, lens, reduction="batch"
)
# Compute classification error at test time
if stage != sb.Stage.TRAIN:
self.error_metrics.append(batch.id, predictions, spkid, lens)
return loss
def on_stage_start(self, stage, epoch=None):
"""Gets called at the beginning of each epoch.
Arguments
---------
stage : sb.Stage
One of sb.Stage.TRAIN, sb.Stage.VALID, or sb.Stage.TEST.
epoch : int
The currently-starting epoch. This is passed
`None` during the test stage.
"""
# Set up statistics trackers for this stage
self.loss_metric = sb.utils.metric_stats.MetricStats(
metric=sb.nnet.losses.nll_loss
)
# Set up evaluation-only statistics trackers
if stage != sb.Stage.TRAIN:
self.error_metrics = self.hparams.error_stats()
def on_stage_end(self, stage, stage_loss, epoch=None):
"""Gets called at the end of an epoch.
Arguments
---------
stage : sb.Stage
One of sb.Stage.TRAIN, sb.Stage.VALID, sb.Stage.TEST
stage_loss : float
The average loss for all of the data processed in this stage.
epoch : int
The currently-starting epoch. This is passed
`None` during the test stage.
"""
# Store the train loss until the validation stage.
if stage == sb.Stage.TRAIN:
self.train_loss = stage_loss
# Summarize the statistics from the stage for record-keeping.
else:
stats = {
"loss": stage_loss,
"error": self.error_metrics.summarize("average"),
}
# At the end of validation...
if stage == sb.Stage.VALID:
old_lr, new_lr = self.hparams.lr_annealing(epoch)
sb.nnet.schedulers.update_learning_rate(self.optimizer, new_lr)
# The train_logger writes a summary to stdout and to the logfile.
self.hparams.train_logger.log_stats(
{"Epoch": epoch, "lr": old_lr},
train_stats={"loss": self.train_loss},
valid_stats=stats,
)
# Save the current checkpoint and delete previous checkpoints,
self.checkpointer.save_and_keep_only(meta=stats, min_keys=["error"])
# We also write statistics about test data to stdout and to the logfile.
if stage == sb.Stage.TEST:
self.hparams.train_logger.log_stats(
{"Epoch loaded": self.hparams.epoch_counter.current},
test_stats=stats,
)
def dataio_prep(hparams):
"""This function prepares the datasets to be used in the brain class.
It also defines the data processing pipeline through user-defined functions.
We expect `prepare_mini_librispeech` to have been called before this,
so that the `train.json`, `valid.json`, and `valid.json` manifest files
are available.
Arguments
---------
hparams : dict
This dictionary is loaded from the `train.yaml` file, and it includes
all the hyperparameters needed for dataset construction and loading.
Returns
-------
datasets : dict
Contains two keys, "train" and "valid" that correspond
to the appropriate DynamicItemDataset object.
"""
# Initialization of the label encoder. The label encoder assigns to each
# of the observed label a unique index (e.g, 'spk01': 0, 'spk02': 1, ..)
label_encoder = sb.dataio.encoder.CategoricalEncoder()
# Define audio pipeline
@sb.utils.data_pipeline.takes("wav")
@sb.utils.data_pipeline.provides("sig")
def audio_pipeline(wav):
"""Load the signal, and pass it and its length to the corruption class.
This is done on the CPU in the `collate_fn`."""
sig = sb.dataio.dataio.read_audio(wav)
return sig
# Define label pipeline:
@sb.utils.data_pipeline.takes("spk_id")
@sb.utils.data_pipeline.provides("spk_id", "spk_id_encoded")
def label_pipeline(spk_id):
"""Defines the pipeline to process the input speaker label."""
yield spk_id
spk_id_encoded = label_encoder.encode_label_torch(spk_id)
yield spk_id_encoded
# Define datasets. We also connect the dataset with the data processing
# functions defined above.
datasets = {}
data_info = {
"train": hparams["train_annotation"],
"valid": hparams["valid_annotation"],
"test": hparams["test_annotation"],
}
hparams["dataloader_options"]["shuffle"] = False
for dataset in data_info:
datasets[dataset] = sb.dataio.dataset.DynamicItemDataset.from_json(
json_path=data_info[dataset],
replacements={"data_root": hparams["data_folder"]},
dynamic_items=[audio_pipeline, label_pipeline],
output_keys=["id", "sig", "spk_id_encoded"],
)
# Load or compute the label encoder (with multi-GPU DDP support)
# Please, take a look into the lab_enc_file to see the label to index
# mapping.
lab_enc_file = os.path.join(hparams["save_folder"], "label_encoder.txt")
label_encoder.load_or_create(
path=lab_enc_file,
from_didatasets=[datasets["train"]],
output_key="spk_id",
)
return datasets
# Recipe begins!
if __name__ == "__main__":
# Reading command line arguments.
hparams_file, run_opts, overrides = sb.parse_arguments(sys.argv[1:])
# Initialize ddp (useful only for multi-GPU DDP training).
sb.utils.distributed.ddp_init_group(run_opts)
# Load hyperparameters file with command-line overrides.
with open(hparams_file) as fin:
hparams = load_hyperpyyaml(fin, overrides)
# Create experiment directory
sb.create_experiment_directory(
experiment_directory=hparams["output_folder"],
hyperparams_to_save=hparams_file,
overrides=overrides,
)
# Data preparation, to be run on only one process.
if not hparams["skip_prep"]:
sb.utils.distributed.run_on_main(
prepare_mini_librispeech,
kwargs={
"data_folder": hparams["data_folder"],
"save_json_train": hparams["train_annotation"],
"save_json_valid": hparams["valid_annotation"],
"save_json_test": hparams["test_annotation"],
"split_ratio": hparams["split_ratio"],
},
)
# Create dataset objects "train", "valid", and "test".
datasets = dataio_prep(hparams)
# Initialize the Brain object to prepare for mask training.
spk_id_brain = SpkIdBrain(
modules=hparams["modules"],
opt_class=hparams["opt_class"],
hparams=hparams,
run_opts=run_opts,
checkpointer=hparams["checkpointer"],
)
# The `fit()` method iterates the training loop, calling the methods
# necessary to update the parameters of the model. Since all objects
# with changing state are managed by the Checkpointer, training can be
# stopped at any point, and will be resumed on next call.
spk_id_brain.fit(
epoch_counter=spk_id_brain.hparams.epoch_counter,
train_set=datasets["train"],
valid_set=datasets["valid"],
train_loader_kwargs=hparams["dataloader_options"],
valid_loader_kwargs=hparams["dataloader_options"],
)
# Load the best checkpoint for evaluation
test_stats = spk_id_brain.evaluate(
test_set=datasets["test"],
min_key="error",
test_loader_kwargs=hparams["dataloader_options"],
)
| [
"[email protected]"
] | |
6deefd1f16785bce2090866dab195b0c52bb9f78 | e649eaa158a0fb311ac69f8df466097b69f29d8a | /tapioca_toggl/tapioca_toggl.py | 0d8116f1937344e5376c39b6db74915601d32816 | [
"Python-2.0",
"MIT"
] | permissive | pgniewosz/tapioca-toggl | 862f1d454e34139e75bcb1596f92387c94a004f5 | 0b789934d18cbbfe1bdcbe6b0905bf653fb9c68f | refs/heads/master | 2020-12-31T02:00:52.044366 | 2015-12-09T21:24:17 | 2015-12-09T21:24:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,167 | py | # -*- coding: utf-8 -*-
from tapioca import (
JSONAdapterMixin,
TapiocaAdapter,
generate_wrapper_from_adapter,
)
from requests.auth import HTTPBasicAuth
from .resource_mapping import RESOURCE_MAPPING
class TogglClientAdapter(JSONAdapterMixin, TapiocaAdapter):
api_root = 'https://www.toggl.com/api/v8/'
resource_mapping = RESOURCE_MAPPING
def get_request_kwargs(self, api_params, *args, **kwargs):
params = super(TogglClientAdapter, self).get_request_kwargs(
api_params, *args, **kwargs
)
access_token = api_params.get('access_token')
if access_token:
params['auth'] = HTTPBasicAuth(access_token, 'api_token')
else:
params['auth'] = HTTPBasicAuth(
api_params.get('user'),
api_params.get('password')
)
return params
def get_iterator_list(self, response_data):
return response_data
def get_iterator_next_request_kwargs(self, iterator_request_kwargs,
response_data, response):
pass
Toggl = generate_wrapper_from_adapter(TogglClientAdapter)
| [
"[email protected]"
] | |
91417fed22a522075bbf7a6fe7c62e14eb481945 | edbf37a80849468145cdcfca2012d205cdba9b50 | /csv_to_hdf5.py | a1fdc67f0ebeb87b9e3b822575a7a3e38dc3bb06 | [] | no_license | hsiaoyi0504/cheminfo-final | f0f19d67c697b91195aff7fd52044e2f7a9fd434 | 7dbfb9729a443060d45562123768398513d11085 | refs/heads/master | 2021-01-12T09:32:26.927273 | 2017-02-14T17:21:26 | 2017-02-14T17:21:26 | 76,188,236 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,469 | py | import sys
import os
from itertools import islice
import h5py
import numpy as np
from sklearn.model_selection import train_test_split
sys.path.append(os.path.abspath("./keras-molecules"))
from molecules.utils import load_dataset, one_hot_array, one_hot_index
import pandas as pd
data, charset = load_dataset('./keras-molecules/data/processed_zinc12_250k.h5', split = False)
charset = list(charset)
del data
smiles = []
solubility = []
with open('./data/total.csv') as f:
for line in islice(f,1,None):
temp = line.rstrip('\r\n')
temp = temp.split(',')
smiles.append(temp[0])
solubility.append(float(temp[1]))
clean_smiles = []
clean_solubility = []
for i in range(len(smiles)):
in_charset = True
if len(smiles[i])>120:
in_charset = False
else:
for char in smiles[i]:
if char not in charset:
in_charset = False
break
if in_charset:
clean_smiles.append(smiles[i])
clean_solubility.append(solubility[i])
h5f = h5py.File('./data/processed_solubility.h5', 'w')
data = pd.DataFrame({'structure':clean_smiles,'logS':clean_solubility})
keys = data['structure'].map(len)<121
data = data[keys]
dt = h5py.special_dtype(vlen=unicode)
h5f.create_dataset('structure',data=data['structure'],dtype=dt)
structures = data['structure'].map(lambda x: list(x.ljust(120)))
one_hot_encoded_fn = lambda row: map(lambda x: one_hot_array(x, len(charset)),one_hot_index(row, charset))
h5f.create_dataset('charset', data = charset)
def chunk_iterator(dataset, chunk_size=100):
chunk_indices = np.array_split(np.arange(len(dataset)),len(dataset)/chunk_size)
for chunk_ixs in chunk_indices:
chunk = dataset[chunk_ixs]
yield (chunk_ixs, chunk)
raise StopIteration
def create_chunk_dataset(h5file, dataset_name, dataset, dataset_shape,chunk_size=100, apply_fn=None):
new_data = h5file.create_dataset(dataset_name, dataset_shape,chunks=tuple([chunk_size]+list(dataset_shape[1:])))
for (chunk_ixs, chunk) in chunk_iterator(dataset):
if not apply_fn:
new_data[chunk_ixs, ...] = chunk
else:
new_data[chunk_ixs, ...] = apply_fn(chunk)
test_idx = structures.index
create_chunk_dataset(h5f, 'data_test', test_idx,(len(test_idx), 120, len(charset)),apply_fn=lambda ch: np.array(map(one_hot_encoded_fn,structures[ch])))
h5f.create_dataset('solubility',data=data['logS'][test_idx])
h5f.close()
| [
"[email protected]"
] | |
395ae2d504cb4be15aacfe24989028ced7cd5bb6 | 9ecd7568b6e4f0f55af7fc865451ac40038be3c4 | /tianlikai/shandong/qingdao.py | 2a7b9ffffeabdc15e72299245459613fca9782da | [] | no_license | jasonTLK/scrapy | f5ac6e575e902c077a07dc0eb9d228506f1a173f | 2de8245fbc8731cfd868bbd91168e26271045300 | refs/heads/master | 2021-01-20T04:22:23.080864 | 2017-04-28T07:46:29 | 2017-04-28T07:46:29 | 89,681,374 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,444 | py | # -*- coding: utf-8 -*-
from items.biding import biding_gov
from utils.toDB import *
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
import datetime
# 山东青岛招投标网站
# 其他信息
class LianjiaSpider(CrawlSpider):
name = "qingdao.py"
allowed_domains = ["ggzy.qingdao.gov.cn"]
start_urls = [
"http://ggzy.qingdao.gov.cn/index.html"
]
rules = [
# 匹配正则表达式,处理下一页
Rule(LinkExtractor(allow=('',), deny=(r'.*(n32205482)|(n32205478)|(zbFlag=0).*',), unique=True), follow=True, callback='parse_item')
]
def parse_item(self, response):
print response.url
items = biding_gov()
items["url"] = response.url
items["info"] = ""
items["create_time"] = datetime.datetime.now()
items["update_time"] = datetime.datetime.now()
page_info = "".join(response.body)
try:
items["info"] = "".join(page_info).decode('gbk')
except:
items["info"] = "".join(page_info)
db = MongodbHandle("172.20.3.10 ", 27017, "Bid_Other_info")
db.get_insert(
"bid_shandong_QingDao",
{
"url": items["url"],
"info": items["info"],
"create_time": items["create_time"],
"update_time": items["update_time"]
}
)
| [
"[email protected]"
] | |
1c4c926d1547bee952cd3b18817763f0a75c1a1d | 55123cea6831600a7f94b29df86aa12c9ccd82e4 | /test/test_gpu_programming.py | 26bcc6aa254f5b802e5a5dbb514fe0ccd3266ec9 | [
"MIT"
] | permissive | yngtodd/gpu_programming | 34915f76d2c39d3a3dfe633d0dd40fee1c077579 | 84ce7cb4280690bfb46cb36fb7ef47863d97a529 | refs/heads/master | 2020-04-10T10:50:54.522162 | 2018-12-08T22:54:24 | 2018-12-08T22:54:24 | 160,977,394 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 300 | py | """
Tests for `gpu_programming` module.
"""
import pytest
from gpu_programming import gpu_programming
class TestGpu_programming(object):
@classmethod
def setup_class(cls):
pass
def test_something(self):
pass
@classmethod
def teardown_class(cls):
pass
| [
"[email protected]"
] | |
48f1a194c93c3f79e47c8abb291e2846c3dc4d3c | 24b2f3f5f49ed19cf7fd3dcd433d6b72806e08cf | /python/sorting_and_searching/0658_Find_K_Closest_Elements.py | 05baab2d171b85dcb87d49d361a97f8f74117f59 | [] | no_license | lizzzcai/leetcode | 97089e4ca8c3c53b5a4a50de899591be415bac37 | 551cd3b4616c16a6562eb7c577ce671b419f0616 | refs/heads/master | 2021-06-23T05:59:56.928042 | 2020-12-07T03:07:58 | 2020-12-07T03:07:58 | 162,840,861 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,752 | py | '''
08/04/2020
658. Find K Closest Elements - Medium
Tag: Binary Search
Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.
Example 1:
Input: [1,2,3,4,5], k=4, x=3
Output: [1,2,3,4]
Example 2:
Input: [1,2,3,4,5], k=4, x=-1
Output: [1,2,3,4]
Note:
The value k is positive and will always be smaller than the length of the sorted array.
Length of the given array is positive and will not exceed 104
Absolute value of elements in the array and x will not exceed 104
UPDATE (2017/9/19):
The arr parameter had been changed to an array of integers (instead of a list of integers). Please reload the code definition to get the latest changes.
'''
from typing import List
# Solution
class Solution1:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
'''
Time: O(n+nlogn+klogk)
Space: O(n)
'''
dist = [(abs(i-x), i) for i in arr]
dist.sort()
return sorted([t[1] for t in dist[:k]])
class Solution2:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
'''
Time: O(logn + k)
Space: O(k)
'''
def binary_search(l, r, target):
'''
find the first element >= than target
'''
while l <= r:
mid = (l+r) // 2
if arr[mid] >= target:
r = mid - 1
else:
l = mid + 1
return l
if x <= arr[0]:
return arr[:k]
if x >= arr[-1]:
return arr[-k:]
n = len(arr)
idx = binary_search(0, n-1, x)
l, r = max(0, idx-k), min(n-1, idx+k)
while l+k <= r:
# If there is a tie, the smaller elements are always preferred.
if x - arr[l] <= arr[r] - x:
r -= 1
else:# x - arr[l] > arr[r] - x:
l += 1
return arr[l:r+1]
# Unit Test
import unittest
class TestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_testCase(self):
for Sol in [Solution1(), Solution2()]:
func = Sol.findClosestElements
self.assertEqual(func([1,2,3,4,5], 4, 3), [1,2,3,4])
self.assertEqual(func([1,2,3,4,5], 4, -1), [1,2,3,4])
self.assertEqual(func([0,0,1,2,3,3,4,7,7,8], 3, 5), [3,3,4])
self.assertEqual(func([0,1,2,2,2,3,6,8,8,9], 5, 9), [3,6,8,8,9])
if __name__ == '__main__':
unittest.main() | [
"[email protected]"
] | |
033a22f493ad32f11f1b533014f8c78daae54fa2 | 29597b67f10d456bdcc90a693ac93f571635ae34 | /structure/recursion/keypad.py | b9565dcadcb6cdd6cf9c359c88e82b56b566a7ad | [] | no_license | sh-tatsuno/python-algorithm | 67d50f24604550c115f957ed74e81483566c560d | 2800050077562eef50b6f0bd8ba6733068469c4c | refs/heads/master | 2020-05-17T09:46:05.714449 | 2019-07-25T15:43:20 | 2019-07-25T15:43:20 | 183,641,527 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,577 | py | def get_characters(num):
if num == 2:
return "abc"
elif num == 3:
return "def"
elif num == 4:
return "ghi"
elif num == 5:
return "jkl"
elif num == 6:
return "mno"
elif num == 7:
return "pqrs"
elif num == 8:
return "tuv"
elif num == 9:
return "wxyz"
else:
return ""
def keypad(num):
text = str(num)
if len(text) <= 1:
return [s for s in get_characters(num)]
ret = []
for c in get_characters(int(text[0])):
ret += [c + keys for keys in keypad(int(text[1:]))]
return ret
def test_keypad(input, expected_output):
if sorted(keypad(input)) == expected_output:
print("Yay. We got it right.")
else:
print("Oops! That was incorrect.")
# Base case: list with empty string
input = 0
expected_output = [""]
test_keypad(input, expected_output)
# Example case
input = 23
expected_output = sorted(["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"])
test_keypad(input, expected_output)
# Example case
input = 32
expected_output = sorted(["da", "db", "dc", "ea", "eb", "ec", "fa", "fb", "fc"])
test_keypad(input, expected_output)
# Example case
input = 8
expected_output = sorted(["t", "u", "v"])
test_keypad(input, expected_output)
input = 354
expected_output = sorted(["djg", "ejg", "fjg", "dkg", "ekg", "fkg", "dlg", "elg", "flg", "djh", "ejh", "fjh", "dkh", "ekh", "fkh", "dlh", "elh", "flh", "dji", "eji", "fji", "dki", "eki", "fki", "dli", "eli", "fli"])
test_keypad(input, expected_output) | [
"[email protected]"
] | |
89ab0709a97719352d3faf225b1ef3224e177f24 | 30c820b171447ab772e58f04ac0dc55c4d5ffbdf | /transax/setup.py | fca863366f71e276dc836f489d4594540c33f89a | [] | no_license | TransactiveSCC/TRANSAX | 3b58cff757fb646a825872dc243e04eea3d0b712 | 13c45a1254cb14607d1bfa86267dbde9e61fd538 | refs/heads/main | 2023-05-13T10:50:20.868093 | 2021-05-15T02:45:53 | 2021-05-15T02:45:53 | 316,015,185 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 284 | py | from setuptools import setup
setup(
name='transax',
version='1.0',
description='',
author='Scott Eisele',
author_email='[email protected]',
packages=['transax'], #same as name
install_requires=['scipy','pycurl'], #external packages as dependencies
) | [
"[email protected]"
] | |
6d7534730773802df64b5660a516a95e01c824f8 | 3953a4cf5dee0667c08e1fe1250a3067090e3f24 | /mural/config/settings/base.py | 4b847aae2bbfb7548c7bdbde55ea49cc1d1314f1 | [] | no_license | DigitalGizmo/msm_mural_project | 41960242c84050ee578da90afabcb7f9bc1923df | 5566a2b6f7445dc53d8aaf96cf7d24236fd5ed96 | refs/heads/master | 2020-03-07T11:04:49.633149 | 2019-02-13T18:10:44 | 2019-02-13T18:10:44 | 127,447,243 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,677 | py | """
Django settings for mural project.
Generated by 'django-admin startproject' using Django 2.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
# import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from unipath import Path
BASE_DIR = Path(__file__).ancestor(3)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '%-qkyq-id+=w)vd8p3+1#apulkq^@1h%vaq&lk1hsy(ww@h56h'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['msm-mural.digitalgizmo.com', '127.0.0.1']
# Application definition
INSTALLED_APPS = [
'panels.apps.PanelsConfig',
'pops.apps.PopsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'config.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR.child("templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'msm_mural_db',
'USER': 'msm_mural_user',
'PASSWORD': 'Moser$1872',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/New_York'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
# Static files (CSS, JavaScript, Images)
STATIC_ROOT = BASE_DIR.ancestor(2).child("msm_mural_static")
STATICFILES_DIRS = (
BASE_DIR.child("local_static"),
)
| [
"[email protected]"
] | |
ebcc2fb4ec2070fc0d085207134c5027fb58105f | 428165a69405e0ce5245d225e6038598cd2a5be9 | /courses/urls.py | ccbf1b37e0d07f8dff067aa1658bfa5fb2514919 | [] | no_license | alialwahish/courses | 2374a0e52a87e18808f5cdf268a9ecbaa788b3e5 | c01e6cc1b05313764fe07d514c0f10009c3f80b2 | refs/heads/master | 2020-03-17T19:06:57.991045 | 2018-05-17T17:22:27 | 2018-05-17T17:22:27 | 133,846,142 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 106 | py | from django.conf.urls import url,include
urlpatterns = [
url(r'^',include('apps.appCourses.urls'))
]
| [
"[email protected]"
] | |
8f1c32b9228c8eae48071a9322737aa0ae75e2ee | 306afd5282d9c24d58297478a1728a006c29e57e | /python3/905_Sort_Array_By_Parity.py | 3a705fc16ba5f96d63db2ec53acf28e955804135 | [] | no_license | ytatus94/Leetcode | d2c1fe3995c7a065139f772569485dc6184295a9 | 01ee75be4ec9bbb080f170cb747f3fc443eb4d55 | refs/heads/master | 2023-06-08T17:32:34.439601 | 2023-05-29T04:33:19 | 2023-05-29T04:33:19 | 171,921,974 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 455 | py | class Solution:
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
even =[]
odd = []
for i in A:
if i % 2 == 0:
even.append(i)
else:
odd.append(i)
return even + odd
class Solution:
def sortArrayByParity(self, A):
# 看到一個別的方法
return sorted(A, key=lambda x: x%2)
| [
"[email protected]"
] | |
c559b7dcb34495138c12b520236775a346862bd8 | 9d30dcfcedc98306e60779d25cad83345b4f032c | /src/pip/_internal/models/target_python.py | 7ad5786c4354cb0e520e8f9493c72619c29ebf82 | [
"MIT"
] | permissive | loke5555/pip | 1cb04e69eecb9969cf663a2a1bf5095b84cdff55 | a8510bc5e6b7c4849a0351deab3c1d41fd9a63d1 | refs/heads/master | 2020-06-14T08:22:50.373830 | 2019-07-02T09:00:02 | 2019-07-02T09:00:02 | 194,958,398 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,734 | py | import sys
from pip._internal.pep425tags import get_supported, version_info_to_nodot
from pip._internal.utils.misc import normalize_version_info
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from typing import List, Optional, Tuple
from pip._internal.pep425tags import Pep425Tag
class TargetPython(object):
"""
Encapsulates the properties of a Python interpreter one is targeting
for a package install, download, etc.
"""
def __init__(
self,
platform=None, # type: Optional[str]
py_version_info=None, # type: Optional[Tuple[int, ...]]
abi=None, # type: Optional[str]
implementation=None, # type: Optional[str]
):
# type: (...) -> None
"""
:param platform: A string or None. If None, searches for packages
that are supported by the current system. Otherwise, will find
packages that can be built on the platform passed in. These
packages will only be downloaded for distribution: they will
not be built locally.
:param py_version_info: An optional tuple of ints representing the
Python version information to use (e.g. `sys.version_info[:3]`).
This can have length 1, 2, or 3 when provided.
:param abi: A string or None. This is passed to pep425tags.py's
get_supported() function as is.
:param implementation: A string or None. This is passed to
pep425tags.py's get_supported() function as is.
"""
# Store the given py_version_info for when we call get_supported().
self._given_py_version_info = py_version_info
if py_version_info is None:
py_version_info = sys.version_info[:3]
else:
py_version_info = normalize_version_info(py_version_info)
py_version = '.'.join(map(str, py_version_info[:2]))
self.abi = abi
self.implementation = implementation
self.platform = platform
self.py_version = py_version
self.py_version_info = py_version_info
# This is used to cache the return value of get_tags().
self._valid_tags = None # type: Optional[List[Pep425Tag]]
def format_given(self):
# type: () -> str
"""
Format the given, non-None attributes for display.
"""
display_version = None
if self._given_py_version_info is not None:
display_version = '.'.join(
str(part) for part in self._given_py_version_info
)
key_values = [
('platform', self.platform),
('version_info', display_version),
('abi', self.abi),
('implementation', self.implementation),
]
return ' '.join(
'{}={!r}'.format(key, value) for key, value in key_values
if value is not None
)
def get_tags(self):
# type: () -> List[Pep425Tag]
"""
Return the supported tags to check wheel candidates against.
"""
if self._valid_tags is None:
# Pass versions=None if no py_version_info was given since
# versions=None uses special default logic.
py_version_info = self._given_py_version_info
if py_version_info is None:
versions = None
else:
versions = [version_info_to_nodot(py_version_info)]
tags = get_supported(
versions=versions,
platform=self.platform,
abi=self.abi,
impl=self.implementation,
)
self._valid_tags = tags
return self._valid_tags
| [
"[email protected]"
] | |
3fcfcef8fa826d5b89ab602739c53b107e8c0050 | 14f223f1855215f6cbeaba533bcfe26532161918 | /basics and advanced/armstrong_pract.py | 0e16e80f5392370354718a9842eda8c0614e3e04 | [] | no_license | iiibsceprana/pranavsai | 1026519a44eac429db8c4a6e3664277839d5dd52 | ffd8c937c50814676b0ee1eabdfd461087d52b96 | refs/heads/master | 2020-03-09T23:36:23.258180 | 2018-04-11T08:53:55 | 2018-04-11T08:53:55 | 129,061,808 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 296 | py | inp=int(input("Enter an Integer:"))
num=inp
print("num:",num)
sum=0
while inp>0:
n=inp%10
print("n:",n)
sum+=n*n*n
print("sum:",sum)
inp=inp//10
print("inp:",inp)
if num==sum:
print("Given number is Armtrong")
else:
print("Given number is not Armstrong")
| [
"[email protected]"
] | |
4c85c67d781eb179e4dafca7cb96d60c8873cc0e | 0b35072547001ebefa3fde2eea0eae30423e2190 | /editregions/contrib/textfiles/admin.py | 1bc746c9c1addc07aa4ae926a814393591df4afb | [
"BSD-2-Clause-Views",
"BSD-2-Clause"
] | permissive | kezabelle/django-editregions | ceba5561a4768ccda9ccd279f3a6a35e11dbdfea | 961ddeffb37d30d40fb4e3e9224bc3f956b7a5b5 | refs/heads/master | 2020-06-06T19:40:36.682702 | 2015-01-21T14:33:52 | 2015-01-21T14:33:52 | 14,645,861 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,474 | py | # -*- coding: utf-8 -*-
from functools import update_wrapper
from django.contrib import admin
from django.contrib.admin import ModelAdmin
from django.core.exceptions import ValidationError, PermissionDenied
from django.http import HttpResponse
from django.template.defaultfilters import striptags
from django.template.loader import render_to_string
try:
from django.utils.text import Truncator
def truncate_words(s, num):
return Truncator(s).words(num, truncate='...')
except ImportError as e: # pragma: no cover
from django.utils.text import truncate_words
from editregions.admin.modeladmins import ChunkAdmin
from editregions.contrib.textfiles.utils import valid_md_file
from .models import Markdown
from .forms import MarkdownSelectionForm
class MarkdownAdmin(ChunkAdmin, ModelAdmin):
form = MarkdownSelectionForm
list_display = ['filepath', 'created', 'modified']
add_form_template = 'admin/editregions/markdown/change_form.html'
change_form_template = 'admin/editregions/markdown/change_form.html'
def render_into_region(self, obj, context, **kwargs):
return render_to_string('editregions/textfiles/markdown.html',
context_instance=context)
def render_into_summary(self, obj, context, **kwargs):
data = striptags(obj.rendered_content).strip()
if data:
return truncate_words(data, 50)
return '[missing content]'
def get_urls(self):
default_urls = super(MarkdownAdmin, self).get_urls()
from django.conf.urls import patterns, url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.model._meta.app_label, self.model._meta.model_name
urlpatterns = patterns('',
url(r'^preview/(.+)$', wrap(self.preview), name='%s_%s_preview' % info),
)
return urlpatterns + default_urls
def preview(self, request, target_file, extra_context=None):
if not self.has_add_permission(request):
raise PermissionDenied("Need add permission")
try:
valid_md_file(target_file)
except ValidationError:
raise PermissionDenied("Invalid file")
fake_obj = self.model(filepath=target_file)
return HttpResponse(fake_obj.rendered_content)
admin.site.register(Markdown, MarkdownAdmin)
| [
"[email protected]"
] | |
2ffcff7acb286a0ae13295300bd567c7f8e0cc56 | b8467af3373374f54aef8e4a060eb9550028f298 | /functionsprogram/myprograms.py | dcf9e8fa570248d0908469b331daa249eba8591c | [] | no_license | luminartraining/luminarPythonNovember | 6790acf957bba6ec47ab5c872f8f22b1c22d63f7 | 33f4627f89c281fca45f58d00a4e3f1f221144fc | refs/heads/master | 2023-01-28T20:23:03.863310 | 2020-12-07T02:46:03 | 2020-12-07T02:46:03 | 315,807,677 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 222 | py | #import modules
#module ? package?
#we have to import mathooperatoons.py module
import functionsprogram.matoperations as fun
res=fun.add(100,200)
print(res)
sub=fun.sub(200,100)
print(res)
#create account in github
#git | [
"[email protected]"
] | |
ab03d8f6384fcbd71e3cd2408f91f5910e8878b7 | 521c1beeb2776161ae6d550be35cd0c180887129 | /customkeywords/tailProtocol.py | a1c19882a20fb2a2a23c6e113b2e1687b55fbdc7 | [] | no_license | elvis2workspace/CustomLibrary | 601b552792ac2c33beeb709474f857c82793ac7e | 6449eea8aa99ca1172f54b669d97703d36132ce3 | refs/heads/master | 2021-01-23T21:33:05.617871 | 2017-09-26T01:57:48 | 2017-09-26T01:57:48 | 58,983,388 | 0 | 1 | null | 2016-12-06T09:56:14 | 2016-05-17T02:22:14 | Python | UTF-8 | Python | false | false | 3,144 | py | # -*- coding: utf-8 -*-
"""
Created on 2015年5月8日
@author: zhang.xiuhai
"""
import os
import hashlib
from twisted.internet.protocol import ServerFactory, ProcessProtocol
from twisted.protocols.basic import LineReceiver
from twisted.python import log
from twisted.internet import reactor, threads
class TailProtocol(object):
"""classdocs"""
def __init__(self, write_callback):
self.write = write_callback
def out_received(self, data):
self.write("Begin lastlog\n")
data = [line for line in data.split('\n') if not line.startswith('==')]
for d in data:
self.write(d + '\n')
self.write("End lastlog\n")
def processEnded(self, reason):
if reason.value.exitCode != 0:
log.msg(reason)
class HashCompute(object):
def __init__(self, path, write_callback):
self.path = path
self.write = write_callback
def blockingMethod(self):
os.path.isfile(self.path)
data = file(self.path).read()
# uncomment to add more delay
# import time
# time.sleep(10)
return hashlib.sha1(data).hexdigest()
def compute(self):
d = threads.deferToThread(self.blockingMethod)
d.addCallback(self.ret)
d.addErrback(self.err)
def ret(self, hdata):
self.write("File hash is : %s\n" % hdata)
def err(self, failure):
self.write("An error occured : %s\n" % failure.getErrorMessage())
class CmdProtocol(LineReceiver):
delimiter = '\n'
def processCmd(self, line):
if line.startswith('lastlog'):
tailProtocol = TailProtocol(self.transport.write)
# reactor.spawnProcess(tailProtocol, '/usr/bin/tail', args=['/usr/bin/tail', '-10', '/var/log/syslog'])
elif line.startswith('comphash'):
try:
useless, path = line.split(' ')
except:
self.transport.write('Please provide a path.\n')
return
hc = HashCompute(path, self.transport.write)
hc.compute()
elif line.startswith('exit'):
self.transport.loseConnection()
else:
self.transport.write('Command not found.\n')
def connectionMade(self):
self.client_ip = self.transport.getPeer()[1]
log.msg("Client connection from %s" % self.client_ip)
if len(self.factory.clients) >= self.factory.clients_max:
log.msg("Too many connections. bye !")
self.client_ip = None
self.transport.loseConnection()
else:
self.factory.clients.append(self.client_ip)
def connectionLost(self, reason):
log.msg('Lost client connection. Reason: %s' % reason)
if self.client_ip:
self.factory.clients.remove(self.client_ip)
def lineReceived(self, line):
log.msg('Cmd received from %s : %s' % (self.client_ip, line))
self.processCmd(line)
class MyFactory(ServerFactory):
protocol = CmdProtocol
def __init__(self, clients_max=10):
self.clients_max = clients_max
self.clients = [] | [
"[email protected]"
] | |
3c70d5350e30d99e67991d3efcbe1f1fce136e79 | 786027545626c24486753351d6e19093b261cd7d | /ghidra9.2.1_pyi/ghidra/app/util/demangler/gnu/__init__.pyi | 32ce2a5c514debd6436731a597a14186a1d74212 | [
"MIT"
] | permissive | kohnakagawa/ghidra_scripts | 51cede1874ef2b1fed901b802316449b4bf25661 | 5afed1234a7266c0624ec445133280993077c376 | refs/heads/main | 2023-03-25T08:25:16.842142 | 2021-03-18T13:31:40 | 2021-03-18T13:31:40 | 338,577,905 | 14 | 1 | null | null | null | null | UTF-8 | Python | false | false | 386 | pyi | from .DemanglerParseException import DemanglerParseException as DemanglerParseException
from .GnuDemangler import GnuDemangler as GnuDemangler
from .GnuDemanglerNativeProcess import GnuDemanglerNativeProcess as GnuDemanglerNativeProcess
from .GnuDemanglerOptions import GnuDemanglerOptions as GnuDemanglerOptions
from .GnuDemanglerParser import GnuDemanglerParser as GnuDemanglerParser
| [
"[email protected]"
] | |
58f4826f555e588ae83241260f0facb1e977d6de | 7f916c679df3cd4158afcaf57b7c0e042f59ce91 | /allel/io/vcf_read.py | 61667de07956e067f50cd99f8406c5ba6023ba8b | [
"MIT"
] | permissive | haseley/scikit-allel | 08998a9a418ee68ddc9adb4e263c23c34dab5d37 | 300ab04c858eedf64d339e942589dfcf45d719c7 | refs/heads/master | 2020-04-01T18:22:40.881846 | 2018-10-18T18:59:02 | 2018-10-18T18:59:02 | 153,488,427 | 0 | 0 | MIT | 2018-10-18T18:52:38 | 2018-10-17T16:23:44 | Jupyter Notebook | UTF-8 | Python | false | false | 57,129 | py | # -*- coding: utf-8 -*-
"""
Extract data from VCF files.
This module contains Functions for extracting data from Variant Call Format (VCF) files and loading
into NumPy arrays, NumPy files, HDF5 files or Zarr array stores.
"""
from __future__ import absolute_import, print_function, division
import gzip
import os
import re
from collections import namedtuple
import warnings
import time
import subprocess
import numpy as np
from allel.compat import PY2, FileNotFoundError, text_type
from allel.opt.io_vcf_read import VCFChunkIterator, FileInputStream
# expose some names from cython extension
from allel.opt.io_vcf_read import ( # noqa: F401
ANNTransformer, ANN_AA_LENGTH_FIELD, ANN_AA_POS_FIELD, ANN_ANNOTATION_FIELD,
ANN_ANNOTATION_IMPACT_FIELD, ANN_CDNA_LENGTH_FIELD, ANN_CDNA_POS_FIELD, ANN_CDS_LENGTH_FIELD,
ANN_CDS_POS_FIELD, ANN_DISTANCE_FIELD, ANN_FEATURE_ID_FIELD, ANN_FEATURE_TYPE_FIELD, ANN_FIELD,
ANN_FIELDS, ANN_GENE_ID_FIELD, ANN_GENE_NAME_FIELD, ANN_HGVS_C_FIELD, ANN_HGVS_P_FIELD,
ANN_RANK_FIELD, ANN_TRANSCRIPT_BIOTYPE_FIELD
)
DEFAULT_BUFFER_SIZE = 2**14
DEFAULT_CHUNK_LENGTH = 2**16
DEFAULT_CHUNK_WIDTH = 2**6
DEFAULT_ALT_NUMBER = 3
def _prep_fields_param(fields):
"""Prepare the `fields` parameter, and determine whether or not to store samples."""
store_samples = False
if fields is None:
# add samples by default
return True, None
if isinstance(fields, str):
fields = [fields]
else:
fields = list(fields)
if 'samples' in fields:
fields.remove('samples')
store_samples = True
elif '*' in fields:
store_samples = True
return store_samples, fields
def _chunk_iter_progress(it, log, prefix):
"""Wrap a chunk iterator for progress logging."""
n_variants = 0
before_all = time.time()
before_chunk = before_all
for chunk, chunk_length, chrom, pos in it:
after_chunk = time.time()
elapsed_chunk = after_chunk - before_chunk
elapsed = after_chunk - before_all
n_variants += chunk_length
chrom = text_type(chrom, 'utf8')
message = (
'%s %s rows in %.2fs; chunk in %.2fs (%s rows/s)' %
(prefix, n_variants, elapsed, elapsed_chunk, int(chunk_length // elapsed_chunk))
)
if chrom:
message += '; %s:%s' % (chrom, pos)
print(message, file=log)
log.flush()
yield chunk, chunk_length, chrom, pos
before_chunk = after_chunk
after_all = time.time()
elapsed = after_all - before_all
print('%s all done (%s rows/s)' %
(prefix, int(n_variants // elapsed)), file=log)
log.flush()
def _chunk_iter_transform(it, transformers):
for chunk, chunk_length, chrom, pos in it:
for transformer in transformers:
transformer.transform_chunk(chunk)
yield chunk, chunk_length, chrom, pos
_doc_param_input = \
"""Path to VCF file on the local file system. May be uncompressed or gzip-compatible
compressed file. May also be a file-like object (e.g., `io.BytesIO`)."""
_doc_param_fields = \
"""Fields to extract data for. Should be a list of strings, e.g., ``['variants/CHROM',
'variants/POS', 'variants/DP', 'calldata/GT']``. If you are feeling lazy, you can drop
the 'variants/' and 'calldata/' prefixes, in which case the fields will be matched against
fields declared in the VCF header, with variants taking priority over calldata if a field
with the same ID exists both in INFO and FORMAT headers. I.e., ``['CHROM', 'POS', 'DP',
'GT']`` will work, although watch out for fields like 'DP' which can be both
INFO and FORMAT. For convenience, some special string values are also recognized. To
extract all fields, provide just the string ``'*'``. To extract all variants fields
(including all INFO fields) provide ``'variants/*'``. To extract all calldata fields (i.e.,
defined in FORMAT headers) provide ``'calldata/*'``."""
_doc_param_types = \
"""Overide data types. Should be a dictionary mapping field names to NumPy data types.
E.g., providing the dictionary ``{'variants/DP': 'i8', 'calldata/GQ': 'i2'}`` will mean
the 'variants/DP' field is stored in a 64-bit integer array, and the 'calldata/GQ' field
is stored in a 16-bit integer array."""
_doc_param_numbers = \
"""Override the expected number of values. Should be a dictionary mapping field names to
integers. E.g., providing the dictionary ``{'variants/ALT': 5, 'variants/AC': 5,
'calldata/HQ': 2}`` will mean that, for each variant, 5 values are stored for the
'variants/ALT' field, 5 values are stored for the 'variants/AC' field, and for each
sample, 2 values are stored for the 'calldata/HQ' field."""
_doc_param_alt_number = \
"""Assume this number of alternate alleles and set expected number of values accordingly for
any field declared with number 'A' or 'R' in the VCF meta-information."""
_doc_param_fills = \
"""Override the fill value used for empty values. Should be a dictionary mapping field names
to fill values."""
_doc_param_region = \
"""Genomic region to extract variants for. If provided, should be a tabix-style region string,
which can be either just a chromosome name (e.g., '2L'), or a chromosome name followed by
1-based beginning and end coordinates (e.g., '2L:100000-200000'). Note that only variants
whose start position (POS) is within the requested range will be included. This is slightly
different from the default tabix behaviour, where a variant (e.g., deletion) may be included
if its position (POS) occurs before the requested region but its reference allele overlaps
the region - such a variant will *not* be included in the data returned by this function."""
_doc_param_tabix = \
"""Name or path to tabix executable. Only required if `region` is given. Setting `tabix` to
`None` will cause a fall-back to scanning through the VCF file from the beginning, which
may be much slower than tabix but the only option if tabix is not available on your system
and/or the VCF file has not been tabix-indexed."""
_doc_param_samples = \
"""Selection of samples to extract calldata for. If provided, should be a list of strings
giving sample identifiers. May also be a list of integers giving indices of selected
samples."""
_doc_param_transformers = \
"""Transformers for post-processing data. If provided, should be a list of Transformer
objects, each of which must implement a "transform()" method that accepts a dict
containing the chunk of data to be transformed. See also the :class:`ANNTransformer`
class which implements post-processing of data from SNPEFF."""
_doc_param_buffer_size = \
"""Size in bytes of the I/O buffer used when reading data from the underlying file or tabix
stream."""
_doc_param_chunk_length = \
"""Length (number of variants) of chunks in which data are processed."""
_doc_param_log = \
"""A file-like object (e.g., `sys.stderr`) to print progress information."""
def read_vcf(input,
fields=None,
types=None,
numbers=None,
alt_number=DEFAULT_ALT_NUMBER,
fills=None,
region=None,
tabix='tabix',
samples=None,
transformers=None,
buffer_size=DEFAULT_BUFFER_SIZE,
chunk_length=DEFAULT_CHUNK_LENGTH,
log=None):
"""Read data from a VCF file into NumPy arrays.
Parameters
----------
input : string or file-like
{input}
fields : list of strings, optional
{fields}
types : dict, optional
{types}
numbers : dict, optional
{numbers}
alt_number : int, optional
{alt_number}
fills : dict, optional
{fills}
region : string, optional
{region}
tabix : string, optional
{tabix}
samples : list of strings
{samples}
transformers : list of transformer objects, optional
{transformers}
buffer_size : int, optional
{buffer_size}
chunk_length : int, optional
{chunk_length}
log : file-like, optional
{log}
Returns
-------
data : dict[str, ndarray]
A dictionary holding arrays.
"""
# samples requested?
# noinspection PyTypeChecker
store_samples, fields = _prep_fields_param(fields)
# setup
_, samples, _, it = iter_vcf_chunks(
input=input, fields=fields, types=types, numbers=numbers, alt_number=alt_number,
buffer_size=buffer_size, chunk_length=chunk_length, fills=fills, region=region,
tabix=tabix, samples=samples, transformers=transformers
)
# setup progress logging
if log is not None:
it = _chunk_iter_progress(it, log, prefix='[read_vcf]')
# read all chunks into a list
chunks = [d[0] for d in it]
# setup output
output = dict()
if len(samples) > 0 and store_samples:
output['samples'] = samples
if chunks:
# find array keys
keys = sorted(chunks[0].keys())
# concatenate chunks
for k in keys:
output[k] = np.concatenate([chunk[k] for chunk in chunks], axis=0)
return output
read_vcf.__doc__ = read_vcf.__doc__.format(
input=_doc_param_input,
fields=_doc_param_fields,
types=_doc_param_types,
numbers=_doc_param_numbers,
alt_number=_doc_param_alt_number,
fills=_doc_param_fills,
region=_doc_param_region,
tabix=_doc_param_tabix,
samples=_doc_param_samples,
transformers=_doc_param_transformers,
buffer_size=_doc_param_buffer_size,
chunk_length=_doc_param_chunk_length,
log=_doc_param_log,
)
_doc_param_output = \
"""File-system path to write output to."""
_doc_param_overwrite = \
"""If False (default), do not overwrite an existing file."""
def vcf_to_npz(input, output,
compressed=True,
overwrite=False,
fields=None,
types=None,
numbers=None,
alt_number=DEFAULT_ALT_NUMBER,
fills=None,
region=None,
tabix=True,
samples=None,
transformers=None,
buffer_size=DEFAULT_BUFFER_SIZE,
chunk_length=DEFAULT_CHUNK_LENGTH,
log=None):
"""Read data from a VCF file into NumPy arrays and save as a .npz file.
Parameters
----------
input : string
{input}
output : string
{output}
compressed : bool, optional
If True (default), save with compression.
overwrite : bool, optional
{overwrite}
fields : list of strings, optional
{fields}
types : dict, optional
{types}
numbers : dict, optional
{numbers}
alt_number : int, optional
{alt_number}
fills : dict, optional
{fills}
region : string, optional
{region}
tabix : string, optional
{tabix}
samples : list of strings
{samples}
transformers : list of transformer objects, optional
{transformers}
buffer_size : int, optional
{buffer_size}
chunk_length : int, optional
{chunk_length}
log : file-like, optional
{log}
"""
# guard condition
if not overwrite and os.path.exists(output):
raise ValueError('file exists at path %r; use overwrite=True to replace' % output)
# read all data into memory
data = read_vcf(
input=input, fields=fields, types=types, numbers=numbers, alt_number=alt_number,
buffer_size=buffer_size, chunk_length=chunk_length, log=log, fills=fills,
region=region, tabix=tabix, samples=samples, transformers=transformers
)
# setup save function
if compressed:
savez = np.savez_compressed
else:
savez = np.savez
# save as npz
savez(output, **data)
vcf_to_npz.__doc__ = vcf_to_npz.__doc__.format(
input=_doc_param_input,
output=_doc_param_output,
overwrite=_doc_param_overwrite,
fields=_doc_param_fields,
types=_doc_param_types,
numbers=_doc_param_numbers,
alt_number=_doc_param_alt_number,
fills=_doc_param_fills,
region=_doc_param_region,
tabix=_doc_param_tabix,
samples=_doc_param_samples,
transformers=_doc_param_transformers,
buffer_size=_doc_param_buffer_size,
chunk_length=_doc_param_chunk_length,
log=_doc_param_log,
)
def _hdf5_setup_datasets(chunk, root, chunk_length, chunk_width, compression, compression_opts,
shuffle, overwrite, headers, vlen):
import h5py
# handle no input
if chunk is None:
raise RuntimeError('input file has no data?')
# setup datasets
keys = sorted(chunk.keys())
for k in keys:
# obtain initial data
data = chunk[k]
# determine chunk shape
if data.ndim == 1:
chunk_shape = (chunk_length,)
else:
chunk_shape = (chunk_length, min(chunk_width, data.shape[1])) + data.shape[2:]
# create dataset
group, name = k.split('/')
if name in root[group]:
if overwrite:
del root[group][name]
else:
raise ValueError('dataset exists at path %r; use overwrite=True to replace' % k)
shape = (0,) + data.shape[1:]
maxshape = (None,) + data.shape[1:]
if data.dtype.kind == 'O':
if vlen:
dt = h5py.special_dtype(vlen=str)
else:
data = data.astype('S')
dt = data.dtype
else:
dt = data.dtype
ds = root[group].create_dataset(
name, shape=shape, maxshape=maxshape, chunks=chunk_shape, dtype=dt,
compression=compression, compression_opts=compression_opts, shuffle=shuffle
)
# copy metadata from VCF headers
meta = None
if group == 'variants' and name in headers.infos:
meta = headers.infos[name]
elif group == 'calldata' and name in headers.formats:
meta = headers.formats[name]
if meta is not None:
ds.attrs['ID'] = meta['ID']
ds.attrs['Number'] = meta['Number']
ds.attrs['Type'] = meta['Type']
ds.attrs['Description'] = meta['Description']
return keys
def _hdf5_store_chunk(root, keys, chunk, vlen):
# compute length of current chunk
current_chunk_length = chunk[keys[0]].shape[0]
# find current length of datasets
old_length = root[keys[0]].shape[0]
# new length of all arrays after loading this chunk
new_length = old_length + current_chunk_length
# load arrays
for k in keys:
# data to be loaded
data = chunk[k]
# obtain dataset
dataset = root[k]
# handle variable length strings
if data.dtype.kind == 'O' and not vlen:
data = data.astype('S')
if data.dtype.itemsize > dataset.dtype.itemsize:
warnings.warn(
'found string length %s longer than %s guessed for field %r, values will be '
'truncated; recommend rerunning setting type to at least "S%s"' %
(data.dtype.itemsize, dataset.dtype.itemsize, k, data.dtype.itemsize)
)
# ensure dataset is long enough
dataset.resize(new_length, axis=0)
# store the data
dataset[old_length:new_length, ...] = data
_doc_param_chunk_width = \
"""Width (number of samples) to use when storing chunks in output."""
def vcf_to_hdf5(input, output,
group='/',
compression='gzip',
compression_opts=1,
shuffle=False,
overwrite=False,
vlen=True,
fields=None,
types=None,
numbers=None,
alt_number=DEFAULT_ALT_NUMBER,
fills=None,
region=None,
tabix='tabix',
samples=None,
transformers=None,
buffer_size=DEFAULT_BUFFER_SIZE,
chunk_length=DEFAULT_CHUNK_LENGTH,
chunk_width=DEFAULT_CHUNK_WIDTH,
log=None):
"""Read data from a VCF file and load into an HDF5 file.
Parameters
----------
input : string
{input}
output : string
{output}
group : string
Group within destination HDF5 file to store data in.
compression : string
Compression algorithm, e.g., 'gzip' (default).
compression_opts : int
Compression level, e.g., 1 (default).
shuffle : bool
Use byte shuffling, which may improve compression (default is False).
overwrite : bool
{overwrite}
vlen : bool
If True, store variable length strings. Note that there is considerable storage overhead
for variable length strings in HDF5, and leaving this option as True (default) may lead
to large file sizes. If False, all strings will be stored in the HDF5 file as fixed length
strings, even if they are specified as 'object' type. In this case, the string length for
any field with 'object' type will be determined based on the maximum length of strings
found in the first chunk, and this may cause values to be truncated if longer values are
found in later chunks. To avoid truncation and large file sizes, manually set the type for
all string fields to an explicit fixed length string type, e.g., 'S10' for a field where
you know at most 10 characters are required.
fields : list of strings, optional
{fields}
types : dict, optional
{types}
numbers : dict, optional
{numbers}
alt_number : int, optional
{alt_number}
fills : dict, optional
{fills}
region : string, optional
{region}
tabix : string, optional
{tabix}
samples : list of strings
{samples}
transformers : list of transformer objects, optional
{transformers}
buffer_size : int, optional
{buffer_size}
chunk_length : int, optional
{chunk_length}
chunk_width : int, optional
{chunk_width}
log : file-like, optional
{log}
"""
import h5py
# samples requested?
# noinspection PyTypeChecker
store_samples, fields = _prep_fields_param(fields)
with h5py.File(output, mode='a') as h5f:
# obtain root group that data will be stored into
root = h5f.require_group(group)
# ensure sub-groups
root.require_group('variants')
root.require_group('calldata')
# setup chunk iterator
_, samples, headers, it = iter_vcf_chunks(
input, fields=fields, types=types, numbers=numbers, alt_number=alt_number,
buffer_size=buffer_size, chunk_length=chunk_length, fills=fills, region=region,
tabix=tabix, samples=samples, transformers=transformers
)
# setup progress logging
if log is not None:
it = _chunk_iter_progress(it, log, prefix='[vcf_to_hdf5]')
if len(samples) > 0 and store_samples:
# store samples
name = 'samples'
if name in root:
if overwrite:
del root[name]
else:
raise ValueError('dataset exists at path %r; use overwrite=True to replace'
% name)
if samples.dtype.kind == 'O':
if vlen:
t = h5py.special_dtype(vlen=str)
else:
samples = samples.astype('S')
t = samples.dtype
else:
t = samples.dtype
root.create_dataset(name, data=samples, chunks=None, dtype=t)
# read first chunk
chunk, _, _, _ = next(it)
# setup datasets
# noinspection PyTypeChecker
keys = _hdf5_setup_datasets(
chunk=chunk, root=root, chunk_length=chunk_length, chunk_width=chunk_width,
compression=compression, compression_opts=compression_opts, shuffle=shuffle,
overwrite=overwrite, headers=headers, vlen=vlen
)
# store first chunk
_hdf5_store_chunk(root, keys, chunk, vlen)
# store remaining chunks
for chunk, _, _, _ in it:
_hdf5_store_chunk(root, keys, chunk, vlen)
vcf_to_hdf5.__doc__ = vcf_to_hdf5.__doc__.format(
input=_doc_param_input,
output=_doc_param_output,
overwrite=_doc_param_overwrite,
fields=_doc_param_fields,
types=_doc_param_types,
numbers=_doc_param_numbers,
alt_number=_doc_param_alt_number,
fills=_doc_param_fills,
region=_doc_param_region,
tabix=_doc_param_tabix,
samples=_doc_param_samples,
transformers=_doc_param_transformers,
buffer_size=_doc_param_buffer_size,
chunk_length=_doc_param_chunk_length,
chunk_width=_doc_param_chunk_width,
log=_doc_param_log,
)
def _zarr_setup_datasets(chunk, root, chunk_length, chunk_width, compressor, overwrite, headers):
# handle no input
if chunk is None:
raise RuntimeError('input file has no data?')
# setup datasets
keys = sorted(chunk.keys())
for k in keys:
# obtain initial data
data = chunk[k]
# determine chunk shape
if data.ndim == 1:
chunk_shape = (chunk_length,)
else:
chunk_shape = (chunk_length, min(chunk_width, data.shape[1])) + data.shape[2:]
# create dataset
shape = (0,) + data.shape[1:]
if data.dtype.kind == 'O':
if PY2:
dtype = 'unicode'
else:
dtype = 'str'
else:
dtype = data.dtype
ds = root.create_dataset(k, shape=shape, chunks=chunk_shape, dtype=dtype,
compressor=compressor, overwrite=overwrite)
# copy metadata from VCF headers
group, name = k.split('/')
meta = None
if group == 'variants' and name in headers.infos:
meta = headers.infos[name]
elif group == 'calldata' and name in headers.formats:
meta = headers.formats[name]
if meta is not None:
ds.attrs['ID'] = meta['ID']
ds.attrs['Number'] = meta['Number']
ds.attrs['Type'] = meta['Type']
ds.attrs['Description'] = meta['Description']
return keys
def _zarr_store_chunk(root, keys, chunk):
# load arrays
for k in keys:
# append data
root[k].append(chunk[k], axis=0)
def vcf_to_zarr(input, output,
group='/',
compressor='default',
overwrite=False,
fields=None,
types=None,
numbers=None,
alt_number=DEFAULT_ALT_NUMBER,
fills=None,
region=None,
tabix='tabix',
samples=None,
transformers=None,
buffer_size=DEFAULT_BUFFER_SIZE,
chunk_length=DEFAULT_CHUNK_LENGTH,
chunk_width=DEFAULT_CHUNK_WIDTH,
log=None):
"""Read data from a VCF file and load into a Zarr on-disk store.
Parameters
----------
input : string
{input}
output : string
{output}
group : string
Group within destination Zarr hierarchy to store data in.
compressor : compressor
Compression algorithm, e.g., zarr.Blosc(cname='zstd', clevel=1, shuffle=1).
overwrite : bool
{overwrite}
fields : list of strings, optional
{fields}
types : dict, optional
{types}
numbers : dict, optional
{numbers}
alt_number : int, optional
{alt_number}
fills : dict, optional
{fills}
region : string, optional
{region}
tabix : string, optional
{tabix}
samples : list of strings
{samples}
transformers : list of transformer objects, optional
{transformers}
buffer_size : int, optional
{buffer_size}
chunk_length : int, optional
{chunk_length}
chunk_width : int, optional
{chunk_width}
log : file-like, optional
{log}
"""
import zarr
# samples requested?
# noinspection PyTypeChecker
store_samples, fields = _prep_fields_param(fields)
# open root group
root = zarr.open_group(output, mode='a', path=group)
# ensure sub-groups
root.require_group('variants')
root.require_group('calldata')
# setup chunk iterator
_, samples, headers, it = iter_vcf_chunks(
input, fields=fields, types=types, numbers=numbers, alt_number=alt_number,
buffer_size=buffer_size, chunk_length=chunk_length, fills=fills, region=region,
tabix=tabix, samples=samples, transformers=transformers
)
# setup progress logging
if log is not None:
it = _chunk_iter_progress(it, log, prefix='[vcf_to_zarr]')
if len(samples) > 0 and store_samples:
# store samples
if samples.dtype.kind == 'O':
if PY2:
dtype = 'unicode'
else:
dtype = 'str'
else:
dtype = samples.dtype
root.create_dataset('samples', data=samples, compressor=None, overwrite=overwrite,
dtype=dtype)
# read first chunk
chunk, _, _, _ = next(it)
# setup datasets
# noinspection PyTypeChecker
keys = _zarr_setup_datasets(
chunk, root=root, chunk_length=chunk_length, chunk_width=chunk_width, compressor=compressor,
overwrite=overwrite, headers=headers
)
# store first chunk
_zarr_store_chunk(root, keys, chunk)
# store remaining chunks
for chunk, _, _, _ in it:
_zarr_store_chunk(root, keys, chunk)
vcf_to_zarr.__doc__ = vcf_to_zarr.__doc__.format(
input=_doc_param_input,
output=_doc_param_output,
overwrite=_doc_param_overwrite,
fields=_doc_param_fields,
types=_doc_param_types,
numbers=_doc_param_numbers,
alt_number=_doc_param_alt_number,
fills=_doc_param_fills,
region=_doc_param_region,
tabix=_doc_param_tabix,
samples=_doc_param_samples,
transformers=_doc_param_transformers,
buffer_size=_doc_param_buffer_size,
chunk_length=_doc_param_chunk_length,
chunk_width=_doc_param_chunk_width,
log=_doc_param_log,
)
def iter_vcf_chunks(input,
fields=None,
types=None,
numbers=None,
alt_number=DEFAULT_ALT_NUMBER,
fills=None,
region=None,
tabix='tabix',
samples=None,
transformers=None,
buffer_size=DEFAULT_BUFFER_SIZE,
chunk_length=DEFAULT_CHUNK_LENGTH):
"""Iterate over chunks of data from a VCF file as NumPy arrays.
Parameters
----------
input : string
{input}
fields : list of strings, optional
{fields}
types : dict, optional
{types}
numbers : dict, optional
{numbers}
alt_number : int, optional
{alt_number}
fills : dict, optional
{fills}
region : string, optional
{region}
tabix : string, optional
{tabix}
samples : list of strings
{samples}
transformers : list of transformer objects, optional
{transformers}
buffer_size : int, optional
{buffer_size}
chunk_length : int, optional
{chunk_length}
Returns
-------
fields : list of strings
Normalised names of fields that will be extracted.
samples : ndarray
Samples for which data will be extracted.
headers : VCFHeaders
Tuple of metadata extracted from VCF headers.
it : iterator
Chunk iterator.
"""
# setup commmon keyword args
kwds = dict(fields=fields, types=types, numbers=numbers, alt_number=alt_number,
chunk_length=chunk_length, fills=fills, samples=samples)
# obtain a file-like object
close = False
if isinstance(input, str) and input.endswith('gz'):
if region and tabix and os.name != 'nt':
try:
# try tabix
p = subprocess.Popen([tabix, '-h', input, region],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=0)
# check if tabix exited early, look for tabix error
time.sleep(.5)
poll = p.poll()
if poll is not None and poll > 0:
err = p.stdout.read()
if not PY2:
err = str(err, 'ascii')
p.stdout.close()
raise RuntimeError(err.strip())
fileobj = p.stdout
close = True
# N.B., still pass the region parameter through so we get strictly only
# variants that start within the requested region. See also
# https://github.com/alimanfoo/vcfnp/issues/54
except FileNotFoundError:
# no tabix, fall back to scanning
warnings.warn('tabix not found, falling back to scanning to region')
fileobj = gzip.open(input, mode='rb')
close = True
except Exception as e:
warnings.warn('error occurred attempting tabix (%s); falling back to '
'scanning to region' % e)
fileobj = gzip.open(input, mode='rb')
close = True
else:
fileobj = gzip.open(input, mode='rb')
close = True
elif isinstance(input, str):
# assume no compression
fileobj = open(input, mode='rb', buffering=0)
close = True
elif hasattr(input, 'readinto'):
fileobj = input
else:
raise ValueError('path must be string or file-like, found %r' % input)
# setup input stream
stream = FileInputStream(fileobj, buffer_size=buffer_size, close=close)
# deal with region
kwds['region'] = region
# setup iterator
fields, samples, headers, it = _iter_vcf_stream(stream, **kwds)
# setup transformers
if transformers is not None:
# API flexibility
if not isinstance(transformers, (list, tuple)):
transformers = [transformers]
for trans in transformers:
fields = trans.transform_fields(fields)
it = _chunk_iter_transform(it, transformers)
return fields, samples, headers, it
iter_vcf_chunks.__doc__ = iter_vcf_chunks.__doc__.format(
input=_doc_param_input,
fields=_doc_param_fields,
types=_doc_param_types,
numbers=_doc_param_numbers,
alt_number=_doc_param_alt_number,
fills=_doc_param_fills,
region=_doc_param_region,
tabix=_doc_param_tabix,
samples=_doc_param_samples,
transformers=_doc_param_transformers,
buffer_size=_doc_param_buffer_size,
chunk_length=_doc_param_chunk_length,
log=_doc_param_log,
)
FIXED_VARIANTS_FIELDS = (
'CHROM',
'POS',
'ID',
'REF',
'ALT',
'QUAL',
)
def _normalize_field_prefix(field, headers):
# already contains prefix?
if field.startswith('variants/') or field.startswith('calldata/'):
return field
# try to find in fixed fields
elif field in FIXED_VARIANTS_FIELDS:
return 'variants/' + field
# try to find in FILTER
elif field.startswith('FILTER_'):
return 'variants/' + field
# try to find in FILTER
elif field in headers.filters:
return 'variants/FILTER_' + field
# try to find in INFO
elif field in headers.infos:
return 'variants/' + field
# try to find in FORMAT
elif field in headers.formats:
return 'calldata/' + field
else:
# assume anything else in variants, even if header not found
return 'variants/' + field
def _check_field(field, headers):
# assume field is already normalized for prefix
group, name = field.split('/')
if group == 'variants':
if name in FIXED_VARIANTS_FIELDS:
pass
elif name in ['numalt', 'svlen', 'is_snp']:
# computed fields
pass
elif name.startswith('FILTER_'):
filter_name = name[7:]
if filter_name in headers.filters:
pass
else:
warnings.warn('%r FILTER header not found' % filter_name)
elif name in headers.infos:
pass
else:
warnings.warn('%r INFO header not found' % name)
elif group == 'calldata':
if name in headers.formats:
pass
else:
warnings.warn('%r FORMAT header not found' % name)
else:
# should never be reached
raise ValueError('invalid field specification: %r' % field)
def _add_all_fields(fields, headers, samples):
_add_all_variants_fields(fields, headers)
if len(samples) > 0:
_add_all_calldata_fields(fields, headers)
def _add_all_variants_fields(fields, headers):
_add_all_fixed_variants_fields(fields)
_add_all_info_fields(fields, headers)
_add_all_filter_fields(fields, headers)
# add in computed fields
for f in 'variants/numalt', 'variants/svlen', 'variants/is_snp':
if f not in fields:
fields.append(f)
def _add_all_fixed_variants_fields(fields):
for k in FIXED_VARIANTS_FIELDS:
f = 'variants/' + k
if f not in fields:
fields.append(f)
def _add_all_info_fields(fields, headers):
for k in headers.infos:
f = 'variants/' + k
if f not in fields:
fields.append(f)
def _add_all_filter_fields(fields, headers):
fields.append('variants/FILTER_PASS')
for k in headers.filters:
f = 'variants/FILTER_' + k
if f not in fields:
fields.append(f)
def _add_all_calldata_fields(fields, headers):
# only add calldata fields if there are samples
if headers.samples:
for k in headers.formats:
f = 'calldata/' + k
if f not in fields:
fields.append(f)
def _normalize_fields(fields, headers, samples):
# setup normalized fields
normed_fields = list()
# special case, single field specification
if isinstance(fields, str):
fields = [fields]
for f in fields:
# special cases: be lenient about how to specify
if f in ['*', 'kitchen sink']:
_add_all_fields(normed_fields, headers, samples)
elif f in ['variants', 'variants*', 'variants/*']:
_add_all_variants_fields(normed_fields, headers)
elif f in ['calldata', 'calldata*', 'calldata/*'] and len(samples) > 0:
_add_all_calldata_fields(normed_fields, headers)
elif f in ['INFO', 'INFO*', 'INFO/*', 'variants/INFO', 'variants/INFO*', 'variants/INFO/*']:
_add_all_info_fields(normed_fields, headers)
elif f in ['FILTER', 'FILTER*', 'FILTER/*', 'FILTER_*', 'variants/FILTER',
'variants/FILTER*', 'variants/FILTER/*', 'variants/FILTER_*']:
_add_all_filter_fields(normed_fields, headers)
# exact field specification
else:
# normalize field specification
f = _normalize_field_prefix(f, headers)
_check_field(f, headers)
if f.startswith('calldata/') and len(samples) == 0:
# only add calldata fields if there are samples
pass
elif f not in normed_fields:
normed_fields.append(f)
return normed_fields
default_integer_dtype = 'i4'
default_float_dtype = 'f4'
default_string_dtype = 'object'
def _normalize_type(t):
if t == 'Integer':
return np.dtype(default_integer_dtype)
elif t == 'Float':
return np.dtype(default_float_dtype)
elif t == 'String':
return np.dtype(default_string_dtype)
elif t == 'Character':
return np.dtype('S1')
elif t == 'Flag':
return np.dtype(bool)
elif isinstance(t, str) and t.startswith('genotype/'):
# custom genotype dtype
return t
elif isinstance(t, str) and t.startswith('genotype_ac/'):
# custom genotype allele counts dtype
return t
else:
return np.dtype(t)
default_types = {
'variants/CHROM': 'object',
'variants/POS': 'i4',
'variants/ID': 'object',
'variants/REF': 'object',
'variants/ALT': 'object',
'variants/QUAL': 'f4',
'variants/DP': 'i4',
'variants/AN': 'i4',
'variants/AC': 'i4',
'variants/AF': 'f4',
'variants/MQ': 'f4',
'variants/ANN': 'object',
'calldata/GT': 'genotype/i1',
'calldata/GQ': 'i1',
'calldata/HQ': 'i1',
'calldata/DP': 'i2',
'calldata/AD': 'i2',
'calldata/MQ0': 'i2',
'calldata/MQ': 'f2',
}
def _normalize_types(types, fields, headers):
# normalize user-provided types
if types is None:
types = dict()
types = {_normalize_field_prefix(f, headers): _normalize_type(t)
for f, t in types.items()}
# setup output
normed_types = dict()
for f in fields:
group, name = f.split('/')
default_type = default_types.get(f)
if default_type:
default_type = _normalize_type(default_type)
if f in types:
# user had manually specified the type
normed_types[f] = types[f]
elif group == 'variants':
if name in ['numalt', 'svlen', 'is_snp']:
# computed fields, special case
continue
elif name.startswith('FILTER_'):
normed_types[f] = np.dtype(bool)
elif name in headers.infos:
header_type = _normalize_type(headers.infos[name]['Type'])
if isinstance(default_type, np.dtype):
# check that default is compatible with header
if default_type.kind in 'ifb' and default_type.kind != header_type.kind:
# default is not compatible with header, fall back to header
t = header_type
else:
t = default_type
elif default_type:
t = default_type
else:
t = header_type
normed_types[f] = t
elif default_type:
normed_types[f] = default_type
else:
# fall back to string
normed_types[f] = _normalize_type('String')
warnings.warn('no type for field %r, assuming %s' % (f, normed_types[f]))
elif group == 'calldata':
if name in headers.formats:
header_type = _normalize_type(headers.formats[name]['Type'])
if isinstance(default_type, np.dtype):
# check that default is compatible with header
if default_type.kind in 'ifb' and default_type.kind != header_type.kind:
# default is not compatible with header, fall back to header
t = header_type
else:
t = default_type
elif default_type:
t = default_type
else:
t = header_type
normed_types[f] = t
elif default_type:
normed_types[f] = default_type
else:
# fall back to string
normed_types[f] = _normalize_type('String')
warnings.warn('no type for field %r, assuming %s' % (f, normed_types[f]))
else:
raise RuntimeError('unpected field: %r' % f)
return normed_types
default_numbers = {
'variants/CHROM': 1,
'variants/POS': 1,
'variants/ID': 1,
'variants/REF': 1,
'variants/ALT': 'A',
'variants/QUAL': 1,
'variants/DP': 1,
'variants/AN': 1,
'variants/AC': 'A',
'variants/AF': 'A',
'variants/MQ': 1,
'variants/ANN': 1,
'calldata/DP': 1,
'calldata/GT': 2,
'calldata/GQ': 1,
'calldata/HQ': 2,
'calldata/AD': 'R',
'calldata/MQ0': 1,
'calldata/MQ': 1,
}
def _normalize_number(field, n, alt_number):
if n == '.':
return 1
elif n == 'A':
return alt_number
elif n == 'R':
return alt_number + 1
elif n == 'G':
return 3
else:
try:
return int(n)
except ValueError:
warnings.warn('error parsing %r as number for field %r' % (n, field))
return 1
def _normalize_numbers(numbers, fields, headers, alt_number):
# normalize field prefixes
if numbers is None:
numbers = dict()
numbers = {_normalize_field_prefix(f, headers): n for f, n in numbers.items()}
# setup output
normed_numbers = dict()
for f in fields:
group, name = f.split('/')
if f in numbers:
normed_numbers[f] = _normalize_number(f, numbers[f], alt_number)
elif f in default_numbers:
normed_numbers[f] = _normalize_number(f, default_numbers[f], alt_number)
elif group == 'variants':
if name in ['numalt', 'svlen', 'is_snp']:
# computed fields, special case (for svlen, number depends on ALT)
continue
elif name.startswith('FILTER_'):
normed_numbers[f] = 0
elif name in headers.infos:
normed_numbers[f] = _normalize_number(f, headers.infos[name]['Number'], alt_number)
else:
# fall back to 1
normed_numbers[f] = 1
warnings.warn('no number for field %r, assuming 1' % f)
elif group == 'calldata':
if name in headers.formats:
normed_numbers[f] = _normalize_number(f, headers.formats[name]['Number'],
alt_number)
else:
# fall back to 1
normed_numbers[f] = 1
warnings.warn('no number for field %r, assuming 1' % f)
else:
raise RuntimeError('unexpected field: %r' % f)
return normed_numbers
def _normalize_fills(fills, fields, headers):
if fills is None:
fills = dict()
fills = {_normalize_field_prefix(f, headers): v
for f, v in fills.items()}
# setup output
normed_fills = dict()
for f in fields:
if f in fills:
normed_fills[f] = fills[f]
return normed_fills
def _normalize_samples(samples, headers, types):
loc_samples = np.zeros(len(headers.samples), dtype='u1')
if samples is None:
normed_samples = list(headers.samples)
loc_samples.fill(1)
else:
samples = set(samples)
normed_samples = []
for i, s in enumerate(headers.samples):
if i in samples:
normed_samples.append(s)
samples.remove(i)
loc_samples[i] = 1
elif s in samples:
normed_samples.append(s)
samples.remove(s)
loc_samples[i] = 1
if len(samples) > 0:
warnings.warn('some samples not found, will be ignored: ' +
', '.join(map(repr, sorted(samples))))
t = default_string_dtype
if types is not None:
t = types.get('samples', t)
normed_samples = np.array(normed_samples, dtype=t)
return normed_samples, loc_samples
def _iter_vcf_stream(stream, fields, types, numbers, alt_number, chunk_length, fills, region,
samples):
# read VCF headers
headers = _read_vcf_headers(stream)
# setup samples
samples, loc_samples = _normalize_samples(samples=samples, headers=headers, types=types)
# setup fields to read
if fields is None:
# choose default fields
fields = list()
_add_all_fixed_variants_fields(fields)
fields.append('variants/FILTER_PASS')
if len(samples) > 0 and 'GT' in headers.formats:
fields.append('calldata/GT')
else:
fields = _normalize_fields(fields=fields, headers=headers, samples=samples)
# setup data types
types = _normalize_types(types=types, fields=fields, headers=headers)
# setup numbers (a.k.a., arity)
numbers = _normalize_numbers(numbers=numbers, fields=fields, headers=headers,
alt_number=alt_number)
# setup fills
fills = _normalize_fills(fills=fills, fields=fields, headers=headers)
# setup chunks iterator
chunks = VCFChunkIterator(
stream, chunk_length=chunk_length, headers=headers, fields=fields, types=types,
numbers=numbers, fills=fills, region=region, loc_samples=loc_samples
)
return fields, samples, headers, chunks
# pre-compile some regular expressions
_re_filter_header = \
re.compile('##FILTER=<ID=([^,]+),Description="([^"]*)">')
_re_info_header = \
re.compile('##INFO=<ID=([^,]+),Number=([^,]+),Type=([^,]+),Description="([^"]*)">')
_re_format_header = \
re.compile('##FORMAT=<ID=([^,]+),Number=([^,]+),Type=([^,]+),Description="([^"]*)">')
VCFHeaders = namedtuple('VCFHeaders', ['headers', 'filters', 'infos', 'formats', 'samples'])
def _read_vcf_headers(stream):
# setup
headers = []
samples = None
filters = dict()
infos = dict()
formats = dict()
# read first header line
header = stream.readline()
header = text_type(header, 'utf8')
while header and header[0] == '#':
headers.append(header)
if header.startswith('##FILTER'):
match = _re_filter_header.match(header)
if match is None:
warnings.warn('invalid FILTER header: %r' % header)
else:
k, d = match.groups()
if k in filters:
warnings.warn('multiple FILTER headers for %r' % k)
filters[k] = {'ID': k, 'Description': d}
elif header.startswith('##INFO'):
match = _re_info_header.match(header)
if match is None:
warnings.warn('invalid INFO header: %r' % header)
else:
k, n, t, d = match.groups()
if k in infos:
warnings.warn('multiple INFO headers for %r' % k)
infos[k] = {'ID': k, 'Number': n, 'Type': t, 'Description': d}
elif header.startswith('##FORMAT'):
match = _re_format_header.match(header)
if match is None:
warnings.warn('invalid FORMAT header: %r' % header)
else:
k, n, t, d = match.groups()
if k in formats:
warnings.warn('multiple FORMAT headers for %r' % k)
formats[k] = {'ID': k, 'Number': n, 'Type': t, 'Description': d}
elif header.startswith('#CHROM'):
# parse out samples
samples = header.strip().split('\t')[9:]
break
# read next header line
header = stream.readline()
header = text_type(header, 'utf8')
# check if we saw the mandatory header line or not
if samples is None:
# can't warn about this, it's fatal
raise RuntimeError('VCF file is missing mandatory header line ("#CHROM...")')
return VCFHeaders(headers, filters, infos, formats, samples)
def _chunk_to_dataframe(fields, chunk):
import pandas
items = list()
for f in fields:
a = chunk[f]
group, name = f.split('/')
assert group == 'variants'
if a.dtype.kind == 'S':
# always convert strings for pandas - if U then pandas will use object dtype
a = a.astype('U')
if a.ndim == 1:
items.append((name, a))
elif a.ndim == 2:
for i in range(a.shape[1]):
items.append(('%s_%s' % (name, i + 1), a[:, i]))
else:
warnings.warn('cannot handle array %r with >2 dimensions, skipping' % name)
df = pandas.DataFrame.from_items(items)
return df
def vcf_to_dataframe(input,
fields=None,
types=None,
numbers=None,
alt_number=DEFAULT_ALT_NUMBER,
fills=None,
region=None,
tabix='tabix',
transformers=None,
buffer_size=DEFAULT_BUFFER_SIZE,
chunk_length=DEFAULT_CHUNK_LENGTH,
log=None):
"""Read data from a VCF file into a pandas DataFrame.
Parameters
----------
input : string
{input}
fields : list of strings, optional
{fields}
types : dict, optional
{types}
numbers : dict, optional
{numbers}
alt_number : int, optional
{alt_number}
fills : dict, optional
{fills}
region : string, optional
{region}
tabix : string, optional
{tabix}
transformers : list of transformer objects, optional
{transformers}
buffer_size : int, optional
{buffer_size}
chunk_length : int, optional
{chunk_length}
log : file-like, optional
{log}
Returns
-------
df : pandas.DataFrame
"""
import pandas
# samples requested?
# noinspection PyTypeChecker
_, fields = _prep_fields_param(fields)
# setup
fields, _, _, it = iter_vcf_chunks(
input=input, fields=fields, types=types, numbers=numbers, alt_number=alt_number,
buffer_size=buffer_size, chunk_length=chunk_length, fills=fills, region=region,
tabix=tabix, samples=[], transformers=transformers
)
# setup progress logging
if log is not None:
it = _chunk_iter_progress(it, log, prefix='[vcf_to_dataframe]')
# read all chunks into a list
chunks = [d[0] for d in it]
# setup output
output = None
if chunks:
# concatenate chunks
output = pandas.concat([_chunk_to_dataframe(fields, chunk)
for chunk in chunks])
return output
vcf_to_dataframe.__doc__ = vcf_to_dataframe.__doc__.format(
input=_doc_param_input,
fields=_doc_param_fields,
types=_doc_param_types,
numbers=_doc_param_numbers,
alt_number=_doc_param_alt_number,
fills=_doc_param_fills,
region=_doc_param_region,
tabix=_doc_param_tabix,
transformers=_doc_param_transformers,
buffer_size=_doc_param_buffer_size,
chunk_length=_doc_param_chunk_length,
log=_doc_param_log,
)
def vcf_to_csv(input, output,
fields=None,
types=None,
numbers=None,
alt_number=DEFAULT_ALT_NUMBER,
fills=None,
region=None,
tabix='tabix',
transformers=None,
buffer_size=DEFAULT_BUFFER_SIZE,
chunk_length=DEFAULT_CHUNK_LENGTH,
log=None,
**kwargs):
r"""Read data from a VCF file and write out to a comma-separated values (CSV) file.
Parameters
----------
input : string
{input}
output : string
{output}
fields : list of strings, optional
{fields}
types : dict, optional
{types}
numbers : dict, optional
{numbers}
alt_number : int, optional
{alt_number}
fills : dict, optional
{fills}
region : string, optional
{region}
tabix : string, optional
{tabix}
transformers : list of transformer objects, optional
{transformers}
buffer_size : int, optional
{buffer_size}
chunk_length : int, optional
{chunk_length}
log : file-like, optional
{log}
kwargs : keyword arguments
All remaining keyword arguments are passed through to pandas.DataFrame.to_csv().
E.g., to write a tab-delimited file, provide `sep='\t'`.
"""
# samples requested?
# noinspection PyTypeChecker
_, fields = _prep_fields_param(fields)
# setup
fields, _, _, it = iter_vcf_chunks(
input=input, fields=fields, types=types, numbers=numbers, alt_number=alt_number,
buffer_size=buffer_size, chunk_length=chunk_length, fills=fills, region=region, tabix=tabix,
samples=[], transformers=transformers
)
# setup progress logging
if log is not None:
it = _chunk_iter_progress(it, log, prefix='[vcf_to_csv]')
kwargs['index'] = False
for i, (chunk, _, _, _) in enumerate(it):
df = _chunk_to_dataframe(fields, chunk)
if i == 0:
kwargs['header'] = True
kwargs['mode'] = 'w'
else:
kwargs['header'] = False
kwargs['mode'] = 'a'
df.to_csv(output, **kwargs)
vcf_to_csv.__doc__ = vcf_to_csv.__doc__.format(
input=_doc_param_input,
output=_doc_param_output,
fields=_doc_param_fields,
types=_doc_param_types,
numbers=_doc_param_numbers,
alt_number=_doc_param_alt_number,
fills=_doc_param_fills,
region=_doc_param_region,
tabix=_doc_param_tabix,
transformers=_doc_param_transformers,
buffer_size=_doc_param_buffer_size,
chunk_length=_doc_param_chunk_length,
log=_doc_param_log,
)
def _chunk_to_recarray(fields, chunk):
arrays = list()
names = list()
for f in fields:
a = chunk[f]
group, name = f.split('/')
if a.ndim == 1:
arrays.append(a)
names.append(name)
elif a.ndim == 2:
for i in range(a.shape[1]):
arrays.append(a[:, i])
names.append('%s_%s' % (name, i + 1))
else:
warnings.warn('cannot handle arrays with >2 dimensions, ignoring %r' % name)
ra = np.rec.fromarrays(arrays, names=names)
return ra
def vcf_to_recarray(input,
fields=None,
types=None,
numbers=None,
alt_number=DEFAULT_ALT_NUMBER,
fills=None,
region=None,
tabix='tabix',
transformers=None,
buffer_size=DEFAULT_BUFFER_SIZE,
chunk_length=DEFAULT_CHUNK_LENGTH,
log=None):
"""Read data from a VCF file into a NumPy recarray.
Parameters
----------
input : string
{input}
fields : list of strings, optional
{fields}
types : dict, optional
{types}
numbers : dict, optional
{numbers}
alt_number : int, optional
{alt_number}
fills : dict, optional
{fills}
region : string, optional
{region}
tabix : string, optional
{tabix}
transformers : list of transformer objects, optional
{transformers}
buffer_size : int, optional
{buffer_size}
chunk_length : int, optional
{chunk_length}
log : file-like, optional
{log}
Returns
-------
ra : np.rec.array
"""
# samples requested?
# noinspection PyTypeChecker
_, fields = _prep_fields_param(fields)
# setup chunk iterator
# N.B., set samples to empty list so we don't get any calldata fields
fields, _, _, it = iter_vcf_chunks(
input=input, fields=fields, types=types, numbers=numbers, alt_number=alt_number,
buffer_size=buffer_size, chunk_length=chunk_length, fills=fills, region=region,
tabix=tabix, samples=[], transformers=transformers
)
# setup progress logging
if log is not None:
it = _chunk_iter_progress(it, log, prefix='[vcf_to_recarray]')
# read all chunks into a list
chunks = [d[0] for d in it]
# setup output
output = None
if chunks:
# concatenate chunks
output = np.concatenate([_chunk_to_recarray(fields, chunk) for chunk in chunks])
return output
vcf_to_recarray.__doc__ = vcf_to_recarray.__doc__.format(
input=_doc_param_input,
fields=_doc_param_fields,
types=_doc_param_types,
numbers=_doc_param_numbers,
alt_number=_doc_param_alt_number,
fills=_doc_param_fills,
region=_doc_param_region,
tabix=_doc_param_tabix,
transformers=_doc_param_transformers,
buffer_size=_doc_param_buffer_size,
chunk_length=_doc_param_chunk_length,
log=_doc_param_log,
)
| [
"[email protected]"
] | |
8ff270a59500d90bbb8a3db156cc23e09b9628ce | 0124528676ee3bbaec60df5d6950b408e6da37c8 | /Projects/QTPy/adafruit-circuitpython-bundle-7.x-mpy-20220601/examples/lsm303_accel_fast.py | 87d21c1b86f615c46bf8bd76cc4373c70703b763 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | land-boards/lb-boards | 8127658dc537dcfde0bb59a5018ab75c3f0087f6 | eeb98cc2003dac1924845d949f6f5bd387376568 | refs/heads/master | 2023-06-07T15:44:46.110742 | 2023-06-02T22:53:24 | 2023-06-02T22:53:24 | 4,847,305 | 10 | 12 | null | null | null | null | UTF-8 | Python | false | false | 445 | py | # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
""" Read data from the accelerometer and print it out, ASAP! """
import board
import adafruit_lsm303_accel
i2c = board.I2C() # uses board.SCL and board.SDA
sensor = adafruit_lsm303_accel.LSM303_Accel(i2c)
while True:
accel_x, accel_y, accel_z = sensor.acceleration
print("{0:10.3f} {1:10.3f} {2:10.3f}".format(accel_x, accel_y, accel_z))
| [
"[email protected]"
] | |
ef94ec0911459dc49f3392233ca8f7e4ed07ddc1 | 1dacbf90eeb384455ab84a8cf63d16e2c9680a90 | /lib/python2.7/site-packages/openopt/kernel/oologfcn.py | e9819b86d856962730889b3c6c11f8a6131dfd5e | [
"Python-2.0",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown"
] | permissive | wangyum/Anaconda | ac7229b21815dd92b0bd1c8b7ec4e85c013b8994 | 2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6 | refs/heads/master | 2022-10-21T15:14:23.464126 | 2022-10-05T12:10:31 | 2022-10-05T12:10:31 | 76,526,728 | 11 | 10 | Apache-2.0 | 2022-10-05T12:10:32 | 2016-12-15T05:26:12 | Python | UTF-8 | Python | false | false | 1,040 | py | class OpenOptException(BaseException):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
#pass
#def ooassert(cond, msg):
# assert cond, msg
def oowarn(msg):
s = oowarn.s + msg
print(s)
return s
oowarn.s = 'OpenOpt Warning: '
errSet = set()
def ooerr(msg):
s = ooerr.s + msg
if msg not in errSet:
print(s)
errSet.add(msg)
raise OpenOptException(msg)
ooerr.s = 'OpenOpt Error: '
ooerr.set = errSet
pwSet = set()
def ooPWarn(msg):
if msg in pwSet: return ''
pwSet.add(msg)
oowarn(msg)
return msg
ooPWarn.s = 'OpenOpt Warning: '
ooPWarn.set = pwSet
def ooinfo(msg):
s = ooinfo.s + msg
print(s)
return s
ooinfo.s = 'OpenOpt info: '
def oohint(msg):
s = oohint.s + msg
print(s)
return s
oohint.s = 'OpenOpt hint: '
def oodisp(msg):
print(msg)
return msg
oodisp.s = ''
def oodebugmsg(p, msg):
if p.debug:
print('OpenOpt debug msg: %s' % msg)
return msg
return ''
| [
"[email protected]"
] | |
d1a6d4762ab2b6475a8e17c25b4e44c0fe9b6611 | 6bc0a7bbbe769192ff7a7c403d2c5086be1d186c | /main.py | 570d04262295be9d63758e1cf20432c9c0e60610 | [
"MIT"
] | permissive | veryhannibal/pytorch-distributed-cifar | 5c4c2aff27b16f4c6350e7e789f2edc9c50f8111 | cc3528bb80c1bb498fbf717a30d6083ef1931fad | refs/heads/master | 2022-03-12T21:26:06.125558 | 2019-11-21T11:58:02 | 2019-11-21T11:58:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,497 | py | '''Train CIFAR10 with PyTorch.'''
from __future__ import print_function
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
import os
import time
import argparse
from models.vgg import *
from models.dpn import *
from models.lenet import *
from models.senet import *
from models.pnasnet import *
from models.densenet import *
from models.googlenet import *
from models.shufflenet import *
from models.shufflenetv2 import *
from models.resnet import *
from models.resnext import *
from models.preact_resnet import *
from models.mobilenet import *
from models.mobilenetv2 import *
# from utils import progress_bar
parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')
parser.add_argument('--lr', default=0.1, type=float, help='learning rate')
parser.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint')
parser.add_argument('--data_dir', type=str)
parser.add_argument('--batch_size', type=int, default=128)
parser.add_argument('--model', type=str)
parser.add_argument('--model_dir', type=str)
parser.add_argument('--lr_decay_step_size', type=int, default=0)
parser.add_argument('--lr_decay_factor', type=float, default=1.0)
parser.add_argument('--save_frequency', type=int, default=100)
parser.add_argument('--num_epochs', type=int)
parser.add_argument('--device_ids', nargs='+', type=int)
args = parser.parse_args()
device = 'cuda' if torch.cuda.is_available() else 'cpu'
best_acc = 0 # best test accuracy
start_epoch = 0 # start from epoch 0 or last checkpoint epoch
# Data
print('==> Preparing data..')
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
# trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)
# trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2)
trainset = torchvision.datasets.CIFAR10(root=args.data_dir, train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=args.batch_size, shuffle=True, num_workers=2)
# testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)
# testloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=2)
testset = torchvision.datasets.CIFAR10(root=args.data_dir, train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
# Model
print('==> Building model: ' + args.model)
if args.model == 'vgg16':
net = VGG('VGG16')
elif args.model == 'vgg19':
net = VGG('VGG19')
elif args.model == 'resnet18':
net = ResNet18()
elif args.model == 'resnet34':
net = ResNet34()
elif args.model == 'resnet50':
net = ResNet50()
elif args.model == 'resnet101':
net = ResNet101()
elif args.model == 'resnet152':
net = ResNet152()
# net = PreActResNet18()
elif args.model == 'googlenet':
net = GoogLeNet()
# net = DenseNet121()
# net = ResNeXt29_2x64d()
# net = MobileNet()
# net = MobileNetV2()
# net = DPN92()
# net = ShuffleNetG2()
# net = SENet18()
# net = ShuffleNetV2(1)
net = net.to(device)
if device == 'cuda':
if args.device_ids is not None:
net = torch.nn.DataParallel(net, device_ids=args.device_ids)
else:
net = torch.nn.DataParallel(net)
cudnn.benchmark = True
if args.resume:
# Load checkpoint.
print('==> Resuming from checkpoint..')
assert os.path.isdir(model_dir), 'Error: no checkpoint directory found!'
checkpoint = torch.load(model_dir + '/ckpt.t7')
net.load_state_dict(checkpoint['net'])
best_acc = checkpoint['acc']
start_epoch = checkpoint['epoch']
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=0.9, weight_decay=5e-4)
if args.lr_decay_step_size > 0:
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=args.lr_decay_step_size, gamma=args.lr_decay_factor)
# Training
def train(epoch):
lr = scheduler.get_lr()[0] if args.lr_decay_step_size > 0 else args.lr
print('\nEpoch: %d\nlr = %g' % (epoch, lr))
net.train()
train_loss = 0
correct = 0
total = 0
time_used = 0.0
for batch_idx, (inputs, targets) in enumerate(trainloader):
start = time.time()
inputs, targets = inputs.to(device), targets.to(device)
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
end = time.time()
time_used += end - start
train_loss += loss.item()
_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()
# progress_bar(batch_idx, len(trainloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'
# % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))
print('[%d/%d] Loss: %.3f | Acc: %.3f%% (%d/%d) | Throughput: %.3f (images/sec)'
% (batch_idx + 1, len(trainloader), train_loss/(batch_idx+1),
100.*correct/total, correct, total, args.batch_size/(end-start+1e-6)))
print('\n[Epoch %d] Loss: %.3f | Acc: %.3f%% (%d/%d) | Throughput: %.3f (images/sec)'
% (epoch, train_loss/(len(trainloader)),
100.*correct/total, correct, total,
args.batch_size*len(trainloader)/(time_used+1e-6)))
def test(epoch):
global best_acc
net.eval()
test_loss = 0
correct = 0
total = 0
with torch.no_grad():
for batch_idx, (inputs, targets) in enumerate(testloader):
inputs, targets = inputs.to(device), targets.to(device)
outputs = net(inputs)
loss = criterion(outputs, targets)
test_loss += loss.item()
_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()
# progress_bar(batch_idx, len(testloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'
# % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))
print('\n[Evaluation] Loss: %.3f | Acc: %.3f%% (%d/%d)'
% (test_loss/(batch_idx+1), 100.*correct/total, correct, total))
# Save checkpoint.
acc = 100.*correct/total
if (epoch == start_epoch + args.num_epochs - 1) or \
(args.save_frequency > 0 and (epoch + 1) % args.save_frequency == 0):
# if acc > best_acc:
print('\nSaving..')
state = {
'net': net.state_dict(),
'acc': acc,
'epoch': epoch,
}
if not os.path.isdir(args.model_dir):
os.makedirs(args.model_dir)
torch.save(state, args.model_dir + '/' + str(epoch) + '-ckpt.t7')
if acc > best_acc:
best_acc = acc
for epoch in range(start_epoch, start_epoch + args.num_epochs):
train(epoch)
test(epoch)
if args.lr_decay_step_size > 0:
scheduler.step()
| [
"[email protected]"
] | |
9f9628dbb17329bb8f0ea4ceb9b08d65ac60ec44 | a3c8b67b91fac686aa98fd20179f8807be3ad4c0 | /rsbroker/core/upstream.py | 1ace31aa954eabd78a040a0b49ac38183023f813 | [
"Apache-2.0"
] | permissive | land-pack/RsBroker | d0c6c8fa13cec0c057d24b9f02b20e256b199737 | d556fda09582e0540cac0eabc163a984e8fc1c44 | refs/heads/master | 2021-01-12T07:16:39.853668 | 2016-12-22T07:28:05 | 2016-12-22T07:28:05 | 76,930,656 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,322 | py | import time
import logging
import ujson
from tornado import gen
from tornado import httpclient
from tornado import httputil
from tornado import ioloop
from tornado import websocket
try:
from util.tools import Log
except ImportError:
logger = logging.getLogger(__name__)
else:
logger = Log().getLog()
APPLICATION_JSON = 'application/json'
DEFAULT_CONNECT_TIMEOUT = 30
DEFAULT_REQUEST_TIMEOUT = 30
class WebSocketClient(object):
"""Base for web socket clients.
"""
DISCONNECTED = 0
CONNECTING = 1
CONNECTED = 2
def __init__(self, io_loop=None,
connect_timeout=DEFAULT_CONNECT_TIMEOUT,
request_timeout=DEFAULT_REQUEST_TIMEOUT):
self.connect_timeout = connect_timeout
self.request_timeout = request_timeout
self._io_loop = io_loop or ioloop.IOLoop.current()
self._ws_connection = None
self._connect_status = self.DISCONNECTED
def connect(self, url):
"""Connect to the server.
:param str url: server URL.
"""
self._connect_status = self.CONNECTING
headers = httputil.HTTPHeaders({'Content-Type': APPLICATION_JSON})
request = httpclient.HTTPRequest(url=url,
connect_timeout=self.connect_timeout,
request_timeout=self.request_timeout,
headers=headers)
ws_conn = websocket.WebSocketClientConnection(self._io_loop, request)
ws_conn.connect_future.add_done_callback(self._connect_callback)
def send(self, data):
"""Send message to the server
:param str data: message.
"""
if self._ws_connection:
self._ws_connection.write_message(ujson.dumps(data))
def close(self, reason=''):
"""Close connection.
"""
if self._connect_status != self.DISCONNECTED:
self._connect_status = self.DISCONNECTED
self._ws_connection and self._ws_connection.close()
self._ws_connection = None
self.on_connection_close(reason)
def _connect_callback(self, future):
if future.exception() is None:
self._connect_status = self.CONNECTED
self._ws_connection = future.result()
self.on_connection_success()
self._read_messages()
else:
self.close(future.exception())
def is_connected(self):
return self._ws_connection is not None
@gen.coroutine
def _read_messages(self):
while True:
msg = yield self._ws_connection.read_message()
if msg is None:
self.close()
break
self.on_message(msg)
def on_message(self, msg):
"""This is called when new message is available from the server.
:param str msg: server message.
"""
pass
def on_connection_success(self):
"""This is called on successful connection ot the server.
"""
pass
def on_connection_close(self, reason):
"""This is called when server closed the connection.
"""
pass
class RTCWebSocketClient(WebSocketClient):
hb_msg = 'p' # hearbeat
message = ''
heartbeat_interval = 3
def __init__(self, io_loop=None,
connect_timeout=DEFAULT_CONNECT_TIMEOUT,
request_timeout=DEFAULT_REQUEST_TIMEOUT):
self.connect_timeout = connect_timeout
self.request_timeout = request_timeout
self._io_loop = io_loop or ioloop.IOLoop.current()
self.ws_url = None
self.auto_reconnet = False
self.last_active_time = 0
self.pending_hb = None
super(RTCWebSocketClient, self).__init__(self._io_loop,
self.connect_timeout,
self.request_timeout)
def connect(self, url, auto_reconnet=True, reconnet_interval=10):
# self.url_template = url
# self.ws_url = url % self._node_id
self.ws_url = url
self.auto_reconnet = auto_reconnet
self.reconnect_interval = reconnet_interval
super(RTCWebSocketClient, self).connect(self.ws_url)
def send(self, msg):
super(RTCWebSocketClient, self).send(msg)
self.last_active_time = time.time()
def on_message(self, msg):
self.last_active_time = time.time()
self.dispatch(msg)
def on_connection_success(self):
logger.info('Connect ...')
self.last_active_time = time.time()
self.send_heartbeat()
def on_connection_close(self, reason):
logger.warning('Connection closed reason=%s' % (reason,))
self.pending_hb and self._io_loop.remove_timeout(self.pending_hb)
self.reconnect()
def reconnect(self):
logger.info('Reconnect')
# TODO when reconnect the room server has trigger,
# TODO the url should has new param ~~
# self.ws_url = self.ws_recovery_url % self._nod_id
logger.info("Send node id [%s] to remote server" % self._node_id)
# self.ws_url = self.url_template % self._node_id
if not self.is_connected() and self.auto_reconnet:
self._io_loop.call_later(self.reconnect_interval,
super(RTCWebSocketClient, self).connect, self.ws_url)
def send_heartbeat(self):
if self.is_connected():
now = time.time()
if (now > self.last_active_time + self.heartbeat_interval):
self.last_active_time = now
self.send(self.hb_msg)
self.pending_hb = self._io_loop.call_later(self.heartbeat_interval, self.send_heartbeat)
def dispatch(self, message):
"""
You must override this method!
"""
print 'message .......[%s]' % (message,)
def main():
io_loop = ioloop.IOLoop.instance()
client = RTCWebSocketClient(io_loop)
# ws_url = 'ws://127.0.0.1:8888/ws?ip=127.0.0.1&port=9001&mode=1'
ws_url = 'ws://echo.websocket.org'
client.connect(ws_url, auto_reconnet=True, reconnet_interval=10)
try:
io_loop.start()
except KeyboardInterrupt:
client.close()
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
675b214d92c6d69d2cb94daf2533333331d29cb5 | edf6a50044827f5f24b7fab4806dc25d8887c316 | /news/migrations/0001_initial.py | aa5a3112ead155a681e1a9bdbfb815eb1a9690cf | [] | no_license | zhcxk1998/AlgYun | 4958fdf31bb9009cb6541c39f715410f569b84ff | c54b95af8a87a12848401c7088bb7748793e6b63 | refs/heads/master | 2020-03-09T04:30:35.322800 | 2018-04-08T01:33:29 | 2018-04-08T01:33:29 | 128,589,517 | 1 | 1 | null | 2018-04-08T02:40:27 | 2018-04-08T02:40:27 | null | UTF-8 | Python | false | false | 2,345 | py | # Generated by Django 2.0.3 on 2018-04-03 16:36
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='Article',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=256, verbose_name='标题')),
('slug', models.CharField(db_index=True, max_length=256, verbose_name='网址')),
('content', models.TextField(blank=True, default='', verbose_name='内容')),
('pub_date', models.DateTimeField(auto_now_add=True, verbose_name='发表时间')),
('update_time', models.DateTimeField(auto_now=True, null=True, verbose_name='更新时间')),
('published', models.BooleanField(default=True, verbose_name='正式发布')),
('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='作者')),
],
options={
'verbose_name': '教程',
'verbose_name_plural': '教程',
},
),
migrations.CreateModel(
name='Column',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=256, verbose_name='栏目名称')),
('slug', models.CharField(db_index=True, max_length=256, verbose_name='栏目网址')),
('intro', models.TextField(default='', verbose_name='栏目简介')),
],
options={
'verbose_name': '栏目',
'verbose_name_plural': '栏目',
'ordering': ['name'],
},
),
migrations.AddField(
model_name='article',
name='column',
field=models.ManyToManyField(to='news.Column', verbose_name='归属栏目'),
),
]
| [
"[email protected]"
] | |
9a04690951ef33d0a11036986d4b9e7e88d5b906 | b039d4f7da5085a4e7d7491acb7bc04f7b896f24 | /tests/network/test_fees.py | 683cd8023b40e02b3ed8189ea6bf2916bdcc9128 | [
"MIT"
] | permissive | d4le/bit | c052cfadd79c52add99b6b576d2498119168c478 | 1153162f55c2ed1b007b237d4215d80ab7db429b | refs/heads/master | 2021-01-22T20:43:57.543622 | 2017-03-16T05:15:18 | 2017-03-16T05:15:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,608 | py | from time import sleep, time
import bit
from bit.network.fees import get_fee, get_fee_cached, set_fee_cache_time
def test_set_fee_cache_time():
original = bit.network.fees.DEFAULT_CACHE_TIME
set_fee_cache_time(30)
updated = bit.network.fees.DEFAULT_CACHE_TIME
assert original != updated
assert updated == 30
set_fee_cache_time(original)
def test_get_fee():
assert get_fee(fast=True) != get_fee(fast=False)
class TestFeeCache:
def test_fast(self):
sleep(0.2)
start_time = time()
set_fee_cache_time(0)
get_fee_cached(fast=True)
initial_time = time() - start_time
start_time = time()
set_fee_cache_time(600)
get_fee_cached(fast=True)
cached_time = time() - start_time
assert initial_time > cached_time
def test_hour(self):
sleep(0.2)
start_time = time()
set_fee_cache_time(0)
get_fee_cached(fast=False)
initial_time = time() - start_time
start_time = time()
set_fee_cache_time(600)
get_fee_cached(fast=False)
cached_time = time() - start_time
assert initial_time > cached_time
def test_expires(self):
sleep(0.2)
set_fee_cache_time(0)
get_fee_cached()
start_time = time()
set_fee_cache_time(600)
get_fee_cached()
cached_time = time() - start_time
sleep(0.2)
start_time = time()
set_fee_cache_time(0.1)
get_fee_cached()
update_time = time() - start_time
assert update_time > cached_time
| [
"[email protected]"
] | |
6d9d4d609a09d4ffcab3ad82b4ed5491f6b80906 | 26cf7d2d6c3d6d83b17e304aa94d5e8b3fac323a | /autoencoder.py | a2b7ddcca50d4ad7bc09af0e2d31abe70e518764 | [] | no_license | zbn123/Autoencoder | 4ad8f48e33d9b228dceae6d919c3a5320318fc7e | 13ebeb8f15edecbdd6e362e7769b69053c1f31e0 | refs/heads/master | 2021-07-19T08:46:28.559592 | 2017-10-26T20:08:34 | 2017-10-26T20:08:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,667 | py | import tensorflow.contrib.slim as slim
import matplotlib.pyplot as plt
import cPickle as pickle
import tensorflow as tf
import numpy as np
import requests
import random
import time
import gzip
import os
batch_size = 5000
'''
Leaky RELU
'''
def lrelu(x, leak=0.2, name="lrelu"):
return tf.maximum(x, leak*x)
def encoder(x):
e_conv1 = slim.convolution(x, 32, 2, stride=2, activation_fn=tf.identity, normalizer_fn=slim.batch_norm, scope='e_conv1')
e_conv1 = lrelu(e_conv1)
print 'conv1: ', e_conv1
e_conv2 = slim.convolution(e_conv1, 64, 2, stride=2, activation_fn=tf.identity, normalizer_fn=slim.batch_norm, scope='e_conv2')
e_conv2 = lrelu(e_conv2)
print 'conv2: ', e_conv2
# convolutional layer with a leaky Relu activation
e_conv3 = slim.convolution(e_conv2, 128, 2, stride=2, activation_fn=tf.identity, normalizer_fn=slim.batch_norm, scope='e_conv3')
e_conv3 = lrelu(e_conv3)
print 'conv3: ', e_conv3
e_conv3_flat = tf.reshape(e_conv3, [batch_size, -1])
e_fc1 = slim.fully_connected(e_conv3_flat, 256, normalizer_fn=slim.batch_norm, activation_fn=tf.identity, scope='e_fc1')
e_fc1 = lrelu(e_fc1)
print 'fc1: ', e_fc1
e_fc2 = slim.fully_connected(e_fc1, 64, normalizer_fn=slim.batch_norm, activation_fn=tf.identity, scope='e_fc2')
e_fc2 = lrelu(e_fc2)
print 'fc2: ', e_fc2
e_fc3 = slim.fully_connected(e_fc2, 32, normalizer_fn=slim.batch_norm, activation_fn=tf.identity, scope='e_fc3')
e_fc3 = lrelu(e_fc3)
print 'fc3: ', e_fc3
e_fc4 = slim.fully_connected(e_fc3, 8, normalizer_fn=slim.batch_norm, activation_fn=tf.identity, scope='e_fc4')
e_fc4 = lrelu(e_fc4)
print 'fc4: ', e_fc4
return e_fc4
def decoder(x):
print
print 'x: ', x
d_fc1 = slim.fully_connected(x, 32, normalizer_fn=slim.batch_norm, activation_fn=tf.identity, scope='d_fc1')
d_fc1 = lrelu(d_fc1)
print 'd_fc1: ', d_fc1
d_fc2 = slim.fully_connected(x, 64, normalizer_fn=slim.batch_norm, activation_fn=tf.identity, scope='d_fc2')
d_fc2 = lrelu(d_fc2)
print 'd_fc2: ', d_fc2
d_fc3 = slim.fully_connected(x, 256, normalizer_fn=slim.batch_norm, activation_fn=tf.identity, scope='d_fc3')
d_fc3 = lrelu(d_fc3)
print 'd_fc3: ', d_fc3
d_fc3 = tf.reshape(d_fc3, [batch_size, 4, 4, 16])
print 'd_fc3: ', d_fc3
e_transpose_conv1 = slim.convolution2d_transpose(d_fc3, 64, 2, stride=2, normalizer_fn=slim.batch_norm, activation_fn=tf.identity, scope='e_transpose_conv1')
e_transpose_conv1 = lrelu(e_transpose_conv1)
print 'e_transpose_conv1: ', e_transpose_conv1
e_transpose_conv2 = slim.convolution2d_transpose(e_transpose_conv1, 32, 2, stride=2, normalizer_fn=slim.batch_norm, activation_fn=tf.identity, scope='e_transpose_conv2')
e_transpose_conv2 = lrelu(e_transpose_conv2)
print 'e_transpose_conv2: ', e_transpose_conv2
e_transpose_conv3 = slim.convolution2d_transpose(e_transpose_conv2, 1, 2, stride=2, normalizer_fn=slim.batch_norm, activation_fn=tf.identity, scope='e_transpose_conv3')
e_transpose_conv3 = lrelu(e_transpose_conv3)
e_transpose_conv3 = e_transpose_conv3[:,:28,:28,:]
print 'e_transpose_conv3: ', e_transpose_conv3
return e_transpose_conv3
def train(mnist_train, mnist_test):
with tf.Graph().as_default():
global_step = tf.Variable(0, trainable=False, name='global_step')
# placeholder for mnist images
images = tf.placeholder(tf.float32, [batch_size, 28, 28, 1])
# encode images to 128 dim vector
encoded = encoder(images)
# decode 128 dim vector to (28,28) dim image
decoded = decoder(encoded)
loss = tf.nn.l2_loss(images - decoded)
train_op = tf.train.AdamOptimizer(learning_rate=0.0001).minimize(loss)
# saver for the model
saver = tf.train.Saver(tf.all_variables())
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
try:
os.mkdir('images/')
except:
pass
try:
os.mkdir('checkpoint/')
except:
pass
ckpt = tf.train.get_checkpoint_state('checkpoint/')
if ckpt and ckpt.model_checkpoint_path:
try:
saver.restore(sess, ckpt.model_checkpoint_path)
print 'Model restored'
except:
print 'Could not restore model'
pass
step = 0
while True:
step += 1
# get random images from the training set
batch_images = random.sample(mnist_train, batch_size)
# send through the network
s = time.time()
_, loss_ = sess.run([train_op, loss], feed_dict={images: batch_images})
t = time.time()-s
print 'Step: ' + str(step) + ' Loss: ' + str(loss_) + ' time: ' + str(t)
if step%100 == 0:
print
print 'Saving model'
print
saver.save(sess, "checkpoint/checkpoint", global_step=global_step)
# get random images from the test set
batch_images = random.sample(mnist_test, batch_size)
# encode them using the encoder, then decode them
encode_decode = sess.run(decoded, feed_dict={images: batch_images})
# write out a few
c = 0
for real, dec in zip(batch_images, encode_decode):
dec, real = np.squeeze(dec), np.squeeze(real)
plt.imsave('images/'+str(step)+'_'+str(c)+'real.png', real)
plt.imsave('images/'+str(step)+'_'+str(c)+'dec.png', dec)
if c == 5:
break
c+=1
def main(argv=None):
# mnist data in gz format
url = 'http://deeplearning.net/data/mnist/mnist.pkl.gz'
# check if it's already downloaded
if not os.path.isfile('mnist.pkl.gz'):
print 'Downloading mnist...'
with open('mnist.pkl.gz', 'wb') as f:
r = requests.get(url)
if r.status_code == 200:
f.write(r.content)
else:
print 'Could not connect to ', url
print 'opening mnist'
f = gzip.open('mnist.pkl.gz', 'rb')
train_set, val_set, test_set = pickle.load(f)
mnist_train = []
mnist_test = []
print 'Reading mnist...'
# reshape mnist to make it easier for understanding convs
for t,l in zip(*train_set):
mnist_train.append(np.reshape(t, (28,28,1)))
for t,l in zip(*val_set):
mnist_train.append(np.reshape(t, (28,28,1)))
for t,l in zip(*test_set):
mnist_test.append(np.reshape(t, (28,28,1)))
mnist_train = np.asarray(mnist_train)
mnist_test = np.asarray(mnist_test)
train(mnist_train, mnist_test)
if __name__ == '__main__':
tf.app.run()
| [
"[email protected]"
] | |
f428294c05d4756146b1ab11828c824a50119072 | 7de167836cc8018c3504c6153236c37686621634 | /config/SSD-adam.wo-norm.wo-color-aug/train.py | a9d04637910fecfb82f9ada01947e15508285d31 | [] | no_license | Oliver-ss/Leaves_Damage | 357fd295c66bfdecec141bfe562349e7053bfe37 | 82edc050f2d6e47c5db5e52ee53bd7d1524b2043 | refs/heads/master | 2020-07-26T11:40:17.335589 | 2019-09-30T02:06:13 | 2019-09-30T02:06:13 | 208,630,996 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,446 | py | from data import *
from utils.augmentations import SSDAugmentation
from layers.modules import MultiBoxLoss
from model import build_ssd
import os
import sys
import time
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torch.nn.init as init
import torch.utils.data as data
import numpy as np
import argparse
from cycle_learning_rate import cycle_lr
from common import config
import json
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
parser = argparse.ArgumentParser(
description='Single Shot MultiBox Detector Training With Pytorch')
train_set = parser.add_mutually_exclusive_group()
parser.add_argument('--train_label', default='../../Data/Labels/label_train_new.json',
help='Train label path')
parser.add_argument('--val_label', default='../../Data/Labels/Validation-3class.json',
help='Val label path')
parser.add_argument('--resume', default=None, type=str,
help='Checkpoint state_dict file to resume training from')
parser.add_argument('--start_iter', default=0, type=int,
help='Resume training at this iter')
parser.add_argument('--num_workers', default=4, type=int,
help='Number of workers used in dataloading')
parser.add_argument('--cuda', default=True, type=str2bool,
help='Use CUDA to train model')
parser.add_argument('--visdom', default=False, type=str2bool,
help='Use visdom for loss visualization')
parser.add_argument('--save_folder', default='train_log/',
help='Directory for saving checkpoint models')
parser.add_argument('--gpu', default=0, type=int,
help='GPU device number')
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = str(args.gpu)
if torch.cuda.is_available():
if args.cuda:
torch.set_default_tensor_type('torch.cuda.FloatTensor')
if not args.cuda:
print("WARNING: It looks like you have a CUDA device, but aren't " +
"using CUDA.\nRun with --cuda for optimal training speed.")
torch.set_default_tensor_type('torch.FloatTensor')
else:
torch.set_default_tensor_type('torch.FloatTensor')
if not os.path.exists(args.save_folder):
os.mkdir(args.save_folder)
if not os.path.exists(args.save_folder + 'eval/'):
os.mkdir(args.save_folder + 'eval/')
if not os.path.exists(args.save_folder + 'model/'):
os.mkdir(args.save_folder + 'model/')
if args.visdom:
import visdom
viz = visdom.Visdom(port = 8088)
def train():
cfg = config.Damage
train_dataset = Damage_Dataset(name='train', label_root=args.train_label,
transform=SSDAugmentation(mean=config.MEANS))
val_dataset = Damage_Dataset(name='validation', label_root=args.val_label,
transform=BaseTransform(mean=config.MEANS))
ssd_net = build_ssd('train', cfg['min_dim'], config.num_classes)
net = ssd_net
#cycle_cos_lr = cycle_lr(500, cfg['peak_lr'], cfg['T_init'], cfg['T_warmup'])
if args.cuda:
net = torch.nn.DataParallel(ssd_net)
cudnn.benchmark = True
if args.resume:
print('Resuming training, loading {}...'.format(args.resume))
ssd_net.load_weights(args.resume)
else:
vgg_weights = torch.load('../../pretrained/vgg16_reducedfc.pth')
print('Loading base network...')
ssd_net.vgg.load_state_dict(vgg_weights)
if args.cuda:
net = net.cuda()
if not args.resume:
print('Initializing weights...')
# initialize newly added layers' weights with xavier method
ssd_net.extras.apply(weights_init)
ssd_net.loc.apply(weights_init)
ssd_net.conf.apply(weights_init)
#optimizer = optim.SGD(net.parameters(), lr=config.lr, momentum=config.momentum,
# weight_decay=config.weight_decay)
optimizer = optim.Adam(net.parameters(), lr=config.lr, weight_decay=config.weight_decay)
criterion = MultiBoxLoss(config.num_classes, overlap_thresh=0.5,
prior_for_matching=True, bkg_label=0,
neg_mining=True, neg_pos=3, neg_overlap=0.5,
encode_target=False, use_gpu=args.cuda)
net.train()
# loss counters
loc_loss = 0
conf_loss = 0
epoch = 0
print('Loading the train dataset...')
epoch_size = len(train_dataset) // config.batch_size
print('Training SSD on:', train_dataset.name)
print('Using the specified args:')
print(args)
step_index = 0
if args.visdom:
vis_title = os.getcwd().split('/')[-1]
vis_legend = ['Loc Loss', 'Conf Loss', 'Total Loss']
iter_plot = create_vis_plot('Iteration', 'Loss', vis_title, vis_legend)
#epoch_plot = create_vis_plot('Epoch', 'Loss', vis_title, vis_legend)
iter_val_plot = create_vis_plot('Iteration', 'Val Loss', vis_title, vis_legend)
data_loader = data.DataLoader(train_dataset, config.batch_size,
num_workers=args.num_workers,
shuffle=True, collate_fn=detection_collate,
pin_memory=True)
val_data_loader = data.DataLoader(val_dataset, config.batch_size,
num_workers=args.num_workers,shuffle=True,
collate_fn=detection_collate, pin_memory=True)
# create batch iterator
batch_iterator = iter(data_loader)
val_batch_iterator = iter(val_data_loader)
num = [0, 0, 0]
for iteration in range(args.start_iter, config.max_iter):
#if args.visdom and iteration != 0 and (iteration % epoch_size == 0):
# update_vis_plot(epoch, loc_loss, conf_loss, epoch_plot, None,
# 'append', epoch_size)
# # reset epoch loss counters
# loc_loss = 0
# conf_loss = 0
# epoch += 1
if iteration in config.lr_steps:
step_index += 1
adjust_learning_rate(optimizer, config.gamma, step_index)
# cycle lr
#for param_group in optimizer.param_groups:
# param_group['lr'] = cycle_cos_lr.get_lr(iteration)
# load train data
try:
images, targets = next(batch_iterator)
except StopIteration:
batch_iterator = iter(data_loader)
images, targets = next(batch_iterator)
# calculate the frequency of every class
for i in targets:
labels = np.array(i)[:,4]
for j in labels:
num[int(j)] += 1
if args.cuda:
images = Variable(images.cuda())
targets = [Variable(ann.cuda(), volatile=True) for ann in targets]
else:
images = Variable(images)
targets = [Variable(ann, volatile=True) for ann in targets]
# forward
t0 = time.time()
out = net(images)
# backprop
optimizer.zero_grad()
loss_l, loss_c = criterion(out, targets)
loss = loss_l + loss_c
loss.backward()
optimizer.step()
t1 = time.time()
loc_loss += loss_l.item()
conf_loss += loss_c.item()
if iteration % 10 == 0:
print('timer: %.4f sec.' % (t1 - t0))
print('iter ' + repr(iteration) + ' || Loss: %.4f ||' % (loss.item()), end=' ')
print(num)
if args.visdom:
viz.line(
X=torch.ones((1, 3)).cpu() * iteration,
Y=torch.Tensor([loss_l, loss_c, loss]).unsqueeze(0).cpu(),
win=iter_plot,
update='True' if iteration == 10 else 'append'
)
if iteration % 100 == 0 and iteration != 0:
val_loss_l, val_loss_c, val_loss = val(net, val_data_loader, criterion)
print('Val_Loss: %.4f ||' % (val_loss.item()), end=' ')
if args.visdom:
viz.line(
X=torch.ones((1, 3)).cpu() * iteration,
Y=torch.Tensor([val_loss_l, val_loss_c, val_loss]).unsqueeze(0).cpu(),
win=iter_val_plot,
update='True' if iteration == 100 else 'append'
)
#if args.visdom:
#update_vis_plot(iteration, loss_l.data[0], loss_c.data[0],
# update_vis_plot(iteration, loss_l.item(), loss_c.item(),
# iter_plot, epoch_plot, 'append')
if iteration != 0 and iteration % 1000 == 0:
print('Saving state, iter:', iteration)
torch.save(ssd_net.state_dict(), args.save_folder + 'model/'
+ repr(iteration) + '.pth')
loss_file = {'loss': val_loss.item(), 'loc_loss': val_loss_l.item(), 'conf_loss': val_loss_c.item()}
with open(os.path.join(args.save_folder, 'eval', repr(iteration)+'.json'), 'w') as f:
json.dump(loss_file, f)
torch.save(ssd_net.state_dict(),
args.save_folder + 'model/' + 'leaves' + '.pth')
def val(model, dataloader, criterion):
model.eval() # evaluation mode
loc_loss = 0
conf_loss = 0
num_img = 0
for iteration, (images, targets) in enumerate(dataloader):
num_img += 1
if args.cuda:
images = Variable(images.cuda())
targets = [Variable(ann.cuda(), volatile=True) for ann in targets]
else:
images = Variable(images)
targets = [Variable(ann, volatile=True) for ann in targets]
out = model(images)
with torch.no_grad():
loss_l, loss_c = criterion(out, targets)
loc_loss += loss_l.data
conf_loss += loss_c.data
loc_loss /= num_img
conf_loss /= num_img
loss = loc_loss + conf_loss
model.train()
return loc_loss, conf_loss, loss
def adjust_learning_rate(optimizer, gamma, step):
"""Sets the learning rate to the initial LR decayed by 10 at every
specified step
# Adapted from PyTorch Imagenet example:
# https://github.com/pytorch/examples/blob/master/imagenet/main.py
"""
lr = config.lr * (gamma ** (step))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def xavier(param):
init.xavier_uniform(param)
def weights_init(m):
if isinstance(m, nn.Conv2d):
xavier(m.weight.data)
m.bias.data.zero_()
def create_vis_plot(_xlabel, _ylabel, _title, _legend):
return viz.line(
X=torch.zeros((1,)).cpu(),
Y=torch.zeros((1, 3)).cpu(),
opts=dict(
xlabel=_xlabel,
ylabel=_ylabel,
title=_title,
legend=_legend
)
)
def update_vis_plot(iteration, loc, conf, window1, window2, update_type,
epoch_size=1):
viz.line(
X=torch.ones((1, 3)).cpu() * iteration,
Y=torch.Tensor([loc, conf, loc + conf]).unsqueeze(0).cpu() / epoch_size,
win=window1,
update=update_type
)
# initialize epoch plot on first iteration
if iteration == 0:
viz.line(
X=torch.zeros((1, 3)).cpu(),
Y=torch.Tensor([loc, conf, loc + conf]).unsqueeze(0).cpu(),
win=window2,
update=True
)
if __name__ == '__main__':
train()
| [
"[email protected]"
] | |
6c393566b9210d3e5a742abc679204096e6546fc | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03795/s630946730.py | 758e56e2caec2ce4b1f82b042b9e042537e4b2d4 | [] | 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 | 104 | py | input_num = int(input())
X = input_num * 800
Y = int(input_num / 15) * 200
result = X - Y
print(result) | [
"[email protected]"
] | |
114fc87817862cd893476714a9ddd0fcef1b5e71 | f4726db4ec192dee3709c6d474b1fb9a743e9d2f | /rllib/algorithms/mpc/abstract_solver.py | 6e9395f231c134c5549b377604bf32b20c842991 | [
"MIT"
] | permissive | SamueleMeta/optimal_is | fc32dbec2eaa1ceb24a70a0c6c7d982bd7cb2c69 | 7d8e0041825acfa003874cd1ad2aec0581f6a9e1 | refs/heads/master | 2023-03-05T23:25:22.651481 | 2021-02-13T21:30:30 | 2021-02-13T21:30:30 | 323,657,959 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,597 | py | """MPC Algorithms."""
import time
from abc import ABCMeta, abstractmethod
import numpy as np
import torch
import torch.nn as nn
from rllib.dataset.utilities import stack_list_of_tuples
from rllib.util.multiprocessing import run_parallel_returns
from rllib.util.neural_networks.utilities import repeat_along_dimension
from rllib.util.rollout import rollout_actions
from rllib.util.value_estimation import discount_sum
class MPCSolver(nn.Module, metaclass=ABCMeta):
r"""Solve the discrete time trajectory optimization controller.
..math :: u[0:H-1] = \arg \max \sum_{t=0}^{H-1} r(x0, u) + final_reward(x_H)
When called, it will return the sequence of actions that solves the problem.
Parameters
----------
dynamical_model: state transition model.
reward_model: reward model.
horizon: int.
Horizon to solve planning problem.
gamma: float, optional.
Discount factor.
scale: float, optional.
Scale of covariance matrix to sample.
num_iter: int, optional.
Number of iterations of solver method.
num_samples: int, optional.
Number of samples for shooting method.
termination_model: Callable, optional.
Termination condition.
terminal_reward: terminal reward model, optional.
warm_start: bool, optional.
Whether or not to start the optimization with a warm start.
default_action: str, optional.
Default action behavior.
num_cpu: int, optional.
Number of CPUs to run the solver.
"""
def __init__(
self,
dynamical_model,
reward_model,
horizon=25,
gamma=1.0,
num_iter=1,
num_samples=400,
termination_model=None,
scale=0.3,
terminal_reward=None,
warm_start=True,
clamp=True,
default_action="zero",
action_scale=1.0,
num_cpu=1,
*args,
**kwargs,
):
super().__init__()
self.dynamical_model = dynamical_model
self.reward_model = reward_model
self.termination_model = termination_model
assert self.dynamical_model.model_kind == "dynamics"
assert self.reward_model.model_kind == "rewards"
if self.termination_model is not None:
assert self.termination_model.model_kind == "termination"
self.horizon = horizon
self.gamma = gamma
self.num_iter = num_iter
self.num_samples = num_samples
self.terminal_reward = terminal_reward
self.warm_start = warm_start
self.default_action = default_action
self.dim_action = self.dynamical_model.dim_action[0]
self.mean = None
self._scale = scale
self.covariance = (scale ** 2) * torch.eye(self.dim_action).repeat(
self.horizon, 1, 1
)
if isinstance(action_scale, np.ndarray):
action_scale = torch.tensor(action_scale, dtype=torch.get_default_dtype())
elif not isinstance(action_scale, torch.Tensor):
action_scale = torch.full((self.dim_action,), action_scale)
if len(action_scale) < self.dim_action:
extra_dim = self.dim_action - len(action_scale)
action_scale = torch.cat((action_scale, torch.ones(extra_dim)))
self.action_scale = action_scale
self.clamp = clamp
self.num_cpu = num_cpu
def evaluate_action_sequence(self, action_sequence, state):
"""Evaluate action sequence by performing a rollout."""
trajectory = stack_list_of_tuples(
rollout_actions(
self.dynamical_model,
self.reward_model,
self.action_scale * action_sequence, # scale actions.
state,
self.termination_model,
),
dim=-2,
)
returns = discount_sum(trajectory.reward, self.gamma)
if self.terminal_reward:
terminal_reward = self.terminal_reward(trajectory.next_state[..., -1, :])
returns = returns + self.gamma ** self.horizon * terminal_reward
return returns
@abstractmethod
def get_candidate_action_sequence(self):
"""Get candidate actions."""
raise NotImplementedError
@abstractmethod
def get_best_action(self, action_sequence, returns):
"""Get best action."""
raise NotImplementedError
@abstractmethod
def update_sequence_generation(self, elite_actions):
"""Update sequence generation."""
raise NotImplementedError
def initialize_actions(self, batch_shape):
"""Initialize mean and covariance of action distribution."""
if self.warm_start and self.mean is not None:
next_mean = self.mean[1:, ..., :]
if self.default_action == "zero":
final_action = torch.zeros_like(self.mean[:1, ..., :])
elif self.default_action == "constant":
final_action = self.mean[-1:, ..., :]
elif self.default_action == "mean":
final_action = torch.mean(next_mean, dim=0, keepdim=True)
else:
raise NotImplementedError
self.mean = torch.cat((next_mean, final_action), dim=0)
else:
self.mean = torch.zeros(self.horizon, *batch_shape, self.dim_action)
self.covariance = (self._scale ** 2) * torch.eye(self.dim_action).repeat(
self.horizon, *batch_shape, 1, 1
)
def get_action_sequence_and_returns(
self, state, action_sequence, returns, process_nr=0
):
"""Get action_sequence and returns associated.
These are bundled for parallel execution.
The data inside action_sequence and returns will get modified.
"""
if self.num_cpu > 1:
# Multi-Processing inherits random state.
torch.manual_seed(int(1000 * time.time()))
action_sequence[:] = self.get_candidate_action_sequence()
returns[:] = self.evaluate_action_sequence(action_sequence, state)
def forward(self, state):
"""Return action that solves the MPC problem."""
self.dynamical_model.eval()
batch_shape = state.shape[:-1]
self.initialize_actions(batch_shape)
state = repeat_along_dimension(state, number=self.num_samples, dim=-2)
batch_actions = [
torch.randn(
(self.horizon,) + batch_shape + (self.num_samples, self.dim_action)
)
for _ in range(self.num_cpu)
]
batch_returns = [
torch.randn(batch_shape + (self.num_samples,)) for _ in range(self.num_cpu)
]
for action_, return_ in zip(batch_actions, batch_returns):
action_.share_memory_()
return_.share_memory_()
for _ in range(self.num_iter):
run_parallel_returns(
self.get_action_sequence_and_returns,
[
(state, batch_actions[rank], batch_returns[rank], rank)
for rank in range(self.num_cpu)
],
num_cpu=self.num_cpu,
)
action_sequence = torch.cat(batch_actions, dim=-2)
returns = torch.cat(batch_returns, dim=-1)
elite_actions = self.get_best_action(action_sequence, returns)
self.update_sequence_generation(elite_actions)
if self.clamp:
return self.mean.clamp(-1.0, 1.0)
return self.mean
def reset(self, warm_action=None):
"""Reset warm action."""
self.mean = warm_action
| [
"[email protected]"
] | |
c9ddc6020f6335f0c218bb5bf57f71ec81f55e3c | 62179a165ec620ba967dbc20016e890978fbff50 | /tests/torch/pruning/test_onnx_export.py | 841d1b4a7fc6f0b959dc57c9259844df873540c2 | [
"Apache-2.0"
] | permissive | openvinotoolkit/nncf | 91fcf153a96f85da166aacb7a70ca4941e4ba4a4 | c027c8b43c4865d46b8de01d8350dd338ec5a874 | refs/heads/develop | 2023-08-24T11:25:05.704499 | 2023-08-23T14:44:05 | 2023-08-23T14:44:05 | 263,687,600 | 558 | 157 | Apache-2.0 | 2023-09-14T17:06:41 | 2020-05-13T16:41:05 | Python | UTF-8 | Python | false | false | 6,169 | py | # Copyright (c) 2023 Intel Corporation
# 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 pytest
from tests.torch.helpers import load_exported_onnx_version
from tests.torch.pruning.helpers import BigPruningTestModel
from tests.torch.pruning.helpers import DiffConvsModel
from tests.torch.pruning.helpers import GroupNormModel
from tests.torch.pruning.helpers import PruningTestModelConcat
from tests.torch.pruning.helpers import PruningTestModelEltwise
from tests.torch.pruning.helpers import get_basic_pruning_config
pytestmark = pytest.mark.skip(reason="Export as actually deleting filters from the model is currently disabled.")
def find_value_by_name_in_list(obj_list, name):
for obj in obj_list:
if obj.name == name:
return obj
return None
def check_bias_and_weight_shape(node_name, onnx_model_proto, weight_shape, bias_shape):
node_weight = find_value_by_name_in_list(onnx_model_proto.graph.initializer, node_name + ".weight")
node_bias = find_value_by_name_in_list(onnx_model_proto.graph.initializer, node_name + ".bias")
assert node_weight.dims == weight_shape
assert node_bias.dims == bias_shape
def test_pruning_export_simple_model(tmp_path):
model = BigPruningTestModel()
nncf_config = get_basic_pruning_config(input_sample_size=[1, 1, 8, 8])
nncf_config["compression"]["pruning_init"] = 0.5
nncf_config["compression"]["algorithm"] = "filter_pruning"
onnx_model_proto = load_exported_onnx_version(nncf_config, model, path_to_storage_dir=tmp_path)
# Check that conv2 + BN were pruned by output filters
# WARNING: starting from at least torch 1.7.0, torch.onnx.export will fuses BN into previous
# convs if torch.onnx.export is done with `training=False`, so this test might fail.
check_bias_and_weight_shape("nncf_module.conv2", onnx_model_proto, [16, 16, 3, 3], [16])
check_bias_and_weight_shape("nncf_module.bn", onnx_model_proto, [16], [16])
# Check that up was pruned by input filters
check_bias_and_weight_shape("nncf_module.up", onnx_model_proto, [16, 32, 3, 3], [32])
# Check that conv3 was pruned by input filters
check_bias_and_weight_shape("nncf_module.conv3", onnx_model_proto, [1, 32, 5, 5], [1])
@pytest.mark.parametrize(
("prune_first", "ref_shapes"),
[
(False, [[[16, 1, 2, 2], [16]], [[16, 16, 2, 2], [16]], [[16, 16, 2, 2], [16]], [[16, 32, 3, 3], [16]]]),
(True, [[[8, 1, 2, 2], [8]], [[16, 8, 2, 2], [16]], [[16, 8, 2, 2], [16]], [[16, 32, 3, 3], [16]]]),
],
)
def test_pruning_export_concat_model(tmp_path, prune_first, ref_shapes):
model = PruningTestModelConcat()
nncf_config = get_basic_pruning_config(input_sample_size=[1, 1, 8, 8])
nncf_config["compression"]["algorithm"] = "filter_pruning"
nncf_config["compression"]["params"]["prune_first_conv"] = prune_first
nncf_config["compression"]["pruning_init"] = 0.5
onnx_model_proto = load_exported_onnx_version(nncf_config, model, path_to_storage_dir=tmp_path)
for i in range(1, 5):
conv_name = "nncf_module.conv{}".format(i)
check_bias_and_weight_shape(conv_name, onnx_model_proto, *ref_shapes[i - 1])
@pytest.mark.parametrize(
("prune_first", "ref_shapes"),
[
(False, [[[16, 1, 2, 2], [16]], [[16, 16, 2, 2], [16]], [[16, 16, 2, 2], [16]], [[16, 16, 3, 3], [16]]]),
(True, [[[8, 1, 2, 2], [8]], [[16, 8, 2, 2], [16]], [[16, 8, 2, 2], [16]], [[16, 16, 3, 3], [16]]]),
],
)
def test_pruning_export_eltwise_model(tmp_path, prune_first, ref_shapes):
model = PruningTestModelEltwise()
nncf_config = get_basic_pruning_config(input_sample_size=[1, 1, 8, 8])
nncf_config["compression"]["algorithm"] = "filter_pruning"
nncf_config["compression"]["params"]["prune_first_conv"] = prune_first
nncf_config["compression"]["pruning_init"] = 0.5
onnx_model_proto = load_exported_onnx_version(nncf_config, model, path_to_storage_dir=tmp_path)
for i in range(1, 5):
conv_name = "nncf_module.conv{}".format(i)
check_bias_and_weight_shape(conv_name, onnx_model_proto, *ref_shapes[i - 1])
@pytest.mark.parametrize(
("prune_first", "ref_shapes"),
[
(False, [[[32, 1, 2, 2], [32]], [[32, 1, 1, 1], [32]], [[32, 32, 3, 3], [32]], [[16, 4, 1, 1], [16]]]),
(True, [[[16, 1, 2, 2], [16]], [[16, 1, 1, 1], [16]], [[32, 16, 3, 3], [32]], [[16, 4, 1, 1], [16]]]),
],
)
def test_pruning_export_diffconvs_model(tmp_path, prune_first, ref_shapes):
model = DiffConvsModel()
nncf_config = get_basic_pruning_config(input_sample_size=[1, 1, 8, 8])
nncf_config["compression"]["algorithm"] = "filter_pruning"
nncf_config["compression"]["params"]["prune_first_conv"] = prune_first
nncf_config["compression"]["pruning_init"] = 0.5
onnx_model_proto = load_exported_onnx_version(nncf_config, model, path_to_storage_dir=tmp_path)
for i in range(1, 5):
conv_name = "nncf_module.conv{}".format(i)
check_bias_and_weight_shape(conv_name, onnx_model_proto, *ref_shapes[i - 1])
def test_pruning_export_groupnorm_model(tmp_path):
model = GroupNormModel()
nncf_config = get_basic_pruning_config(input_sample_size=[1, 1, 8, 8])
nncf_config["compression"]["algorithm"] = "filter_pruning"
nncf_config["compression"]["params"]["prune_first_conv"] = True
nncf_config["compression"]["pruning_init"] = 0.5
onnx_model_proto = load_exported_onnx_version(nncf_config, model, path_to_storage_dir=tmp_path)
check_bias_and_weight_shape("nncf_module.conv1", onnx_model_proto, [8, 1, 1, 1], [8])
check_bias_and_weight_shape("nncf_module.conv2", onnx_model_proto, [16, 8, 1, 1], [16])
| [
"[email protected]"
] | |
dc7b599f8daa973d59789d42ded36ded640ad411 | be0f3dfbaa2fa3d8bbe59229aef3212d032e7dd1 | /Gauss_v45r10p1/Gen/DecFiles/options/16165060.py | 6c65b7ec1a29a4f35185a3b5334145f51a786eb9 | [] | 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 | 1,597 | py | # file /home/hep/ss4314/cmtuser/Gauss_v45r10p1/Gen/DecFiles/options/16165060.py generated: Wed, 25 Jan 2017 15:25:15
#
# Event Type: 16165060
#
# ASCII decay Descriptor: [ Xi_bc+ -> (D+ -> K- pi+ pi+) p+ K- ]cc
#
from Configurables import Generation
Generation().EventType = 16165060
Generation().SampleGenerationTool = "Special"
from Configurables import Special
Generation().addTool( Special )
Generation().Special.ProductionTool = "GenXiccProduction"
Generation().PileUpTool = "FixedLuminosityForRareProcess"
from Configurables import GenXiccProduction
Generation().Special.addTool( GenXiccProduction )
Generation().Special.GenXiccProduction.BaryonState = "Xi_bc+"
Generation().Special.GenXiccProduction.Commands = ["mixevnt imix 1", "loggrade ivegasopen 0", "loggrade igrade 1", "vegasbin nvbin 300", "counter xmaxwgt 5000000", "confine pscutmin 0.0", "confine pscutmax 7.0"]
from Configurables import ToolSvc
from Configurables import EvtGenDecay
ToolSvc().addTool( EvtGenDecay )
ToolSvc().EvtGenDecay.UserDecayFile = "$DECFILESROOT/dkfiles/Xibc_DpK,Kpipi=DecProdCut,m=6.9GeV,t=0.4ps.dec"
Generation().Special.CutTool = "XiccDaughtersInLHCb"
from Configurables import XiccDaughtersInLHCb
Generation().Special.addTool( XiccDaughtersInLHCb )
Generation().Special.XiccDaughtersInLHCb.BaryonState = Generation().Special.GenXiccProduction.BaryonState
from Configurables import LHCb__ParticlePropertySvc
LHCb__ParticlePropertySvc().Particles = [ " Xi_bc+ 532 5242 1.0 6.90000000 0.400000e-12 Xi_bc+ 5242 0.00000000", " Xi_bc~- 533 -5242 -1.0 6.90000000 0.400000e-12 anti-Xi_bc- -5242 0.00000000" ]
| [
"[email protected]"
] | |
763f3843193e373ffd0a2229f3233e4ebeb3d73f | 3d14a2263e7547f9d3b463a35e4b25e3abb67306 | /ccal/get_vcf_info_ann.py | 4e76f65f9a5dda963ac65d084997f3fcb9b8b31f | [
"MIT"
] | permissive | alex-wenzel/ccal | ec91d214cd169913909de67a8592b9ce4a82af3f | 74dfc604d93e6ce9e12f34a828b601618df51faa | refs/heads/master | 2020-04-17T02:45:50.976156 | 2019-04-22T01:14:24 | 2019-04-22T01:14:24 | 166,151,841 | 0 | 0 | MIT | 2019-01-17T03:10:39 | 2019-01-17T03:10:38 | null | UTF-8 | Python | false | false | 352 | py | from .get_vcf_info import get_vcf_info
from .VCF_ANN_FIELDS import VCF_ANN_FIELDS
def get_vcf_info_ann(info, field, n_ann=None):
ann = get_vcf_info(info, "ANN")
if ann:
field_index = VCF_ANN_FIELDS.index(field)
return [ann_.split(sep="|")[field_index] for ann_ in ann.split(sep=",")[:n_ann]]
else:
return []
| [
"[email protected]"
] | |
7675618bd38f2113e3e7c2c01134a738a88bf0fd | 11b9e95ce3d73e62ac07893a36690cb3a0d9041b | /NeuralNetwork/随机森林(非神经网络)/RandomForest2.py | 9bc8c512e9be0109525f67ca4ab60c14b7a1ff62 | [] | no_license | zhangjinzhi/SimpleTools | 3fdd2005cb8cf52e8e75d8ec283090a628cebc59 | be9e766d2e22124ce41bec254664b12fdfacaa4b | refs/heads/master | 2020-12-30T11:51:27.116851 | 2018-01-30T09:47:01 | 2018-01-30T09:47:01 | 91,527,509 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 716 | py | # coding=utf-8
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import numpy as np
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['is_train'] = np.random.uniform(0, 1, len(df)) <= .75
df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)
df.head()
train, test = df[df['is_train']==True], df[df['is_train']==False]
features = df.columns[:4]
clf = RandomForestClassifier(n_jobs=2)
y, _ = pd.factorize(train['species'])
clf.fit(train[features], y)
preds = iris.target_names[clf.predict(test[features])]
pd.crosstab(test['species'], preds, rownames=['actual'], colnames=['preds']) | [
"[email protected]"
] | |
f03019f06080a632cd818000dfeb75a5995b4219 | fd877cb919622d6a4efa305fb9eaec8a31e8dd37 | /scripts/ua/rule13.py | 45196c0db7db6b6593bc008e7f51e87aa635ae06 | [
"MIT"
] | permissive | NCiobo/iem | 37df9bc466ffcbe4f6b1f9c29c6b5266559f200c | 75da5e681b073c6047f5a2fb76721eaa0964c2ed | refs/heads/master | 2021-01-23T09:39:33.090955 | 2017-09-05T16:34:12 | 2017-09-05T16:34:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,671 | py | '''
Compute the difference between the 12 UTC 850 hPa temp and afternoon high
'''
from pyiem.datatypes import temperature
import psycopg2
import datetime
ASOS = psycopg2.connect(database='asos', host='iemdb', user='nobody')
acursor = ASOS.cursor()
POSTGIS = psycopg2.connect(database='postgis', host='iemdb', user='nobody')
pcursor = POSTGIS.cursor()
data = [0]*12
for i in range(12):
data[i] = []
pcursor.execute("""
select valid, tmpc from raob_profile p JOIN raob_flights f on
(p.fid = f.fid) where f.station in ('KOAX', 'KOVN', 'KOMA') and
p.pressure = 850 and extract(hour from valid at time zone 'UTC') = 12
and tmpc > -40
ORDER by valid ASC
""")
for row in pcursor:
valid = row[0]
t850 = temperature(row[1], 'C')
acursor.execute("""SELECT max(tmpf) from t"""+ str(valid.year) +"""
WHERE station = 'OMA' and valid BETWEEN %s and %s
""", (valid, valid + datetime.timedelta(hours=12)))
row2 = acursor.fetchone()
if row2[0] is None:
continue
high = temperature(row2[0], 'F')
print valid.year, valid.month, high.value('C') - t850.value('C')
data[valid.month-1].append( high.value('C') - t850.value('C') )
import matplotlib.pyplot as plt
(fig, ax) = plt.subplots(1,1)
ax.plot([1,12], [13,13], '-', lw=1.5, color='green', zorder=1)
ax.boxplot(data)
ax.set_title("1960-2013 Omaha Daytime High Temp vs 12 UTC 850 hPa Temp")
ax.set_ylabel(r"Temperature Difference $^\circ$C")
ax.set_xticks(range(1,13))
ax.set_ylim(-20,25)
ax.set_xticklabels(("Jan", 'Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec') )
ax.grid(axis='y')
fig.savefig('test.ps')
import iemplot
iemplot.makefeature('test') | [
"[email protected]"
] | |
6d23619ee3008348e0c51778e10152aa5b555140 | 099172fda019272760aebaa7795def519907e152 | /com.ibm.streamsx.topology/opt/python/packages/streamsx/topology/schema.py | 480e8799768afddfd82f92c6a4705a006a30baf0 | [
"Apache-2.0"
] | permissive | rrea/streamsx.topology | 58ffd48745e83cd6d054d50405e9f7bbbe73876d | d8828ccf3e32cb8a7629f9e325fc14f565cf913e | refs/heads/master | 2020-12-11T07:16:53.701724 | 2016-08-12T19:36:42 | 2016-08-12T19:36:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,601 | py | import enum
class StreamSchema(object) :
"""SPL stream schema."""
def __init__(self, schema):
self.__schema=schema.strip()
def schema(self):
return self.__schema;
def spl_json(self):
_splj = {}
_splj["type"] = 'spltype'
_splj["value"] = self.schema()
return _splj
def extend(self, schema):
"""
Extend a schema by another
"""
base = self.schema()
extends = schema.schema()
new_schema = base[:-1] + ',' + extends[6:]
return StreamSchema(new_schema)
# XML = StreamSchema("tuple<xml document>")
@enum.unique
class CommonSchema(enum.Enum):
"""
Common stream schemas for interoperability within Streams applications.
Python - Stream constains Python objects
Json - Stream contains JSON objects. Streams with schema Json can be published and subscribed between Streams applications implemented in different languages.
String - Stream contains strings. Streams with schema String can be published and subscribed between Streams applications implemented in different languages.
Binary - Stream contains binary tuples. NOT YET SUPPORTED IN Python.
"""
Python = StreamSchema("tuple<blob __spl_po>")
Json = StreamSchema("tuple<rstring jsonString>")
String = StreamSchema("tuple<rstring string>")
Binary = StreamSchema("tuple<blob binary>")
def schema(self):
return self.value.schema();
def spl_json(self):
return self.value.spl_json()
def extend(self, schema):
return self.value.extend(schema)
| [
"[email protected]"
] | |
c3dbd2c439c3758ad3b7f4b9ce1618b504c41c15 | b92eee41d665314bc42043d1ff46c608af5ffdfd | /sesion_2/prueba.2.py | aeeadbfa75b82afe081d82967acbd794d76c7081 | [] | no_license | badillosoft/python-economics | 40efe8326558a8fb93f84fdbd2137428844ee5f3 | 82af43c7a47297ce186dc0e23e30620d46e6693a | refs/heads/master | 2021-01-11T18:55:15.762752 | 2017-05-09T01:15:59 | 2017-05-09T01:15:59 | 79,656,798 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 162 | py | # Importación unitaria (por elemento)
from geg import suma, suma2
# from geg import *
print suma([1, 3, 5, 7, 9])
print suma([1, 76, 201, 76])
print suma([5])
| [
"[email protected]"
] | |
07522c3ec7506ead2e1af745eda523dcd66be75d | 7d027557cee0ad5ae783480fe79c1b3d11c4eccb | /backend/delivery_order/migrations/0001_initial.py | 0f19ff998f55d6c8023cdddbe7fe661b124db324 | [] | no_license | crowdbotics-apps/lol-21119 | b284e53d4b7ebfa9e4c068807aff813f53871c1e | 78965517edf60545b646e90e77a63aeb7c4515af | refs/heads/master | 2022-12-24T13:05:52.179667 | 2020-10-05T17:54:53 | 2020-10-05T17:54:53 | 301,492,013 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,307 | py | # Generated by Django 2.2.16 on 2020-10-05 17:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
("menu", "0001_initial"),
("delivery_user_profile", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="Bill",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("total_amount", models.FloatField()),
("timestamp_created", models.DateTimeField(auto_now_add=True)),
(
"contact_info",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="bill_contact_info",
to="delivery_user_profile.ContactInfo",
),
),
(
"profile",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="bill_profile",
to="delivery_user_profile.Profile",
),
),
],
),
migrations.CreateModel(
name="PaymentMethod",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=255)),
("detail", models.TextField()),
],
),
migrations.CreateModel(
name="Order",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("quantity", models.IntegerField()),
("total_price", models.FloatField()),
("status", models.CharField(max_length=20)),
("notes", models.TextField()),
("timestamp_created", models.DateTimeField(auto_now_add=True)),
(
"bill",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="order_bill",
to="delivery_order.Bill",
),
),
(
"item_variant",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="order_item_variant",
to="menu.ItemVariant",
),
),
(
"payment_method",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="order_payment_method",
to="delivery_order.PaymentMethod",
),
),
(
"profile",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="order_profile",
to="delivery_user_profile.Profile",
),
),
],
),
]
| [
"[email protected]"
] | |
d199b63471d48fe41ba0034f9a18d32ec3530fc2 | 0dfdeec83f0b4acd804b9a52212426e9045edfd2 | /v13/addons/cristo_concern/models/dashboard.py | a62adf086f3cf39937c6a7ab9fea53b4303af462 | [] | no_license | cokotracy/Cristo | 2c89d6789a901ec2f1e2f0eca7563d1cebee40cb | aea45d82d9b822c0ffe6275cfcce3eeb5283a152 | refs/heads/main | 2023-08-30T05:01:02.913064 | 2021-07-06T10:09:29 | 2021-07-06T10:09:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,787 | py | # -*- coding: utf-8 -*-
from odoo import models, fields, api, _
class Member(models.Model):
_inherit = 'res.member'
@api.model
def get_user_member_details(self):
res = super(Member, self).get_user_member_details()
# Navigation
con_action_id = self.env.ref("cristo_concern.action_concern").id
con_menu_id = self.env.ref("cristo_concern.cristo_concern_main_menu").id
res[0].update({'con_action_id': con_action_id, 'con_menu_id': con_menu_id, })
if self.user_has_groups('cristo_concern.group_concern_user') or self.user_has_groups('cristo.group_role_cristo_bsa_super_admin'):
total_concern = self.env['cristo.concern'].search_count([])
if self.user_has_groups('cristo.group_role_cristo_religious_institute_admin'):
total_cal = self.env['cristo.concern'].search_count([('user_id','=',self.env.user.id),('institute_id','=',self.env.user.institute_id.id)])
elif self.user_has_groups('cristo.group_role_cristo_religious_province'):
total_cal = self.env['cristo.concern'].search_count([('user_id','=',self.env.user.id),('rel_province_id','=',self.env.user.rel_province_id.id)])
elif self.user_has_groups('cristo.group_role_cristo_religious_house'):
total_cal = self.env['cristo.concern'].search_count([('user_id','=',self.env.user.id),('community_id','=',self.env.user.community_id.id)])
elif self.user_has_groups('cristo.group_role_cristo_apostolic_institution'):
total_cal = self.env['cristo.concern'].search_count([('user_id','=',self.env.user.id),('institution_id','=',self.env.user.institution_id.id)])
res[0].update({'concern':1,'total_concern':total_concern})
return res | [
"[email protected]"
] | |
43e00d123f74fceb0d9123050968b8d5a1ecd98c | a86293a2033c06410aa8ed19bcbce8ca55ea3c55 | /src/client_libraries/python/microsoft/dynamics/customerinsights/api/models/workflow_refresh_schedule_py3.py | 686a18f736ebacb397d4da542efc3475aa595443 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | ramotheonly/Dynamics365-CustomerInsights-Client-Libraries | a3ca28aa78d2b5509e65d9895ff4a0d42d05f611 | e00632f7972717b03e0fb1a9e2667e8f9444a0fe | refs/heads/main | 2023-08-02T08:09:04.063030 | 2021-09-28T22:42:15 | 2021-09-28T22:42:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,286 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class WorkflowRefreshSchedule(Model):
"""Represents a DAG refresh schedule.
Variables are only populated by the server, and will be ignored when
sending a request.
:param operation_type: Possible values include: 'none', 'ingestion',
'derivedEntity', 'dataPreparation', 'map', 'match', 'merge',
'profileStore', 'search', 'activity', 'attributeMeasures',
'entityMeasures', 'measures', 'segmentation', 'enrichment',
'intelligence', 'aiBuilder', 'insights', 'export', 'modelManagement',
'relationship', 'roleAssignment', 'analysis', 'all'
:type operation_type: str or
~microsoft.dynamics.customerinsights.api.models.enum
:param sub_type: Possible values include: 'templatedMeasures',
'createAnalysisModel', 'linkAnalysisModel'
:type sub_type: str or
~microsoft.dynamics.customerinsights.api.models.enum
:param identifiers: Gets the identifiers of the schedule
:type identifiers: list[str]
:param job_type: Possible values include: 'full', 'incremental'
:type job_type: str or
~microsoft.dynamics.customerinsights.api.models.enum
:ivar is_active: Gets a value indicating whether the schedule is active.
:vartype is_active: bool
:ivar timezone_id: Gets the ID of the timezone
:vartype timezone_id: str
:ivar cron_schedules: Gets the schedule in CRON format
:vartype cron_schedules: list[str]
:ivar schedule_id: Gets the ID of the schedule
:vartype schedule_id: str
:ivar instance_id: Gets the Customer Insights instance id associated with
this object.
:vartype instance_id: str
"""
_validation = {
'is_active': {'readonly': True},
'timezone_id': {'readonly': True},
'cron_schedules': {'readonly': True},
'schedule_id': {'readonly': True},
'instance_id': {'readonly': True},
}
_attribute_map = {
'operation_type': {'key': 'operationType', 'type': 'str'},
'sub_type': {'key': 'subType', 'type': 'str'},
'identifiers': {'key': 'identifiers', 'type': '[str]'},
'job_type': {'key': 'jobType', 'type': 'str'},
'is_active': {'key': 'isActive', 'type': 'bool'},
'timezone_id': {'key': 'timezoneId', 'type': 'str'},
'cron_schedules': {'key': 'cronSchedules', 'type': '[str]'},
'schedule_id': {'key': 'scheduleId', 'type': 'str'},
'instance_id': {'key': 'instanceId', 'type': 'str'},
}
def __init__(self, *, operation_type=None, sub_type=None, identifiers=None, job_type=None, **kwargs) -> None:
super(WorkflowRefreshSchedule, self).__init__(**kwargs)
self.operation_type = operation_type
self.sub_type = sub_type
self.identifiers = identifiers
self.job_type = job_type
self.is_active = None
self.timezone_id = None
self.cron_schedules = None
self.schedule_id = None
self.instance_id = None
| [
"[email protected]"
] | |
4b20687780fb0fdf9ee2aa84da2e4f050fe6925d | 09e57dd1374713f06b70d7b37a580130d9bbab0d | /data/cirq_new/cirq_program/startCirq_pragma17.py | 3146b2f412bfb79c7789014ace702fe920a73cb6 | [
"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 | 2,262 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=8
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
class Opty(cirq.PointOptimizer):
def optimization_at(
self,
circuit: 'cirq.Circuit',
index: int,
op: 'cirq.Operation'
) -> Optional[cirq.PointOptimizationSummary]:
if (isinstance(op, cirq.ops.GateOperation) and isinstance(op.gate, cirq.CZPowGate)):
return cirq.PointOptimizationSummary(
clear_span=1,
clear_qubits=op.qubits,
new_operations=[
cirq.CZ(*op.qubits),
cirq.X.on_each(*op.qubits),
cirq.X.on_each(*op.qubits),
]
)
#thatsNoCode
def make_circuit(n: int, input_qubit):
c = cirq.Circuit() # circuit begin
c.append(cirq.H.on(input_qubit[0])) # number=1
c.append(cirq.H.on(input_qubit[1])) # number=2
c.append(cirq.rx(1.6147786239451536).on(input_qubit[3])) # number=5
c.append(cirq.H.on(input_qubit[2])) # number=3
c.append(cirq.H.on(input_qubit[3])) # number=4
c.append(cirq.CNOT.on(input_qubit[2],input_qubit[0])) # number=6
c.append(cirq.CNOT.on(input_qubit[2],input_qubit[0])) # number=7
# circuit end
c.append(cirq.measure(*input_qubit, key='result'))
return c
def bitstring(bits):
return ''.join(str(int(b)) for b in bits)
if __name__ == '__main__':
qubit_count = 4
input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
circuit = make_circuit(qubit_count,input_qubits)
circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')
circuit_sample_count =2000
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=circuit_sample_count)
frequencies = result.histogram(key='result', fold_func=bitstring)
writefile = open("../data/startCirq_pragma17.csv","w+")
print(format(frequencies),file=writefile)
print("results end", file=writefile)
print(circuit.__len__(), file=writefile)
print(circuit,file=writefile)
writefile.close() | [
"[email protected]"
] | |
155563938f93e28b814ded6a968be8956f270d22 | 1287bbb696e240dd0b92d56d4fdf4246370f3e14 | /numpy-demo.py | fd2619fdc2e82feac4224f8733d84b6b6ec43540 | [] | no_license | omerfarukcelenk/PythonCalismalari | ed0c204084860fddcb892e6edad84fdbc1ed38ec | 28da12d7d042ec306f064fb1cc3a1a026cb57b74 | refs/heads/main | 2023-04-13T18:23:15.270020 | 2021-04-26T21:06:21 | 2021-04-26T21:06:21 | 361,893,918 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,151 | py | import numpy as np
# 1- (10,15,30,45,60) değerlerine sahip numpy dizisi oluşturunuz.
result = np.array([10,15,30,45,60])
# 2- (5-15) arasındaki sayılarla numpy dizisi oluşturunuz.
result = np.arange(5,15)
# 3- (50-100) arasında 5'er 5'er artarak numpy dizisi oluşturunuz.
result = np.arange(50,100,5)
# 4- 10 elemanlı sıfırlardan oluşan bir dizi oluşturunuz.
result = np.zeros(10)
# 5- 10 elemanlı birlerden oluşan bir dizi oluşturunuz.
result = np.ones(10)
# 6- (0-100) arasında eşit aralıklı 5 sayı üretin.
result = np.linspace(0,100,5)
# 7- (10-30) arasında rastgele 5 tane tamsayı üretin.
result = np.random.randint(10,30,5)
# 8- [-1 ile 1] arasında 10 adet sayı üretin.
result = np.random.randn(10)
# 9- (3x5) boyutlarında (10-50) arasında rastgele bir matris oluşturunuz.
# result = np.random.randint(10,50,15).reshape(3,5)
# 10- Üretilen matrisin satır ve sütun sayıları toplamlarını hesaplayınız ?
matris = np.random.randint(-50,50,15).reshape(3,5)
# rowTotal = matris.sum(axis = 1)
# colTotal = matris.sum(axis = 0)
print(matris)
# print(rowTotal)
# print(colTotal)
# 11- Üretilen matrisin en büyük, en küçük ve ortalaması nedir ?
result = matris.max()
result = matris.min()
result = matris.mean()
# 12- Üretilen matrisin en büyük değerinin indeksi kaçtır ?
result = matris.argmax()
result = matris.argmin()
# 13- (10-20) arasındaki sayıları içeren dizinin ilk 3 elemanını seçiniz.
arr = np.arange(10,20)
print(arr)
result = arr[0:3]
# 14- Üretilen dizinin elemanlarını tersten yazdırın.
result = arr[::-1]
# 15- Üretilen matrisin ilk satırını seçiniz.
result = matris[0]
# 16- Üretilen matrisin 2.satır 3.sütundaki elemanı hangisidir ?
result = matris[1,2]
# 17- Üretilen matrisin tüm satırlardaki ilk elemanı seçiniz.
result = matris[:,0]
# 18- Üretilen matrisin her bir elemanının karesini alınız.
result = matris ** 2
# 19- Üretilen matris elemanlarının hangisi pozitif çift sayıdır ?
# Aralığı (-50,+50) arasında yapınız.
ciftler = matris[matris % 2 == 0]
result = ciftler[ciftler>0]
print(result) | [
"[email protected]"
] | |
5f1384b0ccaccf589e497ee288792f747e49c667 | e2860eb874db045fb8d0279566a935af907e5bdf | /keras01/keras24_cancer_binary.py | 224913ac725bca03a09cec370f03a7af20a3ef3f | [] | no_license | MinseokCHAE/Bitcamp2_new | dda7990907cb136c2e709a345eec634dfdb6ac02 | 849adb5a330b621f1c681f0b5e92005d1281a44d | refs/heads/main | 2023-08-31T03:28:18.068561 | 2021-10-05T00:48:52 | 2021-10-05T00:48:52 | 390,228,262 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,010 | py | import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.callbacks import EarlyStopping
#1. 데이터
datasets = load_breast_cancer()
'''
print(datasets)
print(datasets.keys())
print(datasets.feature_names)
print(datasets.DESCR)
'''
x = datasets.data
y = datasets.target
'''
print(x.shape) # (569, 30)
print(y.shape) # (569, )
print(y[:20]) # [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]
print(np.unique(y)) # [0 1]
'''
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=66)
scaler = StandardScaler()
scaler.fit(x_train)
x_train = scaler.transform(x_train)
x_test = scaler.transform(x_test)
#2. 모델링
input = Input(shape=(30, ))
x = Dense(128, activation='relu')(input)
x = Dense(64, activation='relu')(x)
x = Dense(64, activation='relu')(x)
x = Dense(64, activation='relu')(x)
x = Dense(32, activation='relu')(x)
output = Dense(1, activation='sigmoid')(x)
model = Model(inputs=input, outputs=output)
#3. 컴파일, 훈련
es = EarlyStopping(monitor='loss', patience=5, mode='min', verbose=1)
num_epochs = 100
model.compile(loss='binary_crossentropy', optimizer='adam',
metrics=['mse', 'accuracy'])
model.fit(x_train, y_train, epochs=num_epochs, batch_size=8,
validation_split=0.1, callbacks=[es])
#4. 평가,예측
loss = model.evaluate(x_test, y_test)
y_predict = model.predict(x_test[-5:-1])
print('epochs = ', num_epochs)
print('loss = ', loss[0])
print('mse = ', loss[1])
print('accuracy = ', loss[2])
print(y_test[-5:-1])
print(y_predict)
'''
epochs = 100
loss = 0.2840605676174164
mse = 0.0262874998152256
accuracy = 0.9736841917037964
[1 0 1 1]
[[1.0000000e+00]
[1.7312156e-16]
[1.0000000e+00]
[1.0000000e+00]]
'''
| [
"[email protected]"
] | |
c9ccf86a379bb6844db6786edbb90773790e6322 | 8f1996c1b5a0211474c7fa287be7dc20a517f5f0 | /hail/python/test/hailtop/test_fs.py | fdf431bb6c0fc00b1b5deaf9fbee66b5ced13160 | [
"MIT"
] | permissive | johnc1231/hail | 9568d6effe05e68dcc7bf398cb32df11bec061be | 3dcaa0e31c297e8452ebfcbeda5db859cd3f6dc7 | refs/heads/main | 2022-04-27T10:51:09.554544 | 2022-02-08T20:05:49 | 2022-02-08T20:05:49 | 78,463,138 | 0 | 0 | MIT | 2022-03-01T15:55:25 | 2017-01-09T19:52:45 | Python | UTF-8 | Python | false | false | 14,201 | py | from typing import Tuple, AsyncIterator
import random
import functools
import os
import secrets
from concurrent.futures import ThreadPoolExecutor
import asyncio
import pytest
from hailtop.utils import secret_alnum_string, retry_transient_errors, bounded_gather2, url_scheme
from hailtop.aiotools import LocalAsyncFS, UnexpectedEOFError, AsyncFS
from hailtop.aiotools.router_fs import RouterAsyncFS
from hailtop.aiocloud.aioaws import S3AsyncFS
from hailtop.aiocloud.aioazure import AzureAsyncFS
from hailtop.aiocloud.aiogoogle import GoogleStorageAsyncFS
@pytest.fixture(params=['file', 'gs', 's3', 'hail-az', 'router/file', 'router/gs', 'router/s3', 'router/hail-az'])
async def filesystem(request) -> AsyncIterator[Tuple[asyncio.Semaphore, AsyncFS, str]]:
token = secret_alnum_string()
with ThreadPoolExecutor() as thread_pool:
fs: AsyncFS
if request.param.startswith('router/'):
fs = RouterAsyncFS(
'file', filesystems=[LocalAsyncFS(thread_pool),
GoogleStorageAsyncFS(),
S3AsyncFS(thread_pool),
AzureAsyncFS()])
elif request.param == 'file':
fs = LocalAsyncFS(thread_pool)
elif request.param.endswith('gs'):
fs = GoogleStorageAsyncFS()
elif request.param.endswith('s3'):
fs = S3AsyncFS(thread_pool)
else:
assert request.param.endswith('hail-az')
fs = AzureAsyncFS()
async with fs:
if request.param.endswith('file'):
base = f'/tmp/{token}/'
elif request.param.endswith('gs'):
bucket = os.environ['HAIL_TEST_GCS_BUCKET']
base = f'gs://{bucket}/tmp/{token}/'
elif request.param.endswith('s3'):
bucket = os.environ['HAIL_TEST_S3_BUCKET']
base = f's3://{bucket}/tmp/{token}/'
else:
assert request.param.endswith('hail-az')
account = os.environ['HAIL_TEST_AZURE_ACCOUNT']
container = os.environ['HAIL_TEST_AZURE_CONTAINER']
base = f'hail-az://{account}/{container}/tmp/{token}/'
await fs.mkdir(base)
sema = asyncio.Semaphore(50)
async with sema:
yield (sema, fs, base)
await fs.rmtree(sema, base)
assert not await fs.isdir(base)
@pytest.fixture
async def local_filesystem(request):
token = secret_alnum_string()
with ThreadPoolExecutor() as thread_pool:
async with LocalAsyncFS(thread_pool) as fs:
base = f'/tmp/{token}/'
await fs.mkdir(base)
sema = asyncio.Semaphore(50)
async with sema:
yield (sema, fs, base)
await fs.rmtree(sema, base)
assert not await fs.isdir(base)
@pytest.fixture(params=['small', 'multipart', 'large'])
def file_data(request):
if request.param == 'small':
return [b'foo']
elif request.param == 'multipart':
return [b'foo', b'bar', b'baz']
else:
assert request.param == 'large'
return [secrets.token_bytes(1_000_000)]
@pytest.mark.asyncio
async def test_write_read(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str], file_data):
sema, fs, base = filesystem
file = f'{base}foo'
async with await fs.create(file) as writer:
for b in file_data:
await writer.write(b)
expected = b''.join(file_data)
async with await fs.open(file) as reader:
actual = await reader.read()
assert expected == actual
@pytest.mark.asyncio
async def test_open_from(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str]):
sema, fs, base = filesystem
file = f'{base}foo'
async with await fs.create(file) as f:
await f.write(b'abcde')
async with await fs.open_from(file, 2) as f:
r = await f.read()
assert r == b'cde'
@pytest.mark.asyncio
async def test_open_nonexistent_file(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str]):
sema, fs, base = filesystem
file = f'{base}foo'
try:
async with await fs.open(file) as f:
await f.read()
except FileNotFoundError:
pass
else:
assert False
@pytest.mark.asyncio
async def test_open_from_nonexistent_file(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str]):
sema, fs, base = filesystem
file = f'{base}foo'
try:
async with await fs.open_from(file, 2) as f:
await f.read()
except FileNotFoundError:
pass
else:
assert False
@pytest.mark.asyncio
async def test_read_from(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str]):
sema, fs, base = filesystem
file = f'{base}foo'
await fs.write(file, b'abcde')
r = await fs.read_from(file, 2)
assert r == b'cde'
@pytest.mark.asyncio
async def test_read_range(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str]):
sema, fs, base = filesystem
file = f'{base}foo'
await fs.write(file, b'abcde')
r = await fs.read_range(file, 2, 2)
assert r == b'c'
r = await fs.read_range(file, 2, 4)
assert r == b'cde'
try:
await fs.read_range(file, 2, 10)
except UnexpectedEOFError:
pass
else:
assert False
@pytest.mark.asyncio
async def test_write_read_range(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str], file_data):
sema, fs, base = filesystem
file = f'{base}foo'
async with await fs.create(file) as f:
for b in file_data:
await f.write(b)
pt1 = random.randint(0, len(file_data))
pt2 = random.randint(0, len(file_data))
start = min(pt1, pt2)
end = max(pt1, pt2)
expected = b''.join(file_data)[start:end+1]
actual = await fs.read_range(file, start, end) # end is inclusive
assert expected == actual
@pytest.mark.asyncio
async def test_isfile(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str]):
sema, fs, base = filesystem
file = f'{base}foo'
# doesn't exist yet
assert not await fs.isfile(file)
await fs.touch(file)
assert await fs.isfile(file)
@pytest.mark.asyncio
async def test_isdir(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str]):
sema, fs, base = filesystem
# mkdir with trailing slash
dir = f'{base}dir/'
await fs.mkdir(dir)
await fs.touch(f'{dir}foo')
# can't test this until after creating foo
assert await fs.isdir(dir)
# mkdir without trailing slash
dir2 = f'{base}dir2'
await fs.mkdir(dir2)
await fs.touch(f'{dir2}/foo')
assert await fs.isdir(dir)
@pytest.mark.asyncio
async def test_isdir_subdir_only(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str]):
sema, fs, base = filesystem
dir = f'{base}dir/'
await fs.mkdir(dir)
subdir = f'{dir}subdir/'
await fs.mkdir(subdir)
await fs.touch(f'{subdir}foo')
# can't test this until after creating foo
assert await fs.isdir(dir)
assert await fs.isdir(subdir)
@pytest.mark.asyncio
async def test_remove(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str]):
sema, fs, base = filesystem
file = f'{base}foo'
await fs.touch(file)
assert await fs.isfile(file)
await fs.remove(file)
assert not await fs.isfile(file)
@pytest.mark.asyncio
async def test_rmtree(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str]):
sema, fs, base = filesystem
dir = f'{base}foo/'
subdir1 = f'{dir}foo/'
subdir1subdir1 = f'{subdir1}foo/'
subdir1subdir2 = f'{subdir1}bar/'
subdir1subdir3 = f'{subdir1}baz/'
subdir1subdir4_empty = f'{subdir1}qux/'
subdir2 = f'{dir}bar/'
subdir3 = f'{dir}baz/'
subdir4_empty = f'{dir}qux/'
await fs.mkdir(dir)
await fs.touch(f'{dir}a')
await fs.touch(f'{dir}b')
await fs.mkdir(subdir1)
await fs.mkdir(subdir1subdir1)
await fs.mkdir(subdir1subdir2)
await fs.mkdir(subdir1subdir3)
await fs.mkdir(subdir1subdir4_empty)
await fs.mkdir(subdir2)
await fs.mkdir(subdir3)
await fs.mkdir(subdir4_empty)
sema = asyncio.Semaphore(100)
await bounded_gather2(sema, *[
functools.partial(fs.touch, f'{subdir}a{i:02}')
for subdir in [dir, subdir1, subdir2, subdir3, subdir1subdir1, subdir1subdir2, subdir1subdir3]
for i in range(30)])
assert await fs.isdir(dir)
assert await fs.isdir(subdir1)
assert await fs.isdir(subdir1subdir1)
assert await fs.isdir(subdir1subdir2)
assert await fs.isdir(subdir1subdir3)
# subdir1subdir4_empty: in cloud fses, empty dirs do not exist and thus are not dirs
assert await fs.isdir(subdir2)
assert await fs.isdir(subdir3)
# subdir4_empty: in cloud fses, empty dirs do not exist and thus are not dirs
await fs.rmtree(sema, subdir1subdir2)
assert await fs.isdir(dir)
assert await fs.isfile(f'{dir}a')
assert await fs.isfile(f'{dir}b')
assert await fs.isdir(subdir1)
assert await fs.isfile(f'{subdir1}a00')
assert await fs.isdir(subdir1subdir1)
assert await fs.isfile(f'{subdir1subdir1}a00')
assert not await fs.isdir(subdir1subdir2)
assert not await fs.isfile(f'{subdir1subdir2}a00')
assert await fs.isdir(subdir1subdir3)
assert await fs.isfile(f'{subdir1subdir3}a00')
assert await fs.isdir(subdir2)
assert await fs.isfile(f'{subdir2}a00')
assert await fs.isdir(subdir3)
assert await fs.isfile(f'{subdir3}a00')
await fs.rmtree(sema, dir)
assert not await fs.isdir(dir)
@pytest.mark.asyncio
async def test_rmtree_empty_dir(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str]):
sema, fs, base = filesystem
dir = f'{base}bar/'
await fs.mkdir(dir)
await fs.rmtree(sema, dir)
assert not await fs.isdir(dir)
@pytest.mark.asyncio
async def test_cloud_rmtree_file_ending_in_slash(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str]):
sema, fs, base = filesystem
base_scheme = url_scheme(base)
if isinstance(fs, LocalAsyncFS) or base_scheme in ('', 'file'):
return
fname = f'{base}bar/'
async with await fs.create(fname) as f:
await f.write(b'test_rmtree_file_ending_in_slash')
await fs.rmtree(sema, fname)
assert not await fs.isdir(fname)
assert not await fs.isfile(fname)
assert not await fs.exists(fname)
@pytest.mark.asyncio
async def test_statfile_nonexistent_file(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str]):
sema, fs, base = filesystem
with pytest.raises(FileNotFoundError):
await fs.statfile(f'{base}foo')
@pytest.mark.asyncio
async def test_statfile_directory(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str]):
sema, fs, base = filesystem
await fs.mkdir(f'{base}dir/')
await fs.touch(f'{base}dir/foo')
with pytest.raises(FileNotFoundError):
# statfile raises FileNotFound on directories
await fs.statfile(f'{base}dir')
@pytest.mark.asyncio
async def test_statfile(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str]):
sema, fs, base = filesystem
n = 37
file = f'{base}bar'
await fs.write(file, secrets.token_bytes(n))
status = await fs.statfile(file)
assert await status.size() == n
@pytest.mark.asyncio
async def test_listfiles(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str]):
sema, fs, base = filesystem
with pytest.raises(FileNotFoundError):
await fs.listfiles(f'{base}does/not/exist')
with pytest.raises(FileNotFoundError):
await fs.listfiles(f'{base}does/not/exist', recursive=True)
# create the following directory structure in base:
# foobar
# foo/a
# foo/b/c
a = f'{base}foo/a'
b = f'{base}foo/b/'
c = f'{base}foo/b/c'
await fs.touch(f'{base}foobar')
await fs.mkdir(f'{base}foo/')
await fs.touch(a)
await fs.mkdir(b)
await fs.touch(c)
async def listfiles(dir, recursive):
return {(await entry.url(), await entry.is_file()) async for entry in await fs.listfiles(dir, recursive)}
assert await listfiles(f'{base}foo/', recursive=True) == {(a, True), (c, True)}
assert await listfiles(f'{base}foo/', recursive=False) == {(a, True), (b, False)}
# without trailing slash
assert await listfiles(f'{base}foo', recursive=True) == {(a, True), (c, True)}
assert await listfiles(f'{base}foo', recursive=False) == {(a, True), (b, False)}
# test FileListEntry.status raises on directory
async for entry in await fs.listfiles(f'{base}foo/', recursive=False):
if await entry.is_dir():
with pytest.raises(IsADirectoryError):
await entry.status()
else:
stat = await entry.status()
assert await stat.size() == 0
@pytest.mark.asyncio
@pytest.mark.parametrize("permutation", [
None,
[0, 1, 2],
[0, 2, 1],
[1, 2, 0],
[2, 1, 0]
])
async def test_multi_part_create(filesystem: Tuple[asyncio.Semaphore, AsyncFS, str], permutation):
sema, fs, base = filesystem
# S3 has a minimum part size (except for the last part) of 5MiB
if base.startswith('s3'):
min_part_size = 5 * 1024 * 1024
part_data_size = [min_part_size, min_part_size, min_part_size]
else:
part_data_size = [8192, 600, 20000]
part_data = [secrets.token_bytes(s) for s in part_data_size]
s = 0
part_start = []
for b in part_data:
part_start.append(s)
s += len(b)
path = f'{base}a'
async with await fs.multi_part_create(sema, path, len(part_data)) as c:
async def create_part(i):
async with await c.create_part(i, part_start[i]) as f:
await f.write(part_data[i])
if permutation:
# do it in a fixed order
for i in permutation:
await retry_transient_errors(create_part, i)
else:
# do in parallel
await asyncio.gather(*[
retry_transient_errors(create_part, i)
for i in range(len(part_data))])
expected = b''.join(part_data)
async with await fs.open(path) as f:
actual = await f.read()
assert expected == actual
| [
"[email protected]"
] | |
962812ea95c14c421b5d385ad22db70190075490 | 3284c2a6e99c27c9a72de68f60284b7865a7fb0c | /Principles_of_Computing/poc_fifteen_testsuite.py | d67f71a5ed434da0c1ac0fb0994003f591b64614 | [] | no_license | bbusenius/Projects | e6c972a4356d1ece978b402004cd0bdf23279c98 | 57240764f64dd66ce69336450509e8556dbc597e | refs/heads/master | 2022-09-17T17:18:08.884037 | 2022-08-27T21:39:55 | 2022-08-27T21:39:55 | 20,620,395 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,706 | py | import random
from Fifteen import Puzzle
def test_lower_row_invariant(puzzle, start):
""" test lower row invariants """
assert start[0] > 1, "not an interior tile"
assert puzzle.lower_row_invariant(*start)
if start[1] == 0:
puzzle.solve_col0_tile(start[0])
else:
puzzle.solve_interior_tile(*start)
if start[1] > 0:
return puzzle.lower_row_invariant(start[0], start[1]-1)
else:
return puzzle.lower_row_invariant(start[0]-1, puzzle.get_width()-1)
def test_upper_row_invariants(puzzle, start):
""" test row0 and row1 invariants """
if start[0] == 1:
assert puzzle.row1_invariant(start[1])
puzzle.solve_row1_tile(start[1])
return puzzle.row0_invariant(start[1])
else:
assert puzzle.row0_invariant(start[1])
puzzle.solve_row0_tile(start[1])
return puzzle.row1_invariant(start[1]-1)
def test_2x2(puzzle, dummy=None):
""" test if puzzle's top-left corner is correct """
assert puzzle.row1_invariant(1)
puzzle.solve_2x2()
return is_correct(puzzle)
def test_game(puzzle, dummy=None):
""" complete puzzle test runner """
move_str = generate_random_move_str()
valid_moves = []
for move in move_str:
try:
puzzle.update_puzzle(move)
valid_moves.append(move)
except AssertionError:
pass # ignore invalid moves
print "puzzle string: %s\n" % "".join(valid_moves)
print puzzle
result = puzzle.solve_puzzle()
return is_correct(puzzle)
def run_test(puzzle, start, name, complete=False, stats=[0,0]):
""" run single test """
print "running test '%s'" % name
if complete:
test_func = test_game
else:
print puzzle
if start is None:
test_func = test_2x2
else:
test_func = test_lower_row_invariant if start[0] >= 2 else test_upper_row_invariants
if test_func(puzzle, start):
stats[0] += 1
print puzzle
print "test #%d: '%s' passed. total=%d/%d\n" % (sum(stats), name, stats[0], stats[1])
else:
stats[1] += 1
print puzzle
print "test #%d: '%s' failed. total=%d/%d\n" % (sum(stats), name, stats[0], stats[1])
def run_tests_interior():
""" interior test runner """
base = Puzzle(4, 5, [[10, 11, 12, 9, 8],
[7, 6, 5, 4, 3],
[2, 1, 0, 13, 14],
[15, 16, 17, 18, 19]])
obj = base.clone()
run_test(obj, (2,2), "interior same col")
obj = base.clone()
obj.set_number(1,1, 12)
obj.set_number(0,2, 6)
run_test(obj, (2,2), "interior half left")
obj = base.clone()
obj.set_number(1,3, 12)
obj.set_number(0,2, 4)
run_test(obj, (2,2), "interior half right")
obj = base.clone()
obj.set_number(0,0, 12)
obj.set_number(0,2, 10)
run_test(obj, (2,2), "interior upper left")
obj = base.clone()
obj.set_number(0,4, 12)
obj.set_number(0,2, 8)
run_test(obj, (2,2), "interior upper right")
obj = base.clone()
obj.set_number(2,0, 12)
obj.set_number(0,2, 2)
run_test(obj, (2,2), "interior same row")
obj = base.clone()
obj.set_number(2,1, 12)
obj.set_number(0,2, 1)
run_test(obj, (2,2), "interior short path")
def run_tests_col0():
""" column 0 test runner """
base = Puzzle(4, 5, [[10, 6, 5, 4, 3],
[2, 1, 8, 9, 7],
[0, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
obj = base.clone()
obj.set_number(1,0, 10)
obj.set_number(0,0, 2)
run_test(obj, (2,0), "col0 short path")
obj = base.clone()
run_test(obj, (2,0), "col0 upper left")
obj = base.clone()
obj.set_number(0,4, 10)
obj.set_number(0,0, 3)
run_test(obj, (2,0), "col0 upper right")
obj = base.clone()
obj.set_number(1,2, 10)
obj.set_number(0,0, 8)
run_test(obj, (2,0), "col0 half right")
obj = base.clone()
obj.set_number(1,1, 10)
obj.set_number(0,0, 1)
run_test(obj, (2,0), "col0 diagonal")
def run_tests_row1():
""" row 1 test runner """
base = Puzzle(4, 5, [[9, 4, 6, 5, 1],
[7, 3, 8, 2, 0],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
obj = base.clone()
run_test(obj, (1,4), "row1 upper left")
base = Puzzle(4, 5, [[4,7,2,6,9],
[5,3,8,1,0],
[10,11,12,13,14],
[15,16,17,18,19]])
obj = base.clone()
run_test(obj, (1,4), "row1 upper right")
obj = base.clone()
obj.set_number(1,0, 9)
obj.set_number(0,0, 7)
run_test(obj, (1,4), "row1 lower left")
obj = base.clone()
obj.set_number(1,4, 9)
obj.set_number(1,3, 0)
obj.set_number(0,0, 2)
obj.set_number(0,4, 4)
obj.set_number(0,1, 1)
run_test(obj, (1,3), "row1 lower half left")
obj = base.clone()
obj.set_number(1,4, 9)
obj.set_number(1,3, 0)
obj.set_number(1,2, 6)
obj.set_number(0,2, 8)
obj.set_number(0,4, 4)
obj.set_number(0,1, 1)
run_test(obj, (1,3), "row1 upper half left")
def run_tests_row0():
""" row 0 test runner """
base = Puzzle(4, 5, [[1, 5, 6, 0, 4],
[7, 3, 2, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
obj = base.clone()
run_test(obj, (0,3), "row0 lower half left")
obj = base.clone()
obj.set_number(0,1, 3)
obj.set_number(1,1, 5)
run_test(obj, (0,3), "row0 upper half left")
obj = base.clone()
obj.set_number(1,2, 3)
obj.set_number(1,1, 2)
run_test(obj, (0,3), "row0 diagonal")
obj = base.clone()
obj.set_number(1,0, 3)
obj.set_number(1,1, 7)
run_test(obj, (0,3), "row0 lower left")
obj = base.clone()
obj.set_number(0,0, 3)
obj.set_number(1,1, 1)
run_test(obj, (0,3),"row0 upper left")
obj = Puzzle(4, 5, [[1, 2, 0, 3, 4],
[6, 5, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
obj.solve_row0_tile(2)
def run_tests_2x2():
""" 2x2 test runner """
base = Puzzle(4, 5, [[1, 6, 2, 3, 4],
[5, 0, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
obj = base.clone()
run_test(obj, None, "2x2 #1")
obj = base.clone()
obj.set_number(0,0, 6)
obj.set_number(0,1, 5)
obj.set_number(1,0, 1)
obj.set_number(1,1, 0)
run_test(obj, None, "2x2 #2")
base = Puzzle(3, 3, [[4, 3, 2], [1, 0, 5], [6, 7, 8]])
obj = base.clone()
run_test(obj, None, "2x2 #3")
def run_tests_game():
""" complete game test runner """
sizes = [(2,2), (2,3), (3,2), (3,3), (5,4), (2,5), (5,2)]
for size in sizes:
run_test(Puzzle(*size), None, "random Puzzle(%d,%d)" % size, True)
def is_correct(puzzle):
for row in range(puzzle.get_height()):
for col in range(puzzle.get_width()):
if not puzzle.current_position(row, col) == (row, col):
return False
return True
def generate_random_move_str():
""" helper method to generate a random solvable puzzle """
num = 100
moves = list("r" * 100 + "l" * 100 + "u" * 100 + "d" * 100)
random.shuffle(moves)
move_str = "".join(moves)
return "".join(move_str)
run_tests_interior()
#run_tests_col0()
#run_tests_row1()
#run_tests_row0()
#run_tests_2x2()
#run_tests_game()
| [
"[email protected]"
] | |
e0e7d78dd4f1fee7f98cffb633332ada28ece746 | 1cef5a1cfbe5986142f58995e9ce34b6d51fe8e5 | /parser.py | f531b12682bc90d17a45860672b4e4dabcbe3ad0 | [
"MIT"
] | permissive | sauloal/py_ncbi_taxonomy | cdc70a9a4be13ad2b159ddb7804879de9111b445 | 6e2607e77945609d109f6f418dad0524543c76cf | refs/heads/master | 2020-08-24T21:59:42.245261 | 2019-10-27T21:29:45 | 2019-10-27T21:29:45 | 216,914,883 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 14,348 | py | #!/usr/bin/env python3
import os
import sys
import pickle
from collections import OrderedDict
import simplejson as json
#import json
from tax import *
import pandas as pd
import fastparquet
class AllData(General):
__slots__ = [
"divisions",
"genetic_codes",
"names",
"nodes",
# "no_parents",
# "parents"
]
__attributes__ = __slots__
__shared__ = []
def __init__(self):
self.divisions = parse_division()
self.genetic_codes = parse_gencode()
self.nodes = parse_nodes()
self.names = parse_names()
self.no_parents, self.parents = gen_parents(self.nodes)
def __iter__(self):
return self.next()
def __next__(self):
return self.next()
def get(self, tax_id):
if tax_id not in self.nodes:
raise KeyError("No such tax_id")
node = self.nodes[tax_id]
(
tax_id,
parent_tax_id,
rank_id,
rank_name,
embl_code_id,
embl_code,
division_id,
inherited_div_flag,
genetic_code_id,
inherited_GC_flag,
mitochondrial_genetic_code_id,
inherited_MGC_flag,
genBank_hidden_flag,
hidden_subtree_root_flag
) = node.get()
parent = self.nodes[parent_tax_id]
parent_rank_id = parent.rank_id
parent_rank = parent.rank_name
if rank_id != 0:
assert rank_id >= parent_rank_id, "rank {} ({}) < than rank {} ({})".format(rank_id, rank_name, parent_rank_id, parent_rank)
name_tax_id, names = self.names[tax_id].get()
division = self.divisions[division_id].get()
genetic_code = self.genetic_codes[genetic_code_id]
mitochondrial_genetic_code = self.genetic_codes[mitochondrial_genetic_code_id]
_, division_cde_id, division_cde, division_name_id, division_name, division_comments = division
genetic_code_abbreviation , genetic_code_name , genetic_code_cde , genetic_code_starts = genetic_code
mitochondrial_genetic_code_abbreviation, mitochondrial_genetic_code_name, mitochondrial_genetic_code_cde, mitochondrial_genetic_code_starts = mitochondrial_genetic_code
is_parent = tax_id in self.parents
asc = None
if True: #not is_parent:
asc = [None] * len(RANKS)
try:
gen_asc(self.nodes, asc, tax_id)
except AssertionError as e:
print(e)
print(rank_id, rank_name, division_cde, division_name, names)
asc = None
row = Row(
tax_id,
parent_tax_id,
rank_id,
rank_name,
embl_code_id,
embl_code,
division_id,
division_cde_id,
division_cde,
division_name_id,
division_name,
division_comments,
inherited_div_flag,
genetic_code_id,
genetic_code_abbreviation,
genetic_code_name,
genetic_code_cde,
genetic_code_starts,
inherited_GC_flag,
mitochondrial_genetic_code_id,
mitochondrial_genetic_code_abbreviation,
mitochondrial_genetic_code_name,
mitochondrial_genetic_code_cde,
mitochondrial_genetic_code_starts,
inherited_MGC_flag,
names,
genBank_hidden_flag,
hidden_subtree_root_flag,
is_parent,
asc
)
return row
def next(self):
for node_pos, tax_id in enumerate(self.nodes.keys()):
if (node_pos+1) % 100000 == 0:
print(" {:12,d} / {:12,d}".format(node_pos+1, len(self.nodes)))
sys.stdout.flush()
yield self.get(tax_id)
def search_by_name(self, FILTER_VAL):
nids = []
for nid, name in self.names.items():
if FILTER_VAL.lower() in [t.lower() for t in name.txts]:
nids.append(nid)
return list(set(nids))
def parser_save(fn, cls, data):
# for e, (k,v) in enumerate(data.items()):
# if e < 5 or e > len(data) - 5:
# print(k, v)
print(" converting to dataframe")
sys.stdout.flush()
df = pd.DataFrame.from_dict({k: v._to_pandas() for k,v in data.items()}, orient="index", columns=cls.__pds__)
# print(pd.concat([df.head(), df.tail()]))
print(" saving to", fn)
sys.stdout.flush()
df.to_parquet(fn, engine="fastparquet", compression="snappy", index=True)#, partition_cols=)
print(" done")
sys.stdout.flush()
return df
def parser_load(fn, cls):
print(" loading", fn)
sys.stdout.flush()
data = pd.read_parquet(fn, engine="fastparquet")
print(" converting to class")
sys.stdout.flush()
# print(pd.concat([data.head(), data.tail()]))
data = data.to_dict(orient="index", into=OrderedDict)
data = OrderedDict((k, cls(*[v[s] for s in cls.__pds__])) for k,v in data.items())
# for e, (k,v) in enumerate(data.items()):
# if e < 5 or e > len(data) - 5:
# print(k, v)
print(" done")
sys.stdout.flush()
return data
def parse_division():
print("parsing division")
if os.path.exists("db_division.pq"):
print(" loading db_division.pq")
sys.stdout.flush()
divisions = parser_load(fn="db_division.pq", cls=Division)
# with open("db_division.pickle", "rb") as fhd:
# divisions = pickle.load(fhd)
else:
divisions = OrderedDict()
for linenum, cols in read_dump("division.dmp"):
# print(linenum, cols)
division = Division(*cols)
assert division.did not in divisions
divisions[division.did] = division
# print(division)
print(" saving db_division.pq")
sys.stdout.flush()
divisions = parser_save(fn="db_division.pq", cls=Division, data=divisions)
# divisions2 = parser_load(fn="db_division.pq", cls=Division)
# assert repr(divisions2) == repr(divisions)
# with open("db_division.pickle", "wb") as fhd:
# pickle.dump(divisions, fhd, protocol=0)
print(" divisions {:12,d}".format(len(divisions )))
sys.stdout.flush()
return divisions
def parse_gencode():
print("parsing gencode")
if os.path.exists("db_gencode.pickle"):
print(" loading db_gencode.pickle")
sys.stdout.flush()
with open("db_gencode.pickle", "rb") as fhd:
gencodes = pickle.load(fhd)
else:
gencodes = OrderedDict()
for linenum, cols in read_dump("gencode.dmp"):
# print(linenum, cols)
genetic_code_id, abbreviation, name, cde, starts = cols
genetic_code_id = int(genetic_code_id)
gencodes[genetic_code_id] = (abbreviation, name, cde, starts)
print(" saving db_gencode.pickle")
sys.stdout.flush()
with open("db_gencode.pickle", "wb") as fhd:
pickle.dump(gencodes, fhd, protocol=0)
print(" gencodes {:12,d}".format(len(gencodes)))
sys.stdout.flush()
return gencodes
def parse_nodes():
print("parsing nodes")
if os.path.exists("db_nodes.pq"):
print(" loading db_nodes.pq")
sys.stdout.flush()
# with open("db_nodes.pickle", "rb") as fhd:
# nodes = pickle.load(fhd)
nodes = parser_load(fn="db_nodes.pq", cls=Node)
else:
nodes = OrderedDict()
for linenum, cols in read_dump("nodes.dmp"):
# print(linenum, cols)
if (linenum+1) % 100000 == 0:
print(" {:12,d}".format(linenum+1))
sys.stdout.flush()
node = Node(*cols[:12])
assert node.tax_id not in nodes
nodes[node.tax_id] = node
# print(node)
print(" saving db_nodes.pq")
sys.stdout.flush()
parser_save( fn="db_nodes.pq", cls=Node, data=nodes)
# nodes2 = parser_load(fn="db_nodes.pq", cls=Node)
# assert repr(nodes2) == repr(nodes)
# with open("db_nodes.pickle", "wb") as fhd:
# pickle.dump(nodes, fhd, protocol=0)
print(" nodes {:12,d}".format(len(nodes )))
sys.stdout.flush()
return nodes
def parse_names():
print("parsing names")
if os.path.exists("db_names.pq"):
print(" loading db_names.pq")
sys.stdout.flush()
names = parser_load(fn="db_names.pq", cls=Name)
# with open("db_names.pickle", "rb") as fhd:
# names = pickle.load(fhd)
else:
names = OrderedDict()
for linenum, cols in read_dump("names.dmp"):
# print(linenum, cols)
if (linenum+1) % 100000 == 0:
print(" {:12,d}".format(linenum+1))
sys.stdout.flush()
name = Name(*cols)
if name.tax_id in names:
names[name.tax_id].merge(name)
# assert tax_id not in names, "duplicated tax_id {}. {}".format(tax_id, names[tax_id])
else:
names[name.tax_id] = name
# print(names[tax_id])
# print()
print(" saving db_names.pq")
sys.stdout.flush()
parser_save( fn="db_names.pq", cls=Name, data=names)
# names2 = parser_load(fn="db_names.pq", cls=Name)
# assert repr(names2) == repr(names)
# with open("db_names.pickle", "wb") as fhd:
# pickle.dump(names, fhd, protocol=0)
print(" names {:12,d}".format(len(names )))
return names
def gen_parents(nodes):
print("generating parents")
sys.stdout.flush()
parents = OrderedDict()
for pos, (tax_id, node) in enumerate(nodes.items()):
(
tax_id,
parent_tax_id,
rank_id,
rank_name,
embl_code_id,
embl_code,
division_id,
inherited_div_flag,
genetic_code_id,
inherited_GC_flag,
mitochondrial_genetic_code_id,
inherited_MGC_flag,
genBank_hidden_flag,
hidden_subtree_root_flag
) = node.get()
if (pos + 1) % 100000 == 0:
print(" {:12,d}".format(pos+1))
sys.stdout.flush()
parents[parent_tax_id] = parents.get(parent_tax_id, 0) + 1
no_parents = list(set(nodes.keys()) - set(parents.keys()))
print(" total {:12,d}".format(len(nodes )))
print(" parents {:12,d}".format(len(parents )))
print(" no parents {:12,d}".format(len(no_parents)))
sys.stdout.flush()
return no_parents, parents
def gen_asc(nodes, asc, tax_id, level=0):
node = nodes[tax_id]
node_rank_id = node.rank_id
parent_tax_id = node.parent_tax_id
assert asc[node_rank_id] is None and asc[node_rank_id] != tax_id, (tax_id, node_rank_id, RANKS[node_rank_id], parent_tax_id, level, asc)
if node_rank_id != 0:
asc[node_rank_id] = tax_id
gen_asc(nodes, asc, parent_tax_id, level=level+1)
def gen_tree(all_data, asc, matrix, tree, rank=0):
if rank >= len(asc):
return
tax_id = asc[rank]
if tax_id is None:
gen_tree(all_data, asc, matrix, tree, rank=rank+1)
else:
if tax_id not in tree:
tree[tax_id] = OrderedDict()
# tree[tax_id].update(all_data.get(tax_id).as_dict())
el = tree[tax_id]
if "chl" not in el:
el["tid"] = tax_id
el["rid"] = rank
el["chl"] = OrderedDict()
gen_tree(all_data, asc, matrix, el["chl"], rank=rank+1)
def main():
FILTER_LEVEL = RANKS.index("genus")
FILTER_CLASS = "scientific name"
FILTER_VAL = "Solanum"
all_data = None
out_data = None
individuals = None
parents = None
matrix = None
if os.path.exists("db_out_all_data.pickle") and os.path.exists("db_out_matrix.pickle"):
print("loading db_out_all_data.pickle")
sys.stdout.flush()
with open("db_out_all_data.pickle", "rb") as fhd:
all_data = pickle.load(fhd)
print("loading db_out_matrix.pickle")
sys.stdout.flush()
with open("db_out_matrix.pickle", "rb") as fhd:
matrix = pickle.load(fhd)
else:
print("creating all data")
sys.stdout.flush()
all_data = AllData()
out_data = OrderedDict()
individuals = OrderedDict()
parents = OrderedDict()
print("summarizing data")
sys.stdout.flush()
par_ids = all_data.search_by_name(FILTER_VAL)
print(" par_ids", par_ids)
ascs = []
max_id = 0
for row in all_data:
# print(row.tax_id)
if row.asc is None:
# print( " no asc")
continue
fl = row.asc[FILTER_LEVEL]
if fl is None:
# print( " no fl", FILTER_LEVEL)
continue
if fl not in par_ids:
continue
# print( row )
out_data[row.tax_id] = row
if row.is_parent:
parents[row.tax_id] = row
else:
individuals[row.tax_id] = row
ascs.append(row.asc)
max_id = max([row.tax_id, max_id])
print(" out_data {:12,d}".format(len(out_data )))
print(" individuals {:12,d}".format(len(individuals)))
print(" parents {:12,d}".format(len(parents )))
print(" max_id {:12,d}".format(max_id ))
sys.stdout.flush()
# #https://www.geeksforgeeks.org/construct-tree-from-ancestor-matrix/
# matrix = [0 for p in range(max_id * max_id)]
# for asc in ascs:
# for r in range(len(asc) - 1, 0, -1):
# rv = asc[r]
# if rv is None:
# continue
# for l in range(r - 1):
# lv = asc[l]
# if lv is None:
# continue
# matrix[rv * lv] = 1
print("saving db_out_all_data.pickle")
sys.stdout.flush()
with open("db_out_all_data.pickle", "wb") as fhd:
pickle.dump(all_data, fhd, protocol=0)
print("saving db_out_rows.pickle")
sys.stdout.flush()
with open("db_out_rows.pickle", "wb") as fhd:
pickle.dump(out_data, fhd, protocol=0)
print("saving db_out_rows_parents.pickle")
sys.stdout.flush()
with open("db_out_rows_parents.pickle", "wb") as fhd:
pickle.dump(parents, fhd, protocol=0)
print("saving db_out_rows_individuals.pickle")
sys.stdout.flush()
with open("db_out_rows_individuals.pickle", "wb") as fhd:
pickle.dump(individuals, fhd, protocol=0)
print("saving db_out_matrix.pickle")
sys.stdout.flush()
with open("db_out_matrix.pickle", "wb") as fhd:
pickle.dump(matrix, fhd, protocol=0)
print("creating tree")
sys.stdout.flush()
tree = OrderedDict()
rows = OrderedDict()
for row_num, row in enumerate(all_data):
# print(tax_id, row.tax_id])
rows[row.tax_id] = row
if row.asc:
# print(row.tax_id, row.asc)
gen_tree(all_data, row.asc, matrix, tree)
# if row_num == 100:
# break
print("saving json tree")
sys.stdout.flush()
# print(json.dumps(tree, indent=1, for_json=True))
with open("db_tree.json", "wt") as fhd:
json.dump(tree, fhd, indent=1, for_json=True)
print("saving json data")
sys.stdout.flush()
# print(json.dumps(tree, indent=1, for_json=True))
with open("db_tree_data.json", "wt") as fhd:
json.dump(rows, fhd, indent=1, for_json=True)
print("saving json ranks")
sys.stdout.flush()
# print(json.dumps(tree, indent=1, for_json=True))
with open("db_tree_ranks.json", "wt") as fhd:
json.dump(RANKS, fhd, indent=1, for_json=True)
RANKS
if __name__ == "__main__":
main()
| [
"[email protected]"
] | |
aad2138a61d1e64fd72fccf6ba6766bfefb768b7 | 08d23df88950f1c9beae44ebef584fbf8292866a | /tests.py | 4b71881fbaeb6546d2435f924afd47e8ffdc6dbf | [
"MIT"
] | permissive | arpit1997/church | 7752e19e343d3473f369c672ba8ff0f8d82070bd | 828a8e274b90b6185e47a736bd1b9b6260028e0e | refs/heads/master | 2021-01-11T03:59:48.760502 | 2016-10-18T12:26:38 | 2016-10-18T12:26:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 23,498 | py | import array
import re
from unittest import TestCase
import church._common as common
from church.church import (
Address, Text, Personal,
Datetime, Network, File,
Development, Food, Hardware,
Science, Numbers, Business,
Church
)
from church.exceptions import (
UnsupportedLocale
)
from church.utils import pull
# en, es, de, fr, it, ru, pt,
# pt-br, da, no
LANG = 'en'
class AddressTestCase(TestCase):
def setUp(self):
self.address = Address(LANG)
def tearDown(self):
del self.address
def test_street_number(self):
result = self.address.street_number()
self.assertTrue(re.match(r'[0-9]{1,5}$', result))
def test_street_name(self):
result = self.address.street_name()
parent_file = pull('street', self.address.lang)
self.assertIn(result + '\n', parent_file)
def test_street_suffix(self):
result = self.address.street_suffix()
parent_file = pull('st_suffix', self.address.lang)
self.assertIn(result + '\n', parent_file)
def test_address(self):
result = self.address.address()
self.assertTrue(len(result) > 6)
def test_state(self):
result = self.address.state()
parent_file = pull('states', self.address.lang)
self.assertIn(result + '\n', parent_file)
def test_postal_code(self):
result = self.address.postal_code()
if self.address.lang == 'ru':
self.assertTrue(re.match(r'[0-9]{6}$', str(result)))
else:
self.assertTrue(re.match(r'[0-9]{5}$', str(result)))
def test_country(self):
result = self.address.country() + '\n'
self.assertTrue(len(result) > 3)
result2 = self.address.country(only_iso_code=True) + '\n'
self.assertTrue(len(result2) < 4)
def test_city(self):
result = self.address.city()
parent_file = pull('cities', self.address.lang)
self.assertIn(result + '\n', parent_file)
class NumbersTestCase(TestCase):
def setUp(self):
self.numbers = Numbers()
def tearDown(self):
del self.numbers
def test_floats(self):
result = self.numbers.floats()
self.assertEqual(len(result), 100)
self.assertIsInstance(result, array.array)
result = self.numbers.floats(n=3, to_list=True)
self.assertEqual(len(result), 1000)
self.assertIsInstance(result, list)
def test_primes(self):
result = self.numbers.primes()
self.assertEqual(len(result), 50)
self.assertIsInstance(result, array.array)
result = self.numbers.primes(n=3, to_list=True)
self.assertEqual(len(result), 500)
self.assertIsInstance(result, list)
class TextTestCase(TestCase):
def setUp(self):
self.data = Text(LANG)
def tearDown(self):
del self.data
def test_sentence(self):
result = self.data.sentence() + '\n'
parent_file = pull('text', self.data.lang)
self.assertIn(result, parent_file)
def test_title(self):
result = self.data.title() + '\n'
parent_file = pull('text', self.data.lang)
self.assertIn(result, parent_file)
def test_lorem_ipsum(self):
result = self.data.lorem_ipsum(quantity=2)
self.assertIsNot(result, None)
self.assertIsInstance(result, str)
def test_words(self):
result = self.data.words()
self.assertEqual(len(result), 5)
result = self.data.words(quantity=1)
self.assertEqual(len(result), 1)
def test_word(self):
result = self.data.word()
parent_file = pull('words', self.data.lang)
self.assertIn(result + '\n', parent_file)
def test_swear_word(self):
result = self.data.swear_word()
parent_file = pull('swear_words', self.data.lang)
self.assertIn(result + '\n', parent_file)
def test_naughty_strings(self):
result = self.data.naughty_strings()
self.assertTrue(len(result) > 10)
self.assertIsInstance(result, list)
def test_quote_from_movie(self):
result = self.data.quote_from_movie()
parent_file = pull('quotes', self.data.lang)
self.assertIn(result + '\n', parent_file)
def test_color(self):
result = self.data.color()
parent_file = pull('colors', self.data.lang)
self.assertIn(result + '\n', parent_file)
def test_hex_color(self):
result = self.data.hex_color()
self.assertIn('#', result)
def test_emoji(self):
result = self.data.emoji()
self.assertIn(result, common.EMOJI)
def test_hashtags(self):
result = self.data.hashtags(quantity=5)
self.assertEqual(len(result), 5)
result = self.data.hashtags(quantity=1, category='general')
self.assertIn(result[0], common.HASHTAGS['general'])
def test_weather(self):
result = self.data.weather(scale='c').split(' ')
temp, scale = float(result[0]), result[1]
self.assertEqual(scale, '°C')
self.assertTrue((temp >= -30) and (temp <= 40))
result = self.data.weather(scale='f', a=0, b=10).split(' ')
temp, scale = float(result[0]), result[1]
self.assertEqual(scale, '°F')
self.assertTrue((temp >= 0) and (temp <= (10 * 1.8) + 32))
class BusinessTestCase(TestCase):
def setUp(self):
self.business = Business(LANG)
def test_company_type(self):
result = self.business.company_type()
self.assertTrue(len(result) > 8)
def test_company(self):
result = self.business.company()
parent_file = pull('company', self.business.lang)
self.assertIn(result + '\n', parent_file)
def test_copyright(self):
result = self.business.copyright()
copyright_symbol = '©'
self.assertIn(copyright_symbol, result)
result = self.business.copyright(without_date=True)
self.assertFalse(any(char.isdigit() for char in result))
def test_currency_sio(self):
result = self.business.currency_iso()
self.assertIn(result, common.CURRENCY)
class PersonalTestCase(TestCase):
def setUp(self):
self.person = Personal(LANG)
def tearDown(self):
del self.person
def test_age(self):
result = self.person.age(maximum=55)
self.assertTrue(result <= 55)
def test_name(self):
result = self.person.name()
parent_file = pull('f_names', self.person.lang)
self.assertIn(result + '\n', parent_file)
result = self.person.name('m')
parent_file = pull('m_names', self.person.lang)
self.assertIn(result + '\n', parent_file)
def test_telephone(self):
result = self.person.telephone()
self.assertTrue(len(result) >= 11)
mask = '+5 (###)-###-##-##'
result2 = self.person.telephone(mask=mask)
head = result2.split(' ')[0]
self.assertEqual(head, '+5')
def test_surname(self):
if self.person.lang == 'ru':
result = self.person.surname('f')
parent_file = pull('f_surnames', self.person.lang)
self.assertIn(result + '\n', parent_file)
result = self.person.surname('m')
parent_file = pull('m_surnames', self.person.lang)
self.assertIn(result + '\n', parent_file)
else:
result = self.person.surname()
parent_file = pull('surnames', self.person.lang)
self.assertIn(result + '\n', parent_file)
def test_full_name(self):
result = self.person.full_name('f')
_result = result.split(' ')
self.assertEqual(len(_result), 2)
def test_username(self):
result = self.person.username()
self.assertTrue(re.match(r'^[a-zA-Z0-9_.-]+$', result))
result = self.person.username('f')
self.assertTrue(re.match(r'^[a-zA-Z0-9_.-]+$', result))
def test_twitter(self):
result = self.person.twitter('f')
self.assertIsNotNone(result)
_result = self.person.twitter('m')
self.assertIsNotNone(_result)
def test_facebook(self):
result = self.person.facebook('f')
self.assertIsNotNone(result)
_result = self.person.facebook('m')
self.assertIsNotNone(_result)
def test_wmid(self):
result = self.person.wmid()
self.assertEqual(len(result), 12)
def test_paypal(self):
result = self.person.paypal()
self.assertIsNotNone(result)
def test_yandex_money(self):
result = self.person.yandex_money()
self.assertEqual(len(result), 14)
def test_password(self):
plain = self.person.password(length=15)
self.assertEqual(len(plain), 15)
md5 = self.person.password(algorithm='md5')
self.assertEqual(len(md5), 32)
sha1 = self.person.password(algorithm='sha1')
self.assertEqual(len(sha1), 40)
sha256 = self.person.password(algorithm='sha256')
self.assertEqual(len(sha256), 64)
sha512 = self.person.password(algorithm='sha512')
self.assertEqual(len(sha512), 128)
def test_email(self):
result = self.person.email()
self.assertTrue(
re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)",
result))
def test_home_page(self):
result = self.person.home_page()
self.assertTrue(re.match(r'http[s]?://(?:[a-zA-Z]|[0-9]|'
r'[$-_@.&+]|[!*\(\),]|'
r'(?:%[0-9a-fA-F][0-9a-fA-F]))+', result))
def test_subreddit(self):
result = self.person.subreddit()
self.assertIn(result, common.SUBREDDITS)
full_result = self.person.subreddit(full_url=True)
self.assertTrue(len(full_result) > 20)
result_nsfw = self.person.subreddit(nsfw=True)
self.assertIn(result_nsfw, common.SUBREDDITS_NSFW)
full_result = self.person.subreddit(nsfw=True, full_url=True)
self.assertTrue(len(full_result) > 20)
def test_bitcoin(self):
result = self.person.bitcoin()
self.assertEqual(len(result), 34)
def test_cvv(self):
result = self.person.cvv()
self.assertTrue((100 <= result) and (result <= 999))
def test_credit_card_number(self):
result = self.person.credit_card_number()
self.assertTrue(re.match(r'[\d]+((-|\s)?[\d]+)+', result))
def test_expiration_date(self):
result = self.person.credit_card_expiration_date(mi=16, mx=25)
year = result.split('/')[1]
self.assertTrue((int(year) >= 16) and (int(year) <= 25))
def test_cid(self):
result = self.person.cid()
self.assertTrue((1000 <= result) and (result <= 9999))
def test_gender(self):
result = self.person.gender() + '\n'
self.assertIn(result, pull('gender', self.person.lang))
result_abbr = self.person.gender(abbr=True) + '\n'
self.assertEqual(len(result_abbr), 2)
def test_height(self):
result = self.person.height(from_=1.60, to_=1.90)
self.assertTrue(result.startswith('1'))
self.assertIsInstance(result, str)
def test_weight(self):
result = self.person.weight(from_=40, to_=60)
self.assertTrue((result >= 40) and (result <= 60))
def test_blood_type(self):
result = self.person.blood_type()
self.assertIn(result, common.BLOOD_GROUPS)
def test_sexual_orientation(self):
result = self.person.sexual_orientation()
parent_file = pull('sexuality', self.person.lang)
self.assertIn(result + '\n', parent_file)
def test_profession(self):
result = self.person.profession()
parent_file = pull('professions', self.person.lang)
self.assertIn(result + '\n', parent_file)
def test_university(self):
result = self.person.university()
parent_file = pull('university', self.person.lang)
self.assertIn(result + '\n', parent_file)
def test_qualification(self):
result = self.person.qualification()
parent_file = pull('qualifications', self.person.lang)
self.assertIn(result + '\n', parent_file)
def test_language(self):
result = self.person.language()
parent_file = pull('languages', self.person.lang)
self.assertIn(result + '\n', parent_file)
def test_favorite_movie(self):
result = self.person.favorite_movie()
parent_file = pull('movies', self.person.lang)
self.assertIn(result + '\n', parent_file)
def test_favorite_music_genre(self):
result = self.person.favorite_music_genre()
self.assertIn(result, common.FAVORITE_MUSIC_GENRE)
def test_worldview(self):
result = self.person.worldview()
parent_file = pull('worldview', self.person.lang)
self.assertIn(result + '\n', parent_file)
def test_views_on(self):
result = self.person.views_on()
parent_file = pull('views_on', self.person.lang)
self.assertIn(result + '\n', parent_file)
def test_political_views(self):
result = self.person.political_views()
parent_file = pull('political_views', self.person.lang)
self.assertIn(result + '\n', parent_file)
def test_avatar(self):
result = self.person.avatar()
self.assertTrue(len(result) > 20)
def test_vehicle(self):
result = self.person.vehicle()
self.assertIn(result, common.THE_VEHICLES)
class DatetimeTestCase(TestCase):
def setUp(self):
self.datetime = Datetime(LANG)
def tearDown(self):
del self.datetime
def test_day_of_week(self):
result = self.datetime.day_of_week() + '\n'
self.assertGreater(len(result), 4)
result_abbr = self.datetime.day_of_week(abbr=True)
self.assertTrue(len(result_abbr) < 6 or '.' in result_abbr)
def test_month(self):
result = self.datetime.month() + '\n'
self.assertGreater(len(result), 3)
result_abbr = self.datetime.month(abbr=True)
self.assertIsInstance(result_abbr, str)
def test_year(self):
result = self.datetime.year(from_=2000, to_=2016)
self.assertTrue((result >= 2000) and (result <= 2016))
def test_periodicity(self):
result = self.datetime.periodicity()
parent_file = pull('periodicity', self.datetime.lang)
self.assertIn(result + '\n', parent_file)
def test_day_of_month(self):
result = self.datetime.day_of_month()
self.assertTrue((result >= 1) or (result <= 31))
def test_birthday(self):
result = self.datetime.birthday()
self.assertIsInstance(result, str)
class NetworkTestCase(TestCase):
def setUp(self):
self.net = Network()
def test_ip_v4(self):
result = self.net.ip_v4()
ip_v4_pattern = r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"
self.assertTrue(re.match(ip_v4_pattern, result))
def test_ip_v6(self):
result = self.net.ip_v6()
ip_v6_pattern = \
r'(([0-9a-fA-F]{1,4}:)' \
'{7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:)' \
'{1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]' \
'{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4})' \
'{1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}' \
'|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|' \
'([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|' \
'[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|' \
':((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]' \
'{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:)' \
'{0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.)' \
'{3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|' \
'([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|' \
'1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|' \
'(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))'
self.assertTrue(re.match(ip_v6_pattern, result))
def test_mac_address(self):
result = self.net.mac_address()
mac_pattern = r'^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$'
self.assertTrue(re.match(mac_pattern, result))
def test_user_agent(self):
result = self.net.user_agent()
parent_file = pull('useragents', 'en')
self.assertIn(result + '\n', parent_file)
class FileTestCase(TestCase):
def setUp(self):
self.file = File()
def tearDown(self):
del self.file
def test_extension(self):
text = self.file.extension()
self.assertIn(text, common.EXTENSIONS['text'])
class ScienceTestCase(TestCase):
def setUp(self):
self.science = Science(LANG)
def tearDown(self):
del self.science
def test_math_formula(self):
result = self.science.math_formula()
self.assertIn(result, common.MATH_FORMULAS)
def test_article_on_wiki(self):
result = self.science.article_on_wiki()
parent_file = pull('science_wiki', self.science.lang)
self.assertIn(result + '\n', parent_file)
def test_scientist(self):
result = self.science.scientist()
parent_file = pull('scientist', self.science.lang)
self.assertIn(result + '\n', parent_file)
def test_chemical_element(self):
result = self.science.chemical_element(name_only=True)
self.assertGreater(len(result), 2)
_result = self.science.chemical_element(name_only=False)
self.assertIsInstance(_result, dict)
class DevelopmentTestCase(TestCase):
def setUp(self):
self.dev = Development()
def tearDown(self):
del self.dev
def test_license(self):
result = self.dev.software_license()
self.assertIn(result, common.LICENSES)
def test_version(self):
result = self.dev.version().split('.')
major = int(result[0])
self.assertTrue((major >= 0) and (major <= 11))
minor = int(result[1])
self.assertTrue((minor >= 0) and (minor <= 11))
micro = int(result[2])
self.assertTrue((micro >= 0) and (micro <= 11))
def test_programming_language(self):
result = self.dev.programming_language()
self.assertIn(result, common.PROGRAMMING_LANGS)
def test_database(self):
result = self.dev.database()
self.assertIn(result, common.SQL)
_result = self.dev.database(nosql=True)
self.assertIn(_result, common.NOSQL)
def test_other(self):
result = self.dev.other()
self.assertIn(result, common.OTHER_TECH)
def test_framework(self):
result = self.dev.framework(_type='front')
self.assertIn(result, common.FRONTEND)
_result = self.dev.framework(_type='back')
self.assertIn(_result, common.BACKEND)
def test_stack_of_tech(self):
result = self.dev.stack_of_tech(nosql=True)
self.assertIsInstance(result, dict)
def test_os(self):
result = self.dev.os()
self.assertIn(result, common.OS)
def test_stackoverflow_question(self):
url = self.dev.stackoverflow_question()
post_id = int(url.split('/')[-1])
self.assertTrue((post_id >= 1000000) and
(post_id <= 9999999))
class FoodTestCase(TestCase):
def setUp(self):
self.food = Food(LANG)
def tearDown(self):
del self.food
def test_berry(self):
result = self.food.berry()
parent_file = pull('berries', self.food.lang)
self.assertIn(result + '\n', parent_file)
def test_vegetable(self):
result = self.food.vegetable()
parent_file = pull('vegetables', self.food.lang)
self.assertIn(result + '\n', parent_file)
def test_fruit(self):
result = self.food.fruit()
parent_file = pull('fruits', self.food.lang)
self.assertIn(result + '\n', parent_file)
def test_dish(self):
result = self.food.dish()
parent_file = pull('dishes', self.food.lang)
self.assertIn(result + '\n', parent_file)
def test_drink(self):
result = self.food.drink()
parent_file = pull('drinks', self.food.lang)
self.assertIn(result + '\n', parent_file)
def test_spices(self):
result = self.food.spices()
parent_file = pull('spices', self.food.lang)
self.assertIn(result + '\n', parent_file)
def test_mushroom(self):
result = self.food.mushroom()
parent_file = pull('mushrooms', self.food.lang)
self.assertIn(result + '\n', parent_file)
class HardwareTestCase(TestCase):
def setUp(self):
self.hard = Hardware()
def tearDown(self):
del self.hard
def test_resolution(self):
result = self.hard.resolution()
self.assertIn(result, common.RESOLUTIONS)
def test_screen_size(self):
result = self.hard.screen_size()
self.assertIn(result, common.SCREEN_SIZES)
def test_generation(self):
result = self.hard.generation()
self.assertIn(result, common.GENERATION)
def test_cpu_frequency(self):
result = self.hard.cpu_frequency().split('G')[0]
self.assertLess(float(result), 4.4)
def test_cpu(self):
result = self.hard.cpu()
self.assertIn(result, common.CPU)
def test_cpu_codename(self):
result = self.hard.cpu_codename()
self.assertIn(result, common.CPU_CODENAMES)
def test_ram_type(self):
result = self.hard.ram_type()
self.assertIn(result, ['DDR2', 'DDR3', 'DDR4'])
def test_ram_size(self):
result = self.hard.ram_size().split(' ')
self.assertGreater(len(result), 0)
def test_ssd_or_hdd(self):
result = self.hard.ssd_or_hdd()
self.assertIn(result, common.MEMORY)
def test_graphics(self):
result = self.hard.graphics()
self.assertIn(result, common.GRAPHICS)
def test_manufacturer(self):
result = self.hard.manufacturer()
self.assertIn(result, common.MANUFACTURERS)
def test_hardware_full(self):
result = self.hard.hardware_full_info()
self.assertGreater(len(result), 15)
def test_phone_model(self):
result = self.hard.phone_model()
self.assertIn(result, common.PHONE_MODELS)
class PullTestCase(TestCase):
def test_pull(self):
result = pull('views_on', 'en')
self.assertIsNotNone(result)
self.assertIsInstance(result, list)
self.assertRaises(
UnsupportedLocale, lambda: pull('views_on', 'spoke'))
self.assertRaises(
FileNotFoundError, lambda: pull('something', 'en'))
class ChurchTestCase(TestCase):
def setUp(self):
self.church = Church('en')
def test_personal(self):
result = self.church.personal.username()
self.assertIsNotNone(result)
def test_text(self):
result = self.church.text.words()
self.assertIsNotNone(result)
def test_address(self):
result = self.church.address.address()
self.assertIsNotNone(result)
def test_food(self):
result = self.church.food.fruit()
self.assertIsNotNone(result)
def test_science(self):
result = self.church.science.scientist()
self.assertIsNotNone(result)
def test_business(self):
result = self.church.business.copyright()
self.assertIsNotNone(result)
| [
"[email protected]"
] | |
1611536927117e0f2425a541aa43462b10ab69e1 | 1fcfb16bbcc4387c83212c559c824cde65664533 | /MAST-1.4.0/MAST/ingredients/checker/genericchecker.py | 633f5c2480ca4559e8918c99f9d2eb8ca9d2efa0 | [
"MIT"
] | permissive | ZhewenSong/USIT | 29a0b207f2a40c8d9ed865854cdac5f82c2281ee | aaa383b8d81c4755cdff22293ef4f0bfe7694cb4 | refs/heads/master | 2021-01-10T14:46:13.155077 | 2016-04-04T19:48:14 | 2016-04-04T19:48:14 | 53,438,454 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,391 | py | ##############################################################
# This code is part of the MAterials Simulation Toolkit (MAST)
#
# Maintainer: Tam Mayeshiba
# Last updated: 2014-04-25
##############################################################
from pymatgen.io.vaspio import Poscar
from pymatgen.io.vaspio import Outcar
from pymatgen.io.vaspio import Potcar
from pymatgen.io.vaspio import Incar
from pymatgen.io.vaspio import Kpoints
from pymatgen.core.structure import Structure
from MAST.utility import dirutil
from MAST.utility.mastfile import MASTFile
from MAST.utility import MASTError
from MAST.ingredients.checker import BaseChecker
from MAST.ingredients.checker import VaspChecker
import os
import logging
import pymatgen
import numpy as np
import time
import shutil
class GenericChecker(BaseChecker):
"""Generic checker functions
The generic program should accept an input file named "input.txt"
with separate lines of the format:
keyword <delimiter> value
The delimiter should be set in mast_input_delimiter:
mast_input_delimiter =
The default is mast_input_delimiter None, which corresponds to a space.
The generic program should be run as:
<mast_exec value>
for example, "python myscript.py input.txt"
The generic starting signal should be given by the presence of a file:
mast_started_file <filename>
The generic completion signal should be given in the ingredient
subsection in the $ingredients section of the input file as:
mast_complete_file <filename>
mast_complete_search <string to search for, for completion>
OR, use the value None in order to check
just the existence of the file.
Defaults to None.
"""
def __init__(self, **kwargs):
allowed_keys = {
'name' : (str, str(), 'Name of directory'),
'program_keys': (dict, dict(), 'Dictionary of program keywords'),
'structure': (Structure, None, 'Pymatgen Structure object')
}
BaseChecker.__init__(self, allowed_keys, **kwargs)
def is_complete(self):
"""Check for the existence of mast_complete_file (default), or
for a certain string, given by mast_complete_search"""
if not 'mast_complete_file' in self.keywords['program_keys'].keys():
raise MASTError(self.__class__.__name__, "No completion file indicated by mast_complete_file keyword for %s. Cannot determine whether run is complete." % self.keywords['name'])
return False
checkfile = os.path.join(self.keywords['name'],self.keywords['program_keys']['mast_complete_file'])
searchstr = None
if 'mast_complete_search' in self.keywords['program_keys'].keys():
searchstr = self.keywords['program_keys']['mast_complete_search']
if searchstr == "None":
searchstr = None
if os.path.isfile(checkfile):
if searchstr == None:
return True
else:
tempopen = MASTFile(checkfile)
mymatch = tempopen.get_last_line_match(searchstr)
if mymatch == None:
return False
else:
return True
else:
return False
def is_ready_to_run(self):
"""Generic program is ready to run if the input.txt file
has been written, and if any files in
mast_copy_files are present.
The mast_copy_files keyword must be a space-delimited list of full file paths.
"""
dirname = self.keywords['name']
notready=0
if not(os.path.isfile(dirname + "/input.txt")):
notready = notready + 1
if 'mast_copy_files' in self.keywords['program_keys'].keys():
myfiles = self.keywords['program_keys']['mast_copy_files'].split()
for myfile in myfiles:
fname = os.path.basename(myfile)
if not os.path.isfile(os.path.join(dirname, fname)):
notready = notready + 1
if notready > 0:
return False
else:
return True
def _copy_over_any_files(self):
"""
The mast_copy_files ingredient keyword must be a
space-delimited list of full file paths:
mast_copy_files //home/user/f1 //home/user/f2
"""
dirname = self.keywords['name']
if 'mast_copy_files' in self.keywords['program_keys'].keys():
myfiles = self.keywords['program_keys']['mast_copy_files'].split()
for myfile in myfiles:
fname = os.path.basename(myfile)
if not os.path.isfile(os.path.join(dirname, fname)):
shutil.copy(myfile, os.path.join(dirname, fname))
def _phon_poscar_setup(self):
"""Set up a PHON POSCAR file. Strip out the "elements" line (that is,
use VASP version 4 format. Also strip out anything beneath the atoms
line.
"""
name = self.keywords['name']
pospath = os.path.join(name, "POSCAR")
prepath = os.path.join(name, "POSCAR_prePHON")
if os.path.isfile(pospath): #Already done. Return.
return
my_poscar = Poscar.from_file(prepath)
my_poscar.selective_dynamics=None #unset SD if it is set
my_poscar.velocities=None #unset velocities
dirutil.lock_directory(name)
my_poscar.write_file(pospath)
dirutil.unlock_directory(name)
#pick up a copy and strip out the elements line.
mypfile = MASTFile(pospath)
myline6=mypfile.get_line_number(6)
if myline6.strip().split()[0].isalpha:
mypfile.modify_file_by_line_number(6,"D")
mypfile.to_file(pospath)
return
def _input_get_non_mast_keywords(self):
"""Sort out the non-mast keywords and make a dictionary."""
input_dict=dict()
#allowedpath = os.path.join(dirutil.get_mast_install_path(), 'MAST',
# 'ingredients','programkeys','phon_allowed_keywords.py')
#allowed_list = self._phon_inphon_get_allowed_keywords(allowedpath)
for key, value in self.keywords['program_keys'].iteritems():
if not key[0:5] == "mast_":
input_dict[key]=value
return input_dict
def _input_setup(self):
"""Set up the input.txt file. Note that this is not the recipe
input file, it is the ingredient input file.
"""
name=self.keywords['name']
myd = dict()
myd = self._input_get_non_mast_keywords()
my_input = MASTFile()
if not 'mast_delimiter' in self.keywords['program_keys'].keys():
delim = " "
else:
delim = self.keywords['program_keys']['mast_delimiter']
if delim == "None":
delim = " "
for key, value in myd.iteritems():
my_input.data.append(str(key) + delim + str(value) + "\n")
my_input.to_file(name + "/input.txt")
self._copy_over_any_files()
return
def set_up_program_input(self):
"""For the generic program, MAST will only set up the input.txt
file. All other necessary files must be previously set up and
located in the input.txt file, for example:
StartingFile = ~/structurebank/startingstructure.xyz
in input.txt. This file will not be created by MAST.
"""
self._input_setup()
return
def is_started(self):
"""See if the ingredient has been started on
the queue. For the generic program, a signal file must
be specified in the ingredients keywords as mast_started_file
"""
if not 'mast_started_file' in self.keywords['program_keys'].keys():
raise MASTError(self.__class__.__name__, "No file indicated by mast_started_file keyword for %s. Cannot determine whether run has started." % self.keywords['name'])
return False
checkfile = os.path.join(self.keywords['name'],self.keywords['program_keys']['mast_started_file'])
if os.path.isfile(checkfile):
return True
else:
return False
| [
"[email protected]"
] | |
c98db546b314ceed3b99d5a290116ca53e79c0be | 5e45f1d1d9f58aa1456777b0d75334d6efd43840 | /challenges/contests/code_forces/round310/b.py | ddeeef394ad7437d7d538332cc5b25d2b0c84464 | [] | no_license | missingdays/nerdy.school | 604953dc9b3c38a0f71793f066ce2707aa980dae | 051673e0ebc54bc2f7e96a6477697d1d528dc45c | refs/heads/master | 2021-01-17T08:10:19.558851 | 2016-06-06T15:29:01 | 2016-06-06T15:29:01 | 59,897,184 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 777 | py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 missingdays <missingdays@missingdays>
#
# Distributed under terms of the MIT license.
"""
"""
def rotate(a, n):
clock = True
for i in range(n):
if clock:
if a[i] == n-1:
a[i] = 0
else:
a[i] += 1
else:
if a[i] == 0:
a[i] = n-1
else:
a[i] -= 1
clock = not clock
return a
def check(a):
for i in range(len(a)):
if a[i] != i:
return False
return True
n = int(input())
a = list(map(int, input().split()))
while a[0] != 0:
a = rotate(a, n)
yes = check(a)
if yes:
print("YES")
else:
print("NO")
| [
"[email protected]"
] | |
2d226f5e77c40290e347888ab04c3fd10c6a2a14 | d92330be8ea281bdfefff5d17039b1a6d44057dc | /src/stiamro/startup.py | 478af5d7aa11eaad8202de82c16120520a35f02a | [] | no_license | avoinea/stiamro | 2af6f2329abafb59b7e6b54abacb95c8f6b3d697 | 5ee6ec3b754a776cb87a9fa452e21cb2afbf38f9 | refs/heads/master | 2021-01-18T14:38:49.669592 | 2011-03-11T10:39:44 | 2011-03-11T10:39:44 | 1,397,488 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,354 | py | import os
import sys
import code
import zdaemon.zdctl
import zope.app.wsgi
import zope.app.debug
def application_factory(global_conf, conf='zope.conf'):
zope_conf = os.path.join(global_conf['here'], conf)
return zope.app.wsgi.getWSGIApplication(zope_conf)
def interactive_debug_prompt(zope_conf='zope.conf'):
db = zope.app.wsgi.config(zope_conf)
debugger = zope.app.debug.Debugger.fromDatabase(db)
# Invoke an interactive interpreter shell
banner = ("Welcome to the interactive debug prompt.\n"
"The 'root' variable contains the ZODB root folder.\n"
"The 'app' variable contains the Debugger, 'app.publish(path)' "
"simulates a request.")
code.interact(banner=banner, local={'debugger': debugger,
'app': debugger,
'root': debugger.root()})
class ControllerCommands(zdaemon.zdctl.ZDCmd):
def do_debug(self, rest):
interactive_debug_prompt()
def help_debug(self):
print "debug -- Initialize the application, providing a debugger"
print " object at an interactive Python prompt."
def zdaemon_controller(zdaemon_conf='zdaemon.conf'):
args = ['-C', zdaemon_conf] + sys.argv[1:]
zdaemon.zdctl.main(args, options=None, cmdclass=ControllerCommands)
| [
"alin@serenity.(none)"
] | alin@serenity.(none) |
0823d037b25810b90b0805adedcdad019270008c | 301b039050c00a9efa4f3a5635e8b633f8adf988 | /caffe2/experiments/python/SparseTransformer.py | c09bb09574798a2db7772eb526185e515e98feb4 | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | permissive | sunpan822/caffe2 | 9704b6fe556d272fbedfd6edfdb796f6a8f02970 | a3c56d892eb85054b4e7cbd1cf0a0d07422ae796 | refs/heads/master | 2020-04-12T14:31:45.919799 | 2019-04-19T04:10:40 | 2019-04-19T04:10:40 | 162,555,100 | 1 | 0 | Apache-2.0 | 2018-12-20T09:14:48 | 2018-12-20T09:14:47 | null | UTF-8 | Python | false | false | 6,362 | py | ## @package SparseTransformer
# Module caffe2.experiments.python.SparseTransformer
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import workspace
import scipy.sparse
class NetDefNode():
def __init__(self, name, optype, p=None, op=None):
self.name = name
self.optype = optype
self.ops = {}
self.prev = {}
self.insertInput(p)
self.visited = False
self.op = op
def insertInput(self, p):
"""
Insert input of this op
also maintain the output of previous op
p: a node or a list of node
"""
if isinstance(p, list):
for i in p:
self.prev[i.name] = i
i.ops[self.name] = self
elif isinstance(p, NetDefNode):
self.prev[p.name] = p
p.ops[self.name] = self
def deleteInput(self, p):
if isinstance(p, NetDefNode):
del self.prev[p.name]
del p.ops[self.name]
def maskNallocate(weight_name):
"""
Combine mask and weights
create wcsr, iw, jw, return their names
"""
w = workspace.FetchBlob(weight_name)
w_csr = scipy.sparse.csr_matrix(w)
wcsr = w_csr.data
iw = w_csr.indptr
jw = w_csr.indices
workspace.FeedBlob(weight_name + "wcsr", wcsr)
workspace.FeedBlob(weight_name + "iw", iw)
workspace.FeedBlob(weight_name + "jw", jw)
return weight_name + "wcsr", weight_name + "iw", weight_name + "jw"
def transFCRelu(cur, id2node, name2id, ops, model):
"""
Add trans before and after this FC_Prune->(Relu)->FC_Prune chain.
"""
# 1. add trans before the start of this chain
# assuming that cur is a FC_Prune, and it has only one input
pre = cur.prev.itervalues().next()
# Create a node /op and insert it.
# TODO(wyiming): check whether it is correct here
current_blob = model.Transpose(cur.op.input[0], cur.op.input[0] + "_trans")
# print model.net.Proto()
trans_op = model.net.Proto().op[-1]
trans_node = NetDefNode(trans_op.output[0], "Transpose", pre, trans_op)
trans_node.visited = True
pre_new = trans_node
# 2. use while loop to visit the chain
while True:
# breakup with the parent
cur.deleteInput(pre)
if not (cur.optype == "FC_Prune" or cur.optype == "Relu"):
print("Reaching the end of the chain")
break
if len(cur.ops) > 1:
print("A FC/Relu giving more than 1 useful outputs")
if cur.optype == "FC_Prune":
op = cur.op
wcsr, iw, jw = maskNallocate(op.input[1])
bias_name = op.input[3]
# TODO(wyiming): create a new Op here
current_blob = model.FC_Sparse(current_blob,
cur.op.output[0] + "_Sparse",
wcsr, iw, jw, bias_name)
sps_op = model.net.Proto().op[-1]
sps_node = NetDefNode(cur.op.output[0] + "_Sparse",
"FC_Sparse",
pre_new, sps_op)
sps_node.visited = True
pre_new = sps_node
if cur.optype == "Relu":
op = cur.op
current_blob = model.Relu(current_blob, current_blob)
rel_op = model.net.Proto().op[-1]
rel_node = NetDefNode(str(current_blob), "Relu",
pre_new, rel_op)
rel_node.visited = True
pre_new = rel_node
cur.visited = True
pre = cur
flag = False
for _, temp in cur.ops.iteritems():
if temp.optype == "Relu" or temp.optype == "FC_Prune":
flag = True
cur = temp
if not flag:
# assume that there is only 1 output that is not PrintOP
cur = cur.ops.itervalues().next()
cur.deleteInput(pre)
print("No FC/RElu children")
print(cur.op.type)
break
# 3. add trans after this chain like 1.
current_blob = model.Transpose(current_blob, pre.op.output[0])
trans_op = model.net.Proto().op[-1]
trans_node = NetDefNode(str(current_blob), "Transpose", pre_new, trans_op)
trans_node.visited = True
cur.insertInput(trans_node)
print(cur.prev)
print(trans_node.ops)
def Prune2Sparse(cur, id2node, name2id, ops, model):
# Assume that FC and Relu takes in only 1 input;
# If not raise warning
if not cur.visited and cur.optype == "FC_Prune":
transFCRelu(cur, id2node, name2id, ops, model)
cur.visited = True
for name, n in cur.ops.iteritems():
Prune2Sparse(n, id2node, name2id, ops, model)
def net2list(net_root):
"""
Use topological order(BFS) to print the op of a net in a list
"""
bfs_queue = []
op_list = []
cur = net_root
for _, n in cur.ops.iteritems():
bfs_queue.append(n)
while bfs_queue:
node = bfs_queue[0]
bfs_queue = bfs_queue[1:]
op_list.append(node.op)
for _, n in node.ops.iteritems():
bfs_queue.append(n)
return op_list
def netbuilder(model):
print("Welcome to model checker")
proto = model.net.Proto()
net_name2id = {}
net_id2node = {}
net_root = NetDefNode("net_root", "root", None)
for op_id, op in enumerate(proto.op):
if op.type == "Print":
continue
op_name = '%s/%s (op#%d)' % (op.name, op.type, op_id) \
if op.name else '%s (op#%d)' % (op.type, op_id)
# print(op_name)
op_node = NetDefNode(op_name, op.type, op=op)
net_id2node[op_id] = op_node
if_has_layer_input = False
for input_name in op.input:
if input_name not in net_name2id:
# assume that un_occured name are non_layers
# TODO: write a non-layer checker and log it
continue
op_node.insertInput(net_id2node[net_name2id[input_name]])
if_has_layer_input = True
if not if_has_layer_input:
op_node.insertInput(net_root)
for output_name in op.output:
net_name2id[output_name] = op_id
return net_root, net_name2id, net_id2node
| [
"[email protected]"
] | |
10d6c38f461f0064766acde067ce1501198f039b | b92b0e9ba2338ab311312dcbbeefcbb7c912fc2e | /build/shogun_lib/applications/edrt/tutorial_examples/isomap.py | 968afc975fb56b891080841483da3d0476df5337 | [] | no_license | behollis/muViewBranch | 384f8f97f67723b2a4019294854969d6fc1f53e8 | 1d80914f57e47b3ad565c4696861f7b3213675e0 | refs/heads/master | 2021-01-10T13:22:28.580069 | 2015-10-27T21:43:20 | 2015-10-27T21:43:20 | 45,059,082 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,100 | py | import modshogun as sg
import data
import numpy as np
# load data
feature_matrix = data.swissroll()
# create features instance
features = sg.RealFeatures(feature_matrix)
# create Isomap converter instance
converter = sg.Isomap()
# set target dimensionality
converter.set_target_dim(2)
# compute embedding with Isomap method
embedding = converter.embed(features)
# enable landmark approximation
converter.set_landmark(True)
# set number of landmarks
converter.set_landmark_number(100)
# set number of threads
converter.parallel.set_num_threads(2)
# compute approximate embedding
approx_embedding = converter.embed(features)
# disable landmark approximation
converter.set_landmark(False)
# compute cosine distance matrix 'manually'
N = features.get_num_vectors()
distance_matrix = np.zeros((N,N))
for i in range(N):
for j in range(N):
distance_matrix[i,j] = \
np.cos(np.linalg.norm(feature_matrix[:,i]-feature_matrix[:,j],2))
# create custom distance instance
distance = sg.CustomDistance(distance_matrix)
# construct embedding based on created distance
converter.embed_distance(distance)
| [
"prosen@305cdda6-5ce1-45b3-a98d-dfc68c8b3305"
] | prosen@305cdda6-5ce1-45b3-a98d-dfc68c8b3305 |
7e22946ff315b5f228a8591af59455b54238cba7 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03151/s822034196.py | 4313c1c0f2ac588afa27facef6408828aef26183 | [] | 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 | 431 | py | n = int(input())
a_list = list(map(int, input().split()))
b_list = list(map(int, input().split()))
if sum(a_list) < sum(b_list):
print(-1)
exit()
a_sub_b = [a_list[i] - b_list[i] for i in range(n)]
insufficients = [x for x in a_sub_b if x < 0]
cnt = len(insufficients)
sum_insuf = sum(insufficients)
for x in sorted(a_sub_b, reverse=True):
if sum_insuf >= 0:
break
sum_insuf += x
cnt += 1
print(cnt)
| [
"[email protected]"
] | |
788ba397c4eae832f0db90c5895d6a977650d8ce | 98c6ea9c884152e8340605a706efefbea6170be5 | /examples/data/Assignment_8/crnkee002/question2.py | cb2b9f4a82509a3b49d881ae545369931ced4326 | [] | no_license | MrHamdulay/csc3-capstone | 479d659e1dcd28040e83ebd9e3374d0ccc0c6817 | 6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2 | refs/heads/master | 2021-03-12T21:55:57.781339 | 2014-09-22T02:22:22 | 2014-09-22T02:22:22 | 22,372,174 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 694 | py | """A8Q2 - Character Pairs
5/3/2012
CRNKEE002"""
def main():
message = input('Enter a message:\n')
print('Number of pairs:', double_chars(0, message))
def double_chars(pos, word):
if len(word) == 1 or len(word) == 0:
return 0
elif (word[pos] == word[pos+1]) and (pos+1 == len(word)-1):
return 1
elif (word[pos] == word[pos+1]) and (pos+1 < len(word)-1):
return 1 + double_chars(0, word[2::])
elif (word[pos] != word[pos+1]) and (pos+1 == len(word)-1):
return 0
elif (word[pos] != word[pos+1]) and (pos+1 < len(word)-1):
return double_chars(0, word[1::])
if __name__ == '__main__':
main() | [
"[email protected]"
] | |
d0cac88d4a8c7145000a7513167b23dddeb83fc1 | f2f88a578165a764d2ebb4a022d19e2ea4cc9946 | /pyvisdk/do/host_vmci_access_manager_access_spec.py | 3be9649b6bb56dbd6ab8a434dee41655e7e84b7b | [
"MIT"
] | permissive | pombredanne/pyvisdk | 1ecc68a1bf264095f72f274c776e5868fb302673 | de24eb4426eb76233dc2e57640d3274ffd304eb3 | refs/heads/master | 2021-01-21T16:18:39.233611 | 2014-07-28T19:50:38 | 2014-07-28T19:50:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,363 | py |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def HostVmciAccessManagerAccessSpec(vim, *args, **kwargs):
'''The AccessSpec data object declares an update to the service access granted to
a VM. The given list of services will either be granted in addition to existing
services, replace the existing service or be revoked depending on the mode
specified. In case of a revoke, an empty or non-existing service list indicates
that all granted services should be revoked.'''
obj = vim.client.factory.create('ns0:HostVmciAccessManagerAccessSpec')
# do some validation checking...
if (len(args) + len(kwargs)) < 2:
raise IndexError('Expected at least 3 arguments got: %d' % len(args))
required = [ 'mode', 'vm' ]
optional = [ 'services', 'dynamicProperty', 'dynamicType' ]
for name, arg in zip(required+optional, args):
setattr(obj, name, arg)
for name, value in kwargs.items():
if name in required + optional:
setattr(obj, name, value)
else:
raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional)))
return obj
| [
"[email protected]"
] | |
1b172b649cf62bea7e4b718c542cb3c43cb28435 | d38a37c6997f2282b2138fc0a74a82996940dade | /loginapp/views.py | 62e1e750131eabd25d674f07cffda8e604f17a49 | [] | no_license | ethicalrushi/SignUp | 9a295c0dcf20ea7eb47fe4af968b0c3d0caf6532 | 6deac079539bb9281f32f19e027d47436d59ce3d | refs/heads/master | 2020-03-08T13:25:28.023977 | 2018-04-05T15:13:08 | 2018-04-05T15:13:08 | 128,157,728 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,319 | py | from django.shortcuts import render
from .forms import UserForm
from .models import User
from django.contrib.auth.hashers import make_password, check_password
from django.http import HttpResponse
from rest_framework.response import Response
from rest_framework import status, viewsets
from .serializers import UserSerializer
from django.http import JsonResponse
import json
from django.views.generic.base import View
from django.urls import resolve
# Create your view
def register(request):
form = UserForm()
if request.method == 'POST':
form = UserForm(request.POST, request.FILES)
if form.is_valid():
password = form.cleaned_data['password']
print(password)
user = User()
user.password = make_password(password)
user.username = form.cleaned_data['username']
user.fullname = form.cleaned_data['fullname']
user.image = form.cleaned_data['image']
user.save()
print(user.password)
else:
print(form.errors)
return render(request,'register.html',{'form':form,})
else:
return render(request,'register.html',{'form':form,})
return render(request,'register.html',{'form':form,})
class DisplayViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class= UserSerializer
def dataview(request):
return render(request,'data.html') | [
"[email protected]"
] | |
ba51dcc9f9c7d92cde27dcd455523ff50ad8d58e | 8930d812d545e4a67be14b928212878befa1a535 | /primes/euler0124.py | 393a0d38105dda9afc7ccd0dea331099a4a39243 | [] | no_license | jwodder/euler | bd59935e9f359e8760b4140243c907a6c44247b8 | 7549bb38dba746a04dcaa021f0c7dc06342d078b | refs/heads/master | 2020-12-22T20:20:29.311514 | 2016-08-06T01:28:33 | 2016-08-06T01:28:33 | 21,482,466 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,028 | py | #!/usr/bin/python
r"""Ordered radicals
The radical of $n$, $rad(n)$, is the product of the distinct prime factors
of $n$. For example, $504 = 2^3\times 3^2\times 7$, so $rad(504) = 2\times
3\times 7 = 42$.
If we calculate $rad(n)$ for $1\leq n\leq 10$, then sort them on $rad(n)$,
and sorting on $n$ if the radical values are equal, we get:
**Unsorted** **Sorted**
$n$ $rad(n)$ $n$ $rad(n)$ $k$
1 1 1 1 1
2 2 2 2 2
3 3 4 2 3
4 2 8 2 4
5 5 3 3 5
6 6 9 3 6
7 7 5 5 7
8 2 6 6 8
9 3 7 7 9
10 10 10 10 10
Let $E(k)$ be the $k$th element in the sorted $n$ column; for example,
$E(4) = 8$ and $E(6) = 9$.
If $rad(n)$ is sorted for $1\leq n\leq 100000$, find $E(10000)$."""
import sys; sys.path.insert(1, sys.path[0] + '/..')
from eulerlib import primeIter, generateAsc
__tags__ = ['radical', 'prime numbers', 'ordering', 'factorization']
bound = 100000
index = 10000
def solve():
primes = tuple(primeIter(bound=bound))
seen = 0
def nextNodes(x):
rad, ps, nextI = x
if nextI < len(primes):
nextP = primes[nextI]
yield (rad*nextP, ps+[nextP], nextI+1)
if ps:
yield (rad//ps[-1] * nextP, ps[:-1]+[nextP], nextI+1)
for (rad, ps, nextI) in generateAsc([(1,[],0)], nextNodes):
expses = [rad]
for p in ps:
for x in expses[:]:
x *= p
while x <= bound:
expses.append(x)
x *= p
seen += len(expses)
if seen >= index:
expses.sort()
return expses[index - seen - 1]
if __name__ == '__main__':
print solve()
| [
"[email protected]"
] | |
9dfda40d614bb48a5fe3ab1fc73a182b42c25ced | 6846a0469efc79b89edc8f856944d5a8005d7244 | /id_0060.py | 01b7c31aa52da90e0370908d86d70201e6913a1f | [] | no_license | CGenie/project_euler | 42cb966e13645339490046eb44a729660ae0c092 | cc90edd061b0f4d9e076d5a684b842c202a6812a | refs/heads/master | 2020-06-05T00:41:49.266961 | 2014-01-13T19:11:31 | 2014-01-13T19:11:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,663 | py | #!/usr/bin/python2
# #####################################################################
# id_0060.py
#
# Przemyslaw Kaminski <[email protected]>
# Time-stamp: <>
######################################################################
import pickle
from itertools import combinations
from id_0003 import is_prime
if __name__ == '__main__':
f = open("./primes.pickle")
lst_primes = pickle.load(f)
f.close()
n = 0
# for primes in combinations(lst_primes[1:500], 5):
# nice_four = True
# if n % 100 == 0:
# n = 1
# print "Testing " + str(primes)
# for doubles in combinations(primes, 2):
# p1 = int(''.join([str(doubles[0]), str(doubles[1])]))
# p2 = int(''.join([str(doubles[1]), str(doubles[0])]))
# if not p1 in lst_primes or not p2 in lst_primes:
# nice_four = False
# break
# if nice_four:
# print "A nice five has been found: " + str(primes)
# print "The sum is " + str(sum(primes))
# foo = input("Press enter to continue...")
# n += 1
join_nums = lambda x, y: int(''.join([str(x), str(y)]))
for idx, x in enumerate(lst_primes):
if x > 10000:
break
maxidx = idx
for a in xrange(5, maxidx):
pa = lst_primes[a]
for b in xrange(a, maxidx):
pb = lst_primes[b]
# check this pair first
pab = join_nums(pa, pb)
pba = join_nums(pb, pa)
#if pab in lst_primes and pba in lst_primes:
if is_prime(pab) and is_prime(pba):
print "%d, %d ok so far..." % (pa, pb)
for c in xrange(b, maxidx):
pc = lst_primes[c]
pac = join_nums(pa, pc)
pca = join_nums(pc, pa)
pbc = join_nums(pb, pc)
pcb = join_nums(pc, pb)
#print "Testing %d with pac = %d, pca = %d, pbc = %d, pcb = %d" % (pc, pac, pca, pbc, pcb)
#if pac in lst_primes and pca in lst_primes and pbc in lst_primes and pcb in lst_primes:
if is_prime(pac) and is_prime(pca) and is_prime(pbc) and is_prime(pcb):
print "%d, %d, %d ok so far..." % (pa, pb, pc)
for d in xrange(c, maxidx):
nice_four = True
pd = lst_primes[d]
pad = join_nums(pa, pd)
pda = join_nums(pd, pa)
pbd = join_nums(pb, pd)
pdb = join_nums(pd, pb)
pcd = join_nums(pc, pd)
pdc = join_nums(pd, pc)
#print "pad = %d, pda = %d, pbd = %d, pdb = %d, pcd = %d, pdc = %d" % (pad, pda, pbd, pdb, pcd, pdc)
for pp in [pad, pda, pbd, pdb, pcd, pdc]:
#if not pp in lst_primes:
if not is_prime(pp):
nice_four = False
break
if nice_four:
print "%d, %d, %d, %d ok so far..." % (pa, pb, pc, pd)
for e in xrange(d, maxidx):
nice_five = True
pe = lst_primes[e]
pae = join_nums(pa, pe)
pea = join_nums(pe, pa)
pbe = join_nums(pb, pe)
peb = join_nums(pe, pb)
pce = join_nums(pc, pe)
pec = join_nums(pe, pc)
pde = join_nums(pd, pe)
ped = join_nums(pe, pd)
for pp in [pae, pea, pbe, peb, pce, pec, pde, ped]:
#if not pp in lst_primes:
if not is_prime(pp):
nice_five = False
break
if nice_five:
print "A nice five has been found: %d, %d, %d, %d, %d" % (pa, pb, pc, pd, pe)
print "The sum is " + str(sum([pa, pb, pc, pd, pe]))
foo = input("Press enter to continue...")
| [
"[email protected]"
] | |
86d8efefc0aaa304a58e7c9b58202117545fbf48 | 03ac34ae59b3d85b1876a9ca61e08c0b7020537c | /myproject/pages/tests.py | 49bde0bf4c1a592e8d6c4a196c1ff01db6c1fbf1 | [] | no_license | pramodkumarpanda/http-django.repo | 1e94890a50ef59166cbe1919791cdac6ca73b21c | 9551a5991f9dda76674a442598eb14c2cf2312cb | refs/heads/master | 2020-07-02T10:32:58.668280 | 2019-10-21T15:28:37 | 2019-10-21T15:28:37 | 201,500,715 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,203 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
# Create your tests here.
from django.http import HttpRequest
#from django.test import SimpleTestCase
from django.urls import reverse
from django.test import TestCase,SimpleTestCase
from . import views
from .models import Post
class HomePageTests(SimpleTestCase):
def test_home_page_status_code(self):
response = self.client.get('/')
self.assertEquals(response.status_code, 200)
def test_view_url_by_name(self):
response = self.client.get(reverse('home'))
self.assertEquals(response.status_code, 200)
def test_view_uses_correct_template(self):
response = self.client.get(reverse('home'))
self.assertEquals(response.status_code, 200)
self.assertTemplateUsed(response, 'home.html')
def test_home_page_contains_correct_html(self):
response = self.client.get('/')
self.assertContains(response, '<h1>Homepage</h1>')
def test_home_page_does_not_contain_incorrect_html(self):
response = self.client.get('/')
self.assertNotContains(
response, 'Hi there! I should not be on the page.')
| [
"user@localhost"
] | user@localhost |
1cca13ce33cc9925a5981731585f0970d3da571e | e3f3b986b256911e43496fe91c463f79dda9b334 | /customauth/migrations/0006_remove_user_is_moderator.py | 3692f715b5ea627df4ca42712fb605ba20be132a | [] | no_license | itkpi/itkpimail | e2ca56849c1ca18dec0b9c7d661b3563ed1f2ffe | 6622208ca36d322e61821935804b2367f956d0b6 | refs/heads/master | 2021-01-01T19:07:29.107033 | 2015-11-08T18:57:45 | 2015-11-08T18:57:45 | 34,176,219 | 3 | 1 | null | 2018-12-09T05:00:27 | 2015-04-18T17:52:20 | JavaScript | UTF-8 | Python | false | false | 358 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('customauth', '0005_user_is_moderator'),
]
operations = [
migrations.RemoveField(
model_name='user',
name='is_moderator',
),
]
| [
"[email protected]"
] | |
35178571ff5eaafb96690f4636cddb7b8642190d | a4e4c3faa29043fc80f62a8442e2f8333cd23933 | /U_Net/primitives.py | cee4c15d4e046dc3f71f456fa4a622db17cc0c77 | [] | no_license | FangYang970206/Intrinsic_Image | 652ab87c2d95b400cf80c6a49d1863a40d1cba07 | 3b8ec261b7b3aeaa1c611473f53fb4e23b82893b | refs/heads/master | 2023-01-21T05:18:40.748488 | 2020-11-24T02:22:00 | 2020-11-24T02:22:00 | 228,824,635 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,432 | py | import sys, torch, torch.nn as nn, torch.nn.functional as F
from torch.autograd import Variable
def conv(in_channels, out_channels, kernel_size, stride, padding):
convolution = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding)
batch_norm = nn.BatchNorm2d(out_channels)
layer = nn.Sequential(convolution, batch_norm)
return layer
## Returns function to concatenate tensors.
## Used in skip layers to join encoder and decoder layers.
def join(ind):
return lambda x, y: torch.cat( (x,y), ind )
## channels : list of ints
## kernel_size : int
## padding : int
## stride_fn : fn(channel_index) --> int
## mult=1 if encoder, 2 if decoder
def build_encoder(channels, kernel_size, padding, stride_fn, mult=1):
layers = []
sys.stdout.write( ' %3d' % channels[0] )
for ind in range(len(channels)-1):
m = 1 if ind == 0 else mult
in_channels = channels[ind] * m
out_channels = channels[ind+1]
stride = stride_fn(ind)
sys.stdout.write( ' --> %3d' % out_channels )
if ind < len(channels)-2:
block = conv(in_channels, out_channels, kernel_size, stride, padding)
else:
block = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding)
layers.append(block)
sys.stdout.write('\n')
sys.stdout.flush()
return nn.ModuleList(layers)
| [
"[email protected]"
] | |
cd7bdd6f7349ed620ec8caa3c68b3e698ce8989b | 4cf3f8845d64ed31737bd7795581753c6e682922 | /.history/main_20200118153146.py | 31e8805576c95a01bdfc7df75a0d30d9316d527b | [] | 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 | 323,675 | 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()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def 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]"
] | |
bf3e130b1bab3b6fcb044e25147092962b48fd91 | 1af49694004c6fbc31deada5618dae37255ce978 | /tools/metrics/histograms/merge_xml.py | d522fae6d1f2e541fa077ec5b9d3ced366c2ce53 | [
"LGPL-2.0-or-later",
"Zlib",
"BSD-3-Clause",
"MIT",
"LGPL-2.1-only",
"LicenseRef-scancode-unknown-license-reference",
"MPL-1.1",
"GPL-2.0-only",
"Apache-2.0",
"LGPL-2.0-only",
"LicenseRef-scancode-unknown",
"APSL-2.0"
] | permissive | sadrulhc/chromium | 59682b173a00269ed036eee5ebfa317ba3a770cc | a4b950c23db47a0fdd63549cccf9ac8acd8e2c41 | refs/heads/master | 2023-02-02T07:59:20.295144 | 2020-12-01T21:32:32 | 2020-12-01T21:32:32 | 317,678,056 | 3 | 0 | BSD-3-Clause | 2020-12-01T21:56:26 | 2020-12-01T21:56:25 | null | UTF-8 | Python | false | false | 7,451 | py | #!/usr/bin/env python
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A script to merge multiple source xml files into a single histograms.xml."""
import argparse
import os
import sys
import xml.dom.minidom
import expand_owners
import extract_histograms
import histogram_configuration_model
import histogram_paths
import populate_enums
def GetElementsByTagName(trees, tag, depth=2):
"""Gets all elements with the specified tag from a set of DOM trees.
Args:
trees: A list of DOM trees.
tag: The tag of the elements to find.
depth: The depth in the trees by which a match should be found.
Returns:
A list of DOM nodes with the specified tag.
"""
iterator = extract_histograms.IterElementsWithTag
return list(e for t in trees for e in iterator(t, tag, depth))
def GetEnumsNodes(doc, trees):
"""Gets all enums from a set of DOM trees.
If trees contain ukm events, populates a list of ints to the
"UkmEventNameHash" enum where each value is a ukm event name hash truncated
to 31 bits and each label is the corresponding event name.
Args:
doc: The document to create the node in.
trees: A list of DOM trees.
Returns:
A list of enums DOM nodes.
"""
enums_list = GetElementsByTagName(trees, 'enums')
ukm_events = GetElementsByTagName(
GetElementsByTagName(trees, 'ukm-configuration'), 'event')
# Early return if there are no ukm events provided. MergeFiles have callers
# that do not pass ukm events so, in that case, we don't need to iterate
# through the enum list.
if not ukm_events:
return enums_list
for enums in enums_list:
populate_enums.PopulateEnumsWithUkmEvents(doc, enums, ukm_events)
return enums_list
def CombineHistogramsSorted(doc, trees):
"""Sorts histograms related nodes by name and returns the combined nodes.
This function sorts nodes including <histogram>, <variant> and
<histogram_suffix>. Then it returns one <histograms> that contains the
sorted <histogram> and <variant> nodes and the other <histogram_suffixes_list>
node containing all <histogram_suffixes> nodes.
Args:
doc: The document to create the node in.
trees: A list of DOM trees.
Returns:
A list containing the combined <histograms> node and the combined
<histogram_suffix_list> node.
"""
# Create the combined <histograms> tag.
combined_histograms = doc.createElement('histograms')
def SortByLowerCaseName(node):
return node.getAttribute('name').lower()
variants_nodes = GetElementsByTagName(trees, 'variants', depth=3)
sorted_variants = sorted(variants_nodes, key=SortByLowerCaseName)
histogram_nodes = GetElementsByTagName(trees, 'histogram', depth=3)
sorted_histograms = sorted(histogram_nodes, key=SortByLowerCaseName)
for variants in sorted_variants:
# Use unsafe version of `appendChild` function here because the safe one
# takes a lot longer (10000x) to append all children. The unsafe version
# is ok here because:
# 1. the node to be appended is a clean node.
# 2. The unsafe version only does fewer checks but not changing any
# behavior and it's documented to be usable if performance matters.
# See https://github.com/python/cpython/blob/2.7/Lib/xml/dom/minidom.py#L276.
xml.dom.minidom._append_child(combined_histograms, variants)
for histogram in sorted_histograms:
xml.dom.minidom._append_child(combined_histograms, histogram)
# Create the combined <histogram_suffixes_list> tag.
combined_histogram_suffixes_list = doc.createElement(
'histogram_suffixes_list')
histogram_suffixes_nodes = GetElementsByTagName(trees,
'histogram_suffixes',
depth=3)
sorted_histogram_suffixes = sorted(histogram_suffixes_nodes,
key=SortByLowerCaseName)
for histogram_suffixes in sorted_histogram_suffixes:
xml.dom.minidom._append_child(combined_histogram_suffixes_list,
histogram_suffixes)
return [combined_histograms, combined_histogram_suffixes_list]
def MakeNodeWithChildren(doc, tag, children):
"""Creates a DOM node with specified tag and child nodes.
Args:
doc: The document to create the node in.
tag: The tag to create the node with.
children: A list of DOM nodes to add as children.
Returns:
A DOM node.
"""
node = doc.createElement(tag)
for child in children:
node.appendChild(child)
return node
def MergeTrees(trees, should_expand_owners):
"""Merges a list of histograms.xml DOM trees.
Args:
trees: A list of histograms.xml DOM trees.
should_expand_owners: Whether we want to expand owners for histograms.
Returns:
A merged DOM tree.
"""
doc = xml.dom.minidom.Document()
doc.appendChild(
MakeNodeWithChildren(
doc,
'histogram-configuration',
# This can result in the merged document having multiple <enums> and
# similar sections, but scripts ignore these anyway.
GetEnumsNodes(doc, trees) +
# Sort the <histogram> and <histogram_suffixes> nodes by name and
# return the combined nodes.
CombineHistogramsSorted(doc, trees)))
# After using the unsafe version of appendChild, we see a regression when
# pretty-printing the merged |doc|. This might because the unsafe appendChild
# doesn't build indexes for later lookup. And thus, we need to convert the
# merged |doc| to a xml string and convert it back to force it to build
# indexes for the merged |doc|.
doc = xml.dom.minidom.parseString(doc.toxml())
# Only perform fancy operations after |doc| becomes stable. This helps improve
# the runtime perforamnce.
if should_expand_owners:
for histograms in doc.getElementsByTagName('histograms'):
expand_owners.ExpandHistogramsOWNERS(histograms)
return doc
def MergeFiles(filenames=[], files=[], should_expand_owners=False):
"""Merges a list of histograms.xml files.
Args:
filenames: A list of histograms.xml filenames.
files: A list of histograms.xml file-like objects.
should_expand_owners: Whether we want to expand owners. By default, it's
false because most of the callers don't care about the owners for each
metadata.
Returns:
A merged DOM tree.
"""
all_files = files + [open(f) for f in filenames]
trees = [xml.dom.minidom.parse(f) for f in all_files]
return MergeTrees(trees, should_expand_owners)
def PrettyPrintMergedFiles(filenames=[], files=[]):
return histogram_configuration_model.PrettifyTree(
MergeFiles(filenames=filenames, files=files, should_expand_owners=True))
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--output', required=True)
args = parser.parse_args()
with open(args.output, 'w') as f:
# This is run by
# https://source.chromium.org/chromium/chromium/src/+/master:tools/metrics/BUILD.gn;drc=573e48309695102dec2da1e8f806c18c3200d414;l=5
# to send the merged histograms.xml to the server side. Providing |UKM_XML|
# here is not to merge ukm.xml but to populate `UkmEventNameHash` enum
# values.
f.write(PrettyPrintMergedFiles(
histogram_paths.ALL_XMLS + [histogram_paths.UKM_XML]))
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
51c20a8be35d9a81e63f1be880d978d0d13c9257 | 017033cc7094fd20334607e4c3e6e90bc5006687 | /django/api/index/migrations/0032_auto_20210607_1433.py | 92261d96b3f94ca8d42235adf992eaaf50474f0b | [] | no_license | HellMenDos/DjangoDockerPostgresSocket.io | cadc8cbc5ec1cd84b1e2455361f9a04ac557c73c | 88e4ff65cfc80df7932cffe23eee0ae221ec3519 | refs/heads/master | 2023-05-31T06:31:35.206756 | 2021-06-21T19:14:55 | 2021-06-21T19:14:55 | 367,129,423 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 441 | py | # Generated by Django 3.1.4 on 2021-06-07 14:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('index', '0031_auto_20210607_1431'),
]
operations = [
migrations.AlterField(
model_name='userdata',
name='avatar',
field=models.ImageField(blank=True, default='', upload_to='static', verbose_name='фото'),
),
]
| [
"[email protected]"
] | |
afae6fd7399ac8af7fc3a16e3a00a3201726ef74 | 1f006f0c7871fcde10986c4f5cec916f545afc9f | /apps/ice/plugins/pdf_utils/plugin_pdf_utils_test.py | 70219e5a0cb7c5d6363c9d19dc99114ee0ef7663 | [] | no_license | ptsefton/integrated-content-environment | 248b8cd29b29e8989ec1a154dd373814742a38c1 | c1d6b5a1bea3df4dde10cb582fb0da361dd747bc | refs/heads/master | 2021-01-10T04:46:09.319989 | 2011-05-05T01:42:52 | 2011-05-05T01:42:52 | 36,273,470 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,933 | py | #!/usr/bin/env python
# Copyright (C) 2007 Distance and e-Learning Centre,
# University of Southern Queensland
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
try:
from ice_common import IceCommon
IceCommon.setup()
except:
import sys, os
sys.path.append(os.getcwd())
sys.path.append(".")
os.chdir("../../")
from ice_common import IceCommon
sys.path.append("../utils")
from system import System, system
#import os
#import sys
#sys.path.append("../ice")
#from ice_common import IceCommon
#from pdf_utils import *
fs = IceCommon.FileSystem(".")
from plugin_pdf_utils import *
basePath = "plugins/pdf_utils/"
class MockIceContext(object):
def __init__(self, IceCommon):
self.fs = IceCommon.FileSystem(".")
self.system = system
self.xmlUtils = IceCommon.xmlUtils
self.rep = MockRep(self.fs)
self.isWindows = system.isWindows
self.isLinux = system.isLinux
self.isMac = system.isMac
class MockRep(object):
def __init__(self, fs):
self.__fs = fs
def getAbsPath(self, path):
return self.__fs.join(self.__fs.absolutePath(), path)
class PDFUtilsTests(IceCommon.TestCase):
def setUp(self):
self.iceContext = MockIceContext(IceCommon)
self.pdfUtils = PdfUtils(self.iceContext.fs)
#self.stdout = sys.stdout
#sys.stdout = StringIO()
def tearDown(self):
pass
#sys.stdout = self.stdout
def testInit(self):
pdfUtils = PdfUtils(self.iceContext.fs)
def testPdfFileNotExist(self):
testData = "%stestData/multipages1.pdf" % basePath
testDataAbsPath = self.iceContext.fs.absPath(testData)
pdfUtils = PdfUtils(self.iceContext.fs)
pdfReaderUtil = pdfUtils.pdfReader()
pdfReader = pdfReaderUtil.createPdfReader(testDataAbsPath)
self.assertEquals(pdfReader, None)
self.assertEquals(pdfReaderUtil.errMsg, \
'File /home/octalina/workspace/trunk/apps/ice/plugins/pdf_utils/testData/multipages1.pdf is not exist')
def testOpeningNormalPdf(self):
testData = "%stestData/multipages.pdf" % basePath
testDataAbsPath = self.iceContext.fs.absPath(testData)
pdfUtils = PdfUtils(self.iceContext.fs)
pdfReaderUtil = pdfUtils.pdfReader()
pdfReader = pdfReaderUtil.createPdfReader(testDataAbsPath)
self.assertEqual(isinstance(pdfReader, PdfFileReader), True)
self.assertEquals(pdfReaderUtil.numOfPages, 3)
self.assertEquals(pdfReaderUtil.isEncrypted, False)
self.assertEquals(pdfReaderUtil.errMsg, "")
self.assertEqual(pdfReaderUtil.getpageBox(pdfReader.getPage(0)), RectangleObject([0, 0, 595, 842]))
def testOpeningEncryptedPdf(self):
testData = "%stestData/encrypted.pdf" % basePath
testDataAbsPath = self.iceContext.fs.absPath(testData)
pdfUtils = PdfUtils(self.iceContext.fs)
pdfReaderUtil = pdfUtils.pdfReader()
pdfReader = pdfReaderUtil.createPdfReader(testDataAbsPath)
self.assertEqual(isinstance(pdfReader, PdfFileReader), True)
self.assertEqual(pdfReaderUtil.numOfPages, 'file has not been decrypted')
def testConvertingPdfToImages(self):
testData = "%stestData/multipages.pdf" % basePath
imageFolder = "%stestData/images" % basePath
if self.iceContext.fs.isDirectory(imageFolder):
self.iceContext.fs.delete(imageFolder)
self.iceContext.fs.makeDirectory(imageFolder)
imageMagickConverter = ImageMagickConverter(self.iceContext, imageFolder, self.iceContext.fs.absPath(testData))
self.assertEqual(imageMagickConverter.hasLocalImageMagick, True)
imageMagickConverter.convertingPdfToImages()
self.assertEquals(len(self.iceContext.fs.listFiles(imageFolder)), 3)
def xtestOpeningCorrupedPdf(self):
testData = "%stestData/corrupted.pdf" % basePath
testDataAbsPath = self.iceContext.fs.absPath(testData)
pdfUtils = PdfUtils(self.iceContext.fs)
pdfReaderUtil = pdfUtils.pdfReader()
pdfReader = pdfReaderUtil.createPdfReader(testDataAbsPath)
self.assertEqual(pdfReader, None)
self.assertEqual(pdfReaderUtil.errMsg.find("EOF marker not found")!= -1, True)
self.assertEqual(pdfUtils.fixPdf(testDataAbsPath), "Fixed")
pdfReader = pdfReaderUtil.createPdfReader(testDataAbsPath)
self.assertEqual(isinstance(pdfReader, PdfFileReader), True)
self.assertEqual(pdfReaderUtil.numOfPages, '1')
def xtestMergePdfWithEncryptedError(self):
#Note: even corrupted pdfs have been fixed, this error must be reported to EPS in case the pdf is malformed
#Note: only encrypted error sent to direct and stop merging
corruptedPdfList = []
encryptedPdfList = []
fileList = [singlePagePdf, multiplePagesPdf, encryptedPdf, corruptedPdf]
for file in fileList:
print 'processing: ', file
filePath = self.iceContext.fs.absolutePath(file)
pdfReader = PdfReader(self.iceContext.fs)
pdfReader.createPdfReader(filePath)
if pdfReader.pdfFileReader is None:
corruptedPdfList.append(file)
self.pdfUtils.fixPdf(filePath)
pdfReader.createPdfReader(filePath)
else:
if pdfReader.isEncrypted:
encryptedPdfList.append(file)
self.assertEqual(corruptedPdfList, ['testData/corrupted.pdf'])
self.assertEqual(encryptedPdfList, ['testData/encrypted.pdf'])
def xtestMergePdfWithoutEncryptedError(self):
#Note: even corrupted pdfs have been fixed, this error must be reported to EPS in case the pdf is malformed
#Note: only encrypted error sent to direct and stop merging
corruptedPdfList = []
encryptedPdfList = []
outputFile = "testData/merged.pdf"
outputAbsPath = self.iceContext.fs.absolutePath(outputFile)
fileList = [singlePagePdf, multiplePagesPdf, corruptedPdf]
pdfWriter = PdfWriter(outputAbsPath)
for file in fileList:
print 'processing: ', file
filePath = self.iceContext.fs.absolutePath(file)
pdfReader = PdfReader(self.iceContext.fs)
pdfReader.createPdfReader(filePath)
if pdfReader.pdfFileReader is None:
corruptedPdfList.append(file)
self.pdfUtils.fixPdf(filePath)
pdfReader.createPdfReader(filePath)
for pageNum in range(pdfReader.numOfPages):
pdfWriter.outputWriter.addPage(pdfReader.getPage(pageNum))
else:
if pdfReader.isEncrypted:
encryptedPdfList.append(file)
else:
pdfReader.createPdfReader(filePath)
for pageNum in range(pdfReader.numOfPages):
pdfWriter.outputWriter.addPage(pdfReader.getPage(pageNum))
self.assertEqual(corruptedPdfList, ['testData/corrupted.pdf'])
self.assertEqual(encryptedPdfList, [])
pdfWriter.savePdf()
self.assertEqual(self.iceContext.fs.isFile(outputAbsPath), True)
pdfReader = PdfReader(self.iceContext.fs)
pdfReader.createPdfReader(outputAbsPath)
self.assertEqual(pdfReader.numOfPages, 5)
# def testNumPages(self):
# pdfUtil = PDFUtils(fs, multiplePagesPdf)
# pdfReader = pdfUtil.inputReader
# self.assertEquals(pdfReader.numberOfPages, 3)
#
# def testPageDetail(self):
# pdfUtil = PDFUtils(fs, singlePagePdf)
# pdfReader = pdfUtil.inputReader
# expectedResult = {'units_y': 842, 'units_x': 595, 'height': 842, 'width': 595, 'offset_x': 0,
# 'offset_y': 0, 'unit': 'pt'}
#
# #get page property for page 1
# page = pdfReader.getPageBox(0)
# result = pdfReader.rectangle2box(page)
# self.assertEquals(result, expectedResult)
#
# def testMakeEmptyPage(self):
# pdfUtil = PDFUtils(fs)
# newPageReader = pdfUtil.makeEmptyPagesPdf(1)
#
# result = newPageReader.rectangle2box(newPageReader.getPage(0).trimBox)
# expected = {'units_y': 841.8898, 'units_x': 595.2756, 'height': 841.8898, 'width': 595.2756, 'offset_x': 0, 'offset_y': 0, 'unit': 'pt'}
#
# for key in result:
# resultVal = str(result[key])
# expectVal = str(expected[key])
# self.assertEquals(resultVal, expectVal)
#
#
#
# def testResize(self):
# #only resize first page
# pdfFile = "testData/differentSize.pdf"
# outputFile = "testData/outputFile.pdf"
# pdfUtil = PDFUtils(fs, pdfFile)
# pdfReader = pdfUtil.inputReader
# outputWriter = pdfUtil.createPdfWriter()
#
# emptyReader = pdfUtil.makeEmptyPagesPdf(1)
# emptyPage = emptyReader.getPage(0)
# emptyRectangle = emptyReader.rectangle2box(emptyPage.trimBox)
# emptyWidth = emptyRectangle['width']
# emptyHeight = emptyRectangle['height']
#
# oriPage = pdfReader.getPage(1)
# oriRectangle = pdfReader.rectangle2box(oriPage.trimBox)
# oriWidth = oriRectangle['width']
# oriHeight = oriRectangle['height']
# outputWriter.addPage(emptyPage)
# pdfUtil.scalePage(emptyPage, oriPage,
# (0, emptyHeight/oriHeight), # offset x,y
# (emptyWidth/oriWidth, emptyHeight/oriHeight) # scaling x,y
# )
#
# pdfUtil.savePdf(outputWriter, outputFile)
#
# outputUtil = PDFUtils(fs, outputFile)
# outputReader = outputUtil.inputReader
# outputRectangle = outputReader.rectangle2box(outputReader.getPage(0).trimBox)
# #makesure the size is the same as emptyPage
# self.assertEquals(emptyRectangle, outputRectangle)
#
#
#
#
# def xtestExtractingPdfPages(self):
# # Test on singlePage
# pdfUtils = PDFUtils(fs)
# extractedFile = pdfUtils.extractPdfPages(singlePagePdf)
# self.assertTrue(len(extractedFile), 1)
# for file in extractedFile:
# self.assertTrue(fs.isFile(fs.absolutePath(file)))
#
#
# # Test on multiplePages
# extractedFile = pdfUtils.extractPdfPages(multiplePagesPdf)
# self.assertTrue(len(extractedFile), 3)
# for file in extractedFile:
# self.assertTrue(fs.isFile(fs.absolutePath(file)))
#
#
# def xtestConvertPdfToPs(self):
# pdfUtils = PDFUtils(fs)
# extractedFile = pdfUtils.extractPdfPages(singlePagePdf)
# psFiles = pdfUtils.convertPagesToPS(extractedFile)
# self.assertTrue(len(extractedFile), 1)
# for file in psFiles:
# self.assertTrue(fs.isFile(fs.absolutePath(file)))
#
# epsFiles = pdfUtils.convertPsToEps(psFiles)
# self.assertTrue(len(extractedFile), 1)
# for file in epsFiles:
# self.assertTrue(fs.isFile(fs.absolutePath(file)))
#
# for file in extractedFile:
# fs.delete(fs.absolutePath(file))
## for file in psFiles:
## fs.delete(fs.absolutePath(file))
#
#
# extractedFile = pdfUtils.extractPdfPages(multiplePagesPdf)
# psFiles = pdfUtils.convertPagesToPS(extractedFile)
# self.assertTrue(len(extractedFile), 3)
# for file in psFiles:
# self.assertTrue(fs.isFile(fs.absolutePath(file)))
#
# epsFiles = pdfUtils.convertPsToEps(psFiles)
# self.assertTrue(len(extractedFile), 3)
# for file in epsFiles:
# self.assertTrue(fs.isFile(fs.absolutePath(file)))
#
# for file in extractedFile:
# fs.delete(fs.absolutePath(file))
## for file in psFiles:
## fs.delete(fs.absolutePath(file))
#
# def xtestConvertUseImageMagick(self):
# pdfUtils = PDFUtils(fs)
# extractedFile = pdfUtils.extractPdfPages(singlePagePdf)
# epsFiles = pdfUtils.convertUsesImageMagick(extractedFile)
# self.assertTrue(len(epsFiles), 1)
# for file in epsFiles:
# self.assertTrue(fs.isFile(fs.absolutePath(file)))
#
# extractedFile = pdfUtils.extractPdfPages(imagePdf)
# epsFiles = pdfUtils.convertUsesImageMagick(extractedFile)
# self.assertTrue(len(epsFiles), 1)
# for file in epsFiles:
# self.assertTrue(fs.isFile(fs.absolutePath(file)))
#
# extractedFile = pdfUtils.extractPdfPages(multiplePagesPdf)
# epsFiles = pdfUtils.convertUsesImageMagick(extractedFile)
# self.assertTrue(len(epsFiles), 3)
# for file in epsFiles:
# self.assertTrue(fs.isFile(fs.absolutePath(file)))
if __name__ == "__main__":
IceCommon.runUnitTests(locals())
| [
"[email protected]@110e3293-9ef9-cb8f-f479-66bdb1942d05"
] | [email protected]@110e3293-9ef9-cb8f-f479-66bdb1942d05 |
b91955ad63dfda9a71f830d93717f0db2366bf70 | 7ec91f8b8342b1ab62d315424f43588a13dda307 | /solu/221. Maximal Square.py | f17368e629bb9254ed8a5f5a492dfce8f0b97edc | [] | no_license | coolmich/py-leetcode | bbd001a1cb41b13cd0515d1b764ec327dfaaa03c | 3129438b032d3aeb87c6ac5c4733df0ebc1272ba | refs/heads/master | 2020-05-21T08:44:46.564419 | 2016-09-15T15:45:08 | 2016-09-15T15:45:08 | 60,917,444 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 665 | py | class Solution(object):
def maximalSquare(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if not len(matrix): return 0
mat, maxi = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))], 0
for c in range(len(matrix[0])):
for r in range(len(matrix)):
if not r or not c:
mat[r][c] = 1 if matrix[r][c] == '1' else 0
else:
if matrix[r][c] == '1':
mat[r][c] = min(mat[r-1][c-1], mat[r][c-1], mat[r-1][c]) + 1
maxi = max(maxi, mat[r][c])
return maxi**2 | [
"[email protected]"
] | |
fc36f5d3bbf141bd5b97e9bfa970fa8c1f641c82 | 31fc068f935aa723a089eda3c8a639e1d9c4cee9 | /jason.py | 27b41fdd76c9d5384f1f606053da85231f1a696c | [] | no_license | jaythaceo/Jaythaceo | 31098a016c4b3453996ef89252f2d9a1f05e9c10 | f4cea385318b0ff1708e3d35e96f4eb53925d8d0 | refs/heads/master | 2023-05-30T15:16:27.589337 | 2023-04-28T16:23:31 | 2023-04-28T16:23:31 | 157,614,343 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 969 | py | # Lets make a bot that does some cool shit
from flask import Flask, render_template, request, jsonify
import aiml
import os
app = Flask(__name__)
@app.route("/")
def hello():
return render_template('chat.html')
@app.route("/ask", methods=['POST'])
def ask():
message = request.form['messageText'].encode('utf-8').strip()
kernel = aiml.Kernel()
if os.path.isfile("bot_brain.brn"):
kernel.bootstrap(brainFile = "bot_brain.brn")
else:
kernel.bootstrap(learnFiles = os.path.abspath("aiml/std-startup.xml"), commands = "load aiml b")
kernel.saveBrain("bot_brain.brn")
# kernel now ready for use
while True:
if message == "quit":
exit()
elif message == "save":
kernel.saveBrain("bot_brain.brn")
else:
bot_response = kernel.respond(message)
# print bot_response
return jsonify({'status':'OK','answer':bot_response})
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True) | [
"[email protected]"
] | |
88c1de86d4d9ba1db69c49098476c61e05196810 | 540b4199dd80228f1d84c9b687e974cfa2c289a2 | /【Python+Dash快速web应用开发】系列文章/16 多页面应用/app2.py | 4298790c10256c39aeb6b4f979952cf587c417be | [] | no_license | CNFeffery/DataScienceStudyNotes | 1186e26c88874b89b65f841af5f78dc49429e479 | d45b42b49be04ba4add9cdd18b4787fb3c334b1f | refs/heads/master | 2023-08-17T07:18:43.730916 | 2023-07-25T14:05:17 | 2023-07-25T14:05:17 | 206,516,448 | 1,141 | 485 | null | null | null | null | UTF-8 | Python | false | false | 1,543 | py | import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
app = dash.Dash(__name__)
app.layout = dbc.Container(
[
dcc.Location(id='url', refresh=False),
dbc.Row(
[
dbc.Col(
[
html.A('页面A', href='/pageA'),
html.Br(),
html.A('页面B', href='/pageB'),
html.Br(),
html.A('页面C', href='/pageC'),
],
width=2,
style={
'backgroundColor': '#eeeeee'
}
),
dbc.Col(
html.H3(id='render-page-content'),
width=10
)
]
)
],
style={
'paddingTop': '20px',
'height': '100vh',
'weight': '100vw'
}
)
@app.callback(
Output('render-page-content', 'children'),
Input('url', 'pathname')
)
def render_page_content(pathname):
if pathname == '/':
return '欢迎来到首页'
elif pathname == '/pageA':
return '欢迎来到页面A'
elif pathname == '/pageB':
return '欢迎来到页面B'
elif pathname == '/pageC':
return '欢迎来到页面C'
else:
return '当前页面不存在!'
if __name__ == '__main__':
app.run_server(debug=True)
| [
"[email protected]"
] | |
1c555d3c397b93d8929f1f3d32c733ad9362307a | 28bf7793cde66074ac6cbe2c76df92bd4803dab9 | /answers/Utkarsh Srivastava/Day 6/Question 1.py | 51078cd3ed9f7841f0a3dc1a97b49dc757ef6903 | [
"MIT"
] | permissive | Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021 | 2dee33e057ba22092795a6ecc6686a9d31607c9d | 66c7d85025481074c93cfda7853b145c88a30da4 | refs/heads/main | 2023-05-29T10:33:31.795738 | 2021-06-10T14:57:30 | 2021-06-10T14:57:30 | 348,153,476 | 22 | 135 | MIT | 2021-06-10T14:57:31 | 2021-03-15T23:37:26 | Java | UTF-8 | Python | false | false | 371 | py | candies = input("Enter Candies ").split()
max = 0
result = [0]*len(candies)
extra = int(input("Enter extra candies "))
for i in range(len(candies)):
candies[i] = int(candies[i])
if int(candies[i])>max:
max = candies[i]
for i in range(len(candies)):
if(candies[i]+extra>=max):
result[i] = True
else:
result[i] = False
print(result)
| [
"[email protected]"
] | |
3cc37cf0d6c169ef8ca16a2422467566dd03733e | 24e843a90a3b3a37cc4d76a207f41d1fc628c2e7 | /python3/test141~225.py | 8fb44d48461a29e5a31ea55c2269ee6e23ee6e0f | [] | no_license | erikliu0801/leetcode | c595ea786716f7df86bd352c1e8d691f1870ec70 | 1de7bfe192324f9de28afa06b9539331c87d1346 | refs/heads/master | 2023-08-07T14:47:19.074076 | 2021-09-05T09:46:35 | 2021-09-05T09:46:35 | 224,321,259 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,035 | py | #141
def hasCycle(head):
linked_list = []
while head != None:
if head in linked_list:
return True
linked_list.append(head)
head = head.next
return False
#168
def convertToTitle(n):
if n <= 0:
return
else:
digits = ['Z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y']
digits_sum, digits_num, digits_level = 0, 1, 0
while digits_sum < n:
digits_num *= 26
digits_level += 1
digits_sum += digits_num
if digits_sum == n:
return 'Z' * digits_level
else:
all_digits = ''
while digits_level > 0:
all_digits = digits[n % 26] + all_digits
if n % 26 == 0:
n = n//26 -1
else:
n = n//26
digits_level -= 1
return all_digits
#169
def majorityElement(nums):
for num in set(nums):
if nums.count(num) > len(nums)//2:
return num
#171
def titleToNumber(s):
def addSum(digits):
add_sum = 0
if digits > 0:
add_sum = 26**digits + addSum(digits-1)
return add_sum
digits = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
add_sum = addSum(len(s)-1) + 1
for i in range(len(s)):
add_sum += digits.index(s[-1-i]) * 26 ** i
return add_sum
#172
def trailingZeroes(n):
negative = False
if n < 0 and n % 2 != 0:
negative = True
n = abs(n)
five_scale = 5
five_scale_addnum = [1]
while five_scale < n:
five_scale *= 5
five_scale_addnum.append(five_scale_addnum[-1]*5 +1)
add_num = 0
for i in range(1,len(five_scale_addnum)+1):
add_num += (n // five_scale) * five_scale_addnum[-i]
n %= five_scale
five_scale //= 5
if negative == True:
return 0 - add_num
else:
return add_num
#202
def isHappy(n):
if n < 1:
return False
pre = list()
while n != 1:
if n in pre:
return False
pre.append(n)
cache = 0
for c in str(n):
cache += int(c)**2
n = cache
return True
# def main():
# print(isHappy(200))
#203
def removeElements(head, val):
if type(head) != ListNode:
return
while head.val == val:
if head.next != None:
head = head.next
else:
return
if head.next == None:
return head
l1 = removeElements(head.next, val)
if l1:
head.next = l1
else:
head.next = None
return head
#204
def countPrimes(n):
import time
now = time.time()
if n <= 2:
return 0
else:
primes = set({2})
x = set(range(3,n,2))
while len(x) != 0:
prime = min(x)
primes.add(prime)
x.remove(prime)#
x -= x.intersection(set(range(prime**2,n,prime))) ##
if prime**2 >= n:
break
primes |= x
print(time.time() - now)
return len(primes)
#205
def isIsomorphic(s, t):
pass
#206
def reverseList(head):
if type(head) != ListNode:
return
elif head.next == None:
return head
else:
node = head.next #n2
head.next = None #n1->X
while node.next: #if n3 exist
new_head = node.next #n3
node.next = head #n2->n1
if new_head.next != None:
head = node # n1 = n2
node = new_head # n2 = n3
else:
new_head.next = node #n3->n2
return new_head
node.next = head
return node
#217
def containsDuplicate(nums):
return len(set(nums)) != len(nums)
#219
def containsNearbyDuplicate(nums, k):
if len(set(nums)) == len(nums):
return False
c = list()
c_i_j = list()
for m, num in enumerate(nums):
if num in c:
c_i_j[c.index(num)].append(m)
else:
c.append(num)
c_i_j.append([m])
k_s = set()
for m in c_i_j:
for n, i in enumerate(m):
for j in m[n+1:]:
k_s.add(abs(j-i))
return k in k_s
def main():
input_nums = [[1,2,3,1], [1,0,1,1], [1,0,1,1], [1,0,1,1], [1,2,3,1,2,3], [1,2,3,1,2,3]]
input_k = [3, 1, 2, 3, 2, 3]
expected_output = [True, True, True, True, False, True]
for i in range(len(input_nums)):
if containsNearbyDuplicate(input_nums[i], input_k[i]) != expected_output[i]:
print("Wrong!!!")
print(containsNearbyDuplicate(input_nums[i], input_k[i]))
else:
print("Right")
# print(containsNearbyDuplicate(input_nums[-1], input_k[-1]))
if __name__ == '__main__':
main()
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def LinkedList2List(ListNode):
"""
ListNode: Head
rtype: List
"""
list1 = []
l0 = ListNode
while l0 != None:
list1.append(l0.val)
l0 = l0.next
return list1
def List2LinkedList(List):
"""
rtype: Head of ListNode
"""
l = ListNode(0)
l0 = l
for i in range(len(List)):
l.val = List[i]
if i + 1 != len(List):
l.next = ListNode(0)
l = l.next
return l0
#141
# input_linked_list = [[3,2,0,-4]]
# expected_output = [True]
# for i in range(len(input_linked_list)):
# if hasCycle(List2LinkedList(input_linked_list[i])) != expected_output[i]:
# print("Wrong!!!")
# print(hasCycle(List2LinkedList(input_linked_list[i])))
# else:
# print("Right")
# print(hasCycle(List2LinkedList(input_linked_list[-1])))
#168
# for i in range(1,28):
# print(convertToTitle(i))
# input_int = [1, 26, 28, 701, 702, 703, 17576, 18278, 18279]
# expected_output = ['A', 'Z', 'AB', 'ZY', 'ZZ', 'AAA', 'YYZ', 'ZZZ', 'AAAA']
# for i in range(len(input_int)):
# if convertToTitle(input_int[i]) != expected_output[i]:
# print("Wrong!!!")
# print(convertToTitle(input_int[i]))
# else:
# print("Right")
# print(convertToTitle())
#169
# print(majorityElement([2,2,1,1,1,2,2]))
#171
# print(titleToNumber('BA'))
#172
# for i in range(1,11):
# print(factorial(i))
# print(trailingZeroes(124))
#203
# print(LinkedList2List(removeElements(List2LinkedList([6,6,3,4,5,6,6]),6)))
#204
# print(countPrimes(1000000))
#205
# input_s = ['egg', 'foo', 'paper']
# input_t = ['add', 'bar', 'title']
# expected_output = [True, False, True]
# for i in range(len(input_s)):
# if isIsomorphic(input_s[i],input_t[i]) != expected_output[i]:
# print("Wrong!!!")
# print(isIsomorphic(input_s[i],input_t[i]))
# else:
# print("Right")
# print(isIsomorphic(input_s[-1],input_t[-1]))
#206
# print(LinkedList2List(reverseList(List2LinkedList([1,2]))))
#217
# print(containsDuplicate([1,2]))
#219 | [
"[email protected]"
] | |
e356b5be593efe2b242480222729f42b266cea26 | 99799383b4e618061fe9261aa70cfe420e02a5aa | /person/migrations/0008_person_datetime_updated.py | b93c4440a6d2a8a9406b93a49b315141c371f377 | [
"MIT"
] | permissive | openkamer/openkamer | f311a97d5c9e182eabd6602f42475e8e049912b0 | bb99963c00ad90299deccd44d977c27aee7eb16c | refs/heads/master | 2023-07-20T10:45:11.402427 | 2023-07-18T17:41:56 | 2023-07-18T17:41:56 | 57,322,204 | 62 | 7 | MIT | 2023-07-17T18:15:43 | 2016-04-28T17:43:23 | Python | UTF-8 | Python | false | false | 397 | py | # Generated by Django 2.2.8 on 2019-12-05 19:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('person', '0007_auto_20191205_1833'),
]
operations = [
migrations.AddField(
model_name='person',
name='datetime_updated',
field=models.DateTimeField(auto_now=True),
),
]
| [
"[email protected]"
] | |
4ff6bf0f114dfc486ac2a7d447a98809d1b04a35 | d63b1b36634b68070f6f3c017c0250a7ea646e6f | /SMC/GEM5/gem5/src/mem/ruby/structures/RubyPrefetcher.py | 18bb3dc69472cf6d08ff90277396485033e73a76 | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.0-or-later",
"MIT"
] | permissive | jiwon-choe/Brown-SMCSim | ccf506d34d85fb3d085bf50ed47de8b4eeaee474 | ff3d9334c1d5c8d6a00421848c0d51e50e6b67f8 | refs/heads/master | 2021-06-30T00:15:57.128209 | 2020-11-24T03:11:41 | 2020-11-24T03:11:41 | 192,596,189 | 15 | 8 | MIT | 2019-06-20T15:43:00 | 2019-06-18T18:53:40 | C++ | UTF-8 | Python | false | false | 2,437 | py | # Copyright (c) 2012 Mark D. Hill and David A. Wood
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Nilay Vaish
from m5.SimObject import SimObject
from System import System
from m5.params import *
from m5.proxy import *
class Prefetcher(SimObject):
type = 'Prefetcher'
cxx_class = 'Prefetcher'
cxx_header = "mem/ruby/structures/Prefetcher.hh"
num_streams = Param.UInt32(4,
"Number of prefetch streams to be allocated")
pf_per_stream = Param.UInt32(1, "Number of prefetches per stream")
unit_filter = Param.UInt32(8,
"Number of entries in the unit filter array")
nonunit_filter = Param.UInt32(8,
"Number of entries in the non-unit filter array")
train_misses = Param.UInt32(4, "")
num_startup_pfs = Param.UInt32(1, "")
cross_page = Param.Bool(False, """True if prefetched address can be on a
page different from the observed address""")
sys = Param.System(Parent.any, "System this prefetcher belongs to")
| [
"[email protected]"
] | |
6063712ab5545c979e943f37231f60c58696e514 | 1cc5d45273d008e97497dad9ec004505cc68c765 | /cheatsheet/ops_doc-master/Service/cfaq/personalNoteBook/pythonLearn-decorator.py | 79936304b8d47aa4fb0180ebc31d541b08fcf72f | [] | no_license | wangfuli217/ld_note | 6efb802989c3ea8acf031a10ccf8a8a27c679142 | ad65bc3b711ec00844da7493fc55e5445d58639f | refs/heads/main | 2023-08-26T19:26:45.861748 | 2023-03-25T08:13:19 | 2023-03-25T08:13:19 | 375,861,686 | 5 | 6 | null | null | null | null | UTF-8 | Python | false | false | 859 | py |
from functools import wraps
def memorization(func: object) -> object:
cache = {}
@wraps(func)
def wrapper(*args):
v = cache.get(args, None)
if v == None:
cache[args] = func(*args)
return cache[args]
return wrapper
@memorization
def fibonacci(n: int) -> int:
global count
count += 1
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
count = 0
if __name__ == '__main__':
for i in range(10):
num = fibonacci(i)
print(i, num, sep='->',end=';')
print('compute times: ',count)
/////////////////////////////////////output:
#0->0;1->1;2->1;3->2;4->3;5->5;6->8;7->13;8->21;9->34;compute times: 10 with memorization
#0->0;1->1;2->1;3->2;4->3;5->5;6->8;7->13;8->21;9->34;compute times: 276 without memorization
| [
"[email protected]"
] | |
a42a09467bc051a0ce5993db6de29f1ad7ec391d | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/InnerDetector/InDetExample/InDetSLHC_Example/scripts/IDPerformanceSLHCRTT_dynamic_pagemaker.py | 7eef87f5215cdfe7baf69f62e24cc6f840ac2d91 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,674 | py | #! /usr/bin/env python
# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
import os
import sys
from Logger import Logger
# module: IDPerformanceSLHCRTT_dynamic_pagemaker.py
class IDPerformanceSLHCRTT_dynamic_pagemaker:
def __init__(self,argDict={}):
# access my args from the dictionary passed in, and convert any basic types
# self.myArg = argDict.get('MyArg') # = the Python string type '3'
# self.myArg = int(self.myArg) # = the Python integer type 3
# access the RTT descriptor instance
rttDescriptor = argDict.get('JobDescriptor')
# grab some stuff from it
self.release = str(rttDescriptor.paths.release)
#self.build = str(rttDescriptor.paths.build)
self.jobGroup = str(rttDescriptor.jobGroup)
#self.platform = str(rttDescriptor.paths.targetCMTCONFIG)
self.branch = str(rttDescriptor.paths.branch)
self.runPath = str(rttDescriptor.runPath)
# I don't use the logger, but the RTT post-processing module runner now fails if it can't find one. Hrmph.
self.logger = Logger()
def run(self):
# do the stuff I wanted to do...
logfile = open(self.runPath + "/IDPerformanceSLHCRTT_dynamic_pagemaker.log",'a')
logfile.write("Starting IDPerformanceSLHCRTT_dynamic_pagemaker.py run method\n")
inputfile = self.runPath + "/ALL_IDPerformanceSLHCRTT_Plots.html"
outputfile = inputfile.replace(".html","_Dynamic.html")
datasetlist = { "AthenaMu1SLHCRTT": "Muons1GeV",
"AthenaMu100SLHCRTT": "Muons100GeV",
"AthenaZtomumuSLHCRTT": "ZtoMuMu",
"AthenaMu1SLHCRTTKalman": "Muons1GeVKalman",
"AthenaMu100SLHCRTTKalman": "Muons100GeVKalman",
"AthenaZtomumuSLHCRTTKalman": "ZtoMuMuKalman",
"AthenaPi1SLHCRTT": "Pions1GeV",
"AthenaPi100SLHCRTT": "Pions100GeV",
"AthenaEle1SLHCRTT": "Electrons1GeV",
"AthenaEle100SLHCRTT": "Electrons100GeV",
"AthenaPi1SLHCRTTKalman": "Pions1GeVKalman",
"AthenaPi100SLHCRTTKalman": "Pions100GeVKalman",
"AthenaEle1SLHCRTTKalman": "Electrons1GeVKalman",
"AthenaEle100SLHCRTTKalman": "Electrons100GeVKalman",
"AthenaTtbarSLHCRTT": "Ttbar",
"AthenaTtbarSLHCRTTKalman": "TtbarKalman",
"AthenaZtomumuPileupSLHCRTT": "ZtoMuMuPileup",
"AthenaZtomumuPileupSLHCRTTKalman": "ZtoMuMuPileupKalman",
"AthenaMinBiasSLHCRTT": "MinBias",
"AthenaMinBiasSLHCRTTKalman": "MinBiasKalman",
"AthenaEle5SLHCRTTKalmanDNA": "Electrons5GeVKalmanDNA",
"AthenaEle60SLHCRTTKalmanDNA": "Electrons60GeVKalmanDNA",
"AthenaEle5SLHCRTTGaussianSumFilter": "Electrons5GeVGaussianSumFilter",
"AthenaEle60SLHCRTTGaussianSumFilter": "Electrons60GeVGaussianSumFilter"}
# helper function
def szsplit(stringlist,splitchar=" "):
if str(splitchar) == splitchar:
try:
return stringlist.split(splitchar)
except:
newlist = []
for item in stringlist:
newlist += item.split(splitchar)
return newlist
else:
for onechar in splitchar:
stringlist = szsplit(stringlist,onechar)
return stringlist
logfile.write("Input file: " + inputfile + "\n")
logfile.write("Output file: " + outputfile + "\n")
logfile.write("datasetlist: \n")
for key in datasetlist.keys():
logfile.write(" " + key + ": " + datasetlist[key] +"\n")
logfile.write("Getting dataset... ")
try:
dataset = datasetlist[self.jobGroup]
logfile.write("OK!\n")
except:
dataset = "Unknown (jobGroup = " + self.jobGroup + ")"
logfile.write("Unknown!\n")
logfile.write(" Dataset name is " + dataset + "\n")
jobinfolist = { "Release" : self.release , "Branch" : self.branch , "Dataset" : dataset }
#jobinfolist = { "Release" : self.release , "Branch" : self.branch , "Build" : self.build , "Platform" : self.platform ,
# "Dataset" : dataset }
#http://atlas-project-rtt-results.web.cern.ch/atlas-project-rtt-results/page2.php?xml=rel_3/pcache/build/i686-slc3-gcc323-opt/offline/RTTSummary.xml&package=InDetRTT&job=InDetRTT_jobOptions&id=182
#/afs/cern.ch/atlas/project/RTT/Results/rel_1/val/build/i686-slc4-gcc34-opt/offline/InDetRTT/AthenaHighPtMu/InDetRTT_jobOptions/183
#http://atlas-project-rtt-results.web.cern.ch/atlas-project-rtt-results/page2.php?xml=rel_1/val/build/i686-slc4-gcc34-opt/offline/RTTSummary.xml&package=InDetRTT&job=InDetRTT_jobOptions&id=183
# For testing purposes
if self.runPath == ".":
self.runPath = "/afs/cern.ch/atlas/project/RTT/Results/rel_1/bugfix/build/i686-slc4-gcc34-opt/offline/InDetPerformanceRTT/AthenaMu100SLHCRTT/InDetPerformanceRTT_jobOptions/334"
logfile.write("Runpath: " + self.runPath + "\n")
logfile.write("jobinfolist: \n")
for key in jobinfolist.keys():
logfile.write(" " + key + ": " + jobinfolist[key] +"\n")
logfile.write("Opening input file: " + inputfile + "\n")
input = open(inputfile,'r')
logfile.write("Opening output file: " + outputfile + "\n")
output = open(outputfile,'w')
logfile.write("Starting copy...\n")
for line in input:
logfile.write("Line: " + line)
if line.count("<h2>Contents</h2>"):
logfile.write(" Contains <h2>Contents</h2>\n")
output.write("<TABLE BORDER=6 CELLSPACING=4 CELLPADDING=4>\n")
for key in jobinfolist.keys():
logfile.write(" Going through jobinfo list and writing value of " + key + "... ")
output.write(" <TR><TD><b>" + key + "</b></TD><TD>" + jobinfolist[key] + "</TD></TR>\n")
logfile.write("Done.\n")
logfile.write("Writing date and finishing table... ")
output.write(" <TR><TD><b>" + "Date" + "</b></TD><TD>" + os.popen("date").readline().strip() + "</TD></TR>\n")
output.write("</TABLE>\n\n")
logfile.write("Done.\n")
if line.count("DCube"):
htmlline = "<li><a href=\""
dcubedir = False
for item in os.listdir(self.runPath):
if item.count("DCube-"):
dcubedir = item
break
if dcubedir:
htmlline += dcubedir + "/InDetStandardPlots.root.dcube.xml.php\">DCube histogram comparison page</a></li>\n"
logfile.write("Writing DCube line: " + htmlline)
output.write(htmlline)
continue
if line.count("Log files"):
logfile.write(" Contains log files")
htmlline = "<li>Log files: "
for filename in os.listdir(self.runPath):
if filename.count("log"):
htmlline += "<a href=\"" + filename + "\">" + filename + "</a> "
htmlline += "</li>\n"
output.write(htmlline)
logfile.write(" Writing: " + htmlline)
else:
output.write(line)
logfile.write(" Output original line.\n")
logfile.write("Now closing files.\n")
output.close()
input.close()
logfile.close()
return 0
class fakePaths:
def __init__(self,release="release",branch="branch"):
self.release = release
#self.build = build
#self.targetCMTCONFIG = platform
self.branch = branch
self.runPath = os.popen("pwd").readline().strip()
#class fakePaths:
# def __init__(self,release="release",build="build",platform="platform",branch="branch"):
# self.release = release
# self.build = build
# self.targetCMTCONFIG = platform
# self.branch = branch
# self.runPath = os.popen("pwd").readline().strip()
class fakeRttDescriptor:
def __init__(self):
self.paths = fakePaths()
self.jobGroup = "AthenaSingleMu"
self.runPath = "."
# Test run
if sys.argv[0] == "./IDPerformanceSLHCRTT_dynamic_pagemaker.py":
fakedecr = fakeRttDescriptor()
fakeArgDict = { 'JobDescriptor' : fakedecr }
pagemaker = IDPerformanceSLHCRTT_dynamic_pagemaker(fakeArgDict)
pagemaker.run()
| [
"[email protected]"
] | |
ec8332242621c2a458f725a777fa1c7e23397c1c | 998e1a1346f59c8e9b7669e7ebf716f9ac8cd117 | /EVSCapp/EVSCApi/urls.py | a7f4daee03f8376cd0fe5a37f9a9cb4180942c30 | [] | no_license | meku54444026/EVSCProject | 3415cf3b0abb682866fcca9bbebb32f37cb744c4 | 1bef5b405391409f27ea5948203c5e28fa1a28ff | refs/heads/master | 2023-07-02T04:45:15.314439 | 2021-08-10T14:52:48 | 2021-08-10T14:52:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,339 | py | from django.db import router
from django.urls import path
from django.urls.conf import include
from EVSCapp.EVSCApi.views import (RecordDetailAPIView,
LisVehicle,
VehicleDetailAPIView,
ReportRUDAPIView,
UpdateFcmTokenApiView,
ListFcmTokenDevices,
# fcm_token_detail
ListReport,
MyProfileLoadAPIView,
ListUser,
ListUserDetail,
RecordViewSet,
# RecordList,
list_records
)
from rest_framework.routers import DefaultRouter
from EVSCapp.EVSCApi import views as qv
router=DefaultRouter()
router.register("records",qv.RecordViewSet)
# router.register('devices', FCMDeviceAuthorizedViewSet)
urlpatterns = [
# path("",include(router.urls)),
path("",include(router.urls)),
path('rest-auth/',include("rest_auth.urls")),
path('records/',list_records,name='list-rcords'),
path('records/<int:pk>/',RecordDetailAPIView.as_view(),name='list-detail'),
path("records/<int:pk>/report/", qv.ReportCreateAPiView.as_view(),name='create-report'),
path('vehicles/',LisVehicle.as_view(),name='list-vehicle'),
path('vehicles/<int:pk>/',VehicleDetailAPIView.as_view(),name='vehicle-detail'),
path('reports/',ListReport.as_view(),name='report-list'),
path('reports/<int:pk>',ReportRUDAPIView.as_view(),name='report-detail'),
path('devices/',ListFcmTokenDevices.as_view(),name='list-device-token'),
path('devices/<int:user>/',UpdateFcmTokenApiView.as_view(),name='create-device-token'),
path('user-profile/',MyProfileLoadAPIView.as_view(),name ='retriev-user-profile'),
path('users/',ListUser.as_view(), name ='users'),
path('users/<int:pk>',ListUserDetail.as_view(), name = 'user-detail')
# path('devices/<int:pk>',fcm_token_detail,name='create-device-token')
# path('records/<int:pk>/report',ReportCreateAPiView.as_view(),name='create-record')
]
| [
"[email protected]"
] | |
1b01557b777216b35b876eb5b76e8c11dcae98f7 | 51a37b7108f2f69a1377d98f714711af3c32d0df | /src/leetcode/P376.py | 67230c5dd08e1fd4c1ad079f193aeec2d1ebc6e8 | [] | no_license | stupidchen/leetcode | 1dd2683ba4b1c0382e9263547d6c623e4979a806 | 72d172ea25777980a49439042dbc39448fcad73d | refs/heads/master | 2022-03-14T21:15:47.263954 | 2022-02-27T15:33:15 | 2022-02-27T15:33:15 | 55,680,865 | 7 | 1 | null | null | null | null | UTF-8 | Python | false | false | 697 | py | class Solution:
def wiggleMaxLength(self, nums):
n = len(nums)
if n < 2:
return n
inc = None
t = 1
for i in range(1, n):
if inc is None:
if nums[i] == nums[i - 1]:
continue
else:
if nums[i] < nums[i - 1]:
inc = True
else:
inc = False
if (inc and nums[i] < nums[i - 1]) or (not inc and nums[i] > nums[i - 1]) :
t += 1
inc = not inc
return t
if __name__ == '__main__':
print(Solution().wiggleMaxLength([1,17,5,10,13,15,10,5,16,8])) | [
"[email protected]"
] | |
11dcbec116bedb68d9ed2b8d582d4fa3c22d4ed6 | e87403a46c10b0528ae3d51e9d316c6c92409e2c | /models/attention/encoders/bgru_encoder.py | 1f4cbcc86a02f9905836b1f34c787648784c843e | [
"MIT"
] | permissive | xwang0415/tensorflow_end2end_speech_recognition | 662c9b899863f5595f903c4ce3b87e675e1d51a1 | 9d4661e9296b01d1116e82de823f398407207e1f | refs/heads/master | 2021-01-21T20:53:51.563852 | 2017-06-19T06:52:37 | 2017-06-19T06:52:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,718 | py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Bidirectional GRU Encoder class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from .encoder_base import EncoderOutput, EncoderBase
class BGRUEncoder(EncoderBase):
"""Bidirectional GRU Encoder.
Args:
num_unit:
num_layer:
keep_prob_input:
keep_prob_hidden:
parameter_init:
clip_activation: not used
num_proj: not used
"""
def __init__(self,
num_unit,
num_layer,
keep_prob_input=1.0,
keep_prob_hidden=1.0,
parameter_init=0.1,
clip_activation=50, # not used
num_proj=None, # not used
name='bgru_encoder'):
EncoderBase.__init__(self, num_unit, num_layer, keep_prob_input,
keep_prob_hidden, parameter_init, clip_activation,
num_proj, name)
def _build(self, inputs, inputs_seq_len):
"""Construct Bidirectional GRU encoder.
Args:
inputs:
inputs_seq_len:
Returns:
EncoderOutput: A tuple of
`(outputs, final_state,
attention_values, attention_values_length)`
outputs:
final_state:
attention_values:
attention_values_length:
"""
self.inputs = inputs
self.inputs_seq_len = inputs_seq_len
# Input dropout
outputs = tf.nn.dropout(inputs,
self.keep_prob_input,
name='dropout_input')
# Hidden layers
for i_layer in range(self.num_layer):
with tf.name_scope('BiGRU_encoder_hidden' + str(i_layer + 1)):
initializer = tf.random_uniform_initializer(
minval=-self.parameter_init,
maxval=self.parameter_init)
with tf.variable_scope('GRU', initializer=initializer):
gru_fw = tf.contrib.rnn.GRUCell(self.num_unit)
gru_bw = tf.contrib.rnn.GRUCell(self.num_unit)
# Dropout (output)
gru_fw = tf.contrib.rnn.DropoutWrapper(
gru_fw,
output_keep_prob=self.keep_prob_hidden)
gru_bw = tf.contrib.rnn.DropoutWrapper(
gru_bw,
output_keep_prob=self.keep_prob_hidden)
# _init_state_fw = lstm_fw.zero_state(self.batch_size,
# tf.float32)
# _init_state_bw = lstm_bw.zero_state(self.batch_size,
# tf.float32)
# initial_state_fw=_init_state_fw,
# initial_state_bw=_init_state_bw,
# Stacking
(outputs_fw, outputs_bw), final_state = tf.nn.bidirectional_dynamic_rnn(
cell_fw=gru_fw,
cell_bw=gru_bw,
inputs=outputs,
sequence_length=inputs_seq_len,
dtype=tf.float32,
scope='BiGRU_' + str(i_layer + 1))
# Concatenate each direction
outputs = tf.concat(
axis=2, values=[outputs_fw, outputs_bw])
return EncoderOutput(outputs=outputs,
final_state=final_state,
attention_values=outputs,
attention_values_length=inputs_seq_len)
| [
"[email protected]"
] | |
24387105dd66efbecce28fdcd23e85ae0ba6337e | d429c131df32789e11a98e9e965e652176fcee97 | /443A - Anton and Letters.py | 608e7a2cee9913d55638b75cd9c1c8131e89672c | [] | no_license | shan-mathi/Codeforces | a11841a1ef1a1ef78e3d506d58d9fdf4439421bd | 6f8166b79bea0eb1f575dbfc74c252ba71472c7e | refs/heads/main | 2023-06-15T08:25:41.130432 | 2021-06-24T10:36:06 | 2021-06-24T10:36:06 | 341,176,287 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 250 | py | #108786380 Mar/01/2021 14:42UTC+5.5 Shan_XD 443A - Anton and Letters PyPy 3 Accepted 108 ms 0 KB
list = str(input())
if list=='{}':
print(0)
else:
list = (list[1:-1].split(','))
list = [i.strip() for i in list]
print(len(set(list)))
| [
"[email protected]"
] | |
1c79daaf5498a22d80f0c0867463ce97502692e9 | 3da991a057cd81de802c40da2edd640878685258 | /caffe2/python/operator_test/ctc_beam_search_decoder_op_test.py | 21ca68fe007addb4333d4e8913cecfb64e83a685 | [
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | sjx0451/pytorch | 9f5b1c0c7c874f9da72c0190dc131944ba828ab7 | 3544f60f7602081398ee62bc5d652a87f4743dab | refs/heads/master | 2022-12-01T22:30:29.888370 | 2020-08-13T23:45:58 | 2020-08-13T23:48:31 | 287,421,291 | 2 | 0 | NOASSERTION | 2020-08-14T02:06:11 | 2020-08-14T02:06:11 | null | UTF-8 | Python | false | false | 5,391 | py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from caffe2.python.test_util import caffe2_flaky
from collections import defaultdict, Counter
from hypothesis import given, settings
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
import hypothesis.strategies as st
import numpy as np
import unittest
DEFAULT_BEAM_WIDTH = 10
DEFAULT_PRUNE_THRESHOLD = 0.001
class TestCTCBeamSearchDecoderOp(serial.SerializedTestCase):
@given(
batch=st.sampled_from([1, 2, 4]),
max_time=st.sampled_from([1, 8, 64]),
alphabet_size=st.sampled_from([1, 2, 32, 128, 512]),
beam_width=st.sampled_from([1, 2, 16, None]),
num_candidates=st.sampled_from([1, 2]),
**hu.gcs_cpu_only
)
@settings(deadline=None, max_examples=30)
def test_ctc_beam_search_decoder(
self, batch, max_time, alphabet_size, beam_width, num_candidates, gc, dc
):
if not beam_width:
beam_width = DEFAULT_BEAM_WIDTH
op_seq_len = core.CreateOperator('CTCBeamSearchDecoder',
['INPUTS', 'SEQ_LEN'],
['OUTPUT_LEN', 'VALUES', 'OUTPUT_PROB'],
num_candidates=num_candidates)
op_no_seq_len = core.CreateOperator('CTCBeamSearchDecoder',
['INPUTS'],
['OUTPUT_LEN', 'VALUES', 'OUTPUT_PROB'],
num_candidates=num_candidates)
else:
num_candidates = min(num_candidates, beam_width)
op_seq_len = core.CreateOperator('CTCBeamSearchDecoder',
['INPUTS', 'SEQ_LEN'],
['OUTPUT_LEN', 'VALUES', 'OUTPUT_PROB'],
beam_width=beam_width,
num_candidates=num_candidates)
op_no_seq_len = core.CreateOperator('CTCBeamSearchDecoder',
['INPUTS'],
['OUTPUT_LEN', 'VALUES', 'OUTPUT_PROB'],
beam_width=beam_width,
num_candidates=num_candidates)
def input_generater():
inputs = np.random.rand(max_time, batch, alphabet_size)\
.astype(np.float32)
seq_len = np.random.randint(1, max_time + 1, size=batch)\
.astype(np.int32)
return inputs, seq_len
def ref_ctc_decoder(inputs, seq_len):
output_len = np.zeros(batch * num_candidates, dtype=np.int32)
output_prob = np.zeros(batch * num_candidates, dtype=np.float32)
val = np.array([]).astype(np.int32)
for i in range(batch):
Pb, Pnb = defaultdict(Counter), defaultdict(Counter)
Pb[0][()] = 1
Pnb[0][()] = 0
A_prev = [()]
ctc = inputs[:, i, :]
ctc = np.vstack((np.zeros(alphabet_size), ctc))
len_i = seq_len[i] if seq_len is not None else max_time
for t in range(1, len_i + 1):
pruned_alphabet = np.where(ctc[t] > DEFAULT_PRUNE_THRESHOLD)[0]
for l in A_prev:
for c in pruned_alphabet:
if c == 0:
Pb[t][l] += ctc[t][c] * (Pb[t - 1][l] + Pnb[t - 1][l])
else:
l_plus = l + (c,)
if len(l) > 0 and c == l[-1]:
Pnb[t][l_plus] += ctc[t][c] * Pb[t - 1][l]
Pnb[t][l] += ctc[t][c] * Pnb[t - 1][l]
else:
Pnb[t][l_plus] += \
ctc[t][c] * (Pb[t - 1][l] + Pnb[t - 1][l])
if l_plus not in A_prev:
Pb[t][l_plus] += \
ctc[t][0] * \
(Pb[t - 1][l_plus] + Pnb[t - 1][l_plus])
Pnb[t][l_plus] += ctc[t][c] * Pnb[t - 1][l_plus]
A_next = Pb[t] + Pnb[t]
A_prev = sorted(A_next, key=A_next.get, reverse=True)
A_prev = A_prev[:beam_width]
candidates = A_prev[:num_candidates]
index = 0
for candidate in candidates:
val = np.hstack((val, candidate))
output_len[i * num_candidates + index] = len(candidate)
output_prob[i * num_candidates + index] = Pb[t][candidate] + Pnb[t][candidate]
index += 1
return [output_len, val, output_prob]
def ref_ctc_decoder_max_time(inputs):
return ref_ctc_decoder(inputs, None)
inputs, seq_len = input_generater()
self.assertReferenceChecks(
device_option=gc,
op=op_seq_len,
inputs=[inputs, seq_len],
reference=ref_ctc_decoder,
)
self.assertReferenceChecks(
device_option=gc,
op=op_no_seq_len,
inputs=[inputs],
reference=ref_ctc_decoder_max_time,
)
if __name__ == "__main__":
import random
random.seed(2603)
unittest.main()
| [
"[email protected]"
] | |
42894b20a30101258c0c73f702b75506575bf3c4 | e08801ffc8aa0e59ef88662ba529056a89d924ef | /examples/elk/lsda/elk_pp.py | 13592bebd6ed836096d15314b3a173ff5bfc559f | [] | no_license | chrinide/DFTtoolbox | a8c848849693426b82f4c329523cc8d82f4d39ac | dfe003507011ec14ef520df36d0da55f52dd0028 | refs/heads/master | 2021-04-15T14:28:40.593612 | 2017-12-13T23:00:11 | 2017-12-13T23:00:11 | 126,837,451 | 1 | 0 | null | 2018-03-26T14:00:25 | 2018-03-26T14:00:24 | null | UTF-8 | Python | false | false | 710 | py | from DFTtoolbox.elk import postproc
import os
# Parameters =======================================
run_task=[1,2,3,4,5,6]
wkdir=os.path.dirname(os.path.realpath(__file__))
klabel=['$\Gamma$','X','W','K','$\Gamma$','L','U','W','L','K']
Ebound=[-5,5]
state_grp=[['1:1/1/a/a'],['2:2/2/a/a']]
# Main =============================================
print(wkdir)
pp=postproc(wkdir)
for task in run_task:
if task is 1:
pp.band_read()
elif task is 2:
pp.band_plot(klabel,Ebound)
elif task is 3:
pp.fatband_read()
elif task is 4:
pp.fatband_plot(state_grp,klabel,Ebound)
elif task is 5:
pp.pdos_read()
elif task is 6:
pp.pdos_plot(state_grp,Ebound) | [
"[email protected]"
] | |
6d32704f852655a0cfb1ee6f5c83b7814aa83fcb | d748a68c9d9100cb2ad275ebf0fd161532dd8200 | /cubicus/device.py | 04e4204bac84a483be21a740aef3331e7875f0eb | [] | no_license | drpancake/cubicus-daemon | aff192aa6e5b2ed97a5a34d5e1f3528d99bb4e71 | feaa8009a1bfe25ef47ca198e1bc3783ad5b58fd | refs/heads/master | 2021-01-02T09:27:10.321494 | 2012-05-01T21:31:09 | 2012-05-01T21:31:09 | 3,901,291 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,322 | py |
import os
import random
from cubicus.sock import SocketThread
from cubicus.models import Event
PAIRINGS_FILE = 'pairings.dat'
def display_pin(pin):
""" Kludge - PIL for now """
from PIL import Image, ImageDraw
im = Image.new('RGBA', (300, 100))
draw = ImageDraw.Draw(im)
draw.text((5, 5), pin)
im.show()
class DeviceSocketThread(SocketThread):
"""
Accepts a socket to a remote Cubicus device and services it
"""
def __init__(self, clientsocket):
SocketThread.__init__(self, clientsocket)
self._paired = False
self._challenged_guid = None
self._pin = None
# Subscribe to manager updates
self.manager.subscribe(self)
def notify(self, obj, name, new_value):
if name in ['current_context', 'current_application']:
self.send_state()
elif name == 'event':
event = new_value
if event.source != Event.DEVICE_EVENT:
# Event originated elsewhere, so forward it
# to the device
self.queue_message('event', event.to_json())
def allowed_types(self):
types = ['device_identify', 'state', 'event', 'pair_response']
return SocketThread.allowed_types(self) + types
def send_applications(self):
apps = map(lambda a: a.to_json(), self.manager.applications)
self.queue_message('applications', apps)
def handle_pair_response(self, pin):
if pin == self._pin:
# Successfully paired so store the GUID
fp = open(PAIRINGS_FILE, 'a')
fp.write('%s\n' % self._challenged_guid)
fp.close()
# Continue to next step
self._paired = True
self.send_applications()
self.send_state()
else:
self.queue_message('pair_failure')
self.stop()
def handle_device_identify(self, guid):
"""
Checks for existing pairing with the given GUID. If none
exists, initiate the pairing process. Once paired, queues
the remaining handshake messages
"""
assert self._paired is False
# Touch if its not there
if not os.path.isfile(PAIRINGS_FILE):
open(PAIRINGS_FILE, 'w').close()
fp = open(PAIRINGS_FILE, 'r')
s = fp.read()
fp.close()
pairs = s.split('\n')
if guid not in pairs:
# Unknown GUID so challenge for a random PIN number
self.log('Need to pair for "%s"' % guid)
self._challenged_guid = guid
self._pin = ''.join(map(str, [random.randint(0, 9)
for i in range(4)]))
display_pin(self._pin) # Display on host machine
self.queue_message('pair_request')
else:
# Already paired, continue to next step
self._paired = True
self.send_applications()
self.send_state()
def handle_state(self, state):
self.manager.current_application = state['current_application']
self.manager.current_context = state['current_context']
def handle_event(self, json_event):
event = Event.from_json(json_event)
event.source = Event.DEVICE_EVENT
self.manager.send_event(event)
| [
"[email protected]"
] | |
65afdd06bb2760a7cd754a6439f901e8c2c18c55 | ac5e52a3fc52dde58d208746cddabef2e378119e | /exps-sblp-obt/sblp_ut=3.5_rd=0.5_rw=0.06_rn=4_u=0.075-0.325_p=harmonic-2/sched=RUN_trial=50/sched.py | 906f21dc0c17a1a4da4f66497f1581033d82294a | [] | no_license | ricardobtxr/experiment-scripts | 1e2abfcd94fb0ef5a56c5d7dffddfe814752eef1 | 7bcebff7ac2f2822423f211f1162cd017a18babb | refs/heads/master | 2023-04-09T02:37:41.466794 | 2021-04-25T03:27:16 | 2021-04-25T03:27:16 | 358,926,457 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 369 | py | -S 0 -X RUN -Q 0 -L 7 138 400
-S 0 -X RUN -Q 0 -L 7 119 400
-S 1 -X RUN -Q 1 -L 4 90 400
-S 1 -X RUN -Q 1 -L 4 72 250
-S 2 -X RUN -Q 2 -L 3 64 250
-S 2 -X RUN -Q 2 -L 3 62 250
-S 3 -X RUN -Q 3 -L 2 40 125
-S 3 -X RUN -Q 3 -L 2 35 150
-S 4 33 150
-S 4 31 150
-S 4 26 100
-S 5 24 150
-S 4 18 100
-S 5 16 175
-S 5 14 125
-S 5 5 100
| [
"[email protected]"
] | |
1efe310b28c4e6a1bf1bfe0b321d4aecdd908515 | c0aff8a6ea16a6921bdbb907e6769d229dcdb6cb | /src/push_server/ios/push_worker/apnslib/notify_mgr.py | e55b66465e5275213ab7b49bdf5df1d116cc4eb8 | [] | no_license | chwangbjtu/pushService | fe1d3f92ea9f1292603be41894f8496fb7c13fba | 28a58bcba1522275d07bb20d41e8df5642955367 | refs/heads/master | 2021-01-11T18:17:30.263415 | 2016-09-27T10:43:08 | 2016-09-27T10:43:08 | 69,335,813 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,074 | py | #-*- coding: utf-8 -*-
from __init__ import *
from connection import *
from tornado import log
import traceback
import etc
from statistics import Statistics
from tokens import TokenMgr
class APNSNotificationWrapper(object):
sandbox = True
payloads = None
connection = None
identifier = 1
error_at = 0
def __init__(self, certificate = None, sandbox = True):
self.connection = APNSConnection(certificate = certificate)
self.sandbox = sandbox
self.payloads = []
def append(self, payload = None):
if not isinstance(payload, APNSNotification):
raise APNSTypeError, "Unexpected argument type. Argument should be an instance of APNSNotification object"
payload.identify(self.identifier)
self.payloads.append(payload)
self.identifier += 1
def count(self):
return len(self.payloads)
def add_failed_num(self):
statistics_obj = Statistics()
statistics_obj.add_failed_num()
def clear(self):
self.identifier = 1
self.error_at = 0
self.payloads = []
def notify(self):
payloads = [o.payload() for o in self.payloads]
messages = []
if len(payloads) == 0:
return False
for p in payloads:
plen = len(p)
messages.append(struct.pack('%ds' % plen, p))
message = "".join(messages)
apnsConnection = self.connection
if self.sandbox != True:
apns_host = etc.APNS_HOST
else:
apns_host = etc.APNS_SANDBOX_HOST
apnsConnection.connect(apns_host, etc.APNS_PORT)
buf = apnsConnection.write(message)
apnsConnection.close()
if buf:
log.app_log.info("error occured")
self.add_failed_num()
self.error_handler(buf)
return True
def error_handler(self, buf):
try:
unpack_buf = struct.unpack("!BBI", buf)
if len(unpack_buf) == 3:
log.app_log.info("error :%s", unpack_buf)
error_at = unpack_buf[2]
error_no = unpack_buf[1]
start = error_at - self.error_at
if error_no == etc.SHUTDOWN or error_no == etc.NO_ERROR_HAPPENED or error_no == etc.PROCESSING_ERROR:
#start = start - 1
pass
else:
if error_no == etc.INVALID_TOKEN:
error_payload = self.payloads[start - 1]
error_token = error_payload.get_token()
log.app_log.info("invalid token:%s", error_token)
token_mgr = TokenMgr()
token_mgr.add_delete_token(error_token)
self.payloads = self.payloads[start:]
self.error_at = error_at
self.notify()
except Exception, e:
pass
| [
"[email protected]"
] | |
1cd88b885c3b7efa082c8c2e1d20a5c27e47b3b0 | afc8d5a9b1c2dd476ea59a7211b455732806fdfd | /Configurations/qqH_SF/Full2017_HTXS_Stage1p2_v7/aliases.py | 5590cce79052d81eb95a5479ea2953beb062d395 | [] | 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 | 11,277 | py | import os
import copy
import inspect
configurations = os.path.realpath(inspect.getfile(inspect.currentframe())) # this file
configurations = os.path.dirname(configurations) # Full2017_HTXS_Stage1p2_v7
configurations = os.path.dirname(configurations) # qqH_SF
configurations = os.path.dirname(configurations) # Configurations
#aliases = {}
# imported from samples.py:
# samples, signals
mc = [skey for skey in samples if skey not in ('Fake', 'DATA')]
eleWP = 'mvaFall17V1Iso_WP90'
muWP='cut_Tight_HWWW_tthmva_80'
aliases['LepWPCut'] = {
'expr': 'LepCut2l__ele_'+eleWP+'__mu_'+muWP,
'samples': mc + ['DATA']
}
aliases['gstarLow'] = {
'expr': 'Gen_ZGstar_mass >0 && Gen_ZGstar_mass < 4',
'samples': 'VgS'
}
aliases['gstarHigh'] = {
'expr': 'Gen_ZGstar_mass <0 || Gen_ZGstar_mass > 4',
'samples': 'VgS'
}
# Fake leptons transfer factor
aliases['fakeW'] = {
'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP,
'samples': ['Fake']
}
# And variations - already divided by central values in formulas !
aliases['fakeWEleUp'] = {
'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP+'_EleUp',
'samples': ['Fake']
}
aliases['fakeWEleDown'] = {
'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP+'_EleDown',
'samples': ['Fake']
}
aliases['fakeWMuUp'] = {
'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP+'_MuUp',
'samples': ['Fake']
}
aliases['fakeWMuDown'] = {
'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP+'_MuDown',
'samples': ['Fake']
}
aliases['fakeWStatEleUp'] = {
'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP+'_statEleUp',
'samples': ['Fake']
}
aliases['fakeWStatEleDown'] = {
'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP+'_statEleDown',
'samples': ['Fake']
}
aliases['fakeWStatMuUp'] = {
'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP+'_statMuUp',
'samples': ['Fake']
}
aliases['fakeWStatMuDown'] = {
'expr': 'fakeW2l_ele_'+eleWP+'_mu_'+muWP+'_statMuDown',
'samples': ['Fake']
}
# gen-matching to prompt only (GenLepMatch2l matches to *any* gen lepton)
aliases['PromptGenLepMatch2l'] = {
'expr': 'Alt$(Lepton_promptgenmatched[0]*Lepton_promptgenmatched[1], 0)',
'samples': mc
}
aliases['Top_pTrw'] = {
'expr': '(topGenPt * antitopGenPt > 0.) * (TMath::Sqrt((0.103*TMath::Exp(-0.0118*topGenPt) - 0.000134*topGenPt + 0.973) * (0.103*TMath::Exp(-0.0118*antitopGenPt) - 0.000134*antitopGenPt + 0.973))) + (topGenPt * antitopGenPt <= 0.)',
'samples': ['top']
}
aliases['nCleanGenJet'] = {
'linesToAdd': ['.L %s/Differential/ngenjet.cc+' % configurations],
'class': 'CountGenJet',
'samples': mc
}
##### DY Z pT reweighting
aliases['getGenZpt_OTF'] = {
'linesToAdd':['.L %s/src/PlotsConfigurations/Configurations/patches/getGenZpt.cc+' % os.getenv('CMSSW_BASE')],
'class': 'getGenZpt',
'samples': ['DY']
}
handle = open('%s/src/PlotsConfigurations/Configurations/patches/DYrew30.py' % os.getenv('CMSSW_BASE'),'r')
exec(handle)
handle.close()
aliases['DY_NLO_pTllrw'] = {
'expr': '('+DYrew['2017']['NLO'].replace('x', 'getGenZpt_OTF')+')*(nCleanGenJet == 0)+1.0*(nCleanGenJet > 0)',
'samples': ['DY']
}
aliases['DY_LO_pTllrw'] = {
'expr': '('+DYrew['2017']['LO'].replace('x', 'getGenZpt_OTF')+')*(nCleanGenJet == 0)+1.0*(nCleanGenJet > 0)',
'samples': ['DY']
}
# Jet bins
# using Alt$(CleanJet_pt[n], 0) instead of Sum$(CleanJet_pt >= 30) because jet pt ordering is not strictly followed in JES-varied samples
# No jet with pt > 30 GeV
aliases['zeroJet'] = {
'expr': 'Alt$(CleanJet_pt[0], 0) < 30.'
}
aliases['oneJet'] = {
'expr': 'Alt$(CleanJet_pt[0], 0) >= 30. && Alt$(CleanJet_pt[1], 0) < 30.'
}
aliases['multiJet'] = {
'expr': 'Alt$(CleanJet_pt[1], 0) >= 30.'
}
aliases['2jVH'] = {
'expr': '( Alt$(CleanJet_pt[0],0)>=30 && Alt$(CleanJet_pt[1],0)>=30 && ( mjj >= 65 && mjj <= 105 ) )'
}
aliases['2jVBF'] = {
'expr': '( Alt$(CleanJet_pt[0],0)>=30 && Alt$(CleanJet_pt[1],0)>=30 && mjj>=350 )'
}
aliases['2jggH'] = {
'expr': '( Alt$(CleanJet_pt[0],0)>=30 && Alt$(CleanJet_pt[1],0)>=30 && (!2jVH && !2jVBF ) )'
}
# SF cuts
aliases['Higgs0jet'] = {
'expr': '(mll < 60 && mth > 90 && abs(dphill) < 2.30)'
}
aliases['Higgs1jet'] = {
'expr': '(mll < 60 && mth > 80 && abs(dphill) < 2.25)'
}
aliases['Higgs2jet'] = {
'expr': '(mll < 60 && mth > 65 && mth < 150)'
}
aliases['Higgs_qq'] = {
'expr': '(mll < 60 && mth > 60 && mth < 150 && abs(dphill) < 1.60)'
}
aliases['Higgsvh'] = {
'expr': '(mll < 60 && mth > 60 && mth < 150 && abs(dphill) < 1.60)'
}
aliases['Higgsvbf'] = {
'expr': '(mll < 60 && mth > 60 && mth < 150 && abs(dphill) < 1.60)'
}
aliases['Higgshpt'] = {
'expr': '(mll < 60 && mth > 60 && ( (abs(dphill) < 2.0 && !multiJet) || (mth < 150 && multiJet) ))'
}
#Z veto
aliases['ZVeto'] = {
'expr': '(fabs(91.1876 - mll) > 15)'
}
# B tagging
aliases['bVeto'] = {
'expr': 'Sum$(CleanJet_pt > 20. && abs(CleanJet_eta) < 2.5 && Jet_btagDeepB[CleanJet_jetIdx] > 0.1522) == 0'
}
aliases['bReq'] = {
'expr': 'Sum$(CleanJet_pt > 30. && abs(CleanJet_eta) < 2.5 && Jet_btagDeepB[CleanJet_jetIdx] > 0.1522) >= 1'
}
# CR definitions
aliases['topcr'] = {
'expr': 'mtw2>30 && mll>50 && ((zeroJet && !bVeto) || bReq)'
}
aliases['dycr'] = {
'expr': 'mth<60 && mll>40 && mll<80 && bVeto'
}
aliases['wwcr'] = {
'expr': 'mth>60 && mtw2>30 && mll>100 && bVeto && ZVeto'
}
aliases['Zpeak'] = {
'expr': 'fabs(91.1876 - mll) < 7.5'
}
# SR definition
aliases['sr'] = {
'expr': 'bVeto && ZVeto'
}
# B tag scale factors
aliases['bVetoSF'] = {
'expr': 'TMath::Exp(Sum$(TMath::Log((CleanJet_pt>20 && abs(CleanJet_eta)<2.5)*Jet_btagSF_deepcsv_shape[CleanJet_jetIdx]+1*(CleanJet_pt<20 || abs(CleanJet_eta)>2.5))))',
'samples': mc
}
aliases['bReqSF'] = {
'expr': 'TMath::Exp(Sum$(TMath::Log((CleanJet_pt>30 && abs(CleanJet_eta)<2.5)*Jet_btagSF_deepcsv_shape[CleanJet_jetIdx]+1*(CleanJet_pt<30 || abs(CleanJet_eta)>2.5))))',
'samples': mc
}
aliases['btagSF'] = {
'expr': '(bVeto || (topcr && zeroJet))*bVetoSF + (topcr && !zeroJet)*bReqSF',
'samples': mc
}
for shift in ['jes', 'lf', 'hf', 'lfstats1', 'lfstats2', 'hfstats1', 'hfstats2', 'cferr1', 'cferr2']:
for targ in ['bVeto', 'bReq']:
alias = aliases['%sSF%sup' % (targ, shift)] = copy.deepcopy(aliases['%sSF' % targ])
alias['expr'] = alias['expr'].replace('btagSF_deepcsv_shape', 'btagSF_deepcsv_shape_up_%s' % shift)
alias = aliases['%sSF%sdown' % (targ, shift)] = copy.deepcopy(aliases['%sSF' % targ])
alias['expr'] = alias['expr'].replace('btagSF_deepcsv_shape', 'btagSF_deepcsv_shape_down_%s' % shift)
aliases['btagSF%sup' % shift] = {
'expr': aliases['btagSF']['expr'].replace('SF', 'SF' + shift + 'up'),
'samples': mc
}
aliases['btagSF%sdown' % shift] = {
'expr': aliases['btagSF']['expr'].replace('SF', 'SF' + shift + 'down'),
'samples': mc
}
# Jet PU ID SF
aliases['Jet_PUIDSF'] = {
'expr' : 'TMath::Exp(Sum$((Jet_jetId>=2)*TMath::Log(Jet_PUIDSF_loose)))',
'samples': mc
}
aliases['Jet_PUIDSF_up'] = {
'expr' : 'TMath::Exp(Sum$((Jet_jetId>=2)*TMath::Log(Jet_PUIDSF_loose_up)))',
'samples': mc
}
aliases['Jet_PUIDSF_down'] = {
'expr' : 'TMath::Exp(Sum$((Jet_jetId>=2)*TMath::Log(Jet_PUIDSF_loose_down)))',
'samples': mc
}
# Correct trigger efficiencies
aliases['SFweight2lAlt'] = {
'expr' : 'puWeight*TriggerAltEffWeight_2l*Lepton_RecoSF[0]*Lepton_RecoSF[1]*EMTFbug_veto',
'samples': mc
}
aliases['trig_drll_rw'] = {
'expr' : '( ((drll >= 0.00 && drll <0.25)*0.019013 + (drll >= 0.25 && drll <0.50)*0.903772 + (drll >= 0.50 && drll <1.00)*0.996569 + (drll >= 1.00 && drll <1.50)*0.996051 + (drll >= 1.50 && drll <2.00)*0.997844 + (drll >= 2.00 && drll <2.50)*0.998130 + (drll >= 2.50 && drll <3.00)*0.998615 + (drll >= 3.00 && drll <3.50)*0.997920 + (drll >= 3.50 && drll <4.00)*0.997854 + (drll >= 4.00 && drll <4.50)*1.001182 + (drll >= 4.50)*0.994173)*(abs(Lepton_pdgId[0])==11 && abs(Lepton_pdgId[1])==11) + ((drll >= 0.00 && drll <0.25)*0.770696 + (drll >= 0.25 && drll <0.50)*1.003577 + (drll >= 0.50 && drll <1.00)*1.003401 + (drll >= 1.00 && drll <1.50)*1.002837 + (drll >= 1.50 && drll <2.00)*1.004616 + (drll >= 2.00 && drll <2.50)*1.004096 + (drll >= 2.50 && drll <3.00)*1.004561 + (drll >= 3.00 && drll <3.50)*1.004589 + (drll >= 3.50 && drll <4.00)*1.005748 + (drll >= 4.00 && drll <4.50)*1.006065 + (drll >= 4.50)*0.992700)*(abs(Lepton_pdgId[0])==11 && abs(Lepton_pdgId[1])==13) + ((drll >= 0.00 && drll <0.25)*0.857813 + (drll >= 0.25 && drll <0.50)*1.002417 + (drll >= 0.50 && drll <1.00)*0.999297 + (drll >= 1.00 && drll <1.50)*0.999881 + (drll >= 1.50 && drll <2.00)*0.998123 + (drll >= 2.00 && drll <2.50)*0.999193 + (drll >= 2.50 && drll <3.00)*0.997161 + (drll >= 3.00 && drll <3.50)*0.998346 + (drll >= 3.50 && drll <4.00)*0.995930 + (drll >= 4.00 && drll <4.50)*0.998973 + (drll >= 4.50)*0.977712)*(abs(Lepton_pdgId[0])==13 && abs(Lepton_pdgId[1])==11) + ((drll >= 0.00 && drll <0.25)*0.980155 + (drll >= 0.25 && drll <0.50)*0.993574 + (drll >= 0.50 && drll <1.00)*0.998352 + (drll >= 1.00 && drll <1.50)*1.001700 + (drll >= 1.50 && drll <2.00)*1.001031 + (drll >= 2.00 && drll <2.50)*0.999796 + (drll >= 2.50 && drll <3.00)*0.999189 + (drll >= 3.00 && drll <3.50)*1.000540 + (drll >= 3.50 && drll <4.00)*1.000136 + (drll >= 4.00 && drll <4.50)*1.003553 + (drll >= 4.50)*0.992509)*(abs(Lepton_pdgId[0])==13 && abs(Lepton_pdgId[1])==13) )',
'samples' : mc
}
# data/MC scale factors
aliases['SFweight'] = {
'expr': ' * '.join(['SFweight2lAlt', 'LepWPCut', 'LepSF2l__ele_' + eleWP + '__mu_' + muWP, 'btagSF', 'PrefireWeight','Jet_PUIDSF', 'trig_drll_rw']),
'samples': mc
}
# variations
aliases['SFweightEleUp'] = {
'expr': 'LepSF2l__ele_'+eleWP+'__Up',
'samples': mc
}
aliases['SFweightEleDown'] = {
'expr': 'LepSF2l__ele_'+eleWP+'__Do',
'samples': mc
}
aliases['SFweightMuUp'] = {
'expr': 'LepSF2l__mu_'+muWP+'__Up',
'samples': mc
}
aliases['SFweightMuDown'] = {
'expr': 'LepSF2l__mu_'+muWP+'__Do',
'samples': mc
}
aliases['Weight2MINLO'] = {
'linesToAdd': ['.L %s/Differential/weight2MINLO.cc+' % configurations],
'class': 'Weight2MINLO',
'args': '%s/src/LatinoAnalysis/Gardener/python/data/powheg2minlo/NNLOPS_reweight.root' % os.getenv('CMSSW_BASE'),
'samples' : [skey for skey in samples if 'ggH_hww' in skey],
}
## GGHUncertaintyProducer wasn't run for GluGluHToWWTo2L2Nu_Powheg_M125
thus = [
'ggH_mu',
'ggH_res',
'ggH_mig01',
'ggH_mig12',
'ggH_VBF2j',
'ggH_VBF3j',
'ggH_pT60',
'ggH_pT120',
'ggH_qmtop'
]
for thu in thus:
aliases[thu+'_2'] = {
'linesToAdd': ['.L %s/Differential/gghuncertainty.cc+' % configurations],
'class': 'GGHUncertainty',
'args': (thu,),
'samples': [skey for skey in samples if 'ggH_hww' in skey],
'nominalOnly': True
}
# Needed for top QCD scale uncertainty
lastcopy = (1 << 13)
aliases['isTTbar'] = {
'expr': 'Sum$(TMath::Abs(GenPart_pdgId) == 6 && TMath::Odd(GenPart_statusFlags / %d)) == 2' % lastcopy,
'samples': ['top']
}
aliases['isSingleTop'] = {
'expr': 'Sum$(TMath::Abs(GenPart_pdgId) == 6 && TMath::Odd(GenPart_statusFlags / %d)) == 1' % lastcopy,
'samples': ['top']
}
| [
"[email protected]"
] | |
5accc9fcadaf610a635543b7d61a06617e7baa0f | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /python/sympy/2017/8/test_cse.py | 3043acdc987ebd66cdb5945ed4119422d868b14c | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | Python | false | false | 17,101 | py | from functools import reduce
import itertools
from operator import add
from sympy import (
Add, Mul, Pow, Symbol, exp, sqrt, symbols, sympify, cse,
Matrix, S, cos, sin, Eq, Function, Tuple, CRootOf,
IndexedBase, Idx, Piecewise, O
)
from sympy.core.function import count_ops
from sympy.simplify.cse_opts import sub_pre, sub_post
from sympy.functions.special.hyper import meijerg
from sympy.simplify import cse_main, cse_opts
from sympy.utilities.iterables import subsets
from sympy.utilities.pytest import XFAIL, raises
from sympy.matrices import (eye, SparseMatrix, MutableDenseMatrix,
MutableSparseMatrix, ImmutableDenseMatrix, ImmutableSparseMatrix)
from sympy.matrices.expressions import MatrixSymbol
from sympy.core.compatibility import range
w, x, y, z = symbols('w,x,y,z')
x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12 = symbols('x:13')
def test_numbered_symbols():
ns = cse_main.numbered_symbols(prefix='y')
assert list(itertools.islice(
ns, 0, 10)) == [Symbol('y%s' % i) for i in range(0, 10)]
ns = cse_main.numbered_symbols(prefix='y')
assert list(itertools.islice(
ns, 10, 20)) == [Symbol('y%s' % i) for i in range(10, 20)]
ns = cse_main.numbered_symbols()
assert list(itertools.islice(
ns, 0, 10)) == [Symbol('x%s' % i) for i in range(0, 10)]
# Dummy "optimization" functions for testing.
def opt1(expr):
return expr + y
def opt2(expr):
return expr*z
def test_preprocess_for_cse():
assert cse_main.preprocess_for_cse(x, [(opt1, None)]) == x + y
assert cse_main.preprocess_for_cse(x, [(None, opt1)]) == x
assert cse_main.preprocess_for_cse(x, [(None, None)]) == x
assert cse_main.preprocess_for_cse(x, [(opt1, opt2)]) == x + y
assert cse_main.preprocess_for_cse(
x, [(opt1, None), (opt2, None)]) == (x + y)*z
def test_postprocess_for_cse():
assert cse_main.postprocess_for_cse(x, [(opt1, None)]) == x
assert cse_main.postprocess_for_cse(x, [(None, opt1)]) == x + y
assert cse_main.postprocess_for_cse(x, [(None, None)]) == x
assert cse_main.postprocess_for_cse(x, [(opt1, opt2)]) == x*z
# Note the reverse order of application.
assert cse_main.postprocess_for_cse(
x, [(None, opt1), (None, opt2)]) == x*z + y
def test_cse_single():
# Simple substitution.
e = Add(Pow(x + y, 2), sqrt(x + y))
substs, reduced = cse([e])
assert substs == [(x0, x + y)]
assert reduced == [sqrt(x0) + x0**2]
def test_cse_single2():
# Simple substitution, test for being able to pass the expression directly
e = Add(Pow(x + y, 2), sqrt(x + y))
substs, reduced = cse(e)
assert substs == [(x0, x + y)]
assert reduced == [sqrt(x0) + x0**2]
substs, reduced = cse(Matrix([[1]]))
assert isinstance(reduced[0], Matrix)
def test_cse_not_possible():
# No substitution possible.
e = Add(x, y)
substs, reduced = cse([e])
assert substs == []
assert reduced == [x + y]
# issue 6329
eq = (meijerg((1, 2), (y, 4), (5,), [], x) +
meijerg((1, 3), (y, 4), (5,), [], x))
assert cse(eq) == ([], [eq])
def test_nested_substitution():
# Substitution within a substitution.
e = Add(Pow(w*x + y, 2), sqrt(w*x + y))
substs, reduced = cse([e])
assert substs == [(x0, w*x + y)]
assert reduced == [sqrt(x0) + x0**2]
def test_subtraction_opt():
# Make sure subtraction is optimized.
e = (x - y)*(z - y) + exp((x - y)*(z - y))
substs, reduced = cse(
[e], optimizations=[(cse_opts.sub_pre, cse_opts.sub_post)])
assert substs == [(x0, (x - y)*(y - z))]
assert reduced == [-x0 + exp(-x0)]
e = -(x - y)*(z - y) + exp(-(x - y)*(z - y))
substs, reduced = cse(
[e], optimizations=[(cse_opts.sub_pre, cse_opts.sub_post)])
assert substs == [(x0, (x - y)*(y - z))]
assert reduced == [x0 + exp(x0)]
# issue 4077
n = -1 + 1/x
e = n/x/(-n)**2 - 1/n/x
assert cse(e, optimizations=[(cse_opts.sub_pre, cse_opts.sub_post)]) == \
([], [0])
def test_multiple_expressions():
e1 = (x + y)*z
e2 = (x + y)*w
substs, reduced = cse([e1, e2])
assert substs == [(x0, x + y)]
assert reduced == [x0*z, x0*w]
l = [w*x*y + z, w*y]
substs, reduced = cse(l)
rsubsts, _ = cse(reversed(l))
assert substs == rsubsts
assert reduced == [z + x*x0, x0]
l = [w*x*y, w*x*y + z, w*y]
substs, reduced = cse(l)
rsubsts, _ = cse(reversed(l))
assert substs == rsubsts
assert reduced == [x1, x1 + z, x0]
l = [(x - z)*(y - z), x - z, y - z]
substs, reduced = cse(l)
rsubsts, _ = cse(reversed(l))
assert substs == [(x0, -z), (x1, x + x0), (x2, x0 + y)]
assert rsubsts == [(x0, -z), (x1, x0 + y), (x2, x + x0)]
assert reduced == [x1*x2, x1, x2]
l = [w*y + w + x + y + z, w*x*y]
assert cse(l) == ([(x0, w*y)], [w + x + x0 + y + z, x*x0])
assert cse([x + y, x + y + z]) == ([(x0, x + y)], [x0, z + x0])
assert cse([x + y, x + z]) == ([], [x + y, x + z])
assert cse([x*y, z + x*y, x*y*z + 3]) == \
([(x0, x*y)], [x0, z + x0, 3 + x0*z])
@XFAIL # CSE of non-commutative Mul terms is disabled
def test_non_commutative_cse():
A, B, C = symbols('A B C', commutative=False)
l = [A*B*C, A*C]
assert cse(l) == ([], l)
l = [A*B*C, A*B]
assert cse(l) == ([(x0, A*B)], [x0*C, x0])
# Test if CSE of non-commutative Mul terms is disabled
def test_bypass_non_commutatives():
A, B, C = symbols('A B C', commutative=False)
l = [A*B*C, A*C]
assert cse(l) == ([], l)
l = [A*B*C, A*B]
assert cse(l) == ([], l)
l = [B*C, A*B*C]
assert cse(l) == ([], l)
@XFAIL # CSE fails when replacing non-commutative sub-expressions
def test_non_commutative_order():
A, B, C = symbols('A B C', commutative=False)
x0 = symbols('x0', commutative=False)
l = [B+C, A*(B+C)]
assert cse(l) == ([(x0, B+C)], [x0, A*x0])
@XFAIL # Worked in gh-11232, but was reverted due to performance considerations
def test_issue_10228():
assert cse([x*y**2 + x*y]) == ([(x0, x*y)], [x0*y + x0])
assert cse([x + y, 2*x + y]) == ([(x0, x + y)], [x0, x + x0])
assert cse((w + 2*x + y + z, w + x + 1)) == (
[(x0, w + x)], [x0 + x + y + z, x0 + 1])
assert cse(((w + x + y + z)*(w - x))/(w + x)) == (
[(x0, w + x)], [(x0 + y + z)*(w - x)/x0])
a, b, c, d, f, g, j, m = symbols('a, b, c, d, f, g, j, m')
exprs = (d*g**2*j*m, 4*a*f*g*m, a*b*c*f**2)
assert cse(exprs) == (
[(x0, g*m), (x1, a*f)], [d*g*j*x0, 4*x0*x1, b*c*f*x1]
)
@XFAIL
def test_powers():
assert cse(x*y**2 + x*y) == ([(x0, x*y)], [x0*y + x0])
def test_issue_4498():
assert cse(w/(x - y) + z/(y - x), optimizations='basic') == \
([], [(w - z)/(x - y)])
def test_issue_4020():
assert cse(x**5 + x**4 + x**3 + x**2, optimizations='basic') \
== ([(x0, x**2)], [x0*(x**3 + x + x0 + 1)])
def test_issue_4203():
assert cse(sin(x**x)/x**x) == ([(x0, x**x)], [sin(x0)/x0])
def test_issue_6263():
e = Eq(x*(-x + 1) + x*(x - 1), 0)
assert cse(e, optimizations='basic') == ([], [True])
def test_dont_cse_tuples():
from sympy import Subs
f = Function("f")
g = Function("g")
name_val, (expr,) = cse(
Subs(f(x, y), (x, y), (0, 1))
+ Subs(g(x, y), (x, y), (0, 1)))
assert name_val == []
assert expr == (Subs(f(x, y), (x, y), (0, 1))
+ Subs(g(x, y), (x, y), (0, 1)))
name_val, (expr,) = cse(
Subs(f(x, y), (x, y), (0, x + y))
+ Subs(g(x, y), (x, y), (0, x + y)))
assert name_val == [(x0, x + y)]
assert expr == Subs(f(x, y), (x, y), (0, x0)) + \
Subs(g(x, y), (x, y), (0, x0))
def test_pow_invpow():
assert cse(1/x**2 + x**2) == \
([(x0, x**2)], [x0 + 1/x0])
assert cse(x**2 + (1 + 1/x**2)/x**2) == \
([(x0, x**2), (x1, 1/x0)], [x0 + x1*(x1 + 1)])
assert cse(1/x**2 + (1 + 1/x**2)*x**2) == \
([(x0, x**2), (x1, 1/x0)], [x0*(x1 + 1) + x1])
assert cse(cos(1/x**2) + sin(1/x**2)) == \
([(x0, x**(-2))], [sin(x0) + cos(x0)])
assert cse(cos(x**2) + sin(x**2)) == \
([(x0, x**2)], [sin(x0) + cos(x0)])
assert cse(y/(2 + x**2) + z/x**2/y) == \
([(x0, x**2)], [y/(x0 + 2) + z/(x0*y)])
assert cse(exp(x**2) + x**2*cos(1/x**2)) == \
([(x0, x**2)], [x0*cos(1/x0) + exp(x0)])
assert cse((1 + 1/x**2)/x**2) == \
([(x0, x**(-2))], [x0*(x0 + 1)])
assert cse(x**(2*y) + x**(-2*y)) == \
([(x0, x**(2*y))], [x0 + 1/x0])
def test_postprocess():
eq = (x + 1 + exp((x + 1)/(y + 1)) + cos(y + 1))
assert cse([eq, Eq(x, z + 1), z - 2, (z + 1)*(x + 1)],
postprocess=cse_main.cse_separate) == \
[[(x1, y + 1), (x2, z + 1), (x, x2), (x0, x + 1)],
[x0 + exp(x0/x1) + cos(x1), z - 2, x0*x2]]
def test_issue_4499():
# previously, this gave 16 constants
from sympy.abc import a, b
B = Function('B')
G = Function('G')
t = Tuple(*
(a, a + S(1)/2, 2*a, b, 2*a - b + 1, (sqrt(z)/2)**(-2*a + 1)*B(2*a -
b, sqrt(z))*B(b - 1, sqrt(z))*G(b)*G(2*a - b + 1),
sqrt(z)*(sqrt(z)/2)**(-2*a + 1)*B(b, sqrt(z))*B(2*a - b,
sqrt(z))*G(b)*G(2*a - b + 1), sqrt(z)*(sqrt(z)/2)**(-2*a + 1)*B(b - 1,
sqrt(z))*B(2*a - b + 1, sqrt(z))*G(b)*G(2*a - b + 1),
(sqrt(z)/2)**(-2*a + 1)*B(b, sqrt(z))*B(2*a - b + 1,
sqrt(z))*G(b)*G(2*a - b + 1), 1, 0, S(1)/2, z/2, -b + 1, -2*a + b,
-2*a))
c = cse(t)
ans = (
[(x0, 2*a), (x1, -b), (x2, x1 + 1), (x3, x0 + x2), (x4, sqrt(z)), (x5,
B(x0 + x1, x4)), (x6, G(b)), (x7, G(x3)), (x8, -x0), (x9,
(x4/2)**(x8 + 1)), (x10, x6*x7*x9*B(b - 1, x4)), (x11, x6*x7*x9*B(b,
x4)), (x12, B(x3, x4))], [(a, a + S(1)/2, x0, b, x3, x10*x5,
x11*x4*x5, x10*x12*x4, x11*x12, 1, 0, S(1)/2, z/2, x2, b + x8, x8)])
assert ans == c
def test_issue_6169():
r = CRootOf(x**6 - 4*x**5 - 2, 1)
assert cse(r) == ([], [r])
# and a check that the right thing is done with the new
# mechanism
assert sub_post(sub_pre((-x - y)*z - x - y)) == -z*(x + y) - x - y
def test_cse_Indexed():
len_y = 5
y = IndexedBase('y', shape=(len_y,))
x = IndexedBase('x', shape=(len_y,))
Dy = IndexedBase('Dy', shape=(len_y-1,))
i = Idx('i', len_y-1)
expr1 = (y[i+1]-y[i])/(x[i+1]-x[i])
expr2 = 1/(x[i+1]-x[i])
replacements, reduced_exprs = cse([expr1, expr2])
assert len(replacements) > 0
def test_cse_MatrixSymbol():
# MatrixSymbols have non-Basic args, so make sure that works
A = MatrixSymbol("A", 3, 3)
assert cse(A) == ([], [A])
n = symbols('n', integer=True)
B = MatrixSymbol("B", n, n)
assert cse(B) == ([], [B])
def test_cse_MatrixExpr():
from sympy import MatrixSymbol
A = MatrixSymbol('A', 3, 3)
y = MatrixSymbol('y', 3, 1)
expr1 = (A.T*A).I * A * y
expr2 = (A.T*A) * A * y
replacements, reduced_exprs = cse([expr1, expr2])
assert len(replacements) > 0
replacements, reduced_exprs = cse([expr1 + expr2, expr1])
assert replacements
replacements, reduced_exprs = cse([A**2, A + A**2])
assert replacements
def test_Piecewise():
f = Piecewise((-z + x*y, Eq(y, 0)), (-z - x*y, True))
ans = cse(f)
actual_ans = ([(x0, -z), (x1, x*y)], [Piecewise((x0+x1, Eq(y, 0)), (x0 - x1, True))])
assert ans == actual_ans
def test_ignore_order_terms():
eq = exp(x).series(x,0,3) + sin(y+x**3) - 1
assert cse(eq) == ([], [sin(x**3 + y) + x + x**2/2 + O(x**3)])
def test_name_conflict():
z1 = x0 + y
z2 = x2 + x3
l = [cos(z1) + z1, cos(z2) + z2, x0 + x2]
substs, reduced = cse(l)
assert [e.subs(reversed(substs)) for e in reduced] == l
def test_name_conflict_cust_symbols():
z1 = x0 + y
z2 = x2 + x3
l = [cos(z1) + z1, cos(z2) + z2, x0 + x2]
substs, reduced = cse(l, symbols("x:10"))
assert [e.subs(reversed(substs)) for e in reduced] == l
def test_symbols_exhausted_error():
l = cos(x+y)+x+y+cos(w+y)+sin(w+y)
sym = [x, y, z]
with raises(ValueError) as excinfo:
cse(l, symbols=sym)
def test_issue_7840():
# daveknippers' example
C393 = sympify( \
'Piecewise((C391 - 1.65, C390 < 0.5), (Piecewise((C391 - 1.65, \
C391 > 2.35), (C392, True)), True))'
)
C391 = sympify( \
'Piecewise((2.05*C390**(-1.03), C390 < 0.5), (2.5*C390**(-0.625), True))'
)
C393 = C393.subs('C391',C391)
# simple substitution
sub = {}
sub['C390'] = 0.703451854
sub['C392'] = 1.01417794
ss_answer = C393.subs(sub)
# cse
substitutions,new_eqn = cse(C393)
for pair in substitutions:
sub[pair[0].name] = pair[1].subs(sub)
cse_answer = new_eqn[0].subs(sub)
# both methods should be the same
assert ss_answer == cse_answer
# GitRay's example
expr = sympify(
"Piecewise((Symbol('ON'), Equality(Symbol('mode'), Symbol('ON'))), \
(Piecewise((Piecewise((Symbol('OFF'), StrictLessThan(Symbol('x'), \
Symbol('threshold'))), (Symbol('ON'), S.true)), Equality(Symbol('mode'), \
Symbol('AUTO'))), (Symbol('OFF'), S.true)), S.true))"
)
substitutions, new_eqn = cse(expr)
# this Piecewise should be exactly the same
assert new_eqn[0] == expr
# there should not be any replacements
assert len(substitutions) < 1
def test_issue_8891():
for cls in (MutableDenseMatrix, MutableSparseMatrix,
ImmutableDenseMatrix, ImmutableSparseMatrix):
m = cls(2, 2, [x + y, 0, 0, 0])
res = cse([x + y, m])
ans = ([(x0, x + y)], [x0, cls([[x0, 0], [0, 0]])])
assert res == ans
assert isinstance(res[1][-1], cls)
def test_issue_11230():
# a specific test that always failed
a, b, f, k, l, i = symbols('a b f k l i')
p = [a*b*f*k*l, a*i*k**2*l, f*i*k**2*l]
R, C = cse(p)
assert not any(i.is_Mul for a in C for i in a.args)
# random tests for the issue
from random import choice
from sympy.core.function import expand_mul
s = symbols('a:m')
# 35 Mul tests, none of which should ever fail
ex = [Mul(*[choice(s) for i in range(5)]) for i in range(7)]
for p in subsets(ex, 3):
p = list(p)
R, C = cse(p)
assert not any(i.is_Mul for a in C for i in a.args)
for ri in reversed(R):
for i in range(len(C)):
C[i] = C[i].subs(*ri)
assert p == C
# 35 Add tests, none of which should ever fail
ex = [Add(*[choice(s[:7]) for i in range(5)]) for i in range(7)]
for p in subsets(ex, 3):
p = list(p)
was = R, C = cse(p)
assert not any(i.is_Add for a in C for i in a.args)
for ri in reversed(R):
for i in range(len(C)):
C[i] = C[i].subs(*ri)
# use expand_mul to handle cases like this:
# p = [a + 2*b + 2*e, 2*b + c + 2*e, b + 2*c + 2*g]
# x0 = 2*(b + e) is identified giving a rebuilt p that
# is now `[a + 2*(b + e), c + 2*(b + e), b + 2*c + 2*g]`
assert p == [expand_mul(i) for i in C]
@XFAIL
def test_issue_11577():
def check(eq):
r, c = cse(eq)
assert eq.count_ops() >= \
len(r) + sum([i[1].count_ops() for i in r]) + \
count_ops(c)
eq = x**5*y**2 + x**5*y + x**5
assert cse(eq) == (
[(x0, x**4), (x1, x*y)], [x**5 + x0*x1*y + x0*x1])
# ([(x0, x**5*y)], [x0*y + x0 + x**5]) or
# ([(x0, x**5)], [x0*y**2 + x0*y + x0])
check(eq)
eq = x**2/(y + 1)**2 + x/(y + 1)
assert cse(eq) == (
[(x0, y + 1)], [x**2/x0**2 + x/x0])
# ([(x0, x/(y + 1))], [x0**2 + x0])
check(eq)
def test_hollow_rejection():
eq = [x + 3, x + 4]
assert cse(eq) == ([], eq)
def test_cse_ignore():
exprs = [exp(y)*(3*y + 3*sqrt(x+1)), exp(y)*(5*y + 5*sqrt(x+1))]
subst1, red1 = cse(exprs)
assert any(y in sub.free_symbols for _, sub in subst1), "cse failed to identify any term with y"
subst2, red2 = cse(exprs, ignore=(y,)) # y is not allowed in substitutions
assert not any(y in sub.free_symbols for _, sub in subst2), "Sub-expressions containing y must be ignored"
assert any(sub - sqrt(x + 1) == 0 for _, sub in subst2), "cse failed to identify sqrt(x + 1) as sub-expression"
def test_cse__performance():
import time
nexprs, nterms = 3, 20
x = symbols('x:%d' % nterms)
exprs = [
reduce(add, [x[j]*(-1)**(i+j) for j in range(nterms)])
for i in range(nexprs)
]
assert (exprs[0] + exprs[1]).simplify() == 0
subst, red = cse(exprs)
assert len(subst) > 0, "exprs[0] == -exprs[2], i.e. a CSE"
for i, e in enumerate(red):
assert (e.subs(reversed(subst)) - exprs[i]).simplify() == 0
def test_issue_12070():
exprs = [x + y, 2 + x + y, x + y + z, 3 + x + y + z]
subst, red = cse(exprs)
assert 6 >= (len(subst) + sum([v.count_ops() for k, v in subst]) +
count_ops(red))
def test_issue_13000():
eq = x/(-4*x**2 + y**2)
cse_eq = cse(eq)[1][0]
assert cse_eq == eq
| [
"[email protected]"
] | |
98ee322836ec34a3a4310506f52b914c4f8634ea | 56bf1dbfa5d23257522fb03906e13c597a829ed3 | /lib/wamp_components/analytics_component.py | 09b1634f64ccea3c071b0d8e16dfe5a84f9696bd | [
"MIT"
] | permissive | fendaq/SerpentAI | 0417777bbc0fccb50df456d0ced1bce839aa3211 | e9c147f33a790a9cd3e4ee631ddbf6bbf91c3921 | refs/heads/master | 2021-07-23T02:04:15.977726 | 2017-08-26T23:31:59 | 2017-08-26T23:31:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,685 | py | import asyncio
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner
from autobahn.wamp.types import RegisterOptions, SubscribeOptions
from autobahn.wamp import auth
from lib.config import config
import aioredis
import json
class AnalyticsComponent:
@classmethod
def run(cls):
print(f"Starting {cls.__name__}...")
url = "ws://%s:%s" % (config["analytics"]["host"], config["analytics"]["port"])
runner = ApplicationRunner(url=url, realm=config["analytics"]["realm"])
runner.run(AnalyticsWAMPComponent)
class AnalyticsWAMPComponent(ApplicationSession):
def __init__(self, c=None):
super().__init__(c)
def onConnect(self):
self.join(config["analytics"]["realm"], ["wampcra"], config["analytics"]["auth"]["username"])
def onDisconnect(self):
print("Disconnected from Crossbar!")
def onChallenge(self, challenge):
secret = config["analytics"]["auth"]["password"]
signature = auth.compute_wcs(secret.encode('utf8'), challenge.extra['challenge'].encode('utf8'))
return signature.decode('ascii')
async def onJoin(self, details):
self.redis_client = await self._initialize_redis_client()
while True:
redis_key, event = await self.redis_client.brpop("SERPENT:AISAAC_MAZE:EVENTS")
event = json.loads(event.decode("utf-8"))
topic = event.pop("project_key")
self.publish(topic, event)
async def _initialize_redis_client(self):
return await aioredis.create_redis(
(config["redis"]["host"], config["redis"]["port"]),
loop=asyncio.get_event_loop()
)
| [
"[email protected]"
] | |
468e2fa105770bc6613f4c974b423ea70ccf8192 | 26b03741c4651eb2f076e51cd34d71f2fb826fcf | /dev/web/Rocky/src/accounts/migrations/0007_wallettransactions.py | ba8f123aea7966fa763c98b89bb2264471459679 | [] | no_license | sreeram315/Rocky---Hardware-project-ATmega-Django-mySQL | 072fc8e9913f22dc0e47a73d29ace6ff1795ed0f | 1ef82b1914bdfc57866e7420e12bf4318cf3f030 | refs/heads/main | 2023-06-04T16:01:51.176564 | 2021-06-21T22:18:01 | 2021-06-21T22:18:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,182 | py | # Generated by Django 2.2.7 on 2020-04-03 05:40
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('accounts', '0006_userprofile_wallet_balance'),
]
operations = [
migrations.CreateModel(
name='WalletTransactions',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('credit', models.IntegerField(default=0)),
('created_on', models.DateTimeField(auto_now_add=True, null=True)),
('updated_on', models.DateTimeField(auto_now=True, null=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='wallet', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'Wallet Transaction',
'verbose_name_plural': 'Wallet Transactions',
'db_table': 'tbl_wallet_transactions',
},
),
]
| [
"[email protected]"
] | |
de0c136c8109404cf6cd1042ce98bf631f321851 | 2dd26e031162e75f37ecb1f7dd7f675eeb634c63 | /nemo/utils/callbacks/nemo_model_checkpoint.py | b96eea0192c57fbb46df4e7688c0b4f841e97c04 | [
"Apache-2.0"
] | permissive | NVIDIA/NeMo | 1b001fa2ae5d14defbfd02f3fe750c5a09e89dd1 | c20a16ea8aa2a9d8e31a98eb22178ddb9d5935e7 | refs/heads/main | 2023-08-21T15:28:04.447838 | 2023-08-21T00:49:36 | 2023-08-21T00:49:36 | 200,722,670 | 7,957 | 1,986 | Apache-2.0 | 2023-09-14T18:49:54 | 2019-08-05T20:16:42 | Python | UTF-8 | Python | false | false | 12,380 | py | # Copyright (c) 2023, NVIDIA CORPORATION. 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.
import os
import re
from copy import deepcopy
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
import pytorch_lightning
import torch
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.utilities import rank_zero_info
from nemo.collections.common.callbacks import EMA
from nemo.utils import logging
from nemo.utils.app_state import AppState
from nemo.utils.get_rank import is_global_rank_zero
from nemo.utils.model_utils import inject_model_parallel_rank, uninject_model_parallel_rank
class NeMoModelCheckpoint(ModelCheckpoint):
""" Light wrapper around Lightning's ModelCheckpoint to force a saved checkpoint on train_end.
Extends Lightning's on_save_checkpoint func to save the .nemo file. Saves the .nemo file based
on the best checkpoint saved (according to the monitor value).
Also contains func to save the EMA copy of the model.
"""
def __init__(
self,
always_save_nemo: bool = False,
save_nemo_on_train_end: bool = True,
save_best_model: bool = False,
postfix: str = ".nemo",
n_resume: bool = False,
model_parallel_size: int = None,
**kwargs,
):
# Parse and store "extended" parameters: save_best model and postfix.
self.always_save_nemo = always_save_nemo
self.save_nemo_on_train_end = save_nemo_on_train_end
self.save_best_model = save_best_model
if self.save_best_model and not self.save_nemo_on_train_end:
logging.warning(
(
"Found save_best_model is True and save_nemo_on_train_end is False. "
"Set save_nemo_on_train_end to True to automatically save the best model."
)
)
self.postfix = postfix
self.previous_best_path = ""
self.model_parallel_size = model_parallel_size
# `prefix` is deprecated
if 'prefix' in kwargs:
self.prefix = kwargs.pop('prefix')
else:
self.prefix = ""
# Call the parent class constructor with the remaining kwargs.
super().__init__(**kwargs)
if self.save_top_k != -1 and n_resume:
logging.debug("Checking previous runs")
self.nemo_topk_check_previous_run()
def nemo_topk_check_previous_run(self):
try:
self.best_k_models
self.kth_best_model_path
self.best_model_score
self.best_model_path
except AttributeError:
raise AttributeError("Lightning's ModelCheckpoint was updated. NeMoModelCheckpoint will need an update.")
self.best_k_models = {}
self.kth_best_model_path = ""
self.best_model_score = None
self.best_model_path = ""
checkpoints = list(path for path in self._saved_checkpoint_paths if not self._is_ema_filepath(path))
for checkpoint in checkpoints:
if 'mp_rank' in str(checkpoint) or 'tp_rank' in str(checkpoint):
checkpoint = uninject_model_parallel_rank(checkpoint)
checkpoint = str(checkpoint)
if checkpoint[-10:] == '-last.ckpt':
continue
index = checkpoint.find(self.monitor) + len(self.monitor) + 1 # Find monitor in str + 1 for '='
if index != len(self.monitor):
match = re.search('[A-z]', checkpoint[index:])
if match:
value = checkpoint[index : index + match.start() - 1] # -1 due to separator hypen
self.best_k_models[checkpoint] = float(value)
if len(self.best_k_models) < 1:
return # No saved checkpoints yet
_reverse = False if self.mode == "min" else True
best_k_models = sorted(self.best_k_models, key=self.best_k_models.get, reverse=_reverse)
### This section should be ok as rank zero will delete all excess checkpoints, since all other ranks are
### instantiated after rank zero. models_to_delete should be 0 for all other ranks.
if self.model_parallel_size is not None:
models_to_delete = len(best_k_models) - self.model_parallel_size * self.save_top_k
else:
models_to_delete = len(best_k_models) - self.save_top_k
logging.debug(f'Number of models to delete: {models_to_delete}')
# If EMA enabled, delete the additional EMA weights
ema_enabled = self._has_ema_ckpts(self._saved_checkpoint_paths)
for _ in range(models_to_delete):
model = best_k_models.pop(-1)
self.best_k_models.pop(model)
self._del_model_without_trainer(model)
if ema_enabled and self._fs.exists(self._ema_format_filepath(model)):
self._del_model_without_trainer(self._ema_format_filepath(model))
logging.debug(f"Removed checkpoint: {model}")
self.kth_best_model_path = best_k_models[-1]
self.best_model_path = best_k_models[0]
self.best_model_score = self.best_k_models[self.best_model_path]
def on_save_checkpoint(self, trainer, pl_module, checkpoint):
output = super().on_save_checkpoint(trainer, pl_module, checkpoint)
if not self.always_save_nemo:
return output
# Load the best model and then re-save it
app_state = AppState()
if app_state.model_parallel_size is not None and app_state.model_parallel_size > 1:
logging.warning(f'always_save_nemo will slow down training for model_parallel > 1.')
# since we are creating tarfile artifacts we need to update .nemo path
app_state.model_restore_path = os.path.abspath(
os.path.expanduser(os.path.join(self.dirpath, self.prefix + self.postfix))
)
if app_state.model_parallel_size is not None and app_state.model_parallel_size > 1:
maybe_injected_best_model_path = inject_model_parallel_rank(self.best_model_path)
else:
maybe_injected_best_model_path = self.best_model_path
if self.save_best_model:
if not os.path.exists(maybe_injected_best_model_path):
return
if self.best_model_path == self.previous_best_path:
return output
self.previous_model_path = self.best_model_path
old_state_dict = deepcopy(pl_module.state_dict())
checkpoint = torch.load(maybe_injected_best_model_path, map_location='cpu')
if 'state_dict' in checkpoint:
checkpoint = checkpoint['state_dict']
# get a new instanace of the model
pl_module.load_state_dict(checkpoint, strict=True)
if torch.distributed.is_initialized():
torch.distributed.barrier()
pl_module.save_to(save_path=app_state.model_restore_path)
logging.info(f"New best .nemo model saved to: {app_state.model_restore_path}")
pl_module.load_state_dict(old_state_dict, strict=True)
else:
if torch.distributed.is_initialized():
torch.distributed.barrier()
pl_module.save_to(save_path=app_state.model_restore_path)
logging.info(f"New .nemo model saved to: {app_state.model_restore_path}")
return output
def on_train_end(self, trainer, pl_module):
if trainer.fast_dev_run:
return None
# check if we need to save a last checkpoint manually as validation isn't always run based on the interval
if self.save_last and trainer.val_check_interval != 0:
should_save_last_checkpoint = False
if isinstance(trainer.val_check_interval, float) and trainer.val_check_interval % trainer.global_step != 0:
should_save_last_checkpoint = True
if isinstance(trainer.val_check_interval, int) and trainer.global_step % trainer.val_check_interval != 0:
should_save_last_checkpoint = True
if should_save_last_checkpoint:
monitor_candidates = self._monitor_candidates(trainer)
super()._save_last_checkpoint(trainer, monitor_candidates)
# Call parent on_train_end() to save the -last checkpoint
super().on_train_end(trainer, pl_module)
# Load the best model and then re-save it
if self.save_best_model:
# wait for all processes
trainer.strategy.barrier("SaveBestCheckpointConnector.resume_end")
if self.best_model_path == "":
logging.warning(
f"{self} was told to save the best checkpoint at the end of training, but no saved checkpoints "
"were found. Saving latest model instead."
)
else:
self.best_model_path = trainer.strategy.broadcast(self.best_model_path)
trainer._checkpoint_connector.restore(self.best_model_path)
if self.save_nemo_on_train_end:
pl_module.save_to(save_path=os.path.join(self.dirpath, self.prefix + self.postfix))
def _del_model_without_trainer(self, filepath: str) -> None:
app_state = AppState()
if app_state.model_parallel_size is not None and app_state.model_parallel_size > 1:
# filepath needs to be updated to include mp_rank
filepath = inject_model_parallel_rank(filepath)
# each model parallel rank needs to remove its model
if is_global_rank_zero() or (app_state.model_parallel_size is not None and app_state.data_parallel_rank == 0):
try:
self._fs.rm(filepath)
logging.info(f"Removed checkpoint: {filepath}")
except:
logging.info(f"Tried to remove checkpoint: {filepath} but failed.")
def _ema_callback(self, trainer: 'pytorch_lightning.Trainer') -> Optional[EMA]:
ema_callback = None
for callback in trainer.callbacks:
if isinstance(callback, EMA):
ema_callback = callback
return ema_callback
def _save_checkpoint(self, trainer: 'pytorch_lightning.Trainer', filepath: str) -> None:
ema_callback = self._ema_callback(trainer)
if ema_callback is not None:
with ema_callback.save_original_optimizer_state(trainer):
super()._save_checkpoint(trainer, filepath)
# save EMA copy of the model as well.
with ema_callback.save_ema_model(trainer):
filepath = self._ema_format_filepath(filepath)
if self.verbose:
rank_zero_info(f"Saving EMA weights to separate checkpoint {filepath}")
super()._save_checkpoint(trainer, filepath)
else:
super()._save_checkpoint(trainer, filepath)
def _remove_checkpoint(self, trainer: "pytorch_lightning.Trainer", filepath: str) -> None:
super()._remove_checkpoint(trainer, filepath)
ema_callback = self._ema_callback(trainer)
if ema_callback is not None:
# remove EMA copy of the state dict as well.
filepath = self._ema_format_filepath(filepath)
super()._remove_checkpoint(trainer, filepath)
def _ema_format_filepath(self, filepath: str) -> str:
return filepath.replace(self.FILE_EXTENSION, f'-EMA{self.FILE_EXTENSION}')
def _has_ema_ckpts(self, checkpoints: Iterable[Path]) -> bool:
return any(self._is_ema_filepath(checkpoint_path) for checkpoint_path in checkpoints)
def _is_ema_filepath(self, filepath: Union[Path, str]) -> bool:
return str(filepath).endswith(f'-EMA{self.FILE_EXTENSION}')
@property
def _saved_checkpoint_paths(self) -> Iterable[Path]:
return Path(self.dirpath).rglob("*.ckpt")
| [
"[email protected]"
] | |
054b06d9579be1ed0da49ab1d44ab99a4bdf7eaf | 27b86f422246a78704e0e84983b2630533a47db6 | /docs/source/tutorials/src/hatch/solid_hatch_true_color.py | 71612e3499d520bbc0a4d87c8b1813705602c924 | [
"MIT"
] | permissive | mozman/ezdxf | 7512decd600896960660f0f580cab815bf0d7a51 | ba6ab0264dcb6833173042a37b1b5ae878d75113 | refs/heads/master | 2023-09-01T11:55:13.462105 | 2023-08-15T11:50:05 | 2023-08-15T12:00:04 | 79,697,117 | 750 | 194 | MIT | 2023-09-14T09:40:41 | 2017-01-22T05:55:55 | Python | UTF-8 | Python | false | false | 598 | py | import ezdxf
# hatch with true color requires DXF R2004 or later
doc = ezdxf.new("R2004")
msp = doc.modelspace()
# important: major axis >= minor axis (ratio <= 1.)
msp.add_ellipse((0, 0), major_axis=(0, 10), ratio=0.5)
hatch = msp.add_hatch() # use default ACI fill color
hatch.rgb = (211, 40, 215)
# every boundary path is a 2D element
edge_path = hatch.paths.add_edge_path()
# each edge path can contain line arc, ellipse and spline elements
# important: major axis >= minor axis (ratio <= 1.)
edge_path.add_ellipse((0, 0), major_axis=(0, 10), ratio=0.5)
doc.saveas("solid_rgb_hatch.dxf")
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.