index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
21,677 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/rules/yarn_help.py | 12,13 | 1,18 | get_new_command | 13,18 | 13,18 | import re
from thefuck.utils import for_app
from thefuck.system import open_command
@for_app('yarn', at_least=2)
def match(command):
return (command.script_parts[1] == 'help'
and 'for documentation about this command.' in command.output)
def get_new_command(command):
FILL_FUNC_BODY | import re
from thefuck.utils import for_app
from thefuck.system import open_command
@for_app('yarn', at_least=2)
def match(command):
return (command.script_parts[1] == 'help'
and 'for documentation about this command.' in command.output)
def get_new_command(command):
FILL_FUNC_BODY | url = re.findall(
r'Visit ([^ ]*) for documentation about this command.',
command.output)[0]
return open_command(url)
| url = re.findall(
r'Visit ([^ ]*) for documentation about this command.',
command.output)[0]
return open_command(url)
| 14 | 101 | 48 | 149 | import re
from thefuck.utils import for_app
from thefuck.system import open_command
@for_app('yarn', at_least=2)
def match(command):
return (command.script_parts[1] == 'help'
and 'for documentation about this command.' in command.output)
def get_new_command(command):
FILL_FUNC_BODY | import re
from thefuck.utils import for_app
from thefuck.system import open_command
@for_app('yarn', at_least=2)
def match(command):
return (command.script_parts[1] == 'help'
and 'for documentation about this command.' in command.output)
def get_new_command(command):
FILL_FUNC_BODY | |
21,678 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/rules/yum_invalid_operation.py | 17,18 | 1,40 | _get_operations | 18,28 | 18,28 | import subprocess
from itertools import dropwhile, islice, takewhile
from thefuck.specific.sudo import sudo_support
from thefuck.specific.yum import yum_available
from thefuck.utils import for_app, replace_command, which, cache
enabled_by_default = yum_available
@sudo_support
@for_app('yum')
def match(command):
... | import subprocess
from itertools import dropwhile, islice, takewhile
from thefuck.specific.sudo import sudo_support
from thefuck.specific.yum import yum_available
from thefuck.utils import for_app, replace_command, which, cache
enabled_by_default = yum_available
@sudo_support
@for_app('yum')
def match(command):
... | proc = subprocess.Popen('yum', stdout=subprocess.PIPE)
lines = proc.stdout.readlines()
lines = [line.decode('utf-8') for line in lines]
lines = dropwhile(lambda line: not line.startswith("List of Commands:"), lines)
lines = islice(lines, 2, None)
lines = list(takewhile(lambda line: line.strip()... | proc = subprocess.Popen('yum', stdout=subprocess.PIPE)
lines = proc.stdout.readlines()
lines = [line.decode('utf-8') for line in lines]
lines = dropwhile(lambda line: not line.startswith("List of Commands:"), lines)
lines = islice(lines, 2, None)
lines = list(takewhile(lambda line: line.strip()... | 41 | 242 | 142 | 384 | import subprocess
from itertools import dropwhile, islice, takewhile
from thefuck.specific.sudo import sudo_support
from thefuck.specific.yum import yum_available
from thefuck.utils import for_app, replace_command, which, cache
enabled_by_default = yum_available
@sudo_support
@for_app('yum')
def match(command):
... | import subprocess
from itertools import dropwhile, islice, takewhile
from thefuck.specific.sudo import sudo_support
from thefuck.specific.yum import yum_available
from thefuck.utils import for_app, replace_command, which, cache
enabled_by_default = yum_available
@sudo_support
@for_app('yum')
def match(command):
... | |
21,680 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/shells/bash.py | 14,15 | 11,93 | app_alias | Bash | 15,37 | 15,37 | class Bash(Generic):
friendly_name = 'Bash'
def app_alias(self, alias_name):
FILL_FUNC_BODY def instant_mode_alias(self, alias_name):
if os.environ.get('THEFUCK_INSTANT_MODE', '').lower() == 'true':
mark = USER_COMMAND_MARK + '\b' * len(USER_COMMAND_MARK)
return '''
... | class Bash(Generic):
friendly_name = 'Bash'
def app_alias(self, alias_name):
FILL_FUNC_BODY def instant_mode_alias(self, alias_name):
if os.environ.get('THEFUCK_INSTANT_MODE', '').lower() == 'true':
mark = USER_COMMAND_MARK + '\b' * len(USER_COMMAND_MARK)
return '''
... | # It is VERY important to have the variables declared WITHIN the function
return '''
function {name} () {{
TF_PYTHONIOENCODING=$PYTHONIOENCODING;
export TF_SHELL=bash;
export TF_ALIAS={name};
export TF_SHELL_ALIASES=$(alias);
... | # It is VERY important to have the variables declared WITHIN the function
return '''
function {name} () {{
TF_PYTHONIOENCODING=$PYTHONIOENCODING;
export TF_SHELL=bash;
export TF_ALIAS={name};
export TF_SHELL_ALIASES=$(alias);
... | 56 | 730 | 294 | 1,024 | import os
from subprocess import Popen, PIPE
from tempfile import gettempdir
from uuid import uuid4
from ..conf import settings
from ..const import ARGUMENT_PLACEHOLDER, USER_COMMAND_MARK
from ..utils import DEVNULL, memoize
from .generic import Generic
class Bash(Generic):
friendly_name = 'Bash'
def app_ali... | import os
from subprocess import Popen, PIPE
from tempfile import gettempdir
from uuid import uuid4
from ..conf import settings
from ..const import ARGUMENT_PLACEHOLDER, USER_COMMAND_MARK
from ..utils import DEVNULL, memoize
from .generic import Generic
class Bash(Generic):
friendly_name = 'Bash'
def app_ali... |
21,681 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/shells/fish.py | 20,22 | 1,130 | _get_aliases | 22,40 | 22,40 | from subprocess import Popen, PIPE
from time import time
import os
import sys
import six
from .. import logs
from ..conf import settings
from ..const import ARGUMENT_PLACEHOLDER
from ..utils import DEVNULL, cache
from .generic import Generic
@cache('~/.config/fish/config.fish', '~/.config/fish/functions')
def _get_fu... | from subprocess import Popen, PIPE
from time import time
import os
import sys
import six
from .. import logs
from ..conf import settings
from ..const import ARGUMENT_PLACEHOLDER
from ..utils import DEVNULL, cache
from .generic import Generic
@cache('~/.config/fish/config.fish', '~/.config/fish/functions')
def _get_fu... | aliases = {}
proc = Popen(['fish', '-ic', 'alias'], stdout=PIPE, stderr=DEVNULL)
alias_out = proc.stdout.read().decode('utf-8').strip()
if not alias_out:
return aliases
for alias in alias_out.split('\n'):
for separator in (' ', '='):
split_alias = alias.replace('alias ', ... | aliases = {}
proc = Popen(['fish', '-ic', 'alias'], stdout=PIPE, stderr=DEVNULL)
alias_out = proc.stdout.read().decode('utf-8').strip()
if not alias_out:
return aliases
for alias in alias_out.split('\n'):
for separator in (' ', '='):
split_alias = alias.replace('alias ', ... | 56 | 1,311 | 194 | 1,505 | from subprocess import Popen, PIPE
from time import time
import os
import sys
import six
from .. import logs
from ..conf import settings
from ..const import ARGUMENT_PLACEHOLDER
from ..utils import DEVNULL, cache
from .generic import Generic
@cache('~/.config/fish/config.fish', '~/.config/fish/functions')
def _get_fu... | from subprocess import Popen, PIPE
from time import time
import os
import sys
import six
from .. import logs
from ..conf import settings
from ..const import ARGUMENT_PLACEHOLDER
from ..utils import DEVNULL, cache
from .generic import Generic
@cache('~/.config/fish/config.fish', '~/.config/fish/functions')
def _get_fu... | |
21,682 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/shells/fish.py | 43,44 | 40,130 | _get_overridden_aliases | Fish | 44,51 | 44,51 | class Fish(Generic):
friendly_name = 'Fish Shell'
def _get_overridden_aliases(self):
FILL_FUNC_BODY def app_alias(self, alias_name):
if settings.alter_history:
alter_history = (' builtin history delete --exact'
' --case-sensitive -- $fucked_up_command\n'
... | class Fish(Generic):
friendly_name = 'Fish Shell'
def _get_overridden_aliases(self):
FILL_FUNC_BODY def app_alias(self, alias_name):
if settings.alter_history:
alter_history = (' builtin history delete --exact'
' --case-sensitive -- $fucked_up_command\n'
... | overridden = os.environ.get('THEFUCK_OVERRIDDEN_ALIASES',
os.environ.get('TF_OVERRIDDEN_ALIASES', ''))
default = {'cd', 'grep', 'ls', 'man', 'open'}
for alias in overridden.split(','):
default.add(alias.strip())
return sorted(default)
| overridden = os.environ.get('THEFUCK_OVERRIDDEN_ALIASES',
os.environ.get('TF_OVERRIDDEN_ALIASES', ''))
default = {'cd', 'grep', 'ls', 'man', 'open'}
for alias in overridden.split(','):
default.add(alias.strip())
return sorted(default)
| 19 | 1,002 | 113 | 1,115 | from subprocess import Popen, PIPE
from time import time
import os
import sys
import six
from .. import logs
from ..conf import settings
from ..const import ARGUMENT_PLACEHOLDER
from ..utils import DEVNULL, cache
from .generic import Generic
@cache('~/.config/fish/config.fish', '~/.config/fish/functions')
def _get_fu... | from subprocess import Popen, PIPE
from time import time
import os
import sys
import six
from .. import logs
from ..conf import settings
from ..const import ARGUMENT_PLACEHOLDER
from ..utils import DEVNULL, cache
from .generic import Generic
@cache('~/.config/fish/config.fish', '~/.config/fish/functions')
def _get_fu... |
21,683 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/shells/generic.py | 140,141 | 16,155 | info | Generic | 142,149 | 141,149 | class Generic(object):
friendly_name = 'Generic Shell'
def get_aliases(self):
return {}
def _expand_aliases(self, command_script):
aliases = self.get_aliases()
binary = command_script.split(' ')[0]
if binary in aliases:
return command_script.replace(binary, alia... | class Generic(object):
friendly_name = 'Generic Shell'
def get_aliases(self):
return {}
def _expand_aliases(self, command_script):
aliases = self.get_aliases()
binary = command_script.split(' ')[0]
if binary in aliases:
return command_script.replace(binary, alia... | try:
version = self._get_version()
except Exception as e:
warn(u'Could not determine shell version: {}'.format(e))
version = ''
return u'{} {}'.format(self.friendly_name, version).rstrip()
| """Returns the name and version of the current shell"""
try:
version = self._get_version()
except Exception as e:
warn(u'Could not determine shell version: {}'.format(e))
version = ''
return u'{} {}'.format(self.friendly_name, version).rstrip()
| 21 | 1,268 | 73 | 1,341 | import io
import os
import shlex
import six
from collections import namedtuple
from ..logs import warn
from ..utils import memoize
from ..conf import settings
from ..system import Path
ShellConfiguration = namedtuple('ShellConfiguration', (
'content', 'path', 'reload', 'can_configure_automatically'))
class Gene... | import io
import os
import shlex
import six
from collections import namedtuple
from ..logs import warn
from ..utils import memoize
from ..conf import settings
from ..system import Path
ShellConfiguration = namedtuple('ShellConfiguration', (
'content', 'path', 'reload', 'can_configure_automatically'))
class Gene... |
21,684 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/shells/powershell.py | 32,33 | 6,44 | _get_version | Powershell | 34,44 | 33,44 | class Powershell(Generic):
friendly_name = 'PowerShell'
def app_alias(self, alias_name):
return 'function ' + alias_name + ' {\n' \
' $history = (Get-History -Count 1).CommandLine;\n' \
' if (-not [string]::IsNullOrWhiteSpace($history)) {\n' \
' ... | class Powershell(Generic):
friendly_name = 'PowerShell'
def app_alias(self, alias_name):
return 'function ' + alias_name + ' {\n' \
' $history = (Get-History -Count 1).CommandLine;\n' \
' if (-not [string]::IsNullOrWhiteSpace($history)) {\n' \
' ... | try:
proc = Popen(
['powershell.exe', '$PSVersionTable.PSVersion'],
stdout=PIPE,
stderr=DEVNULL)
version = proc.stdout.read().decode('utf-8').rstrip().split('\n')
return '.'.join(version[-1].split())
except IOError:
... | """Returns the version of the current shell"""
try:
proc = Popen(
['powershell.exe', '$PSVersionTable.PSVersion'],
stdout=PIPE,
stderr=DEVNULL)
version = proc.stdout.read().decode('utf-8').rstrip().split('\n')
return '.'... | 23 | 356 | 150 | 506 | from subprocess import Popen, PIPE
from ..utils import DEVNULL
from .generic import Generic, ShellConfiguration
class Powershell(Generic):
friendly_name = 'PowerShell'
def app_alias(self, alias_name):
return 'function ' + alias_name + ' {\n' \
' $history = (Get-History -Count 1).Com... | from subprocess import Popen, PIPE
from ..utils import DEVNULL
from .generic import Generic, ShellConfiguration
class Powershell(Generic):
friendly_name = 'PowerShell'
def app_alias(self, alias_name):
return 'function ' + alias_name + ' {\n' \
' $history = (Get-History -Count 1).Com... |
21,685 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/shells/tcsh.py | 11,12 | 8,45 | app_alias | Tcsh | 12,16 | 12,16 | class Tcsh(Generic):
friendly_name = 'Tcsh'
def app_alias(self, alias_name):
FILL_FUNC_BODY def _parse_alias(self, alias):
name, value = alias.split("\t", 1)
return name, value
@memoize
def get_aliases(self):
proc = Popen(['tcsh', '-ic', 'alias'], stdout=PIPE, stderr=DEVNULL... | class Tcsh(Generic):
friendly_name = 'Tcsh'
def app_alias(self, alias_name):
FILL_FUNC_BODY def _parse_alias(self, alias):
name, value = alias.split("\t", 1)
return name, value
@memoize
def get_aliases(self):
proc = Popen(['tcsh', '-ic', 'alias'], stdout=PIPE, stderr=DEVNULL... | return ("alias {0} 'setenv TF_SHELL tcsh && setenv TF_ALIAS {0} && "
"set fucked_cmd=`history -h 2 | head -n 1` && "
"eval `thefuck ${{fucked_cmd}}`'").format(alias_name)
| return ("alias {0} 'setenv TF_SHELL tcsh && setenv TF_ALIAS {0} && "
"set fucked_cmd=`history -h 2 | head -n 1` && "
"eval `thefuck ${{fucked_cmd}}`'").format(alias_name)
| 25 | 382 | 87 | 469 | from subprocess import Popen, PIPE
from time import time
import os
from ..utils import DEVNULL, memoize
from .generic import Generic
class Tcsh(Generic):
friendly_name = 'Tcsh'
def app_alias(self, alias_name):
FILL_FUNC_BODY def _parse_alias(self, alias):
name, value = alias.split("\t", 1)
... | from subprocess import Popen, PIPE
from time import time
import os
from ..utils import DEVNULL, memoize
from .generic import Generic
class Tcsh(Generic):
friendly_name = 'Tcsh'
def app_alias(self, alias_name):
FILL_FUNC_BODY def _parse_alias(self, alias):
name, value = alias.split("\t", 1)
... |
21,686 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/shells/zsh.py | 92,93 | 12,97 | _get_version | Zsh | 94,97 | 93,97 | class Zsh(Generic):
friendly_name = 'ZSH'
def app_alias(self, alias_name):
# It is VERY important to have the variables declared WITHIN the function
return '''
{name} () {{
TF_PYTHONIOENCODING=$PYTHONIOENCODING;
export TF_SHELL=zsh;
ex... | class Zsh(Generic):
friendly_name = 'ZSH'
def app_alias(self, alias_name):
# It is VERY important to have the variables declared WITHIN the function
return '''
{name} () {{
TF_PYTHONIOENCODING=$PYTHONIOENCODING;
export TF_SHELL=zsh;
ex... | proc = Popen(['zsh', '-c', 'echo $ZSH_VERSION'],
stdout=PIPE, stderr=DEVNULL)
return proc.stdout.read().decode('utf-8').strip()
| """Returns the version of the current shell"""
proc = Popen(['zsh', '-c', 'echo $ZSH_VERSION'],
stdout=PIPE, stderr=DEVNULL)
return proc.stdout.read().decode('utf-8').strip()
| 10 | 965 | 57 | 1,022 | from time import time
import os
from subprocess import Popen, PIPE
from tempfile import gettempdir
from uuid import uuid4
from ..conf import settings
from ..const import ARGUMENT_PLACEHOLDER, USER_COMMAND_MARK
from ..utils import DEVNULL, memoize
from .generic import Generic
class Zsh(Generic):
friendly_name = 'Z... | from time import time
import os
from subprocess import Popen, PIPE
from tempfile import gettempdir
from uuid import uuid4
from ..conf import settings
from ..const import ARGUMENT_PLACEHOLDER, USER_COMMAND_MARK
from ..utils import DEVNULL, memoize
from .generic import Generic
class Zsh(Generic):
friendly_name = 'Z... |
21,687 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/specific/archlinux.py | 34,35 | 1,49 | archlinux_env | 35,49 | 35,49 | """ This file provide some utility functions for Arch Linux specific rules."""
import subprocess
from .. import utils
@utils.memoize
def get_pkgfile(command):
""" Gets the packages that provide the given command using `pkgfile`.
If the command is of the form `sudo foo`, searches for the `foo` command
ins... | """ This file provide some utility functions for Arch Linux specific rules."""
import subprocess
from .. import utils
@utils.memoize
def get_pkgfile(command):
""" Gets the packages that provide the given command using `pkgfile`.
If the command is of the form `sudo foo`, searches for the `foo` command
ins... | if utils.which('yay'):
pacman = 'yay'
elif utils.which('pikaur'):
pacman = 'pikaur'
elif utils.which('yaourt'):
pacman = 'yaourt'
elif utils.which('pacman'):
pacman = 'sudo pacman'
else:
return False, None
enabled_by_default = utils.which('pkgfile')
... | if utils.which('yay'):
pacman = 'yay'
elif utils.which('pikaur'):
pacman = 'pikaur'
elif utils.which('yaourt'):
pacman = 'yaourt'
elif utils.which('pacman'):
pacman = 'sudo pacman'
else:
return False, None
enabled_by_default = utils.which('pkgfile')
... | 31 | 260 | 141 | 401 | """ This file provide some utility functions for Arch Linux specific rules."""
import subprocess
from .. import utils
@utils.memoize
def get_pkgfile(command):
""" Gets the packages that provide the given command using `pkgfile`.
If the command is of the form `sudo foo`, searches for the `foo` command
ins... | """ This file provide some utility functions for Arch Linux specific rules."""
import subprocess
from .. import utils
@utils.memoize
def get_pkgfile(command):
""" Gets the packages that provide the given command using `pkgfile`.
If the command is of the form `sudo foo`, searches for the `foo` command
ins... | |
21,688 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/specific/brew.py | 8,10 | 1,16 | get_brew_path_prefix | 11,16 | 10,16 | import subprocess
from ..utils import memoize, which
brew_available = bool(which('brew'))
@memoize
def get_brew_path_prefix():
FILL_FUNC_BODY | import subprocess
from ..utils import memoize, which
brew_available = bool(which('brew'))
@memoize
def get_brew_path_prefix():
"""To get brew path"""
FILL_FUNC_BODY | try:
return subprocess.check_output(['brew', '--prefix'],
universal_newlines=True).strip()
except Exception:
return None
| """To get brew path"""
try:
return subprocess.check_output(['brew', '--prefix'],
universal_newlines=True).strip()
except Exception:
return None
| 9 | 62 | 45 | 107 | import subprocess
from ..utils import memoize, which
brew_available = bool(which('brew'))
@memoize
def get_brew_path_prefix():
FILL_FUNC_BODY | import subprocess
from ..utils import memoize, which
brew_available = bool(which('brew'))
@memoize
def get_brew_path_prefix():
"""To get brew path"""
FILL_FUNC_BODY | |
21,689 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/specific/npm.py | 8,11 | 1,22 | get_scripts | 12,22 | 11,22 | import re
from subprocess import Popen, PIPE
from thefuck.utils import memoize, eager, which
npm_available = bool(which('npm'))
@memoize
@eager
def get_scripts():
FILL_FUNC_BODY | import re
from subprocess import Popen, PIPE
from thefuck.utils import memoize, eager, which
npm_available = bool(which('npm'))
@memoize
@eager
def get_scripts():
"""Get custom npm scripts."""
FILL_FUNC_BODY | proc = Popen(['npm', 'run-script'], stdout=PIPE)
should_yeild = False
for line in proc.stdout.readlines():
line = line.decode()
if 'available via `npm run-script`:' in line:
should_yeild = True
continue
if should_yeild and re.match(r'^ [^ ]+', line):
... | """Get custom npm scripts."""
proc = Popen(['npm', 'run-script'], stdout=PIPE)
should_yeild = False
for line in proc.stdout.readlines():
line = line.decode()
if 'available via `npm run-script`:' in line:
should_yeild = True
continue
if should_yeild and re... | 36 | 77 | 123 | 200 | import re
from subprocess import Popen, PIPE
from thefuck.utils import memoize, eager, which
npm_available = bool(which('npm'))
@memoize
@eager
def get_scripts():
FILL_FUNC_BODY | import re
from subprocess import Popen, PIPE
from thefuck.utils import memoize, eager, which
npm_available = bool(which('npm'))
@memoize
@eager
def get_scripts():
"""Get custom npm scripts."""
FILL_FUNC_BODY | |
21,690 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/types.py | 35,37 | 12,85 | script_parts | Command | 37,47 | 37,47 | class Command(object):
"""Command that should be fixed."""
def __init__(self, script, output):
"""Initializes command with given values.
:type script: basestring
:type output: basestring
"""
self.script = script
self.output = output
@property
def stdou... | class Command(object):
"""Command that should be fixed."""
def __init__(self, script, output):
"""Initializes command with given values.
:type script: basestring
:type output: basestring
"""
self.script = script
self.output = output
@property
def stdou... | if not hasattr(self, '_script_parts'):
try:
self._script_parts = shell.split_command(self.script)
except Exception:
logs.debug(u"Can't split command script {} because:\n {}".format(
self, sys.exc_info()))
self._script_pa... | if not hasattr(self, '_script_parts'):
try:
self._script_parts = shell.split_command(self.script)
except Exception:
logs.debug(u"Can't split command script {} because:\n {}".format(
self, sys.exc_info()))
self._script_pa... | 24 | 474 | 103 | 577 | import os
import sys
from . import logs
from .shells import shell
from .conf import settings, load_source
from .const import DEFAULT_PRIORITY, ALL_ENABLED
from .exceptions import EmptyCommand
from .utils import get_alias, format_raw_script
from .output_readers import get_output
class Command(object):
"""Command t... | import os
import sys
from . import logs
from .shells import shell
from .conf import settings, load_source
from .const import DEFAULT_PRIORITY, ALL_ENABLED
from .exceptions import EmptyCommand
from .utils import get_alias, format_raw_script
from .output_readers import get_output
class Command(object):
"""Command t... |
21,691 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/types.py | 247,248 | 201,262 | run | CorrectedCommand | 253,262 | 248,262 | class CorrectedCommand(object):
"""Corrected by rule command."""
def __init__(self, script, side_effect, priority):
"""Initializes instance with given fields.
:type script: basestring
:type side_effect: (Command, basestring) -> None
:type priority: int
"""
self... | class CorrectedCommand(object):
"""Corrected by rule command."""
def __init__(self, script, side_effect, priority):
"""Initializes instance with given fields.
:type script: basestring
:type side_effect: (Command, basestring) -> None
:type priority: int
"""
self... | if self.side_effect:
self.side_effect(old_cmd, self.script)
if settings.alter_history:
shell.put_to_history(self.script)
# This depends on correct setting of PYTHONIOENCODING by the alias:
logs.debug(u'PYTHONIOENCODING: {}'.format(
os.environ.get('PYTH... | """Runs command from rule for passed command.
:type old_cmd: Command
"""
if self.side_effect:
self.side_effect(old_cmd, self.script)
if settings.alter_history:
shell.put_to_history(self.script)
# This depends on correct setting of PYTHONIOENCODIN... | 23 | 450 | 142 | 592 | import os
import sys
from . import logs
from .shells import shell
from .conf import settings, load_source
from .const import DEFAULT_PRIORITY, ALL_ENABLED
from .exceptions import EmptyCommand
from .utils import get_alias, format_raw_script
from .output_readers import get_output
class Command(object):
"""Command t... | import os
import sys
from . import logs
from .shells import shell
from .conf import settings, load_source
from .const import DEFAULT_PRIORITY, ALL_ENABLED
from .exceptions import EmptyCommand
from .utils import get_alias, format_raw_script
from .output_readers import get_output
class Command(object):
"""Command t... |
21,692 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/types.py | 129,131 | 85,201 | from_path | Rule | 137,155 | 131,155 | class Rule(object):
"""Rule for fixing commands."""
def __init__(self, name, match, get_new_command,
enabled_by_default, side_effect,
priority, requires_output):
"""Initializes rule with given fields.
:type name: basestring
:type match: (Command) -> bo... | class Rule(object):
"""Rule for fixing commands."""
def __init__(self, name, match, get_new_command,
enabled_by_default, side_effect,
priority, requires_output):
"""Initializes rule with given fields.
:type name: basestring
:type match: (Command) -> bo... | name = path.name[:-3]
if name in settings.exclude_rules:
logs.debug(u'Ignoring excluded rule: {}'.format(name))
return
with logs.debug_time(u'Importing rule: {};'.format(name)):
try:
rule_module = load_source(name, str(path))
except... | """Creates rule instance from path.
:type path: pathlib.Path
:rtype: Rule
"""
name = path.name[:-3]
if name in settings.exclude_rules:
logs.debug(u'Ignoring excluded rule: {}'.format(name))
return
with logs.debug_time(u'Importing rule: {}... | 50 | 895 | 250 | 1,145 | import os
import sys
from . import logs
from .shells import shell
from .conf import settings, load_source
from .const import DEFAULT_PRIORITY, ALL_ENABLED
from .exceptions import EmptyCommand
from .utils import get_alias, format_raw_script
from .output_readers import get_output
class Command(object):
"""Command t... | import os
import sys
from . import logs
from .shells import shell
from .conf import settings, load_source
from .const import DEFAULT_PRIORITY, ALL_ENABLED
from .exceptions import EmptyCommand
from .utils import get_alias, format_raw_script
from .output_readers import get_output
class Command(object):
"""Command t... |
21,693 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/ui.py | 59,60 | 1,96 | select_command | 70,96 | 60,96 | # -*- encoding: utf-8 -*-
import sys
from .conf import settings
from .exceptions import NoRuleMatched
from .system import get_key
from .utils import get_alias
from . import logs, const
def read_actions():
"""Yields actions for pressed keys."""
while True:
key = get_key()
# Handle arrows, j/k... | # -*- encoding: utf-8 -*-
import sys
from .conf import settings
from .exceptions import NoRuleMatched
from .system import get_key
from .utils import get_alias
from . import logs, const
def read_actions():
"""Yields actions for pressed keys."""
while True:
key = get_key()
# Handle arrows, j/k... | try:
selector = CommandSelector(corrected_commands)
except NoRuleMatched:
logs.failed('No fucks given' if get_alias() == 'fuck'
else 'Nothing found')
return
if not settings.require_confirmation:
logs.show_corrected_command(selector.value)
return s... | """Returns:
- the first command when confirmation disabled;
- None when ctrl+c pressed;
- selected command.
:type corrected_commands: Iterable[thefuck.types.CorrectedCommand]
:rtype: thefuck.types.CorrectedCommand | None
"""
try:
selector = CommandSelector(corrected_command... | 53 | 615 | 263 | 878 | # -*- encoding: utf-8 -*-
import sys
from .conf import settings
from .exceptions import NoRuleMatched
from .system import get_key
from .utils import get_alias
from . import logs, const
def read_actions():
"""Yields actions for pressed keys."""
while True:
key = get_key()
# Handle arrows, j/k... | # -*- encoding: utf-8 -*-
import sys
from .conf import settings
from .exceptions import NoRuleMatched
from .system import get_key
from .utils import get_alias
from . import logs, const
def read_actions():
"""Yields actions for pressed keys."""
while True:
key = get_key()
# Handle arrows, j/k... | |
21,694 | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck | /home/hieuvd/dung_repo/raw/stars_01/nvbn_thefuck/thefuck/thefuck/ui.py | 45,46 | 27,59 | next | CommandSelector | 46,49 | 46,49 | class CommandSelector(object):
"""Helper for selecting rule from rules list."""
def __init__(self, commands):
""":type commands: Iterable[thefuck.types.CorrectedCommand]"""
self._commands_gen = commands
try:
self._commands = [next(self._commands_gen)]
except StopIter... | class CommandSelector(object):
"""Helper for selecting rule from rules list."""
def __init__(self, commands):
""":type commands: Iterable[thefuck.types.CorrectedCommand]"""
self._commands_gen = commands
try:
self._commands = [next(self._commands_gen)]
except StopIter... | self._realise()
self._index = (self._index + 1) % len(self._commands)
| self._realise()
self._index = (self._index + 1) % len(self._commands)
| 8 | 251 | 32 | 283 | # -*- encoding: utf-8 -*-
import sys
from .conf import settings
from .exceptions import NoRuleMatched
from .system import get_key
from .utils import get_alias
from . import logs, const
def read_actions():
"""Yields actions for pressed keys."""
while True:
key = get_key()
# Handle arrows, j/k... | # -*- encoding: utf-8 -*-
import sys
from .conf import settings
from .exceptions import NoRuleMatched
from .system import get_key
from .utils import get_alias
from . import logs, const
def read_actions():
"""Yields actions for pressed keys."""
while True:
key = get_key()
# Handle arrows, j/k... |
22,809 | /home/hieuvd/dung_repo/raw/stars_01/openai_DALL-E/DALL-E | /home/hieuvd/dung_repo/raw/stars_01/openai_DALL-E/DALL-E/setup.py | 3,4 | 1,17 | parse_requirements | 4,7 | 4,7 | from setuptools import setup
def parse_requirements(filename):
FILL_FUNC_BODYsetup(name='DALL-E',
version='0.1',
description='PyTorch package for the discrete VAE used for DALL·E.',
url='http://github.com/openai/DALL-E',
author='Aditya Ramesh',
author_email='aramesh@openai.com',... | from setuptools import setup
def parse_requirements(filename):
FILL_FUNC_BODYsetup(name='DALL-E',
version='0.1',
description='PyTorch package for the discrete VAE used for DALL·E.',
url='http://github.com/openai/DALL-E',
author='Aditya Ramesh',
author_email='aramesh@openai.com',... | lines = (line.strip() for line in open(filename))
return [line for line in lines if line and not line.startswith("#")]
| lines = (line.strip() for line in open(filename))
return [line for line in lines if line and not line.startswith("#")]
| 18 | 158 | 39 | 197 | from setuptools import setup
def parse_requirements(filename):
FILL_FUNC_BODYsetup(name='DALL-E',
version='0.1',
description='PyTorch package for the discrete VAE used for DALL·E.',
url='http://github.com/openai/DALL-E',
author='Aditya Ramesh',
author_email='aramesh@openai.com',... | from setuptools import setup
def parse_requirements(filename):
FILL_FUNC_BODYsetup(name='DALL-E',
version='0.1',
description='PyTorch package for the discrete VAE used for DALL·E.',
url='http://github.com/openai/DALL-E',
author='Aditya Ramesh',
author_email='aramesh@openai.com',... | |
22,932 | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper/setup.py | 9,10 | 1,43 | read_version | 10,14 | 10,14 | import platform
import sys
from pathlib import Path
import pkg_resources
from setuptools import find_packages, setup
def read_version(fname="whisper/version.py"):
FILL_FUNC_BODYrequirements = []
if sys.platform.startswith("linux") and platform.machine() == "x86_64":
requirements.append("triton>=2.0.0,<3")
setup... | import platform
import sys
from pathlib import Path
import pkg_resources
from setuptools import find_packages, setup
def read_version(fname="whisper/version.py"):
FILL_FUNC_BODYrequirements = []
if sys.platform.startswith("linux") and platform.machine() == "x86_64":
requirements.append("triton>=2.0.0,<3")
setup... | exec(compile(open(fname, encoding="utf-8").read(), fname, "exec"))
return locals()["__version__"]
| exec(compile(open(fname, encoding="utf-8").read(), fname, "exec"))
return locals()["__version__"]
| 6 | 408 | 42 | 450 | import platform
import sys
from pathlib import Path
import pkg_resources
from setuptools import find_packages, setup
def read_version(fname="whisper/version.py"):
FILL_FUNC_BODYrequirements = []
if sys.platform.startswith("linux") and platform.machine() == "x86_64":
requirements.append("triton>=2.0.0,<3")
setup... | import platform
import sys
from pathlib import Path
import pkg_resources
from setuptools import find_packages, setup
def read_version(fname="whisper/version.py"):
FILL_FUNC_BODYrequirements = []
if sys.platform.startswith("linux") and platform.machine() == "x86_64":
requirements.append("triton>=2.0.0,<3")
setup... | |
22,933 | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper/whisper/audio.py | 25,26 | 1,158 | load_audio | 41,65 | 26,65 | import os
from functools import lru_cache
from subprocess import CalledProcessError, run
from typing import Optional, Union
import numpy as np
import torch
import torch.nn.functional as F
from .utils import exact_div
# hard-coded audio hyperparameters
SAMPLE_RATE = 16000
N_FFT = 400
HOP_LENGTH = 160
CHUNK_LENGTH = 3... | import os
from functools import lru_cache
from subprocess import CalledProcessError, run
from typing import Optional, Union
import numpy as np
import torch
import torch.nn.functional as F
from .utils import exact_div
# hard-coded audio hyperparameters
SAMPLE_RATE = 16000
N_FFT = 400
HOP_LENGTH = 160
CHUNK_LENGTH = 3... |
# This launches a subprocess to decode audio while down-mixing
# and resampling as necessary. Requires the ffmpeg CLI in PATH.
# fmt: off
cmd = [
"ffmpeg",
"-nostdin",
"-threads", "0",
"-i", file,
"-f", "s16le",
"-ac", "1",
"-acodec", "pcm_s16le"... | """
Open an audio file and read as mono waveform, resampling as necessary
Parameters
----------
file: str
The audio file to open
sr: int
The sample rate to resample the audio if necessary
Returns
-------
A NumPy array containing the audio waveform, in float32 dtype... | 69 | 1,574 | 262 | 1,836 | import os
from functools import lru_cache
from subprocess import CalledProcessError, run
from typing import Optional, Union
import numpy as np
import torch
import torch.nn.functional as F
from .utils import exact_div
# hard-coded audio hyperparameters
SAMPLE_RATE = 16000
N_FFT = 400
HOP_LENGTH = 160
CHUNK_LENGTH = 3... | import os
from functools import lru_cache
from subprocess import CalledProcessError, run
from typing import Optional, Union
import numpy as np
import torch
import torch.nn.functional as F
from .utils import exact_div
# hard-coded audio hyperparameters
SAMPLE_RATE = 16000
N_FFT = 400
HOP_LENGTH = 160
CHUNK_LENGTH = 3... | |
22,934 | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper/whisper/normalizers/basic.py | 27,28 | 1,77 | remove_symbols_and_diacritics | 32,46 | 28,46 | import re
import unicodedata
import regex
# non-ASCII letters that are not separated by "NFKD" normalization
ADDITIONAL_DIACRITICS = {
"œ": "oe",
"Œ": "OE",
"ø": "o",
"Ø": "O",
"æ": "ae",
"Æ": "AE",
"ß": "ss",
"ẞ": "SS",
"đ": "d",
"Đ": "D",
"ð": "d",
"Ð": "D",
"þ": ... | import re
import unicodedata
import regex
# non-ASCII letters that are not separated by "NFKD" normalization
ADDITIONAL_DIACRITICS = {
"œ": "oe",
"Œ": "OE",
"ø": "o",
"Ø": "O",
"æ": "ae",
"Æ": "AE",
"ß": "ss",
"ẞ": "SS",
"đ": "d",
"Đ": "D",
"ð": "d",
"Ð": "D",
"þ": ... | return "".join(
c
if c in keep
else ADDITIONAL_DIACRITICS[c]
if c in ADDITIONAL_DIACRITICS
else ""
if unicodedata.category(c) == "Mn"
else " "
if unicodedata.category(c)[0] in "MSP"
else c
for c in unicodedata.normalize("NFKD", s)
)... | """
Replace any other markers, symbols, and punctuations with a space,
and drop any diacritics (category 'Mn' and some manual mappings)
"""
return "".join(
c
if c in keep
else ADDITIONAL_DIACRITICS[c]
if c in ADDITIONAL_DIACRITICS
else ""
if unicodedat... | 34 | 616 | 132 | 748 | import re
import unicodedata
import regex
# non-ASCII letters that are not separated by "NFKD" normalization
ADDITIONAL_DIACRITICS = {
"œ": "oe",
"Œ": "OE",
"ø": "o",
"Ø": "O",
"æ": "ae",
"Æ": "AE",
"ß": "ss",
"ẞ": "SS",
"đ": "d",
"Đ": "D",
"ð": "d",
"Ð": "D",
"þ": ... | import re
import unicodedata
import regex
# non-ASCII letters that are not separated by "NFKD" normalization
ADDITIONAL_DIACRITICS = {
"œ": "oe",
"Œ": "OE",
"ø": "o",
"Ø": "O",
"æ": "ae",
"Æ": "AE",
"ß": "ss",
"ẞ": "SS",
"đ": "d",
"Đ": "D",
"ð": "d",
"Ð": "D",
"þ": ... | |
22,936 | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper/whisper/utils.py | 103,106 | 85,109 | write_result | ResultWriter | 106,109 | 106,109 | class ResultWriter:
extension: str
def __init__(self, output_dir: str):
self.output_dir = output_dir
def __call__(
self, result: dict, audio_path: str, options: Optional[dict] = None, **kwargs
):
audio_basename = os.path.basename(audio_path)
audio_basename = os.path.spl... | class ResultWriter:
extension: str
def __init__(self, output_dir: str):
self.output_dir = output_dir
def __call__(
self, result: dict, audio_path: str, options: Optional[dict] = None, **kwargs
):
audio_basename = os.path.basename(audio_path)
audio_basename = os.path.spl... | raise NotImplementedError
| raise NotImplementedError
| 2 | 236 | 13 | 249 | import json
import os
import re
import sys
import zlib
from typing import Callable, List, Optional, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# a... | import json
import os
import re
import sys
import zlib
from typing import Callable, List, Optional, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# a... |
22,937 | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper/whisper/utils.py | 142,143 | 119,236 | iterate_subtitles | SubtitlesWriter | 143,196 | 143,196 | class SubtitlesWriter(ResultWriter):
always_include_hours: bool
decimal_marker: str
def iterate_result(
self,
result: dict,
options: Optional[dict] = None,
*,
max_line_width: Optional[int] = None,
max_line_count: Optional[int] = None,
highlight_words:... | class SubtitlesWriter(ResultWriter):
always_include_hours: bool
decimal_marker: str
def iterate_result(
self,
result: dict,
options: Optional[dict] = None,
*,
max_line_width: Optional[int] = None,
max_line_count: Optional[int] = None,
highlight_words:... | line_len = 0
line_count = 1
# the next subtitle to yield (a list of word timings with whitespace)
subtitle: List[dict] = []
last: float = get_start(result["segments"]) or 0.0
for segment in result["segments"]:
chunk_index = 0
... | line_len = 0
line_count = 1
# the next subtitle to yield (a list of word timings with whitespace)
subtitle: List[dict] = []
last: float = get_start(result["segments"]) or 0.0
for segment in result["segments"]:
chunk_index = 0
... | 189 | 769 | 593 | 1,362 | import json
import os
import re
import sys
import zlib
from typing import Callable, List, Optional, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# a... | import json
import os
import re
import sys
import zlib
from typing import Callable, List, Optional, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# a... |
22,938 | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper/whisper/utils.py | 288,291 | 285,294 | write_result | WriteJSON | 291,294 | 291,294 | class WriteJSON(ResultWriter):
extension: str = "json"
def write_result(
self, result: dict, file: TextIO, options: Optional[dict] = None, **kwargs
):
FILL_FUNC_BODY | class WriteJSON(ResultWriter):
extension: str = "json"
def write_result(
self, result: dict, file: TextIO, options: Optional[dict] = None, **kwargs
):
FILL_FUNC_BODY | json.dump(result, file)
| json.dump(result, file)
| 2 | 63 | 15 | 78 | import json
import os
import re
import sys
import zlib
from typing import Callable, List, Optional, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# a... | import json
import os
import re
import sys
import zlib
from typing import Callable, List, Optional, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# a... |
22,939 | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper/whisper/utils.py | 254,257 | 249,263 | write_result | WriteSRT | 257,263 | 257,263 | class WriteSRT(SubtitlesWriter):
extension: str = "srt"
always_include_hours: bool = True
decimal_marker: str = ","
def write_result(
self, result: dict, file: TextIO, options: Optional[dict] = None, **kwargs
):
FILL_FUNC_BODY | class WriteSRT(SubtitlesWriter):
extension: str = "srt"
always_include_hours: bool = True
decimal_marker: str = ","
def write_result(
self, result: dict, file: TextIO, options: Optional[dict] = None, **kwargs
):
FILL_FUNC_BODY | for i, (start, end, text) in enumerate(
self.iterate_result(result, options, **kwargs), start=1
):
print(f"{i}\n{start} --> {end}\n{text}\n", file=file, flush=True)
| for i, (start, end, text) in enumerate(
self.iterate_result(result, options, **kwargs), start=1
):
print(f"{i}\n{start} --> {end}\n{text}\n", file=file, flush=True)
| 17 | 89 | 79 | 168 | import json
import os
import re
import sys
import zlib
from typing import Callable, List, Optional, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# a... | import json
import os
import re
import sys
import zlib
from typing import Callable, List, Optional, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# a... |
22,940 | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper/whisper/utils.py | 275,278 | 263,285 | write_result | WriteTSV | 278,285 | 278,285 | class WriteTSV(ResultWriter):
"""
Write a transcript to a file in TSV (tab-separated values) format containing lines like:
<start time in integer milliseconds>\t<end time in integer milliseconds>\t<transcript text>
Using integer milliseconds as start and end times means there's no chance of interferenc... | class WriteTSV(ResultWriter):
"""
Write a transcript to a file in TSV (tab-separated values) format containing lines like:
<start time in integer milliseconds>\t<end time in integer milliseconds>\t<transcript text>
Using integer milliseconds as start and end times means there's no chance of interferenc... | print("start", "end", "text", sep="\t", file=file)
for segment in result["segments"]:
print(round(1000 * segment["start"]), file=file, end="\t")
print(round(1000 * segment["end"]), file=file, end="\t")
print(segment["text"].strip().replace("\t", " "), file=file, flush... | print("start", "end", "text", sep="\t", file=file)
for segment in result["segments"]:
print(round(1000 * segment["start"]), file=file, end="\t")
print(round(1000 * segment["end"]), file=file, end="\t")
print(segment["text"].strip().replace("\t", " "), file=file, flush... | 24 | 190 | 120 | 310 | import json
import os
import re
import sys
import zlib
from typing import Callable, List, Optional, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# a... | import json
import os
import re
import sys
import zlib
from typing import Callable, List, Optional, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# a... |
22,941 | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper/whisper/utils.py | 112,115 | 109,119 | write_result | WriteTXT | 115,119 | 115,119 | class WriteTXT(ResultWriter):
extension: str = "txt"
def write_result(
self, result: dict, file: TextIO, options: Optional[dict] = None, **kwargs
):
FILL_FUNC_BODY | class WriteTXT(ResultWriter):
extension: str = "txt"
def write_result(
self, result: dict, file: TextIO, options: Optional[dict] = None, **kwargs
):
FILL_FUNC_BODY | for segment in result["segments"]:
print(segment["text"].strip(), file=file, flush=True)
| for segment in result["segments"]:
print(segment["text"].strip(), file=file, flush=True)
| 7 | 64 | 36 | 100 | import json
import os
import re
import sys
import zlib
from typing import Callable, List, Optional, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# a... | import json
import os
import re
import sys
import zlib
from typing import Callable, List, Optional, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# a... |
22,942 | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper | /home/hieuvd/dung_repo/raw/stars_01/openai_whisper/whisper/whisper/utils.py | 241,244 | 236,249 | write_result | WriteVTT | 244,249 | 244,249 | class WriteVTT(SubtitlesWriter):
extension: str = "vtt"
always_include_hours: bool = False
decimal_marker: str = "."
def write_result(
self, result: dict, file: TextIO, options: Optional[dict] = None, **kwargs
):
FILL_FUNC_BODY | class WriteVTT(SubtitlesWriter):
extension: str = "vtt"
always_include_hours: bool = False
decimal_marker: str = "."
def write_result(
self, result: dict, file: TextIO, options: Optional[dict] = None, **kwargs
):
FILL_FUNC_BODY | print("WEBVTT\n", file=file)
for start, end, text in self.iterate_result(result, options, **kwargs):
print(f"{start} --> {end}\n{text}\n", file=file, flush=True)
| print("WEBVTT\n", file=file)
for start, end, text in self.iterate_result(result, options, **kwargs):
print(f"{start} --> {end}\n{text}\n", file=file, flush=True)
| 15 | 89 | 73 | 162 | import json
import os
import re
import sys
import zlib
from typing import Callable, List, Optional, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# a... | import json
import os
import re
import sys
import zlib
from typing import Callable, List, Optional, TextIO
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# a... |
23,019 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/base.py | 126,127 | 1,138 | default | 127,138 | 127,138 | import datetime
import uuid
import simplejson as json
from jinja2 import Environment
from ..commons import utils
from ..globals import CurrentConfig, RenderType, ThemeType
from ..options import InitOpts, RenderOpts
from ..options.global_options import AnimationOpts
from ..options.series_options import BasicOpts
from ... | import datetime
import uuid
import simplejson as json
from jinja2 import Environment
from ..commons import utils
from ..globals import CurrentConfig, RenderType, ThemeType
from ..options import InitOpts, RenderOpts
from ..options.global_options import AnimationOpts
from ..options.series_options import BasicOpts
from ... | if isinstance(o, (datetime.date, datetime.datetime)):
return o.isoformat()
if isinstance(o, utils.JsCode):
return (
o.replace("\\n|\\t", "").replace(r"\\n", "\n").replace(r"\\t", "\t").js_code
)
if isinstance(o, BasicOpts):
if isinstance(o.opts, Sequence):
... | if isinstance(o, (datetime.date, datetime.datetime)):
return o.isoformat()
if isinstance(o, utils.JsCode):
return (
o.replace("\\n|\\t", "").replace(r"\\n", "\n").replace(r"\\t", "\t").js_code
)
if isinstance(o, BasicOpts):
if isinstance(o.opts, Sequence):
... | 31 | 1,355 | 170 | 1,525 | import datetime
import uuid
import simplejson as json
from jinja2 import Environment
from ..commons import utils
from ..globals import CurrentConfig, RenderType, ThemeType
from ..options import InitOpts, RenderOpts
from ..options.global_options import AnimationOpts
from ..options.series_options import BasicOpts
from ... | import datetime
import uuid
import simplejson as json
from jinja2 import Environment
from ..commons import utils
from ..globals import CurrentConfig, RenderType, ThemeType
from ..options import InitOpts, RenderOpts
from ..options.global_options import AnimationOpts
from ..options.series_options import BasicOpts
from ... | |
23,020 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/base.py | 115,116 | 17,126 | _prepare_render | Base | 116,126 | 116,126 | class Base(ChartMixin):
"""
`Base` is the root class for all graphical class, it provides
part of the initialization parameters and common methods
"""
def __init__(
self,
init_opts: Union[InitOpts, dict] = InitOpts(),
render_opts: Union[RenderOpts, dict] = RenderOpts(),
... | class Base(ChartMixin):
"""
`Base` is the root class for all graphical class, it provides
part of the initialization parameters and common methods
"""
def __init__(
self,
init_opts: Union[InitOpts, dict] = InitOpts(),
render_opts: Union[RenderOpts, dict] = RenderOpts(),
... | self.json_contents = self.dump_options()
self._use_theme()
self._render_cache.clear()
if self.render_options.get("embed_js"):
self._render_cache[
"javascript"
] = self.load_javascript().load_javascript_contents()
| self.json_contents = self.dump_options()
self._use_theme()
self._render_cache.clear()
if self.render_options.get("embed_js"):
self._render_cache[
"javascript"
] = self.load_javascript().load_javascript_contents()
| 12 | 1,157 | 90 | 1,247 | import datetime
import uuid
import simplejson as json
from jinja2 import Environment
from ..commons import utils
from ..globals import CurrentConfig, RenderType, ThemeType
from ..options import InitOpts, RenderOpts
from ..options.global_options import AnimationOpts
from ..options.series_options import BasicOpts
from ... | import datetime
import uuid
import simplejson as json
from jinja2 import Environment
from ..commons import utils
from ..globals import CurrentConfig, RenderType, ThemeType
from ..options import InitOpts, RenderOpts
from ..options.global_options import AnimationOpts
from ..options.series_options import BasicOpts
from ... |
23,021 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/bar.py | 15,53 | 7,98 | add_yaxis | Bar | 53,98 | 53,98 | class Bar(RectChart):
"""
<<< Bar Chart >>>
Bar chart presents categorical data with rectangular bars
with heights or lengths proportional to the values that they represent.
"""
def add_yaxis(
self,
series_name: str,
y_axis: types.Sequence[types.Union[types.Numeric, opt... | class Bar(RectChart):
"""
<<< Bar Chart >>>
Bar chart presents categorical data with rectangular bars
with heights or lengths proportional to the values that they represent.
"""
def add_yaxis(
self,
series_name: str,
y_axis: types.Sequence[types.Union[types.Numeric, opt... | self._append_color(color)
self._append_legend(series_name)
if self.options.get("dataset") is not None:
y_axis = None
self.options.get("series").append(
{
"type": ChartType.BAR,
"name": series_name,
"xAxisIndex": xa... | self._append_color(color)
self._append_legend(series_name)
if self.options.get("dataset") is not None:
y_axis = None
self.options.get("series").append(
{
"type": ChartType.BAR,
"name": series_name,
"xAxisIndex": xa... | 84 | 620 | 476 | 1,096 | from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class Bar(RectChart):
"""
<<< Bar Chart >>>
Bar chart presents categorical data with rectangular bars
with heights or lengths proportional to the values that they represent.
... | from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class Bar(RectChart):
"""
<<< Bar Chart >>>
Bar chart presents categorical data with rectangular bars
with heights or lengths proportional to the values that they represent.
... |
23,022 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/bmap.py | 32,33 | 12,93 | _feed_data | BMap | 33,47 | 33,47 | class BMap(GeoChartBase):
"""
<<< Baidu coordinate system >>>
Support scatter plot, line
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
is_ignore_nonexistent_coord: bool = False,
render_opts: types.RenderInit = opts.RenderOpts(),
):
sup... | class BMap(GeoChartBase):
"""
<<< Baidu coordinate system >>>
Support scatter plot, line
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
is_ignore_nonexistent_coord: bool = False,
render_opts: types.RenderInit = opts.RenderOpts(),
):
sup... | result = []
type_list = [ChartType.LINES, ChartType.CUSTOM]
if type_ in type_list:
result = data_pair
else:
for n, v in data_pair:
try:
lng, lat = self.get_coordinate(n)
result.append({"name": n, "value": [ln... | result = []
type_list = [ChartType.LINES, ChartType.CUSTOM]
if type_ in type_list:
result = data_pair
else:
for n, v in data_pair:
try:
lng, lat = self.get_coordinate(n)
result.append({"name": n, "value": [ln... | 46 | 685 | 163 | 848 | from ... import options as opts
from ... import types
from ...charts.basic_charts.geo import GeoChartBase
from ...commons.utils import OrderedSet
from ...exceptions import NonexistentCoordinatesException
from ...globals import ChartType
BAIDU_MAP_API = "https://api.map.baidu.com/api?v=2.0&ak={}"
BAIDU_MAP_GETSCRIPT = ... | from ... import options as opts
from ... import types
from ...charts.basic_charts.geo import GeoChartBase
from ...commons.utils import OrderedSet
from ...exceptions import NonexistentCoordinatesException
from ...globals import ChartType
BAIDU_MAP_API = "https://api.map.baidu.com/api?v=2.0&ak={}"
BAIDU_MAP_GETSCRIPT = ... |
23,023 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/boxplot.py | 60,62 | 7,85 | prepare_data | Boxplot | 62,85 | 62,85 | class Boxplot(RectChart):
"""
<<< Boxplot >>>
A box-plot is a statistical chart used to show a set of data dispersion data.
It displays the maximum, minimum, median, lower quartile, and upper quartile
of a set of data.
"""
def add_yaxis(
self,
series_name: str,
y_ax... | class Boxplot(RectChart):
"""
<<< Boxplot >>>
A box-plot is a statistical chart used to show a set of data dispersion data.
It displays the maximum, minimum, median, lower quartile, and upper quartile
of a set of data.
"""
def add_yaxis(
self,
series_name: str,
y_ax... | data = []
for item in items:
if not item:
data.append([])
try:
d, res = sorted(item), []
for i in range(1, 4):
n = i * (len(d) + 1) / 4
k = int(n)
m = n - k
... | data = []
for item in items:
if not item:
data.append([])
try:
d, res = sorted(item), []
for i in range(1, 4):
n = i * (len(d) + 1) / 4
k = int(n)
m = n - k
... | 109 | 567 | 298 | 865 | from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class Boxplot(RectChart):
"""
<<< Boxplot >>>
A box-plot is a statistical chart used to show a set of data dispersion data.
It displays the maximum, minimum, median, lower quar... | from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class Boxplot(RectChart):
"""
<<< Boxplot >>>
A box-plot is a statistical chart used to show a set of data dispersion data.
It displays the maximum, minimum, median, lower quar... |
23,024 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/calendar.py | 24,39 | 7,60 | add | Calendar | 39,60 | 39,60 | class Calendar(Chart):
"""
<<< Calendar Diagram >>>
The calendar diagram is mainly used to represent the size of a value by
color and must be used in conjunction with the visualMap component.
Two categories of axes must be used in rectangular coordinates.
"""
def __init__(
self,
... | class Calendar(Chart):
"""
<<< Calendar Diagram >>>
The calendar diagram is mainly used to represent the size of a value by
color and must be used in conjunction with the visualMap component.
Two categories of axes must be used in rectangular coordinates.
"""
def __init__(
self,
... | if calendar_opts:
self.options.update(calendar=calendar_opts)
if visualmap_opts:
self.options.update(visualMap=visualmap_opts)
self._append_legend(series_name)
self.options.get("series").append(
{
"type": type_,
"coordi... | if calendar_opts:
self.options.update(calendar=calendar_opts)
if visualmap_opts:
self.options.update(visualMap=visualmap_opts)
self._append_legend(series_name)
self.options.get("series").append(
{
"type": type_,
"coordi... | 32 | 361 | 203 | 564 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Calendar(Chart):
"""
<<< Calendar Diagram >>>
The calendar diagram is mainly used to represent the size of a value by
color and must be used in conjunction with the visualMap... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Calendar(Chart):
"""
<<< Calendar Diagram >>>
The calendar diagram is mainly used to represent the size of a value by
color and must be used in conjunction with the visualMap... |
23,025 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/custom.py | 15,41 | 7,71 | add | Custom | 41,71 | 41,71 | class Custom(Chart):
"""
<<< Custom >>>
Custom series allows you to customize the rendering of graphical elements
in the series. This enables the extension of different charts.
"""
def add(
self,
series_name: str,
render_item: types.JSFunc,
*,
color_by: ... | class Custom(Chart):
"""
<<< Custom >>>
Custom series allows you to customize the rendering of graphical elements
in the series. This enables the extension of different charts.
"""
def add(
self,
series_name: str,
render_item: types.JSFunc,
*,
color_by: ... | self._append_legend(series_name)
self.options.get("series").append(
{
"type": ChartType.CUSTOM,
"name": series_name,
"renderItem": render_item,
"colorBy": color_by,
"legendHoverLink": is_legend_hover_link,
... | self._append_legend(series_name)
self.options.get("series").append(
{
"type": ChartType.CUSTOM,
"name": series_name,
"renderItem": render_item,
"colorBy": color_by,
"legendHoverLink": is_legend_hover_link,
... | 53 | 376 | 310 | 686 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Custom(Chart):
"""
<<< Custom >>>
Custom series allows you to customize the rendering of graphical elements
in the series. This enables the extension of different charts.
... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Custom(Chart):
"""
<<< Custom >>>
Custom series allows you to customize the rendering of graphical elements
in the series. This enables the extension of different charts.
... |
23,026 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/effectscatter.py | 14,32 | 7,60 | add_yaxis | EffectScatter | 32,60 | 32,60 | class EffectScatter(RectChart):
"""
<<< Scatter plots with ripple effects animation >>>
Use animation effects to visually highlight designated data set.
"""
def add_yaxis(
self,
series_name: str,
y_axis: types.Sequence[types.Union[opts.EffectScatterItem, dict]],
*,
... | class EffectScatter(RectChart):
"""
<<< Scatter plots with ripple effects animation >>>
Use animation effects to visually highlight designated data set.
"""
def add_yaxis(
self,
series_name: str,
y_axis: types.Sequence[types.Union[opts.EffectScatterItem, dict]],
*,
... | self._append_color(color)
self._append_legend(series_name)
if all([isinstance(d, opts.EffectScatterItem) for d in y_axis]):
y_axis = y_axis
else:
y_axis = [list(z) for z in zip(self._xaxis_data, y_axis)]
self.options.get("series").append(
{
... | self._append_color(color)
self._append_legend(series_name)
if all([isinstance(d, opts.EffectScatterItem) for d in y_axis]):
y_axis = y_axis
else:
y_axis = [list(z) for z in zip(self._xaxis_data, y_axis)]
self.options.get("series").append(
{
... | 57 | 298 | 299 | 597 | from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class EffectScatter(RectChart):
"""
<<< Scatter plots with ripple effects animation >>>
Use animation effects to visually highlight designated data set.
"""
def add_yaxis(... | from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class EffectScatter(RectChart):
"""
<<< Scatter plots with ripple effects animation >>>
Use animation effects to visually highlight designated data set.
"""
def add_yaxis(... |
23,027 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/funnel.py | 18,31 | 7,58 | add | Funnel | 31,58 | 31,58 | class Funnel(Chart):
"""
<<< Funnel >>>
Funnel diagram is suitable for one-way analysis of single process
with standardized business process, long cycle and multiple links.
Through comparison of business data of each link in the funnel,
the link where the potential problems can be found intuiti... | class Funnel(Chart):
"""
<<< Funnel >>>
Funnel diagram is suitable for one-way analysis of single process
with standardized business process, long cycle and multiple links.
Through comparison of business data of each link in the funnel,
the link where the potential problems can be found intuiti... | self._append_color(color)
if all([isinstance(d, opts.FunnelItem) for d in data_pair]):
data = data_pair
for a in data_pair:
self._append_legend(a.opts.get("name"))
else:
data = [{"name": n, "value": v} for n, v in data_pair]
for a, ... | self._append_color(color)
if all([isinstance(d, opts.FunnelItem) for d in data_pair]):
data = data_pair
for a in data_pair:
self._append_legend(a.opts.get("name"))
else:
data = [{"name": n, "value": v} for n, v in data_pair]
for a, ... | 62 | 229 | 302 | 531 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Funnel(Chart):
"""
<<< Funnel >>>
Funnel diagram is suitable for one-way analysis of single process
with standardized business process, long cycle and multiple links.
Thr... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Funnel(Chart):
"""
<<< Funnel >>>
Funnel diagram is suitable for one-way analysis of single process
with standardized business process, long cycle and multiple links.
Thr... |
23,028 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/gauge.py | 14,44 | 7,75 | add | Gauge | 44,75 | 44,75 | class Gauge(Chart):
"""
<<< Gauge >>>
The gauge displays a single key business measure.
"""
def add(
self,
series_name: str,
data_pair: types.Sequence,
*,
min_: types.Numeric = 0,
max_: types.Numeric = 100,
split_number: types.Numeric = 10,
... | class Gauge(Chart):
"""
<<< Gauge >>>
The gauge displays a single key business measure.
"""
def add(
self,
series_name: str,
data_pair: types.Sequence,
*,
min_: types.Numeric = 0,
max_: types.Numeric = 100,
split_number: types.Numeric = 10,
... | if center is None:
center = ["50%", "50%"]
self._append_legend(series_name)
self.options.get("series").append(
{
"type": ChartType.GAUGE,
"title": title_label_opts,
"detail": detail_label_opts,
"name": serie... | if center is None:
center = ["50%", "50%"]
self._append_legend(series_name)
self.options.get("series").append(
{
"type": ChartType.GAUGE,
"title": title_label_opts,
"detail": detail_label_opts,
"name": serie... | 67 | 422 | 319 | 741 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Gauge(Chart):
"""
<<< Gauge >>>
The gauge displays a single key business measure.
"""
def add(
self,
series_name: str,
data_pair: types.Sequence,... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Gauge(Chart):
"""
<<< Gauge >>>
The gauge displays a single key business measure.
"""
def add(
self,
series_name: str,
data_pair: types.Sequence,... |
23,029 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/graph.py | 14,42 | 7,98 | add | Graph | 42,98 | 42,98 | class Graph(Chart):
"""
<<< Graph >>>
The graph is used to represent the relational data.
"""
def add(
self,
series_name: str,
nodes: types.Sequence[types.GraphNode],
links: types.Sequence[types.GraphLink],
categories: types.Union[types.Sequence[types.GraphC... | class Graph(Chart):
"""
<<< Graph >>>
The graph is used to represent the relational data.
"""
def add(
self,
series_name: str,
nodes: types.Sequence[types.GraphNode],
links: types.Sequence[types.GraphLink],
categories: types.Union[types.Sequence[types.GraphC... | _nodes = []
for n in nodes:
if isinstance(n, opts.GraphNode):
n = n.opts
_nodes.append(n)
_links = []
for link in links:
if isinstance(link, opts.GraphLink):
link = link.opts
_links.append(link)
if ... | _nodes = []
for n in nodes:
if isinstance(n, opts.GraphNode):
n = n.opts
_nodes.append(n)
_links = []
for link in links:
if isinstance(link, opts.GraphLink):
link = link.opts
_links.append(link)
if ... | 117 | 394 | 535 | 929 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Graph(Chart):
"""
<<< Graph >>>
The graph is used to represent the relational data.
"""
def add(
self,
series_name: str,
nodes: types.Sequence[ty... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Graph(Chart):
"""
<<< Graph >>>
The graph is used to represent the relational data.
"""
def add(
self,
series_name: str,
nodes: types.Sequence[ty... |
23,030 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/heatmap.py | 24,39 | 7,57 | add_yaxis | HeatMap | 39,57 | 39,57 | class HeatMap(RectChart):
"""
<<< HeatMap >>>
The heat map is mainly used to represent the size of the value by color,
which must be used in conjunction with the visualMap component.
Two categories of axes must be used in rectangular coordinates.
"""
def __init__(
self,
ini... | class HeatMap(RectChart):
"""
<<< HeatMap >>>
The heat map is mainly used to represent the size of the value by color,
which must be used in conjunction with the visualMap component.
Two categories of axes must be used in rectangular coordinates.
"""
def __init__(
self,
ini... | self._append_legend(series_name)
self.options.get("yAxis")[0].update(data=yaxis_data)
self.options.get("series").append(
{
"type": ChartType.HEATMAP,
"name": series_name,
"xAxisIndex": xaxis_index,
"yAxisIndex": yaxis_in... | self._append_legend(series_name)
self.options.get("yAxis")[0].update(data=yaxis_data)
self.options.get("series").append(
{
"type": ChartType.HEATMAP,
"name": series_name,
"xAxisIndex": xaxis_index,
"yAxisIndex": yaxis_in... | 30 | 365 | 194 | 559 | from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class HeatMap(RectChart):
"""
<<< HeatMap >>>
The heat map is mainly used to represent the size of the value by color,
which must be used in conjunction with the visualMap comp... | from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class HeatMap(RectChart):
"""
<<< HeatMap >>>
The heat map is mainly used to represent the size of the value by color,
which must be used in conjunction with the visualMap comp... |
23,031 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/kline.py | 28,44 | 7,63 | add_yaxis | Kline | 44,63 | 44,63 | class Kline(RectChart):
"""
<<< K-line >>>
K-line shows the highest value, the lowest value,
the starting value and the ending value of the data on the day,
which is used to show the daily fluctuation of the data or
the fluctuation of a certain period.
"""
def __init__(
self,
... | class Kline(RectChart):
"""
<<< K-line >>>
K-line shows the highest value, the lowest value,
the starting value and the ending value of the data on the day,
which is used to show the daily fluctuation of the data or
the fluctuation of a certain period.
"""
def __init__(
self,
... | self._append_legend(series_name)
self.options.get("series").append(
{
"type": ChartType.KLINE,
"name": series_name,
"colorBy": color_by,
"layout": layout,
"barWidth": bar_width,
"xAxisIndex": xaxi... | self._append_legend(series_name)
self.options.get("series").append(
{
"type": ChartType.KLINE,
"name": series_name,
"colorBy": color_by,
"layout": layout,
"barWidth": bar_width,
"xAxisIndex": xaxi... | 33 | 421 | 191 | 612 | from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class Kline(RectChart):
"""
<<< K-line >>>
K-line shows the highest value, the lowest value,
the starting value and the ending value of the data on the day,
which is used t... | from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class Kline(RectChart):
"""
<<< K-line >>>
K-line shows the highest value, the lowest value,
the starting value and the ending value of the data on the day,
which is used t... |
23,032 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/line.py | 15,48 | 7,102 | add_yaxis | Line | 48,102 | 48,102 | class Line(RectChart):
"""
<<< Line Chart >>>
Line chart is a graph that connects all data points
with single line to show the change trend of data.
"""
def add_yaxis(
self,
series_name: str,
y_axis: types.Sequence[types.Union[opts.LineItem, dict]],
*,
i... | class Line(RectChart):
"""
<<< Line Chart >>>
Line chart is a graph that connects all data points
with single line to show the change trend of data.
"""
def add_yaxis(
self,
series_name: str,
y_axis: types.Sequence[types.Union[opts.LineItem, dict]],
*,
i... | self._append_color(color)
self._append_legend(series_name)
if all([isinstance(d, opts.LineItem) for d in y_axis]):
data = y_axis
else:
# 合并 x 和 y 轴数据,避免当 X 轴的类型设置为 'value' 的时候,
# X、Y 轴均显示 Y 轴数据
try:
xaxis_index = xaxis_inde... | self._append_color(color)
self._append_legend(series_name)
if all([isinstance(d, opts.LineItem) for d in y_axis]):
data = y_axis
else:
# 合并 x 和 y 轴数据,避免当 X 轴的类型设置为 'value' 的时候,
# X、Y 轴均显示 Y 轴数据
try:
xaxis_index = xaxis_inde... | 129 | 504 | 586 | 1,090 | from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class Line(RectChart):
"""
<<< Line Chart >>>
Line chart is a graph that connects all data points
with single line to show the change trend of data.
"""
def add_yaxis(... | from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class Line(RectChart):
"""
<<< Line Chart >>>
Line chart is a graph that connects all data points
with single line to show the change trend of data.
"""
def add_yaxis(... |
23,033 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/liquid.py | 22,38 | 7,66 | add | Liquid | 38,66 | 38,66 | class Liquid(Chart):
"""
<<< Liquid >>>
The liquid chart is mainly used to highlight the percentage of data.
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.RenderInit = opts.RenderOpts(),
):
super().__init__(init_opts=init_op... | class Liquid(Chart):
"""
<<< Liquid >>>
The liquid chart is mainly used to highlight the percentage of data.
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.RenderInit = opts.RenderOpts(),
):
super().__init__(init_opts=init_op... | _animation_dur, _animation_dur_update = 2000, 1000
if not is_animation:
_animation_dur, _animation_dur_update = 0, 0
color = color or ["#294D99", "#156ACF", "#1598ED", "#45BDFF"]
self.options.get("series").append(
{
"type": ChartType.LIQUID,
... | _animation_dur, _animation_dur_update = 2000, 1000
if not is_animation:
_animation_dur, _animation_dur_update = 0, 0
color = color or ["#294D99", "#156ACF", "#1598ED", "#45BDFF"]
self.options.get("series").append(
{
"type": ChartType.LIQUID,
... | 61 | 325 | 310 | 635 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Liquid(Chart):
"""
<<< Liquid >>>
The liquid chart is mainly used to highlight the percentage of data.
"""
def __init__(
self,
init_opts: types.Init = op... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Liquid(Chart):
"""
<<< Liquid >>>
The liquid chart is mainly used to highlight the percentage of data.
"""
def __init__(
self,
init_opts: types.Init = op... |
23,034 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/map.py | 108,109 | 107,111 | add_geo_json | Map | 109,111 | 109,111 | class Map(Chart, MapMixin):
def add_geo_json(self, geo_json: dict):
FILL_FUNC_BODY | class Map(Chart, MapMixin):
def add_geo_json(self, geo_json: dict):
FILL_FUNC_BODY | self._geo_json = geo_json
return self
| self._geo_json = geo_json
return self
| 5 | 38 | 18 | 56 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class MapMixin:
"""
<<< Map >>>
Map are mainly used for visualization of geographic area data.
"""
def add(
self,
series_name: str,
data_pair: types.Se... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class MapMixin:
"""
<<< Map >>>
Map are mainly used for visualization of geographic area data.
"""
def add(
self,
series_name: str,
data_pair: types.Se... |
23,035 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/map.py | 14,50 | 7,107 | add | MapMixin | 50,107 | 50,107 | class MapMixin:
"""
<<< Map >>>
Map are mainly used for visualization of geographic area data.
"""
def add(
self,
series_name: str,
data_pair: types.Sequence[types.Union[types.Sequence, opts.MapItem, dict]],
maptype: str = "china",
*,
is_roam: bool =... | class MapMixin:
"""
<<< Map >>>
Map are mainly used for visualization of geographic area data.
"""
def add(
self,
series_name: str,
data_pair: types.Sequence[types.Union[types.Sequence, opts.MapItem, dict]],
maptype: str = "china",
*,
is_roam: bool =... | self.js_dependencies.add(maptype)
self._geo_json_name = maptype
if isinstance(data_pair[0], opts.MapItem):
data = data_pair
else:
data = [{"name": n, "value": v} for n, v in data_pair]
scale_limit: types.Optional[dict] = {
"min": min_scale_li... | self.js_dependencies.add(maptype)
self._geo_json_name = maptype
if isinstance(data_pair[0], opts.MapItem):
data = data_pair
else:
data = [{"name": n, "value": v} for n, v in data_pair]
scale_limit: types.Optional[dict] = {
"min": min_scale_li... | 116 | 604 | 580 | 1,184 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class MapMixin:
"""
<<< Map >>>
Map are mainly used for visualization of geographic area data.
"""
def add(
self,
series_name: str,
data_pair: types.Se... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class MapMixin:
"""
<<< Map >>>
Map are mainly used for visualization of geographic area data.
"""
def add(
self,
series_name: str,
data_pair: types.Se... |
23,036 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/parallel.py | 41,52 | 7,67 | add | Parallel | 52,67 | 52,67 | class Parallel(Chart):
"""
<<< Parallel >>>
Parallel coordinate systems are commonly used to visualize graphs of
high dimensional data.
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.RenderInit = opts.RenderOpts(),
):
sup... | class Parallel(Chart):
"""
<<< Parallel >>>
Parallel coordinate systems are commonly used to visualize graphs of
high dimensional data.
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.RenderInit = opts.RenderOpts(),
):
sup... | self._append_legend(series_name)
self.options.get("series").append(
{
"type": ChartType.PARALLEL,
"coordinateSystem": "parallel",
"lineStyle": linestyle_opts,
"name": series_name,
"data": data,
"s... | self._append_legend(series_name)
self.options.get("series").append(
{
"type": ChartType.PARALLEL,
"coordinateSystem": "parallel",
"lineStyle": linestyle_opts,
"name": series_name,
"data": data,
"s... | 25 | 430 | 145 | 575 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Parallel(Chart):
"""
<<< Parallel >>>
Parallel coordinate systems are commonly used to visualize graphs of
high dimensional data.
"""
def __init__(
self,
... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Parallel(Chart):
"""
<<< Parallel >>>
Parallel coordinate systems are commonly used to visualize graphs of
high dimensional data.
"""
def __init__(
self,
... |
23,037 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/pictorialbar.py | 15,42 | 7,72 | add_yaxis | PictorialBar | 42,72 | 42,72 | class PictorialBar(RectChart):
"""
<<< PictorialBar Chart >>>
PictorialBar is a histogram that can set various figurative graphic
elements (such as images, SVG PathData, etc.)
"""
def add_yaxis(
self,
series_name: str,
y_axis: types.Sequence[types.Union[types.Numeric, o... | class PictorialBar(RectChart):
"""
<<< PictorialBar Chart >>>
PictorialBar is a histogram that can set various figurative graphic
elements (such as images, SVG PathData, etc.)
"""
def add_yaxis(
self,
series_name: str,
y_axis: types.Sequence[types.Union[types.Numeric, o... | self._append_color(color)
self._append_legend(series_name)
self.options.get("series").append(
{
"type": ChartType.PICTORIALBAR,
"symbol": symbol,
"symbolSize": symbol_size,
"symbolPosition": symbol_pos,
"... | self._append_color(color)
self._append_legend(series_name)
self.options.get("series").append(
{
"type": ChartType.PICTORIALBAR,
"symbol": symbol,
"symbolSize": symbol_size,
"symbolPosition": symbol_pos,
"... | 54 | 477 | 323 | 800 | from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class PictorialBar(RectChart):
"""
<<< PictorialBar Chart >>>
PictorialBar is a histogram that can set various figurative graphic
elements (such as images, SVG PathData, etc.)
... | from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class PictorialBar(RectChart):
"""
<<< PictorialBar Chart >>>
PictorialBar is a histogram that can set various figurative graphic
elements (such as images, SVG PathData, etc.)
... |
23,038 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/pie.py | 16,45 | 7,99 | add | Pie | 45,99 | 45,99 | class Pie(Chart):
"""
<<< Pie >>>
The pie chart is mainly used to represent the proportion of data of
different categories in the total. Each radian represents the ratio of
the number of data points.
"""
def add(
self,
series_name: str,
data_pair: types.Sequence[typ... | class Pie(Chart):
"""
<<< Pie >>>
The pie chart is mainly used to represent the proportion of data of
different categories in the total. Each radian represents the ratio of
the number of data points.
"""
def add(
self,
series_name: str,
data_pair: types.Sequence[typ... | if self.options.get("dataset") is not None:
data = None
self.options.get("legend")[0].update(
data=[d[0] for d in self.options.get("dataset")[0].get("source")][1:]
)
elif isinstance(data_pair[0], opts.PieItem):
data = data_pair
else... | if self.options.get("dataset") is not None:
data = None
self.options.get("legend")[0].update(
data=[d[0] for d in self.options.get("dataset")[0].get("source")][1:]
)
elif isinstance(data_pair[0], opts.PieItem):
data = data_pair
else... | 118 | 489 | 651 | 1,140 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Pie(Chart):
"""
<<< Pie >>>
The pie chart is mainly used to represent the proportion of data of
different categories in the total. Each radian represents the ratio of
the... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Pie(Chart):
"""
<<< Pie >>>
The pie chart is mainly used to represent the proportion of data of
different categories in the total. Each radian represents the ratio of
the... |
23,039 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/polar.py | 35,52 | 8,122 | add | Polar | 52,122 | 52,122 | class Polar(Chart):
"""
<<< Polar >>>
Polar coordinates can be used for scatter and polyline graphs.
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.RenderInit = opts.RenderOpts(),
):
super().__init__(init_opts=init_opts, rend... | class Polar(Chart):
"""
<<< Polar >>>
Polar coordinates can be used for scatter and polyline graphs.
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.RenderInit = opts.RenderOpts(),
):
super().__init__(init_opts=init_opts, rend... | self._append_legend(series_name)
self.options.update(polar={"center": center if center else ["50%", "50%"]})
if type_ in (ChartType.SCATTER, ChartType.LINE, ChartType.BAR):
self.options.get("series").append(
{
"type": type_,
"n... | self._append_legend(series_name)
self.options.update(polar={"center": center if center else ["50%", "50%"]})
if type_ in (ChartType.SCATTER, ChartType.LINE, ChartType.BAR):
self.options.get("series").append(
{
"type": type_,
"n... | 146 | 473 | 703 | 1,176 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...commons.utils import JsCode
from ...globals import ChartType
class Polar(Chart):
"""
<<< Polar >>>
Polar coordinates can be used for scatter and polyline graphs.
"""
def __init__(
self,
... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...commons.utils import JsCode
from ...globals import ChartType
class Polar(Chart):
"""
<<< Polar >>>
Polar coordinates can be used for scatter and polyline graphs.
"""
def __init__(
self,
... |
23,040 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/radar.py | 14,33 | 7,100 | add_schema | Radar | 33,65 | 33,65 | class Radar(Chart):
"""
<<< Radar >>>
Radar maps are mainly used to represent multivariable data.
"""
def add_schema(
self,
schema: types.Sequence[types.Union[opts.RadarIndicatorItem, dict]],
shape: types.Optional[str] = None,
center: types.Optional[types.Sequence] ... | class Radar(Chart):
"""
<<< Radar >>>
Radar maps are mainly used to represent multivariable data.
"""
def add_schema(
self,
schema: types.Sequence[types.Union[opts.RadarIndicatorItem, dict]],
shape: types.Optional[str] = None,
center: types.Optional[types.Sequence] ... | self.options.update(
radiusAxis=radiusaxis_opts, angleAxis=angleaxis_opts, polar=polar_opts
)
indicators = []
for s in schema:
if isinstance(s, opts.RadarIndicatorItem):
s = s.opts
indicators.append(s)
if self.options.get("rad... | self.options.update(
radiusAxis=radiusaxis_opts, angleAxis=angleaxis_opts, polar=polar_opts
)
indicators = []
for s in schema:
if isinstance(s, opts.RadarIndicatorItem):
s = s.opts
indicators.append(s)
if self.options.get("rad... | 57 | 715 | 309 | 1,024 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Radar(Chart):
"""
<<< Radar >>>
Radar maps are mainly used to represent multivariable data.
"""
def add_schema(
self,
schema: types.Sequence[types.Union[... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Radar(Chart):
"""
<<< Radar >>>
Radar maps are mainly used to represent multivariable data.
"""
def add_schema(
self,
schema: types.Sequence[types.Union[... |
23,041 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/sankey.py | 16,40 | 7,67 | add | Sankey | 40,67 | 40,67 | class Sankey(Chart):
"""
<<< Sankey >>>
Sankey diagram is a special flow diagram, which is mainly used to
express how raw materials, energy and so on from the initial form through
the intermediate process of processing, transformation to the final form.
"""
def add(
self,
s... | class Sankey(Chart):
"""
<<< Sankey >>>
Sankey diagram is a special flow diagram, which is mainly used to
express how raw materials, energy and so on from the initial form through
the intermediate process of processing, transformation to the final form.
"""
def add(
self,
s... | self._append_legend(series_name)
self.options.get("series").append(
{
"type": ChartType.SANKEY,
"name": series_name,
"data": nodes,
"links": links,
"left": pos_left,
"top": pos_top,
... | self._append_legend(series_name)
self.options.get("series").append(
{
"type": ChartType.SANKEY,
"name": series_name,
"data": nodes,
"links": links,
"left": pos_left,
"top": pos_top,
... | 49 | 395 | 273 | 668 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Sankey(Chart):
"""
<<< Sankey >>>
Sankey diagram is a special flow diagram, which is mainly used to
express how raw materials, energy and so on from the initial form through
... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Sankey(Chart):
"""
<<< Sankey >>>
Sankey diagram is a special flow diagram, which is mainly used to
express how raw materials, energy and so on from the initial form through
... |
23,042 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/scatter.py | 36,56 | 9,82 | add_yaxis | Scatter | 56,82 | 56,82 | class Scatter(RectChart):
"""
<<< Scatter >>>
The scatter diagram on the rectangular coordinate system can be used to
show the relationship between x and y of the data. If the data item has
multiple dimensions, it can be represented by color, and the
visualmap component can be used.
"""
... | class Scatter(RectChart):
"""
<<< Scatter >>>
The scatter diagram on the rectangular coordinate system can be used to
show the relationship between x and y of the data. If the data item has
multiple dimensions, it can be represented by color, and the
visualmap component can be used.
"""
... | self._append_color(color)
self._append_legend(series_name)
data = self._parse_data(y_axis=y_axis)
self.options.get("series").append(
{
"type": ChartType.SCATTER,
"name": series_name,
"xAxisIndex": xaxis_index,
... | self._append_color(color)
self._append_legend(series_name)
data = self._parse_data(y_axis=y_axis)
self.options.get("series").append(
{
"type": ChartType.SCATTER,
"name": series_name,
"xAxisIndex": xaxis_index,
... | 43 | 576 | 256 | 832 | import itertools
from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class Scatter(RectChart):
"""
<<< Scatter >>>
The scatter diagram on the rectangular coordinate system can be used to
show the relationship between x and y of... | import itertools
from ... import options as opts
from ... import types
from ...charts.chart import RectChart
from ...globals import ChartType
class Scatter(RectChart):
"""
<<< Scatter >>>
The scatter diagram on the rectangular coordinate system can be used to
show the relationship between x and y of... |
23,043 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/sunburst.py | 17,38 | 7,66 | add | Sunburst | 38,66 | 38,66 | class Sunburst(Chart):
"""
<<< Sunburst >>
Sunburst graphs are composed of multiple layers of ring graphs.
In terms of data structure, inner circle is the parent node of outer circle.
Therefore, it can represent local and global proportions like pie charts and
hierarchical relationships like re... | class Sunburst(Chart):
"""
<<< Sunburst >>
Sunburst graphs are composed of multiple layers of ring graphs.
In terms of data structure, inner circle is the parent node of outer circle.
Therefore, it can represent local and global proportions like pie charts and
hierarchical relationships like re... | if not center:
center = ["50%", "50%"]
if not radius:
radius = ["0%", "75%"]
self.options.get("series").append(
{
"type": ChartType.SUNBURST,
"name": series_name,
"data": data_pair,
"center": cen... | if not center:
center = ["50%", "50%"]
if not radius:
radius = ["0%", "75%"]
self.options.get("series").append(
{
"type": ChartType.SUNBURST,
"name": series_name,
"data": data_pair,
"center": cen... | 56 | 354 | 282 | 636 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Sunburst(Chart):
"""
<<< Sunburst >>
Sunburst graphs are composed of multiple layers of ring graphs.
In terms of data structure, inner circle is the parent node of outer circ... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Sunburst(Chart):
"""
<<< Sunburst >>
Sunburst graphs are composed of multiple layers of ring graphs.
In terms of data structure, inner circle is the parent node of outer circ... |
23,044 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/themeriver.py | 16,27 | 7,45 | add | ThemeRiver | 27,45 | 27,45 | class ThemeRiver(Chart):
"""
<<< ThemeRiver >>>
ThemeRiver graph is a special kind of flow graph,
which is mainly used to show the changes of events or themes
over a period of time.
"""
def add(
self,
series_name: types.Sequence,
data: types.Sequence[types.Union[opt... | class ThemeRiver(Chart):
"""
<<< ThemeRiver >>>
ThemeRiver graph is a special kind of flow graph,
which is mainly used to show the changes of events or themes
over a period of time.
"""
def add(
self,
series_name: types.Sequence,
data: types.Sequence[types.Union[opt... | for n in series_name:
self._append_legend(n)
self.options.get("series").append(
{
"type": ChartType.THEMERIVER,
"name": series_name,
"data": data,
"label": label_opts,
"tooltip": tooltip_opts,
... | for n in series_name:
self._append_legend(n)
self.options.get("series").append(
{
"type": ChartType.THEMERIVER,
"name": series_name,
"data": data,
"label": label_opts,
"tooltip": tooltip_opts,
... | 27 | 200 | 170 | 370 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class ThemeRiver(Chart):
"""
<<< ThemeRiver >>>
ThemeRiver graph is a special kind of flow graph,
which is mainly used to show the changes of events or themes
over a period of ... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class ThemeRiver(Chart):
"""
<<< ThemeRiver >>>
ThemeRiver graph is a special kind of flow graph,
which is mainly used to show the changes of events or themes
over a period of ... |
23,045 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/tree.py | 16,18 | 7,87 | _set_collapse_interval | Tree | 24,35 | 18,35 | class Tree(Chart):
"""
<<< Tree diagrams >>>
Tree diagrams are used primarily to visualize tree data structures,
which are special hierarchical types with unique root nodes, left subtrees,
and right subtrees.
"""
@staticmethod
def _set_collapse_interval(data, interval):
FILL_FUNC_BODY ... | class Tree(Chart):
"""
<<< Tree diagrams >>>
Tree diagrams are used primarily to visualize tree data structures,
which are special hierarchical types with unique root nodes, left subtrees,
and right subtrees.
"""
@staticmethod
def _set_collapse_interval(data, interval):
"""
... | if interval <= 0:
return data
if data and isinstance(data, list):
for d in data:
children = d.get("children", None)
if children and interval > 0:
for index, value in enumerate(children):
if index % interv... | """
间隔折叠节点,当节点过多时可以解决节点显示过杂间隔。
:param data: 节点数据
:param interval: 指定间隔
"""
if interval <= 0:
return data
if data and isinstance(data, list):
for d in data:
children = d.get("children", None)
if children and ... | 39 | 731 | 100 | 831 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Tree(Chart):
"""
<<< Tree diagrams >>>
Tree diagrams are used primarily to visualize tree data structures,
which are special hierarchical types with unique root nodes, left s... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class Tree(Chart):
"""
<<< Tree diagrams >>>
Tree diagrams are used primarily to visualize tree data structures,
which are special hierarchical types with unique root nodes, left s... |
23,046 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/treemap.py | 15,48 | 7,84 | add | TreeMap | 48,84 | 48,84 | class TreeMap(Chart):
"""
<<< TreeMap >>>
TreeMap are a common visual representation of "hierarchical data" and "tree data".
It mainly uses area to highlight the important nodes in the hierarchy of "tree".
"""
def add(
self,
series_name: str,
data: types.Sequence[types.... | class TreeMap(Chart):
"""
<<< TreeMap >>>
TreeMap are a common visual representation of "hierarchical data" and "tree data".
It mainly uses area to highlight the important nodes in the hierarchy of "tree".
"""
def add(
self,
series_name: str,
data: types.Sequence[types.... | self._append_legend(series_name)
self.options.get("series").append(
{
"type": ChartType.TREEMAP,
"name": series_name,
"data": data,
"left": pos_left,
"right": pos_right,
"top": pos_top,
... | self._append_legend(series_name)
self.options.get("series").append(
{
"type": ChartType.TREEMAP,
"name": series_name,
"data": data,
"left": pos_left,
"right": pos_right,
"top": pos_top,
... | 67 | 603 | 393 | 996 | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class TreeMap(Chart):
"""
<<< TreeMap >>>
TreeMap are a common visual representation of "hierarchical data" and "tree data".
It mainly uses area to highlight the important nodes in... | from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...globals import ChartType
class TreeMap(Chart):
"""
<<< TreeMap >>>
TreeMap are a common visual representation of "hierarchical data" and "tree data".
It mainly uses area to highlight the important nodes in... |
23,047 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/wordcloud.py | 15,16 | 1,141 | gen_color | 19,26 | 16,26 | import base64
import random
from pathlib import Path
from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...commons.utils import JsCode
from ...exceptions import WordCloudMaskImageException
from ...globals import ChartType
SHAPES = ("cardioid", "diamond", "triangle-forward", "... | import base64
import random
from pathlib import Path
from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...commons.utils import JsCode
from ...exceptions import WordCloudMaskImageException
from ...globals import ChartType
SHAPES = ("cardioid", "diamond", "triangle-forward", "... | return "rgb(%s,%s,%s)" % (
random.randint(0, 160),
random.randint(0, 160),
random.randint(0, 160),
)
| """
generate random color for WordCloud
"""
return "rgb(%s,%s,%s)" % (
random.randint(0, 160),
random.randint(0, 160),
random.randint(0, 160),
)
| 11 | 1,418 | 72 | 1,490 | import base64
import random
from pathlib import Path
from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...commons.utils import JsCode
from ...exceptions import WordCloudMaskImageException
from ...globals import ChartType
SHAPES = ("cardioid", "diamond", "triangle-forward", "... | import base64
import random
from pathlib import Path
from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...commons.utils import JsCode
from ...exceptions import WordCloudMaskImageException
from ...globals import ChartType
SHAPES = ("cardioid", "diamond", "triangle-forward", "... | |
23,048 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/basic_charts/wordcloud.py | 56,57 | 26,141 | _encode_image_to_base64 | WordCloud | 57,71 | 57,71 | class WordCloud(Chart):
"""
<<< WordCloud >>>
Word cloud is to visually highlight the keywords that
appear frequently in the text.
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.RenderInit = opts.RenderOpts(),
):
super().... | class WordCloud(Chart):
"""
<<< WordCloud >>>
Word cloud is to visually highlight the keywords that
appear frequently in the text.
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.RenderInit = opts.RenderOpts(),
):
super().... | try:
# 尝试判断是否为图片路径(base64 长度很长会导致 Pathlib 会异常)
is_image_file = Path(image_or_path).is_file()
is_image_file_exist = Path(image_or_path).exists()
if is_image_file and is_image_file_exist:
ext = Path(image_or_path).suffix[1:]
if ext in... | try:
# 尝试判断是否为图片路径(base64 长度很长会导致 Pathlib 会异常)
is_image_file = Path(image_or_path).is_file()
is_image_file_exist = Path(image_or_path).exists()
if is_image_file and is_image_file_exist:
ext = Path(image_or_path).suffix[1:]
if ext in... | 40 | 1,100 | 215 | 1,315 | import base64
import random
from pathlib import Path
from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...commons.utils import JsCode
from ...exceptions import WordCloudMaskImageException
from ...globals import ChartType
SHAPES = ("cardioid", "diamond", "triangle-forward", "... | import base64
import random
from pathlib import Path
from ... import options as opts
from ... import types
from ...charts.chart import Chart
from ...commons.utils import JsCode
from ...exceptions import WordCloudMaskImageException
from ...globals import ChartType
SHAPES = ("cardioid", "diamond", "triangle-forward", "... |
23,050 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/chart.py | 276,304 | 261,336 | add_globe | Chart3D | 304,336 | 304,336 | class Chart3D(Chart):
"""
`Chart3D`类是所有 3D 类图表的基类,继承自 `Chart` 类
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.RenderInit = opts.RenderOpts(),
):
init_opts.renderer = RenderType.CANVAS
super().__init__(init_opts, render_op... | class Chart3D(Chart):
"""
`Chart3D`类是所有 3D 类图表的基类,继承自 `Chart` 类
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.RenderInit = opts.RenderOpts(),
):
init_opts.renderer = RenderType.CANVAS
super().__init__(init_opts, render_op... | self.options.update(
globe={
"show": is_show,
"globeRadius": globe_radius,
"globeOuterRadius": globe_outer_radius,
"environment": environment,
"baseTexture": base_texture,
"heightTexture": height_texture,... | self.options.update(
globe={
"show": is_show,
"globeRadius": globe_radius,
"globeOuterRadius": globe_outer_radius,
"environment": environment,
"baseTexture": base_texture,
"heightTexture": height_texture,... | 57 | 687 | 332 | 1,019 | from .. import options as opts
from .. import types
from ..charts.base import Base
from ..globals import RenderType, ThemeType, ToolTipFormatterType
from ..types import Optional, Sequence
class Chart(Base):
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.Ren... | from .. import options as opts
from .. import types
from ..charts.base import Base
from ..globals import RenderType, ThemeType, ToolTipFormatterType
from ..types import Optional, Sequence
class Chart(Base):
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.Ren... |
23,051 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/chart.py | 219,225 | 210,261 | extend_axis | RectChart | 225,236 | 225,236 | class RectChart(Chart):
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.RenderInit = opts.RenderOpts(),
):
super().__init__(init_opts=init_opts, render_opts=render_opts)
self.options.update(xAxis=[opts.AxisOpts().opts], yAxis=[opts.AxisOpts... | class RectChart(Chart):
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.RenderInit = opts.RenderOpts(),
):
super().__init__(init_opts=init_opts, render_opts=render_opts)
self.options.update(xAxis=[opts.AxisOpts().opts], yAxis=[opts.AxisOpts... | if xaxis is not None:
if isinstance(xaxis, opts.AxisOpts):
xaxis = xaxis.opts
xaxis.update(data=xaxis_data)
self.options["xAxis"].append(xaxis)
if yaxis is not None:
if isinstance(yaxis, opts.AxisOpts):
yaxis = yaxis.opts
... | if xaxis is not None:
if isinstance(xaxis, opts.AxisOpts):
xaxis = xaxis.opts
xaxis.update(data=xaxis_data)
self.options["xAxis"].append(xaxis)
if yaxis is not None:
if isinstance(yaxis, opts.AxisOpts):
yaxis = yaxis.opts
... | 27 | 484 | 124 | 608 | from .. import options as opts
from .. import types
from ..charts.base import Base
from ..globals import RenderType, ThemeType, ToolTipFormatterType
from ..types import Optional, Sequence
class Chart(Base):
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.Ren... | from .. import options as opts
from .. import types
from ..charts.base import Base
from ..globals import RenderType, ThemeType, ToolTipFormatterType
from ..types import Optional, Sequence
class Chart(Base):
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.Ren... |
23,052 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/chart.py | 337,356 | 336,397 | add | ThreeAxisChart | 356,397 | 356,397 | class ThreeAxisChart(Chart3D):
def add(
self,
series_name: str,
data: Sequence,
shading: Optional[str] = None,
itemstyle_opts: types.ItemStyle = None,
label_opts: types.Label = opts.LabelOpts(is_show=False),
grid_3d_index: types.Numeric = 0,
xaxis3d_op... | class ThreeAxisChart(Chart3D):
def add(
self,
series_name: str,
data: Sequence,
shading: Optional[str] = None,
itemstyle_opts: types.ItemStyle = None,
label_opts: types.Label = opts.LabelOpts(is_show=False),
grid_3d_index: types.Numeric = 0,
xaxis3d_op... | self.options.get("legend")[0].get("data").append(series_name)
self.options.update(
xAxis3D=xaxis3d_opts,
yAxis3D=yaxis3d_opts,
zAxis3D=zaxis3d_opts,
grid3D=grid3d_opts,
)
if self._3d_chart_type == "surface":
self.options.get("s... | self.options.get("legend")[0].get("data").append(series_name)
self.options.update(
xAxis3D=xaxis3d_opts,
yAxis3D=yaxis3d_opts,
zAxis3D=zaxis3d_opts,
grid3D=grid3d_opts,
)
if self._3d_chart_type == "surface":
self.options.get("s... | 65 | 348 | 425 | 773 | from .. import options as opts
from .. import types
from ..charts.base import Base
from ..globals import RenderType, ThemeType, ToolTipFormatterType
from ..types import Optional, Sequence
class Chart(Base):
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.Ren... | from .. import options as opts
from .. import types
from ..charts.base import Base
from ..globals import RenderType, ThemeType, ToolTipFormatterType
from ..types import Optional, Sequence
class Chart(Base):
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.Ren... |
23,053 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/composite_charts/grid.py | 28,36 | 10,112 | add | Grid | 36,112 | 36,112 | class Grid(Base):
"""
`Gird` Drawing grid in rectangular coordinate. In a single grid,
at most two X and Y axes each is allowed. Line chart, bar chart,
and scatter chart (bubble chart) can be drawn in grid.
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
... | class Grid(Base):
"""
`Gird` Drawing grid in rectangular coordinate. In a single grid,
at most two X and Y axes each is allowed. Line chart, bar chart,
and scatter chart (bubble chart) can be drawn in grid.
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
... | if self.options is None:
self.options = copy.deepcopy(chart.options)
self.chart_id = chart.chart_id
self.options.update(grid=[], title=[])
if self.theme != ThemeType.WHITE:
self.options.update(color=[])
# Priority Order: Grid > Other C... | if self.options is None:
self.options = copy.deepcopy(chart.options)
self.chart_id = chart.chart_id
self.options.update(grid=[], title=[])
if self.theme != ThemeType.WHITE:
self.options.update(color=[])
# Priority Order: Grid > Other C... | 165 | 273 | 998 | 1,271 | import copy
from ... import options as opts
from ... import types
from ...globals import ThemeType
from ..basic_charts.radar import Radar
from ..chart import Base, Chart, RectChart
class Grid(Base):
"""
`Gird` Drawing grid in rectangular coordinate. In a single grid,
at most two X and Y axes each is allo... | import copy
from ... import options as opts
from ... import types
from ...globals import ThemeType
from ..basic_charts.radar import Radar
from ..chart import Base, Chart, RectChart
class Grid(Base):
"""
`Gird` Drawing grid in rectangular coordinate. In a single grid,
at most two X and Y axes each is allo... |
23,054 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/composite_charts/page.py | 150,151 | 42,212 | render_notebook | Page | 151,162 | 151,162 | class Page(CompositeMixin):
"""
`Page` A container object to present multiple charts vertically in a single page
"""
SimplePageLayout = PageLayoutOpts(
justify_content="center", display="flex", flex_wrap="wrap"
)
DraggablePageLayout = PageLayoutOpts()
def __init__(
self,
... | class Page(CompositeMixin):
"""
`Page` A container object to present multiple charts vertically in a single page
"""
SimplePageLayout = PageLayoutOpts(
justify_content="center", display="flex", flex_wrap="wrap"
)
DraggablePageLayout = PageLayoutOpts()
def __init__(
self,
... | for c in self:
c.chart_id = uuid.uuid4().hex
if hasattr(c, "dump_options"):
c.json_contents = c.dump_options()
if hasattr(c, "theme"):
if c.theme not in ThemeType.BUILTIN_THEMES:
self.js_dependencies.add(c.theme)
ret... | for c in self:
c.chart_id = uuid.uuid4().hex
if hasattr(c, "dump_options"):
c.json_contents = c.dump_options()
if hasattr(c, "theme"):
if c.theme not in ThemeType.BUILTIN_THEMES:
self.js_dependencies.add(c.theme)
ret... | 28 | 1,681 | 152 | 1,833 | import json
import re
import uuid
from jinja2 import Environment
from ... import types
from ...commons import utils
from ...globals import CurrentConfig, ThemeType
from ...options import PageLayoutOpts
from ...render import engine
from ..mixins import CompositeMixin
_MARK_FREEDOM_LAYOUT = "_MARK_FREEDOM_LAYOUT_"
DO... | import json
import re
import uuid
from jinja2 import Environment
from ... import types
from ...commons import utils
from ...globals import CurrentConfig, ThemeType
from ...options import PageLayoutOpts
from ...render import engine
from ..mixins import CompositeMixin
_MARK_FREEDOM_LAYOUT = "_MARK_FREEDOM_LAYOUT_"
DO... |
23,055 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/composite_charts/tab.py | 157,158 | 55,165 | render_notebook | Tab | 158,165 | 158,165 | class Tab(CompositeMixin):
def __init__(
self,
page_title: str = CurrentConfig.PAGE_TITLE,
js_host: str = "",
bg_color: str = "",
tab_css_opts: TabChartGlobalOpts = TabChartGlobalOpts(),
):
self.js_host: str = js_host or CurrentConfig.ONLINE_HOST
self.page... | class Tab(CompositeMixin):
def __init__(
self,
page_title: str = CurrentConfig.PAGE_TITLE,
js_host: str = "",
bg_color: str = "",
tab_css_opts: TabChartGlobalOpts = TabChartGlobalOpts(),
):
self.js_host: str = js_host or CurrentConfig.ONLINE_HOST
self.page... | self._prepare_render()
# only notebook env need to re-generate chart_id
for c in self:
c.chart_id = uuid.uuid4().hex
return engine.render_notebook(
self, "nb_jupyter_notebook_tab.html", "nb_jupyter_lab_tab.html"
)
| self._prepare_render()
# only notebook env need to re-generate chart_id
for c in self:
c.chart_id = uuid.uuid4().hex
return engine.render_notebook(
self, "nb_jupyter_notebook_tab.html", "nb_jupyter_lab_tab.html"
)
| 22 | 1,206 | 98 | 1,304 | import uuid
from jinja2 import Environment
from ... import types
from ...commons import utils
from ...globals import CurrentConfig, ThemeType
from ...options.charts_options import TabChartGlobalOpts
from ...render import engine
from ..mixins import CompositeMixin
DEFAULT_TAB_CSS: str = """
.chart-container {
di... | import uuid
from jinja2 import Environment
from ... import types
from ...commons import utils
from ...globals import CurrentConfig, ThemeType
from ...options.charts_options import TabChartGlobalOpts
from ...render import engine
from ..mixins import CompositeMixin
DEFAULT_TAB_CSS: str = """
.chart-container {
di... |
23,056 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/composite_charts/timeline.py | 21,51 | 6,134 | add_schema | Timeline | 51,86 | 51,86 | class Timeline(Base):
"""
`Timeline` provides functions like switching and playing between multiple charts.
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.RenderInit = opts.RenderOpts(),
):
super().__init__(init_opts=init_opts, re... | class Timeline(Base):
"""
`Timeline` provides functions like switching and playing between multiple charts.
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: types.RenderInit = opts.RenderOpts(),
):
super().__init__(init_opts=init_opts, re... | self.options.get("baseOption").get("timeline").update(
{
"axisType": axis_type,
"currentIndex": current_index,
"orient": orient,
"autoPlay": is_auto_play,
"controlPosition": control_position,
"loop": is_l... | self.options.get("baseOption").get("timeline").update(
{
"axisType": axis_type,
"currentIndex": current_index,
"orient": orient,
"autoPlay": is_auto_play,
"controlPosition": control_position,
"loop": is_l... | 63 | 1,036 | 353 | 1,389 | from ... import options as opts
from ... import types
from ...charts.chart import Base
class Timeline(Base):
"""
`Timeline` provides functions like switching and playing between multiple charts.
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: type... | from ... import options as opts
from ... import types
from ...charts.chart import Base
class Timeline(Base):
"""
`Timeline` provides functions like switching and playing between multiple charts.
"""
def __init__(
self,
init_opts: types.Init = opts.InitOpts(),
render_opts: type... |
23,057 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/mixins.py | 5,6 | 4,14 | add_js_funcs | ChartMixin | 6,10 | 6,10 | class ChartMixin:
def add_js_funcs(self, *fns):
FILL_FUNC_BODY def load_javascript(self):
return engine.load_javascript(self)
| class ChartMixin:
def add_js_funcs(self, *fns):
FILL_FUNC_BODY def load_javascript(self):
return engine.load_javascript(self)
| for fn in fns:
self.js_functions.add(fn)
return self
| for fn in fns:
self.js_functions.add(fn)
return self
| 7 | 54 | 29 | 83 | from ..render import engine
class ChartMixin:
def add_js_funcs(self, *fns):
FILL_FUNC_BODY def load_javascript(self):
return engine.load_javascript(self)
class CompositeMixin(ChartMixin):
def __iter__(self):
for chart in self._charts:
yield chart
def __len__(self):
... | from ..render import engine
class ChartMixin:
def add_js_funcs(self, *fns):
FILL_FUNC_BODY def load_javascript(self):
return engine.load_javascript(self)
class CompositeMixin(ChartMixin):
def __iter__(self):
for chart in self._charts:
yield chart
def __len__(self):
... |
23,058 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/three_axis_charts/graph_gl.py | 22,36 | 8,52 | add | GraphGL | 36,52 | 36,52 | class GraphGL(Chart3D):
"""
<<< GraphGL Relational graphs using WebGL to support the layout and
drawing of large-scale network/relational data. >>>
"""
def __init__(
self,
init_opts: types.Init = InitOpts(),
render_opts: types.RenderInit = RenderOpts(),
):
super(... | class GraphGL(Chart3D):
"""
<<< GraphGL Relational graphs using WebGL to support the layout and
drawing of large-scale network/relational data. >>>
"""
def __init__(
self,
init_opts: types.Init = InitOpts(),
render_opts: types.RenderInit = RenderOpts(),
):
super(... | self.options.get("series").append(
{
"type": ChartType.GRAPHGL,
"name": series_name,
"layout": layout,
"forceAtlas2": force_atlas2_opts,
"nodes": nodes,
"links": links,
"symbol": symbol,
... | self.options.get("series").append(
{
"type": ChartType.GRAPHGL,
"name": series_name,
"layout": layout,
"forceAtlas2": force_atlas2_opts,
"nodes": nodes,
"links": links,
"symbol": symbol,
... | 28 | 297 | 150 | 447 | from ... import options as opts
from ... import types
from ...charts.chart import Chart3D
from ...globals import ChartType
from ...options import InitOpts, RenderOpts
class GraphGL(Chart3D):
"""
<<< GraphGL Relational graphs using WebGL to support the layout and
drawing of large-scale network/relational d... | from ... import options as opts
from ... import types
from ...charts.chart import Chart3D
from ...globals import ChartType
from ...options import InitOpts, RenderOpts
class GraphGL(Chart3D):
"""
<<< GraphGL Relational graphs using WebGL to support the layout and
drawing of large-scale network/relational d... |
23,059 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/three_axis_charts/lines3D.py | 21,42 | 8,67 | add | Lines3D | 42,67 | 42,67 | class Lines3D(Chart3D):
"""
Lines 3D
"""
def __init__(
self,
init_opts: types.Init = InitOpts(),
render_opts: types.RenderInit = RenderOpts(),
):
super().__init__(init_opts, render_opts)
self._3d_chart_type = ChartType.LINES3D
def add(
self,
... | class Lines3D(Chart3D):
"""
Lines 3D
"""
def __init__(
self,
init_opts: types.Init = InitOpts(),
render_opts: types.RenderInit = RenderOpts(),
):
super().__init__(init_opts, render_opts)
self._3d_chart_type = ChartType.LINES3D
def add(
self,
... | self.options.get("series").append(
{
"type": ChartType.LINES3D,
"name": series_name,
"data": data_pair,
"coordinateSystem": coordinate_system,
"geo3DIndex": geo_3d_index,
"globeIndex": globe_index,
... | self.options.get("series").append(
{
"type": ChartType.LINES3D,
"name": series_name,
"data": data_pair,
"coordinateSystem": coordinate_system,
"geo3DIndex": geo_3d_index,
"globeIndex": globe_index,
... | 45 | 389 | 287 | 676 | from ... import options as opts
from ... import types
from ...charts.chart import Chart3D
from ...globals import ChartType
from ...options import InitOpts, RenderOpts
class Lines3D(Chart3D):
"""
Lines 3D
"""
def __init__(
self,
init_opts: types.Init = InitOpts(),
render_opts: ... | from ... import options as opts
from ... import types
from ...charts.chart import Chart3D
from ...globals import ChartType
from ...options import InitOpts, RenderOpts
class Lines3D(Chart3D):
"""
Lines 3D
"""
def __init__(
self,
init_opts: types.Init = InitOpts(),
render_opts: ... |
23,061 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/charts/three_axis_charts/map_globe.py | 40,41 | 15,55 | render_notebook | MapGlobe | 41,55 | 41,55 | class MapGlobe(Chart3D, MapMixin):
"""
Globe Map
"""
def __init__(
self,
init_opts: types.Init = InitOpts(),
render_opts: types.RenderInit = RenderOpts(),
):
super().__init__(init_opts, render_opts)
def add_schema(self, maptype: str = "china"):
self.js_d... | class MapGlobe(Chart3D, MapMixin):
"""
Globe Map
"""
def __init__(
self,
init_opts: types.Init = InitOpts(),
render_opts: types.RenderInit = RenderOpts(),
):
super().__init__(init_opts, render_opts)
def add_schema(self, maptype: str = "china"):
self.js_d... | self.chart_id = uuid.uuid4().hex
self._prepare_render()
if CurrentConfig.NOTEBOOK_TYPE == NotebookType.JUPYTER_NOTEBOOK:
require_config = utils.produce_require_dict(
self.js_dependencies, self.js_host
)
return HTML(
RenderEngine... | self.chart_id = uuid.uuid4().hex
self._prepare_render()
if CurrentConfig.NOTEBOOK_TYPE == NotebookType.JUPYTER_NOTEBOOK:
require_config = utils.produce_require_dict(
self.js_dependencies, self.js_host
)
return HTML(
RenderEngine... | 23 | 234 | 173 | 407 | import uuid
from jinja2 import Environment
from ... import types
from ...charts.basic_charts.map import MapMixin
from ...charts.chart import Chart3D
from ...commons import utils
from ...globals import CurrentConfig, NotebookType
from ...options import InitOpts, RenderOpts
from ...render.display import HTML
from ...re... | import uuid
from jinja2 import Environment
from ... import types
from ...charts.basic_charts.map import MapMixin
from ...charts.chart import Chart3D
from ...commons import utils
from ...globals import CurrentConfig, NotebookType
from ...options import InitOpts, RenderOpts
from ...render.display import HTML
from ...re... |
23,062 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/commons/utils.py | 53,54 | 1,113 | replace_placeholder_with_quotes | 54,67 | 54,67 | import re
from ..datasets import EXTRA, FILENAMES
class JsCode:
def __init__(self, js_code: str):
self.js_code = "--x_x--0_0--" + js_code + "--x_x--0_0--"
def replace(self, pattern: str, repl: str):
self.js_code = re.sub(pattern, repl, self.js_code)
return self
class OrderedSet:
... | import re
from ..datasets import EXTRA, FILENAMES
class JsCode:
def __init__(self, js_code: str):
self.js_code = "--x_x--0_0--" + js_code + "--x_x--0_0--"
def replace(self, pattern: str, repl: str):
self.js_code = re.sub(pattern, repl, self.js_code)
return self
class OrderedSet:
... | return re.sub("--x_x--0_0--", "", html)
# def _flat(obj):
# if hasattr(obj, "js_dependencies"):
# return list(obj.js_dependencies)
#
# if isinstance(obj, (list, tuple, set)):
# return obj
#
# return (obj,) # tuple
| return re.sub("--x_x--0_0--", "", html)
# def _flat(obj):
# if hasattr(obj, "js_dependencies"):
# return list(obj.js_dependencies)
#
# if isinstance(obj, (list, tuple, set)):
# return obj
#
# return (obj,) # tuple
| 30 | 910 | 110 | 1,020 | import re
from ..datasets import EXTRA, FILENAMES
class JsCode:
def __init__(self, js_code: str):
self.js_code = "--x_x--0_0--" + js_code + "--x_x--0_0--"
def replace(self, pattern: str, repl: str):
self.js_code = re.sub(pattern, repl, self.js_code)
return self
class OrderedSet:
... | import re
from ..datasets import EXTRA, FILENAMES
class JsCode:
def __init__(self, js_code: str):
self.js_code = "--x_x--0_0--" + js_code + "--x_x--0_0--"
def replace(self, pattern: str, repl: str):
self.js_code = re.sub(pattern, repl, self.js_code)
return self
class OrderedSet:
... | |
23,063 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/commons/utils.py | 10,11 | 6,15 | replace | JsCode | 11,15 | 11,15 | class JsCode:
def __init__(self, js_code: str):
self.js_code = "--x_x--0_0--" + js_code + "--x_x--0_0--"
def replace(self, pattern: str, repl: str):
FILL_FUNC_BODY | class JsCode:
def __init__(self, js_code: str):
self.js_code = "--x_x--0_0--" + js_code + "--x_x--0_0--"
def replace(self, pattern: str, repl: str):
FILL_FUNC_BODY | self.js_code = re.sub(pattern, repl, self.js_code)
return self
| self.js_code = re.sub(pattern, repl, self.js_code)
return self
| 7 | 79 | 32 | 111 | import re
from ..datasets import EXTRA, FILENAMES
class JsCode:
def __init__(self, js_code: str):
self.js_code = "--x_x--0_0--" + js_code + "--x_x--0_0--"
def replace(self, pattern: str, repl: str):
FILL_FUNC_BODYclass OrderedSet:
def __init__(self, *args):
self._values = dict()
... | import re
from ..datasets import EXTRA, FILENAMES
class JsCode:
def __init__(self, js_code: str):
self.js_code = "--x_x--0_0--" + js_code + "--x_x--0_0--"
def replace(self, pattern: str, repl: str):
FILL_FUNC_BODYclass OrderedSet:
def __init__(self, *args):
self._values = dict()
... |
23,064 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/commons/utils.py | 22,23 | 15,29 | add | OrderedSet | 23,29 | 23,29 | class OrderedSet:
def __init__(self, *args):
self._values = dict()
self.items = []
for a in args:
self.add(a)
def add(self, *items):
FILL_FUNC_BODY | class OrderedSet:
def __init__(self, *args):
self._values = dict()
self.items = []
for a in args:
self.add(a)
def add(self, *items):
FILL_FUNC_BODY | for item in items:
if not self._values.get(item, False):
self._values.update({item: True})
self.items.append(item)
| for item in items:
if not self._values.get(item, False):
self._values.update({item: True})
self.items.append(item)
| 11 | 68 | 51 | 119 | import re
from ..datasets import EXTRA, FILENAMES
class JsCode:
def __init__(self, js_code: str):
self.js_code = "--x_x--0_0--" + js_code + "--x_x--0_0--"
def replace(self, pattern: str, repl: str):
self.js_code = re.sub(pattern, repl, self.js_code)
return self
class OrderedSet:
... | import re
from ..datasets import EXTRA, FILENAMES
class JsCode:
def __init__(self, js_code: str):
self.js_code = "--x_x--0_0--" + js_code + "--x_x--0_0--"
def replace(self, pattern: str, repl: str):
self.js_code = re.sub(pattern, repl, self.js_code)
return self
class OrderedSet:
... |
23,065 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/components/image.py | 23,24 | 13,57 | add | Image | 24,32 | 24,32 | class Image(ChartMixin):
def __init__(self, page_title: str = CurrentConfig.PAGE_TITLE, js_host: str = ""):
self.page_title = page_title
self.js_host = js_host or CurrentConfig.ONLINE_HOST
self.js_dependencies: OrderedSet = OrderedSet()
self.title_opts: ComponentTitleOpts = Component... | class Image(ChartMixin):
def __init__(self, page_title: str = CurrentConfig.PAGE_TITLE, js_host: str = ""):
self.page_title = page_title
self.js_host = js_host or CurrentConfig.ONLINE_HOST
self.js_dependencies: OrderedSet = OrderedSet()
self.title_opts: ComponentTitleOpts = Component... | html_tag_args = ""
html_tag_args += 'src="{}" '.format(src)
if style_opts:
for k, v in style_opts.items():
html_tag_args += '{}="{}" '.format(k, v)
self.html_content = html_tag_args
return self
| html_tag_args = ""
html_tag_args += 'src="{}" '.format(src)
if style_opts:
for k, v in style_opts.items():
html_tag_args += '{}="{}" '.format(k, v)
self.html_content = html_tag_args
return self
| 24 | 436 | 95 | 531 | import uuid
from jinja2 import Environment
from ..charts.mixins import ChartMixin
from ..commons.utils import OrderedSet
from ..globals import CurrentConfig
from ..options import ComponentTitleOpts
from ..render import engine
from ..types import Optional, Union
class Image(ChartMixin):
def __init__(self, page_t... | import uuid
from jinja2 import Environment
from ..charts.mixins import ChartMixin
from ..commons.utils import OrderedSet
from ..globals import CurrentConfig
from ..options import ComponentTitleOpts
from ..render import engine
from ..types import Optional, Union
class Image(ChartMixin):
def __init__(self, page_t... |
23,066 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/components/table.py | 25,26 | 14,58 | add | Table | 26,33 | 26,33 | class Table(ChartMixin):
def __init__(self, page_title: str = CurrentConfig.PAGE_TITLE, js_host: str = ""):
self.page_title = page_title
self.js_host = js_host or CurrentConfig.ONLINE_HOST
self.js_dependencies: OrderedSet = OrderedSet()
self.js_functions: OrderedSet = OrderedSet()
... | class Table(ChartMixin):
def __init__(self, page_title: str = CurrentConfig.PAGE_TITLE, js_host: str = ""):
self.page_title = page_title
self.js_host = js_host or CurrentConfig.ONLINE_HOST
self.js_dependencies: OrderedSet = OrderedSet()
self.js_functions: OrderedSet = OrderedSet()
... | attributes = attributes or {"class": "fl-table"}
table = PrettyTable(headers, attributes=attributes)
for r in rows:
table.add_row(r)
self.html_content = table.get_html_string()
return self
| attributes = attributes or {"class": "fl-table"}
table = PrettyTable(headers, attributes=attributes)
for r in rows:
table.add_row(r)
self.html_content = table.get_html_string()
return self
| 20 | 456 | 73 | 529 | import uuid
from jinja2 import Environment
from prettytable import PrettyTable
from ..charts.mixins import ChartMixin
from ..commons.utils import OrderedSet
from ..globals import CurrentConfig
from ..options import ComponentTitleOpts
from ..render import engine
from ..types import Optional, Sequence, Union
class Ta... | import uuid
from jinja2 import Environment
from prettytable import PrettyTable
from ..charts.mixins import ChartMixin
from ..commons.utils import OrderedSet
from ..globals import CurrentConfig
from ..options import ComponentTitleOpts
from ..render import engine
from ..types import Optional, Sequence, Union
class Ta... |
23,067 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/faker.py | 100,102 | 97,103 | funcs | Collector | 102,103 | 102,103 | class Collector:
charts = []
@staticmethod
def funcs(fn):
FILL_FUNC_BODY | class Collector:
charts = []
@staticmethod
def funcs(fn):
FILL_FUNC_BODY | Collector.charts.append((fn, fn.__name__))
| Collector.charts.append((fn, fn.__name__))
| 2 | 34 | 18 | 52 | import os
import random
class _Faker:
clothes = ["衬衫", "毛衣", "领带", "裤子", "风衣", "高跟鞋", "袜子"]
drinks = ["可乐", "雪碧", "橙汁", "绿茶", "奶茶", "百威", "青岛"]
phones = ["小米", "三星", "华为", "苹果", "魅族", "VIVO", "OPPO"]
fruits = ["草莓", "芒果", "葡萄", "雪梨", "西瓜", "柠檬", "车厘子"]
animal = ["河马", "蟒蛇", "老虎", "大象", "兔子", "熊猫",... | import os
import random
class _Faker:
clothes = ["衬衫", "毛衣", "领带", "裤子", "风衣", "高跟鞋", "袜子"]
drinks = ["可乐", "雪碧", "橙汁", "绿茶", "奶茶", "百威", "青岛"]
phones = ["小米", "三星", "华为", "苹果", "魅族", "VIVO", "OPPO"]
fruits = ["草莓", "芒果", "葡萄", "雪梨", "西瓜", "柠檬", "车厘子"]
animal = ["河马", "蟒蛇", "老虎", "大象", "兔子", "熊猫",... |
23,068 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/faker.py | 64,66 | 5,94 | rand_color | _Faker | 66,89 | 66,89 | class _Faker:
clothes = ["衬衫", "毛衣", "领带", "裤子", "风衣", "高跟鞋", "袜子"]
drinks = ["可乐", "雪碧", "橙汁", "绿茶", "奶茶", "百威", "青岛"]
phones = ["小米", "三星", "华为", "苹果", "魅族", "VIVO", "OPPO"]
fruits = ["草莓", "芒果", "葡萄", "雪梨", "西瓜", "柠檬", "车厘子"]
animal = ["河马", "蟒蛇", "老虎", "大象", "兔子", "熊猫", "狮子"]
cars = ["宝马", "... | class _Faker:
clothes = ["衬衫", "毛衣", "领带", "裤子", "风衣", "高跟鞋", "袜子"]
drinks = ["可乐", "雪碧", "橙汁", "绿茶", "奶茶", "百威", "青岛"]
phones = ["小米", "三星", "华为", "苹果", "魅族", "VIVO", "OPPO"]
fruits = ["草莓", "芒果", "葡萄", "雪梨", "西瓜", "柠檬", "车厘子"]
animal = ["河马", "蟒蛇", "老虎", "大象", "兔子", "熊猫", "狮子"]
cars = ["宝马", "... | return random.choice(
[
"#c23531",
"#2f4554",
"#61a0a8",
"#d48265",
"#749f83",
"#ca8622",
"#bda29a",
"#6e7074",
"#546570",
"#c4ccd3",
... | return random.choice(
[
"#c23531",
"#2f4554",
"#61a0a8",
"#d48265",
"#749f83",
"#ca8622",
"#bda29a",
"#6e7074",
"#546570",
"#c4ccd3",
... | 23 | 898 | 216 | 1,114 | import os
import random
class _Faker:
clothes = ["衬衫", "毛衣", "领带", "裤子", "风衣", "高跟鞋", "袜子"]
drinks = ["可乐", "雪碧", "橙汁", "绿茶", "奶茶", "百威", "青岛"]
phones = ["小米", "三星", "华为", "苹果", "魅族", "VIVO", "OPPO"]
fruits = ["草莓", "芒果", "葡萄", "雪梨", "西瓜", "柠檬", "车厘子"]
animal = ["河马", "蟒蛇", "老虎", "大象", "兔子", "熊猫",... | import os
import random
class _Faker:
clothes = ["衬衫", "毛衣", "领带", "裤子", "风衣", "高跟鞋", "袜子"]
drinks = ["可乐", "雪碧", "橙汁", "绿茶", "奶茶", "百威", "青岛"]
phones = ["小米", "三星", "华为", "苹果", "魅族", "VIVO", "OPPO"]
fruits = ["草莓", "芒果", "葡萄", "雪梨", "西瓜", "柠檬", "车厘子"]
animal = ["河马", "蟒蛇", "老虎", "大象", "兔子", "熊猫",... |
23,069 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/options/charts_options.py | 299,300 | 283,306 | _convert_dict_to_string | ComponentTitleOpts | 300,306 | 300,306 | class ComponentTitleOpts:
def __init__(
self,
title: str = "",
subtitle: str = "",
title_style: Optional[dict] = None,
subtitle_style: Optional[dict] = None,
):
self.title = title.replace("\n", "<br/>")
self.subtitle = subtitle.replace("\n", "<br/>")
... | class ComponentTitleOpts:
def __init__(
self,
title: str = "",
subtitle: str = "",
title_style: Optional[dict] = None,
subtitle_style: Optional[dict] = None,
):
self.title = title.replace("\n", "<br/>")
self.subtitle = subtitle.replace("\n", "<br/>")
... | for k, v in title_style.items():
self.title_style += '{}="{}" '.format(k, v)
for k, v in subtitle_style.items():
self.subtitle_style += '{}="{}" '.format(k, v)
| for k, v in title_style.items():
self.title_style += '{}="{}" '.format(k, v)
for k, v in subtitle_style.items():
self.subtitle_style += '{}="{}" '.format(k, v)
| 20 | 239 | 78 | 317 | import simplejson as json
from ..globals import BMapType
from .global_options import TooltipOpts
from .series_options import (
BasicOpts,
ItemStyleOpts,
JSFunc,
LabelOpts,
LineStyleOpts,
Numeric,
Optional,
Sequence,
TextStyleOpts,
Union,
AreaStyleOpts,
)
# Chart Options
cl... | import simplejson as json
from ..globals import BMapType
from .global_options import TooltipOpts
from .series_options import (
BasicOpts,
ItemStyleOpts,
JSFunc,
LabelOpts,
LineStyleOpts,
Numeric,
Optional,
Sequence,
TextStyleOpts,
Union,
AreaStyleOpts,
)
# Chart Options
cl... |
23,070 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/render/display.py | 10,11 | 6,17 | _repr_html_ | HTML | 11,13 | 11,13 | class HTML:
def __init__(self, data: Optional[str] = None):
self.data = data
def _repr_html_(self):
FILL_FUNC_BODY def __html__(self):
return self._repr_html_()
| class HTML:
def __init__(self, data: Optional[str] = None):
self.data = data
def _repr_html_(self):
FILL_FUNC_BODY def __html__(self):
return self._repr_html_()
| return self.data
| return self.data
| 2 | 71 | 9 | 80 | from ..types import Optional, Sequence, Union
from urllib.parse import urlparse
import http.client
class HTML:
def __init__(self, data: Optional[str] = None):
self.data = data
def _repr_html_(self):
FILL_FUNC_BODY def __html__(self):
return self._repr_html_()
_lib_t1 = """new Promise(fun... | from ..types import Optional, Sequence, Union
from urllib.parse import urlparse
import http.client
class HTML:
def __init__(self, data: Optional[str] = None):
self.data = data
def _repr_html_(self):
FILL_FUNC_BODY def __html__(self):
return self._repr_html_()
_lib_t1 = """new Promise(fun... |
23,071 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/render/display.py | 67,68 | 37,87 | load_javascript_contents | Javascript | 68,87 | 68,87 | class Javascript:
def __init__(
self,
data: Optional[str] = None,
lib: Optional[Union[str, Sequence]] = None,
css: Optional[Union[str, Sequence]] = None,
):
if isinstance(lib, str):
lib = [lib]
elif lib is None:
lib = []
if isinstan... | class Javascript:
def __init__(
self,
data: Optional[str] = None,
lib: Optional[Union[str, Sequence]] = None,
css: Optional[Union[str, Sequence]] = None,
):
if isinstance(lib, str):
lib = [lib]
elif lib is None:
lib = []
if isinstan... | for lib in self.lib:
parsed_url = urlparse(lib)
host: str = str(parsed_url.hostname)
port: int = parsed_url.port
path: str = parsed_url.path
resp: Optional[http.client.HTTPResponse] = None
try:
conn = http.client.HTTPSConn... | for lib in self.lib:
parsed_url = urlparse(lib)
host: str = str(parsed_url.hostname)
port: int = parsed_url.port
path: str = parsed_url.path
resp: Optional[http.client.HTTPResponse] = None
try:
conn = http.client.HTTPSConn... | 57 | 261 | 206 | 467 | from ..types import Optional, Sequence, Union
from urllib.parse import urlparse
import http.client
class HTML:
def __init__(self, data: Optional[str] = None):
self.data = data
def _repr_html_(self):
return self.data
def __html__(self):
return self._repr_html_()
_lib_t1 = """new... | from ..types import Optional, Sequence, Union
from urllib.parse import urlparse
import http.client
class HTML:
def __init__(self, data: Optional[str] = None):
self.data = data
def _repr_html_(self):
return self.data
def __html__(self):
return self._repr_html_()
_lib_t1 = """new... |
23,072 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/render/engine.py | 89,90 | 1,122 | render_notebook | 90,116 | 90,116 | import os
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
from jinja2 import Environment
from ..commons import utils
from ..datasets import EXTRA, FILENAMES
from ..globals import CurrentConfig, NotebookType
from ..types import Any, Optional
from .display import ... | import os
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
from jinja2 import Environment
from ..commons import utils
from ..datasets import EXTRA, FILENAMES
from ..globals import CurrentConfig, NotebookType
from ..types import Any, Optional
from .display import ... | instance = self if isinstance(self, Iterable) else (self,)
if CurrentConfig.NOTEBOOK_TYPE == NotebookType.JUPYTER_NOTEBOOK:
require_config = utils.produce_require_dict(self.js_dependencies, self.js_host)
return HTML(
RenderEngine().render_chart_to_notebook(
template_n... | instance = self if isinstance(self, Iterable) else (self,)
if CurrentConfig.NOTEBOOK_TYPE == NotebookType.JUPYTER_NOTEBOOK:
require_config = utils.produce_require_dict(self.js_dependencies, self.js_host)
return HTML(
RenderEngine().render_chart_to_notebook(
template_n... | 50 | 977 | 299 | 1,276 | import os
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
from jinja2 import Environment
from ..commons import utils
from ..datasets import EXTRA, FILENAMES
from ..globals import CurrentConfig, NotebookType
from ..types import Any, Optional
from .display import ... | import os
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
from jinja2 import Environment
from ..commons import utils
from ..datasets import EXTRA, FILENAMES
from ..globals import CurrentConfig, NotebookType
from ..types import Any, Optional
from .display import ... | |
23,073 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/render/engine.py | 26,28 | 22,72 | generate_js_link | RenderEngine | 28,47 | 28,47 | class RenderEngine:
def __init__(self, env: Optional[Environment] = None):
self.env = env or CurrentConfig.GLOBAL_ENV
@staticmethod
def generate_js_link(chart: Any) -> Any:
FILL_FUNC_BODY def render_chart_to_file(self, template_name: str, chart: Any, path: str, **kwargs):
"""
Ren... | class RenderEngine:
def __init__(self, env: Optional[Environment] = None):
self.env = env or CurrentConfig.GLOBAL_ENV
@staticmethod
def generate_js_link(chart: Any) -> Any:
FILL_FUNC_BODY def render_chart_to_file(self, template_name: str, chart: Any, path: str, **kwargs):
"""
Ren... | if not chart.js_host:
chart.js_host = CurrentConfig.ONLINE_HOST
links = []
for dep in chart.js_dependencies.items:
# TODO: if?
if dep.startswith("https://api.map.baidu.com"):
links.append(dep)
if dep in FILENAMES:
f,... | if not chart.js_host:
chart.js_host = CurrentConfig.ONLINE_HOST
links = []
for dep in chart.js_dependencies.items:
# TODO: if?
if dep.startswith("https://api.map.baidu.com"):
links.append(dep)
if dep in FILENAMES:
f,... | 53 | 381 | 214 | 595 | import os
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
from jinja2 import Environment
from ..commons import utils
from ..datasets import EXTRA, FILENAMES
from ..globals import CurrentConfig, NotebookType
from ..types import Any, Optional
from .display import ... | import os
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
from jinja2 import Environment
from ..commons import utils
from ..datasets import EXTRA, FILENAMES
from ..globals import CurrentConfig, NotebookType
from ..types import Any, Optional
from .display import ... |
23,074 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/pyecharts/render/snapshot.py | 20,29 | 1,100 | make_snapshot | 29,64 | 29,64 | import base64
import codecs
import logging
import os
from io import BytesIO
from ..types import Any
logger = logging.getLogger(__name__)
PNG_FORMAT = "png"
JPG_FORMAT = "jpeg"
GIF_FORMAT = "gif"
PDF_FORMAT = "pdf"
SVG_FORMAT = "svg"
EPS_FORMAT = "eps"
B64_FORMAT = "base64"
def make_snapshot(
engine: Any,
f... | import base64
import codecs
import logging
import os
from io import BytesIO
from ..types import Any
logger = logging.getLogger(__name__)
PNG_FORMAT = "png"
JPG_FORMAT = "jpeg"
GIF_FORMAT = "gif"
PDF_FORMAT = "pdf"
SVG_FORMAT = "svg"
EPS_FORMAT = "eps"
B64_FORMAT = "base64"
def make_snapshot(
engine: Any,
f... | logger.info("Generating file ...")
file_type = output_name.split(".")[-1]
content = engine.make_snapshot(
html_path=file_name,
file_type=file_type,
delay=delay,
pixel_ratio=pixel_ratio,
**kwargs,
)
if file_type in [SVG_FORMAT, B64_FORMAT]:
save_as_tex... | logger.info("Generating file ...")
file_type = output_name.split(".")[-1]
content = engine.make_snapshot(
html_path=file_name,
file_type=file_type,
delay=delay,
pixel_ratio=pixel_ratio,
**kwargs,
)
if file_type in [SVG_FORMAT, B64_FORMAT]:
save_as_tex... | 82 | 584 | 408 | 992 | import base64
import codecs
import logging
import os
from io import BytesIO
from ..types import Any
logger = logging.getLogger(__name__)
PNG_FORMAT = "png"
JPG_FORMAT = "jpeg"
GIF_FORMAT = "gif"
PDF_FORMAT = "pdf"
SVG_FORMAT = "svg"
EPS_FORMAT = "eps"
B64_FORMAT = "base64"
def make_snapshot(
engine: Any,
f... | import base64
import codecs
import logging
import os
from io import BytesIO
from ..types import Any
logger = logging.getLogger(__name__)
PNG_FORMAT = "png"
JPG_FORMAT = "jpeg"
GIF_FORMAT = "gif"
PDF_FORMAT = "pdf"
SVG_FORMAT = "svg"
EPS_FORMAT = "eps"
B64_FORMAT = "base64"
def make_snapshot(
engine: Any,
f... | |
23,075 | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts | /home/hieuvd/dung_repo/raw/stars_01/pyecharts_pyecharts/pyecharts/setup.py | 50,51 | 36,72 | run | UploadCommand | 51,72 | 51,72 | class UploadCommand(Command):
description = "Build and publish the package."
user_options = []
@staticmethod
def status(s):
print("✨✨ {0}".format(s))
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
FILL_FUNC_BODY | class UploadCommand(Command):
description = "Build and publish the package."
user_options = []
@staticmethod
def status(s):
print("✨✨ {0}".format(s))
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
FILL_FUNC_BODY | try:
self.status("Removing previous builds…")
rmtree(os.path.join(here, "dist"))
rmtree(os.path.join(here, "build"))
rmtree(os.path.join(here, "{0}.egg-info".format(__title__)))
except OSError:
pass
self.status("Building Source and Whe... | try:
self.status("Removing previous builds…")
rmtree(os.path.join(here, "dist"))
rmtree(os.path.join(here, "build"))
rmtree(os.path.join(here, "{0}.egg-info".format(__title__)))
except OSError:
pass
self.status("Building Source and Whe... | 48 | 102 | 251 | 353 | import os
import sys
from shutil import rmtree
from setuptools import Command, find_packages, setup
# RELEASE STEPS
# $ python setup.py upload
__title__ = "pyecharts"
__description__ = "Python options, make charting easier"
__url__ = "https://github.com/pyecharts/pyecharts"
__author_email__ = "chenjiandongx@qq.com"... | import os
import sys
from shutil import rmtree
from setuptools import Command, find_packages, setup
# RELEASE STEPS
# $ python setup.py upload
__title__ = "pyecharts"
__description__ = "Python options, make charting easier"
__url__ = "https://github.com/pyecharts/pyecharts"
__author_email__ = "chenjiandongx@qq.com"... |
23,167 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/benchmark/benchmarks/numpy_benchmarks/cronbach.py | 7,8 | 1,12 | cronbach | 8,12 | 8,12 | # http://stackoverflow.com/questions/20799403/improving-performance-of-cronbach-alpha-code-python-numpy
# pythran export cronbach(float [][])
# setup: import numpy as np ; N = 600 ; items = np.random.rand(N,N)
# run: cronbach(items)
def cronbach(itemscores):
FILL_FUNC_BODY | # http://stackoverflow.com/questions/20799403/improving-performance-of-cronbach-alpha-code-python-numpy
# pythran export cronbach(float [][])
# setup: import numpy as np ; N = 600 ; items = np.random.rand(N,N)
# run: cronbach(items)
def cronbach(itemscores):
FILL_FUNC_BODY | itemvars = itemscores.var(axis=1, ddof=1)
tscores = itemscores.sum(axis=0)
nitems = len(itemscores)
return nitems / (nitems - 1) * (1 - itemvars.sum() / tscores.var(ddof=1))
| itemvars = itemscores.var(axis=1, ddof=1)
tscores = itemscores.sum(axis=0)
nitems = len(itemscores)
return nitems / (nitems - 1) * (1 - itemvars.sum() / tscores.var(ddof=1))
| 22 | 112 | 86 | 198 | # http://stackoverflow.com/questions/20799403/improving-performance-of-cronbach-alpha-code-python-numpy
# pythran export cronbach(float [][])
# setup: import numpy as np ; N = 600 ; items = np.random.rand(N,N)
# run: cronbach(items)
def cronbach(itemscores):
FILL_FUNC_BODY | # http://stackoverflow.com/questions/20799403/improving-performance-of-cronbach-alpha-code-python-numpy
# pythran export cronbach(float [][])
# setup: import numpy as np ; N = 600 ; items = np.random.rand(N,N)
# run: cronbach(items)
def cronbach(itemscores):
FILL_FUNC_BODY | |
23,168 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/benchmark/benchmarks/numpy_benchmarks/diffusion.py | 7,8 | 1,24 | diffusion | 11,24 | 8,24 | # setup: import numpy as np;lx,ly=(2**6,2**6);u=np.zeros([lx,ly],dtype=np.double);u[lx//2,ly//2]=1000.0;tempU=np.zeros([lx,ly],dtype=np.double)
# run: diffusion(u,tempU,100)
# pythran export diffusion(float [][], float [][], int)
def diffusion(u, tempU, iterNum):
FILL_FUNC_BODY | # setup: import numpy as np;lx,ly=(2**6,2**6);u=np.zeros([lx,ly],dtype=np.double);u[lx//2,ly//2]=1000.0;tempU=np.zeros([lx,ly],dtype=np.double)
# run: diffusion(u,tempU,100)
# pythran export diffusion(float [][], float [][], int)
def diffusion(u, tempU, iterNum):
"""
Apply Numpy matrix for the Forward-Euler ... | mu = 0.1
for _ in range(iterNum):
tempU[1:-1, 1:-1] = u[1:-1, 1:-1] + mu * (
u[2:, 1:-1]
- 2 * u[1:-1, 1:-1]
+ u[0:-2, 1:-1]
+ u[1:-1, 2:]
- 2 * u[1:-1, 1:-1]
+ u[1:-1, 0:-2]
)
u[:, :] = tempU[:, :]
tempU[:,... | """
Apply Numpy matrix for the Forward-Euler Approximation
"""
mu = 0.1
for _ in range(iterNum):
tempU[1:-1, 1:-1] = u[1:-1, 1:-1] + mu * (
u[2:, 1:-1]
- 2 * u[1:-1, 1:-1]
+ u[0:-2, 1:-1]
+ u[1:-1, 2:]
- 2 * u[1:-1, 1:-1]
... | 47 | 163 | 176 | 339 | # setup: import numpy as np;lx,ly=(2**6,2**6);u=np.zeros([lx,ly],dtype=np.double);u[lx//2,ly//2]=1000.0;tempU=np.zeros([lx,ly],dtype=np.double)
# run: diffusion(u,tempU,100)
# pythran export diffusion(float [][], float [][], int)
def diffusion(u, tempU, iterNum):
FILL_FUNC_BODY | # setup: import numpy as np;lx,ly=(2**6,2**6);u=np.zeros([lx,ly],dtype=np.double);u[lx//2,ly//2]=1000.0;tempU=np.zeros([lx,ly],dtype=np.double)
# run: diffusion(u,tempU,100)
# pythran export diffusion(float [][], float [][], int)
def diffusion(u, tempU, iterNum):
"""
Apply Numpy matrix for the Forward-Euler ... | |
23,169 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/benchmark/benchmarks/numpy_benchmarks/growcut.py | 23,24 | 1,61 | growcut | 24,61 | 24,61 | # from: http://continuum.io/blog/numba_performance
# setup: N = 10 ; import numpy as np ; image = np.random.rand(N, N, 3) ; state = np.zeros((N, N, 2)) ; state_next = np.empty_like(state) ; state[0, 0, 0] = state[0, 0, 1] = 1
# run: growcut(image, state, state_next, 2)
# pythran export growcut(float[][][], float[][][]... | # from: http://continuum.io/blog/numba_performance
# setup: N = 10 ; import numpy as np ; image = np.random.rand(N, N, 3) ; state = np.zeros((N, N, 2)) ; state_next = np.empty_like(state) ; state[0, 0, 0] = state[0, 0, 1] = 1
# run: growcut(image, state, state_next, 2)
# pythran export growcut(float[][][], float[][][]... | changes = 0
sqrt_3 = math.sqrt(3.0)
height = image.shape[0]
width = image.shape[1]
for j in range(width):
for i in range(height):
winning_colony = state[i, j, 0]
defense_strength = state[i, j, 1]
for jj in range(
window_floor(j, window_r... | changes = 0
sqrt_3 = math.sqrt(3.0)
height = image.shape[0]
width = image.shape[1]
for j in range(width):
for i in range(height):
winning_colony = state[i, j, 0]
defense_strength = state[i, j, 1]
for jj in range(
window_floor(j, window_r... | 136 | 250 | 423 | 673 | # from: http://continuum.io/blog/numba_performance
# setup: N = 10 ; import numpy as np ; image = np.random.rand(N, N, 3) ; state = np.zeros((N, N, 2)) ; state_next = np.empty_like(state) ; state[0, 0, 0] = state[0, 0, 1] = 1
# run: growcut(image, state, state_next, 2)
# pythran export growcut(float[][][], float[][][]... | # from: http://continuum.io/blog/numba_performance
# setup: N = 10 ; import numpy as np ; image = np.random.rand(N, N, 3) ; state = np.zeros((N, N, 2)) ; state_next = np.empty_like(state) ; state[0, 0, 0] = state[0, 0, 1] = 1
# run: growcut(image, state, state_next, 2)
# pythran export growcut(float[][][], float[][][]... | |
23,170 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/benchmark/benchmarks/numpy_benchmarks/harris.py | 8,9 | 1,30 | harris | 9,30 | 9,30 | # from: parakeet testbed
# setup: import numpy as np ; M, N = 512, 512 ; X = np.random.randn(M,N)
# run: harris(X)
# pythran export harris(float64[][])
def harris(X):
FILL_FUNC_BODY | # from: parakeet testbed
# setup: import numpy as np ; M, N = 512, 512 ; X = np.random.randn(M,N)
# run: harris(X)
# pythran export harris(float64[][])
def harris(X):
FILL_FUNC_BODY | m, n = X.shape
dx = (X[1:, :] - X[: m - 1, :])[:, 1:]
dy = (X[:, 1:] - X[:, : n - 1])[1:, :]
#
# At each point we build a matrix
# of derivative products
# M =
# | A = dx^2 C = dx * dy |
# | C = dy * dx B = dy * dy |
#
# and the score at that point is:
#... | m, n = X.shape
dx = (X[1:, :] - X[: m - 1, :])[:, 1:]
dy = (X[:, 1:] - X[:, : n - 1])[1:, :]
#
# At each point we build a matrix
# of derivative products
# M =
# | A = dx^2 C = dx * dy |
# | C = dy * dx B = dy * dy |
#
# and the score at that point is:
#... | 120 | 89 | 236 | 325 | # from: parakeet testbed
# setup: import numpy as np ; M, N = 512, 512 ; X = np.random.randn(M,N)
# run: harris(X)
# pythran export harris(float64[][])
def harris(X):
FILL_FUNC_BODY | # from: parakeet testbed
# setup: import numpy as np ; M, N = 512, 512 ; X = np.random.randn(M,N)
# run: harris(X)
# pythran export harris(float64[][])
def harris(X):
FILL_FUNC_BODY | |
23,171 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/benchmark/benchmarks/numpy_benchmarks/large_decimal_list.py | 5,6 | 1,7 | large_decimal_list | 6,7 | 6,7 | # setup: from decimal import Decimal ; A = [Decimal('2.1') for i in range(1000)] ; B = [Decimal('3.2') for i in range(1000)]
# run: large_decimal_list(A, B)
def large_decimal_list(A, B):
FILL_FUNC_BODY | # setup: from decimal import Decimal ; A = [Decimal('2.1') for i in range(1000)] ; B = [Decimal('3.2') for i in range(1000)]
# run: large_decimal_list(A, B)
def large_decimal_list(A, B):
FILL_FUNC_BODY | return [a * b for a, b in zip(A, B, strict=True)]
| return [a * b for a, b in zip(A, B, strict=True)]
| 11 | 91 | 23 | 114 | # setup: from decimal import Decimal ; A = [Decimal('2.1') for i in range(1000)] ; B = [Decimal('3.2') for i in range(1000)]
# run: large_decimal_list(A, B)
def large_decimal_list(A, B):
FILL_FUNC_BODY | # setup: from decimal import Decimal ; A = [Decimal('2.1') for i in range(1000)] ; B = [Decimal('3.2') for i in range(1000)]
# run: large_decimal_list(A, B)
def large_decimal_list(A, B):
FILL_FUNC_BODY | |
23,172 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/benchmark/benchmarks/numpy_benchmarks/mandel.py | 7,8 | 1,36 | kernel | 13,23 | 8,23 | # setup: import numpy as np; image = np.zeros((64, 32), dtype = np.uint8)
# run: mandel(-2.0, 1.0, -1.0, 1.0, image, 20)
# pythran export mandel(float, float, float, float, uint8[][], int)
def kernel(x, y, max_iters):
FILL_FUNC_BODYdef mandel(min_x, max_x, min_y, max_y, image, iters):
height = image.shape[0]
... | # setup: import numpy as np; image = np.zeros((64, 32), dtype = np.uint8)
# run: mandel(-2.0, 1.0, -1.0, 1.0, image, 20)
# pythran export mandel(float, float, float, float, uint8[][], int)
def kernel(x, y, max_iters):
"""
Given the real and imaginary parts of a complex number,
determine if it is a candid... | c = complex(x, y)
z = 0.0j
for i in range(max_iters):
z = z * z + c
if (z.real * z.real + z.imag * z.imag) >= 4:
return i
return max_iters
| """
Given the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations.
"""
c = complex(x, y)
z = 0.0j
for i in range(max_iters):
z = z * z + c
if (z.real * z.real + z.imag * z.ima... | 32 | 316 | 86 | 402 | # setup: import numpy as np; image = np.zeros((64, 32), dtype = np.uint8)
# run: mandel(-2.0, 1.0, -1.0, 1.0, image, 20)
# pythran export mandel(float, float, float, float, uint8[][], int)
def kernel(x, y, max_iters):
FILL_FUNC_BODYdef mandel(min_x, max_x, min_y, max_y, image, iters):
height = image.shape[0]
... | # setup: import numpy as np; image = np.zeros((64, 32), dtype = np.uint8)
# run: mandel(-2.0, 1.0, -1.0, 1.0, image, 20)
# pythran export mandel(float, float, float, float, uint8[][], int)
def kernel(x, y, max_iters):
"""
Given the real and imaginary parts of a complex number,
determine if it is a candid... | |
23,173 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/benchmark/benchmarks/numpy_benchmarks/smoothing.py | 8,9 | 1,19 | smoothing | 15,19 | 9,19 | # setup: import numpy as np ; N = 1000 ; a = np.arange(0,1,N)
# run: smoothing(a, .4)
# from: http://www.parakeetpython.com/
# pythran export smoothing(float[], float)
def smoothing(x, alpha):
FILL_FUNC_BODY | # setup: import numpy as np ; N = 1000 ; a = np.arange(0,1,N)
# run: smoothing(a, .4)
# from: http://www.parakeetpython.com/
# pythran export smoothing(float[], float)
def smoothing(x, alpha):
"""
Exponential smoothing of a time series
For x = 10**6 floats
- Python runtime: 9 seconds
- Parakeet r... | s = x.copy()
for i in range(1, len(x)):
s[i] = alpha * x[i] + (1 - alpha) * s[i - 1]
return s
| """
Exponential smoothing of a time series
For x = 10**6 floats
- Python runtime: 9 seconds
- Parakeet runtime: .01 seconds
"""
s = x.copy()
for i in range(1, len(x)):
s[i] = alpha * x[i] + (1 - alpha) * s[i - 1]
return s
| 23 | 141 | 57 | 198 | # setup: import numpy as np ; N = 1000 ; a = np.arange(0,1,N)
# run: smoothing(a, .4)
# from: http://www.parakeetpython.com/
# pythran export smoothing(float[], float)
def smoothing(x, alpha):
FILL_FUNC_BODY | # setup: import numpy as np ; N = 1000 ; a = np.arange(0,1,N)
# run: smoothing(a, .4)
# from: http://www.parakeetpython.com/
# pythran export smoothing(float[], float)
def smoothing(x, alpha):
"""
Exponential smoothing of a time series
For x = 10**6 floats
- Python runtime: 9 seconds
- Parakeet r... | |
23,174 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/benchmark/benchmarks/numpy_benchmarks/specialconvolve.py | 7,8 | 1,14 | specialconvolve | 8,14 | 8,14 | # from: http://stackoverflow.com/questions/2196693/improving-numpy-performance
# pythran export specialconvolve(uint32 [][])
# setup: import numpy as np ; r = np.arange(100*10000, dtype=np.uint32).reshape(1000,1000)
# run: specialconvolve(r)
def specialconvolve(a):
FILL_FUNC_BODY | # from: http://stackoverflow.com/questions/2196693/improving-numpy-performance
# pythran export specialconvolve(uint32 [][])
# setup: import numpy as np ; r = np.arange(100*10000, dtype=np.uint32).reshape(1000,1000)
# run: specialconvolve(r)
def specialconvolve(a):
FILL_FUNC_BODY | # sorry, you must pad the input yourself
rowconvol = a[1:-1, :] + a[:-2, :] + a[2:, :]
colconvol = (
rowconvol[:, 1:-1] + rowconvol[:, :-2] + rowconvol[:, 2:] - 9 * a[1:-1, 1:-1]
)
return colconvol
| # sorry, you must pad the input yourself
rowconvol = a[1:-1, :] + a[:-2, :] + a[2:, :]
colconvol = (
rowconvol[:, 1:-1] + rowconvol[:, :-2] + rowconvol[:, 2:] - 9 * a[1:-1, 1:-1]
)
return colconvol
| 37 | 128 | 109 | 237 | # from: http://stackoverflow.com/questions/2196693/improving-numpy-performance
# pythran export specialconvolve(uint32 [][])
# setup: import numpy as np ; r = np.arange(100*10000, dtype=np.uint32).reshape(1000,1000)
# run: specialconvolve(r)
def specialconvolve(a):
FILL_FUNC_BODY | # from: http://stackoverflow.com/questions/2196693/improving-numpy-performance
# pythran export specialconvolve(uint32 [][])
# setup: import numpy as np ; r = np.arange(100*10000, dtype=np.uint32).reshape(1000,1000)
# run: specialconvolve(r)
def specialconvolve(a):
FILL_FUNC_BODY | |
23,175 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/benchmark/benchmarks/pandas_benchmarks/join_df.py | 5,6 | 1,7 | join_df | 6,7 | 6,7 | # setup: import pandas as pd ; import numpy ; N = 1000000 ; df1 = pd.DataFrame(numpy.random.randint(0, 10, size=(N, 3)), columns=["col1", "col2", "col3"]) ; df2 = pd.DataFrame(numpy.random.randint(0, 10, size=(N, 3)), columns=["col4", "col5", "col6"]) # noqa: E501
# run: join_df(df1, df2)
def join_df(df1, df2):
FILL... | # setup: import pandas as pd ; import numpy ; N = 1000000 ; df1 = pd.DataFrame(numpy.random.randint(0, 10, size=(N, 3)), columns=["col1", "col2", "col3"]) ; df2 = pd.DataFrame(numpy.random.randint(0, 10, size=(N, 3)), columns=["col4", "col5", "col6"]) # noqa: E501
# run: join_df(df1, df2)
def join_df(df1, df2):
FILL... | return df1.join(df2, how="outer")
| return df1.join(df2, how="outer")
| 3 | 168 | 17 | 185 | # setup: import pandas as pd ; import numpy ; N = 1000000 ; df1 = pd.DataFrame(numpy.random.randint(0, 10, size=(N, 3)), columns=["col1", "col2", "col3"]) ; df2 = pd.DataFrame(numpy.random.randint(0, 10, size=(N, 3)), columns=["col4", "col5", "col6"]) # noqa: E501
# run: join_df(df1, df2)
def join_df(df1, df2):
FILL... | # setup: import pandas as pd ; import numpy ; N = 1000000 ; df1 = pd.DataFrame(numpy.random.randint(0, 10, size=(N, 3)), columns=["col1", "col2", "col3"]) ; df2 = pd.DataFrame(numpy.random.randint(0, 10, size=(N, 3)), columns=["col4", "col5", "col6"]) # noqa: E501
# run: join_df(df1, df2)
def join_df(df1, df2):
FILL... | |
23,176 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/benchmark/stack_usage.py | 30,33 | 1,88 | test_stack_usage | 33,88 | 33,88 | import pytest
@pytest.fixture(scope="session")
def print_info():
headings = [
"browser",
"py_limit",
"py_usage",
"js_depth",
"py_depth",
"js_depth/py_usage",
"js_depth/py_depth",
]
fmt = "## {{:{:d}s}} {{:{:d}g}} {{:{:d}.2f}} {{:{:d}g}} {{:{:d}g}... | import pytest
@pytest.fixture(scope="session")
def print_info():
headings = [
"browser",
"py_limit",
"py_usage",
"js_depth",
"py_depth",
"js_depth/py_usage",
"js_depth/py_depth",
]
fmt = "## {{:{:d}s}} {{:{:d}g}} {{:{:d}.2f}} {{:{:d}g}} {{:{:d}g}... | res = selenium.run_js(
"""
self.measure_available_js_stack_depth = () => {
let depth = 0;
function recurse() { depth += 1; recurse(); }
try { recurse(); } catch (err) { }
return depth;
};
let py_limit = pyodide.runPython("import sys; sy... | res = selenium.run_js(
"""
self.measure_available_js_stack_depth = () => {
let depth = 0;
function recurse() { depth += 1; recurse(); }
try { recurse(); } catch (err) { }
return depth;
};
let py_limit = pyodide.runPython("import sys; sy... | 135 | 300 | 591 | 891 | import pytest
@pytest.fixture(scope="session")
def print_info():
headings = [
"browser",
"py_limit",
"py_usage",
"js_depth",
"py_depth",
"js_depth/py_usage",
"js_depth/py_depth",
]
fmt = "## {{:{:d}s}} {{:{:d}g}} {{:{:d}.2f}} {{:{:d}g}} {{:{:d}g}... | import pytest
@pytest.fixture(scope="session")
def print_info():
headings = [
"browser",
"py_limit",
"py_usage",
"js_depth",
"py_depth",
"js_depth/py_usage",
"js_depth/py_depth",
]
fmt = "## {{:{:d}s}} {{:{:d}g}} {{:{:d}.2f}} {{:{:d}g}} {{:{:d}g}... | |
23,177 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/cpython/adjust_sysconfig.py | 13,14 | 1,79 | write_sysconfig | 14,41 | 14,41 | import os
from textwrap import dedent
PYODIDE_ROOT = os.environ["PYODIDE_ROOT"]
def load_sysconfig(sysconfig_name: str):
_temp = __import__(sysconfig_name, globals(), locals(), ["build_time_vars"], 0)
config_vars = _temp.build_time_vars
return config_vars, _temp.__file__
def write_sysconfig(destfile: s... | import os
from textwrap import dedent
PYODIDE_ROOT = os.environ["PYODIDE_ROOT"]
def load_sysconfig(sysconfig_name: str):
_temp = __import__(sysconfig_name, globals(), locals(), ["build_time_vars"], 0)
config_vars = _temp.build_time_vars
return config_vars, _temp.__file__
def write_sysconfig(destfile: s... | with open(destfile, "w", encoding="utf8") as f:
f.write("# system configuration generated and used by the sysconfig module\n")
# Set PYODIDE_ROOT
f.write("import os\n")
f.write(f'PYODIDE_ROOT = os.environ.get("PYODIDE_ROOT", "{PYODIDE_ROOT}")\n')
f.write("build_time_vars = ")... | with open(destfile, "w", encoding="utf8") as f:
f.write("# system configuration generated and used by the sysconfig module\n")
# Set PYODIDE_ROOT
f.write("import os\n")
f.write(f'PYODIDE_ROOT = os.environ.get("PYODIDE_ROOT", "{PYODIDE_ROOT}")\n')
f.write("build_time_vars = ")... | 117 | 632 | 349 | 981 | import os
from textwrap import dedent
PYODIDE_ROOT = os.environ["PYODIDE_ROOT"]
def load_sysconfig(sysconfig_name: str):
_temp = __import__(sysconfig_name, globals(), locals(), ["build_time_vars"], 0)
config_vars = _temp.build_time_vars
return config_vars, _temp.__file__
def write_sysconfig(destfile: s... | import os
from textwrap import dedent
PYODIDE_ROOT = os.environ["PYODIDE_ROOT"]
def load_sysconfig(sysconfig_name: str):
_temp = __import__(sysconfig_name, globals(), locals(), ["build_time_vars"], 0)
config_vars = _temp.build_time_vars
return config_vars, _temp.__file__
def write_sysconfig(destfile: s... | |
23,179 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/docs/sphinx_pyodide/sphinx_pyodide/util.py | 20,21 | 1,56 | docs_argspec | 28,56 | 21,56 | from functools import update_wrapper
from textwrap import dedent
from typing import Any
def delete_attrs(cls):
"""Prevent attributes of a class or module from being documented.
The top level documentation comment of the class or module will still be
rendered.
"""
for name in dir(cls):
if ... | from functools import update_wrapper
from textwrap import dedent
from typing import Any
def delete_attrs(cls):
"""Prevent attributes of a class or module from being documented.
The top level documentation comment of the class or module will still be
rendered.
"""
for name in dir(cls):
if ... |
def dec(func):
d = func.__globals__
TEMP_NAME = "_xxxffff___"
assert TEMP_NAME not in d
code = dedent(
f"""\
def {TEMP_NAME}{argspec}:
pass
"""
)
# exec in func.__globals__ context so that type hints don't case Name... | """Decorator to override the argument spec of the function that is
rendered in the docs.
If the documentation finds a __wrapped__ attribute, it will use that to
render the argspec instead of the function itself. Assign an appropriate
fake function to __wrapped__ with the desired argspec.
"""
... | 83 | 218 | 248 | 466 | from functools import update_wrapper
from textwrap import dedent
from typing import Any
def delete_attrs(cls):
"""Prevent attributes of a class or module from being documented.
The top level documentation comment of the class or module will still be
rendered.
"""
for name in dir(cls):
if ... | from functools import update_wrapper
from textwrap import dedent
from typing import Any
def delete_attrs(cls):
"""Prevent attributes of a class or module from being documented.
The top level documentation comment of the class or module will still be
rendered.
"""
for name in dir(cls):
if ... | |
23,180 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/packages/Jinja2/test_jinja2.py | 4,6 | 1,11 | test_jinja2 | 6,11 | 6,11 | from pytest_pyodide import run_in_pyodide
@run_in_pyodide(packages=["Jinja2"])
def test_jinja2(selenium):
FILL_FUNC_BODY | from pytest_pyodide import run_in_pyodide
@run_in_pyodide(packages=["Jinja2"])
def test_jinja2(selenium):
FILL_FUNC_BODY | import jinja2
template = jinja2.Template("Hello {{ name }}!")
content = template.render(name="Zach")
assert content == "Hello Zach!"
| import jinja2
template = jinja2.Template("Hello {{ name }}!")
content = template.render(name="Zach")
assert content == "Hello Zach!"
| 16 | 60 | 54 | 114 | from pytest_pyodide import run_in_pyodide
@run_in_pyodide(packages=["Jinja2"])
def test_jinja2(selenium):
FILL_FUNC_BODY | from pytest_pyodide import run_in_pyodide
@run_in_pyodide(packages=["Jinja2"])
def test_jinja2(selenium):
FILL_FUNC_BODY | |
23,181 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/packages/b2d/test_pyb2d.py | 4,6 | 1,16 | test_pyb2d | 6,16 | 6,16 | import pytest
@pytest.mark.driver_timeout(40)
def test_pyb2d(selenium_standalone, request):
FILL_FUNC_BODY | import pytest
@pytest.mark.driver_timeout(40)
def test_pyb2d(selenium_standalone, request):
FILL_FUNC_BODY | selenium = selenium_standalone
selenium.load_package("b2d")
selenium.run(
"""
import numpy as np
import b2d
w = b2d.world(gravity=(0,-10))
"""
)
| selenium = selenium_standalone
selenium.load_package("b2d")
selenium.run(
"""
import numpy as np
import b2d
w = b2d.world(gravity=(0,-10))
"""
)
| 17 | 48 | 86 | 134 | import pytest
@pytest.mark.driver_timeout(40)
def test_pyb2d(selenium_standalone, request):
FILL_FUNC_BODY | import pytest
@pytest.mark.driver_timeout(40)
def test_pyb2d(selenium_standalone, request):
FILL_FUNC_BODY | |
23,182 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/packages/idna/test_idna.py | 4,6 | 1,9 | test_idna | 6,9 | 6,9 | from pytest_pyodide import run_in_pyodide
@run_in_pyodide(packages=["idna"])
def test_idna(selenium_standalone):
FILL_FUNC_BODY | from pytest_pyodide import run_in_pyodide
@run_in_pyodide(packages=["idna"])
def test_idna(selenium_standalone):
FILL_FUNC_BODY | import idna
assert idna.encode("ドメイン.テスト") == b"xn--eckwd4c7c.xn--zckzah"
| import idna
assert idna.encode("ドメイン.テスト") == b"xn--eckwd4c7c.xn--zckzah"
| 6 | 59 | 55 | 114 | from pytest_pyodide import run_in_pyodide
@run_in_pyodide(packages=["idna"])
def test_idna(selenium_standalone):
FILL_FUNC_BODY | from pytest_pyodide import run_in_pyodide
@run_in_pyodide(packages=["idna"])
def test_idna(selenium_standalone):
FILL_FUNC_BODY | |
23,183 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/packages/joblib/test_joblib.py | 21,22 | 1,40 | test_joblib_parallel | 22,40 | 22,40 | def test_joblib_numpy_pickle(selenium, request):
selenium.load_package(["numpy", "joblib"])
selenium.run(
"""
import joblib
import numpy as np
from numpy.testing import assert_array_equal
X = np.ones(10)
file_path = "./X.pkl"
joblib.dump(X, file_path)
... | def test_joblib_numpy_pickle(selenium, request):
selenium.load_package(["numpy", "joblib"])
selenium.run(
"""
import joblib
import numpy as np
from numpy.testing import assert_array_equal
X = np.ones(10)
file_path = "./X.pkl"
joblib.dump(X, file_path)
... | selenium.load_package(["numpy", "joblib"])
selenium.clean_logs()
selenium.run(
"""
from math import sqrt
from joblib import Parallel, delayed
# check that the default multiprocessing backend
# gracefully reduces to n_jobs=1
res = Parallel(n_jobs=2)(delayed(sqrt)(i... | selenium.load_package(["numpy", "joblib"])
selenium.clean_logs()
selenium.run(
"""
from math import sqrt
from joblib import Parallel, delayed
# check that the default multiprocessing backend
# gracefully reduces to n_jobs=1
res = Parallel(n_jobs=2)(delayed(sqrt)(i... | 60 | 175 | 210 | 385 | def test_joblib_numpy_pickle(selenium, request):
selenium.load_package(["numpy", "joblib"])
selenium.run(
"""
import joblib
import numpy as np
from numpy.testing import assert_array_equal
X = np.ones(10)
file_path = "./X.pkl"
joblib.dump(X, file_path)
... | def test_joblib_numpy_pickle(selenium, request):
selenium.load_package(["numpy", "joblib"])
selenium.run(
"""
import joblib
import numpy as np
from numpy.testing import assert_array_equal
X = np.ones(10)
file_path = "./X.pkl"
joblib.dump(X, file_path)
... | |
23,184 | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide | /home/hieuvd/dung_repo/raw/stars_01/pyodide_pyodide/pyodide/packages/nltk/test_nltk.py | 11,12 | 1,31 | test_nltk_jaccard_distance | 12,22 | 12,22 | import pytest
def test_nltk_edit_distance(selenium):
selenium.load_package("nltk")
selenium.run("import nltk")
edit_distance = selenium.run("nltk.edit_distance('foo', 'food')")
assert edit_distance == 1
def test_nltk_jaccard_distance(selenium):
FILL_FUNC_BODYdef test_nltk_ngrams(selenium):
selen... | import pytest
def test_nltk_edit_distance(selenium):
selenium.load_package("nltk")
selenium.run("import nltk")
edit_distance = selenium.run("nltk.edit_distance('foo', 'food')")
assert edit_distance == 1
def test_nltk_jaccard_distance(selenium):
FILL_FUNC_BODYdef test_nltk_ngrams(selenium):
selen... | selenium.load_package("nltk")
selenium.run("import nltk")
jaccard_distance = selenium.run(
"""
nltk.jaccard_distance(set('mapping'), set('mappings'))
"""
)
assert jaccard_distance == pytest.approx(0.1428571)
| selenium.load_package("nltk")
selenium.run("import nltk")
jaccard_distance = selenium.run(
"""
nltk.jaccard_distance(set('mapping'), set('mappings'))
"""
)
assert jaccard_distance == pytest.approx(0.1428571)
| 15 | 272 | 107 | 379 | import pytest
def test_nltk_edit_distance(selenium):
selenium.load_package("nltk")
selenium.run("import nltk")
edit_distance = selenium.run("nltk.edit_distance('foo', 'food')")
assert edit_distance == 1
def test_nltk_jaccard_distance(selenium):
FILL_FUNC_BODYdef test_nltk_ngrams(selenium):
selen... | import pytest
def test_nltk_edit_distance(selenium):
selenium.load_package("nltk")
selenium.run("import nltk")
edit_distance = selenium.run("nltk.edit_distance('foo', 'food')")
assert edit_distance == 1
def test_nltk_jaccard_distance(selenium):
FILL_FUNC_BODYdef test_nltk_ngrams(selenium):
selen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.