hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 1.02M | avg_line_length float64 1 417k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 1
class | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f7104bc49d07210082b385fe7fdff2047bffb718 | 9,835 | py | Python | env/lib/python3.6/site-packages/jet/dashboard/dashboard.py | anthowen/duplify | 846d01c1b21230937fdf0281b0cf8c0b08a8c24e | [
"MIT"
] | 2 | 2019-12-04T16:24:44.000Z | 2020-04-06T21:49:34.000Z | env/lib/python3.6/site-packages/jet/dashboard/dashboard.py | anthowen/duplify | 846d01c1b21230937fdf0281b0cf8c0b08a8c24e | [
"MIT"
] | 21 | 2021-02-04T01:37:44.000Z | 2022-03-12T01:00:55.000Z | env/lib/python3.6/site-packages/jet/dashboard/dashboard.py | anthowen/duplify | 846d01c1b21230937fdf0281b0cf8c0b08a8c24e | [
"MIT"
] | null | null | null | from importlib import import_module
try:
from django.core.urlresolvers import reverse
except ImportError: # Django 1.11
from django.urls import reverse
from django.template.loader import render_to_string
from jet.dashboard import modules
from jet.dashboard.models import UserDashboardModule
from django.utils.translation import ugettext_lazy as _
from jet.ordered_set import OrderedSet
from jet.utils import get_admin_site_name, context_to_dict
try:
from django.template.context_processors import csrf
except ImportError:
from django.core.context_processors import csrf
class Dashboard(object):
"""
Base dashboard class. All custom dashboards should inherit it.
"""
#: Number of columns in which widgets can be placed
columns = 2
#: Dashboard Modules (widgets) that dashboard is filled with, when the user open it for the first time
#:
#: List of dashboard module **instances**
children = None
#: Dashboard Modules (widgets) that user can add to dashboard at any time
# (not created when the user open dashboard for the first time)
#:
#: List of dashboard module **classes**
available_children = None
app_label = None
context = None
modules = None
class Media:
css = ()
js = ()
def __init__(self, context, **kwargs):
for key in kwargs:
if hasattr(self.__class__, key):
setattr(self, key, kwargs[key])
self.children = self.children or []
self.available_children = self.available_children or []
self.set_context(context)
def set_context(self, context):
self.context = context
self.init_with_context(context)
self.load_modules()
def init_with_context(self, context):
"""
Override this method to fill your custom **Dashboard** class with widgets.
You should add your widgets to ``children`` and ``available_children`` attributes.
Usage example:
.. code-block:: python
from django.utils.translation import ugettext_lazy as _
from jet.dashboard import modules
from jet.dashboard.dashboard import Dashboard, AppIndexDashboard
class CustomIndexDashboard(Dashboard):
columns = 3
def init_with_context(self, context):
self.available_children.append(modules.LinkList)
self.children.append(modules.LinkList(
_('Support'),
children=[
{
'title': _('Django documentation'),
'url': 'http://docs.djangoproject.com/',
'external': True,
},
{
'title': _('Django "django-users" mailing list'),
'url': 'http://groups.google.com/group/django-users',
'external': True,
},
{
'title': _('Django irc channel'),
'url': 'irc://irc.freenode.net/django',
'external': True,
},
],
column=0,
order=0
))
"""
pass
def load_module(self, module_fullname):
package, module_name = module_fullname.rsplit('.', 1)
package = import_module(package)
module = getattr(package, module_name)
return module
def create_initial_module_models(self, user):
module_models = []
i = 0
for module in self.children:
column = module.column if module.column is not None else i % self.columns
order = module.order if module.order is not None else int(i / self.columns)
module_models.append(UserDashboardModule.objects.create(
title=module.title,
app_label=self.app_label,
user=user.pk,
module=module.fullname(),
column=column,
order=order,
settings=module.dump_settings(),
children=module.dump_children()
))
i += 1
return module_models
def load_modules(self):
module_models = UserDashboardModule.objects.filter(
app_label=self.app_label,
user=self.context['request'].user.pk
).all()
if len(module_models) == 0:
module_models = self.create_initial_module_models(self.context['request'].user)
loaded_modules = []
for module_model in module_models:
module_cls = module_model.load_module()
if module_cls is not None:
module = module_cls(model=module_model, context=self.context)
loaded_modules.append(module)
self.modules = loaded_modules
def render(self):
context = context_to_dict(self.context)
context.update({
'columns': range(self.columns),
'modules': self.modules,
'app_label': self.app_label,
})
context.update(csrf(context['request']))
return render_to_string('jet.dashboard/dashboard.html', context)
def render_tools(self):
context = context_to_dict(self.context)
context.update({
'children': self.children,
'app_label': self.app_label,
'available_children': self.available_children
})
context.update(csrf(context['request']))
return render_to_string('jet.dashboard/dashboard_tools.html', context)
def media(self):
unique_css = OrderedSet()
unique_js = OrderedSet()
for js in getattr(self.Media, 'js', ()):
unique_js.add(js)
for css in getattr(self.Media, 'css', ()):
unique_css.add(css)
for module in self.modules:
for js in getattr(module.Media, 'js', ()):
unique_js.add(js)
for css in getattr(module.Media, 'css', ()):
unique_css.add(css)
class Media:
css = list(unique_css)
js = list(unique_js)
return Media
class AppIndexDashboard(Dashboard):
def get_app_content_types(self):
return self.app_label + '.*',
def models(self):
return self.app_label + '.*',
class DefaultIndexDashboard(Dashboard):
columns = 3
def init_with_context(self, context):
self.available_children.append(modules.LinkList)
self.available_children.append(modules.Feed)
site_name = get_admin_site_name(context)
# append a link list module for "quick links"
self.children.append(modules.LinkList(
_('Quick links'),
layout='inline',
draggable=False,
deletable=False,
collapsible=False,
children=[
[_('Return to site'), '/'],
[_('Change password'),
reverse('%s:password_change' % site_name)],
[_('Log out'), reverse('%s:logout' % site_name)],
],
column=0,
order=0
))
# append an app list module for "Applications"
self.children.append(modules.AppList(
_('Applications'),
exclude=('auth.*',),
column=1,
order=0
))
# append an app list module for "Administration"
self.children.append(modules.AppList(
_('Administration'),
models=('auth.*',),
column=2,
order=0
))
# append a recent actions module
self.children.append(modules.RecentActions(
_('Recent Actions'),
10,
column=0,
order=1
))
# append a feed module
self.children.append(modules.Feed(
_('Latest Django News'),
feed_url='http://www.djangoproject.com/rss/weblog/',
limit=5,
column=1,
order=1
))
# append another link list module for "support".
self.children.append(modules.LinkList(
_('Support'),
children=[
{
'title': _('Django documentation'),
'url': 'http://docs.djangoproject.com/',
'external': True,
},
{
'title': _('Django "django-users" mailing list'),
'url': 'http://groups.google.com/group/django-users',
'external': True,
},
{
'title': _('Django irc channel'),
'url': 'irc://irc.freenode.net/django',
'external': True,
},
],
column=2,
order=1
))
class DefaultAppIndexDashboard(AppIndexDashboard):
def init_with_context(self, context):
self.available_children.append(modules.LinkList)
self.children.append(modules.ModelList(
title=_('Application models'),
models=self.models(),
column=0,
order=0
))
self.children.append(modules.RecentActions(
include_list=self.get_app_content_types(),
column=1,
order=0
))
class DashboardUrls(object):
_urls = []
def get_urls(self):
return self._urls
def register_url(self, url):
self._urls.append(url)
def register_urls(self, urls):
self._urls.extend(urls)
urls = DashboardUrls()
| 30.927673 | 106 | 0.54306 | from importlib import import_module
try:
from django.core.urlresolvers import reverse
except ImportError:
from django.urls import reverse
from django.template.loader import render_to_string
from jet.dashboard import modules
from jet.dashboard.models import UserDashboardModule
from django.utils.translation import ugettext_lazy as _
from jet.ordered_set import OrderedSet
from jet.utils import get_admin_site_name, context_to_dict
try:
from django.template.context_processors import csrf
except ImportError:
from django.core.context_processors import csrf
class Dashboard(object):
columns = 2
children = None
available_children = None
app_label = None
context = None
modules = None
class Media:
css = ()
js = ()
def __init__(self, context, **kwargs):
for key in kwargs:
if hasattr(self.__class__, key):
setattr(self, key, kwargs[key])
self.children = self.children or []
self.available_children = self.available_children or []
self.set_context(context)
def set_context(self, context):
self.context = context
self.init_with_context(context)
self.load_modules()
def init_with_context(self, context):
pass
def load_module(self, module_fullname):
package, module_name = module_fullname.rsplit('.', 1)
package = import_module(package)
module = getattr(package, module_name)
return module
def create_initial_module_models(self, user):
module_models = []
i = 0
for module in self.children:
column = module.column if module.column is not None else i % self.columns
order = module.order if module.order is not None else int(i / self.columns)
module_models.append(UserDashboardModule.objects.create(
title=module.title,
app_label=self.app_label,
user=user.pk,
module=module.fullname(),
column=column,
order=order,
settings=module.dump_settings(),
children=module.dump_children()
))
i += 1
return module_models
def load_modules(self):
module_models = UserDashboardModule.objects.filter(
app_label=self.app_label,
user=self.context['request'].user.pk
).all()
if len(module_models) == 0:
module_models = self.create_initial_module_models(self.context['request'].user)
loaded_modules = []
for module_model in module_models:
module_cls = module_model.load_module()
if module_cls is not None:
module = module_cls(model=module_model, context=self.context)
loaded_modules.append(module)
self.modules = loaded_modules
def render(self):
context = context_to_dict(self.context)
context.update({
'columns': range(self.columns),
'modules': self.modules,
'app_label': self.app_label,
})
context.update(csrf(context['request']))
return render_to_string('jet.dashboard/dashboard.html', context)
def render_tools(self):
context = context_to_dict(self.context)
context.update({
'children': self.children,
'app_label': self.app_label,
'available_children': self.available_children
})
context.update(csrf(context['request']))
return render_to_string('jet.dashboard/dashboard_tools.html', context)
def media(self):
unique_css = OrderedSet()
unique_js = OrderedSet()
for js in getattr(self.Media, 'js', ()):
unique_js.add(js)
for css in getattr(self.Media, 'css', ()):
unique_css.add(css)
for module in self.modules:
for js in getattr(module.Media, 'js', ()):
unique_js.add(js)
for css in getattr(module.Media, 'css', ()):
unique_css.add(css)
class Media:
css = list(unique_css)
js = list(unique_js)
return Media
class AppIndexDashboard(Dashboard):
def get_app_content_types(self):
return self.app_label + '.*',
def models(self):
return self.app_label + '.*',
class DefaultIndexDashboard(Dashboard):
columns = 3
def init_with_context(self, context):
self.available_children.append(modules.LinkList)
self.available_children.append(modules.Feed)
site_name = get_admin_site_name(context)
self.children.append(modules.LinkList(
_('Quick links'),
layout='inline',
draggable=False,
deletable=False,
collapsible=False,
children=[
[_('Return to site'), '/'],
[_('Change password'),
reverse('%s:password_change' % site_name)],
[_('Log out'), reverse('%s:logout' % site_name)],
],
column=0,
order=0
))
self.children.append(modules.AppList(
_('Applications'),
exclude=('auth.*',),
column=1,
order=0
))
self.children.append(modules.AppList(
_('Administration'),
models=('auth.*',),
column=2,
order=0
))
self.children.append(modules.RecentActions(
_('Recent Actions'),
10,
column=0,
order=1
))
self.children.append(modules.Feed(
_('Latest Django News'),
feed_url='http://www.djangoproject.com/rss/weblog/',
limit=5,
column=1,
order=1
))
self.children.append(modules.LinkList(
_('Support'),
children=[
{
'title': _('Django documentation'),
'url': 'http://docs.djangoproject.com/',
'external': True,
},
{
'title': _('Django "django-users" mailing list'),
'url': 'http://groups.google.com/group/django-users',
'external': True,
},
{
'title': _('Django irc channel'),
'url': 'irc://irc.freenode.net/django',
'external': True,
},
],
column=2,
order=1
))
class DefaultAppIndexDashboard(AppIndexDashboard):
def init_with_context(self, context):
self.available_children.append(modules.LinkList)
self.children.append(modules.ModelList(
title=_('Application models'),
models=self.models(),
column=0,
order=0
))
self.children.append(modules.RecentActions(
include_list=self.get_app_content_types(),
column=1,
order=0
))
class DashboardUrls(object):
_urls = []
def get_urls(self):
return self._urls
def register_url(self, url):
self._urls.append(url)
def register_urls(self, urls):
self._urls.extend(urls)
urls = DashboardUrls()
| true | true |
f7104c3230ed827c44d1fa39deafc95074822af7 | 2,126 | py | Python | gateware/info/git.py | paddatrapper/HDMI2USB-litex-firmware | 6a0235abe0ce9195b1717742c13c0dc4d45c3f4d | [
"BSD-2-Clause"
] | 4 | 2018-08-19T03:50:15.000Z | 2020-07-24T23:08:48.000Z | gateware/info/git.py | bunnie/litex-buildenv | 7a704884a7f139716880ea02fec9309e253878e4 | [
"BSD-2-Clause"
] | null | null | null | gateware/info/git.py | bunnie/litex-buildenv | 7a704884a7f139716880ea02fec9309e253878e4 | [
"BSD-2-Clause"
] | null | null | null | import binascii
import os
import subprocess
import sys
from migen.fhdl import *
from litex.soc.interconnect.csr import *
def git_root():
if sys.platform == "win32":
# Git on Windows is likely to use Unix-style paths (`/c/path/to/repo`),
# whereas directories passed to Python should be Windows-style paths
# (`C:/path/to/repo`) (because Python calls into the Windows API).
# `cygpath` converts between the two.
git = subprocess.Popen(
"git rev-parse --show-toplevel",
cwd=os.path.dirname(__file__),
stdout=subprocess.PIPE,
)
path = subprocess.check_output(
"cygpath -wf -",
stdin=git.stdout,
)
git.wait()
return path.decode('ascii').strip()
else:
return subprocess.check_output(
"git rev-parse --show-toplevel",
shell=True,
cwd=os.path.dirname(__file__),
).decode('ascii').strip()
def git_commit():
data = subprocess.check_output(
"git rev-parse HEAD",
shell=True,
cwd=git_root(),
).decode('ascii').strip()
return binascii.unhexlify(data)
def git_describe():
return subprocess.check_output(
"git describe --dirty",
shell=True,
cwd=git_root(),
).decode('ascii').strip()
def git_status():
return subprocess.check_output(
"git status --short",
shell=True,
cwd=git_root(),
).decode('ascii').strip()
class GitInfo(Module, AutoCSR):
def __init__(self):
commit = sum(int(x) << (i*8) for i, x in enumerate(reversed(git_commit())))
self.commit = CSRStatus(160)
# FIXME: This should be a read-only Memory object
#extradata = [ord(x) for x in "\0".join([
# "https://github.com/timvideos/HDMI2USB-misoc-firmware.git",
# git_describe(),
# git_status(),
# "",
# ])]
#self.extradata = CSRStatus(len(extradata)*8)
self.comb += [
self.commit.status.eq(commit),
# self.extradata.status.eq(extradata),
]
| 28.72973 | 83 | 0.574788 | import binascii
import os
import subprocess
import sys
from migen.fhdl import *
from litex.soc.interconnect.csr import *
def git_root():
if sys.platform == "win32":
git = subprocess.Popen(
"git rev-parse --show-toplevel",
cwd=os.path.dirname(__file__),
stdout=subprocess.PIPE,
)
path = subprocess.check_output(
"cygpath -wf -",
stdin=git.stdout,
)
git.wait()
return path.decode('ascii').strip()
else:
return subprocess.check_output(
"git rev-parse --show-toplevel",
shell=True,
cwd=os.path.dirname(__file__),
).decode('ascii').strip()
def git_commit():
data = subprocess.check_output(
"git rev-parse HEAD",
shell=True,
cwd=git_root(),
).decode('ascii').strip()
return binascii.unhexlify(data)
def git_describe():
return subprocess.check_output(
"git describe --dirty",
shell=True,
cwd=git_root(),
).decode('ascii').strip()
def git_status():
return subprocess.check_output(
"git status --short",
shell=True,
cwd=git_root(),
).decode('ascii').strip()
class GitInfo(Module, AutoCSR):
def __init__(self):
commit = sum(int(x) << (i*8) for i, x in enumerate(reversed(git_commit())))
self.commit = CSRStatus(160)
self.comb += [
self.commit.status.eq(commit),
]
| true | true |
f7104c78c2bdf22a9a4177a3028c98b9bd1f60e0 | 20,626 | py | Python | conans/model/build_info.py | pasrom/conan | 5704fafa72e6619abb9714d99df5d13081d6f357 | [
"MIT"
] | null | null | null | conans/model/build_info.py | pasrom/conan | 5704fafa72e6619abb9714d99df5d13081d6f357 | [
"MIT"
] | null | null | null | conans/model/build_info.py | pasrom/conan | 5704fafa72e6619abb9714d99df5d13081d6f357 | [
"MIT"
] | null | null | null | import os
from collections import OrderedDict
from copy import copy
from conans.errors import ConanException
from conans.util.conan_v2_mode import conan_v2_behavior
DEFAULT_INCLUDE = "include"
DEFAULT_LIB = "lib"
DEFAULT_BIN = "bin"
DEFAULT_RES = "res"
DEFAULT_SHARE = "share"
DEFAULT_BUILD = ""
DEFAULT_FRAMEWORK = "Frameworks"
COMPONENT_SCOPE = "::"
class DefaultOrderedDict(OrderedDict):
def __init__(self, factory):
self.factory = factory
super(DefaultOrderedDict, self).__init__()
def __getitem__(self, key):
if key not in self.keys():
super(DefaultOrderedDict, self).__setitem__(key, self.factory())
super(DefaultOrderedDict, self).__getitem__(key).name = key
return super(DefaultOrderedDict, self).__getitem__(key)
def __copy__(self):
the_copy = DefaultOrderedDict(self.factory)
for key, value in super(DefaultOrderedDict, self).items():
the_copy[key] = value
return the_copy
class _CppInfo(object):
""" Object that stores all the necessary information to build in C/C++.
It is intended to be system independent, translation to
specific systems will be produced from this info
"""
def __init__(self):
self._name = None
self.names = {}
self.system_libs = [] # Ordered list of system libraries
self.includedirs = [] # Ordered list of include paths
self.srcdirs = [] # Ordered list of source paths
self.libdirs = [] # Directories to find libraries
self.resdirs = [] # Directories to find resources, data, etc
self.bindirs = [] # Directories to find executables and shared libs
self.builddirs = []
self.frameworks = [] # Macos .framework
self.frameworkdirs = []
self.rootpaths = []
self.libs = [] # The libs to link against
self.defines = [] # preprocessor definitions
self.cflags = [] # pure C flags
self.cxxflags = [] # C++ compilation flags
self.sharedlinkflags = [] # linker flags
self.exelinkflags = [] # linker flags
self.build_modules = []
self.filenames = {} # name of filename to create for various generators
self.rootpath = ""
self.sysroot = ""
self._build_modules_paths = None
self._include_paths = None
self._lib_paths = None
self._bin_paths = None
self._build_paths = None
self._res_paths = None
self._src_paths = None
self._framework_paths = None
self.version = None # Version of the conan package
self.description = None # Description of the conan package
# When package is editable, filter_empty=False, so empty dirs are maintained
self.filter_empty = True
def _filter_paths(self, paths):
abs_paths = [os.path.join(self.rootpath, p)
if not os.path.isabs(p) else p for p in paths]
if self.filter_empty:
return [p for p in abs_paths if os.path.isdir(p)]
else:
return abs_paths
@property
def build_modules_paths(self):
if self._build_modules_paths is None:
self._build_modules_paths = [os.path.join(self.rootpath, p) if not os.path.isabs(p)
else p for p in self.build_modules]
return self._build_modules_paths
@property
def include_paths(self):
if self._include_paths is None:
self._include_paths = self._filter_paths(self.includedirs)
return self._include_paths
@property
def lib_paths(self):
if self._lib_paths is None:
self._lib_paths = self._filter_paths(self.libdirs)
return self._lib_paths
@property
def src_paths(self):
if self._src_paths is None:
self._src_paths = self._filter_paths(self.srcdirs)
return self._src_paths
@property
def bin_paths(self):
if self._bin_paths is None:
self._bin_paths = self._filter_paths(self.bindirs)
return self._bin_paths
@property
def build_paths(self):
if self._build_paths is None:
self._build_paths = self._filter_paths(self.builddirs)
return self._build_paths
@property
def res_paths(self):
if self._res_paths is None:
self._res_paths = self._filter_paths(self.resdirs)
return self._res_paths
@property
def framework_paths(self):
if self._framework_paths is None:
self._framework_paths = self._filter_paths(self.frameworkdirs)
return self._framework_paths
@property
def name(self):
conan_v2_behavior("Use 'get_name(generator)' instead")
return self._name
@name.setter
def name(self, value):
self._name = value
def get_name(self, generator):
return self.names.get(generator, self._name)
def get_filename(self, generator):
result = self.filenames.get(generator)
if result:
return result
return self.get_name(generator)
# Compatibility for 'cppflags' (old style property to allow decoration)
def get_cppflags(self):
conan_v2_behavior("'cpp_info.cppflags' is deprecated, use 'cxxflags' instead")
return self.cxxflags
def set_cppflags(self, value):
conan_v2_behavior("'cpp_info.cppflags' is deprecated, use 'cxxflags' instead")
self.cxxflags = value
cppflags = property(get_cppflags, set_cppflags)
class Component(_CppInfo):
def __init__(self, rootpath):
super(Component, self).__init__()
self.rootpath = rootpath
self.includedirs.append(DEFAULT_INCLUDE)
self.libdirs.append(DEFAULT_LIB)
self.bindirs.append(DEFAULT_BIN)
self.resdirs.append(DEFAULT_RES)
self.builddirs.append(DEFAULT_BUILD)
self.frameworkdirs.append(DEFAULT_FRAMEWORK)
self.requires = []
class CppInfo(_CppInfo):
""" Build Information declared to be used by the CONSUMERS of a
conans. That means that consumers must use this flags and configs i order
to build properly.
Defined in user CONANFILE, directories are relative at user definition time
"""
def __init__(self, ref_name, root_folder):
super(CppInfo, self).__init__()
self._ref_name = ref_name
self._name = ref_name
self.rootpath = root_folder # the full path of the package in which the conans is found
self.includedirs.append(DEFAULT_INCLUDE)
self.libdirs.append(DEFAULT_LIB)
self.bindirs.append(DEFAULT_BIN)
self.resdirs.append(DEFAULT_RES)
self.builddirs.append(DEFAULT_BUILD)
self.frameworkdirs.append(DEFAULT_FRAMEWORK)
self.components = DefaultOrderedDict(lambda: Component(self.rootpath))
# public_deps is needed to accumulate list of deps for cmake targets
self.public_deps = []
self._configs = {}
def __str__(self):
return self._ref_name
def get_name(self, generator):
name = super(CppInfo, self).get_name(generator)
# Legacy logic for pkg_config generator
from conans.client.generators.pkg_config import PkgConfigGenerator
if generator == PkgConfigGenerator.name:
fallback = self._name.lower() if self._name != self._ref_name else self._ref_name
if PkgConfigGenerator.name not in self.names and self._name != self._name.lower():
conan_v2_behavior("Generated file and name for {gen} generator will change in"
" Conan v2 to '{name}'. Use 'self.cpp_info.names[\"{gen}\"]"
" = \"{fallback}\"' in your recipe to continue using current name."
.format(gen=PkgConfigGenerator.name, name=name, fallback=fallback))
name = self.names.get(generator, fallback)
return name
@property
def configs(self):
return self._configs
def __getattr__(self, config):
def _get_cpp_info():
result = _CppInfo()
result.filter_empty = self.filter_empty
result.rootpath = self.rootpath
result.sysroot = self.sysroot
result.includedirs.append(DEFAULT_INCLUDE)
result.libdirs.append(DEFAULT_LIB)
result.bindirs.append(DEFAULT_BIN)
result.resdirs.append(DEFAULT_RES)
result.builddirs.append(DEFAULT_BUILD)
result.frameworkdirs.append(DEFAULT_FRAMEWORK)
return result
return self._configs.setdefault(config, _get_cpp_info())
def _raise_incorrect_components_definition(self, package_name, package_requires):
# Raise if mixing components
if (self.includedirs != [DEFAULT_INCLUDE] or
self.libdirs != [DEFAULT_LIB] or
self.bindirs != [DEFAULT_BIN] or
self.resdirs != [DEFAULT_RES] or
self.builddirs != [DEFAULT_BUILD] or
self.frameworkdirs != [DEFAULT_FRAMEWORK] or
self.libs or
self.system_libs or
self.frameworks or
self.defines or
self.cflags or
self.cxxflags or
self.sharedlinkflags or
self.exelinkflags or
self.build_modules) and self.components:
raise ConanException("self.cpp_info.components cannot be used with self.cpp_info "
"global values at the same time")
if self._configs and self.components:
raise ConanException("self.cpp_info.components cannot be used with self.cpp_info configs"
" (release/debug/...) at the same time")
# Raise on component name
for comp_name, comp in self.components.items():
if comp_name == package_name:
raise ConanException("Component name cannot be the same as the package name: '%s'"
% comp_name)
if self.components:
comp_requires = set()
for comp_name, comp in self.components.items():
for comp_require in comp.requires:
if COMPONENT_SCOPE in comp_require:
comp_requires.add(
comp_require[:comp_require.find(COMPONENT_SCOPE)])
pkg_requires = [require.ref.name for require in package_requires.values()]
# Raise on components requires without package requires
for pkg_require in pkg_requires:
if pkg_require not in comp_requires:
raise ConanException("Package require '%s' not used in components requires"
% pkg_require)
# Raise on components requires requiring inexistent package requires
for comp_require in comp_requires:
if comp_require not in pkg_requires:
raise ConanException("Package require '%s' declared in components requires "
"but not defined as a recipe requirement" % comp_require)
class _BaseDepsCppInfo(_CppInfo):
def __init__(self):
super(_BaseDepsCppInfo, self).__init__()
def update(self, dep_cpp_info):
def merge_lists(seq1, seq2):
return [s for s in seq1 if s not in seq2] + seq2
self.system_libs = merge_lists(self.system_libs, dep_cpp_info.system_libs)
self.includedirs = merge_lists(self.includedirs, dep_cpp_info.include_paths)
self.srcdirs = merge_lists(self.srcdirs, dep_cpp_info.src_paths)
self.libdirs = merge_lists(self.libdirs, dep_cpp_info.lib_paths)
self.bindirs = merge_lists(self.bindirs, dep_cpp_info.bin_paths)
self.resdirs = merge_lists(self.resdirs, dep_cpp_info.res_paths)
self.builddirs = merge_lists(self.builddirs, dep_cpp_info.build_paths)
self.frameworkdirs = merge_lists(self.frameworkdirs, dep_cpp_info.framework_paths)
self.libs = merge_lists(self.libs, dep_cpp_info.libs)
self.frameworks = merge_lists(self.frameworks, dep_cpp_info.frameworks)
self.build_modules = merge_lists(self.build_modules, dep_cpp_info.build_modules_paths)
self.rootpaths.append(dep_cpp_info.rootpath)
# Note these are in reverse order
self.defines = merge_lists(dep_cpp_info.defines, self.defines)
self.cxxflags = merge_lists(dep_cpp_info.cxxflags, self.cxxflags)
self.cflags = merge_lists(dep_cpp_info.cflags, self.cflags)
self.sharedlinkflags = merge_lists(dep_cpp_info.sharedlinkflags, self.sharedlinkflags)
self.exelinkflags = merge_lists(dep_cpp_info.exelinkflags, self.exelinkflags)
if not self.sysroot:
self.sysroot = dep_cpp_info.sysroot
@property
def build_modules_paths(self):
return self.build_modules
@property
def include_paths(self):
return self.includedirs
@property
def lib_paths(self):
return self.libdirs
@property
def src_paths(self):
return self.srcdirs
@property
def bin_paths(self):
return self.bindirs
@property
def build_paths(self):
return self.builddirs
@property
def res_paths(self):
return self.resdirs
@property
def framework_paths(self):
return self.frameworkdirs
class DepCppInfo(object):
def __init__(self, cpp_info):
self._cpp_info = cpp_info
self._libs = None
self._system_libs = None
self._frameworks = None
self._defines = None
self._cxxflags = None
self._cflags = None
self._sharedlinkflags = None
self._exelinkflags = None
self._include_paths = None
self._lib_paths = None
self._bin_paths = None
self._build_paths = None
self._res_paths = None
self._src_paths = None
self._framework_paths = None
self._build_module_paths = None
self._sorted_components = None
self._check_component_requires()
def __str__(self):
return str(self._cpp_info)
def __getattr__(self, item):
try:
attr = self._cpp_info.__getattribute__(item)
except AttributeError: # item is not defined, get config (CppInfo)
attr = self._cpp_info.__getattr__(item)
return attr
@staticmethod
def _merge_lists(seq1, seq2):
return seq1 + [s for s in seq2 if s not in seq1]
def _aggregated_values(self, item):
values = getattr(self, "_%s" % item)
if values is not None:
return values
values = getattr(self._cpp_info, item)
if self._cpp_info.components:
for component in self._get_sorted_components().values():
values = self._merge_lists(values, getattr(component, item))
setattr(self, "_%s" % item, values)
return values
def _aggregated_paths(self, item):
paths = getattr(self, "_%s_paths" % item)
if paths is not None:
return paths
paths = getattr(self._cpp_info, "%s_paths" % item)
if self._cpp_info.components:
for component in self._get_sorted_components().values():
paths = self._merge_lists(paths, getattr(component, "%s_paths" % item))
setattr(self, "_%s_paths" % item, paths)
return paths
@staticmethod
def _filter_component_requires(requires):
return [r for r in requires if COMPONENT_SCOPE not in r]
def _check_component_requires(self):
for comp_name, comp in self._cpp_info.components.items():
if not all([require in self._cpp_info.components for require in
self._filter_component_requires(comp.requires)]):
raise ConanException("Component '%s' declares a missing dependency" % comp_name)
bad_requires = [r for r in comp.requires if r.startswith(COMPONENT_SCOPE)]
if bad_requires:
msg = "Leading character '%s' not allowed in %s requires: %s. Omit it to require " \
"components inside the same package." \
% (COMPONENT_SCOPE, comp_name, bad_requires)
raise ConanException(msg)
def _get_sorted_components(self):
"""
Sort Components from most dependent one first to the less dependent one last
:return: List of sorted components
"""
if not self._sorted_components:
if any([[require for require in self._filter_component_requires(comp.requires)]
for comp in self._cpp_info.components.values()]):
ordered = OrderedDict()
components = copy(self._cpp_info.components)
while len(ordered) != len(self._cpp_info.components):
# Search next element to be processed
for comp_name, comp in components.items():
# Check if component is not required and can be added to ordered
if comp_name not in [require for dep in components.values() for require in
self._filter_component_requires(dep.requires)]:
ordered[comp_name] = comp
del components[comp_name]
break
else:
raise ConanException("There is a dependency loop in "
"'self.cpp_info.components' requires")
self._sorted_components = ordered
else: # If components do not have requirements, keep them in the same order
self._sorted_components = self._cpp_info.components
return self._sorted_components
@property
def build_modules_paths(self):
return self._aggregated_paths("build_modules")
@property
def include_paths(self):
return self._aggregated_paths("include")
@property
def lib_paths(self):
return self._aggregated_paths("lib")
@property
def src_paths(self):
return self._aggregated_paths("src")
@property
def bin_paths(self):
return self._aggregated_paths("bin")
@property
def build_paths(self):
return self._aggregated_paths("build")
@property
def res_paths(self):
return self._aggregated_paths("res")
@property
def framework_paths(self):
return self._aggregated_paths("framework")
@property
def libs(self):
return self._aggregated_values("libs")
@property
def system_libs(self):
return self._aggregated_values("system_libs")
@property
def frameworks(self):
return self._aggregated_values("frameworks")
@property
def defines(self):
return self._aggregated_values("defines")
@property
def cxxflags(self):
return self._aggregated_values("cxxflags")
@property
def cflags(self):
return self._aggregated_values("cflags")
@property
def sharedlinkflags(self):
return self._aggregated_values("sharedlinkflags")
@property
def exelinkflags(self):
return self._aggregated_values("exelinkflags")
class DepsCppInfo(_BaseDepsCppInfo):
""" Build Information necessary to build a given conans. It contains the
flags, directories and options if its dependencies. The conans CONANFILE
should use these flags to pass them to the underlaying build system (Cmake, make),
so deps info is managed
"""
def __init__(self):
super(DepsCppInfo, self).__init__()
self._dependencies = OrderedDict()
self._configs = {}
def __getattr__(self, config):
return self._configs.setdefault(config, _BaseDepsCppInfo())
@property
def configs(self):
return self._configs
@property
def dependencies(self):
return self._dependencies.items()
@property
def deps(self):
return self._dependencies.keys()
def __getitem__(self, item):
return self._dependencies[item]
def add(self, pkg_name, cpp_info):
assert pkg_name == str(cpp_info), "'{}' != '{}'".format(pkg_name, cpp_info)
assert isinstance(cpp_info, (CppInfo, DepCppInfo))
self._dependencies[pkg_name] = cpp_info
super(DepsCppInfo, self).update(cpp_info)
for config, cpp_info in cpp_info.configs.items():
self._configs.setdefault(config, _BaseDepsCppInfo()).update(cpp_info)
| 36.832143 | 101 | 0.635412 | import os
from collections import OrderedDict
from copy import copy
from conans.errors import ConanException
from conans.util.conan_v2_mode import conan_v2_behavior
DEFAULT_INCLUDE = "include"
DEFAULT_LIB = "lib"
DEFAULT_BIN = "bin"
DEFAULT_RES = "res"
DEFAULT_SHARE = "share"
DEFAULT_BUILD = ""
DEFAULT_FRAMEWORK = "Frameworks"
COMPONENT_SCOPE = "::"
class DefaultOrderedDict(OrderedDict):
def __init__(self, factory):
self.factory = factory
super(DefaultOrderedDict, self).__init__()
def __getitem__(self, key):
if key not in self.keys():
super(DefaultOrderedDict, self).__setitem__(key, self.factory())
super(DefaultOrderedDict, self).__getitem__(key).name = key
return super(DefaultOrderedDict, self).__getitem__(key)
def __copy__(self):
the_copy = DefaultOrderedDict(self.factory)
for key, value in super(DefaultOrderedDict, self).items():
the_copy[key] = value
return the_copy
class _CppInfo(object):
def __init__(self):
self._name = None
self.names = {}
self.system_libs = []
self.includedirs = []
self.srcdirs = []
self.libdirs = []
self.resdirs = []
self.bindirs = []
self.builddirs = []
self.frameworks = []
self.frameworkdirs = []
self.rootpaths = []
self.libs = []
self.defines = []
self.cflags = []
self.cxxflags = []
self.sharedlinkflags = []
self.exelinkflags = []
self.build_modules = []
self.filenames = {}
self.rootpath = ""
self.sysroot = ""
self._build_modules_paths = None
self._include_paths = None
self._lib_paths = None
self._bin_paths = None
self._build_paths = None
self._res_paths = None
self._src_paths = None
self._framework_paths = None
self.version = None
self.description = None
self.filter_empty = True
def _filter_paths(self, paths):
abs_paths = [os.path.join(self.rootpath, p)
if not os.path.isabs(p) else p for p in paths]
if self.filter_empty:
return [p for p in abs_paths if os.path.isdir(p)]
else:
return abs_paths
@property
def build_modules_paths(self):
if self._build_modules_paths is None:
self._build_modules_paths = [os.path.join(self.rootpath, p) if not os.path.isabs(p)
else p for p in self.build_modules]
return self._build_modules_paths
@property
def include_paths(self):
if self._include_paths is None:
self._include_paths = self._filter_paths(self.includedirs)
return self._include_paths
@property
def lib_paths(self):
if self._lib_paths is None:
self._lib_paths = self._filter_paths(self.libdirs)
return self._lib_paths
@property
def src_paths(self):
if self._src_paths is None:
self._src_paths = self._filter_paths(self.srcdirs)
return self._src_paths
@property
def bin_paths(self):
if self._bin_paths is None:
self._bin_paths = self._filter_paths(self.bindirs)
return self._bin_paths
@property
def build_paths(self):
if self._build_paths is None:
self._build_paths = self._filter_paths(self.builddirs)
return self._build_paths
@property
def res_paths(self):
if self._res_paths is None:
self._res_paths = self._filter_paths(self.resdirs)
return self._res_paths
@property
def framework_paths(self):
if self._framework_paths is None:
self._framework_paths = self._filter_paths(self.frameworkdirs)
return self._framework_paths
@property
def name(self):
conan_v2_behavior("Use 'get_name(generator)' instead")
return self._name
@name.setter
def name(self, value):
self._name = value
def get_name(self, generator):
return self.names.get(generator, self._name)
def get_filename(self, generator):
result = self.filenames.get(generator)
if result:
return result
return self.get_name(generator)
def get_cppflags(self):
conan_v2_behavior("'cpp_info.cppflags' is deprecated, use 'cxxflags' instead")
return self.cxxflags
def set_cppflags(self, value):
conan_v2_behavior("'cpp_info.cppflags' is deprecated, use 'cxxflags' instead")
self.cxxflags = value
cppflags = property(get_cppflags, set_cppflags)
class Component(_CppInfo):
def __init__(self, rootpath):
super(Component, self).__init__()
self.rootpath = rootpath
self.includedirs.append(DEFAULT_INCLUDE)
self.libdirs.append(DEFAULT_LIB)
self.bindirs.append(DEFAULT_BIN)
self.resdirs.append(DEFAULT_RES)
self.builddirs.append(DEFAULT_BUILD)
self.frameworkdirs.append(DEFAULT_FRAMEWORK)
self.requires = []
class CppInfo(_CppInfo):
def __init__(self, ref_name, root_folder):
super(CppInfo, self).__init__()
self._ref_name = ref_name
self._name = ref_name
self.rootpath = root_folder
self.includedirs.append(DEFAULT_INCLUDE)
self.libdirs.append(DEFAULT_LIB)
self.bindirs.append(DEFAULT_BIN)
self.resdirs.append(DEFAULT_RES)
self.builddirs.append(DEFAULT_BUILD)
self.frameworkdirs.append(DEFAULT_FRAMEWORK)
self.components = DefaultOrderedDict(lambda: Component(self.rootpath))
self.public_deps = []
self._configs = {}
def __str__(self):
return self._ref_name
def get_name(self, generator):
name = super(CppInfo, self).get_name(generator)
from conans.client.generators.pkg_config import PkgConfigGenerator
if generator == PkgConfigGenerator.name:
fallback = self._name.lower() if self._name != self._ref_name else self._ref_name
if PkgConfigGenerator.name not in self.names and self._name != self._name.lower():
conan_v2_behavior("Generated file and name for {gen} generator will change in"
" Conan v2 to '{name}'. Use 'self.cpp_info.names[\"{gen}\"]"
" = \"{fallback}\"' in your recipe to continue using current name."
.format(gen=PkgConfigGenerator.name, name=name, fallback=fallback))
name = self.names.get(generator, fallback)
return name
@property
def configs(self):
return self._configs
def __getattr__(self, config):
def _get_cpp_info():
result = _CppInfo()
result.filter_empty = self.filter_empty
result.rootpath = self.rootpath
result.sysroot = self.sysroot
result.includedirs.append(DEFAULT_INCLUDE)
result.libdirs.append(DEFAULT_LIB)
result.bindirs.append(DEFAULT_BIN)
result.resdirs.append(DEFAULT_RES)
result.builddirs.append(DEFAULT_BUILD)
result.frameworkdirs.append(DEFAULT_FRAMEWORK)
return result
return self._configs.setdefault(config, _get_cpp_info())
def _raise_incorrect_components_definition(self, package_name, package_requires):
if (self.includedirs != [DEFAULT_INCLUDE] or
self.libdirs != [DEFAULT_LIB] or
self.bindirs != [DEFAULT_BIN] or
self.resdirs != [DEFAULT_RES] or
self.builddirs != [DEFAULT_BUILD] or
self.frameworkdirs != [DEFAULT_FRAMEWORK] or
self.libs or
self.system_libs or
self.frameworks or
self.defines or
self.cflags or
self.cxxflags or
self.sharedlinkflags or
self.exelinkflags or
self.build_modules) and self.components:
raise ConanException("self.cpp_info.components cannot be used with self.cpp_info "
"global values at the same time")
if self._configs and self.components:
raise ConanException("self.cpp_info.components cannot be used with self.cpp_info configs"
" (release/debug/...) at the same time")
for comp_name, comp in self.components.items():
if comp_name == package_name:
raise ConanException("Component name cannot be the same as the package name: '%s'"
% comp_name)
if self.components:
comp_requires = set()
for comp_name, comp in self.components.items():
for comp_require in comp.requires:
if COMPONENT_SCOPE in comp_require:
comp_requires.add(
comp_require[:comp_require.find(COMPONENT_SCOPE)])
pkg_requires = [require.ref.name for require in package_requires.values()]
for pkg_require in pkg_requires:
if pkg_require not in comp_requires:
raise ConanException("Package require '%s' not used in components requires"
% pkg_require)
for comp_require in comp_requires:
if comp_require not in pkg_requires:
raise ConanException("Package require '%s' declared in components requires "
"but not defined as a recipe requirement" % comp_require)
class _BaseDepsCppInfo(_CppInfo):
def __init__(self):
super(_BaseDepsCppInfo, self).__init__()
def update(self, dep_cpp_info):
def merge_lists(seq1, seq2):
return [s for s in seq1 if s not in seq2] + seq2
self.system_libs = merge_lists(self.system_libs, dep_cpp_info.system_libs)
self.includedirs = merge_lists(self.includedirs, dep_cpp_info.include_paths)
self.srcdirs = merge_lists(self.srcdirs, dep_cpp_info.src_paths)
self.libdirs = merge_lists(self.libdirs, dep_cpp_info.lib_paths)
self.bindirs = merge_lists(self.bindirs, dep_cpp_info.bin_paths)
self.resdirs = merge_lists(self.resdirs, dep_cpp_info.res_paths)
self.builddirs = merge_lists(self.builddirs, dep_cpp_info.build_paths)
self.frameworkdirs = merge_lists(self.frameworkdirs, dep_cpp_info.framework_paths)
self.libs = merge_lists(self.libs, dep_cpp_info.libs)
self.frameworks = merge_lists(self.frameworks, dep_cpp_info.frameworks)
self.build_modules = merge_lists(self.build_modules, dep_cpp_info.build_modules_paths)
self.rootpaths.append(dep_cpp_info.rootpath)
self.defines = merge_lists(dep_cpp_info.defines, self.defines)
self.cxxflags = merge_lists(dep_cpp_info.cxxflags, self.cxxflags)
self.cflags = merge_lists(dep_cpp_info.cflags, self.cflags)
self.sharedlinkflags = merge_lists(dep_cpp_info.sharedlinkflags, self.sharedlinkflags)
self.exelinkflags = merge_lists(dep_cpp_info.exelinkflags, self.exelinkflags)
if not self.sysroot:
self.sysroot = dep_cpp_info.sysroot
@property
def build_modules_paths(self):
return self.build_modules
@property
def include_paths(self):
return self.includedirs
@property
def lib_paths(self):
return self.libdirs
@property
def src_paths(self):
return self.srcdirs
@property
def bin_paths(self):
return self.bindirs
@property
def build_paths(self):
return self.builddirs
@property
def res_paths(self):
return self.resdirs
@property
def framework_paths(self):
return self.frameworkdirs
class DepCppInfo(object):
def __init__(self, cpp_info):
self._cpp_info = cpp_info
self._libs = None
self._system_libs = None
self._frameworks = None
self._defines = None
self._cxxflags = None
self._cflags = None
self._sharedlinkflags = None
self._exelinkflags = None
self._include_paths = None
self._lib_paths = None
self._bin_paths = None
self._build_paths = None
self._res_paths = None
self._src_paths = None
self._framework_paths = None
self._build_module_paths = None
self._sorted_components = None
self._check_component_requires()
def __str__(self):
return str(self._cpp_info)
def __getattr__(self, item):
try:
attr = self._cpp_info.__getattribute__(item)
except AttributeError:
attr = self._cpp_info.__getattr__(item)
return attr
@staticmethod
def _merge_lists(seq1, seq2):
return seq1 + [s for s in seq2 if s not in seq1]
def _aggregated_values(self, item):
values = getattr(self, "_%s" % item)
if values is not None:
return values
values = getattr(self._cpp_info, item)
if self._cpp_info.components:
for component in self._get_sorted_components().values():
values = self._merge_lists(values, getattr(component, item))
setattr(self, "_%s" % item, values)
return values
def _aggregated_paths(self, item):
paths = getattr(self, "_%s_paths" % item)
if paths is not None:
return paths
paths = getattr(self._cpp_info, "%s_paths" % item)
if self._cpp_info.components:
for component in self._get_sorted_components().values():
paths = self._merge_lists(paths, getattr(component, "%s_paths" % item))
setattr(self, "_%s_paths" % item, paths)
return paths
@staticmethod
def _filter_component_requires(requires):
return [r for r in requires if COMPONENT_SCOPE not in r]
def _check_component_requires(self):
for comp_name, comp in self._cpp_info.components.items():
if not all([require in self._cpp_info.components for require in
self._filter_component_requires(comp.requires)]):
raise ConanException("Component '%s' declares a missing dependency" % comp_name)
bad_requires = [r for r in comp.requires if r.startswith(COMPONENT_SCOPE)]
if bad_requires:
msg = "Leading character '%s' not allowed in %s requires: %s. Omit it to require " \
"components inside the same package." \
% (COMPONENT_SCOPE, comp_name, bad_requires)
raise ConanException(msg)
def _get_sorted_components(self):
if not self._sorted_components:
if any([[require for require in self._filter_component_requires(comp.requires)]
for comp in self._cpp_info.components.values()]):
ordered = OrderedDict()
components = copy(self._cpp_info.components)
while len(ordered) != len(self._cpp_info.components):
for comp_name, comp in components.items():
if comp_name not in [require for dep in components.values() for require in
self._filter_component_requires(dep.requires)]:
ordered[comp_name] = comp
del components[comp_name]
break
else:
raise ConanException("There is a dependency loop in "
"'self.cpp_info.components' requires")
self._sorted_components = ordered
else:
self._sorted_components = self._cpp_info.components
return self._sorted_components
@property
def build_modules_paths(self):
return self._aggregated_paths("build_modules")
@property
def include_paths(self):
return self._aggregated_paths("include")
@property
def lib_paths(self):
return self._aggregated_paths("lib")
@property
def src_paths(self):
return self._aggregated_paths("src")
@property
def bin_paths(self):
return self._aggregated_paths("bin")
@property
def build_paths(self):
return self._aggregated_paths("build")
@property
def res_paths(self):
return self._aggregated_paths("res")
@property
def framework_paths(self):
return self._aggregated_paths("framework")
@property
def libs(self):
return self._aggregated_values("libs")
@property
def system_libs(self):
return self._aggregated_values("system_libs")
@property
def frameworks(self):
return self._aggregated_values("frameworks")
@property
def defines(self):
return self._aggregated_values("defines")
@property
def cxxflags(self):
return self._aggregated_values("cxxflags")
@property
def cflags(self):
return self._aggregated_values("cflags")
@property
def sharedlinkflags(self):
return self._aggregated_values("sharedlinkflags")
@property
def exelinkflags(self):
return self._aggregated_values("exelinkflags")
class DepsCppInfo(_BaseDepsCppInfo):
def __init__(self):
super(DepsCppInfo, self).__init__()
self._dependencies = OrderedDict()
self._configs = {}
def __getattr__(self, config):
return self._configs.setdefault(config, _BaseDepsCppInfo())
@property
def configs(self):
return self._configs
@property
def dependencies(self):
return self._dependencies.items()
@property
def deps(self):
return self._dependencies.keys()
def __getitem__(self, item):
return self._dependencies[item]
def add(self, pkg_name, cpp_info):
assert pkg_name == str(cpp_info), "'{}' != '{}'".format(pkg_name, cpp_info)
assert isinstance(cpp_info, (CppInfo, DepCppInfo))
self._dependencies[pkg_name] = cpp_info
super(DepsCppInfo, self).update(cpp_info)
for config, cpp_info in cpp_info.configs.items():
self._configs.setdefault(config, _BaseDepsCppInfo()).update(cpp_info)
| true | true |
f7104c814506d615d1761157b853952abbef975d | 4,425 | py | Python | regression/run/arrayclass/python/test.py | ExternalRepositories/shroud | 86c39d2324d947d28055f9024f52cc493eb0c813 | [
"BSD-3-Clause"
] | 73 | 2017-10-11T17:01:50.000Z | 2022-01-01T21:42:12.000Z | regression/run/arrayclass/python/test.py | ExternalRepositories/shroud | 86c39d2324d947d28055f9024f52cc493eb0c813 | [
"BSD-3-Clause"
] | 29 | 2018-03-21T19:34:29.000Z | 2022-02-04T18:13:14.000Z | regression/run/arrayclass/python/test.py | ExternalRepositories/shroud | 86c39d2324d947d28055f9024f52cc493eb0c813 | [
"BSD-3-Clause"
] | 8 | 2017-11-22T14:27:01.000Z | 2022-03-30T08:49:03.000Z | # Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and
# other Shroud Project Developers.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (BSD-3-Clause)
# #######################################################################
#
# Test Python API generated from references.yaml.
#
from __future__ import print_function
import numpy as np
import unittest
import arrayclass
class Arrayclass(unittest.TestCase):
"""Test struct problem"""
def XXsetUp(self):
""" Setting up for the test """
print("FooTest:setUp_:begin")
## do something...
print("FooTest:setUp_:end")
def XXtearDown(self):
"""Cleaning up after the test"""
print("FooTest:tearDown_:begin")
## do something...
print("FooTest:tearDown_:end")
def test_ArrayWrapper(self):
arrinst = arrayclass.ArrayWrapper()
arrinst.setSize(10)
self.assertEqual(10, arrinst.getSize())
isize = arrinst.fillSize()
self.assertEqual(10, isize)
arrinst.allocate()
arr = arrinst.getArray()
self.assertIsInstance(arr, np.ndarray)
self.assertEqual('float64', arr.dtype.name)
self.assertEqual(1, arr.ndim)
self.assertEqual((10,), arr.shape)
self.assertEqual(10, arr.size)
# Make sure we're pointing to the array in the instance.
arr[:] = 0.0
self.assertEqual(0.0, arrinst.sumArray())
arr[:] = 1.0
self.assertEqual(10.0, arrinst.sumArray())
arr[:] = 0.0
arr[0] = 10.0
arr[9] = 1.0
self.assertEqual(11.0, arrinst.sumArray())
arrconst = arrinst.getArrayConst()
self.assertIsInstance(arrconst, np.ndarray)
self.assertEqual('float64', arrconst.dtype.name)
self.assertEqual(1, arrconst.ndim)
self.assertEqual((10,), arrconst.shape)
self.assertEqual(10, arrconst.size)
# Both getArray and getArrayConst return a NumPy array to the
# same pointer. But a new array is created each time.
self.assertIsNot(arr, arrconst)
arr3 = arrinst.getArrayC()
self.assertIsInstance(arr3, np.ndarray)
self.assertEqual('float64', arr3.dtype.name)
self.assertEqual(1, arr3.ndim)
self.assertEqual((10,), arr3.shape)
self.assertEqual(10, arr3.size)
arr4 = arrinst.getArrayConstC()
self.assertIsInstance(arr4, np.ndarray)
self.assertEqual('float64', arr4.dtype.name)
self.assertEqual(1, arr4.ndim)
self.assertEqual((10,), arr4.shape)
self.assertEqual(10, arr4.size)
arr5 = arrinst.fetchArrayPtr()
self.assertIsInstance(arr4, np.ndarray)
self.assertEqual('float64', arr5.dtype.name)
self.assertEqual(1, arr5.ndim)
self.assertEqual((10,), arr5.shape)
self.assertEqual(10, arr5.size)
arr6 = arrinst.fetchArrayRef()
self.assertIsInstance(arr4, np.ndarray)
self.assertEqual('float64', arr6.dtype.name)
self.assertEqual(1, arr6.ndim)
self.assertEqual((10,), arr6.shape)
self.assertEqual(10, arr6.size)
arr7 = arrinst.fetchArrayPtrConst()
self.assertIsInstance(arr4, np.ndarray)
self.assertEqual('float64', arr7.dtype.name)
self.assertEqual(1, arr7.ndim)
self.assertEqual((10,), arr7.shape)
self.assertEqual(10, arr7.size)
arr8 = arrinst.fetchArrayRefConst()
self.assertIsInstance(arr4, np.ndarray)
self.assertEqual('float64', arr8.dtype.name)
self.assertEqual(1, arr8.ndim)
self.assertEqual((10,), arr8.shape)
self.assertEqual(10, arr8.size)
with self.assertRaises(ValueError) as context:
arrinst.checkPtr(None)
self.assertTrue("called with invalid PyCapsule object"
in str(context.exception))
voidptr = arrinst.fetchVoidPtr()
self.assertEqual('PyCapsule', voidptr.__class__.__name__)
self.assertTrue(arrinst.checkPtr(voidptr))
voidptr = arrinst.fetchVoidRef()
self.assertEqual('PyCapsule', voidptr.__class__.__name__)
self.assertTrue(arrinst.checkPtr(voidptr))
# creating a new test suite
newSuite = unittest.TestSuite()
# adding a test case
newSuite.addTest(unittest.makeSuite(Arrayclass))
if __name__ == "__main__":
unittest.main()
| 33.522727 | 73 | 0.629153 |
Equal((10,), arr6.shape)
self.assertEqual(10, arr6.size)
arr7 = arrinst.fetchArrayPtrConst()
self.assertIsInstance(arr4, np.ndarray)
self.assertEqual('float64', arr7.dtype.name)
self.assertEqual(1, arr7.ndim)
self.assertEqual((10,), arr7.shape)
self.assertEqual(10, arr7.size)
arr8 = arrinst.fetchArrayRefConst()
self.assertIsInstance(arr4, np.ndarray)
self.assertEqual('float64', arr8.dtype.name)
self.assertEqual(1, arr8.ndim)
self.assertEqual((10,), arr8.shape)
self.assertEqual(10, arr8.size)
with self.assertRaises(ValueError) as context:
arrinst.checkPtr(None)
self.assertTrue("called with invalid PyCapsule object"
in str(context.exception))
voidptr = arrinst.fetchVoidPtr()
self.assertEqual('PyCapsule', voidptr.__class__.__name__)
self.assertTrue(arrinst.checkPtr(voidptr))
voidptr = arrinst.fetchVoidRef()
self.assertEqual('PyCapsule', voidptr.__class__.__name__)
self.assertTrue(arrinst.checkPtr(voidptr))
# creating a new test suite
newSuite = unittest.TestSuite()
# adding a test case
newSuite.addTest(unittest.makeSuite(Arrayclass))
if __name__ == "__main__":
unittest.main()
| true | true |
f7104cdb14a8ffefb3c373799881a44789831177 | 522 | py | Python | project_version/help.py | dmytrostriletskyi/project-version | c4c29f2e7b633a69eda1f89d022eadff3fe33d41 | [
"MIT"
] | 7 | 2022-01-18T20:12:29.000Z | 2022-01-25T18:04:09.000Z | project_version/help.py | dmytrostriletskyi/project-version | c4c29f2e7b633a69eda1f89d022eadff3fe33d41 | [
"MIT"
] | 3 | 2022-01-29T15:46:46.000Z | 2022-01-29T16:19:40.000Z | project_version/help.py | dmytrostriletskyi/project-version | c4c29f2e7b633a69eda1f89d022eadff3fe33d41 | [
"MIT"
] | null | null | null | """
Provide help message for command line interface commands.
"""
PROVIDER_NAME_HELP = 'A provider of hosting for software development and version control name.'
ORGANIZATION_NAME_HELP = "The provider's organization name."
REPOSITORY_NAME_HELP = "The provider's repository name."
BRANCH = 'A branch.'
BASE_BRANCH = 'A branch to compare a project version with. Usually, a default branch.'
HEAD_BRANCH = 'A branch to get its project version for comparison. Usually, a feature branch.'
PROJECT_VERSION = 'A project version.'
| 47.454545 | 95 | 0.781609 | PROVIDER_NAME_HELP = 'A provider of hosting for software development and version control name.'
ORGANIZATION_NAME_HELP = "The provider's organization name."
REPOSITORY_NAME_HELP = "The provider's repository name."
BRANCH = 'A branch.'
BASE_BRANCH = 'A branch to compare a project version with. Usually, a default branch.'
HEAD_BRANCH = 'A branch to get its project version for comparison. Usually, a feature branch.'
PROJECT_VERSION = 'A project version.'
| true | true |
f7104d2f9d9499f3cf55c7355a54c7358562d6b1 | 1,015 | py | Python | examples/classify_names/rough_work.py | huangruizhe/espresso | ee658bcc959bfbe8a7a61d7374d532d082d2aa26 | [
"MIT"
] | null | null | null | examples/classify_names/rough_work.py | huangruizhe/espresso | ee658bcc959bfbe8a7a61d7374d532d082d2aa26 | [
"MIT"
] | null | null | null | examples/classify_names/rough_work.py | huangruizhe/espresso | ee658bcc959bfbe8a7a61d7374d532d082d2aa26 | [
"MIT"
] | null | null | null | # Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
import numpy as np
list_a = []
for i in range(2):
for j in range(5):
list_a.append(i)
list_a = np.random.permutation(list_a)
print('class labels')
print(list_a)
list_a = np.array(list_a)
index_i = 0
classid_of_index0=list_a[index_i]
print('class_of_index0: ', classid_of_index0)
classid_of_index0_locations = np.where(list_a == classid_of_index0)
classid_of_index0_locations = classid_of_index0_locations[0]
print('class_of_index0_locations', classid_of_index0_locations)
print(classid_of_index0_locations != index_i)
same_index_list = classid_of_index0_locations[classid_of_index0_locations != index_i]
print(same_index_list)
print(same_index_list[0:2])
num_tokens_vec = [5,6,7,5,4,3,5,4,6,7]
for pos in same_index_list[0:2]:
print(num_tokens_vec[pos])
max_val = tuple(num_tokens_vec[pos] for pos in same_index_list[0:2])
max_val1 = max(max_val)
print(max_val)
print(max_val1)
| 30.757576 | 85 | 0.782266 |
import numpy as np
list_a = []
for i in range(2):
for j in range(5):
list_a.append(i)
list_a = np.random.permutation(list_a)
print('class labels')
print(list_a)
list_a = np.array(list_a)
index_i = 0
classid_of_index0=list_a[index_i]
print('class_of_index0: ', classid_of_index0)
classid_of_index0_locations = np.where(list_a == classid_of_index0)
classid_of_index0_locations = classid_of_index0_locations[0]
print('class_of_index0_locations', classid_of_index0_locations)
print(classid_of_index0_locations != index_i)
same_index_list = classid_of_index0_locations[classid_of_index0_locations != index_i]
print(same_index_list)
print(same_index_list[0:2])
num_tokens_vec = [5,6,7,5,4,3,5,4,6,7]
for pos in same_index_list[0:2]:
print(num_tokens_vec[pos])
max_val = tuple(num_tokens_vec[pos] for pos in same_index_list[0:2])
max_val1 = max(max_val)
print(max_val)
print(max_val1)
| true | true |
f7104d4af3e8e0b0704eb63303567f70590746a2 | 16,667 | py | Python | calipy/viewer.py | jaedong27/calipy | ed5b5af2654b2a25e16af4267683cafc83d72729 | [
"MIT"
] | 1 | 2020-02-17T10:50:41.000Z | 2020-02-17T10:50:41.000Z | calipy/viewer.py | jaedong27/calipy | ed5b5af2654b2a25e16af4267683cafc83d72729 | [
"MIT"
] | 1 | 2020-02-17T10:51:27.000Z | 2020-02-17T10:51:27.000Z | calipy/viewer.py | jaedong27/calipy | ed5b5af2654b2a25e16af4267683cafc83d72729 | [
"MIT"
] | null | null | null | import vtk
from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
import math
import numpy as np
import numpy.matlib
import os
import json
import cv2
# Z
# /
# /
# /
# ---------- X
# |
# |
# |
# Y
class vtkRenderer():
def __init__(self, widget=None):
self.ren = vtk.vtkRenderer()
if widget is not None:
# Qt Widget Mode
self.qtwidget_mode = True
#### Init
# self.vtkWidget = QVTKRenderWindowInteractor(self.centralwidget)
# self.vtkWidget.setGeometry(0,0,200,200)
# self.vtkRenderer = calipy.vtkRenderer(self.vtkWidget)
# Qt Widget
self.vtkWidget = widget
self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
self.iren.Initialize()
self.iren.Start()
else:
# Window Mode
self.qtwidget_mode = False
# Make empty window
self.renWin = vtk.vtkRenderWindow()
self.renWin.AddRenderer(self.ren)
self.renWin.SetSize(960, 540)
self.iren = vtk.vtkRenderWindowInteractor()
self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
self.iren.SetRenderWindow(self.renWin)
self.iren.Initialize()
self.ren.SetBackground(0, 0.1, 0)
self.actor_list = {}
axes = vtk.vtkAxesActor()
self.ren.AddActor(axes)
self.actor_list["axes"] = axes
self.ren.ResetCamera()
self.iren.AddObserver('LeftButtonPressEvent', self.pushLeftButtonPressEventOnVTK, 1.0)
# Add Event for get Position
def pushLeftButtonPressEventOnVTK(self, obj, ev):
clickPos = self.iren.GetEventPosition()
#print(clickPos)
picker = vtk.vtkPropPicker()
picker.Pick(clickPos[0], clickPos[1], 0, self.ren)
print(picker.GetPickPosition())
def setMainCamera(self, R = np.eye(3), t = np.zeros((3,1)), fov = 80):
camera = vtk.vtkCamera()
camera.SetPosition(t[0,0],t[1,0],t[2,0])
#camera.SetFocalPoint(0,1,0)
focalpoint = np.array([[0],[0],[1]])
focalpoint = np.dot(R,focalpoint) + t
camera.SetFocalPoint(focalpoint[0],focalpoint[1],focalpoint[2])
ref = np.array([[0],[-1],[0]])
cam_up = np.dot(R, ref)
#camera.SetPosition(0,1,0)
#camera.SetViewUp(0,1,0)
camera.SetViewUp(cam_up[0],cam_up[1],cam_up[2])
camera.SetViewAngle(fov)
self.ren.SetActiveCamera(camera)
def setMainCameraToSeeTarget(self, t = np.zeros((3,1)), target = np.zeros((3,1)), fov = 80):
camera = vtk.vtkCamera()
camera.SetPosition(t[0,0],t[1,0],t[2,0])
#print("Position :", t)
#camera.SetFocalPoint(0,1,0)
#focalpoint = np.array([[0],[0],[1]])
#focalpoint = np.dot(R,focalpoint) + t
target_focalpoint = (target - t).ravel()
#print(target_focalpoint)
target_focalpoint = target_focalpoint / np.linalg.norm(target_focalpoint)
#print("focalpoint", target)
camera.SetFocalPoint(target[0],target[1],target[2])
ref = np.array([[0],[-1],[0]]).ravel()
#print(focalpoint, ref)
ref_right = np.cross(target_focalpoint, ref)
ref_right = ref_right / np.linalg.norm(ref_right)
#print(ref_right, focalpoint)
cam_up = np.cross(ref_right, target_focalpoint)
cam_up = cam_up / np.linalg.norm(cam_up)
print("Up",cam_up)
#cam_up = np.dot(R, ref)
#camera.SetPosition(0,1,0)
#camera.SetViewUp(0,1,0)
camera.SetViewUp(cam_up[0],cam_up[1],cam_up[2])
camera.SetViewAngle(fov)
self.ren.SetActiveCamera(camera)
def getActorList(self):
return self.actor_list.keys()
def removeActorByName(self, name):
#print(self.actor_list)
if name in self.actor_list.keys():
actor = self.actor_list.pop(name)
self.ren.RemoveActor(actor)
#print("remove! ", name)
def addText(self, name, text, pos_x, pos_y):
self.removeActorByName(name)
textActor = vtk.vtkTextActor()
textActor.SetInput( text )
textActor.SetPosition( pos_x, pos_y )
textActor.GetTextProperty().SetFontSize ( 50 )
textActor.GetTextProperty().SetColor ( 1.0, 1.0, 1.0 )
self.ren.AddActor2D(textActor)
self.actor_list[name] = textActor
def addPlane(self, name, point1, point2, point3, color=np.array([255.0,255.0,255.0]), opacity=1.0):
self.removeActorByName(name)
# Create a plane
planeSource = vtk.vtkPlaneSource()
# planeSource.SetOrigin(center_point[0], center_point[1], center_point[2])
# #planeSource.SetNormal(normal_vector[0], normal_vector[1], normal_vector[2])
# #print(dir(planeSource))
# planeSource.SetPoint1(top_left_point[0], top_left_point[1], top_left_point[2])
# planeSource.SetPoint2(bot_right_point[0], bot_right_point[1], bot_right_point[2])
# planeSource.SetXResolution(10)
# planeSource.SetYResolution(340)
planeSource.SetOrigin(point1[0], point1[1], point1[2])
planeSource.SetPoint1(point2[0], point2[1], point2[2])
planeSource.SetPoint2(point3[0], point3[1], point3[2])
planeSource.SetXResolution(10)
planeSource.SetYResolution(340)
planeSource.Update()
plane = planeSource.GetOutput()
# Create a mapper and actor
polygonMapper = vtk.vtkPolyDataMapper()
if vtk.VTK_MAJOR_VERSION <= 5:
polygonMapper.SetInputConnection(polygon.GetProducerPort())
else:
polygonMapper.SetInputData(plane)
polygonMapper.Update()
polygonActor = vtk.vtkActor()
polygonActor.SetMapper(polygonMapper)
polygonActor.GetProperty().SetColor([color[0],color[1],color[2]])
polygonActor.GetProperty().SetOpacity(opacity)
#actor.GetProperty().SetColor(colors->GetColor3d("Cyan").GetData());
self.ren.AddActor(polygonActor)
self.actor_list[name] = polygonActor
def addPlanWithTexture(self, name, point1, point2, point3, path, opacity=1.0):
self.removeActorByName(name)
#png_file = vtk.vtkPNGReader()
#print(png_file.CanReadFile(path))
# Read the image which will be the texture
#vtkSmartPointer<vtkJPEGReader> jPEGReader = vtkSmartPointer<vtkJPEGReader>::New();
#jPEGReader->SetFileName ( inputFilename.c_str() );
img = vtk.vtkJPEGReader()
img.SetFileName(path)
#print(img.CanReadFile(path))
#print(path)
# Create a plane
#vtkSmartPointer<vtkPlaneSource> plane = vtkSmartPointer<vtkPlaneSource>::New();
#plane->SetCenter(0.0, 0.0, 0.0);
#plane->SetNormal(0.0, 0.0, 1.0);
plane = vtk.vtkPlaneSource()
# planeSource.SetOrigin(center_point[0], center_point[1], center_point[2])
# #planeSource.SetNormal(normal_vector[0], normal_vector[1], normal_vector[2])
# #print(dir(planeSource))
# planeSource.SetPoint1(top_left_point[0], top_left_point[1], top_left_point[2])
# planeSource.SetPoint2(bot_right_point[0], bot_right_point[1], bot_right_point[2])
# planeSource.SetXResolution(10)
# planeSource.SetYResolution(340)
#plane.SetCenter(0.0,0.0,0.0)
#plane.SetNormal(0.0,0.0,1.0)
plane.SetOrigin(point1[0], point1[1], point1[2])
plane.SetPoint1(point2[0], point2[1], point2[2])
plane.SetPoint2(point3[0], point3[1], point3[2])
plane.SetXResolution(1920)
plane.SetYResolution(1080)
# Apply the texture
#vtkSmartPointer<vtkTexture> texture = vtkSmartPointer<vtkTexture>::New();
#texture->SetInputConnection(jPEGReader->GetOutputPort());
texture = vtk.vtkTexture()
texture.SetInputConnection(img.GetOutputPort())
#vtkSmartPointer<vtkTextureMapToPlane> texturePlane = vtkSmartPointer<vtkTextureMapToPlane>::New();
#texturePlane->SetInputConnection(plane->GetOutputPort());
texturePlane = vtk.vtkTextureMapToPlane()
texturePlane.SetInputConnection(plane.GetOutputPort())
#planeSource.Update()
#plane = planeSource.GetOutput()
#vtkSmartPointer<vtkPolyDataMapper> planeMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
#planeMapper->SetInputConnection(texturePlane->GetOutputPort());
planeMapper = vtk.vtkPolyDataMapper()
planeMapper.SetInputConnection(texturePlane.GetOutputPort())
#vtkSmartPointer<vtkActor> texturedPlane = vtkSmartPointer<vtkActor>::New();
#texturedPlane->SetMapper(planeMapper);
#texturedPlane->SetTexture(texture);
texturedPlane = vtk.vtkActor()
texturedPlane.SetMapper(planeMapper)
texturedPlane.SetTexture(texture)
# Create a mapper and actor
#polygonMapper = vtk.vtkPolyDataMapper()
#if vtk.VTK_MAJOR_VERSION <= 5:
# polygonMapper.SetInputConnection(texturePlane.GetProducePort())
#else:
# polygonMapper.SetInputData(texturePlane.GetOutput())
# polygonMapper.Update()
#polygonActor = vtk.vtkActor()
#polygonActor.SetMapper(polygonMapper)
#polygonActor.SetTexture(texture)
#polygonActor.GetProperty().SetColor([color[0],color[1],color[2]])
#polygonActor.GetProperty().SetOpacity(opacity)
#actor.GetProperty().SetColor(colors->GetColor3d("Cyan").GetData());
self.ren.AddActor(texturedPlane)
self.actor_list[name] = texturedPlane
def addLines(self, name, points, idx_list = None, line_width = 1, color=np.array([255.0,255.0,255.0])): # points => numpy vector [3, 0~n]
self.removeActorByName(name)
vtkpoints = vtk.vtkPoints()
vtklines = vtk.vtkCellArray()
colors = vtk.vtkUnsignedCharArray()
colors.SetNumberOfComponents(3)
points_size = points.shape[0]
vtkpoints.SetNumberOfPoints(points_size)
for idx, point in enumerate(points):
vtkpoints.SetPoint(idx, point[0], point[1], point[2])
colors.InsertNextTuple(color)
colors.SetName(name+"_colors")
if idx_list is None:
vtklines.InsertNextCell(points_size)
for idx in range(points_size):
vtklines.InsertCellPoint(idx)
else:
vtklines.InsertNextCell(len(idx_list))
for idx in idx_list:
vtklines.InsertCellPoint(idx)
polygon = vtk.vtkPolyData()
polygon.SetPoints(vtkpoints)
polygon.SetLines(vtklines)
polygon.GetCellData().SetScalars(colors)
polygonMapper = vtk.vtkPolyDataMapper()
if vtk.VTK_MAJOR_VERSION <= 5:
polygonMapper.SetInputConnection(polygon.GetProducerPort())
else:
polygonMapper.SetInputData(polygon)
polygonMapper.Update()
polygonActor = vtk.vtkActor()
polygonActor.SetMapper(polygonMapper)
polygonActor.GetProperty().SetLineWidth(line_width)
self.ren.AddActor(polygonActor)
self.actor_list[name] = polygonActor
def addCamera(self, name, R = np.eye(3), t = np.zeros((3,1)), cs = 0.1, line_width = 2, color=np.array([255,255,255])):
self.removeActorByName(name)
camera_points = np.zeros((12,3))
camera_points[0,:] = np.array([-cs/2, -cs/2, cs])
camera_points[1] = np.array([ cs/2, -cs/2, cs])
camera_points[2] = np.array([-cs/2, cs/2, cs])
camera_points[3] = np.array([ cs/2, cs/2, cs])
camera_points[4] = np.array([-cs/4, -cs/4, cs/2])
camera_points[5] = np.array([ cs/4, -cs/4, cs/2])
camera_points[6] = np.array([-cs/4, cs/4, cs/2])
camera_points[7] = np.array([ cs/4, cs/4, cs/2])
camera_points[8] = np.array([-cs/4, -cs/4, 0])
camera_points[9] = np.array([ cs/4, -cs/4, 0])
camera_points[10] = np.array([-cs/4, cs/4, 0])
camera_points[11] = np.array([ cs/4, cs/4, 0])
camera_points = np.transpose(camera_points)
camera_points = np.dot(R, camera_points) + np.matlib.repmat(t, 1, camera_points.shape[1])
camera_points = np.transpose(camera_points)
points = vtk.vtkPoints()
points.SetNumberOfPoints(12)
colors = vtk.vtkUnsignedCharArray()
points.SetNumberOfPoints(12)
colors.SetNumberOfComponents(3)
for idx, point in enumerate(camera_points):
points.SetPoint(idx, point[0], point[1], point[2])
colors.InsertNextTuple(color)
colors.SetName(name+"_colors")
lines = vtk.vtkCellArray()
lines.InsertNextCell(24)
lines.InsertCellPoint(0)
lines.InsertCellPoint(1)
lines.InsertCellPoint(3)
lines.InsertCellPoint(2)
lines.InsertCellPoint(0)
lines.InsertCellPoint(4)
lines.InsertCellPoint(5)
lines.InsertCellPoint(7)
lines.InsertCellPoint(6)
lines.InsertCellPoint(4)
lines.InsertCellPoint(8)
lines.InsertCellPoint(9)
lines.InsertCellPoint(11)
lines.InsertCellPoint(10)
lines.InsertCellPoint(8)
lines.InsertCellPoint(9)
lines.InsertCellPoint(5)
lines.InsertCellPoint(1)
lines.InsertCellPoint(3)
lines.InsertCellPoint(7)
lines.InsertCellPoint(11)
lines.InsertCellPoint(10)
lines.InsertCellPoint(6)
lines.InsertCellPoint(2)
polygon = vtk.vtkPolyData()
polygon.SetPoints(points)
polygon.SetLines(lines)
polygon.GetCellData().SetScalars(colors)
polygonMapper = vtk.vtkPolyDataMapper()
if vtk.VTK_MAJOR_VERSION <= 5:
polygonMapper.SetInputConnection(polygon.GetProducerPort())
else:
polygonMapper.SetInputData(polygon)
polygonMapper.Update()
polygonActor = vtk.vtkActor()
polygonActor.SetMapper(polygonMapper)
polygonActor.GetProperty().SetPointSize(0.1)
polygonActor.GetProperty().SetLineWidth(line_width)
self.ren.AddActor(polygonActor)
self.actor_list[name] = polygonActor
def drawPoints(self, name, point_list, input_color=np.array([[255,0,0]]), point_size = 2):
self.removeActorByName(name)
points = vtk.vtkPoints()
vertices = vtk.vtkCellArray()
colors = vtk.vtkUnsignedCharArray()
colors.SetNumberOfComponents(3)
#colors.SetName("Colors")
#colors.SetNumberOfComponents(3)
if input_color.shape[0] == 1:
color_list = np.ones(point_list.shape) * input_color[0]
else:
color_list = input_color
for point, color in zip(point_list, color_list):
id = points.InsertNextPoint(point.tolist())
vertices.InsertNextCell(1)
vertices.InsertCellPoint(id)
colors.InsertNextTuple(color)
point = vtk.vtkPolyData()
# Set the points and vertices we created as the geometry and topology of the polydata
point.SetPoints(points)
point.SetVerts(vertices)
point.GetPointData().SetScalars(colors)
polygonMapper = vtk.vtkPolyDataMapper()
if vtk.VTK_MAJOR_VERSION <= 5:
polygonMapper.SetInputConnection(ps.GetProducerPort())
else:
polygonMapper.SetInputData(point)
polygonMapper.Update()
polygonActor = vtk.vtkActor()
polygonActor.SetMapper(polygonMapper)
polygonActor.GetProperty().SetPointSize(point_size)
self.ren.AddActor(polygonActor)
self.actor_list[name] = polygonActor
def render(self):
self.iren.Render()
if self.qtwidget_mode == False:
self.iren.Start()
if __name__ == "__main__":
window_width = 1.18
window_height = 0.75
window_points = [[-window_width/2, -window_height*math.cos((5.0/180.0) * math.pi), -window_height*math.sin((5.0/180.0) * math.pi)],
[ window_width/2, -window_height*math.cos((5.0/180.0) * math.pi), -window_height*math.sin((5.0/180.0) * math.pi)],
[-window_width/2, 0, 0],
[ window_width/2, 0, 0]]
index = np.array([0,1,3,2,0])
ren = vtkRenderer()
ren.addLines(np.transpose(window_points), index)
ren.showImage() | 39.032787 | 141 | 0.628427 | import vtk
from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
import math
import numpy as np
import numpy.matlib
import os
import json
import cv2
class vtkRenderer():
def __init__(self, widget=None):
self.ren = vtk.vtkRenderer()
if widget is not None:
self.qtwidget_mode = True
self.vtkWidget = widget
self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
self.iren.Initialize()
self.iren.Start()
else:
self.qtwidget_mode = False
self.renWin = vtk.vtkRenderWindow()
self.renWin.AddRenderer(self.ren)
self.renWin.SetSize(960, 540)
self.iren = vtk.vtkRenderWindowInteractor()
self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
self.iren.SetRenderWindow(self.renWin)
self.iren.Initialize()
self.ren.SetBackground(0, 0.1, 0)
self.actor_list = {}
axes = vtk.vtkAxesActor()
self.ren.AddActor(axes)
self.actor_list["axes"] = axes
self.ren.ResetCamera()
self.iren.AddObserver('LeftButtonPressEvent', self.pushLeftButtonPressEventOnVTK, 1.0)
def pushLeftButtonPressEventOnVTK(self, obj, ev):
clickPos = self.iren.GetEventPosition()
picker = vtk.vtkPropPicker()
picker.Pick(clickPos[0], clickPos[1], 0, self.ren)
print(picker.GetPickPosition())
def setMainCamera(self, R = np.eye(3), t = np.zeros((3,1)), fov = 80):
camera = vtk.vtkCamera()
camera.SetPosition(t[0,0],t[1,0],t[2,0])
focalpoint = np.array([[0],[0],[1]])
focalpoint = np.dot(R,focalpoint) + t
camera.SetFocalPoint(focalpoint[0],focalpoint[1],focalpoint[2])
ref = np.array([[0],[-1],[0]])
cam_up = np.dot(R, ref)
camera.SetViewUp(cam_up[0],cam_up[1],cam_up[2])
camera.SetViewAngle(fov)
self.ren.SetActiveCamera(camera)
def setMainCameraToSeeTarget(self, t = np.zeros((3,1)), target = np.zeros((3,1)), fov = 80):
camera = vtk.vtkCamera()
camera.SetPosition(t[0,0],t[1,0],t[2,0])
target_focalpoint = (target - t).ravel()
target_focalpoint = target_focalpoint / np.linalg.norm(target_focalpoint)
camera.SetFocalPoint(target[0],target[1],target[2])
ref = np.array([[0],[-1],[0]]).ravel()
ref_right = np.cross(target_focalpoint, ref)
ref_right = ref_right / np.linalg.norm(ref_right)
cam_up = np.cross(ref_right, target_focalpoint)
cam_up = cam_up / np.linalg.norm(cam_up)
print("Up",cam_up)
camera.SetViewUp(cam_up[0],cam_up[1],cam_up[2])
camera.SetViewAngle(fov)
self.ren.SetActiveCamera(camera)
def getActorList(self):
return self.actor_list.keys()
def removeActorByName(self, name):
if name in self.actor_list.keys():
actor = self.actor_list.pop(name)
self.ren.RemoveActor(actor)
def addText(self, name, text, pos_x, pos_y):
self.removeActorByName(name)
textActor = vtk.vtkTextActor()
textActor.SetInput( text )
textActor.SetPosition( pos_x, pos_y )
textActor.GetTextProperty().SetFontSize ( 50 )
textActor.GetTextProperty().SetColor ( 1.0, 1.0, 1.0 )
self.ren.AddActor2D(textActor)
self.actor_list[name] = textActor
def addPlane(self, name, point1, point2, point3, color=np.array([255.0,255.0,255.0]), opacity=1.0):
self.removeActorByName(name)
planeSource = vtk.vtkPlaneSource()
int1[2])
planeSource.SetPoint1(point2[0], point2[1], point2[2])
planeSource.SetPoint2(point3[0], point3[1], point3[2])
planeSource.SetXResolution(10)
planeSource.SetYResolution(340)
planeSource.Update()
plane = planeSource.GetOutput()
polygonMapper = vtk.vtkPolyDataMapper()
if vtk.VTK_MAJOR_VERSION <= 5:
polygonMapper.SetInputConnection(polygon.GetProducerPort())
else:
polygonMapper.SetInputData(plane)
polygonMapper.Update()
polygonActor = vtk.vtkActor()
polygonActor.SetMapper(polygonMapper)
polygonActor.GetProperty().SetColor([color[0],color[1],color[2]])
polygonActor.GetProperty().SetOpacity(opacity)
self.ren.AddActor(polygonActor)
self.actor_list[name] = polygonActor
def addPlanWithTexture(self, name, point1, point2, point3, path, opacity=1.0):
self.removeActorByName(name)
img = vtk.vtkJPEGReader()
img.SetFileName(path)
plane = vtk.vtkPlaneSource()
oint1[1], point1[2])
plane.SetPoint1(point2[0], point2[1], point2[2])
plane.SetPoint2(point3[0], point3[1], point3[2])
plane.SetXResolution(1920)
plane.SetYResolution(1080)
texture = vtk.vtkTexture()
texture.SetInputConnection(img.GetOutputPort())
texturePlane = vtk.vtkTextureMapToPlane()
texturePlane.SetInputConnection(plane.GetOutputPort())
planeMapper = vtk.vtkPolyDataMapper()
planeMapper.SetInputConnection(texturePlane.GetOutputPort())
texturedPlane = vtk.vtkActor()
texturedPlane.SetMapper(planeMapper)
texturedPlane.SetTexture(texture)
self.ren.AddActor(texturedPlane)
self.actor_list[name] = texturedPlane
def addLines(self, name, points, idx_list = None, line_width = 1, color=np.array([255.0,255.0,255.0])):
self.removeActorByName(name)
vtkpoints = vtk.vtkPoints()
vtklines = vtk.vtkCellArray()
colors = vtk.vtkUnsignedCharArray()
colors.SetNumberOfComponents(3)
points_size = points.shape[0]
vtkpoints.SetNumberOfPoints(points_size)
for idx, point in enumerate(points):
vtkpoints.SetPoint(idx, point[0], point[1], point[2])
colors.InsertNextTuple(color)
colors.SetName(name+"_colors")
if idx_list is None:
vtklines.InsertNextCell(points_size)
for idx in range(points_size):
vtklines.InsertCellPoint(idx)
else:
vtklines.InsertNextCell(len(idx_list))
for idx in idx_list:
vtklines.InsertCellPoint(idx)
polygon = vtk.vtkPolyData()
polygon.SetPoints(vtkpoints)
polygon.SetLines(vtklines)
polygon.GetCellData().SetScalars(colors)
polygonMapper = vtk.vtkPolyDataMapper()
if vtk.VTK_MAJOR_VERSION <= 5:
polygonMapper.SetInputConnection(polygon.GetProducerPort())
else:
polygonMapper.SetInputData(polygon)
polygonMapper.Update()
polygonActor = vtk.vtkActor()
polygonActor.SetMapper(polygonMapper)
polygonActor.GetProperty().SetLineWidth(line_width)
self.ren.AddActor(polygonActor)
self.actor_list[name] = polygonActor
def addCamera(self, name, R = np.eye(3), t = np.zeros((3,1)), cs = 0.1, line_width = 2, color=np.array([255,255,255])):
self.removeActorByName(name)
camera_points = np.zeros((12,3))
camera_points[0,:] = np.array([-cs/2, -cs/2, cs])
camera_points[1] = np.array([ cs/2, -cs/2, cs])
camera_points[2] = np.array([-cs/2, cs/2, cs])
camera_points[3] = np.array([ cs/2, cs/2, cs])
camera_points[4] = np.array([-cs/4, -cs/4, cs/2])
camera_points[5] = np.array([ cs/4, -cs/4, cs/2])
camera_points[6] = np.array([-cs/4, cs/4, cs/2])
camera_points[7] = np.array([ cs/4, cs/4, cs/2])
camera_points[8] = np.array([-cs/4, -cs/4, 0])
camera_points[9] = np.array([ cs/4, -cs/4, 0])
camera_points[10] = np.array([-cs/4, cs/4, 0])
camera_points[11] = np.array([ cs/4, cs/4, 0])
camera_points = np.transpose(camera_points)
camera_points = np.dot(R, camera_points) + np.matlib.repmat(t, 1, camera_points.shape[1])
camera_points = np.transpose(camera_points)
points = vtk.vtkPoints()
points.SetNumberOfPoints(12)
colors = vtk.vtkUnsignedCharArray()
points.SetNumberOfPoints(12)
colors.SetNumberOfComponents(3)
for idx, point in enumerate(camera_points):
points.SetPoint(idx, point[0], point[1], point[2])
colors.InsertNextTuple(color)
colors.SetName(name+"_colors")
lines = vtk.vtkCellArray()
lines.InsertNextCell(24)
lines.InsertCellPoint(0)
lines.InsertCellPoint(1)
lines.InsertCellPoint(3)
lines.InsertCellPoint(2)
lines.InsertCellPoint(0)
lines.InsertCellPoint(4)
lines.InsertCellPoint(5)
lines.InsertCellPoint(7)
lines.InsertCellPoint(6)
lines.InsertCellPoint(4)
lines.InsertCellPoint(8)
lines.InsertCellPoint(9)
lines.InsertCellPoint(11)
lines.InsertCellPoint(10)
lines.InsertCellPoint(8)
lines.InsertCellPoint(9)
lines.InsertCellPoint(5)
lines.InsertCellPoint(1)
lines.InsertCellPoint(3)
lines.InsertCellPoint(7)
lines.InsertCellPoint(11)
lines.InsertCellPoint(10)
lines.InsertCellPoint(6)
lines.InsertCellPoint(2)
polygon = vtk.vtkPolyData()
polygon.SetPoints(points)
polygon.SetLines(lines)
polygon.GetCellData().SetScalars(colors)
polygonMapper = vtk.vtkPolyDataMapper()
if vtk.VTK_MAJOR_VERSION <= 5:
polygonMapper.SetInputConnection(polygon.GetProducerPort())
else:
polygonMapper.SetInputData(polygon)
polygonMapper.Update()
polygonActor = vtk.vtkActor()
polygonActor.SetMapper(polygonMapper)
polygonActor.GetProperty().SetPointSize(0.1)
polygonActor.GetProperty().SetLineWidth(line_width)
self.ren.AddActor(polygonActor)
self.actor_list[name] = polygonActor
def drawPoints(self, name, point_list, input_color=np.array([[255,0,0]]), point_size = 2):
self.removeActorByName(name)
points = vtk.vtkPoints()
vertices = vtk.vtkCellArray()
colors = vtk.vtkUnsignedCharArray()
colors.SetNumberOfComponents(3)
if input_color.shape[0] == 1:
color_list = np.ones(point_list.shape) * input_color[0]
else:
color_list = input_color
for point, color in zip(point_list, color_list):
id = points.InsertNextPoint(point.tolist())
vertices.InsertNextCell(1)
vertices.InsertCellPoint(id)
colors.InsertNextTuple(color)
point = vtk.vtkPolyData()
point.SetPoints(points)
point.SetVerts(vertices)
point.GetPointData().SetScalars(colors)
polygonMapper = vtk.vtkPolyDataMapper()
if vtk.VTK_MAJOR_VERSION <= 5:
polygonMapper.SetInputConnection(ps.GetProducerPort())
else:
polygonMapper.SetInputData(point)
polygonMapper.Update()
polygonActor = vtk.vtkActor()
polygonActor.SetMapper(polygonMapper)
polygonActor.GetProperty().SetPointSize(point_size)
self.ren.AddActor(polygonActor)
self.actor_list[name] = polygonActor
def render(self):
self.iren.Render()
if self.qtwidget_mode == False:
self.iren.Start()
if __name__ == "__main__":
window_width = 1.18
window_height = 0.75
window_points = [[-window_width/2, -window_height*math.cos((5.0/180.0) * math.pi), -window_height*math.sin((5.0/180.0) * math.pi)],
[ window_width/2, -window_height*math.cos((5.0/180.0) * math.pi), -window_height*math.sin((5.0/180.0) * math.pi)],
[-window_width/2, 0, 0],
[ window_width/2, 0, 0]]
index = np.array([0,1,3,2,0])
ren = vtkRenderer()
ren.addLines(np.transpose(window_points), index)
ren.showImage() | true | true |
f7104d857d6a0526aa83bfe43b03b59f697ae241 | 1,653 | py | Python | setup.py | DiegoHeer/QuickFSScraping | cd0622eb56a9b3bee13dd3c8960a1c95e2c2443e | [
"MIT"
] | 1 | 2021-01-19T09:15:06.000Z | 2021-01-19T09:15:06.000Z | setup.py | DiegoHeer/QuickFSScraping | cd0622eb56a9b3bee13dd3c8960a1c95e2c2443e | [
"MIT"
] | null | null | null | setup.py | DiegoHeer/QuickFSScraping | cd0622eb56a9b3bee13dd3c8960a1c95e2c2443e | [
"MIT"
] | 1 | 2021-01-19T10:04:29.000Z | 2021-01-19T10:04:29.000Z | from distutils.core import setup
from setuptools import find_packages
import os
# User-friendly description from README.md
current_directory = os.path.dirname(os.path.abspath(__file__))
package_name = os.path.basename(current_directory)
try:
with open(os.path.join(current_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
except Exception:
long_description = ''
setup(
# Name of the package
name=package_name,
# Packages to include into the distribution
packages=find_packages(','),
# Start with a small number and increase it with
# every change you make https://semver.org
version='0.0.1',
# Chose a license from here: https: //
# help.github.com / articles / licensing - a -
# repository. For example: MIT
license='MIT',
# Short description of your library
description='A package to scrape financial data using tickers from the QuickFS website',
# Long description of your library
long_description=long_description,
long_description_content_type='text/markdown',
# Your name
author='Diego Heer',
# Your email
author_email='diegojonathanheer@gmail.com',
# Either the link to your github or to your website
url=r'www.github.com/DiegoHeer',
# List of keywords
keywords=['Stocks', 'Financial Analysis', 'Rule #1'],
# List of packages to install with this one
install_requires=[],
# https://pypi.org/classifiers/
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent"
],
zip_safe=False
)
| 33.734694 | 92 | 0.69026 | from distutils.core import setup
from setuptools import find_packages
import os
current_directory = os.path.dirname(os.path.abspath(__file__))
package_name = os.path.basename(current_directory)
try:
with open(os.path.join(current_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
except Exception:
long_description = ''
setup(
name=package_name,
packages=find_packages(','),
version='0.0.1',
license='MIT',
description='A package to scrape financial data using tickers from the QuickFS website',
long_description=long_description,
long_description_content_type='text/markdown',
author='Diego Heer',
author_email='diegojonathanheer@gmail.com',
url=r'www.github.com/DiegoHeer',
keywords=['Stocks', 'Financial Analysis', 'Rule #1'],
install_requires=[],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent"
],
zip_safe=False
)
| true | true |
f7104e042a9381fe9862f42a9135c2bac0fc99aa | 14,268 | py | Python | cdippy/stndata.py | wdar/cdippy | ef38b3445351ec8d9d7ea30b5b0d15825d794b0b | [
"BSD-3-Clause"
] | null | null | null | cdippy/stndata.py | wdar/cdippy | ef38b3445351ec8d9d7ea30b5b0d15825d794b0b | [
"BSD-3-Clause"
] | 278 | 2018-10-28T13:48:18.000Z | 2022-03-28T11:07:24.000Z | cdippy/stndata.py | wdar/cdippy | ef38b3445351ec8d9d7ea30b5b0d15825d794b0b | [
"BSD-3-Clause"
] | null | null | null | from datetime import datetime, timedelta
from bisect import bisect_left
import numpy.ma as ma
from cdippy.cdippy import CDIPnc, Archive, Realtime, RealtimeXY, Historic
import cdippy.timestamp_utils as tsu
import cdippy.utils as cu
class StnData(CDIPnc):
"""
Returns data and metadata for the specified station.
This class handles the problem that neither the Realtime
nor the Historic .nc file may exist for either data or metadata,
and the number of deployment files is unknown apriori.
It tries to seam the multiple station files together.
"""
max_deployments = 99 # Checks at most this number of deployment nc files
# Commonly requested sets of variables
parameter_vars = ['waveHs', 'waveTp', 'waveDp', 'waveTa']
xyz_vars = ['xyzXDisplacement', 'xyzYDisplacement', 'xyzZDisplacement']
spectrum_vars = [
'waveEnergyDensity', 'waveMeanDirection',
'waveA1Value', 'waveB1Value', 'waveA2Value', 'waveB2Value',
'waveCheckFactor',]
meta_vars = [
'metaStationName',
'metaDeployLatitude', 'metaDeployLongitude', 'metaWaterDepth',
'metaDeclilnation']
meta_attributes = [
'wmo_id',
'geospatial_lat_min', 'geospatial_lat_max', 'geospatial_lat_units', 'geospatial_lat_resolution',
'geospatial_lon_min', 'geospatial_lon_max', 'geospatial_lon_units', 'geospatial_lon_resolution',
'geospatial_vertical_min', 'geospatial_vertical_max', 'geospatial_vertical_units', 'geospatial_vertical_resolution',
'time_coverage_start', 'time_coverage_end',
'date_created', 'date_modified' ]
def __init__(cls, stn, data_dir=None, org=None):
cls.nc = None
cls.stn = stn
cls.data_dir = data_dir
cls.org = org
cls.historic = Historic(cls.stn, cls.data_dir, cls.org)
cls.realtime = Realtime(cls.stn, cls.data_dir, cls.org)
if cls.historic and cls.historic.nc :
cls.meta = cls.historic
else:
if cls.realtime and cls.realtime.nc :
cls.meta = cls.realtime
else:
return None
def get_parameters(cls, start=None, end=None, pub_set='public', apply_mask=True, target_records=0):
return cls.get_series(start, end, cls.parameter_vars, pub_set, apply_mask, target_records)
def get_stn_meta(cls):
""" Returns a dict of station meta data using historic or realtime file. """
result = {}
if cls.meta is None:
return result
cls.meta.set_request_info(vrs=cls.meta_vars)
result = cls.meta.get_request()
for attr_name in cls.meta_attributes:
if hasattr(cls.meta.nc, attr_name):
result[attr_name] = getattr(cls.meta.nc, attr_name)
return result
def get_xyz(cls, start=None, end=None, pub_set='public'):
return cls.get_series(start, end, cls.xyz_vars, pub_set)
def get_spectra(cls, start=None, end=None, pub_set='public', apply_mask=True, target_records=0):
return cls.get_series(start, end, cls.spectrum_vars, pub_set, apply_mask, target_records)
def get_series(cls, start=None, end=None, vrs=None, pub_set='public', apply_mask=True, target_records=0):
"""
Returns a dict of data between start and end dates with specified quality.
Use this to get series that may span realtime and historic files.
If end is None, then start is considered a target date.
"""
if vrs is None:
vrs = cls.parameter_vars
prefix = cls.get_var_prefix(vrs[0])
if start is not None and end is None: # Target time
ts_I = cls.get_target_timespan(cu.datetime_to_timestamp(start), target_records, prefix+'Time')
if ts_I[0] is not None:
start = cu.timestamp_to_datetime(ts_I[0])
end = cu.timestamp_to_datetime(ts_I[1])
else:
return None
elif start is None: # Use default 3 days back
start = datetime.utcnow()-timedelta(days=3)
end = datetime.utcnow()
cls.set_request_info(start, end, vrs, pub_set, apply_mask)
if vrs is not None and prefix == 'xyz':
return cls.merge_xyz_request()
else:
return cls.merge_request()
def aggregate_dicts(cls, dict1, dict2):
""" Aggregate the data in two dictionaries. Dict1 has oldest data. """
#- Union the keys to make sure we check each one
ukeys = set(dict1.keys()) | set(dict2.keys())
result = { }
#- Combine the variables
for key in ukeys :
if key in dict2 and key in dict1:
result[key] = ma.concatenate([dict1[key], dict2[key]])
elif key in dict2:
result[key] = dict2[key]
else:
result[key] = dict1[key]
return result
def merge_xyz_request(cls):
""" Merge xyz data from realtime and archive nc files. """
if cls.vrs and cls.vrs[0] == 'xyzData':
cls.vrs = ['xyzXDisplacement','xyzYDisplacement','xyzZDisplacement']
request_timespan = cu.Timespan(cls.start_stamp, cls.end_stamp)
result = {}
def helper(cdip_nc, request_timespan, result):
# Try the next file if it is without xyz data
z = cdip_nc.get_var('xyzZDisplacement')
if z is None:
return result, cls.start_stamp
# Try the next file if start_stamp cannot be calculated
start_stamp = cdip_nc.get_xyz_timestamp(0)
end_stamp = cdip_nc.get_xyz_timestamp(len(z)-1)
if start_stamp is None:
return result, cls.start_stamp
file_timespan = cu.Timespan(start_stamp, end_stamp)
# Add data if request timespan overlaps data timespan
if request_timespan.overlap(file_timespan):
cdip_nc.start_stamp = cls.start_stamp
cdip_nc.end_stamp = cls.end_stamp
cdip_nc.pub_set = cls.pub_set
cdip_nc.apply_mask = cls.apply_mask
cdip_nc.vrs = cls.vrs
tmp_result = cdip_nc.get_request()
result = cls.aggregate_dicts(result, tmp_result)
return result, start_stamp
# First get realtime data if it exists
rt = RealtimeXY(cls.stn)
if rt.nc is not None:
result, start_stamp = helper(rt, request_timespan, result)
# If the request start time is more recent than the realtime
# start time, no need to look in the archives
if cls.start_stamp > start_stamp:
return result
# Second, look in archive files for data
for dep in range(1, cls.max_deployments):
deployment = 'd'+'{:02d}'.format(dep)
ar = Archive(cls.stn, deployment, cls.data_dir, cls.org)
if ar.nc is None:
break
result, start_stamp = helper(ar, request_timespan, result)
# Break if file start stamp is greater than request end stamp
if start_stamp > cls.end_stamp :
break
return result
def merge_request(cls):
""" Returns data for given request across realtime and historic files """
rt = {};
r = cls.realtime
# Note that we are assuming that waveTime will work for every time dim.
if r.nc is not None and r.get_var('waveTime')[0] <= cls.end_stamp:
r.vrs = cls.vrs
r.start_stamp = cls.start_stamp
r.end_stamp = cls.end_stamp
r.pub_set = cls.pub_set
r.apply_mask = cls.apply_mask
rt = r.get_request()
ht = {};
h = cls.historic
if h.nc is not None and h.get_var('waveTime')[-1] >= cls.start_stamp:
h.vrs = cls.vrs
h.start_stamp = cls.start_stamp
h.end_stamp = cls.end_stamp
h.pub_set = cls.pub_set
h.apply_mask = cls.apply_mask
ht = h.get_request()
return cls.aggregate_dicts(ht, rt)
def get_nc_files(cls, types=['realtime','historic','archive']):
""" Returns dict of netcdf4 objects of a station's netcdf files """
result = {}
for type in types:
if type == 'realtime':
rt = Realtime(cls.stn, cls.data_dir, cls.org)
if rt.nc:
result[rt.filename] = rt.nc
if type == 'historic':
ht = Historic(cls.stn, cls.data_dir, cls.org)
if ht.nc:
result[ht.filename] = ht.nc
if type == 'archive':
for dep in range(1,cls.max_deployments):
deployment = 'd'+'{:02d}'.format(dep)
ar = Archive(cls.stn, deployment, cls.data_dir, cls.org)
if ar.nc is None:
break
result[ar.filename] = ar
return result
def get_target_timespan(cls, target_timestamp, n, time_var):
"""
Returns a 2-tuple of timestamps, an interval corresponding to n records to
the right or left of target_timestamp.
Given a time_var (e.g. 'waveTime') and target timestamp, returns a 2-tuple
of timestamps corresponding to i and i+n (n<0 or n>=0) taken from
the realtime and historic nc files. Those timestamps can then be used in
set_request_info().
"""
r_ok = False
if cls.realtime.nc is not None:
r_ok = True
h_ok = False
if cls.historic.nc is not None:
h_ok = True
# Check realtime to find closest index
r_closest_idx = None
if r_ok:
r_stamps = cls.realtime.get_var(time_var)[:]
r_last_idx = len(r_stamps) - 1
i_b = bisect_left(r_stamps, target_timestamp)
# i_b will be possibly one more than the last index
i_b = min(i_b, r_last_idx)
# Target timestamp is exactly equal to a data time
if i_b == r_last_idx or r_stamps[i_b] == target_timestamp:
r_closest_idx = i_b
elif i_b > 0:
r_closest_idx = tsu.get_closest_index(i_b-1, i_b, r_stamps, target_timestamp)
# If closest index not found, check historic
h_closest_idx = None
h_last_idx = None # Let's us know if h_stamps has been loaded
if h_ok and not r_closest_idx:
h_stamps = cls.historic.get_var(time_var)[:]
h_last_idx = len(h_stamps) - 1
i_b = bisect_left(h_stamps, target_timestamp)
i_b = min(i_b, h_last_idx)
# Target timestamp is exactly equal to a data time
if (i_b <= h_last_idx and h_stamps[i_b] == target_timestamp) or i_b == 0:
h_closest_idx = i_b
elif i_b >= h_last_idx: # Target is between the two files
if r_ok:
if abs(h_stamps[h_last_idx]-target_timestamp) < abs(r_stamps[0]-target_timestamp):
h_closest_idx = i_b
else:
r_closest_idx = 0
else: # No realtime file
h_closest_idx = i_b
else: # Within middle of historic stamps
h_closest_idx = tsu.get_closest_index(i_b-1, i_b, h_stamps, target_timestamp)
# Now we have the closest index, find the intervals
if r_closest_idx is not None:
r_interval = tsu.get_interval(r_stamps, r_closest_idx, n)
# If bound exceeded toward H and H exists, cacluate h_interval
if r_interval[2] < 0 and h_ok:
if not h_last_idx:
h_stamps = cls.historic.get_var(time_var)[:]
h_last_idx = len(h_stamps) - 1
h_interval = tsu.get_interval(h_stamps, h_last_idx, n+r_closest_idx+1)
#print("Rx H interval: ", h_interval)
#print("Rx R interval: ", r_interval)
return tsu.combine_intervals(h_interval, r_interval)
else:
return r_interval
elif h_closest_idx is not None:
h_interval = tsu.get_interval(h_stamps, h_closest_idx, n)
# If bound exceeded toward R and R exists, cacluate r_interval
if h_interval[2] > 0 and r_ok:
r_interval = tsu.get_interval(r_stamps, 0, n+h_closest_idx-h_last_idx-1)
#print("Hx H interval: ", h_interval)
#print("Hx R interval: ", r_interval)
return tsu.combine_intervals(h_interval, r_interval)
else:
return h_interval
# If we get to here there's a problem
return (None, None, None)
if __name__ == "__main__":
#- Tests
def t0():
s = StnData('100p1')
d = s.get_stn_meta()
print(d)
def t1():
s = StnData('100p1')
d = s.get_spectra(datetime(2016,8,1), target_records=3)
print(d.keys())
print(d['waveEnergyDensity'].shape)
def t2():
s = StnData('100p1',org='ww3')
d = s.get_series('2016-08-01 00:00:00','2016-08-02 23:59:59',['waveHs'],'public')
print(d)
def t3():
s = StnData('100p1',data_dir='./gdata')
d = s.get_nc_files(['historic','archive','realtime'])
print(d.keys())
def t4():
s = StnData('100p1')
# Across deployments 5 and 6
d = s.get_series('2007-05-30 00:00:00','2007-06-01 23:59:59',['xyzData'],'public')
print(len(d['xyzXDisplacement']))
print(len(d['xyzTime']))
print(d['xyzTime'][0],d['xyzTime'][-1])
def t5():
s = StnData('100p1')
dt = datetime(2010,4,1,0,0)
d = s.get_series(dt, target_records=-4)
print(d)
def t6():
# Mark 1 filter delay set to -999.9
s = StnData('071p1')
end = datetime.utcnow()
end = datetime(1996,1,22,15,57,00)
start = end - timedelta(hours=2)
d = s.get_xyz(start, end)
print("D: "+repr(d))
print("Len: "+repr(len(d['xyzTime'])))
t6()
| 41.597668 | 124 | 0.584665 | from datetime import datetime, timedelta
from bisect import bisect_left
import numpy.ma as ma
from cdippy.cdippy import CDIPnc, Archive, Realtime, RealtimeXY, Historic
import cdippy.timestamp_utils as tsu
import cdippy.utils as cu
class StnData(CDIPnc):
max_deployments = 99
parameter_vars = ['waveHs', 'waveTp', 'waveDp', 'waveTa']
xyz_vars = ['xyzXDisplacement', 'xyzYDisplacement', 'xyzZDisplacement']
spectrum_vars = [
'waveEnergyDensity', 'waveMeanDirection',
'waveA1Value', 'waveB1Value', 'waveA2Value', 'waveB2Value',
'waveCheckFactor',]
meta_vars = [
'metaStationName',
'metaDeployLatitude', 'metaDeployLongitude', 'metaWaterDepth',
'metaDeclilnation']
meta_attributes = [
'wmo_id',
'geospatial_lat_min', 'geospatial_lat_max', 'geospatial_lat_units', 'geospatial_lat_resolution',
'geospatial_lon_min', 'geospatial_lon_max', 'geospatial_lon_units', 'geospatial_lon_resolution',
'geospatial_vertical_min', 'geospatial_vertical_max', 'geospatial_vertical_units', 'geospatial_vertical_resolution',
'time_coverage_start', 'time_coverage_end',
'date_created', 'date_modified' ]
def __init__(cls, stn, data_dir=None, org=None):
cls.nc = None
cls.stn = stn
cls.data_dir = data_dir
cls.org = org
cls.historic = Historic(cls.stn, cls.data_dir, cls.org)
cls.realtime = Realtime(cls.stn, cls.data_dir, cls.org)
if cls.historic and cls.historic.nc :
cls.meta = cls.historic
else:
if cls.realtime and cls.realtime.nc :
cls.meta = cls.realtime
else:
return None
def get_parameters(cls, start=None, end=None, pub_set='public', apply_mask=True, target_records=0):
return cls.get_series(start, end, cls.parameter_vars, pub_set, apply_mask, target_records)
def get_stn_meta(cls):
result = {}
if cls.meta is None:
return result
cls.meta.set_request_info(vrs=cls.meta_vars)
result = cls.meta.get_request()
for attr_name in cls.meta_attributes:
if hasattr(cls.meta.nc, attr_name):
result[attr_name] = getattr(cls.meta.nc, attr_name)
return result
def get_xyz(cls, start=None, end=None, pub_set='public'):
return cls.get_series(start, end, cls.xyz_vars, pub_set)
def get_spectra(cls, start=None, end=None, pub_set='public', apply_mask=True, target_records=0):
return cls.get_series(start, end, cls.spectrum_vars, pub_set, apply_mask, target_records)
def get_series(cls, start=None, end=None, vrs=None, pub_set='public', apply_mask=True, target_records=0):
if vrs is None:
vrs = cls.parameter_vars
prefix = cls.get_var_prefix(vrs[0])
if start is not None and end is None:
ts_I = cls.get_target_timespan(cu.datetime_to_timestamp(start), target_records, prefix+'Time')
if ts_I[0] is not None:
start = cu.timestamp_to_datetime(ts_I[0])
end = cu.timestamp_to_datetime(ts_I[1])
else:
return None
elif start is None:
start = datetime.utcnow()-timedelta(days=3)
end = datetime.utcnow()
cls.set_request_info(start, end, vrs, pub_set, apply_mask)
if vrs is not None and prefix == 'xyz':
return cls.merge_xyz_request()
else:
return cls.merge_request()
def aggregate_dicts(cls, dict1, dict2):
ukeys = set(dict1.keys()) | set(dict2.keys())
result = { }
for key in ukeys :
if key in dict2 and key in dict1:
result[key] = ma.concatenate([dict1[key], dict2[key]])
elif key in dict2:
result[key] = dict2[key]
else:
result[key] = dict1[key]
return result
def merge_xyz_request(cls):
if cls.vrs and cls.vrs[0] == 'xyzData':
cls.vrs = ['xyzXDisplacement','xyzYDisplacement','xyzZDisplacement']
request_timespan = cu.Timespan(cls.start_stamp, cls.end_stamp)
result = {}
def helper(cdip_nc, request_timespan, result):
z = cdip_nc.get_var('xyzZDisplacement')
if z is None:
return result, cls.start_stamp
start_stamp = cdip_nc.get_xyz_timestamp(0)
end_stamp = cdip_nc.get_xyz_timestamp(len(z)-1)
if start_stamp is None:
return result, cls.start_stamp
file_timespan = cu.Timespan(start_stamp, end_stamp)
if request_timespan.overlap(file_timespan):
cdip_nc.start_stamp = cls.start_stamp
cdip_nc.end_stamp = cls.end_stamp
cdip_nc.pub_set = cls.pub_set
cdip_nc.apply_mask = cls.apply_mask
cdip_nc.vrs = cls.vrs
tmp_result = cdip_nc.get_request()
result = cls.aggregate_dicts(result, tmp_result)
return result, start_stamp
rt = RealtimeXY(cls.stn)
if rt.nc is not None:
result, start_stamp = helper(rt, request_timespan, result)
if cls.start_stamp > start_stamp:
return result
for dep in range(1, cls.max_deployments):
deployment = 'd'+'{:02d}'.format(dep)
ar = Archive(cls.stn, deployment, cls.data_dir, cls.org)
if ar.nc is None:
break
result, start_stamp = helper(ar, request_timespan, result)
if start_stamp > cls.end_stamp :
break
return result
def merge_request(cls):
rt = {};
r = cls.realtime
if r.nc is not None and r.get_var('waveTime')[0] <= cls.end_stamp:
r.vrs = cls.vrs
r.start_stamp = cls.start_stamp
r.end_stamp = cls.end_stamp
r.pub_set = cls.pub_set
r.apply_mask = cls.apply_mask
rt = r.get_request()
ht = {};
h = cls.historic
if h.nc is not None and h.get_var('waveTime')[-1] >= cls.start_stamp:
h.vrs = cls.vrs
h.start_stamp = cls.start_stamp
h.end_stamp = cls.end_stamp
h.pub_set = cls.pub_set
h.apply_mask = cls.apply_mask
ht = h.get_request()
return cls.aggregate_dicts(ht, rt)
def get_nc_files(cls, types=['realtime','historic','archive']):
result = {}
for type in types:
if type == 'realtime':
rt = Realtime(cls.stn, cls.data_dir, cls.org)
if rt.nc:
result[rt.filename] = rt.nc
if type == 'historic':
ht = Historic(cls.stn, cls.data_dir, cls.org)
if ht.nc:
result[ht.filename] = ht.nc
if type == 'archive':
for dep in range(1,cls.max_deployments):
deployment = 'd'+'{:02d}'.format(dep)
ar = Archive(cls.stn, deployment, cls.data_dir, cls.org)
if ar.nc is None:
break
result[ar.filename] = ar
return result
def get_target_timespan(cls, target_timestamp, n, time_var):
r_ok = False
if cls.realtime.nc is not None:
r_ok = True
h_ok = False
if cls.historic.nc is not None:
h_ok = True
r_closest_idx = None
if r_ok:
r_stamps = cls.realtime.get_var(time_var)[:]
r_last_idx = len(r_stamps) - 1
i_b = bisect_left(r_stamps, target_timestamp)
i_b = min(i_b, r_last_idx)
if i_b == r_last_idx or r_stamps[i_b] == target_timestamp:
r_closest_idx = i_b
elif i_b > 0:
r_closest_idx = tsu.get_closest_index(i_b-1, i_b, r_stamps, target_timestamp)
h_closest_idx = None
h_last_idx = None
if h_ok and not r_closest_idx:
h_stamps = cls.historic.get_var(time_var)[:]
h_last_idx = len(h_stamps) - 1
i_b = bisect_left(h_stamps, target_timestamp)
i_b = min(i_b, h_last_idx)
# Target timestamp is exactly equal to a data time
if (i_b <= h_last_idx and h_stamps[i_b] == target_timestamp) or i_b == 0:
h_closest_idx = i_b
elif i_b >= h_last_idx: # Target is between the two files
if r_ok:
if abs(h_stamps[h_last_idx]-target_timestamp) < abs(r_stamps[0]-target_timestamp):
h_closest_idx = i_b
else:
r_closest_idx = 0
else: # No realtime file
h_closest_idx = i_b
else: # Within middle of historic stamps
h_closest_idx = tsu.get_closest_index(i_b-1, i_b, h_stamps, target_timestamp)
# Now we have the closest index, find the intervals
if r_closest_idx is not None:
r_interval = tsu.get_interval(r_stamps, r_closest_idx, n)
# If bound exceeded toward H and H exists, cacluate h_interval
if r_interval[2] < 0 and h_ok:
if not h_last_idx:
h_stamps = cls.historic.get_var(time_var)[:]
h_last_idx = len(h_stamps) - 1
h_interval = tsu.get_interval(h_stamps, h_last_idx, n+r_closest_idx+1)
#print("Rx H interval: ", h_interval)
#print("Rx R interval: ", r_interval)
return tsu.combine_intervals(h_interval, r_interval)
else:
return r_interval
elif h_closest_idx is not None:
h_interval = tsu.get_interval(h_stamps, h_closest_idx, n)
# If bound exceeded toward R and R exists, cacluate r_interval
if h_interval[2] > 0 and r_ok:
r_interval = tsu.get_interval(r_stamps, 0, n+h_closest_idx-h_last_idx-1)
#print("Hx H interval: ", h_interval)
#print("Hx R interval: ", r_interval)
return tsu.combine_intervals(h_interval, r_interval)
else:
return h_interval
# If we get to here there's a problem
return (None, None, None)
if __name__ == "__main__":
def t0():
s = StnData('100p1')
d = s.get_stn_meta()
print(d)
def t1():
s = StnData('100p1')
d = s.get_spectra(datetime(2016,8,1), target_records=3)
print(d.keys())
print(d['waveEnergyDensity'].shape)
def t2():
s = StnData('100p1',org='ww3')
d = s.get_series('2016-08-01 00:00:00','2016-08-02 23:59:59',['waveHs'],'public')
print(d)
def t3():
s = StnData('100p1',data_dir='./gdata')
d = s.get_nc_files(['historic','archive','realtime'])
print(d.keys())
def t4():
s = StnData('100p1')
d = s.get_series('2007-05-30 00:00:00','2007-06-01 23:59:59',['xyzData'],'public')
print(len(d['xyzXDisplacement']))
print(len(d['xyzTime']))
print(d['xyzTime'][0],d['xyzTime'][-1])
def t5():
s = StnData('100p1')
dt = datetime(2010,4,1,0,0)
d = s.get_series(dt, target_records=-4)
print(d)
def t6():
s = StnData('071p1')
end = datetime.utcnow()
end = datetime(1996,1,22,15,57,00)
start = end - timedelta(hours=2)
d = s.get_xyz(start, end)
print("D: "+repr(d))
print("Len: "+repr(len(d['xyzTime'])))
t6()
| true | true |
f7104e1171ca3c5b939f29866585440a8400cd28 | 19,337 | py | Python | Interface/Reduce.py | shaesaert/TuLiPXML | 56cf4d58a9d7e17b6f6aebe6de8d5a1231035671 | [
"BSD-3-Clause"
] | 1 | 2021-05-28T23:44:28.000Z | 2021-05-28T23:44:28.000Z | Interface/Reduce.py | shaesaert/TuLiPXML | 56cf4d58a9d7e17b6f6aebe6de8d5a1231035671 | [
"BSD-3-Clause"
] | 2 | 2017-10-03T18:54:08.000Z | 2018-08-21T09:50:09.000Z | Interface/Reduce.py | shaesaert/TuLiPXML | 56cf4d58a9d7e17b6f6aebe6de8d5a1231035671 | [
"BSD-3-Clause"
] | 1 | 2018-10-06T12:58:52.000Z | 2018-10-06T12:58:52.000Z | """ Local routines
Written by S.Haesaert
CONTENT
helpfull functions for JPL project
Bridging Tulip with the Statechart autocoder
DATE 2 June
"""
# TODO : Check whether output set of reduced mealy machines (i,e.,ctrl.outputs) is too big?
from __future__ import absolute_import
from __future__ import print_function
import logging
from itertools import product as it_product
from networkx.algorithms.minors import equivalence_classes
from tulip import transys
from Interface import synth2 as synth
logger = logging.getLogger(__name__)
def remove_aux_inputs(ctrl, inputs):
#1. check whether you are allowed to remove the aux inputs. <= not done
#2. remove aux. inputs.
ctrl_new = transys.MealyMachine()
ctrl_new.add_outputs(ctrl.outputs)
# this needs to be changed to be a limited set
inputs_dict = dict()
for i in inputs:
inputs_dict[i] = ctrl.inputs[i]
ctrl_new.add_inputs(inputs_dict)
# add nodes from original mealy
ctrl_new.add_nodes_from(ctrl.nodes())
block_pairs = it_product(ctrl, ctrl)
for (b, c) in block_pairs:
labels = {frozenset([(key, label[key]) for key in ctrl_new.inputs.keys()]
+ [(output, label[output]) for output in ctrl_new.outputs.keys()])
for (x, y, label) in ctrl.transitions.find(b, c)}
for q in labels:
ctrl_new.transitions.add(b, c, **dict(q))
ctrl_new.states.initial.add_from(ctrl.states.initial)
return ctrl_new
def reduce_mealy(ctrl, outputs={'ctrl'}, relabel=False, prune_set=None,
full=True, combine_trans=False, verbose=True):
""" reduce mealy machines by computing the quotient system of the maximal equivalence class
Parameters
----------
ctrl: mealy machine
outputs : Tells which outputs are critical and should be kept. Given as a set of strings.
relabel : True/False = Relabels nodes (especially needed when ctrl comes with hash like names)
prune_init : if set => try 'prune' => remove all transitions that do not belong to the set of allowed initialisations
Else determinize
"""
assert isinstance(prune_set, set) or prune_set is None, 'prune_set is not a set'
ctrl_s = prune_init(ctrl, init_event=prune_set)
if verbose: print('Original number of states = ' + str(len(ctrl)) + '\n'
+ ' number of transitions = ' + str(len(ctrl.transitions.find())))
it_beh = True
len_last = len(ctrl_s)
while it_beh:
equiv_classes = equiv_alpha(ctrl_s, outputs)
if verbose: print('Start iterating for maximally coarse bisimulation')
it = True
# now you should iterate for maximally coarse
while it:
if verbose: print('Number of states = ' + str(len(equiv_classes)))
equiv_classes_new = iterate_equiv(equiv_classes, ctrl_s, outputs=outputs)
it = (len(equiv_classes_new) != len(equiv_classes))
equiv_classes = equiv_classes_new
if verbose: print('Found equivalence classes')
# now compute quotient system
equiv_dict = dict(sum([list(it_product(block, {i})) for (i, block) in enumerate(equiv_classes)], []))
node_rel = lambda u, v: equiv_dict[u] == equiv_dict[v] # the initial relation
ctrl_s = quotient_mealy(ctrl_s, node_relation=node_rel, relabel=relabel, outputs=outputs)
if full:
equiv_classes = reduce_guar_beh(ctrl_s, outputs=outputs)
equiv_dict = dict(sum([list(it_product(block, {i})) for (i, block) in enumerate(equiv_classes)], []))
node_rel = lambda u, v: equiv_dict[u] == equiv_dict[v] # the initial relation => groups of nodes that can
# have equal next nodes
ctrl_s = quotient_mealy(ctrl_s, node_relation=node_rel, relabel=relabel, outputs=outputs)
if verbose: print('Behavioural equivalence reductions \n' +
'- number of states = ' + str(len(ctrl_s)) + '\n'
+ '- number of transitions = ' + str(len(ctrl_s.transitions.find())))
it_beh = ((len(ctrl_s) != len_last) and full)
len_last = len(ctrl_s)
if combine_trans:
ctrl_s = combine_transitions(ctrl_s)
if verbose: print('Combine transitions \n' +
'- number of states = ' + str(len(ctrl_s)) + '\n'
+ '- number of transitions = ' + str(len(ctrl_s.transitions.find())))
return ctrl_s
def reduce_guar_beh(ctrl,outputs={'loc'}):
ctrl_n=ctrl.copy()
"""
compute equivalence classes.
Parameters
----------
ctrl : mealy machine
outputs : Tells which outputs are critical and should be kept. Given as a set of strings.
Code is adapted from networkx.algorithms.minors.equivalenceclasses by Jeffry Finkelstein.
"""
# 1. Find R_0 = equivalence class of elements with the same labels on their outgoing transitions.
blocks = []
# Determine the equivalence class for each element of the iterable.
# TODO Order first :
# => Dont go directly over ctrl.states(), first order them on the number of transitions they have.
stat_len = [(y, len(ctrl_n.transitions.find(y))) for y in ctrl_n.states()]
sorted_nodes = sorted(stat_len, key=lambda stat_len: -stat_len[1])
for (y,_t) in sorted_nodes:
# Each element y must be in *exactly one* equivalence class.
#
# Each block is guaranteed to be non-empty
if y == 'Sinit': # the initial state gets its own block
blocks.append([y])
continue
for block in blocks:
x = next(iter(block))
if len(ctrl[x]) < len(ctrl[y]):
#print('unequal number')
continue
if x == 'Sinit': # the initial state gets its own block
continue
# compute set of labels:
labels_x = {frozenset([(key, label[key]) for key in ctrl_n.inputs.keys()]
+ [(output, label[output]) for output in outputs]+[('node',_y)])
for (_x, _y, label) in ctrl_n.transitions.find({x})}
labels_y = {frozenset([(key, label[key]) for key in ctrl_n.inputs.keys()]
+ [(output, label[output]) for output in outputs]+[('node',_y)])
for (_x, _y, label) in ctrl_n.transitions.find({y})}
if labels_y <= labels_x:
block.append(y)
break
labelin_x = {frozenset([(key, label[key]) for key in ctrl_n.inputs.keys()])
for (_x, _y, label) in ctrl_n.transitions.find({x})}
labelin_y = {frozenset([(key, label[key]) for key in ctrl_n.inputs.keys()])
for (_x, _y, label) in ctrl_n.transitions.find({y})}
if len(labels_y | labels_x) == len(labelin_y | labelin_x):
block.append(y) #TODO (THIS is WRONG, the labels are now no longer correct!!!
# after adding a new state to a block, the first state of the block needs to get
# additional outgoing transitions)
# you need to also immediatly add the additional outgoing transition. Otherwise you are creating errors )
# find the missing input labels
for label in labels_y.difference(labels_x):
ldict=dict(label)
ctrl_n.transitions.add(x, ldict.pop('node'), **ldict)
ctrl_n.transitions.find(x, **ldict)
# labels = {frozenset([(key, label[key]) for key in mealy.inputs.keys()]
# + [(output, label[output]) for output in outputs])
# for (x, y, label) in mealy.transitions.find(b, c)}
# for q in labels:
# q_mealy.transitions.add(mapping[b], mapping[c], **dict(q))
break
else:
# If the element y is not part of any known equivalence class, it
# must be in its own, so we create a new singleton equivalence
# class for it.
blocks.append([y])
return {frozenset(block) for block in blocks}
def combine_transitions(ctrl):
""" Combine parallell transitions when they are independent of environment actions
Parameters
----------
ctrl: mealy machine
"""
ctrl_copy = ctrl.copy()
for c_state in ctrl_copy.nodes():
for post_s in ctrl_copy.states.post(c_state):
logger.info('(' + str(c_state) + ')' + '(' + str(post_s) + ')')
labels = [set(label.items()) for (x, y, label) in ctrl_copy.transitions.find({c_state}, {post_s})]
min_set = set.intersection(*labels)
labels_mins = [lab - min_set for lab in labels]
if set.union(*labels_mins) == set():
continue
list_in = [set(it_product({key}, values)) for (key, values) in ctrl_copy.inputs.items()
if (not values == {0, 1}) & (set(it_product({key}, values)) <= set.union(*labels_mins))] + [
set(it_product({key}, {True, False})) for (key, values) in ctrl_copy.inputs.items()
if ((values == {0, 1}) & (set(it_product({key}, values)) <= set.union(*labels_mins)))]
labels_updated = labels.copy()
for list_el in list_in:
for label in labels_updated:
label_gen = [(label - list_el) | {el_set} for el_set in list_el]
if all([any([label_gen_el == labels_el for labels_el in labels_updated]) for label_gen_el in
label_gen]):
labels_updated = set(frozenset(labels_el) for labels_el in labels_updated if
not any([label_gen_el == labels_el for label_gen_el in label_gen]))
labels_updated |= {frozenset((label - list_el))}
ctrl_copy.transitions.remove_from(ctrl_copy.transitions.find({c_state}, {post_s}))
for labels_updated_el in labels_updated:
ctrl_copy.transitions.add(c_state, post_s, dict(set(labels_updated_el)))
return ctrl_copy
def equiv_alpha(ctrl, outputs={'loc'}):
"""
compute equivalence classes.
Parameters
----------
ctrl : mealy machine
outputs : Tells which outputs are critical and should be kept. Given as a set of strings.
Code is adapted from networkx.algorithms.minors.equivalenceclasses by Jeffry Finkelstein.
"""
# 1. Find R_0 = equivalence class of elements with the same labels on their outgoing transitions.
blocks = []
# Determine the equivalence class for each element of the iterable.
for y in ctrl.states():
# Each element y must be in *exactly one* equivalence class.
#
# Each block is guaranteed to be non-empty
for block in blocks:
x = next(iter(block))
if len(ctrl[x]) != len(ctrl[y]):
# print('unequal number')
continue
# compute set of labels:
labels_x = {frozenset([(key, label[key]) for key in ctrl.inputs.keys()]
+ [(output, label[output]) for output in outputs])
for (_x, _y, label) in ctrl.transitions.find({x})}
labels_y = {frozenset([(key, label[key]) for key in ctrl.inputs.keys()]
+ [(output, label[output]) for output in outputs])
for (_x, _y, label) in ctrl.transitions.find({y})}
if labels_x == labels_y:
block.append(y)
break
else:
# If the element y is not part of any known equivalence class, it
# must be in its own, so we create a new singleton equivalence
# class for it.
blocks.append([y])
return {frozenset(block) for block in blocks}
def iterate_equiv(q_blocks, ctrl, outputs={'loc'}):
""" Iterate the equivalence classes
Parameters
----------
q_blocks : equivalence classes
ctrl : mealy machine
outputs : Tells which outputs are critical and should be kept. Given as a set of strings.
"""
dict__r = dict(sum([list(it_product(block, {i})) for (i, block) in enumerate(q_blocks)], []))
blocks = []
# Determine the equivalence class for each element of the iterable.
for y in ctrl.states():
# Each element y must be in *exactly one* equivalence class.
#
# Each block is guaranteed to be non-empty
if y in ctrl.states.initial:
blocks.append([y]) # We don't want to group in the initial state. Because that will give issues witht he autocoding.
else:
for block in blocks:
x = next(iter(block))
if len(ctrl[x]) != len(ctrl[y]):
# print('unequal number')
continue
# compute set of labels:
labels_x = {frozenset([(key, label[key]) for key in ctrl.inputs.keys()] +
[(output, label[output]) for output in outputs] +
[('Relx', dict__r[_x])]+[('Rely', dict__r[_y])])
for (_x, _y, label) in ctrl.transitions.find({x})}
labels_y = {frozenset([(key, label[key]) for key in ctrl.inputs.keys()] +
[(output, label[output]) for output in outputs] +
[('Relx', dict__r[_x])]+[('Rely', dict__r[_y])])
for (_x, _y, label) in ctrl.transitions.find({y})}
if labels_x == labels_y:
block.append(y)
break
else:
# If the element y is not part of any known equivalence class, it
# must be in its own, so we create a new singleton equivalence
# class for it.
blocks.append([y])
return {frozenset(block) for block in blocks}
def prune_init(ctrl,init_event=None):
ctrl_s = synth.determinize_machine_init(ctrl)
if init_event is not None:
try:
keys = list(set(key for (key,val) in list(init_event)))
inputsb = {env_var: ctrl.inputs[env_var] for env_var in keys}
# this allows you to give a subset of the inputs
set_in = set.union(*[set(it_product({key}, values)) for (key, values) in inputsb.items()
if not values == {0, 1}] + [
set(it_product({key}, {True, False})) for (key, values) in inputsb.items()
if values == {0, 1}])
if not init_event <= set_in:
raise ValueError('The set of initial environment values does not'
' belong to the set of inputs of the mealy machine')
for s, to, label in ctrl_s.transitions.find({'Sinit'}):
if not (set.intersection(set(label.items()), set_in)) <= init_event:
ctrl_s.transitions.remove(s, to, attr_dict=label)
if ctrl_s['Sinit'] is None:
raise ValueError('The set of initial environment values does not'
' belong to the set of inputs of the mealy machine.\n'
' All initial transitions were removed.')
except ValueError as inst:
print(inst.args)
print('Determinized Mealy machine,'
' initial transitions have not been pruned.(WARNING)')
return synth.determinize_machine_init(ctrl)
return ctrl_s
def quotient_mealy(mealy, node_relation=None, relabel=False, outputs={'loc'}):
"""Returns the quotient graph of ``G`` under the specified equivalence
relation on nodes.
Parameters
----------
mealy : NetworkX graph
The graph for which to return the quotient graph with the specified node
relation.
node_relation : Boolean function with two arguments
This function must represent an equivalence relation on the nodes of
``G``. It must take two arguments *u* and *v* and return ``True``
exactly when *u* and *v* are in the same equivalence class. The
equivalence classes form the nodes in the returned graph.
unlike the original networkx.quotient_graph selfloops are maintained
relabel : Boolean
if true relabel nodes in the graph
outputs : Tells which outputs are critical and should be kept. Given as a set of strings.
"""
if node_relation is None:
node_relation = lambda u, v: mealy.states.post(u) == mealy.states.post(v)
q_mealy = transys.MealyMachine()
q_mealy.add_inputs(mealy.inputs)
q_mealy.add_outputs(mealy.outputs)
# Compute the blocks of the partition on the nodes of G induced by the
# equivalence relation R.
if relabel:
mapping = dict((n, i) for (i, n) in enumerate(equivalence_classes(mealy, node_relation)))
for (n, i) in mapping.items():
if {'Sinit'} <= set(n):
mapping[n] = 'Sinit'
q_mealy.add_nodes_from({n for (i, n) in mapping.items()})
else:
q_mealy.add_nodes_from(equivalence_classes(mealy, node_relation))
if relabel:
block_pairs = it_product(mapping.keys(), mapping.keys())
for (b, c) in block_pairs:
labels = {frozenset([(key, label[key]) for key in mealy.inputs.keys()]
+ [(output, label[output]) for output in outputs])
for (x, y, label) in mealy.transitions.find(b, c)}
for q in labels:
q_mealy.transitions.add(mapping[b], mapping[c], **dict(q))
else:
block_pairs = it_product(q_mealy, q_mealy)
for (b, c) in block_pairs:
labels = {frozenset([(key, label[key]) for key in mealy.inputs.keys()]
+ [(output, label[output]) for output in outputs])
for (x, y, label) in mealy.transitions.find(b, c)}
for q in labels:
q_mealy.transitions.add(b, c, **dict(q))
if relabel:
for node_eq in mapping.keys():
if any(init in node_eq for init in mealy.states.initial):
q_mealy.states.initial.add(mapping[node_eq])
else: # only initializing after relabel
for node_eq in q_mealy.nodes():
if any(init in node_eq for init in mealy.states.initial):
q_mealy.states.initial.add(node_eq)
return q_mealy
def save_png(ctrl,name='untitled'):
from tulip.transys.export import graph2dot
pydot_ctrl = graph2dot._graph2pydot(ctrl)
pydot_ctrl.set_rankdir('TB')
# pydot_ctrl.set_splines('polyline')
pydot_ctrl.set_bgcolor('white')
pydot_ctrl.set_nodesep(.4)
pydot_ctrl.set_ranksep(.4)
pydot_ctrl.set_size('"40,30"')
pydot_ctrl.set_concentrate('False')
#png_str = pydot_ctrl.create_jpeg(prog='dot')
pydot_ctrl.write_png(name+'.png',prog='dot')
return
| 42.875831 | 128 | 0.584734 |
from __future__ import absolute_import
from __future__ import print_function
import logging
from itertools import product as it_product
from networkx.algorithms.minors import equivalence_classes
from tulip import transys
from Interface import synth2 as synth
logger = logging.getLogger(__name__)
def remove_aux_inputs(ctrl, inputs):
ctrl_new = transys.MealyMachine()
ctrl_new.add_outputs(ctrl.outputs)
inputs_dict = dict()
for i in inputs:
inputs_dict[i] = ctrl.inputs[i]
ctrl_new.add_inputs(inputs_dict)
ctrl_new.add_nodes_from(ctrl.nodes())
block_pairs = it_product(ctrl, ctrl)
for (b, c) in block_pairs:
labels = {frozenset([(key, label[key]) for key in ctrl_new.inputs.keys()]
+ [(output, label[output]) for output in ctrl_new.outputs.keys()])
for (x, y, label) in ctrl.transitions.find(b, c)}
for q in labels:
ctrl_new.transitions.add(b, c, **dict(q))
ctrl_new.states.initial.add_from(ctrl.states.initial)
return ctrl_new
def reduce_mealy(ctrl, outputs={'ctrl'}, relabel=False, prune_set=None,
full=True, combine_trans=False, verbose=True):
assert isinstance(prune_set, set) or prune_set is None, 'prune_set is not a set'
ctrl_s = prune_init(ctrl, init_event=prune_set)
if verbose: print('Original number of states = ' + str(len(ctrl)) + '\n'
+ ' number of transitions = ' + str(len(ctrl.transitions.find())))
it_beh = True
len_last = len(ctrl_s)
while it_beh:
equiv_classes = equiv_alpha(ctrl_s, outputs)
if verbose: print('Start iterating for maximally coarse bisimulation')
it = True
while it:
if verbose: print('Number of states = ' + str(len(equiv_classes)))
equiv_classes_new = iterate_equiv(equiv_classes, ctrl_s, outputs=outputs)
it = (len(equiv_classes_new) != len(equiv_classes))
equiv_classes = equiv_classes_new
if verbose: print('Found equivalence classes')
equiv_dict = dict(sum([list(it_product(block, {i})) for (i, block) in enumerate(equiv_classes)], []))
node_rel = lambda u, v: equiv_dict[u] == equiv_dict[v]
ctrl_s = quotient_mealy(ctrl_s, node_relation=node_rel, relabel=relabel, outputs=outputs)
if full:
equiv_classes = reduce_guar_beh(ctrl_s, outputs=outputs)
equiv_dict = dict(sum([list(it_product(block, {i})) for (i, block) in enumerate(equiv_classes)], []))
node_rel = lambda u, v: equiv_dict[u] == equiv_dict[v]
ctrl_s = quotient_mealy(ctrl_s, node_relation=node_rel, relabel=relabel, outputs=outputs)
if verbose: print('Behavioural equivalence reductions \n' +
'- number of states = ' + str(len(ctrl_s)) + '\n'
+ '- number of transitions = ' + str(len(ctrl_s.transitions.find())))
it_beh = ((len(ctrl_s) != len_last) and full)
len_last = len(ctrl_s)
if combine_trans:
ctrl_s = combine_transitions(ctrl_s)
if verbose: print('Combine transitions \n' +
'- number of states = ' + str(len(ctrl_s)) + '\n'
+ '- number of transitions = ' + str(len(ctrl_s.transitions.find())))
return ctrl_s
def reduce_guar_beh(ctrl,outputs={'loc'}):
ctrl_n=ctrl.copy()
blocks = []
stat_len = [(y, len(ctrl_n.transitions.find(y))) for y in ctrl_n.states()]
sorted_nodes = sorted(stat_len, key=lambda stat_len: -stat_len[1])
for (y,_t) in sorted_nodes:
if y == 'Sinit':
blocks.append([y])
continue
for block in blocks:
x = next(iter(block))
if len(ctrl[x]) < len(ctrl[y]):
continue
if x == 'Sinit':
continue
labels_x = {frozenset([(key, label[key]) for key in ctrl_n.inputs.keys()]
+ [(output, label[output]) for output in outputs]+[('node',_y)])
for (_x, _y, label) in ctrl_n.transitions.find({x})}
labels_y = {frozenset([(key, label[key]) for key in ctrl_n.inputs.keys()]
+ [(output, label[output]) for output in outputs]+[('node',_y)])
for (_x, _y, label) in ctrl_n.transitions.find({y})}
if labels_y <= labels_x:
block.append(y)
break
labelin_x = {frozenset([(key, label[key]) for key in ctrl_n.inputs.keys()])
for (_x, _y, label) in ctrl_n.transitions.find({x})}
labelin_y = {frozenset([(key, label[key]) for key in ctrl_n.inputs.keys()])
for (_x, _y, label) in ctrl_n.transitions.find({y})}
if len(labels_y | labels_x) == len(labelin_y | labelin_x):
block.append(y)
for label in labels_y.difference(labels_x):
ldict=dict(label)
ctrl_n.transitions.add(x, ldict.pop('node'), **ldict)
ctrl_n.transitions.find(x, **ldict)
break
else:
blocks.append([y])
return {frozenset(block) for block in blocks}
def combine_transitions(ctrl):
ctrl_copy = ctrl.copy()
for c_state in ctrl_copy.nodes():
for post_s in ctrl_copy.states.post(c_state):
logger.info('(' + str(c_state) + ')' + '(' + str(post_s) + ')')
labels = [set(label.items()) for (x, y, label) in ctrl_copy.transitions.find({c_state}, {post_s})]
min_set = set.intersection(*labels)
labels_mins = [lab - min_set for lab in labels]
if set.union(*labels_mins) == set():
continue
list_in = [set(it_product({key}, values)) for (key, values) in ctrl_copy.inputs.items()
if (not values == {0, 1}) & (set(it_product({key}, values)) <= set.union(*labels_mins))] + [
set(it_product({key}, {True, False})) for (key, values) in ctrl_copy.inputs.items()
if ((values == {0, 1}) & (set(it_product({key}, values)) <= set.union(*labels_mins)))]
labels_updated = labels.copy()
for list_el in list_in:
for label in labels_updated:
label_gen = [(label - list_el) | {el_set} for el_set in list_el]
if all([any([label_gen_el == labels_el for labels_el in labels_updated]) for label_gen_el in
label_gen]):
labels_updated = set(frozenset(labels_el) for labels_el in labels_updated if
not any([label_gen_el == labels_el for label_gen_el in label_gen]))
labels_updated |= {frozenset((label - list_el))}
ctrl_copy.transitions.remove_from(ctrl_copy.transitions.find({c_state}, {post_s}))
for labels_updated_el in labels_updated:
ctrl_copy.transitions.add(c_state, post_s, dict(set(labels_updated_el)))
return ctrl_copy
def equiv_alpha(ctrl, outputs={'loc'}):
blocks = []
for y in ctrl.states():
for block in blocks:
x = next(iter(block))
if len(ctrl[x]) != len(ctrl[y]):
continue
labels_x = {frozenset([(key, label[key]) for key in ctrl.inputs.keys()]
+ [(output, label[output]) for output in outputs])
for (_x, _y, label) in ctrl.transitions.find({x})}
labels_y = {frozenset([(key, label[key]) for key in ctrl.inputs.keys()]
+ [(output, label[output]) for output in outputs])
for (_x, _y, label) in ctrl.transitions.find({y})}
if labels_x == labels_y:
block.append(y)
break
else:
blocks.append([y])
return {frozenset(block) for block in blocks}
def iterate_equiv(q_blocks, ctrl, outputs={'loc'}):
dict__r = dict(sum([list(it_product(block, {i})) for (i, block) in enumerate(q_blocks)], []))
blocks = []
for y in ctrl.states():
if y in ctrl.states.initial:
blocks.append([y])
else:
for block in blocks:
x = next(iter(block))
if len(ctrl[x]) != len(ctrl[y]):
# print('unequal number')
continue
# compute set of labels:
labels_x = {frozenset([(key, label[key]) for key in ctrl.inputs.keys()] +
[(output, label[output]) for output in outputs] +
[('Relx', dict__r[_x])]+[('Rely', dict__r[_y])])
for (_x, _y, label) in ctrl.transitions.find({x})}
labels_y = {frozenset([(key, label[key]) for key in ctrl.inputs.keys()] +
[(output, label[output]) for output in outputs] +
[('Relx', dict__r[_x])]+[('Rely', dict__r[_y])])
for (_x, _y, label) in ctrl.transitions.find({y})}
if labels_x == labels_y:
block.append(y)
break
else:
# If the element y is not part of any known equivalence class, it
# must be in its own, so we create a new singleton equivalence
# class for it.
blocks.append([y])
return {frozenset(block) for block in blocks}
def prune_init(ctrl,init_event=None):
ctrl_s = synth.determinize_machine_init(ctrl)
if init_event is not None:
try:
keys = list(set(key for (key,val) in list(init_event)))
inputsb = {env_var: ctrl.inputs[env_var] for env_var in keys}
# this allows you to give a subset of the inputs
set_in = set.union(*[set(it_product({key}, values)) for (key, values) in inputsb.items()
if not values == {0, 1}] + [
set(it_product({key}, {True, False})) for (key, values) in inputsb.items()
if values == {0, 1}])
if not init_event <= set_in:
raise ValueError('The set of initial environment values does not'
' belong to the set of inputs of the mealy machine')
for s, to, label in ctrl_s.transitions.find({'Sinit'}):
if not (set.intersection(set(label.items()), set_in)) <= init_event:
ctrl_s.transitions.remove(s, to, attr_dict=label)
if ctrl_s['Sinit'] is None:
raise ValueError('The set of initial environment values does not'
' belong to the set of inputs of the mealy machine.\n'
' All initial transitions were removed.')
except ValueError as inst:
print(inst.args)
print('Determinized Mealy machine,'
' initial transitions have not been pruned.(WARNING)')
return synth.determinize_machine_init(ctrl)
return ctrl_s
def quotient_mealy(mealy, node_relation=None, relabel=False, outputs={'loc'}):
if node_relation is None:
node_relation = lambda u, v: mealy.states.post(u) == mealy.states.post(v)
q_mealy = transys.MealyMachine()
q_mealy.add_inputs(mealy.inputs)
q_mealy.add_outputs(mealy.outputs)
# Compute the blocks of the partition on the nodes of G induced by the
# equivalence relation R.
if relabel:
mapping = dict((n, i) for (i, n) in enumerate(equivalence_classes(mealy, node_relation)))
for (n, i) in mapping.items():
if {'Sinit'} <= set(n):
mapping[n] = 'Sinit'
q_mealy.add_nodes_from({n for (i, n) in mapping.items()})
else:
q_mealy.add_nodes_from(equivalence_classes(mealy, node_relation))
if relabel:
block_pairs = it_product(mapping.keys(), mapping.keys())
for (b, c) in block_pairs:
labels = {frozenset([(key, label[key]) for key in mealy.inputs.keys()]
+ [(output, label[output]) for output in outputs])
for (x, y, label) in mealy.transitions.find(b, c)}
for q in labels:
q_mealy.transitions.add(mapping[b], mapping[c], **dict(q))
else:
block_pairs = it_product(q_mealy, q_mealy)
for (b, c) in block_pairs:
labels = {frozenset([(key, label[key]) for key in mealy.inputs.keys()]
+ [(output, label[output]) for output in outputs])
for (x, y, label) in mealy.transitions.find(b, c)}
for q in labels:
q_mealy.transitions.add(b, c, **dict(q))
if relabel:
for node_eq in mapping.keys():
if any(init in node_eq for init in mealy.states.initial):
q_mealy.states.initial.add(mapping[node_eq])
else: # only initializing after relabel
for node_eq in q_mealy.nodes():
if any(init in node_eq for init in mealy.states.initial):
q_mealy.states.initial.add(node_eq)
return q_mealy
def save_png(ctrl,name='untitled'):
from tulip.transys.export import graph2dot
pydot_ctrl = graph2dot._graph2pydot(ctrl)
pydot_ctrl.set_rankdir('TB')
# pydot_ctrl.set_splines('polyline')
pydot_ctrl.set_bgcolor('white')
pydot_ctrl.set_nodesep(.4)
pydot_ctrl.set_ranksep(.4)
pydot_ctrl.set_size('"40,30"')
pydot_ctrl.set_concentrate('False')
#png_str = pydot_ctrl.create_jpeg(prog='dot')
pydot_ctrl.write_png(name+'.png',prog='dot')
return
| true | true |
f7104e5f53580b564470d7f299654cf1542444e0 | 469 | py | Python | env/Lib/site-packages/plotly/validators/scatterpolar/marker/colorbar/tickformatstop/_value.py | andresgreen-byte/Laboratorio-1--Inversion-de-Capital | 8a4707301d19c3826c31026c4077930bcd6a8182 | [
"MIT"
] | 11,750 | 2015-10-12T07:03:39.000Z | 2022-03-31T20:43:15.000Z | env/Lib/site-packages/plotly/validators/scatterpolar/marker/colorbar/tickformatstop/_value.py | andresgreen-byte/Laboratorio-1--Inversion-de-Capital | 8a4707301d19c3826c31026c4077930bcd6a8182 | [
"MIT"
] | 2,951 | 2015-10-12T00:41:25.000Z | 2022-03-31T22:19:26.000Z | env/Lib/site-packages/plotly/validators/scatterpolar/marker/colorbar/tickformatstop/_value.py | andresgreen-byte/Laboratorio-1--Inversion-de-Capital | 8a4707301d19c3826c31026c4077930bcd6a8182 | [
"MIT"
] | 2,623 | 2015-10-15T14:40:27.000Z | 2022-03-28T16:05:50.000Z | import _plotly_utils.basevalidators
class ValueValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="value",
parent_name="scatterpolar.marker.colorbar.tickformatstop",
**kwargs
):
super(ValueValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colorbars"),
**kwargs
)
| 27.588235 | 67 | 0.637527 | import _plotly_utils.basevalidators
class ValueValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="value",
parent_name="scatterpolar.marker.colorbar.tickformatstop",
**kwargs
):
super(ValueValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colorbars"),
**kwargs
)
| true | true |
f7104f1742e63a1113fe4bfce148895fa8e5ac2d | 2,699 | py | Python | twilio/access_token.py | quippp/twilio-python | 22b84cdfd19a6b1bde84350053870a7c507af410 | [
"MIT"
] | 14 | 2016-12-10T18:44:38.000Z | 2020-08-05T21:09:42.000Z | twilio/access_token.py | quippp/twilio-python | 22b84cdfd19a6b1bde84350053870a7c507af410 | [
"MIT"
] | 1 | 2016-05-26T21:39:12.000Z | 2016-05-26T21:39:14.000Z | v/lib/python2.7/site-packages/twilio/access_token.py | josh6beasttt/HangWithFriends | 0c5113bf1203190364d4922754c21eb5d87a5c25 | [
"Apache-2.0"
] | 5 | 2017-01-08T13:00:25.000Z | 2020-06-03T09:46:17.000Z | import time
from twilio import jwt
class IpMessagingGrant(object):
""" Grant to access Twilio IP Messaging """
def __init__(self, service_sid=None, endpoint_id=None,
deployment_role_sid=None, push_credential_sid=None):
self.service_sid = service_sid
self.endpoint_id = endpoint_id
self.deployment_role_sid = deployment_role_sid
self.push_credential_sid = push_credential_sid
@property
def key(self):
return "ip_messaging"
def to_payload(self):
grant = {}
if self.service_sid:
grant['service_sid'] = self.service_sid
if self.endpoint_id:
grant['endpoint_id'] = self.endpoint_id
if self.deployment_role_sid:
grant['deployment_role_sid'] = self.deployment_role_sid
if self.push_credential_sid:
grant['push_credential_sid'] = self.push_credential_sid
return grant
class ConversationsGrant(object):
""" Grant to access Twilio Conversations """
def __init__(self, configuration_profile_sid=None):
self.configuration_profile_sid = configuration_profile_sid
@property
def key(self):
return "rtc"
def to_payload(self):
grant = {}
if self.configuration_profile_sid:
grant['configuration_profile_sid'] = self.configuration_profile_sid
return grant
class AccessToken(object):
""" Access Token used to access Twilio Resources """
def __init__(self, account_sid, signing_key_sid, secret,
identity=None, ttl=3600, nbf=None):
self.account_sid = account_sid
self.signing_key_sid = signing_key_sid
self.secret = secret
self.identity = identity
self.ttl = ttl
self.nbf = nbf
self.grants = []
def add_grant(self, grant):
self.grants.append(grant)
def to_jwt(self, algorithm='HS256'):
now = int(time.time())
headers = {
"typ": "JWT",
"cty": "twilio-fpa;v=1"
}
grants = {}
if self.identity:
grants["identity"] = self.identity
for grant in self.grants:
grants[grant.key] = grant.to_payload()
payload = {
"jti": '{0}-{1}'.format(self.signing_key_sid, now),
"iss": self.signing_key_sid,
"sub": self.account_sid,
"exp": now + self.ttl,
"grants": grants
}
if self.nbf is not None:
payload['nbf'] = self.nbf
return jwt.encode(payload, self.secret, headers=headers,
algorithm=algorithm)
def __str__(self):
return self.to_jwt()
| 28.410526 | 79 | 0.603557 | import time
from twilio import jwt
class IpMessagingGrant(object):
def __init__(self, service_sid=None, endpoint_id=None,
deployment_role_sid=None, push_credential_sid=None):
self.service_sid = service_sid
self.endpoint_id = endpoint_id
self.deployment_role_sid = deployment_role_sid
self.push_credential_sid = push_credential_sid
@property
def key(self):
return "ip_messaging"
def to_payload(self):
grant = {}
if self.service_sid:
grant['service_sid'] = self.service_sid
if self.endpoint_id:
grant['endpoint_id'] = self.endpoint_id
if self.deployment_role_sid:
grant['deployment_role_sid'] = self.deployment_role_sid
if self.push_credential_sid:
grant['push_credential_sid'] = self.push_credential_sid
return grant
class ConversationsGrant(object):
def __init__(self, configuration_profile_sid=None):
self.configuration_profile_sid = configuration_profile_sid
@property
def key(self):
return "rtc"
def to_payload(self):
grant = {}
if self.configuration_profile_sid:
grant['configuration_profile_sid'] = self.configuration_profile_sid
return grant
class AccessToken(object):
def __init__(self, account_sid, signing_key_sid, secret,
identity=None, ttl=3600, nbf=None):
self.account_sid = account_sid
self.signing_key_sid = signing_key_sid
self.secret = secret
self.identity = identity
self.ttl = ttl
self.nbf = nbf
self.grants = []
def add_grant(self, grant):
self.grants.append(grant)
def to_jwt(self, algorithm='HS256'):
now = int(time.time())
headers = {
"typ": "JWT",
"cty": "twilio-fpa;v=1"
}
grants = {}
if self.identity:
grants["identity"] = self.identity
for grant in self.grants:
grants[grant.key] = grant.to_payload()
payload = {
"jti": '{0}-{1}'.format(self.signing_key_sid, now),
"iss": self.signing_key_sid,
"sub": self.account_sid,
"exp": now + self.ttl,
"grants": grants
}
if self.nbf is not None:
payload['nbf'] = self.nbf
return jwt.encode(payload, self.secret, headers=headers,
algorithm=algorithm)
def __str__(self):
return self.to_jwt()
| true | true |
f7104f79652ee5e3c7047f0cf3b972ab698cbea7 | 6,962 | py | Python | nova/console/websocketproxy.py | ebalduf/nova-backports | 6bf97ec73467de522d34ab7a17ca0e0874baa7f9 | [
"Apache-2.0"
] | null | null | null | nova/console/websocketproxy.py | ebalduf/nova-backports | 6bf97ec73467de522d34ab7a17ca0e0874baa7f9 | [
"Apache-2.0"
] | null | null | null | nova/console/websocketproxy.py | ebalduf/nova-backports | 6bf97ec73467de522d34ab7a17ca0e0874baa7f9 | [
"Apache-2.0"
] | 1 | 2020-07-24T00:41:18.000Z | 2020-07-24T00:41:18.000Z | # Copyright (c) 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
'''
Websocket proxy that is compatible with OpenStack Nova.
Leverages websockify.py by Joel Martin
'''
import socket
import sys
from oslo_log import log as logging
from six.moves import http_cookies as Cookie
import six.moves.urllib.parse as urlparse
import websockify
import nova.conf
from nova.consoleauth import rpcapi as consoleauth_rpcapi
from nova import context
from nova import exception
from nova.i18n import _
LOG = logging.getLogger(__name__)
CONF = nova.conf.CONF
class NovaProxyRequestHandlerBase(object):
def address_string(self):
# NOTE(rpodolyaka): override the superclass implementation here and
# explicitly disable the reverse DNS lookup, which might fail on some
# deployments due to DNS configuration and break VNC access completely
return str(self.client_address[0])
def verify_origin_proto(self, connection_info, origin_proto):
access_url = connection_info.get('access_url')
if not access_url:
detail = _("No access_url in connection_info. "
"Cannot validate protocol")
raise exception.ValidationError(detail=detail)
expected_protos = [urlparse.urlparse(access_url).scheme]
# NOTE: For serial consoles the expected protocol could be ws or
# wss which correspond to http and https respectively in terms of
# security.
if 'ws' in expected_protos:
expected_protos.append('http')
if 'wss' in expected_protos:
expected_protos.append('https')
return origin_proto in expected_protos
def new_websocket_client(self):
"""Called after a new WebSocket connection has been established."""
# Reopen the eventlet hub to make sure we don't share an epoll
# fd with parent and/or siblings, which would be bad
from eventlet import hubs
hubs.use_hub()
# The nova expected behavior is to have token
# passed to the method GET of the request
parse = urlparse.urlparse(self.path)
if parse.scheme not in ('http', 'https'):
# From a bug in urlparse in Python < 2.7.4 we cannot support
# special schemes (cf: http://bugs.python.org/issue9374)
if sys.version_info < (2, 7, 4):
raise exception.NovaException(
_("We do not support scheme '%s' under Python < 2.7.4, "
"please use http or https") % parse.scheme)
query = parse.query
token = urlparse.parse_qs(query).get("token", [""]).pop()
if not token:
# NoVNC uses it's own convention that forward token
# from the request to a cookie header, we should check
# also for this behavior
hcookie = self.headers.getheader('cookie')
if hcookie:
cookie = Cookie.SimpleCookie()
cookie.load(hcookie)
if 'token' in cookie:
token = cookie['token'].value
ctxt = context.get_admin_context()
rpcapi = consoleauth_rpcapi.ConsoleAuthAPI()
connect_info = rpcapi.check_token(ctxt, token=token)
if not connect_info:
raise exception.InvalidToken(token=token)
# Verify Origin
expected_origin_hostname = self.headers.getheader('Host')
if ':' in expected_origin_hostname:
e = expected_origin_hostname
if '[' in e and ']' in e:
expected_origin_hostname = e.split(']')[0][1:]
else:
expected_origin_hostname = e.split(':')[0]
expected_origin_hostnames = CONF.console_allowed_origins
expected_origin_hostnames.append(expected_origin_hostname)
origin_url = self.headers.getheader('Origin')
# missing origin header indicates non-browser client which is OK
if origin_url is not None:
origin = urlparse.urlparse(origin_url)
origin_hostname = origin.hostname
origin_scheme = origin.scheme
if origin_hostname == '' or origin_scheme == '':
detail = _("Origin header not valid.")
raise exception.ValidationError(detail=detail)
if origin_hostname not in expected_origin_hostnames:
detail = _("Origin header does not match this host.")
raise exception.ValidationError(detail=detail)
if not self.verify_origin_proto(connect_info, origin_scheme):
detail = _("Origin header protocol does not match this host.")
raise exception.ValidationError(detail=detail)
self.msg(_('connect info: %s'), str(connect_info))
host = connect_info['host']
port = int(connect_info['port'])
# Connect to the target
self.msg(_("connecting to: %(host)s:%(port)s") % {'host': host,
'port': port})
tsock = self.socket(host, port, connect=True)
# Handshake as necessary
if connect_info.get('internal_access_path'):
tsock.send("CONNECT %s HTTP/1.1\r\n\r\n" %
connect_info['internal_access_path'])
while True:
data = tsock.recv(4096, socket.MSG_PEEK)
if data.find("\r\n\r\n") != -1:
if data.split("\r\n")[0].find("200") == -1:
raise exception.InvalidConnectionInfo()
tsock.recv(len(data))
break
# Start proxying
try:
self.do_proxy(tsock)
except Exception:
if tsock:
tsock.shutdown(socket.SHUT_RDWR)
tsock.close()
self.vmsg(_("%(host)s:%(port)s: Target closed") %
{'host': host, 'port': port})
raise
class NovaProxyRequestHandler(NovaProxyRequestHandlerBase,
websockify.ProxyRequestHandler):
def __init__(self, *args, **kwargs):
websockify.ProxyRequestHandler.__init__(self, *args, **kwargs)
def socket(self, *args, **kwargs):
return websockify.WebSocketServer.socket(*args, **kwargs)
class NovaWebSocketProxy(websockify.WebSocketProxy):
@staticmethod
def get_logger():
return LOG
| 40.011494 | 78 | 0.620511 |
import socket
import sys
from oslo_log import log as logging
from six.moves import http_cookies as Cookie
import six.moves.urllib.parse as urlparse
import websockify
import nova.conf
from nova.consoleauth import rpcapi as consoleauth_rpcapi
from nova import context
from nova import exception
from nova.i18n import _
LOG = logging.getLogger(__name__)
CONF = nova.conf.CONF
class NovaProxyRequestHandlerBase(object):
def address_string(self):
return str(self.client_address[0])
def verify_origin_proto(self, connection_info, origin_proto):
access_url = connection_info.get('access_url')
if not access_url:
detail = _("No access_url in connection_info. "
"Cannot validate protocol")
raise exception.ValidationError(detail=detail)
expected_protos = [urlparse.urlparse(access_url).scheme]
if 'ws' in expected_protos:
expected_protos.append('http')
if 'wss' in expected_protos:
expected_protos.append('https')
return origin_proto in expected_protos
def new_websocket_client(self):
# fd with parent and/or siblings, which would be bad
from eventlet import hubs
hubs.use_hub()
# The nova expected behavior is to have token
# passed to the method GET of the request
parse = urlparse.urlparse(self.path)
if parse.scheme not in ('http', 'https'):
# From a bug in urlparse in Python < 2.7.4 we cannot support
# special schemes (cf: http://bugs.python.org/issue9374)
if sys.version_info < (2, 7, 4):
raise exception.NovaException(
_("We do not support scheme '%s' under Python < 2.7.4, "
"please use http or https") % parse.scheme)
query = parse.query
token = urlparse.parse_qs(query).get("token", [""]).pop()
if not token:
# NoVNC uses it's own convention that forward token
hcookie = self.headers.getheader('cookie')
if hcookie:
cookie = Cookie.SimpleCookie()
cookie.load(hcookie)
if 'token' in cookie:
token = cookie['token'].value
ctxt = context.get_admin_context()
rpcapi = consoleauth_rpcapi.ConsoleAuthAPI()
connect_info = rpcapi.check_token(ctxt, token=token)
if not connect_info:
raise exception.InvalidToken(token=token)
expected_origin_hostname = self.headers.getheader('Host')
if ':' in expected_origin_hostname:
e = expected_origin_hostname
if '[' in e and ']' in e:
expected_origin_hostname = e.split(']')[0][1:]
else:
expected_origin_hostname = e.split(':')[0]
expected_origin_hostnames = CONF.console_allowed_origins
expected_origin_hostnames.append(expected_origin_hostname)
origin_url = self.headers.getheader('Origin')
if origin_url is not None:
origin = urlparse.urlparse(origin_url)
origin_hostname = origin.hostname
origin_scheme = origin.scheme
if origin_hostname == '' or origin_scheme == '':
detail = _("Origin header not valid.")
raise exception.ValidationError(detail=detail)
if origin_hostname not in expected_origin_hostnames:
detail = _("Origin header does not match this host.")
raise exception.ValidationError(detail=detail)
if not self.verify_origin_proto(connect_info, origin_scheme):
detail = _("Origin header protocol does not match this host.")
raise exception.ValidationError(detail=detail)
self.msg(_('connect info: %s'), str(connect_info))
host = connect_info['host']
port = int(connect_info['port'])
self.msg(_("connecting to: %(host)s:%(port)s") % {'host': host,
'port': port})
tsock = self.socket(host, port, connect=True)
if connect_info.get('internal_access_path'):
tsock.send("CONNECT %s HTTP/1.1\r\n\r\n" %
connect_info['internal_access_path'])
while True:
data = tsock.recv(4096, socket.MSG_PEEK)
if data.find("\r\n\r\n") != -1:
if data.split("\r\n")[0].find("200") == -1:
raise exception.InvalidConnectionInfo()
tsock.recv(len(data))
break
try:
self.do_proxy(tsock)
except Exception:
if tsock:
tsock.shutdown(socket.SHUT_RDWR)
tsock.close()
self.vmsg(_("%(host)s:%(port)s: Target closed") %
{'host': host, 'port': port})
raise
class NovaProxyRequestHandler(NovaProxyRequestHandlerBase,
websockify.ProxyRequestHandler):
def __init__(self, *args, **kwargs):
websockify.ProxyRequestHandler.__init__(self, *args, **kwargs)
def socket(self, *args, **kwargs):
return websockify.WebSocketServer.socket(*args, **kwargs)
class NovaWebSocketProxy(websockify.WebSocketProxy):
@staticmethod
def get_logger():
return LOG
| true | true |
f710508ef545bbdf41fe33a0d1d1d6589a1d0706 | 1,215 | py | Python | sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/get_personal_preferences_response.py | iscai-msft/azure-sdk-for-python | 83715b95c41e519d5be7f1180195e2fba136fc0f | [
"MIT"
] | 8 | 2021-01-13T23:44:08.000Z | 2021-03-17T10:13:36.000Z | sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/get_personal_preferences_response.py | iscai-msft/azure-sdk-for-python | 83715b95c41e519d5be7f1180195e2fba136fc0f | [
"MIT"
] | 226 | 2019-07-24T07:57:21.000Z | 2019-10-15T01:07:24.000Z | sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/get_personal_preferences_response.py | iscai-msft/azure-sdk-for-python | 83715b95c41e519d5be7f1180195e2fba136fc0f | [
"MIT"
] | 2 | 2020-05-21T22:51:22.000Z | 2020-05-26T20:53:01.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class GetPersonalPreferencesResponse(Model):
"""Represents the PersonalPreferences for the user.
:param id: Id to be used by the cache orchestrator
:type id: str
:param favorite_lab_resource_ids: Array of favorite lab resource ids
:type favorite_lab_resource_ids: list[str]
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'favorite_lab_resource_ids': {'key': 'favoriteLabResourceIds', 'type': '[str]'},
}
def __init__(self, **kwargs):
super(GetPersonalPreferencesResponse, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.favorite_lab_resource_ids = kwargs.get('favorite_lab_resource_ids', None)
| 36.818182 | 88 | 0.61893 |
from msrest.serialization import Model
class GetPersonalPreferencesResponse(Model):
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'favorite_lab_resource_ids': {'key': 'favoriteLabResourceIds', 'type': '[str]'},
}
def __init__(self, **kwargs):
super(GetPersonalPreferencesResponse, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
self.favorite_lab_resource_ids = kwargs.get('favorite_lab_resource_ids', None)
| true | true |
f71050d4778b9b286032e81da7a40b8d26399ce8 | 5,024 | py | Python | model/model.py | zoumt1633/pytorch-project-template | 871e00ebde6c2191de5f61b4cb7010c72b93c198 | [
"Apache-2.0"
] | 1 | 2021-04-23T03:26:55.000Z | 2021-04-23T03:26:55.000Z | model/model.py | zoumt1633/pytorch-project-template | 871e00ebde6c2191de5f61b4cb7010c72b93c198 | [
"Apache-2.0"
] | null | null | null | model/model.py | zoumt1633/pytorch-project-template | 871e00ebde6c2191de5f61b4cb7010c72b93c198 | [
"Apache-2.0"
] | 1 | 2021-09-06T02:38:50.000Z | 2021-09-06T02:38:50.000Z | import torch
import torch.nn
from torch.nn.parallel import DistributedDataParallel as DDP
from collections import OrderedDict
import os.path as osp
import wandb
from utils.utils import DotDict
class Model:
def __init__(self, hp, net_arch, loss_f, rank=0, world_size=1):
self.hp = hp
self.device = self.hp.model.device
self.net = net_arch.to(self.device)
self.rank = rank
self.world_size = world_size
if self.device != "cpu" and self.world_size != 0:
self.net = DDP(self.net, device_ids=[self.rank])
self.input = None
self.GT = None
self.step = 0
self.epoch = -1
# init optimizer
optimizer_mode = self.hp.train.optimizer.mode
if optimizer_mode == "adam":
self.optimizer = torch.optim.Adam(
self.net.parameters(), **(self.hp.train.optimizer[optimizer_mode])
)
else:
raise Exception("%s optimizer not supported" % optimizer_mode)
# init loss
self.loss_f = loss_f
self.log = DotDict()
def feed_data(self, **data): # data's keys: input, GT
for k, v in data.items():
data[k] = v.to(self.device)
self.input = data.get("input")
self.GT = data.get("GT")
def optimize_parameters(self):
self.net.train()
self.optimizer.zero_grad()
output = self.run_network()
loss_v = self.loss_f(output, self.GT)
loss_v.backward()
self.optimizer.step()
# set log
self.log.loss_v = loss_v.item()
def inference(self):
self.net.eval()
output = self.run_network()
return output
def run_network(self):
output = self.net(self.input)
return output
def save_network(self, logger, save_file=True):
if self.rank == 0:
net = self.net.module if isinstance(self.net, DDP) else self.net
state_dict = net.state_dict()
for key, param in state_dict.items():
state_dict[key] = param.to("cpu")
if save_file:
save_filename = "%s_%d.pt" % (self.hp.log.name, self.step)
save_path = osp.join(self.hp.log.chkpt_dir, save_filename)
torch.save(state_dict, save_path)
if self.hp.log.use_wandb:
wandb.save(save_path)
if logger is not None:
logger.info("Saved network checkpoint to: %s" % save_path)
return state_dict
def load_network(self, loaded_net=None, logger=None):
add_log = False
if loaded_net is None:
add_log = True
if self.hp.load.wandb_load_path is not None:
self.hp.load.network_chkpt_path = wandb.restore(
self.hp.load.network_chkpt_path,
run_path=self.hp.load.wandb_load_path,
).name
loaded_net = torch.load(
self.hp.load.network_chkpt_path, map_location=torch.device(self.device)
)
loaded_clean_net = OrderedDict() # remove unnecessary 'module.'
for k, v in loaded_net.items():
if k.startswith("module."):
loaded_clean_net[k[7:]] = v
else:
loaded_clean_net[k] = v
self.net.load_state_dict(loaded_clean_net, strict=self.hp.load.strict_load)
if logger is not None and add_log:
logger.info("Checkpoint %s is loaded" % self.hp.load.network_chkpt_path)
def save_training_state(self, logger):
if self.rank == 0:
save_filename = "%s_%d.state" % (self.hp.log.name, self.step)
save_path = osp.join(self.hp.log.chkpt_dir, save_filename)
net_state_dict = self.save_network(None, False)
state = {
"model": net_state_dict,
"optimizer": self.optimizer.state_dict(),
"step": self.step,
"epoch": self.epoch,
}
torch.save(state, save_path)
if self.hp.log.use_wandb:
wandb.save(save_path)
if logger is not None:
logger.info("Saved training state to: %s" % save_path)
def load_training_state(self, logger):
if self.hp.load.wandb_load_path is not None:
self.hp.load.resume_state_path = wandb.restore(
self.hp.load.resume_state_path, run_path=self.hp.load.wandb_load_path
).name
resume_state = torch.load(
self.hp.load.resume_state_path, map_location=torch.device(self.device)
)
self.load_network(loaded_net=resume_state["model"], logger=logger)
self.optimizer.load_state_dict(resume_state["optimizer"])
self.step = resume_state["step"]
self.epoch = resume_state["epoch"]
if logger is not None:
logger.info(
"Resuming from training state: %s" % self.hp.load.resume_state_path
)
| 36.405797 | 87 | 0.579618 | import torch
import torch.nn
from torch.nn.parallel import DistributedDataParallel as DDP
from collections import OrderedDict
import os.path as osp
import wandb
from utils.utils import DotDict
class Model:
def __init__(self, hp, net_arch, loss_f, rank=0, world_size=1):
self.hp = hp
self.device = self.hp.model.device
self.net = net_arch.to(self.device)
self.rank = rank
self.world_size = world_size
if self.device != "cpu" and self.world_size != 0:
self.net = DDP(self.net, device_ids=[self.rank])
self.input = None
self.GT = None
self.step = 0
self.epoch = -1
optimizer_mode = self.hp.train.optimizer.mode
if optimizer_mode == "adam":
self.optimizer = torch.optim.Adam(
self.net.parameters(), **(self.hp.train.optimizer[optimizer_mode])
)
else:
raise Exception("%s optimizer not supported" % optimizer_mode)
self.loss_f = loss_f
self.log = DotDict()
def feed_data(self, **data):
for k, v in data.items():
data[k] = v.to(self.device)
self.input = data.get("input")
self.GT = data.get("GT")
def optimize_parameters(self):
self.net.train()
self.optimizer.zero_grad()
output = self.run_network()
loss_v = self.loss_f(output, self.GT)
loss_v.backward()
self.optimizer.step()
# set log
self.log.loss_v = loss_v.item()
def inference(self):
self.net.eval()
output = self.run_network()
return output
def run_network(self):
output = self.net(self.input)
return output
def save_network(self, logger, save_file=True):
if self.rank == 0:
net = self.net.module if isinstance(self.net, DDP) else self.net
state_dict = net.state_dict()
for key, param in state_dict.items():
state_dict[key] = param.to("cpu")
if save_file:
save_filename = "%s_%d.pt" % (self.hp.log.name, self.step)
save_path = osp.join(self.hp.log.chkpt_dir, save_filename)
torch.save(state_dict, save_path)
if self.hp.log.use_wandb:
wandb.save(save_path)
if logger is not None:
logger.info("Saved network checkpoint to: %s" % save_path)
return state_dict
def load_network(self, loaded_net=None, logger=None):
add_log = False
if loaded_net is None:
add_log = True
if self.hp.load.wandb_load_path is not None:
self.hp.load.network_chkpt_path = wandb.restore(
self.hp.load.network_chkpt_path,
run_path=self.hp.load.wandb_load_path,
).name
loaded_net = torch.load(
self.hp.load.network_chkpt_path, map_location=torch.device(self.device)
)
loaded_clean_net = OrderedDict() # remove unnecessary 'module.'
for k, v in loaded_net.items():
if k.startswith("module."):
loaded_clean_net[k[7:]] = v
else:
loaded_clean_net[k] = v
self.net.load_state_dict(loaded_clean_net, strict=self.hp.load.strict_load)
if logger is not None and add_log:
logger.info("Checkpoint %s is loaded" % self.hp.load.network_chkpt_path)
def save_training_state(self, logger):
if self.rank == 0:
save_filename = "%s_%d.state" % (self.hp.log.name, self.step)
save_path = osp.join(self.hp.log.chkpt_dir, save_filename)
net_state_dict = self.save_network(None, False)
state = {
"model": net_state_dict,
"optimizer": self.optimizer.state_dict(),
"step": self.step,
"epoch": self.epoch,
}
torch.save(state, save_path)
if self.hp.log.use_wandb:
wandb.save(save_path)
if logger is not None:
logger.info("Saved training state to: %s" % save_path)
def load_training_state(self, logger):
if self.hp.load.wandb_load_path is not None:
self.hp.load.resume_state_path = wandb.restore(
self.hp.load.resume_state_path, run_path=self.hp.load.wandb_load_path
).name
resume_state = torch.load(
self.hp.load.resume_state_path, map_location=torch.device(self.device)
)
self.load_network(loaded_net=resume_state["model"], logger=logger)
self.optimizer.load_state_dict(resume_state["optimizer"])
self.step = resume_state["step"]
self.epoch = resume_state["epoch"]
if logger is not None:
logger.info(
"Resuming from training state: %s" % self.hp.load.resume_state_path
)
| true | true |
f71050ebef8199c7d5a9e55369e430fba92d5a18 | 366 | py | Python | 5th May Assignments/case study 1/question_2.py | JangirSumit/data_science | a1957122f8a4c66e3b4c7b7c93a74c53a2db1fe4 | [
"MIT"
] | 15 | 2019-05-05T04:48:42.000Z | 2022-02-15T12:08:33.000Z | 5th May Assignments/case study 1/question_2.py | JangirSumit/data_science | a1957122f8a4c66e3b4c7b7c93a74c53a2db1fe4 | [
"MIT"
] | null | null | null | 5th May Assignments/case study 1/question_2.py | JangirSumit/data_science | a1957122f8a4c66e3b4c7b7c93a74c53a2db1fe4 | [
"MIT"
] | 53 | 2019-11-10T05:09:25.000Z | 2022-03-28T01:26:32.000Z | # 2. Write a code which accepts a sequence of words as input
# and prints the words in a sequence after sorting them alphabetically.
print("Enter sequence of words")
print("For example -\nMy name is Sumit\n")
words = input(">>> ")
temp = words.split(" ")
temp.sort()
sorted_string = " ".join(temp)
print("string after sorting is - \n")
print(f"{sorted_string}")
| 24.4 | 71 | 0.702186 |
print("Enter sequence of words")
print("For example -\nMy name is Sumit\n")
words = input(">>> ")
temp = words.split(" ")
temp.sort()
sorted_string = " ".join(temp)
print("string after sorting is - \n")
print(f"{sorted_string}")
| true | true |
f7105223a14265887aab39c6802321ba32a7ba59 | 1,840 | py | Python | test/test_precision.py | HubBucket-Team/tensorforce | 92c987424c89e96238a3689aa4018df0d9d40504 | [
"Apache-2.0"
] | 1 | 2019-09-23T18:39:57.000Z | 2019-09-23T18:39:57.000Z | test/test_precision.py | VonRosenchild/tensorforce | 92c987424c89e96238a3689aa4018df0d9d40504 | [
"Apache-2.0"
] | null | null | null | test/test_precision.py | VonRosenchild/tensorforce | 92c987424c89e96238a3689aa4018df0d9d40504 | [
"Apache-2.0"
] | 1 | 2019-09-23T18:40:00.000Z | 2019-09-23T18:40:00.000Z | # Copyright 2018 Tensorforce Team. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import pytest
import unittest
import numpy as np
import tensorflow as tf
from tensorforce import util
from test.unittest_base import UnittestBase
class TestPrecision(UnittestBase, unittest.TestCase):
exclude_bounded_action = True # TODO: shouldn't be necessary!
require_observe = True
def test_precision(self):
self.start_tests()
try:
util.np_dtype_mapping = dict(
bool=np.bool_, int=np.int16, long=np.int32, float=np.float32 # TODO: float16
)
util.tf_dtype_mapping = dict(
bool=tf.bool, int=tf.int16, long=tf.int32, float=tf.float32 # TODO: float16
)
self.unittest(network=dict(type='auto', internal_rnn=False)) # TODO: shouldn't be necessary!
except Exception as exc:
raise exc
self.assertTrue(expr=False)
finally:
util.np_dtype_mapping = dict(
bool=np.bool_, int=np.int32, long=np.int64, float=np.float32
)
util.tf_dtype_mapping = dict(
bool=tf.bool, int=tf.int32, long=tf.int64, float=tf.float32
)
| 33.454545 | 105 | 0.634783 |
import pytest
import unittest
import numpy as np
import tensorflow as tf
from tensorforce import util
from test.unittest_base import UnittestBase
class TestPrecision(UnittestBase, unittest.TestCase):
exclude_bounded_action = True
require_observe = True
def test_precision(self):
self.start_tests()
try:
util.np_dtype_mapping = dict(
bool=np.bool_, int=np.int16, long=np.int32, float=np.float32 # TODO: float16
)
util.tf_dtype_mapping = dict(
bool=tf.bool, int=tf.int16, long=tf.int32, float=tf.float32 # TODO: float16
)
self.unittest(network=dict(type='auto', internal_rnn=False)) # TODO: shouldn't be necessary!
except Exception as exc:
raise exc
self.assertTrue(expr=False)
finally:
util.np_dtype_mapping = dict(
bool=np.bool_, int=np.int32, long=np.int64, float=np.float32
)
util.tf_dtype_mapping = dict(
bool=tf.bool, int=tf.int32, long=tf.int64, float=tf.float32
)
| true | true |
f710538cddf41d04cf71c058a094540469e6a98f | 1,910 | py | Python | src/exoplanet/distributions/physical_test.py | ericagol/exoplanet | ec270622f28cd53d3052ed44d20f30b5d2b4dcb6 | [
"MIT"
] | null | null | null | src/exoplanet/distributions/physical_test.py | ericagol/exoplanet | ec270622f28cd53d3052ed44d20f30b5d2b4dcb6 | [
"MIT"
] | null | null | null | src/exoplanet/distributions/physical_test.py | ericagol/exoplanet | ec270622f28cd53d3052ed44d20f30b5d2b4dcb6 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import numpy as np
import pymc3 as pm
from scipy.stats import kstest
from .base_test import _Base
from .physical import ImpactParameter, QuadLimbDark
class TestPhysical(_Base):
random_seed = 19860925
def test_quad_limb_dark(self):
with self._model():
dist = QuadLimbDark("u", shape=2)
# Test random sampling
samples = dist.random(size=100)
assert np.shape(samples) == (100, 2)
logp = QuadLimbDark.dist(shape=2).logp(samples).eval().flatten()
assert np.all(np.isfinite(logp))
assert np.allclose(logp[0], logp)
trace = self._sample()
u1 = trace["u"][:, 0]
u2 = trace["u"][:, 1]
# Make sure that the physical constraints are satisfied
assert np.all(u1 + u2 < 1)
assert np.all(u1 > 0)
assert np.all(u1 + 2 * u2 > 0)
# Make sure that the qs are uniform
q1 = (u1 + u2) ** 2
q2 = 0.5 * u1 / (u1 + u2)
cdf = lambda x: np.clip(x, 0, 1) # NOQA
for q in (q1, q2):
s, p = kstest(q, cdf)
assert s < 0.05
def test_impact(self):
lower = 0.1
upper = 1.0
with self._model():
ror = pm.Uniform("ror", lower=lower, upper=upper, shape=(5, 2))
dist = ImpactParameter("b", ror=ror)
# Test random sampling
samples = dist.random(size=100)
assert np.shape(samples) == (100, 5, 2)
assert np.all((0 <= samples) & (samples <= 1 + upper))
trace = self._sample()
u = trace["ror"]
u = np.reshape(u, (len(u), -1))
cdf = lambda x: np.clip((x - lower) / (upper - lower), 0, 1) # NOQA
for i in range(u.shape[1]):
s, p = kstest(u[:, i], cdf)
assert s < 0.05
assert np.all(trace["b"] <= 1 + trace["ror"])
| 28.507463 | 76 | 0.517277 |
import numpy as np
import pymc3 as pm
from scipy.stats import kstest
from .base_test import _Base
from .physical import ImpactParameter, QuadLimbDark
class TestPhysical(_Base):
random_seed = 19860925
def test_quad_limb_dark(self):
with self._model():
dist = QuadLimbDark("u", shape=2)
samples = dist.random(size=100)
assert np.shape(samples) == (100, 2)
logp = QuadLimbDark.dist(shape=2).logp(samples).eval().flatten()
assert np.all(np.isfinite(logp))
assert np.allclose(logp[0], logp)
trace = self._sample()
u1 = trace["u"][:, 0]
u2 = trace["u"][:, 1]
assert np.all(u1 + u2 < 1)
assert np.all(u1 > 0)
assert np.all(u1 + 2 * u2 > 0)
q1 = (u1 + u2) ** 2
q2 = 0.5 * u1 / (u1 + u2)
cdf = lambda x: np.clip(x, 0, 1)
for q in (q1, q2):
s, p = kstest(q, cdf)
assert s < 0.05
def test_impact(self):
lower = 0.1
upper = 1.0
with self._model():
ror = pm.Uniform("ror", lower=lower, upper=upper, shape=(5, 2))
dist = ImpactParameter("b", ror=ror)
samples = dist.random(size=100)
assert np.shape(samples) == (100, 5, 2)
assert np.all((0 <= samples) & (samples <= 1 + upper))
trace = self._sample()
u = trace["ror"]
u = np.reshape(u, (len(u), -1))
cdf = lambda x: np.clip((x - lower) / (upper - lower), 0, 1)
for i in range(u.shape[1]):
s, p = kstest(u[:, i], cdf)
assert s < 0.05
assert np.all(trace["b"] <= 1 + trace["ror"])
| true | true |
f710547f67632e5a20d33fad4e5177244d58a71a | 2,670 | py | Python | azure/mgmt/network/v2017_03_01/models/connectivity_information.py | EnjoyLifeFund/Debian_py36_packages | 1985d4c73fabd5f08f54b922e73a9306e09c77a5 | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | 1 | 2022-01-25T22:52:58.000Z | 2022-01-25T22:52:58.000Z | azure/mgmt/network/v2017_03_01/models/connectivity_information.py | EnjoyLifeFund/Debian_py36_packages | 1985d4c73fabd5f08f54b922e73a9306e09c77a5 | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | null | null | null | azure/mgmt/network/v2017_03_01/models/connectivity_information.py | EnjoyLifeFund/Debian_py36_packages | 1985d4c73fabd5f08f54b922e73a9306e09c77a5 | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | null | null | null | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class ConnectivityInformation(Model):
"""Information on the connectivity status.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar hops: List of hops between the source and the destination.
:vartype hops:
list[~azure.mgmt.network.v2017_03_01.models.ConnectivityHop]
:ivar connection_status: The connection status. Possible values include:
'Unknown', 'Connected', 'Disconnected', 'Degraded'
:vartype connection_status: str or
~azure.mgmt.network.v2017_03_01.models.ConnectionStatus
:ivar avg_latency_in_ms: Average latency in milliseconds.
:vartype avg_latency_in_ms: int
:ivar min_latency_in_ms: Minimum latency in milliseconds.
:vartype min_latency_in_ms: int
:ivar max_latency_in_ms: Maximum latency in milliseconds.
:vartype max_latency_in_ms: int
:ivar probes_sent: Total number of probes sent.
:vartype probes_sent: int
:ivar probes_failed: Number of failed probes.
:vartype probes_failed: int
"""
_validation = {
'hops': {'readonly': True},
'connection_status': {'readonly': True},
'avg_latency_in_ms': {'readonly': True},
'min_latency_in_ms': {'readonly': True},
'max_latency_in_ms': {'readonly': True},
'probes_sent': {'readonly': True},
'probes_failed': {'readonly': True},
}
_attribute_map = {
'hops': {'key': 'hops', 'type': '[ConnectivityHop]'},
'connection_status': {'key': 'connectionStatus', 'type': 'str'},
'avg_latency_in_ms': {'key': 'avgLatencyInMs', 'type': 'int'},
'min_latency_in_ms': {'key': 'minLatencyInMs', 'type': 'int'},
'max_latency_in_ms': {'key': 'maxLatencyInMs', 'type': 'int'},
'probes_sent': {'key': 'probesSent', 'type': 'int'},
'probes_failed': {'key': 'probesFailed', 'type': 'int'},
}
def __init__(self):
self.hops = None
self.connection_status = None
self.avg_latency_in_ms = None
self.min_latency_in_ms = None
self.max_latency_in_ms = None
self.probes_sent = None
self.probes_failed = None
| 39.264706 | 76 | 0.63221 |
from msrest.serialization import Model
class ConnectivityInformation(Model):
_validation = {
'hops': {'readonly': True},
'connection_status': {'readonly': True},
'avg_latency_in_ms': {'readonly': True},
'min_latency_in_ms': {'readonly': True},
'max_latency_in_ms': {'readonly': True},
'probes_sent': {'readonly': True},
'probes_failed': {'readonly': True},
}
_attribute_map = {
'hops': {'key': 'hops', 'type': '[ConnectivityHop]'},
'connection_status': {'key': 'connectionStatus', 'type': 'str'},
'avg_latency_in_ms': {'key': 'avgLatencyInMs', 'type': 'int'},
'min_latency_in_ms': {'key': 'minLatencyInMs', 'type': 'int'},
'max_latency_in_ms': {'key': 'maxLatencyInMs', 'type': 'int'},
'probes_sent': {'key': 'probesSent', 'type': 'int'},
'probes_failed': {'key': 'probesFailed', 'type': 'int'},
}
def __init__(self):
self.hops = None
self.connection_status = None
self.avg_latency_in_ms = None
self.min_latency_in_ms = None
self.max_latency_in_ms = None
self.probes_sent = None
self.probes_failed = None
| true | true |
f71055aa651cf305c9a8166cdce7eaafefa9e974 | 29 | py | Python | code/abc039_b_01.py | KoyanagiHitoshi/AtCoder | 731892543769b5df15254e1f32b756190378d292 | [
"MIT"
] | 3 | 2019-08-16T16:55:48.000Z | 2021-04-11T10:21:40.000Z | code/abc039_b_01.py | KoyanagiHitoshi/AtCoder | 731892543769b5df15254e1f32b756190378d292 | [
"MIT"
] | null | null | null | code/abc039_b_01.py | KoyanagiHitoshi/AtCoder | 731892543769b5df15254e1f32b756190378d292 | [
"MIT"
] | null | null | null | print(int(int(input())**.25)) | 29 | 29 | 0.62069 | print(int(int(input())**.25)) | true | true |
f7105759a01a9f8a1433c4a5979ba50ebcbdd63e | 311,762 | py | Python | python/phonenumbers/carrierdata/data0.py | elineda/python-phonenumbers | 112c05ea2c1bf0b346494456832ffd0fef29be63 | [
"Apache-2.0"
] | null | null | null | python/phonenumbers/carrierdata/data0.py | elineda/python-phonenumbers | 112c05ea2c1bf0b346494456832ffd0fef29be63 | [
"Apache-2.0"
] | null | null | null | python/phonenumbers/carrierdata/data0.py | elineda/python-phonenumbers | 112c05ea2c1bf0b346494456832ffd0fef29be63 | [
"Apache-2.0"
] | null | null | null | """Per-prefix data, mapping each prefix to a dict of locale:name.
Auto-generated file, do not edit by hand.
"""
from ..util import u
# Copyright (C) 2011-2020 The Libphonenumber Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
data = {
'1242357':{'en': 'BaTelCo'},
'1242359':{'en': 'BaTelCo'},
'1242375':{'en': 'BaTelCo'},
'1242376':{'en': 'BaTelCo'},
'1242395':{'en': 'BaTelCo'},
'124242':{'en': 'BaTelCo'},
'124243':{'en': 'BaTelCo'},
'124244':{'en': 'BaTelCo'},
'124245':{'en': 'BaTelCo'},
'1242462':{'en': 'BaTelCo'},
'1242463':{'en': 'BaTelCo'},
'1242464':{'en': 'BaTelCo'},
'1242465':{'en': 'BaTelCo'},
'1242466':{'en': 'BaTelCo'},
'1242467':{'en': 'BaTelCo'},
'1242468':{'en': 'BaTelCo'},
'124247':{'en': 'BaTelCo'},
'124248':{'en': 'BaTelCo'},
'124252':{'en': 'BaTelCo'},
'124253':{'en': 'BaTelCo'},
'124254':{'en': 'BaTelCo'},
'124255':{'en': 'BaTelCo'},
'124256':{'en': 'BaTelCo'},
'124257':{'en': 'BaTelCo'},
'124263':{'en': 'BaTelCo'},
'1242646':{'en': 'BaTelCo'},
'124272':{'en': 'BaTelCo'},
'124273':{'en': 'aliv'},
'12428':{'en': 'aliv'},
'124623':{'en': 'LIME'},
'124624':{'en': 'LIME'},
'124625':{'en': 'LIME'},
'1246256':{'en': 'Digicel'},
'1246257':{'en': 'Digicel'},
'1246258':{'en': 'Digicel'},
'1246259':{'en': 'Digicel'},
'124626':{'en': 'Digicel'},
'124628':{'en': 'Cable & Wireless'},
'124645':{'en': 'Sunbeach Communications'},
'124669':{'en': 'Ozone'},
'12468':{'en': 'Digicel'},
'1264469':{'en': 'Cable & Wireless'},
'126453':{'en': 'Weblinks Limited'},
'126458':{'en': 'Digicel'},
'1264729':{'en': 'Cable & Wireless'},
'126477':{'en': 'Cable & Wireless'},
'126871':{'en': 'Digicel'},
'1268720':{'en': 'Digicel'},
'1268721':{'en': 'Digicel'},
'1268722':{'en': 'Digicel'},
'1268724':{'en': 'Digicel'},
'1268725':{'en': 'Digicel'},
'1268726':{'en': 'Digicel'},
'1268727':{'en': 'APUA'},
'1268729':{'en': 'APUA'},
'1268730':{'en': 'APUA'},
'1268732':{'en': 'Digicel'},
'1268734':{'en': 'Digicel'},
'1268736':{'en': 'Digicel'},
'1268773':{'en': 'APUA'},
'1268774':{'en': 'APUA'},
'1268775':{'en': 'APUA'},
'1268780':{'en': 'APUA'},
'1268781':{'en': 'APUA'},
'1268783':{'en': 'Digicel'},
'1268785':{'en': 'Digicel'},
'1268787':{'en': 'Cable & Wireless'},
'1268788':{'en': 'Digicel'},
'128424':{'en': 'Cable & Wireless'},
'1284300':{'en': 'Digicel'},
'128434':{'en': 'Digicel'},
'128436':{'en': 'Digicel'},
'128439':{'en': 'Digicel'},
'128444':{'en': 'CCT'},
'12844689':{'en': 'CCT'},
'12844966':{'en': 'CCT'},
'12844967':{'en': 'CCT'},
'12844968':{'en': 'CCT'},
'12844969':{'en': 'CCT'},
'1284499':{'en': 'CCT'},
'1284546':{'en': 'Cable & Wireless'},
'128456':{'en': 'Cable & Wireless'},
'128459':{'en': 'Cable & Wireless'},
'1340423':{'en': 'Vitelcom Cellular'},
'134044':{'en': 'GIGSKY Mobile'},
'1340725':{'en': 'Vitelcom Cellular'},
'134532':{'en': 'Digicel'},
'134542':{'en': 'Digicel'},
'134551':{'en': 'Digicel'},
'134552':{'en': 'Digicel'},
'134554':{'en': 'Digicel'},
'134555':{'en': 'Digicel'},
'1345649':{'en': 'Digicel'},
'1345919':{'en': 'Cable & Wireless'},
'1345930':{'en': 'LIME'},
'1345936':{'en': 'Cable & Wireless'},
'1345937':{'en': 'Cable & Wireless'},
'1345938':{'en': 'Cable & Wireless'},
'1345939':{'en': 'Cable & Wireless'},
'134599':{'en': 'Cable & Wireless'},
'14412':{'en': 'Cellular One'},
'14413':{'en': 'Mobility'},
'144150':{'en': 'Digicel Bermuda'},
'144151':{'en': 'Digicel Bermuda'},
'144152':{'en': 'Digicel Bermuda'},
'144153':{'en': 'Digicel Bermuda'},
'144159':{'en': 'Digicel Bermuda'},
'14417':{'en': 'Cellular One'},
'14418':{'en': 'Cellular One'},
'1473402':{'en': 'Affordable Island Communications'},
'147341':{'en': 'Digicel Grenada'},
'147342':{'en': 'Digicel Grenada'},
'147352':{'en': 'Affordable Island Communications'},
'147353':{'en': 'AWS Grenada'},
'147390':{'en': 'Affordable Island Communications'},
'164923':{'en': 'C&W'},
'164924':{'en': 'Cable & Wireless'},
'16493':{'en': 'Digicel'},
'164943':{'en': 'Islandcom'},
'1658295':{'en': 'Cable & Wireless'},
'1659200':{'en': 'Onvoy'},
'1659222':{'en': 'Onvoy'},
'1659300':{'en': 'Onvoy'},
'1659400':{'en': 'Onvoy'},
'1659444':{'en': 'Onvoy'},
'1659500':{'en': 'Onvoy'},
'1659529':{'en': 'Fractel'},
'1659600':{'en': 'Onvoy'},
'1659666':{'en': 'Onvoy'},
'1659766':{'en': 'Fractel'},
'1659777':{'en': 'Onvoy'},
'1659800':{'en': 'Onvoy'},
'1659888':{'en': 'Fractel'},
'1659900':{'en': 'Onvoy'},
'1659999':{'en': 'Onvoy'},
'166434':{'en': 'Cable & Wireless'},
'166439':{'en': 'Digicel'},
'1670284':{'en': 'PTI PACIFICA'},
'167148':{'en': 'GTA'},
'167174':{'en': 'PTI PACIFICA'},
'167183':{'en': 'i CAN_GSM'},
'167184':{'en': 'i CAN_GSM'},
'167185':{'en': 'i CAN_GSM'},
'1671864':{'en': 'GTA'},
'1671868':{'en': 'Choice Phone'},
'167187':{'en': 'Choice Phone'},
'167188':{'en': 'Choice Phone'},
'167189':{'en': 'Choice Phone'},
'168424':{'en': 'ASTCA'},
'168425':{'en': 'Blue Sky'},
'168427':{'en': 'Blue Sky'},
'16847':{'en': 'ASTCA'},
'175828':{'en': 'Cable & Wireless'},
'17583':{'en': 'Cable & Wireless'},
'1758460':{'en': 'Cable & Wireless'},
'1758461':{'en': 'Cable & Wireless'},
'1758484':{'en': 'Cable & Wireless'},
'1758485':{'en': 'Cable & Wireless'},
'1758486':{'en': 'Cable & Wireless'},
'1758487':{'en': 'Cable & Wireless'},
'1758488':{'en': 'Cable & Wireless'},
'1758489':{'en': 'Cable & Wireless'},
'175851':{'en': 'Digicel'},
'175852':{'en': 'Digicel'},
'175858':{'en': 'Cable & Wireless'},
'175871':{'en': 'Digicel'},
'175872':{'en': 'Digicel'},
'175873':{'en': 'Digicel'},
'17588':{'en': 'Digicel'},
'176722':{'en': 'Cable & Wireless'},
'176723':{'en': 'Cable & Wireless'},
'176724':{'en': 'Cable & Wireless'},
'1767265':{'en': 'Cable & Wireless'},
'176727':{'en': 'Cable & Wireless'},
'176728':{'en': 'Cable & Wireless'},
'176729':{'en': 'Cable & Wireless'},
'17673':{'en': 'Digicel'},
'17676':{'en': 'Digicel'},
'1767704':{'en': 'Digicel'},
'1767705':{'en': 'Digicel'},
'1767706':{'en': 'Digicel'},
'1784430':{'en': 'AT&T'},
'1784431':{'en': 'AT&T'},
'1784432':{'en': 'AT&T'},
'1784433':{'en': 'Digicel'},
'1784434':{'en': 'Digicel'},
'1784435':{'en': 'Digicel'},
'1784454':{'en': 'Cable & Wireless'},
'1784455':{'en': 'Cable & Wireless'},
'1784489':{'en': 'Cable & Wireless'},
'1784490':{'en': 'Cable & Wireless'},
'1784491':{'en': 'Cable & Wireless'},
'1784492':{'en': 'Cable & Wireless'},
'1784493':{'en': 'Cable & Wireless'},
'1784494':{'en': 'Cable & Wireless'},
'1784495':{'en': 'Cable & Wireless'},
'178452':{'en': 'Digicel'},
'178453':{'en': 'Digicel'},
'178472':{'en': 'Digicel'},
'1787203':{'en': 'Claro'},
'1787210':{'en': 'SunCom Wireless Puerto Rico'},
'1787212':{'en': 'Claro'},
'1787213':{'en': 'Claro'},
'1787214':{'en': 'Claro'},
'1787215':{'en': 'Claro'},
'1787216':{'en': 'Claro'},
'1787217':{'en': 'Claro'},
'1787218':{'en': 'Claro'},
'1787219':{'en': 'Claro'},
'1787220':{'en': 'CENTENNIAL'},
'1787221':{'en': 'CENTENNIAL'},
'1787222':{'en': 'CENTENNIAL'},
'1787223':{'en': 'CENTENNIAL'},
'1787224':{'en': 'CENTENNIAL'},
'1787225':{'en': 'SunCom Wireless Puerto Rico'},
'1787226':{'en': 'SunCom Wireless Puerto Rico'},
'1787227':{'en': 'CENTENNIAL'},
'1787229':{'en': 'CENTENNIAL'},
'1787253':{'en': 'Claro'},
'1787254':{'en': 'Claro'},
'1787255':{'en': 'Claro'},
'1787256':{'en': 'Claro'},
'1787257':{'en': 'Claro'},
'1787258':{'en': 'Claro'},
'1787259':{'en': 'Claro'},
'1787260':{'en': 'Claro'},
'1787291':{'en': 'CENTENNIAL'},
'1787299':{'en': 'SunCom Wireless Puerto Rico'},
'1787300':{'en': 'CENTENNIAL'},
'1787310':{'en': 'SunCom Wireless Puerto Rico'},
'1787312':{'en': 'Claro'},
'1787313':{'en': 'Claro'},
'1787314':{'en': 'Claro'},
'1787315':{'en': 'Claro'},
'1787316':{'en': 'Claro'},
'1787317':{'en': 'Claro'},
'1787318':{'en': 'Claro'},
'17873191':{'en': 'Claro'},
'17873192':{'en': 'Claro'},
'17873193':{'en': 'Claro'},
'17873194':{'en': 'Claro'},
'17873195':{'en': 'Claro'},
'17873196':{'en': 'Claro'},
'17873197':{'en': 'Claro'},
'17873198':{'en': 'Claro'},
'17873199':{'en': 'Claro'},
'1787341':{'en': 'SunCom Wireless Puerto Rico'},
'1787344':{'en': 'SunCom Wireless Puerto Rico'},
'1787346':{'en': 'SunCom Wireless Puerto Rico'},
'1787355':{'en': 'CENTENNIAL'},
'1787357':{'en': 'CENTENNIAL'},
'1787359':{'en': 'SunCom Wireless Puerto Rico'},
'1787367':{'en': 'SunCom Wireless Puerto Rico'},
'1787368':{'en': 'SunCom Wireless Puerto Rico'},
'1787369':{'en': 'CENTENNIAL'},
'1787371':{'en': 'Claro'},
'1787372':{'en': 'Claro'},
'1787374':{'en': 'Claro'},
'1787375':{'en': 'Claro'},
'1787376':{'en': 'Claro'},
'1787380':{'en': 'Claro'},
'1787381':{'en': 'Claro'},
'1787382':{'en': 'Claro'},
'1787383':{'en': 'Claro'},
'1787384':{'en': 'Claro'},
'1787385':{'en': 'Claro'},
'1787389':{'en': 'Claro'},
'1787390':{'en': 'Claro'},
'1787391':{'en': 'Claro'},
'1787392':{'en': 'Claro'},
'1787400':{'en': 'CENTENNIAL'},
'1787410':{'en': 'SunCom Wireless Puerto Rico'},
'1787434':{'en': 'CENTENNIAL'},
'1787447':{'en': 'CENTENNIAL'},
'1787448':{'en': 'CENTENNIAL'},
'1787449':{'en': 'CENTENNIAL'},
'1787450':{'en': 'Claro'},
'1787453':{'en': 'Claro'},
'1787454':{'en': 'SunCom Wireless Puerto Rico'},
'1787458':{'en': 'SunCom Wireless Puerto Rico'},
'1787459':{'en': 'SunCom Wireless Puerto Rico'},
'1787460':{'en': 'SunCom Wireless Puerto Rico'},
'1787462':{'en': 'SunCom Wireless Puerto Rico'},
'1787463':{'en': 'SunCom Wireless Puerto Rico'},
'1787465':{'en': 'CENTENNIAL'},
'1787466':{'en': 'SunCom Wireless Puerto Rico'},
'1787471':{'en': 'CENTENNIAL'},
'1787473':{'en': 'CENTENNIAL'},
'1787474':{'en': 'CENTENNIAL'},
'1787478':{'en': 'SunCom Wireless Puerto Rico'},
'1787479':{'en': 'CENTENNIAL'},
'1787481':{'en': 'Claro'},
'1787484':{'en': 'Claro'},
'1787485':{'en': 'Claro'},
'1787486':{'en': 'Claro'},
'1787487':{'en': 'Claro'},
'1787513':{'en': 'SunCom Wireless Puerto Rico'},
'1787514':{'en': 'Claro'},
'1787515':{'en': 'Claro'},
'1787516':{'en': 'Claro'},
'1787517':{'en': 'Claro'},
'1787518':{'en': 'Claro'},
'1787519':{'en': 'Claro'},
'1787520':{'en': 'CENTENNIAL'},
'1787521':{'en': 'CENTENNIAL'},
'1787522':{'en': 'CENTENNIAL'},
'1787523':{'en': 'CENTENNIAL'},
'1787528':{'en': 'SunCom Wireless Puerto Rico'},
'1787534':{'en': 'CENTENNIAL'},
'1787535':{'en': 'CENTENNIAL'},
'1787537':{'en': 'CENTENNIAL'},
'1787544':{'en': 'CENTENNIAL'},
'1787545':{'en': 'CENTENNIAL'},
'1787546':{'en': 'SunCom Wireless Puerto Rico'},
'1787551':{'en': 'CENTENNIAL'},
'1787553':{'en': 'Claro'},
'1787561':{'en': 'CENTENNIAL'},
'1787563':{'en': 'CENTENNIAL'},
'1787568':{'en': 'SunCom Wireless Puerto Rico'},
'1787569':{'en': 'CENTENNIAL'},
'1787579':{'en': 'Claro'},
'1787580':{'en': 'CENTENNIAL'},
'1787585':{'en': 'CENTENNIAL'},
'1787588':{'en': 'CENTENNIAL'},
'1787589':{'en': 'CENTENNIAL'},
'1787595':{'en': 'SunCom Wireless Puerto Rico'},
'1787597':{'en': 'SunCom Wireless Puerto Rico'},
'1787598':{'en': 'SunCom Wireless Puerto Rico'},
'1787601':{'en': 'SunCom Wireless Puerto Rico'},
'1787602':{'en': 'CENTENNIAL'},
'1787604':{'en': 'SunCom Wireless Puerto Rico'},
'1787605':{'en': 'SunCom Wireless Puerto Rico'},
'1787607':{'en': 'CENTENNIAL'},
'1787608':{'en': 'CENTENNIAL'},
'1787609':{'en': 'CENTENNIAL'},
'1787612':{'en': 'Claro'},
'1787613':{'en': 'Claro'},
'1787614':{'en': 'Claro'},
'1787615':{'en': 'Claro'},
'1787616':{'en': 'Claro'},
'1787617':{'en': 'Claro'},
'1787619':{'en': 'SunCom Wireless Puerto Rico'},
'1787620':{'en': 'CENTENNIAL'},
'1787621':{'en': 'CENTENNIAL'},
'1787622':{'en': 'CENTENNIAL'},
'1787623':{'en': 'CENTENNIAL'},
'1787624':{'en': 'CENTENNIAL'},
'1787625':{'en': 'CENTENNIAL'},
'1787626':{'en': 'CENTENNIAL'},
'1787628':{'en': 'CENTENNIAL'},
'1787629':{'en': 'SunCom Wireless Puerto Rico'},
'178764':{'en': 'CENTENNIAL'},
'178765':{'en': 'CENTENNIAL'},
'1787662':{'en': 'SunCom Wireless Puerto Rico'},
'1787666':{'en': 'SunCom Wireless Puerto Rico'},
'1787673':{'en': 'SunCom Wireless Puerto Rico'},
'1787675':{'en': 'CENTENNIAL'},
'1787678':{'en': 'SunCom Wireless Puerto Rico'},
'1787686':{'en': 'CENTENNIAL'},
'1787687':{'en': 'CENTENNIAL'},
'1787689':{'en': 'CENTENNIAL'},
'1787690':{'en': 'CENTENNIAL'},
'1787692':{'en': 'CENTENNIAL'},
'1787693':{'en': 'CENTENNIAL'},
'1787695':{'en': 'CENTENNIAL'},
'1787717':{'en': 'CENTENNIAL'},
'1787719':{'en': 'CENTENNIAL'},
'1787901':{'en': 'SunCom Wireless Puerto Rico'},
'1787903':{'en': 'CENTENNIAL'},
'1787904':{'en': 'SunCom Wireless Puerto Rico'},
'1787908':{'en': 'CENTENNIAL'},
'1787912':{'en': 'CENTENNIAL'},
'1787915':{'en': 'CENTENNIAL'},
'1787916':{'en': 'CENTENNIAL'},
'1787917':{'en': 'CENTENNIAL'},
'1787922':{'en': 'SunCom Wireless Puerto Rico'},
'1787923':{'en': 'SunCom Wireless Puerto Rico'},
'1787924':{'en': 'CENTENNIAL'},
'1787926':{'en': 'CENTENNIAL'},
'1787927':{'en': 'CENTENNIAL'},
'1787928':{'en': 'CENTENNIAL'},
'1787933':{'en': 'CENTENNIAL'},
'1787935':{'en': 'CENTENNIAL'},
'1787937':{'en': 'CENTENNIAL'},
'1787940':{'en': 'CENTENNIAL'},
'1787947':{'en': 'CENTENNIAL'},
'1787949':{'en': 'SunCom Wireless Puerto Rico'},
'1787952':{'en': 'CENTENNIAL'},
'1787953':{'en': 'CENTENNIAL'},
'1787954':{'en': 'CENTENNIAL'},
'1787957':{'en': 'CENTENNIAL'},
'1787961':{'en': 'CENTENNIAL'},
'1787968':{'en': 'CENTENNIAL'},
'1787969':{'en': 'CENTENNIAL'},
'1787971':{'en': 'CENTENNIAL'},
'1787975':{'en': 'CENTENNIAL'},
'1787978':{'en': 'CENTENNIAL'},
'1787992':{'en': 'CENTENNIAL'},
'1787993':{'en': 'CENTENNIAL'},
'1787998':{'en': 'CENTENNIAL'},
'1787999':{'en': 'CENTENNIAL'},
'180920':{'en': 'Tricom'},
'180922':{'en': 'Claro'},
'180923':{'en': 'Claro'},
'180924':{'en': 'Claro'},
'180925':{'en': 'Claro'},
'180926':{'en': 'Claro'},
'180927':{'en': 'Claro'},
'180928':{'en': 'Claro'},
'180929':{'en': 'Tricom'},
'18093':{'en': 'Claro'},
'180930':{'en': 'Viva'},
'180931':{'en': 'Tricom'},
'180932':{'en': 'Tricom'},
'180934':{'en': 'Tricom'},
'180941':{'en': 'Viva'},
'180942':{'en': 'Claro'},
'180943':{'en': 'Viva'},
'180944':{'en': 'Viva'},
'180945':{'en': 'Claro'},
'180947':{'en': 'Tricom'},
'180948':{'en': 'Claro'},
'180949':{'en': 'Claro'},
'180951':{'en': 'Claro'},
'180954':{'en': 'Claro'},
'180960':{'en': 'Claro'},
'180962':{'en': 'Tricom'},
'180963':{'en': 'Tricom'},
'180964':{'en': 'Tricom'},
'180965':{'en': 'Tricom'},
'180967':{'en': 'Claro'},
'180969':{'en': 'Claro'},
'180970':{'en': 'Claro'},
'180971':{'en': 'Claro'},
'180972':{'en': 'Claro'},
'180974':{'en': 'Claro'},
'180975':{'en': 'Claro'},
'180976':{'en': 'Claro'},
'180977':{'en': 'Viva'},
'180978':{'en': 'Claro'},
'180979':{'en': 'Claro'},
'18098':{'en': 'Orange'},
'180981':{'en': 'Viva'},
'180982':{'en': 'Claro'},
'180983':{'en': 'Claro'},
'180987':{'en': 'Tricom'},
'180991':{'en': 'Orange'},
'180992':{'en': 'Tricom'},
'180993':{'en': 'Tricom'},
'180994':{'en': 'Tricom'},
'180995':{'en': 'Claro'},
'180997':{'en': 'Orange'},
'180998':{'en': 'Orange'},
'180999':{'en': 'Tricom'},
'1868263':{'en': 'Digicel'},
'1868264':{'en': 'Digicel'},
'1868265':{'en': 'Digicel'},
'1868266':{'en': 'bmobile'},
'1868267':{'en': 'bmobile'},
'1868268':{'en': 'bmobile'},
'1868269':{'en': 'bmobile'},
'186827':{'en': 'bmobile'},
'186828':{'en': 'bmobile'},
'186829':{'en': 'bmobile'},
'18683':{'en': 'Digicel'},
'18684':{'en': 'bmobile'},
'1868620':{'en': 'bmobile'},
'1868678':{'en': 'bmobile'},
'186868':{'en': 'bmobile'},
'18687':{'en': 'bmobile'},
'186948':{'en': 'Cable & Wireless'},
'186955':{'en': 'CariGlobe St. Kitts'},
'186956':{'en': 'The Cable St. Kitts'},
'1869660':{'en': 'Cable & Wireless'},
'1869661':{'en': 'Cable & Wireless'},
'1869662':{'en': 'Cable & Wireless'},
'1869663':{'en': 'Cable & Wireless'},
'1869664':{'en': 'Cable & Wireless'},
'1869665':{'en': 'Cable & Wireless'},
'1869667':{'en': 'Cable & Wireless'},
'1869668':{'en': 'Cable & Wireless'},
'1869669':{'en': 'Cable & Wireless'},
'1869760':{'en': 'Digicel'},
'1869762':{'en': 'Digicel'},
'1869763':{'en': 'Digicel'},
'1869764':{'en': 'Digicel'},
'1869765':{'en': 'Digicel'},
'1869766':{'en': 'Digicel'},
'1876210':{'en': 'Cable & Wireless'},
'187622':{'en': 'Cable & Wireless'},
'187623':{'en': 'Cable & Wireless'},
'187624':{'en': 'Digicel'},
'187625':{'en': 'Digicel'},
'187626':{'en': 'Digicel'},
'1876275':{'en': 'Digicel'},
'1876276':{'en': 'Digicel'},
'1876277':{'en': 'Digicel'},
'1876278':{'en': 'Digicel'},
'1876279':{'en': 'Digicel'},
'187628':{'en': 'Digicel'},
'187629':{'en': 'Digicel'},
'187630':{'en': 'Digicel'},
'1876310':{'en': 'Cable & Wireless'},
'1876312':{'en': 'Cable & Wireless'},
'1876313':{'en': 'Cable & Wireless'},
'1876314':{'en': 'Cable & Wireless'},
'1876315':{'en': 'Cable & Wireless'},
'1876316':{'en': 'Cable & Wireless'},
'1876317':{'en': 'Cable & Wireless'},
'1876318':{'en': 'Cable & Wireless'},
'1876319':{'en': 'Cable & Wireless'},
'187632':{'en': 'Cable & Wireless'},
'187633':{'en': 'Cable & Wireless'},
'187634':{'en': 'Cable & Wireless'},
'187635':{'en': 'Digicel'},
'187636':{'en': 'Digicel'},
'187637':{'en': 'Digicel'},
'187638':{'en': 'Digicel'},
'187639':{'en': 'Digicel'},
'187640':{'en': 'Digicel'},
'187641':{'en': 'Digicel'},
'187642':{'en': 'Digicel'},
'187643':{'en': 'Digicel'},
'1876440':{'en': 'Digicel'},
'1876441':{'en': 'Digicel'},
'1876442':{'en': 'Digicel'},
'1876443':{'en': 'Digicel'},
'1876445':{'en': 'Digicel'},
'1876446':{'en': 'Digicel'},
'1876447':{'en': 'Digicel'},
'1876448':{'en': 'Digicel'},
'1876449':{'en': 'Digicel'},
'187645':{'en': 'Digicel'},
'187646':{'en': 'Digicel'},
'187647':{'en': 'Digicel'},
'187648':{'en': 'Digicel'},
'187649':{'en': 'Digicel'},
'1876501':{'en': 'Cable & Wireless'},
'1876503':{'en': 'Digicel'},
'1876504':{'en': 'Digicel'},
'1876505':{'en': 'Digicel'},
'1876506':{'en': 'Digicel'},
'1876507':{'en': 'Digicel'},
'1876508':{'en': 'Digicel'},
'1876509':{'en': 'Digicel'},
'1876515':{'en': 'Cable & Wireless'},
'1876517':{'en': 'Cable & Wireless'},
'1876519':{'en': 'Cable & Wireless'},
'187652':{'en': 'Digicel'},
'187653':{'en': 'Cable & Wireless'},
'187654':{'en': 'Cable & Wireless'},
'1876550':{'en': 'Digicel'},
'1876551':{'en': 'Digicel'},
'1876552':{'en': 'Digicel'},
'1876553':{'en': 'Digicel'},
'1876554':{'en': 'Digicel'},
'1876556':{'en': 'Digicel'},
'1876557':{'en': 'Digicel'},
'1876558':{'en': 'Digicel'},
'1876559':{'en': 'Digicel'},
'1876560':{'en': 'Digicel'},
'1876561':{'en': 'Digicel'},
'1876562':{'en': 'Digicel'},
'1876564':{'en': 'Digicel'},
'1876565':{'en': 'Digicel'},
'1876566':{'en': 'Digicel'},
'1876567':{'en': 'Digicel'},
'1876568':{'en': 'Digicel'},
'1876569':{'en': 'Digicel'},
'187657':{'en': 'Digicel'},
'187658':{'en': 'Digicel'},
'187659':{'en': 'Digicel'},
'1876648':{'en': 'Digicel'},
'1876649':{'en': 'Digicel'},
'1876666':{'en': 'Digicel'},
'1876667':{'en': 'Digicel'},
'1876700':{'en': 'Cable & Wireless'},
'1876707':{'en': 'Cable & Wireless'},
'187677':{'en': 'Cable & Wireless'},
'1876781':{'en': 'Cable & Wireless'},
'1876782':{'en': 'Cable & Wireless'},
'1876783':{'en': 'Cable & Wireless'},
'1876784':{'en': 'Cable & Wireless'},
'1876787':{'en': 'Cable & Wireless'},
'1876788':{'en': 'Cable & Wireless'},
'1876789':{'en': 'Cable & Wireless'},
'1876790':{'en': 'Cable & Wireless'},
'1876791':{'en': 'Cable & Wireless'},
'1876792':{'en': 'Cable & Wireless'},
'1876793':{'en': 'Cable & Wireless'},
'1876796':{'en': 'Cable & Wireless'},
'1876797':{'en': 'Cable & Wireless'},
'1876798':{'en': 'Cable & Wireless'},
'1876799':{'en': 'Cable & Wireless'},
'187680':{'en': 'Cable & Wireless'},
'1876810':{'en': 'Cable & Wireless'},
'1876812':{'en': 'Cable & Wireless'},
'1876813':{'en': 'Cable & Wireless'},
'1876814':{'en': 'Cable & Wireless'},
'1876815':{'en': 'Cable & Wireless'},
'1876816':{'en': 'Cable & Wireless'},
'1876817':{'en': 'Cable & Wireless'},
'1876818':{'en': 'Cable & Wireless'},
'1876819':{'en': 'Cable & Wireless'},
'187682':{'en': 'Cable & Wireless'},
'187683':{'en': 'Cable & Wireless'},
'187684':{'en': 'Digicel'},
'187685':{'en': 'Digicel'},
'187686':{'en': 'Digicel'},
'187687':{'en': 'Digicel'},
'187688':{'en': 'Digicel'},
'187689':{'en': 'Digicel'},
'1876909':{'en': 'Cable & Wireless'},
'1876919':{'en': 'Cable & Wireless'},
'1876990':{'en': 'Cable & Wireless'},
'1876995':{'en': 'Cable & Wireless'},
'1876997':{'en': 'Cable & Wireless'},
'1876999':{'en': 'Cable & Wireless'},
'1939201':{'en': 'CENTENNIAL'},
'1939212':{'en': 'CENTENNIAL'},
'1939214':{'en': 'CENTENNIAL'},
'1939240':{'en': 'SunCom Wireless Puerto Rico'},
'19392410':{'en': 'Claro'},
'19392411':{'en': 'Claro'},
'19392412':{'en': 'Claro'},
'19392413':{'en': 'Claro'},
'19392414':{'en': 'Claro'},
'19392415':{'en': 'Claro'},
'19392416':{'en': 'Claro'},
'193924199':{'en': 'Claro'},
'1939242':{'en': 'Claro'},
'19392433':{'en': 'Claro'},
'19392434':{'en': 'Claro'},
'19392435':{'en': 'Claro'},
'19392436':{'en': 'Claro'},
'19392437':{'en': 'Claro'},
'19392438':{'en': 'Claro'},
'19392439':{'en': 'Claro'},
'1939244':{'en': 'Claro'},
'1939245':{'en': 'Claro'},
'1939246':{'en': 'Claro'},
'1939247':{'en': 'Claro'},
'1939248':{'en': 'Claro'},
'1939249':{'en': 'Claro'},
'193925':{'en': 'Claro'},
'1939252':{'en': 'CENTENNIAL'},
'1939307':{'en': 'CENTENNIAL'},
'1939325':{'en': 'SunCom Wireless Puerto Rico'},
'1939329':{'en': 'CENTENNIAL'},
'1939334':{'en': 'Claro'},
'1939339':{'en': 'SunCom Wireless Puerto Rico'},
'1939394':{'en': 'CENTENNIAL'},
'1939440':{'en': 'CENTENNIAL'},
'1939628':{'en': 'CENTENNIAL'},
'1939630':{'en': 'CENTENNIAL'},
'1939639':{'en': 'CENTENNIAL'},
'1939640':{'en': 'CENTENNIAL'},
'1939642':{'en': 'CENTENNIAL'},
'1939644':{'en': 'CENTENNIAL'},
'1939645':{'en': 'CENTENNIAL'},
'1939697':{'en': 'CENTENNIAL'},
'1939717':{'en': 'CENTENNIAL'},
'1939731':{'en': 'CENTENNIAL'},
'1939777':{'en': 'Claro'},
'1939865':{'en': 'SunCom Wireless Puerto Rico'},
'1939891':{'en': 'SunCom Wireless Puerto Rico'},
'1939910':{'en': 'CENTENNIAL'},
'1939940':{'en': 'CENTENNIAL'},
'1939969':{'en': 'CENTENNIAL'},
'2010':{'en': 'Vodafone'},
'2011':{'en': 'Etisalat'},
'2012':{'en': 'Orange'},
'2015':{'en': 'TE'},
'21112':{'en': 'Sudatel Group'},
'21191':{'en': 'Zain'},
'21192':{'en': 'MTN'},
'21195':{'en': 'Network of the World'},
'21197':{'en': 'Gemtel'},
'21199':{'en': 'MTN'},
'21260':{'en': 'Inwi'},
'21261':{'en': 'Maroc Telecom'},
'212612':{'en': u('M\u00e9ditel')},
'212614':{'en': u('M\u00e9ditel')},
'212617':{'en': u('M\u00e9ditel')},
'212619':{'en': u('M\u00e9ditel')},
'212620':{'en': u('M\u00e9ditel')},
'212621':{'en': u('M\u00e9ditel')},
'212622':{'en': 'Maroc Telecom'},
'212623':{'en': 'Maroc Telecom'},
'212624':{'en': 'Maroc Telecom'},
'212625':{'en': u('M\u00e9ditel')},
'212626':{'en': 'Inwi'},
'212627':{'en': 'Inwi'},
'212628':{'en': 'Maroc Telecom'},
'212629':{'en': 'Inwi'},
'212630':{'en': 'Inwi'},
'212631':{'en': u('M\u00e9ditel')},
'212632':{'en': u('M\u00e9ditel')},
'212633':{'en': 'Inwi'},
'212634':{'en': 'Inwi'},
'212635':{'en': 'Inwi'},
'212636':{'en': 'Maroc Telecom'},
'212637':{'en': 'Maroc Telecom'},
'212638':{'en': 'Inwi'},
'212639':{'en': 'Maroc Telecom'},
'212640':{'en': 'Inwi'},
'212641':{'en': 'Maroc Telecom'},
'212642':{'en': 'Maroc Telecom'},
'212643':{'en': 'Maroc Telecom'},
'212644':{'en': u('M\u00e9ditel')},
'212645':{'en': u('M\u00e9ditel')},
'212646':{'en': 'Inwi'},
'212647':{'en': 'Inwi'},
'212648':{'en': 'Maroc Telecom'},
'212649':{'en': u('M\u00e9ditel')},
'21265':{'en': 'Maroc Telecom'},
'212656':{'en': u('M\u00e9ditel')},
'212657':{'en': u('M\u00e9ditel')},
'212660':{'en': u('M\u00e9ditel')},
'212661':{'en': 'Maroc Telecom'},
'212662':{'en': 'Maroc Telecom'},
'212663':{'en': u('M\u00e9ditel')},
'212664':{'en': u('M\u00e9ditel')},
'212665':{'en': u('M\u00e9ditel')},
'212666':{'en': 'Maroc Telecom'},
'212667':{'en': 'Maroc Telecom'},
'212668':{'en': 'Maroc Telecom'},
'212669':{'en': u('M\u00e9ditel')},
'21267':{'en': 'Maroc Telecom'},
'212674':{'en': u('M\u00e9ditel')},
'212675':{'en': u('M\u00e9ditel')},
'212679':{'en': u('M\u00e9ditel')},
'212680':{'en': 'Inwi'},
'212681':{'en': 'Inwi'},
'212682':{'en': 'Maroc Telecom'},
'212684':{'en': u('M\u00e9ditel')},
'212687':{'en': 'Inwi'},
'212688':{'en': u('M\u00e9ditel')},
'212689':{'en': 'Maroc Telecom'},
'212690':{'en': 'Inwi'},
'212691':{'en': u('M\u00e9ditel')},
'2126921':{'en': 'Al Hourria Telecom'},
'2126922':{'en': 'Al Hourria Telecom'},
'212693':{'en': u('M\u00e9ditel')},
'212694':{'en': u('M\u00e9ditel')},
'212695':{'en': 'Inwi'},
'212696':{'en': 'Maroc Telecom'},
'212697':{'en': 'Maroc Telecom'},
'212698':{'en': 'Inwi'},
'212699':{'en': 'Inwi'},
'212700':{'en': 'Inwi'},
'212706':{'en': 'Inwi'},
'212707':{'en': 'Inwi'},
'212708':{'en': 'Inwi'},
'21276':{'en': 'Maroc Telecom'},
'21277':{'en': u('M\u00e9ditel')},
'2135':{'en': 'Ooredoo'},
'2136':{'en': 'Mobilis'},
'2137':{'en': 'Djezzy'},
'2162':{'en': 'Ooredoo'},
'21640':{'en': 'Tunisie Telecom'},
'21641':{'en': 'Tunisie Telecom'},
'21642':{'en': 'Tunisie Telecom'},
'21643':{'en': 'Lyca Mobile'},
'21644':{'en': 'Tunisie Telecom'},
'21645':{'en': 'Watany Ettisalat'},
'21646':{'en': 'Ooredoo'},
'21647':{'en': 'Tunisie Telecom'},
'2165':{'en': 'Orange'},
'2169':{'en': 'Tunisie Telecom'},
'21891':{'en': 'Al-Madar'},
'21892':{'en': 'Libyana'},
'21893':{'en': 'Al-Madar'},
'21894':{'en': 'Libyana'},
'21895':{'en': 'Libya Telecom & Technology'},
'21896':{'en': 'Libya Telecom & Technology'},
'2202':{'en': 'Africell'},
'2203':{'en': 'QCell'},
'22050':{'en': 'QCell'},
'22051':{'en': 'QCell'},
'22052':{'en': 'QCell'},
'22053':{'en': 'QCell'},
'22058':{'en': 'QCell'},
'22059':{'en': 'QCell'},
'2206':{'en': 'Comium'},
'2207':{'en': 'Africell'},
'2209':{'en': 'Gamcel'},
'22170':{'en': 'Expresso'},
'22172':{'en': 'HAYO'},
'22176':{'en': 'Tigo'},
'22177':{'en': 'Orange'},
'22178':{'en': 'Orange'},
'22179':{'en': 'ADIE'},
'22220':{'en': 'Chinguitel'},
'22221':{'en': 'Chinguitel'},
'22222':{'en': 'Chinguitel'},
'22223':{'en': 'Chinguitel'},
'22224':{'en': 'Chinguitel'},
'22226':{'en': 'Chinguitel'},
'22227':{'en': 'Chinguitel'},
'22228':{'en': 'Chinguitel'},
'22229':{'en': 'Chinguitel'},
'22230':{'en': 'Mattel'},
'22231':{'en': 'Mattel'},
'22232':{'en': 'Mattel'},
'22233':{'en': 'Mattel'},
'22234':{'en': 'Mattel'},
'22236':{'en': 'Mattel'},
'22237':{'en': 'Mattel'},
'22238':{'en': 'Mattel'},
'22239':{'en': 'Mattel'},
'22240':{'en': 'Mauritel'},
'22241':{'en': 'Mauritel'},
'22242':{'en': 'Mauritel'},
'22243':{'en': 'Mauritel'},
'22244':{'en': 'Mauritel'},
'22246':{'en': 'Mauritel'},
'22247':{'en': 'Mauritel'},
'22248':{'en': 'Mauritel'},
'22249':{'en': 'Mauritel'},
'223200':{'en': 'Orange'},
'2232079':{'en': 'Sotelma'},
'223217':{'en': 'Sotelma'},
'2235':{'en': 'Atel'},
'2236':{'en': 'Sotelma'},
'2237':{'en': 'Orange'},
'22382':{'en': 'Orange'},
'22383':{'en': 'Orange'},
'22389':{'en': 'Sotelma'},
'22390':{'en': 'Orange'},
'22391':{'en': 'Orange'},
'22392':{'en': 'Orange'},
'22393':{'en': 'Orange'},
'22394':{'en': 'Orange'},
'22395':{'en': 'Sotelma'},
'22396':{'en': 'Sotelma'},
'22397':{'en': 'Sotelma'},
'22398':{'en': 'Sotelma'},
'22399':{'en': 'Sotelma'},
'22460':{'en': 'Sotelgui'},
'22462':{'en': 'Orange'},
'22463':{'en': 'Intercel'},
'22465':{'en': 'Cellcom'},
'22466':{'en': 'Areeba'},
'22501':{'en': 'Moov'},
'22502':{'en': 'Moov'},
'22503':{'en': 'Moov'},
'22504':{'en': 'MTN'},
'22505':{'en': 'MTN'},
'22506':{'en': 'MTN'},
'22507':{'en': 'Orange'},
'22508':{'en': 'Orange'},
'22509':{'en': 'Orange'},
'225208':{'en': 'Moov'},
'225218':{'en': 'Moov'},
'225228':{'en': 'Moov'},
'225238':{'en': 'Moov'},
'22540':{'en': 'Moov'},
'22541':{'en': 'Moov'},
'22542':{'en': 'Moov'},
'22543':{'en': 'Moov'},
'22544':{'en': 'MTN'},
'22545':{'en': 'MTN'},
'22546':{'en': 'MTN'},
'22547':{'en': 'Orange'},
'22548':{'en': 'Orange'},
'22549':{'en': 'Orange'},
'22550':{'en': 'Moov'},
'22551':{'en': 'Moov'},
'22552':{'en': 'Moov'},
'22553':{'en': 'Moov'},
'22554':{'en': 'MTN'},
'22555':{'en': 'MTN'},
'22556':{'en': 'MTN'},
'22557':{'en': 'Orange'},
'22558':{'en': 'Orange'},
'22559':{'en': 'Orange'},
'22560':{'en': 'GreenN'},
'22561':{'en': 'GreenN'},
'22564':{'en': 'MTN'},
'22565':{'en': 'MTN'},
'22566':{'en': 'MTN'},
'22567':{'en': 'Orange'},
'22568':{'en': 'Orange'},
'22569':{'en': 'Aircom'},
'22570':{'en': 'Moov'},
'22571':{'en': 'Moov'},
'22572':{'en': 'Moov'},
'22573':{'en': 'Moov'},
'22574':{'en': 'MTN'},
'22575':{'en': 'MTN'},
'22576':{'en': 'MTN'},
'22577':{'en': 'Orange'},
'22578':{'en': 'Orange'},
'22579':{'en': 'Orange'},
'22584':{'en': 'MTN'},
'22585':{'en': 'MTN'},
'22586':{'en': 'MTN'},
'22587':{'en': 'Orange'},
'22588':{'en': 'Orange'},
'22589':{'en': 'Orange'},
'22595':{'en': 'MTN'},
'22597':{'en': 'Orange'},
'22601':{'en': 'Onatel'},
'22602':{'en': 'Onatel'},
'22607':{'en': 'Orange'},
'22651':{'en': 'Telmob'},
'22652':{'en': 'Telmob'},
'22653':{'en': 'Onatel'},
'22654':{'en': 'Orange'},
'22655':{'en': 'Orange'},
'22656':{'en': 'Orange'},
'22657':{'en': 'Orange'},
'22658':{'en': 'Telecel Faso'},
'22660':{'en': 'Telmob'},
'22661':{'en': 'Telmob'},
'22662':{'en': 'Telmob'},
'22663':{'en': 'Telmob'},
'22664':{'en': 'Orange'},
'22665':{'en': 'Orange'},
'22666':{'en': 'Orange'},
'22667':{'en': 'Orange'},
'22668':{'en': 'Telecel Faso'},
'22669':{'en': 'Telecel Faso'},
'22670':{'en': 'Telmob'},
'22671':{'en': 'Telmob'},
'22672':{'en': 'Telmob'},
'22673':{'en': 'Telmob'},
'22674':{'en': 'Orange'},
'22675':{'en': 'Orange'},
'22676':{'en': 'Orange'},
'22677':{'en': 'Orange'},
'22678':{'en': 'Telecel Faso'},
'22679':{'en': 'Telecel Faso'},
'22723':{'en': 'Orange'},
'22780':{'en': 'Orange'},
'22781':{'en': 'Orange'},
'22788':{'en': 'Airtel'},
'22789':{'en': 'Airtel'},
'22790':{'en': 'Orange'},
'22791':{'en': 'Orange'},
'22792':{'en': 'Orange'},
'22793':{'en': 'SahelCom'},
'22794':{'en': 'Moov'},
'22795':{'en': 'Moov'},
'22796':{'en': 'Airtel'},
'22797':{'en': 'Airtel'},
'22798':{'en': 'Airtel'},
'22799':{'en': 'Airtel'},
'22870':{'en': 'TOGOCEL'},
'22879':{'en': 'Moov'},
'22890':{'en': 'TOGOCEL'},
'22891':{'en': 'TOGOCEL'},
'22892':{'en': 'TOGOCEL'},
'22893':{'en': 'TOGOCEL'},
'22896':{'en': 'Moov'},
'22897':{'en': 'TOGOCEL'},
'22898':{'en': 'Moov'},
'22899':{'en': 'Moov'},
'2295':{'en': 'MTN'},
'22960':{'en': 'Moov'},
'22961':{'en': 'MTN'},
'22962':{'en': 'MTN'},
'22963':{'en': 'Moov'},
'22964':{'en': 'Moov'},
'22965':{'en': 'Moov'},
'22966':{'en': 'MTN'},
'22967':{'en': 'MTN'},
'22968':{'en': 'Moov'},
'22969':{'en': 'MTN'},
'22990':{'en': 'Moov'},
'22991':{'en': 'Moov'},
'22993':{'en': 'BLK'},
'22994':{'en': 'Moov'},
'22995':{'en': 'Moov'},
'22997':{'en': 'MTN'},
'22998':{'en': 'Moov'},
'22999':{'en': 'Moov'},
'230525':{'en': 'Cellplus'},
'230528':{'en': 'MTML'},
'230529':{'en': 'MTML'},
'23054':{'en': 'Emtel'},
'2305471':{'en': 'Cellplus'},
'23057':{'en': 'Cellplus'},
'230571':{'en': 'Emtel'},
'230572':{'en': 'Emtel'},
'230573':{'en': 'Emtel'},
'230574':{'en': 'Emtel'},
'230580':{'en': 'Cellplus'},
'230581':{'en': 'Cellplus'},
'230582':{'en': 'Cellplus'},
'230583':{'en': 'Cellplus'},
'230584':{'en': 'Emtel'},
'230585':{'en': 'Emtel'},
'230586':{'en': 'MTML'},
'2305871':{'en': 'MTML'},
'2305875':{'en': 'Cellplus'},
'2305876':{'en': 'Cellplus'},
'2305877':{'en': 'Cellplus'},
'2305878':{'en': 'Cellplus'},
'230588':{'en': 'MTML'},
'230589':{'en': 'MTML'},
'230590':{'en': 'Cellplus'},
'230591':{'en': 'Cellplus'},
'230592':{'en': 'Cellplus'},
'230593':{'en': 'Emtel'},
'230594':{'en': 'Cellplus'},
'230595':{'en': 'MTML'},
'230596':{'en': 'MTML'},
'230597':{'en': 'Emtel'},
'230598':{'en': 'Emtel'},
'231330':{'en': 'West Africa Telecom'},
'231555':{'en': 'Lonestar Cell'},
'2316':{'en': 'Lonestar Cell'},
'2317':{'en': 'Orange'},
'2318':{'en': 'Lonestar Cell'},
'23225':{'en': 'Sierratel'},
'23230':{'en': 'Africell'},
'23231':{'en': 'QCELL'},
'23233':{'en': 'Africell'},
'23234':{'en': 'QCELL'},
'23235':{'en': 'IPTEL'},
'2326':{'en': 'Onlime'},
'23274':{'en': 'Orange'},
'23275':{'en': 'Orange'},
'23276':{'en': 'Orange'},
'23277':{'en': 'Africell'},
'23278':{'en': 'Orange'},
'23279':{'en': 'Orange'},
'2328':{'en': 'Africell'},
'2329':{'en': 'Africell'},
'23320':{'en': 'Vodafone'},
'23323':{'en': 'Globacom (Zain)'},
'23324':{'en': 'MTN'},
'23326':{'en': 'Airtel'},
'23327':{'en': 'tiGO'},
'23328':{'en': 'Expresso'},
'23350':{'en': 'Vodafone'},
'23354':{'en': 'MTN'},
'23355':{'en': 'MTN'},
'23356':{'en': 'Airtel'},
'23357':{'en': 'tiGO'},
'23359':{'en': 'MTN'},
'234701':{'en': 'Airtel'},
'2347020':{'en': 'Smile'},
'2347021':{'en': 'Ntel'},
'2347022':{'en': 'Ntel'},
'2347024':{'en': 'Prestel'},
'2347025':{'en': 'Visafone'},
'2347026':{'en': 'Visafone'},
'2347027':{'en': 'Multilinks'},
'2347028':{'en': 'Starcomms'},
'2347029':{'en': 'Starcomms'},
'234703':{'en': 'MTN'},
'234704':{'en': 'Visafone'},
'234705':{'en': 'Glo'},
'234706':{'en': 'MTN'},
'234708':{'en': 'Airtel'},
'234709':{'en': 'Multilinks'},
'234801':{'en': 'Megatech'},
'234802':{'en': 'Airtel'},
'234803':{'en': 'MTN'},
'234804':{'en': 'Ntel'},
'234805':{'en': 'Glo'},
'234806':{'en': 'MTN'},
'234807':{'en': 'Glo'},
'234808':{'en': 'Airtel'},
'234809':{'en': '9mobile'},
'234810':{'en': 'MTN'},
'234811':{'en': 'Glo'},
'234812':{'en': 'Airtel'},
'234813':{'en': 'MTN'},
'234814':{'en': 'MTN'},
'234815':{'en': 'Glo'},
'234816':{'en': 'MTN'},
'234817':{'en': '9mobile'},
'234818':{'en': '9mobile'},
'234819':{'en': 'Starcomms'},
'234901':{'en': 'Airtel'},
'234902':{'en': 'Airtel'},
'234903':{'en': 'MTN'},
'234904':{'en': 'Airtel'},
'234905':{'en': 'Glo'},
'234906':{'en': 'MTN'},
'234907':{'en': 'Airtel'},
'234908':{'en': '9mobile'},
'234909':{'en': '9mobile'},
'2356':{'en': 'Airtel'},
'2357':{'en': 'Sotel'},
'2359':{'en': 'Tigo'},
'23670':{'en': 'A-Cell'},
'23672':{'en': 'Orange'},
'23675':{'en': 'Telecel'},
'23677':{'en': 'Nationlink'},
'237650':{'en': 'MTN Cameroon'},
'237651':{'en': 'MTN Cameroon'},
'237652':{'en': 'MTN Cameroon'},
'237653':{'en': 'MTN Cameroon'},
'237654':{'en': 'MTN Cameroon'},
'237655':{'en': 'Orange'},
'237656':{'en': 'Orange'},
'237657':{'en': 'Orange'},
'237658':{'en': 'Orange'},
'237659':{'en': 'Orange'},
'23766':{'en': 'NEXTTEL'},
'23767':{'en': 'MTN Cameroon'},
'23768':{'en': 'NEXTTEL'},
'237680':{'en': 'MTN Cameroon'},
'237681':{'en': 'MTN Cameroon'},
'237682':{'en': 'MTN Cameroon'},
'237683':{'en': 'MTN Cameroon'},
'23769':{'en': 'Orange'},
'23833':{'en': 'T+'},
'23836':{'en': 'CVMOVEL'},
'23843':{'en': 'T+'},
'23846':{'en': 'CVMOVEL'},
'23851':{'en': 'T+'},
'23852':{'en': 'T+'},
'23853':{'en': 'T+'},
'23858':{'en': 'CVMOVEL'},
'23859':{'en': 'CVMOVEL'},
'23891':{'en': 'T+'},
'23892':{'en': 'T+'},
'23893':{'en': 'T+'},
'23895':{'en': 'CVMOVEL'},
'23897':{'en': 'CVMOVEL'},
'23898':{'en': 'CVMOVEL'},
'23899':{'en': 'CVMOVEL'},
'23990':{'en': 'Unitel'},
'23998':{'en': 'CSTmovel'},
'23999':{'en': 'CSTmovel'},
'2402':{'en': 'GETESA'},
'240550':{'en': 'Muni'},
'240551':{'en': 'HiTS'},
'24104':{'en': 'Airtel'},
'24105':{'en': 'Moov'},
'24106':{'en': 'Libertis'},
'24107':{'en': 'Airtel'},
'24120':{'en': 'Libertis'},
'24121':{'en': 'Libertis'},
'24122':{'en': 'Libertis'},
'24123':{'en': 'Libertis'},
'24124':{'en': 'Libertis'},
'24125':{'en': 'Libertis'},
'24126':{'en': 'Libertis'},
'24127':{'en': 'Libertis'},
'2413':{'en': 'Libertis'},
'2414':{'en': 'Airtel'},
'2415':{'en': 'Moov'},
'2416':{'en': 'Libertis'},
'24165':{'en': 'Moov'},
'2417':{'en': 'Airtel'},
'24201':{'en': 'Equateur Telecom'},
'24204':{'en': 'Warid'},
'24205':{'en': 'Airtel'},
'24206':{'en': 'MTN'},
'24380':{'en': 'Supercell'},
'24381':{'en': 'Vodacom'},
'24382':{'en': 'Vodacom'},
'24384':{'en': 'CCT'},
'24388':{'en': 'Yozma Timeturns sprl -YTT'},
'24389':{'en': 'Sait-Telecom (Oasis)'},
'24390':{'en': 'Africell'},
'24391':{'en': 'Africell'},
'24397':{'en': 'Zain'},
'24398':{'en': 'Zain'},
'24399':{'en': 'Zain'},
'24491':{'en': 'Movicel'},
'24492':{'en': 'UNITEL'},
'24493':{'en': 'UNITEL'},
'24494':{'en': 'UNITEL'},
'24499':{'en': 'Movicel'},
'24595':{'en': 'Orange'},
'24596':{'en': 'Spacetel'},
'24597':{'en': 'Guinetel'},
'24638':{'en': 'Sure Ltd'},
'24741':{'en': 'Sure South Atlantic'},
'24742':{'en': 'Sure South Atlantic'},
'24743':{'en': 'Sure South Atlantic'},
'24745':{'en': 'Sure South Atlantic'},
'24746':{'en': 'Sure South Atlantic'},
'24747':{'en': 'Sure South Atlantic'},
'24748':{'en': 'Sure South Atlantic'},
'24825':{'en': 'CWS'},
'24826':{'en': 'CWS'},
'24827':{'en': 'Airtel'},
'24828':{'en': 'Airtel'},
'24910':{'en': 'Sudatel'},
'24911':{'en': 'Sudatel'},
'24912':{'en': 'Sudatel'},
'24990':{'en': 'Zain'},
'24991':{'en': 'Zain'},
'24992':{'en': 'MTN'},
'24993':{'en': 'MTN'},
'24995':{'en': 'Network of The World Ltd'},
'24996':{'en': 'Zain'},
'24999':{'en': 'MTN'},
'25072':{'en': 'TIGO'},
'25073':{'en': 'Airtel'},
'25078':{'en': 'MTN'},
'2519':{'en': 'Ethio Telecom'},
'25224':{'en': 'Telesom'},
'25228':{'en': 'Nationlink'},
'25235':{'en': 'AirSom'},
'25239':{'en': 'AirSom'},
'25248':{'en': 'AirSom'},
'25249':{'en': 'AirSom'},
'25262':{'en': 'Somtel'},
'25263':{'en': 'Telesom'},
'25264':{'en': 'Somali Networks'},
'25265':{'en': 'Somtel'},
'25266':{'en': 'Somtel'},
'25267':{'en': 'Nationlink'},
'25268':{'en': 'Nationlink'},
'25269':{'en': 'Nationlink'},
'25279':{'en': 'Somtel'},
'25280':{'en': 'Somali Networks'},
'25288':{'en': 'Somali Networks'},
'2529':{'en': 'STG'},
'25290':{'en': 'Golis Telecom'},
'2537':{'en': 'Evatis'},
'25410':{'en': 'Airtel'},
'25411':{'en': 'Safaricom'},
'25470':{'en': 'Safaricom'},
'25471':{'en': 'Safaricom'},
'25472':{'en': 'Safaricom'},
'25473':{'en': 'Airtel'},
'25474':{'en': 'Safaricom'},
'254744':{'en': 'Homeland Media'},
'254747':{'en': 'JTL'},
'254749':{'en': 'WiAfrica'},
'25475':{'en': 'Airtel'},
'254757':{'en': 'Safaricom'},
'254758':{'en': 'Safaricom'},
'254759':{'en': 'Safaricom'},
'254760':{'en': 'Mobile Pay'},
'254761':{'en': 'Airtel'},
'254762':{'en': 'Airtel'},
'254763':{'en': 'Finserve'},
'254764':{'en': 'Finserve'},
'254765':{'en': 'Finserve'},
'254766':{'en': 'Finserve'},
'254767':{'en': 'Sema Mobile'},
'254768':{'en': 'Safaricom'},
'254769':{'en': 'Safaricom'},
'25477':{'en': 'Telkom'},
'25478':{'en': 'Airtel'},
'25479':{'en': 'Safaricom'},
'25562':{'en': 'Viettel'},
'25563':{'en': 'MTC'},
'25564':{'en': 'Cootel'},
'25565':{'en': 'tiGO'},
'25566':{'en': 'SMILE'},
'25567':{'en': 'tiGO'},
'25568':{'en': 'Airtel'},
'25569':{'en': 'Airtel'},
'25571':{'en': 'tiGO'},
'25573':{'en': 'Tanzania Telecom'},
'25574':{'en': 'Vodacom'},
'25575':{'en': 'Vodacom'},
'25576':{'en': 'Vodacom'},
'25577':{'en': 'Zantel'},
'25578':{'en': 'Airtel'},
'25579':{'en': 'Benson Informatics'},
'25670':{'en': 'Airtel'},
'25671':{'en': 'UTL'},
'256720':{'en': 'Smile'},
'256726':{'en': 'Tangerine'},
'25673':{'en': 'Hamilton Telecom'},
'25674':{'en': 'Sure Telecom'},
'25675':{'en': 'Airtel'},
'25677':{'en': 'MTN'},
'25678':{'en': 'MTN'},
'25679':{'en': 'Africell'},
'25729':{'en': 'Leo'},
'2573':{'en': 'Viettel'},
'2576':{'en': 'Viettel'},
'25771':{'en': 'Leo'},
'25772':{'en': 'Leo'},
'25775':{'en': 'Smart Mobile'},
'25776':{'en': 'Leo'},
'25777':{'en': 'Onatel'},
'25778':{'en': 'Smart Mobile'},
'25779':{'en': 'Leo'},
'25882':{'en': 'mcel'},
'25883':{'en': 'mcel'},
'25884':{'en': 'Vodacom'},
'25885':{'en': 'Vodacom'},
'25886':{'en': 'Movitel'},
'25887':{'en': 'Movitel'},
'25889':{'en': 'GMPCS'},
'26076':{'en': 'MTN'},
'26077':{'en': 'Airtel'},
'26095':{'en': 'ZAMTEL'},
'26096':{'en': 'MTN'},
'26097':{'en': 'Airtel'},
'26132':{'en': 'Orange'},
'26133':{'en': 'Airtel'},
'26134':{'en': 'Telma'},
'26139':{'en': 'Blueline'},
'26263900':{'en': 'Orange'},
'26263901':{'en': 'Orange'},
'26263902':{'en': 'Orange'},
'26263903':{'en': 'Only'},
'26263904':{'en': 'Only'},
'26263905':{'en': 'Only'},
'26263906':{'en': 'Only'},
'26263907':{'en': 'Only'},
'26263909':{'en': 'SFR'},
'26263910':{'en': 'SFR'},
'26263911':{'en': 'SFR'},
'26263919':{'en': 'Only'},
'2626392':{'en': 'SFR'},
'26263926':{'en': 'Only'},
'26263930':{'en': 'BJT'},
'26263939':{'en': 'Only'},
'2626394':{'en': 'SFR'},
'2626395':{'en': 'BJT'},
'26263960':{'en': 'Orange'},
'26263961':{'en': 'Orange'},
'26263962':{'en': 'Orange'},
'26263963':{'en': 'Orange'},
'26263964':{'en': 'Orange'},
'26263965':{'en': 'SFR'},
'26263966':{'en': 'SFR'},
'26263967':{'en': 'SFR'},
'26263968':{'en': 'SFR'},
'26263969':{'en': 'SFR'},
'26263970':{'en': 'BJT'},
'26263971':{'en': 'Only'},
'26263972':{'en': 'Only'},
'26263973':{'en': 'Only'},
'26263974':{'en': 'Only'},
'26263975':{'en': 'Only'},
'26263976':{'en': 'Orange'},
'26263977':{'en': 'Orange'},
'26263978':{'en': 'Orange'},
'26263979':{'en': 'Orange'},
'26263990':{'en': 'BJT'},
'26263994':{'en': 'Only'},
'26263995':{'en': 'Only'},
'26263996':{'en': 'Only'},
'26263997':{'en': 'Only'},
'26263999':{'en': 'Orange'},
'262692':{'en': 'SFR'},
'2626920':{'en': 'Orange'},
'2626922':{'en': 'Orange'},
'2626923':{'en': 'Orange'},
'26269240':{'en': 'Orange'},
'26269241':{'en': 'Orange'},
'26269242':{'en': 'Orange'},
'26269243':{'en': 'Orange'},
'26269244':{'en': 'Orange'},
'26269292':{'en': 'Only'},
'26269293':{'en': 'Only'},
'26269294':{'en': 'Only'},
'26269300':{'en': 'Orange'},
'26269301':{'en': 'SFR'},
'26269302':{'en': 'SFR'},
'26269303':{'en': 'SFR'},
'26269304':{'en': 'SFR'},
'26269306':{'en': 'Orange'},
'26269310':{'en': 'SFR'},
'26269311':{'en': 'Orange'},
'26269313':{'en': 'SFR'},
'26269320':{'en': 'SFR'},
'26269321':{'en': 'Orange'},
'26269322':{'en': 'Orange'},
'26269330':{'en': 'Only'},
'26269331':{'en': 'Only'},
'26269332':{'en': 'Only'},
'26269333':{'en': 'Orange'},
'26269339':{'en': 'Orange'},
'2626934':{'en': 'Only'},
'26269350':{'en': 'Only'},
'26269355':{'en': 'Orange'},
'26269360':{'en': 'Only'},
'26269361':{'en': 'ZEOP Mobile'},
'26269362':{'en': 'ZEOP Mobile'},
'26269366':{'en': 'Orange'},
'26269370':{'en': 'Only'},
'26269371':{'en': 'Only'},
'26269372':{'en': 'Only'},
'26269377':{'en': 'Orange'},
'26269380':{'en': 'Only'},
'26269381':{'en': 'Only'},
'26269382':{'en': 'Only'},
'26269383':{'en': 'Only'},
'26269388':{'en': 'Orange'},
'26269390':{'en': 'Orange'},
'26269391':{'en': 'Orange'},
'26269392':{'en': 'Orange'},
'26269393':{'en': 'Orange'},
'26269394':{'en': 'SFR'},
'26269397':{'en': 'SFR'},
'26269399':{'en': 'Orange'},
'2629':{'en': 'Orange'},
'26371':{'en': 'Net*One'},
'26373':{'en': 'Telecel'},
'26377':{'en': 'Econet'},
'26378':{'en': 'Econet'},
'26460':{'en': 'Telecom Namibia'},
'26481':{'en': 'MTC'},
'26482':{'en': 'Telecom Namibia'},
'26484':{'en': 'MTN'},
'26485':{'en': 'TN Mobile'},
'26511':{'en': 'Malawi Telecom-munications Ltd (MTL)'},
'2653':{'en': 'TNM'},
'2657':{'en': 'Globally Advanced Integrated Networks Ltd'},
'2658':{'en': 'TNM'},
'2659':{'en': 'Airtel'},
'2665':{'en': 'Vodacom Lesotho (Pty) Ltd'},
'2666':{'en': 'Econet Ezi-Cel Lesotho'},
'26771':{'en': 'Mascom'},
'26772':{'en': 'Orange'},
'26773':{'en': 'BTC Mobile'},
'26774':{'en': 'Mascom'},
'267743':{'en': 'Orange'},
'267744':{'en': 'Orange'},
'267748':{'en': 'Orange'},
'267749':{'en': 'BTC Mobile'},
'267750':{'en': 'Orange'},
'267751':{'en': 'Orange'},
'267752':{'en': 'Orange'},
'267753':{'en': 'Orange'},
'267754':{'en': 'Mascom'},
'267755':{'en': 'Mascom'},
'267756':{'en': 'Mascom'},
'267757':{'en': 'Orange'},
'267758':{'en': 'BTC Mobile'},
'267759':{'en': 'Mascom'},
'267760':{'en': 'Mascom'},
'267761':{'en': 'Mascom'},
'267762':{'en': 'Mascom'},
'267763':{'en': 'Orange'},
'267764':{'en': 'Orange'},
'267765':{'en': 'Orange'},
'267766':{'en': 'Mascom'},
'267767':{'en': 'Mascom'},
'267768':{'en': 'BTC Mobile'},
'267769':{'en': 'Orange'},
'267770':{'en': 'Mascom'},
'267771':{'en': 'Mascom'},
'267772':{'en': 'BTC Mobile'},
'267773':{'en': 'Orange'},
'267774':{'en': 'Orange'},
'267775':{'en': 'Orange'},
'267776':{'en': 'Mascom'},
'267777':{'en': 'Mascom'},
'267778':{'en': 'Mascom'},
'267779':{'en': 'Orange'},
'26876':{'en': 'Swazi MTN'},
'26877':{'en': 'SPTC'},
'26878':{'en': 'Swazi MTN'},
'26879':{'en': 'Swazi Mobile Ltd'},
'2693':{'en': 'Comores Telecom'},
'2694':{'en': 'TELCO'},
'2710492':{'en': 'Vodacom'},
'2710493':{'en': 'Vodacom'},
'2710494':{'en': 'Vodacom'},
'2712492':{'en': 'Vodacom'},
'27134920':{'en': 'Vodacom'},
'27134921':{'en': 'Vodacom'},
'27134922':{'en': 'Vodacom'},
'27134925':{'en': 'Vodacom'},
'27144950':{'en': 'Vodacom'},
'27144952':{'en': 'Vodacom'},
'27144953':{'en': 'Vodacom'},
'27144955':{'en': 'Vodacom'},
'27154920':{'en': 'Vodacom'},
'27154950':{'en': 'Vodacom'},
'27154951':{'en': 'Vodacom'},
'27164920':{'en': 'Vodacom'},
'27174920':{'en': 'Vodacom'},
'27184920':{'en': 'Vodacom'},
'2719':{'en': 'Telkom Mobile'},
'2721492':{'en': 'Vodacom'},
'27224950':{'en': 'Vodacom'},
'27274950':{'en': 'Vodacom'},
'27284920':{'en': 'Vodacom'},
'2731492':{'en': 'Vodacom'},
'27324920':{'en': 'Vodacom'},
'27334920':{'en': 'Vodacom'},
'27344920':{'en': 'Vodacom'},
'27354920':{'en': 'Vodacom'},
'27364920':{'en': 'Vodacom'},
'27394920':{'en': 'Vodacom'},
'27404920':{'en': 'Vodacom'},
'2741492':{'en': 'Vodacom'},
'27424920':{'en': 'Vodacom'},
'27434920':{'en': 'Vodacom'},
'27434921':{'en': 'Vodacom'},
'27444920':{'en': 'Vodacom'},
'27444921':{'en': 'Vodacom'},
'27454920':{'en': 'Vodacom'},
'27464920':{'en': 'Vodacom'},
'27474950':{'en': 'Vodacom'},
'27484920':{'en': 'Vodacom'},
'27494920':{'en': 'Vodacom'},
'2751492':{'en': 'Vodacom'},
'27544950':{'en': 'Vodacom'},
'27564920':{'en': 'Vodacom'},
'27574920':{'en': 'Vodacom'},
'27584920':{'en': 'Vodacom'},
'27603':{'en': 'MTN'},
'27604':{'en': 'MTN'},
'27605':{'en': 'MTN'},
'27606':{'en': 'Vodacom'},
'27607':{'en': 'Vodacom'},
'27608':{'en': 'Vodacom'},
'27609':{'en': 'Vodacom'},
'2761':{'en': 'Cell C'},
'27614':{'en': 'Telkom Mobile'},
'2762':{'en': 'Cell C'},
'2763':{'en': 'MTN'},
'27636':{'en': 'Vodacom'},
'27637':{'en': 'Vodacom'},
'27640':{'en': 'MTN'},
'27641':{'en': 'Cell C'},
'27642':{'en': 'Cell C'},
'27643':{'en': 'Cell C'},
'27644':{'en': 'Cell C'},
'27645':{'en': 'Cell C'},
'27646':{'en': 'Vodacom'},
'27647':{'en': 'Vodacom'},
'27648':{'en': 'Vodacom'},
'27649':{'en': 'Vodacom'},
'27650':{'en': 'Cell C'},
'27651':{'en': 'Cell C'},
'27652':{'en': 'Cell C'},
'27653':{'en': 'Cell C'},
'27654':{'en': 'Cell C'},
'27655':{'en': 'MTN'},
'27656':{'en': 'MTN'},
'27657':{'en': 'MTN'},
'27658':{'en': 'Telkom Mobile'},
'27659':{'en': 'Telkom Mobile'},
'27660':{'en': 'Vodacom'},
'27661':{'en': 'Vodacom'},
'27662':{'en': 'Vodacom'},
'27663':{'en': 'Vodacom'},
'27664':{'en': 'Vodacom'},
'27665':{'en': 'Vodacom'},
'27670':{'en': 'Telkom Mobile'},
'27671':{'en': 'Telkom Mobile'},
'27672':{'en': 'Telkom Mobile'},
'27673':{'en': 'Vodacom'},
'27674':{'en': 'Vodacom'},
'27675':{'en': 'Vodacom'},
'27676':{'en': 'Telkom Mobile'},
'27677':{'en': 'Telkom Mobile'},
'2771':{'en': 'Vodacom'},
'27710':{'en': 'MTN'},
'27717':{'en': 'MTN'},
'27718':{'en': 'MTN'},
'27719':{'en': 'MTN'},
'2772':{'en': 'Vodacom'},
'2773':{'en': 'MTN'},
'2774':{'en': 'Cell C'},
'27741':{'en': 'Virgin Mobile'},
'2776':{'en': 'Vodacom'},
'2778':{'en': 'MTN'},
'2779':{'en': 'Vodacom'},
'27810':{'en': 'MTN'},
'27811':{'en': 'Telkom Mobile'},
'27812':{'en': 'Telkom Mobile'},
'27813':{'en': 'Telkom Mobile'},
'27814':{'en': 'Telkom Mobile'},
'27815':{'en': 'Telkom Mobile'},
'27816':{'en': 'WBS Mobile'},
'27817':{'en': 'Telkom Mobile'},
'27818':{'en': 'Vodacom'},
'278190':{'en': 'TelAfrica (Wirles Connect)'},
'278191':{'en': 'TelAfrica (Wirles Connect)'},
'278192':{'en': 'TelAfrica (Wirles Connect)'},
'2782':{'en': 'Vodacom'},
'2783':{'en': 'MTN'},
'2784':{'en': 'Cell C'},
'2787086':{'en': 'Vodacom'},
'2787087':{'en': 'Vodacom'},
'2787158':{'en': 'Vodacom'},
'2787285':{'en': 'Vodacom'},
'2787286':{'en': 'Vodacom'},
'2787287':{'en': 'Vodacom'},
'2787288':{'en': 'Vodacom'},
'2787289':{'en': 'Vodacom'},
'2787310':{'en': 'Vodacom'},
'29051':{'en': 'Sure South Atlantic Ltd'},
'29052':{'en': 'Sure South Atlantic Ltd'},
'29053':{'en': 'Sure South Atlantic Ltd'},
'29054':{'en': 'Sure South Atlantic Ltd'},
'29055':{'en': 'Sure South Atlantic Ltd'},
'29056':{'en': 'Sure South Atlantic Ltd'},
'29057':{'en': 'Sure South Atlantic Ltd'},
'29058':{'en': 'Sure South Atlantic Ltd'},
'29061':{'en': 'Sure South Atlantic Ltd'},
'29062':{'en': 'Sure South Atlantic Ltd'},
'29063':{'en': 'Sure South Atlantic Ltd'},
'29064':{'en': 'Sure South Atlantic Ltd'},
'29065':{'en': 'Sure South Atlantic Ltd'},
'29066':{'en': 'Sure South Atlantic Ltd'},
'29067':{'en': 'Sure South Atlantic Ltd'},
'29068':{'en': 'Sure South Atlantic Ltd'},
'29117':{'en': 'EriTel'},
'2917':{'en': 'EriTel'},
'29729':{'en': 'Digicel'},
'29756':{'en': 'SETAR'},
'29759':{'en': 'SETAR'},
'29760':{'en': 'SETAR'},
'29762':{'en': 'MIO Wireless'},
'29763':{'en': 'MIO Wireless'},
'29764':{'en': 'Digicel'},
'29766':{'en': 'SETAR'},
'297690':{'en': 'SETAR'},
'297699':{'en': 'SETAR'},
'29773':{'en': 'Digicel'},
'29774':{'en': 'Digicel'},
'29777':{'en': 'SETAR'},
'29821':{'en': 'Faroese Telecom'},
'29822':{'en': 'Faroese Telecom'},
'29823':{'en': 'Faroese Telecom'},
'29824':{'en': 'Faroese Telecom'},
'29825':{'en': 'Faroese Telecom'},
'29826':{'en': 'Faroese Telecom'},
'29827':{'en': 'Faroese Telecom'},
'29828':{'en': 'Faroese Telecom'},
'29829':{'en': 'Faroese Telecom'},
'2985':{'en': 'Vodafone'},
'2987':{'en': 'Vodafone'},
'29878':{'en': 'Faroese Telecom'},
'29879':{'en': 'Faroese Telecom'},
'2992':{'en': 'TELE Greenland A/S'},
'2994':{'en': 'TELE Greenland A/S'},
'2995':{'en': 'TELE Greenland A/S'},
'30685185':{'en': 'Cyta'},
'3068519':{'en': 'Cyta'},
'30685500':{'en': 'Cyta'},
'30685501':{'en': 'BWS'},
'30685505':{'en': 'Cyta'},
'30685550':{'en': 'Cyta'},
'30685555':{'en': 'Cyta'},
'30685585':{'en': 'Cyta'},
'30687500':{'en': 'BWS'},
'30688500':{'en': 'BWS'},
'30689900':{'en': 'OTEGlobe'},
'306900':{'en': 'BWS'},
'30690100':{'en': 'MI Carrier Services'},
'30690199':{'en': 'BWS'},
'30690200':{'en': 'MI Carrier Services'},
'30690299':{'en': 'BWS'},
'30690300':{'en': 'MI Carrier Services'},
'30690399':{'en': 'BWS'},
'30690400':{'en': 'MI Carrier Services'},
'30690499':{'en': 'BWS'},
'30690500':{'en': 'MI Carrier Services'},
'30690555':{'en': 'AMD Telecom'},
'30690574':{'en': 'BWS'},
'30690575':{'en': 'BWS'},
'30690588':{'en': 'BWS'},
'30690599':{'en': 'BWS'},
'306906':{'en': 'Wind'},
'306907':{'en': 'Wind'},
'306908':{'en': 'Wind'},
'306909':{'en': 'Wind'},
'30691000':{'en': 'BWS'},
'30691234':{'en': 'M-STAT'},
'30691345':{'en': 'Forthnet'},
'30691400':{'en': 'AMD Telecom'},
'30691600':{'en': 'Compatel'},
'30691700':{'en': 'Inter Telecom'},
'30691888':{'en': 'OSE'},
'30692354':{'en': 'Premium Net International'},
'30692356':{'en': 'SIA NETBALT'},
'30692428':{'en': 'Premium Net International'},
'30693':{'en': 'Wind'},
'30694':{'en': 'Vodafone'},
'306950':{'en': 'Vodafone'},
'306951':{'en': 'Vodafone'},
'30695200':{'en': 'Compatel'},
'3069522':{'en': 'Vodafone'},
'3069523':{'en': 'Vodafone'},
'3069524':{'en': 'BWS'},
'3069529':{'en': 'BWS'},
'3069530':{'en': 'Cyta'},
'30695310':{'en': 'MI Carrier Services'},
'30695328':{'en': 'Premium Net International'},
'30695330':{'en': 'Apifon'},
'30695340':{'en': 'AMD Telecom'},
'30695355':{'en': 'Cyta'},
'30695400':{'en': 'AMD Telecom'},
'30695410':{'en': 'MI Carrier Services'},
'30695456':{'en': 'BWS'},
'30695490':{'en': 'MI Carrier Services'},
'30695499':{'en': 'M-STAT'},
'306955':{'en': 'Vodafone'},
'306956':{'en': 'Vodafone'},
'306957':{'en': 'Vodafone'},
'306958':{'en': 'Vodafone'},
'306959':{'en': 'Vodafone'},
'3069601':{'en': 'OTE'},
'30697':{'en': 'Cosmote'},
'30698':{'en': 'Cosmote'},
'3069900':{'en': 'Wind'},
'30699010':{'en': 'BWS'},
'30699022':{'en': 'Yuboto'},
'30699046':{'en': 'Premium Net International'},
'30699048':{'en': 'AMD Telecom'},
'30699099':{'en': 'BWS'},
'306991':{'en': 'Wind'},
'306992':{'en': 'Wind'},
'306993':{'en': 'Wind'},
'306994':{'en': 'Wind'},
'306995':{'en': 'Wind'},
'306996':{'en': 'Wind'},
'306997':{'en': 'Wind'},
'306998':{'en': 'Wind'},
'306999':{'en': 'Wind'},
'3094':{'en': 'Vodafone'},
'31610':{'en': 'KPN'},
'31611':{'en': 'Vodafone Libertel B.V.'},
'31612':{'en': 'KPN'},
'31613':{'en': 'KPN'},
'31614':{'en': 'T-Mobile'},
'31615':{'en': 'Vodafone Libertel B.V.'},
'31616':{'en': 'Telfort'},
'31617':{'en': 'Telfort'},
'31618':{'en': 'T-Mobile Thuis'},
'31619':{'en': 'KPN'},
'31620':{'en': 'KPN'},
'31621':{'en': 'Vodafone Libertel B.V.'},
'31622':{'en': 'KPN'},
'31623':{'en': 'KPN'},
'31624':{'en': 'T-Mobile'},
'31625':{'en': 'Vodafone Libertel B.V.'},
'31626':{'en': 'Telfort'},
'31627':{'en': 'Vodafone Libertel B.V.'},
'31628':{'en': 'T-Mobile Thuis'},
'31629':{'en': 'Vodafone Libertel B.V.'},
'31630':{'en': 'KPN'},
'31631':{'en': 'Vodafone Libertel B.V.'},
'31633':{'en': 'Telfort'},
'31634':{'en': 'T-Mobile'},
'316351':{'en': 'Glotell B.V (V-Tell NL)'},
'316352':{'en': 'Lancelot'},
'316353':{'en': 'KPN'},
'316356':{'en': 'ASPIDER Solutions Nederland B.V.'},
'316357':{'en': 'ASPIDER Solutions Nederland B.V.'},
'316358':{'en': 'ASPIDER Solutions Nederland B.V.'},
'316359':{'en': 'ASPIDER Solutions Nederland B.V.'},
'31636':{'en': 'Tele2'},
'31637':{'en': 'Teleena (MVNE)'},
'31638':{'en': 'T-Mobile Thuis'},
'31639':{'en': 'T-Mobile Thuis'},
'31640':{'en': 'Tele2'},
'31641':{'en': 'T-Mobile'},
'31642':{'en': 'T-Mobile'},
'31643':{'en': 'T-Mobile'},
'31644':{'en': 'Telfort'},
'31645':{'en': 'Telfort'},
'31646':{'en': 'Vodafone Libertel B.V.'},
'31647':{'en': 'Telfort'},
'31648':{'en': 'T-Mobile Thuis'},
'31649':{'en': 'Telfort'},
'31650':{'en': 'Vodafone Libertel B.V.'},
'31651':{'en': 'KPN'},
'31652':{'en': 'Vodafone Libertel B.V.'},
'31653':{'en': 'KPN'},
'31654':{'en': 'Vodafone Libertel B.V.'},
'31655':{'en': 'Vodafone Libertel B.V.'},
'31656':{'en': 'T-Mobile'},
'31657':{'en': 'KPN'},
'31658':{'en': 'Telfort'},
'316580':{'en': 'Private Mobility Nederland'},
'31659':{'en': 'Vectone Mobile/Delight Mobile'},
'316599':{'en': 'Motto'},
'31680':{'en': 'Vodafone Libertel B.V.'},
'31681':{'en': 'T-Mobile'},
'31682':{'en': 'KPN'},
'31683':{'en': 'KPN'},
'31684':{'en': 'Lycamobile'},
'31685':{'en': 'Lycamobile'},
'31686':{'en': 'Lycamobile'},
'31687':{'en': 'Lycamobile'},
'3245001':{'en': 'Gateway Communications'},
'32455':{'en': 'VOO'},
'32456':{'en': 'Mobile Vikings/JIM Mobile'},
'32460':{'en': 'Proximus'},
'324618':{'en': 'N.M.B.S.'},
'324630':{'en': 'TISMI BV'},
'324651':{'en': 'Lycamobile'},
'324652':{'en': 'Lycamobile'},
'324653':{'en': 'Lycamobile'},
'324654':{'en': 'Lycamobile'},
'324655':{'en': 'Lycamobile'},
'324656':{'en': 'Lycamobile'},
'324657':{'en': 'Lycamobile'},
'324658':{'en': 'Lycamobile'},
'324659':{'en': 'Lycamobile'},
'324660':{'en': 'Lycamobile'},
'324661':{'en': 'Lycamobile'},
'324662':{'en': 'Lycamobile'},
'324663':{'en': 'Lycamobile'},
'324664':{'en': 'Lycamobile'},
'324665':{'en': 'Vectone'},
'324666':{'en': 'Vectone'},
'324667':{'en': 'Vectone'},
'324669':{'en': 'Voxbone SA'},
'324670':{'en': 'Telenet'},
'324671':{'en': 'Join Experience Belgium'},
'324672':{'en': 'Join Experience Belgium'},
'32467306':{'en': 'Telenet'},
'324674':{'en': 'Febo Telecom'},
'324676':{'en': 'Lycamobile'},
'324677':{'en': 'Lycamobile'},
'324678':{'en': 'Lycamobile'},
'324679':{'en': 'Interactive Digital Media GmbH'},
'32468':{'en': 'Telenet'},
'324686':{'en': u('OnOff T\u00e9l\u00e9com SASU')},
'324687':{'en': 'Premium Routing GmbH'},
'324688':{'en': 'Premium Routing GmbH'},
'324689':{'en': 'Febo Telecom'},
'3247':{'en': 'Proximus'},
'324805':{'en': 'Voyacom SPRL'},
'324807':{'en': 'MessageBird BV'},
'324809':{'en': 'Ericsson NV'},
'32483':{'en': 'Telenet'},
'32484':{'en': 'Telenet'},
'32485':{'en': 'Telenet'},
'32486':{'en': 'Telenet'},
'32487':{'en': 'Telenet'},
'32488':{'en': 'Telenet'},
'32489':{'en': 'Telenet'},
'3249':{'en': 'Orange'},
'336000':{'en': 'Free Mobile'},
'336001':{'en': 'Orange France'},
'336002':{'en': 'SFR'},
'336003':{'en': 'Bouygues'},
'3360040':{'en': 'Zeop'},
'3360041':{'en': 'Orange France'},
'3360042':{'en': 'Digicel Antilles Francaises Guyane'},
'3360043':{'en': 'Dauphin Telecom'},
'3360044':{'en': 'OUTREMER TELECOM'},
'3360045':{'en': 'UTS CARAIBES'},
'3360051':{'en': 'Orange France'},
'3360052':{'en': 'SFR'},
'3360053':{'en': 'BJT'},
'3360054':{'en': 'Only (Telco OI)'},
'3360055':{'en': 'Only (Telco OI)'},
'336006':{'en': 'Free Mobile'},
'336007':{'en': 'SFR'},
'336008':{'en': 'Orange France'},
'336009':{'en': 'Bouygues'},
'33601':{'en': 'SFR'},
'33602':{'en': 'SFR'},
'33603':{'en': 'SFR'},
'336040':{'en': 'Afone'},
'336041':{'en': 'Afone'},
'336042':{'en': 'e*Message'},
'336043':{'en': 'e*Message'},
'336044':{'en': 'Afone'},
'336045':{'en': 'SFR'},
'336046':{'en': 'SFR'},
'336047':{'en': 'SFR'},
'336048':{'en': 'SFR'},
'336049':{'en': 'SFR'},
'336050':{'en': 'Euroinformation Telecom'},
'336051':{'en': 'Euroinformation Telecom'},
'336052':{'en': 'Euroinformation Telecom'},
'336053':{'en': 'Euroinformation Telecom'},
'336054':{'en': 'Euroinformation Telecom'},
'336055':{'en': 'Lycamobile'},
'336056':{'en': 'Lycamobile'},
'336057':{'en': 'Lycamobile'},
'336058':{'en': 'Lycamobile'},
'336059':{'en': 'Lycamobile'},
'336060':{'en': 'e*Message'},
'336061':{'en': 'e*Message'},
'336062':{'en': 'e*Message'},
'336063':{'en': 'e*Message'},
'336064':{'en': 'Afone'},
'336065':{'en': 'Euroinformation Telecom'},
'336066':{'en': 'Euroinformation Telecom'},
'336067':{'en': 'Euroinformation Telecom'},
'336068':{'en': 'Euroinformation Telecom'},
'336069':{'en': 'Euroinformation Telecom'},
'33607':{'en': 'Orange France'},
'33608':{'en': 'Orange France'},
'33609':{'en': 'SFR'},
'3361':{'en': 'SFR'},
'3362':{'en': 'SFR'},
'33630':{'en': 'Orange France'},
'33631':{'en': 'Orange France'},
'33632':{'en': 'Orange France'},
'33633':{'en': 'Orange France'},
'33634':{'en': 'SFR'},
'33635':{'en': 'SFR'},
'33636':{'en': 'Euroinformation Telecom'},
'33637':{'en': 'Orange France'},
'33638':{'en': 'Orange France'},
'3363800':{'en': 'Globalstar Europe'},
'3363801':{'en': 'Prixtel'},
'3363802':{'en': 'Prixtel'},
'3363803':{'en': 'Prixtel'},
'3363804':{'en': 'Prixtel'},
'3363805':{'en': 'Prixtel'},
'3363806':{'en': 'IP Directions'},
'3363807':{'en': 'Alphalink'},
'3363808':{'en': 'Alphalink'},
'3363809':{'en': 'Alphalink'},
'33640':{'en': 'Orange France'},
'3364000':{'en': 'Globalstar Europe'},
'3364001':{'en': 'Globalstar Europe'},
'3364002':{'en': 'Globalstar Europe'},
'3364003':{'en': 'Globalstar Europe'},
'3364004':{'en': 'Globalstar Europe'},
'3364005':{'en': 'Coriolis Telecom'},
'3364006':{'en': 'Coriolis Telecom'},
'3364007':{'en': 'Coriolis Telecom'},
'3364008':{'en': 'Coriolis Telecom'},
'3364009':{'en': 'Coriolis Telecom'},
'336410':{'en': 'La poste telecom'},
'336411':{'en': 'La poste telecom'},
'336412':{'en': 'La poste telecom'},
'336413':{'en': 'La poste telecom'},
'336414':{'en': 'La poste telecom'},
'336415':{'en': 'La poste telecom'},
'3364160':{'en': 'Euroinformation Telecom'},
'3364161':{'en': 'Euroinformation Telecom'},
'3364162':{'en': 'Mobiquithings'},
'3364163':{'en': 'SCT'},
'3364164':{'en': 'Legos'},
'3364165':{'en': 'e*Message'},
'3364166':{'en': 'SFR'},
'3364167':{'en': 'SFR'},
'3364168':{'en': 'SFR'},
'3364169':{'en': 'SFR'},
'33642':{'en': 'Orange France'},
'33643':{'en': 'Orange France'},
'336440':{'en': 'La poste telecom'},
'336441':{'en': 'Orange France'},
'336442':{'en': 'Orange France'},
'336443':{'en': 'Orange France'},
'336444':{'en': 'Transatel'},
'336445':{'en': 'Transatel'},
'336446':{'en': 'Transatel'},
'336447':{'en': 'La poste telecom'},
'336448':{'en': 'La poste telecom'},
'336449':{'en': 'La poste telecom'},
'33645':{'en': 'Orange France'},
'33646':{'en': 'SFR'},
'33647':{'en': 'Orange France'},
'33648':{'en': 'Orange France'},
'33649':{'en': 'Orange France'},
'3364950':{'en': 'Keyyo'},
'3364990':{'en': 'Intercall'},
'3364991':{'en': 'Intercall'},
'3364994':{'en': 'e*Message'},
'3364995':{'en': 'Prixtel'},
'3364996':{'en': 'e*Message'},
'3364997':{'en': 'e*Message'},
'3364998':{'en': 'Prixtel'},
'3364999':{'en': 'SFR'},
'33650':{'en': 'Bouygues'},
'33651':{'en': 'Free Mobile'},
'33652':{'en': 'Free Mobile'},
'336530':{'en': 'Bouygues'},
'336531':{'en': 'Bouygues'},
'336532':{'en': 'Bouygues'},
'336533':{'en': 'Bouygues'},
'336534':{'en': 'Bouygues'},
'336535':{'en': 'Free Mobile'},
'336536':{'en': 'Free Mobile'},
'336537':{'en': 'Free Mobile'},
'336538':{'en': 'Free Mobile'},
'336539':{'en': 'Free Mobile'},
'33654':{'en': 'Orange France'},
'33655':{'en': 'SFR'},
'33656':{'en': 'e*Message'},
'3365660':{'en': 'Mobiquithings'},
'3365661':{'en': 'Airbus Defence and Space'},
'3365662':{'en': 'Mobiquithings'},
'3365663':{'en': 'Mobiquithings'},
'3365664':{'en': 'Mobiquithings'},
'3365665':{'en': 'Mobiquithings'},
'3365666':{'en': 'Prixtel'},
'3365667':{'en': 'Prixtel'},
'3365668':{'en': 'Prixtel'},
'3365669':{'en': 'Prixtel'},
'336567':{'en': 'La poste telecom'},
'336568':{'en': 'La poste telecom'},
'33657':{'en': 'e*Message'},
'33658':{'en': 'Bouygues'},
'33659':{'en': 'Bouygues'},
'3366':{'en': 'Bouygues'},
'3367':{'en': 'Orange France'},
'3368':{'en': 'Orange France'},
'33692':{'en': 'Bouygues'},
'33693':{'en': 'Bouygues'},
'33696':{'en': 'Bouygues'},
'33698':{'en': 'Bouygues'},
'33699':{'en': 'Bouygues'},
'33700000':{'en': 'Orange France'},
'33700001':{'en': 'SFR'},
'33700002':{'en': 'Mobiquithings'},
'33700003':{'en': 'Bouygues'},
'33700004':{'en': 'Afone'},
'33700005':{'en': 'Coriolis Telecom'},
'33700006':{'en': 'Mobiquithings'},
'337500':{'en': 'Euroinformation Telecom'},
'337501':{'en': 'SFR'},
'337502':{'en': 'SFR'},
'337503':{'en': 'SFR'},
'337504':{'en': 'SFR'},
'3375050':{'en': 'Euroinformation Telecom'},
'3375051':{'en': 'Euroinformation Telecom'},
'3375052':{'en': 'Euroinformation Telecom'},
'3375053':{'en': 'Euroinformation Telecom'},
'3375057':{'en': 'Euroinformation Telecom'},
'3375058':{'en': 'Euroinformation Telecom'},
'3375059':{'en': 'Sewan communications'},
'337506':{'en': 'Orange France'},
'3375060':{'en': 'Euroinformation Telecom'},
'3375070':{'en': 'Euroinformation Telecom'},
'3375071':{'en': 'Netcom Group'},
'3375072':{'en': 'Netcom Group'},
'3375073':{'en': 'Alphalink'},
'3375074':{'en': 'Alphalink'},
'3375075':{'en': 'Alphalink'},
'3375076':{'en': 'Globalstar Europe'},
'3375077':{'en': 'Globalstar Europe'},
'3375078':{'en': 'China Telecom (France) Limited'},
'3375079':{'en': 'China Telecom (France) Limited'},
'337508':{'en': 'SFR'},
'337509':{'en': 'SFR'},
'33751':{'en': 'Lycamobile'},
'337516':{'en': 'SFR'},
'337517':{'en': 'Completel'},
'337518':{'en': 'Lebara France Limited'},
'337519':{'en': 'Lebara France Limited'},
'3375202':{'en': 'Prixtel'},
'3375203':{'en': 'Prixtel'},
'3375204':{'en': 'Prixtel'},
'3375205':{'en': 'Prixtel'},
'3375206':{'en': 'Prixtel'},
'3375207':{'en': 'Prixtel'},
'3375208':{'en': 'Prixtel'},
'3375209':{'en': 'Prixtel'},
'337521':{'en': 'Lebara France Limited'},
'337522':{'en': 'Lebara France Limited'},
'337523':{'en': 'Lebara France Limited'},
'337524':{'en': 'Lebara France Limited'},
'337525':{'en': 'Lebara France Limited'},
'337526':{'en': 'SFR'},
'337527':{'en': 'Lebara France Limited'},
'337528':{'en': 'Lebara France Limited'},
'337529':{'en': 'Lebara France Limited'},
'33753':{'en': 'Lycamobile'},
'337540':{'en': 'Lebara France Limited'},
'337541':{'en': 'Lebara France Limited'},
'337542':{'en': 'Lebara France Limited'},
'337543':{'en': 'Prixtel'},
'3375430':{'en': 'TDF'},
'3375431':{'en': 'Legos'},
'3375432':{'en': 'Euroinformation Telecom'},
'337544':{'en': 'Lebara France Limited'},
'337545':{'en': 'Lebara France Limited'},
'337546':{'en': 'Mobiquithings'},
'337547':{'en': 'ACN Communications'},
'337548':{'en': 'Completel'},
'337549':{'en': 'Completel'},
'33755':{'en': 'Lebara France Limited'},
'3375550':{'en': 'Legos'},
'3375551':{'en': 'Legos'},
'3375552':{'en': 'Legos'},
'3375553':{'en': 'Legos'},
'3375554':{'en': 'Legos'},
'3375555':{'en': 'Euroinformation Telecom'},
'3375556':{'en': 'Intercall'},
'3375557':{'en': 'Intercall'},
'3375558':{'en': 'Sewan communications'},
'3375559':{'en': 'Sewan communications'},
'3375560':{'en': 'Prixtel'},
'3375561':{'en': 'Prixtel'},
'3375562':{'en': 'Prixtel'},
'3375563':{'en': 'Prixtel'},
'3375564':{'en': 'Prixtel'},
'3375565':{'en': 'Sewan communications'},
'3375566':{'en': 'Euroinformation Telecom'},
'3375567':{'en': 'Euroinformation Telecom'},
'3375568':{'en': 'Euroinformation Telecom'},
'3375569':{'en': 'Axialys'},
'337560':{'en': 'Euroinformation Telecom'},
'337561':{'en': 'Euroinformation Telecom'},
'337562':{'en': 'Euroinformation Telecom'},
'3375630':{'en': 'Euroinformation Telecom'},
'3375631':{'en': 'Euroinformation Telecom'},
'3375632':{'en': 'Euroinformation Telecom'},
'3375633':{'en': 'Euroinformation Telecom'},
'3375634':{'en': 'Euroinformation Telecom'},
'337565':{'en': 'Transatel'},
'337566':{'en': 'Transatel'},
'337567':{'en': 'Transatel'},
'337568':{'en': 'Transatel'},
'337569':{'en': 'Transatel'},
'3375700':{'en': 'Sewan communications'},
'3375701':{'en': 'Mobiweb telecom limited'},
'3375702':{'en': 'Mobiweb telecom limited'},
'3375703':{'en': 'Mobiweb telecom limited'},
'3375704':{'en': 'Mobiweb telecom limited'},
'3375705':{'en': 'Mobiweb telecom limited'},
'3375706':{'en': 'Nordnet'},
'3375707':{'en': 'Keyyo'},
'3375717':{'en': 'Keyyo'},
'337572':{'en': 'Mobiquithings'},
'337573':{'en': 'Mobiquithings'},
'337574':{'en': 'Coriolis Telecom'},
'3375750':{'en': 'Coriolis Telecom'},
'3375751':{'en': 'Coriolis Telecom'},
'3375752':{'en': 'Coriolis Telecom'},
'3375753':{'en': 'Coriolis Telecom'},
'3375754':{'en': 'Coriolis Telecom'},
'3375755':{'en': 'Coriolis Telecom'},
'3375756':{'en': 'Coriolis Telecom'},
'3375757':{'en': 'Euroinformation Telecom'},
'3375758':{'en': 'Euroinformation Telecom'},
'3375763':{'en': 'Euroinformation Telecom'},
'3375767':{'en': 'Euroinformation Telecom'},
'3375777':{'en': 'Euroinformation Telecom'},
'3375779':{'en': 'Halys'},
'3375787':{'en': 'Euroinformation Telecom'},
'3375788':{'en': 'BJT'},
'3375789':{'en': 'BJT'},
'337579':{'en': 'Legos'},
'33758':{'en': 'Lycamobile'},
'33759':{'en': 'Vectone mobile'},
'3376':{'en': 'Bouygues'},
'33766':{'en': 'Free Mobile'},
'33767':{'en': 'Free Mobile'},
'33768':{'en': 'Free Mobile'},
'33769':{'en': 'Free Mobile'},
'337700':{'en': 'Orange France'},
'337701':{'en': 'Orange France'},
'337702':{'en': 'Orange France'},
'337703':{'en': 'SFR'},
'337704':{'en': 'SFR'},
'337705':{'en': 'Euroinformation Telecom'},
'337706':{'en': 'Euroinformation Telecom'},
'337707':{'en': 'Euroinformation Telecom'},
'337708':{'en': 'Euroinformation Telecom'},
'337709':{'en': 'Euroinformation Telecom'},
'337710':{'en': 'Euroinformation Telecom'},
'337711':{'en': 'Euroinformation Telecom'},
'337712':{'en': 'Euroinformation Telecom'},
'337713':{'en': 'SFR'},
'337714':{'en': 'SFR'},
'3377150':{'en': 'SFR'},
'3377151':{'en': 'SFR'},
'3377152':{'en': 'SFR'},
'3377153':{'en': 'SFR'},
'3377154':{'en': 'SFR'},
'3377155':{'en': 'Euroinformation Telecom'},
'3377156':{'en': 'Euroinformation Telecom'},
'3377157':{'en': 'Euroinformation Telecom'},
'3377158':{'en': 'Euroinformation Telecom'},
'3377159':{'en': 'Euroinformation Telecom'},
'337716':{'en': 'Euroinformation Telecom'},
'337717':{'en': 'Euroinformation Telecom'},
'337718':{'en': 'Euroinformation Telecom'},
'3377190':{'en': 'Euroinformation Telecom'},
'3377191':{'en': 'Euroinformation Telecom'},
'3377192':{'en': 'Euroinformation Telecom'},
'3377193':{'en': 'Euroinformation Telecom'},
'3377194':{'en': 'Euroinformation Telecom'},
'33772':{'en': 'Orange France'},
'33773':{'en': 'Syma mobile'},
'33774':{'en': 'Syma mobile'},
'337750':{'en': 'SFR'},
'337751':{'en': 'SFR'},
'337752':{'en': 'SFR'},
'337753':{'en': 'SFR'},
'337754':{'en': 'SFR'},
'337755':{'en': 'Mobiquithings'},
'337756':{'en': 'Mobiquithings'},
'337757':{'en': 'Free Mobile'},
'33776':{'en': 'SFR'},
'33777':{'en': 'SFR'},
'33778':{'en': 'SFR'},
'33779':{'en': 'SFR'},
'3378':{'en': 'Orange France'},
'33780':{'en': 'Afone'},
'337807':{'en': 'Lebara France Limited'},
'337808':{'en': 'Lebara France Limited'},
'337809':{'en': 'Onoff telecom'},
'33781':{'en': 'Free Mobile'},
'33782':{'en': 'Free Mobile'},
'33783':{'en': 'Free Mobile'},
'337846':{'en': 'La poste telecom'},
'337847':{'en': 'La poste telecom'},
'337848':{'en': 'La poste telecom'},
'337849':{'en': 'Euroinformation Telecom'},
'34600':{'en': 'Vodafone'},
'34601':{'en': 'Vodafone'},
'346016':{'en': 'Orange'},
'346018':{'en': 'Orange'},
'346019':{'en': 'Orange'},
'346020':{'en': 'Lycamobile'},
'346021':{'en': 'Lycamobile'},
'3460220':{'en': 'Orange'},
'3460221':{'en': 'Ion mobile'},
'3460222':{'en': 'Vozelia'},
'3460223':{'en': 'Orange'},
'3460224':{'en': 'Oceans'},
'3460225':{'en': 'VozTelecom'},
'3460226':{'en': 'Orange'},
'3460227':{'en': 'Orange'},
'3460228':{'en': 'Orange'},
'3460229':{'en': 'Boutique'},
'346023':{'en': 'Lycamobile'},
'346024':{'en': 'Lebara'},
'346025':{'en': 'Lebara'},
'346026':{'en': 'Lebara'},
'346027':{'en': 'Lebara'},
'346028':{'en': 'Lycamobile'},
'346029':{'en': 'DIA'},
'3460300':{'en': 'Vodafone'},
'3460301':{'en': 'Vodafone'},
'3460302':{'en': 'Vodafone'},
'3460303':{'en': 'Vodafone'},
'3460304':{'en': 'Vodafone'},
'3460305':{'en': 'Lebara'},
'3460306':{'en': 'Lebara'},
'3460307':{'en': 'Lebara'},
'3460308':{'en': 'Lebara'},
'3460309':{'en': 'Lebara'},
'346031':{'en': 'Lebara'},
'346032':{'en': 'Lebara'},
'346033':{'en': 'Lebara'},
'346034':{'en': 'Vodafone'},
'346035':{'en': 'Vodafone'},
'346036':{'en': 'Vodafone'},
'346037':{'en': 'Vodafone'},
'346038':{'en': 'Vodafone'},
'346039':{'en': 'Lebara'},
'34604':{'en': 'Lebara'},
'346040':{'en': 'Orange'},
'346045':{'en': 'Orange'},
'34605':{'en': 'Orange'},
'3460529':{'en': 'MasMovil'},
'34606':{'en': 'Movistar'},
'34607':{'en': 'Vodafone'},
'34608':{'en': 'Movistar'},
'34609':{'en': 'Movistar'},
'34610':{'en': 'Vodafone'},
'34611':{'en': 'Republica Movil'},
'346110':{'en': 'Orange'},
'346112':{'en': 'Lebara'},
'346113':{'en': 'Lebara'},
'34612':{'en': 'Syma'},
'346122':{'en': 'Lycamobile'},
'346124':{'en': 'Lycamobile'},
'346125':{'en': 'Lycamobile'},
'34615':{'en': 'Orange'},
'34616':{'en': 'Movistar'},
'34617':{'en': 'Vodafone'},
'34618':{'en': 'Movistar'},
'34619':{'en': 'Movistar'},
'34620':{'en': 'Movistar'},
'346210':{'en': 'Republica Movil'},
'346211':{'en': 'Republica Movil'},
'346212':{'en': 'Movistar'},
'346213':{'en': 'Republica Movil'},
'346214':{'en': 'Republica Movil'},
'346215':{'en': 'Republica Movil'},
'346216':{'en': 'Republica Movil'},
'34622':{'en': 'Yoigo'},
'346230':{'en': 'Yoigo'},
'346231':{'en': 'Yoigo'},
'346236':{'en': 'Altecom'},
'34625':{'en': 'Orange'},
'3462529':{'en': 'Yoigo'},
'34626':{'en': 'Movistar'},
'34627':{'en': 'Vodafone'},
'34628':{'en': 'Movistar'},
'34629':{'en': 'Movistar'},
'34630':{'en': 'Movistar'},
'34631':{'en': 'Lycamobile'},
'34632':{'en': 'Lycamobile'},
'34633':{'en': 'Yoigo'},
'34634':{'en': 'Vodafone'},
'346340':{'en': 'Lebara'},
'346341':{'en': 'Lebara'},
'346343':{'en': 'Carrier Enabler'},
'346345':{'en': 'Movistar'},
'34635':{'en': 'Orange'},
'3463529':{'en': 'Yoigo'},
'34636':{'en': 'Movistar'},
'34637':{'en': 'Vodafone'},
'34638':{'en': 'Movistar'},
'34639':{'en': 'Movistar'},
'34640':{'en': 'Orange'},
'34641':{'en': 'Movistar'},
'34642':{'en': 'DigiMobil'},
'346430':{'en': 'DigiMobil'},
'346431':{'en': 'DigiMobil'},
'346432':{'en': 'DigiMobil'},
'346433':{'en': 'DigiMobil'},
'346434':{'en': 'DigiMobil'},
'346435':{'en': 'DigiMobil'},
'346436':{'en': 'DigiMobil'},
'346437':{'en': 'DigiMobil'},
'34644':{'en': 'Orange'},
'34645':{'en': 'Orange'},
'3464529':{'en': 'Yoigo'},
'34646':{'en': 'Movistar'},
'34647':{'en': 'Vodafone'},
'34648':{'en': 'Movistar'},
'34649':{'en': 'Movistar'},
'3465':{'en': 'Orange'},
'34650':{'en': 'Movistar'},
'3465229':{'en': 'Yoigo'},
'3465329':{'en': 'DIA'},
'3465429':{'en': 'DIA'},
'3465529':{'en': 'DIA'},
'3465729':{'en': 'DIA'},
'3465829':{'en': 'DIA'},
'34659':{'en': 'Movistar'},
'34660':{'en': 'Movistar'},
'34661':{'en': 'Vodafone'},
'34662':{'en': 'Vodafone'},
'34663':{'en': 'Vodafone'},
'34664':{'en': 'Vodafone'},
'34665':{'en': 'Orange'},
'34666':{'en': 'Vodafone'},
'34667':{'en': 'Vodafone'},
'346681':{'en': 'Truphone'},
'346685':{'en': 'Orange'},
'346686':{'en': 'Parlem'},
'346688':{'en': 'Parlem'},
'34669':{'en': 'Movistar'},
'3467':{'en': 'Vodafone'},
'346725':{'en': 'Lebara'},
'346728':{'en': 'Lebara'},
'346729':{'en': 'Lebara'},
'34675':{'en': 'Orange'},
'34676':{'en': 'Movistar'},
'34679':{'en': 'Movistar'},
'34680':{'en': 'Movistar'},
'346810':{'en': 'Movistar'},
'346811':{'en': 'Movistar'},
'346812':{'en': 'Movistar'},
'346813':{'en': 'Movistar'},
'346814':{'en': 'Movistar'},
'346815':{'en': 'Movistar'},
'346816':{'en': 'Yoigo'},
'34682':{'en': 'Movistar'},
'34683':{'en': 'Movistar'},
'346840':{'en': 'Movistar'},
'346841':{'en': 'Movistar'},
'346842':{'en': 'Movistar'},
'346843':{'en': 'Movistar'},
'3468440':{'en': 'Eurona'},
'3468441':{'en': 'Lemonvil'},
'3468442':{'en': 'BluePhone'},
'3468443':{'en': 'BT'},
'3468444':{'en': 'BT'},
'3468445':{'en': 'Aire Networks'},
'3468447':{'en': 'Quattre'},
'3468448':{'en': 'Nethits'},
'346845':{'en': 'Movistar'},
'346846':{'en': 'Telecable'},
'34685':{'en': 'Orange'},
'3468529':{'en': 'Carrefour'},
'34686':{'en': 'Movistar'},
'34687':{'en': 'Vodafone'},
'346880':{'en': 'YouMobile'},
'346881':{'en': 'YouMobile'},
'346882':{'en': 'Yoigo'},
'346883':{'en': 'Yoigo'},
'346884':{'en': 'Yoigo'},
'346885':{'en': 'YouMobile'},
'346886':{'en': 'Euskaltel'},
'346887':{'en': 'Euskaltel'},
'3468870':{'en': 'OpenMovil'},
'346888':{'en': 'Euskaltel'},
'3468883':{'en': 'Sarenet'},
'346889':{'en': 'PepePhone'},
'34689':{'en': 'Movistar'},
'34690':{'en': 'Movistar'},
'34691':{'en': 'Orange'},
'346919':{'en': 'Yoigo'},
'3469190':{'en': 'MasMovil'},
'3469198':{'en': 'Carrefour'},
'3469199':{'en': 'Carrefour'},
'34692':{'en': 'Orange'},
'3469229':{'en': 'Carrefour'},
'346927':{'en': 'Carrefour'},
'3469300':{'en': 'MasMovil'},
'3469301':{'en': 'Yoigo'},
'3469302':{'en': 'Yoigo'},
'3469303':{'en': 'Yoigo'},
'3469304':{'en': 'Yoigo'},
'3469305':{'en': 'Yoigo'},
'3469306':{'en': 'Yoigo'},
'346931':{'en': 'Orange'},
'3469310':{'en': 'MasMovil'},
'346932':{'en': 'Yoigo'},
'3469320':{'en': 'Carrefour'},
'3469321':{'en': 'Carrefour'},
'3469329':{'en': 'Orange'},
'346933':{'en': 'Carrefour'},
'3469336':{'en': 'Yoigo'},
'3469337':{'en': 'Yoigo'},
'3469340':{'en': 'DIA'},
'3469341':{'en': 'DIA'},
'3469342':{'en': 'DIA'},
'3469343':{'en': 'DIA'},
'3469344':{'en': 'DIA'},
'3469345':{'en': 'Yoigo'},
'3469346':{'en': 'Yoigo'},
'3469347':{'en': 'Yoigo'},
'3469348':{'en': 'Yoigo'},
'3469349':{'en': 'Yoigo'},
'346935':{'en': 'Yoigo'},
'3469360':{'en': 'DIA'},
'3469361':{'en': 'DIA'},
'3469362':{'en': 'DIA'},
'3469363':{'en': 'DIA'},
'3469364':{'en': 'DIA'},
'3469365':{'en': 'Carrefour'},
'3469366':{'en': 'Carrefour'},
'3469367':{'en': 'Yoigo'},
'3469368':{'en': 'Yoigo'},
'3469369':{'en': 'Yoigo'},
'346937':{'en': 'Yoigo'},
'346938':{'en': 'Yoigo'},
'346939':{'en': 'Yoigo'},
'34694':{'en': 'Movistar'},
'346944':{'en': 'Yoigo'},
'346945':{'en': 'Yoigo'},
'346946':{'en': 'Yoigo'},
'34695':{'en': 'Orange'},
'34696':{'en': 'Movistar'},
'34697':{'en': 'Vodafone'},
'34698':{'en': 'Yoigo'},
'346981':{'en': 'R'},
'346989':{'en': 'Vodafone'},
'34699':{'en': 'Movistar'},
'347110':{'en': 'Zinnia'},
'347111':{'en': 'Vodafone'},
'347117':{'en': 'Vodafone'},
'347121':{'en': 'Yoigo'},
'347122':{'en': 'Yoigo'},
'347123':{'en': 'Yoigo'},
'347124':{'en': 'Yoigo'},
'347125':{'en': 'Yoigo'},
'347126':{'en': 'Yoigo'},
'347127':{'en': 'Yoigo'},
'347128':{'en': 'Yoigo'},
'347170':{'en': 'Movistar'},
'347171':{'en': 'Vodafone'},
'347177':{'en': 'Movistar'},
'3471770':{'en': 'PepePhone'},
'3471771':{'en': 'PepePhone'},
'3471777':{'en': 'PepePhone'},
'347221':{'en': 'Yoigo'},
'347222':{'en': 'Yoigo'},
'347223':{'en': 'Yoigo'},
'347224':{'en': 'Yoigo'},
'347225':{'en': 'Yoigo'},
'347226':{'en': 'Yoigo'},
'3472260':{'en': 'MasMovil'},
'3472261':{'en': 'PepePhone'},
'347227':{'en': 'Yoigo'},
'347228':{'en': 'Yoigo'},
'347277':{'en': 'Vodafone'},
'3474442':{'en': 'Deion'},
'3474443':{'en': 'InfoVOIP'},
'3474447':{'en': 'Jetnet'},
'3474448':{'en': 'Aire Networks'},
'3474449':{'en': 'Alai'},
'347446':{'en': 'PTV'},
'347477':{'en': 'Orange'},
'347478':{'en': 'Orange'},
'3505':{'en': 'GibTel'},
'35060':{'en': 'GibTel'},
'35062':{'en': 'Limba'},
'351609':{'en': 'NOS'},
'35163':{'en': 'NOS'},
'35165':{'en': 'NOS'},
'35166':{'en': 'NOS'},
'35191':{'en': 'Vodafone'},
'3519200':{'en': 'Lycamobile'},
'3519201':{'en': 'Lycamobile'},
'3519202':{'en': 'Lycamobile'},
'3519203':{'en': 'Lycamobile'},
'3519204':{'en': 'Lycamobile'},
'3519205':{'en': 'Lycamobile'},
'351921':{'en': 'Vodafone'},
'3519220':{'en': 'Vodafone'},
'3519221':{'en': 'MEO'},
'3519222':{'en': 'MEO'},
'3519230':{'en': 'NOS'},
'3519231':{'en': 'NOS'},
'3519232':{'en': 'NOS'},
'3519233':{'en': 'NOS'},
'3519234':{'en': 'NOS'},
'3519240':{'en': 'MEO'},
'3519241':{'en': 'MEO'},
'3519242':{'en': 'MEO'},
'3519243':{'en': 'MEO'},
'3519244':{'en': 'MEO'},
'351925':{'en': 'MEO'},
'351926':{'en': 'MEO'},
'351927':{'en': 'MEO'},
'3519280':{'en': 'NOWO'},
'3519281':{'en': 'NOWO'},
'3519285':{'en': 'ONITELECOM'},
'3519290':{'en': 'NOS'},
'3519291':{'en': 'NOS'},
'3519292':{'en': 'NOS'},
'3519293':{'en': 'NOS'},
'3519294':{'en': 'NOS'},
'35193':{'en': 'NOS'},
'35196':{'en': 'MEO'},
'35262':{'en': 'POST'},
'352651':{'en': 'POST'},
'352658':{'en': 'POST'},
'35266':{'en': 'Orange'},
'352671':{'en': 'JOIN'},
'352678':{'en': 'JOIN'},
'35269':{'en': 'Tango'},
'35383':{'en': '3'},
'35385':{'en': 'Meteor'},
'35386':{'en': 'O2'},
'35387':{'en': 'Vodafone'},
'35388':{'en': 'eMobile'},
'35389':{'en': 'Tesco Mobile'},
'3538900':{'en': 'Eircom'},
'353892':{'en': 'Liffey Telecom'},
'353894':{'en': 'Liffey Telecom'},
'353895':{'en': '3'},
'3538960':{'en': 'Virgin Media'},
'3538961':{'en': 'Virgin Media'},
'3538962':{'en': 'Virgin Media'},
'3538970':{'en': 'Carphone Warehouse Ireland Mobile Limited'},
'3538971':{'en': 'Carphone Warehouse Ireland Mobile Limited'},
'3538994':{'en': 'Lycamobile'},
'3538995':{'en': 'Lycamobile'},
'3538996':{'en': 'Lycamobile'},
'3538997':{'en': 'Lycamobile'},
'3538998':{'en': 'Lycamobile'},
'354385':{'en': u('S\u00edminn')},
'354388':{'en': 'IMC'},
'354389':{'en': 'IMC'},
'35461':{'en': 'Vodafone'},
'35462':{'en': 'Vodafone'},
'354630':{'en': 'IMC'},
'354632':{'en': 'Tismi'},
'354637':{'en': u('\u00d6ryggisfjarskipti')},
'354638':{'en': u('\u00d6ryggisfjarskipti')},
'354639':{'en': u('\u00d6ryggisfjarskipti')},
'354640':{'en': u('\u00d6ryggisfjarskipti')},
'354641':{'en': u('\u00d6ryggisfjarskipti')},
'354644':{'en': 'Nova'},
'354646':{'en': 'IMC'},
'354647':{'en': 'IMC'},
'354649':{'en': 'Vodafone'},
'354650':{'en': 'IMC'},
'354651':{'en': 'IMC'},
'354655':{'en': 'Vodafone'},
'354659':{'en': 'Vodafone'},
'35466':{'en': 'Vodafone'},
'35467':{'en': 'Vodafone'},
'354680':{'en': 'Vodafone'},
'354686':{'en': 'Vodafone'},
'354687':{'en': 'Vodafone'},
'354688':{'en': 'Vodafone'},
'35469':{'en': 'Vodafone'},
'354750':{'en': u('S\u00edminn')},
'354755':{'en': u('S\u00edminn')},
'354757':{'en': 'Vodafone'},
'35476':{'en': 'Nova'},
'35477':{'en': 'Nova'},
'35478':{'en': 'Nova'},
'35479':{'en': 'Nova'},
'35482':{'en': 'Vodafone'},
'35483':{'en': u('S\u00edminn')},
'35484':{'en': u('S\u00edminn')},
'35485':{'en': u('S\u00edminn')},
'35486':{'en': u('S\u00edminn')},
'354882':{'en': u('S\u00edminn')},
'354888':{'en': u('S\u00edminn')},
'35489':{'en': u('S\u00edminn')},
'35567':{'en': 'ALBtelecom'},
'35568':{'en': 'Telekom'},
'35569':{'en': 'Vodafone'},
'35672':{'en': 'GO Mobile'},
'35677':{'en': 'Melita Mobile'},
'35679':{'en': 'GO Mobile'},
'35692':{'en': 'Vodafone'},
'35696':{'en': 'YOM'},
'356981':{'en': 'Melita Mobile'},
'356988':{'en': 'GO Mobile'},
'356989':{'en': 'Vodafone'},
'35699':{'en': 'Vodafone'},
'35794':{'en': 'Lemontel'},
'35795':{'en': 'PrimeTel'},
'35796':{'en': 'MTN'},
'35797':{'en': 'Cytamobile-Vodafone'},
'35799':{'en': 'Cytamobile-Vodafone'},
'35840':{'en': 'Telia'},
'35841':{'en': 'DNA'},
'35842':{'en': 'Telia'},
'3584320':{'en': 'Cuuma'},
'3584321':{'en': 'Cuuma'},
'3584322':{'en': 'Benemen Oy'},
'3584323':{'en': 'Top Connect OU'},
'3584324':{'en': 'Nord Connect SIA'},
'358436':{'en': 'DNA'},
'358438':{'en': 'DNA'},
'35844':{'en': 'DNA'},
'358450':{'en': 'Telia'},
'358451':{'en': 'Elisa'},
'358452':{'en': 'Elisa'},
'358453':{'en': 'Elisa'},
'3584540':{'en': 'MobiWeb'},
'3584541':{'en': 'AinaCom'},
'3584542':{'en': 'Nokia'},
'3584543':{'en': 'Nokia'},
'3584544':{'en': 'Nokia'},
'3584545':{'en': 'Interactive Digital Media'},
'3584546':{'en': 'NextGen Mobile / CardBoardFish'},
'3584547':{'en': 'SMS Provider Corp'},
'3584548':{'en': 'Voxbone'},
'3584549':{'en': 'Beepsend'},
'3584550':{'en': 'Suomen Virveverkko'},
'3584552':{'en': 'Suomen Virveverkko'},
'3584554':{'en': 'Suomen Virveverkko'},
'3584555':{'en': 'Nokia Solutions and Networks'},
'3584556':{'en': 'Liikennevirasto'},
'3584557':{'en': 'Compatel'},
'3584558':{'en': 'Suomen Virveverkko'},
'3584559':{'en': 'MI'},
'358456':{'en': 'Elisa'},
'3584570':{'en': 'AMT'},
'3584571':{'en': 'Tismi'},
'3584572':{'en': 'Telavox AB'},
'3584573':{'en': 'AMT'},
'3584574':{'en': 'DNA'},
'3584575':{'en': 'AMT'},
'3584576':{'en': 'DNA'},
'3584577':{'en': 'DNA'},
'3584578':{'en': 'DNA'},
'3584579':{'en': 'DNA'},
'358458':{'en': 'Elisa'},
'35846':{'en': 'Elisa'},
'35850':{'en': 'Elisa'},
'35987':{'en': 'Vivacom'},
'35988':{'en': 'A1'},
'35989':{'en': 'Telenor'},
'359988':{'en': 'Bob'},
'359989':{'en': 'A1'},
'359996':{'en': 'Bulsatcom'},
'359999':{'en': 'MAX'},
'3620':{'en': 'Telenor'},
'3630':{'en': 'Magyar Telekom'},
'36312000':{'en': 'Netfone Telecom'},
'36312001':{'en': 'Netfone Telecom'},
'3631310':{'en': 'Vodafone'},
'3631311':{'en': 'Vodafone'},
'3631312':{'en': 'Vodafone'},
'3631313':{'en': 'Vodafone'},
'3631314':{'en': 'Vodafone'},
'3631315':{'en': 'Vodafone'},
'3631316':{'en': 'Vodafone'},
'3631317':{'en': 'Vodafone'},
'3631318':{'en': 'Vodafone'},
'36313190':{'en': 'Vodafone'},
'36313191':{'en': 'Vodafone'},
'36313192':{'en': 'Vodafone'},
'36313193':{'en': 'Vodafone'},
'36313194':{'en': 'Vodafone'},
'36313195':{'en': 'Vodafone'},
'36313196':{'en': 'Vodafone'},
'36313197':{'en': 'Vodafone'},
'36313199':{'en': 'Vodafone'},
'3631320':{'en': 'Vodafone'},
'3631321':{'en': 'Vodafone'},
'3631322':{'en': 'Vodafone'},
'3631323':{'en': 'Vodafone'},
'3631324':{'en': 'Vodafone'},
'3631325':{'en': 'Vodafone'},
'3631326':{'en': 'Vodafone'},
'3631327':{'en': 'Vodafone'},
'3631328':{'en': 'Vodafone'},
'36313290':{'en': 'Vodafone'},
'36313291':{'en': 'Vodafone'},
'36313292':{'en': 'Vodafone'},
'3631330':{'en': 'Vodafone'},
'3631331':{'en': 'Vodafone'},
'3631332':{'en': 'Vodafone'},
'36313330':{'en': 'Vidanet'},
'36313331':{'en': 'Vidanet'},
'36313666':{'en': 'Vodafone'},
'36317000':{'en': 'TARR'},
'36317001':{'en': 'TARR'},
'36317002':{'en': 'TARR'},
'36317003':{'en': 'TARR'},
'36317004':{'en': 'TARR'},
'3631770':{'en': 'UPC'},
'3631771':{'en': 'UPC'},
'363178':{'en': 'UPC'},
'3631790':{'en': 'UPC'},
'36501':{'en': 'DIGI'},
'36502':{'en': 'DIGI'},
'3670':{'en': 'Vodafone'},
'37060':{'en': 'Tele 2'},
'37061':{'en': 'Omnitel'},
'37062':{'en': 'Omnitel'},
'37063':{'en': u('BIT\u00c4')},
'37064':{'en': u('BIT\u00c4')},
'370645':{'en': 'Tele 2'},
'370646':{'en': 'Tele 2'},
'370647':{'en': 'Tele 2'},
'370648':{'en': 'Tele 2'},
'37065':{'en': u('BIT\u00c4')},
'370660':{'en': u('BIT\u00c4')},
'370661':{'en': u('BIT\u00c4')},
'3706610':{'en': 'Tele 2'},
'370662':{'en': 'Omnitel'},
'37066313':{'en': u('BIT\u00c4')},
'37066314':{'en': u('BIT\u00c4')},
'37066315':{'en': u('BIT\u00c4')},
'37066316':{'en': u('BIT\u00c4')},
'37066317':{'en': u('BIT\u00c4')},
'37066318':{'en': u('BIT\u00c4')},
'37066319':{'en': u('BIT\u00c4')},
'37066320':{'en': u('BIT\u00c4')},
'37066323':{'en': u('BIT\u00c4')},
'37066522':{'en': u('BIT\u00c4')},
'3706660':{'en': u('BIT\u00c4')},
'3706661':{'en': u('BIT\u00c4')},
'37066622':{'en': u('BIT\u00c4')},
'37066623':{'en': u('BIT\u00c4')},
'37066624':{'en': u('BIT\u00c4')},
'37066625':{'en': u('BIT\u00c4')},
'37066626':{'en': u('BIT\u00c4')},
'37066627':{'en': u('BIT\u00c4')},
'37066628':{'en': u('BIT\u00c4')},
'37066629':{'en': u('BIT\u00c4')},
'3706665':{'en': u('BIT\u00c4')},
'3706666':{'en': 'Tele 2'},
'3706667':{'en': u('BIT\u00c4')},
'3706668':{'en': u('BIT\u00c4')},
'3706669':{'en': u('BIT\u00c4')},
'3706670':{'en': u('BIT\u00c4')},
'37066711':{'en': u('BIT\u00c4')},
'37066719':{'en': u('BIT\u00c4')},
'37066728':{'en': u('BIT\u00c4')},
'37066729':{'en': u('BIT\u00c4')},
'3706676':{'en': u('BIT\u00c4')},
'3706677':{'en': u('BIT\u00c4')},
'3706678':{'en': u('BIT\u00c4')},
'3706679':{'en': u('BIT\u00c4')},
'3706680':{'en': 'Tele 2'},
'37066839':{'en': 'Tele 2'},
'37066840':{'en': 'Tele 2'},
'37066841':{'en': 'Tele 2'},
'37066842':{'en': 'Tele 2'},
'37066860':{'en': 'Tele 2'},
'37066861':{'en': 'Tele 2'},
'37066862':{'en': 'Tele 2'},
'37066863':{'en': 'Tele 2'},
'37066864':{'en': 'Tele 2'},
'37066865':{'en': 'Tele 2'},
'37066876':{'en': u('BIT\u00c4')},
'37066877':{'en': u('BIT\u00c4')},
'37066900':{'en': u('BIT\u00c4')},
'3706696':{'en': u('BIT\u00c4')},
'3706697':{'en': u('BIT\u00c4')},
'3706698':{'en': u('BIT\u00c4')},
'3706699':{'en': u('BIT\u00c4')},
'37067':{'en': 'Tele 2'},
'370680':{'en': 'Omnitel'},
'370681':{'en': u('BIT\u00c4')},
'370682':{'en': 'Omnitel'},
'370683':{'en': 'Tele 2'},
'370684':{'en': 'Tele 2'},
'370685':{'en': u('BIT\u00c4')},
'370686':{'en': 'Omnitel'},
'370687':{'en': 'Omnitel'},
'370688':{'en': 'Omnitel'},
'370689':{'en': u('BIT\u00c4')},
'370690':{'en': u('BIT\u00c4')},
'370691':{'en': u('BIT\u00c4')},
'370692':{'en': 'Omnitel'},
'370693':{'en': 'Omnitel'},
'370694':{'en': 'Omnitel'},
'370695':{'en': 'Omnitel'},
'370696':{'en': 'Omnitel'},
'37069742':{'en': u('BIT\u00c4')},
'37069743':{'en': u('BIT\u00c4')},
'370698':{'en': 'Omnitel'},
'370699':{'en': u('BIT\u00c4')},
'37250':{'en': 'Telia Eesti AS'},
'372519':{'en': 'Telia Eesti AS'},
'37252':{'en': 'Telia Eesti AS'},
'372530':{'en': 'Telia Eesti AS'},
'372533':{'en': 'Telia Eesti AS'},
'372534':{'en': 'Telia Eesti AS'},
'372536':{'en': 'Telia Eesti AS'},
'372537':{'en': 'Telia Eesti AS'},
'372538':{'en': 'Telia Eesti AS'},
'372539':{'en': 'Telia Eesti AS'},
'37254':{'en': 'Telia Eesti AS'},
'372545':{'en': 'Elisa'},
'3725461':{'en': 'Elisa'},
'3725462':{'en': 'Elisa'},
'3725463':{'en': 'Elisa'},
'37254664':{'en': 'Elisa'},
'37254665':{'en': 'Elisa'},
'37254667':{'en': 'Elisa'},
'37254668':{'en': 'Elisa'},
'37254669':{'en': 'Elisa'},
'37255':{'en': 'Tele 2'},
'37256':{'en': 'Elisa'},
'37257':{'en': 'Telia Eesti AS'},
'37258':{'en': 'Tele 2'},
'372589':{'en': 'Elisa'},
'37259':{'en': 'Telia Eesti AS'},
'37259120':{'en': 'Tele 2'},
'37259121':{'en': 'Tele 2'},
'37259140':{'en': 'Tele 2'},
'372591410':{'en': 'Tele 2'},
'372591411':{'en': 'Tele 2'},
'372591412':{'en': 'Tele 2'},
'372591413':{'en': 'Tele 2'},
'37259144':{'en': 'Tele 2'},
'37281':{'en': 'Telia Eesti AS'},
'3728110':{'en': 'Tele 2'},
'3728111':{'en': 'Elisa'},
'37282':{'en': 'Elisa'},
'3728200':{'en': 'Telia Eesti AS'},
'3728204':{'en': 'Tele 2'},
'37282056':{'en': 'Tele 2'},
'37282057':{'en': 'Tele 2'},
'37282058':{'en': 'Tele 2'},
'37282059':{'en': 'Tele 2'},
'3728206':{'en': 'Tele 2'},
'3728216':{'en': 'Tele 2'},
'3728217':{'en': 'Tele 2'},
'3728218':{'en': 'Tele 2'},
'37282199':{'en': 'Tele 2'},
'3728282':{'en': 'Telia Eesti AS'},
'37283':{'en': 'Tele 2'},
'37284':{'en': 'Tele 2'},
'37284510':{'en': 'Telia Eesti AS'},
'37284511':{'en': 'Telia Eesti AS'},
'37284512':{'en': 'Telia Eesti AS'},
'37356':{'en': 'IDC'},
'37360':{'en': 'Orange'},
'373610':{'en': 'Orange'},
'373611':{'en': 'Orange'},
'373620':{'en': 'Orange'},
'373621':{'en': 'Orange'},
'37367':{'en': 'Moldtelecom'},
'37368':{'en': 'Orange'},
'37369':{'en': 'Orange'},
'37376':{'en': 'Moldcell'},
'373774':{'en': 'IDC'},
'373775':{'en': 'IDC'},
'373777':{'en': 'IDC'},
'373778':{'en': 'IDC'},
'373779':{'en': 'IDC'},
'37378':{'en': 'Moldcell'},
'37379':{'en': 'Moldcell'},
'37433':{'en': 'Beeline', 'ru': u('\u0411\u0438\u043b\u0430\u0439\u043d')},
'37441':{'en': 'Ucom', 'ru': u('\u042e\u043a\u043e\u043c')},
'37443':{'en': 'Beeline', 'ru': u('\u0411\u0438\u043b\u0430\u0439\u043d')},
'37444':{'en': 'Ucom', 'ru': u('\u042e\u043a\u043e\u043c')},
'37449':{'en': 'VivaCell-MTS', 'ru': u('\u0412\u0438\u0432\u0430\u0421\u0435\u043b\u043b-\u041c\u0422\u0421')},
'3745':{'en': 'Ucom', 'ru': u('\u042e\u043a\u043e\u043c')},
'3747':{'en': 'VivaCell-MTS', 'ru': u('\u0412\u0438\u0432\u0430\u0421\u0435\u043b\u043b-\u041c\u0422\u0421')},
'37488':{'en': 'VivaCell-MTS', 'ru': u('\u0412\u0438\u0432\u0430\u0421\u0435\u043b\u043b-\u041c\u0422\u0421')},
'37491':{'en': 'Beeline', 'ru': u('\u0411\u0438\u043b\u0430\u0439\u043d')},
'37493':{'en': 'VivaCell-MTS', 'ru': u('\u0412\u0438\u0432\u0430\u0421\u0435\u043b\u043b-\u041c\u0422\u0421')},
'37494':{'en': 'VivaCell-MTS', 'ru': u('\u0412\u0438\u0432\u0430\u0421\u0435\u043b\u043b-\u041c\u0422\u0421')},
'37495':{'en': 'Ucom', 'ru': u('\u042e\u043a\u043e\u043c')},
'37496':{'en': 'Beeline', 'ru': u('\u0411\u0438\u043b\u0430\u0439\u043d')},
'37498':{'en': 'VivaCell-MTS', 'ru': u('\u0412\u0438\u0432\u0430\u0421\u0435\u043b\u043b-\u041c\u0422\u0421')},
'37499':{'en': 'Beeline', 'ru': u('\u0411\u0438\u043b\u0430\u0439\u043d')},
'37525':{'be': u('\u0411\u0435\u0421\u0422'), 'en': 'life:)', 'ru': 'life:)'},
'375291':{'be': 'Velcom', 'en': 'Velcom', 'ru': 'Velcom'},
'375292':{'be': u('\u041c\u0422\u0421'), 'en': 'MTS', 'ru': u('\u041c\u0422\u0421')},
'375293':{'be': 'Velcom', 'en': 'Velcom', 'ru': 'Velcom'},
'375294':{'be': u('\u0411\u0435\u043b\u0421\u0435\u043b'), 'en': 'Belcel', 'ru': u('\u0411\u0435\u043b\u0421\u0435\u043b')},
'375295':{'be': u('\u041c\u0422\u0421'), 'en': 'MTS', 'ru': u('\u041c\u0422\u0421')},
'375296':{'be': 'Velcom', 'en': 'Velcom', 'ru': 'Velcom'},
'375297':{'be': u('\u041c\u0422\u0421'), 'en': 'MTS', 'ru': u('\u041c\u0422\u0421')},
'375298':{'be': u('\u041c\u0422\u0421'), 'en': 'MTS', 'ru': u('\u041c\u0422\u0421')},
'375299':{'be': 'Velcom', 'en': 'Velcom', 'ru': 'Velcom'},
'37533':{'be': u('\u041c\u0422\u0421'), 'en': 'MTS', 'ru': u('\u041c\u0422\u0421')},
'37544':{'be': 'Velcom', 'en': 'Velcom', 'ru': 'Velcom'},
'3763':{'en': 'Mobiland'},
'3765':{'en': 'Mobiland'},
'3766':{'en': 'Mobiland'},
'3773':{'en': 'Monaco Telecom'},
'3774':{'en': 'Monaco Telecom'},
'3776':{'en': 'Monaco Telecom'},
'37861':{'en': 'TELENET'},
'37866':{'en': 'Telecom Italia San Marino'},
'38050':{'en': 'Vodafone', 'uk': u('Vodafone \u0423\u043a\u0440\u0430\u0457\u043d\u0430')},
'38063':{'en': 'lifecell', 'uk': 'lifecell'},
'38066':{'en': 'Vodafone', 'uk': u('Vodafone \u0423\u043a\u0440\u0430\u0457\u043d\u0430')},
'38067':{'en': 'Kyivstar', 'uk': u('\u041a\u0438\u0457\u0432\u0441\u0442\u0430\u0440')},
'38068':{'en': 'Kyivstar', 'uk': u('\u041a\u0438\u0457\u0432\u0441\u0442\u0430\u0440')},
'38073':{'en': 'lifecell', 'uk': 'lifecell'},
'38091':{'en': 'TriMob', 'uk': u('\u0422\u0440\u0438\u041c\u043e\u0431')},
'38092':{'en': 'PEOPLEnet', 'uk': 'PEOPLEnet'},
'38093':{'en': 'lifecell', 'uk': 'lifecell'},
'38094':{'en': 'Intertelecom', 'uk': u('\u0406\u043d\u0442\u0435\u0440\u0442\u0435\u043b\u0435\u043a\u043e\u043c')},
'38095':{'en': 'Vodafone', 'uk': u('Vodafone \u0423\u043a\u0440\u0430\u0457\u043d\u0430')},
'38096':{'en': 'Kyivstar', 'uk': u('\u041a\u0438\u0457\u0432\u0441\u0442\u0430\u0440')},
'38097':{'en': 'Kyivstar', 'uk': u('\u041a\u0438\u0457\u0432\u0441\u0442\u0430\u0440')},
'38098':{'en': 'Kyivstar', 'uk': u('\u041a\u0438\u0457\u0432\u0441\u0442\u0430\u0440')},
'38099':{'en': 'Vodafone', 'uk': u('Vodafone \u0423\u043a\u0440\u0430\u0457\u043d\u0430')},
'38160':{'en': 'VIP'},
'38161':{'en': 'VIP'},
'38162':{'en': 'Telenor'},
'38163':{'en': 'Telenor'},
'38164':{'en': 'Telekom Srbija a.d.'},
'38165':{'en': 'Telekom Srbija a.d.'},
'38166':{'en': 'Telekom Srbija a.d.'},
'381677':{'en': 'GLOBALTEL'},
'381678':{'en': 'Vectone Mobile'},
'38168':{'en': 'VIP'},
'38169':{'en': 'Telenor'},
'38260':{'en': 'm:tel'},
'38263':{'en': 'Telenor'},
'38266':{'en': 'Telekom'},
'38267':{'en': 'Telekom'},
'38268':{'en': 'm:tel'},
'38269':{'en': 'Telenor'},
'38343':{'en': 'IPKO'},
'38344':{'en': 'vala'},
'383451':{'en': 'vala'},
'383452':{'en': 'vala'},
'383453':{'en': 'vala'},
'383454':{'en': 'vala'},
'383455':{'en': 'Z Mobile'},
'383456':{'en': 'Z Mobile'},
'383457':{'en': 'vala'},
'383458':{'en': 'vala'},
'383459':{'en': 'vala'},
'383461':{'en': 'Z Mobile'},
'3834710':{'en': 'mts d.o.o.'},
'3834711':{'en': 'mts d.o.o.'},
'3834712':{'en': 'mts d.o.o.'},
'3834713':{'en': 'mts d.o.o.'},
'3834714':{'en': 'mts d.o.o.'},
'3834715':{'en': 'mts d.o.o.'},
'38348':{'en': 'IPKO'},
'38349':{'en': 'IPKO'},
'38590':{'en': 'Tele2'},
'38591':{'en': 'A1 Telekom'},
'38592':{'en': 'A1 Telekom'},
'38595':{'en': 'Tele2'},
'385970':{'en': 'Hrvatski Telekom'},
'385975':{'en': 'Telefocus'},
'385976':{'en': 'Hrvatski Telekom'},
'385977':{'en': 'Hrvatski Telekom'},
'385979':{'en': 'Hrvatski Telekom'},
'38598':{'en': 'Hrvatski Telekom'},
'38599':{'en': 'Hrvatski Telekom'},
'38630':{'en': 'A1'},
'38631':{'en': 'Telekom Slovenije'},
'38640':{'en': 'A1'},
'38641':{'en': 'Telekom Slovenije'},
'38643':{'en': 'Telekom Slovenije'},
'38649':{'en': 'Telekom Slovenije'},
'38651':{'en': 'Telekom Slovenije'},
'38664':{'en': 'T-2'},
'386651':{'en': u('S\u017d - Infrastruktura')},
'386655':{'en': 'Telekom Slovenije'},
'386656':{'en': 'Telekom Slovenije'},
'386657':{'en': 'Novatel'},
'38668':{'en': 'A1'},
'38669':{'en': 'A1'},
'3866910':{'en': 'Compatel'},
'38670':{'en': 'Telemach'},
'38671':{'en': 'Telemach'},
'38760':{'en': 'BH Telecom'},
'38761':{'en': 'BH Telecom'},
'38762':{'en': 'BH Telecom'},
'38763':{'en': 'HT ERONET'},
'38764':{'en': 'HT ERONET'},
'38765':{'en': 'm:tel'},
'38766':{'en': 'm:tel'},
'38767':{'en': 'm:tel'},
'38970':{'en': 'T-Mobile'},
'38971':{'en': 'T-Mobile'},
'38972':{'en': 'T-Mobile'},
'389732':{'en': 'Vip'},
'389733':{'en': 'ALO Telecom'},
'389734':{'en': 'Vip'},
'389742':{'en': 'T-Mobile'},
'3897421':{'en': 'Mobik'},
'389746':{'en': 'T-Mobile'},
'389747':{'en': 'T-Mobile'},
'38975':{'en': 'Vip'},
'38976':{'en': 'Vip'},
'38977':{'en': 'Vip'},
'38978':{'en': 'Vip'},
'38979':{'en': 'Lycamobile'},
'39319':{'en': 'Intermatica'},
'3932':{'en': 'WIND'},
'3933':{'en': 'TIM'},
'3934':{'en': 'Vodafone'},
'3936':{'en': 'TIM'},
'39370':{'en': 'TIM'},
'39373':{'en': '3 Italia'},
'39377':{'en': 'Vodafone'},
'3938':{'en': 'WIND'},
'39383':{'en': 'Vodafone'},
'3939':{'en': '3 Italia'},
'407000':{'en': 'Enigma-System'},
'407013':{'en': 'Lycamobile'},
'407014':{'en': 'Lycamobile'},
'407015':{'en': 'Lycamobile'},
'407016':{'en': 'Lycamobile'},
'407017':{'en': 'Lycamobile'},
'407018':{'en': 'Lycamobile'},
'407019':{'en': 'Lycamobile'},
'40702':{'en': 'Lycamobile'},
'40705':{'en': 'Iristel'},
'40711':{'en': 'Telekom'},
'40712':{'en': '2K Telecom'},
'4072':{'en': 'Vodafone'},
'4073':{'en': 'Vodafone'},
'4074':{'en': 'Orange'},
'4075':{'en': 'Orange'},
'4076':{'en': 'Telekom'},
'40770':{'en': 'Digi Mobil'},
'40771':{'en': 'Digi Mobil'},
'40772':{'en': 'Digi Mobil'},
'40773':{'en': 'Digi Mobil'},
'40774':{'en': 'Digi Mobil'},
'40775':{'en': 'Digi Mobil'},
'40776':{'en': 'Digi Mobil'},
'40777':{'en': 'Digi Mobil'},
'4078':{'en': 'Telekom'},
'4079':{'en': 'Vodafone'},
'417500':{'en': 'Swisscom'},
'41754':{'en': 'Swisscom'},
'417550':{'en': 'Swisscom'},
'417551':{'en': 'Swisscom'},
'417552':{'en': 'Swisscom'},
'417553':{'en': 'Swisscom'},
'417600':{'en': 'Sunrise'},
'41762':{'en': 'Sunrise'},
'41763':{'en': 'Sunrise'},
'41764':{'en': 'Sunrise'},
'41765':{'en': 'Sunrise'},
'41766':{'en': 'Sunrise'},
'41767':{'en': 'Sunrise'},
'41768':{'en': 'Sunrise'},
'41769':{'en': 'Sunrise'},
'41770':{'en': 'Swisscom'},
'417710':{'en': 'Swisscom'},
'417712':{'en': 'Swisscom'},
'417713':{'en': 'Swisscom'},
'417715':{'en': 'Swisscom'},
'41772':{'en': 'Sunrise'},
'417730':{'en': 'Sunrise'},
'4177310':{'en': 'Sunrise'},
'4177311':{'en': 'Sunrise'},
'4177312':{'en': 'Sunrise'},
'4177313':{'en': 'Sunrise'},
'4177314':{'en': 'Sunrise'},
'4177315':{'en': 'Sunrise'},
'4177316':{'en': 'Sunrise'},
'4177357':{'en': 'In&Phone'},
'41774':{'en': 'Swisscom'},
'417750':{'en': 'Swisscom'},
'417751':{'en': 'Swisscom'},
'417752':{'en': 'Swisscom'},
'417753':{'en': 'Swisscom'},
'417780':{'en': 'BeeOne Communications'},
'417781':{'en': 'BeeOne Communications'},
'417788':{'en': 'Vectone Mobile Limited (Mundio)'},
'417789':{'en': 'Vectone Mobile Limited (Mundio)'},
'41779':{'en': 'Lycamobile'},
'41780':{'en': 'Salt'},
'41781':{'en': 'Salt'},
'41782':{'en': 'Salt'},
'41783':{'en': 'Salt'},
'417840':{'en': 'UPC Switzerland'},
'417841':{'en': 'UPC Switzerland'},
'417842':{'en': 'UPC Switzerland'},
'4178490':{'en': 'Telecom26 AG'},
'41785':{'en': 'Salt'},
'41786':{'en': 'Salt'},
'41787':{'en': 'Salt'},
'41788':{'en': 'Salt'},
'41789':{'en': 'Salt'},
'41790':{'en': 'Swisscom'},
'41791':{'en': 'Swisscom'},
'41792':{'en': 'Swisscom'},
'41793':{'en': 'Swisscom'},
'41794':{'en': 'Swisscom'},
'41795':{'en': 'Swisscom'},
'41796':{'en': 'Swisscom'},
'41797':{'en': 'Swisscom'},
'41798':{'en': 'Swisscom'},
'417990':{'en': 'Swisscom'},
'417991':{'en': 'Swisscom'},
'417992':{'en': 'Swisscom'},
'417993':{'en': 'Swisscom'},
'417994':{'en': 'Swisscom'},
'417995':{'en': 'Swisscom'},
'417996':{'en': 'Swisscom'},
'4179977':{'en': 'Relario AG (Bebbicell)'},
'4179978':{'en': 'Relario AG (Bebbicell)'},
'4179979':{'en': 'Relario AG (Bebbicell)'},
'417999':{'en': 'Comfone AG'},
'420601':{'en': 'O2'},
'420602':{'en': 'O2'},
'420603':{'en': 'T-Mobile'},
'420604':{'en': 'T-Mobile'},
'420605':{'en': 'T-Mobile'},
'420606':{'en': 'O2'},
'420607':{'en': 'O2'},
'420608':{'en': 'Vodafone'},
'420702':{'en': 'O2'},
'42070300':{'en': 'T-Mobile'},
'4207031':{'en': 'T-Mobile'},
'4207032':{'en': 'T-Mobile'},
'4207033':{'en': 'T-Mobile'},
'4207034':{'en': 'T-Mobile'},
'4207035':{'en': 'T-Mobile'},
'4207036':{'en': 'T-Mobile'},
'42070370':{'en': 'FAYN Telecommunications'},
'42070373':{'en': 'COMA'},
'4207038':{'en': 'T-Mobile'},
'4207039':{'en': 'T-Mobile'},
'4207040':{'en': 'SAZKA sazkova kancelar, a.s'},
'4207041':{'en': 'SAZKA sazkova kancelar, a.s'},
'4207042':{'en': 'SAZKA sazkova kancelar, a.s'},
'4207043':{'en': 'SAZKA sazkova kancelar, a.s'},
'4207044':{'en': 'SAZKA sazkova kancelar, a.s'},
'4207045':{'en': 'SAZKA sazkova kancelar, a.s'},
'4207047':{'en': 'SAZKA sazkova kancelar, a.s'},
'4207050':{'en': 'O2'},
'4207051':{'en': 'O2'},
'4207052':{'en': 'O2'},
'4207053':{'en': 'O2'},
'4207054':{'en': 'O2'},
'42070570':{'en': 'T-Mobile'},
'42072':{'en': 'O2'},
'4207300':{'en': 'T-Mobile'},
'4207301':{'en': 'T-Mobile'},
'4207302':{'en': 'T-Mobile'},
'42073030':{'en': 'T-Mobile'},
'42073033':{'en': 'Axfone'},
'42073035':{'en': 'MATERNA Communications'},
'42073040':{'en': 'Compatel'},
'42073041':{'en': 'SMART Comp'},
'42073042':{'en': 'SMART Comp'},
'42073043':{'en': 'PODA a.s. (SkyNet)'},
'42073044':{'en': 'Vodafone'},
'42073045':{'en': 'Vodafone'},
'42073046':{'en': 'Vodafone'},
'42073047':{'en': 'Vodafone'},
'42073048':{'en': 'Vodafone'},
'4207305':{'en': 'T-Mobile'},
'4207306':{'en': 'T-Mobile'},
'42073070':{'en': 'T-Mobile'},
'42073072':{'en': 'Amcatel'},
'42073073':{'en': 'T-Mobile'},
'42073077':{'en': 'T-Mobile'},
'4207308':{'en': 'T-Mobile'},
'4207309':{'en': 'T-Mobile'},
'420731':{'en': 'T-Mobile'},
'420732':{'en': 'T-Mobile'},
'420733':{'en': 'T-Mobile'},
'420734':{'en': 'T-Mobile'},
'420735':{'en': 'T-Mobile'},
'420736':{'en': 'T-Mobile'},
'420737':{'en': 'T-Mobile'},
'420738':{'en': 'T-Mobile'},
'420739':{'en': 'T-Mobile'},
'4207700':{'en': 'Vodafone'},
'4207701':{'en': 'Vodafone'},
'4207702':{'en': 'Vodafone'},
'4207703':{'en': 'Vodafone'},
'4207704':{'en': 'Vodafone'},
'42077050':{'en': 'Compatel'},
'42077051':{'en': '3ton s.r.o.'},
'42077052':{'en': '3ton s.r.o.'},
'42077055':{'en': 'ASTELNET'},
'4207706':{'en': 'Vodafone'},
'42077071':{'en': 'Cesky bezdrat'},
'42077072':{'en': 'Cesky bezdrat'},
'42077073':{'en': 'T-Mobile'},
'42077077':{'en': 'T-Mobile'},
'42077080':{'en': 'Vodafone'},
'42077081':{'en': 'Vodafone'},
'42077082':{'en': 'Vodafone'},
'42077083':{'en': 'Vodafone'},
'42077084':{'en': 'Vodafone'},
'42077100':{'en': 'TT Quality s.r.o.'},
'42077111':{'en': 'miniTEL'},
'42077177':{'en': 'MONTYHO TECHNOLOGY s.r.o. (CANISTEC)'},
'42077200':{'en': 'TT Quality s.r.o.'},
'42077272':{'en': 'IPEX'},
'42077273':{'en': 'IPEX'},
'42077277':{'en': 'Dragon Internet'},
'420773':{'en': 'Vodafone'},
'420774':{'en': 'Vodafone'},
'420775':{'en': 'Vodafone'},
'420776':{'en': 'Vodafone'},
'420777':{'en': 'Vodafone'},
'4207780':{'en': 'Vodafone'},
'42077811':{'en': 'Vodafone'},
'42077812':{'en': 'Vodafone'},
'42077813':{'en': 'Vodafone'},
'42077814':{'en': 'Vodafone'},
'42077815':{'en': 'Vodafone'},
'42077816':{'en': 'Vodafone'},
'42077817':{'en': 'Vodafone'},
'42077818':{'en': 'Vodafone'},
'42077819':{'en': 'Vodafone'},
'4207782':{'en': 'Vodafone'},
'4207783':{'en': 'Vodafone'},
'4207784':{'en': 'Vodafone'},
'4207785':{'en': 'Vodafone'},
'4207786':{'en': 'Vodafone'},
'4207787':{'en': 'Vodafone'},
'42077880':{'en': 'ha-vel internet'},
'42077881':{'en': 'Vodafone'},
'42077882':{'en': 'Vodafone'},
'42077883':{'en': 'Vodafone'},
'42077884':{'en': 'Vodafone'},
'42077885':{'en': 'Vodafone'},
'42077886':{'en': 'Vodafone'},
'42077887':{'en': 'Vodafone'},
'42077888':{'en': 'Vodafone'},
'42077889':{'en': 'Vodafone'},
'4207789':{'en': 'Vodafone'},
'42077900':{'en': 'TT Quality s.r.o.'},
'42077977':{'en': 'TT Quality s.r.o.'},
'42077990':{'en': 'ha-vel internet'},
'42077997':{'en': 'Plus4U Mobile s.r.o.'},
'42077999':{'en': 'T-Mobile'},
'42079000':{'en': 'Nordic Telecom s.r.o.(Air Telecom - MobilKom)'},
'42079058':{'en': 'T-Mobile'},
'42079083':{'en': 'T-Mobile'},
'4207910':{'en': 'TRAVEL TELEKOMMUNIKATION'},
'42079191':{'en': 'T-Mobile'},
'42079192':{'en': '3ton s.r.o.'},
'42079193':{'en': 'GOPE Systems a.s.'},
'4207920':{'en': 'O2'},
'4207921':{'en': 'O2'},
'4207922':{'en': 'O2'},
'4207923':{'en': 'O2'},
'42079234':{'en': 'Tesco Mobile CR'},
'42079235':{'en': 'Tesco Mobile CR'},
'42079238':{'en': 'Tesco Mobile CR'},
'42079240':{'en': 'Tesco Mobile CR'},
'42079241':{'en': 'Tesco Mobile CR'},
'42079242':{'en': 'Tesco Mobile CR'},
'42079243':{'en': 'Tesco Mobile CR'},
'42079244':{'en': 'Tesco Mobile CR'},
'42079245':{'en': 'O2'},
'42079246':{'en': 'O2'},
'42079247':{'en': 'O2'},
'42079248':{'en': 'O2'},
'42079249':{'en': 'O2'},
'4207925':{'en': 'O2'},
'42079260':{'en': 'SIA Net Balt'},
'4207927':{'en': 'O2'},
'42079390':{'en': 'T-Mobile'},
'4207940':{'en': 'Vectone Distribution Czech Republic s.r.o(Mundio)'},
'4207950':{'en': 'Vectone Distribution Czech Republic s.r.o(Mundio)'},
'42079750':{'en': 'Dial Telecom'},
'4207976':{'en': 'T-Mobile'},
'42079770':{'en': 'T-Mobile'},
'42079771':{'en': 'T-Mobile'},
'42079772':{'en': 'T-Mobile'},
'42079775':{'en': 'T-Mobile'},
'42079777':{'en': 'T-Mobile'},
'42079779':{'en': 'T-Mobile'},
'4207978':{'en': 'T-Mobile'},
'42079797':{'en': 'T-Mobile'},
'42079799':{'en': 'T-Mobile'},
'42079900':{'en': 'MAXPROGRES'},
'42079910':{'en': 'New Telekom'},
'42079911':{'en': 'New Telekom'},
'42079920':{'en': 'METRONET'},
'42079950':{'en': 'TERMS'},
'42079951':{'en': 'TERMS'},
'42079952':{'en': 'TERMS'},
'42079979':{'en': 'miniTEL'},
'42079999':{'en': 'MAXPROGRES'},
'42093':{'en': 'T-Mobile'},
'420962':{'en': 'O2'},
'420963':{'en': 'T-Mobile'},
'420964':{'en': 'T-Mobile'},
'420965':{'en': 'T-Mobile'},
'420966':{'en': 'O2'},
'420967':{'en': 'Vodafone'},
'421901':{'en': 'T-Mobile (Slovak Telekom)'},
'421902':{'en': 'T-Mobile (Slovak Telekom)'},
'421903':{'en': 'T-Mobile (Slovak Telekom)'},
'421904':{'en': 'T-Mobile (Slovak Telekom)'},
'421905':{'en': 'Orange'},
'421906':{'en': 'Orange'},
'421907':{'en': 'Orange'},
'421908':{'en': 'Orange'},
'4219091':{'en': 'T-Mobile (Slovak Telekom)'},
'4219092':{'en': 'T-Mobile (Slovak Telekom)'},
'4219093':{'en': 'T-Mobile (Slovak Telekom)'},
'4219094':{'en': 'T-Mobile (Slovak Telekom)'},
'4219095':{'en': 'T-Mobile (Slovak Telekom)'},
'4219096':{'en': 'T-Mobile (Slovak Telekom)'},
'4219097':{'en': 'T-Mobile (Slovak Telekom)'},
'4219098':{'en': 'T-Mobile (Slovak Telekom)'},
'4219099':{'en': 'T-Mobile (Slovak Telekom)'},
'421910':{'en': 'T-Mobile (Slovak Telekom)'},
'421911':{'en': 'T-Mobile (Slovak Telekom)'},
'421912':{'en': 'T-Mobile (Slovak Telekom)'},
'421914':{'en': 'T-Mobile (Slovak Telekom)'},
'421915':{'en': 'Orange'},
'421916':{'en': 'Orange'},
'421917':{'en': 'Orange'},
'421918':{'en': 'Orange'},
'421919':{'en': 'Orange'},
'421940':{'en': 'Telefonica O2'},
'42194312':{'en': 'Alternet, s.r.o.'},
'42194333':{'en': 'IPfon, s.r.o.'},
'421944':{'en': 'Telefonica O2'},
'421945':{'en': 'Orange'},
'421947':{'en': 'Telefonica O2'},
'421948':{'en': 'Telefonica O2'},
'421949':{'en': 'Telefonica O2'},
'421950':{'en': '4ka of SWAN'},
'421951':{'en': '4ka of SWAN'},
'4219598':{'en': 'Slovak Republic Railways (GSM-R)'},
'42364':{'en': 'Soracom'},
'423650':{'en': 'Telecom Liechtenstein'},
'423651':{'en': 'Cubic'},
'423652':{'en': 'Cubic'},
'423653':{'en': 'Cubic'},
'423660':{'en': 'Telecom Liechtenstein'},
'423661':{'en': 'Dimoco'},
'4236620':{'en': 'Telecom Liechtenstein'},
'4236626':{'en': 'Datamobile'},
'4236627':{'en': 'Datamobile'},
'4236628':{'en': 'Datamobile'},
'4236629':{'en': 'Datamobile'},
'423663':{'en': 'Emnify'},
'42373':{'en': 'Telecom Liechtenstein'},
'42374':{'en': 'First Mobile'},
'42377':{'en': 'Swisscom'},
'42378':{'en': 'Salt'},
'42379':{'en': 'Telecom Liechtenstein'},
'43650':{'en': 'tele.ring'},
'43660':{'en': 'Hutchison Drei Austria'},
'43664':{'en': 'A1 TA'},
'43676':{'en': 'T-Mobile AT'},
'436770':{'en': 'T-Mobile AT'},
'436771':{'en': 'T-Mobile AT'},
'436772':{'en': 'T-Mobile AT'},
'436778':{'en': 'T-Mobile AT'},
'436779':{'en': 'T-Mobile AT'},
'4368181':{'en': 'A1 TA'},
'4368182':{'en': 'A1 TA'},
'4368183':{'en': 'Orange AT'},
'4368184':{'en': 'A1 TA'},
'43688':{'en': 'Orange AT'},
'43699':{'en': 'Orange AT'},
'447106':{'en': 'O2'},
'447107':{'en': 'O2'},
'447300':{'en': 'EE'},
'447301':{'en': 'EE'},
'447302':{'en': 'EE'},
'447303':{'en': 'EE'},
'447304':{'en': 'EE'},
'447305':{'en': 'Virgin Mobile'},
'447306':{'en': 'Virgin Mobile'},
'447340':{'en': 'Vodafone'},
'447341':{'en': 'Vodafone'},
'447342':{'en': 'Vodafone'},
'447365':{'en': 'Three'},
'447366':{'en': 'Three'},
'447367':{'en': 'Three'},
'4473680':{'en': 'Teleena'},
'4473682':{'en': 'Sky'},
'4473683':{'en': 'Sky'},
'4473684':{'en': 'Sky'},
'4473685':{'en': 'Sky'},
'4473686':{'en': 'Sky'},
'4473699':{'en': 'Anywhere Sim'},
'447375':{'en': 'EE'},
'447376':{'en': 'EE'},
'447377':{'en': 'EE'},
'447378':{'en': 'Three'},
'4473780':{'en': 'Limitless'},
'447379':{'en': 'Vodafone'},
'447380':{'en': 'Three'},
'4473800':{'en': 'AMSUK'},
'447381':{'en': 'O2'},
'447382':{'en': 'O2'},
'447383':{'en': 'Three'},
'447384':{'en': 'Vodafone'},
'447385':{'en': 'Vodafone'},
'447386':{'en': 'Vodafone'},
'447387':{'en': 'Vodafone'},
'447388':{'en': 'Vodafone'},
'4473890':{'en': 'Three'},
'4473891':{'en': 'Three'},
'4473892':{'en': 'TalkTalk'},
'4473893':{'en': 'TalkTalk'},
'4473894':{'en': 'TalkTalk'},
'4473895':{'en': 'TalkTalk'},
'4473896':{'en': 'Hanhaa'},
'4473897':{'en': 'Vodafone'},
'4473898':{'en': 'Vodafone'},
'4473900':{'en': 'Home Office'},
'447391':{'en': 'Vodafone'},
'447392':{'en': 'Vodafone'},
'447393':{'en': 'Vodafone'},
'447394':{'en': 'O2'},
'447395':{'en': 'O2'},
'447396':{'en': 'EE'},
'4473970':{'en': 'Three'},
'4473971':{'en': 'Three'},
'4473972':{'en': 'Three'},
'4473973':{'en': 'Three'},
'4473975':{'en': 'Three'},
'4473976':{'en': 'Three'},
'4473977':{'en': 'Three'},
'4473978':{'en': 'Three'},
'4473979':{'en': 'Three'},
'447398':{'en': 'EE'},
'447399':{'en': 'EE'},
'447400':{'en': 'Three'},
'447401':{'en': 'Three'},
'447402':{'en': 'Three'},
'447403':{'en': 'Three'},
'447404':{'en': 'Lycamobile'},
'447405':{'en': 'Lycamobile'},
'4474060':{'en': 'Cheers'},
'4474061':{'en': 'Cheers'},
'4474062':{'en': 'Cheers'},
'4474065':{'en': 'Telecom2'},
'4474066':{'en': '24 Seven'},
'4474067':{'en': 'TGL'},
'4474068':{'en': '08Direct'},
'4474069':{'en': 'CardBoardFish'},
'447407':{'en': 'Vodafone'},
'4474080':{'en': 'Truphone'},
'4474081':{'en': 'Truphone'},
'4474082':{'en': 'Truphone'},
'4474088':{'en': 'Truphone'},
'4474089':{'en': 'Truphone'},
'447409':{'en': 'Orange'},
'447410':{'en': 'Orange'},
'447411':{'en': 'Three'},
'447412':{'en': 'Three'},
'447413':{'en': 'Three'},
'447414':{'en': 'Three'},
'447415':{'en': 'EE'},
'447416':{'en': 'Orange'},
'4474171':{'en': 'CardBoardFish'},
'4474172':{'en': 'Core Telecom'},
'4474173':{'en': 'Lycamobile'},
'4474174':{'en': 'Lycamobile'},
'4474175':{'en': 'Lycamobile'},
'4474178':{'en': 'Truphone'},
'4474179':{'en': 'Core Telecom'},
'4474180':{'en': 'Three'},
'4474181':{'en': 'Bellingham'},
'4474182':{'en': 'TGL'},
'4474183':{'en': 'Tismi'},
'4474184':{'en': 'Manx Telecom'},
'4474185':{'en': 'Telna'},
'4474186':{'en': 'Ace Call'},
'4474187':{'en': 'Teleena'},
'4474189':{'en': 'Teleena'},
'447419':{'en': 'Orange'},
'447420':{'en': 'Orange'},
'447421':{'en': 'Orange'},
'447422':{'en': 'Orange'},
'447423':{'en': 'Vodafone'},
'447424':{'en': 'Lycamobile'},
'447425':{'en': 'Vodafone'},
'447426':{'en': 'Three'},
'447427':{'en': 'Three'},
'447428':{'en': 'Three'},
'447429':{'en': 'Three'},
'447430':{'en': 'O2'},
'447431':{'en': 'O2'},
'447432':{'en': 'EE'},
'447433':{'en': 'EE'},
'447434':{'en': 'EE'},
'447435':{'en': 'Vodafone'},
'447436':{'en': 'Vodafone'},
'447437':{'en': 'Vodafone'},
'447438':{'en': 'Lycamobile'},
'4474390':{'en': 'TalkTalk'},
'4474391':{'en': 'TalkTalk'},
'4474392':{'en': 'TalkTalk'},
'4474393':{'en': 'TalkTalk'},
'447440':{'en': 'Lycamobile'},
'4474408':{'en': 'Telecoms Cloud'},
'4474409':{'en': 'Cloud9'},
'4474410':{'en': 'Mediatel'},
'4474411':{'en': 'Andrews & Arnold'},
'4474413':{'en': 'Stour Marine'},
'4474414':{'en': 'Tismi'},
'4474415':{'en': 'Synectiv'},
'4474416':{'en': 'Vodafone'},
'4474417':{'en': 'Synectiv'},
'4474418':{'en': 'Core Telecom'},
'4474419':{'en': 'Voxbone'},
'447442':{'en': 'Vodafone'},
'447443':{'en': 'Vodafone'},
'447444':{'en': 'Vodafone'},
'447445':{'en': 'Three'},
'447446':{'en': 'Three'},
'447447':{'en': 'Three'},
'447448':{'en': 'Lycamobile'},
'447449':{'en': 'Three'},
'447450':{'en': 'Three'},
'447451':{'en': 'Vectone Mobile'},
'4474512':{'en': 'Tismi'},
'4474515':{'en': 'Premium O'},
'4474516':{'en': 'UK Broadband'},
'4474517':{'en': 'UK Broadband'},
'447452':{'en': 'Manx Telecom'},
'4474527':{'en': 'Three'},
'4474528':{'en': 'Three'},
'4474529':{'en': 'Three'},
'447453':{'en': 'Three'},
'447454':{'en': 'Three'},
'447455':{'en': 'Three'},
'447456':{'en': 'Three'},
'4474570':{'en': 'Vectone Mobile'},
'4474571':{'en': 'Vectone Mobile'},
'4474572':{'en': 'Marathon Telecom'},
'4474573':{'en': 'Vectone Mobile'},
'4474574':{'en': 'Voicetec'},
'4474575':{'en': 'Vectone Mobile'},
'4474576':{'en': 'Sure'},
'4474577':{'en': 'Spacetel'},
'4474578':{'en': 'CardBoardFish'},
'4474579':{'en': 'CardBoardFish'},
'4474580':{'en': 'Gamma Telecom'},
'4474581':{'en': 'Gamma Telecom'},
'4474582':{'en': 'Premium Routing'},
'4474583':{'en': 'Virgin Mobile'},
'4474584':{'en': 'Airwave'},
'4474585':{'en': 'Marathon Telecom'},
'4474586':{'en': 'Three'},
'4474587':{'en': 'Limitless'},
'4474588':{'en': 'Limitless'},
'4474589':{'en': 'Three'},
'447459':{'en': 'Lycamobile'},
'447460':{'en': 'Three'},
'447461':{'en': 'O2'},
'447462':{'en': 'Three'},
'447463':{'en': 'Three'},
'447464':{'en': 'Vodafone'},
'447465':{'en': 'Three'},
'4474650':{'en': 'Vectone Mobile'},
'4474651':{'en': 'Vectone Mobile'},
'4474653':{'en': 'Compatel'},
'4474655':{'en': 'GlobalReach'},
'447466':{'en': 'Lycamobile'},
'447467':{'en': 'Vodafone'},
'447468':{'en': 'Vodafone'},
'447469':{'en': 'Vodafone'},
'44747':{'en': 'Three'},
'447470':{'en': 'Vodafone'},
'447471':{'en': 'Vodafone'},
'447480':{'en': 'Three'},
'447481':{'en': 'Three'},
'447482':{'en': 'Three'},
'447483':{'en': 'EE'},
'447484':{'en': 'EE'},
'447485':{'en': 'EE'},
'447486':{'en': 'EE'},
'447487':{'en': 'EE'},
'4474880':{'en': 'Fogg'},
'4474881':{'en': 'CESG'},
'4474882':{'en': 'Sky'},
'4474883':{'en': 'Sky'},
'4474884':{'en': 'Three'},
'4474885':{'en': 'Three'},
'4474886':{'en': 'Lanonyx'},
'4474887':{'en': 'Three'},
'4474888':{'en': 'Ziron'},
'4474889':{'en': 'Three'},
'447489':{'en': 'O2'},
'447490':{'en': 'Three'},
'447491':{'en': 'Three'},
'447492':{'en': 'Three'},
'447493':{'en': 'Vodafone'},
'447494':{'en': 'EE'},
'447495':{'en': 'EE'},
'447496':{'en': 'EE'},
'447497':{'en': 'EE'},
'447498':{'en': 'EE'},
'447499':{'en': 'O2'},
'447500':{'en': 'Vodafone'},
'447501':{'en': 'Vodafone'},
'447502':{'en': 'Vodafone'},
'447503':{'en': 'Vodafone'},
'447504':{'en': 'EE'},
'447505':{'en': 'EE'},
'447506':{'en': 'EE'},
'447507':{'en': 'EE'},
'447508':{'en': 'EE'},
'4475090':{'en': 'JT'},
'4475091':{'en': 'JT'},
'4475092':{'en': 'JT'},
'4475093':{'en': 'JT'},
'4475094':{'en': 'JT'},
'4475095':{'en': 'JT'},
'4475096':{'en': 'JT'},
'4475097':{'en': 'JT'},
'44751':{'en': 'O2'},
'4475200':{'en': 'Simwood'},
'4475201':{'en': 'BT OnePhone'},
'4475202':{'en': 'Vectone Mobile'},
'4475204':{'en': 'Core Communication'},
'4475205':{'en': 'Esendex'},
'4475206':{'en': 'Tismi'},
'4475207':{'en': 'aql'},
'447521':{'en': 'O2'},
'447522':{'en': 'O2'},
'447523':{'en': 'O2'},
'447525':{'en': 'O2'},
'447526':{'en': 'O2'},
'447527':{'en': 'Orange'},
'447528':{'en': 'Orange'},
'447529':{'en': 'Orange'},
'447530':{'en': 'Orange'},
'447531':{'en': 'Orange'},
'4475320':{'en': 'Orange'},
'4475321':{'en': 'Orange'},
'4475322':{'en': 'Orange'},
'4475323':{'en': 'Orange'},
'4475324':{'en': 'Orange'},
'4475325':{'en': 'SMSRelay AG'},
'4475326':{'en': 'Three'},
'4475327':{'en': 'Three'},
'4475328':{'en': 'Three'},
'4475329':{'en': 'Mobiweb'},
'447533':{'en': 'Three'},
'447534':{'en': 'EE'},
'447535':{'en': 'EE'},
'447536':{'en': 'Orange'},
'4475370':{'en': 'Wavecrest'},
'4475371':{'en': 'Stour Marine'},
'4475373':{'en': 'Swiftnet'},
'4475374':{'en': 'Vodafone'},
'4475376':{'en': 'Mediatel'},
'4475377':{'en': 'CFL'},
'4475378':{'en': 'Three'},
'4475379':{'en': 'Three'},
'447538':{'en': 'EE'},
'447539':{'en': 'EE'},
'44754':{'en': 'O2'},
'447550':{'en': 'EE'},
'447551':{'en': 'Vodafone'},
'447552':{'en': 'Vodafone'},
'447553':{'en': 'Vodafone'},
'447554':{'en': 'Vodafone'},
'447555':{'en': 'Vodafone'},
'447556':{'en': 'Orange'},
'447557':{'en': 'Vodafone'},
'4475580':{'en': 'Mobile FX Services Ltd'},
'4475588':{'en': 'Cloud9'},
'4475590':{'en': 'Mars'},
'4475591':{'en': 'LegendTel'},
'4475592':{'en': 'IPV6'},
'4475593':{'en': 'Globecom'},
'4475594':{'en': 'Truphone'},
'4475595':{'en': 'Confabulate'},
'4475596':{'en': 'Lleida.net'},
'4475597':{'en': 'Core Telecom'},
'4475598':{'en': 'Nodemax'},
'4475599':{'en': 'Resilient'},
'44756':{'en': 'O2'},
'447570':{'en': 'Vodafone'},
'4475710':{'en': '09 Mobile'},
'4475718':{'en': 'Alliance'},
'447572':{'en': 'EE'},
'447573':{'en': 'EE'},
'447574':{'en': 'EE'},
'447575':{'en': 'Three'},
'447576':{'en': 'Three'},
'447577':{'en': 'Three'},
'447578':{'en': 'Three'},
'447579':{'en': 'Orange'},
'447580':{'en': 'Orange'},
'447581':{'en': 'Orange'},
'447582':{'en': 'Orange'},
'447583':{'en': 'Orange'},
'447584':{'en': 'Vodafone'},
'447585':{'en': 'Vodafone'},
'447586':{'en': 'Vodafone'},
'447587':{'en': 'Vodafone'},
'447588':{'en': 'Three'},
'4475890':{'en': 'Yim Siam'},
'4475891':{'en': 'Oxygen8'},
'4475892':{'en': 'Oxygen8'},
'4475893':{'en': 'Oxygen8'},
'4475894':{'en': 'Vectone Mobile'},
'4475895':{'en': 'Vectone Mobile'},
'4475896':{'en': 'Vectone Mobile'},
'4475897':{'en': 'Vectone Mobile'},
'4475898':{'en': 'Test2date'},
'44759':{'en': 'O2'},
'4476000':{'en': 'Mediatel'},
'4476002':{'en': 'PageOne'},
'4476006':{'en': '24 Seven'},
'4476007':{'en': 'Relax'},
'4476020':{'en': 'O2'},
'4476022':{'en': 'Relax'},
'447623':{'en': 'PageOne'},
'447624':{'en': 'Manx Telecom'},
'4476242':{'en': 'Sure'},
'44762450':{'en': 'BlueWave Communications'},
'44762456':{'en': 'Sure'},
'447625':{'en': 'O2'},
'447626':{'en': 'O2'},
'4476400':{'en': 'Core Telecom'},
'4476401':{'en': 'Telecom2'},
'4476402':{'en': 'FIO Telecom'},
'4476403':{'en': 'PageOne'},
'4476404':{'en': 'PageOne'},
'4476406':{'en': 'PageOne'},
'4476407':{'en': 'PageOne'},
'4476411':{'en': 'Orange'},
'4476433':{'en': 'Yim Siam'},
'4476440':{'en': 'O2'},
'4476441':{'en': 'O2'},
'4476446':{'en': 'Media'},
'4476542':{'en': 'PageOne'},
'4476543':{'en': 'PageOne'},
'4476545':{'en': 'PageOne'},
'4476546':{'en': 'PageOne'},
'4476591':{'en': 'Vodafone'},
'4476592':{'en': 'PageOne'},
'4476593':{'en': 'Vodafone'},
'4476594':{'en': 'Vodafone'},
'4476595':{'en': 'Vodafone'},
'4476596':{'en': 'Vodafone'},
'4476598':{'en': 'Vodafone'},
'4476599':{'en': 'PageOne'},
'4476600':{'en': 'Plus'},
'4476601':{'en': 'PageOne'},
'4476602':{'en': 'PageOne'},
'4476603':{'en': 'PageOne'},
'4476604':{'en': 'PageOne'},
'4476605':{'en': 'PageOne'},
'4476606':{'en': '24 Seven'},
'4476607':{'en': 'Premium O'},
'4476608':{'en': 'Premium O'},
'4476609':{'en': 'Premium O'},
'447661':{'en': 'PageOne'},
'4476620':{'en': 'Premium O'},
'4476633':{'en': 'Syntec'},
'4476636':{'en': 'Relax'},
'4476637':{'en': 'Vodafone'},
'447666':{'en': 'Vodafone'},
'4476660':{'en': '24 Seven'},
'4476669':{'en': 'FIO Telecom'},
'4476690':{'en': 'O2'},
'4476691':{'en': 'O2'},
'4476692':{'en': 'O2'},
'4476693':{'en': 'Confabulate'},
'4476696':{'en': 'Cheers'},
'4476698':{'en': 'O2'},
'4476699':{'en': 'O2'},
'4476770':{'en': '24 Seven'},
'4476772':{'en': 'Relax'},
'4476776':{'en': 'Telsis'},
'4476778':{'en': 'Core Telecom'},
'4476810':{'en': 'PageOne'},
'4476814':{'en': 'PageOne'},
'4476818':{'en': 'PageOne'},
'447693':{'en': 'O2'},
'447699':{'en': 'Vodafone'},
'44770':{'en': 'O2'},
'4477000':{'en': 'Cloud9'},
'4477001':{'en': 'Nationwide Telephone'},
'4477003':{'en': 'Sure'},
'4477007':{'en': 'Sure'},
'4477008':{'en': 'Sure'},
'44771':{'en': 'O2'},
'447717':{'en': 'Vodafone'},
'447720':{'en': 'O2'},
'447721':{'en': 'Vodafone'},
'447722':{'en': 'EE'},
'447723':{'en': 'Three'},
'447724':{'en': 'O2'},
'447725':{'en': 'O2'},
'447726':{'en': 'EE'},
'447727':{'en': 'Three'},
'447728':{'en': 'Three'},
'447729':{'en': 'O2'},
'44773':{'en': 'O2'},
'447733':{'en': 'Vodafone'},
'447735':{'en': 'Three'},
'447737':{'en': 'Three'},
'447740':{'en': 'O2'},
'447741':{'en': 'Vodafone'},
'447742':{'en': 'O2'},
'447743':{'en': 'O2'},
'4477442':{'en': 'Core Communication'},
'4477443':{'en': 'Core Communication'},
'4477444':{'en': 'Core Communication'},
'4477445':{'en': 'Core Communication'},
'4477446':{'en': 'Core Communication'},
'4477447':{'en': 'Core Communication'},
'4477448':{'en': 'Core Communication'},
'4477449':{'en': 'Core Communication'},
'447745':{'en': 'O2'},
'447746':{'en': 'O2'},
'447747':{'en': 'Vodafone'},
'447748':{'en': 'Vodafone'},
'447749':{'en': 'O2'},
'447750':{'en': 'O2'},
'447751':{'en': 'O2'},
'447752':{'en': 'O2'},
'447753':{'en': 'O2'},
'4477530':{'en': 'Airwave'},
'447754':{'en': 'O2'},
'4477552':{'en': 'Core Communication'},
'4477553':{'en': 'Core Communication'},
'4477554':{'en': 'Core Communication'},
'4477555':{'en': 'Core Communication'},
'447756':{'en': 'O2'},
'447757':{'en': 'EE'},
'447758':{'en': 'EE'},
'447759':{'en': 'O2'},
'44776':{'en': 'Vodafone'},
'447761':{'en': 'O2'},
'447762':{'en': 'O2'},
'447763':{'en': 'O2'},
'447764':{'en': 'O2'},
'44777':{'en': 'Vodafone'},
'447772':{'en': 'Orange'},
'447773':{'en': 'Orange'},
'447777':{'en': 'EE'},
'447779':{'en': 'Orange'},
'44778':{'en': 'Vodafone'},
'447781':{'en': 'Sure'},
'447782':{'en': 'Three'},
'447783':{'en': 'O2'},
'447784':{'en': 'O2'},
'447790':{'en': 'Orange'},
'447791':{'en': 'Orange'},
'447792':{'en': 'Orange'},
'447793':{'en': 'O2'},
'447794':{'en': 'Orange'},
'447795':{'en': 'Vodafone'},
'447796':{'en': 'Vodafone'},
'447797':{'en': 'JT'},
'447798':{'en': 'Vodafone'},
'447799':{'en': 'Vodafone'},
'447800':{'en': 'Orange'},
'447801':{'en': 'O2'},
'447802':{'en': 'O2'},
'447803':{'en': 'O2'},
'447804':{'en': 'EE'},
'447805':{'en': 'Orange'},
'447806':{'en': 'EE'},
'447807':{'en': 'Orange'},
'447808':{'en': 'O2'},
'447809':{'en': 'O2'},
'44781':{'en': 'Orange'},
'447810':{'en': 'Vodafone'},
'447818':{'en': 'Vodafone'},
'447819':{'en': 'O2'},
'447820':{'en': 'O2'},
'447821':{'en': 'O2'},
'4478220':{'en': 'FleXtel'},
'4478221':{'en': 'Swiftnet'},
'4478222':{'en': 'TalkTalk'},
'4478224':{'en': 'aql'},
'4478225':{'en': 'Icron Network'},
'4478226':{'en': 'aql'},
'4478227':{'en': 'Cheers'},
'4478228':{'en': 'Vodafone'},
'4478229':{'en': 'Oxygen8'},
'447823':{'en': 'Vodafone'},
'447824':{'en': 'Vodafone'},
'447825':{'en': 'Vodafone'},
'447826':{'en': 'Vodafone'},
'447827':{'en': 'Vodafone'},
'447828':{'en': 'Three'},
'4478297':{'en': 'Airtel'},
'4478298':{'en': 'Airtel'},
'4478299':{'en': 'Airtel'},
'447830':{'en': 'Three'},
'447831':{'en': 'Vodafone'},
'447832':{'en': 'Three'},
'447833':{'en': 'Vodafone'},
'447834':{'en': 'O2'},
'447835':{'en': 'O2'},
'447836':{'en': 'Vodafone'},
'447837':{'en': 'Orange'},
'447838':{'en': 'Three'},
'4478391':{'en': 'Airtel'},
'4478392':{'en': 'Airtel'},
'4478397':{'en': 'Airtel'},
'4478398':{'en': 'Sure'},
'44784':{'en': 'O2'},
'447846':{'en': 'Three'},
'447847':{'en': 'EE'},
'447848':{'en': 'Three'},
'447850':{'en': 'O2'},
'447851':{'en': 'O2'},
'447852':{'en': 'EE'},
'447853':{'en': 'Three'},
'447854':{'en': 'Orange'},
'447855':{'en': 'Orange'},
'447856':{'en': 'O2'},
'447857':{'en': 'O2'},
'447858':{'en': 'O2'},
'447859':{'en': 'Three'},
'447860':{'en': 'O2'},
'447861':{'en': 'Three'},
'447862':{'en': 'Three'},
'447863':{'en': 'Three'},
'4478640':{'en': 'O2'},
'4478641':{'en': 'O2'},
'4478642':{'en': 'O2'},
'4478643':{'en': 'O2'},
'4478645':{'en': 'O2'},
'4478646':{'en': 'O2'},
'4478647':{'en': 'O2'},
'4478648':{'en': 'O2'},
'4478649':{'en': 'O2'},
'447865':{'en': 'Three'},
'447866':{'en': 'Orange'},
'447867':{'en': 'Vodafone'},
'447868':{'en': 'Three'},
'447869':{'en': 'Three'},
'447870':{'en': 'Orange'},
'447871':{'en': 'O2'},
'447872':{'en': 'O2'},
'4478722':{'en': 'Cloud9'},
'4478727':{'en': 'Telecom 10'},
'447873':{'en': 'O2'},
'4478730':{'en': 'Telesign'},
'4478740':{'en': 'O2'},
'4478741':{'en': 'O2'},
'4478742':{'en': 'O2'},
'4478743':{'en': 'O2'},
'4478744':{'en': 'Citrus'},
'4478746':{'en': 'O2'},
'4478747':{'en': 'O2'},
'4478748':{'en': 'O2'},
'4478749':{'en': 'O2'},
'447875':{'en': 'Orange'},
'447876':{'en': 'Vodafone'},
'447877':{'en': 'Three'},
'447878':{'en': 'Three'},
'447879':{'en': 'Vodafone'},
'447880':{'en': 'Vodafone'},
'447881':{'en': 'Vodafone'},
'447882':{'en': 'Three'},
'447883':{'en': 'Three'},
'447884':{'en': 'Vodafone'},
'447885':{'en': 'O2'},
'447886':{'en': 'Three'},
'447887':{'en': 'Vodafone'},
'447888':{'en': 'Three'},
'447889':{'en': 'O2'},
'447890':{'en': 'Orange'},
'447891':{'en': 'Orange'},
'4478920':{'en': 'HSL'},
'4478921':{'en': 'Vectone Mobile'},
'4478923':{'en': 'O2'},
'4478924':{'en': 'O2'},
'4478925':{'en': 'FleXtel'},
'4478926':{'en': 'O2'},
'4478927':{'en': 'O2'},
'4478928':{'en': 'O2'},
'4478929':{'en': 'O2'},
'4478930':{'en': 'Magrathea'},
'4478931':{'en': '24 Seven'},
'4478932':{'en': 'O2'},
'4478933':{'en': 'Yim Siam'},
'4478934':{'en': 'O2'},
'4478935':{'en': 'O2'},
'4478936':{'en': 'O2'},
'4478937':{'en': 'O2'},
'4478938':{'en': 'aql'},
'4478939':{'en': 'Citrus'},
'447894':{'en': 'O2'},
'447895':{'en': 'O2'},
'447896':{'en': 'Orange'},
'447897':{'en': 'Three'},
'447898':{'en': 'Three'},
'447899':{'en': 'Vodafone'},
'447900':{'en': 'Vodafone'},
'447901':{'en': 'Vodafone'},
'447902':{'en': 'O2'},
'447903':{'en': 'EE'},
'447904':{'en': 'EE'},
'447905':{'en': 'EE'},
'447906':{'en': 'EE'},
'447907':{'en': 'O2'},
'447908':{'en': 'EE'},
'447909':{'en': 'Vodafone'},
'447910':{'en': 'EE'},
'4479110':{'en': 'Marathon Telecom'},
'4479111':{'en': 'JT'},
'4479112':{'en': '24 Seven'},
'4479117':{'en': 'JT'},
'4479118':{'en': '24 Seven'},
'447912':{'en': 'O2'},
'447913':{'en': 'EE'},
'447914':{'en': 'EE'},
'447915':{'en': 'Three'},
'447916':{'en': 'Three'},
'447917':{'en': 'Vodafone'},
'447918':{'en': 'Vodafone'},
'447919':{'en': 'Vodafone'},
'44792':{'en': 'O2'},
'447920':{'en': 'Vodafone'},
'447924':{'en': 'Manx Telecom'},
'4479245':{'en': 'Cloud9'},
'447929':{'en': 'Orange'},
'447930':{'en': 'EE'},
'447931':{'en': 'EE'},
'447932':{'en': 'EE'},
'447933':{'en': 'O2'},
'447934':{'en': 'O2'},
'447935':{'en': 'O2'},
'447936':{'en': 'O2'},
'447937':{'en': 'JT'},
'447938':{'en': 'O2'},
'447939':{'en': 'EE'},
'44794':{'en': 'EE'},
'44795':{'en': 'EE'},
'447955':{'en': 'O2'},
'44796':{'en': 'Orange'},
'447960':{'en': 'EE'},
'447961':{'en': 'EE'},
'447962':{'en': 'EE'},
'447963':{'en': 'EE'},
'447970':{'en': 'Orange'},
'447971':{'en': 'Orange'},
'447972':{'en': 'Orange'},
'447973':{'en': 'Orange'},
'447974':{'en': 'Orange'},
'447975':{'en': 'Orange'},
'447976':{'en': 'Orange'},
'447977':{'en': 'Orange'},
'4479781':{'en': 'QX Telecom'},
'4479782':{'en': 'Cloud9'},
'4479783':{'en': 'Cloud9'},
'4479784':{'en': 'Cheers'},
'4479785':{'en': 'Icron Network'},
'4479786':{'en': 'Oxygen8'},
'4479787':{'en': 'TeleWare'},
'4479788':{'en': 'Truphone'},
'4479789':{'en': 'IV Response'},
'447979':{'en': 'Vodafone'},
'44798':{'en': 'EE'},
'447980':{'en': 'Orange'},
'447988':{'en': 'Three'},
'447989':{'en': 'Orange'},
'447990':{'en': 'Vodafone'},
'447999':{'en': 'O2'},
'45201':{'en': 'tdc'},
'45202':{'en': 'tdc'},
'45203':{'en': 'tdc'},
'45204':{'en': 'tdc'},
'45205':{'en': 'tdc'},
'45206':{'en': 'telenor'},
'45207':{'en': 'telenor'},
'45208':{'en': 'telenor'},
'45209':{'en': 'telenor'},
'45211':{'en': 'tdc'},
'45212':{'en': 'tdc'},
'45213':{'en': 'tdc'},
'45214':{'en': 'tdc'},
'45215':{'en': 'tdc'},
'45216':{'en': 'tdc'},
'45217':{'en': 'tdc'},
'45218':{'en': 'tdc'},
'45219':{'en': 'tdc'},
'45221':{'en': 'telenor'},
'45222':{'en': 'telenor'},
'45223':{'en': 'telenor'},
'45224':{'en': 'telenor'},
'45225':{'en': 'telenor'},
'45226':{'en': 'telenor'},
'45227':{'en': 'telenor'},
'45228':{'en': 'telenor'},
'45229':{'en': 'telenor'},
'45231':{'en': 'tdc'},
'45232':{'en': 'tdc'},
'45233':{'en': 'tdc'},
'45234':{'en': 'tdc'},
'45235':{'en': 'tdc'},
'45236':{'en': 'tdc'},
'45237':{'en': 'tdc'},
'45238':{'en': 'tdc'},
'45239':{'en': 'tdc'},
'452395':{'en': 'telia'},
'45241':{'en': 'tdc'},
'45242':{'en': 'tdc'},
'45243':{'en': 'tdc'},
'45244':{'en': 'tdc'},
'45245':{'en': 'tdc'},
'45246':{'en': 'tdc'},
'45247':{'en': 'tdc'},
'45248':{'en': 'tdc'},
'45249':{'en': 'tdc'},
'45251':{'en': 'telenor'},
'45252':{'en': 'telenor'},
'45253':{'en': 'telenor'},
'45254':{'en': 'telenor'},
'45255':{'en': 'telenor'},
'45256':{'en': 'telenor'},
'45257':{'en': 'telenor'},
'45258':{'en': 'telenor'},
'452590':{'en': 'mi carrier services'},
'452591':{'en': 'link mobile'},
'452592':{'en': 'link mobile'},
'452593':{'en': 'compatel limited'},
'452594':{'en': 'firmafon'},
'452595':{'en': 'link mobile'},
'452596':{'en': 'viptel'},
'452597':{'en': '3'},
'4525980':{'en': 'uni-tel'},
'4525981':{'en': 'mobiweb limited'},
'4525982':{'en': 'jay.net'},
'4525983':{'en': '42 telecom ab'},
'4525984':{'en': 'link mobile'},
'4525985':{'en': '42 telecom ab'},
'4525986':{'en': '42 telecom ab'},
'4525987':{'en': 'netfors unified messaging'},
'4525988':{'en': 'link mobile'},
'4525989':{'en': 'ipnordic'},
'452599':{'en': 'telenor'},
'4526':{'en': 'telia'},
'4527':{'en': 'telia'},
'4528':{'en': 'telia'},
'45291':{'en': 'tdc'},
'45292':{'en': 'tdc'},
'45293':{'en': 'tdc'},
'45294':{'en': 'tdc'},
'45295':{'en': 'tdc'},
'45296':{'en': 'tdc'},
'45297':{'en': 'tdc'},
'45298':{'en': 'tdc'},
'45299':{'en': 'tdc'},
'45301':{'en': 'tdc'},
'45302':{'en': 'tdc'},
'45303':{'en': 'tdc'},
'45304':{'en': 'tdc'},
'45305':{'en': 'tdc'},
'45306':{'en': 'tdc'},
'45307':{'en': 'tdc'},
'45308':{'en': 'tdc'},
'45309':{'en': 'tdc'},
'45311':{'en': '3'},
'45312':{'en': '3'},
'45313':{'en': '3'},
'4531312':{'en': 'mi carrier services'},
'45314':{'en': '3'},
'45315':{'en': '3'},
'45316':{'en': '3'},
'45317':{'en': '3'},
'45318':{'en': 'lycamobile denmark ltd'},
'45319':{'en': 'telenor'},
'45321':{'en': 'telenor'},
'45322':{'en': 'telenor'},
'45323':{'en': 'telenor'},
'45324':{'en': 'telenor'},
'45325':{'en': 'telenor'},
'45326':{'en': 'telenor'},
'45327':{'en': 'telenor'},
'45328':{'en': 'telenor'},
'45329':{'en': 'telenor'},
'45331':{'en': 'telenor'},
'45332':{'en': 'telenor'},
'45333':{'en': 'telenor'},
'45334':{'en': 'telenor'},
'45335':{'en': 'telenor'},
'45336':{'en': 'telenor'},
'45337':{'en': 'telenor'},
'45338':{'en': 'telenor'},
'45339':{'en': 'telenor'},
'45341':{'en': 'telenor'},
'45342':{'en': 'telenor'},
'453434':{'en': 'telenor'},
'45351':{'en': 'telenor'},
'45352':{'en': 'telenor'},
'45353':{'en': 'telenor'},
'45354':{'en': 'telenor'},
'45355':{'en': 'telenor'},
'45356':{'en': 'telenor'},
'45357':{'en': 'telenor'},
'45358':{'en': 'telenor'},
'45359':{'en': 'telenor'},
'45361':{'en': 'telenor'},
'45362':{'en': 'telenor'},
'45363':{'en': 'telenor'},
'45364':{'en': 'telenor'},
'45365':{'en': 'telenor'},
'45366':{'en': 'telenor'},
'45367':{'en': 'telenor'},
'45368':{'en': 'telenor'},
'45369':{'en': 'telenor'},
'45381':{'en': 'telenor'},
'45382':{'en': 'telenor'},
'45383':{'en': 'telenor'},
'45384':{'en': 'telenor'},
'45385':{'en': 'telenor'},
'45386':{'en': 'telenor'},
'45387':{'en': 'telenor'},
'45388':{'en': 'telenor'},
'45389':{'en': 'telenor'},
'45391':{'en': 'telenor'},
'45392':{'en': 'telenor'},
'45393':{'en': 'telenor'},
'45394':{'en': 'telenor'},
'45395':{'en': 'telenor'},
'45396':{'en': 'telenor'},
'45397':{'en': 'telenor'},
'45398':{'en': 'telenor'},
'45399':{'en': 'telenor'},
'45401':{'en': 'tdc'},
'45402':{'en': 'tdc'},
'45403':{'en': 'tdc'},
'45404':{'en': 'tdc'},
'45405':{'en': 'telenor'},
'45406':{'en': 'telenor'},
'45407':{'en': 'telenor'},
'45408':{'en': 'telenor'},
'45409':{'en': 'telenor'},
'45411':{'en': 'telenor'},
'45412':{'en': 'telenor'},
'45413':{'en': 'telenor'},
'45414':{'en': 'telenor'},
'45415':{'en': 'telenor'},
'45416':{'en': 'telenor'},
'45417':{'en': 'telenor'},
'45418':{'en': 'telenor'},
'45419':{'en': 'telenor'},
'45421':{'en': 'telia'},
'45422':{'en': 'telia'},
'45423':{'en': 'telia'},
'45424':{'en': 'telenor'},
'45425':{'en': 'telenor'},
'45426':{'en': 'telenor'},
'45427':{'en': 'telenor'},
'45428':{'en': 'telenor'},
'4542900':{'en': 'telenor'},
'4542901':{'en': 'telenor'},
'4542902':{'en': 'telenor'},
'4542903':{'en': 'telenor'},
'4542904':{'en': 'telenor'},
'4542905':{'en': 'telenor'},
'45429060':{'en': 'telenor'},
'45429061':{'en': 'telenor'},
'45429062':{'en': 'telenor'},
'45429063':{'en': 'telenor'},
'45429064':{'en': 'telenor'},
'45429065':{'en': 'telenor'},
'45429066':{'en': 'telenor'},
'45429067':{'en': 'telenor'},
'45429068':{'en': 'tdc'},
'45429084':{'en': 'tdc'},
'454291':{'en': '3'},
'454292':{'en': '3'},
'454293':{'en': 'cbb mobil'},
'454294':{'en': '3'},
'454295':{'en': '3'},
'454296':{'en': 'telia'},
'454297':{'en': 'telia'},
'454298':{'en': 'telia'},
'454299':{'en': 'telia'},
'45431':{'en': 'telenor'},
'45432':{'en': 'telenor'},
'45433':{'en': 'telenor'},
'45434':{'en': 'telenor'},
'45435':{'en': 'telenor'},
'45436':{'en': 'telenor'},
'45437':{'en': 'telenor'},
'45438':{'en': 'telenor'},
'45439':{'en': 'telenor'},
'45441':{'en': 'telenor'},
'45442':{'en': 'telenor'},
'45443':{'en': 'telenor'},
'45444':{'en': 'telenor'},
'45445':{'en': 'telenor'},
'45446':{'en': 'telenor'},
'45447':{'en': 'telenor'},
'45448':{'en': 'telenor'},
'45449':{'en': 'telenor'},
'45451':{'en': 'telenor'},
'45452':{'en': 'telenor'},
'45453':{'en': 'telenor'},
'45454':{'en': 'telenor'},
'45455':{'en': 'telenor'},
'45456':{'en': 'telenor'},
'45457':{'en': 'telenor'},
'45458':{'en': 'telenor'},
'45459':{'en': 'telenor'},
'45461':{'en': 'telenor'},
'45462':{'en': 'telenor'},
'45463':{'en': 'telenor'},
'45464':{'en': 'telenor'},
'45465':{'en': 'telenor'},
'45466':{'en': 'telenor'},
'45467':{'en': 'telenor'},
'45468':{'en': 'telenor'},
'45469':{'en': 'telenor'},
'45471':{'en': 'telenor'},
'45472':{'en': 'telenor'},
'45473':{'en': 'telenor'},
'45474':{'en': 'telenor'},
'45475':{'en': 'telenor'},
'45476':{'en': 'telenor'},
'45477':{'en': 'telenor'},
'45478':{'en': 'telenor'},
'45479':{'en': 'telenor'},
'45481':{'en': 'telenor'},
'45482':{'en': 'telenor'},
'45483':{'en': 'telenor'},
'45484':{'en': 'telenor'},
'45485':{'en': 'telenor'},
'45486':{'en': 'telenor'},
'45487':{'en': 'telenor'},
'45488':{'en': 'telenor'},
'45489':{'en': 'telenor'},
'4549109':{'en': 'tdc'},
'454911':{'en': 'tdc'},
'454912':{'en': 'tdc'},
'4549130':{'en': 'tdc'},
'4549131':{'en': 'tdc'},
'4549132':{'en': 'tdc'},
'4549133':{'en': 'tdc'},
'4549134':{'en': 'tdc'},
'4549135':{'en': 'tdc'},
'4549136':{'en': 'tdc'},
'4549138':{'en': 'tdc'},
'4549139':{'en': 'tdc'},
'454914':{'en': 'tdc'},
'4549150':{'en': 'tdc'},
'4549151':{'en': 'tdc'},
'4549155':{'en': 'tdc'},
'4549156':{'en': 'tdc'},
'4549157':{'en': 'tdc'},
'4549158':{'en': 'tdc'},
'4549159':{'en': 'tdc'},
'4549160':{'en': 'tdc'},
'4549161':{'en': 'tdc'},
'4549162':{'en': 'tdc'},
'4549163':{'en': 'tdc'},
'4549168':{'en': 'tdc'},
'4549169':{'en': 'tdc'},
'454917':{'en': 'tdc'},
'4549180':{'en': 'tdc'},
'4549181':{'en': 'tdc'},
'4549184':{'en': 'tdc'},
'4549185':{'en': 'tdc'},
'4549187':{'en': 'tdc'},
'4549188':{'en': 'tdc'},
'4549189':{'en': 'tdc'},
'454919':{'en': 'tdc'},
'4549200':{'en': 'tdc'},
'4549201':{'en': 'tdc'},
'4549202':{'en': 'tdc'},
'4549203':{'en': 'tdc'},
'454921':{'en': 'tdc'},
'4549220':{'en': 'tdc'},
'4549221':{'en': 'tdc'},
'4549222':{'en': 'tdc'},
'4549223':{'en': 'tdc'},
'4549224':{'en': 'tdc'},
'4549225':{'en': 'tdc'},
'4549226':{'en': 'tdc'},
'4549250':{'en': 'tdc'},
'4549251':{'en': 'tdc'},
'4549252':{'en': 'tdc'},
'4549253':{'en': 'tdc'},
'4549255':{'en': 'tdc'},
'4549256':{'en': 'tdc'},
'4549258':{'en': 'tdc'},
'4549259':{'en': 'tdc'},
'4549260':{'en': 'tdc'},
'4549261':{'en': 'tdc'},
'4549262':{'en': 'tdc'},
'4549263':{'en': 'tdc'},
'4549264':{'en': 'tdc'},
'4549265':{'en': 'tdc'},
'4549266':{'en': 'tdc'},
'454927':{'en': 'tdc'},
'454928':{'en': 'tdc'},
'4549295':{'en': 'tdc'},
'4549298':{'en': 'tdc'},
'4549299':{'en': 'tdc'},
'45493':{'en': 'telenor'},
'45494':{'en': 'telenor'},
'4549700':{'en': 'tdc'},
'4549701':{'en': 'tdc'},
'4549702':{'en': 'tdc'},
'4549703':{'en': 'tdc'},
'4549704':{'en': 'tdc'},
'4549707':{'en': 'tdc'},
'4549708':{'en': 'tdc'},
'4549709':{'en': 'tdc'},
'454971':{'en': 'tdc'},
'4549750':{'en': 'tdc'},
'4549751':{'en': 'tdc'},
'4549752':{'en': 'tdc'},
'4549753':{'en': 'tdc'},
'4549754':{'en': 'tdc'},
'4549755':{'en': 'tdc'},
'4549758':{'en': 'tdc'},
'4549759':{'en': 'tdc'},
'4549760':{'en': 'tdc'},
'4549761':{'en': 'tdc'},
'4549762':{'en': 'tdc'},
'4549763':{'en': 'tdc'},
'4549765':{'en': 'tdc'},
'4549766':{'en': 'tdc'},
'4549767':{'en': 'tdc'},
'454977':{'en': 'tdc'},
'4549780':{'en': 'tdc'},
'4549789':{'en': 'tdc'},
'45501':{'en': 'telenor'},
'45502':{'en': 'telenor'},
'45503':{'en': 'telenor'},
'45504':{'en': 'telenor'},
'45505':{'en': 'telenor'},
'455060':{'en': 'ipvision'},
'455061':{'en': 'svr technologies (mach connectivity)'},
'455062':{'en': 'cbb mobil'},
'455063':{'en': 'mundio mobile'},
'455064':{'en': 'lycamobile denmark ltd'},
'455065':{'en': 'lebara limited'},
'455066':{'en': 'cbb mobil'},
'455067':{'en': 'cbb mobil'},
'455068':{'en': 'cbb mobil'},
'455069':{'en': '3'},
'45507':{'en': 'telenor'},
'45508':{'en': 'telenor'},
'45509':{'en': 'telenor'},
'4551':{'en': 'tdc'},
'45510':{'en': 'orange'},
'455188':{'en': 'telia'},
'455189':{'en': 'telia'},
'45521':{'en': 'telia'},
'455210':{'en': 'firstcom'},
'455211':{'en': '3'},
'455212':{'en': '3'},
'45522':{'en': 'telia'},
'455220':{'en': 'link mobile'},
'455222':{'en': 'lebara limited'},
'455225':{'en': 'cbb mobil'},
'45523':{'en': 'telia'},
'455230':{'en': 'tdc'},
'455233':{'en': 'cbb mobil'},
'45524':{'en': 'telia'},
'455240':{'en': 'tdc'},
'455242':{'en': 'cbb mobil'},
'455244':{'en': 'cbb mobil'},
'455250':{'en': 'tdc'},
'455251':{'en': 'link mobile'},
'455252':{'en': 'lebara limited'},
'455253':{'en': 'cbb mobil'},
'455254':{'en': 'simservice'},
'455255':{'en': 'cbb mobil'},
'455256':{'en': 'simservice'},
'455257':{'en': 'simservice'},
'455258':{'en': 'tdc'},
'455259':{'en': '42 telecom ab'},
'45526':{'en': 'telenor'},
'45527':{'en': 'telenor'},
'45528':{'en': 'telenor'},
'45529':{'en': 'telenor'},
'45531':{'en': 'cbb mobil'},
'455319':{'en': 'telia'},
'45532':{'en': 'telia'},
'45533':{'en': 'telia'},
'455333':{'en': 'lebara limited'},
'45534':{'en': 'telia'},
'45535':{'en': '3'},
'45536':{'en': '3'},
'45537':{'en': '3'},
'45538':{'en': '3'},
'45539':{'en': 'cbb mobil'},
'455398':{'en': 'nextgen mobile ldt t/a cardboardfish'},
'45541':{'en': 'telenor'},
'45542':{'en': 'telenor'},
'45543':{'en': 'telenor'},
'45544':{'en': 'telenor'},
'45545':{'en': 'telenor'},
'45546':{'en': 'telenor'},
'45547':{'en': 'telenor'},
'45548':{'en': 'telenor'},
'45549':{'en': 'telenor'},
'45551':{'en': 'telenor'},
'45552':{'en': 'telenor'},
'45553':{'en': 'telenor'},
'45554':{'en': 'telenor'},
'45555':{'en': 'telenor'},
'45556':{'en': 'telenor'},
'45557':{'en': 'telenor'},
'45558':{'en': 'telenor'},
'45559':{'en': 'telenor'},
'45561':{'en': 'telenor'},
'45562':{'en': 'telenor'},
'45563':{'en': 'telenor'},
'45564':{'en': 'telenor'},
'45565':{'en': 'telenor'},
'45566':{'en': 'telenor'},
'45567':{'en': 'telenor'},
'45568':{'en': 'telenor'},
'45569':{'en': 'telenor'},
'45571':{'en': 'telenor'},
'45572':{'en': 'telenor'},
'45573':{'en': 'telenor'},
'45574':{'en': 'telenor'},
'45575':{'en': 'telenor'},
'45576':{'en': 'telenor'},
'45577':{'en': 'telenor'},
'45578':{'en': 'telenor'},
'45579':{'en': 'telenor'},
'45581':{'en': 'telenor'},
'45582':{'en': 'telenor'},
'45583':{'en': 'telenor'},
'45584':{'en': 'telenor'},
'45585':{'en': 'telenor'},
'45586':{'en': 'telenor'},
'45587':{'en': 'telenor'},
'45588':{'en': 'telenor'},
'45589':{'en': 'telenor'},
'45591':{'en': 'telenor'},
'45592':{'en': 'telenor'},
'45593':{'en': 'telenor'},
'45594':{'en': 'telenor'},
'45595':{'en': 'telenor'},
'45596':{'en': 'telenor'},
'45597':{'en': 'telenor'},
'45598':{'en': 'telenor'},
'45599':{'en': 'telenor'},
'45601':{'en': 'telia'},
'45602':{'en': 'telia'},
'45603':{'en': 'telia'},
'45604':{'en': 'telia'},
'45605':{'en': '3'},
'456050':{'en': 'telenor'},
'45606':{'en': 'cbb mobil'},
'45607':{'en': 'cbb mobil'},
'45608':{'en': 'cbb mobil'},
'456090':{'en': 'lebara limited'},
'456091':{'en': 'telenor'},
'456092':{'en': 'telenor'},
'456093':{'en': 'telenor'},
'456094':{'en': 'telenor'},
'456095':{'en': 'telenor'},
'456096':{'en': 'tripple track europe'},
'456097':{'en': 'tripple track europe'},
'456098':{'en': 'telavox'},
'456099':{'en': 'svr technologies (mach connectivity)'},
'4561':{'en': 'tdc'},
'45610':{'en': 'orange'},
'456146':{'en': 'telia'},
'45618':{'en': 'telenor'},
'45619':{'en': 'telenor'},
'45621':{'en': 'telenor'},
'45622':{'en': 'telenor'},
'45623':{'en': 'telenor'},
'45624':{'en': 'telenor'},
'45625':{'en': 'telenor'},
'45626':{'en': 'telenor'},
'45627':{'en': 'telenor'},
'45628':{'en': 'telenor'},
'45629':{'en': 'telenor'},
'45631':{'en': 'telenor'},
'45632':{'en': 'telenor'},
'45633':{'en': 'telenor'},
'45634':{'en': 'telenor'},
'45635':{'en': 'telenor'},
'45636':{'en': 'telenor'},
'45637':{'en': 'telenor'},
'45638':{'en': 'telenor'},
'45639':{'en': 'telenor'},
'4564212':{'en': 'tdc'},
'4564215':{'en': 'tdc'},
'4564222':{'en': 'tdc'},
'4564281':{'en': 'tdc'},
'4564292':{'en': 'tdc'},
'4564400':{'en': 'tdc'},
'4564401':{'en': 'tdc'},
'4564402':{'en': 'tdc'},
'4564403':{'en': 'tdc'},
'4564404':{'en': 'tdc'},
'4564406':{'en': 'tdc'},
'456441':{'en': 'tdc'},
'4564421':{'en': 'tdc'},
'4564422':{'en': 'tdc'},
'4564423':{'en': 'tdc'},
'4564431':{'en': 'tdc'},
'4564432':{'en': 'tdc'},
'4564433':{'en': 'tdc'},
'4564441':{'en': 'tdc'},
'4564442':{'en': 'tdc'},
'4564451':{'en': 'tdc'},
'4564457':{'en': 'tdc'},
'4564458':{'en': 'tdc'},
'4564459':{'en': 'tdc'},
'4564460':{'en': 'tdc'},
'4564461':{'en': 'tdc'},
'4564462':{'en': 'tdc'},
'4564471':{'en': 'tdc'},
'4564472':{'en': 'tdc'},
'4564473':{'en': 'tdc'},
'4564474':{'en': 'tdc'},
'4564481':{'en': 'tdc'},
'4564491':{'en': 'tdc'},
'4564492':{'en': 'tdc'},
'4564505':{'en': 'tdc'},
'456463':{'en': 'telenor'},
'456464':{'en': 'waoo'},
'456465':{'en': 'waoo'},
'456466':{'en': 'waoo'},
'456467':{'en': 'waoo'},
'456468':{'en': 'waoo'},
'456469':{'en': 'waoo'},
'456471':{'en': 'tdc'},
'4564721':{'en': 'tdc'},
'4564722':{'en': 'tdc'},
'4564723':{'en': 'tdc'},
'4564731':{'en': 'tdc'},
'4564732':{'en': 'tdc'},
'4564733':{'en': 'tdc'},
'4564741':{'en': 'tdc'},
'4564742':{'en': 'tdc'},
'4564746':{'en': 'tdc'},
'4564747':{'en': 'tdc'},
'4564751':{'en': 'tdc'},
'4564752':{'en': 'tdc'},
'4564761':{'en': 'tdc'},
'4564762':{'en': 'tdc'},
'4564763':{'en': 'tdc'},
'4564764':{'en': 'tdc'},
'4564771':{'en': 'tdc'},
'4564781':{'en': 'tdc'},
'4564787':{'en': 'tdc'},
'4564788':{'en': 'tdc'},
'4564789':{'en': 'tdc'},
'4564790':{'en': 'tdc'},
'4564791':{'en': 'tdc'},
'4564792':{'en': 'tdc'},
'4564801':{'en': 'tdc'},
'4564804':{'en': 'tdc'},
'4564805':{'en': 'tdc'},
'4564806':{'en': 'tdc'},
'4564811':{'en': 'tdc'},
'4564812':{'en': 'tdc'},
'4564813':{'en': 'tdc'},
'4564814':{'en': 'tdc'},
'4564820':{'en': 'tdc'},
'4564821':{'en': 'tdc'},
'4564822':{'en': 'tdc'},
'4564823':{'en': 'tdc'},
'4564824':{'en': 'tdc'},
'4564825':{'en': 'tdc'},
'4564826':{'en': 'tdc'},
'4564827':{'en': 'tdc'},
'4564828':{'en': 'tdc'},
'4564831':{'en': 'tdc'},
'4564841':{'en': 'tdc'},
'4564842':{'en': 'tdc'},
'4564851':{'en': 'tdc'},
'4564852':{'en': 'tdc'},
'4564861':{'en': 'tdc'},
'4564871':{'en': 'tdc'},
'4564872':{'en': 'tdc'},
'4564881':{'en': 'tdc'},
'4564882':{'en': 'tdc'},
'4564891':{'en': 'tdc'},
'4564892':{'en': 'tdc'},
'4564893':{'en': 'tdc'},
'4564897':{'en': 'tdc'},
'4564898':{'en': 'tdc'},
'4564899':{'en': 'tdc'},
'45651':{'en': 'telenor'},
'45652':{'en': 'telenor'},
'45653':{'en': 'telenor'},
'45654':{'en': 'telenor'},
'45655':{'en': 'telenor'},
'45656':{'en': 'telenor'},
'45657':{'en': 'telenor'},
'45658':{'en': 'telenor'},
'45659':{'en': 'telenor'},
'45661':{'en': 'telenor'},
'45662':{'en': 'telenor'},
'45663':{'en': 'telenor'},
'45664':{'en': 'telenor'},
'45665':{'en': 'telenor'},
'45666':{'en': 'telenor'},
'45667':{'en': 'telenor'},
'45668':{'en': 'telenor'},
'45669':{'en': 'telenor'},
'45691':{'en': 'telenor'},
'45692':{'en': 'telenor'},
'45693':{'en': 'telenor'},
'45694':{'en': 'telenor'},
'456957':{'en': 'telenor'},
'456958':{'en': 'telenor'},
'456959':{'en': 'telenor'},
'45696':{'en': 'telenor'},
'45697':{'en': 'telenor'},
'45698':{'en': 'telenor'},
'45699':{'en': 'telenor'},
'457010':{'en': 'tdc'},
'457011':{'en': 'tdc'},
'457012':{'en': 'tdc'},
'457013':{'en': 'tdc'},
'457014':{'en': 'tdc'},
'457015':{'en': 'tdc'},
'4570160':{'en': 'telenor'},
'4570161':{'en': 'telenor'},
'4570180':{'en': 'herobase'},
'4570181':{'en': 'telenor'},
'457019':{'en': 'telenor'},
'457030':{'en': 'telenor'},
'4570300':{'en': 'telia'},
'4570301':{'en': 'telia'},
'4570302':{'en': 'telia'},
'457031':{'en': 'telenor'},
'4570323':{'en': 'telenor'},
'457033':{'en': 'telenor'},
'4570345':{'en': 'telenor'},
'4570444':{'en': 'telenor'},
'4570500':{'en': 'telenor'},
'4570505':{'en': 'telenor'},
'4570507':{'en': 'telus aps'},
'4570555':{'en': 'telenor'},
'457060':{'en': 'telenor'},
'4570666':{'en': 'telenor'},
'457070':{'en': 'telenor'},
'457071':{'en': 'telenor'},
'4570770':{'en': 'telenor'},
'4570776':{'en': 'telenor'},
'4570777':{'en': 'telenor'},
'4570778':{'en': 'telenor'},
'457080':{'en': 'telenor'},
'4570810':{'en': 'telenor'},
'4570811':{'en': 'telenor'},
'4570812':{'en': 'telenor'},
'4570813':{'en': 'telenor'},
'4570814':{'en': 'telenor'},
'4570815':{'en': 'telenor'},
'4570816':{'en': 'telenor'},
'4570817':{'en': 'telenor'},
'4570818':{'en': 'telenor'},
'4570828':{'en': 'telenor'},
'4570838':{'en': 'telenor'},
'4570848':{'en': 'telenor'},
'4570858':{'en': 'telenor'},
'4570868':{'en': 'telenor'},
'457087':{'en': 'telenor'},
'457088':{'en': 'supertel danmark'},
'457089':{'en': 'telenor'},
'4570900':{'en': 'telenor'},
'4570907':{'en': 'telus aps'},
'4570909':{'en': 'telenor'},
'4570999':{'en': 'telenor'},
'45711':{'en': 'telenor'},
'45712':{'en': 'telenor'},
'45713':{'en': 'lycamobile denmark ltd'},
'45714':{'en': 'lycamobile denmark ltd'},
'45715':{'en': 'lycamobile denmark ltd'},
'45716':{'en': 'lycamobile denmark ltd'},
'457170':{'en': 'yousee'},
'457171':{'en': 'telenor'},
'457172':{'en': 'tdc'},
'457173':{'en': 'cbb mobil'},
'45717409':{'en': 'tdc'},
'45717429':{'en': 'tdc'},
'457175':{'en': 'telenor'},
'457176':{'en': 'telenor'},
'457177':{'en': 'tdc'},
'457178':{'en': 'telenor'},
'457179':{'en': 'telenor'},
'45718':{'en': 'lycamobile denmark ltd'},
'457190':{'en': '3'},
'457191':{'en': 'telecom x'},
'457192':{'en': 'fullrate'},
'457193':{'en': 'cbb mobil'},
'457194':{'en': 'telenor'},
'457195':{'en': 'telenor'},
'4571960':{'en': 'tdc'},
'45719649':{'en': 'tdc'},
'45719689':{'en': 'tdc'},
'457197':{'en': 'mundio mobile'},
'457198':{'en': 'mundio mobile'},
'457199':{'en': 'firmafon'},
'45721':{'en': 'telenor'},
'45722':{'en': 'telenor'},
'45723':{'en': 'telenor'},
'45724':{'en': 'telenor'},
'45725':{'en': 'telenor'},
'45726':{'en': 'telenor'},
'45727':{'en': 'telenor'},
'45728':{'en': 'telenor'},
'45729':{'en': 'telenor'},
'45731':{'en': 'telenor'},
'45732':{'en': 'telenor'},
'45733':{'en': 'telenor'},
'45734':{'en': 'telenor'},
'45735':{'en': 'telenor'},
'45736':{'en': 'telenor'},
'45737':{'en': 'telenor'},
'45738':{'en': 'telenor'},
'45739':{'en': 'telenor'},
'45741':{'en': 'telenor'},
'45742':{'en': 'telenor'},
'45743':{'en': 'telenor'},
'45744':{'en': 'telenor'},
'45745':{'en': 'telenor'},
'45746':{'en': 'telenor'},
'45747':{'en': 'telenor'},
'45748':{'en': 'telenor'},
'45749':{'en': 'telenor'},
'45751':{'en': 'telenor'},
'45752':{'en': 'telenor'},
'45753':{'en': 'telenor'},
'45754':{'en': 'telenor'},
'45755':{'en': 'telenor'},
'45756':{'en': 'telenor'},
'45757':{'en': 'telenor'},
'45758':{'en': 'telenor'},
'45759':{'en': 'telenor'},
'45761':{'en': 'telenor'},
'45762':{'en': 'telenor'},
'45763':{'en': 'telenor'},
'45764':{'en': 'telenor'},
'45765':{'en': 'telenor'},
'45766':{'en': 'telenor'},
'45767':{'en': 'telenor'},
'45768':{'en': 'telenor'},
'45769':{'en': 'telenor'},
'45771':{'en': 'telenor'},
'45772':{'en': 'telenor'},
'45773':{'en': 'telenor'},
'45774':{'en': 'telenor'},
'45775':{'en': 'telenor'},
'45776':{'en': 'telenor'},
'45777':{'en': 'telenor'},
'45778':{'en': 'telenor'},
'45779':{'en': 'telenor'},
'45781':{'en': 'telenor'},
'45782':{'en': 'telenor'},
'45783':{'en': 'telenor'},
'45784':{'en': 'telenor'},
'45785':{'en': 'telenor'},
'45786':{'en': 'telenor'},
'45787':{'en': 'telenor'},
'457879':{'en': 'supertel danmark'},
'45788':{'en': 'telenor'},
'45789':{'en': 'telenor'},
'45791':{'en': 'telenor'},
'45792':{'en': 'telenor'},
'45793':{'en': 'telenor'},
'45794':{'en': 'telenor'},
'45795':{'en': 'telenor'},
'45796':{'en': 'telenor'},
'45797':{'en': 'telenor'},
'45798':{'en': 'telenor'},
'45799':{'en': 'telenor'},
'45811':{'en': 'telenor'},
'45812':{'en': 'telenor'},
'458130':{'en': 'cbb mobil'},
'458131':{'en': 'cbb mobil'},
'458132':{'en': 'cbb mobil'},
'458133':{'en': 'cbb mobil'},
'458134':{'en': 'cbb mobil'},
'458135':{'en': 'cbb mobil'},
'458136':{'en': 'cbb mobil'},
'4581370':{'en': 'telenor'},
'4581371':{'en': 'clx networks ab'},
'4581372':{'en': 'care solutions aka phone-it'},
'4581373':{'en': 'tdc'},
'4581374':{'en': 'mitto ag'},
'4581375':{'en': 'monty uk global limited'},
'4581376':{'en': 'icentrex lso(tdc)'},
'4581379':{'en': 'telenor'},
'458138':{'en': 'mundio mobile'},
'458139':{'en': 'mundio mobile'},
'458140':{'en': 'ipnordic'},
'458141':{'en': '3'},
'458144':{'en': 'fullrate'},
'458145':{'en': 'telavox'},
'458146':{'en': 'mundio mobile'},
'458147':{'en': 'mundio mobile'},
'458148':{'en': 'mundio mobile'},
'458149':{'en': 'mundio mobile'},
'45815':{'en': 'cbb mobil'},
'45816':{'en': 'cbb mobil'},
'458161':{'en': 'tdc'},
'458170':{'en': 'cbb mobil'},
'458171':{'en': 'tdc'},
'458172':{'en': 'fullrate'},
'458173':{'en': 'tdc'},
'458174':{'en': 'tdc'},
'458175':{'en': 'tdc'},
'458176':{'en': 'cbb mobil'},
'458177':{'en': 'ipvision'},
'458178':{'en': 'cbb mobil'},
'458179':{'en': 'cbb mobil'},
'45818':{'en': 'cbb mobil'},
'458180':{'en': 'ipvision'},
'458181':{'en': 'maxtel.dk'},
'458182':{'en': 'polperro'},
'458188':{'en': 'ipvision'},
'458190':{'en': 'lebara limited'},
'458191':{'en': 'lebara limited'},
'458192':{'en': 'lebara limited'},
'458193':{'en': 'lebara limited'},
'458194':{'en': 'lebara limited'},
'458195':{'en': 'cbb mobil'},
'458196':{'en': 'cbb mobil'},
'458197':{'en': 'cbb mobil'},
'458198':{'en': 'cbb mobil'},
'458199':{'en': 'telenor'},
'45821':{'en': 'telenor'},
'45822':{'en': 'telenor'},
'45823':{'en': 'telenor'},
'45824':{'en': 'telenor'},
'45825':{'en': 'telenor'},
'45826':{'en': 'telenor'},
'45827':{'en': 'telenor'},
'45828':{'en': 'telenor'},
'45829':{'en': 'telenor'},
'45861':{'en': 'telenor'},
'45862':{'en': 'telenor'},
'45863':{'en': 'telenor'},
'45864':{'en': 'telenor'},
'45865':{'en': 'telenor'},
'45866':{'en': 'telenor'},
'45867':{'en': 'telenor'},
'45868':{'en': 'telenor'},
'45869':{'en': 'telenor'},
'45871':{'en': 'telenor'},
'45872':{'en': 'telenor'},
'45873':{'en': 'telenor'},
'45874':{'en': 'telenor'},
'45875':{'en': 'telenor'},
'45876':{'en': 'telenor'},
'45877':{'en': 'telenor'},
'45878':{'en': 'telenor'},
'45879':{'en': 'telenor'},
'45881':{'en': 'telenor'},
'45882':{'en': 'telenor'},
'45883':{'en': 'telenor'},
'45884':{'en': 'telenor'},
'45885':{'en': 'telenor'},
'45886':{'en': 'telenor'},
'45887':{'en': 'telenor'},
'45888':{'en': 'telenor'},
'45889':{'en': 'telenor'},
'45891':{'en': 'telenor'},
'45892':{'en': 'telenor'},
'45893':{'en': 'telenor'},
'45894':{'en': 'telenor'},
'45895':{'en': 'telenor'},
'45896':{'en': 'telenor'},
'45897':{'en': 'telenor'},
'45898':{'en': 'telenor'},
'45899':{'en': 'telenor'},
'459110':{'en': 'lebara limited'},
'459111':{'en': 'lebara limited'},
'459112':{'en': 'simservice'},
'459113':{'en': 'simservice'},
'459114':{'en': 'simservice'},
'459115':{'en': 'tdc'},
'459116':{'en': 'tdc'},
'459117':{'en': 'tdc'},
'459118':{'en': 'tdc'},
'459119':{'en': 'lebara limited'},
'459120':{'en': 'tismi bv'},
'459121':{'en': 'simservice'},
'459122':{'en': 'tdc'},
'459123':{'en': 'tdc'},
'459124':{'en': 'tdc'},
'459125':{'en': 'tdc'},
'459126':{'en': 'mundio mobile'},
'459127':{'en': 'mundio mobile'},
'459128':{'en': 'mundio mobile'},
'459129':{'en': 'mundio mobile'},
'4591300':{'en': 'maxtel.dk'},
'4591303':{'en': 'maxtel.dk'},
'459131':{'en': 'telenor'},
'459132':{'en': 'telenor'},
'459133':{'en': 'telenor'},
'459134':{'en': 'telenor'},
'459135':{'en': 'telenor'},
'459136':{'en': 'telenor'},
'459137':{'en': 'telenor'},
'459138':{'en': 'telenor'},
'459139':{'en': 'telenor'},
'45914':{'en': 'lycamobile denmark ltd'},
'459150':{'en': 'telenor'},
'459151':{'en': 'telenor'},
'459152':{'en': 'tdc'},
'459153':{'en': 'tdc'},
'459154':{'en': 'tdc'},
'459155':{'en': 'tdc'},
'459156':{'en': 'tdc'},
'459157':{'en': 'mundio mobile'},
'459158':{'en': 'nextgen mobile ldt t/a cardboardfish'},
'459159':{'en': 'simservice'},
'45916':{'en': 'lycamobile denmark ltd'},
'45917':{'en': 'lycamobile denmark ltd'},
'45918':{'en': 'lebara limited'},
'459189':{'en': 'tdc'},
'45919':{'en': 'lebara limited'},
'459190':{'en': 'intelecom'},
'459191':{'en': 'maxtel.dk'},
'45921':{'en': 'tdc'},
'459217':{'en': 'interactive digital media gmbh'},
'459218':{'en': 'telenor'},
'459219':{'en': 'telenor'},
'459220':{'en': 'telenor'},
'459221':{'en': 'tdc'},
'459222':{'en': 'tdc'},
'459223':{'en': '42 telecom ab'},
'459224':{'en': 'simservice'},
'459225':{'en': 'mundio mobile'},
'459226':{'en': 'mundio mobile'},
'459227':{'en': 'mundio mobile'},
'459228':{'en': 'mundio mobile'},
'459229':{'en': 'beepsend ab'},
'45923':{'en': 'telenor'},
'459240':{'en': 'gigsky aps'},
'459241':{'en': 'gigsky aps'},
'459242':{'en': 'gigsky aps'},
'459243':{'en': 'tdc'},
'459244':{'en': 'ipnordic'},
'459245':{'en': 'compatel limited'},
'459246':{'en': 'telenor'},
'459247':{'en': 'telenor'},
'459248':{'en': 'telenor'},
'459249':{'en': 'telenor'},
'45925':{'en': 'telenor'},
'45926':{'en': 'telenor'},
'45927':{'en': 'telenor'},
'459270':{'en': 'ice danmark'},
'459272':{'en': 'thyfon'},
'45928':{'en': 'telenor'},
'459280':{'en': 'voxbone'},
'459281':{'en': 'gigsky aps'},
'459282':{'en': 'flexfone'},
'459283':{'en': 'tdc'},
'45929':{'en': 'telenor'},
'459290':{'en': 'fullrate'},
'459299':{'en': 'ipvision'},
'459310':{'en': 'fullrate'},
'459311':{'en': 'benemen lso (tdc)'},
'459312':{'en': 'tdc'},
'459313':{'en': 'tdc'},
'459314':{'en': 'simservice'},
'459315':{'en': 'simservice'},
'459316':{'en': 'simservice'},
'459317':{'en': 'simservice'},
'459318':{'en': 'simservice'},
'459319':{'en': 'tdc'},
'459320':{'en': 'fullrate'},
'459321':{'en': 'simservice'},
'459322':{'en': 'simservice'},
'459323':{'en': 'simservice'},
'459324':{'en': 'simservice'},
'459325':{'en': 'telenor'},
'459326':{'en': 'telenor'},
'459327':{'en': 'telenor'},
'459328':{'en': 'telenor'},
'459329':{'en': 'telenor'},
'459330':{'en': 'fullrate'},
'459331':{'en': 'tdc'},
'459332':{'en': 'telenor'},
'459333':{'en': 'onoffapp'},
'459334':{'en': 'simservice'},
'459335':{'en': 'simservice'},
'459336':{'en': 'simservice'},
'459337':{'en': 'simservice'},
'459338':{'en': 'simservice'},
'459339':{'en': 'uni-tel'},
'459340':{'en': 'fullrate'},
'459341':{'en': 'telenor'},
'459342':{'en': 'telenor'},
'459343':{'en': 'telenor'},
'459344':{'en': 'telenor'},
'459345':{'en': 'telenor'},
'459346':{'en': 'simservice'},
'459347':{'en': 'simservice'},
'459348':{'en': 'simservice'},
'459349':{'en': 'simservice'},
'45935':{'en': 'telenor'},
'45936':{'en': 'simservice'},
'459360':{'en': '3'},
'459361':{'en': 'telenor'},
'459362':{'en': 'telenor'},
'459363':{'en': 'tdc'},
'459370':{'en': 'telenor'},
'459371':{'en': 'simservice'},
'459372':{'en': 'simservice'},
'459373':{'en': 'simservice'},
'459375':{'en': 'telenor'},
'459376':{'en': 'tdc'},
'459377':{'en': 'tdc'},
'459378':{'en': 'telenor'},
'459379':{'en': 'tdc'},
'45938':{'en': '3'},
'459381':{'en': 'tdc'},
'459382':{'en': 'tdc'},
'45939':{'en': '3'},
'459440':{'en': 'tdc'},
'459441':{'en': 'tdc'},
'459442':{'en': 'tdc'},
'459481':{'en': 'tdc'},
'4596':{'en': 'telenor'},
'45971':{'en': 'telenor'},
'45972':{'en': 'telenor'},
'45973':{'en': 'telenor'},
'45974':{'en': 'telenor'},
'45975':{'en': 'telenor'},
'45976':{'en': 'telenor'},
'45978':{'en': 'telenor'},
'45979':{'en': 'telenor'},
'45981':{'en': 'telenor'},
'45982':{'en': 'telenor'},
'45983':{'en': 'telenor'},
'45984':{'en': 'telenor'},
'45985':{'en': 'telenor'},
'45986':{'en': 'telenor'},
'45987':{'en': 'telenor'},
'45988':{'en': 'telenor'},
'45989':{'en': 'telenor'},
'45991':{'en': 'telenor'},
'45992':{'en': 'telenor'},
'45993':{'en': 'telenor'},
'45994':{'en': 'telenor'},
'45995':{'en': 'telenor'},
'45996':{'en': 'telenor'},
'45997':{'en': 'telenor'},
'45998':{'en': 'telenor'},
'45999':{'en': 'telenor'},
'46700':{'en': 'Tele2 Sverige'},
'467010':{'en': 'SPINBOX AB'},
'467011':{'en': 'Telenor Sverige'},
'467012':{'en': 'SPINBOX AB'},
'46701332':{'en': 'EU Tel AB'},
'46701334':{'en': 'EU Tel AB'},
'46701335':{'en': 'EU Tel AB'},
'46701336':{'en': 'EU Tel AB'},
'46701338':{'en': 'EU Tel AB'},
'46701339':{'en': 'EU Tel AB'},
'46701341':{'en': 'EU Tel AB'},
'46701342':{'en': 'EU Tel AB'},
'46701346':{'en': 'EU Tel AB'},
'46701347':{'en': 'EU Tel AB'},
'46701348':{'en': 'EU Tel AB'},
'46701349':{'en': 'EU Tel AB'},
'46701353':{'en': 'EU Tel AB'},
'46701356':{'en': 'EU Tel AB'},
'46701358':{'en': 'EU Tel AB'},
'46701359':{'en': 'EU Tel AB'},
'46701362':{'en': 'EU Tel AB'},
'46701364':{'en': '42 Telecom AB'},
'46701365':{'en': '42 Telecom AB'},
'46701366':{'en': '42 Telecom AB'},
'46701367':{'en': '42 Telecom AB'},
'46701368':{'en': '42 Telecom AB'},
'46701369':{'en': '42 Telecom AB'},
'4670137':{'en': '42 Telecom AB'},
'46701381':{'en': '42 Telecom AB'},
'46701383':{'en': '42 Telecom AB'},
'46701384':{'en': '42 Telecom AB'},
'46701385':{'en': '42 Telecom AB'},
'46701386':{'en': '42 Telecom AB'},
'46701388':{'en': '42 Telecom AB'},
'46701389':{'en': '42 Telecom AB'},
'46701390':{'en': '42 Telecom AB'},
'46701391':{'en': '42 Telecom AB'},
'46701392':{'en': '42 Telecom AB'},
'46701393':{'en': '42 Telecom AB'},
'46701394':{'en': '42 Telecom AB'},
'46701396':{'en': '42 Telecom AB'},
'46701397':{'en': '42 Telecom AB'},
'46701398':{'en': '42 Telecom AB'},
'46701399':{'en': '42 Telecom AB'},
'467014':{'en': 'Telenor Sverige'},
'467015':{'en': 'Tele2 Sverige'},
'467016':{'en': 'Tele2 Sverige'},
'46701717':{'en': '42 Telecom AB'},
'46701741':{'en': '42 Telecom AB'},
'46701779':{'en': 'EU Tel AB'},
'46701780':{'en': '42 Telecom AB'},
'46701781':{'en': '42 Telecom AB'},
'46701782':{'en': '42 Telecom AB'},
'46701783':{'en': '42 Telecom AB'},
'46701784':{'en': '42 Telecom AB'},
'46701785':{'en': '42 Telecom AB'},
'46701786':{'en': '42 Telecom AB'},
'46701788':{'en': 'Ventelo Sverige'},
'46701790':{'en': 'Svea Billing System'},
'46701791':{'en': 'Svea Billing System'},
'46701792':{'en': 'Svea Billing System'},
'46701793':{'en': 'Svea Billing System'},
'46701794':{'en': 'Svea Billing System'},
'46701795':{'en': 'Svea Billing System'},
'46701796':{'en': 'Svea Billing System'},
'46701797':{'en': 'EU Tel AB'},
'46701798':{'en': 'Gotalandsnatet'},
'467018':{'en': 'SPINBOX AB'},
'4670189':{'en': 'Alltele Sverige'},
'46701897':{'en': 'Gotalandsnatet'},
'4670190':{'en': 'Ventelo Sverige'},
'4670191':{'en': 'Ventelo Sverige'},
'46701920':{'en': 'Viatel Sweden'},
'46701921':{'en': 'Beepsend'},
'46701924':{'en': 'Compatel Limited'},
'46701925':{'en': 'Mobile Arts AB'},
'46701926':{'en': 'Beepsend'},
'46701928':{'en': 'HORISEN AG'},
'4670193':{'en': 'Com Hem'},
'4670194':{'en': 'Gotalandsnatet'},
'4670195':{'en': 'Gotalandsnatet'},
'46701965':{'en': '42 Telecom AB'},
'46701966':{'en': '42 Telecom AB'},
'46701967':{'en': '42 Telecom AB'},
'46701968':{'en': '42 Telecom AB'},
'4670197':{'en': 'Weblink IP Phone'},
'46701977':{'en': '42 Telecom AB'},
'46701978':{'en': '42 Telecom AB'},
'46701979':{'en': '42 Telecom AB'},
'4670198':{'en': 'IP-Only Telecommunication'},
'46701990':{'en': 'Telenor Sverige'},
'46701991':{'en': 'Telenor Sverige'},
'46701992':{'en': 'Telenor Sverige'},
'46701993':{'en': 'Telenor Sverige'},
'46701994':{'en': 'Telenor Sverige'},
'46701995':{'en': 'Telenor Sverige'},
'46701997':{'en': '42 Telecom AB'},
'46701998':{'en': 'MERCURY INTERNATIONA'},
'46701999':{'en': '42 Telecom AB'},
'46702':{'en': 'TeliaSonera'},
'46703':{'en': 'TeliaSonera'},
'46704':{'en': 'Tele2 Sverige'},
'46705':{'en': 'TeliaSonera'},
'46706':{'en': 'TeliaSonera'},
'46707':{'en': 'Tele2 Sverige'},
'46708':{'en': 'Telenor Sverige'},
'46709':{'en': 'Telenor Sverige'},
'467200':{'en': 'Tele2 Sverige'},
'467201':{'en': 'Tele2 Sverige'},
'467202':{'en': 'Tele2 Sverige'},
'467203':{'en': 'Tele2 Sverige'},
'467204':{'en': 'Tele2 Sverige'},
'46720501':{'en': 'Generic Mobil Systems'},
'46720502':{'en': 'Telavox AB'},
'46720503':{'en': 'Telavox AB'},
'46720504':{'en': 'Telavox AB'},
'46720505':{'en': 'Telavox AB'},
'46720506':{'en': 'Telavox AB'},
'46720507':{'en': 'Telavox AB'},
'46720509':{'en': 'Telavox AB'},
'4672051':{'en': 'WIFOG AB'},
'4672052':{'en': 'WIFOG AB'},
'4672053':{'en': 'WIFOG AB'},
'4672054':{'en': 'WIFOG AB'},
'4672055':{'en': 'Bahnhof AB'},
'4672056':{'en': 'Bahnhof AB'},
'4672057':{'en': 'WIFOG AB'},
'46720580':{'en': 'MERCURY INTERNATIONA'},
'46720581':{'en': 'Beepsend'},
'46720582':{'en': 'iCentrex Sweden AB'},
'46720583':{'en': 'iCentrex Sweden AB'},
'46720584':{'en': 'iCentrex Sweden AB'},
'46720585':{'en': 'iCentrex Sweden AB'},
'46720586':{'en': 'iCentrex Sweden AB'},
'4672059':{'en': 'Telenor Sverige'},
'467206':{'en': 'Com Hem'},
'467207':{'en': 'SOLUNO BC AB'},
'46720801':{'en': 'Telavox AB'},
'46720802':{'en': 'Telavox AB'},
'46720803':{'en': 'Telavox AB'},
'46720807':{'en': 'Telavox AB'},
'46720808':{'en': 'Telavox AB'},
'4672081':{'en': 'BM Sverige AB'},
'4672082':{'en': 'Fibio Nordic AB'},
'4672083':{'en': 'Tele2 Sverige'},
'4672084':{'en': 'Tele2 Sverige'},
'4672085':{'en': 'Tele2 Sverige'},
'4672088':{'en': 'Telenor Sverige'},
'46720902':{'en': 'Telavox AB'},
'46720908':{'en': 'Telavox AB'},
'4672092':{'en': 'Telavox AB'},
'46720999':{'en': 'MOBIWEB LTD'},
'467210':{'en': 'SVENSK KONSUMENTMOBI'},
'467211':{'en': 'SVENSK KONSUMENTMOBI'},
'467212':{'en': 'TeliaSonera'},
'467213':{'en': 'TeliaSonera'},
'4672140':{'en': 'Bredband 2'},
'4672141':{'en': 'Tele2 Sverige'},
'4672142':{'en': 'Tele2 Sverige'},
'4672143':{'en': 'Tele2 Sverige'},
'4672144':{'en': 'Tele2 Sverige'},
'4672145':{'en': 'Tele2 Sverige'},
'4672146':{'en': 'Tele2 Sverige'},
'4672147':{'en': 'Tele2 Sverige'},
'4672148':{'en': 'Tele2 Sverige'},
'46721490':{'en': 'Tele2 Sverige'},
'46721491':{'en': 'Tele2 Sverige'},
'46721492':{'en': 'Tele2 Sverige'},
'46721493':{'en': 'Tele2 Sverige'},
'46721494':{'en': 'Tele2 Sverige'},
'46721495':{'en': 'Beepsend'},
'46721497':{'en': 'MONTY UK GLOBAL LIM'},
'46721498':{'en': 'Beepsend'},
'467215':{'en': 'Telenor Sverige'},
'467216':{'en': 'Telenor Sverige'},
'467217':{'en': 'Telenor Sverige'},
'467218':{'en': 'Telenor Sverige'},
'467219':{'en': 'Telenor Sverige'},
'46722':{'en': 'TeliaSonera'},
'467230':{'en': 'HI3G Access'},
'467231':{'en': 'HI3G Access'},
'467232':{'en': 'HI3G Access'},
'467233':{'en': 'HI3G Access'},
'46723401':{'en': 'LOXYTEL AB'},
'46723403':{'en': 'Beepsend'},
'46723404':{'en': 'LOXYTEL AB'},
'46723405':{'en': 'LOXYTEL AB'},
'46723406':{'en': 'LOXYTEL AB'},
'46723407':{'en': 'LOXYTEL AB'},
'46723408':{'en': 'ONOFF TELECOM SAS'},
'46723409':{'en': 'ONOFF TELECOM SAS'},
'4672341':{'en': 'TELIGOO AB (Fello AB)'},
'4672342':{'en': 'Telenor Sverige'},
'4672343':{'en': 'MESSAGEBIRD B.V.'},
'46723440':{'en': 'Beepsend'},
'46723449':{'en': 'Beepsend'},
'4672345':{'en': '42 Telecom AB'},
'46723460':{'en': 'Beepsend'},
'4672347':{'en': 'Benemen Oy'},
'4672348':{'en': 'Benemen Oy'},
'46723490':{'en': 'Beepsend'},
'46723499':{'en': 'Beepsend'},
'467235':{'en': 'Telenor Sverige'},
'467236':{'en': 'Telenor Sverige'},
'467237':{'en': 'Telenor Sverige'},
'467238':{'en': 'Telenor Sverige'},
'467239':{'en': 'Telenor Sverige'},
'46724000':{'en': 'Telenor Sverige'},
'46724001':{'en': 'Beepsend'},
'46724002':{'en': 'Voice Integrate'},
'46724003':{'en': 'Voice Integrate'},
'46724004':{'en': 'Beepsend'},
'46724008':{'en': 'Telavox AB'},
'4672401':{'en': 'Telavox AB'},
'4672402':{'en': 'Telavox AB'},
'467242':{'en': 'WIFOG AB'},
'467243':{'en': 'WIFOG AB'},
'467244':{'en': 'Telenor Sverige'},
'467245':{'en': 'TeliaSonera'},
'467246':{'en': 'TeliaSonera'},
'467247':{'en': 'TeliaSonera'},
'467248':{'en': 'TeliaSonera'},
'467249':{'en': 'TeliaSonera'},
'46725':{'en': 'TeliaSonera'},
'46726000':{'en': 'Beepsend'},
'46726001':{'en': 'FINK TELECOM SERVIC'},
'46726003':{'en': 'MOBIWEB LTD'},
'46726004':{'en': 'Tele2 Sverige'},
'46726005':{'en': 'Tele2 Sverige'},
'46726006':{'en': 'Telavox AB'},
'46726008':{'en': 'Global Telefoni Sve'},
'4672601':{'en': 'Telavox AB'},
'4672606':{'en': 'Tele2 Sverige'},
'467261':{'en': 'GLOBETOUCH AB'},
'467262':{'en': 'GLOBETOUCH AB'},
'467263':{'en': 'GLOBETOUCH AB'},
'46726421':{'en': 'WARSIN HOLDING AB'},
'46726422':{'en': 'Beepsend'},
'46726423':{'en': 'Global Telefoni Sve'},
'46726424':{'en': 'Global Telefoni Sve'},
'46726425':{'en': 'Global Telefoni Sve'},
'46726426':{'en': 'Global Telefoni Sve'},
'46726427':{'en': 'Global Telefoni Sve'},
'46726428':{'en': 'Global Telefoni Sve'},
'46726429':{'en': 'Global Telefoni Sve'},
'4672644':{'en': 'Telenor Sverige'},
'467265':{'en': 'TeliaSonera'},
'4672660':{'en': 'Telenor Sverige'},
'4672666':{'en': 'Telenor Sverige'},
'4672669':{'en': 'Nortech'},
'467267':{'en': 'TeliaSonera'},
'467268':{'en': 'TeliaSonera'},
'4672698':{'en': 'SWEDFONENET AB'},
'46726990':{'en': 'Gotalandsnatet'},
'46726991':{'en': 'Fast Communication'},
'46726992':{'en': 'Fast Communication'},
'46726993':{'en': 'SWEDFONENET AB'},
'46726994':{'en': 'SWEDFONENET AB'},
'46726995':{'en': 'SWEDFONENET AB'},
'46726996':{'en': 'Nortech'},
'46726997':{'en': 'ONOFF TELECOM SAS'},
'46726998':{'en': 'ONOFF TELECOM SAS'},
'467270':{'en': 'TeliaSonera'},
'467271':{'en': 'TeliaSonera'},
'467272':{'en': 'TeliaSonera'},
'467273':{'en': 'TeliaSonera'},
'467274':{'en': 'TeliaSonera'},
'46727501':{'en': 'ONOFF TELECOM SAS'},
'46727502':{'en': 'ONOFF TELECOM SAS'},
'46727503':{'en': 'MINITEL AB'},
'46727504':{'en': 'FINK TELECOM SERVIC'},
'46727506':{'en': 'FINK TELECOM SERVIC'},
'46727507':{'en': 'FINK TELECOM SERVIC'},
'46727510':{'en': 'ONOFF TELECOM SAS'},
'46727511':{'en': 'ONOFF TELECOM SAS'},
'46727515':{'en': 'FINK TELECOM SERVIC'},
'46727516':{'en': 'FINK TELECOM SERVIC'},
'4672753':{'en': 'NETMORE GROUP AB'},
'4672754':{'en': 'Telenor Sverige'},
'4672755':{'en': 'FINK TELECOM SERVIC'},
'4672756':{'en': 'FINK TELECOM SERVIC'},
'467276':{'en': 'Lycamobile Sweden'},
'467277':{'en': 'Lycamobile Sweden'},
'467278':{'en': 'Lycamobile Sweden'},
'46728100':{'en': 'Voice Integrate'},
'46728101':{'en': 'Beepsend'},
'46728198':{'en': 'Telavox AB'},
'467282':{'en': 'Telecom3 Networks'},
'467283':{'en': 'Tele2 Sverige'},
'467284':{'en': 'Tele2 Sverige'},
'467285':{'en': 'Tele2 Sverige'},
'467286':{'en': 'Tele2 Sverige'},
'467287':{'en': 'Tele2 Sverige'},
'467288':{'en': 'Telenor Sverige'},
'467289':{'en': 'Qall Telecom AB'},
'467290':{'en': 'Tele2 Sverige'},
'467291':{'en': 'Tele2 Sverige'},
'467292':{'en': 'Tele2 Sverige'},
'467293':{'en': 'Tele2 Sverige'},
'467294':{'en': 'Tele2 Sverige'},
'467296':{'en': 'Telenor Sverige'},
'467297':{'en': 'Telenor Sverige'},
'467298':{'en': 'Telenor Sverige'},
'467299':{'en': 'Telenor Sverige'},
'46730':{'en': 'TeliaSonera'},
'467301':{'en': 'Maingate (Sierra Wireless)'},
'467310':{'en': 'Telenor Sverige'},
'467311':{'en': 'Maingate (Sierra Wireless)'},
'4673120':{'en': 'Telavox AB'},
'46731214':{'en': 'Voice Integrate'},
'46731215':{'en': 'COOLTEL APS'},
'46731216':{'en': 'HORISEN AG'},
'46731219':{'en': 'CLX Networks AB'},
'4673122':{'en': 'EU Tel AB'},
'4673123':{'en': '42 Telecom AB'},
'46731245':{'en': 'EU Tel AB'},
'46731247':{'en': 'Beepsend'},
'46731248':{'en': 'TELNESS AB'},
'4673125':{'en': 'Telenor Sverige'},
'4673126':{'en': 'Telenor Connexion'},
'4673127':{'en': 'SWEDFONENET AB'},
'4673128':{'en': 'SST Net Sverige AB'},
'4673129':{'en': 'SPIRIUS AB'},
'467313':{'en': 'iMEZ'},
'467314':{'en': 'Telenor Sverige'},
'467315':{'en': 'Telenor Sverige'},
'467316':{'en': 'Alltele Sverige'},
'46731706':{'en': 'Soatso AB'},
'4673171':{'en': 'Ventelo Sverige'},
'46731721':{'en': 'REWICOM SCANDINAVIA'},
'46731723':{'en': 'REWICOM SCANDINAVIA'},
'46731724':{'en': 'REWICOM SCANDINAVIA'},
'46731725':{'en': 'REWICOM SCANDINAVIA'},
'46731726':{'en': 'REWICOM SCANDINAVIA'},
'46731727':{'en': 'Beepsend'},
'46731728':{'en': 'Beepsend'},
'46731729':{'en': 'IPIFY LIMITED'},
'4673173':{'en': 'Svea Billing System'},
'4673174':{'en': 'Svea Billing System'},
'4673175':{'en': 'Svea Billing System'},
'4673176':{'en': 'ID Mobile'},
'4673177':{'en': 'SST Net Sverige AB'},
'4673178':{'en': 'SST Net Sverige AB'},
'4673179':{'en': 'SST Net Sverige AB'},
'467318':{'en': 'ACN Communications Sweden'},
'467319':{'en': 'TeliaSonera'},
'467320':{'en': 'Telenor Sverige'},
'467321':{'en': 'Tele2 Sverige'},
'467322':{'en': 'Tele2 Sverige'},
'467323':{'en': 'Telenor Sverige'},
'467324':{'en': 'Telenor Sverige'},
'467325':{'en': 'Telenor Sverige'},
'467326':{'en': 'Telenor Sverige'},
'467327':{'en': 'Ventelo Sverige'},
'467328':{'en': 'Telenor Sverige'},
'46733':{'en': 'Telenor Sverige'},
'467340':{'en': 'Telenor Sverige'},
'467341':{'en': 'Telenor Sverige'},
'467342':{'en': 'Telenor Sverige'},
'467343':{'en': 'Telenor Sverige'},
'467344':{'en': 'Telenor Sverige'},
'4673450':{'en': 'Weelia Enterprise A'},
'4673451':{'en': 'CELLIP AB'},
'46734520':{'en': 'Soatso AB'},
'46734521':{'en': 'Soatso AB'},
'46734522':{'en': 'Soatso AB'},
'46734523':{'en': 'Soatso AB'},
'46734524':{'en': 'Soatso AB'},
'46734525':{'en': 'Soatso AB'},
'46734527':{'en': 'Soatso AB'},
'46734528':{'en': 'Soatso AB'},
'46734529':{'en': 'Soatso AB'},
'4673454':{'en': 'Tele2 Sverige'},
'4673455':{'en': 'Viatel Sweden'},
'4673456':{'en': 'Svea Billing System'},
'4673457':{'en': 'Telenor Sverige'},
'4673458':{'en': 'Telenor Sverige'},
'4673459':{'en': '42 Telecom AB'},
'467346':{'en': 'Telenor Sverige'},
'4673460':{'en': 'Ventelo Sverige'},
'46734600':{'en': 'MERCURY INTERNATIONA'},
'46734601':{'en': 'MERCURY INTERNATIONA'},
'4673461':{'en': 'Ventelo Sverige'},
'46734700':{'en': '42 Telecom AB'},
'46734702':{'en': 'MOBIWEB LTD'},
'46734703':{'en': 'MOBIWEB LTD'},
'46734704':{'en': 'MOBIWEB LTD'},
'46734705':{'en': 'MOBIWEB LTD'},
'46734706':{'en': 'MOBIWEB LTD'},
'46734707':{'en': 'MOBIWEB LTD'},
'46734708':{'en': 'MOBIWEB LTD'},
'46734709':{'en': 'MOBIWEB LTD'},
'4673471':{'en': 'Telenor Sverige'},
'4673472':{'en': 'Telenor Sverige'},
'46734731':{'en': 'MERCURY INTERNATIONA'},
'46734732':{'en': 'MERCURY INTERNATIONA'},
'46734733':{'en': 'MERCURY INTERNATIONA'},
'46734734':{'en': 'MERCURY INTERNATIONA'},
'46734735':{'en': 'MERCURY INTERNATIONA'},
'46734736':{'en': 'MERCURY INTERNATIONA'},
'46734737':{'en': 'MERCURY INTERNATIONA'},
'46734738':{'en': 'MERCURY INTERNATIONA'},
'46734739':{'en': 'MERCURY INTERNATIONA'},
'46734740':{'en': 'Gotalandsnatet'},
'46734741':{'en': 'Soatso AB'},
'46734743':{'en': 'Soatso AB'},
'46734744':{'en': 'Soatso AB'},
'46734745':{'en': 'Beepsend'},
'46734747':{'en': 'Telavox AB'},
'4673475':{'en': 'Lycamobile Sweden'},
'4673476':{'en': 'Lycamobile Sweden'},
'4673477':{'en': 'Lycamobile Sweden'},
'4673478':{'en': 'Lycamobile Sweden'},
'4673479':{'en': 'Lycamobile Sweden'},
'467348':{'en': 'Lycamobile Sweden'},
'467349':{'en': 'Lycamobile Sweden'},
'467350':{'en': 'HI3G Access'},
'467351':{'en': 'HI3G Access'},
'467352':{'en': 'HI3G Access'},
'467353':{'en': 'HI3G Access'},
'467354':{'en': 'HI3G Access'},
'467355':{'en': 'Tele2 Sverige'},
'467356':{'en': 'Tele2 Sverige'},
'467357':{'en': 'Tele2 Sverige'},
'467358':{'en': 'Tele2 Sverige'},
'467359':{'en': 'Tele2 Sverige'},
'46736':{'en': 'Tele2 Sverige'},
'46737':{'en': 'Tele2 Sverige'},
'467380':{'en': 'TeliaSonera'},
'467381':{'en': 'TeliaSonera'},
'467382':{'en': 'TeliaSonera'},
'467383':{'en': 'TeliaSonera'},
'467384':{'en': 'TeliaSonera'},
'467385':{'en': 'Telenor Sverige'},
'4673860':{'en': 'Telenor Sverige'},
'4673861':{'en': 'Telenor Sverige'},
'4673862':{'en': 'Telenor Sverige'},
'46738631':{'en': 'Beepsend'},
'46738632':{'en': 'Beepsend'},
'46738634':{'en': 'MERCURY INTERNATIONA'},
'46738635':{'en': 'MERCURY INTERNATIONA'},
'46738636':{'en': 'MERCURY INTERNATIONA'},
'46738637':{'en': 'MERCURY INTERNATIONA'},
'46738638':{'en': 'MERCURY INTERNATIONA'},
'46738639':{'en': 'MERCURY INTERNATIONA'},
'46738640':{'en': 'EU Tel AB'},
'46738641':{'en': 'iCentrex Sweden AB'},
'46738642':{'en': '42 Telecom AB'},
'46738643':{'en': 'Beepsend'},
'46738644':{'en': 'Beepsend'},
'46738645':{'en': 'Beepsend'},
'46738647':{'en': 'EU Tel AB'},
'46738651':{'en': 'MERCURY INTERNATIONA'},
'46738652':{'en': 'MERCURY INTERNATIONA'},
'46738653':{'en': 'MERCURY INTERNATIONA'},
'46738654':{'en': 'MERCURY INTERNATIONA'},
'46738655':{'en': 'MERCURY INTERNATIONA'},
'46738656':{'en': 'MERCURY INTERNATIONA'},
'46738657':{'en': 'MERCURY INTERNATIONA'},
'46738658':{'en': 'MERCURY INTERNATIONA'},
'46738659':{'en': 'MERCURY INTERNATIONA'},
'4673866':{'en': 'Tele2 Sverige'},
'4673867':{'en': 'Tele2 Sverige'},
'4673868':{'en': 'Tele2 Sverige'},
'46738691':{'en': 'MERCURY INTERNATIONA'},
'46738692':{'en': 'MERCURY INTERNATIONA'},
'46738693':{'en': 'MERCURY INTERNATIONA'},
'46738694':{'en': 'MERCURY INTERNATIONA'},
'46738695':{'en': 'MERCURY INTERNATIONA'},
'46738696':{'en': 'MERCURY INTERNATIONA'},
'46738697':{'en': 'MERCURY INTERNATIONA'},
'46738698':{'en': 'MERCURY INTERNATIONA'},
'46738699':{'en': 'MERCURY INTERNATIONA'},
'467387':{'en': 'Tele2 Sverige'},
'467388':{'en': 'Telenor Sverige'},
'467389':{'en': 'Tele2 Sverige'},
'46739':{'en': 'Tele2 Sverige'},
'467600':{'en': 'HI3G Access'},
'467601':{'en': 'HI3G Access'},
'467602':{'en': 'HI3G Access'},
'467603':{'en': 'HI3G Access'},
'467604':{'en': 'HI3G Access'},
'467605':{'en': 'Tele2 Sverige'},
'467606':{'en': 'Tele2 Sverige'},
'467607':{'en': 'Tele2 Sverige'},
'467608':{'en': 'Tele2 Sverige'},
'467609':{'en': 'Tele2 Sverige'},
'467610':{'en': 'TeliaSonera'},
'467611':{'en': 'TeliaSonera'},
'467612':{'en': 'TeliaSonera'},
'467613':{'en': 'TeliaSonera'},
'467614':{'en': 'TeliaSonera'},
'467615':{'en': 'Lycamobile Sweden'},
'467616':{'en': 'HI3G Access'},
'467617':{'en': 'HI3G Access'},
'467618':{'en': 'HI3G Access'},
'467619':{'en': 'HI3G Access'},
'46762':{'en': 'Tele2 Sverige'},
'46763':{'en': 'HI3G Access'},
'467635':{'en': 'Telenor Sverige'},
'467636':{'en': 'Telenor Sverige'},
'467637':{'en': 'Telenor Sverige'},
'467638':{'en': 'Easy Telecom AB (BILDNINGSAGENTEN 559)'},
'467640':{'en': 'Tele2 Sverige'},
'467641':{'en': 'Tele2 Sverige'},
'467642':{'en': 'Tele2 Sverige'},
'467643':{'en': 'Lycamobile Sweden'},
'467644':{'en': 'Lycamobile Sweden'},
'467645':{'en': 'Lycamobile Sweden'},
'4676460':{'en': 'Lycamobile Sweden'},
'4676461':{'en': 'Lycamobile Sweden'},
'4676462':{'en': 'Lycamobile Sweden'},
'4676463':{'en': 'Lycamobile Sweden'},
'4676464':{'en': 'Lycamobile Sweden'},
'46764651':{'en': 'EU Tel AB'},
'46764652':{'en': 'MERCURY INTERNATIONA'},
'46764653':{'en': 'MERCURY INTERNATIONA'},
'46764654':{'en': 'MERCURY INTERNATIONA'},
'46764655':{'en': 'MERCURY INTERNATIONA'},
'46764656':{'en': 'MERCURY INTERNATIONA'},
'46764657':{'en': 'MERCURY INTERNATIONA'},
'46764658':{'en': 'MERCURY INTERNATIONA'},
'46764659':{'en': 'MERCURY INTERNATIONA'},
'4676466':{'en': 'Gotalandsnatet'},
'4676467':{'en': 'MERCURY INTERNATIONA'},
'4676468':{'en': 'MERCURY INTERNATIONA'},
'4676469':{'en': 'MERCURY INTERNATIONA'},
'467647':{'en': 'Tele2 Sverige'},
'4676478':{'en': 'WIFOG AB'},
'4676479':{'en': 'Beepsend'},
'467648':{'en': 'GLOBETOUCH AB'},
'46764901':{'en': 'MERCURY INTERNATIONA'},
'46764902':{'en': 'MERCURY INTERNATIONA'},
'46764903':{'en': 'MERCURY INTERNATIONA'},
'46764904':{'en': 'MERCURY INTERNATIONA'},
'46764905':{'en': 'MERCURY INTERNATIONA'},
'46764906':{'en': 'MERCURY INTERNATIONA'},
'46764907':{'en': 'MERCURY INTERNATIONA'},
'46764908':{'en': 'MERCURY INTERNATIONA'},
'46764909':{'en': 'MERCURY INTERNATIONA'},
'4676492':{'en': 'Telavox AB'},
'46764940':{'en': 'Tele2 Sverige'},
'46764942':{'en': 'IPIFY LIMITED'},
'46764943':{'en': 'IPIFY LIMITED'},
'46764944':{'en': 'IPIFY LIMITED'},
'46764945':{'en': 'IPIFY LIMITED'},
'46764946':{'en': 'IPIFY LIMITED'},
'46764947':{'en': 'IPIFY LIMITED'},
'46764948':{'en': 'IPIFY LIMITED'},
'46764949':{'en': 'IPIFY LIMITED'},
'4676495':{'en': 'Tele2 Sverige'},
'4676496':{'en': 'Tele2 Sverige'},
'46764981':{'en': 'MERCURY INTERNATIONA'},
'46764982':{'en': 'MERCURY INTERNATIONA'},
'46764983':{'en': 'MERCURY INTERNATIONA'},
'46764984':{'en': 'MERCURY INTERNATIONA'},
'46764985':{'en': 'MERCURY INTERNATIONA'},
'46764986':{'en': 'MERCURY INTERNATIONA'},
'46764987':{'en': 'MERCURY INTERNATIONA'},
'46764988':{'en': 'MERCURY INTERNATIONA'},
'46764989':{'en': 'MERCURY INTERNATIONA'},
'46764990':{'en': 'Gotalandsnatet'},
'46764991':{'en': 'MERCURY INTERNATIONA'},
'46764992':{'en': 'MERCURY INTERNATIONA'},
'46764993':{'en': 'MERCURY INTERNATIONA'},
'46764994':{'en': 'MERCURY INTERNATIONA'},
'46764995':{'en': 'MERCURY INTERNATIONA'},
'46764996':{'en': 'MERCURY INTERNATIONA'},
'46764997':{'en': 'MERCURY INTERNATIONA'},
'46764998':{'en': 'MERCURY INTERNATIONA'},
'46765':{'en': 'Tele2 Sverige'},
'467660':{'en': 'Telenor Sverige'},
'467661':{'en': 'Telenor Sverige'},
'467662':{'en': 'Telenor Sverige'},
'467663':{'en': 'Telenor Sverige'},
'467664':{'en': 'Telenor Sverige'},
'467665':{'en': 'Tele2 Sverige'},
'4676660':{'en': 'NETETT SVERIGE AB (AINMT Sverige)'},
'4676661':{'en': 'NETETT SVERIGE AB (AINMT Sverige)'},
'4676662':{'en': 'NETETT SVERIGE AB (AINMT Sverige)'},
'4676663':{'en': 'NETETT SVERIGE AB (AINMT Sverige)'},
'4676664':{'en': 'NETETT SVERIGE AB (AINMT Sverige)'},
'4676665':{'en': 'NETETT SVERIGE AB (AINMT Sverige)'},
'4676666':{'en': u('\u00d6RETEL AB')},
'4676667':{'en': 'Unicorn Telecom'},
'4676668':{'en': 'MERCURY INTERNATIONA'},
'46766696':{'en': 'Telavox AB'},
'46766697':{'en': 'Telavox AB'},
'46766698':{'en': 'Telavox AB'},
'4676670':{'en': 'Svea Billing System'},
'4676671':{'en': 'Svea Billing System'},
'4676672':{'en': 'Svea Billing System'},
'4676673':{'en': 'Svea Billing System'},
'4676674':{'en': 'Svea Billing System'},
'46766750':{'en': '42 Telecom AB'},
'46766753':{'en': 'Beepsend'},
'46766754':{'en': 'Beepsend'},
'46766760':{'en': 'Voice Integrate'},
'4676677':{'en': 'Telavox AB'},
'4676678':{'en': 'SWEDFONENET AB'},
'46766791':{'en': 'Beepsend'},
'46766798':{'en': 'Beepsend'},
'46766799':{'en': '42 Telecom AB'},
'467668':{'en': 'Tele2 Sverige'},
'46766901':{'en': 'MERCURY INTERNATIONA'},
'46766902':{'en': 'MERCURY INTERNATIONA'},
'46766903':{'en': 'MERCURY INTERNATIONA'},
'46766904':{'en': 'MERCURY INTERNATIONA'},
'46766905':{'en': 'MERCURY INTERNATIONA'},
'46766906':{'en': 'MERCURY INTERNATIONA'},
'46766907':{'en': 'MERCURY INTERNATIONA'},
'46766908':{'en': 'MERCURY INTERNATIONA'},
'46766909':{'en': 'MERCURY INTERNATIONA'},
'46766911':{'en': 'MERCURY INTERNATIONA'},
'46766912':{'en': 'MERCURY INTERNATIONA'},
'46766913':{'en': 'MERCURY INTERNATIONA'},
'46766914':{'en': 'MERCURY INTERNATIONA'},
'46766915':{'en': 'MERCURY INTERNATIONA'},
'46766916':{'en': 'MERCURY INTERNATIONA'},
'46766917':{'en': 'MERCURY INTERNATIONA'},
'46766918':{'en': 'MERCURY INTERNATIONA'},
'46766919':{'en': 'MERCURY INTERNATIONA'},
'4676692':{'en': 'Voxbone'},
'46766930':{'en': 'MERCURY INTERNATIONA'},
'46766931':{'en': 'Beepsend'},
'46766932':{'en': 'IPIFY LIMITED'},
'46766933':{'en': 'Connectel AB'},
'46766934':{'en': 'IPIFY LIMITED'},
'46766935':{'en': 'Beepsend'},
'46766936':{'en': 'IPIFY LIMITED'},
'46766937':{'en': 'IPIFY LIMITED'},
'46766938':{'en': 'IPIFY LIMITED'},
'4676694':{'en': '42 Telecom AB'},
'4676695':{'en': 'Tele2 Sverige'},
'4676696':{'en': 'Tele2 Sverige'},
'4676697':{'en': 'Tele2 Sverige'},
'4676698':{'en': 'Tele2 Sverige'},
'4676699':{'en': 'Tele2 Sverige'},
'467670':{'en': 'Tele2 Sverige'},
'467671':{'en': 'Tele2 Sverige'},
'4676720':{'en': 'Tele2 Sverige'},
'4676721':{'en': 'Tele2 Sverige'},
'4676722':{'en': 'Tele2 Sverige'},
'4676723':{'en': 'Tele2 Sverige'},
'4676724':{'en': 'Tele2 Sverige'},
'4676725':{'en': 'Tele2 Sverige'},
'46767260':{'en': 'EU Tel AB'},
'46767261':{'en': 'Beepsend'},
'46767262':{'en': 'Beepsend'},
'46767265':{'en': 'HORISEN AG'},
'46767266':{'en': 'Beepsend'},
'46767268':{'en': 'Rebtel Networks'},
'4676727':{'en': 'Telenor Sverige'},
'467674':{'en': 'Lycamobile Sweden'},
'467675':{'en': 'Lycamobile Sweden'},
'467676':{'en': 'TeliaSonera'},
'467677':{'en': 'TeliaSonera'},
'467678':{'en': 'TeliaSonera'},
'467679':{'en': 'TeliaSonera'},
'467680':{'en': 'TeliaSonera'},
'467681':{'en': 'TeliaSonera'},
'467682':{'en': 'TeliaSonera'},
'467683':{'en': 'TeliaSonera'},
'467684':{'en': 'TeliaSonera'},
'467685':{'en': 'Telenor Sverige'},
'467686':{'en': 'Telenor Sverige'},
'467687':{'en': 'Telenor Sverige'},
'467688':{'en': 'Telenor Sverige'},
'467689':{'en': 'Telenor Sverige'},
'467690':{'en': 'Tele2 Sverige'},
'467691':{'en': 'Tele2 Sverige'},
'467692':{'en': 'Tele2 Sverige'},
'467693':{'en': 'Tele2 Sverige'},
'467694':{'en': 'Tele2 Sverige'},
'467695':{'en': 'Lycamobile Sweden'},
'467696':{'en': 'Lycamobile Sweden'},
'467697':{'en': 'Lycamobile Sweden'},
'467698':{'en': 'TeliaSonera'},
'467699':{'en': 'TeliaSonera'},
'4679000':{'en': '0700 LTD'},
'4679001':{'en': 'EU Tel AB'},
'4679002':{'en': '0700 LTD'},
'4679003':{'en': '0700 LTD'},
'4679004':{'en': '0700 LTD'},
'46790050':{'en': 'Telenor Sverige'},
'46790051':{'en': 'Telenor Sverige'},
'46790052':{'en': 'Telenor Sverige'},
'46790053':{'en': 'Telenor Sverige'},
'46790054':{'en': 'Telenor Sverige'},
'46790055':{'en': 'Telenor Sverige'},
'46790056':{'en': 'Telenor Sverige'},
'46790057':{'en': 'Telenor Sverige'},
'4679006':{'en': 'Telavox AB'},
'4679007':{'en': 'FONIA AB'},
'4679008':{'en': 'Voice Integrate'},
'4679009':{'en': 'BIZTELCO SVERIGE AB'},
'467901':{'en': 'Tele2 Sverige'},
'467902':{'en': 'Tele2 Sverige'},
'467903':{'en': 'Tele2 Sverige'},
'467904':{'en': 'Tele2 Sverige'},
'467905':{'en': 'Tele2 Sverige'},
'467906':{'en': 'Tele2 Sverige'},
'467907':{'en': 'Tele2 Sverige'},
'467908':{'en': 'Tele2 Sverige'},
'467909':{'en': 'Tele2 Sverige'},
'467910':{'en': 'TELL ESS AB'},
'467930':{'en': 'HI3G Access'},
'467931':{'en': 'HI3G Access'},
'467932':{'en': 'HI3G Access'},
'467933':{'en': 'HI3G Access'},
'467934':{'en': 'HI3G Access'},
'467950':{'en': 'JUNYVERSE AB'},
'467951':{'en': 'JUNYVERSE AB'},
'467952':{'en': 'JUNYVERSE AB'},
'467953':{'en': 'JUNYVERSE AB'},
'467954':{'en': 'JUNYVERSE AB'},
'4679580':{'en': 'Borderlight'},
'4679581':{'en': 'Borderlight'},
'4679585':{'en': 'Telavox AB'},
'467997':{'en': 'Telenor Sverige'},
'47400':{'en': 'telenor norge'},
'474000':{'en': 'telia'},
'474001':{'en': 'telia'},
'474002':{'en': 'telia'},
'474003':{'en': 'telia'},
'47401':{'en': 'telenor norge'},
'474010':{'en': 'telia'},
'474011':{'en': 'telia'},
'474014':{'en': 'nextgentel'},
'474020':{'en': 'telia'},
'474021':{'en': 'telia'},
'474022':{'en': 'telenor norge'},
'474023':{'en': 'telia'},
'474024':{'en': 'telia'},
'474025':{'en': 'sierra wireless'},
'474026':{'en': 'sierra wireless'},
'474027':{'en': 'sierra wireless'},
'474028':{'en': 'telenor norge'},
'474029':{'en': 'telia'},
'47403':{'en': 'telia'},
'474035':{'en': 'sierra wireless'},
'474036':{'en': 'sierra wireless'},
'474037':{'en': 'sierra wireless'},
'47404':{'en': 'telia'},
'47405':{'en': 'telia'},
'474060':{'en': 'telia'},
'474061':{'en': 'telia'},
'474062':{'en': 'telia'},
'474063':{'en': 'telia'},
'474064':{'en': 'telia'},
'474065':{'en': 'telia telecom solution'},
'474067':{'en': 'nextgentel'},
'474068':{'en': 'telenor norge'},
'474069':{'en': 'telenor norge'},
'47407':{'en': 'telia'},
'47408':{'en': 'telenor norge'},
'474080':{'en': 'telia telecom solution'},
'474081':{'en': 'telia telecom solution'},
'4740820':{'en': 'telia telecom solution'},
'4740821':{'en': 'telia telecom solution'},
'4740822':{'en': 'telia telecom solution'},
'4740823':{'en': 'telia telecom solution'},
'4740824':{'en': 'telia telecom solution'},
'47409':{'en': 'lyca mobile'},
'474090':{'en': 'telia telecom solution'},
'474091':{'en': 'telia telecom solution'},
'4740920':{'en': 'telia telecom solution'},
'4740921':{'en': 'telia telecom solution'},
'4740922':{'en': 'telia telecom solution'},
'4740923':{'en': 'telia telecom solution'},
'4740924':{'en': 'telia telecom solution'},
'4740925':{'en': 'telenor norge'},
'4740926':{'en': 'telenor norge'},
'4740927':{'en': 'telenor norge'},
'4740928':{'en': 'telenor norge'},
'4740929':{'en': 'telenor norge'},
'474093':{'en': 'telenor norge'},
'4741':{'en': 'telenor norge'},
'474100':{'en': 'telia'},
'474101':{'en': 'telia'},
'474104':{'en': 'telia'},
'474106':{'en': 'telia'},
'474107':{'en': 'telia'},
'474110':{'en': 'telia'},
'474111':{'en': 'chilimobil'},
'474112':{'en': 'chilimobil'},
'474113':{'en': 'chilimobil'},
'474114':{'en': 'telia'},
'474115':{'en': 'chilimobil'},
'474116':{'en': 'chilimobil'},
'474117':{'en': 'telia'},
'474118':{'en': 'telia'},
'474119':{'en': 'telia'},
'47412':{'en': 'telia'},
'47413':{'en': 'telia'},
'4745':{'en': 'telia'},
'47453':{'en': 'telenor norge'},
'474536':{'en': 'nkom (nasjonal kommunikasjonsmyndighet)'},
'474537':{'en': 'erate'},
'474538':{'en': 'erate'},
'47455':{'en': 'lyca mobile'},
'47458':{'en': 'telenor norge'},
'474590':{'en': 'telenor norge'},
'474592':{'en': 'lyca mobile'},
'474595':{'en': 'telenor norge'},
'474596':{'en': 'telenor norge'},
'474598':{'en': 'telenor norge'},
'474599':{'en': 'telenor norge'},
'47460':{'en': 'telenor norge'},
'47461':{'en': 'chilimobil'},
'474610':{'en': 'telenor norge'},
'474617':{'en': 'telenor norge'},
'474618':{'en': 'telenor norge'},
'474619':{'en': 'telenor norge'},
'47462':{'en': 'telia'},
'474620':{'en': 'telenor norge'},
'474628':{'en': 'erate'},
'474629':{'en': 'erate'},
'47463':{'en': 'telia'},
'47464':{'en': 'NetCom'},
'474650':{'en': 'telia'},
'474651':{'en': 'ice norge'},
'474652':{'en': 'ice norge'},
'474653':{'en': 'ice norge'},
'474654':{'en': 'telia'},
'474655':{'en': 'telia'},
'474656':{'en': 'telia'},
'474657':{'en': 'telia'},
'474658':{'en': 'telia'},
'474659':{'en': 'telia'},
'47466':{'en': 'telia'},
'474666':{'en': 'telenor norge'},
'474667':{'en': 'telenor norge'},
'474670':{'en': 'telia'},
'474671':{'en': 'lyca mobile'},
'474672':{'en': 'lyca mobile'},
'474674':{'en': 'telia'},
'474675':{'en': 'telia'},
'474676':{'en': 'telia'},
'474677':{'en': 'telia'},
'474678':{'en': 'telia'},
'474679':{'en': 'telia'},
'47468':{'en': 'telenor norge'},
'474690':{'en': 'telenor norge'},
'474691':{'en': 'telenor norge'},
'474692':{'en': 'telenor norge'},
'474693':{'en': 'telenor norge'},
'474694':{'en': 'telenor norge'},
'474695':{'en': 'telenor norge'},
'474696':{'en': 'telenor norge'},
'474697':{'en': 'telia'},
'474698':{'en': 'telenor norge'},
'47470':{'en': 'telenor norge'},
'474710':{'en': 'telenor norge'},
'474711':{'en': 'telenor norge'},
'474712':{'en': 'telenor norge'},
'474713':{'en': 'telia'},
'474714':{'en': 'telia'},
'474715':{'en': 'telia'},
'474716':{'en': 'telia'},
'474717':{'en': 'telia'},
'474718':{'en': 'chilimobil'},
'474719':{'en': 'chilimobil'},
'47472':{'en': 'telia'},
'47473':{'en': 'telia'},
'47474':{'en': 'telia'},
'474740':{'en': 'telenor norge'},
'474741':{'en': 'telenor norge'},
'474742':{'en': 'telenor norge'},
'474743':{'en': 'telenor norge'},
'47475':{'en': 'altibox'},
'474750':{'en': 'telenor norge'},
'474751':{'en': 'telenor norge'},
'47476':{'en': 'telenor norge'},
'474769':{'en': 'telia'},
'47477':{'en': 'telia'},
'474770':{'en': 'telenor norge'},
'474771':{'en': 'telenor norge'},
'474775':{'en': 'telenor norge'},
'474776':{'en': 'telenor norge'},
'47478':{'en': 'telenor norge'},
'47479':{'en': 'telia'},
'474790':{'en': 'telenor norge'},
'474798':{'en': 'telenor norge'},
'474799':{'en': 'telenor norge'},
'47480':{'en': 'telenor norge'},
'47481':{'en': 'telenor norge'},
'47482':{'en': 'telenor norge'},
'474830':{'en': 'telenor norge'},
'474831':{'en': 'telenor norge'},
'474832':{'en': 'telenor norge'},
'474833':{'en': 'telia'},
'474834':{'en': 'telia'},
'474835':{'en': 'telia'},
'474836':{'en': 'telia'},
'474838':{'en': 'ice norge'},
'474839':{'en': 'ice norge'},
'47484':{'en': 'telia'},
'474841':{'en': 'telenor norge'},
'474842':{'en': 'telenor norge'},
'474848':{'en': 'erate'},
'474849':{'en': 'erate'},
'474850':{'en': 'telia'},
'474851':{'en': 'nextgentel'},
'474858':{'en': 'telenor norge'},
'474859':{'en': 'erate'},
'474860':{'en': 'telia'},
'474861':{'en': 'telia'},
'474862':{'en': 'telia'},
'474863':{'en': 'telia'},
'474864':{'en': 'telia'},
'474865':{'en': 'telia'},
'474866':{'en': 'telia'},
'474867':{'en': 'telia'},
'474868':{'en': 'telia'},
'474884':{'en': 'telenor norge'},
'474885':{'en': 'telenor norge'},
'474886':{'en': 'telia'},
'474888':{'en': 'telia'},
'474889':{'en': 'telia'},
'474890':{'en': 'telenor norge'},
'474891':{'en': 'telenor norge'},
'474892':{'en': 'telenor norge'},
'474893':{'en': 'telia'},
'474894':{'en': 'telenor norge'},
'474895':{'en': 'telia'},
'474896':{'en': 'telenor norge'},
'474898':{'en': 'telenor norge'},
'474899':{'en': 'telia'},
'47591':{'en': 'telenor norge'},
'4790':{'en': 'telenor norge'},
'479042':{'en': 'svea billing services'},
'479043':{'en': 'svea billing services'},
'479044':{'en': 'svea billing services'},
'479048':{'en': 'telavox'},
'479049':{'en': 'telavox'},
'4791':{'en': 'telenor norge'},
'479120':{'en': 'chilimobil'},
'479121':{'en': 'chilimobil'},
'479122':{'en': 'chilimobil'},
'479123':{'en': 'chilimobil'},
'479125':{'en': 'lyca mobile'},
'479126':{'en': 'lyca mobile'},
'479127':{'en': 'lyca mobile'},
'479128':{'en': 'lyca mobile'},
'479129':{'en': 'lyca mobile'},
'4792':{'en': 'telia'},
'479218':{'en': 'telenor norge'},
'479219':{'en': 'telenor norge'},
'479236':{'en': 'telenor norge'},
'479238':{'en': 'telenor norge'},
'479239':{'en': 'telenor norge'},
'479258':{'en': 'telenor norge'},
'479259':{'en': 'telenor norge'},
'47927':{'en': 'telenor norge'},
'47929':{'en': 'telenor norge'},
'47930':{'en': 'telia'},
'479310':{'en': 'telenor norge'},
'479311':{'en': 'telenor norge'},
'479312':{'en': 'telenor norge'},
'479313':{'en': 'telenor norge'},
'479314':{'en': 'telenor norge'},
'479315':{'en': 'telenor norge'},
'479316':{'en': 'telenor norge'},
'479318':{'en': 'telenor norge'},
'479319':{'en': 'telenor norge'},
'47932':{'en': 'telia'},
'479330':{'en': 'telenor norge'},
'479331':{'en': 'telenor norge'},
'479332':{'en': 'telenor norge'},
'479333':{'en': 'telenor norge'},
'479334':{'en': 'telenor norge'},
'479335':{'en': 'telenor norge'},
'479336':{'en': 'telenor norge'},
'479337':{'en': 'telia'},
'479338':{'en': 'telenor norge'},
'479339':{'en': 'telenor norge'},
'47934':{'en': 'telia'},
'479350':{'en': 'telenor norge'},
'479351':{'en': 'telenor norge'},
'479352':{'en': 'telenor norge'},
'479353':{'en': 'telenor norge'},
'479354':{'en': 'telenor norge'},
'479355':{'en': 'telenor norge'},
'479356':{'en': 'telenor norge'},
'479357':{'en': 'telia'},
'479358':{'en': 'telenor norge'},
'479359':{'en': 'telenor norge'},
'47936':{'en': 'telia'},
'479370':{'en': 'telenor norge'},
'479371':{'en': 'telenor norge'},
'479372':{'en': 'telenor norge'},
'479373':{'en': 'telenor norge'},
'479374':{'en': 'telenor norge'},
'479375':{'en': 'telenor norge'},
'479376':{'en': 'telenor norge'},
'479377':{'en': 'telia'},
'479378':{'en': 'telenor norge'},
'479379':{'en': 'telenor norge'},
'47938':{'en': 'telia'},
'47939':{'en': 'telia'},
'479390':{'en': 'telenor norge'},
'479400':{'en': 'telia'},
'479401':{'en': 'telia'},
'479402':{'en': 'telia'},
'479403':{'en': 'telenor norge'},
'479404':{'en': 'com4'},
'479405':{'en': 'telenor norge'},
'479406':{'en': 'telenor norge'},
'479407':{'en': 'telenor norge'},
'479408':{'en': 'ice norge'},
'479409':{'en': 'ice norge'},
'47941':{'en': 'telenor norge'},
'479410':{'en': 'telia'},
'479411':{'en': 'telia'},
'479412':{'en': 'telia'},
'47942':{'en': 'telia'},
'47943':{'en': 'telenor norge'},
'479440':{'en': 'telenor norge'},
'479441':{'en': 'telenor norge'},
'479442':{'en': 'telia'},
'479443':{'en': 'telia'},
'479444':{'en': 'telenor norge'},
'479445':{'en': 'telenor norge'},
'479446':{'en': 'telenor norge'},
'479447':{'en': 'telia'},
'479448':{'en': 'telia'},
'479449':{'en': 'telia'},
'479450':{'en': 'telia telecom solution'},
'479451':{'en': 'telia telecom solution'},
'479452':{'en': 'telia telecom solution'},
'479453':{'en': 'telia telecom solution'},
'479454':{'en': 'telia telecom solution'},
'479471':{'en': 'lyca mobile'},
'479472':{'en': 'lyca mobile'},
'479473':{'en': 'lyca mobile'},
'479474':{'en': 'telenor norge'},
'479475':{'en': 'telenor norge'},
'479476':{'en': 'telenor norge'},
'479477':{'en': 'telenor norge'},
'479478':{'en': 'telenor norge'},
'479479':{'en': 'telenor norge'},
'47948':{'en': 'telenor norge'},
'47949':{'en': 'telenor norge'},
'479499':{'en': 'telia'},
'4795':{'en': 'telenor norge'},
'479600':{'en': 'phonect'},
'479601':{'en': 'telenor norge'},
'479604':{'en': 'telenor norge'},
'479609':{'en': 'telenor norge'},
'47961':{'en': 'telenor norge'},
'47962':{'en': 'telenor norge'},
'47965':{'en': 'telenor norge'},
'479660':{'en': 'erate'},
'479661':{'en': 'erate'},
'479662':{'en': 'erate'},
'479663':{'en': 'erate'},
'479664':{'en': 'erate'},
'479665':{'en': 'telia'},
'479666':{'en': 'telia'},
'479667':{'en': 'telia'},
'479668':{'en': 'telia'},
'479669':{'en': 'telia'},
'479670':{'en': 'telia'},
'479671':{'en': 'telia'},
'479672':{'en': 'telia'},
'479673':{'en': 'telia'},
'479674':{'en': 'telia'},
'479675':{'en': 'telia'},
'479679':{'en': 'telenor norge'},
'47968':{'en': 'telia'},
'479689':{'en': 'telenor norge'},
'479690':{'en': 'erate'},
'479691':{'en': 'erate'},
'479692':{'en': 'erate'},
'479693':{'en': 'telenor norge'},
'479694':{'en': 'telia'},
'479695':{'en': 'lyca mobile'},
'479696':{'en': 'lyca mobile'},
'479697':{'en': 'lyca mobile'},
'479698':{'en': 'lyca mobile'},
'479699':{'en': 'lyca mobile'},
'4797':{'en': 'telenor norge'},
'479730':{'en': 'ice norge'},
'479731':{'en': 'ice norge'},
'479735':{'en': 'lyca mobile'},
'479736':{'en': 'lyca mobile'},
'479737':{'en': 'lyca mobile'},
'479738':{'en': 'lyca mobile'},
'479739':{'en': 'lyca mobile'},
'47978':{'en': 'telia'},
'479790':{'en': 'telia'},
'479791':{'en': 'telia'},
'479792':{'en': 'telia'},
'479793':{'en': 'telia'},
'479794':{'en': 'telia'},
'47980':{'en': 'telia'},
'47981':{'en': 'telia'},
'47982':{'en': 'telia'},
'47983':{'en': 'telia'},
'479838':{'en': 'telenor norge'},
'479839':{'en': 'telenor norge'},
'47984':{'en': 'telia'},
'47985':{'en': 'telenor norge'},
'479854':{'en': 'telia'},
'47986':{'en': 'telia'},
'479870':{'en': 'kvantel'},
'479876':{'en': 'telia'},
'479877':{'en': 'chilimobil'},
'47988':{'en': 'telia'},
'47989':{'en': 'telenor norge'},
'479890':{'en': 'telia'},
'479899':{'en': 'telia'},
'47990':{'en': 'telenor norge'},
'479908':{'en': 'telia'},
'479909':{'en': 'telia'},
'47991':{'en': 'telenor norge'},
'47992':{'en': 'telenor norge'},
'47993':{'en': 'telenor norge'},
'47994':{'en': 'telenor norge'},
'47995':{'en': 'telenor norge'},
'47996':{'en': 'telenor norge'},
'479967':{'en': 'telia'},
'479968':{'en': 'telia'},
'47997':{'en': 'telenor norge'},
'479980':{'en': 'telenor norge'},
'479981':{'en': 'telenor norge'},
'479982':{'en': 'telenor norge'},
'479983':{'en': 'telenor norge'},
'479984':{'en': 'telenor norge'},
'479985':{'en': 'telia'},
'479986':{'en': 'telia'},
'479987':{'en': 'telia'},
'479988':{'en': 'telia'},
'479989':{'en': 'telia'},
'4845':{'en': 'Rezerwa Prezesa UKE'},
'48450':{'en': 'Play'},
'484590':{'en': 'Play'},
'4845910':{'en': 'Play'},
'4845911':{'en': 'Play'},
'4845912':{'en': 'Play'},
'4845913':{'en': 'Play'},
'4845914':{'en': 'Play'},
'4845920':{'en': 'SIA Ntel Solutions'},
'484593':{'en': 'Play'},
'4845945':{'en': 'Plus'},
'484595':{'en': 'Plus'},
'4845950':{'en': 'SIA Ntel Solutions'},
'4845957':{'en': 'BSG ESTONIA OU'},
'4845958':{'en': 'TELESTRADA S.A.'},
'4845959':{'en': 'TELESTRADA S.A.'},
'484598':{'en': 'Plus'},
'4850':{'en': 'Orange'},
'4851':{'en': 'Orange'},
'4853':{'en': 'Play'},
'48532':{'en': 'T-Mobile'},
'485366':{'en': 'Plus'},
'48538':{'en': 'T-Mobile'},
'48539':{'en': 'T-Mobile'},
'4857':{'en': 'Play'},
'48571':{'en': 'Orange'},
'485717':{'en': 'Rezerwa Prezesa UKE'},
'485718':{'en': 'Rezerwa Prezesa UKE'},
'485719':{'en': 'Rezerwa Prezesa UKE'},
'48572':{'en': 'Orange'},
'48573':{'en': 'Orange'},
'485735':{'en': 'Rezerwa Prezesa UKE'},
'485736':{'en': 'Rezerwa Prezesa UKE'},
'485737':{'en': 'Rezerwa Prezesa UKE'},
'485738':{'en': 'Rezerwa Prezesa UKE'},
'485791':{'en': 'Plus'},
'485792':{'en': 'Plus'},
'485793':{'en': 'Plus'},
'4857941':{'en': 'Messagebird B.V.'},
'4857942':{'en': 'SIA NetBalt'},
'4857946':{'en': 'Plus'},
'4857947':{'en': 'Plus'},
'4857948':{'en': 'SIA Ntel Solutions'},
'4857949':{'en': 'Plus'},
'4857950':{'en': 'Plus'},
'4857953':{'en': 'SIA NetBalt'},
'4857958':{'en': 'NIMBUSFIVE GmbH'},
'485797':{'en': 'Plus'},
'48600':{'en': 'T-Mobile'},
'48601':{'en': 'Plus'},
'48602':{'en': 'T-Mobile'},
'48603':{'en': 'Plus'},
'48604':{'en': 'T-Mobile'},
'48605':{'en': 'Plus'},
'48606':{'en': 'T-Mobile'},
'48607':{'en': 'Plus'},
'48608':{'en': 'T-Mobile'},
'48609':{'en': 'Plus'},
'48660':{'en': 'T-Mobile'},
'48661':{'en': 'Plus'},
'48662':{'en': 'T-Mobile'},
'48663':{'en': 'Plus'},
'48664':{'en': 'T-Mobile'},
'48665':{'en': 'Plus'},
'48666':{'en': 'T-Mobile'},
'486666':{'en': 'Play'},
'48667':{'en': 'Plus'},
'48668':{'en': 'T-Mobile'},
'48669':{'en': 'Plus'},
'48690':{'en': 'Orange'},
'486900':{'en': 'Play'},
'486907':{'en': 'Play'},
'486908':{'en': 'Play'},
'486909':{'en': 'Play'},
'48691':{'en': 'Plus'},
'48692':{'en': 'T-Mobile'},
'48693':{'en': 'Plus'},
'48694':{'en': 'T-Mobile'},
'48695':{'en': 'Plus'},
'48696':{'en': 'T-Mobile'},
'48697':{'en': 'Plus'},
'48698':{'en': 'T-Mobile'},
'48699':{'en': 'Plus'},
'4869901':{'en': 'AMD Telecom S.A.'},
'4869922':{'en': 'Play'},
'4869950':{'en': 'AMD Telecom S.A.'},
'4869951':{'en': 'Mobiledata Sp. z o.o.'},
'4869952':{'en': 'Mobiledata Sp. z o.o.'},
'4869953':{'en': 'Mobiledata Sp. z o.o.'},
'4869954':{'en': 'Mobiledata Sp. z o.o.'},
'4869955':{'en': 'Mobiledata Sp. z o.o.'},
'4869956':{'en': 'Twilio Ireland Limited'},
'4869957':{'en': 'Softelnet S.A. Sp. k.'},
'4869958':{'en': 'Rezerwa Prezesa UKE'},
'4869959':{'en': 'Move Telecom S.A.'},
'4869960':{'en': 'Play'},
'4869970':{'en': 'Play'},
'4869974':{'en': 'Compatel Limited'},
'4869978':{'en': 'VOXBONE SA'},
'4869979':{'en': 'Play'},
'486998':{'en': 'Play'},
'4872':{'en': 'Plus'},
'487208':{'en': 'Play'},
'487271':{'en': 'Nordisk'},
'487272':{'en': 'T-Mobile'},
'487273':{'en': 'T-Mobile'},
'48728':{'en': 'T-Mobile'},
'487290':{'en': 'Play'},
'487291':{'en': 'Play'},
'4872970':{'en': 'AMD Telecom S.A.'},
'4872972':{'en': 'Compatel Limited'},
'4872973':{'en': 'Play'},
'4872974':{'en': 'Play'},
'4872975':{'en': 'Rezerwa Prezesa UKE'},
'4872977':{'en': 'INTERNETIA Sp. o.o.'},
'4872978':{'en': 'Play'},
'4872979':{'en': 'Play'},
'4872980':{'en': 'Play'},
'4872981':{'en': 'Play'},
'4872982':{'en': 'Play'},
'4872983':{'en': 'Rezerwa Prezesa UKE'},
'4872984':{'en': 'Rezerwa Prezesa UKE'},
'4872985':{'en': 'Rezerwa Prezesa UKE'},
'4872986':{'en': 'Rezerwa Prezesa UKE'},
'4872987':{'en': 'Premium Mobile SA'},
'4872988':{'en': 'Premium Mobile SA'},
'4872989':{'en': 'Premium Mobile SA'},
'4872990':{'en': 'TELCO LEADERS LTD'},
'48730':{'en': 'Play'},
'48731':{'en': 'Play'},
'48732':{'en': 'Play'},
'48733':{'en': 'Play'},
'48734':{'en': 'T-Mobile'},
'48735':{'en': 'T-Mobile'},
'48736':{'en': 'T-Mobile'},
'487360':{'en': 'Play'},
'487367':{'en': 'Play'},
'487368':{'en': 'Play'},
'487369':{'en': 'Play'},
'48737':{'en': 'Play'},
'487370':{'en': 'Plus'},
'487371':{'en': 'Plus'},
'487372':{'en': 'Plus'},
'48738':{'en': 'PKP Polskie Linie Kolejowe S.A.'},
'48739':{'en': 'Plus'},
'487390':{'en': 'Play'},
'487391':{'en': 'Play'},
'487392':{'en': 'Play'},
'4873930':{'en': 'Play'},
'4873990':{'en': 'Play'},
'4873991':{'en': 'AGILE TELECOM POLAND'},
'4873992':{'en': 'MobiWeb Telecom Limited'},
'4873993':{'en': 'SIA NetBalt'},
'4873997':{'en': 'Play'},
'4873998':{'en': 'Play'},
'4873999':{'en': 'Play'},
'487800':{'en': 'Orange'},
'487801':{'en': 'Orange'},
'487802':{'en': 'Play'},
'4878020':{'en': 'Plus'},
'4878025':{'en': 'Interactive Digital Media GmbH'},
'4878026':{'en': 'SIA NetBalt'},
'4878029':{'en': 'SMSHIGHWAY LIMITED'},
'487803':{'en': 'T-Mobile'},
'487804':{'en': 'Rezerwa Prezesa UKE'},
'4878040':{'en': 'Plus'},
'487805':{'en': 'Orange'},
'487806':{'en': 'Orange'},
'487807':{'en': 'Play'},
'487808':{'en': 'Play'},
'487809':{'en': 'Rezerwa Prezesa UKE'},
'48781':{'en': 'Plus'},
'48782':{'en': 'Plus'},
'48783':{'en': 'Plus'},
'48784':{'en': 'T-Mobile'},
'48785':{'en': 'Plus'},
'487860':{'en': 'Plus'},
'4878607':{'en': 'Play'},
'4878608':{'en': 'Play'},
'487861':{'en': 'Play'},
'487862':{'en': 'Play'},
'487863':{'en': 'Play'},
'487864':{'en': 'Play'},
'487865':{'en': 'Rezerwa Prezesa UKE'},
'487866':{'en': 'Rezerwa Prezesa UKE'},
'487867':{'en': 'Rezerwa Prezesa UKE'},
'4878678':{'en': 'Play'},
'487868':{'en': 'Orange'},
'487869':{'en': 'Orange'},
'48787':{'en': 'T-Mobile'},
'48788':{'en': 'T-Mobile'},
'487890':{'en': 'Orange'},
'487891':{'en': 'Orange'},
'487892':{'en': 'Orange'},
'487893':{'en': 'Orange'},
'487894':{'en': 'Orange'},
'487895':{'en': 'Plus'},
'487896':{'en': 'Plus'},
'487897':{'en': 'Plus'},
'487898':{'en': 'Plus'},
'487899':{'en': 'Plus'},
'4879':{'en': 'Play'},
'487951':{'en': 'T-Mobile'},
'487952':{'en': 'T-Mobile'},
'487953':{'en': 'T-Mobile'},
'487954':{'en': 'T-Mobile'},
'487955':{'en': 'T-Mobile'},
'48797':{'en': 'Orange'},
'48798':{'en': 'Orange'},
'487990':{'en': 'Orange'},
'487996':{'en': 'Orange'},
'48880':{'en': 'T-Mobile'},
'48881':{'en': 'Play'},
'488810':{'en': 'T-Mobile'},
'488811':{'en': 'Plus'},
'488818':{'en': 'T-Mobile'},
'488819':{'en': 'T-Mobile'},
'48882':{'en': 'T-Mobile'},
'48883':{'en': 'Play'},
'488833':{'en': 'T-Mobile'},
'488838':{'en': 'T-Mobile'},
'48884':{'en': 'Play'},
'488841':{'en': 'T-Mobile'},
'488842':{'en': 'T-Mobile'},
'488844':{'en': 'Plus'},
'488845':{'en': 'Rezerwa Prezesa UKE'},
'48885':{'en': 'Plus'},
'48886':{'en': 'T-Mobile'},
'48887':{'en': 'Plus'},
'48888':{'en': 'T-Mobile'},
'48889':{'en': 'T-Mobile'},
'4915020':{'en': 'Interactive digital media'},
'4915050':{'en': 'NAKA AG'},
'4915080':{'en': 'Easy World'},
'49151':{'en': 'T-Mobile'},
'491520':{'en': 'Vodafone'},
'491521':{'en': 'Vodafone/Lycamobile'},
'491522':{'en': 'Vodafone'},
'491523':{'en': 'Vodafone'},
'491525':{'en': 'Vodafone'},
'491526':{'en': 'Vodafone'},
'491529':{'en': 'Vodafone/Truphone'},
'4915555':{'en': 'Tismi BV'},
'4915566':{'en': 'Drillisch Online'},
'4915630':{'en': 'Multiconnect'},
'4915678':{'en': 'Argon Networks'},
'491570':{'en': 'Eplus/Telogic'},
'491573':{'en': 'Eplus'},
'491575':{'en': 'Eplus'},
'491577':{'en': 'Eplus'},
'491578':{'en': 'Eplus'},
'491579':{'en': 'Eplus/Sipgate'},
'4915888':{'en': 'TelcoVillage'},
'491590':{'en': 'O2'},
'49160':{'en': 'T-Mobile'},
'49162':{'en': 'Vodafone'},
'49163':{'en': 'Eplus'},
'49170':{'en': 'T-Mobile'},
'49171':{'en': 'T-Mobile'},
'49172':{'en': 'Vodafone'},
'49173':{'en': 'Vodafone'},
'49174':{'en': 'Vodafone'},
'49175':{'en': 'T-Mobile'},
'49176':{'en': 'O2'},
'49177':{'en': 'Eplus'},
'49178':{'en': 'Eplus'},
'49179':{'en': 'O2'},
'5005':{'en': 'Sure South Atlantic Limited'},
'5006':{'en': 'Sure South Atlantic Limited'},
'50160':{'en': 'Belize Telemedia Ltd (Digi)'},
'50161':{'en': 'Belize Telemedia Ltd (Digi)'},
'50162':{'en': 'Belize Telemedia Ltd (Digi)'},
'50163':{'en': 'Belize Telemedia Ltd (Digi)'},
'50165':{'en': 'Speednet (Smart)'},
'50166':{'en': 'Speednet (Smart)'},
'50167':{'en': 'Speednet (Smart)'},
'50230':{'en': 'Tigo'},
'50231':{'en': 'Tigo'},
'50232':{'en': 'Tigo'},
'5023229':{'en': 'Telgua'},
'50233':{'en': 'Tigo'},
'50234':{'en': 'Movistar'},
'502350':{'en': 'Movistar'},
'502351':{'en': 'Movistar'},
'502352':{'en': 'Movistar'},
'502353':{'en': 'Movistar'},
'502354':{'en': 'Movistar'},
'502355':{'en': 'Movistar'},
'502356':{'en': 'Movistar'},
'502370':{'en': 'Tigo'},
'502371':{'en': 'Tigo'},
'502372':{'en': 'Tigo'},
'502373':{'en': 'Tigo'},
'502374':{'en': 'Tigo'},
'50240':{'en': 'Tigo'},
'502400':{'en': 'Movistar'},
'50241':{'en': 'Telgua'},
'50242':{'en': 'Telgua'},
'50243':{'en': 'Movistar'},
'50244':{'en': 'Movistar'},
'5024476':{'en': 'Tigo'},
'5024477':{'en': 'Tigo'},
'5024478':{'en': 'Tigo'},
'5024479':{'en': 'Tigo'},
'502448':{'en': 'Tigo'},
'502449':{'en': 'Tigo'},
'50245':{'en': 'Tigo'},
'50246':{'en': 'Tigo'},
'50247':{'en': 'Telgua'},
'502477':{'en': 'Tigo'},
'502478':{'en': 'Tigo'},
'502479':{'en': 'Tigo'},
'50248':{'en': 'Tigo'},
'50249':{'en': 'Tigo'},
'502500':{'en': 'Tigo'},
'502501':{'en': 'Telgua'},
'502502':{'en': 'Movistar'},
'502503':{'en': 'Tigo'},
'502504':{'en': 'Tigo'},
'502505':{'en': 'Tigo'},
'502506':{'en': 'Tigo'},
'502507':{'en': 'Movistar'},
'502508':{'en': 'Movistar'},
'502509':{'en': 'Movistar'},
'502510':{'en': 'Movistar'},
'502511':{'en': 'Telgua'},
'502512':{'en': 'Telgua'},
'502513':{'en': 'Telgua'},
'502514':{'en': 'Movistar'},
'502515':{'en': 'Tigo'},
'502516':{'en': 'Tigo'},
'502517':{'en': 'Tigo'},
'502518':{'en': 'Tigo'},
'502519':{'en': 'Tigo'},
'50252':{'en': 'Movistar'},
'502520':{'en': 'Tigo'},
'50253':{'en': 'Tigo'},
'5025310':{'en': 'Telgua'},
'5025311':{'en': 'Telgua'},
'5025312':{'en': 'Movistar'},
'5025313':{'en': 'Movistar'},
'502539':{'en': 'Movistar'},
'50254':{'en': 'Telgua'},
'502540':{'en': 'Movistar'},
'502550':{'en': 'Movistar'},
'502551':{'en': 'Telgua'},
'5025518':{'en': 'Movistar'},
'5025519':{'en': 'Movistar'},
'502552':{'en': 'Tigo'},
'5025531':{'en': 'Telgua'},
'5025532':{'en': 'Telgua'},
'5025533':{'en': 'Telgua'},
'5025534':{'en': 'Telgua'},
'5025535':{'en': 'Telgua'},
'5025536':{'en': 'Telgua'},
'5025537':{'en': 'Telgua'},
'5025538':{'en': 'Telgua'},
'5025539':{'en': 'Telgua'},
'502554':{'en': 'Movistar'},
'5025543':{'en': 'Telgua'},
'5025544':{'en': 'Telgua'},
'502555':{'en': 'Telgua'},
'5025550':{'en': 'Tigo'},
'5025551':{'en': 'Tigo'},
'5025552':{'en': 'Tigo'},
'5025553':{'en': 'Tigo'},
'502556':{'en': 'Telgua'},
'502557':{'en': 'Telgua'},
'502558':{'en': 'Telgua'},
'5025580':{'en': 'Tigo'},
'5025581':{'en': 'Tigo'},
'502559':{'en': 'Telgua'},
'50256':{'en': 'Movistar'},
'502561':{'en': 'Telgua'},
'502562':{'en': 'Telgua'},
'502563':{'en': 'Telgua'},
'502569':{'en': 'Telgua'},
'50257':{'en': 'Tigo'},
'502571':{'en': 'Telgua'},
'502579':{'en': 'Movistar'},
'50258':{'en': 'Telgua'},
'502580':{'en': 'Tigo'},
'5025819':{'en': 'Tigo'},
'502588':{'en': 'Tigo'},
'502589':{'en': 'Tigo'},
'50259':{'en': 'Telgua'},
'502590':{'en': 'Tigo'},
'5025915':{'en': 'Movistar'},
'5025916':{'en': 'Movistar'},
'5025917':{'en': 'Movistar'},
'5025918':{'en': 'Tigo'},
'5025919':{'en': 'Tigo'},
'502599':{'en': 'Tigo'},
'503600':{'en': 'Tigo'},
'503601':{'en': 'Tigo'},
'503602':{'en': 'Tigo'},
'503603':{'en': 'Tigo'},
'503604':{'en': 'Tigo'},
'503605':{'en': 'Tigo'},
'503609':{'en': 'Tigo'},
'50361':{'en': 'Movistar'},
'503620':{'en': 'Digicel'},
'503630':{'en': 'Claro'},
'5036310':{'en': 'Claro'},
'5036311':{'en': 'Claro'},
'5036312':{'en': 'Claro'},
'5036313':{'en': 'Claro'},
'5036314':{'en': 'Claro'},
'5036315':{'en': 'Claro'},
'5036316':{'en': 'Claro'},
'50363170':{'en': 'Claro'},
'50363171':{'en': 'Claro'},
'50363172':{'en': 'Claro'},
'50363173':{'en': 'Claro'},
'50363174':{'en': 'Claro'},
'503642':{'en': 'Movistar'},
'5036430':{'en': 'Movistar'},
'5036431':{'en': 'Movistar'},
'5036611':{'en': 'Movistar'},
'503700':{'en': 'Claro'},
'503701':{'en': 'Claro'},
'503702':{'en': 'Claro'},
'503703':{'en': 'Claro'},
'503704':{'en': 'Claro'},
'503705':{'en': 'Claro'},
'503706':{'en': 'Claro'},
'50370700':{'en': 'Claro'},
'50370701':{'en': 'Tigo'},
'50370702':{'en': 'Movistar'},
'50370703':{'en': 'Claro'},
'50370704':{'en': 'Claro'},
'50370705':{'en': 'Claro'},
'50370706':{'en': 'Tigo'},
'50370707':{'en': 'Claro'},
'50370708':{'en': 'Movistar'},
'50370709':{'en': 'Tigo'},
'50370710':{'en': 'Claro'},
'50370711':{'en': 'Movistar'},
'50370712':{'en': 'Claro'},
'50370713':{'en': 'Tigo'},
'50370714':{'en': 'Tigo'},
'50370715':{'en': 'Tigo'},
'50370716':{'en': 'Movistar'},
'50370717':{'en': 'Claro'},
'50370719':{'en': 'Tigo'},
'5037072':{'en': 'Digicel'},
'50370730':{'en': 'Digicel'},
'50370731':{'en': 'Digicel'},
'50370732':{'en': 'Digicel'},
'50370733':{'en': 'Digicel'},
'50370734':{'en': 'Digicel'},
'50370735':{'en': 'Claro'},
'50370736':{'en': 'Claro'},
'50370737':{'en': 'Claro'},
'50370738':{'en': 'Claro'},
'50370739':{'en': 'Claro'},
'50370740':{'en': 'Claro'},
'50370741':{'en': 'Claro'},
'50370742':{'en': 'Claro'},
'50370743':{'en': 'Claro'},
'50370744':{'en': 'Claro'},
'50370745':{'en': 'Claro'},
'50370746':{'en': 'Claro'},
'503708':{'en': 'Claro'},
'503709':{'en': 'Claro'},
'50371':{'en': 'Movistar'},
'50372':{'en': 'Tigo'},
'50373':{'en': 'Digicel'},
'50374':{'en': 'Digicel'},
'503745':{'en': 'Movistar'},
'503747':{'en': 'Tigo'},
'503748':{'en': 'Tigo'},
'503749':{'en': 'Tigo'},
'50375':{'en': 'Tigo'},
'50376':{'en': 'Claro'},
'503767':{'en': 'Tigo'},
'503768':{'en': 'Tigo'},
'50376865':{'en': 'Movistar'},
'50376866':{'en': 'Movistar'},
'50376867':{'en': 'Movistar'},
'50376868':{'en': 'Movistar'},
'50376869':{'en': 'Movistar'},
'5037691':{'en': 'Movistar'},
'5037692':{'en': 'Movistar'},
'5037693':{'en': 'Movistar'},
'5037694':{'en': 'Movistar'},
'5037695':{'en': 'Digicel'},
'5037696':{'en': 'Digicel'},
'5037697':{'en': 'Digicel'},
'5037698':{'en': 'Digicel'},
'5037699':{'en': 'Movistar'},
'503770':{'en': 'Movistar'},
'503771':{'en': 'Movistar'},
'503772':{'en': 'Tigo'},
'503773':{'en': 'Tigo'},
'503774':{'en': 'Claro'},
'503775':{'en': 'Claro'},
'503776':{'en': 'Digicel'},
'503777':{'en': 'Digicel'},
'5037780':{'en': 'Movistar'},
'5037781':{'en': 'Movistar'},
'5037782':{'en': 'Movistar'},
'5037783':{'en': 'Movistar'},
'5037784':{'en': 'Movistar'},
'5037785':{'en': 'Tigo'},
'5037786':{'en': 'Tigo'},
'5037787':{'en': 'Tigo'},
'5037788':{'en': 'Tigo'},
'5037789':{'en': 'Tigo'},
'5037790':{'en': 'Movistar'},
'5037791':{'en': 'Movistar'},
'5037792':{'en': 'Movistar'},
'5037793':{'en': 'Movistar'},
'5037794':{'en': 'Movistar'},
'5037795':{'en': 'Tigo'},
'5037796':{'en': 'Tigo'},
'5037797':{'en': 'Tigo'},
'5037798':{'en': 'Tigo'},
'5037799':{'en': 'Tigo'},
'5037800':{'en': 'Movistar'},
'5037801':{'en': 'Digicel'},
'50378020':{'en': 'Digicel'},
'50378021':{'en': 'Digicel'},
'50378022':{'en': 'Digicel'},
'50378023':{'en': 'Digicel'},
'50378024':{'en': 'Digicel'},
'50378025':{'en': 'Claro'},
'50378026':{'en': 'Claro'},
'50378027':{'en': 'Claro'},
'50378028':{'en': 'Claro'},
'50378029':{'en': 'Claro'},
'5037803':{'en': 'Claro'},
'5037805':{'en': 'Claro'},
'5037806':{'en': 'Claro'},
'5037807':{'en': 'Claro'},
'5037808':{'en': 'Claro'},
'5037809':{'en': 'Claro'},
'503781':{'en': 'Movistar'},
'503782':{'en': 'Movistar'},
'503783':{'en': 'Movistar'},
'5037840':{'en': 'Claro'},
'5037841':{'en': 'Claro'},
'5037842':{'en': 'Claro'},
'5037843':{'en': 'Claro'},
'5037844':{'en': 'Claro'},
'5037845':{'en': 'Movistar'},
'5037846':{'en': 'Movistar'},
'5037847':{'en': 'Movistar'},
'5037848':{'en': 'Movistar'},
'5037849':{'en': 'Movistar'},
'503785':{'en': 'Claro'},
'503786':{'en': 'Claro'},
'503787':{'en': 'Tigo'},
'503788':{'en': 'Tigo'},
'503789':{'en': 'Tigo'},
'503790':{'en': 'Tigo'},
'503791':{'en': 'Tigo'},
'503792':{'en': 'Tigo'},
'503793':{'en': 'Tigo'},
'503794':{'en': 'Tigo'},
'503795':{'en': 'Claro'},
'503796':{'en': 'Claro'},
'503797':{'en': 'Digicel'},
'5037980':{'en': 'Intelfon'},
'5037981':{'en': 'Intelfon'},
'5037982':{'en': 'Intelfon'},
'5037983':{'en': 'Intelfon'},
'5037984':{'en': 'Intelfon'},
'5037985':{'en': 'Claro'},
'5037986':{'en': 'Claro'},
'5037987':{'en': 'Claro'},
'5037988':{'en': 'Claro'},
'5037989':{'en': 'Claro'},
'503799':{'en': 'Movistar'},
'5043':{'en': 'Sercom (Claro)'},
'5047':{'en': 'HONDUTEL'},
'5048':{'en': 'Digicel Honduras'},
'5049':{'en': 'Celtel (Tigo)'},
'5055':{'en': 'Claro'},
'5056':{'en': 'CooTel'},
'5057':{'en': 'Movistar'},
'50581':{'en': 'Movistar'},
'50582':{'en': 'Movistar'},
'505820':{'en': 'Claro'},
'505821':{'en': 'Claro'},
'505822':{'en': 'Claro'},
'505823':{'en': 'Claro'},
'505832':{'en': 'Movistar'},
'505833':{'en': 'Claro'},
'505835':{'en': 'Claro'},
'505836':{'en': 'Claro'},
'505837':{'en': 'Movistar'},
'505838':{'en': 'Movistar'},
'505839':{'en': 'Movistar'},
'50584':{'en': 'Claro'},
'505845':{'en': 'Movistar'},
'505846':{'en': 'Movistar'},
'505847':{'en': 'Movistar'},
'505848':{'en': 'Movistar'},
'505850':{'en': 'Claro'},
'505851':{'en': 'Claro'},
'505852':{'en': 'Claro'},
'505853':{'en': 'Claro'},
'505854':{'en': 'Claro'},
'505855':{'en': 'Movistar'},
'505856':{'en': 'Movistar'},
'505857':{'en': 'Movistar'},
'505858':{'en': 'Movistar'},
'505859':{'en': 'Movistar'},
'50586':{'en': 'Claro'},
'505867':{'en': 'Movistar'},
'505868':{'en': 'Movistar'},
'505870':{'en': 'Claro'},
'505871':{'en': 'Claro'},
'505872':{'en': 'Claro'},
'505873':{'en': 'Claro'},
'505874':{'en': 'Claro'},
'505875':{'en': 'Movistar'},
'505876':{'en': 'Movistar'},
'505877':{'en': 'Movistar'},
'505878':{'en': 'Movistar'},
'505879':{'en': 'Movistar'},
'50588':{'en': 'Movistar'},
'505882':{'en': 'Claro'},
'505883':{'en': 'Claro'},
'505884':{'en': 'Claro'},
'505885':{'en': 'Claro'},
'505890':{'en': 'Claro'},
'505891':{'en': 'Claro'},
'505892':{'en': 'Claro'},
'505893':{'en': 'Claro'},
'505894':{'en': 'Claro'},
'505895':{'en': 'Movistar'},
'505896':{'en': 'Movistar'},
'505897':{'en': 'Movistar'},
'505898':{'en': 'Movistar'},
'505899':{'en': 'Movistar'},
'5063':{'en': 'Kolbi ICE'},
'50650':{'en': 'Kolbi ICE'},
'50657':{'en': 'Kolbi ICE'},
'5066':{'en': 'Movistar'},
'5067000':{'en': 'Claro'},
'50670010':{'en': 'Claro'},
'50670011':{'en': 'Claro'},
'50670012':{'en': 'Claro'},
'50670013':{'en': 'Claro'},
'50670014':{'en': 'Claro'},
'5067002':{'en': 'Claro'},
'5067003':{'en': 'Claro'},
'5067004':{'en': 'Claro'},
'5067005':{'en': 'Claro'},
'5067006':{'en': 'Claro'},
'5067007':{'en': 'Claro'},
'5067008':{'en': 'Claro'},
'5067009':{'en': 'Claro'},
'506701':{'en': 'Claro'},
'506702':{'en': 'Claro'},
'506703':{'en': 'Claro'},
'506704':{'en': 'Claro'},
'506705':{'en': 'Claro'},
'506706':{'en': 'Claro'},
'506707':{'en': 'Claro'},
'506708':{'en': 'Claro'},
'506709':{'en': 'Claro'},
'50671':{'en': 'Claro'},
'50672':{'en': 'Claro'},
'5067300':{'en': 'Claro'},
'5067301':{'en': 'Claro'},
'50683':{'en': 'Kolbi ICE'},
'50684':{'en': 'Kolbi ICE'},
'50685':{'en': 'Kolbi ICE'},
'50686':{'en': 'Kolbi ICE'},
'50687':{'en': 'Kolbi ICE'},
'50688':{'en': 'Kolbi ICE'},
'50689':{'en': 'Kolbi ICE'},
'507111':{'en': 'Claro'},
'507161':{'en': 'Cable & Wireless'},
'507218':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507219':{'en': u('Telef\u00f3nica M\u00f3viles')},
'50760':{'en': 'Digicel'},
'50761':{'en': 'Digicel'},
'507616':{'en': u('Telef\u00f3nica M\u00f3viles')},
'50762':{'en': 'Claro'},
'507630':{'en': 'Claro'},
'507631':{'en': 'Claro'},
'507632':{'en': 'Claro'},
'507633':{'en': 'Cable & Wireless'},
'507634':{'en': 'Cable & Wireless'},
'507635':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507636':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507637':{'en': 'Cable & Wireless'},
'507638':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507639':{'en': u('Telef\u00f3nica M\u00f3viles')},
'50764':{'en': u('Telef\u00f3nica M\u00f3viles')},
'50765':{'en': 'Cable & Wireless'},
'507656':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507657':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507658':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507659':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507660':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507661':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507662':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507663':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507664':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507665':{'en': 'Cable & Wireless'},
'507666':{'en': 'Cable & Wireless'},
'507667':{'en': 'Cable & Wireless'},
'507668':{'en': 'Cable & Wireless'},
'507669':{'en': 'Cable & Wireless'},
'50767':{'en': 'Cable & Wireless'},
'50768':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507680':{'en': 'Cable & Wireless'},
'507684':{'en': 'Cable & Wireless'},
'507687':{'en': 'Cable & Wireless'},
'507688':{'en': 'Cable & Wireless'},
'50769':{'en': 'Cable & Wireless'},
'507692':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507693':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507697':{'en': u('Telef\u00f3nica M\u00f3viles')},
'50781':{'en': 'Mobilphone'},
'507872':{'en': 'Cable & Wireless'},
'507873':{'en': 'Cable & Wireless'},
'50840':{'en': 'Globaltel'},
'50842':{'en': 'Orange'},
'50843':{'en': 'Diabolocom'},
'50844':{'en': 'Globaltel'},
'50850':{'en': 'Keyyo'},
'50855':{'en': 'SPM Telecom'},
'50930':{'en': 'Digicel'},
'50931':{'en': 'Digicel'},
'50934':{'en': 'Digicel'},
'50936':{'en': 'Digicel'},
'50937':{'en': 'Digicel'},
'50938':{'en': 'Digicel'},
'50939':{'en': 'Digicel'},
'50940':{'en': 'Natcom'},
'50941':{'en': 'Natcom'},
'50942':{'en': 'Natcom'},
'50943':{'en': 'Natcom'},
'50944':{'en': 'Digicel'},
'50946':{'en': 'Digicel'},
'50947':{'en': 'Digicel'},
'50948':{'en': 'Digicel'},
'50949':{'en': 'Digicel'},
'51900':{'en': 'Claro'},
'51901':{'en': 'Claro'},
'51910':{'en': 'Claro'},
'51912':{'en': 'Entel'},
'51913':{'en': 'Claro'},
'51914':{'en': 'Claro'},
'51915':{'en': 'Claro'},
'51916':{'en': 'Claro'},
'51917':{'en': 'Claro'},
'51918':{'en': 'Claro'},
'519190':{'en': 'Claro'},
'519191':{'en': 'Claro'},
'5191920':{'en': 'Claro'},
'5191921':{'en': 'Claro'},
'5191922':{'en': 'Claro'},
'5191923':{'en': 'Claro'},
'5191924':{'en': 'Claro'},
'5191925':{'en': 'Claro'},
'5191926':{'en': 'Claro'},
'5191927':{'en': 'Claro'},
'51920':{'en': 'Movistar'},
'51921':{'en': 'Claro'},
'51922':{'en': 'Entel'},
'51923':{'en': 'Entel'},
'51924':{'en': 'Entel'},
'51925':{'en': 'Claro'},
'519260':{'en': 'Claro'},
'519261':{'en': 'Claro'},
'519262':{'en': 'Claro'},
'5192630':{'en': 'Claro'},
'5192631':{'en': 'Claro'},
'5192632':{'en': 'Claro'},
'5192633':{'en': 'Claro'},
'5192634':{'en': 'Claro'},
'5192635':{'en': 'Claro'},
'5192638':{'en': 'Entel'},
'5192639':{'en': 'Entel'},
'519264':{'en': 'Claro'},
'519265':{'en': 'Claro'},
'519266':{'en': 'Entel'},
'519267':{'en': 'Entel'},
'519268':{'en': 'Entel'},
'519269':{'en': 'Entel'},
'51927':{'en': 'Claro'},
'51928':{'en': 'Claro'},
'51929':{'en': 'Claro'},
'51930':{'en': 'Claro'},
'51931':{'en': 'Claro'},
'51932':{'en': 'Claro'},
'519327':{'en': 'Movistar'},
'519328':{'en': 'Movistar'},
'519329':{'en': 'Movistar'},
'51933':{'en': 'Entel'},
'51934':{'en': 'Entel'},
'51935':{'en': 'Claro'},
'51936':{'en': 'Entel'},
'51937':{'en': 'Movistar'},
'519370':{'en': 'Entel'},
'519371':{'en': 'Entel'},
'519372':{'en': 'Entel'},
'519373':{'en': 'Claro'},
'5193730':{'en': 'Entel'},
'5193731':{'en': 'Entel'},
'5193732':{'en': 'Entel'},
'5193733':{'en': 'Entel'},
'51938':{'en': 'Movistar'},
'51939':{'en': 'Movistar'},
'51940':{'en': 'Claro'},
'51941':{'en': 'Claro'},
'519418':{'en': 'Movistar'},
'519419':{'en': 'Movistar'},
'51942':{'en': 'Movistar'},
'519422':{'en': 'Claro'},
'519423':{'en': 'Claro'},
'519427':{'en': 'Claro'},
'51943':{'en': 'Movistar'},
'519433':{'en': 'Claro'},
'519435':{'en': 'Claro'},
'519437':{'en': 'Claro'},
'51944':{'en': 'Claro'},
'519444':{'en': 'Movistar'},
'519446':{'en': 'Movistar'},
'519448':{'en': 'Movistar'},
'519449':{'en': 'Movistar'},
'51945':{'en': 'Movistar'},
'51946':{'en': 'Entel'},
'519466':{'en': 'Claro'},
'519467':{'en': 'Claro'},
'519468':{'en': 'Claro'},
'5194680':{'en': 'Movistar'},
'5194681':{'en': 'Movistar'},
'5194682':{'en': 'Movistar'},
'5194683':{'en': 'Movistar'},
'519469':{'en': 'Movistar'},
'51947':{'en': 'Movistar'},
'519471':{'en': 'Entel'},
'519472':{'en': 'Entel'},
'519473':{'en': 'Entel'},
'519477':{'en': 'Claro'},
'51948':{'en': 'Movistar'},
'5194805':{'en': 'Claro'},
'5194806':{'en': 'Claro'},
'5194807':{'en': 'Claro'},
'5194808':{'en': 'Claro'},
'5194809':{'en': 'Claro'},
'519482':{'en': 'Claro'},
'519483':{'en': 'Claro'},
'519487':{'en': 'Claro'},
'519490':{'en': 'Movistar'},
'5194907':{'en': 'Claro'},
'5194908':{'en': 'Claro'},
'5194909':{'en': 'Claro'},
'519491':{'en': 'Claro'},
'519492':{'en': 'Claro'},
'519493':{'en': 'Claro'},
'519494':{'en': 'Movistar'},
'519495':{'en': 'Movistar'},
'519496':{'en': 'Movistar'},
'519497':{'en': 'Claro'},
'5194978':{'en': 'Movistar'},
'5194979':{'en': 'Movistar'},
'519498':{'en': 'Movistar'},
'5194990':{'en': 'Movistar'},
'5194991':{'en': 'Movistar'},
'5194992':{'en': 'Movistar'},
'5194993':{'en': 'Movistar'},
'5194994':{'en': 'Movistar'},
'5194995':{'en': 'Movistar'},
'5194996':{'en': 'Movistar'},
'5194997':{'en': 'Movistar'},
'51949980':{'en': 'Movistar'},
'51949981':{'en': 'Movistar'},
'519499822':{'en': 'Movistar'},
'519499823':{'en': 'Movistar'},
'519499824':{'en': 'Movistar'},
'519499825':{'en': 'Movistar'},
'519499826':{'en': 'Movistar'},
'519499827':{'en': 'Movistar'},
'519499828':{'en': 'Movistar'},
'519499829':{'en': 'Movistar'},
'51949983':{'en': 'Movistar'},
'51949984':{'en': 'Movistar'},
'51949985':{'en': 'Movistar'},
'51949986':{'en': 'Movistar'},
'519499875':{'en': 'Movistar'},
'519499876':{'en': 'Movistar'},
'519499877':{'en': 'Movistar'},
'519499878':{'en': 'Movistar'},
'519499879':{'en': 'Movistar'},
'5194999':{'en': 'Movistar'},
'5195':{'en': 'Movistar'},
'519501':{'en': 'Claro'},
'5195010':{'en': 'Entel'},
'519502':{'en': 'Claro'},
'519503':{'en': 'Claro'},
'519507':{'en': 'Claro'},
'519511':{'en': 'Claro'},
'519512':{'en': 'Claro'},
'519513':{'en': 'Claro'},
'519517':{'en': 'Claro'},
'519521':{'en': 'Claro'},
'5195210':{'en': 'Entel'},
'519523':{'en': 'Claro'},
'519524':{'en': 'Claro'},
'5195270':{'en': 'Claro'},
'5195271':{'en': 'Claro'},
'5195272':{'en': 'Claro'},
'51953':{'en': 'Claro'},
'5195310':{'en': 'Entel'},
'519541':{'en': 'Claro'},
'5195420':{'en': 'Claro'},
'5195430':{'en': 'Claro'},
'519547':{'en': 'Claro'},
'51955':{'en': 'Entel'},
'519557':{'en': 'Claro'},
'519562':{'en': 'Claro'},
'519563':{'en': 'Claro'},
'519567':{'en': 'Claro'},
'519570':{'en': 'Claro'},
'519571':{'en': 'Claro'},
'519572':{'en': 'Claro'},
'519573':{'en': 'Claro'},
'519577':{'en': 'Claro'},
'5195805':{'en': 'Claro'},
'5195806':{'en': 'Claro'},
'5195807':{'en': 'Claro'},
'5195808':{'en': 'Claro'},
'5195809':{'en': 'Claro'},
'519581':{'en': 'Claro'},
'519582':{'en': 'Claro'},
'519583':{'en': 'Claro'},
'5195847':{'en': 'Claro'},
'5195848':{'en': 'Claro'},
'5195849':{'en': 'Claro'},
'519587':{'en': 'Claro'},
'5195895':{'en': 'Claro'},
'5195896':{'en': 'Claro'},
'5195897':{'en': 'Claro'},
'5195898':{'en': 'Claro'},
'5195899':{'en': 'Claro'},
'519591':{'en': 'Claro'},
'519592':{'en': 'Claro'},
'519593':{'en': 'Claro'},
'519597':{'en': 'Claro'},
'5196004':{'en': 'Claro'},
'5196005':{'en': 'Claro'},
'5196006':{'en': 'Claro'},
'5196007':{'en': 'Claro'},
'5196008':{'en': 'Claro'},
'5196009':{'en': 'Claro'},
'519601':{'en': 'Entel'},
'519602':{'en': 'Entel'},
'519603':{'en': 'Entel'},
'519604':{'en': 'Entel'},
'519605':{'en': 'Entel'},
'519606':{'en': 'Entel'},
'519607':{'en': 'Entel'},
'519608':{'en': 'Entel'},
'519609':{'en': 'Entel'},
'519610':{'en': 'Movistar'},
'519611':{'en': 'Movistar'},
'519612':{'en': 'Claro'},
'519613':{'en': 'Claro'},
'519614':{'en': 'Claro'},
'519615':{'en': 'Movistar'},
'519616':{'en': 'Movistar'},
'519617':{'en': 'Claro'},
'519618':{'en': 'Claro'},
'519619':{'en': 'Movistar'},
'51962':{'en': 'Movistar'},
'519622':{'en': 'Claro'},
'519623':{'en': 'Claro'},
'519627':{'en': 'Claro'},
'51963':{'en': 'Claro'},
'5196350':{'en': 'Movistar'},
'5196351':{'en': 'Movistar'},
'5196352':{'en': 'Movistar'},
'5196353':{'en': 'Movistar'},
'5196354':{'en': 'Movistar'},
'519636':{'en': 'Movistar'},
'519639':{'en': 'Movistar'},
'5196396':{'en': 'Entel'},
'5196397':{'en': 'Entel'},
'51964':{'en': 'Movistar'},
'519641':{'en': 'Claro'},
'519642':{'en': 'Claro'},
'519643':{'en': 'Claro'},
'51965':{'en': 'Claro'},
'519650':{'en': 'Movistar'},
'519656':{'en': 'Movistar'},
'519658':{'en': 'Movistar'},
'519659':{'en': 'Movistar'},
'51966':{'en': 'Movistar'},
'519663':{'en': 'Claro'},
'519664':{'en': 'Claro'},
'519667':{'en': 'Claro'},
'51967':{'en': 'Claro'},
'5196765':{'en': 'Movistar'},
'5196766':{'en': 'Movistar'},
'5196768':{'en': 'Movistar'},
'5196769':{'en': 'Movistar'},
'5196790':{'en': 'Movistar'},
'5196791':{'en': 'Movistar'},
'5196798':{'en': 'Movistar'},
'5196799':{'en': 'Movistar'},
'51968':{'en': 'Movistar'},
'5196820':{'en': 'Entel'},
'5196821':{'en': 'Claro'},
'519683':{'en': 'Claro'},
'519687':{'en': 'Claro'},
'51969':{'en': 'Movistar'},
'519693':{'en': 'Claro'},
'519697':{'en': 'Claro'},
'51970':{'en': 'Entel'},
'519700':{'en': 'Movistar'},
'519702':{'en': 'Claro'},
'519709':{'en': 'Movistar'},
'51971':{'en': 'Movistar'},
'519720':{'en': 'Entel'},
'519721':{'en': 'Entel'},
'519722':{'en': 'Claro'},
'519723':{'en': 'Claro'},
'519724':{'en': 'Claro'},
'519725':{'en': 'Claro'},
'5197250':{'en': 'Movistar'},
'5197251':{'en': 'Movistar'},
'5197252':{'en': 'Movistar'},
'519726':{'en': 'Movistar'},
'519727':{'en': 'Claro'},
'519728':{'en': 'Movistar'},
'519729':{'en': 'Movistar'},
'51973':{'en': 'Claro'},
'519738':{'en': 'Movistar'},
'519739':{'en': 'Movistar'},
'51974':{'en': 'Claro'},
'519740':{'en': 'Movistar'},
'519741':{'en': 'Movistar'},
'5197410':{'en': 'Entel'},
'5197487':{'en': 'Movistar'},
'5197488':{'en': 'Movistar'},
'5197489':{'en': 'Movistar'},
'519749':{'en': 'Movistar'},
'51975':{'en': 'Movistar'},
'519760':{'en': 'Movistar'},
'519761':{'en': 'Movistar'},
'519762':{'en': 'Claro'},
'519763':{'en': 'Claro'},
'519766':{'en': 'Movistar'},
'519767':{'en': 'Movistar'},
'519768':{'en': 'Movistar'},
'519769':{'en': 'Movistar'},
'51977':{'en': 'Entel'},
'519770':{'en': 'Claro'},
'519771':{'en': 'Claro'},
'519772':{'en': 'Movistar'},
'51978':{'en': 'Movistar'},
'5197820':{'en': 'Claro'},
'5197821':{'en': 'Entel'},
'519783':{'en': 'Claro'},
'519786':{'en': 'Claro'},
'519787':{'en': 'Claro'},
'51979':{'en': 'Movistar'},
'519793':{'en': 'Claro'},
'519797':{'en': 'Claro'},
'5198':{'en': 'Claro'},
'519800':{'en': 'Movistar'},
'5198000':{'en': 'Entel'},
'5198001':{'en': 'Entel'},
'5198002':{'en': 'Entel'},
'519801':{'en': 'Movistar'},
'519802':{'en': 'Movistar'},
'519803':{'en': 'Movistar'},
'51981':{'en': 'Entel'},
'519816':{'en': 'Movistar'},
'519817':{'en': 'Movistar'},
'519818':{'en': 'Movistar'},
'519819':{'en': 'Movistar'},
'5198260':{'en': 'Movistar'},
'5198261':{'en': 'Movistar'},
'5198268':{'en': 'Movistar'},
'5198298':{'en': 'Movistar'},
'519834':{'en': 'Entel'},
'519835':{'en': 'Entel'},
'519836':{'en': 'Movistar'},
'519839':{'en': 'Movistar'},
'519840':{'en': 'Movistar'},
'519845':{'en': 'Movistar'},
'519846':{'en': 'Movistar'},
'519848':{'en': 'Movistar'},
'519849':{'en': 'Movistar'},
'51985':{'en': 'Movistar'},
'51988':{'en': 'Movistar'},
'51990':{'en': 'Movistar'},
'51991':{'en': 'Claro'},
'51992':{'en': 'Claro'},
'51993':{'en': 'Claro'},
'519940':{'en': 'Entel'},
'519941':{'en': 'Entel'},
'519942':{'en': 'Entel'},
'519943':{'en': 'Claro'},
'519944':{'en': 'Movistar'},
'519945':{'en': 'Movistar'},
'519946':{'en': 'Claro'},
'519947':{'en': 'Claro'},
'519948':{'en': 'Claro'},
'519949':{'en': 'Claro'},
'51995':{'en': 'Movistar'},
'51996':{'en': 'Movistar'},
'51997':{'en': 'Claro'},
'51998':{'en': 'Movistar'},
'519981':{'en': 'Entel'},
'519982':{'en': 'Entel'},
'519983':{'en': 'Entel'},
'51999':{'en': 'Movistar'},
'535':{'en': 'etecsa'},
'549113':{'en': 'Personal'},
'549114':{'en': 'Personal'},
'549115':{'en': 'Personal'},
'549116':{'en': 'Personal'},
'549220':{'en': 'Personal'},
'549221':{'en': 'Personal'},
'549222':{'en': 'Personal'},
'549223':{'en': 'Personal'},
'549224':{'en': 'Personal'},
'549225':{'en': 'Personal'},
'549226':{'en': 'Personal'},
'549227':{'en': 'Personal'},
'549228':{'en': 'Personal'},
'549229':{'en': 'Personal'},
'549230':{'en': 'Personal'},
'549231':{'en': 'Personal'},
'549232':{'en': 'Personal'},
'549233':{'en': 'Personal'},
'549234':{'en': 'Personal'},
'549235':{'en': 'Personal'},
'549236':{'en': 'Personal'},
'549239':{'en': 'Personal'},
'549247':{'en': 'Personal'},
'549249':{'en': 'Personal'},
'549260':{'en': 'Personal'},
'549261':{'en': 'Personal'},
'549262':{'en': 'Personal'},
'549263':{'en': 'Personal'},
'549264':{'en': 'Personal'},
'549265':{'en': 'Personal'},
'549266':{'en': 'Personal'},
'549280':{'en': 'Personal'},
'549290':{'en': 'Personal'},
'549291':{'en': 'Personal'},
'549292':{'en': 'Personal'},
'549293':{'en': 'Personal'},
'549294':{'en': 'Personal'},
'549295':{'en': 'Personal'},
'549296':{'en': 'Personal'},
'549297':{'en': 'Personal'},
'549298':{'en': 'Personal'},
'549299':{'en': 'Personal'},
'549332':{'en': 'Personal'},
'549336':{'en': 'Personal'},
'549338':{'en': 'Personal'},
'549340':{'en': 'Personal'},
'549341':{'en': 'Personal'},
'549342':{'en': 'Personal'},
'549343':{'en': 'Personal'},
'549344':{'en': 'Personal'},
'549345':{'en': 'Personal'},
'549346':{'en': 'Personal'},
'549347':{'en': 'Personal'},
'549348':{'en': 'Personal'},
'549349':{'en': 'Personal'},
'549351':{'en': 'Personal'},
'549352':{'en': 'Personal'},
'549353':{'en': 'Personal'},
'549354':{'en': 'Personal'},
'549356':{'en': 'Personal'},
'549357':{'en': 'Personal'},
'549358':{'en': 'Personal'},
'549362':{'en': 'Personal'},
'549364':{'en': 'Personal'},
'549370':{'en': 'Personal'},
'549371':{'en': 'Personal'},
'549372':{'en': 'Personal'},
'549373':{'en': 'Personal'},
'549374':{'en': 'Personal'},
'549375':{'en': 'Personal'},
'549376':{'en': 'Personal'},
'549377':{'en': 'Personal'},
'549378':{'en': 'Personal'},
'549379':{'en': 'Personal'},
'549380':{'en': 'Personal'},
'549381':{'en': 'Personal'},
'549382':{'en': 'Personal'},
'549383':{'en': 'Personal'},
'549384':{'en': 'Personal'},
'549385':{'en': 'Personal'},
'549386':{'en': 'Personal'},
'549387':{'en': 'Personal'},
'549388':{'en': 'Personal'},
'549389':{'en': 'Personal'},
'551195472':{'en': 'Vivo'},
'551195473':{'en': 'Vivo'},
'551195474':{'en': 'Vivo'},
'551195769':{'en': 'Vivo'},
'55119577':{'en': 'Vivo'},
'551195780':{'en': 'Vivo'},
'551195781':{'en': 'Vivo'},
'551195782':{'en': 'Vivo'},
'551195783':{'en': 'Vivo'},
'551195784':{'en': 'Vivo'},
'551195785':{'en': 'Vivo'},
'551195786':{'en': 'Vivo'},
'551196057':{'en': 'Vivo'},
'551196058':{'en': 'Vivo'},
'551196059':{'en': 'Vivo'},
'551196060':{'en': 'Vivo'},
'551196168':{'en': 'Claro BR'},
'551196169':{'en': 'Claro BR'},
'55119617':{'en': 'Claro BR'},
'55119618':{'en': 'Vivo'},
'551196180':{'en': 'Claro BR'},
'551196181':{'en': 'Claro BR'},
'55119619':{'en': 'Vivo'},
'55119630':{'en': 'Claro BR'},
'55119631':{'en': 'Claro BR'},
'55119632':{'en': 'Claro BR'},
'55119633':{'en': 'Claro BR'},
'55119637':{'en': 'Vivo'},
'55119638':{'en': 'Vivo'},
'55119639':{'en': 'Vivo'},
'55119640':{'en': 'Vivo'},
'55119641':{'en': 'Vivo'},
'55119647':{'en': 'Vivo'},
'55119648':{'en': 'Vivo'},
'55119649':{'en': 'Vivo'},
'55119657':{'en': 'Claro BR'},
'55119658':{'en': 'Claro BR'},
'55119659':{'en': 'Claro BR'},
'55119660':{'en': 'Claro BR'},
'55119661':{'en': 'Claro BR'},
'55119662':{'en': 'Claro BR'},
'55119663':{'en': 'Claro BR'},
'55119664':{'en': 'Claro BR'},
'551196650':{'en': 'Claro BR'},
'55119684':{'en': 'Vivo'},
'55119685':{'en': 'Vivo'},
'551196860':{'en': 'Vivo'},
'551196861':{'en': 'Vivo'},
'551196862':{'en': 'Vivo'},
'551196863':{'en': 'Vivo'},
'551196864':{'en': 'Vivo'},
'551196865':{'en': 'Vivo'},
'551196866':{'en': 'Vivo'},
'55119690':{'en': 'Vivo'},
'55119691':{'en': 'Claro BR'},
'551196910':{'en': 'Vivo'},
'551196911':{'en': 'Vivo'},
'551196912':{'en': 'Vivo'},
'551196913':{'en': 'Vivo'},
'55119692':{'en': 'Claro BR'},
'551196930':{'en': 'Claro BR'},
'551196931':{'en': 'Claro BR'},
'551197011':{'en': 'TIM'},
'551197012':{'en': 'TIM'},
'551197013':{'en': 'TIM'},
'551197014':{'en': 'TIM'},
'551197015':{'en': 'TIM'},
'551197016':{'en': 'TIM'},
'551197017':{'en': 'TIM'},
'551197018':{'en': 'TIM'},
'551197019':{'en': 'TIM'},
'55119702':{'en': 'TIM'},
'551197030':{'en': 'TIM'},
'551197031':{'en': 'TIM'},
'551197032':{'en': 'TIM'},
'551197033':{'en': 'TIM'},
'551197034':{'en': 'TIM'},
'551197035':{'en': 'TIM'},
'551197036':{'en': 'TIM'},
'551197037':{'en': 'TIM'},
'551197038':{'en': 'TIM'},
'551197049':{'en': 'TIM'},
'55119705':{'en': 'Claro BR'},
'551197050':{'en': 'TIM'},
'551197051':{'en': 'TIM'},
'55119706':{'en': 'Claro BR'},
'55119707':{'en': 'Claro BR'},
'55119708':{'en': 'Claro BR'},
'551197087':{'en': 'Vivo'},
'551197088':{'en': 'Vivo'},
'551197089':{'en': 'Vivo'},
'55119709':{'en': 'Vivo'},
'5511971':{'en': 'Vivo'},
'5511972':{'en': 'Vivo'},
'5511973':{'en': 'Vivo'},
'5511974':{'en': 'Vivo'},
'5511975':{'en': 'Vivo'},
'5511976':{'en': 'Claro BR'},
'551197968':{'en': 'Claro BR'},
'551197969':{'en': 'Claro BR'},
'55119797':{'en': 'Oi'},
'551197970':{'en': 'Claro BR'},
'55119798':{'en': 'Oi'},
'551197990':{'en': 'Oi'},
'551197991':{'en': 'Oi'},
'551197992':{'en': 'Oi'},
'551197993':{'en': 'Oi'},
'551197994':{'en': 'Oi'},
'551197995':{'en': 'Oi'},
'551198023':{'en': 'Oi'},
'551198024':{'en': 'Oi'},
'551198025':{'en': 'Oi'},
'551198026':{'en': 'Oi'},
'551198027':{'en': 'Oi'},
'551198028':{'en': 'Oi'},
'551198029':{'en': 'Oi'},
'55119803':{'en': 'Oi'},
'55119804':{'en': 'Oi'},
'55119805':{'en': 'Oi'},
'55119806':{'en': 'Oi'},
'55119807':{'en': 'Oi'},
'55119808':{'en': 'Oi'},
'55119809':{'en': 'Oi'},
'5511981':{'en': 'TIM'},
'5511982':{'en': 'TIM'},
'5511983':{'en': 'TIM'},
'5511984':{'en': 'TIM'},
'5511985':{'en': 'TIM'},
'5511986':{'en': 'TIM'},
'5511987':{'en': 'TIM'},
'5511988':{'en': 'Claro BR'},
'5511989':{'en': 'Claro BR'},
'5511991':{'en': 'Claro BR'},
'5511992':{'en': 'Claro BR'},
'5511993':{'en': 'Claro BR'},
'5511994':{'en': 'Claro BR'},
'5511995':{'en': 'Vivo'},
'5511996':{'en': 'Vivo'},
'5511997':{'en': 'Vivo'},
'5511998':{'en': 'Vivo'},
'5511999':{'en': 'Vivo'},
'551298111':{'en': 'TIM'},
'551298112':{'en': 'TIM'},
'551298113':{'en': 'TIM'},
'551298114':{'en': 'TIM'},
'551298115':{'en': 'TIM'},
'551298116':{'en': 'TIM'},
'551298117':{'en': 'TIM'},
'551298118':{'en': 'TIM'},
'551298119':{'en': 'TIM'},
'551298121':{'en': 'TIM'},
'551298122':{'en': 'TIM'},
'551298123':{'en': 'TIM'},
'551298124':{'en': 'TIM'},
'551298125':{'en': 'TIM'},
'551298126':{'en': 'TIM'},
'551298127':{'en': 'TIM'},
'551298128':{'en': 'TIM'},
'551298129':{'en': 'TIM'},
'551298131':{'en': 'TIM'},
'551298132':{'en': 'TIM'},
'551298133':{'en': 'TIM'},
'551298134':{'en': 'TIM'},
'551298135':{'en': 'TIM'},
'551298136':{'en': 'TIM'},
'551298137':{'en': 'TIM'},
'551298138':{'en': 'TIM'},
'551298139':{'en': 'TIM'},
'551298141':{'en': 'TIM'},
'551298142':{'en': 'TIM'},
'551298143':{'en': 'TIM'},
'551298144':{'en': 'TIM'},
'551298145':{'en': 'TIM'},
'551298146':{'en': 'TIM'},
'551298147':{'en': 'TIM'},
'551298148':{'en': 'TIM'},
'551298149':{'en': 'TIM'},
'551298151':{'en': 'TIM'},
'551298152':{'en': 'TIM'},
'551298153':{'en': 'TIM'},
'551298154':{'en': 'TIM'},
'551298155':{'en': 'TIM'},
'551298156':{'en': 'TIM'},
'551298157':{'en': 'TIM'},
'551298158':{'en': 'TIM'},
'551298159':{'en': 'TIM'},
'551298161':{'en': 'TIM'},
'551298162':{'en': 'TIM'},
'551298163':{'en': 'TIM'},
'551298164':{'en': 'TIM'},
'551298165':{'en': 'TIM'},
'551298166':{'en': 'TIM'},
'551298167':{'en': 'TIM'},
'551298168':{'en': 'TIM'},
'551298169':{'en': 'TIM'},
'551298171':{'en': 'TIM'},
'551298172':{'en': 'TIM'},
'551298173':{'en': 'TIM'},
'551298174':{'en': 'TIM'},
'551298175':{'en': 'TIM'},
'551298176':{'en': 'TIM'},
'551298177':{'en': 'TIM'},
'551298178':{'en': 'TIM'},
'551298179':{'en': 'TIM'},
'551298181':{'en': 'TIM'},
'551298182':{'en': 'TIM'},
'551298808':{'en': 'Oi'},
'551298809':{'en': 'Oi'},
'55129881':{'en': 'Oi'},
'551298820':{'en': 'Oi'},
'551298821':{'en': 'Oi'},
'551298822':{'en': 'Oi'},
'551298823':{'en': 'Oi'},
'5512991':{'en': 'Claro BR'},
'55129920':{'en': 'Claro BR'},
'55129921':{'en': 'Claro BR'},
'55129922':{'en': 'Claro BR'},
'55129923':{'en': 'Claro BR'},
'551299240':{'en': 'Claro BR'},
'551299241':{'en': 'Claro BR'},
'551299242':{'en': 'Claro BR'},
'551299243':{'en': 'Claro BR'},
'551299244':{'en': 'Claro BR'},
'551299245':{'en': 'Claro BR'},
'55129960':{'en': 'Vivo'},
'55129961':{'en': 'Vivo'},
'55129962':{'en': 'Vivo'},
'551299630':{'en': 'Vivo'},
'551299631':{'en': 'Vivo'},
'551299632':{'en': 'Vivo'},
'5512997':{'en': 'Vivo'},
'551398111':{'en': 'TIM'},
'551398112':{'en': 'TIM'},
'551398113':{'en': 'TIM'},
'551398114':{'en': 'TIM'},
'551398115':{'en': 'TIM'},
'551398116':{'en': 'TIM'},
'551398117':{'en': 'TIM'},
'551398118':{'en': 'TIM'},
'551398119':{'en': 'TIM'},
'551398121':{'en': 'TIM'},
'551398122':{'en': 'TIM'},
'551398123':{'en': 'TIM'},
'551398124':{'en': 'TIM'},
'551398125':{'en': 'TIM'},
'551398126':{'en': 'TIM'},
'551398127':{'en': 'TIM'},
'551398128':{'en': 'TIM'},
'551398129':{'en': 'TIM'},
'551398131':{'en': 'TIM'},
'551398132':{'en': 'TIM'},
'551398133':{'en': 'TIM'},
'551398134':{'en': 'TIM'},
'551398135':{'en': 'TIM'},
'551398136':{'en': 'TIM'},
'551398137':{'en': 'TIM'},
'551398138':{'en': 'TIM'},
'551398139':{'en': 'TIM'},
'551398141':{'en': 'TIM'},
'551398142':{'en': 'TIM'},
'551398143':{'en': 'TIM'},
'551398144':{'en': 'TIM'},
'551398145':{'en': 'TIM'},
'551398146':{'en': 'TIM'},
'551398147':{'en': 'TIM'},
'551398149':{'en': 'TIM'},
'551398151':{'en': 'TIM'},
'551398152':{'en': 'TIM'},
'551398153':{'en': 'TIM'},
'551398154':{'en': 'TIM'},
'551398155':{'en': 'TIM'},
'551398156':{'en': 'TIM'},
'551398157':{'en': 'TIM'},
'551398158':{'en': 'TIM'},
'551398159':{'en': 'TIM'},
'551398161':{'en': 'TIM'},
'551398803':{'en': 'Oi'},
'551398804':{'en': 'Oi'},
'551398805':{'en': 'Oi'},
'551398806':{'en': 'Oi'},
'551398807':{'en': 'Oi'},
'551398808':{'en': 'Oi'},
'551398809':{'en': 'Oi'},
'55139881':{'en': 'Oi'},
'551398820':{'en': 'Oi'},
'5513991':{'en': 'Claro BR'},
'55139920':{'en': 'Claro BR'},
'551399210':{'en': 'Claro BR'},
'551399211':{'en': 'Claro BR'},
'55139960':{'en': 'Vivo'},
'55139961':{'en': 'Vivo'},
'55139962':{'en': 'Vivo'},
'551399630':{'en': 'Vivo'},
'551399631':{'en': 'Vivo'},
'551399632':{'en': 'Vivo'},
'551399633':{'en': 'Vivo'},
'551399634':{'en': 'Vivo'},
'551399635':{'en': 'Vivo'},
'551399636':{'en': 'Vivo'},
'551399637':{'en': 'Vivo'},
'5513997':{'en': 'Vivo'},
'551498111':{'en': 'TIM'},
'551498112':{'en': 'TIM'},
'551498113':{'en': 'TIM'},
'551498114':{'en': 'TIM'},
'551498115':{'en': 'TIM'},
'551498116':{'en': 'TIM'},
'551498117':{'en': 'TIM'},
'551498118':{'en': 'TIM'},
'551498119':{'en': 'TIM'},
'551498121':{'en': 'TIM'},
'551498122':{'en': 'TIM'},
'551498123':{'en': 'TIM'},
'551498124':{'en': 'TIM'},
'551498125':{'en': 'TIM'},
'551498126':{'en': 'TIM'},
'551498127':{'en': 'TIM'},
'551498128':{'en': 'TIM'},
'551498129':{'en': 'TIM'},
'551498131':{'en': 'TIM'},
'551498132':{'en': 'TIM'},
'551498133':{'en': 'TIM'},
'551498134':{'en': 'TIM'},
'551498135':{'en': 'TIM'},
'551498136':{'en': 'TIM'},
'551498137':{'en': 'TIM'},
'551498138':{'en': 'TIM'},
'551498139':{'en': 'TIM'},
'551498141':{'en': 'TIM'},
'551498142':{'en': 'TIM'},
'551498143':{'en': 'TIM'},
'551498144':{'en': 'TIM'},
'551498145':{'en': 'TIM'},
'551498146':{'en': 'TIM'},
'551498147':{'en': 'TIM'},
'551498148':{'en': 'TIM'},
'551498149':{'en': 'TIM'},
'551498151':{'en': 'TIM'},
'551498152':{'en': 'TIM'},
'551498153':{'en': 'TIM'},
'551498154':{'en': 'TIM'},
'551498155':{'en': 'TIM'},
'551498156':{'en': 'TIM'},
'551498157':{'en': 'TIM'},
'551498158':{'en': 'TIM'},
'551498159':{'en': 'TIM'},
'551498161':{'en': 'TIM'},
'551498162':{'en': 'TIM'},
'551498163':{'en': 'TIM'},
'551498164':{'en': 'TIM'},
'551498165':{'en': 'TIM'},
'551498166':{'en': 'TIM'},
'551498806':{'en': 'Oi'},
'551498807':{'en': 'Oi'},
'551498808':{'en': 'Oi'},
'551498809':{'en': 'Oi'},
'551498810':{'en': 'Oi'},
'551498811':{'en': 'Oi'},
'551498812':{'en': 'Oi'},
'551498813':{'en': 'Oi'},
'551498814':{'en': 'Oi'},
'551499101':{'en': 'Claro BR'},
'551499102':{'en': 'Claro BR'},
'551499103':{'en': 'Claro BR'},
'551499104':{'en': 'Claro BR'},
'551499105':{'en': 'Claro BR'},
'551499106':{'en': 'Claro BR'},
'551499107':{'en': 'Claro BR'},
'551499108':{'en': 'Claro BR'},
'551499109':{'en': 'Claro BR'},
'551499111':{'en': 'Claro BR'},
'551499112':{'en': 'Claro BR'},
'551499113':{'en': 'Claro BR'},
'551499114':{'en': 'Claro BR'},
'551499115':{'en': 'Claro BR'},
'551499116':{'en': 'Claro BR'},
'551499117':{'en': 'Claro BR'},
'551499118':{'en': 'Claro BR'},
'551499119':{'en': 'Claro BR'},
'551499121':{'en': 'Claro BR'},
'551499122':{'en': 'Claro BR'},
'551499123':{'en': 'Claro BR'},
'551499124':{'en': 'Claro BR'},
'551499125':{'en': 'Claro BR'},
'551499126':{'en': 'Claro BR'},
'551499127':{'en': 'Claro BR'},
'551499128':{'en': 'Claro BR'},
'551499129':{'en': 'Claro BR'},
'551499131':{'en': 'Claro BR'},
'551499132':{'en': 'Claro BR'},
'551499133':{'en': 'Claro BR'},
'551499134':{'en': 'Claro BR'},
'551499135':{'en': 'Claro BR'},
'551499136':{'en': 'Claro BR'},
'551499137':{'en': 'Claro BR'},
'551499138':{'en': 'Claro BR'},
'551499141':{'en': 'Claro BR'},
'551499142':{'en': 'Claro BR'},
'551499143':{'en': 'Claro BR'},
'551499146':{'en': 'Claro BR'},
'551499147':{'en': 'Claro BR'},
'551499148':{'en': 'Claro BR'},
'551499149':{'en': 'Claro BR'},
'551499151':{'en': 'Claro BR'},
'551499152':{'en': 'Claro BR'},
'551499153':{'en': 'Claro BR'},
'551499154':{'en': 'Claro BR'},
'551499155':{'en': 'Claro BR'},
'551499156':{'en': 'Claro BR'},
'551499157':{'en': 'Claro BR'},
'551499161':{'en': 'Claro BR'},
'551499162':{'en': 'Claro BR'},
'551499163':{'en': 'Claro BR'},
'551499164':{'en': 'Claro BR'},
'551499165':{'en': 'Claro BR'},
'551499166':{'en': 'Claro BR'},
'551499167':{'en': 'Claro BR'},
'551499168':{'en': 'Claro BR'},
'551499169':{'en': 'Claro BR'},
'551499171':{'en': 'Claro BR'},
'551499172':{'en': 'Claro BR'},
'551499173':{'en': 'Claro BR'},
'551499174':{'en': 'Claro BR'},
'551499175':{'en': 'Claro BR'},
'551499176':{'en': 'Claro BR'},
'551499177':{'en': 'Claro BR'},
'551499178':{'en': 'Claro BR'},
'551499179':{'en': 'Claro BR'},
'551499181':{'en': 'Claro BR'},
'551499182':{'en': 'Claro BR'},
'551499183':{'en': 'Claro BR'},
'551499184':{'en': 'Claro BR'},
'551499185':{'en': 'Claro BR'},
'551499186':{'en': 'Claro BR'},
'551499187':{'en': 'Claro BR'},
'551499188':{'en': 'Claro BR'},
'551499189':{'en': 'Claro BR'},
'551499191':{'en': 'Claro BR'},
'551499192':{'en': 'Claro BR'},
'551499193':{'en': 'Claro BR'},
'551499194':{'en': 'Claro BR'},
'551499195':{'en': 'Claro BR'},
'551499196':{'en': 'Claro BR'},
'551499197':{'en': 'Claro BR'},
'5514996':{'en': 'Vivo'},
'5514997':{'en': 'Vivo'},
'55149980':{'en': 'Vivo'},
'55149981':{'en': 'Vivo'},
'55149982':{'en': 'Vivo'},
'551499830':{'en': 'Vivo'},
'551499831':{'en': 'Vivo'},
'551499832':{'en': 'Vivo'},
'551598111':{'en': 'TIM'},
'551598112':{'en': 'TIM'},
'551598113':{'en': 'TIM'},
'551598114':{'en': 'TIM'},
'551598115':{'en': 'TIM'},
'551598116':{'en': 'TIM'},
'551598117':{'en': 'TIM'},
'551598118':{'en': 'TIM'},
'551598119':{'en': 'TIM'},
'551598121':{'en': 'TIM'},
'551598122':{'en': 'TIM'},
'551598123':{'en': 'TIM'},
'551598124':{'en': 'TIM'},
'551598125':{'en': 'TIM'},
'551598126':{'en': 'TIM'},
'551598127':{'en': 'TIM'},
'551598128':{'en': 'TIM'},
'551598129':{'en': 'TIM'},
'551598131':{'en': 'TIM'},
'551598132':{'en': 'TIM'},
'551598133':{'en': 'TIM'},
'551598134':{'en': 'TIM'},
'551598135':{'en': 'TIM'},
'551598136':{'en': 'TIM'},
'551598138':{'en': 'TIM'},
'551598139':{'en': 'TIM'},
'551598141':{'en': 'TIM'},
'551598804':{'en': 'Oi'},
'551598805':{'en': 'Oi'},
'551598806':{'en': 'Oi'},
'551598807':{'en': 'Oi'},
'551598808':{'en': 'Oi'},
'551598809':{'en': 'Oi'},
'551598810':{'en': 'Oi'},
'551598813':{'en': 'Oi'},
'551598814':{'en': 'Oi'},
'551598815':{'en': 'Oi'},
'551599101':{'en': 'Claro BR'},
'551599102':{'en': 'Claro BR'},
'551599103':{'en': 'Claro BR'},
'551599104':{'en': 'Claro BR'},
'551599105':{'en': 'Claro BR'},
'551599106':{'en': 'Claro BR'},
'551599107':{'en': 'Claro BR'},
'551599108':{'en': 'Claro BR'},
'551599109':{'en': 'Claro BR'},
'551599111':{'en': 'Claro BR'},
'551599112':{'en': 'Claro BR'},
'551599113':{'en': 'Claro BR'},
'551599114':{'en': 'Claro BR'},
'551599115':{'en': 'Claro BR'},
'551599116':{'en': 'Claro BR'},
'551599117':{'en': 'Claro BR'},
'551599118':{'en': 'Claro BR'},
'551599119':{'en': 'Claro BR'},
'551599121':{'en': 'Claro BR'},
'551599122':{'en': 'Claro BR'},
'551599123':{'en': 'Claro BR'},
'551599124':{'en': 'Claro BR'},
'551599125':{'en': 'Claro BR'},
'551599126':{'en': 'Claro BR'},
'551599127':{'en': 'Claro BR'},
'551599128':{'en': 'Claro BR'},
'551599129':{'en': 'Claro BR'},
'551599131':{'en': 'Claro BR'},
'551599132':{'en': 'Claro BR'},
'551599133':{'en': 'Claro BR'},
'551599134':{'en': 'Claro BR'},
'551599135':{'en': 'Claro BR'},
'551599136':{'en': 'Claro BR'},
'551599137':{'en': 'Claro BR'},
'551599138':{'en': 'Claro BR'},
'551599139':{'en': 'Claro BR'},
'551599141':{'en': 'Claro BR'},
'551599142':{'en': 'Claro BR'},
'551599143':{'en': 'Claro BR'},
'551599144':{'en': 'Claro BR'},
'551599145':{'en': 'Claro BR'},
'551599146':{'en': 'Claro BR'},
'551599147':{'en': 'Claro BR'},
'551599148':{'en': 'Claro BR'},
'551599149':{'en': 'Claro BR'},
'551599151':{'en': 'Claro BR'},
'551599152':{'en': 'Claro BR'},
'551599153':{'en': 'Claro BR'},
'551599154':{'en': 'Claro BR'},
'551599155':{'en': 'Claro BR'},
'551599156':{'en': 'Claro BR'},
'551599157':{'en': 'Claro BR'},
'551599158':{'en': 'Claro BR'},
'551599159':{'en': 'Claro BR'},
'551599161':{'en': 'Claro BR'},
'551599162':{'en': 'Claro BR'},
'551599163':{'en': 'Claro BR'},
'551599164':{'en': 'Claro BR'},
'551599165':{'en': 'Claro BR'},
'551599166':{'en': 'Claro BR'},
'551599167':{'en': 'Claro BR'},
'551599168':{'en': 'Claro BR'},
'551599169':{'en': 'Claro BR'},
'551599171':{'en': 'Claro BR'},
'551599172':{'en': 'Claro BR'},
'551599173':{'en': 'Claro BR'},
'551599174':{'en': 'Claro BR'},
'551599175':{'en': 'Claro BR'},
'551599176':{'en': 'Claro BR'},
'551599177':{'en': 'Claro BR'},
'551599178':{'en': 'Claro BR'},
'551599179':{'en': 'Claro BR'},
'551599181':{'en': 'Claro BR'},
'551599182':{'en': 'Claro BR'},
'551599183':{'en': 'Claro BR'},
'551599184':{'en': 'Claro BR'},
'551599185':{'en': 'Claro BR'},
'551599186':{'en': 'Claro BR'},
'551599187':{'en': 'Claro BR'},
'551599188':{'en': 'Claro BR'},
'551599201':{'en': 'Claro BR'},
'55159960':{'en': 'Vivo'},
'55159961':{'en': 'Vivo'},
'55159962':{'en': 'Vivo'},
'55159963':{'en': 'Vivo'},
'55159964':{'en': 'Vivo'},
'55159965':{'en': 'Vivo'},
'55159966':{'en': 'Vivo'},
'55159967':{'en': 'Vivo'},
'55159968':{'en': 'Vivo'},
'551599690':{'en': 'Vivo'},
'551599691':{'en': 'Vivo'},
'551599692':{'en': 'Vivo'},
'551599693':{'en': 'Vivo'},
'551599694':{'en': 'Vivo'},
'551599695':{'en': 'Vivo'},
'551599696':{'en': 'Vivo'},
'551599697':{'en': 'Vivo'},
'5515997':{'en': 'Vivo'},
'551698111':{'en': 'TIM'},
'551698112':{'en': 'TIM'},
'551698113':{'en': 'TIM'},
'551698114':{'en': 'TIM'},
'551698115':{'en': 'TIM'},
'551698116':{'en': 'TIM'},
'551698117':{'en': 'TIM'},
'551698118':{'en': 'TIM'},
'551698119':{'en': 'TIM'},
'551698121':{'en': 'TIM'},
'551698122':{'en': 'TIM'},
'551698123':{'en': 'TIM'},
'551698124':{'en': 'TIM'},
'551698125':{'en': 'TIM'},
'551698126':{'en': 'TIM'},
'551698127':{'en': 'TIM'},
'551698128':{'en': 'TIM'},
'551698129':{'en': 'TIM'},
'551698131':{'en': 'TIM'},
'551698132':{'en': 'TIM'},
'551698133':{'en': 'TIM'},
'551698134':{'en': 'TIM'},
'551698135':{'en': 'TIM'},
'551698136':{'en': 'TIM'},
'551698137':{'en': 'TIM'},
'551698138':{'en': 'TIM'},
'551698139':{'en': 'TIM'},
'551698141':{'en': 'TIM'},
'551698142':{'en': 'TIM'},
'551698143':{'en': 'TIM'},
'551698144':{'en': 'TIM'},
'551698145':{'en': 'TIM'},
'551698146':{'en': 'TIM'},
'551698147':{'en': 'TIM'},
'551698148':{'en': 'TIM'},
'551698149':{'en': 'TIM'},
'551698151':{'en': 'TIM'},
'551698152':{'en': 'TIM'},
'551698153':{'en': 'TIM'},
'551698154':{'en': 'TIM'},
'551698155':{'en': 'TIM'},
'551698156':{'en': 'TIM'},
'551698157':{'en': 'TIM'},
'551698158':{'en': 'TIM'},
'551698159':{'en': 'TIM'},
'551698161':{'en': 'TIM'},
'551698162':{'en': 'TIM'},
'551698163':{'en': 'TIM'},
'551698164':{'en': 'TIM'},
'551698165':{'en': 'TIM'},
'551698166':{'en': 'TIM'},
'551698167':{'en': 'TIM'},
'551698168':{'en': 'TIM'},
'551698169':{'en': 'TIM'},
'551698171':{'en': 'TIM'},
'551698172':{'en': 'TIM'},
'551698173':{'en': 'TIM'},
'551698174':{'en': 'TIM'},
'551698175':{'en': 'TIM'},
'551698176':{'en': 'TIM'},
'551698177':{'en': 'TIM'},
'551698178':{'en': 'TIM'},
'551698179':{'en': 'TIM'},
'551698181':{'en': 'TIM'},
'551698182':{'en': 'TIM'},
'551698183':{'en': 'TIM'},
'551698184':{'en': 'TIM'},
'551698803':{'en': 'Oi'},
'551698804':{'en': 'Oi'},
'551698805':{'en': 'Oi'},
'551698806':{'en': 'Oi'},
'551698807':{'en': 'Oi'},
'551698808':{'en': 'Oi'},
'551698809':{'en': 'Oi'},
'55169881':{'en': 'Oi'},
'551698820':{'en': 'Oi'},
'551698821':{'en': 'Oi'},
'551698822':{'en': 'Oi'},
'551698823':{'en': 'Oi'},
'5516991':{'en': 'Claro BR'},
'5516992':{'en': 'Claro BR'},
'55169930':{'en': 'Claro BR'},
'55169931':{'en': 'Claro BR'},
'55169932':{'en': 'Claro BR'},
'55169933':{'en': 'Claro BR'},
'55169934':{'en': 'Claro BR'},
'55169935':{'en': 'Claro BR'},
'551699360':{'en': 'Claro BR'},
'551699361':{'en': 'Claro BR'},
'551699362':{'en': 'Claro BR'},
'551699363':{'en': 'Claro BR'},
'551699364':{'en': 'Claro BR'},
'551699601':{'en': 'Vivo'},
'551699606':{'en': 'Vivo'},
'551699607':{'en': 'Vivo'},
'551699608':{'en': 'Vivo'},
'551699609':{'en': 'Vivo'},
'551699701':{'en': 'Vivo'},
'551699702':{'en': 'Vivo'},
'551699703':{'en': 'Vivo'},
'551699704':{'en': 'Vivo'},
'551699705':{'en': 'Vivo'},
'551699706':{'en': 'Vivo'},
'551699707':{'en': 'Vivo'},
'551699708':{'en': 'Vivo'},
'551699709':{'en': 'Vivo'},
'551699711':{'en': 'Vivo'},
'551699712':{'en': 'Vivo'},
'551699713':{'en': 'Vivo'},
'551699714':{'en': 'Vivo'},
'551699715':{'en': 'Vivo'},
'551699716':{'en': 'Vivo'},
'551699717':{'en': 'Vivo'},
'551699718':{'en': 'Vivo'},
'551699719':{'en': 'Vivo'},
'551699721':{'en': 'Vivo'},
'551699722':{'en': 'Vivo'},
'551699723':{'en': 'Vivo'},
'551699724':{'en': 'Vivo'},
'551699725':{'en': 'Vivo'},
'551699726':{'en': 'Vivo'},
'551699727':{'en': 'Vivo'},
'551699728':{'en': 'Vivo'},
'551699729':{'en': 'Vivo'},
'551699731':{'en': 'Vivo'},
'551699732':{'en': 'Vivo'},
'551699733':{'en': 'Vivo'},
'551699734':{'en': 'Vivo'},
'551699735':{'en': 'Vivo'},
'551699736':{'en': 'Vivo'},
'551699737':{'en': 'Vivo'},
'551699738':{'en': 'Vivo'},
'551699739':{'en': 'Vivo'},
'551699741':{'en': 'Vivo'},
'551699742':{'en': 'Vivo'},
'551699743':{'en': 'Vivo'},
'551699744':{'en': 'Vivo'},
'551699745':{'en': 'Vivo'},
'551699746':{'en': 'Vivo'},
'551699747':{'en': 'Vivo'},
'551699748':{'en': 'Vivo'},
'551699749':{'en': 'Vivo'},
'551699751':{'en': 'Vivo'},
'551699752':{'en': 'Vivo'},
'551699753':{'en': 'Vivo'},
'551699754':{'en': 'Vivo'},
'551699755':{'en': 'Vivo'},
'551699756':{'en': 'Vivo'},
'551699757':{'en': 'Vivo'},
'551699758':{'en': 'Vivo'},
'551699759':{'en': 'Vivo'},
'551699761':{'en': 'Vivo'},
'551699762':{'en': 'Vivo'},
'551699763':{'en': 'Vivo'},
'551699764':{'en': 'Vivo'},
'551699765':{'en': 'Vivo'},
'551699766':{'en': 'Vivo'},
'551699767':{'en': 'Vivo'},
'551699768':{'en': 'Vivo'},
'551699769':{'en': 'Vivo'},
'551699770':{'en': 'Vivo'},
'551699771':{'en': 'Vivo'},
'551699772':{'en': 'Vivo'},
'551699773':{'en': 'Vivo'},
'551699774':{'en': 'Vivo'},
'551699775':{'en': 'Vivo'},
'551699776':{'en': 'Vivo'},
'551699777':{'en': 'Vivo'},
'551699778':{'en': 'Vivo'},
'551699780':{'en': 'Vivo'},
'551699781':{'en': 'Vivo'},
'551699782':{'en': 'Vivo'},
'551699783':{'en': 'Vivo'},
'551699784':{'en': 'Vivo'},
'551699785':{'en': 'Vivo'},
'551699786':{'en': 'Vivo'},
'551699787':{'en': 'Vivo'},
'551699788':{'en': 'Vivo'},
'551699791':{'en': 'Vivo'},
'551699792':{'en': 'Vivo'},
'551699793':{'en': 'Vivo'},
'551699794':{'en': 'Vivo'},
'551699796':{'en': 'Vivo'},
'551699961':{'en': 'Vivo'},
'551699962':{'en': 'Vivo'},
'551699963':{'en': 'Vivo'},
'551699964':{'en': 'Vivo'},
'551699975':{'en': 'Vivo'},
'551699991':{'en': 'Vivo'},
'551699992':{'en': 'Vivo'},
'551699993':{'en': 'Vivo'},
'551699994':{'en': 'Vivo'},
'551798111':{'en': 'TIM'},
'551798112':{'en': 'TIM'},
'551798113':{'en': 'TIM'},
'551798114':{'en': 'TIM'},
'551798115':{'en': 'TIM'},
'551798116':{'en': 'TIM'},
'551798117':{'en': 'TIM'},
'551798118':{'en': 'TIM'},
'551798119':{'en': 'TIM'},
'551798121':{'en': 'TIM'},
'551798122':{'en': 'TIM'},
'551798123':{'en': 'TIM'},
'551798124':{'en': 'TIM'},
'551798125':{'en': 'TIM'},
'551798126':{'en': 'TIM'},
'551798127':{'en': 'TIM'},
'551798128':{'en': 'TIM'},
'551798129':{'en': 'TIM'},
'551798131':{'en': 'TIM'},
'551798132':{'en': 'TIM'},
'551798133':{'en': 'TIM'},
'551798134':{'en': 'TIM'},
'551798135':{'en': 'TIM'},
'551798136':{'en': 'TIM'},
'551798137':{'en': 'TIM'},
'551798138':{'en': 'TIM'},
'551798139':{'en': 'TIM'},
'551798141':{'en': 'TIM'},
'551798142':{'en': 'TIM'},
'551798143':{'en': 'TIM'},
'551798144':{'en': 'TIM'},
'551798145':{'en': 'TIM'},
'551798146':{'en': 'TIM'},
'551798147':{'en': 'TIM'},
'551798148':{'en': 'TIM'},
'551798149':{'en': 'TIM'},
'551798151':{'en': 'TIM'},
'551798152':{'en': 'TIM'},
'551798153':{'en': 'TIM'},
'551798154':{'en': 'TIM'},
'551798155':{'en': 'TIM'},
'551798156':{'en': 'TIM'},
'551798803':{'en': 'Oi'},
'551798804':{'en': 'Oi'},
'551798805':{'en': 'Oi'},
'551798806':{'en': 'Oi'},
'551798807':{'en': 'Oi'},
'551798808':{'en': 'Oi'},
'551798809':{'en': 'Oi'},
'551798810':{'en': 'Oi'},
'551798811':{'en': 'Oi'},
'551798812':{'en': 'Oi'},
'551798813':{'en': 'Oi'},
'5517991':{'en': 'Claro BR'},
'55179920':{'en': 'Claro BR'},
'55179921':{'en': 'Claro BR'},
'55179922':{'en': 'Claro BR'},
'551799230':{'en': 'Claro BR'},
'551799231':{'en': 'Claro BR'},
'551799232':{'en': 'Claro BR'},
'551799233':{'en': 'Claro BR'},
'551799234':{'en': 'Claro BR'},
'551799235':{'en': 'Claro BR'},
'551799236':{'en': 'Claro BR'},
'551799601':{'en': 'Vivo'},
'551799602':{'en': 'Vivo'},
'551799603':{'en': 'Vivo'},
'551799604':{'en': 'Vivo'},
'551799605':{'en': 'Vivo'},
'551799606':{'en': 'Vivo'},
'551799607':{'en': 'Vivo'},
'551799608':{'en': 'Vivo'},
'551799609':{'en': 'Vivo'},
'551799611':{'en': 'Vivo'},
'551799612':{'en': 'Vivo'},
'551799613':{'en': 'Vivo'},
'551799614':{'en': 'Vivo'},
'551799615':{'en': 'Vivo'},
'551799616':{'en': 'Vivo'},
'551799617':{'en': 'Vivo'},
'551799618':{'en': 'Vivo'},
'551799619':{'en': 'Vivo'},
'551799621':{'en': 'Vivo'},
'551799622':{'en': 'Vivo'},
'551799623':{'en': 'Vivo'},
'551799624':{'en': 'Vivo'},
'551799625':{'en': 'Vivo'},
'551799626':{'en': 'Vivo'},
'551799627':{'en': 'Vivo'},
'551799628':{'en': 'Vivo'},
'551799629':{'en': 'Vivo'},
'551799631':{'en': 'Vivo'},
'551799632':{'en': 'Vivo'},
'551799633':{'en': 'Vivo'},
'551799634':{'en': 'Vivo'},
'551799635':{'en': 'Vivo'},
'551799636':{'en': 'Vivo'},
'551799637':{'en': 'Vivo'},
'551799638':{'en': 'Vivo'},
'551799639':{'en': 'Vivo'},
'551799641':{'en': 'Vivo'},
'551799642':{'en': 'Vivo'},
'551799643':{'en': 'Vivo'},
'551799644':{'en': 'Vivo'},
'551799645':{'en': 'Vivo'},
'551799646':{'en': 'Vivo'},
'551799701':{'en': 'Vivo'},
'551799702':{'en': 'Vivo'},
'551799703':{'en': 'Vivo'},
'551799704':{'en': 'Vivo'},
'551799705':{'en': 'Vivo'},
'551799706':{'en': 'Vivo'},
'551799707':{'en': 'Vivo'},
'551799708':{'en': 'Vivo'},
'551799709':{'en': 'Vivo'},
'551799711':{'en': 'Vivo'},
'551799712':{'en': 'Vivo'},
'551799713':{'en': 'Vivo'},
'551799714':{'en': 'Vivo'},
'551799715':{'en': 'Vivo'},
'551799716':{'en': 'Vivo'},
'551799717':{'en': 'Vivo'},
'551799718':{'en': 'Vivo'},
'551799719':{'en': 'Vivo'},
'551799721':{'en': 'Vivo'},
'551799722':{'en': 'Vivo'},
'551799723':{'en': 'Vivo'},
'551799724':{'en': 'Vivo'},
'551799725':{'en': 'Vivo'},
'551799726':{'en': 'Vivo'},
'551799727':{'en': 'Vivo'},
'551799728':{'en': 'Vivo'},
'551799729':{'en': 'Vivo'},
'551799731':{'en': 'Vivo'},
'551799732':{'en': 'Vivo'},
'551799733':{'en': 'Vivo'},
'551799734':{'en': 'Vivo'},
'551799735':{'en': 'Vivo'},
'551799736':{'en': 'Vivo'},
'551799737':{'en': 'Vivo'},
'551799738':{'en': 'Vivo'},
'551799739':{'en': 'Vivo'},
'551799741':{'en': 'Vivo'},
'551799742':{'en': 'Vivo'},
'551799743':{'en': 'Vivo'},
'551799744':{'en': 'Vivo'},
'551799745':{'en': 'Vivo'},
'551799746':{'en': 'Vivo'},
'551799747':{'en': 'Vivo'},
'551799748':{'en': 'Vivo'},
'551799749':{'en': 'Vivo'},
'551799751':{'en': 'Vivo'},
'551799752':{'en': 'Vivo'},
'551799753':{'en': 'Vivo'},
'551799754':{'en': 'Vivo'},
'551799755':{'en': 'Vivo'},
'551799756':{'en': 'Vivo'},
'551799757':{'en': 'Vivo'},
'551799758':{'en': 'Vivo'},
'551799759':{'en': 'Vivo'},
'551799761':{'en': 'Vivo'},
'551799762':{'en': 'Vivo'},
'551799763':{'en': 'Vivo'},
'551799764':{'en': 'Vivo'},
'551799765':{'en': 'Vivo'},
'551799766':{'en': 'Vivo'},
'551799767':{'en': 'Vivo'},
'551799768':{'en': 'Vivo'},
'551799769':{'en': 'Vivo'},
'551799771':{'en': 'Vivo'},
'551799772':{'en': 'Vivo'},
'551799773':{'en': 'Vivo'},
'551799774':{'en': 'Vivo'},
'551799775':{'en': 'Vivo'},
'551799776':{'en': 'Vivo'},
'551799777':{'en': 'Vivo'},
'551799778':{'en': 'Vivo'},
'551799779':{'en': 'Vivo'},
'551799780':{'en': 'Vivo'},
'551799783':{'en': 'Vivo'},
'551799784':{'en': 'Vivo'},
'551799785':{'en': 'Vivo'},
'551799791':{'en': 'Vivo'},
'551898111':{'en': 'TIM'},
'551898112':{'en': 'TIM'},
'551898113':{'en': 'TIM'},
'551898114':{'en': 'TIM'},
'551898115':{'en': 'TIM'},
'551898116':{'en': 'TIM'},
'551898117':{'en': 'TIM'},
'551898118':{'en': 'TIM'},
'551898119':{'en': 'TIM'},
'551898121':{'en': 'TIM'},
'551898122':{'en': 'TIM'},
'551898123':{'en': 'TIM'},
'551898124':{'en': 'TIM'},
'551898125':{'en': 'TIM'},
'551898126':{'en': 'TIM'},
'551898127':{'en': 'TIM'},
'551898128':{'en': 'TIM'},
'551898129':{'en': 'TIM'},
'551898131':{'en': 'TIM'},
'551898132':{'en': 'TIM'},
'551898133':{'en': 'TIM'},
'551898134':{'en': 'TIM'},
'551898135':{'en': 'TIM'},
'551898136':{'en': 'TIM'},
'551898137':{'en': 'TIM'},
'551898138':{'en': 'TIM'},
'551898139':{'en': 'TIM'},
'551898141':{'en': 'TIM'},
'551898142':{'en': 'TIM'},
'551898143':{'en': 'TIM'},
'551898144':{'en': 'TIM'},
'551898145':{'en': 'TIM'},
'551898146':{'en': 'TIM'},
'551898147':{'en': 'TIM'},
'551898148':{'en': 'TIM'},
'551898149':{'en': 'TIM'},
'551898151':{'en': 'TIM'},
'551898810':{'en': 'Oi'},
'551898811':{'en': 'Oi'},
'55189910':{'en': 'Claro BR'},
'55189911':{'en': 'Claro BR'},
'55189912':{'en': 'Claro BR'},
'55189913':{'en': 'Claro BR'},
'55189914':{'en': 'Claro BR'},
'55189915':{'en': 'Claro BR'},
'55189916':{'en': 'Claro BR'},
'55189917':{'en': 'Claro BR'},
'551899180':{'en': 'Claro BR'},
'551899197':{'en': 'Claro BR'},
'551899198':{'en': 'Claro BR'},
'551899199':{'en': 'Claro BR'},
'551899601':{'en': 'Vivo'},
'551899602':{'en': 'Vivo'},
'551899603':{'en': 'Vivo'},
'551899604':{'en': 'Vivo'},
'551899605':{'en': 'Vivo'},
'551899606':{'en': 'Vivo'},
'551899607':{'en': 'Vivo'},
'551899608':{'en': 'Vivo'},
'551899609':{'en': 'Vivo'},
'551899611':{'en': 'Vivo'},
'551899612':{'en': 'Vivo'},
'551899613':{'en': 'Vivo'},
'551899614':{'en': 'Vivo'},
'551899615':{'en': 'Vivo'},
'551899616':{'en': 'Vivo'},
'551899617':{'en': 'Vivo'},
'551899618':{'en': 'Vivo'},
'551899621':{'en': 'Vivo'},
'551899622':{'en': 'Vivo'},
'551899623':{'en': 'Vivo'},
'551899624':{'en': 'Vivo'},
'551899625':{'en': 'Vivo'},
'551899626':{'en': 'Vivo'},
'551899627':{'en': 'Vivo'},
'551899628':{'en': 'Vivo'},
'551899629':{'en': 'Vivo'},
'551899631':{'en': 'Vivo'},
'551899632':{'en': 'Vivo'},
'551899633':{'en': 'Vivo'},
'551899634':{'en': 'Vivo'},
'551899635':{'en': 'Vivo'},
'551899636':{'en': 'Vivo'},
'551899637':{'en': 'Vivo'},
'551899638':{'en': 'Vivo'},
'551899639':{'en': 'Vivo'},
'551899641':{'en': 'Vivo'},
'551899642':{'en': 'Vivo'},
'551899643':{'en': 'Vivo'},
'551899644':{'en': 'Vivo'},
'551899645':{'en': 'Vivo'},
'551899646':{'en': 'Vivo'},
'551899647':{'en': 'Vivo'},
'551899648':{'en': 'Vivo'},
'551899649':{'en': 'Vivo'},
'551899651':{'en': 'Vivo'},
'551899652':{'en': 'Vivo'},
'551899653':{'en': 'Vivo'},
'551899654':{'en': 'Vivo'},
'551899655':{'en': 'Vivo'},
'551899656':{'en': 'Vivo'},
'551899657':{'en': 'Vivo'},
'551899658':{'en': 'Vivo'},
'551899659':{'en': 'Vivo'},
'551899661':{'en': 'Vivo'},
'551899662':{'en': 'Vivo'},
'551899663':{'en': 'Vivo'},
'551899664':{'en': 'Vivo'},
'551899665':{'en': 'Vivo'},
'551899666':{'en': 'Vivo'},
'551899667':{'en': 'Vivo'},
'551899668':{'en': 'Vivo'},
'551899669':{'en': 'Vivo'},
'551899671':{'en': 'Vivo'},
'551899672':{'en': 'Vivo'},
'551899673':{'en': 'Vivo'},
'551899674':{'en': 'Vivo'},
'551899675':{'en': 'Vivo'},
'551899676':{'en': 'Vivo'},
'551899677':{'en': 'Vivo'},
'551899678':{'en': 'Vivo'},
'551899679':{'en': 'Vivo'},
'551899681':{'en': 'Vivo'},
'551899682':{'en': 'Vivo'},
'551899683':{'en': 'Vivo'},
'551899684':{'en': 'Vivo'},
'551899685':{'en': 'Vivo'},
'551899686':{'en': 'Vivo'},
'551899687':{'en': 'Vivo'},
'551899701':{'en': 'Vivo'},
'551899702':{'en': 'Vivo'},
'551899703':{'en': 'Vivo'},
'551899704':{'en': 'Vivo'},
'551899705':{'en': 'Vivo'},
'551899706':{'en': 'Vivo'},
'551899707':{'en': 'Vivo'},
'551899708':{'en': 'Vivo'},
'551899709':{'en': 'Vivo'},
'551899711':{'en': 'Vivo'},
'551899712':{'en': 'Vivo'},
'551899713':{'en': 'Vivo'},
'551899714':{'en': 'Vivo'},
'551899715':{'en': 'Vivo'},
'551899716':{'en': 'Vivo'},
'551899717':{'en': 'Vivo'},
'551899718':{'en': 'Vivo'},
'551899719':{'en': 'Vivo'},
'551899721':{'en': 'Vivo'},
'551899722':{'en': 'Vivo'},
'551899723':{'en': 'Vivo'},
'551899724':{'en': 'Vivo'},
'551899725':{'en': 'Vivo'},
'551899726':{'en': 'Vivo'},
'551899727':{'en': 'Vivo'},
'551899728':{'en': 'Vivo'},
'551899729':{'en': 'Vivo'},
'551899731':{'en': 'Vivo'},
'551899732':{'en': 'Vivo'},
'551899733':{'en': 'Vivo'},
'551899734':{'en': 'Vivo'},
'551899735':{'en': 'Vivo'},
'551899736':{'en': 'Vivo'},
'551899737':{'en': 'Vivo'},
'551899738':{'en': 'Vivo'},
'551899739':{'en': 'Vivo'},
'551899741':{'en': 'Vivo'},
'551899742':{'en': 'Vivo'},
'551899743':{'en': 'Vivo'},
'551899744':{'en': 'Vivo'},
'551899745':{'en': 'Vivo'},
'551899746':{'en': 'Vivo'},
'551899747':{'en': 'Vivo'},
'551899748':{'en': 'Vivo'},
'551899749':{'en': 'Vivo'},
'551899751':{'en': 'Vivo'},
'551899752':{'en': 'Vivo'},
'551899753':{'en': 'Vivo'},
'551899754':{'en': 'Vivo'},
'551899755':{'en': 'Vivo'},
'551899756':{'en': 'Vivo'},
'551899757':{'en': 'Vivo'},
'551899758':{'en': 'Vivo'},
'551899759':{'en': 'Vivo'},
'551899761':{'en': 'Vivo'},
'551899762':{'en': 'Vivo'},
'551899763':{'en': 'Vivo'},
'551899764':{'en': 'Vivo'},
'551899765':{'en': 'Vivo'},
'551899766':{'en': 'Vivo'},
'551899767':{'en': 'Vivo'},
'551899768':{'en': 'Vivo'},
'551899771':{'en': 'Vivo'},
'551899772':{'en': 'Vivo'},
'551899773':{'en': 'Vivo'},
'551899774':{'en': 'Vivo'},
'551899775':{'en': 'Vivo'},
'551899776':{'en': 'Vivo'},
'551899777':{'en': 'Vivo'},
'551899778':{'en': 'Vivo'},
'551899779':{'en': 'Vivo'},
'55189978':{'en': 'Vivo'},
'551899791':{'en': 'Vivo'},
'551899792':{'en': 'Vivo'},
'551899793':{'en': 'Vivo'},
'551899794':{'en': 'Vivo'},
'551899795':{'en': 'Vivo'},
'551899796':{'en': 'Vivo'},
'551899797':{'en': 'Vivo'},
'551899798':{'en': 'Vivo'},
'551899799':{'en': 'Vivo'},
'5519981':{'en': 'TIM'},
'551998201':{'en': 'TIM'},
'551998202':{'en': 'TIM'},
'551998203':{'en': 'TIM'},
'551998204':{'en': 'TIM'},
'551998205':{'en': 'TIM'},
'551998206':{'en': 'TIM'},
'551998207':{'en': 'TIM'},
'551998208':{'en': 'TIM'},
'551998209':{'en': 'TIM'},
'551998211':{'en': 'TIM'},
'551998212':{'en': 'TIM'},
'551998213':{'en': 'TIM'},
'551998214':{'en': 'TIM'},
'551998215':{'en': 'TIM'},
'551998216':{'en': 'TIM'},
'551998217':{'en': 'TIM'},
'551998218':{'en': 'TIM'},
'551998219':{'en': 'TIM'},
'551998221':{'en': 'TIM'},
'551998222':{'en': 'TIM'},
'551998223':{'en': 'TIM'},
'551998224':{'en': 'TIM'},
'551998225':{'en': 'TIM'},
'551998226':{'en': 'TIM'},
'551998227':{'en': 'TIM'},
'551998229':{'en': 'TIM'},
'5519991':{'en': 'Claro BR'},
'5519992':{'en': 'Claro BR'},
'5519993':{'en': 'Claro BR'},
'5519994':{'en': 'Claro BR'},
'551999500':{'en': 'Claro BR'},
'551999501':{'en': 'Claro BR'},
'551999502':{'en': 'Claro BR'},
'551999503':{'en': 'Claro BR'},
'551999504':{'en': 'Claro BR'},
'551999505':{'en': 'Claro BR'},
'551999506':{'en': 'Claro BR'},
'551999507':{'en': 'Claro BR'},
'551999508':{'en': 'Claro BR'},
'551999601':{'en': 'Vivo'},
'551999602':{'en': 'Vivo'},
'551999603':{'en': 'Vivo'},
'551999604':{'en': 'Vivo'},
'551999605':{'en': 'Vivo'},
'551999606':{'en': 'Vivo'},
'551999607':{'en': 'Vivo'},
'551999608':{'en': 'Vivo'},
'551999609':{'en': 'Vivo'},
'55199961':{'en': 'Vivo'},
'551999621':{'en': 'Vivo'},
'551999622':{'en': 'Vivo'},
'551999623':{'en': 'Vivo'},
'551999624':{'en': 'Vivo'},
'551999625':{'en': 'Vivo'},
'551999626':{'en': 'Vivo'},
'551999627':{'en': 'Vivo'},
'551999628':{'en': 'Vivo'},
'551999629':{'en': 'Vivo'},
'551999631':{'en': 'Vivo'},
'551999632':{'en': 'Vivo'},
'551999633':{'en': 'Vivo'},
'551999634':{'en': 'Vivo'},
'551999635':{'en': 'Vivo'},
'551999636':{'en': 'Vivo'},
'551999637':{'en': 'Vivo'},
'551999638':{'en': 'Vivo'},
'551999639':{'en': 'Vivo'},
'551999641':{'en': 'Vivo'},
'551999642':{'en': 'Vivo'},
'551999643':{'en': 'Vivo'},
'551999644':{'en': 'Vivo'},
'551999645':{'en': 'Vivo'},
'551999646':{'en': 'Vivo'},
'551999647':{'en': 'Vivo'},
'551999648':{'en': 'Vivo'},
'551999649':{'en': 'Vivo'},
'551999651':{'en': 'Vivo'},
'551999652':{'en': 'Vivo'},
'551999653':{'en': 'Vivo'},
'551999654':{'en': 'Vivo'},
'551999655':{'en': 'Vivo'},
'551999656':{'en': 'Vivo'},
'551999657':{'en': 'Vivo'},
'551999658':{'en': 'Vivo'},
'551999659':{'en': 'Vivo'},
'551999661':{'en': 'Vivo'},
'551999662':{'en': 'Vivo'},
'551999663':{'en': 'Vivo'},
'551999664':{'en': 'Vivo'},
'551999665':{'en': 'Vivo'},
'551999666':{'en': 'Vivo'},
'551999667':{'en': 'Vivo'},
'551999668':{'en': 'Vivo'},
'551999669':{'en': 'Vivo'},
'551999671':{'en': 'Vivo'},
'551999672':{'en': 'Vivo'},
'551999673':{'en': 'Vivo'},
'551999674':{'en': 'Vivo'},
'551999675':{'en': 'Vivo'},
'551999676':{'en': 'Vivo'},
'551999677':{'en': 'Vivo'},
'551999678':{'en': 'Vivo'},
'551999679':{'en': 'Vivo'},
'551999681':{'en': 'Vivo'},
'551999682':{'en': 'Vivo'},
'551999683':{'en': 'Vivo'},
'551999684':{'en': 'Vivo'},
'551999685':{'en': 'Vivo'},
'551999686':{'en': 'Vivo'},
'551999687':{'en': 'Vivo'},
'551999688':{'en': 'Vivo'},
'551999689':{'en': 'Vivo'},
'551999691':{'en': 'Vivo'},
'551999692':{'en': 'Vivo'},
'551999693':{'en': 'Vivo'},
'551999694':{'en': 'Vivo'},
'551999695':{'en': 'Vivo'},
'551999696':{'en': 'Vivo'},
'551999697':{'en': 'Vivo'},
'551999698':{'en': 'Vivo'},
'551999699':{'en': 'Vivo'},
'55199970':{'en': 'Vivo'},
'55199971':{'en': 'Vivo'},
'55199972':{'en': 'Vivo'},
'55199973':{'en': 'Vivo'},
'55199974':{'en': 'Vivo'},
'551999751':{'en': 'Vivo'},
'551999752':{'en': 'Vivo'},
'551999753':{'en': 'Vivo'},
'551999754':{'en': 'Vivo'},
'551999755':{'en': 'Vivo'},
'551999756':{'en': 'Vivo'},
'551999757':{'en': 'Vivo'},
'551999758':{'en': 'Vivo'},
'551999759':{'en': 'Vivo'},
'551999761':{'en': 'Vivo'},
'551999762':{'en': 'Vivo'},
'551999763':{'en': 'Vivo'},
'551999764':{'en': 'Vivo'},
'551999765':{'en': 'Vivo'},
'551999766':{'en': 'Vivo'},
'551999767':{'en': 'Vivo'},
'551999768':{'en': 'Vivo'},
'551999769':{'en': 'Vivo'},
'551999771':{'en': 'Vivo'},
'551999772':{'en': 'Vivo'},
'551999773':{'en': 'Vivo'},
'551999774':{'en': 'Vivo'},
'551999775':{'en': 'Vivo'},
'551999776':{'en': 'Vivo'},
'551999777':{'en': 'Vivo'},
'551999778':{'en': 'Vivo'},
'551999779':{'en': 'Vivo'},
'55199978':{'en': 'Vivo'},
'55199979':{'en': 'Vivo'},
'55199980':{'en': 'Vivo'},
'55199981':{'en': 'Vivo'},
'55199982':{'en': 'Vivo'},
'55199983':{'en': 'Vivo'},
'55199984':{'en': 'Vivo'},
'55199985':{'en': 'Vivo'},
'55199986':{'en': 'Vivo'},
'55199987':{'en': 'Vivo'},
'55199988':{'en': 'Vivo'},
'551999890':{'en': 'Vivo'},
'5521971':{'en': 'Vivo'},
'5521972':{'en': 'Vivo'},
'55219730':{'en': 'Claro BR'},
'55219731':{'en': 'Claro BR'},
'55219732':{'en': 'Claro BR'},
'55219733':{'en': 'Claro BR'},
'55219734':{'en': 'Claro BR'},
'55219735':{'en': 'Claro BR'},
'55219736':{'en': 'Claro BR'},
'552197370':{'en': 'Claro BR'},
'552197371':{'en': 'Claro BR'},
'552197372':{'en': 'Claro BR'},
'552197373':{'en': 'Claro BR'},
'5521974':{'en': 'Claro BR'},
'5521975':{'en': 'Claro BR'},
'5521976':{'en': 'Claro BR'},
'5521981':{'en': 'TIM'},
'5521982':{'en': 'TIM'},
'552198301':{'en': 'TIM'},
'552198302':{'en': 'TIM'},
'552198303':{'en': 'TIM'},
'552198304':{'en': 'TIM'},
'552198305':{'en': 'TIM'},
'552198306':{'en': 'TIM'},
'552198307':{'en': 'TIM'},
'552198308':{'en': 'TIM'},
'552198309':{'en': 'TIM'},
'552198311':{'en': 'TIM'},
'552198312':{'en': 'TIM'},
'552198313':{'en': 'TIM'},
'552198314':{'en': 'TIM'},
'552198315':{'en': 'TIM'},
'552198316':{'en': 'TIM'},
'552198317':{'en': 'TIM'},
'552198318':{'en': 'TIM'},
'552198319':{'en': 'TIM'},
'552198321':{'en': 'TIM'},
'552198322':{'en': 'TIM'},
'552198323':{'en': 'TIM'},
'552198324':{'en': 'TIM'},
'552198325':{'en': 'TIM'},
'552198326':{'en': 'TIM'},
'552198327':{'en': 'TIM'},
'552198328':{'en': 'TIM'},
'552198329':{'en': 'TIM'},
'552198331':{'en': 'TIM'},
'552198332':{'en': 'TIM'},
'552198333':{'en': 'TIM'},
'552198334':{'en': 'TIM'},
'552198335':{'en': 'TIM'},
'552198336':{'en': 'TIM'},
'552198337':{'en': 'TIM'},
'552198338':{'en': 'TIM'},
'552198339':{'en': 'TIM'},
'552198341':{'en': 'TIM'},
'552198342':{'en': 'TIM'},
'552198343':{'en': 'TIM'},
'552198344':{'en': 'TIM'},
'552198345':{'en': 'TIM'},
'552198346':{'en': 'TIM'},
'552198347':{'en': 'TIM'},
'552198348':{'en': 'TIM'},
'552198349':{'en': 'TIM'},
'552198351':{'en': 'TIM'},
'552198352':{'en': 'TIM'},
'552198353':{'en': 'TIM'},
'552198354':{'en': 'TIM'},
'552198355':{'en': 'TIM'},
'552198356':{'en': 'TIM'},
'552198357':{'en': 'TIM'},
'552198358':{'en': 'TIM'},
'552198359':{'en': 'TIM'},
'552198361':{'en': 'TIM'},
'552198362':{'en': 'TIM'},
'552198363':{'en': 'TIM'},
'552198364':{'en': 'TIM'},
'552198365':{'en': 'TIM'},
'552198366':{'en': 'TIM'},
'552198367':{'en': 'TIM'},
'552198368':{'en': 'TIM'},
'552198369':{'en': 'TIM'},
'552198371':{'en': 'TIM'},
'552198372':{'en': 'TIM'},
'552198373':{'en': 'TIM'},
'552198374':{'en': 'TIM'},
'552198375':{'en': 'TIM'},
'552198376':{'en': 'TIM'},
'552198377':{'en': 'TIM'},
'552198378':{'en': 'TIM'},
'552198379':{'en': 'TIM'},
'552198381':{'en': 'TIM'},
'552198382':{'en': 'TIM'},
'552198383':{'en': 'TIM'},
'552198384':{'en': 'TIM'},
'552198385':{'en': 'TIM'},
'552198386':{'en': 'TIM'},
'552198401':{'en': 'Oi'},
'552198402':{'en': 'Oi'},
'552198403':{'en': 'Oi'},
'552198404':{'en': 'Oi'},
'552198405':{'en': 'Oi'},
'552198406':{'en': 'Oi'},
'552198407':{'en': 'Oi'},
'552198408':{'en': 'Oi'},
'552198409':{'en': 'Oi'},
'552198411':{'en': 'Oi'},
'552198412':{'en': 'Oi'},
'552198413':{'en': 'Oi'},
'552198414':{'en': 'Oi'},
'552198415':{'en': 'Oi'},
'552198416':{'en': 'Oi'},
'552198417':{'en': 'Oi'},
'552198418':{'en': 'Oi'},
'552198419':{'en': 'Oi'},
'5521985':{'en': 'Oi'},
'5521986':{'en': 'Oi'},
'5521987':{'en': 'Oi'},
'5521988':{'en': 'Oi'},
'5521989':{'en': 'Oi'},
'5521991':{'en': 'Claro BR'},
'5521992':{'en': 'Claro BR'},
'5521993':{'en': 'Claro BR'},
'5521994':{'en': 'Claro BR'},
'5521995':{'en': 'Vivo'},
'5521996':{'en': 'Vivo'},
'5521997':{'en': 'Vivo'},
'5521998':{'en': 'Vivo'},
'5521999':{'en': 'Vivo'},
'552298111':{'en': 'TIM'},
'552298112':{'en': 'TIM'},
'552298113':{'en': 'TIM'},
'552298114':{'en': 'TIM'},
'552298115':{'en': 'TIM'},
'552298116':{'en': 'TIM'},
'552298117':{'en': 'TIM'},
'552298118':{'en': 'TIM'},
'552298119':{'en': 'TIM'},
'552298121':{'en': 'TIM'},
'552298122':{'en': 'TIM'},
'552298123':{'en': 'TIM'},
'552298124':{'en': 'TIM'},
'552298125':{'en': 'TIM'},
'552298126':{'en': 'TIM'},
'552298127':{'en': 'TIM'},
'552298128':{'en': 'TIM'},
'552298129':{'en': 'TIM'},
'552298131':{'en': 'TIM'},
'552298132':{'en': 'TIM'},
'552298133':{'en': 'TIM'},
'552298134':{'en': 'TIM'},
'552298135':{'en': 'TIM'},
'552298136':{'en': 'TIM'},
'552298137':{'en': 'TIM'},
'552298138':{'en': 'TIM'},
'552298139':{'en': 'TIM'},
'552298141':{'en': 'TIM'},
'552298142':{'en': 'TIM'},
'552298143':{'en': 'TIM'},
'552298144':{'en': 'TIM'},
'552298145':{'en': 'TIM'},
'552298146':{'en': 'TIM'},
'552298147':{'en': 'TIM'},
'552298148':{'en': 'TIM'},
'552298149':{'en': 'TIM'},
'552298151':{'en': 'TIM'},
'5522985':{'en': 'Oi'},
'5522986':{'en': 'Oi'},
'5522987':{'en': 'Oi'},
'5522988':{'en': 'Oi'},
'5522989':{'en': 'Oi'},
'552299101':{'en': 'Claro BR'},
'552299102':{'en': 'Claro BR'},
'552299103':{'en': 'Claro BR'},
'552299104':{'en': 'Claro BR'},
'552299105':{'en': 'Claro BR'},
'552299201':{'en': 'Claro BR'},
'552299202':{'en': 'Claro BR'},
'552299203':{'en': 'Claro BR'},
'552299204':{'en': 'Claro BR'},
'552299205':{'en': 'Claro BR'},
'552299206':{'en': 'Claro BR'},
'552299207':{'en': 'Claro BR'},
'552299208':{'en': 'Claro BR'},
'552299209':{'en': 'Claro BR'},
'552299211':{'en': 'Claro BR'},
'552299212':{'en': 'Claro BR'},
'552299213':{'en': 'Claro BR'},
'552299214':{'en': 'Claro BR'},
'552299215':{'en': 'Claro BR'},
'552299216':{'en': 'Claro BR'},
'552299217':{'en': 'Claro BR'},
'552299218':{'en': 'Claro BR'},
'552299219':{'en': 'Claro BR'},
'552299221':{'en': 'Claro BR'},
'552299222':{'en': 'Claro BR'},
'552299223':{'en': 'Claro BR'},
'552299224':{'en': 'Claro BR'},
'552299225':{'en': 'Claro BR'},
'552299226':{'en': 'Claro BR'},
'552299227':{'en': 'Claro BR'},
'552299228':{'en': 'Claro BR'},
'552299229':{'en': 'Claro BR'},
'552299231':{'en': 'Claro BR'},
'552299232':{'en': 'Claro BR'},
'552299233':{'en': 'Claro BR'},
'552299234':{'en': 'Claro BR'},
'552299235':{'en': 'Claro BR'},
'552299236':{'en': 'Claro BR'},
'552299237':{'en': 'Claro BR'},
'552299238':{'en': 'Claro BR'},
'552299239':{'en': 'Claro BR'},
'552299241':{'en': 'Claro BR'},
'552299242':{'en': 'Claro BR'},
'552299243':{'en': 'Claro BR'},
'552299244':{'en': 'Claro BR'},
'552299245':{'en': 'Claro BR'},
'552299246':{'en': 'Claro BR'},
'552299247':{'en': 'Claro BR'},
'552299248':{'en': 'Claro BR'},
'552299249':{'en': 'Claro BR'},
'552299251':{'en': 'Claro BR'},
'552299252':{'en': 'Claro BR'},
'552299253':{'en': 'Claro BR'},
'552299254':{'en': 'Claro BR'},
'552299255':{'en': 'Claro BR'},
'552299256':{'en': 'Claro BR'},
'552299257':{'en': 'Claro BR'},
'552299258':{'en': 'Claro BR'},
'552299259':{'en': 'Claro BR'},
'552299261':{'en': 'Claro BR'},
'552299262':{'en': 'Claro BR'},
'552299263':{'en': 'Claro BR'},
'552299264':{'en': 'Claro BR'},
'552299265':{'en': 'Claro BR'},
'552299266':{'en': 'Claro BR'},
'552299267':{'en': 'Claro BR'},
'552299268':{'en': 'Claro BR'},
'552299269':{'en': 'Claro BR'},
'552299271':{'en': 'Claro BR'},
'552299272':{'en': 'Claro BR'},
'552299273':{'en': 'Claro BR'},
'552299274':{'en': 'Claro BR'},
'552299275':{'en': 'Claro BR'},
'552299276':{'en': 'Claro BR'},
'552299277':{'en': 'Claro BR'},
'552299278':{'en': 'Claro BR'},
'552299279':{'en': 'Claro BR'},
'552299281':{'en': 'Claro BR'},
'552299282':{'en': 'Claro BR'},
'552299283':{'en': 'Claro BR'},
'552299284':{'en': 'Claro BR'},
'552299285':{'en': 'Claro BR'},
'552299286':{'en': 'Claro BR'},
'552299287':{'en': 'Claro BR'},
'552299288':{'en': 'Claro BR'},
'552299289':{'en': 'Claro BR'},
'55229970':{'en': 'Vivo'},
'55229971':{'en': 'Vivo'},
'55229972':{'en': 'Vivo'},
'55229973':{'en': 'Vivo'},
'55229974':{'en': 'Vivo'},
'55229975':{'en': 'Vivo'},
'552299760':{'en': 'Vivo'},
'552299761':{'en': 'Vivo'},
'552299762':{'en': 'Vivo'},
'552299763':{'en': 'Vivo'},
'552299764':{'en': 'Vivo'},
'552299765':{'en': 'Vivo'},
'552299766':{'en': 'Vivo'},
'552299767':{'en': 'Vivo'},
'5522998':{'en': 'Vivo'},
'5522999':{'en': 'Vivo'},
'552498111':{'en': 'TIM'},
'552498112':{'en': 'TIM'},
'552498113':{'en': 'TIM'},
'552498114':{'en': 'TIM'},
'552498115':{'en': 'TIM'},
'552498116':{'en': 'TIM'},
'552498117':{'en': 'TIM'},
'552498118':{'en': 'TIM'},
'552498119':{'en': 'TIM'},
'552498121':{'en': 'TIM'},
'552498122':{'en': 'TIM'},
'552498123':{'en': 'TIM'},
'552498124':{'en': 'TIM'},
'552498125':{'en': 'TIM'},
'552498126':{'en': 'TIM'},
'552498127':{'en': 'TIM'},
'552498128':{'en': 'TIM'},
'552498129':{'en': 'TIM'},
'552498131':{'en': 'TIM'},
'552498132':{'en': 'TIM'},
'552498133':{'en': 'TIM'},
'552498134':{'en': 'TIM'},
'552498135':{'en': 'TIM'},
'552498136':{'en': 'TIM'},
'552498137':{'en': 'TIM'},
'552498138':{'en': 'TIM'},
'552498139':{'en': 'TIM'},
'552498141':{'en': 'TIM'},
'552498142':{'en': 'TIM'},
'552498143':{'en': 'TIM'},
'552498144':{'en': 'TIM'},
'552498145':{'en': 'TIM'},
'552498182':{'en': 'TIM'},
'5524985':{'en': 'Oi'},
'5524986':{'en': 'Oi'},
'5524987':{'en': 'Oi'},
'5524988':{'en': 'Oi'},
'5524989':{'en': 'Oi'},
'55249920':{'en': 'Claro BR'},
'55249921':{'en': 'Claro BR'},
'55249922':{'en': 'Claro BR'},
'55249923':{'en': 'Claro BR'},
'55249924':{'en': 'Claro BR'},
'55249925':{'en': 'Claro BR'},
'55249926':{'en': 'Claro BR'},
'55249927':{'en': 'Claro BR'},
'552499280':{'en': 'Claro BR'},
'552499281':{'en': 'Claro BR'},
'552499282':{'en': 'Claro BR'},
'552499291':{'en': 'Claro BR'},
'552499292':{'en': 'Claro BR'},
'552499293':{'en': 'Claro BR'},
'552499294':{'en': 'Claro BR'},
'552499295':{'en': 'Claro BR'},
'552499296':{'en': 'Claro BR'},
'552499297':{'en': 'Claro BR'},
'552499298':{'en': 'Claro BR'},
'552499299':{'en': 'Claro BR'},
'552499301':{'en': 'Claro BR'},
'552499395':{'en': 'Claro BR'},
'55249962':{'en': 'Vivo'},
'55249963':{'en': 'Vivo'},
'55249964':{'en': 'Vivo'},
'55249965':{'en': 'Vivo'},
'55249966':{'en': 'Vivo'},
'55249967':{'en': 'Vivo'},
'55249968':{'en': 'Vivo'},
'55249969':{'en': 'Vivo'},
'5524997':{'en': 'Vivo'},
'5524998':{'en': 'Vivo'},
'55249990':{'en': 'Vivo'},
'55249991':{'en': 'Vivo'},
'552499920':{'en': 'Vivo'},
'552499921':{'en': 'Vivo'},
'552499922':{'en': 'Vivo'},
'552499923':{'en': 'Vivo'},
'552499924':{'en': 'Vivo'},
'552499925':{'en': 'Vivo'},
'55249994':{'en': 'Vivo'},
'55249995':{'en': 'Vivo'},
'55249996':{'en': 'Vivo'},
'55249997':{'en': 'Vivo'},
'55249998':{'en': 'Vivo'},
'55249999':{'en': 'Vivo'},
'552798111':{'en': 'TIM'},
'552798112':{'en': 'TIM'},
'552798113':{'en': 'TIM'},
'552798114':{'en': 'TIM'},
'552798115':{'en': 'TIM'},
'552798116':{'en': 'TIM'},
'552798117':{'en': 'TIM'},
'552798118':{'en': 'TIM'},
'552798119':{'en': 'TIM'},
'552798121':{'en': 'TIM'},
'552798122':{'en': 'TIM'},
'552798123':{'en': 'TIM'},
'552798124':{'en': 'TIM'},
'552798125':{'en': 'TIM'},
'552798126':{'en': 'TIM'},
'552798127':{'en': 'TIM'},
'552798128':{'en': 'TIM'},
'552798129':{'en': 'TIM'},
'552798131':{'en': 'TIM'},
'552798132':{'en': 'TIM'},
'552798133':{'en': 'TIM'},
'552798134':{'en': 'TIM'},
'552798135':{'en': 'TIM'},
'552798136':{'en': 'TIM'},
'552798137':{'en': 'TIM'},
'552798138':{'en': 'TIM'},
'552798139':{'en': 'TIM'},
'552798141':{'en': 'TIM'},
'552798142':{'en': 'TIM'},
'552798143':{'en': 'TIM'},
'552798144':{'en': 'TIM'},
'552798145':{'en': 'TIM'},
'552798146':{'en': 'TIM'},
'552798147':{'en': 'TIM'},
'552798148':{'en': 'TIM'},
'552798149':{'en': 'TIM'},
'552798151':{'en': 'TIM'},
'552798152':{'en': 'TIM'},
'552798153':{'en': 'TIM'},
'552798154':{'en': 'TIM'},
'552798155':{'en': 'TIM'},
'552798156':{'en': 'TIM'},
'552798157':{'en': 'TIM'},
'552798158':{'en': 'TIM'},
'552798159':{'en': 'TIM'},
'552798161':{'en': 'TIM'},
'552798162':{'en': 'TIM'},
'552798163':{'en': 'TIM'},
'552798164':{'en': 'TIM'},
'552798165':{'en': 'TIM'},
'552798166':{'en': 'TIM'},
'552798167':{'en': 'TIM'},
'552798168':{'en': 'TIM'},
'552798169':{'en': 'TIM'},
'552798171':{'en': 'TIM'},
'552798172':{'en': 'TIM'},
'552798173':{'en': 'TIM'},
'552798174':{'en': 'TIM'},
'552798175':{'en': 'TIM'},
'552798176':{'en': 'TIM'},
'552798177':{'en': 'TIM'},
'552798178':{'en': 'TIM'},
'552798182':{'en': 'TIM'},
'5527985':{'en': 'Oi'},
'5527986':{'en': 'Oi'},
'5527987':{'en': 'Oi'},
'5527988':{'en': 'Oi'},
'5527989':{'en': 'Oi'},
'552799201':{'en': 'Claro BR'},
'552799202':{'en': 'Claro BR'},
'552799203':{'en': 'Claro BR'},
'552799204':{'en': 'Claro BR'},
'552799205':{'en': 'Claro BR'},
'552799222':{'en': 'Claro BR'},
'552799223':{'en': 'Claro BR'},
'552799224':{'en': 'Claro BR'},
'552799225':{'en': 'Claro BR'},
'552799226':{'en': 'Claro BR'},
'552799227':{'en': 'Claro BR'},
'552799228':{'en': 'Claro BR'},
'552799229':{'en': 'Claro BR'},
'552799231':{'en': 'Claro BR'},
'552799232':{'en': 'Claro BR'},
'552799233':{'en': 'Claro BR'},
'552799234':{'en': 'Claro BR'},
'552799235':{'en': 'Claro BR'},
'552799236':{'en': 'Claro BR'},
'552799237':{'en': 'Claro BR'},
'552799238':{'en': 'Claro BR'},
'552799239':{'en': 'Claro BR'},
'552799241':{'en': 'Claro BR'},
'552799242':{'en': 'Claro BR'},
'552799243':{'en': 'Claro BR'},
'552799244':{'en': 'Claro BR'},
'552799245':{'en': 'Claro BR'},
'552799246':{'en': 'Claro BR'},
'552799247':{'en': 'Claro BR'},
'552799248':{'en': 'Claro BR'},
'552799249':{'en': 'Claro BR'},
'552799251':{'en': 'Claro BR'},
'552799252':{'en': 'Claro BR'},
'552799253':{'en': 'Claro BR'},
'552799254':{'en': 'Claro BR'},
'552799255':{'en': 'Claro BR'},
'552799256':{'en': 'Claro BR'},
'552799257':{'en': 'Claro BR'},
'552799258':{'en': 'Claro BR'},
'552799259':{'en': 'Claro BR'},
'552799261':{'en': 'Claro BR'},
'552799262':{'en': 'Claro BR'},
'552799263':{'en': 'Claro BR'},
'552799264':{'en': 'Claro BR'},
'552799265':{'en': 'Claro BR'},
'552799266':{'en': 'Claro BR'},
'552799267':{'en': 'Claro BR'},
'552799268':{'en': 'Claro BR'},
'552799269':{'en': 'Claro BR'},
'552799271':{'en': 'Claro BR'},
'552799272':{'en': 'Claro BR'},
'552799273':{'en': 'Claro BR'},
'552799274':{'en': 'Claro BR'},
'552799275':{'en': 'Claro BR'},
'552799276':{'en': 'Claro BR'},
'552799277':{'en': 'Claro BR'},
'552799278':{'en': 'Claro BR'},
'552799279':{'en': 'Claro BR'},
'552799281':{'en': 'Claro BR'},
'552799282':{'en': 'Claro BR'},
'552799283':{'en': 'Claro BR'},
'552799284':{'en': 'Claro BR'},
'552799285':{'en': 'Claro BR'},
'552799286':{'en': 'Claro BR'},
'552799287':{'en': 'Claro BR'},
'552799288':{'en': 'Claro BR'},
'552799289':{'en': 'Claro BR'},
'552799291':{'en': 'Claro BR'},
'552799292':{'en': 'Claro BR'},
'552799293':{'en': 'Claro BR'},
'552799294':{'en': 'Claro BR'},
'552799295':{'en': 'Claro BR'},
'552799296':{'en': 'Claro BR'},
'552799297':{'en': 'Claro BR'},
'552799298':{'en': 'Claro BR'},
'552799299':{'en': 'Claro BR'},
'552799309':{'en': 'Claro BR'},
'552799311':{'en': 'Claro BR'},
'552799312':{'en': 'Claro BR'},
'552799316':{'en': 'Claro BR'},
'55279960':{'en': 'Vivo'},
'55279961':{'en': 'Vivo'},
'55279962':{'en': 'Vivo'},
'55279963':{'en': 'Vivo'},
'55279964':{'en': 'Vivo'},
'552799650':{'en': 'Vivo'},
'552799651':{'en': 'Vivo'},
'552799652':{'en': 'Vivo'},
'552799653':{'en': 'Vivo'},
'5527997':{'en': 'Vivo'},
'5527998':{'en': 'Vivo'},
'5527999':{'en': 'Vivo'},
'552898111':{'en': 'TIM'},
'552898112':{'en': 'TIM'},
'552898113':{'en': 'TIM'},
'552898114':{'en': 'TIM'},
'552898115':{'en': 'TIM'},
'552898116':{'en': 'TIM'},
'552898117':{'en': 'TIM'},
'552898118':{'en': 'TIM'},
'552898119':{'en': 'TIM'},
'5528985':{'en': 'Oi'},
'5528986':{'en': 'Oi'},
'5528987':{'en': 'Oi'},
'5528988':{'en': 'Oi'},
'5528989':{'en': 'Oi'},
'552899210':{'en': 'Claro BR'},
'552899222':{'en': 'Claro BR'},
'552899251':{'en': 'Claro BR'},
'552899252':{'en': 'Claro BR'},
'552899253':{'en': 'Claro BR'},
'552899254':{'en': 'Claro BR'},
'552899255':{'en': 'Claro BR'},
'552899256':{'en': 'Claro BR'},
'552899257':{'en': 'Claro BR'},
'552899258':{'en': 'Claro BR'},
'552899271':{'en': 'Claro BR'},
'552899272':{'en': 'Claro BR'},
'552899273':{'en': 'Claro BR'},
'552899274':{'en': 'Claro BR'},
'552899275':{'en': 'Claro BR'},
'552899276':{'en': 'Claro BR'},
'552899277':{'en': 'Claro BR'},
'552899278':{'en': 'Claro BR'},
'552899279':{'en': 'Claro BR'},
'552899291':{'en': 'Claro BR'},
'552899298':{'en': 'Claro BR'},
'552899881':{'en': 'Vivo'},
'552899882':{'en': 'Vivo'},
'552899883':{'en': 'Vivo'},
'552899884':{'en': 'Vivo'},
'552899885':{'en': 'Vivo'},
'552899886':{'en': 'Vivo'},
'552899901':{'en': 'Vivo'},
'552899902':{'en': 'Vivo'},
'552899903':{'en': 'Vivo'},
'552899904':{'en': 'Vivo'},
'552899905':{'en': 'Vivo'},
'552899915':{'en': 'Vivo'},
'552899916':{'en': 'Vivo'},
'552899917':{'en': 'Vivo'},
'552899918':{'en': 'Vivo'},
'552899919':{'en': 'Vivo'},
'552899921':{'en': 'Vivo'},
'552899922':{'en': 'Vivo'},
'552899923':{'en': 'Vivo'},
'552899924':{'en': 'Vivo'},
'552899925':{'en': 'Vivo'},
'552899926':{'en': 'Vivo'},
'552899935':{'en': 'Vivo'},
'552899938':{'en': 'Vivo'},
'552899939':{'en': 'Vivo'},
'552899945':{'en': 'Vivo'},
'552899946':{'en': 'Vivo'},
'552899951':{'en': 'Vivo'},
'552899952':{'en': 'Vivo'},
'552899953':{'en': 'Vivo'},
'552899954':{'en': 'Vivo'},
'552899955':{'en': 'Vivo'},
'552899956':{'en': 'Vivo'},
'552899957':{'en': 'Vivo'},
'552899958':{'en': 'Vivo'},
'552899959':{'en': 'Vivo'},
'552899961':{'en': 'Vivo'},
'552899962':{'en': 'Vivo'},
'552899963':{'en': 'Vivo'},
'552899964':{'en': 'Vivo'},
'552899965':{'en': 'Vivo'},
'552899966':{'en': 'Vivo'},
'552899967':{'en': 'Vivo'},
'552899968':{'en': 'Vivo'},
'552899969':{'en': 'Vivo'},
'552899971':{'en': 'Vivo'},
'552899972':{'en': 'Vivo'},
'552899973':{'en': 'Vivo'},
'552899974':{'en': 'Vivo'},
'552899975':{'en': 'Vivo'},
'552899976':{'en': 'Vivo'},
'552899977':{'en': 'Vivo'},
'552899978':{'en': 'Vivo'},
'552899979':{'en': 'Vivo'},
'552899981':{'en': 'Vivo'},
'552899982':{'en': 'Vivo'},
'552899983':{'en': 'Vivo'},
'552899984':{'en': 'Vivo'},
'552899985':{'en': 'Vivo'},
'552899986':{'en': 'Vivo'},
'552899987':{'en': 'Vivo'},
'552899988':{'en': 'Vivo'},
'552899989':{'en': 'Vivo'},
'552899991':{'en': 'Vivo'},
'552899992':{'en': 'Vivo'},
'552899993':{'en': 'Vivo'},
'552899994':{'en': 'Vivo'},
'552899995':{'en': 'Vivo'},
'552899996':{'en': 'Vivo'},
'552899997':{'en': 'Vivo'},
'552899998':{'en': 'Vivo'},
'55319820':{'en': 'Claro BR'},
'55319821':{'en': 'Claro BR'},
'55319822':{'en': 'Claro BR'},
'55319823':{'en': 'Claro BR'},
'553198240':{'en': 'Claro BR'},
'553198241':{'en': 'Claro BR'},
'553198242':{'en': 'Claro BR'},
'553198243':{'en': 'Claro BR'},
'553198244':{'en': 'Claro BR'},
'553198245':{'en': 'Claro BR'},
'5531983':{'en': 'Claro BR'},
'5531984':{'en': 'Claro BR'},
'5531985':{'en': 'Oi'},
'5531986':{'en': 'Oi'},
'5531987':{'en': 'Oi'},
'5531988':{'en': 'Oi'},
'5531989':{'en': 'Oi'},
'553199101':{'en': 'TIM'},
'553199102':{'en': 'TIM'},
'553199103':{'en': 'TIM'},
'553199104':{'en': 'TIM'},
'553199105':{'en': 'TIM'},
'553199106':{'en': 'TIM'},
'553199107':{'en': 'TIM'},
'553199108':{'en': 'TIM'},
'553199109':{'en': 'TIM'},
'55319911':{'en': 'TIM'},
'55319912':{'en': 'TIM'},
'55319913':{'en': 'TIM'},
'55319914':{'en': 'TIM'},
'55319915':{'en': 'TIM'},
'553199161':{'en': 'TIM'},
'553199162':{'en': 'TIM'},
'553199163':{'en': 'TIM'},
'553199164':{'en': 'TIM'},
'553199165':{'en': 'TIM'},
'553199166':{'en': 'TIM'},
'553199167':{'en': 'TIM'},
'553199168':{'en': 'TIM'},
'553199169':{'en': 'TIM'},
'553199171':{'en': 'TIM'},
'553199172':{'en': 'TIM'},
'553199173':{'en': 'TIM'},
'553199174':{'en': 'TIM'},
'553199175':{'en': 'TIM'},
'553199176':{'en': 'TIM'},
'553199177':{'en': 'TIM'},
'553199178':{'en': 'TIM'},
'553199179':{'en': 'TIM'},
'553199181':{'en': 'TIM'},
'553199182':{'en': 'TIM'},
'553199183':{'en': 'TIM'},
'553199184':{'en': 'TIM'},
'553199185':{'en': 'TIM'},
'553199186':{'en': 'TIM'},
'553199187':{'en': 'TIM'},
'553199188':{'en': 'TIM'},
'553199189':{'en': 'TIM'},
'553199191':{'en': 'TIM'},
'553199192':{'en': 'TIM'},
'553199193':{'en': 'TIM'},
'553199194':{'en': 'TIM'},
'553199195':{'en': 'TIM'},
'553199196':{'en': 'TIM'},
'553199197':{'en': 'TIM'},
'553199198':{'en': 'TIM'},
'553199199':{'en': 'TIM'},
'5531992':{'en': 'TIM'},
'5531993':{'en': 'TIM'},
'553199401':{'en': 'TIM'},
'553199402':{'en': 'TIM'},
'553199403':{'en': 'TIM'},
'553199404':{'en': 'TIM'},
'553199405':{'en': 'TIM'},
'553199406':{'en': 'TIM'},
'553199407':{'en': 'TIM'},
'553199408':{'en': 'TIM'},
'553199409':{'en': 'TIM'},
'553199411':{'en': 'TIM'},
'553199412':{'en': 'TIM'},
'553199413':{'en': 'TIM'},
'553199414':{'en': 'TIM'},
'553199415':{'en': 'TIM'},
'553199416':{'en': 'TIM'},
'553199601':{'en': 'Telemig Celular'},
'553199602':{'en': 'Telemig Celular'},
'553199603':{'en': 'Telemig Celular'},
'553199604':{'en': 'Telemig Celular'},
'553199605':{'en': 'Telemig Celular'},
'553199606':{'en': 'Telemig Celular'},
'553199607':{'en': 'Telemig Celular'},
'553199608':{'en': 'Telemig Celular'},
'553199609':{'en': 'Telemig Celular'},
'553199611':{'en': 'Telemig Celular'},
'553199612':{'en': 'Telemig Celular'},
'553199613':{'en': 'Telemig Celular'},
'553199614':{'en': 'Telemig Celular'},
'553199615':{'en': 'Telemig Celular'},
'553199616':{'en': 'Telemig Celular'},
'553199617':{'en': 'Telemig Celular'},
'553199618':{'en': 'Telemig Celular'},
'553199619':{'en': 'Telemig Celular'},
'553199621':{'en': 'Telemig Celular'},
'553199622':{'en': 'Telemig Celular'},
'553199624':{'en': 'Telemig Celular'},
'553199625':{'en': 'Telemig Celular'},
'553199626':{'en': 'Telemig Celular'},
'553199627':{'en': 'Telemig Celular'},
'553199628':{'en': 'Telemig Celular'},
'553199629':{'en': 'Telemig Celular'},
'553199631':{'en': 'Telemig Celular'},
'553199632':{'en': 'Telemig Celular'},
'553199633':{'en': 'Telemig Celular'},
'553199634':{'en': 'Telemig Celular'},
'553199635':{'en': 'Telemig Celular'},
'553199636':{'en': 'Telemig Celular'},
'553199637':{'en': 'Telemig Celular'},
'553199638':{'en': 'Telemig Celular'},
'553199639':{'en': 'Telemig Celular'},
'553199641':{'en': 'Telemig Celular'},
'553199642':{'en': 'Telemig Celular'},
'553199643':{'en': 'Telemig Celular'},
'553199644':{'en': 'Telemig Celular'},
'553199645':{'en': 'Telemig Celular'},
'553199646':{'en': 'Telemig Celular'},
'553199647':{'en': 'Telemig Celular'},
'553199648':{'en': 'Telemig Celular'},
'553199649':{'en': 'Telemig Celular'},
'553199651':{'en': 'Telemig Celular'},
'553199652':{'en': 'Telemig Celular'},
'553199653':{'en': 'Telemig Celular'},
'553199654':{'en': 'Telemig Celular'},
'553199655':{'en': 'Telemig Celular'},
'553199656':{'en': 'Telemig Celular'},
'553199657':{'en': 'Telemig Celular'},
'553199658':{'en': 'Telemig Celular'},
'553199659':{'en': 'Telemig Celular'},
'553199661':{'en': 'Telemig Celular'},
'553199662':{'en': 'Telemig Celular'},
'553199663':{'en': 'Telemig Celular'},
'553199664':{'en': 'Telemig Celular'},
'553199665':{'en': 'Telemig Celular'},
'553199666':{'en': 'Telemig Celular'},
'553199667':{'en': 'Telemig Celular'},
'553199668':{'en': 'Telemig Celular'},
'553199669':{'en': 'Telemig Celular'},
'553199671':{'en': 'Telemig Celular'},
'553199672':{'en': 'Telemig Celular'},
'553199673':{'en': 'Telemig Celular'},
'553199674':{'en': 'Telemig Celular'},
'553199675':{'en': 'Telemig Celular'},
'553199676':{'en': 'Telemig Celular'},
'553199677':{'en': 'Telemig Celular'},
'553199678':{'en': 'Telemig Celular'},
'553199679':{'en': 'Telemig Celular'},
'553199681':{'en': 'Telemig Celular'},
'553199682':{'en': 'Telemig Celular'},
'553199683':{'en': 'Telemig Celular'},
'553199684':{'en': 'Telemig Celular'},
'553199685':{'en': 'Telemig Celular'},
'553199686':{'en': 'Telemig Celular'},
'553199687':{'en': 'Telemig Celular'},
'553199688':{'en': 'Telemig Celular'},
'553199689':{'en': 'Telemig Celular'},
'553199691':{'en': 'Telemig Celular'},
'553199692':{'en': 'Telemig Celular'},
'553199693':{'en': 'Telemig Celular'},
'553199694':{'en': 'Telemig Celular'},
'553199695':{'en': 'Telemig Celular'},
'553199696':{'en': 'Telemig Celular'},
'553199697':{'en': 'Telemig Celular'},
'553199698':{'en': 'Telemig Celular'},
'553199699':{'en': 'Telemig Celular'},
'553199701':{'en': 'Telemig Celular'},
'553199702':{'en': 'Telemig Celular'},
'553199703':{'en': 'Telemig Celular'},
'553199704':{'en': 'Telemig Celular'},
'553199705':{'en': 'Telemig Celular'},
'553199706':{'en': 'Telemig Celular'},
'553199707':{'en': 'Telemig Celular'},
'553199708':{'en': 'Telemig Celular'},
'553199709':{'en': 'Telemig Celular'},
'553199711':{'en': 'Telemig Celular'},
'553199712':{'en': 'Telemig Celular'},
'553199713':{'en': 'Telemig Celular'},
'553199714':{'en': 'Telemig Celular'},
'553199715':{'en': 'Telemig Celular'},
'553199717':{'en': 'Telemig Celular'},
'553199718':{'en': 'Telemig Celular'},
'553199719':{'en': 'Telemig Celular'},
'553199721':{'en': 'Telemig Celular'},
'553199722':{'en': 'Telemig Celular'},
'553199723':{'en': 'Telemig Celular'},
'553199724':{'en': 'Telemig Celular'},
'553199725':{'en': 'Telemig Celular'},
'553199726':{'en': 'Telemig Celular'},
'553199728':{'en': 'Telemig Celular'},
'553199729':{'en': 'Telemig Celular'},
'553199731':{'en': 'Telemig Celular'},
'553199732':{'en': 'Telemig Celular'},
'553199733':{'en': 'Telemig Celular'},
'553199734':{'en': 'Telemig Celular'},
'553199735':{'en': 'Telemig Celular'},
'553199736':{'en': 'Telemig Celular'},
'553199737':{'en': 'Telemig Celular'},
'553199738':{'en': 'Telemig Celular'},
'553199739':{'en': 'Telemig Celular'},
'553199741':{'en': 'Telemig Celular'},
'553199742':{'en': 'Telemig Celular'},
'553199743':{'en': 'Telemig Celular'},
'553199744':{'en': 'Telemig Celular'},
'553199745':{'en': 'Telemig Celular'},
'553199746':{'en': 'Telemig Celular'},
'553199747':{'en': 'Telemig Celular'},
'553199748':{'en': 'Telemig Celular'},
'553199749':{'en': 'Telemig Celular'},
'553199751':{'en': 'Telemig Celular'},
'553199752':{'en': 'Telemig Celular'},
'553199753':{'en': 'Telemig Celular'},
'553199755':{'en': 'Telemig Celular'},
'553199756':{'en': 'Telemig Celular'},
'553199757':{'en': 'Telemig Celular'},
'553199758':{'en': 'Telemig Celular'},
'553199759':{'en': 'Telemig Celular'},
'553199761':{'en': 'Telemig Celular'},
'553199762':{'en': 'Telemig Celular'},
'553199763':{'en': 'Telemig Celular'},
'553199764':{'en': 'Telemig Celular'},
'553199765':{'en': 'Telemig Celular'},
'553199766':{'en': 'Telemig Celular'},
'553199767':{'en': 'Telemig Celular'},
'553199768':{'en': 'Telemig Celular'},
'553199769':{'en': 'Telemig Celular'},
'553199771':{'en': 'Telemig Celular'},
'553199772':{'en': 'Telemig Celular'},
'553199773':{'en': 'Telemig Celular'},
'553199774':{'en': 'Telemig Celular'},
'553199775':{'en': 'Telemig Celular'},
'553199776':{'en': 'Telemig Celular'},
'553199777':{'en': 'Telemig Celular'},
'553199778':{'en': 'Telemig Celular'},
'553199779':{'en': 'Telemig Celular'},
'553199781':{'en': 'Telemig Celular'},
'553199782':{'en': 'Telemig Celular'},
'553199783':{'en': 'Telemig Celular'},
'553199784':{'en': 'Telemig Celular'},
'553199785':{'en': 'Telemig Celular'},
'553199786':{'en': 'Telemig Celular'},
'553199787':{'en': 'Telemig Celular'},
'553199788':{'en': 'Telemig Celular'},
'553199789':{'en': 'Telemig Celular'},
'553199791':{'en': 'Telemig Celular'},
'553199792':{'en': 'Telemig Celular'},
'553199793':{'en': 'Telemig Celular'},
'553199794':{'en': 'Telemig Celular'},
'553199795':{'en': 'Telemig Celular'},
'553199796':{'en': 'Telemig Celular'},
'553199797':{'en': 'Telemig Celular'},
'553199798':{'en': 'Telemig Celular'},
'553199799':{'en': 'Telemig Celular'},
'5531998':{'en': 'Telemig Celular'},
'553199800':{'en': 'TIM'},
'553199810':{'en': 'TIM'},
'553199820':{'en': 'TIM'},
'553199830':{'en': 'TIM'},
'553199840':{'en': 'TIM'},
'553199850':{'en': 'TIM'},
'553199860':{'en': 'TIM'},
'553199870':{'en': 'TIM'},
'553199880':{'en': 'TIM'},
'553199890':{'en': 'TIM'},
'553199901':{'en': 'Telemig Celular'},
'553199902':{'en': 'Telemig Celular'},
'553199903':{'en': 'Telemig Celular'},
'553199904':{'en': 'Telemig Celular'},
'553199905':{'en': 'Telemig Celular'},
'553199906':{'en': 'Telemig Celular'},
'553199907':{'en': 'Telemig Celular'},
'553199908':{'en': 'Telemig Celular'},
'553199909':{'en': 'Telemig Celular'},
'553199911':{'en': 'Telemig Celular'},
'553199912':{'en': 'Telemig Celular'},
'553199913':{'en': 'Telemig Celular'},
'553199914':{'en': 'Telemig Celular'},
'553199915':{'en': 'Telemig Celular'},
'553199916':{'en': 'Telemig Celular'},
'553199917':{'en': 'Telemig Celular'},
'553199918':{'en': 'Telemig Celular'},
'553199919':{'en': 'Telemig Celular'},
'553199921':{'en': 'Telemig Celular'},
'553199922':{'en': 'Telemig Celular'},
'553199923':{'en': 'Telemig Celular'},
'553199924':{'en': 'Telemig Celular'},
'553199925':{'en': 'Telemig Celular'},
'553199926':{'en': 'Telemig Celular'},
'553199927':{'en': 'Telemig Celular'},
'553199928':{'en': 'Telemig Celular'},
'553199929':{'en': 'Telemig Celular'},
'553199931':{'en': 'Telemig Celular'},
'553199932':{'en': 'Telemig Celular'},
'553199933':{'en': 'Telemig Celular'},
'553199934':{'en': 'Telemig Celular'},
'553199935':{'en': 'Telemig Celular'},
'553199936':{'en': 'Telemig Celular'},
'553199937':{'en': 'Telemig Celular'},
'553199938':{'en': 'Telemig Celular'},
'553199939':{'en': 'Telemig Celular'},
'553199941':{'en': 'Telemig Celular'},
'553199942':{'en': 'Telemig Celular'},
'553199943':{'en': 'Telemig Celular'},
'553199944':{'en': 'Telemig Celular'},
'553199945':{'en': 'Telemig Celular'},
'553199946':{'en': 'Telemig Celular'},
'553199947':{'en': 'Telemig Celular'},
'553199948':{'en': 'Telemig Celular'},
'553199949':{'en': 'Telemig Celular'},
'55319995':{'en': 'Telemig Celular'},
'55319996':{'en': 'Telemig Celular'},
'55319997':{'en': 'Telemig Celular'},
'55319998':{'en': 'Telemig Celular'},
'55319999':{'en': 'Telemig Celular'},
'55329840':{'en': 'Claro BR'},
'55329841':{'en': 'Claro BR'},
'55329842':{'en': 'Claro BR'},
'55329843':{'en': 'Claro BR'},
'55329844':{'en': 'Claro BR'},
'55329845':{'en': 'Claro BR'},
'55329846':{'en': 'Claro BR'},
'55329847':{'en': 'Claro BR'},
'553298480':{'en': 'Claro BR'},
'553298481':{'en': 'Claro BR'},
'553298482':{'en': 'Claro BR'},
'553298483':{'en': 'Claro BR'},
'553298484':{'en': 'Claro BR'},
'553298485':{'en': 'Claro BR'},
'5532985':{'en': 'Oi'},
'5532986':{'en': 'Oi'},
'5532987':{'en': 'Oi'},
'5532988':{'en': 'Oi'},
'5532989':{'en': 'Oi'},
'553299101':{'en': 'TIM'},
'553299102':{'en': 'TIM'},
'553299103':{'en': 'TIM'},
'553299104':{'en': 'TIM'},
'553299105':{'en': 'TIM'},
'553299106':{'en': 'TIM'},
'553299107':{'en': 'TIM'},
'553299108':{'en': 'TIM'},
'553299109':{'en': 'TIM'},
'553299111':{'en': 'TIM'},
'553299112':{'en': 'TIM'},
'553299113':{'en': 'TIM'},
'553299114':{'en': 'TIM'},
'553299115':{'en': 'TIM'},
'553299116':{'en': 'TIM'},
'553299117':{'en': 'TIM'},
'553299118':{'en': 'TIM'},
'553299119':{'en': 'TIM'},
'553299121':{'en': 'TIM'},
'553299122':{'en': 'TIM'},
'553299123':{'en': 'TIM'},
'553299124':{'en': 'TIM'},
'553299125':{'en': 'TIM'},
'553299126':{'en': 'TIM'},
'553299127':{'en': 'TIM'},
'553299128':{'en': 'TIM'},
'553299129':{'en': 'TIM'},
'553299131':{'en': 'TIM'},
'553299132':{'en': 'TIM'},
'553299133':{'en': 'TIM'},
'553299134':{'en': 'TIM'},
'553299135':{'en': 'TIM'},
'553299136':{'en': 'TIM'},
'553299137':{'en': 'TIM'},
'553299138':{'en': 'TIM'},
'553299139':{'en': 'TIM'},
'553299141':{'en': 'TIM'},
'553299142':{'en': 'TIM'},
'553299143':{'en': 'TIM'},
'553299144':{'en': 'TIM'},
'553299145':{'en': 'TIM'},
'553299146':{'en': 'TIM'},
'553299193':{'en': 'TIM'},
'553299194':{'en': 'TIM'},
'553299195':{'en': 'TIM'},
'553299197':{'en': 'TIM'},
'553299198':{'en': 'TIM'},
'553299199':{'en': 'TIM'},
'553299901':{'en': 'Telemig Celular'},
'553299902':{'en': 'Telemig Celular'},
'553299903':{'en': 'Telemig Celular'},
'553299904':{'en': 'Telemig Celular'},
'553299905':{'en': 'Telemig Celular'},
'553299906':{'en': 'Telemig Celular'},
'553299907':{'en': 'Telemig Celular'},
'553299908':{'en': 'Telemig Celular'},
'553299909':{'en': 'Telemig Celular'},
'553299911':{'en': 'Telemig Celular'},
'553299912':{'en': 'Telemig Celular'},
'553299913':{'en': 'Telemig Celular'},
'553299914':{'en': 'Telemig Celular'},
'553299917':{'en': 'Telemig Celular'},
'553299918':{'en': 'Telemig Celular'},
'553299919':{'en': 'Telemig Celular'},
'553299921':{'en': 'Telemig Celular'},
'553299922':{'en': 'Telemig Celular'},
'553299923':{'en': 'Telemig Celular'},
'553299924':{'en': 'Telemig Celular'},
'553299925':{'en': 'Telemig Celular'},
'553299931':{'en': 'Telemig Celular'},
'553299932':{'en': 'Telemig Celular'},
'553299933':{'en': 'Telemig Celular'},
'553299934':{'en': 'Telemig Celular'},
'553299935':{'en': 'Telemig Celular'},
'553299936':{'en': 'Telemig Celular'},
'553299937':{'en': 'Telemig Celular'},
'553299938':{'en': 'Telemig Celular'},
'553299939':{'en': 'Telemig Celular'},
'553299941':{'en': 'Telemig Celular'},
'553299942':{'en': 'Telemig Celular'},
'553299943':{'en': 'Telemig Celular'},
'553299944':{'en': 'Telemig Celular'},
'553299945':{'en': 'Telemig Celular'},
'553299946':{'en': 'Telemig Celular'},
'553299947':{'en': 'Telemig Celular'},
'553299948':{'en': 'Telemig Celular'},
'553299949':{'en': 'Telemig Celular'},
'553299951':{'en': 'Telemig Celular'},
'553299952':{'en': 'Telemig Celular'},
'553299953':{'en': 'Telemig Celular'},
'553299954':{'en': 'Telemig Celular'},
'553299955':{'en': 'Telemig Celular'},
'553299956':{'en': 'Telemig Celular'},
'553299957':{'en': 'Telemig Celular'},
'553299958':{'en': 'Telemig Celular'},
'553299959':{'en': 'Telemig Celular'},
'55329996':{'en': 'Telemig Celular'},
'553299971':{'en': 'Telemig Celular'},
'553299972':{'en': 'Telemig Celular'},
'553299973':{'en': 'Telemig Celular'},
'553299974':{'en': 'Telemig Celular'},
'553299975':{'en': 'Telemig Celular'},
'553299976':{'en': 'Telemig Celular'},
'553299977':{'en': 'Telemig Celular'},
'553299979':{'en': 'Telemig Celular'},
'55329998':{'en': 'Telemig Celular'},
'553299991':{'en': 'Telemig Celular'},
'553299992':{'en': 'Telemig Celular'},
'553299993':{'en': 'Telemig Celular'},
'553299994':{'en': 'Telemig Celular'},
'553299995':{'en': 'Telemig Celular'},
'553299996':{'en': 'Telemig Celular'},
'553299997':{'en': 'Telemig Celular'},
'553299998':{'en': 'Telemig Celular'},
'553398401':{'en': 'Claro BR'},
'553398402':{'en': 'Claro BR'},
'553398403':{'en': 'Claro BR'},
'553398404':{'en': 'Claro BR'},
'553398405':{'en': 'Claro BR'},
'553398406':{'en': 'Claro BR'},
'553398407':{'en': 'Claro BR'},
'553398408':{'en': 'Claro BR'},
'553398409':{'en': 'Claro BR'},
'553398411':{'en': 'Claro BR'},
'553398412':{'en': 'Claro BR'},
'553398413':{'en': 'Claro BR'},
'553398414':{'en': 'Claro BR'},
'553398415':{'en': 'Claro BR'},
'553398416':{'en': 'Claro BR'},
'553398417':{'en': 'Claro BR'},
'553398418':{'en': 'Claro BR'},
'553398419':{'en': 'Claro BR'},
'553398421':{'en': 'Claro BR'},
'553398422':{'en': 'Claro BR'},
'553398423':{'en': 'Claro BR'},
'553398424':{'en': 'Claro BR'},
'553398425':{'en': 'Claro BR'},
'553398426':{'en': 'Claro BR'},
'553398427':{'en': 'Claro BR'},
'553398428':{'en': 'Claro BR'},
'553398429':{'en': 'Claro BR'},
'553398431':{'en': 'Claro BR'},
'553398432':{'en': 'Claro BR'},
'553398433':{'en': 'Claro BR'},
'553398434':{'en': 'Claro BR'},
'553398435':{'en': 'Claro BR'},
'553398436':{'en': 'Claro BR'},
'553398437':{'en': 'Claro BR'},
'553398438':{'en': 'Claro BR'},
'553398439':{'en': 'Claro BR'},
'553398441':{'en': 'Claro BR'},
'553398442':{'en': 'Claro BR'},
'553398443':{'en': 'Claro BR'},
'553398444':{'en': 'Claro BR'},
'553398445':{'en': 'Claro BR'},
'553398446':{'en': 'Claro BR'},
'553398447':{'en': 'Claro BR'},
'553398448':{'en': 'Claro BR'},
'553398449':{'en': 'Claro BR'},
'553398451':{'en': 'Claro BR'},
'553398452':{'en': 'Claro BR'},
'553398453':{'en': 'Claro BR'},
'553398454':{'en': 'Claro BR'},
'553398455':{'en': 'Claro BR'},
'553398456':{'en': 'Claro BR'},
'5533985':{'en': 'Oi'},
'5533986':{'en': 'Oi'},
'5533987':{'en': 'Oi'},
'5533988':{'en': 'Oi'},
'5533989':{'en': 'Oi'},
'553399101':{'en': 'TIM'},
'553399102':{'en': 'TIM'},
'553399103':{'en': 'TIM'},
'553399104':{'en': 'TIM'},
'553399105':{'en': 'TIM'},
'553399106':{'en': 'TIM'},
'553399107':{'en': 'TIM'},
'553399108':{'en': 'TIM'},
'553399109':{'en': 'TIM'},
'553399111':{'en': 'TIM'},
'553399112':{'en': 'TIM'},
'553399113':{'en': 'TIM'},
'553399114':{'en': 'TIM'},
'553399115':{'en': 'TIM'},
'553399116':{'en': 'TIM'},
'553399117':{'en': 'TIM'},
'553399118':{'en': 'TIM'},
'553399119':{'en': 'TIM'},
'553399121':{'en': 'TIM'},
'553399122':{'en': 'TIM'},
'553399123':{'en': 'TIM'},
'553399124':{'en': 'TIM'},
'553399125':{'en': 'TIM'},
'553399126':{'en': 'TIM'},
}
| 31.104659 | 125 | 0.53265 | from ..util import u
data = {
'1242357':{'en': 'BaTelCo'},
'1242359':{'en': 'BaTelCo'},
'1242375':{'en': 'BaTelCo'},
'1242376':{'en': 'BaTelCo'},
'1242395':{'en': 'BaTelCo'},
'124242':{'en': 'BaTelCo'},
'124243':{'en': 'BaTelCo'},
'124244':{'en': 'BaTelCo'},
'124245':{'en': 'BaTelCo'},
'1242462':{'en': 'BaTelCo'},
'1242463':{'en': 'BaTelCo'},
'1242464':{'en': 'BaTelCo'},
'1242465':{'en': 'BaTelCo'},
'1242466':{'en': 'BaTelCo'},
'1242467':{'en': 'BaTelCo'},
'1242468':{'en': 'BaTelCo'},
'124247':{'en': 'BaTelCo'},
'124248':{'en': 'BaTelCo'},
'124252':{'en': 'BaTelCo'},
'124253':{'en': 'BaTelCo'},
'124254':{'en': 'BaTelCo'},
'124255':{'en': 'BaTelCo'},
'124256':{'en': 'BaTelCo'},
'124257':{'en': 'BaTelCo'},
'124263':{'en': 'BaTelCo'},
'1242646':{'en': 'BaTelCo'},
'124272':{'en': 'BaTelCo'},
'124273':{'en': 'aliv'},
'12428':{'en': 'aliv'},
'124623':{'en': 'LIME'},
'124624':{'en': 'LIME'},
'124625':{'en': 'LIME'},
'1246256':{'en': 'Digicel'},
'1246257':{'en': 'Digicel'},
'1246258':{'en': 'Digicel'},
'1246259':{'en': 'Digicel'},
'124626':{'en': 'Digicel'},
'124628':{'en': 'Cable & Wireless'},
'124645':{'en': 'Sunbeach Communications'},
'124669':{'en': 'Ozone'},
'12468':{'en': 'Digicel'},
'1264469':{'en': 'Cable & Wireless'},
'126453':{'en': 'Weblinks Limited'},
'126458':{'en': 'Digicel'},
'1264729':{'en': 'Cable & Wireless'},
'126477':{'en': 'Cable & Wireless'},
'126871':{'en': 'Digicel'},
'1268720':{'en': 'Digicel'},
'1268721':{'en': 'Digicel'},
'1268722':{'en': 'Digicel'},
'1268724':{'en': 'Digicel'},
'1268725':{'en': 'Digicel'},
'1268726':{'en': 'Digicel'},
'1268727':{'en': 'APUA'},
'1268729':{'en': 'APUA'},
'1268730':{'en': 'APUA'},
'1268732':{'en': 'Digicel'},
'1268734':{'en': 'Digicel'},
'1268736':{'en': 'Digicel'},
'1268773':{'en': 'APUA'},
'1268774':{'en': 'APUA'},
'1268775':{'en': 'APUA'},
'1268780':{'en': 'APUA'},
'1268781':{'en': 'APUA'},
'1268783':{'en': 'Digicel'},
'1268785':{'en': 'Digicel'},
'1268787':{'en': 'Cable & Wireless'},
'1268788':{'en': 'Digicel'},
'128424':{'en': 'Cable & Wireless'},
'1284300':{'en': 'Digicel'},
'128434':{'en': 'Digicel'},
'128436':{'en': 'Digicel'},
'128439':{'en': 'Digicel'},
'128444':{'en': 'CCT'},
'12844689':{'en': 'CCT'},
'12844966':{'en': 'CCT'},
'12844967':{'en': 'CCT'},
'12844968':{'en': 'CCT'},
'12844969':{'en': 'CCT'},
'1284499':{'en': 'CCT'},
'1284546':{'en': 'Cable & Wireless'},
'128456':{'en': 'Cable & Wireless'},
'128459':{'en': 'Cable & Wireless'},
'1340423':{'en': 'Vitelcom Cellular'},
'134044':{'en': 'GIGSKY Mobile'},
'1340725':{'en': 'Vitelcom Cellular'},
'134532':{'en': 'Digicel'},
'134542':{'en': 'Digicel'},
'134551':{'en': 'Digicel'},
'134552':{'en': 'Digicel'},
'134554':{'en': 'Digicel'},
'134555':{'en': 'Digicel'},
'1345649':{'en': 'Digicel'},
'1345919':{'en': 'Cable & Wireless'},
'1345930':{'en': 'LIME'},
'1345936':{'en': 'Cable & Wireless'},
'1345937':{'en': 'Cable & Wireless'},
'1345938':{'en': 'Cable & Wireless'},
'1345939':{'en': 'Cable & Wireless'},
'134599':{'en': 'Cable & Wireless'},
'14412':{'en': 'Cellular One'},
'14413':{'en': 'Mobility'},
'144150':{'en': 'Digicel Bermuda'},
'144151':{'en': 'Digicel Bermuda'},
'144152':{'en': 'Digicel Bermuda'},
'144153':{'en': 'Digicel Bermuda'},
'144159':{'en': 'Digicel Bermuda'},
'14417':{'en': 'Cellular One'},
'14418':{'en': 'Cellular One'},
'1473402':{'en': 'Affordable Island Communications'},
'147341':{'en': 'Digicel Grenada'},
'147342':{'en': 'Digicel Grenada'},
'147352':{'en': 'Affordable Island Communications'},
'147353':{'en': 'AWS Grenada'},
'147390':{'en': 'Affordable Island Communications'},
'164923':{'en': 'C&W'},
'164924':{'en': 'Cable & Wireless'},
'16493':{'en': 'Digicel'},
'164943':{'en': 'Islandcom'},
'1658295':{'en': 'Cable & Wireless'},
'1659200':{'en': 'Onvoy'},
'1659222':{'en': 'Onvoy'},
'1659300':{'en': 'Onvoy'},
'1659400':{'en': 'Onvoy'},
'1659444':{'en': 'Onvoy'},
'1659500':{'en': 'Onvoy'},
'1659529':{'en': 'Fractel'},
'1659600':{'en': 'Onvoy'},
'1659666':{'en': 'Onvoy'},
'1659766':{'en': 'Fractel'},
'1659777':{'en': 'Onvoy'},
'1659800':{'en': 'Onvoy'},
'1659888':{'en': 'Fractel'},
'1659900':{'en': 'Onvoy'},
'1659999':{'en': 'Onvoy'},
'166434':{'en': 'Cable & Wireless'},
'166439':{'en': 'Digicel'},
'1670284':{'en': 'PTI PACIFICA'},
'167148':{'en': 'GTA'},
'167174':{'en': 'PTI PACIFICA'},
'167183':{'en': 'i CAN_GSM'},
'167184':{'en': 'i CAN_GSM'},
'167185':{'en': 'i CAN_GSM'},
'1671864':{'en': 'GTA'},
'1671868':{'en': 'Choice Phone'},
'167187':{'en': 'Choice Phone'},
'167188':{'en': 'Choice Phone'},
'167189':{'en': 'Choice Phone'},
'168424':{'en': 'ASTCA'},
'168425':{'en': 'Blue Sky'},
'168427':{'en': 'Blue Sky'},
'16847':{'en': 'ASTCA'},
'175828':{'en': 'Cable & Wireless'},
'17583':{'en': 'Cable & Wireless'},
'1758460':{'en': 'Cable & Wireless'},
'1758461':{'en': 'Cable & Wireless'},
'1758484':{'en': 'Cable & Wireless'},
'1758485':{'en': 'Cable & Wireless'},
'1758486':{'en': 'Cable & Wireless'},
'1758487':{'en': 'Cable & Wireless'},
'1758488':{'en': 'Cable & Wireless'},
'1758489':{'en': 'Cable & Wireless'},
'175851':{'en': 'Digicel'},
'175852':{'en': 'Digicel'},
'175858':{'en': 'Cable & Wireless'},
'175871':{'en': 'Digicel'},
'175872':{'en': 'Digicel'},
'175873':{'en': 'Digicel'},
'17588':{'en': 'Digicel'},
'176722':{'en': 'Cable & Wireless'},
'176723':{'en': 'Cable & Wireless'},
'176724':{'en': 'Cable & Wireless'},
'1767265':{'en': 'Cable & Wireless'},
'176727':{'en': 'Cable & Wireless'},
'176728':{'en': 'Cable & Wireless'},
'176729':{'en': 'Cable & Wireless'},
'17673':{'en': 'Digicel'},
'17676':{'en': 'Digicel'},
'1767704':{'en': 'Digicel'},
'1767705':{'en': 'Digicel'},
'1767706':{'en': 'Digicel'},
'1784430':{'en': 'AT&T'},
'1784431':{'en': 'AT&T'},
'1784432':{'en': 'AT&T'},
'1784433':{'en': 'Digicel'},
'1784434':{'en': 'Digicel'},
'1784435':{'en': 'Digicel'},
'1784454':{'en': 'Cable & Wireless'},
'1784455':{'en': 'Cable & Wireless'},
'1784489':{'en': 'Cable & Wireless'},
'1784490':{'en': 'Cable & Wireless'},
'1784491':{'en': 'Cable & Wireless'},
'1784492':{'en': 'Cable & Wireless'},
'1784493':{'en': 'Cable & Wireless'},
'1784494':{'en': 'Cable & Wireless'},
'1784495':{'en': 'Cable & Wireless'},
'178452':{'en': 'Digicel'},
'178453':{'en': 'Digicel'},
'178472':{'en': 'Digicel'},
'1787203':{'en': 'Claro'},
'1787210':{'en': 'SunCom Wireless Puerto Rico'},
'1787212':{'en': 'Claro'},
'1787213':{'en': 'Claro'},
'1787214':{'en': 'Claro'},
'1787215':{'en': 'Claro'},
'1787216':{'en': 'Claro'},
'1787217':{'en': 'Claro'},
'1787218':{'en': 'Claro'},
'1787219':{'en': 'Claro'},
'1787220':{'en': 'CENTENNIAL'},
'1787221':{'en': 'CENTENNIAL'},
'1787222':{'en': 'CENTENNIAL'},
'1787223':{'en': 'CENTENNIAL'},
'1787224':{'en': 'CENTENNIAL'},
'1787225':{'en': 'SunCom Wireless Puerto Rico'},
'1787226':{'en': 'SunCom Wireless Puerto Rico'},
'1787227':{'en': 'CENTENNIAL'},
'1787229':{'en': 'CENTENNIAL'},
'1787253':{'en': 'Claro'},
'1787254':{'en': 'Claro'},
'1787255':{'en': 'Claro'},
'1787256':{'en': 'Claro'},
'1787257':{'en': 'Claro'},
'1787258':{'en': 'Claro'},
'1787259':{'en': 'Claro'},
'1787260':{'en': 'Claro'},
'1787291':{'en': 'CENTENNIAL'},
'1787299':{'en': 'SunCom Wireless Puerto Rico'},
'1787300':{'en': 'CENTENNIAL'},
'1787310':{'en': 'SunCom Wireless Puerto Rico'},
'1787312':{'en': 'Claro'},
'1787313':{'en': 'Claro'},
'1787314':{'en': 'Claro'},
'1787315':{'en': 'Claro'},
'1787316':{'en': 'Claro'},
'1787317':{'en': 'Claro'},
'1787318':{'en': 'Claro'},
'17873191':{'en': 'Claro'},
'17873192':{'en': 'Claro'},
'17873193':{'en': 'Claro'},
'17873194':{'en': 'Claro'},
'17873195':{'en': 'Claro'},
'17873196':{'en': 'Claro'},
'17873197':{'en': 'Claro'},
'17873198':{'en': 'Claro'},
'17873199':{'en': 'Claro'},
'1787341':{'en': 'SunCom Wireless Puerto Rico'},
'1787344':{'en': 'SunCom Wireless Puerto Rico'},
'1787346':{'en': 'SunCom Wireless Puerto Rico'},
'1787355':{'en': 'CENTENNIAL'},
'1787357':{'en': 'CENTENNIAL'},
'1787359':{'en': 'SunCom Wireless Puerto Rico'},
'1787367':{'en': 'SunCom Wireless Puerto Rico'},
'1787368':{'en': 'SunCom Wireless Puerto Rico'},
'1787369':{'en': 'CENTENNIAL'},
'1787371':{'en': 'Claro'},
'1787372':{'en': 'Claro'},
'1787374':{'en': 'Claro'},
'1787375':{'en': 'Claro'},
'1787376':{'en': 'Claro'},
'1787380':{'en': 'Claro'},
'1787381':{'en': 'Claro'},
'1787382':{'en': 'Claro'},
'1787383':{'en': 'Claro'},
'1787384':{'en': 'Claro'},
'1787385':{'en': 'Claro'},
'1787389':{'en': 'Claro'},
'1787390':{'en': 'Claro'},
'1787391':{'en': 'Claro'},
'1787392':{'en': 'Claro'},
'1787400':{'en': 'CENTENNIAL'},
'1787410':{'en': 'SunCom Wireless Puerto Rico'},
'1787434':{'en': 'CENTENNIAL'},
'1787447':{'en': 'CENTENNIAL'},
'1787448':{'en': 'CENTENNIAL'},
'1787449':{'en': 'CENTENNIAL'},
'1787450':{'en': 'Claro'},
'1787453':{'en': 'Claro'},
'1787454':{'en': 'SunCom Wireless Puerto Rico'},
'1787458':{'en': 'SunCom Wireless Puerto Rico'},
'1787459':{'en': 'SunCom Wireless Puerto Rico'},
'1787460':{'en': 'SunCom Wireless Puerto Rico'},
'1787462':{'en': 'SunCom Wireless Puerto Rico'},
'1787463':{'en': 'SunCom Wireless Puerto Rico'},
'1787465':{'en': 'CENTENNIAL'},
'1787466':{'en': 'SunCom Wireless Puerto Rico'},
'1787471':{'en': 'CENTENNIAL'},
'1787473':{'en': 'CENTENNIAL'},
'1787474':{'en': 'CENTENNIAL'},
'1787478':{'en': 'SunCom Wireless Puerto Rico'},
'1787479':{'en': 'CENTENNIAL'},
'1787481':{'en': 'Claro'},
'1787484':{'en': 'Claro'},
'1787485':{'en': 'Claro'},
'1787486':{'en': 'Claro'},
'1787487':{'en': 'Claro'},
'1787513':{'en': 'SunCom Wireless Puerto Rico'},
'1787514':{'en': 'Claro'},
'1787515':{'en': 'Claro'},
'1787516':{'en': 'Claro'},
'1787517':{'en': 'Claro'},
'1787518':{'en': 'Claro'},
'1787519':{'en': 'Claro'},
'1787520':{'en': 'CENTENNIAL'},
'1787521':{'en': 'CENTENNIAL'},
'1787522':{'en': 'CENTENNIAL'},
'1787523':{'en': 'CENTENNIAL'},
'1787528':{'en': 'SunCom Wireless Puerto Rico'},
'1787534':{'en': 'CENTENNIAL'},
'1787535':{'en': 'CENTENNIAL'},
'1787537':{'en': 'CENTENNIAL'},
'1787544':{'en': 'CENTENNIAL'},
'1787545':{'en': 'CENTENNIAL'},
'1787546':{'en': 'SunCom Wireless Puerto Rico'},
'1787551':{'en': 'CENTENNIAL'},
'1787553':{'en': 'Claro'},
'1787561':{'en': 'CENTENNIAL'},
'1787563':{'en': 'CENTENNIAL'},
'1787568':{'en': 'SunCom Wireless Puerto Rico'},
'1787569':{'en': 'CENTENNIAL'},
'1787579':{'en': 'Claro'},
'1787580':{'en': 'CENTENNIAL'},
'1787585':{'en': 'CENTENNIAL'},
'1787588':{'en': 'CENTENNIAL'},
'1787589':{'en': 'CENTENNIAL'},
'1787595':{'en': 'SunCom Wireless Puerto Rico'},
'1787597':{'en': 'SunCom Wireless Puerto Rico'},
'1787598':{'en': 'SunCom Wireless Puerto Rico'},
'1787601':{'en': 'SunCom Wireless Puerto Rico'},
'1787602':{'en': 'CENTENNIAL'},
'1787604':{'en': 'SunCom Wireless Puerto Rico'},
'1787605':{'en': 'SunCom Wireless Puerto Rico'},
'1787607':{'en': 'CENTENNIAL'},
'1787608':{'en': 'CENTENNIAL'},
'1787609':{'en': 'CENTENNIAL'},
'1787612':{'en': 'Claro'},
'1787613':{'en': 'Claro'},
'1787614':{'en': 'Claro'},
'1787615':{'en': 'Claro'},
'1787616':{'en': 'Claro'},
'1787617':{'en': 'Claro'},
'1787619':{'en': 'SunCom Wireless Puerto Rico'},
'1787620':{'en': 'CENTENNIAL'},
'1787621':{'en': 'CENTENNIAL'},
'1787622':{'en': 'CENTENNIAL'},
'1787623':{'en': 'CENTENNIAL'},
'1787624':{'en': 'CENTENNIAL'},
'1787625':{'en': 'CENTENNIAL'},
'1787626':{'en': 'CENTENNIAL'},
'1787628':{'en': 'CENTENNIAL'},
'1787629':{'en': 'SunCom Wireless Puerto Rico'},
'178764':{'en': 'CENTENNIAL'},
'178765':{'en': 'CENTENNIAL'},
'1787662':{'en': 'SunCom Wireless Puerto Rico'},
'1787666':{'en': 'SunCom Wireless Puerto Rico'},
'1787673':{'en': 'SunCom Wireless Puerto Rico'},
'1787675':{'en': 'CENTENNIAL'},
'1787678':{'en': 'SunCom Wireless Puerto Rico'},
'1787686':{'en': 'CENTENNIAL'},
'1787687':{'en': 'CENTENNIAL'},
'1787689':{'en': 'CENTENNIAL'},
'1787690':{'en': 'CENTENNIAL'},
'1787692':{'en': 'CENTENNIAL'},
'1787693':{'en': 'CENTENNIAL'},
'1787695':{'en': 'CENTENNIAL'},
'1787717':{'en': 'CENTENNIAL'},
'1787719':{'en': 'CENTENNIAL'},
'1787901':{'en': 'SunCom Wireless Puerto Rico'},
'1787903':{'en': 'CENTENNIAL'},
'1787904':{'en': 'SunCom Wireless Puerto Rico'},
'1787908':{'en': 'CENTENNIAL'},
'1787912':{'en': 'CENTENNIAL'},
'1787915':{'en': 'CENTENNIAL'},
'1787916':{'en': 'CENTENNIAL'},
'1787917':{'en': 'CENTENNIAL'},
'1787922':{'en': 'SunCom Wireless Puerto Rico'},
'1787923':{'en': 'SunCom Wireless Puerto Rico'},
'1787924':{'en': 'CENTENNIAL'},
'1787926':{'en': 'CENTENNIAL'},
'1787927':{'en': 'CENTENNIAL'},
'1787928':{'en': 'CENTENNIAL'},
'1787933':{'en': 'CENTENNIAL'},
'1787935':{'en': 'CENTENNIAL'},
'1787937':{'en': 'CENTENNIAL'},
'1787940':{'en': 'CENTENNIAL'},
'1787947':{'en': 'CENTENNIAL'},
'1787949':{'en': 'SunCom Wireless Puerto Rico'},
'1787952':{'en': 'CENTENNIAL'},
'1787953':{'en': 'CENTENNIAL'},
'1787954':{'en': 'CENTENNIAL'},
'1787957':{'en': 'CENTENNIAL'},
'1787961':{'en': 'CENTENNIAL'},
'1787968':{'en': 'CENTENNIAL'},
'1787969':{'en': 'CENTENNIAL'},
'1787971':{'en': 'CENTENNIAL'},
'1787975':{'en': 'CENTENNIAL'},
'1787978':{'en': 'CENTENNIAL'},
'1787992':{'en': 'CENTENNIAL'},
'1787993':{'en': 'CENTENNIAL'},
'1787998':{'en': 'CENTENNIAL'},
'1787999':{'en': 'CENTENNIAL'},
'180920':{'en': 'Tricom'},
'180922':{'en': 'Claro'},
'180923':{'en': 'Claro'},
'180924':{'en': 'Claro'},
'180925':{'en': 'Claro'},
'180926':{'en': 'Claro'},
'180927':{'en': 'Claro'},
'180928':{'en': 'Claro'},
'180929':{'en': 'Tricom'},
'18093':{'en': 'Claro'},
'180930':{'en': 'Viva'},
'180931':{'en': 'Tricom'},
'180932':{'en': 'Tricom'},
'180934':{'en': 'Tricom'},
'180941':{'en': 'Viva'},
'180942':{'en': 'Claro'},
'180943':{'en': 'Viva'},
'180944':{'en': 'Viva'},
'180945':{'en': 'Claro'},
'180947':{'en': 'Tricom'},
'180948':{'en': 'Claro'},
'180949':{'en': 'Claro'},
'180951':{'en': 'Claro'},
'180954':{'en': 'Claro'},
'180960':{'en': 'Claro'},
'180962':{'en': 'Tricom'},
'180963':{'en': 'Tricom'},
'180964':{'en': 'Tricom'},
'180965':{'en': 'Tricom'},
'180967':{'en': 'Claro'},
'180969':{'en': 'Claro'},
'180970':{'en': 'Claro'},
'180971':{'en': 'Claro'},
'180972':{'en': 'Claro'},
'180974':{'en': 'Claro'},
'180975':{'en': 'Claro'},
'180976':{'en': 'Claro'},
'180977':{'en': 'Viva'},
'180978':{'en': 'Claro'},
'180979':{'en': 'Claro'},
'18098':{'en': 'Orange'},
'180981':{'en': 'Viva'},
'180982':{'en': 'Claro'},
'180983':{'en': 'Claro'},
'180987':{'en': 'Tricom'},
'180991':{'en': 'Orange'},
'180992':{'en': 'Tricom'},
'180993':{'en': 'Tricom'},
'180994':{'en': 'Tricom'},
'180995':{'en': 'Claro'},
'180997':{'en': 'Orange'},
'180998':{'en': 'Orange'},
'180999':{'en': 'Tricom'},
'1868263':{'en': 'Digicel'},
'1868264':{'en': 'Digicel'},
'1868265':{'en': 'Digicel'},
'1868266':{'en': 'bmobile'},
'1868267':{'en': 'bmobile'},
'1868268':{'en': 'bmobile'},
'1868269':{'en': 'bmobile'},
'186827':{'en': 'bmobile'},
'186828':{'en': 'bmobile'},
'186829':{'en': 'bmobile'},
'18683':{'en': 'Digicel'},
'18684':{'en': 'bmobile'},
'1868620':{'en': 'bmobile'},
'1868678':{'en': 'bmobile'},
'186868':{'en': 'bmobile'},
'18687':{'en': 'bmobile'},
'186948':{'en': 'Cable & Wireless'},
'186955':{'en': 'CariGlobe St. Kitts'},
'186956':{'en': 'The Cable St. Kitts'},
'1869660':{'en': 'Cable & Wireless'},
'1869661':{'en': 'Cable & Wireless'},
'1869662':{'en': 'Cable & Wireless'},
'1869663':{'en': 'Cable & Wireless'},
'1869664':{'en': 'Cable & Wireless'},
'1869665':{'en': 'Cable & Wireless'},
'1869667':{'en': 'Cable & Wireless'},
'1869668':{'en': 'Cable & Wireless'},
'1869669':{'en': 'Cable & Wireless'},
'1869760':{'en': 'Digicel'},
'1869762':{'en': 'Digicel'},
'1869763':{'en': 'Digicel'},
'1869764':{'en': 'Digicel'},
'1869765':{'en': 'Digicel'},
'1869766':{'en': 'Digicel'},
'1876210':{'en': 'Cable & Wireless'},
'187622':{'en': 'Cable & Wireless'},
'187623':{'en': 'Cable & Wireless'},
'187624':{'en': 'Digicel'},
'187625':{'en': 'Digicel'},
'187626':{'en': 'Digicel'},
'1876275':{'en': 'Digicel'},
'1876276':{'en': 'Digicel'},
'1876277':{'en': 'Digicel'},
'1876278':{'en': 'Digicel'},
'1876279':{'en': 'Digicel'},
'187628':{'en': 'Digicel'},
'187629':{'en': 'Digicel'},
'187630':{'en': 'Digicel'},
'1876310':{'en': 'Cable & Wireless'},
'1876312':{'en': 'Cable & Wireless'},
'1876313':{'en': 'Cable & Wireless'},
'1876314':{'en': 'Cable & Wireless'},
'1876315':{'en': 'Cable & Wireless'},
'1876316':{'en': 'Cable & Wireless'},
'1876317':{'en': 'Cable & Wireless'},
'1876318':{'en': 'Cable & Wireless'},
'1876319':{'en': 'Cable & Wireless'},
'187632':{'en': 'Cable & Wireless'},
'187633':{'en': 'Cable & Wireless'},
'187634':{'en': 'Cable & Wireless'},
'187635':{'en': 'Digicel'},
'187636':{'en': 'Digicel'},
'187637':{'en': 'Digicel'},
'187638':{'en': 'Digicel'},
'187639':{'en': 'Digicel'},
'187640':{'en': 'Digicel'},
'187641':{'en': 'Digicel'},
'187642':{'en': 'Digicel'},
'187643':{'en': 'Digicel'},
'1876440':{'en': 'Digicel'},
'1876441':{'en': 'Digicel'},
'1876442':{'en': 'Digicel'},
'1876443':{'en': 'Digicel'},
'1876445':{'en': 'Digicel'},
'1876446':{'en': 'Digicel'},
'1876447':{'en': 'Digicel'},
'1876448':{'en': 'Digicel'},
'1876449':{'en': 'Digicel'},
'187645':{'en': 'Digicel'},
'187646':{'en': 'Digicel'},
'187647':{'en': 'Digicel'},
'187648':{'en': 'Digicel'},
'187649':{'en': 'Digicel'},
'1876501':{'en': 'Cable & Wireless'},
'1876503':{'en': 'Digicel'},
'1876504':{'en': 'Digicel'},
'1876505':{'en': 'Digicel'},
'1876506':{'en': 'Digicel'},
'1876507':{'en': 'Digicel'},
'1876508':{'en': 'Digicel'},
'1876509':{'en': 'Digicel'},
'1876515':{'en': 'Cable & Wireless'},
'1876517':{'en': 'Cable & Wireless'},
'1876519':{'en': 'Cable & Wireless'},
'187652':{'en': 'Digicel'},
'187653':{'en': 'Cable & Wireless'},
'187654':{'en': 'Cable & Wireless'},
'1876550':{'en': 'Digicel'},
'1876551':{'en': 'Digicel'},
'1876552':{'en': 'Digicel'},
'1876553':{'en': 'Digicel'},
'1876554':{'en': 'Digicel'},
'1876556':{'en': 'Digicel'},
'1876557':{'en': 'Digicel'},
'1876558':{'en': 'Digicel'},
'1876559':{'en': 'Digicel'},
'1876560':{'en': 'Digicel'},
'1876561':{'en': 'Digicel'},
'1876562':{'en': 'Digicel'},
'1876564':{'en': 'Digicel'},
'1876565':{'en': 'Digicel'},
'1876566':{'en': 'Digicel'},
'1876567':{'en': 'Digicel'},
'1876568':{'en': 'Digicel'},
'1876569':{'en': 'Digicel'},
'187657':{'en': 'Digicel'},
'187658':{'en': 'Digicel'},
'187659':{'en': 'Digicel'},
'1876648':{'en': 'Digicel'},
'1876649':{'en': 'Digicel'},
'1876666':{'en': 'Digicel'},
'1876667':{'en': 'Digicel'},
'1876700':{'en': 'Cable & Wireless'},
'1876707':{'en': 'Cable & Wireless'},
'187677':{'en': 'Cable & Wireless'},
'1876781':{'en': 'Cable & Wireless'},
'1876782':{'en': 'Cable & Wireless'},
'1876783':{'en': 'Cable & Wireless'},
'1876784':{'en': 'Cable & Wireless'},
'1876787':{'en': 'Cable & Wireless'},
'1876788':{'en': 'Cable & Wireless'},
'1876789':{'en': 'Cable & Wireless'},
'1876790':{'en': 'Cable & Wireless'},
'1876791':{'en': 'Cable & Wireless'},
'1876792':{'en': 'Cable & Wireless'},
'1876793':{'en': 'Cable & Wireless'},
'1876796':{'en': 'Cable & Wireless'},
'1876797':{'en': 'Cable & Wireless'},
'1876798':{'en': 'Cable & Wireless'},
'1876799':{'en': 'Cable & Wireless'},
'187680':{'en': 'Cable & Wireless'},
'1876810':{'en': 'Cable & Wireless'},
'1876812':{'en': 'Cable & Wireless'},
'1876813':{'en': 'Cable & Wireless'},
'1876814':{'en': 'Cable & Wireless'},
'1876815':{'en': 'Cable & Wireless'},
'1876816':{'en': 'Cable & Wireless'},
'1876817':{'en': 'Cable & Wireless'},
'1876818':{'en': 'Cable & Wireless'},
'1876819':{'en': 'Cable & Wireless'},
'187682':{'en': 'Cable & Wireless'},
'187683':{'en': 'Cable & Wireless'},
'187684':{'en': 'Digicel'},
'187685':{'en': 'Digicel'},
'187686':{'en': 'Digicel'},
'187687':{'en': 'Digicel'},
'187688':{'en': 'Digicel'},
'187689':{'en': 'Digicel'},
'1876909':{'en': 'Cable & Wireless'},
'1876919':{'en': 'Cable & Wireless'},
'1876990':{'en': 'Cable & Wireless'},
'1876995':{'en': 'Cable & Wireless'},
'1876997':{'en': 'Cable & Wireless'},
'1876999':{'en': 'Cable & Wireless'},
'1939201':{'en': 'CENTENNIAL'},
'1939212':{'en': 'CENTENNIAL'},
'1939214':{'en': 'CENTENNIAL'},
'1939240':{'en': 'SunCom Wireless Puerto Rico'},
'19392410':{'en': 'Claro'},
'19392411':{'en': 'Claro'},
'19392412':{'en': 'Claro'},
'19392413':{'en': 'Claro'},
'19392414':{'en': 'Claro'},
'19392415':{'en': 'Claro'},
'19392416':{'en': 'Claro'},
'193924199':{'en': 'Claro'},
'1939242':{'en': 'Claro'},
'19392433':{'en': 'Claro'},
'19392434':{'en': 'Claro'},
'19392435':{'en': 'Claro'},
'19392436':{'en': 'Claro'},
'19392437':{'en': 'Claro'},
'19392438':{'en': 'Claro'},
'19392439':{'en': 'Claro'},
'1939244':{'en': 'Claro'},
'1939245':{'en': 'Claro'},
'1939246':{'en': 'Claro'},
'1939247':{'en': 'Claro'},
'1939248':{'en': 'Claro'},
'1939249':{'en': 'Claro'},
'193925':{'en': 'Claro'},
'1939252':{'en': 'CENTENNIAL'},
'1939307':{'en': 'CENTENNIAL'},
'1939325':{'en': 'SunCom Wireless Puerto Rico'},
'1939329':{'en': 'CENTENNIAL'},
'1939334':{'en': 'Claro'},
'1939339':{'en': 'SunCom Wireless Puerto Rico'},
'1939394':{'en': 'CENTENNIAL'},
'1939440':{'en': 'CENTENNIAL'},
'1939628':{'en': 'CENTENNIAL'},
'1939630':{'en': 'CENTENNIAL'},
'1939639':{'en': 'CENTENNIAL'},
'1939640':{'en': 'CENTENNIAL'},
'1939642':{'en': 'CENTENNIAL'},
'1939644':{'en': 'CENTENNIAL'},
'1939645':{'en': 'CENTENNIAL'},
'1939697':{'en': 'CENTENNIAL'},
'1939717':{'en': 'CENTENNIAL'},
'1939731':{'en': 'CENTENNIAL'},
'1939777':{'en': 'Claro'},
'1939865':{'en': 'SunCom Wireless Puerto Rico'},
'1939891':{'en': 'SunCom Wireless Puerto Rico'},
'1939910':{'en': 'CENTENNIAL'},
'1939940':{'en': 'CENTENNIAL'},
'1939969':{'en': 'CENTENNIAL'},
'2010':{'en': 'Vodafone'},
'2011':{'en': 'Etisalat'},
'2012':{'en': 'Orange'},
'2015':{'en': 'TE'},
'21112':{'en': 'Sudatel Group'},
'21191':{'en': 'Zain'},
'21192':{'en': 'MTN'},
'21195':{'en': 'Network of the World'},
'21197':{'en': 'Gemtel'},
'21199':{'en': 'MTN'},
'21260':{'en': 'Inwi'},
'21261':{'en': 'Maroc Telecom'},
'212612':{'en': u('M\u00e9ditel')},
'212614':{'en': u('M\u00e9ditel')},
'212617':{'en': u('M\u00e9ditel')},
'212619':{'en': u('M\u00e9ditel')},
'212620':{'en': u('M\u00e9ditel')},
'212621':{'en': u('M\u00e9ditel')},
'212622':{'en': 'Maroc Telecom'},
'212623':{'en': 'Maroc Telecom'},
'212624':{'en': 'Maroc Telecom'},
'212625':{'en': u('M\u00e9ditel')},
'212626':{'en': 'Inwi'},
'212627':{'en': 'Inwi'},
'212628':{'en': 'Maroc Telecom'},
'212629':{'en': 'Inwi'},
'212630':{'en': 'Inwi'},
'212631':{'en': u('M\u00e9ditel')},
'212632':{'en': u('M\u00e9ditel')},
'212633':{'en': 'Inwi'},
'212634':{'en': 'Inwi'},
'212635':{'en': 'Inwi'},
'212636':{'en': 'Maroc Telecom'},
'212637':{'en': 'Maroc Telecom'},
'212638':{'en': 'Inwi'},
'212639':{'en': 'Maroc Telecom'},
'212640':{'en': 'Inwi'},
'212641':{'en': 'Maroc Telecom'},
'212642':{'en': 'Maroc Telecom'},
'212643':{'en': 'Maroc Telecom'},
'212644':{'en': u('M\u00e9ditel')},
'212645':{'en': u('M\u00e9ditel')},
'212646':{'en': 'Inwi'},
'212647':{'en': 'Inwi'},
'212648':{'en': 'Maroc Telecom'},
'212649':{'en': u('M\u00e9ditel')},
'21265':{'en': 'Maroc Telecom'},
'212656':{'en': u('M\u00e9ditel')},
'212657':{'en': u('M\u00e9ditel')},
'212660':{'en': u('M\u00e9ditel')},
'212661':{'en': 'Maroc Telecom'},
'212662':{'en': 'Maroc Telecom'},
'212663':{'en': u('M\u00e9ditel')},
'212664':{'en': u('M\u00e9ditel')},
'212665':{'en': u('M\u00e9ditel')},
'212666':{'en': 'Maroc Telecom'},
'212667':{'en': 'Maroc Telecom'},
'212668':{'en': 'Maroc Telecom'},
'212669':{'en': u('M\u00e9ditel')},
'21267':{'en': 'Maroc Telecom'},
'212674':{'en': u('M\u00e9ditel')},
'212675':{'en': u('M\u00e9ditel')},
'212679':{'en': u('M\u00e9ditel')},
'212680':{'en': 'Inwi'},
'212681':{'en': 'Inwi'},
'212682':{'en': 'Maroc Telecom'},
'212684':{'en': u('M\u00e9ditel')},
'212687':{'en': 'Inwi'},
'212688':{'en': u('M\u00e9ditel')},
'212689':{'en': 'Maroc Telecom'},
'212690':{'en': 'Inwi'},
'212691':{'en': u('M\u00e9ditel')},
'2126921':{'en': 'Al Hourria Telecom'},
'2126922':{'en': 'Al Hourria Telecom'},
'212693':{'en': u('M\u00e9ditel')},
'212694':{'en': u('M\u00e9ditel')},
'212695':{'en': 'Inwi'},
'212696':{'en': 'Maroc Telecom'},
'212697':{'en': 'Maroc Telecom'},
'212698':{'en': 'Inwi'},
'212699':{'en': 'Inwi'},
'212700':{'en': 'Inwi'},
'212706':{'en': 'Inwi'},
'212707':{'en': 'Inwi'},
'212708':{'en': 'Inwi'},
'21276':{'en': 'Maroc Telecom'},
'21277':{'en': u('M\u00e9ditel')},
'2135':{'en': 'Ooredoo'},
'2136':{'en': 'Mobilis'},
'2137':{'en': 'Djezzy'},
'2162':{'en': 'Ooredoo'},
'21640':{'en': 'Tunisie Telecom'},
'21641':{'en': 'Tunisie Telecom'},
'21642':{'en': 'Tunisie Telecom'},
'21643':{'en': 'Lyca Mobile'},
'21644':{'en': 'Tunisie Telecom'},
'21645':{'en': 'Watany Ettisalat'},
'21646':{'en': 'Ooredoo'},
'21647':{'en': 'Tunisie Telecom'},
'2165':{'en': 'Orange'},
'2169':{'en': 'Tunisie Telecom'},
'21891':{'en': 'Al-Madar'},
'21892':{'en': 'Libyana'},
'21893':{'en': 'Al-Madar'},
'21894':{'en': 'Libyana'},
'21895':{'en': 'Libya Telecom & Technology'},
'21896':{'en': 'Libya Telecom & Technology'},
'2202':{'en': 'Africell'},
'2203':{'en': 'QCell'},
'22050':{'en': 'QCell'},
'22051':{'en': 'QCell'},
'22052':{'en': 'QCell'},
'22053':{'en': 'QCell'},
'22058':{'en': 'QCell'},
'22059':{'en': 'QCell'},
'2206':{'en': 'Comium'},
'2207':{'en': 'Africell'},
'2209':{'en': 'Gamcel'},
'22170':{'en': 'Expresso'},
'22172':{'en': 'HAYO'},
'22176':{'en': 'Tigo'},
'22177':{'en': 'Orange'},
'22178':{'en': 'Orange'},
'22179':{'en': 'ADIE'},
'22220':{'en': 'Chinguitel'},
'22221':{'en': 'Chinguitel'},
'22222':{'en': 'Chinguitel'},
'22223':{'en': 'Chinguitel'},
'22224':{'en': 'Chinguitel'},
'22226':{'en': 'Chinguitel'},
'22227':{'en': 'Chinguitel'},
'22228':{'en': 'Chinguitel'},
'22229':{'en': 'Chinguitel'},
'22230':{'en': 'Mattel'},
'22231':{'en': 'Mattel'},
'22232':{'en': 'Mattel'},
'22233':{'en': 'Mattel'},
'22234':{'en': 'Mattel'},
'22236':{'en': 'Mattel'},
'22237':{'en': 'Mattel'},
'22238':{'en': 'Mattel'},
'22239':{'en': 'Mattel'},
'22240':{'en': 'Mauritel'},
'22241':{'en': 'Mauritel'},
'22242':{'en': 'Mauritel'},
'22243':{'en': 'Mauritel'},
'22244':{'en': 'Mauritel'},
'22246':{'en': 'Mauritel'},
'22247':{'en': 'Mauritel'},
'22248':{'en': 'Mauritel'},
'22249':{'en': 'Mauritel'},
'223200':{'en': 'Orange'},
'2232079':{'en': 'Sotelma'},
'223217':{'en': 'Sotelma'},
'2235':{'en': 'Atel'},
'2236':{'en': 'Sotelma'},
'2237':{'en': 'Orange'},
'22382':{'en': 'Orange'},
'22383':{'en': 'Orange'},
'22389':{'en': 'Sotelma'},
'22390':{'en': 'Orange'},
'22391':{'en': 'Orange'},
'22392':{'en': 'Orange'},
'22393':{'en': 'Orange'},
'22394':{'en': 'Orange'},
'22395':{'en': 'Sotelma'},
'22396':{'en': 'Sotelma'},
'22397':{'en': 'Sotelma'},
'22398':{'en': 'Sotelma'},
'22399':{'en': 'Sotelma'},
'22460':{'en': 'Sotelgui'},
'22462':{'en': 'Orange'},
'22463':{'en': 'Intercel'},
'22465':{'en': 'Cellcom'},
'22466':{'en': 'Areeba'},
'22501':{'en': 'Moov'},
'22502':{'en': 'Moov'},
'22503':{'en': 'Moov'},
'22504':{'en': 'MTN'},
'22505':{'en': 'MTN'},
'22506':{'en': 'MTN'},
'22507':{'en': 'Orange'},
'22508':{'en': 'Orange'},
'22509':{'en': 'Orange'},
'225208':{'en': 'Moov'},
'225218':{'en': 'Moov'},
'225228':{'en': 'Moov'},
'225238':{'en': 'Moov'},
'22540':{'en': 'Moov'},
'22541':{'en': 'Moov'},
'22542':{'en': 'Moov'},
'22543':{'en': 'Moov'},
'22544':{'en': 'MTN'},
'22545':{'en': 'MTN'},
'22546':{'en': 'MTN'},
'22547':{'en': 'Orange'},
'22548':{'en': 'Orange'},
'22549':{'en': 'Orange'},
'22550':{'en': 'Moov'},
'22551':{'en': 'Moov'},
'22552':{'en': 'Moov'},
'22553':{'en': 'Moov'},
'22554':{'en': 'MTN'},
'22555':{'en': 'MTN'},
'22556':{'en': 'MTN'},
'22557':{'en': 'Orange'},
'22558':{'en': 'Orange'},
'22559':{'en': 'Orange'},
'22560':{'en': 'GreenN'},
'22561':{'en': 'GreenN'},
'22564':{'en': 'MTN'},
'22565':{'en': 'MTN'},
'22566':{'en': 'MTN'},
'22567':{'en': 'Orange'},
'22568':{'en': 'Orange'},
'22569':{'en': 'Aircom'},
'22570':{'en': 'Moov'},
'22571':{'en': 'Moov'},
'22572':{'en': 'Moov'},
'22573':{'en': 'Moov'},
'22574':{'en': 'MTN'},
'22575':{'en': 'MTN'},
'22576':{'en': 'MTN'},
'22577':{'en': 'Orange'},
'22578':{'en': 'Orange'},
'22579':{'en': 'Orange'},
'22584':{'en': 'MTN'},
'22585':{'en': 'MTN'},
'22586':{'en': 'MTN'},
'22587':{'en': 'Orange'},
'22588':{'en': 'Orange'},
'22589':{'en': 'Orange'},
'22595':{'en': 'MTN'},
'22597':{'en': 'Orange'},
'22601':{'en': 'Onatel'},
'22602':{'en': 'Onatel'},
'22607':{'en': 'Orange'},
'22651':{'en': 'Telmob'},
'22652':{'en': 'Telmob'},
'22653':{'en': 'Onatel'},
'22654':{'en': 'Orange'},
'22655':{'en': 'Orange'},
'22656':{'en': 'Orange'},
'22657':{'en': 'Orange'},
'22658':{'en': 'Telecel Faso'},
'22660':{'en': 'Telmob'},
'22661':{'en': 'Telmob'},
'22662':{'en': 'Telmob'},
'22663':{'en': 'Telmob'},
'22664':{'en': 'Orange'},
'22665':{'en': 'Orange'},
'22666':{'en': 'Orange'},
'22667':{'en': 'Orange'},
'22668':{'en': 'Telecel Faso'},
'22669':{'en': 'Telecel Faso'},
'22670':{'en': 'Telmob'},
'22671':{'en': 'Telmob'},
'22672':{'en': 'Telmob'},
'22673':{'en': 'Telmob'},
'22674':{'en': 'Orange'},
'22675':{'en': 'Orange'},
'22676':{'en': 'Orange'},
'22677':{'en': 'Orange'},
'22678':{'en': 'Telecel Faso'},
'22679':{'en': 'Telecel Faso'},
'22723':{'en': 'Orange'},
'22780':{'en': 'Orange'},
'22781':{'en': 'Orange'},
'22788':{'en': 'Airtel'},
'22789':{'en': 'Airtel'},
'22790':{'en': 'Orange'},
'22791':{'en': 'Orange'},
'22792':{'en': 'Orange'},
'22793':{'en': 'SahelCom'},
'22794':{'en': 'Moov'},
'22795':{'en': 'Moov'},
'22796':{'en': 'Airtel'},
'22797':{'en': 'Airtel'},
'22798':{'en': 'Airtel'},
'22799':{'en': 'Airtel'},
'22870':{'en': 'TOGOCEL'},
'22879':{'en': 'Moov'},
'22890':{'en': 'TOGOCEL'},
'22891':{'en': 'TOGOCEL'},
'22892':{'en': 'TOGOCEL'},
'22893':{'en': 'TOGOCEL'},
'22896':{'en': 'Moov'},
'22897':{'en': 'TOGOCEL'},
'22898':{'en': 'Moov'},
'22899':{'en': 'Moov'},
'2295':{'en': 'MTN'},
'22960':{'en': 'Moov'},
'22961':{'en': 'MTN'},
'22962':{'en': 'MTN'},
'22963':{'en': 'Moov'},
'22964':{'en': 'Moov'},
'22965':{'en': 'Moov'},
'22966':{'en': 'MTN'},
'22967':{'en': 'MTN'},
'22968':{'en': 'Moov'},
'22969':{'en': 'MTN'},
'22990':{'en': 'Moov'},
'22991':{'en': 'Moov'},
'22993':{'en': 'BLK'},
'22994':{'en': 'Moov'},
'22995':{'en': 'Moov'},
'22997':{'en': 'MTN'},
'22998':{'en': 'Moov'},
'22999':{'en': 'Moov'},
'230525':{'en': 'Cellplus'},
'230528':{'en': 'MTML'},
'230529':{'en': 'MTML'},
'23054':{'en': 'Emtel'},
'2305471':{'en': 'Cellplus'},
'23057':{'en': 'Cellplus'},
'230571':{'en': 'Emtel'},
'230572':{'en': 'Emtel'},
'230573':{'en': 'Emtel'},
'230574':{'en': 'Emtel'},
'230580':{'en': 'Cellplus'},
'230581':{'en': 'Cellplus'},
'230582':{'en': 'Cellplus'},
'230583':{'en': 'Cellplus'},
'230584':{'en': 'Emtel'},
'230585':{'en': 'Emtel'},
'230586':{'en': 'MTML'},
'2305871':{'en': 'MTML'},
'2305875':{'en': 'Cellplus'},
'2305876':{'en': 'Cellplus'},
'2305877':{'en': 'Cellplus'},
'2305878':{'en': 'Cellplus'},
'230588':{'en': 'MTML'},
'230589':{'en': 'MTML'},
'230590':{'en': 'Cellplus'},
'230591':{'en': 'Cellplus'},
'230592':{'en': 'Cellplus'},
'230593':{'en': 'Emtel'},
'230594':{'en': 'Cellplus'},
'230595':{'en': 'MTML'},
'230596':{'en': 'MTML'},
'230597':{'en': 'Emtel'},
'230598':{'en': 'Emtel'},
'231330':{'en': 'West Africa Telecom'},
'231555':{'en': 'Lonestar Cell'},
'2316':{'en': 'Lonestar Cell'},
'2317':{'en': 'Orange'},
'2318':{'en': 'Lonestar Cell'},
'23225':{'en': 'Sierratel'},
'23230':{'en': 'Africell'},
'23231':{'en': 'QCELL'},
'23233':{'en': 'Africell'},
'23234':{'en': 'QCELL'},
'23235':{'en': 'IPTEL'},
'2326':{'en': 'Onlime'},
'23274':{'en': 'Orange'},
'23275':{'en': 'Orange'},
'23276':{'en': 'Orange'},
'23277':{'en': 'Africell'},
'23278':{'en': 'Orange'},
'23279':{'en': 'Orange'},
'2328':{'en': 'Africell'},
'2329':{'en': 'Africell'},
'23320':{'en': 'Vodafone'},
'23323':{'en': 'Globacom (Zain)'},
'23324':{'en': 'MTN'},
'23326':{'en': 'Airtel'},
'23327':{'en': 'tiGO'},
'23328':{'en': 'Expresso'},
'23350':{'en': 'Vodafone'},
'23354':{'en': 'MTN'},
'23355':{'en': 'MTN'},
'23356':{'en': 'Airtel'},
'23357':{'en': 'tiGO'},
'23359':{'en': 'MTN'},
'234701':{'en': 'Airtel'},
'2347020':{'en': 'Smile'},
'2347021':{'en': 'Ntel'},
'2347022':{'en': 'Ntel'},
'2347024':{'en': 'Prestel'},
'2347025':{'en': 'Visafone'},
'2347026':{'en': 'Visafone'},
'2347027':{'en': 'Multilinks'},
'2347028':{'en': 'Starcomms'},
'2347029':{'en': 'Starcomms'},
'234703':{'en': 'MTN'},
'234704':{'en': 'Visafone'},
'234705':{'en': 'Glo'},
'234706':{'en': 'MTN'},
'234708':{'en': 'Airtel'},
'234709':{'en': 'Multilinks'},
'234801':{'en': 'Megatech'},
'234802':{'en': 'Airtel'},
'234803':{'en': 'MTN'},
'234804':{'en': 'Ntel'},
'234805':{'en': 'Glo'},
'234806':{'en': 'MTN'},
'234807':{'en': 'Glo'},
'234808':{'en': 'Airtel'},
'234809':{'en': '9mobile'},
'234810':{'en': 'MTN'},
'234811':{'en': 'Glo'},
'234812':{'en': 'Airtel'},
'234813':{'en': 'MTN'},
'234814':{'en': 'MTN'},
'234815':{'en': 'Glo'},
'234816':{'en': 'MTN'},
'234817':{'en': '9mobile'},
'234818':{'en': '9mobile'},
'234819':{'en': 'Starcomms'},
'234901':{'en': 'Airtel'},
'234902':{'en': 'Airtel'},
'234903':{'en': 'MTN'},
'234904':{'en': 'Airtel'},
'234905':{'en': 'Glo'},
'234906':{'en': 'MTN'},
'234907':{'en': 'Airtel'},
'234908':{'en': '9mobile'},
'234909':{'en': '9mobile'},
'2356':{'en': 'Airtel'},
'2357':{'en': 'Sotel'},
'2359':{'en': 'Tigo'},
'23670':{'en': 'A-Cell'},
'23672':{'en': 'Orange'},
'23675':{'en': 'Telecel'},
'23677':{'en': 'Nationlink'},
'237650':{'en': 'MTN Cameroon'},
'237651':{'en': 'MTN Cameroon'},
'237652':{'en': 'MTN Cameroon'},
'237653':{'en': 'MTN Cameroon'},
'237654':{'en': 'MTN Cameroon'},
'237655':{'en': 'Orange'},
'237656':{'en': 'Orange'},
'237657':{'en': 'Orange'},
'237658':{'en': 'Orange'},
'237659':{'en': 'Orange'},
'23766':{'en': 'NEXTTEL'},
'23767':{'en': 'MTN Cameroon'},
'23768':{'en': 'NEXTTEL'},
'237680':{'en': 'MTN Cameroon'},
'237681':{'en': 'MTN Cameroon'},
'237682':{'en': 'MTN Cameroon'},
'237683':{'en': 'MTN Cameroon'},
'23769':{'en': 'Orange'},
'23833':{'en': 'T+'},
'23836':{'en': 'CVMOVEL'},
'23843':{'en': 'T+'},
'23846':{'en': 'CVMOVEL'},
'23851':{'en': 'T+'},
'23852':{'en': 'T+'},
'23853':{'en': 'T+'},
'23858':{'en': 'CVMOVEL'},
'23859':{'en': 'CVMOVEL'},
'23891':{'en': 'T+'},
'23892':{'en': 'T+'},
'23893':{'en': 'T+'},
'23895':{'en': 'CVMOVEL'},
'23897':{'en': 'CVMOVEL'},
'23898':{'en': 'CVMOVEL'},
'23899':{'en': 'CVMOVEL'},
'23990':{'en': 'Unitel'},
'23998':{'en': 'CSTmovel'},
'23999':{'en': 'CSTmovel'},
'2402':{'en': 'GETESA'},
'240550':{'en': 'Muni'},
'240551':{'en': 'HiTS'},
'24104':{'en': 'Airtel'},
'24105':{'en': 'Moov'},
'24106':{'en': 'Libertis'},
'24107':{'en': 'Airtel'},
'24120':{'en': 'Libertis'},
'24121':{'en': 'Libertis'},
'24122':{'en': 'Libertis'},
'24123':{'en': 'Libertis'},
'24124':{'en': 'Libertis'},
'24125':{'en': 'Libertis'},
'24126':{'en': 'Libertis'},
'24127':{'en': 'Libertis'},
'2413':{'en': 'Libertis'},
'2414':{'en': 'Airtel'},
'2415':{'en': 'Moov'},
'2416':{'en': 'Libertis'},
'24165':{'en': 'Moov'},
'2417':{'en': 'Airtel'},
'24201':{'en': 'Equateur Telecom'},
'24204':{'en': 'Warid'},
'24205':{'en': 'Airtel'},
'24206':{'en': 'MTN'},
'24380':{'en': 'Supercell'},
'24381':{'en': 'Vodacom'},
'24382':{'en': 'Vodacom'},
'24384':{'en': 'CCT'},
'24388':{'en': 'Yozma Timeturns sprl -YTT'},
'24389':{'en': 'Sait-Telecom (Oasis)'},
'24390':{'en': 'Africell'},
'24391':{'en': 'Africell'},
'24397':{'en': 'Zain'},
'24398':{'en': 'Zain'},
'24399':{'en': 'Zain'},
'24491':{'en': 'Movicel'},
'24492':{'en': 'UNITEL'},
'24493':{'en': 'UNITEL'},
'24494':{'en': 'UNITEL'},
'24499':{'en': 'Movicel'},
'24595':{'en': 'Orange'},
'24596':{'en': 'Spacetel'},
'24597':{'en': 'Guinetel'},
'24638':{'en': 'Sure Ltd'},
'24741':{'en': 'Sure South Atlantic'},
'24742':{'en': 'Sure South Atlantic'},
'24743':{'en': 'Sure South Atlantic'},
'24745':{'en': 'Sure South Atlantic'},
'24746':{'en': 'Sure South Atlantic'},
'24747':{'en': 'Sure South Atlantic'},
'24748':{'en': 'Sure South Atlantic'},
'24825':{'en': 'CWS'},
'24826':{'en': 'CWS'},
'24827':{'en': 'Airtel'},
'24828':{'en': 'Airtel'},
'24910':{'en': 'Sudatel'},
'24911':{'en': 'Sudatel'},
'24912':{'en': 'Sudatel'},
'24990':{'en': 'Zain'},
'24991':{'en': 'Zain'},
'24992':{'en': 'MTN'},
'24993':{'en': 'MTN'},
'24995':{'en': 'Network of The World Ltd'},
'24996':{'en': 'Zain'},
'24999':{'en': 'MTN'},
'25072':{'en': 'TIGO'},
'25073':{'en': 'Airtel'},
'25078':{'en': 'MTN'},
'2519':{'en': 'Ethio Telecom'},
'25224':{'en': 'Telesom'},
'25228':{'en': 'Nationlink'},
'25235':{'en': 'AirSom'},
'25239':{'en': 'AirSom'},
'25248':{'en': 'AirSom'},
'25249':{'en': 'AirSom'},
'25262':{'en': 'Somtel'},
'25263':{'en': 'Telesom'},
'25264':{'en': 'Somali Networks'},
'25265':{'en': 'Somtel'},
'25266':{'en': 'Somtel'},
'25267':{'en': 'Nationlink'},
'25268':{'en': 'Nationlink'},
'25269':{'en': 'Nationlink'},
'25279':{'en': 'Somtel'},
'25280':{'en': 'Somali Networks'},
'25288':{'en': 'Somali Networks'},
'2529':{'en': 'STG'},
'25290':{'en': 'Golis Telecom'},
'2537':{'en': 'Evatis'},
'25410':{'en': 'Airtel'},
'25411':{'en': 'Safaricom'},
'25470':{'en': 'Safaricom'},
'25471':{'en': 'Safaricom'},
'25472':{'en': 'Safaricom'},
'25473':{'en': 'Airtel'},
'25474':{'en': 'Safaricom'},
'254744':{'en': 'Homeland Media'},
'254747':{'en': 'JTL'},
'254749':{'en': 'WiAfrica'},
'25475':{'en': 'Airtel'},
'254757':{'en': 'Safaricom'},
'254758':{'en': 'Safaricom'},
'254759':{'en': 'Safaricom'},
'254760':{'en': 'Mobile Pay'},
'254761':{'en': 'Airtel'},
'254762':{'en': 'Airtel'},
'254763':{'en': 'Finserve'},
'254764':{'en': 'Finserve'},
'254765':{'en': 'Finserve'},
'254766':{'en': 'Finserve'},
'254767':{'en': 'Sema Mobile'},
'254768':{'en': 'Safaricom'},
'254769':{'en': 'Safaricom'},
'25477':{'en': 'Telkom'},
'25478':{'en': 'Airtel'},
'25479':{'en': 'Safaricom'},
'25562':{'en': 'Viettel'},
'25563':{'en': 'MTC'},
'25564':{'en': 'Cootel'},
'25565':{'en': 'tiGO'},
'25566':{'en': 'SMILE'},
'25567':{'en': 'tiGO'},
'25568':{'en': 'Airtel'},
'25569':{'en': 'Airtel'},
'25571':{'en': 'tiGO'},
'25573':{'en': 'Tanzania Telecom'},
'25574':{'en': 'Vodacom'},
'25575':{'en': 'Vodacom'},
'25576':{'en': 'Vodacom'},
'25577':{'en': 'Zantel'},
'25578':{'en': 'Airtel'},
'25579':{'en': 'Benson Informatics'},
'25670':{'en': 'Airtel'},
'25671':{'en': 'UTL'},
'256720':{'en': 'Smile'},
'256726':{'en': 'Tangerine'},
'25673':{'en': 'Hamilton Telecom'},
'25674':{'en': 'Sure Telecom'},
'25675':{'en': 'Airtel'},
'25677':{'en': 'MTN'},
'25678':{'en': 'MTN'},
'25679':{'en': 'Africell'},
'25729':{'en': 'Leo'},
'2573':{'en': 'Viettel'},
'2576':{'en': 'Viettel'},
'25771':{'en': 'Leo'},
'25772':{'en': 'Leo'},
'25775':{'en': 'Smart Mobile'},
'25776':{'en': 'Leo'},
'25777':{'en': 'Onatel'},
'25778':{'en': 'Smart Mobile'},
'25779':{'en': 'Leo'},
'25882':{'en': 'mcel'},
'25883':{'en': 'mcel'},
'25884':{'en': 'Vodacom'},
'25885':{'en': 'Vodacom'},
'25886':{'en': 'Movitel'},
'25887':{'en': 'Movitel'},
'25889':{'en': 'GMPCS'},
'26076':{'en': 'MTN'},
'26077':{'en': 'Airtel'},
'26095':{'en': 'ZAMTEL'},
'26096':{'en': 'MTN'},
'26097':{'en': 'Airtel'},
'26132':{'en': 'Orange'},
'26133':{'en': 'Airtel'},
'26134':{'en': 'Telma'},
'26139':{'en': 'Blueline'},
'26263900':{'en': 'Orange'},
'26263901':{'en': 'Orange'},
'26263902':{'en': 'Orange'},
'26263903':{'en': 'Only'},
'26263904':{'en': 'Only'},
'26263905':{'en': 'Only'},
'26263906':{'en': 'Only'},
'26263907':{'en': 'Only'},
'26263909':{'en': 'SFR'},
'26263910':{'en': 'SFR'},
'26263911':{'en': 'SFR'},
'26263919':{'en': 'Only'},
'2626392':{'en': 'SFR'},
'26263926':{'en': 'Only'},
'26263930':{'en': 'BJT'},
'26263939':{'en': 'Only'},
'2626394':{'en': 'SFR'},
'2626395':{'en': 'BJT'},
'26263960':{'en': 'Orange'},
'26263961':{'en': 'Orange'},
'26263962':{'en': 'Orange'},
'26263963':{'en': 'Orange'},
'26263964':{'en': 'Orange'},
'26263965':{'en': 'SFR'},
'26263966':{'en': 'SFR'},
'26263967':{'en': 'SFR'},
'26263968':{'en': 'SFR'},
'26263969':{'en': 'SFR'},
'26263970':{'en': 'BJT'},
'26263971':{'en': 'Only'},
'26263972':{'en': 'Only'},
'26263973':{'en': 'Only'},
'26263974':{'en': 'Only'},
'26263975':{'en': 'Only'},
'26263976':{'en': 'Orange'},
'26263977':{'en': 'Orange'},
'26263978':{'en': 'Orange'},
'26263979':{'en': 'Orange'},
'26263990':{'en': 'BJT'},
'26263994':{'en': 'Only'},
'26263995':{'en': 'Only'},
'26263996':{'en': 'Only'},
'26263997':{'en': 'Only'},
'26263999':{'en': 'Orange'},
'262692':{'en': 'SFR'},
'2626920':{'en': 'Orange'},
'2626922':{'en': 'Orange'},
'2626923':{'en': 'Orange'},
'26269240':{'en': 'Orange'},
'26269241':{'en': 'Orange'},
'26269242':{'en': 'Orange'},
'26269243':{'en': 'Orange'},
'26269244':{'en': 'Orange'},
'26269292':{'en': 'Only'},
'26269293':{'en': 'Only'},
'26269294':{'en': 'Only'},
'26269300':{'en': 'Orange'},
'26269301':{'en': 'SFR'},
'26269302':{'en': 'SFR'},
'26269303':{'en': 'SFR'},
'26269304':{'en': 'SFR'},
'26269306':{'en': 'Orange'},
'26269310':{'en': 'SFR'},
'26269311':{'en': 'Orange'},
'26269313':{'en': 'SFR'},
'26269320':{'en': 'SFR'},
'26269321':{'en': 'Orange'},
'26269322':{'en': 'Orange'},
'26269330':{'en': 'Only'},
'26269331':{'en': 'Only'},
'26269332':{'en': 'Only'},
'26269333':{'en': 'Orange'},
'26269339':{'en': 'Orange'},
'2626934':{'en': 'Only'},
'26269350':{'en': 'Only'},
'26269355':{'en': 'Orange'},
'26269360':{'en': 'Only'},
'26269361':{'en': 'ZEOP Mobile'},
'26269362':{'en': 'ZEOP Mobile'},
'26269366':{'en': 'Orange'},
'26269370':{'en': 'Only'},
'26269371':{'en': 'Only'},
'26269372':{'en': 'Only'},
'26269377':{'en': 'Orange'},
'26269380':{'en': 'Only'},
'26269381':{'en': 'Only'},
'26269382':{'en': 'Only'},
'26269383':{'en': 'Only'},
'26269388':{'en': 'Orange'},
'26269390':{'en': 'Orange'},
'26269391':{'en': 'Orange'},
'26269392':{'en': 'Orange'},
'26269393':{'en': 'Orange'},
'26269394':{'en': 'SFR'},
'26269397':{'en': 'SFR'},
'26269399':{'en': 'Orange'},
'2629':{'en': 'Orange'},
'26371':{'en': 'Net*One'},
'26373':{'en': 'Telecel'},
'26377':{'en': 'Econet'},
'26378':{'en': 'Econet'},
'26460':{'en': 'Telecom Namibia'},
'26481':{'en': 'MTC'},
'26482':{'en': 'Telecom Namibia'},
'26484':{'en': 'MTN'},
'26485':{'en': 'TN Mobile'},
'26511':{'en': 'Malawi Telecom-munications Ltd (MTL)'},
'2653':{'en': 'TNM'},
'2657':{'en': 'Globally Advanced Integrated Networks Ltd'},
'2658':{'en': 'TNM'},
'2659':{'en': 'Airtel'},
'2665':{'en': 'Vodacom Lesotho (Pty) Ltd'},
'2666':{'en': 'Econet Ezi-Cel Lesotho'},
'26771':{'en': 'Mascom'},
'26772':{'en': 'Orange'},
'26773':{'en': 'BTC Mobile'},
'26774':{'en': 'Mascom'},
'267743':{'en': 'Orange'},
'267744':{'en': 'Orange'},
'267748':{'en': 'Orange'},
'267749':{'en': 'BTC Mobile'},
'267750':{'en': 'Orange'},
'267751':{'en': 'Orange'},
'267752':{'en': 'Orange'},
'267753':{'en': 'Orange'},
'267754':{'en': 'Mascom'},
'267755':{'en': 'Mascom'},
'267756':{'en': 'Mascom'},
'267757':{'en': 'Orange'},
'267758':{'en': 'BTC Mobile'},
'267759':{'en': 'Mascom'},
'267760':{'en': 'Mascom'},
'267761':{'en': 'Mascom'},
'267762':{'en': 'Mascom'},
'267763':{'en': 'Orange'},
'267764':{'en': 'Orange'},
'267765':{'en': 'Orange'},
'267766':{'en': 'Mascom'},
'267767':{'en': 'Mascom'},
'267768':{'en': 'BTC Mobile'},
'267769':{'en': 'Orange'},
'267770':{'en': 'Mascom'},
'267771':{'en': 'Mascom'},
'267772':{'en': 'BTC Mobile'},
'267773':{'en': 'Orange'},
'267774':{'en': 'Orange'},
'267775':{'en': 'Orange'},
'267776':{'en': 'Mascom'},
'267777':{'en': 'Mascom'},
'267778':{'en': 'Mascom'},
'267779':{'en': 'Orange'},
'26876':{'en': 'Swazi MTN'},
'26877':{'en': 'SPTC'},
'26878':{'en': 'Swazi MTN'},
'26879':{'en': 'Swazi Mobile Ltd'},
'2693':{'en': 'Comores Telecom'},
'2694':{'en': 'TELCO'},
'2710492':{'en': 'Vodacom'},
'2710493':{'en': 'Vodacom'},
'2710494':{'en': 'Vodacom'},
'2712492':{'en': 'Vodacom'},
'27134920':{'en': 'Vodacom'},
'27134921':{'en': 'Vodacom'},
'27134922':{'en': 'Vodacom'},
'27134925':{'en': 'Vodacom'},
'27144950':{'en': 'Vodacom'},
'27144952':{'en': 'Vodacom'},
'27144953':{'en': 'Vodacom'},
'27144955':{'en': 'Vodacom'},
'27154920':{'en': 'Vodacom'},
'27154950':{'en': 'Vodacom'},
'27154951':{'en': 'Vodacom'},
'27164920':{'en': 'Vodacom'},
'27174920':{'en': 'Vodacom'},
'27184920':{'en': 'Vodacom'},
'2719':{'en': 'Telkom Mobile'},
'2721492':{'en': 'Vodacom'},
'27224950':{'en': 'Vodacom'},
'27274950':{'en': 'Vodacom'},
'27284920':{'en': 'Vodacom'},
'2731492':{'en': 'Vodacom'},
'27324920':{'en': 'Vodacom'},
'27334920':{'en': 'Vodacom'},
'27344920':{'en': 'Vodacom'},
'27354920':{'en': 'Vodacom'},
'27364920':{'en': 'Vodacom'},
'27394920':{'en': 'Vodacom'},
'27404920':{'en': 'Vodacom'},
'2741492':{'en': 'Vodacom'},
'27424920':{'en': 'Vodacom'},
'27434920':{'en': 'Vodacom'},
'27434921':{'en': 'Vodacom'},
'27444920':{'en': 'Vodacom'},
'27444921':{'en': 'Vodacom'},
'27454920':{'en': 'Vodacom'},
'27464920':{'en': 'Vodacom'},
'27474950':{'en': 'Vodacom'},
'27484920':{'en': 'Vodacom'},
'27494920':{'en': 'Vodacom'},
'2751492':{'en': 'Vodacom'},
'27544950':{'en': 'Vodacom'},
'27564920':{'en': 'Vodacom'},
'27574920':{'en': 'Vodacom'},
'27584920':{'en': 'Vodacom'},
'27603':{'en': 'MTN'},
'27604':{'en': 'MTN'},
'27605':{'en': 'MTN'},
'27606':{'en': 'Vodacom'},
'27607':{'en': 'Vodacom'},
'27608':{'en': 'Vodacom'},
'27609':{'en': 'Vodacom'},
'2761':{'en': 'Cell C'},
'27614':{'en': 'Telkom Mobile'},
'2762':{'en': 'Cell C'},
'2763':{'en': 'MTN'},
'27636':{'en': 'Vodacom'},
'27637':{'en': 'Vodacom'},
'27640':{'en': 'MTN'},
'27641':{'en': 'Cell C'},
'27642':{'en': 'Cell C'},
'27643':{'en': 'Cell C'},
'27644':{'en': 'Cell C'},
'27645':{'en': 'Cell C'},
'27646':{'en': 'Vodacom'},
'27647':{'en': 'Vodacom'},
'27648':{'en': 'Vodacom'},
'27649':{'en': 'Vodacom'},
'27650':{'en': 'Cell C'},
'27651':{'en': 'Cell C'},
'27652':{'en': 'Cell C'},
'27653':{'en': 'Cell C'},
'27654':{'en': 'Cell C'},
'27655':{'en': 'MTN'},
'27656':{'en': 'MTN'},
'27657':{'en': 'MTN'},
'27658':{'en': 'Telkom Mobile'},
'27659':{'en': 'Telkom Mobile'},
'27660':{'en': 'Vodacom'},
'27661':{'en': 'Vodacom'},
'27662':{'en': 'Vodacom'},
'27663':{'en': 'Vodacom'},
'27664':{'en': 'Vodacom'},
'27665':{'en': 'Vodacom'},
'27670':{'en': 'Telkom Mobile'},
'27671':{'en': 'Telkom Mobile'},
'27672':{'en': 'Telkom Mobile'},
'27673':{'en': 'Vodacom'},
'27674':{'en': 'Vodacom'},
'27675':{'en': 'Vodacom'},
'27676':{'en': 'Telkom Mobile'},
'27677':{'en': 'Telkom Mobile'},
'2771':{'en': 'Vodacom'},
'27710':{'en': 'MTN'},
'27717':{'en': 'MTN'},
'27718':{'en': 'MTN'},
'27719':{'en': 'MTN'},
'2772':{'en': 'Vodacom'},
'2773':{'en': 'MTN'},
'2774':{'en': 'Cell C'},
'27741':{'en': 'Virgin Mobile'},
'2776':{'en': 'Vodacom'},
'2778':{'en': 'MTN'},
'2779':{'en': 'Vodacom'},
'27810':{'en': 'MTN'},
'27811':{'en': 'Telkom Mobile'},
'27812':{'en': 'Telkom Mobile'},
'27813':{'en': 'Telkom Mobile'},
'27814':{'en': 'Telkom Mobile'},
'27815':{'en': 'Telkom Mobile'},
'27816':{'en': 'WBS Mobile'},
'27817':{'en': 'Telkom Mobile'},
'27818':{'en': 'Vodacom'},
'278190':{'en': 'TelAfrica (Wirles Connect)'},
'278191':{'en': 'TelAfrica (Wirles Connect)'},
'278192':{'en': 'TelAfrica (Wirles Connect)'},
'2782':{'en': 'Vodacom'},
'2783':{'en': 'MTN'},
'2784':{'en': 'Cell C'},
'2787086':{'en': 'Vodacom'},
'2787087':{'en': 'Vodacom'},
'2787158':{'en': 'Vodacom'},
'2787285':{'en': 'Vodacom'},
'2787286':{'en': 'Vodacom'},
'2787287':{'en': 'Vodacom'},
'2787288':{'en': 'Vodacom'},
'2787289':{'en': 'Vodacom'},
'2787310':{'en': 'Vodacom'},
'29051':{'en': 'Sure South Atlantic Ltd'},
'29052':{'en': 'Sure South Atlantic Ltd'},
'29053':{'en': 'Sure South Atlantic Ltd'},
'29054':{'en': 'Sure South Atlantic Ltd'},
'29055':{'en': 'Sure South Atlantic Ltd'},
'29056':{'en': 'Sure South Atlantic Ltd'},
'29057':{'en': 'Sure South Atlantic Ltd'},
'29058':{'en': 'Sure South Atlantic Ltd'},
'29061':{'en': 'Sure South Atlantic Ltd'},
'29062':{'en': 'Sure South Atlantic Ltd'},
'29063':{'en': 'Sure South Atlantic Ltd'},
'29064':{'en': 'Sure South Atlantic Ltd'},
'29065':{'en': 'Sure South Atlantic Ltd'},
'29066':{'en': 'Sure South Atlantic Ltd'},
'29067':{'en': 'Sure South Atlantic Ltd'},
'29068':{'en': 'Sure South Atlantic Ltd'},
'29117':{'en': 'EriTel'},
'2917':{'en': 'EriTel'},
'29729':{'en': 'Digicel'},
'29756':{'en': 'SETAR'},
'29759':{'en': 'SETAR'},
'29760':{'en': 'SETAR'},
'29762':{'en': 'MIO Wireless'},
'29763':{'en': 'MIO Wireless'},
'29764':{'en': 'Digicel'},
'29766':{'en': 'SETAR'},
'297690':{'en': 'SETAR'},
'297699':{'en': 'SETAR'},
'29773':{'en': 'Digicel'},
'29774':{'en': 'Digicel'},
'29777':{'en': 'SETAR'},
'29821':{'en': 'Faroese Telecom'},
'29822':{'en': 'Faroese Telecom'},
'29823':{'en': 'Faroese Telecom'},
'29824':{'en': 'Faroese Telecom'},
'29825':{'en': 'Faroese Telecom'},
'29826':{'en': 'Faroese Telecom'},
'29827':{'en': 'Faroese Telecom'},
'29828':{'en': 'Faroese Telecom'},
'29829':{'en': 'Faroese Telecom'},
'2985':{'en': 'Vodafone'},
'2987':{'en': 'Vodafone'},
'29878':{'en': 'Faroese Telecom'},
'29879':{'en': 'Faroese Telecom'},
'2992':{'en': 'TELE Greenland A/S'},
'2994':{'en': 'TELE Greenland A/S'},
'2995':{'en': 'TELE Greenland A/S'},
'30685185':{'en': 'Cyta'},
'3068519':{'en': 'Cyta'},
'30685500':{'en': 'Cyta'},
'30685501':{'en': 'BWS'},
'30685505':{'en': 'Cyta'},
'30685550':{'en': 'Cyta'},
'30685555':{'en': 'Cyta'},
'30685585':{'en': 'Cyta'},
'30687500':{'en': 'BWS'},
'30688500':{'en': 'BWS'},
'30689900':{'en': 'OTEGlobe'},
'306900':{'en': 'BWS'},
'30690100':{'en': 'MI Carrier Services'},
'30690199':{'en': 'BWS'},
'30690200':{'en': 'MI Carrier Services'},
'30690299':{'en': 'BWS'},
'30690300':{'en': 'MI Carrier Services'},
'30690399':{'en': 'BWS'},
'30690400':{'en': 'MI Carrier Services'},
'30690499':{'en': 'BWS'},
'30690500':{'en': 'MI Carrier Services'},
'30690555':{'en': 'AMD Telecom'},
'30690574':{'en': 'BWS'},
'30690575':{'en': 'BWS'},
'30690588':{'en': 'BWS'},
'30690599':{'en': 'BWS'},
'306906':{'en': 'Wind'},
'306907':{'en': 'Wind'},
'306908':{'en': 'Wind'},
'306909':{'en': 'Wind'},
'30691000':{'en': 'BWS'},
'30691234':{'en': 'M-STAT'},
'30691345':{'en': 'Forthnet'},
'30691400':{'en': 'AMD Telecom'},
'30691600':{'en': 'Compatel'},
'30691700':{'en': 'Inter Telecom'},
'30691888':{'en': 'OSE'},
'30692354':{'en': 'Premium Net International'},
'30692356':{'en': 'SIA NETBALT'},
'30692428':{'en': 'Premium Net International'},
'30693':{'en': 'Wind'},
'30694':{'en': 'Vodafone'},
'306950':{'en': 'Vodafone'},
'306951':{'en': 'Vodafone'},
'30695200':{'en': 'Compatel'},
'3069522':{'en': 'Vodafone'},
'3069523':{'en': 'Vodafone'},
'3069524':{'en': 'BWS'},
'3069529':{'en': 'BWS'},
'3069530':{'en': 'Cyta'},
'30695310':{'en': 'MI Carrier Services'},
'30695328':{'en': 'Premium Net International'},
'30695330':{'en': 'Apifon'},
'30695340':{'en': 'AMD Telecom'},
'30695355':{'en': 'Cyta'},
'30695400':{'en': 'AMD Telecom'},
'30695410':{'en': 'MI Carrier Services'},
'30695456':{'en': 'BWS'},
'30695490':{'en': 'MI Carrier Services'},
'30695499':{'en': 'M-STAT'},
'306955':{'en': 'Vodafone'},
'306956':{'en': 'Vodafone'},
'306957':{'en': 'Vodafone'},
'306958':{'en': 'Vodafone'},
'306959':{'en': 'Vodafone'},
'3069601':{'en': 'OTE'},
'30697':{'en': 'Cosmote'},
'30698':{'en': 'Cosmote'},
'3069900':{'en': 'Wind'},
'30699010':{'en': 'BWS'},
'30699022':{'en': 'Yuboto'},
'30699046':{'en': 'Premium Net International'},
'30699048':{'en': 'AMD Telecom'},
'30699099':{'en': 'BWS'},
'306991':{'en': 'Wind'},
'306992':{'en': 'Wind'},
'306993':{'en': 'Wind'},
'306994':{'en': 'Wind'},
'306995':{'en': 'Wind'},
'306996':{'en': 'Wind'},
'306997':{'en': 'Wind'},
'306998':{'en': 'Wind'},
'306999':{'en': 'Wind'},
'3094':{'en': 'Vodafone'},
'31610':{'en': 'KPN'},
'31611':{'en': 'Vodafone Libertel B.V.'},
'31612':{'en': 'KPN'},
'31613':{'en': 'KPN'},
'31614':{'en': 'T-Mobile'},
'31615':{'en': 'Vodafone Libertel B.V.'},
'31616':{'en': 'Telfort'},
'31617':{'en': 'Telfort'},
'31618':{'en': 'T-Mobile Thuis'},
'31619':{'en': 'KPN'},
'31620':{'en': 'KPN'},
'31621':{'en': 'Vodafone Libertel B.V.'},
'31622':{'en': 'KPN'},
'31623':{'en': 'KPN'},
'31624':{'en': 'T-Mobile'},
'31625':{'en': 'Vodafone Libertel B.V.'},
'31626':{'en': 'Telfort'},
'31627':{'en': 'Vodafone Libertel B.V.'},
'31628':{'en': 'T-Mobile Thuis'},
'31629':{'en': 'Vodafone Libertel B.V.'},
'31630':{'en': 'KPN'},
'31631':{'en': 'Vodafone Libertel B.V.'},
'31633':{'en': 'Telfort'},
'31634':{'en': 'T-Mobile'},
'316351':{'en': 'Glotell B.V (V-Tell NL)'},
'316352':{'en': 'Lancelot'},
'316353':{'en': 'KPN'},
'316356':{'en': 'ASPIDER Solutions Nederland B.V.'},
'316357':{'en': 'ASPIDER Solutions Nederland B.V.'},
'316358':{'en': 'ASPIDER Solutions Nederland B.V.'},
'316359':{'en': 'ASPIDER Solutions Nederland B.V.'},
'31636':{'en': 'Tele2'},
'31637':{'en': 'Teleena (MVNE)'},
'31638':{'en': 'T-Mobile Thuis'},
'31639':{'en': 'T-Mobile Thuis'},
'31640':{'en': 'Tele2'},
'31641':{'en': 'T-Mobile'},
'31642':{'en': 'T-Mobile'},
'31643':{'en': 'T-Mobile'},
'31644':{'en': 'Telfort'},
'31645':{'en': 'Telfort'},
'31646':{'en': 'Vodafone Libertel B.V.'},
'31647':{'en': 'Telfort'},
'31648':{'en': 'T-Mobile Thuis'},
'31649':{'en': 'Telfort'},
'31650':{'en': 'Vodafone Libertel B.V.'},
'31651':{'en': 'KPN'},
'31652':{'en': 'Vodafone Libertel B.V.'},
'31653':{'en': 'KPN'},
'31654':{'en': 'Vodafone Libertel B.V.'},
'31655':{'en': 'Vodafone Libertel B.V.'},
'31656':{'en': 'T-Mobile'},
'31657':{'en': 'KPN'},
'31658':{'en': 'Telfort'},
'316580':{'en': 'Private Mobility Nederland'},
'31659':{'en': 'Vectone Mobile/Delight Mobile'},
'316599':{'en': 'Motto'},
'31680':{'en': 'Vodafone Libertel B.V.'},
'31681':{'en': 'T-Mobile'},
'31682':{'en': 'KPN'},
'31683':{'en': 'KPN'},
'31684':{'en': 'Lycamobile'},
'31685':{'en': 'Lycamobile'},
'31686':{'en': 'Lycamobile'},
'31687':{'en': 'Lycamobile'},
'3245001':{'en': 'Gateway Communications'},
'32455':{'en': 'VOO'},
'32456':{'en': 'Mobile Vikings/JIM Mobile'},
'32460':{'en': 'Proximus'},
'324618':{'en': 'N.M.B.S.'},
'324630':{'en': 'TISMI BV'},
'324651':{'en': 'Lycamobile'},
'324652':{'en': 'Lycamobile'},
'324653':{'en': 'Lycamobile'},
'324654':{'en': 'Lycamobile'},
'324655':{'en': 'Lycamobile'},
'324656':{'en': 'Lycamobile'},
'324657':{'en': 'Lycamobile'},
'324658':{'en': 'Lycamobile'},
'324659':{'en': 'Lycamobile'},
'324660':{'en': 'Lycamobile'},
'324661':{'en': 'Lycamobile'},
'324662':{'en': 'Lycamobile'},
'324663':{'en': 'Lycamobile'},
'324664':{'en': 'Lycamobile'},
'324665':{'en': 'Vectone'},
'324666':{'en': 'Vectone'},
'324667':{'en': 'Vectone'},
'324669':{'en': 'Voxbone SA'},
'324670':{'en': 'Telenet'},
'324671':{'en': 'Join Experience Belgium'},
'324672':{'en': 'Join Experience Belgium'},
'32467306':{'en': 'Telenet'},
'324674':{'en': 'Febo Telecom'},
'324676':{'en': 'Lycamobile'},
'324677':{'en': 'Lycamobile'},
'324678':{'en': 'Lycamobile'},
'324679':{'en': 'Interactive Digital Media GmbH'},
'32468':{'en': 'Telenet'},
'324686':{'en': u('OnOff T\u00e9l\u00e9com SASU')},
'324687':{'en': 'Premium Routing GmbH'},
'324688':{'en': 'Premium Routing GmbH'},
'324689':{'en': 'Febo Telecom'},
'3247':{'en': 'Proximus'},
'324805':{'en': 'Voyacom SPRL'},
'324807':{'en': 'MessageBird BV'},
'324809':{'en': 'Ericsson NV'},
'32483':{'en': 'Telenet'},
'32484':{'en': 'Telenet'},
'32485':{'en': 'Telenet'},
'32486':{'en': 'Telenet'},
'32487':{'en': 'Telenet'},
'32488':{'en': 'Telenet'},
'32489':{'en': 'Telenet'},
'3249':{'en': 'Orange'},
'336000':{'en': 'Free Mobile'},
'336001':{'en': 'Orange France'},
'336002':{'en': 'SFR'},
'336003':{'en': 'Bouygues'},
'3360040':{'en': 'Zeop'},
'3360041':{'en': 'Orange France'},
'3360042':{'en': 'Digicel Antilles Francaises Guyane'},
'3360043':{'en': 'Dauphin Telecom'},
'3360044':{'en': 'OUTREMER TELECOM'},
'3360045':{'en': 'UTS CARAIBES'},
'3360051':{'en': 'Orange France'},
'3360052':{'en': 'SFR'},
'3360053':{'en': 'BJT'},
'3360054':{'en': 'Only (Telco OI)'},
'3360055':{'en': 'Only (Telco OI)'},
'336006':{'en': 'Free Mobile'},
'336007':{'en': 'SFR'},
'336008':{'en': 'Orange France'},
'336009':{'en': 'Bouygues'},
'33601':{'en': 'SFR'},
'33602':{'en': 'SFR'},
'33603':{'en': 'SFR'},
'336040':{'en': 'Afone'},
'336041':{'en': 'Afone'},
'336042':{'en': 'e*Message'},
'336043':{'en': 'e*Message'},
'336044':{'en': 'Afone'},
'336045':{'en': 'SFR'},
'336046':{'en': 'SFR'},
'336047':{'en': 'SFR'},
'336048':{'en': 'SFR'},
'336049':{'en': 'SFR'},
'336050':{'en': 'Euroinformation Telecom'},
'336051':{'en': 'Euroinformation Telecom'},
'336052':{'en': 'Euroinformation Telecom'},
'336053':{'en': 'Euroinformation Telecom'},
'336054':{'en': 'Euroinformation Telecom'},
'336055':{'en': 'Lycamobile'},
'336056':{'en': 'Lycamobile'},
'336057':{'en': 'Lycamobile'},
'336058':{'en': 'Lycamobile'},
'336059':{'en': 'Lycamobile'},
'336060':{'en': 'e*Message'},
'336061':{'en': 'e*Message'},
'336062':{'en': 'e*Message'},
'336063':{'en': 'e*Message'},
'336064':{'en': 'Afone'},
'336065':{'en': 'Euroinformation Telecom'},
'336066':{'en': 'Euroinformation Telecom'},
'336067':{'en': 'Euroinformation Telecom'},
'336068':{'en': 'Euroinformation Telecom'},
'336069':{'en': 'Euroinformation Telecom'},
'33607':{'en': 'Orange France'},
'33608':{'en': 'Orange France'},
'33609':{'en': 'SFR'},
'3361':{'en': 'SFR'},
'3362':{'en': 'SFR'},
'33630':{'en': 'Orange France'},
'33631':{'en': 'Orange France'},
'33632':{'en': 'Orange France'},
'33633':{'en': 'Orange France'},
'33634':{'en': 'SFR'},
'33635':{'en': 'SFR'},
'33636':{'en': 'Euroinformation Telecom'},
'33637':{'en': 'Orange France'},
'33638':{'en': 'Orange France'},
'3363800':{'en': 'Globalstar Europe'},
'3363801':{'en': 'Prixtel'},
'3363802':{'en': 'Prixtel'},
'3363803':{'en': 'Prixtel'},
'3363804':{'en': 'Prixtel'},
'3363805':{'en': 'Prixtel'},
'3363806':{'en': 'IP Directions'},
'3363807':{'en': 'Alphalink'},
'3363808':{'en': 'Alphalink'},
'3363809':{'en': 'Alphalink'},
'33640':{'en': 'Orange France'},
'3364000':{'en': 'Globalstar Europe'},
'3364001':{'en': 'Globalstar Europe'},
'3364002':{'en': 'Globalstar Europe'},
'3364003':{'en': 'Globalstar Europe'},
'3364004':{'en': 'Globalstar Europe'},
'3364005':{'en': 'Coriolis Telecom'},
'3364006':{'en': 'Coriolis Telecom'},
'3364007':{'en': 'Coriolis Telecom'},
'3364008':{'en': 'Coriolis Telecom'},
'3364009':{'en': 'Coriolis Telecom'},
'336410':{'en': 'La poste telecom'},
'336411':{'en': 'La poste telecom'},
'336412':{'en': 'La poste telecom'},
'336413':{'en': 'La poste telecom'},
'336414':{'en': 'La poste telecom'},
'336415':{'en': 'La poste telecom'},
'3364160':{'en': 'Euroinformation Telecom'},
'3364161':{'en': 'Euroinformation Telecom'},
'3364162':{'en': 'Mobiquithings'},
'3364163':{'en': 'SCT'},
'3364164':{'en': 'Legos'},
'3364165':{'en': 'e*Message'},
'3364166':{'en': 'SFR'},
'3364167':{'en': 'SFR'},
'3364168':{'en': 'SFR'},
'3364169':{'en': 'SFR'},
'33642':{'en': 'Orange France'},
'33643':{'en': 'Orange France'},
'336440':{'en': 'La poste telecom'},
'336441':{'en': 'Orange France'},
'336442':{'en': 'Orange France'},
'336443':{'en': 'Orange France'},
'336444':{'en': 'Transatel'},
'336445':{'en': 'Transatel'},
'336446':{'en': 'Transatel'},
'336447':{'en': 'La poste telecom'},
'336448':{'en': 'La poste telecom'},
'336449':{'en': 'La poste telecom'},
'33645':{'en': 'Orange France'},
'33646':{'en': 'SFR'},
'33647':{'en': 'Orange France'},
'33648':{'en': 'Orange France'},
'33649':{'en': 'Orange France'},
'3364950':{'en': 'Keyyo'},
'3364990':{'en': 'Intercall'},
'3364991':{'en': 'Intercall'},
'3364994':{'en': 'e*Message'},
'3364995':{'en': 'Prixtel'},
'3364996':{'en': 'e*Message'},
'3364997':{'en': 'e*Message'},
'3364998':{'en': 'Prixtel'},
'3364999':{'en': 'SFR'},
'33650':{'en': 'Bouygues'},
'33651':{'en': 'Free Mobile'},
'33652':{'en': 'Free Mobile'},
'336530':{'en': 'Bouygues'},
'336531':{'en': 'Bouygues'},
'336532':{'en': 'Bouygues'},
'336533':{'en': 'Bouygues'},
'336534':{'en': 'Bouygues'},
'336535':{'en': 'Free Mobile'},
'336536':{'en': 'Free Mobile'},
'336537':{'en': 'Free Mobile'},
'336538':{'en': 'Free Mobile'},
'336539':{'en': 'Free Mobile'},
'33654':{'en': 'Orange France'},
'33655':{'en': 'SFR'},
'33656':{'en': 'e*Message'},
'3365660':{'en': 'Mobiquithings'},
'3365661':{'en': 'Airbus Defence and Space'},
'3365662':{'en': 'Mobiquithings'},
'3365663':{'en': 'Mobiquithings'},
'3365664':{'en': 'Mobiquithings'},
'3365665':{'en': 'Mobiquithings'},
'3365666':{'en': 'Prixtel'},
'3365667':{'en': 'Prixtel'},
'3365668':{'en': 'Prixtel'},
'3365669':{'en': 'Prixtel'},
'336567':{'en': 'La poste telecom'},
'336568':{'en': 'La poste telecom'},
'33657':{'en': 'e*Message'},
'33658':{'en': 'Bouygues'},
'33659':{'en': 'Bouygues'},
'3366':{'en': 'Bouygues'},
'3367':{'en': 'Orange France'},
'3368':{'en': 'Orange France'},
'33692':{'en': 'Bouygues'},
'33693':{'en': 'Bouygues'},
'33696':{'en': 'Bouygues'},
'33698':{'en': 'Bouygues'},
'33699':{'en': 'Bouygues'},
'33700000':{'en': 'Orange France'},
'33700001':{'en': 'SFR'},
'33700002':{'en': 'Mobiquithings'},
'33700003':{'en': 'Bouygues'},
'33700004':{'en': 'Afone'},
'33700005':{'en': 'Coriolis Telecom'},
'33700006':{'en': 'Mobiquithings'},
'337500':{'en': 'Euroinformation Telecom'},
'337501':{'en': 'SFR'},
'337502':{'en': 'SFR'},
'337503':{'en': 'SFR'},
'337504':{'en': 'SFR'},
'3375050':{'en': 'Euroinformation Telecom'},
'3375051':{'en': 'Euroinformation Telecom'},
'3375052':{'en': 'Euroinformation Telecom'},
'3375053':{'en': 'Euroinformation Telecom'},
'3375057':{'en': 'Euroinformation Telecom'},
'3375058':{'en': 'Euroinformation Telecom'},
'3375059':{'en': 'Sewan communications'},
'337506':{'en': 'Orange France'},
'3375060':{'en': 'Euroinformation Telecom'},
'3375070':{'en': 'Euroinformation Telecom'},
'3375071':{'en': 'Netcom Group'},
'3375072':{'en': 'Netcom Group'},
'3375073':{'en': 'Alphalink'},
'3375074':{'en': 'Alphalink'},
'3375075':{'en': 'Alphalink'},
'3375076':{'en': 'Globalstar Europe'},
'3375077':{'en': 'Globalstar Europe'},
'3375078':{'en': 'China Telecom (France) Limited'},
'3375079':{'en': 'China Telecom (France) Limited'},
'337508':{'en': 'SFR'},
'337509':{'en': 'SFR'},
'33751':{'en': 'Lycamobile'},
'337516':{'en': 'SFR'},
'337517':{'en': 'Completel'},
'337518':{'en': 'Lebara France Limited'},
'337519':{'en': 'Lebara France Limited'},
'3375202':{'en': 'Prixtel'},
'3375203':{'en': 'Prixtel'},
'3375204':{'en': 'Prixtel'},
'3375205':{'en': 'Prixtel'},
'3375206':{'en': 'Prixtel'},
'3375207':{'en': 'Prixtel'},
'3375208':{'en': 'Prixtel'},
'3375209':{'en': 'Prixtel'},
'337521':{'en': 'Lebara France Limited'},
'337522':{'en': 'Lebara France Limited'},
'337523':{'en': 'Lebara France Limited'},
'337524':{'en': 'Lebara France Limited'},
'337525':{'en': 'Lebara France Limited'},
'337526':{'en': 'SFR'},
'337527':{'en': 'Lebara France Limited'},
'337528':{'en': 'Lebara France Limited'},
'337529':{'en': 'Lebara France Limited'},
'33753':{'en': 'Lycamobile'},
'337540':{'en': 'Lebara France Limited'},
'337541':{'en': 'Lebara France Limited'},
'337542':{'en': 'Lebara France Limited'},
'337543':{'en': 'Prixtel'},
'3375430':{'en': 'TDF'},
'3375431':{'en': 'Legos'},
'3375432':{'en': 'Euroinformation Telecom'},
'337544':{'en': 'Lebara France Limited'},
'337545':{'en': 'Lebara France Limited'},
'337546':{'en': 'Mobiquithings'},
'337547':{'en': 'ACN Communications'},
'337548':{'en': 'Completel'},
'337549':{'en': 'Completel'},
'33755':{'en': 'Lebara France Limited'},
'3375550':{'en': 'Legos'},
'3375551':{'en': 'Legos'},
'3375552':{'en': 'Legos'},
'3375553':{'en': 'Legos'},
'3375554':{'en': 'Legos'},
'3375555':{'en': 'Euroinformation Telecom'},
'3375556':{'en': 'Intercall'},
'3375557':{'en': 'Intercall'},
'3375558':{'en': 'Sewan communications'},
'3375559':{'en': 'Sewan communications'},
'3375560':{'en': 'Prixtel'},
'3375561':{'en': 'Prixtel'},
'3375562':{'en': 'Prixtel'},
'3375563':{'en': 'Prixtel'},
'3375564':{'en': 'Prixtel'},
'3375565':{'en': 'Sewan communications'},
'3375566':{'en': 'Euroinformation Telecom'},
'3375567':{'en': 'Euroinformation Telecom'},
'3375568':{'en': 'Euroinformation Telecom'},
'3375569':{'en': 'Axialys'},
'337560':{'en': 'Euroinformation Telecom'},
'337561':{'en': 'Euroinformation Telecom'},
'337562':{'en': 'Euroinformation Telecom'},
'3375630':{'en': 'Euroinformation Telecom'},
'3375631':{'en': 'Euroinformation Telecom'},
'3375632':{'en': 'Euroinformation Telecom'},
'3375633':{'en': 'Euroinformation Telecom'},
'3375634':{'en': 'Euroinformation Telecom'},
'337565':{'en': 'Transatel'},
'337566':{'en': 'Transatel'},
'337567':{'en': 'Transatel'},
'337568':{'en': 'Transatel'},
'337569':{'en': 'Transatel'},
'3375700':{'en': 'Sewan communications'},
'3375701':{'en': 'Mobiweb telecom limited'},
'3375702':{'en': 'Mobiweb telecom limited'},
'3375703':{'en': 'Mobiweb telecom limited'},
'3375704':{'en': 'Mobiweb telecom limited'},
'3375705':{'en': 'Mobiweb telecom limited'},
'3375706':{'en': 'Nordnet'},
'3375707':{'en': 'Keyyo'},
'3375717':{'en': 'Keyyo'},
'337572':{'en': 'Mobiquithings'},
'337573':{'en': 'Mobiquithings'},
'337574':{'en': 'Coriolis Telecom'},
'3375750':{'en': 'Coriolis Telecom'},
'3375751':{'en': 'Coriolis Telecom'},
'3375752':{'en': 'Coriolis Telecom'},
'3375753':{'en': 'Coriolis Telecom'},
'3375754':{'en': 'Coriolis Telecom'},
'3375755':{'en': 'Coriolis Telecom'},
'3375756':{'en': 'Coriolis Telecom'},
'3375757':{'en': 'Euroinformation Telecom'},
'3375758':{'en': 'Euroinformation Telecom'},
'3375763':{'en': 'Euroinformation Telecom'},
'3375767':{'en': 'Euroinformation Telecom'},
'3375777':{'en': 'Euroinformation Telecom'},
'3375779':{'en': 'Halys'},
'3375787':{'en': 'Euroinformation Telecom'},
'3375788':{'en': 'BJT'},
'3375789':{'en': 'BJT'},
'337579':{'en': 'Legos'},
'33758':{'en': 'Lycamobile'},
'33759':{'en': 'Vectone mobile'},
'3376':{'en': 'Bouygues'},
'33766':{'en': 'Free Mobile'},
'33767':{'en': 'Free Mobile'},
'33768':{'en': 'Free Mobile'},
'33769':{'en': 'Free Mobile'},
'337700':{'en': 'Orange France'},
'337701':{'en': 'Orange France'},
'337702':{'en': 'Orange France'},
'337703':{'en': 'SFR'},
'337704':{'en': 'SFR'},
'337705':{'en': 'Euroinformation Telecom'},
'337706':{'en': 'Euroinformation Telecom'},
'337707':{'en': 'Euroinformation Telecom'},
'337708':{'en': 'Euroinformation Telecom'},
'337709':{'en': 'Euroinformation Telecom'},
'337710':{'en': 'Euroinformation Telecom'},
'337711':{'en': 'Euroinformation Telecom'},
'337712':{'en': 'Euroinformation Telecom'},
'337713':{'en': 'SFR'},
'337714':{'en': 'SFR'},
'3377150':{'en': 'SFR'},
'3377151':{'en': 'SFR'},
'3377152':{'en': 'SFR'},
'3377153':{'en': 'SFR'},
'3377154':{'en': 'SFR'},
'3377155':{'en': 'Euroinformation Telecom'},
'3377156':{'en': 'Euroinformation Telecom'},
'3377157':{'en': 'Euroinformation Telecom'},
'3377158':{'en': 'Euroinformation Telecom'},
'3377159':{'en': 'Euroinformation Telecom'},
'337716':{'en': 'Euroinformation Telecom'},
'337717':{'en': 'Euroinformation Telecom'},
'337718':{'en': 'Euroinformation Telecom'},
'3377190':{'en': 'Euroinformation Telecom'},
'3377191':{'en': 'Euroinformation Telecom'},
'3377192':{'en': 'Euroinformation Telecom'},
'3377193':{'en': 'Euroinformation Telecom'},
'3377194':{'en': 'Euroinformation Telecom'},
'33772':{'en': 'Orange France'},
'33773':{'en': 'Syma mobile'},
'33774':{'en': 'Syma mobile'},
'337750':{'en': 'SFR'},
'337751':{'en': 'SFR'},
'337752':{'en': 'SFR'},
'337753':{'en': 'SFR'},
'337754':{'en': 'SFR'},
'337755':{'en': 'Mobiquithings'},
'337756':{'en': 'Mobiquithings'},
'337757':{'en': 'Free Mobile'},
'33776':{'en': 'SFR'},
'33777':{'en': 'SFR'},
'33778':{'en': 'SFR'},
'33779':{'en': 'SFR'},
'3378':{'en': 'Orange France'},
'33780':{'en': 'Afone'},
'337807':{'en': 'Lebara France Limited'},
'337808':{'en': 'Lebara France Limited'},
'337809':{'en': 'Onoff telecom'},
'33781':{'en': 'Free Mobile'},
'33782':{'en': 'Free Mobile'},
'33783':{'en': 'Free Mobile'},
'337846':{'en': 'La poste telecom'},
'337847':{'en': 'La poste telecom'},
'337848':{'en': 'La poste telecom'},
'337849':{'en': 'Euroinformation Telecom'},
'34600':{'en': 'Vodafone'},
'34601':{'en': 'Vodafone'},
'346016':{'en': 'Orange'},
'346018':{'en': 'Orange'},
'346019':{'en': 'Orange'},
'346020':{'en': 'Lycamobile'},
'346021':{'en': 'Lycamobile'},
'3460220':{'en': 'Orange'},
'3460221':{'en': 'Ion mobile'},
'3460222':{'en': 'Vozelia'},
'3460223':{'en': 'Orange'},
'3460224':{'en': 'Oceans'},
'3460225':{'en': 'VozTelecom'},
'3460226':{'en': 'Orange'},
'3460227':{'en': 'Orange'},
'3460228':{'en': 'Orange'},
'3460229':{'en': 'Boutique'},
'346023':{'en': 'Lycamobile'},
'346024':{'en': 'Lebara'},
'346025':{'en': 'Lebara'},
'346026':{'en': 'Lebara'},
'346027':{'en': 'Lebara'},
'346028':{'en': 'Lycamobile'},
'346029':{'en': 'DIA'},
'3460300':{'en': 'Vodafone'},
'3460301':{'en': 'Vodafone'},
'3460302':{'en': 'Vodafone'},
'3460303':{'en': 'Vodafone'},
'3460304':{'en': 'Vodafone'},
'3460305':{'en': 'Lebara'},
'3460306':{'en': 'Lebara'},
'3460307':{'en': 'Lebara'},
'3460308':{'en': 'Lebara'},
'3460309':{'en': 'Lebara'},
'346031':{'en': 'Lebara'},
'346032':{'en': 'Lebara'},
'346033':{'en': 'Lebara'},
'346034':{'en': 'Vodafone'},
'346035':{'en': 'Vodafone'},
'346036':{'en': 'Vodafone'},
'346037':{'en': 'Vodafone'},
'346038':{'en': 'Vodafone'},
'346039':{'en': 'Lebara'},
'34604':{'en': 'Lebara'},
'346040':{'en': 'Orange'},
'346045':{'en': 'Orange'},
'34605':{'en': 'Orange'},
'3460529':{'en': 'MasMovil'},
'34606':{'en': 'Movistar'},
'34607':{'en': 'Vodafone'},
'34608':{'en': 'Movistar'},
'34609':{'en': 'Movistar'},
'34610':{'en': 'Vodafone'},
'34611':{'en': 'Republica Movil'},
'346110':{'en': 'Orange'},
'346112':{'en': 'Lebara'},
'346113':{'en': 'Lebara'},
'34612':{'en': 'Syma'},
'346122':{'en': 'Lycamobile'},
'346124':{'en': 'Lycamobile'},
'346125':{'en': 'Lycamobile'},
'34615':{'en': 'Orange'},
'34616':{'en': 'Movistar'},
'34617':{'en': 'Vodafone'},
'34618':{'en': 'Movistar'},
'34619':{'en': 'Movistar'},
'34620':{'en': 'Movistar'},
'346210':{'en': 'Republica Movil'},
'346211':{'en': 'Republica Movil'},
'346212':{'en': 'Movistar'},
'346213':{'en': 'Republica Movil'},
'346214':{'en': 'Republica Movil'},
'346215':{'en': 'Republica Movil'},
'346216':{'en': 'Republica Movil'},
'34622':{'en': 'Yoigo'},
'346230':{'en': 'Yoigo'},
'346231':{'en': 'Yoigo'},
'346236':{'en': 'Altecom'},
'34625':{'en': 'Orange'},
'3462529':{'en': 'Yoigo'},
'34626':{'en': 'Movistar'},
'34627':{'en': 'Vodafone'},
'34628':{'en': 'Movistar'},
'34629':{'en': 'Movistar'},
'34630':{'en': 'Movistar'},
'34631':{'en': 'Lycamobile'},
'34632':{'en': 'Lycamobile'},
'34633':{'en': 'Yoigo'},
'34634':{'en': 'Vodafone'},
'346340':{'en': 'Lebara'},
'346341':{'en': 'Lebara'},
'346343':{'en': 'Carrier Enabler'},
'346345':{'en': 'Movistar'},
'34635':{'en': 'Orange'},
'3463529':{'en': 'Yoigo'},
'34636':{'en': 'Movistar'},
'34637':{'en': 'Vodafone'},
'34638':{'en': 'Movistar'},
'34639':{'en': 'Movistar'},
'34640':{'en': 'Orange'},
'34641':{'en': 'Movistar'},
'34642':{'en': 'DigiMobil'},
'346430':{'en': 'DigiMobil'},
'346431':{'en': 'DigiMobil'},
'346432':{'en': 'DigiMobil'},
'346433':{'en': 'DigiMobil'},
'346434':{'en': 'DigiMobil'},
'346435':{'en': 'DigiMobil'},
'346436':{'en': 'DigiMobil'},
'346437':{'en': 'DigiMobil'},
'34644':{'en': 'Orange'},
'34645':{'en': 'Orange'},
'3464529':{'en': 'Yoigo'},
'34646':{'en': 'Movistar'},
'34647':{'en': 'Vodafone'},
'34648':{'en': 'Movistar'},
'34649':{'en': 'Movistar'},
'3465':{'en': 'Orange'},
'34650':{'en': 'Movistar'},
'3465229':{'en': 'Yoigo'},
'3465329':{'en': 'DIA'},
'3465429':{'en': 'DIA'},
'3465529':{'en': 'DIA'},
'3465729':{'en': 'DIA'},
'3465829':{'en': 'DIA'},
'34659':{'en': 'Movistar'},
'34660':{'en': 'Movistar'},
'34661':{'en': 'Vodafone'},
'34662':{'en': 'Vodafone'},
'34663':{'en': 'Vodafone'},
'34664':{'en': 'Vodafone'},
'34665':{'en': 'Orange'},
'34666':{'en': 'Vodafone'},
'34667':{'en': 'Vodafone'},
'346681':{'en': 'Truphone'},
'346685':{'en': 'Orange'},
'346686':{'en': 'Parlem'},
'346688':{'en': 'Parlem'},
'34669':{'en': 'Movistar'},
'3467':{'en': 'Vodafone'},
'346725':{'en': 'Lebara'},
'346728':{'en': 'Lebara'},
'346729':{'en': 'Lebara'},
'34675':{'en': 'Orange'},
'34676':{'en': 'Movistar'},
'34679':{'en': 'Movistar'},
'34680':{'en': 'Movistar'},
'346810':{'en': 'Movistar'},
'346811':{'en': 'Movistar'},
'346812':{'en': 'Movistar'},
'346813':{'en': 'Movistar'},
'346814':{'en': 'Movistar'},
'346815':{'en': 'Movistar'},
'346816':{'en': 'Yoigo'},
'34682':{'en': 'Movistar'},
'34683':{'en': 'Movistar'},
'346840':{'en': 'Movistar'},
'346841':{'en': 'Movistar'},
'346842':{'en': 'Movistar'},
'346843':{'en': 'Movistar'},
'3468440':{'en': 'Eurona'},
'3468441':{'en': 'Lemonvil'},
'3468442':{'en': 'BluePhone'},
'3468443':{'en': 'BT'},
'3468444':{'en': 'BT'},
'3468445':{'en': 'Aire Networks'},
'3468447':{'en': 'Quattre'},
'3468448':{'en': 'Nethits'},
'346845':{'en': 'Movistar'},
'346846':{'en': 'Telecable'},
'34685':{'en': 'Orange'},
'3468529':{'en': 'Carrefour'},
'34686':{'en': 'Movistar'},
'34687':{'en': 'Vodafone'},
'346880':{'en': 'YouMobile'},
'346881':{'en': 'YouMobile'},
'346882':{'en': 'Yoigo'},
'346883':{'en': 'Yoigo'},
'346884':{'en': 'Yoigo'},
'346885':{'en': 'YouMobile'},
'346886':{'en': 'Euskaltel'},
'346887':{'en': 'Euskaltel'},
'3468870':{'en': 'OpenMovil'},
'346888':{'en': 'Euskaltel'},
'3468883':{'en': 'Sarenet'},
'346889':{'en': 'PepePhone'},
'34689':{'en': 'Movistar'},
'34690':{'en': 'Movistar'},
'34691':{'en': 'Orange'},
'346919':{'en': 'Yoigo'},
'3469190':{'en': 'MasMovil'},
'3469198':{'en': 'Carrefour'},
'3469199':{'en': 'Carrefour'},
'34692':{'en': 'Orange'},
'3469229':{'en': 'Carrefour'},
'346927':{'en': 'Carrefour'},
'3469300':{'en': 'MasMovil'},
'3469301':{'en': 'Yoigo'},
'3469302':{'en': 'Yoigo'},
'3469303':{'en': 'Yoigo'},
'3469304':{'en': 'Yoigo'},
'3469305':{'en': 'Yoigo'},
'3469306':{'en': 'Yoigo'},
'346931':{'en': 'Orange'},
'3469310':{'en': 'MasMovil'},
'346932':{'en': 'Yoigo'},
'3469320':{'en': 'Carrefour'},
'3469321':{'en': 'Carrefour'},
'3469329':{'en': 'Orange'},
'346933':{'en': 'Carrefour'},
'3469336':{'en': 'Yoigo'},
'3469337':{'en': 'Yoigo'},
'3469340':{'en': 'DIA'},
'3469341':{'en': 'DIA'},
'3469342':{'en': 'DIA'},
'3469343':{'en': 'DIA'},
'3469344':{'en': 'DIA'},
'3469345':{'en': 'Yoigo'},
'3469346':{'en': 'Yoigo'},
'3469347':{'en': 'Yoigo'},
'3469348':{'en': 'Yoigo'},
'3469349':{'en': 'Yoigo'},
'346935':{'en': 'Yoigo'},
'3469360':{'en': 'DIA'},
'3469361':{'en': 'DIA'},
'3469362':{'en': 'DIA'},
'3469363':{'en': 'DIA'},
'3469364':{'en': 'DIA'},
'3469365':{'en': 'Carrefour'},
'3469366':{'en': 'Carrefour'},
'3469367':{'en': 'Yoigo'},
'3469368':{'en': 'Yoigo'},
'3469369':{'en': 'Yoigo'},
'346937':{'en': 'Yoigo'},
'346938':{'en': 'Yoigo'},
'346939':{'en': 'Yoigo'},
'34694':{'en': 'Movistar'},
'346944':{'en': 'Yoigo'},
'346945':{'en': 'Yoigo'},
'346946':{'en': 'Yoigo'},
'34695':{'en': 'Orange'},
'34696':{'en': 'Movistar'},
'34697':{'en': 'Vodafone'},
'34698':{'en': 'Yoigo'},
'346981':{'en': 'R'},
'346989':{'en': 'Vodafone'},
'34699':{'en': 'Movistar'},
'347110':{'en': 'Zinnia'},
'347111':{'en': 'Vodafone'},
'347117':{'en': 'Vodafone'},
'347121':{'en': 'Yoigo'},
'347122':{'en': 'Yoigo'},
'347123':{'en': 'Yoigo'},
'347124':{'en': 'Yoigo'},
'347125':{'en': 'Yoigo'},
'347126':{'en': 'Yoigo'},
'347127':{'en': 'Yoigo'},
'347128':{'en': 'Yoigo'},
'347170':{'en': 'Movistar'},
'347171':{'en': 'Vodafone'},
'347177':{'en': 'Movistar'},
'3471770':{'en': 'PepePhone'},
'3471771':{'en': 'PepePhone'},
'3471777':{'en': 'PepePhone'},
'347221':{'en': 'Yoigo'},
'347222':{'en': 'Yoigo'},
'347223':{'en': 'Yoigo'},
'347224':{'en': 'Yoigo'},
'347225':{'en': 'Yoigo'},
'347226':{'en': 'Yoigo'},
'3472260':{'en': 'MasMovil'},
'3472261':{'en': 'PepePhone'},
'347227':{'en': 'Yoigo'},
'347228':{'en': 'Yoigo'},
'347277':{'en': 'Vodafone'},
'3474442':{'en': 'Deion'},
'3474443':{'en': 'InfoVOIP'},
'3474447':{'en': 'Jetnet'},
'3474448':{'en': 'Aire Networks'},
'3474449':{'en': 'Alai'},
'347446':{'en': 'PTV'},
'347477':{'en': 'Orange'},
'347478':{'en': 'Orange'},
'3505':{'en': 'GibTel'},
'35060':{'en': 'GibTel'},
'35062':{'en': 'Limba'},
'351609':{'en': 'NOS'},
'35163':{'en': 'NOS'},
'35165':{'en': 'NOS'},
'35166':{'en': 'NOS'},
'35191':{'en': 'Vodafone'},
'3519200':{'en': 'Lycamobile'},
'3519201':{'en': 'Lycamobile'},
'3519202':{'en': 'Lycamobile'},
'3519203':{'en': 'Lycamobile'},
'3519204':{'en': 'Lycamobile'},
'3519205':{'en': 'Lycamobile'},
'351921':{'en': 'Vodafone'},
'3519220':{'en': 'Vodafone'},
'3519221':{'en': 'MEO'},
'3519222':{'en': 'MEO'},
'3519230':{'en': 'NOS'},
'3519231':{'en': 'NOS'},
'3519232':{'en': 'NOS'},
'3519233':{'en': 'NOS'},
'3519234':{'en': 'NOS'},
'3519240':{'en': 'MEO'},
'3519241':{'en': 'MEO'},
'3519242':{'en': 'MEO'},
'3519243':{'en': 'MEO'},
'3519244':{'en': 'MEO'},
'351925':{'en': 'MEO'},
'351926':{'en': 'MEO'},
'351927':{'en': 'MEO'},
'3519280':{'en': 'NOWO'},
'3519281':{'en': 'NOWO'},
'3519285':{'en': 'ONITELECOM'},
'3519290':{'en': 'NOS'},
'3519291':{'en': 'NOS'},
'3519292':{'en': 'NOS'},
'3519293':{'en': 'NOS'},
'3519294':{'en': 'NOS'},
'35193':{'en': 'NOS'},
'35196':{'en': 'MEO'},
'35262':{'en': 'POST'},
'352651':{'en': 'POST'},
'352658':{'en': 'POST'},
'35266':{'en': 'Orange'},
'352671':{'en': 'JOIN'},
'352678':{'en': 'JOIN'},
'35269':{'en': 'Tango'},
'35383':{'en': '3'},
'35385':{'en': 'Meteor'},
'35386':{'en': 'O2'},
'35387':{'en': 'Vodafone'},
'35388':{'en': 'eMobile'},
'35389':{'en': 'Tesco Mobile'},
'3538900':{'en': 'Eircom'},
'353892':{'en': 'Liffey Telecom'},
'353894':{'en': 'Liffey Telecom'},
'353895':{'en': '3'},
'3538960':{'en': 'Virgin Media'},
'3538961':{'en': 'Virgin Media'},
'3538962':{'en': 'Virgin Media'},
'3538970':{'en': 'Carphone Warehouse Ireland Mobile Limited'},
'3538971':{'en': 'Carphone Warehouse Ireland Mobile Limited'},
'3538994':{'en': 'Lycamobile'},
'3538995':{'en': 'Lycamobile'},
'3538996':{'en': 'Lycamobile'},
'3538997':{'en': 'Lycamobile'},
'3538998':{'en': 'Lycamobile'},
'354385':{'en': u('S\u00edminn')},
'354388':{'en': 'IMC'},
'354389':{'en': 'IMC'},
'35461':{'en': 'Vodafone'},
'35462':{'en': 'Vodafone'},
'354630':{'en': 'IMC'},
'354632':{'en': 'Tismi'},
'354637':{'en': u('\u00d6ryggisfjarskipti')},
'354638':{'en': u('\u00d6ryggisfjarskipti')},
'354639':{'en': u('\u00d6ryggisfjarskipti')},
'354640':{'en': u('\u00d6ryggisfjarskipti')},
'354641':{'en': u('\u00d6ryggisfjarskipti')},
'354644':{'en': 'Nova'},
'354646':{'en': 'IMC'},
'354647':{'en': 'IMC'},
'354649':{'en': 'Vodafone'},
'354650':{'en': 'IMC'},
'354651':{'en': 'IMC'},
'354655':{'en': 'Vodafone'},
'354659':{'en': 'Vodafone'},
'35466':{'en': 'Vodafone'},
'35467':{'en': 'Vodafone'},
'354680':{'en': 'Vodafone'},
'354686':{'en': 'Vodafone'},
'354687':{'en': 'Vodafone'},
'354688':{'en': 'Vodafone'},
'35469':{'en': 'Vodafone'},
'354750':{'en': u('S\u00edminn')},
'354755':{'en': u('S\u00edminn')},
'354757':{'en': 'Vodafone'},
'35476':{'en': 'Nova'},
'35477':{'en': 'Nova'},
'35478':{'en': 'Nova'},
'35479':{'en': 'Nova'},
'35482':{'en': 'Vodafone'},
'35483':{'en': u('S\u00edminn')},
'35484':{'en': u('S\u00edminn')},
'35485':{'en': u('S\u00edminn')},
'35486':{'en': u('S\u00edminn')},
'354882':{'en': u('S\u00edminn')},
'354888':{'en': u('S\u00edminn')},
'35489':{'en': u('S\u00edminn')},
'35567':{'en': 'ALBtelecom'},
'35568':{'en': 'Telekom'},
'35569':{'en': 'Vodafone'},
'35672':{'en': 'GO Mobile'},
'35677':{'en': 'Melita Mobile'},
'35679':{'en': 'GO Mobile'},
'35692':{'en': 'Vodafone'},
'35696':{'en': 'YOM'},
'356981':{'en': 'Melita Mobile'},
'356988':{'en': 'GO Mobile'},
'356989':{'en': 'Vodafone'},
'35699':{'en': 'Vodafone'},
'35794':{'en': 'Lemontel'},
'35795':{'en': 'PrimeTel'},
'35796':{'en': 'MTN'},
'35797':{'en': 'Cytamobile-Vodafone'},
'35799':{'en': 'Cytamobile-Vodafone'},
'35840':{'en': 'Telia'},
'35841':{'en': 'DNA'},
'35842':{'en': 'Telia'},
'3584320':{'en': 'Cuuma'},
'3584321':{'en': 'Cuuma'},
'3584322':{'en': 'Benemen Oy'},
'3584323':{'en': 'Top Connect OU'},
'3584324':{'en': 'Nord Connect SIA'},
'358436':{'en': 'DNA'},
'358438':{'en': 'DNA'},
'35844':{'en': 'DNA'},
'358450':{'en': 'Telia'},
'358451':{'en': 'Elisa'},
'358452':{'en': 'Elisa'},
'358453':{'en': 'Elisa'},
'3584540':{'en': 'MobiWeb'},
'3584541':{'en': 'AinaCom'},
'3584542':{'en': 'Nokia'},
'3584543':{'en': 'Nokia'},
'3584544':{'en': 'Nokia'},
'3584545':{'en': 'Interactive Digital Media'},
'3584546':{'en': 'NextGen Mobile / CardBoardFish'},
'3584547':{'en': 'SMS Provider Corp'},
'3584548':{'en': 'Voxbone'},
'3584549':{'en': 'Beepsend'},
'3584550':{'en': 'Suomen Virveverkko'},
'3584552':{'en': 'Suomen Virveverkko'},
'3584554':{'en': 'Suomen Virveverkko'},
'3584555':{'en': 'Nokia Solutions and Networks'},
'3584556':{'en': 'Liikennevirasto'},
'3584557':{'en': 'Compatel'},
'3584558':{'en': 'Suomen Virveverkko'},
'3584559':{'en': 'MI'},
'358456':{'en': 'Elisa'},
'3584570':{'en': 'AMT'},
'3584571':{'en': 'Tismi'},
'3584572':{'en': 'Telavox AB'},
'3584573':{'en': 'AMT'},
'3584574':{'en': 'DNA'},
'3584575':{'en': 'AMT'},
'3584576':{'en': 'DNA'},
'3584577':{'en': 'DNA'},
'3584578':{'en': 'DNA'},
'3584579':{'en': 'DNA'},
'358458':{'en': 'Elisa'},
'35846':{'en': 'Elisa'},
'35850':{'en': 'Elisa'},
'35987':{'en': 'Vivacom'},
'35988':{'en': 'A1'},
'35989':{'en': 'Telenor'},
'359988':{'en': 'Bob'},
'359989':{'en': 'A1'},
'359996':{'en': 'Bulsatcom'},
'359999':{'en': 'MAX'},
'3620':{'en': 'Telenor'},
'3630':{'en': 'Magyar Telekom'},
'36312000':{'en': 'Netfone Telecom'},
'36312001':{'en': 'Netfone Telecom'},
'3631310':{'en': 'Vodafone'},
'3631311':{'en': 'Vodafone'},
'3631312':{'en': 'Vodafone'},
'3631313':{'en': 'Vodafone'},
'3631314':{'en': 'Vodafone'},
'3631315':{'en': 'Vodafone'},
'3631316':{'en': 'Vodafone'},
'3631317':{'en': 'Vodafone'},
'3631318':{'en': 'Vodafone'},
'36313190':{'en': 'Vodafone'},
'36313191':{'en': 'Vodafone'},
'36313192':{'en': 'Vodafone'},
'36313193':{'en': 'Vodafone'},
'36313194':{'en': 'Vodafone'},
'36313195':{'en': 'Vodafone'},
'36313196':{'en': 'Vodafone'},
'36313197':{'en': 'Vodafone'},
'36313199':{'en': 'Vodafone'},
'3631320':{'en': 'Vodafone'},
'3631321':{'en': 'Vodafone'},
'3631322':{'en': 'Vodafone'},
'3631323':{'en': 'Vodafone'},
'3631324':{'en': 'Vodafone'},
'3631325':{'en': 'Vodafone'},
'3631326':{'en': 'Vodafone'},
'3631327':{'en': 'Vodafone'},
'3631328':{'en': 'Vodafone'},
'36313290':{'en': 'Vodafone'},
'36313291':{'en': 'Vodafone'},
'36313292':{'en': 'Vodafone'},
'3631330':{'en': 'Vodafone'},
'3631331':{'en': 'Vodafone'},
'3631332':{'en': 'Vodafone'},
'36313330':{'en': 'Vidanet'},
'36313331':{'en': 'Vidanet'},
'36313666':{'en': 'Vodafone'},
'36317000':{'en': 'TARR'},
'36317001':{'en': 'TARR'},
'36317002':{'en': 'TARR'},
'36317003':{'en': 'TARR'},
'36317004':{'en': 'TARR'},
'3631770':{'en': 'UPC'},
'3631771':{'en': 'UPC'},
'363178':{'en': 'UPC'},
'3631790':{'en': 'UPC'},
'36501':{'en': 'DIGI'},
'36502':{'en': 'DIGI'},
'3670':{'en': 'Vodafone'},
'37060':{'en': 'Tele 2'},
'37061':{'en': 'Omnitel'},
'37062':{'en': 'Omnitel'},
'37063':{'en': u('BIT\u00c4')},
'37064':{'en': u('BIT\u00c4')},
'370645':{'en': 'Tele 2'},
'370646':{'en': 'Tele 2'},
'370647':{'en': 'Tele 2'},
'370648':{'en': 'Tele 2'},
'37065':{'en': u('BIT\u00c4')},
'370660':{'en': u('BIT\u00c4')},
'370661':{'en': u('BIT\u00c4')},
'3706610':{'en': 'Tele 2'},
'370662':{'en': 'Omnitel'},
'37066313':{'en': u('BIT\u00c4')},
'37066314':{'en': u('BIT\u00c4')},
'37066315':{'en': u('BIT\u00c4')},
'37066316':{'en': u('BIT\u00c4')},
'37066317':{'en': u('BIT\u00c4')},
'37066318':{'en': u('BIT\u00c4')},
'37066319':{'en': u('BIT\u00c4')},
'37066320':{'en': u('BIT\u00c4')},
'37066323':{'en': u('BIT\u00c4')},
'37066522':{'en': u('BIT\u00c4')},
'3706660':{'en': u('BIT\u00c4')},
'3706661':{'en': u('BIT\u00c4')},
'37066622':{'en': u('BIT\u00c4')},
'37066623':{'en': u('BIT\u00c4')},
'37066624':{'en': u('BIT\u00c4')},
'37066625':{'en': u('BIT\u00c4')},
'37066626':{'en': u('BIT\u00c4')},
'37066627':{'en': u('BIT\u00c4')},
'37066628':{'en': u('BIT\u00c4')},
'37066629':{'en': u('BIT\u00c4')},
'3706665':{'en': u('BIT\u00c4')},
'3706666':{'en': 'Tele 2'},
'3706667':{'en': u('BIT\u00c4')},
'3706668':{'en': u('BIT\u00c4')},
'3706669':{'en': u('BIT\u00c4')},
'3706670':{'en': u('BIT\u00c4')},
'37066711':{'en': u('BIT\u00c4')},
'37066719':{'en': u('BIT\u00c4')},
'37066728':{'en': u('BIT\u00c4')},
'37066729':{'en': u('BIT\u00c4')},
'3706676':{'en': u('BIT\u00c4')},
'3706677':{'en': u('BIT\u00c4')},
'3706678':{'en': u('BIT\u00c4')},
'3706679':{'en': u('BIT\u00c4')},
'3706680':{'en': 'Tele 2'},
'37066839':{'en': 'Tele 2'},
'37066840':{'en': 'Tele 2'},
'37066841':{'en': 'Tele 2'},
'37066842':{'en': 'Tele 2'},
'37066860':{'en': 'Tele 2'},
'37066861':{'en': 'Tele 2'},
'37066862':{'en': 'Tele 2'},
'37066863':{'en': 'Tele 2'},
'37066864':{'en': 'Tele 2'},
'37066865':{'en': 'Tele 2'},
'37066876':{'en': u('BIT\u00c4')},
'37066877':{'en': u('BIT\u00c4')},
'37066900':{'en': u('BIT\u00c4')},
'3706696':{'en': u('BIT\u00c4')},
'3706697':{'en': u('BIT\u00c4')},
'3706698':{'en': u('BIT\u00c4')},
'3706699':{'en': u('BIT\u00c4')},
'37067':{'en': 'Tele 2'},
'370680':{'en': 'Omnitel'},
'370681':{'en': u('BIT\u00c4')},
'370682':{'en': 'Omnitel'},
'370683':{'en': 'Tele 2'},
'370684':{'en': 'Tele 2'},
'370685':{'en': u('BIT\u00c4')},
'370686':{'en': 'Omnitel'},
'370687':{'en': 'Omnitel'},
'370688':{'en': 'Omnitel'},
'370689':{'en': u('BIT\u00c4')},
'370690':{'en': u('BIT\u00c4')},
'370691':{'en': u('BIT\u00c4')},
'370692':{'en': 'Omnitel'},
'370693':{'en': 'Omnitel'},
'370694':{'en': 'Omnitel'},
'370695':{'en': 'Omnitel'},
'370696':{'en': 'Omnitel'},
'37069742':{'en': u('BIT\u00c4')},
'37069743':{'en': u('BIT\u00c4')},
'370698':{'en': 'Omnitel'},
'370699':{'en': u('BIT\u00c4')},
'37250':{'en': 'Telia Eesti AS'},
'372519':{'en': 'Telia Eesti AS'},
'37252':{'en': 'Telia Eesti AS'},
'372530':{'en': 'Telia Eesti AS'},
'372533':{'en': 'Telia Eesti AS'},
'372534':{'en': 'Telia Eesti AS'},
'372536':{'en': 'Telia Eesti AS'},
'372537':{'en': 'Telia Eesti AS'},
'372538':{'en': 'Telia Eesti AS'},
'372539':{'en': 'Telia Eesti AS'},
'37254':{'en': 'Telia Eesti AS'},
'372545':{'en': 'Elisa'},
'3725461':{'en': 'Elisa'},
'3725462':{'en': 'Elisa'},
'3725463':{'en': 'Elisa'},
'37254664':{'en': 'Elisa'},
'37254665':{'en': 'Elisa'},
'37254667':{'en': 'Elisa'},
'37254668':{'en': 'Elisa'},
'37254669':{'en': 'Elisa'},
'37255':{'en': 'Tele 2'},
'37256':{'en': 'Elisa'},
'37257':{'en': 'Telia Eesti AS'},
'37258':{'en': 'Tele 2'},
'372589':{'en': 'Elisa'},
'37259':{'en': 'Telia Eesti AS'},
'37259120':{'en': 'Tele 2'},
'37259121':{'en': 'Tele 2'},
'37259140':{'en': 'Tele 2'},
'372591410':{'en': 'Tele 2'},
'372591411':{'en': 'Tele 2'},
'372591412':{'en': 'Tele 2'},
'372591413':{'en': 'Tele 2'},
'37259144':{'en': 'Tele 2'},
'37281':{'en': 'Telia Eesti AS'},
'3728110':{'en': 'Tele 2'},
'3728111':{'en': 'Elisa'},
'37282':{'en': 'Elisa'},
'3728200':{'en': 'Telia Eesti AS'},
'3728204':{'en': 'Tele 2'},
'37282056':{'en': 'Tele 2'},
'37282057':{'en': 'Tele 2'},
'37282058':{'en': 'Tele 2'},
'37282059':{'en': 'Tele 2'},
'3728206':{'en': 'Tele 2'},
'3728216':{'en': 'Tele 2'},
'3728217':{'en': 'Tele 2'},
'3728218':{'en': 'Tele 2'},
'37282199':{'en': 'Tele 2'},
'3728282':{'en': 'Telia Eesti AS'},
'37283':{'en': 'Tele 2'},
'37284':{'en': 'Tele 2'},
'37284510':{'en': 'Telia Eesti AS'},
'37284511':{'en': 'Telia Eesti AS'},
'37284512':{'en': 'Telia Eesti AS'},
'37356':{'en': 'IDC'},
'37360':{'en': 'Orange'},
'373610':{'en': 'Orange'},
'373611':{'en': 'Orange'},
'373620':{'en': 'Orange'},
'373621':{'en': 'Orange'},
'37367':{'en': 'Moldtelecom'},
'37368':{'en': 'Orange'},
'37369':{'en': 'Orange'},
'37376':{'en': 'Moldcell'},
'373774':{'en': 'IDC'},
'373775':{'en': 'IDC'},
'373777':{'en': 'IDC'},
'373778':{'en': 'IDC'},
'373779':{'en': 'IDC'},
'37378':{'en': 'Moldcell'},
'37379':{'en': 'Moldcell'},
'37433':{'en': 'Beeline', 'ru': u('\u0411\u0438\u043b\u0430\u0439\u043d')},
'37441':{'en': 'Ucom', 'ru': u('\u042e\u043a\u043e\u043c')},
'37443':{'en': 'Beeline', 'ru': u('\u0411\u0438\u043b\u0430\u0439\u043d')},
'37444':{'en': 'Ucom', 'ru': u('\u042e\u043a\u043e\u043c')},
'37449':{'en': 'VivaCell-MTS', 'ru': u('\u0412\u0438\u0432\u0430\u0421\u0435\u043b\u043b-\u041c\u0422\u0421')},
'3745':{'en': 'Ucom', 'ru': u('\u042e\u043a\u043e\u043c')},
'3747':{'en': 'VivaCell-MTS', 'ru': u('\u0412\u0438\u0432\u0430\u0421\u0435\u043b\u043b-\u041c\u0422\u0421')},
'37488':{'en': 'VivaCell-MTS', 'ru': u('\u0412\u0438\u0432\u0430\u0421\u0435\u043b\u043b-\u041c\u0422\u0421')},
'37491':{'en': 'Beeline', 'ru': u('\u0411\u0438\u043b\u0430\u0439\u043d')},
'37493':{'en': 'VivaCell-MTS', 'ru': u('\u0412\u0438\u0432\u0430\u0421\u0435\u043b\u043b-\u041c\u0422\u0421')},
'37494':{'en': 'VivaCell-MTS', 'ru': u('\u0412\u0438\u0432\u0430\u0421\u0435\u043b\u043b-\u041c\u0422\u0421')},
'37495':{'en': 'Ucom', 'ru': u('\u042e\u043a\u043e\u043c')},
'37496':{'en': 'Beeline', 'ru': u('\u0411\u0438\u043b\u0430\u0439\u043d')},
'37498':{'en': 'VivaCell-MTS', 'ru': u('\u0412\u0438\u0432\u0430\u0421\u0435\u043b\u043b-\u041c\u0422\u0421')},
'37499':{'en': 'Beeline', 'ru': u('\u0411\u0438\u043b\u0430\u0439\u043d')},
'37525':{'be': u('\u0411\u0435\u0421\u0422'), 'en': 'life:)', 'ru': 'life:)'},
'375291':{'be': 'Velcom', 'en': 'Velcom', 'ru': 'Velcom'},
'375292':{'be': u('\u041c\u0422\u0421'), 'en': 'MTS', 'ru': u('\u041c\u0422\u0421')},
'375293':{'be': 'Velcom', 'en': 'Velcom', 'ru': 'Velcom'},
'375294':{'be': u('\u0411\u0435\u043b\u0421\u0435\u043b'), 'en': 'Belcel', 'ru': u('\u0411\u0435\u043b\u0421\u0435\u043b')},
'375295':{'be': u('\u041c\u0422\u0421'), 'en': 'MTS', 'ru': u('\u041c\u0422\u0421')},
'375296':{'be': 'Velcom', 'en': 'Velcom', 'ru': 'Velcom'},
'375297':{'be': u('\u041c\u0422\u0421'), 'en': 'MTS', 'ru': u('\u041c\u0422\u0421')},
'375298':{'be': u('\u041c\u0422\u0421'), 'en': 'MTS', 'ru': u('\u041c\u0422\u0421')},
'375299':{'be': 'Velcom', 'en': 'Velcom', 'ru': 'Velcom'},
'37533':{'be': u('\u041c\u0422\u0421'), 'en': 'MTS', 'ru': u('\u041c\u0422\u0421')},
'37544':{'be': 'Velcom', 'en': 'Velcom', 'ru': 'Velcom'},
'3763':{'en': 'Mobiland'},
'3765':{'en': 'Mobiland'},
'3766':{'en': 'Mobiland'},
'3773':{'en': 'Monaco Telecom'},
'3774':{'en': 'Monaco Telecom'},
'3776':{'en': 'Monaco Telecom'},
'37861':{'en': 'TELENET'},
'37866':{'en': 'Telecom Italia San Marino'},
'38050':{'en': 'Vodafone', 'uk': u('Vodafone \u0423\u043a\u0440\u0430\u0457\u043d\u0430')},
'38063':{'en': 'lifecell', 'uk': 'lifecell'},
'38066':{'en': 'Vodafone', 'uk': u('Vodafone \u0423\u043a\u0440\u0430\u0457\u043d\u0430')},
'38067':{'en': 'Kyivstar', 'uk': u('\u041a\u0438\u0457\u0432\u0441\u0442\u0430\u0440')},
'38068':{'en': 'Kyivstar', 'uk': u('\u041a\u0438\u0457\u0432\u0441\u0442\u0430\u0440')},
'38073':{'en': 'lifecell', 'uk': 'lifecell'},
'38091':{'en': 'TriMob', 'uk': u('\u0422\u0440\u0438\u041c\u043e\u0431')},
'38092':{'en': 'PEOPLEnet', 'uk': 'PEOPLEnet'},
'38093':{'en': 'lifecell', 'uk': 'lifecell'},
'38094':{'en': 'Intertelecom', 'uk': u('\u0406\u043d\u0442\u0435\u0440\u0442\u0435\u043b\u0435\u043a\u043e\u043c')},
'38095':{'en': 'Vodafone', 'uk': u('Vodafone \u0423\u043a\u0440\u0430\u0457\u043d\u0430')},
'38096':{'en': 'Kyivstar', 'uk': u('\u041a\u0438\u0457\u0432\u0441\u0442\u0430\u0440')},
'38097':{'en': 'Kyivstar', 'uk': u('\u041a\u0438\u0457\u0432\u0441\u0442\u0430\u0440')},
'38098':{'en': 'Kyivstar', 'uk': u('\u041a\u0438\u0457\u0432\u0441\u0442\u0430\u0440')},
'38099':{'en': 'Vodafone', 'uk': u('Vodafone \u0423\u043a\u0440\u0430\u0457\u043d\u0430')},
'38160':{'en': 'VIP'},
'38161':{'en': 'VIP'},
'38162':{'en': 'Telenor'},
'38163':{'en': 'Telenor'},
'38164':{'en': 'Telekom Srbija a.d.'},
'38165':{'en': 'Telekom Srbija a.d.'},
'38166':{'en': 'Telekom Srbija a.d.'},
'381677':{'en': 'GLOBALTEL'},
'381678':{'en': 'Vectone Mobile'},
'38168':{'en': 'VIP'},
'38169':{'en': 'Telenor'},
'38260':{'en': 'm:tel'},
'38263':{'en': 'Telenor'},
'38266':{'en': 'Telekom'},
'38267':{'en': 'Telekom'},
'38268':{'en': 'm:tel'},
'38269':{'en': 'Telenor'},
'38343':{'en': 'IPKO'},
'38344':{'en': 'vala'},
'383451':{'en': 'vala'},
'383452':{'en': 'vala'},
'383453':{'en': 'vala'},
'383454':{'en': 'vala'},
'383455':{'en': 'Z Mobile'},
'383456':{'en': 'Z Mobile'},
'383457':{'en': 'vala'},
'383458':{'en': 'vala'},
'383459':{'en': 'vala'},
'383461':{'en': 'Z Mobile'},
'3834710':{'en': 'mts d.o.o.'},
'3834711':{'en': 'mts d.o.o.'},
'3834712':{'en': 'mts d.o.o.'},
'3834713':{'en': 'mts d.o.o.'},
'3834714':{'en': 'mts d.o.o.'},
'3834715':{'en': 'mts d.o.o.'},
'38348':{'en': 'IPKO'},
'38349':{'en': 'IPKO'},
'38590':{'en': 'Tele2'},
'38591':{'en': 'A1 Telekom'},
'38592':{'en': 'A1 Telekom'},
'38595':{'en': 'Tele2'},
'385970':{'en': 'Hrvatski Telekom'},
'385975':{'en': 'Telefocus'},
'385976':{'en': 'Hrvatski Telekom'},
'385977':{'en': 'Hrvatski Telekom'},
'385979':{'en': 'Hrvatski Telekom'},
'38598':{'en': 'Hrvatski Telekom'},
'38599':{'en': 'Hrvatski Telekom'},
'38630':{'en': 'A1'},
'38631':{'en': 'Telekom Slovenije'},
'38640':{'en': 'A1'},
'38641':{'en': 'Telekom Slovenije'},
'38643':{'en': 'Telekom Slovenije'},
'38649':{'en': 'Telekom Slovenije'},
'38651':{'en': 'Telekom Slovenije'},
'38664':{'en': 'T-2'},
'386651':{'en': u('S\u017d - Infrastruktura')},
'386655':{'en': 'Telekom Slovenije'},
'386656':{'en': 'Telekom Slovenije'},
'386657':{'en': 'Novatel'},
'38668':{'en': 'A1'},
'38669':{'en': 'A1'},
'3866910':{'en': 'Compatel'},
'38670':{'en': 'Telemach'},
'38671':{'en': 'Telemach'},
'38760':{'en': 'BH Telecom'},
'38761':{'en': 'BH Telecom'},
'38762':{'en': 'BH Telecom'},
'38763':{'en': 'HT ERONET'},
'38764':{'en': 'HT ERONET'},
'38765':{'en': 'm:tel'},
'38766':{'en': 'm:tel'},
'38767':{'en': 'm:tel'},
'38970':{'en': 'T-Mobile'},
'38971':{'en': 'T-Mobile'},
'38972':{'en': 'T-Mobile'},
'389732':{'en': 'Vip'},
'389733':{'en': 'ALO Telecom'},
'389734':{'en': 'Vip'},
'389742':{'en': 'T-Mobile'},
'3897421':{'en': 'Mobik'},
'389746':{'en': 'T-Mobile'},
'389747':{'en': 'T-Mobile'},
'38975':{'en': 'Vip'},
'38976':{'en': 'Vip'},
'38977':{'en': 'Vip'},
'38978':{'en': 'Vip'},
'38979':{'en': 'Lycamobile'},
'39319':{'en': 'Intermatica'},
'3932':{'en': 'WIND'},
'3933':{'en': 'TIM'},
'3934':{'en': 'Vodafone'},
'3936':{'en': 'TIM'},
'39370':{'en': 'TIM'},
'39373':{'en': '3 Italia'},
'39377':{'en': 'Vodafone'},
'3938':{'en': 'WIND'},
'39383':{'en': 'Vodafone'},
'3939':{'en': '3 Italia'},
'407000':{'en': 'Enigma-System'},
'407013':{'en': 'Lycamobile'},
'407014':{'en': 'Lycamobile'},
'407015':{'en': 'Lycamobile'},
'407016':{'en': 'Lycamobile'},
'407017':{'en': 'Lycamobile'},
'407018':{'en': 'Lycamobile'},
'407019':{'en': 'Lycamobile'},
'40702':{'en': 'Lycamobile'},
'40705':{'en': 'Iristel'},
'40711':{'en': 'Telekom'},
'40712':{'en': '2K Telecom'},
'4072':{'en': 'Vodafone'},
'4073':{'en': 'Vodafone'},
'4074':{'en': 'Orange'},
'4075':{'en': 'Orange'},
'4076':{'en': 'Telekom'},
'40770':{'en': 'Digi Mobil'},
'40771':{'en': 'Digi Mobil'},
'40772':{'en': 'Digi Mobil'},
'40773':{'en': 'Digi Mobil'},
'40774':{'en': 'Digi Mobil'},
'40775':{'en': 'Digi Mobil'},
'40776':{'en': 'Digi Mobil'},
'40777':{'en': 'Digi Mobil'},
'4078':{'en': 'Telekom'},
'4079':{'en': 'Vodafone'},
'417500':{'en': 'Swisscom'},
'41754':{'en': 'Swisscom'},
'417550':{'en': 'Swisscom'},
'417551':{'en': 'Swisscom'},
'417552':{'en': 'Swisscom'},
'417553':{'en': 'Swisscom'},
'417600':{'en': 'Sunrise'},
'41762':{'en': 'Sunrise'},
'41763':{'en': 'Sunrise'},
'41764':{'en': 'Sunrise'},
'41765':{'en': 'Sunrise'},
'41766':{'en': 'Sunrise'},
'41767':{'en': 'Sunrise'},
'41768':{'en': 'Sunrise'},
'41769':{'en': 'Sunrise'},
'41770':{'en': 'Swisscom'},
'417710':{'en': 'Swisscom'},
'417712':{'en': 'Swisscom'},
'417713':{'en': 'Swisscom'},
'417715':{'en': 'Swisscom'},
'41772':{'en': 'Sunrise'},
'417730':{'en': 'Sunrise'},
'4177310':{'en': 'Sunrise'},
'4177311':{'en': 'Sunrise'},
'4177312':{'en': 'Sunrise'},
'4177313':{'en': 'Sunrise'},
'4177314':{'en': 'Sunrise'},
'4177315':{'en': 'Sunrise'},
'4177316':{'en': 'Sunrise'},
'4177357':{'en': 'In&Phone'},
'41774':{'en': 'Swisscom'},
'417750':{'en': 'Swisscom'},
'417751':{'en': 'Swisscom'},
'417752':{'en': 'Swisscom'},
'417753':{'en': 'Swisscom'},
'417780':{'en': 'BeeOne Communications'},
'417781':{'en': 'BeeOne Communications'},
'417788':{'en': 'Vectone Mobile Limited (Mundio)'},
'417789':{'en': 'Vectone Mobile Limited (Mundio)'},
'41779':{'en': 'Lycamobile'},
'41780':{'en': 'Salt'},
'41781':{'en': 'Salt'},
'41782':{'en': 'Salt'},
'41783':{'en': 'Salt'},
'417840':{'en': 'UPC Switzerland'},
'417841':{'en': 'UPC Switzerland'},
'417842':{'en': 'UPC Switzerland'},
'4178490':{'en': 'Telecom26 AG'},
'41785':{'en': 'Salt'},
'41786':{'en': 'Salt'},
'41787':{'en': 'Salt'},
'41788':{'en': 'Salt'},
'41789':{'en': 'Salt'},
'41790':{'en': 'Swisscom'},
'41791':{'en': 'Swisscom'},
'41792':{'en': 'Swisscom'},
'41793':{'en': 'Swisscom'},
'41794':{'en': 'Swisscom'},
'41795':{'en': 'Swisscom'},
'41796':{'en': 'Swisscom'},
'41797':{'en': 'Swisscom'},
'41798':{'en': 'Swisscom'},
'417990':{'en': 'Swisscom'},
'417991':{'en': 'Swisscom'},
'417992':{'en': 'Swisscom'},
'417993':{'en': 'Swisscom'},
'417994':{'en': 'Swisscom'},
'417995':{'en': 'Swisscom'},
'417996':{'en': 'Swisscom'},
'4179977':{'en': 'Relario AG (Bebbicell)'},
'4179978':{'en': 'Relario AG (Bebbicell)'},
'4179979':{'en': 'Relario AG (Bebbicell)'},
'417999':{'en': 'Comfone AG'},
'420601':{'en': 'O2'},
'420602':{'en': 'O2'},
'420603':{'en': 'T-Mobile'},
'420604':{'en': 'T-Mobile'},
'420605':{'en': 'T-Mobile'},
'420606':{'en': 'O2'},
'420607':{'en': 'O2'},
'420608':{'en': 'Vodafone'},
'420702':{'en': 'O2'},
'42070300':{'en': 'T-Mobile'},
'4207031':{'en': 'T-Mobile'},
'4207032':{'en': 'T-Mobile'},
'4207033':{'en': 'T-Mobile'},
'4207034':{'en': 'T-Mobile'},
'4207035':{'en': 'T-Mobile'},
'4207036':{'en': 'T-Mobile'},
'42070370':{'en': 'FAYN Telecommunications'},
'42070373':{'en': 'COMA'},
'4207038':{'en': 'T-Mobile'},
'4207039':{'en': 'T-Mobile'},
'4207040':{'en': 'SAZKA sazkova kancelar, a.s'},
'4207041':{'en': 'SAZKA sazkova kancelar, a.s'},
'4207042':{'en': 'SAZKA sazkova kancelar, a.s'},
'4207043':{'en': 'SAZKA sazkova kancelar, a.s'},
'4207044':{'en': 'SAZKA sazkova kancelar, a.s'},
'4207045':{'en': 'SAZKA sazkova kancelar, a.s'},
'4207047':{'en': 'SAZKA sazkova kancelar, a.s'},
'4207050':{'en': 'O2'},
'4207051':{'en': 'O2'},
'4207052':{'en': 'O2'},
'4207053':{'en': 'O2'},
'4207054':{'en': 'O2'},
'42070570':{'en': 'T-Mobile'},
'42072':{'en': 'O2'},
'4207300':{'en': 'T-Mobile'},
'4207301':{'en': 'T-Mobile'},
'4207302':{'en': 'T-Mobile'},
'42073030':{'en': 'T-Mobile'},
'42073033':{'en': 'Axfone'},
'42073035':{'en': 'MATERNA Communications'},
'42073040':{'en': 'Compatel'},
'42073041':{'en': 'SMART Comp'},
'42073042':{'en': 'SMART Comp'},
'42073043':{'en': 'PODA a.s. (SkyNet)'},
'42073044':{'en': 'Vodafone'},
'42073045':{'en': 'Vodafone'},
'42073046':{'en': 'Vodafone'},
'42073047':{'en': 'Vodafone'},
'42073048':{'en': 'Vodafone'},
'4207305':{'en': 'T-Mobile'},
'4207306':{'en': 'T-Mobile'},
'42073070':{'en': 'T-Mobile'},
'42073072':{'en': 'Amcatel'},
'42073073':{'en': 'T-Mobile'},
'42073077':{'en': 'T-Mobile'},
'4207308':{'en': 'T-Mobile'},
'4207309':{'en': 'T-Mobile'},
'420731':{'en': 'T-Mobile'},
'420732':{'en': 'T-Mobile'},
'420733':{'en': 'T-Mobile'},
'420734':{'en': 'T-Mobile'},
'420735':{'en': 'T-Mobile'},
'420736':{'en': 'T-Mobile'},
'420737':{'en': 'T-Mobile'},
'420738':{'en': 'T-Mobile'},
'420739':{'en': 'T-Mobile'},
'4207700':{'en': 'Vodafone'},
'4207701':{'en': 'Vodafone'},
'4207702':{'en': 'Vodafone'},
'4207703':{'en': 'Vodafone'},
'4207704':{'en': 'Vodafone'},
'42077050':{'en': 'Compatel'},
'42077051':{'en': '3ton s.r.o.'},
'42077052':{'en': '3ton s.r.o.'},
'42077055':{'en': 'ASTELNET'},
'4207706':{'en': 'Vodafone'},
'42077071':{'en': 'Cesky bezdrat'},
'42077072':{'en': 'Cesky bezdrat'},
'42077073':{'en': 'T-Mobile'},
'42077077':{'en': 'T-Mobile'},
'42077080':{'en': 'Vodafone'},
'42077081':{'en': 'Vodafone'},
'42077082':{'en': 'Vodafone'},
'42077083':{'en': 'Vodafone'},
'42077084':{'en': 'Vodafone'},
'42077100':{'en': 'TT Quality s.r.o.'},
'42077111':{'en': 'miniTEL'},
'42077177':{'en': 'MONTYHO TECHNOLOGY s.r.o. (CANISTEC)'},
'42077200':{'en': 'TT Quality s.r.o.'},
'42077272':{'en': 'IPEX'},
'42077273':{'en': 'IPEX'},
'42077277':{'en': 'Dragon Internet'},
'420773':{'en': 'Vodafone'},
'420774':{'en': 'Vodafone'},
'420775':{'en': 'Vodafone'},
'420776':{'en': 'Vodafone'},
'420777':{'en': 'Vodafone'},
'4207780':{'en': 'Vodafone'},
'42077811':{'en': 'Vodafone'},
'42077812':{'en': 'Vodafone'},
'42077813':{'en': 'Vodafone'},
'42077814':{'en': 'Vodafone'},
'42077815':{'en': 'Vodafone'},
'42077816':{'en': 'Vodafone'},
'42077817':{'en': 'Vodafone'},
'42077818':{'en': 'Vodafone'},
'42077819':{'en': 'Vodafone'},
'4207782':{'en': 'Vodafone'},
'4207783':{'en': 'Vodafone'},
'4207784':{'en': 'Vodafone'},
'4207785':{'en': 'Vodafone'},
'4207786':{'en': 'Vodafone'},
'4207787':{'en': 'Vodafone'},
'42077880':{'en': 'ha-vel internet'},
'42077881':{'en': 'Vodafone'},
'42077882':{'en': 'Vodafone'},
'42077883':{'en': 'Vodafone'},
'42077884':{'en': 'Vodafone'},
'42077885':{'en': 'Vodafone'},
'42077886':{'en': 'Vodafone'},
'42077887':{'en': 'Vodafone'},
'42077888':{'en': 'Vodafone'},
'42077889':{'en': 'Vodafone'},
'4207789':{'en': 'Vodafone'},
'42077900':{'en': 'TT Quality s.r.o.'},
'42077977':{'en': 'TT Quality s.r.o.'},
'42077990':{'en': 'ha-vel internet'},
'42077997':{'en': 'Plus4U Mobile s.r.o.'},
'42077999':{'en': 'T-Mobile'},
'42079000':{'en': 'Nordic Telecom s.r.o.(Air Telecom - MobilKom)'},
'42079058':{'en': 'T-Mobile'},
'42079083':{'en': 'T-Mobile'},
'4207910':{'en': 'TRAVEL TELEKOMMUNIKATION'},
'42079191':{'en': 'T-Mobile'},
'42079192':{'en': '3ton s.r.o.'},
'42079193':{'en': 'GOPE Systems a.s.'},
'4207920':{'en': 'O2'},
'4207921':{'en': 'O2'},
'4207922':{'en': 'O2'},
'4207923':{'en': 'O2'},
'42079234':{'en': 'Tesco Mobile CR'},
'42079235':{'en': 'Tesco Mobile CR'},
'42079238':{'en': 'Tesco Mobile CR'},
'42079240':{'en': 'Tesco Mobile CR'},
'42079241':{'en': 'Tesco Mobile CR'},
'42079242':{'en': 'Tesco Mobile CR'},
'42079243':{'en': 'Tesco Mobile CR'},
'42079244':{'en': 'Tesco Mobile CR'},
'42079245':{'en': 'O2'},
'42079246':{'en': 'O2'},
'42079247':{'en': 'O2'},
'42079248':{'en': 'O2'},
'42079249':{'en': 'O2'},
'4207925':{'en': 'O2'},
'42079260':{'en': 'SIA Net Balt'},
'4207927':{'en': 'O2'},
'42079390':{'en': 'T-Mobile'},
'4207940':{'en': 'Vectone Distribution Czech Republic s.r.o(Mundio)'},
'4207950':{'en': 'Vectone Distribution Czech Republic s.r.o(Mundio)'},
'42079750':{'en': 'Dial Telecom'},
'4207976':{'en': 'T-Mobile'},
'42079770':{'en': 'T-Mobile'},
'42079771':{'en': 'T-Mobile'},
'42079772':{'en': 'T-Mobile'},
'42079775':{'en': 'T-Mobile'},
'42079777':{'en': 'T-Mobile'},
'42079779':{'en': 'T-Mobile'},
'4207978':{'en': 'T-Mobile'},
'42079797':{'en': 'T-Mobile'},
'42079799':{'en': 'T-Mobile'},
'42079900':{'en': 'MAXPROGRES'},
'42079910':{'en': 'New Telekom'},
'42079911':{'en': 'New Telekom'},
'42079920':{'en': 'METRONET'},
'42079950':{'en': 'TERMS'},
'42079951':{'en': 'TERMS'},
'42079952':{'en': 'TERMS'},
'42079979':{'en': 'miniTEL'},
'42079999':{'en': 'MAXPROGRES'},
'42093':{'en': 'T-Mobile'},
'420962':{'en': 'O2'},
'420963':{'en': 'T-Mobile'},
'420964':{'en': 'T-Mobile'},
'420965':{'en': 'T-Mobile'},
'420966':{'en': 'O2'},
'420967':{'en': 'Vodafone'},
'421901':{'en': 'T-Mobile (Slovak Telekom)'},
'421902':{'en': 'T-Mobile (Slovak Telekom)'},
'421903':{'en': 'T-Mobile (Slovak Telekom)'},
'421904':{'en': 'T-Mobile (Slovak Telekom)'},
'421905':{'en': 'Orange'},
'421906':{'en': 'Orange'},
'421907':{'en': 'Orange'},
'421908':{'en': 'Orange'},
'4219091':{'en': 'T-Mobile (Slovak Telekom)'},
'4219092':{'en': 'T-Mobile (Slovak Telekom)'},
'4219093':{'en': 'T-Mobile (Slovak Telekom)'},
'4219094':{'en': 'T-Mobile (Slovak Telekom)'},
'4219095':{'en': 'T-Mobile (Slovak Telekom)'},
'4219096':{'en': 'T-Mobile (Slovak Telekom)'},
'4219097':{'en': 'T-Mobile (Slovak Telekom)'},
'4219098':{'en': 'T-Mobile (Slovak Telekom)'},
'4219099':{'en': 'T-Mobile (Slovak Telekom)'},
'421910':{'en': 'T-Mobile (Slovak Telekom)'},
'421911':{'en': 'T-Mobile (Slovak Telekom)'},
'421912':{'en': 'T-Mobile (Slovak Telekom)'},
'421914':{'en': 'T-Mobile (Slovak Telekom)'},
'421915':{'en': 'Orange'},
'421916':{'en': 'Orange'},
'421917':{'en': 'Orange'},
'421918':{'en': 'Orange'},
'421919':{'en': 'Orange'},
'421940':{'en': 'Telefonica O2'},
'42194312':{'en': 'Alternet, s.r.o.'},
'42194333':{'en': 'IPfon, s.r.o.'},
'421944':{'en': 'Telefonica O2'},
'421945':{'en': 'Orange'},
'421947':{'en': 'Telefonica O2'},
'421948':{'en': 'Telefonica O2'},
'421949':{'en': 'Telefonica O2'},
'421950':{'en': '4ka of SWAN'},
'421951':{'en': '4ka of SWAN'},
'4219598':{'en': 'Slovak Republic Railways (GSM-R)'},
'42364':{'en': 'Soracom'},
'423650':{'en': 'Telecom Liechtenstein'},
'423651':{'en': 'Cubic'},
'423652':{'en': 'Cubic'},
'423653':{'en': 'Cubic'},
'423660':{'en': 'Telecom Liechtenstein'},
'423661':{'en': 'Dimoco'},
'4236620':{'en': 'Telecom Liechtenstein'},
'4236626':{'en': 'Datamobile'},
'4236627':{'en': 'Datamobile'},
'4236628':{'en': 'Datamobile'},
'4236629':{'en': 'Datamobile'},
'423663':{'en': 'Emnify'},
'42373':{'en': 'Telecom Liechtenstein'},
'42374':{'en': 'First Mobile'},
'42377':{'en': 'Swisscom'},
'42378':{'en': 'Salt'},
'42379':{'en': 'Telecom Liechtenstein'},
'43650':{'en': 'tele.ring'},
'43660':{'en': 'Hutchison Drei Austria'},
'43664':{'en': 'A1 TA'},
'43676':{'en': 'T-Mobile AT'},
'436770':{'en': 'T-Mobile AT'},
'436771':{'en': 'T-Mobile AT'},
'436772':{'en': 'T-Mobile AT'},
'436778':{'en': 'T-Mobile AT'},
'436779':{'en': 'T-Mobile AT'},
'4368181':{'en': 'A1 TA'},
'4368182':{'en': 'A1 TA'},
'4368183':{'en': 'Orange AT'},
'4368184':{'en': 'A1 TA'},
'43688':{'en': 'Orange AT'},
'43699':{'en': 'Orange AT'},
'447106':{'en': 'O2'},
'447107':{'en': 'O2'},
'447300':{'en': 'EE'},
'447301':{'en': 'EE'},
'447302':{'en': 'EE'},
'447303':{'en': 'EE'},
'447304':{'en': 'EE'},
'447305':{'en': 'Virgin Mobile'},
'447306':{'en': 'Virgin Mobile'},
'447340':{'en': 'Vodafone'},
'447341':{'en': 'Vodafone'},
'447342':{'en': 'Vodafone'},
'447365':{'en': 'Three'},
'447366':{'en': 'Three'},
'447367':{'en': 'Three'},
'4473680':{'en': 'Teleena'},
'4473682':{'en': 'Sky'},
'4473683':{'en': 'Sky'},
'4473684':{'en': 'Sky'},
'4473685':{'en': 'Sky'},
'4473686':{'en': 'Sky'},
'4473699':{'en': 'Anywhere Sim'},
'447375':{'en': 'EE'},
'447376':{'en': 'EE'},
'447377':{'en': 'EE'},
'447378':{'en': 'Three'},
'4473780':{'en': 'Limitless'},
'447379':{'en': 'Vodafone'},
'447380':{'en': 'Three'},
'4473800':{'en': 'AMSUK'},
'447381':{'en': 'O2'},
'447382':{'en': 'O2'},
'447383':{'en': 'Three'},
'447384':{'en': 'Vodafone'},
'447385':{'en': 'Vodafone'},
'447386':{'en': 'Vodafone'},
'447387':{'en': 'Vodafone'},
'447388':{'en': 'Vodafone'},
'4473890':{'en': 'Three'},
'4473891':{'en': 'Three'},
'4473892':{'en': 'TalkTalk'},
'4473893':{'en': 'TalkTalk'},
'4473894':{'en': 'TalkTalk'},
'4473895':{'en': 'TalkTalk'},
'4473896':{'en': 'Hanhaa'},
'4473897':{'en': 'Vodafone'},
'4473898':{'en': 'Vodafone'},
'4473900':{'en': 'Home Office'},
'447391':{'en': 'Vodafone'},
'447392':{'en': 'Vodafone'},
'447393':{'en': 'Vodafone'},
'447394':{'en': 'O2'},
'447395':{'en': 'O2'},
'447396':{'en': 'EE'},
'4473970':{'en': 'Three'},
'4473971':{'en': 'Three'},
'4473972':{'en': 'Three'},
'4473973':{'en': 'Three'},
'4473975':{'en': 'Three'},
'4473976':{'en': 'Three'},
'4473977':{'en': 'Three'},
'4473978':{'en': 'Three'},
'4473979':{'en': 'Three'},
'447398':{'en': 'EE'},
'447399':{'en': 'EE'},
'447400':{'en': 'Three'},
'447401':{'en': 'Three'},
'447402':{'en': 'Three'},
'447403':{'en': 'Three'},
'447404':{'en': 'Lycamobile'},
'447405':{'en': 'Lycamobile'},
'4474060':{'en': 'Cheers'},
'4474061':{'en': 'Cheers'},
'4474062':{'en': 'Cheers'},
'4474065':{'en': 'Telecom2'},
'4474066':{'en': '24 Seven'},
'4474067':{'en': 'TGL'},
'4474068':{'en': '08Direct'},
'4474069':{'en': 'CardBoardFish'},
'447407':{'en': 'Vodafone'},
'4474080':{'en': 'Truphone'},
'4474081':{'en': 'Truphone'},
'4474082':{'en': 'Truphone'},
'4474088':{'en': 'Truphone'},
'4474089':{'en': 'Truphone'},
'447409':{'en': 'Orange'},
'447410':{'en': 'Orange'},
'447411':{'en': 'Three'},
'447412':{'en': 'Three'},
'447413':{'en': 'Three'},
'447414':{'en': 'Three'},
'447415':{'en': 'EE'},
'447416':{'en': 'Orange'},
'4474171':{'en': 'CardBoardFish'},
'4474172':{'en': 'Core Telecom'},
'4474173':{'en': 'Lycamobile'},
'4474174':{'en': 'Lycamobile'},
'4474175':{'en': 'Lycamobile'},
'4474178':{'en': 'Truphone'},
'4474179':{'en': 'Core Telecom'},
'4474180':{'en': 'Three'},
'4474181':{'en': 'Bellingham'},
'4474182':{'en': 'TGL'},
'4474183':{'en': 'Tismi'},
'4474184':{'en': 'Manx Telecom'},
'4474185':{'en': 'Telna'},
'4474186':{'en': 'Ace Call'},
'4474187':{'en': 'Teleena'},
'4474189':{'en': 'Teleena'},
'447419':{'en': 'Orange'},
'447420':{'en': 'Orange'},
'447421':{'en': 'Orange'},
'447422':{'en': 'Orange'},
'447423':{'en': 'Vodafone'},
'447424':{'en': 'Lycamobile'},
'447425':{'en': 'Vodafone'},
'447426':{'en': 'Three'},
'447427':{'en': 'Three'},
'447428':{'en': 'Three'},
'447429':{'en': 'Three'},
'447430':{'en': 'O2'},
'447431':{'en': 'O2'},
'447432':{'en': 'EE'},
'447433':{'en': 'EE'},
'447434':{'en': 'EE'},
'447435':{'en': 'Vodafone'},
'447436':{'en': 'Vodafone'},
'447437':{'en': 'Vodafone'},
'447438':{'en': 'Lycamobile'},
'4474390':{'en': 'TalkTalk'},
'4474391':{'en': 'TalkTalk'},
'4474392':{'en': 'TalkTalk'},
'4474393':{'en': 'TalkTalk'},
'447440':{'en': 'Lycamobile'},
'4474408':{'en': 'Telecoms Cloud'},
'4474409':{'en': 'Cloud9'},
'4474410':{'en': 'Mediatel'},
'4474411':{'en': 'Andrews & Arnold'},
'4474413':{'en': 'Stour Marine'},
'4474414':{'en': 'Tismi'},
'4474415':{'en': 'Synectiv'},
'4474416':{'en': 'Vodafone'},
'4474417':{'en': 'Synectiv'},
'4474418':{'en': 'Core Telecom'},
'4474419':{'en': 'Voxbone'},
'447442':{'en': 'Vodafone'},
'447443':{'en': 'Vodafone'},
'447444':{'en': 'Vodafone'},
'447445':{'en': 'Three'},
'447446':{'en': 'Three'},
'447447':{'en': 'Three'},
'447448':{'en': 'Lycamobile'},
'447449':{'en': 'Three'},
'447450':{'en': 'Three'},
'447451':{'en': 'Vectone Mobile'},
'4474512':{'en': 'Tismi'},
'4474515':{'en': 'Premium O'},
'4474516':{'en': 'UK Broadband'},
'4474517':{'en': 'UK Broadband'},
'447452':{'en': 'Manx Telecom'},
'4474527':{'en': 'Three'},
'4474528':{'en': 'Three'},
'4474529':{'en': 'Three'},
'447453':{'en': 'Three'},
'447454':{'en': 'Three'},
'447455':{'en': 'Three'},
'447456':{'en': 'Three'},
'4474570':{'en': 'Vectone Mobile'},
'4474571':{'en': 'Vectone Mobile'},
'4474572':{'en': 'Marathon Telecom'},
'4474573':{'en': 'Vectone Mobile'},
'4474574':{'en': 'Voicetec'},
'4474575':{'en': 'Vectone Mobile'},
'4474576':{'en': 'Sure'},
'4474577':{'en': 'Spacetel'},
'4474578':{'en': 'CardBoardFish'},
'4474579':{'en': 'CardBoardFish'},
'4474580':{'en': 'Gamma Telecom'},
'4474581':{'en': 'Gamma Telecom'},
'4474582':{'en': 'Premium Routing'},
'4474583':{'en': 'Virgin Mobile'},
'4474584':{'en': 'Airwave'},
'4474585':{'en': 'Marathon Telecom'},
'4474586':{'en': 'Three'},
'4474587':{'en': 'Limitless'},
'4474588':{'en': 'Limitless'},
'4474589':{'en': 'Three'},
'447459':{'en': 'Lycamobile'},
'447460':{'en': 'Three'},
'447461':{'en': 'O2'},
'447462':{'en': 'Three'},
'447463':{'en': 'Three'},
'447464':{'en': 'Vodafone'},
'447465':{'en': 'Three'},
'4474650':{'en': 'Vectone Mobile'},
'4474651':{'en': 'Vectone Mobile'},
'4474653':{'en': 'Compatel'},
'4474655':{'en': 'GlobalReach'},
'447466':{'en': 'Lycamobile'},
'447467':{'en': 'Vodafone'},
'447468':{'en': 'Vodafone'},
'447469':{'en': 'Vodafone'},
'44747':{'en': 'Three'},
'447470':{'en': 'Vodafone'},
'447471':{'en': 'Vodafone'},
'447480':{'en': 'Three'},
'447481':{'en': 'Three'},
'447482':{'en': 'Three'},
'447483':{'en': 'EE'},
'447484':{'en': 'EE'},
'447485':{'en': 'EE'},
'447486':{'en': 'EE'},
'447487':{'en': 'EE'},
'4474880':{'en': 'Fogg'},
'4474881':{'en': 'CESG'},
'4474882':{'en': 'Sky'},
'4474883':{'en': 'Sky'},
'4474884':{'en': 'Three'},
'4474885':{'en': 'Three'},
'4474886':{'en': 'Lanonyx'},
'4474887':{'en': 'Three'},
'4474888':{'en': 'Ziron'},
'4474889':{'en': 'Three'},
'447489':{'en': 'O2'},
'447490':{'en': 'Three'},
'447491':{'en': 'Three'},
'447492':{'en': 'Three'},
'447493':{'en': 'Vodafone'},
'447494':{'en': 'EE'},
'447495':{'en': 'EE'},
'447496':{'en': 'EE'},
'447497':{'en': 'EE'},
'447498':{'en': 'EE'},
'447499':{'en': 'O2'},
'447500':{'en': 'Vodafone'},
'447501':{'en': 'Vodafone'},
'447502':{'en': 'Vodafone'},
'447503':{'en': 'Vodafone'},
'447504':{'en': 'EE'},
'447505':{'en': 'EE'},
'447506':{'en': 'EE'},
'447507':{'en': 'EE'},
'447508':{'en': 'EE'},
'4475090':{'en': 'JT'},
'4475091':{'en': 'JT'},
'4475092':{'en': 'JT'},
'4475093':{'en': 'JT'},
'4475094':{'en': 'JT'},
'4475095':{'en': 'JT'},
'4475096':{'en': 'JT'},
'4475097':{'en': 'JT'},
'44751':{'en': 'O2'},
'4475200':{'en': 'Simwood'},
'4475201':{'en': 'BT OnePhone'},
'4475202':{'en': 'Vectone Mobile'},
'4475204':{'en': 'Core Communication'},
'4475205':{'en': 'Esendex'},
'4475206':{'en': 'Tismi'},
'4475207':{'en': 'aql'},
'447521':{'en': 'O2'},
'447522':{'en': 'O2'},
'447523':{'en': 'O2'},
'447525':{'en': 'O2'},
'447526':{'en': 'O2'},
'447527':{'en': 'Orange'},
'447528':{'en': 'Orange'},
'447529':{'en': 'Orange'},
'447530':{'en': 'Orange'},
'447531':{'en': 'Orange'},
'4475320':{'en': 'Orange'},
'4475321':{'en': 'Orange'},
'4475322':{'en': 'Orange'},
'4475323':{'en': 'Orange'},
'4475324':{'en': 'Orange'},
'4475325':{'en': 'SMSRelay AG'},
'4475326':{'en': 'Three'},
'4475327':{'en': 'Three'},
'4475328':{'en': 'Three'},
'4475329':{'en': 'Mobiweb'},
'447533':{'en': 'Three'},
'447534':{'en': 'EE'},
'447535':{'en': 'EE'},
'447536':{'en': 'Orange'},
'4475370':{'en': 'Wavecrest'},
'4475371':{'en': 'Stour Marine'},
'4475373':{'en': 'Swiftnet'},
'4475374':{'en': 'Vodafone'},
'4475376':{'en': 'Mediatel'},
'4475377':{'en': 'CFL'},
'4475378':{'en': 'Three'},
'4475379':{'en': 'Three'},
'447538':{'en': 'EE'},
'447539':{'en': 'EE'},
'44754':{'en': 'O2'},
'447550':{'en': 'EE'},
'447551':{'en': 'Vodafone'},
'447552':{'en': 'Vodafone'},
'447553':{'en': 'Vodafone'},
'447554':{'en': 'Vodafone'},
'447555':{'en': 'Vodafone'},
'447556':{'en': 'Orange'},
'447557':{'en': 'Vodafone'},
'4475580':{'en': 'Mobile FX Services Ltd'},
'4475588':{'en': 'Cloud9'},
'4475590':{'en': 'Mars'},
'4475591':{'en': 'LegendTel'},
'4475592':{'en': 'IPV6'},
'4475593':{'en': 'Globecom'},
'4475594':{'en': 'Truphone'},
'4475595':{'en': 'Confabulate'},
'4475596':{'en': 'Lleida.net'},
'4475597':{'en': 'Core Telecom'},
'4475598':{'en': 'Nodemax'},
'4475599':{'en': 'Resilient'},
'44756':{'en': 'O2'},
'447570':{'en': 'Vodafone'},
'4475710':{'en': '09 Mobile'},
'4475718':{'en': 'Alliance'},
'447572':{'en': 'EE'},
'447573':{'en': 'EE'},
'447574':{'en': 'EE'},
'447575':{'en': 'Three'},
'447576':{'en': 'Three'},
'447577':{'en': 'Three'},
'447578':{'en': 'Three'},
'447579':{'en': 'Orange'},
'447580':{'en': 'Orange'},
'447581':{'en': 'Orange'},
'447582':{'en': 'Orange'},
'447583':{'en': 'Orange'},
'447584':{'en': 'Vodafone'},
'447585':{'en': 'Vodafone'},
'447586':{'en': 'Vodafone'},
'447587':{'en': 'Vodafone'},
'447588':{'en': 'Three'},
'4475890':{'en': 'Yim Siam'},
'4475891':{'en': 'Oxygen8'},
'4475892':{'en': 'Oxygen8'},
'4475893':{'en': 'Oxygen8'},
'4475894':{'en': 'Vectone Mobile'},
'4475895':{'en': 'Vectone Mobile'},
'4475896':{'en': 'Vectone Mobile'},
'4475897':{'en': 'Vectone Mobile'},
'4475898':{'en': 'Test2date'},
'44759':{'en': 'O2'},
'4476000':{'en': 'Mediatel'},
'4476002':{'en': 'PageOne'},
'4476006':{'en': '24 Seven'},
'4476007':{'en': 'Relax'},
'4476020':{'en': 'O2'},
'4476022':{'en': 'Relax'},
'447623':{'en': 'PageOne'},
'447624':{'en': 'Manx Telecom'},
'4476242':{'en': 'Sure'},
'44762450':{'en': 'BlueWave Communications'},
'44762456':{'en': 'Sure'},
'447625':{'en': 'O2'},
'447626':{'en': 'O2'},
'4476400':{'en': 'Core Telecom'},
'4476401':{'en': 'Telecom2'},
'4476402':{'en': 'FIO Telecom'},
'4476403':{'en': 'PageOne'},
'4476404':{'en': 'PageOne'},
'4476406':{'en': 'PageOne'},
'4476407':{'en': 'PageOne'},
'4476411':{'en': 'Orange'},
'4476433':{'en': 'Yim Siam'},
'4476440':{'en': 'O2'},
'4476441':{'en': 'O2'},
'4476446':{'en': 'Media'},
'4476542':{'en': 'PageOne'},
'4476543':{'en': 'PageOne'},
'4476545':{'en': 'PageOne'},
'4476546':{'en': 'PageOne'},
'4476591':{'en': 'Vodafone'},
'4476592':{'en': 'PageOne'},
'4476593':{'en': 'Vodafone'},
'4476594':{'en': 'Vodafone'},
'4476595':{'en': 'Vodafone'},
'4476596':{'en': 'Vodafone'},
'4476598':{'en': 'Vodafone'},
'4476599':{'en': 'PageOne'},
'4476600':{'en': 'Plus'},
'4476601':{'en': 'PageOne'},
'4476602':{'en': 'PageOne'},
'4476603':{'en': 'PageOne'},
'4476604':{'en': 'PageOne'},
'4476605':{'en': 'PageOne'},
'4476606':{'en': '24 Seven'},
'4476607':{'en': 'Premium O'},
'4476608':{'en': 'Premium O'},
'4476609':{'en': 'Premium O'},
'447661':{'en': 'PageOne'},
'4476620':{'en': 'Premium O'},
'4476633':{'en': 'Syntec'},
'4476636':{'en': 'Relax'},
'4476637':{'en': 'Vodafone'},
'447666':{'en': 'Vodafone'},
'4476660':{'en': '24 Seven'},
'4476669':{'en': 'FIO Telecom'},
'4476690':{'en': 'O2'},
'4476691':{'en': 'O2'},
'4476692':{'en': 'O2'},
'4476693':{'en': 'Confabulate'},
'4476696':{'en': 'Cheers'},
'4476698':{'en': 'O2'},
'4476699':{'en': 'O2'},
'4476770':{'en': '24 Seven'},
'4476772':{'en': 'Relax'},
'4476776':{'en': 'Telsis'},
'4476778':{'en': 'Core Telecom'},
'4476810':{'en': 'PageOne'},
'4476814':{'en': 'PageOne'},
'4476818':{'en': 'PageOne'},
'447693':{'en': 'O2'},
'447699':{'en': 'Vodafone'},
'44770':{'en': 'O2'},
'4477000':{'en': 'Cloud9'},
'4477001':{'en': 'Nationwide Telephone'},
'4477003':{'en': 'Sure'},
'4477007':{'en': 'Sure'},
'4477008':{'en': 'Sure'},
'44771':{'en': 'O2'},
'447717':{'en': 'Vodafone'},
'447720':{'en': 'O2'},
'447721':{'en': 'Vodafone'},
'447722':{'en': 'EE'},
'447723':{'en': 'Three'},
'447724':{'en': 'O2'},
'447725':{'en': 'O2'},
'447726':{'en': 'EE'},
'447727':{'en': 'Three'},
'447728':{'en': 'Three'},
'447729':{'en': 'O2'},
'44773':{'en': 'O2'},
'447733':{'en': 'Vodafone'},
'447735':{'en': 'Three'},
'447737':{'en': 'Three'},
'447740':{'en': 'O2'},
'447741':{'en': 'Vodafone'},
'447742':{'en': 'O2'},
'447743':{'en': 'O2'},
'4477442':{'en': 'Core Communication'},
'4477443':{'en': 'Core Communication'},
'4477444':{'en': 'Core Communication'},
'4477445':{'en': 'Core Communication'},
'4477446':{'en': 'Core Communication'},
'4477447':{'en': 'Core Communication'},
'4477448':{'en': 'Core Communication'},
'4477449':{'en': 'Core Communication'},
'447745':{'en': 'O2'},
'447746':{'en': 'O2'},
'447747':{'en': 'Vodafone'},
'447748':{'en': 'Vodafone'},
'447749':{'en': 'O2'},
'447750':{'en': 'O2'},
'447751':{'en': 'O2'},
'447752':{'en': 'O2'},
'447753':{'en': 'O2'},
'4477530':{'en': 'Airwave'},
'447754':{'en': 'O2'},
'4477552':{'en': 'Core Communication'},
'4477553':{'en': 'Core Communication'},
'4477554':{'en': 'Core Communication'},
'4477555':{'en': 'Core Communication'},
'447756':{'en': 'O2'},
'447757':{'en': 'EE'},
'447758':{'en': 'EE'},
'447759':{'en': 'O2'},
'44776':{'en': 'Vodafone'},
'447761':{'en': 'O2'},
'447762':{'en': 'O2'},
'447763':{'en': 'O2'},
'447764':{'en': 'O2'},
'44777':{'en': 'Vodafone'},
'447772':{'en': 'Orange'},
'447773':{'en': 'Orange'},
'447777':{'en': 'EE'},
'447779':{'en': 'Orange'},
'44778':{'en': 'Vodafone'},
'447781':{'en': 'Sure'},
'447782':{'en': 'Three'},
'447783':{'en': 'O2'},
'447784':{'en': 'O2'},
'447790':{'en': 'Orange'},
'447791':{'en': 'Orange'},
'447792':{'en': 'Orange'},
'447793':{'en': 'O2'},
'447794':{'en': 'Orange'},
'447795':{'en': 'Vodafone'},
'447796':{'en': 'Vodafone'},
'447797':{'en': 'JT'},
'447798':{'en': 'Vodafone'},
'447799':{'en': 'Vodafone'},
'447800':{'en': 'Orange'},
'447801':{'en': 'O2'},
'447802':{'en': 'O2'},
'447803':{'en': 'O2'},
'447804':{'en': 'EE'},
'447805':{'en': 'Orange'},
'447806':{'en': 'EE'},
'447807':{'en': 'Orange'},
'447808':{'en': 'O2'},
'447809':{'en': 'O2'},
'44781':{'en': 'Orange'},
'447810':{'en': 'Vodafone'},
'447818':{'en': 'Vodafone'},
'447819':{'en': 'O2'},
'447820':{'en': 'O2'},
'447821':{'en': 'O2'},
'4478220':{'en': 'FleXtel'},
'4478221':{'en': 'Swiftnet'},
'4478222':{'en': 'TalkTalk'},
'4478224':{'en': 'aql'},
'4478225':{'en': 'Icron Network'},
'4478226':{'en': 'aql'},
'4478227':{'en': 'Cheers'},
'4478228':{'en': 'Vodafone'},
'4478229':{'en': 'Oxygen8'},
'447823':{'en': 'Vodafone'},
'447824':{'en': 'Vodafone'},
'447825':{'en': 'Vodafone'},
'447826':{'en': 'Vodafone'},
'447827':{'en': 'Vodafone'},
'447828':{'en': 'Three'},
'4478297':{'en': 'Airtel'},
'4478298':{'en': 'Airtel'},
'4478299':{'en': 'Airtel'},
'447830':{'en': 'Three'},
'447831':{'en': 'Vodafone'},
'447832':{'en': 'Three'},
'447833':{'en': 'Vodafone'},
'447834':{'en': 'O2'},
'447835':{'en': 'O2'},
'447836':{'en': 'Vodafone'},
'447837':{'en': 'Orange'},
'447838':{'en': 'Three'},
'4478391':{'en': 'Airtel'},
'4478392':{'en': 'Airtel'},
'4478397':{'en': 'Airtel'},
'4478398':{'en': 'Sure'},
'44784':{'en': 'O2'},
'447846':{'en': 'Three'},
'447847':{'en': 'EE'},
'447848':{'en': 'Three'},
'447850':{'en': 'O2'},
'447851':{'en': 'O2'},
'447852':{'en': 'EE'},
'447853':{'en': 'Three'},
'447854':{'en': 'Orange'},
'447855':{'en': 'Orange'},
'447856':{'en': 'O2'},
'447857':{'en': 'O2'},
'447858':{'en': 'O2'},
'447859':{'en': 'Three'},
'447860':{'en': 'O2'},
'447861':{'en': 'Three'},
'447862':{'en': 'Three'},
'447863':{'en': 'Three'},
'4478640':{'en': 'O2'},
'4478641':{'en': 'O2'},
'4478642':{'en': 'O2'},
'4478643':{'en': 'O2'},
'4478645':{'en': 'O2'},
'4478646':{'en': 'O2'},
'4478647':{'en': 'O2'},
'4478648':{'en': 'O2'},
'4478649':{'en': 'O2'},
'447865':{'en': 'Three'},
'447866':{'en': 'Orange'},
'447867':{'en': 'Vodafone'},
'447868':{'en': 'Three'},
'447869':{'en': 'Three'},
'447870':{'en': 'Orange'},
'447871':{'en': 'O2'},
'447872':{'en': 'O2'},
'4478722':{'en': 'Cloud9'},
'4478727':{'en': 'Telecom 10'},
'447873':{'en': 'O2'},
'4478730':{'en': 'Telesign'},
'4478740':{'en': 'O2'},
'4478741':{'en': 'O2'},
'4478742':{'en': 'O2'},
'4478743':{'en': 'O2'},
'4478744':{'en': 'Citrus'},
'4478746':{'en': 'O2'},
'4478747':{'en': 'O2'},
'4478748':{'en': 'O2'},
'4478749':{'en': 'O2'},
'447875':{'en': 'Orange'},
'447876':{'en': 'Vodafone'},
'447877':{'en': 'Three'},
'447878':{'en': 'Three'},
'447879':{'en': 'Vodafone'},
'447880':{'en': 'Vodafone'},
'447881':{'en': 'Vodafone'},
'447882':{'en': 'Three'},
'447883':{'en': 'Three'},
'447884':{'en': 'Vodafone'},
'447885':{'en': 'O2'},
'447886':{'en': 'Three'},
'447887':{'en': 'Vodafone'},
'447888':{'en': 'Three'},
'447889':{'en': 'O2'},
'447890':{'en': 'Orange'},
'447891':{'en': 'Orange'},
'4478920':{'en': 'HSL'},
'4478921':{'en': 'Vectone Mobile'},
'4478923':{'en': 'O2'},
'4478924':{'en': 'O2'},
'4478925':{'en': 'FleXtel'},
'4478926':{'en': 'O2'},
'4478927':{'en': 'O2'},
'4478928':{'en': 'O2'},
'4478929':{'en': 'O2'},
'4478930':{'en': 'Magrathea'},
'4478931':{'en': '24 Seven'},
'4478932':{'en': 'O2'},
'4478933':{'en': 'Yim Siam'},
'4478934':{'en': 'O2'},
'4478935':{'en': 'O2'},
'4478936':{'en': 'O2'},
'4478937':{'en': 'O2'},
'4478938':{'en': 'aql'},
'4478939':{'en': 'Citrus'},
'447894':{'en': 'O2'},
'447895':{'en': 'O2'},
'447896':{'en': 'Orange'},
'447897':{'en': 'Three'},
'447898':{'en': 'Three'},
'447899':{'en': 'Vodafone'},
'447900':{'en': 'Vodafone'},
'447901':{'en': 'Vodafone'},
'447902':{'en': 'O2'},
'447903':{'en': 'EE'},
'447904':{'en': 'EE'},
'447905':{'en': 'EE'},
'447906':{'en': 'EE'},
'447907':{'en': 'O2'},
'447908':{'en': 'EE'},
'447909':{'en': 'Vodafone'},
'447910':{'en': 'EE'},
'4479110':{'en': 'Marathon Telecom'},
'4479111':{'en': 'JT'},
'4479112':{'en': '24 Seven'},
'4479117':{'en': 'JT'},
'4479118':{'en': '24 Seven'},
'447912':{'en': 'O2'},
'447913':{'en': 'EE'},
'447914':{'en': 'EE'},
'447915':{'en': 'Three'},
'447916':{'en': 'Three'},
'447917':{'en': 'Vodafone'},
'447918':{'en': 'Vodafone'},
'447919':{'en': 'Vodafone'},
'44792':{'en': 'O2'},
'447920':{'en': 'Vodafone'},
'447924':{'en': 'Manx Telecom'},
'4479245':{'en': 'Cloud9'},
'447929':{'en': 'Orange'},
'447930':{'en': 'EE'},
'447931':{'en': 'EE'},
'447932':{'en': 'EE'},
'447933':{'en': 'O2'},
'447934':{'en': 'O2'},
'447935':{'en': 'O2'},
'447936':{'en': 'O2'},
'447937':{'en': 'JT'},
'447938':{'en': 'O2'},
'447939':{'en': 'EE'},
'44794':{'en': 'EE'},
'44795':{'en': 'EE'},
'447955':{'en': 'O2'},
'44796':{'en': 'Orange'},
'447960':{'en': 'EE'},
'447961':{'en': 'EE'},
'447962':{'en': 'EE'},
'447963':{'en': 'EE'},
'447970':{'en': 'Orange'},
'447971':{'en': 'Orange'},
'447972':{'en': 'Orange'},
'447973':{'en': 'Orange'},
'447974':{'en': 'Orange'},
'447975':{'en': 'Orange'},
'447976':{'en': 'Orange'},
'447977':{'en': 'Orange'},
'4479781':{'en': 'QX Telecom'},
'4479782':{'en': 'Cloud9'},
'4479783':{'en': 'Cloud9'},
'4479784':{'en': 'Cheers'},
'4479785':{'en': 'Icron Network'},
'4479786':{'en': 'Oxygen8'},
'4479787':{'en': 'TeleWare'},
'4479788':{'en': 'Truphone'},
'4479789':{'en': 'IV Response'},
'447979':{'en': 'Vodafone'},
'44798':{'en': 'EE'},
'447980':{'en': 'Orange'},
'447988':{'en': 'Three'},
'447989':{'en': 'Orange'},
'447990':{'en': 'Vodafone'},
'447999':{'en': 'O2'},
'45201':{'en': 'tdc'},
'45202':{'en': 'tdc'},
'45203':{'en': 'tdc'},
'45204':{'en': 'tdc'},
'45205':{'en': 'tdc'},
'45206':{'en': 'telenor'},
'45207':{'en': 'telenor'},
'45208':{'en': 'telenor'},
'45209':{'en': 'telenor'},
'45211':{'en': 'tdc'},
'45212':{'en': 'tdc'},
'45213':{'en': 'tdc'},
'45214':{'en': 'tdc'},
'45215':{'en': 'tdc'},
'45216':{'en': 'tdc'},
'45217':{'en': 'tdc'},
'45218':{'en': 'tdc'},
'45219':{'en': 'tdc'},
'45221':{'en': 'telenor'},
'45222':{'en': 'telenor'},
'45223':{'en': 'telenor'},
'45224':{'en': 'telenor'},
'45225':{'en': 'telenor'},
'45226':{'en': 'telenor'},
'45227':{'en': 'telenor'},
'45228':{'en': 'telenor'},
'45229':{'en': 'telenor'},
'45231':{'en': 'tdc'},
'45232':{'en': 'tdc'},
'45233':{'en': 'tdc'},
'45234':{'en': 'tdc'},
'45235':{'en': 'tdc'},
'45236':{'en': 'tdc'},
'45237':{'en': 'tdc'},
'45238':{'en': 'tdc'},
'45239':{'en': 'tdc'},
'452395':{'en': 'telia'},
'45241':{'en': 'tdc'},
'45242':{'en': 'tdc'},
'45243':{'en': 'tdc'},
'45244':{'en': 'tdc'},
'45245':{'en': 'tdc'},
'45246':{'en': 'tdc'},
'45247':{'en': 'tdc'},
'45248':{'en': 'tdc'},
'45249':{'en': 'tdc'},
'45251':{'en': 'telenor'},
'45252':{'en': 'telenor'},
'45253':{'en': 'telenor'},
'45254':{'en': 'telenor'},
'45255':{'en': 'telenor'},
'45256':{'en': 'telenor'},
'45257':{'en': 'telenor'},
'45258':{'en': 'telenor'},
'452590':{'en': 'mi carrier services'},
'452591':{'en': 'link mobile'},
'452592':{'en': 'link mobile'},
'452593':{'en': 'compatel limited'},
'452594':{'en': 'firmafon'},
'452595':{'en': 'link mobile'},
'452596':{'en': 'viptel'},
'452597':{'en': '3'},
'4525980':{'en': 'uni-tel'},
'4525981':{'en': 'mobiweb limited'},
'4525982':{'en': 'jay.net'},
'4525983':{'en': '42 telecom ab'},
'4525984':{'en': 'link mobile'},
'4525985':{'en': '42 telecom ab'},
'4525986':{'en': '42 telecom ab'},
'4525987':{'en': 'netfors unified messaging'},
'4525988':{'en': 'link mobile'},
'4525989':{'en': 'ipnordic'},
'452599':{'en': 'telenor'},
'4526':{'en': 'telia'},
'4527':{'en': 'telia'},
'4528':{'en': 'telia'},
'45291':{'en': 'tdc'},
'45292':{'en': 'tdc'},
'45293':{'en': 'tdc'},
'45294':{'en': 'tdc'},
'45295':{'en': 'tdc'},
'45296':{'en': 'tdc'},
'45297':{'en': 'tdc'},
'45298':{'en': 'tdc'},
'45299':{'en': 'tdc'},
'45301':{'en': 'tdc'},
'45302':{'en': 'tdc'},
'45303':{'en': 'tdc'},
'45304':{'en': 'tdc'},
'45305':{'en': 'tdc'},
'45306':{'en': 'tdc'},
'45307':{'en': 'tdc'},
'45308':{'en': 'tdc'},
'45309':{'en': 'tdc'},
'45311':{'en': '3'},
'45312':{'en': '3'},
'45313':{'en': '3'},
'4531312':{'en': 'mi carrier services'},
'45314':{'en': '3'},
'45315':{'en': '3'},
'45316':{'en': '3'},
'45317':{'en': '3'},
'45318':{'en': 'lycamobile denmark ltd'},
'45319':{'en': 'telenor'},
'45321':{'en': 'telenor'},
'45322':{'en': 'telenor'},
'45323':{'en': 'telenor'},
'45324':{'en': 'telenor'},
'45325':{'en': 'telenor'},
'45326':{'en': 'telenor'},
'45327':{'en': 'telenor'},
'45328':{'en': 'telenor'},
'45329':{'en': 'telenor'},
'45331':{'en': 'telenor'},
'45332':{'en': 'telenor'},
'45333':{'en': 'telenor'},
'45334':{'en': 'telenor'},
'45335':{'en': 'telenor'},
'45336':{'en': 'telenor'},
'45337':{'en': 'telenor'},
'45338':{'en': 'telenor'},
'45339':{'en': 'telenor'},
'45341':{'en': 'telenor'},
'45342':{'en': 'telenor'},
'453434':{'en': 'telenor'},
'45351':{'en': 'telenor'},
'45352':{'en': 'telenor'},
'45353':{'en': 'telenor'},
'45354':{'en': 'telenor'},
'45355':{'en': 'telenor'},
'45356':{'en': 'telenor'},
'45357':{'en': 'telenor'},
'45358':{'en': 'telenor'},
'45359':{'en': 'telenor'},
'45361':{'en': 'telenor'},
'45362':{'en': 'telenor'},
'45363':{'en': 'telenor'},
'45364':{'en': 'telenor'},
'45365':{'en': 'telenor'},
'45366':{'en': 'telenor'},
'45367':{'en': 'telenor'},
'45368':{'en': 'telenor'},
'45369':{'en': 'telenor'},
'45381':{'en': 'telenor'},
'45382':{'en': 'telenor'},
'45383':{'en': 'telenor'},
'45384':{'en': 'telenor'},
'45385':{'en': 'telenor'},
'45386':{'en': 'telenor'},
'45387':{'en': 'telenor'},
'45388':{'en': 'telenor'},
'45389':{'en': 'telenor'},
'45391':{'en': 'telenor'},
'45392':{'en': 'telenor'},
'45393':{'en': 'telenor'},
'45394':{'en': 'telenor'},
'45395':{'en': 'telenor'},
'45396':{'en': 'telenor'},
'45397':{'en': 'telenor'},
'45398':{'en': 'telenor'},
'45399':{'en': 'telenor'},
'45401':{'en': 'tdc'},
'45402':{'en': 'tdc'},
'45403':{'en': 'tdc'},
'45404':{'en': 'tdc'},
'45405':{'en': 'telenor'},
'45406':{'en': 'telenor'},
'45407':{'en': 'telenor'},
'45408':{'en': 'telenor'},
'45409':{'en': 'telenor'},
'45411':{'en': 'telenor'},
'45412':{'en': 'telenor'},
'45413':{'en': 'telenor'},
'45414':{'en': 'telenor'},
'45415':{'en': 'telenor'},
'45416':{'en': 'telenor'},
'45417':{'en': 'telenor'},
'45418':{'en': 'telenor'},
'45419':{'en': 'telenor'},
'45421':{'en': 'telia'},
'45422':{'en': 'telia'},
'45423':{'en': 'telia'},
'45424':{'en': 'telenor'},
'45425':{'en': 'telenor'},
'45426':{'en': 'telenor'},
'45427':{'en': 'telenor'},
'45428':{'en': 'telenor'},
'4542900':{'en': 'telenor'},
'4542901':{'en': 'telenor'},
'4542902':{'en': 'telenor'},
'4542903':{'en': 'telenor'},
'4542904':{'en': 'telenor'},
'4542905':{'en': 'telenor'},
'45429060':{'en': 'telenor'},
'45429061':{'en': 'telenor'},
'45429062':{'en': 'telenor'},
'45429063':{'en': 'telenor'},
'45429064':{'en': 'telenor'},
'45429065':{'en': 'telenor'},
'45429066':{'en': 'telenor'},
'45429067':{'en': 'telenor'},
'45429068':{'en': 'tdc'},
'45429084':{'en': 'tdc'},
'454291':{'en': '3'},
'454292':{'en': '3'},
'454293':{'en': 'cbb mobil'},
'454294':{'en': '3'},
'454295':{'en': '3'},
'454296':{'en': 'telia'},
'454297':{'en': 'telia'},
'454298':{'en': 'telia'},
'454299':{'en': 'telia'},
'45431':{'en': 'telenor'},
'45432':{'en': 'telenor'},
'45433':{'en': 'telenor'},
'45434':{'en': 'telenor'},
'45435':{'en': 'telenor'},
'45436':{'en': 'telenor'},
'45437':{'en': 'telenor'},
'45438':{'en': 'telenor'},
'45439':{'en': 'telenor'},
'45441':{'en': 'telenor'},
'45442':{'en': 'telenor'},
'45443':{'en': 'telenor'},
'45444':{'en': 'telenor'},
'45445':{'en': 'telenor'},
'45446':{'en': 'telenor'},
'45447':{'en': 'telenor'},
'45448':{'en': 'telenor'},
'45449':{'en': 'telenor'},
'45451':{'en': 'telenor'},
'45452':{'en': 'telenor'},
'45453':{'en': 'telenor'},
'45454':{'en': 'telenor'},
'45455':{'en': 'telenor'},
'45456':{'en': 'telenor'},
'45457':{'en': 'telenor'},
'45458':{'en': 'telenor'},
'45459':{'en': 'telenor'},
'45461':{'en': 'telenor'},
'45462':{'en': 'telenor'},
'45463':{'en': 'telenor'},
'45464':{'en': 'telenor'},
'45465':{'en': 'telenor'},
'45466':{'en': 'telenor'},
'45467':{'en': 'telenor'},
'45468':{'en': 'telenor'},
'45469':{'en': 'telenor'},
'45471':{'en': 'telenor'},
'45472':{'en': 'telenor'},
'45473':{'en': 'telenor'},
'45474':{'en': 'telenor'},
'45475':{'en': 'telenor'},
'45476':{'en': 'telenor'},
'45477':{'en': 'telenor'},
'45478':{'en': 'telenor'},
'45479':{'en': 'telenor'},
'45481':{'en': 'telenor'},
'45482':{'en': 'telenor'},
'45483':{'en': 'telenor'},
'45484':{'en': 'telenor'},
'45485':{'en': 'telenor'},
'45486':{'en': 'telenor'},
'45487':{'en': 'telenor'},
'45488':{'en': 'telenor'},
'45489':{'en': 'telenor'},
'4549109':{'en': 'tdc'},
'454911':{'en': 'tdc'},
'454912':{'en': 'tdc'},
'4549130':{'en': 'tdc'},
'4549131':{'en': 'tdc'},
'4549132':{'en': 'tdc'},
'4549133':{'en': 'tdc'},
'4549134':{'en': 'tdc'},
'4549135':{'en': 'tdc'},
'4549136':{'en': 'tdc'},
'4549138':{'en': 'tdc'},
'4549139':{'en': 'tdc'},
'454914':{'en': 'tdc'},
'4549150':{'en': 'tdc'},
'4549151':{'en': 'tdc'},
'4549155':{'en': 'tdc'},
'4549156':{'en': 'tdc'},
'4549157':{'en': 'tdc'},
'4549158':{'en': 'tdc'},
'4549159':{'en': 'tdc'},
'4549160':{'en': 'tdc'},
'4549161':{'en': 'tdc'},
'4549162':{'en': 'tdc'},
'4549163':{'en': 'tdc'},
'4549168':{'en': 'tdc'},
'4549169':{'en': 'tdc'},
'454917':{'en': 'tdc'},
'4549180':{'en': 'tdc'},
'4549181':{'en': 'tdc'},
'4549184':{'en': 'tdc'},
'4549185':{'en': 'tdc'},
'4549187':{'en': 'tdc'},
'4549188':{'en': 'tdc'},
'4549189':{'en': 'tdc'},
'454919':{'en': 'tdc'},
'4549200':{'en': 'tdc'},
'4549201':{'en': 'tdc'},
'4549202':{'en': 'tdc'},
'4549203':{'en': 'tdc'},
'454921':{'en': 'tdc'},
'4549220':{'en': 'tdc'},
'4549221':{'en': 'tdc'},
'4549222':{'en': 'tdc'},
'4549223':{'en': 'tdc'},
'4549224':{'en': 'tdc'},
'4549225':{'en': 'tdc'},
'4549226':{'en': 'tdc'},
'4549250':{'en': 'tdc'},
'4549251':{'en': 'tdc'},
'4549252':{'en': 'tdc'},
'4549253':{'en': 'tdc'},
'4549255':{'en': 'tdc'},
'4549256':{'en': 'tdc'},
'4549258':{'en': 'tdc'},
'4549259':{'en': 'tdc'},
'4549260':{'en': 'tdc'},
'4549261':{'en': 'tdc'},
'4549262':{'en': 'tdc'},
'4549263':{'en': 'tdc'},
'4549264':{'en': 'tdc'},
'4549265':{'en': 'tdc'},
'4549266':{'en': 'tdc'},
'454927':{'en': 'tdc'},
'454928':{'en': 'tdc'},
'4549295':{'en': 'tdc'},
'4549298':{'en': 'tdc'},
'4549299':{'en': 'tdc'},
'45493':{'en': 'telenor'},
'45494':{'en': 'telenor'},
'4549700':{'en': 'tdc'},
'4549701':{'en': 'tdc'},
'4549702':{'en': 'tdc'},
'4549703':{'en': 'tdc'},
'4549704':{'en': 'tdc'},
'4549707':{'en': 'tdc'},
'4549708':{'en': 'tdc'},
'4549709':{'en': 'tdc'},
'454971':{'en': 'tdc'},
'4549750':{'en': 'tdc'},
'4549751':{'en': 'tdc'},
'4549752':{'en': 'tdc'},
'4549753':{'en': 'tdc'},
'4549754':{'en': 'tdc'},
'4549755':{'en': 'tdc'},
'4549758':{'en': 'tdc'},
'4549759':{'en': 'tdc'},
'4549760':{'en': 'tdc'},
'4549761':{'en': 'tdc'},
'4549762':{'en': 'tdc'},
'4549763':{'en': 'tdc'},
'4549765':{'en': 'tdc'},
'4549766':{'en': 'tdc'},
'4549767':{'en': 'tdc'},
'454977':{'en': 'tdc'},
'4549780':{'en': 'tdc'},
'4549789':{'en': 'tdc'},
'45501':{'en': 'telenor'},
'45502':{'en': 'telenor'},
'45503':{'en': 'telenor'},
'45504':{'en': 'telenor'},
'45505':{'en': 'telenor'},
'455060':{'en': 'ipvision'},
'455061':{'en': 'svr technologies (mach connectivity)'},
'455062':{'en': 'cbb mobil'},
'455063':{'en': 'mundio mobile'},
'455064':{'en': 'lycamobile denmark ltd'},
'455065':{'en': 'lebara limited'},
'455066':{'en': 'cbb mobil'},
'455067':{'en': 'cbb mobil'},
'455068':{'en': 'cbb mobil'},
'455069':{'en': '3'},
'45507':{'en': 'telenor'},
'45508':{'en': 'telenor'},
'45509':{'en': 'telenor'},
'4551':{'en': 'tdc'},
'45510':{'en': 'orange'},
'455188':{'en': 'telia'},
'455189':{'en': 'telia'},
'45521':{'en': 'telia'},
'455210':{'en': 'firstcom'},
'455211':{'en': '3'},
'455212':{'en': '3'},
'45522':{'en': 'telia'},
'455220':{'en': 'link mobile'},
'455222':{'en': 'lebara limited'},
'455225':{'en': 'cbb mobil'},
'45523':{'en': 'telia'},
'455230':{'en': 'tdc'},
'455233':{'en': 'cbb mobil'},
'45524':{'en': 'telia'},
'455240':{'en': 'tdc'},
'455242':{'en': 'cbb mobil'},
'455244':{'en': 'cbb mobil'},
'455250':{'en': 'tdc'},
'455251':{'en': 'link mobile'},
'455252':{'en': 'lebara limited'},
'455253':{'en': 'cbb mobil'},
'455254':{'en': 'simservice'},
'455255':{'en': 'cbb mobil'},
'455256':{'en': 'simservice'},
'455257':{'en': 'simservice'},
'455258':{'en': 'tdc'},
'455259':{'en': '42 telecom ab'},
'45526':{'en': 'telenor'},
'45527':{'en': 'telenor'},
'45528':{'en': 'telenor'},
'45529':{'en': 'telenor'},
'45531':{'en': 'cbb mobil'},
'455319':{'en': 'telia'},
'45532':{'en': 'telia'},
'45533':{'en': 'telia'},
'455333':{'en': 'lebara limited'},
'45534':{'en': 'telia'},
'45535':{'en': '3'},
'45536':{'en': '3'},
'45537':{'en': '3'},
'45538':{'en': '3'},
'45539':{'en': 'cbb mobil'},
'455398':{'en': 'nextgen mobile ldt t/a cardboardfish'},
'45541':{'en': 'telenor'},
'45542':{'en': 'telenor'},
'45543':{'en': 'telenor'},
'45544':{'en': 'telenor'},
'45545':{'en': 'telenor'},
'45546':{'en': 'telenor'},
'45547':{'en': 'telenor'},
'45548':{'en': 'telenor'},
'45549':{'en': 'telenor'},
'45551':{'en': 'telenor'},
'45552':{'en': 'telenor'},
'45553':{'en': 'telenor'},
'45554':{'en': 'telenor'},
'45555':{'en': 'telenor'},
'45556':{'en': 'telenor'},
'45557':{'en': 'telenor'},
'45558':{'en': 'telenor'},
'45559':{'en': 'telenor'},
'45561':{'en': 'telenor'},
'45562':{'en': 'telenor'},
'45563':{'en': 'telenor'},
'45564':{'en': 'telenor'},
'45565':{'en': 'telenor'},
'45566':{'en': 'telenor'},
'45567':{'en': 'telenor'},
'45568':{'en': 'telenor'},
'45569':{'en': 'telenor'},
'45571':{'en': 'telenor'},
'45572':{'en': 'telenor'},
'45573':{'en': 'telenor'},
'45574':{'en': 'telenor'},
'45575':{'en': 'telenor'},
'45576':{'en': 'telenor'},
'45577':{'en': 'telenor'},
'45578':{'en': 'telenor'},
'45579':{'en': 'telenor'},
'45581':{'en': 'telenor'},
'45582':{'en': 'telenor'},
'45583':{'en': 'telenor'},
'45584':{'en': 'telenor'},
'45585':{'en': 'telenor'},
'45586':{'en': 'telenor'},
'45587':{'en': 'telenor'},
'45588':{'en': 'telenor'},
'45589':{'en': 'telenor'},
'45591':{'en': 'telenor'},
'45592':{'en': 'telenor'},
'45593':{'en': 'telenor'},
'45594':{'en': 'telenor'},
'45595':{'en': 'telenor'},
'45596':{'en': 'telenor'},
'45597':{'en': 'telenor'},
'45598':{'en': 'telenor'},
'45599':{'en': 'telenor'},
'45601':{'en': 'telia'},
'45602':{'en': 'telia'},
'45603':{'en': 'telia'},
'45604':{'en': 'telia'},
'45605':{'en': '3'},
'456050':{'en': 'telenor'},
'45606':{'en': 'cbb mobil'},
'45607':{'en': 'cbb mobil'},
'45608':{'en': 'cbb mobil'},
'456090':{'en': 'lebara limited'},
'456091':{'en': 'telenor'},
'456092':{'en': 'telenor'},
'456093':{'en': 'telenor'},
'456094':{'en': 'telenor'},
'456095':{'en': 'telenor'},
'456096':{'en': 'tripple track europe'},
'456097':{'en': 'tripple track europe'},
'456098':{'en': 'telavox'},
'456099':{'en': 'svr technologies (mach connectivity)'},
'4561':{'en': 'tdc'},
'45610':{'en': 'orange'},
'456146':{'en': 'telia'},
'45618':{'en': 'telenor'},
'45619':{'en': 'telenor'},
'45621':{'en': 'telenor'},
'45622':{'en': 'telenor'},
'45623':{'en': 'telenor'},
'45624':{'en': 'telenor'},
'45625':{'en': 'telenor'},
'45626':{'en': 'telenor'},
'45627':{'en': 'telenor'},
'45628':{'en': 'telenor'},
'45629':{'en': 'telenor'},
'45631':{'en': 'telenor'},
'45632':{'en': 'telenor'},
'45633':{'en': 'telenor'},
'45634':{'en': 'telenor'},
'45635':{'en': 'telenor'},
'45636':{'en': 'telenor'},
'45637':{'en': 'telenor'},
'45638':{'en': 'telenor'},
'45639':{'en': 'telenor'},
'4564212':{'en': 'tdc'},
'4564215':{'en': 'tdc'},
'4564222':{'en': 'tdc'},
'4564281':{'en': 'tdc'},
'4564292':{'en': 'tdc'},
'4564400':{'en': 'tdc'},
'4564401':{'en': 'tdc'},
'4564402':{'en': 'tdc'},
'4564403':{'en': 'tdc'},
'4564404':{'en': 'tdc'},
'4564406':{'en': 'tdc'},
'456441':{'en': 'tdc'},
'4564421':{'en': 'tdc'},
'4564422':{'en': 'tdc'},
'4564423':{'en': 'tdc'},
'4564431':{'en': 'tdc'},
'4564432':{'en': 'tdc'},
'4564433':{'en': 'tdc'},
'4564441':{'en': 'tdc'},
'4564442':{'en': 'tdc'},
'4564451':{'en': 'tdc'},
'4564457':{'en': 'tdc'},
'4564458':{'en': 'tdc'},
'4564459':{'en': 'tdc'},
'4564460':{'en': 'tdc'},
'4564461':{'en': 'tdc'},
'4564462':{'en': 'tdc'},
'4564471':{'en': 'tdc'},
'4564472':{'en': 'tdc'},
'4564473':{'en': 'tdc'},
'4564474':{'en': 'tdc'},
'4564481':{'en': 'tdc'},
'4564491':{'en': 'tdc'},
'4564492':{'en': 'tdc'},
'4564505':{'en': 'tdc'},
'456463':{'en': 'telenor'},
'456464':{'en': 'waoo'},
'456465':{'en': 'waoo'},
'456466':{'en': 'waoo'},
'456467':{'en': 'waoo'},
'456468':{'en': 'waoo'},
'456469':{'en': 'waoo'},
'456471':{'en': 'tdc'},
'4564721':{'en': 'tdc'},
'4564722':{'en': 'tdc'},
'4564723':{'en': 'tdc'},
'4564731':{'en': 'tdc'},
'4564732':{'en': 'tdc'},
'4564733':{'en': 'tdc'},
'4564741':{'en': 'tdc'},
'4564742':{'en': 'tdc'},
'4564746':{'en': 'tdc'},
'4564747':{'en': 'tdc'},
'4564751':{'en': 'tdc'},
'4564752':{'en': 'tdc'},
'4564761':{'en': 'tdc'},
'4564762':{'en': 'tdc'},
'4564763':{'en': 'tdc'},
'4564764':{'en': 'tdc'},
'4564771':{'en': 'tdc'},
'4564781':{'en': 'tdc'},
'4564787':{'en': 'tdc'},
'4564788':{'en': 'tdc'},
'4564789':{'en': 'tdc'},
'4564790':{'en': 'tdc'},
'4564791':{'en': 'tdc'},
'4564792':{'en': 'tdc'},
'4564801':{'en': 'tdc'},
'4564804':{'en': 'tdc'},
'4564805':{'en': 'tdc'},
'4564806':{'en': 'tdc'},
'4564811':{'en': 'tdc'},
'4564812':{'en': 'tdc'},
'4564813':{'en': 'tdc'},
'4564814':{'en': 'tdc'},
'4564820':{'en': 'tdc'},
'4564821':{'en': 'tdc'},
'4564822':{'en': 'tdc'},
'4564823':{'en': 'tdc'},
'4564824':{'en': 'tdc'},
'4564825':{'en': 'tdc'},
'4564826':{'en': 'tdc'},
'4564827':{'en': 'tdc'},
'4564828':{'en': 'tdc'},
'4564831':{'en': 'tdc'},
'4564841':{'en': 'tdc'},
'4564842':{'en': 'tdc'},
'4564851':{'en': 'tdc'},
'4564852':{'en': 'tdc'},
'4564861':{'en': 'tdc'},
'4564871':{'en': 'tdc'},
'4564872':{'en': 'tdc'},
'4564881':{'en': 'tdc'},
'4564882':{'en': 'tdc'},
'4564891':{'en': 'tdc'},
'4564892':{'en': 'tdc'},
'4564893':{'en': 'tdc'},
'4564897':{'en': 'tdc'},
'4564898':{'en': 'tdc'},
'4564899':{'en': 'tdc'},
'45651':{'en': 'telenor'},
'45652':{'en': 'telenor'},
'45653':{'en': 'telenor'},
'45654':{'en': 'telenor'},
'45655':{'en': 'telenor'},
'45656':{'en': 'telenor'},
'45657':{'en': 'telenor'},
'45658':{'en': 'telenor'},
'45659':{'en': 'telenor'},
'45661':{'en': 'telenor'},
'45662':{'en': 'telenor'},
'45663':{'en': 'telenor'},
'45664':{'en': 'telenor'},
'45665':{'en': 'telenor'},
'45666':{'en': 'telenor'},
'45667':{'en': 'telenor'},
'45668':{'en': 'telenor'},
'45669':{'en': 'telenor'},
'45691':{'en': 'telenor'},
'45692':{'en': 'telenor'},
'45693':{'en': 'telenor'},
'45694':{'en': 'telenor'},
'456957':{'en': 'telenor'},
'456958':{'en': 'telenor'},
'456959':{'en': 'telenor'},
'45696':{'en': 'telenor'},
'45697':{'en': 'telenor'},
'45698':{'en': 'telenor'},
'45699':{'en': 'telenor'},
'457010':{'en': 'tdc'},
'457011':{'en': 'tdc'},
'457012':{'en': 'tdc'},
'457013':{'en': 'tdc'},
'457014':{'en': 'tdc'},
'457015':{'en': 'tdc'},
'4570160':{'en': 'telenor'},
'4570161':{'en': 'telenor'},
'4570180':{'en': 'herobase'},
'4570181':{'en': 'telenor'},
'457019':{'en': 'telenor'},
'457030':{'en': 'telenor'},
'4570300':{'en': 'telia'},
'4570301':{'en': 'telia'},
'4570302':{'en': 'telia'},
'457031':{'en': 'telenor'},
'4570323':{'en': 'telenor'},
'457033':{'en': 'telenor'},
'4570345':{'en': 'telenor'},
'4570444':{'en': 'telenor'},
'4570500':{'en': 'telenor'},
'4570505':{'en': 'telenor'},
'4570507':{'en': 'telus aps'},
'4570555':{'en': 'telenor'},
'457060':{'en': 'telenor'},
'4570666':{'en': 'telenor'},
'457070':{'en': 'telenor'},
'457071':{'en': 'telenor'},
'4570770':{'en': 'telenor'},
'4570776':{'en': 'telenor'},
'4570777':{'en': 'telenor'},
'4570778':{'en': 'telenor'},
'457080':{'en': 'telenor'},
'4570810':{'en': 'telenor'},
'4570811':{'en': 'telenor'},
'4570812':{'en': 'telenor'},
'4570813':{'en': 'telenor'},
'4570814':{'en': 'telenor'},
'4570815':{'en': 'telenor'},
'4570816':{'en': 'telenor'},
'4570817':{'en': 'telenor'},
'4570818':{'en': 'telenor'},
'4570828':{'en': 'telenor'},
'4570838':{'en': 'telenor'},
'4570848':{'en': 'telenor'},
'4570858':{'en': 'telenor'},
'4570868':{'en': 'telenor'},
'457087':{'en': 'telenor'},
'457088':{'en': 'supertel danmark'},
'457089':{'en': 'telenor'},
'4570900':{'en': 'telenor'},
'4570907':{'en': 'telus aps'},
'4570909':{'en': 'telenor'},
'4570999':{'en': 'telenor'},
'45711':{'en': 'telenor'},
'45712':{'en': 'telenor'},
'45713':{'en': 'lycamobile denmark ltd'},
'45714':{'en': 'lycamobile denmark ltd'},
'45715':{'en': 'lycamobile denmark ltd'},
'45716':{'en': 'lycamobile denmark ltd'},
'457170':{'en': 'yousee'},
'457171':{'en': 'telenor'},
'457172':{'en': 'tdc'},
'457173':{'en': 'cbb mobil'},
'45717409':{'en': 'tdc'},
'45717429':{'en': 'tdc'},
'457175':{'en': 'telenor'},
'457176':{'en': 'telenor'},
'457177':{'en': 'tdc'},
'457178':{'en': 'telenor'},
'457179':{'en': 'telenor'},
'45718':{'en': 'lycamobile denmark ltd'},
'457190':{'en': '3'},
'457191':{'en': 'telecom x'},
'457192':{'en': 'fullrate'},
'457193':{'en': 'cbb mobil'},
'457194':{'en': 'telenor'},
'457195':{'en': 'telenor'},
'4571960':{'en': 'tdc'},
'45719649':{'en': 'tdc'},
'45719689':{'en': 'tdc'},
'457197':{'en': 'mundio mobile'},
'457198':{'en': 'mundio mobile'},
'457199':{'en': 'firmafon'},
'45721':{'en': 'telenor'},
'45722':{'en': 'telenor'},
'45723':{'en': 'telenor'},
'45724':{'en': 'telenor'},
'45725':{'en': 'telenor'},
'45726':{'en': 'telenor'},
'45727':{'en': 'telenor'},
'45728':{'en': 'telenor'},
'45729':{'en': 'telenor'},
'45731':{'en': 'telenor'},
'45732':{'en': 'telenor'},
'45733':{'en': 'telenor'},
'45734':{'en': 'telenor'},
'45735':{'en': 'telenor'},
'45736':{'en': 'telenor'},
'45737':{'en': 'telenor'},
'45738':{'en': 'telenor'},
'45739':{'en': 'telenor'},
'45741':{'en': 'telenor'},
'45742':{'en': 'telenor'},
'45743':{'en': 'telenor'},
'45744':{'en': 'telenor'},
'45745':{'en': 'telenor'},
'45746':{'en': 'telenor'},
'45747':{'en': 'telenor'},
'45748':{'en': 'telenor'},
'45749':{'en': 'telenor'},
'45751':{'en': 'telenor'},
'45752':{'en': 'telenor'},
'45753':{'en': 'telenor'},
'45754':{'en': 'telenor'},
'45755':{'en': 'telenor'},
'45756':{'en': 'telenor'},
'45757':{'en': 'telenor'},
'45758':{'en': 'telenor'},
'45759':{'en': 'telenor'},
'45761':{'en': 'telenor'},
'45762':{'en': 'telenor'},
'45763':{'en': 'telenor'},
'45764':{'en': 'telenor'},
'45765':{'en': 'telenor'},
'45766':{'en': 'telenor'},
'45767':{'en': 'telenor'},
'45768':{'en': 'telenor'},
'45769':{'en': 'telenor'},
'45771':{'en': 'telenor'},
'45772':{'en': 'telenor'},
'45773':{'en': 'telenor'},
'45774':{'en': 'telenor'},
'45775':{'en': 'telenor'},
'45776':{'en': 'telenor'},
'45777':{'en': 'telenor'},
'45778':{'en': 'telenor'},
'45779':{'en': 'telenor'},
'45781':{'en': 'telenor'},
'45782':{'en': 'telenor'},
'45783':{'en': 'telenor'},
'45784':{'en': 'telenor'},
'45785':{'en': 'telenor'},
'45786':{'en': 'telenor'},
'45787':{'en': 'telenor'},
'457879':{'en': 'supertel danmark'},
'45788':{'en': 'telenor'},
'45789':{'en': 'telenor'},
'45791':{'en': 'telenor'},
'45792':{'en': 'telenor'},
'45793':{'en': 'telenor'},
'45794':{'en': 'telenor'},
'45795':{'en': 'telenor'},
'45796':{'en': 'telenor'},
'45797':{'en': 'telenor'},
'45798':{'en': 'telenor'},
'45799':{'en': 'telenor'},
'45811':{'en': 'telenor'},
'45812':{'en': 'telenor'},
'458130':{'en': 'cbb mobil'},
'458131':{'en': 'cbb mobil'},
'458132':{'en': 'cbb mobil'},
'458133':{'en': 'cbb mobil'},
'458134':{'en': 'cbb mobil'},
'458135':{'en': 'cbb mobil'},
'458136':{'en': 'cbb mobil'},
'4581370':{'en': 'telenor'},
'4581371':{'en': 'clx networks ab'},
'4581372':{'en': 'care solutions aka phone-it'},
'4581373':{'en': 'tdc'},
'4581374':{'en': 'mitto ag'},
'4581375':{'en': 'monty uk global limited'},
'4581376':{'en': 'icentrex lso(tdc)'},
'4581379':{'en': 'telenor'},
'458138':{'en': 'mundio mobile'},
'458139':{'en': 'mundio mobile'},
'458140':{'en': 'ipnordic'},
'458141':{'en': '3'},
'458144':{'en': 'fullrate'},
'458145':{'en': 'telavox'},
'458146':{'en': 'mundio mobile'},
'458147':{'en': 'mundio mobile'},
'458148':{'en': 'mundio mobile'},
'458149':{'en': 'mundio mobile'},
'45815':{'en': 'cbb mobil'},
'45816':{'en': 'cbb mobil'},
'458161':{'en': 'tdc'},
'458170':{'en': 'cbb mobil'},
'458171':{'en': 'tdc'},
'458172':{'en': 'fullrate'},
'458173':{'en': 'tdc'},
'458174':{'en': 'tdc'},
'458175':{'en': 'tdc'},
'458176':{'en': 'cbb mobil'},
'458177':{'en': 'ipvision'},
'458178':{'en': 'cbb mobil'},
'458179':{'en': 'cbb mobil'},
'45818':{'en': 'cbb mobil'},
'458180':{'en': 'ipvision'},
'458181':{'en': 'maxtel.dk'},
'458182':{'en': 'polperro'},
'458188':{'en': 'ipvision'},
'458190':{'en': 'lebara limited'},
'458191':{'en': 'lebara limited'},
'458192':{'en': 'lebara limited'},
'458193':{'en': 'lebara limited'},
'458194':{'en': 'lebara limited'},
'458195':{'en': 'cbb mobil'},
'458196':{'en': 'cbb mobil'},
'458197':{'en': 'cbb mobil'},
'458198':{'en': 'cbb mobil'},
'458199':{'en': 'telenor'},
'45821':{'en': 'telenor'},
'45822':{'en': 'telenor'},
'45823':{'en': 'telenor'},
'45824':{'en': 'telenor'},
'45825':{'en': 'telenor'},
'45826':{'en': 'telenor'},
'45827':{'en': 'telenor'},
'45828':{'en': 'telenor'},
'45829':{'en': 'telenor'},
'45861':{'en': 'telenor'},
'45862':{'en': 'telenor'},
'45863':{'en': 'telenor'},
'45864':{'en': 'telenor'},
'45865':{'en': 'telenor'},
'45866':{'en': 'telenor'},
'45867':{'en': 'telenor'},
'45868':{'en': 'telenor'},
'45869':{'en': 'telenor'},
'45871':{'en': 'telenor'},
'45872':{'en': 'telenor'},
'45873':{'en': 'telenor'},
'45874':{'en': 'telenor'},
'45875':{'en': 'telenor'},
'45876':{'en': 'telenor'},
'45877':{'en': 'telenor'},
'45878':{'en': 'telenor'},
'45879':{'en': 'telenor'},
'45881':{'en': 'telenor'},
'45882':{'en': 'telenor'},
'45883':{'en': 'telenor'},
'45884':{'en': 'telenor'},
'45885':{'en': 'telenor'},
'45886':{'en': 'telenor'},
'45887':{'en': 'telenor'},
'45888':{'en': 'telenor'},
'45889':{'en': 'telenor'},
'45891':{'en': 'telenor'},
'45892':{'en': 'telenor'},
'45893':{'en': 'telenor'},
'45894':{'en': 'telenor'},
'45895':{'en': 'telenor'},
'45896':{'en': 'telenor'},
'45897':{'en': 'telenor'},
'45898':{'en': 'telenor'},
'45899':{'en': 'telenor'},
'459110':{'en': 'lebara limited'},
'459111':{'en': 'lebara limited'},
'459112':{'en': 'simservice'},
'459113':{'en': 'simservice'},
'459114':{'en': 'simservice'},
'459115':{'en': 'tdc'},
'459116':{'en': 'tdc'},
'459117':{'en': 'tdc'},
'459118':{'en': 'tdc'},
'459119':{'en': 'lebara limited'},
'459120':{'en': 'tismi bv'},
'459121':{'en': 'simservice'},
'459122':{'en': 'tdc'},
'459123':{'en': 'tdc'},
'459124':{'en': 'tdc'},
'459125':{'en': 'tdc'},
'459126':{'en': 'mundio mobile'},
'459127':{'en': 'mundio mobile'},
'459128':{'en': 'mundio mobile'},
'459129':{'en': 'mundio mobile'},
'4591300':{'en': 'maxtel.dk'},
'4591303':{'en': 'maxtel.dk'},
'459131':{'en': 'telenor'},
'459132':{'en': 'telenor'},
'459133':{'en': 'telenor'},
'459134':{'en': 'telenor'},
'459135':{'en': 'telenor'},
'459136':{'en': 'telenor'},
'459137':{'en': 'telenor'},
'459138':{'en': 'telenor'},
'459139':{'en': 'telenor'},
'45914':{'en': 'lycamobile denmark ltd'},
'459150':{'en': 'telenor'},
'459151':{'en': 'telenor'},
'459152':{'en': 'tdc'},
'459153':{'en': 'tdc'},
'459154':{'en': 'tdc'},
'459155':{'en': 'tdc'},
'459156':{'en': 'tdc'},
'459157':{'en': 'mundio mobile'},
'459158':{'en': 'nextgen mobile ldt t/a cardboardfish'},
'459159':{'en': 'simservice'},
'45916':{'en': 'lycamobile denmark ltd'},
'45917':{'en': 'lycamobile denmark ltd'},
'45918':{'en': 'lebara limited'},
'459189':{'en': 'tdc'},
'45919':{'en': 'lebara limited'},
'459190':{'en': 'intelecom'},
'459191':{'en': 'maxtel.dk'},
'45921':{'en': 'tdc'},
'459217':{'en': 'interactive digital media gmbh'},
'459218':{'en': 'telenor'},
'459219':{'en': 'telenor'},
'459220':{'en': 'telenor'},
'459221':{'en': 'tdc'},
'459222':{'en': 'tdc'},
'459223':{'en': '42 telecom ab'},
'459224':{'en': 'simservice'},
'459225':{'en': 'mundio mobile'},
'459226':{'en': 'mundio mobile'},
'459227':{'en': 'mundio mobile'},
'459228':{'en': 'mundio mobile'},
'459229':{'en': 'beepsend ab'},
'45923':{'en': 'telenor'},
'459240':{'en': 'gigsky aps'},
'459241':{'en': 'gigsky aps'},
'459242':{'en': 'gigsky aps'},
'459243':{'en': 'tdc'},
'459244':{'en': 'ipnordic'},
'459245':{'en': 'compatel limited'},
'459246':{'en': 'telenor'},
'459247':{'en': 'telenor'},
'459248':{'en': 'telenor'},
'459249':{'en': 'telenor'},
'45925':{'en': 'telenor'},
'45926':{'en': 'telenor'},
'45927':{'en': 'telenor'},
'459270':{'en': 'ice danmark'},
'459272':{'en': 'thyfon'},
'45928':{'en': 'telenor'},
'459280':{'en': 'voxbone'},
'459281':{'en': 'gigsky aps'},
'459282':{'en': 'flexfone'},
'459283':{'en': 'tdc'},
'45929':{'en': 'telenor'},
'459290':{'en': 'fullrate'},
'459299':{'en': 'ipvision'},
'459310':{'en': 'fullrate'},
'459311':{'en': 'benemen lso (tdc)'},
'459312':{'en': 'tdc'},
'459313':{'en': 'tdc'},
'459314':{'en': 'simservice'},
'459315':{'en': 'simservice'},
'459316':{'en': 'simservice'},
'459317':{'en': 'simservice'},
'459318':{'en': 'simservice'},
'459319':{'en': 'tdc'},
'459320':{'en': 'fullrate'},
'459321':{'en': 'simservice'},
'459322':{'en': 'simservice'},
'459323':{'en': 'simservice'},
'459324':{'en': 'simservice'},
'459325':{'en': 'telenor'},
'459326':{'en': 'telenor'},
'459327':{'en': 'telenor'},
'459328':{'en': 'telenor'},
'459329':{'en': 'telenor'},
'459330':{'en': 'fullrate'},
'459331':{'en': 'tdc'},
'459332':{'en': 'telenor'},
'459333':{'en': 'onoffapp'},
'459334':{'en': 'simservice'},
'459335':{'en': 'simservice'},
'459336':{'en': 'simservice'},
'459337':{'en': 'simservice'},
'459338':{'en': 'simservice'},
'459339':{'en': 'uni-tel'},
'459340':{'en': 'fullrate'},
'459341':{'en': 'telenor'},
'459342':{'en': 'telenor'},
'459343':{'en': 'telenor'},
'459344':{'en': 'telenor'},
'459345':{'en': 'telenor'},
'459346':{'en': 'simservice'},
'459347':{'en': 'simservice'},
'459348':{'en': 'simservice'},
'459349':{'en': 'simservice'},
'45935':{'en': 'telenor'},
'45936':{'en': 'simservice'},
'459360':{'en': '3'},
'459361':{'en': 'telenor'},
'459362':{'en': 'telenor'},
'459363':{'en': 'tdc'},
'459370':{'en': 'telenor'},
'459371':{'en': 'simservice'},
'459372':{'en': 'simservice'},
'459373':{'en': 'simservice'},
'459375':{'en': 'telenor'},
'459376':{'en': 'tdc'},
'459377':{'en': 'tdc'},
'459378':{'en': 'telenor'},
'459379':{'en': 'tdc'},
'45938':{'en': '3'},
'459381':{'en': 'tdc'},
'459382':{'en': 'tdc'},
'45939':{'en': '3'},
'459440':{'en': 'tdc'},
'459441':{'en': 'tdc'},
'459442':{'en': 'tdc'},
'459481':{'en': 'tdc'},
'4596':{'en': 'telenor'},
'45971':{'en': 'telenor'},
'45972':{'en': 'telenor'},
'45973':{'en': 'telenor'},
'45974':{'en': 'telenor'},
'45975':{'en': 'telenor'},
'45976':{'en': 'telenor'},
'45978':{'en': 'telenor'},
'45979':{'en': 'telenor'},
'45981':{'en': 'telenor'},
'45982':{'en': 'telenor'},
'45983':{'en': 'telenor'},
'45984':{'en': 'telenor'},
'45985':{'en': 'telenor'},
'45986':{'en': 'telenor'},
'45987':{'en': 'telenor'},
'45988':{'en': 'telenor'},
'45989':{'en': 'telenor'},
'45991':{'en': 'telenor'},
'45992':{'en': 'telenor'},
'45993':{'en': 'telenor'},
'45994':{'en': 'telenor'},
'45995':{'en': 'telenor'},
'45996':{'en': 'telenor'},
'45997':{'en': 'telenor'},
'45998':{'en': 'telenor'},
'45999':{'en': 'telenor'},
'46700':{'en': 'Tele2 Sverige'},
'467010':{'en': 'SPINBOX AB'},
'467011':{'en': 'Telenor Sverige'},
'467012':{'en': 'SPINBOX AB'},
'46701332':{'en': 'EU Tel AB'},
'46701334':{'en': 'EU Tel AB'},
'46701335':{'en': 'EU Tel AB'},
'46701336':{'en': 'EU Tel AB'},
'46701338':{'en': 'EU Tel AB'},
'46701339':{'en': 'EU Tel AB'},
'46701341':{'en': 'EU Tel AB'},
'46701342':{'en': 'EU Tel AB'},
'46701346':{'en': 'EU Tel AB'},
'46701347':{'en': 'EU Tel AB'},
'46701348':{'en': 'EU Tel AB'},
'46701349':{'en': 'EU Tel AB'},
'46701353':{'en': 'EU Tel AB'},
'46701356':{'en': 'EU Tel AB'},
'46701358':{'en': 'EU Tel AB'},
'46701359':{'en': 'EU Tel AB'},
'46701362':{'en': 'EU Tel AB'},
'46701364':{'en': '42 Telecom AB'},
'46701365':{'en': '42 Telecom AB'},
'46701366':{'en': '42 Telecom AB'},
'46701367':{'en': '42 Telecom AB'},
'46701368':{'en': '42 Telecom AB'},
'46701369':{'en': '42 Telecom AB'},
'4670137':{'en': '42 Telecom AB'},
'46701381':{'en': '42 Telecom AB'},
'46701383':{'en': '42 Telecom AB'},
'46701384':{'en': '42 Telecom AB'},
'46701385':{'en': '42 Telecom AB'},
'46701386':{'en': '42 Telecom AB'},
'46701388':{'en': '42 Telecom AB'},
'46701389':{'en': '42 Telecom AB'},
'46701390':{'en': '42 Telecom AB'},
'46701391':{'en': '42 Telecom AB'},
'46701392':{'en': '42 Telecom AB'},
'46701393':{'en': '42 Telecom AB'},
'46701394':{'en': '42 Telecom AB'},
'46701396':{'en': '42 Telecom AB'},
'46701397':{'en': '42 Telecom AB'},
'46701398':{'en': '42 Telecom AB'},
'46701399':{'en': '42 Telecom AB'},
'467014':{'en': 'Telenor Sverige'},
'467015':{'en': 'Tele2 Sverige'},
'467016':{'en': 'Tele2 Sverige'},
'46701717':{'en': '42 Telecom AB'},
'46701741':{'en': '42 Telecom AB'},
'46701779':{'en': 'EU Tel AB'},
'46701780':{'en': '42 Telecom AB'},
'46701781':{'en': '42 Telecom AB'},
'46701782':{'en': '42 Telecom AB'},
'46701783':{'en': '42 Telecom AB'},
'46701784':{'en': '42 Telecom AB'},
'46701785':{'en': '42 Telecom AB'},
'46701786':{'en': '42 Telecom AB'},
'46701788':{'en': 'Ventelo Sverige'},
'46701790':{'en': 'Svea Billing System'},
'46701791':{'en': 'Svea Billing System'},
'46701792':{'en': 'Svea Billing System'},
'46701793':{'en': 'Svea Billing System'},
'46701794':{'en': 'Svea Billing System'},
'46701795':{'en': 'Svea Billing System'},
'46701796':{'en': 'Svea Billing System'},
'46701797':{'en': 'EU Tel AB'},
'46701798':{'en': 'Gotalandsnatet'},
'467018':{'en': 'SPINBOX AB'},
'4670189':{'en': 'Alltele Sverige'},
'46701897':{'en': 'Gotalandsnatet'},
'4670190':{'en': 'Ventelo Sverige'},
'4670191':{'en': 'Ventelo Sverige'},
'46701920':{'en': 'Viatel Sweden'},
'46701921':{'en': 'Beepsend'},
'46701924':{'en': 'Compatel Limited'},
'46701925':{'en': 'Mobile Arts AB'},
'46701926':{'en': 'Beepsend'},
'46701928':{'en': 'HORISEN AG'},
'4670193':{'en': 'Com Hem'},
'4670194':{'en': 'Gotalandsnatet'},
'4670195':{'en': 'Gotalandsnatet'},
'46701965':{'en': '42 Telecom AB'},
'46701966':{'en': '42 Telecom AB'},
'46701967':{'en': '42 Telecom AB'},
'46701968':{'en': '42 Telecom AB'},
'4670197':{'en': 'Weblink IP Phone'},
'46701977':{'en': '42 Telecom AB'},
'46701978':{'en': '42 Telecom AB'},
'46701979':{'en': '42 Telecom AB'},
'4670198':{'en': 'IP-Only Telecommunication'},
'46701990':{'en': 'Telenor Sverige'},
'46701991':{'en': 'Telenor Sverige'},
'46701992':{'en': 'Telenor Sverige'},
'46701993':{'en': 'Telenor Sverige'},
'46701994':{'en': 'Telenor Sverige'},
'46701995':{'en': 'Telenor Sverige'},
'46701997':{'en': '42 Telecom AB'},
'46701998':{'en': 'MERCURY INTERNATIONA'},
'46701999':{'en': '42 Telecom AB'},
'46702':{'en': 'TeliaSonera'},
'46703':{'en': 'TeliaSonera'},
'46704':{'en': 'Tele2 Sverige'},
'46705':{'en': 'TeliaSonera'},
'46706':{'en': 'TeliaSonera'},
'46707':{'en': 'Tele2 Sverige'},
'46708':{'en': 'Telenor Sverige'},
'46709':{'en': 'Telenor Sverige'},
'467200':{'en': 'Tele2 Sverige'},
'467201':{'en': 'Tele2 Sverige'},
'467202':{'en': 'Tele2 Sverige'},
'467203':{'en': 'Tele2 Sverige'},
'467204':{'en': 'Tele2 Sverige'},
'46720501':{'en': 'Generic Mobil Systems'},
'46720502':{'en': 'Telavox AB'},
'46720503':{'en': 'Telavox AB'},
'46720504':{'en': 'Telavox AB'},
'46720505':{'en': 'Telavox AB'},
'46720506':{'en': 'Telavox AB'},
'46720507':{'en': 'Telavox AB'},
'46720509':{'en': 'Telavox AB'},
'4672051':{'en': 'WIFOG AB'},
'4672052':{'en': 'WIFOG AB'},
'4672053':{'en': 'WIFOG AB'},
'4672054':{'en': 'WIFOG AB'},
'4672055':{'en': 'Bahnhof AB'},
'4672056':{'en': 'Bahnhof AB'},
'4672057':{'en': 'WIFOG AB'},
'46720580':{'en': 'MERCURY INTERNATIONA'},
'46720581':{'en': 'Beepsend'},
'46720582':{'en': 'iCentrex Sweden AB'},
'46720583':{'en': 'iCentrex Sweden AB'},
'46720584':{'en': 'iCentrex Sweden AB'},
'46720585':{'en': 'iCentrex Sweden AB'},
'46720586':{'en': 'iCentrex Sweden AB'},
'4672059':{'en': 'Telenor Sverige'},
'467206':{'en': 'Com Hem'},
'467207':{'en': 'SOLUNO BC AB'},
'46720801':{'en': 'Telavox AB'},
'46720802':{'en': 'Telavox AB'},
'46720803':{'en': 'Telavox AB'},
'46720807':{'en': 'Telavox AB'},
'46720808':{'en': 'Telavox AB'},
'4672081':{'en': 'BM Sverige AB'},
'4672082':{'en': 'Fibio Nordic AB'},
'4672083':{'en': 'Tele2 Sverige'},
'4672084':{'en': 'Tele2 Sverige'},
'4672085':{'en': 'Tele2 Sverige'},
'4672088':{'en': 'Telenor Sverige'},
'46720902':{'en': 'Telavox AB'},
'46720908':{'en': 'Telavox AB'},
'4672092':{'en': 'Telavox AB'},
'46720999':{'en': 'MOBIWEB LTD'},
'467210':{'en': 'SVENSK KONSUMENTMOBI'},
'467211':{'en': 'SVENSK KONSUMENTMOBI'},
'467212':{'en': 'TeliaSonera'},
'467213':{'en': 'TeliaSonera'},
'4672140':{'en': 'Bredband 2'},
'4672141':{'en': 'Tele2 Sverige'},
'4672142':{'en': 'Tele2 Sverige'},
'4672143':{'en': 'Tele2 Sverige'},
'4672144':{'en': 'Tele2 Sverige'},
'4672145':{'en': 'Tele2 Sverige'},
'4672146':{'en': 'Tele2 Sverige'},
'4672147':{'en': 'Tele2 Sverige'},
'4672148':{'en': 'Tele2 Sverige'},
'46721490':{'en': 'Tele2 Sverige'},
'46721491':{'en': 'Tele2 Sverige'},
'46721492':{'en': 'Tele2 Sverige'},
'46721493':{'en': 'Tele2 Sverige'},
'46721494':{'en': 'Tele2 Sverige'},
'46721495':{'en': 'Beepsend'},
'46721497':{'en': 'MONTY UK GLOBAL LIM'},
'46721498':{'en': 'Beepsend'},
'467215':{'en': 'Telenor Sverige'},
'467216':{'en': 'Telenor Sverige'},
'467217':{'en': 'Telenor Sverige'},
'467218':{'en': 'Telenor Sverige'},
'467219':{'en': 'Telenor Sverige'},
'46722':{'en': 'TeliaSonera'},
'467230':{'en': 'HI3G Access'},
'467231':{'en': 'HI3G Access'},
'467232':{'en': 'HI3G Access'},
'467233':{'en': 'HI3G Access'},
'46723401':{'en': 'LOXYTEL AB'},
'46723403':{'en': 'Beepsend'},
'46723404':{'en': 'LOXYTEL AB'},
'46723405':{'en': 'LOXYTEL AB'},
'46723406':{'en': 'LOXYTEL AB'},
'46723407':{'en': 'LOXYTEL AB'},
'46723408':{'en': 'ONOFF TELECOM SAS'},
'46723409':{'en': 'ONOFF TELECOM SAS'},
'4672341':{'en': 'TELIGOO AB (Fello AB)'},
'4672342':{'en': 'Telenor Sverige'},
'4672343':{'en': 'MESSAGEBIRD B.V.'},
'46723440':{'en': 'Beepsend'},
'46723449':{'en': 'Beepsend'},
'4672345':{'en': '42 Telecom AB'},
'46723460':{'en': 'Beepsend'},
'4672347':{'en': 'Benemen Oy'},
'4672348':{'en': 'Benemen Oy'},
'46723490':{'en': 'Beepsend'},
'46723499':{'en': 'Beepsend'},
'467235':{'en': 'Telenor Sverige'},
'467236':{'en': 'Telenor Sverige'},
'467237':{'en': 'Telenor Sverige'},
'467238':{'en': 'Telenor Sverige'},
'467239':{'en': 'Telenor Sverige'},
'46724000':{'en': 'Telenor Sverige'},
'46724001':{'en': 'Beepsend'},
'46724002':{'en': 'Voice Integrate'},
'46724003':{'en': 'Voice Integrate'},
'46724004':{'en': 'Beepsend'},
'46724008':{'en': 'Telavox AB'},
'4672401':{'en': 'Telavox AB'},
'4672402':{'en': 'Telavox AB'},
'467242':{'en': 'WIFOG AB'},
'467243':{'en': 'WIFOG AB'},
'467244':{'en': 'Telenor Sverige'},
'467245':{'en': 'TeliaSonera'},
'467246':{'en': 'TeliaSonera'},
'467247':{'en': 'TeliaSonera'},
'467248':{'en': 'TeliaSonera'},
'467249':{'en': 'TeliaSonera'},
'46725':{'en': 'TeliaSonera'},
'46726000':{'en': 'Beepsend'},
'46726001':{'en': 'FINK TELECOM SERVIC'},
'46726003':{'en': 'MOBIWEB LTD'},
'46726004':{'en': 'Tele2 Sverige'},
'46726005':{'en': 'Tele2 Sverige'},
'46726006':{'en': 'Telavox AB'},
'46726008':{'en': 'Global Telefoni Sve'},
'4672601':{'en': 'Telavox AB'},
'4672606':{'en': 'Tele2 Sverige'},
'467261':{'en': 'GLOBETOUCH AB'},
'467262':{'en': 'GLOBETOUCH AB'},
'467263':{'en': 'GLOBETOUCH AB'},
'46726421':{'en': 'WARSIN HOLDING AB'},
'46726422':{'en': 'Beepsend'},
'46726423':{'en': 'Global Telefoni Sve'},
'46726424':{'en': 'Global Telefoni Sve'},
'46726425':{'en': 'Global Telefoni Sve'},
'46726426':{'en': 'Global Telefoni Sve'},
'46726427':{'en': 'Global Telefoni Sve'},
'46726428':{'en': 'Global Telefoni Sve'},
'46726429':{'en': 'Global Telefoni Sve'},
'4672644':{'en': 'Telenor Sverige'},
'467265':{'en': 'TeliaSonera'},
'4672660':{'en': 'Telenor Sverige'},
'4672666':{'en': 'Telenor Sverige'},
'4672669':{'en': 'Nortech'},
'467267':{'en': 'TeliaSonera'},
'467268':{'en': 'TeliaSonera'},
'4672698':{'en': 'SWEDFONENET AB'},
'46726990':{'en': 'Gotalandsnatet'},
'46726991':{'en': 'Fast Communication'},
'46726992':{'en': 'Fast Communication'},
'46726993':{'en': 'SWEDFONENET AB'},
'46726994':{'en': 'SWEDFONENET AB'},
'46726995':{'en': 'SWEDFONENET AB'},
'46726996':{'en': 'Nortech'},
'46726997':{'en': 'ONOFF TELECOM SAS'},
'46726998':{'en': 'ONOFF TELECOM SAS'},
'467270':{'en': 'TeliaSonera'},
'467271':{'en': 'TeliaSonera'},
'467272':{'en': 'TeliaSonera'},
'467273':{'en': 'TeliaSonera'},
'467274':{'en': 'TeliaSonera'},
'46727501':{'en': 'ONOFF TELECOM SAS'},
'46727502':{'en': 'ONOFF TELECOM SAS'},
'46727503':{'en': 'MINITEL AB'},
'46727504':{'en': 'FINK TELECOM SERVIC'},
'46727506':{'en': 'FINK TELECOM SERVIC'},
'46727507':{'en': 'FINK TELECOM SERVIC'},
'46727510':{'en': 'ONOFF TELECOM SAS'},
'46727511':{'en': 'ONOFF TELECOM SAS'},
'46727515':{'en': 'FINK TELECOM SERVIC'},
'46727516':{'en': 'FINK TELECOM SERVIC'},
'4672753':{'en': 'NETMORE GROUP AB'},
'4672754':{'en': 'Telenor Sverige'},
'4672755':{'en': 'FINK TELECOM SERVIC'},
'4672756':{'en': 'FINK TELECOM SERVIC'},
'467276':{'en': 'Lycamobile Sweden'},
'467277':{'en': 'Lycamobile Sweden'},
'467278':{'en': 'Lycamobile Sweden'},
'46728100':{'en': 'Voice Integrate'},
'46728101':{'en': 'Beepsend'},
'46728198':{'en': 'Telavox AB'},
'467282':{'en': 'Telecom3 Networks'},
'467283':{'en': 'Tele2 Sverige'},
'467284':{'en': 'Tele2 Sverige'},
'467285':{'en': 'Tele2 Sverige'},
'467286':{'en': 'Tele2 Sverige'},
'467287':{'en': 'Tele2 Sverige'},
'467288':{'en': 'Telenor Sverige'},
'467289':{'en': 'Qall Telecom AB'},
'467290':{'en': 'Tele2 Sverige'},
'467291':{'en': 'Tele2 Sverige'},
'467292':{'en': 'Tele2 Sverige'},
'467293':{'en': 'Tele2 Sverige'},
'467294':{'en': 'Tele2 Sverige'},
'467296':{'en': 'Telenor Sverige'},
'467297':{'en': 'Telenor Sverige'},
'467298':{'en': 'Telenor Sverige'},
'467299':{'en': 'Telenor Sverige'},
'46730':{'en': 'TeliaSonera'},
'467301':{'en': 'Maingate (Sierra Wireless)'},
'467310':{'en': 'Telenor Sverige'},
'467311':{'en': 'Maingate (Sierra Wireless)'},
'4673120':{'en': 'Telavox AB'},
'46731214':{'en': 'Voice Integrate'},
'46731215':{'en': 'COOLTEL APS'},
'46731216':{'en': 'HORISEN AG'},
'46731219':{'en': 'CLX Networks AB'},
'4673122':{'en': 'EU Tel AB'},
'4673123':{'en': '42 Telecom AB'},
'46731245':{'en': 'EU Tel AB'},
'46731247':{'en': 'Beepsend'},
'46731248':{'en': 'TELNESS AB'},
'4673125':{'en': 'Telenor Sverige'},
'4673126':{'en': 'Telenor Connexion'},
'4673127':{'en': 'SWEDFONENET AB'},
'4673128':{'en': 'SST Net Sverige AB'},
'4673129':{'en': 'SPIRIUS AB'},
'467313':{'en': 'iMEZ'},
'467314':{'en': 'Telenor Sverige'},
'467315':{'en': 'Telenor Sverige'},
'467316':{'en': 'Alltele Sverige'},
'46731706':{'en': 'Soatso AB'},
'4673171':{'en': 'Ventelo Sverige'},
'46731721':{'en': 'REWICOM SCANDINAVIA'},
'46731723':{'en': 'REWICOM SCANDINAVIA'},
'46731724':{'en': 'REWICOM SCANDINAVIA'},
'46731725':{'en': 'REWICOM SCANDINAVIA'},
'46731726':{'en': 'REWICOM SCANDINAVIA'},
'46731727':{'en': 'Beepsend'},
'46731728':{'en': 'Beepsend'},
'46731729':{'en': 'IPIFY LIMITED'},
'4673173':{'en': 'Svea Billing System'},
'4673174':{'en': 'Svea Billing System'},
'4673175':{'en': 'Svea Billing System'},
'4673176':{'en': 'ID Mobile'},
'4673177':{'en': 'SST Net Sverige AB'},
'4673178':{'en': 'SST Net Sverige AB'},
'4673179':{'en': 'SST Net Sverige AB'},
'467318':{'en': 'ACN Communications Sweden'},
'467319':{'en': 'TeliaSonera'},
'467320':{'en': 'Telenor Sverige'},
'467321':{'en': 'Tele2 Sverige'},
'467322':{'en': 'Tele2 Sverige'},
'467323':{'en': 'Telenor Sverige'},
'467324':{'en': 'Telenor Sverige'},
'467325':{'en': 'Telenor Sverige'},
'467326':{'en': 'Telenor Sverige'},
'467327':{'en': 'Ventelo Sverige'},
'467328':{'en': 'Telenor Sverige'},
'46733':{'en': 'Telenor Sverige'},
'467340':{'en': 'Telenor Sverige'},
'467341':{'en': 'Telenor Sverige'},
'467342':{'en': 'Telenor Sverige'},
'467343':{'en': 'Telenor Sverige'},
'467344':{'en': 'Telenor Sverige'},
'4673450':{'en': 'Weelia Enterprise A'},
'4673451':{'en': 'CELLIP AB'},
'46734520':{'en': 'Soatso AB'},
'46734521':{'en': 'Soatso AB'},
'46734522':{'en': 'Soatso AB'},
'46734523':{'en': 'Soatso AB'},
'46734524':{'en': 'Soatso AB'},
'46734525':{'en': 'Soatso AB'},
'46734527':{'en': 'Soatso AB'},
'46734528':{'en': 'Soatso AB'},
'46734529':{'en': 'Soatso AB'},
'4673454':{'en': 'Tele2 Sverige'},
'4673455':{'en': 'Viatel Sweden'},
'4673456':{'en': 'Svea Billing System'},
'4673457':{'en': 'Telenor Sverige'},
'4673458':{'en': 'Telenor Sverige'},
'4673459':{'en': '42 Telecom AB'},
'467346':{'en': 'Telenor Sverige'},
'4673460':{'en': 'Ventelo Sverige'},
'46734600':{'en': 'MERCURY INTERNATIONA'},
'46734601':{'en': 'MERCURY INTERNATIONA'},
'4673461':{'en': 'Ventelo Sverige'},
'46734700':{'en': '42 Telecom AB'},
'46734702':{'en': 'MOBIWEB LTD'},
'46734703':{'en': 'MOBIWEB LTD'},
'46734704':{'en': 'MOBIWEB LTD'},
'46734705':{'en': 'MOBIWEB LTD'},
'46734706':{'en': 'MOBIWEB LTD'},
'46734707':{'en': 'MOBIWEB LTD'},
'46734708':{'en': 'MOBIWEB LTD'},
'46734709':{'en': 'MOBIWEB LTD'},
'4673471':{'en': 'Telenor Sverige'},
'4673472':{'en': 'Telenor Sverige'},
'46734731':{'en': 'MERCURY INTERNATIONA'},
'46734732':{'en': 'MERCURY INTERNATIONA'},
'46734733':{'en': 'MERCURY INTERNATIONA'},
'46734734':{'en': 'MERCURY INTERNATIONA'},
'46734735':{'en': 'MERCURY INTERNATIONA'},
'46734736':{'en': 'MERCURY INTERNATIONA'},
'46734737':{'en': 'MERCURY INTERNATIONA'},
'46734738':{'en': 'MERCURY INTERNATIONA'},
'46734739':{'en': 'MERCURY INTERNATIONA'},
'46734740':{'en': 'Gotalandsnatet'},
'46734741':{'en': 'Soatso AB'},
'46734743':{'en': 'Soatso AB'},
'46734744':{'en': 'Soatso AB'},
'46734745':{'en': 'Beepsend'},
'46734747':{'en': 'Telavox AB'},
'4673475':{'en': 'Lycamobile Sweden'},
'4673476':{'en': 'Lycamobile Sweden'},
'4673477':{'en': 'Lycamobile Sweden'},
'4673478':{'en': 'Lycamobile Sweden'},
'4673479':{'en': 'Lycamobile Sweden'},
'467348':{'en': 'Lycamobile Sweden'},
'467349':{'en': 'Lycamobile Sweden'},
'467350':{'en': 'HI3G Access'},
'467351':{'en': 'HI3G Access'},
'467352':{'en': 'HI3G Access'},
'467353':{'en': 'HI3G Access'},
'467354':{'en': 'HI3G Access'},
'467355':{'en': 'Tele2 Sverige'},
'467356':{'en': 'Tele2 Sverige'},
'467357':{'en': 'Tele2 Sverige'},
'467358':{'en': 'Tele2 Sverige'},
'467359':{'en': 'Tele2 Sverige'},
'46736':{'en': 'Tele2 Sverige'},
'46737':{'en': 'Tele2 Sverige'},
'467380':{'en': 'TeliaSonera'},
'467381':{'en': 'TeliaSonera'},
'467382':{'en': 'TeliaSonera'},
'467383':{'en': 'TeliaSonera'},
'467384':{'en': 'TeliaSonera'},
'467385':{'en': 'Telenor Sverige'},
'4673860':{'en': 'Telenor Sverige'},
'4673861':{'en': 'Telenor Sverige'},
'4673862':{'en': 'Telenor Sverige'},
'46738631':{'en': 'Beepsend'},
'46738632':{'en': 'Beepsend'},
'46738634':{'en': 'MERCURY INTERNATIONA'},
'46738635':{'en': 'MERCURY INTERNATIONA'},
'46738636':{'en': 'MERCURY INTERNATIONA'},
'46738637':{'en': 'MERCURY INTERNATIONA'},
'46738638':{'en': 'MERCURY INTERNATIONA'},
'46738639':{'en': 'MERCURY INTERNATIONA'},
'46738640':{'en': 'EU Tel AB'},
'46738641':{'en': 'iCentrex Sweden AB'},
'46738642':{'en': '42 Telecom AB'},
'46738643':{'en': 'Beepsend'},
'46738644':{'en': 'Beepsend'},
'46738645':{'en': 'Beepsend'},
'46738647':{'en': 'EU Tel AB'},
'46738651':{'en': 'MERCURY INTERNATIONA'},
'46738652':{'en': 'MERCURY INTERNATIONA'},
'46738653':{'en': 'MERCURY INTERNATIONA'},
'46738654':{'en': 'MERCURY INTERNATIONA'},
'46738655':{'en': 'MERCURY INTERNATIONA'},
'46738656':{'en': 'MERCURY INTERNATIONA'},
'46738657':{'en': 'MERCURY INTERNATIONA'},
'46738658':{'en': 'MERCURY INTERNATIONA'},
'46738659':{'en': 'MERCURY INTERNATIONA'},
'4673866':{'en': 'Tele2 Sverige'},
'4673867':{'en': 'Tele2 Sverige'},
'4673868':{'en': 'Tele2 Sverige'},
'46738691':{'en': 'MERCURY INTERNATIONA'},
'46738692':{'en': 'MERCURY INTERNATIONA'},
'46738693':{'en': 'MERCURY INTERNATIONA'},
'46738694':{'en': 'MERCURY INTERNATIONA'},
'46738695':{'en': 'MERCURY INTERNATIONA'},
'46738696':{'en': 'MERCURY INTERNATIONA'},
'46738697':{'en': 'MERCURY INTERNATIONA'},
'46738698':{'en': 'MERCURY INTERNATIONA'},
'46738699':{'en': 'MERCURY INTERNATIONA'},
'467387':{'en': 'Tele2 Sverige'},
'467388':{'en': 'Telenor Sverige'},
'467389':{'en': 'Tele2 Sverige'},
'46739':{'en': 'Tele2 Sverige'},
'467600':{'en': 'HI3G Access'},
'467601':{'en': 'HI3G Access'},
'467602':{'en': 'HI3G Access'},
'467603':{'en': 'HI3G Access'},
'467604':{'en': 'HI3G Access'},
'467605':{'en': 'Tele2 Sverige'},
'467606':{'en': 'Tele2 Sverige'},
'467607':{'en': 'Tele2 Sverige'},
'467608':{'en': 'Tele2 Sverige'},
'467609':{'en': 'Tele2 Sverige'},
'467610':{'en': 'TeliaSonera'},
'467611':{'en': 'TeliaSonera'},
'467612':{'en': 'TeliaSonera'},
'467613':{'en': 'TeliaSonera'},
'467614':{'en': 'TeliaSonera'},
'467615':{'en': 'Lycamobile Sweden'},
'467616':{'en': 'HI3G Access'},
'467617':{'en': 'HI3G Access'},
'467618':{'en': 'HI3G Access'},
'467619':{'en': 'HI3G Access'},
'46762':{'en': 'Tele2 Sverige'},
'46763':{'en': 'HI3G Access'},
'467635':{'en': 'Telenor Sverige'},
'467636':{'en': 'Telenor Sverige'},
'467637':{'en': 'Telenor Sverige'},
'467638':{'en': 'Easy Telecom AB (BILDNINGSAGENTEN 559)'},
'467640':{'en': 'Tele2 Sverige'},
'467641':{'en': 'Tele2 Sverige'},
'467642':{'en': 'Tele2 Sverige'},
'467643':{'en': 'Lycamobile Sweden'},
'467644':{'en': 'Lycamobile Sweden'},
'467645':{'en': 'Lycamobile Sweden'},
'4676460':{'en': 'Lycamobile Sweden'},
'4676461':{'en': 'Lycamobile Sweden'},
'4676462':{'en': 'Lycamobile Sweden'},
'4676463':{'en': 'Lycamobile Sweden'},
'4676464':{'en': 'Lycamobile Sweden'},
'46764651':{'en': 'EU Tel AB'},
'46764652':{'en': 'MERCURY INTERNATIONA'},
'46764653':{'en': 'MERCURY INTERNATIONA'},
'46764654':{'en': 'MERCURY INTERNATIONA'},
'46764655':{'en': 'MERCURY INTERNATIONA'},
'46764656':{'en': 'MERCURY INTERNATIONA'},
'46764657':{'en': 'MERCURY INTERNATIONA'},
'46764658':{'en': 'MERCURY INTERNATIONA'},
'46764659':{'en': 'MERCURY INTERNATIONA'},
'4676466':{'en': 'Gotalandsnatet'},
'4676467':{'en': 'MERCURY INTERNATIONA'},
'4676468':{'en': 'MERCURY INTERNATIONA'},
'4676469':{'en': 'MERCURY INTERNATIONA'},
'467647':{'en': 'Tele2 Sverige'},
'4676478':{'en': 'WIFOG AB'},
'4676479':{'en': 'Beepsend'},
'467648':{'en': 'GLOBETOUCH AB'},
'46764901':{'en': 'MERCURY INTERNATIONA'},
'46764902':{'en': 'MERCURY INTERNATIONA'},
'46764903':{'en': 'MERCURY INTERNATIONA'},
'46764904':{'en': 'MERCURY INTERNATIONA'},
'46764905':{'en': 'MERCURY INTERNATIONA'},
'46764906':{'en': 'MERCURY INTERNATIONA'},
'46764907':{'en': 'MERCURY INTERNATIONA'},
'46764908':{'en': 'MERCURY INTERNATIONA'},
'46764909':{'en': 'MERCURY INTERNATIONA'},
'4676492':{'en': 'Telavox AB'},
'46764940':{'en': 'Tele2 Sverige'},
'46764942':{'en': 'IPIFY LIMITED'},
'46764943':{'en': 'IPIFY LIMITED'},
'46764944':{'en': 'IPIFY LIMITED'},
'46764945':{'en': 'IPIFY LIMITED'},
'46764946':{'en': 'IPIFY LIMITED'},
'46764947':{'en': 'IPIFY LIMITED'},
'46764948':{'en': 'IPIFY LIMITED'},
'46764949':{'en': 'IPIFY LIMITED'},
'4676495':{'en': 'Tele2 Sverige'},
'4676496':{'en': 'Tele2 Sverige'},
'46764981':{'en': 'MERCURY INTERNATIONA'},
'46764982':{'en': 'MERCURY INTERNATIONA'},
'46764983':{'en': 'MERCURY INTERNATIONA'},
'46764984':{'en': 'MERCURY INTERNATIONA'},
'46764985':{'en': 'MERCURY INTERNATIONA'},
'46764986':{'en': 'MERCURY INTERNATIONA'},
'46764987':{'en': 'MERCURY INTERNATIONA'},
'46764988':{'en': 'MERCURY INTERNATIONA'},
'46764989':{'en': 'MERCURY INTERNATIONA'},
'46764990':{'en': 'Gotalandsnatet'},
'46764991':{'en': 'MERCURY INTERNATIONA'},
'46764992':{'en': 'MERCURY INTERNATIONA'},
'46764993':{'en': 'MERCURY INTERNATIONA'},
'46764994':{'en': 'MERCURY INTERNATIONA'},
'46764995':{'en': 'MERCURY INTERNATIONA'},
'46764996':{'en': 'MERCURY INTERNATIONA'},
'46764997':{'en': 'MERCURY INTERNATIONA'},
'46764998':{'en': 'MERCURY INTERNATIONA'},
'46765':{'en': 'Tele2 Sverige'},
'467660':{'en': 'Telenor Sverige'},
'467661':{'en': 'Telenor Sverige'},
'467662':{'en': 'Telenor Sverige'},
'467663':{'en': 'Telenor Sverige'},
'467664':{'en': 'Telenor Sverige'},
'467665':{'en': 'Tele2 Sverige'},
'4676660':{'en': 'NETETT SVERIGE AB (AINMT Sverige)'},
'4676661':{'en': 'NETETT SVERIGE AB (AINMT Sverige)'},
'4676662':{'en': 'NETETT SVERIGE AB (AINMT Sverige)'},
'4676663':{'en': 'NETETT SVERIGE AB (AINMT Sverige)'},
'4676664':{'en': 'NETETT SVERIGE AB (AINMT Sverige)'},
'4676665':{'en': 'NETETT SVERIGE AB (AINMT Sverige)'},
'4676666':{'en': u('\u00d6RETEL AB')},
'4676667':{'en': 'Unicorn Telecom'},
'4676668':{'en': 'MERCURY INTERNATIONA'},
'46766696':{'en': 'Telavox AB'},
'46766697':{'en': 'Telavox AB'},
'46766698':{'en': 'Telavox AB'},
'4676670':{'en': 'Svea Billing System'},
'4676671':{'en': 'Svea Billing System'},
'4676672':{'en': 'Svea Billing System'},
'4676673':{'en': 'Svea Billing System'},
'4676674':{'en': 'Svea Billing System'},
'46766750':{'en': '42 Telecom AB'},
'46766753':{'en': 'Beepsend'},
'46766754':{'en': 'Beepsend'},
'46766760':{'en': 'Voice Integrate'},
'4676677':{'en': 'Telavox AB'},
'4676678':{'en': 'SWEDFONENET AB'},
'46766791':{'en': 'Beepsend'},
'46766798':{'en': 'Beepsend'},
'46766799':{'en': '42 Telecom AB'},
'467668':{'en': 'Tele2 Sverige'},
'46766901':{'en': 'MERCURY INTERNATIONA'},
'46766902':{'en': 'MERCURY INTERNATIONA'},
'46766903':{'en': 'MERCURY INTERNATIONA'},
'46766904':{'en': 'MERCURY INTERNATIONA'},
'46766905':{'en': 'MERCURY INTERNATIONA'},
'46766906':{'en': 'MERCURY INTERNATIONA'},
'46766907':{'en': 'MERCURY INTERNATIONA'},
'46766908':{'en': 'MERCURY INTERNATIONA'},
'46766909':{'en': 'MERCURY INTERNATIONA'},
'46766911':{'en': 'MERCURY INTERNATIONA'},
'46766912':{'en': 'MERCURY INTERNATIONA'},
'46766913':{'en': 'MERCURY INTERNATIONA'},
'46766914':{'en': 'MERCURY INTERNATIONA'},
'46766915':{'en': 'MERCURY INTERNATIONA'},
'46766916':{'en': 'MERCURY INTERNATIONA'},
'46766917':{'en': 'MERCURY INTERNATIONA'},
'46766918':{'en': 'MERCURY INTERNATIONA'},
'46766919':{'en': 'MERCURY INTERNATIONA'},
'4676692':{'en': 'Voxbone'},
'46766930':{'en': 'MERCURY INTERNATIONA'},
'46766931':{'en': 'Beepsend'},
'46766932':{'en': 'IPIFY LIMITED'},
'46766933':{'en': 'Connectel AB'},
'46766934':{'en': 'IPIFY LIMITED'},
'46766935':{'en': 'Beepsend'},
'46766936':{'en': 'IPIFY LIMITED'},
'46766937':{'en': 'IPIFY LIMITED'},
'46766938':{'en': 'IPIFY LIMITED'},
'4676694':{'en': '42 Telecom AB'},
'4676695':{'en': 'Tele2 Sverige'},
'4676696':{'en': 'Tele2 Sverige'},
'4676697':{'en': 'Tele2 Sverige'},
'4676698':{'en': 'Tele2 Sverige'},
'4676699':{'en': 'Tele2 Sverige'},
'467670':{'en': 'Tele2 Sverige'},
'467671':{'en': 'Tele2 Sverige'},
'4676720':{'en': 'Tele2 Sverige'},
'4676721':{'en': 'Tele2 Sverige'},
'4676722':{'en': 'Tele2 Sverige'},
'4676723':{'en': 'Tele2 Sverige'},
'4676724':{'en': 'Tele2 Sverige'},
'4676725':{'en': 'Tele2 Sverige'},
'46767260':{'en': 'EU Tel AB'},
'46767261':{'en': 'Beepsend'},
'46767262':{'en': 'Beepsend'},
'46767265':{'en': 'HORISEN AG'},
'46767266':{'en': 'Beepsend'},
'46767268':{'en': 'Rebtel Networks'},
'4676727':{'en': 'Telenor Sverige'},
'467674':{'en': 'Lycamobile Sweden'},
'467675':{'en': 'Lycamobile Sweden'},
'467676':{'en': 'TeliaSonera'},
'467677':{'en': 'TeliaSonera'},
'467678':{'en': 'TeliaSonera'},
'467679':{'en': 'TeliaSonera'},
'467680':{'en': 'TeliaSonera'},
'467681':{'en': 'TeliaSonera'},
'467682':{'en': 'TeliaSonera'},
'467683':{'en': 'TeliaSonera'},
'467684':{'en': 'TeliaSonera'},
'467685':{'en': 'Telenor Sverige'},
'467686':{'en': 'Telenor Sverige'},
'467687':{'en': 'Telenor Sverige'},
'467688':{'en': 'Telenor Sverige'},
'467689':{'en': 'Telenor Sverige'},
'467690':{'en': 'Tele2 Sverige'},
'467691':{'en': 'Tele2 Sverige'},
'467692':{'en': 'Tele2 Sverige'},
'467693':{'en': 'Tele2 Sverige'},
'467694':{'en': 'Tele2 Sverige'},
'467695':{'en': 'Lycamobile Sweden'},
'467696':{'en': 'Lycamobile Sweden'},
'467697':{'en': 'Lycamobile Sweden'},
'467698':{'en': 'TeliaSonera'},
'467699':{'en': 'TeliaSonera'},
'4679000':{'en': '0700 LTD'},
'4679001':{'en': 'EU Tel AB'},
'4679002':{'en': '0700 LTD'},
'4679003':{'en': '0700 LTD'},
'4679004':{'en': '0700 LTD'},
'46790050':{'en': 'Telenor Sverige'},
'46790051':{'en': 'Telenor Sverige'},
'46790052':{'en': 'Telenor Sverige'},
'46790053':{'en': 'Telenor Sverige'},
'46790054':{'en': 'Telenor Sverige'},
'46790055':{'en': 'Telenor Sverige'},
'46790056':{'en': 'Telenor Sverige'},
'46790057':{'en': 'Telenor Sverige'},
'4679006':{'en': 'Telavox AB'},
'4679007':{'en': 'FONIA AB'},
'4679008':{'en': 'Voice Integrate'},
'4679009':{'en': 'BIZTELCO SVERIGE AB'},
'467901':{'en': 'Tele2 Sverige'},
'467902':{'en': 'Tele2 Sverige'},
'467903':{'en': 'Tele2 Sverige'},
'467904':{'en': 'Tele2 Sverige'},
'467905':{'en': 'Tele2 Sverige'},
'467906':{'en': 'Tele2 Sverige'},
'467907':{'en': 'Tele2 Sverige'},
'467908':{'en': 'Tele2 Sverige'},
'467909':{'en': 'Tele2 Sverige'},
'467910':{'en': 'TELL ESS AB'},
'467930':{'en': 'HI3G Access'},
'467931':{'en': 'HI3G Access'},
'467932':{'en': 'HI3G Access'},
'467933':{'en': 'HI3G Access'},
'467934':{'en': 'HI3G Access'},
'467950':{'en': 'JUNYVERSE AB'},
'467951':{'en': 'JUNYVERSE AB'},
'467952':{'en': 'JUNYVERSE AB'},
'467953':{'en': 'JUNYVERSE AB'},
'467954':{'en': 'JUNYVERSE AB'},
'4679580':{'en': 'Borderlight'},
'4679581':{'en': 'Borderlight'},
'4679585':{'en': 'Telavox AB'},
'467997':{'en': 'Telenor Sverige'},
'47400':{'en': 'telenor norge'},
'474000':{'en': 'telia'},
'474001':{'en': 'telia'},
'474002':{'en': 'telia'},
'474003':{'en': 'telia'},
'47401':{'en': 'telenor norge'},
'474010':{'en': 'telia'},
'474011':{'en': 'telia'},
'474014':{'en': 'nextgentel'},
'474020':{'en': 'telia'},
'474021':{'en': 'telia'},
'474022':{'en': 'telenor norge'},
'474023':{'en': 'telia'},
'474024':{'en': 'telia'},
'474025':{'en': 'sierra wireless'},
'474026':{'en': 'sierra wireless'},
'474027':{'en': 'sierra wireless'},
'474028':{'en': 'telenor norge'},
'474029':{'en': 'telia'},
'47403':{'en': 'telia'},
'474035':{'en': 'sierra wireless'},
'474036':{'en': 'sierra wireless'},
'474037':{'en': 'sierra wireless'},
'47404':{'en': 'telia'},
'47405':{'en': 'telia'},
'474060':{'en': 'telia'},
'474061':{'en': 'telia'},
'474062':{'en': 'telia'},
'474063':{'en': 'telia'},
'474064':{'en': 'telia'},
'474065':{'en': 'telia telecom solution'},
'474067':{'en': 'nextgentel'},
'474068':{'en': 'telenor norge'},
'474069':{'en': 'telenor norge'},
'47407':{'en': 'telia'},
'47408':{'en': 'telenor norge'},
'474080':{'en': 'telia telecom solution'},
'474081':{'en': 'telia telecom solution'},
'4740820':{'en': 'telia telecom solution'},
'4740821':{'en': 'telia telecom solution'},
'4740822':{'en': 'telia telecom solution'},
'4740823':{'en': 'telia telecom solution'},
'4740824':{'en': 'telia telecom solution'},
'47409':{'en': 'lyca mobile'},
'474090':{'en': 'telia telecom solution'},
'474091':{'en': 'telia telecom solution'},
'4740920':{'en': 'telia telecom solution'},
'4740921':{'en': 'telia telecom solution'},
'4740922':{'en': 'telia telecom solution'},
'4740923':{'en': 'telia telecom solution'},
'4740924':{'en': 'telia telecom solution'},
'4740925':{'en': 'telenor norge'},
'4740926':{'en': 'telenor norge'},
'4740927':{'en': 'telenor norge'},
'4740928':{'en': 'telenor norge'},
'4740929':{'en': 'telenor norge'},
'474093':{'en': 'telenor norge'},
'4741':{'en': 'telenor norge'},
'474100':{'en': 'telia'},
'474101':{'en': 'telia'},
'474104':{'en': 'telia'},
'474106':{'en': 'telia'},
'474107':{'en': 'telia'},
'474110':{'en': 'telia'},
'474111':{'en': 'chilimobil'},
'474112':{'en': 'chilimobil'},
'474113':{'en': 'chilimobil'},
'474114':{'en': 'telia'},
'474115':{'en': 'chilimobil'},
'474116':{'en': 'chilimobil'},
'474117':{'en': 'telia'},
'474118':{'en': 'telia'},
'474119':{'en': 'telia'},
'47412':{'en': 'telia'},
'47413':{'en': 'telia'},
'4745':{'en': 'telia'},
'47453':{'en': 'telenor norge'},
'474536':{'en': 'nkom (nasjonal kommunikasjonsmyndighet)'},
'474537':{'en': 'erate'},
'474538':{'en': 'erate'},
'47455':{'en': 'lyca mobile'},
'47458':{'en': 'telenor norge'},
'474590':{'en': 'telenor norge'},
'474592':{'en': 'lyca mobile'},
'474595':{'en': 'telenor norge'},
'474596':{'en': 'telenor norge'},
'474598':{'en': 'telenor norge'},
'474599':{'en': 'telenor norge'},
'47460':{'en': 'telenor norge'},
'47461':{'en': 'chilimobil'},
'474610':{'en': 'telenor norge'},
'474617':{'en': 'telenor norge'},
'474618':{'en': 'telenor norge'},
'474619':{'en': 'telenor norge'},
'47462':{'en': 'telia'},
'474620':{'en': 'telenor norge'},
'474628':{'en': 'erate'},
'474629':{'en': 'erate'},
'47463':{'en': 'telia'},
'47464':{'en': 'NetCom'},
'474650':{'en': 'telia'},
'474651':{'en': 'ice norge'},
'474652':{'en': 'ice norge'},
'474653':{'en': 'ice norge'},
'474654':{'en': 'telia'},
'474655':{'en': 'telia'},
'474656':{'en': 'telia'},
'474657':{'en': 'telia'},
'474658':{'en': 'telia'},
'474659':{'en': 'telia'},
'47466':{'en': 'telia'},
'474666':{'en': 'telenor norge'},
'474667':{'en': 'telenor norge'},
'474670':{'en': 'telia'},
'474671':{'en': 'lyca mobile'},
'474672':{'en': 'lyca mobile'},
'474674':{'en': 'telia'},
'474675':{'en': 'telia'},
'474676':{'en': 'telia'},
'474677':{'en': 'telia'},
'474678':{'en': 'telia'},
'474679':{'en': 'telia'},
'47468':{'en': 'telenor norge'},
'474690':{'en': 'telenor norge'},
'474691':{'en': 'telenor norge'},
'474692':{'en': 'telenor norge'},
'474693':{'en': 'telenor norge'},
'474694':{'en': 'telenor norge'},
'474695':{'en': 'telenor norge'},
'474696':{'en': 'telenor norge'},
'474697':{'en': 'telia'},
'474698':{'en': 'telenor norge'},
'47470':{'en': 'telenor norge'},
'474710':{'en': 'telenor norge'},
'474711':{'en': 'telenor norge'},
'474712':{'en': 'telenor norge'},
'474713':{'en': 'telia'},
'474714':{'en': 'telia'},
'474715':{'en': 'telia'},
'474716':{'en': 'telia'},
'474717':{'en': 'telia'},
'474718':{'en': 'chilimobil'},
'474719':{'en': 'chilimobil'},
'47472':{'en': 'telia'},
'47473':{'en': 'telia'},
'47474':{'en': 'telia'},
'474740':{'en': 'telenor norge'},
'474741':{'en': 'telenor norge'},
'474742':{'en': 'telenor norge'},
'474743':{'en': 'telenor norge'},
'47475':{'en': 'altibox'},
'474750':{'en': 'telenor norge'},
'474751':{'en': 'telenor norge'},
'47476':{'en': 'telenor norge'},
'474769':{'en': 'telia'},
'47477':{'en': 'telia'},
'474770':{'en': 'telenor norge'},
'474771':{'en': 'telenor norge'},
'474775':{'en': 'telenor norge'},
'474776':{'en': 'telenor norge'},
'47478':{'en': 'telenor norge'},
'47479':{'en': 'telia'},
'474790':{'en': 'telenor norge'},
'474798':{'en': 'telenor norge'},
'474799':{'en': 'telenor norge'},
'47480':{'en': 'telenor norge'},
'47481':{'en': 'telenor norge'},
'47482':{'en': 'telenor norge'},
'474830':{'en': 'telenor norge'},
'474831':{'en': 'telenor norge'},
'474832':{'en': 'telenor norge'},
'474833':{'en': 'telia'},
'474834':{'en': 'telia'},
'474835':{'en': 'telia'},
'474836':{'en': 'telia'},
'474838':{'en': 'ice norge'},
'474839':{'en': 'ice norge'},
'47484':{'en': 'telia'},
'474841':{'en': 'telenor norge'},
'474842':{'en': 'telenor norge'},
'474848':{'en': 'erate'},
'474849':{'en': 'erate'},
'474850':{'en': 'telia'},
'474851':{'en': 'nextgentel'},
'474858':{'en': 'telenor norge'},
'474859':{'en': 'erate'},
'474860':{'en': 'telia'},
'474861':{'en': 'telia'},
'474862':{'en': 'telia'},
'474863':{'en': 'telia'},
'474864':{'en': 'telia'},
'474865':{'en': 'telia'},
'474866':{'en': 'telia'},
'474867':{'en': 'telia'},
'474868':{'en': 'telia'},
'474884':{'en': 'telenor norge'},
'474885':{'en': 'telenor norge'},
'474886':{'en': 'telia'},
'474888':{'en': 'telia'},
'474889':{'en': 'telia'},
'474890':{'en': 'telenor norge'},
'474891':{'en': 'telenor norge'},
'474892':{'en': 'telenor norge'},
'474893':{'en': 'telia'},
'474894':{'en': 'telenor norge'},
'474895':{'en': 'telia'},
'474896':{'en': 'telenor norge'},
'474898':{'en': 'telenor norge'},
'474899':{'en': 'telia'},
'47591':{'en': 'telenor norge'},
'4790':{'en': 'telenor norge'},
'479042':{'en': 'svea billing services'},
'479043':{'en': 'svea billing services'},
'479044':{'en': 'svea billing services'},
'479048':{'en': 'telavox'},
'479049':{'en': 'telavox'},
'4791':{'en': 'telenor norge'},
'479120':{'en': 'chilimobil'},
'479121':{'en': 'chilimobil'},
'479122':{'en': 'chilimobil'},
'479123':{'en': 'chilimobil'},
'479125':{'en': 'lyca mobile'},
'479126':{'en': 'lyca mobile'},
'479127':{'en': 'lyca mobile'},
'479128':{'en': 'lyca mobile'},
'479129':{'en': 'lyca mobile'},
'4792':{'en': 'telia'},
'479218':{'en': 'telenor norge'},
'479219':{'en': 'telenor norge'},
'479236':{'en': 'telenor norge'},
'479238':{'en': 'telenor norge'},
'479239':{'en': 'telenor norge'},
'479258':{'en': 'telenor norge'},
'479259':{'en': 'telenor norge'},
'47927':{'en': 'telenor norge'},
'47929':{'en': 'telenor norge'},
'47930':{'en': 'telia'},
'479310':{'en': 'telenor norge'},
'479311':{'en': 'telenor norge'},
'479312':{'en': 'telenor norge'},
'479313':{'en': 'telenor norge'},
'479314':{'en': 'telenor norge'},
'479315':{'en': 'telenor norge'},
'479316':{'en': 'telenor norge'},
'479318':{'en': 'telenor norge'},
'479319':{'en': 'telenor norge'},
'47932':{'en': 'telia'},
'479330':{'en': 'telenor norge'},
'479331':{'en': 'telenor norge'},
'479332':{'en': 'telenor norge'},
'479333':{'en': 'telenor norge'},
'479334':{'en': 'telenor norge'},
'479335':{'en': 'telenor norge'},
'479336':{'en': 'telenor norge'},
'479337':{'en': 'telia'},
'479338':{'en': 'telenor norge'},
'479339':{'en': 'telenor norge'},
'47934':{'en': 'telia'},
'479350':{'en': 'telenor norge'},
'479351':{'en': 'telenor norge'},
'479352':{'en': 'telenor norge'},
'479353':{'en': 'telenor norge'},
'479354':{'en': 'telenor norge'},
'479355':{'en': 'telenor norge'},
'479356':{'en': 'telenor norge'},
'479357':{'en': 'telia'},
'479358':{'en': 'telenor norge'},
'479359':{'en': 'telenor norge'},
'47936':{'en': 'telia'},
'479370':{'en': 'telenor norge'},
'479371':{'en': 'telenor norge'},
'479372':{'en': 'telenor norge'},
'479373':{'en': 'telenor norge'},
'479374':{'en': 'telenor norge'},
'479375':{'en': 'telenor norge'},
'479376':{'en': 'telenor norge'},
'479377':{'en': 'telia'},
'479378':{'en': 'telenor norge'},
'479379':{'en': 'telenor norge'},
'47938':{'en': 'telia'},
'47939':{'en': 'telia'},
'479390':{'en': 'telenor norge'},
'479400':{'en': 'telia'},
'479401':{'en': 'telia'},
'479402':{'en': 'telia'},
'479403':{'en': 'telenor norge'},
'479404':{'en': 'com4'},
'479405':{'en': 'telenor norge'},
'479406':{'en': 'telenor norge'},
'479407':{'en': 'telenor norge'},
'479408':{'en': 'ice norge'},
'479409':{'en': 'ice norge'},
'47941':{'en': 'telenor norge'},
'479410':{'en': 'telia'},
'479411':{'en': 'telia'},
'479412':{'en': 'telia'},
'47942':{'en': 'telia'},
'47943':{'en': 'telenor norge'},
'479440':{'en': 'telenor norge'},
'479441':{'en': 'telenor norge'},
'479442':{'en': 'telia'},
'479443':{'en': 'telia'},
'479444':{'en': 'telenor norge'},
'479445':{'en': 'telenor norge'},
'479446':{'en': 'telenor norge'},
'479447':{'en': 'telia'},
'479448':{'en': 'telia'},
'479449':{'en': 'telia'},
'479450':{'en': 'telia telecom solution'},
'479451':{'en': 'telia telecom solution'},
'479452':{'en': 'telia telecom solution'},
'479453':{'en': 'telia telecom solution'},
'479454':{'en': 'telia telecom solution'},
'479471':{'en': 'lyca mobile'},
'479472':{'en': 'lyca mobile'},
'479473':{'en': 'lyca mobile'},
'479474':{'en': 'telenor norge'},
'479475':{'en': 'telenor norge'},
'479476':{'en': 'telenor norge'},
'479477':{'en': 'telenor norge'},
'479478':{'en': 'telenor norge'},
'479479':{'en': 'telenor norge'},
'47948':{'en': 'telenor norge'},
'47949':{'en': 'telenor norge'},
'479499':{'en': 'telia'},
'4795':{'en': 'telenor norge'},
'479600':{'en': 'phonect'},
'479601':{'en': 'telenor norge'},
'479604':{'en': 'telenor norge'},
'479609':{'en': 'telenor norge'},
'47961':{'en': 'telenor norge'},
'47962':{'en': 'telenor norge'},
'47965':{'en': 'telenor norge'},
'479660':{'en': 'erate'},
'479661':{'en': 'erate'},
'479662':{'en': 'erate'},
'479663':{'en': 'erate'},
'479664':{'en': 'erate'},
'479665':{'en': 'telia'},
'479666':{'en': 'telia'},
'479667':{'en': 'telia'},
'479668':{'en': 'telia'},
'479669':{'en': 'telia'},
'479670':{'en': 'telia'},
'479671':{'en': 'telia'},
'479672':{'en': 'telia'},
'479673':{'en': 'telia'},
'479674':{'en': 'telia'},
'479675':{'en': 'telia'},
'479679':{'en': 'telenor norge'},
'47968':{'en': 'telia'},
'479689':{'en': 'telenor norge'},
'479690':{'en': 'erate'},
'479691':{'en': 'erate'},
'479692':{'en': 'erate'},
'479693':{'en': 'telenor norge'},
'479694':{'en': 'telia'},
'479695':{'en': 'lyca mobile'},
'479696':{'en': 'lyca mobile'},
'479697':{'en': 'lyca mobile'},
'479698':{'en': 'lyca mobile'},
'479699':{'en': 'lyca mobile'},
'4797':{'en': 'telenor norge'},
'479730':{'en': 'ice norge'},
'479731':{'en': 'ice norge'},
'479735':{'en': 'lyca mobile'},
'479736':{'en': 'lyca mobile'},
'479737':{'en': 'lyca mobile'},
'479738':{'en': 'lyca mobile'},
'479739':{'en': 'lyca mobile'},
'47978':{'en': 'telia'},
'479790':{'en': 'telia'},
'479791':{'en': 'telia'},
'479792':{'en': 'telia'},
'479793':{'en': 'telia'},
'479794':{'en': 'telia'},
'47980':{'en': 'telia'},
'47981':{'en': 'telia'},
'47982':{'en': 'telia'},
'47983':{'en': 'telia'},
'479838':{'en': 'telenor norge'},
'479839':{'en': 'telenor norge'},
'47984':{'en': 'telia'},
'47985':{'en': 'telenor norge'},
'479854':{'en': 'telia'},
'47986':{'en': 'telia'},
'479870':{'en': 'kvantel'},
'479876':{'en': 'telia'},
'479877':{'en': 'chilimobil'},
'47988':{'en': 'telia'},
'47989':{'en': 'telenor norge'},
'479890':{'en': 'telia'},
'479899':{'en': 'telia'},
'47990':{'en': 'telenor norge'},
'479908':{'en': 'telia'},
'479909':{'en': 'telia'},
'47991':{'en': 'telenor norge'},
'47992':{'en': 'telenor norge'},
'47993':{'en': 'telenor norge'},
'47994':{'en': 'telenor norge'},
'47995':{'en': 'telenor norge'},
'47996':{'en': 'telenor norge'},
'479967':{'en': 'telia'},
'479968':{'en': 'telia'},
'47997':{'en': 'telenor norge'},
'479980':{'en': 'telenor norge'},
'479981':{'en': 'telenor norge'},
'479982':{'en': 'telenor norge'},
'479983':{'en': 'telenor norge'},
'479984':{'en': 'telenor norge'},
'479985':{'en': 'telia'},
'479986':{'en': 'telia'},
'479987':{'en': 'telia'},
'479988':{'en': 'telia'},
'479989':{'en': 'telia'},
'4845':{'en': 'Rezerwa Prezesa UKE'},
'48450':{'en': 'Play'},
'484590':{'en': 'Play'},
'4845910':{'en': 'Play'},
'4845911':{'en': 'Play'},
'4845912':{'en': 'Play'},
'4845913':{'en': 'Play'},
'4845914':{'en': 'Play'},
'4845920':{'en': 'SIA Ntel Solutions'},
'484593':{'en': 'Play'},
'4845945':{'en': 'Plus'},
'484595':{'en': 'Plus'},
'4845950':{'en': 'SIA Ntel Solutions'},
'4845957':{'en': 'BSG ESTONIA OU'},
'4845958':{'en': 'TELESTRADA S.A.'},
'4845959':{'en': 'TELESTRADA S.A.'},
'484598':{'en': 'Plus'},
'4850':{'en': 'Orange'},
'4851':{'en': 'Orange'},
'4853':{'en': 'Play'},
'48532':{'en': 'T-Mobile'},
'485366':{'en': 'Plus'},
'48538':{'en': 'T-Mobile'},
'48539':{'en': 'T-Mobile'},
'4857':{'en': 'Play'},
'48571':{'en': 'Orange'},
'485717':{'en': 'Rezerwa Prezesa UKE'},
'485718':{'en': 'Rezerwa Prezesa UKE'},
'485719':{'en': 'Rezerwa Prezesa UKE'},
'48572':{'en': 'Orange'},
'48573':{'en': 'Orange'},
'485735':{'en': 'Rezerwa Prezesa UKE'},
'485736':{'en': 'Rezerwa Prezesa UKE'},
'485737':{'en': 'Rezerwa Prezesa UKE'},
'485738':{'en': 'Rezerwa Prezesa UKE'},
'485791':{'en': 'Plus'},
'485792':{'en': 'Plus'},
'485793':{'en': 'Plus'},
'4857941':{'en': 'Messagebird B.V.'},
'4857942':{'en': 'SIA NetBalt'},
'4857946':{'en': 'Plus'},
'4857947':{'en': 'Plus'},
'4857948':{'en': 'SIA Ntel Solutions'},
'4857949':{'en': 'Plus'},
'4857950':{'en': 'Plus'},
'4857953':{'en': 'SIA NetBalt'},
'4857958':{'en': 'NIMBUSFIVE GmbH'},
'485797':{'en': 'Plus'},
'48600':{'en': 'T-Mobile'},
'48601':{'en': 'Plus'},
'48602':{'en': 'T-Mobile'},
'48603':{'en': 'Plus'},
'48604':{'en': 'T-Mobile'},
'48605':{'en': 'Plus'},
'48606':{'en': 'T-Mobile'},
'48607':{'en': 'Plus'},
'48608':{'en': 'T-Mobile'},
'48609':{'en': 'Plus'},
'48660':{'en': 'T-Mobile'},
'48661':{'en': 'Plus'},
'48662':{'en': 'T-Mobile'},
'48663':{'en': 'Plus'},
'48664':{'en': 'T-Mobile'},
'48665':{'en': 'Plus'},
'48666':{'en': 'T-Mobile'},
'486666':{'en': 'Play'},
'48667':{'en': 'Plus'},
'48668':{'en': 'T-Mobile'},
'48669':{'en': 'Plus'},
'48690':{'en': 'Orange'},
'486900':{'en': 'Play'},
'486907':{'en': 'Play'},
'486908':{'en': 'Play'},
'486909':{'en': 'Play'},
'48691':{'en': 'Plus'},
'48692':{'en': 'T-Mobile'},
'48693':{'en': 'Plus'},
'48694':{'en': 'T-Mobile'},
'48695':{'en': 'Plus'},
'48696':{'en': 'T-Mobile'},
'48697':{'en': 'Plus'},
'48698':{'en': 'T-Mobile'},
'48699':{'en': 'Plus'},
'4869901':{'en': 'AMD Telecom S.A.'},
'4869922':{'en': 'Play'},
'4869950':{'en': 'AMD Telecom S.A.'},
'4869951':{'en': 'Mobiledata Sp. z o.o.'},
'4869952':{'en': 'Mobiledata Sp. z o.o.'},
'4869953':{'en': 'Mobiledata Sp. z o.o.'},
'4869954':{'en': 'Mobiledata Sp. z o.o.'},
'4869955':{'en': 'Mobiledata Sp. z o.o.'},
'4869956':{'en': 'Twilio Ireland Limited'},
'4869957':{'en': 'Softelnet S.A. Sp. k.'},
'4869958':{'en': 'Rezerwa Prezesa UKE'},
'4869959':{'en': 'Move Telecom S.A.'},
'4869960':{'en': 'Play'},
'4869970':{'en': 'Play'},
'4869974':{'en': 'Compatel Limited'},
'4869978':{'en': 'VOXBONE SA'},
'4869979':{'en': 'Play'},
'486998':{'en': 'Play'},
'4872':{'en': 'Plus'},
'487208':{'en': 'Play'},
'487271':{'en': 'Nordisk'},
'487272':{'en': 'T-Mobile'},
'487273':{'en': 'T-Mobile'},
'48728':{'en': 'T-Mobile'},
'487290':{'en': 'Play'},
'487291':{'en': 'Play'},
'4872970':{'en': 'AMD Telecom S.A.'},
'4872972':{'en': 'Compatel Limited'},
'4872973':{'en': 'Play'},
'4872974':{'en': 'Play'},
'4872975':{'en': 'Rezerwa Prezesa UKE'},
'4872977':{'en': 'INTERNETIA Sp. o.o.'},
'4872978':{'en': 'Play'},
'4872979':{'en': 'Play'},
'4872980':{'en': 'Play'},
'4872981':{'en': 'Play'},
'4872982':{'en': 'Play'},
'4872983':{'en': 'Rezerwa Prezesa UKE'},
'4872984':{'en': 'Rezerwa Prezesa UKE'},
'4872985':{'en': 'Rezerwa Prezesa UKE'},
'4872986':{'en': 'Rezerwa Prezesa UKE'},
'4872987':{'en': 'Premium Mobile SA'},
'4872988':{'en': 'Premium Mobile SA'},
'4872989':{'en': 'Premium Mobile SA'},
'4872990':{'en': 'TELCO LEADERS LTD'},
'48730':{'en': 'Play'},
'48731':{'en': 'Play'},
'48732':{'en': 'Play'},
'48733':{'en': 'Play'},
'48734':{'en': 'T-Mobile'},
'48735':{'en': 'T-Mobile'},
'48736':{'en': 'T-Mobile'},
'487360':{'en': 'Play'},
'487367':{'en': 'Play'},
'487368':{'en': 'Play'},
'487369':{'en': 'Play'},
'48737':{'en': 'Play'},
'487370':{'en': 'Plus'},
'487371':{'en': 'Plus'},
'487372':{'en': 'Plus'},
'48738':{'en': 'PKP Polskie Linie Kolejowe S.A.'},
'48739':{'en': 'Plus'},
'487390':{'en': 'Play'},
'487391':{'en': 'Play'},
'487392':{'en': 'Play'},
'4873930':{'en': 'Play'},
'4873990':{'en': 'Play'},
'4873991':{'en': 'AGILE TELECOM POLAND'},
'4873992':{'en': 'MobiWeb Telecom Limited'},
'4873993':{'en': 'SIA NetBalt'},
'4873997':{'en': 'Play'},
'4873998':{'en': 'Play'},
'4873999':{'en': 'Play'},
'487800':{'en': 'Orange'},
'487801':{'en': 'Orange'},
'487802':{'en': 'Play'},
'4878020':{'en': 'Plus'},
'4878025':{'en': 'Interactive Digital Media GmbH'},
'4878026':{'en': 'SIA NetBalt'},
'4878029':{'en': 'SMSHIGHWAY LIMITED'},
'487803':{'en': 'T-Mobile'},
'487804':{'en': 'Rezerwa Prezesa UKE'},
'4878040':{'en': 'Plus'},
'487805':{'en': 'Orange'},
'487806':{'en': 'Orange'},
'487807':{'en': 'Play'},
'487808':{'en': 'Play'},
'487809':{'en': 'Rezerwa Prezesa UKE'},
'48781':{'en': 'Plus'},
'48782':{'en': 'Plus'},
'48783':{'en': 'Plus'},
'48784':{'en': 'T-Mobile'},
'48785':{'en': 'Plus'},
'487860':{'en': 'Plus'},
'4878607':{'en': 'Play'},
'4878608':{'en': 'Play'},
'487861':{'en': 'Play'},
'487862':{'en': 'Play'},
'487863':{'en': 'Play'},
'487864':{'en': 'Play'},
'487865':{'en': 'Rezerwa Prezesa UKE'},
'487866':{'en': 'Rezerwa Prezesa UKE'},
'487867':{'en': 'Rezerwa Prezesa UKE'},
'4878678':{'en': 'Play'},
'487868':{'en': 'Orange'},
'487869':{'en': 'Orange'},
'48787':{'en': 'T-Mobile'},
'48788':{'en': 'T-Mobile'},
'487890':{'en': 'Orange'},
'487891':{'en': 'Orange'},
'487892':{'en': 'Orange'},
'487893':{'en': 'Orange'},
'487894':{'en': 'Orange'},
'487895':{'en': 'Plus'},
'487896':{'en': 'Plus'},
'487897':{'en': 'Plus'},
'487898':{'en': 'Plus'},
'487899':{'en': 'Plus'},
'4879':{'en': 'Play'},
'487951':{'en': 'T-Mobile'},
'487952':{'en': 'T-Mobile'},
'487953':{'en': 'T-Mobile'},
'487954':{'en': 'T-Mobile'},
'487955':{'en': 'T-Mobile'},
'48797':{'en': 'Orange'},
'48798':{'en': 'Orange'},
'487990':{'en': 'Orange'},
'487996':{'en': 'Orange'},
'48880':{'en': 'T-Mobile'},
'48881':{'en': 'Play'},
'488810':{'en': 'T-Mobile'},
'488811':{'en': 'Plus'},
'488818':{'en': 'T-Mobile'},
'488819':{'en': 'T-Mobile'},
'48882':{'en': 'T-Mobile'},
'48883':{'en': 'Play'},
'488833':{'en': 'T-Mobile'},
'488838':{'en': 'T-Mobile'},
'48884':{'en': 'Play'},
'488841':{'en': 'T-Mobile'},
'488842':{'en': 'T-Mobile'},
'488844':{'en': 'Plus'},
'488845':{'en': 'Rezerwa Prezesa UKE'},
'48885':{'en': 'Plus'},
'48886':{'en': 'T-Mobile'},
'48887':{'en': 'Plus'},
'48888':{'en': 'T-Mobile'},
'48889':{'en': 'T-Mobile'},
'4915020':{'en': 'Interactive digital media'},
'4915050':{'en': 'NAKA AG'},
'4915080':{'en': 'Easy World'},
'49151':{'en': 'T-Mobile'},
'491520':{'en': 'Vodafone'},
'491521':{'en': 'Vodafone/Lycamobile'},
'491522':{'en': 'Vodafone'},
'491523':{'en': 'Vodafone'},
'491525':{'en': 'Vodafone'},
'491526':{'en': 'Vodafone'},
'491529':{'en': 'Vodafone/Truphone'},
'4915555':{'en': 'Tismi BV'},
'4915566':{'en': 'Drillisch Online'},
'4915630':{'en': 'Multiconnect'},
'4915678':{'en': 'Argon Networks'},
'491570':{'en': 'Eplus/Telogic'},
'491573':{'en': 'Eplus'},
'491575':{'en': 'Eplus'},
'491577':{'en': 'Eplus'},
'491578':{'en': 'Eplus'},
'491579':{'en': 'Eplus/Sipgate'},
'4915888':{'en': 'TelcoVillage'},
'491590':{'en': 'O2'},
'49160':{'en': 'T-Mobile'},
'49162':{'en': 'Vodafone'},
'49163':{'en': 'Eplus'},
'49170':{'en': 'T-Mobile'},
'49171':{'en': 'T-Mobile'},
'49172':{'en': 'Vodafone'},
'49173':{'en': 'Vodafone'},
'49174':{'en': 'Vodafone'},
'49175':{'en': 'T-Mobile'},
'49176':{'en': 'O2'},
'49177':{'en': 'Eplus'},
'49178':{'en': 'Eplus'},
'49179':{'en': 'O2'},
'5005':{'en': 'Sure South Atlantic Limited'},
'5006':{'en': 'Sure South Atlantic Limited'},
'50160':{'en': 'Belize Telemedia Ltd (Digi)'},
'50161':{'en': 'Belize Telemedia Ltd (Digi)'},
'50162':{'en': 'Belize Telemedia Ltd (Digi)'},
'50163':{'en': 'Belize Telemedia Ltd (Digi)'},
'50165':{'en': 'Speednet (Smart)'},
'50166':{'en': 'Speednet (Smart)'},
'50167':{'en': 'Speednet (Smart)'},
'50230':{'en': 'Tigo'},
'50231':{'en': 'Tigo'},
'50232':{'en': 'Tigo'},
'5023229':{'en': 'Telgua'},
'50233':{'en': 'Tigo'},
'50234':{'en': 'Movistar'},
'502350':{'en': 'Movistar'},
'502351':{'en': 'Movistar'},
'502352':{'en': 'Movistar'},
'502353':{'en': 'Movistar'},
'502354':{'en': 'Movistar'},
'502355':{'en': 'Movistar'},
'502356':{'en': 'Movistar'},
'502370':{'en': 'Tigo'},
'502371':{'en': 'Tigo'},
'502372':{'en': 'Tigo'},
'502373':{'en': 'Tigo'},
'502374':{'en': 'Tigo'},
'50240':{'en': 'Tigo'},
'502400':{'en': 'Movistar'},
'50241':{'en': 'Telgua'},
'50242':{'en': 'Telgua'},
'50243':{'en': 'Movistar'},
'50244':{'en': 'Movistar'},
'5024476':{'en': 'Tigo'},
'5024477':{'en': 'Tigo'},
'5024478':{'en': 'Tigo'},
'5024479':{'en': 'Tigo'},
'502448':{'en': 'Tigo'},
'502449':{'en': 'Tigo'},
'50245':{'en': 'Tigo'},
'50246':{'en': 'Tigo'},
'50247':{'en': 'Telgua'},
'502477':{'en': 'Tigo'},
'502478':{'en': 'Tigo'},
'502479':{'en': 'Tigo'},
'50248':{'en': 'Tigo'},
'50249':{'en': 'Tigo'},
'502500':{'en': 'Tigo'},
'502501':{'en': 'Telgua'},
'502502':{'en': 'Movistar'},
'502503':{'en': 'Tigo'},
'502504':{'en': 'Tigo'},
'502505':{'en': 'Tigo'},
'502506':{'en': 'Tigo'},
'502507':{'en': 'Movistar'},
'502508':{'en': 'Movistar'},
'502509':{'en': 'Movistar'},
'502510':{'en': 'Movistar'},
'502511':{'en': 'Telgua'},
'502512':{'en': 'Telgua'},
'502513':{'en': 'Telgua'},
'502514':{'en': 'Movistar'},
'502515':{'en': 'Tigo'},
'502516':{'en': 'Tigo'},
'502517':{'en': 'Tigo'},
'502518':{'en': 'Tigo'},
'502519':{'en': 'Tigo'},
'50252':{'en': 'Movistar'},
'502520':{'en': 'Tigo'},
'50253':{'en': 'Tigo'},
'5025310':{'en': 'Telgua'},
'5025311':{'en': 'Telgua'},
'5025312':{'en': 'Movistar'},
'5025313':{'en': 'Movistar'},
'502539':{'en': 'Movistar'},
'50254':{'en': 'Telgua'},
'502540':{'en': 'Movistar'},
'502550':{'en': 'Movistar'},
'502551':{'en': 'Telgua'},
'5025518':{'en': 'Movistar'},
'5025519':{'en': 'Movistar'},
'502552':{'en': 'Tigo'},
'5025531':{'en': 'Telgua'},
'5025532':{'en': 'Telgua'},
'5025533':{'en': 'Telgua'},
'5025534':{'en': 'Telgua'},
'5025535':{'en': 'Telgua'},
'5025536':{'en': 'Telgua'},
'5025537':{'en': 'Telgua'},
'5025538':{'en': 'Telgua'},
'5025539':{'en': 'Telgua'},
'502554':{'en': 'Movistar'},
'5025543':{'en': 'Telgua'},
'5025544':{'en': 'Telgua'},
'502555':{'en': 'Telgua'},
'5025550':{'en': 'Tigo'},
'5025551':{'en': 'Tigo'},
'5025552':{'en': 'Tigo'},
'5025553':{'en': 'Tigo'},
'502556':{'en': 'Telgua'},
'502557':{'en': 'Telgua'},
'502558':{'en': 'Telgua'},
'5025580':{'en': 'Tigo'},
'5025581':{'en': 'Tigo'},
'502559':{'en': 'Telgua'},
'50256':{'en': 'Movistar'},
'502561':{'en': 'Telgua'},
'502562':{'en': 'Telgua'},
'502563':{'en': 'Telgua'},
'502569':{'en': 'Telgua'},
'50257':{'en': 'Tigo'},
'502571':{'en': 'Telgua'},
'502579':{'en': 'Movistar'},
'50258':{'en': 'Telgua'},
'502580':{'en': 'Tigo'},
'5025819':{'en': 'Tigo'},
'502588':{'en': 'Tigo'},
'502589':{'en': 'Tigo'},
'50259':{'en': 'Telgua'},
'502590':{'en': 'Tigo'},
'5025915':{'en': 'Movistar'},
'5025916':{'en': 'Movistar'},
'5025917':{'en': 'Movistar'},
'5025918':{'en': 'Tigo'},
'5025919':{'en': 'Tigo'},
'502599':{'en': 'Tigo'},
'503600':{'en': 'Tigo'},
'503601':{'en': 'Tigo'},
'503602':{'en': 'Tigo'},
'503603':{'en': 'Tigo'},
'503604':{'en': 'Tigo'},
'503605':{'en': 'Tigo'},
'503609':{'en': 'Tigo'},
'50361':{'en': 'Movistar'},
'503620':{'en': 'Digicel'},
'503630':{'en': 'Claro'},
'5036310':{'en': 'Claro'},
'5036311':{'en': 'Claro'},
'5036312':{'en': 'Claro'},
'5036313':{'en': 'Claro'},
'5036314':{'en': 'Claro'},
'5036315':{'en': 'Claro'},
'5036316':{'en': 'Claro'},
'50363170':{'en': 'Claro'},
'50363171':{'en': 'Claro'},
'50363172':{'en': 'Claro'},
'50363173':{'en': 'Claro'},
'50363174':{'en': 'Claro'},
'503642':{'en': 'Movistar'},
'5036430':{'en': 'Movistar'},
'5036431':{'en': 'Movistar'},
'5036611':{'en': 'Movistar'},
'503700':{'en': 'Claro'},
'503701':{'en': 'Claro'},
'503702':{'en': 'Claro'},
'503703':{'en': 'Claro'},
'503704':{'en': 'Claro'},
'503705':{'en': 'Claro'},
'503706':{'en': 'Claro'},
'50370700':{'en': 'Claro'},
'50370701':{'en': 'Tigo'},
'50370702':{'en': 'Movistar'},
'50370703':{'en': 'Claro'},
'50370704':{'en': 'Claro'},
'50370705':{'en': 'Claro'},
'50370706':{'en': 'Tigo'},
'50370707':{'en': 'Claro'},
'50370708':{'en': 'Movistar'},
'50370709':{'en': 'Tigo'},
'50370710':{'en': 'Claro'},
'50370711':{'en': 'Movistar'},
'50370712':{'en': 'Claro'},
'50370713':{'en': 'Tigo'},
'50370714':{'en': 'Tigo'},
'50370715':{'en': 'Tigo'},
'50370716':{'en': 'Movistar'},
'50370717':{'en': 'Claro'},
'50370719':{'en': 'Tigo'},
'5037072':{'en': 'Digicel'},
'50370730':{'en': 'Digicel'},
'50370731':{'en': 'Digicel'},
'50370732':{'en': 'Digicel'},
'50370733':{'en': 'Digicel'},
'50370734':{'en': 'Digicel'},
'50370735':{'en': 'Claro'},
'50370736':{'en': 'Claro'},
'50370737':{'en': 'Claro'},
'50370738':{'en': 'Claro'},
'50370739':{'en': 'Claro'},
'50370740':{'en': 'Claro'},
'50370741':{'en': 'Claro'},
'50370742':{'en': 'Claro'},
'50370743':{'en': 'Claro'},
'50370744':{'en': 'Claro'},
'50370745':{'en': 'Claro'},
'50370746':{'en': 'Claro'},
'503708':{'en': 'Claro'},
'503709':{'en': 'Claro'},
'50371':{'en': 'Movistar'},
'50372':{'en': 'Tigo'},
'50373':{'en': 'Digicel'},
'50374':{'en': 'Digicel'},
'503745':{'en': 'Movistar'},
'503747':{'en': 'Tigo'},
'503748':{'en': 'Tigo'},
'503749':{'en': 'Tigo'},
'50375':{'en': 'Tigo'},
'50376':{'en': 'Claro'},
'503767':{'en': 'Tigo'},
'503768':{'en': 'Tigo'},
'50376865':{'en': 'Movistar'},
'50376866':{'en': 'Movistar'},
'50376867':{'en': 'Movistar'},
'50376868':{'en': 'Movistar'},
'50376869':{'en': 'Movistar'},
'5037691':{'en': 'Movistar'},
'5037692':{'en': 'Movistar'},
'5037693':{'en': 'Movistar'},
'5037694':{'en': 'Movistar'},
'5037695':{'en': 'Digicel'},
'5037696':{'en': 'Digicel'},
'5037697':{'en': 'Digicel'},
'5037698':{'en': 'Digicel'},
'5037699':{'en': 'Movistar'},
'503770':{'en': 'Movistar'},
'503771':{'en': 'Movistar'},
'503772':{'en': 'Tigo'},
'503773':{'en': 'Tigo'},
'503774':{'en': 'Claro'},
'503775':{'en': 'Claro'},
'503776':{'en': 'Digicel'},
'503777':{'en': 'Digicel'},
'5037780':{'en': 'Movistar'},
'5037781':{'en': 'Movistar'},
'5037782':{'en': 'Movistar'},
'5037783':{'en': 'Movistar'},
'5037784':{'en': 'Movistar'},
'5037785':{'en': 'Tigo'},
'5037786':{'en': 'Tigo'},
'5037787':{'en': 'Tigo'},
'5037788':{'en': 'Tigo'},
'5037789':{'en': 'Tigo'},
'5037790':{'en': 'Movistar'},
'5037791':{'en': 'Movistar'},
'5037792':{'en': 'Movistar'},
'5037793':{'en': 'Movistar'},
'5037794':{'en': 'Movistar'},
'5037795':{'en': 'Tigo'},
'5037796':{'en': 'Tigo'},
'5037797':{'en': 'Tigo'},
'5037798':{'en': 'Tigo'},
'5037799':{'en': 'Tigo'},
'5037800':{'en': 'Movistar'},
'5037801':{'en': 'Digicel'},
'50378020':{'en': 'Digicel'},
'50378021':{'en': 'Digicel'},
'50378022':{'en': 'Digicel'},
'50378023':{'en': 'Digicel'},
'50378024':{'en': 'Digicel'},
'50378025':{'en': 'Claro'},
'50378026':{'en': 'Claro'},
'50378027':{'en': 'Claro'},
'50378028':{'en': 'Claro'},
'50378029':{'en': 'Claro'},
'5037803':{'en': 'Claro'},
'5037805':{'en': 'Claro'},
'5037806':{'en': 'Claro'},
'5037807':{'en': 'Claro'},
'5037808':{'en': 'Claro'},
'5037809':{'en': 'Claro'},
'503781':{'en': 'Movistar'},
'503782':{'en': 'Movistar'},
'503783':{'en': 'Movistar'},
'5037840':{'en': 'Claro'},
'5037841':{'en': 'Claro'},
'5037842':{'en': 'Claro'},
'5037843':{'en': 'Claro'},
'5037844':{'en': 'Claro'},
'5037845':{'en': 'Movistar'},
'5037846':{'en': 'Movistar'},
'5037847':{'en': 'Movistar'},
'5037848':{'en': 'Movistar'},
'5037849':{'en': 'Movistar'},
'503785':{'en': 'Claro'},
'503786':{'en': 'Claro'},
'503787':{'en': 'Tigo'},
'503788':{'en': 'Tigo'},
'503789':{'en': 'Tigo'},
'503790':{'en': 'Tigo'},
'503791':{'en': 'Tigo'},
'503792':{'en': 'Tigo'},
'503793':{'en': 'Tigo'},
'503794':{'en': 'Tigo'},
'503795':{'en': 'Claro'},
'503796':{'en': 'Claro'},
'503797':{'en': 'Digicel'},
'5037980':{'en': 'Intelfon'},
'5037981':{'en': 'Intelfon'},
'5037982':{'en': 'Intelfon'},
'5037983':{'en': 'Intelfon'},
'5037984':{'en': 'Intelfon'},
'5037985':{'en': 'Claro'},
'5037986':{'en': 'Claro'},
'5037987':{'en': 'Claro'},
'5037988':{'en': 'Claro'},
'5037989':{'en': 'Claro'},
'503799':{'en': 'Movistar'},
'5043':{'en': 'Sercom (Claro)'},
'5047':{'en': 'HONDUTEL'},
'5048':{'en': 'Digicel Honduras'},
'5049':{'en': 'Celtel (Tigo)'},
'5055':{'en': 'Claro'},
'5056':{'en': 'CooTel'},
'5057':{'en': 'Movistar'},
'50581':{'en': 'Movistar'},
'50582':{'en': 'Movistar'},
'505820':{'en': 'Claro'},
'505821':{'en': 'Claro'},
'505822':{'en': 'Claro'},
'505823':{'en': 'Claro'},
'505832':{'en': 'Movistar'},
'505833':{'en': 'Claro'},
'505835':{'en': 'Claro'},
'505836':{'en': 'Claro'},
'505837':{'en': 'Movistar'},
'505838':{'en': 'Movistar'},
'505839':{'en': 'Movistar'},
'50584':{'en': 'Claro'},
'505845':{'en': 'Movistar'},
'505846':{'en': 'Movistar'},
'505847':{'en': 'Movistar'},
'505848':{'en': 'Movistar'},
'505850':{'en': 'Claro'},
'505851':{'en': 'Claro'},
'505852':{'en': 'Claro'},
'505853':{'en': 'Claro'},
'505854':{'en': 'Claro'},
'505855':{'en': 'Movistar'},
'505856':{'en': 'Movistar'},
'505857':{'en': 'Movistar'},
'505858':{'en': 'Movistar'},
'505859':{'en': 'Movistar'},
'50586':{'en': 'Claro'},
'505867':{'en': 'Movistar'},
'505868':{'en': 'Movistar'},
'505870':{'en': 'Claro'},
'505871':{'en': 'Claro'},
'505872':{'en': 'Claro'},
'505873':{'en': 'Claro'},
'505874':{'en': 'Claro'},
'505875':{'en': 'Movistar'},
'505876':{'en': 'Movistar'},
'505877':{'en': 'Movistar'},
'505878':{'en': 'Movistar'},
'505879':{'en': 'Movistar'},
'50588':{'en': 'Movistar'},
'505882':{'en': 'Claro'},
'505883':{'en': 'Claro'},
'505884':{'en': 'Claro'},
'505885':{'en': 'Claro'},
'505890':{'en': 'Claro'},
'505891':{'en': 'Claro'},
'505892':{'en': 'Claro'},
'505893':{'en': 'Claro'},
'505894':{'en': 'Claro'},
'505895':{'en': 'Movistar'},
'505896':{'en': 'Movistar'},
'505897':{'en': 'Movistar'},
'505898':{'en': 'Movistar'},
'505899':{'en': 'Movistar'},
'5063':{'en': 'Kolbi ICE'},
'50650':{'en': 'Kolbi ICE'},
'50657':{'en': 'Kolbi ICE'},
'5066':{'en': 'Movistar'},
'5067000':{'en': 'Claro'},
'50670010':{'en': 'Claro'},
'50670011':{'en': 'Claro'},
'50670012':{'en': 'Claro'},
'50670013':{'en': 'Claro'},
'50670014':{'en': 'Claro'},
'5067002':{'en': 'Claro'},
'5067003':{'en': 'Claro'},
'5067004':{'en': 'Claro'},
'5067005':{'en': 'Claro'},
'5067006':{'en': 'Claro'},
'5067007':{'en': 'Claro'},
'5067008':{'en': 'Claro'},
'5067009':{'en': 'Claro'},
'506701':{'en': 'Claro'},
'506702':{'en': 'Claro'},
'506703':{'en': 'Claro'},
'506704':{'en': 'Claro'},
'506705':{'en': 'Claro'},
'506706':{'en': 'Claro'},
'506707':{'en': 'Claro'},
'506708':{'en': 'Claro'},
'506709':{'en': 'Claro'},
'50671':{'en': 'Claro'},
'50672':{'en': 'Claro'},
'5067300':{'en': 'Claro'},
'5067301':{'en': 'Claro'},
'50683':{'en': 'Kolbi ICE'},
'50684':{'en': 'Kolbi ICE'},
'50685':{'en': 'Kolbi ICE'},
'50686':{'en': 'Kolbi ICE'},
'50687':{'en': 'Kolbi ICE'},
'50688':{'en': 'Kolbi ICE'},
'50689':{'en': 'Kolbi ICE'},
'507111':{'en': 'Claro'},
'507161':{'en': 'Cable & Wireless'},
'507218':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507219':{'en': u('Telef\u00f3nica M\u00f3viles')},
'50760':{'en': 'Digicel'},
'50761':{'en': 'Digicel'},
'507616':{'en': u('Telef\u00f3nica M\u00f3viles')},
'50762':{'en': 'Claro'},
'507630':{'en': 'Claro'},
'507631':{'en': 'Claro'},
'507632':{'en': 'Claro'},
'507633':{'en': 'Cable & Wireless'},
'507634':{'en': 'Cable & Wireless'},
'507635':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507636':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507637':{'en': 'Cable & Wireless'},
'507638':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507639':{'en': u('Telef\u00f3nica M\u00f3viles')},
'50764':{'en': u('Telef\u00f3nica M\u00f3viles')},
'50765':{'en': 'Cable & Wireless'},
'507656':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507657':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507658':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507659':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507660':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507661':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507662':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507663':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507664':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507665':{'en': 'Cable & Wireless'},
'507666':{'en': 'Cable & Wireless'},
'507667':{'en': 'Cable & Wireless'},
'507668':{'en': 'Cable & Wireless'},
'507669':{'en': 'Cable & Wireless'},
'50767':{'en': 'Cable & Wireless'},
'50768':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507680':{'en': 'Cable & Wireless'},
'507684':{'en': 'Cable & Wireless'},
'507687':{'en': 'Cable & Wireless'},
'507688':{'en': 'Cable & Wireless'},
'50769':{'en': 'Cable & Wireless'},
'507692':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507693':{'en': u('Telef\u00f3nica M\u00f3viles')},
'507697':{'en': u('Telef\u00f3nica M\u00f3viles')},
'50781':{'en': 'Mobilphone'},
'507872':{'en': 'Cable & Wireless'},
'507873':{'en': 'Cable & Wireless'},
'50840':{'en': 'Globaltel'},
'50842':{'en': 'Orange'},
'50843':{'en': 'Diabolocom'},
'50844':{'en': 'Globaltel'},
'50850':{'en': 'Keyyo'},
'50855':{'en': 'SPM Telecom'},
'50930':{'en': 'Digicel'},
'50931':{'en': 'Digicel'},
'50934':{'en': 'Digicel'},
'50936':{'en': 'Digicel'},
'50937':{'en': 'Digicel'},
'50938':{'en': 'Digicel'},
'50939':{'en': 'Digicel'},
'50940':{'en': 'Natcom'},
'50941':{'en': 'Natcom'},
'50942':{'en': 'Natcom'},
'50943':{'en': 'Natcom'},
'50944':{'en': 'Digicel'},
'50946':{'en': 'Digicel'},
'50947':{'en': 'Digicel'},
'50948':{'en': 'Digicel'},
'50949':{'en': 'Digicel'},
'51900':{'en': 'Claro'},
'51901':{'en': 'Claro'},
'51910':{'en': 'Claro'},
'51912':{'en': 'Entel'},
'51913':{'en': 'Claro'},
'51914':{'en': 'Claro'},
'51915':{'en': 'Claro'},
'51916':{'en': 'Claro'},
'51917':{'en': 'Claro'},
'51918':{'en': 'Claro'},
'519190':{'en': 'Claro'},
'519191':{'en': 'Claro'},
'5191920':{'en': 'Claro'},
'5191921':{'en': 'Claro'},
'5191922':{'en': 'Claro'},
'5191923':{'en': 'Claro'},
'5191924':{'en': 'Claro'},
'5191925':{'en': 'Claro'},
'5191926':{'en': 'Claro'},
'5191927':{'en': 'Claro'},
'51920':{'en': 'Movistar'},
'51921':{'en': 'Claro'},
'51922':{'en': 'Entel'},
'51923':{'en': 'Entel'},
'51924':{'en': 'Entel'},
'51925':{'en': 'Claro'},
'519260':{'en': 'Claro'},
'519261':{'en': 'Claro'},
'519262':{'en': 'Claro'},
'5192630':{'en': 'Claro'},
'5192631':{'en': 'Claro'},
'5192632':{'en': 'Claro'},
'5192633':{'en': 'Claro'},
'5192634':{'en': 'Claro'},
'5192635':{'en': 'Claro'},
'5192638':{'en': 'Entel'},
'5192639':{'en': 'Entel'},
'519264':{'en': 'Claro'},
'519265':{'en': 'Claro'},
'519266':{'en': 'Entel'},
'519267':{'en': 'Entel'},
'519268':{'en': 'Entel'},
'519269':{'en': 'Entel'},
'51927':{'en': 'Claro'},
'51928':{'en': 'Claro'},
'51929':{'en': 'Claro'},
'51930':{'en': 'Claro'},
'51931':{'en': 'Claro'},
'51932':{'en': 'Claro'},
'519327':{'en': 'Movistar'},
'519328':{'en': 'Movistar'},
'519329':{'en': 'Movistar'},
'51933':{'en': 'Entel'},
'51934':{'en': 'Entel'},
'51935':{'en': 'Claro'},
'51936':{'en': 'Entel'},
'51937':{'en': 'Movistar'},
'519370':{'en': 'Entel'},
'519371':{'en': 'Entel'},
'519372':{'en': 'Entel'},
'519373':{'en': 'Claro'},
'5193730':{'en': 'Entel'},
'5193731':{'en': 'Entel'},
'5193732':{'en': 'Entel'},
'5193733':{'en': 'Entel'},
'51938':{'en': 'Movistar'},
'51939':{'en': 'Movistar'},
'51940':{'en': 'Claro'},
'51941':{'en': 'Claro'},
'519418':{'en': 'Movistar'},
'519419':{'en': 'Movistar'},
'51942':{'en': 'Movistar'},
'519422':{'en': 'Claro'},
'519423':{'en': 'Claro'},
'519427':{'en': 'Claro'},
'51943':{'en': 'Movistar'},
'519433':{'en': 'Claro'},
'519435':{'en': 'Claro'},
'519437':{'en': 'Claro'},
'51944':{'en': 'Claro'},
'519444':{'en': 'Movistar'},
'519446':{'en': 'Movistar'},
'519448':{'en': 'Movistar'},
'519449':{'en': 'Movistar'},
'51945':{'en': 'Movistar'},
'51946':{'en': 'Entel'},
'519466':{'en': 'Claro'},
'519467':{'en': 'Claro'},
'519468':{'en': 'Claro'},
'5194680':{'en': 'Movistar'},
'5194681':{'en': 'Movistar'},
'5194682':{'en': 'Movistar'},
'5194683':{'en': 'Movistar'},
'519469':{'en': 'Movistar'},
'51947':{'en': 'Movistar'},
'519471':{'en': 'Entel'},
'519472':{'en': 'Entel'},
'519473':{'en': 'Entel'},
'519477':{'en': 'Claro'},
'51948':{'en': 'Movistar'},
'5194805':{'en': 'Claro'},
'5194806':{'en': 'Claro'},
'5194807':{'en': 'Claro'},
'5194808':{'en': 'Claro'},
'5194809':{'en': 'Claro'},
'519482':{'en': 'Claro'},
'519483':{'en': 'Claro'},
'519487':{'en': 'Claro'},
'519490':{'en': 'Movistar'},
'5194907':{'en': 'Claro'},
'5194908':{'en': 'Claro'},
'5194909':{'en': 'Claro'},
'519491':{'en': 'Claro'},
'519492':{'en': 'Claro'},
'519493':{'en': 'Claro'},
'519494':{'en': 'Movistar'},
'519495':{'en': 'Movistar'},
'519496':{'en': 'Movistar'},
'519497':{'en': 'Claro'},
'5194978':{'en': 'Movistar'},
'5194979':{'en': 'Movistar'},
'519498':{'en': 'Movistar'},
'5194990':{'en': 'Movistar'},
'5194991':{'en': 'Movistar'},
'5194992':{'en': 'Movistar'},
'5194993':{'en': 'Movistar'},
'5194994':{'en': 'Movistar'},
'5194995':{'en': 'Movistar'},
'5194996':{'en': 'Movistar'},
'5194997':{'en': 'Movistar'},
'51949980':{'en': 'Movistar'},
'51949981':{'en': 'Movistar'},
'519499822':{'en': 'Movistar'},
'519499823':{'en': 'Movistar'},
'519499824':{'en': 'Movistar'},
'519499825':{'en': 'Movistar'},
'519499826':{'en': 'Movistar'},
'519499827':{'en': 'Movistar'},
'519499828':{'en': 'Movistar'},
'519499829':{'en': 'Movistar'},
'51949983':{'en': 'Movistar'},
'51949984':{'en': 'Movistar'},
'51949985':{'en': 'Movistar'},
'51949986':{'en': 'Movistar'},
'519499875':{'en': 'Movistar'},
'519499876':{'en': 'Movistar'},
'519499877':{'en': 'Movistar'},
'519499878':{'en': 'Movistar'},
'519499879':{'en': 'Movistar'},
'5194999':{'en': 'Movistar'},
'5195':{'en': 'Movistar'},
'519501':{'en': 'Claro'},
'5195010':{'en': 'Entel'},
'519502':{'en': 'Claro'},
'519503':{'en': 'Claro'},
'519507':{'en': 'Claro'},
'519511':{'en': 'Claro'},
'519512':{'en': 'Claro'},
'519513':{'en': 'Claro'},
'519517':{'en': 'Claro'},
'519521':{'en': 'Claro'},
'5195210':{'en': 'Entel'},
'519523':{'en': 'Claro'},
'519524':{'en': 'Claro'},
'5195270':{'en': 'Claro'},
'5195271':{'en': 'Claro'},
'5195272':{'en': 'Claro'},
'51953':{'en': 'Claro'},
'5195310':{'en': 'Entel'},
'519541':{'en': 'Claro'},
'5195420':{'en': 'Claro'},
'5195430':{'en': 'Claro'},
'519547':{'en': 'Claro'},
'51955':{'en': 'Entel'},
'519557':{'en': 'Claro'},
'519562':{'en': 'Claro'},
'519563':{'en': 'Claro'},
'519567':{'en': 'Claro'},
'519570':{'en': 'Claro'},
'519571':{'en': 'Claro'},
'519572':{'en': 'Claro'},
'519573':{'en': 'Claro'},
'519577':{'en': 'Claro'},
'5195805':{'en': 'Claro'},
'5195806':{'en': 'Claro'},
'5195807':{'en': 'Claro'},
'5195808':{'en': 'Claro'},
'5195809':{'en': 'Claro'},
'519581':{'en': 'Claro'},
'519582':{'en': 'Claro'},
'519583':{'en': 'Claro'},
'5195847':{'en': 'Claro'},
'5195848':{'en': 'Claro'},
'5195849':{'en': 'Claro'},
'519587':{'en': 'Claro'},
'5195895':{'en': 'Claro'},
'5195896':{'en': 'Claro'},
'5195897':{'en': 'Claro'},
'5195898':{'en': 'Claro'},
'5195899':{'en': 'Claro'},
'519591':{'en': 'Claro'},
'519592':{'en': 'Claro'},
'519593':{'en': 'Claro'},
'519597':{'en': 'Claro'},
'5196004':{'en': 'Claro'},
'5196005':{'en': 'Claro'},
'5196006':{'en': 'Claro'},
'5196007':{'en': 'Claro'},
'5196008':{'en': 'Claro'},
'5196009':{'en': 'Claro'},
'519601':{'en': 'Entel'},
'519602':{'en': 'Entel'},
'519603':{'en': 'Entel'},
'519604':{'en': 'Entel'},
'519605':{'en': 'Entel'},
'519606':{'en': 'Entel'},
'519607':{'en': 'Entel'},
'519608':{'en': 'Entel'},
'519609':{'en': 'Entel'},
'519610':{'en': 'Movistar'},
'519611':{'en': 'Movistar'},
'519612':{'en': 'Claro'},
'519613':{'en': 'Claro'},
'519614':{'en': 'Claro'},
'519615':{'en': 'Movistar'},
'519616':{'en': 'Movistar'},
'519617':{'en': 'Claro'},
'519618':{'en': 'Claro'},
'519619':{'en': 'Movistar'},
'51962':{'en': 'Movistar'},
'519622':{'en': 'Claro'},
'519623':{'en': 'Claro'},
'519627':{'en': 'Claro'},
'51963':{'en': 'Claro'},
'5196350':{'en': 'Movistar'},
'5196351':{'en': 'Movistar'},
'5196352':{'en': 'Movistar'},
'5196353':{'en': 'Movistar'},
'5196354':{'en': 'Movistar'},
'519636':{'en': 'Movistar'},
'519639':{'en': 'Movistar'},
'5196396':{'en': 'Entel'},
'5196397':{'en': 'Entel'},
'51964':{'en': 'Movistar'},
'519641':{'en': 'Claro'},
'519642':{'en': 'Claro'},
'519643':{'en': 'Claro'},
'51965':{'en': 'Claro'},
'519650':{'en': 'Movistar'},
'519656':{'en': 'Movistar'},
'519658':{'en': 'Movistar'},
'519659':{'en': 'Movistar'},
'51966':{'en': 'Movistar'},
'519663':{'en': 'Claro'},
'519664':{'en': 'Claro'},
'519667':{'en': 'Claro'},
'51967':{'en': 'Claro'},
'5196765':{'en': 'Movistar'},
'5196766':{'en': 'Movistar'},
'5196768':{'en': 'Movistar'},
'5196769':{'en': 'Movistar'},
'5196790':{'en': 'Movistar'},
'5196791':{'en': 'Movistar'},
'5196798':{'en': 'Movistar'},
'5196799':{'en': 'Movistar'},
'51968':{'en': 'Movistar'},
'5196820':{'en': 'Entel'},
'5196821':{'en': 'Claro'},
'519683':{'en': 'Claro'},
'519687':{'en': 'Claro'},
'51969':{'en': 'Movistar'},
'519693':{'en': 'Claro'},
'519697':{'en': 'Claro'},
'51970':{'en': 'Entel'},
'519700':{'en': 'Movistar'},
'519702':{'en': 'Claro'},
'519709':{'en': 'Movistar'},
'51971':{'en': 'Movistar'},
'519720':{'en': 'Entel'},
'519721':{'en': 'Entel'},
'519722':{'en': 'Claro'},
'519723':{'en': 'Claro'},
'519724':{'en': 'Claro'},
'519725':{'en': 'Claro'},
'5197250':{'en': 'Movistar'},
'5197251':{'en': 'Movistar'},
'5197252':{'en': 'Movistar'},
'519726':{'en': 'Movistar'},
'519727':{'en': 'Claro'},
'519728':{'en': 'Movistar'},
'519729':{'en': 'Movistar'},
'51973':{'en': 'Claro'},
'519738':{'en': 'Movistar'},
'519739':{'en': 'Movistar'},
'51974':{'en': 'Claro'},
'519740':{'en': 'Movistar'},
'519741':{'en': 'Movistar'},
'5197410':{'en': 'Entel'},
'5197487':{'en': 'Movistar'},
'5197488':{'en': 'Movistar'},
'5197489':{'en': 'Movistar'},
'519749':{'en': 'Movistar'},
'51975':{'en': 'Movistar'},
'519760':{'en': 'Movistar'},
'519761':{'en': 'Movistar'},
'519762':{'en': 'Claro'},
'519763':{'en': 'Claro'},
'519766':{'en': 'Movistar'},
'519767':{'en': 'Movistar'},
'519768':{'en': 'Movistar'},
'519769':{'en': 'Movistar'},
'51977':{'en': 'Entel'},
'519770':{'en': 'Claro'},
'519771':{'en': 'Claro'},
'519772':{'en': 'Movistar'},
'51978':{'en': 'Movistar'},
'5197820':{'en': 'Claro'},
'5197821':{'en': 'Entel'},
'519783':{'en': 'Claro'},
'519786':{'en': 'Claro'},
'519787':{'en': 'Claro'},
'51979':{'en': 'Movistar'},
'519793':{'en': 'Claro'},
'519797':{'en': 'Claro'},
'5198':{'en': 'Claro'},
'519800':{'en': 'Movistar'},
'5198000':{'en': 'Entel'},
'5198001':{'en': 'Entel'},
'5198002':{'en': 'Entel'},
'519801':{'en': 'Movistar'},
'519802':{'en': 'Movistar'},
'519803':{'en': 'Movistar'},
'51981':{'en': 'Entel'},
'519816':{'en': 'Movistar'},
'519817':{'en': 'Movistar'},
'519818':{'en': 'Movistar'},
'519819':{'en': 'Movistar'},
'5198260':{'en': 'Movistar'},
'5198261':{'en': 'Movistar'},
'5198268':{'en': 'Movistar'},
'5198298':{'en': 'Movistar'},
'519834':{'en': 'Entel'},
'519835':{'en': 'Entel'},
'519836':{'en': 'Movistar'},
'519839':{'en': 'Movistar'},
'519840':{'en': 'Movistar'},
'519845':{'en': 'Movistar'},
'519846':{'en': 'Movistar'},
'519848':{'en': 'Movistar'},
'519849':{'en': 'Movistar'},
'51985':{'en': 'Movistar'},
'51988':{'en': 'Movistar'},
'51990':{'en': 'Movistar'},
'51991':{'en': 'Claro'},
'51992':{'en': 'Claro'},
'51993':{'en': 'Claro'},
'519940':{'en': 'Entel'},
'519941':{'en': 'Entel'},
'519942':{'en': 'Entel'},
'519943':{'en': 'Claro'},
'519944':{'en': 'Movistar'},
'519945':{'en': 'Movistar'},
'519946':{'en': 'Claro'},
'519947':{'en': 'Claro'},
'519948':{'en': 'Claro'},
'519949':{'en': 'Claro'},
'51995':{'en': 'Movistar'},
'51996':{'en': 'Movistar'},
'51997':{'en': 'Claro'},
'51998':{'en': 'Movistar'},
'519981':{'en': 'Entel'},
'519982':{'en': 'Entel'},
'519983':{'en': 'Entel'},
'51999':{'en': 'Movistar'},
'535':{'en': 'etecsa'},
'549113':{'en': 'Personal'},
'549114':{'en': 'Personal'},
'549115':{'en': 'Personal'},
'549116':{'en': 'Personal'},
'549220':{'en': 'Personal'},
'549221':{'en': 'Personal'},
'549222':{'en': 'Personal'},
'549223':{'en': 'Personal'},
'549224':{'en': 'Personal'},
'549225':{'en': 'Personal'},
'549226':{'en': 'Personal'},
'549227':{'en': 'Personal'},
'549228':{'en': 'Personal'},
'549229':{'en': 'Personal'},
'549230':{'en': 'Personal'},
'549231':{'en': 'Personal'},
'549232':{'en': 'Personal'},
'549233':{'en': 'Personal'},
'549234':{'en': 'Personal'},
'549235':{'en': 'Personal'},
'549236':{'en': 'Personal'},
'549239':{'en': 'Personal'},
'549247':{'en': 'Personal'},
'549249':{'en': 'Personal'},
'549260':{'en': 'Personal'},
'549261':{'en': 'Personal'},
'549262':{'en': 'Personal'},
'549263':{'en': 'Personal'},
'549264':{'en': 'Personal'},
'549265':{'en': 'Personal'},
'549266':{'en': 'Personal'},
'549280':{'en': 'Personal'},
'549290':{'en': 'Personal'},
'549291':{'en': 'Personal'},
'549292':{'en': 'Personal'},
'549293':{'en': 'Personal'},
'549294':{'en': 'Personal'},
'549295':{'en': 'Personal'},
'549296':{'en': 'Personal'},
'549297':{'en': 'Personal'},
'549298':{'en': 'Personal'},
'549299':{'en': 'Personal'},
'549332':{'en': 'Personal'},
'549336':{'en': 'Personal'},
'549338':{'en': 'Personal'},
'549340':{'en': 'Personal'},
'549341':{'en': 'Personal'},
'549342':{'en': 'Personal'},
'549343':{'en': 'Personal'},
'549344':{'en': 'Personal'},
'549345':{'en': 'Personal'},
'549346':{'en': 'Personal'},
'549347':{'en': 'Personal'},
'549348':{'en': 'Personal'},
'549349':{'en': 'Personal'},
'549351':{'en': 'Personal'},
'549352':{'en': 'Personal'},
'549353':{'en': 'Personal'},
'549354':{'en': 'Personal'},
'549356':{'en': 'Personal'},
'549357':{'en': 'Personal'},
'549358':{'en': 'Personal'},
'549362':{'en': 'Personal'},
'549364':{'en': 'Personal'},
'549370':{'en': 'Personal'},
'549371':{'en': 'Personal'},
'549372':{'en': 'Personal'},
'549373':{'en': 'Personal'},
'549374':{'en': 'Personal'},
'549375':{'en': 'Personal'},
'549376':{'en': 'Personal'},
'549377':{'en': 'Personal'},
'549378':{'en': 'Personal'},
'549379':{'en': 'Personal'},
'549380':{'en': 'Personal'},
'549381':{'en': 'Personal'},
'549382':{'en': 'Personal'},
'549383':{'en': 'Personal'},
'549384':{'en': 'Personal'},
'549385':{'en': 'Personal'},
'549386':{'en': 'Personal'},
'549387':{'en': 'Personal'},
'549388':{'en': 'Personal'},
'549389':{'en': 'Personal'},
'551195472':{'en': 'Vivo'},
'551195473':{'en': 'Vivo'},
'551195474':{'en': 'Vivo'},
'551195769':{'en': 'Vivo'},
'55119577':{'en': 'Vivo'},
'551195780':{'en': 'Vivo'},
'551195781':{'en': 'Vivo'},
'551195782':{'en': 'Vivo'},
'551195783':{'en': 'Vivo'},
'551195784':{'en': 'Vivo'},
'551195785':{'en': 'Vivo'},
'551195786':{'en': 'Vivo'},
'551196057':{'en': 'Vivo'},
'551196058':{'en': 'Vivo'},
'551196059':{'en': 'Vivo'},
'551196060':{'en': 'Vivo'},
'551196168':{'en': 'Claro BR'},
'551196169':{'en': 'Claro BR'},
'55119617':{'en': 'Claro BR'},
'55119618':{'en': 'Vivo'},
'551196180':{'en': 'Claro BR'},
'551196181':{'en': 'Claro BR'},
'55119619':{'en': 'Vivo'},
'55119630':{'en': 'Claro BR'},
'55119631':{'en': 'Claro BR'},
'55119632':{'en': 'Claro BR'},
'55119633':{'en': 'Claro BR'},
'55119637':{'en': 'Vivo'},
'55119638':{'en': 'Vivo'},
'55119639':{'en': 'Vivo'},
'55119640':{'en': 'Vivo'},
'55119641':{'en': 'Vivo'},
'55119647':{'en': 'Vivo'},
'55119648':{'en': 'Vivo'},
'55119649':{'en': 'Vivo'},
'55119657':{'en': 'Claro BR'},
'55119658':{'en': 'Claro BR'},
'55119659':{'en': 'Claro BR'},
'55119660':{'en': 'Claro BR'},
'55119661':{'en': 'Claro BR'},
'55119662':{'en': 'Claro BR'},
'55119663':{'en': 'Claro BR'},
'55119664':{'en': 'Claro BR'},
'551196650':{'en': 'Claro BR'},
'55119684':{'en': 'Vivo'},
'55119685':{'en': 'Vivo'},
'551196860':{'en': 'Vivo'},
'551196861':{'en': 'Vivo'},
'551196862':{'en': 'Vivo'},
'551196863':{'en': 'Vivo'},
'551196864':{'en': 'Vivo'},
'551196865':{'en': 'Vivo'},
'551196866':{'en': 'Vivo'},
'55119690':{'en': 'Vivo'},
'55119691':{'en': 'Claro BR'},
'551196910':{'en': 'Vivo'},
'551196911':{'en': 'Vivo'},
'551196912':{'en': 'Vivo'},
'551196913':{'en': 'Vivo'},
'55119692':{'en': 'Claro BR'},
'551196930':{'en': 'Claro BR'},
'551196931':{'en': 'Claro BR'},
'551197011':{'en': 'TIM'},
'551197012':{'en': 'TIM'},
'551197013':{'en': 'TIM'},
'551197014':{'en': 'TIM'},
'551197015':{'en': 'TIM'},
'551197016':{'en': 'TIM'},
'551197017':{'en': 'TIM'},
'551197018':{'en': 'TIM'},
'551197019':{'en': 'TIM'},
'55119702':{'en': 'TIM'},
'551197030':{'en': 'TIM'},
'551197031':{'en': 'TIM'},
'551197032':{'en': 'TIM'},
'551197033':{'en': 'TIM'},
'551197034':{'en': 'TIM'},
'551197035':{'en': 'TIM'},
'551197036':{'en': 'TIM'},
'551197037':{'en': 'TIM'},
'551197038':{'en': 'TIM'},
'551197049':{'en': 'TIM'},
'55119705':{'en': 'Claro BR'},
'551197050':{'en': 'TIM'},
'551197051':{'en': 'TIM'},
'55119706':{'en': 'Claro BR'},
'55119707':{'en': 'Claro BR'},
'55119708':{'en': 'Claro BR'},
'551197087':{'en': 'Vivo'},
'551197088':{'en': 'Vivo'},
'551197089':{'en': 'Vivo'},
'55119709':{'en': 'Vivo'},
'5511971':{'en': 'Vivo'},
'5511972':{'en': 'Vivo'},
'5511973':{'en': 'Vivo'},
'5511974':{'en': 'Vivo'},
'5511975':{'en': 'Vivo'},
'5511976':{'en': 'Claro BR'},
'551197968':{'en': 'Claro BR'},
'551197969':{'en': 'Claro BR'},
'55119797':{'en': 'Oi'},
'551197970':{'en': 'Claro BR'},
'55119798':{'en': 'Oi'},
'551197990':{'en': 'Oi'},
'551197991':{'en': 'Oi'},
'551197992':{'en': 'Oi'},
'551197993':{'en': 'Oi'},
'551197994':{'en': 'Oi'},
'551197995':{'en': 'Oi'},
'551198023':{'en': 'Oi'},
'551198024':{'en': 'Oi'},
'551198025':{'en': 'Oi'},
'551198026':{'en': 'Oi'},
'551198027':{'en': 'Oi'},
'551198028':{'en': 'Oi'},
'551198029':{'en': 'Oi'},
'55119803':{'en': 'Oi'},
'55119804':{'en': 'Oi'},
'55119805':{'en': 'Oi'},
'55119806':{'en': 'Oi'},
'55119807':{'en': 'Oi'},
'55119808':{'en': 'Oi'},
'55119809':{'en': 'Oi'},
'5511981':{'en': 'TIM'},
'5511982':{'en': 'TIM'},
'5511983':{'en': 'TIM'},
'5511984':{'en': 'TIM'},
'5511985':{'en': 'TIM'},
'5511986':{'en': 'TIM'},
'5511987':{'en': 'TIM'},
'5511988':{'en': 'Claro BR'},
'5511989':{'en': 'Claro BR'},
'5511991':{'en': 'Claro BR'},
'5511992':{'en': 'Claro BR'},
'5511993':{'en': 'Claro BR'},
'5511994':{'en': 'Claro BR'},
'5511995':{'en': 'Vivo'},
'5511996':{'en': 'Vivo'},
'5511997':{'en': 'Vivo'},
'5511998':{'en': 'Vivo'},
'5511999':{'en': 'Vivo'},
'551298111':{'en': 'TIM'},
'551298112':{'en': 'TIM'},
'551298113':{'en': 'TIM'},
'551298114':{'en': 'TIM'},
'551298115':{'en': 'TIM'},
'551298116':{'en': 'TIM'},
'551298117':{'en': 'TIM'},
'551298118':{'en': 'TIM'},
'551298119':{'en': 'TIM'},
'551298121':{'en': 'TIM'},
'551298122':{'en': 'TIM'},
'551298123':{'en': 'TIM'},
'551298124':{'en': 'TIM'},
'551298125':{'en': 'TIM'},
'551298126':{'en': 'TIM'},
'551298127':{'en': 'TIM'},
'551298128':{'en': 'TIM'},
'551298129':{'en': 'TIM'},
'551298131':{'en': 'TIM'},
'551298132':{'en': 'TIM'},
'551298133':{'en': 'TIM'},
'551298134':{'en': 'TIM'},
'551298135':{'en': 'TIM'},
'551298136':{'en': 'TIM'},
'551298137':{'en': 'TIM'},
'551298138':{'en': 'TIM'},
'551298139':{'en': 'TIM'},
'551298141':{'en': 'TIM'},
'551298142':{'en': 'TIM'},
'551298143':{'en': 'TIM'},
'551298144':{'en': 'TIM'},
'551298145':{'en': 'TIM'},
'551298146':{'en': 'TIM'},
'551298147':{'en': 'TIM'},
'551298148':{'en': 'TIM'},
'551298149':{'en': 'TIM'},
'551298151':{'en': 'TIM'},
'551298152':{'en': 'TIM'},
'551298153':{'en': 'TIM'},
'551298154':{'en': 'TIM'},
'551298155':{'en': 'TIM'},
'551298156':{'en': 'TIM'},
'551298157':{'en': 'TIM'},
'551298158':{'en': 'TIM'},
'551298159':{'en': 'TIM'},
'551298161':{'en': 'TIM'},
'551298162':{'en': 'TIM'},
'551298163':{'en': 'TIM'},
'551298164':{'en': 'TIM'},
'551298165':{'en': 'TIM'},
'551298166':{'en': 'TIM'},
'551298167':{'en': 'TIM'},
'551298168':{'en': 'TIM'},
'551298169':{'en': 'TIM'},
'551298171':{'en': 'TIM'},
'551298172':{'en': 'TIM'},
'551298173':{'en': 'TIM'},
'551298174':{'en': 'TIM'},
'551298175':{'en': 'TIM'},
'551298176':{'en': 'TIM'},
'551298177':{'en': 'TIM'},
'551298178':{'en': 'TIM'},
'551298179':{'en': 'TIM'},
'551298181':{'en': 'TIM'},
'551298182':{'en': 'TIM'},
'551298808':{'en': 'Oi'},
'551298809':{'en': 'Oi'},
'55129881':{'en': 'Oi'},
'551298820':{'en': 'Oi'},
'551298821':{'en': 'Oi'},
'551298822':{'en': 'Oi'},
'551298823':{'en': 'Oi'},
'5512991':{'en': 'Claro BR'},
'55129920':{'en': 'Claro BR'},
'55129921':{'en': 'Claro BR'},
'55129922':{'en': 'Claro BR'},
'55129923':{'en': 'Claro BR'},
'551299240':{'en': 'Claro BR'},
'551299241':{'en': 'Claro BR'},
'551299242':{'en': 'Claro BR'},
'551299243':{'en': 'Claro BR'},
'551299244':{'en': 'Claro BR'},
'551299245':{'en': 'Claro BR'},
'55129960':{'en': 'Vivo'},
'55129961':{'en': 'Vivo'},
'55129962':{'en': 'Vivo'},
'551299630':{'en': 'Vivo'},
'551299631':{'en': 'Vivo'},
'551299632':{'en': 'Vivo'},
'5512997':{'en': 'Vivo'},
'551398111':{'en': 'TIM'},
'551398112':{'en': 'TIM'},
'551398113':{'en': 'TIM'},
'551398114':{'en': 'TIM'},
'551398115':{'en': 'TIM'},
'551398116':{'en': 'TIM'},
'551398117':{'en': 'TIM'},
'551398118':{'en': 'TIM'},
'551398119':{'en': 'TIM'},
'551398121':{'en': 'TIM'},
'551398122':{'en': 'TIM'},
'551398123':{'en': 'TIM'},
'551398124':{'en': 'TIM'},
'551398125':{'en': 'TIM'},
'551398126':{'en': 'TIM'},
'551398127':{'en': 'TIM'},
'551398128':{'en': 'TIM'},
'551398129':{'en': 'TIM'},
'551398131':{'en': 'TIM'},
'551398132':{'en': 'TIM'},
'551398133':{'en': 'TIM'},
'551398134':{'en': 'TIM'},
'551398135':{'en': 'TIM'},
'551398136':{'en': 'TIM'},
'551398137':{'en': 'TIM'},
'551398138':{'en': 'TIM'},
'551398139':{'en': 'TIM'},
'551398141':{'en': 'TIM'},
'551398142':{'en': 'TIM'},
'551398143':{'en': 'TIM'},
'551398144':{'en': 'TIM'},
'551398145':{'en': 'TIM'},
'551398146':{'en': 'TIM'},
'551398147':{'en': 'TIM'},
'551398149':{'en': 'TIM'},
'551398151':{'en': 'TIM'},
'551398152':{'en': 'TIM'},
'551398153':{'en': 'TIM'},
'551398154':{'en': 'TIM'},
'551398155':{'en': 'TIM'},
'551398156':{'en': 'TIM'},
'551398157':{'en': 'TIM'},
'551398158':{'en': 'TIM'},
'551398159':{'en': 'TIM'},
'551398161':{'en': 'TIM'},
'551398803':{'en': 'Oi'},
'551398804':{'en': 'Oi'},
'551398805':{'en': 'Oi'},
'551398806':{'en': 'Oi'},
'551398807':{'en': 'Oi'},
'551398808':{'en': 'Oi'},
'551398809':{'en': 'Oi'},
'55139881':{'en': 'Oi'},
'551398820':{'en': 'Oi'},
'5513991':{'en': 'Claro BR'},
'55139920':{'en': 'Claro BR'},
'551399210':{'en': 'Claro BR'},
'551399211':{'en': 'Claro BR'},
'55139960':{'en': 'Vivo'},
'55139961':{'en': 'Vivo'},
'55139962':{'en': 'Vivo'},
'551399630':{'en': 'Vivo'},
'551399631':{'en': 'Vivo'},
'551399632':{'en': 'Vivo'},
'551399633':{'en': 'Vivo'},
'551399634':{'en': 'Vivo'},
'551399635':{'en': 'Vivo'},
'551399636':{'en': 'Vivo'},
'551399637':{'en': 'Vivo'},
'5513997':{'en': 'Vivo'},
'551498111':{'en': 'TIM'},
'551498112':{'en': 'TIM'},
'551498113':{'en': 'TIM'},
'551498114':{'en': 'TIM'},
'551498115':{'en': 'TIM'},
'551498116':{'en': 'TIM'},
'551498117':{'en': 'TIM'},
'551498118':{'en': 'TIM'},
'551498119':{'en': 'TIM'},
'551498121':{'en': 'TIM'},
'551498122':{'en': 'TIM'},
'551498123':{'en': 'TIM'},
'551498124':{'en': 'TIM'},
'551498125':{'en': 'TIM'},
'551498126':{'en': 'TIM'},
'551498127':{'en': 'TIM'},
'551498128':{'en': 'TIM'},
'551498129':{'en': 'TIM'},
'551498131':{'en': 'TIM'},
'551498132':{'en': 'TIM'},
'551498133':{'en': 'TIM'},
'551498134':{'en': 'TIM'},
'551498135':{'en': 'TIM'},
'551498136':{'en': 'TIM'},
'551498137':{'en': 'TIM'},
'551498138':{'en': 'TIM'},
'551498139':{'en': 'TIM'},
'551498141':{'en': 'TIM'},
'551498142':{'en': 'TIM'},
'551498143':{'en': 'TIM'},
'551498144':{'en': 'TIM'},
'551498145':{'en': 'TIM'},
'551498146':{'en': 'TIM'},
'551498147':{'en': 'TIM'},
'551498148':{'en': 'TIM'},
'551498149':{'en': 'TIM'},
'551498151':{'en': 'TIM'},
'551498152':{'en': 'TIM'},
'551498153':{'en': 'TIM'},
'551498154':{'en': 'TIM'},
'551498155':{'en': 'TIM'},
'551498156':{'en': 'TIM'},
'551498157':{'en': 'TIM'},
'551498158':{'en': 'TIM'},
'551498159':{'en': 'TIM'},
'551498161':{'en': 'TIM'},
'551498162':{'en': 'TIM'},
'551498163':{'en': 'TIM'},
'551498164':{'en': 'TIM'},
'551498165':{'en': 'TIM'},
'551498166':{'en': 'TIM'},
'551498806':{'en': 'Oi'},
'551498807':{'en': 'Oi'},
'551498808':{'en': 'Oi'},
'551498809':{'en': 'Oi'},
'551498810':{'en': 'Oi'},
'551498811':{'en': 'Oi'},
'551498812':{'en': 'Oi'},
'551498813':{'en': 'Oi'},
'551498814':{'en': 'Oi'},
'551499101':{'en': 'Claro BR'},
'551499102':{'en': 'Claro BR'},
'551499103':{'en': 'Claro BR'},
'551499104':{'en': 'Claro BR'},
'551499105':{'en': 'Claro BR'},
'551499106':{'en': 'Claro BR'},
'551499107':{'en': 'Claro BR'},
'551499108':{'en': 'Claro BR'},
'551499109':{'en': 'Claro BR'},
'551499111':{'en': 'Claro BR'},
'551499112':{'en': 'Claro BR'},
'551499113':{'en': 'Claro BR'},
'551499114':{'en': 'Claro BR'},
'551499115':{'en': 'Claro BR'},
'551499116':{'en': 'Claro BR'},
'551499117':{'en': 'Claro BR'},
'551499118':{'en': 'Claro BR'},
'551499119':{'en': 'Claro BR'},
'551499121':{'en': 'Claro BR'},
'551499122':{'en': 'Claro BR'},
'551499123':{'en': 'Claro BR'},
'551499124':{'en': 'Claro BR'},
'551499125':{'en': 'Claro BR'},
'551499126':{'en': 'Claro BR'},
'551499127':{'en': 'Claro BR'},
'551499128':{'en': 'Claro BR'},
'551499129':{'en': 'Claro BR'},
'551499131':{'en': 'Claro BR'},
'551499132':{'en': 'Claro BR'},
'551499133':{'en': 'Claro BR'},
'551499134':{'en': 'Claro BR'},
'551499135':{'en': 'Claro BR'},
'551499136':{'en': 'Claro BR'},
'551499137':{'en': 'Claro BR'},
'551499138':{'en': 'Claro BR'},
'551499141':{'en': 'Claro BR'},
'551499142':{'en': 'Claro BR'},
'551499143':{'en': 'Claro BR'},
'551499146':{'en': 'Claro BR'},
'551499147':{'en': 'Claro BR'},
'551499148':{'en': 'Claro BR'},
'551499149':{'en': 'Claro BR'},
'551499151':{'en': 'Claro BR'},
'551499152':{'en': 'Claro BR'},
'551499153':{'en': 'Claro BR'},
'551499154':{'en': 'Claro BR'},
'551499155':{'en': 'Claro BR'},
'551499156':{'en': 'Claro BR'},
'551499157':{'en': 'Claro BR'},
'551499161':{'en': 'Claro BR'},
'551499162':{'en': 'Claro BR'},
'551499163':{'en': 'Claro BR'},
'551499164':{'en': 'Claro BR'},
'551499165':{'en': 'Claro BR'},
'551499166':{'en': 'Claro BR'},
'551499167':{'en': 'Claro BR'},
'551499168':{'en': 'Claro BR'},
'551499169':{'en': 'Claro BR'},
'551499171':{'en': 'Claro BR'},
'551499172':{'en': 'Claro BR'},
'551499173':{'en': 'Claro BR'},
'551499174':{'en': 'Claro BR'},
'551499175':{'en': 'Claro BR'},
'551499176':{'en': 'Claro BR'},
'551499177':{'en': 'Claro BR'},
'551499178':{'en': 'Claro BR'},
'551499179':{'en': 'Claro BR'},
'551499181':{'en': 'Claro BR'},
'551499182':{'en': 'Claro BR'},
'551499183':{'en': 'Claro BR'},
'551499184':{'en': 'Claro BR'},
'551499185':{'en': 'Claro BR'},
'551499186':{'en': 'Claro BR'},
'551499187':{'en': 'Claro BR'},
'551499188':{'en': 'Claro BR'},
'551499189':{'en': 'Claro BR'},
'551499191':{'en': 'Claro BR'},
'551499192':{'en': 'Claro BR'},
'551499193':{'en': 'Claro BR'},
'551499194':{'en': 'Claro BR'},
'551499195':{'en': 'Claro BR'},
'551499196':{'en': 'Claro BR'},
'551499197':{'en': 'Claro BR'},
'5514996':{'en': 'Vivo'},
'5514997':{'en': 'Vivo'},
'55149980':{'en': 'Vivo'},
'55149981':{'en': 'Vivo'},
'55149982':{'en': 'Vivo'},
'551499830':{'en': 'Vivo'},
'551499831':{'en': 'Vivo'},
'551499832':{'en': 'Vivo'},
'551598111':{'en': 'TIM'},
'551598112':{'en': 'TIM'},
'551598113':{'en': 'TIM'},
'551598114':{'en': 'TIM'},
'551598115':{'en': 'TIM'},
'551598116':{'en': 'TIM'},
'551598117':{'en': 'TIM'},
'551598118':{'en': 'TIM'},
'551598119':{'en': 'TIM'},
'551598121':{'en': 'TIM'},
'551598122':{'en': 'TIM'},
'551598123':{'en': 'TIM'},
'551598124':{'en': 'TIM'},
'551598125':{'en': 'TIM'},
'551598126':{'en': 'TIM'},
'551598127':{'en': 'TIM'},
'551598128':{'en': 'TIM'},
'551598129':{'en': 'TIM'},
'551598131':{'en': 'TIM'},
'551598132':{'en': 'TIM'},
'551598133':{'en': 'TIM'},
'551598134':{'en': 'TIM'},
'551598135':{'en': 'TIM'},
'551598136':{'en': 'TIM'},
'551598138':{'en': 'TIM'},
'551598139':{'en': 'TIM'},
'551598141':{'en': 'TIM'},
'551598804':{'en': 'Oi'},
'551598805':{'en': 'Oi'},
'551598806':{'en': 'Oi'},
'551598807':{'en': 'Oi'},
'551598808':{'en': 'Oi'},
'551598809':{'en': 'Oi'},
'551598810':{'en': 'Oi'},
'551598813':{'en': 'Oi'},
'551598814':{'en': 'Oi'},
'551598815':{'en': 'Oi'},
'551599101':{'en': 'Claro BR'},
'551599102':{'en': 'Claro BR'},
'551599103':{'en': 'Claro BR'},
'551599104':{'en': 'Claro BR'},
'551599105':{'en': 'Claro BR'},
'551599106':{'en': 'Claro BR'},
'551599107':{'en': 'Claro BR'},
'551599108':{'en': 'Claro BR'},
'551599109':{'en': 'Claro BR'},
'551599111':{'en': 'Claro BR'},
'551599112':{'en': 'Claro BR'},
'551599113':{'en': 'Claro BR'},
'551599114':{'en': 'Claro BR'},
'551599115':{'en': 'Claro BR'},
'551599116':{'en': 'Claro BR'},
'551599117':{'en': 'Claro BR'},
'551599118':{'en': 'Claro BR'},
'551599119':{'en': 'Claro BR'},
'551599121':{'en': 'Claro BR'},
'551599122':{'en': 'Claro BR'},
'551599123':{'en': 'Claro BR'},
'551599124':{'en': 'Claro BR'},
'551599125':{'en': 'Claro BR'},
'551599126':{'en': 'Claro BR'},
'551599127':{'en': 'Claro BR'},
'551599128':{'en': 'Claro BR'},
'551599129':{'en': 'Claro BR'},
'551599131':{'en': 'Claro BR'},
'551599132':{'en': 'Claro BR'},
'551599133':{'en': 'Claro BR'},
'551599134':{'en': 'Claro BR'},
'551599135':{'en': 'Claro BR'},
'551599136':{'en': 'Claro BR'},
'551599137':{'en': 'Claro BR'},
'551599138':{'en': 'Claro BR'},
'551599139':{'en': 'Claro BR'},
'551599141':{'en': 'Claro BR'},
'551599142':{'en': 'Claro BR'},
'551599143':{'en': 'Claro BR'},
'551599144':{'en': 'Claro BR'},
'551599145':{'en': 'Claro BR'},
'551599146':{'en': 'Claro BR'},
'551599147':{'en': 'Claro BR'},
'551599148':{'en': 'Claro BR'},
'551599149':{'en': 'Claro BR'},
'551599151':{'en': 'Claro BR'},
'551599152':{'en': 'Claro BR'},
'551599153':{'en': 'Claro BR'},
'551599154':{'en': 'Claro BR'},
'551599155':{'en': 'Claro BR'},
'551599156':{'en': 'Claro BR'},
'551599157':{'en': 'Claro BR'},
'551599158':{'en': 'Claro BR'},
'551599159':{'en': 'Claro BR'},
'551599161':{'en': 'Claro BR'},
'551599162':{'en': 'Claro BR'},
'551599163':{'en': 'Claro BR'},
'551599164':{'en': 'Claro BR'},
'551599165':{'en': 'Claro BR'},
'551599166':{'en': 'Claro BR'},
'551599167':{'en': 'Claro BR'},
'551599168':{'en': 'Claro BR'},
'551599169':{'en': 'Claro BR'},
'551599171':{'en': 'Claro BR'},
'551599172':{'en': 'Claro BR'},
'551599173':{'en': 'Claro BR'},
'551599174':{'en': 'Claro BR'},
'551599175':{'en': 'Claro BR'},
'551599176':{'en': 'Claro BR'},
'551599177':{'en': 'Claro BR'},
'551599178':{'en': 'Claro BR'},
'551599179':{'en': 'Claro BR'},
'551599181':{'en': 'Claro BR'},
'551599182':{'en': 'Claro BR'},
'551599183':{'en': 'Claro BR'},
'551599184':{'en': 'Claro BR'},
'551599185':{'en': 'Claro BR'},
'551599186':{'en': 'Claro BR'},
'551599187':{'en': 'Claro BR'},
'551599188':{'en': 'Claro BR'},
'551599201':{'en': 'Claro BR'},
'55159960':{'en': 'Vivo'},
'55159961':{'en': 'Vivo'},
'55159962':{'en': 'Vivo'},
'55159963':{'en': 'Vivo'},
'55159964':{'en': 'Vivo'},
'55159965':{'en': 'Vivo'},
'55159966':{'en': 'Vivo'},
'55159967':{'en': 'Vivo'},
'55159968':{'en': 'Vivo'},
'551599690':{'en': 'Vivo'},
'551599691':{'en': 'Vivo'},
'551599692':{'en': 'Vivo'},
'551599693':{'en': 'Vivo'},
'551599694':{'en': 'Vivo'},
'551599695':{'en': 'Vivo'},
'551599696':{'en': 'Vivo'},
'551599697':{'en': 'Vivo'},
'5515997':{'en': 'Vivo'},
'551698111':{'en': 'TIM'},
'551698112':{'en': 'TIM'},
'551698113':{'en': 'TIM'},
'551698114':{'en': 'TIM'},
'551698115':{'en': 'TIM'},
'551698116':{'en': 'TIM'},
'551698117':{'en': 'TIM'},
'551698118':{'en': 'TIM'},
'551698119':{'en': 'TIM'},
'551698121':{'en': 'TIM'},
'551698122':{'en': 'TIM'},
'551698123':{'en': 'TIM'},
'551698124':{'en': 'TIM'},
'551698125':{'en': 'TIM'},
'551698126':{'en': 'TIM'},
'551698127':{'en': 'TIM'},
'551698128':{'en': 'TIM'},
'551698129':{'en': 'TIM'},
'551698131':{'en': 'TIM'},
'551698132':{'en': 'TIM'},
'551698133':{'en': 'TIM'},
'551698134':{'en': 'TIM'},
'551698135':{'en': 'TIM'},
'551698136':{'en': 'TIM'},
'551698137':{'en': 'TIM'},
'551698138':{'en': 'TIM'},
'551698139':{'en': 'TIM'},
'551698141':{'en': 'TIM'},
'551698142':{'en': 'TIM'},
'551698143':{'en': 'TIM'},
'551698144':{'en': 'TIM'},
'551698145':{'en': 'TIM'},
'551698146':{'en': 'TIM'},
'551698147':{'en': 'TIM'},
'551698148':{'en': 'TIM'},
'551698149':{'en': 'TIM'},
'551698151':{'en': 'TIM'},
'551698152':{'en': 'TIM'},
'551698153':{'en': 'TIM'},
'551698154':{'en': 'TIM'},
'551698155':{'en': 'TIM'},
'551698156':{'en': 'TIM'},
'551698157':{'en': 'TIM'},
'551698158':{'en': 'TIM'},
'551698159':{'en': 'TIM'},
'551698161':{'en': 'TIM'},
'551698162':{'en': 'TIM'},
'551698163':{'en': 'TIM'},
'551698164':{'en': 'TIM'},
'551698165':{'en': 'TIM'},
'551698166':{'en': 'TIM'},
'551698167':{'en': 'TIM'},
'551698168':{'en': 'TIM'},
'551698169':{'en': 'TIM'},
'551698171':{'en': 'TIM'},
'551698172':{'en': 'TIM'},
'551698173':{'en': 'TIM'},
'551698174':{'en': 'TIM'},
'551698175':{'en': 'TIM'},
'551698176':{'en': 'TIM'},
'551698177':{'en': 'TIM'},
'551698178':{'en': 'TIM'},
'551698179':{'en': 'TIM'},
'551698181':{'en': 'TIM'},
'551698182':{'en': 'TIM'},
'551698183':{'en': 'TIM'},
'551698184':{'en': 'TIM'},
'551698803':{'en': 'Oi'},
'551698804':{'en': 'Oi'},
'551698805':{'en': 'Oi'},
'551698806':{'en': 'Oi'},
'551698807':{'en': 'Oi'},
'551698808':{'en': 'Oi'},
'551698809':{'en': 'Oi'},
'55169881':{'en': 'Oi'},
'551698820':{'en': 'Oi'},
'551698821':{'en': 'Oi'},
'551698822':{'en': 'Oi'},
'551698823':{'en': 'Oi'},
'5516991':{'en': 'Claro BR'},
'5516992':{'en': 'Claro BR'},
'55169930':{'en': 'Claro BR'},
'55169931':{'en': 'Claro BR'},
'55169932':{'en': 'Claro BR'},
'55169933':{'en': 'Claro BR'},
'55169934':{'en': 'Claro BR'},
'55169935':{'en': 'Claro BR'},
'551699360':{'en': 'Claro BR'},
'551699361':{'en': 'Claro BR'},
'551699362':{'en': 'Claro BR'},
'551699363':{'en': 'Claro BR'},
'551699364':{'en': 'Claro BR'},
'551699601':{'en': 'Vivo'},
'551699606':{'en': 'Vivo'},
'551699607':{'en': 'Vivo'},
'551699608':{'en': 'Vivo'},
'551699609':{'en': 'Vivo'},
'551699701':{'en': 'Vivo'},
'551699702':{'en': 'Vivo'},
'551699703':{'en': 'Vivo'},
'551699704':{'en': 'Vivo'},
'551699705':{'en': 'Vivo'},
'551699706':{'en': 'Vivo'},
'551699707':{'en': 'Vivo'},
'551699708':{'en': 'Vivo'},
'551699709':{'en': 'Vivo'},
'551699711':{'en': 'Vivo'},
'551699712':{'en': 'Vivo'},
'551699713':{'en': 'Vivo'},
'551699714':{'en': 'Vivo'},
'551699715':{'en': 'Vivo'},
'551699716':{'en': 'Vivo'},
'551699717':{'en': 'Vivo'},
'551699718':{'en': 'Vivo'},
'551699719':{'en': 'Vivo'},
'551699721':{'en': 'Vivo'},
'551699722':{'en': 'Vivo'},
'551699723':{'en': 'Vivo'},
'551699724':{'en': 'Vivo'},
'551699725':{'en': 'Vivo'},
'551699726':{'en': 'Vivo'},
'551699727':{'en': 'Vivo'},
'551699728':{'en': 'Vivo'},
'551699729':{'en': 'Vivo'},
'551699731':{'en': 'Vivo'},
'551699732':{'en': 'Vivo'},
'551699733':{'en': 'Vivo'},
'551699734':{'en': 'Vivo'},
'551699735':{'en': 'Vivo'},
'551699736':{'en': 'Vivo'},
'551699737':{'en': 'Vivo'},
'551699738':{'en': 'Vivo'},
'551699739':{'en': 'Vivo'},
'551699741':{'en': 'Vivo'},
'551699742':{'en': 'Vivo'},
'551699743':{'en': 'Vivo'},
'551699744':{'en': 'Vivo'},
'551699745':{'en': 'Vivo'},
'551699746':{'en': 'Vivo'},
'551699747':{'en': 'Vivo'},
'551699748':{'en': 'Vivo'},
'551699749':{'en': 'Vivo'},
'551699751':{'en': 'Vivo'},
'551699752':{'en': 'Vivo'},
'551699753':{'en': 'Vivo'},
'551699754':{'en': 'Vivo'},
'551699755':{'en': 'Vivo'},
'551699756':{'en': 'Vivo'},
'551699757':{'en': 'Vivo'},
'551699758':{'en': 'Vivo'},
'551699759':{'en': 'Vivo'},
'551699761':{'en': 'Vivo'},
'551699762':{'en': 'Vivo'},
'551699763':{'en': 'Vivo'},
'551699764':{'en': 'Vivo'},
'551699765':{'en': 'Vivo'},
'551699766':{'en': 'Vivo'},
'551699767':{'en': 'Vivo'},
'551699768':{'en': 'Vivo'},
'551699769':{'en': 'Vivo'},
'551699770':{'en': 'Vivo'},
'551699771':{'en': 'Vivo'},
'551699772':{'en': 'Vivo'},
'551699773':{'en': 'Vivo'},
'551699774':{'en': 'Vivo'},
'551699775':{'en': 'Vivo'},
'551699776':{'en': 'Vivo'},
'551699777':{'en': 'Vivo'},
'551699778':{'en': 'Vivo'},
'551699780':{'en': 'Vivo'},
'551699781':{'en': 'Vivo'},
'551699782':{'en': 'Vivo'},
'551699783':{'en': 'Vivo'},
'551699784':{'en': 'Vivo'},
'551699785':{'en': 'Vivo'},
'551699786':{'en': 'Vivo'},
'551699787':{'en': 'Vivo'},
'551699788':{'en': 'Vivo'},
'551699791':{'en': 'Vivo'},
'551699792':{'en': 'Vivo'},
'551699793':{'en': 'Vivo'},
'551699794':{'en': 'Vivo'},
'551699796':{'en': 'Vivo'},
'551699961':{'en': 'Vivo'},
'551699962':{'en': 'Vivo'},
'551699963':{'en': 'Vivo'},
'551699964':{'en': 'Vivo'},
'551699975':{'en': 'Vivo'},
'551699991':{'en': 'Vivo'},
'551699992':{'en': 'Vivo'},
'551699993':{'en': 'Vivo'},
'551699994':{'en': 'Vivo'},
'551798111':{'en': 'TIM'},
'551798112':{'en': 'TIM'},
'551798113':{'en': 'TIM'},
'551798114':{'en': 'TIM'},
'551798115':{'en': 'TIM'},
'551798116':{'en': 'TIM'},
'551798117':{'en': 'TIM'},
'551798118':{'en': 'TIM'},
'551798119':{'en': 'TIM'},
'551798121':{'en': 'TIM'},
'551798122':{'en': 'TIM'},
'551798123':{'en': 'TIM'},
'551798124':{'en': 'TIM'},
'551798125':{'en': 'TIM'},
'551798126':{'en': 'TIM'},
'551798127':{'en': 'TIM'},
'551798128':{'en': 'TIM'},
'551798129':{'en': 'TIM'},
'551798131':{'en': 'TIM'},
'551798132':{'en': 'TIM'},
'551798133':{'en': 'TIM'},
'551798134':{'en': 'TIM'},
'551798135':{'en': 'TIM'},
'551798136':{'en': 'TIM'},
'551798137':{'en': 'TIM'},
'551798138':{'en': 'TIM'},
'551798139':{'en': 'TIM'},
'551798141':{'en': 'TIM'},
'551798142':{'en': 'TIM'},
'551798143':{'en': 'TIM'},
'551798144':{'en': 'TIM'},
'551798145':{'en': 'TIM'},
'551798146':{'en': 'TIM'},
'551798147':{'en': 'TIM'},
'551798148':{'en': 'TIM'},
'551798149':{'en': 'TIM'},
'551798151':{'en': 'TIM'},
'551798152':{'en': 'TIM'},
'551798153':{'en': 'TIM'},
'551798154':{'en': 'TIM'},
'551798155':{'en': 'TIM'},
'551798156':{'en': 'TIM'},
'551798803':{'en': 'Oi'},
'551798804':{'en': 'Oi'},
'551798805':{'en': 'Oi'},
'551798806':{'en': 'Oi'},
'551798807':{'en': 'Oi'},
'551798808':{'en': 'Oi'},
'551798809':{'en': 'Oi'},
'551798810':{'en': 'Oi'},
'551798811':{'en': 'Oi'},
'551798812':{'en': 'Oi'},
'551798813':{'en': 'Oi'},
'5517991':{'en': 'Claro BR'},
'55179920':{'en': 'Claro BR'},
'55179921':{'en': 'Claro BR'},
'55179922':{'en': 'Claro BR'},
'551799230':{'en': 'Claro BR'},
'551799231':{'en': 'Claro BR'},
'551799232':{'en': 'Claro BR'},
'551799233':{'en': 'Claro BR'},
'551799234':{'en': 'Claro BR'},
'551799235':{'en': 'Claro BR'},
'551799236':{'en': 'Claro BR'},
'551799601':{'en': 'Vivo'},
'551799602':{'en': 'Vivo'},
'551799603':{'en': 'Vivo'},
'551799604':{'en': 'Vivo'},
'551799605':{'en': 'Vivo'},
'551799606':{'en': 'Vivo'},
'551799607':{'en': 'Vivo'},
'551799608':{'en': 'Vivo'},
'551799609':{'en': 'Vivo'},
'551799611':{'en': 'Vivo'},
'551799612':{'en': 'Vivo'},
'551799613':{'en': 'Vivo'},
'551799614':{'en': 'Vivo'},
'551799615':{'en': 'Vivo'},
'551799616':{'en': 'Vivo'},
'551799617':{'en': 'Vivo'},
'551799618':{'en': 'Vivo'},
'551799619':{'en': 'Vivo'},
'551799621':{'en': 'Vivo'},
'551799622':{'en': 'Vivo'},
'551799623':{'en': 'Vivo'},
'551799624':{'en': 'Vivo'},
'551799625':{'en': 'Vivo'},
'551799626':{'en': 'Vivo'},
'551799627':{'en': 'Vivo'},
'551799628':{'en': 'Vivo'},
'551799629':{'en': 'Vivo'},
'551799631':{'en': 'Vivo'},
'551799632':{'en': 'Vivo'},
'551799633':{'en': 'Vivo'},
'551799634':{'en': 'Vivo'},
'551799635':{'en': 'Vivo'},
'551799636':{'en': 'Vivo'},
'551799637':{'en': 'Vivo'},
'551799638':{'en': 'Vivo'},
'551799639':{'en': 'Vivo'},
'551799641':{'en': 'Vivo'},
'551799642':{'en': 'Vivo'},
'551799643':{'en': 'Vivo'},
'551799644':{'en': 'Vivo'},
'551799645':{'en': 'Vivo'},
'551799646':{'en': 'Vivo'},
'551799701':{'en': 'Vivo'},
'551799702':{'en': 'Vivo'},
'551799703':{'en': 'Vivo'},
'551799704':{'en': 'Vivo'},
'551799705':{'en': 'Vivo'},
'551799706':{'en': 'Vivo'},
'551799707':{'en': 'Vivo'},
'551799708':{'en': 'Vivo'},
'551799709':{'en': 'Vivo'},
'551799711':{'en': 'Vivo'},
'551799712':{'en': 'Vivo'},
'551799713':{'en': 'Vivo'},
'551799714':{'en': 'Vivo'},
'551799715':{'en': 'Vivo'},
'551799716':{'en': 'Vivo'},
'551799717':{'en': 'Vivo'},
'551799718':{'en': 'Vivo'},
'551799719':{'en': 'Vivo'},
'551799721':{'en': 'Vivo'},
'551799722':{'en': 'Vivo'},
'551799723':{'en': 'Vivo'},
'551799724':{'en': 'Vivo'},
'551799725':{'en': 'Vivo'},
'551799726':{'en': 'Vivo'},
'551799727':{'en': 'Vivo'},
'551799728':{'en': 'Vivo'},
'551799729':{'en': 'Vivo'},
'551799731':{'en': 'Vivo'},
'551799732':{'en': 'Vivo'},
'551799733':{'en': 'Vivo'},
'551799734':{'en': 'Vivo'},
'551799735':{'en': 'Vivo'},
'551799736':{'en': 'Vivo'},
'551799737':{'en': 'Vivo'},
'551799738':{'en': 'Vivo'},
'551799739':{'en': 'Vivo'},
'551799741':{'en': 'Vivo'},
'551799742':{'en': 'Vivo'},
'551799743':{'en': 'Vivo'},
'551799744':{'en': 'Vivo'},
'551799745':{'en': 'Vivo'},
'551799746':{'en': 'Vivo'},
'551799747':{'en': 'Vivo'},
'551799748':{'en': 'Vivo'},
'551799749':{'en': 'Vivo'},
'551799751':{'en': 'Vivo'},
'551799752':{'en': 'Vivo'},
'551799753':{'en': 'Vivo'},
'551799754':{'en': 'Vivo'},
'551799755':{'en': 'Vivo'},
'551799756':{'en': 'Vivo'},
'551799757':{'en': 'Vivo'},
'551799758':{'en': 'Vivo'},
'551799759':{'en': 'Vivo'},
'551799761':{'en': 'Vivo'},
'551799762':{'en': 'Vivo'},
'551799763':{'en': 'Vivo'},
'551799764':{'en': 'Vivo'},
'551799765':{'en': 'Vivo'},
'551799766':{'en': 'Vivo'},
'551799767':{'en': 'Vivo'},
'551799768':{'en': 'Vivo'},
'551799769':{'en': 'Vivo'},
'551799771':{'en': 'Vivo'},
'551799772':{'en': 'Vivo'},
'551799773':{'en': 'Vivo'},
'551799774':{'en': 'Vivo'},
'551799775':{'en': 'Vivo'},
'551799776':{'en': 'Vivo'},
'551799777':{'en': 'Vivo'},
'551799778':{'en': 'Vivo'},
'551799779':{'en': 'Vivo'},
'551799780':{'en': 'Vivo'},
'551799783':{'en': 'Vivo'},
'551799784':{'en': 'Vivo'},
'551799785':{'en': 'Vivo'},
'551799791':{'en': 'Vivo'},
'551898111':{'en': 'TIM'},
'551898112':{'en': 'TIM'},
'551898113':{'en': 'TIM'},
'551898114':{'en': 'TIM'},
'551898115':{'en': 'TIM'},
'551898116':{'en': 'TIM'},
'551898117':{'en': 'TIM'},
'551898118':{'en': 'TIM'},
'551898119':{'en': 'TIM'},
'551898121':{'en': 'TIM'},
'551898122':{'en': 'TIM'},
'551898123':{'en': 'TIM'},
'551898124':{'en': 'TIM'},
'551898125':{'en': 'TIM'},
'551898126':{'en': 'TIM'},
'551898127':{'en': 'TIM'},
'551898128':{'en': 'TIM'},
'551898129':{'en': 'TIM'},
'551898131':{'en': 'TIM'},
'551898132':{'en': 'TIM'},
'551898133':{'en': 'TIM'},
'551898134':{'en': 'TIM'},
'551898135':{'en': 'TIM'},
'551898136':{'en': 'TIM'},
'551898137':{'en': 'TIM'},
'551898138':{'en': 'TIM'},
'551898139':{'en': 'TIM'},
'551898141':{'en': 'TIM'},
'551898142':{'en': 'TIM'},
'551898143':{'en': 'TIM'},
'551898144':{'en': 'TIM'},
'551898145':{'en': 'TIM'},
'551898146':{'en': 'TIM'},
'551898147':{'en': 'TIM'},
'551898148':{'en': 'TIM'},
'551898149':{'en': 'TIM'},
'551898151':{'en': 'TIM'},
'551898810':{'en': 'Oi'},
'551898811':{'en': 'Oi'},
'55189910':{'en': 'Claro BR'},
'55189911':{'en': 'Claro BR'},
'55189912':{'en': 'Claro BR'},
'55189913':{'en': 'Claro BR'},
'55189914':{'en': 'Claro BR'},
'55189915':{'en': 'Claro BR'},
'55189916':{'en': 'Claro BR'},
'55189917':{'en': 'Claro BR'},
'551899180':{'en': 'Claro BR'},
'551899197':{'en': 'Claro BR'},
'551899198':{'en': 'Claro BR'},
'551899199':{'en': 'Claro BR'},
'551899601':{'en': 'Vivo'},
'551899602':{'en': 'Vivo'},
'551899603':{'en': 'Vivo'},
'551899604':{'en': 'Vivo'},
'551899605':{'en': 'Vivo'},
'551899606':{'en': 'Vivo'},
'551899607':{'en': 'Vivo'},
'551899608':{'en': 'Vivo'},
'551899609':{'en': 'Vivo'},
'551899611':{'en': 'Vivo'},
'551899612':{'en': 'Vivo'},
'551899613':{'en': 'Vivo'},
'551899614':{'en': 'Vivo'},
'551899615':{'en': 'Vivo'},
'551899616':{'en': 'Vivo'},
'551899617':{'en': 'Vivo'},
'551899618':{'en': 'Vivo'},
'551899621':{'en': 'Vivo'},
'551899622':{'en': 'Vivo'},
'551899623':{'en': 'Vivo'},
'551899624':{'en': 'Vivo'},
'551899625':{'en': 'Vivo'},
'551899626':{'en': 'Vivo'},
'551899627':{'en': 'Vivo'},
'551899628':{'en': 'Vivo'},
'551899629':{'en': 'Vivo'},
'551899631':{'en': 'Vivo'},
'551899632':{'en': 'Vivo'},
'551899633':{'en': 'Vivo'},
'551899634':{'en': 'Vivo'},
'551899635':{'en': 'Vivo'},
'551899636':{'en': 'Vivo'},
'551899637':{'en': 'Vivo'},
'551899638':{'en': 'Vivo'},
'551899639':{'en': 'Vivo'},
'551899641':{'en': 'Vivo'},
'551899642':{'en': 'Vivo'},
'551899643':{'en': 'Vivo'},
'551899644':{'en': 'Vivo'},
'551899645':{'en': 'Vivo'},
'551899646':{'en': 'Vivo'},
'551899647':{'en': 'Vivo'},
'551899648':{'en': 'Vivo'},
'551899649':{'en': 'Vivo'},
'551899651':{'en': 'Vivo'},
'551899652':{'en': 'Vivo'},
'551899653':{'en': 'Vivo'},
'551899654':{'en': 'Vivo'},
'551899655':{'en': 'Vivo'},
'551899656':{'en': 'Vivo'},
'551899657':{'en': 'Vivo'},
'551899658':{'en': 'Vivo'},
'551899659':{'en': 'Vivo'},
'551899661':{'en': 'Vivo'},
'551899662':{'en': 'Vivo'},
'551899663':{'en': 'Vivo'},
'551899664':{'en': 'Vivo'},
'551899665':{'en': 'Vivo'},
'551899666':{'en': 'Vivo'},
'551899667':{'en': 'Vivo'},
'551899668':{'en': 'Vivo'},
'551899669':{'en': 'Vivo'},
'551899671':{'en': 'Vivo'},
'551899672':{'en': 'Vivo'},
'551899673':{'en': 'Vivo'},
'551899674':{'en': 'Vivo'},
'551899675':{'en': 'Vivo'},
'551899676':{'en': 'Vivo'},
'551899677':{'en': 'Vivo'},
'551899678':{'en': 'Vivo'},
'551899679':{'en': 'Vivo'},
'551899681':{'en': 'Vivo'},
'551899682':{'en': 'Vivo'},
'551899683':{'en': 'Vivo'},
'551899684':{'en': 'Vivo'},
'551899685':{'en': 'Vivo'},
'551899686':{'en': 'Vivo'},
'551899687':{'en': 'Vivo'},
'551899701':{'en': 'Vivo'},
'551899702':{'en': 'Vivo'},
'551899703':{'en': 'Vivo'},
'551899704':{'en': 'Vivo'},
'551899705':{'en': 'Vivo'},
'551899706':{'en': 'Vivo'},
'551899707':{'en': 'Vivo'},
'551899708':{'en': 'Vivo'},
'551899709':{'en': 'Vivo'},
'551899711':{'en': 'Vivo'},
'551899712':{'en': 'Vivo'},
'551899713':{'en': 'Vivo'},
'551899714':{'en': 'Vivo'},
'551899715':{'en': 'Vivo'},
'551899716':{'en': 'Vivo'},
'551899717':{'en': 'Vivo'},
'551899718':{'en': 'Vivo'},
'551899719':{'en': 'Vivo'},
'551899721':{'en': 'Vivo'},
'551899722':{'en': 'Vivo'},
'551899723':{'en': 'Vivo'},
'551899724':{'en': 'Vivo'},
'551899725':{'en': 'Vivo'},
'551899726':{'en': 'Vivo'},
'551899727':{'en': 'Vivo'},
'551899728':{'en': 'Vivo'},
'551899729':{'en': 'Vivo'},
'551899731':{'en': 'Vivo'},
'551899732':{'en': 'Vivo'},
'551899733':{'en': 'Vivo'},
'551899734':{'en': 'Vivo'},
'551899735':{'en': 'Vivo'},
'551899736':{'en': 'Vivo'},
'551899737':{'en': 'Vivo'},
'551899738':{'en': 'Vivo'},
'551899739':{'en': 'Vivo'},
'551899741':{'en': 'Vivo'},
'551899742':{'en': 'Vivo'},
'551899743':{'en': 'Vivo'},
'551899744':{'en': 'Vivo'},
'551899745':{'en': 'Vivo'},
'551899746':{'en': 'Vivo'},
'551899747':{'en': 'Vivo'},
'551899748':{'en': 'Vivo'},
'551899749':{'en': 'Vivo'},
'551899751':{'en': 'Vivo'},
'551899752':{'en': 'Vivo'},
'551899753':{'en': 'Vivo'},
'551899754':{'en': 'Vivo'},
'551899755':{'en': 'Vivo'},
'551899756':{'en': 'Vivo'},
'551899757':{'en': 'Vivo'},
'551899758':{'en': 'Vivo'},
'551899759':{'en': 'Vivo'},
'551899761':{'en': 'Vivo'},
'551899762':{'en': 'Vivo'},
'551899763':{'en': 'Vivo'},
'551899764':{'en': 'Vivo'},
'551899765':{'en': 'Vivo'},
'551899766':{'en': 'Vivo'},
'551899767':{'en': 'Vivo'},
'551899768':{'en': 'Vivo'},
'551899771':{'en': 'Vivo'},
'551899772':{'en': 'Vivo'},
'551899773':{'en': 'Vivo'},
'551899774':{'en': 'Vivo'},
'551899775':{'en': 'Vivo'},
'551899776':{'en': 'Vivo'},
'551899777':{'en': 'Vivo'},
'551899778':{'en': 'Vivo'},
'551899779':{'en': 'Vivo'},
'55189978':{'en': 'Vivo'},
'551899791':{'en': 'Vivo'},
'551899792':{'en': 'Vivo'},
'551899793':{'en': 'Vivo'},
'551899794':{'en': 'Vivo'},
'551899795':{'en': 'Vivo'},
'551899796':{'en': 'Vivo'},
'551899797':{'en': 'Vivo'},
'551899798':{'en': 'Vivo'},
'551899799':{'en': 'Vivo'},
'5519981':{'en': 'TIM'},
'551998201':{'en': 'TIM'},
'551998202':{'en': 'TIM'},
'551998203':{'en': 'TIM'},
'551998204':{'en': 'TIM'},
'551998205':{'en': 'TIM'},
'551998206':{'en': 'TIM'},
'551998207':{'en': 'TIM'},
'551998208':{'en': 'TIM'},
'551998209':{'en': 'TIM'},
'551998211':{'en': 'TIM'},
'551998212':{'en': 'TIM'},
'551998213':{'en': 'TIM'},
'551998214':{'en': 'TIM'},
'551998215':{'en': 'TIM'},
'551998216':{'en': 'TIM'},
'551998217':{'en': 'TIM'},
'551998218':{'en': 'TIM'},
'551998219':{'en': 'TIM'},
'551998221':{'en': 'TIM'},
'551998222':{'en': 'TIM'},
'551998223':{'en': 'TIM'},
'551998224':{'en': 'TIM'},
'551998225':{'en': 'TIM'},
'551998226':{'en': 'TIM'},
'551998227':{'en': 'TIM'},
'551998229':{'en': 'TIM'},
'5519991':{'en': 'Claro BR'},
'5519992':{'en': 'Claro BR'},
'5519993':{'en': 'Claro BR'},
'5519994':{'en': 'Claro BR'},
'551999500':{'en': 'Claro BR'},
'551999501':{'en': 'Claro BR'},
'551999502':{'en': 'Claro BR'},
'551999503':{'en': 'Claro BR'},
'551999504':{'en': 'Claro BR'},
'551999505':{'en': 'Claro BR'},
'551999506':{'en': 'Claro BR'},
'551999507':{'en': 'Claro BR'},
'551999508':{'en': 'Claro BR'},
'551999601':{'en': 'Vivo'},
'551999602':{'en': 'Vivo'},
'551999603':{'en': 'Vivo'},
'551999604':{'en': 'Vivo'},
'551999605':{'en': 'Vivo'},
'551999606':{'en': 'Vivo'},
'551999607':{'en': 'Vivo'},
'551999608':{'en': 'Vivo'},
'551999609':{'en': 'Vivo'},
'55199961':{'en': 'Vivo'},
'551999621':{'en': 'Vivo'},
'551999622':{'en': 'Vivo'},
'551999623':{'en': 'Vivo'},
'551999624':{'en': 'Vivo'},
'551999625':{'en': 'Vivo'},
'551999626':{'en': 'Vivo'},
'551999627':{'en': 'Vivo'},
'551999628':{'en': 'Vivo'},
'551999629':{'en': 'Vivo'},
'551999631':{'en': 'Vivo'},
'551999632':{'en': 'Vivo'},
'551999633':{'en': 'Vivo'},
'551999634':{'en': 'Vivo'},
'551999635':{'en': 'Vivo'},
'551999636':{'en': 'Vivo'},
'551999637':{'en': 'Vivo'},
'551999638':{'en': 'Vivo'},
'551999639':{'en': 'Vivo'},
'551999641':{'en': 'Vivo'},
'551999642':{'en': 'Vivo'},
'551999643':{'en': 'Vivo'},
'551999644':{'en': 'Vivo'},
'551999645':{'en': 'Vivo'},
'551999646':{'en': 'Vivo'},
'551999647':{'en': 'Vivo'},
'551999648':{'en': 'Vivo'},
'551999649':{'en': 'Vivo'},
'551999651':{'en': 'Vivo'},
'551999652':{'en': 'Vivo'},
'551999653':{'en': 'Vivo'},
'551999654':{'en': 'Vivo'},
'551999655':{'en': 'Vivo'},
'551999656':{'en': 'Vivo'},
'551999657':{'en': 'Vivo'},
'551999658':{'en': 'Vivo'},
'551999659':{'en': 'Vivo'},
'551999661':{'en': 'Vivo'},
'551999662':{'en': 'Vivo'},
'551999663':{'en': 'Vivo'},
'551999664':{'en': 'Vivo'},
'551999665':{'en': 'Vivo'},
'551999666':{'en': 'Vivo'},
'551999667':{'en': 'Vivo'},
'551999668':{'en': 'Vivo'},
'551999669':{'en': 'Vivo'},
'551999671':{'en': 'Vivo'},
'551999672':{'en': 'Vivo'},
'551999673':{'en': 'Vivo'},
'551999674':{'en': 'Vivo'},
'551999675':{'en': 'Vivo'},
'551999676':{'en': 'Vivo'},
'551999677':{'en': 'Vivo'},
'551999678':{'en': 'Vivo'},
'551999679':{'en': 'Vivo'},
'551999681':{'en': 'Vivo'},
'551999682':{'en': 'Vivo'},
'551999683':{'en': 'Vivo'},
'551999684':{'en': 'Vivo'},
'551999685':{'en': 'Vivo'},
'551999686':{'en': 'Vivo'},
'551999687':{'en': 'Vivo'},
'551999688':{'en': 'Vivo'},
'551999689':{'en': 'Vivo'},
'551999691':{'en': 'Vivo'},
'551999692':{'en': 'Vivo'},
'551999693':{'en': 'Vivo'},
'551999694':{'en': 'Vivo'},
'551999695':{'en': 'Vivo'},
'551999696':{'en': 'Vivo'},
'551999697':{'en': 'Vivo'},
'551999698':{'en': 'Vivo'},
'551999699':{'en': 'Vivo'},
'55199970':{'en': 'Vivo'},
'55199971':{'en': 'Vivo'},
'55199972':{'en': 'Vivo'},
'55199973':{'en': 'Vivo'},
'55199974':{'en': 'Vivo'},
'551999751':{'en': 'Vivo'},
'551999752':{'en': 'Vivo'},
'551999753':{'en': 'Vivo'},
'551999754':{'en': 'Vivo'},
'551999755':{'en': 'Vivo'},
'551999756':{'en': 'Vivo'},
'551999757':{'en': 'Vivo'},
'551999758':{'en': 'Vivo'},
'551999759':{'en': 'Vivo'},
'551999761':{'en': 'Vivo'},
'551999762':{'en': 'Vivo'},
'551999763':{'en': 'Vivo'},
'551999764':{'en': 'Vivo'},
'551999765':{'en': 'Vivo'},
'551999766':{'en': 'Vivo'},
'551999767':{'en': 'Vivo'},
'551999768':{'en': 'Vivo'},
'551999769':{'en': 'Vivo'},
'551999771':{'en': 'Vivo'},
'551999772':{'en': 'Vivo'},
'551999773':{'en': 'Vivo'},
'551999774':{'en': 'Vivo'},
'551999775':{'en': 'Vivo'},
'551999776':{'en': 'Vivo'},
'551999777':{'en': 'Vivo'},
'551999778':{'en': 'Vivo'},
'551999779':{'en': 'Vivo'},
'55199978':{'en': 'Vivo'},
'55199979':{'en': 'Vivo'},
'55199980':{'en': 'Vivo'},
'55199981':{'en': 'Vivo'},
'55199982':{'en': 'Vivo'},
'55199983':{'en': 'Vivo'},
'55199984':{'en': 'Vivo'},
'55199985':{'en': 'Vivo'},
'55199986':{'en': 'Vivo'},
'55199987':{'en': 'Vivo'},
'55199988':{'en': 'Vivo'},
'551999890':{'en': 'Vivo'},
'5521971':{'en': 'Vivo'},
'5521972':{'en': 'Vivo'},
'55219730':{'en': 'Claro BR'},
'55219731':{'en': 'Claro BR'},
'55219732':{'en': 'Claro BR'},
'55219733':{'en': 'Claro BR'},
'55219734':{'en': 'Claro BR'},
'55219735':{'en': 'Claro BR'},
'55219736':{'en': 'Claro BR'},
'552197370':{'en': 'Claro BR'},
'552197371':{'en': 'Claro BR'},
'552197372':{'en': 'Claro BR'},
'552197373':{'en': 'Claro BR'},
'5521974':{'en': 'Claro BR'},
'5521975':{'en': 'Claro BR'},
'5521976':{'en': 'Claro BR'},
'5521981':{'en': 'TIM'},
'5521982':{'en': 'TIM'},
'552198301':{'en': 'TIM'},
'552198302':{'en': 'TIM'},
'552198303':{'en': 'TIM'},
'552198304':{'en': 'TIM'},
'552198305':{'en': 'TIM'},
'552198306':{'en': 'TIM'},
'552198307':{'en': 'TIM'},
'552198308':{'en': 'TIM'},
'552198309':{'en': 'TIM'},
'552198311':{'en': 'TIM'},
'552198312':{'en': 'TIM'},
'552198313':{'en': 'TIM'},
'552198314':{'en': 'TIM'},
'552198315':{'en': 'TIM'},
'552198316':{'en': 'TIM'},
'552198317':{'en': 'TIM'},
'552198318':{'en': 'TIM'},
'552198319':{'en': 'TIM'},
'552198321':{'en': 'TIM'},
'552198322':{'en': 'TIM'},
'552198323':{'en': 'TIM'},
'552198324':{'en': 'TIM'},
'552198325':{'en': 'TIM'},
'552198326':{'en': 'TIM'},
'552198327':{'en': 'TIM'},
'552198328':{'en': 'TIM'},
'552198329':{'en': 'TIM'},
'552198331':{'en': 'TIM'},
'552198332':{'en': 'TIM'},
'552198333':{'en': 'TIM'},
'552198334':{'en': 'TIM'},
'552198335':{'en': 'TIM'},
'552198336':{'en': 'TIM'},
'552198337':{'en': 'TIM'},
'552198338':{'en': 'TIM'},
'552198339':{'en': 'TIM'},
'552198341':{'en': 'TIM'},
'552198342':{'en': 'TIM'},
'552198343':{'en': 'TIM'},
'552198344':{'en': 'TIM'},
'552198345':{'en': 'TIM'},
'552198346':{'en': 'TIM'},
'552198347':{'en': 'TIM'},
'552198348':{'en': 'TIM'},
'552198349':{'en': 'TIM'},
'552198351':{'en': 'TIM'},
'552198352':{'en': 'TIM'},
'552198353':{'en': 'TIM'},
'552198354':{'en': 'TIM'},
'552198355':{'en': 'TIM'},
'552198356':{'en': 'TIM'},
'552198357':{'en': 'TIM'},
'552198358':{'en': 'TIM'},
'552198359':{'en': 'TIM'},
'552198361':{'en': 'TIM'},
'552198362':{'en': 'TIM'},
'552198363':{'en': 'TIM'},
'552198364':{'en': 'TIM'},
'552198365':{'en': 'TIM'},
'552198366':{'en': 'TIM'},
'552198367':{'en': 'TIM'},
'552198368':{'en': 'TIM'},
'552198369':{'en': 'TIM'},
'552198371':{'en': 'TIM'},
'552198372':{'en': 'TIM'},
'552198373':{'en': 'TIM'},
'552198374':{'en': 'TIM'},
'552198375':{'en': 'TIM'},
'552198376':{'en': 'TIM'},
'552198377':{'en': 'TIM'},
'552198378':{'en': 'TIM'},
'552198379':{'en': 'TIM'},
'552198381':{'en': 'TIM'},
'552198382':{'en': 'TIM'},
'552198383':{'en': 'TIM'},
'552198384':{'en': 'TIM'},
'552198385':{'en': 'TIM'},
'552198386':{'en': 'TIM'},
'552198401':{'en': 'Oi'},
'552198402':{'en': 'Oi'},
'552198403':{'en': 'Oi'},
'552198404':{'en': 'Oi'},
'552198405':{'en': 'Oi'},
'552198406':{'en': 'Oi'},
'552198407':{'en': 'Oi'},
'552198408':{'en': 'Oi'},
'552198409':{'en': 'Oi'},
'552198411':{'en': 'Oi'},
'552198412':{'en': 'Oi'},
'552198413':{'en': 'Oi'},
'552198414':{'en': 'Oi'},
'552198415':{'en': 'Oi'},
'552198416':{'en': 'Oi'},
'552198417':{'en': 'Oi'},
'552198418':{'en': 'Oi'},
'552198419':{'en': 'Oi'},
'5521985':{'en': 'Oi'},
'5521986':{'en': 'Oi'},
'5521987':{'en': 'Oi'},
'5521988':{'en': 'Oi'},
'5521989':{'en': 'Oi'},
'5521991':{'en': 'Claro BR'},
'5521992':{'en': 'Claro BR'},
'5521993':{'en': 'Claro BR'},
'5521994':{'en': 'Claro BR'},
'5521995':{'en': 'Vivo'},
'5521996':{'en': 'Vivo'},
'5521997':{'en': 'Vivo'},
'5521998':{'en': 'Vivo'},
'5521999':{'en': 'Vivo'},
'552298111':{'en': 'TIM'},
'552298112':{'en': 'TIM'},
'552298113':{'en': 'TIM'},
'552298114':{'en': 'TIM'},
'552298115':{'en': 'TIM'},
'552298116':{'en': 'TIM'},
'552298117':{'en': 'TIM'},
'552298118':{'en': 'TIM'},
'552298119':{'en': 'TIM'},
'552298121':{'en': 'TIM'},
'552298122':{'en': 'TIM'},
'552298123':{'en': 'TIM'},
'552298124':{'en': 'TIM'},
'552298125':{'en': 'TIM'},
'552298126':{'en': 'TIM'},
'552298127':{'en': 'TIM'},
'552298128':{'en': 'TIM'},
'552298129':{'en': 'TIM'},
'552298131':{'en': 'TIM'},
'552298132':{'en': 'TIM'},
'552298133':{'en': 'TIM'},
'552298134':{'en': 'TIM'},
'552298135':{'en': 'TIM'},
'552298136':{'en': 'TIM'},
'552298137':{'en': 'TIM'},
'552298138':{'en': 'TIM'},
'552298139':{'en': 'TIM'},
'552298141':{'en': 'TIM'},
'552298142':{'en': 'TIM'},
'552298143':{'en': 'TIM'},
'552298144':{'en': 'TIM'},
'552298145':{'en': 'TIM'},
'552298146':{'en': 'TIM'},
'552298147':{'en': 'TIM'},
'552298148':{'en': 'TIM'},
'552298149':{'en': 'TIM'},
'552298151':{'en': 'TIM'},
'5522985':{'en': 'Oi'},
'5522986':{'en': 'Oi'},
'5522987':{'en': 'Oi'},
'5522988':{'en': 'Oi'},
'5522989':{'en': 'Oi'},
'552299101':{'en': 'Claro BR'},
'552299102':{'en': 'Claro BR'},
'552299103':{'en': 'Claro BR'},
'552299104':{'en': 'Claro BR'},
'552299105':{'en': 'Claro BR'},
'552299201':{'en': 'Claro BR'},
'552299202':{'en': 'Claro BR'},
'552299203':{'en': 'Claro BR'},
'552299204':{'en': 'Claro BR'},
'552299205':{'en': 'Claro BR'},
'552299206':{'en': 'Claro BR'},
'552299207':{'en': 'Claro BR'},
'552299208':{'en': 'Claro BR'},
'552299209':{'en': 'Claro BR'},
'552299211':{'en': 'Claro BR'},
'552299212':{'en': 'Claro BR'},
'552299213':{'en': 'Claro BR'},
'552299214':{'en': 'Claro BR'},
'552299215':{'en': 'Claro BR'},
'552299216':{'en': 'Claro BR'},
'552299217':{'en': 'Claro BR'},
'552299218':{'en': 'Claro BR'},
'552299219':{'en': 'Claro BR'},
'552299221':{'en': 'Claro BR'},
'552299222':{'en': 'Claro BR'},
'552299223':{'en': 'Claro BR'},
'552299224':{'en': 'Claro BR'},
'552299225':{'en': 'Claro BR'},
'552299226':{'en': 'Claro BR'},
'552299227':{'en': 'Claro BR'},
'552299228':{'en': 'Claro BR'},
'552299229':{'en': 'Claro BR'},
'552299231':{'en': 'Claro BR'},
'552299232':{'en': 'Claro BR'},
'552299233':{'en': 'Claro BR'},
'552299234':{'en': 'Claro BR'},
'552299235':{'en': 'Claro BR'},
'552299236':{'en': 'Claro BR'},
'552299237':{'en': 'Claro BR'},
'552299238':{'en': 'Claro BR'},
'552299239':{'en': 'Claro BR'},
'552299241':{'en': 'Claro BR'},
'552299242':{'en': 'Claro BR'},
'552299243':{'en': 'Claro BR'},
'552299244':{'en': 'Claro BR'},
'552299245':{'en': 'Claro BR'},
'552299246':{'en': 'Claro BR'},
'552299247':{'en': 'Claro BR'},
'552299248':{'en': 'Claro BR'},
'552299249':{'en': 'Claro BR'},
'552299251':{'en': 'Claro BR'},
'552299252':{'en': 'Claro BR'},
'552299253':{'en': 'Claro BR'},
'552299254':{'en': 'Claro BR'},
'552299255':{'en': 'Claro BR'},
'552299256':{'en': 'Claro BR'},
'552299257':{'en': 'Claro BR'},
'552299258':{'en': 'Claro BR'},
'552299259':{'en': 'Claro BR'},
'552299261':{'en': 'Claro BR'},
'552299262':{'en': 'Claro BR'},
'552299263':{'en': 'Claro BR'},
'552299264':{'en': 'Claro BR'},
'552299265':{'en': 'Claro BR'},
'552299266':{'en': 'Claro BR'},
'552299267':{'en': 'Claro BR'},
'552299268':{'en': 'Claro BR'},
'552299269':{'en': 'Claro BR'},
'552299271':{'en': 'Claro BR'},
'552299272':{'en': 'Claro BR'},
'552299273':{'en': 'Claro BR'},
'552299274':{'en': 'Claro BR'},
'552299275':{'en': 'Claro BR'},
'552299276':{'en': 'Claro BR'},
'552299277':{'en': 'Claro BR'},
'552299278':{'en': 'Claro BR'},
'552299279':{'en': 'Claro BR'},
'552299281':{'en': 'Claro BR'},
'552299282':{'en': 'Claro BR'},
'552299283':{'en': 'Claro BR'},
'552299284':{'en': 'Claro BR'},
'552299285':{'en': 'Claro BR'},
'552299286':{'en': 'Claro BR'},
'552299287':{'en': 'Claro BR'},
'552299288':{'en': 'Claro BR'},
'552299289':{'en': 'Claro BR'},
'55229970':{'en': 'Vivo'},
'55229971':{'en': 'Vivo'},
'55229972':{'en': 'Vivo'},
'55229973':{'en': 'Vivo'},
'55229974':{'en': 'Vivo'},
'55229975':{'en': 'Vivo'},
'552299760':{'en': 'Vivo'},
'552299761':{'en': 'Vivo'},
'552299762':{'en': 'Vivo'},
'552299763':{'en': 'Vivo'},
'552299764':{'en': 'Vivo'},
'552299765':{'en': 'Vivo'},
'552299766':{'en': 'Vivo'},
'552299767':{'en': 'Vivo'},
'5522998':{'en': 'Vivo'},
'5522999':{'en': 'Vivo'},
'552498111':{'en': 'TIM'},
'552498112':{'en': 'TIM'},
'552498113':{'en': 'TIM'},
'552498114':{'en': 'TIM'},
'552498115':{'en': 'TIM'},
'552498116':{'en': 'TIM'},
'552498117':{'en': 'TIM'},
'552498118':{'en': 'TIM'},
'552498119':{'en': 'TIM'},
'552498121':{'en': 'TIM'},
'552498122':{'en': 'TIM'},
'552498123':{'en': 'TIM'},
'552498124':{'en': 'TIM'},
'552498125':{'en': 'TIM'},
'552498126':{'en': 'TIM'},
'552498127':{'en': 'TIM'},
'552498128':{'en': 'TIM'},
'552498129':{'en': 'TIM'},
'552498131':{'en': 'TIM'},
'552498132':{'en': 'TIM'},
'552498133':{'en': 'TIM'},
'552498134':{'en': 'TIM'},
'552498135':{'en': 'TIM'},
'552498136':{'en': 'TIM'},
'552498137':{'en': 'TIM'},
'552498138':{'en': 'TIM'},
'552498139':{'en': 'TIM'},
'552498141':{'en': 'TIM'},
'552498142':{'en': 'TIM'},
'552498143':{'en': 'TIM'},
'552498144':{'en': 'TIM'},
'552498145':{'en': 'TIM'},
'552498182':{'en': 'TIM'},
'5524985':{'en': 'Oi'},
'5524986':{'en': 'Oi'},
'5524987':{'en': 'Oi'},
'5524988':{'en': 'Oi'},
'5524989':{'en': 'Oi'},
'55249920':{'en': 'Claro BR'},
'55249921':{'en': 'Claro BR'},
'55249922':{'en': 'Claro BR'},
'55249923':{'en': 'Claro BR'},
'55249924':{'en': 'Claro BR'},
'55249925':{'en': 'Claro BR'},
'55249926':{'en': 'Claro BR'},
'55249927':{'en': 'Claro BR'},
'552499280':{'en': 'Claro BR'},
'552499281':{'en': 'Claro BR'},
'552499282':{'en': 'Claro BR'},
'552499291':{'en': 'Claro BR'},
'552499292':{'en': 'Claro BR'},
'552499293':{'en': 'Claro BR'},
'552499294':{'en': 'Claro BR'},
'552499295':{'en': 'Claro BR'},
'552499296':{'en': 'Claro BR'},
'552499297':{'en': 'Claro BR'},
'552499298':{'en': 'Claro BR'},
'552499299':{'en': 'Claro BR'},
'552499301':{'en': 'Claro BR'},
'552499395':{'en': 'Claro BR'},
'55249962':{'en': 'Vivo'},
'55249963':{'en': 'Vivo'},
'55249964':{'en': 'Vivo'},
'55249965':{'en': 'Vivo'},
'55249966':{'en': 'Vivo'},
'55249967':{'en': 'Vivo'},
'55249968':{'en': 'Vivo'},
'55249969':{'en': 'Vivo'},
'5524997':{'en': 'Vivo'},
'5524998':{'en': 'Vivo'},
'55249990':{'en': 'Vivo'},
'55249991':{'en': 'Vivo'},
'552499920':{'en': 'Vivo'},
'552499921':{'en': 'Vivo'},
'552499922':{'en': 'Vivo'},
'552499923':{'en': 'Vivo'},
'552499924':{'en': 'Vivo'},
'552499925':{'en': 'Vivo'},
'55249994':{'en': 'Vivo'},
'55249995':{'en': 'Vivo'},
'55249996':{'en': 'Vivo'},
'55249997':{'en': 'Vivo'},
'55249998':{'en': 'Vivo'},
'55249999':{'en': 'Vivo'},
'552798111':{'en': 'TIM'},
'552798112':{'en': 'TIM'},
'552798113':{'en': 'TIM'},
'552798114':{'en': 'TIM'},
'552798115':{'en': 'TIM'},
'552798116':{'en': 'TIM'},
'552798117':{'en': 'TIM'},
'552798118':{'en': 'TIM'},
'552798119':{'en': 'TIM'},
'552798121':{'en': 'TIM'},
'552798122':{'en': 'TIM'},
'552798123':{'en': 'TIM'},
'552798124':{'en': 'TIM'},
'552798125':{'en': 'TIM'},
'552798126':{'en': 'TIM'},
'552798127':{'en': 'TIM'},
'552798128':{'en': 'TIM'},
'552798129':{'en': 'TIM'},
'552798131':{'en': 'TIM'},
'552798132':{'en': 'TIM'},
'552798133':{'en': 'TIM'},
'552798134':{'en': 'TIM'},
'552798135':{'en': 'TIM'},
'552798136':{'en': 'TIM'},
'552798137':{'en': 'TIM'},
'552798138':{'en': 'TIM'},
'552798139':{'en': 'TIM'},
'552798141':{'en': 'TIM'},
'552798142':{'en': 'TIM'},
'552798143':{'en': 'TIM'},
'552798144':{'en': 'TIM'},
'552798145':{'en': 'TIM'},
'552798146':{'en': 'TIM'},
'552798147':{'en': 'TIM'},
'552798148':{'en': 'TIM'},
'552798149':{'en': 'TIM'},
'552798151':{'en': 'TIM'},
'552798152':{'en': 'TIM'},
'552798153':{'en': 'TIM'},
'552798154':{'en': 'TIM'},
'552798155':{'en': 'TIM'},
'552798156':{'en': 'TIM'},
'552798157':{'en': 'TIM'},
'552798158':{'en': 'TIM'},
'552798159':{'en': 'TIM'},
'552798161':{'en': 'TIM'},
'552798162':{'en': 'TIM'},
'552798163':{'en': 'TIM'},
'552798164':{'en': 'TIM'},
'552798165':{'en': 'TIM'},
'552798166':{'en': 'TIM'},
'552798167':{'en': 'TIM'},
'552798168':{'en': 'TIM'},
'552798169':{'en': 'TIM'},
'552798171':{'en': 'TIM'},
'552798172':{'en': 'TIM'},
'552798173':{'en': 'TIM'},
'552798174':{'en': 'TIM'},
'552798175':{'en': 'TIM'},
'552798176':{'en': 'TIM'},
'552798177':{'en': 'TIM'},
'552798178':{'en': 'TIM'},
'552798182':{'en': 'TIM'},
'5527985':{'en': 'Oi'},
'5527986':{'en': 'Oi'},
'5527987':{'en': 'Oi'},
'5527988':{'en': 'Oi'},
'5527989':{'en': 'Oi'},
'552799201':{'en': 'Claro BR'},
'552799202':{'en': 'Claro BR'},
'552799203':{'en': 'Claro BR'},
'552799204':{'en': 'Claro BR'},
'552799205':{'en': 'Claro BR'},
'552799222':{'en': 'Claro BR'},
'552799223':{'en': 'Claro BR'},
'552799224':{'en': 'Claro BR'},
'552799225':{'en': 'Claro BR'},
'552799226':{'en': 'Claro BR'},
'552799227':{'en': 'Claro BR'},
'552799228':{'en': 'Claro BR'},
'552799229':{'en': 'Claro BR'},
'552799231':{'en': 'Claro BR'},
'552799232':{'en': 'Claro BR'},
'552799233':{'en': 'Claro BR'},
'552799234':{'en': 'Claro BR'},
'552799235':{'en': 'Claro BR'},
'552799236':{'en': 'Claro BR'},
'552799237':{'en': 'Claro BR'},
'552799238':{'en': 'Claro BR'},
'552799239':{'en': 'Claro BR'},
'552799241':{'en': 'Claro BR'},
'552799242':{'en': 'Claro BR'},
'552799243':{'en': 'Claro BR'},
'552799244':{'en': 'Claro BR'},
'552799245':{'en': 'Claro BR'},
'552799246':{'en': 'Claro BR'},
'552799247':{'en': 'Claro BR'},
'552799248':{'en': 'Claro BR'},
'552799249':{'en': 'Claro BR'},
'552799251':{'en': 'Claro BR'},
'552799252':{'en': 'Claro BR'},
'552799253':{'en': 'Claro BR'},
'552799254':{'en': 'Claro BR'},
'552799255':{'en': 'Claro BR'},
'552799256':{'en': 'Claro BR'},
'552799257':{'en': 'Claro BR'},
'552799258':{'en': 'Claro BR'},
'552799259':{'en': 'Claro BR'},
'552799261':{'en': 'Claro BR'},
'552799262':{'en': 'Claro BR'},
'552799263':{'en': 'Claro BR'},
'552799264':{'en': 'Claro BR'},
'552799265':{'en': 'Claro BR'},
'552799266':{'en': 'Claro BR'},
'552799267':{'en': 'Claro BR'},
'552799268':{'en': 'Claro BR'},
'552799269':{'en': 'Claro BR'},
'552799271':{'en': 'Claro BR'},
'552799272':{'en': 'Claro BR'},
'552799273':{'en': 'Claro BR'},
'552799274':{'en': 'Claro BR'},
'552799275':{'en': 'Claro BR'},
'552799276':{'en': 'Claro BR'},
'552799277':{'en': 'Claro BR'},
'552799278':{'en': 'Claro BR'},
'552799279':{'en': 'Claro BR'},
'552799281':{'en': 'Claro BR'},
'552799282':{'en': 'Claro BR'},
'552799283':{'en': 'Claro BR'},
'552799284':{'en': 'Claro BR'},
'552799285':{'en': 'Claro BR'},
'552799286':{'en': 'Claro BR'},
'552799287':{'en': 'Claro BR'},
'552799288':{'en': 'Claro BR'},
'552799289':{'en': 'Claro BR'},
'552799291':{'en': 'Claro BR'},
'552799292':{'en': 'Claro BR'},
'552799293':{'en': 'Claro BR'},
'552799294':{'en': 'Claro BR'},
'552799295':{'en': 'Claro BR'},
'552799296':{'en': 'Claro BR'},
'552799297':{'en': 'Claro BR'},
'552799298':{'en': 'Claro BR'},
'552799299':{'en': 'Claro BR'},
'552799309':{'en': 'Claro BR'},
'552799311':{'en': 'Claro BR'},
'552799312':{'en': 'Claro BR'},
'552799316':{'en': 'Claro BR'},
'55279960':{'en': 'Vivo'},
'55279961':{'en': 'Vivo'},
'55279962':{'en': 'Vivo'},
'55279963':{'en': 'Vivo'},
'55279964':{'en': 'Vivo'},
'552799650':{'en': 'Vivo'},
'552799651':{'en': 'Vivo'},
'552799652':{'en': 'Vivo'},
'552799653':{'en': 'Vivo'},
'5527997':{'en': 'Vivo'},
'5527998':{'en': 'Vivo'},
'5527999':{'en': 'Vivo'},
'552898111':{'en': 'TIM'},
'552898112':{'en': 'TIM'},
'552898113':{'en': 'TIM'},
'552898114':{'en': 'TIM'},
'552898115':{'en': 'TIM'},
'552898116':{'en': 'TIM'},
'552898117':{'en': 'TIM'},
'552898118':{'en': 'TIM'},
'552898119':{'en': 'TIM'},
'5528985':{'en': 'Oi'},
'5528986':{'en': 'Oi'},
'5528987':{'en': 'Oi'},
'5528988':{'en': 'Oi'},
'5528989':{'en': 'Oi'},
'552899210':{'en': 'Claro BR'},
'552899222':{'en': 'Claro BR'},
'552899251':{'en': 'Claro BR'},
'552899252':{'en': 'Claro BR'},
'552899253':{'en': 'Claro BR'},
'552899254':{'en': 'Claro BR'},
'552899255':{'en': 'Claro BR'},
'552899256':{'en': 'Claro BR'},
'552899257':{'en': 'Claro BR'},
'552899258':{'en': 'Claro BR'},
'552899271':{'en': 'Claro BR'},
'552899272':{'en': 'Claro BR'},
'552899273':{'en': 'Claro BR'},
'552899274':{'en': 'Claro BR'},
'552899275':{'en': 'Claro BR'},
'552899276':{'en': 'Claro BR'},
'552899277':{'en': 'Claro BR'},
'552899278':{'en': 'Claro BR'},
'552899279':{'en': 'Claro BR'},
'552899291':{'en': 'Claro BR'},
'552899298':{'en': 'Claro BR'},
'552899881':{'en': 'Vivo'},
'552899882':{'en': 'Vivo'},
'552899883':{'en': 'Vivo'},
'552899884':{'en': 'Vivo'},
'552899885':{'en': 'Vivo'},
'552899886':{'en': 'Vivo'},
'552899901':{'en': 'Vivo'},
'552899902':{'en': 'Vivo'},
'552899903':{'en': 'Vivo'},
'552899904':{'en': 'Vivo'},
'552899905':{'en': 'Vivo'},
'552899915':{'en': 'Vivo'},
'552899916':{'en': 'Vivo'},
'552899917':{'en': 'Vivo'},
'552899918':{'en': 'Vivo'},
'552899919':{'en': 'Vivo'},
'552899921':{'en': 'Vivo'},
'552899922':{'en': 'Vivo'},
'552899923':{'en': 'Vivo'},
'552899924':{'en': 'Vivo'},
'552899925':{'en': 'Vivo'},
'552899926':{'en': 'Vivo'},
'552899935':{'en': 'Vivo'},
'552899938':{'en': 'Vivo'},
'552899939':{'en': 'Vivo'},
'552899945':{'en': 'Vivo'},
'552899946':{'en': 'Vivo'},
'552899951':{'en': 'Vivo'},
'552899952':{'en': 'Vivo'},
'552899953':{'en': 'Vivo'},
'552899954':{'en': 'Vivo'},
'552899955':{'en': 'Vivo'},
'552899956':{'en': 'Vivo'},
'552899957':{'en': 'Vivo'},
'552899958':{'en': 'Vivo'},
'552899959':{'en': 'Vivo'},
'552899961':{'en': 'Vivo'},
'552899962':{'en': 'Vivo'},
'552899963':{'en': 'Vivo'},
'552899964':{'en': 'Vivo'},
'552899965':{'en': 'Vivo'},
'552899966':{'en': 'Vivo'},
'552899967':{'en': 'Vivo'},
'552899968':{'en': 'Vivo'},
'552899969':{'en': 'Vivo'},
'552899971':{'en': 'Vivo'},
'552899972':{'en': 'Vivo'},
'552899973':{'en': 'Vivo'},
'552899974':{'en': 'Vivo'},
'552899975':{'en': 'Vivo'},
'552899976':{'en': 'Vivo'},
'552899977':{'en': 'Vivo'},
'552899978':{'en': 'Vivo'},
'552899979':{'en': 'Vivo'},
'552899981':{'en': 'Vivo'},
'552899982':{'en': 'Vivo'},
'552899983':{'en': 'Vivo'},
'552899984':{'en': 'Vivo'},
'552899985':{'en': 'Vivo'},
'552899986':{'en': 'Vivo'},
'552899987':{'en': 'Vivo'},
'552899988':{'en': 'Vivo'},
'552899989':{'en': 'Vivo'},
'552899991':{'en': 'Vivo'},
'552899992':{'en': 'Vivo'},
'552899993':{'en': 'Vivo'},
'552899994':{'en': 'Vivo'},
'552899995':{'en': 'Vivo'},
'552899996':{'en': 'Vivo'},
'552899997':{'en': 'Vivo'},
'552899998':{'en': 'Vivo'},
'55319820':{'en': 'Claro BR'},
'55319821':{'en': 'Claro BR'},
'55319822':{'en': 'Claro BR'},
'55319823':{'en': 'Claro BR'},
'553198240':{'en': 'Claro BR'},
'553198241':{'en': 'Claro BR'},
'553198242':{'en': 'Claro BR'},
'553198243':{'en': 'Claro BR'},
'553198244':{'en': 'Claro BR'},
'553198245':{'en': 'Claro BR'},
'5531983':{'en': 'Claro BR'},
'5531984':{'en': 'Claro BR'},
'5531985':{'en': 'Oi'},
'5531986':{'en': 'Oi'},
'5531987':{'en': 'Oi'},
'5531988':{'en': 'Oi'},
'5531989':{'en': 'Oi'},
'553199101':{'en': 'TIM'},
'553199102':{'en': 'TIM'},
'553199103':{'en': 'TIM'},
'553199104':{'en': 'TIM'},
'553199105':{'en': 'TIM'},
'553199106':{'en': 'TIM'},
'553199107':{'en': 'TIM'},
'553199108':{'en': 'TIM'},
'553199109':{'en': 'TIM'},
'55319911':{'en': 'TIM'},
'55319912':{'en': 'TIM'},
'55319913':{'en': 'TIM'},
'55319914':{'en': 'TIM'},
'55319915':{'en': 'TIM'},
'553199161':{'en': 'TIM'},
'553199162':{'en': 'TIM'},
'553199163':{'en': 'TIM'},
'553199164':{'en': 'TIM'},
'553199165':{'en': 'TIM'},
'553199166':{'en': 'TIM'},
'553199167':{'en': 'TIM'},
'553199168':{'en': 'TIM'},
'553199169':{'en': 'TIM'},
'553199171':{'en': 'TIM'},
'553199172':{'en': 'TIM'},
'553199173':{'en': 'TIM'},
'553199174':{'en': 'TIM'},
'553199175':{'en': 'TIM'},
'553199176':{'en': 'TIM'},
'553199177':{'en': 'TIM'},
'553199178':{'en': 'TIM'},
'553199179':{'en': 'TIM'},
'553199181':{'en': 'TIM'},
'553199182':{'en': 'TIM'},
'553199183':{'en': 'TIM'},
'553199184':{'en': 'TIM'},
'553199185':{'en': 'TIM'},
'553199186':{'en': 'TIM'},
'553199187':{'en': 'TIM'},
'553199188':{'en': 'TIM'},
'553199189':{'en': 'TIM'},
'553199191':{'en': 'TIM'},
'553199192':{'en': 'TIM'},
'553199193':{'en': 'TIM'},
'553199194':{'en': 'TIM'},
'553199195':{'en': 'TIM'},
'553199196':{'en': 'TIM'},
'553199197':{'en': 'TIM'},
'553199198':{'en': 'TIM'},
'553199199':{'en': 'TIM'},
'5531992':{'en': 'TIM'},
'5531993':{'en': 'TIM'},
'553199401':{'en': 'TIM'},
'553199402':{'en': 'TIM'},
'553199403':{'en': 'TIM'},
'553199404':{'en': 'TIM'},
'553199405':{'en': 'TIM'},
'553199406':{'en': 'TIM'},
'553199407':{'en': 'TIM'},
'553199408':{'en': 'TIM'},
'553199409':{'en': 'TIM'},
'553199411':{'en': 'TIM'},
'553199412':{'en': 'TIM'},
'553199413':{'en': 'TIM'},
'553199414':{'en': 'TIM'},
'553199415':{'en': 'TIM'},
'553199416':{'en': 'TIM'},
'553199601':{'en': 'Telemig Celular'},
'553199602':{'en': 'Telemig Celular'},
'553199603':{'en': 'Telemig Celular'},
'553199604':{'en': 'Telemig Celular'},
'553199605':{'en': 'Telemig Celular'},
'553199606':{'en': 'Telemig Celular'},
'553199607':{'en': 'Telemig Celular'},
'553199608':{'en': 'Telemig Celular'},
'553199609':{'en': 'Telemig Celular'},
'553199611':{'en': 'Telemig Celular'},
'553199612':{'en': 'Telemig Celular'},
'553199613':{'en': 'Telemig Celular'},
'553199614':{'en': 'Telemig Celular'},
'553199615':{'en': 'Telemig Celular'},
'553199616':{'en': 'Telemig Celular'},
'553199617':{'en': 'Telemig Celular'},
'553199618':{'en': 'Telemig Celular'},
'553199619':{'en': 'Telemig Celular'},
'553199621':{'en': 'Telemig Celular'},
'553199622':{'en': 'Telemig Celular'},
'553199624':{'en': 'Telemig Celular'},
'553199625':{'en': 'Telemig Celular'},
'553199626':{'en': 'Telemig Celular'},
'553199627':{'en': 'Telemig Celular'},
'553199628':{'en': 'Telemig Celular'},
'553199629':{'en': 'Telemig Celular'},
'553199631':{'en': 'Telemig Celular'},
'553199632':{'en': 'Telemig Celular'},
'553199633':{'en': 'Telemig Celular'},
'553199634':{'en': 'Telemig Celular'},
'553199635':{'en': 'Telemig Celular'},
'553199636':{'en': 'Telemig Celular'},
'553199637':{'en': 'Telemig Celular'},
'553199638':{'en': 'Telemig Celular'},
'553199639':{'en': 'Telemig Celular'},
'553199641':{'en': 'Telemig Celular'},
'553199642':{'en': 'Telemig Celular'},
'553199643':{'en': 'Telemig Celular'},
'553199644':{'en': 'Telemig Celular'},
'553199645':{'en': 'Telemig Celular'},
'553199646':{'en': 'Telemig Celular'},
'553199647':{'en': 'Telemig Celular'},
'553199648':{'en': 'Telemig Celular'},
'553199649':{'en': 'Telemig Celular'},
'553199651':{'en': 'Telemig Celular'},
'553199652':{'en': 'Telemig Celular'},
'553199653':{'en': 'Telemig Celular'},
'553199654':{'en': 'Telemig Celular'},
'553199655':{'en': 'Telemig Celular'},
'553199656':{'en': 'Telemig Celular'},
'553199657':{'en': 'Telemig Celular'},
'553199658':{'en': 'Telemig Celular'},
'553199659':{'en': 'Telemig Celular'},
'553199661':{'en': 'Telemig Celular'},
'553199662':{'en': 'Telemig Celular'},
'553199663':{'en': 'Telemig Celular'},
'553199664':{'en': 'Telemig Celular'},
'553199665':{'en': 'Telemig Celular'},
'553199666':{'en': 'Telemig Celular'},
'553199667':{'en': 'Telemig Celular'},
'553199668':{'en': 'Telemig Celular'},
'553199669':{'en': 'Telemig Celular'},
'553199671':{'en': 'Telemig Celular'},
'553199672':{'en': 'Telemig Celular'},
'553199673':{'en': 'Telemig Celular'},
'553199674':{'en': 'Telemig Celular'},
'553199675':{'en': 'Telemig Celular'},
'553199676':{'en': 'Telemig Celular'},
'553199677':{'en': 'Telemig Celular'},
'553199678':{'en': 'Telemig Celular'},
'553199679':{'en': 'Telemig Celular'},
'553199681':{'en': 'Telemig Celular'},
'553199682':{'en': 'Telemig Celular'},
'553199683':{'en': 'Telemig Celular'},
'553199684':{'en': 'Telemig Celular'},
'553199685':{'en': 'Telemig Celular'},
'553199686':{'en': 'Telemig Celular'},
'553199687':{'en': 'Telemig Celular'},
'553199688':{'en': 'Telemig Celular'},
'553199689':{'en': 'Telemig Celular'},
'553199691':{'en': 'Telemig Celular'},
'553199692':{'en': 'Telemig Celular'},
'553199693':{'en': 'Telemig Celular'},
'553199694':{'en': 'Telemig Celular'},
'553199695':{'en': 'Telemig Celular'},
'553199696':{'en': 'Telemig Celular'},
'553199697':{'en': 'Telemig Celular'},
'553199698':{'en': 'Telemig Celular'},
'553199699':{'en': 'Telemig Celular'},
'553199701':{'en': 'Telemig Celular'},
'553199702':{'en': 'Telemig Celular'},
'553199703':{'en': 'Telemig Celular'},
'553199704':{'en': 'Telemig Celular'},
'553199705':{'en': 'Telemig Celular'},
'553199706':{'en': 'Telemig Celular'},
'553199707':{'en': 'Telemig Celular'},
'553199708':{'en': 'Telemig Celular'},
'553199709':{'en': 'Telemig Celular'},
'553199711':{'en': 'Telemig Celular'},
'553199712':{'en': 'Telemig Celular'},
'553199713':{'en': 'Telemig Celular'},
'553199714':{'en': 'Telemig Celular'},
'553199715':{'en': 'Telemig Celular'},
'553199717':{'en': 'Telemig Celular'},
'553199718':{'en': 'Telemig Celular'},
'553199719':{'en': 'Telemig Celular'},
'553199721':{'en': 'Telemig Celular'},
'553199722':{'en': 'Telemig Celular'},
'553199723':{'en': 'Telemig Celular'},
'553199724':{'en': 'Telemig Celular'},
'553199725':{'en': 'Telemig Celular'},
'553199726':{'en': 'Telemig Celular'},
'553199728':{'en': 'Telemig Celular'},
'553199729':{'en': 'Telemig Celular'},
'553199731':{'en': 'Telemig Celular'},
'553199732':{'en': 'Telemig Celular'},
'553199733':{'en': 'Telemig Celular'},
'553199734':{'en': 'Telemig Celular'},
'553199735':{'en': 'Telemig Celular'},
'553199736':{'en': 'Telemig Celular'},
'553199737':{'en': 'Telemig Celular'},
'553199738':{'en': 'Telemig Celular'},
'553199739':{'en': 'Telemig Celular'},
'553199741':{'en': 'Telemig Celular'},
'553199742':{'en': 'Telemig Celular'},
'553199743':{'en': 'Telemig Celular'},
'553199744':{'en': 'Telemig Celular'},
'553199745':{'en': 'Telemig Celular'},
'553199746':{'en': 'Telemig Celular'},
'553199747':{'en': 'Telemig Celular'},
'553199748':{'en': 'Telemig Celular'},
'553199749':{'en': 'Telemig Celular'},
'553199751':{'en': 'Telemig Celular'},
'553199752':{'en': 'Telemig Celular'},
'553199753':{'en': 'Telemig Celular'},
'553199755':{'en': 'Telemig Celular'},
'553199756':{'en': 'Telemig Celular'},
'553199757':{'en': 'Telemig Celular'},
'553199758':{'en': 'Telemig Celular'},
'553199759':{'en': 'Telemig Celular'},
'553199761':{'en': 'Telemig Celular'},
'553199762':{'en': 'Telemig Celular'},
'553199763':{'en': 'Telemig Celular'},
'553199764':{'en': 'Telemig Celular'},
'553199765':{'en': 'Telemig Celular'},
'553199766':{'en': 'Telemig Celular'},
'553199767':{'en': 'Telemig Celular'},
'553199768':{'en': 'Telemig Celular'},
'553199769':{'en': 'Telemig Celular'},
'553199771':{'en': 'Telemig Celular'},
'553199772':{'en': 'Telemig Celular'},
'553199773':{'en': 'Telemig Celular'},
'553199774':{'en': 'Telemig Celular'},
'553199775':{'en': 'Telemig Celular'},
'553199776':{'en': 'Telemig Celular'},
'553199777':{'en': 'Telemig Celular'},
'553199778':{'en': 'Telemig Celular'},
'553199779':{'en': 'Telemig Celular'},
'553199781':{'en': 'Telemig Celular'},
'553199782':{'en': 'Telemig Celular'},
'553199783':{'en': 'Telemig Celular'},
'553199784':{'en': 'Telemig Celular'},
'553199785':{'en': 'Telemig Celular'},
'553199786':{'en': 'Telemig Celular'},
'553199787':{'en': 'Telemig Celular'},
'553199788':{'en': 'Telemig Celular'},
'553199789':{'en': 'Telemig Celular'},
'553199791':{'en': 'Telemig Celular'},
'553199792':{'en': 'Telemig Celular'},
'553199793':{'en': 'Telemig Celular'},
'553199794':{'en': 'Telemig Celular'},
'553199795':{'en': 'Telemig Celular'},
'553199796':{'en': 'Telemig Celular'},
'553199797':{'en': 'Telemig Celular'},
'553199798':{'en': 'Telemig Celular'},
'553199799':{'en': 'Telemig Celular'},
'5531998':{'en': 'Telemig Celular'},
'553199800':{'en': 'TIM'},
'553199810':{'en': 'TIM'},
'553199820':{'en': 'TIM'},
'553199830':{'en': 'TIM'},
'553199840':{'en': 'TIM'},
'553199850':{'en': 'TIM'},
'553199860':{'en': 'TIM'},
'553199870':{'en': 'TIM'},
'553199880':{'en': 'TIM'},
'553199890':{'en': 'TIM'},
'553199901':{'en': 'Telemig Celular'},
'553199902':{'en': 'Telemig Celular'},
'553199903':{'en': 'Telemig Celular'},
'553199904':{'en': 'Telemig Celular'},
'553199905':{'en': 'Telemig Celular'},
'553199906':{'en': 'Telemig Celular'},
'553199907':{'en': 'Telemig Celular'},
'553199908':{'en': 'Telemig Celular'},
'553199909':{'en': 'Telemig Celular'},
'553199911':{'en': 'Telemig Celular'},
'553199912':{'en': 'Telemig Celular'},
'553199913':{'en': 'Telemig Celular'},
'553199914':{'en': 'Telemig Celular'},
'553199915':{'en': 'Telemig Celular'},
'553199916':{'en': 'Telemig Celular'},
'553199917':{'en': 'Telemig Celular'},
'553199918':{'en': 'Telemig Celular'},
'553199919':{'en': 'Telemig Celular'},
'553199921':{'en': 'Telemig Celular'},
'553199922':{'en': 'Telemig Celular'},
'553199923':{'en': 'Telemig Celular'},
'553199924':{'en': 'Telemig Celular'},
'553199925':{'en': 'Telemig Celular'},
'553199926':{'en': 'Telemig Celular'},
'553199927':{'en': 'Telemig Celular'},
'553199928':{'en': 'Telemig Celular'},
'553199929':{'en': 'Telemig Celular'},
'553199931':{'en': 'Telemig Celular'},
'553199932':{'en': 'Telemig Celular'},
'553199933':{'en': 'Telemig Celular'},
'553199934':{'en': 'Telemig Celular'},
'553199935':{'en': 'Telemig Celular'},
'553199936':{'en': 'Telemig Celular'},
'553199937':{'en': 'Telemig Celular'},
'553199938':{'en': 'Telemig Celular'},
'553199939':{'en': 'Telemig Celular'},
'553199941':{'en': 'Telemig Celular'},
'553199942':{'en': 'Telemig Celular'},
'553199943':{'en': 'Telemig Celular'},
'553199944':{'en': 'Telemig Celular'},
'553199945':{'en': 'Telemig Celular'},
'553199946':{'en': 'Telemig Celular'},
'553199947':{'en': 'Telemig Celular'},
'553199948':{'en': 'Telemig Celular'},
'553199949':{'en': 'Telemig Celular'},
'55319995':{'en': 'Telemig Celular'},
'55319996':{'en': 'Telemig Celular'},
'55319997':{'en': 'Telemig Celular'},
'55319998':{'en': 'Telemig Celular'},
'55319999':{'en': 'Telemig Celular'},
'55329840':{'en': 'Claro BR'},
'55329841':{'en': 'Claro BR'},
'55329842':{'en': 'Claro BR'},
'55329843':{'en': 'Claro BR'},
'55329844':{'en': 'Claro BR'},
'55329845':{'en': 'Claro BR'},
'55329846':{'en': 'Claro BR'},
'55329847':{'en': 'Claro BR'},
'553298480':{'en': 'Claro BR'},
'553298481':{'en': 'Claro BR'},
'553298482':{'en': 'Claro BR'},
'553298483':{'en': 'Claro BR'},
'553298484':{'en': 'Claro BR'},
'553298485':{'en': 'Claro BR'},
'5532985':{'en': 'Oi'},
'5532986':{'en': 'Oi'},
'5532987':{'en': 'Oi'},
'5532988':{'en': 'Oi'},
'5532989':{'en': 'Oi'},
'553299101':{'en': 'TIM'},
'553299102':{'en': 'TIM'},
'553299103':{'en': 'TIM'},
'553299104':{'en': 'TIM'},
'553299105':{'en': 'TIM'},
'553299106':{'en': 'TIM'},
'553299107':{'en': 'TIM'},
'553299108':{'en': 'TIM'},
'553299109':{'en': 'TIM'},
'553299111':{'en': 'TIM'},
'553299112':{'en': 'TIM'},
'553299113':{'en': 'TIM'},
'553299114':{'en': 'TIM'},
'553299115':{'en': 'TIM'},
'553299116':{'en': 'TIM'},
'553299117':{'en': 'TIM'},
'553299118':{'en': 'TIM'},
'553299119':{'en': 'TIM'},
'553299121':{'en': 'TIM'},
'553299122':{'en': 'TIM'},
'553299123':{'en': 'TIM'},
'553299124':{'en': 'TIM'},
'553299125':{'en': 'TIM'},
'553299126':{'en': 'TIM'},
'553299127':{'en': 'TIM'},
'553299128':{'en': 'TIM'},
'553299129':{'en': 'TIM'},
'553299131':{'en': 'TIM'},
'553299132':{'en': 'TIM'},
'553299133':{'en': 'TIM'},
'553299134':{'en': 'TIM'},
'553299135':{'en': 'TIM'},
'553299136':{'en': 'TIM'},
'553299137':{'en': 'TIM'},
'553299138':{'en': 'TIM'},
'553299139':{'en': 'TIM'},
'553299141':{'en': 'TIM'},
'553299142':{'en': 'TIM'},
'553299143':{'en': 'TIM'},
'553299144':{'en': 'TIM'},
'553299145':{'en': 'TIM'},
'553299146':{'en': 'TIM'},
'553299193':{'en': 'TIM'},
'553299194':{'en': 'TIM'},
'553299195':{'en': 'TIM'},
'553299197':{'en': 'TIM'},
'553299198':{'en': 'TIM'},
'553299199':{'en': 'TIM'},
'553299901':{'en': 'Telemig Celular'},
'553299902':{'en': 'Telemig Celular'},
'553299903':{'en': 'Telemig Celular'},
'553299904':{'en': 'Telemig Celular'},
'553299905':{'en': 'Telemig Celular'},
'553299906':{'en': 'Telemig Celular'},
'553299907':{'en': 'Telemig Celular'},
'553299908':{'en': 'Telemig Celular'},
'553299909':{'en': 'Telemig Celular'},
'553299911':{'en': 'Telemig Celular'},
'553299912':{'en': 'Telemig Celular'},
'553299913':{'en': 'Telemig Celular'},
'553299914':{'en': 'Telemig Celular'},
'553299917':{'en': 'Telemig Celular'},
'553299918':{'en': 'Telemig Celular'},
'553299919':{'en': 'Telemig Celular'},
'553299921':{'en': 'Telemig Celular'},
'553299922':{'en': 'Telemig Celular'},
'553299923':{'en': 'Telemig Celular'},
'553299924':{'en': 'Telemig Celular'},
'553299925':{'en': 'Telemig Celular'},
'553299931':{'en': 'Telemig Celular'},
'553299932':{'en': 'Telemig Celular'},
'553299933':{'en': 'Telemig Celular'},
'553299934':{'en': 'Telemig Celular'},
'553299935':{'en': 'Telemig Celular'},
'553299936':{'en': 'Telemig Celular'},
'553299937':{'en': 'Telemig Celular'},
'553299938':{'en': 'Telemig Celular'},
'553299939':{'en': 'Telemig Celular'},
'553299941':{'en': 'Telemig Celular'},
'553299942':{'en': 'Telemig Celular'},
'553299943':{'en': 'Telemig Celular'},
'553299944':{'en': 'Telemig Celular'},
'553299945':{'en': 'Telemig Celular'},
'553299946':{'en': 'Telemig Celular'},
'553299947':{'en': 'Telemig Celular'},
'553299948':{'en': 'Telemig Celular'},
'553299949':{'en': 'Telemig Celular'},
'553299951':{'en': 'Telemig Celular'},
'553299952':{'en': 'Telemig Celular'},
'553299953':{'en': 'Telemig Celular'},
'553299954':{'en': 'Telemig Celular'},
'553299955':{'en': 'Telemig Celular'},
'553299956':{'en': 'Telemig Celular'},
'553299957':{'en': 'Telemig Celular'},
'553299958':{'en': 'Telemig Celular'},
'553299959':{'en': 'Telemig Celular'},
'55329996':{'en': 'Telemig Celular'},
'553299971':{'en': 'Telemig Celular'},
'553299972':{'en': 'Telemig Celular'},
'553299973':{'en': 'Telemig Celular'},
'553299974':{'en': 'Telemig Celular'},
'553299975':{'en': 'Telemig Celular'},
'553299976':{'en': 'Telemig Celular'},
'553299977':{'en': 'Telemig Celular'},
'553299979':{'en': 'Telemig Celular'},
'55329998':{'en': 'Telemig Celular'},
'553299991':{'en': 'Telemig Celular'},
'553299992':{'en': 'Telemig Celular'},
'553299993':{'en': 'Telemig Celular'},
'553299994':{'en': 'Telemig Celular'},
'553299995':{'en': 'Telemig Celular'},
'553299996':{'en': 'Telemig Celular'},
'553299997':{'en': 'Telemig Celular'},
'553299998':{'en': 'Telemig Celular'},
'553398401':{'en': 'Claro BR'},
'553398402':{'en': 'Claro BR'},
'553398403':{'en': 'Claro BR'},
'553398404':{'en': 'Claro BR'},
'553398405':{'en': 'Claro BR'},
'553398406':{'en': 'Claro BR'},
'553398407':{'en': 'Claro BR'},
'553398408':{'en': 'Claro BR'},
'553398409':{'en': 'Claro BR'},
'553398411':{'en': 'Claro BR'},
'553398412':{'en': 'Claro BR'},
'553398413':{'en': 'Claro BR'},
'553398414':{'en': 'Claro BR'},
'553398415':{'en': 'Claro BR'},
'553398416':{'en': 'Claro BR'},
'553398417':{'en': 'Claro BR'},
'553398418':{'en': 'Claro BR'},
'553398419':{'en': 'Claro BR'},
'553398421':{'en': 'Claro BR'},
'553398422':{'en': 'Claro BR'},
'553398423':{'en': 'Claro BR'},
'553398424':{'en': 'Claro BR'},
'553398425':{'en': 'Claro BR'},
'553398426':{'en': 'Claro BR'},
'553398427':{'en': 'Claro BR'},
'553398428':{'en': 'Claro BR'},
'553398429':{'en': 'Claro BR'},
'553398431':{'en': 'Claro BR'},
'553398432':{'en': 'Claro BR'},
'553398433':{'en': 'Claro BR'},
'553398434':{'en': 'Claro BR'},
'553398435':{'en': 'Claro BR'},
'553398436':{'en': 'Claro BR'},
'553398437':{'en': 'Claro BR'},
'553398438':{'en': 'Claro BR'},
'553398439':{'en': 'Claro BR'},
'553398441':{'en': 'Claro BR'},
'553398442':{'en': 'Claro BR'},
'553398443':{'en': 'Claro BR'},
'553398444':{'en': 'Claro BR'},
'553398445':{'en': 'Claro BR'},
'553398446':{'en': 'Claro BR'},
'553398447':{'en': 'Claro BR'},
'553398448':{'en': 'Claro BR'},
'553398449':{'en': 'Claro BR'},
'553398451':{'en': 'Claro BR'},
'553398452':{'en': 'Claro BR'},
'553398453':{'en': 'Claro BR'},
'553398454':{'en': 'Claro BR'},
'553398455':{'en': 'Claro BR'},
'553398456':{'en': 'Claro BR'},
'5533985':{'en': 'Oi'},
'5533986':{'en': 'Oi'},
'5533987':{'en': 'Oi'},
'5533988':{'en': 'Oi'},
'5533989':{'en': 'Oi'},
'553399101':{'en': 'TIM'},
'553399102':{'en': 'TIM'},
'553399103':{'en': 'TIM'},
'553399104':{'en': 'TIM'},
'553399105':{'en': 'TIM'},
'553399106':{'en': 'TIM'},
'553399107':{'en': 'TIM'},
'553399108':{'en': 'TIM'},
'553399109':{'en': 'TIM'},
'553399111':{'en': 'TIM'},
'553399112':{'en': 'TIM'},
'553399113':{'en': 'TIM'},
'553399114':{'en': 'TIM'},
'553399115':{'en': 'TIM'},
'553399116':{'en': 'TIM'},
'553399117':{'en': 'TIM'},
'553399118':{'en': 'TIM'},
'553399119':{'en': 'TIM'},
'553399121':{'en': 'TIM'},
'553399122':{'en': 'TIM'},
'553399123':{'en': 'TIM'},
'553399124':{'en': 'TIM'},
'553399125':{'en': 'TIM'},
'553399126':{'en': 'TIM'},
}
| true | true |
f7105885e9a4c5e32b25abca7ec9383fb427430d | 22,990 | py | Python | python/mxnet/image.py | Leopard-X/MXNET | 7ac046c58f0815223712f77288722a7b06755ec3 | [
"Apache-2.0"
] | 1 | 2019-09-10T17:06:29.000Z | 2019-09-10T17:06:29.000Z | python/mxnet/image.py | Leopard-X/MXNET | 7ac046c58f0815223712f77288722a7b06755ec3 | [
"Apache-2.0"
] | null | null | null | python/mxnet/image.py | Leopard-X/MXNET | 7ac046c58f0815223712f77288722a7b06755ec3 | [
"Apache-2.0"
] | null | null | null | # pylint: disable=no-member, too-many-lines, redefined-builtin, protected-access, unused-import, invalid-name
# pylint: disable=too-many-arguments, too-many-locals, no-name-in-module, too-many-branches, too-many-statements
"""Read invidual image files and perform augmentations."""
from __future__ import absolute_import, print_function
import os
import random
import logging
import numpy as np
try:
import cv2
except ImportError:
cv2 = None
from .base import numeric_types
from . import ndarray as nd
from . import _ndarray_internal as _internal
from ._ndarray_internal import _cvimresize as imresize
from ._ndarray_internal import _cvcopyMakeBorder as copyMakeBorder
from . import io
from . import recordio
def imdecode(buf, **kwargs):
"""Decode an image to an NDArray.
Note: `imdecode` uses OpenCV (not the CV2 Python library).
MXNet must have been built with OpenCV for `imdecode` to work.
Parameters
----------
buf : str/bytes or numpy.ndarray
Binary image data as string or numpy ndarray.
flag : int, optional, default=1
1 for three channel color output. 0 for grayscale output.
to_rgb : int, optional, default=1
1 for RGB formatted output (MXNet default). 0 for BGR formatted output (OpenCV default).
out : NDArray, optional
Output buffer. Use `None` for automatic allocation.
Returns
-------
NDArray
An `NDArray` containing the image.
Example
-------
>>> with open("flower.jpg", 'rb') as fp:
... str_image = fp.read()
...
>>> image = mx.img.imdecode(str_image)
>>> image
<NDArray 224x224x3 @cpu(0)>
Set `flag` parameter to 0 to get grayscale output
>>> with open("flower.jpg", 'rb') as fp:
... str_image = fp.read()
...
>>> image = mx.img.imdecode(str_image, flag=0)
>>> image
<NDArray 224x224x1 @cpu(0)>
Set `to_rgb` parameter to 0 to get output in OpenCV format (BGR)
>>> with open("flower.jpg", 'rb') as fp:
... str_image = fp.read()
...
>>> image = mx.img.imdecode(str_image, to_rgb=0)
>>> image
<NDArray 224x224x3 @cpu(0)>
"""
if not isinstance(buf, nd.NDArray):
buf = nd.array(np.frombuffer(buf, dtype=np.uint8), dtype=np.uint8)
return _internal._cvimdecode(buf, **kwargs)
def scale_down(src_size, size):
"""Scales down crop size if it's larger than image size.
If width/height of the crop is larger than the width/height of the image,
sets the width/height to the width/height of the image.
Parameters
----------
src_size : tuple of int
Size of the image in (width, height) format.
size : tuple of int
Size of the crop in (width, height) format.
Returns
-------
tuple of int
A tuple containing the scaled crop size in (width, height) format.
Example
--------
>>> src_size = (640,480)
>>> size = (720,120)
>>> new_size = mx.img.scale_down(src_size, size)
>>> new_size
(640,106)
"""
w, h = size
sw, sh = src_size
if sh < h:
w, h = float(w * sh) / h, sh
if sw < w:
w, h = sw, float(h * sw) / w
return int(w), int(h)
def resize_short(src, size, interp=2):
"""Resizes shorter edge to size.
Note: `resize_short` uses OpenCV (not the CV2 Python library).
MXNet must have been built with OpenCV for `resize_short` to work.
Resizes the original image by setting the shorter edge to size
and setting the longer edge accordingly.
Resizing function is called from OpenCV.
Parameters
----------
src : NDArray
The original image.
size : int
The length to be set for the shorter edge.
interp : int, optional, default=2
Interpolation method used for resizing the image.
Default method is bicubic interpolation.
More details can be found in the documentation of OpenCV, please refer to
http://docs.opencv.org/master/da/d54/group__imgproc__transform.html.
Returns
-------
NDArray
An 'NDArray' containing the resized image.
Example
-------
>>> with open("flower.jpeg", 'rb') as fp:
... str_image = fp.read()
...
>>> image = mx.img.imdecode(str_image)
>>> image
<NDArray 2321x3482x3 @cpu(0)>
>>> size = 640
>>> new_image = mx.img.resize_short(image, size)
>>> new_image
<NDArray 2321x3482x3 @cpu(0)>
"""
h, w, _ = src.shape
if h > w:
new_h, new_w = size * h / w, size
else:
new_h, new_w = size, size * w / h
return imresize(src, new_w, new_h, interp=interp)
def fixed_crop(src, x0, y0, w, h, size=None, interp=2):
"""Crop src at fixed location, and (optionally) resize it to size."""
out = nd.crop(src, begin=(y0, x0, 0), end=(y0 + h, x0 + w, int(src.shape[2])))
if size is not None and (w, h) != size:
out = imresize(out, *size, interp=interp)
return out
def random_crop(src, size, interp=2):
"""Randomly crop `src` with `size` (width, height).
Upsample result if `src` is smaller than `size`.
Parameters
----------
src: Source image `NDArray`
size: Size of the crop formatted as (width, height). If the `size` is larger
than the image, then the source image is upsampled to `size` and returned.
interp: Interpolation method to be used in case the size is larger (default: bicubic).
Uses OpenCV convention for the parameters. Nearest - 0, Bilinear - 1, Bicubic - 2,
Area - 3. See OpenCV imresize function for more details.
Returns
-------
NDArray
An `NDArray` containing the cropped image.
Tuple
A tuple (x, y, width, height) where (x, y) is top-left position of the crop in the
original image and (width, height) are the dimensions of the cropped image.
Example
-------
>>> im = mx.nd.array(cv2.imread("flower.jpg"))
>>> cropped_im, rect = mx.image.random_crop(im, (100, 100))
>>> print cropped_im
<NDArray 100x100x1 @cpu(0)>
>>> print rect
(20, 21, 100, 100)
"""
h, w, _ = src.shape
new_w, new_h = scale_down((w, h), size)
x0 = random.randint(0, w - new_w)
y0 = random.randint(0, h - new_h)
out = fixed_crop(src, x0, y0, new_w, new_h, size, interp)
return out, (x0, y0, new_w, new_h)
def center_crop(src, size, interp=2):
"""Crops the image `src` to the given `size` by trimming on all four
sides and preserving the center of the image. Upsamples if `src` is smaller
than `size`.
.. note:: This requires MXNet to be compiled with USE_OPENCV.
Parameters
----------
src : NDArray
Binary source image data.
size : list or tuple of int
The desired output image size.
interp : interpolation, optional, default=Area-based
The type of interpolation that is done to the image.
Possible values:
0: Nearest Neighbors Interpolation.
1: Bilinear interpolation.
2: Area-based (resampling using pixel area relation). It may be a
preferred method for image decimation, as it gives moire-free
results. But when the image is zoomed, it is similar to the Nearest
Neighbors method. (used by default).
3: Bicubic interpolation over 4x4 pixel neighborhood.
4: Lanczos interpolation over 8x8 pixel neighborhood.
When shrinking an image, it will generally look best with AREA-based
interpolation, whereas, when enlarging an image, it will generally look best
with Bicubic (slow) or Bilinear (faster but still looks OK).
Returns
-------
NDArray
The cropped image.
Tuple
(x, y, width, height) where x, y are the positions of the crop in the
original image and width, height the dimensions of the crop.
Example
-------
>>> with open("flower.jpg", 'rb') as fp:
... str_image = fp.read()
...
>>> image = mx.image.imdecode(str_image)
>>> image
<NDArray 2321x3482x3 @cpu(0)>
>>> cropped_image, (x, y, width, height) = mx.image.center_crop(image, (1000, 500))
>>> cropped_image
<NDArray 500x1000x3 @cpu(0)>
>>> x, y, width, height
(1241, 910, 1000, 500)
"""
h, w, _ = src.shape
new_w, new_h = scale_down((w, h), size)
x0 = int((w - new_w) / 2)
y0 = int((h - new_h) / 2)
out = fixed_crop(src, x0, y0, new_w, new_h, size, interp)
return out, (x0, y0, new_w, new_h)
def color_normalize(src, mean, std=None):
"""Normalize src with mean and std."""
src -= mean
if std is not None:
src /= std
return src
def random_size_crop(src, size, min_area, ratio, interp=2):
"""Randomly crop src with size. Randomize area and aspect ratio."""
h, w, _ = src.shape
new_ratio = random.uniform(*ratio)
if new_ratio * h > w:
max_area = w * int(w / new_ratio)
else:
max_area = h * int(h * new_ratio)
min_area *= h * w
if max_area < min_area:
return random_crop(src, size, interp)
new_area = random.uniform(min_area, max_area)
new_w = int(np.sqrt(new_area * new_ratio))
new_h = int(np.sqrt(new_area / new_ratio))
assert new_w <= w and new_h <= h
x0 = random.randint(0, w - new_w)
y0 = random.randint(0, h - new_h)
out = fixed_crop(src, x0, y0, new_w, new_h, size, interp)
return out, (x0, y0, new_w, new_h)
def ResizeAug(size, interp=2):
"""Make resize shorter edge to size augmenter."""
def aug(src):
"""Augmenter body"""
return [resize_short(src, size, interp)]
return aug
def RandomCropAug(size, interp=2):
"""Make random crop augmenter"""
def aug(src):
"""Augmenter body"""
return [random_crop(src, size, interp)[0]]
return aug
def RandomSizedCropAug(size, min_area, ratio, interp=2):
"""Make random crop with random resizing and random aspect ratio jitter augmenter."""
def aug(src):
"""Augmenter body"""
return [random_size_crop(src, size, min_area, ratio, interp)[0]]
return aug
def CenterCropAug(size, interp=2):
"""Make center crop augmenter."""
def aug(src):
"""Augmenter body"""
return [center_crop(src, size, interp)[0]]
return aug
def RandomOrderAug(ts):
"""Apply list of augmenters in random order"""
def aug(src):
"""Augmenter body"""
src = [src]
random.shuffle(ts)
for t in ts:
src = [j for i in src for j in t(i)]
return src
return aug
def ColorJitterAug(brightness, contrast, saturation):
"""Apply random brightness, contrast and saturation jitter in random order."""
ts = []
coef = nd.array([[[0.299, 0.587, 0.114]]])
if brightness > 0:
def baug(src):
"""Augmenter body"""
alpha = 1.0 + random.uniform(-brightness, brightness)
src *= alpha
return [src]
ts.append(baug)
if contrast > 0:
def caug(src):
"""Augmenter body"""
alpha = 1.0 + random.uniform(-contrast, contrast)
gray = src * coef
gray = (3.0 * (1.0 - alpha) / gray.size) * nd.sum(gray)
src *= alpha
src += gray
return [src]
ts.append(caug)
if saturation > 0:
def saug(src):
"""Augmenter body"""
alpha = 1.0 + random.uniform(-saturation, saturation)
gray = src * coef
gray = nd.sum(gray, axis=2, keepdims=True)
gray *= (1.0 - alpha)
src *= alpha
src += gray
return [src]
ts.append(saug)
return RandomOrderAug(ts)
def LightingAug(alphastd, eigval, eigvec):
"""Add PCA based noise."""
def aug(src):
"""Augmenter body"""
alpha = np.random.normal(0, alphastd, size=(3,))
rgb = np.dot(eigvec * alpha, eigval)
src += nd.array(rgb)
return [src]
return aug
def ColorNormalizeAug(mean, std):
"""Mean and std normalization."""
mean = nd.array(mean)
std = nd.array(std)
def aug(src):
"""Augmenter body"""
return [color_normalize(src, mean, std)]
return aug
def HorizontalFlipAug(p):
"""Random horizontal flipping."""
def aug(src):
"""Augmenter body"""
if random.random() < p:
src = nd.flip(src, axis=1)
return [src]
return aug
def CastAug():
"""Cast to float32"""
def aug(src):
"""Augmenter body"""
src = src.astype(np.float32)
return [src]
return aug
def CreateAugmenter(data_shape, resize=0, rand_crop=False, rand_resize=False, rand_mirror=False,
mean=None, std=None, brightness=0, contrast=0, saturation=0,
pca_noise=0, inter_method=2):
"""Creates an augmenter list."""
auglist = []
if resize > 0:
auglist.append(ResizeAug(resize, inter_method))
crop_size = (data_shape[2], data_shape[1])
if rand_resize:
assert rand_crop
auglist.append(RandomSizedCropAug(crop_size, 0.3, (3.0 / 4.0, 4.0 / 3.0), inter_method))
elif rand_crop:
auglist.append(RandomCropAug(crop_size, inter_method))
else:
auglist.append(CenterCropAug(crop_size, inter_method))
if rand_mirror:
auglist.append(HorizontalFlipAug(0.5))
auglist.append(CastAug())
if brightness or contrast or saturation:
auglist.append(ColorJitterAug(brightness, contrast, saturation))
if pca_noise > 0:
eigval = np.array([55.46, 4.794, 1.148])
eigvec = np.array([[-0.5675, 0.7192, 0.4009],
[-0.5808, -0.0045, -0.8140],
[-0.5836, -0.6948, 0.4203]])
auglist.append(LightingAug(pca_noise, eigval, eigvec))
if mean is True:
mean = np.array([123.68, 116.28, 103.53])
elif mean is not None:
assert isinstance(mean, np.ndarray) and mean.shape[0] in [1, 3]
if std is True:
std = np.array([58.395, 57.12, 57.375])
elif std is not None:
assert isinstance(std, np.ndarray) and std.shape[0] in [1, 3]
if mean is not None and std is not None:
auglist.append(ColorNormalizeAug(mean, std))
return auglist
class ImageIter(io.DataIter):
"""Image data iterator with a large number of augmentation choices.
This iterator supports reading from both .rec files and raw image files.
To load input images from .rec files, use `path_imgrec` parameter and to load from raw image
files, use `path_imglist` and `path_root` parameters.
To use data partition (for distributed training) or shuffling, specify `path_imgidx` parameter.
Parameters
----------
batch_size : int
Number of examples per batch.
data_shape : tuple
Data shape in (channels, height, width) format.
For now, only RGB image with 3 channels is supported.
label_width : int, optional
Number of labels per example. The default label width is 1.
path_imgrec : str
Path to image record file (.rec).
Created with tools/im2rec.py or bin/im2rec.
path_imglist : str
Path to image list (.lst).
Created with tools/im2rec.py or with custom script.
Format: Tab separated record of index, one or more labels and relative_path_from_root.
imglist: list
A list of images with the label(s).
Each item is a list [imagelabel: float or list of float, imgpath].
path_root : str
Root folder of image files.
path_imgidx : str
Path to image index file. Needed for partition and shuffling when using .rec source.
shuffle : bool
Whether to shuffle all images at the start of each iteration or not.
Can be slow for HDD.
part_index : int
Partition index.
num_parts : int
Total number of partitions.
data_name : str
Data name for provided symbols.
label_name : str
Label name for provided symbols.
kwargs : ...
More arguments for creating augmenter. See mx.image.CreateAugmenter.
"""
def __init__(self, batch_size, data_shape, label_width=1,
path_imgrec=None, path_imglist=None, path_root=None, path_imgidx=None,
shuffle=False, part_index=0, num_parts=1, aug_list=None, imglist=None,
data_name='data', label_name='softmax_label', **kwargs):
super(ImageIter, self).__init__()
assert path_imgrec or path_imglist or (isinstance(imglist, list))
if path_imgrec:
print('loading recordio...')
if path_imgidx:
self.imgrec = recordio.MXIndexedRecordIO(path_imgidx, path_imgrec, 'r') # pylint: disable=redefined-variable-type
self.imgidx = list(self.imgrec.keys)
else:
self.imgrec = recordio.MXRecordIO(path_imgrec, 'r') # pylint: disable=redefined-variable-type
self.imgidx = None
else:
self.imgrec = None
if path_imglist:
print('loading image list...')
with open(path_imglist) as fin:
imglist = {}
imgkeys = []
for line in iter(fin.readline, ''):
line = line.strip().split('\t')
label = nd.array([float(i) for i in line[1:-1]])
key = int(line[0])
imglist[key] = (label, line[-1])
imgkeys.append(key)
self.imglist = imglist
elif isinstance(imglist, list):
print('loading image list...')
result = {}
imgkeys = []
index = 1
for img in imglist:
key = str(index) # pylint: disable=redefined-variable-type
index += 1
if isinstance(img[0], numeric_types):
label = nd.array([img[0]])
else:
label = nd.array(img[0])
result[key] = (label, img[1])
imgkeys.append(str(key))
self.imglist = result
else:
self.imglist = None
self.path_root = path_root
self.check_data_shape(data_shape)
self.provide_data = [(data_name, (batch_size,) + data_shape)]
if label_width > 1:
self.provide_label = [(label_name, (batch_size, label_width))]
else:
self.provide_label = [(label_name, (batch_size,))]
self.batch_size = batch_size
self.data_shape = data_shape
self.label_width = label_width
self.shuffle = shuffle
if self.imgrec is None:
self.seq = imgkeys
elif shuffle or num_parts > 1:
assert self.imgidx is not None
self.seq = self.imgidx
else:
self.seq = None
if num_parts > 1:
assert part_index < num_parts
N = len(self.seq)
C = N / num_parts
self.seq = self.seq[part_index * C:(part_index + 1) * C]
if aug_list is None:
self.auglist = CreateAugmenter(data_shape, **kwargs)
else:
self.auglist = aug_list
self.cur = 0
self.reset()
def reset(self):
"""Resets the iterator to the beginning of the data."""
if self.shuffle:
random.shuffle(self.seq)
if self.imgrec is not None:
self.imgrec.reset()
self.cur = 0
def next_sample(self):
"""Helper function for reading in next sample."""
if self.seq is not None:
if self.cur >= len(self.seq):
raise StopIteration
idx = self.seq[self.cur]
self.cur += 1
if self.imgrec is not None:
s = self.imgrec.read_idx(idx)
header, img = recordio.unpack(s)
if self.imglist is None:
return header.label, img
else:
return self.imglist[idx][0], img
else:
label, fname = self.imglist[idx]
return label, self.read_image(fname)
else:
s = self.imgrec.read()
if s is None:
raise StopIteration
header, img = recordio.unpack(s)
return header.label, img
def next(self):
"""Returns the next batch of data."""
batch_size = self.batch_size
c, h, w = self.data_shape
batch_data = nd.empty((batch_size, c, h, w))
batch_label = nd.empty(self.provide_label[0][1])
i = 0
try:
while i < batch_size:
label, s = self.next_sample()
data = [self.imdecode(s)]
try:
self.check_valid_image(data)
except RuntimeError as e:
logging.debug('Invalid image, skipping: %s', str(e))
continue
data = self.augmentation_transform(data)
for datum in data:
assert i < batch_size, 'Batch size must be multiples of augmenter output length'
batch_data[i][:] = self.postprocess_data(datum)
batch_label[i][:] = label
i += 1
except StopIteration:
if not i:
raise StopIteration
return io.DataBatch([batch_data], [batch_label], batch_size - i)
def check_data_shape(self, data_shape):
"""Checks if the input data shape is valid"""
if not len(data_shape) == 3:
raise ValueError('data_shape should have length 3, with dimensions CxHxW')
if not data_shape[0] == 3:
raise ValueError('This iterator expects inputs to have 3 channels.')
def check_valid_image(self, data):
"""Checks if the input data is valid"""
if len(data[0].shape) == 0:
raise RuntimeError('Data shape is wrong')
def imdecode(self, s):
"""Decodes a string or byte string to an NDArray.
See mx.img.imdecode for more details."""
return imdecode(s)
def read_image(self, fname):
"""Reads an input image `fname` and returns the decoded raw bytes.
Example usage:
----------
>>> dataIter.read_image('Face.jpg') # returns decoded raw bytes.
'\xff\xd8\xff\xe0\x00...'
"""
with open(os.path.join(self.path_root, fname), 'rb') as fin:
img = fin.read()
return img
def augmentation_transform(self, data):
"""Transforms input data with specified augmentation."""
for aug in self.auglist:
data = [ret for src in data for ret in aug(src)]
return data
def postprocess_data(self, datum):
"""Final postprocessing step before image is loaded into the batch."""
return nd.transpose(datum, axes=(2, 0, 1))
| 31.666667 | 130 | 0.588473 |
from __future__ import absolute_import, print_function
import os
import random
import logging
import numpy as np
try:
import cv2
except ImportError:
cv2 = None
from .base import numeric_types
from . import ndarray as nd
from . import _ndarray_internal as _internal
from ._ndarray_internal import _cvimresize as imresize
from ._ndarray_internal import _cvcopyMakeBorder as copyMakeBorder
from . import io
from . import recordio
def imdecode(buf, **kwargs):
if not isinstance(buf, nd.NDArray):
buf = nd.array(np.frombuffer(buf, dtype=np.uint8), dtype=np.uint8)
return _internal._cvimdecode(buf, **kwargs)
def scale_down(src_size, size):
w, h = size
sw, sh = src_size
if sh < h:
w, h = float(w * sh) / h, sh
if sw < w:
w, h = sw, float(h * sw) / w
return int(w), int(h)
def resize_short(src, size, interp=2):
h, w, _ = src.shape
if h > w:
new_h, new_w = size * h / w, size
else:
new_h, new_w = size, size * w / h
return imresize(src, new_w, new_h, interp=interp)
def fixed_crop(src, x0, y0, w, h, size=None, interp=2):
out = nd.crop(src, begin=(y0, x0, 0), end=(y0 + h, x0 + w, int(src.shape[2])))
if size is not None and (w, h) != size:
out = imresize(out, *size, interp=interp)
return out
def random_crop(src, size, interp=2):
h, w, _ = src.shape
new_w, new_h = scale_down((w, h), size)
x0 = random.randint(0, w - new_w)
y0 = random.randint(0, h - new_h)
out = fixed_crop(src, x0, y0, new_w, new_h, size, interp)
return out, (x0, y0, new_w, new_h)
def center_crop(src, size, interp=2):
h, w, _ = src.shape
new_w, new_h = scale_down((w, h), size)
x0 = int((w - new_w) / 2)
y0 = int((h - new_h) / 2)
out = fixed_crop(src, x0, y0, new_w, new_h, size, interp)
return out, (x0, y0, new_w, new_h)
def color_normalize(src, mean, std=None):
src -= mean
if std is not None:
src /= std
return src
def random_size_crop(src, size, min_area, ratio, interp=2):
h, w, _ = src.shape
new_ratio = random.uniform(*ratio)
if new_ratio * h > w:
max_area = w * int(w / new_ratio)
else:
max_area = h * int(h * new_ratio)
min_area *= h * w
if max_area < min_area:
return random_crop(src, size, interp)
new_area = random.uniform(min_area, max_area)
new_w = int(np.sqrt(new_area * new_ratio))
new_h = int(np.sqrt(new_area / new_ratio))
assert new_w <= w and new_h <= h
x0 = random.randint(0, w - new_w)
y0 = random.randint(0, h - new_h)
out = fixed_crop(src, x0, y0, new_w, new_h, size, interp)
return out, (x0, y0, new_w, new_h)
def ResizeAug(size, interp=2):
def aug(src):
return [resize_short(src, size, interp)]
return aug
def RandomCropAug(size, interp=2):
def aug(src):
return [random_crop(src, size, interp)[0]]
return aug
def RandomSizedCropAug(size, min_area, ratio, interp=2):
def aug(src):
return [random_size_crop(src, size, min_area, ratio, interp)[0]]
return aug
def CenterCropAug(size, interp=2):
def aug(src):
return [center_crop(src, size, interp)[0]]
return aug
def RandomOrderAug(ts):
def aug(src):
src = [src]
random.shuffle(ts)
for t in ts:
src = [j for i in src for j in t(i)]
return src
return aug
def ColorJitterAug(brightness, contrast, saturation):
ts = []
coef = nd.array([[[0.299, 0.587, 0.114]]])
if brightness > 0:
def baug(src):
alpha = 1.0 + random.uniform(-brightness, brightness)
src *= alpha
return [src]
ts.append(baug)
if contrast > 0:
def caug(src):
alpha = 1.0 + random.uniform(-contrast, contrast)
gray = src * coef
gray = (3.0 * (1.0 - alpha) / gray.size) * nd.sum(gray)
src *= alpha
src += gray
return [src]
ts.append(caug)
if saturation > 0:
def saug(src):
alpha = 1.0 + random.uniform(-saturation, saturation)
gray = src * coef
gray = nd.sum(gray, axis=2, keepdims=True)
gray *= (1.0 - alpha)
src *= alpha
src += gray
return [src]
ts.append(saug)
return RandomOrderAug(ts)
def LightingAug(alphastd, eigval, eigvec):
def aug(src):
alpha = np.random.normal(0, alphastd, size=(3,))
rgb = np.dot(eigvec * alpha, eigval)
src += nd.array(rgb)
return [src]
return aug
def ColorNormalizeAug(mean, std):
mean = nd.array(mean)
std = nd.array(std)
def aug(src):
return [color_normalize(src, mean, std)]
return aug
def HorizontalFlipAug(p):
def aug(src):
if random.random() < p:
src = nd.flip(src, axis=1)
return [src]
return aug
def CastAug():
def aug(src):
src = src.astype(np.float32)
return [src]
return aug
def CreateAugmenter(data_shape, resize=0, rand_crop=False, rand_resize=False, rand_mirror=False,
mean=None, std=None, brightness=0, contrast=0, saturation=0,
pca_noise=0, inter_method=2):
auglist = []
if resize > 0:
auglist.append(ResizeAug(resize, inter_method))
crop_size = (data_shape[2], data_shape[1])
if rand_resize:
assert rand_crop
auglist.append(RandomSizedCropAug(crop_size, 0.3, (3.0 / 4.0, 4.0 / 3.0), inter_method))
elif rand_crop:
auglist.append(RandomCropAug(crop_size, inter_method))
else:
auglist.append(CenterCropAug(crop_size, inter_method))
if rand_mirror:
auglist.append(HorizontalFlipAug(0.5))
auglist.append(CastAug())
if brightness or contrast or saturation:
auglist.append(ColorJitterAug(brightness, contrast, saturation))
if pca_noise > 0:
eigval = np.array([55.46, 4.794, 1.148])
eigvec = np.array([[-0.5675, 0.7192, 0.4009],
[-0.5808, -0.0045, -0.8140],
[-0.5836, -0.6948, 0.4203]])
auglist.append(LightingAug(pca_noise, eigval, eigvec))
if mean is True:
mean = np.array([123.68, 116.28, 103.53])
elif mean is not None:
assert isinstance(mean, np.ndarray) and mean.shape[0] in [1, 3]
if std is True:
std = np.array([58.395, 57.12, 57.375])
elif std is not None:
assert isinstance(std, np.ndarray) and std.shape[0] in [1, 3]
if mean is not None and std is not None:
auglist.append(ColorNormalizeAug(mean, std))
return auglist
class ImageIter(io.DataIter):
def __init__(self, batch_size, data_shape, label_width=1,
path_imgrec=None, path_imglist=None, path_root=None, path_imgidx=None,
shuffle=False, part_index=0, num_parts=1, aug_list=None, imglist=None,
data_name='data', label_name='softmax_label', **kwargs):
super(ImageIter, self).__init__()
assert path_imgrec or path_imglist or (isinstance(imglist, list))
if path_imgrec:
print('loading recordio...')
if path_imgidx:
self.imgrec = recordio.MXIndexedRecordIO(path_imgidx, path_imgrec, 'r')
self.imgidx = list(self.imgrec.keys)
else:
self.imgrec = recordio.MXRecordIO(path_imgrec, 'r')
self.imgidx = None
else:
self.imgrec = None
if path_imglist:
print('loading image list...')
with open(path_imglist) as fin:
imglist = {}
imgkeys = []
for line in iter(fin.readline, ''):
line = line.strip().split('\t')
label = nd.array([float(i) for i in line[1:-1]])
key = int(line[0])
imglist[key] = (label, line[-1])
imgkeys.append(key)
self.imglist = imglist
elif isinstance(imglist, list):
print('loading image list...')
result = {}
imgkeys = []
index = 1
for img in imglist:
key = str(index)
index += 1
if isinstance(img[0], numeric_types):
label = nd.array([img[0]])
else:
label = nd.array(img[0])
result[key] = (label, img[1])
imgkeys.append(str(key))
self.imglist = result
else:
self.imglist = None
self.path_root = path_root
self.check_data_shape(data_shape)
self.provide_data = [(data_name, (batch_size,) + data_shape)]
if label_width > 1:
self.provide_label = [(label_name, (batch_size, label_width))]
else:
self.provide_label = [(label_name, (batch_size,))]
self.batch_size = batch_size
self.data_shape = data_shape
self.label_width = label_width
self.shuffle = shuffle
if self.imgrec is None:
self.seq = imgkeys
elif shuffle or num_parts > 1:
assert self.imgidx is not None
self.seq = self.imgidx
else:
self.seq = None
if num_parts > 1:
assert part_index < num_parts
N = len(self.seq)
C = N / num_parts
self.seq = self.seq[part_index * C:(part_index + 1) * C]
if aug_list is None:
self.auglist = CreateAugmenter(data_shape, **kwargs)
else:
self.auglist = aug_list
self.cur = 0
self.reset()
def reset(self):
if self.shuffle:
random.shuffle(self.seq)
if self.imgrec is not None:
self.imgrec.reset()
self.cur = 0
def next_sample(self):
if self.seq is not None:
if self.cur >= len(self.seq):
raise StopIteration
idx = self.seq[self.cur]
self.cur += 1
if self.imgrec is not None:
s = self.imgrec.read_idx(idx)
header, img = recordio.unpack(s)
if self.imglist is None:
return header.label, img
else:
return self.imglist[idx][0], img
else:
label, fname = self.imglist[idx]
return label, self.read_image(fname)
else:
s = self.imgrec.read()
if s is None:
raise StopIteration
header, img = recordio.unpack(s)
return header.label, img
def next(self):
batch_size = self.batch_size
c, h, w = self.data_shape
batch_data = nd.empty((batch_size, c, h, w))
batch_label = nd.empty(self.provide_label[0][1])
i = 0
try:
while i < batch_size:
label, s = self.next_sample()
data = [self.imdecode(s)]
try:
self.check_valid_image(data)
except RuntimeError as e:
logging.debug('Invalid image, skipping: %s', str(e))
continue
data = self.augmentation_transform(data)
for datum in data:
assert i < batch_size, 'Batch size must be multiples of augmenter output length'
batch_data[i][:] = self.postprocess_data(datum)
batch_label[i][:] = label
i += 1
except StopIteration:
if not i:
raise StopIteration
return io.DataBatch([batch_data], [batch_label], batch_size - i)
def check_data_shape(self, data_shape):
if not len(data_shape) == 3:
raise ValueError('data_shape should have length 3, with dimensions CxHxW')
if not data_shape[0] == 3:
raise ValueError('This iterator expects inputs to have 3 channels.')
def check_valid_image(self, data):
if len(data[0].shape) == 0:
raise RuntimeError('Data shape is wrong')
def imdecode(self, s):
return imdecode(s)
def read_image(self, fname):
with open(os.path.join(self.path_root, fname), 'rb') as fin:
img = fin.read()
return img
def augmentation_transform(self, data):
for aug in self.auglist:
data = [ret for src in data for ret in aug(src)]
return data
def postprocess_data(self, datum):
return nd.transpose(datum, axes=(2, 0, 1))
| true | true |
f71058b38f7fbd38e77a131f05712abc41a0e552 | 1,539 | py | Python | mqtt-servers/server2.py | pranaypareek/cc | 1d8ee42d3bbe5295543ad0119053baf1cfdbd7d3 | [
"Apache-2.0"
] | null | null | null | mqtt-servers/server2.py | pranaypareek/cc | 1d8ee42d3bbe5295543ad0119053baf1cfdbd7d3 | [
"Apache-2.0"
] | null | null | null | mqtt-servers/server2.py | pranaypareek/cc | 1d8ee42d3bbe5295543ad0119053baf1cfdbd7d3 | [
"Apache-2.0"
] | null | null | null | """
A small Test application to show how to use Flask-MQTT.
"""
import eventlet
import json
from flask import Flask, render_template
from flask_mqtt import Mqtt
from flask_socketio import SocketIO
from flask_bootstrap import Bootstrap
eventlet.monkey_patch()
app = Flask(__name__)
app.config['SECRET'] = 'my secret key'
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['MQTT_BROKER_URL'] = 'broker.hivemq.com'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = ''
app.config['MQTT_PASSWORD'] = ''
app.config['MQTT_KEEPALIVE'] = 5
app.config['MQTT_TLS_ENABLED'] = False
mqtt = Mqtt(app)
socketio = SocketIO(app)
bootstrap = Bootstrap(app)
@socketio.on('publish')
def handle_publish(json_str):
data = json.loads(json_str)
#mqtt.publish(data['topic'], data['message'])
@socketio.on('subscribe')
def handle_subscribe(json_str):
data = json.loads(json_str)
#mqtt.subscribe(data['topic'])
@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
data = dict(
topic=message.topic,
payload=message.payload.decode()
)
print('Server 2: Received message', data['payload'], 'from topic: ', data['topic'])
socketio.emit('mqtt_message', data=data)
@mqtt.on_log()
def handle_logging(client, userdata, level, buf):
print(level, buf)
if __name__ == '__main__':
#print('Server 2: subscribing to rmpbpp')
#socketio.emit('subscribe', None)
mqtt.subscribe('channel01')
socketio.run(app, host='0.0.0.0', port=5001, use_reloader=True, debug=True)
| 26.534483 | 87 | 0.7141 |
import eventlet
import json
from flask import Flask, render_template
from flask_mqtt import Mqtt
from flask_socketio import SocketIO
from flask_bootstrap import Bootstrap
eventlet.monkey_patch()
app = Flask(__name__)
app.config['SECRET'] = 'my secret key'
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['MQTT_BROKER_URL'] = 'broker.hivemq.com'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = ''
app.config['MQTT_PASSWORD'] = ''
app.config['MQTT_KEEPALIVE'] = 5
app.config['MQTT_TLS_ENABLED'] = False
mqtt = Mqtt(app)
socketio = SocketIO(app)
bootstrap = Bootstrap(app)
@socketio.on('publish')
def handle_publish(json_str):
data = json.loads(json_str)
@socketio.on('subscribe')
def handle_subscribe(json_str):
data = json.loads(json_str)
@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
data = dict(
topic=message.topic,
payload=message.payload.decode()
)
print('Server 2: Received message', data['payload'], 'from topic: ', data['topic'])
socketio.emit('mqtt_message', data=data)
@mqtt.on_log()
def handle_logging(client, userdata, level, buf):
print(level, buf)
if __name__ == '__main__':
mqtt.subscribe('channel01')
socketio.run(app, host='0.0.0.0', port=5001, use_reloader=True, debug=True)
| true | true |
f7105bfdf7b8d86c2077099103949015886a8533 | 15,565 | py | Python | Detection/MtcnnDetector.py | qma16443/AIcamp_MTCNN | 431c3ce1cabf24266690322d525bdf7133666dc0 | [
"MIT"
] | null | null | null | Detection/MtcnnDetector.py | qma16443/AIcamp_MTCNN | 431c3ce1cabf24266690322d525bdf7133666dc0 | [
"MIT"
] | null | null | null | Detection/MtcnnDetector.py | qma16443/AIcamp_MTCNN | 431c3ce1cabf24266690322d525bdf7133666dc0 | [
"MIT"
] | null | null | null | import cv2
import time
import numpy as np
import sys
sys.path.append("../")
from train_models.MTCNN_config import config
from Detection.nms import py_nms
class MtcnnDetector(object):
def __init__(self,
detectors,
min_face_size=25,
stride=2,
threshold=[0.6, 0.7, 0.7],
scale_factor=0.79,
#scale_factor=0.709,#change
slide_window=False):
self.pnet_detector = detectors[0]
self.rnet_detector = detectors[1]
self.onet_detector = detectors[2]
self.min_face_size = min_face_size
self.stride = stride
self.thresh = threshold
self.scale_factor = scale_factor
self.slide_window = slide_window
def convert_to_square(self, bbox):
"""
convert bbox to square
Parameters:
----------
bbox: numpy array , shape n x 5
input bbox
Returns:
-------
square bbox
"""
square_bbox = bbox.copy()
h = bbox[:, 3] - bbox[:, 1] + 1
w = bbox[:, 2] - bbox[:, 0] + 1
max_side = np.maximum(h, w)
square_bbox[:, 0] = bbox[:, 0] + w * 0.5 - max_side * 0.5
square_bbox[:, 1] = bbox[:, 1] + h * 0.5 - max_side * 0.5
square_bbox[:, 2] = square_bbox[:, 0] + max_side - 1
square_bbox[:, 3] = square_bbox[:, 1] + max_side - 1
return square_bbox
def calibrate_box(self, bbox, reg):
"""
calibrate bboxes
Parameters:
----------
bbox: numpy array, shape n x 5
input bboxes
reg: numpy array, shape n x 4
bboxes adjustment
Returns:
-------
bboxes after refinement
"""
bbox_c = bbox.copy()
w = bbox[:, 2] - bbox[:, 0] + 1
w = np.expand_dims(w, 1)
h = bbox[:, 3] - bbox[:, 1] + 1
h = np.expand_dims(h, 1)
reg_m = np.hstack([w, h, w, h])
aug = reg_m * reg
bbox_c[:, 0:4] = bbox_c[:, 0:4] + aug
return bbox_c
def generate_bbox(self, cls_map, reg, scale, threshold):
"""
generate bbox from feature cls_map
Parameters:
----------
cls_map: numpy array , n x m
detect score for each position
reg: numpy array , n x m x 4
bbox
scale: float number
scale of this detection
threshold: float number
detect threshold
Returns:
-------
bbox array
"""
stride = 2
#stride = 4
cellsize = 12
#cellsize = 25
t_index = np.where(cls_map > threshold)
# find nothing
if t_index[0].size == 0:
return np.array([])
#offset
dx1, dy1, dx2, dy2 = [reg[t_index[0], t_index[1], i] for i in range(4)]
reg = np.array([dx1, dy1, dx2, dy2])
score = cls_map[t_index[0], t_index[1]]
boundingbox = np.vstack([np.round((stride * t_index[1]) / scale),
np.round((stride * t_index[0]) / scale),
np.round((stride * t_index[1] + cellsize) / scale),
np.round((stride * t_index[0] + cellsize) / scale),
score,
reg])
return boundingbox.T
#pre-process images
def processed_image(self, img, scale):
height, width, channels = img.shape
new_height = int(height * scale) # resized new height
new_width = int(width * scale) # resized new width
new_dim = (new_width, new_height)
img_resized = cv2.resize(img, new_dim, interpolation=cv2.INTER_LINEAR) # resized image
img_resized = (img_resized - 127.5) / 128
return img_resized
def pad(self, bboxes, w, h):
"""
pad the the bboxes, alse restrict the size of it
Parameters:
----------
bboxes: numpy array, n x 5
input bboxes
w: float number
width of the input image
h: float number
height of the input image
Returns :
------
dy, dx : numpy array, n x 1
start point of the bbox in target image
edy, edx : numpy array, n x 1
end point of the bbox in target image
y, x : numpy array, n x 1
start point of the bbox in original image
ex, ex : numpy array, n x 1
end point of the bbox in original image
tmph, tmpw: numpy array, n x 1
height and width of the bbox
"""
tmpw, tmph = bboxes[:, 2] - bboxes[:, 0] + 1, bboxes[:, 3] - bboxes[:, 1] + 1
num_box = bboxes.shape[0]
dx, dy = np.zeros((num_box,)), np.zeros((num_box,))
edx, edy = tmpw.copy() - 1, tmph.copy() - 1
x, y, ex, ey = bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 3]
tmp_index = np.where(ex > w - 1)
edx[tmp_index] = tmpw[tmp_index] + w - 2 - ex[tmp_index]
ex[tmp_index] = w - 1
tmp_index = np.where(ey > h - 1)
edy[tmp_index] = tmph[tmp_index] + h - 2 - ey[tmp_index]
ey[tmp_index] = h - 1
tmp_index = np.where(x < 0)
dx[tmp_index] = 0 - x[tmp_index]
x[tmp_index] = 0
tmp_index = np.where(y < 0)
dy[tmp_index] = 0 - y[tmp_index]
y[tmp_index] = 0
return_list = [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph]
return_list = [item.astype(np.int32) for item in return_list]
return return_list
def detect_pnet(self, im):
"""Get face candidates through pnet
Parameters:
----------
im: numpy array
input image array
Returns:
-------
boxes: numpy array
detected boxes before calibration
boxes_c: numpy array
boxes after calibration
"""
h, w, c = im.shape
net_size = 12
current_scale = float(net_size) / self.min_face_size # find initial scale
# print("current_scale", net_size, self.min_face_size, current_scale)
im_resized = self.processed_image(im, current_scale)
current_height, current_width, _ = im_resized.shape
# fcn
all_boxes = list()
while min(current_height, current_width) > net_size:
#return the result predicted by pnet
#cls_cls_map : H*w*2
#reg: H*w*4
cls_cls_map, reg = self.pnet_detector.predict(im_resized)
#boxes: num*9(x1,y1,x2,y2,score,x1_offset,y1_offset,x2_offset,y2_offset)
boxes = self.generate_bbox(cls_cls_map[:, :,1], reg, current_scale, self.thresh[0])
current_scale *= self.scale_factor
im_resized = self.processed_image(im, current_scale)
current_height, current_width, _ = im_resized.shape
if boxes.size == 0:
continue
keep = py_nms(boxes[:, :5], 0.5, 'Union')
boxes = boxes[keep]
all_boxes.append(boxes)
if len(all_boxes) == 0:
return None, None, None
all_boxes = np.vstack(all_boxes)
# merge the detection from first stage
keep = py_nms(all_boxes[:, 0:5], 0.7, 'Union')
all_boxes = all_boxes[keep]
boxes = all_boxes[:, :5]
bbw = all_boxes[:, 2] - all_boxes[:, 0] + 1
bbh = all_boxes[:, 3] - all_boxes[:, 1] + 1
# refine the boxes
boxes_c = np.vstack([all_boxes[:, 0] + all_boxes[:, 5] * bbw,
all_boxes[:, 1] + all_boxes[:, 6] * bbh,
all_boxes[:, 2] + all_boxes[:, 7] * bbw,
all_boxes[:, 3] + all_boxes[:, 8] * bbh,
all_boxes[:, 4]])
boxes_c = boxes_c.T
return boxes, boxes_c, None
def detect_rnet(self, im, dets):
"""Get face candidates using rnet
Parameters:
----------
im: numpy array
input image array
dets: numpy array
detection results of pnet
Returns:
-------
boxes: numpy array
detected boxes before calibration
boxes_c: numpy array
boxes after calibration
"""
h, w, c = im.shape
dets = self.convert_to_square(dets)
dets[:, 0:4] = np.round(dets[:, 0:4])
[dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(dets, w, h)
num_boxes = dets.shape[0]
cropped_ims = np.zeros((num_boxes, 24, 24, 3), dtype=np.float32)
for i in range(num_boxes):
tmp = np.zeros((tmph[i], tmpw[i], 3), dtype=np.uint8)
tmp[dy[i]:edy[i] + 1, dx[i]:edx[i] + 1, :] = im[y[i]:ey[i] + 1, x[i]:ex[i] + 1, :]
cropped_ims[i, :, :, :] = (cv2.resize(tmp, (24, 24))-127.5) / 128
#cls_scores : num_data*2
#reg: num_data*4
#landmark: num_data*10
cls_scores, reg, _ = self.rnet_detector.predict(cropped_ims)
cls_scores = cls_scores[:,1]
keep_inds = np.where(cls_scores > self.thresh[1])[0]
if len(keep_inds) > 0:
boxes = dets[keep_inds]
boxes[:, 4] = cls_scores[keep_inds]
reg = reg[keep_inds]
#landmark = landmark[keep_inds]
else:
return None, None, None
keep = py_nms(boxes, 0.6)
boxes = boxes[keep]
boxes_c = self.calibrate_box(boxes, reg[keep])
return boxes, boxes_c,None
def detect_onet(self, im, dets):
"""Get face candidates using onet
Parameters:
----------
im: numpy array
input image array
dets: numpy array
detection results of rnet
Returns:
-------
boxes: numpy array
detected boxes before calibration
boxes_c: numpy array
boxes after calibration
"""
h, w, c = im.shape
dets = self.convert_to_square(dets)
dets[:, 0:4] = np.round(dets[:, 0:4])
[dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(dets, w, h)
num_boxes = dets.shape[0]
cropped_ims = np.zeros((num_boxes, 48, 48, 3), dtype=np.float32)
for i in range(num_boxes):
tmp = np.zeros((tmph[i], tmpw[i], 3), dtype=np.uint8)
tmp[dy[i]:edy[i] + 1, dx[i]:edx[i] + 1, :] = im[y[i]:ey[i] + 1, x[i]:ex[i] + 1, :]
cropped_ims[i, :, :, :] = (cv2.resize(tmp, (48, 48))-127.5) / 128
cls_scores, reg,landmark = self.onet_detector.predict(cropped_ims)
#prob belongs to face
cls_scores = cls_scores[:,1]
keep_inds = np.where(cls_scores > self.thresh[2])[0]
if len(keep_inds) > 0:
#pickout filtered box
boxes = dets[keep_inds]
boxes[:, 4] = cls_scores[keep_inds]
reg = reg[keep_inds]
landmark = landmark[keep_inds]
else:
return None, None, None
#width
w = boxes[:,2] - boxes[:,0] + 1
#height
h = boxes[:,3] - boxes[:,1] + 1
landmark[:,0::2] = (np.tile(w,(5,1)) * landmark[:,0::2].T + np.tile(boxes[:,0],(5,1)) - 1).T
landmark[:,1::2] = (np.tile(h,(5,1)) * landmark[:,1::2].T + np.tile(boxes[:,1],(5,1)) - 1).T
boxes_c = self.calibrate_box(boxes, reg)
boxes = boxes[py_nms(boxes, 0.6, "Minimum")]
keep = py_nms(boxes_c, 0.6, "Minimum")
boxes_c = boxes_c[keep]
landmark = landmark[keep]
return boxes, boxes_c,landmark
#use for video
def detect(self, img):
"""Detect face over image
"""
boxes = None
t = time.time()
# pnet
t1 = 0
if self.pnet_detector:
boxes, boxes_c,_ = self.detect_pnet(img)
if boxes_c is None:
return np.array([]),np.array([])
t1 = time.time() - t
t = time.time()
# rnet
t2 = 0
if self.rnet_detector:
boxes, boxes_c,_ = self.detect_rnet(img, boxes_c)
if boxes_c is None:
return np.array([]),np.array([])
t2 = time.time() - t
t = time.time()
# onet
t3 = 0
if self.onet_detector:
boxes, boxes_c,landmark = self.detect_onet(img, boxes_c)
if boxes_c is None:
return np.array([]),np.array([])
t3 = time.time() - t
t = time.time()
print(
"time cost " + '{:.3f}'.format(t1 + t2 + t3) + ' pnet {:.3f} rnet {:.3f} onet {:.3f}'.format(t1, t2,
t3))
return boxes_c,landmark
def detect_face(self, test_data):
all_boxes = []#save each image's bboxes
landmarks = []
batch_idx = 0
sum_time = 0
#test_data is iter_
for databatch in test_data:
#databatch(image returned)
if batch_idx % 100 == 0:
print("%d images done" % batch_idx)
im = databatch
# pnet
t1 = 0
if self.pnet_detector:
t = time.time()
#ignore landmark
boxes, boxes_c, landmark = self.detect_pnet(im)
t1 = time.time() - t
sum_time += t1
if boxes_c is None:
print("boxes_c is None...")
all_boxes.append(np.array([]))
#pay attention
landmarks.append(np.array([]))
batch_idx += 1
continue
# rnet
t2 = 0
if self.rnet_detector:
t = time.time()
#ignore landmark
boxes, boxes_c, landmark = self.detect_rnet(im, boxes_c)
t2 = time.time() - t
sum_time += t2
if boxes_c is None:
all_boxes.append(np.array([]))
landmarks.append(np.array([]))
batch_idx += 1
continue
# onet
t3 = 0
if self.onet_detector:
t = time.time()
boxes, boxes_c, landmark = self.detect_onet(im, boxes_c)
t3 = time.time() - t
sum_time += t3
if boxes_c is None:
all_boxes.append(np.array([]))
landmarks.append(np.array([]))
batch_idx += 1
continue
print(
"time cost " + '{:.3f}'.format(sum_time) + ' pnet {:.3f} rnet {:.3f} onet {:.3f}'.format(t1, t2,t3))
all_boxes.append(boxes_c)
landmarks.append(landmark)
batch_idx += 1
#num_of_data*9,num_of_data*10
return all_boxes,landmarks
| 34.743304 | 123 | 0.477739 | import cv2
import time
import numpy as np
import sys
sys.path.append("../")
from train_models.MTCNN_config import config
from Detection.nms import py_nms
class MtcnnDetector(object):
def __init__(self,
detectors,
min_face_size=25,
stride=2,
threshold=[0.6, 0.7, 0.7],
scale_factor=0.79,
slide_window=False):
self.pnet_detector = detectors[0]
self.rnet_detector = detectors[1]
self.onet_detector = detectors[2]
self.min_face_size = min_face_size
self.stride = stride
self.thresh = threshold
self.scale_factor = scale_factor
self.slide_window = slide_window
def convert_to_square(self, bbox):
square_bbox = bbox.copy()
h = bbox[:, 3] - bbox[:, 1] + 1
w = bbox[:, 2] - bbox[:, 0] + 1
max_side = np.maximum(h, w)
square_bbox[:, 0] = bbox[:, 0] + w * 0.5 - max_side * 0.5
square_bbox[:, 1] = bbox[:, 1] + h * 0.5 - max_side * 0.5
square_bbox[:, 2] = square_bbox[:, 0] + max_side - 1
square_bbox[:, 3] = square_bbox[:, 1] + max_side - 1
return square_bbox
def calibrate_box(self, bbox, reg):
bbox_c = bbox.copy()
w = bbox[:, 2] - bbox[:, 0] + 1
w = np.expand_dims(w, 1)
h = bbox[:, 3] - bbox[:, 1] + 1
h = np.expand_dims(h, 1)
reg_m = np.hstack([w, h, w, h])
aug = reg_m * reg
bbox_c[:, 0:4] = bbox_c[:, 0:4] + aug
return bbox_c
def generate_bbox(self, cls_map, reg, scale, threshold):
stride = 2
cellsize = 12
t_index = np.where(cls_map > threshold)
if t_index[0].size == 0:
return np.array([])
dx1, dy1, dx2, dy2 = [reg[t_index[0], t_index[1], i] for i in range(4)]
reg = np.array([dx1, dy1, dx2, dy2])
score = cls_map[t_index[0], t_index[1]]
boundingbox = np.vstack([np.round((stride * t_index[1]) / scale),
np.round((stride * t_index[0]) / scale),
np.round((stride * t_index[1] + cellsize) / scale),
np.round((stride * t_index[0] + cellsize) / scale),
score,
reg])
return boundingbox.T
def processed_image(self, img, scale):
height, width, channels = img.shape
new_height = int(height * scale)
new_width = int(width * scale)
new_dim = (new_width, new_height)
img_resized = cv2.resize(img, new_dim, interpolation=cv2.INTER_LINEAR)
img_resized = (img_resized - 127.5) / 128
return img_resized
def pad(self, bboxes, w, h):
tmpw, tmph = bboxes[:, 2] - bboxes[:, 0] + 1, bboxes[:, 3] - bboxes[:, 1] + 1
num_box = bboxes.shape[0]
dx, dy = np.zeros((num_box,)), np.zeros((num_box,))
edx, edy = tmpw.copy() - 1, tmph.copy() - 1
x, y, ex, ey = bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 3]
tmp_index = np.where(ex > w - 1)
edx[tmp_index] = tmpw[tmp_index] + w - 2 - ex[tmp_index]
ex[tmp_index] = w - 1
tmp_index = np.where(ey > h - 1)
edy[tmp_index] = tmph[tmp_index] + h - 2 - ey[tmp_index]
ey[tmp_index] = h - 1
tmp_index = np.where(x < 0)
dx[tmp_index] = 0 - x[tmp_index]
x[tmp_index] = 0
tmp_index = np.where(y < 0)
dy[tmp_index] = 0 - y[tmp_index]
y[tmp_index] = 0
return_list = [dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph]
return_list = [item.astype(np.int32) for item in return_list]
return return_list
def detect_pnet(self, im):
h, w, c = im.shape
net_size = 12
current_scale = float(net_size) / self.min_face_size
im_resized = self.processed_image(im, current_scale)
current_height, current_width, _ = im_resized.shape
all_boxes = list()
while min(current_height, current_width) > net_size:
cls_cls_map, reg = self.pnet_detector.predict(im_resized)
boxes = self.generate_bbox(cls_cls_map[:, :,1], reg, current_scale, self.thresh[0])
current_scale *= self.scale_factor
im_resized = self.processed_image(im, current_scale)
current_height, current_width, _ = im_resized.shape
if boxes.size == 0:
continue
keep = py_nms(boxes[:, :5], 0.5, 'Union')
boxes = boxes[keep]
all_boxes.append(boxes)
if len(all_boxes) == 0:
return None, None, None
all_boxes = np.vstack(all_boxes)
keep = py_nms(all_boxes[:, 0:5], 0.7, 'Union')
all_boxes = all_boxes[keep]
boxes = all_boxes[:, :5]
bbw = all_boxes[:, 2] - all_boxes[:, 0] + 1
bbh = all_boxes[:, 3] - all_boxes[:, 1] + 1
boxes_c = np.vstack([all_boxes[:, 0] + all_boxes[:, 5] * bbw,
all_boxes[:, 1] + all_boxes[:, 6] * bbh,
all_boxes[:, 2] + all_boxes[:, 7] * bbw,
all_boxes[:, 3] + all_boxes[:, 8] * bbh,
all_boxes[:, 4]])
boxes_c = boxes_c.T
return boxes, boxes_c, None
def detect_rnet(self, im, dets):
h, w, c = im.shape
dets = self.convert_to_square(dets)
dets[:, 0:4] = np.round(dets[:, 0:4])
[dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(dets, w, h)
num_boxes = dets.shape[0]
cropped_ims = np.zeros((num_boxes, 24, 24, 3), dtype=np.float32)
for i in range(num_boxes):
tmp = np.zeros((tmph[i], tmpw[i], 3), dtype=np.uint8)
tmp[dy[i]:edy[i] + 1, dx[i]:edx[i] + 1, :] = im[y[i]:ey[i] + 1, x[i]:ex[i] + 1, :]
cropped_ims[i, :, :, :] = (cv2.resize(tmp, (24, 24))-127.5) / 128
cls_scores, reg, _ = self.rnet_detector.predict(cropped_ims)
cls_scores = cls_scores[:,1]
keep_inds = np.where(cls_scores > self.thresh[1])[0]
if len(keep_inds) > 0:
boxes = dets[keep_inds]
boxes[:, 4] = cls_scores[keep_inds]
reg = reg[keep_inds]
else:
return None, None, None
keep = py_nms(boxes, 0.6)
boxes = boxes[keep]
boxes_c = self.calibrate_box(boxes, reg[keep])
return boxes, boxes_c,None
def detect_onet(self, im, dets):
h, w, c = im.shape
dets = self.convert_to_square(dets)
dets[:, 0:4] = np.round(dets[:, 0:4])
[dy, edy, dx, edx, y, ey, x, ex, tmpw, tmph] = self.pad(dets, w, h)
num_boxes = dets.shape[0]
cropped_ims = np.zeros((num_boxes, 48, 48, 3), dtype=np.float32)
for i in range(num_boxes):
tmp = np.zeros((tmph[i], tmpw[i], 3), dtype=np.uint8)
tmp[dy[i]:edy[i] + 1, dx[i]:edx[i] + 1, :] = im[y[i]:ey[i] + 1, x[i]:ex[i] + 1, :]
cropped_ims[i, :, :, :] = (cv2.resize(tmp, (48, 48))-127.5) / 128
cls_scores, reg,landmark = self.onet_detector.predict(cropped_ims)
cls_scores = cls_scores[:,1]
keep_inds = np.where(cls_scores > self.thresh[2])[0]
if len(keep_inds) > 0:
boxes = dets[keep_inds]
boxes[:, 4] = cls_scores[keep_inds]
reg = reg[keep_inds]
landmark = landmark[keep_inds]
else:
return None, None, None
w = boxes[:,2] - boxes[:,0] + 1
h = boxes[:,3] - boxes[:,1] + 1
landmark[:,0::2] = (np.tile(w,(5,1)) * landmark[:,0::2].T + np.tile(boxes[:,0],(5,1)) - 1).T
landmark[:,1::2] = (np.tile(h,(5,1)) * landmark[:,1::2].T + np.tile(boxes[:,1],(5,1)) - 1).T
boxes_c = self.calibrate_box(boxes, reg)
boxes = boxes[py_nms(boxes, 0.6, "Minimum")]
keep = py_nms(boxes_c, 0.6, "Minimum")
boxes_c = boxes_c[keep]
landmark = landmark[keep]
return boxes, boxes_c,landmark
def detect(self, img):
boxes = None
t = time.time()
t1 = 0
if self.pnet_detector:
boxes, boxes_c,_ = self.detect_pnet(img)
if boxes_c is None:
return np.array([]),np.array([])
t1 = time.time() - t
t = time.time()
t2 = 0
if self.rnet_detector:
boxes, boxes_c,_ = self.detect_rnet(img, boxes_c)
if boxes_c is None:
return np.array([]),np.array([])
t2 = time.time() - t
t = time.time()
t3 = 0
if self.onet_detector:
boxes, boxes_c,landmark = self.detect_onet(img, boxes_c)
if boxes_c is None:
return np.array([]),np.array([])
t3 = time.time() - t
t = time.time()
print(
"time cost " + '{:.3f}'.format(t1 + t2 + t3) + ' pnet {:.3f} rnet {:.3f} onet {:.3f}'.format(t1, t2,
t3))
return boxes_c,landmark
def detect_face(self, test_data):
all_boxes = []
landmarks = []
batch_idx = 0
sum_time = 0
#test_data is iter_
for databatch in test_data:
#databatch(image returned)
if batch_idx % 100 == 0:
print("%d images done" % batch_idx)
im = databatch
# pnet
t1 = 0
if self.pnet_detector:
t = time.time()
#ignore landmark
boxes, boxes_c, landmark = self.detect_pnet(im)
t1 = time.time() - t
sum_time += t1
if boxes_c is None:
print("boxes_c is None...")
all_boxes.append(np.array([]))
#pay attention
landmarks.append(np.array([]))
batch_idx += 1
continue
# rnet
t2 = 0
if self.rnet_detector:
t = time.time()
#ignore landmark
boxes, boxes_c, landmark = self.detect_rnet(im, boxes_c)
t2 = time.time() - t
sum_time += t2
if boxes_c is None:
all_boxes.append(np.array([]))
landmarks.append(np.array([]))
batch_idx += 1
continue
# onet
t3 = 0
if self.onet_detector:
t = time.time()
boxes, boxes_c, landmark = self.detect_onet(im, boxes_c)
t3 = time.time() - t
sum_time += t3
if boxes_c is None:
all_boxes.append(np.array([]))
landmarks.append(np.array([]))
batch_idx += 1
continue
print(
"time cost " + '{:.3f}'.format(sum_time) + ' pnet {:.3f} rnet {:.3f} onet {:.3f}'.format(t1, t2,t3))
all_boxes.append(boxes_c)
landmarks.append(landmark)
batch_idx += 1
#num_of_data*9,num_of_data*10
return all_boxes,landmarks
| true | true |
f7105ca75b04c3c8c1d2283faf3211318318e6be | 2,694 | py | Python | tk/users/views.py | ShinJungJae/TK-backend | b58b54a4d664e6512188ade63ca192a1fdf36382 | [
"MIT"
] | null | null | null | tk/users/views.py | ShinJungJae/TK-backend | b58b54a4d664e6512188ade63ca192a1fdf36382 | [
"MIT"
] | null | null | null | tk/users/views.py | ShinJungJae/TK-backend | b58b54a4d664e6512188ade63ca192a1fdf36382 | [
"MIT"
] | null | null | null | from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from . import models, serializers
class ExploreUsers(APIView):
def get(self, request, format=None):
last_five = models.User.objects.all().order_by('-date_joined')[:5]
serializer = serializers.ListUserSerializer(last_five, many=True)
return Response(data=serializer.data, status=status.HTTP_200_OK)
class FollowUser(APIView):
def post(self, request, user_id, format=None):
user = request.user
print(user)
try:
user_to_follow = models.User.objects.get(id=user_id)
print(user_to_follow)
except models.User.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
user.following.add(user_to_follow)
user.save()
return Response(status=status.HTTP_200_OK)
class UnFollowUser(APIView):
def post(self, request, user_id, format=None):
user = request.user
try:
user_to_follow = models.User.objects.get(id=user_id)
except models.User.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
user.following.remove(user_to_follow)
user.save()
return Response(status=status.HTTP_200_OK)
class UserProfile(APIView):
def get(self, request, username, format=None):
try:
found_user = models.User.objects.get(username=username)
except models.User.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
serializer = serializers.UserProfileSerializer(found_user)
return Response(data=serializer.data, status=status.HTTP_200_OK)
class UserFollowers(APIView):
def get(self, request, username, format=None):
try:
found_user = models.User.objects.get(username=username)
except models.User.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
user_followers = found_user.followers.all()
serializer = serializers.ListUserSerializer( user_followers, many=True)
return Response(data=serializer.data, status=status.HTTP_200_OK)
class UserFollowing(APIView):
def get(self, request, username, format=None):
try:
found_user = models.User.objects.get(username=username)
except models.User.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
user_following = found_user.following.all()
serializer = serializers.ListUserSerializer(user_following, many=True)
return Response(data=serializer.data, status=status.HTTP_200_OK)
| 26.15534 | 79 | 0.690052 | from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from . import models, serializers
class ExploreUsers(APIView):
def get(self, request, format=None):
last_five = models.User.objects.all().order_by('-date_joined')[:5]
serializer = serializers.ListUserSerializer(last_five, many=True)
return Response(data=serializer.data, status=status.HTTP_200_OK)
class FollowUser(APIView):
def post(self, request, user_id, format=None):
user = request.user
print(user)
try:
user_to_follow = models.User.objects.get(id=user_id)
print(user_to_follow)
except models.User.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
user.following.add(user_to_follow)
user.save()
return Response(status=status.HTTP_200_OK)
class UnFollowUser(APIView):
def post(self, request, user_id, format=None):
user = request.user
try:
user_to_follow = models.User.objects.get(id=user_id)
except models.User.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
user.following.remove(user_to_follow)
user.save()
return Response(status=status.HTTP_200_OK)
class UserProfile(APIView):
def get(self, request, username, format=None):
try:
found_user = models.User.objects.get(username=username)
except models.User.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
serializer = serializers.UserProfileSerializer(found_user)
return Response(data=serializer.data, status=status.HTTP_200_OK)
class UserFollowers(APIView):
def get(self, request, username, format=None):
try:
found_user = models.User.objects.get(username=username)
except models.User.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
user_followers = found_user.followers.all()
serializer = serializers.ListUserSerializer( user_followers, many=True)
return Response(data=serializer.data, status=status.HTTP_200_OK)
class UserFollowing(APIView):
def get(self, request, username, format=None):
try:
found_user = models.User.objects.get(username=username)
except models.User.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
user_following = found_user.following.all()
serializer = serializers.ListUserSerializer(user_following, many=True)
return Response(data=serializer.data, status=status.HTTP_200_OK)
| true | true |
f7105db64aa4eae243200441bceaf95732ded3c3 | 104 | py | Python | tests/example_files/imports_template.py | kracekumar/pep585-upgrade | 949a8d6d9afeee4b178ee4a1d534aa174e5adb7d | [
"BSD-3-Clause"
] | null | null | null | tests/example_files/imports_template.py | kracekumar/pep585-upgrade | 949a8d6d9afeee4b178ee4a1d534aa174e5adb7d | [
"BSD-3-Clause"
] | null | null | null | tests/example_files/imports_template.py | kracekumar/pep585-upgrade | 949a8d6d9afeee4b178ee4a1d534aa174e5adb7d | [
"BSD-3-Clause"
] | null | null | null | from __future__ import annotations
from typing import List
x: List
def b(*, x: list[str]):
pass
| 10.4 | 34 | 0.692308 | from __future__ import annotations
from typing import List
x: List
def b(*, x: list[str]):
pass
| true | true |
f7105f00c7bb9e047b58c19b604412f60319b49d | 430 | py | Python | maluforce/__version__.py | rmcferrao/maluforce | 12c776dc129c8d778086e22fd8ad9de996816081 | [
"MIT"
] | null | null | null | maluforce/__version__.py | rmcferrao/maluforce | 12c776dc129c8d778086e22fd8ad9de996816081 | [
"MIT"
] | null | null | null | maluforce/__version__.py | rmcferrao/maluforce | 12c776dc129c8d778086e22fd8ad9de996816081 | [
"MIT"
] | null | null | null | """Version details for maluforce"""
__title__ = "maluforce"
__description__ = "A basic Salesforce and Pandas interface"
__url__ = "https://github.com/rodrigoelemesmo/maluforce"
__version__ = "0.0.6"
__author__ = "Rodrigo Maluf"
__author_email__ = "rodrigo1793@gmail.com"
__license__ = "None"
__maintainer__ = "Rodrigo Maluf"
__maintainer_email__ = "rodrigo1793@gmail.com"
__keywords__ = "python salesforce salesforce.com pandas"
| 33.076923 | 59 | 0.781395 |
__title__ = "maluforce"
__description__ = "A basic Salesforce and Pandas interface"
__url__ = "https://github.com/rodrigoelemesmo/maluforce"
__version__ = "0.0.6"
__author__ = "Rodrigo Maluf"
__author_email__ = "rodrigo1793@gmail.com"
__license__ = "None"
__maintainer__ = "Rodrigo Maluf"
__maintainer_email__ = "rodrigo1793@gmail.com"
__keywords__ = "python salesforce salesforce.com pandas"
| true | true |
f710618df3ce59a74e0e72dab814554fa94101d9 | 7,201 | py | Python | graph4nlp/pytorch/test/seq_decoder/graph2seq/src/g2s_v2/core/utils/vocab_utils.py | stjordanis/graph4nlp | c6ebde32bc77d3a7b78f86a93f19b1c057963ffa | [
"Apache-2.0"
] | 18 | 2020-09-09T03:33:29.000Z | 2021-07-22T11:17:16.000Z | graph4nlp/pytorch/test/seq_decoder/graph2seq/src/g2s_v2/core/utils/vocab_utils.py | stjordanis/graph4nlp | c6ebde32bc77d3a7b78f86a93f19b1c057963ffa | [
"Apache-2.0"
] | null | null | null | graph4nlp/pytorch/test/seq_decoder/graph2seq/src/g2s_v2/core/utils/vocab_utils.py | stjordanis/graph4nlp | c6ebde32bc77d3a7b78f86a93f19b1c057963ffa | [
"Apache-2.0"
] | 1 | 2021-11-01T08:41:26.000Z | 2021-11-01T08:41:26.000Z | # -*- coding: utf-8 -*-
from __future__ import print_function
import os
import re
import pickle
import numpy as np
from collections import Counter
from functools import lru_cache
from . import constants
from .data_utils import tokenize
word_detector = re.compile('\w')
class VocabModel(object):
def __init__(self, data_set, config):
print('Building vocabs...')
(allWords, allEdgeTypes) = collect_vocabs(data_set)
print('Number of words: {}'.format(len(allWords)))
print('Number of edge types: {}'.format(len(allEdgeTypes)))
self.word_vocab = Vocab()
self.word_vocab.build_vocab(allWords, vocab_size=config['top_word_vocab'], min_freq=config['min_word_freq'])
if config.get('pretrained_word_embed_file', None):
self.word_vocab.load_embeddings(config['pretrained_word_embed_file'])
print('Using pretrained word embeddings')
else:
self.word_vocab.randomize_embeddings(config['word_embed_dim'])
print('Using randomized word embeddings')
print('word_vocab: {}'.format(self.word_vocab.embeddings.shape))
self.edge_vocab = Vocab()
self.edge_vocab.build_vocab(allEdgeTypes)
print('edge_vocab: {}'.format((self.edge_vocab.get_vocab_size())))
@classmethod
def build(cls, saved_vocab_file=None, data_set=None, config=None):
"""
Loads a Vocabulary from disk.
Args:
saved_vocab_file (str): path to the saved vocab file
data_set:
config:
Returns:
Vocabulary: loaded Vocabulary
"""
if os.path.exists(saved_vocab_file):
print('Loading pre-built vocab model stored in {}'.format(saved_vocab_file))
vocab_model = pickle.load(open(saved_vocab_file, 'rb'))
else:
vocab_model = VocabModel(data_set, config)
print('Saving vocab model to {}'.format(saved_vocab_file))
pickle.dump(vocab_model, open(saved_vocab_file, 'wb'))
return vocab_model
class Vocab(object):
def __init__(self):
self.PAD = 0
self.SOS = 1
self.EOS = 2
self.UNK = 3
self.pad_token = constants._PAD_TOKEN
self.sos_token = constants._SOS_TOKEN
self.eos_token = constants._EOS_TOKEN
self.unk_token = constants._UNK_TOKEN
self.reserved = [self.pad_token, self.sos_token, self.eos_token, self.unk_token]
self.index2word = self.reserved[:]
self.word2index = dict(zip(self.reserved, range(len(self.reserved))))
self.word2count = Counter()
self.embeddings = None
def build_vocab(self, vocab_counter, vocab_size=None, min_freq=1):
self.word2count = vocab_counter
self._add_words(vocab_counter.keys())
self._trim(vocab_size=vocab_size, min_freq=min_freq)
def _add_words(self, words):
for word in words:
if word not in self.word2index:
self.word2index[word] = len(self.index2word)
self.index2word.append(word)
assert len(self.word2index) == len(self.index2word)
def _trim(self, vocab_size: int=None, min_freq: int=1):
if min_freq <= 1 and (vocab_size is None or vocab_size >= len(self.word2index)):
return
ordered_words = sorted(((c, w) for (w, c) in self.word2count.items()), reverse=True)
if vocab_size:
ordered_words = ordered_words[:vocab_size]
self.index2word = self.reserved[:]
self.word2index = dict(zip(self.reserved, range(len(self.reserved))))
self.word2count = Counter()
for count, word in ordered_words:
if count < min_freq: break
if word not in self.word2index:
self.word2index[word] = len(self.index2word)
self.word2count[word] = count
self.index2word.append(word)
assert len(self.word2index) == len(self.index2word)
def load_embeddings(self, file_path, scale=0.08, dtype=np.float32):
hit_words = set()
vocab_size = len(self)
with open(file_path, 'rb') as f:
for line in f:
line = line.split()
word = line[0].decode('utf-8')
idx = self.word2index.get(word.lower(), None)
if idx is None or idx in hit_words:
continue
vec = np.array(line[1:], dtype=dtype)
if self.embeddings is None:
n_dims = len(vec)
self.embeddings = np.array(np.random.uniform(low=-scale, high=scale, size=(vocab_size, n_dims)), dtype=dtype)
self.embeddings[self.PAD] = np.zeros(n_dims)
self.embeddings[idx] = vec
hit_words.add(idx)
print('Pretrained word embeddings hit ratio: {}'.format(len(hit_words) / len(self.index2word)))
def randomize_embeddings(self, n_dims, scale=0.08):
vocab_size = self.get_vocab_size()
shape = (vocab_size, n_dims)
self.embeddings = np.array(np.random.uniform(low=-scale, high=scale, size=shape), dtype=np.float32)
self.embeddings[self.PAD] = np.zeros(n_dims)
def __getitem__(self, item):
if type(item) is int:
return self.index2word[item]
return self.word2index.get(item, self.UNK)
def __len__(self):
return len(self.index2word)
@lru_cache(maxsize=None)
def is_word(self, token_id: int) -> bool:
"""Return whether the token at `token_id` is a word; False for punctuations."""
if token_id < 4: return False
if token_id >= len(self): return True # OOV is assumed to be words
token_str = self.index2word[token_id]
if not word_detector.search(token_str) or token_str == '<P>':
return False
return True
def get_vocab_size(self):
return len(self.index2word)
def getIndex(self, word):
return self.word2index.get(word, self.UNK)
def getWord(self, idx):
return self.index2word[idx] if idx < len(self.index2word) else self.unk_token
def to_word_sequence(self, seq):
sentence = []
for idx in seq:
word = self.getWord(idx)
sentence.append(word)
return sentence
def to_index_sequence(self, sentence):
sentence = sentence.strip()
seq = []
for word in tokenize(sentence):
idx = self.getIndex(word)
seq.append(idx)
return seq
def to_index_sequence_for_list(self, words):
seq = []
for word in words:
idx = self.getIndex(word)
seq.append(idx)
return seq
def collect_vocabs(all_instances):
all_words = Counter()
all_edge_types = Counter()
for (sent1, sent2) in all_instances:
# for each in sent1.words:
# all_words.update(each)
for each in sent1.graph['g_features']:
all_words.update(each)
all_words.update(sent2.words)
# for node, value in sent1.graph['g_adj'].items():
# all_edge_types.update([each['edge'] for each in value])
return all_words, all_edge_types
| 37.118557 | 129 | 0.617831 |
from __future__ import print_function
import os
import re
import pickle
import numpy as np
from collections import Counter
from functools import lru_cache
from . import constants
from .data_utils import tokenize
word_detector = re.compile('\w')
class VocabModel(object):
def __init__(self, data_set, config):
print('Building vocabs...')
(allWords, allEdgeTypes) = collect_vocabs(data_set)
print('Number of words: {}'.format(len(allWords)))
print('Number of edge types: {}'.format(len(allEdgeTypes)))
self.word_vocab = Vocab()
self.word_vocab.build_vocab(allWords, vocab_size=config['top_word_vocab'], min_freq=config['min_word_freq'])
if config.get('pretrained_word_embed_file', None):
self.word_vocab.load_embeddings(config['pretrained_word_embed_file'])
print('Using pretrained word embeddings')
else:
self.word_vocab.randomize_embeddings(config['word_embed_dim'])
print('Using randomized word embeddings')
print('word_vocab: {}'.format(self.word_vocab.embeddings.shape))
self.edge_vocab = Vocab()
self.edge_vocab.build_vocab(allEdgeTypes)
print('edge_vocab: {}'.format((self.edge_vocab.get_vocab_size())))
@classmethod
def build(cls, saved_vocab_file=None, data_set=None, config=None):
if os.path.exists(saved_vocab_file):
print('Loading pre-built vocab model stored in {}'.format(saved_vocab_file))
vocab_model = pickle.load(open(saved_vocab_file, 'rb'))
else:
vocab_model = VocabModel(data_set, config)
print('Saving vocab model to {}'.format(saved_vocab_file))
pickle.dump(vocab_model, open(saved_vocab_file, 'wb'))
return vocab_model
class Vocab(object):
def __init__(self):
self.PAD = 0
self.SOS = 1
self.EOS = 2
self.UNK = 3
self.pad_token = constants._PAD_TOKEN
self.sos_token = constants._SOS_TOKEN
self.eos_token = constants._EOS_TOKEN
self.unk_token = constants._UNK_TOKEN
self.reserved = [self.pad_token, self.sos_token, self.eos_token, self.unk_token]
self.index2word = self.reserved[:]
self.word2index = dict(zip(self.reserved, range(len(self.reserved))))
self.word2count = Counter()
self.embeddings = None
def build_vocab(self, vocab_counter, vocab_size=None, min_freq=1):
self.word2count = vocab_counter
self._add_words(vocab_counter.keys())
self._trim(vocab_size=vocab_size, min_freq=min_freq)
def _add_words(self, words):
for word in words:
if word not in self.word2index:
self.word2index[word] = len(self.index2word)
self.index2word.append(word)
assert len(self.word2index) == len(self.index2word)
def _trim(self, vocab_size: int=None, min_freq: int=1):
if min_freq <= 1 and (vocab_size is None or vocab_size >= len(self.word2index)):
return
ordered_words = sorted(((c, w) for (w, c) in self.word2count.items()), reverse=True)
if vocab_size:
ordered_words = ordered_words[:vocab_size]
self.index2word = self.reserved[:]
self.word2index = dict(zip(self.reserved, range(len(self.reserved))))
self.word2count = Counter()
for count, word in ordered_words:
if count < min_freq: break
if word not in self.word2index:
self.word2index[word] = len(self.index2word)
self.word2count[word] = count
self.index2word.append(word)
assert len(self.word2index) == len(self.index2word)
def load_embeddings(self, file_path, scale=0.08, dtype=np.float32):
hit_words = set()
vocab_size = len(self)
with open(file_path, 'rb') as f:
for line in f:
line = line.split()
word = line[0].decode('utf-8')
idx = self.word2index.get(word.lower(), None)
if idx is None or idx in hit_words:
continue
vec = np.array(line[1:], dtype=dtype)
if self.embeddings is None:
n_dims = len(vec)
self.embeddings = np.array(np.random.uniform(low=-scale, high=scale, size=(vocab_size, n_dims)), dtype=dtype)
self.embeddings[self.PAD] = np.zeros(n_dims)
self.embeddings[idx] = vec
hit_words.add(idx)
print('Pretrained word embeddings hit ratio: {}'.format(len(hit_words) / len(self.index2word)))
def randomize_embeddings(self, n_dims, scale=0.08):
vocab_size = self.get_vocab_size()
shape = (vocab_size, n_dims)
self.embeddings = np.array(np.random.uniform(low=-scale, high=scale, size=shape), dtype=np.float32)
self.embeddings[self.PAD] = np.zeros(n_dims)
def __getitem__(self, item):
if type(item) is int:
return self.index2word[item]
return self.word2index.get(item, self.UNK)
def __len__(self):
return len(self.index2word)
@lru_cache(maxsize=None)
def is_word(self, token_id: int) -> bool:
if token_id < 4: return False
if token_id >= len(self): return True
token_str = self.index2word[token_id]
if not word_detector.search(token_str) or token_str == '<P>':
return False
return True
def get_vocab_size(self):
return len(self.index2word)
def getIndex(self, word):
return self.word2index.get(word, self.UNK)
def getWord(self, idx):
return self.index2word[idx] if idx < len(self.index2word) else self.unk_token
def to_word_sequence(self, seq):
sentence = []
for idx in seq:
word = self.getWord(idx)
sentence.append(word)
return sentence
def to_index_sequence(self, sentence):
sentence = sentence.strip()
seq = []
for word in tokenize(sentence):
idx = self.getIndex(word)
seq.append(idx)
return seq
def to_index_sequence_for_list(self, words):
seq = []
for word in words:
idx = self.getIndex(word)
seq.append(idx)
return seq
def collect_vocabs(all_instances):
all_words = Counter()
all_edge_types = Counter()
for (sent1, sent2) in all_instances:
for each in sent1.graph['g_features']:
all_words.update(each)
all_words.update(sent2.words)
return all_words, all_edge_types
| true | true |
f710621a406cb46d8fd1148a07770249421a7f62 | 2,190 | py | Python | config/settings/local.py | sahilpysquad/SMT | b03d5d2e32fcda26cdbae35588cfd0f785c02d3a | [
"MIT"
] | null | null | null | config/settings/local.py | sahilpysquad/SMT | b03d5d2e32fcda26cdbae35588cfd0f785c02d3a | [
"MIT"
] | 1 | 2022-03-30T20:23:58.000Z | 2022-03-30T20:23:58.000Z | config/settings/local.py | sahilpysquad/SMT | b03d5d2e32fcda26cdbae35588cfd0f785c02d3a | [
"MIT"
] | null | null | null | from .base import * # noqa
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = True
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env(
"DJANGO_SECRET_KEY",
default="Zn3KXHlnNzLcEZ9pnrLwkkhwzlkzJp7bjgy6DqXLLqyGP59Ayn1J7ZrlpxcnVxWe",
)
# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ["localhost", "0.0.0.0", "127.0.0.1"]
# CACHES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#caches
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "",
}
}
# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = env(
"DJANGO_EMAIL_BACKEND", default="django.core.mail.backends.console.EmailBackend"
)
# django-debug-toolbar
# ------------------------------------------------------------------------------
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#prerequisites
INSTALLED_APPS += ["debug_toolbar"] # noqa F405
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#middleware
MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"] # noqa F405
# https://django-debug-toolbar.readthedocs.io/en/latest/configuration.html#debug-toolbar-config
DEBUG_TOOLBAR_CONFIG = {
"DISABLE_PANELS": ["debug_toolbar.panels.redirects.RedirectsPanel"],
"SHOW_TEMPLATE_CONTEXT": True,
}
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#internal-ips
INTERNAL_IPS = ["127.0.0.1", "10.0.2.2"]
# django-extensions
# ------------------------------------------------------------------------------
# https://django-extensions.readthedocs.io/en/latest/installation_instructions.html#configuration
INSTALLED_APPS += ["django_extensions"] # noqa F405
# Your stuff...
# ------------------------------------------------------------------------------
| 39.818182 | 97 | 0.583105 | from .base import *
from .base import env
= True
= env(
"DJANGO_SECRET_KEY",
default="Zn3KXHlnNzLcEZ9pnrLwkkhwzlkzJp7bjgy6DqXLLqyGP59Ayn1J7ZrlpxcnVxWe",
)
= ["localhost", "0.0.0.0", "127.0.0.1"]
= {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "",
}
}
= env(
"DJANGO_EMAIL_BACKEND", default="django.core.mail.backends.console.EmailBackend"
)
S += ["debug_toolbar"]
+= ["debug_toolbar.middleware.DebugToolbarMiddleware"]
= {
"DISABLE_PANELS": ["debug_toolbar.panels.redirects.RedirectsPanel"],
"SHOW_TEMPLATE_CONTEXT": True,
}
= ["127.0.0.1", "10.0.2.2"]
S += ["django_extensions"]
| true | true |
f71062ea8686c0a6c55bd7f8ff2dfe5d3c51b140 | 4,096 | py | Python | sandpileModel_v0_0_1.py | Alex-Github-Programmer/fractal | ab463a715a6a9883b43a4eefe899c1af549f5ddd | [
"MIT"
] | null | null | null | sandpileModel_v0_0_1.py | Alex-Github-Programmer/fractal | ab463a715a6a9883b43a4eefe899c1af549f5ddd | [
"MIT"
] | null | null | null | sandpileModel_v0_0_1.py | Alex-Github-Programmer/fractal | ab463a715a6a9883b43a4eefe899c1af549f5ddd | [
"MIT"
] | null | null | null | import array
class bmp:
""" bmp data structure """
def __init__(self, w=1080, h=1920):
self.w = w
self.h = h
def calc_data_size (self):
if((self.w*3)%4 == 0):
self.dataSize = self.w * 3 * self.h
else:
self.dataSize = (((self.w * 3) // 4 + 1) * 4) * self.h
self.fileSize = self.dataSize + 54
def conv2byte(self, l, num, len):
tmp = num
for i in range(len):
l.append(tmp & 0x000000ff)
tmp >>= 8
def gen_bmp_header (self):
self.calc_data_size();
self.bmp_header = [0x42, 0x4d]
self.conv2byte(self.bmp_header, self.fileSize, 4) #file size
self.conv2byte(self.bmp_header, 0, 2)
self.conv2byte(self.bmp_header, 0, 2)
self.conv2byte(self.bmp_header, 54, 4) #rgb data offset
self.conv2byte(self.bmp_header, 40, 4) #info block size
self.conv2byte(self.bmp_header, self.w, 4)
self.conv2byte(self.bmp_header, self.h, 4)
self.conv2byte(self.bmp_header, 1, 2)
self.conv2byte(self.bmp_header, 24, 2) #888
self.conv2byte(self.bmp_header, 0, 4) #no compression
self.conv2byte(self.bmp_header, self.dataSize, 4) #rgb data size
self.conv2byte(self.bmp_header, 0, 4)
self.conv2byte(self.bmp_header, 0, 4)
self.conv2byte(self.bmp_header, 0, 4)
self.conv2byte(self.bmp_header, 0, 4)
def print_bmp_header (self):
length = len(self.bmp_header)
for i in range(length):
print("{:0>2x}".format(self.bmp_header[i]), end=' ')
if i%16 == 15:
print('')
print('')
def paint_bgcolor(self, color=0xffffff):
## self.rgbData = []
## for r in range(self.h):
## self.rgbDataRow = []
## for c in range(self.w):
## self.rgbDataRow.append(color)
## self.rgbData.append(self.rgbDataRow)
rgbDataRow = [color] * (self.w+1)
self.rgbData = [rgbDataRow.copy() for i in range(self.h)]
def set_at(self,x, y, color):
self.rgbData[y][x] = color
def paint_line(self, x1, y1, x2, y2, color):
k = (y2 - y1) / (x2 - x1)
for x in range(x1, x2+1):
y = int(k * (x - x1) + y1)
self.rgbData[y][x] = color
def paint_rect(self, x1, y1, w, h, color):
for x in range(x1, x1+w):
for y in range(y1, y1+h):
self.rgbData[y][x] = color
def save_image(self, name="save.bmp"):
f = open(name, 'wb')
#write bmp header
f.write(array.array('B', self.bmp_header).tobytes())
#write rgb data
zeroBytes = self.dataSize // self.h - self.w * 3
for r in range(self.h):
l = []
for i in range(len(self.rgbData[r])):
p = self.rgbData[r][i]
l.append(p & 0x0000ff)
p >>= 8
l.append(p & 0x0000ff)
p >>= 8
l.append(p & 0x0000ff)
f.write(array.array('B', l).tobytes())
for i in range(zeroBytes):
f.write(bytes(0x00))
f.close()
sand = list([0] * 2003 for i in range(2003))
final = ''
image = bmp(2003, 2003)
image.gen_bmp_header()
image.print_bmp_header()
image.paint_bgcolor(0x000000)
stack = []
def update(i, j):
if i == 0 or i == 2002 or j == 0 or j == 2002:
sand[i][j] = 0
elif sand[i][j] >= 4:
q = sand[i][j] // 4
sand[i + 1][j] += q
sand[i - 1][j] += q
sand[i][j + 1] += q
sand[i][j - 1] += q
sand[i][j] %= 4
stack.append((i + 1, j))
stack.append((i - 1, j))
stack.append((i, j + 1))
stack.append((i, j - 1))
for i in range(40000):
sand[1001][1001] += 1
stack.append((1001, 1001))
while stack:
update(*stack.pop())
if i%100==0:print(i)
for i in range(1, 2003):
for j in range(1, 2003):
image.set_at(i, j, [0x0000ff, 0x00ffff, 0x00ff00, 0xff0000][sand[i][j]])
if i%100==0:print(i)
image.save_image('sand.bmp')
| 33.57377 | 80 | 0.523682 | import array
class bmp:
def __init__(self, w=1080, h=1920):
self.w = w
self.h = h
def calc_data_size (self):
if((self.w*3)%4 == 0):
self.dataSize = self.w * 3 * self.h
else:
self.dataSize = (((self.w * 3) // 4 + 1) * 4) * self.h
self.fileSize = self.dataSize + 54
def conv2byte(self, l, num, len):
tmp = num
for i in range(len):
l.append(tmp & 0x000000ff)
tmp >>= 8
def gen_bmp_header (self):
self.calc_data_size();
self.bmp_header = [0x42, 0x4d]
self.conv2byte(self.bmp_header, self.fileSize, 4)
self.conv2byte(self.bmp_header, 0, 2)
self.conv2byte(self.bmp_header, 0, 2)
self.conv2byte(self.bmp_header, 54, 4)
self.conv2byte(self.bmp_header, 40, 4)
self.conv2byte(self.bmp_header, self.w, 4)
self.conv2byte(self.bmp_header, self.h, 4)
self.conv2byte(self.bmp_header, 1, 2)
self.conv2byte(self.bmp_header, 24, 2)
self.conv2byte(self.bmp_header, 0, 4)
self.conv2byte(self.bmp_header, self.dataSize, 4)
self.conv2byte(self.bmp_header, 0, 4)
self.conv2byte(self.bmp_header, 0, 4)
self.conv2byte(self.bmp_header, 0, 4)
self.conv2byte(self.bmp_header, 0, 4)
def print_bmp_header (self):
length = len(self.bmp_header)
for i in range(length):
print("{:0>2x}".format(self.bmp_header[i]), end=' ')
if i%16 == 15:
print('')
print('')
def paint_bgcolor(self, color=0xffffff):
, color):
k = (y2 - y1) / (x2 - x1)
for x in range(x1, x2+1):
y = int(k * (x - x1) + y1)
self.rgbData[y][x] = color
def paint_rect(self, x1, y1, w, h, color):
for x in range(x1, x1+w):
for y in range(y1, y1+h):
self.rgbData[y][x] = color
def save_image(self, name="save.bmp"):
f = open(name, 'wb')
f.write(array.array('B', self.bmp_header).tobytes())
zeroBytes = self.dataSize // self.h - self.w * 3
for r in range(self.h):
l = []
for i in range(len(self.rgbData[r])):
p = self.rgbData[r][i]
l.append(p & 0x0000ff)
p >>= 8
l.append(p & 0x0000ff)
p >>= 8
l.append(p & 0x0000ff)
f.write(array.array('B', l).tobytes())
for i in range(zeroBytes):
f.write(bytes(0x00))
f.close()
sand = list([0] * 2003 for i in range(2003))
final = ''
image = bmp(2003, 2003)
image.gen_bmp_header()
image.print_bmp_header()
image.paint_bgcolor(0x000000)
stack = []
def update(i, j):
if i == 0 or i == 2002 or j == 0 or j == 2002:
sand[i][j] = 0
elif sand[i][j] >= 4:
q = sand[i][j] // 4
sand[i + 1][j] += q
sand[i - 1][j] += q
sand[i][j + 1] += q
sand[i][j - 1] += q
sand[i][j] %= 4
stack.append((i + 1, j))
stack.append((i - 1, j))
stack.append((i, j + 1))
stack.append((i, j - 1))
for i in range(40000):
sand[1001][1001] += 1
stack.append((1001, 1001))
while stack:
update(*stack.pop())
if i%100==0:print(i)
for i in range(1, 2003):
for j in range(1, 2003):
image.set_at(i, j, [0x0000ff, 0x00ffff, 0x00ff00, 0xff0000][sand[i][j]])
if i%100==0:print(i)
image.save_image('sand.bmp')
| true | true |
f71063a4b5711bb34d16be052982c1c2e1e50f81 | 9,849 | py | Python | detectron2/export/api.py | YinchaoGao/detectron2 | 04958b93e1232935e126c2fd9e6ccd3f57c3a8f3 | [
"Apache-2.0"
] | null | null | null | detectron2/export/api.py | YinchaoGao/detectron2 | 04958b93e1232935e126c2fd9e6ccd3f57c3a8f3 | [
"Apache-2.0"
] | null | null | null | detectron2/export/api.py | YinchaoGao/detectron2 | 04958b93e1232935e126c2fd9e6ccd3f57c3a8f3 | [
"Apache-2.0"
] | null | null | null | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import copy
import logging
import os
import torch
from caffe2.proto import caffe2_pb2
from torch import nn
from detectron2.config import CfgNode as CN
from .caffe2_export import export_caffe2_detection_model
from .caffe2_export import export_onnx_model as export_onnx_model_impl
from .caffe2_export import run_and_save_graph
from .caffe2_inference import ProtobufDetectionModel
from .caffe2_modeling import META_ARCH_CAFFE2_EXPORT_TYPE_MAP, convert_batched_inputs_to_c2_format
from .shared import get_pb_arg_vali, get_pb_arg_vals, save_graph
__all__ = ["add_export_config", "export_caffe2_model", "Caffe2Model", "export_onnx_model"]
def add_export_config(cfg):
"""
Args:
cfg (CfgNode): a detectron2 config
Returns:
CfgNode: an updated config with new options that will be used
by :class:`Caffe2Tracer`.
"""
is_frozen = cfg.is_frozen()
cfg.defrost()
cfg.EXPORT_CAFFE2 = CN()
cfg.EXPORT_CAFFE2.USE_HEATMAP_MAX_KEYPOINT = False
if is_frozen:
cfg.freeze()
return cfg
class Caffe2Tracer:
"""
Make a detectron2 model traceable with caffe2 style.
An original detectron2 model may not be traceable, or
cannot be deployed directly after being traced, due to some reasons:
1. control flow in some ops
2. custom ops
3. complicated pre/post processing
This class provides a traceable version of a detectron2 model by:
1. Rewrite parts of the model using ops in caffe2
2. Define the inputs "after pre-processing" as inputs to the model
3. Remove post-processing and produce raw layer outputs
More specifically about inputs: all builtin models take two input tensors.
(1) NCHW float "data" which is an image (usually in [0, 255])
(2) Nx3 float "im_info", each row of which is (height, width, 1.0)
After making a traceable model, the class provide methods to export such a
model to different deployment formats.
The class currently only supports models using builtin meta architectures.
Experimental. Don't use.
"""
def __init__(self, cfg, model, inputs):
"""
Args:
cfg (CfgNode): a detectron2 config, with extra export-related options
added by :func:`add_export_config`.
model (nn.Module): a model built by
:func:`detectron2.modeling.build_model`.
inputs: sample inputs that the given model takes for inference.
Will be used to trace the model.
"""
assert isinstance(cfg, CN), cfg
assert isinstance(model, torch.nn.Module), type(model)
if "EXPORT_CAFFE2" not in cfg:
cfg = add_export_config(cfg) # will just the defaults
self.cfg = cfg
self.model = model
self.inputs = inputs
def _get_traceable(self):
# TODO how to make it extensible to support custom models
C2MetaArch = META_ARCH_CAFFE2_EXPORT_TYPE_MAP[self.cfg.MODEL.META_ARCHITECTURE]
traceable_model = C2MetaArch(self.cfg, copy.deepcopy(self.model))
traceable_inputs = traceable_model.get_caffe2_inputs(self.inputs)
return traceable_model, traceable_inputs
def export_caffe2(self):
"""
Export the model to Caffe2's protobuf format.
The returned object can be saved with `.save_protobuf()` method.
The result can be loaded and executed using Caffe2 runtime.
Returns:
Caffe2Model
"""
model, inputs = self._get_traceable()
predict_net, init_net = export_caffe2_detection_model(model, inputs)
return Caffe2Model(predict_net, init_net)
def export_onnx(self):
"""
Export the model to ONNX format.
Note that the exported model contains custom ops only available in caffe2, therefore it
cannot be directly executed by other runtime. Post-processing or transformation passes
may be applied on the model to accommodate different runtimes.
Returns:
onnx.ModelProto: an onnx model.
"""
model, inputs = self._get_traceable()
return export_onnx_model_impl(model, (inputs,))
def export_torchscript(self):
"""
Export the model to a `torch.jit.TracedModule` by tracing.
The returned object can be saved to a file by ".save()".
Returns:
torch.jit.TracedModule: a torch TracedModule
"""
model, inputs = self._get_traceable()
logger = logging.getLogger(__name__)
logger.info("Tracing the model with torch.jit.trace ...")
with torch.no_grad():
return torch.jit.trace(model, (inputs,))
def export_caffe2_model(cfg, model, inputs):
"""
Export a detectron2 model to caffe2 format.
Args:
cfg (CfgNode): a detectron2 config, with extra export-related options
added by :func:`add_export_config`.
model (nn.Module): a model built by
:func:`detectron2.modeling.build_model`.
It will be modified by this function.
inputs: sample inputs that the given model takes for inference.
Will be used to trace the model.
Returns:
Caffe2Model
"""
return Caffe2Tracer(cfg, model, inputs).export_caffe2()
def export_onnx_model(cfg, model, inputs):
"""
Export a detectron2 model to ONNX format.
Note that the exported model contains custom ops only available in caffe2, therefore it
cannot be directly executed by other runtime. Post-processing or transformation passes
may be applied on the model to accommodate different runtimes.
Args:
cfg (CfgNode): a detectron2 config, with extra export-related options
added by :func:`add_export_config`.
model (nn.Module): a model built by
:func:`detectron2.modeling.build_model`.
It will be modified by this function.
inputs: sample inputs that the given model takes for inference.
Will be used to trace the model.
Returns:
onnx.ModelProto: an onnx model.
"""
return Caffe2Tracer(cfg, model, inputs).export_onnx()
class Caffe2Model(nn.Module):
"""
A wrapper around the traced model in caffe2's pb format.
"""
def __init__(self, predict_net, init_net):
super().__init__()
self.eval() # always in eval mode
self._predict_net = predict_net
self._init_net = init_net
self._predictor = None
@property
def predict_net(self):
"""
Returns:
core.Net: the underlying caffe2 predict net
"""
return self._predict_net
@property
def init_net(self):
"""
Returns:
core.Net: the underlying caffe2 init net
"""
return self._init_net
__init__.__HIDE_SPHINX_DOC__ = True
def save_protobuf(self, output_dir):
"""
Save the model as caffe2's protobuf format.
Args:
output_dir (str): the output directory to save protobuf files.
"""
logger = logging.getLogger(__name__)
logger.info("Saving model to {} ...".format(output_dir))
os.makedirs(output_dir, exist_ok=True)
with open(os.path.join(output_dir, "model.pb"), "wb") as f:
f.write(self._predict_net.SerializeToString())
with open(os.path.join(output_dir, "model.pbtxt"), "w") as f:
f.write(str(self._predict_net))
with open(os.path.join(output_dir, "model_init.pb"), "wb") as f:
f.write(self._init_net.SerializeToString())
def save_graph(self, output_file, inputs=None):
"""
Save the graph as SVG format.
Args:
output_file (str): a SVG file
inputs: optional inputs given to the model.
If given, the inputs will be used to run the graph to record
shape of every tensor. The shape information will be
saved together with the graph.
"""
if inputs is None:
save_graph(self._predict_net, output_file, op_only=False)
else:
size_divisibility = get_pb_arg_vali(self._predict_net, "size_divisibility", 0)
device = get_pb_arg_vals(self._predict_net, "device", b"cpu").decode("ascii")
inputs = convert_batched_inputs_to_c2_format(inputs, size_divisibility, device)
inputs = [x.cpu().numpy() for x in inputs]
run_and_save_graph(self._predict_net, self._init_net, inputs, output_file)
@staticmethod
def load_protobuf(dir):
"""
Args:
dir (str): a directory used to save Caffe2Model with
:meth:`save_protobuf`.
The files "model.pb" and "model_init.pb" are needed.
Returns:
Caffe2Model: the caffe2 model loaded from this directory.
"""
predict_net = caffe2_pb2.NetDef()
with open(os.path.join(dir, "model.pb"), "rb") as f:
predict_net.ParseFromString(f.read())
init_net = caffe2_pb2.NetDef()
with open(os.path.join(dir, "model_init.pb"), "rb") as f:
init_net.ParseFromString(f.read())
return Caffe2Model(predict_net, init_net)
def __call__(self, inputs):
"""
An interface that wraps around a caffe2 model and mimics detectron2's models'
input & output format. This is used to compare the outputs of caffe2 model
with its original torch model.
Due to the extra conversion between torch/caffe2,
this method is not meant for benchmark.
"""
if self._predictor is None:
self._predictor = ProtobufDetectionModel(self._predict_net, self._init_net)
return self._predictor(inputs)
| 36.076923 | 98 | 0.653873 |
import copy
import logging
import os
import torch
from caffe2.proto import caffe2_pb2
from torch import nn
from detectron2.config import CfgNode as CN
from .caffe2_export import export_caffe2_detection_model
from .caffe2_export import export_onnx_model as export_onnx_model_impl
from .caffe2_export import run_and_save_graph
from .caffe2_inference import ProtobufDetectionModel
from .caffe2_modeling import META_ARCH_CAFFE2_EXPORT_TYPE_MAP, convert_batched_inputs_to_c2_format
from .shared import get_pb_arg_vali, get_pb_arg_vals, save_graph
__all__ = ["add_export_config", "export_caffe2_model", "Caffe2Model", "export_onnx_model"]
def add_export_config(cfg):
is_frozen = cfg.is_frozen()
cfg.defrost()
cfg.EXPORT_CAFFE2 = CN()
cfg.EXPORT_CAFFE2.USE_HEATMAP_MAX_KEYPOINT = False
if is_frozen:
cfg.freeze()
return cfg
class Caffe2Tracer:
def __init__(self, cfg, model, inputs):
assert isinstance(cfg, CN), cfg
assert isinstance(model, torch.nn.Module), type(model)
if "EXPORT_CAFFE2" not in cfg:
cfg = add_export_config(cfg)
self.cfg = cfg
self.model = model
self.inputs = inputs
def _get_traceable(self):
C2MetaArch = META_ARCH_CAFFE2_EXPORT_TYPE_MAP[self.cfg.MODEL.META_ARCHITECTURE]
traceable_model = C2MetaArch(self.cfg, copy.deepcopy(self.model))
traceable_inputs = traceable_model.get_caffe2_inputs(self.inputs)
return traceable_model, traceable_inputs
def export_caffe2(self):
model, inputs = self._get_traceable()
predict_net, init_net = export_caffe2_detection_model(model, inputs)
return Caffe2Model(predict_net, init_net)
def export_onnx(self):
model, inputs = self._get_traceable()
return export_onnx_model_impl(model, (inputs,))
def export_torchscript(self):
model, inputs = self._get_traceable()
logger = logging.getLogger(__name__)
logger.info("Tracing the model with torch.jit.trace ...")
with torch.no_grad():
return torch.jit.trace(model, (inputs,))
def export_caffe2_model(cfg, model, inputs):
return Caffe2Tracer(cfg, model, inputs).export_caffe2()
def export_onnx_model(cfg, model, inputs):
return Caffe2Tracer(cfg, model, inputs).export_onnx()
class Caffe2Model(nn.Module):
def __init__(self, predict_net, init_net):
super().__init__()
self.eval()
self._predict_net = predict_net
self._init_net = init_net
self._predictor = None
@property
def predict_net(self):
return self._predict_net
@property
def init_net(self):
return self._init_net
__init__.__HIDE_SPHINX_DOC__ = True
def save_protobuf(self, output_dir):
logger = logging.getLogger(__name__)
logger.info("Saving model to {} ...".format(output_dir))
os.makedirs(output_dir, exist_ok=True)
with open(os.path.join(output_dir, "model.pb"), "wb") as f:
f.write(self._predict_net.SerializeToString())
with open(os.path.join(output_dir, "model.pbtxt"), "w") as f:
f.write(str(self._predict_net))
with open(os.path.join(output_dir, "model_init.pb"), "wb") as f:
f.write(self._init_net.SerializeToString())
def save_graph(self, output_file, inputs=None):
if inputs is None:
save_graph(self._predict_net, output_file, op_only=False)
else:
size_divisibility = get_pb_arg_vali(self._predict_net, "size_divisibility", 0)
device = get_pb_arg_vals(self._predict_net, "device", b"cpu").decode("ascii")
inputs = convert_batched_inputs_to_c2_format(inputs, size_divisibility, device)
inputs = [x.cpu().numpy() for x in inputs]
run_and_save_graph(self._predict_net, self._init_net, inputs, output_file)
@staticmethod
def load_protobuf(dir):
predict_net = caffe2_pb2.NetDef()
with open(os.path.join(dir, "model.pb"), "rb") as f:
predict_net.ParseFromString(f.read())
init_net = caffe2_pb2.NetDef()
with open(os.path.join(dir, "model_init.pb"), "rb") as f:
init_net.ParseFromString(f.read())
return Caffe2Model(predict_net, init_net)
def __call__(self, inputs):
if self._predictor is None:
self._predictor = ProtobufDetectionModel(self._predict_net, self._init_net)
return self._predictor(inputs)
| true | true |
f7106495e4d1a8e150aa9de84bcd4cc085c2136a | 5,775 | py | Python | code/old_FINDER_CN_cost_tf/my_testReal_v2.py | faraz2023/FINDER | 170255f9a442b11e1a27483fe6eaf2ee61766454 | [
"MIT"
] | null | null | null | code/old_FINDER_CN_cost_tf/my_testReal_v2.py | faraz2023/FINDER | 170255f9a442b11e1a27483fe6eaf2ee61766454 | [
"MIT"
] | null | null | null | code/old_FINDER_CN_cost_tf/my_testReal_v2.py | faraz2023/FINDER | 170255f9a442b11e1a27483fe6eaf2ee61766454 | [
"MIT"
] | null | null | null | import sys,os
sys.path.append(os.path.dirname(__file__) + os.sep + '../')
from FINDER import FINDER
import numpy as np
from tqdm import tqdm
import time
import networkx as nx
import pandas as pd
import pickle as cp
import random
def mkdir(path):
if not os.path.exists(path):
os.mkdir(path)
g_type = "barabasi_albert"
def GetSolution(STEPRATIO, MODEL_FILE):
######################################################################################################################
##................................................Get Solution (model).....................................................
dqn = FINDER()
## data_test
data_test_path = '../../data/real/cost/'
#data_test_name = ['Crime', 'HI-II-14']
#data_test_costType = ['degree', 'random']
#data_test_name = ['HI-II-14', 'Digg']
data_test_name = ['modified-morPOP-NL-day20.txt']
data_test_costType = ['degree']
#data_test_costType = ['degree']
#model_file = './FINDER_ND_cost/models/%s'%MODEL_FILE
model_file = './models/{}'.format(MODEL_FILE)
## save_dir
save_dir = '../results/my_FINDER_CN_cost_tf/real'
if not os.path.exists(save_dir):
os.makedirs(save_dir, exist_ok=True)
save_dir_degree = save_dir + '/Data_degree'
save_dir_random = save_dir + '/Data_random'
mkdir(save_dir_degree)
mkdir(save_dir_random)
## begin computing...
print('The best model is :%s' % (model_file))
dqn.LoadModel(model_file)
for costType in data_test_costType:
df = pd.DataFrame(np.arange(1 * len(data_test_name)).reshape((1, len(data_test_name))), index=['time'],
columns=data_test_name)
#################################### modify to choose which stepRatio to get the solution
stepRatio = STEPRATIO
for j in range(len(data_test_name)):
print('Testing dataset %s' % data_test_name[j])
data_test = data_test_path + data_test_name[j] + '_' + costType + '.gml'
if costType == 'degree':
solution, time = dqn.EvaluateRealData(model_file, data_test, save_dir_degree, stepRatio)
elif costType == 'random':
solution, time = dqn.EvaluateRealData(model_file, data_test, save_dir_random, stepRatio)
df.iloc[0, j] = time
if costType == 'degree':
save_dir_local = save_dir_degree + '/StepRatio_%.4f' % stepRatio
elif costType == 'random':
save_dir_local = save_dir_random + '/StepRatio_%.4f' % stepRatio
if not os.path.exists(save_dir_local):
mkdir(save_dir_local)
df.to_csv(save_dir_local + '/solution_%s_time.csv' % costType, encoding='utf-8', index=False)
print('model has been tested!')
def EvaluateSolution(STEPRATIO, STRTEGYID):
#######################################################################################################################
##................................................Evaluate Solution.....................................................
dqn = FINDER()
## data_test
data_test_path = '../../data/real/cost/'
#data_test_name = ['Crime', 'HI-II-14']
#data_test_costType = ['degree', 'random']
#data_test_name = ['HI-II-14', 'Digg']
data_test_name = ['modified-morPOP-NL-day20.txt']
data_test_costType = ['degree']
#data_test_costType = ['degree']
## save_dir
save_dir_degree = '../results/my_FINDER_CN_cost_tf/real/Data_degree/StepRatio_%.4f/' % STEPRATIO
save_dir_random = '../results/my_FINDER_CN_cost_tf/real/Data_random/StepRatio_%.4f/' % STEPRATIO
## begin computing...
for costType in data_test_costType:
df = pd.DataFrame(np.arange(2 * len(data_test_name)).reshape((2, len(data_test_name))),
index=['solution', 'time'], columns=data_test_name)
for i in range(len(data_test_name)):
print('Evaluating dataset %s' % data_test_name[i])
data_test = data_test_path + data_test_name[i] + '_' + costType + '.gml'
if costType == 'degree':
solution = save_dir_degree + data_test_name[i] + '_degree.txt'
elif costType == 'random':
solution = save_dir_random + data_test_name[i] + '_random.txt'
t1 = time.time()
# strategyID: 0:no insert; 1:count; 2:rank; 3:multiply
################################## modify to choose which strategy to evaluate
strategyID = STRTEGYID
score, MaxCCList, solution = dqn.EvaluateSol(data_test, solution, strategyID, reInsertStep=20)
t2 = time.time()
df.iloc[0, i] = score
df.iloc[1, i] = t2 - t1
if costType == 'degree':
result_file = save_dir_degree + '/MaxCCList__Strategy_' + data_test_name[i] + '.txt'
elif costType == 'random':
result_file = save_dir_random + '/MaxCCList_Strategy_' + data_test_name[i] + '.txt'
with open(result_file, 'w') as f_out:
for j in range(len(MaxCCList)):
f_out.write('%.8f\n' % MaxCCList[j])
print('Data:%s, score:%.6f!' % (data_test_name[i], score))
if costType == 'degree':
df.to_csv(save_dir_degree + '/solution_%s_score.csv' % (costType), encoding='utf-8', index=False)
elif costType == 'random':
df.to_csv(save_dir_random + '/solution_%s_score.csv' % (costType), encoding='utf-8', index=False)
def main():
model_file = 'Model_{}/nrange_30_50_iter_400000.ckpt'.format(g_type)
#model_file = 'nrange_30_50_iter_122100.ckpt'
GetSolution(0.01, model_file)
EvaluateSolution(0.01, 0)
if __name__=="__main__":
main()
| 42.153285 | 127 | 0.56658 | import sys,os
sys.path.append(os.path.dirname(__file__) + os.sep + '../')
from FINDER import FINDER
import numpy as np
from tqdm import tqdm
import time
import networkx as nx
import pandas as pd
import pickle as cp
import random
def mkdir(path):
if not os.path.exists(path):
os.mkdir(path)
g_type = "barabasi_albert"
def GetSolution(STEPRATIO, MODEL_FILE):
| true | true |
f710660d6ad8ecf6f6d600d86493d14a6e55249c | 326,598 | py | Python | pandas/core/frame.py | UrielMaD/pandas | b5233c447f3ed0ecfe256501e357326b82ce9120 | [
"BSD-3-Clause"
] | null | null | null | pandas/core/frame.py | UrielMaD/pandas | b5233c447f3ed0ecfe256501e357326b82ce9120 | [
"BSD-3-Clause"
] | null | null | null | pandas/core/frame.py | UrielMaD/pandas | b5233c447f3ed0ecfe256501e357326b82ce9120 | [
"BSD-3-Clause"
] | null | null | null | """
DataFrame
---------
An efficient 2D container for potentially mixed-type time series or other
labeled data series.
Similar to its R counterpart, data.frame, except providing automatic data
alignment and a host of useful data manipulation methods having to do with the
labeling information
"""
from __future__ import annotations
import collections
from collections import abc
import datetime
from io import StringIO
import itertools
import mmap
from textwrap import dedent
from typing import (
IO,
TYPE_CHECKING,
Any,
AnyStr,
Dict,
FrozenSet,
Hashable,
Iterable,
Iterator,
List,
Optional,
Sequence,
Set,
Tuple,
Type,
Union,
cast,
overload,
)
import warnings
import numpy as np
import numpy.ma as ma
from pandas._config import get_option
from pandas._libs import algos as libalgos, lib, properties
from pandas._libs.lib import no_default
from pandas._typing import (
AggFuncType,
ArrayLike,
Axes,
Axis,
CompressionOptions,
Dtype,
FilePathOrBuffer,
FrameOrSeriesUnion,
IndexKeyFunc,
Label,
Level,
Renamer,
StorageOptions,
ValueKeyFunc,
)
from pandas.compat._optional import import_optional_dependency
from pandas.compat.numpy import function as nv
from pandas.util._decorators import (
Appender,
Substitution,
deprecate_kwarg,
doc,
rewrite_axis_style_signature,
)
from pandas.util._validators import (
validate_axis_style_args,
validate_bool_kwarg,
validate_percentile,
)
from pandas.core.dtypes.cast import (
cast_scalar_to_array,
coerce_to_dtypes,
construct_1d_arraylike_from_scalar,
find_common_type,
infer_dtype_from_scalar,
invalidate_string_dtypes,
maybe_box_datetimelike,
maybe_cast_to_datetime,
maybe_casted_values,
maybe_convert_platform,
maybe_downcast_to_dtype,
maybe_infer_to_datetimelike,
maybe_upcast,
validate_numeric_casting,
)
from pandas.core.dtypes.common import (
ensure_int64,
ensure_platform_int,
infer_dtype_from_object,
is_bool_dtype,
is_dataclass,
is_datetime64_any_dtype,
is_dict_like,
is_dtype_equal,
is_extension_array_dtype,
is_float,
is_float_dtype,
is_hashable,
is_integer,
is_integer_dtype,
is_iterator,
is_list_like,
is_named_tuple,
is_object_dtype,
is_scalar,
is_sequence,
pandas_dtype,
)
from pandas.core.dtypes.missing import isna, notna
from pandas.core import algorithms, common as com, generic, nanops, ops
from pandas.core.accessor import CachedAccessor
from pandas.core.aggregation import (
aggregate,
reconstruct_func,
relabel_result,
transform,
)
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays import Categorical, ExtensionArray
from pandas.core.arrays.sparse import SparseFrameAccessor
from pandas.core.construction import extract_array
from pandas.core.generic import NDFrame, _shared_docs
from pandas.core.indexes import base as ibase
from pandas.core.indexes.api import (
DatetimeIndex,
Index,
PeriodIndex,
ensure_index,
ensure_index_from_sequences,
)
from pandas.core.indexes.multi import MultiIndex, maybe_droplevels
from pandas.core.indexing import check_bool_indexer, convert_to_index_sliceable
from pandas.core.internals import BlockManager
from pandas.core.internals.construction import (
arrays_to_mgr,
dataclasses_to_dicts,
get_names_from_index,
init_dict,
init_ndarray,
masked_rec_array_to_mgr,
reorder_arrays,
sanitize_index,
to_arrays,
)
from pandas.core.reshape.melt import melt
from pandas.core.series import Series
from pandas.core.sorting import get_group_index, lexsort_indexer, nargsort
from pandas.io.common import get_handle
from pandas.io.formats import console, format as fmt
from pandas.io.formats.info import BaseInfo, DataFrameInfo
import pandas.plotting
if TYPE_CHECKING:
from typing import Literal
from pandas.core.groupby.generic import DataFrameGroupBy
from pandas.io.formats.style import Styler
# ---------------------------------------------------------------------
# Docstring templates
_shared_doc_kwargs = {
"axes": "index, columns",
"klass": "DataFrame",
"axes_single_arg": "{0 or 'index', 1 or 'columns'}",
"axis": """axis : {0 or 'index', 1 or 'columns'}, default 0
If 0 or 'index': apply function to each column.
If 1 or 'columns': apply function to each row.""",
"optional_by": """
by : str or list of str
Name or list of names to sort by.
- if `axis` is 0 or `'index'` then `by` may contain index
levels and/or column labels.
- if `axis` is 1 or `'columns'` then `by` may contain column
levels and/or index labels.""",
"optional_labels": """labels : array-like, optional
New labels / index to conform the axis specified by 'axis' to.""",
"optional_axis": """axis : int or str, optional
Axis to target. Can be either the axis name ('index', 'columns')
or number (0, 1).""",
}
_numeric_only_doc = """numeric_only : boolean, default None
Include only float, int, boolean data. If None, will attempt to use
everything, then use only numeric data
"""
_merge_doc = """
Merge DataFrame or named Series objects with a database-style join.
The join is done on columns or indexes. If joining columns on
columns, the DataFrame indexes *will be ignored*. Otherwise if joining indexes
on indexes or indexes on a column or columns, the index will be passed on.
When performing a cross merge, no column specifications to merge on are
allowed.
Parameters
----------%s
right : DataFrame or named Series
Object to merge with.
how : {'left', 'right', 'outer', 'inner', 'cross'}, default 'inner'
Type of merge to be performed.
* left: use only keys from left frame, similar to a SQL left outer join;
preserve key order.
* right: use only keys from right frame, similar to a SQL right outer join;
preserve key order.
* outer: use union of keys from both frames, similar to a SQL full outer
join; sort keys lexicographically.
* inner: use intersection of keys from both frames, similar to a SQL inner
join; preserve the order of the left keys.
* cross: creates the cartesian product from both frames, preserves the order
of the left keys.
.. versionadded:: 1.2.0
on : label or list
Column or index level names to join on. These must be found in both
DataFrames. If `on` is None and not merging on indexes then this defaults
to the intersection of the columns in both DataFrames.
left_on : label or list, or array-like
Column or index level names to join on in the left DataFrame. Can also
be an array or list of arrays of the length of the left DataFrame.
These arrays are treated as if they are columns.
right_on : label or list, or array-like
Column or index level names to join on in the right DataFrame. Can also
be an array or list of arrays of the length of the right DataFrame.
These arrays are treated as if they are columns.
left_index : bool, default False
Use the index from the left DataFrame as the join key(s). If it is a
MultiIndex, the number of keys in the other DataFrame (either the index
or a number of columns) must match the number of levels.
right_index : bool, default False
Use the index from the right DataFrame as the join key. Same caveats as
left_index.
sort : bool, default False
Sort the join keys lexicographically in the result DataFrame. If False,
the order of the join keys depends on the join type (how keyword).
suffixes : list-like, default is ("_x", "_y")
A length-2 sequence where each element is optionally a string
indicating the suffix to add to overlapping column names in
`left` and `right` respectively. Pass a value of `None` instead
of a string to indicate that the column name from `left` or
`right` should be left as-is, with no suffix. At least one of the
values must not be None.
copy : bool, default True
If False, avoid copy if possible.
indicator : bool or str, default False
If True, adds a column to the output DataFrame called "_merge" with
information on the source of each row. The column can be given a different
name by providing a string argument. The column will have a Categorical
type with the value of "left_only" for observations whose merge key only
appears in the left DataFrame, "right_only" for observations
whose merge key only appears in the right DataFrame, and "both"
if the observation's merge key is found in both DataFrames.
validate : str, optional
If specified, checks if merge is of specified type.
* "one_to_one" or "1:1": check if merge keys are unique in both
left and right datasets.
* "one_to_many" or "1:m": check if merge keys are unique in left
dataset.
* "many_to_one" or "m:1": check if merge keys are unique in right
dataset.
* "many_to_many" or "m:m": allowed, but does not result in checks.
Returns
-------
DataFrame
A DataFrame of the two merged objects.
See Also
--------
merge_ordered : Merge with optional filling/interpolation.
merge_asof : Merge on nearest keys.
DataFrame.join : Similar method using indices.
Notes
-----
Support for specifying index levels as the `on`, `left_on`, and
`right_on` parameters was added in version 0.23.0
Support for merging named Series objects was added in version 0.24.0
Examples
--------
>>> df1 = pd.DataFrame({'lkey': ['foo', 'bar', 'baz', 'foo'],
... 'value': [1, 2, 3, 5]})
>>> df2 = pd.DataFrame({'rkey': ['foo', 'bar', 'baz', 'foo'],
... 'value': [5, 6, 7, 8]})
>>> df1
lkey value
0 foo 1
1 bar 2
2 baz 3
3 foo 5
>>> df2
rkey value
0 foo 5
1 bar 6
2 baz 7
3 foo 8
Merge df1 and df2 on the lkey and rkey columns. The value columns have
the default suffixes, _x and _y, appended.
>>> df1.merge(df2, left_on='lkey', right_on='rkey')
lkey value_x rkey value_y
0 foo 1 foo 5
1 foo 1 foo 8
2 foo 5 foo 5
3 foo 5 foo 8
4 bar 2 bar 6
5 baz 3 baz 7
Merge DataFrames df1 and df2 with specified left and right suffixes
appended to any overlapping columns.
>>> df1.merge(df2, left_on='lkey', right_on='rkey',
... suffixes=('_left', '_right'))
lkey value_left rkey value_right
0 foo 1 foo 5
1 foo 1 foo 8
2 foo 5 foo 5
3 foo 5 foo 8
4 bar 2 bar 6
5 baz 3 baz 7
Merge DataFrames df1 and df2, but raise an exception if the DataFrames have
any overlapping columns.
>>> df1.merge(df2, left_on='lkey', right_on='rkey', suffixes=(False, False))
Traceback (most recent call last):
...
ValueError: columns overlap but no suffix specified:
Index(['value'], dtype='object')
>>> df1 = pd.DataFrame({'a': ['foo', 'bar'], 'b': [1, 2]})
>>> df2 = pd.DataFrame({'a': ['foo', 'baz'], 'c': [3, 4]})
>>> df1
a b
0 foo 1
1 bar 2
>>> df2
a c
0 foo 3
1 baz 4
>>> df1.merge(df2, how='inner', on='a')
a b c
0 foo 1 3
>>> df1.merge(df2, how='left', on='a')
a b c
0 foo 1 3.0
1 bar 2 NaN
>>> df1 = pd.DataFrame({'left': ['foo', 'bar']})
>>> df2 = pd.DataFrame({'right': [7, 8]})
>>> df1
left
0 foo
1 bar
>>> df2
right
0 7
1 8
>>> df1.merge(df2, how='cross')
left right
0 foo 7
1 foo 8
2 bar 7
3 bar 8
"""
# -----------------------------------------------------------------------
# DataFrame class
class DataFrame(NDFrame, OpsMixin):
"""
Two-dimensional, size-mutable, potentially heterogeneous tabular data.
Data structure also contains labeled axes (rows and columns).
Arithmetic operations align on both row and column labels. Can be
thought of as a dict-like container for Series objects. The primary
pandas data structure.
Parameters
----------
data : ndarray (structured or homogeneous), Iterable, dict, or DataFrame
Dict can contain Series, arrays, constants, dataclass or list-like objects. If
data is a dict, column order follows insertion-order.
.. versionchanged:: 0.25.0
If data is a list of dicts, column order follows insertion-order.
index : Index or array-like
Index to use for resulting frame. Will default to RangeIndex if
no indexing information part of input data and no index provided.
columns : Index or array-like
Column labels to use for resulting frame. Will default to
RangeIndex (0, 1, 2, ..., n) if no column labels are provided.
dtype : dtype, default None
Data type to force. Only a single dtype is allowed. If None, infer.
copy : bool, default False
Copy data from inputs. Only affects DataFrame / 2d ndarray input.
See Also
--------
DataFrame.from_records : Constructor from tuples, also record arrays.
DataFrame.from_dict : From dicts of Series, arrays, or dicts.
read_csv : Read a comma-separated values (csv) file into DataFrame.
read_table : Read general delimited file into DataFrame.
read_clipboard : Read text from clipboard into DataFrame.
Examples
--------
Constructing DataFrame from a dictionary.
>>> d = {'col1': [1, 2], 'col2': [3, 4]}
>>> df = pd.DataFrame(data=d)
>>> df
col1 col2
0 1 3
1 2 4
Notice that the inferred dtype is int64.
>>> df.dtypes
col1 int64
col2 int64
dtype: object
To enforce a single dtype:
>>> df = pd.DataFrame(data=d, dtype=np.int8)
>>> df.dtypes
col1 int8
col2 int8
dtype: object
Constructing DataFrame from numpy ndarray:
>>> df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
... columns=['a', 'b', 'c'])
>>> df2
a b c
0 1 2 3
1 4 5 6
2 7 8 9
Constructing DataFrame from dataclass:
>>> from dataclasses import make_dataclass
>>> Point = make_dataclass("Point", [("x", int), ("y", int)])
>>> pd.DataFrame([Point(0, 0), Point(0, 3), Point(2, 3)])
x y
0 0 0
1 0 3
2 2 3
"""
_internal_names_set = {"columns", "index"} | NDFrame._internal_names_set
_typ = "dataframe"
_HANDLED_TYPES = (Series, Index, ExtensionArray, np.ndarray)
@property
def _constructor(self) -> Type[DataFrame]:
return DataFrame
_constructor_sliced: Type[Series] = Series
_hidden_attrs: FrozenSet[str] = NDFrame._hidden_attrs | frozenset([])
_accessors: Set[str] = {"sparse"}
@property
def _constructor_expanddim(self):
# GH#31549 raising NotImplementedError on a property causes trouble
# for `inspect`
def constructor(*args, **kwargs):
raise NotImplementedError("Not supported for DataFrames!")
return constructor
# ----------------------------------------------------------------------
# Constructors
def __init__(
self,
data=None,
index: Optional[Axes] = None,
columns: Optional[Axes] = None,
dtype: Optional[Dtype] = None,
copy: bool = False,
):
if data is None:
data = {}
if dtype is not None:
dtype = self._validate_dtype(dtype)
if isinstance(data, DataFrame):
data = data._mgr
if isinstance(data, BlockManager):
if index is None and columns is None and dtype is None and copy is False:
# GH#33357 fastpath
NDFrame.__init__(self, data)
return
mgr = self._init_mgr(
data, axes={"index": index, "columns": columns}, dtype=dtype, copy=copy
)
elif isinstance(data, dict):
mgr = init_dict(data, index, columns, dtype=dtype)
elif isinstance(data, ma.MaskedArray):
import numpy.ma.mrecords as mrecords
# masked recarray
if isinstance(data, mrecords.MaskedRecords):
mgr = masked_rec_array_to_mgr(data, index, columns, dtype, copy)
# a masked array
else:
mask = ma.getmaskarray(data)
if mask.any():
data, fill_value = maybe_upcast(data, copy=True)
data.soften_mask() # set hardmask False if it was True
data[mask] = fill_value
else:
data = data.copy()
mgr = init_ndarray(data, index, columns, dtype=dtype, copy=copy)
elif isinstance(data, (np.ndarray, Series, Index)):
if data.dtype.names:
data_columns = list(data.dtype.names)
data = {k: data[k] for k in data_columns}
if columns is None:
columns = data_columns
mgr = init_dict(data, index, columns, dtype=dtype)
elif getattr(data, "name", None) is not None:
mgr = init_dict({data.name: data}, index, columns, dtype=dtype)
else:
mgr = init_ndarray(data, index, columns, dtype=dtype, copy=copy)
# For data is list-like, or Iterable (will consume into list)
elif isinstance(data, abc.Iterable) and not isinstance(data, (str, bytes)):
if not isinstance(data, (abc.Sequence, ExtensionArray)):
data = list(data)
if len(data) > 0:
if is_dataclass(data[0]):
data = dataclasses_to_dicts(data)
if is_list_like(data[0]) and getattr(data[0], "ndim", 1) == 1:
if is_named_tuple(data[0]) and columns is None:
columns = data[0]._fields
arrays, columns = to_arrays(data, columns, dtype=dtype)
columns = ensure_index(columns)
# set the index
if index is None:
if isinstance(data[0], Series):
index = get_names_from_index(data)
elif isinstance(data[0], Categorical):
index = ibase.default_index(len(data[0]))
else:
index = ibase.default_index(len(data))
mgr = arrays_to_mgr(arrays, columns, index, columns, dtype=dtype)
else:
mgr = init_ndarray(data, index, columns, dtype=dtype, copy=copy)
else:
mgr = init_dict({}, index, columns, dtype=dtype)
# For data is scalar
else:
if index is None or columns is None:
raise ValueError("DataFrame constructor not properly called!")
if not dtype:
dtype, _ = infer_dtype_from_scalar(data, pandas_dtype=True)
# For data is a scalar extension dtype
if is_extension_array_dtype(dtype):
values = [
construct_1d_arraylike_from_scalar(data, len(index), dtype)
for _ in range(len(columns))
]
mgr = arrays_to_mgr(values, columns, index, columns, dtype=None)
else:
# Attempt to coerce to a numpy array
try:
arr = np.array(data, dtype=dtype, copy=copy)
except (ValueError, TypeError) as err:
exc = TypeError(
"DataFrame constructor called with "
f"incompatible data and dtype: {err}"
)
raise exc from err
if arr.ndim != 0:
raise ValueError("DataFrame constructor not properly called!")
values = cast_scalar_to_array(
(len(index), len(columns)), data, dtype=dtype
)
mgr = init_ndarray(
values, index, columns, dtype=values.dtype, copy=False
)
NDFrame.__init__(self, mgr)
# ----------------------------------------------------------------------
@property
def axes(self) -> List[Index]:
"""
Return a list representing the axes of the DataFrame.
It has the row axis labels and column axis labels as the only members.
They are returned in that order.
Examples
--------
>>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
>>> df.axes
[RangeIndex(start=0, stop=2, step=1), Index(['col1', 'col2'],
dtype='object')]
"""
return [self.index, self.columns]
@property
def shape(self) -> Tuple[int, int]:
"""
Return a tuple representing the dimensionality of the DataFrame.
See Also
--------
ndarray.shape : Tuple of array dimensions.
Examples
--------
>>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
>>> df.shape
(2, 2)
>>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4],
... 'col3': [5, 6]})
>>> df.shape
(2, 3)
"""
return len(self.index), len(self.columns)
@property
def _is_homogeneous_type(self) -> bool:
"""
Whether all the columns in a DataFrame have the same type.
Returns
-------
bool
See Also
--------
Index._is_homogeneous_type : Whether the object has a single
dtype.
MultiIndex._is_homogeneous_type : Whether all the levels of a
MultiIndex have the same dtype.
Examples
--------
>>> DataFrame({"A": [1, 2], "B": [3, 4]})._is_homogeneous_type
True
>>> DataFrame({"A": [1, 2], "B": [3.0, 4.0]})._is_homogeneous_type
False
Items with the same type but different sizes are considered
different types.
>>> DataFrame({
... "A": np.array([1, 2], dtype=np.int32),
... "B": np.array([1, 2], dtype=np.int64)})._is_homogeneous_type
False
"""
if self._mgr.any_extension_types:
return len({block.dtype for block in self._mgr.blocks}) == 1
else:
return not self._is_mixed_type
@property
def _can_fast_transpose(self) -> bool:
"""
Can we transpose this DataFrame without creating any new array objects.
"""
if self._mgr.any_extension_types:
# TODO(EA2D) special case would be unnecessary with 2D EAs
return False
return len(self._mgr.blocks) == 1
# ----------------------------------------------------------------------
# Rendering Methods
def _repr_fits_vertical_(self) -> bool:
"""
Check length against max_rows.
"""
max_rows = get_option("display.max_rows")
return len(self) <= max_rows
def _repr_fits_horizontal_(self, ignore_width: bool = False) -> bool:
"""
Check if full repr fits in horizontal boundaries imposed by the display
options width and max_columns.
In case of non-interactive session, no boundaries apply.
`ignore_width` is here so ipynb+HTML output can behave the way
users expect. display.max_columns remains in effect.
GH3541, GH3573
"""
width, height = console.get_console_size()
max_columns = get_option("display.max_columns")
nb_columns = len(self.columns)
# exceed max columns
if (max_columns and nb_columns > max_columns) or (
(not ignore_width) and width and nb_columns > (width // 2)
):
return False
# used by repr_html under IPython notebook or scripts ignore terminal
# dims
if ignore_width or not console.in_interactive_session():
return True
if get_option("display.width") is not None or console.in_ipython_frontend():
# check at least the column row for excessive width
max_rows = 1
else:
max_rows = get_option("display.max_rows")
# when auto-detecting, so width=None and not in ipython front end
# check whether repr fits horizontal by actually checking
# the width of the rendered repr
buf = StringIO()
# only care about the stuff we'll actually print out
# and to_string on entire frame may be expensive
d = self
if not (max_rows is None): # unlimited rows
# min of two, where one may be None
d = d.iloc[: min(max_rows, len(d))]
else:
return True
d.to_string(buf=buf)
value = buf.getvalue()
repr_width = max(len(line) for line in value.split("\n"))
return repr_width < width
def _info_repr(self) -> bool:
"""
True if the repr should show the info view.
"""
info_repr_option = get_option("display.large_repr") == "info"
return info_repr_option and not (
self._repr_fits_horizontal_() and self._repr_fits_vertical_()
)
def __repr__(self) -> str:
"""
Return a string representation for a particular DataFrame.
"""
buf = StringIO("")
if self._info_repr():
self.info(buf=buf)
return buf.getvalue()
max_rows = get_option("display.max_rows")
min_rows = get_option("display.min_rows")
max_cols = get_option("display.max_columns")
max_colwidth = get_option("display.max_colwidth")
show_dimensions = get_option("display.show_dimensions")
if get_option("display.expand_frame_repr"):
width, _ = console.get_console_size()
else:
width = None
self.to_string(
buf=buf,
max_rows=max_rows,
min_rows=min_rows,
max_cols=max_cols,
line_width=width,
max_colwidth=max_colwidth,
show_dimensions=show_dimensions,
)
return buf.getvalue()
def _repr_html_(self) -> Optional[str]:
"""
Return a html representation for a particular DataFrame.
Mainly for IPython notebook.
"""
if self._info_repr():
buf = StringIO("")
self.info(buf=buf)
# need to escape the <class>, should be the first line.
val = buf.getvalue().replace("<", r"<", 1)
val = val.replace(">", r">", 1)
return "<pre>" + val + "</pre>"
if get_option("display.notebook_repr_html"):
max_rows = get_option("display.max_rows")
min_rows = get_option("display.min_rows")
max_cols = get_option("display.max_columns")
show_dimensions = get_option("display.show_dimensions")
formatter = fmt.DataFrameFormatter(
self,
columns=None,
col_space=None,
na_rep="NaN",
formatters=None,
float_format=None,
sparsify=None,
justify=None,
index_names=True,
header=True,
index=True,
bold_rows=True,
escape=True,
max_rows=max_rows,
min_rows=min_rows,
max_cols=max_cols,
show_dimensions=show_dimensions,
decimal=".",
)
return fmt.DataFrameRenderer(formatter).to_html(notebook=True)
else:
return None
@Substitution(
header_type="bool or sequence",
header="Write out the column names. If a list of strings "
"is given, it is assumed to be aliases for the "
"column names",
col_space_type="int, list or dict of int",
col_space="The minimum width of each column",
)
@Substitution(shared_params=fmt.common_docstring, returns=fmt.return_docstring)
def to_string(
self,
buf: Optional[FilePathOrBuffer[str]] = None,
columns: Optional[Sequence[str]] = None,
col_space: Optional[int] = None,
header: Union[bool, Sequence[str]] = True,
index: bool = True,
na_rep: str = "NaN",
formatters: Optional[fmt.FormattersType] = None,
float_format: Optional[fmt.FloatFormatType] = None,
sparsify: Optional[bool] = None,
index_names: bool = True,
justify: Optional[str] = None,
max_rows: Optional[int] = None,
min_rows: Optional[int] = None,
max_cols: Optional[int] = None,
show_dimensions: bool = False,
decimal: str = ".",
line_width: Optional[int] = None,
max_colwidth: Optional[int] = None,
encoding: Optional[str] = None,
) -> Optional[str]:
"""
Render a DataFrame to a console-friendly tabular output.
%(shared_params)s
line_width : int, optional
Width to wrap a line in characters.
max_colwidth : int, optional
Max width to truncate each column in characters. By default, no limit.
.. versionadded:: 1.0.0
encoding : str, default "utf-8"
Set character encoding.
.. versionadded:: 1.0
%(returns)s
See Also
--------
to_html : Convert DataFrame to HTML.
Examples
--------
>>> d = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}
>>> df = pd.DataFrame(d)
>>> print(df.to_string())
col1 col2
0 1 4
1 2 5
2 3 6
"""
from pandas import option_context
with option_context("display.max_colwidth", max_colwidth):
formatter = fmt.DataFrameFormatter(
self,
columns=columns,
col_space=col_space,
na_rep=na_rep,
formatters=formatters,
float_format=float_format,
sparsify=sparsify,
justify=justify,
index_names=index_names,
header=header,
index=index,
min_rows=min_rows,
max_rows=max_rows,
max_cols=max_cols,
show_dimensions=show_dimensions,
decimal=decimal,
)
return fmt.DataFrameRenderer(formatter).to_string(
buf=buf,
encoding=encoding,
line_width=line_width,
)
# ----------------------------------------------------------------------
@property
def style(self) -> Styler:
"""
Returns a Styler object.
Contains methods for building a styled HTML representation of the DataFrame.
See Also
--------
io.formats.style.Styler : Helps style a DataFrame or Series according to the
data with HTML and CSS.
"""
from pandas.io.formats.style import Styler
return Styler(self)
_shared_docs[
"items"
] = r"""
Iterate over (column name, Series) pairs.
Iterates over the DataFrame columns, returning a tuple with
the column name and the content as a Series.
Yields
------
label : object
The column names for the DataFrame being iterated over.
content : Series
The column entries belonging to each label, as a Series.
See Also
--------
DataFrame.iterrows : Iterate over DataFrame rows as
(index, Series) pairs.
DataFrame.itertuples : Iterate over DataFrame rows as namedtuples
of the values.
Examples
--------
>>> df = pd.DataFrame({'species': ['bear', 'bear', 'marsupial'],
... 'population': [1864, 22000, 80000]},
... index=['panda', 'polar', 'koala'])
>>> df
species population
panda bear 1864
polar bear 22000
koala marsupial 80000
>>> for label, content in df.items():
... print(f'label: {label}')
... print(f'content: {content}', sep='\n')
...
label: species
content:
panda bear
polar bear
koala marsupial
Name: species, dtype: object
label: population
content:
panda 1864
polar 22000
koala 80000
Name: population, dtype: int64
"""
@Appender(_shared_docs["items"])
def items(self) -> Iterable[Tuple[Label, Series]]:
if self.columns.is_unique and hasattr(self, "_item_cache"):
for k in self.columns:
yield k, self._get_item_cache(k)
else:
for i, k in enumerate(self.columns):
yield k, self._ixs(i, axis=1)
@Appender(_shared_docs["items"])
def iteritems(self) -> Iterable[Tuple[Label, Series]]:
yield from self.items()
def iterrows(self) -> Iterable[Tuple[Label, Series]]:
"""
Iterate over DataFrame rows as (index, Series) pairs.
Yields
------
index : label or tuple of label
The index of the row. A tuple for a `MultiIndex`.
data : Series
The data of the row as a Series.
See Also
--------
DataFrame.itertuples : Iterate over DataFrame rows as namedtuples of the values.
DataFrame.items : Iterate over (column name, Series) pairs.
Notes
-----
1. Because ``iterrows`` returns a Series for each row,
it does **not** preserve dtypes across the rows (dtypes are
preserved across columns for DataFrames). For example,
>>> df = pd.DataFrame([[1, 1.5]], columns=['int', 'float'])
>>> row = next(df.iterrows())[1]
>>> row
int 1.0
float 1.5
Name: 0, dtype: float64
>>> print(row['int'].dtype)
float64
>>> print(df['int'].dtype)
int64
To preserve dtypes while iterating over the rows, it is better
to use :meth:`itertuples` which returns namedtuples of the values
and which is generally faster than ``iterrows``.
2. You should **never modify** something you are iterating over.
This is not guaranteed to work in all cases. Depending on the
data types, the iterator returns a copy and not a view, and writing
to it will have no effect.
"""
columns = self.columns
klass = self._constructor_sliced
for k, v in zip(self.index, self.values):
s = klass(v, index=columns, name=k)
yield k, s
def itertuples(self, index: bool = True, name: Optional[str] = "Pandas"):
"""
Iterate over DataFrame rows as namedtuples.
Parameters
----------
index : bool, default True
If True, return the index as the first element of the tuple.
name : str or None, default "Pandas"
The name of the returned namedtuples or None to return regular
tuples.
Returns
-------
iterator
An object to iterate over namedtuples for each row in the
DataFrame with the first field possibly being the index and
following fields being the column values.
See Also
--------
DataFrame.iterrows : Iterate over DataFrame rows as (index, Series)
pairs.
DataFrame.items : Iterate over (column name, Series) pairs.
Notes
-----
The column names will be renamed to positional names if they are
invalid Python identifiers, repeated, or start with an underscore.
On python versions < 3.7 regular tuples are returned for DataFrames
with a large number of columns (>254).
Examples
--------
>>> df = pd.DataFrame({'num_legs': [4, 2], 'num_wings': [0, 2]},
... index=['dog', 'hawk'])
>>> df
num_legs num_wings
dog 4 0
hawk 2 2
>>> for row in df.itertuples():
... print(row)
...
Pandas(Index='dog', num_legs=4, num_wings=0)
Pandas(Index='hawk', num_legs=2, num_wings=2)
By setting the `index` parameter to False we can remove the index
as the first element of the tuple:
>>> for row in df.itertuples(index=False):
... print(row)
...
Pandas(num_legs=4, num_wings=0)
Pandas(num_legs=2, num_wings=2)
With the `name` parameter set we set a custom name for the yielded
namedtuples:
>>> for row in df.itertuples(name='Animal'):
... print(row)
...
Animal(Index='dog', num_legs=4, num_wings=0)
Animal(Index='hawk', num_legs=2, num_wings=2)
"""
arrays = []
fields = list(self.columns)
if index:
arrays.append(self.index)
fields.insert(0, "Index")
# use integer indexing because of possible duplicate column names
arrays.extend(self.iloc[:, k] for k in range(len(self.columns)))
if name is not None:
# https://github.com/python/mypy/issues/9046
# error: namedtuple() expects a string literal as the first argument
itertuple = collections.namedtuple( # type: ignore[misc]
name, fields, rename=True
)
return map(itertuple._make, zip(*arrays))
# fallback to regular tuples
return zip(*arrays)
def __len__(self) -> int:
"""
Returns length of info axis, but here we use the index.
"""
return len(self.index)
def dot(self, other):
"""
Compute the matrix multiplication between the DataFrame and other.
This method computes the matrix product between the DataFrame and the
values of an other Series, DataFrame or a numpy array.
It can also be called using ``self @ other`` in Python >= 3.5.
Parameters
----------
other : Series, DataFrame or array-like
The other object to compute the matrix product with.
Returns
-------
Series or DataFrame
If other is a Series, return the matrix product between self and
other as a Series. If other is a DataFrame or a numpy.array, return
the matrix product of self and other in a DataFrame of a np.array.
See Also
--------
Series.dot: Similar method for Series.
Notes
-----
The dimensions of DataFrame and other must be compatible in order to
compute the matrix multiplication. In addition, the column names of
DataFrame and the index of other must contain the same values, as they
will be aligned prior to the multiplication.
The dot method for Series computes the inner product, instead of the
matrix product here.
Examples
--------
Here we multiply a DataFrame with a Series.
>>> df = pd.DataFrame([[0, 1, -2, -1], [1, 1, 1, 1]])
>>> s = pd.Series([1, 1, 2, 1])
>>> df.dot(s)
0 -4
1 5
dtype: int64
Here we multiply a DataFrame with another DataFrame.
>>> other = pd.DataFrame([[0, 1], [1, 2], [-1, -1], [2, 0]])
>>> df.dot(other)
0 1
0 1 4
1 2 2
Note that the dot method give the same result as @
>>> df @ other
0 1
0 1 4
1 2 2
The dot method works also if other is an np.array.
>>> arr = np.array([[0, 1], [1, 2], [-1, -1], [2, 0]])
>>> df.dot(arr)
0 1
0 1 4
1 2 2
Note how shuffling of the objects does not change the result.
>>> s2 = s.reindex([1, 0, 2, 3])
>>> df.dot(s2)
0 -4
1 5
dtype: int64
"""
if isinstance(other, (Series, DataFrame)):
common = self.columns.union(other.index)
if len(common) > len(self.columns) or len(common) > len(other.index):
raise ValueError("matrices are not aligned")
left = self.reindex(columns=common, copy=False)
right = other.reindex(index=common, copy=False)
lvals = left.values
rvals = right._values
else:
left = self
lvals = self.values
rvals = np.asarray(other)
if lvals.shape[1] != rvals.shape[0]:
raise ValueError(
f"Dot product shape mismatch, {lvals.shape} vs {rvals.shape}"
)
if isinstance(other, DataFrame):
return self._constructor(
np.dot(lvals, rvals), index=left.index, columns=other.columns
)
elif isinstance(other, Series):
return self._constructor_sliced(np.dot(lvals, rvals), index=left.index)
elif isinstance(rvals, (np.ndarray, Index)):
result = np.dot(lvals, rvals)
if result.ndim == 2:
return self._constructor(result, index=left.index)
else:
return self._constructor_sliced(result, index=left.index)
else: # pragma: no cover
raise TypeError(f"unsupported type: {type(other)}")
def __matmul__(self, other):
"""
Matrix multiplication using binary `@` operator in Python>=3.5.
"""
return self.dot(other)
def __rmatmul__(self, other):
"""
Matrix multiplication using binary `@` operator in Python>=3.5.
"""
try:
return self.T.dot(np.transpose(other)).T
except ValueError as err:
if "shape mismatch" not in str(err):
raise
# GH#21581 give exception message for original shapes
msg = f"shapes {np.shape(other)} and {self.shape} not aligned"
raise ValueError(msg) from err
# ----------------------------------------------------------------------
# IO methods (to / from other formats)
@classmethod
def from_dict(cls, data, orient="columns", dtype=None, columns=None) -> DataFrame:
"""
Construct DataFrame from dict of array-like or dicts.
Creates DataFrame object from dictionary by columns or by index
allowing dtype specification.
Parameters
----------
data : dict
Of the form {field : array-like} or {field : dict}.
orient : {'columns', 'index'}, default 'columns'
The "orientation" of the data. If the keys of the passed dict
should be the columns of the resulting DataFrame, pass 'columns'
(default). Otherwise if the keys should be rows, pass 'index'.
dtype : dtype, default None
Data type to force, otherwise infer.
columns : list, default None
Column labels to use when ``orient='index'``. Raises a ValueError
if used with ``orient='columns'``.
Returns
-------
DataFrame
See Also
--------
DataFrame.from_records : DataFrame from structured ndarray, sequence
of tuples or dicts, or DataFrame.
DataFrame : DataFrame object creation using constructor.
Examples
--------
By default the keys of the dict become the DataFrame columns:
>>> data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']}
>>> pd.DataFrame.from_dict(data)
col_1 col_2
0 3 a
1 2 b
2 1 c
3 0 d
Specify ``orient='index'`` to create the DataFrame using dictionary
keys as rows:
>>> data = {'row_1': [3, 2, 1, 0], 'row_2': ['a', 'b', 'c', 'd']}
>>> pd.DataFrame.from_dict(data, orient='index')
0 1 2 3
row_1 3 2 1 0
row_2 a b c d
When using the 'index' orientation, the column names can be
specified manually:
>>> pd.DataFrame.from_dict(data, orient='index',
... columns=['A', 'B', 'C', 'D'])
A B C D
row_1 3 2 1 0
row_2 a b c d
"""
index = None
orient = orient.lower()
if orient == "index":
if len(data) > 0:
# TODO speed up Series case
if isinstance(list(data.values())[0], (Series, dict)):
data = _from_nested_dict(data)
else:
data, index = list(data.values()), list(data.keys())
elif orient == "columns":
if columns is not None:
raise ValueError("cannot use columns parameter with orient='columns'")
else: # pragma: no cover
raise ValueError("only recognize index or columns for orient")
return cls(data, index=index, columns=columns, dtype=dtype)
def to_numpy(
self, dtype=None, copy: bool = False, na_value=lib.no_default
) -> np.ndarray:
"""
Convert the DataFrame to a NumPy array.
.. versionadded:: 0.24.0
By default, the dtype of the returned array will be the common NumPy
dtype of all types in the DataFrame. For example, if the dtypes are
``float16`` and ``float32``, the results dtype will be ``float32``.
This may require copying data and coercing values, which may be
expensive.
Parameters
----------
dtype : str or numpy.dtype, optional
The dtype to pass to :meth:`numpy.asarray`.
copy : bool, default False
Whether to ensure that the returned value is not a view on
another array. Note that ``copy=False`` does not *ensure* that
``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that
a copy is made, even if not strictly necessary.
na_value : Any, optional
The value to use for missing values. The default value depends
on `dtype` and the dtypes of the DataFrame columns.
.. versionadded:: 1.1.0
Returns
-------
numpy.ndarray
See Also
--------
Series.to_numpy : Similar method for Series.
Examples
--------
>>> pd.DataFrame({"A": [1, 2], "B": [3, 4]}).to_numpy()
array([[1, 3],
[2, 4]])
With heterogeneous data, the lowest common type will have to
be used.
>>> df = pd.DataFrame({"A": [1, 2], "B": [3.0, 4.5]})
>>> df.to_numpy()
array([[1. , 3. ],
[2. , 4.5]])
For a mix of numeric and non-numeric types, the output array will
have object dtype.
>>> df['C'] = pd.date_range('2000', periods=2)
>>> df.to_numpy()
array([[1, 3.0, Timestamp('2000-01-01 00:00:00')],
[2, 4.5, Timestamp('2000-01-02 00:00:00')]], dtype=object)
"""
self._consolidate_inplace()
result = self._mgr.as_array(
transpose=self._AXIS_REVERSED, dtype=dtype, copy=copy, na_value=na_value
)
if result.dtype is not dtype:
result = np.array(result, dtype=dtype, copy=False)
return result
def to_dict(self, orient="dict", into=dict):
"""
Convert the DataFrame to a dictionary.
The type of the key-value pairs can be customized with the parameters
(see below).
Parameters
----------
orient : str {'dict', 'list', 'series', 'split', 'records', 'index'}
Determines the type of the values of the dictionary.
- 'dict' (default) : dict like {column -> {index -> value}}
- 'list' : dict like {column -> [values]}
- 'series' : dict like {column -> Series(values)}
- 'split' : dict like
{'index' -> [index], 'columns' -> [columns], 'data' -> [values]}
- 'records' : list like
[{column -> value}, ... , {column -> value}]
- 'index' : dict like {index -> {column -> value}}
Abbreviations are allowed. `s` indicates `series` and `sp`
indicates `split`.
into : class, default dict
The collections.abc.Mapping subclass used for all Mappings
in the return value. Can be the actual class or an empty
instance of the mapping type you want. If you want a
collections.defaultdict, you must pass it initialized.
Returns
-------
dict, list or collections.abc.Mapping
Return a collections.abc.Mapping object representing the DataFrame.
The resulting transformation depends on the `orient` parameter.
See Also
--------
DataFrame.from_dict: Create a DataFrame from a dictionary.
DataFrame.to_json: Convert a DataFrame to JSON format.
Examples
--------
>>> df = pd.DataFrame({'col1': [1, 2],
... 'col2': [0.5, 0.75]},
... index=['row1', 'row2'])
>>> df
col1 col2
row1 1 0.50
row2 2 0.75
>>> df.to_dict()
{'col1': {'row1': 1, 'row2': 2}, 'col2': {'row1': 0.5, 'row2': 0.75}}
You can specify the return orientation.
>>> df.to_dict('series')
{'col1': row1 1
row2 2
Name: col1, dtype: int64,
'col2': row1 0.50
row2 0.75
Name: col2, dtype: float64}
>>> df.to_dict('split')
{'index': ['row1', 'row2'], 'columns': ['col1', 'col2'],
'data': [[1, 0.5], [2, 0.75]]}
>>> df.to_dict('records')
[{'col1': 1, 'col2': 0.5}, {'col1': 2, 'col2': 0.75}]
>>> df.to_dict('index')
{'row1': {'col1': 1, 'col2': 0.5}, 'row2': {'col1': 2, 'col2': 0.75}}
You can also specify the mapping type.
>>> from collections import OrderedDict, defaultdict
>>> df.to_dict(into=OrderedDict)
OrderedDict([('col1', OrderedDict([('row1', 1), ('row2', 2)])),
('col2', OrderedDict([('row1', 0.5), ('row2', 0.75)]))])
If you want a `defaultdict`, you need to initialize it:
>>> dd = defaultdict(list)
>>> df.to_dict('records', into=dd)
[defaultdict(<class 'list'>, {'col1': 1, 'col2': 0.5}),
defaultdict(<class 'list'>, {'col1': 2, 'col2': 0.75})]
"""
if not self.columns.is_unique:
warnings.warn(
"DataFrame columns are not unique, some columns will be omitted.",
UserWarning,
stacklevel=2,
)
# GH16122
into_c = com.standardize_mapping(into)
orient = orient.lower()
# GH32515
if orient.startswith(("d", "l", "s", "r", "i")) and orient not in {
"dict",
"list",
"series",
"split",
"records",
"index",
}:
warnings.warn(
"Using short name for 'orient' is deprecated. Only the "
"options: ('dict', list, 'series', 'split', 'records', 'index') "
"will be used in a future version. Use one of the above "
"to silence this warning.",
FutureWarning,
)
if orient.startswith("d"):
orient = "dict"
elif orient.startswith("l"):
orient = "list"
elif orient.startswith("sp"):
orient = "split"
elif orient.startswith("s"):
orient = "series"
elif orient.startswith("r"):
orient = "records"
elif orient.startswith("i"):
orient = "index"
if orient == "dict":
return into_c((k, v.to_dict(into)) for k, v in self.items())
elif orient == "list":
return into_c((k, v.tolist()) for k, v in self.items())
elif orient == "split":
return into_c(
(
("index", self.index.tolist()),
("columns", self.columns.tolist()),
(
"data",
[
list(map(maybe_box_datetimelike, t))
for t in self.itertuples(index=False, name=None)
],
),
)
)
elif orient == "series":
return into_c((k, maybe_box_datetimelike(v)) for k, v in self.items())
elif orient == "records":
columns = self.columns.tolist()
rows = (
dict(zip(columns, row))
for row in self.itertuples(index=False, name=None)
)
return [
into_c((k, maybe_box_datetimelike(v)) for k, v in row.items())
for row in rows
]
elif orient == "index":
if not self.index.is_unique:
raise ValueError("DataFrame index must be unique for orient='index'.")
return into_c(
(t[0], dict(zip(self.columns, t[1:])))
for t in self.itertuples(name=None)
)
else:
raise ValueError(f"orient '{orient}' not understood")
def to_gbq(
self,
destination_table,
project_id=None,
chunksize=None,
reauth=False,
if_exists="fail",
auth_local_webserver=False,
table_schema=None,
location=None,
progress_bar=True,
credentials=None,
) -> None:
"""
Write a DataFrame to a Google BigQuery table.
This function requires the `pandas-gbq package
<https://pandas-gbq.readthedocs.io>`__.
See the `How to authenticate with Google BigQuery
<https://pandas-gbq.readthedocs.io/en/latest/howto/authentication.html>`__
guide for authentication instructions.
Parameters
----------
destination_table : str
Name of table to be written, in the form ``dataset.tablename``.
project_id : str, optional
Google BigQuery Account project ID. Optional when available from
the environment.
chunksize : int, optional
Number of rows to be inserted in each chunk from the dataframe.
Set to ``None`` to load the whole dataframe at once.
reauth : bool, default False
Force Google BigQuery to re-authenticate the user. This is useful
if multiple accounts are used.
if_exists : str, default 'fail'
Behavior when the destination table exists. Value can be one of:
``'fail'``
If table exists raise pandas_gbq.gbq.TableCreationError.
``'replace'``
If table exists, drop it, recreate it, and insert data.
``'append'``
If table exists, insert data. Create if does not exist.
auth_local_webserver : bool, default False
Use the `local webserver flow`_ instead of the `console flow`_
when getting user credentials.
.. _local webserver flow:
https://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_local_server
.. _console flow:
https://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_console
*New in version 0.2.0 of pandas-gbq*.
table_schema : list of dicts, optional
List of BigQuery table fields to which according DataFrame
columns conform to, e.g. ``[{'name': 'col1', 'type':
'STRING'},...]``. If schema is not provided, it will be
generated according to dtypes of DataFrame columns. See
BigQuery API documentation on available names of a field.
*New in version 0.3.1 of pandas-gbq*.
location : str, optional
Location where the load job should run. See the `BigQuery locations
documentation
<https://cloud.google.com/bigquery/docs/dataset-locations>`__ for a
list of available locations. The location must match that of the
target dataset.
*New in version 0.5.0 of pandas-gbq*.
progress_bar : bool, default True
Use the library `tqdm` to show the progress bar for the upload,
chunk by chunk.
*New in version 0.5.0 of pandas-gbq*.
credentials : google.auth.credentials.Credentials, optional
Credentials for accessing Google APIs. Use this parameter to
override default credentials, such as to use Compute Engine
:class:`google.auth.compute_engine.Credentials` or Service
Account :class:`google.oauth2.service_account.Credentials`
directly.
*New in version 0.8.0 of pandas-gbq*.
.. versionadded:: 0.24.0
See Also
--------
pandas_gbq.to_gbq : This function in the pandas-gbq library.
read_gbq : Read a DataFrame from Google BigQuery.
"""
from pandas.io import gbq
gbq.to_gbq(
self,
destination_table,
project_id=project_id,
chunksize=chunksize,
reauth=reauth,
if_exists=if_exists,
auth_local_webserver=auth_local_webserver,
table_schema=table_schema,
location=location,
progress_bar=progress_bar,
credentials=credentials,
)
@classmethod
def from_records(
cls,
data,
index=None,
exclude=None,
columns=None,
coerce_float=False,
nrows=None,
) -> DataFrame:
"""
Convert structured or record ndarray to DataFrame.
Creates a DataFrame object from a structured ndarray, sequence of
tuples or dicts, or DataFrame.
Parameters
----------
data : structured ndarray, sequence of tuples or dicts, or DataFrame
Structured input data.
index : str, list of fields, array-like
Field of array to use as the index, alternately a specific set of
input labels to use.
exclude : sequence, default None
Columns or fields to exclude.
columns : sequence, default None
Column names to use. If the passed data do not have names
associated with them, this argument provides names for the
columns. Otherwise this argument indicates the order of the columns
in the result (any names not found in the data will become all-NA
columns).
coerce_float : bool, default False
Attempt to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets.
nrows : int, default None
Number of rows to read if data is an iterator.
Returns
-------
DataFrame
See Also
--------
DataFrame.from_dict : DataFrame from dict of array-like or dicts.
DataFrame : DataFrame object creation using constructor.
Examples
--------
Data can be provided as a structured ndarray:
>>> data = np.array([(3, 'a'), (2, 'b'), (1, 'c'), (0, 'd')],
... dtype=[('col_1', 'i4'), ('col_2', 'U1')])
>>> pd.DataFrame.from_records(data)
col_1 col_2
0 3 a
1 2 b
2 1 c
3 0 d
Data can be provided as a list of dicts:
>>> data = [{'col_1': 3, 'col_2': 'a'},
... {'col_1': 2, 'col_2': 'b'},
... {'col_1': 1, 'col_2': 'c'},
... {'col_1': 0, 'col_2': 'd'}]
>>> pd.DataFrame.from_records(data)
col_1 col_2
0 3 a
1 2 b
2 1 c
3 0 d
Data can be provided as a list of tuples with corresponding columns:
>>> data = [(3, 'a'), (2, 'b'), (1, 'c'), (0, 'd')]
>>> pd.DataFrame.from_records(data, columns=['col_1', 'col_2'])
col_1 col_2
0 3 a
1 2 b
2 1 c
3 0 d
"""
# Make a copy of the input columns so we can modify it
if columns is not None:
columns = ensure_index(columns)
if is_iterator(data):
if nrows == 0:
return cls()
try:
first_row = next(data)
except StopIteration:
return cls(index=index, columns=columns)
dtype = None
if hasattr(first_row, "dtype") and first_row.dtype.names:
dtype = first_row.dtype
values = [first_row]
if nrows is None:
values += data
else:
values.extend(itertools.islice(data, nrows - 1))
if dtype is not None:
data = np.array(values, dtype=dtype)
else:
data = values
if isinstance(data, dict):
if columns is None:
columns = arr_columns = ensure_index(sorted(data))
arrays = [data[k] for k in columns]
else:
arrays = []
arr_columns_list = []
for k, v in data.items():
if k in columns:
arr_columns_list.append(k)
arrays.append(v)
arrays, arr_columns = reorder_arrays(arrays, arr_columns_list, columns)
elif isinstance(data, (np.ndarray, DataFrame)):
arrays, columns = to_arrays(data, columns)
if columns is not None:
columns = ensure_index(columns)
arr_columns = columns
else:
arrays, arr_columns = to_arrays(data, columns, coerce_float=coerce_float)
arr_columns = ensure_index(arr_columns)
if columns is not None:
columns = ensure_index(columns)
else:
columns = arr_columns
if exclude is None:
exclude = set()
else:
exclude = set(exclude)
result_index = None
if index is not None:
if isinstance(index, str) or not hasattr(index, "__iter__"):
i = columns.get_loc(index)
exclude.add(index)
if len(arrays) > 0:
result_index = Index(arrays[i], name=index)
else:
result_index = Index([], name=index)
else:
try:
index_data = [arrays[arr_columns.get_loc(field)] for field in index]
except (KeyError, TypeError):
# raised by get_loc, see GH#29258
result_index = index
else:
result_index = ensure_index_from_sequences(index_data, names=index)
exclude.update(index)
if any(exclude):
arr_exclude = [x for x in exclude if x in arr_columns]
to_remove = [arr_columns.get_loc(col) for col in arr_exclude]
arrays = [v for i, v in enumerate(arrays) if i not in to_remove]
arr_columns = arr_columns.drop(arr_exclude)
columns = columns.drop(exclude)
mgr = arrays_to_mgr(arrays, arr_columns, result_index, columns)
return cls(mgr)
def to_records(
self, index=True, column_dtypes=None, index_dtypes=None
) -> np.recarray:
"""
Convert DataFrame to a NumPy record array.
Index will be included as the first field of the record array if
requested.
Parameters
----------
index : bool, default True
Include index in resulting record array, stored in 'index'
field or using the index label, if set.
column_dtypes : str, type, dict, default None
.. versionadded:: 0.24.0
If a string or type, the data type to store all columns. If
a dictionary, a mapping of column names and indices (zero-indexed)
to specific data types.
index_dtypes : str, type, dict, default None
.. versionadded:: 0.24.0
If a string or type, the data type to store all index levels. If
a dictionary, a mapping of index level names and indices
(zero-indexed) to specific data types.
This mapping is applied only if `index=True`.
Returns
-------
numpy.recarray
NumPy ndarray with the DataFrame labels as fields and each row
of the DataFrame as entries.
See Also
--------
DataFrame.from_records: Convert structured or record ndarray
to DataFrame.
numpy.recarray: An ndarray that allows field access using
attributes, analogous to typed columns in a
spreadsheet.
Examples
--------
>>> df = pd.DataFrame({'A': [1, 2], 'B': [0.5, 0.75]},
... index=['a', 'b'])
>>> df
A B
a 1 0.50
b 2 0.75
>>> df.to_records()
rec.array([('a', 1, 0.5 ), ('b', 2, 0.75)],
dtype=[('index', 'O'), ('A', '<i8'), ('B', '<f8')])
If the DataFrame index has no label then the recarray field name
is set to 'index'. If the index has a label then this is used as the
field name:
>>> df.index = df.index.rename("I")
>>> df.to_records()
rec.array([('a', 1, 0.5 ), ('b', 2, 0.75)],
dtype=[('I', 'O'), ('A', '<i8'), ('B', '<f8')])
The index can be excluded from the record array:
>>> df.to_records(index=False)
rec.array([(1, 0.5 ), (2, 0.75)],
dtype=[('A', '<i8'), ('B', '<f8')])
Data types can be specified for the columns:
>>> df.to_records(column_dtypes={"A": "int32"})
rec.array([('a', 1, 0.5 ), ('b', 2, 0.75)],
dtype=[('I', 'O'), ('A', '<i4'), ('B', '<f8')])
As well as for the index:
>>> df.to_records(index_dtypes="<S2")
rec.array([(b'a', 1, 0.5 ), (b'b', 2, 0.75)],
dtype=[('I', 'S2'), ('A', '<i8'), ('B', '<f8')])
>>> index_dtypes = f"<S{df.index.str.len().max()}"
>>> df.to_records(index_dtypes=index_dtypes)
rec.array([(b'a', 1, 0.5 ), (b'b', 2, 0.75)],
dtype=[('I', 'S1'), ('A', '<i8'), ('B', '<f8')])
"""
if index:
if isinstance(self.index, MultiIndex):
# array of tuples to numpy cols. copy copy copy
ix_vals = list(map(np.array, zip(*self.index._values)))
else:
ix_vals = [self.index.values]
arrays = ix_vals + [
np.asarray(self.iloc[:, i]) for i in range(len(self.columns))
]
count = 0
index_names = list(self.index.names)
if isinstance(self.index, MultiIndex):
for i, n in enumerate(index_names):
if n is None:
index_names[i] = f"level_{count}"
count += 1
elif index_names[0] is None:
index_names = ["index"]
names = [str(name) for name in itertools.chain(index_names, self.columns)]
else:
arrays = [np.asarray(self.iloc[:, i]) for i in range(len(self.columns))]
names = [str(c) for c in self.columns]
index_names = []
index_len = len(index_names)
formats = []
for i, v in enumerate(arrays):
index = i
# When the names and arrays are collected, we
# first collect those in the DataFrame's index,
# followed by those in its columns.
#
# Thus, the total length of the array is:
# len(index_names) + len(DataFrame.columns).
#
# This check allows us to see whether we are
# handling a name / array in the index or column.
if index < index_len:
dtype_mapping = index_dtypes
name = index_names[index]
else:
index -= index_len
dtype_mapping = column_dtypes
name = self.columns[index]
# We have a dictionary, so we get the data type
# associated with the index or column (which can
# be denoted by its name in the DataFrame or its
# position in DataFrame's array of indices or
# columns, whichever is applicable.
if is_dict_like(dtype_mapping):
if name in dtype_mapping:
dtype_mapping = dtype_mapping[name]
elif index in dtype_mapping:
dtype_mapping = dtype_mapping[index]
else:
dtype_mapping = None
# If no mapping can be found, use the array's
# dtype attribute for formatting.
#
# A valid dtype must either be a type or
# string naming a type.
if dtype_mapping is None:
formats.append(v.dtype)
elif isinstance(dtype_mapping, (type, np.dtype, str)):
formats.append(dtype_mapping)
else:
element = "row" if i < index_len else "column"
msg = f"Invalid dtype {dtype_mapping} specified for {element} {name}"
raise ValueError(msg)
return np.rec.fromarrays(arrays, dtype={"names": names, "formats": formats})
@classmethod
def _from_arrays(
cls,
arrays,
columns,
index,
dtype: Optional[Dtype] = None,
verify_integrity: bool = True,
) -> DataFrame:
"""
Create DataFrame from a list of arrays corresponding to the columns.
Parameters
----------
arrays : list-like of arrays
Each array in the list corresponds to one column, in order.
columns : list-like, Index
The column names for the resulting DataFrame.
index : list-like, Index
The rows labels for the resulting DataFrame.
dtype : dtype, optional
Optional dtype to enforce for all arrays.
verify_integrity : bool, default True
Validate and homogenize all input. If set to False, it is assumed
that all elements of `arrays` are actual arrays how they will be
stored in a block (numpy ndarray or ExtensionArray), have the same
length as and are aligned with the index, and that `columns` and
`index` are ensured to be an Index object.
Returns
-------
DataFrame
"""
if dtype is not None:
dtype = pandas_dtype(dtype)
mgr = arrays_to_mgr(
arrays,
columns,
index,
columns,
dtype=dtype,
verify_integrity=verify_integrity,
)
return cls(mgr)
@doc(storage_options=generic._shared_docs["storage_options"])
@deprecate_kwarg(old_arg_name="fname", new_arg_name="path")
def to_stata(
self,
path: FilePathOrBuffer,
convert_dates: Optional[Dict[Label, str]] = None,
write_index: bool = True,
byteorder: Optional[str] = None,
time_stamp: Optional[datetime.datetime] = None,
data_label: Optional[str] = None,
variable_labels: Optional[Dict[Label, str]] = None,
version: Optional[int] = 114,
convert_strl: Optional[Sequence[Label]] = None,
compression: CompressionOptions = "infer",
storage_options: StorageOptions = None,
) -> None:
"""
Export DataFrame object to Stata dta format.
Writes the DataFrame to a Stata dataset file.
"dta" files contain a Stata dataset.
Parameters
----------
path : str, buffer or path object
String, path object (pathlib.Path or py._path.local.LocalPath) or
object implementing a binary write() function. If using a buffer
then the buffer will not be automatically closed after the file
data has been written.
.. versionchanged:: 1.0.0
Previously this was "fname"
convert_dates : dict
Dictionary mapping columns containing datetime types to stata
internal format to use when writing the dates. Options are 'tc',
'td', 'tm', 'tw', 'th', 'tq', 'ty'. Column can be either an integer
or a name. Datetime columns that do not have a conversion type
specified will be converted to 'tc'. Raises NotImplementedError if
a datetime column has timezone information.
write_index : bool
Write the index to Stata dataset.
byteorder : str
Can be ">", "<", "little", or "big". default is `sys.byteorder`.
time_stamp : datetime
A datetime to use as file creation date. Default is the current
time.
data_label : str, optional
A label for the data set. Must be 80 characters or smaller.
variable_labels : dict
Dictionary containing columns as keys and variable labels as
values. Each label must be 80 characters or smaller.
version : {{114, 117, 118, 119, None}}, default 114
Version to use in the output dta file. Set to None to let pandas
decide between 118 or 119 formats depending on the number of
columns in the frame. Version 114 can be read by Stata 10 and
later. Version 117 can be read by Stata 13 or later. Version 118
is supported in Stata 14 and later. Version 119 is supported in
Stata 15 and later. Version 114 limits string variables to 244
characters or fewer while versions 117 and later allow strings
with lengths up to 2,000,000 characters. Versions 118 and 119
support Unicode characters, and version 119 supports more than
32,767 variables.
Version 119 should usually only be used when the number of
variables exceeds the capacity of dta format 118. Exporting
smaller datasets in format 119 may have unintended consequences,
and, as of November 2020, Stata SE cannot read version 119 files.
.. versionchanged:: 1.0.0
Added support for formats 118 and 119.
convert_strl : list, optional
List of column names to convert to string columns to Stata StrL
format. Only available if version is 117. Storing strings in the
StrL format can produce smaller dta files if strings have more than
8 characters and values are repeated.
compression : str or dict, default 'infer'
For on-the-fly compression of the output dta. If string, specifies
compression mode. If dict, value at key 'method' specifies
compression mode. Compression mode must be one of {{'infer', 'gzip',
'bz2', 'zip', 'xz', None}}. If compression mode is 'infer' and
`fname` is path-like, then detect compression from the following
extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no
compression). If dict and compression mode is one of {{'zip',
'gzip', 'bz2'}}, or inferred as one of the above, other entries
passed as additional compression options.
.. versionadded:: 1.1.0
{storage_options}
.. versionadded:: 1.2.0
Raises
------
NotImplementedError
* If datetimes contain timezone information
* Column dtype is not representable in Stata
ValueError
* Columns listed in convert_dates are neither datetime64[ns]
or datetime.datetime
* Column listed in convert_dates is not in DataFrame
* Categorical label contains more than 32,000 characters
See Also
--------
read_stata : Import Stata data files.
io.stata.StataWriter : Low-level writer for Stata data files.
io.stata.StataWriter117 : Low-level writer for version 117 files.
Examples
--------
>>> df = pd.DataFrame({{'animal': ['falcon', 'parrot', 'falcon',
... 'parrot'],
... 'speed': [350, 18, 361, 15]}})
>>> df.to_stata('animals.dta') # doctest: +SKIP
"""
if version not in (114, 117, 118, 119, None):
raise ValueError("Only formats 114, 117, 118 and 119 are supported.")
if version == 114:
if convert_strl is not None:
raise ValueError("strl is not supported in format 114")
from pandas.io.stata import StataWriter as statawriter
elif version == 117:
# mypy: Name 'statawriter' already defined (possibly by an import)
from pandas.io.stata import ( # type: ignore[no-redef]
StataWriter117 as statawriter,
)
else: # versions 118 and 119
# mypy: Name 'statawriter' already defined (possibly by an import)
from pandas.io.stata import ( # type: ignore[no-redef]
StataWriterUTF8 as statawriter,
)
kwargs: Dict[str, Any] = {}
if version is None or version >= 117:
# strl conversion is only supported >= 117
kwargs["convert_strl"] = convert_strl
if version is None or version >= 118:
# Specifying the version is only supported for UTF8 (118 or 119)
kwargs["version"] = version
# mypy: Too many arguments for "StataWriter"
writer = statawriter( # type: ignore[call-arg]
path,
self,
convert_dates=convert_dates,
byteorder=byteorder,
time_stamp=time_stamp,
data_label=data_label,
write_index=write_index,
variable_labels=variable_labels,
compression=compression,
storage_options=storage_options,
**kwargs,
)
writer.write_file()
@deprecate_kwarg(old_arg_name="fname", new_arg_name="path")
def to_feather(self, path: FilePathOrBuffer[AnyStr], **kwargs) -> None:
"""
Write a DataFrame to the binary Feather format.
Parameters
----------
path : str or file-like object
If a string, it will be used as Root Directory path.
**kwargs :
Additional keywords passed to :func:`pyarrow.feather.write_feather`.
Starting with pyarrow 0.17, this includes the `compression`,
`compression_level`, `chunksize` and `version` keywords.
.. versionadded:: 1.1.0
"""
from pandas.io.feather_format import to_feather
to_feather(self, path, **kwargs)
@doc(
Series.to_markdown,
klass=_shared_doc_kwargs["klass"],
storage_options=_shared_docs["storage_options"],
examples="""Examples
--------
>>> df = pd.DataFrame(
... data={"animal_1": ["elk", "pig"], "animal_2": ["dog", "quetzal"]}
... )
>>> print(df.to_markdown())
| | animal_1 | animal_2 |
|---:|:-----------|:-----------|
| 0 | elk | dog |
| 1 | pig | quetzal |
Output markdown with a tabulate option.
>>> print(df.to_markdown(tablefmt="grid"))
+----+------------+------------+
| | animal_1 | animal_2 |
+====+============+============+
| 0 | elk | dog |
+----+------------+------------+
| 1 | pig | quetzal |
+----+------------+------------+
""",
)
def to_markdown(
self,
buf: Optional[Union[IO[str], str]] = None,
mode: str = "wt",
index: bool = True,
storage_options: StorageOptions = None,
**kwargs,
) -> Optional[str]:
if "showindex" in kwargs:
warnings.warn(
"'showindex' is deprecated. Only 'index' will be used "
"in a future version. Use 'index' to silence this warning.",
FutureWarning,
stacklevel=2,
)
kwargs.setdefault("headers", "keys")
kwargs.setdefault("tablefmt", "pipe")
kwargs.setdefault("showindex", index)
tabulate = import_optional_dependency("tabulate")
result = tabulate.tabulate(self, **kwargs)
if buf is None:
return result
with get_handle(buf, mode, storage_options=storage_options) as handles:
assert not isinstance(handles.handle, (str, mmap.mmap))
handles.handle.writelines(result)
return None
@doc(storage_options=generic._shared_docs["storage_options"])
@deprecate_kwarg(old_arg_name="fname", new_arg_name="path")
def to_parquet(
self,
path: Optional[FilePathOrBuffer] = None,
engine: str = "auto",
compression: Optional[str] = "snappy",
index: Optional[bool] = None,
partition_cols: Optional[List[str]] = None,
storage_options: StorageOptions = None,
**kwargs,
) -> Optional[bytes]:
"""
Write a DataFrame to the binary parquet format.
This function writes the dataframe as a `parquet file
<https://parquet.apache.org/>`_. You can choose different parquet
backends, and have the option of compression. See
:ref:`the user guide <io.parquet>` for more details.
Parameters
----------
path : str or file-like object, default None
If a string, it will be used as Root Directory path
when writing a partitioned dataset. By file-like object,
we refer to objects with a write() method, such as a file handle
(e.g. via builtin open function) or io.BytesIO. The engine
fastparquet does not accept file-like objects. If path is None,
a bytes object is returned.
.. versionchanged:: 1.2.0
Previously this was "fname"
engine : {{'auto', 'pyarrow', 'fastparquet'}}, default 'auto'
Parquet library to use. If 'auto', then the option
``io.parquet.engine`` is used. The default ``io.parquet.engine``
behavior is to try 'pyarrow', falling back to 'fastparquet' if
'pyarrow' is unavailable.
compression : {{'snappy', 'gzip', 'brotli', None}}, default 'snappy'
Name of the compression to use. Use ``None`` for no compression.
index : bool, default None
If ``True``, include the dataframe's index(es) in the file output.
If ``False``, they will not be written to the file.
If ``None``, similar to ``True`` the dataframe's index(es)
will be saved. However, instead of being saved as values,
the RangeIndex will be stored as a range in the metadata so it
doesn't require much space and is faster. Other indexes will
be included as columns in the file output.
.. versionadded:: 0.24.0
partition_cols : list, optional, default None
Column names by which to partition the dataset.
Columns are partitioned in the order they are given.
Must be None if path is not a string.
.. versionadded:: 0.24.0
{storage_options}
.. versionadded:: 1.2.0
**kwargs
Additional arguments passed to the parquet library. See
:ref:`pandas io <io.parquet>` for more details.
Returns
-------
bytes if no path argument is provided else None
See Also
--------
read_parquet : Read a parquet file.
DataFrame.to_csv : Write a csv file.
DataFrame.to_sql : Write to a sql table.
DataFrame.to_hdf : Write to hdf.
Notes
-----
This function requires either the `fastparquet
<https://pypi.org/project/fastparquet>`_ or `pyarrow
<https://arrow.apache.org/docs/python/>`_ library.
Examples
--------
>>> df = pd.DataFrame(data={{'col1': [1, 2], 'col2': [3, 4]}})
>>> df.to_parquet('df.parquet.gzip',
... compression='gzip') # doctest: +SKIP
>>> pd.read_parquet('df.parquet.gzip') # doctest: +SKIP
col1 col2
0 1 3
1 2 4
If you want to get a buffer to the parquet content you can use a io.BytesIO
object, as long as you don't use partition_cols, which creates multiple files.
>>> import io
>>> f = io.BytesIO()
>>> df.to_parquet(f)
>>> f.seek(0)
0
>>> content = f.read()
"""
from pandas.io.parquet import to_parquet
return to_parquet(
self,
path,
engine,
compression=compression,
index=index,
partition_cols=partition_cols,
storage_options=storage_options,
**kwargs,
)
@Substitution(
header_type="bool",
header="Whether to print column labels, default True",
col_space_type="str or int, list or dict of int or str",
col_space="The minimum width of each column in CSS length "
"units. An int is assumed to be px units.\n\n"
" .. versionadded:: 0.25.0\n"
" Ability to use str",
)
@Substitution(shared_params=fmt.common_docstring, returns=fmt.return_docstring)
def to_html(
self,
buf=None,
columns=None,
col_space=None,
header=True,
index=True,
na_rep="NaN",
formatters=None,
float_format=None,
sparsify=None,
index_names=True,
justify=None,
max_rows=None,
max_cols=None,
show_dimensions=False,
decimal=".",
bold_rows=True,
classes=None,
escape=True,
notebook=False,
border=None,
table_id=None,
render_links=False,
encoding=None,
):
"""
Render a DataFrame as an HTML table.
%(shared_params)s
bold_rows : bool, default True
Make the row labels bold in the output.
classes : str or list or tuple, default None
CSS class(es) to apply to the resulting html table.
escape : bool, default True
Convert the characters <, >, and & to HTML-safe sequences.
notebook : {True, False}, default False
Whether the generated HTML is for IPython Notebook.
border : int
A ``border=border`` attribute is included in the opening
`<table>` tag. Default ``pd.options.display.html.border``.
encoding : str, default "utf-8"
Set character encoding.
.. versionadded:: 1.0
table_id : str, optional
A css id is included in the opening `<table>` tag if specified.
render_links : bool, default False
Convert URLs to HTML links.
.. versionadded:: 0.24.0
%(returns)s
See Also
--------
to_string : Convert DataFrame to a string.
"""
if justify is not None and justify not in fmt._VALID_JUSTIFY_PARAMETERS:
raise ValueError("Invalid value for justify parameter")
formatter = fmt.DataFrameFormatter(
self,
columns=columns,
col_space=col_space,
na_rep=na_rep,
header=header,
index=index,
formatters=formatters,
float_format=float_format,
bold_rows=bold_rows,
sparsify=sparsify,
justify=justify,
index_names=index_names,
escape=escape,
decimal=decimal,
max_rows=max_rows,
max_cols=max_cols,
show_dimensions=show_dimensions,
)
# TODO: a generic formatter wld b in DataFrameFormatter
return fmt.DataFrameRenderer(formatter).to_html(
buf=buf,
classes=classes,
notebook=notebook,
border=border,
encoding=encoding,
table_id=table_id,
render_links=render_links,
)
# ----------------------------------------------------------------------
@Substitution(
klass="DataFrame",
type_sub=" and columns",
max_cols_sub=dedent(
"""\
max_cols : int, optional
When to switch from the verbose to the truncated output. If the
DataFrame has more than `max_cols` columns, the truncated output
is used. By default, the setting in
``pandas.options.display.max_info_columns`` is used."""
),
show_counts_sub=dedent(
"""\
show_counts : bool, optional
Whether to show the non-null counts. By default, this is shown
only if the DataFrame is smaller than
``pandas.options.display.max_info_rows`` and
``pandas.options.display.max_info_columns``. A value of True always
shows the counts, and False never shows the counts.
null_counts : bool, optional
.. deprecated:: 1.2.0
Use show_counts instead."""
),
examples_sub=dedent(
"""\
>>> int_values = [1, 2, 3, 4, 5]
>>> text_values = ['alpha', 'beta', 'gamma', 'delta', 'epsilon']
>>> float_values = [0.0, 0.25, 0.5, 0.75, 1.0]
>>> df = pd.DataFrame({"int_col": int_values, "text_col": text_values,
... "float_col": float_values})
>>> df
int_col text_col float_col
0 1 alpha 0.00
1 2 beta 0.25
2 3 gamma 0.50
3 4 delta 0.75
4 5 epsilon 1.00
Prints information of all columns:
>>> df.info(verbose=True)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 int_col 5 non-null int64
1 text_col 5 non-null object
2 float_col 5 non-null float64
dtypes: float64(1), int64(1), object(1)
memory usage: 248.0+ bytes
Prints a summary of columns count and its dtypes but not per column
information:
>>> df.info(verbose=False)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Columns: 3 entries, int_col to float_col
dtypes: float64(1), int64(1), object(1)
memory usage: 248.0+ bytes
Pipe output of DataFrame.info to buffer instead of sys.stdout, get
buffer content and writes to a text file:
>>> import io
>>> buffer = io.StringIO()
>>> df.info(buf=buffer)
>>> s = buffer.getvalue()
>>> with open("df_info.txt", "w",
... encoding="utf-8") as f: # doctest: +SKIP
... f.write(s)
260
The `memory_usage` parameter allows deep introspection mode, specially
useful for big DataFrames and fine-tune memory optimization:
>>> random_strings_array = np.random.choice(['a', 'b', 'c'], 10 ** 6)
>>> df = pd.DataFrame({
... 'column_1': np.random.choice(['a', 'b', 'c'], 10 ** 6),
... 'column_2': np.random.choice(['a', 'b', 'c'], 10 ** 6),
... 'column_3': np.random.choice(['a', 'b', 'c'], 10 ** 6)
... })
>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000000 entries, 0 to 999999
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 column_1 1000000 non-null object
1 column_2 1000000 non-null object
2 column_3 1000000 non-null object
dtypes: object(3)
memory usage: 22.9+ MB
>>> df.info(memory_usage='deep')
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000000 entries, 0 to 999999
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 column_1 1000000 non-null object
1 column_2 1000000 non-null object
2 column_3 1000000 non-null object
dtypes: object(3)
memory usage: 165.9 MB"""
),
see_also_sub=dedent(
"""\
DataFrame.describe: Generate descriptive statistics of DataFrame
columns.
DataFrame.memory_usage: Memory usage of DataFrame columns."""
),
version_added_sub="",
)
@doc(BaseInfo.render)
def info(
self,
verbose: Optional[bool] = None,
buf: Optional[IO[str]] = None,
max_cols: Optional[int] = None,
memory_usage: Optional[Union[bool, str]] = None,
show_counts: Optional[bool] = None,
null_counts: Optional[bool] = None,
) -> None:
if null_counts is not None:
if show_counts is not None:
raise ValueError("null_counts used with show_counts. Use show_counts.")
warnings.warn(
"null_counts is deprecated. Use show_counts instead",
FutureWarning,
stacklevel=2,
)
show_counts = null_counts
info = DataFrameInfo(
data=self,
memory_usage=memory_usage,
)
info.render(
buf=buf,
max_cols=max_cols,
verbose=verbose,
show_counts=show_counts,
)
def memory_usage(self, index=True, deep=False) -> Series:
"""
Return the memory usage of each column in bytes.
The memory usage can optionally include the contribution of
the index and elements of `object` dtype.
This value is displayed in `DataFrame.info` by default. This can be
suppressed by setting ``pandas.options.display.memory_usage`` to False.
Parameters
----------
index : bool, default True
Specifies whether to include the memory usage of the DataFrame's
index in returned Series. If ``index=True``, the memory usage of
the index is the first item in the output.
deep : bool, default False
If True, introspect the data deeply by interrogating
`object` dtypes for system-level memory consumption, and include
it in the returned values.
Returns
-------
Series
A Series whose index is the original column names and whose values
is the memory usage of each column in bytes.
See Also
--------
numpy.ndarray.nbytes : Total bytes consumed by the elements of an
ndarray.
Series.memory_usage : Bytes consumed by a Series.
Categorical : Memory-efficient array for string values with
many repeated values.
DataFrame.info : Concise summary of a DataFrame.
Examples
--------
>>> dtypes = ['int64', 'float64', 'complex128', 'object', 'bool']
>>> data = dict([(t, np.ones(shape=5000, dtype=int).astype(t))
... for t in dtypes])
>>> df = pd.DataFrame(data)
>>> df.head()
int64 float64 complex128 object bool
0 1 1.0 1.0+0.0j 1 True
1 1 1.0 1.0+0.0j 1 True
2 1 1.0 1.0+0.0j 1 True
3 1 1.0 1.0+0.0j 1 True
4 1 1.0 1.0+0.0j 1 True
>>> df.memory_usage()
Index 128
int64 40000
float64 40000
complex128 80000
object 40000
bool 5000
dtype: int64
>>> df.memory_usage(index=False)
int64 40000
float64 40000
complex128 80000
object 40000
bool 5000
dtype: int64
The memory footprint of `object` dtype columns is ignored by default:
>>> df.memory_usage(deep=True)
Index 128
int64 40000
float64 40000
complex128 80000
object 180000
bool 5000
dtype: int64
Use a Categorical for efficient storage of an object-dtype column with
many repeated values.
>>> df['object'].astype('category').memory_usage(deep=True)
5244
"""
result = self._constructor_sliced(
[c.memory_usage(index=False, deep=deep) for col, c in self.items()],
index=self.columns,
)
if index:
result = self._constructor_sliced(
self.index.memory_usage(deep=deep), index=["Index"]
).append(result)
return result
def transpose(self, *args, copy: bool = False) -> DataFrame:
"""
Transpose index and columns.
Reflect the DataFrame over its main diagonal by writing rows as columns
and vice-versa. The property :attr:`.T` is an accessor to the method
:meth:`transpose`.
Parameters
----------
*args : tuple, optional
Accepted for compatibility with NumPy.
copy : bool, default False
Whether to copy the data after transposing, even for DataFrames
with a single dtype.
Note that a copy is always required for mixed dtype DataFrames,
or for DataFrames with any extension types.
Returns
-------
DataFrame
The transposed DataFrame.
See Also
--------
numpy.transpose : Permute the dimensions of a given array.
Notes
-----
Transposing a DataFrame with mixed dtypes will result in a homogeneous
DataFrame with the `object` dtype. In such a case, a copy of the data
is always made.
Examples
--------
**Square DataFrame with homogeneous dtype**
>>> d1 = {'col1': [1, 2], 'col2': [3, 4]}
>>> df1 = pd.DataFrame(data=d1)
>>> df1
col1 col2
0 1 3
1 2 4
>>> df1_transposed = df1.T # or df1.transpose()
>>> df1_transposed
0 1
col1 1 2
col2 3 4
When the dtype is homogeneous in the original DataFrame, we get a
transposed DataFrame with the same dtype:
>>> df1.dtypes
col1 int64
col2 int64
dtype: object
>>> df1_transposed.dtypes
0 int64
1 int64
dtype: object
**Non-square DataFrame with mixed dtypes**
>>> d2 = {'name': ['Alice', 'Bob'],
... 'score': [9.5, 8],
... 'employed': [False, True],
... 'kids': [0, 0]}
>>> df2 = pd.DataFrame(data=d2)
>>> df2
name score employed kids
0 Alice 9.5 False 0
1 Bob 8.0 True 0
>>> df2_transposed = df2.T # or df2.transpose()
>>> df2_transposed
0 1
name Alice Bob
score 9.5 8.0
employed False True
kids 0 0
When the DataFrame has mixed dtypes, we get a transposed DataFrame with
the `object` dtype:
>>> df2.dtypes
name object
score float64
employed bool
kids int64
dtype: object
>>> df2_transposed.dtypes
0 object
1 object
dtype: object
"""
nv.validate_transpose(args, {})
# construct the args
dtypes = list(self.dtypes)
if self._is_homogeneous_type and dtypes and is_extension_array_dtype(dtypes[0]):
# We have EAs with the same dtype. We can preserve that dtype in transpose.
dtype = dtypes[0]
arr_type = dtype.construct_array_type()
values = self.values
new_values = [arr_type._from_sequence(row, dtype=dtype) for row in values]
result = self._constructor(
dict(zip(self.index, new_values)), index=self.columns
)
else:
new_values = self.values.T
if copy:
new_values = new_values.copy()
result = self._constructor(
new_values, index=self.columns, columns=self.index
)
return result.__finalize__(self, method="transpose")
@property
def T(self) -> DataFrame:
return self.transpose()
# ----------------------------------------------------------------------
# Indexing Methods
def _ixs(self, i: int, axis: int = 0):
"""
Parameters
----------
i : int
axis : int
Notes
-----
If slice passed, the resulting data will be a view.
"""
# irow
if axis == 0:
new_values = self._mgr.fast_xs(i)
# if we are a copy, mark as such
copy = isinstance(new_values, np.ndarray) and new_values.base is None
result = self._constructor_sliced(
new_values,
index=self.columns,
name=self.index[i],
dtype=new_values.dtype,
)
result._set_is_copy(self, copy=copy)
return result
# icol
else:
label = self.columns[i]
values = self._mgr.iget(i)
result = self._box_col_values(values, i)
# this is a cached value, mark it so
result._set_as_cached(label, self)
return result
def _get_column_array(self, i: int) -> ArrayLike:
"""
Get the values of the i'th column (ndarray or ExtensionArray, as stored
in the Block)
"""
return self._mgr.iget_values(i)
def _iter_column_arrays(self) -> Iterator[ArrayLike]:
"""
Iterate over the arrays of all columns in order.
This returns the values as stored in the Block (ndarray or ExtensionArray).
"""
for i in range(len(self.columns)):
yield self._get_column_array(i)
def __getitem__(self, key):
key = lib.item_from_zerodim(key)
key = com.apply_if_callable(key, self)
if is_hashable(key):
# shortcut if the key is in columns
if self.columns.is_unique and key in self.columns:
if isinstance(self.columns, MultiIndex):
return self._getitem_multilevel(key)
return self._get_item_cache(key)
# Do we have a slicer (on rows)?
indexer = convert_to_index_sliceable(self, key)
if indexer is not None:
if isinstance(indexer, np.ndarray):
indexer = lib.maybe_indices_to_slice(
indexer.astype(np.intp, copy=False), len(self)
)
# either we have a slice or we have a string that can be converted
# to a slice for partial-string date indexing
return self._slice(indexer, axis=0)
# Do we have a (boolean) DataFrame?
if isinstance(key, DataFrame):
return self.where(key)
# Do we have a (boolean) 1d indexer?
if com.is_bool_indexer(key):
return self._getitem_bool_array(key)
# We are left with two options: a single key, and a collection of keys,
# We interpret tuples as collections only for non-MultiIndex
is_single_key = isinstance(key, tuple) or not is_list_like(key)
if is_single_key:
if self.columns.nlevels > 1:
return self._getitem_multilevel(key)
indexer = self.columns.get_loc(key)
if is_integer(indexer):
indexer = [indexer]
else:
if is_iterator(key):
key = list(key)
indexer = self.loc._get_listlike_indexer(key, axis=1, raise_missing=True)[1]
# take() does not accept boolean indexers
if getattr(indexer, "dtype", None) == bool:
indexer = np.where(indexer)[0]
data = self._take_with_is_copy(indexer, axis=1)
if is_single_key:
# What does looking for a single key in a non-unique index return?
# The behavior is inconsistent. It returns a Series, except when
# - the key itself is repeated (test on data.shape, #9519), or
# - we have a MultiIndex on columns (test on self.columns, #21309)
if data.shape[1] == 1 and not isinstance(self.columns, MultiIndex):
# GH#26490 using data[key] can cause RecursionError
data = data._get_item_cache(key)
return data
def _getitem_bool_array(self, key):
# also raises Exception if object array with NA values
# warning here just in case -- previously __setitem__ was
# reindexing but __getitem__ was not; it seems more reasonable to
# go with the __setitem__ behavior since that is more consistent
# with all other indexing behavior
if isinstance(key, Series) and not key.index.equals(self.index):
warnings.warn(
"Boolean Series key will be reindexed to match DataFrame index.",
UserWarning,
stacklevel=3,
)
elif len(key) != len(self.index):
raise ValueError(
f"Item wrong length {len(key)} instead of {len(self.index)}."
)
# check_bool_indexer will throw exception if Series key cannot
# be reindexed to match DataFrame rows
key = check_bool_indexer(self.index, key)
indexer = key.nonzero()[0]
return self._take_with_is_copy(indexer, axis=0)
def _getitem_multilevel(self, key):
# self.columns is a MultiIndex
loc = self.columns.get_loc(key)
if isinstance(loc, (slice, np.ndarray)):
new_columns = self.columns[loc]
result_columns = maybe_droplevels(new_columns, key)
if self._is_mixed_type:
result = self.reindex(columns=new_columns)
result.columns = result_columns
else:
new_values = self.values[:, loc]
result = self._constructor(
new_values, index=self.index, columns=result_columns
)
result = result.__finalize__(self)
# If there is only one column being returned, and its name is
# either an empty string, or a tuple with an empty string as its
# first element, then treat the empty string as a placeholder
# and return the column as if the user had provided that empty
# string in the key. If the result is a Series, exclude the
# implied empty string from its name.
if len(result.columns) == 1:
top = result.columns[0]
if isinstance(top, tuple):
top = top[0]
if top == "":
result = result[""]
if isinstance(result, Series):
result = self._constructor_sliced(
result, index=self.index, name=key
)
result._set_is_copy(self)
return result
else:
# loc is neither a slice nor ndarray, so must be an int
return self._ixs(loc, axis=1)
def _get_value(self, index, col, takeable: bool = False):
"""
Quickly retrieve single value at passed column and index.
Parameters
----------
index : row label
col : column label
takeable : interpret the index/col as indexers, default False
Returns
-------
scalar
"""
if takeable:
series = self._ixs(col, axis=1)
return series._values[index]
series = self._get_item_cache(col)
engine = self.index._engine
try:
loc = engine.get_loc(index)
return series._values[loc]
except KeyError:
# GH 20629
if self.index.nlevels > 1:
# partial indexing forbidden
raise
# we cannot handle direct indexing
# use positional
col = self.columns.get_loc(col)
index = self.index.get_loc(index)
return self._get_value(index, col, takeable=True)
def __setitem__(self, key, value):
key = com.apply_if_callable(key, self)
# see if we can slice the rows
indexer = convert_to_index_sliceable(self, key)
if indexer is not None:
# either we have a slice or we have a string that can be converted
# to a slice for partial-string date indexing
return self._setitem_slice(indexer, value)
if isinstance(key, DataFrame) or getattr(key, "ndim", None) == 2:
self._setitem_frame(key, value)
elif isinstance(key, (Series, np.ndarray, list, Index)):
self._setitem_array(key, value)
else:
# set column
self._set_item(key, value)
def _setitem_slice(self, key: slice, value):
# NB: we can't just use self.loc[key] = value because that
# operates on labels and we need to operate positional for
# backwards-compat, xref GH#31469
self._check_setitem_copy()
self.iloc._setitem_with_indexer(key, value)
def _setitem_array(self, key, value):
# also raises Exception if object array with NA values
if com.is_bool_indexer(key):
if len(key) != len(self.index):
raise ValueError(
f"Item wrong length {len(key)} instead of {len(self.index)}!"
)
key = check_bool_indexer(self.index, key)
indexer = key.nonzero()[0]
self._check_setitem_copy()
self.iloc._setitem_with_indexer(indexer, value)
else:
if isinstance(value, DataFrame):
if len(value.columns) != len(key):
raise ValueError("Columns must be same length as key")
for k1, k2 in zip(key, value.columns):
self[k1] = value[k2]
else:
self.loc._ensure_listlike_indexer(key, axis=1, value=value)
indexer = self.loc._get_listlike_indexer(
key, axis=1, raise_missing=False
)[1]
self._check_setitem_copy()
self.iloc._setitem_with_indexer((slice(None), indexer), value)
def _setitem_frame(self, key, value):
# support boolean setting with DataFrame input, e.g.
# df[df > df2] = 0
if isinstance(key, np.ndarray):
if key.shape != self.shape:
raise ValueError("Array conditional must be same shape as self")
key = self._constructor(key, **self._construct_axes_dict())
if key.size and not is_bool_dtype(key.values):
raise TypeError(
"Must pass DataFrame or 2-d ndarray with boolean values only"
)
self._check_inplace_setting(value)
self._check_setitem_copy()
self._where(-key, value, inplace=True)
def _iset_item(self, loc: int, value):
self._ensure_valid_index(value)
# technically _sanitize_column expects a label, not a position,
# but the behavior is the same as long as we pass broadcast=False
value = self._sanitize_column(loc, value, broadcast=False)
NDFrame._iset_item(self, loc, value)
# check if we are modifying a copy
# try to set first as we want an invalid
# value exception to occur first
if len(self):
self._check_setitem_copy()
def _set_item(self, key, value):
"""
Add series to DataFrame in specified column.
If series is a numpy-array (not a Series/TimeSeries), it must be the
same length as the DataFrames index or an error will be thrown.
Series/TimeSeries will be conformed to the DataFrames index to
ensure homogeneity.
"""
self._ensure_valid_index(value)
value = self._sanitize_column(key, value)
NDFrame._set_item(self, key, value)
# check if we are modifying a copy
# try to set first as we want an invalid
# value exception to occur first
if len(self):
self._check_setitem_copy()
def _set_value(self, index, col, value, takeable: bool = False):
"""
Put single value at passed column and index.
Parameters
----------
index : row label
col : column label
value : scalar
takeable : interpret the index/col as indexers, default False
"""
try:
if takeable is True:
series = self._ixs(col, axis=1)
series._set_value(index, value, takeable=True)
return
series = self._get_item_cache(col)
engine = self.index._engine
loc = engine.get_loc(index)
validate_numeric_casting(series.dtype, value)
series._values[loc] = value
# Note: trying to use series._set_value breaks tests in
# tests.frame.indexing.test_indexing and tests.indexing.test_partial
except (KeyError, TypeError):
# set using a non-recursive method & reset the cache
if takeable:
self.iloc[index, col] = value
else:
self.loc[index, col] = value
self._item_cache.pop(col, None)
def _ensure_valid_index(self, value):
"""
Ensure that if we don't have an index, that we can create one from the
passed value.
"""
# GH5632, make sure that we are a Series convertible
if not len(self.index) and is_list_like(value) and len(value):
try:
value = Series(value)
except (ValueError, NotImplementedError, TypeError) as err:
raise ValueError(
"Cannot set a frame with no defined index "
"and a value that cannot be converted to a Series"
) from err
# GH31368 preserve name of index
index_copy = value.index.copy()
if self.index.name is not None:
index_copy.name = self.index.name
self._mgr = self._mgr.reindex_axis(index_copy, axis=1, fill_value=np.nan)
def _box_col_values(self, values, loc: int) -> Series:
"""
Provide boxed values for a column.
"""
# Lookup in columns so that if e.g. a str datetime was passed
# we attach the Timestamp object as the name.
name = self.columns[loc]
klass = self._constructor_sliced
return klass(values, index=self.index, name=name, fastpath=True)
# ----------------------------------------------------------------------
# Unsorted
def query(self, expr, inplace=False, **kwargs):
"""
Query the columns of a DataFrame with a boolean expression.
Parameters
----------
expr : str
The query string to evaluate.
You can refer to variables
in the environment by prefixing them with an '@' character like
``@a + b``.
You can refer to column names that are not valid Python variable names
by surrounding them in backticks. Thus, column names containing spaces
or punctuations (besides underscores) or starting with digits must be
surrounded by backticks. (For example, a column named "Area (cm^2) would
be referenced as `Area (cm^2)`). Column names which are Python keywords
(like "list", "for", "import", etc) cannot be used.
For example, if one of your columns is called ``a a`` and you want
to sum it with ``b``, your query should be ```a a` + b``.
.. versionadded:: 0.25.0
Backtick quoting introduced.
.. versionadded:: 1.0.0
Expanding functionality of backtick quoting for more than only spaces.
inplace : bool
Whether the query should modify the data in place or return
a modified copy.
**kwargs
See the documentation for :func:`eval` for complete details
on the keyword arguments accepted by :meth:`DataFrame.query`.
Returns
-------
DataFrame or None
DataFrame resulting from the provided query expression or
None if ``inplace=True``.
See Also
--------
eval : Evaluate a string describing operations on
DataFrame columns.
DataFrame.eval : Evaluate a string describing operations on
DataFrame columns.
Notes
-----
The result of the evaluation of this expression is first passed to
:attr:`DataFrame.loc` and if that fails because of a
multidimensional key (e.g., a DataFrame) then the result will be passed
to :meth:`DataFrame.__getitem__`.
This method uses the top-level :func:`eval` function to
evaluate the passed query.
The :meth:`~pandas.DataFrame.query` method uses a slightly
modified Python syntax by default. For example, the ``&`` and ``|``
(bitwise) operators have the precedence of their boolean cousins,
:keyword:`and` and :keyword:`or`. This *is* syntactically valid Python,
however the semantics are different.
You can change the semantics of the expression by passing the keyword
argument ``parser='python'``. This enforces the same semantics as
evaluation in Python space. Likewise, you can pass ``engine='python'``
to evaluate an expression using Python itself as a backend. This is not
recommended as it is inefficient compared to using ``numexpr`` as the
engine.
The :attr:`DataFrame.index` and
:attr:`DataFrame.columns` attributes of the
:class:`~pandas.DataFrame` instance are placed in the query namespace
by default, which allows you to treat both the index and columns of the
frame as a column in the frame.
The identifier ``index`` is used for the frame index; you can also
use the name of the index to identify it in a query. Please note that
Python keywords may not be used as identifiers.
For further details and examples see the ``query`` documentation in
:ref:`indexing <indexing.query>`.
*Backtick quoted variables*
Backtick quoted variables are parsed as literal Python code and
are converted internally to a Python valid identifier.
This can lead to the following problems.
During parsing a number of disallowed characters inside the backtick
quoted string are replaced by strings that are allowed as a Python identifier.
These characters include all operators in Python, the space character, the
question mark, the exclamation mark, the dollar sign, and the euro sign.
For other characters that fall outside the ASCII range (U+0001..U+007F)
and those that are not further specified in PEP 3131,
the query parser will raise an error.
This excludes whitespace different than the space character,
but also the hashtag (as it is used for comments) and the backtick
itself (backtick can also not be escaped).
In a special case, quotes that make a pair around a backtick can
confuse the parser.
For example, ```it's` > `that's``` will raise an error,
as it forms a quoted string (``'s > `that'``) with a backtick inside.
See also the Python documentation about lexical analysis
(https://docs.python.org/3/reference/lexical_analysis.html)
in combination with the source code in :mod:`pandas.core.computation.parsing`.
Examples
--------
>>> df = pd.DataFrame({'A': range(1, 6),
... 'B': range(10, 0, -2),
... 'C C': range(10, 5, -1)})
>>> df
A B C C
0 1 10 10
1 2 8 9
2 3 6 8
3 4 4 7
4 5 2 6
>>> df.query('A > B')
A B C C
4 5 2 6
The previous expression is equivalent to
>>> df[df.A > df.B]
A B C C
4 5 2 6
For columns with spaces in their name, you can use backtick quoting.
>>> df.query('B == `C C`')
A B C C
0 1 10 10
The previous expression is equivalent to
>>> df[df.B == df['C C']]
A B C C
0 1 10 10
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if not isinstance(expr, str):
msg = f"expr must be a string to be evaluated, {type(expr)} given"
raise ValueError(msg)
kwargs["level"] = kwargs.pop("level", 0) + 1
kwargs["target"] = None
res = self.eval(expr, **kwargs)
try:
result = self.loc[res]
except ValueError:
# when res is multi-dimensional loc raises, but this is sometimes a
# valid query
result = self[res]
if inplace:
self._update_inplace(result)
else:
return result
def eval(self, expr, inplace=False, **kwargs):
"""
Evaluate a string describing operations on DataFrame columns.
Operates on columns only, not specific rows or elements. This allows
`eval` to run arbitrary code, which can make you vulnerable to code
injection if you pass user input to this function.
Parameters
----------
expr : str
The expression string to evaluate.
inplace : bool, default False
If the expression contains an assignment, whether to perform the
operation inplace and mutate the existing DataFrame. Otherwise,
a new DataFrame is returned.
**kwargs
See the documentation for :func:`eval` for complete details
on the keyword arguments accepted by
:meth:`~pandas.DataFrame.query`.
Returns
-------
ndarray, scalar, pandas object, or None
The result of the evaluation or None if ``inplace=True``.
See Also
--------
DataFrame.query : Evaluates a boolean expression to query the columns
of a frame.
DataFrame.assign : Can evaluate an expression or function to create new
values for a column.
eval : Evaluate a Python expression as a string using various
backends.
Notes
-----
For more details see the API documentation for :func:`~eval`.
For detailed examples see :ref:`enhancing performance with eval
<enhancingperf.eval>`.
Examples
--------
>>> df = pd.DataFrame({'A': range(1, 6), 'B': range(10, 0, -2)})
>>> df
A B
0 1 10
1 2 8
2 3 6
3 4 4
4 5 2
>>> df.eval('A + B')
0 11
1 10
2 9
3 8
4 7
dtype: int64
Assignment is allowed though by default the original DataFrame is not
modified.
>>> df.eval('C = A + B')
A B C
0 1 10 11
1 2 8 10
2 3 6 9
3 4 4 8
4 5 2 7
>>> df
A B
0 1 10
1 2 8
2 3 6
3 4 4
4 5 2
Use ``inplace=True`` to modify the original DataFrame.
>>> df.eval('C = A + B', inplace=True)
>>> df
A B C
0 1 10 11
1 2 8 10
2 3 6 9
3 4 4 8
4 5 2 7
Multiple columns can be assigned to using multi-line expressions:
>>> df.eval(
... '''
... C = A + B
... D = A - B
... '''
... )
A B C D
0 1 10 11 -9
1 2 8 10 -6
2 3 6 9 -3
3 4 4 8 0
4 5 2 7 3
"""
from pandas.core.computation.eval import eval as _eval
inplace = validate_bool_kwarg(inplace, "inplace")
resolvers = kwargs.pop("resolvers", None)
kwargs["level"] = kwargs.pop("level", 0) + 1
if resolvers is None:
index_resolvers = self._get_index_resolvers()
column_resolvers = self._get_cleaned_column_resolvers()
resolvers = column_resolvers, index_resolvers
if "target" not in kwargs:
kwargs["target"] = self
kwargs["resolvers"] = kwargs.get("resolvers", ()) + tuple(resolvers)
return _eval(expr, inplace=inplace, **kwargs)
def select_dtypes(self, include=None, exclude=None) -> DataFrame:
"""
Return a subset of the DataFrame's columns based on the column dtypes.
Parameters
----------
include, exclude : scalar or list-like
A selection of dtypes or strings to be included/excluded. At least
one of these parameters must be supplied.
Returns
-------
DataFrame
The subset of the frame including the dtypes in ``include`` and
excluding the dtypes in ``exclude``.
Raises
------
ValueError
* If both of ``include`` and ``exclude`` are empty
* If ``include`` and ``exclude`` have overlapping elements
* If any kind of string dtype is passed in.
See Also
--------
DataFrame.dtypes: Return Series with the data type of each column.
Notes
-----
* To select all *numeric* types, use ``np.number`` or ``'number'``
* To select strings you must use the ``object`` dtype, but note that
this will return *all* object dtype columns
* See the `numpy dtype hierarchy
<https://numpy.org/doc/stable/reference/arrays.scalars.html>`__
* To select datetimes, use ``np.datetime64``, ``'datetime'`` or
``'datetime64'``
* To select timedeltas, use ``np.timedelta64``, ``'timedelta'`` or
``'timedelta64'``
* To select Pandas categorical dtypes, use ``'category'``
* To select Pandas datetimetz dtypes, use ``'datetimetz'`` (new in
0.20.0) or ``'datetime64[ns, tz]'``
Examples
--------
>>> df = pd.DataFrame({'a': [1, 2] * 3,
... 'b': [True, False] * 3,
... 'c': [1.0, 2.0] * 3})
>>> df
a b c
0 1 True 1.0
1 2 False 2.0
2 1 True 1.0
3 2 False 2.0
4 1 True 1.0
5 2 False 2.0
>>> df.select_dtypes(include='bool')
b
0 True
1 False
2 True
3 False
4 True
5 False
>>> df.select_dtypes(include=['float64'])
c
0 1.0
1 2.0
2 1.0
3 2.0
4 1.0
5 2.0
>>> df.select_dtypes(exclude=['int64'])
b c
0 True 1.0
1 False 2.0
2 True 1.0
3 False 2.0
4 True 1.0
5 False 2.0
"""
if not is_list_like(include):
include = (include,) if include is not None else ()
if not is_list_like(exclude):
exclude = (exclude,) if exclude is not None else ()
selection = (frozenset(include), frozenset(exclude))
if not any(selection):
raise ValueError("at least one of include or exclude must be nonempty")
# convert the myriad valid dtypes object to a single representation
include = frozenset(infer_dtype_from_object(x) for x in include)
exclude = frozenset(infer_dtype_from_object(x) for x in exclude)
for dtypes in (include, exclude):
invalidate_string_dtypes(dtypes)
# can't both include AND exclude!
if not include.isdisjoint(exclude):
raise ValueError(f"include and exclude overlap on {(include & exclude)}")
# We raise when both include and exclude are empty
# Hence, we can just shrink the columns we want to keep
keep_these = np.full(self.shape[1], True)
def extract_unique_dtypes_from_dtypes_set(
dtypes_set: FrozenSet[Dtype], unique_dtypes: np.ndarray
) -> List[Dtype]:
extracted_dtypes = [
unique_dtype
for unique_dtype in unique_dtypes
# error: Argument 1 to "tuple" has incompatible type
# "FrozenSet[Union[ExtensionDtype, str, Any, Type[str],
# Type[float], Type[int], Type[complex], Type[bool]]]";
# expected "Iterable[Union[type, Tuple[Any, ...]]]"
if issubclass(
unique_dtype.type, tuple(dtypes_set) # type: ignore[arg-type]
)
]
return extracted_dtypes
unique_dtypes = self.dtypes.unique()
if include:
included_dtypes = extract_unique_dtypes_from_dtypes_set(
include, unique_dtypes
)
keep_these &= self.dtypes.isin(included_dtypes)
if exclude:
excluded_dtypes = extract_unique_dtypes_from_dtypes_set(
exclude, unique_dtypes
)
keep_these &= ~self.dtypes.isin(excluded_dtypes)
return self.iloc[:, keep_these.values]
def insert(self, loc, column, value, allow_duplicates=False) -> None:
"""
Insert column into DataFrame at specified location.
Raises a ValueError if `column` is already contained in the DataFrame,
unless `allow_duplicates` is set to True.
Parameters
----------
loc : int
Insertion index. Must verify 0 <= loc <= len(columns).
column : str, number, or hashable object
Label of the inserted column.
value : int, Series, or array-like
allow_duplicates : bool, optional
"""
if allow_duplicates and not self.flags.allows_duplicate_labels:
raise ValueError(
"Cannot specify 'allow_duplicates=True' when "
"'self.flags.allows_duplicate_labels' is False."
)
self._ensure_valid_index(value)
value = self._sanitize_column(column, value, broadcast=False)
self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates)
def assign(self, **kwargs) -> DataFrame:
r"""
Assign new columns to a DataFrame.
Returns a new object with all original columns in addition to new ones.
Existing columns that are re-assigned will be overwritten.
Parameters
----------
**kwargs : dict of {str: callable or Series}
The column names are keywords. If the values are
callable, they are computed on the DataFrame and
assigned to the new columns. The callable must not
change input DataFrame (though pandas doesn't check it).
If the values are not callable, (e.g. a Series, scalar, or array),
they are simply assigned.
Returns
-------
DataFrame
A new DataFrame with the new columns in addition to
all the existing columns.
Notes
-----
Assigning multiple columns within the same ``assign`` is possible.
Later items in '\*\*kwargs' may refer to newly created or modified
columns in 'df'; items are computed and assigned into 'df' in order.
Examples
--------
>>> df = pd.DataFrame({'temp_c': [17.0, 25.0]},
... index=['Portland', 'Berkeley'])
>>> df
temp_c
Portland 17.0
Berkeley 25.0
Where the value is a callable, evaluated on `df`:
>>> df.assign(temp_f=lambda x: x.temp_c * 9 / 5 + 32)
temp_c temp_f
Portland 17.0 62.6
Berkeley 25.0 77.0
Alternatively, the same behavior can be achieved by directly
referencing an existing Series or sequence:
>>> df.assign(temp_f=df['temp_c'] * 9 / 5 + 32)
temp_c temp_f
Portland 17.0 62.6
Berkeley 25.0 77.0
You can create multiple columns within the same assign where one
of the columns depends on another one defined within the same assign:
>>> df.assign(temp_f=lambda x: x['temp_c'] * 9 / 5 + 32,
... temp_k=lambda x: (x['temp_f'] + 459.67) * 5 / 9)
temp_c temp_f temp_k
Portland 17.0 62.6 290.15
Berkeley 25.0 77.0 298.15
"""
data = self.copy()
for k, v in kwargs.items():
data[k] = com.apply_if_callable(v, data)
return data
def _sanitize_column(self, key, value, broadcast=True):
"""
Ensures new columns (which go into the BlockManager as new blocks) are
always copied and converted into an array.
Parameters
----------
key : object
value : scalar, Series, or array-like
broadcast : bool, default True
If ``key`` matches multiple duplicate column names in the
DataFrame, this parameter indicates whether ``value`` should be
tiled so that the returned array contains a (duplicated) column for
each occurrence of the key. If False, ``value`` will not be tiled.
Returns
-------
numpy.ndarray
"""
def reindexer(value):
# reindex if necessary
if value.index.equals(self.index) or not len(self.index):
value = value._values.copy()
else:
# GH 4107
try:
value = value.reindex(self.index)._values
except ValueError as err:
# raised in MultiIndex.from_tuples, see test_insert_error_msmgs
if not value.index.is_unique:
# duplicate axis
raise err
# other
raise TypeError(
"incompatible index of inserted column with frame index"
) from err
return value
if isinstance(value, Series):
value = reindexer(value)
elif isinstance(value, DataFrame):
# align right-hand-side columns if self.columns
# is multi-index and self[key] is a sub-frame
if isinstance(self.columns, MultiIndex) and key in self.columns:
loc = self.columns.get_loc(key)
if isinstance(loc, (slice, Series, np.ndarray, Index)):
cols = maybe_droplevels(self.columns[loc], key)
if len(cols) and not cols.equals(value.columns):
value = value.reindex(cols, axis=1)
# now align rows
value = reindexer(value).T
elif isinstance(value, ExtensionArray):
# Explicitly copy here, instead of in sanitize_index,
# as sanitize_index won't copy an EA, even with copy=True
value = value.copy()
value = sanitize_index(value, self.index)
elif isinstance(value, Index) or is_sequence(value):
# turn me into an ndarray
value = sanitize_index(value, self.index)
if not isinstance(value, (np.ndarray, Index)):
if isinstance(value, list) and len(value) > 0:
value = maybe_convert_platform(value)
else:
value = com.asarray_tuplesafe(value)
elif value.ndim == 2:
value = value.copy().T
elif isinstance(value, Index):
value = value.copy(deep=True)
else:
value = value.copy()
# possibly infer to datetimelike
if is_object_dtype(value.dtype):
value = maybe_infer_to_datetimelike(value)
else:
# cast ignores pandas dtypes. so save the dtype first
infer_dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=True)
# upcast
if is_extension_array_dtype(infer_dtype):
value = construct_1d_arraylike_from_scalar(
value, len(self.index), infer_dtype
)
else:
# pandas\core\frame.py:3827: error: Argument 1 to
# "cast_scalar_to_array" has incompatible type "int"; expected
# "Tuple[Any, ...]" [arg-type]
value = cast_scalar_to_array(
len(self.index), value # type: ignore[arg-type]
)
value = maybe_cast_to_datetime(value, infer_dtype)
# return internal types directly
if is_extension_array_dtype(value):
return value
# broadcast across multiple columns if necessary
if broadcast and key in self.columns and value.ndim == 1:
if not self.columns.is_unique or isinstance(self.columns, MultiIndex):
existing_piece = self[key]
if isinstance(existing_piece, DataFrame):
value = np.tile(value, (len(existing_piece.columns), 1))
return np.atleast_2d(np.asarray(value))
@property
def _series(self):
return {
item: Series(
self._mgr.iget(idx), index=self.index, name=item, fastpath=True
)
for idx, item in enumerate(self.columns)
}
def lookup(self, row_labels, col_labels) -> np.ndarray:
"""
Label-based "fancy indexing" function for DataFrame.
Given equal-length arrays of row and column labels, return an
array of the values corresponding to each (row, col) pair.
.. deprecated:: 1.2.0
DataFrame.lookup is deprecated,
use DataFrame.melt and DataFrame.loc instead.
For an example see :meth:`~pandas.DataFrame.lookup`
in the user guide.
Parameters
----------
row_labels : sequence
The row labels to use for lookup.
col_labels : sequence
The column labels to use for lookup.
Returns
-------
numpy.ndarray
The found values.
"""
msg = (
"The 'lookup' method is deprecated and will be"
"removed in a future version."
"You can use DataFrame.melt and DataFrame.loc"
"as a substitute."
)
warnings.warn(msg, FutureWarning, stacklevel=2)
n = len(row_labels)
if n != len(col_labels):
raise ValueError("Row labels must have same size as column labels")
if not (self.index.is_unique and self.columns.is_unique):
# GH#33041
raise ValueError("DataFrame.lookup requires unique index and columns")
thresh = 1000
if not self._is_mixed_type or n > thresh:
values = self.values
ridx = self.index.get_indexer(row_labels)
cidx = self.columns.get_indexer(col_labels)
if (ridx == -1).any():
raise KeyError("One or more row labels was not found")
if (cidx == -1).any():
raise KeyError("One or more column labels was not found")
flat_index = ridx * len(self.columns) + cidx
result = values.flat[flat_index]
else:
result = np.empty(n, dtype="O")
for i, (r, c) in enumerate(zip(row_labels, col_labels)):
result[i] = self._get_value(r, c)
if is_object_dtype(result):
result = lib.maybe_convert_objects(result)
return result
# ----------------------------------------------------------------------
# Reindexing and alignment
def _reindex_axes(self, axes, level, limit, tolerance, method, fill_value, copy):
frame = self
columns = axes["columns"]
if columns is not None:
frame = frame._reindex_columns(
columns, method, copy, level, fill_value, limit, tolerance
)
index = axes["index"]
if index is not None:
frame = frame._reindex_index(
index, method, copy, level, fill_value, limit, tolerance
)
return frame
def _reindex_index(
self,
new_index,
method,
copy,
level,
fill_value=np.nan,
limit=None,
tolerance=None,
):
new_index, indexer = self.index.reindex(
new_index, method=method, level=level, limit=limit, tolerance=tolerance
)
return self._reindex_with_indexers(
{0: [new_index, indexer]},
copy=copy,
fill_value=fill_value,
allow_dups=False,
)
def _reindex_columns(
self,
new_columns,
method,
copy,
level,
fill_value=None,
limit=None,
tolerance=None,
):
new_columns, indexer = self.columns.reindex(
new_columns, method=method, level=level, limit=limit, tolerance=tolerance
)
return self._reindex_with_indexers(
{1: [new_columns, indexer]},
copy=copy,
fill_value=fill_value,
allow_dups=False,
)
def _reindex_multi(self, axes, copy, fill_value) -> DataFrame:
"""
We are guaranteed non-Nones in the axes.
"""
new_index, row_indexer = self.index.reindex(axes["index"])
new_columns, col_indexer = self.columns.reindex(axes["columns"])
if row_indexer is not None and col_indexer is not None:
indexer = row_indexer, col_indexer
new_values = algorithms.take_2d_multi(
self.values, indexer, fill_value=fill_value
)
return self._constructor(new_values, index=new_index, columns=new_columns)
else:
return self._reindex_with_indexers(
{0: [new_index, row_indexer], 1: [new_columns, col_indexer]},
copy=copy,
fill_value=fill_value,
)
@doc(NDFrame.align, **_shared_doc_kwargs)
def align(
self,
other,
join="outer",
axis=None,
level=None,
copy=True,
fill_value=None,
method=None,
limit=None,
fill_axis=0,
broadcast_axis=None,
) -> DataFrame:
return super().align(
other,
join=join,
axis=axis,
level=level,
copy=copy,
fill_value=fill_value,
method=method,
limit=limit,
fill_axis=fill_axis,
broadcast_axis=broadcast_axis,
)
@Appender(
"""
Examples
--------
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
Change the row labels.
>>> df.set_axis(['a', 'b', 'c'], axis='index')
A B
a 1 4
b 2 5
c 3 6
Change the column labels.
>>> df.set_axis(['I', 'II'], axis='columns')
I II
0 1 4
1 2 5
2 3 6
Now, update the labels inplace.
>>> df.set_axis(['i', 'ii'], axis='columns', inplace=True)
>>> df
i ii
0 1 4
1 2 5
2 3 6
"""
)
@Substitution(
**_shared_doc_kwargs,
extended_summary_sub=" column or",
axis_description_sub=", and 1 identifies the columns",
see_also_sub=" or columns",
)
@Appender(NDFrame.set_axis.__doc__)
def set_axis(self, labels, axis: Axis = 0, inplace: bool = False):
return super().set_axis(labels, axis=axis, inplace=inplace)
@Substitution(**_shared_doc_kwargs)
@Appender(NDFrame.reindex.__doc__)
@rewrite_axis_style_signature(
"labels",
[
("method", None),
("copy", True),
("level", None),
("fill_value", np.nan),
("limit", None),
("tolerance", None),
],
)
def reindex(self, *args, **kwargs) -> DataFrame:
axes = validate_axis_style_args(self, args, kwargs, "labels", "reindex")
kwargs.update(axes)
# Pop these, since the values are in `kwargs` under different names
kwargs.pop("axis", None)
kwargs.pop("labels", None)
return super().reindex(**kwargs)
def drop(
self,
labels=None,
axis=0,
index=None,
columns=None,
level=None,
inplace=False,
errors="raise",
):
"""
Drop specified labels from rows or columns.
Remove rows or columns by specifying label names and corresponding
axis, or by specifying directly index or column names. When using a
multi-index, labels on different levels can be removed by specifying
the level.
Parameters
----------
labels : single label or list-like
Index or column labels to drop.
axis : {0 or 'index', 1 or 'columns'}, default 0
Whether to drop labels from the index (0 or 'index') or
columns (1 or 'columns').
index : single label or list-like
Alternative to specifying axis (``labels, axis=0``
is equivalent to ``index=labels``).
columns : single label or list-like
Alternative to specifying axis (``labels, axis=1``
is equivalent to ``columns=labels``).
level : int or level name, optional
For MultiIndex, level from which the labels will be removed.
inplace : bool, default False
If False, return a copy. Otherwise, do operation
inplace and return None.
errors : {'ignore', 'raise'}, default 'raise'
If 'ignore', suppress error and only existing labels are
dropped.
Returns
-------
DataFrame or None
DataFrame without the removed index or column labels or
None if ``inplace=True``.
Raises
------
KeyError
If any of the labels is not found in the selected axis.
See Also
--------
DataFrame.loc : Label-location based indexer for selection by label.
DataFrame.dropna : Return DataFrame with labels on given axis omitted
where (all or any) data are missing.
DataFrame.drop_duplicates : Return DataFrame with duplicate rows
removed, optionally only considering certain columns.
Series.drop : Return Series with specified index labels removed.
Examples
--------
>>> df = pd.DataFrame(np.arange(12).reshape(3, 4),
... columns=['A', 'B', 'C', 'D'])
>>> df
A B C D
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
Drop columns
>>> df.drop(['B', 'C'], axis=1)
A D
0 0 3
1 4 7
2 8 11
>>> df.drop(columns=['B', 'C'])
A D
0 0 3
1 4 7
2 8 11
Drop a row by index
>>> df.drop([0, 1])
A B C D
2 8 9 10 11
Drop columns and/or rows of MultiIndex DataFrame
>>> midx = pd.MultiIndex(levels=[['lama', 'cow', 'falcon'],
... ['speed', 'weight', 'length']],
... codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2],
... [0, 1, 2, 0, 1, 2, 0, 1, 2]])
>>> df = pd.DataFrame(index=midx, columns=['big', 'small'],
... data=[[45, 30], [200, 100], [1.5, 1], [30, 20],
... [250, 150], [1.5, 0.8], [320, 250],
... [1, 0.8], [0.3, 0.2]])
>>> df
big small
lama speed 45.0 30.0
weight 200.0 100.0
length 1.5 1.0
cow speed 30.0 20.0
weight 250.0 150.0
length 1.5 0.8
falcon speed 320.0 250.0
weight 1.0 0.8
length 0.3 0.2
>>> df.drop(index='cow', columns='small')
big
lama speed 45.0
weight 200.0
length 1.5
falcon speed 320.0
weight 1.0
length 0.3
>>> df.drop(index='length', level=1)
big small
lama speed 45.0 30.0
weight 200.0 100.0
cow speed 30.0 20.0
weight 250.0 150.0
falcon speed 320.0 250.0
weight 1.0 0.8
"""
return super().drop(
labels=labels,
axis=axis,
index=index,
columns=columns,
level=level,
inplace=inplace,
errors=errors,
)
@rewrite_axis_style_signature(
"mapper",
[("copy", True), ("inplace", False), ("level", None), ("errors", "ignore")],
)
def rename(
self,
mapper: Optional[Renamer] = None,
*,
index: Optional[Renamer] = None,
columns: Optional[Renamer] = None,
axis: Optional[Axis] = None,
copy: bool = True,
inplace: bool = False,
level: Optional[Level] = None,
errors: str = "ignore",
) -> Optional[DataFrame]:
"""
Alter axes labels.
Function / dict values must be unique (1-to-1). Labels not contained in
a dict / Series will be left as-is. Extra labels listed don't throw an
error.
See the :ref:`user guide <basics.rename>` for more.
Parameters
----------
mapper : dict-like or function
Dict-like or function transformations to apply to
that axis' values. Use either ``mapper`` and ``axis`` to
specify the axis to target with ``mapper``, or ``index`` and
``columns``.
index : dict-like or function
Alternative to specifying axis (``mapper, axis=0``
is equivalent to ``index=mapper``).
columns : dict-like or function
Alternative to specifying axis (``mapper, axis=1``
is equivalent to ``columns=mapper``).
axis : {0 or 'index', 1 or 'columns'}, default 0
Axis to target with ``mapper``. Can be either the axis name
('index', 'columns') or number (0, 1). The default is 'index'.
copy : bool, default True
Also copy underlying data.
inplace : bool, default False
Whether to return a new DataFrame. If True then value of copy is
ignored.
level : int or level name, default None
In case of a MultiIndex, only rename labels in the specified
level.
errors : {'ignore', 'raise'}, default 'ignore'
If 'raise', raise a `KeyError` when a dict-like `mapper`, `index`,
or `columns` contains labels that are not present in the Index
being transformed.
If 'ignore', existing keys will be renamed and extra keys will be
ignored.
Returns
-------
DataFrame or None
DataFrame with the renamed axis labels or None if ``inplace=True``.
Raises
------
KeyError
If any of the labels is not found in the selected axis and
"errors='raise'".
See Also
--------
DataFrame.rename_axis : Set the name of the axis.
Examples
--------
``DataFrame.rename`` supports two calling conventions
* ``(index=index_mapper, columns=columns_mapper, ...)``
* ``(mapper, axis={'index', 'columns'}, ...)``
We *highly* recommend using keyword arguments to clarify your
intent.
Rename columns using a mapping:
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
>>> df.rename(columns={"A": "a", "B": "c"})
a c
0 1 4
1 2 5
2 3 6
Rename index using a mapping:
>>> df.rename(index={0: "x", 1: "y", 2: "z"})
A B
x 1 4
y 2 5
z 3 6
Cast index labels to a different type:
>>> df.index
RangeIndex(start=0, stop=3, step=1)
>>> df.rename(index=str).index
Index(['0', '1', '2'], dtype='object')
>>> df.rename(columns={"A": "a", "B": "b", "C": "c"}, errors="raise")
Traceback (most recent call last):
KeyError: ['C'] not found in axis
Using axis-style parameters:
>>> df.rename(str.lower, axis='columns')
a b
0 1 4
1 2 5
2 3 6
>>> df.rename({1: 2, 2: 4}, axis='index')
A B
0 1 4
2 2 5
4 3 6
"""
return super().rename(
mapper=mapper,
index=index,
columns=columns,
axis=axis,
copy=copy,
inplace=inplace,
level=level,
errors=errors,
)
@doc(NDFrame.fillna, **_shared_doc_kwargs)
def fillna(
self,
value=None,
method=None,
axis=None,
inplace=False,
limit=None,
downcast=None,
) -> Optional[DataFrame]:
return super().fillna(
value=value,
method=method,
axis=axis,
inplace=inplace,
limit=limit,
downcast=downcast,
)
def pop(self, item: Label) -> Series:
"""
Return item and drop from frame. Raise KeyError if not found.
Parameters
----------
item : label
Label of column to be popped.
Returns
-------
Series
Examples
--------
>>> df = pd.DataFrame([('falcon', 'bird', 389.0),
... ('parrot', 'bird', 24.0),
... ('lion', 'mammal', 80.5),
... ('monkey', 'mammal', np.nan)],
... columns=('name', 'class', 'max_speed'))
>>> df
name class max_speed
0 falcon bird 389.0
1 parrot bird 24.0
2 lion mammal 80.5
3 monkey mammal NaN
>>> df.pop('class')
0 bird
1 bird
2 mammal
3 mammal
Name: class, dtype: object
>>> df
name max_speed
0 falcon 389.0
1 parrot 24.0
2 lion 80.5
3 monkey NaN
"""
return super().pop(item=item)
@doc(NDFrame.replace, **_shared_doc_kwargs)
def replace(
self,
to_replace=None,
value=None,
inplace=False,
limit=None,
regex=False,
method="pad",
):
return super().replace(
to_replace=to_replace,
value=value,
inplace=inplace,
limit=limit,
regex=regex,
method=method,
)
def _replace_columnwise(
self, mapping: Dict[Label, Tuple[Any, Any]], inplace: bool, regex
):
"""
Dispatch to Series.replace column-wise.
Parameters
----------
mapping : dict
of the form {col: (target, value)}
inplace : bool
regex : bool or same types as `to_replace` in DataFrame.replace
Returns
-------
DataFrame or None
"""
# Operate column-wise
res = self if inplace else self.copy()
ax = self.columns
for i in range(len(ax)):
if ax[i] in mapping:
ser = self.iloc[:, i]
target, value = mapping[ax[i]]
newobj = ser.replace(target, value, regex=regex)
res.iloc[:, i] = newobj
if inplace:
return
return res.__finalize__(self)
@doc(NDFrame.shift, klass=_shared_doc_kwargs["klass"])
def shift(
self, periods=1, freq=None, axis=0, fill_value=lib.no_default
) -> DataFrame:
axis = self._get_axis_number(axis)
ncols = len(self.columns)
if axis == 1 and periods != 0 and fill_value is lib.no_default and ncols > 0:
# We will infer fill_value to match the closest column
if periods > 0:
result = self.iloc[:, :-periods]
for col in range(min(ncols, abs(periods))):
# TODO(EA2D): doing this in a loop unnecessary with 2D EAs
# Define filler inside loop so we get a copy
filler = self.iloc[:, 0].shift(len(self))
result.insert(0, col, filler, allow_duplicates=True)
else:
result = self.iloc[:, -periods:]
for col in range(min(ncols, abs(periods))):
# Define filler inside loop so we get a copy
filler = self.iloc[:, -1].shift(len(self))
result.insert(
len(result.columns), col, filler, allow_duplicates=True
)
result.columns = self.columns.copy()
return result
return super().shift(
periods=periods, freq=freq, axis=axis, fill_value=fill_value
)
def set_index(
self, keys, drop=True, append=False, inplace=False, verify_integrity=False
):
"""
Set the DataFrame index using existing columns.
Set the DataFrame index (row labels) using one or more existing
columns or arrays (of the correct length). The index can replace the
existing index or expand on it.
Parameters
----------
keys : label or array-like or list of labels/arrays
This parameter can be either a single column key, a single array of
the same length as the calling DataFrame, or a list containing an
arbitrary combination of column keys and arrays. Here, "array"
encompasses :class:`Series`, :class:`Index`, ``np.ndarray``, and
instances of :class:`~collections.abc.Iterator`.
drop : bool, default True
Delete columns to be used as the new index.
append : bool, default False
Whether to append columns to existing index.
inplace : bool, default False
If True, modifies the DataFrame in place (do not create a new object).
verify_integrity : bool, default False
Check the new index for duplicates. Otherwise defer the check until
necessary. Setting to False will improve the performance of this
method.
Returns
-------
DataFrame or None
Changed row labels or None if ``inplace=True``.
See Also
--------
DataFrame.reset_index : Opposite of set_index.
DataFrame.reindex : Change to new indices or expand indices.
DataFrame.reindex_like : Change to same indices as other DataFrame.
Examples
--------
>>> df = pd.DataFrame({'month': [1, 4, 7, 10],
... 'year': [2012, 2014, 2013, 2014],
... 'sale': [55, 40, 84, 31]})
>>> df
month year sale
0 1 2012 55
1 4 2014 40
2 7 2013 84
3 10 2014 31
Set the index to become the 'month' column:
>>> df.set_index('month')
year sale
month
1 2012 55
4 2014 40
7 2013 84
10 2014 31
Create a MultiIndex using columns 'year' and 'month':
>>> df.set_index(['year', 'month'])
sale
year month
2012 1 55
2014 4 40
2013 7 84
2014 10 31
Create a MultiIndex using an Index and a column:
>>> df.set_index([pd.Index([1, 2, 3, 4]), 'year'])
month sale
year
1 2012 1 55
2 2014 4 40
3 2013 7 84
4 2014 10 31
Create a MultiIndex using two Series:
>>> s = pd.Series([1, 2, 3, 4])
>>> df.set_index([s, s**2])
month year sale
1 1 1 2012 55
2 4 4 2014 40
3 9 7 2013 84
4 16 10 2014 31
"""
inplace = validate_bool_kwarg(inplace, "inplace")
self._check_inplace_and_allows_duplicate_labels(inplace)
if not isinstance(keys, list):
keys = [keys]
err_msg = (
'The parameter "keys" may be a column key, one-dimensional '
"array, or a list containing only valid column keys and "
"one-dimensional arrays."
)
missing: List[Label] = []
for col in keys:
if isinstance(col, (Index, Series, np.ndarray, list, abc.Iterator)):
# arrays are fine as long as they are one-dimensional
# iterators get converted to list below
if getattr(col, "ndim", 1) != 1:
raise ValueError(err_msg)
else:
# everything else gets tried as a key; see GH 24969
try:
found = col in self.columns
except TypeError as err:
raise TypeError(
f"{err_msg}. Received column of type {type(col)}"
) from err
else:
if not found:
missing.append(col)
if missing:
raise KeyError(f"None of {missing} are in the columns")
if inplace:
frame = self
else:
frame = self.copy()
arrays = []
names: List[Label] = []
if append:
names = list(self.index.names)
if isinstance(self.index, MultiIndex):
for i in range(self.index.nlevels):
arrays.append(self.index._get_level_values(i))
else:
arrays.append(self.index)
to_remove: List[Label] = []
for col in keys:
if isinstance(col, MultiIndex):
for n in range(col.nlevels):
arrays.append(col._get_level_values(n))
names.extend(col.names)
elif isinstance(col, (Index, Series)):
# if Index then not MultiIndex (treated above)
arrays.append(col)
names.append(col.name)
elif isinstance(col, (list, np.ndarray)):
arrays.append(col)
names.append(None)
elif isinstance(col, abc.Iterator):
arrays.append(list(col))
names.append(None)
# from here, col can only be a column label
else:
arrays.append(frame[col]._values)
names.append(col)
if drop:
to_remove.append(col)
if len(arrays[-1]) != len(self):
# check newest element against length of calling frame, since
# ensure_index_from_sequences would not raise for append=False.
raise ValueError(
f"Length mismatch: Expected {len(self)} rows, "
f"received array of length {len(arrays[-1])}"
)
index = ensure_index_from_sequences(arrays, names)
if verify_integrity and not index.is_unique:
duplicates = index[index.duplicated()].unique()
raise ValueError(f"Index has duplicate keys: {duplicates}")
# use set to handle duplicate column names gracefully in case of drop
for c in set(to_remove):
del frame[c]
# clear up memory usage
index._cleanup()
frame.index = index
if not inplace:
return frame
@overload
# https://github.com/python/mypy/issues/6580
# Overloaded function signatures 1 and 2 overlap with incompatible return types
def reset_index( # type: ignore[misc]
self,
level: Optional[Union[Hashable, Sequence[Hashable]]] = ...,
drop: bool = ...,
inplace: Literal[False] = ...,
col_level: Hashable = ...,
col_fill: Label = ...,
) -> DataFrame:
...
@overload
def reset_index(
self,
level: Optional[Union[Hashable, Sequence[Hashable]]] = ...,
drop: bool = ...,
inplace: Literal[True] = ...,
col_level: Hashable = ...,
col_fill: Label = ...,
) -> None:
...
def reset_index(
self,
level: Optional[Union[Hashable, Sequence[Hashable]]] = None,
drop: bool = False,
inplace: bool = False,
col_level: Hashable = 0,
col_fill: Label = "",
) -> Optional[DataFrame]:
"""
Reset the index, or a level of it.
Reset the index of the DataFrame, and use the default one instead.
If the DataFrame has a MultiIndex, this method can remove one or more
levels.
Parameters
----------
level : int, str, tuple, or list, default None
Only remove the given levels from the index. Removes all levels by
default.
drop : bool, default False
Do not try to insert index into dataframe columns. This resets
the index to the default integer index.
inplace : bool, default False
Modify the DataFrame in place (do not create a new object).
col_level : int or str, default 0
If the columns have multiple levels, determines which level the
labels are inserted into. By default it is inserted into the first
level.
col_fill : object, default ''
If the columns have multiple levels, determines how the other
levels are named. If None then the index name is repeated.
Returns
-------
DataFrame or None
DataFrame with the new index or None if ``inplace=True``.
See Also
--------
DataFrame.set_index : Opposite of reset_index.
DataFrame.reindex : Change to new indices or expand indices.
DataFrame.reindex_like : Change to same indices as other DataFrame.
Examples
--------
>>> df = pd.DataFrame([('bird', 389.0),
... ('bird', 24.0),
... ('mammal', 80.5),
... ('mammal', np.nan)],
... index=['falcon', 'parrot', 'lion', 'monkey'],
... columns=('class', 'max_speed'))
>>> df
class max_speed
falcon bird 389.0
parrot bird 24.0
lion mammal 80.5
monkey mammal NaN
When we reset the index, the old index is added as a column, and a
new sequential index is used:
>>> df.reset_index()
index class max_speed
0 falcon bird 389.0
1 parrot bird 24.0
2 lion mammal 80.5
3 monkey mammal NaN
We can use the `drop` parameter to avoid the old index being added as
a column:
>>> df.reset_index(drop=True)
class max_speed
0 bird 389.0
1 bird 24.0
2 mammal 80.5
3 mammal NaN
You can also use `reset_index` with `MultiIndex`.
>>> index = pd.MultiIndex.from_tuples([('bird', 'falcon'),
... ('bird', 'parrot'),
... ('mammal', 'lion'),
... ('mammal', 'monkey')],
... names=['class', 'name'])
>>> columns = pd.MultiIndex.from_tuples([('speed', 'max'),
... ('species', 'type')])
>>> df = pd.DataFrame([(389.0, 'fly'),
... ( 24.0, 'fly'),
... ( 80.5, 'run'),
... (np.nan, 'jump')],
... index=index,
... columns=columns)
>>> df
speed species
max type
class name
bird falcon 389.0 fly
parrot 24.0 fly
mammal lion 80.5 run
monkey NaN jump
If the index has multiple levels, we can reset a subset of them:
>>> df.reset_index(level='class')
class speed species
max type
name
falcon bird 389.0 fly
parrot bird 24.0 fly
lion mammal 80.5 run
monkey mammal NaN jump
If we are not dropping the index, by default, it is placed in the top
level. We can place it in another level:
>>> df.reset_index(level='class', col_level=1)
speed species
class max type
name
falcon bird 389.0 fly
parrot bird 24.0 fly
lion mammal 80.5 run
monkey mammal NaN jump
When the index is inserted under another level, we can specify under
which one with the parameter `col_fill`:
>>> df.reset_index(level='class', col_level=1, col_fill='species')
species speed species
class max type
name
falcon bird 389.0 fly
parrot bird 24.0 fly
lion mammal 80.5 run
monkey mammal NaN jump
If we specify a nonexistent level for `col_fill`, it is created:
>>> df.reset_index(level='class', col_level=1, col_fill='genus')
genus speed species
class max type
name
falcon bird 389.0 fly
parrot bird 24.0 fly
lion mammal 80.5 run
monkey mammal NaN jump
"""
inplace = validate_bool_kwarg(inplace, "inplace")
self._check_inplace_and_allows_duplicate_labels(inplace)
if inplace:
new_obj = self
else:
new_obj = self.copy()
new_index = ibase.default_index(len(new_obj))
if level is not None:
if not isinstance(level, (tuple, list)):
level = [level]
level = [self.index._get_level_number(lev) for lev in level]
if len(level) < self.index.nlevels:
new_index = self.index.droplevel(level)
if not drop:
to_insert: Iterable[Tuple[Any, Optional[Any]]]
if isinstance(self.index, MultiIndex):
names = [
(n if n is not None else f"level_{i}")
for i, n in enumerate(self.index.names)
]
to_insert = zip(self.index.levels, self.index.codes)
else:
default = "index" if "index" not in self else "level_0"
names = [default] if self.index.name is None else [self.index.name]
to_insert = ((self.index, None),)
multi_col = isinstance(self.columns, MultiIndex)
for i, (lev, lab) in reversed(list(enumerate(to_insert))):
if not (level is None or i in level):
continue
name = names[i]
if multi_col:
col_name = list(name) if isinstance(name, tuple) else [name]
if col_fill is None:
if len(col_name) not in (1, self.columns.nlevels):
raise ValueError(
"col_fill=None is incompatible "
f"with incomplete column name {name}"
)
col_fill = col_name[0]
lev_num = self.columns._get_level_number(col_level)
name_lst = [col_fill] * lev_num + col_name
missing = self.columns.nlevels - len(name_lst)
name_lst += [col_fill] * missing
name = tuple(name_lst)
# to ndarray and maybe infer different dtype
level_values = maybe_casted_values(lev, lab)
new_obj.insert(0, name, level_values)
new_obj.index = new_index
if not inplace:
return new_obj
return None
# ----------------------------------------------------------------------
# Reindex-based selection methods
@doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"])
def isna(self) -> DataFrame:
result = self._constructor(self._mgr.isna(func=isna))
return result.__finalize__(self, method="isna")
@doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"])
def isnull(self) -> DataFrame:
return self.isna()
@doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"])
def notna(self) -> DataFrame:
return ~self.isna()
@doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"])
def notnull(self) -> DataFrame:
return ~self.isna()
def dropna(self, axis=0, how="any", thresh=None, subset=None, inplace=False):
"""
Remove missing values.
See the :ref:`User Guide <missing_data>` for more on which values are
considered missing, and how to work with missing data.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
Determine if rows or columns which contain missing values are
removed.
* 0, or 'index' : Drop rows which contain missing values.
* 1, or 'columns' : Drop columns which contain missing value.
.. versionchanged:: 1.0.0
Pass tuple or list to drop on multiple axes.
Only a single axis is allowed.
how : {'any', 'all'}, default 'any'
Determine if row or column is removed from DataFrame, when we have
at least one NA or all NA.
* 'any' : If any NA values are present, drop that row or column.
* 'all' : If all values are NA, drop that row or column.
thresh : int, optional
Require that many non-NA values.
subset : array-like, optional
Labels along other axis to consider, e.g. if you are dropping rows
these would be a list of columns to include.
inplace : bool, default False
If True, do operation inplace and return None.
Returns
-------
DataFrame or None
DataFrame with NA entries dropped from it or None if ``inplace=True``.
See Also
--------
DataFrame.isna: Indicate missing values.
DataFrame.notna : Indicate existing (non-missing) values.
DataFrame.fillna : Replace missing values.
Series.dropna : Drop missing values.
Index.dropna : Drop missing indices.
Examples
--------
>>> df = pd.DataFrame({"name": ['Alfred', 'Batman', 'Catwoman'],
... "toy": [np.nan, 'Batmobile', 'Bullwhip'],
... "born": [pd.NaT, pd.Timestamp("1940-04-25"),
... pd.NaT]})
>>> df
name toy born
0 Alfred NaN NaT
1 Batman Batmobile 1940-04-25
2 Catwoman Bullwhip NaT
Drop the rows where at least one element is missing.
>>> df.dropna()
name toy born
1 Batman Batmobile 1940-04-25
Drop the columns where at least one element is missing.
>>> df.dropna(axis='columns')
name
0 Alfred
1 Batman
2 Catwoman
Drop the rows where all elements are missing.
>>> df.dropna(how='all')
name toy born
0 Alfred NaN NaT
1 Batman Batmobile 1940-04-25
2 Catwoman Bullwhip NaT
Keep only the rows with at least 2 non-NA values.
>>> df.dropna(thresh=2)
name toy born
1 Batman Batmobile 1940-04-25
2 Catwoman Bullwhip NaT
Define in which columns to look for missing values.
>>> df.dropna(subset=['name', 'toy'])
name toy born
1 Batman Batmobile 1940-04-25
2 Catwoman Bullwhip NaT
Keep the DataFrame with valid entries in the same variable.
>>> df.dropna(inplace=True)
>>> df
name toy born
1 Batman Batmobile 1940-04-25
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if isinstance(axis, (tuple, list)):
# GH20987
raise TypeError("supplying multiple axes to axis is no longer supported.")
axis = self._get_axis_number(axis)
agg_axis = 1 - axis
agg_obj = self
if subset is not None:
ax = self._get_axis(agg_axis)
indices = ax.get_indexer_for(subset)
check = indices == -1
if check.any():
raise KeyError(list(np.compress(check, subset)))
agg_obj = self.take(indices, axis=agg_axis)
count = agg_obj.count(axis=agg_axis)
if thresh is not None:
mask = count >= thresh
elif how == "any":
mask = count == len(agg_obj._get_axis(agg_axis))
elif how == "all":
mask = count > 0
else:
if how is not None:
raise ValueError(f"invalid how option: {how}")
else:
raise TypeError("must specify how or thresh")
result = self.loc(axis=axis)[mask]
if inplace:
self._update_inplace(result)
else:
return result
def drop_duplicates(
self,
subset: Optional[Union[Hashable, Sequence[Hashable]]] = None,
keep: Union[str, bool] = "first",
inplace: bool = False,
ignore_index: bool = False,
) -> Optional[DataFrame]:
"""
Return DataFrame with duplicate rows removed.
Considering certain columns is optional. Indexes, including time indexes
are ignored.
Parameters
----------
subset : column label or sequence of labels, optional
Only consider certain columns for identifying duplicates, by
default use all of the columns.
keep : {'first', 'last', False}, default 'first'
Determines which duplicates (if any) to keep.
- ``first`` : Drop duplicates except for the first occurrence.
- ``last`` : Drop duplicates except for the last occurrence.
- False : Drop all duplicates.
inplace : bool, default False
Whether to drop duplicates in place or to return a copy.
ignore_index : bool, default False
If True, the resulting axis will be labeled 0, 1, …, n - 1.
.. versionadded:: 1.0.0
Returns
-------
DataFrame or None
DataFrame with duplicates removed or None if ``inplace=True``.
See Also
--------
DataFrame.value_counts: Count unique combinations of columns.
Examples
--------
Consider dataset containing ramen rating.
>>> df = pd.DataFrame({
... 'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],
... 'style': ['cup', 'cup', 'cup', 'pack', 'pack'],
... 'rating': [4, 4, 3.5, 15, 5]
... })
>>> df
brand style rating
0 Yum Yum cup 4.0
1 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0
By default, it removes duplicate rows based on all columns.
>>> df.drop_duplicates()
brand style rating
0 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0
To remove duplicates on specific column(s), use ``subset``.
>>> df.drop_duplicates(subset=['brand'])
brand style rating
0 Yum Yum cup 4.0
2 Indomie cup 3.5
To remove duplicates and keep last occurrences, use ``keep``.
>>> df.drop_duplicates(subset=['brand', 'style'], keep='last')
brand style rating
1 Yum Yum cup 4.0
2 Indomie cup 3.5
4 Indomie pack 5.0
"""
if self.empty:
return self.copy()
inplace = validate_bool_kwarg(inplace, "inplace")
ignore_index = validate_bool_kwarg(ignore_index, "ignore_index")
duplicated = self.duplicated(subset, keep=keep)
result = self[-duplicated]
if ignore_index:
result.index = ibase.default_index(len(result))
if inplace:
self._update_inplace(result)
return None
else:
return result
def duplicated(
self,
subset: Optional[Union[Hashable, Sequence[Hashable]]] = None,
keep: Union[str, bool] = "first",
) -> Series:
"""
Return boolean Series denoting duplicate rows.
Considering certain columns is optional.
Parameters
----------
subset : column label or sequence of labels, optional
Only consider certain columns for identifying duplicates, by
default use all of the columns.
keep : {'first', 'last', False}, default 'first'
Determines which duplicates (if any) to mark.
- ``first`` : Mark duplicates as ``True`` except for the first occurrence.
- ``last`` : Mark duplicates as ``True`` except for the last occurrence.
- False : Mark all duplicates as ``True``.
Returns
-------
Series
Boolean series for each duplicated rows.
See Also
--------
Index.duplicated : Equivalent method on index.
Series.duplicated : Equivalent method on Series.
Series.drop_duplicates : Remove duplicate values from Series.
DataFrame.drop_duplicates : Remove duplicate values from DataFrame.
Examples
--------
Consider dataset containing ramen rating.
>>> df = pd.DataFrame({
... 'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],
... 'style': ['cup', 'cup', 'cup', 'pack', 'pack'],
... 'rating': [4, 4, 3.5, 15, 5]
... })
>>> df
brand style rating
0 Yum Yum cup 4.0
1 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0
By default, for each set of duplicated values, the first occurrence
is set on False and all others on True.
>>> df.duplicated()
0 False
1 True
2 False
3 False
4 False
dtype: bool
By using 'last', the last occurrence of each set of duplicated values
is set on False and all others on True.
>>> df.duplicated(keep='last')
0 True
1 False
2 False
3 False
4 False
dtype: bool
By setting ``keep`` on False, all duplicates are True.
>>> df.duplicated(keep=False)
0 True
1 True
2 False
3 False
4 False
dtype: bool
To find duplicates on specific column(s), use ``subset``.
>>> df.duplicated(subset=['brand'])
0 False
1 True
2 False
3 True
4 True
dtype: bool
"""
from pandas._libs.hashtable import SIZE_HINT_LIMIT, duplicated_int64
if self.empty:
return self._constructor_sliced(dtype=bool)
def f(vals):
labels, shape = algorithms.factorize(
vals, size_hint=min(len(self), SIZE_HINT_LIMIT)
)
return labels.astype("i8", copy=False), len(shape)
if subset is None:
subset = self.columns
elif (
not np.iterable(subset)
or isinstance(subset, str)
or isinstance(subset, tuple)
and subset in self.columns
):
subset = (subset,)
# needed for mypy since can't narrow types using np.iterable
subset = cast(Iterable, subset)
# Verify all columns in subset exist in the queried dataframe
# Otherwise, raise a KeyError, same as if you try to __getitem__ with a
# key that doesn't exist.
diff = Index(subset).difference(self.columns)
if not diff.empty:
raise KeyError(diff)
vals = (col.values for name, col in self.items() if name in subset)
labels, shape = map(list, zip(*map(f, vals)))
ids = get_group_index(labels, shape, sort=False, xnull=False)
result = self._constructor_sliced(duplicated_int64(ids, keep), index=self.index)
return result.__finalize__(self, method="duplicated")
# ----------------------------------------------------------------------
# Sorting
# TODO: Just move the sort_values doc here.
@Substitution(**_shared_doc_kwargs)
@Appender(NDFrame.sort_values.__doc__)
# error: Signature of "sort_values" incompatible with supertype "NDFrame"
def sort_values( # type: ignore[override]
self,
by,
axis=0,
ascending=True,
inplace=False,
kind="quicksort",
na_position="last",
ignore_index=False,
key: ValueKeyFunc = None,
):
inplace = validate_bool_kwarg(inplace, "inplace")
axis = self._get_axis_number(axis)
if not isinstance(by, list):
by = [by]
if is_sequence(ascending) and len(by) != len(ascending):
raise ValueError(
f"Length of ascending ({len(ascending)}) != length of by ({len(by)})"
)
if len(by) > 1:
keys = [self._get_label_or_level_values(x, axis=axis) for x in by]
# need to rewrap columns in Series to apply key function
if key is not None:
keys = [Series(k, name=name) for (k, name) in zip(keys, by)]
indexer = lexsort_indexer(
keys, orders=ascending, na_position=na_position, key=key
)
indexer = ensure_platform_int(indexer)
else:
by = by[0]
k = self._get_label_or_level_values(by, axis=axis)
# need to rewrap column in Series to apply key function
if key is not None:
k = Series(k, name=by)
if isinstance(ascending, (tuple, list)):
ascending = ascending[0]
indexer = nargsort(
k, kind=kind, ascending=ascending, na_position=na_position, key=key
)
new_data = self._mgr.take(
indexer, axis=self._get_block_manager_axis(axis), verify=False
)
if ignore_index:
new_data.axes[1] = ibase.default_index(len(indexer))
result = self._constructor(new_data)
if inplace:
return self._update_inplace(result)
else:
return result.__finalize__(self, method="sort_values")
def sort_index(
self,
axis=0,
level=None,
ascending: bool = True,
inplace: bool = False,
kind: str = "quicksort",
na_position: str = "last",
sort_remaining: bool = True,
ignore_index: bool = False,
key: IndexKeyFunc = None,
):
"""
Sort object by labels (along an axis).
Returns a new DataFrame sorted by label if `inplace` argument is
``False``, otherwise updates the original DataFrame and returns None.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis along which to sort. The value 0 identifies the rows,
and 1 identifies the columns.
level : int or level name or list of ints or list of level names
If not None, sort on values in specified index level(s).
ascending : bool or list of bools, default True
Sort ascending vs. descending. When the index is a MultiIndex the
sort direction can be controlled for each level individually.
inplace : bool, default False
If True, perform operation in-place.
kind : {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'
Choice of sorting algorithm. See also ndarray.np.sort for more
information. `mergesort` is the only stable algorithm. For
DataFrames, this option is only applied when sorting on a single
column or label.
na_position : {'first', 'last'}, default 'last'
Puts NaNs at the beginning if `first`; `last` puts NaNs at the end.
Not implemented for MultiIndex.
sort_remaining : bool, default True
If True and sorting by level and index is multilevel, sort by other
levels too (in order) after sorting by specified level.
ignore_index : bool, default False
If True, the resulting axis will be labeled 0, 1, …, n - 1.
.. versionadded:: 1.0.0
key : callable, optional
If not None, apply the key function to the index values
before sorting. This is similar to the `key` argument in the
builtin :meth:`sorted` function, with the notable difference that
this `key` function should be *vectorized*. It should expect an
``Index`` and return an ``Index`` of the same shape. For MultiIndex
inputs, the key is applied *per level*.
.. versionadded:: 1.1.0
Returns
-------
DataFrame or None
The original DataFrame sorted by the labels or None if ``inplace=True``.
See Also
--------
Series.sort_index : Sort Series by the index.
DataFrame.sort_values : Sort DataFrame by the value.
Series.sort_values : Sort Series by the value.
Examples
--------
>>> df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150],
... columns=['A'])
>>> df.sort_index()
A
1 4
29 2
100 1
150 5
234 3
By default, it sorts in ascending order, to sort in descending order,
use ``ascending=False``
>>> df.sort_index(ascending=False)
A
234 3
150 5
100 1
29 2
1 4
A key function can be specified which is applied to the index before
sorting. For a ``MultiIndex`` this is applied to each level separately.
>>> df = pd.DataFrame({"a": [1, 2, 3, 4]}, index=['A', 'b', 'C', 'd'])
>>> df.sort_index(key=lambda x: x.str.lower())
a
A 1
b 2
C 3
d 4
"""
return super().sort_index(
axis,
level,
ascending,
inplace,
kind,
na_position,
sort_remaining,
ignore_index,
key,
)
def value_counts(
self,
subset: Optional[Sequence[Label]] = None,
normalize: bool = False,
sort: bool = True,
ascending: bool = False,
):
"""
Return a Series containing counts of unique rows in the DataFrame.
.. versionadded:: 1.1.0
Parameters
----------
subset : list-like, optional
Columns to use when counting unique combinations.
normalize : bool, default False
Return proportions rather than frequencies.
sort : bool, default True
Sort by frequencies.
ascending : bool, default False
Sort in ascending order.
Returns
-------
Series
See Also
--------
Series.value_counts: Equivalent method on Series.
Notes
-----
The returned Series will have a MultiIndex with one level per input
column. By default, rows that contain any NA values are omitted from
the result. By default, the resulting Series will be in descending
order so that the first element is the most frequently-occurring row.
Examples
--------
>>> df = pd.DataFrame({'num_legs': [2, 4, 4, 6],
... 'num_wings': [2, 0, 0, 0]},
... index=['falcon', 'dog', 'cat', 'ant'])
>>> df
num_legs num_wings
falcon 2 2
dog 4 0
cat 4 0
ant 6 0
>>> df.value_counts()
num_legs num_wings
4 0 2
2 2 1
6 0 1
dtype: int64
>>> df.value_counts(sort=False)
num_legs num_wings
2 2 1
4 0 2
6 0 1
dtype: int64
>>> df.value_counts(ascending=True)
num_legs num_wings
2 2 1
6 0 1
4 0 2
dtype: int64
>>> df.value_counts(normalize=True)
num_legs num_wings
4 0 0.50
2 2 0.25
6 0 0.25
dtype: float64
"""
if subset is None:
subset = self.columns.tolist()
counts = self.groupby(subset).grouper.size()
if sort:
counts = counts.sort_values(ascending=ascending)
if normalize:
counts /= counts.sum()
# Force MultiIndex for single column
if len(subset) == 1:
counts.index = MultiIndex.from_arrays(
[counts.index], names=[counts.index.name]
)
return counts
def nlargest(self, n, columns, keep="first") -> DataFrame:
"""
Return the first `n` rows ordered by `columns` in descending order.
Return the first `n` rows with the largest values in `columns`, in
descending order. The columns that are not specified are returned as
well, but not used for ordering.
This method is equivalent to
``df.sort_values(columns, ascending=False).head(n)``, but more
performant.
Parameters
----------
n : int
Number of rows to return.
columns : label or list of labels
Column label(s) to order by.
keep : {'first', 'last', 'all'}, default 'first'
Where there are duplicate values:
- `first` : prioritize the first occurrence(s)
- `last` : prioritize the last occurrence(s)
- ``all`` : do not drop any duplicates, even it means
selecting more than `n` items.
.. versionadded:: 0.24.0
Returns
-------
DataFrame
The first `n` rows ordered by the given columns in descending
order.
See Also
--------
DataFrame.nsmallest : Return the first `n` rows ordered by `columns` in
ascending order.
DataFrame.sort_values : Sort DataFrame by the values.
DataFrame.head : Return the first `n` rows without re-ordering.
Notes
-----
This function cannot be used with all column types. For example, when
specifying columns with `object` or `category` dtypes, ``TypeError`` is
raised.
Examples
--------
>>> df = pd.DataFrame({'population': [59000000, 65000000, 434000,
... 434000, 434000, 337000, 11300,
... 11300, 11300],
... 'GDP': [1937894, 2583560 , 12011, 4520, 12128,
... 17036, 182, 38, 311],
... 'alpha-2': ["IT", "FR", "MT", "MV", "BN",
... "IS", "NR", "TV", "AI"]},
... index=["Italy", "France", "Malta",
... "Maldives", "Brunei", "Iceland",
... "Nauru", "Tuvalu", "Anguilla"])
>>> df
population GDP alpha-2
Italy 59000000 1937894 IT
France 65000000 2583560 FR
Malta 434000 12011 MT
Maldives 434000 4520 MV
Brunei 434000 12128 BN
Iceland 337000 17036 IS
Nauru 11300 182 NR
Tuvalu 11300 38 TV
Anguilla 11300 311 AI
In the following example, we will use ``nlargest`` to select the three
rows having the largest values in column "population".
>>> df.nlargest(3, 'population')
population GDP alpha-2
France 65000000 2583560 FR
Italy 59000000 1937894 IT
Malta 434000 12011 MT
When using ``keep='last'``, ties are resolved in reverse order:
>>> df.nlargest(3, 'population', keep='last')
population GDP alpha-2
France 65000000 2583560 FR
Italy 59000000 1937894 IT
Brunei 434000 12128 BN
When using ``keep='all'``, all duplicate items are maintained:
>>> df.nlargest(3, 'population', keep='all')
population GDP alpha-2
France 65000000 2583560 FR
Italy 59000000 1937894 IT
Malta 434000 12011 MT
Maldives 434000 4520 MV
Brunei 434000 12128 BN
To order by the largest values in column "population" and then "GDP",
we can specify multiple columns like in the next example.
>>> df.nlargest(3, ['population', 'GDP'])
population GDP alpha-2
France 65000000 2583560 FR
Italy 59000000 1937894 IT
Brunei 434000 12128 BN
"""
return algorithms.SelectNFrame(self, n=n, keep=keep, columns=columns).nlargest()
def nsmallest(self, n, columns, keep="first") -> DataFrame:
"""
Return the first `n` rows ordered by `columns` in ascending order.
Return the first `n` rows with the smallest values in `columns`, in
ascending order. The columns that are not specified are returned as
well, but not used for ordering.
This method is equivalent to
``df.sort_values(columns, ascending=True).head(n)``, but more
performant.
Parameters
----------
n : int
Number of items to retrieve.
columns : list or str
Column name or names to order by.
keep : {'first', 'last', 'all'}, default 'first'
Where there are duplicate values:
- ``first`` : take the first occurrence.
- ``last`` : take the last occurrence.
- ``all`` : do not drop any duplicates, even it means
selecting more than `n` items.
.. versionadded:: 0.24.0
Returns
-------
DataFrame
See Also
--------
DataFrame.nlargest : Return the first `n` rows ordered by `columns` in
descending order.
DataFrame.sort_values : Sort DataFrame by the values.
DataFrame.head : Return the first `n` rows without re-ordering.
Examples
--------
>>> df = pd.DataFrame({'population': [59000000, 65000000, 434000,
... 434000, 434000, 337000, 337000,
... 11300, 11300],
... 'GDP': [1937894, 2583560 , 12011, 4520, 12128,
... 17036, 182, 38, 311],
... 'alpha-2': ["IT", "FR", "MT", "MV", "BN",
... "IS", "NR", "TV", "AI"]},
... index=["Italy", "France", "Malta",
... "Maldives", "Brunei", "Iceland",
... "Nauru", "Tuvalu", "Anguilla"])
>>> df
population GDP alpha-2
Italy 59000000 1937894 IT
France 65000000 2583560 FR
Malta 434000 12011 MT
Maldives 434000 4520 MV
Brunei 434000 12128 BN
Iceland 337000 17036 IS
Nauru 337000 182 NR
Tuvalu 11300 38 TV
Anguilla 11300 311 AI
In the following example, we will use ``nsmallest`` to select the
three rows having the smallest values in column "population".
>>> df.nsmallest(3, 'population')
population GDP alpha-2
Tuvalu 11300 38 TV
Anguilla 11300 311 AI
Iceland 337000 17036 IS
When using ``keep='last'``, ties are resolved in reverse order:
>>> df.nsmallest(3, 'population', keep='last')
population GDP alpha-2
Anguilla 11300 311 AI
Tuvalu 11300 38 TV
Nauru 337000 182 NR
When using ``keep='all'``, all duplicate items are maintained:
>>> df.nsmallest(3, 'population', keep='all')
population GDP alpha-2
Tuvalu 11300 38 TV
Anguilla 11300 311 AI
Iceland 337000 17036 IS
Nauru 337000 182 NR
To order by the smallest values in column "population" and then "GDP", we can
specify multiple columns like in the next example.
>>> df.nsmallest(3, ['population', 'GDP'])
population GDP alpha-2
Tuvalu 11300 38 TV
Anguilla 11300 311 AI
Nauru 337000 182 NR
"""
return algorithms.SelectNFrame(
self, n=n, keep=keep, columns=columns
).nsmallest()
def swaplevel(self, i=-2, j=-1, axis=0) -> DataFrame:
"""
Swap levels i and j in a MultiIndex on a particular axis.
Parameters
----------
i, j : int or str
Levels of the indices to be swapped. Can pass level name as string.
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to swap levels on. 0 or 'index' for row-wise, 1 or
'columns' for column-wise.
Returns
-------
DataFrame
"""
result = self.copy()
axis = self._get_axis_number(axis)
if not isinstance(result._get_axis(axis), MultiIndex): # pragma: no cover
raise TypeError("Can only swap levels on a hierarchical axis.")
if axis == 0:
assert isinstance(result.index, MultiIndex)
result.index = result.index.swaplevel(i, j)
else:
assert isinstance(result.columns, MultiIndex)
result.columns = result.columns.swaplevel(i, j)
return result
def reorder_levels(self, order, axis=0) -> DataFrame:
"""
Rearrange index levels using input order. May not drop or duplicate levels.
Parameters
----------
order : list of int or list of str
List representing new level order. Reference level by number
(position) or by key (label).
axis : {0 or 'index', 1 or 'columns'}, default 0
Where to reorder levels.
Returns
-------
DataFrame
"""
axis = self._get_axis_number(axis)
if not isinstance(self._get_axis(axis), MultiIndex): # pragma: no cover
raise TypeError("Can only reorder levels on a hierarchical axis.")
result = self.copy()
if axis == 0:
assert isinstance(result.index, MultiIndex)
result.index = result.index.reorder_levels(order)
else:
assert isinstance(result.columns, MultiIndex)
result.columns = result.columns.reorder_levels(order)
return result
# ----------------------------------------------------------------------
# Arithmetic Methods
def _cmp_method(self, other, op):
axis = 1 # only relevant for Series other case
self, other = ops.align_method_FRAME(self, other, axis, flex=False, level=None)
# See GH#4537 for discussion of scalar op behavior
new_data = self._dispatch_frame_op(other, op, axis=axis)
return self._construct_result(new_data)
def _arith_method(self, other, op):
if ops.should_reindex_frame_op(self, other, op, 1, 1, None, None):
return ops.frame_arith_method_with_reindex(self, other, op)
axis = 1 # only relevant for Series other case
self, other = ops.align_method_FRAME(self, other, axis, flex=True, level=None)
new_data = self._dispatch_frame_op(other, op, axis=axis)
return self._construct_result(new_data)
_logical_method = _arith_method
def _dispatch_frame_op(self, right, func, axis: Optional[int] = None):
"""
Evaluate the frame operation func(left, right) by evaluating
column-by-column, dispatching to the Series implementation.
Parameters
----------
right : scalar, Series, or DataFrame
func : arithmetic or comparison operator
axis : {None, 0, 1}
Returns
-------
DataFrame
"""
# Get the appropriate array-op to apply to each column/block's values.
array_op = ops.get_array_op(func)
right = lib.item_from_zerodim(right)
if not is_list_like(right):
# i.e. scalar, faster than checking np.ndim(right) == 0
bm = self._mgr.apply(array_op, right=right)
return type(self)(bm)
elif isinstance(right, DataFrame):
assert self.index.equals(right.index)
assert self.columns.equals(right.columns)
# TODO: The previous assertion `assert right._indexed_same(self)`
# fails in cases with empty columns reached via
# _frame_arith_method_with_reindex
bm = self._mgr.operate_blockwise(right._mgr, array_op)
return type(self)(bm)
elif isinstance(right, Series) and axis == 1:
# axis=1 means we want to operate row-by-row
assert right.index.equals(self.columns)
right = right._values
# maybe_align_as_frame ensures we do not have an ndarray here
assert not isinstance(right, np.ndarray)
arrays = [
array_op(_left, _right)
for _left, _right in zip(self._iter_column_arrays(), right)
]
elif isinstance(right, Series):
assert right.index.equals(self.index) # Handle other cases later
right = right._values
arrays = [array_op(left, right) for left in self._iter_column_arrays()]
else:
# Remaining cases have less-obvious dispatch rules
raise NotImplementedError(right)
return type(self)._from_arrays(
arrays, self.columns, self.index, verify_integrity=False
)
def _combine_frame(self, other: DataFrame, func, fill_value=None):
# at this point we have `self._indexed_same(other)`
if fill_value is None:
# since _arith_op may be called in a loop, avoid function call
# overhead if possible by doing this check once
_arith_op = func
else:
def _arith_op(left, right):
# for the mixed_type case where we iterate over columns,
# _arith_op(left, right) is equivalent to
# left._binop(right, func, fill_value=fill_value)
left, right = ops.fill_binop(left, right, fill_value)
return func(left, right)
new_data = self._dispatch_frame_op(other, _arith_op)
return new_data
def _construct_result(self, result) -> DataFrame:
"""
Wrap the result of an arithmetic, comparison, or logical operation.
Parameters
----------
result : DataFrame
Returns
-------
DataFrame
"""
out = self._constructor(result, copy=False)
# Pin columns instead of passing to constructor for compat with
# non-unique columns case
out.columns = self.columns
out.index = self.index
return out
def __divmod__(self, other) -> Tuple[DataFrame, DataFrame]:
# Naive implementation, room for optimization
div = self // other
mod = self - div * other
return div, mod
def __rdivmod__(self, other) -> Tuple[DataFrame, DataFrame]:
# Naive implementation, room for optimization
div = other // self
mod = other - div * self
return div, mod
# ----------------------------------------------------------------------
# Combination-Related
@doc(
_shared_docs["compare"],
"""
Returns
-------
DataFrame
DataFrame that shows the differences stacked side by side.
The resulting index will be a MultiIndex with 'self' and 'other'
stacked alternately at the inner level.
Raises
------
ValueError
When the two DataFrames don't have identical labels or shape.
See Also
--------
Series.compare : Compare with another Series and show differences.
DataFrame.equals : Test whether two objects contain the same elements.
Notes
-----
Matching NaNs will not appear as a difference.
Can only compare identically-labeled
(i.e. same shape, identical row and column labels) DataFrames
Examples
--------
>>> df = pd.DataFrame(
... {{
... "col1": ["a", "a", "b", "b", "a"],
... "col2": [1.0, 2.0, 3.0, np.nan, 5.0],
... "col3": [1.0, 2.0, 3.0, 4.0, 5.0]
... }},
... columns=["col1", "col2", "col3"],
... )
>>> df
col1 col2 col3
0 a 1.0 1.0
1 a 2.0 2.0
2 b 3.0 3.0
3 b NaN 4.0
4 a 5.0 5.0
>>> df2 = df.copy()
>>> df2.loc[0, 'col1'] = 'c'
>>> df2.loc[2, 'col3'] = 4.0
>>> df2
col1 col2 col3
0 c 1.0 1.0
1 a 2.0 2.0
2 b 3.0 4.0
3 b NaN 4.0
4 a 5.0 5.0
Align the differences on columns
>>> df.compare(df2)
col1 col3
self other self other
0 a c NaN NaN
2 NaN NaN 3.0 4.0
Stack the differences on rows
>>> df.compare(df2, align_axis=0)
col1 col3
0 self a NaN
other c NaN
2 self NaN 3.0
other NaN 4.0
Keep the equal values
>>> df.compare(df2, keep_equal=True)
col1 col3
self other self other
0 a c 1.0 1.0
2 b b 3.0 4.0
Keep all original rows and columns
>>> df.compare(df2, keep_shape=True)
col1 col2 col3
self other self other self other
0 a c NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN 3.0 4.0
3 NaN NaN NaN NaN NaN NaN
4 NaN NaN NaN NaN NaN NaN
Keep all original rows and columns and also all original values
>>> df.compare(df2, keep_shape=True, keep_equal=True)
col1 col2 col3
self other self other self other
0 a c 1.0 1.0 1.0 1.0
1 a a 2.0 2.0 2.0 2.0
2 b b 3.0 3.0 3.0 4.0
3 b b NaN NaN 4.0 4.0
4 a a 5.0 5.0 5.0 5.0
""",
klass=_shared_doc_kwargs["klass"],
)
def compare(
self,
other: DataFrame,
align_axis: Axis = 1,
keep_shape: bool = False,
keep_equal: bool = False,
) -> DataFrame:
return super().compare(
other=other,
align_axis=align_axis,
keep_shape=keep_shape,
keep_equal=keep_equal,
)
def combine(
self, other: DataFrame, func, fill_value=None, overwrite=True
) -> DataFrame:
"""
Perform column-wise combine with another DataFrame.
Combines a DataFrame with `other` DataFrame using `func`
to element-wise combine columns. The row and column indexes of the
resulting DataFrame will be the union of the two.
Parameters
----------
other : DataFrame
The DataFrame to merge column-wise.
func : function
Function that takes two series as inputs and return a Series or a
scalar. Used to merge the two dataframes column by columns.
fill_value : scalar value, default None
The value to fill NaNs with prior to passing any column to the
merge func.
overwrite : bool, default True
If True, columns in `self` that do not exist in `other` will be
overwritten with NaNs.
Returns
-------
DataFrame
Combination of the provided DataFrames.
See Also
--------
DataFrame.combine_first : Combine two DataFrame objects and default to
non-null values in frame calling the method.
Examples
--------
Combine using a simple function that chooses the smaller column.
>>> df1 = pd.DataFrame({'A': [0, 0], 'B': [4, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
>>> take_smaller = lambda s1, s2: s1 if s1.sum() < s2.sum() else s2
>>> df1.combine(df2, take_smaller)
A B
0 0 3
1 0 3
Example using a true element-wise combine function.
>>> df1 = pd.DataFrame({'A': [5, 0], 'B': [2, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
>>> df1.combine(df2, np.minimum)
A B
0 1 2
1 0 3
Using `fill_value` fills Nones prior to passing the column to the
merge function.
>>> df1 = pd.DataFrame({'A': [0, 0], 'B': [None, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
>>> df1.combine(df2, take_smaller, fill_value=-5)
A B
0 0 -5.0
1 0 4.0
However, if the same element in both dataframes is None, that None
is preserved
>>> df1 = pd.DataFrame({'A': [0, 0], 'B': [None, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [None, 3]})
>>> df1.combine(df2, take_smaller, fill_value=-5)
A B
0 0 -5.0
1 0 3.0
Example that demonstrates the use of `overwrite` and behavior when
the axis differ between the dataframes.
>>> df1 = pd.DataFrame({'A': [0, 0], 'B': [4, 4]})
>>> df2 = pd.DataFrame({'B': [3, 3], 'C': [-10, 1], }, index=[1, 2])
>>> df1.combine(df2, take_smaller)
A B C
0 NaN NaN NaN
1 NaN 3.0 -10.0
2 NaN 3.0 1.0
>>> df1.combine(df2, take_smaller, overwrite=False)
A B C
0 0.0 NaN NaN
1 0.0 3.0 -10.0
2 NaN 3.0 1.0
Demonstrating the preference of the passed in dataframe.
>>> df2 = pd.DataFrame({'B': [3, 3], 'C': [1, 1], }, index=[1, 2])
>>> df2.combine(df1, take_smaller)
A B C
0 0.0 NaN NaN
1 0.0 3.0 NaN
2 NaN 3.0 NaN
>>> df2.combine(df1, take_smaller, overwrite=False)
A B C
0 0.0 NaN NaN
1 0.0 3.0 1.0
2 NaN 3.0 1.0
"""
other_idxlen = len(other.index) # save for compare
this, other = self.align(other, copy=False)
new_index = this.index
if other.empty and len(new_index) == len(self.index):
return self.copy()
if self.empty and len(other) == other_idxlen:
return other.copy()
# sorts if possible
new_columns = this.columns.union(other.columns)
do_fill = fill_value is not None
result = {}
for col in new_columns:
series = this[col]
otherSeries = other[col]
this_dtype = series.dtype
other_dtype = otherSeries.dtype
this_mask = isna(series)
other_mask = isna(otherSeries)
# don't overwrite columns unnecessarily
# DO propagate if this column is not in the intersection
if not overwrite and other_mask.all():
result[col] = this[col].copy()
continue
if do_fill:
series = series.copy()
otherSeries = otherSeries.copy()
series[this_mask] = fill_value
otherSeries[other_mask] = fill_value
if col not in self.columns:
# If self DataFrame does not have col in other DataFrame,
# try to promote series, which is all NaN, as other_dtype.
new_dtype = other_dtype
try:
series = series.astype(new_dtype, copy=False)
except ValueError:
# e.g. new_dtype is integer types
pass
else:
# if we have different dtypes, possibly promote
new_dtype = find_common_type([this_dtype, other_dtype])
if not is_dtype_equal(this_dtype, new_dtype):
series = series.astype(new_dtype)
if not is_dtype_equal(other_dtype, new_dtype):
otherSeries = otherSeries.astype(new_dtype)
arr = func(series, otherSeries)
arr = maybe_downcast_to_dtype(arr, new_dtype)
result[col] = arr
# convert_objects just in case
return self._constructor(result, index=new_index, columns=new_columns)
def combine_first(self, other: DataFrame) -> DataFrame:
"""
Update null elements with value in the same location in `other`.
Combine two DataFrame objects by filling null values in one DataFrame
with non-null values from other DataFrame. The row and column indexes
of the resulting DataFrame will be the union of the two.
Parameters
----------
other : DataFrame
Provided DataFrame to use to fill null values.
Returns
-------
DataFrame
See Also
--------
DataFrame.combine : Perform series-wise operation on two DataFrames
using a given function.
Examples
--------
>>> df1 = pd.DataFrame({'A': [None, 0], 'B': [None, 4]})
>>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]})
>>> df1.combine_first(df2)
A B
0 1.0 3.0
1 0.0 4.0
Null values still persist if the location of that null value
does not exist in `other`
>>> df1 = pd.DataFrame({'A': [None, 0], 'B': [4, None]})
>>> df2 = pd.DataFrame({'B': [3, 3], 'C': [1, 1]}, index=[1, 2])
>>> df1.combine_first(df2)
A B C
0 NaN 4.0 NaN
1 0.0 3.0 1.0
2 NaN 3.0 1.0
"""
import pandas.core.computation.expressions as expressions
def combiner(x, y):
mask = extract_array(isna(x))
x_values = extract_array(x, extract_numpy=True)
y_values = extract_array(y, extract_numpy=True)
# If the column y in other DataFrame is not in first DataFrame,
# just return y_values.
if y.name not in self.columns:
return y_values
return expressions.where(mask, y_values, x_values)
return self.combine(other, combiner, overwrite=False)
def update(
self, other, join="left", overwrite=True, filter_func=None, errors="ignore"
) -> None:
"""
Modify in place using non-NA values from another DataFrame.
Aligns on indices. There is no return value.
Parameters
----------
other : DataFrame, or object coercible into a DataFrame
Should have at least one matching index/column label
with the original DataFrame. If a Series is passed,
its name attribute must be set, and that will be
used as the column name to align with the original DataFrame.
join : {'left'}, default 'left'
Only left join is implemented, keeping the index and columns of the
original object.
overwrite : bool, default True
How to handle non-NA values for overlapping keys:
* True: overwrite original DataFrame's values
with values from `other`.
* False: only update values that are NA in
the original DataFrame.
filter_func : callable(1d-array) -> bool 1d-array, optional
Can choose to replace values other than NA. Return True for values
that should be updated.
errors : {'raise', 'ignore'}, default 'ignore'
If 'raise', will raise a ValueError if the DataFrame and `other`
both contain non-NA data in the same place.
.. versionchanged:: 0.24.0
Changed from `raise_conflict=False|True`
to `errors='ignore'|'raise'`.
Returns
-------
None : method directly changes calling object
Raises
------
ValueError
* When `errors='raise'` and there's overlapping non-NA data.
* When `errors` is not either `'ignore'` or `'raise'`
NotImplementedError
* If `join != 'left'`
See Also
--------
dict.update : Similar method for dictionaries.
DataFrame.merge : For column(s)-on-column(s) operations.
Examples
--------
>>> df = pd.DataFrame({'A': [1, 2, 3],
... 'B': [400, 500, 600]})
>>> new_df = pd.DataFrame({'B': [4, 5, 6],
... 'C': [7, 8, 9]})
>>> df.update(new_df)
>>> df
A B
0 1 4
1 2 5
2 3 6
The DataFrame's length does not increase as a result of the update,
only values at matching index/column labels are updated.
>>> df = pd.DataFrame({'A': ['a', 'b', 'c'],
... 'B': ['x', 'y', 'z']})
>>> new_df = pd.DataFrame({'B': ['d', 'e', 'f', 'g', 'h', 'i']})
>>> df.update(new_df)
>>> df
A B
0 a d
1 b e
2 c f
For Series, its name attribute must be set.
>>> df = pd.DataFrame({'A': ['a', 'b', 'c'],
... 'B': ['x', 'y', 'z']})
>>> new_column = pd.Series(['d', 'e'], name='B', index=[0, 2])
>>> df.update(new_column)
>>> df
A B
0 a d
1 b y
2 c e
>>> df = pd.DataFrame({'A': ['a', 'b', 'c'],
... 'B': ['x', 'y', 'z']})
>>> new_df = pd.DataFrame({'B': ['d', 'e']}, index=[1, 2])
>>> df.update(new_df)
>>> df
A B
0 a x
1 b d
2 c e
If `other` contains NaNs the corresponding values are not updated
in the original dataframe.
>>> df = pd.DataFrame({'A': [1, 2, 3],
... 'B': [400, 500, 600]})
>>> new_df = pd.DataFrame({'B': [4, np.nan, 6]})
>>> df.update(new_df)
>>> df
A B
0 1 4.0
1 2 500.0
2 3 6.0
"""
import pandas.core.computation.expressions as expressions
# TODO: Support other joins
if join != "left": # pragma: no cover
raise NotImplementedError("Only left join is supported")
if errors not in ["ignore", "raise"]:
raise ValueError("The parameter errors must be either 'ignore' or 'raise'")
if not isinstance(other, DataFrame):
other = DataFrame(other)
other = other.reindex_like(self)
for col in self.columns:
this = self[col]._values
that = other[col]._values
if filter_func is not None:
with np.errstate(all="ignore"):
mask = ~filter_func(this) | isna(that)
else:
if errors == "raise":
mask_this = notna(that)
mask_that = notna(this)
if any(mask_this & mask_that):
raise ValueError("Data overlaps.")
if overwrite:
mask = isna(that)
else:
mask = notna(this)
# don't overwrite columns unnecessarily
if mask.all():
continue
self[col] = expressions.where(mask, this, that)
# ----------------------------------------------------------------------
# Data reshaping
@Appender(
"""
Examples
--------
>>> df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',
... 'Parrot', 'Parrot'],
... 'Max Speed': [380., 370., 24., 26.]})
>>> df
Animal Max Speed
0 Falcon 380.0
1 Falcon 370.0
2 Parrot 24.0
3 Parrot 26.0
>>> df.groupby(['Animal']).mean()
Max Speed
Animal
Falcon 375.0
Parrot 25.0
**Hierarchical Indexes**
We can groupby different levels of a hierarchical index
using the `level` parameter:
>>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'],
... ['Captive', 'Wild', 'Captive', 'Wild']]
>>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type'))
>>> df = pd.DataFrame({'Max Speed': [390., 350., 30., 20.]},
... index=index)
>>> df
Max Speed
Animal Type
Falcon Captive 390.0
Wild 350.0
Parrot Captive 30.0
Wild 20.0
>>> df.groupby(level=0).mean()
Max Speed
Animal
Falcon 370.0
Parrot 25.0
>>> df.groupby(level="Type").mean()
Max Speed
Type
Captive 210.0
Wild 185.0
We can also choose to include NA in group keys or not by setting
`dropna` parameter, the default setting is `True`:
>>> l = [[1, 2, 3], [1, None, 4], [2, 1, 3], [1, 2, 2]]
>>> df = pd.DataFrame(l, columns=["a", "b", "c"])
>>> df.groupby(by=["b"]).sum()
a c
b
1.0 2 3
2.0 2 5
>>> df.groupby(by=["b"], dropna=False).sum()
a c
b
1.0 2 3
2.0 2 5
NaN 1 4
>>> l = [["a", 12, 12], [None, 12.3, 33.], ["b", 12.3, 123], ["a", 1, 1]]
>>> df = pd.DataFrame(l, columns=["a", "b", "c"])
>>> df.groupby(by="a").sum()
b c
a
a 13.0 13.0
b 12.3 123.0
>>> df.groupby(by="a", dropna=False).sum()
b c
a
a 13.0 13.0
b 12.3 123.0
NaN 12.3 33.0
"""
)
@Appender(_shared_docs["groupby"] % _shared_doc_kwargs)
def groupby(
self,
by=None,
axis=0,
level=None,
as_index: bool = True,
sort: bool = True,
group_keys: bool = True,
squeeze: bool = no_default,
observed: bool = False,
dropna: bool = True,
) -> DataFrameGroupBy:
from pandas.core.groupby.generic import DataFrameGroupBy
if squeeze is not no_default:
warnings.warn(
(
"The `squeeze` parameter is deprecated and "
"will be removed in a future version."
),
FutureWarning,
stacklevel=2,
)
else:
squeeze = False
if level is None and by is None:
raise TypeError("You have to supply one of 'by' and 'level'")
axis = self._get_axis_number(axis)
return DataFrameGroupBy(
obj=self,
keys=by,
axis=axis,
level=level,
as_index=as_index,
sort=sort,
group_keys=group_keys,
squeeze=squeeze,
observed=observed,
dropna=dropna,
)
_shared_docs[
"pivot"
] = """
Return reshaped DataFrame organized by given index / column values.
Reshape data (produce a "pivot" table) based on column values. Uses
unique values from specified `index` / `columns` to form axes of the
resulting DataFrame. This function does not support data
aggregation, multiple values will result in a MultiIndex in the
columns. See the :ref:`User Guide <reshaping>` for more on reshaping.
Parameters
----------%s
index : str or object or a list of str, optional
Column to use to make new frame's index. If None, uses
existing index.
.. versionchanged:: 1.1.0
Also accept list of index names.
columns : str or object or a list of str
Column to use to make new frame's columns.
.. versionchanged:: 1.1.0
Also accept list of columns names.
values : str, object or a list of the previous, optional
Column(s) to use for populating new frame's values. If not
specified, all remaining columns will be used and the result will
have hierarchically indexed columns.
Returns
-------
DataFrame
Returns reshaped DataFrame.
Raises
------
ValueError:
When there are any `index`, `columns` combinations with multiple
values. `DataFrame.pivot_table` when you need to aggregate.
See Also
--------
DataFrame.pivot_table : Generalization of pivot that can handle
duplicate values for one index/column pair.
DataFrame.unstack : Pivot based on the index values instead of a
column.
wide_to_long : Wide panel to long format. Less flexible but more
user-friendly than melt.
Notes
-----
For finer-tuned control, see hierarchical indexing documentation along
with the related stack/unstack methods.
Examples
--------
>>> df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two',
... 'two'],
... 'bar': ['A', 'B', 'C', 'A', 'B', 'C'],
... 'baz': [1, 2, 3, 4, 5, 6],
... 'zoo': ['x', 'y', 'z', 'q', 'w', 't']})
>>> df
foo bar baz zoo
0 one A 1 x
1 one B 2 y
2 one C 3 z
3 two A 4 q
4 two B 5 w
5 two C 6 t
>>> df.pivot(index='foo', columns='bar', values='baz')
bar A B C
foo
one 1 2 3
two 4 5 6
>>> df.pivot(index='foo', columns='bar')['baz']
bar A B C
foo
one 1 2 3
two 4 5 6
>>> df.pivot(index='foo', columns='bar', values=['baz', 'zoo'])
baz zoo
bar A B C A B C
foo
one 1 2 3 x y z
two 4 5 6 q w t
You could also assign a list of column names or a list of index names.
>>> df = pd.DataFrame({
... "lev1": [1, 1, 1, 2, 2, 2],
... "lev2": [1, 1, 2, 1, 1, 2],
... "lev3": [1, 2, 1, 2, 1, 2],
... "lev4": [1, 2, 3, 4, 5, 6],
... "values": [0, 1, 2, 3, 4, 5]})
>>> df
lev1 lev2 lev3 lev4 values
0 1 1 1 1 0
1 1 1 2 2 1
2 1 2 1 3 2
3 2 1 2 4 3
4 2 1 1 5 4
5 2 2 2 6 5
>>> df.pivot(index="lev1", columns=["lev2", "lev3"],values="values")
lev2 1 2
lev3 1 2 1 2
lev1
1 0.0 1.0 2.0 NaN
2 4.0 3.0 NaN 5.0
>>> df.pivot(index=["lev1", "lev2"], columns=["lev3"],values="values")
lev3 1 2
lev1 lev2
1 1 0.0 1.0
2 2.0 NaN
2 1 4.0 3.0
2 NaN 5.0
A ValueError is raised if there are any duplicates.
>>> df = pd.DataFrame({"foo": ['one', 'one', 'two', 'two'],
... "bar": ['A', 'A', 'B', 'C'],
... "baz": [1, 2, 3, 4]})
>>> df
foo bar baz
0 one A 1
1 one A 2
2 two B 3
3 two C 4
Notice that the first two rows are the same for our `index`
and `columns` arguments.
>>> df.pivot(index='foo', columns='bar', values='baz')
Traceback (most recent call last):
...
ValueError: Index contains duplicate entries, cannot reshape
"""
@Substitution("")
@Appender(_shared_docs["pivot"])
def pivot(self, index=None, columns=None, values=None) -> DataFrame:
from pandas.core.reshape.pivot import pivot
return pivot(self, index=index, columns=columns, values=values)
_shared_docs[
"pivot_table"
] = """
Create a spreadsheet-style pivot table as a DataFrame.
The levels in the pivot table will be stored in MultiIndex objects
(hierarchical indexes) on the index and columns of the result DataFrame.
Parameters
----------%s
values : column to aggregate, optional
index : column, Grouper, array, or list of the previous
If an array is passed, it must be the same length as the data. The
list can contain any of the other types (except list).
Keys to group by on the pivot table index. If an array is passed,
it is being used as the same manner as column values.
columns : column, Grouper, array, or list of the previous
If an array is passed, it must be the same length as the data. The
list can contain any of the other types (except list).
Keys to group by on the pivot table column. If an array is passed,
it is being used as the same manner as column values.
aggfunc : function, list of functions, dict, default numpy.mean
If list of functions passed, the resulting pivot table will have
hierarchical columns whose top level are the function names
(inferred from the function objects themselves)
If dict is passed, the key is column to aggregate and value
is function or list of functions.
fill_value : scalar, default None
Value to replace missing values with (in the resulting pivot table,
after aggregation).
margins : bool, default False
Add all row / columns (e.g. for subtotal / grand totals).
dropna : bool, default True
Do not include columns whose entries are all NaN.
margins_name : str, default 'All'
Name of the row / column that will contain the totals
when margins is True.
observed : bool, default False
This only applies if any of the groupers are Categoricals.
If True: only show observed values for categorical groupers.
If False: show all values for categorical groupers.
.. versionchanged:: 0.25.0
Returns
-------
DataFrame
An Excel style pivot table.
See Also
--------
DataFrame.pivot : Pivot without aggregation that can handle
non-numeric data.
DataFrame.melt: Unpivot a DataFrame from wide to long format,
optionally leaving identifiers set.
wide_to_long : Wide panel to long format. Less flexible but more
user-friendly than melt.
Examples
--------
>>> df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
... "bar", "bar", "bar", "bar"],
... "B": ["one", "one", "one", "two", "two",
... "one", "one", "two", "two"],
... "C": ["small", "large", "large", "small",
... "small", "large", "small", "small",
... "large"],
... "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
... "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
>>> df
A B C D E
0 foo one small 1 2
1 foo one large 2 4
2 foo one large 2 5
3 foo two small 3 5
4 foo two small 3 6
5 bar one large 4 6
6 bar one small 5 8
7 bar two small 6 9
8 bar two large 7 9
This first example aggregates values by taking the sum.
>>> table = pd.pivot_table(df, values='D', index=['A', 'B'],
... columns=['C'], aggfunc=np.sum)
>>> table
C large small
A B
bar one 4.0 5.0
two 7.0 6.0
foo one 4.0 1.0
two NaN 6.0
We can also fill missing values using the `fill_value` parameter.
>>> table = pd.pivot_table(df, values='D', index=['A', 'B'],
... columns=['C'], aggfunc=np.sum, fill_value=0)
>>> table
C large small
A B
bar one 4 5
two 7 6
foo one 4 1
two 0 6
The next example aggregates by taking the mean across multiple columns.
>>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],
... aggfunc={'D': np.mean,
... 'E': np.mean})
>>> table
D E
A C
bar large 5.500000 7.500000
small 5.500000 8.500000
foo large 2.000000 4.500000
small 2.333333 4.333333
We can also calculate multiple types of aggregations for any given
value column.
>>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],
... aggfunc={'D': np.mean,
... 'E': [min, max, np.mean]})
>>> table
D E
mean max mean min
A C
bar large 5.500000 9.0 7.500000 6.0
small 5.500000 9.0 8.500000 8.0
foo large 2.000000 5.0 4.500000 4.0
small 2.333333 6.0 4.333333 2.0
"""
@Substitution("")
@Appender(_shared_docs["pivot_table"])
def pivot_table(
self,
values=None,
index=None,
columns=None,
aggfunc="mean",
fill_value=None,
margins=False,
dropna=True,
margins_name="All",
observed=False,
) -> DataFrame:
from pandas.core.reshape.pivot import pivot_table
return pivot_table(
self,
values=values,
index=index,
columns=columns,
aggfunc=aggfunc,
fill_value=fill_value,
margins=margins,
dropna=dropna,
margins_name=margins_name,
observed=observed,
)
def stack(self, level=-1, dropna=True):
"""
Stack the prescribed level(s) from columns to index.
Return a reshaped DataFrame or Series having a multi-level
index with one or more new inner-most levels compared to the current
DataFrame. The new inner-most levels are created by pivoting the
columns of the current dataframe:
- if the columns have a single level, the output is a Series;
- if the columns have multiple levels, the new index
level(s) is (are) taken from the prescribed level(s) and
the output is a DataFrame.
Parameters
----------
level : int, str, list, default -1
Level(s) to stack from the column axis onto the index
axis, defined as one index or label, or a list of indices
or labels.
dropna : bool, default True
Whether to drop rows in the resulting Frame/Series with
missing values. Stacking a column level onto the index
axis can create combinations of index and column values
that are missing from the original dataframe. See Examples
section.
Returns
-------
DataFrame or Series
Stacked dataframe or series.
See Also
--------
DataFrame.unstack : Unstack prescribed level(s) from index axis
onto column axis.
DataFrame.pivot : Reshape dataframe from long format to wide
format.
DataFrame.pivot_table : Create a spreadsheet-style pivot table
as a DataFrame.
Notes
-----
The function is named by analogy with a collection of books
being reorganized from being side by side on a horizontal
position (the columns of the dataframe) to being stacked
vertically on top of each other (in the index of the
dataframe).
Examples
--------
**Single level columns**
>>> df_single_level_cols = pd.DataFrame([[0, 1], [2, 3]],
... index=['cat', 'dog'],
... columns=['weight', 'height'])
Stacking a dataframe with a single level column axis returns a Series:
>>> df_single_level_cols
weight height
cat 0 1
dog 2 3
>>> df_single_level_cols.stack()
cat weight 0
height 1
dog weight 2
height 3
dtype: int64
**Multi level columns: simple case**
>>> multicol1 = pd.MultiIndex.from_tuples([('weight', 'kg'),
... ('weight', 'pounds')])
>>> df_multi_level_cols1 = pd.DataFrame([[1, 2], [2, 4]],
... index=['cat', 'dog'],
... columns=multicol1)
Stacking a dataframe with a multi-level column axis:
>>> df_multi_level_cols1
weight
kg pounds
cat 1 2
dog 2 4
>>> df_multi_level_cols1.stack()
weight
cat kg 1
pounds 2
dog kg 2
pounds 4
**Missing values**
>>> multicol2 = pd.MultiIndex.from_tuples([('weight', 'kg'),
... ('height', 'm')])
>>> df_multi_level_cols2 = pd.DataFrame([[1.0, 2.0], [3.0, 4.0]],
... index=['cat', 'dog'],
... columns=multicol2)
It is common to have missing values when stacking a dataframe
with multi-level columns, as the stacked dataframe typically
has more values than the original dataframe. Missing values
are filled with NaNs:
>>> df_multi_level_cols2
weight height
kg m
cat 1.0 2.0
dog 3.0 4.0
>>> df_multi_level_cols2.stack()
height weight
cat kg NaN 1.0
m 2.0 NaN
dog kg NaN 3.0
m 4.0 NaN
**Prescribing the level(s) to be stacked**
The first parameter controls which level or levels are stacked:
>>> df_multi_level_cols2.stack(0)
kg m
cat height NaN 2.0
weight 1.0 NaN
dog height NaN 4.0
weight 3.0 NaN
>>> df_multi_level_cols2.stack([0, 1])
cat height m 2.0
weight kg 1.0
dog height m 4.0
weight kg 3.0
dtype: float64
**Dropping missing values**
>>> df_multi_level_cols3 = pd.DataFrame([[None, 1.0], [2.0, 3.0]],
... index=['cat', 'dog'],
... columns=multicol2)
Note that rows where all values are missing are dropped by
default but this behaviour can be controlled via the dropna
keyword parameter:
>>> df_multi_level_cols3
weight height
kg m
cat NaN 1.0
dog 2.0 3.0
>>> df_multi_level_cols3.stack(dropna=False)
height weight
cat kg NaN NaN
m 1.0 NaN
dog kg NaN 2.0
m 3.0 NaN
>>> df_multi_level_cols3.stack(dropna=True)
height weight
cat m 1.0 NaN
dog kg NaN 2.0
m 3.0 NaN
"""
from pandas.core.reshape.reshape import stack, stack_multiple
if isinstance(level, (tuple, list)):
result = stack_multiple(self, level, dropna=dropna)
else:
result = stack(self, level, dropna=dropna)
return result.__finalize__(self, method="stack")
def explode(
self, column: Union[str, Tuple], ignore_index: bool = False
) -> DataFrame:
"""
Transform each element of a list-like to a row, replicating index values.
.. versionadded:: 0.25.0
Parameters
----------
column : str or tuple
Column to explode.
ignore_index : bool, default False
If True, the resulting index will be labeled 0, 1, …, n - 1.
.. versionadded:: 1.1.0
Returns
-------
DataFrame
Exploded lists to rows of the subset columns;
index will be duplicated for these rows.
Raises
------
ValueError :
if columns of the frame are not unique.
See Also
--------
DataFrame.unstack : Pivot a level of the (necessarily hierarchical)
index labels.
DataFrame.melt : Unpivot a DataFrame from wide format to long format.
Series.explode : Explode a DataFrame from list-like columns to long format.
Notes
-----
This routine will explode list-likes including lists, tuples, sets,
Series, and np.ndarray. The result dtype of the subset rows will
be object. Scalars will be returned unchanged, and empty list-likes will
result in a np.nan for that row. In addition, the ordering of rows in the
output will be non-deterministic when exploding sets.
Examples
--------
>>> df = pd.DataFrame({'A': [[1, 2, 3], 'foo', [], [3, 4]], 'B': 1})
>>> df
A B
0 [1, 2, 3] 1
1 foo 1
2 [] 1
3 [3, 4] 1
>>> df.explode('A')
A B
0 1 1
0 2 1
0 3 1
1 foo 1
2 NaN 1
3 3 1
3 4 1
"""
if not (is_scalar(column) or isinstance(column, tuple)):
raise ValueError("column must be a scalar")
if not self.columns.is_unique:
raise ValueError("columns must be unique")
df = self.reset_index(drop=True)
result = df[column].explode()
result = df.drop([column], axis=1).join(result)
if ignore_index:
result.index = ibase.default_index(len(result))
else:
result.index = self.index.take(result.index)
result = result.reindex(columns=self.columns, copy=False)
return result
def unstack(self, level=-1, fill_value=None):
"""
Pivot a level of the (necessarily hierarchical) index labels.
Returns a DataFrame having a new level of column labels whose inner-most level
consists of the pivoted index labels.
If the index is not a MultiIndex, the output will be a Series
(the analogue of stack when the columns are not a MultiIndex).
Parameters
----------
level : int, str, or list of these, default -1 (last level)
Level(s) of index to unstack, can pass level name.
fill_value : int, str or dict
Replace NaN with this value if the unstack produces missing values.
Returns
-------
Series or DataFrame
See Also
--------
DataFrame.pivot : Pivot a table based on column values.
DataFrame.stack : Pivot a level of the column labels (inverse operation
from `unstack`).
Examples
--------
>>> index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'),
... ('two', 'a'), ('two', 'b')])
>>> s = pd.Series(np.arange(1.0, 5.0), index=index)
>>> s
one a 1.0
b 2.0
two a 3.0
b 4.0
dtype: float64
>>> s.unstack(level=-1)
a b
one 1.0 2.0
two 3.0 4.0
>>> s.unstack(level=0)
one two
a 1.0 3.0
b 2.0 4.0
>>> df = s.unstack(level=0)
>>> df.unstack()
one a 1.0
b 2.0
two a 3.0
b 4.0
dtype: float64
"""
from pandas.core.reshape.reshape import unstack
result = unstack(self, level, fill_value)
return result.__finalize__(self, method="unstack")
@Appender(_shared_docs["melt"] % {"caller": "df.melt(", "other": "melt"})
def melt(
self,
id_vars=None,
value_vars=None,
var_name=None,
value_name="value",
col_level=None,
ignore_index=True,
) -> DataFrame:
return melt(
self,
id_vars=id_vars,
value_vars=value_vars,
var_name=var_name,
value_name=value_name,
col_level=col_level,
ignore_index=ignore_index,
)
# ----------------------------------------------------------------------
# Time series-related
@doc(
Series.diff,
klass="Dataframe",
extra_params="axis : {0 or 'index', 1 or 'columns'}, default 0\n "
"Take difference over rows (0) or columns (1).\n",
other_klass="Series",
examples=dedent(
"""
Difference with previous row
>>> df = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6],
... 'b': [1, 1, 2, 3, 5, 8],
... 'c': [1, 4, 9, 16, 25, 36]})
>>> df
a b c
0 1 1 1
1 2 1 4
2 3 2 9
3 4 3 16
4 5 5 25
5 6 8 36
>>> df.diff()
a b c
0 NaN NaN NaN
1 1.0 0.0 3.0
2 1.0 1.0 5.0
3 1.0 1.0 7.0
4 1.0 2.0 9.0
5 1.0 3.0 11.0
Difference with previous column
>>> df.diff(axis=1)
a b c
0 NaN 0 0
1 NaN -1 3
2 NaN -1 7
3 NaN -1 13
4 NaN 0 20
5 NaN 2 28
Difference with 3rd previous row
>>> df.diff(periods=3)
a b c
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 3.0 2.0 15.0
4 3.0 4.0 21.0
5 3.0 6.0 27.0
Difference with following row
>>> df.diff(periods=-1)
a b c
0 -1.0 0.0 -3.0
1 -1.0 -1.0 -5.0
2 -1.0 -1.0 -7.0
3 -1.0 -2.0 -9.0
4 -1.0 -3.0 -11.0
5 NaN NaN NaN
Overflow in input dtype
>>> df = pd.DataFrame({'a': [1, 0]}, dtype=np.uint8)
>>> df.diff()
a
0 NaN
1 255.0"""
),
)
def diff(self, periods: int = 1, axis: Axis = 0) -> DataFrame:
if not isinstance(periods, int):
if not (is_float(periods) and periods.is_integer()):
raise ValueError("periods must be an integer")
periods = int(periods)
bm_axis = self._get_block_manager_axis(axis)
if bm_axis == 0 and periods != 0:
return self - self.shift(periods, axis=axis)
new_data = self._mgr.diff(n=periods, axis=bm_axis)
return self._constructor(new_data).__finalize__(self, "diff")
# ----------------------------------------------------------------------
# Function application
def _gotitem(
self,
key: Union[Label, List[Label]],
ndim: int,
subset: Optional[FrameOrSeriesUnion] = None,
) -> FrameOrSeriesUnion:
"""
Sub-classes to define. Return a sliced object.
Parameters
----------
key : string / list of selections
ndim : 1,2
requested ndim of result
subset : object, default None
subset to act on
"""
if subset is None:
subset = self
elif subset.ndim == 1: # is Series
return subset
# TODO: _shallow_copy(subset)?
return subset[key]
_agg_summary_and_see_also_doc = dedent(
"""
The aggregation operations are always performed over an axis, either the
index (default) or the column axis. This behavior is different from
`numpy` aggregation functions (`mean`, `median`, `prod`, `sum`, `std`,
`var`), where the default is to compute the aggregation of the flattened
array, e.g., ``numpy.mean(arr_2d)`` as opposed to
``numpy.mean(arr_2d, axis=0)``.
`agg` is an alias for `aggregate`. Use the alias.
See Also
--------
DataFrame.apply : Perform any type of operations.
DataFrame.transform : Perform transformation type operations.
core.groupby.GroupBy : Perform operations over groups.
core.resample.Resampler : Perform operations over resampled bins.
core.window.Rolling : Perform operations over rolling window.
core.window.Expanding : Perform operations over expanding window.
core.window.ExponentialMovingWindow : Perform operation over exponential weighted
window.
"""
)
_agg_examples_doc = dedent(
"""
Examples
--------
>>> df = pd.DataFrame([[1, 2, 3],
... [4, 5, 6],
... [7, 8, 9],
... [np.nan, np.nan, np.nan]],
... columns=['A', 'B', 'C'])
Aggregate these functions over the rows.
>>> df.agg(['sum', 'min'])
A B C
sum 12.0 15.0 18.0
min 1.0 2.0 3.0
Different aggregations per column.
>>> df.agg({'A' : ['sum', 'min'], 'B' : ['min', 'max']})
A B
sum 12.0 NaN
min 1.0 2.0
max NaN 8.0
Aggregate different functions over the columns and rename the index of the resulting
DataFrame.
>>> df.agg(x=('A', max), y=('B', 'min'), z=('C', np.mean))
A B C
x 7.0 NaN NaN
y NaN 2.0 NaN
z NaN NaN 6.0
Aggregate over the columns.
>>> df.agg("mean", axis="columns")
0 2.0
1 5.0
2 8.0
3 NaN
dtype: float64
"""
)
@doc(
_shared_docs["aggregate"],
klass=_shared_doc_kwargs["klass"],
axis=_shared_doc_kwargs["axis"],
see_also=_agg_summary_and_see_also_doc,
examples=_agg_examples_doc,
)
def aggregate(self, func=None, axis=0, *args, **kwargs):
axis = self._get_axis_number(axis)
relabeling, func, columns, order = reconstruct_func(func, **kwargs)
result = None
try:
result, how = self._aggregate(func, axis, *args, **kwargs)
except TypeError as err:
exc = TypeError(
"DataFrame constructor called with "
f"incompatible data and dtype: {err}"
)
raise exc from err
if result is None:
return self.apply(func, axis=axis, args=args, **kwargs)
if relabeling:
# This is to keep the order to columns occurrence unchanged, and also
# keep the order of new columns occurrence unchanged
# For the return values of reconstruct_func, if relabeling is
# False, columns and order will be None.
assert columns is not None
assert order is not None
result_in_dict = relabel_result(result, func, columns, order)
result = DataFrame(result_in_dict, index=columns)
return result
def _aggregate(self, arg, axis=0, *args, **kwargs):
if axis == 1:
# NDFrame.aggregate returns a tuple, and we need to transpose
# only result
result, how = aggregate(self.T, arg, *args, **kwargs)
result = result.T if result is not None else result
return result, how
return aggregate(self, arg, *args, **kwargs)
agg = aggregate
@doc(
_shared_docs["transform"],
klass=_shared_doc_kwargs["klass"],
axis=_shared_doc_kwargs["axis"],
)
def transform(
self, func: AggFuncType, axis: Axis = 0, *args, **kwargs
) -> DataFrame:
result = transform(self, func, axis, *args, **kwargs)
assert isinstance(result, DataFrame)
return result
def apply(self, func, axis=0, raw=False, result_type=None, args=(), **kwds):
"""
Apply a function along an axis of the DataFrame.
Objects passed to the function are Series objects whose index is
either the DataFrame's index (``axis=0``) or the DataFrame's columns
(``axis=1``). By default (``result_type=None``), the final return type
is inferred from the return type of the applied function. Otherwise,
it depends on the `result_type` argument.
Parameters
----------
func : function
Function to apply to each column or row.
axis : {0 or 'index', 1 or 'columns'}, default 0
Axis along which the function is applied:
* 0 or 'index': apply function to each column.
* 1 or 'columns': apply function to each row.
raw : bool, default False
Determines if row or column is passed as a Series or ndarray object:
* ``False`` : passes each row or column as a Series to the
function.
* ``True`` : the passed function will receive ndarray objects
instead.
If you are just applying a NumPy reduction function this will
achieve much better performance.
result_type : {'expand', 'reduce', 'broadcast', None}, default None
These only act when ``axis=1`` (columns):
* 'expand' : list-like results will be turned into columns.
* 'reduce' : returns a Series if possible rather than expanding
list-like results. This is the opposite of 'expand'.
* 'broadcast' : results will be broadcast to the original shape
of the DataFrame, the original index and columns will be
retained.
The default behaviour (None) depends on the return value of the
applied function: list-like results will be returned as a Series
of those. However if the apply function returns a Series these
are expanded to columns.
args : tuple
Positional arguments to pass to `func` in addition to the
array/series.
**kwds
Additional keyword arguments to pass as keywords arguments to
`func`.
Returns
-------
Series or DataFrame
Result of applying ``func`` along the given axis of the
DataFrame.
See Also
--------
DataFrame.applymap: For elementwise operations.
DataFrame.aggregate: Only perform aggregating type operations.
DataFrame.transform: Only perform transforming type operations.
Examples
--------
>>> df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B'])
>>> df
A B
0 4 9
1 4 9
2 4 9
Using a numpy universal function (in this case the same as
``np.sqrt(df)``):
>>> df.apply(np.sqrt)
A B
0 2.0 3.0
1 2.0 3.0
2 2.0 3.0
Using a reducing function on either axis
>>> df.apply(np.sum, axis=0)
A 12
B 27
dtype: int64
>>> df.apply(np.sum, axis=1)
0 13
1 13
2 13
dtype: int64
Returning a list-like will result in a Series
>>> df.apply(lambda x: [1, 2], axis=1)
0 [1, 2]
1 [1, 2]
2 [1, 2]
dtype: object
Passing ``result_type='expand'`` will expand list-like results
to columns of a Dataframe
>>> df.apply(lambda x: [1, 2], axis=1, result_type='expand')
0 1
0 1 2
1 1 2
2 1 2
Returning a Series inside the function is similar to passing
``result_type='expand'``. The resulting column names
will be the Series index.
>>> df.apply(lambda x: pd.Series([1, 2], index=['foo', 'bar']), axis=1)
foo bar
0 1 2
1 1 2
2 1 2
Passing ``result_type='broadcast'`` will ensure the same shape
result, whether list-like or scalar is returned by the function,
and broadcast it along the axis. The resulting column names will
be the originals.
>>> df.apply(lambda x: [1, 2], axis=1, result_type='broadcast')
A B
0 1 2
1 1 2
2 1 2
"""
from pandas.core.apply import frame_apply
op = frame_apply(
self,
func=func,
axis=axis,
raw=raw,
result_type=result_type,
args=args,
kwds=kwds,
)
return op.get_result()
def applymap(self, func, na_action: Optional[str] = None) -> DataFrame:
"""
Apply a function to a Dataframe elementwise.
This method applies a function that accepts and returns a scalar
to every element of a DataFrame.
Parameters
----------
func : callable
Python function, returns a single value from a single value.
na_action : {None, 'ignore'}, default None
If ‘ignore’, propagate NaN values, without passing them to func.
.. versionadded:: 1.2
Returns
-------
DataFrame
Transformed DataFrame.
See Also
--------
DataFrame.apply : Apply a function along input axis of DataFrame.
Examples
--------
>>> df = pd.DataFrame([[1, 2.12], [3.356, 4.567]])
>>> df
0 1
0 1.000 2.120
1 3.356 4.567
>>> df.applymap(lambda x: len(str(x)))
0 1
0 3 4
1 5 5
Like Series.map, NA values can be ignored:
>>> df_copy = df.copy()
>>> df_copy.iloc[0, 0] = pd.NA
>>> df_copy.applymap(lambda x: len(str(x)), na_action='ignore')
0 1
0 <NA> 4
1 5 5
Note that a vectorized version of `func` often exists, which will
be much faster. You could square each number elementwise.
>>> df.applymap(lambda x: x**2)
0 1
0 1.000000 4.494400
1 11.262736 20.857489
But it's better to avoid applymap in that case.
>>> df ** 2
0 1
0 1.000000 4.494400
1 11.262736 20.857489
"""
if na_action not in {"ignore", None}:
raise ValueError(
f"na_action must be 'ignore' or None. Got {repr(na_action)}"
)
ignore_na = na_action == "ignore"
# if we have a dtype == 'M8[ns]', provide boxed values
def infer(x):
if x.empty:
return lib.map_infer(x, func, ignore_na=ignore_na)
return lib.map_infer(x.astype(object)._values, func, ignore_na=ignore_na)
return self.apply(infer).__finalize__(self, "applymap")
# ----------------------------------------------------------------------
# Merging / joining methods
def append(
self, other, ignore_index=False, verify_integrity=False, sort=False
) -> DataFrame:
"""
Append rows of `other` to the end of caller, returning a new object.
Columns in `other` that are not in the caller are added as new columns.
Parameters
----------
other : DataFrame or Series/dict-like object, or list of these
The data to append.
ignore_index : bool, default False
If True, the resulting axis will be labeled 0, 1, …, n - 1.
verify_integrity : bool, default False
If True, raise ValueError on creating index with duplicates.
sort : bool, default False
Sort columns if the columns of `self` and `other` are not aligned.
.. versionchanged:: 1.0.0
Changed to not sort by default.
Returns
-------
DataFrame
See Also
--------
concat : General function to concatenate DataFrame or Series objects.
Notes
-----
If a list of dict/series is passed and the keys are all contained in
the DataFrame's index, the order of the columns in the resulting
DataFrame will be unchanged.
Iteratively appending rows to a DataFrame can be more computationally
intensive than a single concatenate. A better solution is to append
those rows to a list and then concatenate the list with the original
DataFrame all at once.
Examples
--------
>>> df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
>>> df
A B
0 1 2
1 3 4
>>> df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
>>> df.append(df2)
A B
0 1 2
1 3 4
0 5 6
1 7 8
With `ignore_index` set to True:
>>> df.append(df2, ignore_index=True)
A B
0 1 2
1 3 4
2 5 6
3 7 8
The following, while not recommended methods for generating DataFrames,
show two ways to generate a DataFrame from multiple data sources.
Less efficient:
>>> df = pd.DataFrame(columns=['A'])
>>> for i in range(5):
... df = df.append({'A': i}, ignore_index=True)
>>> df
A
0 0
1 1
2 2
3 3
4 4
More efficient:
>>> pd.concat([pd.DataFrame([i], columns=['A']) for i in range(5)],
... ignore_index=True)
A
0 0
1 1
2 2
3 3
4 4
"""
if isinstance(other, (Series, dict)):
if isinstance(other, dict):
if not ignore_index:
raise TypeError("Can only append a dict if ignore_index=True")
other = Series(other)
if other.name is None and not ignore_index:
raise TypeError(
"Can only append a Series if ignore_index=True "
"or if the Series has a name"
)
index = Index([other.name], name=self.index.name)
idx_diff = other.index.difference(self.columns)
try:
combined_columns = self.columns.append(idx_diff)
except TypeError:
combined_columns = self.columns.astype(object).append(idx_diff)
other = (
other.reindex(combined_columns, copy=False)
.to_frame()
.T.infer_objects()
.rename_axis(index.names, copy=False)
)
if not self.columns.equals(combined_columns):
self = self.reindex(columns=combined_columns)
elif isinstance(other, list):
if not other:
pass
elif not isinstance(other[0], DataFrame):
other = DataFrame(other)
if (self.columns.get_indexer(other.columns) >= 0).all():
other = other.reindex(columns=self.columns)
from pandas.core.reshape.concat import concat
if isinstance(other, (list, tuple)):
to_concat = [self, *other]
else:
to_concat = [self, other]
return (
concat(
to_concat,
ignore_index=ignore_index,
verify_integrity=verify_integrity,
sort=sort,
)
).__finalize__(self, method="append")
def join(
self, other, on=None, how="left", lsuffix="", rsuffix="", sort=False
) -> DataFrame:
"""
Join columns of another DataFrame.
Join columns with `other` DataFrame either on index or on a key
column. Efficiently join multiple DataFrame objects by index at once by
passing a list.
Parameters
----------
other : DataFrame, Series, or list of DataFrame
Index should be similar to one of the columns in this one. If a
Series is passed, its name attribute must be set, and that will be
used as the column name in the resulting joined DataFrame.
on : str, list of str, or array-like, optional
Column or index level name(s) in the caller to join on the index
in `other`, otherwise joins index-on-index. If multiple
values given, the `other` DataFrame must have a MultiIndex. Can
pass an array as the join key if it is not already contained in
the calling DataFrame. Like an Excel VLOOKUP operation.
how : {'left', 'right', 'outer', 'inner'}, default 'left'
How to handle the operation of the two objects.
* left: use calling frame's index (or column if on is specified)
* right: use `other`'s index.
* outer: form union of calling frame's index (or column if on is
specified) with `other`'s index, and sort it.
lexicographically.
* inner: form intersection of calling frame's index (or column if
on is specified) with `other`'s index, preserving the order
of the calling's one.
lsuffix : str, default ''
Suffix to use from left frame's overlapping columns.
rsuffix : str, default ''
Suffix to use from right frame's overlapping columns.
sort : bool, default False
Order result DataFrame lexicographically by the join key. If False,
the order of the join key depends on the join type (how keyword).
Returns
-------
DataFrame
A dataframe containing columns from both the caller and `other`.
See Also
--------
DataFrame.merge : For column(s)-on-column(s) operations.
Notes
-----
Parameters `on`, `lsuffix`, and `rsuffix` are not supported when
passing a list of `DataFrame` objects.
Support for specifying index levels as the `on` parameter was added
in version 0.23.0.
Examples
--------
>>> df = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'],
... 'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']})
>>> df
key A
0 K0 A0
1 K1 A1
2 K2 A2
3 K3 A3
4 K4 A4
5 K5 A5
>>> other = pd.DataFrame({'key': ['K0', 'K1', 'K2'],
... 'B': ['B0', 'B1', 'B2']})
>>> other
key B
0 K0 B0
1 K1 B1
2 K2 B2
Join DataFrames using their indexes.
>>> df.join(other, lsuffix='_caller', rsuffix='_other')
key_caller A key_other B
0 K0 A0 K0 B0
1 K1 A1 K1 B1
2 K2 A2 K2 B2
3 K3 A3 NaN NaN
4 K4 A4 NaN NaN
5 K5 A5 NaN NaN
If we want to join using the key columns, we need to set key to be
the index in both `df` and `other`. The joined DataFrame will have
key as its index.
>>> df.set_index('key').join(other.set_index('key'))
A B
key
K0 A0 B0
K1 A1 B1
K2 A2 B2
K3 A3 NaN
K4 A4 NaN
K5 A5 NaN
Another option to join using the key columns is to use the `on`
parameter. DataFrame.join always uses `other`'s index but we can use
any column in `df`. This method preserves the original DataFrame's
index in the result.
>>> df.join(other.set_index('key'), on='key')
key A B
0 K0 A0 B0
1 K1 A1 B1
2 K2 A2 B2
3 K3 A3 NaN
4 K4 A4 NaN
5 K5 A5 NaN
"""
return self._join_compat(
other, on=on, how=how, lsuffix=lsuffix, rsuffix=rsuffix, sort=sort
)
def _join_compat(
self, other, on=None, how="left", lsuffix="", rsuffix="", sort=False
):
from pandas.core.reshape.concat import concat
from pandas.core.reshape.merge import merge
if isinstance(other, Series):
if other.name is None:
raise ValueError("Other Series must have a name")
other = DataFrame({other.name: other})
if isinstance(other, DataFrame):
if how == "cross":
return merge(
self,
other,
how=how,
on=on,
suffixes=(lsuffix, rsuffix),
sort=sort,
)
return merge(
self,
other,
left_on=on,
how=how,
left_index=on is None,
right_index=True,
suffixes=(lsuffix, rsuffix),
sort=sort,
)
else:
if on is not None:
raise ValueError(
"Joining multiple DataFrames only supported for joining on index"
)
frames = [self] + list(other)
can_concat = all(df.index.is_unique for df in frames)
# join indexes only using concat
if can_concat:
if how == "left":
res = concat(
frames, axis=1, join="outer", verify_integrity=True, sort=sort
)
return res.reindex(self.index, copy=False)
else:
return concat(
frames, axis=1, join=how, verify_integrity=True, sort=sort
)
joined = frames[0]
for frame in frames[1:]:
joined = merge(
joined, frame, how=how, left_index=True, right_index=True
)
return joined
@Substitution("")
@Appender(_merge_doc, indents=2)
def merge(
self,
right,
how="inner",
on=None,
left_on=None,
right_on=None,
left_index=False,
right_index=False,
sort=False,
suffixes=("_x", "_y"),
copy=True,
indicator=False,
validate=None,
) -> DataFrame:
from pandas.core.reshape.merge import merge
return merge(
self,
right,
how=how,
on=on,
left_on=left_on,
right_on=right_on,
left_index=left_index,
right_index=right_index,
sort=sort,
suffixes=suffixes,
copy=copy,
indicator=indicator,
validate=validate,
)
def round(self, decimals=0, *args, **kwargs) -> DataFrame:
"""
Round a DataFrame to a variable number of decimal places.
Parameters
----------
decimals : int, dict, Series
Number of decimal places to round each column to. If an int is
given, round each column to the same number of places.
Otherwise dict and Series round to variable numbers of places.
Column names should be in the keys if `decimals` is a
dict-like, or in the index if `decimals` is a Series. Any
columns not included in `decimals` will be left as is. Elements
of `decimals` which are not columns of the input will be
ignored.
*args
Additional keywords have no effect but might be accepted for
compatibility with numpy.
**kwargs
Additional keywords have no effect but might be accepted for
compatibility with numpy.
Returns
-------
DataFrame
A DataFrame with the affected columns rounded to the specified
number of decimal places.
See Also
--------
numpy.around : Round a numpy array to the given number of decimals.
Series.round : Round a Series to the given number of decimals.
Examples
--------
>>> df = pd.DataFrame([(.21, .32), (.01, .67), (.66, .03), (.21, .18)],
... columns=['dogs', 'cats'])
>>> df
dogs cats
0 0.21 0.32
1 0.01 0.67
2 0.66 0.03
3 0.21 0.18
By providing an integer each column is rounded to the same number
of decimal places
>>> df.round(1)
dogs cats
0 0.2 0.3
1 0.0 0.7
2 0.7 0.0
3 0.2 0.2
With a dict, the number of places for specific columns can be
specified with the column names as key and the number of decimal
places as value
>>> df.round({'dogs': 1, 'cats': 0})
dogs cats
0 0.2 0.0
1 0.0 1.0
2 0.7 0.0
3 0.2 0.0
Using a Series, the number of places for specific columns can be
specified with the column names as index and the number of
decimal places as value
>>> decimals = pd.Series([0, 1], index=['cats', 'dogs'])
>>> df.round(decimals)
dogs cats
0 0.2 0.0
1 0.0 1.0
2 0.7 0.0
3 0.2 0.0
"""
from pandas.core.reshape.concat import concat
def _dict_round(df, decimals):
for col, vals in df.items():
try:
yield _series_round(vals, decimals[col])
except KeyError:
yield vals
def _series_round(s, decimals):
if is_integer_dtype(s) or is_float_dtype(s):
return s.round(decimals)
return s
nv.validate_round(args, kwargs)
if isinstance(decimals, (dict, Series)):
if isinstance(decimals, Series):
if not decimals.index.is_unique:
raise ValueError("Index of decimals must be unique")
new_cols = list(_dict_round(self, decimals))
elif is_integer(decimals):
# Dispatch to Series.round
new_cols = [_series_round(v, decimals) for _, v in self.items()]
else:
raise TypeError("decimals must be an integer, a dict-like or a Series")
if len(new_cols) > 0:
return self._constructor(
concat(new_cols, axis=1), index=self.index, columns=self.columns
)
else:
return self
# ----------------------------------------------------------------------
# Statistical methods, etc.
def corr(self, method="pearson", min_periods=1) -> DataFrame:
"""
Compute pairwise correlation of columns, excluding NA/null values.
Parameters
----------
method : {'pearson', 'kendall', 'spearman'} or callable
Method of correlation:
* pearson : standard correlation coefficient
* kendall : Kendall Tau correlation coefficient
* spearman : Spearman rank correlation
* callable: callable with input two 1d ndarrays
and returning a float. Note that the returned matrix from corr
will have 1 along the diagonals and will be symmetric
regardless of the callable's behavior.
.. versionadded:: 0.24.0
min_periods : int, optional
Minimum number of observations required per pair of columns
to have a valid result. Currently only available for Pearson
and Spearman correlation.
Returns
-------
DataFrame
Correlation matrix.
See Also
--------
DataFrame.corrwith : Compute pairwise correlation with another
DataFrame or Series.
Series.corr : Compute the correlation between two Series.
Examples
--------
>>> def histogram_intersection(a, b):
... v = np.minimum(a, b).sum().round(decimals=1)
... return v
>>> df = pd.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)],
... columns=['dogs', 'cats'])
>>> df.corr(method=histogram_intersection)
dogs cats
dogs 1.0 0.3
cats 0.3 1.0
"""
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.to_numpy(dtype=float, na_value=np.nan, copy=False)
if method == "pearson":
correl = libalgos.nancorr(mat, minp=min_periods)
elif method == "spearman":
correl = libalgos.nancorr_spearman(mat, minp=min_periods)
elif method == "kendall" or callable(method):
if min_periods is None:
min_periods = 1
mat = mat.T
corrf = nanops.get_corr_func(method)
K = len(cols)
correl = np.empty((K, K), dtype=float)
mask = np.isfinite(mat)
for i, ac in enumerate(mat):
for j, bc in enumerate(mat):
if i > j:
continue
valid = mask[i] & mask[j]
if valid.sum() < min_periods:
c = np.nan
elif i == j:
c = 1.0
elif not valid.all():
c = corrf(ac[valid], bc[valid])
else:
c = corrf(ac, bc)
correl[i, j] = c
correl[j, i] = c
else:
raise ValueError(
"method must be either 'pearson', "
"'spearman', 'kendall', or a callable, "
f"'{method}' was supplied"
)
return self._constructor(correl, index=idx, columns=cols)
def cov(
self, min_periods: Optional[int] = None, ddof: Optional[int] = 1
) -> DataFrame:
"""
Compute pairwise covariance of columns, excluding NA/null values.
Compute the pairwise covariance among the series of a DataFrame.
The returned data frame is the `covariance matrix
<https://en.wikipedia.org/wiki/Covariance_matrix>`__ of the columns
of the DataFrame.
Both NA and null values are automatically excluded from the
calculation. (See the note below about bias from missing values.)
A threshold can be set for the minimum number of
observations for each value created. Comparisons with observations
below this threshold will be returned as ``NaN``.
This method is generally used for the analysis of time series data to
understand the relationship between different measures
across time.
Parameters
----------
min_periods : int, optional
Minimum number of observations required per pair of columns
to have a valid result.
ddof : int, default 1
Delta degrees of freedom. The divisor used in calculations
is ``N - ddof``, where ``N`` represents the number of elements.
.. versionadded:: 1.1.0
Returns
-------
DataFrame
The covariance matrix of the series of the DataFrame.
See Also
--------
Series.cov : Compute covariance with another Series.
core.window.ExponentialMovingWindow.cov: Exponential weighted sample covariance.
core.window.Expanding.cov : Expanding sample covariance.
core.window.Rolling.cov : Rolling sample covariance.
Notes
-----
Returns the covariance matrix of the DataFrame's time series.
The covariance is normalized by N-ddof.
For DataFrames that have Series that are missing data (assuming that
data is `missing at random
<https://en.wikipedia.org/wiki/Missing_data#Missing_at_random>`__)
the returned covariance matrix will be an unbiased estimate
of the variance and covariance between the member Series.
However, for many applications this estimate may not be acceptable
because the estimate covariance matrix is not guaranteed to be positive
semi-definite. This could lead to estimate correlations having
absolute values which are greater than one, and/or a non-invertible
covariance matrix. See `Estimation of covariance matrices
<https://en.wikipedia.org/w/index.php?title=Estimation_of_covariance_
matrices>`__ for more details.
Examples
--------
>>> df = pd.DataFrame([(1, 2), (0, 3), (2, 0), (1, 1)],
... columns=['dogs', 'cats'])
>>> df.cov()
dogs cats
dogs 0.666667 -1.000000
cats -1.000000 1.666667
>>> np.random.seed(42)
>>> df = pd.DataFrame(np.random.randn(1000, 5),
... columns=['a', 'b', 'c', 'd', 'e'])
>>> df.cov()
a b c d e
a 0.998438 -0.020161 0.059277 -0.008943 0.014144
b -0.020161 1.059352 -0.008543 -0.024738 0.009826
c 0.059277 -0.008543 1.010670 -0.001486 -0.000271
d -0.008943 -0.024738 -0.001486 0.921297 -0.013692
e 0.014144 0.009826 -0.000271 -0.013692 0.977795
**Minimum number of periods**
This method also supports an optional ``min_periods`` keyword
that specifies the required minimum number of non-NA observations for
each column pair in order to have a valid result:
>>> np.random.seed(42)
>>> df = pd.DataFrame(np.random.randn(20, 3),
... columns=['a', 'b', 'c'])
>>> df.loc[df.index[:5], 'a'] = np.nan
>>> df.loc[df.index[5:10], 'b'] = np.nan
>>> df.cov(min_periods=12)
a b c
a 0.316741 NaN -0.150812
b NaN 1.248003 0.191417
c -0.150812 0.191417 0.895202
"""
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.to_numpy(dtype=float, na_value=np.nan, copy=False)
if notna(mat).all():
if min_periods is not None and min_periods > len(mat):
base_cov = np.empty((mat.shape[1], mat.shape[1]))
base_cov.fill(np.nan)
else:
base_cov = np.cov(mat.T, ddof=ddof)
base_cov = base_cov.reshape((len(cols), len(cols)))
else:
base_cov = libalgos.nancorr(mat, cov=True, minp=min_periods)
return self._constructor(base_cov, index=idx, columns=cols)
def corrwith(self, other, axis=0, drop=False, method="pearson") -> Series:
"""
Compute pairwise correlation.
Pairwise correlation is computed between rows or columns of
DataFrame with rows or columns of Series or DataFrame. DataFrames
are first aligned along both axes before computing the
correlations.
Parameters
----------
other : DataFrame, Series
Object with which to compute correlations.
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to use. 0 or 'index' to compute column-wise, 1 or 'columns' for
row-wise.
drop : bool, default False
Drop missing indices from result.
method : {'pearson', 'kendall', 'spearman'} or callable
Method of correlation:
* pearson : standard correlation coefficient
* kendall : Kendall Tau correlation coefficient
* spearman : Spearman rank correlation
* callable: callable with input two 1d ndarrays
and returning a float.
.. versionadded:: 0.24.0
Returns
-------
Series
Pairwise correlations.
See Also
--------
DataFrame.corr : Compute pairwise correlation of columns.
"""
axis = self._get_axis_number(axis)
this = self._get_numeric_data()
if isinstance(other, Series):
return this.apply(lambda x: other.corr(x, method=method), axis=axis)
other = other._get_numeric_data()
left, right = this.align(other, join="inner", copy=False)
if axis == 1:
left = left.T
right = right.T
if method == "pearson":
# mask missing values
left = left + right * 0
right = right + left * 0
# demeaned data
ldem = left - left.mean()
rdem = right - right.mean()
num = (ldem * rdem).sum()
dom = (left.count() - 1) * left.std() * right.std()
correl = num / dom
elif method in ["kendall", "spearman"] or callable(method):
def c(x):
return nanops.nancorr(x[0], x[1], method=method)
correl = self._constructor_sliced(
map(c, zip(left.values.T, right.values.T)), index=left.columns
)
else:
raise ValueError(
f"Invalid method {method} was passed, "
"valid methods are: 'pearson', 'kendall', "
"'spearman', or callable"
)
if not drop:
# Find non-matching labels along the given axis
# and append missing correlations (GH 22375)
raxis = 1 if axis == 0 else 0
result_index = this._get_axis(raxis).union(other._get_axis(raxis))
idx_diff = result_index.difference(correl.index)
if len(idx_diff) > 0:
correl = correl.append(Series([np.nan] * len(idx_diff), index=idx_diff))
return correl
# ----------------------------------------------------------------------
# ndarray-like stats methods
def count(self, axis=0, level=None, numeric_only=False):
"""
Count non-NA cells for each column or row.
The values `None`, `NaN`, `NaT`, and optionally `numpy.inf` (depending
on `pandas.options.mode.use_inf_as_na`) are considered NA.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
If 0 or 'index' counts are generated for each column.
If 1 or 'columns' counts are generated for each row.
level : int or str, optional
If the axis is a `MultiIndex` (hierarchical), count along a
particular `level`, collapsing into a `DataFrame`.
A `str` specifies the level name.
numeric_only : bool, default False
Include only `float`, `int` or `boolean` data.
Returns
-------
Series or DataFrame
For each column/row the number of non-NA/null entries.
If `level` is specified returns a `DataFrame`.
See Also
--------
Series.count: Number of non-NA elements in a Series.
DataFrame.value_counts: Count unique combinations of columns.
DataFrame.shape: Number of DataFrame rows and columns (including NA
elements).
DataFrame.isna: Boolean same-sized DataFrame showing places of NA
elements.
Examples
--------
Constructing DataFrame from a dictionary:
>>> df = pd.DataFrame({"Person":
... ["John", "Myla", "Lewis", "John", "Myla"],
... "Age": [24., np.nan, 21., 33, 26],
... "Single": [False, True, True, True, False]})
>>> df
Person Age Single
0 John 24.0 False
1 Myla NaN True
2 Lewis 21.0 True
3 John 33.0 True
4 Myla 26.0 False
Notice the uncounted NA values:
>>> df.count()
Person 5
Age 4
Single 5
dtype: int64
Counts for each **row**:
>>> df.count(axis='columns')
0 3
1 2
2 3
3 3
4 3
dtype: int64
Counts for one level of a `MultiIndex`:
>>> df.set_index(["Person", "Single"]).count(level="Person")
Age
Person
John 2
Lewis 1
Myla 1
"""
axis = self._get_axis_number(axis)
if level is not None:
return self._count_level(level, axis=axis, numeric_only=numeric_only)
if numeric_only:
frame = self._get_numeric_data()
else:
frame = self
# GH #423
if len(frame._get_axis(axis)) == 0:
result = self._constructor_sliced(0, index=frame._get_agg_axis(axis))
else:
if frame._is_mixed_type or frame._mgr.any_extension_types:
# the or any_extension_types is really only hit for single-
# column frames with an extension array
result = notna(frame).sum(axis=axis)
else:
# GH13407
series_counts = notna(frame).sum(axis=axis)
counts = series_counts.values
result = self._constructor_sliced(
counts, index=frame._get_agg_axis(axis)
)
return result.astype("int64")
def _count_level(self, level, axis=0, numeric_only=False):
if numeric_only:
frame = self._get_numeric_data()
else:
frame = self
count_axis = frame._get_axis(axis)
agg_axis = frame._get_agg_axis(axis)
if not isinstance(count_axis, MultiIndex):
raise TypeError(
f"Can only count levels on hierarchical {self._get_axis_name(axis)}."
)
# Mask NaNs: Mask rows or columns where the index level is NaN, and all
# values in the DataFrame that are NaN
if frame._is_mixed_type:
# Since we have mixed types, calling notna(frame.values) might
# upcast everything to object
values_mask = notna(frame).values
else:
# But use the speedup when we have homogeneous dtypes
values_mask = notna(frame.values)
index_mask = notna(count_axis.get_level_values(level=level))
if axis == 1:
mask = index_mask & values_mask
else:
mask = index_mask.reshape(-1, 1) & values_mask
if isinstance(level, str):
level = count_axis._get_level_number(level)
level_name = count_axis._names[level]
level_index = count_axis.levels[level]._shallow_copy(name=level_name)
level_codes = ensure_int64(count_axis.codes[level])
counts = lib.count_level_2d(mask, level_codes, len(level_index), axis=axis)
if axis == 1:
result = self._constructor(counts, index=agg_axis, columns=level_index)
else:
result = self._constructor(counts, index=level_index, columns=agg_axis)
return result
def _reduce(
self,
op,
name: str,
*,
axis=0,
skipna=True,
numeric_only=None,
filter_type=None,
**kwds,
):
assert filter_type is None or filter_type == "bool", filter_type
out_dtype = "bool" if filter_type == "bool" else None
own_dtypes = [arr.dtype for arr in self._iter_column_arrays()]
dtype_is_dt = np.array(
[is_datetime64_any_dtype(dtype) for dtype in own_dtypes],
dtype=bool,
)
if numeric_only is None and name in ["mean", "median"] and dtype_is_dt.any():
warnings.warn(
"DataFrame.mean and DataFrame.median with numeric_only=None "
"will include datetime64 and datetime64tz columns in a "
"future version.",
FutureWarning,
stacklevel=5,
)
cols = self.columns[~dtype_is_dt]
self = self[cols]
# TODO: Make other agg func handle axis=None properly GH#21597
axis = self._get_axis_number(axis)
labels = self._get_agg_axis(axis)
assert axis in [0, 1]
def func(values):
if is_extension_array_dtype(values.dtype):
return extract_array(values)._reduce(name, skipna=skipna, **kwds)
else:
return op(values, axis=axis, skipna=skipna, **kwds)
def blk_func(values):
if isinstance(values, ExtensionArray):
return values._reduce(name, skipna=skipna, **kwds)
else:
return op(values, axis=1, skipna=skipna, **kwds)
def _get_data() -> DataFrame:
if filter_type is None:
data = self._get_numeric_data()
else:
# GH#25101, GH#24434
assert filter_type == "bool"
data = self._get_bool_data()
return data
if numeric_only is not None or axis == 0:
# For numeric_only non-None and axis non-None, we know
# which blocks to use and no try/except is needed.
# For numeric_only=None only the case with axis==0 and no object
# dtypes are unambiguous can be handled with BlockManager.reduce
# Case with EAs see GH#35881
df = self
if numeric_only is True:
df = _get_data()
if axis == 1:
df = df.T
axis = 0
ignore_failures = numeric_only is None
# After possibly _get_data and transposing, we are now in the
# simple case where we can use BlockManager.reduce
res, indexer = df._mgr.reduce(blk_func, ignore_failures=ignore_failures)
out = df._constructor(res).iloc[0]
if out_dtype is not None:
out = out.astype(out_dtype)
if axis == 0 and is_object_dtype(out.dtype):
# GH#35865 careful to cast explicitly to object
nvs = coerce_to_dtypes(out.values, df.dtypes.iloc[np.sort(indexer)])
out[:] = np.array(nvs, dtype=object)
if axis == 0 and len(self) == 0 and name in ["sum", "prod"]:
# Even if we are object dtype, follow numpy and return
# float64, see test_apply_funcs_over_empty
out = out.astype(np.float64)
return out
assert numeric_only is None
data = self
values = data.values
try:
result = func(values)
except TypeError:
# e.g. in nanops trying to convert strs to float
data = _get_data()
labels = data._get_agg_axis(axis)
values = data.values
with np.errstate(all="ignore"):
result = func(values)
if filter_type == "bool" and notna(result).all():
result = result.astype(np.bool_)
elif filter_type is None and is_object_dtype(result.dtype):
try:
result = result.astype(np.float64)
except (ValueError, TypeError):
# try to coerce to the original dtypes item by item if we can
if axis == 0:
result = coerce_to_dtypes(result, data.dtypes)
result = self._constructor_sliced(result, index=labels)
return result
def nunique(self, axis=0, dropna=True) -> Series:
"""
Count distinct observations over requested axis.
Return Series with number of distinct observations. Can ignore NaN
values.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for
column-wise.
dropna : bool, default True
Don't include NaN in the counts.
Returns
-------
Series
See Also
--------
Series.nunique: Method nunique for Series.
DataFrame.count: Count non-NA cells for each column or row.
Examples
--------
>>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [1, 1, 1]})
>>> df.nunique()
A 3
B 1
dtype: int64
>>> df.nunique(axis=1)
0 1
1 2
2 2
dtype: int64
"""
return self.apply(Series.nunique, axis=axis, dropna=dropna)
def idxmin(self, axis=0, skipna=True) -> Series:
"""
Return index of first occurrence of minimum over requested axis.
NA/null values are excluded.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for column-wise.
skipna : bool, default True
Exclude NA/null values. If an entire row/column is NA, the result
will be NA.
Returns
-------
Series
Indexes of minima along the specified axis.
Raises
------
ValueError
* If the row/column is empty
See Also
--------
Series.idxmin : Return index of the minimum element.
Notes
-----
This method is the DataFrame version of ``ndarray.argmin``.
Examples
--------
Consider a dataset containing food consumption in Argentina.
>>> df = pd.DataFrame({'consumption': [10.51, 103.11, 55.48],
... 'co2_emissions': [37.2, 19.66, 1712]},
... index=['Pork', 'Wheat Products', 'Beef'])
>>> df
consumption co2_emissions
Pork 10.51 37.20
Wheat Products 103.11 19.66
Beef 55.48 1712.00
By default, it returns the index for the minimum value in each column.
>>> df.idxmin()
consumption Pork
co2_emissions Wheat Products
dtype: object
To return the index for the minimum value in each row, use ``axis="columns"``.
>>> df.idxmin(axis="columns")
Pork consumption
Wheat Products co2_emissions
Beef consumption
dtype: object
"""
axis = self._get_axis_number(axis)
res = self._reduce(
nanops.nanargmin, "argmin", axis=axis, skipna=skipna, numeric_only=False
)
indices = res._values
# indices will always be np.ndarray since axis is not None and
# values is a 2d array for DataFrame
# error: Item "int" of "Union[int, Any]" has no attribute "__iter__"
assert isinstance(indices, np.ndarray) # for mypy
index = self._get_axis(axis)
result = [index[i] if i >= 0 else np.nan for i in indices]
return self._constructor_sliced(result, index=self._get_agg_axis(axis))
def idxmax(self, axis=0, skipna=True) -> Series:
"""
Return index of first occurrence of maximum over requested axis.
NA/null values are excluded.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for column-wise.
skipna : bool, default True
Exclude NA/null values. If an entire row/column is NA, the result
will be NA.
Returns
-------
Series
Indexes of maxima along the specified axis.
Raises
------
ValueError
* If the row/column is empty
See Also
--------
Series.idxmax : Return index of the maximum element.
Notes
-----
This method is the DataFrame version of ``ndarray.argmax``.
Examples
--------
Consider a dataset containing food consumption in Argentina.
>>> df = pd.DataFrame({'consumption': [10.51, 103.11, 55.48],
... 'co2_emissions': [37.2, 19.66, 1712]},
... index=['Pork', 'Wheat Products', 'Beef'])
>>> df
consumption co2_emissions
Pork 10.51 37.20
Wheat Products 103.11 19.66
Beef 55.48 1712.00
By default, it returns the index for the maximum value in each column.
>>> df.idxmax()
consumption Wheat Products
co2_emissions Beef
dtype: object
To return the index for the maximum value in each row, use ``axis="columns"``.
>>> df.idxmax(axis="columns")
Pork co2_emissions
Wheat Products consumption
Beef co2_emissions
dtype: object
"""
axis = self._get_axis_number(axis)
res = self._reduce(
nanops.nanargmax, "argmax", axis=axis, skipna=skipna, numeric_only=False
)
indices = res._values
# indices will always be np.ndarray since axis is not None and
# values is a 2d array for DataFrame
# error: Item "int" of "Union[int, Any]" has no attribute "__iter__"
assert isinstance(indices, np.ndarray) # for mypy
index = self._get_axis(axis)
result = [index[i] if i >= 0 else np.nan for i in indices]
return self._constructor_sliced(result, index=self._get_agg_axis(axis))
def _get_agg_axis(self, axis_num: int) -> Index:
"""
Let's be explicit about this.
"""
if axis_num == 0:
return self.columns
elif axis_num == 1:
return self.index
else:
raise ValueError(f"Axis must be 0 or 1 (got {repr(axis_num)})")
def mode(self, axis=0, numeric_only=False, dropna=True) -> DataFrame:
"""
Get the mode(s) of each element along the selected axis.
The mode of a set of values is the value that appears most often.
It can be multiple values.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to iterate over while searching for the mode:
* 0 or 'index' : get mode of each column
* 1 or 'columns' : get mode of each row.
numeric_only : bool, default False
If True, only apply to numeric columns.
dropna : bool, default True
Don't consider counts of NaN/NaT.
.. versionadded:: 0.24.0
Returns
-------
DataFrame
The modes of each column or row.
See Also
--------
Series.mode : Return the highest frequency value in a Series.
Series.value_counts : Return the counts of values in a Series.
Examples
--------
>>> df = pd.DataFrame([('bird', 2, 2),
... ('mammal', 4, np.nan),
... ('arthropod', 8, 0),
... ('bird', 2, np.nan)],
... index=('falcon', 'horse', 'spider', 'ostrich'),
... columns=('species', 'legs', 'wings'))
>>> df
species legs wings
falcon bird 2 2.0
horse mammal 4 NaN
spider arthropod 8 0.0
ostrich bird 2 NaN
By default, missing values are not considered, and the mode of wings
are both 0 and 2. Because the resulting DataFrame has two rows,
the second row of ``species`` and ``legs`` contains ``NaN``.
>>> df.mode()
species legs wings
0 bird 2.0 0.0
1 NaN NaN 2.0
Setting ``dropna=False`` ``NaN`` values are considered and they can be
the mode (like for wings).
>>> df.mode(dropna=False)
species legs wings
0 bird 2 NaN
Setting ``numeric_only=True``, only the mode of numeric columns is
computed, and columns of other types are ignored.
>>> df.mode(numeric_only=True)
legs wings
0 2.0 0.0
1 NaN 2.0
To compute the mode over columns and not rows, use the axis parameter:
>>> df.mode(axis='columns', numeric_only=True)
0 1
falcon 2.0 NaN
horse 4.0 NaN
spider 0.0 8.0
ostrich 2.0 NaN
"""
data = self if not numeric_only else self._get_numeric_data()
def f(s):
return s.mode(dropna=dropna)
return data.apply(f, axis=axis)
def quantile(self, q=0.5, axis=0, numeric_only=True, interpolation="linear"):
"""
Return values at the given quantile over requested axis.
Parameters
----------
q : float or array-like, default 0.5 (50% quantile)
Value between 0 <= q <= 1, the quantile(s) to compute.
axis : {0, 1, 'index', 'columns'}, default 0
Equals 0 or 'index' for row-wise, 1 or 'columns' for column-wise.
numeric_only : bool, default True
If False, the quantile of datetime and timedelta data will be
computed as well.
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
This optional parameter specifies the interpolation method to use,
when the desired quantile lies between two data points `i` and `j`:
* linear: `i + (j - i) * fraction`, where `fraction` is the
fractional part of the index surrounded by `i` and `j`.
* lower: `i`.
* higher: `j`.
* nearest: `i` or `j` whichever is nearest.
* midpoint: (`i` + `j`) / 2.
Returns
-------
Series or DataFrame
If ``q`` is an array, a DataFrame will be returned where the
index is ``q``, the columns are the columns of self, and the
values are the quantiles.
If ``q`` is a float, a Series will be returned where the
index is the columns of self and the values are the quantiles.
See Also
--------
core.window.Rolling.quantile: Rolling quantile.
numpy.percentile: Numpy function to compute the percentile.
Examples
--------
>>> df = pd.DataFrame(np.array([[1, 1], [2, 10], [3, 100], [4, 100]]),
... columns=['a', 'b'])
>>> df.quantile(.1)
a 1.3
b 3.7
Name: 0.1, dtype: float64
>>> df.quantile([.1, .5])
a b
0.1 1.3 3.7
0.5 2.5 55.0
Specifying `numeric_only=False` will also compute the quantile of
datetime and timedelta data.
>>> df = pd.DataFrame({'A': [1, 2],
... 'B': [pd.Timestamp('2010'),
... pd.Timestamp('2011')],
... 'C': [pd.Timedelta('1 days'),
... pd.Timedelta('2 days')]})
>>> df.quantile(0.5, numeric_only=False)
A 1.5
B 2010-07-02 12:00:00
C 1 days 12:00:00
Name: 0.5, dtype: object
"""
validate_percentile(q)
data = self._get_numeric_data() if numeric_only else self
axis = self._get_axis_number(axis)
is_transposed = axis == 1
if is_transposed:
data = data.T
if len(data.columns) == 0:
# GH#23925 _get_numeric_data may have dropped all columns
cols = Index([], name=self.columns.name)
if is_list_like(q):
return self._constructor([], index=q, columns=cols)
return self._constructor_sliced([], index=cols, name=q, dtype=np.float64)
result = data._mgr.quantile(
qs=q, axis=1, interpolation=interpolation, transposed=is_transposed
)
if result.ndim == 2:
result = self._constructor(result)
else:
result = self._constructor_sliced(result, name=q)
if is_transposed:
result = result.T
return result
def to_timestamp(
self, freq=None, how: str = "start", axis: Axis = 0, copy: bool = True
) -> DataFrame:
"""
Cast to DatetimeIndex of timestamps, at *beginning* of period.
Parameters
----------
freq : str, default frequency of PeriodIndex
Desired frequency.
how : {'s', 'e', 'start', 'end'}
Convention for converting period to timestamp; start of period
vs. end.
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to convert (the index by default).
copy : bool, default True
If False then underlying input data is not copied.
Returns
-------
DataFrame with DatetimeIndex
"""
new_obj = self.copy(deep=copy)
axis_name = self._get_axis_name(axis)
old_ax = getattr(self, axis_name)
if not isinstance(old_ax, PeriodIndex):
raise TypeError(f"unsupported Type {type(old_ax).__name__}")
new_ax = old_ax.to_timestamp(freq=freq, how=how)
setattr(new_obj, axis_name, new_ax)
return new_obj
def to_period(self, freq=None, axis: Axis = 0, copy: bool = True) -> DataFrame:
"""
Convert DataFrame from DatetimeIndex to PeriodIndex.
Convert DataFrame from DatetimeIndex to PeriodIndex with desired
frequency (inferred from index if not passed).
Parameters
----------
freq : str, default
Frequency of the PeriodIndex.
axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to convert (the index by default).
copy : bool, default True
If False then underlying input data is not copied.
Returns
-------
DataFrame with PeriodIndex
"""
new_obj = self.copy(deep=copy)
axis_name = self._get_axis_name(axis)
old_ax = getattr(self, axis_name)
if not isinstance(old_ax, DatetimeIndex):
raise TypeError(f"unsupported Type {type(old_ax).__name__}")
new_ax = old_ax.to_period(freq=freq)
setattr(new_obj, axis_name, new_ax)
return new_obj
def isin(self, values) -> DataFrame:
"""
Whether each element in the DataFrame is contained in values.
Parameters
----------
values : iterable, Series, DataFrame or dict
The result will only be true at a location if all the
labels match. If `values` is a Series, that's the index. If
`values` is a dict, the keys must be the column names,
which must match. If `values` is a DataFrame,
then both the index and column labels must match.
Returns
-------
DataFrame
DataFrame of booleans showing whether each element in the DataFrame
is contained in values.
See Also
--------
DataFrame.eq: Equality test for DataFrame.
Series.isin: Equivalent method on Series.
Series.str.contains: Test if pattern or regex is contained within a
string of a Series or Index.
Examples
--------
>>> df = pd.DataFrame({'num_legs': [2, 4], 'num_wings': [2, 0]},
... index=['falcon', 'dog'])
>>> df
num_legs num_wings
falcon 2 2
dog 4 0
When ``values`` is a list check whether every value in the DataFrame
is present in the list (which animals have 0 or 2 legs or wings)
>>> df.isin([0, 2])
num_legs num_wings
falcon True True
dog False True
When ``values`` is a dict, we can pass values to check for each
column separately:
>>> df.isin({'num_wings': [0, 3]})
num_legs num_wings
falcon False False
dog False True
When ``values`` is a Series or DataFrame the index and column must
match. Note that 'falcon' does not match based on the number of legs
in df2.
>>> other = pd.DataFrame({'num_legs': [8, 2], 'num_wings': [0, 2]},
... index=['spider', 'falcon'])
>>> df.isin(other)
num_legs num_wings
falcon True True
dog False False
"""
if isinstance(values, dict):
from pandas.core.reshape.concat import concat
values = collections.defaultdict(list, values)
return concat(
(
self.iloc[:, [i]].isin(values[col])
for i, col in enumerate(self.columns)
),
axis=1,
)
elif isinstance(values, Series):
if not values.index.is_unique:
raise ValueError("cannot compute isin with a duplicate axis.")
return self.eq(values.reindex_like(self), axis="index")
elif isinstance(values, DataFrame):
if not (values.columns.is_unique and values.index.is_unique):
raise ValueError("cannot compute isin with a duplicate axis.")
return self.eq(values.reindex_like(self))
else:
if not is_list_like(values):
raise TypeError(
"only list-like or dict-like objects are allowed "
"to be passed to DataFrame.isin(), "
f"you passed a '{type(values).__name__}'"
)
return self._constructor(
algorithms.isin(self.values.ravel(), values).reshape(self.shape),
self.index,
self.columns,
)
# ----------------------------------------------------------------------
# Add index and columns
_AXIS_ORDERS = ["index", "columns"]
_AXIS_TO_AXIS_NUMBER: Dict[Axis, int] = {
**NDFrame._AXIS_TO_AXIS_NUMBER,
1: 1,
"columns": 1,
}
_AXIS_REVERSED = True
_AXIS_LEN = len(_AXIS_ORDERS)
_info_axis_number = 1
_info_axis_name = "columns"
index: Index = properties.AxisProperty(
axis=1, doc="The index (row labels) of the DataFrame."
)
columns: Index = properties.AxisProperty(
axis=0, doc="The column labels of the DataFrame."
)
@property
def _AXIS_NUMBERS(self) -> Dict[str, int]:
""".. deprecated:: 1.1.0"""
super()._AXIS_NUMBERS
return {"index": 0, "columns": 1}
@property
def _AXIS_NAMES(self) -> Dict[int, str]:
""".. deprecated:: 1.1.0"""
super()._AXIS_NAMES
return {0: "index", 1: "columns"}
# ----------------------------------------------------------------------
# Add plotting methods to DataFrame
plot = CachedAccessor("plot", pandas.plotting.PlotAccessor)
hist = pandas.plotting.hist_frame
boxplot = pandas.plotting.boxplot_frame
sparse = CachedAccessor("sparse", SparseFrameAccessor)
DataFrame._add_numeric_operations()
ops.add_flex_arithmetic_methods(DataFrame)
def _from_nested_dict(data) -> collections.defaultdict:
new_data: collections.defaultdict = collections.defaultdict(dict)
for index, s in data.items():
for col, v in s.items():
new_data[col][index] = v
return new_data
| 34.371501 | 170 | 0.531602 | from __future__ import annotations
import collections
from collections import abc
import datetime
from io import StringIO
import itertools
import mmap
from textwrap import dedent
from typing import (
IO,
TYPE_CHECKING,
Any,
AnyStr,
Dict,
FrozenSet,
Hashable,
Iterable,
Iterator,
List,
Optional,
Sequence,
Set,
Tuple,
Type,
Union,
cast,
overload,
)
import warnings
import numpy as np
import numpy.ma as ma
from pandas._config import get_option
from pandas._libs import algos as libalgos, lib, properties
from pandas._libs.lib import no_default
from pandas._typing import (
AggFuncType,
ArrayLike,
Axes,
Axis,
CompressionOptions,
Dtype,
FilePathOrBuffer,
FrameOrSeriesUnion,
IndexKeyFunc,
Label,
Level,
Renamer,
StorageOptions,
ValueKeyFunc,
)
from pandas.compat._optional import import_optional_dependency
from pandas.compat.numpy import function as nv
from pandas.util._decorators import (
Appender,
Substitution,
deprecate_kwarg,
doc,
rewrite_axis_style_signature,
)
from pandas.util._validators import (
validate_axis_style_args,
validate_bool_kwarg,
validate_percentile,
)
from pandas.core.dtypes.cast import (
cast_scalar_to_array,
coerce_to_dtypes,
construct_1d_arraylike_from_scalar,
find_common_type,
infer_dtype_from_scalar,
invalidate_string_dtypes,
maybe_box_datetimelike,
maybe_cast_to_datetime,
maybe_casted_values,
maybe_convert_platform,
maybe_downcast_to_dtype,
maybe_infer_to_datetimelike,
maybe_upcast,
validate_numeric_casting,
)
from pandas.core.dtypes.common import (
ensure_int64,
ensure_platform_int,
infer_dtype_from_object,
is_bool_dtype,
is_dataclass,
is_datetime64_any_dtype,
is_dict_like,
is_dtype_equal,
is_extension_array_dtype,
is_float,
is_float_dtype,
is_hashable,
is_integer,
is_integer_dtype,
is_iterator,
is_list_like,
is_named_tuple,
is_object_dtype,
is_scalar,
is_sequence,
pandas_dtype,
)
from pandas.core.dtypes.missing import isna, notna
from pandas.core import algorithms, common as com, generic, nanops, ops
from pandas.core.accessor import CachedAccessor
from pandas.core.aggregation import (
aggregate,
reconstruct_func,
relabel_result,
transform,
)
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays import Categorical, ExtensionArray
from pandas.core.arrays.sparse import SparseFrameAccessor
from pandas.core.construction import extract_array
from pandas.core.generic import NDFrame, _shared_docs
from pandas.core.indexes import base as ibase
from pandas.core.indexes.api import (
DatetimeIndex,
Index,
PeriodIndex,
ensure_index,
ensure_index_from_sequences,
)
from pandas.core.indexes.multi import MultiIndex, maybe_droplevels
from pandas.core.indexing import check_bool_indexer, convert_to_index_sliceable
from pandas.core.internals import BlockManager
from pandas.core.internals.construction import (
arrays_to_mgr,
dataclasses_to_dicts,
get_names_from_index,
init_dict,
init_ndarray,
masked_rec_array_to_mgr,
reorder_arrays,
sanitize_index,
to_arrays,
)
from pandas.core.reshape.melt import melt
from pandas.core.series import Series
from pandas.core.sorting import get_group_index, lexsort_indexer, nargsort
from pandas.io.common import get_handle
from pandas.io.formats import console, format as fmt
from pandas.io.formats.info import BaseInfo, DataFrameInfo
import pandas.plotting
if TYPE_CHECKING:
from typing import Literal
from pandas.core.groupby.generic import DataFrameGroupBy
from pandas.io.formats.style import Styler
_shared_doc_kwargs = {
"axes": "index, columns",
"klass": "DataFrame",
"axes_single_arg": "{0 or 'index', 1 or 'columns'}",
"axis": """axis : {0 or 'index', 1 or 'columns'}, default 0
If 0 or 'index': apply function to each column.
If 1 or 'columns': apply function to each row.""",
"optional_by": """
by : str or list of str
Name or list of names to sort by.
- if `axis` is 0 or `'index'` then `by` may contain index
levels and/or column labels.
- if `axis` is 1 or `'columns'` then `by` may contain column
levels and/or index labels.""",
"optional_labels": """labels : array-like, optional
New labels / index to conform the axis specified by 'axis' to.""",
"optional_axis": """axis : int or str, optional
Axis to target. Can be either the axis name ('index', 'columns')
or number (0, 1).""",
}
_numeric_only_doc = """numeric_only : boolean, default None
Include only float, int, boolean data. If None, will attempt to use
everything, then use only numeric data
"""
_merge_doc = """
Merge DataFrame or named Series objects with a database-style join.
The join is done on columns or indexes. If joining columns on
columns, the DataFrame indexes *will be ignored*. Otherwise if joining indexes
on indexes or indexes on a column or columns, the index will be passed on.
When performing a cross merge, no column specifications to merge on are
allowed.
Parameters
----------%s
right : DataFrame or named Series
Object to merge with.
how : {'left', 'right', 'outer', 'inner', 'cross'}, default 'inner'
Type of merge to be performed.
* left: use only keys from left frame, similar to a SQL left outer join;
preserve key order.
* right: use only keys from right frame, similar to a SQL right outer join;
preserve key order.
* outer: use union of keys from both frames, similar to a SQL full outer
join; sort keys lexicographically.
* inner: use intersection of keys from both frames, similar to a SQL inner
join; preserve the order of the left keys.
* cross: creates the cartesian product from both frames, preserves the order
of the left keys.
.. versionadded:: 1.2.0
on : label or list
Column or index level names to join on. These must be found in both
DataFrames. If `on` is None and not merging on indexes then this defaults
to the intersection of the columns in both DataFrames.
left_on : label or list, or array-like
Column or index level names to join on in the left DataFrame. Can also
be an array or list of arrays of the length of the left DataFrame.
These arrays are treated as if they are columns.
right_on : label or list, or array-like
Column or index level names to join on in the right DataFrame. Can also
be an array or list of arrays of the length of the right DataFrame.
These arrays are treated as if they are columns.
left_index : bool, default False
Use the index from the left DataFrame as the join key(s). If it is a
MultiIndex, the number of keys in the other DataFrame (either the index
or a number of columns) must match the number of levels.
right_index : bool, default False
Use the index from the right DataFrame as the join key. Same caveats as
left_index.
sort : bool, default False
Sort the join keys lexicographically in the result DataFrame. If False,
the order of the join keys depends on the join type (how keyword).
suffixes : list-like, default is ("_x", "_y")
A length-2 sequence where each element is optionally a string
indicating the suffix to add to overlapping column names in
`left` and `right` respectively. Pass a value of `None` instead
of a string to indicate that the column name from `left` or
`right` should be left as-is, with no suffix. At least one of the
values must not be None.
copy : bool, default True
If False, avoid copy if possible.
indicator : bool or str, default False
If True, adds a column to the output DataFrame called "_merge" with
information on the source of each row. The column can be given a different
name by providing a string argument. The column will have a Categorical
type with the value of "left_only" for observations whose merge key only
appears in the left DataFrame, "right_only" for observations
whose merge key only appears in the right DataFrame, and "both"
if the observation's merge key is found in both DataFrames.
validate : str, optional
If specified, checks if merge is of specified type.
* "one_to_one" or "1:1": check if merge keys are unique in both
left and right datasets.
* "one_to_many" or "1:m": check if merge keys are unique in left
dataset.
* "many_to_one" or "m:1": check if merge keys are unique in right
dataset.
* "many_to_many" or "m:m": allowed, but does not result in checks.
Returns
-------
DataFrame
A DataFrame of the two merged objects.
See Also
--------
merge_ordered : Merge with optional filling/interpolation.
merge_asof : Merge on nearest keys.
DataFrame.join : Similar method using indices.
Notes
-----
Support for specifying index levels as the `on`, `left_on`, and
`right_on` parameters was added in version 0.23.0
Support for merging named Series objects was added in version 0.24.0
Examples
--------
>>> df1 = pd.DataFrame({'lkey': ['foo', 'bar', 'baz', 'foo'],
... 'value': [1, 2, 3, 5]})
>>> df2 = pd.DataFrame({'rkey': ['foo', 'bar', 'baz', 'foo'],
... 'value': [5, 6, 7, 8]})
>>> df1
lkey value
0 foo 1
1 bar 2
2 baz 3
3 foo 5
>>> df2
rkey value
0 foo 5
1 bar 6
2 baz 7
3 foo 8
Merge df1 and df2 on the lkey and rkey columns. The value columns have
the default suffixes, _x and _y, appended.
>>> df1.merge(df2, left_on='lkey', right_on='rkey')
lkey value_x rkey value_y
0 foo 1 foo 5
1 foo 1 foo 8
2 foo 5 foo 5
3 foo 5 foo 8
4 bar 2 bar 6
5 baz 3 baz 7
Merge DataFrames df1 and df2 with specified left and right suffixes
appended to any overlapping columns.
>>> df1.merge(df2, left_on='lkey', right_on='rkey',
... suffixes=('_left', '_right'))
lkey value_left rkey value_right
0 foo 1 foo 5
1 foo 1 foo 8
2 foo 5 foo 5
3 foo 5 foo 8
4 bar 2 bar 6
5 baz 3 baz 7
Merge DataFrames df1 and df2, but raise an exception if the DataFrames have
any overlapping columns.
>>> df1.merge(df2, left_on='lkey', right_on='rkey', suffixes=(False, False))
Traceback (most recent call last):
...
ValueError: columns overlap but no suffix specified:
Index(['value'], dtype='object')
>>> df1 = pd.DataFrame({'a': ['foo', 'bar'], 'b': [1, 2]})
>>> df2 = pd.DataFrame({'a': ['foo', 'baz'], 'c': [3, 4]})
>>> df1
a b
0 foo 1
1 bar 2
>>> df2
a c
0 foo 3
1 baz 4
>>> df1.merge(df2, how='inner', on='a')
a b c
0 foo 1 3
>>> df1.merge(df2, how='left', on='a')
a b c
0 foo 1 3.0
1 bar 2 NaN
>>> df1 = pd.DataFrame({'left': ['foo', 'bar']})
>>> df2 = pd.DataFrame({'right': [7, 8]})
>>> df1
left
0 foo
1 bar
>>> df2
right
0 7
1 8
>>> df1.merge(df2, how='cross')
left right
0 foo 7
1 foo 8
2 bar 7
3 bar 8
"""
# -----------------------------------------------------------------------
# DataFrame class
class DataFrame(NDFrame, OpsMixin):
_internal_names_set = {"columns", "index"} | NDFrame._internal_names_set
_typ = "dataframe"
_HANDLED_TYPES = (Series, Index, ExtensionArray, np.ndarray)
@property
def _constructor(self) -> Type[DataFrame]:
return DataFrame
_constructor_sliced: Type[Series] = Series
_hidden_attrs: FrozenSet[str] = NDFrame._hidden_attrs | frozenset([])
_accessors: Set[str] = {"sparse"}
@property
def _constructor_expanddim(self):
# GH#31549 raising NotImplementedError on a property causes trouble
# for `inspect`
def constructor(*args, **kwargs):
raise NotImplementedError("Not supported for DataFrames!")
return constructor
# ----------------------------------------------------------------------
# Constructors
def __init__(
self,
data=None,
index: Optional[Axes] = None,
columns: Optional[Axes] = None,
dtype: Optional[Dtype] = None,
copy: bool = False,
):
if data is None:
data = {}
if dtype is not None:
dtype = self._validate_dtype(dtype)
if isinstance(data, DataFrame):
data = data._mgr
if isinstance(data, BlockManager):
if index is None and columns is None and dtype is None and copy is False:
# GH#33357 fastpath
NDFrame.__init__(self, data)
return
mgr = self._init_mgr(
data, axes={"index": index, "columns": columns}, dtype=dtype, copy=copy
)
elif isinstance(data, dict):
mgr = init_dict(data, index, columns, dtype=dtype)
elif isinstance(data, ma.MaskedArray):
import numpy.ma.mrecords as mrecords
# masked recarray
if isinstance(data, mrecords.MaskedRecords):
mgr = masked_rec_array_to_mgr(data, index, columns, dtype, copy)
# a masked array
else:
mask = ma.getmaskarray(data)
if mask.any():
data, fill_value = maybe_upcast(data, copy=True)
data.soften_mask() # set hardmask False if it was True
data[mask] = fill_value
else:
data = data.copy()
mgr = init_ndarray(data, index, columns, dtype=dtype, copy=copy)
elif isinstance(data, (np.ndarray, Series, Index)):
if data.dtype.names:
data_columns = list(data.dtype.names)
data = {k: data[k] for k in data_columns}
if columns is None:
columns = data_columns
mgr = init_dict(data, index, columns, dtype=dtype)
elif getattr(data, "name", None) is not None:
mgr = init_dict({data.name: data}, index, columns, dtype=dtype)
else:
mgr = init_ndarray(data, index, columns, dtype=dtype, copy=copy)
# For data is list-like, or Iterable (will consume into list)
elif isinstance(data, abc.Iterable) and not isinstance(data, (str, bytes)):
if not isinstance(data, (abc.Sequence, ExtensionArray)):
data = list(data)
if len(data) > 0:
if is_dataclass(data[0]):
data = dataclasses_to_dicts(data)
if is_list_like(data[0]) and getattr(data[0], "ndim", 1) == 1:
if is_named_tuple(data[0]) and columns is None:
columns = data[0]._fields
arrays, columns = to_arrays(data, columns, dtype=dtype)
columns = ensure_index(columns)
# set the index
if index is None:
if isinstance(data[0], Series):
index = get_names_from_index(data)
elif isinstance(data[0], Categorical):
index = ibase.default_index(len(data[0]))
else:
index = ibase.default_index(len(data))
mgr = arrays_to_mgr(arrays, columns, index, columns, dtype=dtype)
else:
mgr = init_ndarray(data, index, columns, dtype=dtype, copy=copy)
else:
mgr = init_dict({}, index, columns, dtype=dtype)
# For data is scalar
else:
if index is None or columns is None:
raise ValueError("DataFrame constructor not properly called!")
if not dtype:
dtype, _ = infer_dtype_from_scalar(data, pandas_dtype=True)
# For data is a scalar extension dtype
if is_extension_array_dtype(dtype):
values = [
construct_1d_arraylike_from_scalar(data, len(index), dtype)
for _ in range(len(columns))
]
mgr = arrays_to_mgr(values, columns, index, columns, dtype=None)
else:
# Attempt to coerce to a numpy array
try:
arr = np.array(data, dtype=dtype, copy=copy)
except (ValueError, TypeError) as err:
exc = TypeError(
"DataFrame constructor called with "
f"incompatible data and dtype: {err}"
)
raise exc from err
if arr.ndim != 0:
raise ValueError("DataFrame constructor not properly called!")
values = cast_scalar_to_array(
(len(index), len(columns)), data, dtype=dtype
)
mgr = init_ndarray(
values, index, columns, dtype=values.dtype, copy=False
)
NDFrame.__init__(self, mgr)
# ----------------------------------------------------------------------
@property
def axes(self) -> List[Index]:
return [self.index, self.columns]
@property
def shape(self) -> Tuple[int, int]:
return len(self.index), len(self.columns)
@property
def _is_homogeneous_type(self) -> bool:
if self._mgr.any_extension_types:
return len({block.dtype for block in self._mgr.blocks}) == 1
else:
return not self._is_mixed_type
@property
def _can_fast_transpose(self) -> bool:
if self._mgr.any_extension_types:
# TODO(EA2D) special case would be unnecessary with 2D EAs
return False
return len(self._mgr.blocks) == 1
# ----------------------------------------------------------------------
# Rendering Methods
def _repr_fits_vertical_(self) -> bool:
max_rows = get_option("display.max_rows")
return len(self) <= max_rows
def _repr_fits_horizontal_(self, ignore_width: bool = False) -> bool:
width, height = console.get_console_size()
max_columns = get_option("display.max_columns")
nb_columns = len(self.columns)
# exceed max columns
if (max_columns and nb_columns > max_columns) or (
(not ignore_width) and width and nb_columns > (width // 2)
):
return False
# used by repr_html under IPython notebook or scripts ignore terminal
# dims
if ignore_width or not console.in_interactive_session():
return True
if get_option("display.width") is not None or console.in_ipython_frontend():
# check at least the column row for excessive width
max_rows = 1
else:
max_rows = get_option("display.max_rows")
# when auto-detecting, so width=None and not in ipython front end
# check whether repr fits horizontal by actually checking
# the width of the rendered repr
buf = StringIO()
# only care about the stuff we'll actually print out
d = self
if not (max_rows is None):
d = d.iloc[: min(max_rows, len(d))]
else:
return True
d.to_string(buf=buf)
value = buf.getvalue()
repr_width = max(len(line) for line in value.split("\n"))
return repr_width < width
def _info_repr(self) -> bool:
info_repr_option = get_option("display.large_repr") == "info"
return info_repr_option and not (
self._repr_fits_horizontal_() and self._repr_fits_vertical_()
)
def __repr__(self) -> str:
buf = StringIO("")
if self._info_repr():
self.info(buf=buf)
return buf.getvalue()
max_rows = get_option("display.max_rows")
min_rows = get_option("display.min_rows")
max_cols = get_option("display.max_columns")
max_colwidth = get_option("display.max_colwidth")
show_dimensions = get_option("display.show_dimensions")
if get_option("display.expand_frame_repr"):
width, _ = console.get_console_size()
else:
width = None
self.to_string(
buf=buf,
max_rows=max_rows,
min_rows=min_rows,
max_cols=max_cols,
line_width=width,
max_colwidth=max_colwidth,
show_dimensions=show_dimensions,
)
return buf.getvalue()
def _repr_html_(self) -> Optional[str]:
if self._info_repr():
buf = StringIO("")
self.info(buf=buf)
val = buf.getvalue().replace("<", r"<", 1)
val = val.replace(">", r">", 1)
return "<pre>" + val + "</pre>"
if get_option("display.notebook_repr_html"):
max_rows = get_option("display.max_rows")
min_rows = get_option("display.min_rows")
max_cols = get_option("display.max_columns")
show_dimensions = get_option("display.show_dimensions")
formatter = fmt.DataFrameFormatter(
self,
columns=None,
col_space=None,
na_rep="NaN",
formatters=None,
float_format=None,
sparsify=None,
justify=None,
index_names=True,
header=True,
index=True,
bold_rows=True,
escape=True,
max_rows=max_rows,
min_rows=min_rows,
max_cols=max_cols,
show_dimensions=show_dimensions,
decimal=".",
)
return fmt.DataFrameRenderer(formatter).to_html(notebook=True)
else:
return None
@Substitution(
header_type="bool or sequence",
header="Write out the column names. If a list of strings "
"is given, it is assumed to be aliases for the "
"column names",
col_space_type="int, list or dict of int",
col_space="The minimum width of each column",
)
@Substitution(shared_params=fmt.common_docstring, returns=fmt.return_docstring)
def to_string(
self,
buf: Optional[FilePathOrBuffer[str]] = None,
columns: Optional[Sequence[str]] = None,
col_space: Optional[int] = None,
header: Union[bool, Sequence[str]] = True,
index: bool = True,
na_rep: str = "NaN",
formatters: Optional[fmt.FormattersType] = None,
float_format: Optional[fmt.FloatFormatType] = None,
sparsify: Optional[bool] = None,
index_names: bool = True,
justify: Optional[str] = None,
max_rows: Optional[int] = None,
min_rows: Optional[int] = None,
max_cols: Optional[int] = None,
show_dimensions: bool = False,
decimal: str = ".",
line_width: Optional[int] = None,
max_colwidth: Optional[int] = None,
encoding: Optional[str] = None,
) -> Optional[str]:
from pandas import option_context
with option_context("display.max_colwidth", max_colwidth):
formatter = fmt.DataFrameFormatter(
self,
columns=columns,
col_space=col_space,
na_rep=na_rep,
formatters=formatters,
float_format=float_format,
sparsify=sparsify,
justify=justify,
index_names=index_names,
header=header,
index=index,
min_rows=min_rows,
max_rows=max_rows,
max_cols=max_cols,
show_dimensions=show_dimensions,
decimal=decimal,
)
return fmt.DataFrameRenderer(formatter).to_string(
buf=buf,
encoding=encoding,
line_width=line_width,
)
@property
def style(self) -> Styler:
from pandas.io.formats.style import Styler
return Styler(self)
_shared_docs[
"items"
] = r"""
Iterate over (column name, Series) pairs.
Iterates over the DataFrame columns, returning a tuple with
the column name and the content as a Series.
Yields
------
label : object
The column names for the DataFrame being iterated over.
content : Series
The column entries belonging to each label, as a Series.
See Also
--------
DataFrame.iterrows : Iterate over DataFrame rows as
(index, Series) pairs.
DataFrame.itertuples : Iterate over DataFrame rows as namedtuples
of the values.
Examples
--------
>>> df = pd.DataFrame({'species': ['bear', 'bear', 'marsupial'],
... 'population': [1864, 22000, 80000]},
... index=['panda', 'polar', 'koala'])
>>> df
species population
panda bear 1864
polar bear 22000
koala marsupial 80000
>>> for label, content in df.items():
... print(f'label: {label}')
... print(f'content: {content}', sep='\n')
...
label: species
content:
panda bear
polar bear
koala marsupial
Name: species, dtype: object
label: population
content:
panda 1864
polar 22000
koala 80000
Name: population, dtype: int64
"""
@Appender(_shared_docs["items"])
def items(self) -> Iterable[Tuple[Label, Series]]:
if self.columns.is_unique and hasattr(self, "_item_cache"):
for k in self.columns:
yield k, self._get_item_cache(k)
else:
for i, k in enumerate(self.columns):
yield k, self._ixs(i, axis=1)
@Appender(_shared_docs["items"])
def iteritems(self) -> Iterable[Tuple[Label, Series]]:
yield from self.items()
def iterrows(self) -> Iterable[Tuple[Label, Series]]:
columns = self.columns
klass = self._constructor_sliced
for k, v in zip(self.index, self.values):
s = klass(v, index=columns, name=k)
yield k, s
def itertuples(self, index: bool = True, name: Optional[str] = "Pandas"):
arrays = []
fields = list(self.columns)
if index:
arrays.append(self.index)
fields.insert(0, "Index")
arrays.extend(self.iloc[:, k] for k in range(len(self.columns)))
if name is not None:
itertuple = collections.namedtuple(
name, fields, rename=True
)
return map(itertuple._make, zip(*arrays))
return zip(*arrays)
def __len__(self) -> int:
return len(self.index)
def dot(self, other):
if isinstance(other, (Series, DataFrame)):
common = self.columns.union(other.index)
if len(common) > len(self.columns) or len(common) > len(other.index):
raise ValueError("matrices are not aligned")
left = self.reindex(columns=common, copy=False)
right = other.reindex(index=common, copy=False)
lvals = left.values
rvals = right._values
else:
left = self
lvals = self.values
rvals = np.asarray(other)
if lvals.shape[1] != rvals.shape[0]:
raise ValueError(
f"Dot product shape mismatch, {lvals.shape} vs {rvals.shape}"
)
if isinstance(other, DataFrame):
return self._constructor(
np.dot(lvals, rvals), index=left.index, columns=other.columns
)
elif isinstance(other, Series):
return self._constructor_sliced(np.dot(lvals, rvals), index=left.index)
elif isinstance(rvals, (np.ndarray, Index)):
result = np.dot(lvals, rvals)
if result.ndim == 2:
return self._constructor(result, index=left.index)
else:
return self._constructor_sliced(result, index=left.index)
else:
raise TypeError(f"unsupported type: {type(other)}")
def __matmul__(self, other):
return self.dot(other)
def __rmatmul__(self, other):
try:
return self.T.dot(np.transpose(other)).T
except ValueError as err:
if "shape mismatch" not in str(err):
raise
{self.shape} not aligned"
raise ValueError(msg) from err
@classmethod
def from_dict(cls, data, orient="columns", dtype=None, columns=None) -> DataFrame:
index = None
orient = orient.lower()
if orient == "index":
if len(data) > 0:
if isinstance(list(data.values())[0], (Series, dict)):
data = _from_nested_dict(data)
else:
data, index = list(data.values()), list(data.keys())
elif orient == "columns":
if columns is not None:
raise ValueError("cannot use columns parameter with orient='columns'")
else:
raise ValueError("only recognize index or columns for orient")
return cls(data, index=index, columns=columns, dtype=dtype)
def to_numpy(
self, dtype=None, copy: bool = False, na_value=lib.no_default
) -> np.ndarray:
self._consolidate_inplace()
result = self._mgr.as_array(
transpose=self._AXIS_REVERSED, dtype=dtype, copy=copy, na_value=na_value
)
if result.dtype is not dtype:
result = np.array(result, dtype=dtype, copy=False)
return result
def to_dict(self, orient="dict", into=dict):
if not self.columns.is_unique:
warnings.warn(
"DataFrame columns are not unique, some columns will be omitted.",
UserWarning,
stacklevel=2,
)
into_c = com.standardize_mapping(into)
orient = orient.lower()
if orient.startswith(("d", "l", "s", "r", "i")) and orient not in {
"dict",
"list",
"series",
"split",
"records",
"index",
}:
warnings.warn(
"Using short name for 'orient' is deprecated. Only the "
"options: ('dict', list, 'series', 'split', 'records', 'index') "
"will be used in a future version. Use one of the above "
"to silence this warning.",
FutureWarning,
)
if orient.startswith("d"):
orient = "dict"
elif orient.startswith("l"):
orient = "list"
elif orient.startswith("sp"):
orient = "split"
elif orient.startswith("s"):
orient = "series"
elif orient.startswith("r"):
orient = "records"
elif orient.startswith("i"):
orient = "index"
if orient == "dict":
return into_c((k, v.to_dict(into)) for k, v in self.items())
elif orient == "list":
return into_c((k, v.tolist()) for k, v in self.items())
elif orient == "split":
return into_c(
(
("index", self.index.tolist()),
("columns", self.columns.tolist()),
(
"data",
[
list(map(maybe_box_datetimelike, t))
for t in self.itertuples(index=False, name=None)
],
),
)
)
elif orient == "series":
return into_c((k, maybe_box_datetimelike(v)) for k, v in self.items())
elif orient == "records":
columns = self.columns.tolist()
rows = (
dict(zip(columns, row))
for row in self.itertuples(index=False, name=None)
)
return [
into_c((k, maybe_box_datetimelike(v)) for k, v in row.items())
for row in rows
]
elif orient == "index":
if not self.index.is_unique:
raise ValueError("DataFrame index must be unique for orient='index'.")
return into_c(
(t[0], dict(zip(self.columns, t[1:])))
for t in self.itertuples(name=None)
)
else:
raise ValueError(f"orient '{orient}' not understood")
def to_gbq(
self,
destination_table,
project_id=None,
chunksize=None,
reauth=False,
if_exists="fail",
auth_local_webserver=False,
table_schema=None,
location=None,
progress_bar=True,
credentials=None,
) -> None:
from pandas.io import gbq
gbq.to_gbq(
self,
destination_table,
project_id=project_id,
chunksize=chunksize,
reauth=reauth,
if_exists=if_exists,
auth_local_webserver=auth_local_webserver,
table_schema=table_schema,
location=location,
progress_bar=progress_bar,
credentials=credentials,
)
@classmethod
def from_records(
cls,
data,
index=None,
exclude=None,
columns=None,
coerce_float=False,
nrows=None,
) -> DataFrame:
if columns is not None:
columns = ensure_index(columns)
if is_iterator(data):
if nrows == 0:
return cls()
try:
first_row = next(data)
except StopIteration:
return cls(index=index, columns=columns)
dtype = None
if hasattr(first_row, "dtype") and first_row.dtype.names:
dtype = first_row.dtype
values = [first_row]
if nrows is None:
values += data
else:
values.extend(itertools.islice(data, nrows - 1))
if dtype is not None:
data = np.array(values, dtype=dtype)
else:
data = values
if isinstance(data, dict):
if columns is None:
columns = arr_columns = ensure_index(sorted(data))
arrays = [data[k] for k in columns]
else:
arrays = []
arr_columns_list = []
for k, v in data.items():
if k in columns:
arr_columns_list.append(k)
arrays.append(v)
arrays, arr_columns = reorder_arrays(arrays, arr_columns_list, columns)
elif isinstance(data, (np.ndarray, DataFrame)):
arrays, columns = to_arrays(data, columns)
if columns is not None:
columns = ensure_index(columns)
arr_columns = columns
else:
arrays, arr_columns = to_arrays(data, columns, coerce_float=coerce_float)
arr_columns = ensure_index(arr_columns)
if columns is not None:
columns = ensure_index(columns)
else:
columns = arr_columns
if exclude is None:
exclude = set()
else:
exclude = set(exclude)
result_index = None
if index is not None:
if isinstance(index, str) or not hasattr(index, "__iter__"):
i = columns.get_loc(index)
exclude.add(index)
if len(arrays) > 0:
result_index = Index(arrays[i], name=index)
else:
result_index = Index([], name=index)
else:
try:
index_data = [arrays[arr_columns.get_loc(field)] for field in index]
except (KeyError, TypeError):
result_index = index
else:
result_index = ensure_index_from_sequences(index_data, names=index)
exclude.update(index)
if any(exclude):
arr_exclude = [x for x in exclude if x in arr_columns]
to_remove = [arr_columns.get_loc(col) for col in arr_exclude]
arrays = [v for i, v in enumerate(arrays) if i not in to_remove]
arr_columns = arr_columns.drop(arr_exclude)
columns = columns.drop(exclude)
mgr = arrays_to_mgr(arrays, arr_columns, result_index, columns)
return cls(mgr)
def to_records(
self, index=True, column_dtypes=None, index_dtypes=None
) -> np.recarray:
if index:
if isinstance(self.index, MultiIndex):
ix_vals = list(map(np.array, zip(*self.index._values)))
else:
ix_vals = [self.index.values]
arrays = ix_vals + [
np.asarray(self.iloc[:, i]) for i in range(len(self.columns))
]
count = 0
index_names = list(self.index.names)
if isinstance(self.index, MultiIndex):
for i, n in enumerate(index_names):
if n is None:
index_names[i] = f"level_{count}"
count += 1
elif index_names[0] is None:
index_names = ["index"]
names = [str(name) for name in itertools.chain(index_names, self.columns)]
else:
arrays = [np.asarray(self.iloc[:, i]) for i in range(len(self.columns))]
names = [str(c) for c in self.columns]
index_names = []
index_len = len(index_names)
formats = []
for i, v in enumerate(arrays):
index = i
# followed by those in its columns.
#
# Thus, the total length of the array is:
# len(index_names) + len(DataFrame.columns).
#
# This check allows us to see whether we are
# handling a name / array in the index or column.
if index < index_len:
dtype_mapping = index_dtypes
name = index_names[index]
else:
index -= index_len
dtype_mapping = column_dtypes
name = self.columns[index]
# We have a dictionary, so we get the data type
# associated with the index or column (which can
# be denoted by its name in the DataFrame or its
# position in DataFrame's array of indices or
if is_dict_like(dtype_mapping):
if name in dtype_mapping:
dtype_mapping = dtype_mapping[name]
elif index in dtype_mapping:
dtype_mapping = dtype_mapping[index]
else:
dtype_mapping = None
# dtype attribute for formatting.
#
# A valid dtype must either be a type or
# string naming a type.
if dtype_mapping is None:
formats.append(v.dtype)
elif isinstance(dtype_mapping, (type, np.dtype, str)):
formats.append(dtype_mapping)
else:
element = "row" if i < index_len else "column"
msg = f"Invalid dtype {dtype_mapping} specified for {element} {name}"
raise ValueError(msg)
return np.rec.fromarrays(arrays, dtype={"names": names, "formats": formats})
@classmethod
def _from_arrays(
cls,
arrays,
columns,
index,
dtype: Optional[Dtype] = None,
verify_integrity: bool = True,
) -> DataFrame:
if dtype is not None:
dtype = pandas_dtype(dtype)
mgr = arrays_to_mgr(
arrays,
columns,
index,
columns,
dtype=dtype,
verify_integrity=verify_integrity,
)
return cls(mgr)
@doc(storage_options=generic._shared_docs["storage_options"])
@deprecate_kwarg(old_arg_name="fname", new_arg_name="path")
def to_stata(
self,
path: FilePathOrBuffer,
convert_dates: Optional[Dict[Label, str]] = None,
write_index: bool = True,
byteorder: Optional[str] = None,
time_stamp: Optional[datetime.datetime] = None,
data_label: Optional[str] = None,
variable_labels: Optional[Dict[Label, str]] = None,
version: Optional[int] = 114,
convert_strl: Optional[Sequence[Label]] = None,
compression: CompressionOptions = "infer",
storage_options: StorageOptions = None,
) -> None:
if version not in (114, 117, 118, 119, None):
raise ValueError("Only formats 114, 117, 118 and 119 are supported.")
if version == 114:
if convert_strl is not None:
raise ValueError("strl is not supported in format 114")
from pandas.io.stata import StataWriter as statawriter
elif version == 117:
# mypy: Name 'statawriter' already defined (possibly by an import)
from pandas.io.stata import ( # type: ignore[no-redef]
StataWriter117 as statawriter,
)
else: # versions 118 and 119
# mypy: Name 'statawriter' already defined (possibly by an import)
from pandas.io.stata import ( # type: ignore[no-redef]
StataWriterUTF8 as statawriter,
)
kwargs: Dict[str, Any] = {}
if version is None or version >= 117:
# strl conversion is only supported >= 117
kwargs["convert_strl"] = convert_strl
if version is None or version >= 118:
# Specifying the version is only supported for UTF8 (118 or 119)
kwargs["version"] = version
# mypy: Too many arguments for "StataWriter"
writer = statawriter( # type: ignore[call-arg]
path,
self,
convert_dates=convert_dates,
byteorder=byteorder,
time_stamp=time_stamp,
data_label=data_label,
write_index=write_index,
variable_labels=variable_labels,
compression=compression,
storage_options=storage_options,
**kwargs,
)
writer.write_file()
@deprecate_kwarg(old_arg_name="fname", new_arg_name="path")
def to_feather(self, path: FilePathOrBuffer[AnyStr], **kwargs) -> None:
from pandas.io.feather_format import to_feather
to_feather(self, path, **kwargs)
@doc(
Series.to_markdown,
klass=_shared_doc_kwargs["klass"],
storage_options=_shared_docs["storage_options"],
examples="""Examples
--------
>>> df = pd.DataFrame(
... data={"animal_1": ["elk", "pig"], "animal_2": ["dog", "quetzal"]}
... )
>>> print(df.to_markdown())
| | animal_1 | animal_2 |
|---:|:-----------|:-----------|
| 0 | elk | dog |
| 1 | pig | quetzal |
Output markdown with a tabulate option.
>>> print(df.to_markdown(tablefmt="grid"))
+----+------------+------------+
| | animal_1 | animal_2 |
+====+============+============+
| 0 | elk | dog |
+----+------------+------------+
| 1 | pig | quetzal |
+----+------------+------------+
""",
)
def to_markdown(
self,
buf: Optional[Union[IO[str], str]] = None,
mode: str = "wt",
index: bool = True,
storage_options: StorageOptions = None,
**kwargs,
) -> Optional[str]:
if "showindex" in kwargs:
warnings.warn(
"'showindex' is deprecated. Only 'index' will be used "
"in a future version. Use 'index' to silence this warning.",
FutureWarning,
stacklevel=2,
)
kwargs.setdefault("headers", "keys")
kwargs.setdefault("tablefmt", "pipe")
kwargs.setdefault("showindex", index)
tabulate = import_optional_dependency("tabulate")
result = tabulate.tabulate(self, **kwargs)
if buf is None:
return result
with get_handle(buf, mode, storage_options=storage_options) as handles:
assert not isinstance(handles.handle, (str, mmap.mmap))
handles.handle.writelines(result)
return None
@doc(storage_options=generic._shared_docs["storage_options"])
@deprecate_kwarg(old_arg_name="fname", new_arg_name="path")
def to_parquet(
self,
path: Optional[FilePathOrBuffer] = None,
engine: str = "auto",
compression: Optional[str] = "snappy",
index: Optional[bool] = None,
partition_cols: Optional[List[str]] = None,
storage_options: StorageOptions = None,
**kwargs,
) -> Optional[bytes]:
from pandas.io.parquet import to_parquet
return to_parquet(
self,
path,
engine,
compression=compression,
index=index,
partition_cols=partition_cols,
storage_options=storage_options,
**kwargs,
)
@Substitution(
header_type="bool",
header="Whether to print column labels, default True",
col_space_type="str or int, list or dict of int or str",
col_space="The minimum width of each column in CSS length "
"units. An int is assumed to be px units.\n\n"
" .. versionadded:: 0.25.0\n"
" Ability to use str",
)
@Substitution(shared_params=fmt.common_docstring, returns=fmt.return_docstring)
def to_html(
self,
buf=None,
columns=None,
col_space=None,
header=True,
index=True,
na_rep="NaN",
formatters=None,
float_format=None,
sparsify=None,
index_names=True,
justify=None,
max_rows=None,
max_cols=None,
show_dimensions=False,
decimal=".",
bold_rows=True,
classes=None,
escape=True,
notebook=False,
border=None,
table_id=None,
render_links=False,
encoding=None,
):
if justify is not None and justify not in fmt._VALID_JUSTIFY_PARAMETERS:
raise ValueError("Invalid value for justify parameter")
formatter = fmt.DataFrameFormatter(
self,
columns=columns,
col_space=col_space,
na_rep=na_rep,
header=header,
index=index,
formatters=formatters,
float_format=float_format,
bold_rows=bold_rows,
sparsify=sparsify,
justify=justify,
index_names=index_names,
escape=escape,
decimal=decimal,
max_rows=max_rows,
max_cols=max_cols,
show_dimensions=show_dimensions,
)
# TODO: a generic formatter wld b in DataFrameFormatter
return fmt.DataFrameRenderer(formatter).to_html(
buf=buf,
classes=classes,
notebook=notebook,
border=border,
encoding=encoding,
table_id=table_id,
render_links=render_links,
)
# ----------------------------------------------------------------------
@Substitution(
klass="DataFrame",
type_sub=" and columns",
max_cols_sub=dedent(
"""\
max_cols : int, optional
When to switch from the verbose to the truncated output. If the
DataFrame has more than `max_cols` columns, the truncated output
is used. By default, the setting in
``pandas.options.display.max_info_columns`` is used."""
),
show_counts_sub=dedent(
"""\
show_counts : bool, optional
Whether to show the non-null counts. By default, this is shown
only if the DataFrame is smaller than
``pandas.options.display.max_info_rows`` and
``pandas.options.display.max_info_columns``. A value of True always
shows the counts, and False never shows the counts.
null_counts : bool, optional
.. deprecated:: 1.2.0
Use show_counts instead."""
),
examples_sub=dedent(
"""\
>>> int_values = [1, 2, 3, 4, 5]
>>> text_values = ['alpha', 'beta', 'gamma', 'delta', 'epsilon']
>>> float_values = [0.0, 0.25, 0.5, 0.75, 1.0]
>>> df = pd.DataFrame({"int_col": int_values, "text_col": text_values,
... "float_col": float_values})
>>> df
int_col text_col float_col
0 1 alpha 0.00
1 2 beta 0.25
2 3 gamma 0.50
3 4 delta 0.75
4 5 epsilon 1.00
Prints information of all columns:
>>> df.info(verbose=True)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 int_col 5 non-null int64
1 text_col 5 non-null object
2 float_col 5 non-null float64
dtypes: float64(1), int64(1), object(1)
memory usage: 248.0+ bytes
Prints a summary of columns count and its dtypes but not per column
information:
>>> df.info(verbose=False)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Columns: 3 entries, int_col to float_col
dtypes: float64(1), int64(1), object(1)
memory usage: 248.0+ bytes
Pipe output of DataFrame.info to buffer instead of sys.stdout, get
buffer content and writes to a text file:
>>> import io
>>> buffer = io.StringIO()
>>> df.info(buf=buffer)
>>> s = buffer.getvalue()
>>> with open("df_info.txt", "w",
... encoding="utf-8") as f: # doctest: +SKIP
... f.write(s)
260
The `memory_usage` parameter allows deep introspection mode, specially
useful for big DataFrames and fine-tune memory optimization:
>>> random_strings_array = np.random.choice(['a', 'b', 'c'], 10 ** 6)
>>> df = pd.DataFrame({
... 'column_1': np.random.choice(['a', 'b', 'c'], 10 ** 6),
... 'column_2': np.random.choice(['a', 'b', 'c'], 10 ** 6),
... 'column_3': np.random.choice(['a', 'b', 'c'], 10 ** 6)
... })
>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000000 entries, 0 to 999999
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 column_1 1000000 non-null object
1 column_2 1000000 non-null object
2 column_3 1000000 non-null object
dtypes: object(3)
memory usage: 22.9+ MB
>>> df.info(memory_usage='deep')
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000000 entries, 0 to 999999
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 column_1 1000000 non-null object
1 column_2 1000000 non-null object
2 column_3 1000000 non-null object
dtypes: object(3)
memory usage: 165.9 MB"""
),
see_also_sub=dedent(
"""\
DataFrame.describe: Generate descriptive statistics of DataFrame
columns.
DataFrame.memory_usage: Memory usage of DataFrame columns."""
),
version_added_sub="",
)
@doc(BaseInfo.render)
def info(
self,
verbose: Optional[bool] = None,
buf: Optional[IO[str]] = None,
max_cols: Optional[int] = None,
memory_usage: Optional[Union[bool, str]] = None,
show_counts: Optional[bool] = None,
null_counts: Optional[bool] = None,
) -> None:
if null_counts is not None:
if show_counts is not None:
raise ValueError("null_counts used with show_counts. Use show_counts.")
warnings.warn(
"null_counts is deprecated. Use show_counts instead",
FutureWarning,
stacklevel=2,
)
show_counts = null_counts
info = DataFrameInfo(
data=self,
memory_usage=memory_usage,
)
info.render(
buf=buf,
max_cols=max_cols,
verbose=verbose,
show_counts=show_counts,
)
def memory_usage(self, index=True, deep=False) -> Series:
result = self._constructor_sliced(
[c.memory_usage(index=False, deep=deep) for col, c in self.items()],
index=self.columns,
)
if index:
result = self._constructor_sliced(
self.index.memory_usage(deep=deep), index=["Index"]
).append(result)
return result
def transpose(self, *args, copy: bool = False) -> DataFrame:
nv.validate_transpose(args, {})
# construct the args
dtypes = list(self.dtypes)
if self._is_homogeneous_type and dtypes and is_extension_array_dtype(dtypes[0]):
# We have EAs with the same dtype. We can preserve that dtype in transpose.
dtype = dtypes[0]
arr_type = dtype.construct_array_type()
values = self.values
new_values = [arr_type._from_sequence(row, dtype=dtype) for row in values]
result = self._constructor(
dict(zip(self.index, new_values)), index=self.columns
)
else:
new_values = self.values.T
if copy:
new_values = new_values.copy()
result = self._constructor(
new_values, index=self.columns, columns=self.index
)
return result.__finalize__(self, method="transpose")
@property
def T(self) -> DataFrame:
return self.transpose()
# ----------------------------------------------------------------------
# Indexing Methods
def _ixs(self, i: int, axis: int = 0):
# irow
if axis == 0:
new_values = self._mgr.fast_xs(i)
# if we are a copy, mark as such
copy = isinstance(new_values, np.ndarray) and new_values.base is None
result = self._constructor_sliced(
new_values,
index=self.columns,
name=self.index[i],
dtype=new_values.dtype,
)
result._set_is_copy(self, copy=copy)
return result
# icol
else:
label = self.columns[i]
values = self._mgr.iget(i)
result = self._box_col_values(values, i)
# this is a cached value, mark it so
result._set_as_cached(label, self)
return result
def _get_column_array(self, i: int) -> ArrayLike:
return self._mgr.iget_values(i)
def _iter_column_arrays(self) -> Iterator[ArrayLike]:
for i in range(len(self.columns)):
yield self._get_column_array(i)
def __getitem__(self, key):
key = lib.item_from_zerodim(key)
key = com.apply_if_callable(key, self)
if is_hashable(key):
# shortcut if the key is in columns
if self.columns.is_unique and key in self.columns:
if isinstance(self.columns, MultiIndex):
return self._getitem_multilevel(key)
return self._get_item_cache(key)
# Do we have a slicer (on rows)?
indexer = convert_to_index_sliceable(self, key)
if indexer is not None:
if isinstance(indexer, np.ndarray):
indexer = lib.maybe_indices_to_slice(
indexer.astype(np.intp, copy=False), len(self)
)
# either we have a slice or we have a string that can be converted
# to a slice for partial-string date indexing
return self._slice(indexer, axis=0)
# Do we have a (boolean) DataFrame?
if isinstance(key, DataFrame):
return self.where(key)
# Do we have a (boolean) 1d indexer?
if com.is_bool_indexer(key):
return self._getitem_bool_array(key)
# We are left with two options: a single key, and a collection of keys,
# We interpret tuples as collections only for non-MultiIndex
is_single_key = isinstance(key, tuple) or not is_list_like(key)
if is_single_key:
if self.columns.nlevels > 1:
return self._getitem_multilevel(key)
indexer = self.columns.get_loc(key)
if is_integer(indexer):
indexer = [indexer]
else:
if is_iterator(key):
key = list(key)
indexer = self.loc._get_listlike_indexer(key, axis=1, raise_missing=True)[1]
# take() does not accept boolean indexers
if getattr(indexer, "dtype", None) == bool:
indexer = np.where(indexer)[0]
data = self._take_with_is_copy(indexer, axis=1)
if is_single_key:
# What does looking for a single key in a non-unique index return?
# The behavior is inconsistent. It returns a Series, except when
# - the key itself is repeated (test on data.shape, #9519), or
# - we have a MultiIndex on columns (test on self.columns, #21309)
if data.shape[1] == 1 and not isinstance(self.columns, MultiIndex):
# GH#26490 using data[key] can cause RecursionError
data = data._get_item_cache(key)
return data
def _getitem_bool_array(self, key):
# also raises Exception if object array with NA values
# warning here just in case -- previously __setitem__ was
# reindexing but __getitem__ was not; it seems more reasonable to
# go with the __setitem__ behavior since that is more consistent
# with all other indexing behavior
if isinstance(key, Series) and not key.index.equals(self.index):
warnings.warn(
"Boolean Series key will be reindexed to match DataFrame index.",
UserWarning,
stacklevel=3,
)
elif len(key) != len(self.index):
raise ValueError(
f"Item wrong length {len(key)} instead of {len(self.index)}."
)
# check_bool_indexer will throw exception if Series key cannot
# be reindexed to match DataFrame rows
key = check_bool_indexer(self.index, key)
indexer = key.nonzero()[0]
return self._take_with_is_copy(indexer, axis=0)
def _getitem_multilevel(self, key):
# self.columns is a MultiIndex
loc = self.columns.get_loc(key)
if isinstance(loc, (slice, np.ndarray)):
new_columns = self.columns[loc]
result_columns = maybe_droplevels(new_columns, key)
if self._is_mixed_type:
result = self.reindex(columns=new_columns)
result.columns = result_columns
else:
new_values = self.values[:, loc]
result = self._constructor(
new_values, index=self.index, columns=result_columns
)
result = result.__finalize__(self)
# If there is only one column being returned, and its name is
# either an empty string, or a tuple with an empty string as its
# first element, then treat the empty string as a placeholder
# and return the column as if the user had provided that empty
# string in the key. If the result is a Series, exclude the
# implied empty string from its name.
if len(result.columns) == 1:
top = result.columns[0]
if isinstance(top, tuple):
top = top[0]
if top == "":
result = result[""]
if isinstance(result, Series):
result = self._constructor_sliced(
result, index=self.index, name=key
)
result._set_is_copy(self)
return result
else:
# loc is neither a slice nor ndarray, so must be an int
return self._ixs(loc, axis=1)
def _get_value(self, index, col, takeable: bool = False):
if takeable:
series = self._ixs(col, axis=1)
return series._values[index]
series = self._get_item_cache(col)
engine = self.index._engine
try:
loc = engine.get_loc(index)
return series._values[loc]
except KeyError:
# GH 20629
if self.index.nlevels > 1:
# partial indexing forbidden
raise
# we cannot handle direct indexing
# use positional
col = self.columns.get_loc(col)
index = self.index.get_loc(index)
return self._get_value(index, col, takeable=True)
def __setitem__(self, key, value):
key = com.apply_if_callable(key, self)
# see if we can slice the rows
indexer = convert_to_index_sliceable(self, key)
if indexer is not None:
# either we have a slice or we have a string that can be converted
# to a slice for partial-string date indexing
return self._setitem_slice(indexer, value)
if isinstance(key, DataFrame) or getattr(key, "ndim", None) == 2:
self._setitem_frame(key, value)
elif isinstance(key, (Series, np.ndarray, list, Index)):
self._setitem_array(key, value)
else:
# set column
self._set_item(key, value)
def _setitem_slice(self, key: slice, value):
# NB: we can't just use self.loc[key] = value because that
self._check_setitem_copy()
self.iloc._setitem_with_indexer(key, value)
def _setitem_array(self, key, value):
if com.is_bool_indexer(key):
if len(key) != len(self.index):
raise ValueError(
f"Item wrong length {len(key)} instead of {len(self.index)}!"
)
key = check_bool_indexer(self.index, key)
indexer = key.nonzero()[0]
self._check_setitem_copy()
self.iloc._setitem_with_indexer(indexer, value)
else:
if isinstance(value, DataFrame):
if len(value.columns) != len(key):
raise ValueError("Columns must be same length as key")
for k1, k2 in zip(key, value.columns):
self[k1] = value[k2]
else:
self.loc._ensure_listlike_indexer(key, axis=1, value=value)
indexer = self.loc._get_listlike_indexer(
key, axis=1, raise_missing=False
)[1]
self._check_setitem_copy()
self.iloc._setitem_with_indexer((slice(None), indexer), value)
def _setitem_frame(self, key, value):
if isinstance(key, np.ndarray):
if key.shape != self.shape:
raise ValueError("Array conditional must be same shape as self")
key = self._constructor(key, **self._construct_axes_dict())
if key.size and not is_bool_dtype(key.values):
raise TypeError(
"Must pass DataFrame or 2-d ndarray with boolean values only"
)
self._check_inplace_setting(value)
self._check_setitem_copy()
self._where(-key, value, inplace=True)
def _iset_item(self, loc: int, value):
self._ensure_valid_index(value)
value = self._sanitize_column(loc, value, broadcast=False)
NDFrame._iset_item(self, loc, value)
if len(self):
self._check_setitem_copy()
def _set_item(self, key, value):
self._ensure_valid_index(value)
value = self._sanitize_column(key, value)
NDFrame._set_item(self, key, value)
if len(self):
self._check_setitem_copy()
def _set_value(self, index, col, value, takeable: bool = False):
try:
if takeable is True:
series = self._ixs(col, axis=1)
series._set_value(index, value, takeable=True)
return
series = self._get_item_cache(col)
engine = self.index._engine
loc = engine.get_loc(index)
validate_numeric_casting(series.dtype, value)
series._values[loc] = value
except (KeyError, TypeError):
if takeable:
self.iloc[index, col] = value
else:
self.loc[index, col] = value
self._item_cache.pop(col, None)
def _ensure_valid_index(self, value):
if not len(self.index) and is_list_like(value) and len(value):
try:
value = Series(value)
except (ValueError, NotImplementedError, TypeError) as err:
raise ValueError(
"Cannot set a frame with no defined index "
"and a value that cannot be converted to a Series"
) from err
index_copy = value.index.copy()
if self.index.name is not None:
index_copy.name = self.index.name
self._mgr = self._mgr.reindex_axis(index_copy, axis=1, fill_value=np.nan)
def _box_col_values(self, values, loc: int) -> Series:
name = self.columns[loc]
klass = self._constructor_sliced
return klass(values, index=self.index, name=name, fastpath=True)
def query(self, expr, inplace=False, **kwargs):
inplace = validate_bool_kwarg(inplace, "inplace")
if not isinstance(expr, str):
msg = f"expr must be a string to be evaluated, {type(expr)} given"
raise ValueError(msg)
kwargs["level"] = kwargs.pop("level", 0) + 1
kwargs["target"] = None
res = self.eval(expr, **kwargs)
try:
result = self.loc[res]
except ValueError:
result = self[res]
if inplace:
self._update_inplace(result)
else:
return result
def eval(self, expr, inplace=False, **kwargs):
from pandas.core.computation.eval import eval as _eval
inplace = validate_bool_kwarg(inplace, "inplace")
resolvers = kwargs.pop("resolvers", None)
kwargs["level"] = kwargs.pop("level", 0) + 1
if resolvers is None:
index_resolvers = self._get_index_resolvers()
column_resolvers = self._get_cleaned_column_resolvers()
resolvers = column_resolvers, index_resolvers
if "target" not in kwargs:
kwargs["target"] = self
kwargs["resolvers"] = kwargs.get("resolvers", ()) + tuple(resolvers)
return _eval(expr, inplace=inplace, **kwargs)
def select_dtypes(self, include=None, exclude=None) -> DataFrame:
if not is_list_like(include):
include = (include,) if include is not None else ()
if not is_list_like(exclude):
exclude = (exclude,) if exclude is not None else ()
selection = (frozenset(include), frozenset(exclude))
if not any(selection):
raise ValueError("at least one of include or exclude must be nonempty")
include = frozenset(infer_dtype_from_object(x) for x in include)
exclude = frozenset(infer_dtype_from_object(x) for x in exclude)
for dtypes in (include, exclude):
invalidate_string_dtypes(dtypes)
if not include.isdisjoint(exclude):
raise ValueError(f"include and exclude overlap on {(include & exclude)}")
# We raise when both include and exclude are empty
# Hence, we can just shrink the columns we want to keep
keep_these = np.full(self.shape[1], True)
def extract_unique_dtypes_from_dtypes_set(
dtypes_set: FrozenSet[Dtype], unique_dtypes: np.ndarray
) -> List[Dtype]:
extracted_dtypes = [
unique_dtype
for unique_dtype in unique_dtypes
# error: Argument 1 to "tuple" has incompatible type
# "FrozenSet[Union[ExtensionDtype, str, Any, Type[str],
# Type[float], Type[int], Type[complex], Type[bool]]]";
# expected "Iterable[Union[type, Tuple[Any, ...]]]"
if issubclass(
unique_dtype.type, tuple(dtypes_set) # type: ignore[arg-type]
)
]
return extracted_dtypes
unique_dtypes = self.dtypes.unique()
if include:
included_dtypes = extract_unique_dtypes_from_dtypes_set(
include, unique_dtypes
)
keep_these &= self.dtypes.isin(included_dtypes)
if exclude:
excluded_dtypes = extract_unique_dtypes_from_dtypes_set(
exclude, unique_dtypes
)
keep_these &= ~self.dtypes.isin(excluded_dtypes)
return self.iloc[:, keep_these.values]
def insert(self, loc, column, value, allow_duplicates=False) -> None:
if allow_duplicates and not self.flags.allows_duplicate_labels:
raise ValueError(
"Cannot specify 'allow_duplicates=True' when "
"'self.flags.allows_duplicate_labels' is False."
)
self._ensure_valid_index(value)
value = self._sanitize_column(column, value, broadcast=False)
self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates)
def assign(self, **kwargs) -> DataFrame:
data = self.copy()
for k, v in kwargs.items():
data[k] = com.apply_if_callable(v, data)
return data
def _sanitize_column(self, key, value, broadcast=True):
def reindexer(value):
# reindex if necessary
if value.index.equals(self.index) or not len(self.index):
value = value._values.copy()
else:
# GH 4107
try:
value = value.reindex(self.index)._values
except ValueError as err:
# raised in MultiIndex.from_tuples, see test_insert_error_msmgs
if not value.index.is_unique:
# duplicate axis
raise err
# other
raise TypeError(
"incompatible index of inserted column with frame index"
) from err
return value
if isinstance(value, Series):
value = reindexer(value)
elif isinstance(value, DataFrame):
# align right-hand-side columns if self.columns
# is multi-index and self[key] is a sub-frame
if isinstance(self.columns, MultiIndex) and key in self.columns:
loc = self.columns.get_loc(key)
if isinstance(loc, (slice, Series, np.ndarray, Index)):
cols = maybe_droplevels(self.columns[loc], key)
if len(cols) and not cols.equals(value.columns):
value = value.reindex(cols, axis=1)
# now align rows
value = reindexer(value).T
elif isinstance(value, ExtensionArray):
# Explicitly copy here, instead of in sanitize_index,
# as sanitize_index won't copy an EA, even with copy=True
value = value.copy()
value = sanitize_index(value, self.index)
elif isinstance(value, Index) or is_sequence(value):
value = sanitize_index(value, self.index)
if not isinstance(value, (np.ndarray, Index)):
if isinstance(value, list) and len(value) > 0:
value = maybe_convert_platform(value)
else:
value = com.asarray_tuplesafe(value)
elif value.ndim == 2:
value = value.copy().T
elif isinstance(value, Index):
value = value.copy(deep=True)
else:
value = value.copy()
if is_object_dtype(value.dtype):
value = maybe_infer_to_datetimelike(value)
else:
infer_dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=True)
if is_extension_array_dtype(infer_dtype):
value = construct_1d_arraylike_from_scalar(
value, len(self.index), infer_dtype
)
else:
value = cast_scalar_to_array(
len(self.index), value
)
value = maybe_cast_to_datetime(value, infer_dtype)
if is_extension_array_dtype(value):
return value
if broadcast and key in self.columns and value.ndim == 1:
if not self.columns.is_unique or isinstance(self.columns, MultiIndex):
existing_piece = self[key]
if isinstance(existing_piece, DataFrame):
value = np.tile(value, (len(existing_piece.columns), 1))
return np.atleast_2d(np.asarray(value))
@property
def _series(self):
return {
item: Series(
self._mgr.iget(idx), index=self.index, name=item, fastpath=True
)
for idx, item in enumerate(self.columns)
}
def lookup(self, row_labels, col_labels) -> np.ndarray:
msg = (
"The 'lookup' method is deprecated and will be"
"removed in a future version."
"You can use DataFrame.melt and DataFrame.loc"
"as a substitute."
)
warnings.warn(msg, FutureWarning, stacklevel=2)
n = len(row_labels)
if n != len(col_labels):
raise ValueError("Row labels must have same size as column labels")
if not (self.index.is_unique and self.columns.is_unique):
raise ValueError("DataFrame.lookup requires unique index and columns")
thresh = 1000
if not self._is_mixed_type or n > thresh:
values = self.values
ridx = self.index.get_indexer(row_labels)
cidx = self.columns.get_indexer(col_labels)
if (ridx == -1).any():
raise KeyError("One or more row labels was not found")
if (cidx == -1).any():
raise KeyError("One or more column labels was not found")
flat_index = ridx * len(self.columns) + cidx
result = values.flat[flat_index]
else:
result = np.empty(n, dtype="O")
for i, (r, c) in enumerate(zip(row_labels, col_labels)):
result[i] = self._get_value(r, c)
if is_object_dtype(result):
result = lib.maybe_convert_objects(result)
return result
def _reindex_axes(self, axes, level, limit, tolerance, method, fill_value, copy):
frame = self
columns = axes["columns"]
if columns is not None:
frame = frame._reindex_columns(
columns, method, copy, level, fill_value, limit, tolerance
)
index = axes["index"]
if index is not None:
frame = frame._reindex_index(
index, method, copy, level, fill_value, limit, tolerance
)
return frame
def _reindex_index(
self,
new_index,
method,
copy,
level,
fill_value=np.nan,
limit=None,
tolerance=None,
):
new_index, indexer = self.index.reindex(
new_index, method=method, level=level, limit=limit, tolerance=tolerance
)
return self._reindex_with_indexers(
{0: [new_index, indexer]},
copy=copy,
fill_value=fill_value,
allow_dups=False,
)
def _reindex_columns(
self,
new_columns,
method,
copy,
level,
fill_value=None,
limit=None,
tolerance=None,
):
new_columns, indexer = self.columns.reindex(
new_columns, method=method, level=level, limit=limit, tolerance=tolerance
)
return self._reindex_with_indexers(
{1: [new_columns, indexer]},
copy=copy,
fill_value=fill_value,
allow_dups=False,
)
def _reindex_multi(self, axes, copy, fill_value) -> DataFrame:
new_index, row_indexer = self.index.reindex(axes["index"])
new_columns, col_indexer = self.columns.reindex(axes["columns"])
if row_indexer is not None and col_indexer is not None:
indexer = row_indexer, col_indexer
new_values = algorithms.take_2d_multi(
self.values, indexer, fill_value=fill_value
)
return self._constructor(new_values, index=new_index, columns=new_columns)
else:
return self._reindex_with_indexers(
{0: [new_index, row_indexer], 1: [new_columns, col_indexer]},
copy=copy,
fill_value=fill_value,
)
@doc(NDFrame.align, **_shared_doc_kwargs)
def align(
self,
other,
join="outer",
axis=None,
level=None,
copy=True,
fill_value=None,
method=None,
limit=None,
fill_axis=0,
broadcast_axis=None,
) -> DataFrame:
return super().align(
other,
join=join,
axis=axis,
level=level,
copy=copy,
fill_value=fill_value,
method=method,
limit=limit,
fill_axis=fill_axis,
broadcast_axis=broadcast_axis,
)
@Appender(
"""
Examples
--------
>>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
Change the row labels.
>>> df.set_axis(['a', 'b', 'c'], axis='index')
A B
a 1 4
b 2 5
c 3 6
Change the column labels.
>>> df.set_axis(['I', 'II'], axis='columns')
I II
0 1 4
1 2 5
2 3 6
Now, update the labels inplace.
>>> df.set_axis(['i', 'ii'], axis='columns', inplace=True)
>>> df
i ii
0 1 4
1 2 5
2 3 6
"""
)
@Substitution(
**_shared_doc_kwargs,
extended_summary_sub=" column or",
axis_description_sub=", and 1 identifies the columns",
see_also_sub=" or columns",
)
@Appender(NDFrame.set_axis.__doc__)
def set_axis(self, labels, axis: Axis = 0, inplace: bool = False):
return super().set_axis(labels, axis=axis, inplace=inplace)
@Substitution(**_shared_doc_kwargs)
@Appender(NDFrame.reindex.__doc__)
@rewrite_axis_style_signature(
"labels",
[
("method", None),
("copy", True),
("level", None),
("fill_value", np.nan),
("limit", None),
("tolerance", None),
],
)
def reindex(self, *args, **kwargs) -> DataFrame:
axes = validate_axis_style_args(self, args, kwargs, "labels", "reindex")
kwargs.update(axes)
kwargs.pop("axis", None)
kwargs.pop("labels", None)
return super().reindex(**kwargs)
def drop(
self,
labels=None,
axis=0,
index=None,
columns=None,
level=None,
inplace=False,
errors="raise",
):
return super().drop(
labels=labels,
axis=axis,
index=index,
columns=columns,
level=level,
inplace=inplace,
errors=errors,
)
@rewrite_axis_style_signature(
"mapper",
[("copy", True), ("inplace", False), ("level", None), ("errors", "ignore")],
)
def rename(
self,
mapper: Optional[Renamer] = None,
*,
index: Optional[Renamer] = None,
columns: Optional[Renamer] = None,
axis: Optional[Axis] = None,
copy: bool = True,
inplace: bool = False,
level: Optional[Level] = None,
errors: str = "ignore",
) -> Optional[DataFrame]:
return super().rename(
mapper=mapper,
index=index,
columns=columns,
axis=axis,
copy=copy,
inplace=inplace,
level=level,
errors=errors,
)
@doc(NDFrame.fillna, **_shared_doc_kwargs)
def fillna(
self,
value=None,
method=None,
axis=None,
inplace=False,
limit=None,
downcast=None,
) -> Optional[DataFrame]:
return super().fillna(
value=value,
method=method,
axis=axis,
inplace=inplace,
limit=limit,
downcast=downcast,
)
def pop(self, item: Label) -> Series:
return super().pop(item=item)
@doc(NDFrame.replace, **_shared_doc_kwargs)
def replace(
self,
to_replace=None,
value=None,
inplace=False,
limit=None,
regex=False,
method="pad",
):
return super().replace(
to_replace=to_replace,
value=value,
inplace=inplace,
limit=limit,
regex=regex,
method=method,
)
def _replace_columnwise(
self, mapping: Dict[Label, Tuple[Any, Any]], inplace: bool, regex
):
res = self if inplace else self.copy()
ax = self.columns
for i in range(len(ax)):
if ax[i] in mapping:
ser = self.iloc[:, i]
target, value = mapping[ax[i]]
newobj = ser.replace(target, value, regex=regex)
res.iloc[:, i] = newobj
if inplace:
return
return res.__finalize__(self)
@doc(NDFrame.shift, klass=_shared_doc_kwargs["klass"])
def shift(
self, periods=1, freq=None, axis=0, fill_value=lib.no_default
) -> DataFrame:
axis = self._get_axis_number(axis)
ncols = len(self.columns)
if axis == 1 and periods != 0 and fill_value is lib.no_default and ncols > 0:
if periods > 0:
result = self.iloc[:, :-periods]
for col in range(min(ncols, abs(periods))):
filler = self.iloc[:, 0].shift(len(self))
result.insert(0, col, filler, allow_duplicates=True)
else:
result = self.iloc[:, -periods:]
for col in range(min(ncols, abs(periods))):
filler = self.iloc[:, -1].shift(len(self))
result.insert(
len(result.columns), col, filler, allow_duplicates=True
)
result.columns = self.columns.copy()
return result
return super().shift(
periods=periods, freq=freq, axis=axis, fill_value=fill_value
)
def set_index(
self, keys, drop=True, append=False, inplace=False, verify_integrity=False
):
inplace = validate_bool_kwarg(inplace, "inplace")
self._check_inplace_and_allows_duplicate_labels(inplace)
if not isinstance(keys, list):
keys = [keys]
err_msg = (
'The parameter "keys" may be a column key, one-dimensional '
"array, or a list containing only valid column keys and "
"one-dimensional arrays."
)
missing: List[Label] = []
for col in keys:
if isinstance(col, (Index, Series, np.ndarray, list, abc.Iterator)):
if getattr(col, "ndim", 1) != 1:
raise ValueError(err_msg)
else:
try:
found = col in self.columns
except TypeError as err:
raise TypeError(
f"{err_msg}. Received column of type {type(col)}"
) from err
else:
if not found:
missing.append(col)
if missing:
raise KeyError(f"None of {missing} are in the columns")
if inplace:
frame = self
else:
frame = self.copy()
arrays = []
names: List[Label] = []
if append:
names = list(self.index.names)
if isinstance(self.index, MultiIndex):
for i in range(self.index.nlevels):
arrays.append(self.index._get_level_values(i))
else:
arrays.append(self.index)
to_remove: List[Label] = []
for col in keys:
if isinstance(col, MultiIndex):
for n in range(col.nlevels):
arrays.append(col._get_level_values(n))
names.extend(col.names)
elif isinstance(col, (Index, Series)):
arrays.append(col)
names.append(col.name)
elif isinstance(col, (list, np.ndarray)):
arrays.append(col)
names.append(None)
elif isinstance(col, abc.Iterator):
arrays.append(list(col))
names.append(None)
else:
arrays.append(frame[col]._values)
names.append(col)
if drop:
to_remove.append(col)
if len(arrays[-1]) != len(self):
raise ValueError(
f"Length mismatch: Expected {len(self)} rows, "
f"received array of length {len(arrays[-1])}"
)
index = ensure_index_from_sequences(arrays, names)
if verify_integrity and not index.is_unique:
duplicates = index[index.duplicated()].unique()
raise ValueError(f"Index has duplicate keys: {duplicates}")
for c in set(to_remove):
del frame[c]
index._cleanup()
frame.index = index
if not inplace:
return frame
@overload
def reset_index(
self,
level: Optional[Union[Hashable, Sequence[Hashable]]] = ...,
drop: bool = ...,
inplace: Literal[False] = ...,
col_level: Hashable = ...,
col_fill: Label = ...,
) -> DataFrame:
...
@overload
def reset_index(
self,
level: Optional[Union[Hashable, Sequence[Hashable]]] = ...,
drop: bool = ...,
inplace: Literal[True] = ...,
col_level: Hashable = ...,
col_fill: Label = ...,
) -> None:
...
def reset_index(
self,
level: Optional[Union[Hashable, Sequence[Hashable]]] = None,
drop: bool = False,
inplace: bool = False,
col_level: Hashable = 0,
col_fill: Label = "",
) -> Optional[DataFrame]:
inplace = validate_bool_kwarg(inplace, "inplace")
self._check_inplace_and_allows_duplicate_labels(inplace)
if inplace:
new_obj = self
else:
new_obj = self.copy()
new_index = ibase.default_index(len(new_obj))
if level is not None:
if not isinstance(level, (tuple, list)):
level = [level]
level = [self.index._get_level_number(lev) for lev in level]
if len(level) < self.index.nlevels:
new_index = self.index.droplevel(level)
if not drop:
to_insert: Iterable[Tuple[Any, Optional[Any]]]
if isinstance(self.index, MultiIndex):
names = [
(n if n is not None else f"level_{i}")
for i, n in enumerate(self.index.names)
]
to_insert = zip(self.index.levels, self.index.codes)
else:
default = "index" if "index" not in self else "level_0"
names = [default] if self.index.name is None else [self.index.name]
to_insert = ((self.index, None),)
multi_col = isinstance(self.columns, MultiIndex)
for i, (lev, lab) in reversed(list(enumerate(to_insert))):
if not (level is None or i in level):
continue
name = names[i]
if multi_col:
col_name = list(name) if isinstance(name, tuple) else [name]
if col_fill is None:
if len(col_name) not in (1, self.columns.nlevels):
raise ValueError(
"col_fill=None is incompatible "
f"with incomplete column name {name}"
)
col_fill = col_name[0]
lev_num = self.columns._get_level_number(col_level)
name_lst = [col_fill] * lev_num + col_name
missing = self.columns.nlevels - len(name_lst)
name_lst += [col_fill] * missing
name = tuple(name_lst)
level_values = maybe_casted_values(lev, lab)
new_obj.insert(0, name, level_values)
new_obj.index = new_index
if not inplace:
return new_obj
return None
@doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"])
def isna(self) -> DataFrame:
result = self._constructor(self._mgr.isna(func=isna))
return result.__finalize__(self, method="isna")
@doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"])
def isnull(self) -> DataFrame:
return self.isna()
@doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"])
def notna(self) -> DataFrame:
return ~self.isna()
@doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"])
def notnull(self) -> DataFrame:
return ~self.isna()
def dropna(self, axis=0, how="any", thresh=None, subset=None, inplace=False):
inplace = validate_bool_kwarg(inplace, "inplace")
if isinstance(axis, (tuple, list)):
raise TypeError("supplying multiple axes to axis is no longer supported.")
axis = self._get_axis_number(axis)
agg_axis = 1 - axis
agg_obj = self
if subset is not None:
ax = self._get_axis(agg_axis)
indices = ax.get_indexer_for(subset)
check = indices == -1
if check.any():
raise KeyError(list(np.compress(check, subset)))
agg_obj = self.take(indices, axis=agg_axis)
count = agg_obj.count(axis=agg_axis)
if thresh is not None:
mask = count >= thresh
elif how == "any":
mask = count == len(agg_obj._get_axis(agg_axis))
elif how == "all":
mask = count > 0
else:
if how is not None:
raise ValueError(f"invalid how option: {how}")
else:
raise TypeError("must specify how or thresh")
result = self.loc(axis=axis)[mask]
if inplace:
self._update_inplace(result)
else:
return result
def drop_duplicates(
self,
subset: Optional[Union[Hashable, Sequence[Hashable]]] = None,
keep: Union[str, bool] = "first",
inplace: bool = False,
ignore_index: bool = False,
) -> Optional[DataFrame]:
if self.empty:
return self.copy()
inplace = validate_bool_kwarg(inplace, "inplace")
ignore_index = validate_bool_kwarg(ignore_index, "ignore_index")
duplicated = self.duplicated(subset, keep=keep)
result = self[-duplicated]
if ignore_index:
result.index = ibase.default_index(len(result))
if inplace:
self._update_inplace(result)
return None
else:
return result
def duplicated(
self,
subset: Optional[Union[Hashable, Sequence[Hashable]]] = None,
keep: Union[str, bool] = "first",
) -> Series:
from pandas._libs.hashtable import SIZE_HINT_LIMIT, duplicated_int64
if self.empty:
return self._constructor_sliced(dtype=bool)
def f(vals):
labels, shape = algorithms.factorize(
vals, size_hint=min(len(self), SIZE_HINT_LIMIT)
)
return labels.astype("i8", copy=False), len(shape)
if subset is None:
subset = self.columns
elif (
not np.iterable(subset)
or isinstance(subset, str)
or isinstance(subset, tuple)
and subset in self.columns
):
subset = (subset,)
subset = cast(Iterable, subset)
# Verify all columns in subset exist in the queried dataframe
# Otherwise, raise a KeyError, same as if you try to __getitem__ with a
# key that doesn't exist.
diff = Index(subset).difference(self.columns)
if not diff.empty:
raise KeyError(diff)
vals = (col.values for name, col in self.items() if name in subset)
labels, shape = map(list, zip(*map(f, vals)))
ids = get_group_index(labels, shape, sort=False, xnull=False)
result = self._constructor_sliced(duplicated_int64(ids, keep), index=self.index)
return result.__finalize__(self, method="duplicated")
@Substitution(**_shared_doc_kwargs)
@Appender(NDFrame.sort_values.__doc__)
def sort_values(
self,
by,
axis=0,
ascending=True,
inplace=False,
kind="quicksort",
na_position="last",
ignore_index=False,
key: ValueKeyFunc = None,
):
inplace = validate_bool_kwarg(inplace, "inplace")
axis = self._get_axis_number(axis)
if not isinstance(by, list):
by = [by]
if is_sequence(ascending) and len(by) != len(ascending):
raise ValueError(
f"Length of ascending ({len(ascending)}) != length of by ({len(by)})"
)
if len(by) > 1:
keys = [self._get_label_or_level_values(x, axis=axis) for x in by]
if key is not None:
keys = [Series(k, name=name) for (k, name) in zip(keys, by)]
indexer = lexsort_indexer(
keys, orders=ascending, na_position=na_position, key=key
)
indexer = ensure_platform_int(indexer)
else:
by = by[0]
k = self._get_label_or_level_values(by, axis=axis)
if key is not None:
k = Series(k, name=by)
if isinstance(ascending, (tuple, list)):
ascending = ascending[0]
indexer = nargsort(
k, kind=kind, ascending=ascending, na_position=na_position, key=key
)
new_data = self._mgr.take(
indexer, axis=self._get_block_manager_axis(axis), verify=False
)
if ignore_index:
new_data.axes[1] = ibase.default_index(len(indexer))
result = self._constructor(new_data)
if inplace:
return self._update_inplace(result)
else:
return result.__finalize__(self, method="sort_values")
def sort_index(
self,
axis=0,
level=None,
ascending: bool = True,
inplace: bool = False,
kind: str = "quicksort",
na_position: str = "last",
sort_remaining: bool = True,
ignore_index: bool = False,
key: IndexKeyFunc = None,
):
return super().sort_index(
axis,
level,
ascending,
inplace,
kind,
na_position,
sort_remaining,
ignore_index,
key,
)
def value_counts(
self,
subset: Optional[Sequence[Label]] = None,
normalize: bool = False,
sort: bool = True,
ascending: bool = False,
):
if subset is None:
subset = self.columns.tolist()
counts = self.groupby(subset).grouper.size()
if sort:
counts = counts.sort_values(ascending=ascending)
if normalize:
counts /= counts.sum()
if len(subset) == 1:
counts.index = MultiIndex.from_arrays(
[counts.index], names=[counts.index.name]
)
return counts
def nlargest(self, n, columns, keep="first") -> DataFrame:
return algorithms.SelectNFrame(self, n=n, keep=keep, columns=columns).nlargest()
def nsmallest(self, n, columns, keep="first") -> DataFrame:
return algorithms.SelectNFrame(
self, n=n, keep=keep, columns=columns
).nsmallest()
def swaplevel(self, i=-2, j=-1, axis=0) -> DataFrame:
result = self.copy()
axis = self._get_axis_number(axis)
if not isinstance(result._get_axis(axis), MultiIndex):
raise TypeError("Can only swap levels on a hierarchical axis.")
if axis == 0:
assert isinstance(result.index, MultiIndex)
result.index = result.index.swaplevel(i, j)
else:
assert isinstance(result.columns, MultiIndex)
result.columns = result.columns.swaplevel(i, j)
return result
def reorder_levels(self, order, axis=0) -> DataFrame:
axis = self._get_axis_number(axis)
if not isinstance(self._get_axis(axis), MultiIndex):
raise TypeError("Can only reorder levels on a hierarchical axis.")
result = self.copy()
if axis == 0:
assert isinstance(result.index, MultiIndex)
result.index = result.index.reorder_levels(order)
else:
assert isinstance(result.columns, MultiIndex)
result.columns = result.columns.reorder_levels(order)
return result
def _cmp_method(self, other, op):
axis = 1
self, other = ops.align_method_FRAME(self, other, axis, flex=False, level=None)
p(other, op, axis=axis)
return self._construct_result(new_data)
def _arith_method(self, other, op):
if ops.should_reindex_frame_op(self, other, op, 1, 1, None, None):
return ops.frame_arith_method_with_reindex(self, other, op)
axis = 1
self, other = ops.align_method_FRAME(self, other, axis, flex=True, level=None)
new_data = self._dispatch_frame_op(other, op, axis=axis)
return self._construct_result(new_data)
_logical_method = _arith_method
def _dispatch_frame_op(self, right, func, axis: Optional[int] = None):
array_op = ops.get_array_op(func)
right = lib.item_from_zerodim(right)
if not is_list_like(right):
# i.e. scalar, faster than checking np.ndim(right) == 0
bm = self._mgr.apply(array_op, right=right)
return type(self)(bm)
elif isinstance(right, DataFrame):
assert self.index.equals(right.index)
assert self.columns.equals(right.columns)
# TODO: The previous assertion `assert right._indexed_same(self)`
# fails in cases with empty columns reached via
# _frame_arith_method_with_reindex
bm = self._mgr.operate_blockwise(right._mgr, array_op)
return type(self)(bm)
elif isinstance(right, Series) and axis == 1:
# axis=1 means we want to operate row-by-row
assert right.index.equals(self.columns)
right = right._values
# maybe_align_as_frame ensures we do not have an ndarray here
assert not isinstance(right, np.ndarray)
arrays = [
array_op(_left, _right)
for _left, _right in zip(self._iter_column_arrays(), right)
]
elif isinstance(right, Series):
assert right.index.equals(self.index) # Handle other cases later
right = right._values
arrays = [array_op(left, right) for left in self._iter_column_arrays()]
else:
# Remaining cases have less-obvious dispatch rules
raise NotImplementedError(right)
return type(self)._from_arrays(
arrays, self.columns, self.index, verify_integrity=False
)
def _combine_frame(self, other: DataFrame, func, fill_value=None):
# at this point we have `self._indexed_same(other)`
if fill_value is None:
# since _arith_op may be called in a loop, avoid function call
# overhead if possible by doing this check once
_arith_op = func
else:
def _arith_op(left, right):
# for the mixed_type case where we iterate over columns,
# _arith_op(left, right) is equivalent to
# left._binop(right, func, fill_value=fill_value)
left, right = ops.fill_binop(left, right, fill_value)
return func(left, right)
new_data = self._dispatch_frame_op(other, _arith_op)
return new_data
def _construct_result(self, result) -> DataFrame:
out = self._constructor(result, copy=False)
# Pin columns instead of passing to constructor for compat with
# non-unique columns case
out.columns = self.columns
out.index = self.index
return out
def __divmod__(self, other) -> Tuple[DataFrame, DataFrame]:
# Naive implementation, room for optimization
div = self // other
mod = self - div * other
return div, mod
def __rdivmod__(self, other) -> Tuple[DataFrame, DataFrame]:
# Naive implementation, room for optimization
div = other // self
mod = other - div * self
return div, mod
# ----------------------------------------------------------------------
# Combination-Related
@doc(
_shared_docs["compare"],
"""
Returns
-------
DataFrame
DataFrame that shows the differences stacked side by side.
The resulting index will be a MultiIndex with 'self' and 'other'
stacked alternately at the inner level.
Raises
------
ValueError
When the two DataFrames don't have identical labels or shape.
See Also
--------
Series.compare : Compare with another Series and show differences.
DataFrame.equals : Test whether two objects contain the same elements.
Notes
-----
Matching NaNs will not appear as a difference.
Can only compare identically-labeled
(i.e. same shape, identical row and column labels) DataFrames
Examples
--------
>>> df = pd.DataFrame(
... {{
... "col1": ["a", "a", "b", "b", "a"],
... "col2": [1.0, 2.0, 3.0, np.nan, 5.0],
... "col3": [1.0, 2.0, 3.0, 4.0, 5.0]
... }},
... columns=["col1", "col2", "col3"],
... )
>>> df
col1 col2 col3
0 a 1.0 1.0
1 a 2.0 2.0
2 b 3.0 3.0
3 b NaN 4.0
4 a 5.0 5.0
>>> df2 = df.copy()
>>> df2.loc[0, 'col1'] = 'c'
>>> df2.loc[2, 'col3'] = 4.0
>>> df2
col1 col2 col3
0 c 1.0 1.0
1 a 2.0 2.0
2 b 3.0 4.0
3 b NaN 4.0
4 a 5.0 5.0
Align the differences on columns
>>> df.compare(df2)
col1 col3
self other self other
0 a c NaN NaN
2 NaN NaN 3.0 4.0
Stack the differences on rows
>>> df.compare(df2, align_axis=0)
col1 col3
0 self a NaN
other c NaN
2 self NaN 3.0
other NaN 4.0
Keep the equal values
>>> df.compare(df2, keep_equal=True)
col1 col3
self other self other
0 a c 1.0 1.0
2 b b 3.0 4.0
Keep all original rows and columns
>>> df.compare(df2, keep_shape=True)
col1 col2 col3
self other self other self other
0 a c NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN 3.0 4.0
3 NaN NaN NaN NaN NaN NaN
4 NaN NaN NaN NaN NaN NaN
Keep all original rows and columns and also all original values
>>> df.compare(df2, keep_shape=True, keep_equal=True)
col1 col2 col3
self other self other self other
0 a c 1.0 1.0 1.0 1.0
1 a a 2.0 2.0 2.0 2.0
2 b b 3.0 3.0 3.0 4.0
3 b b NaN NaN 4.0 4.0
4 a a 5.0 5.0 5.0 5.0
""",
klass=_shared_doc_kwargs["klass"],
)
def compare(
self,
other: DataFrame,
align_axis: Axis = 1,
keep_shape: bool = False,
keep_equal: bool = False,
) -> DataFrame:
return super().compare(
other=other,
align_axis=align_axis,
keep_shape=keep_shape,
keep_equal=keep_equal,
)
def combine(
self, other: DataFrame, func, fill_value=None, overwrite=True
) -> DataFrame:
other_idxlen = len(other.index)
this, other = self.align(other, copy=False)
new_index = this.index
if other.empty and len(new_index) == len(self.index):
return self.copy()
if self.empty and len(other) == other_idxlen:
return other.copy()
new_columns = this.columns.union(other.columns)
do_fill = fill_value is not None
result = {}
for col in new_columns:
series = this[col]
otherSeries = other[col]
this_dtype = series.dtype
other_dtype = otherSeries.dtype
this_mask = isna(series)
other_mask = isna(otherSeries)
# DO propagate if this column is not in the intersection
if not overwrite and other_mask.all():
result[col] = this[col].copy()
continue
if do_fill:
series = series.copy()
otherSeries = otherSeries.copy()
series[this_mask] = fill_value
otherSeries[other_mask] = fill_value
if col not in self.columns:
# If self DataFrame does not have col in other DataFrame,
# try to promote series, which is all NaN, as other_dtype.
new_dtype = other_dtype
try:
series = series.astype(new_dtype, copy=False)
except ValueError:
# e.g. new_dtype is integer types
pass
else:
# if we have different dtypes, possibly promote
new_dtype = find_common_type([this_dtype, other_dtype])
if not is_dtype_equal(this_dtype, new_dtype):
series = series.astype(new_dtype)
if not is_dtype_equal(other_dtype, new_dtype):
otherSeries = otherSeries.astype(new_dtype)
arr = func(series, otherSeries)
arr = maybe_downcast_to_dtype(arr, new_dtype)
result[col] = arr
# convert_objects just in case
return self._constructor(result, index=new_index, columns=new_columns)
def combine_first(self, other: DataFrame) -> DataFrame:
import pandas.core.computation.expressions as expressions
def combiner(x, y):
mask = extract_array(isna(x))
x_values = extract_array(x, extract_numpy=True)
y_values = extract_array(y, extract_numpy=True)
# If the column y in other DataFrame is not in first DataFrame,
# just return y_values.
if y.name not in self.columns:
return y_values
return expressions.where(mask, y_values, x_values)
return self.combine(other, combiner, overwrite=False)
def update(
self, other, join="left", overwrite=True, filter_func=None, errors="ignore"
) -> None:
import pandas.core.computation.expressions as expressions
# TODO: Support other joins
if join != "left": # pragma: no cover
raise NotImplementedError("Only left join is supported")
if errors not in ["ignore", "raise"]:
raise ValueError("The parameter errors must be either 'ignore' or 'raise'")
if not isinstance(other, DataFrame):
other = DataFrame(other)
other = other.reindex_like(self)
for col in self.columns:
this = self[col]._values
that = other[col]._values
if filter_func is not None:
with np.errstate(all="ignore"):
mask = ~filter_func(this) | isna(that)
else:
if errors == "raise":
mask_this = notna(that)
mask_that = notna(this)
if any(mask_this & mask_that):
raise ValueError("Data overlaps.")
if overwrite:
mask = isna(that)
else:
mask = notna(this)
# don't overwrite columns unnecessarily
if mask.all():
continue
self[col] = expressions.where(mask, this, that)
@Appender(
"""
Examples
--------
>>> df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',
... 'Parrot', 'Parrot'],
... 'Max Speed': [380., 370., 24., 26.]})
>>> df
Animal Max Speed
0 Falcon 380.0
1 Falcon 370.0
2 Parrot 24.0
3 Parrot 26.0
>>> df.groupby(['Animal']).mean()
Max Speed
Animal
Falcon 375.0
Parrot 25.0
**Hierarchical Indexes**
We can groupby different levels of a hierarchical index
using the `level` parameter:
>>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'],
... ['Captive', 'Wild', 'Captive', 'Wild']]
>>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type'))
>>> df = pd.DataFrame({'Max Speed': [390., 350., 30., 20.]},
... index=index)
>>> df
Max Speed
Animal Type
Falcon Captive 390.0
Wild 350.0
Parrot Captive 30.0
Wild 20.0
>>> df.groupby(level=0).mean()
Max Speed
Animal
Falcon 370.0
Parrot 25.0
>>> df.groupby(level="Type").mean()
Max Speed
Type
Captive 210.0
Wild 185.0
We can also choose to include NA in group keys or not by setting
`dropna` parameter, the default setting is `True`:
>>> l = [[1, 2, 3], [1, None, 4], [2, 1, 3], [1, 2, 2]]
>>> df = pd.DataFrame(l, columns=["a", "b", "c"])
>>> df.groupby(by=["b"]).sum()
a c
b
1.0 2 3
2.0 2 5
>>> df.groupby(by=["b"], dropna=False).sum()
a c
b
1.0 2 3
2.0 2 5
NaN 1 4
>>> l = [["a", 12, 12], [None, 12.3, 33.], ["b", 12.3, 123], ["a", 1, 1]]
>>> df = pd.DataFrame(l, columns=["a", "b", "c"])
>>> df.groupby(by="a").sum()
b c
a
a 13.0 13.0
b 12.3 123.0
>>> df.groupby(by="a", dropna=False).sum()
b c
a
a 13.0 13.0
b 12.3 123.0
NaN 12.3 33.0
"""
)
@Appender(_shared_docs["groupby"] % _shared_doc_kwargs)
def groupby(
self,
by=None,
axis=0,
level=None,
as_index: bool = True,
sort: bool = True,
group_keys: bool = True,
squeeze: bool = no_default,
observed: bool = False,
dropna: bool = True,
) -> DataFrameGroupBy:
from pandas.core.groupby.generic import DataFrameGroupBy
if squeeze is not no_default:
warnings.warn(
(
"The `squeeze` parameter is deprecated and "
"will be removed in a future version."
),
FutureWarning,
stacklevel=2,
)
else:
squeeze = False
if level is None and by is None:
raise TypeError("You have to supply one of 'by' and 'level'")
axis = self._get_axis_number(axis)
return DataFrameGroupBy(
obj=self,
keys=by,
axis=axis,
level=level,
as_index=as_index,
sort=sort,
group_keys=group_keys,
squeeze=squeeze,
observed=observed,
dropna=dropna,
)
_shared_docs[
"pivot"
] = """
Return reshaped DataFrame organized by given index / column values.
Reshape data (produce a "pivot" table) based on column values. Uses
unique values from specified `index` / `columns` to form axes of the
resulting DataFrame. This function does not support data
aggregation, multiple values will result in a MultiIndex in the
columns. See the :ref:`User Guide <reshaping>` for more on reshaping.
Parameters
----------%s
index : str or object or a list of str, optional
Column to use to make new frame's index. If None, uses
existing index.
.. versionchanged:: 1.1.0
Also accept list of index names.
columns : str or object or a list of str
Column to use to make new frame's columns.
.. versionchanged:: 1.1.0
Also accept list of columns names.
values : str, object or a list of the previous, optional
Column(s) to use for populating new frame's values. If not
specified, all remaining columns will be used and the result will
have hierarchically indexed columns.
Returns
-------
DataFrame
Returns reshaped DataFrame.
Raises
------
ValueError:
When there are any `index`, `columns` combinations with multiple
values. `DataFrame.pivot_table` when you need to aggregate.
See Also
--------
DataFrame.pivot_table : Generalization of pivot that can handle
duplicate values for one index/column pair.
DataFrame.unstack : Pivot based on the index values instead of a
column.
wide_to_long : Wide panel to long format. Less flexible but more
user-friendly than melt.
Notes
-----
For finer-tuned control, see hierarchical indexing documentation along
with the related stack/unstack methods.
Examples
--------
>>> df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two',
... 'two'],
... 'bar': ['A', 'B', 'C', 'A', 'B', 'C'],
... 'baz': [1, 2, 3, 4, 5, 6],
... 'zoo': ['x', 'y', 'z', 'q', 'w', 't']})
>>> df
foo bar baz zoo
0 one A 1 x
1 one B 2 y
2 one C 3 z
3 two A 4 q
4 two B 5 w
5 two C 6 t
>>> df.pivot(index='foo', columns='bar', values='baz')
bar A B C
foo
one 1 2 3
two 4 5 6
>>> df.pivot(index='foo', columns='bar')['baz']
bar A B C
foo
one 1 2 3
two 4 5 6
>>> df.pivot(index='foo', columns='bar', values=['baz', 'zoo'])
baz zoo
bar A B C A B C
foo
one 1 2 3 x y z
two 4 5 6 q w t
You could also assign a list of column names or a list of index names.
>>> df = pd.DataFrame({
... "lev1": [1, 1, 1, 2, 2, 2],
... "lev2": [1, 1, 2, 1, 1, 2],
... "lev3": [1, 2, 1, 2, 1, 2],
... "lev4": [1, 2, 3, 4, 5, 6],
... "values": [0, 1, 2, 3, 4, 5]})
>>> df
lev1 lev2 lev3 lev4 values
0 1 1 1 1 0
1 1 1 2 2 1
2 1 2 1 3 2
3 2 1 2 4 3
4 2 1 1 5 4
5 2 2 2 6 5
>>> df.pivot(index="lev1", columns=["lev2", "lev3"],values="values")
lev2 1 2
lev3 1 2 1 2
lev1
1 0.0 1.0 2.0 NaN
2 4.0 3.0 NaN 5.0
>>> df.pivot(index=["lev1", "lev2"], columns=["lev3"],values="values")
lev3 1 2
lev1 lev2
1 1 0.0 1.0
2 2.0 NaN
2 1 4.0 3.0
2 NaN 5.0
A ValueError is raised if there are any duplicates.
>>> df = pd.DataFrame({"foo": ['one', 'one', 'two', 'two'],
... "bar": ['A', 'A', 'B', 'C'],
... "baz": [1, 2, 3, 4]})
>>> df
foo bar baz
0 one A 1
1 one A 2
2 two B 3
3 two C 4
Notice that the first two rows are the same for our `index`
and `columns` arguments.
>>> df.pivot(index='foo', columns='bar', values='baz')
Traceback (most recent call last):
...
ValueError: Index contains duplicate entries, cannot reshape
"""
@Substitution("")
@Appender(_shared_docs["pivot"])
def pivot(self, index=None, columns=None, values=None) -> DataFrame:
from pandas.core.reshape.pivot import pivot
return pivot(self, index=index, columns=columns, values=values)
_shared_docs[
"pivot_table"
] = """
Create a spreadsheet-style pivot table as a DataFrame.
The levels in the pivot table will be stored in MultiIndex objects
(hierarchical indexes) on the index and columns of the result DataFrame.
Parameters
----------%s
values : column to aggregate, optional
index : column, Grouper, array, or list of the previous
If an array is passed, it must be the same length as the data. The
list can contain any of the other types (except list).
Keys to group by on the pivot table index. If an array is passed,
it is being used as the same manner as column values.
columns : column, Grouper, array, or list of the previous
If an array is passed, it must be the same length as the data. The
list can contain any of the other types (except list).
Keys to group by on the pivot table column. If an array is passed,
it is being used as the same manner as column values.
aggfunc : function, list of functions, dict, default numpy.mean
If list of functions passed, the resulting pivot table will have
hierarchical columns whose top level are the function names
(inferred from the function objects themselves)
If dict is passed, the key is column to aggregate and value
is function or list of functions.
fill_value : scalar, default None
Value to replace missing values with (in the resulting pivot table,
after aggregation).
margins : bool, default False
Add all row / columns (e.g. for subtotal / grand totals).
dropna : bool, default True
Do not include columns whose entries are all NaN.
margins_name : str, default 'All'
Name of the row / column that will contain the totals
when margins is True.
observed : bool, default False
This only applies if any of the groupers are Categoricals.
If True: only show observed values for categorical groupers.
If False: show all values for categorical groupers.
.. versionchanged:: 0.25.0
Returns
-------
DataFrame
An Excel style pivot table.
See Also
--------
DataFrame.pivot : Pivot without aggregation that can handle
non-numeric data.
DataFrame.melt: Unpivot a DataFrame from wide to long format,
optionally leaving identifiers set.
wide_to_long : Wide panel to long format. Less flexible but more
user-friendly than melt.
Examples
--------
>>> df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
... "bar", "bar", "bar", "bar"],
... "B": ["one", "one", "one", "two", "two",
... "one", "one", "two", "two"],
... "C": ["small", "large", "large", "small",
... "small", "large", "small", "small",
... "large"],
... "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
... "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
>>> df
A B C D E
0 foo one small 1 2
1 foo one large 2 4
2 foo one large 2 5
3 foo two small 3 5
4 foo two small 3 6
5 bar one large 4 6
6 bar one small 5 8
7 bar two small 6 9
8 bar two large 7 9
This first example aggregates values by taking the sum.
>>> table = pd.pivot_table(df, values='D', index=['A', 'B'],
... columns=['C'], aggfunc=np.sum)
>>> table
C large small
A B
bar one 4.0 5.0
two 7.0 6.0
foo one 4.0 1.0
two NaN 6.0
We can also fill missing values using the `fill_value` parameter.
>>> table = pd.pivot_table(df, values='D', index=['A', 'B'],
... columns=['C'], aggfunc=np.sum, fill_value=0)
>>> table
C large small
A B
bar one 4 5
two 7 6
foo one 4 1
two 0 6
The next example aggregates by taking the mean across multiple columns.
>>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],
... aggfunc={'D': np.mean,
... 'E': np.mean})
>>> table
D E
A C
bar large 5.500000 7.500000
small 5.500000 8.500000
foo large 2.000000 4.500000
small 2.333333 4.333333
We can also calculate multiple types of aggregations for any given
value column.
>>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],
... aggfunc={'D': np.mean,
... 'E': [min, max, np.mean]})
>>> table
D E
mean max mean min
A C
bar large 5.500000 9.0 7.500000 6.0
small 5.500000 9.0 8.500000 8.0
foo large 2.000000 5.0 4.500000 4.0
small 2.333333 6.0 4.333333 2.0
"""
@Substitution("")
@Appender(_shared_docs["pivot_table"])
def pivot_table(
self,
values=None,
index=None,
columns=None,
aggfunc="mean",
fill_value=None,
margins=False,
dropna=True,
margins_name="All",
observed=False,
) -> DataFrame:
from pandas.core.reshape.pivot import pivot_table
return pivot_table(
self,
values=values,
index=index,
columns=columns,
aggfunc=aggfunc,
fill_value=fill_value,
margins=margins,
dropna=dropna,
margins_name=margins_name,
observed=observed,
)
def stack(self, level=-1, dropna=True):
from pandas.core.reshape.reshape import stack, stack_multiple
if isinstance(level, (tuple, list)):
result = stack_multiple(self, level, dropna=dropna)
else:
result = stack(self, level, dropna=dropna)
return result.__finalize__(self, method="stack")
def explode(
self, column: Union[str, Tuple], ignore_index: bool = False
) -> DataFrame:
if not (is_scalar(column) or isinstance(column, tuple)):
raise ValueError("column must be a scalar")
if not self.columns.is_unique:
raise ValueError("columns must be unique")
df = self.reset_index(drop=True)
result = df[column].explode()
result = df.drop([column], axis=1).join(result)
if ignore_index:
result.index = ibase.default_index(len(result))
else:
result.index = self.index.take(result.index)
result = result.reindex(columns=self.columns, copy=False)
return result
def unstack(self, level=-1, fill_value=None):
from pandas.core.reshape.reshape import unstack
result = unstack(self, level, fill_value)
return result.__finalize__(self, method="unstack")
@Appender(_shared_docs["melt"] % {"caller": "df.melt(", "other": "melt"})
def melt(
self,
id_vars=None,
value_vars=None,
var_name=None,
value_name="value",
col_level=None,
ignore_index=True,
) -> DataFrame:
return melt(
self,
id_vars=id_vars,
value_vars=value_vars,
var_name=var_name,
value_name=value_name,
col_level=col_level,
ignore_index=ignore_index,
)
# ----------------------------------------------------------------------
# Time series-related
@doc(
Series.diff,
klass="Dataframe",
extra_params="axis : {0 or 'index', 1 or 'columns'}, default 0\n "
"Take difference over rows (0) or columns (1).\n",
other_klass="Series",
examples=dedent(
"""
Difference with previous row
>>> df = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6],
... 'b': [1, 1, 2, 3, 5, 8],
... 'c': [1, 4, 9, 16, 25, 36]})
>>> df
a b c
0 1 1 1
1 2 1 4
2 3 2 9
3 4 3 16
4 5 5 25
5 6 8 36
>>> df.diff()
a b c
0 NaN NaN NaN
1 1.0 0.0 3.0
2 1.0 1.0 5.0
3 1.0 1.0 7.0
4 1.0 2.0 9.0
5 1.0 3.0 11.0
Difference with previous column
>>> df.diff(axis=1)
a b c
0 NaN 0 0
1 NaN -1 3
2 NaN -1 7
3 NaN -1 13
4 NaN 0 20
5 NaN 2 28
Difference with 3rd previous row
>>> df.diff(periods=3)
a b c
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 3.0 2.0 15.0
4 3.0 4.0 21.0
5 3.0 6.0 27.0
Difference with following row
>>> df.diff(periods=-1)
a b c
0 -1.0 0.0 -3.0
1 -1.0 -1.0 -5.0
2 -1.0 -1.0 -7.0
3 -1.0 -2.0 -9.0
4 -1.0 -3.0 -11.0
5 NaN NaN NaN
Overflow in input dtype
>>> df = pd.DataFrame({'a': [1, 0]}, dtype=np.uint8)
>>> df.diff()
a
0 NaN
1 255.0"""
),
)
def diff(self, periods: int = 1, axis: Axis = 0) -> DataFrame:
if not isinstance(periods, int):
if not (is_float(periods) and periods.is_integer()):
raise ValueError("periods must be an integer")
periods = int(periods)
bm_axis = self._get_block_manager_axis(axis)
if bm_axis == 0 and periods != 0:
return self - self.shift(periods, axis=axis)
new_data = self._mgr.diff(n=periods, axis=bm_axis)
return self._constructor(new_data).__finalize__(self, "diff")
# ----------------------------------------------------------------------
# Function application
def _gotitem(
self,
key: Union[Label, List[Label]],
ndim: int,
subset: Optional[FrameOrSeriesUnion] = None,
) -> FrameOrSeriesUnion:
if subset is None:
subset = self
elif subset.ndim == 1: # is Series
return subset
# TODO: _shallow_copy(subset)?
return subset[key]
_agg_summary_and_see_also_doc = dedent(
"""
The aggregation operations are always performed over an axis, either the
index (default) or the column axis. This behavior is different from
`numpy` aggregation functions (`mean`, `median`, `prod`, `sum`, `std`,
`var`), where the default is to compute the aggregation of the flattened
array, e.g., ``numpy.mean(arr_2d)`` as opposed to
``numpy.mean(arr_2d, axis=0)``.
`agg` is an alias for `aggregate`. Use the alias.
See Also
--------
DataFrame.apply : Perform any type of operations.
DataFrame.transform : Perform transformation type operations.
core.groupby.GroupBy : Perform operations over groups.
core.resample.Resampler : Perform operations over resampled bins.
core.window.Rolling : Perform operations over rolling window.
core.window.Expanding : Perform operations over expanding window.
core.window.ExponentialMovingWindow : Perform operation over exponential weighted
window.
"""
)
_agg_examples_doc = dedent(
"""
Examples
--------
>>> df = pd.DataFrame([[1, 2, 3],
... [4, 5, 6],
... [7, 8, 9],
... [np.nan, np.nan, np.nan]],
... columns=['A', 'B', 'C'])
Aggregate these functions over the rows.
>>> df.agg(['sum', 'min'])
A B C
sum 12.0 15.0 18.0
min 1.0 2.0 3.0
Different aggregations per column.
>>> df.agg({'A' : ['sum', 'min'], 'B' : ['min', 'max']})
A B
sum 12.0 NaN
min 1.0 2.0
max NaN 8.0
Aggregate different functions over the columns and rename the index of the resulting
DataFrame.
>>> df.agg(x=('A', max), y=('B', 'min'), z=('C', np.mean))
A B C
x 7.0 NaN NaN
y NaN 2.0 NaN
z NaN NaN 6.0
Aggregate over the columns.
>>> df.agg("mean", axis="columns")
0 2.0
1 5.0
2 8.0
3 NaN
dtype: float64
"""
)
@doc(
_shared_docs["aggregate"],
klass=_shared_doc_kwargs["klass"],
axis=_shared_doc_kwargs["axis"],
see_also=_agg_summary_and_see_also_doc,
examples=_agg_examples_doc,
)
def aggregate(self, func=None, axis=0, *args, **kwargs):
axis = self._get_axis_number(axis)
relabeling, func, columns, order = reconstruct_func(func, **kwargs)
result = None
try:
result, how = self._aggregate(func, axis, *args, **kwargs)
except TypeError as err:
exc = TypeError(
"DataFrame constructor called with "
f"incompatible data and dtype: {err}"
)
raise exc from err
if result is None:
return self.apply(func, axis=axis, args=args, **kwargs)
if relabeling:
# This is to keep the order to columns occurrence unchanged, and also
# keep the order of new columns occurrence unchanged
# For the return values of reconstruct_func, if relabeling is
# False, columns and order will be None.
assert columns is not None
assert order is not None
result_in_dict = relabel_result(result, func, columns, order)
result = DataFrame(result_in_dict, index=columns)
return result
def _aggregate(self, arg, axis=0, *args, **kwargs):
if axis == 1:
# NDFrame.aggregate returns a tuple, and we need to transpose
# only result
result, how = aggregate(self.T, arg, *args, **kwargs)
result = result.T if result is not None else result
return result, how
return aggregate(self, arg, *args, **kwargs)
agg = aggregate
@doc(
_shared_docs["transform"],
klass=_shared_doc_kwargs["klass"],
axis=_shared_doc_kwargs["axis"],
)
def transform(
self, func: AggFuncType, axis: Axis = 0, *args, **kwargs
) -> DataFrame:
result = transform(self, func, axis, *args, **kwargs)
assert isinstance(result, DataFrame)
return result
def apply(self, func, axis=0, raw=False, result_type=None, args=(), **kwds):
from pandas.core.apply import frame_apply
op = frame_apply(
self,
func=func,
axis=axis,
raw=raw,
result_type=result_type,
args=args,
kwds=kwds,
)
return op.get_result()
def applymap(self, func, na_action: Optional[str] = None) -> DataFrame:
if na_action not in {"ignore", None}:
raise ValueError(
f"na_action must be 'ignore' or None. Got {repr(na_action)}"
)
ignore_na = na_action == "ignore"
# if we have a dtype == 'M8[ns]', provide boxed values
def infer(x):
if x.empty:
return lib.map_infer(x, func, ignore_na=ignore_na)
return lib.map_infer(x.astype(object)._values, func, ignore_na=ignore_na)
return self.apply(infer).__finalize__(self, "applymap")
# ----------------------------------------------------------------------
# Merging / joining methods
def append(
self, other, ignore_index=False, verify_integrity=False, sort=False
) -> DataFrame:
if isinstance(other, (Series, dict)):
if isinstance(other, dict):
if not ignore_index:
raise TypeError("Can only append a dict if ignore_index=True")
other = Series(other)
if other.name is None and not ignore_index:
raise TypeError(
"Can only append a Series if ignore_index=True "
"or if the Series has a name"
)
index = Index([other.name], name=self.index.name)
idx_diff = other.index.difference(self.columns)
try:
combined_columns = self.columns.append(idx_diff)
except TypeError:
combined_columns = self.columns.astype(object).append(idx_diff)
other = (
other.reindex(combined_columns, copy=False)
.to_frame()
.T.infer_objects()
.rename_axis(index.names, copy=False)
)
if not self.columns.equals(combined_columns):
self = self.reindex(columns=combined_columns)
elif isinstance(other, list):
if not other:
pass
elif not isinstance(other[0], DataFrame):
other = DataFrame(other)
if (self.columns.get_indexer(other.columns) >= 0).all():
other = other.reindex(columns=self.columns)
from pandas.core.reshape.concat import concat
if isinstance(other, (list, tuple)):
to_concat = [self, *other]
else:
to_concat = [self, other]
return (
concat(
to_concat,
ignore_index=ignore_index,
verify_integrity=verify_integrity,
sort=sort,
)
).__finalize__(self, method="append")
def join(
self, other, on=None, how="left", lsuffix="", rsuffix="", sort=False
) -> DataFrame:
return self._join_compat(
other, on=on, how=how, lsuffix=lsuffix, rsuffix=rsuffix, sort=sort
)
def _join_compat(
self, other, on=None, how="left", lsuffix="", rsuffix="", sort=False
):
from pandas.core.reshape.concat import concat
from pandas.core.reshape.merge import merge
if isinstance(other, Series):
if other.name is None:
raise ValueError("Other Series must have a name")
other = DataFrame({other.name: other})
if isinstance(other, DataFrame):
if how == "cross":
return merge(
self,
other,
how=how,
on=on,
suffixes=(lsuffix, rsuffix),
sort=sort,
)
return merge(
self,
other,
left_on=on,
how=how,
left_index=on is None,
right_index=True,
suffixes=(lsuffix, rsuffix),
sort=sort,
)
else:
if on is not None:
raise ValueError(
"Joining multiple DataFrames only supported for joining on index"
)
frames = [self] + list(other)
can_concat = all(df.index.is_unique for df in frames)
# join indexes only using concat
if can_concat:
if how == "left":
res = concat(
frames, axis=1, join="outer", verify_integrity=True, sort=sort
)
return res.reindex(self.index, copy=False)
else:
return concat(
frames, axis=1, join=how, verify_integrity=True, sort=sort
)
joined = frames[0]
for frame in frames[1:]:
joined = merge(
joined, frame, how=how, left_index=True, right_index=True
)
return joined
@Substitution("")
@Appender(_merge_doc, indents=2)
def merge(
self,
right,
how="inner",
on=None,
left_on=None,
right_on=None,
left_index=False,
right_index=False,
sort=False,
suffixes=("_x", "_y"),
copy=True,
indicator=False,
validate=None,
) -> DataFrame:
from pandas.core.reshape.merge import merge
return merge(
self,
right,
how=how,
on=on,
left_on=left_on,
right_on=right_on,
left_index=left_index,
right_index=right_index,
sort=sort,
suffixes=suffixes,
copy=copy,
indicator=indicator,
validate=validate,
)
def round(self, decimals=0, *args, **kwargs) -> DataFrame:
from pandas.core.reshape.concat import concat
def _dict_round(df, decimals):
for col, vals in df.items():
try:
yield _series_round(vals, decimals[col])
except KeyError:
yield vals
def _series_round(s, decimals):
if is_integer_dtype(s) or is_float_dtype(s):
return s.round(decimals)
return s
nv.validate_round(args, kwargs)
if isinstance(decimals, (dict, Series)):
if isinstance(decimals, Series):
if not decimals.index.is_unique:
raise ValueError("Index of decimals must be unique")
new_cols = list(_dict_round(self, decimals))
elif is_integer(decimals):
# Dispatch to Series.round
new_cols = [_series_round(v, decimals) for _, v in self.items()]
else:
raise TypeError("decimals must be an integer, a dict-like or a Series")
if len(new_cols) > 0:
return self._constructor(
concat(new_cols, axis=1), index=self.index, columns=self.columns
)
else:
return self
# ----------------------------------------------------------------------
# Statistical methods, etc.
def corr(self, method="pearson", min_periods=1) -> DataFrame:
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.to_numpy(dtype=float, na_value=np.nan, copy=False)
if method == "pearson":
correl = libalgos.nancorr(mat, minp=min_periods)
elif method == "spearman":
correl = libalgos.nancorr_spearman(mat, minp=min_periods)
elif method == "kendall" or callable(method):
if min_periods is None:
min_periods = 1
mat = mat.T
corrf = nanops.get_corr_func(method)
K = len(cols)
correl = np.empty((K, K), dtype=float)
mask = np.isfinite(mat)
for i, ac in enumerate(mat):
for j, bc in enumerate(mat):
if i > j:
continue
valid = mask[i] & mask[j]
if valid.sum() < min_periods:
c = np.nan
elif i == j:
c = 1.0
elif not valid.all():
c = corrf(ac[valid], bc[valid])
else:
c = corrf(ac, bc)
correl[i, j] = c
correl[j, i] = c
else:
raise ValueError(
"method must be either 'pearson', "
"'spearman', 'kendall', or a callable, "
f"'{method}' was supplied"
)
return self._constructor(correl, index=idx, columns=cols)
def cov(
self, min_periods: Optional[int] = None, ddof: Optional[int] = 1
) -> DataFrame:
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.to_numpy(dtype=float, na_value=np.nan, copy=False)
if notna(mat).all():
if min_periods is not None and min_periods > len(mat):
base_cov = np.empty((mat.shape[1], mat.shape[1]))
base_cov.fill(np.nan)
else:
base_cov = np.cov(mat.T, ddof=ddof)
base_cov = base_cov.reshape((len(cols), len(cols)))
else:
base_cov = libalgos.nancorr(mat, cov=True, minp=min_periods)
return self._constructor(base_cov, index=idx, columns=cols)
def corrwith(self, other, axis=0, drop=False, method="pearson") -> Series:
axis = self._get_axis_number(axis)
this = self._get_numeric_data()
if isinstance(other, Series):
return this.apply(lambda x: other.corr(x, method=method), axis=axis)
other = other._get_numeric_data()
left, right = this.align(other, join="inner", copy=False)
if axis == 1:
left = left.T
right = right.T
if method == "pearson":
# mask missing values
left = left + right * 0
right = right + left * 0
# demeaned data
ldem = left - left.mean()
rdem = right - right.mean()
num = (ldem * rdem).sum()
dom = (left.count() - 1) * left.std() * right.std()
correl = num / dom
elif method in ["kendall", "spearman"] or callable(method):
def c(x):
return nanops.nancorr(x[0], x[1], method=method)
correl = self._constructor_sliced(
map(c, zip(left.values.T, right.values.T)), index=left.columns
)
else:
raise ValueError(
f"Invalid method {method} was passed, "
"valid methods are: 'pearson', 'kendall', "
"'spearman', or callable"
)
if not drop:
# Find non-matching labels along the given axis
# and append missing correlations (GH 22375)
raxis = 1 if axis == 0 else 0
result_index = this._get_axis(raxis).union(other._get_axis(raxis))
idx_diff = result_index.difference(correl.index)
if len(idx_diff) > 0:
correl = correl.append(Series([np.nan] * len(idx_diff), index=idx_diff))
return correl
# ----------------------------------------------------------------------
# ndarray-like stats methods
def count(self, axis=0, level=None, numeric_only=False):
axis = self._get_axis_number(axis)
if level is not None:
return self._count_level(level, axis=axis, numeric_only=numeric_only)
if numeric_only:
frame = self._get_numeric_data()
else:
frame = self
# GH #423
if len(frame._get_axis(axis)) == 0:
result = self._constructor_sliced(0, index=frame._get_agg_axis(axis))
else:
if frame._is_mixed_type or frame._mgr.any_extension_types:
# the or any_extension_types is really only hit for single-
# column frames with an extension array
result = notna(frame).sum(axis=axis)
else:
# GH13407
series_counts = notna(frame).sum(axis=axis)
counts = series_counts.values
result = self._constructor_sliced(
counts, index=frame._get_agg_axis(axis)
)
return result.astype("int64")
def _count_level(self, level, axis=0, numeric_only=False):
if numeric_only:
frame = self._get_numeric_data()
else:
frame = self
count_axis = frame._get_axis(axis)
agg_axis = frame._get_agg_axis(axis)
if not isinstance(count_axis, MultiIndex):
raise TypeError(
f"Can only count levels on hierarchical {self._get_axis_name(axis)}."
)
# Mask NaNs: Mask rows or columns where the index level is NaN, and all
# values in the DataFrame that are NaN
if frame._is_mixed_type:
# Since we have mixed types, calling notna(frame.values) might
# upcast everything to object
values_mask = notna(frame).values
else:
# But use the speedup when we have homogeneous dtypes
values_mask = notna(frame.values)
index_mask = notna(count_axis.get_level_values(level=level))
if axis == 1:
mask = index_mask & values_mask
else:
mask = index_mask.reshape(-1, 1) & values_mask
if isinstance(level, str):
level = count_axis._get_level_number(level)
level_name = count_axis._names[level]
level_index = count_axis.levels[level]._shallow_copy(name=level_name)
level_codes = ensure_int64(count_axis.codes[level])
counts = lib.count_level_2d(mask, level_codes, len(level_index), axis=axis)
if axis == 1:
result = self._constructor(counts, index=agg_axis, columns=level_index)
else:
result = self._constructor(counts, index=level_index, columns=agg_axis)
return result
def _reduce(
self,
op,
name: str,
*,
axis=0,
skipna=True,
numeric_only=None,
filter_type=None,
**kwds,
):
assert filter_type is None or filter_type == "bool", filter_type
out_dtype = "bool" if filter_type == "bool" else None
own_dtypes = [arr.dtype for arr in self._iter_column_arrays()]
dtype_is_dt = np.array(
[is_datetime64_any_dtype(dtype) for dtype in own_dtypes],
dtype=bool,
)
if numeric_only is None and name in ["mean", "median"] and dtype_is_dt.any():
warnings.warn(
"DataFrame.mean and DataFrame.median with numeric_only=None "
"will include datetime64 and datetime64tz columns in a "
"future version.",
FutureWarning,
stacklevel=5,
)
cols = self.columns[~dtype_is_dt]
self = self[cols]
# TODO: Make other agg func handle axis=None properly GH#21597
axis = self._get_axis_number(axis)
labels = self._get_agg_axis(axis)
assert axis in [0, 1]
def func(values):
if is_extension_array_dtype(values.dtype):
return extract_array(values)._reduce(name, skipna=skipna, **kwds)
else:
return op(values, axis=axis, skipna=skipna, **kwds)
def blk_func(values):
if isinstance(values, ExtensionArray):
return values._reduce(name, skipna=skipna, **kwds)
else:
return op(values, axis=1, skipna=skipna, **kwds)
def _get_data() -> DataFrame:
if filter_type is None:
data = self._get_numeric_data()
else:
# GH#25101, GH#24434
assert filter_type == "bool"
data = self._get_bool_data()
return data
if numeric_only is not None or axis == 0:
# For numeric_only non-None and axis non-None, we know
# which blocks to use and no try/except is needed.
# For numeric_only=None only the case with axis==0 and no object
# dtypes are unambiguous can be handled with BlockManager.reduce
# Case with EAs see GH#35881
df = self
if numeric_only is True:
df = _get_data()
if axis == 1:
df = df.T
axis = 0
ignore_failures = numeric_only is None
# After possibly _get_data and transposing, we are now in the
# simple case where we can use BlockManager.reduce
res, indexer = df._mgr.reduce(blk_func, ignore_failures=ignore_failures)
out = df._constructor(res).iloc[0]
if out_dtype is not None:
out = out.astype(out_dtype)
if axis == 0 and is_object_dtype(out.dtype):
# GH#35865 careful to cast explicitly to object
nvs = coerce_to_dtypes(out.values, df.dtypes.iloc[np.sort(indexer)])
out[:] = np.array(nvs, dtype=object)
if axis == 0 and len(self) == 0 and name in ["sum", "prod"]:
# Even if we are object dtype, follow numpy and return
# float64, see test_apply_funcs_over_empty
out = out.astype(np.float64)
return out
assert numeric_only is None
data = self
values = data.values
try:
result = func(values)
except TypeError:
# e.g. in nanops trying to convert strs to float
data = _get_data()
labels = data._get_agg_axis(axis)
values = data.values
with np.errstate(all="ignore"):
result = func(values)
if filter_type == "bool" and notna(result).all():
result = result.astype(np.bool_)
elif filter_type is None and is_object_dtype(result.dtype):
try:
result = result.astype(np.float64)
except (ValueError, TypeError):
# try to coerce to the original dtypes item by item if we can
if axis == 0:
result = coerce_to_dtypes(result, data.dtypes)
result = self._constructor_sliced(result, index=labels)
return result
def nunique(self, axis=0, dropna=True) -> Series:
return self.apply(Series.nunique, axis=axis, dropna=dropna)
def idxmin(self, axis=0, skipna=True) -> Series:
axis = self._get_axis_number(axis)
res = self._reduce(
nanops.nanargmin, "argmin", axis=axis, skipna=skipna, numeric_only=False
)
indices = res._values
# indices will always be np.ndarray since axis is not None and
# values is a 2d array for DataFrame
# error: Item "int" of "Union[int, Any]" has no attribute "__iter__"
assert isinstance(indices, np.ndarray) # for mypy
index = self._get_axis(axis)
result = [index[i] if i >= 0 else np.nan for i in indices]
return self._constructor_sliced(result, index=self._get_agg_axis(axis))
def idxmax(self, axis=0, skipna=True) -> Series:
axis = self._get_axis_number(axis)
res = self._reduce(
nanops.nanargmax, "argmax", axis=axis, skipna=skipna, numeric_only=False
)
indices = res._values
# indices will always be np.ndarray since axis is not None and
# values is a 2d array for DataFrame
# error: Item "int" of "Union[int, Any]" has no attribute "__iter__"
assert isinstance(indices, np.ndarray) # for mypy
index = self._get_axis(axis)
result = [index[i] if i >= 0 else np.nan for i in indices]
return self._constructor_sliced(result, index=self._get_agg_axis(axis))
def _get_agg_axis(self, axis_num: int) -> Index:
if axis_num == 0:
return self.columns
elif axis_num == 1:
return self.index
else:
raise ValueError(f"Axis must be 0 or 1 (got {repr(axis_num)})")
def mode(self, axis=0, numeric_only=False, dropna=True) -> DataFrame:
data = self if not numeric_only else self._get_numeric_data()
def f(s):
return s.mode(dropna=dropna)
return data.apply(f, axis=axis)
def quantile(self, q=0.5, axis=0, numeric_only=True, interpolation="linear"):
validate_percentile(q)
data = self._get_numeric_data() if numeric_only else self
axis = self._get_axis_number(axis)
is_transposed = axis == 1
if is_transposed:
data = data.T
if len(data.columns) == 0:
# GH#23925 _get_numeric_data may have dropped all columns
cols = Index([], name=self.columns.name)
if is_list_like(q):
return self._constructor([], index=q, columns=cols)
return self._constructor_sliced([], index=cols, name=q, dtype=np.float64)
result = data._mgr.quantile(
qs=q, axis=1, interpolation=interpolation, transposed=is_transposed
)
if result.ndim == 2:
result = self._constructor(result)
else:
result = self._constructor_sliced(result, name=q)
if is_transposed:
result = result.T
return result
def to_timestamp(
self, freq=None, how: str = "start", axis: Axis = 0, copy: bool = True
) -> DataFrame:
new_obj = self.copy(deep=copy)
axis_name = self._get_axis_name(axis)
old_ax = getattr(self, axis_name)
if not isinstance(old_ax, PeriodIndex):
raise TypeError(f"unsupported Type {type(old_ax).__name__}")
new_ax = old_ax.to_timestamp(freq=freq, how=how)
setattr(new_obj, axis_name, new_ax)
return new_obj
def to_period(self, freq=None, axis: Axis = 0, copy: bool = True) -> DataFrame:
new_obj = self.copy(deep=copy)
axis_name = self._get_axis_name(axis)
old_ax = getattr(self, axis_name)
if not isinstance(old_ax, DatetimeIndex):
raise TypeError(f"unsupported Type {type(old_ax).__name__}")
new_ax = old_ax.to_period(freq=freq)
setattr(new_obj, axis_name, new_ax)
return new_obj
def isin(self, values) -> DataFrame:
if isinstance(values, dict):
from pandas.core.reshape.concat import concat
values = collections.defaultdict(list, values)
return concat(
(
self.iloc[:, [i]].isin(values[col])
for i, col in enumerate(self.columns)
),
axis=1,
)
elif isinstance(values, Series):
if not values.index.is_unique:
raise ValueError("cannot compute isin with a duplicate axis.")
return self.eq(values.reindex_like(self), axis="index")
elif isinstance(values, DataFrame):
if not (values.columns.is_unique and values.index.is_unique):
raise ValueError("cannot compute isin with a duplicate axis.")
return self.eq(values.reindex_like(self))
else:
if not is_list_like(values):
raise TypeError(
"only list-like or dict-like objects are allowed "
"to be passed to DataFrame.isin(), "
f"you passed a '{type(values).__name__}'"
)
return self._constructor(
algorithms.isin(self.values.ravel(), values).reshape(self.shape),
self.index,
self.columns,
)
# ----------------------------------------------------------------------
# Add index and columns
_AXIS_ORDERS = ["index", "columns"]
_AXIS_TO_AXIS_NUMBER: Dict[Axis, int] = {
**NDFrame._AXIS_TO_AXIS_NUMBER,
1: 1,
"columns": 1,
}
_AXIS_REVERSED = True
_AXIS_LEN = len(_AXIS_ORDERS)
_info_axis_number = 1
_info_axis_name = "columns"
index: Index = properties.AxisProperty(
axis=1, doc="The index (row labels) of the DataFrame."
)
columns: Index = properties.AxisProperty(
axis=0, doc="The column labels of the DataFrame."
)
@property
def _AXIS_NUMBERS(self) -> Dict[str, int]:
super()._AXIS_NUMBERS
return {"index": 0, "columns": 1}
@property
def _AXIS_NAMES(self) -> Dict[int, str]:
super()._AXIS_NAMES
return {0: "index", 1: "columns"}
# ----------------------------------------------------------------------
# Add plotting methods to DataFrame
plot = CachedAccessor("plot", pandas.plotting.PlotAccessor)
hist = pandas.plotting.hist_frame
boxplot = pandas.plotting.boxplot_frame
sparse = CachedAccessor("sparse", SparseFrameAccessor)
DataFrame._add_numeric_operations()
ops.add_flex_arithmetic_methods(DataFrame)
def _from_nested_dict(data) -> collections.defaultdict:
new_data: collections.defaultdict = collections.defaultdict(dict)
for index, s in data.items():
for col, v in s.items():
new_data[col][index] = v
return new_data
| true | true |
f710668d288a186a66be2bcf743c10315b88fa0a | 2,738 | py | Python | taln2016/icsisumm-primary-sys34_v1/nltk/nltk-0.9.2/nltk/compat.py | hectormartinez/rougexstem | 32da9eab253cb88fc1882e59026e8b5b40900a25 | [
"Apache-2.0"
] | null | null | null | taln2016/icsisumm-primary-sys34_v1/nltk/nltk-0.9.2/nltk/compat.py | hectormartinez/rougexstem | 32da9eab253cb88fc1882e59026e8b5b40900a25 | [
"Apache-2.0"
] | null | null | null | taln2016/icsisumm-primary-sys34_v1/nltk/nltk-0.9.2/nltk/compat.py | hectormartinez/rougexstem | 32da9eab253cb88fc1882e59026e8b5b40900a25 | [
"Apache-2.0"
] | null | null | null | # Natural Language Toolkit: Compatibility Functions
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: Steven Bird <sb@csse.unimelb.edu.au>
# Edward Loper <edloper@gradient.cis.upenn.edu>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
"""
Backwards compatibility with previous versions of Python.
This module provides backwards compatibility by defining
functions and classes that were not available in earlier versions of
Python. Intented usage:
>>> from nltk.compat import *
Currently, NLTK requires Python 2.4 or later.
"""
######################################################################
# New in Python 2.5
######################################################################
# ElementTree
try:
from xml.etree import ElementTree
except ImportError:
from nltk.etree import ElementTree
# collections.defaultdict
# originally contributed by Yoav Goldberg <yoav.goldberg@gmail.com>
# new version by Jason Kirtland from Python cookbook.
# <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/523034>
try:
from collections import defaultdict
except ImportError:
class defaultdict(dict):
def __init__(self, default_factory=None, *a, **kw):
if (default_factory is not None and
not hasattr(default_factory, '__call__')):
raise TypeError('first argument must be callable')
dict.__init__(self, *a, **kw)
self.default_factory = default_factory
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
return self.__missing__(key)
def __missing__(self, key):
if self.default_factory is None:
raise KeyError(key)
self[key] = value = self.default_factory()
return value
def __reduce__(self):
if self.default_factory is None:
args = tuple()
else:
args = self.default_factory,
return type(self), args, None, None, self.items()
def copy(self):
return self.__copy__()
def __copy__(self):
return type(self)(self.default_factory, self)
def __deepcopy__(self, memo):
import copy
return type(self)(self.default_factory,
copy.deepcopy(self.items()))
def __repr__(self):
return 'defaultdict(%s, %s)' % (self.default_factory,
dict.__repr__(self))
# [XX] to make pickle happy in python 2.4:
import collections
collections.defaultdict = defaultdict
__all__ = ['ElementTree', 'defaultdict']
| 34.658228 | 70 | 0.597516 | true | true | |
f710673561a8d0361c9a9589feaf7aab93ae560e | 231 | py | Python | servermanager/admin.py | wjzhangcsu/MyDjangoBlog | 6f1a1d9205ad84b38ba1cbc1bf3bdba46eaaa9d7 | [
"MIT"
] | 1 | 2018-04-23T06:29:22.000Z | 2018-04-23T06:29:22.000Z | servermanager/admin.py | lxguidu/DjangoBlog | 620ab1d8131cc7124d5a85fc1ef153a4271d4abc | [
"MIT"
] | 15 | 2020-02-11T21:37:20.000Z | 2022-03-11T23:12:25.000Z | servermanager/admin.py | wjzhangcsu/MyDjangoBlog | 6f1a1d9205ad84b38ba1cbc1bf3bdba46eaaa9d7 | [
"MIT"
] | null | null | null | from django.contrib import admin
# Register your models here.
from .models import commands
class CommandsAdmin(admin.ModelAdmin):
list_display = ('title', 'command', 'describe')
admin.site.register(commands, CommandsAdmin)
| 21 | 51 | 0.766234 | from django.contrib import admin
from .models import commands
class CommandsAdmin(admin.ModelAdmin):
list_display = ('title', 'command', 'describe')
admin.site.register(commands, CommandsAdmin)
| true | true |
f71069b14bf1ad73d77cf9f7bb28f95c8cd7322e | 1,506 | py | Python | lib/surface/compute/vpn_tunnels/__init__.py | google-cloud-sdk-unofficial/google-cloud-sdk | 2a48a04df14be46c8745050f98768e30474a1aac | [
"Apache-2.0"
] | 2 | 2019-11-10T09:17:07.000Z | 2019-12-18T13:44:08.000Z | lib/surface/compute/vpn_tunnels/__init__.py | google-cloud-sdk-unofficial/google-cloud-sdk | 2a48a04df14be46c8745050f98768e30474a1aac | [
"Apache-2.0"
] | null | null | null | lib/surface/compute/vpn_tunnels/__init__.py | google-cloud-sdk-unofficial/google-cloud-sdk | 2a48a04df14be46c8745050f98768e30474a1aac | [
"Apache-2.0"
] | 1 | 2020-07-25T01:40:19.000Z | 2020-07-25T01:40:19.000Z | # -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Commands for reading and manipulating VPN Gateways."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class VpnTunnels(base.Group):
"""Read and manipulate Compute Engine VPN tunnels."""
# Placeholder to indicate that a detailed_help field exists and should
# be set outside the class definition.
detailed_help = None
VpnTunnels.category = base.NETWORKING_CATEGORY
VpnTunnels.detailed_help = {
'DESCRIPTION': """
Read and manipulate Cloud VPN tunnels.
For more information about Cloud VPN tunnels, see the
[Cloud VPN tunnels documentation](https://cloud.google.com//network-connectivity/docs/vpn/concepts/overview).
See also: [VPN tunnels API](https://cloud.google.com/compute/docs/reference/rest/v1/vpnTunnels).
""",
}
| 34.227273 | 117 | 0.749668 |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class VpnTunnels(base.Group):
detailed_help = None
VpnTunnels.category = base.NETWORKING_CATEGORY
VpnTunnels.detailed_help = {
'DESCRIPTION': """
Read and manipulate Cloud VPN tunnels.
For more information about Cloud VPN tunnels, see the
[Cloud VPN tunnels documentation](https://cloud.google.com//network-connectivity/docs/vpn/concepts/overview).
See also: [VPN tunnels API](https://cloud.google.com/compute/docs/reference/rest/v1/vpnTunnels).
""",
}
| true | true |
f7106e85bf3410c064655c4349ec8f21e9e33c1d | 450 | py | Python | src/conreality/sdk/message.py | conreality/conreality.py | 7c5d40367aebdc69eb2c77bc71793b8dd5737c29 | [
"Unlicense"
] | 4 | 2017-06-16T21:21:06.000Z | 2018-06-06T10:20:48.000Z | src/conreality/sdk/message.py | conreality/conreality.py | 7c5d40367aebdc69eb2c77bc71793b8dd5737c29 | [
"Unlicense"
] | 2 | 2020-07-02T04:41:51.000Z | 2022-02-11T06:31:54.000Z | src/conreality/sdk/message.py | conreality/conreality.py | 7c5d40367aebdc69eb2c77bc71793b8dd5737c29 | [
"Unlicense"
] | null | null | null | # This is free and unencumbered software released into the public domain.
class Message:
"""A message."""
def __init__(self, id=None):
self.id = id
def __repr__(self):
"""Returns a human-readable string representation of this object."""
return "message{{id={}}}".format(self.id)
def __str__(self):
"""Returns a human-readable string representation of this object."""
return self.__repr__()
| 28.125 | 76 | 0.642222 |
class Message:
def __init__(self, id=None):
self.id = id
def __repr__(self):
return "message{{id={}}}".format(self.id)
def __str__(self):
return self.__repr__()
| true | true |
f7106e89f73ac2d0682993b85172d2beb9988f1a | 3,271 | py | Python | exchangelib/configuration.py | ifour92/exchangelib | eb86f2ab9f9a16e07f0d19e0dcf69065b02d9f8a | [
"BSD-2-Clause"
] | null | null | null | exchangelib/configuration.py | ifour92/exchangelib | eb86f2ab9f9a16e07f0d19e0dcf69065b02d9f8a | [
"BSD-2-Clause"
] | null | null | null | exchangelib/configuration.py | ifour92/exchangelib | eb86f2ab9f9a16e07f0d19e0dcf69065b02d9f8a | [
"BSD-2-Clause"
] | null | null | null | import logging
from cached_property import threaded_cached_property
from .credentials import BaseCredentials
from .protocol import RetryPolicy, FailFast
from .transport import AUTH_TYPE_MAP
from .util import split_url
from .version import Version
log = logging.getLogger(__name__)
class Configuration:
"""
Assembles a connection protocol when autodiscover is not used.
If the server is not configured with autodiscover, the following should be sufficient:
config = Configuration(server='example.com', credentials=Credentials('MYWINDOMAIN\\myusername', 'topsecret'))
account = Account(primary_smtp_address='john@example.com', config=config)
You can also set the EWS service endpoint directly:
config = Configuration(service_endpoint='https://mail.example.com/EWS/Exchange.asmx', credentials=...)
If you know which authentication type the server uses, you add that as a hint:
config = Configuration(service_endpoint='https://example.com/EWS/Exchange.asmx', auth_type=NTLM, credentials=..)
If you want to use autodiscover, don't use a Configuration object. Instead, set up an account like this:
credentials = Credentials(username='MYWINDOMAIN\\myusername', password='topsecret')
account = Account(primary_smtp_address='john@example.com', credentials=credentials, autodiscover=True)
"""
def __init__(self, credentials=None, server=None, service_endpoint=None, auth_type=None, version=None,
retry_policy=None):
if not isinstance(credentials, (BaseCredentials, type(None))):
raise ValueError("'credentials' %r must be a Credentials instance" % credentials)
if server and service_endpoint:
raise AttributeError("Only one of 'server' or 'service_endpoint' must be provided")
if auth_type is not None and auth_type not in AUTH_TYPE_MAP:
raise ValueError("'auth_type' %r must be one of %s"
% (auth_type, ', '.join("'%s'" % k for k in sorted(AUTH_TYPE_MAP.keys()))))
if not retry_policy:
retry_policy = FailFast()
if not isinstance(version, (Version, type(None))):
raise ValueError("'version' %r must be a Version instance" % version)
if not isinstance(retry_policy, RetryPolicy):
raise ValueError("'retry_policy' %r must be a RetryPolicy instance" % retry_policy)
self._credentials = credentials
if server:
self.service_endpoint = 'https://%s/EWS/Exchange.asmx' % server
else:
self.service_endpoint = service_endpoint
self.auth_type = auth_type
self.version = version
self.retry_policy = retry_policy
@property
def credentials(self):
# Do not update credentials from this class. Instead, do it from Protocol
return self._credentials
@threaded_cached_property
def server(self):
if not self.service_endpoint:
return None
return split_url(self.service_endpoint)[1]
def __repr__(self):
return self.__class__.__name__ + '(%s)' % ', '.join('%s=%r' % (k, getattr(self, k)) for k in (
'credentials', 'service_endpoint', 'auth_type', 'version', 'retry_policy'
))
| 43.039474 | 120 | 0.682972 | import logging
from cached_property import threaded_cached_property
from .credentials import BaseCredentials
from .protocol import RetryPolicy, FailFast
from .transport import AUTH_TYPE_MAP
from .util import split_url
from .version import Version
log = logging.getLogger(__name__)
class Configuration:
def __init__(self, credentials=None, server=None, service_endpoint=None, auth_type=None, version=None,
retry_policy=None):
if not isinstance(credentials, (BaseCredentials, type(None))):
raise ValueError("'credentials' %r must be a Credentials instance" % credentials)
if server and service_endpoint:
raise AttributeError("Only one of 'server' or 'service_endpoint' must be provided")
if auth_type is not None and auth_type not in AUTH_TYPE_MAP:
raise ValueError("'auth_type' %r must be one of %s"
% (auth_type, ', '.join("'%s'" % k for k in sorted(AUTH_TYPE_MAP.keys()))))
if not retry_policy:
retry_policy = FailFast()
if not isinstance(version, (Version, type(None))):
raise ValueError("'version' %r must be a Version instance" % version)
if not isinstance(retry_policy, RetryPolicy):
raise ValueError("'retry_policy' %r must be a RetryPolicy instance" % retry_policy)
self._credentials = credentials
if server:
self.service_endpoint = 'https://%s/EWS/Exchange.asmx' % server
else:
self.service_endpoint = service_endpoint
self.auth_type = auth_type
self.version = version
self.retry_policy = retry_policy
@property
def credentials(self):
return self._credentials
@threaded_cached_property
def server(self):
if not self.service_endpoint:
return None
return split_url(self.service_endpoint)[1]
def __repr__(self):
return self.__class__.__name__ + '(%s)' % ', '.join('%s=%r' % (k, getattr(self, k)) for k in (
'credentials', 'service_endpoint', 'auth_type', 'version', 'retry_policy'
))
| true | true |
f710702e90b4523c81be699400931b542b2a5907 | 668 | py | Python | libraries/boost-build/src/example/python_modules/python_helpers.py | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | 198 | 2015-01-13T05:47:18.000Z | 2022-03-09T04:46:46.000Z | libs/boost/tools/build/example/python_modules/python_helpers.py | flingone/frameworks_base_cmds_remoted | 4509d9f0468137ed7fd8d100179160d167e7d943 | [
"Apache-2.0"
] | 61 | 2015-05-27T11:20:11.000Z | 2019-12-20T15:06:21.000Z | libs/boost/tools/build/example/python_modules/python_helpers.py | flingone/frameworks_base_cmds_remoted | 4509d9f0468137ed7fd8d100179160d167e7d943 | [
"Apache-2.0"
] | 139 | 2015-01-15T20:09:31.000Z | 2022-01-31T15:21:16.000Z | # Copyright 2006 Vladimir Prus
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
# Declare a couple of functions called from Boost.Build
#
# Each function will receive as many arguments as there ":"-separated
# arguments in bjam call. Each argument is a list of strings.
# As a special exception (aka bug), if no arguments are passed in bjam,
# Python function will be passed a single empty list.
#
# All Python functions must return a list of strings, which may be empty.
def test1(l):
return ["foo", "bar"]
def test2(l, l2):
return [l[0], l2[0]] | 37.111111 | 82 | 0.715569 |
def test1(l):
return ["foo", "bar"]
def test2(l, l2):
return [l[0], l2[0]] | true | true |
f7107105fc2ad424c38b5ad9e757ac35f41dbfc7 | 3,837 | py | Python | aiida/cmdline/commands/cmd_data/cmd_remote.py | lekah/aiida_core | 54b22a221657b47044483dc9d4f51788ce8ab6b2 | [
"BSD-2-Clause"
] | null | null | null | aiida/cmdline/commands/cmd_data/cmd_remote.py | lekah/aiida_core | 54b22a221657b47044483dc9d4f51788ce8ab6b2 | [
"BSD-2-Clause"
] | null | null | null | aiida/cmdline/commands/cmd_data/cmd_remote.py | lekah/aiida_core | 54b22a221657b47044483dc9d4f51788ce8ab6b2 | [
"BSD-2-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida-core #
# For further information on the license, see the LICENSE.txt file #
# For further information please visit http://www.aiida.net #
###########################################################################
"""`verdi data remote` command."""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import io
import click
from aiida.cmdline.commands.cmd_data import verdi_data
from aiida.cmdline.params import arguments, types
from aiida.cmdline.utils import echo
from aiida.common.files import get_mode_string
@verdi_data.group('remote')
def remote():
"""Manipulate RemoteData objects (reference to remote folders).
A RemoteData can be thought as a "symbolic link" to a folder on one of the
Computers set up in AiiDA (e.g. where a CalcJob will run).
This folder is called "remote" in the sense that it is on a Computer and
not in the AiiDA repository. Note, however, that the "remote" computer
could also be "localhost"."""
@remote.command('ls')
@arguments.DATUM(type=types.DataParamType(sub_classes=('aiida.data:remote',)))
@click.option('-l', '--long', 'ls_long', is_flag=True, default=False, help='Display also file metadata.')
@click.option('-p', '--path', type=click.STRING, default='.', help='The folder to list.')
def remote_ls(ls_long, path, datum):
"""List content of a (sub)directory in a RemoteData object."""
import datetime
try:
content = datum.listdir_withattributes(path=path)
except (IOError, OSError) as err:
echo.echo_critical(
'Unable to access the remote folder or file, check if it exists.\n'
'Original error: {}'.format(str(err))
)
for metadata in content:
if ls_long:
mtime = datetime.datetime.fromtimestamp(metadata['attributes'].st_mtime)
pre_line = '{} {:10} {} '.format(
get_mode_string(metadata['attributes'].st_mode), metadata['attributes'].st_size,
mtime.strftime('%d %b %Y %H:%M')
)
click.echo(pre_line, nl=False)
if metadata['isdir']:
click.echo(click.style(metadata['name'], fg='blue'))
else:
click.echo(metadata['name'])
@remote.command('cat')
@arguments.DATUM(type=types.DataParamType(sub_classes=('aiida.data:remote',)))
@click.argument('path', type=click.STRING)
def remote_cat(datum, path):
"""Show content of a file in a RemoteData object."""
import os
import sys
import tempfile
try:
with tempfile.NamedTemporaryFile(delete=False) as tmpf:
tmpf.close()
datum.getfile(path, tmpf.name)
with io.open(tmpf.name, encoding='utf8') as fhandle:
sys.stdout.write(fhandle.read())
except IOError as err:
echo.echo_critical('{}: {}'.format(err.errno, str(err)))
try:
os.remove(tmpf.name)
except OSError:
# If you cannot delete, ignore (maybe I didn't manage to create it in the first place
pass
@remote.command('show')
@arguments.DATUM(type=types.DataParamType(sub_classes=('aiida.data:remote',)))
def remote_show(datum):
"""Show information for a RemoteData object."""
click.echo('- Remote computer name:')
click.echo(' {}'.format(datum.get_computer_name()))
click.echo('- Remote folder full path:')
click.echo(' {}'.format(datum.get_remote_path()))
| 40.389474 | 105 | 0.614021 | true | true | |
f71071d4bb2196aec59b0c0f18d4ae62abec55f4 | 1,313 | py | Python | api/clean/sequence_nick.py | Latent-Lxx/dazhou-dw | 902b4b625cda4c9e4eb205017b8955b81f37a0b5 | [
"MIT"
] | null | null | null | api/clean/sequence_nick.py | Latent-Lxx/dazhou-dw | 902b4b625cda4c9e4eb205017b8955b81f37a0b5 | [
"MIT"
] | null | null | null | api/clean/sequence_nick.py | Latent-Lxx/dazhou-dw | 902b4b625cda4c9e4eb205017b8955b81f37a0b5 | [
"MIT"
] | 1 | 2022-02-11T04:44:37.000Z | 2022-02-11T04:44:37.000Z | # !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/7/5 下午5:29
# @Author : Latent
# @Email : latentsky@gmail.com
# @File : sequence_nick.py
# @Software: PyCharm
# @class : 清晰店铺的相关信息
"""
字段说明:
1.nick_id ---->数据库自增
2.nick_name
3.nick
4.brand
5.company_name
6.platform
"""
from tools_class import Tools_Class
class Sequence_Nick(object):
# 品牌提取
@classmethod
def sequence_brand(cls, data):
# 1. 店铺名称
seller = Sequence_Nick.sequence_seller(data=data)
# 2.店铺编号
sid = Tools_Class.tools_md5(nick=seller)
# 3. 品牌
brand = data['public']['brand']
# 4. 平台
platform = data['platform']
if platform == 'taobao':
tmall = data['public']['tmall']
if tmall:
platform = 'tmall'
else:
platform = 'taobao'
platform = {
'seller': seller,
'nick_id': sid,
'brand': brand,
'platform': platform
}
return platform
# 商品店铺名称
@classmethod
def sequence_seller(cls, data):
try:
seller = data['seller']
except KeyError as k:
seller = data['seller_nick']
if seller is None:
seller = data['public']['nick']
return seller
| 20.84127 | 57 | 0.529322 |
from tools_class import Tools_Class
class Sequence_Nick(object):
@classmethod
def sequence_brand(cls, data):
seller = Sequence_Nick.sequence_seller(data=data)
sid = Tools_Class.tools_md5(nick=seller)
brand = data['public']['brand']
platform = data['platform']
if platform == 'taobao':
tmall = data['public']['tmall']
if tmall:
platform = 'tmall'
else:
platform = 'taobao'
platform = {
'seller': seller,
'nick_id': sid,
'brand': brand,
'platform': platform
}
return platform
@classmethod
def sequence_seller(cls, data):
try:
seller = data['seller']
except KeyError as k:
seller = data['seller_nick']
if seller is None:
seller = data['public']['nick']
return seller
| true | true |
f710733735df4a859b306164419416ca4ee1c954 | 889 | py | Python | setup.py | whitehead-internal/DialogTag | 226def810db21fd34c1ac9363e841a3357dacf96 | [
"MIT"
] | null | null | null | setup.py | whitehead-internal/DialogTag | 226def810db21fd34c1ac9363e841a3357dacf96 | [
"MIT"
] | null | null | null | setup.py | whitehead-internal/DialogTag | 226def810db21fd34c1ac9363e841a3357dacf96 | [
"MIT"
] | null | null | null | import setuptools
with open("README.md", mode="r", encoding="utf-8") as readme_file:
long_description = readme_file.read()
setuptools.setup(
name="DialogTag",
version="1.1.3",
author="Bhavitvya Malik",
author_email="bhavitvya.malik@gmail.com",
description="A python library to classify dialogue tag.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/bhavitvyamalik/DialogTag",
packages=setuptools.find_packages(),
install_requires=[
'transformers>=3.0.0',
'tqdm',
'tensorflow>=2.0.0'
],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
keywords="Tensorflow BERT NLP deep learning Transformer Networks "
)
| 30.655172 | 70 | 0.662542 | import setuptools
with open("README.md", mode="r", encoding="utf-8") as readme_file:
long_description = readme_file.read()
setuptools.setup(
name="DialogTag",
version="1.1.3",
author="Bhavitvya Malik",
author_email="bhavitvya.malik@gmail.com",
description="A python library to classify dialogue tag.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/bhavitvyamalik/DialogTag",
packages=setuptools.find_packages(),
install_requires=[
'transformers>=3.0.0',
'tqdm',
'tensorflow>=2.0.0'
],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
keywords="Tensorflow BERT NLP deep learning Transformer Networks "
)
| true | true |
f7107448bde30ae16755d5ac91e74e290f2cc800 | 1,086 | py | Python | autodiff/examples/svm.py | gwtaylor/pyautodiff | 7973e26f1c233570ed4bb10d08634ec7378e2152 | [
"BSD-3-Clause"
] | 59 | 2015-02-03T20:50:59.000Z | 2020-05-26T05:38:54.000Z | autodiff/examples/svm.py | gwtaylor/pyautodiff | 7973e26f1c233570ed4bb10d08634ec7378e2152 | [
"BSD-3-Clause"
] | 3 | 2015-05-10T06:22:45.000Z | 2016-12-06T02:20:58.000Z | autodiff/examples/svm.py | gwtaylor/pyautodiff | 7973e26f1c233570ed4bb10d08634ec7378e2152 | [
"BSD-3-Clause"
] | 11 | 2015-04-15T16:52:09.000Z | 2017-06-28T12:10:39.000Z | """
Linear SVM
==========
This script fits a linear support vector machine classifier to random data. It
illustrates how a function defined purely by NumPy operations can be minimized
directly with a gradient-based solver.
"""
import numpy as np
from autodiff.optimize import fmin_l_bfgs_b
def test_svm():
rng = np.random.RandomState(1)
# -- create some fake data
x = rng.rand(10, 5)
y = 2 * (rng.rand(10) > 0.5) - 1
l2_regularization = 1e-4
# -- loss function
def loss_fn(weights, bias):
margin = y * (np.dot(x, weights) + bias)
loss = np.maximum(0, 1 - margin) ** 2
l2_cost = 0.5 * l2_regularization * np.dot(weights, weights)
loss = np.mean(loss) + l2_cost
print('ran loss_fn(), returning {}'.format(loss))
return loss
# -- call optimizer
w_0, b_0 = np.zeros(5), np.zeros(())
w, b = fmin_l_bfgs_b(loss_fn, init_args=(w_0, b_0))
final_loss = loss_fn(w, b)
assert np.allclose(final_loss, 0.7229)
print('optimization successful!')
if __name__ == '__main__':
test_svm()
| 24.681818 | 79 | 0.632597 | import numpy as np
from autodiff.optimize import fmin_l_bfgs_b
def test_svm():
rng = np.random.RandomState(1)
x = rng.rand(10, 5)
y = 2 * (rng.rand(10) > 0.5) - 1
l2_regularization = 1e-4
def loss_fn(weights, bias):
margin = y * (np.dot(x, weights) + bias)
loss = np.maximum(0, 1 - margin) ** 2
l2_cost = 0.5 * l2_regularization * np.dot(weights, weights)
loss = np.mean(loss) + l2_cost
print('ran loss_fn(), returning {}'.format(loss))
return loss
w_0, b_0 = np.zeros(5), np.zeros(())
w, b = fmin_l_bfgs_b(loss_fn, init_args=(w_0, b_0))
final_loss = loss_fn(w, b)
assert np.allclose(final_loss, 0.7229)
print('optimization successful!')
if __name__ == '__main__':
test_svm()
| true | true |
f71075962ac4461a97d97f6545a5d430a4db8c29 | 1,259 | py | Python | PyRemoteConsole/common_connection.py | Wykleph/PyRemoteConsole | 98c4df6c78060c1506681965a05d5240165eb111 | [
"MIT"
] | null | null | null | PyRemoteConsole/common_connection.py | Wykleph/PyRemoteConsole | 98c4df6c78060c1506681965a05d5240165eb111 | [
"MIT"
] | null | null | null | PyRemoteConsole/common_connection.py | Wykleph/PyRemoteConsole | 98c4df6c78060c1506681965a05d5240165eb111 | [
"MIT"
] | null | null | null | try:
from prawframe.obfuscation import Scrambler
except ImportError:
from .obfuscation import Encryptor
def bytes_packet(_bytes, termination_string=']'):
"""
Create a packet containing the amount of bytes for the proceeding data.
:param _bytes:
:param termination_string:
:return:
"""
return '{}{}'.format(len(_bytes), termination_string)
def scrambles_input_unscrambles_output(func):
scrambler = Encryptor().load_key_file()
def decorator(*args, **kwargs):
args = list(args)
args[0] = scrambler.encrypt(args[0])
result = func(*args, **kwargs)
descrabled = scrambler.decrypt(result)
return descrabled
return decorator
def unscrambles_output(func):
scrambler = Encryptor().load_key_file()
def decorator(*args, **kwargs):
args = list(args)
scrambled_result = func(*args, **kwargs)
result = scrambler.decrypt(scrambled_result)
return result
return decorator
def scrambles_input(func):
scrambler = Encryptor().load_key_file()
def decorator(*args, **kwargs):
args = list(args)
args[0] = scrambler.encrypt(args[0])
result = func(*args, **kwargs)
return result
return decorator
| 24.686275 | 75 | 0.656076 | try:
from prawframe.obfuscation import Scrambler
except ImportError:
from .obfuscation import Encryptor
def bytes_packet(_bytes, termination_string=']'):
return '{}{}'.format(len(_bytes), termination_string)
def scrambles_input_unscrambles_output(func):
scrambler = Encryptor().load_key_file()
def decorator(*args, **kwargs):
args = list(args)
args[0] = scrambler.encrypt(args[0])
result = func(*args, **kwargs)
descrabled = scrambler.decrypt(result)
return descrabled
return decorator
def unscrambles_output(func):
scrambler = Encryptor().load_key_file()
def decorator(*args, **kwargs):
args = list(args)
scrambled_result = func(*args, **kwargs)
result = scrambler.decrypt(scrambled_result)
return result
return decorator
def scrambles_input(func):
scrambler = Encryptor().load_key_file()
def decorator(*args, **kwargs):
args = list(args)
args[0] = scrambler.encrypt(args[0])
result = func(*args, **kwargs)
return result
return decorator
| true | true |
f710765d0c0048687b632aaad0876e54da59b574 | 2,249 | py | Python | lib/models/resnet_trans_head.py | hz-ants/CDPN-source- | 625f9a80858f8a2fb9e74f88ea83073495141693 | [
"Apache-2.0"
] | 31 | 2020-12-21T09:36:30.000Z | 2022-03-04T03:27:48.000Z | lib/models/resnet_trans_head.py | hz-ants/CDPN-source- | 625f9a80858f8a2fb9e74f88ea83073495141693 | [
"Apache-2.0"
] | 3 | 2021-03-29T10:54:41.000Z | 2021-04-28T08:33:48.000Z | lib/models/resnet_trans_head.py | hz-ants/CDPN-source- | 625f9a80858f8a2fb9e74f88ea83073495141693 | [
"Apache-2.0"
] | 13 | 2020-12-21T09:42:05.000Z | 2022-03-25T06:04:24.000Z | import torch.nn as nn
import torch
class TransHeadNet(nn.Module):
def __init__(self, in_channels, num_layers=3, num_filters=256, kernel_size=3, output_dim=3, freeze=False,
with_bias_end=True):
super(TransHeadNet, self).__init__()
self.freeze = freeze
if kernel_size == 3:
padding = 1
elif kernel_size == 2:
padding = 0
self.features = nn.ModuleList()
for i in range(num_layers):
_in_channels = in_channels if i == 0 else num_filters
self.features.append(nn.Conv2d(_in_channels, num_filters, kernel_size=kernel_size, stride=1, padding=padding, bias=False))
self.features.append(nn.BatchNorm2d(num_filters))
self.features.append(nn.ReLU(inplace=True))
self.linears = nn.ModuleList()
self.linears.append(nn.Linear(256 * 8 * 8, 4096))
self.linears.append(nn.ReLU(inplace=True))
self.linears.append(nn.Linear(4096, 4096))
self.linears.append(nn.ReLU(inplace=True))
self.linears.append(nn.Linear(4096, output_dim))
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.normal_(m.weight, mean=0, std=0.001)
if with_bias_end and (m.bias is not None):
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.ConvTranspose2d):
nn.init.normal_(m.weight, mean=0, std=0.001)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, mean=0, std=0.001)
def forward(self, x):
if self.freeze:
with torch.no_grad():
for i, l in enumerate(self.features):
x = l(x)
x = x.view(-1, 256*8*8)
for i, l in enumerate(self.linears):
x = l(x)
return x.detach()
else:
for i, l in enumerate(self.features):
x = l(x)
x = x.view(-1, 256*8*8)
for i, l in enumerate(self.linears):
x = l(x)
return x
| 37.483333 | 134 | 0.549133 | import torch.nn as nn
import torch
class TransHeadNet(nn.Module):
def __init__(self, in_channels, num_layers=3, num_filters=256, kernel_size=3, output_dim=3, freeze=False,
with_bias_end=True):
super(TransHeadNet, self).__init__()
self.freeze = freeze
if kernel_size == 3:
padding = 1
elif kernel_size == 2:
padding = 0
self.features = nn.ModuleList()
for i in range(num_layers):
_in_channels = in_channels if i == 0 else num_filters
self.features.append(nn.Conv2d(_in_channels, num_filters, kernel_size=kernel_size, stride=1, padding=padding, bias=False))
self.features.append(nn.BatchNorm2d(num_filters))
self.features.append(nn.ReLU(inplace=True))
self.linears = nn.ModuleList()
self.linears.append(nn.Linear(256 * 8 * 8, 4096))
self.linears.append(nn.ReLU(inplace=True))
self.linears.append(nn.Linear(4096, 4096))
self.linears.append(nn.ReLU(inplace=True))
self.linears.append(nn.Linear(4096, output_dim))
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.normal_(m.weight, mean=0, std=0.001)
if with_bias_end and (m.bias is not None):
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.ConvTranspose2d):
nn.init.normal_(m.weight, mean=0, std=0.001)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, mean=0, std=0.001)
def forward(self, x):
if self.freeze:
with torch.no_grad():
for i, l in enumerate(self.features):
x = l(x)
x = x.view(-1, 256*8*8)
for i, l in enumerate(self.linears):
x = l(x)
return x.detach()
else:
for i, l in enumerate(self.features):
x = l(x)
x = x.view(-1, 256*8*8)
for i, l in enumerate(self.linears):
x = l(x)
return x
| true | true |
f710769b0ae8210f3a325400b468f41629c87e45 | 4,382 | py | Python | pipelines/cont_pipeline.py | SurvivorT/SRTP | 1ddc0c4ec31d61daf9f4292c533722e61818eb51 | [
"MIT"
] | 489 | 2017-02-21T21:40:22.000Z | 2022-03-31T08:01:30.000Z | pipelines/cont_pipeline.py | AliBeikmohammadi/MADRL | 3156eb6d6a1e8a4c91ff1dce9f5fc565b2c25c94 | [
"MIT"
] | 35 | 2017-03-10T12:28:11.000Z | 2022-02-14T14:58:21.000Z | pipelines/cont_pipeline.py | AliBeikmohammadi/MADRL | 3156eb6d6a1e8a4c91ff1dce9f5fc565b2c25c94 | [
"MIT"
] | 121 | 2017-02-24T20:13:53.000Z | 2022-03-08T08:56:32.000Z | #!/usr/bin/env python
#
# File: cont_pipeline.py
#
# Created: Friday, July 15 2016 by rejuvyesh <mail@rejuvyesh.com>
#
import argparse
import os
import yaml
import shutil
import rltools
from pipelines import pipeline
# Fix python 2.x
try:
input = raw_input
except NameError:
pass
def phase_train(spec, spec_file):
rltools.util.header('=== Running {} ==='.format(spec_file))
# Make checkpoint dir. All outputs go here
storagedir = spec['options']['storagedir']
n_workers = spec['options']['n_workers']
checkptdir = os.path.join(spec['options']['storagedir'], spec['options']['checkpt_subdir'])
rltools.util.mkdir_p(checkptdir)
assert not os.listdir(checkptdir), 'Checkpoint directory {} is not empty!'.format(checkptdir)
cmd_templates, output_filenames, argdicts = [], [], []
for alg in spec['training']['algorithms']:
for bline in spec['training']['baselines']:
for n_ev in spec['n_evaders']:
for n_pu in spec['n_pursuers']:
for n_se in spec['n_sensors']:
for n_co in spec['n_coop']:
# Number of cooperating agents can't be greater than pursuers
if n_co > n_pu:
continue
for f_rew in spec['food_reward']:
for p_rew in spec['poison_reward']:
for e_rew in spec['encounter_reward']:
for disc in spec['discounts']:
for gae in spec['gae_lambdas']:
for run in range(spec['training']['runs']):
strid = 'alg={},bline={},n_ev={},n_pu={},n_se={},n_co={},f_rew={},p_rew={},e_rew={},disc={},gae={},run={}'.format(
alg['name'], bline, n_ev, n_pu, n_se, n_co,
f_rew, p_rew, e_rew, disc, gae, run)
cmd_templates.append(alg['cmd'].replace(
'\n', ' ').strip())
output_filenames.append(strid + '.txt')
argdicts.append({
'baseline_type': bline,
'n_evaders': n_ev,
'n_pursuers': n_pu,
'n_sensors': n_se,
'n_coop': n_co,
'discount': disc,
'food_reward': f_rew,
'poison_reward': p_rew,
'encounter_reward': e_rew,
'gae_lambda': gae,
'log': os.path.join(checkptdir,
strid + '.h5')
})
rltools.util.ok('{} jobs to run...'.format(len(cmd_templates)))
rltools.util.warn('Continue? y/n')
if input() == 'y':
pipeline.run_jobs(cmd_templates, output_filenames, argdicts, storagedir,
n_workers=n_workers)
else:
rltools.util.failure('Canceled.')
sys.exit(1)
# Copy the pipeline yaml file to the output dir too
shutil.copyfile(spec_file, os.path.join(checkptdir, 'pipeline.yaml'))
# Keep git commit
import subprocess
git_hash = subprocess.check_output('git rev-parse HEAD', shell=True).strip()
with open(os.path.join(checkptdir, 'git_hash.txt'), 'w') as f:
f.write(git_hash + '\n')
def main():
parser = argparse.ArgumentParser()
parser.add_argument('spec', type=str)
args = parser.parse_args()
with open(args.spec, 'r') as f:
spec = yaml.load(f)
phase_train(spec, args.spec)
if __name__ == '__main__':
main()
| 43.82 | 166 | 0.438384 |
import argparse
import os
import yaml
import shutil
import rltools
from pipelines import pipeline
try:
input = raw_input
except NameError:
pass
def phase_train(spec, spec_file):
rltools.util.header('=== Running {} ==='.format(spec_file))
storagedir = spec['options']['storagedir']
n_workers = spec['options']['n_workers']
checkptdir = os.path.join(spec['options']['storagedir'], spec['options']['checkpt_subdir'])
rltools.util.mkdir_p(checkptdir)
assert not os.listdir(checkptdir), 'Checkpoint directory {} is not empty!'.format(checkptdir)
cmd_templates, output_filenames, argdicts = [], [], []
for alg in spec['training']['algorithms']:
for bline in spec['training']['baselines']:
for n_ev in spec['n_evaders']:
for n_pu in spec['n_pursuers']:
for n_se in spec['n_sensors']:
for n_co in spec['n_coop']:
if n_co > n_pu:
continue
for f_rew in spec['food_reward']:
for p_rew in spec['poison_reward']:
for e_rew in spec['encounter_reward']:
for disc in spec['discounts']:
for gae in spec['gae_lambdas']:
for run in range(spec['training']['runs']):
strid = 'alg={},bline={},n_ev={},n_pu={},n_se={},n_co={},f_rew={},p_rew={},e_rew={},disc={},gae={},run={}'.format(
alg['name'], bline, n_ev, n_pu, n_se, n_co,
f_rew, p_rew, e_rew, disc, gae, run)
cmd_templates.append(alg['cmd'].replace(
'\n', ' ').strip())
output_filenames.append(strid + '.txt')
argdicts.append({
'baseline_type': bline,
'n_evaders': n_ev,
'n_pursuers': n_pu,
'n_sensors': n_se,
'n_coop': n_co,
'discount': disc,
'food_reward': f_rew,
'poison_reward': p_rew,
'encounter_reward': e_rew,
'gae_lambda': gae,
'log': os.path.join(checkptdir,
strid + '.h5')
})
rltools.util.ok('{} jobs to run...'.format(len(cmd_templates)))
rltools.util.warn('Continue? y/n')
if input() == 'y':
pipeline.run_jobs(cmd_templates, output_filenames, argdicts, storagedir,
n_workers=n_workers)
else:
rltools.util.failure('Canceled.')
sys.exit(1)
# Copy the pipeline yaml file to the output dir too
shutil.copyfile(spec_file, os.path.join(checkptdir, 'pipeline.yaml'))
# Keep git commit
import subprocess
git_hash = subprocess.check_output('git rev-parse HEAD', shell=True).strip()
with open(os.path.join(checkptdir, 'git_hash.txt'), 'w') as f:
f.write(git_hash + '\n')
def main():
parser = argparse.ArgumentParser()
parser.add_argument('spec', type=str)
args = parser.parse_args()
with open(args.spec, 'r') as f:
spec = yaml.load(f)
phase_train(spec, args.spec)
if __name__ == '__main__':
main()
| true | true |
f71076ba0db1bec326551e5faa965b228c3a02be | 1,296 | py | Python | src/resnet_model/read_lmdb.py | Granular-data/cloudless | e45d93b48b8e668a8a6cea6fab51d59f389591a8 | [
"Apache-2.0"
] | null | null | null | src/resnet_model/read_lmdb.py | Granular-data/cloudless | e45d93b48b8e668a8a6cea6fab51d59f389591a8 | [
"Apache-2.0"
] | null | null | null | src/resnet_model/read_lmdb.py | Granular-data/cloudless | e45d93b48b8e668a8a6cea6fab51d59f389591a8 | [
"Apache-2.0"
] | null | null | null | import sys
sys.path.insert(0,'../../../deeplab-public-ver2/python')
import caffe
import leveldb
import numpy as np
from caffe.proto import caffe_pb2
import csv
import cv2
# Wei Yang 2015-08-19
# Source
# Read LevelDB/LMDB
# ==================
# http://research.beenfrog.com/code/2015/03/28/read-leveldb-lmdb-for-caffe-with-python.html
# Plot image
# ==================
# http://www.pyimagesearch.com/2014/11/03/display-matplotlib-rgb-image/
# Creating LMDB in python
# ==================
# http://deepdish.io/2015/04/28/creating-lmdb-in-python/
leveldb_dir = "../../../../datasets/planet_cloudless/leveldb/train_leveldb"
PC_DIR = "../../../../datasets/planet_cloudless/"
OUT_DIR = PC_DIR + "images/"
w_train = csv.writer(open(PC_DIR + "train.csv", 'w'), delimiter=" ")
db = leveldb.LevelDB(leveldb_dir)
datum = caffe_pb2.Datum()
img_no = 0
for key, value in db.RangeIter():
datum.ParseFromString(value)
label = datum.label
data = caffe.io.datum_to_array(datum)
r = data[0,:,:]
g = data[1,:,:]
b = data[2,:,:]
#rgb rbg gbr grb brg bgr
image = cv2.merge([r,b,g])
cv2.imwrite(OUT_DIR + str(img_no).zfill(10) + '.jpg', image)
w_train.writerow([OUT_DIR + str(img_no).zfill(10) + '.jpg', label])
img_no += 1
| 25.411765 | 97 | 0.623457 | import sys
sys.path.insert(0,'../../../deeplab-public-ver2/python')
import caffe
import leveldb
import numpy as np
from caffe.proto import caffe_pb2
import csv
import cv2
leveldb_dir = "../../../../datasets/planet_cloudless/leveldb/train_leveldb"
PC_DIR = "../../../../datasets/planet_cloudless/"
OUT_DIR = PC_DIR + "images/"
w_train = csv.writer(open(PC_DIR + "train.csv", 'w'), delimiter=" ")
db = leveldb.LevelDB(leveldb_dir)
datum = caffe_pb2.Datum()
img_no = 0
for key, value in db.RangeIter():
datum.ParseFromString(value)
label = datum.label
data = caffe.io.datum_to_array(datum)
r = data[0,:,:]
g = data[1,:,:]
b = data[2,:,:]
image = cv2.merge([r,b,g])
cv2.imwrite(OUT_DIR + str(img_no).zfill(10) + '.jpg', image)
w_train.writerow([OUT_DIR + str(img_no).zfill(10) + '.jpg', label])
img_no += 1
| true | true |
f71076f22cf14b8fce877f67e5317aca94dd9306 | 7,920 | py | Python | docs/conf.py | determined-ai/pedl_sphinx_theme | 9edfa7c6ce6926def9fc69b8ddd7666f3419a907 | [
"MIT"
] | null | null | null | docs/conf.py | determined-ai/pedl_sphinx_theme | 9edfa7c6ce6926def9fc69b8ddd7666f3419a907 | [
"MIT"
] | 2 | 2020-03-10T00:15:46.000Z | 2020-04-04T19:39:15.000Z | docs/conf.py | determined-ai/pedl_sphinx_theme | 9edfa7c6ce6926def9fc69b8ddd7666f3419a907 | [
"MIT"
] | null | null | null | import sys
import os
sys.path.append(os.path.abspath('..'))
sys.path.append(os.path.abspath('./demo/'))
from determined_ai_sphinx_theme import __version__
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'sphinx.ext.intersphinx',
'sphinx.ext.autodoc',
'sphinx.ext.viewcode',
'sphinxcontrib.httpdomain',
]
# Do not warn about external images (status badges in README.rst)
suppress_warnings = ['image.nonlocal_uri']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'PyTorch Sphinx Theme'
copyright = u'PyTorch'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = __version__
# The full version, including alpha/beta/rc tags.
release = __version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
language = 'en'
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'default'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
intersphinx_mapping = {'rtd': ('https://docs.readthedocs.io/en/latest/', None)}
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'determined_ai_sphinx_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
'logo_only': True
}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ["../"]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = "demo/static/pytorch-logo-dark.svg"
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
#html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'DeterminedAISphinxthemedemodoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'PyTorchthemedemo.tex', u'PyTorch theme demo Documentation',
u'PyTorch, PyTorch', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'pytorchthemedemo', u'PyTorch theme demo Documentation',
[u'PyTorch'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'PyTorchthemedemo', u'PyTorch theme demo Documentation',
u'PyTorch', 'PyTorchthemedemo',
'One line description of project.', 'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
| 31.935484 | 80 | 0.716162 | import sys
import os
sys.path.append(os.path.abspath('..'))
sys.path.append(os.path.abspath('./demo/'))
from determined_ai_sphinx_theme import __version__
extensions = [
'sphinx.ext.intersphinx',
'sphinx.ext.autodoc',
'sphinx.ext.viewcode',
'sphinxcontrib.httpdomain',
]
suppress_warnings = ['image.nonlocal_uri']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'PyTorch Sphinx Theme'
copyright = u'PyTorch'
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = __version__
# The full version, including alpha/beta/rc tags.
release = __version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
language = 'en'
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'default'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
intersphinx_mapping = {'rtd': ('https://docs.readthedocs.io/en/latest/', None)}
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'determined_ai_sphinx_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
'logo_only': True
}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ["../"]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = "demo/static/pytorch-logo-dark.svg"
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
#html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'DeterminedAISphinxthemedemodoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'PyTorchthemedemo.tex', u'PyTorch theme demo Documentation',
u'PyTorch, PyTorch', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'pytorchthemedemo', u'PyTorch theme demo Documentation',
[u'PyTorch'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'PyTorchthemedemo', u'PyTorch theme demo Documentation',
u'PyTorch', 'PyTorchthemedemo',
'One line description of project.', 'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
| true | true |
f710770cd6b6cc55fa5e3661cb8e82cfeb494a6f | 313 | py | Python | console/widgets/extra.py | dustinlacewell/console | b65f63354dd8ba60f211e3e169e53c078b99fdf8 | [
"MIT"
] | 11 | 2015-06-10T22:23:03.000Z | 2021-02-16T10:55:55.000Z | console/widgets/extra.py | rrosajp/console | b65f63354dd8ba60f211e3e169e53c078b99fdf8 | [
"MIT"
] | 1 | 2015-07-01T00:04:50.000Z | 2015-08-19T16:40:18.000Z | console/widgets/extra.py | rrosajp/console | b65f63354dd8ba60f211e3e169e53c078b99fdf8 | [
"MIT"
] | 5 | 2015-06-20T11:08:32.000Z | 2022-03-07T00:01:50.000Z | import urwid
class AlwaysFocusedEdit(urwid.Edit):
"""
This Edit widget is convinced that it is always in focus. This is so that
it will respond to input events even if it isn't.'
"""
def render(self, size, focus=False):
return super(AlwaysFocusedEdit, self).render(size, focus=True)
| 28.454545 | 77 | 0.690096 | import urwid
class AlwaysFocusedEdit(urwid.Edit):
def render(self, size, focus=False):
return super(AlwaysFocusedEdit, self).render(size, focus=True)
| true | true |
f7107796de3cb4b1078c5b12ab816311e6504df2 | 3,833 | py | Python | ui/tests/test_base.py | iqre8/kubeinit | ef5988e8b8649452bb9c94f465add4626a660def | [
"Apache-2.0"
] | null | null | null | ui/tests/test_base.py | iqre8/kubeinit | ef5988e8b8649452bb9c94f465add4626a660def | [
"Apache-2.0"
] | null | null | null | ui/tests/test_base.py | iqre8/kubeinit | ef5988e8b8649452bb9c94f465add4626a660def | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
"""
Copyright 2019 Kubeinit (kubeinit.com).
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
"""
from logging import CRITICAL, disable
disable(CRITICAL)
urls = {
'': (
'/fixed_sidebar',
'/fixed_footer',
'/plain_page',
'/page_403',
'/page_404',
'/page_500'
),
'/home': (
'/index',
'/index2',
'/index3'
),
'/forms': (
'/form',
'/form_advanced',
'/form_validation',
'/form_wizards',
'/form_upload',
'/form_buttons'
),
'/ui': (
'/general_elements',
'/media_gallery',
'/typography',
'/icons',
'/glyphicons',
'/widgets',
'/invoice',
'/inbox',
'/calendar'
),
'/tables': (
'/tables',
'/tables_dynamic'
),
'/data': (
'/chartjs',
'/chartjs2',
'/morisjs',
'/echarts',
'/other_charts'
),
'/additional': (
'/ecommerce',
'/projects',
'/project_detail',
'/contacts',
'/profile',
'/pricing'
)
}
free_access = {'/', '/login', '/page_403', '/page_404', '/page_500'}
def check_pages(*pages):
"""
Test the base app.
This is method function
"""
def decorator(function):
def wrapper(user_client):
function(user_client)
for page in pages:
r = user_client.get(page, follow_redirects=True)
print(r)
# assert r.status_code == 200
assert True
return wrapper
return decorator
def check_blueprints(*blueprints):
"""
Test the base app.
This is method function
"""
def decorator(function):
def wrapper(user_client):
function(user_client)
for blueprint in blueprints:
for page in urls[blueprint]:
r = user_client.get(blueprint + page,
follow_redirects=True)
print(r)
# assert r.status_code == 200
assert True
return wrapper
return decorator
# Base test
# test the login system: login, user creation, logout
# test that all pages respond with HTTP 403 if not logged in, 200 otherwise
def test_authentication(base_client):
"""
Test the base app.
This is method function
"""
for blueprint, pages in urls.items():
for page in pages:
page_url = blueprint + page
expected_code = 200 if page_url in free_access else 403
r = base_client.get(page_url, follow_redirects=True)
print(expected_code)
print(r)
# assert r.status_code == expected_code
assert True
def test_urls(user_client):
"""
Test the base app.
This is method function
"""
for blueprint, pages in urls.items():
for page in pages:
page_url = blueprint + page
r = user_client.get(page_url, follow_redirects=True)
print(r)
# assert r.status_code == 200
assert True
# logout and test that we cannot access anything anymore
r = user_client.get('/logout', follow_redirects=True)
test_authentication(user_client)
| 24.729032 | 75 | 0.559614 |
from logging import CRITICAL, disable
disable(CRITICAL)
urls = {
'': (
'/fixed_sidebar',
'/fixed_footer',
'/plain_page',
'/page_403',
'/page_404',
'/page_500'
),
'/home': (
'/index',
'/index2',
'/index3'
),
'/forms': (
'/form',
'/form_advanced',
'/form_validation',
'/form_wizards',
'/form_upload',
'/form_buttons'
),
'/ui': (
'/general_elements',
'/media_gallery',
'/typography',
'/icons',
'/glyphicons',
'/widgets',
'/invoice',
'/inbox',
'/calendar'
),
'/tables': (
'/tables',
'/tables_dynamic'
),
'/data': (
'/chartjs',
'/chartjs2',
'/morisjs',
'/echarts',
'/other_charts'
),
'/additional': (
'/ecommerce',
'/projects',
'/project_detail',
'/contacts',
'/profile',
'/pricing'
)
}
free_access = {'/', '/login', '/page_403', '/page_404', '/page_500'}
def check_pages(*pages):
def decorator(function):
def wrapper(user_client):
function(user_client)
for page in pages:
r = user_client.get(page, follow_redirects=True)
print(r)
assert True
return wrapper
return decorator
def check_blueprints(*blueprints):
def decorator(function):
def wrapper(user_client):
function(user_client)
for blueprint in blueprints:
for page in urls[blueprint]:
r = user_client.get(blueprint + page,
follow_redirects=True)
print(r)
assert True
return wrapper
return decorator
def test_authentication(base_client):
for blueprint, pages in urls.items():
for page in pages:
page_url = blueprint + page
expected_code = 200 if page_url in free_access else 403
r = base_client.get(page_url, follow_redirects=True)
print(expected_code)
print(r)
assert True
def test_urls(user_client):
for blueprint, pages in urls.items():
for page in pages:
page_url = blueprint + page
r = user_client.get(page_url, follow_redirects=True)
print(r)
assert True
r = user_client.get('/logout', follow_redirects=True)
test_authentication(user_client)
| true | true |
f71077ad9b03cf9d6c21b1546d2812ac45c55448 | 1,010 | py | Python | Examples/first_vscode/robot2.py | slowrunner/GoPiLgc | e86505d83b2d2e7b1c5c2a04c1eed19774cf76b0 | [
"CC0-1.0"
] | null | null | null | Examples/first_vscode/robot2.py | slowrunner/GoPiLgc | e86505d83b2d2e7b1c5c2a04c1eed19774cf76b0 | [
"CC0-1.0"
] | null | null | null | Examples/first_vscode/robot2.py | slowrunner/GoPiLgc | e86505d83b2d2e7b1c5c2a04c1eed19774cf76b0 | [
"CC0-1.0"
] | null | null | null | #!/usr/bin/python3
# FILE: robot2.py
# PURPOSE: Test reading distance sensor and ultrasonic sensor
from easygopigo3 import EasyGoPiGo3
import time
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(funcName)s: %(message)s')
DIODE_DROP = 0.7
ULTRASONIC_CORRECTION_AT_100mm = 17.0 # mm
ToF_CORRECTION_AT_100mm = -5.0 # mm
def main():
egpg = EasyGoPiGo3(use_mutex=True)
egpg.ds = egpg.init_distance_sensor()
egpg.us = egpg.init_ultrasonic_sensor(port="AD2")
while True:
try:
vBatt = egpg.volt()+DIODE_DROP
dist_ds_mm = egpg.ds.read_mm()+ToF_CORRECTION_AT_100mm
time.sleep(0.01)
dist_us_mm = egpg.us.read_mm()+ULTRASONIC_CORRECTION_AT_100mm
logging.info(": vBatt:{:>5.2f}v ds:{:>5.0f}mm us:{:>5.0f}mm".format(vBatt,dist_ds_mm,dist_us_mm))
time.sleep(0.075)
except KeyboardInterrupt:
print("\nExiting...")
break
if __name__ == "__main__":
main() | 28.055556 | 111 | 0.654455 |
from easygopigo3 import EasyGoPiGo3
import time
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(funcName)s: %(message)s')
DIODE_DROP = 0.7
ULTRASONIC_CORRECTION_AT_100mm = 17.0
ToF_CORRECTION_AT_100mm = -5.0
def main():
egpg = EasyGoPiGo3(use_mutex=True)
egpg.ds = egpg.init_distance_sensor()
egpg.us = egpg.init_ultrasonic_sensor(port="AD2")
while True:
try:
vBatt = egpg.volt()+DIODE_DROP
dist_ds_mm = egpg.ds.read_mm()+ToF_CORRECTION_AT_100mm
time.sleep(0.01)
dist_us_mm = egpg.us.read_mm()+ULTRASONIC_CORRECTION_AT_100mm
logging.info(": vBatt:{:>5.2f}v ds:{:>5.0f}mm us:{:>5.0f}mm".format(vBatt,dist_ds_mm,dist_us_mm))
time.sleep(0.075)
except KeyboardInterrupt:
print("\nExiting...")
break
if __name__ == "__main__":
main() | true | true |
f71077dfaecb2df505c4d5574b2fd9f2d6699926 | 3,190 | py | Python | app.py | sejaldua/duolingogogo | 226a2a9417238f9c3f0ce738d491b58cdf4dcbdc | [
"MIT"
] | null | null | null | app.py | sejaldua/duolingogogo | 226a2a9417238f9c3f0ce738d491b58cdf4dcbdc | [
"MIT"
] | null | null | null | app.py | sejaldua/duolingogogo | 226a2a9417238f9c3f0ce738d491b58cdf4dcbdc | [
"MIT"
] | null | null | null | import streamlit as st
import pandas as pd
import yaml
import duolingo
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.font_manager
from datetime import timezone, timedelta
matplotlib.rcParams['font.family'] = ['Source Han Sans CN']
with open("duo_credentials.yaml", 'r') as stream:
creds = yaml.safe_load(stream)
lingo = duolingo.Duolingo(creds['username'], creds['password'])
st.write("Hello :wave: " + lingo.get_user_info()['username'])
streak = lingo.get_streak_info()
xp = lingo.get_daily_xp_progress()
st.header("Calendar")
cal = lingo.get_calendar('zs')
cal_df = pd.DataFrame.from_records(cal)
# creating new datetime-based features
# cal_df['timestamp'] = cal_df['datetime'].apply(lambda x: pytz.timezone("America/New_York").localize(pd.to_datetime(x, unit='ms'), is_dst=None))
cal_df['timestamp'] = cal_df['datetime'].apply(lambda x: pd.to_datetime(x, unit='ms') - timedelta(hours=4))
cal_df['year'] = cal_df.timestamp.dt.year
cal_df['month'] = cal_df.timestamp.dt.month
cal_df['hour'] = cal_df.timestamp.dt.hour
cal_df['weekday'] = cal_df.timestamp.dt.day_name()
cal_df['week_num'] = cal_df['timestamp'].apply(lambda x: x.isocalendar()[1] % 52)
# get weekday_num in order of MTWTFSS because we want to sort the rows of the heatmap in order
weekday_order = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
mapping = {k: v for k, v in zip(weekday_order, [i+1 for i in range(7)])}
cal_df['weekday_num'] = cal_df['weekday'].apply(lambda x: mapping[x])
# st.dataframe(cal_df)
df_to_pivot = cal_df[['week_num', 'weekday_num', 'improvement']]
pivoted_data = pd.pivot_table(df_to_pivot, values='improvement', index=['weekday_num'], columns=['week_num'], aggfunc=sum)
pivoted_data = pivoted_data.reindex([i+1 for i in range(max(pivoted_data.columns))], axis=1)
pivoted_data.dropna(axis=1, how='all', inplace=True)
# st.dataframe(pivoted_data)
fig = plt.figure(figsize=(6,4));
sns.heatmap(pivoted_data, linewidths=6, cmap='BuGn', cbar=True,
linecolor='white', square=True, yticklabels=weekday_order);
# xticklabels=[*space, 'Jan', *space, 'Feb', *space, 'Mar', *space, 'Apr',
# *space, 'May', *space, 'Jun', *space, 'Jul']);
plt.ylabel("");
plt.xlabel("");
st.write(fig)
# cal_df.sort_values(by='datetime', ascending=False, inplace=True)
# cal_df['datetime'] = cal_df['datetime'].apply(lambda x: pd.to_datetime(x, unit='ms').date())
# fig = plt.figure(figsize=(10,6))
# ax = sns.barplot(data=cal_df, x='datetime', y='improvement', estimator=sum, ci=None)
# st.write(fig)
st.header("Language Details")
ld = lingo.get_language_details('Chinese')
lp = lingo.get_language_progress('zs')
st.write("Streak: ", ld['streak'], " :fire:")
st.write("Total points: ", ld['points'], " 📈")
st.write("Skills learned: ", lp['num_skills_learned'], " :seedling:")
st.write("Current level: ", ld['level'], " 🤓")
st.write('Progress towards next level: ', lp['level_progress'], '/', lp['level_points'])
st.progress(lp['level_percent'])
st.header('Known Topics')
st.write(', '.join(lingo.get_known_topics('zs')))
st.header('Known Words')
st.write(', '.join(lingo.get_known_words('zs')))
| 43.108108 | 145 | 0.70094 | import streamlit as st
import pandas as pd
import yaml
import duolingo
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.font_manager
from datetime import timezone, timedelta
matplotlib.rcParams['font.family'] = ['Source Han Sans CN']
with open("duo_credentials.yaml", 'r') as stream:
creds = yaml.safe_load(stream)
lingo = duolingo.Duolingo(creds['username'], creds['password'])
st.write("Hello :wave: " + lingo.get_user_info()['username'])
streak = lingo.get_streak_info()
xp = lingo.get_daily_xp_progress()
st.header("Calendar")
cal = lingo.get_calendar('zs')
cal_df = pd.DataFrame.from_records(cal)
cal_df['timestamp'] = cal_df['datetime'].apply(lambda x: pd.to_datetime(x, unit='ms') - timedelta(hours=4))
cal_df['year'] = cal_df.timestamp.dt.year
cal_df['month'] = cal_df.timestamp.dt.month
cal_df['hour'] = cal_df.timestamp.dt.hour
cal_df['weekday'] = cal_df.timestamp.dt.day_name()
cal_df['week_num'] = cal_df['timestamp'].apply(lambda x: x.isocalendar()[1] % 52)
weekday_order = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
mapping = {k: v for k, v in zip(weekday_order, [i+1 for i in range(7)])}
cal_df['weekday_num'] = cal_df['weekday'].apply(lambda x: mapping[x])
df_to_pivot = cal_df[['week_num', 'weekday_num', 'improvement']]
pivoted_data = pd.pivot_table(df_to_pivot, values='improvement', index=['weekday_num'], columns=['week_num'], aggfunc=sum)
pivoted_data = pivoted_data.reindex([i+1 for i in range(max(pivoted_data.columns))], axis=1)
pivoted_data.dropna(axis=1, how='all', inplace=True)
fig = plt.figure(figsize=(6,4));
sns.heatmap(pivoted_data, linewidths=6, cmap='BuGn', cbar=True,
linecolor='white', square=True, yticklabels=weekday_order);
plt.ylabel("");
plt.xlabel("");
st.write(fig)
st.header("Language Details")
ld = lingo.get_language_details('Chinese')
lp = lingo.get_language_progress('zs')
st.write("Streak: ", ld['streak'], " :fire:")
st.write("Total points: ", ld['points'], " 📈")
st.write("Skills learned: ", lp['num_skills_learned'], " :seedling:")
st.write("Current level: ", ld['level'], " 🤓")
st.write('Progress towards next level: ', lp['level_progress'], '/', lp['level_points'])
st.progress(lp['level_percent'])
st.header('Known Topics')
st.write(', '.join(lingo.get_known_topics('zs')))
st.header('Known Words')
st.write(', '.join(lingo.get_known_words('zs')))
| true | true |
f71077e6e85282814575b8276103abfbb46cbf21 | 25,589 | py | Python | big-fish/bigfish/stack/postprocess.py | Henley13/paper_translation_factories_2020 | 77558ed70467cf91062abf62e46c794bfbc08e4a | [
"BSD-3-Clause"
] | 2 | 2020-09-03T20:50:53.000Z | 2020-10-02T14:39:31.000Z | big-fish/bigfish/stack/postprocess.py | Henley13/paper_translation_factories_2020 | 77558ed70467cf91062abf62e46c794bfbc08e4a | [
"BSD-3-Clause"
] | 4 | 2020-01-15T10:26:14.000Z | 2020-10-01T18:36:39.000Z | big-fish/bigfish/stack/postprocess.py | Henley13/paper_translation_factories_2020 | 77558ed70467cf91062abf62e46c794bfbc08e4a | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Functions used to format and clean any intermediate results loaded in or
returned by a bigfish method.
"""
import numpy as np
from scipy import ndimage as ndi
from .utils import check_array, check_parameter, get_offset_value
from skimage.measure import regionprops, find_contours
from skimage.draw import polygon_perimeter
# ### Transcription sites ###
def remove_transcription_site(mask_nuc, spots_in_foci, foci):
"""We define a transcription site as a foci detected in the nucleus.
Parameters
----------
mask_nuc : np.ndarray, bool
Binary mask of the nuclei with shape (y, x).
spots_in_foci : np.ndarray, np.int64
Coordinate of the spots detected inside foci, with shape (nb_spots, 4).
One coordinate per dimension (zyx coordinates) plus the index of the
foci.
foci : np.ndarray, np.int64
Array with shape (nb_foci, 5). One coordinate per dimension for the
foci centroid (zyx coordinates), the number of RNAs detected in the
foci and its index.
Returns
-------
spots_in_foci_cleaned : np.ndarray, np.int64
Coordinate of the spots detected inside foci, with shape (nb_spots, 4).
One coordinate per dimension (zyx coordinates) plus the index of the
foci. Transcription sites are removed.
foci_cleaned : np.ndarray, np.int64
Array with shape (nb_foci, 5). One coordinate per dimension for the
foci centroid (zyx coordinates), the number of RNAs detected in the
foci and its index. Transcription sites are removed.
"""
# check parameters
check_array(mask_nuc,
ndim=2,
dtype=[bool],
allow_nan=False)
check_array(spots_in_foci,
ndim=2,
dtype=[np.int64],
allow_nan=False)
check_array(foci,
ndim=2,
dtype=[np.int64],
allow_nan=False)
# remove foci inside nuclei
mask_transcription_site = mask_nuc[foci[:, 1], foci[:, 2]]
foci_cleaned = foci[~mask_transcription_site]
# filter spots in transcription sites
spots_to_keep = foci_cleaned[:, 4]
mask_spots_to_keep = np.isin(spots_in_foci[:, 3], spots_to_keep)
spots_in_foci_cleaned = spots_in_foci[mask_spots_to_keep]
return spots_in_foci_cleaned, foci_cleaned
# ### Cell extraction ###
def extract_spots_from_frame(spots, z_lim=None, y_lim=None, x_lim=None):
"""Get spots coordinates within a given frame.
Parameters
----------
spots : np.ndarray, np.int64
Coordinate of the spots detected inside foci, with shape (nb_spots, 3)
or (nb_spots, 4). One coordinate per dimension (zyx coordinates) plus
the index of the foci if necessary.
z_lim : tuple[int, int]
Minimum and maximum coordinate of the frame along the z axis.
y_lim : tuple[int, int]
Minimum and maximum coordinate of the frame along the y axis.
x_lim : tuple[int, int]
Minimum and maximum coordinate of the frame along the x axis.
Returns
-------
extracted_spots : np.ndarray, np.int64
Coordinate of the spots detected inside foci, with shape (nb_spots, 3)
or (nb_spots, 4). One coordinate per dimension (zyx coordinates) plus
the index of the foci if necessary.
"""
# check parameters
check_array(spots,
ndim=2,
dtype=[np.int64],
allow_nan=False)
check_parameter(z_lim=(tuple, type(None)),
y_lim=(tuple, type(None)),
x_lim=(tuple, type(None)))
# extract spots
extracted_spots = spots.copy()
if z_lim is not None:
extracted_spots = extracted_spots[extracted_spots[:, 0] < z_lim[1]]
extracted_spots = extracted_spots[z_lim[0] < extracted_spots[:, 0]]
extracted_spots[:, 0] -= z_lim[0]
if y_lim is not None:
extracted_spots = extracted_spots[extracted_spots[:, 1] < y_lim[1]]
extracted_spots = extracted_spots[y_lim[0] < extracted_spots[:, 1]]
extracted_spots[:, 1] -= y_lim[0]
if x_lim is not None:
extracted_spots = extracted_spots[extracted_spots[:, 2] < x_lim[1]]
extracted_spots = extracted_spots[x_lim[0] < extracted_spots[:, 2]]
extracted_spots[:, 2] -= x_lim[0]
return extracted_spots
def extract_coordinates_image(cyt_labelled, nuc_labelled, spots_out, spots_in,
foci):
"""Extract relevant coordinates from an image, based on segmentation and
detection results.
For each cell in an image we return the coordinates of the cytoplasm, the
nucleus, the RNA spots and information about the detected foci. We extract
2-d coordinates for the cell and 3-d coordinates for the spots and foci.
Parameters
----------
cyt_labelled : np.ndarray, np.uint or np.int
Labelled cytoplasms image with shape (y, x).
nuc_labelled : np.ndarray, np.uint or np.int
Labelled nuclei image with shape (y, x).
spots_out : np.ndarray, np.int64
Coordinate of the spots detected outside foci, with shape
(nb_spots, 4). One coordinate per dimension (zyx coordinates) plus a
default index (-1 for mRNAs spotted outside a foci).
spots_in : np.ndarray, np.int64
Coordinate of the spots detected inside foci, with shape (nb_spots, 4).
One coordinate per dimension (zyx coordinates) plus the index of the
foci.
foci : np.ndarray, np.int64
Array with shape (nb_foci, 5). One coordinate per dimension for the
foci centroid (zyx coordinates), the number of RNAs detected in the
foci and its index.
Returns
-------
results : List[(cyt_coord, nuc_coord, rna_coord, cell_foci, cell)]
- cyt_coord : np.ndarray, np.int64
Coordinates of the cytoplasm border with shape (nb_points, 2).
- nuc_coord : np.ndarray, np.int64
Coordinates of the nuclei border with shape (nb_points, 2).
- rna_coord : np.ndarray, np.int64
Coordinates of the RNA spots with shape (nb_spots, 4). One
coordinate per dimension (zyx dimension), plus the index of a
potential foci.
- cell_foci : np.ndarray, np.int64
Array with shape (nb_foci, 5). One coordinate per dimension for the
foci centroid (zyx coordinates), the number of RNAs detected in the
foci and its index.
- cell : Tuple[int]
Box coordinate of the cell in the original image (min_y, min_x,
max_y and max_x).
"""
# check parameters
check_array(cyt_labelled,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64],
allow_nan=True)
check_array(nuc_labelled,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64],
allow_nan=True)
check_array(spots_out,
ndim=2,
dtype=[np.int64],
allow_nan=False)
check_array(spots_in,
ndim=2,
dtype=[np.int64],
allow_nan=False)
check_array(foci,
ndim=2,
dtype=[np.int64],
allow_nan=False)
# initialize results
results = []
borders = np.zeros(cyt_labelled.shape, dtype=bool)
borders[:, 0] = True
borders[0, :] = True
borders[:, cyt_labelled.shape[1] - 1] = True
borders[cyt_labelled.shape[0] - 1, :] = True
cells = regionprops(cyt_labelled)
for cell in cells:
# get information about the cell
label = cell.label
(min_y, min_x, max_y, max_x) = cell.bbox
# get masks of the cell
cyt = cyt_labelled.copy()
cyt = (cyt == label)
nuc = nuc_labelled.copy()
nuc = (nuc == label)
# check if cell is not cropped by the borders
if _check_cropped_cell(cyt, borders):
continue
# check if nucleus is in the cytoplasm
if not _check_nucleus_in_cell(cyt, nuc):
continue
# get boundaries coordinates
cyt_coord, nuc_coord = _get_boundaries_coordinates(cyt, nuc)
# filter foci
foci_cell, spots_in_foci_cell = _extract_foci(foci, spots_in, cyt)
# get rna coordinates
spots_out_foci_cell = _extract_spots_outside_foci(cyt, spots_out)
rna_coord = np.concatenate([spots_out_foci_cell, spots_in_foci_cell],
axis=0)
# filter cell without enough spots
if len(rna_coord) < 30:
continue
# initialize cell coordinates
cyt_coord[:, 0] -= min_y
cyt_coord[:, 1] -= min_x
nuc_coord[:, 0] -= min_y
nuc_coord[:, 1] -= min_x
rna_coord[:, 1] -= min_y
rna_coord[:, 2] -= min_x
foci_cell[:, 1] -= min_y
foci_cell[:, 2] -= min_x
results.append((cyt_coord, nuc_coord, rna_coord, foci_cell, cell.bbox))
return results
def _check_cropped_cell(cell_cyt_mask, border_frame):
"""
Check if a cell is cropped by the border frame.
Parameters
----------
cell_cyt_mask : np.ndarray, bool
Binary mask of the cell cytoplasm.
border_frame : np.ndarray, bool
Binary mask of the border frame.
Returns
-------
_ : bool
True if cell is cropped.
"""
# check cell is not cropped by the borders
crop = cell_cyt_mask & border_frame
if np.any(crop):
return True
else:
return False
def _check_nucleus_in_cell(cell_cyt_mask, cell_nuc_mask):
"""
Check if the nucleus is properly contained in the cell cytoplasm.
Parameters
----------
cell_cyt_mask : np.ndarray, bool
Binary mask of the cell cytoplasm.
cell_nuc_mask : np.ndarray, bool
Binary mask of the nucleus cytoplasm.
Returns
-------
_ : bool
True if the nucleus is in the cell.
"""
diff = cell_cyt_mask | cell_nuc_mask
if np.any(diff != cell_cyt_mask):
return False
else:
return True
def _get_boundaries_coordinates(cell_cyt_mask, cell_nuc_mask):
"""
Find boundaries coordinates for cytoplasm and nucleus.
Parameters
----------
cell_cyt_mask : np.ndarray, bool
Mask of the cell cytoplasm.
cell_nuc_mask : np.ndarray, bool
Mask of the cell nucleus.
Returns
-------
cyt_coord : np.ndarray, np.int64
Coordinates of the cytoplasm in 2-d (yx dimension).
nuc_coord : np.ndarray, np.int64
Coordinates of the nucleus in 2-d (yx dimension).
"""
cyt_coord = np.array([], dtype=np.int64).reshape((0, 2))
nuc_coord = np.array([], dtype=np.int64).reshape((0, 2))
# cyt coordinates
cell_cyt_coord = find_contours(cell_cyt_mask, level=0)
if len(cell_cyt_coord) == 0:
pass
elif len(cell_cyt_coord) == 1:
cyt_coord = cell_cyt_coord[0].astype(np.int64)
else:
m = 0
for coord in cell_cyt_coord:
if len(coord) > m:
m = len(coord)
cyt_coord = coord.astype(np.int64)
# nuc coordinates
cell_nuc_coord = find_contours(cell_nuc_mask, level=0)
if len(cell_nuc_coord) == 0:
pass
elif len(cell_nuc_coord) == 1:
nuc_coord = cell_nuc_coord[0].astype(np.int64)
else:
m = 0
for coord in cell_nuc_coord:
if len(coord) > m:
m = len(coord)
nuc_coord = coord.astype(np.int64)
return cyt_coord, nuc_coord
def _extract_foci(foci, spots_in_foci, cell_cyt_mask):
"""
Extract foci and related spots detected in a specific cell.
Parameters
----------
foci : np.ndarray, np.int64
Array with shape (nb_foci, 5). One coordinate per dimension for the
foci centroid (zyx coordinates), the number of RNAs detected in the
foci and its index.
spots_in_foci : : np.ndarray, np.int64
Coordinate of the spots detected inside foci, with shape (nb_spots, 4).
One coordinate per dimension (zyx coordinates) plus the index of the
foci.
cell_cyt_mask : np.ndarray, bool
Binary mask of the cell with shape (y, x).
Returns
-------
spots_in_foci_cell : np.ndarray, np.int64
Coordinate of the spots detected inside foci in the cell, with shape
(nb_spots, 4). One coordinate per dimension (zyx coordinates) plus the
index of the foci.
foci_cell : np.ndarray, np.int64
Array with shape (nb_foci, 5). One coordinate per dimension for the
foci centroid (zyx coordinates), the number of RNAs detected in the
foci and its index.
"""
# filter foci
mask_foci_cell = cell_cyt_mask[foci[:, 1], foci[:, 2]]
if mask_foci_cell.sum() == 0:
foci_cell = np.array([], dtype=np.int64).reshape((0, 5))
spots_in_foci_cell = np.array([], dtype=np.int64).reshape((0, 4))
return foci_cell, spots_in_foci_cell
foci_cell = foci[mask_foci_cell]
# filter spots in foci
spots_to_keep = foci_cell[:, 4]
mask_spots_to_keep = np.isin(spots_in_foci[:, 3], spots_to_keep)
spots_in_foci_cell = spots_in_foci[mask_spots_to_keep]
return foci_cell, spots_in_foci_cell
def _extract_spots_outside_foci(cell_cyt_mask, spots_out_foci):
"""
Extract spots detected outside foci, in a specific cell.
Parameters
----------
cell_cyt_mask : np.ndarray, bool
Binary mask of the cell with shape (y, x).
spots_out_foci : np.ndarray, np.int64
Coordinate of the spots detected outside foci, with shape
(nb_spots, 4). One coordinate per dimension (zyx coordinates) plus a
default index (-1 for mRNAs spotted outside a foci).
Returns
-------
spots_out_foci_cell : np.ndarray, np.int64
Coordinate of the spots detected outside foci in the cell, with shape
(nb_spots, 4). One coordinate per dimension (zyx coordinates) plus the
index of the foci.
"""
# get coordinates of rna outside foci
mask_spots_to_keep = cell_cyt_mask[spots_out_foci[:, 1],
spots_out_foci[:, 2]]
spots_out_foci_cell = spots_out_foci[mask_spots_to_keep]
return spots_out_foci_cell
# ### Segmentation postprocessing ###
# TODO add from_binary_surface_to_binary_boundaries
def center_binary_mask(cyt, nuc=None, rna=None):
"""Center a 2-d binary mask (surface or boundaries) and pad it.
One mask should be at least provided ('cyt'). If others masks are provided
('nuc' and 'rna'), they will be transformed like the main mask. All the
provided masks should have the same shape. If others coordinates are
provided, the values will be transformed, but an array of coordinates with
the same format is returned
Parameters
----------
cyt : np.ndarray, np.uint or np.int or bool
Binary image of cytoplasm with shape (y, x).
nuc : np.ndarray, np.uint or np.int or bool
Binary image of nucleus with shape (y, x) or array of nucleus
coordinates with shape (nb_points, 2).
rna : np.ndarray, np.uint or np.int or bool
Binary image of mRNAs localization with shape (y, x) or array of mRNAs
coordinates with shape (nb_points, 2) or (nb_points, 3).
Returns
-------
cyt_centered : np.ndarray, np.uint or np.int or bool
Centered binary image of cytoplasm with shape (y, x).
nuc_centered : np.ndarray, np.uint or np.int or bool
Centered binary image of nucleus with shape (y, x).
rna_centered : np.ndarray, np.uint or np.int or bool
Centered binary image of mRNAs localizations with shape (y, x).
"""
# check parameters
check_array(cyt,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64, bool])
if nuc is not None:
check_array(nuc,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64, bool])
if rna is not None:
check_array(rna,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64, bool])
# initialize parameter
nuc_centered, rna_centered = None, None
marge = get_offset_value()
# center the binary mask of the cell
coord = np.nonzero(cyt)
coord = np.column_stack(coord)
min_y, max_y = coord[:, 0].min(), coord[:, 0].max()
min_x, max_x = coord[:, 1].min(), coord[:, 1].max()
shape_y = max_y - min_y + 1
shape_x = max_x - min_x + 1
cyt_centered_shape = (shape_y + 2 * marge, shape_x + 2 * marge)
cyt_centered = np.zeros(cyt_centered_shape, dtype=bool)
crop = cyt[min_y:max_y + 1, min_x:max_x + 1]
cyt_centered[marge:shape_y + marge, marge:shape_x + marge] = crop
# center the binary mask of the nucleus with the same transformation
if nuc is not None:
if nuc.shape == 2:
nuc_centered = nuc.copy()
nuc_centered[:, 0] = nuc_centered[:, 0] - min_y + marge
nuc_centered[:, 1] = nuc_centered[:, 1] - min_x + marge
elif nuc.shape == cyt.shape:
nuc_centered = np.zeros(cyt_centered_shape, dtype=bool)
crop = nuc[min_y:max_y + 1, min_x:max_x + 1]
nuc_centered[marge:shape_y + marge, marge:shape_x + marge] = crop
else:
raise ValueError("mRNAs mask should have the same shape than "
"cytoplasm mask and coordinates should be in 2-d")
# center the binary mask of the mRNAs with the same transformation
if rna is not None:
if rna.shape[1] == 3:
rna_centered = rna.copy()
rna_centered[:, 1] = rna_centered[:, 1] - min_y + marge
rna_centered[:, 2] = rna_centered[:, 2] - min_x + marge
elif rna.shape[1] == 2:
rna_centered = rna.copy()
rna_centered[:, 0] = rna_centered[:, 0] - min_y + marge
rna_centered[:, 1] = rna_centered[:, 1] - min_x + marge
elif rna.shape == cyt.shape:
rna_centered = np.zeros(cyt_centered_shape, dtype=bool)
crop = rna[min_y:max_y + 1, min_x:max_x + 1]
rna_centered[marge:shape_y + marge, marge:shape_x + marge] = crop
else:
raise ValueError("mRNAs mask should have the same shape than "
"cytoplasm mask and coordinates should be in 2-d "
"or 3-d")
return cyt_centered, nuc_centered, rna_centered
def from_surface_to_coord(binary_surface):
"""Extract coordinates from a 2-d binary matrix.
The resulting coordinates represent the external boundaries of the object.
Parameters
----------
binary_surface : np.ndarray, np.uint or np.int or bool
Binary image with shape (y, x).
Returns
-------
coord : np.ndarray, np.int64
Array of boundaries coordinates with shape (nb_points, 2).
"""
# check parameters
check_array(binary_surface,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64, bool])
# from binary surface to 2D coordinates boundaries
coord = find_contours(binary_surface, level=0)[0].astype(np.int64)
return coord
def complete_coord_boundaries(coord):
"""Complete a 2-d coordinates array, by generating/interpolating missing
points.
Parameters
----------
coord : np.ndarray, np.int64
Array of coordinates to complete, with shape (nb_points, 2).
Returns
-------
coord_completed : np.ndarray, np.int64
Completed coordinates arrays, with shape (nb_points, 2).
"""
# check parameters
check_array(coord,
ndim=2,
dtype=[np.int64])
# for each array in the list, complete its coordinates using the scikit
# image method 'polygon_perimeter'
coord_y, coord_x = polygon_perimeter(coord[:, 0], coord[:, 1])
coord_y = coord_y[:, np.newaxis]
coord_x = coord_x[:, np.newaxis]
coord_completed = np.concatenate((coord_y, coord_x), axis=-1)
return coord_completed
def _from_coord_to_boundaries(coord_cyt, coord_nuc=None, coord_rna=None):
"""Convert 2-d coordinates to a binary matrix with the boundaries of the
object.
As we manipulate the coordinates of the external boundaries, the relative
binary matrix has two extra pixels in each dimension. We compensate by
reducing the marge by one in order to keep the same shape for the frame.
If others coordinates are provided, the relative binary matrix is build
with the same shape as the main coordinates.
Parameters
----------
coord_cyt : np.ndarray, np.int64
Array of cytoplasm boundaries coordinates with shape (nb_points, 2).
coord_nuc : np.ndarray, np.int64
Array of nucleus boundaries coordinates with shape (nb_points, 2).
coord_rna : np.ndarray, np.int64
Array of mRNAs coordinates with shape (nb_points, 2) or
(nb_points, 3).
Returns
-------
cyt : np.ndarray, np.uint or np.int or bool
Binary image of cytoplasm boundaries with shape (y, x).
nuc : np.ndarray, np.uint or np.int or bool
Binary image of nucleus boundaries with shape (y, x).
rna : np.ndarray, np.uint or np.int or bool
Binary image of mRNAs localizations with shape (y, x).
"""
# initialize parameter
nuc, rna = None, None
marge = get_offset_value()
marge -= 1
# from 2D coordinates boundaries to binary boundaries
max_y = coord_cyt[:, 0].max()
max_x = coord_cyt[:, 1].max()
min_y = coord_cyt[:, 0].min()
min_x = coord_cyt[:, 1].min()
shape_y = max_y - min_y + 1
shape_x = max_x - min_x + 1
image_shape = (shape_y + 2 * marge, shape_x + 2 * marge)
coord_cyt[:, 0] = coord_cyt[:, 0] - min_y + marge
coord_cyt[:, 1] = coord_cyt[:, 1] - min_x + marge
cyt = np.zeros(image_shape, dtype=bool)
cyt[coord_cyt[:, 0], coord_cyt[:, 1]] = True
# transform nucleus coordinates with the same parameters
if coord_nuc is not None:
nuc = np.zeros(image_shape, dtype=bool)
coord_nuc[:, 0] = coord_nuc[:, 0] - min_y + marge
coord_nuc[:, 1] = coord_nuc[:, 1] - min_x + marge
nuc[coord_nuc[:, 0], coord_nuc[:, 1]] = True
# transform mRNAs coordinates with the same parameters
if coord_rna is not None:
rna = np.zeros(image_shape, dtype=bool)
if coord_rna.shape[1] == 3:
coord_rna[:, 1] = coord_rna[:, 1] - min_y + marge
coord_rna[:, 2] = coord_rna[:, 2] - min_x + marge
rna[coord_rna[:, 1], coord_rna[:, 2]] = True
else:
coord_rna[:, 0] = coord_rna[:, 0] - min_y + marge
coord_rna[:, 1] = coord_rna[:, 1] - min_x + marge
rna[coord_rna[:, 0], coord_rna[:, 1]] = True
return cyt, nuc, rna
def from_boundaries_to_surface(binary_boundaries):
"""Fill in the binary matrix representing the boundaries of an object.
Parameters
----------
binary_boundaries : np.ndarray, np.uint or np.int or bool
Binary image with shape (y, x).
Returns
-------
binary_surface : np.ndarray, np.uint or np.int or bool
Binary image with shape (y, x).
"""
# TODO check dtype input & output
# check parameters
check_array(binary_boundaries,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64, bool])
# from binary boundaries to binary surface
binary_surface = ndi.binary_fill_holes(binary_boundaries)
return binary_surface
def from_coord_to_surface(coord_cyt, coord_nuc=None, coord_rna=None):
"""Convert 2-d coordinates to a binary matrix with the surface of the
object.
As we manipulate the coordinates of the external boundaries, the relative
binary matrix has two extra pixels in each dimension. We compensate by
keeping only the inside pixels of the object surface.
If others coordinates are provided, the relative binary matrix is build
with the same shape as the main coordinates.
Parameters
----------
coord_cyt : np.ndarray, np.int64
Array of cytoplasm boundaries coordinates with shape (nb_points, 2).
coord_nuc : np.ndarray, np.int64
Array of nucleus boundaries coordinates with shape (nb_points, 2).
coord_rna : np.ndarray, np.int64
Array of mRNAs coordinates with shape (nb_points, 2) or
(nb_points, 3).
Returns
-------
cyt_surface : np.ndarray, np.uint or np.int or bool
Binary image of cytoplasm surface with shape (y, x).
nuc_surface : np.ndarray, np.uint or np.int or bool
Binary image of nucleus surface with shape (y, x).
rna : np.ndarray, np.uint or np.int or bool
Binary image of mRNAs localizations with shape (y, x).
"""
# check parameters
check_array(coord_cyt,
ndim=2,
dtype=[np.int64])
if coord_nuc is not None:
check_array(coord_nuc,
ndim=2,
dtype=[np.int64])
if coord_rna is not None:
check_array(coord_rna,
ndim=2,
dtype=[np.int64])
# from coordinates to binary boundaries
cyt, nuc, rna = _from_coord_to_boundaries(coord_cyt, coord_nuc, coord_rna)
# from binary boundaries to binary surface
cyt_surface = from_boundaries_to_surface(cyt)
nuc_surface = from_boundaries_to_surface(nuc)
return cyt_surface, nuc_surface, rna
| 34.57973 | 79 | 0.626754 |
import numpy as np
from scipy import ndimage as ndi
from .utils import check_array, check_parameter, get_offset_value
from skimage.measure import regionprops, find_contours
from skimage.draw import polygon_perimeter
(mask_nuc,
ndim=2,
dtype=[bool],
allow_nan=False)
check_array(spots_in_foci,
ndim=2,
dtype=[np.int64],
allow_nan=False)
check_array(foci,
ndim=2,
dtype=[np.int64],
allow_nan=False)
mask_transcription_site = mask_nuc[foci[:, 1], foci[:, 2]]
foci_cleaned = foci[~mask_transcription_site]
spots_to_keep = foci_cleaned[:, 4]
mask_spots_to_keep = np.isin(spots_in_foci[:, 3], spots_to_keep)
spots_in_foci_cleaned = spots_in_foci[mask_spots_to_keep]
return spots_in_foci_cleaned, foci_cleaned
):
check_array(spots,
ndim=2,
dtype=[np.int64],
allow_nan=False)
check_parameter(z_lim=(tuple, type(None)),
y_lim=(tuple, type(None)),
x_lim=(tuple, type(None)))
extracted_spots = spots.copy()
if z_lim is not None:
extracted_spots = extracted_spots[extracted_spots[:, 0] < z_lim[1]]
extracted_spots = extracted_spots[z_lim[0] < extracted_spots[:, 0]]
extracted_spots[:, 0] -= z_lim[0]
if y_lim is not None:
extracted_spots = extracted_spots[extracted_spots[:, 1] < y_lim[1]]
extracted_spots = extracted_spots[y_lim[0] < extracted_spots[:, 1]]
extracted_spots[:, 1] -= y_lim[0]
if x_lim is not None:
extracted_spots = extracted_spots[extracted_spots[:, 2] < x_lim[1]]
extracted_spots = extracted_spots[x_lim[0] < extracted_spots[:, 2]]
extracted_spots[:, 2] -= x_lim[0]
return extracted_spots
def extract_coordinates_image(cyt_labelled, nuc_labelled, spots_out, spots_in,
foci):
check_array(cyt_labelled,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64],
allow_nan=True)
check_array(nuc_labelled,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64],
allow_nan=True)
check_array(spots_out,
ndim=2,
dtype=[np.int64],
allow_nan=False)
check_array(spots_in,
ndim=2,
dtype=[np.int64],
allow_nan=False)
check_array(foci,
ndim=2,
dtype=[np.int64],
allow_nan=False)
results = []
borders = np.zeros(cyt_labelled.shape, dtype=bool)
borders[:, 0] = True
borders[0, :] = True
borders[:, cyt_labelled.shape[1] - 1] = True
borders[cyt_labelled.shape[0] - 1, :] = True
cells = regionprops(cyt_labelled)
for cell in cells:
label = cell.label
(min_y, min_x, max_y, max_x) = cell.bbox
cyt = cyt_labelled.copy()
cyt = (cyt == label)
nuc = nuc_labelled.copy()
nuc = (nuc == label)
if _check_cropped_cell(cyt, borders):
continue
if not _check_nucleus_in_cell(cyt, nuc):
continue
cyt_coord, nuc_coord = _get_boundaries_coordinates(cyt, nuc)
foci_cell, spots_in_foci_cell = _extract_foci(foci, spots_in, cyt)
spots_out_foci_cell = _extract_spots_outside_foci(cyt, spots_out)
rna_coord = np.concatenate([spots_out_foci_cell, spots_in_foci_cell],
axis=0)
if len(rna_coord) < 30:
continue
cyt_coord[:, 0] -= min_y
cyt_coord[:, 1] -= min_x
nuc_coord[:, 0] -= min_y
nuc_coord[:, 1] -= min_x
rna_coord[:, 1] -= min_y
rna_coord[:, 2] -= min_x
foci_cell[:, 1] -= min_y
foci_cell[:, 2] -= min_x
results.append((cyt_coord, nuc_coord, rna_coord, foci_cell, cell.bbox))
return results
def _check_cropped_cell(cell_cyt_mask, border_frame):
crop = cell_cyt_mask & border_frame
if np.any(crop):
return True
else:
return False
def _check_nucleus_in_cell(cell_cyt_mask, cell_nuc_mask):
diff = cell_cyt_mask | cell_nuc_mask
if np.any(diff != cell_cyt_mask):
return False
else:
return True
def _get_boundaries_coordinates(cell_cyt_mask, cell_nuc_mask):
cyt_coord = np.array([], dtype=np.int64).reshape((0, 2))
nuc_coord = np.array([], dtype=np.int64).reshape((0, 2))
cell_cyt_coord = find_contours(cell_cyt_mask, level=0)
if len(cell_cyt_coord) == 0:
pass
elif len(cell_cyt_coord) == 1:
cyt_coord = cell_cyt_coord[0].astype(np.int64)
else:
m = 0
for coord in cell_cyt_coord:
if len(coord) > m:
m = len(coord)
cyt_coord = coord.astype(np.int64)
cell_nuc_coord = find_contours(cell_nuc_mask, level=0)
if len(cell_nuc_coord) == 0:
pass
elif len(cell_nuc_coord) == 1:
nuc_coord = cell_nuc_coord[0].astype(np.int64)
else:
m = 0
for coord in cell_nuc_coord:
if len(coord) > m:
m = len(coord)
nuc_coord = coord.astype(np.int64)
return cyt_coord, nuc_coord
def _extract_foci(foci, spots_in_foci, cell_cyt_mask):
mask_foci_cell = cell_cyt_mask[foci[:, 1], foci[:, 2]]
if mask_foci_cell.sum() == 0:
foci_cell = np.array([], dtype=np.int64).reshape((0, 5))
spots_in_foci_cell = np.array([], dtype=np.int64).reshape((0, 4))
return foci_cell, spots_in_foci_cell
foci_cell = foci[mask_foci_cell]
spots_to_keep = foci_cell[:, 4]
mask_spots_to_keep = np.isin(spots_in_foci[:, 3], spots_to_keep)
spots_in_foci_cell = spots_in_foci[mask_spots_to_keep]
return foci_cell, spots_in_foci_cell
def _extract_spots_outside_foci(cell_cyt_mask, spots_out_foci):
mask_spots_to_keep = cell_cyt_mask[spots_out_foci[:, 1],
spots_out_foci[:, 2]]
spots_out_foci_cell = spots_out_foci[mask_spots_to_keep]
return spots_out_foci_cell
dtype=[np.uint8, np.uint16, np.int64, bool])
if nuc is not None:
check_array(nuc,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64, bool])
if rna is not None:
check_array(rna,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64, bool])
nuc_centered, rna_centered = None, None
marge = get_offset_value()
coord = np.nonzero(cyt)
coord = np.column_stack(coord)
min_y, max_y = coord[:, 0].min(), coord[:, 0].max()
min_x, max_x = coord[:, 1].min(), coord[:, 1].max()
shape_y = max_y - min_y + 1
shape_x = max_x - min_x + 1
cyt_centered_shape = (shape_y + 2 * marge, shape_x + 2 * marge)
cyt_centered = np.zeros(cyt_centered_shape, dtype=bool)
crop = cyt[min_y:max_y + 1, min_x:max_x + 1]
cyt_centered[marge:shape_y + marge, marge:shape_x + marge] = crop
if nuc is not None:
if nuc.shape == 2:
nuc_centered = nuc.copy()
nuc_centered[:, 0] = nuc_centered[:, 0] - min_y + marge
nuc_centered[:, 1] = nuc_centered[:, 1] - min_x + marge
elif nuc.shape == cyt.shape:
nuc_centered = np.zeros(cyt_centered_shape, dtype=bool)
crop = nuc[min_y:max_y + 1, min_x:max_x + 1]
nuc_centered[marge:shape_y + marge, marge:shape_x + marge] = crop
else:
raise ValueError("mRNAs mask should have the same shape than "
"cytoplasm mask and coordinates should be in 2-d")
if rna is not None:
if rna.shape[1] == 3:
rna_centered = rna.copy()
rna_centered[:, 1] = rna_centered[:, 1] - min_y + marge
rna_centered[:, 2] = rna_centered[:, 2] - min_x + marge
elif rna.shape[1] == 2:
rna_centered = rna.copy()
rna_centered[:, 0] = rna_centered[:, 0] - min_y + marge
rna_centered[:, 1] = rna_centered[:, 1] - min_x + marge
elif rna.shape == cyt.shape:
rna_centered = np.zeros(cyt_centered_shape, dtype=bool)
crop = rna[min_y:max_y + 1, min_x:max_x + 1]
rna_centered[marge:shape_y + marge, marge:shape_x + marge] = crop
else:
raise ValueError("mRNAs mask should have the same shape than "
"cytoplasm mask and coordinates should be in 2-d "
"or 3-d")
return cyt_centered, nuc_centered, rna_centered
def from_surface_to_coord(binary_surface):
check_array(binary_surface,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64, bool])
coord = find_contours(binary_surface, level=0)[0].astype(np.int64)
return coord
def complete_coord_boundaries(coord):
check_array(coord,
ndim=2,
dtype=[np.int64])
coord_y, coord_x = polygon_perimeter(coord[:, 0], coord[:, 1])
coord_y = coord_y[:, np.newaxis]
coord_x = coord_x[:, np.newaxis]
coord_completed = np.concatenate((coord_y, coord_x), axis=-1)
return coord_completed
def _from_coord_to_boundaries(coord_cyt, coord_nuc=None, coord_rna=None):
nuc, rna = None, None
marge = get_offset_value()
marge -= 1
max_y = coord_cyt[:, 0].max()
max_x = coord_cyt[:, 1].max()
min_y = coord_cyt[:, 0].min()
min_x = coord_cyt[:, 1].min()
shape_y = max_y - min_y + 1
shape_x = max_x - min_x + 1
image_shape = (shape_y + 2 * marge, shape_x + 2 * marge)
coord_cyt[:, 0] = coord_cyt[:, 0] - min_y + marge
coord_cyt[:, 1] = coord_cyt[:, 1] - min_x + marge
cyt = np.zeros(image_shape, dtype=bool)
cyt[coord_cyt[:, 0], coord_cyt[:, 1]] = True
if coord_nuc is not None:
nuc = np.zeros(image_shape, dtype=bool)
coord_nuc[:, 0] = coord_nuc[:, 0] - min_y + marge
coord_nuc[:, 1] = coord_nuc[:, 1] - min_x + marge
nuc[coord_nuc[:, 0], coord_nuc[:, 1]] = True
if coord_rna is not None:
rna = np.zeros(image_shape, dtype=bool)
if coord_rna.shape[1] == 3:
coord_rna[:, 1] = coord_rna[:, 1] - min_y + marge
coord_rna[:, 2] = coord_rna[:, 2] - min_x + marge
rna[coord_rna[:, 1], coord_rna[:, 2]] = True
else:
coord_rna[:, 0] = coord_rna[:, 0] - min_y + marge
coord_rna[:, 1] = coord_rna[:, 1] - min_x + marge
rna[coord_rna[:, 0], coord_rna[:, 1]] = True
return cyt, nuc, rna
def from_boundaries_to_surface(binary_boundaries):
check_array(binary_boundaries,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64, bool])
binary_surface = ndi.binary_fill_holes(binary_boundaries)
return binary_surface
def from_coord_to_surface(coord_cyt, coord_nuc=None, coord_rna=None):
check_array(coord_cyt,
ndim=2,
dtype=[np.int64])
if coord_nuc is not None:
check_array(coord_nuc,
ndim=2,
dtype=[np.int64])
if coord_rna is not None:
check_array(coord_rna,
ndim=2,
dtype=[np.int64])
cyt, nuc, rna = _from_coord_to_boundaries(coord_cyt, coord_nuc, coord_rna)
cyt_surface = from_boundaries_to_surface(cyt)
nuc_surface = from_boundaries_to_surface(nuc)
return cyt_surface, nuc_surface, rna
| true | true |
f710797ab784835c1442fbb48d68ecbf113174ad | 88 | py | Python | det3d/datasets/waymo/__init__.py | alsun-oven/CenterPoint | cafd89c4008270e648e97202bc256aff968e8109 | [
"MIT"
] | 1,124 | 2020-06-22T00:48:18.000Z | 2022-03-31T22:03:35.000Z | det3d/datasets/waymo/__init__.py | alsun-oven/CenterPoint | cafd89c4008270e648e97202bc256aff968e8109 | [
"MIT"
] | 290 | 2020-06-23T01:29:04.000Z | 2022-03-29T16:27:32.000Z | det3d/datasets/waymo/__init__.py | alsun-oven/CenterPoint | cafd89c4008270e648e97202bc256aff968e8109 | [
"MIT"
] | 326 | 2020-06-22T01:48:10.000Z | 2022-03-31T08:15:08.000Z | from .waymo import WaymoDataset
from .waymo_common import *
__all__ = ["WaymoDataset"]
| 17.6 | 31 | 0.772727 | from .waymo import WaymoDataset
from .waymo_common import *
__all__ = ["WaymoDataset"]
| true | true |
f7107b0890bd09696c94ec6fab76c27c05bdde01 | 6,696 | py | Python | deprecated/code/datacleaning.py | metamoles/metamoles | 251de6672029566d8becf2538684c0506fc297d0 | [
"MIT"
] | 3 | 2019-04-04T22:44:00.000Z | 2020-07-30T18:16:56.000Z | deprecated/code/datacleaning.py | metamoles/metamoles | 251de6672029566d8becf2538684c0506fc297d0 | [
"MIT"
] | null | null | null | deprecated/code/datacleaning.py | metamoles/metamoles | 251de6672029566d8becf2538684c0506fc297d0 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
import Bio
from Bio.KEGG import REST
from Bio.KEGG import Enzyme
import re
from Bio.KEGG import Compound
import gzip
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
def create_enzyme_df(path_to_file):
"""
input:path_to_file. file.gz format
output:enzyme dataframe
"""
enzyme_fields = [method for method in dir(Enzyme.Record()) if not method.startswith('_')]
data_matrix = []
with gzip.open(path_to_file, 'rt') as file:
for record in enzyme.parse(file):
data_matrix.append([getattr(record, field) for field in enzyme_fields])
enzyme_df = pd.DataFrame(data_matrix, columns=enzyme_fields)
return enzyme_df
def get_compact_promiscuous_df(enzyme_df):
"""
input:enzyme dataframe (dataframe)
output:promiscuous enzyme dataframe (dataframe)
"""
promiscuous_df = enzyme_df[[True if len(rxn) > 1 else False for rxn in enzyme_df['reaction']]]
compact_promiscuous_df = promiscuous_df[['entry','reaction','product','substrate']]
return compact_promiscuous_df
def get_reaction_list(df):
"""
get the list of reaction from a dataframe that contains reaction column
input:dataframe with reaction column (df)
output: list of reaction (list)
"""
reaction_list = []
for index,row in df.iterrows():
for reaction in row['reaction']:
reaction_split = reaction.split("[RN:")[-1]
if reaction_split.startswith("R") and not reaction_split.startswith("RN"):
for i in reaction_split[:-1].split(" "):
reaction_list.append(i)
return reaction_list
def query_reversible_reaction(reaction_list):
"""
get the list of reversible reaction
input:list of reactions(list) eg)["R00709"]
output:list of reversible reactions(list)
"""
reversible_reaction = []
for reaction in reaction_list:
reaction_file = REST.kegg_get(reaction).read()
for i in reaction_file.rstrip().split("\n"):
if i.startswith("EQUATION") and "<=>" in i:
reversible_reaction.append(reaction)
return reversible_reaction
def combine_substrate_product(df):
"""
append substrates to product column.
should not be run multiple times.
it will append substrates multiple times
input:dataframe with substrate and product(df)
output:dataframe with combined substrate and product. named under product column(df)
"""
rowindex = np.arange(0,len(df))
df_with_ordered_index = df.set_index(rowindex)
newdf = df_with_ordered_index
for index,row in df_with_ordered_index.iterrows():
productlist = row['product']
substratelist = row['substrate']
newdf.iloc[index,2] = productlist + substratelist
return newdf[["entry","product"]]
def get_cofactor_list(cofactor_df,CPDcolumnname):
"""
<input>
cofactor_df : cofactor dataframe(df)
CPDcolumnname : name of CPD columnname from cofactor dataframe(str)
<output>
cofactor_list : list of cofactors from cofactor dataframe (list)
"""
cofactor_list = [cofactor[4:10] for cofactor in cofactor_df[CPDcolumnname]]
return cofactor_list
def get_cpd_id(compound_full):
"""
input:compound_full = compound full name (str) eg) 'oxalureate [CPD:C00802]'
output: cpd = cpd id (str) eg) 'C01007'
"""
cpd = compound_full[-7:-1]
return cpd
def rm_cofactor_only_cpd(enzyme_df,cofactor_list,compound_columnname="product",keepNA=True):
"""
<input>
enzyme_df : dataframe with enzyme information. should have substrate and product combined(df)
compound_columnname : name of the column with compounds (str)
cofactor_list : list of cofactors to be removed (list)
keepNA : if false, will drop the row with no compounds (boolean, default:True)
<output>
clean dataframe (df)
"""
newdf = enzyme_df.drop(["product"],axis=1)
cleaned_compound_column = []
for index,row in enzyme_df.iterrows():
cpd_compound_list =[]
for compound in row[compound_columnname]:
if "CPD" in compound:
onlycpd = get_cpd(compound)
if onlycpd not in cofactor_list:
cpd_compound_list.append(onlycpd)
else:
pass
if len(cpd_compound_list)==0:
cleaned_compound_column.append("NA")
else:
cleaned_compound_column.append(cpd_compound_list)
newdf['product'] = cleaned_compound_column
if keepNA==False:
newdf = newdf.loc[cleaned_df_productinList['product']!='NA']
return newdf
def itemlist_eachrow(df,oldcolumnname,newcolumnname,sorting_column):
"""
<input>
df: dataframe with list items in one column (dataframe)
oldcolumnname : name of the old column to be replaced (str) eg)"products"
newcolumnname : name of the new column to replace (str) eg)"product"
sorting_column : name of the column to be sorted by (str) eg)"entry"
<output>
dataframe with each item in each row.
"""
newdf = df[oldcolumnname].\
apply(pd.Series).\
merge(df, left_index=True, right_index=True).\
drop([oldcolumnname],axis=1).\
melt(id_vars=[enzymecolumn],value_name=newcolumnname).\
sort_values(by=[sorting_column]).\
dropna().\
drop(columns=["variable"])
return newdf
def compound_records_to_df(file_path):
"""
Function parses all records using Biopython.Bio.KEGG.Compound parser, and returns a pandas dataframe.
<Input>
filepath = file path to a gzipped text file of KEGG enzyme records (str)
<output>
compound dataframe
"""
compound_fields = [method for method in dir(Compound.Record()) if not method.startswith('_')]
data_matrix = []
with gzip.open(file_path, 'rt') as file:
for record in Compound.parse(file):
data_matrix.append([getattr(record, field) for field in compound_fields])
compound_df = pd.DataFrame(data_matrix, columns=compound_fields)
return compound_df
def extract_PubChem_id(field):
"""
This function uses regular expressions to extract the PubChem compound IDs from a field in a record
input : field
output : pubchem_id
"""
regex = "'PubChem', \[\'(\d+)\'\]\)" # matches "'PubChem', ['" characters exactly, then captures any number of digits (\d+), before another literal "']" character match
ids = re.findall(regex, str(field), re.IGNORECASE)
if len(ids) > 0:
pubchem_id = ids[0]
else:
pubchem_id = ''
return pubchem_id
| 30.162162 | 172 | 0.670251 |
import Bio
from Bio.KEGG import REST
from Bio.KEGG import Enzyme
import re
from Bio.KEGG import Compound
import gzip
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
def create_enzyme_df(path_to_file):
enzyme_fields = [method for method in dir(Enzyme.Record()) if not method.startswith('_')]
data_matrix = []
with gzip.open(path_to_file, 'rt') as file:
for record in enzyme.parse(file):
data_matrix.append([getattr(record, field) for field in enzyme_fields])
enzyme_df = pd.DataFrame(data_matrix, columns=enzyme_fields)
return enzyme_df
def get_compact_promiscuous_df(enzyme_df):
promiscuous_df = enzyme_df[[True if len(rxn) > 1 else False for rxn in enzyme_df['reaction']]]
compact_promiscuous_df = promiscuous_df[['entry','reaction','product','substrate']]
return compact_promiscuous_df
def get_reaction_list(df):
reaction_list = []
for index,row in df.iterrows():
for reaction in row['reaction']:
reaction_split = reaction.split("[RN:")[-1]
if reaction_split.startswith("R") and not reaction_split.startswith("RN"):
for i in reaction_split[:-1].split(" "):
reaction_list.append(i)
return reaction_list
def query_reversible_reaction(reaction_list):
reversible_reaction = []
for reaction in reaction_list:
reaction_file = REST.kegg_get(reaction).read()
for i in reaction_file.rstrip().split("\n"):
if i.startswith("EQUATION") and "<=>" in i:
reversible_reaction.append(reaction)
return reversible_reaction
def combine_substrate_product(df):
rowindex = np.arange(0,len(df))
df_with_ordered_index = df.set_index(rowindex)
newdf = df_with_ordered_index
for index,row in df_with_ordered_index.iterrows():
productlist = row['product']
substratelist = row['substrate']
newdf.iloc[index,2] = productlist + substratelist
return newdf[["entry","product"]]
def get_cofactor_list(cofactor_df,CPDcolumnname):
cofactor_list = [cofactor[4:10] for cofactor in cofactor_df[CPDcolumnname]]
return cofactor_list
def get_cpd_id(compound_full):
cpd = compound_full[-7:-1]
return cpd
def rm_cofactor_only_cpd(enzyme_df,cofactor_list,compound_columnname="product",keepNA=True):
newdf = enzyme_df.drop(["product"],axis=1)
cleaned_compound_column = []
for index,row in enzyme_df.iterrows():
cpd_compound_list =[]
for compound in row[compound_columnname]:
if "CPD" in compound:
onlycpd = get_cpd(compound)
if onlycpd not in cofactor_list:
cpd_compound_list.append(onlycpd)
else:
pass
if len(cpd_compound_list)==0:
cleaned_compound_column.append("NA")
else:
cleaned_compound_column.append(cpd_compound_list)
newdf['product'] = cleaned_compound_column
if keepNA==False:
newdf = newdf.loc[cleaned_df_productinList['product']!='NA']
return newdf
def itemlist_eachrow(df,oldcolumnname,newcolumnname,sorting_column):
newdf = df[oldcolumnname].\
apply(pd.Series).\
merge(df, left_index=True, right_index=True).\
drop([oldcolumnname],axis=1).\
melt(id_vars=[enzymecolumn],value_name=newcolumnname).\
sort_values(by=[sorting_column]).\
dropna().\
drop(columns=["variable"])
return newdf
def compound_records_to_df(file_path):
compound_fields = [method for method in dir(Compound.Record()) if not method.startswith('_')]
data_matrix = []
with gzip.open(file_path, 'rt') as file:
for record in Compound.parse(file):
data_matrix.append([getattr(record, field) for field in compound_fields])
compound_df = pd.DataFrame(data_matrix, columns=compound_fields)
return compound_df
def extract_PubChem_id(field):
regex = "'PubChem', \[\'(\d+)\'\]\)"
ids = re.findall(regex, str(field), re.IGNORECASE)
if len(ids) > 0:
pubchem_id = ids[0]
else:
pubchem_id = ''
return pubchem_id
| true | true |
f7107b1d4396af6ead7cd03880a25ba2d1787e88 | 12,815 | py | Python | TP07 PB.py | JPFigueredo/Hardware-Monitoring-System_Incomplete-Version | c8bcec269907382ea07c0355b2314007dcb36821 | [
"Apache-2.0"
] | 1 | 2021-08-06T19:55:34.000Z | 2021-08-06T19:55:34.000Z | TP07 PB.py | JPFigueredo/Hardware-Monitoring-System_Incomplete-Version | c8bcec269907382ea07c0355b2314007dcb36821 | [
"Apache-2.0"
] | null | null | null | TP07 PB.py | JPFigueredo/Hardware-Monitoring-System_Incomplete-Version | c8bcec269907382ea07c0355b2314007dcb36821 | [
"Apache-2.0"
] | null | null | null | import pygame
import psutil
import cpuinfo
import socket
import time
import nmap
from cpuinfo import get_cpu_info
red = (200,0,0)
white = (210,214,217)
blue = (0,0,200)
grey = (105,105,105)
black = (0,0,0)
largura_tela, altura_tela = 1024,760
pygame.init()
pygame.font.init()
font = pygame.font.Font(None, 32)
uso = psutil.cpu_percent(interval=1, percpu=True)
tela = pygame.display.set_mode((largura_tela, altura_tela))
ip = socket.gethostbyname(socket.gethostname())
info = get_cpu_info()
address = psutil.net_if_addrs()
p = psutil.Process()
processos = psutil.pids()
menu = ""
menu1 = True
menu2 = True
menu3 = True
p_lista = []
pos = pygame.mouse.get_pos()
buttons = 30
pygame.display.set_caption("TP07 - Monitoramento do PC")
pygame.display.init()
clock = pygame.time.Clock()
def pc_infos():
font = pygame.font.Font(None, 36)
s1 = pygame.surface.Surface((largura_tela, altura_tela/3))
texto_barra = "Detalhes do Processador"
text = font.render(texto_barra, 1, white)
s1.blit(text, (30, 10))
font = pygame.font.Font(None, 28)
texto_barra = ('Nome: {}'.format(info['brand_raw']))
text = font.render(texto_barra, 1, white)
s1.blit(text, (30, 50))
texto_barra = ('Arquitetura: {}'.format(info['arch_string_raw']))
text = font.render(texto_barra, 1, white)
s1.blit(text, (30, 90))
texto_barra = ('Palavra (bits): {}'.format(info['bits']))
text = font.render(texto_barra, 1, white)
s1.blit(text, (30, 120))
texto_barra = ('Frequência (MHz): {}'.format(round(psutil.cpu_freq().current, 2)))
text = font.render(texto_barra, 1, white)
s1.blit(text, (30, 150))
texto_barra = ('Núcleos (Físicos): {} ({})'.format(psutil.cpu_count(), psutil.cpu_count(logical=False)))
text = font.render(texto_barra, 1, white)
s1.blit(text, (30, 180))
y = 60
for chave in address:
IP = address[chave][1]
addrs = IP[:3]
y+= 30
texto_barra = ('{:12.10}: {} - netmask: {}'.format(chave, addrs[1], addrs[2]))
text = font.render(texto_barra, 1, white)
s1.blit(text, (350, y))
tela.blit(s1, (0, 0))
def cpu_graph():
s2 = pygame.surface.Surface((largura_tela, altura_tela/5))
uso = psutil.cpu_percent(interval=1)
larg = largura_tela - 2*40
pygame.draw.rect(s2, blue, (20, 30, larg, 10))
larg = larg*uso/100
pygame.draw.rect(s2, red, (20, 30, larg, 10))
texto_barra = 'Uso de CPU: {}%'.format(uso)
text = font.render(texto_barra, 1, white)
s2.blit(text, (20, 0))
tela.blit(s2, (0, 250))
def m_graph():
s3 = pygame.surface.Surface((largura_tela, altura_tela/5))
m = psutil.virtual_memory()
larg = largura_tela - 2*40
pygame.draw.rect(s3, blue, (20, 30, larg, 10))
larg = larg*m.percent/100
pygame.draw.rect(s3, red, (20, 30, larg, 10))
total = round(m.total/(1024*1024*1024),2)
texto_barra = 'Uso de Memória: {}% (Total: {} GB)'.format(m.percent, total)
text = font.render(texto_barra, 1, white)
s3.blit(text, (20, 0))
tela.blit(s3, (0, 350))
def disk_graph():
s4 = pygame.surface.Surface((largura_tela, altura_tela/5))
disk = psutil.disk_usage('.')
larg = largura_tela - 2*40
pygame.draw.rect(s4, blue, (20, 30, larg, 10))
larg = larg*disk.percent/100
pygame.draw.rect(s4, red, (20, 30, larg, 10))
total = round(disk.total/(1024*1024*1024), 2)
texto_barra = 'Uso de Disco: {}% (Total: {} GB):'.format(disk.percent,total)
text = font.render(texto_barra, 1, white)
s4.blit(text, (20, 0))
tela.blit(s4, (0, 450))
def threads_graph():
s5 = pygame.surface.Surface((largura_tela, altura_tela))
y = 10
num_cpu = len(uso)
desl = 9
d = y + desl
for i in range(num_cpu):
alt = s5.get_height() - 2*y
larg = (alt - (num_cpu+1)*desl)/num_cpu
pygame.draw.rect(s5, red, (d, y, larg, alt))
pygame.draw.rect(s5, blue, (d, y, larg, (alt*uso[i]/100)))
d = d + larg + desl
tela.blit(s5, (0, 550))
def threads_text():
s5 = pygame.surface.Surface((largura_tela, altura_tela))
texto_barra = 'Uso de Threads:'.format()
text = font.render(texto_barra, 1, white)
s5.blit(text, (20, 0))
tela.blit(s5, (0, 530))
def infos():
s1 = pygame.surface.Surface((largura_tela, altura_tela))
font = pygame.font.Font(None, 36)
texto_barra = "Monitoramento de Uso"
text = font.render(texto_barra, 1, white)
s1.blit(text, (350, 10))
font = pygame.font.Font(None, 28)
texto_barra = ('Nome: {}'.format(info['brand_raw']))
text = font.render(texto_barra, 1, white)
s1.blit(text, (20, 60))
texto_barra = ('Arquitetura: {}'.format(info['arch_string_raw']))
text = font.render(texto_barra, 1, white)
s1.blit(text, (20, 90))
texto_barra = ('Palavra (bits): {}'.format(info['bits']))
text = font.render(texto_barra, 1, white)
s1.blit(text, (20, 120))
texto_barra = ('Frequência (MHz): {}'.format(round(psutil.cpu_freq().current, 2)))
text = font.render(texto_barra, 1, white)
s1.blit(text, (20, 150))
texto_barra = ('Núcleos (físicos): {} ({})'.format(str(psutil.cpu_count()), str(psutil.cpu_count(logical=False))))
text = font.render(texto_barra, 1, white)
s1.blit(text, (20, 180))
texto_barra = ('IP Address: {}'.format(ip))
text = font.render(texto_barra, 1, white)
s1.blit(text, (20, 210))
font = pygame.font.Font(None, 38)
#CPU
uso = psutil.cpu_percent(interval=0)
texto_barra = ('Uso de CPU: {}% Usado'.format(uso))
text = font.render(texto_barra, 1, white)
s1.blit(text, (230, 275))
#MEMORIA
m = psutil.virtual_memory()
total = round(m.total/(1024*1024*1024), 2)
texto_barra = ('Uso de Memória: {}% (Total: {} GB)'.format(m.percent, total))
text = font.render(texto_barra, 1, white)
s1.blit(text, (230, 325))
#HD
disco = psutil.disk_usage('.')
total = round(disco.total/(1024*1024*1024), 2)
texto_barra = ('Uso de Disco: {}% (Total: {})'.format(disco.percent, total))
text = font.render(texto_barra, 1, white)
s1.blit(text, (230, 375))
tela.blit(s1, (0, 0))
#THREADS
uso2 = psutil.cpu_percent(interval=1, percpu=True)
y = 0
x = 0
for i in range(len(uso2)):
texto_barra = ('Uso de Thread {} : {}% Usado'.format(i + 1, uso2[i]))
text = font.render(texto_barra, 1, white)
s1.blit(text, (20+x, 450+y))
tela.blit(s1, (0, 0))
y += 30
if i == 7:
x += 500
y -= 240
def dir_header():
s1 = pygame.surface.Surface((largura_tela, altura_tela/10))
font = pygame.font.Font(None, 36)
texto = '{}'.format("Detalhes de Arquivos/Diretórios")
text = font.render(texto, 1, white)
s1.blit(text, (650, 10))
tela.blit(s1, (0, 0))
def process_header():
s6 = pygame.surface.Surface((largura_tela, altura_tela/8))
font = pygame.font.Font(None, 16)
texto_barra = '{:<6}'.format("PID") + " "
texto_barra = texto_barra + '{:10}'.format("Threads") + " "
texto_barra = texto_barra + '{:30}'.format("Data de Criação") + " "
texto_barra = texto_barra + '{:25}'.format("CPU - UT")
# UT - User Time
# ST - System Time
texto_barra = texto_barra + '{:26}'.format("CPU - ST")
texto_barra = texto_barra + '{:25}'.format("Memory(%)") + " "
texto_barra = texto_barra + '{:10}'.format("RSS") + " "
# Vss = virtual set size
# Rss = resident set size
texto_barra = texto_barra + '{:25}'.format("VMS") + " "
texto_barra = texto_barra + '{:20}'.format("Executável")
text = font.render(texto_barra, 1, white)
s6.blit(text, (20, 80))
tela.blit(s6, (0, 0))
def arq_dir():
s1 = pygame.surface.Surface((largura_tela, altura_tela))
p = psutil.Process()
font = pygame.font.Font(None, 14)
y = 100
for i in processos:
texto_barra = '{:<6}'.format(i) + " "
texto_barra = texto_barra + '{:^12}'.format(p.num_threads()) + " "
texto_barra = texto_barra + '{:26}'.format(time.ctime(p.create_time()))
texto_barra = texto_barra + '{:20.2f}'.format(p.cpu_times().user)
texto_barra = texto_barra + '{:30.2f}'.format(p.cpu_times().system)
texto_barra = texto_barra + '{:30.2f}'.format(p.memory_percent()) + " MB"
rss = p.memory_info().rss/1024/1024
texto_barra = texto_barra + '{:30.2f}'.format(rss) + " MB"
# Vss = virtual set size
# Rss = resident set size
vms = p.memory_info().vms/1024/1024
texto_barra = texto_barra + '{:15.2f}'.format(vms) + " MB" + " "
texto_barra = texto_barra + '{:15}'.format(p.exe())
text = font.render(texto_barra, 1, white)
s1.blit(text, (30, y))
tela.blit(s1, (0, 0))
y+= 15
if y >= 600:
break
# if (i % 3 == 0) and (i % 5 == 0):
# break
def arq_dir_button():
s1 = pygame.surface.Surface((largura_tela, altura_tela))
font = pygame.font.Font(None, 32)
pygame.draw.rect(s1, grey, (20, 30, 125, 30))
texto_barra = "Próximo"
text = font.render(texto_barra, 1, white)
s1.blit(text, (38, 35))
tela.blit(s1, (670, 670))
def menu_init():
s0 = pygame.surface.Surface((largura_tela, altura_tela))
s0.fill(white)
font = pygame.font.Font(None, 50)
texto_barra = ("OPÇOES DE TELA")
text = font.render(texto_barra, 1, black)
s0.blit(text, (350, 20))
tela.blit(s0, (0, 0))
texto_barra = ("Botão esquerdo do mouse - Gráfico de Uso")
text = font.render(texto_barra, 1, black)
s0.blit(text, (70, 140))
tela.blit(s0, (0, 0))
texto_barra = ("Botão direito do mouse - Monitoramento de Uso Geral")
text = font.render(texto_barra, 1, black)
s0.blit(text, (70, 260))
tela.blit(s0, (0, 0))
texto_barra = ("ESPAÇO - Detalhes de Arquivos/Diretórios")
text = font.render(texto_barra, 1, black)
s0.blit(text, (70, 380))
tela.blit(s0, (0, 0))
texto_barra = ("SHIFT - ESCANEAMENTO DE IP")
text = font.render(texto_barra, 1, black)
s0.blit(text, (70, 500))
tela.blit(s0, (0, 0))
texto_barra = ("TAB - Voltar a Tela Inicial")
text = font.render(texto_barra, 1, black)
s0.blit(text, (70, 620))
tela.blit(s0, (0, 0))
def ping_ip(host):
s1 = pygame.surface.Surface((largura_tela, altura_tela))
font = pygame.font.Font(None, 32)
nmp = nmap.PortScanner()
nmp.scan(host)
y = 0
for proto in nmp[host].all_protocols():
texto_barra = 'Protocolo : {}'.format(proto)
text = font.render(texto_barra, 1, white)
s1.blit(text, (20, 20))
tela.blit(s1, (0, 0))
lport = nmp[host][proto].keys()
for port in lport:
texto_barra = 'Porta: {:<15} Estado: {:>10}'.format(port, nmp[host][proto][port]['state'])
text = font.render(texto_barra, 1, white)
s1.blit(text, (70, 120+y))
tela.blit(s1, (0, 0))
y+= 30
menu_init()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
pos_x, pos_y = pygame.mouse.get_pos()
if pos_x >= 691 and pos_x <= 815 and pos_y >= 700 and pos_y <= 730:
buttons += 30
else:
menu = "menu1"
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 3:
menu = "menu2"
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
menu = "menu3"
if event.type == pygame.KEYDOWN and event.key == pygame.K_TAB:
menu = ""
menu_init()
if event.type == pygame.KEYDOWN and event.key == pygame.K_LSHIFT:
ping_ip(ip)
if menu == "menu1":
pc_infos()
cpu_graph()
m_graph()
disk_graph()
threads_text()
threads_graph()
if menu != "menu1":
break
if menu == "menu2":
infos()
if menu != "menu2":
break
if menu == "menu3":
arq_dir()
process_header()
dir_header()
arq_dir_button()
time.sleep(0.1)
if menu != "menu3":
break
pygame.display.update()
clock.tick(50)
pygame.display.quit() | 36.40625 | 119 | 0.569957 | import pygame
import psutil
import cpuinfo
import socket
import time
import nmap
from cpuinfo import get_cpu_info
red = (200,0,0)
white = (210,214,217)
blue = (0,0,200)
grey = (105,105,105)
black = (0,0,0)
largura_tela, altura_tela = 1024,760
pygame.init()
pygame.font.init()
font = pygame.font.Font(None, 32)
uso = psutil.cpu_percent(interval=1, percpu=True)
tela = pygame.display.set_mode((largura_tela, altura_tela))
ip = socket.gethostbyname(socket.gethostname())
info = get_cpu_info()
address = psutil.net_if_addrs()
p = psutil.Process()
processos = psutil.pids()
menu = ""
menu1 = True
menu2 = True
menu3 = True
p_lista = []
pos = pygame.mouse.get_pos()
buttons = 30
pygame.display.set_caption("TP07 - Monitoramento do PC")
pygame.display.init()
clock = pygame.time.Clock()
def pc_infos():
font = pygame.font.Font(None, 36)
s1 = pygame.surface.Surface((largura_tela, altura_tela/3))
texto_barra = "Detalhes do Processador"
text = font.render(texto_barra, 1, white)
s1.blit(text, (30, 10))
font = pygame.font.Font(None, 28)
texto_barra = ('Nome: {}'.format(info['brand_raw']))
text = font.render(texto_barra, 1, white)
s1.blit(text, (30, 50))
texto_barra = ('Arquitetura: {}'.format(info['arch_string_raw']))
text = font.render(texto_barra, 1, white)
s1.blit(text, (30, 90))
texto_barra = ('Palavra (bits): {}'.format(info['bits']))
text = font.render(texto_barra, 1, white)
s1.blit(text, (30, 120))
texto_barra = ('Frequência (MHz): {}'.format(round(psutil.cpu_freq().current, 2)))
text = font.render(texto_barra, 1, white)
s1.blit(text, (30, 150))
texto_barra = ('Núcleos (Físicos): {} ({})'.format(psutil.cpu_count(), psutil.cpu_count(logical=False)))
text = font.render(texto_barra, 1, white)
s1.blit(text, (30, 180))
y = 60
for chave in address:
IP = address[chave][1]
addrs = IP[:3]
y+= 30
texto_barra = ('{:12.10}: {} - netmask: {}'.format(chave, addrs[1], addrs[2]))
text = font.render(texto_barra, 1, white)
s1.blit(text, (350, y))
tela.blit(s1, (0, 0))
def cpu_graph():
s2 = pygame.surface.Surface((largura_tela, altura_tela/5))
uso = psutil.cpu_percent(interval=1)
larg = largura_tela - 2*40
pygame.draw.rect(s2, blue, (20, 30, larg, 10))
larg = larg*uso/100
pygame.draw.rect(s2, red, (20, 30, larg, 10))
texto_barra = 'Uso de CPU: {}%'.format(uso)
text = font.render(texto_barra, 1, white)
s2.blit(text, (20, 0))
tela.blit(s2, (0, 250))
def m_graph():
s3 = pygame.surface.Surface((largura_tela, altura_tela/5))
m = psutil.virtual_memory()
larg = largura_tela - 2*40
pygame.draw.rect(s3, blue, (20, 30, larg, 10))
larg = larg*m.percent/100
pygame.draw.rect(s3, red, (20, 30, larg, 10))
total = round(m.total/(1024*1024*1024),2)
texto_barra = 'Uso de Memória: {}% (Total: {} GB)'.format(m.percent, total)
text = font.render(texto_barra, 1, white)
s3.blit(text, (20, 0))
tela.blit(s3, (0, 350))
def disk_graph():
s4 = pygame.surface.Surface((largura_tela, altura_tela/5))
disk = psutil.disk_usage('.')
larg = largura_tela - 2*40
pygame.draw.rect(s4, blue, (20, 30, larg, 10))
larg = larg*disk.percent/100
pygame.draw.rect(s4, red, (20, 30, larg, 10))
total = round(disk.total/(1024*1024*1024), 2)
texto_barra = 'Uso de Disco: {}% (Total: {} GB):'.format(disk.percent,total)
text = font.render(texto_barra, 1, white)
s4.blit(text, (20, 0))
tela.blit(s4, (0, 450))
def threads_graph():
s5 = pygame.surface.Surface((largura_tela, altura_tela))
y = 10
num_cpu = len(uso)
desl = 9
d = y + desl
for i in range(num_cpu):
alt = s5.get_height() - 2*y
larg = (alt - (num_cpu+1)*desl)/num_cpu
pygame.draw.rect(s5, red, (d, y, larg, alt))
pygame.draw.rect(s5, blue, (d, y, larg, (alt*uso[i]/100)))
d = d + larg + desl
tela.blit(s5, (0, 550))
def threads_text():
s5 = pygame.surface.Surface((largura_tela, altura_tela))
texto_barra = 'Uso de Threads:'.format()
text = font.render(texto_barra, 1, white)
s5.blit(text, (20, 0))
tela.blit(s5, (0, 530))
def infos():
s1 = pygame.surface.Surface((largura_tela, altura_tela))
font = pygame.font.Font(None, 36)
texto_barra = "Monitoramento de Uso"
text = font.render(texto_barra, 1, white)
s1.blit(text, (350, 10))
font = pygame.font.Font(None, 28)
texto_barra = ('Nome: {}'.format(info['brand_raw']))
text = font.render(texto_barra, 1, white)
s1.blit(text, (20, 60))
texto_barra = ('Arquitetura: {}'.format(info['arch_string_raw']))
text = font.render(texto_barra, 1, white)
s1.blit(text, (20, 90))
texto_barra = ('Palavra (bits): {}'.format(info['bits']))
text = font.render(texto_barra, 1, white)
s1.blit(text, (20, 120))
texto_barra = ('Frequência (MHz): {}'.format(round(psutil.cpu_freq().current, 2)))
text = font.render(texto_barra, 1, white)
s1.blit(text, (20, 150))
texto_barra = ('Núcleos (físicos): {} ({})'.format(str(psutil.cpu_count()), str(psutil.cpu_count(logical=False))))
text = font.render(texto_barra, 1, white)
s1.blit(text, (20, 180))
texto_barra = ('IP Address: {}'.format(ip))
text = font.render(texto_barra, 1, white)
s1.blit(text, (20, 210))
font = pygame.font.Font(None, 38)
uso = psutil.cpu_percent(interval=0)
texto_barra = ('Uso de CPU: {}% Usado'.format(uso))
text = font.render(texto_barra, 1, white)
s1.blit(text, (230, 275))
m = psutil.virtual_memory()
total = round(m.total/(1024*1024*1024), 2)
texto_barra = ('Uso de Memória: {}% (Total: {} GB)'.format(m.percent, total))
text = font.render(texto_barra, 1, white)
s1.blit(text, (230, 325))
disco = psutil.disk_usage('.')
total = round(disco.total/(1024*1024*1024), 2)
texto_barra = ('Uso de Disco: {}% (Total: {})'.format(disco.percent, total))
text = font.render(texto_barra, 1, white)
s1.blit(text, (230, 375))
tela.blit(s1, (0, 0))
uso2 = psutil.cpu_percent(interval=1, percpu=True)
y = 0
x = 0
for i in range(len(uso2)):
texto_barra = ('Uso de Thread {} : {}% Usado'.format(i + 1, uso2[i]))
text = font.render(texto_barra, 1, white)
s1.blit(text, (20+x, 450+y))
tela.blit(s1, (0, 0))
y += 30
if i == 7:
x += 500
y -= 240
def dir_header():
s1 = pygame.surface.Surface((largura_tela, altura_tela/10))
font = pygame.font.Font(None, 36)
texto = '{}'.format("Detalhes de Arquivos/Diretórios")
text = font.render(texto, 1, white)
s1.blit(text, (650, 10))
tela.blit(s1, (0, 0))
def process_header():
s6 = pygame.surface.Surface((largura_tela, altura_tela/8))
font = pygame.font.Font(None, 16)
texto_barra = '{:<6}'.format("PID") + " "
texto_barra = texto_barra + '{:10}'.format("Threads") + " "
texto_barra = texto_barra + '{:30}'.format("Data de Criação") + " "
texto_barra = texto_barra + '{:25}'.format("CPU - UT")
texto_barra = texto_barra + '{:26}'.format("CPU - ST")
texto_barra = texto_barra + '{:25}'.format("Memory(%)") + " "
texto_barra = texto_barra + '{:10}'.format("RSS") + " "
texto_barra = texto_barra + '{:25}'.format("VMS") + " "
texto_barra = texto_barra + '{:20}'.format("Executável")
text = font.render(texto_barra, 1, white)
s6.blit(text, (20, 80))
tela.blit(s6, (0, 0))
def arq_dir():
s1 = pygame.surface.Surface((largura_tela, altura_tela))
p = psutil.Process()
font = pygame.font.Font(None, 14)
y = 100
for i in processos:
texto_barra = '{:<6}'.format(i) + " "
texto_barra = texto_barra + '{:^12}'.format(p.num_threads()) + " "
texto_barra = texto_barra + '{:26}'.format(time.ctime(p.create_time()))
texto_barra = texto_barra + '{:20.2f}'.format(p.cpu_times().user)
texto_barra = texto_barra + '{:30.2f}'.format(p.cpu_times().system)
texto_barra = texto_barra + '{:30.2f}'.format(p.memory_percent()) + " MB"
rss = p.memory_info().rss/1024/1024
texto_barra = texto_barra + '{:30.2f}'.format(rss) + " MB"
vms = p.memory_info().vms/1024/1024
texto_barra = texto_barra + '{:15.2f}'.format(vms) + " MB" + " "
texto_barra = texto_barra + '{:15}'.format(p.exe())
text = font.render(texto_barra, 1, white)
s1.blit(text, (30, y))
tela.blit(s1, (0, 0))
y+= 15
if y >= 600:
break
def arq_dir_button():
s1 = pygame.surface.Surface((largura_tela, altura_tela))
font = pygame.font.Font(None, 32)
pygame.draw.rect(s1, grey, (20, 30, 125, 30))
texto_barra = "Próximo"
text = font.render(texto_barra, 1, white)
s1.blit(text, (38, 35))
tela.blit(s1, (670, 670))
def menu_init():
s0 = pygame.surface.Surface((largura_tela, altura_tela))
s0.fill(white)
font = pygame.font.Font(None, 50)
texto_barra = ("OPÇOES DE TELA")
text = font.render(texto_barra, 1, black)
s0.blit(text, (350, 20))
tela.blit(s0, (0, 0))
texto_barra = ("Botão esquerdo do mouse - Gráfico de Uso")
text = font.render(texto_barra, 1, black)
s0.blit(text, (70, 140))
tela.blit(s0, (0, 0))
texto_barra = ("Botão direito do mouse - Monitoramento de Uso Geral")
text = font.render(texto_barra, 1, black)
s0.blit(text, (70, 260))
tela.blit(s0, (0, 0))
texto_barra = ("ESPAÇO - Detalhes de Arquivos/Diretórios")
text = font.render(texto_barra, 1, black)
s0.blit(text, (70, 380))
tela.blit(s0, (0, 0))
texto_barra = ("SHIFT - ESCANEAMENTO DE IP")
text = font.render(texto_barra, 1, black)
s0.blit(text, (70, 500))
tela.blit(s0, (0, 0))
texto_barra = ("TAB - Voltar a Tela Inicial")
text = font.render(texto_barra, 1, black)
s0.blit(text, (70, 620))
tela.blit(s0, (0, 0))
def ping_ip(host):
s1 = pygame.surface.Surface((largura_tela, altura_tela))
font = pygame.font.Font(None, 32)
nmp = nmap.PortScanner()
nmp.scan(host)
y = 0
for proto in nmp[host].all_protocols():
texto_barra = 'Protocolo : {}'.format(proto)
text = font.render(texto_barra, 1, white)
s1.blit(text, (20, 20))
tela.blit(s1, (0, 0))
lport = nmp[host][proto].keys()
for port in lport:
texto_barra = 'Porta: {:<15} Estado: {:>10}'.format(port, nmp[host][proto][port]['state'])
text = font.render(texto_barra, 1, white)
s1.blit(text, (70, 120+y))
tela.blit(s1, (0, 0))
y+= 30
menu_init()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
pos_x, pos_y = pygame.mouse.get_pos()
if pos_x >= 691 and pos_x <= 815 and pos_y >= 700 and pos_y <= 730:
buttons += 30
else:
menu = "menu1"
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 3:
menu = "menu2"
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
menu = "menu3"
if event.type == pygame.KEYDOWN and event.key == pygame.K_TAB:
menu = ""
menu_init()
if event.type == pygame.KEYDOWN and event.key == pygame.K_LSHIFT:
ping_ip(ip)
if menu == "menu1":
pc_infos()
cpu_graph()
m_graph()
disk_graph()
threads_text()
threads_graph()
if menu != "menu1":
break
if menu == "menu2":
infos()
if menu != "menu2":
break
if menu == "menu3":
arq_dir()
process_header()
dir_header()
arq_dir_button()
time.sleep(0.1)
if menu != "menu3":
break
pygame.display.update()
clock.tick(50)
pygame.display.quit() | true | true |
f7107ca561761e166b2411668c743cfd45a39430 | 453 | py | Python | crawler/crawler/items.py | suchkultur/trueffelschwein | 189ffccb8a26d852107ab66d055879c39f7dcebd | [
"MIT"
] | null | null | null | crawler/crawler/items.py | suchkultur/trueffelschwein | 189ffccb8a26d852107ab66d055879c39f7dcebd | [
"MIT"
] | null | null | null | crawler/crawler/items.py | suchkultur/trueffelschwein | 189ffccb8a26d852107ab66d055879c39f7dcebd | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.item import Item, Field
class CrawlerItem(scrapy.Item):
url = Field()
html_title = Field()
html_h1 = Field()
html_h2 = Field()
html_h3 = Field()
html_h4 = Field()
html_h5 = Field()
html_h6 = Field()
html_p = Field()
html_a = Field()
| 19.695652 | 51 | 0.637969 |
import scrapy
from scrapy.item import Item, Field
class CrawlerItem(scrapy.Item):
url = Field()
html_title = Field()
html_h1 = Field()
html_h2 = Field()
html_h3 = Field()
html_h4 = Field()
html_h5 = Field()
html_h6 = Field()
html_p = Field()
html_a = Field()
| true | true |
f7107dc6017ef5f07ab6acc581e8700372001f5a | 391 | py | Python | src/application/tables/table.py | cruz-f/protrend | b72c17fa1606b4cf5ca6d60c51737b43ba3fdbc1 | [
"MIT"
] | null | null | null | src/application/tables/table.py | cruz-f/protrend | b72c17fa1606b4cf5ca6d60c51737b43ba3fdbc1 | [
"MIT"
] | 1 | 2022-02-11T18:38:39.000Z | 2022-02-11T18:38:39.000Z | src/application/tables/table.py | cruz-f/protrend | b72c17fa1606b4cf5ca6d60c51737b43ba3fdbc1 | [
"MIT"
] | null | null | null | class Table:
context = ''
fields = ()
columns = ()
sortable = ()
types = ()
def context_dict(self):
return {field: {'field': field,
'column': col,
'sortable': sort,
'type': type_}
for field, col, sort, type_ in zip(self.fields, self.columns, self.sortable, self.types)}
| 27.928571 | 105 | 0.460358 | class Table:
context = ''
fields = ()
columns = ()
sortable = ()
types = ()
def context_dict(self):
return {field: {'field': field,
'column': col,
'sortable': sort,
'type': type_}
for field, col, sort, type_ in zip(self.fields, self.columns, self.sortable, self.types)}
| true | true |
f7107f13b8744297c5a93ee8a1e0309058d01042 | 2,855 | py | Python | moxom/compiler/astparser.py | sikrinick/moxom | 75e1e59b93ea1c8eea2141c0105d083089e25ca9 | [
"MIT"
] | 4 | 2020-10-26T01:06:37.000Z | 2022-02-02T18:35:03.000Z | moxom/compiler/astparser.py | sikrinick/moxom | 75e1e59b93ea1c8eea2141c0105d083089e25ca9 | [
"MIT"
] | null | null | null | moxom/compiler/astparser.py | sikrinick/moxom | 75e1e59b93ea1c8eea2141c0105d083089e25ca9 | [
"MIT"
] | null | null | null | from dataclasses import dataclass
from moxom.compiler.lexer import OperatorToken, IdentifierToken, AtomTokens
from typing import Union, Optional
from .cstparser import CstNode, Expr
import ast
from moxom.compiler.operators import operator_dict, AssignOperator, AndOperator, ThenOperator
@dataclass
class AtomNode:
value: [str, int, float]
chain: Union['AtomNode', 'FunctionNode', None] = None
@dataclass
class BinaryNode:
token: OperatorToken
lhs: 'AstNode'
rhs: 'AstNode'
@dataclass
class FunctionNode:
token: IdentifierToken
chain: Union[AtomNode, 'FunctionNode', None] = None
@dataclass
class DeclarationNode:
token: IdentifierToken
arguments: [IdentifierToken]
subroutine: Union['AstNode']
AstNode = Union[AtomNode, BinaryNode, FunctionNode, DeclarationNode]
class AstParser:
def parse(self, cst: CstNode) -> AstNode:
if isinstance(cst.token_or_expr, IdentifierToken):
return FunctionNode(
cst.token_or_expr,
self.parse(cst.right_node) if cst.right_node is not None else None
)
elif type(cst.token_or_expr) in AtomTokens:
value = cst.token_or_expr.value
value = ast.literal_eval(value) if type(value) == str else value
return AtomNode(
value,
self.parse(cst.right_node) if cst.right_node is not None else None
)
elif isinstance(cst.token_or_expr, Expr):
return self.parse(cst.right_node)
elif isinstance(cst.token_or_expr, OperatorToken):
operator = operator_dict[cst.token_or_expr.value]
if operator in [AndOperator, ThenOperator]:
left = self.parse(cst.left_node)
right = self.parse(cst.right_node)
return BinaryNode(cst.token_or_expr, left, right)
elif operator is AssignOperator:
name, arguments = self.parse_signature(cst.left_node)
body = self.parse(cst.right_node)
return DeclarationNode(name, arguments, body)
raise Exception("Not supported token: %s" % cst.token_or_expr)
@dataclass
class FunctionSignature:
name: IdentifierToken
arguments: [IdentifierToken]
def parse_signature(self, cst: CstNode) -> (IdentifierToken, [IdentifierToken]):
return cst.token_or_expr, self.parse_signature_arguments(cst.right_node)
def parse_signature_arguments(self, cst: Optional[CstNode]) -> [IdentifierToken]:
if cst is None:
return []
elif type(cst.token_or_expr) is IdentifierToken:
arguments = [cst.token_or_expr]
return arguments + self.parse_signature_arguments(cst.right_node)
else:
raise Exception("Function signature should contain only identifiers")
| 32.078652 | 93 | 0.6669 | from dataclasses import dataclass
from moxom.compiler.lexer import OperatorToken, IdentifierToken, AtomTokens
from typing import Union, Optional
from .cstparser import CstNode, Expr
import ast
from moxom.compiler.operators import operator_dict, AssignOperator, AndOperator, ThenOperator
@dataclass
class AtomNode:
value: [str, int, float]
chain: Union['AtomNode', 'FunctionNode', None] = None
@dataclass
class BinaryNode:
token: OperatorToken
lhs: 'AstNode'
rhs: 'AstNode'
@dataclass
class FunctionNode:
token: IdentifierToken
chain: Union[AtomNode, 'FunctionNode', None] = None
@dataclass
class DeclarationNode:
token: IdentifierToken
arguments: [IdentifierToken]
subroutine: Union['AstNode']
AstNode = Union[AtomNode, BinaryNode, FunctionNode, DeclarationNode]
class AstParser:
def parse(self, cst: CstNode) -> AstNode:
if isinstance(cst.token_or_expr, IdentifierToken):
return FunctionNode(
cst.token_or_expr,
self.parse(cst.right_node) if cst.right_node is not None else None
)
elif type(cst.token_or_expr) in AtomTokens:
value = cst.token_or_expr.value
value = ast.literal_eval(value) if type(value) == str else value
return AtomNode(
value,
self.parse(cst.right_node) if cst.right_node is not None else None
)
elif isinstance(cst.token_or_expr, Expr):
return self.parse(cst.right_node)
elif isinstance(cst.token_or_expr, OperatorToken):
operator = operator_dict[cst.token_or_expr.value]
if operator in [AndOperator, ThenOperator]:
left = self.parse(cst.left_node)
right = self.parse(cst.right_node)
return BinaryNode(cst.token_or_expr, left, right)
elif operator is AssignOperator:
name, arguments = self.parse_signature(cst.left_node)
body = self.parse(cst.right_node)
return DeclarationNode(name, arguments, body)
raise Exception("Not supported token: %s" % cst.token_or_expr)
@dataclass
class FunctionSignature:
name: IdentifierToken
arguments: [IdentifierToken]
def parse_signature(self, cst: CstNode) -> (IdentifierToken, [IdentifierToken]):
return cst.token_or_expr, self.parse_signature_arguments(cst.right_node)
def parse_signature_arguments(self, cst: Optional[CstNode]) -> [IdentifierToken]:
if cst is None:
return []
elif type(cst.token_or_expr) is IdentifierToken:
arguments = [cst.token_or_expr]
return arguments + self.parse_signature_arguments(cst.right_node)
else:
raise Exception("Function signature should contain only identifiers")
| true | true |
f7107f2436acaf4ce2118c270a01d52b337bb5df | 20,619 | py | Python | lib/surface/init.py | bopopescu/Google-Cloud-SDK-1 | c4683bacb2f6192d8a816932e438a0493085469b | [
"Apache-2.0"
] | null | null | null | lib/surface/init.py | bopopescu/Google-Cloud-SDK-1 | c4683bacb2f6192d8a816932e438a0493085469b | [
"Apache-2.0"
] | null | null | null | lib/surface/init.py | bopopescu/Google-Cloud-SDK-1 | c4683bacb2f6192d8a816932e438a0493085469b | [
"Apache-2.0"
] | 1 | 2020-07-24T20:13:29.000Z | 2020-07-24T20:13:29.000Z | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Workflow to set up gcloud environment."""
import os
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions as c_exc
from googlecloudsdk.calliope import usage_text
from googlecloudsdk.command_lib import init_util
from googlecloudsdk.core import config
from googlecloudsdk.core import execution_utils
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import yaml
from googlecloudsdk.core.configurations import named_configs
from googlecloudsdk.core.console import console_io
from googlecloudsdk.core.credentials import store as c_store
from googlecloudsdk.core.diagnostics import network_diagnostics
from googlecloudsdk.core.resource import resource_projector
from googlecloudsdk.core.util import platforms
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Init(base.Command):
"""Initialize or reinitialize gcloud.
{command} launches an interactive Getting Started workflow for gcloud.
It performs the following setup steps:
- Authorizes gcloud and other SDK tools to access Google Cloud Platform using
your user account credentials, or lets you select from accounts whose
credentials are already available.
- Sets properties in a gcloud configuration, including the current project and
the default Google Compute Engine region and zone.
{command} can be used for initial setup of gcloud and to create new or
reinitialize gcloud configurations. More information can be found by
running `gcloud topic configurations`.
Properties set by {command} are local and persistent, and are not affected by
remote changes to the project. For example, the default Compute Engine zone in
your configuration remains stable, even if you or another user changes the
project-level default zone in the Cloud Platform Console.
To sync the configuration, re-run {command}
"""
@staticmethod
def Args(parser):
parser.add_argument(
'obsolete_project_arg',
nargs='?',
hidden=True,
help='THIS ARGUMENT NEEDS HELP TEXT.')
parser.add_argument(
'--console-only',
action='store_true',
help=('Prevent the command from launching a browser for '
'authorization.'))
parser.add_argument(
'--skip-diagnostics',
action='store_true',
help='Do not run diagnostics.')
def Run(self, args):
"""Allows user to select configuration, and initialize it."""
if args.obsolete_project_arg:
raise c_exc.InvalidArgumentException(
args.obsolete_project_arg,
'`gcloud init` has changed and no longer takes a PROJECT argument. '
'Please use `gcloud source repos clone` to clone this '
'project\'s source repositories.')
log.status.write('Welcome! This command will take you through '
'the configuration of gcloud.\n\n')
if properties.VALUES.core.disable_prompts.GetBool():
raise c_exc.InvalidArgumentException(
'disable_prompts/--quiet',
'gcloud init command cannot run with disabled prompts.')
configuration_name = self._PickConfiguration()
if not configuration_name:
return
log.status.write('Your current configuration has been set to: [{0}]\n\n'
.format(configuration_name))
if not args.skip_diagnostics:
log.status.write('You can skip diagnostics next time by using the '
'following flag:\n')
log.status.write(' gcloud init --skip-diagnostics\n\n')
network_passed = network_diagnostics.NetworkDiagnostic().RunChecks()
if not network_passed:
if not console_io.PromptContinue(
message='Network errors detected.',
prompt_string='Would you like to continue anyway',
default=False):
log.status.write('You can re-run diagnostics with the following '
'command:\n')
log.status.write(' gcloud info --run-diagnostics\n\n')
return
# User project quota is now the global default, but this command calls
# legacy APIs where it should be disabled. It must happen after the config
# settings are persisted so this temporary value doesn't get persisted as
# well.
base.DisableUserProjectQuota()
if not self._PickAccount(args.console_only, preselected=args.account):
return
if not self._PickProject(preselected=args.project):
return
self._PickDefaultRegionAndZone()
self._CreateBotoConfig()
self._Summarize(configuration_name)
def _PickAccount(self, console_only, preselected=None):
"""Checks if current credentials are valid, if not runs auth login.
Args:
console_only: bool, True if the auth flow shouldn't use the browser
preselected: str, disable prompts and use this value if not None
Returns:
bool, True if valid credentials are setup.
"""
new_credentials = False
accounts = c_store.AvailableAccounts()
if accounts:
# There is at least one credentialed account.
if preselected:
# Try to use the preselected account. Fail if its not credentialed.
account = preselected
if account not in accounts:
log.status.write('\n[{0}] is not one of your credentialed accounts '
'[{1}].\n'.format(account, ','.join(accounts)))
return False
# Fall through to the set the account property.
else:
# Prompt for the account to use.
idx = console_io.PromptChoice(
accounts + ['Log in with a new account'],
message='Choose the account you would like to use to perform '
'operations for this configuration:',
prompt_string=None)
if idx is None:
return False
if idx < len(accounts):
account = accounts[idx]
else:
new_credentials = True
elif preselected:
# Preselected account specified but there are no credentialed accounts.
log.status.write('\n[{0}] is not a credentialed account.\n'.format(
preselected))
return False
else:
# Must log in with new credentials.
answer = console_io.PromptContinue(
prompt_string='You must log in to continue. Would you like to log in')
if not answer:
return False
new_credentials = True
if new_credentials:
# Call `gcloud auth login` to get new credentials.
# `gcloud auth login` may have user interaction, do not suppress it.
browser_args = ['--no-launch-browser'] if console_only else []
if not self._RunCmd(['auth', 'login'],
['--force', '--brief'] + browser_args,
disable_user_output=False):
return False
# `gcloud auth login` already did `gcloud config set account`.
else:
# Set the config account to the already credentialed account.
properties.PersistProperty(properties.VALUES.core.account, account)
log.status.write('You are logged in as: [{0}].\n\n'
.format(properties.VALUES.core.account.Get()))
return True
def _PickConfiguration(self):
"""Allows user to re-initialize, create or pick new configuration.
Returns:
Configuration name or None.
"""
configs = named_configs.ConfigurationStore.AllConfigs()
active_config = named_configs.ConfigurationStore.ActiveConfig()
if not configs or active_config.name not in configs:
# Listing the configs will automatically create the default config. The
# only way configs could be empty here is if there are no configurations
# and the --configuration flag or env var is set to something that does
# not exist. If configs has items, but the active config is not in there,
# that similarly means that hey are using the flag or the env var and that
# config does not exist. In either case, just create it and go with that
# one as the one that as they have already selected it.
named_configs.ConfigurationStore.CreateConfig(active_config.name)
# Need to active it in the file, not just the environment.
active_config.Activate()
return active_config.name
# If there is a only 1 config, it is the default, and there are no
# properties set, assume it was auto created and that it should be
# initialized as if it didn't exist.
if len(configs) == 1:
default_config = configs.get(named_configs.DEFAULT_CONFIG_NAME, None)
if default_config and not default_config.GetProperties():
default_config.Activate()
return default_config.name
choices = []
log.status.write('Settings from your current configuration [{0}] are:\n'
.format(active_config.name))
log.status.flush()
log.status.write(yaml.dump(properties.VALUES.AllValues()))
log.out.flush()
log.status.write('\n')
log.status.flush()
choices.append(
'Re-initialize this configuration [{0}] with new settings '.format(
active_config.name))
choices.append('Create a new configuration')
config_choices = [name for name, c in sorted(configs.iteritems())
if not c.is_active]
choices.extend('Switch to and re-initialize '
'existing configuration: [{0}]'.format(name)
for name in config_choices)
idx = console_io.PromptChoice(choices, message='Pick configuration to use:')
if idx is None:
return None
if idx == 0: # If reinitialize was selected.
self._CleanCurrentConfiguration()
return active_config.name
if idx == 1: # Second option is to create new configuration.
return self._CreateConfiguration()
config_name = config_choices[idx - 2]
named_configs.ConfigurationStore.ActivateConfig(config_name)
return config_name
def _PickProject(self, preselected=None):
"""Allows user to select a project.
Args:
preselected: str, use this value if not None
Returns:
str, project_id or None if was not selected.
"""
project_id = init_util.PickProject(preselected=preselected)
if project_id is not None:
properties.PersistProperty(properties.VALUES.core.project, project_id)
log.status.write('Your current project has been set to: [{0}].\n\n'
.format(project_id))
return project_id
def _PickDefaultRegionAndZone(self):
"""Pulls metadata properties for region and zone and sets them in gcloud."""
try:
# Use --quiet flag to skip the enable api prompt.
project_info = self._RunCmd(['compute', 'project-info', 'describe'],
params=['--quiet'])
except Exception: # pylint:disable=broad-except
log.status.write("""\
Not setting default zone/region (this feature makes it easier to use
[gcloud compute] by setting an appropriate default value for the
--zone and --region flag).
See https://cloud.google.com/compute/docs/gcloud-compute section on how to set
default compute region and zone manually. If you would like [gcloud init] to be
able to do this for you the next time you run it, make sure the
Compute Engine API is enabled for your project on the
https://console.developers.google.com/apis page.
""")
return None
default_zone = None
default_region = None
if project_info is not None:
project_info = resource_projector.MakeSerializable(project_info)
metadata = project_info.get('commonInstanceMetadata', {})
for item in metadata.get('items', []):
if item['key'] == 'google-compute-default-zone':
default_zone = item['value']
elif item['key'] == 'google-compute-default-region':
default_region = item['value']
# We could not determine zone automatically. Before offering choices for
# zone and/or region ask user if he/she wants to do this.
if not default_zone:
answer = console_io.PromptContinue(
prompt_string=('Do you want to configure a default Compute '
'Region and Zone?'))
if not answer:
return
# Same logic applies to region and zone properties.
def SetProperty(name, default_value, list_command):
"""Set named compute property to default_value or get via list command."""
if not default_value:
values = self._RunCmd(list_command)
if values is None:
return
values = list(values)
message = (
'Which Google Compute Engine {0} would you like to use as project '
'default?\n'
'If you do not specify a {0} via a command line flag while working '
'with Compute Engine resources, the default is assumed.').format(
name)
idx = console_io.PromptChoice(
[value['name'] for value in values]
+ ['Do not set default {0}'.format(name)],
message=message, prompt_string=None, allow_freeform=True,
freeform_suggester=usage_text.TextChoiceSuggester())
if idx is None or idx == len(values):
return
default_value = values[idx]
properties.PersistProperty(properties.VALUES.compute.Property(name),
default_value['name'])
log.status.write('Your project default Compute Engine {0} has been set '
'to [{1}].\nYou can change it by running '
'[gcloud config set compute/{0} NAME].\n\n'
.format(name, default_value['name']))
return default_value
if default_zone:
default_zone = self._RunCmd(['compute', 'zones', 'describe'],
[default_zone])
zone = SetProperty('zone', default_zone, ['compute', 'zones', 'list'])
if zone and not default_region:
default_region = zone['region']
if default_region:
default_region = self._RunCmd(['compute', 'regions', 'describe'],
[default_region])
SetProperty('region', default_region, ['compute', 'regions', 'list'])
def _Summarize(self, configuration_name):
log.status.Print('Your Google Cloud SDK is configured and ready to use!\n')
log.status.Print(
'* Commands that require authentication will use {0} by default'
.format(properties.VALUES.core.account.Get()))
project = properties.VALUES.core.project.Get()
if project:
log.status.Print(
'* Commands will reference project `{0}` by default'
.format(project))
region = properties.VALUES.compute.region.Get()
if region:
log.status.Print(
'* Compute Engine commands will use region `{0}` by default'
.format(region))
zone = properties.VALUES.compute.zone.Get()
if zone:
log.status.Print(
'* Compute Engine commands will use zone `{0}` by default\n'
.format(zone))
log.status.Print(
'Run `gcloud help config` to learn how to change individual settings\n')
log.status.Print(
'This gcloud configuration is called [{config}]. You can create '
'additional configurations if you work with multiple accounts and/or '
'projects.'.format(config=configuration_name))
log.status.Print('Run `gcloud topic configurations` to learn more.\n')
log.status.Print('Some things to try next:\n')
log.status.Print(
'* Run `gcloud --help` to see the Cloud Platform services you can '
'interact with. And run `gcloud help COMMAND` to get help on any '
'gcloud command.')
log.status.Print(
'* Run `gcloud topic -h` to learn about advanced features of the SDK '
'like arg files and output formatting')
def _CreateConfiguration(self):
configuration_name = console_io.PromptResponse(
'Enter configuration name. Names start with a lower case letter and '
'contain only lower case letters a-z, digits 0-9, and hyphens \'-\': ')
configuration_name = configuration_name.strip()
named_configs.ConfigurationStore.CreateConfig(configuration_name)
named_configs.ConfigurationStore.ActivateConfig(configuration_name)
named_configs.ActivePropertiesFile.Invalidate()
return configuration_name
def _CreateBotoConfig(self):
gsutil_path = _FindGsutil()
if not gsutil_path:
log.debug('Unable to find [gsutil]. Not configuring default .boto '
'file')
return
boto_path = platforms.ExpandHomePath(os.path.join('~', '.boto'))
if os.path.exists(boto_path):
log.debug('Not configuring default .boto file. File already '
'exists at [{boto_path}].'.format(boto_path=boto_path))
return
# 'gsutil config -n' creates a default .boto file that the user can read and
# modify.
command_args = ['config', '-n', '-o', boto_path]
if platforms.OperatingSystem.Current() == platforms.OperatingSystem.WINDOWS:
gsutil_args = execution_utils.ArgsForCMDTool(gsutil_path,
*command_args)
else:
gsutil_args = execution_utils.ArgsForExecutableTool(gsutil_path,
*command_args)
return_code = execution_utils.Exec(gsutil_args, no_exit=True,
out_func=log.file_only_logger.debug,
err_func=log.file_only_logger.debug)
if return_code == 0:
log.status.write("""\
Created a default .boto configuration file at [{boto_path}]. See this file and
[https://cloud.google.com/storage/docs/gsutil/commands/config] for more
information about configuring Google Cloud Storage.
""".format(boto_path=boto_path))
else:
log.status.write('Error creating a default .boto configuration file. '
'Please run [gsutil config -n] if you would like to '
'create this file.\n')
def _CleanCurrentConfiguration(self):
properties.PersistProperty(properties.VALUES.core.account, None)
properties.PersistProperty(properties.VALUES.core.project, None)
properties.PersistProperty(properties.VALUES.compute.region, None)
properties.PersistProperty(properties.VALUES.compute.zone, None)
named_configs.ActivePropertiesFile.Invalidate()
def _RunCmd(self, cmd, params=None, disable_user_output=True):
if not self._cli_power_users_only.IsValidCommand(cmd):
log.info('Command %s does not exist.', cmd)
return None
if params is None:
params = []
args = cmd + params
log.info('Executing: [gcloud %s]', ' '.join(args))
try:
# Disable output from individual commands, so that we get
# command run results, and don't clutter output of init.
if disable_user_output:
args.append('--no-user-output-enabled')
if (properties.VALUES.core.verbosity.Get() is None and
disable_user_output):
# Unless user explicitly set verbosity, suppress from subcommands.
args.append('--verbosity=none')
if properties.VALUES.core.log_http.GetBool():
args.append('--log-http')
# TODO(b/38338044): Remove usage of ExecuteCommandDoNotUse
return resource_projector.MakeSerializable(
self.ExecuteCommandDoNotUse(args))
except SystemExit as exc:
log.info('[%s] has failed\n', ' '.join(cmd + params))
raise c_exc.FailedSubCommand(cmd + params, exc.code)
except BaseException:
log.info('Failed to run [%s]\n', ' '.join(cmd + params))
raise
def _FindGsutil():
"""Finds the bundled gsutil wrapper.
Returns:
The path to gsutil.
"""
sdk_bin_path = config.Paths().sdk_bin_path
if not sdk_bin_path:
return
if platforms.OperatingSystem.Current() == platforms.OperatingSystem.WINDOWS:
gsutil = 'gsutil.cmd'
else:
gsutil = 'gsutil'
return os.path.join(sdk_bin_path, gsutil)
| 41.073705 | 80 | 0.668461 |
import os
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions as c_exc
from googlecloudsdk.calliope import usage_text
from googlecloudsdk.command_lib import init_util
from googlecloudsdk.core import config
from googlecloudsdk.core import execution_utils
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import yaml
from googlecloudsdk.core.configurations import named_configs
from googlecloudsdk.core.console import console_io
from googlecloudsdk.core.credentials import store as c_store
from googlecloudsdk.core.diagnostics import network_diagnostics
from googlecloudsdk.core.resource import resource_projector
from googlecloudsdk.core.util import platforms
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Init(base.Command):
@staticmethod
def Args(parser):
parser.add_argument(
'obsolete_project_arg',
nargs='?',
hidden=True,
help='THIS ARGUMENT NEEDS HELP TEXT.')
parser.add_argument(
'--console-only',
action='store_true',
help=('Prevent the command from launching a browser for '
'authorization.'))
parser.add_argument(
'--skip-diagnostics',
action='store_true',
help='Do not run diagnostics.')
def Run(self, args):
if args.obsolete_project_arg:
raise c_exc.InvalidArgumentException(
args.obsolete_project_arg,
'`gcloud init` has changed and no longer takes a PROJECT argument. '
'Please use `gcloud source repos clone` to clone this '
'project\'s source repositories.')
log.status.write('Welcome! This command will take you through '
'the configuration of gcloud.\n\n')
if properties.VALUES.core.disable_prompts.GetBool():
raise c_exc.InvalidArgumentException(
'disable_prompts/--quiet',
'gcloud init command cannot run with disabled prompts.')
configuration_name = self._PickConfiguration()
if not configuration_name:
return
log.status.write('Your current configuration has been set to: [{0}]\n\n'
.format(configuration_name))
if not args.skip_diagnostics:
log.status.write('You can skip diagnostics next time by using the '
'following flag:\n')
log.status.write(' gcloud init --skip-diagnostics\n\n')
network_passed = network_diagnostics.NetworkDiagnostic().RunChecks()
if not network_passed:
if not console_io.PromptContinue(
message='Network errors detected.',
prompt_string='Would you like to continue anyway',
default=False):
log.status.write('You can re-run diagnostics with the following '
'command:\n')
log.status.write(' gcloud info --run-diagnostics\n\n')
return
# User project quota is now the global default, but this command calls
# legacy APIs where it should be disabled. It must happen after the config
# settings are persisted so this temporary value doesn't get persisted as
base.DisableUserProjectQuota()
if not self._PickAccount(args.console_only, preselected=args.account):
return
if not self._PickProject(preselected=args.project):
return
self._PickDefaultRegionAndZone()
self._CreateBotoConfig()
self._Summarize(configuration_name)
def _PickAccount(self, console_only, preselected=None):
new_credentials = False
accounts = c_store.AvailableAccounts()
if accounts:
if preselected:
account = preselected
if account not in accounts:
log.status.write('\n[{0}] is not one of your credentialed accounts '
'[{1}].\n'.format(account, ','.join(accounts)))
return False
else:
idx = console_io.PromptChoice(
accounts + ['Log in with a new account'],
message='Choose the account you would like to use to perform '
'operations for this configuration:',
prompt_string=None)
if idx is None:
return False
if idx < len(accounts):
account = accounts[idx]
else:
new_credentials = True
elif preselected:
log.status.write('\n[{0}] is not a credentialed account.\n'.format(
preselected))
return False
else:
answer = console_io.PromptContinue(
prompt_string='You must log in to continue. Would you like to log in')
if not answer:
return False
new_credentials = True
if new_credentials:
browser_args = ['--no-launch-browser'] if console_only else []
if not self._RunCmd(['auth', 'login'],
['--force', '--brief'] + browser_args,
disable_user_output=False):
return False
else:
properties.PersistProperty(properties.VALUES.core.account, account)
log.status.write('You are logged in as: [{0}].\n\n'
.format(properties.VALUES.core.account.Get()))
return True
def _PickConfiguration(self):
configs = named_configs.ConfigurationStore.AllConfigs()
active_config = named_configs.ConfigurationStore.ActiveConfig()
if not configs or active_config.name not in configs:
named_configs.ConfigurationStore.CreateConfig(active_config.name)
active_config.Activate()
return active_config.name
if len(configs) == 1:
default_config = configs.get(named_configs.DEFAULT_CONFIG_NAME, None)
if default_config and not default_config.GetProperties():
default_config.Activate()
return default_config.name
choices = []
log.status.write('Settings from your current configuration [{0}] are:\n'
.format(active_config.name))
log.status.flush()
log.status.write(yaml.dump(properties.VALUES.AllValues()))
log.out.flush()
log.status.write('\n')
log.status.flush()
choices.append(
'Re-initialize this configuration [{0}] with new settings '.format(
active_config.name))
choices.append('Create a new configuration')
config_choices = [name for name, c in sorted(configs.iteritems())
if not c.is_active]
choices.extend('Switch to and re-initialize '
'existing configuration: [{0}]'.format(name)
for name in config_choices)
idx = console_io.PromptChoice(choices, message='Pick configuration to use:')
if idx is None:
return None
if idx == 0: # If reinitialize was selected.
self._CleanCurrentConfiguration()
return active_config.name
if idx == 1: # Second option is to create new configuration.
return self._CreateConfiguration()
config_name = config_choices[idx - 2]
named_configs.ConfigurationStore.ActivateConfig(config_name)
return config_name
def _PickProject(self, preselected=None):
project_id = init_util.PickProject(preselected=preselected)
if project_id is not None:
properties.PersistProperty(properties.VALUES.core.project, project_id)
log.status.write('Your current project has been set to: [{0}].\n\n'
.format(project_id))
return project_id
def _PickDefaultRegionAndZone(self):
try:
# Use --quiet flag to skip the enable api prompt.
project_info = self._RunCmd(['compute', 'project-info', 'describe'],
params=['--quiet'])
except Exception: # pylint:disable=broad-except
log.status.write("""\
Not setting default zone/region (this feature makes it easier to use
[gcloud compute] by setting an appropriate default value for the
--zone and --region flag).
See https://cloud.google.com/compute/docs/gcloud-compute section on how to set
default compute region and zone manually. If you would like [gcloud init] to be
able to do this for you the next time you run it, make sure the
Compute Engine API is enabled for your project on the
https://console.developers.google.com/apis page.
""")
return None
default_zone = None
default_region = None
if project_info is not None:
project_info = resource_projector.MakeSerializable(project_info)
metadata = project_info.get('commonInstanceMetadata', {})
for item in metadata.get('items', []):
if item['key'] == 'google-compute-default-zone':
default_zone = item['value']
elif item['key'] == 'google-compute-default-region':
default_region = item['value']
# We could not determine zone automatically. Before offering choices for
# zone and/or region ask user if he/she wants to do this.
if not default_zone:
answer = console_io.PromptContinue(
prompt_string=('Do you want to configure a default Compute '
'Region and Zone?'))
if not answer:
return
# Same logic applies to region and zone properties.
def SetProperty(name, default_value, list_command):
if not default_value:
values = self._RunCmd(list_command)
if values is None:
return
values = list(values)
message = (
'Which Google Compute Engine {0} would you like to use as project '
'default?\n'
'If you do not specify a {0} via a command line flag while working '
'with Compute Engine resources, the default is assumed.').format(
name)
idx = console_io.PromptChoice(
[value['name'] for value in values]
+ ['Do not set default {0}'.format(name)],
message=message, prompt_string=None, allow_freeform=True,
freeform_suggester=usage_text.TextChoiceSuggester())
if idx is None or idx == len(values):
return
default_value = values[idx]
properties.PersistProperty(properties.VALUES.compute.Property(name),
default_value['name'])
log.status.write('Your project default Compute Engine {0} has been set '
'to [{1}].\nYou can change it by running '
'[gcloud config set compute/{0} NAME].\n\n'
.format(name, default_value['name']))
return default_value
if default_zone:
default_zone = self._RunCmd(['compute', 'zones', 'describe'],
[default_zone])
zone = SetProperty('zone', default_zone, ['compute', 'zones', 'list'])
if zone and not default_region:
default_region = zone['region']
if default_region:
default_region = self._RunCmd(['compute', 'regions', 'describe'],
[default_region])
SetProperty('region', default_region, ['compute', 'regions', 'list'])
def _Summarize(self, configuration_name):
log.status.Print('Your Google Cloud SDK is configured and ready to use!\n')
log.status.Print(
'* Commands that require authentication will use {0} by default'
.format(properties.VALUES.core.account.Get()))
project = properties.VALUES.core.project.Get()
if project:
log.status.Print(
'* Commands will reference project `{0}` by default'
.format(project))
region = properties.VALUES.compute.region.Get()
if region:
log.status.Print(
'* Compute Engine commands will use region `{0}` by default'
.format(region))
zone = properties.VALUES.compute.zone.Get()
if zone:
log.status.Print(
'* Compute Engine commands will use zone `{0}` by default\n'
.format(zone))
log.status.Print(
'Run `gcloud help config` to learn how to change individual settings\n')
log.status.Print(
'This gcloud configuration is called [{config}]. You can create '
'additional configurations if you work with multiple accounts and/or '
'projects.'.format(config=configuration_name))
log.status.Print('Run `gcloud topic configurations` to learn more.\n')
log.status.Print('Some things to try next:\n')
log.status.Print(
'* Run `gcloud --help` to see the Cloud Platform services you can '
'interact with. And run `gcloud help COMMAND` to get help on any '
'gcloud command.')
log.status.Print(
'* Run `gcloud topic -h` to learn about advanced features of the SDK '
'like arg files and output formatting')
def _CreateConfiguration(self):
configuration_name = console_io.PromptResponse(
'Enter configuration name. Names start with a lower case letter and '
'contain only lower case letters a-z, digits 0-9, and hyphens \'-\': ')
configuration_name = configuration_name.strip()
named_configs.ConfigurationStore.CreateConfig(configuration_name)
named_configs.ConfigurationStore.ActivateConfig(configuration_name)
named_configs.ActivePropertiesFile.Invalidate()
return configuration_name
def _CreateBotoConfig(self):
gsutil_path = _FindGsutil()
if not gsutil_path:
log.debug('Unable to find [gsutil]. Not configuring default .boto '
'file')
return
boto_path = platforms.ExpandHomePath(os.path.join('~', '.boto'))
if os.path.exists(boto_path):
log.debug('Not configuring default .boto file. File already '
'exists at [{boto_path}].'.format(boto_path=boto_path))
return
# 'gsutil config -n' creates a default .boto file that the user can read and
# modify.
command_args = ['config', '-n', '-o', boto_path]
if platforms.OperatingSystem.Current() == platforms.OperatingSystem.WINDOWS:
gsutil_args = execution_utils.ArgsForCMDTool(gsutil_path,
*command_args)
else:
gsutil_args = execution_utils.ArgsForExecutableTool(gsutil_path,
*command_args)
return_code = execution_utils.Exec(gsutil_args, no_exit=True,
out_func=log.file_only_logger.debug,
err_func=log.file_only_logger.debug)
if return_code == 0:
log.status.write("""\
Created a default .boto configuration file at [{boto_path}]. See this file and
[https://cloud.google.com/storage/docs/gsutil/commands/config] for more
information about configuring Google Cloud Storage.
""".format(boto_path=boto_path))
else:
log.status.write('Error creating a default .boto configuration file. '
'Please run [gsutil config -n] if you would like to '
'create this file.\n')
def _CleanCurrentConfiguration(self):
properties.PersistProperty(properties.VALUES.core.account, None)
properties.PersistProperty(properties.VALUES.core.project, None)
properties.PersistProperty(properties.VALUES.compute.region, None)
properties.PersistProperty(properties.VALUES.compute.zone, None)
named_configs.ActivePropertiesFile.Invalidate()
def _RunCmd(self, cmd, params=None, disable_user_output=True):
if not self._cli_power_users_only.IsValidCommand(cmd):
log.info('Command %s does not exist.', cmd)
return None
if params is None:
params = []
args = cmd + params
log.info('Executing: [gcloud %s]', ' '.join(args))
try:
# Disable output from individual commands, so that we get
# command run results, and don't clutter output of init.
if disable_user_output:
args.append('--no-user-output-enabled')
if (properties.VALUES.core.verbosity.Get() is None and
disable_user_output):
args.append('--verbosity=none')
if properties.VALUES.core.log_http.GetBool():
args.append('--log-http')
return resource_projector.MakeSerializable(
self.ExecuteCommandDoNotUse(args))
except SystemExit as exc:
log.info('[%s] has failed\n', ' '.join(cmd + params))
raise c_exc.FailedSubCommand(cmd + params, exc.code)
except BaseException:
log.info('Failed to run [%s]\n', ' '.join(cmd + params))
raise
def _FindGsutil():
sdk_bin_path = config.Paths().sdk_bin_path
if not sdk_bin_path:
return
if platforms.OperatingSystem.Current() == platforms.OperatingSystem.WINDOWS:
gsutil = 'gsutil.cmd'
else:
gsutil = 'gsutil'
return os.path.join(sdk_bin_path, gsutil)
| true | true |
f7107fda7c5bfabbde90193d9508ada61985db57 | 1,954 | py | Python | .cf_status.py | pointtonull/888 | a7a576a91c92b76f9e4d33e8f7ef83cbe9e68429 | [
"MIT"
] | null | null | null | .cf_status.py | pointtonull/888 | a7a576a91c92b76f9e4d33e8f7ef83cbe9e68429 | [
"MIT"
] | null | null | null | .cf_status.py | pointtonull/888 | a7a576a91c92b76f9e4d33e8f7ef83cbe9e68429 | [
"MIT"
] | null | null | null | import json
from pprint import pprint, pformat
from dateutil.parser import parse as parsetimestamp
SILENCE_STATUSES = [
"CREATE_COMPLETE",
"CREATE_IN_PROGRESS",
"DELETE_COMPLETE",
"DELETE_IN_PROGRESS",
"REVIEW_IN_PROGRESS",
"ROLLBACK_COMPLETE",
"ROLLBACK_IN_PROGRESS",
"UPDATE_COMPLETE",
"UPDATE_COMPLETE_CLEANUP_IN_PROGRESS",
"UPDATE_IN_PROGRESS",
"UPDATE_ROLLBACK_COMPLETE",
"UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS",
"UPDATE_ROLLBACK_IN_PROGRESS",
]
def get_time(event):
return parsetimestamp(event["Timestamp"])
def tprint(title):
print("%s\n%s\n" % (title, "#" * len(title)))
def iformat(string, indent=0):
if not isinstance(object, str):
string = pformat(string)
return ("\n" + " " * indent).join(string.splitlines())
messages = json.load(open(".cf.messages"))
events = messages["StackEvents"]
relevant = []
ignored = set()
last_time = get_time(events[0])
for event in events:
age = last_time - get_time(event)
status = event.get("ResourceStatus")
if age.seconds > 60:
break
last_time = get_time(event)
if status not in SILENCE_STATUSES:
event["RelativeAge"] = str(age)
relevant.append(event)
else:
ignored.add(status)
if ignored:
print("Ignoring %s" % ", ".join(ignored))
if relevant:
print("\nTraceback (most recent event at botom):")
for event in relevant[::-1]:
status = event.pop("ResourceStatus")
properties = event.get("ResourceProperties", "{}")
try:
event["ResourceProperties"] = json.loads(properties)
except:
print("could not process properties '%s'" % properties)
print(status)
for key, value in event.items():
print(" %s: %s" % (key, iformat(value, 8)))
print("")
else:
print("CloudFormation Stack's logs looks clear.")
| 27.521127 | 67 | 0.627943 | import json
from pprint import pprint, pformat
from dateutil.parser import parse as parsetimestamp
SILENCE_STATUSES = [
"CREATE_COMPLETE",
"CREATE_IN_PROGRESS",
"DELETE_COMPLETE",
"DELETE_IN_PROGRESS",
"REVIEW_IN_PROGRESS",
"ROLLBACK_COMPLETE",
"ROLLBACK_IN_PROGRESS",
"UPDATE_COMPLETE",
"UPDATE_COMPLETE_CLEANUP_IN_PROGRESS",
"UPDATE_IN_PROGRESS",
"UPDATE_ROLLBACK_COMPLETE",
"UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS",
"UPDATE_ROLLBACK_IN_PROGRESS",
]
def get_time(event):
return parsetimestamp(event["Timestamp"])
def tprint(title):
print("%s\n%s\n" % (title, "#" * len(title)))
def iformat(string, indent=0):
if not isinstance(object, str):
string = pformat(string)
return ("\n" + " " * indent).join(string.splitlines())
messages = json.load(open(".cf.messages"))
events = messages["StackEvents"]
relevant = []
ignored = set()
last_time = get_time(events[0])
for event in events:
age = last_time - get_time(event)
status = event.get("ResourceStatus")
if age.seconds > 60:
break
last_time = get_time(event)
if status not in SILENCE_STATUSES:
event["RelativeAge"] = str(age)
relevant.append(event)
else:
ignored.add(status)
if ignored:
print("Ignoring %s" % ", ".join(ignored))
if relevant:
print("\nTraceback (most recent event at botom):")
for event in relevant[::-1]:
status = event.pop("ResourceStatus")
properties = event.get("ResourceProperties", "{}")
try:
event["ResourceProperties"] = json.loads(properties)
except:
print("could not process properties '%s'" % properties)
print(status)
for key, value in event.items():
print(" %s: %s" % (key, iformat(value, 8)))
print("")
else:
print("CloudFormation Stack's logs looks clear.")
| true | true |
f710810b12384c37843d991e733d7c74f738237f | 1,160 | py | Python | tflitehub/mobilenet_quant_test.py | rsuderman/iree-samples | e7ba8e639c1bdd763793a6cf21930fb238607b3f | [
"Apache-2.0"
] | 12 | 2021-08-18T07:01:50.000Z | 2022-03-30T18:19:12.000Z | tflitehub/mobilenet_quant_test.py | rsuderman/iree-samples | e7ba8e639c1bdd763793a6cf21930fb238607b3f | [
"Apache-2.0"
] | 10 | 2021-09-29T01:23:47.000Z | 2022-03-25T21:59:04.000Z | tflitehub/mobilenet_quant_test.py | rsuderman/iree-samples | e7ba8e639c1bdd763793a6cf21930fb238607b3f | [
"Apache-2.0"
] | 12 | 2021-09-09T00:58:53.000Z | 2022-03-03T17:35:32.000Z | # RUN: %PYTHON %s
import absl.testing
import numpy
import test_util
import urllib.request
from PIL import Image
model_path = "https://tfhub.dev/tensorflow/lite-model/mobilenet_v2_1.0_224_quantized/1/default/1?lite-format=tflite"
class MobilenetQuantTest(test_util.TFLiteModelTest):
def __init__(self, *args, **kwargs):
super(MobilenetQuantTest, self).__init__(model_path, *args, **kwargs)
def compare_results(self, iree_results, tflite_results, details):
super(MobilenetQuantTest, self).compare_results(iree_results, tflite_results, details)
self.assertTrue(numpy.isclose(iree_results[0], tflite_results[0], atol=1e-6).all())
def generate_inputs(self, input_details):
img_path = "https://github.com/google-coral/test_data/raw/master/cat.bmp"
local_path = "/".join([self.workdir, "cat.bmp"])
urllib.request.urlretrieve(img_path, local_path)
shape = input_details[0]["shape"]
im = numpy.array(Image.open(local_path).resize((shape[1], shape[2])))
args = [im.reshape(shape)]
return args
def test_compile_tflite(self):
self.compile_and_execute()
if __name__ == '__main__':
absl.testing.absltest.main()
| 33.142857 | 116 | 0.743966 |
import absl.testing
import numpy
import test_util
import urllib.request
from PIL import Image
model_path = "https://tfhub.dev/tensorflow/lite-model/mobilenet_v2_1.0_224_quantized/1/default/1?lite-format=tflite"
class MobilenetQuantTest(test_util.TFLiteModelTest):
def __init__(self, *args, **kwargs):
super(MobilenetQuantTest, self).__init__(model_path, *args, **kwargs)
def compare_results(self, iree_results, tflite_results, details):
super(MobilenetQuantTest, self).compare_results(iree_results, tflite_results, details)
self.assertTrue(numpy.isclose(iree_results[0], tflite_results[0], atol=1e-6).all())
def generate_inputs(self, input_details):
img_path = "https://github.com/google-coral/test_data/raw/master/cat.bmp"
local_path = "/".join([self.workdir, "cat.bmp"])
urllib.request.urlretrieve(img_path, local_path)
shape = input_details[0]["shape"]
im = numpy.array(Image.open(local_path).resize((shape[1], shape[2])))
args = [im.reshape(shape)]
return args
def test_compile_tflite(self):
self.compile_and_execute()
if __name__ == '__main__':
absl.testing.absltest.main()
| true | true |
f7108151b0c3aa3b406dfde25785279e911d6bea | 6,443 | py | Python | logtools/_parse.py | AlainLich/logtools | 584e575d25f0ebcd7a51cc6d5aefb530f80f6d22 | [
"Apache-2.0"
] | 2 | 2021-06-08T21:48:18.000Z | 2022-03-09T05:50:13.000Z | logtools/_parse.py | AlainLich/logtools | 584e575d25f0ebcd7a51cc6d5aefb530f80f6d22 | [
"Apache-2.0"
] | null | null | null | logtools/_parse.py | AlainLich/logtools | 584e575d25f0ebcd7a51cc6d5aefb530f80f6d22 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ........................................ NOTICE
#
# This file has been derived and modified from a source licensed under Apache Version 2.0.
# See files NOTICE and README.md for more details.
#
# ........................................ ******
"""
logtools._parse
Log format parsing programmatic and command-line utilities.
uses the logtools.parsers module
"""
import sys
import logging
from operator import and_
from optparse import OptionParser
from functools import reduce
import json
import logtools.parsers
import logtools.parsers2
from ._config import interpolate_config, AttrDict, setLoglevel
from ._config import checkDpath
from .parsers2 import FileFormat , TraditionalFileFormat, ForwardFormat
from .parsers2 import TraditionalForwardFormat
from .utils import getObj
checkDpath()
__all__ = ['logparse_parse_args', 'logparse', 'logparse_main']
def logparse_parse_args():
parser = OptionParser()
parser.add_option("-p", "--parser", dest="parser", default=None,
help="Log format parser (e.g 'CommonLogFormat'). See documentation for available parsers.") # noqa
parser.add_option("-F", "--format", dest="format", default=None,
help="Format string. Used by the parser (e.g AccessLog format specifier)") # noqa
parser.add_option("-f", "--field", dest="field", default=None,
help="Parsed Field index to output")
parser.add_option("-i", "--ignore", dest="ignore", default=None, action="store_true", # noqa
help="Ignore missing fields errors (skip lines with missing fields)") # noqa
parser.add_option("-H", "--header", dest="header", default=None, action="store_true", # noqa
help="Prepend a header describing the selected fields to output.") # noqa
parser.add_option("-P", "--profile", dest="profile", default='logparse',
help="Configuration profile (section in configuration file)") # noqa
parser.add_option("-R", "--raw", dest="raw", default=None, action="store_true",
help="When set output is not encoded for UTF-8")
## default kept for compatibility
# logging level for debug and other information
parser.add_option("-s","--sym" , type = str,
dest="logLevSym",
help="logging level (symbol)")
parser.add_option("-n","--num" , type=int ,
dest="logLevVal",
help="logging level (value)")
options, args = parser.parse_args()
# Interpolate from configuration
options.parser = interpolate_config(options.parser, options.profile, 'parser')
options.format = interpolate_config(options.format, options.profile, 'format',
default=False)
options.field = interpolate_config(options.field, options.profile, 'field')
options.ignore = interpolate_config(options.ignore, options.profile, 'ignore',
default=False, type=bool)
options.header = interpolate_config(options.header, options.profile, 'header',
default=False, type=bool)
options.raw = interpolate_config(options.raw, options.profile, 'raw')
# Set the logging level
setLoglevel(options)
return AttrDict(options.__dict__), args
def logparse(options, args, fh):
"""Parse given input stream using given
parser class and emit specified field(s)"""
field = options.field
logtools.parsers2.addConfigFileSection()
parser = getObj(options.parser, (logtools.parsers, logtools.parsers2))()
if options.get('format', None):
parser.set_format(options.format)
keyfunc = None
keys = None
if isinstance(options.field, int) or \
(isinstance(options.field, str) and options.field.isdigit()):
# Field given as integer (index)
field = int(options.field) - 1
key_func = lambda x: parser(x.strip()).by_index(field, raw=True)
keys = [options.field]
else:
if isinstance(parser, logtools.parsers2.JSONParserPlus):
key_func = logtools.parsers2.dpath_getter_gen(parser, options.field, options)
else:
# Field given as string
# Check how many fields are requested
keys = options.field.split(",")
L = len(keys)
if L == 1:
key_func = lambda x: parser(x.strip())[field]
else:
# Multiple fields requested
is_indices = reduce(and_, (k.isdigit() for k in keys), True)
key_func = logtools.parsers.multikey_getter_gen(parser, keys,
is_indices=is_indices)
if options.header is True:
yield '\t'.join(keys)
for line in fh:
try:
yield key_func(line)
except KeyError as exc:
# Could not find user-specified field
logging.warn("Could not match user-specified fields: %s", exc)
except ValueError as exc:
# Could not parse the log line
if options.ignore:
logging.debug("Could not match fields for parsed line: %s", line)
continue
else:
logging.error("Could not match fields for parsed line: %s", line)
raise
def logparse_main():
"""Console entry-point"""
options, args = logparse_parse_args()
for row in logparse(options, args, fh=sys.stdin):
if row:
if isinstance(row, dict):
json.dump(row, sys.stdout)
elif options.raw:
print(row)
else:
print( row.encode('ascii', 'ignore') )
return 0
| 38.580838 | 121 | 0.609809 |
import sys
import logging
from operator import and_
from optparse import OptionParser
from functools import reduce
import json
import logtools.parsers
import logtools.parsers2
from ._config import interpolate_config, AttrDict, setLoglevel
from ._config import checkDpath
from .parsers2 import FileFormat , TraditionalFileFormat, ForwardFormat
from .parsers2 import TraditionalForwardFormat
from .utils import getObj
checkDpath()
__all__ = ['logparse_parse_args', 'logparse', 'logparse_main']
def logparse_parse_args():
parser = OptionParser()
parser.add_option("-p", "--parser", dest="parser", default=None,
help="Log format parser (e.g 'CommonLogFormat'). See documentation for available parsers.")
parser.add_option("-F", "--format", dest="format", default=None,
help="Format string. Used by the parser (e.g AccessLog format specifier)")
parser.add_option("-f", "--field", dest="field", default=None,
help="Parsed Field index to output")
parser.add_option("-i", "--ignore", dest="ignore", default=None, action="store_true",
help="Ignore missing fields errors (skip lines with missing fields)")
parser.add_option("-H", "--header", dest="header", default=None, action="store_true",
help="Prepend a header describing the selected fields to output.")
parser.add_option("-P", "--profile", dest="profile", default='logparse',
help="Configuration profile (section in configuration file)")
parser.add_option("-R", "--raw", dest="raw", default=None, action="store_true",
help="When set output is not encoded for UTF-8")
","--sym" , type = str,
dest="logLevSym",
help="logging level (symbol)")
parser.add_option("-n","--num" , type=int ,
dest="logLevVal",
help="logging level (value)")
options, args = parser.parse_args()
options.parser = interpolate_config(options.parser, options.profile, 'parser')
options.format = interpolate_config(options.format, options.profile, 'format',
default=False)
options.field = interpolate_config(options.field, options.profile, 'field')
options.ignore = interpolate_config(options.ignore, options.profile, 'ignore',
default=False, type=bool)
options.header = interpolate_config(options.header, options.profile, 'header',
default=False, type=bool)
options.raw = interpolate_config(options.raw, options.profile, 'raw')
setLoglevel(options)
return AttrDict(options.__dict__), args
def logparse(options, args, fh):
field = options.field
logtools.parsers2.addConfigFileSection()
parser = getObj(options.parser, (logtools.parsers, logtools.parsers2))()
if options.get('format', None):
parser.set_format(options.format)
keyfunc = None
keys = None
if isinstance(options.field, int) or \
(isinstance(options.field, str) and options.field.isdigit()):
field = int(options.field) - 1
key_func = lambda x: parser(x.strip()).by_index(field, raw=True)
keys = [options.field]
else:
if isinstance(parser, logtools.parsers2.JSONParserPlus):
key_func = logtools.parsers2.dpath_getter_gen(parser, options.field, options)
else:
keys = options.field.split(",")
L = len(keys)
if L == 1:
key_func = lambda x: parser(x.strip())[field]
else:
is_indices = reduce(and_, (k.isdigit() for k in keys), True)
key_func = logtools.parsers.multikey_getter_gen(parser, keys,
is_indices=is_indices)
if options.header is True:
yield '\t'.join(keys)
for line in fh:
try:
yield key_func(line)
except KeyError as exc:
logging.warn("Could not match user-specified fields: %s", exc)
except ValueError as exc:
if options.ignore:
logging.debug("Could not match fields for parsed line: %s", line)
continue
else:
logging.error("Could not match fields for parsed line: %s", line)
raise
def logparse_main():
options, args = logparse_parse_args()
for row in logparse(options, args, fh=sys.stdin):
if row:
if isinstance(row, dict):
json.dump(row, sys.stdout)
elif options.raw:
print(row)
else:
print( row.encode('ascii', 'ignore') )
return 0
| true | true |
f7108264cb02420e9950c61ae9763e056ed2199c | 807 | py | Python | Core Concepts/Deep Learning/3_RELU_activation_function.py | WyckliffeAluga/data-chronicles | 5219fe9cdbafb9fd7be88727483952c4c13f2790 | [
"MIT"
] | null | null | null | Core Concepts/Deep Learning/3_RELU_activation_function.py | WyckliffeAluga/data-chronicles | 5219fe9cdbafb9fd7be88727483952c4c13f2790 | [
"MIT"
] | null | null | null | Core Concepts/Deep Learning/3_RELU_activation_function.py | WyckliffeAluga/data-chronicles | 5219fe9cdbafb9fd7be88727483952c4c13f2790 | [
"MIT"
] | 1 | 2021-02-09T12:22:55.000Z | 2021-02-09T12:22:55.000Z | import numpy as np
def relu(input):
'''Define your relu activation function here'''
# Calculate the value for the output of the relu function: output
output = max(input, 0)
# Return the value just calculated
return(output)
input_data = np.array([3,5])
# Calculate node 0 value: node_0_output
node_0_input = (input_data * weights['node_0']).sum()
node_0_output = relu(node_0_input)
# Calculate node 1 value: node_1_output
node_1_input = (input_data * weights['node_1']).sum()
node_1_output = relu(node_1_input)
# Put node values into array: hidden_layer_outputs
hidden_layer_outputs = np.array([node_0_output, node_1_output])
# Calculate model output (do not apply relu)
model_output = (hidden_layer_outputs * weights['output']).sum()
# Print model output
print(model_output)
| 27.827586 | 69 | 0.739777 | import numpy as np
def relu(input):
output = max(input, 0)
return(output)
input_data = np.array([3,5])
node_0_input = (input_data * weights['node_0']).sum()
node_0_output = relu(node_0_input)
node_1_input = (input_data * weights['node_1']).sum()
node_1_output = relu(node_1_input)
hidden_layer_outputs = np.array([node_0_output, node_1_output])
model_output = (hidden_layer_outputs * weights['output']).sum()
print(model_output)
| true | true |
f7108274340407b2057c752d7910bfe615395f11 | 28,071 | py | Python | misc/config_tools/launch_config/com.py | lifeix/acrn-hypervisor | 0d12dacc2549c72a96b3703d6cfe900ed904c302 | [
"BSD-3-Clause"
] | null | null | null | misc/config_tools/launch_config/com.py | lifeix/acrn-hypervisor | 0d12dacc2549c72a96b3703d6cfe900ed904c302 | [
"BSD-3-Clause"
] | 1 | 2021-07-26T22:16:18.000Z | 2021-07-26T22:16:18.000Z | misc/config_tools/launch_config/com.py | Surfndez/acrn-hypervisor | 69fef2e685597e51ce2103e8701e90d210ec0640 | [
"BSD-3-Clause"
] | null | null | null | # Copyright (C) 2019 Intel Corporation. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#
import scenario_cfg_lib
import launch_cfg_lib
import common
import pt
def is_nuc_whl_linux(names, vmid):
uos_type = names['uos_types'][vmid]
board_name = names['board_name']
if launch_cfg_lib.is_linux_like(uos_type) and board_name not in ("apl-mrb", "apl-up2"):
return True
return False
def is_mount_needed(virt_io, vmid):
if True in launch_cfg_lib.MOUNT_FLAG_DIC[vmid]:
return True
return False
def tap_uos_net(names, virt_io, vmid, config):
uos_type = names['uos_types'][vmid]
board_name = names['board_name']
vm_name = common.undline_name(uos_type).lower()
if launch_cfg_lib.is_linux_like(uos_type) or uos_type in ("ANDROID", "ALIOS"):
i = 0
for mount_flag in launch_cfg_lib.MOUNT_FLAG_DIC[vmid]:
if not mount_flag:
i += 1
continue
blk = virt_io['block'][vmid][i]
rootfs_img = blk.split(':')[1].strip(':')
print('if [ ! -f "/data{}/{}" ]; then'.format(i, rootfs_img), file=config)
print(' echo "no /data{}/{}, exit"'.format(i, rootfs_img), file=config)
print(" exit", file=config)
print("fi", file=config)
print("", file=config)
i += 1
print("#vm-name used to generate uos-mac address", file=config)
print("mac=$(cat /sys/class/net/e*/address)", file=config)
print("vm_name=post_vm_id$1", file=config)
print("mac_seed=${mac:0:17}-${vm_name}", file=config)
print("", file=config)
for net in virt_io['network'][vmid]:
if net:
net_name = net
if ',' in net:
net_name = net.split(',')[0]
print("tap_net tap_{}".format(net_name), file=config)
print("#check if the vm is running or not", file=config)
print("vm_ps=$(pgrep -a -f acrn-dm)", file=config)
print('result=$(echo $vm_ps | grep -w "${vm_name}")', file=config)
print('if [[ "$result" != "" ]]; then', file=config)
print(' echo "$vm_name is running, can\'t create twice!"', file=config)
print(" exit", file=config)
print("fi", file=config)
print("", file=config)
def off_line_cpus(args, vmid, uos_type, config):
"""
:param args: the dictionary of argument for acrn-dm
:param vmid: ID of the vm
:param uos_type: the type of UOS
:param config: it is a file pointer to write offline cpu information
"""
pcpu_id_list = get_cpu_affinity_list(args["cpu_affinity"], vmid)
if not pcpu_id_list:
sos_vmid = launch_cfg_lib.get_sos_vmid()
cpu_affinity = common.get_leaf_tag_map(common.SCENARIO_INFO_FILE, "cpu_affinity", "pcpu_id")
pcpu_id_list = get_cpu_affinity_list(cpu_affinity, sos_vmid+vmid)
if not pcpu_id_list:
key = "scenario config error"
launch_cfg_lib.ERR_LIST[key] = "No available cpu to offline and pass it to vm {}".format(vmid)
print("# offline pinned vCPUs from SOS before launch UOS", file=config)
print('cpu_path="/sys/devices/system/cpu"', file=config)
print("for i in `ls ${cpu_path}`; do", file=config)
print(" for j in {}; do".format(' '.join([str(i) for i in pcpu_id_list])), file=config)
print(' if [ "cpu"$j = $i ]; then', file=config)
print(' online=`cat ${cpu_path}/$i/online`', file=config)
print(' idx=`echo $i | tr -cd "[1-99]"`', file=config)
print(' echo $i online=$online', file=config)
print(' if [ "$online" = "1" ]; then', file=config)
print(" echo 0 > ${cpu_path}/$i/online", file=config)
print(" online=`cat ${cpu_path}/$i/online`", file=config)
print(" # during boot time, cpu hotplug may be disabled by pci_device_probe during a pci module insmod", file=config)
print(' while [ "$online" = "1" ]; do', file=config)
print(" sleep 1", file=config)
print(" echo 0 > ${cpu_path}/$i/online", file=config)
print(" online=`cat ${cpu_path}/$i/online`", file=config)
print(" done", file=config)
print(" echo $idx > /sys/devices/virtual/misc/acrn_hsm/remove_cpu", file=config)
print(" fi", file=config)
print(" fi", file=config)
print(" done", file=config)
print("done", file=config)
print("", file=config)
def run_container(board_name, uos_type, config):
"""
The container contains the clearlinux as rootfs
:param board_name: board name
:param uos_type: the os name of user os
:param config: the file pointer to store the information
"""
# the runC.json is store in the path under board name, but for nuc7i7dnb/nuc6cayh/kbl-nuc-i7 is under nuc/
if 'nuc' in board_name:
board_name = 'nuc'
if board_name not in ("apl-mrb", "nuc") or not launch_cfg_lib.is_linux_like(uos_type):
return
print("function run_container()", file=config)
print("{", file=config)
print("vm_name=vm1", file=config)
print('config_src="/usr/share/acrn/samples/{}/runC.json"'.format(board_name), file=config)
print('shell="/usr/share/acrn/conf/add/$vm_name.sh"', file=config)
print('arg_file="/usr/share/acrn/conf/add/$vm_name.args"', file=config)
print('runc_bundle="/usr/share/acrn/conf/add/runc/$vm_name"', file=config)
print('rootfs_dir="/usr/share/acrn/conf/add/runc/rootfs"', file=config)
print('config_dst="$runc_bundle/config.json"', file=config)
print("", file=config)
print("", file=config)
print("input=$(runc list -f table | awk '{print $1}''{print $3}')", file=config)
print("arr=(${input// / })", file=config)
print("", file=config)
print("for((i=0;i<${#arr[@]};i++))", file=config)
print("do", file=config)
print(' if [ "$vm_name" = "${arr[$i]}" ]; then', file=config)
print(' if [ "running" = "${arr[$i+1]}" ]; then', file=config)
print(' echo "runC instance ${arr[$i]} is running"', file=config)
print(" exit", file=config)
print(" else", file=config)
print(" runc kill ${arr[$i]}", file=config)
print(" runc delete ${arr[$i]}", file=config)
print(" fi", file=config)
print(" fi", file=config)
print("done", file=config)
print("vmsts=$(acrnctl list)", file=config)
print("vms=(${vmsts// / })", file=config)
print("for((i=0;i<${#vms[@]};i++))", file=config)
print("do", file=config)
print(' if [ "$vm_name" = "${vms[$i]}" ]; then', file=config)
print(' if [ "stopped" != "${vms[$i+1]}" ]; then', file=config)
print(' echo "Uos ${vms[$i]} ${vms[$i+1]}"', file=config)
print(" acrnctl stop ${vms[$i]}", file=config)
print(" fi", file=config)
print(" fi", file=config)
print("done", file=config)
dst_str = """ cp "$config_src" "$config_dst"
args=$(sed '{s/-C//g;s/^[ \\t]*//g;s/^/\\"/;s/ /\\",\\"/g;s/$/\\"/}' ${arg_file})
sed -i "s|\\"sh\\"|\\"$shell\\", $args|" $config_dst"""
print('', file=config)
print('if [ ! -f "$shell" ]; then', file=config)
print(' echo "Pls add the vm at first!"', file=config)
print(' exit', file=config)
print('fi', file=config)
print('', file=config)
print('if [ ! -f "$arg_file" ]; then', file=config)
print(' echo "Pls add the vm args!"', file=config)
print(' exit', file=config)
print('fi', file=config)
print('', file=config)
print('if [ ! -d "$rootfs_dir" ]; then', file=config)
print(' mkdir -p "$rootfs_dir"', file=config)
print('fi', file=config)
print('if [ ! -d "$runc_bundle" ]; then', file=config)
print(' mkdir -p "$runc_bundle"', file=config)
print('fi', file=config)
print('if [ ! -f "$config_dst" ]; then', file=config)
print('{}'.format(dst_str), file=config)
print('fi', file=config)
print('runc run --bundle $runc_bundle -d $vm_name', file=config)
print('echo "The runC container is running in backgroud"', file=config)
print('echo "\'#runc exec <vmname> bash\' to login the container bash"', file=config)
print('exit', file=config)
print('}', file=config)
print('', file=config)
def boot_image_type(args, vmid, config):
if not args['vbootloader'][vmid] or (args['vbootloader'][vmid] and args['vbootloader'][vmid] != "vsbl"):
return
print('boot_dev_flag=",b"', file=config)
print("if [ $4 == 1 ];then", file=config)
print(' boot_image_option="--vsbl /usr/share/acrn/bios/VSBL_debug.bin"', file=config)
print("else", file=config)
print(' boot_image_option="--vsbl /usr/share/acrn/bios/VSBL.bin"', file=config)
print("fi", file=config)
print("", file=config)
def interrupt_storm(pt_sel, config):
if not pt_sel:
return
# TODO: --intr_monitor should be configurable by user
print("#interrupt storm monitor for pass-through devices, params order:", file=config)
print("#threshold/s,probe-period(s),intr-inject-delay-time(ms),delay-duration(ms)", file=config)
print('intr_storm_monitor="--intr_monitor 10000,10,1,100"', file=config)
print("", file=config)
def gvt_arg_set(dm, vmid, uos_type, config):
gvt_args = dm['gvt_args'][vmid]
if gvt_args == "gvtd":
bus = int(launch_cfg_lib.GPU_BDF.split(':')[0], 16)
dev = int(launch_cfg_lib.GPU_BDF.split('.')[0].split(':')[1], 16)
fun = int(launch_cfg_lib.GPU_BDF.split('.')[1], 16)
print(' -s 2,passthru,{}/{}/{},gpu \\'.format(bus, dev, fun), file=config)
elif gvt_args:
print(' -s 2,pci-gvt -G "$2" \\', file=config)
def log_level_set(uos_type, config):
print("#logger_setting, format: logger_name,level; like following", file=config)
print('logger_setting="--logger_setting console,level=4;kmsg,level=3;disk,level=5"', file=config)
print("", file=config)
def tap_network(virt_io, vmid, config):
none_i = 0
tap_net_list = virt_io['network'][vmid]
for net in tap_net_list:
if net == None:
none_i += 1
tap_net_num = len(tap_net_list) - none_i
if tap_net_num >= 1:
print("function tap_net() {", file=config)
print("# create a unique tap device for each VM", file=config)
print("tap=$1", file=config)
print('tap_exist=$(ip a | grep "$tap" | awk \'{print $1}\')', file=config)
print('if [ "$tap_exist"x != "x" ]; then', file=config)
print(' echo "tap device existed, reuse $tap"', file=config)
print("else", file=config)
print(" ip tuntap add dev $tap mode tap", file=config)
print("fi", file=config)
print("", file=config)
print("# if acrn-br0 exists, add VM's unique tap device under it", file=config)
print("br_exist=$(ip a | grep acrn-br0 | awk '{print $1}')", file=config)
print('if [ "$br_exist"x != "x" -a "$tap_exist"x = "x" ]; then', file=config)
print(' echo "acrn-br0 bridge aleady exists, adding new tap device to it..."', file=config)
print(' ip link set "$tap" master acrn-br0', file=config)
print(' ip link set dev "$tap" down', file=config)
print(' ip link set dev "$tap" up', file=config)
print("fi", file=config)
print("}", file=config)
print("", file=config)
def launch_begin(names, virt_io, vmid, config):
board_name = names['board_name']
uos_type = names['uos_types'][vmid]
launch_uos = common.undline_name(uos_type).lower()
tap_network(virt_io, vmid, config)
run_container(board_name, uos_type, config)
print("function launch_{}()".format(launch_uos), file=config)
print("{", file=config)
def wa_usage(uos_type, config):
if uos_type in ("ANDROID", "ALIOS"):
print("# WA for USB role switch hang issue, disable runtime PM of xHCI device", file=config)
print("echo on > /sys/devices/pci0000:00/0000:00:15.0/power/control", file=config)
print("", file=config)
def mem_size_set(args, vmid, config):
mem_size = args['mem_size'][vmid]
print("mem_size={}M".format(mem_size), file=config)
def uos_launch(names, args, virt_io, vmid, config):
gvt_args = args['gvt_args'][vmid]
uos_type = names['uos_types'][vmid]
launch_uos = common.undline_name(uos_type).lower()
board_name = names['board_name']
if 'nuc' in board_name:
board_name = 'nuc'
if uos_type == "CLEARLINUX" and board_name in ("apl-mrb", "nuc"):
print('if [ "$1" = "-C" ];then', file=config)
print(' if [ $(hostname) = "runc" ]; then', file=config)
print(' echo "Already in container exit!"', file=config)
print(" exit", file=config)
print(" fi", file=config)
print(' echo "runc_container"', file=config)
print(" run_container", file=config)
if board_name == "apl-mrb":
print(" exit", file=config)
print("fi", file=config)
if is_mount_needed(virt_io, vmid):
print("", file=config)
if gvt_args == "gvtd" or not gvt_args:
print('launch_{} {} "{}" $debug'.format(launch_uos, vmid, vmid), file=config)
else:
print('launch_{} {} "{}" "{}" $debug'.format(launch_uos, vmid, gvt_args, vmid), file=config)
print("", file=config)
i = 0
for mount_flag in launch_cfg_lib.MOUNT_FLAG_DIC[vmid]:
if not mount_flag:
i += 1
continue
print("umount /data{}".format(i), file=config)
i += 1
else:
print("else", file=config)
if gvt_args == "gvtd" or not gvt_args:
print(' launch_{} {}'.format(launch_uos, vmid), file=config)
elif gvt_args:
print(' launch_{} {} "{}"'.format(launch_uos, vmid, gvt_args), file=config)
print("fi", file=config)
return
elif not is_mount_needed(virt_io, vmid):
if gvt_args == "gvtd" or not gvt_args:
print('launch_{} {}'.format(launch_uos, vmid), file=config)
else:
print('launch_{} {} "{}"'.format(launch_uos, vmid, gvt_args), file=config)
else:
print("", file=config)
if gvt_args == "gvtd" or not gvt_args:
print('launch_{} {} "{}" $debug'.format(launch_uos, vmid, vmid), file=config)
else:
print('launch_{} {} "{}" "{}" $debug'.format(launch_uos, vmid, gvt_args, vmid), file=config)
print("", file=config)
i = 0
for mount_flag in launch_cfg_lib.MOUNT_FLAG_DIC[vmid]:
if not mount_flag:
i += 1
continue
print("umount /data{}".format(i), file=config)
i += 1
def launch_end(names, args, virt_io, vmid, config):
board_name = names['board_name']
uos_type = names['uos_types'][vmid]
mem_size = args["mem_size"][vmid]
if uos_type in ("CLEARLINUX", "ANDROID", "ALIOS") and not is_nuc_whl_linux(names, vmid):
print("debug=0", file=config)
print("", file=config)
print('while getopts "hdC" opt', file=config)
print("do", file=config)
print(" case $opt in", file=config)
print(" d) debug=1", file=config)
print(" ;;", file=config)
print(" C)", file=config)
print(" ;;", file=config)
print(" h) help", file=config)
print(" exit 1", file=config)
print(" ;;", file=config)
print(" ?) help", file=config)
print(" exit 1", file=config)
print(" ;;", file=config)
print(" esac", file=config)
print("done", file=config)
print("", file=config)
if is_mount_needed(virt_io, vmid):
i = 0
for mount_flag in launch_cfg_lib.MOUNT_FLAG_DIC[vmid]:
if not mount_flag:
i += 1
continue
blk = virt_io['block'][vmid][i]
root_fs = blk.split(':')[0]
print('if [ ! -b "{}" ]; then'.format(root_fs), file=config)
print(' echo "no {} data partition, exit"'.format(root_fs), file=config)
print(" exit", file=config)
print("fi", file=config)
print("mkdir -p /data{}".format(i), file=config)
print("mount {} /data{}".format(root_fs, i), file=config)
print("", file=config)
i += 1
sos_vmid = launch_cfg_lib.get_sos_vmid()
if args['cpu_sharing'] == "SCHED_NOOP" or common.VM_TYPES[vmid+sos_vmid] == "POST_RT_VM":
off_line_cpus(args, vmid, uos_type, config)
uos_launch(names, args, virt_io, vmid, config)
def set_dm_pt(names, sel, vmid, config, dm):
uos_type = names['uos_types'][vmid]
if sel.bdf['usb_xdci'][vmid] and sel.slot['usb_xdci'][vmid]:
sub_attr = ''
if uos_type == "WINDOWS":
sub_attr = ',d3hot_reset'
print(' -s {},passthru,{}/{}/{}{} \\'.format(sel.slot["usb_xdci"][vmid], sel.bdf["usb_xdci"][vmid][0:2],\
sel.bdf["usb_xdci"][vmid][3:5], sel.bdf["usb_xdci"][vmid][6:7], sub_attr), file=config)
# pass through audio/audio_codec
if sel.bdf['audio'][vmid]:
print(" $boot_audio_option \\", file=config)
if sel.bdf['cse'][vmid] and sel.slot['cse'][vmid]:
print(" $boot_cse_option \\", file=config)
if sel.bdf["sd_card"][vmid] and sel.slot['sd_card'][vmid]:
print(' -s {},passthru,{}/{}/{} \\'.format(sel.slot["sd_card"][vmid], sel.bdf["sd_card"][vmid][0:2], \
sel.bdf["sd_card"][vmid][3:5], sel.bdf["sd_card"][vmid][6:7]), file=config)
if sel.bdf['bluetooth'][vmid] and sel.slot['bluetooth'][vmid]:
print(' -s {},passthru,{}/{}/{} \\'.format(sel.slot["bluetooth"][vmid], sel.bdf["bluetooth"][vmid][0:2], \
sel.bdf["bluetooth"][vmid][3:5], sel.bdf["bluetooth"][vmid][6:7]), file=config)
if sel.bdf['wifi'][vmid] and sel.slot['wifi'][vmid]:
if uos_type == "ANDROID":
print(" -s {},passthru,{}/{}/{},keep_gsi \\".format(sel.slot["wifi"][vmid], sel.bdf["wifi"][vmid][0:2], \
sel.bdf["wifi"][vmid][3:5], sel.bdf["wifi"][vmid][6:7]), file=config)
else:
print(" -s {},passthru,{}/{}/{} \\".format(sel.slot["wifi"][vmid], sel.bdf["wifi"][vmid][0:2], \
sel.bdf["wifi"][vmid][3:5], sel.bdf["wifi"][vmid][6:7]), file=config)
if sel.bdf['ipu'][vmid] or sel.bdf['ipu_i2c'][vmid]:
print(" $boot_ipu_option \\", file=config)
if sel.bdf['ethernet'][vmid] and sel.slot['ethernet'][vmid]:
if vmid in dm["enable_ptm"] and dm["enable_ptm"][vmid] == 'y':
print(" -s {},passthru,{}/{}/{},enable_ptm \\".format(sel.slot["ethernet"][vmid], sel.bdf["ethernet"][vmid][0:2], \
sel.bdf["ethernet"][vmid][3:5], sel.bdf["ethernet"][vmid][6:7]), file=config)
else:
print(" -s {},passthru,{}/{}/{} \\".format(sel.slot["ethernet"][vmid], sel.bdf["ethernet"][vmid][0:2], \
sel.bdf["ethernet"][vmid][3:5], sel.bdf["ethernet"][vmid][6:7]), file=config)
if sel.bdf['sata'] and sel.slot["sata"][vmid]:
print(" -s {},passthru,{}/{}/{} \\".format(sel.slot["sata"][vmid], sel.bdf["sata"][vmid][0:2], \
sel.bdf["sata"][vmid][3:5], sel.bdf["sata"][vmid][6:7]), file=config)
if sel.bdf['nvme'] and sel.slot["nvme"][vmid]:
print(" -s {},passthru,{}/{}/{} \\".format(sel.slot["nvme"][vmid], sel.bdf["nvme"][vmid][0:2], \
sel.bdf["nvme"][vmid][3:5], sel.bdf["nvme"][vmid][6:7]), file=config)
def vboot_arg_set(dm, vmid, config):
"""
Set the argument of vbootloader
:param dm: the dictionary of argument for acrn-dm
:param vmid: ID of the vm
:param config: it is a file pointer to write vboot loader information
:return: None
"""
# TODO: Support to generate '-k' xml config from webUI and to parse it
if dm['vbootloader'][vmid] == "ovmf":
print(" --ovmf /usr/share/acrn/bios/OVMF.fd \\", file=config)
elif dm['vbootloader'][vmid] == "vsbl":
print(" $boot_image_option \\",file=config)
def xhci_args_set(dm, vmid, config):
# usb_xhci set, the value is string
if dm['xhci'][vmid]:
print(" -s {},xhci,{} \\".format(
launch_cfg_lib.virtual_dev_slot("xhci"), dm['xhci'][vmid]), file=config)
def shm_arg_set(dm, vmid, config):
if dm['shm_enabled'] == "n":
return
for shm_region in dm["shm_regions"][vmid]:
print(" -s {},ivshmem,{} \\".format(
launch_cfg_lib.virtual_dev_slot("shm_region_{}".format(shm_region)), shm_region), file=config)
def virtio_args_set(dm, virt_io, vmid, config):
# virtio-input set, the value type is a list
for input_val in virt_io['input'][vmid]:
if input_val:
print(" -s {},virtio-input,{} \\".format(
launch_cfg_lib.virtual_dev_slot("virtio-input{}".format(input_val)), input_val), file=config)
# virtio-blk set, the value type is a list
i = 0
for mount_flag in launch_cfg_lib.MOUNT_FLAG_DIC[vmid]:
blk = virt_io['block'][vmid][i]
if not mount_flag:
if blk:
rootfs_img = blk.strip(':')
print(" -s {},virtio-blk,{} \\".format(launch_cfg_lib.virtual_dev_slot("virtio-blk{}".format(blk)), rootfs_img), file=config)
i += 1
continue
rootfs_img = blk.split(':')[1].strip(':')
print(" -s {},virtio-blk,/data{}/{} \\".format(launch_cfg_lib.virtual_dev_slot("blk_mount_{}".format(i)), i, rootfs_img), file=config)
i += 1
# virtio-net set, the value type is a list
for net in virt_io['network'][vmid]:
if net:
print(" -s {},virtio-net,tap_{} \\".format(launch_cfg_lib.virtual_dev_slot("virtio-net{}".format(net)), net), file=config)
# virtio-console set, the value type is a string
if virt_io['console'][vmid]:
print(" -s {},virtio-console,{} \\".format(
launch_cfg_lib.virtual_dev_slot("virtio-console"),
virt_io['console'][vmid]), file=config)
def get_cpu_affinity_list(cpu_affinity, vmid):
pcpu_id_list = ''
for uos_id,cpus in cpu_affinity.items():
if vmid == uos_id:
pcpu_id_list = [id for id in list(cpu_affinity[uos_id]) if id != None]
return pcpu_id_list
def pcpu_arg_set(dm, vmid, config):
if dm['cpu_sharing'] == "SCHED_NOOP":
return
pcpu_id_list = get_cpu_affinity_list(dm["cpu_affinity"], vmid)
if pcpu_id_list:
print(" --cpu_affinity {} \\".format(','.join(pcpu_id_list)), file=config)
def dm_arg_set(names, sel, virt_io, dm, vmid, config):
uos_type = names['uos_types'][vmid]
board_name = names['board_name']
boot_image_type(dm, vmid, config)
# uuid get
sos_vmid = launch_cfg_lib.get_sos_vmid()
scenario_uuid = launch_cfg_lib.get_scenario_uuid(vmid, sos_vmid)
# clearlinux/android/alios
print('acrn-dm -A -m $mem_size -s 0:0,hostbridge -U {} \\'.format(scenario_uuid), file=config)
if launch_cfg_lib.is_linux_like(uos_type) or uos_type in ("ANDROID", "ALIOS"):
if uos_type in ("ANDROID", "ALIOS"):
print(' $npk_virt \\', file=config)
print(" -s {},virtio-rpmb \\".format(launch_cfg_lib.virtual_dev_slot("virtio-rpmb")), file=config)
print(" --enable_trusty \\", file=config)
# mac_seed
print(" --mac_seed $mac_seed \\", file=config)
if dm['rtos_type'][vmid] != "no":
if virt_io:
print(" --virtio_poll 1000000 \\", file=config)
if dm['rtos_type'][vmid] == "Soft RT":
print(" --rtvm \\", file=config)
if dm['rtos_type'][vmid] == "Hard RT":
print(" --lapic_pt \\", file=config)
# windows
if uos_type == "WINDOWS":
print(" --windows \\", file=config)
# pm_channel set
if dm['pm_channel'][vmid] and dm['pm_channel'][vmid] != None:
pm_key = dm['pm_channel'][vmid]
pm_vuart = "--pm_notify_channel uart"
if vmid in dm["allow_trigger_s5"] and dm["allow_trigger_s5"][vmid] == 'y':
pm_vuart = pm_vuart + ",allow_trigger_s5 "
else:
pm_vuart = pm_vuart + " "
if pm_key == "vuart1(tty)":
vuart_base = launch_cfg_lib.get_vuart1_from_scenario(sos_vmid + vmid)
if vuart_base == "INVALID_COM_BASE":
err_key = "uos:id={}:poweroff_channel".format(vmid)
launch_cfg_lib.ERR_LIST[err_key] = "vuart1 of VM{} in scenario file should select 'SOS_COM2_BASE'".format(sos_vmid + vmid)
return
scenario_cfg_lib.get_sos_vuart_settings()
print(" {} \\".format(pm_vuart + launch_cfg_lib.PM_CHANNEL_DIC[pm_key] + scenario_cfg_lib.SOS_UART1_VALID_NUM), file=config)
elif pm_key == "vuart1(pty)":
print(" {} \\".format(pm_vuart + launch_cfg_lib.PM_CHANNEL_DIC[pm_key]), file=config)
else:
print(" {} \\".format(launch_cfg_lib.PM_CHANNEL_DIC[pm_key]), file=config)
# set logger_setting for all VMs
print(" $logger_setting \\", file=config)
# XHCI args set
xhci_args_set(dm, vmid, config)
# VIRTIO args set
virtio_args_set(dm, virt_io, vmid, config)
# GVT args set
gvt_arg_set(dm, vmid, uos_type, config)
# vbootloader setting
vboot_arg_set(dm, vmid, config)
# pcpu-list args set
pcpu_arg_set(dm, vmid, config)
# shm regions args set
shm_arg_set(dm, vmid, config)
# ssram set
ssram_enabled = 'n'
try:
ssram_enabled = common.get_hv_item_tag(common.SCENARIO_INFO_FILE, "FEATURES", "SSRAM", "SSRAM_ENABLED")
except:
pass
if uos_type == "PREEMPT-RT LINUX" and ssram_enabled == 'y':
print(" --ssram \\", file=config)
for value in sel.bdf.values():
if value[vmid]:
print(" $intr_storm_monitor \\", file=config)
break
if uos_type != "PREEMPT-RT LINUX":
print(" -s 31:0,lpc \\", file=config)
# redirect console
if dm['vuart0'][vmid] == "Enable":
print(" -l com1,stdio \\", file=config)
if launch_cfg_lib.is_linux_like(uos_type) or uos_type in ("ANDROID", "ALIOS"):
if board_name == "apl-mrb":
print(" -i /run/acrn/ioc_$vm_name,0x20 \\", file=config)
print(" -l com2,/run/acrn/ioc_$vm_name \\", file=config)
if not is_nuc_whl_linux(names, vmid):
print(" -s {},wdt-i6300esb \\".format(launch_cfg_lib.virtual_dev_slot("wdt-i6300esb")), file=config)
set_dm_pt(names, sel, vmid, config, dm)
if dm['console_vuart'][vmid] == "Enable":
print(" -s {},uart,vuart_idx:0 \\".format(launch_cfg_lib.virtual_dev_slot("console_vuart")), file=config)
for vuart_id in dm["communication_vuarts"][vmid]:
if not vuart_id:
break
print(" -s {},uart,vuart_idx:{} \\".format(
launch_cfg_lib.virtual_dev_slot("communication_vuart_{}".format(vuart_id)), vuart_id), file=config)
print(" $vm_name", file=config)
print("}", file=config)
def gen(names, pt_sel, virt_io, dm, vmid, config):
board_name = names['board_name']
uos_type = names['uos_types'][vmid]
# passthrough bdf/vpid dictionay
pt.gen_pt_head(names, dm, pt_sel, vmid, config)
# gen launch header
launch_begin(names, virt_io, vmid, config)
tap_uos_net(names, virt_io, vmid, config)
# passthrough device
pt.gen_pt(names, dm, pt_sel, vmid, config)
wa_usage(uos_type, config)
mem_size_set(dm, vmid, config)
interrupt_storm(pt_sel, config)
log_level_set(uos_type, config)
# gen acrn-dm args
dm_arg_set(names, pt_sel, virt_io, dm, vmid, config)
# gen launch end
launch_end(names, dm, virt_io, vmid, config)
| 40.565029 | 144 | 0.5858 |
import scenario_cfg_lib
import launch_cfg_lib
import common
import pt
def is_nuc_whl_linux(names, vmid):
uos_type = names['uos_types'][vmid]
board_name = names['board_name']
if launch_cfg_lib.is_linux_like(uos_type) and board_name not in ("apl-mrb", "apl-up2"):
return True
return False
def is_mount_needed(virt_io, vmid):
if True in launch_cfg_lib.MOUNT_FLAG_DIC[vmid]:
return True
return False
def tap_uos_net(names, virt_io, vmid, config):
uos_type = names['uos_types'][vmid]
board_name = names['board_name']
vm_name = common.undline_name(uos_type).lower()
if launch_cfg_lib.is_linux_like(uos_type) or uos_type in ("ANDROID", "ALIOS"):
i = 0
for mount_flag in launch_cfg_lib.MOUNT_FLAG_DIC[vmid]:
if not mount_flag:
i += 1
continue
blk = virt_io['block'][vmid][i]
rootfs_img = blk.split(':')[1].strip(':')
print('if [ ! -f "/data{}/{}" ]; then'.format(i, rootfs_img), file=config)
print(' echo "no /data{}/{}, exit"'.format(i, rootfs_img), file=config)
print(" exit", file=config)
print("fi", file=config)
print("", file=config)
i += 1
print("#vm-name used to generate uos-mac address", file=config)
print("mac=$(cat /sys/class/net/e*/address)", file=config)
print("vm_name=post_vm_id$1", file=config)
print("mac_seed=${mac:0:17}-${vm_name}", file=config)
print("", file=config)
for net in virt_io['network'][vmid]:
if net:
net_name = net
if ',' in net:
net_name = net.split(',')[0]
print("tap_net tap_{}".format(net_name), file=config)
print("#check if the vm is running or not", file=config)
print("vm_ps=$(pgrep -a -f acrn-dm)", file=config)
print('result=$(echo $vm_ps | grep -w "${vm_name}")', file=config)
print('if [[ "$result" != "" ]]; then', file=config)
print(' echo "$vm_name is running, can\'t create twice!"', file=config)
print(" exit", file=config)
print("fi", file=config)
print("", file=config)
def off_line_cpus(args, vmid, uos_type, config):
pcpu_id_list = get_cpu_affinity_list(args["cpu_affinity"], vmid)
if not pcpu_id_list:
sos_vmid = launch_cfg_lib.get_sos_vmid()
cpu_affinity = common.get_leaf_tag_map(common.SCENARIO_INFO_FILE, "cpu_affinity", "pcpu_id")
pcpu_id_list = get_cpu_affinity_list(cpu_affinity, sos_vmid+vmid)
if not pcpu_id_list:
key = "scenario config error"
launch_cfg_lib.ERR_LIST[key] = "No available cpu to offline and pass it to vm {}".format(vmid)
print("# offline pinned vCPUs from SOS before launch UOS", file=config)
print('cpu_path="/sys/devices/system/cpu"', file=config)
print("for i in `ls ${cpu_path}`; do", file=config)
print(" for j in {}; do".format(' '.join([str(i) for i in pcpu_id_list])), file=config)
print(' if [ "cpu"$j = $i ]; then', file=config)
print(' online=`cat ${cpu_path}/$i/online`', file=config)
print(' idx=`echo $i | tr -cd "[1-99]"`', file=config)
print(' echo $i online=$online', file=config)
print(' if [ "$online" = "1" ]; then', file=config)
print(" echo 0 > ${cpu_path}/$i/online", file=config)
print(" online=`cat ${cpu_path}/$i/online`", file=config)
print(" # during boot time, cpu hotplug may be disabled by pci_device_probe during a pci module insmod", file=config)
print(' while [ "$online" = "1" ]; do', file=config)
print(" sleep 1", file=config)
print(" echo 0 > ${cpu_path}/$i/online", file=config)
print(" online=`cat ${cpu_path}/$i/online`", file=config)
print(" done", file=config)
print(" echo $idx > /sys/devices/virtual/misc/acrn_hsm/remove_cpu", file=config)
print(" fi", file=config)
print(" fi", file=config)
print(" done", file=config)
print("done", file=config)
print("", file=config)
def run_container(board_name, uos_type, config):
# the runC.json is store in the path under board name, but for nuc7i7dnb/nuc6cayh/kbl-nuc-i7 is under nuc/
if 'nuc' in board_name:
board_name = 'nuc'
if board_name not in ("apl-mrb", "nuc") or not launch_cfg_lib.is_linux_like(uos_type):
return
print("function run_container()", file=config)
print("{", file=config)
print("vm_name=vm1", file=config)
print('config_src="/usr/share/acrn/samples/{}/runC.json"'.format(board_name), file=config)
print('shell="/usr/share/acrn/conf/add/$vm_name.sh"', file=config)
print('arg_file="/usr/share/acrn/conf/add/$vm_name.args"', file=config)
print('runc_bundle="/usr/share/acrn/conf/add/runc/$vm_name"', file=config)
print('rootfs_dir="/usr/share/acrn/conf/add/runc/rootfs"', file=config)
print('config_dst="$runc_bundle/config.json"', file=config)
print("", file=config)
print("", file=config)
print("input=$(runc list -f table | awk '{print $1}''{print $3}')", file=config)
print("arr=(${input// / })", file=config)
print("", file=config)
print("for((i=0;i<${#arr[@]};i++))", file=config)
print("do", file=config)
print(' if [ "$vm_name" = "${arr[$i]}" ]; then', file=config)
print(' if [ "running" = "${arr[$i+1]}" ]; then', file=config)
print(' echo "runC instance ${arr[$i]} is running"', file=config)
print(" exit", file=config)
print(" else", file=config)
print(" runc kill ${arr[$i]}", file=config)
print(" runc delete ${arr[$i]}", file=config)
print(" fi", file=config)
print(" fi", file=config)
print("done", file=config)
print("vmsts=$(acrnctl list)", file=config)
print("vms=(${vmsts// / })", file=config)
print("for((i=0;i<${#vms[@]};i++))", file=config)
print("do", file=config)
print(' if [ "$vm_name" = "${vms[$i]}" ]; then', file=config)
print(' if [ "stopped" != "${vms[$i+1]}" ]; then', file=config)
print(' echo "Uos ${vms[$i]} ${vms[$i+1]}"', file=config)
print(" acrnctl stop ${vms[$i]}", file=config)
print(" fi", file=config)
print(" fi", file=config)
print("done", file=config)
dst_str = """ cp "$config_src" "$config_dst"
args=$(sed '{s/-C//g;s/^[ \\t]*//g;s/^/\\"/;s/ /\\",\\"/g;s/$/\\"/}' ${arg_file})
sed -i "s|\\"sh\\"|\\"$shell\\", $args|" $config_dst"""
print('', file=config)
print('if [ ! -f "$shell" ]; then', file=config)
print(' echo "Pls add the vm at first!"', file=config)
print(' exit', file=config)
print('fi', file=config)
print('', file=config)
print('if [ ! -f "$arg_file" ]; then', file=config)
print(' echo "Pls add the vm args!"', file=config)
print(' exit', file=config)
print('fi', file=config)
print('', file=config)
print('if [ ! -d "$rootfs_dir" ]; then', file=config)
print(' mkdir -p "$rootfs_dir"', file=config)
print('fi', file=config)
print('if [ ! -d "$runc_bundle" ]; then', file=config)
print(' mkdir -p "$runc_bundle"', file=config)
print('fi', file=config)
print('if [ ! -f "$config_dst" ]; then', file=config)
print('{}'.format(dst_str), file=config)
print('fi', file=config)
print('runc run --bundle $runc_bundle -d $vm_name', file=config)
print('echo "The runC container is running in backgroud"', file=config)
print('echo "\'#runc exec <vmname> bash\' to login the container bash"', file=config)
print('exit', file=config)
print('}', file=config)
print('', file=config)
def boot_image_type(args, vmid, config):
if not args['vbootloader'][vmid] or (args['vbootloader'][vmid] and args['vbootloader'][vmid] != "vsbl"):
return
print('boot_dev_flag=",b"', file=config)
print("if [ $4 == 1 ];then", file=config)
print(' boot_image_option="--vsbl /usr/share/acrn/bios/VSBL_debug.bin"', file=config)
print("else", file=config)
print(' boot_image_option="--vsbl /usr/share/acrn/bios/VSBL.bin"', file=config)
print("fi", file=config)
print("", file=config)
def interrupt_storm(pt_sel, config):
if not pt_sel:
return
# TODO: --intr_monitor should be configurable by user
print("#interrupt storm monitor for pass-through devices, params order:", file=config)
print("#threshold/s,probe-period(s),intr-inject-delay-time(ms),delay-duration(ms)", file=config)
print('intr_storm_monitor="--intr_monitor 10000,10,1,100"', file=config)
print("", file=config)
def gvt_arg_set(dm, vmid, uos_type, config):
gvt_args = dm['gvt_args'][vmid]
if gvt_args == "gvtd":
bus = int(launch_cfg_lib.GPU_BDF.split(':')[0], 16)
dev = int(launch_cfg_lib.GPU_BDF.split('.')[0].split(':')[1], 16)
fun = int(launch_cfg_lib.GPU_BDF.split('.')[1], 16)
print(' -s 2,passthru,{}/{}/{},gpu \\'.format(bus, dev, fun), file=config)
elif gvt_args:
print(' -s 2,pci-gvt -G "$2" \\', file=config)
def log_level_set(uos_type, config):
print("#logger_setting, format: logger_name,level; like following", file=config)
print('logger_setting="--logger_setting console,level=4;kmsg,level=3;disk,level=5"', file=config)
print("", file=config)
def tap_network(virt_io, vmid, config):
none_i = 0
tap_net_list = virt_io['network'][vmid]
for net in tap_net_list:
if net == None:
none_i += 1
tap_net_num = len(tap_net_list) - none_i
if tap_net_num >= 1:
print("function tap_net() {", file=config)
print("# create a unique tap device for each VM", file=config)
print("tap=$1", file=config)
print('tap_exist=$(ip a | grep "$tap" | awk \'{print $1}\')', file=config)
print('if [ "$tap_exist"x != "x" ]; then', file=config)
print(' echo "tap device existed, reuse $tap"', file=config)
print("else", file=config)
print(" ip tuntap add dev $tap mode tap", file=config)
print("fi", file=config)
print("", file=config)
print("# if acrn-br0 exists, add VM's unique tap device under it", file=config)
print("br_exist=$(ip a | grep acrn-br0 | awk '{print $1}')", file=config)
print('if [ "$br_exist"x != "x" -a "$tap_exist"x = "x" ]; then', file=config)
print(' echo "acrn-br0 bridge aleady exists, adding new tap device to it..."', file=config)
print(' ip link set "$tap" master acrn-br0', file=config)
print(' ip link set dev "$tap" down', file=config)
print(' ip link set dev "$tap" up', file=config)
print("fi", file=config)
print("}", file=config)
print("", file=config)
def launch_begin(names, virt_io, vmid, config):
board_name = names['board_name']
uos_type = names['uos_types'][vmid]
launch_uos = common.undline_name(uos_type).lower()
tap_network(virt_io, vmid, config)
run_container(board_name, uos_type, config)
print("function launch_{}()".format(launch_uos), file=config)
print("{", file=config)
def wa_usage(uos_type, config):
if uos_type in ("ANDROID", "ALIOS"):
print("# WA for USB role switch hang issue, disable runtime PM of xHCI device", file=config)
print("echo on > /sys/devices/pci0000:00/0000:00:15.0/power/control", file=config)
print("", file=config)
def mem_size_set(args, vmid, config):
mem_size = args['mem_size'][vmid]
print("mem_size={}M".format(mem_size), file=config)
def uos_launch(names, args, virt_io, vmid, config):
gvt_args = args['gvt_args'][vmid]
uos_type = names['uos_types'][vmid]
launch_uos = common.undline_name(uos_type).lower()
board_name = names['board_name']
if 'nuc' in board_name:
board_name = 'nuc'
if uos_type == "CLEARLINUX" and board_name in ("apl-mrb", "nuc"):
print('if [ "$1" = "-C" ];then', file=config)
print(' if [ $(hostname) = "runc" ]; then', file=config)
print(' echo "Already in container exit!"', file=config)
print(" exit", file=config)
print(" fi", file=config)
print(' echo "runc_container"', file=config)
print(" run_container", file=config)
if board_name == "apl-mrb":
print(" exit", file=config)
print("fi", file=config)
if is_mount_needed(virt_io, vmid):
print("", file=config)
if gvt_args == "gvtd" or not gvt_args:
print('launch_{} {} "{}" $debug'.format(launch_uos, vmid, vmid), file=config)
else:
print('launch_{} {} "{}" "{}" $debug'.format(launch_uos, vmid, gvt_args, vmid), file=config)
print("", file=config)
i = 0
for mount_flag in launch_cfg_lib.MOUNT_FLAG_DIC[vmid]:
if not mount_flag:
i += 1
continue
print("umount /data{}".format(i), file=config)
i += 1
else:
print("else", file=config)
if gvt_args == "gvtd" or not gvt_args:
print(' launch_{} {}'.format(launch_uos, vmid), file=config)
elif gvt_args:
print(' launch_{} {} "{}"'.format(launch_uos, vmid, gvt_args), file=config)
print("fi", file=config)
return
elif not is_mount_needed(virt_io, vmid):
if gvt_args == "gvtd" or not gvt_args:
print('launch_{} {}'.format(launch_uos, vmid), file=config)
else:
print('launch_{} {} "{}"'.format(launch_uos, vmid, gvt_args), file=config)
else:
print("", file=config)
if gvt_args == "gvtd" or not gvt_args:
print('launch_{} {} "{}" $debug'.format(launch_uos, vmid, vmid), file=config)
else:
print('launch_{} {} "{}" "{}" $debug'.format(launch_uos, vmid, gvt_args, vmid), file=config)
print("", file=config)
i = 0
for mount_flag in launch_cfg_lib.MOUNT_FLAG_DIC[vmid]:
if not mount_flag:
i += 1
continue
print("umount /data{}".format(i), file=config)
i += 1
def launch_end(names, args, virt_io, vmid, config):
board_name = names['board_name']
uos_type = names['uos_types'][vmid]
mem_size = args["mem_size"][vmid]
if uos_type in ("CLEARLINUX", "ANDROID", "ALIOS") and not is_nuc_whl_linux(names, vmid):
print("debug=0", file=config)
print("", file=config)
print('while getopts "hdC" opt', file=config)
print("do", file=config)
print(" case $opt in", file=config)
print(" d) debug=1", file=config)
print(" ;;", file=config)
print(" C)", file=config)
print(" ;;", file=config)
print(" h) help", file=config)
print(" exit 1", file=config)
print(" ;;", file=config)
print(" ?) help", file=config)
print(" exit 1", file=config)
print(" ;;", file=config)
print(" esac", file=config)
print("done", file=config)
print("", file=config)
if is_mount_needed(virt_io, vmid):
i = 0
for mount_flag in launch_cfg_lib.MOUNT_FLAG_DIC[vmid]:
if not mount_flag:
i += 1
continue
blk = virt_io['block'][vmid][i]
root_fs = blk.split(':')[0]
print('if [ ! -b "{}" ]; then'.format(root_fs), file=config)
print(' echo "no {} data partition, exit"'.format(root_fs), file=config)
print(" exit", file=config)
print("fi", file=config)
print("mkdir -p /data{}".format(i), file=config)
print("mount {} /data{}".format(root_fs, i), file=config)
print("", file=config)
i += 1
sos_vmid = launch_cfg_lib.get_sos_vmid()
if args['cpu_sharing'] == "SCHED_NOOP" or common.VM_TYPES[vmid+sos_vmid] == "POST_RT_VM":
off_line_cpus(args, vmid, uos_type, config)
uos_launch(names, args, virt_io, vmid, config)
def set_dm_pt(names, sel, vmid, config, dm):
uos_type = names['uos_types'][vmid]
if sel.bdf['usb_xdci'][vmid] and sel.slot['usb_xdci'][vmid]:
sub_attr = ''
if uos_type == "WINDOWS":
sub_attr = ',d3hot_reset'
print(' -s {},passthru,{}/{}/{}{} \\'.format(sel.slot["usb_xdci"][vmid], sel.bdf["usb_xdci"][vmid][0:2],\
sel.bdf["usb_xdci"][vmid][3:5], sel.bdf["usb_xdci"][vmid][6:7], sub_attr), file=config)
if sel.bdf['audio'][vmid]:
print(" $boot_audio_option \\", file=config)
if sel.bdf['cse'][vmid] and sel.slot['cse'][vmid]:
print(" $boot_cse_option \\", file=config)
if sel.bdf["sd_card"][vmid] and sel.slot['sd_card'][vmid]:
print(' -s {},passthru,{}/{}/{} \\'.format(sel.slot["sd_card"][vmid], sel.bdf["sd_card"][vmid][0:2], \
sel.bdf["sd_card"][vmid][3:5], sel.bdf["sd_card"][vmid][6:7]), file=config)
if sel.bdf['bluetooth'][vmid] and sel.slot['bluetooth'][vmid]:
print(' -s {},passthru,{}/{}/{} \\'.format(sel.slot["bluetooth"][vmid], sel.bdf["bluetooth"][vmid][0:2], \
sel.bdf["bluetooth"][vmid][3:5], sel.bdf["bluetooth"][vmid][6:7]), file=config)
if sel.bdf['wifi'][vmid] and sel.slot['wifi'][vmid]:
if uos_type == "ANDROID":
print(" -s {},passthru,{}/{}/{},keep_gsi \\".format(sel.slot["wifi"][vmid], sel.bdf["wifi"][vmid][0:2], \
sel.bdf["wifi"][vmid][3:5], sel.bdf["wifi"][vmid][6:7]), file=config)
else:
print(" -s {},passthru,{}/{}/{} \\".format(sel.slot["wifi"][vmid], sel.bdf["wifi"][vmid][0:2], \
sel.bdf["wifi"][vmid][3:5], sel.bdf["wifi"][vmid][6:7]), file=config)
if sel.bdf['ipu'][vmid] or sel.bdf['ipu_i2c'][vmid]:
print(" $boot_ipu_option \\", file=config)
if sel.bdf['ethernet'][vmid] and sel.slot['ethernet'][vmid]:
if vmid in dm["enable_ptm"] and dm["enable_ptm"][vmid] == 'y':
print(" -s {},passthru,{}/{}/{},enable_ptm \\".format(sel.slot["ethernet"][vmid], sel.bdf["ethernet"][vmid][0:2], \
sel.bdf["ethernet"][vmid][3:5], sel.bdf["ethernet"][vmid][6:7]), file=config)
else:
print(" -s {},passthru,{}/{}/{} \\".format(sel.slot["ethernet"][vmid], sel.bdf["ethernet"][vmid][0:2], \
sel.bdf["ethernet"][vmid][3:5], sel.bdf["ethernet"][vmid][6:7]), file=config)
if sel.bdf['sata'] and sel.slot["sata"][vmid]:
print(" -s {},passthru,{}/{}/{} \\".format(sel.slot["sata"][vmid], sel.bdf["sata"][vmid][0:2], \
sel.bdf["sata"][vmid][3:5], sel.bdf["sata"][vmid][6:7]), file=config)
if sel.bdf['nvme'] and sel.slot["nvme"][vmid]:
print(" -s {},passthru,{}/{}/{} \\".format(sel.slot["nvme"][vmid], sel.bdf["nvme"][vmid][0:2], \
sel.bdf["nvme"][vmid][3:5], sel.bdf["nvme"][vmid][6:7]), file=config)
def vboot_arg_set(dm, vmid, config):
if dm['vbootloader'][vmid] == "ovmf":
print(" --ovmf /usr/share/acrn/bios/OVMF.fd \\", file=config)
elif dm['vbootloader'][vmid] == "vsbl":
print(" $boot_image_option \\",file=config)
def xhci_args_set(dm, vmid, config):
if dm['xhci'][vmid]:
print(" -s {},xhci,{} \\".format(
launch_cfg_lib.virtual_dev_slot("xhci"), dm['xhci'][vmid]), file=config)
def shm_arg_set(dm, vmid, config):
if dm['shm_enabled'] == "n":
return
for shm_region in dm["shm_regions"][vmid]:
print(" -s {},ivshmem,{} \\".format(
launch_cfg_lib.virtual_dev_slot("shm_region_{}".format(shm_region)), shm_region), file=config)
def virtio_args_set(dm, virt_io, vmid, config):
for input_val in virt_io['input'][vmid]:
if input_val:
print(" -s {},virtio-input,{} \\".format(
launch_cfg_lib.virtual_dev_slot("virtio-input{}".format(input_val)), input_val), file=config)
i = 0
for mount_flag in launch_cfg_lib.MOUNT_FLAG_DIC[vmid]:
blk = virt_io['block'][vmid][i]
if not mount_flag:
if blk:
rootfs_img = blk.strip(':')
print(" -s {},virtio-blk,{} \\".format(launch_cfg_lib.virtual_dev_slot("virtio-blk{}".format(blk)), rootfs_img), file=config)
i += 1
continue
rootfs_img = blk.split(':')[1].strip(':')
print(" -s {},virtio-blk,/data{}/{} \\".format(launch_cfg_lib.virtual_dev_slot("blk_mount_{}".format(i)), i, rootfs_img), file=config)
i += 1
for net in virt_io['network'][vmid]:
if net:
print(" -s {},virtio-net,tap_{} \\".format(launch_cfg_lib.virtual_dev_slot("virtio-net{}".format(net)), net), file=config)
if virt_io['console'][vmid]:
print(" -s {},virtio-console,{} \\".format(
launch_cfg_lib.virtual_dev_slot("virtio-console"),
virt_io['console'][vmid]), file=config)
def get_cpu_affinity_list(cpu_affinity, vmid):
pcpu_id_list = ''
for uos_id,cpus in cpu_affinity.items():
if vmid == uos_id:
pcpu_id_list = [id for id in list(cpu_affinity[uos_id]) if id != None]
return pcpu_id_list
def pcpu_arg_set(dm, vmid, config):
if dm['cpu_sharing'] == "SCHED_NOOP":
return
pcpu_id_list = get_cpu_affinity_list(dm["cpu_affinity"], vmid)
if pcpu_id_list:
print(" --cpu_affinity {} \\".format(','.join(pcpu_id_list)), file=config)
def dm_arg_set(names, sel, virt_io, dm, vmid, config):
uos_type = names['uos_types'][vmid]
board_name = names['board_name']
boot_image_type(dm, vmid, config)
sos_vmid = launch_cfg_lib.get_sos_vmid()
scenario_uuid = launch_cfg_lib.get_scenario_uuid(vmid, sos_vmid)
print('acrn-dm -A -m $mem_size -s 0:0,hostbridge -U {} \\'.format(scenario_uuid), file=config)
if launch_cfg_lib.is_linux_like(uos_type) or uos_type in ("ANDROID", "ALIOS"):
if uos_type in ("ANDROID", "ALIOS"):
print(' $npk_virt \\', file=config)
print(" -s {},virtio-rpmb \\".format(launch_cfg_lib.virtual_dev_slot("virtio-rpmb")), file=config)
print(" --enable_trusty \\", file=config)
print(" --mac_seed $mac_seed \\", file=config)
if dm['rtos_type'][vmid] != "no":
if virt_io:
print(" --virtio_poll 1000000 \\", file=config)
if dm['rtos_type'][vmid] == "Soft RT":
print(" --rtvm \\", file=config)
if dm['rtos_type'][vmid] == "Hard RT":
print(" --lapic_pt \\", file=config)
if uos_type == "WINDOWS":
print(" --windows \\", file=config)
if dm['pm_channel'][vmid] and dm['pm_channel'][vmid] != None:
pm_key = dm['pm_channel'][vmid]
pm_vuart = "--pm_notify_channel uart"
if vmid in dm["allow_trigger_s5"] and dm["allow_trigger_s5"][vmid] == 'y':
pm_vuart = pm_vuart + ",allow_trigger_s5 "
else:
pm_vuart = pm_vuart + " "
if pm_key == "vuart1(tty)":
vuart_base = launch_cfg_lib.get_vuart1_from_scenario(sos_vmid + vmid)
if vuart_base == "INVALID_COM_BASE":
err_key = "uos:id={}:poweroff_channel".format(vmid)
launch_cfg_lib.ERR_LIST[err_key] = "vuart1 of VM{} in scenario file should select 'SOS_COM2_BASE'".format(sos_vmid + vmid)
return
scenario_cfg_lib.get_sos_vuart_settings()
print(" {} \\".format(pm_vuart + launch_cfg_lib.PM_CHANNEL_DIC[pm_key] + scenario_cfg_lib.SOS_UART1_VALID_NUM), file=config)
elif pm_key == "vuart1(pty)":
print(" {} \\".format(pm_vuart + launch_cfg_lib.PM_CHANNEL_DIC[pm_key]), file=config)
else:
print(" {} \\".format(launch_cfg_lib.PM_CHANNEL_DIC[pm_key]), file=config)
print(" $logger_setting \\", file=config)
xhci_args_set(dm, vmid, config)
virtio_args_set(dm, virt_io, vmid, config)
gvt_arg_set(dm, vmid, uos_type, config)
vboot_arg_set(dm, vmid, config)
pcpu_arg_set(dm, vmid, config)
shm_arg_set(dm, vmid, config)
ssram_enabled = 'n'
try:
ssram_enabled = common.get_hv_item_tag(common.SCENARIO_INFO_FILE, "FEATURES", "SSRAM", "SSRAM_ENABLED")
except:
pass
if uos_type == "PREEMPT-RT LINUX" and ssram_enabled == 'y':
print(" --ssram \\", file=config)
for value in sel.bdf.values():
if value[vmid]:
print(" $intr_storm_monitor \\", file=config)
break
if uos_type != "PREEMPT-RT LINUX":
print(" -s 31:0,lpc \\", file=config)
if dm['vuart0'][vmid] == "Enable":
print(" -l com1,stdio \\", file=config)
if launch_cfg_lib.is_linux_like(uos_type) or uos_type in ("ANDROID", "ALIOS"):
if board_name == "apl-mrb":
print(" -i /run/acrn/ioc_$vm_name,0x20 \\", file=config)
print(" -l com2,/run/acrn/ioc_$vm_name \\", file=config)
if not is_nuc_whl_linux(names, vmid):
print(" -s {},wdt-i6300esb \\".format(launch_cfg_lib.virtual_dev_slot("wdt-i6300esb")), file=config)
set_dm_pt(names, sel, vmid, config, dm)
if dm['console_vuart'][vmid] == "Enable":
print(" -s {},uart,vuart_idx:0 \\".format(launch_cfg_lib.virtual_dev_slot("console_vuart")), file=config)
for vuart_id in dm["communication_vuarts"][vmid]:
if not vuart_id:
break
print(" -s {},uart,vuart_idx:{} \\".format(
launch_cfg_lib.virtual_dev_slot("communication_vuart_{}".format(vuart_id)), vuart_id), file=config)
print(" $vm_name", file=config)
print("}", file=config)
def gen(names, pt_sel, virt_io, dm, vmid, config):
board_name = names['board_name']
uos_type = names['uos_types'][vmid]
pt.gen_pt_head(names, dm, pt_sel, vmid, config)
launch_begin(names, virt_io, vmid, config)
tap_uos_net(names, virt_io, vmid, config)
pt.gen_pt(names, dm, pt_sel, vmid, config)
wa_usage(uos_type, config)
mem_size_set(dm, vmid, config)
interrupt_storm(pt_sel, config)
log_level_set(uos_type, config)
dm_arg_set(names, pt_sel, virt_io, dm, vmid, config)
launch_end(names, dm, virt_io, vmid, config)
| true | true |
f71082af93d1c265ed09483c58f606154391284b | 11,088 | py | Python | astro_dynamo/model.py | cwegg/astro-dynamo | 024f8aad8785488e9ae3328095d3d9c53b3e31b0 | [
"MIT"
] | null | null | null | astro_dynamo/model.py | cwegg/astro-dynamo | 024f8aad8785488e9ae3328095d3d9c53b3e31b0 | [
"MIT"
] | null | null | null | astro_dynamo/model.py | cwegg/astro-dynamo | 024f8aad8785488e9ae3328095d3d9c53b3e31b0 | [
"MIT"
] | null | null | null | import math
from typing import List, Union, Tuple
import torch
import torch.nn as nn
from astro_dynamo.snap import SnapShot
from .snaptools import align_bar
def _symmetrize_matrix(x, dim):
"""Symmetrize a tensor along dimension dim"""
return (x + x.flip(dims=[dim])) / 2
class DynamicalModel(nn.Module):
"""DynamicalModels class. This containts a snapshot of the particles, the potentials
in which they move, and the targets to which the model should be fitted.
Attributes:
snap:
Should be a SnapShot whose masses will be optimised
potentials:
The potentials add. If self gravity is not required set self_gravity_update to None.
If self gravity is required then the potential of the snapshot should be in potentials[0]
and self_gravity_update represents how much to update the running average of the density on
each iteration. Default value is 0.2 which is then exponential averages the density with timescale
5 snapshots(=1/0.2).
targets:
A list of targets. Running
model = DynamicalModel(snap, potentials, targets)
current_target_list = model()
will provide an list of theDynamicalModelse targets evaluated with the present model. These are then
typically combined to a loss that pytorch can optimise.
Methods:
forward()
Computes the targets by evaluating them on the current snapshot. Can also be called as DynamicalModel()
integrate(steps=256)
Integrates the model forward by steps. Updates potential the density assocaiates to potential[0]
update_potential()
Recomputes the accelerations from potential[0]. Adjust each snapshots velocity by a factor vc_new/vc_old
resample()
Resamples the snapshot to equal mass particles.
"""
def __init__(self, snap, potentials, targets, self_gravity_update=0.2):
super(DynamicalModel, self).__init__()
self.snap = snap
self.targets = nn.ModuleList(targets)
self.potentials = nn.ModuleList(potentials)
self.self_gravity_update = self_gravity_update
def forward(self):
return [target(self) for target in self.targets]
def integrate(self, steps=256):
with torch.no_grad():
self.snap.leapfrog_steps(potentials=self.potentials, steps=steps)
if self.self_gravity_update is not None:
self.potentials[0].update_density(self.snap.positions,
self.snap.masses.detach(),
fractional_update=self.self_gravity_update)
def update_potential(self, dm_potential=None, update_velocities=True):
with torch.no_grad():
if update_velocities:
old_accelerations = self.snap.get_accelerations(self.potentials,
self.snap.positions)
old_vc = torch.sum(-old_accelerations * self.snap.positions,
dim=-1).sqrt()
self.potentials[0].rho = _symmetrize_matrix(
_symmetrize_matrix(
_symmetrize_matrix(self.potentials[0].rho, 0), 1), 2)
self.potentials[0].grid_accelerations()
if dm_potential is not None:
self.potentials[1] = dm_potential
if update_velocities:
new_accelerations = self.snap.get_accelerations(self.potentials,
self.snap.positions)
new_vc = torch.sum(-new_accelerations * self.snap.positions,
dim=-1).sqrt()
gd = torch.isfinite(new_vc / old_vc) & (new_vc / old_vc > 0)
self.snap.velocities[gd, :] *= (new_vc / old_vc)[gd, None]
align_bar(self.snap)
def resample(self, velocity_perturbation=0.01):
"""Resample the model to equal mass particles.
Note that the snapshot changes and so the parameters of
the model also change in a way that any optimiser that keeps parameter-by-parameter information e.g.
gradients must also be update."""
with torch.no_grad():
self.snap = self.snap.resample(self.potentials,
velocity_perturbation=velocity_perturbation)
align_bar(self.snap)
def vc(self, components=False, r=torch.linspace(0, 9),
phi=torch.linspace(0, math.pi)):
"""Returns (r,vc) the circular velocity of the model in physical units and locations at which it was evaluated.
If components=True then return list containing the vc of each component, otherwise just return the total.
r optionally specifies the physical radii at which to compute vc
phi specifies the azimuths over which to average."""
phi_grid, r_grid = torch.meshgrid(phi, r)
phi_grid, r_grid = phi_grid.flatten(), r_grid.flatten()
pos = torch.stack((r_grid * torch.cos(phi_grid),
r_grid * torch.sin(phi_grid), 0 * phi_grid)).t()
pos = pos.to(device=self.d_scale.device)
pos /= self.d_scale
vc = []
for potential in self.potentials:
device = next(potential.buffers()).device
acc = potential.get_accelerations(pos.to(device=device)).to(
device=pos.device)
vc += [torch.sum(-acc * pos, dim=1).sqrt().reshape(
phi.shape + r.shape).mean(dim=0) * self.v_scale]
if components:
return r, vc
else:
total_vc = vc[0]
for thisvc in vc[1:]:
total_vc = (total_vc ** 2 + thisvc ** 2).sqrt()
return r, total_vc
class MilkyWayModel(DynamicalModel):
def __init__(self, snap: SnapShot, potentials: List[nn.Module],
targets: List[nn.Module],
self_gravity_update: Union[float, torch.Tensor] = 0.2,
bar_angle: Union[float, torch.Tensor] = 27.,
r_0: Union[float, torch.Tensor] = 8.2,
z_0: Union[float, torch.Tensor] = 0.014,
v_scale: Union[float, torch.Tensor] = 240,
d_scale: Union[float, torch.Tensor] = 1.4,
v_sun: Union[List[float], Tuple[float, float, float],
torch.Tensor] = (11.1, 12.24 + 238.0, 7.25)
):
super(MilkyWayModel, self).__init__(snap, potentials, targets,
self_gravity_update)
self.bar_angle = nn.Parameter(torch.as_tensor(bar_angle),
requires_grad=False)
self.r_0 = nn.Parameter(torch.as_tensor(r_0), requires_grad=False)
self.z_0 = nn.Parameter(torch.as_tensor(z_0), requires_grad=False)
self.v_scale = nn.Parameter(torch.as_tensor(v_scale),
requires_grad=False)
self.d_scale = nn.Parameter(torch.as_tensor(d_scale),
requires_grad=False)
self.v_sun = nn.Parameter(torch.as_tensor(v_sun), requires_grad=False)
@property
def m_scale(self) -> torch.tensor:
G = 4.302E-3 # Gravitational constant in astronomical units
return self.d_scale * 1e3 * self.v_scale ** 2 / G
@property
def t_scale(self) -> torch.tensor:
"""1 iu in time in Gyr"""
return self.d_scale / self.v_scale * 0.977813106 # note that 1km/s is almost 1kpc/Gyr
@property
def xyz(self) -> torch.tensor:
"""Return position of particles in relative to the Sun in cartesian coordinates with units kpc
"""
ddtor = math.pi / 180.
ang = self.bar_angle * ddtor
pos = self.snap.positions
xyz = torch.zeros_like(pos)
inplane_gc_distance = (self.r_0 ** 2 - self.z_0 ** 2).sqrt()
xyz[:, 0] = (pos[:, 0] * torch.cos(-ang) - pos[:, 1] * torch.sin(
-ang)) * self.d_scale + inplane_gc_distance
xyz[:, 1] = (pos[:, 0] * torch.sin(-ang) + pos[:, 1] * torch.cos(
-ang)) * self.d_scale
xyz[:, 2] = pos[:, 2] * self.d_scale - self.z_0
return xyz
@property
def l_b_mu(self) -> torch.tensor:
"""Return array of particles in galactic (l,b,mu) coordinates. (l,b) in degrees. mu is distance modulus"""
xyz = self.xyz
l_b_mu = torch.zeros_like(xyz)
d = (xyz[:, 0] ** 2 + xyz[:, 1] ** 2 + xyz[:, 2] ** 2).sqrt()
l_b_mu[:, 0] = torch.atan2(xyz[:, 1], xyz[:, 0]) * 180 / math.pi
b_offset = torch.asin(
self.z_0 / self.r_0) # the GC has z = -z_0, rotate b coordinate so this is at l,b=(0,0)
l_b_mu[:, 1] = (torch.asin(xyz[:, 2] / d) + b_offset) * 180 / math.pi
l_b_mu[:, 2] = 5 * (100 * d).log10()
return l_b_mu
@property
def masses(self) -> torch.tensor:
return self.snap.masses * self.m_scale
@property
def omega(self) -> torch.tensor:
return self.snap.omega * self.v_scale / self.d_scale
@omega.setter
def omega(self, omega: float):
self.snap.omega = omega / self.v_scale * self.d_scale
@property
def uvw(self) -> torch.tensor:
"""Return UVW velocities.
"""
ddtor = math.pi / 180.
ang = self.bar_angle * ddtor
vxyz = torch.zeros_like(self.snap.positions)
# sun moves at Vsun[0] towards galactic center i.e. other stars are moving away towards larger x
vel = self.snap.velocities * self.v_scale
vxyz[:, 0] = (vel[:, 0] * torch.cos(-ang) - vel[:, 1] * torch.sin(-ang)) + self.v_sun[0]
# sun moves at Vsun[1] in direction of rotation, other stars are going slower than (0,-Vc,0)
vxyz[:, 1] = (vel[:, 0] * torch.sin(-ang) + vel[:, 1] * torch.cos(-ang)) - self.v_sun[1]
# sun is moving towards ngp i.e. other stars on average move at negative vz
vxyz[:, 2] = vel[:, 2] - self.v_sun[2]
return vxyz
@property
def vr(self) -> torch.tensor:
"""Return array of particles radial velocities in [km/s]"""
xyz = self.xyz
vxyz = self.uvw
r = xyz.norm(dim=-1)
vr = (xyz * vxyz).sum(dim=-1) / r
return vr
@property
def mul_mub(self) -> torch.tensor:
"""Return proper motions of particles in [mas/yr] in (l, b).
Proper motion in l is (rate of change of l)*cos(b)"""
xyz = self.xyz
vxyz = self.uvw
r = xyz.norm(dim=-1)
rxy = (xyz[:, 0] ** 2 + xyz[:, 1] ** 2).sqrt()
# magic number comes from: 1 mas/yr = 4.74057 km/s at 1 kpc
mul = (-vxyz[:, 0] * xyz[:, 1] / rxy + vxyz[:, 1] * xyz[:, 0] / rxy) / r / 4.74057
mub = (-vxyz[:, 0] * xyz[:, 2] * xyz[:, 0] / rxy - vxyz[:, 1] * xyz[:, 2] * xyz[:, 1] / rxy + vxyz[:, 2] * rxy) / (
r ** 2) / 4.74057
return torch.stack((mul, mub), dim=-1)
| 45.818182 | 123 | 0.578734 | import math
from typing import List, Union, Tuple
import torch
import torch.nn as nn
from astro_dynamo.snap import SnapShot
from .snaptools import align_bar
def _symmetrize_matrix(x, dim):
return (x + x.flip(dims=[dim])) / 2
class DynamicalModel(nn.Module):
def __init__(self, snap, potentials, targets, self_gravity_update=0.2):
super(DynamicalModel, self).__init__()
self.snap = snap
self.targets = nn.ModuleList(targets)
self.potentials = nn.ModuleList(potentials)
self.self_gravity_update = self_gravity_update
def forward(self):
return [target(self) for target in self.targets]
def integrate(self, steps=256):
with torch.no_grad():
self.snap.leapfrog_steps(potentials=self.potentials, steps=steps)
if self.self_gravity_update is not None:
self.potentials[0].update_density(self.snap.positions,
self.snap.masses.detach(),
fractional_update=self.self_gravity_update)
def update_potential(self, dm_potential=None, update_velocities=True):
with torch.no_grad():
if update_velocities:
old_accelerations = self.snap.get_accelerations(self.potentials,
self.snap.positions)
old_vc = torch.sum(-old_accelerations * self.snap.positions,
dim=-1).sqrt()
self.potentials[0].rho = _symmetrize_matrix(
_symmetrize_matrix(
_symmetrize_matrix(self.potentials[0].rho, 0), 1), 2)
self.potentials[0].grid_accelerations()
if dm_potential is not None:
self.potentials[1] = dm_potential
if update_velocities:
new_accelerations = self.snap.get_accelerations(self.potentials,
self.snap.positions)
new_vc = torch.sum(-new_accelerations * self.snap.positions,
dim=-1).sqrt()
gd = torch.isfinite(new_vc / old_vc) & (new_vc / old_vc > 0)
self.snap.velocities[gd, :] *= (new_vc / old_vc)[gd, None]
align_bar(self.snap)
def resample(self, velocity_perturbation=0.01):
with torch.no_grad():
self.snap = self.snap.resample(self.potentials,
velocity_perturbation=velocity_perturbation)
align_bar(self.snap)
def vc(self, components=False, r=torch.linspace(0, 9),
phi=torch.linspace(0, math.pi)):
phi_grid, r_grid = torch.meshgrid(phi, r)
phi_grid, r_grid = phi_grid.flatten(), r_grid.flatten()
pos = torch.stack((r_grid * torch.cos(phi_grid),
r_grid * torch.sin(phi_grid), 0 * phi_grid)).t()
pos = pos.to(device=self.d_scale.device)
pos /= self.d_scale
vc = []
for potential in self.potentials:
device = next(potential.buffers()).device
acc = potential.get_accelerations(pos.to(device=device)).to(
device=pos.device)
vc += [torch.sum(-acc * pos, dim=1).sqrt().reshape(
phi.shape + r.shape).mean(dim=0) * self.v_scale]
if components:
return r, vc
else:
total_vc = vc[0]
for thisvc in vc[1:]:
total_vc = (total_vc ** 2 + thisvc ** 2).sqrt()
return r, total_vc
class MilkyWayModel(DynamicalModel):
def __init__(self, snap: SnapShot, potentials: List[nn.Module],
targets: List[nn.Module],
self_gravity_update: Union[float, torch.Tensor] = 0.2,
bar_angle: Union[float, torch.Tensor] = 27.,
r_0: Union[float, torch.Tensor] = 8.2,
z_0: Union[float, torch.Tensor] = 0.014,
v_scale: Union[float, torch.Tensor] = 240,
d_scale: Union[float, torch.Tensor] = 1.4,
v_sun: Union[List[float], Tuple[float, float, float],
torch.Tensor] = (11.1, 12.24 + 238.0, 7.25)
):
super(MilkyWayModel, self).__init__(snap, potentials, targets,
self_gravity_update)
self.bar_angle = nn.Parameter(torch.as_tensor(bar_angle),
requires_grad=False)
self.r_0 = nn.Parameter(torch.as_tensor(r_0), requires_grad=False)
self.z_0 = nn.Parameter(torch.as_tensor(z_0), requires_grad=False)
self.v_scale = nn.Parameter(torch.as_tensor(v_scale),
requires_grad=False)
self.d_scale = nn.Parameter(torch.as_tensor(d_scale),
requires_grad=False)
self.v_sun = nn.Parameter(torch.as_tensor(v_sun), requires_grad=False)
@property
def m_scale(self) -> torch.tensor:
G = 4.302E-3
return self.d_scale * 1e3 * self.v_scale ** 2 / G
@property
def t_scale(self) -> torch.tensor:
return self.d_scale / self.v_scale * 0.977813106
@property
def xyz(self) -> torch.tensor:
ddtor = math.pi / 180.
ang = self.bar_angle * ddtor
pos = self.snap.positions
xyz = torch.zeros_like(pos)
inplane_gc_distance = (self.r_0 ** 2 - self.z_0 ** 2).sqrt()
xyz[:, 0] = (pos[:, 0] * torch.cos(-ang) - pos[:, 1] * torch.sin(
-ang)) * self.d_scale + inplane_gc_distance
xyz[:, 1] = (pos[:, 0] * torch.sin(-ang) + pos[:, 1] * torch.cos(
-ang)) * self.d_scale
xyz[:, 2] = pos[:, 2] * self.d_scale - self.z_0
return xyz
@property
def l_b_mu(self) -> torch.tensor:
xyz = self.xyz
l_b_mu = torch.zeros_like(xyz)
d = (xyz[:, 0] ** 2 + xyz[:, 1] ** 2 + xyz[:, 2] ** 2).sqrt()
l_b_mu[:, 0] = torch.atan2(xyz[:, 1], xyz[:, 0]) * 180 / math.pi
b_offset = torch.asin(
self.z_0 / self.r_0)
l_b_mu[:, 1] = (torch.asin(xyz[:, 2] / d) + b_offset) * 180 / math.pi
l_b_mu[:, 2] = 5 * (100 * d).log10()
return l_b_mu
@property
def masses(self) -> torch.tensor:
return self.snap.masses * self.m_scale
@property
def omega(self) -> torch.tensor:
return self.snap.omega * self.v_scale / self.d_scale
@omega.setter
def omega(self, omega: float):
self.snap.omega = omega / self.v_scale * self.d_scale
@property
def uvw(self) -> torch.tensor:
ddtor = math.pi / 180.
ang = self.bar_angle * ddtor
vxyz = torch.zeros_like(self.snap.positions)
vel = self.snap.velocities * self.v_scale
vxyz[:, 0] = (vel[:, 0] * torch.cos(-ang) - vel[:, 1] * torch.sin(-ang)) + self.v_sun[0]
vxyz[:, 1] = (vel[:, 0] * torch.sin(-ang) + vel[:, 1] * torch.cos(-ang)) - self.v_sun[1]
vxyz[:, 2] = vel[:, 2] - self.v_sun[2]
return vxyz
@property
def vr(self) -> torch.tensor:
xyz = self.xyz
vxyz = self.uvw
r = xyz.norm(dim=-1)
vr = (xyz * vxyz).sum(dim=-1) / r
return vr
@property
def mul_mub(self) -> torch.tensor:
xyz = self.xyz
vxyz = self.uvw
r = xyz.norm(dim=-1)
rxy = (xyz[:, 0] ** 2 + xyz[:, 1] ** 2).sqrt()
mul = (-vxyz[:, 0] * xyz[:, 1] / rxy + vxyz[:, 1] * xyz[:, 0] / rxy) / r / 4.74057
mub = (-vxyz[:, 0] * xyz[:, 2] * xyz[:, 0] / rxy - vxyz[:, 1] * xyz[:, 2] * xyz[:, 1] / rxy + vxyz[:, 2] * rxy) / (
r ** 2) / 4.74057
return torch.stack((mul, mub), dim=-1)
| true | true |
f710835d66959fdc467c2e264eac9c235841223e | 6,455 | py | Python | src/dataset/transforms.py | HennyJie/BrainGB | 96cf6711e2f2e6fa48b699ce3c0d6e318955c4de | [
"MIT"
] | 3 | 2022-03-17T01:34:49.000Z | 2022-03-22T07:53:17.000Z | src/dataset/transforms.py | HennyJie/BrainGB | 96cf6711e2f2e6fa48b699ce3c0d6e318955c4de | [
"MIT"
] | null | null | null | src/dataset/transforms.py | HennyJie/BrainGB | 96cf6711e2f2e6fa48b699ce3c0d6e318955c4de | [
"MIT"
] | null | null | null | import torch
from node2vec import Node2Vec as Node2Vec_
from .brain_data import BrainData
from torch_geometric.data import Data
from networkx.convert_matrix import from_numpy_matrix
from .utils import binning, LDP
import networkx as nx
from .base_transform import BaseTransform
from numpy import linalg as LA
import numpy as np
class FromSVTransform(BaseTransform):
def __init__(self, sv_transform):
super(FromSVTransform, self).__init__()
self.sv_transform = sv_transform
def __call__(self, data):
keys = list(filter(lambda x: x.startswith('edge_index'), data.keys))
for key in keys:
if key.startswith('edge_index'):
postfix = key[10:]
edge_index = data[f'edge_index{postfix}']
edge_attr = data[f'edge_attr{postfix}']
svdata = Data(edge_index=edge_index, edge_attr=edge_attr, num_nodes=data.num_nodes)
svdata_transformed = self.sv_transform(svdata)
data[f'x{postfix}'] = svdata_transformed.x
data[f'edge_index{postfix}'] = svdata_transformed.edge_index
data[f'edge_attr{postfix}'] = svdata_transformed.edge_attr
return data
def __str__(self):
return self.sv_transform.__class__.__name__
class Identity(BaseTransform):
def __call__(self, data: BrainData):
"""
Returns a diagonal matrix with ones on the diagonal.
:param data: BrainData
:return: torch.Tensor
"""
data.x = torch.diag(torch.ones(data.num_nodes))
return data
class Degree(BaseTransform):
def __call__(self, data: BrainData):
"""
Returns a diagonal matrix with the degree of each node on the diagonal.
:param data: BrainData
:return: torch.Tensor
"""
adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])
adj = adj.to_dense()
data.x = torch.Tensor(adj.sum(dim=1, keepdim=True)).float()
return data
def __str__(self):
return 'Degree'
class LDPTransform(BaseTransform):
def __call__(self, data: BrainData):
"""
Returns node feature with LDP transform.
:param data: BrainData
:return: torch.Tensor
"""
adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])
adj = adj.to_dense()
data.x = torch.Tensor(
LDP(nx.from_numpy_array(adj.numpy()))
).float()
return data
def __str__(self):
return 'LDP'
class DegreeBin(BaseTransform):
def __call__(self, data: BrainData):
"""
Returns node feature with degree bin transform.
:param data: BrainData
:return: torch.Tensor
"""
adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])
adj = adj.to_dense()
return torch.Tensor(binning(adj.sum(dim=1))).float()
def __str__(self):
return 'Degree_Bin'
class Adj(BaseTransform):
def __call__(self, data: BrainData):
"""
Returns adjacency matrix.
:param data: BrainData
:return: torch.Tensor
"""
adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])
adj = adj.to_dense()
data.x = adj
return data
def __str__(self):
return 'Adj'
class Eigenvector(BaseTransform):
def __call__(self, data: BrainData):
"""
Returns node feature with eigenvector.
:param data: BrainData
:return: torch.Tensor
"""
adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])
adj = adj.to_dense()
w, v = LA.eig(adj.numpy())
# indices = np.argsort(w)[::-1]
v = v.transpose()
data.x = torch.Tensor(v).float()
return data
class EigenNorm(BaseTransform):
def __call__(self, data: BrainData):
"""
Returns node feature with eigen norm.
:param data: BrainData
:return: torch.Tensor
"""
adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])
adj = adj.to_dense()
sum_of_rows = adj.sum(dim=1)
adj /= sum_of_rows
adj = torch.nan_to_num(adj)
w, v = LA.eig(adj.numpy())
# indices = np.argsort(w)[::-1]
v = v.transpose()
data.x = torch.Tensor(v).float()
return data
class Node2Vec(BaseTransform):
def __init__(self, feature_dim=32, walk_length=5, num_walks=200, num_workers=4,
window=10, min_count=1, batch_words=4):
super(Node2Vec, self).__init__()
self.feature_dim = feature_dim
self.walk_length = walk_length
self.num_walks = num_walks
self.num_workers = num_workers
self.window = window
self.min_count = min_count
self.batch_words = batch_words
def __call__(self, data):
"""
Returns node feature with node2vec transform.
:param data: BrainData
:return: torch.Tensor
"""
adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])
adj = adj.to_dense()
if (adj < 0).int().sum() > 0:
# split the adjacency matrix into two (negative and positive) parts
pos_adj = adj.clone()
pos_adj[adj < 0] = 0
neg_adj = adj.clone()
neg_adj[adj > 0] = 0
neg_adj = -neg_adj
adjs = [pos_adj, neg_adj]
else:
adjs = [adj]
xs = []
for adj in adjs:
x = torch.zeros((data.num_nodes, self.feature_dim))
graph = from_numpy_matrix(adj.numpy())
node2vec = Node2Vec_(graph, dimensions=self.feature_dim, walk_length=self.walk_length,
num_walks=self.num_walks, workers=self.num_workers)
model = node2vec.fit(window=self.window, min_count=self.min_count,
batch_words=self.batch_words)
for i in range(data.num_nodes):
x[i] = torch.Tensor(model.wv[f'{i}'].copy())
xs.append(x)
data.x = torch.cat(xs, dim=-1)
return data
def __str__(self):
return 'Node2Vec'
| 33.273196 | 104 | 0.604028 | import torch
from node2vec import Node2Vec as Node2Vec_
from .brain_data import BrainData
from torch_geometric.data import Data
from networkx.convert_matrix import from_numpy_matrix
from .utils import binning, LDP
import networkx as nx
from .base_transform import BaseTransform
from numpy import linalg as LA
import numpy as np
class FromSVTransform(BaseTransform):
def __init__(self, sv_transform):
super(FromSVTransform, self).__init__()
self.sv_transform = sv_transform
def __call__(self, data):
keys = list(filter(lambda x: x.startswith('edge_index'), data.keys))
for key in keys:
if key.startswith('edge_index'):
postfix = key[10:]
edge_index = data[f'edge_index{postfix}']
edge_attr = data[f'edge_attr{postfix}']
svdata = Data(edge_index=edge_index, edge_attr=edge_attr, num_nodes=data.num_nodes)
svdata_transformed = self.sv_transform(svdata)
data[f'x{postfix}'] = svdata_transformed.x
data[f'edge_index{postfix}'] = svdata_transformed.edge_index
data[f'edge_attr{postfix}'] = svdata_transformed.edge_attr
return data
def __str__(self):
return self.sv_transform.__class__.__name__
class Identity(BaseTransform):
def __call__(self, data: BrainData):
data.x = torch.diag(torch.ones(data.num_nodes))
return data
class Degree(BaseTransform):
def __call__(self, data: BrainData):
adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])
adj = adj.to_dense()
data.x = torch.Tensor(adj.sum(dim=1, keepdim=True)).float()
return data
def __str__(self):
return 'Degree'
class LDPTransform(BaseTransform):
def __call__(self, data: BrainData):
adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])
adj = adj.to_dense()
data.x = torch.Tensor(
LDP(nx.from_numpy_array(adj.numpy()))
).float()
return data
def __str__(self):
return 'LDP'
class DegreeBin(BaseTransform):
def __call__(self, data: BrainData):
adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])
adj = adj.to_dense()
return torch.Tensor(binning(adj.sum(dim=1))).float()
def __str__(self):
return 'Degree_Bin'
class Adj(BaseTransform):
def __call__(self, data: BrainData):
adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])
adj = adj.to_dense()
data.x = adj
return data
def __str__(self):
return 'Adj'
class Eigenvector(BaseTransform):
def __call__(self, data: BrainData):
adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])
adj = adj.to_dense()
w, v = LA.eig(adj.numpy())
v = v.transpose()
data.x = torch.Tensor(v).float()
return data
class EigenNorm(BaseTransform):
def __call__(self, data: BrainData):
adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])
adj = adj.to_dense()
sum_of_rows = adj.sum(dim=1)
adj /= sum_of_rows
adj = torch.nan_to_num(adj)
w, v = LA.eig(adj.numpy())
v = v.transpose()
data.x = torch.Tensor(v).float()
return data
class Node2Vec(BaseTransform):
def __init__(self, feature_dim=32, walk_length=5, num_walks=200, num_workers=4,
window=10, min_count=1, batch_words=4):
super(Node2Vec, self).__init__()
self.feature_dim = feature_dim
self.walk_length = walk_length
self.num_walks = num_walks
self.num_workers = num_workers
self.window = window
self.min_count = min_count
self.batch_words = batch_words
def __call__(self, data):
adj = torch.sparse_coo_tensor(data.edge_index, data.edge_attr, [data.num_nodes, data.num_nodes])
adj = adj.to_dense()
if (adj < 0).int().sum() > 0:
pos_adj = adj.clone()
pos_adj[adj < 0] = 0
neg_adj = adj.clone()
neg_adj[adj > 0] = 0
neg_adj = -neg_adj
adjs = [pos_adj, neg_adj]
else:
adjs = [adj]
xs = []
for adj in adjs:
x = torch.zeros((data.num_nodes, self.feature_dim))
graph = from_numpy_matrix(adj.numpy())
node2vec = Node2Vec_(graph, dimensions=self.feature_dim, walk_length=self.walk_length,
num_walks=self.num_walks, workers=self.num_workers)
model = node2vec.fit(window=self.window, min_count=self.min_count,
batch_words=self.batch_words)
for i in range(data.num_nodes):
x[i] = torch.Tensor(model.wv[f'{i}'].copy())
xs.append(x)
data.x = torch.cat(xs, dim=-1)
return data
def __str__(self):
return 'Node2Vec'
| true | true |
f710836a29ffda363d4610fc11190b6952224671 | 2,208 | py | Python | tensorflow_probability/python/bijectors/tanh.py | oahziur/probability | 11645be43d2845da65a4fbafde4cfa95780280c0 | [
"Apache-2.0"
] | 1 | 2020-04-29T11:29:25.000Z | 2020-04-29T11:29:25.000Z | tensorflow_probability/python/bijectors/tanh.py | jinxin0924/probability | ca14fa8924749593fd21e2b6389551f964527eec | [
"Apache-2.0"
] | null | null | null | tensorflow_probability/python/bijectors/tanh.py | jinxin0924/probability | ca14fa8924749593fd21e2b6389551f964527eec | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tanh bijector."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from tensorflow_probability.python.bijectors import bijector
__all__ = [
"Tanh",
]
class Tanh(bijector.Bijector):
"""Bijector that computes `Y = tanh(X)`, therefore `Y in (-1, 1)`.
This can be achieved by an affine transform of the Sigmoid bijector, i.e.,
it is equivalent to
```
tfb.Chain([tfb.Affine(shift=-1, scale=2.),
tfb.Sigmoid(),
tfb.Affine(scale=2.)])
```
However, using the `Tanh` bijector directly is slightly faster and more
numerically stable.
"""
def __init__(self, validate_args=False, name="tanh"):
super(Tanh, self).__init__(
forward_min_event_ndims=0,
validate_args=validate_args,
name=name)
def _forward(self, x):
return tf.nn.tanh(x)
def _inverse(self, y):
return tf.atanh(y)
def _inverse_log_det_jacobian(self, y):
return -tf.log1p(-tf.square(y))
def _forward_log_det_jacobian(self, x):
# This formula is mathematically equivalent to
# `tf.log1p(-tf.square(tf.tanh(x)))`, however this code is more numerically
# stable.
# Derivation:
# log(1 - tanh(x)^2)
# = log(sech(x)^2)
# = 2 * log(sech(x))
# = 2 * log(2e^-x / (e^-2x + 1))
# = 2 * (log(2) - x - log(e^-2x + 1))
# = 2 * (log(2) - x - softplus(-2x))
return 2. * (np.log(2.) - x - tf.nn.softplus(-2. * x))
| 29.837838 | 80 | 0.639493 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from tensorflow_probability.python.bijectors import bijector
__all__ = [
"Tanh",
]
class Tanh(bijector.Bijector):
def __init__(self, validate_args=False, name="tanh"):
super(Tanh, self).__init__(
forward_min_event_ndims=0,
validate_args=validate_args,
name=name)
def _forward(self, x):
return tf.nn.tanh(x)
def _inverse(self, y):
return tf.atanh(y)
def _inverse_log_det_jacobian(self, y):
return -tf.log1p(-tf.square(y))
def _forward_log_det_jacobian(self, x):
return 2. * (np.log(2.) - x - tf.nn.softplus(-2. * x))
| true | true |
f71084351b782abccdb2e0b46a99a1a1615969c0 | 8,206 | py | Python | qualcoder/settings.py | WPFilmmaker/QualCoder | 6d9529031358e3f85ef702a99e6ccfedb59efcd5 | [
"MIT"
] | null | null | null | qualcoder/settings.py | WPFilmmaker/QualCoder | 6d9529031358e3f85ef702a99e6ccfedb59efcd5 | [
"MIT"
] | null | null | null | qualcoder/settings.py | WPFilmmaker/QualCoder | 6d9529031358e3f85ef702a99e6ccfedb59efcd5 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
'''
Copyright (c) 2019 Colin Curtain
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Author: Colin Curtain (ccbogel)
https://github.com/ccbogel/QualCoder
https://qualcoder.wordpress.com/
'''
from PyQt5 import QtGui, QtWidgets, QtCore
import os
import sys
import logging
import traceback
from GUI.ui_dialog_settings import Ui_Dialog_settings
home = os.path.expanduser('~')
path = os.path.abspath(os.path.dirname(__file__))
logger = logging.getLogger(__name__)
def exception_handler(exception_type, value, tb_obj):
""" Global exception handler useful in GUIs.
tb_obj: exception.__traceback__ """
tb = '\n'.join(traceback.format_tb(tb_obj))
text = 'Traceback (most recent call last):\n' + tb + '\n' + exception_type.__name__ + ': ' + str(value)
print(text)
logger.error(_("Uncaught exception: ") + text)
QtWidgets.QMessageBox.critical(None, _('Uncaught Exception'), text)
class DialogSettings(QtWidgets.QDialog):
""" Settings for the coder name, coder table and to display ids. """
settings = {}
def __init__(self, app, parent=None):
sys.excepthook = exception_handler
self.app = app
self.settings = app.settings
super(QtWidgets.QDialog, self).__init__(parent) # overrride accept method
QtWidgets.QDialog.__init__(self)
self.ui = Ui_Dialog_settings()
self.ui.setupUi(self)
font = 'font: ' + str(self.app.settings['fontsize']) + 'pt '
font += '"' + self.app.settings['font'] + '";'
self.setStyleSheet(font)
self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint)
new_font = QtGui.QFont(self.settings['font'], self.settings['fontsize'], QtGui.QFont.Normal)
self.ui.fontComboBox.setCurrentFont(new_font)
# get coder names from all tables
# Note: does not appear to require a distinct clause
sql = "select owner from code_image union select owner from code_text union select owner from code_av "
sql += " union select owner from cases union select owner from journal union select owner from attribute "
sql += "union select owner from source union select owner from annotation union select owner from code_name "
sql += "union select owner from code_cat"
coders = [""]
if self.app.conn is not None:
cur = self.app.conn.cursor()
cur.execute(sql)
results = cur.fetchall()
for row in results:
coders.append(row[0])
self.ui.comboBox_coders.addItems(coders)
languages = ["Deutsch de", "English en", "Ελληνικά el", "Español es", "Français fr", "日本 jp"]
self.ui.comboBox_language.addItems(languages)
for index, lang in enumerate(languages):
if lang[-2:] == self.settings['language']:
self.ui.comboBox_language.setCurrentIndex(index)
timestampformats = ["[mm.ss]", "[mm:ss]", "[hh.mm.ss]", "[hh:mm:ss]",
"{hh:mm:ss}", "#hh:mm:ss.sss#"]
self.ui.comboBox_timestamp.addItems(timestampformats)
for index, ts in enumerate(timestampformats):
if ts == self.settings['timestampformat']:
self.ui.comboBox_timestamp.setCurrentIndex(index)
speakernameformats = ["[]", "{}"]
self.ui.comboBox_speaker.addItems(speakernameformats)
for index, snf in enumerate(speakernameformats):
if snf == self.settings['speakernameformat']:
self.ui.comboBox_speaker.setCurrentIndex(index)
self.ui.spinBox.setValue(self.settings['fontsize'])
self.ui.spinBox_treefontsize.setValue(self.settings['treefontsize'])
self.ui.lineEdit_coderName.setText(self.settings['codername'])
self.ui.comboBox_coders.currentIndexChanged.connect(self.comboBox_coder_changed)
self.ui.checkBox_auto_backup.stateChanged.connect(self.backup_state_changed)
if self.settings['showids'] == 'True':
self.ui.checkBox.setChecked(True)
else:
self.ui.checkBox.setChecked(False)
if self.settings['backup_on_open'] == 'True':
self.ui.checkBox_auto_backup.setChecked(True)
else:
self.ui.checkBox_auto_backup.setChecked(False)
if self.settings['backup_av_files'] == 'True':
self.ui.checkBox_backup_AV_files.setChecked(True)
else:
self.ui.checkBox_backup_AV_files.setChecked(False)
if self.settings['directory'] == "":
self.settings['directory'] = os.path.expanduser("~")
self.ui.label_directory.setText(self.settings['directory'])
self.ui.pushButton_choose_directory.clicked.connect(self.choose_directory)
def backup_state_changed(self):
""" Enable and disable av backup checkbox. Only enable when checkBox_auto_backup is checked. """
if self.ui.checkBox_auto_backup.isChecked():
self.ui.checkBox_backup_AV_files.setEnabled(True)
else:
self.ui.checkBox_backup_AV_files.setEnabled(False)
def comboBox_coder_changed(self):
""" Set the coder name to the current selection. """
self.ui.lineEdit_coderName.setText(self.ui.comboBox_coders.currentText())
def choose_directory(self):
""" Choose default project directory. """
directory = QtWidgets.QFileDialog.getExistingDirectory(self,
_('Choose project directory'), self.settings['directory'])
if directory == "":
return
self.ui.label_directory.setText(directory)
def accept(self):
self.settings['codername'] = self.ui.lineEdit_coderName.text()
if self.settings['codername'] == "":
self.settings['codername'] = "default"
self.settings['font'] = self.ui.fontComboBox.currentText()
self.settings['fontsize'] = self.ui.spinBox.value()
self.settings['treefontsize'] = self.ui.spinBox_treefontsize.value()
self.settings['directory'] = self.ui.label_directory.text()
if self.ui.checkBox.isChecked():
self.settings['showids'] = 'True'
else:
self.settings['showids'] = 'False'
self.settings['language'] = self.ui.comboBox_language.currentText()[-2:]
self.settings['timestampformat'] = self.ui.comboBox_timestamp.currentText()
self.settings['speakernameformat'] = self.ui.comboBox_speaker.currentText()
if self.ui.checkBox_auto_backup.isChecked():
self.settings['backup_on_open'] = 'True'
else:
self.settings['backup_on_open'] = 'False'
if self.ui.checkBox_backup_AV_files.isChecked():
self.settings['backup_av_files'] = 'True'
else:
self.settings['backup_av_files'] = 'False'
self.save_settings()
self.close()
def save_settings(self):
""" Save settings to text file in user's home directory.
Each setting has a variable identifier then a colon
followed by the value. """
self.app.write_config_ini(self.settings)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ui = DialogSettings()
ui.show()
sys.exit(app.exec_())
| 44.11828 | 117 | 0.672069 |
from PyQt5 import QtGui, QtWidgets, QtCore
import os
import sys
import logging
import traceback
from GUI.ui_dialog_settings import Ui_Dialog_settings
home = os.path.expanduser('~')
path = os.path.abspath(os.path.dirname(__file__))
logger = logging.getLogger(__name__)
def exception_handler(exception_type, value, tb_obj):
tb = '\n'.join(traceback.format_tb(tb_obj))
text = 'Traceback (most recent call last):\n' + tb + '\n' + exception_type.__name__ + ': ' + str(value)
print(text)
logger.error(_("Uncaught exception: ") + text)
QtWidgets.QMessageBox.critical(None, _('Uncaught Exception'), text)
class DialogSettings(QtWidgets.QDialog):
settings = {}
def __init__(self, app, parent=None):
sys.excepthook = exception_handler
self.app = app
self.settings = app.settings
super(QtWidgets.QDialog, self).__init__(parent)
QtWidgets.QDialog.__init__(self)
self.ui = Ui_Dialog_settings()
self.ui.setupUi(self)
font = 'font: ' + str(self.app.settings['fontsize']) + 'pt '
font += '"' + self.app.settings['font'] + '";'
self.setStyleSheet(font)
self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint)
new_font = QtGui.QFont(self.settings['font'], self.settings['fontsize'], QtGui.QFont.Normal)
self.ui.fontComboBox.setCurrentFont(new_font)
sql = "select owner from code_image union select owner from code_text union select owner from code_av "
sql += " union select owner from cases union select owner from journal union select owner from attribute "
sql += "union select owner from source union select owner from annotation union select owner from code_name "
sql += "union select owner from code_cat"
coders = [""]
if self.app.conn is not None:
cur = self.app.conn.cursor()
cur.execute(sql)
results = cur.fetchall()
for row in results:
coders.append(row[0])
self.ui.comboBox_coders.addItems(coders)
languages = ["Deutsch de", "English en", "Ελληνικά el", "Español es", "Français fr", "日本 jp"]
self.ui.comboBox_language.addItems(languages)
for index, lang in enumerate(languages):
if lang[-2:] == self.settings['language']:
self.ui.comboBox_language.setCurrentIndex(index)
timestampformats = ["[mm.ss]", "[mm:ss]", "[hh.mm.ss]", "[hh:mm:ss]",
"{hh:mm:ss}", "#hh:mm:ss.sss#"]
self.ui.comboBox_timestamp.addItems(timestampformats)
for index, ts in enumerate(timestampformats):
if ts == self.settings['timestampformat']:
self.ui.comboBox_timestamp.setCurrentIndex(index)
speakernameformats = ["[]", "{}"]
self.ui.comboBox_speaker.addItems(speakernameformats)
for index, snf in enumerate(speakernameformats):
if snf == self.settings['speakernameformat']:
self.ui.comboBox_speaker.setCurrentIndex(index)
self.ui.spinBox.setValue(self.settings['fontsize'])
self.ui.spinBox_treefontsize.setValue(self.settings['treefontsize'])
self.ui.lineEdit_coderName.setText(self.settings['codername'])
self.ui.comboBox_coders.currentIndexChanged.connect(self.comboBox_coder_changed)
self.ui.checkBox_auto_backup.stateChanged.connect(self.backup_state_changed)
if self.settings['showids'] == 'True':
self.ui.checkBox.setChecked(True)
else:
self.ui.checkBox.setChecked(False)
if self.settings['backup_on_open'] == 'True':
self.ui.checkBox_auto_backup.setChecked(True)
else:
self.ui.checkBox_auto_backup.setChecked(False)
if self.settings['backup_av_files'] == 'True':
self.ui.checkBox_backup_AV_files.setChecked(True)
else:
self.ui.checkBox_backup_AV_files.setChecked(False)
if self.settings['directory'] == "":
self.settings['directory'] = os.path.expanduser("~")
self.ui.label_directory.setText(self.settings['directory'])
self.ui.pushButton_choose_directory.clicked.connect(self.choose_directory)
def backup_state_changed(self):
if self.ui.checkBox_auto_backup.isChecked():
self.ui.checkBox_backup_AV_files.setEnabled(True)
else:
self.ui.checkBox_backup_AV_files.setEnabled(False)
def comboBox_coder_changed(self):
self.ui.lineEdit_coderName.setText(self.ui.comboBox_coders.currentText())
def choose_directory(self):
directory = QtWidgets.QFileDialog.getExistingDirectory(self,
_('Choose project directory'), self.settings['directory'])
if directory == "":
return
self.ui.label_directory.setText(directory)
def accept(self):
self.settings['codername'] = self.ui.lineEdit_coderName.text()
if self.settings['codername'] == "":
self.settings['codername'] = "default"
self.settings['font'] = self.ui.fontComboBox.currentText()
self.settings['fontsize'] = self.ui.spinBox.value()
self.settings['treefontsize'] = self.ui.spinBox_treefontsize.value()
self.settings['directory'] = self.ui.label_directory.text()
if self.ui.checkBox.isChecked():
self.settings['showids'] = 'True'
else:
self.settings['showids'] = 'False'
self.settings['language'] = self.ui.comboBox_language.currentText()[-2:]
self.settings['timestampformat'] = self.ui.comboBox_timestamp.currentText()
self.settings['speakernameformat'] = self.ui.comboBox_speaker.currentText()
if self.ui.checkBox_auto_backup.isChecked():
self.settings['backup_on_open'] = 'True'
else:
self.settings['backup_on_open'] = 'False'
if self.ui.checkBox_backup_AV_files.isChecked():
self.settings['backup_av_files'] = 'True'
else:
self.settings['backup_av_files'] = 'False'
self.save_settings()
self.close()
def save_settings(self):
self.app.write_config_ini(self.settings)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ui = DialogSettings()
ui.show()
sys.exit(app.exec_())
| true | true |
f710846c80ef3b7e1dcd8677b178febf876f4ee5 | 126 | py | Python | flask_sample_program.py | Divya-Madhuri/ppty_mgmnt | c57c2dbdb5ecc224b825e8e084c228085d6ff5e7 | [
"MIT"
] | null | null | null | flask_sample_program.py | Divya-Madhuri/ppty_mgmnt | c57c2dbdb5ecc224b825e8e084c228085d6ff5e7 | [
"MIT"
] | 10 | 2018-07-11T08:59:26.000Z | 2018-11-11T07:47:07.000Z | flask_sample_program.py | Divya-Madhuri/ppty_mgmnt | c57c2dbdb5ecc224b825e8e084c228085d6ff5e7 | [
"MIT"
] | null | null | null | from flask import Flask
app = Flask(__name__)
@app.route("/")
def sample_program():
return "This is sample flask program"
| 21 | 41 | 0.722222 | from flask import Flask
app = Flask(__name__)
@app.route("/")
def sample_program():
return "This is sample flask program"
| true | true |
f710852baef6447333c4f3c0bfd0f7c232311700 | 368 | py | Python | products/urls.py | zerobug110/Syfters_project | 3fac21dee2e0ff9dea4efa62e325ca02b4811c5b | [
"MIT"
] | null | null | null | products/urls.py | zerobug110/Syfters_project | 3fac21dee2e0ff9dea4efa62e325ca02b4811c5b | [
"MIT"
] | null | null | null | products/urls.py | zerobug110/Syfters_project | 3fac21dee2e0ff9dea4efa62e325ca02b4811c5b | [
"MIT"
] | null | null | null | from django.urls import path
from . import views
urlpatterns = [
path('', views.Home, name="home"),
path('portfolio', views.portfolio, name="portfolio"),
path('news', views.news, name="new"),
path('contacts', views.contacts, name="contacts"),
path('about', views.about, name="about"),
path('product/<str:pk>', views.details, name="product")
]
| 30.666667 | 59 | 0.649457 | from django.urls import path
from . import views
urlpatterns = [
path('', views.Home, name="home"),
path('portfolio', views.portfolio, name="portfolio"),
path('news', views.news, name="new"),
path('contacts', views.contacts, name="contacts"),
path('about', views.about, name="about"),
path('product/<str:pk>', views.details, name="product")
]
| true | true |
f7108595916ac71d85b22900f9d5e26db9ef5485 | 167 | py | Python | t4proj/apps/survey/templatetags/survey_extra.py | mivanov-utwente/t4proj | 78b717dc6e7ab8db6a3fc69cea64a640c050dc5c | [
"BSD-2-Clause"
] | null | null | null | t4proj/apps/survey/templatetags/survey_extra.py | mivanov-utwente/t4proj | 78b717dc6e7ab8db6a3fc69cea64a640c050dc5c | [
"BSD-2-Clause"
] | null | null | null | t4proj/apps/survey/templatetags/survey_extra.py | mivanov-utwente/t4proj | 78b717dc6e7ab8db6a3fc69cea64a640c050dc5c | [
"BSD-2-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
from django import template
register = template.Library()
@register.filter(name='times')
def times(value, arg):
return value * int(arg) | 16.7 | 30 | 0.676647 |
from django import template
register = template.Library()
@register.filter(name='times')
def times(value, arg):
return value * int(arg) | true | true |
f71085e653a5d2a7a7371d23a0bed36878d58053 | 353 | py | Python | main.py | manji6/scraping_playstation | 8f68dcd862ea6018fea566a271a473ad0226eb4a | [
"MIT"
] | null | null | null | main.py | manji6/scraping_playstation | 8f68dcd862ea6018fea566a271a473ad0226eb4a | [
"MIT"
] | null | null | null | main.py | manji6/scraping_playstation | 8f68dcd862ea6018fea566a271a473ad0226eb4a | [
"MIT"
] | null | null | null | import os
from flask import Flask, jsonify
from scraper import Scraper
app = Flask(__name__)
scraper = Scraper()
@app.route("/")
def store_playstation():
return jsonify(scraper.store_playstation("https://store.playstation.com/ja-jp/category/1b6c3e7d-4445-4cef-a046-efd94a1085b7/"))
if __name__ == "__main__":
app.run(port=8001,debug=True) | 20.764706 | 131 | 0.745042 | import os
from flask import Flask, jsonify
from scraper import Scraper
app = Flask(__name__)
scraper = Scraper()
@app.route("/")
def store_playstation():
return jsonify(scraper.store_playstation("https://store.playstation.com/ja-jp/category/1b6c3e7d-4445-4cef-a046-efd94a1085b7/"))
if __name__ == "__main__":
app.run(port=8001,debug=True) | true | true |
f71085ec739d1449547fd29afdf7e03034eab25f | 5,960 | py | Python | scenario analysis/portfolio_evaluation.py | iamlmn/monte_carlo_analysis | 45f7af2b439f80bce429a94257a1167c9d5f4a2c | [
"MIT"
] | null | null | null | scenario analysis/portfolio_evaluation.py | iamlmn/monte_carlo_analysis | 45f7af2b439f80bce429a94257a1167c9d5f4a2c | [
"MIT"
] | null | null | null | scenario analysis/portfolio_evaluation.py | iamlmn/monte_carlo_analysis | 45f7af2b439f80bce429a94257a1167c9d5f4a2c | [
"MIT"
] | 1 | 2022-03-12T02:43:40.000Z | 2022-03-12T02:43:40.000Z | import yfinance
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
def _simulate_returns(historical_returns,forecast_days):
return historical_returns.sample(n = forecast_days,
replace = True).reset_index(drop = True)
def simulate_modified_returns(
historical_returns,
forecast_days,
correct_mean_by):
h = historical_returns.copy()
new_series = h + correct_mean_by
return new_series.sample(n=forecast_days,
replace = True).reset_index(drop=True)
def simulate_portfolio(historical_returns,composition,forecast_days):
result = 0
for t in tqdm(composition):
name,weight = t[0],t[1]
s = _simulate_returns(historical_returns['return_%s' % (name)], forecast_days)
result = result + s * weight
return(result)
def simulate_modified_portfolio(
historical_returns,
composition,
forecast_days):
result = 0
for t in composition:
name,weight,correction = t[0],t[1],t[2]
s = simulate_modified_returns(
historical_returns['return_%s' % (name)],
forecast_days,correction
)
result = result + s * weight
return(result)
def simulation(historical_returns,composition,forecast_days,n_iterations):
simulated_portfolios = None
for i in range(n_iterations):
sim = simulate_modified_portfolio(historical_returns,composition,forecast_days)
sim_port = pd.DataFrame({'returns_%d' % (i) : sim})
if simulated_portfolios is None:
simulated_portfolios = sim_port
else:
simulated_portfolios = simulated_portfolios.join(sim_port)
return simulated_portfolios
if __name__ == '__main__':
portfolio_composition = [('MSFT',0.5),('AAPL',0.2),('GOOG',0.3)]
returns = pd.DataFrame({})
# create returns portfolio dataframe
for t in portfolio_composition:
name = t[0]
ticker = yfinance.Ticker(name)
data = ticker.history(interval="1d",start="2010-01-01",end="2019-12-31")
data['return_%s' % (name)] = data['Close'].pct_change(1)
returns = returns.join(data[['return_%s' % (name)]],how="outer").dropna()
# Monte Carlo simulation of a portfolio
# simulate_portfolio(returns,portfolio_composition,10)
# This may be enough for portfolio simulation, but we want something more, that is the what-if analysis.
# print("The historical average returns are : \n", returns.mean(axis=0))
'''
If we perform portfolio simulation as shown before,
we are simply saying that the future returns are a random sample
of the past returns. We already know this isn’t completely true.
Moreover, maybe we are performing scenario analysis because
we want to know what happens if certain conditions will occur.
For example, what happens if the average daily return of each stock
is lower than its historical value?If we perform portfolio
simulation as shown before, we are simply saying that the future returns
are a random sample of the past returns. We already know this
isn’t completely true. Moreover, maybe we are performing scenario analysis
because we want to know what happens if certain conditions will occur.
For example, what happens if the average daily return of each
stock is lower than its historical value?
'''
print('Let’s try to simulate what happens if the average \
returns drop by -0.0001 for MSFT, -0.001 for AAPL and -0.0005 for GOOG. \
We must subtract these quantities from each stock and then simulate the \
future portfolios with the new, modified data.')
# We’ll add these corrections directly to the portfolio_composition list (they are the third component of each tuple):
new_portfolio_composition = [
('MSFT', 0.5,-0.0001),
('AAPL', 0.2,-0.001),
('GOOG', 0.3,-0.0005)
]
# Simulations and results
forecast_days = 20
n_iterations = 200
simulated_portfolios = simulation(returns,
new_portfolio_composition,forecast_days,n_iterations)
# Taken the daily returns of a portfolio, we can build the return after N days with the compound interest formula:
percentile_5th = simulated_portfolios.cumsum().apply(lambda x : np.percentile(x,5),axis=1)
percentile_95th = simulated_portfolios.cumsum().apply(lambda x : np.percentile(x,95),axis=1)
average_port = simulated_portfolios.cumsum().apply(lambda x : np.mean(x),axis=1)
print(percentile_5th.tail(1))
print(percentile_95th.tail(1))
print(average_port.tail(1))
# Confidence interval for future portfolios
x = range(forecast_days)
plt.rcParams['figure.figsize'] = [10, 10]
plt.plot(x,average_port,label="Average portfolio")
plt.xlabel("Day")
plt.ylabel("Portfolio return")
plt.fill_between(x, percentile_5th, percentile_95th,alpha=0.2)
plt.grid()
plt.legend()
plt.show()
# Probability of beating the portfolio target
target_return = 0.02
target_prob_port = simulated_portfolios.cumsum().apply(lambda x : np.mean(x > target_return),axis=1)
print("Probabilityof beating the portfolio target {} ".format(target_return),target_prob_port.tail(1))
# The size of the error bars is calculated with the standard error formula:
err_bars = np.sqrt(
target_prob_port * (1-target_prob_port) / n_iterations
)
x = range(forecast_days)
plt.rcParams['figure.figsize'] = [10, 10]
plt.bar(x,target_prob_port,yerr = err_bars)
plt.xlabel("Day")
plt.ylabel("Probability of return >= %.2f" % (target_return))
plt.grid()
plt.show()
# Sharpe ratio histogram
'''
performance metric of a portfolio
'''
sharpe_indices = simulated_portfolios.apply(lambda x : np.mean(x)/np.std(x))
plt.hist(sharpe_indices,bins="rice")
plt.xlabel("Sharpe ratio")
plt.show()
print("Sharpe ratio mean value",np.mean(sharpe_indices)) | 32.043011 | 122 | 0.696477 | import yfinance
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
def _simulate_returns(historical_returns,forecast_days):
return historical_returns.sample(n = forecast_days,
replace = True).reset_index(drop = True)
def simulate_modified_returns(
historical_returns,
forecast_days,
correct_mean_by):
h = historical_returns.copy()
new_series = h + correct_mean_by
return new_series.sample(n=forecast_days,
replace = True).reset_index(drop=True)
def simulate_portfolio(historical_returns,composition,forecast_days):
result = 0
for t in tqdm(composition):
name,weight = t[0],t[1]
s = _simulate_returns(historical_returns['return_%s' % (name)], forecast_days)
result = result + s * weight
return(result)
def simulate_modified_portfolio(
historical_returns,
composition,
forecast_days):
result = 0
for t in composition:
name,weight,correction = t[0],t[1],t[2]
s = simulate_modified_returns(
historical_returns['return_%s' % (name)],
forecast_days,correction
)
result = result + s * weight
return(result)
def simulation(historical_returns,composition,forecast_days,n_iterations):
simulated_portfolios = None
for i in range(n_iterations):
sim = simulate_modified_portfolio(historical_returns,composition,forecast_days)
sim_port = pd.DataFrame({'returns_%d' % (i) : sim})
if simulated_portfolios is None:
simulated_portfolios = sim_port
else:
simulated_portfolios = simulated_portfolios.join(sim_port)
return simulated_portfolios
if __name__ == '__main__':
portfolio_composition = [('MSFT',0.5),('AAPL',0.2),('GOOG',0.3)]
returns = pd.DataFrame({})
for t in portfolio_composition:
name = t[0]
ticker = yfinance.Ticker(name)
data = ticker.history(interval="1d",start="2010-01-01",end="2019-12-31")
data['return_%s' % (name)] = data['Close'].pct_change(1)
returns = returns.join(data[['return_%s' % (name)]],how="outer").dropna()
print('Let’s try to simulate what happens if the average \
returns drop by -0.0001 for MSFT, -0.001 for AAPL and -0.0005 for GOOG. \
We must subtract these quantities from each stock and then simulate the \
future portfolios with the new, modified data.')
new_portfolio_composition = [
('MSFT', 0.5,-0.0001),
('AAPL', 0.2,-0.001),
('GOOG', 0.3,-0.0005)
]
forecast_days = 20
n_iterations = 200
simulated_portfolios = simulation(returns,
new_portfolio_composition,forecast_days,n_iterations)
percentile_5th = simulated_portfolios.cumsum().apply(lambda x : np.percentile(x,5),axis=1)
percentile_95th = simulated_portfolios.cumsum().apply(lambda x : np.percentile(x,95),axis=1)
average_port = simulated_portfolios.cumsum().apply(lambda x : np.mean(x),axis=1)
print(percentile_5th.tail(1))
print(percentile_95th.tail(1))
print(average_port.tail(1))
x = range(forecast_days)
plt.rcParams['figure.figsize'] = [10, 10]
plt.plot(x,average_port,label="Average portfolio")
plt.xlabel("Day")
plt.ylabel("Portfolio return")
plt.fill_between(x, percentile_5th, percentile_95th,alpha=0.2)
plt.grid()
plt.legend()
plt.show()
target_return = 0.02
target_prob_port = simulated_portfolios.cumsum().apply(lambda x : np.mean(x > target_return),axis=1)
print("Probabilityof beating the portfolio target {} ".format(target_return),target_prob_port.tail(1))
err_bars = np.sqrt(
target_prob_port * (1-target_prob_port) / n_iterations
)
x = range(forecast_days)
plt.rcParams['figure.figsize'] = [10, 10]
plt.bar(x,target_prob_port,yerr = err_bars)
plt.xlabel("Day")
plt.ylabel("Probability of return >= %.2f" % (target_return))
plt.grid()
plt.show()
sharpe_indices = simulated_portfolios.apply(lambda x : np.mean(x)/np.std(x))
plt.hist(sharpe_indices,bins="rice")
plt.xlabel("Sharpe ratio")
plt.show()
print("Sharpe ratio mean value",np.mean(sharpe_indices)) | true | true |
f71086a27c8d2575723b4d063f71368735eda0f7 | 547 | py | Python | WebMirror/management/rss_parser_funcs/feed_parse_extractWriterupdatesCom.py | fake-name/ReadableWebProxy | ed5c7abe38706acc2684a1e6cd80242a03c5f010 | [
"BSD-3-Clause"
] | 193 | 2016-08-02T22:04:35.000Z | 2022-03-09T20:45:41.000Z | WebMirror/management/rss_parser_funcs/feed_parse_extractWriterupdatesCom.py | fake-name/ReadableWebProxy | ed5c7abe38706acc2684a1e6cd80242a03c5f010 | [
"BSD-3-Clause"
] | 533 | 2016-08-23T20:48:23.000Z | 2022-03-28T15:55:13.000Z | WebMirror/management/rss_parser_funcs/feed_parse_extractWriterupdatesCom.py | rrosajp/ReadableWebProxy | ed5c7abe38706acc2684a1e6cd80242a03c5f010 | [
"BSD-3-Clause"
] | 19 | 2015-08-13T18:01:08.000Z | 2021-07-12T17:13:09.000Z |
def extractWriterupdatesCom(item):
'''
Parser for 'writerupdates.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
| 24.863636 | 104 | 0.632541 |
def extractWriterupdatesCom(item):
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
| true | true |
f7108744cd51bdd0a03c5f6fc838c34d3a33e864 | 2,948 | py | Python | tests/factors/test_selector.py | eru1030/zvt | 8a2cc66a0c24a587cc28b9b7b3df99738c59c684 | [
"MIT"
] | 6 | 2021-08-15T10:00:35.000Z | 2022-03-14T14:40:46.000Z | tests/factors/test_selector.py | eru1030/zvt | 8a2cc66a0c24a587cc28b9b7b3df99738c59c684 | [
"MIT"
] | null | null | null | tests/factors/test_selector.py | eru1030/zvt | 8a2cc66a0c24a587cc28b9b7b3df99738c59c684 | [
"MIT"
] | 5 | 2021-07-18T08:27:37.000Z | 2022-03-31T14:10:21.000Z | # -*- coding: utf-8 -*-
from zvt.contract import IntervalLevel
from zvt.factors.target_selector import TargetSelector
from zvt.factors.ma.ma_factor import CrossMaFactor
from zvt.factors import BullFactor
from ..context import init_test_context
init_test_context()
class TechnicalSelector(TargetSelector):
def init_factors(self, entity_ids, entity_schema, exchanges, codes, the_timestamp, start_timestamp,
end_timestamp, level):
bull_factor = BullFactor(entity_ids=entity_ids, entity_schema=entity_schema, exchanges=exchanges,
codes=codes, the_timestamp=the_timestamp, start_timestamp=start_timestamp,
end_timestamp=end_timestamp, provider='joinquant', level=level, adjust_type='qfq')
self.filter_factors = [bull_factor]
def test_cross_ma_selector():
entity_ids = ['stock_sz_000338']
entity_type = 'stock'
start_timestamp = '2018-01-01'
end_timestamp = '2019-06-30'
my_selector = TargetSelector(entity_ids=entity_ids,
entity_schema=entity_type,
start_timestamp=start_timestamp,
end_timestamp=end_timestamp)
# add the factors
my_selector \
.add_filter_factor(CrossMaFactor(entity_ids=entity_ids,
start_timestamp=start_timestamp,
end_timestamp=end_timestamp,
computing_window=10,
windows=[5, 10],
need_persist=False,
level=IntervalLevel.LEVEL_1DAY,
adjust_type='qfq'))
my_selector.run()
print(my_selector.open_long_df)
print(my_selector.open_short_df)
assert 'stock_sz_000338' in my_selector.get_open_short_targets('2018-01-29')
def test_technical_selector():
selector = TechnicalSelector(start_timestamp='2019-01-01',
end_timestamp='2019-06-10',
level=IntervalLevel.LEVEL_1DAY,
provider='joinquant')
selector.run()
print(selector.get_result_df())
targets = selector.get_open_long_targets('2019-06-04')
assert 'stock_sz_000338' not in targets
assert 'stock_sz_000338' not in targets
assert 'stock_sz_002572' not in targets
assert 'stock_sz_002572' not in targets
targets = selector.get_open_short_targets('2019-06-04')
assert 'stock_sz_000338' in targets
assert 'stock_sz_000338' in targets
assert 'stock_sz_002572' in targets
assert 'stock_sz_002572' in targets
selector.move_on(timeout=0)
targets = selector.get_open_long_targets('2019-06-19')
assert 'stock_sz_000338' in targets
assert 'stock_sz_002572' not in targets
| 38.789474 | 115 | 0.623474 |
from zvt.contract import IntervalLevel
from zvt.factors.target_selector import TargetSelector
from zvt.factors.ma.ma_factor import CrossMaFactor
from zvt.factors import BullFactor
from ..context import init_test_context
init_test_context()
class TechnicalSelector(TargetSelector):
def init_factors(self, entity_ids, entity_schema, exchanges, codes, the_timestamp, start_timestamp,
end_timestamp, level):
bull_factor = BullFactor(entity_ids=entity_ids, entity_schema=entity_schema, exchanges=exchanges,
codes=codes, the_timestamp=the_timestamp, start_timestamp=start_timestamp,
end_timestamp=end_timestamp, provider='joinquant', level=level, adjust_type='qfq')
self.filter_factors = [bull_factor]
def test_cross_ma_selector():
entity_ids = ['stock_sz_000338']
entity_type = 'stock'
start_timestamp = '2018-01-01'
end_timestamp = '2019-06-30'
my_selector = TargetSelector(entity_ids=entity_ids,
entity_schema=entity_type,
start_timestamp=start_timestamp,
end_timestamp=end_timestamp)
my_selector \
.add_filter_factor(CrossMaFactor(entity_ids=entity_ids,
start_timestamp=start_timestamp,
end_timestamp=end_timestamp,
computing_window=10,
windows=[5, 10],
need_persist=False,
level=IntervalLevel.LEVEL_1DAY,
adjust_type='qfq'))
my_selector.run()
print(my_selector.open_long_df)
print(my_selector.open_short_df)
assert 'stock_sz_000338' in my_selector.get_open_short_targets('2018-01-29')
def test_technical_selector():
selector = TechnicalSelector(start_timestamp='2019-01-01',
end_timestamp='2019-06-10',
level=IntervalLevel.LEVEL_1DAY,
provider='joinquant')
selector.run()
print(selector.get_result_df())
targets = selector.get_open_long_targets('2019-06-04')
assert 'stock_sz_000338' not in targets
assert 'stock_sz_000338' not in targets
assert 'stock_sz_002572' not in targets
assert 'stock_sz_002572' not in targets
targets = selector.get_open_short_targets('2019-06-04')
assert 'stock_sz_000338' in targets
assert 'stock_sz_000338' in targets
assert 'stock_sz_002572' in targets
assert 'stock_sz_002572' in targets
selector.move_on(timeout=0)
targets = selector.get_open_long_targets('2019-06-19')
assert 'stock_sz_000338' in targets
assert 'stock_sz_002572' not in targets
| true | true |
f71089cb130f4b31517af470738fe6f309467cf0 | 4,535 | py | Python | tests/plugins/test_docker_api.py | MartinBasti/atomic-reactor | 4431225c5a474c7f88c63ec1f25216d4b84a0f1d | [
"BSD-3-Clause"
] | null | null | null | tests/plugins/test_docker_api.py | MartinBasti/atomic-reactor | 4431225c5a474c7f88c63ec1f25216d4b84a0f1d | [
"BSD-3-Clause"
] | 1 | 2018-04-25T12:42:14.000Z | 2018-04-29T20:31:00.000Z | tests/plugins/test_docker_api.py | MartinBasti/atomic-reactor | 4431225c5a474c7f88c63ec1f25216d4b84a0f1d | [
"BSD-3-Clause"
] | null | null | null | """
Copyright (c) 2017 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import unicode_literals
import docker
import requests
from dockerfile_parse import DockerfileParser
from atomic_reactor.plugin import PluginFailedException
from atomic_reactor.build import InsideBuilder, BuildResult
from atomic_reactor.util import ImageName, CommandResult
from atomic_reactor.inner import DockerBuildWorkflow
from atomic_reactor.constants import INSPECT_ROOTFS, INSPECT_ROOTFS_LAYERS
from tests.docker_mock import mock_docker
from flexmock import flexmock
import pytest
from tests.constants import MOCK_SOURCE
class MockDocker(object):
def history(self, name):
return []
class MockDockerTasker(object):
def __init__(self):
self.d = MockDocker()
def inspect_image(self, name):
return {}
def build_image_from_path(self):
return True
class X(object):
pass
class MockInsideBuilder(object):
def __init__(self, failed=False, image_id=None):
self.tasker = MockDockerTasker()
self.base_image = ImageName(repo='Fedora', tag='22')
self.image_id = image_id or 'asd'
self.image = 'image'
self.failed = failed
self.df_path = 'some'
self.df_dir = 'some'
def simplegen(x, y):
yield "some\u2018".encode('utf-8')
flexmock(self.tasker, build_image_from_path=simplegen)
@property
def source(self):
return flexmock(
dockerfile_path='/',
path='/tmp',
config=flexmock(image_build_method='docker_api'),
)
def pull_base_image(self, source_registry, insecure=False):
pass
def get_built_image_info(self):
return {'Id': 'some'}
def inspect_built_image(self):
return {INSPECT_ROOTFS: {INSPECT_ROOTFS_LAYERS: []}}
def ensure_not_built(self):
pass
@pytest.mark.parametrize('is_failed', [
True,
False,
])
@pytest.mark.parametrize('image_id', ['sha256:12345', '12345'])
def test_build(is_failed, image_id):
"""
tests docker build api plugin working
"""
flexmock(DockerfileParser, content='df_content')
mock_docker()
fake_builder = MockInsideBuilder(image_id=image_id)
flexmock(InsideBuilder).new_instances(fake_builder)
workflow = DockerBuildWorkflow(MOCK_SOURCE, 'test-image')
flexmock(CommandResult).should_receive('is_failed').and_return(is_failed)
error = "error message"
error_detail = "{u'message': u\"%s\"}" % error
if is_failed:
flexmock(CommandResult, error=error, error_detail=error_detail)
with pytest.raises(PluginFailedException):
workflow.build_docker_image()
else:
workflow.build_docker_image()
assert isinstance(workflow.buildstep_result['docker_api'], BuildResult)
assert workflow.build_result == workflow.buildstep_result['docker_api']
assert workflow.build_result.is_failed() == is_failed
if is_failed:
assert workflow.build_result.fail_reason == error
assert '\\' not in workflow.plugins_errors['docker_api']
assert error in workflow.plugins_errors['docker_api']
else:
assert workflow.build_result.image_id.startswith('sha256:')
assert workflow.build_result.image_id.count(':') == 1
def test_syntax_error():
"""
tests reporting of syntax errors
"""
flexmock(DockerfileParser, content='df_content')
mock_docker()
fake_builder = MockInsideBuilder()
def raise_exc(*args, **kwargs):
explanation = ("Syntax error - can't find = in \"CMD\". "
"Must be of the form: name=value")
http_error = requests.HTTPError('500 Server Error')
raise docker.errors.APIError(message='foo',
response=http_error,
explanation=explanation)
yield {}
fake_builder.tasker.build_image_from_path = raise_exc
flexmock(InsideBuilder).new_instances(fake_builder)
workflow = DockerBuildWorkflow(MOCK_SOURCE, 'test-image')
with pytest.raises(PluginFailedException):
workflow.build_docker_image()
assert isinstance(workflow.buildstep_result['docker_api'], BuildResult)
assert workflow.build_result == workflow.buildstep_result['docker_api']
assert workflow.build_result.is_failed()
assert "Syntax error" in workflow.build_result.fail_reason
| 30.641892 | 77 | 0.690849 |
from __future__ import unicode_literals
import docker
import requests
from dockerfile_parse import DockerfileParser
from atomic_reactor.plugin import PluginFailedException
from atomic_reactor.build import InsideBuilder, BuildResult
from atomic_reactor.util import ImageName, CommandResult
from atomic_reactor.inner import DockerBuildWorkflow
from atomic_reactor.constants import INSPECT_ROOTFS, INSPECT_ROOTFS_LAYERS
from tests.docker_mock import mock_docker
from flexmock import flexmock
import pytest
from tests.constants import MOCK_SOURCE
class MockDocker(object):
def history(self, name):
return []
class MockDockerTasker(object):
def __init__(self):
self.d = MockDocker()
def inspect_image(self, name):
return {}
def build_image_from_path(self):
return True
class X(object):
pass
class MockInsideBuilder(object):
def __init__(self, failed=False, image_id=None):
self.tasker = MockDockerTasker()
self.base_image = ImageName(repo='Fedora', tag='22')
self.image_id = image_id or 'asd'
self.image = 'image'
self.failed = failed
self.df_path = 'some'
self.df_dir = 'some'
def simplegen(x, y):
yield "some\u2018".encode('utf-8')
flexmock(self.tasker, build_image_from_path=simplegen)
@property
def source(self):
return flexmock(
dockerfile_path='/',
path='/tmp',
config=flexmock(image_build_method='docker_api'),
)
def pull_base_image(self, source_registry, insecure=False):
pass
def get_built_image_info(self):
return {'Id': 'some'}
def inspect_built_image(self):
return {INSPECT_ROOTFS: {INSPECT_ROOTFS_LAYERS: []}}
def ensure_not_built(self):
pass
@pytest.mark.parametrize('is_failed', [
True,
False,
])
@pytest.mark.parametrize('image_id', ['sha256:12345', '12345'])
def test_build(is_failed, image_id):
flexmock(DockerfileParser, content='df_content')
mock_docker()
fake_builder = MockInsideBuilder(image_id=image_id)
flexmock(InsideBuilder).new_instances(fake_builder)
workflow = DockerBuildWorkflow(MOCK_SOURCE, 'test-image')
flexmock(CommandResult).should_receive('is_failed').and_return(is_failed)
error = "error message"
error_detail = "{u'message': u\"%s\"}" % error
if is_failed:
flexmock(CommandResult, error=error, error_detail=error_detail)
with pytest.raises(PluginFailedException):
workflow.build_docker_image()
else:
workflow.build_docker_image()
assert isinstance(workflow.buildstep_result['docker_api'], BuildResult)
assert workflow.build_result == workflow.buildstep_result['docker_api']
assert workflow.build_result.is_failed() == is_failed
if is_failed:
assert workflow.build_result.fail_reason == error
assert '\\' not in workflow.plugins_errors['docker_api']
assert error in workflow.plugins_errors['docker_api']
else:
assert workflow.build_result.image_id.startswith('sha256:')
assert workflow.build_result.image_id.count(':') == 1
def test_syntax_error():
flexmock(DockerfileParser, content='df_content')
mock_docker()
fake_builder = MockInsideBuilder()
def raise_exc(*args, **kwargs):
explanation = ("Syntax error - can't find = in \"CMD\". "
"Must be of the form: name=value")
http_error = requests.HTTPError('500 Server Error')
raise docker.errors.APIError(message='foo',
response=http_error,
explanation=explanation)
yield {}
fake_builder.tasker.build_image_from_path = raise_exc
flexmock(InsideBuilder).new_instances(fake_builder)
workflow = DockerBuildWorkflow(MOCK_SOURCE, 'test-image')
with pytest.raises(PluginFailedException):
workflow.build_docker_image()
assert isinstance(workflow.buildstep_result['docker_api'], BuildResult)
assert workflow.build_result == workflow.buildstep_result['docker_api']
assert workflow.build_result.is_failed()
assert "Syntax error" in workflow.build_result.fail_reason
| true | true |
f7108f493a2b4e0859207074f20dfc4dc12a43b2 | 167 | py | Python | utils/models/common_models/blocks/__init__.py | voldemortX/DeeplabV3_PyTorch1.3_Codebase | d22d23e74800fafb58eeb61d6649008745c1a287 | [
"BSD-3-Clause"
] | 1 | 2020-09-17T06:21:39.000Z | 2020-09-17T06:21:39.000Z | utils/models/common_models/blocks/__init__.py | voldemortX/pytorch-segmentation | 9c62c0a721d11c8ea6bf312ecf1c7b238a54dcda | [
"BSD-3-Clause"
] | null | null | null | utils/models/common_models/blocks/__init__.py | voldemortX/pytorch-segmentation | 9c62c0a721d11c8ea6bf312ecf1c7b238a54dcda | [
"BSD-3-Clause"
] | null | null | null | from .inverted_residual import InvertedResidual, InvertedResidualV3
from .non_bottleneck_1d import non_bottleneck_1d
from .dilated_bottleneck import DilatedBottleneck
| 41.75 | 67 | 0.898204 | from .inverted_residual import InvertedResidual, InvertedResidualV3
from .non_bottleneck_1d import non_bottleneck_1d
from .dilated_bottleneck import DilatedBottleneck
| true | true |
f7108f52cfbe4b54cdab9073d5746e1107e734cd | 2,368 | py | Python | pypeerassets/kutil.py | sparklecoin/pypeerassets | 51a0597d45dd23768d7f4eb41558400f758020fc | [
"BSD-3-Clause"
] | null | null | null | pypeerassets/kutil.py | sparklecoin/pypeerassets | 51a0597d45dd23768d7f4eb41558400f758020fc | [
"BSD-3-Clause"
] | null | null | null | pypeerassets/kutil.py | sparklecoin/pypeerassets | 51a0597d45dd23768d7f4eb41558400f758020fc | [
"BSD-3-Clause"
] | null | null | null |
from hashlib import sha256
from os import urandom
from btcpy.structs.crypto import PublicKey, PrivateKey
from btcpy.structs.transaction import MutableTransaction, TxOut
from btcpy.structs.sig import P2pkhSolver
from pypeerassets.networks import net_query
class Kutil:
def __init__(self, network: str, privkey: bytearray=None, from_string: str=None,
from_wif: str=None) -> None:
'''
High level helper class for handling public key cryptography.
: privkey - privatekey bytes
: from_wif - <WIF> import private key from your wallet in WIF format
: from_bytes - import private key in binary format
: network - specify network [ppc, tppc, btc]
: from_string - specify seed (string) to make the privkey from
'''
self.network = network
self.btcpy_constants = net_query(self.network).btcpy_constants
if privkey is not None:
self._private_key = PrivateKey(privkey)
if from_string is not None:
self._private_key = PrivateKey(sha256(
from_string.encode()).digest())
if from_wif is not None:
self._private_key = PrivateKey.from_wif(wif=from_wif,
network=self.btcpy_constants,
)
if not privkey:
if from_string == from_wif is None: # generate a new privkey
self._private_key = PrivateKey(bytearray(urandom(32)))
self.privkey = str(self._private_key)
self._public_key = PublicKey.from_priv(self._private_key)
self.pubkey = str(self._public_key)
@property
def address(self) -> str:
'''generate an address from pubkey'''
btcpy_constants = net_query(self.network).btcpy_constants
return str(self._public_key.to_address(btcpy_constants))
@property
def wif(self) -> str:
'''convert raw private key to WIF'''
return self._private_key.to_wif(network=self.btcpy_constants)
def sign_transaction(self, txin: TxOut,
tx: MutableTransaction) -> MutableTransaction:
'''sign the parent txn outputs P2PKH'''
solver = P2pkhSolver(self._private_key)
return tx.spend([txin], [solver])
| 34.823529 | 84 | 0.616976 |
from hashlib import sha256
from os import urandom
from btcpy.structs.crypto import PublicKey, PrivateKey
from btcpy.structs.transaction import MutableTransaction, TxOut
from btcpy.structs.sig import P2pkhSolver
from pypeerassets.networks import net_query
class Kutil:
def __init__(self, network: str, privkey: bytearray=None, from_string: str=None,
from_wif: str=None) -> None:
self.network = network
self.btcpy_constants = net_query(self.network).btcpy_constants
if privkey is not None:
self._private_key = PrivateKey(privkey)
if from_string is not None:
self._private_key = PrivateKey(sha256(
from_string.encode()).digest())
if from_wif is not None:
self._private_key = PrivateKey.from_wif(wif=from_wif,
network=self.btcpy_constants,
)
if not privkey:
if from_string == from_wif is None:
self._private_key = PrivateKey(bytearray(urandom(32)))
self.privkey = str(self._private_key)
self._public_key = PublicKey.from_priv(self._private_key)
self.pubkey = str(self._public_key)
@property
def address(self) -> str:
btcpy_constants = net_query(self.network).btcpy_constants
return str(self._public_key.to_address(btcpy_constants))
@property
def wif(self) -> str:
return self._private_key.to_wif(network=self.btcpy_constants)
def sign_transaction(self, txin: TxOut,
tx: MutableTransaction) -> MutableTransaction:
solver = P2pkhSolver(self._private_key)
return tx.spend([txin], [solver])
| true | true |
f7108f756f946059be6c4f65b83a9a568d67d595 | 4,743 | py | Python | evalie.py | ferhatgec/evalie | caa85312e015df46a75855998adffd3df7df61d2 | [
"MIT"
] | 1 | 2022-03-19T13:53:47.000Z | 2022-03-19T13:53:47.000Z | evalie.py | ferhatgec/evalie | caa85312e015df46a75855998adffd3df7df61d2 | [
"MIT"
] | null | null | null | evalie.py | ferhatgec/evalie | caa85312e015df46a75855998adffd3df7df61d2 | [
"MIT"
] | null | null | null | # MIT License
#
# Copyright (c) 2022 Ferhat Geçdoğan All Rights Reserved.
# Distributed under the terms of the MIT License.
#
#
# evalie - a toy evaluator using
# shunting-yard algorithm.
# ------
# github.com/ferhatgec/evalie
#
import math
class evalie:
def __init__(self):
self.precedence = {
'+': 2,
'-': 2,
'*': 3,
'/': 3,
'!': 4,
'^': 4,
'%': 4
}
self.left = 0
self.right = 0
self.op = ''
self.stack = self.evalie_values()
self.pi = str(math.pi)
self.e = str(math.e)
self.tau = str(math.tau)
self.golden_ratio = str(1.618033988749895)
class evalie_values:
def __init__(self):
self.values = []
self.operators = []
@staticmethod
def check_none(val):
return val if val is not None else -1
def get_precedence(self, ch) -> int:
return self.check_none(self.precedence.get(ch))
def perform(self):
if self.left is None:
self.left = 0
if self.right is None:
self.right = 0
match self.op:
case '+':
return self.left + self.right
case '-':
return self.right - self.left
case '*':
return self.left * self.right
case '/':
return self.right / self.left
case '^':
return self.right ** self.left
case '!':
return float(math.factorial(int(self.left)))
case '%':
return self.right % self.left
def pop(self, data):
if type(data) == float:
data = [data]
return data.pop()
if len(data) > 0:
val = data.pop()
return val
def precalc(self, data: str):
return data.replace('pi', self.pi) \
.replace('π', self.pi) \
.replace('e', self.e) \
.replace('tau', self.tau) \
.replace('τ', self.tau) \
.replace('phi', self.golden_ratio) \
.replace('φ', self.golden_ratio) \
.replace('mod', '%')\
.replace('+', ' + ')\
.replace('-', ' - ')\
.replace('/', ' / ')\
.replace('*', ' * ')
def clear(self):
self.left = self.right = 0
self.op = 0
self.stack = self.evalie_values()
def eval(self, data):
data = self.precalc(data)
i = 0
while i < len(data):
match data[i]:
case ' ':
i += 1
continue
case '(':
self.stack.operators.append(data[i])
case ')':
while len(self.stack.operators) != 0 and self.stack.operators[-1] != '(':
self.left = self.pop(self.stack.values)
self.right = self.pop(self.stack.values)
self.op = self.pop(self.stack.operators)
self.stack.values.append(self.perform())
self.pop(self.stack.operators)
case _ if data[i].isdigit() or (data[i] == '-' and self.left > 0 and self.right == 0):
value = ''
while i < len(data) and (data[i].isdigit() or data[i] == '.' or data[i] == '-'):
value += data[i]
i += 1
value = float(value)
self.stack.values.append(value)
i -= 1
case _ as arg:
while (len(self.stack.operators) != 0
and self.get_precedence(self.stack.operators[-1]) >=
self.get_precedence(arg)):
self.left = self.pop(self.stack.values)
if self.stack.operators[-1] != '!':
self.right = self.pop(self.stack.values)
self.op = self.pop(self.stack.operators)
self.stack.values.append(self.perform())
self.stack.operators.append(data[i])
i += 1
while len(self.stack.operators) != 0:
self.left = self.pop(self.stack.values)
self.right = self.pop(self.stack.values)
self.op = self.pop(self.stack.operators)
self.stack.values = self.perform()
if type(self.stack.values) == float:
self.stack.values = [self.stack.values]
if type(self.stack.values) == list and len(self.stack.values) > 0:
return self.stack.values[-1] | 27.736842 | 102 | 0.452456 |
import math
class evalie:
def __init__(self):
self.precedence = {
'+': 2,
'-': 2,
'*': 3,
'/': 3,
'!': 4,
'^': 4,
'%': 4
}
self.left = 0
self.right = 0
self.op = ''
self.stack = self.evalie_values()
self.pi = str(math.pi)
self.e = str(math.e)
self.tau = str(math.tau)
self.golden_ratio = str(1.618033988749895)
class evalie_values:
def __init__(self):
self.values = []
self.operators = []
@staticmethod
def check_none(val):
return val if val is not None else -1
def get_precedence(self, ch) -> int:
return self.check_none(self.precedence.get(ch))
def perform(self):
if self.left is None:
self.left = 0
if self.right is None:
self.right = 0
match self.op:
case '+':
return self.left + self.right
case '-':
return self.right - self.left
case '*':
return self.left * self.right
case '/':
return self.right / self.left
case '^':
return self.right ** self.left
case '!':
return float(math.factorial(int(self.left)))
case '%':
return self.right % self.left
def pop(self, data):
if type(data) == float:
data = [data]
return data.pop()
if len(data) > 0:
val = data.pop()
return val
def precalc(self, data: str):
return data.replace('pi', self.pi) \
.replace('π', self.pi) \
.replace('e', self.e) \
.replace('tau', self.tau) \
.replace('τ', self.tau) \
.replace('phi', self.golden_ratio) \
.replace('φ', self.golden_ratio) \
.replace('mod', '%')\
.replace('+', ' + ')\
.replace('-', ' - ')\
.replace('/', ' / ')\
.replace('*', ' * ')
def clear(self):
self.left = self.right = 0
self.op = 0
self.stack = self.evalie_values()
def eval(self, data):
data = self.precalc(data)
i = 0
while i < len(data):
match data[i]:
case ' ':
i += 1
continue
case '(':
self.stack.operators.append(data[i])
case ')':
while len(self.stack.operators) != 0 and self.stack.operators[-1] != '(':
self.left = self.pop(self.stack.values)
self.right = self.pop(self.stack.values)
self.op = self.pop(self.stack.operators)
self.stack.values.append(self.perform())
self.pop(self.stack.operators)
case _ if data[i].isdigit() or (data[i] == '-' and self.left > 0 and self.right == 0):
value = ''
while i < len(data) and (data[i].isdigit() or data[i] == '.' or data[i] == '-'):
value += data[i]
i += 1
value = float(value)
self.stack.values.append(value)
i -= 1
case _ as arg:
while (len(self.stack.operators) != 0
and self.get_precedence(self.stack.operators[-1]) >=
self.get_precedence(arg)):
self.left = self.pop(self.stack.values)
if self.stack.operators[-1] != '!':
self.right = self.pop(self.stack.values)
self.op = self.pop(self.stack.operators)
self.stack.values.append(self.perform())
self.stack.operators.append(data[i])
i += 1
while len(self.stack.operators) != 0:
self.left = self.pop(self.stack.values)
self.right = self.pop(self.stack.values)
self.op = self.pop(self.stack.operators)
self.stack.values = self.perform()
if type(self.stack.values) == float:
self.stack.values = [self.stack.values]
if type(self.stack.values) == list and len(self.stack.values) > 0:
return self.stack.values[-1] | true | true |
f7108fa0fd5d5b3741acce8fdb783ffafa07316b | 1,592 | py | Python | Scrap11888/lib/DataManagement/Cacher.py | GeorgeVasiliadis/Scrap11888 | f485ac894c681489e15c71597b4110859cfc7645 | [
"MIT"
] | 1 | 2021-12-14T22:28:43.000Z | 2021-12-14T22:28:43.000Z | Scrap11888/lib/DataManagement/Cacher.py | GeorgeVasiliadis/Scrap11888 | f485ac894c681489e15c71597b4110859cfc7645 | [
"MIT"
] | null | null | null | Scrap11888/lib/DataManagement/Cacher.py | GeorgeVasiliadis/Scrap11888 | f485ac894c681489e15c71597b4110859cfc7645 | [
"MIT"
] | null | null | null | import os
import pickle
from .Utils import purify, staticPath
def cacheIn(dir, name, data):
"""
Store given `data` under ./cache/dir/name.pickle file.
Note that `dir` and `name` are "purified" before used!
-dir: string of sub-directory to be created. Cache-file will be stored in it.
It shouldn't be None.
-name: string of filename without any extension. Cache-file will be named
after it. It shouldn't be None.
-data: python object to be cached.
"""
path = staticPath(__file__, "cache")
dir = purify(dir)
name = purify(name)
path = os.path.join(path, dir)
# If specified file exists, overwrite it without errors or warnings.
os.makedirs(path, exist_ok=True)
filename = name + ".pickle"
path = os.path.join(path, filename)
with open(path, "wb") as file:
pickle.dump(data, file)
def cacheOut(dir, name):
"""
Try to retrieve cached data under `./cache/dir/name.pickle`. If the
cache-file doesn't exist, None is being returned.
Note that `dir` and `name` are "purified" before used!
-dir: string of sub-directory to searched for cache-file. It shouldn't be
None.
-name: string of filename to be searched without any extension. It shouldn't
be None.
"""
data = None
path = staticPath(__file__, "cache")
dir = purify(dir)
name = purify(name)
filename = name + ".pickle"
path = os.path.join(path, dir, filename)
if os.path.isfile(path):
with open(path, "rb") as file:
data = pickle.load(file)
return data
| 27.929825 | 81 | 0.641332 | import os
import pickle
from .Utils import purify, staticPath
def cacheIn(dir, name, data):
path = staticPath(__file__, "cache")
dir = purify(dir)
name = purify(name)
path = os.path.join(path, dir)
os.makedirs(path, exist_ok=True)
filename = name + ".pickle"
path = os.path.join(path, filename)
with open(path, "wb") as file:
pickle.dump(data, file)
def cacheOut(dir, name):
data = None
path = staticPath(__file__, "cache")
dir = purify(dir)
name = purify(name)
filename = name + ".pickle"
path = os.path.join(path, dir, filename)
if os.path.isfile(path):
with open(path, "rb") as file:
data = pickle.load(file)
return data
| true | true |
f7108fcbde1f439374e9925f785ce0a7eab9e618 | 2,076 | py | Python | website_cloner/website_cloner.py | tre3x/awesomeScripts | e70cd64eff7791cfac05f069fb9f7037c1bf05bf | [
"MIT"
] | 245 | 2020-09-24T03:49:20.000Z | 2021-01-31T20:09:57.000Z | website_cloner/website_cloner.py | tre3x/awesomeScripts | e70cd64eff7791cfac05f069fb9f7037c1bf05bf | [
"MIT"
] | 252 | 2020-09-28T02:19:44.000Z | 2021-01-23T09:00:34.000Z | website_cloner/website_cloner.py | tre3x/awesomeScripts | e70cd64eff7791cfac05f069fb9f7037c1bf05bf | [
"MIT"
] | 219 | 2020-09-23T18:51:42.000Z | 2021-01-23T09:54:40.000Z | """"
Program name : Website cloner
author : https://github.com/codeperfectplus
How to use : Check README.md
"""
import os
import sys
import requests
from bs4 import BeautifulSoup
class CloneWebsite:
def __init__(self, website_name):
self.website_name = website_name
def crawl_website(self):
""" This function will crawl website and return content"""
content = requests.get(website_name)
if content.status_code == 200:
return content
def create_folder(self):
""" This funtion will create folder for website """
folder_name = (website_name.split("/"))[2]
try:
os.makedirs(folder_name)
except Exception as e:
print(e)
return folder_name
def save_website(self):
""" This function will save website to respective folder """
folder_name = self.create_folder()
content = self.crawl_website()
with open(
f"{folder_name}/index.html", "w", encoding="ascii", errors="ignore"
) as file:
file.write(content.text)
def save_image(self):
folder_name = self.create_folder()
os.chdir(folder_name)
data = requests.get(website_name).text
soup = BeautifulSoup(data, "html.parser")
for img in soup.find_all("img"):
src = img["src"]
print(src)
image_name = src.split("/")[-1]
path = src.split("/")[:-1]
path = "/".join(path)
try:
os.makedirs(path)
except Exception:
print("File Exists")
if "/" == src[:1]:
print(src)
src = website_name + src
img_data = requests.get(src).content
with open(f"{path}/{image_name}", "wb") as file:
file.write(img_data)
print("complete")
if __name__ == "__main__":
website_name = sys.argv[1]
clone = CloneWebsite(website_name)
clone.save_website()
clone.save_image()
| 29.239437 | 79 | 0.560694 |
import os
import sys
import requests
from bs4 import BeautifulSoup
class CloneWebsite:
def __init__(self, website_name):
self.website_name = website_name
def crawl_website(self):
content = requests.get(website_name)
if content.status_code == 200:
return content
def create_folder(self):
folder_name = (website_name.split("/"))[2]
try:
os.makedirs(folder_name)
except Exception as e:
print(e)
return folder_name
def save_website(self):
folder_name = self.create_folder()
content = self.crawl_website()
with open(
f"{folder_name}/index.html", "w", encoding="ascii", errors="ignore"
) as file:
file.write(content.text)
def save_image(self):
folder_name = self.create_folder()
os.chdir(folder_name)
data = requests.get(website_name).text
soup = BeautifulSoup(data, "html.parser")
for img in soup.find_all("img"):
src = img["src"]
print(src)
image_name = src.split("/")[-1]
path = src.split("/")[:-1]
path = "/".join(path)
try:
os.makedirs(path)
except Exception:
print("File Exists")
if "/" == src[:1]:
print(src)
src = website_name + src
img_data = requests.get(src).content
with open(f"{path}/{image_name}", "wb") as file:
file.write(img_data)
print("complete")
if __name__ == "__main__":
website_name = sys.argv[1]
clone = CloneWebsite(website_name)
clone.save_website()
clone.save_image()
| true | true |
f7108fee8a89713ce266ef09bd13226718600bc7 | 7,474 | py | Python | tfx/orchestration/portable/python_executor_operator_test.py | rtg0795/tfx | 63c31b719896eef645df3850d0e6b946e44cd059 | [
"Apache-2.0"
] | null | null | null | tfx/orchestration/portable/python_executor_operator_test.py | rtg0795/tfx | 63c31b719896eef645df3850d0e6b946e44cd059 | [
"Apache-2.0"
] | null | null | null | tfx/orchestration/portable/python_executor_operator_test.py | rtg0795/tfx | 63c31b719896eef645df3850d0e6b946e44cd059 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for tfx.orchestration.portable.python_executor_operator."""
import os
from typing import Any, Dict, List
import tensorflow as tf
from tfx import types
from tfx.dsl.components.base import base_executor
from tfx.dsl.io import fileio
from tfx.orchestration.portable import data_types
from tfx.orchestration.portable import outputs_utils
from tfx.orchestration.portable import python_executor_operator
from tfx.proto.orchestration import executable_spec_pb2
from tfx.proto.orchestration import execution_result_pb2
from tfx.proto.orchestration import pipeline_pb2
from tfx.types import standard_artifacts
from tfx.utils import test_case_utils
from google.protobuf import text_format
class InprocessExecutor(base_executor.BaseExecutor):
"""A Fake in-process executor what returns execution result."""
def Do(
self, input_dict: Dict[str, List[types.Artifact]],
output_dict: Dict[str, List[types.Artifact]],
exec_properties: Dict[str, Any]) -> execution_result_pb2.ExecutorOutput:
executor_output = execution_result_pb2.ExecutorOutput()
outputs_utils.populate_output_artifact(executor_output, output_dict)
outputs_utils.populate_exec_properties(executor_output, exec_properties)
return executor_output
class NotInprocessExecutor(base_executor.BaseExecutor):
"""A Fake not-in-process executor what writes execution result to executor_output_uri."""
def Do(self, input_dict: Dict[str, List[types.Artifact]],
output_dict: Dict[str, List[types.Artifact]],
exec_properties: Dict[str, Any]) -> None:
executor_output = execution_result_pb2.ExecutorOutput()
outputs_utils.populate_output_artifact(executor_output, output_dict)
outputs_utils.populate_exec_properties(executor_output, exec_properties)
with fileio.open(self._context.executor_output_uri, 'wb') as f:
f.write(executor_output.SerializeToString())
class InplaceUpdateExecutor(base_executor.BaseExecutor):
"""A Fake executor that uses the executor Context to compute its output."""
def Do(self, input_dict: Dict[str, List[types.Artifact]],
output_dict: Dict[str, List[types.Artifact]],
exec_properties: Dict[str, Any]) -> None:
model = output_dict['output_key'][0]
model.name = '{0}.{1}.my_model'.format(
self._context.pipeline_info.id,
self._context.pipeline_node.node_info.id)
class PythonExecutorOperatorTest(test_case_utils.TfxTest):
def _get_execution_info(self, input_dict, output_dict, exec_properties):
pipeline_node = pipeline_pb2.PipelineNode(node_info={'id': 'MyPythonNode'})
pipeline_info = pipeline_pb2.PipelineInfo(id='MyPipeline')
stateful_working_dir = os.path.join(self.tmp_dir, 'stateful_working_dir')
executor_output_uri = os.path.join(self.tmp_dir, 'executor_output')
return data_types.ExecutionInfo(
execution_id=1,
input_dict=input_dict,
output_dict=output_dict,
exec_properties=exec_properties,
stateful_working_dir=stateful_working_dir,
execution_output_uri=executor_output_uri,
pipeline_node=pipeline_node,
pipeline_info=pipeline_info,
pipeline_run_id=99)
def testRunExecutor_with_InprocessExecutor(self):
executor_sepc = text_format.Parse(
"""
class_path: "tfx.orchestration.portable.python_executor_operator_test.InprocessExecutor"
""", executable_spec_pb2.PythonClassExecutableSpec())
operator = python_executor_operator.PythonExecutorOperator(executor_sepc)
input_dict = {'input_key': [standard_artifacts.Examples()]}
output_dict = {'output_key': [standard_artifacts.Model()]}
exec_properties = {'key': 'value'}
executor_output = operator.run_executor(
self._get_execution_info(input_dict, output_dict, exec_properties))
self.assertProtoPartiallyEquals(
"""
execution_properties {
key: "key"
value {
string_value: "value"
}
}
output_artifacts {
key: "output_key"
value {
artifacts {
}
}
}""", executor_output)
def testRunExecutor_with_NotInprocessExecutor(self):
executor_sepc = text_format.Parse(
"""
class_path: "tfx.orchestration.portable.python_executor_operator_test.NotInprocessExecutor"
""", executable_spec_pb2.PythonClassExecutableSpec())
operator = python_executor_operator.PythonExecutorOperator(executor_sepc)
input_dict = {'input_key': [standard_artifacts.Examples()]}
output_dict = {'output_key': [standard_artifacts.Model()]}
exec_properties = {'key': 'value'}
executor_output = operator.run_executor(
self._get_execution_info(input_dict, output_dict, exec_properties))
self.assertProtoPartiallyEquals(
"""
execution_properties {
key: "key"
value {
string_value: "value"
}
}
output_artifacts {
key: "output_key"
value {
artifacts {
}
}
}""", executor_output)
def testRunExecutor_with_InplaceUpdateExecutor(self):
executor_sepc = text_format.Parse(
"""
class_path: "tfx.orchestration.portable.python_executor_operator_test.InplaceUpdateExecutor"
""", executable_spec_pb2.PythonClassExecutableSpec())
operator = python_executor_operator.PythonExecutorOperator(executor_sepc)
input_dict = {'input_key': [standard_artifacts.Examples()]}
output_dict = {'output_key': [standard_artifacts.Model()]}
exec_properties = {
'string': 'value',
'int': 1,
'float': 0.0,
# This should not happen on production and will be
# dropped.
'proto': execution_result_pb2.ExecutorOutput()
}
executor_output = operator.run_executor(
self._get_execution_info(input_dict, output_dict, exec_properties))
self.assertProtoPartiallyEquals(
"""
execution_properties {
key: "float"
value {
double_value: 0.0
}
}
execution_properties {
key: "int"
value {
int_value: 1
}
}
execution_properties {
key: "string"
value {
string_value: "value"
}
}
output_artifacts {
key: "output_key"
value {
artifacts {
custom_properties {
key: "name"
value {
string_value: "MyPipeline.MyPythonNode.my_model"
}
}
name: "MyPipeline.MyPythonNode.my_model"
}
}
}""", executor_output)
if __name__ == '__main__':
tf.test.main()
| 37.18408 | 98 | 0.677816 |
import os
from typing import Any, Dict, List
import tensorflow as tf
from tfx import types
from tfx.dsl.components.base import base_executor
from tfx.dsl.io import fileio
from tfx.orchestration.portable import data_types
from tfx.orchestration.portable import outputs_utils
from tfx.orchestration.portable import python_executor_operator
from tfx.proto.orchestration import executable_spec_pb2
from tfx.proto.orchestration import execution_result_pb2
from tfx.proto.orchestration import pipeline_pb2
from tfx.types import standard_artifacts
from tfx.utils import test_case_utils
from google.protobuf import text_format
class InprocessExecutor(base_executor.BaseExecutor):
def Do(
self, input_dict: Dict[str, List[types.Artifact]],
output_dict: Dict[str, List[types.Artifact]],
exec_properties: Dict[str, Any]) -> execution_result_pb2.ExecutorOutput:
executor_output = execution_result_pb2.ExecutorOutput()
outputs_utils.populate_output_artifact(executor_output, output_dict)
outputs_utils.populate_exec_properties(executor_output, exec_properties)
return executor_output
class NotInprocessExecutor(base_executor.BaseExecutor):
def Do(self, input_dict: Dict[str, List[types.Artifact]],
output_dict: Dict[str, List[types.Artifact]],
exec_properties: Dict[str, Any]) -> None:
executor_output = execution_result_pb2.ExecutorOutput()
outputs_utils.populate_output_artifact(executor_output, output_dict)
outputs_utils.populate_exec_properties(executor_output, exec_properties)
with fileio.open(self._context.executor_output_uri, 'wb') as f:
f.write(executor_output.SerializeToString())
class InplaceUpdateExecutor(base_executor.BaseExecutor):
def Do(self, input_dict: Dict[str, List[types.Artifact]],
output_dict: Dict[str, List[types.Artifact]],
exec_properties: Dict[str, Any]) -> None:
model = output_dict['output_key'][0]
model.name = '{0}.{1}.my_model'.format(
self._context.pipeline_info.id,
self._context.pipeline_node.node_info.id)
class PythonExecutorOperatorTest(test_case_utils.TfxTest):
def _get_execution_info(self, input_dict, output_dict, exec_properties):
pipeline_node = pipeline_pb2.PipelineNode(node_info={'id': 'MyPythonNode'})
pipeline_info = pipeline_pb2.PipelineInfo(id='MyPipeline')
stateful_working_dir = os.path.join(self.tmp_dir, 'stateful_working_dir')
executor_output_uri = os.path.join(self.tmp_dir, 'executor_output')
return data_types.ExecutionInfo(
execution_id=1,
input_dict=input_dict,
output_dict=output_dict,
exec_properties=exec_properties,
stateful_working_dir=stateful_working_dir,
execution_output_uri=executor_output_uri,
pipeline_node=pipeline_node,
pipeline_info=pipeline_info,
pipeline_run_id=99)
def testRunExecutor_with_InprocessExecutor(self):
executor_sepc = text_format.Parse(
"""
class_path: "tfx.orchestration.portable.python_executor_operator_test.InprocessExecutor"
""", executable_spec_pb2.PythonClassExecutableSpec())
operator = python_executor_operator.PythonExecutorOperator(executor_sepc)
input_dict = {'input_key': [standard_artifacts.Examples()]}
output_dict = {'output_key': [standard_artifacts.Model()]}
exec_properties = {'key': 'value'}
executor_output = operator.run_executor(
self._get_execution_info(input_dict, output_dict, exec_properties))
self.assertProtoPartiallyEquals(
"""
execution_properties {
key: "key"
value {
string_value: "value"
}
}
output_artifacts {
key: "output_key"
value {
artifacts {
}
}
}""", executor_output)
def testRunExecutor_with_NotInprocessExecutor(self):
executor_sepc = text_format.Parse(
"""
class_path: "tfx.orchestration.portable.python_executor_operator_test.NotInprocessExecutor"
""", executable_spec_pb2.PythonClassExecutableSpec())
operator = python_executor_operator.PythonExecutorOperator(executor_sepc)
input_dict = {'input_key': [standard_artifacts.Examples()]}
output_dict = {'output_key': [standard_artifacts.Model()]}
exec_properties = {'key': 'value'}
executor_output = operator.run_executor(
self._get_execution_info(input_dict, output_dict, exec_properties))
self.assertProtoPartiallyEquals(
"""
execution_properties {
key: "key"
value {
string_value: "value"
}
}
output_artifacts {
key: "output_key"
value {
artifacts {
}
}
}""", executor_output)
def testRunExecutor_with_InplaceUpdateExecutor(self):
executor_sepc = text_format.Parse(
"""
class_path: "tfx.orchestration.portable.python_executor_operator_test.InplaceUpdateExecutor"
""", executable_spec_pb2.PythonClassExecutableSpec())
operator = python_executor_operator.PythonExecutorOperator(executor_sepc)
input_dict = {'input_key': [standard_artifacts.Examples()]}
output_dict = {'output_key': [standard_artifacts.Model()]}
exec_properties = {
'string': 'value',
'int': 1,
'float': 0.0,
'proto': execution_result_pb2.ExecutorOutput()
}
executor_output = operator.run_executor(
self._get_execution_info(input_dict, output_dict, exec_properties))
self.assertProtoPartiallyEquals(
"""
execution_properties {
key: "float"
value {
double_value: 0.0
}
}
execution_properties {
key: "int"
value {
int_value: 1
}
}
execution_properties {
key: "string"
value {
string_value: "value"
}
}
output_artifacts {
key: "output_key"
value {
artifacts {
custom_properties {
key: "name"
value {
string_value: "MyPipeline.MyPythonNode.my_model"
}
}
name: "MyPipeline.MyPythonNode.my_model"
}
}
}""", executor_output)
if __name__ == '__main__':
tf.test.main()
| true | true |
f71092382f306099163685134981cd5673eeb335 | 3,980 | py | Python | visualisation/drift_paper/plot_ohc_drift.py | DamienIrving/ocean-analysis | 23a6dbf616fb84e6e158e32534ffd394e0df2e3e | [
"MIT"
] | 7 | 2017-06-06T20:20:58.000Z | 2020-02-05T23:28:41.000Z | visualisation/drift_paper/plot_ohc_drift.py | DamienIrving/ocean-analysis | 23a6dbf616fb84e6e158e32534ffd394e0df2e3e | [
"MIT"
] | 17 | 2017-04-06T04:46:37.000Z | 2021-07-01T00:47:50.000Z | visualisation/drift_paper/plot_ohc_drift.py | DamienIrving/ocean-analysis | 23a6dbf616fb84e6e158e32534ffd394e0df2e3e | [
"MIT"
] | 4 | 2021-01-19T01:31:40.000Z | 2022-03-15T00:50:11.000Z | """
Filename: plot_ohc_drift.py
Author: Damien Irving, irving.damien@gmail.com
Description: Create a bar chart showing drift in ocean heat content
and its thermal and barystatic components
"""
# Import general Python modules
import sys
import os
import re
import pdb
import argparse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cmdline_provenance as cmdprov
cwd = os.getcwd()
repo_dir = '/'
for directory in cwd.split('/')[1:]:
repo_dir = os.path.join(repo_dir, directory)
if directory == 'ocean-analysis':
break
import matplotlib as mpl
mpl.rcParams['axes.labelsize'] = 'large'
mpl.rcParams['axes.titlesize'] = 'x-large'
mpl.rcParams['xtick.labelsize'] = 'medium'
mpl.rcParams['ytick.labelsize'] = 'large'
mpl.rcParams['legend.fontsize'] = 'large'
# Define functions
def get_quartiles(df, column_name, df_project, units):
"""Get the ensemble quartiles"""
assert len(df) == len(df_project)
quartiles = ['# ' + column_name + ' quartiles']
for project in ['cmip6', 'cmip5']:
df_subset = df[df_project == project]
upper_quartile = df_subset[column_name].abs().quantile(0.75)
median = df_subset[column_name].abs().quantile(0.5)
lower_quartile = df_subset[column_name].abs().quantile(0.25)
upper_quartile_text = "%s upper quartile: %f %s" %(project, upper_quartile, units)
median_text = "%s median: %f %s" %(project, median, units)
lower_quartile_text = "%s lower quartile: %f %s" %(project, lower_quartile, units)
quartiles.append(upper_quartile_text)
quartiles.append(median_text)
quartiles.append(lower_quartile_text)
return quartiles
def main(inargs):
"""Run the program."""
df = pd.read_csv(inargs.infile)
df.set_index(df['model'], drop=True, inplace=True)
#df.set_index(df['model'] + ' (' + df['run'] + ')', drop=True, inplace=True)
x = np.arange(df.shape[0])
ncmip5 = df['project'].value_counts()['cmip5']
df_ohc = df[['OHC (J yr-1)', 'thermal OHC (J yr-1)', 'barystatic OHC (J yr-1)']]
sec_in_year = 365.25 * 24 * 60 * 60
earth_surface_area = 5.1e14
df_ohc = (df_ohc / sec_in_year) / earth_surface_area
df_ohc = df_ohc.rename(columns={"OHC (J yr-1)": "change in OHC ($dH/dt$)",
"thermal OHC (J yr-1)": "change in OHC temperature component ($dH_T/dt$)",
"barystatic OHC (J yr-1)": "change in OHC barystatic component ($dH_m/dt$)"})
df_ohc.plot.bar(figsize=(18,6), color=['#272727', 'tab:red', 'tab:blue'], width=0.9, zorder=2)
plt.axhspan(0.4, 1.0, color='0.95', zorder=1)
plt.axvline(x=ncmip5 - 0.5, color='0.5', linewidth=2.0)
units = 'equivalent planetary energy imbalance (W m$^{-2}$)'
plt.ylabel(units)
plt.axvline(x=x[0]-0.5, color='0.5', linewidth=0.1)
for val in x:
plt.axvline(x=val+0.5, color='0.5', linewidth=0.1)
quartiles = get_quartiles(df_ohc, "change in OHC ($dH/dt$)", df['project'], units)
plt.savefig(inargs.outfile, bbox_inches='tight', dpi=400)
log_file = re.sub('.png', '.met', inargs.outfile)
log_text = cmdprov.new_log(git_repo=repo_dir, extra_notes=quartiles)
cmdprov.write_log(log_file, log_text)
if __name__ == '__main__':
extra_info ="""
author:
Damien Irving, irving.damien@gmail.com
"""
description = 'Create a bar chart showing drift in ocean heat content'
parser = argparse.ArgumentParser(description=description,
epilog=extra_info,
argument_default=argparse.SUPPRESS,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("infile", type=str, help="Input file name")
parser.add_argument("outfile", type=str, help="Output file name")
args = parser.parse_args()
main(args)
| 33.728814 | 113 | 0.634422 |
import sys
import os
import re
import pdb
import argparse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cmdline_provenance as cmdprov
cwd = os.getcwd()
repo_dir = '/'
for directory in cwd.split('/')[1:]:
repo_dir = os.path.join(repo_dir, directory)
if directory == 'ocean-analysis':
break
import matplotlib as mpl
mpl.rcParams['axes.labelsize'] = 'large'
mpl.rcParams['axes.titlesize'] = 'x-large'
mpl.rcParams['xtick.labelsize'] = 'medium'
mpl.rcParams['ytick.labelsize'] = 'large'
mpl.rcParams['legend.fontsize'] = 'large'
def get_quartiles(df, column_name, df_project, units):
assert len(df) == len(df_project)
quartiles = ['# ' + column_name + ' quartiles']
for project in ['cmip6', 'cmip5']:
df_subset = df[df_project == project]
upper_quartile = df_subset[column_name].abs().quantile(0.75)
median = df_subset[column_name].abs().quantile(0.5)
lower_quartile = df_subset[column_name].abs().quantile(0.25)
upper_quartile_text = "%s upper quartile: %f %s" %(project, upper_quartile, units)
median_text = "%s median: %f %s" %(project, median, units)
lower_quartile_text = "%s lower quartile: %f %s" %(project, lower_quartile, units)
quartiles.append(upper_quartile_text)
quartiles.append(median_text)
quartiles.append(lower_quartile_text)
return quartiles
def main(inargs):
df = pd.read_csv(inargs.infile)
df.set_index(df['model'], drop=True, inplace=True)
x = np.arange(df.shape[0])
ncmip5 = df['project'].value_counts()['cmip5']
df_ohc = df[['OHC (J yr-1)', 'thermal OHC (J yr-1)', 'barystatic OHC (J yr-1)']]
sec_in_year = 365.25 * 24 * 60 * 60
earth_surface_area = 5.1e14
df_ohc = (df_ohc / sec_in_year) / earth_surface_area
df_ohc = df_ohc.rename(columns={"OHC (J yr-1)": "change in OHC ($dH/dt$)",
"thermal OHC (J yr-1)": "change in OHC temperature component ($dH_T/dt$)",
"barystatic OHC (J yr-1)": "change in OHC barystatic component ($dH_m/dt$)"})
df_ohc.plot.bar(figsize=(18,6), color=['#272727', 'tab:red', 'tab:blue'], width=0.9, zorder=2)
plt.axhspan(0.4, 1.0, color='0.95', zorder=1)
plt.axvline(x=ncmip5 - 0.5, color='0.5', linewidth=2.0)
units = 'equivalent planetary energy imbalance (W m$^{-2}$)'
plt.ylabel(units)
plt.axvline(x=x[0]-0.5, color='0.5', linewidth=0.1)
for val in x:
plt.axvline(x=val+0.5, color='0.5', linewidth=0.1)
quartiles = get_quartiles(df_ohc, "change in OHC ($dH/dt$)", df['project'], units)
plt.savefig(inargs.outfile, bbox_inches='tight', dpi=400)
log_file = re.sub('.png', '.met', inargs.outfile)
log_text = cmdprov.new_log(git_repo=repo_dir, extra_notes=quartiles)
cmdprov.write_log(log_file, log_text)
if __name__ == '__main__':
extra_info ="""
author:
Damien Irving, irving.damien@gmail.com
"""
description = 'Create a bar chart showing drift in ocean heat content'
parser = argparse.ArgumentParser(description=description,
epilog=extra_info,
argument_default=argparse.SUPPRESS,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("infile", type=str, help="Input file name")
parser.add_argument("outfile", type=str, help="Output file name")
args = parser.parse_args()
main(args)
| true | true |
f710927746bde172fc3423890b8ea4a1489a2714 | 8,943 | py | Python | gui.py | FengZiYjun/Secret-Chat | 8b77afa0d90ad400cf3d2965626f56df5f7cc6d4 | [
"Apache-2.0"
] | 3 | 2019-04-10T03:37:30.000Z | 2020-05-19T18:23:48.000Z | gui.py | FengZiYjun/Secret-Words | 8b77afa0d90ad400cf3d2965626f56df5f7cc6d4 | [
"Apache-2.0"
] | 1 | 2021-05-03T19:59:02.000Z | 2021-05-03T19:59:02.000Z | gui.py | FengZiYjun/Secret-Words | 8b77afa0d90ad400cf3d2965626f56df5f7cc6d4 | [
"Apache-2.0"
] | 1 | 2020-03-04T06:09:41.000Z | 2020-03-04T06:09:41.000Z | import tkinter as tk
import threading
from tkinter import scrolledtext
from tkinter import messagebox
ENCODING = 'utf-8'
class GUI(threading.Thread):
def __init__(self, client):
super().__init__(daemon=False, target=self.run)
self.font = ('Helvetica', 13)
self.client = client
self.login_window = None
self.main_window = None
def run(self):
self.login_window = LoginWindow(self, self.font)
self.main_window = ChatWindow(self, self.font)
self.notify_server(self.login_window.login, 'login')
self.main_window.run()
@staticmethod
def display_alert(message):
"""Display alert box"""
messagebox.showinfo('Error', message)
def update_login_list(self, active_users):
"""Update login list in main window with list of users"""
self.main_window.update_login_list(active_users)
def display_message(self, message):
"""Display message in ChatWindow"""
self.main_window.display_message(message)
def send_message(self, message):
"""Enqueue message in client's queue"""
# add
print('GUI sent: ' + message)
if self.client.target == 'ALL':
act = '2'
else:
act = '1 ' + self.client.target
self.client.queue.put(self.client.encapsulate(message, action=act))
def set_target(self, target):
"""Set target for messages"""
self.client.target = target
def notify_server(self, message, action):
"""Notify server after action was performed"""
#data = action + ";" + message
data = message
# data = data.encode(ENCODING) do not encode before sending!
self.client.notify_server(data, action)
def login(self, login):
self.client.notify_server(login, 'login')
def logout(self, logout):
self.client.notify_server(logout, 'logout')
class Window(object):
def __init__(self, title, font):
self.root = tk.Tk()
self.title = title
self.root.title(title)
self.font = font
class LoginWindow(Window):
def __init__(self, gui, font):
super().__init__("Login", font)
self.gui = gui
self.label = None
self.entry = None
self.button = None
self.login = None
self.build_window()
self.run()
def build_window(self):
"""Build login window, , set widgets positioning and event bindings"""
welcome_text = "Welcome to SECRET CHAT.\nEnter your name."
self.label = tk.Label(self.root, text=welcome_text, width=30, height=5, font=self.font)
self.label.pack(side=tk.TOP, expand=tk.YES)
self.entry = tk.Entry(self.root, width=15, font=self.font)
self.entry.focus_set()
self.entry.pack(side=tk.LEFT, expand=tk.YES)
self.entry.bind('<Return>', self.get_login_event)
self.button = tk.Button(self.root, text='Login', font=self.font)
self.button.pack(side=tk.LEFT, expand=tk.YES)
self.button.bind('<Button-1>', self.get_login_event)
def run(self):
"""Handle login window actions"""
self.root.mainloop()
self.root.destroy()
def get_login_event(self, event):
"""Get login from login box and close login window"""
self.login = self.entry.get()
self.root.quit()
class ChatWindow(Window):
def __init__(self, gui, font):
super().__init__("Secret Chat", font)
self.gui = gui
self.messages_list = None
self.logins_list = None
self.entry = None
self.send_button = None
self.exit_button = None
self.lock = threading.RLock()
self.target = ''
self.login = self.gui.login_window.login
self.build_window()
def build_window(self):
"""Build chat window, set widgets positioning and event bindings"""
# Size config
self.root.geometry('750x500')
self.root.minsize(600, 400)
# Frames config
main_frame = tk.Frame(self.root)
main_frame.grid(row=0, column=0, sticky=tk.N + tk.S + tk.W + tk.E)
self.root.rowconfigure(0, weight=1)
self.root.columnconfigure(0, weight=1)
# swap frame00 and frame01
# List of messages
frame00 = tk.Frame(main_frame)
frame00.grid(column=1, row=0, rowspan=2, sticky=tk.N + tk.S + tk.W + tk.E)
# List of logins
frame01 = tk.Frame(main_frame)
frame01.grid(column=0, row=0, rowspan=2, sticky=tk.N + tk.S + tk.W + tk.E)
# Message entry
frame02 = tk.Frame(main_frame)
frame02.grid(column=0, row=2, columnspan=2, sticky=tk.N + tk.S + tk.W + tk.E)
# Buttons
frame03 = tk.Frame(main_frame)
frame03.grid(column=0, row=3, columnspan=2, sticky=tk.N + tk.S + tk.W + tk.E)
main_frame.rowconfigure(0, weight=1)
main_frame.rowconfigure(1, weight=1)
main_frame.rowconfigure(2, weight=8)
main_frame.columnconfigure(0, weight=1)
main_frame.columnconfigure(1, weight=1)
# ScrolledText widget for displaying messages
self.messages_list = scrolledtext.ScrolledText(frame00, wrap='word', font=self.font)
self.messages_list.insert(tk.END, 'Start Your Secret Chat\n\n')
self.messages_list.configure(state='disabled')
# Listbox widget for displaying active users and selecting them
self.logins_list = tk.Listbox(frame01, selectmode=tk.SINGLE, font=self.font,
exportselection=False)
self.logins_list.bind('<<ListboxSelect>>', self.selected_login_event)
# Entry widget for typing messages in
self.entry = tk.Text(frame02, font=self.font)
self.entry.focus_set()
self.entry.bind('<Return>', self.send_entry_event)
# Button widget for sending messages
self.send_button = tk.Button(frame03, text='Send Message', font=self.font)
self.send_button.bind('<Button-1>', self.send_entry_event)
# Button for exiting
self.exit_button = tk.Button(frame03, text='Exit', font=self.font)
self.exit_button.bind('<Button-1>', self.exit_event)
# Positioning widgets in frame
self.logins_list.pack(fill=tk.BOTH, expand=tk.YES, side=tk.LEFT)
self.messages_list.pack(fill=tk.BOTH, expand=tk.YES, side=tk.LEFT)
self.entry.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.YES)
self.send_button.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.YES)
self.exit_button.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.YES)
# Protocol for closing window using 'x' button
self.root.protocol("WM_DELETE_WINDOW", self.on_closing_event)
def run(self):
"""Handle chat window actions"""
self.root.mainloop()
self.root.destroy()
def selected_login_event(self, event):
"""Set as target currently selected login on login list"""
target = self.logins_list.get(self.logins_list.curselection())
self.target = target
self.gui.set_target(target)
def send_entry_event(self, event):
"""Send message from entry field to target"""
text = self.entry.get(1.0, tk.END)
if text != '\n':
#message = 'msg;' + self.login + ';' + self.target + ';' + text[:-1]
message = text[:-1]
print(message)
self.gui.send_message(message)
self.entry.mark_set(tk.INSERT, 1.0)
self.entry.delete(1.0, tk.END)
self.entry.focus_set()
else:
messagebox.showinfo('Warning', 'You must enter non-empty message')
with self.lock:
self.messages_list.configure(state='normal')
if text != '\n':
self.messages_list.insert(tk.END, text)
self.messages_list.configure(state='disabled')
self.messages_list.see(tk.END)
return 'break'
def exit_event(self, event):
"""Send logout message and quit app when "Exit" pressed"""
self.gui.notify_server(self.login, 'logout')
self.root.quit()
def on_closing_event(self):
"""Exit window when 'x' button is pressed"""
self.exit_event(None)
def display_message(self, message):
"""Display message in ScrolledText widget"""
with self.lock:
self.messages_list.configure(state='normal')
self.messages_list.insert(tk.END, message)
self.messages_list.configure(state='disabled')
self.messages_list.see(tk.END)
def update_login_list(self, active_users):
"""Update listbox with list of active users"""
self.logins_list.delete(0, tk.END)
for user in active_users:
self.logins_list.insert(tk.END, user)
self.logins_list.select_set(0)
self.target = self.logins_list.get(self.logins_list.curselection()) | 35.772 | 95 | 0.620933 | import tkinter as tk
import threading
from tkinter import scrolledtext
from tkinter import messagebox
ENCODING = 'utf-8'
class GUI(threading.Thread):
def __init__(self, client):
super().__init__(daemon=False, target=self.run)
self.font = ('Helvetica', 13)
self.client = client
self.login_window = None
self.main_window = None
def run(self):
self.login_window = LoginWindow(self, self.font)
self.main_window = ChatWindow(self, self.font)
self.notify_server(self.login_window.login, 'login')
self.main_window.run()
@staticmethod
def display_alert(message):
messagebox.showinfo('Error', message)
def update_login_list(self, active_users):
self.main_window.update_login_list(active_users)
def display_message(self, message):
self.main_window.display_message(message)
def send_message(self, message):
print('GUI sent: ' + message)
if self.client.target == 'ALL':
act = '2'
else:
act = '1 ' + self.client.target
self.client.queue.put(self.client.encapsulate(message, action=act))
def set_target(self, target):
self.client.target = target
def notify_server(self, message, action):
data = message
self.client.notify_server(data, action)
def login(self, login):
self.client.notify_server(login, 'login')
def logout(self, logout):
self.client.notify_server(logout, 'logout')
class Window(object):
def __init__(self, title, font):
self.root = tk.Tk()
self.title = title
self.root.title(title)
self.font = font
class LoginWindow(Window):
def __init__(self, gui, font):
super().__init__("Login", font)
self.gui = gui
self.label = None
self.entry = None
self.button = None
self.login = None
self.build_window()
self.run()
def build_window(self):
welcome_text = "Welcome to SECRET CHAT.\nEnter your name."
self.label = tk.Label(self.root, text=welcome_text, width=30, height=5, font=self.font)
self.label.pack(side=tk.TOP, expand=tk.YES)
self.entry = tk.Entry(self.root, width=15, font=self.font)
self.entry.focus_set()
self.entry.pack(side=tk.LEFT, expand=tk.YES)
self.entry.bind('<Return>', self.get_login_event)
self.button = tk.Button(self.root, text='Login', font=self.font)
self.button.pack(side=tk.LEFT, expand=tk.YES)
self.button.bind('<Button-1>', self.get_login_event)
def run(self):
self.root.mainloop()
self.root.destroy()
def get_login_event(self, event):
self.login = self.entry.get()
self.root.quit()
class ChatWindow(Window):
def __init__(self, gui, font):
super().__init__("Secret Chat", font)
self.gui = gui
self.messages_list = None
self.logins_list = None
self.entry = None
self.send_button = None
self.exit_button = None
self.lock = threading.RLock()
self.target = ''
self.login = self.gui.login_window.login
self.build_window()
def build_window(self):
self.root.geometry('750x500')
self.root.minsize(600, 400)
main_frame = tk.Frame(self.root)
main_frame.grid(row=0, column=0, sticky=tk.N + tk.S + tk.W + tk.E)
self.root.rowconfigure(0, weight=1)
self.root.columnconfigure(0, weight=1)
frame00 = tk.Frame(main_frame)
frame00.grid(column=1, row=0, rowspan=2, sticky=tk.N + tk.S + tk.W + tk.E)
frame01 = tk.Frame(main_frame)
frame01.grid(column=0, row=0, rowspan=2, sticky=tk.N + tk.S + tk.W + tk.E)
frame02 = tk.Frame(main_frame)
frame02.grid(column=0, row=2, columnspan=2, sticky=tk.N + tk.S + tk.W + tk.E)
frame03 = tk.Frame(main_frame)
frame03.grid(column=0, row=3, columnspan=2, sticky=tk.N + tk.S + tk.W + tk.E)
main_frame.rowconfigure(0, weight=1)
main_frame.rowconfigure(1, weight=1)
main_frame.rowconfigure(2, weight=8)
main_frame.columnconfigure(0, weight=1)
main_frame.columnconfigure(1, weight=1)
self.messages_list = scrolledtext.ScrolledText(frame00, wrap='word', font=self.font)
self.messages_list.insert(tk.END, 'Start Your Secret Chat\n\n')
self.messages_list.configure(state='disabled')
self.logins_list = tk.Listbox(frame01, selectmode=tk.SINGLE, font=self.font,
exportselection=False)
self.logins_list.bind('<<ListboxSelect>>', self.selected_login_event)
self.entry = tk.Text(frame02, font=self.font)
self.entry.focus_set()
self.entry.bind('<Return>', self.send_entry_event)
self.send_button = tk.Button(frame03, text='Send Message', font=self.font)
self.send_button.bind('<Button-1>', self.send_entry_event)
self.exit_button = tk.Button(frame03, text='Exit', font=self.font)
self.exit_button.bind('<Button-1>', self.exit_event)
self.logins_list.pack(fill=tk.BOTH, expand=tk.YES, side=tk.LEFT)
self.messages_list.pack(fill=tk.BOTH, expand=tk.YES, side=tk.LEFT)
self.entry.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.YES)
self.send_button.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.YES)
self.exit_button.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.YES)
self.root.protocol("WM_DELETE_WINDOW", self.on_closing_event)
def run(self):
self.root.mainloop()
self.root.destroy()
def selected_login_event(self, event):
target = self.logins_list.get(self.logins_list.curselection())
self.target = target
self.gui.set_target(target)
def send_entry_event(self, event):
text = self.entry.get(1.0, tk.END)
if text != '\n':
message = text[:-1]
print(message)
self.gui.send_message(message)
self.entry.mark_set(tk.INSERT, 1.0)
self.entry.delete(1.0, tk.END)
self.entry.focus_set()
else:
messagebox.showinfo('Warning', 'You must enter non-empty message')
with self.lock:
self.messages_list.configure(state='normal')
if text != '\n':
self.messages_list.insert(tk.END, text)
self.messages_list.configure(state='disabled')
self.messages_list.see(tk.END)
return 'break'
def exit_event(self, event):
self.gui.notify_server(self.login, 'logout')
self.root.quit()
def on_closing_event(self):
self.exit_event(None)
def display_message(self, message):
with self.lock:
self.messages_list.configure(state='normal')
self.messages_list.insert(tk.END, message)
self.messages_list.configure(state='disabled')
self.messages_list.see(tk.END)
def update_login_list(self, active_users):
self.logins_list.delete(0, tk.END)
for user in active_users:
self.logins_list.insert(tk.END, user)
self.logins_list.select_set(0)
self.target = self.logins_list.get(self.logins_list.curselection()) | true | true |
f71093e41ef3731d1456d1c31f98330463d1f376 | 1,613 | py | Python | whoahqa/views/request_methods.py | onaio/who-adolescent-hqa | 108a7e60b025d0723247f5f02eab2c4d41f5a02a | [
"Apache-2.0"
] | null | null | null | whoahqa/views/request_methods.py | onaio/who-adolescent-hqa | 108a7e60b025d0723247f5f02eab2c4d41f5a02a | [
"Apache-2.0"
] | 2 | 2018-01-09T08:58:11.000Z | 2019-01-18T09:20:14.000Z | whoahqa/views/request_methods.py | onaio/who-adolescent-hqa | 108a7e60b025d0723247f5f02eab2c4d41f5a02a | [
"Apache-2.0"
] | null | null | null | from sqlalchemy.orm.exc import NoResultFound
from whoahqa.models import (
ClinicFactory,
User,
)
from whoahqa.constants import groups
from whoahqa.constants import permissions as perms
def get_request_user(request):
user_id = request.authenticated_userid
try:
return User.get(User.id == user_id)
except NoResultFound:
return None
def can_list_clinics(request):
return request.has_permission(perms.CAN_LIST_CLINICS,
ClinicFactory(request))
def can_view_clinics(request):
return request.has_permission(perms.CAN_VIEW_CLINICS,
ClinicFactory(request))
def is_super_user(request):
return request.has_permission(perms.SUPER_USER,
ClinicFactory(request))
def can_access_clinics(request):
return request.has_permission(perms.CAN_ASSESS_CLINICS,
ClinicFactory(request))
def can_create_period(request):
return request.has_permission(perms.CAN_CREATE_PERIOD,
ClinicFactory(request))
def can_view_municipality(request):
user = request.user
if user.group.name == groups.MUNICIPALITY_MANAGER or (
user.group.name == groups.STATE_OFFICIAL):
return True
return False
def can_view_state(request):
user = request.user
if user.group.name == groups.STATE_OFFICIAL:
return True
return False
def can_list_state(request):
user = request.user
if user.group.name == groups.NATIONAL_OFFICIAL:
return True
return False
| 23.720588 | 59 | 0.66708 | from sqlalchemy.orm.exc import NoResultFound
from whoahqa.models import (
ClinicFactory,
User,
)
from whoahqa.constants import groups
from whoahqa.constants import permissions as perms
def get_request_user(request):
user_id = request.authenticated_userid
try:
return User.get(User.id == user_id)
except NoResultFound:
return None
def can_list_clinics(request):
return request.has_permission(perms.CAN_LIST_CLINICS,
ClinicFactory(request))
def can_view_clinics(request):
return request.has_permission(perms.CAN_VIEW_CLINICS,
ClinicFactory(request))
def is_super_user(request):
return request.has_permission(perms.SUPER_USER,
ClinicFactory(request))
def can_access_clinics(request):
return request.has_permission(perms.CAN_ASSESS_CLINICS,
ClinicFactory(request))
def can_create_period(request):
return request.has_permission(perms.CAN_CREATE_PERIOD,
ClinicFactory(request))
def can_view_municipality(request):
user = request.user
if user.group.name == groups.MUNICIPALITY_MANAGER or (
user.group.name == groups.STATE_OFFICIAL):
return True
return False
def can_view_state(request):
user = request.user
if user.group.name == groups.STATE_OFFICIAL:
return True
return False
def can_list_state(request):
user = request.user
if user.group.name == groups.NATIONAL_OFFICIAL:
return True
return False
| true | true |
f71094846216537592d2d28a0f6ffcbe78b79a5d | 684 | py | Python | goals/finance_goal/migrations/0001_initial.py | hornd/django-finance | 40647a00509f5f0aa651af86c3b6f11730228041 | [
"Apache-2.0"
] | null | null | null | goals/finance_goal/migrations/0001_initial.py | hornd/django-finance | 40647a00509f5f0aa651af86c3b6f11730228041 | [
"Apache-2.0"
] | null | null | null | goals/finance_goal/migrations/0001_initial.py | hornd/django-finance | 40647a00509f5f0aa651af86c3b6f11730228041 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-11 01:18
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Goal',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('current_amount', models.IntegerField(default=0)),
('goal_amount', models.IntegerField()),
('end_date', models.DateTimeField(verbose_name='Due')),
],
),
]
| 26.307692 | 114 | 0.587719 |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Goal',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('current_amount', models.IntegerField(default=0)),
('goal_amount', models.IntegerField()),
('end_date', models.DateTimeField(verbose_name='Due')),
],
),
]
| true | true |
f710949d97ae83f867dbea8919f8385218e938f6 | 501 | py | Python | Multiplication.py | 13472889991/DataStructures-Algorithms | 3eb219460f0f8108bb3c07c4de5544df412e189e | [
"MIT"
] | null | null | null | Multiplication.py | 13472889991/DataStructures-Algorithms | 3eb219460f0f8108bb3c07c4de5544df412e189e | [
"MIT"
] | null | null | null | Multiplication.py | 13472889991/DataStructures-Algorithms | 3eb219460f0f8108bb3c07c4de5544df412e189e | [
"MIT"
] | null | null | null | from math import ceil
def karatsuba(a,b):
if a < 10 and b < 10:
return a*b
n = max(len(str(a)), len(str(b)))
m = int(ceil(float(n)/2))
a1 = int(a // 10**m)
a2 = int(a % (10**m))
b1 = int(b // 10**m)
b2 = int(b % (10**m))
a = karatsuba(a1,b1)
d = karatsuba(a2,b2)
e = karatsuba(a1 + a2, b1 + b2) -a -d
return int(a*(10**(m*2)) + e*(10**m) + d)
| 19.269231 | 45 | 0.373253 | from math import ceil
def karatsuba(a,b):
if a < 10 and b < 10:
return a*b
n = max(len(str(a)), len(str(b)))
m = int(ceil(float(n)/2))
a1 = int(a // 10**m)
a2 = int(a % (10**m))
b1 = int(b // 10**m)
b2 = int(b % (10**m))
a = karatsuba(a1,b1)
d = karatsuba(a2,b2)
e = karatsuba(a1 + a2, b1 + b2) -a -d
return int(a*(10**(m*2)) + e*(10**m) + d)
| true | true |
f710978296da5c053d75a954fe654c6f36c7a147 | 518 | py | Python | social_core/backends/withings.py | astofsel/package_2 | 149672d16048a1f0d4b158379432034f0234e168 | [
"BSD-3-Clause"
] | 1 | 2017-03-05T01:43:57.000Z | 2017-03-05T01:43:57.000Z | social_core/backends/withings.py | astofsel/package_2 | 149672d16048a1f0d4b158379432034f0234e168 | [
"BSD-3-Clause"
] | 2 | 2022-02-10T16:51:56.000Z | 2022-02-10T18:23:52.000Z | social_core/backends/withings.py | astofsel/package_2 | 149672d16048a1f0d4b158379432034f0234e168 | [
"BSD-3-Clause"
] | null | null | null | from .oauth import BaseOAuth1
class WithingsOAuth(BaseOAuth1):
name = 'withings'
AUTHORIZATION_URL = 'https://oauth.withings.com/account/authorize'
REQUEST_TOKEN_URL = 'https://oauth.withings.com/account/request_token'
ACCESS_TOKEN_URL = 'https://oauth.withings.com/account/access_token'
ID_KEY = 'userid'
def get_user_details(self, response):
"""Return user details from Withings account"""
return {'userid': response['access_token']['userid'],
'email': ''}
| 34.533333 | 74 | 0.685328 | from .oauth import BaseOAuth1
class WithingsOAuth(BaseOAuth1):
name = 'withings'
AUTHORIZATION_URL = 'https://oauth.withings.com/account/authorize'
REQUEST_TOKEN_URL = 'https://oauth.withings.com/account/request_token'
ACCESS_TOKEN_URL = 'https://oauth.withings.com/account/access_token'
ID_KEY = 'userid'
def get_user_details(self, response):
return {'userid': response['access_token']['userid'],
'email': ''}
| true | true |
f7109950a5b343a22646337789e00f664d4489bb | 53,193 | py | Python | heat/tests/engine/test_scheduler.py | larsks/heat | 11064586e90166a037f8868835e6ce36f7306276 | [
"Apache-2.0"
] | null | null | null | heat/tests/engine/test_scheduler.py | larsks/heat | 11064586e90166a037f8868835e6ce36f7306276 | [
"Apache-2.0"
] | null | null | null | heat/tests/engine/test_scheduler.py | larsks/heat | 11064586e90166a037f8868835e6ce36f7306276 | [
"Apache-2.0"
] | null | null | null | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import contextlib
import itertools
import eventlet
import six
from heat.common.i18n import repr_wrapper
from heat.common import timeutils
from heat.engine import dependencies
from heat.engine import scheduler
from heat.tests import common
class DummyTask(object):
def __init__(self, num_steps=3, delays=None):
self.num_steps = num_steps
if delays is not None:
self.delays = iter(delays)
else:
self.delays = itertools.repeat(None)
def __call__(self, *args, **kwargs):
for i in range(1, self.num_steps + 1):
self.do_step(i, *args, **kwargs)
yield next(self.delays)
def do_step(self, step_num, *args, **kwargs):
pass
class ExceptionGroupTest(common.HeatTestCase):
def test_contains_exceptions(self):
exception_group = scheduler.ExceptionGroup()
self.assertIsInstance(exception_group.exceptions, list)
def test_can_be_initialized_with_a_list_of_exceptions(self):
ex1 = Exception("ex 1")
ex2 = Exception("ex 2")
exception_group = scheduler.ExceptionGroup([ex1, ex2])
self.assertIn(ex1, exception_group.exceptions)
self.assertIn(ex2, exception_group.exceptions)
def test_can_add_exceptions_after_init(self):
ex = Exception()
exception_group = scheduler.ExceptionGroup()
exception_group.exceptions.append(ex)
self.assertIn(ex, exception_group.exceptions)
def test_str_representation_aggregates_all_exceptions(self):
ex1 = Exception("ex 1")
ex2 = Exception("ex 2")
exception_group = scheduler.ExceptionGroup([ex1, ex2])
self.assertEqual("['ex 1', 'ex 2']", six.text_type(exception_group))
class DependencyTaskGroupTest(common.HeatTestCase):
def setUp(self):
super(DependencyTaskGroupTest, self).setUp()
self.addCleanup(self.m.VerifyAll)
self.aggregate_exceptions = False
self.error_wait_time = None
self.reverse_order = False
@contextlib.contextmanager
def _dep_test(self, *edges):
dummy = DummyTask(getattr(self, 'steps', 3))
deps = dependencies.Dependencies(edges)
tg = scheduler.DependencyTaskGroup(
deps, dummy, reverse=self.reverse_order,
error_wait_time=self.error_wait_time,
aggregate_exceptions=self.aggregate_exceptions)
self.m.StubOutWithMock(dummy, 'do_step')
yield dummy
self.m.ReplayAll()
scheduler.TaskRunner(tg)(wait_time=None)
def test_no_steps(self):
self.steps = 0
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
with self._dep_test(('second', 'first')):
pass
def test_single_node(self):
with self._dep_test(('only', None)) as dummy:
dummy.do_step(1, 'only').AndReturn(None)
dummy.do_step(2, 'only').AndReturn(None)
dummy.do_step(3, 'only').AndReturn(None)
def test_disjoint(self):
with self._dep_test(('1', None), ('2', None)) as dummy:
dummy.do_step(1, '1').InAnyOrder('1')
dummy.do_step(1, '2').InAnyOrder('1')
dummy.do_step(2, '1').InAnyOrder('2')
dummy.do_step(2, '2').InAnyOrder('2')
dummy.do_step(3, '1').InAnyOrder('3')
dummy.do_step(3, '2').InAnyOrder('3')
def test_single_fwd(self):
with self._dep_test(('second', 'first')) as dummy:
dummy.do_step(1, 'first').AndReturn(None)
dummy.do_step(2, 'first').AndReturn(None)
dummy.do_step(3, 'first').AndReturn(None)
dummy.do_step(1, 'second').AndReturn(None)
dummy.do_step(2, 'second').AndReturn(None)
dummy.do_step(3, 'second').AndReturn(None)
def test_chain_fwd(self):
with self._dep_test(('third', 'second'),
('second', 'first')) as dummy:
dummy.do_step(1, 'first').AndReturn(None)
dummy.do_step(2, 'first').AndReturn(None)
dummy.do_step(3, 'first').AndReturn(None)
dummy.do_step(1, 'second').AndReturn(None)
dummy.do_step(2, 'second').AndReturn(None)
dummy.do_step(3, 'second').AndReturn(None)
dummy.do_step(1, 'third').AndReturn(None)
dummy.do_step(2, 'third').AndReturn(None)
dummy.do_step(3, 'third').AndReturn(None)
def test_diamond_fwd(self):
with self._dep_test(('last', 'mid1'), ('last', 'mid2'),
('mid1', 'first'), ('mid2', 'first')) as dummy:
dummy.do_step(1, 'first').AndReturn(None)
dummy.do_step(2, 'first').AndReturn(None)
dummy.do_step(3, 'first').AndReturn(None)
dummy.do_step(1, 'mid1').InAnyOrder('1')
dummy.do_step(1, 'mid2').InAnyOrder('1')
dummy.do_step(2, 'mid1').InAnyOrder('2')
dummy.do_step(2, 'mid2').InAnyOrder('2')
dummy.do_step(3, 'mid1').InAnyOrder('3')
dummy.do_step(3, 'mid2').InAnyOrder('3')
dummy.do_step(1, 'last').AndReturn(None)
dummy.do_step(2, 'last').AndReturn(None)
dummy.do_step(3, 'last').AndReturn(None)
def test_complex_fwd(self):
with self._dep_test(('last', 'mid1'), ('last', 'mid2'),
('mid1', 'mid3'), ('mid1', 'first'),
('mid3', 'first'), ('mid2', 'first')) as dummy:
dummy.do_step(1, 'first').AndReturn(None)
dummy.do_step(2, 'first').AndReturn(None)
dummy.do_step(3, 'first').AndReturn(None)
dummy.do_step(1, 'mid2').InAnyOrder('1')
dummy.do_step(1, 'mid3').InAnyOrder('1')
dummy.do_step(2, 'mid2').InAnyOrder('2')
dummy.do_step(2, 'mid3').InAnyOrder('2')
dummy.do_step(3, 'mid2').InAnyOrder('3')
dummy.do_step(3, 'mid3').InAnyOrder('3')
dummy.do_step(1, 'mid1').AndReturn(None)
dummy.do_step(2, 'mid1').AndReturn(None)
dummy.do_step(3, 'mid1').AndReturn(None)
dummy.do_step(1, 'last').AndReturn(None)
dummy.do_step(2, 'last').AndReturn(None)
dummy.do_step(3, 'last').AndReturn(None)
def test_many_edges_fwd(self):
with self._dep_test(('last', 'e1'), ('last', 'mid1'), ('last', 'mid2'),
('mid1', 'e2'), ('mid1', 'mid3'),
('mid2', 'mid3'),
('mid3', 'e3')) as dummy:
dummy.do_step(1, 'e1').InAnyOrder('1edges')
dummy.do_step(1, 'e2').InAnyOrder('1edges')
dummy.do_step(1, 'e3').InAnyOrder('1edges')
dummy.do_step(2, 'e1').InAnyOrder('2edges')
dummy.do_step(2, 'e2').InAnyOrder('2edges')
dummy.do_step(2, 'e3').InAnyOrder('2edges')
dummy.do_step(3, 'e1').InAnyOrder('3edges')
dummy.do_step(3, 'e2').InAnyOrder('3edges')
dummy.do_step(3, 'e3').InAnyOrder('3edges')
dummy.do_step(1, 'mid3').AndReturn(None)
dummy.do_step(2, 'mid3').AndReturn(None)
dummy.do_step(3, 'mid3').AndReturn(None)
dummy.do_step(1, 'mid2').InAnyOrder('1mid')
dummy.do_step(1, 'mid1').InAnyOrder('1mid')
dummy.do_step(2, 'mid2').InAnyOrder('2mid')
dummy.do_step(2, 'mid1').InAnyOrder('2mid')
dummy.do_step(3, 'mid2').InAnyOrder('3mid')
dummy.do_step(3, 'mid1').InAnyOrder('3mid')
dummy.do_step(1, 'last').AndReturn(None)
dummy.do_step(2, 'last').AndReturn(None)
dummy.do_step(3, 'last').AndReturn(None)
def test_dbldiamond_fwd(self):
with self._dep_test(('last', 'a1'), ('last', 'a2'),
('a1', 'b1'), ('a2', 'b1'), ('a2', 'b2'),
('b1', 'first'), ('b2', 'first')) as dummy:
dummy.do_step(1, 'first').AndReturn(None)
dummy.do_step(2, 'first').AndReturn(None)
dummy.do_step(3, 'first').AndReturn(None)
dummy.do_step(1, 'b1').InAnyOrder('1b')
dummy.do_step(1, 'b2').InAnyOrder('1b')
dummy.do_step(2, 'b1').InAnyOrder('2b')
dummy.do_step(2, 'b2').InAnyOrder('2b')
dummy.do_step(3, 'b1').InAnyOrder('3b')
dummy.do_step(3, 'b2').InAnyOrder('3b')
dummy.do_step(1, 'a1').InAnyOrder('1a')
dummy.do_step(1, 'a2').InAnyOrder('1a')
dummy.do_step(2, 'a1').InAnyOrder('2a')
dummy.do_step(2, 'a2').InAnyOrder('2a')
dummy.do_step(3, 'a1').InAnyOrder('3a')
dummy.do_step(3, 'a2').InAnyOrder('3a')
dummy.do_step(1, 'last').AndReturn(None)
dummy.do_step(2, 'last').AndReturn(None)
dummy.do_step(3, 'last').AndReturn(None)
def test_circular_deps(self):
d = dependencies.Dependencies([('first', 'second'),
('second', 'third'),
('third', 'first')])
self.assertRaises(dependencies.CircularDependencyException,
scheduler.DependencyTaskGroup, d)
def test_aggregate_exceptions_raises_all_at_the_end(self):
def run_tasks_with_exceptions(e1=None, e2=None):
self.aggregate_exceptions = True
tasks = (('A', None), ('B', None), ('C', None))
with self._dep_test(*tasks) as dummy:
dummy.do_step(1, 'A').InAnyOrder('1')
dummy.do_step(1, 'B').InAnyOrder('1')
dummy.do_step(1, 'C').InAnyOrder('1').AndRaise(e1)
dummy.do_step(2, 'A').InAnyOrder('2')
dummy.do_step(2, 'B').InAnyOrder('2').AndRaise(e2)
dummy.do_step(3, 'A').InAnyOrder('3')
e1 = Exception('e1')
e2 = Exception('e2')
exc = self.assertRaises(scheduler.ExceptionGroup,
run_tasks_with_exceptions, e1, e2)
self.assertEqual(set([e1, e2]), set(exc.exceptions))
def test_aggregate_exceptions_cancels_dependent_tasks_recursively(self):
def run_tasks_with_exceptions(e1=None, e2=None):
self.aggregate_exceptions = True
tasks = (('A', None), ('B', 'A'), ('C', 'B'))
with self._dep_test(*tasks) as dummy:
dummy.do_step(1, 'A').AndRaise(e1)
e1 = Exception('e1')
exc = self.assertRaises(scheduler.ExceptionGroup,
run_tasks_with_exceptions, e1)
self.assertEqual([e1], exc.exceptions)
def test_aggregate_exceptions_cancels_tasks_in_reverse_order(self):
def run_tasks_with_exceptions(e1=None, e2=None):
self.reverse_order = True
self.aggregate_exceptions = True
tasks = (('A', None), ('B', 'A'), ('C', 'B'))
with self._dep_test(*tasks) as dummy:
dummy.do_step(1, 'C').AndRaise(e1)
e1 = Exception('e1')
exc = self.assertRaises(scheduler.ExceptionGroup,
run_tasks_with_exceptions, e1)
self.assertEqual([e1], exc.exceptions)
def test_exceptions_on_cancel(self):
class TestException(Exception):
pass
class ExceptionOnExit(Exception):
pass
cancelled = []
def task_func(arg):
for i in range(4):
if i > 1:
raise TestException
try:
yield
except GeneratorExit:
cancelled.append(arg)
raise ExceptionOnExit
tasks = (('A', None), ('B', None), ('C', None))
deps = dependencies.Dependencies(tasks)
tg = scheduler.DependencyTaskGroup(deps, task_func)
task = tg()
next(task)
next(task)
self.assertRaises(TestException, next, task)
self.assertEqual(len(tasks) - 1, len(cancelled))
def test_exception_grace_period(self):
e1 = Exception('e1')
def run_tasks_with_exceptions():
self.error_wait_time = 5
tasks = (('A', None), ('B', None), ('C', 'A'))
with self._dep_test(*tasks) as dummy:
dummy.do_step(1, 'A').InAnyOrder('1')
dummy.do_step(1, 'B').InAnyOrder('1')
dummy.do_step(2, 'A').InAnyOrder('2').AndRaise(e1)
dummy.do_step(2, 'B').InAnyOrder('2')
dummy.do_step(3, 'B')
exc = self.assertRaises(type(e1), run_tasks_with_exceptions)
self.assertEqual(e1, exc)
def test_exception_grace_period_expired(self):
e1 = Exception('e1')
def run_tasks_with_exceptions():
self.steps = 5
self.error_wait_time = 0.05
def sleep():
eventlet.sleep(self.error_wait_time)
tasks = (('A', None), ('B', None), ('C', 'A'))
with self._dep_test(*tasks) as dummy:
dummy.do_step(1, 'A').InAnyOrder('1')
dummy.do_step(1, 'B').InAnyOrder('1')
dummy.do_step(2, 'A').InAnyOrder('2').AndRaise(e1)
dummy.do_step(2, 'B').InAnyOrder('2')
dummy.do_step(3, 'B')
dummy.do_step(4, 'B').WithSideEffects(sleep)
exc = self.assertRaises(type(e1), run_tasks_with_exceptions)
self.assertEqual(e1, exc)
def test_exception_grace_period_per_task(self):
e1 = Exception('e1')
def get_wait_time(key):
if key == 'B':
return 5
else:
return None
def run_tasks_with_exceptions():
self.error_wait_time = get_wait_time
tasks = (('A', None), ('B', None), ('C', 'A'))
with self._dep_test(*tasks) as dummy:
dummy.do_step(1, 'A').InAnyOrder('1')
dummy.do_step(1, 'B').InAnyOrder('1')
dummy.do_step(2, 'A').InAnyOrder('2').AndRaise(e1)
dummy.do_step(2, 'B').InAnyOrder('2')
dummy.do_step(3, 'B')
exc = self.assertRaises(type(e1), run_tasks_with_exceptions)
self.assertEqual(e1, exc)
def test_thrown_exception_order(self):
e1 = Exception('e1')
e2 = Exception('e2')
tasks = (('A', None), ('B', None), ('C', 'A'))
deps = dependencies.Dependencies(tasks)
tg = scheduler.DependencyTaskGroup(
deps, DummyTask(), reverse=self.reverse_order,
error_wait_time=1,
aggregate_exceptions=self.aggregate_exceptions)
task = tg()
next(task)
task.throw(e1)
next(task)
tg.error_wait_time = None
exc = self.assertRaises(type(e2), task.throw, e2)
self.assertIs(e2, exc)
class TaskTest(common.HeatTestCase):
def setUp(self):
super(TaskTest, self).setUp()
scheduler.ENABLE_SLEEP = True
self.addCleanup(self.m.VerifyAll)
def test_run(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(0).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(3).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
scheduler.TaskRunner(task)()
def test_run_as_task(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
task.do_step(3).AndReturn(None)
self.m.ReplayAll()
tr = scheduler.TaskRunner(task)
rt = tr.as_task()
for step in rt:
pass
self.assertTrue(tr.done())
def test_run_as_task_started(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
task.do_step(3).AndReturn(None)
self.m.ReplayAll()
tr = scheduler.TaskRunner(task)
tr.start()
for step in tr.as_task():
pass
self.assertTrue(tr.done())
def test_run_as_task_cancel(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
self.m.ReplayAll()
tr = scheduler.TaskRunner(task)
rt = tr.as_task()
next(rt)
rt.close()
self.assertTrue(tr.done())
def test_run_as_task_exception(self):
class TestException(Exception):
pass
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
self.m.ReplayAll()
tr = scheduler.TaskRunner(task)
rt = tr.as_task()
next(rt)
self.assertRaises(TestException, rt.throw, TestException)
self.assertTrue(tr.done())
def test_run_as_task_swallow_exception(self):
class TestException(Exception):
pass
def task():
try:
yield
except TestException:
yield
tr = scheduler.TaskRunner(task)
rt = tr.as_task()
next(rt)
rt.throw(TestException)
self.assertFalse(tr.done())
self.assertRaises(StopIteration, next, rt)
self.assertTrue(tr.done())
def test_run_delays(self):
task = DummyTask(delays=itertools.repeat(2))
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(0).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(3).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
scheduler.TaskRunner(task)()
def test_run_delays_dynamic(self):
task = DummyTask(delays=[2, 4, 1])
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(0).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(3).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
scheduler.TaskRunner(task)()
def test_run_wait_time(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(0).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(42).AndReturn(None)
task.do_step(3).AndReturn(None)
scheduler.TaskRunner._sleep(42).AndReturn(None)
self.m.ReplayAll()
scheduler.TaskRunner(task)(wait_time=42)
def test_start_run(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(3).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start()
runner.run_to_completion()
def test_start_run_wait_time(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(24).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(24).AndReturn(None)
task.do_step(3).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start()
runner.run_to_completion(wait_time=24)
def test_run_progress(self):
progress_count = []
def progress():
progress_count.append(None)
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(0).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(3).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
scheduler.TaskRunner(task)(progress_callback=progress)
self.assertEqual(task.num_steps, len(progress_count))
def test_start_run_progress(self):
progress_count = []
def progress():
progress_count.append(None)
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(3).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start()
runner.run_to_completion(progress_callback=progress)
self.assertEqual(task.num_steps - 1, len(progress_count))
def test_run_as_task_progress(self):
progress_count = []
def progress():
progress_count.append(None)
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
task.do_step(3).AndReturn(None)
self.m.ReplayAll()
tr = scheduler.TaskRunner(task)
rt = tr.as_task(progress_callback=progress)
for step in rt:
pass
self.assertEqual(task.num_steps, len(progress_count))
def test_run_progress_exception(self):
class TestException(Exception):
pass
progress_count = []
def progress():
if progress_count:
raise TestException
progress_count.append(None)
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(0).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
self.assertRaises(TestException, scheduler.TaskRunner(task),
progress_callback=progress)
self.assertEqual(1, len(progress_count))
def test_start_run_progress_exception(self):
class TestException(Exception):
pass
progress_count = []
def progress():
if progress_count:
raise TestException
progress_count.append(None)
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(3).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start()
self.assertRaises(TestException, runner.run_to_completion,
progress_callback=progress)
self.assertEqual(1, len(progress_count))
def test_run_as_task_progress_exception(self):
class TestException(Exception):
pass
progress_count = []
def progress():
if progress_count:
raise TestException
progress_count.append(None)
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
self.m.ReplayAll()
tr = scheduler.TaskRunner(task)
rt = tr.as_task(progress_callback=progress)
next(rt)
next(rt)
self.assertRaises(TestException, next, rt)
self.assertEqual(1, len(progress_count))
def test_run_progress_exception_swallow(self):
class TestException(Exception):
pass
progress_count = []
def progress():
try:
if not progress_count:
raise TestException
finally:
progress_count.append(None)
def task():
try:
yield
except TestException:
yield
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
scheduler.TaskRunner._sleep(0).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
scheduler.TaskRunner(task)(progress_callback=progress)
self.assertEqual(2, len(progress_count))
def test_start_run_progress_exception_swallow(self):
class TestException(Exception):
pass
progress_count = []
def progress():
try:
if not progress_count:
raise TestException
finally:
progress_count.append(None)
def task():
yield
try:
yield
except TestException:
yield
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
scheduler.TaskRunner._sleep(1).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start()
runner.run_to_completion(progress_callback=progress)
self.assertEqual(2, len(progress_count))
def test_run_as_task_progress_exception_swallow(self):
class TestException(Exception):
pass
progress_count = []
def progress():
try:
if not progress_count:
raise TestException
finally:
progress_count.append(None)
def task():
try:
yield
except TestException:
yield
tr = scheduler.TaskRunner(task)
rt = tr.as_task(progress_callback=progress)
next(rt)
next(rt)
self.assertRaises(StopIteration, next, rt)
self.assertEqual(2, len(progress_count))
def test_sleep(self):
sleep_time = 42
self.m.StubOutWithMock(eventlet, 'sleep')
eventlet.sleep(0).AndReturn(None)
eventlet.sleep(sleep_time).MultipleTimes().AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(DummyTask())
runner(wait_time=sleep_time)
def test_sleep_zero(self):
self.m.StubOutWithMock(eventlet, 'sleep')
eventlet.sleep(0).MultipleTimes().AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(DummyTask())
runner(wait_time=0)
def test_sleep_none(self):
self.m.StubOutWithMock(eventlet, 'sleep')
self.m.ReplayAll()
runner = scheduler.TaskRunner(DummyTask())
runner(wait_time=None)
def test_args(self):
args = ['foo', 'bar']
kwargs = {'baz': 'quux', 'blarg': 'wibble'}
self.m.StubOutWithMock(DummyTask, '__call__')
task = DummyTask()
task(*args, **kwargs)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task, *args, **kwargs)
runner(wait_time=None)
def test_non_callable(self):
self.assertRaises(AssertionError, scheduler.TaskRunner, object())
def test_stepping(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
task.do_step(3).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start()
self.assertFalse(runner.step())
self.assertTrue(runner)
self.assertFalse(runner.step())
self.assertTrue(runner.step())
self.assertFalse(runner)
def test_start_no_steps(self):
task = DummyTask(0)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start()
self.assertTrue(runner.done())
self.assertTrue(runner.step())
def test_start_only(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
self.assertFalse(runner.started())
runner.start()
self.assertTrue(runner.started())
def test_double_start(self):
runner = scheduler.TaskRunner(DummyTask())
runner.start()
self.assertRaises(AssertionError, runner.start)
def test_start_cancelled(self):
runner = scheduler.TaskRunner(DummyTask())
runner.cancel()
self.assertRaises(AssertionError, runner.start)
def test_call_double_start(self):
runner = scheduler.TaskRunner(DummyTask())
runner(wait_time=None)
self.assertRaises(AssertionError, runner.start)
def test_start_function(self):
def task():
pass
runner = scheduler.TaskRunner(task)
runner.start()
self.assertTrue(runner.started())
self.assertTrue(runner.done())
self.assertTrue(runner.step())
def test_repeated_done(self):
task = DummyTask(0)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start()
self.assertTrue(runner.step())
self.assertTrue(runner.step())
def test_timeout(self):
st = timeutils.wallclock()
def task():
while True:
yield
self.m.StubOutWithMock(timeutils, 'wallclock')
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.5)
timeutils.wallclock().AndReturn(st + 1.5)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start(timeout=1)
self.assertTrue(runner)
self.assertRaises(scheduler.Timeout, runner.step)
def test_timeout_return(self):
st = timeutils.wallclock()
def task():
while True:
try:
yield
except scheduler.Timeout:
return
self.m.StubOutWithMock(timeutils, 'wallclock')
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.5)
timeutils.wallclock().AndReturn(st + 1.5)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start(timeout=1)
self.assertTrue(runner)
self.assertTrue(runner.step())
self.assertFalse(runner)
def test_timeout_swallowed(self):
st = timeutils.wallclock()
def task():
while True:
try:
yield
except scheduler.Timeout:
yield
self.fail('Task still running')
self.m.StubOutWithMock(timeutils, 'wallclock')
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.5)
timeutils.wallclock().AndReturn(st + 1.5)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start(timeout=1)
self.assertTrue(runner)
self.assertTrue(runner.step())
self.assertFalse(runner)
self.assertTrue(runner.step())
def test_as_task_timeout(self):
st = timeutils.wallclock()
def task():
while True:
yield
self.m.StubOutWithMock(timeutils, 'wallclock')
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.5)
timeutils.wallclock().AndReturn(st + 1.5)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
rt = runner.as_task(timeout=1)
next(rt)
self.assertTrue(runner)
self.assertRaises(scheduler.Timeout, next, rt)
def test_as_task_timeout_shorter(self):
st = timeutils.wallclock()
def task():
while True:
yield
self.m.StubOutWithMock(timeutils, 'wallclock')
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.5)
timeutils.wallclock().AndReturn(st + 0.7)
timeutils.wallclock().AndReturn(st + 1.6)
timeutils.wallclock().AndReturn(st + 2.6)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start(timeout=10)
self.assertTrue(runner)
rt = runner.as_task(timeout=1)
next(rt)
self.assertRaises(scheduler.Timeout, next, rt)
def test_as_task_timeout_longer(self):
st = timeutils.wallclock()
def task():
while True:
yield
self.m.StubOutWithMock(timeutils, 'wallclock')
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.5)
timeutils.wallclock().AndReturn(st + 0.6)
timeutils.wallclock().AndReturn(st + 1.5)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start(timeout=1)
self.assertTrue(runner)
rt = runner.as_task(timeout=10)
self.assertRaises(scheduler.Timeout, next, rt)
def test_cancel_not_started(self):
task = DummyTask(1)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
self.assertFalse(runner.started())
runner.cancel()
self.assertTrue(runner.done())
def test_cancel_done(self):
task = DummyTask(1)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
self.assertFalse(runner.started())
runner.start()
self.assertTrue(runner.started())
self.assertTrue(runner.step())
self.assertTrue(runner.done())
runner.cancel()
self.assertTrue(runner.done())
self.assertTrue(runner.step())
def test_cancel(self):
task = DummyTask(3)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
self.assertFalse(runner.started())
runner.start()
self.assertTrue(runner.started())
self.assertFalse(runner.step())
runner.cancel()
self.assertTrue(runner.step())
def test_cancel_grace_period(self):
st = timeutils.wallclock()
task = DummyTask(5)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
self.m.StubOutWithMock(timeutils, 'wallclock')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.5)
task.do_step(3).AndReturn(None)
timeutils.wallclock().AndReturn(st + 1.0)
task.do_step(4).AndReturn(None)
timeutils.wallclock().AndReturn(st + 1.5)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
self.assertFalse(runner.started())
runner.start()
self.assertTrue(runner.started())
self.assertFalse(runner.step())
runner.cancel(grace_period=1.0)
self.assertFalse(runner.step())
self.assertFalse(runner.step())
self.assertTrue(runner.step())
def test_cancel_grace_period_before_timeout(self):
st = timeutils.wallclock()
task = DummyTask(5)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
self.m.StubOutWithMock(timeutils, 'wallclock')
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.1)
task.do_step(1).AndReturn(None)
timeutils.wallclock().AndReturn(st + 0.2)
task.do_step(2).AndReturn(None)
timeutils.wallclock().AndReturn(st + 0.2)
timeutils.wallclock().AndReturn(st + 0.5)
task.do_step(3).AndReturn(None)
timeutils.wallclock().AndReturn(st + 1.0)
task.do_step(4).AndReturn(None)
timeutils.wallclock().AndReturn(st + 1.5)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
self.assertFalse(runner.started())
runner.start(timeout=10)
self.assertTrue(runner.started())
self.assertFalse(runner.step())
runner.cancel(grace_period=1.0)
self.assertFalse(runner.step())
self.assertFalse(runner.step())
self.assertTrue(runner.step())
def test_cancel_grace_period_after_timeout(self):
st = timeutils.wallclock()
task = DummyTask(5)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
self.m.StubOutWithMock(timeutils, 'wallclock')
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.1)
task.do_step(1).AndReturn(None)
timeutils.wallclock().AndReturn(st + 0.2)
task.do_step(2).AndReturn(None)
timeutils.wallclock().AndReturn(st + 0.2)
timeutils.wallclock().AndReturn(st + 0.5)
task.do_step(3).AndReturn(None)
timeutils.wallclock().AndReturn(st + 1.0)
task.do_step(4).AndReturn(None)
timeutils.wallclock().AndReturn(st + 1.5)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
self.assertFalse(runner.started())
runner.start(timeout=1.25)
self.assertTrue(runner.started())
self.assertFalse(runner.step())
runner.cancel(grace_period=3)
self.assertFalse(runner.step())
self.assertFalse(runner.step())
self.assertRaises(scheduler.Timeout, runner.step)
def test_cancel_grace_period_not_started(self):
task = DummyTask(1)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
self.assertFalse(runner.started())
runner.cancel(grace_period=0.5)
self.assertTrue(runner.done())
class TimeoutTest(common.HeatTestCase):
def test_compare(self):
task = scheduler.TaskRunner(DummyTask())
earlier = scheduler.Timeout(task, 10)
eventlet.sleep(0.01)
later = scheduler.Timeout(task, 10)
self.assertTrue(earlier < later)
self.assertTrue(later > earlier)
self.assertEqual(earlier, earlier)
self.assertNotEqual(earlier, later)
class DescriptionTest(common.HeatTestCase):
def setUp(self):
super(DescriptionTest, self).setUp()
self.addCleanup(self.m.VerifyAll)
def test_func(self):
def f():
pass
self.assertEqual('f', scheduler.task_description(f))
def test_lambda(self):
l = lambda: None
self.assertEqual('<lambda>', scheduler.task_description(l))
def test_method(self):
class C(object):
def __str__(self):
return 'C "o"'
def __repr__(self):
return 'o'
def m(self):
pass
self.assertEqual('m from C "o"', scheduler.task_description(C().m))
def test_object(self):
class C(object):
def __str__(self):
return 'C "o"'
def __repr__(self):
return 'o'
def __call__(self):
pass
self.assertEqual('o', scheduler.task_description(C()))
def test_unicode(self):
@repr_wrapper
@six.python_2_unicode_compatible
class C(object):
def __str__(self):
return u'C "\u2665"'
def __repr__(self):
return u'\u2665'
def __call__(self):
pass
def m(self):
pass
self.assertEqual(u'm from C "\u2665"',
scheduler.task_description(C().m))
self.assertEqual(u'\u2665',
scheduler.task_description(C()))
class WrapperTaskTest(common.HeatTestCase):
def setUp(self):
super(WrapperTaskTest, self).setUp()
self.addCleanup(self.m.VerifyAll)
def test_wrap(self):
child_tasks = [DummyTask() for i in range(3)]
@scheduler.wrappertask
def task():
for child_task in child_tasks:
yield child_task()
yield
for child_task in child_tasks:
self.m.StubOutWithMock(child_task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
scheduler.TaskRunner._sleep(0).AndReturn(None)
for child_task in child_tasks:
child_task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
child_task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
child_task.do_step(3).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
scheduler.TaskRunner(task)()
def test_parent_yield_value(self):
@scheduler.wrappertask
def parent_task():
yield
yield 3
yield iter([1, 2, 4])
task = parent_task()
self.assertIsNone(next(task))
self.assertEqual(3, next(task))
self.assertEqual([1, 2, 4], list(next(task)))
def test_child_yield_value(self):
def child_task():
yield
yield 3
yield iter([1, 2, 4])
@scheduler.wrappertask
def parent_task():
yield child_task()
task = parent_task()
self.assertIsNone(next(task))
self.assertEqual(3, next(task))
self.assertEqual([1, 2, 4], list(next(task)))
def test_child_exception(self):
class MyException(Exception):
pass
def child_task():
yield
raise MyException()
@scheduler.wrappertask
def parent_task():
try:
yield child_task()
except MyException:
raise
else:
self.fail('No exception raised in parent_task')
task = parent_task()
next(task)
self.assertRaises(MyException, next, task)
def test_child_exception_exit(self):
class MyException(Exception):
pass
def child_task():
yield
raise MyException()
@scheduler.wrappertask
def parent_task():
try:
yield child_task()
except MyException:
return
else:
self.fail('No exception raised in parent_task')
task = parent_task()
next(task)
self.assertRaises(StopIteration, next, task)
def test_child_exception_swallow(self):
class MyException(Exception):
pass
def child_task():
yield
raise MyException()
@scheduler.wrappertask
def parent_task():
try:
yield child_task()
except MyException:
yield
else:
self.fail('No exception raised in parent_task')
yield
task = parent_task()
next(task)
next(task)
def test_child_exception_swallow_next(self):
class MyException(Exception):
pass
def child_task():
yield
raise MyException()
dummy = DummyTask()
@scheduler.wrappertask
def parent_task():
try:
yield child_task()
except MyException:
pass
else:
self.fail('No exception raised in parent_task')
yield dummy()
task = parent_task()
next(task)
self.m.StubOutWithMock(dummy, 'do_step')
for i in range(1, dummy.num_steps + 1):
dummy.do_step(i).AndReturn(None)
self.m.ReplayAll()
for i in range(1, dummy.num_steps + 1):
next(task)
self.assertRaises(StopIteration, next, task)
def test_thrown_exception_swallow_next(self):
class MyException(Exception):
pass
dummy = DummyTask()
@scheduler.wrappertask
def child_task():
try:
yield
except MyException:
yield dummy()
else:
self.fail('No exception raised in child_task')
@scheduler.wrappertask
def parent_task():
yield child_task()
task = parent_task()
self.m.StubOutWithMock(dummy, 'do_step')
for i in range(1, dummy.num_steps + 1):
dummy.do_step(i).AndReturn(None)
self.m.ReplayAll()
next(task)
task.throw(MyException)
for i in range(2, dummy.num_steps + 1):
next(task)
self.assertRaises(StopIteration, next, task)
def test_thrown_exception_raise(self):
class MyException(Exception):
pass
dummy = DummyTask()
@scheduler.wrappertask
def child_task():
try:
yield
except MyException:
raise
else:
self.fail('No exception raised in child_task')
@scheduler.wrappertask
def parent_task():
try:
yield child_task()
except MyException:
yield dummy()
task = parent_task()
self.m.StubOutWithMock(dummy, 'do_step')
for i in range(1, dummy.num_steps + 1):
dummy.do_step(i).AndReturn(None)
self.m.ReplayAll()
next(task)
task.throw(MyException)
for i in range(2, dummy.num_steps + 1):
next(task)
self.assertRaises(StopIteration, next, task)
def test_thrown_exception_exit(self):
class MyException(Exception):
pass
dummy = DummyTask()
@scheduler.wrappertask
def child_task():
try:
yield
except MyException:
return
else:
self.fail('No exception raised in child_task')
@scheduler.wrappertask
def parent_task():
yield child_task()
yield dummy()
task = parent_task()
self.m.StubOutWithMock(dummy, 'do_step')
for i in range(1, dummy.num_steps + 1):
dummy.do_step(i).AndReturn(None)
self.m.ReplayAll()
next(task)
task.throw(MyException)
for i in range(2, dummy.num_steps + 1):
next(task)
self.assertRaises(StopIteration, next, task)
def test_parent_exception(self):
class MyException(Exception):
pass
def child_task():
yield
@scheduler.wrappertask
def parent_task():
yield child_task()
raise MyException()
task = parent_task()
next(task)
self.assertRaises(MyException, next, task)
def test_parent_throw(self):
class MyException(Exception):
pass
@scheduler.wrappertask
def parent_task():
try:
yield DummyTask()()
except MyException:
raise
else:
self.fail('No exception raised in parent_task')
task = parent_task()
next(task)
self.assertRaises(MyException, task.throw, MyException())
def test_parent_throw_exit(self):
class MyException(Exception):
pass
@scheduler.wrappertask
def parent_task():
try:
yield DummyTask()()
except MyException:
return
else:
self.fail('No exception raised in parent_task')
task = parent_task()
next(task)
self.assertRaises(StopIteration, task.throw, MyException())
def test_parent_cancel(self):
@scheduler.wrappertask
def parent_task():
try:
yield
except GeneratorExit:
raise
else:
self.fail('parent_task not closed')
task = parent_task()
next(task)
task.close()
def test_parent_cancel_exit(self):
@scheduler.wrappertask
def parent_task():
try:
yield
except GeneratorExit:
return
else:
self.fail('parent_task not closed')
task = parent_task()
next(task)
task.close()
def test_cancel(self):
def child_task():
try:
yield
except GeneratorExit:
raise
else:
self.fail('child_task not closed')
@scheduler.wrappertask
def parent_task():
try:
yield child_task()
except GeneratorExit:
raise
else:
self.fail('parent_task not closed')
task = parent_task()
next(task)
task.close()
def test_cancel_exit(self):
def child_task():
try:
yield
except GeneratorExit:
return
else:
self.fail('child_task not closed')
@scheduler.wrappertask
def parent_task():
try:
yield child_task()
except GeneratorExit:
raise
else:
self.fail('parent_task not closed')
task = parent_task()
next(task)
task.close()
def test_cancel_parent_exit(self):
def child_task():
try:
yield
except GeneratorExit:
return
else:
self.fail('child_task not closed')
@scheduler.wrappertask
def parent_task():
try:
yield child_task()
except GeneratorExit:
return
else:
self.fail('parent_task not closed')
task = parent_task()
next(task)
task.close()
| 30.103565 | 79 | 0.579531 |
import contextlib
import itertools
import eventlet
import six
from heat.common.i18n import repr_wrapper
from heat.common import timeutils
from heat.engine import dependencies
from heat.engine import scheduler
from heat.tests import common
class DummyTask(object):
def __init__(self, num_steps=3, delays=None):
self.num_steps = num_steps
if delays is not None:
self.delays = iter(delays)
else:
self.delays = itertools.repeat(None)
def __call__(self, *args, **kwargs):
for i in range(1, self.num_steps + 1):
self.do_step(i, *args, **kwargs)
yield next(self.delays)
def do_step(self, step_num, *args, **kwargs):
pass
class ExceptionGroupTest(common.HeatTestCase):
def test_contains_exceptions(self):
exception_group = scheduler.ExceptionGroup()
self.assertIsInstance(exception_group.exceptions, list)
def test_can_be_initialized_with_a_list_of_exceptions(self):
ex1 = Exception("ex 1")
ex2 = Exception("ex 2")
exception_group = scheduler.ExceptionGroup([ex1, ex2])
self.assertIn(ex1, exception_group.exceptions)
self.assertIn(ex2, exception_group.exceptions)
def test_can_add_exceptions_after_init(self):
ex = Exception()
exception_group = scheduler.ExceptionGroup()
exception_group.exceptions.append(ex)
self.assertIn(ex, exception_group.exceptions)
def test_str_representation_aggregates_all_exceptions(self):
ex1 = Exception("ex 1")
ex2 = Exception("ex 2")
exception_group = scheduler.ExceptionGroup([ex1, ex2])
self.assertEqual("['ex 1', 'ex 2']", six.text_type(exception_group))
class DependencyTaskGroupTest(common.HeatTestCase):
def setUp(self):
super(DependencyTaskGroupTest, self).setUp()
self.addCleanup(self.m.VerifyAll)
self.aggregate_exceptions = False
self.error_wait_time = None
self.reverse_order = False
@contextlib.contextmanager
def _dep_test(self, *edges):
dummy = DummyTask(getattr(self, 'steps', 3))
deps = dependencies.Dependencies(edges)
tg = scheduler.DependencyTaskGroup(
deps, dummy, reverse=self.reverse_order,
error_wait_time=self.error_wait_time,
aggregate_exceptions=self.aggregate_exceptions)
self.m.StubOutWithMock(dummy, 'do_step')
yield dummy
self.m.ReplayAll()
scheduler.TaskRunner(tg)(wait_time=None)
def test_no_steps(self):
self.steps = 0
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
with self._dep_test(('second', 'first')):
pass
def test_single_node(self):
with self._dep_test(('only', None)) as dummy:
dummy.do_step(1, 'only').AndReturn(None)
dummy.do_step(2, 'only').AndReturn(None)
dummy.do_step(3, 'only').AndReturn(None)
def test_disjoint(self):
with self._dep_test(('1', None), ('2', None)) as dummy:
dummy.do_step(1, '1').InAnyOrder('1')
dummy.do_step(1, '2').InAnyOrder('1')
dummy.do_step(2, '1').InAnyOrder('2')
dummy.do_step(2, '2').InAnyOrder('2')
dummy.do_step(3, '1').InAnyOrder('3')
dummy.do_step(3, '2').InAnyOrder('3')
def test_single_fwd(self):
with self._dep_test(('second', 'first')) as dummy:
dummy.do_step(1, 'first').AndReturn(None)
dummy.do_step(2, 'first').AndReturn(None)
dummy.do_step(3, 'first').AndReturn(None)
dummy.do_step(1, 'second').AndReturn(None)
dummy.do_step(2, 'second').AndReturn(None)
dummy.do_step(3, 'second').AndReturn(None)
def test_chain_fwd(self):
with self._dep_test(('third', 'second'),
('second', 'first')) as dummy:
dummy.do_step(1, 'first').AndReturn(None)
dummy.do_step(2, 'first').AndReturn(None)
dummy.do_step(3, 'first').AndReturn(None)
dummy.do_step(1, 'second').AndReturn(None)
dummy.do_step(2, 'second').AndReturn(None)
dummy.do_step(3, 'second').AndReturn(None)
dummy.do_step(1, 'third').AndReturn(None)
dummy.do_step(2, 'third').AndReturn(None)
dummy.do_step(3, 'third').AndReturn(None)
def test_diamond_fwd(self):
with self._dep_test(('last', 'mid1'), ('last', 'mid2'),
('mid1', 'first'), ('mid2', 'first')) as dummy:
dummy.do_step(1, 'first').AndReturn(None)
dummy.do_step(2, 'first').AndReturn(None)
dummy.do_step(3, 'first').AndReturn(None)
dummy.do_step(1, 'mid1').InAnyOrder('1')
dummy.do_step(1, 'mid2').InAnyOrder('1')
dummy.do_step(2, 'mid1').InAnyOrder('2')
dummy.do_step(2, 'mid2').InAnyOrder('2')
dummy.do_step(3, 'mid1').InAnyOrder('3')
dummy.do_step(3, 'mid2').InAnyOrder('3')
dummy.do_step(1, 'last').AndReturn(None)
dummy.do_step(2, 'last').AndReturn(None)
dummy.do_step(3, 'last').AndReturn(None)
def test_complex_fwd(self):
with self._dep_test(('last', 'mid1'), ('last', 'mid2'),
('mid1', 'mid3'), ('mid1', 'first'),
('mid3', 'first'), ('mid2', 'first')) as dummy:
dummy.do_step(1, 'first').AndReturn(None)
dummy.do_step(2, 'first').AndReturn(None)
dummy.do_step(3, 'first').AndReturn(None)
dummy.do_step(1, 'mid2').InAnyOrder('1')
dummy.do_step(1, 'mid3').InAnyOrder('1')
dummy.do_step(2, 'mid2').InAnyOrder('2')
dummy.do_step(2, 'mid3').InAnyOrder('2')
dummy.do_step(3, 'mid2').InAnyOrder('3')
dummy.do_step(3, 'mid3').InAnyOrder('3')
dummy.do_step(1, 'mid1').AndReturn(None)
dummy.do_step(2, 'mid1').AndReturn(None)
dummy.do_step(3, 'mid1').AndReturn(None)
dummy.do_step(1, 'last').AndReturn(None)
dummy.do_step(2, 'last').AndReturn(None)
dummy.do_step(3, 'last').AndReturn(None)
def test_many_edges_fwd(self):
with self._dep_test(('last', 'e1'), ('last', 'mid1'), ('last', 'mid2'),
('mid1', 'e2'), ('mid1', 'mid3'),
('mid2', 'mid3'),
('mid3', 'e3')) as dummy:
dummy.do_step(1, 'e1').InAnyOrder('1edges')
dummy.do_step(1, 'e2').InAnyOrder('1edges')
dummy.do_step(1, 'e3').InAnyOrder('1edges')
dummy.do_step(2, 'e1').InAnyOrder('2edges')
dummy.do_step(2, 'e2').InAnyOrder('2edges')
dummy.do_step(2, 'e3').InAnyOrder('2edges')
dummy.do_step(3, 'e1').InAnyOrder('3edges')
dummy.do_step(3, 'e2').InAnyOrder('3edges')
dummy.do_step(3, 'e3').InAnyOrder('3edges')
dummy.do_step(1, 'mid3').AndReturn(None)
dummy.do_step(2, 'mid3').AndReturn(None)
dummy.do_step(3, 'mid3').AndReturn(None)
dummy.do_step(1, 'mid2').InAnyOrder('1mid')
dummy.do_step(1, 'mid1').InAnyOrder('1mid')
dummy.do_step(2, 'mid2').InAnyOrder('2mid')
dummy.do_step(2, 'mid1').InAnyOrder('2mid')
dummy.do_step(3, 'mid2').InAnyOrder('3mid')
dummy.do_step(3, 'mid1').InAnyOrder('3mid')
dummy.do_step(1, 'last').AndReturn(None)
dummy.do_step(2, 'last').AndReturn(None)
dummy.do_step(3, 'last').AndReturn(None)
def test_dbldiamond_fwd(self):
with self._dep_test(('last', 'a1'), ('last', 'a2'),
('a1', 'b1'), ('a2', 'b1'), ('a2', 'b2'),
('b1', 'first'), ('b2', 'first')) as dummy:
dummy.do_step(1, 'first').AndReturn(None)
dummy.do_step(2, 'first').AndReturn(None)
dummy.do_step(3, 'first').AndReturn(None)
dummy.do_step(1, 'b1').InAnyOrder('1b')
dummy.do_step(1, 'b2').InAnyOrder('1b')
dummy.do_step(2, 'b1').InAnyOrder('2b')
dummy.do_step(2, 'b2').InAnyOrder('2b')
dummy.do_step(3, 'b1').InAnyOrder('3b')
dummy.do_step(3, 'b2').InAnyOrder('3b')
dummy.do_step(1, 'a1').InAnyOrder('1a')
dummy.do_step(1, 'a2').InAnyOrder('1a')
dummy.do_step(2, 'a1').InAnyOrder('2a')
dummy.do_step(2, 'a2').InAnyOrder('2a')
dummy.do_step(3, 'a1').InAnyOrder('3a')
dummy.do_step(3, 'a2').InAnyOrder('3a')
dummy.do_step(1, 'last').AndReturn(None)
dummy.do_step(2, 'last').AndReturn(None)
dummy.do_step(3, 'last').AndReturn(None)
def test_circular_deps(self):
d = dependencies.Dependencies([('first', 'second'),
('second', 'third'),
('third', 'first')])
self.assertRaises(dependencies.CircularDependencyException,
scheduler.DependencyTaskGroup, d)
def test_aggregate_exceptions_raises_all_at_the_end(self):
def run_tasks_with_exceptions(e1=None, e2=None):
self.aggregate_exceptions = True
tasks = (('A', None), ('B', None), ('C', None))
with self._dep_test(*tasks) as dummy:
dummy.do_step(1, 'A').InAnyOrder('1')
dummy.do_step(1, 'B').InAnyOrder('1')
dummy.do_step(1, 'C').InAnyOrder('1').AndRaise(e1)
dummy.do_step(2, 'A').InAnyOrder('2')
dummy.do_step(2, 'B').InAnyOrder('2').AndRaise(e2)
dummy.do_step(3, 'A').InAnyOrder('3')
e1 = Exception('e1')
e2 = Exception('e2')
exc = self.assertRaises(scheduler.ExceptionGroup,
run_tasks_with_exceptions, e1, e2)
self.assertEqual(set([e1, e2]), set(exc.exceptions))
def test_aggregate_exceptions_cancels_dependent_tasks_recursively(self):
def run_tasks_with_exceptions(e1=None, e2=None):
self.aggregate_exceptions = True
tasks = (('A', None), ('B', 'A'), ('C', 'B'))
with self._dep_test(*tasks) as dummy:
dummy.do_step(1, 'A').AndRaise(e1)
e1 = Exception('e1')
exc = self.assertRaises(scheduler.ExceptionGroup,
run_tasks_with_exceptions, e1)
self.assertEqual([e1], exc.exceptions)
def test_aggregate_exceptions_cancels_tasks_in_reverse_order(self):
def run_tasks_with_exceptions(e1=None, e2=None):
self.reverse_order = True
self.aggregate_exceptions = True
tasks = (('A', None), ('B', 'A'), ('C', 'B'))
with self._dep_test(*tasks) as dummy:
dummy.do_step(1, 'C').AndRaise(e1)
e1 = Exception('e1')
exc = self.assertRaises(scheduler.ExceptionGroup,
run_tasks_with_exceptions, e1)
self.assertEqual([e1], exc.exceptions)
def test_exceptions_on_cancel(self):
class TestException(Exception):
pass
class ExceptionOnExit(Exception):
pass
cancelled = []
def task_func(arg):
for i in range(4):
if i > 1:
raise TestException
try:
yield
except GeneratorExit:
cancelled.append(arg)
raise ExceptionOnExit
tasks = (('A', None), ('B', None), ('C', None))
deps = dependencies.Dependencies(tasks)
tg = scheduler.DependencyTaskGroup(deps, task_func)
task = tg()
next(task)
next(task)
self.assertRaises(TestException, next, task)
self.assertEqual(len(tasks) - 1, len(cancelled))
def test_exception_grace_period(self):
e1 = Exception('e1')
def run_tasks_with_exceptions():
self.error_wait_time = 5
tasks = (('A', None), ('B', None), ('C', 'A'))
with self._dep_test(*tasks) as dummy:
dummy.do_step(1, 'A').InAnyOrder('1')
dummy.do_step(1, 'B').InAnyOrder('1')
dummy.do_step(2, 'A').InAnyOrder('2').AndRaise(e1)
dummy.do_step(2, 'B').InAnyOrder('2')
dummy.do_step(3, 'B')
exc = self.assertRaises(type(e1), run_tasks_with_exceptions)
self.assertEqual(e1, exc)
def test_exception_grace_period_expired(self):
e1 = Exception('e1')
def run_tasks_with_exceptions():
self.steps = 5
self.error_wait_time = 0.05
def sleep():
eventlet.sleep(self.error_wait_time)
tasks = (('A', None), ('B', None), ('C', 'A'))
with self._dep_test(*tasks) as dummy:
dummy.do_step(1, 'A').InAnyOrder('1')
dummy.do_step(1, 'B').InAnyOrder('1')
dummy.do_step(2, 'A').InAnyOrder('2').AndRaise(e1)
dummy.do_step(2, 'B').InAnyOrder('2')
dummy.do_step(3, 'B')
dummy.do_step(4, 'B').WithSideEffects(sleep)
exc = self.assertRaises(type(e1), run_tasks_with_exceptions)
self.assertEqual(e1, exc)
def test_exception_grace_period_per_task(self):
e1 = Exception('e1')
def get_wait_time(key):
if key == 'B':
return 5
else:
return None
def run_tasks_with_exceptions():
self.error_wait_time = get_wait_time
tasks = (('A', None), ('B', None), ('C', 'A'))
with self._dep_test(*tasks) as dummy:
dummy.do_step(1, 'A').InAnyOrder('1')
dummy.do_step(1, 'B').InAnyOrder('1')
dummy.do_step(2, 'A').InAnyOrder('2').AndRaise(e1)
dummy.do_step(2, 'B').InAnyOrder('2')
dummy.do_step(3, 'B')
exc = self.assertRaises(type(e1), run_tasks_with_exceptions)
self.assertEqual(e1, exc)
def test_thrown_exception_order(self):
e1 = Exception('e1')
e2 = Exception('e2')
tasks = (('A', None), ('B', None), ('C', 'A'))
deps = dependencies.Dependencies(tasks)
tg = scheduler.DependencyTaskGroup(
deps, DummyTask(), reverse=self.reverse_order,
error_wait_time=1,
aggregate_exceptions=self.aggregate_exceptions)
task = tg()
next(task)
task.throw(e1)
next(task)
tg.error_wait_time = None
exc = self.assertRaises(type(e2), task.throw, e2)
self.assertIs(e2, exc)
class TaskTest(common.HeatTestCase):
def setUp(self):
super(TaskTest, self).setUp()
scheduler.ENABLE_SLEEP = True
self.addCleanup(self.m.VerifyAll)
def test_run(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(0).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(3).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
scheduler.TaskRunner(task)()
def test_run_as_task(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
task.do_step(3).AndReturn(None)
self.m.ReplayAll()
tr = scheduler.TaskRunner(task)
rt = tr.as_task()
for step in rt:
pass
self.assertTrue(tr.done())
def test_run_as_task_started(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
task.do_step(3).AndReturn(None)
self.m.ReplayAll()
tr = scheduler.TaskRunner(task)
tr.start()
for step in tr.as_task():
pass
self.assertTrue(tr.done())
def test_run_as_task_cancel(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
self.m.ReplayAll()
tr = scheduler.TaskRunner(task)
rt = tr.as_task()
next(rt)
rt.close()
self.assertTrue(tr.done())
def test_run_as_task_exception(self):
class TestException(Exception):
pass
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
self.m.ReplayAll()
tr = scheduler.TaskRunner(task)
rt = tr.as_task()
next(rt)
self.assertRaises(TestException, rt.throw, TestException)
self.assertTrue(tr.done())
def test_run_as_task_swallow_exception(self):
class TestException(Exception):
pass
def task():
try:
yield
except TestException:
yield
tr = scheduler.TaskRunner(task)
rt = tr.as_task()
next(rt)
rt.throw(TestException)
self.assertFalse(tr.done())
self.assertRaises(StopIteration, next, rt)
self.assertTrue(tr.done())
def test_run_delays(self):
task = DummyTask(delays=itertools.repeat(2))
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(0).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(3).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
scheduler.TaskRunner(task)()
def test_run_delays_dynamic(self):
task = DummyTask(delays=[2, 4, 1])
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(0).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(3).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
scheduler.TaskRunner(task)()
def test_run_wait_time(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(0).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(42).AndReturn(None)
task.do_step(3).AndReturn(None)
scheduler.TaskRunner._sleep(42).AndReturn(None)
self.m.ReplayAll()
scheduler.TaskRunner(task)(wait_time=42)
def test_start_run(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(3).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start()
runner.run_to_completion()
def test_start_run_wait_time(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(24).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(24).AndReturn(None)
task.do_step(3).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start()
runner.run_to_completion(wait_time=24)
def test_run_progress(self):
progress_count = []
def progress():
progress_count.append(None)
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(0).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(3).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
scheduler.TaskRunner(task)(progress_callback=progress)
self.assertEqual(task.num_steps, len(progress_count))
def test_start_run_progress(self):
progress_count = []
def progress():
progress_count.append(None)
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(3).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start()
runner.run_to_completion(progress_callback=progress)
self.assertEqual(task.num_steps - 1, len(progress_count))
def test_run_as_task_progress(self):
progress_count = []
def progress():
progress_count.append(None)
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
task.do_step(3).AndReturn(None)
self.m.ReplayAll()
tr = scheduler.TaskRunner(task)
rt = tr.as_task(progress_callback=progress)
for step in rt:
pass
self.assertEqual(task.num_steps, len(progress_count))
def test_run_progress_exception(self):
class TestException(Exception):
pass
progress_count = []
def progress():
if progress_count:
raise TestException
progress_count.append(None)
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(0).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
self.assertRaises(TestException, scheduler.TaskRunner(task),
progress_callback=progress)
self.assertEqual(1, len(progress_count))
def test_start_run_progress_exception(self):
class TestException(Exception):
pass
progress_count = []
def progress():
if progress_count:
raise TestException
progress_count.append(None)
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
task.do_step(3).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start()
self.assertRaises(TestException, runner.run_to_completion,
progress_callback=progress)
self.assertEqual(1, len(progress_count))
def test_run_as_task_progress_exception(self):
class TestException(Exception):
pass
progress_count = []
def progress():
if progress_count:
raise TestException
progress_count.append(None)
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
self.m.ReplayAll()
tr = scheduler.TaskRunner(task)
rt = tr.as_task(progress_callback=progress)
next(rt)
next(rt)
self.assertRaises(TestException, next, rt)
self.assertEqual(1, len(progress_count))
def test_run_progress_exception_swallow(self):
class TestException(Exception):
pass
progress_count = []
def progress():
try:
if not progress_count:
raise TestException
finally:
progress_count.append(None)
def task():
try:
yield
except TestException:
yield
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
scheduler.TaskRunner._sleep(0).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
scheduler.TaskRunner(task)(progress_callback=progress)
self.assertEqual(2, len(progress_count))
def test_start_run_progress_exception_swallow(self):
class TestException(Exception):
pass
progress_count = []
def progress():
try:
if not progress_count:
raise TestException
finally:
progress_count.append(None)
def task():
yield
try:
yield
except TestException:
yield
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
scheduler.TaskRunner._sleep(1).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start()
runner.run_to_completion(progress_callback=progress)
self.assertEqual(2, len(progress_count))
def test_run_as_task_progress_exception_swallow(self):
class TestException(Exception):
pass
progress_count = []
def progress():
try:
if not progress_count:
raise TestException
finally:
progress_count.append(None)
def task():
try:
yield
except TestException:
yield
tr = scheduler.TaskRunner(task)
rt = tr.as_task(progress_callback=progress)
next(rt)
next(rt)
self.assertRaises(StopIteration, next, rt)
self.assertEqual(2, len(progress_count))
def test_sleep(self):
sleep_time = 42
self.m.StubOutWithMock(eventlet, 'sleep')
eventlet.sleep(0).AndReturn(None)
eventlet.sleep(sleep_time).MultipleTimes().AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(DummyTask())
runner(wait_time=sleep_time)
def test_sleep_zero(self):
self.m.StubOutWithMock(eventlet, 'sleep')
eventlet.sleep(0).MultipleTimes().AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(DummyTask())
runner(wait_time=0)
def test_sleep_none(self):
self.m.StubOutWithMock(eventlet, 'sleep')
self.m.ReplayAll()
runner = scheduler.TaskRunner(DummyTask())
runner(wait_time=None)
def test_args(self):
args = ['foo', 'bar']
kwargs = {'baz': 'quux', 'blarg': 'wibble'}
self.m.StubOutWithMock(DummyTask, '__call__')
task = DummyTask()
task(*args, **kwargs)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task, *args, **kwargs)
runner(wait_time=None)
def test_non_callable(self):
self.assertRaises(AssertionError, scheduler.TaskRunner, object())
def test_stepping(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
task.do_step(3).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start()
self.assertFalse(runner.step())
self.assertTrue(runner)
self.assertFalse(runner.step())
self.assertTrue(runner.step())
self.assertFalse(runner)
def test_start_no_steps(self):
task = DummyTask(0)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start()
self.assertTrue(runner.done())
self.assertTrue(runner.step())
def test_start_only(self):
task = DummyTask()
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
self.assertFalse(runner.started())
runner.start()
self.assertTrue(runner.started())
def test_double_start(self):
runner = scheduler.TaskRunner(DummyTask())
runner.start()
self.assertRaises(AssertionError, runner.start)
def test_start_cancelled(self):
runner = scheduler.TaskRunner(DummyTask())
runner.cancel()
self.assertRaises(AssertionError, runner.start)
def test_call_double_start(self):
runner = scheduler.TaskRunner(DummyTask())
runner(wait_time=None)
self.assertRaises(AssertionError, runner.start)
def test_start_function(self):
def task():
pass
runner = scheduler.TaskRunner(task)
runner.start()
self.assertTrue(runner.started())
self.assertTrue(runner.done())
self.assertTrue(runner.step())
def test_repeated_done(self):
task = DummyTask(0)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start()
self.assertTrue(runner.step())
self.assertTrue(runner.step())
def test_timeout(self):
st = timeutils.wallclock()
def task():
while True:
yield
self.m.StubOutWithMock(timeutils, 'wallclock')
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.5)
timeutils.wallclock().AndReturn(st + 1.5)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start(timeout=1)
self.assertTrue(runner)
self.assertRaises(scheduler.Timeout, runner.step)
def test_timeout_return(self):
st = timeutils.wallclock()
def task():
while True:
try:
yield
except scheduler.Timeout:
return
self.m.StubOutWithMock(timeutils, 'wallclock')
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.5)
timeutils.wallclock().AndReturn(st + 1.5)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start(timeout=1)
self.assertTrue(runner)
self.assertTrue(runner.step())
self.assertFalse(runner)
def test_timeout_swallowed(self):
st = timeutils.wallclock()
def task():
while True:
try:
yield
except scheduler.Timeout:
yield
self.fail('Task still running')
self.m.StubOutWithMock(timeutils, 'wallclock')
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.5)
timeutils.wallclock().AndReturn(st + 1.5)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start(timeout=1)
self.assertTrue(runner)
self.assertTrue(runner.step())
self.assertFalse(runner)
self.assertTrue(runner.step())
def test_as_task_timeout(self):
st = timeutils.wallclock()
def task():
while True:
yield
self.m.StubOutWithMock(timeutils, 'wallclock')
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.5)
timeutils.wallclock().AndReturn(st + 1.5)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
rt = runner.as_task(timeout=1)
next(rt)
self.assertTrue(runner)
self.assertRaises(scheduler.Timeout, next, rt)
def test_as_task_timeout_shorter(self):
st = timeutils.wallclock()
def task():
while True:
yield
self.m.StubOutWithMock(timeutils, 'wallclock')
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.5)
timeutils.wallclock().AndReturn(st + 0.7)
timeutils.wallclock().AndReturn(st + 1.6)
timeutils.wallclock().AndReturn(st + 2.6)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start(timeout=10)
self.assertTrue(runner)
rt = runner.as_task(timeout=1)
next(rt)
self.assertRaises(scheduler.Timeout, next, rt)
def test_as_task_timeout_longer(self):
st = timeutils.wallclock()
def task():
while True:
yield
self.m.StubOutWithMock(timeutils, 'wallclock')
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.5)
timeutils.wallclock().AndReturn(st + 0.6)
timeutils.wallclock().AndReturn(st + 1.5)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
runner.start(timeout=1)
self.assertTrue(runner)
rt = runner.as_task(timeout=10)
self.assertRaises(scheduler.Timeout, next, rt)
def test_cancel_not_started(self):
task = DummyTask(1)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
self.assertFalse(runner.started())
runner.cancel()
self.assertTrue(runner.done())
def test_cancel_done(self):
task = DummyTask(1)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
self.assertFalse(runner.started())
runner.start()
self.assertTrue(runner.started())
self.assertTrue(runner.step())
self.assertTrue(runner.done())
runner.cancel()
self.assertTrue(runner.done())
self.assertTrue(runner.step())
def test_cancel(self):
task = DummyTask(3)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
self.assertFalse(runner.started())
runner.start()
self.assertTrue(runner.started())
self.assertFalse(runner.step())
runner.cancel()
self.assertTrue(runner.step())
def test_cancel_grace_period(self):
st = timeutils.wallclock()
task = DummyTask(5)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
self.m.StubOutWithMock(timeutils, 'wallclock')
task.do_step(1).AndReturn(None)
task.do_step(2).AndReturn(None)
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.5)
task.do_step(3).AndReturn(None)
timeutils.wallclock().AndReturn(st + 1.0)
task.do_step(4).AndReturn(None)
timeutils.wallclock().AndReturn(st + 1.5)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
self.assertFalse(runner.started())
runner.start()
self.assertTrue(runner.started())
self.assertFalse(runner.step())
runner.cancel(grace_period=1.0)
self.assertFalse(runner.step())
self.assertFalse(runner.step())
self.assertTrue(runner.step())
def test_cancel_grace_period_before_timeout(self):
st = timeutils.wallclock()
task = DummyTask(5)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
self.m.StubOutWithMock(timeutils, 'wallclock')
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.1)
task.do_step(1).AndReturn(None)
timeutils.wallclock().AndReturn(st + 0.2)
task.do_step(2).AndReturn(None)
timeutils.wallclock().AndReturn(st + 0.2)
timeutils.wallclock().AndReturn(st + 0.5)
task.do_step(3).AndReturn(None)
timeutils.wallclock().AndReturn(st + 1.0)
task.do_step(4).AndReturn(None)
timeutils.wallclock().AndReturn(st + 1.5)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
self.assertFalse(runner.started())
runner.start(timeout=10)
self.assertTrue(runner.started())
self.assertFalse(runner.step())
runner.cancel(grace_period=1.0)
self.assertFalse(runner.step())
self.assertFalse(runner.step())
self.assertTrue(runner.step())
def test_cancel_grace_period_after_timeout(self):
st = timeutils.wallclock()
task = DummyTask(5)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
self.m.StubOutWithMock(timeutils, 'wallclock')
timeutils.wallclock().AndReturn(st)
timeutils.wallclock().AndReturn(st + 0.1)
task.do_step(1).AndReturn(None)
timeutils.wallclock().AndReturn(st + 0.2)
task.do_step(2).AndReturn(None)
timeutils.wallclock().AndReturn(st + 0.2)
timeutils.wallclock().AndReturn(st + 0.5)
task.do_step(3).AndReturn(None)
timeutils.wallclock().AndReturn(st + 1.0)
task.do_step(4).AndReturn(None)
timeutils.wallclock().AndReturn(st + 1.5)
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
self.assertFalse(runner.started())
runner.start(timeout=1.25)
self.assertTrue(runner.started())
self.assertFalse(runner.step())
runner.cancel(grace_period=3)
self.assertFalse(runner.step())
self.assertFalse(runner.step())
self.assertRaises(scheduler.Timeout, runner.step)
def test_cancel_grace_period_not_started(self):
task = DummyTask(1)
self.m.StubOutWithMock(task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
self.m.ReplayAll()
runner = scheduler.TaskRunner(task)
self.assertFalse(runner.started())
runner.cancel(grace_period=0.5)
self.assertTrue(runner.done())
class TimeoutTest(common.HeatTestCase):
def test_compare(self):
task = scheduler.TaskRunner(DummyTask())
earlier = scheduler.Timeout(task, 10)
eventlet.sleep(0.01)
later = scheduler.Timeout(task, 10)
self.assertTrue(earlier < later)
self.assertTrue(later > earlier)
self.assertEqual(earlier, earlier)
self.assertNotEqual(earlier, later)
class DescriptionTest(common.HeatTestCase):
def setUp(self):
super(DescriptionTest, self).setUp()
self.addCleanup(self.m.VerifyAll)
def test_func(self):
def f():
pass
self.assertEqual('f', scheduler.task_description(f))
def test_lambda(self):
l = lambda: None
self.assertEqual('<lambda>', scheduler.task_description(l))
def test_method(self):
class C(object):
def __str__(self):
return 'C "o"'
def __repr__(self):
return 'o'
def m(self):
pass
self.assertEqual('m from C "o"', scheduler.task_description(C().m))
def test_object(self):
class C(object):
def __str__(self):
return 'C "o"'
def __repr__(self):
return 'o'
def __call__(self):
pass
self.assertEqual('o', scheduler.task_description(C()))
def test_unicode(self):
@repr_wrapper
@six.python_2_unicode_compatible
class C(object):
def __str__(self):
return u'C "\u2665"'
def __repr__(self):
return u'\u2665'
def __call__(self):
pass
def m(self):
pass
self.assertEqual(u'm from C "\u2665"',
scheduler.task_description(C().m))
self.assertEqual(u'\u2665',
scheduler.task_description(C()))
class WrapperTaskTest(common.HeatTestCase):
def setUp(self):
super(WrapperTaskTest, self).setUp()
self.addCleanup(self.m.VerifyAll)
def test_wrap(self):
child_tasks = [DummyTask() for i in range(3)]
@scheduler.wrappertask
def task():
for child_task in child_tasks:
yield child_task()
yield
for child_task in child_tasks:
self.m.StubOutWithMock(child_task, 'do_step')
self.m.StubOutWithMock(scheduler.TaskRunner, '_sleep')
scheduler.TaskRunner._sleep(0).AndReturn(None)
for child_task in child_tasks:
child_task.do_step(1).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
child_task.do_step(2).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
child_task.do_step(3).AndReturn(None)
scheduler.TaskRunner._sleep(1).AndReturn(None)
self.m.ReplayAll()
scheduler.TaskRunner(task)()
def test_parent_yield_value(self):
@scheduler.wrappertask
def parent_task():
yield
yield 3
yield iter([1, 2, 4])
task = parent_task()
self.assertIsNone(next(task))
self.assertEqual(3, next(task))
self.assertEqual([1, 2, 4], list(next(task)))
def test_child_yield_value(self):
def child_task():
yield
yield 3
yield iter([1, 2, 4])
@scheduler.wrappertask
def parent_task():
yield child_task()
task = parent_task()
self.assertIsNone(next(task))
self.assertEqual(3, next(task))
self.assertEqual([1, 2, 4], list(next(task)))
def test_child_exception(self):
class MyException(Exception):
pass
def child_task():
yield
raise MyException()
@scheduler.wrappertask
def parent_task():
try:
yield child_task()
except MyException:
raise
else:
self.fail('No exception raised in parent_task')
task = parent_task()
next(task)
self.assertRaises(MyException, next, task)
def test_child_exception_exit(self):
class MyException(Exception):
pass
def child_task():
yield
raise MyException()
@scheduler.wrappertask
def parent_task():
try:
yield child_task()
except MyException:
return
else:
self.fail('No exception raised in parent_task')
task = parent_task()
next(task)
self.assertRaises(StopIteration, next, task)
def test_child_exception_swallow(self):
class MyException(Exception):
pass
def child_task():
yield
raise MyException()
@scheduler.wrappertask
def parent_task():
try:
yield child_task()
except MyException:
yield
else:
self.fail('No exception raised in parent_task')
yield
task = parent_task()
next(task)
next(task)
def test_child_exception_swallow_next(self):
class MyException(Exception):
pass
def child_task():
yield
raise MyException()
dummy = DummyTask()
@scheduler.wrappertask
def parent_task():
try:
yield child_task()
except MyException:
pass
else:
self.fail('No exception raised in parent_task')
yield dummy()
task = parent_task()
next(task)
self.m.StubOutWithMock(dummy, 'do_step')
for i in range(1, dummy.num_steps + 1):
dummy.do_step(i).AndReturn(None)
self.m.ReplayAll()
for i in range(1, dummy.num_steps + 1):
next(task)
self.assertRaises(StopIteration, next, task)
def test_thrown_exception_swallow_next(self):
class MyException(Exception):
pass
dummy = DummyTask()
@scheduler.wrappertask
def child_task():
try:
yield
except MyException:
yield dummy()
else:
self.fail('No exception raised in child_task')
@scheduler.wrappertask
def parent_task():
yield child_task()
task = parent_task()
self.m.StubOutWithMock(dummy, 'do_step')
for i in range(1, dummy.num_steps + 1):
dummy.do_step(i).AndReturn(None)
self.m.ReplayAll()
next(task)
task.throw(MyException)
for i in range(2, dummy.num_steps + 1):
next(task)
self.assertRaises(StopIteration, next, task)
def test_thrown_exception_raise(self):
class MyException(Exception):
pass
dummy = DummyTask()
@scheduler.wrappertask
def child_task():
try:
yield
except MyException:
raise
else:
self.fail('No exception raised in child_task')
@scheduler.wrappertask
def parent_task():
try:
yield child_task()
except MyException:
yield dummy()
task = parent_task()
self.m.StubOutWithMock(dummy, 'do_step')
for i in range(1, dummy.num_steps + 1):
dummy.do_step(i).AndReturn(None)
self.m.ReplayAll()
next(task)
task.throw(MyException)
for i in range(2, dummy.num_steps + 1):
next(task)
self.assertRaises(StopIteration, next, task)
def test_thrown_exception_exit(self):
class MyException(Exception):
pass
dummy = DummyTask()
@scheduler.wrappertask
def child_task():
try:
yield
except MyException:
return
else:
self.fail('No exception raised in child_task')
@scheduler.wrappertask
def parent_task():
yield child_task()
yield dummy()
task = parent_task()
self.m.StubOutWithMock(dummy, 'do_step')
for i in range(1, dummy.num_steps + 1):
dummy.do_step(i).AndReturn(None)
self.m.ReplayAll()
next(task)
task.throw(MyException)
for i in range(2, dummy.num_steps + 1):
next(task)
self.assertRaises(StopIteration, next, task)
def test_parent_exception(self):
class MyException(Exception):
pass
def child_task():
yield
@scheduler.wrappertask
def parent_task():
yield child_task()
raise MyException()
task = parent_task()
next(task)
self.assertRaises(MyException, next, task)
def test_parent_throw(self):
class MyException(Exception):
pass
@scheduler.wrappertask
def parent_task():
try:
yield DummyTask()()
except MyException:
raise
else:
self.fail('No exception raised in parent_task')
task = parent_task()
next(task)
self.assertRaises(MyException, task.throw, MyException())
def test_parent_throw_exit(self):
class MyException(Exception):
pass
@scheduler.wrappertask
def parent_task():
try:
yield DummyTask()()
except MyException:
return
else:
self.fail('No exception raised in parent_task')
task = parent_task()
next(task)
self.assertRaises(StopIteration, task.throw, MyException())
def test_parent_cancel(self):
@scheduler.wrappertask
def parent_task():
try:
yield
except GeneratorExit:
raise
else:
self.fail('parent_task not closed')
task = parent_task()
next(task)
task.close()
def test_parent_cancel_exit(self):
@scheduler.wrappertask
def parent_task():
try:
yield
except GeneratorExit:
return
else:
self.fail('parent_task not closed')
task = parent_task()
next(task)
task.close()
def test_cancel(self):
def child_task():
try:
yield
except GeneratorExit:
raise
else:
self.fail('child_task not closed')
@scheduler.wrappertask
def parent_task():
try:
yield child_task()
except GeneratorExit:
raise
else:
self.fail('parent_task not closed')
task = parent_task()
next(task)
task.close()
def test_cancel_exit(self):
def child_task():
try:
yield
except GeneratorExit:
return
else:
self.fail('child_task not closed')
@scheduler.wrappertask
def parent_task():
try:
yield child_task()
except GeneratorExit:
raise
else:
self.fail('parent_task not closed')
task = parent_task()
next(task)
task.close()
def test_cancel_parent_exit(self):
def child_task():
try:
yield
except GeneratorExit:
return
else:
self.fail('child_task not closed')
@scheduler.wrappertask
def parent_task():
try:
yield child_task()
except GeneratorExit:
return
else:
self.fail('parent_task not closed')
task = parent_task()
next(task)
task.close()
| true | true |
f7109b54b5906c81389c8ba2757f70f271fff476 | 1,249 | py | Python | examples/servers_by_group.py | mphbig/cyberwatch_api_toolbox | 26058b0e25aea11b3e2d49efe5ad713db7164dc4 | [
"MIT"
] | null | null | null | examples/servers_by_group.py | mphbig/cyberwatch_api_toolbox | 26058b0e25aea11b3e2d49efe5ad713db7164dc4 | [
"MIT"
] | null | null | null | examples/servers_by_group.py | mphbig/cyberwatch_api_toolbox | 26058b0e25aea11b3e2d49efe5ad713db7164dc4 | [
"MIT"
] | null | null | null | """Example: Find all servers per group"""
import os
from configparser import ConfigParser
from cbw_api_toolbox.cbw_api import CBWApi
CONF = ConfigParser()
CONF.read(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', 'api.conf'))
CLIENT = CBWApi(CONF.get('cyberwatch', 'url'), CONF.get('cyberwatch', 'api_key'), CONF.get('cyberwatch', 'secret_key'))
CLIENT.ping()
SERVERS = CLIENT.servers()
CATEGORY_BY_GROUPS = {}
# append each server to a group by category dict
for server in SERVERS:
server = CLIENT.server(str(server.id))
for group in server.groups:
if group.name not in CATEGORY_BY_GROUPS:
CATEGORY_BY_GROUPS[group.name] = {}
concerned_group = CATEGORY_BY_GROUPS[group.name]
if server.category not in concerned_group:
concerned_group[server.category] = []
concerned_group[server.category].append(server)
for group in CATEGORY_BY_GROUPS:
print("--- GROUP : {0} ---".format(group))
for category in CATEGORY_BY_GROUPS[group]:
print("{0} : {1}".format(category, len(CATEGORY_BY_GROUPS[group][category])))
for server in CATEGORY_BY_GROUPS[group][category]:
print("{0} with hostname : {1}".format(category, server.hostname))
| 31.225 | 119 | 0.689351 |
import os
from configparser import ConfigParser
from cbw_api_toolbox.cbw_api import CBWApi
CONF = ConfigParser()
CONF.read(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', 'api.conf'))
CLIENT = CBWApi(CONF.get('cyberwatch', 'url'), CONF.get('cyberwatch', 'api_key'), CONF.get('cyberwatch', 'secret_key'))
CLIENT.ping()
SERVERS = CLIENT.servers()
CATEGORY_BY_GROUPS = {}
for server in SERVERS:
server = CLIENT.server(str(server.id))
for group in server.groups:
if group.name not in CATEGORY_BY_GROUPS:
CATEGORY_BY_GROUPS[group.name] = {}
concerned_group = CATEGORY_BY_GROUPS[group.name]
if server.category not in concerned_group:
concerned_group[server.category] = []
concerned_group[server.category].append(server)
for group in CATEGORY_BY_GROUPS:
print("--- GROUP : {0} ---".format(group))
for category in CATEGORY_BY_GROUPS[group]:
print("{0} : {1}".format(category, len(CATEGORY_BY_GROUPS[group][category])))
for server in CATEGORY_BY_GROUPS[group][category]:
print("{0} with hostname : {1}".format(category, server.hostname))
| true | true |
f7109b8dd0c34cf93c9e4fe141288fdbca2bd1bc | 1,541 | py | Python | tests/integration/goldens/logging/samples/generated_samples/logging_generated_logging_v2_config_service_v2_get_cmek_settings_sync.py | atulep/gapic-generator-python | ea6cfe6d6a4276894dba9b4a2efe458df86a08a0 | [
"Apache-2.0"
] | null | null | null | tests/integration/goldens/logging/samples/generated_samples/logging_generated_logging_v2_config_service_v2_get_cmek_settings_sync.py | atulep/gapic-generator-python | ea6cfe6d6a4276894dba9b4a2efe458df86a08a0 | [
"Apache-2.0"
] | null | null | null | tests/integration/goldens/logging/samples/generated_samples/logging_generated_logging_v2_config_service_v2_get_cmek_settings_sync.py | atulep/gapic-generator-python | ea6cfe6d6a4276894dba9b4a2efe458df86a08a0 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for GetCmekSettings
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-logging
# [START logging_generated_logging_v2_ConfigServiceV2_GetCmekSettings_sync]
from google.cloud import logging_v2
def sample_get_cmek_settings():
# Create a client
client = logging_v2.ConfigServiceV2Client()
# Initialize request argument(s)
project = "my-project-id"
name = f"projects/{project}/cmekSettings"
request = logging_v2.GetCmekSettingsRequest(
name=name,
)
# Make the request
response = client.get_cmek_settings(request=request)
# Handle response
print(response)
# [END logging_generated_logging_v2_ConfigServiceV2_GetCmekSettings_sync]
| 31.44898 | 85 | 0.757949 |
from google.cloud import logging_v2
def sample_get_cmek_settings():
client = logging_v2.ConfigServiceV2Client()
project = "my-project-id"
name = f"projects/{project}/cmekSettings"
request = logging_v2.GetCmekSettingsRequest(
name=name,
)
response = client.get_cmek_settings(request=request)
print(response)
| true | true |
f7109beea6f6b9d5cc94d3efdcd05188c671498a | 6,705 | py | Python | bindings/python/ensmallen_graph/datasets/string/azotobactervinelandii.py | caufieldjh/ensmallen_graph | 14e98b1cdbc73193a84a913d7d4f2b2b3eb2c43a | [
"MIT"
] | null | null | null | bindings/python/ensmallen_graph/datasets/string/azotobactervinelandii.py | caufieldjh/ensmallen_graph | 14e98b1cdbc73193a84a913d7d4f2b2b3eb2c43a | [
"MIT"
] | null | null | null | bindings/python/ensmallen_graph/datasets/string/azotobactervinelandii.py | caufieldjh/ensmallen_graph | 14e98b1cdbc73193a84a913d7d4f2b2b3eb2c43a | [
"MIT"
] | null | null | null | """
This file offers the methods to automatically retrieve the graph Azotobacter vinelandii.
The graph is automatically retrieved from the STRING repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 2021-02-02 20:28:09.024485
The undirected graph Azotobacter vinelandii has 4955 nodes and 578640 weighted
edges, of which none are self-loops. The graph is dense as it has a density
of 0.04715 and has 18 connected components, where the component with most
nodes has 4918 nodes and the component with the least nodes has 2 nodes.
The graph median node degree is 200, the mean node degree is 233.56, and
the node degree mode is 1. The top 5 most central nodes are 322710.Avin_29560
(degree 2047), 322710.Avin_00630 (degree 1761), 322710.Avin_51910 (degree
1573), 322710.Avin_51880 (degree 1360) and 322710.Avin_35230 (degree 1351).
References
---------------------
Please cite the following if you use the data:
@article{szklarczyk2019string,
title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets},
author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others},
journal={Nucleic acids research},
volume={47},
number={D1},
pages={D607--D613},
year={2019},
publisher={Oxford University Press}
}
Usage example
----------------------
The usage of this graph is relatively straightforward:
.. code:: python
# First import the function to retrieve the graph from the datasets
from ensmallen_graph.datasets.string import AzotobacterVinelandii
# Then load the graph
graph = AzotobacterVinelandii()
# Finally, you can do anything with it, for instance, compute its report:
print(graph)
# If you need to run a link prediction task with validation,
# you can split the graph using a connected holdout as follows:
train_graph, validation_graph = graph.connected_holdout(
# You can use an 80/20 split the holdout, for example.
train_size=0.8,
# The random state is used to reproduce the holdout.
random_state=42,
# Wether to show a loading bar.
verbose=True
)
# Remember that, if you need, you can enable the memory-time trade-offs:
train_graph.enable(
vector_sources=True,
vector_destinations=True,
vector_outbounds=True
)
# Consider using the methods made available in the Embiggen package
# to run graph embedding or link prediction tasks.
"""
from typing import Dict
from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph
from ...ensmallen_graph import EnsmallenGraph # pylint: disable=import-error
def AzotobacterVinelandii(
directed: bool = False,
verbose: int = 2,
cache_path: str = "graphs/string",
**additional_graph_kwargs: Dict
) -> EnsmallenGraph:
"""Return new instance of the Azotobacter vinelandii graph.
The graph is automatically retrieved from the STRING repository.
Parameters
-------------------
directed: bool = False,
Wether to load the graph as directed or undirected.
By default false.
verbose: int = 2,
Wether to show loading bars during the retrieval and building
of the graph.
cache_path: str = "graphs",
Where to store the downloaded graphs.
additional_graph_kwargs: Dict,
Additional graph kwargs.
Returns
-----------------------
Instace of Azotobacter vinelandii graph.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 2021-02-02 20:28:09.024485
The undirected graph Azotobacter vinelandii has 4955 nodes and 578640 weighted
edges, of which none are self-loops. The graph is dense as it has a density
of 0.04715 and has 18 connected components, where the component with most
nodes has 4918 nodes and the component with the least nodes has 2 nodes.
The graph median node degree is 200, the mean node degree is 233.56, and
the node degree mode is 1. The top 5 most central nodes are 322710.Avin_29560
(degree 2047), 322710.Avin_00630 (degree 1761), 322710.Avin_51910 (degree
1573), 322710.Avin_51880 (degree 1360) and 322710.Avin_35230 (degree 1351).
References
---------------------
Please cite the following if you use the data:
@article{szklarczyk2019string,
title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets},
author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others},
journal={Nucleic acids research},
volume={47},
number={D1},
pages={D607--D613},
year={2019},
publisher={Oxford University Press}
}
Usage example
----------------------
The usage of this graph is relatively straightforward:
.. code:: python
# First import the function to retrieve the graph from the datasets
from ensmallen_graph.datasets.string import AzotobacterVinelandii
# Then load the graph
graph = AzotobacterVinelandii()
# Finally, you can do anything with it, for instance, compute its report:
print(graph)
# If you need to run a link prediction task with validation,
# you can split the graph using a connected holdout as follows:
train_graph, validation_graph = graph.connected_holdout(
# You can use an 80/20 split the holdout, for example.
train_size=0.8,
# The random state is used to reproduce the holdout.
random_state=42,
# Wether to show a loading bar.
verbose=True
)
# Remember that, if you need, you can enable the memory-time trade-offs:
train_graph.enable(
vector_sources=True,
vector_destinations=True,
vector_outbounds=True
)
# Consider using the methods made available in the Embiggen package
# to run graph embedding or link prediction tasks.
"""
return AutomaticallyRetrievedGraph(
graph_name="AzotobacterVinelandii",
dataset="string",
directed=directed,
verbose=verbose,
cache_path=cache_path,
additional_graph_kwargs=additional_graph_kwargs
)()
| 35.47619 | 223 | 0.704549 | from typing import Dict
from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph
from ...ensmallen_graph import EnsmallenGraph
def AzotobacterVinelandii(
directed: bool = False,
verbose: int = 2,
cache_path: str = "graphs/string",
**additional_graph_kwargs: Dict
) -> EnsmallenGraph:
return AutomaticallyRetrievedGraph(
graph_name="AzotobacterVinelandii",
dataset="string",
directed=directed,
verbose=verbose,
cache_path=cache_path,
additional_graph_kwargs=additional_graph_kwargs
)()
| true | true |
f7109c9004fba9b86d167445229f2126cfcf0b42 | 295 | py | Python | movies/urls.py | huseyinyilmaz/django-movie-search | 29a989eb04d46319a7218daf776b8a0ec831845b | [
"MIT"
] | null | null | null | movies/urls.py | huseyinyilmaz/django-movie-search | 29a989eb04d46319a7218daf776b8a0ec831845b | [
"MIT"
] | null | null | null | movies/urls.py | huseyinyilmaz/django-movie-search | 29a989eb04d46319a7218daf776b8a0ec831845b | [
"MIT"
] | null | null | null | from django.conf.urls import url
from movies import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='movies-index'),
url(r'^name/$', views.NameSearchView.as_view(), name='movies-name-search'),
url(r'^id/$', views.IDSearchView.as_view(), name='movies-id-search'),
]
| 32.777778 | 79 | 0.681356 | from django.conf.urls import url
from movies import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='movies-index'),
url(r'^name/$', views.NameSearchView.as_view(), name='movies-name-search'),
url(r'^id/$', views.IDSearchView.as_view(), name='movies-id-search'),
]
| true | true |
f7109ced9584331781ae4dbeffdd97a368c81513 | 65,460 | py | Python | elevenclock/__init__.py | wanderleihuttel/ElevenClock | de4272a650111233acf36c909c7e269c8dc810d2 | [
"Apache-2.0"
] | null | null | null | elevenclock/__init__.py | wanderleihuttel/ElevenClock | de4272a650111233acf36c909c7e269c8dc810d2 | [
"Apache-2.0"
] | null | null | null | elevenclock/__init__.py | wanderleihuttel/ElevenClock | de4272a650111233acf36c909c7e269c8dc810d2 | [
"Apache-2.0"
] | null | null | null | try:
import time
FirstTime = time.time()
import os
import io
import sys
import time
import glob
import socket
import locale
import hashlib
import tempfile
import datetime
import subprocess
from ctypes import windll
from urllib.request import urlopen
try:
import psutil
importedPsutil = True
except ImportError:
importedPsutil = False
import win32gui
import win32api
import pythoncom
import win32process
import win32com.client
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import pyqtSignal as Signal
from pynput.keyboard import Controller, Key
from pynput.mouse import Controller as MouseController
from external.FramelessWindow import QFramelessDialog
from languages import *
import globals
old_stdout = sys.stdout
sys.stdout = buffer = io.StringIO()
from settings import *
from tools import *
import tools
from external.WnfReader import isFocusAssistEnabled, getNotificationNumber
blacklistedProcesses = ["msrdc.exe", "mstsc.exe", "CDViewer.exe", "wfica32.exe", "vmware-view.exe", "vmware.exe"]
blacklistedFullscreenApps = ("", "Program Manager", "NVIDIA GeForce Overlay", "ElenenClock_IgnoreFullscreenEvent") # The "" codes for titleless windows
seconddoubleclick = False
isRDPRunning = False
restartCount = 0
tempDir = ""
timeStr = ""
dateTimeFormat = ""
clocks = []
oldScreens = []
isFocusAssist = False
numOfNotifs = 0
print("---------------------------------------------------------------------------------------------------")
print("")
print(f" ElevenClock's {versionName} (v{version}) log: Select all the text and hit Ctrl+C to copy it")
print(f" All modules loaded successfully and sys.stdout patched correctly, starting main script")
print(f" Translator function set language to \"{langName}\"")
print("")
print("---------------------------------------------------------------------------------------------------")
print("")
print(" Log legend:")
print(" 🔵: Verbose")
print(" 🟢: Information")
print(" 🟡: Warning")
print(" 🟠: Handled unexpected exception")
print(" 🔴: Unhandled unexpected exception")
print(" 🟣: Handled expected exception")
print("")
def _(s) -> str:
return tools._(s)
def checkRDP():
def checkIfElevenClockRunning(processess, blacklistedProcess) -> bool:
for p_name in processess:
if p_name in blacklistedProcess:
print(f"🟡 Blacklisted procName {p_name} detected, hiding...")
return True
return False
global isRDPRunning
print("🔵 Starting RDP thread")
while True:
pythoncom.CoInitialize()
_wmi = win32com.client.GetObject('winmgmts:')
processes = _wmi.ExecQuery('Select Name from win32_process')
procs = [p.Name for p in processes]
isRDPRunning = checkIfElevenClockRunning(procs, blacklistedProcesses)
time.sleep(5)
def getMousePos():
try:
return QPoint(mController.position[0], mController.position[1])
except AttributeError:
print("🟠 Mouse thread returned AttributeError")
except Exception as e:
report(e)
def updateChecker():
updateIfPossible()
time.sleep(60)
while True:
updateIfPossible()
time.sleep(7200)
def updateIfPossible(force = False):
try:
if(not(getSettings("DisableAutoCheckForUpdates")) or force):
print("🔵 Starting update check")
integrityPass = False
dmname = socket.gethostbyname_ex("versions.somepythonthings.tk")[0]
if(dmname == "769432b9-3560-4f94-8f90-01c95844d994.id.repl.co" or getSettings("BypassDomainAuthCheck")): # Check provider IP to prevent exploits
integrityPass = True
try:
response = urlopen("https://versions.somepythonthings.tk/versions/elevenclock.ver" if not getSettings("AlternativeUpdateServerProvider") else "http://www.somepythonthings.tk/versions/elevenclock.ver")
except Exception as e:
report(e)
response = urlopen("http://www.somepythonthings.tk/versions/elevenclock.ver")
integrityPass = True
print("🔵 Version URL:", response.url)
response = response.read().decode("utf8")
new_version_number = response.split("///")[0]
provided_hash = response.split("///")[2].replace("\n", "").lower()
if float(new_version_number) > version:
print("🟢 Updates found!")
if(not(getSettings("DisableAutoInstallUpdates")) or force):
showNotif.infoSignal.emit(("ElevenClock Updater"), ("ElevenClock is downloading updates"))
if(integrityPass):
url = "https://github.com/martinet101/ElevenClock/releases/latest/download/ElevenClock.Installer.exe"
filedata = urlopen(url)
datatowrite = filedata.read()
filename = ""
with open(os.path.join(tempDir, "SomePythonThings-ElevenClock-Updater.exe"), 'wb') as f:
f.write(datatowrite)
filename = f.name
if(hashlib.sha256(datatowrite).hexdigest().lower() == provided_hash):
print("🔵 Hash: ", provided_hash)
print("🟢 Hash ok, starting update")
if(getSettings("EnableSilentUpdates") and not(force)):
mousePos = getMousePos()
time.sleep(5)
while mousePos != getMousePos():
print("🟡 User is using the mouse, waiting")
mousePos = getMousePos()
time.sleep(5)
subprocess.run('start /B "" "{0}" /verysilent'.format(filename), shell=True)
else:
subprocess.run('start /B "" "{0}" /silent'.format(filename), shell=True)
else:
print("🟠 Hash not ok")
print("🟠 File hash: ", hashlib.sha256(datatowrite).hexdigest())
print("🟠 Provided hash: ", provided_hash)
showWarn.infoSignal.emit(("Updates found!"), f"ElevenClock Version {new_version_number} is available, but ElevenClock can't verify the authenticity of the package. Please go ElevenClock's homepage and download the latest version from there.\n\nDo you want to open the download page?")
else:
print("🟠 Can't verify update server authenticity, aborting")
print("🟠 Provided DmName:", dmname)
print("🟠 Expected DmNane: 769432b9-3560-4f94-8f90-01c95844d994.id.repl.co")
showWarn.infoSignal.emit(("Updates found!"), f"ElevenClock Version {new_version_number} is available, but ElevenClock can't verify the authenticity of the updates server. Please go ElevenClock's homepage and download the latest version from there.\n\nDo you want to open the download page?")
else:
showNotif.infoSignal.emit(("Updates found!"), f"ElevenClock Version {new_version_number} is available. Go to ElevenClock's Settings to update")
else:
print("🟢 Updates not found")
else:
print("🟠 Update checking disabled")
#old_stdout.write(buffer.getvalue())
#old_stdout.flush()
except Exception as e:
report(e)
#old_stdout.write(buffer.getvalue())
#old_stdout.flush()
def resetRestartCount():
global restartCount
while True:
if(restartCount>0):
print("🔵 Restart loop:", restartCount)
restartCount -= 1
time.sleep(0.3)
def loadClocks():
global clocks, oldScreens, st, restartCount, st
try:
st.kill()
except AttributeError:
pass
ForceClockOnFirstMonitor = getSettings("ForceClockOnFirstMonitor")
HideClockOnSecondaryMonitors = getSettings("HideClockOnSecondaryMonitors")
oldScreens = []
clocks = []
if importedPsutil:
process = psutil.Process(os.getpid())
memOk = (process.memory_info().rss/1048576) <= 150
else:
print("🟠 Psutil couldn't be imported!")
memOk = True
if restartCount<20 and memOk:
restartCount += 1
i = 0
for screen in app.screens():
screen: QScreen
oldScreens.append(getGeometry(screen))
if not screen == QGuiApplication.primaryScreen() or ForceClockOnFirstMonitor: # Check if we are not on the primary screen
if not HideClockOnSecondaryMonitors or screen == QGuiApplication.primaryScreen(): # First monitor is not affected by HideClockOnSecondaryMonitors
clocks.append(Clock(screen.logicalDotsPerInchX()/96, screen.logicalDotsPerInchY()/96, screen, i))
i += 1
else:
print("🟠 This is a secondary screen and is set to be skipped")
else: # Skip the primary display, as it has already the clock
print("🟡 This is the primary screen and is set to be skipped")
st = KillableThread(target=screenCheckThread, daemon=True, name="Main [loaded]: Screen listener")
st.start()
else:
os.startfile(sys.executable)
print("🔴 Overloading system, killing!")
app.quit()
sys.exit(1)
def getGeometry(screen: QScreen):
"""
Return a tuple containing: (screen_width, screen_height, screen_pos_x, screen_pos_y, screen_DPI, desktopWindowRect)
"""
try:
geometry = screen.geometry()
g = (geometry.width(), geometry.height(), geometry.x(), geometry.y(), screen.logicalDotsPerInch(), win32api.EnumDisplayMonitors())
return g
except Exception as e:
report(e)
geometry = QGuiApplication.primaryScreen().geometry()
g = (geometry.width(), geometry.height(), geometry.x(), geometry.y(), screen.logicalDotsPerInch(), win32api.EnumDisplayMonitors())
return g
def theyMatch(oldscreens, newscreens):
if len(oldscreens) != len(newscreens) or len(app.screens()) != len(win32api.EnumDisplayMonitors()):
return False # The number of displays has changed
# Check that all screen dimensions and dpi are the same as before
return all(old == getGeometry(new) for old, new in zip(oldscreens, newscreens))
def wnfDataThread():
global isFocusAssist, numOfNotifs
while True:
isFocusAssist = isFocusAssistEnabled()
time.sleep(0.25)
if not isFocusAssist:
numOfNotifs = getNotificationNumber()
time.sleep(0.25)
def screenCheckThread():
while theyMatch(oldScreens, app.screens()):
time.sleep(1)
signal.restartSignal.emit()
pass
def closeClocks():
for clock in clocks:
clock.hide()
clock.close()
def showMessage(title: str, body: str, uBtn: bool = True) -> None:
"""
Shows a Windows Notification
"""
lastState = i.isVisible()
i.show()
i.showMessage(title, body)
if uBtn:
sw.updateButton.show()
i.setVisible(lastState)
def restartClocks(caller: str = ""):
global clocks, st, rdpThread
closeClocks()
loadClocks()
loadTimeFormat()
try:
rdpThread.kill()
except AttributeError:
pass
rdpThread = KillableThread(target=checkRDP, daemon=True)
if(getSettings("EnableHideOnRDP")):
rdpThread.start()
def isElevenClockRunningThread():
nowTime = time.time()
name = f"ElevenClockRunning{nowTime}"
setSettings(name, True, False)
while True:
try:
for file in glob.glob(os.path.join(os.path.join(os.path.expanduser("~"), ".elevenclock"), "ElevenClockRunning*")):
if(os.path.join(os.path.join(os.path.expanduser("~"), ".elevenclock"), name) == file):
pass
else:
if(float(file.replace(os.path.join(os.path.join(os.path.expanduser("~"), ".elevenclock"), "ElevenClockRunning"), "")) < nowTime): # If lockfile is older
os.remove(file)
if not(getSettings(name)):
print("🟠 KILLING, NEWER VERSION RUNNING")
killSignal.infoSignal.emit("", "")
except Exception as e:
report(e)
time.sleep(2)
def wanrUserAboutUpdates(a, b):
if(QMessageBox.question(sw, a, b, QMessageBox.Open | QMessageBox.Cancel, QMessageBox.Open) == QMessageBox.Open):
os.startfile("https://github.com/martinet101/ElevenClock/releases/latest")
def checkIfWokeUpThread():
while True:
lastTime = time.time()
time.sleep(3)
if((lastTime+6) < time.time()):
os.startfile(sys.executable)
def loadTimeFormat():
global dateTimeFormat
showSeconds = readRegedit(r"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "ShowSecondsInSystemClock", 0) or getSettings("EnableSeconds")
locale.setlocale(locale.LC_ALL, readRegedit(r"Control Panel\International", "LocaleName", "en_US"))
dateTimeFormat = "%HH:%M\n%A\n(W%W) %d/%m/%Y"
if getSettings("DisableTime"):
dateTimeFormat = dateTimeFormat.replace("%HH:%M\n", "")
if getSettings("DisableDate"):
if("\n" in dateTimeFormat):
dateTimeFormat = dateTimeFormat.replace("\n(W%W) %d/%m/%Y", "")
else:
dateTimeFormat = dateTimeFormat.replace("(W%W) %d/%m/%Y", "")
elif not getSettings("EnableWeekNumber"):
dateTimeFormat = dateTimeFormat.replace("(W%W) ", "")
else:
dateTimeFormat = dateTimeFormat.replace("(W%W) ", f"({_('W')}%W) ")
if not getSettings("EnableWeekDay"):
try:
dateTimeFormat = dateTimeFormat.replace("%A", "").replace("\n\n", "\n")
if dateTimeFormat[-1] == "\n":
dateTimeFormat = dateTimeFormat[0:-1]
if dateTimeFormat[0] == "\n":
dateTimeFormat = dateTimeFormat[1:]
except IndexError as e:
print("🟠 Date/Time string looks to be empty!")
except Exception as e:
report(e)
tDateMode = readRegedit(r"Control Panel\International", "sShortDate", "dd/MM/yyyy")
print("🔵 tDateMode:", tDateMode)
dateMode = ""
for i, ministr in enumerate(tDateMode.split("'")):
if i%2==0:
dateMode += ministr.replace("dddd", "%A").replace("ddd", "%a").replace("dd", "%$").replace("d", "%#d").replace("$", "d").replace("MMMM", "%B").replace("MMM", "%b").replace("MM", "%m").replace("M", "%#m").replace("yyyy", "%Y").replace("yy", "%y")
else:
dateMode += ministr
tTimeMode = readRegedit(r"Control Panel\International", "sShortTime", "H:mm")
print("🔵 tTimeMode:", tTimeMode)
timeMode = ""
for i, ministr in enumerate(tTimeMode.split("'")):
if i%2==0:
timeMode += ministr.replace("HH", "%$").replace("H", "%#H").replace("$", "H").replace("hh", "%I").replace("h", "%#I").replace("mm", "%M").replace("m", "%#M").replace("tt", "%p").replace("t", "%p").replace("ss", "%S").replace("s", "%#S")
if not("S" in timeMode) and showSeconds == 1:
for separator in ":.-/_":
if(separator in timeMode):
timeMode += f"{separator}%S"
else:
timeMode += ministr
for separator in ":.-/_":
timeMode = timeMode.replace(f" %p{separator}%S", f"{separator}%S %p")
timeMode = timeMode.replace(f" %p{separator}%#S", f"{separator}%#S %p")
timeMode = timeMode.replace("%S", "%S·").replace("%#S", "%#S·")
dateTimeFormat = dateTimeFormat.replace("%d/%m/%Y", dateMode).replace("%HH:%M", timeMode)
print("🔵 Loaded date time format:", dateTimeFormat)
def timeStrThread():
global timeStr, dateTimeFormat
fixHyphen = getSettings("EnableHyphenFix")
encoding = 'unicode-escape'
while True:
for _ in range(36000):
dateTimeFormatUnicode = dateTimeFormat.encode(encoding).decode()
now = datetime.datetime.now()
timeStr = now.strftime(dateTimeFormatUnicode).encode().decode(encoding)
if fixHyphen:
timeStr = timeStr.replace("t-", "t -")
try:
secs = datetime.datetime.now().strftime("%S")
if secs[-1] == "1":
timeStr = timeStr.replace("·", " \u200e")
else:
timeStr = timeStr.replace("·", "")
except IndexError:
pass
time.sleep(0.1)
class RestartSignal(QObject):
restartSignal = Signal()
def __init__(self) -> None:
super().__init__()
class InfoSignal(QObject):
infoSignal = Signal(str, str)
def __init__(self) -> None:
super().__init__()
class Clock(QWidget):
refresh = Signal()
hideSignal = Signal()
callInMainSignal = Signal(object)
styler = Signal(str)
preferedwidth = 200
preferedHeight = 48
focusassitant = True
lastTheme = 0
clockShouldBeHidden = False
shouldBeVisible = True
isRDPRunning = True
clockOnTheLeft = False
textInputHostHWND = 0
INTLOOPTIME = 2
def __init__(self, dpix: float, dpiy: float, screen: QScreen, index: int):
super().__init__()
if f"_{screen.name()}_" in getSettingsValue("BlacklistedMonitors"):
print("🟠 Monitor blacklisted!")
self.hide()
else:
self.index = index
print(f"🔵 Initializing clock {index}...")
self.callInMainSignal.connect(lambda f: f())
self.styler.connect(self.setStyleSheet)
self.taskbarBackgroundColor = not getSettings("DisableTaskbarBackgroundColor") and not (getSettings("UseCustomBgColor") or getSettings("AccentBackgroundcolor"))
self.transparentBackground = getSettings("DisableTaskbarBackgroundColor") and not (getSettings("UseCustomBgColor") or getSettings("AccentBackgroundcolor"))
if self.taskbarBackgroundColor:
print("🔵 Using taskbar background color")
self.bgcolor = "0, 0, 0, 0"
else:
print("🟡 Not using taskbar background color")
if getSettings("AccentBackgroundcolor"):
self.bgcolor = f"{getColors()[5 if isTaskbarDark() else 1]},100"
else:
self.bgcolor = getSettingsValue("UseCustomBgColor") if getSettingsValue("UseCustomBgColor") else "0, 0, 0, 0"
print("🔵 Using bg color:", self.bgcolor)
self.prefMargins = 0
try:
if readRegedit(r"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "TaskbarSi", 1) == 0 or (not getSettings("DisableTime") and not getSettings("DisableDate") and getSettings("EnableWeekDay")):
self.prefMargins = self.getPx(5)
self.widgetStyleSheet = f"background-color: rgba(bgColor%); margin: {self.getPx(0)}px;margin-top: 0px;margin-bottom: 0px; border-radius: {self.getPx(5)}px;"
if not(not getSettings("DisableTime") and not getSettings("DisableDate") and getSettings("EnableWeekDay")):
print("🟡 Small sized taskbar")
self.preferedHeight = 32
self.preferedwidth = 200
else:
print("🟢 Regular sized taskbar")
self.prefMargins = self.getPx(3)
self.widgetStyleSheet = f"background-color: rgba(bgColor%);margin: {self.getPx(0)}px;border-radius: {self.getPx(5)}px;padding: {self.getPx(2)}px;"
except Exception as e:
print("🟡 Regular sized taskbar")
report(e)
self.prefMargins = self.getPx(3)
self.widgetStyleSheet = f"background-color: rgba(bgColor%);margin: {self.getPx(0)}px;border-radius: {self.getPx(5)}px;;padding: {self.getPx(2)}px;"
self.setStyleSheet(self.widgetStyleSheet.replace("bgColor", self.bgcolor))
if getSettings("ClockFixedHeight"):
print("🟡 Custom height being used!")
try:
self.preferedHeight = int(getSettingsValue("ClockFixedHeight"))
except ValueError as e:
report(e)
self.win32screen = {"Device": None, "Work": (0, 0, 0, 0), "Flags": 0, "Monitor": (0, 0, 0, 0)}
for win32screen in win32api.EnumDisplayMonitors():
try:
if win32api.GetMonitorInfo(win32screen[0].handle)["Device"] == screen.name():
self.win32screen = win32api.GetMonitorInfo(win32screen[0].handle)
except Exception as e:
report(e)
if self.win32screen == {"Device": None, "Work": (0, 0, 0, 0), "Flags": 0, "Monitor": (0, 0, 0, 0)}: #If no display is matching
os.startfile(sys.executable) # Restart elevenclock
app.quit()
self.screenGeometry = QRect(self.win32screen["Monitor"][0], self.win32screen["Monitor"][1], self.win32screen["Monitor"][2]-self.win32screen["Monitor"][0], self.win32screen["Monitor"][3]-self.win32screen["Monitor"][1])
print("🔵 Monitor geometry:", self.screenGeometry)
self.refresh.connect(self.refreshandShow)
self.hideSignal.connect(self.hide)
self.keyboard = Controller()
self.setWindowFlag(Qt.WindowStaysOnTopHint)
self.setWindowFlag(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setWindowFlag(Qt.Tool)
hex_blob = b'0\x00\x00\x00\xfe\xff\xff\xffz\xf4\x00\x00\x03\x00\x00\x00T\x00\x00\x000\x00\x00\x00\x00\x00\x00\x00\x08\x04\x00\x00\x80\x07\x00\x008\x04\x00\x00`\x00\x00\x00\x01\x00\x00\x00'
registry_read_result = readRegedit(r"Software\Microsoft\Windows\CurrentVersion\Explorer\StuckRects3", "Settings", hex_blob)
self.autoHide = registry_read_result[8] == 123
if self.autoHide:
print("🟡 ElevenClock set to hide with the taskbar")
self.clockOnTheLeft = getSettings("ClockOnTheLeft")
screenName = screen.name().replace("\\", "_")
if not self.clockOnTheLeft:
if getSettings(f"SpecificClockOnTheLeft{screenName}"):
self.clockOnTheLeft = True
print(f"🟡 Clock {screenName} on the left (forced)")
else:
if getSettings(f"SpecificClockOnTheRight{screenName}"):
self.clockOnTheLeft = False
print(f"🟡 Clock {screenName} on the right (forced)")
try:
if (registry_read_result[12] == 1 and not getSettings("ForceOnBottom")) or getSettings("ForceOnTop"):
h = self.screenGeometry.y()
print("🟢 Taskbar at top")
else:
h = self.screenGeometry.y()+self.screenGeometry.height()-(self.preferedHeight*dpiy)
print("🟡 Taskbar at bottom")
except Exception as e:
report(e)
h = self.screenGeometry.y()+self.screenGeometry.height()-(self.preferedHeight*dpiy)
print("🟡 Taskbar at bottom")
self.label = Label(timeStr, self)
if self.clockOnTheLeft:
print("🟡 Clock on the left")
w = self.screenGeometry.x()+8*dpix
self.label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
else:
self.label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
print("🟢 Clock on the right")
w = self.screenGeometry.x()+self.screenGeometry.width()-((self.preferedwidth)*dpix)
if getSettings("CenterAlignment"):
self.label.setAlignment(Qt.AlignCenter)
xoff = 0
yoff = 0
if getSettings("ClockXOffset"):
print("🟡 X offset being used!")
try:
xoff = int(getSettingsValue("ClockXOffset"))
except ValueError as e:
report(e)
if getSettings("ClockYOffset"):
print("🟡 Y offset being used!")
try:
yoff = int(getSettingsValue("ClockYOffset"))
except ValueError as e:
report(e)
self.w = int(w) + xoff
self.h = int(h) + yoff
self.dpix = dpix
self.dpiy = dpiy
if not(getSettings("EnableWin32API")):
print("🟢 Using qt's default positioning system")
self.move(self.w, self.h)
self.resize(int(self.preferedwidth*dpix), int(self.preferedHeight*dpiy))
else:
print("🟡 Using win32 API positioning system")
self.user32 = windll.user32
self.user32.SetProcessDPIAware() # forces functions to return real pixel numbers instead of scaled values
win32gui.SetWindowPos(self.winId(), 0, int(w), int(h), int(self.preferedwidth*dpix), int(self.preferedHeight*dpiy), False)
print("🔵 Clock geometry:", self.geometry())
self.font: QFont = QFont()
customFont = getSettingsValue("UseCustomFont")
if customFont == "":
if lang == lang_ko:
self.fontfamilies = ["Malgun Gothic", "Segoe UI Variable", "sans-serif"]
elif lang == lang_zh_TW:
self.fontfamilies = ["Microsoft JhengHei UI", "Segoe UI Variable", "sans-serif"]
elif lang == lang_zh_CN:
self.fontfamilies = ["Microsoft YaHei UI", "Segoe UI Variable", "sans-serif"]
else:
self.fontfamilies = ["Segoe UI Variable Display", "sans-serif"]
else:
self.fontfamilies = [customFont]
print(f"🔵 Font families: {self.fontfamilies}")
customSize = getSettingsValue("UseCustomFontSize")
if customSize == "":
self.font.setPointSizeF(9.3)
else:
try:
self.font.setPointSizeF(float(customSize))
except Exception as e:
self.font.setPointSizeF(9.3)
report(e)
print(f"🔵 Font size: {self.font.pointSizeF()}")
self.font.setStyleStrategy(QFont.PreferOutline)
self.font.setLetterSpacing(QFont.PercentageSpacing, 100)
self.font.setHintingPreference(QFont.HintingPreference.PreferNoHinting)
self.label.setFont(self.font)
accColors = getColors()
def make_style_sheet(a, b, c, d, color):
bg = 1 if isTaskbarDark() else 4
fg = 6 if isTaskbarDark() else 1
return f"*{{padding: {a}px;padding-right: {b}px;margin-right: {c}px;padding-left: {d}px; color: {color};}}#notifIndicator{{background-color: rgb({accColors[bg]});color:rgb({accColors[fg]});}}"
if getSettings("UseCustomFontColor"):
print("🟡 Using custom text color:", getSettingsValue('UseCustomFontColor'))
self.lastTheme = -1
style_sheet_string = make_style_sheet(self.getPx(1), self.getPx(3), self.getPx(12), self.getPx(5), f"rgb({getSettingsValue('UseCustomFontColor')})")
self.label.setStyleSheet(style_sheet_string)
self.label.bgopacity = .1
self.fontfamilies = [element.replace("Segoe UI Variable Display", "Segoe UI Variable Display Semib") for element in self.fontfamilies]
self.font.setFamilies(self.fontfamilies)
if lang == lang_ko:
self.font.setWeight(QFont.Weight.Normal)
elif lang == lang_zh_TW or lang == lang_zh_CN:
self.font.setWeight(QFont.Weight.Normal)
else:
self.font.setWeight(QFont.Weight.DemiBold)
self.label.setFont(self.font)
elif isTaskbarDark():
print("🟢 Using white text (dark mode)")
self.lastTheme = 0
style_sheet_string = make_style_sheet(self.getPx(1), self.getPx(3), self.getPx(12), self.getPx(5), "white")
self.label.setStyleSheet(style_sheet_string)
self.label.bgopacity = .1
self.fontfamilies = [element.replace("Segoe UI Variable Display", "Segoe UI Variable Display Semib") for element in self.fontfamilies]
self.font.setFamilies(self.fontfamilies)
if lang == lang_ko:
self.font.setWeight(QFont.Weight.Normal)
elif lang == lang_zh_TW or lang == lang_zh_CN:
self.font.setWeight(QFont.Weight.Normal)
else:
self.font.setWeight(QFont.Weight.DemiBold)
self.label.setFont(self.font)
else:
print("🟢 Using black text (light mode)")
self.lastTheme = 1
style_sheet_string = make_style_sheet(self.getPx(1), self.getPx(3), self.getPx(12), self.getPx(5), "black")
self.label.setStyleSheet(style_sheet_string)
self.label.bgopacity = .5
self.fontfamilies = [element.replace("Segoe UI Variable Display Semib", "Segoe UI Variable Display") for element in self.fontfamilies]
self.font.setFamilies(self.fontfamilies)
self.font.setWeight(QFont.Weight.ExtraLight)
self.label.setFont(self.font)
self.label.clicked.connect(lambda: self.showCalendar())
self.label.move(0, 0)
self.label.setFixedHeight(self.height())
self.label.resize(self.width()-self.getPx(8), self.height())
self.label.show()
loadTimeFormat()
self.show()
self.raise_()
self.setFocus()
self.full_screen_rect = (self.screenGeometry.x(), self.screenGeometry.y(), self.screenGeometry.x()+self.screenGeometry.width(), self.screenGeometry.y()+self.screenGeometry.height())
print("🔵 Full screen rect: ", self.full_screen_rect)
self.forceDarkTheme = getSettings("ForceDarkTheme")
self.forceLightTheme = getSettings("ForceLightTheme")
self.hideClockWhenClicked = getSettings("HideClockWhenClicked")
self.isLowCpuMode = getSettings("EnableLowCpuMode")
self.primary_screen = QGuiApplication.primaryScreen()
self.oldBgColor = 0
self.user32 = windll.user32
self.user32.SetProcessDPIAware() # optional, makes functions return real pixel numbers instead of scaled values
self.loop0 = KillableThread(target=self.updateTextLoop, daemon=True, name=f"Clock[{index}]: Time updater loop")
self.loop1 = KillableThread(target=self.mainClockLoop, daemon=True, name=f"Clock[{index}]: Main clock loop")
self.loop2 = KillableThread(target=self.backgroundLoop, daemon=True, name=f"Clock[{index}]: Background color loop")
self.loop0.start()
self.loop1.start()
self.loop2.start()
class QHoverButton(QPushButton):
hovered = Signal()
unhovered = Signal()
def __init__(self, text: str = "", parent: QObject = None) -> None:
super().__init__(text=text, parent=parent)
def enterEvent(self, event: QtCore.QEvent) -> None:
self.hovered.emit()
return super().enterEvent(event)
def leaveEvent(self, event: QtCore.QEvent) -> None:
self.unhovered.emit()
return super().leaveEvent(event)
if(readRegedit(r"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "TaskbarSd", 0) == 1) or getSettings("ShowDesktopButton"):
print("🟡 Desktop button enabled")
self.desktopButton = QHoverButton(parent=self)
self.desktopButton.clicked.connect(lambda: self.showDesktop())
self.desktopButton.show()
self.desktopButton.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.desktopButton.move(self.width()-self.getPx(10), 0)
self.desktopButton.resize(self.getPx(10), self.getPx(self.preferedHeight))
self.desktopButton.hovered.connect(lambda: self.desktopButton.setIcon(QIcon(getPath("showdesktop.png"))))
self.desktopButton.unhovered.connect(lambda: self.desktopButton.setIcon(QIcon()))
self.setFixedHeight(self.getPx(self.preferedHeight))
self.desktopButton.setStyleSheet(f"""
QPushButton{{
background-color: rgba(0, 0, 0, 0.01);
margin: 0px;
padding: 0px;
margin-top: 0px;
border-radius: 0px;
margin-bottom: 0px;
border-left: 0px solid rgba(0, 0, 0, 0.05);
border-right: 0px solid rgba(0, 0, 0, 0.05);
}}
QPushButton:hover{{
background-color: rgba(127, 127, 127, 1%);
margin: 0px;
margin-top: 0px;
border-radius: 0px;
margin-bottom: 0px;
border-left: 0px solid rgba(0, 0, 0, 0.05);
border-right: 0px solid rgba(0, 0, 0, 0.05);
}}
QPushButton:pressed{{
background-color: rgba(127, 127, 127, 1%);
margin: 0px;
margin-top: 0px;
border-radius: 0px;
margin-bottom: 0px;
border-left: 0px solid rgba(0, 0, 0, 0.05);
border-right: 0px solid rgba(0, 0, 0, 0.05);
}}
""")
def getPx(self, original) -> int:
return round(original*(self.screen().logicalDotsPerInch()/96))
def backgroundLoop(self):
while True:
try:
if self.taskbarBackgroundColor and not self.isLowCpuMode and not globals.trayIcon.contextMenu().isVisible():
intColor = self.primary_screen.grabWindow(0, self.x()+self.label.x()-1, self.y()+2, 1, 1).toImage().pixel(0, 0)
if intColor != self.oldBgColor:
self.oldBgColor = intColor
color = QColor(intColor)
self.styler.emit(self.widgetStyleSheet.replace("bgColor", f"{color.red()}, {color.green()}, {color.blue()}, 100"))
except AttributeError:
print("🟣 Expected AttributeError on backgroundLoop thread")
time.sleep(0.5)
def theresFullScreenWin(self, clockOnFirstMon, newMethod, legacyMethod):
try:
fullscreen = False
def compareFullScreenRects(window, screen, newMethod):
try:
if(newMethod):
return window[0] <= screen[0] and window[1] <= screen[1] and window[2] >= screen[2] and window[3] >= screen[3]
else:
return window[0] == screen[0] and window[1] == screen[1] and window[2] == screen[2] and window[3] == screen[3]
except Exception as e:
report(e)
def winEnumHandler(hwnd, _):
nonlocal fullscreen
if win32gui.IsWindowVisible(hwnd):
if compareFullScreenRects(win32gui.GetWindowRect(hwnd), self.full_screen_rect, newMethod):
if clockOnFirstMon and self.textInputHostHWND == 0:
pythoncom.CoInitialize()
_, pid = win32process.GetWindowThreadProcessId(hwnd)
_wmi = win32com.client.GetObject('winmgmts:')
# collect all the running processes
processes = _wmi.ExecQuery(f'Select Name from win32_process where ProcessId = {pid}')
for p in processes:
if p.Name != "TextInputHost.exe":
if(win32gui.GetWindowText(hwnd) not in blacklistedFullscreenApps):
print("🟡 Fullscreen window detected!", win32gui.GetWindowText(hwnd), win32gui.GetWindowRect(hwnd), "Fullscreen rect:", self.full_screen_rect)
fullscreen = True
else:
print("🟢 Cached text input host hwnd:", hwnd)
self.textInputHostHWND = hwnd
self.INTLOOPTIME = 2
else:
if win32gui.GetWindowText(hwnd) not in blacklistedFullscreenApps and hwnd != self.textInputHostHWND:
print("🟡 Fullscreen window detected!", win32gui.GetWindowText(hwnd), win32gui.GetWindowRect(hwnd), "Fullscreen rect:", self.full_screen_rect)
fullscreen = True
if not legacyMethod:
win32gui.EnumWindows(winEnumHandler, 0)
else:
hwnd = win32gui.GetForegroundWindow()
if(compareFullScreenRects(win32gui.GetWindowRect(hwnd), self.full_screen_rect, newMethod)):
if(win32gui.GetWindowText(hwnd) not in blacklistedFullscreenApps):
print("🟡 Fullscreen window detected!", win32gui.GetWindowText(hwnd), win32gui.GetWindowRect(hwnd), "Fullscreen rect:", self.full_screen_rect)
fullscreen = True
return fullscreen
except Exception as e:
report(e)
return False
def mainClockLoop(self):
global isRDPRunning, numOfNotifs
EnableHideOnFullScreen = not(getSettings("DisableHideOnFullScreen"))
DisableHideWithTaskbar = getSettings("DisableHideWithTaskbar")
EnableHideOnRDP = getSettings("EnableHideOnRDP")
clockOnFirstMon = getSettings("ForceClockOnFirstMonitor")
newMethod = getSettings("NewFullScreenMethod")
notifs = not getSettings("DisableNotifications")
legacyMethod = getSettings("legacyFullScreenMethod")
oldNotifNumber = 0
print(f"🔵 Show/hide loop started with parameters: HideonFS:{EnableHideOnFullScreen}, NotHideOnTB:{DisableHideWithTaskbar}, HideOnRDP:{EnableHideOnRDP}, ClockOn1Mon:{clockOnFirstMon}, NefWSMethod:{newMethod}, DisableNotifications:{notifs}, legacyFullScreenMethod:{legacyMethod}")
if self.isLowCpuMode or clockOnFirstMon:
self.INTLOOPTIME = 15
else:
self.INTLOOPTIME = 2
while True:
self.isRDPRunning = isRDPRunning
isFullScreen = self.theresFullScreenWin(clockOnFirstMon, newMethod, legacyMethod)
for i in range(self.INTLOOPTIME):
if (not(isFullScreen) or not(EnableHideOnFullScreen)) and not self.clockShouldBeHidden:
if notifs:
if isFocusAssist:
self.callInMainSignal.emit(self.label.enableFocusAssistant)
elif numOfNotifs > 0:
if oldNotifNumber != numOfNotifs:
self.callInMainSignal.emit(self.label.enableNotifDot)
else:
self.callInMainSignal.emit(self.label.disableClockIndicators)
oldNotifNumber = numOfNotifs
if self.autoHide and not(DisableHideWithTaskbar):
mousePos = getMousePos()
if (mousePos.y()+1 == self.screenGeometry.y()+self.screenGeometry.height()) and self.screenGeometry.x() < mousePos.x() and self.screenGeometry.x()+self.screenGeometry.width() > mousePos.x():
self.refresh.emit()
elif (mousePos.y() <= self.screenGeometry.y()+self.screenGeometry.height()-self.preferedHeight):
self.hideSignal.emit()
else:
if(self.isRDPRunning and EnableHideOnRDP):
self.hideSignal.emit()
else:
self.refresh.emit()
else:
self.hideSignal.emit()
time.sleep(0.2)
time.sleep(0.2)
def updateTextLoop(self) -> None:
global timeStr
while True:
self.label.setText(timeStr)
time.sleep(0.1)
def showCalendar(self):
self.keyboard.press(Key.cmd)
self.keyboard.press('n')
self.keyboard.release('n')
self.keyboard.release(Key.cmd)
if self.hideClockWhenClicked:
print("🟡 Hiding clock because clicked!")
self.clockShouldBeHidden = True
def showClockOn10s(self: Clock):
time.sleep(10)
print("🟢 Showing clock because 10s passed!")
self.clockShouldBeHidden = False
KillableThread(target=showClockOn10s, args=(self,), name=f"Temporary: 10s thread").start()
def showDesktop(self):
self.keyboard.press(Key.cmd)
self.keyboard.press('d')
self.keyboard.release('d')
self.keyboard.release(Key.cmd)
def focusOutEvent(self, event: QFocusEvent) -> None:
self.refresh.emit()
def refreshandShow(self):
if(self.shouldBeVisible):
self.show()
self.raise_()
if(self.lastTheme >= 0): # If the color is not customized
theme = readRegedit(r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", "SystemUsesLightTheme", 1)
if(theme != self.lastTheme):
if (theme == 0 or self.forceDarkTheme) and not self.forceLightTheme:
self.lastTheme = 0
self.label.setStyleSheet(f"padding: {self.getPx(1)}px;padding-right: {self.getPx(3)}px;margin-right: {self.getPx(12)}px;padding-left: {self.getPx(5)}px; color: white;")#background-color: rgba({self.bgcolor}%)")
self.label.bgopacity = 0.1
self.fontfamilies = [element.replace("Segoe UI Variable Display", "Segoe UI Variable Display Semib") for element in self.fontfamilies]
self.font.setFamilies(self.fontfamilies)
if lang == lang_ko:
self.font.setWeight(QFont.Weight.Normal)
elif lang == lang_zh_TW or lang == lang_zh_CN:
self.font.setWeight(QFont.Weight.Normal)
else:
self.font.setWeight(QFont.Weight.DemiBold)
self.label.setFont(self.font)
else:
self.lastTheme = 1
self.label.setStyleSheet(f"padding: {self.getPx(1)}px;padding-right: {self.getPx(3)}px;margin-right: {self.getPx(12)}px;padding-left: {self.getPx(5)}px; color: black;")#background-color: rgba({self.bgcolor}%)")
self.label.bgopacity = .5
self.fontfamilies = [element.replace("Segoe UI Variable Display Semib", "Segoe UI Variable Display") for element in self.fontfamilies]
self.font.setFamilies(self.fontfamilies)
self.font.setWeight(QFont.Weight.ExtraLight)
self.label.setFont(self.font)
def closeEvent(self, event: QCloseEvent) -> None:
self.shouldBeVisible = False
try:
print(f"🟡 Closing clock on {self.win32screen}")
self.loop0.kill()
self.loop1.kill()
self.loop2.kill()
except AttributeError:
pass
event.accept()
return super().closeEvent(event)
def showEvent(self, event: QShowEvent) -> None:
return super().showEvent(event)
class Label(QLabel):
clicked = Signal()
def __init__(self, text, parent):
super().__init__(text, parent=parent)
self.setMouseTracking(True)
self.backgroundwidget = QWidget(self)
self.color = "255, 255, 255"
self.installEventFilter(self)
self.bgopacity = 0.1
self.backgroundwidget.setContentsMargins(0, self.window().prefMargins, 0, self.window().prefMargins)
self.backgroundwidget.setStyleSheet(f"background-color: rgba(127, 127, 127, 0.01);border-top: {self.getPx(1)}px solid rgba({self.color},0);margin-top: {self.window().prefMargins}px; margin-bottom: {self.window().prefMargins};")
self.backgroundwidget.show()
if self.window().transparentBackground:
colorOffset = .01
else:
colorOffset = 0
self.showBackground = QVariantAnimation()
self.showBackground.setStartValue(0+colorOffset) # Not 0 to prevent white flashing on the border
self.showBackground.setEndValue(self.bgopacity)
self.showBackground.setDuration(100)
self.showBackground.setEasingCurve(QEasingCurve.InOutQuad) # Not strictly required, just for the aesthetics
self.showBackground.valueChanged.connect(lambda opacity: self.backgroundwidget.setStyleSheet(f"background-color: rgba({self.color}, {opacity/2});border-top: {self.getPx(1)}px solid rgba({self.color}, {opacity+colorOffset});margin-top: {self.window().prefMargins}px; margin-bottom: {self.window().prefMargins};"))
self.hideBackground = QVariantAnimation()
self.hideBackground.setStartValue(self.bgopacity)
self.hideBackground.setEndValue(0+colorOffset) # Not 0 to prevent white flashing on the border
self.hideBackground.setDuration(100)
self.hideBackground.setEasingCurve(QEasingCurve.InOutQuad) # Not strictly required, just for the aesthetics
self.hideBackground.valueChanged.connect(lambda opacity: self.backgroundwidget.setStyleSheet(f"background-color: rgba({self.color}, {opacity/2});border-top: {self.getPx(1)}px solid rgba({self.color}, {opacity+colorOffset});margin-top: {self.window().prefMargins}px; margin-bottom: {self.window().prefMargins};"))
self.setAutoFillBackground(True)
self.backgroundwidget.setGeometry(0, 0, self.width(), self.height())
self.opacity=QGraphicsOpacityEffect(self)
self.opacity.setOpacity(1.00)
self.backgroundwidget.setGraphicsEffect(self.opacity)
self.focusassitant = True
self.focusAssitantLabel = QPushButton(self)
self.focusAssitantLabel.move(self.width(), 0)
self.focusAssitantLabel.setAttribute(Qt.WA_TransparentForMouseEvents)
self.focusAssitantLabel.setStyleSheet("background: transparent; margin: none; padding: none;")
self.focusAssitantLabel.resize(self.getPx(30), self.height())
self.focusAssitantLabel.setIcon(QIcon(getPath(f"moon_{getTaskbarIconMode()}.png")))
self.focusAssitantLabel.setIconSize(QSize(self.getPx(16), self.getPx(16)))
accColors = getColors()
self.notifdot = True
self.notifDotLabel = QLabel("", self)
self.notifDotLabel.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter)
self.notifDotLabel.setObjectName("notifIndicator")
self.notifDotLabel.setStyleSheet(f"font-size: 8pt;font-family: \"Segoe UI Variable Display\";border-radius: {self.getPx(8)}px;padding: 0px;padding-bottom: {self.getPx(2)}px;padding-left: {self.getPx(3)}px;padding-right: {self.getPx(2)}px;margin: 0px;border:0px;")
self.disableClockIndicators()
def enableFocusAssistant(self):
if not self.focusassitant:
if self.notifdot:
self.disableClockIndicators()
self.focusassitant = True
self.setContentsMargins(self.getPx(5), self.getPx(2), self.getPx(43), self.getPx(2))
self.focusAssitantLabel.move(self.width()-self.contentsMargins().right(), 0)
self.focusAssitantLabel.setFixedWidth(self.getPx(30))
self.focusAssitantLabel.setFixedHeight(self.height())
self.focusAssitantLabel.setIconSize(QSize(self.getPx(16), self.getPx(16)))
self.focusAssitantLabel.setIcon(QIcon(getPath(f"moon_{getTaskbarIconMode()}.png")))
self.focusAssitantLabel.show()
def enableNotifDot(self):
self.notifDotLabel.setText(str(numOfNotifs))
if not self.notifdot:
self.notifdot = True
self.setContentsMargins(self.getPx(5), self.getPx(2), self.getPx(43), self.getPx(2))
topBottomPadding = (self.height()-self.getPx(16))/2 # top-bottom margin
leftRightPadding = (self.getPx(30)-self.getPx(16))/2 # left-right margin
self.notifDotLabel.move(int(self.width()-self.contentsMargins().right()+leftRightPadding), int(topBottomPadding))
self.notifDotLabel.resize(self.getPx(16), self.getPx(16))
self.notifDotLabel.setStyleSheet(f"font-size: 8pt;font-family: \"Segoe UI Variable Display\";border-radius: {self.getPx(8)}px;padding: 0px;padding-bottom: {self.getPx(2)}px;padding-left: {self.getPx(3)}px;padding-right: {self.getPx(2)}px;margin: 0px;border:0px;")
self.notifDotLabel.show()
def disableClockIndicators(self):
if self.focusassitant:
self.focusassitant = False
self.setContentsMargins(self.getPx(6), self.getPx(2), self.getPx(13), self.getPx(2))
self.focusAssitantLabel.hide()
if self.notifdot:
self.notifdot = False
self.setContentsMargins(self.getPx(6), self.getPx(2), self.getPx(13), self.getPx(2))
self.notifDotLabel.hide()
def getPx(self, i: int) -> int:
return round(i*(self.screen().logicalDotsPerInch()/96))
def enterEvent(self, event: QEvent, r=False) -> None:
geometry: QRect = self.width()
self.showBackground.setStartValue(.01)
self.showBackground.setEndValue(self.bgopacity) # Not 0 to prevent white flashing on the border
if not self.window().clockOnTheLeft:
self.backgroundwidget.move(0, 2)
self.backgroundwidget.resize(geometry, self.height()-4)
else:
self.backgroundwidget.move(0, 2)
self.backgroundwidget.resize(geometry, self.height()-4)
self.showBackground.start()
if not r:
self.enterEvent(event, r=True)
return super().enterEvent(event)
def leaveEvent(self, event: QEvent) -> None:
self.hideBackground.setStartValue(self.bgopacity)
self.hideBackground.setEndValue(.01) # Not 0 to prevent white flashing on the border
self.hideBackground.start()
return super().leaveEvent(event)
def getTextUsedSpaceRect(self):
text = self.text().strip()
if len(text.split("\n"))>=3:
mult = 0.633333333333333333
elif len(text.split("\n"))==2:
mult = 1
else:
mult = 1.5
return self.fontMetrics().boundingRect(text).width()*mult
def mousePressEvent(self, ev: QMouseEvent) -> None:
self.setWindowOpacity(0.7)
self.setWindowOpacity(0.7)
self.opacity.setOpacity(0.60)
self.backgroundwidget.setGraphicsEffect(self.opacity)
return super().mousePressEvent(ev)
def mouseReleaseEvent(self, ev: QMouseEvent) -> None:
self.setWindowOpacity(1)
self.setWindowOpacity(1)
self.opacity.setOpacity(1.00)
self.backgroundwidget.setGraphicsEffect(self.opacity)
if(ev.button() == Qt.RightButton):
mousePos = getMousePos()
if(i.contextMenu().height() != 480):
mousePos.setY(self.window().y()-(i.contextMenu().height()+5))
else:
if getSettings("HideTaskManagerButton"):
mousePos.setY(self.window().y()-int(260*(i.contextMenu().screen().logicalDotsPerInchX()/96)))
else:
mousePos.setY(self.window().y()-int(370*(i.contextMenu().screen().logicalDotsPerInchX()/96)))
i.execMenu(mousePos)
else:
self.clicked.emit()
return super().mouseReleaseEvent(ev)
def paintEvent(self, event: QPaintEvent) -> None:
w = self.minimumSizeHint().width()
try:
mw = int(getSettingsValue("ClockFixedWidth"))
if mw > w:
w = mw
except Exception as e:
report(e)
if w<self.window().getPx(self.window().preferedwidth) and not self.window().clockOnTheLeft:
self.move(self.window().getPx(self.window().preferedwidth)-w+self.getPx(2), 0)
self.resize(w, self.height())
else:
self.move(0, 0)
self.resize(w, self.height())
return super().paintEvent(event)
def resizeEvent(self, event: QResizeEvent) -> None:
if self.focusassitant:
self.focusassitant = False
self.enableFocusAssistant()
elif self.notifdot:
self.notifdot = False
self.enableNotifDot()
else:
self.notifdot = True
self.focusassitant = True
self.disableClockIndicators()
return super().resizeEvent(event)
def window(self) -> Clock:
return super().window()
# Start of main script
QApplication.setAttribute(Qt.AA_DisableHighDpiScaling)
app = QApplication(sys.argv)
app.setQuitOnLastWindowClosed(False)
mController: MouseController = None
sw: SettingsWindow = None
i: TaskbarIconTray = None
st: KillableThread = None # Will be defined on loadClocks
KillableThread(target=resetRestartCount, daemon=True, name="Main: Restart counter").start()
KillableThread(target=timeStrThread, daemon=True, name="Main: Locale string loader").start()
loadClocks()
print(f"🟢 Loaded clocks in {time.time()-FirstTime}")
tdir = tempfile.TemporaryDirectory()
tempDir = tdir.name
sw = SettingsWindow() # Declare settings window
i = TaskbarIconTray(app)
mController = MouseController()
app.primaryScreenChanged.connect(lambda: os.startfile(sys.executable))
app.screenAdded.connect(lambda: os.startfile(sys.executable))
app.screenRemoved.connect(lambda: os.startfile(sys.executable))
signal = RestartSignal()
showNotif = InfoSignal()
showWarn = InfoSignal()
killSignal = InfoSignal()
showNotif.infoSignal.connect(lambda a, b: showMessage(a, b))
showWarn.infoSignal.connect(lambda a, b: wanrUserAboutUpdates(a, b))
killSignal.infoSignal.connect(lambda: app.quit())
signal.restartSignal.connect(lambda: restartClocks("checkLoop"))
KillableThread(target=updateChecker, daemon=True, name="Main: Updater").start()
KillableThread(target=isElevenClockRunningThread, daemon=True, name="Main: Instance controller").start()
if not getSettings("EnableLowCpuMode"): KillableThread(target=checkIfWokeUpThread, daemon=True, name="Main: Sleep listener").start()
if not getSettings("EnableLowCpuMode"): KillableThread(target=wnfDataThread, daemon=True, name="Main: WNF Data listener").start()
print("🔵 Low cpu mode is set to", str(getSettings("EnableLowCpuMode"))+". DisableNotifications is set to", getSettings("DisableNotifications"))
rdpThread = KillableThread(target=checkRDP, daemon=True, name="Main: Remote desktop controller")
if getSettings("EnableHideOnRDP"):
rdpThread.start()
globals.tempDir = tempDir # Register global variables
globals.old_stdout = old_stdout # Register global variables
globals.buffer = buffer # Register global variables
globals.app = app # Register global variables
globals.sw = sw # Register global variables
globals.trayIcon = i # Register global variables
globals.loadTimeFormat = loadTimeFormat # Register global functions
globals.updateIfPossible = updateIfPossible # Register global functions
globals.restartClocks = restartClocks # Register global functions
globals.closeClocks = closeClocks # Register global functions
if not(getSettings("Updated3.21Already")) and not(getSettings("EnableSilentUpdates")):
setSettings("ForceClockOnFirstMonitor", True)
setSettings("Updated3.21Already", True)
msg = QFramelessDialog(parent=None, closeOnClick=False)
msg.setAutoFillBackground(True)
msg.setStyleSheet(sw.styleSheet())
msg.setAttribute(QtCore.Qt.WA_StyledBackground)
msg.setObjectName("QMessageBox")
msg.setTitle("ElevenClock Updater")
msg.setText(f"""<b>ElevenClock has updated to version {versionName} successfully.</b>
<br><br>This update brings:<br>
<ul><li>The ability to specify a clock minimum width</li>
<li> The ability to search through the settings</li>
<li> Fixed an aesthetic issue with the seconds</li>
<li> Added a button to reset ElevenClock</li>
<li> Fixed an issue where ElevenClock would crash when clicking the right-click menu</li>
<li> Added Nynorsk</li>
<li> Some bugfixing and other improvements</li></ul>""")
msg.addButton("Ok", QDialogButtonBox.ButtonRole.ApplyRole, lambda: msg.close())
msg.addButton("Full changelog", QDialogButtonBox.ButtonRole.ResetRole, lambda: os.startfile("https://github.com/martinet101/ElevenClock/releases"))
def settNClose():
sw.show()
msg.close()
msg.addButton("Settings", QDialogButtonBox.ButtonRole.ActionRole, lambda: settNClose())
msg.setDefaultButtonRole(QDialogButtonBox.ButtonRole.ApplyRole, sw.styleSheet())
msg.setWindowTitle("ElevenClock has updated!")
msg.show()
showSettings = False
if "--settings" in sys.argv or showSettings:
sw.show()
if not getSettings("DefaultPrefsLoaded"):
setSettings("AlreadyInstalled", True)
setSettings("NewFullScreenMethod", True)
setSettings("ForceClockOnFirstMonitor", True)
showMessage("Welcome to ElevenClock", "You can customize Elevenclock from the ElevenClock Settings. You can search them on the start menu or right-clicking on any clock -> ElevenClock Settings", uBtn=False)
print("🟢 Default settings loaded")
setSettings("DefaultPrefsLoaded", True)
showWelcomeWizard = False
if showWelcomeWizard or "--welcome" in sys.argv:
import welcome
ww = welcome.WelcomeWindow()
print(f"🟢 Loaded everything in {time.time()-FirstTime}")
if "--quit-on-loaded" in sys.argv: # This is a testing feature to test if the script can load successfully
sys.exit(0)
app.exec_()
sys.exit(0)
except Exception as e:
import webbrowser, traceback, platform
if not "versionName" in locals() and not "versionName" in globals():
versionName = "Unknown"
if not "version" in locals() and not "version" in globals():
version = "Unknown"
os_info = f"" + \
f" OS: {platform.system()}\n"+\
f" Version: {platform.win32_ver()}\n"+\
f" OS Architecture: {platform.machine()}\n"+\
f" APP Architecture: {platform.architecture()[0]}\n"+\
f" APP Version: {versionName}\n"+\
f" APP Version Code: {version}\n"+\
f" Program: ElevenClock"+\
"\n\n-----------------------------------------------------------------------------------------"
traceback_info = "Traceback (most recent call last):\n"
try:
for line in traceback.extract_tb(e.__traceback__).format():
traceback_info += line
traceback_info += f"\n{type(e).__name__}: {str(e)}"
except:
traceback_info += "\nUnable to get traceback"
traceback_info += str(type(e))
traceback_info += ": "
traceback_info += str(e)
webbrowser.open(("https://www.somepythonthings.tk/error-report/?appName=ElevenClock&errorBody="+os_info.replace('\n', '{l}').replace(' ', '{s}')+"{l}{l}{l}{l}ElevenClock Log:{l}"+str("\n\n\n\n"+traceback_info).replace('\n', '{l}').replace(' ', '{s}')).replace("#", "|=|"))
print(traceback_info)
sys.exit(1) | 50.981308 | 324 | 0.557195 | try:
import time
FirstTime = time.time()
import os
import io
import sys
import time
import glob
import socket
import locale
import hashlib
import tempfile
import datetime
import subprocess
from ctypes import windll
from urllib.request import urlopen
try:
import psutil
importedPsutil = True
except ImportError:
importedPsutil = False
import win32gui
import win32api
import pythoncom
import win32process
import win32com.client
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import pyqtSignal as Signal
from pynput.keyboard import Controller, Key
from pynput.mouse import Controller as MouseController
from external.FramelessWindow import QFramelessDialog
from languages import *
import globals
old_stdout = sys.stdout
sys.stdout = buffer = io.StringIO()
from settings import *
from tools import *
import tools
from external.WnfReader import isFocusAssistEnabled, getNotificationNumber
blacklistedProcesses = ["msrdc.exe", "mstsc.exe", "CDViewer.exe", "wfica32.exe", "vmware-view.exe", "vmware.exe"]
blacklistedFullscreenApps = ("", "Program Manager", "NVIDIA GeForce Overlay", "ElenenClock_IgnoreFullscreenEvent")
seconddoubleclick = False
isRDPRunning = False
restartCount = 0
tempDir = ""
timeStr = ""
dateTimeFormat = ""
clocks = []
oldScreens = []
isFocusAssist = False
numOfNotifs = 0
print("---------------------------------------------------------------------------------------------------")
print("")
print(f" ElevenClock's {versionName} (v{version}) log: Select all the text and hit Ctrl+C to copy it")
print(f" All modules loaded successfully and sys.stdout patched correctly, starting main script")
print(f" Translator function set language to \"{langName}\"")
print("")
print("---------------------------------------------------------------------------------------------------")
print("")
print(" Log legend:")
print(" 🔵: Verbose")
print(" 🟢: Information")
print(" 🟡: Warning")
print(" 🟠: Handled unexpected exception")
print(" 🔴: Unhandled unexpected exception")
print(" 🟣: Handled expected exception")
print("")
def _(s) -> str:
return tools._(s)
def checkRDP():
def checkIfElevenClockRunning(processess, blacklistedProcess) -> bool:
for p_name in processess:
if p_name in blacklistedProcess:
print(f"🟡 Blacklisted procName {p_name} detected, hiding...")
return True
return False
global isRDPRunning
print("🔵 Starting RDP thread")
while True:
pythoncom.CoInitialize()
_wmi = win32com.client.GetObject('winmgmts:')
processes = _wmi.ExecQuery('Select Name from win32_process')
procs = [p.Name for p in processes]
isRDPRunning = checkIfElevenClockRunning(procs, blacklistedProcesses)
time.sleep(5)
def getMousePos():
try:
return QPoint(mController.position[0], mController.position[1])
except AttributeError:
print("🟠 Mouse thread returned AttributeError")
except Exception as e:
report(e)
def updateChecker():
updateIfPossible()
time.sleep(60)
while True:
updateIfPossible()
time.sleep(7200)
def updateIfPossible(force = False):
try:
if(not(getSettings("DisableAutoCheckForUpdates")) or force):
print("🔵 Starting update check")
integrityPass = False
dmname = socket.gethostbyname_ex("versions.somepythonthings.tk")[0]
if(dmname == "769432b9-3560-4f94-8f90-01c95844d994.id.repl.co" or getSettings("BypassDomainAuthCheck")): # Check provider IP to prevent exploits
integrityPass = True
try:
response = urlopen("https://versions.somepythonthings.tk/versions/elevenclock.ver" if not getSettings("AlternativeUpdateServerProvider") else "http://www.somepythonthings.tk/versions/elevenclock.ver")
except Exception as e:
report(e)
response = urlopen("http://www.somepythonthings.tk/versions/elevenclock.ver")
integrityPass = True
print("🔵 Version URL:", response.url)
response = response.read().decode("utf8")
new_version_number = response.split("///")[0]
provided_hash = response.split("///")[2].replace("\n", "").lower()
if float(new_version_number) > version:
print("🟢 Updates found!")
if(not(getSettings("DisableAutoInstallUpdates")) or force):
showNotif.infoSignal.emit(("ElevenClock Updater"), ("ElevenClock is downloading updates"))
if(integrityPass):
url = "https://github.com/martinet101/ElevenClock/releases/latest/download/ElevenClock.Installer.exe"
filedata = urlopen(url)
datatowrite = filedata.read()
filename = ""
with open(os.path.join(tempDir, "SomePythonThings-ElevenClock-Updater.exe"), 'wb') as f:
f.write(datatowrite)
filename = f.name
if(hashlib.sha256(datatowrite).hexdigest().lower() == provided_hash):
print("🔵 Hash: ", provided_hash)
print("🟢 Hash ok, starting update")
if(getSettings("EnableSilentUpdates") and not(force)):
mousePos = getMousePos()
time.sleep(5)
while mousePos != getMousePos():
print("🟡 User is using the mouse, waiting")
mousePos = getMousePos()
time.sleep(5)
subprocess.run('start /B "" "{0}" /verysilent'.format(filename), shell=True)
else:
subprocess.run('start /B "" "{0}" /silent'.format(filename), shell=True)
else:
print("🟠 Hash not ok")
print("🟠 File hash: ", hashlib.sha256(datatowrite).hexdigest())
print("🟠 Provided hash: ", provided_hash)
showWarn.infoSignal.emit(("Updates found!"), f"ElevenClock Version {new_version_number} is available, but ElevenClock can't verify the authenticity of the package. Please go ElevenClock's homepage and download the latest version from there.\n\nDo you want to open the download page?")
else:
print("🟠 Can't verify update server authenticity, aborting")
print("🟠 Provided DmName:", dmname)
print("🟠 Expected DmNane: 769432b9-3560-4f94-8f90-01c95844d994.id.repl.co")
showWarn.infoSignal.emit(("Updates found!"), f"ElevenClock Version {new_version_number} is available, but ElevenClock can't verify the authenticity of the updates server. Please go ElevenClock's homepage and download the latest version from there.\n\nDo you want to open the download page?")
else:
showNotif.infoSignal.emit(("Updates found!"), f"ElevenClock Version {new_version_number} is available. Go to ElevenClock's Settings to update")
else:
print("🟢 Updates not found")
else:
print("🟠 Update checking disabled")
#old_stdout.write(buffer.getvalue())
#old_stdout.flush()
except Exception as e:
report(e)
#old_stdout.write(buffer.getvalue())
#old_stdout.flush()
def resetRestartCount():
global restartCount
while True:
if(restartCount>0):
print("🔵 Restart loop:", restartCount)
restartCount -= 1
time.sleep(0.3)
def loadClocks():
global clocks, oldScreens, st, restartCount, st
try:
st.kill()
except AttributeError:
pass
ForceClockOnFirstMonitor = getSettings("ForceClockOnFirstMonitor")
HideClockOnSecondaryMonitors = getSettings("HideClockOnSecondaryMonitors")
oldScreens = []
clocks = []
if importedPsutil:
process = psutil.Process(os.getpid())
memOk = (process.memory_info().rss/1048576) <= 150
else:
print("🟠 Psutil couldn't be imported!")
memOk = True
if restartCount<20 and memOk:
restartCount += 1
i = 0
for screen in app.screens():
screen: QScreen
oldScreens.append(getGeometry(screen))
if not screen == QGuiApplication.primaryScreen() or ForceClockOnFirstMonitor:
if not HideClockOnSecondaryMonitors or screen == QGuiApplication.primaryScreen():
clocks.append(Clock(screen.logicalDotsPerInchX()/96, screen.logicalDotsPerInchY()/96, screen, i))
i += 1
else:
print("🟠 This is a secondary screen and is set to be skipped")
else:
print("🟡 This is the primary screen and is set to be skipped")
st = KillableThread(target=screenCheckThread, daemon=True, name="Main [loaded]: Screen listener")
st.start()
else:
os.startfile(sys.executable)
print("🔴 Overloading system, killing!")
app.quit()
sys.exit(1)
def getGeometry(screen: QScreen):
try:
geometry = screen.geometry()
g = (geometry.width(), geometry.height(), geometry.x(), geometry.y(), screen.logicalDotsPerInch(), win32api.EnumDisplayMonitors())
return g
except Exception as e:
report(e)
geometry = QGuiApplication.primaryScreen().geometry()
g = (geometry.width(), geometry.height(), geometry.x(), geometry.y(), screen.logicalDotsPerInch(), win32api.EnumDisplayMonitors())
return g
def theyMatch(oldscreens, newscreens):
if len(oldscreens) != len(newscreens) or len(app.screens()) != len(win32api.EnumDisplayMonitors()):
return False
return all(old == getGeometry(new) for old, new in zip(oldscreens, newscreens))
def wnfDataThread():
global isFocusAssist, numOfNotifs
while True:
isFocusAssist = isFocusAssistEnabled()
time.sleep(0.25)
if not isFocusAssist:
numOfNotifs = getNotificationNumber()
time.sleep(0.25)
def screenCheckThread():
while theyMatch(oldScreens, app.screens()):
time.sleep(1)
signal.restartSignal.emit()
pass
def closeClocks():
for clock in clocks:
clock.hide()
clock.close()
def showMessage(title: str, body: str, uBtn: bool = True) -> None:
lastState = i.isVisible()
i.show()
i.showMessage(title, body)
if uBtn:
sw.updateButton.show()
i.setVisible(lastState)
def restartClocks(caller: str = ""):
global clocks, st, rdpThread
closeClocks()
loadClocks()
loadTimeFormat()
try:
rdpThread.kill()
except AttributeError:
pass
rdpThread = KillableThread(target=checkRDP, daemon=True)
if(getSettings("EnableHideOnRDP")):
rdpThread.start()
def isElevenClockRunningThread():
nowTime = time.time()
name = f"ElevenClockRunning{nowTime}"
setSettings(name, True, False)
while True:
try:
for file in glob.glob(os.path.join(os.path.join(os.path.expanduser("~"), ".elevenclock"), "ElevenClockRunning*")):
if(os.path.join(os.path.join(os.path.expanduser("~"), ".elevenclock"), name) == file):
pass
else:
if(float(file.replace(os.path.join(os.path.join(os.path.expanduser("~"), ".elevenclock"), "ElevenClockRunning"), "")) < nowTime):
os.remove(file)
if not(getSettings(name)):
print("🟠 KILLING, NEWER VERSION RUNNING")
killSignal.infoSignal.emit("", "")
except Exception as e:
report(e)
time.sleep(2)
def wanrUserAboutUpdates(a, b):
if(QMessageBox.question(sw, a, b, QMessageBox.Open | QMessageBox.Cancel, QMessageBox.Open) == QMessageBox.Open):
os.startfile("https://github.com/martinet101/ElevenClock/releases/latest")
def checkIfWokeUpThread():
while True:
lastTime = time.time()
time.sleep(3)
if((lastTime+6) < time.time()):
os.startfile(sys.executable)
def loadTimeFormat():
global dateTimeFormat
showSeconds = readRegedit(r"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "ShowSecondsInSystemClock", 0) or getSettings("EnableSeconds")
locale.setlocale(locale.LC_ALL, readRegedit(r"Control Panel\International", "LocaleName", "en_US"))
dateTimeFormat = "%HH:%M\n%A\n(W%W) %d/%m/%Y"
if getSettings("DisableTime"):
dateTimeFormat = dateTimeFormat.replace("%HH:%M\n", "")
if getSettings("DisableDate"):
if("\n" in dateTimeFormat):
dateTimeFormat = dateTimeFormat.replace("\n(W%W) %d/%m/%Y", "")
else:
dateTimeFormat = dateTimeFormat.replace("(W%W) %d/%m/%Y", "")
elif not getSettings("EnableWeekNumber"):
dateTimeFormat = dateTimeFormat.replace("(W%W) ", "")
else:
dateTimeFormat = dateTimeFormat.replace("(W%W) ", f"({_('W')}%W) ")
if not getSettings("EnableWeekDay"):
try:
dateTimeFormat = dateTimeFormat.replace("%A", "").replace("\n\n", "\n")
if dateTimeFormat[-1] == "\n":
dateTimeFormat = dateTimeFormat[0:-1]
if dateTimeFormat[0] == "\n":
dateTimeFormat = dateTimeFormat[1:]
except IndexError as e:
print("🟠 Date/Time string looks to be empty!")
except Exception as e:
report(e)
tDateMode = readRegedit(r"Control Panel\International", "sShortDate", "dd/MM/yyyy")
print("🔵 tDateMode:", tDateMode)
dateMode = ""
for i, ministr in enumerate(tDateMode.split("'")):
if i%2==0:
dateMode += ministr.replace("dddd", "%A").replace("ddd", "%a").replace("dd", "%$").replace("d", "%#d").replace("$", "d").replace("MMMM", "%B").replace("MMM", "%b").replace("MM", "%m").replace("M", "%#m").replace("yyyy", "%Y").replace("yy", "%y")
else:
dateMode += ministr
tTimeMode = readRegedit(r"Control Panel\International", "sShortTime", "H:mm")
print("🔵 tTimeMode:", tTimeMode)
timeMode = ""
for i, ministr in enumerate(tTimeMode.split("'")):
if i%2==0:
timeMode += ministr.replace("HH", "%$").replace("H", "%#H").replace("$", "H").replace("hh", "%I").replace("h", "%#I").replace("mm", "%M").replace("m", "%#M").replace("tt", "%p").replace("t", "%p").replace("ss", "%S").replace("s", "%#S")
if not("S" in timeMode) and showSeconds == 1:
for separator in ":.-/_":
if(separator in timeMode):
timeMode += f"{separator}%S"
else:
timeMode += ministr
for separator in ":.-/_":
timeMode = timeMode.replace(f" %p{separator}%S", f"{separator}%S %p")
timeMode = timeMode.replace(f" %p{separator}%#S", f"{separator}%#S %p")
timeMode = timeMode.replace("%S", "%S·").replace("%#S", "%#S·")
dateTimeFormat = dateTimeFormat.replace("%d/%m/%Y", dateMode).replace("%HH:%M", timeMode)
print("🔵 Loaded date time format:", dateTimeFormat)
def timeStrThread():
global timeStr, dateTimeFormat
fixHyphen = getSettings("EnableHyphenFix")
encoding = 'unicode-escape'
while True:
for _ in range(36000):
dateTimeFormatUnicode = dateTimeFormat.encode(encoding).decode()
now = datetime.datetime.now()
timeStr = now.strftime(dateTimeFormatUnicode).encode().decode(encoding)
if fixHyphen:
timeStr = timeStr.replace("t-", "t -")
try:
secs = datetime.datetime.now().strftime("%S")
if secs[-1] == "1":
timeStr = timeStr.replace("·", " \u200e")
else:
timeStr = timeStr.replace("·", "")
except IndexError:
pass
time.sleep(0.1)
class RestartSignal(QObject):
restartSignal = Signal()
def __init__(self) -> None:
super().__init__()
class InfoSignal(QObject):
infoSignal = Signal(str, str)
def __init__(self) -> None:
super().__init__()
class Clock(QWidget):
refresh = Signal()
hideSignal = Signal()
callInMainSignal = Signal(object)
styler = Signal(str)
preferedwidth = 200
preferedHeight = 48
focusassitant = True
lastTheme = 0
clockShouldBeHidden = False
shouldBeVisible = True
isRDPRunning = True
clockOnTheLeft = False
textInputHostHWND = 0
INTLOOPTIME = 2
def __init__(self, dpix: float, dpiy: float, screen: QScreen, index: int):
super().__init__()
if f"_{screen.name()}_" in getSettingsValue("BlacklistedMonitors"):
print("🟠 Monitor blacklisted!")
self.hide()
else:
self.index = index
print(f"🔵 Initializing clock {index}...")
self.callInMainSignal.connect(lambda f: f())
self.styler.connect(self.setStyleSheet)
self.taskbarBackgroundColor = not getSettings("DisableTaskbarBackgroundColor") and not (getSettings("UseCustomBgColor") or getSettings("AccentBackgroundcolor"))
self.transparentBackground = getSettings("DisableTaskbarBackgroundColor") and not (getSettings("UseCustomBgColor") or getSettings("AccentBackgroundcolor"))
if self.taskbarBackgroundColor:
print("🔵 Using taskbar background color")
self.bgcolor = "0, 0, 0, 0"
else:
print("🟡 Not using taskbar background color")
if getSettings("AccentBackgroundcolor"):
self.bgcolor = f"{getColors()[5 if isTaskbarDark() else 1]},100"
else:
self.bgcolor = getSettingsValue("UseCustomBgColor") if getSettingsValue("UseCustomBgColor") else "0, 0, 0, 0"
print("🔵 Using bg color:", self.bgcolor)
self.prefMargins = 0
try:
if readRegedit(r"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "TaskbarSi", 1) == 0 or (not getSettings("DisableTime") and not getSettings("DisableDate") and getSettings("EnableWeekDay")):
self.prefMargins = self.getPx(5)
self.widgetStyleSheet = f"background-color: rgba(bgColor%); margin: {self.getPx(0)}px;margin-top: 0px;margin-bottom: 0px; border-radius: {self.getPx(5)}px;"
if not(not getSettings("DisableTime") and not getSettings("DisableDate") and getSettings("EnableWeekDay")):
print("🟡 Small sized taskbar")
self.preferedHeight = 32
self.preferedwidth = 200
else:
print("🟢 Regular sized taskbar")
self.prefMargins = self.getPx(3)
self.widgetStyleSheet = f"background-color: rgba(bgColor%);margin: {self.getPx(0)}px;border-radius: {self.getPx(5)}px;padding: {self.getPx(2)}px;"
except Exception as e:
print("🟡 Regular sized taskbar")
report(e)
self.prefMargins = self.getPx(3)
self.widgetStyleSheet = f"background-color: rgba(bgColor%);margin: {self.getPx(0)}px;border-radius: {self.getPx(5)}px;;padding: {self.getPx(2)}px;"
self.setStyleSheet(self.widgetStyleSheet.replace("bgColor", self.bgcolor))
if getSettings("ClockFixedHeight"):
print("🟡 Custom height being used!")
try:
self.preferedHeight = int(getSettingsValue("ClockFixedHeight"))
except ValueError as e:
report(e)
self.win32screen = {"Device": None, "Work": (0, 0, 0, 0), "Flags": 0, "Monitor": (0, 0, 0, 0)}
for win32screen in win32api.EnumDisplayMonitors():
try:
if win32api.GetMonitorInfo(win32screen[0].handle)["Device"] == screen.name():
self.win32screen = win32api.GetMonitorInfo(win32screen[0].handle)
except Exception as e:
report(e)
if self.win32screen == {"Device": None, "Work": (0, 0, 0, 0), "Flags": 0, "Monitor": (0, 0, 0, 0)}:
os.startfile(sys.executable)
app.quit()
self.screenGeometry = QRect(self.win32screen["Monitor"][0], self.win32screen["Monitor"][1], self.win32screen["Monitor"][2]-self.win32screen["Monitor"][0], self.win32screen["Monitor"][3]-self.win32screen["Monitor"][1])
print("🔵 Monitor geometry:", self.screenGeometry)
self.refresh.connect(self.refreshandShow)
self.hideSignal.connect(self.hide)
self.keyboard = Controller()
self.setWindowFlag(Qt.WindowStaysOnTopHint)
self.setWindowFlag(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setWindowFlag(Qt.Tool)
hex_blob = b'0\x00\x00\x00\xfe\xff\xff\xffz\xf4\x00\x00\x03\x00\x00\x00T\x00\x00\x000\x00\x00\x00\x00\x00\x00\x00\x08\x04\x00\x00\x80\x07\x00\x008\x04\x00\x00`\x00\x00\x00\x01\x00\x00\x00'
registry_read_result = readRegedit(r"Software\Microsoft\Windows\CurrentVersion\Explorer\StuckRects3", "Settings", hex_blob)
self.autoHide = registry_read_result[8] == 123
if self.autoHide:
print("🟡 ElevenClock set to hide with the taskbar")
self.clockOnTheLeft = getSettings("ClockOnTheLeft")
screenName = screen.name().replace("\\", "_")
if not self.clockOnTheLeft:
if getSettings(f"SpecificClockOnTheLeft{screenName}"):
self.clockOnTheLeft = True
print(f"🟡 Clock {screenName} on the left (forced)")
else:
if getSettings(f"SpecificClockOnTheRight{screenName}"):
self.clockOnTheLeft = False
print(f"🟡 Clock {screenName} on the right (forced)")
try:
if (registry_read_result[12] == 1 and not getSettings("ForceOnBottom")) or getSettings("ForceOnTop"):
h = self.screenGeometry.y()
print("🟢 Taskbar at top")
else:
h = self.screenGeometry.y()+self.screenGeometry.height()-(self.preferedHeight*dpiy)
print("🟡 Taskbar at bottom")
except Exception as e:
report(e)
h = self.screenGeometry.y()+self.screenGeometry.height()-(self.preferedHeight*dpiy)
print("🟡 Taskbar at bottom")
self.label = Label(timeStr, self)
if self.clockOnTheLeft:
print("🟡 Clock on the left")
w = self.screenGeometry.x()+8*dpix
self.label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
else:
self.label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
print("🟢 Clock on the right")
w = self.screenGeometry.x()+self.screenGeometry.width()-((self.preferedwidth)*dpix)
if getSettings("CenterAlignment"):
self.label.setAlignment(Qt.AlignCenter)
xoff = 0
yoff = 0
if getSettings("ClockXOffset"):
print("🟡 X offset being used!")
try:
xoff = int(getSettingsValue("ClockXOffset"))
except ValueError as e:
report(e)
if getSettings("ClockYOffset"):
print("🟡 Y offset being used!")
try:
yoff = int(getSettingsValue("ClockYOffset"))
except ValueError as e:
report(e)
self.w = int(w) + xoff
self.h = int(h) + yoff
self.dpix = dpix
self.dpiy = dpiy
if not(getSettings("EnableWin32API")):
print("🟢 Using qt's default positioning system")
self.move(self.w, self.h)
self.resize(int(self.preferedwidth*dpix), int(self.preferedHeight*dpiy))
else:
print("🟡 Using win32 API positioning system")
self.user32 = windll.user32
self.user32.SetProcessDPIAware() # forces functions to return real pixel numbers instead of scaled values
win32gui.SetWindowPos(self.winId(), 0, int(w), int(h), int(self.preferedwidth*dpix), int(self.preferedHeight*dpiy), False)
print("🔵 Clock geometry:", self.geometry())
self.font: QFont = QFont()
customFont = getSettingsValue("UseCustomFont")
if customFont == "":
if lang == lang_ko:
self.fontfamilies = ["Malgun Gothic", "Segoe UI Variable", "sans-serif"]
elif lang == lang_zh_TW:
self.fontfamilies = ["Microsoft JhengHei UI", "Segoe UI Variable", "sans-serif"]
elif lang == lang_zh_CN:
self.fontfamilies = ["Microsoft YaHei UI", "Segoe UI Variable", "sans-serif"]
else:
self.fontfamilies = ["Segoe UI Variable Display", "sans-serif"]
else:
self.fontfamilies = [customFont]
print(f"🔵 Font families: {self.fontfamilies}")
customSize = getSettingsValue("UseCustomFontSize")
if customSize == "":
self.font.setPointSizeF(9.3)
else:
try:
self.font.setPointSizeF(float(customSize))
except Exception as e:
self.font.setPointSizeF(9.3)
report(e)
print(f"🔵 Font size: {self.font.pointSizeF()}")
self.font.setStyleStrategy(QFont.PreferOutline)
self.font.setLetterSpacing(QFont.PercentageSpacing, 100)
self.font.setHintingPreference(QFont.HintingPreference.PreferNoHinting)
self.label.setFont(self.font)
accColors = getColors()
def make_style_sheet(a, b, c, d, color):
bg = 1 if isTaskbarDark() else 4
fg = 6 if isTaskbarDark() else 1
return f"*{{padding: {a}px;padding-right: {b}px;margin-right: {c}px;padding-left: {d}px; color: {color};}}#notifIndicator{{background-color: rgb({accColors[bg]});color:rgb({accColors[fg]});}}"
if getSettings("UseCustomFontColor"):
print("🟡 Using custom text color:", getSettingsValue('UseCustomFontColor'))
self.lastTheme = -1
style_sheet_string = make_style_sheet(self.getPx(1), self.getPx(3), self.getPx(12), self.getPx(5), f"rgb({getSettingsValue('UseCustomFontColor')})")
self.label.setStyleSheet(style_sheet_string)
self.label.bgopacity = .1
self.fontfamilies = [element.replace("Segoe UI Variable Display", "Segoe UI Variable Display Semib") for element in self.fontfamilies]
self.font.setFamilies(self.fontfamilies)
if lang == lang_ko:
self.font.setWeight(QFont.Weight.Normal)
elif lang == lang_zh_TW or lang == lang_zh_CN:
self.font.setWeight(QFont.Weight.Normal)
else:
self.font.setWeight(QFont.Weight.DemiBold)
self.label.setFont(self.font)
elif isTaskbarDark():
print("🟢 Using white text (dark mode)")
self.lastTheme = 0
style_sheet_string = make_style_sheet(self.getPx(1), self.getPx(3), self.getPx(12), self.getPx(5), "white")
self.label.setStyleSheet(style_sheet_string)
self.label.bgopacity = .1
self.fontfamilies = [element.replace("Segoe UI Variable Display", "Segoe UI Variable Display Semib") for element in self.fontfamilies]
self.font.setFamilies(self.fontfamilies)
if lang == lang_ko:
self.font.setWeight(QFont.Weight.Normal)
elif lang == lang_zh_TW or lang == lang_zh_CN:
self.font.setWeight(QFont.Weight.Normal)
else:
self.font.setWeight(QFont.Weight.DemiBold)
self.label.setFont(self.font)
else:
print("🟢 Using black text (light mode)")
self.lastTheme = 1
style_sheet_string = make_style_sheet(self.getPx(1), self.getPx(3), self.getPx(12), self.getPx(5), "black")
self.label.setStyleSheet(style_sheet_string)
self.label.bgopacity = .5
self.fontfamilies = [element.replace("Segoe UI Variable Display Semib", "Segoe UI Variable Display") for element in self.fontfamilies]
self.font.setFamilies(self.fontfamilies)
self.font.setWeight(QFont.Weight.ExtraLight)
self.label.setFont(self.font)
self.label.clicked.connect(lambda: self.showCalendar())
self.label.move(0, 0)
self.label.setFixedHeight(self.height())
self.label.resize(self.width()-self.getPx(8), self.height())
self.label.show()
loadTimeFormat()
self.show()
self.raise_()
self.setFocus()
self.full_screen_rect = (self.screenGeometry.x(), self.screenGeometry.y(), self.screenGeometry.x()+self.screenGeometry.width(), self.screenGeometry.y()+self.screenGeometry.height())
print("🔵 Full screen rect: ", self.full_screen_rect)
self.forceDarkTheme = getSettings("ForceDarkTheme")
self.forceLightTheme = getSettings("ForceLightTheme")
self.hideClockWhenClicked = getSettings("HideClockWhenClicked")
self.isLowCpuMode = getSettings("EnableLowCpuMode")
self.primary_screen = QGuiApplication.primaryScreen()
self.oldBgColor = 0
self.user32 = windll.user32
self.user32.SetProcessDPIAware() # optional, makes functions return real pixel numbers instead of scaled values
self.loop0 = KillableThread(target=self.updateTextLoop, daemon=True, name=f"Clock[{index}]: Time updater loop")
self.loop1 = KillableThread(target=self.mainClockLoop, daemon=True, name=f"Clock[{index}]: Main clock loop")
self.loop2 = KillableThread(target=self.backgroundLoop, daemon=True, name=f"Clock[{index}]: Background color loop")
self.loop0.start()
self.loop1.start()
self.loop2.start()
class QHoverButton(QPushButton):
hovered = Signal()
unhovered = Signal()
def __init__(self, text: str = "", parent: QObject = None) -> None:
super().__init__(text=text, parent=parent)
def enterEvent(self, event: QtCore.QEvent) -> None:
self.hovered.emit()
return super().enterEvent(event)
def leaveEvent(self, event: QtCore.QEvent) -> None:
self.unhovered.emit()
return super().leaveEvent(event)
if(readRegedit(r"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", "TaskbarSd", 0) == 1) or getSettings("ShowDesktopButton"):
print("🟡 Desktop button enabled")
self.desktopButton = QHoverButton(parent=self)
self.desktopButton.clicked.connect(lambda: self.showDesktop())
self.desktopButton.show()
self.desktopButton.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.desktopButton.move(self.width()-self.getPx(10), 0)
self.desktopButton.resize(self.getPx(10), self.getPx(self.preferedHeight))
self.desktopButton.hovered.connect(lambda: self.desktopButton.setIcon(QIcon(getPath("showdesktop.png"))))
self.desktopButton.unhovered.connect(lambda: self.desktopButton.setIcon(QIcon()))
self.setFixedHeight(self.getPx(self.preferedHeight))
self.desktopButton.setStyleSheet(f"""
QPushButton{{
background-color: rgba(0, 0, 0, 0.01);
margin: 0px;
padding: 0px;
margin-top: 0px;
border-radius: 0px;
margin-bottom: 0px;
border-left: 0px solid rgba(0, 0, 0, 0.05);
border-right: 0px solid rgba(0, 0, 0, 0.05);
}}
QPushButton:hover{{
background-color: rgba(127, 127, 127, 1%);
margin: 0px;
margin-top: 0px;
border-radius: 0px;
margin-bottom: 0px;
border-left: 0px solid rgba(0, 0, 0, 0.05);
border-right: 0px solid rgba(0, 0, 0, 0.05);
}}
QPushButton:pressed{{
background-color: rgba(127, 127, 127, 1%);
margin: 0px;
margin-top: 0px;
border-radius: 0px;
margin-bottom: 0px;
border-left: 0px solid rgba(0, 0, 0, 0.05);
border-right: 0px solid rgba(0, 0, 0, 0.05);
}}
""")
def getPx(self, original) -> int:
return round(original*(self.screen().logicalDotsPerInch()/96))
def backgroundLoop(self):
while True:
try:
if self.taskbarBackgroundColor and not self.isLowCpuMode and not globals.trayIcon.contextMenu().isVisible():
intColor = self.primary_screen.grabWindow(0, self.x()+self.label.x()-1, self.y()+2, 1, 1).toImage().pixel(0, 0)
if intColor != self.oldBgColor:
self.oldBgColor = intColor
color = QColor(intColor)
self.styler.emit(self.widgetStyleSheet.replace("bgColor", f"{color.red()}, {color.green()}, {color.blue()}, 100"))
except AttributeError:
print("🟣 Expected AttributeError on backgroundLoop thread")
time.sleep(0.5)
def theresFullScreenWin(self, clockOnFirstMon, newMethod, legacyMethod):
try:
fullscreen = False
def compareFullScreenRects(window, screen, newMethod):
try:
if(newMethod):
return window[0] <= screen[0] and window[1] <= screen[1] and window[2] >= screen[2] and window[3] >= screen[3]
else:
return window[0] == screen[0] and window[1] == screen[1] and window[2] == screen[2] and window[3] == screen[3]
except Exception as e:
report(e)
def winEnumHandler(hwnd, _):
nonlocal fullscreen
if win32gui.IsWindowVisible(hwnd):
if compareFullScreenRects(win32gui.GetWindowRect(hwnd), self.full_screen_rect, newMethod):
if clockOnFirstMon and self.textInputHostHWND == 0:
pythoncom.CoInitialize()
_, pid = win32process.GetWindowThreadProcessId(hwnd)
_wmi = win32com.client.GetObject('winmgmts:')
# collect all the running processes
processes = _wmi.ExecQuery(f'Select Name from win32_process where ProcessId = {pid}')
for p in processes:
if p.Name != "TextInputHost.exe":
if(win32gui.GetWindowText(hwnd) not in blacklistedFullscreenApps):
print("🟡 Fullscreen window detected!", win32gui.GetWindowText(hwnd), win32gui.GetWindowRect(hwnd), "Fullscreen rect:", self.full_screen_rect)
fullscreen = True
else:
print("🟢 Cached text input host hwnd:", hwnd)
self.textInputHostHWND = hwnd
self.INTLOOPTIME = 2
else:
if win32gui.GetWindowText(hwnd) not in blacklistedFullscreenApps and hwnd != self.textInputHostHWND:
print("🟡 Fullscreen window detected!", win32gui.GetWindowText(hwnd), win32gui.GetWindowRect(hwnd), "Fullscreen rect:", self.full_screen_rect)
fullscreen = True
if not legacyMethod:
win32gui.EnumWindows(winEnumHandler, 0)
else:
hwnd = win32gui.GetForegroundWindow()
if(compareFullScreenRects(win32gui.GetWindowRect(hwnd), self.full_screen_rect, newMethod)):
if(win32gui.GetWindowText(hwnd) not in blacklistedFullscreenApps):
print("🟡 Fullscreen window detected!", win32gui.GetWindowText(hwnd), win32gui.GetWindowRect(hwnd), "Fullscreen rect:", self.full_screen_rect)
fullscreen = True
return fullscreen
except Exception as e:
report(e)
return False
def mainClockLoop(self):
global isRDPRunning, numOfNotifs
EnableHideOnFullScreen = not(getSettings("DisableHideOnFullScreen"))
DisableHideWithTaskbar = getSettings("DisableHideWithTaskbar")
EnableHideOnRDP = getSettings("EnableHideOnRDP")
clockOnFirstMon = getSettings("ForceClockOnFirstMonitor")
newMethod = getSettings("NewFullScreenMethod")
notifs = not getSettings("DisableNotifications")
legacyMethod = getSettings("legacyFullScreenMethod")
oldNotifNumber = 0
print(f"🔵 Show/hide loop started with parameters: HideonFS:{EnableHideOnFullScreen}, NotHideOnTB:{DisableHideWithTaskbar}, HideOnRDP:{EnableHideOnRDP}, ClockOn1Mon:{clockOnFirstMon}, NefWSMethod:{newMethod}, DisableNotifications:{notifs}, legacyFullScreenMethod:{legacyMethod}")
if self.isLowCpuMode or clockOnFirstMon:
self.INTLOOPTIME = 15
else:
self.INTLOOPTIME = 2
while True:
self.isRDPRunning = isRDPRunning
isFullScreen = self.theresFullScreenWin(clockOnFirstMon, newMethod, legacyMethod)
for i in range(self.INTLOOPTIME):
if (not(isFullScreen) or not(EnableHideOnFullScreen)) and not self.clockShouldBeHidden:
if notifs:
if isFocusAssist:
self.callInMainSignal.emit(self.label.enableFocusAssistant)
elif numOfNotifs > 0:
if oldNotifNumber != numOfNotifs:
self.callInMainSignal.emit(self.label.enableNotifDot)
else:
self.callInMainSignal.emit(self.label.disableClockIndicators)
oldNotifNumber = numOfNotifs
if self.autoHide and not(DisableHideWithTaskbar):
mousePos = getMousePos()
if (mousePos.y()+1 == self.screenGeometry.y()+self.screenGeometry.height()) and self.screenGeometry.x() < mousePos.x() and self.screenGeometry.x()+self.screenGeometry.width() > mousePos.x():
self.refresh.emit()
elif (mousePos.y() <= self.screenGeometry.y()+self.screenGeometry.height()-self.preferedHeight):
self.hideSignal.emit()
else:
if(self.isRDPRunning and EnableHideOnRDP):
self.hideSignal.emit()
else:
self.refresh.emit()
else:
self.hideSignal.emit()
time.sleep(0.2)
time.sleep(0.2)
def updateTextLoop(self) -> None:
global timeStr
while True:
self.label.setText(timeStr)
time.sleep(0.1)
def showCalendar(self):
self.keyboard.press(Key.cmd)
self.keyboard.press('n')
self.keyboard.release('n')
self.keyboard.release(Key.cmd)
if self.hideClockWhenClicked:
print("🟡 Hiding clock because clicked!")
self.clockShouldBeHidden = True
def showClockOn10s(self: Clock):
time.sleep(10)
print("🟢 Showing clock because 10s passed!")
self.clockShouldBeHidden = False
KillableThread(target=showClockOn10s, args=(self,), name=f"Temporary: 10s thread").start()
def showDesktop(self):
self.keyboard.press(Key.cmd)
self.keyboard.press('d')
self.keyboard.release('d')
self.keyboard.release(Key.cmd)
def focusOutEvent(self, event: QFocusEvent) -> None:
self.refresh.emit()
def refreshandShow(self):
if(self.shouldBeVisible):
self.show()
self.raise_()
if(self.lastTheme >= 0): # If the color is not customized
theme = readRegedit(r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", "SystemUsesLightTheme", 1)
if(theme != self.lastTheme):
if (theme == 0 or self.forceDarkTheme) and not self.forceLightTheme:
self.lastTheme = 0
self.label.setStyleSheet(f"padding: {self.getPx(1)}px;padding-right: {self.getPx(3)}px;margin-right: {self.getPx(12)}px;padding-left: {self.getPx(5)}px; color: white;")#background-color: rgba({self.bgcolor}%)")
self.label.bgopacity = 0.1
self.fontfamilies = [element.replace("Segoe UI Variable Display", "Segoe UI Variable Display Semib") for element in self.fontfamilies]
self.font.setFamilies(self.fontfamilies)
if lang == lang_ko:
self.font.setWeight(QFont.Weight.Normal)
elif lang == lang_zh_TW or lang == lang_zh_CN:
self.font.setWeight(QFont.Weight.Normal)
else:
self.font.setWeight(QFont.Weight.DemiBold)
self.label.setFont(self.font)
else:
self.lastTheme = 1
self.label.setStyleSheet(f"padding: {self.getPx(1)}px;padding-right: {self.getPx(3)}px;margin-right: {self.getPx(12)}px;padding-left: {self.getPx(5)}px; color: black;")#background-color: rgba({self.bgcolor}%)")
self.label.bgopacity = .5
self.fontfamilies = [element.replace("Segoe UI Variable Display Semib", "Segoe UI Variable Display") for element in self.fontfamilies]
self.font.setFamilies(self.fontfamilies)
self.font.setWeight(QFont.Weight.ExtraLight)
self.label.setFont(self.font)
def closeEvent(self, event: QCloseEvent) -> None:
self.shouldBeVisible = False
try:
print(f"🟡 Closing clock on {self.win32screen}")
self.loop0.kill()
self.loop1.kill()
self.loop2.kill()
except AttributeError:
pass
event.accept()
return super().closeEvent(event)
def showEvent(self, event: QShowEvent) -> None:
return super().showEvent(event)
class Label(QLabel):
clicked = Signal()
def __init__(self, text, parent):
super().__init__(text, parent=parent)
self.setMouseTracking(True)
self.backgroundwidget = QWidget(self)
self.color = "255, 255, 255"
self.installEventFilter(self)
self.bgopacity = 0.1
self.backgroundwidget.setContentsMargins(0, self.window().prefMargins, 0, self.window().prefMargins)
self.backgroundwidget.setStyleSheet(f"background-color: rgba(127, 127, 127, 0.01);border-top: {self.getPx(1)}px solid rgba({self.color},0);margin-top: {self.window().prefMargins}px; margin-bottom: {self.window().prefMargins};")
self.backgroundwidget.show()
if self.window().transparentBackground:
colorOffset = .01
else:
colorOffset = 0
self.showBackground = QVariantAnimation()
self.showBackground.setStartValue(0+colorOffset) # Not 0 to prevent white flashing on the border
self.showBackground.setEndValue(self.bgopacity)
self.showBackground.setDuration(100)
self.showBackground.setEasingCurve(QEasingCurve.InOutQuad) # Not strictly required, just for the aesthetics
self.showBackground.valueChanged.connect(lambda opacity: self.backgroundwidget.setStyleSheet(f"background-color: rgba({self.color}, {opacity/2});border-top: {self.getPx(1)}px solid rgba({self.color}, {opacity+colorOffset});margin-top: {self.window().prefMargins}px; margin-bottom: {self.window().prefMargins};"))
self.hideBackground = QVariantAnimation()
self.hideBackground.setStartValue(self.bgopacity)
self.hideBackground.setEndValue(0+colorOffset) # Not 0 to prevent white flashing on the border
self.hideBackground.setDuration(100)
self.hideBackground.setEasingCurve(QEasingCurve.InOutQuad) # Not strictly required, just for the aesthetics
self.hideBackground.valueChanged.connect(lambda opacity: self.backgroundwidget.setStyleSheet(f"background-color: rgba({self.color}, {opacity/2});border-top: {self.getPx(1)}px solid rgba({self.color}, {opacity+colorOffset});margin-top: {self.window().prefMargins}px; margin-bottom: {self.window().prefMargins};"))
self.setAutoFillBackground(True)
self.backgroundwidget.setGeometry(0, 0, self.width(), self.height())
self.opacity=QGraphicsOpacityEffect(self)
self.opacity.setOpacity(1.00)
self.backgroundwidget.setGraphicsEffect(self.opacity)
self.focusassitant = True
self.focusAssitantLabel = QPushButton(self)
self.focusAssitantLabel.move(self.width(), 0)
self.focusAssitantLabel.setAttribute(Qt.WA_TransparentForMouseEvents)
self.focusAssitantLabel.setStyleSheet("background: transparent; margin: none; padding: none;")
self.focusAssitantLabel.resize(self.getPx(30), self.height())
self.focusAssitantLabel.setIcon(QIcon(getPath(f"moon_{getTaskbarIconMode()}.png")))
self.focusAssitantLabel.setIconSize(QSize(self.getPx(16), self.getPx(16)))
accColors = getColors()
self.notifdot = True
self.notifDotLabel = QLabel("", self)
self.notifDotLabel.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter)
self.notifDotLabel.setObjectName("notifIndicator")
self.notifDotLabel.setStyleSheet(f"font-size: 8pt;font-family: \"Segoe UI Variable Display\";border-radius: {self.getPx(8)}px;padding: 0px;padding-bottom: {self.getPx(2)}px;padding-left: {self.getPx(3)}px;padding-right: {self.getPx(2)}px;margin: 0px;border:0px;")
self.disableClockIndicators()
def enableFocusAssistant(self):
if not self.focusassitant:
if self.notifdot:
self.disableClockIndicators()
self.focusassitant = True
self.setContentsMargins(self.getPx(5), self.getPx(2), self.getPx(43), self.getPx(2))
self.focusAssitantLabel.move(self.width()-self.contentsMargins().right(), 0)
self.focusAssitantLabel.setFixedWidth(self.getPx(30))
self.focusAssitantLabel.setFixedHeight(self.height())
self.focusAssitantLabel.setIconSize(QSize(self.getPx(16), self.getPx(16)))
self.focusAssitantLabel.setIcon(QIcon(getPath(f"moon_{getTaskbarIconMode()}.png")))
self.focusAssitantLabel.show()
def enableNotifDot(self):
self.notifDotLabel.setText(str(numOfNotifs))
if not self.notifdot:
self.notifdot = True
self.setContentsMargins(self.getPx(5), self.getPx(2), self.getPx(43), self.getPx(2))
topBottomPadding = (self.height()-self.getPx(16))/2 # top-bottom margin
leftRightPadding = (self.getPx(30)-self.getPx(16))/2 # left-right margin
self.notifDotLabel.move(int(self.width()-self.contentsMargins().right()+leftRightPadding), int(topBottomPadding))
self.notifDotLabel.resize(self.getPx(16), self.getPx(16))
self.notifDotLabel.setStyleSheet(f"font-size: 8pt;font-family: \"Segoe UI Variable Display\";border-radius: {self.getPx(8)}px;padding: 0px;padding-bottom: {self.getPx(2)}px;padding-left: {self.getPx(3)}px;padding-right: {self.getPx(2)}px;margin: 0px;border:0px;")
self.notifDotLabel.show()
def disableClockIndicators(self):
if self.focusassitant:
self.focusassitant = False
self.setContentsMargins(self.getPx(6), self.getPx(2), self.getPx(13), self.getPx(2))
self.focusAssitantLabel.hide()
if self.notifdot:
self.notifdot = False
self.setContentsMargins(self.getPx(6), self.getPx(2), self.getPx(13), self.getPx(2))
self.notifDotLabel.hide()
def getPx(self, i: int) -> int:
return round(i*(self.screen().logicalDotsPerInch()/96))
def enterEvent(self, event: QEvent, r=False) -> None:
geometry: QRect = self.width()
self.showBackground.setStartValue(.01)
self.showBackground.setEndValue(self.bgopacity) # Not 0 to prevent white flashing on the border
if not self.window().clockOnTheLeft:
self.backgroundwidget.move(0, 2)
self.backgroundwidget.resize(geometry, self.height()-4)
else:
self.backgroundwidget.move(0, 2)
self.backgroundwidget.resize(geometry, self.height()-4)
self.showBackground.start()
if not r:
self.enterEvent(event, r=True)
return super().enterEvent(event)
def leaveEvent(self, event: QEvent) -> None:
self.hideBackground.setStartValue(self.bgopacity)
self.hideBackground.setEndValue(.01) # Not 0 to prevent white flashing on the border
self.hideBackground.start()
return super().leaveEvent(event)
def getTextUsedSpaceRect(self):
text = self.text().strip()
if len(text.split("\n"))>=3:
mult = 0.633333333333333333
elif len(text.split("\n"))==2:
mult = 1
else:
mult = 1.5
return self.fontMetrics().boundingRect(text).width()*mult
def mousePressEvent(self, ev: QMouseEvent) -> None:
self.setWindowOpacity(0.7)
self.setWindowOpacity(0.7)
self.opacity.setOpacity(0.60)
self.backgroundwidget.setGraphicsEffect(self.opacity)
return super().mousePressEvent(ev)
def mouseReleaseEvent(self, ev: QMouseEvent) -> None:
self.setWindowOpacity(1)
self.setWindowOpacity(1)
self.opacity.setOpacity(1.00)
self.backgroundwidget.setGraphicsEffect(self.opacity)
if(ev.button() == Qt.RightButton):
mousePos = getMousePos()
if(i.contextMenu().height() != 480):
mousePos.setY(self.window().y()-(i.contextMenu().height()+5))
else:
if getSettings("HideTaskManagerButton"):
mousePos.setY(self.window().y()-int(260*(i.contextMenu().screen().logicalDotsPerInchX()/96)))
else:
mousePos.setY(self.window().y()-int(370*(i.contextMenu().screen().logicalDotsPerInchX()/96)))
i.execMenu(mousePos)
else:
self.clicked.emit()
return super().mouseReleaseEvent(ev)
def paintEvent(self, event: QPaintEvent) -> None:
w = self.minimumSizeHint().width()
try:
mw = int(getSettingsValue("ClockFixedWidth"))
if mw > w:
w = mw
except Exception as e:
report(e)
if w<self.window().getPx(self.window().preferedwidth) and not self.window().clockOnTheLeft:
self.move(self.window().getPx(self.window().preferedwidth)-w+self.getPx(2), 0)
self.resize(w, self.height())
else:
self.move(0, 0)
self.resize(w, self.height())
return super().paintEvent(event)
def resizeEvent(self, event: QResizeEvent) -> None:
if self.focusassitant:
self.focusassitant = False
self.enableFocusAssistant()
elif self.notifdot:
self.notifdot = False
self.enableNotifDot()
else:
self.notifdot = True
self.focusassitant = True
self.disableClockIndicators()
return super().resizeEvent(event)
def window(self) -> Clock:
return super().window()
# Start of main script
QApplication.setAttribute(Qt.AA_DisableHighDpiScaling)
app = QApplication(sys.argv)
app.setQuitOnLastWindowClosed(False)
mController: MouseController = None
sw: SettingsWindow = None
i: TaskbarIconTray = None
st: KillableThread = None # Will be defined on loadClocks
KillableThread(target=resetRestartCount, daemon=True, name="Main: Restart counter").start()
KillableThread(target=timeStrThread, daemon=True, name="Main: Locale string loader").start()
loadClocks()
print(f"🟢 Loaded clocks in {time.time()-FirstTime}")
tdir = tempfile.TemporaryDirectory()
tempDir = tdir.name
sw = SettingsWindow() # Declare settings window
i = TaskbarIconTray(app)
mController = MouseController()
app.primaryScreenChanged.connect(lambda: os.startfile(sys.executable))
app.screenAdded.connect(lambda: os.startfile(sys.executable))
app.screenRemoved.connect(lambda: os.startfile(sys.executable))
signal = RestartSignal()
showNotif = InfoSignal()
showWarn = InfoSignal()
killSignal = InfoSignal()
showNotif.infoSignal.connect(lambda a, b: showMessage(a, b))
showWarn.infoSignal.connect(lambda a, b: wanrUserAboutUpdates(a, b))
killSignal.infoSignal.connect(lambda: app.quit())
signal.restartSignal.connect(lambda: restartClocks("checkLoop"))
KillableThread(target=updateChecker, daemon=True, name="Main: Updater").start()
KillableThread(target=isElevenClockRunningThread, daemon=True, name="Main: Instance controller").start()
if not getSettings("EnableLowCpuMode"): KillableThread(target=checkIfWokeUpThread, daemon=True, name="Main: Sleep listener").start()
if not getSettings("EnableLowCpuMode"): KillableThread(target=wnfDataThread, daemon=True, name="Main: WNF Data listener").start()
print("🔵 Low cpu mode is set to", str(getSettings("EnableLowCpuMode"))+". DisableNotifications is set to", getSettings("DisableNotifications"))
rdpThread = KillableThread(target=checkRDP, daemon=True, name="Main: Remote desktop controller")
if getSettings("EnableHideOnRDP"):
rdpThread.start()
globals.tempDir = tempDir # Register global variables
globals.old_stdout = old_stdout # Register global variables
globals.buffer = buffer # Register global variables
globals.app = app # Register global variables
globals.sw = sw # Register global variables
globals.trayIcon = i # Register global variables
globals.loadTimeFormat = loadTimeFormat # Register global functions
globals.updateIfPossible = updateIfPossible # Register global functions
globals.restartClocks = restartClocks # Register global functions
globals.closeClocks = closeClocks # Register global functions
if not(getSettings("Updated3.21Already")) and not(getSettings("EnableSilentUpdates")):
setSettings("ForceClockOnFirstMonitor", True)
setSettings("Updated3.21Already", True)
msg = QFramelessDialog(parent=None, closeOnClick=False)
msg.setAutoFillBackground(True)
msg.setStyleSheet(sw.styleSheet())
msg.setAttribute(QtCore.Qt.WA_StyledBackground)
msg.setObjectName("QMessageBox")
msg.setTitle("ElevenClock Updater")
msg.setText(f"""<b>ElevenClock has updated to version {versionName} successfully.</b>
<br><br>This update brings:<br>
<ul><li>The ability to specify a clock minimum width</li>
<li> The ability to search through the settings</li>
<li> Fixed an aesthetic issue with the seconds</li>
<li> Added a button to reset ElevenClock</li>
<li> Fixed an issue where ElevenClock would crash when clicking the right-click menu</li>
<li> Added Nynorsk</li>
<li> Some bugfixing and other improvements</li></ul>""")
msg.addButton("Ok", QDialogButtonBox.ButtonRole.ApplyRole, lambda: msg.close())
msg.addButton("Full changelog", QDialogButtonBox.ButtonRole.ResetRole, lambda: os.startfile("https://github.com/martinet101/ElevenClock/releases"))
def settNClose():
sw.show()
msg.close()
msg.addButton("Settings", QDialogButtonBox.ButtonRole.ActionRole, lambda: settNClose())
msg.setDefaultButtonRole(QDialogButtonBox.ButtonRole.ApplyRole, sw.styleSheet())
msg.setWindowTitle("ElevenClock has updated!")
msg.show()
showSettings = False
if "--settings" in sys.argv or showSettings:
sw.show()
if not getSettings("DefaultPrefsLoaded"):
setSettings("AlreadyInstalled", True)
setSettings("NewFullScreenMethod", True)
setSettings("ForceClockOnFirstMonitor", True)
showMessage("Welcome to ElevenClock", "You can customize Elevenclock from the ElevenClock Settings. You can search them on the start menu or right-clicking on any clock -> ElevenClock Settings", uBtn=False)
print("🟢 Default settings loaded")
setSettings("DefaultPrefsLoaded", True)
showWelcomeWizard = False
if showWelcomeWizard or "--welcome" in sys.argv:
import welcome
ww = welcome.WelcomeWindow()
print(f"🟢 Loaded everything in {time.time()-FirstTime}")
if "--quit-on-loaded" in sys.argv: # This is a testing feature to test if the script can load successfully
sys.exit(0)
app.exec_()
sys.exit(0)
except Exception as e:
import webbrowser, traceback, platform
if not "versionName" in locals() and not "versionName" in globals():
versionName = "Unknown"
if not "version" in locals() and not "version" in globals():
version = "Unknown"
os_info = f"" + \
f" OS: {platform.system()}\n"+\
f" Version: {platform.win32_ver()}\n"+\
f" OS Architecture: {platform.machine()}\n"+\
f" APP Architecture: {platform.architecture()[0]}\n"+\
f" APP Version: {versionName}\n"+\
f" APP Version Code: {version}\n"+\
f" Program: ElevenClock"+\
"\n\n-----------------------------------------------------------------------------------------"
traceback_info = "Traceback (most recent call last):\n"
try:
for line in traceback.extract_tb(e.__traceback__).format():
traceback_info += line
traceback_info += f"\n{type(e).__name__}: {str(e)}"
except:
traceback_info += "\nUnable to get traceback"
traceback_info += str(type(e))
traceback_info += ": "
traceback_info += str(e)
webbrowser.open(("https://www.somepythonthings.tk/error-report/?appName=ElevenClock&errorBody="+os_info.replace('\n', '{l}').replace(' ', '{s}')+"{l}{l}{l}{l}ElevenClock Log:{l}"+str("\n\n\n\n"+traceback_info).replace('\n', '{l}').replace(' ', '{s}')).replace("#", "|=|"))
print(traceback_info)
sys.exit(1) | true | true |
f7109ddb17e4780f3af2f2375fee8cd66928aded | 1,069 | py | Python | Chapter03/scrapelxml.py | elephantscale/Hands-On-Web-Scraping-with-Python | 013069a23c5bc3846ab475c5774bc6ff9a27c348 | [
"MIT"
] | 43 | 2019-03-05T12:37:35.000Z | 2022-01-24T11:43:37.000Z | Chapter03/scrapelxml.py | elephantscale/Hands-On-Web-Scraping-with-Python | 013069a23c5bc3846ab475c5774bc6ff9a27c348 | [
"MIT"
] | 1 | 2019-12-29T10:34:13.000Z | 2020-08-10T07:19:28.000Z | Chapter03/scrapelxml.py | elephantscale/Hands-On-Web-Scraping-with-Python | 013069a23c5bc3846ab475c5774bc6ff9a27c348 | [
"MIT"
] | 42 | 2019-05-02T10:28:35.000Z | 2022-02-16T16:45:48.000Z | import lxml.html
musicUrl= "http://books.toscrape.com/catalogue/category/books/music_14/index.html"
doc = lxml.html.parse(musicUrl)
#base element
articles = doc.xpath("//*[@id='default']/div/div/div/div/section/div[2]/ol/li[1]/article")[0]
#individual element inside base
title = articles.xpath("//h3/a/text()")
price = articles.xpath("//div[2]/p[contains(@class,'price_color')]/text()")
availability = articles.xpath("//div[2]/p[2][contains(@class,'availability')]/text()[normalize-space()]")
imageUrl = articles.xpath("//div[1][contains(@class,'image_container')]/a/img/@src")
starRating = articles.xpath("//p[contains(@class,'star-rating')]/@class")
#cleaning and formatting
stock = list(map(lambda stock:stock.strip(),availability))
images = list(map(lambda img:img.replace('../../../..','http://books.toscrape.com'),imageUrl))
rating = list(map(lambda rating:rating.replace('star-rating ',''),starRating))
print(title)
print(price)
print(stock)
print(images)
print(rating)
#Merging all
dataset = zip(title,price,stock,images,rating)
print(list(dataset))
| 35.633333 | 105 | 0.715622 | import lxml.html
musicUrl= "http://books.toscrape.com/catalogue/category/books/music_14/index.html"
doc = lxml.html.parse(musicUrl)
articles = doc.xpath("//*[@id='default']/div/div/div/div/section/div[2]/ol/li[1]/article")[0]
title = articles.xpath("//h3/a/text()")
price = articles.xpath("//div[2]/p[contains(@class,'price_color')]/text()")
availability = articles.xpath("//div[2]/p[2][contains(@class,'availability')]/text()[normalize-space()]")
imageUrl = articles.xpath("//div[1][contains(@class,'image_container')]/a/img/@src")
starRating = articles.xpath("//p[contains(@class,'star-rating')]/@class")
stock = list(map(lambda stock:stock.strip(),availability))
images = list(map(lambda img:img.replace('../../../..','http://books.toscrape.com'),imageUrl))
rating = list(map(lambda rating:rating.replace('star-rating ',''),starRating))
print(title)
print(price)
print(stock)
print(images)
print(rating)
dataset = zip(title,price,stock,images,rating)
print(list(dataset))
| true | true |
f7109e2a81729843d72c0ff010349421f9434137 | 3,018 | py | Python | sdk/monitor/azure-monitor-query/setup.py | rsdoherty/azure-sdk-for-python | 6bba5326677468e6660845a703686327178bb7b1 | [
"MIT"
] | 1 | 2021-09-16T02:33:52.000Z | 2021-09-16T02:33:52.000Z | sdk/monitor/azure-monitor-query/setup.py | rsdoherty/azure-sdk-for-python | 6bba5326677468e6660845a703686327178bb7b1 | [
"MIT"
] | 1 | 2019-08-05T19:14:28.000Z | 2019-08-05T19:30:05.000Z | sdk/monitor/azure-monitor-query/setup.py | rsdoherty/azure-sdk-for-python | 6bba5326677468e6660845a703686327178bb7b1 | [
"MIT"
] | 1 | 2016-04-19T22:15:47.000Z | 2016-04-19T22:15:47.000Z | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
import re
import os.path
from io import open
from setuptools import find_packages, setup
# Change the PACKAGE_NAME only to change folder and different name
PACKAGE_NAME = "azure-monitor-query"
PACKAGE_PPRINT_NAME = "Azure Monitor Query"
# a-b-c => a/b/c
package_folder_path = PACKAGE_NAME.replace('-', '/')
# a-b-c => a.b.c
namespace_name = PACKAGE_NAME.replace('-', '.')
# azure v0.x is not compatible with this package
# azure v0.x used to have a __version__ attribute (newer versions don't)
try:
import azure
try:
ver = azure.__version__
raise Exception(
'This package is incompatible with azure=={}. '.format(ver) +
'Uninstall it with "pip uninstall azure".'
)
except AttributeError:
pass
except ImportError:
pass
# Version extraction inspired from 'requests'
with open(os.path.join(package_folder_path, 'version.py')
if os.path.exists(os.path.join(package_folder_path, 'version.py'))
else os.path.join(package_folder_path, '_version.py'), 'r') as fd:
version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version:
raise RuntimeError('Cannot find version information')
with open('README.md', encoding='utf-8') as f:
readme = f.read()
with open('CHANGELOG.md', encoding='utf-8') as f:
changelog = f.read()
setup(
name=PACKAGE_NAME,
version=version,
description='Microsoft {} Client Library for Python'.format(PACKAGE_PPRINT_NAME),
long_description=readme + '\n\n' + changelog,
long_description_content_type='text/markdown',
license='MIT License',
author='Microsoft Corporation',
author_email='azpysdkhelp@microsoft.com',
url='https://github.com/Azure/azure-sdk-for-python',
classifiers=[
"Development Status :: 4 - Beta",
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'License :: OSI Approved :: MIT License',
],
zip_safe=False,
packages=find_packages(exclude=[
'tests',
'samples',
# Exclude packages that will be covered by PEP420 or nspkg
'azure',
'azure.monitor',
]),
install_requires=[
'msrest>=0.6.19',
'azure-core<2.0.0,>=1.12.0',
],
extras_require={
":python_version<'3.0'": ['azure-monitor-nspkg'],
}
)
| 33.164835 | 85 | 0.60603 |
import re
import os.path
from io import open
from setuptools import find_packages, setup
PACKAGE_NAME = "azure-monitor-query"
PACKAGE_PPRINT_NAME = "Azure Monitor Query"
package_folder_path = PACKAGE_NAME.replace('-', '/')
namespace_name = PACKAGE_NAME.replace('-', '.')
try:
import azure
try:
ver = azure.__version__
raise Exception(
'This package is incompatible with azure=={}. '.format(ver) +
'Uninstall it with "pip uninstall azure".'
)
except AttributeError:
pass
except ImportError:
pass
# Version extraction inspired from 'requests'
with open(os.path.join(package_folder_path, 'version.py')
if os.path.exists(os.path.join(package_folder_path, 'version.py'))
else os.path.join(package_folder_path, '_version.py'), 'r') as fd:
version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version:
raise RuntimeError('Cannot find version information')
with open('README.md', encoding='utf-8') as f:
readme = f.read()
with open('CHANGELOG.md', encoding='utf-8') as f:
changelog = f.read()
setup(
name=PACKAGE_NAME,
version=version,
description='Microsoft {} Client Library for Python'.format(PACKAGE_PPRINT_NAME),
long_description=readme + '\n\n' + changelog,
long_description_content_type='text/markdown',
license='MIT License',
author='Microsoft Corporation',
author_email='azpysdkhelp@microsoft.com',
url='https://github.com/Azure/azure-sdk-for-python',
classifiers=[
"Development Status :: 4 - Beta",
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'License :: OSI Approved :: MIT License',
],
zip_safe=False,
packages=find_packages(exclude=[
'tests',
'samples',
# Exclude packages that will be covered by PEP420 or nspkg
'azure',
'azure.monitor',
]),
install_requires=[
'msrest>=0.6.19',
'azure-core<2.0.0,>=1.12.0',
],
extras_require={
":python_version<'3.0'": ['azure-monitor-nspkg'],
}
)
| true | true |
f7109e5f329e34712969175bcdd6c832599f7ef5 | 1,218 | py | Python | mandala/tests/test_call_graph.py | amakelov/mandala | a9ec051ef730ada4eed216c62a07b033126e78d5 | [
"Apache-2.0"
] | 9 | 2022-02-22T19:24:01.000Z | 2022-03-23T04:46:41.000Z | mandala/tests/test_call_graph.py | amakelov/mandala | a9ec051ef730ada4eed216c62a07b033126e78d5 | [
"Apache-2.0"
] | null | null | null | mandala/tests/test_call_graph.py | amakelov/mandala | a9ec051ef730ada4eed216c62a07b033126e78d5 | [
"Apache-2.0"
] | null | null | null | from .utils import *
from .funcs import *
def test_unit():
storage = Storage()
@op(storage)
def f(x:int) -> int:
return x + 1
@superop(storage)
def f_twice(x:int) -> int:
return f(f(x))
with run(storage, autocommit=True):
f_twice(42)
cg = storage.call_graph_st
nodes = cg.get_nodes()
assert nodes == [f_twice.op.qualified_name, f.op.qualified_name]
assert cg.get_neighbors(node=nodes[0]) == [f.op.qualified_name]
assert cg.get_callers(node=f.op.qualified_name) == [f_twice.op.qualified_name]
### now, check that we detect invalidation of previous version of calling superop
@op(storage, version='1')
def f(x:int) -> int:
return x - 1
# this should not work
try:
@superop(storage)
def f_twice(x:int) -> int:
return f(f(x))
assert False
except SynchronizationError:
assert True
except:
assert False
# this should work
try:
@superop(storage, version='1')
def f_twice(x:int) -> int:
return f(f(x))
assert True
except SynchronizationError:
assert False
except:
assert False | 24.857143 | 85 | 0.587028 | from .utils import *
from .funcs import *
def test_unit():
storage = Storage()
@op(storage)
def f(x:int) -> int:
return x + 1
@superop(storage)
def f_twice(x:int) -> int:
return f(f(x))
with run(storage, autocommit=True):
f_twice(42)
cg = storage.call_graph_st
nodes = cg.get_nodes()
assert nodes == [f_twice.op.qualified_name, f.op.qualified_name]
assert cg.get_neighbors(node=nodes[0]) == [f.op.qualified_name]
assert cg.get_callers(node=f.op.qualified_name) == [f_twice.op.qualified_name]
return f(f(x))
assert False
except SynchronizationError:
assert True
except:
assert False
try:
@superop(storage, version='1')
def f_twice(x:int) -> int:
return f(f(x))
assert True
except SynchronizationError:
assert False
except:
assert False | true | true |
f7109e8ff05634250514692e37d4f0e4532aeadd | 364 | py | Python | tests/conanbuilder/test_remote.py | arnaudgelas/mumoco | f38db5bdccc93473e2b8bfeb8e7f2884063fd9de | [
"MIT"
] | null | null | null | tests/conanbuilder/test_remote.py | arnaudgelas/mumoco | f38db5bdccc93473e2b8bfeb8e7f2884063fd9de | [
"MIT"
] | null | null | null | tests/conanbuilder/test_remote.py | arnaudgelas/mumoco | f38db5bdccc93473e2b8bfeb8e7f2884063fd9de | [
"MIT"
] | null | null | null | import pytest
from src.conanbuilder.remote import Remote
@pytest.fixture
def remote():
return Remote("myName", "myUrl")
def test_default_values(remote):
assert remote.name == "myName"
assert remote.url == "myUrl"
assert remote.verify_ssl is True
assert remote.priority == 0
assert remote.force is False
assert remote.login is False
| 21.411765 | 42 | 0.717033 | import pytest
from src.conanbuilder.remote import Remote
@pytest.fixture
def remote():
return Remote("myName", "myUrl")
def test_default_values(remote):
assert remote.name == "myName"
assert remote.url == "myUrl"
assert remote.verify_ssl is True
assert remote.priority == 0
assert remote.force is False
assert remote.login is False
| true | true |
f7109ec47cb12c07cbd7c2c04ebf2dc466ee9099 | 423 | py | Python | commons/templatetags/common_tags.py | lsalta/mapground | d927d283dab6f756574bd88b3251b9e68f000ca7 | [
"MIT"
] | null | null | null | commons/templatetags/common_tags.py | lsalta/mapground | d927d283dab6f756574bd88b3251b9e68f000ca7 | [
"MIT"
] | 3 | 2020-02-11T23:04:56.000Z | 2021-06-10T18:07:53.000Z | commons/templatetags/common_tags.py | lsalta/mapground | d927d283dab6f756574bd88b3251b9e68f000ca7 | [
"MIT"
] | 1 | 2021-08-20T14:49:09.000Z | 2021-08-20T14:49:09.000Z | from django import template
from django.conf import settings
from django.utils.safestring import mark_safe
register = template.Library()
# settings value
@register.simple_tag
def settings_value(name):
defaults = {
'SITE_HEADER': '<b>Map</b>Ground',
'SITE_TITLE': 'MapGround'
}
if name in defaults:
return mark_safe(getattr(settings, name, defaults[name]))
else:
return ''
| 22.263158 | 65 | 0.680851 | from django import template
from django.conf import settings
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag
def settings_value(name):
defaults = {
'SITE_HEADER': '<b>Map</b>Ground',
'SITE_TITLE': 'MapGround'
}
if name in defaults:
return mark_safe(getattr(settings, name, defaults[name]))
else:
return ''
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.