repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
ppb/pursuedpybear | ppb/scenes.py | BaseScene.get | python | def get(self, *, kind: Type=None, tag: Hashable=None, **kwargs) -> Iterator:
return self.game_objects.get(kind=kind, tag=tag, **kwargs) | Get an iterator of GameObjects by kind or tag.
kind: Any type. Pass to get a subset of contained GameObjects with the
given type.
tag: Any Hashable object. Pass to get a subset of contained GameObjects
with the given tag.
Pass both kind and tag to get objects that ar... | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/scenes.py#L171-L190 | null | class BaseScene(Scene, EventMixin):
# Background color, in RGB, each channel is 0-255
background_color: Sequence[int] = (0, 0, 100)
container_class: Type = GameObjectCollection
def __init__(self, engine, *,
set_up: Callable=None, pixel_ratio: Number=64,
... |
ppb/pursuedpybear | setup.py | requirements | python | def requirements(section=None):
if section is None:
filename = "requirements.txt"
else:
filename = f"requirements-{section}.txt"
with open(filename) as file:
return [line.strip() for line in file] | Helper for loading dependencies from requirements files. | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/setup.py#L5-L13 | null | #!/usr/bin/env python3
from setuptools import setup
# See setup.cfg for the actual configuration.
setup(
install_requires=requirements(),
tests_require=requirements('tests'),
)
|
iKevinY/EulerPy | EulerPy/utils.py | problem_glob | python | def problem_glob(extension='.py'):
filenames = glob.glob('*[0-9][0-9][0-9]*{}'.format(extension))
return [ProblemFile(file) for file in filenames] | Returns ProblemFile objects for all valid problem files | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/utils.py#L12-L15 | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
import glob
import math
from EulerPy.problem import ProblemFile
# Use the resource module instead of time.clock() if possible (on Unix)
try:
import resource
except ImportError:
import time
def clock():
"""
Unde... |
iKevinY/EulerPy | EulerPy/utils.py | human_time | python | def human_time(timespan, precision=3):
if timespan >= 60.0:
# Format time greater than one minute in a human-readable format
# Idea from http://snipplr.com/view/5713/
def _format_long_time(time):
suffixes = ('d', 'h', 'm', 's')
lengths = (24*60*60, 60*60, 60, 1)
... | Formats the timespan in a human readable format | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/utils.py#L41-L81 | [
"def _format_long_time(time):\n suffixes = ('d', 'h', 'm', 's')\n lengths = (24*60*60, 60*60, 60, 1)\n\n for suffix, length in zip(suffixes, lengths):\n value = int(time / length)\n\n if value > 0:\n time %= length\n yield '%i%s' % (value, suffix)\n\n if time < 1:... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
import glob
import math
from EulerPy.problem import ProblemFile
def problem_glob(extension='.py'):
"""Returns ProblemFile objects for all valid problem files"""
filenames = glob.glob('*[0-9][0-9][0-9]*{}'.format(extension))
retu... |
iKevinY/EulerPy | EulerPy/utils.py | format_time | python | def format_time(start, end):
try:
cpu_usr = end[0] - start[0]
cpu_sys = end[1] - start[1]
except TypeError:
# `clock()[1] == None` so subtraction results in a TypeError
return 'Time elapsed: {}'.format(human_time(cpu_usr))
else:
times = (human_time(x) for x in (cpu_... | Returns string with relevant time information formatted properly | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/utils.py#L84-L96 | [
"def human_time(timespan, precision=3):\n \"\"\"Formats the timespan in a human readable format\"\"\"\n\n if timespan >= 60.0:\n # Format time greater than one minute in a human-readable format\n # Idea from http://snipplr.com/view/5713/\n def _format_long_time(time):\n suffixe... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
import glob
import math
from EulerPy.problem import ProblemFile
def problem_glob(extension='.py'):
"""Returns ProblemFile objects for all valid problem files"""
filenames = glob.glob('*[0-9][0-9][0-9]*{}'.format(extension))
retu... |
iKevinY/EulerPy | EulerPy/problem.py | Problem.filename | python | def filename(self, prefix='', suffix='', extension='.py'):
return BASE_NAME.format(prefix, self.num, suffix, extension) | Returns filename padded with leading zeros | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/problem.py#L25-L27 | null | class Problem(object):
"""Represents a Project Euler problem of a given problem number"""
def __init__(self, problem_number):
self.num = problem_number
@property
def glob(self):
"""Returns a sorted glob of files belonging to a given problem"""
file_glob = glob.glob(BASE_NAME.fo... |
iKevinY/EulerPy | EulerPy/problem.py | Problem.glob | python | def glob(self):
file_glob = glob.glob(BASE_NAME.format('*', self.num, '*', '.*'))
# Sort globbed files by tuple (filename, extension)
return sorted(file_glob, key=lambda f: os.path.splitext(f)) | Returns a sorted glob of files belonging to a given problem | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/problem.py#L30-L35 | null | class Problem(object):
"""Represents a Project Euler problem of a given problem number"""
def __init__(self, problem_number):
self.num = problem_number
def filename(self, prefix='', suffix='', extension='.py'):
"""Returns filename padded with leading zeros"""
return BASE_NAME.format... |
iKevinY/EulerPy | EulerPy/problem.py | Problem.resources | python | def resources(self):
with open(os.path.join(EULER_DATA, 'resources.json')) as data_file:
data = json.load(data_file)
problem_num = str(self.num)
if problem_num in data:
files = data[problem_num]
# Ensure a list of files is returned
return files ... | Returns a list of resources related to the problem (or None) | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/problem.py#L43-L56 | null | class Problem(object):
"""Represents a Project Euler problem of a given problem number"""
def __init__(self, problem_number):
self.num = problem_number
def filename(self, prefix='', suffix='', extension='.py'):
"""Returns filename padded with leading zeros"""
return BASE_NAME.format... |
iKevinY/EulerPy | EulerPy/problem.py | Problem.copy_resources | python | def copy_resources(self):
if not os.path.isdir('resources'):
os.mkdir('resources')
resource_dir = os.path.join(os.getcwd(), 'resources', '')
copied_resources = []
for resource in self.resources:
src = os.path.join(EULER_DATA, 'resources', resource)
i... | Copies the relevant resources to a resources subdirectory | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/problem.py#L58-L77 | null | class Problem(object):
"""Represents a Project Euler problem of a given problem number"""
def __init__(self, problem_number):
self.num = problem_number
def filename(self, prefix='', suffix='', extension='.py'):
"""Returns filename padded with leading zeros"""
return BASE_NAME.format... |
iKevinY/EulerPy | EulerPy/problem.py | Problem.solution | python | def solution(self):
num = self.num
solution_file = os.path.join(EULER_DATA, 'solutions.txt')
solution_line = linecache.getline(solution_file, num)
try:
answer = solution_line.split('. ')[1].strip()
except IndexError:
answer = None
if answer:
... | Returns the answer to a given problem | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/problem.py#L80-L99 | null | class Problem(object):
"""Represents a Project Euler problem of a given problem number"""
def __init__(self, problem_number):
self.num = problem_number
def filename(self, prefix='', suffix='', extension='.py'):
"""Returns filename padded with leading zeros"""
return BASE_NAME.format... |
iKevinY/EulerPy | EulerPy/problem.py | Problem.text | python | def text(self):
def _problem_iter(problem_num):
problem_file = os.path.join(EULER_DATA, 'problems.txt')
with open(problem_file) as f:
is_problem = False
last_line = ''
for line in f:
if line.strip() == 'Problem %i' % p... | Parses problems.txt and returns problem text | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/problem.py#L102-L134 | [
"def _problem_iter(problem_num):\n problem_file = os.path.join(EULER_DATA, 'problems.txt')\n\n with open(problem_file) as f:\n is_problem = False\n last_line = ''\n\n for line in f:\n if line.strip() == 'Problem %i' % problem_num:\n is_problem = True\n\n ... | class Problem(object):
"""Represents a Project Euler problem of a given problem number"""
def __init__(self, problem_number):
self.num = problem_number
def filename(self, prefix='', suffix='', extension='.py'):
"""Returns filename padded with leading zeros"""
return BASE_NAME.format... |
iKevinY/EulerPy | EulerPy/euler.py | cheat | python | def cheat(num):
# Define solution before echoing in case solution does not exist
solution = click.style(Problem(num).solution, bold=True)
click.confirm("View answer to problem %i?" % num, abort=True)
click.echo("The answer to problem {} is {}.".format(num, solution)) | View the answer to a problem. | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L16-L21 | null | # -*- coding: utf-8 -*-
import os
import sys
import subprocess
from collections import OrderedDict
import click
from EulerPy import __version__
from EulerPy.problem import Problem
from EulerPy.utils import clock, format_time, problem_glob
# --cheat / -c
# --generate / -g
def generate(num, prompt_default=True):
... |
iKevinY/EulerPy | EulerPy/euler.py | generate | python | def generate(num, prompt_default=True):
p = Problem(num)
problem_text = p.text
msg = "Generate file for problem %i?" % num
click.confirm(msg, default=prompt_default, abort=True)
# Allow skipped problem files to be recreated
if p.glob:
filename = str(p.file)
msg = '"{}" already... | Generates Python file for a problem. | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L25-L57 | [
"def filename(self, prefix='', suffix='', extension='.py'):\n \"\"\"Returns filename padded with leading zeros\"\"\"\n return BASE_NAME.format(prefix, self.num, suffix, extension)\n",
"def copy_resources(self):\n \"\"\"Copies the relevant resources to a resources subdirectory\"\"\"\n if not os.path.is... | # -*- coding: utf-8 -*-
import os
import sys
import subprocess
from collections import OrderedDict
import click
from EulerPy import __version__
from EulerPy.problem import Problem
from EulerPy.utils import clock, format_time, problem_glob
# --cheat / -c
def cheat(num):
"""View the answer to a problem."""
#... |
iKevinY/EulerPy | EulerPy/euler.py | preview | python | def preview(num):
# Define problem_text before echoing in case problem does not exist
problem_text = Problem(num).text
click.secho("Project Euler Problem %i" % num, bold=True)
click.echo(problem_text) | Prints the text of a problem. | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L61-L66 | null | # -*- coding: utf-8 -*-
import os
import sys
import subprocess
from collections import OrderedDict
import click
from EulerPy import __version__
from EulerPy.problem import Problem
from EulerPy.utils import clock, format_time, problem_glob
# --cheat / -c
def cheat(num):
"""View the answer to a problem."""
#... |
iKevinY/EulerPy | EulerPy/euler.py | skip | python | def skip(num):
click.echo("Current problem is problem %i." % num)
generate(num + 1, prompt_default=False)
Problem(num).file.change_suffix('-skipped') | Generates Python file for the next problem. | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L70-L74 | [
"def generate(num, prompt_default=True):\n \"\"\"Generates Python file for a problem.\"\"\"\n p = Problem(num)\n\n problem_text = p.text\n\n msg = \"Generate file for problem %i?\" % num\n click.confirm(msg, default=prompt_default, abort=True)\n\n # Allow skipped problem files to be recreated\n ... | # -*- coding: utf-8 -*-
import os
import sys
import subprocess
from collections import OrderedDict
import click
from EulerPy import __version__
from EulerPy.problem import Problem
from EulerPy.utils import clock, format_time, problem_glob
# --cheat / -c
def cheat(num):
"""View the answer to a problem."""
#... |
iKevinY/EulerPy | EulerPy/euler.py | verify | python | def verify(num, filename=None, exit=True):
p = Problem(num)
filename = filename or p.filename()
if not os.path.isfile(filename):
# Attempt to verify the first problem file matched by glob
if p.glob:
filename = str(p.file)
else:
click.secho('No file found for... | Verifies the solution to a problem. | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L78-L136 | [
"def clock():\n \"\"\"\n Under Windows, system CPU time can't be measured. Return time.clock()\n as user time and None as system time.\n \"\"\"\n return time.clock(), None\n",
"def clock():\n \"\"\"\n Returns a tuple (t_user, t_system) since the start of the process.\n This is done via a c... | # -*- coding: utf-8 -*-
import os
import sys
import subprocess
from collections import OrderedDict
import click
from EulerPy import __version__
from EulerPy.problem import Problem
from EulerPy.utils import clock, format_time, problem_glob
# --cheat / -c
def cheat(num):
"""View the answer to a problem."""
#... |
iKevinY/EulerPy | EulerPy/euler.py | verify_all | python | def verify_all(num):
# Define various problem statuses
keys = ('correct', 'incorrect', 'error', 'skipped', 'missing')
symbols = ('C', 'I', 'E', 'S', '.')
colours = ('green', 'red', 'yellow', 'cyan', 'white')
status = OrderedDict(
(key, click.style(symbol, fg=colour, bold=True))
for... | Verifies all problem files in the current directory and
prints an overview of the status of each problem. | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L140-L214 | [
"def problem_glob(extension='.py'):\n \"\"\"Returns ProblemFile objects for all valid problem files\"\"\"\n filenames = glob.glob('*[0-9][0-9][0-9]*{}'.format(extension))\n return [ProblemFile(file) for file in filenames]\n",
"def verify(num, filename=None, exit=True):\n \"\"\"Verifies the solution to... | # -*- coding: utf-8 -*-
import os
import sys
import subprocess
from collections import OrderedDict
import click
from EulerPy import __version__
from EulerPy.problem import Problem
from EulerPy.utils import clock, format_time, problem_glob
# --cheat / -c
def cheat(num):
"""View the answer to a problem."""
#... |
iKevinY/EulerPy | EulerPy/euler.py | euler_options | python | def euler_options(fn):
euler_functions = cheat, generate, preview, skip, verify, verify_all
# Reverse functions to print help page options in alphabetical order
for option in reversed(euler_functions):
name, docstring = option.__name__, option.__doc__
kwargs = {'flag_value': option, 'help':... | Decorator to link CLI options with their appropriate functions | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L217-L232 | null | # -*- coding: utf-8 -*-
import os
import sys
import subprocess
from collections import OrderedDict
import click
from EulerPy import __version__
from EulerPy.problem import Problem
from EulerPy.utils import clock, format_time, problem_glob
# --cheat / -c
def cheat(num):
"""View the answer to a problem."""
#... |
iKevinY/EulerPy | EulerPy/euler.py | main | python | def main(option, problem):
# No problem given (or given option ignores the problem argument)
if problem == 0 or option in {skip, verify_all}:
# Determine the highest problem number in the current directory
files = problem_glob()
problem = max(file.num for file in files) if files else 0
... | Python-based Project Euler command line tool. | train | https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L239-L275 | [
"def problem_glob(extension='.py'):\n \"\"\"Returns ProblemFile objects for all valid problem files\"\"\"\n filenames = glob.glob('*[0-9][0-9][0-9]*{}'.format(extension))\n return [ProblemFile(file) for file in filenames]\n",
"def generate(num, prompt_default=True):\n \"\"\"Generates Python file for a... | # -*- coding: utf-8 -*-
import os
import sys
import subprocess
from collections import OrderedDict
import click
from EulerPy import __version__
from EulerPy.problem import Problem
from EulerPy.utils import clock, format_time, problem_glob
# --cheat / -c
def cheat(num):
"""View the answer to a problem."""
#... |
shidenggui/easyquotation | easyquotation/helpers.py | update_stock_codes | python | def update_stock_codes():
all_stock_codes_url = "http://www.shdjt.com/js/lib/astock.js"
grep_stock_codes = re.compile(r"~(\d+)`")
response = requests.get(all_stock_codes_url)
all_stock_codes = grep_stock_codes.findall(response.text)
with open(stock_code_path(), "w") as f:
f.write(json.dumps(... | 获取所有股票 ID 到 all_stock_code 目录下 | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/helpers.py#L11-L18 | [
"def stock_code_path():\n return os.path.join(os.path.dirname(__file__), STOCK_CODE_PATH)\n"
] | # coding:utf8
import json
import os
import re
import requests
STOCK_CODE_PATH = "stock_codes.conf"
def get_stock_codes(realtime=False):
"""获取所有股票 ID 到 all_stock_code 目录下"""
if realtime:
all_stock_codes_url = "http://www.shdjt.com/js/lib/astock.js"
grep_stock_codes = re.compile(r"~(\d+)`")
... |
shidenggui/easyquotation | easyquotation/helpers.py | get_stock_codes | python | def get_stock_codes(realtime=False):
if realtime:
all_stock_codes_url = "http://www.shdjt.com/js/lib/astock.js"
grep_stock_codes = re.compile(r"~(\d+)`")
response = requests.get(all_stock_codes_url)
stock_codes = grep_stock_codes.findall(response.text)
with open(stock_code_pa... | 获取所有股票 ID 到 all_stock_code 目录下 | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/helpers.py#L21-L33 | [
"def stock_code_path():\n return os.path.join(os.path.dirname(__file__), STOCK_CODE_PATH)\n"
] | # coding:utf8
import json
import os
import re
import requests
STOCK_CODE_PATH = "stock_codes.conf"
def update_stock_codes():
"""获取所有股票 ID 到 all_stock_code 目录下"""
all_stock_codes_url = "http://www.shdjt.com/js/lib/astock.js"
grep_stock_codes = re.compile(r"~(\d+)`")
response = requests.get(all_stock_... |
shidenggui/easyquotation | easyquotation/basequotation.py | BaseQuotation.real | python | def real(self, stock_codes, prefix=False):
if not isinstance(stock_codes, list):
stock_codes = [stock_codes]
stock_list = self.gen_stock_list(stock_codes)
return self.get_stock_data(stock_list, prefix=prefix) | return specific stocks real quotation
:param stock_codes: stock code or list of stock code,
when prefix is True, stock code must start with sh/sz
:param prefix: if prefix i True, stock_codes must contain sh/sz market
flag. If prefix is False, index quotation can't return
... | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/basequotation.py#L73-L87 | [
"def gen_stock_list(self, stock_codes):\n stock_with_exchange_list = self._gen_stock_prefix(stock_codes)\n\n if self.max_num > len(stock_with_exchange_list):\n request_list = \",\".join(stock_with_exchange_list)\n return [request_list]\n\n stock_list = []\n request_num = len(stock_codes) /... | class BaseQuotation(metaclass=abc.ABCMeta):
"""行情获取基类"""
max_num = 800 # 每次请求的最大股票数
@property
@abc.abstractmethod
def stock_api(self) -> str:
"""
行情 api 地址
"""
pass
def __init__(self):
self._session = requests.session()
stock_codes = self.load_... |
shidenggui/easyquotation | easyquotation/basequotation.py | BaseQuotation.market_snapshot | python | def market_snapshot(self, prefix=False):
return self.get_stock_data(self.stock_list, prefix=prefix) | return all market quotation snapshot
:param prefix: if prefix is True, return quotation dict's stock_code
key start with sh/sz market flag | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/basequotation.py#L89-L94 | [
"def get_stock_data(self, stock_list, **kwargs):\n \"\"\"获取并格式化股票信息\"\"\"\n res = self._fetch_stock_data(stock_list)\n return self.format_response_data(res, **kwargs)\n"
] | class BaseQuotation(metaclass=abc.ABCMeta):
"""行情获取基类"""
max_num = 800 # 每次请求的最大股票数
@property
@abc.abstractmethod
def stock_api(self) -> str:
"""
行情 api 地址
"""
pass
def __init__(self):
self._session = requests.session()
stock_codes = self.load_... |
shidenggui/easyquotation | easyquotation/basequotation.py | BaseQuotation.get_stock_data | python | def get_stock_data(self, stock_list, **kwargs):
res = self._fetch_stock_data(stock_list)
return self.format_response_data(res, **kwargs) | 获取并格式化股票信息 | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/basequotation.py#L109-L112 | [
"def _fetch_stock_data(self, stock_list):\n \"\"\"获取股票信息\"\"\"\n pool = multiprocessing.pool.ThreadPool(len(stock_list))\n try:\n res = pool.map(self.get_stocks_by_range, stock_list)\n finally:\n pool.close()\n return [d for d in res if d is not None]\n",
"def format_response_data(sel... | class BaseQuotation(metaclass=abc.ABCMeta):
"""行情获取基类"""
max_num = 800 # 每次请求的最大股票数
@property
@abc.abstractmethod
def stock_api(self) -> str:
"""
行情 api 地址
"""
pass
def __init__(self):
self._session = requests.session()
stock_codes = self.load_... |
shidenggui/easyquotation | easyquotation/basequotation.py | BaseQuotation._fetch_stock_data | python | def _fetch_stock_data(self, stock_list):
pool = multiprocessing.pool.ThreadPool(len(stock_list))
try:
res = pool.map(self.get_stocks_by_range, stock_list)
finally:
pool.close()
return [d for d in res if d is not None] | 获取股票信息 | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/basequotation.py#L114-L121 | null | class BaseQuotation(metaclass=abc.ABCMeta):
"""行情获取基类"""
max_num = 800 # 每次请求的最大股票数
@property
@abc.abstractmethod
def stock_api(self) -> str:
"""
行情 api 地址
"""
pass
def __init__(self):
self._session = requests.session()
stock_codes = self.load_... |
shidenggui/easyquotation | easyquotation/timekline.py | TimeKline._fetch_stock_data | python | def _fetch_stock_data(self, stock_list):
res = super()._fetch_stock_data(stock_list)
with_stock = []
for stock, resp in zip(stock_list, res):
if resp is not None:
with_stock.append((stock, resp))
return with_stock | 因为 timekline 的返回没有带对应的股票代码,所以要手动带上 | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/timekline.py#L29-L37 | null | class TimeKline(basequotation.BaseQuotation):
"""腾讯免费行情获取"""
max_num = 1
@property
def stock_api(self) -> str:
return "http://data.gtimg.cn/flashdata/hushen/minute/"
def _gen_stock_prefix(self, stock_codes):
return [
easyutils.stock.get_stock_type(code) + code[-6:] + "... |
shidenggui/easyquotation | easyquotation/jsl.py | Jsl.formatfundajson | python | def formatfundajson(fundajson):
result = {}
for row in fundajson["rows"]:
funda_id = row["id"]
cell = row["cell"]
result[funda_id] = cell
return result | 格式化集思录返回的json数据,以字典形式保存 | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/jsl.py#L101-L108 | null | class Jsl:
"""
抓取集思路的分级A数据
"""
# 分级A的接口
__funda_url = "http://www.jisilu.cn/data/sfnew/funda_list/?___t={ctime:d}"
# 分级B的接口
__fundb_url = "http://www.jisilu.cn/data/sfnew/fundb_list/?___t={ctime:d}"
# 母基接口
__fundm_url = "https://www.jisilu.cn/data/sfnew/fundm_list/?___t={ctime:d}"... |
shidenggui/easyquotation | easyquotation/jsl.py | Jsl.formatfundbjson | python | def formatfundbjson(fundbjson):
result = {}
for row in fundbjson["rows"]:
cell = row["cell"]
fundb_id = cell["fundb_id"]
result[fundb_id] = cell
return result | 格式化集思录返回的json数据,以字典形式保存 | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/jsl.py#L111-L118 | null | class Jsl:
"""
抓取集思路的分级A数据
"""
# 分级A的接口
__funda_url = "http://www.jisilu.cn/data/sfnew/funda_list/?___t={ctime:d}"
# 分级B的接口
__fundb_url = "http://www.jisilu.cn/data/sfnew/fundb_list/?___t={ctime:d}"
# 母基接口
__fundm_url = "https://www.jisilu.cn/data/sfnew/fundm_list/?___t={ctime:d}"... |
shidenggui/easyquotation | easyquotation/jsl.py | Jsl.formatetfindexjson | python | def formatetfindexjson(fundbjson):
result = {}
for row in fundbjson["rows"]:
cell = row["cell"]
fundb_id = cell["fund_id"]
result[fundb_id] = cell
return result | 格式化集思录返回 指数ETF 的json数据,以字典形式保存 | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/jsl.py#L121-L128 | null | class Jsl:
"""
抓取集思路的分级A数据
"""
# 分级A的接口
__funda_url = "http://www.jisilu.cn/data/sfnew/funda_list/?___t={ctime:d}"
# 分级B的接口
__fundb_url = "http://www.jisilu.cn/data/sfnew/fundb_list/?___t={ctime:d}"
# 母基接口
__fundm_url = "https://www.jisilu.cn/data/sfnew/fundm_list/?___t={ctime:d}"... |
shidenggui/easyquotation | easyquotation/jsl.py | Jsl.funda | python | def funda(
self,
fields=None,
min_volume=0,
min_discount=0,
ignore_nodown=False,
forever=False,
):
if fields is None:
fields = []
# 添加当前的ctime
self.__funda_url = self.__funda_url.format(ctime=int(time.time()))
# 请求数据
... | 以字典形式返回分级A数据
:param fields:利率范围,形如['+3.0%', '6.0%']
:param min_volume:最小交易量,单位万元
:param min_discount:最小折价率, 单位%
:param ignore_nodown:是否忽略无下折品种,默认 False
:param forever: 是否选择永续品种,默认 False | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/jsl.py#L148-L207 | [
"def formatfundajson(fundajson):\n \"\"\"格式化集思录返回的json数据,以字典形式保存\"\"\"\n result = {}\n for row in fundajson[\"rows\"]:\n funda_id = row[\"id\"]\n cell = row[\"cell\"]\n result[funda_id] = cell\n return result\n"
] | class Jsl:
"""
抓取集思路的分级A数据
"""
# 分级A的接口
__funda_url = "http://www.jisilu.cn/data/sfnew/funda_list/?___t={ctime:d}"
# 分级B的接口
__fundb_url = "http://www.jisilu.cn/data/sfnew/fundb_list/?___t={ctime:d}"
# 母基接口
__fundm_url = "https://www.jisilu.cn/data/sfnew/fundm_list/?___t={ctime:d}"... |
shidenggui/easyquotation | easyquotation/jsl.py | Jsl.fundm | python | def fundm(self):
# 添加当前的ctime
self.__fundm_url = self.__fundm_url.format(ctime=int(time.time()))
# 请求数据
rep = requests.get(self.__fundm_url)
# 获取返回的json字符串
fundmjson = json.loads(rep.text)
# 格式化返回的json字符串
data = self.formatfundajson(fundmjson)
self... | 以字典形式返回分级母基数据 | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/jsl.py#L209-L221 | [
"def formatfundajson(fundajson):\n \"\"\"格式化集思录返回的json数据,以字典形式保存\"\"\"\n result = {}\n for row in fundajson[\"rows\"]:\n funda_id = row[\"id\"]\n cell = row[\"cell\"]\n result[funda_id] = cell\n return result\n"
] | class Jsl:
"""
抓取集思路的分级A数据
"""
# 分级A的接口
__funda_url = "http://www.jisilu.cn/data/sfnew/funda_list/?___t={ctime:d}"
# 分级B的接口
__fundb_url = "http://www.jisilu.cn/data/sfnew/fundb_list/?___t={ctime:d}"
# 母基接口
__fundm_url = "https://www.jisilu.cn/data/sfnew/fundm_list/?___t={ctime:d}"... |
shidenggui/easyquotation | easyquotation/jsl.py | Jsl.fundb | python | def fundb(self, fields=None, min_volume=0, min_discount=0, forever=False):
if fields is None:
fields = []
# 添加当前的ctime
self.__fundb_url = self.__fundb_url.format(ctime=int(time.time()))
# 请求数据
rep = requests.get(self.__fundb_url)
# 获取返回的json字符串
fundbjs... | 以字典形式返回分级B数据
:param fields:利率范围,形如['+3.0%', '6.0%']
:param min_volume:最小交易量,单位万元
:param min_discount:最小折价率, 单位%
:param forever: 是否选择永续品种,默认 False | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/jsl.py#L223-L266 | [
"def formatfundbjson(fundbjson):\n \"\"\"格式化集思录返回的json数据,以字典形式保存\"\"\"\n result = {}\n for row in fundbjson[\"rows\"]:\n cell = row[\"cell\"]\n fundb_id = cell[\"fundb_id\"]\n result[fundb_id] = cell\n return result\n"
] | class Jsl:
"""
抓取集思路的分级A数据
"""
# 分级A的接口
__funda_url = "http://www.jisilu.cn/data/sfnew/funda_list/?___t={ctime:d}"
# 分级B的接口
__fundb_url = "http://www.jisilu.cn/data/sfnew/fundb_list/?___t={ctime:d}"
# 母基接口
__fundm_url = "https://www.jisilu.cn/data/sfnew/fundm_list/?___t={ctime:d}"... |
shidenggui/easyquotation | easyquotation/jsl.py | Jsl.fundarb | python | def fundarb(
self,
jsl_username,
jsl_password,
avolume=100,
bvolume=100,
ptype="price",
):
session = requests.session()
headers = {
# pylint: disable=line-too-long
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; ... | 以字典形式返回分级A数据
:param jsl_username: 集思录用户名
:param jsl_password: 集思路登录密码
:param avolume: A成交额,单位百万
:param bvolume: B成交额,单位百万
:param ptype: 溢价计算方式,price=现价,buy=买一,sell=卖一 | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/jsl.py#L268-L323 | [
"def formatfundajson(fundajson):\n \"\"\"格式化集思录返回的json数据,以字典形式保存\"\"\"\n result = {}\n for row in fundajson[\"rows\"]:\n funda_id = row[\"id\"]\n cell = row[\"cell\"]\n result[funda_id] = cell\n return result\n"
] | class Jsl:
"""
抓取集思路的分级A数据
"""
# 分级A的接口
__funda_url = "http://www.jisilu.cn/data/sfnew/funda_list/?___t={ctime:d}"
# 分级B的接口
__fundb_url = "http://www.jisilu.cn/data/sfnew/fundb_list/?___t={ctime:d}"
# 母基接口
__fundm_url = "https://www.jisilu.cn/data/sfnew/fundm_list/?___t={ctime:d}"... |
shidenggui/easyquotation | easyquotation/jsl.py | Jsl.etfindex | python | def etfindex(
self, index_id="", min_volume=0, max_discount=None, min_discount=None
):
# 添加当前的ctime
self.__etf_index_url = self.__etf_index_url.format(
ctime=int(time.time())
)
# 请求数据
rep = requests.get(self.__etf_index_url)
# 获取返回的json字符串, 转化为字典
... | 以字典形式返回 指数ETF 数据
:param index_id: 获取指定的指数
:param min_volume: 最小成交量
:param min_discount: 最低溢价率, 适用于溢价套利, 格式 "-1.2%", "-1.2", -0.012 三种均可
:param max_discount: 最高溢价率, 适用于折价套利, 格式 "-1.2%", "-1.2", -0.012 三种均可
:return: {"fund_id":{}} | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/jsl.py#L325-L391 | [
"def formatetfindexjson(fundbjson):\n \"\"\"格式化集思录返回 指数ETF 的json数据,以字典形式保存\"\"\"\n result = {}\n for row in fundbjson[\"rows\"]:\n cell = row[\"cell\"]\n fundb_id = cell[\"fund_id\"]\n result[fundb_id] = cell\n return result\n",
"def percentage2float(per):\n \"\"\"\n 将字符串的百分... | class Jsl:
"""
抓取集思路的分级A数据
"""
# 分级A的接口
__funda_url = "http://www.jisilu.cn/data/sfnew/funda_list/?___t={ctime:d}"
# 分级B的接口
__fundb_url = "http://www.jisilu.cn/data/sfnew/fundb_list/?___t={ctime:d}"
# 母基接口
__fundm_url = "https://www.jisilu.cn/data/sfnew/fundm_list/?___t={ctime:d}"... |
shidenggui/easyquotation | easyquotation/jsl.py | Jsl.qdii | python | def qdii(self, min_volume=0):
# 添加当前的ctime
self.__qdii_url = self.__qdii_url.format(ctime=int(time.time()))
# 请求数据
rep = requests.get(self.__qdii_url)
# 获取返回的json字符串
fundjson = json.loads(rep.text)
# 格式化返回的json字符串
data = self.formatjisilujson(fundjson)
... | 以字典形式返回QDII数据
:param min_volume:最小交易量,单位万元 | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/jsl.py#L393-L415 | [
"def formatjisilujson(data):\n result = {}\n for row in data[\"rows\"]:\n cell = row[\"cell\"]\n id_ = row[\"id\"]\n result[id_] = cell\n return result\n"
] | class Jsl:
"""
抓取集思路的分级A数据
"""
# 分级A的接口
__funda_url = "http://www.jisilu.cn/data/sfnew/funda_list/?___t={ctime:d}"
# 分级B的接口
__fundb_url = "http://www.jisilu.cn/data/sfnew/fundb_list/?___t={ctime:d}"
# 母基接口
__fundm_url = "https://www.jisilu.cn/data/sfnew/fundm_list/?___t={ctime:d}"... |
shidenggui/easyquotation | easyquotation/jsl.py | Jsl.cb | python | def cb(self, min_volume=0):
# 添加当前的ctime
self.__cb_url = self.__cb_url.format(ctime=int(time.time()))
# 请求数据
rep = requests.get(self.__cb_url)
# 获取返回的json字符串
fundjson = json.loads(rep.text)
# 格式化返回的json字符串
data = self.formatjisilujson(fundjson)
# 过... | 以字典形式返回QDII数据
:param min_volume:最小交易量,单位万元 | train | https://github.com/shidenggui/easyquotation/blob/a75820db4f05f5386e1c1024d05b0bfc1de6cbda/easyquotation/jsl.py#L418-L439 | [
"def formatjisilujson(data):\n result = {}\n for row in data[\"rows\"]:\n cell = row[\"cell\"]\n id_ = row[\"id\"]\n result[id_] = cell\n return result\n"
] | class Jsl:
"""
抓取集思路的分级A数据
"""
# 分级A的接口
__funda_url = "http://www.jisilu.cn/data/sfnew/funda_list/?___t={ctime:d}"
# 分级B的接口
__fundb_url = "http://www.jisilu.cn/data/sfnew/fundb_list/?___t={ctime:d}"
# 母基接口
__fundm_url = "https://www.jisilu.cn/data/sfnew/fundm_list/?___t={ctime:d}"... |
seatgeek/fuzzywuzzy | fuzzywuzzy/process.py | extractWithoutOrder | python | def extractWithoutOrder(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0):
# Catch generators without lengths
def no_process(x):
return x
try:
if choices is None or len(choices) == 0:
raise StopIteration
except TypeError:
pass
#... | Select the best match in a list or dictionary of choices.
Find best matches in a list or dictionary of choices, return a
generator of tuples containing the match and its score. If a dictionary
is used, also returns the key for each match.
Arguments:
query: An object representing the thing we w... | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/fuzzywuzzy/process.py#L16-L119 | [
"def full_process(s, force_ascii=False):\n \"\"\"Process string by\n -- removing all but letters and numbers\n -- trim whitespace\n -- force to lower case\n if force_ascii == True, force convert to ascii\"\"\"\n\n if force_ascii:\n s = asciidammit(s)\n # Keep only Letters... | #!/usr/bin/env python
# encoding: utf-8
from . import fuzz
from . import utils
import heapq
import logging
from functools import partial
default_scorer = fuzz.WRatio
default_processor = utils.full_process
def extract(query, choices, processor=default_processor, scorer=default_scorer, limit=5):
"""Select the ... |
seatgeek/fuzzywuzzy | fuzzywuzzy/process.py | extract | python | def extract(query, choices, processor=default_processor, scorer=default_scorer, limit=5):
sl = extractWithoutOrder(query, choices, processor, scorer)
return heapq.nlargest(limit, sl, key=lambda i: i[1]) if limit is not None else \
sorted(sl, key=lambda i: i[1], reverse=True) | Select the best match in a list or dictionary of choices.
Find best matches in a list or dictionary of choices, return a
list of tuples containing the match and its score. If a dictionary
is used, also returns the key for each match.
Arguments:
query: An object representing the thing we want t... | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/fuzzywuzzy/process.py#L122-L169 | [
"def extractWithoutOrder(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0):\n \"\"\"Select the best match in a list or dictionary of choices.\n\n Find best matches in a list or dictionary of choices, return a\n generator of tuples containing the match and its score. If a d... | #!/usr/bin/env python
# encoding: utf-8
from . import fuzz
from . import utils
import heapq
import logging
from functools import partial
default_scorer = fuzz.WRatio
default_processor = utils.full_process
def extractWithoutOrder(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0):
... |
seatgeek/fuzzywuzzy | fuzzywuzzy/process.py | extractBests | python | def extractBests(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0, limit=5):
best_list = extractWithoutOrder(query, choices, processor, scorer, score_cutoff)
return heapq.nlargest(limit, best_list, key=lambda i: i[1]) if limit is not None else \
sorted(best_list, key=l... | Get a list of the best matches to a collection of choices.
Convenience function for getting the choices with best scores.
Args:
query: A string to match against
choices: A list or dictionary of choices, suitable for use with
extract().
processor: Optional function for trans... | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/fuzzywuzzy/process.py#L172-L194 | [
"def extractWithoutOrder(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0):\n \"\"\"Select the best match in a list or dictionary of choices.\n\n Find best matches in a list or dictionary of choices, return a\n generator of tuples containing the match and its score. If a d... | #!/usr/bin/env python
# encoding: utf-8
from . import fuzz
from . import utils
import heapq
import logging
from functools import partial
default_scorer = fuzz.WRatio
default_processor = utils.full_process
def extractWithoutOrder(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0):
... |
seatgeek/fuzzywuzzy | fuzzywuzzy/process.py | extractOne | python | def extractOne(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0):
best_list = extractWithoutOrder(query, choices, processor, scorer, score_cutoff)
try:
return max(best_list, key=lambda i: i[1])
except ValueError:
return None | Find the single best match above a score in a list of choices.
This is a convenience method which returns the single best choice.
See extract() for the full arguments list.
Args:
query: A string to match against
choices: A list or dictionary of choices, suitable for use with
ex... | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/fuzzywuzzy/process.py#L197-L222 | [
"def extractWithoutOrder(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0):\n \"\"\"Select the best match in a list or dictionary of choices.\n\n Find best matches in a list or dictionary of choices, return a\n generator of tuples containing the match and its score. If a d... | #!/usr/bin/env python
# encoding: utf-8
from . import fuzz
from . import utils
import heapq
import logging
from functools import partial
default_scorer = fuzz.WRatio
default_processor = utils.full_process
def extractWithoutOrder(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0):
... |
seatgeek/fuzzywuzzy | fuzzywuzzy/process.py | dedupe | python | def dedupe(contains_dupes, threshold=70, scorer=fuzz.token_set_ratio):
extractor = []
# iterate over items in *contains_dupes*
for item in contains_dupes:
# return all duplicate matches found
matches = extract(item, contains_dupes, limit=None, scorer=scorer)
# filter matches based ... | This convenience function takes a list of strings containing duplicates and uses fuzzy matching to identify
and remove duplicates. Specifically, it uses the process.extract to identify duplicates that
score greater than a user defined threshold. Then, it looks for the longest item in the duplicate list
sinc... | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/fuzzywuzzy/process.py#L225-L285 | [
"def extract(query, choices, processor=default_processor, scorer=default_scorer, limit=5):\n \"\"\"Select the best match in a list or dictionary of choices.\n\n Find best matches in a list or dictionary of choices, return a\n list of tuples containing the match and its score. If a dictionary\n is used, ... | #!/usr/bin/env python
# encoding: utf-8
from . import fuzz
from . import utils
import heapq
import logging
from functools import partial
default_scorer = fuzz.WRatio
default_processor = utils.full_process
def extractWithoutOrder(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0):
... |
seatgeek/fuzzywuzzy | fuzzywuzzy/utils.py | make_type_consistent | python | def make_type_consistent(s1, s2):
if isinstance(s1, str) and isinstance(s2, str):
return s1, s2
elif isinstance(s1, unicode) and isinstance(s2, unicode):
return s1, s2
else:
return unicode(s1), unicode(s2) | If both objects aren't either both string or unicode instances force them to unicode | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/fuzzywuzzy/utils.py#L73-L82 | null | from __future__ import unicode_literals
import sys
import functools
from fuzzywuzzy.string_processing import StringProcessor
PY3 = sys.version_info[0] == 3
def validate_string(s):
"""
Check input has length and that length > 0
:param s:
:return: True if len(s) > 0 else False
"""
try:
... |
seatgeek/fuzzywuzzy | fuzzywuzzy/utils.py | full_process | python | def full_process(s, force_ascii=False):
if force_ascii:
s = asciidammit(s)
# Keep only Letters and Numbers (see Unicode docs).
string_out = StringProcessor.replace_non_letters_non_numbers_with_whitespace(s)
# Force into lowercase.
string_out = StringProcessor.to_lower_case(string_out)
#... | Process string by
-- removing all but letters and numbers
-- trim whitespace
-- force to lower case
if force_ascii == True, force convert to ascii | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/fuzzywuzzy/utils.py#L85-L100 | [
"def asciidammit(s):\n if type(s) is str:\n return asciionly(s)\n elif type(s) is unicode:\n return asciionly(s.encode('ascii', 'ignore'))\n else:\n return asciidammit(unicode(s))\n",
"def replace_non_letters_non_numbers_with_whitespace(cls, a_string):\n \"\"\"\n This function ... | from __future__ import unicode_literals
import sys
import functools
from fuzzywuzzy.string_processing import StringProcessor
PY3 = sys.version_info[0] == 3
def validate_string(s):
"""
Check input has length and that length > 0
:param s:
:return: True if len(s) > 0 else False
"""
try:
... |
seatgeek/fuzzywuzzy | fuzzywuzzy/fuzz.py | partial_ratio | python | def partial_ratio(s1, s2):
"
s1, s2 = utils.make_type_consistent(s1, s2)
if len(s1) <= len(s2):
shorter = s1
longer = s2
else:
shorter = s2
longer = s1
m = SequenceMatcher(None, shorter, longer)
blocks = m.get_matching_blocks()
# each block represents a seq... | Return the ratio of the most similar substring
as a number between 0 and 100. | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/fuzzywuzzy/fuzz.py#L34-L68 | [
"def make_type_consistent(s1, s2):\n \"\"\"If both objects aren't either both string or unicode instances force them to unicode\"\"\"\n if isinstance(s1, str) and isinstance(s2, str):\n return s1, s2\n\n elif isinstance(s1, unicode) and isinstance(s2, unicode):\n return s1, s2\n\n else:\n ... | #!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
import platform
import warnings
try:
from .StringMatcher import StringMatcher as SequenceMatcher
except ImportError:
if platform.python_implementation() != "PyPy":
warnings.warn('Using slow pure-python SequenceMatcher. Inst... |
seatgeek/fuzzywuzzy | fuzzywuzzy/fuzz.py | _process_and_sort | python | def _process_and_sort(s, force_ascii, full_process=True):
# pull tokens
ts = utils.full_process(s, force_ascii=force_ascii) if full_process else s
tokens = ts.split()
# sort tokens and join
sorted_string = u" ".join(sorted(tokens))
return sorted_string.strip() | Return a cleaned string with token sorted. | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/fuzzywuzzy/fuzz.py#L75-L83 | null | #!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
import platform
import warnings
try:
from .StringMatcher import StringMatcher as SequenceMatcher
except ImportError:
if platform.python_implementation() != "PyPy":
warnings.warn('Using slow pure-python SequenceMatcher. Inst... |
seatgeek/fuzzywuzzy | fuzzywuzzy/fuzz.py | token_sort_ratio | python | def token_sort_ratio(s1, s2, force_ascii=True, full_process=True):
return _token_sort(s1, s2, partial=False, force_ascii=force_ascii, full_process=full_process) | Return a measure of the sequences' similarity between 0 and 100
but sorting the token before comparing. | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/fuzzywuzzy/fuzz.py#L101-L105 | null | #!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
import platform
import warnings
try:
from .StringMatcher import StringMatcher as SequenceMatcher
except ImportError:
if platform.python_implementation() != "PyPy":
warnings.warn('Using slow pure-python SequenceMatcher. Inst... |
seatgeek/fuzzywuzzy | fuzzywuzzy/fuzz.py | partial_token_sort_ratio | python | def partial_token_sort_ratio(s1, s2, force_ascii=True, full_process=True):
return _token_sort(s1, s2, partial=True, force_ascii=force_ascii, full_process=full_process) | Return the ratio of the most similar substring as a number between
0 and 100 but sorting the token before comparing. | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/fuzzywuzzy/fuzz.py#L108-L112 | null | #!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
import platform
import warnings
try:
from .StringMatcher import StringMatcher as SequenceMatcher
except ImportError:
if platform.python_implementation() != "PyPy":
warnings.warn('Using slow pure-python SequenceMatcher. Inst... |
seatgeek/fuzzywuzzy | fuzzywuzzy/fuzz.py | _token_set | python | def _token_set(s1, s2, partial=True, force_ascii=True, full_process=True):
if not full_process and s1 == s2:
return 100
p1 = utils.full_process(s1, force_ascii=force_ascii) if full_process else s1
p2 = utils.full_process(s2, force_ascii=force_ascii) if full_process else s2
if not utils.valida... | Find all alphanumeric tokens in each string...
- treat them as a set
- construct two strings of the form:
<sorted_intersection><sorted_remainder>
- take ratios of those two strings
- controls for unordered partial matches | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/fuzzywuzzy/fuzz.py#L116-L165 | null | #!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
import platform
import warnings
try:
from .StringMatcher import StringMatcher as SequenceMatcher
except ImportError:
if platform.python_implementation() != "PyPy":
warnings.warn('Using slow pure-python SequenceMatcher. Inst... |
seatgeek/fuzzywuzzy | fuzzywuzzy/fuzz.py | QRatio | python | def QRatio(s1, s2, force_ascii=True, full_process=True):
if full_process:
p1 = utils.full_process(s1, force_ascii=force_ascii)
p2 = utils.full_process(s2, force_ascii=force_ascii)
else:
p1 = s1
p2 = s2
if not utils.validate_string(p1):
return 0
if not utils.vali... | Quick ratio comparison between two strings.
Runs full_process from utils on both strings
Short circuits if either of the strings is empty after processing.
:param s1:
:param s2:
:param force_ascii: Allow only ASCII characters (Default: True)
:full_process: Process inputs, used here to avoid do... | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/fuzzywuzzy/fuzz.py#L181-L207 | [
"def full_process(s, force_ascii=False):\n \"\"\"Process string by\n -- removing all but letters and numbers\n -- trim whitespace\n -- force to lower case\n if force_ascii == True, force convert to ascii\"\"\"\n\n if force_ascii:\n s = asciidammit(s)\n # Keep only Letters... | #!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
import platform
import warnings
try:
from .StringMatcher import StringMatcher as SequenceMatcher
except ImportError:
if platform.python_implementation() != "PyPy":
warnings.warn('Using slow pure-python SequenceMatcher. Inst... |
seatgeek/fuzzywuzzy | fuzzywuzzy/fuzz.py | UQRatio | python | def UQRatio(s1, s2, full_process=True):
return QRatio(s1, s2, force_ascii=False, full_process=full_process) | Unicode quick ratio
Calls QRatio with force_ascii set to False
:param s1:
:param s2:
:return: similarity ratio | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/fuzzywuzzy/fuzz.py#L210-L220 | [
"def QRatio(s1, s2, force_ascii=True, full_process=True):\n \"\"\"\n Quick ratio comparison between two strings.\n\n Runs full_process from utils on both strings\n Short circuits if either of the strings is empty after processing.\n\n :param s1:\n :param s2:\n :param force_ascii: Allow only ASC... | #!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
import platform
import warnings
try:
from .StringMatcher import StringMatcher as SequenceMatcher
except ImportError:
if platform.python_implementation() != "PyPy":
warnings.warn('Using slow pure-python SequenceMatcher. Inst... |
seatgeek/fuzzywuzzy | fuzzywuzzy/fuzz.py | WRatio | python | def WRatio(s1, s2, force_ascii=True, full_process=True):
if full_process:
p1 = utils.full_process(s1, force_ascii=force_ascii)
p2 = utils.full_process(s2, force_ascii=force_ascii)
else:
p1 = s1
p2 = s2
if not utils.validate_string(p1):
return 0
if not utils.vali... | Return a measure of the sequences' similarity between 0 and 100, using different algorithms.
**Steps in the order they occur**
#. Run full_process from utils on both strings
#. Short circuit if this makes either string empty
#. Take the ratio of the two processed strings (fuzz.ratio)
#. Run checks... | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/fuzzywuzzy/fuzz.py#L224-L299 | [
"def full_process(s, force_ascii=False):\n \"\"\"Process string by\n -- removing all but letters and numbers\n -- trim whitespace\n -- force to lower case\n if force_ascii == True, force convert to ascii\"\"\"\n\n if force_ascii:\n s = asciidammit(s)\n # Keep only Letters... | #!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
import platform
import warnings
try:
from .StringMatcher import StringMatcher as SequenceMatcher
except ImportError:
if platform.python_implementation() != "PyPy":
warnings.warn('Using slow pure-python SequenceMatcher. Inst... |
seatgeek/fuzzywuzzy | fuzzywuzzy/fuzz.py | UWRatio | python | def UWRatio(s1, s2, full_process=True):
return WRatio(s1, s2, force_ascii=False, full_process=full_process) | Return a measure of the sequences' similarity between 0 and 100,
using different algorithms. Same as WRatio but preserving unicode. | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/fuzzywuzzy/fuzz.py#L302-L306 | [
"def WRatio(s1, s2, force_ascii=True, full_process=True):\n \"\"\"\n Return a measure of the sequences' similarity between 0 and 100, using different algorithms.\n\n **Steps in the order they occur**\n\n #. Run full_process from utils on both strings\n #. Short circuit if this makes either string emp... | #!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
import platform
import warnings
try:
from .StringMatcher import StringMatcher as SequenceMatcher
except ImportError:
if platform.python_implementation() != "PyPy":
warnings.warn('Using slow pure-python SequenceMatcher. Inst... |
seatgeek/fuzzywuzzy | benchmarks.py | print_result_from_timeit | python | def print_result_from_timeit(stmt='pass', setup='pass', number=1000000):
units = ["s", "ms", "us", "ns"]
duration = timeit(stmt, setup, number=int(number))
avg_duration = duration / float(number)
thousands = int(math.floor(math.log(avg_duration, 1000)))
print("Total time: %fs. Average run: %.3f%s."... | Clean function to know how much time took the execution of one statement | train | https://github.com/seatgeek/fuzzywuzzy/blob/778162c5a73256745eb6ae22f925bc2dbcf7c894/benchmarks.py#L47-L57 | null | # -*- coding: utf8 -*-
from timeit import timeit
import math
import csv
iterations = 100000
reader = csv.DictReader(open('data/titledata.csv'), delimiter='|')
titles = [i['custom_title'] for i in reader]
title_blob = '\n'.join(titles)
cirque_strings = [
"cirque du soleil - zarkana - las vegas",
"cirque du... |
ipazc/mtcnn | mtcnn/mtcnn.py | MTCNN.__scale_image | python | def __scale_image(image, scale: float):
height, width, _ = image.shape
width_scaled = int(np.ceil(width * scale))
height_scaled = int(np.ceil(height * scale))
im_data = cv2.resize(image, (width_scaled, height_scaled), interpolation=cv2.INTER_AREA)
# Normalize the image's pixel... | Scales the image to a given scale.
:param image:
:param scale:
:return: | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/mtcnn.py#L230-L247 | null | class MTCNN(object):
"""
Allows to perform MTCNN Detection ->
a) Detection of faces (with the confidence probability)
b) Detection of keypoints (left eye, right eye, nose, mouth_left, mouth_right)
"""
def __init__(self, weights_file: str=None, min_face_size: int=20, steps_threshold: lis... |
ipazc/mtcnn | mtcnn/mtcnn.py | MTCNN.__nms | python | def __nms(boxes, threshold, method):
if boxes.size == 0:
return np.empty((0, 3))
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
s = boxes[:, 4]
area = (x2 - x1 + 1) * (y2 - y1 + 1)
sorted_s = np.argsort(s)
pick =... | Non Maximum Suppression.
:param boxes: np array with bounding boxes.
:param threshold:
:param method: NMS method to apply. Available values ('Min', 'Union')
:return: | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/mtcnn.py#L285-L333 | null | class MTCNN(object):
"""
Allows to perform MTCNN Detection ->
a) Detection of faces (with the confidence probability)
b) Detection of keypoints (left eye, right eye, nose, mouth_left, mouth_right)
"""
def __init__(self, weights_file: str=None, min_face_size: int=20, steps_threshold: lis... |
ipazc/mtcnn | mtcnn/mtcnn.py | MTCNN.detect_faces | python | def detect_faces(self, img) -> list:
if img is None or not hasattr(img, "shape"):
raise InvalidImage("Image not valid.")
height, width, _ = img.shape
stage_status = StageStatus(width=width, height=height)
m = 12 / self.__min_face_size
min_layer = np.amin([height, wi... | Detects bounding boxes from the specified image.
:param img: image to process
:return: list containing all the bounding boxes detected with their keypoints. | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/mtcnn.py#L396-L440 | [
"def __compute_scale_pyramid(self, m, min_layer):\n scales = []\n factor_count = 0\n\n while min_layer >= 12:\n scales += [m * np.power(self.__scale_factor, factor_count)]\n min_layer = min_layer * self.__scale_factor\n factor_count += 1\n\n return scales\n"
] | class MTCNN(object):
"""
Allows to perform MTCNN Detection ->
a) Detection of faces (with the confidence probability)
b) Detection of keypoints (left eye, right eye, nose, mouth_left, mouth_right)
"""
def __init__(self, weights_file: str=None, min_face_size: int=20, steps_threshold: lis... |
ipazc/mtcnn | mtcnn/mtcnn.py | MTCNN.__stage1 | python | def __stage1(self, image, scales: list, stage_status: StageStatus):
total_boxes = np.empty((0, 9))
status = stage_status
for scale in scales:
scaled_image = self.__scale_image(image, scale)
img_x = np.expand_dims(scaled_image, 0)
img_y = np.transpose(img_x, ... | First stage of the MTCNN.
:param image:
:param scales:
:param stage_status:
:return: | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/mtcnn.py#L442-L494 | null | class MTCNN(object):
"""
Allows to perform MTCNN Detection ->
a) Detection of faces (with the confidence probability)
b) Detection of keypoints (left eye, right eye, nose, mouth_left, mouth_right)
"""
def __init__(self, weights_file: str=None, min_face_size: int=20, steps_threshold: lis... |
ipazc/mtcnn | mtcnn/mtcnn.py | MTCNN.__stage2 | python | def __stage2(self, img, total_boxes, stage_status:StageStatus):
num_boxes = total_boxes.shape[0]
if num_boxes == 0:
return total_boxes, stage_status
# second stage
tempimg = np.zeros(shape=(24, 24, 3, num_boxes))
for k in range(0, num_boxes):
tmp = np.z... | Second stage of the MTCNN.
:param img:
:param total_boxes:
:param stage_status:
:return: | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/mtcnn.py#L496-L547 | null | class MTCNN(object):
"""
Allows to perform MTCNN Detection ->
a) Detection of faces (with the confidence probability)
b) Detection of keypoints (left eye, right eye, nose, mouth_left, mouth_right)
"""
def __init__(self, weights_file: str=None, min_face_size: int=20, steps_threshold: lis... |
ipazc/mtcnn | mtcnn/mtcnn.py | MTCNN.__stage3 | python | def __stage3(self, img, total_boxes, stage_status: StageStatus):
num_boxes = total_boxes.shape[0]
if num_boxes == 0:
return total_boxes, np.empty(shape=(0,))
total_boxes = np.fix(total_boxes).astype(np.int32)
status = StageStatus(self.__pad(total_boxes.copy(), stage_status.... | Third stage of the MTCNN.
:param img:
:param total_boxes:
:param stage_status:
:return: | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/mtcnn.py#L549-L613 | null | class MTCNN(object):
"""
Allows to perform MTCNN Detection ->
a) Detection of faces (with the confidence probability)
b) Detection of keypoints (left eye, right eye, nose, mouth_left, mouth_right)
"""
def __init__(self, weights_file: str=None, min_face_size: int=20, steps_threshold: lis... |
ipazc/mtcnn | mtcnn/layer_factory.py | LayerFactory.__make_var | python | def __make_var(self, name: str, shape: list):
return tf.get_variable(name, shape, trainable=self.__network.is_trainable()) | Creates a tensorflow variable with the given name and shape.
:param name: name to set for the variable.
:param shape: list defining the shape of the variable.
:return: created TF variable. | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/layer_factory.py#L72-L79 | null | class LayerFactory(object):
"""
Allows to create stack layers for a given network.
"""
AVAILABLE_PADDINGS = ('SAME', 'VALID')
def __init__(self, network):
self.__network = network
@staticmethod
def __validate_padding(padding):
if padding not in LayerFactory.AVAILABLE_PADDI... |
ipazc/mtcnn | mtcnn/layer_factory.py | LayerFactory.new_feed | python | def new_feed(self, name: str, layer_shape: tuple):
feed_data = tf.placeholder(tf.float32, layer_shape, 'input')
self.__network.add_layer(name, layer_output=feed_data) | Creates a feed layer. This is usually the first layer in the network.
:param name: name of the layer
:return: | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/layer_factory.py#L81-L89 | null | class LayerFactory(object):
"""
Allows to create stack layers for a given network.
"""
AVAILABLE_PADDINGS = ('SAME', 'VALID')
def __init__(self, network):
self.__network = network
@staticmethod
def __validate_padding(padding):
if padding not in LayerFactory.AVAILABLE_PADDI... |
ipazc/mtcnn | mtcnn/layer_factory.py | LayerFactory.new_conv | python | def new_conv(self, name: str, kernel_size: tuple, channels_output: int,
stride_size: tuple, padding: str='SAME',
group: int=1, biased: bool=True, relu: bool=True, input_layer_name: str=None):
# Verify that the padding is acceptable
self.__validate_padding(padding)
... | Creates a convolution layer for the network.
:param name: name for the layer
:param kernel_size: tuple containing the size of the kernel (Width, Height)
:param channels_output: ¿? Perhaps number of channels in the output? it is used as the bias size.
:param stride_size: tuple containing ... | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/layer_factory.py#L91-L138 | [
"def __validate_padding(padding):\n if padding not in LayerFactory.AVAILABLE_PADDINGS:\n raise Exception(\"Padding {} not valid\".format(padding))\n",
"def __validate_grouping(channels_input: int, channels_output: int, group: int):\n if channels_input % group != 0:\n raise Exception(\"The numb... | class LayerFactory(object):
"""
Allows to create stack layers for a given network.
"""
AVAILABLE_PADDINGS = ('SAME', 'VALID')
def __init__(self, network):
self.__network = network
@staticmethod
def __validate_padding(padding):
if padding not in LayerFactory.AVAILABLE_PADDI... |
ipazc/mtcnn | mtcnn/layer_factory.py | LayerFactory.new_prelu | python | def new_prelu(self, name: str, input_layer_name: str=None):
input_layer = self.__network.get_layer(input_layer_name)
with tf.variable_scope(name):
channels_input = int(input_layer.get_shape()[-1])
alpha = self.__make_var('alpha', shape=[channels_input])
output = tf.n... | Creates a new prelu layer with the given name and input.
:param name: name for this layer.
:param input_layer_name: name of the layer that serves as input for this one. | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/layer_factory.py#L140-L153 | [
"def __make_var(self, name: str, shape: list):\n \"\"\"\n Creates a tensorflow variable with the given name and shape.\n :param name: name to set for the variable.\n :param shape: list defining the shape of the variable.\n :return: created TF variable.\n \"\"\"\n return tf.get_variable(name, sh... | class LayerFactory(object):
"""
Allows to create stack layers for a given network.
"""
AVAILABLE_PADDINGS = ('SAME', 'VALID')
def __init__(self, network):
self.__network = network
@staticmethod
def __validate_padding(padding):
if padding not in LayerFactory.AVAILABLE_PADDI... |
ipazc/mtcnn | mtcnn/layer_factory.py | LayerFactory.new_max_pool | python | def new_max_pool(self, name:str, kernel_size: tuple, stride_size: tuple, padding='SAME',
input_layer_name: str=None):
self.__validate_padding(padding)
input_layer = self.__network.get_layer(input_layer_name)
output = tf.nn.max_pool(input_layer,
... | Creates a new max pooling layer.
:param name: name for the layer.
:param kernel_size: tuple containing the size of the kernel (Width, Height)
:param stride_size: tuple containing the size of the stride (Width, Height)
:param padding: Type of padding. Available values are: ('SAME', 'VALID... | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/layer_factory.py#L155-L177 | [
"def __validate_padding(padding):\n if padding not in LayerFactory.AVAILABLE_PADDINGS:\n raise Exception(\"Padding {} not valid\".format(padding))\n"
] | class LayerFactory(object):
"""
Allows to create stack layers for a given network.
"""
AVAILABLE_PADDINGS = ('SAME', 'VALID')
def __init__(self, network):
self.__network = network
@staticmethod
def __validate_padding(padding):
if padding not in LayerFactory.AVAILABLE_PADDI... |
ipazc/mtcnn | mtcnn/layer_factory.py | LayerFactory.new_fully_connected | python | def new_fully_connected(self, name: str, output_count: int, relu=True, input_layer_name: str=None):
with tf.variable_scope(name):
input_layer = self.__network.get_layer(input_layer_name)
vectorized_input, dimension = self.vectorize_input(input_layer)
weights = self.__make_v... | Creates a new fully connected layer.
:param name: name for the layer.
:param output_count: number of outputs of the fully connected layer.
:param relu: boolean flag to set if ReLu should be applied at the end of this layer.
:param input_layer_name: name of the input layer for this layer... | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/layer_factory.py#L179-L200 | [
"def vectorize_input(input_layer):\n input_shape = input_layer.get_shape()\n\n if input_shape.ndims == 4:\n # Spatial input, must be vectorized.\n dim = 1\n for x in input_shape[1:].as_list():\n dim *= int(x)\n\n #dim = operator.mul(*(input_shape[1:].as_list()))\n ... | class LayerFactory(object):
"""
Allows to create stack layers for a given network.
"""
AVAILABLE_PADDINGS = ('SAME', 'VALID')
def __init__(self, network):
self.__network = network
@staticmethod
def __validate_padding(padding):
if padding not in LayerFactory.AVAILABLE_PADDI... |
ipazc/mtcnn | mtcnn/layer_factory.py | LayerFactory.new_softmax | python | def new_softmax(self, name, axis, input_layer_name: str=None):
input_layer = self.__network.get_layer(input_layer_name)
if LooseVersion(tf.__version__) < LooseVersion("1.5.0"):
max_axis = tf.reduce_max(input_layer, axis, keep_dims=True)
target_exp = tf.exp(input_layer - max_axis... | Creates a new softmax layer
:param name: name to set for the layer
:param axis:
:param input_layer_name: name of the input layer for this layer. If None, it will take the last added layer of
the network. | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/layer_factory.py#L202-L223 | null | class LayerFactory(object):
"""
Allows to create stack layers for a given network.
"""
AVAILABLE_PADDINGS = ('SAME', 'VALID')
def __init__(self, network):
self.__network = network
@staticmethod
def __validate_padding(padding):
if padding not in LayerFactory.AVAILABLE_PADDI... |
ipazc/mtcnn | mtcnn/network.py | Network.add_layer | python | def add_layer(self, name: str, layer_output):
self.__layers[name] = layer_output
self.__last_layer_name = name | Adds a layer to the network.
:param name: name of the layer to add
:param layer_output: output layer. | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/network.py#L53-L60 | null | class Network(object):
def __init__(self, session, trainable: bool=True):
"""
Initializes the network.
:param trainable: flag to determine if this network should be trainable or not.
"""
self._session = session
self.__trainable = trainable
self.__layers = {}
... |
ipazc/mtcnn | mtcnn/network.py | Network.get_layer | python | def get_layer(self, name: str=None):
if name is None:
name = self.__last_layer_name
return self.__layers[name] | Retrieves the layer by its name.
:param name: name of the layer to retrieve. If name is None, it will retrieve the last added layer to the
network.
:return: layer output | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/network.py#L62-L72 | null | class Network(object):
def __init__(self, session, trainable: bool=True):
"""
Initializes the network.
:param trainable: flag to determine if this network should be trainable or not.
"""
self._session = session
self.__trainable = trainable
self.__layers = {}
... |
ipazc/mtcnn | mtcnn/network.py | Network.set_weights | python | def set_weights(self, weights_values: dict, ignore_missing=False):
network_name = self.__class__.__name__.lower()
with tf.variable_scope(network_name):
for layer_name in weights_values:
with tf.variable_scope(layer_name, reuse=True):
for param_name, data ... | Sets the weights values of the network.
:param weights_values: dictionary with weights for each layer | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/network.py#L80-L97 | null | class Network(object):
def __init__(self, session, trainable: bool=True):
"""
Initializes the network.
:param trainable: flag to determine if this network should be trainable or not.
"""
self._session = session
self.__trainable = trainable
self.__layers = {}
... |
ipazc/mtcnn | mtcnn/network.py | Network.feed | python | def feed(self, image):
network_name = self.__class__.__name__.lower()
with tf.variable_scope(network_name):
return self._feed(image) | Feeds the network with an image
:param image: image (perhaps loaded with CV2)
:return: network result | train | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/network.py#L99-L108 | [
"def _feed(self, image):\n raise NotImplementedError(\"Method not implemented.\")"
] | class Network(object):
def __init__(self, session, trainable: bool=True):
"""
Initializes the network.
:param trainable: flag to determine if this network should be trainable or not.
"""
self._session = session
self.__trainable = trainable
self.__layers = {}
... |
h2oai/datatable | datatable/xls.py | _parse_row | python | def _parse_row(rowvalues, rowtypes):
n = len(rowvalues)
assert n == len(rowtypes)
if not n:
return []
range_start = None
ranges = []
for i in range(n):
ctype = rowtypes[i]
cval = rowvalues[i]
# Check whether the cell is empty or not. If it is empty, and there is
... | Scan a single row from an Excel file, and return the list of ranges
corresponding to each consecutive span of non-empty cells in this row.
If all cells are empty, return an empty list. Each "range" in the list
is a tuple of the form `(startcol, endcol)`.
For example, if the row is the following:
... | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/datatable/xls.py#L106-L147 | null | #!/usr/bin/env python3
#-------------------------------------------------------------------------------
# Copyright 2018 H2O.ai
#
# 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://... |
h2oai/datatable | datatable/xls.py | _combine_ranges | python | def _combine_ranges(ranges):
ranges2d = []
for irow, rowranges in enumerate(ranges):
ja = 0
jb = 0
while jb < len(rowranges):
bcol0, bcol1 = rowranges[jb]
if ja < len(ranges2d):
_, arow1, acol0, acol1 = ranges2d[ja]
if arow1 < irow:... | This function takes a list of row-ranges (as returned by `_parse_row`)
ordered by rows, and produces a list of distinct rectangular ranges
within this grid.
Within this function we define a 2d-range as a rectangular set of cells
such that:
- there are no empty rows / columns within this rectangle... | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/datatable/xls.py#L150-L197 | [
"def _collapse_ranges(ranges, ja):\n \"\"\"\n Within the `ranges` list find those 2d-ranges that overlap with `ranges[ja]`\n and merge them into `ranges[ja]`. Finally, return the new index of the\n ja-th range within the `ranges` list.\n \"\"\"\n arow0, _, acol0, acol1 = ranges[ja]\n jb = 0\n ... | #!/usr/bin/env python3
#-------------------------------------------------------------------------------
# Copyright 2018 H2O.ai
#
# 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://... |
h2oai/datatable | datatable/xls.py | _collapse_ranges | python | def _collapse_ranges(ranges, ja):
arow0, _, acol0, acol1 = ranges[ja]
jb = 0
while jb < len(ranges):
if jb == ja:
jb += 1
continue
brow0, brow1, bcol0, bcol1 = ranges[jb]
if bcol0 <= acol1 and brow1 >= arow0 and \
not(bcol0 == acol1 and brow1 =... | Within the `ranges` list find those 2d-ranges that overlap with `ranges[ja]`
and merge them into `ranges[ja]`. Finally, return the new index of the
ja-th range within the `ranges` list. | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/datatable/xls.py#L200-L222 | null | #!/usr/bin/env python3
#-------------------------------------------------------------------------------
# Copyright 2018 H2O.ai
#
# 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://... |
h2oai/datatable | ci/setup_utils.py | find_linked_dynamic_libraries | python | def find_linked_dynamic_libraries():
with TaskContext("Find the required dynamic libraries") as log:
llvm = get_llvm()
libs = required_link_libraries()
resolved = []
for libname in libs:
if llvm:
fullpath = os.path.join(llvm, "lib", libname)
... | This function attempts to locate the required link libraries, and returns
them as a list of absolute paths. | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/ci/setup_utils.py#L589-L626 | [
"def get_llvm(with_version=False):\n global g_llvmdir, g_llvmver\n if g_llvmdir is Ellipsis:\n with TaskContext(\"Find an LLVM installation\") as log:\n g_llvmdir = None\n g_llvmver = None\n for LLVMX in [\"LLVM\", \"LLVM7\", \"LLVM6\", \"LLVM5\", \"LLVM4\"]:\n ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Copyright 2018 H2O.ai
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the... |
h2oai/datatable | datatable/utils/terminal.py | Terminal.wait_for_keypresses | python | def wait_for_keypresses(self, refresh_rate=1):
if not self._enable_keyboard:
return
with self._blessed_term.cbreak():
while True:
yield self._blessed_term.inkey(timeout=refresh_rate) | Listen to user's keystrokes and return them to caller one at a time.
The produced values are instances of blessed.keyboard.Keystroke class.
If the user did not press anything with the last `refresh_rate` seconds
the generator will yield `None`, allowing the caller to perform any
updates... | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/datatable/utils/terminal.py#L144-L159 | null | class Terminal:
def __init__(self):
self.jupyter = False
self.ipython = False
if sys.__stdin__ and sys.__stdout__:
import blessed
import _locale
# Save current locale settings
try:
_lls = []
for i in range(100)... |
h2oai/datatable | datatable/utils/misc.py | normalize_slice | python | def normalize_slice(e, n):
if n == 0:
return (0, 0, 1)
step = e.step
if step is None:
step = 1
if step == 0:
start = e.start
count = e.stop
if isinstance(start, int) and isinstance(count, int) and count >= 0:
if start < 0:
start += n
... | Return the slice tuple normalized for an ``n``-element object.
:param e: a slice object representing a selector
:param n: number of elements in a sequence to which ``e`` is applied
:returns: tuple ``(start, count, step)`` derived from ``e``. | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/datatable/utils/misc.py#L65-L127 | null | #!/usr/bin/env python3
# © H2O.ai 2018; -*- encoding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#--------------------------------------------------... |
h2oai/datatable | datatable/utils/misc.py | normalize_range | python | def normalize_range(e, n):
if e.step > 0:
count = max(0, (e.stop - e.start - 1) // e.step + 1)
else:
count = max(0, (e.start - e.stop - 1) // -e.step + 1)
if count == 0:
return (0, 0, e.step)
start = e.start
finish = e.start + (count - 1) * e.step
if start >= 0:
... | Return the range tuple normalized for an ``n``-element object.
The semantics of a range is slightly different than that of a slice.
In particular, a range is similar to a list in meaning (and on Py2 it was
eagerly expanded into a list). Thus we do not allow the range to generate
indices that would be ... | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/datatable/utils/misc.py#L130-L166 | null | #!/usr/bin/env python3
# © H2O.ai 2018; -*- encoding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#--------------------------------------------------... |
h2oai/datatable | datatable/utils/misc.py | load_module | python | def load_module(module):
try:
m = importlib.import_module(module)
return m
except ModuleNotFoundError: # pragma: no cover
raise TImportError("Module `%s` is not installed. It is required for "
"running this function." % module) | Import and return the requested module. | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/datatable/utils/misc.py#L170-L179 | null | #!/usr/bin/env python3
# © H2O.ai 2018; -*- encoding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#--------------------------------------------------... |
h2oai/datatable | datatable/utils/misc.py | humanize_bytes | python | def humanize_bytes(size):
if size == 0: return "0"
if size is None: return ""
assert size >= 0, "`size` cannot be negative, got %d" % size
suffixes = "TGMK"
maxl = len(suffixes)
for i in range(maxl + 1):
shift = (maxl - i) * 10
if size >> shift == 0: continue
ndigits = 0
... | Convert given number of bytes into a human readable representation, i.e. add
prefix such as KB, MB, GB, etc. The `size` argument must be a non-negative
integer.
:param size: integer representing byte size of something
:return: string representation of the size, in human-readable form | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/datatable/utils/misc.py#L182-L208 | null | #!/usr/bin/env python3
# © H2O.ai 2018; -*- encoding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#--------------------------------------------------... |
h2oai/datatable | datatable/widget.py | DataFrameWidget._fetch_data | python | def _fetch_data(self):
self._view_col0 = clamp(self._view_col0, 0, self._max_col0)
self._view_row0 = clamp(self._view_row0, 0, self._max_row0)
self._view_ncols = clamp(self._view_ncols, 0,
self._conn.frame_ncols - self._view_col0)
self._view_nrows = clamp... | Retrieve frame data within the current view window.
This method will adjust the view window if it goes out-of-bounds. | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/datatable/widget.py#L323-L339 | null | class DataFrameWidget(object):
"""
Widget for displaying frame's data interactively.
This widget will show the data in form of the table, and then (if
necessary) enter into the "interactive" mode, responding to user's input in
order to move the viewport.
Along the Y dimension, we will display ... |
h2oai/datatable | ci/make_fast.py | get_files | python | def get_files():
sources = []
headers = ["datatable/include/datatable.h"]
assert os.path.isfile(headers[0])
for dirpath, _, filenames in os.walk("c"):
for f in filenames:
fullname = os.path.join(dirpath, f)
if f.endswith(".h") or f.endswith(".inc"):
header... | Return the list of all source/header files in `c/` directory.
The files will have pathnames relative to the current folder, for example
"c/csv/reader_utils.cc". | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/ci/make_fast.py#L15-L32 | null | #!/usr/bin/env python3
# © H2O.ai 2018; -*- encoding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#--------------------------------------------------... |
h2oai/datatable | ci/make_fast.py | find_includes | python | def find_includes(filename):
includes = []
with open(filename, "r", encoding="utf-8") as inp:
for line in inp:
line = line.strip()
if not line or line.startswith("//"):
continue
if line.startswith("#"):
mm = re.match(rx_include, line)
... | Find user includes (no system includes) requested from given source file.
All .h files will be given relative to the current folder, e.g.
["c/rowindex.h", "c/column.h"]. | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/ci/make_fast.py#L35-L53 | null | #!/usr/bin/env python3
# © H2O.ai 2018; -*- encoding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#--------------------------------------------------... |
h2oai/datatable | ci/make_fast.py | build_headermap | python | def build_headermap(headers):
# TODO: what happens if some headers are circularly dependent?
headermap = {}
for hfile in headers:
headermap[hfile] = None
for hfile in headers:
assert (hfile.startswith("c/") or
hfile.startswith("datatable/include/"))
inc = find_inc... | Construct dictionary {header_file : set_of_included_files}.
This function operates on "real" set of includes, in the sense that it
parses each header file to check which files are included from there. | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/ci/make_fast.py#L56-L78 | [
"def find_includes(filename):\n \"\"\"\n Find user includes (no system includes) requested from given source file.\n\n All .h files will be given relative to the current folder, e.g.\n [\"c/rowindex.h\", \"c/column.h\"].\n \"\"\"\n includes = []\n with open(filename, \"r\", encoding=\"utf-8\") ... | #!/usr/bin/env python3
# © H2O.ai 2018; -*- encoding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#--------------------------------------------------... |
h2oai/datatable | ci/make_fast.py | build_sourcemap | python | def build_sourcemap(sources):
sourcemap = {}
for sfile in sources:
inc = find_includes(sfile)
sourcemap[sfile] = set(inc)
return sourcemap | Similar to build_headermap(), but builds a dictionary of includes from
the "source" files (i.e. ".c/.cc" files). | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/ci/make_fast.py#L81-L90 | [
"def find_includes(filename):\n \"\"\"\n Find user includes (no system includes) requested from given source file.\n\n All .h files will be given relative to the current folder, e.g.\n [\"c/rowindex.h\", \"c/column.h\"].\n \"\"\"\n includes = []\n with open(filename, \"r\", encoding=\"utf-8\") ... | #!/usr/bin/env python3
# © H2O.ai 2018; -*- encoding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#--------------------------------------------------... |
h2oai/datatable | setup.py | get_c_sources | python | def get_c_sources(folder, include_headers=False):
allowed_extensions = [".c", ".C", ".cc", ".cpp", ".cxx", ".c++"]
if include_headers:
allowed_extensions += [".h", ".hpp"]
sources = []
for root, _, files in os.walk(folder):
for name in files:
ext = os.path.splitext(name)[1]
... | Find all C/C++ source files in the `folder` directory. | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/setup.py#L61-L76 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Copyright 2018 H2O.ai
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the... |
h2oai/datatable | datatable/fread.py | GenericReader._get_destination | python | def _get_destination(self, estimated_size):
global _psutil_load_attempted
if not _psutil_load_attempted:
_psutil_load_attempted = True
try:
import psutil
except ImportError:
psutil = None
if self.verbose and estimated_size > 1:... | Invoked from the C level, this function will return either the name of
the folder where the datatable is to be saved; or None, indicating that
the datatable should be read into RAM. This function may also raise an
exception if it determines that it cannot find a good strategy to
handle a... | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/datatable/fread.py#L685-L735 | null | class GenericReader(object):
"""
Parser object for reading CSV files.
"""
def __init__(self, anysource=None, *, file=None, text=None, url=None,
cmd=None, columns=None, sep=None,
max_nrows=None, header=None, na_strings=None, verbose=False,
fill=False, e... |
h2oai/datatable | datatable/nff.py | save_nff | python | def save_nff(self, dest, _strategy="auto"):
if _strategy not in ("auto", "write", "mmap"):
raise TValueError("Invalid parameter _strategy: only 'write' / 'mmap' "
"/ 'auto' are allowed")
dest = os.path.expanduser(dest)
if not os.path.exists(dest):
os.makedirs(dest)... | Save Frame in binary NFF/Jay format.
:param dest: destination where the Frame should be saved.
:param _strategy: one of "mmap", "write" or "auto" | train | https://github.com/h2oai/datatable/blob/dd5fba74d2ca85b66f82ae3c1e0b6ea2fd792564/datatable/nff.py#L24-L61 | [
"def dtwarn(message):\n warnings.warn(message, category=DatatableWarning)\n",
"def _stringify(x):\n if x is None:\n return \"\"\n if isinstance(x, bool):\n return str(int(x))\n return str(x)\n"
] | #!/usr/bin/env python3
# © H2O.ai 2018; -*- encoding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#--------------------------------------------------... |
constverum/ProxyBroker | proxybroker/api.py | Broker.grab | python | async def grab(self, *, countries=None, limit=0):
self._countries = countries
self._limit = limit
task = asyncio.ensure_future(self._grab(check=False))
self._all_tasks.append(task) | Gather proxies from the providers without checking.
:param list countries: (optional) List of ISO country codes
where should be located proxies
:param int limit: (optional) The maximum number of proxies
:ref:`Example of usage <proxybroker-examples-grab>`. | train | https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/api.py#L112-L124 | [
"async def _grab(self, types=None, check=False):\n def _get_tasks(by=MAX_CONCURRENT_PROVIDERS):\n providers = [\n pr\n for pr in self._providers\n if not types or not pr.proto or bool(pr.proto & types.keys())\n ]\n while providers:\n tasks = [\n ... | class Broker:
"""The Broker.
| One broker to rule them all, one broker to find them,
| One broker to bring them all and in the darkness bind them.
:param asyncio.Queue queue: (optional) Queue of found/checked proxies
:param int timeout: (optional) Timeout of a request in seconds
:param int max... |
constverum/ProxyBroker | proxybroker/api.py | Broker.find | python | async def find(
self,
*,
types=None,
data=None,
countries=None,
post=False,
strict=False,
dnsbl=None,
limit=0,
**kwargs
):
ip = await self._resolver.get_real_ext_ip()
types = _update_types(types)
if not types:
... | Gather and check proxies from providers or from a passed data.
:ref:`Example of usage <proxybroker-examples-find>`.
:param list types:
Types (protocols) that need to be check on support by proxy.
Supported: HTTP, HTTPS, SOCKS4, SOCKS5, CONNECT:80, CONNECT:25
And lev... | train | https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/api.py#L126-L200 | [
"def _update_types(types):\n _types = {}\n if not types:\n return _types\n elif isinstance(types, dict):\n return types\n for tp in types:\n lvl = None\n if isinstance(tp, (list, tuple, set)):\n tp, lvl = tp[0], tp[1]\n if isinstance(lvl, str):\n ... | class Broker:
"""The Broker.
| One broker to rule them all, one broker to find them,
| One broker to bring them all and in the darkness bind them.
:param asyncio.Queue queue: (optional) Queue of found/checked proxies
:param int timeout: (optional) Timeout of a request in seconds
:param int max... |
constverum/ProxyBroker | proxybroker/api.py | Broker.serve | python | def serve(self, host='127.0.0.1', port=8888, limit=100, **kwargs):
if limit <= 0:
raise ValueError(
'In serve mode value of the limit cannot be less than or '
'equal to zero. Otherwise, a parsing of providers will be '
'endless'
)
... | Start a local proxy server.
The server distributes incoming requests to a pool of found proxies.
When the server receives an incoming request, it chooses the optimal
proxy (based on the percentage of errors and average response time)
and passes to it the incoming request.
In a... | train | https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/api.py#L202-L288 | [
"async def find(\n self,\n *,\n types=None,\n data=None,\n countries=None,\n post=False,\n strict=False,\n dnsbl=None,\n limit=0,\n **kwargs\n):\n \"\"\"Gather and check proxies from providers or from a passed data.\n\n :ref:`Example of usage <proxybroker-examples-find>`.\n\n ... | class Broker:
"""The Broker.
| One broker to rule them all, one broker to find them,
| One broker to bring them all and in the darkness bind them.
:param asyncio.Queue queue: (optional) Queue of found/checked proxies
:param int timeout: (optional) Timeout of a request in seconds
:param int max... |
constverum/ProxyBroker | proxybroker/api.py | Broker._load | python | async def _load(self, data, check=True):
log.debug('Load proxies from the raw data')
if isinstance(data, io.TextIOWrapper):
data = data.read()
if isinstance(data, str):
data = IPPortPatternLine.findall(data)
proxies = set(data)
for proxy in proxies:
... | Looking for proxies in the passed data.
Transform the passed data from [raw string | file-like object | list]
to set {(host, port), ...}: {('192.168.0.1', '80'), } | train | https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/api.py#L290-L305 | null | class Broker:
"""The Broker.
| One broker to rule them all, one broker to find them,
| One broker to bring them all and in the darkness bind them.
:param asyncio.Queue queue: (optional) Queue of found/checked proxies
:param int timeout: (optional) Timeout of a request in seconds
:param int max... |
constverum/ProxyBroker | proxybroker/api.py | Broker.stop | python | def stop(self):
self._done()
if self._server:
self._server.stop()
self._server = None
log.info('Stop!') | Stop all tasks, and the local proxy server if it's running. | train | https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/api.py#L409-L415 | [
"def _done(self):\n log.debug('called done')\n while self._all_tasks:\n task = self._all_tasks.pop()\n if not task.done():\n task.cancel()\n self._push_to_result(None)\n log.info('Done! Total found proxies: %d' % len(self.unique_proxies))\n"
] | class Broker:
"""The Broker.
| One broker to rule them all, one broker to find them,
| One broker to bring them all and in the darkness bind them.
:param asyncio.Queue queue: (optional) Queue of found/checked proxies
:param int timeout: (optional) Timeout of a request in seconds
:param int max... |
constverum/ProxyBroker | proxybroker/api.py | Broker.show_stats | python | def show_stats(self, verbose=False, **kwargs):
if kwargs:
verbose = True
warnings.warn(
'`full` in `show_stats` is deprecated, '
'use `verbose` instead.',
DeprecationWarning,
)
found_proxies = self.unique_proxies.values... | Show statistics on the found proxies.
Useful for debugging, but you can also use if you're interested.
:param verbose: Flag indicating whether to print verbose stats
.. deprecated:: 0.2.0
Use :attr:`verbose` instead of :attr:`full`. | train | https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/api.py#L426-L514 | null | class Broker:
"""The Broker.
| One broker to rule them all, one broker to find them,
| One broker to bring them all and in the darkness bind them.
:param asyncio.Queue queue: (optional) Queue of found/checked proxies
:param int timeout: (optional) Timeout of a request in seconds
:param int max... |
constverum/ProxyBroker | examples/only_grab.py | save | python | async def save(proxies, filename):
with open(filename, 'w') as f:
while True:
proxy = await proxies.get()
if proxy is None:
break
f.write('%s:%d\n' % (proxy.host, proxy.port)) | Save proxies to a file. | train | https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/examples/only_grab.py#L9-L16 | null | """Gather proxies from the providers without
checking and save them to a file."""
import asyncio
from proxybroker import Broker
def main():
proxies = asyncio.Queue()
broker = Broker(proxies)
tasks = asyncio.gather(
broker.grab(countries=['US', 'GB'], limit=10),
save(proxies, filename... |
constverum/ProxyBroker | proxybroker/resolver.py | Resolver.get_ip_info | python | def get_ip_info(ip):
# from pprint import pprint
try:
ipInfo = _mmdb_reader.get(ip) or {}
except (maxminddb.errors.InvalidDatabaseError, ValueError):
ipInfo = {}
code, name = '--', 'Unknown'
city_name, region_code, region_name = ('Unknown',) * 3
i... | Return geo information about IP address.
`code` - ISO country code
`name` - Full name of country
`region_code` - ISO region code
`region_name` - Full name of region
`city_name` - Full name of city | train | https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/resolver.py#L57-L85 | null | class Resolver:
"""Async host resolver based on aiodns."""
_cached_hosts = {}
_ip_hosts = [
'https://wtfismyip.com/text',
'http://api.ipify.org/',
'http://ipinfo.io/ip',
'http://ipv4.icanhazip.com/',
'http://myexternalip.com/raw',
'http://ipinfo.io/ip',
... |
constverum/ProxyBroker | proxybroker/resolver.py | Resolver.get_real_ext_ip | python | async def get_real_ext_ip(self):
while self._ip_hosts:
try:
timeout = aiohttp.ClientTimeout(total=self._timeout)
async with aiohttp.ClientSession(
timeout=timeout, loop=self._loop
) as session, session.get(self._pop_random_ip_host()... | Return real external IP address. | train | https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/resolver.py#L92-L110 | [
"def host_is_ip(host):\n \"\"\"Check a host is IP address.\"\"\"\n # TODO: add IPv6 support\n try:\n ipaddress.IPv4Address(host)\n except ipaddress.AddressValueError:\n return False\n else:\n return True\n",
"def _pop_random_ip_host(self):\n host = random.choice(self._ip_hos... | class Resolver:
"""Async host resolver based on aiodns."""
_cached_hosts = {}
_ip_hosts = [
'https://wtfismyip.com/text',
'http://api.ipify.org/',
'http://ipinfo.io/ip',
'http://ipv4.icanhazip.com/',
'http://myexternalip.com/raw',
'http://ipinfo.io/ip',
... |
constverum/ProxyBroker | proxybroker/resolver.py | Resolver.resolve | python | async def resolve(
self, host, port=80, family=None, qtype='A', logging=True
):
if self.host_is_ip(host):
return host
_host = self._cached_hosts.get(host)
if _host:
return _host
resp = await self._resolve(host, qtype)
if resp:
ho... | Return resolving IP address(es) from host name. | train | https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/resolver.py#L112-L148 | [
"def host_is_ip(host):\n \"\"\"Check a host is IP address.\"\"\"\n # TODO: add IPv6 support\n try:\n ipaddress.IPv4Address(host)\n except ipaddress.AddressValueError:\n return False\n else:\n return True\n"
] | class Resolver:
"""Async host resolver based on aiodns."""
_cached_hosts = {}
_ip_hosts = [
'https://wtfismyip.com/text',
'http://api.ipify.org/',
'http://ipinfo.io/ip',
'http://ipv4.icanhazip.com/',
'http://myexternalip.com/raw',
'http://ipinfo.io/ip',
... |
constverum/ProxyBroker | proxybroker/proxy.py | Proxy.create | python | async def create(cls, host, *args, **kwargs):
"""Asynchronously create a :class:`Proxy` object.
:param str host: A passed host can be a domain or IP address.
If the host is a domain, try to resolve it
:param str \*args:
(optional) Positional arguments that :... | Asynchronously create a :class:`Proxy` object.
:param str host: A passed host can be a domain or IP address.
If the host is a domain, try to resolve it
:param str \*args:
(optional) Positional arguments that :class:`Proxy` takes
:param str \*\*kwargs:
... | train | https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/proxy.py#L41-L65 | null | class Proxy:
"""Proxy.
:param str host: IP address of the proxy
:param int port: Port of the proxy
:param tuple types:
(optional) List of types (protocols) which may be supported
by the proxy and which can be checked to work with the proxy
:param int timeout:
(optional) Time... |
constverum/ProxyBroker | proxybroker/proxy.py | Proxy.error_rate | python | def error_rate(self):
if not self.stat['requests']:
return 0
return round(
sum(self.stat['errors'].values()) / self.stat['requests'], 2
) | Error rate: from 0 to 1.
For example: 0.7 = 70% requests ends with error.
:rtype: float
.. versionadded:: 0.2.0 | train | https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/proxy.py#L160-L173 | null | class Proxy:
"""Proxy.
:param str host: IP address of the proxy
:param int port: Port of the proxy
:param tuple types:
(optional) List of types (protocols) which may be supported
by the proxy and which can be checked to work with the proxy
:param int timeout:
(optional) Time... |
constverum/ProxyBroker | proxybroker/proxy.py | Proxy.schemes | python | def schemes(self):
if not self._schemes:
_schemes = []
if self.types.keys() & _HTTP_PROTOS:
_schemes.append('HTTP')
if self.types.keys() & _HTTPS_PROTOS:
_schemes.append('HTTPS')
self._schemes = tuple(_schemes)
return self._... | Return supported schemes. | train | https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/proxy.py#L176-L185 | null | class Proxy:
"""Proxy.
:param str host: IP address of the proxy
:param int port: Port of the proxy
:param tuple types:
(optional) List of types (protocols) which may be supported
by the proxy and which can be checked to work with the proxy
:param int timeout:
(optional) Time... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.