edited_code stringlengths 17 978k | original_code stringlengths 17 978k |
|---|---|
"""
Copyright (c) 2020, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
import os
import sys
from http.server import HTTPServer, SimpleHTTPRequestHandler
from multiprocessing... | """
Copyright (c) 2020, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
import os
import sys
from http.server import HTTPServer, SimpleHTTPRequestHandler
from multiprocessing... |
import builtins
import datetime as dt
from io import StringIO
from string import ascii_lowercase
import numpy as np
import pytest
from pandas.errors import UnsupportedFunctionCall
import pandas as pd
from pandas import (
DataFrame,
Index,
MultiIndex,
NaT,
Series,
Timestamp,
_is_numpy_dev,... | import builtins
import datetime as dt
from io import StringIO
from string import ascii_lowercase
import numpy as np
import pytest
from pandas.errors import UnsupportedFunctionCall
import pandas as pd
from pandas import (
DataFrame,
Index,
MultiIndex,
NaT,
Series,
Timestamp,
_is_numpy_dev,... |
"""
Distributed under the terms of the BSD 3-Clause License.
The full license is in the file LICENSE, distributed with this software.
Author: Jun Zhu <jun.zhu@xfel.eu>
Copyright (C) European X-Ray Free-Electron Laser Facility GmbH.
All rights reserved.
"""
from collections import deque
import sys
import traceback
imp... | """
Distributed under the terms of the BSD 3-Clause License.
The full license is in the file LICENSE, distributed with this software.
Author: Jun Zhu <jun.zhu@xfel.eu>
Copyright (C) European X-Ray Free-Electron Laser Facility GmbH.
All rights reserved.
"""
from collections import deque
import sys
import traceback
imp... |
"""
OpenVINO DL Workbench
Class for ORM model described Jupyter notebook abstraction
Copyright (c) 2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apac... | """
OpenVINO DL Workbench
Class for ORM model described Jupyter notebook abstraction
Copyright (c) 2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apac... |
#AUTOGENERATED! DO NOT EDIT! File to edit: dev/15_callback.hook.ipynb (unless otherwise specified).
__all__ = ['Hook', 'hook_output', 'Hooks', 'hook_outputs', 'dummy_eval', 'model_sizes', 'num_features_model',
'has_params', 'HookCallback', 'total_params', 'layer_info', 'ActivationStats']
#Cell
from ..test ... | #AUTOGENERATED! DO NOT EDIT! File to edit: dev/15_callback.hook.ipynb (unless otherwise specified).
__all__ = ['Hook', 'hook_output', 'Hooks', 'hook_outputs', 'dummy_eval', 'model_sizes', 'num_features_model',
'has_params', 'HookCallback', 'total_params', 'layer_info', 'ActivationStats']
#Cell
from ..test ... |
import fasttext
import os
import pandas as pd
from dateutil import parser
from typing import Union
from bso.server.main.apc.apc_detect import detect_apc
from bso.server.main.config import MOUNTED_VOLUME
from bso.server.main.affiliation_matcher import get_matcher_parallel
from bso.server.main.field_detect import detec... | import fasttext
import os
import pandas as pd
from dateutil import parser
from typing import Union
from bso.server.main.apc.apc_detect import detect_apc
from bso.server.main.config import MOUNTED_VOLUME
from bso.server.main.affiliation_matcher import get_matcher_parallel
from bso.server.main.field_detect import detec... |
import sys
import stellargraph as sg
import matplotlib.pyplot as plt
from math import isclose
import sklearn
from sklearn.decomposition import PCA
import os
import networkx as nx
import numpy as np
import pandas as pd
from stellargraph import StellarGraph, datasets
from stellargraph.data import EdgeSplitter
from collec... | import sys
import stellargraph as sg
import matplotlib.pyplot as plt
from math import isclose
import sklearn
from sklearn.decomposition import PCA
import os
import networkx as nx
import numpy as np
import pandas as pd
from stellargraph import StellarGraph, datasets
from stellargraph.data import EdgeSplitter
from collec... |
# vim: sw=4:ts=4:et:cc=120
import datetime
import hashlib
import json
import logging
import os
import requests
import saq
from saq.analysis import Analysis
from saq.constants import *
from saq.modules.sandbox import *
from wildfirelib import parse
class WildfireAnalysis(Analysis):
def initialize_details(self):
... | # vim: sw=4:ts=4:et:cc=120
import datetime
import hashlib
import json
import logging
import os
import requests
import saq
from saq.analysis import Analysis
from saq.constants import *
from saq.modules.sandbox import *
from wildfirelib import parse
class WildfireAnalysis(Analysis):
def initialize_details(self):
... |
import argparse
import os
import logging
import sys
import itertools
from torchsummary import summary
import torch
from torch.utils.data import DataLoader, ConcatDataset
from torch.optim.lr_scheduler import CosineAnnealingLR, MultiStepLR
from vision.utils.misc import str2bool, Timer, freeze_net_layers, store_labels
fr... | import argparse
import os
import logging
import sys
import itertools
from torchsummary import summary
import torch
from torch.utils.data import DataLoader, ConcatDataset
from torch.optim.lr_scheduler import CosineAnnealingLR, MultiStepLR
from vision.utils.misc import str2bool, Timer, freeze_net_layers, store_labels
fr... |
import os
import selenium
import requests
from selenium import webdriver
from optparse import OptionParser
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.firefox.options import Options
from selenium.webdriver import ActionChains
impo... | import os
import selenium
import requests
from selenium import webdriver
from optparse import OptionParser
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.firefox.options import Options
from selenium.webdriver import ActionChains
impo... |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from collections import namedtuple
from io import BytesIO
from operator import attrgetter, itemgetter
fro... | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from collections import namedtuple
from io import BytesIO
from operator import attrgetter, itemgetter
fro... |
import cv2
import numpy as np
from . import ref_input
class Stimulus:
def __init__(self, param):
self.param = param
self.image = create_image(param['image'])
self.motion = self.get_motion_model(param['motion'])
self.vel = np.array([0.0, 0.0])
self.pos = np.array([0.0, 0.0]... | import cv2
import numpy as np
from . import ref_input
class Stimulus:
def __init__(self, param):
self.param = param
self.image = create_image(param['image'])
self.motion = self.get_motion_model(param['motion'])
self.vel = np.array([0.0, 0.0])
self.pos = np.array([0.0, 0.0]... |
from django.shortcuts import render
from django.http import HttpResponse
from catalog.models import Book, Author, BookInstance, Genre
from django.views import generic
from django.contrib.auth.decorators import login_required
@login_required
def index(request):
"""View function for home page of site."""
# Gene... | from django.shortcuts import render
from django.http import HttpResponse
from catalog.models import Book, Author, BookInstance, Genre
from django.views import generic
from django.contrib.auth.decorators import login_required
@login_required
def index(request):
"""View function for home page of site."""
# Gene... |
import os
import torch
import numpy as np
import math
import scipy
from htvlearn.lattice import Lattice
from htvlearn.delaunay import Delaunay
from htvlearn.grid import Grid
class Hex():
"""Hexagonal lattice vectors"""
v1 = Lattice.hexagonal_matrix[:, 0].numpy()
v2 = Lattice.hexagonal_matrix[:, 1].numpy... | import os
import torch
import numpy as np
import math
import scipy
from htvlearn.lattice import Lattice
from htvlearn.delaunay import Delaunay
from htvlearn.grid import Grid
class Hex():
"""Hexagonal lattice vectors"""
v1 = Lattice.hexagonal_matrix[:, 0].numpy()
v2 = Lattice.hexagonal_matrix[:, 1].numpy... |
from glob import glob
import os
import numpy as np
import h5py
def list_keys(path):
keys = []
def get_flat_keys(name, obj):
if isinstance(obj, h5py.Dataset):
keys.append(name)
file = sorted(glob(os.path.join(path, '*.h5')))[0]
with h5py.File(file, 'r') as hdf:
hdf.visitite... | from glob import glob
import os
import numpy as np
import h5py
def list_keys(path):
keys = []
def get_flat_keys(name, obj):
if isinstance(obj, h5py.Dataset):
keys.append(name)
file = sorted(glob(os.path.join(path, '*.h5')))[0]
with h5py.File(file, 'r') as hdf:
hdf.visitite... |
# this python program was written using python 3.8.6
import json
import uuid
import os
import glob
import zipfile
from typing import Callable
import snyk
import requests
# This lambda function takes a cloudstash.io function artifact and
# returns a list of vulnerabilities in the codes/dependencies as reported by snyk
... | # this python program was written using python 3.8.6
import json
import uuid
import os
import glob
import zipfile
from typing import Callable
import snyk
import requests
# This lambda function takes a cloudstash.io function artifact and
# returns a list of vulnerabilities in the codes/dependencies as reported by snyk
... |
import os
def get_nextcloud_options():
# _options = {"recv_speed": 50 * (1024**2)}
_options = {}
if os.getenv('NEXTCLOUD_USERNAME') is not None:
_options['webdav_hostname'] = f"https://antistasi.de/dev_drive/remote.php/dav/files/{os.getenv("NEXTCLOUD_USERNAME")}/"
_options['webdav_login']... | import os
def get_nextcloud_options():
# _options = {"recv_speed": 50 * (1024**2)}
_options = {}
if os.getenv('NEXTCLOUD_USERNAME') is not None:
_options['webdav_hostname'] = f"https://antistasi.de/dev_drive/remote.php/dav/files/{os.getenv('NEXTCLOUD_USERNAME')}/"
_options['webdav_login']... |
import dash_core_components as dcc
import dash_html_components as html
from dash import Dash
from dash.dependencies import Input, Output
from dash_extensions import WebSocket
# Create example app.
app = Dash(prevent_initial_callbacks=True)
app.layout = html.Div([
dcc.Input(id="input", autoComplete="off"), html.Div... | import dash_core_components as dcc
import dash_html_components as html
from dash import Dash
from dash.dependencies import Input, Output
from dash_extensions import WebSocket
# Create example app.
app = Dash(prevent_initial_callbacks=True)
app.layout = html.Div([
dcc.Input(id="input", autoComplete="off"), html.Div... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 11 16:09:52 2020
@author: chrislovejoy & mitated
"""
import os
from datetime import datetime
from typing import List
from models import ResultItem
from youtube_api import YouTubeAPI
yt_driver = YouTubeAPI(os.environ.get('API_KEY', 'default api ke... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 11 16:09:52 2020
@author: chrislovejoy & mitated
"""
import os
from datetime import datetime
from typing import List
from models import ResultItem
from youtube_api import YouTubeAPI
yt_driver = YouTubeAPI(os.environ.get('API_KEY', 'default api ke... |
from __future__ import annotations
from pathlib import Path
try:
import dearpygui.dearpygui as dpg
dearpygui_imported = True
except ImportError:
dearpygui_imported = False
from .. import __version__, config
from ..utils.module_ops import scene_classes_from_file
if dearpygui_imported:
window = dpg.... | from __future__ import annotations
from pathlib import Path
try:
import dearpygui.dearpygui as dpg
dearpygui_imported = True
except ImportError:
dearpygui_imported = False
from .. import __version__, config
from ..utils.module_ops import scene_classes_from_file
if dearpygui_imported:
window = dpg.... |
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
"""Framework for figures embedded in a GUI
Implementation
==============
Plotting is implemented hierarchically in 3 different types of
functions/classes:
top-level (public names)
Top-level functions or classes have public names create an entire figure.
... | # Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
"""Framework for figures embedded in a GUI
Implementation
==============
Plotting is implemented hierarchically in 3 different types of
functions/classes:
top-level (public names)
Top-level functions or classes have public names create an entire figure.
... |
import logging
import torch
from os import path as osp
from basicsr.data import create_dataloader, create_dataset
from basicsr.models import create_model
from basicsr.train import parse_options
from basicsr.utils import (get_env_info, get_root_logger, get_time_str,
make_exp_dirs)
from basics... | import logging
import torch
from os import path as osp
from basicsr.data import create_dataloader, create_dataset
from basicsr.models import create_model
from basicsr.train import parse_options
from basicsr.utils import (get_env_info, get_root_logger, get_time_str,
make_exp_dirs)
from basics... |
import sys
import click
from ecrtools.lib.ecr import Ecr
from ecrtools.lib.utils import convert_bytes
@click.command()
@click.argument('repo')
@click.argument('image', default='', type=str, required=False)
@click.option('-c', '--count', type=int, default=None,
help='Number of images to list.')
@click.... | import sys
import click
from ecrtools.lib.ecr import Ecr
from ecrtools.lib.utils import convert_bytes
@click.command()
@click.argument('repo')
@click.argument('image', default='', type=str, required=False)
@click.option('-c', '--count', type=int, default=None,
help='Number of images to list.')
@click.... |
# -*- coding: utf-8 -*-
################################################################################
# Form generated from reading UI file 'project changed.ui'
#
# Created by: Qt User Interface Compiler version 5.15.2
#
# WARNING! All changes made in this file will be lost when recompiling UI file!
#######... | # -*- coding: utf-8 -*-
################################################################################
# Form generated from reading UI file 'project changed.ui'
#
# Created by: Qt User Interface Compiler version 5.15.2
#
# WARNING! All changes made in this file will be lost when recompiling UI file!
#######... |
import os
import re
import math
from datetime import timedelta
import pprint
import logging
from tinydb import TinyDB, Query
from tqdm import tqdm
from config import built_ins, MAX_BATCH
from util import chunks, file_time_str
from tablo.api import Api
from tablo.apiexception import APIError
from tablo.entities.show i... | import os
import re
import math
from datetime import timedelta
import pprint
import logging
from tinydb import TinyDB, Query
from tqdm import tqdm
from config import built_ins, MAX_BATCH
from util import chunks, file_time_str
from tablo.api import Api
from tablo.apiexception import APIError
from tablo.entities.show i... |
# Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | # Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
#!/usr/bin/env python3
import os
import sys
import time
from collections import defaultdict
from typing import Any
from itertools import zip_longest
import cereal.messaging as messaging
from cereal.visionipc import VisionIpcServer, VisionStreamType
from common.spinner import Spinner
from common.timeout import Timeout
... | #!/usr/bin/env python3
import os
import sys
import time
from collections import defaultdict
from typing import Any
from itertools import zip_longest
import cereal.messaging as messaging
from cereal.visionipc import VisionIpcServer, VisionStreamType
from common.spinner import Spinner
from common.timeout import Timeout
... |
import os
import logging
import configparser
import sys
import smtplib
import csv
import time
from pycoingecko import CoinGeckoAPI
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# ------------------------------------------------------------------
# Logging Setup
# -------------... | import os
import logging
import configparser
import sys
import smtplib
import csv
import time
from pycoingecko import CoinGeckoAPI
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# ------------------------------------------------------------------
# Logging Setup
# -------------... |
import os
import subprocess
from os.path import join
from nerblackbox.modules.datasets.formatter.base_formatter import BaseFormatter
from nerblackbox.modules.utils.env_variable import env_variable
class SICFormatter(BaseFormatter):
def __init__(self):
ner_dataset = "sic"
ner_tag_list = [
... | import os
import subprocess
from os.path import join
from nerblackbox.modules.datasets.formatter.base_formatter import BaseFormatter
from nerblackbox.modules.utils.env_variable import env_variable
class SICFormatter(BaseFormatter):
def __init__(self):
ner_dataset = "sic"
ner_tag_list = [
... |
#usando dicionario
d = {}
d['Nome'] = str(input('Nome: ')).strip()
d['Media'] = float(input(f'Media de {d['Nome']}: '))
if d['Media'] >= 7:
d['Situação'] = 'Aprovado'
elif 5 <= d['Media'] <= 7:
d['Situação'] = 'Recuperação'
else:
d['Situação'] = 'Reprovado'
print('=-' * 20)
for k, v in d.items():
print(... | #usando dicionario
d = {}
d['Nome'] = str(input('Nome: ')).strip()
d['Media'] = float(input(f'Media de {d["Nome"]}: '))
if d['Media'] >= 7:
d['Situação'] = 'Aprovado'
elif 5 <= d['Media'] <= 7:
d['Situação'] = 'Recuperação'
else:
d['Situação'] = 'Reprovado'
print('=-' * 20)
for k, v in d.items():
print(... |
'''
Filters that determine whether a Locus meets a particular criteria.
'''
# %%
from antares_client._api.models import Locus
from typing import Generator
def apply(
stream: Generator[Locus, None, None],
*filters,
debug=False,
):
'''
Apply a series of filters to an iterable sequence of loci.
... | '''
Filters that determine whether a Locus meets a particular criteria.
'''
# %%
from antares_client._api.models import Locus
from typing import Generator
def apply(
stream: Generator[Locus, None, None],
*filters,
debug=False,
):
'''
Apply a series of filters to an iterable sequence of loci.
... |
from copy import deepcopy
from .types import (
Account,
Collection,
Comment,
DirectMedia,
DirectMessage,
DirectResponse,
DirectShortThread,
DirectThread,
Hashtag,
Location,
Media,
MediaOembed,
Resource,
Story,
StoryLink,
StoryMention,
User,
UserSh... | from copy import deepcopy
from .types import (
Account,
Collection,
Comment,
DirectMedia,
DirectMessage,
DirectResponse,
DirectShortThread,
DirectThread,
Hashtag,
Location,
Media,
MediaOembed,
Resource,
Story,
StoryLink,
StoryMention,
User,
UserSh... |
# https://codeforces.com/problemset/problem/1220/A
n, s = int(input()), input()
ones = s.count('n')
zeros = (n-(ones*3))//4
print(f"{"1 "*ones}{"0 "*zeros}") | # https://codeforces.com/problemset/problem/1220/A
n, s = int(input()), input()
ones = s.count('n')
zeros = (n-(ones*3))//4
print(f"{'1 '*ones}{'0 '*zeros}") |
from imagekit.admin import AdminThumbnail
from django.contrib.admin import TabularInline
from core.admin.forms import LimitedInlineFormSet
from core.admin.utils import (
get_change_view_link,
get_changelist_view_link
)
from ..models import PremierProduct
class PremierManufacturerProductsTabularInline(Tabula... | from imagekit.admin import AdminThumbnail
from django.contrib.admin import TabularInline
from core.admin.forms import LimitedInlineFormSet
from core.admin.utils import (
get_change_view_link,
get_changelist_view_link
)
from ..models import PremierProduct
class PremierManufacturerProductsTabularInline(Tabula... |
import sys
from collections import Counter
import datetime as dt
from pathlib import Path
from time import sleep
import curses
from curses import wrapper
# from basin_weights_analysis import gen_task_ctrl
def main(stdscr, status_dir='.remake/metadata_v3/task_status'):
status_dir = Path(status_dir)
# task_ct... | import sys
from collections import Counter
import datetime as dt
from pathlib import Path
from time import sleep
import curses
from curses import wrapper
# from basin_weights_analysis import gen_task_ctrl
def main(stdscr, status_dir='.remake/metadata_v3/task_status'):
status_dir = Path(status_dir)
# task_ct... |
# -*- coding: utf-8 -*-
# Copyright © 2017 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from __future__ import print_function as _
from __future__ import division as _
from... | # -*- coding: utf-8 -*-
# Copyright © 2017 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from __future__ import print_function as _
from __future__ import division as _
from... |
#!/usr/bin/env python3
import sys
import os
import re
"""
This script accepts a list of gene or transcript symbol/synonyms and converts them into one or more
FlyBase IDs.
The synonyms file can be download from:
ftp://ftp.flybase.org/releases/current/precomputed_files/synonyms/
Usage:
./symbol_to_id_lookup.py your... | #!/usr/bin/env python3
import sys
import os
import re
"""
This script accepts a list of gene or transcript symbol/synonyms and converts them into one or more
FlyBase IDs.
The synonyms file can be download from:
ftp://ftp.flybase.org/releases/current/precomputed_files/synonyms/
Usage:
./symbol_to_id_lookup.py your... |
"""Complete either attribute names or file names.
Either on demand or after a user-selected delay after a key character,
pop up a list of candidates.
"""
import __main__
import keyword
import os
import string
import sys
# Modified keyword list is used in fetch_completions.
completion_kwds = [s for s in keyword.kwlist... | """Complete either attribute names or file names.
Either on demand or after a user-selected delay after a key character,
pop up a list of candidates.
"""
import __main__
import keyword
import os
import string
import sys
# Modified keyword list is used in fetch_completions.
completion_kwds = [s for s in keyword.kwlist... |
"""Calculate ROUGE score."""
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | """Calculate ROUGE score."""
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
import difflib
import io
import os
import re
import sys
import unicodedata
import pytest
from tests.helpers.test_utils import *
from neoload_cli_lib import displayer
@pytest.mark.results
@pytest.mark.usefixtures("neoload_login") # it's like @Before on the neoload_login function
class TestDisplayer:
def test_pr... | import difflib
import io
import os
import re
import sys
import unicodedata
import pytest
from tests.helpers.test_utils import *
from neoload_cli_lib import displayer
@pytest.mark.results
@pytest.mark.usefixtures("neoload_login") # it's like @Before on the neoload_login function
class TestDisplayer:
def test_pr... |
# -*- coding: utf-8 -*-
import io
import demjson
import pandas as pd
import requests
from zvt.contract.api import df_to_db
from zvt.contract.recorder import Recorder
from zvt.utils.time_utils import to_pd_timestamp, now_pd_timestamp
from zvt.api.quote import china_stock_code_to_id
from zvt.domain import IndexStock, ... | # -*- coding: utf-8 -*-
import io
import demjson
import pandas as pd
import requests
from zvt.contract.api import df_to_db
from zvt.contract.recorder import Recorder
from zvt.utils.time_utils import to_pd_timestamp, now_pd_timestamp
from zvt.api.quote import china_stock_code_to_id
from zvt.domain import IndexStock, ... |
import inspect
import os
from collections import defaultdict
from keyword import iskeyword
from os.path import join, exists
from typing import Any, Union
import inflect
import sqlalchemy
from sqlalchemy import ForeignKeyConstraint, CheckConstraint, ForeignKey, Column
from sqlalchemy.util import OrderedDict
from .util... | import inspect
import os
from collections import defaultdict
from keyword import iskeyword
from os.path import join, exists
from typing import Any, Union
import inflect
import sqlalchemy
from sqlalchemy import ForeignKeyConstraint, CheckConstraint, ForeignKey, Column
from sqlalchemy.util import OrderedDict
from .util... |
import sys
import json
from pathlib import Path
def main():
# parse command line arguments
if (len(sys.argv) != 2):
print(f'Usage: {Path(sys.argv[0]).name} <track_file_json>')
exit(1)
track_filepath = sys.argv[1]
print(f'track_file: "{track_filepath}"')
... | import sys
import json
from pathlib import Path
def main():
# parse command line arguments
if (len(sys.argv) != 2):
print(f'Usage: {Path(sys.argv[0]).name} <track_file_json>')
exit(1)
track_filepath = sys.argv[1]
print(f'track_file: "{track_filepath}"')
... |
from typing import Any, List
from django.contrib.postgres.fields import JSONField, ArrayField
from django.db import models as django_models
from django.db.models import (
Q,
BooleanField,
DurationField,
)
from django.db.models.fields.related import ManyToManyField, ForeignKey
from baserow.core.registry im... | from typing import Any, List
from django.contrib.postgres.fields import JSONField, ArrayField
from django.db import models as django_models
from django.db.models import (
Q,
BooleanField,
DurationField,
)
from django.db.models.fields.related import ManyToManyField, ForeignKey
from baserow.core.registry im... |
import attr
import struct
import msprime
import tskit
import kastore
import json
from collections import OrderedDict
import warnings
import numpy as np
from ._version import *
from .slim_metadata import *
from .provenance import *
from .util import *
from .slim_metadata import _decode_mutation_pre_nucleotides, _set_me... | import attr
import struct
import msprime
import tskit
import kastore
import json
from collections import OrderedDict
import warnings
import numpy as np
from ._version import *
from .slim_metadata import *
from .provenance import *
from .util import *
from .slim_metadata import _decode_mutation_pre_nucleotides, _set_me... |
import argparse
import logging
import os
import signal
from collections import defaultdict
from datetime import datetime
from time import time
from typing import List
import torch
import torchaudio
from torch import nn as nn
from torch.optim import Adam
from torch.utils.data import DataLoader
from torchaudio.datasets.... | import argparse
import logging
import os
import signal
from collections import defaultdict
from datetime import datetime
from time import time
from typing import List
import torch
import torchaudio
from torch import nn as nn
from torch.optim import Adam
from torch.utils.data import DataLoader
from torchaudio.datasets.... |
"""
Test the code templates by rendering them for different parameter combinations
and checking that the code runs without errors.
"""
import sys
import os
# Activate this in case we need to import some functions, e.g. from utils.
# sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
fr... | """
Test the code templates by rendering them for different parameter combinations
and checking that the code runs without errors.
"""
import sys
import os
# Activate this in case we need to import some functions, e.g. from utils.
# sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
fr... |
#!/usr/bin/env python3
# vim: set syntax=python ts=4 :
#
# Copyright (c) 2018 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import contextlib
import string
import mmap
import sys
import re
import subprocess
import select
import shutil
import shlex
import signal
import threading
import concurrent.fut... | #!/usr/bin/env python3
# vim: set syntax=python ts=4 :
#
# Copyright (c) 2018 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import contextlib
import string
import mmap
import sys
import re
import subprocess
import select
import shutil
import shlex
import signal
import threading
import concurrent.fut... |
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.
"""
import json
import logging
from django.db.models import Q, Avg, Count, Sum, Value, BooleanField, Case, When
from django.conf import settings
from ... | """This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.
"""
import json
import logging
from django.db.models import Q, Avg, Count, Sum, Value, BooleanField, Case, When
from django.conf import settings
from ... |
import os
from lxml import etree
attribute_type = 0
attribute_value = 1
pc_pcf = '/config/web/pcf/line'
apd_class = 'gw.web.rules.APDRulesHelper'
pmp_class = 'gw.pmp.apd.web.rules.APDRulesHelper_PMP'
file_ends = ['PanelSet.pcf', 'Popup.pcf', 'ListDetail.pcf', 'Screen.pcf']
no_process = ['MenuItemSet', 'WizardStepSet... | import os
from lxml import etree
attribute_type = 0
attribute_value = 1
pc_pcf = '/config/web/pcf/line'
apd_class = 'gw.web.rules.APDRulesHelper'
pmp_class = 'gw.pmp.apd.web.rules.APDRulesHelper_PMP'
file_ends = ['PanelSet.pcf', 'Popup.pcf', 'ListDetail.pcf', 'Screen.pcf']
no_process = ['MenuItemSet', 'WizardStepSet... |
import datetime
from telethon.tl.tlobject import TLObject
from telethon.tl.types import MessageEntityPre
from telethon.utils import add_surrogate
def mentionuser(name, userid):
return f"[{name}](tg://user?id={userid})"
def htmlmentionuser(name, userid):
return f"<a href='tg://user?id={userid}'>{name}</a>"
... | import datetime
from telethon.tl.tlobject import TLObject
from telethon.tl.types import MessageEntityPre
from telethon.utils import add_surrogate
def mentionuser(name, userid):
return f"[{name}](tg://user?id={userid})"
def htmlmentionuser(name, userid):
return f"<a href='tg://user?id={userid}'>{name}</a>"
... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import re
import time
from dataclasses import dataclass
from functools import partial
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterable,
List,
Optional,
Pattern,
Type,
Union,
)
from semver import Version... | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import re
import time
from dataclasses import dataclass
from functools import partial
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterable,
List,
Optional,
Pattern,
Type,
Union,
)
from semver import Version... |
import contextlib
import collections
import pickle
import re
import sys
import warnings
from unittest import TestCase, main, skipUnless, skip
from copy import copy, deepcopy
from typing import Any, NoReturn
from typing import TypeVar, AnyStr
from typing import T, KT, VT # Not in __all__.
from typing import Union, Opt... | import contextlib
import collections
import pickle
import re
import sys
import warnings
from unittest import TestCase, main, skipUnless, skip
from copy import copy, deepcopy
from typing import Any, NoReturn
from typing import TypeVar, AnyStr
from typing import T, KT, VT # Not in __all__.
from typing import Union, Opt... |
"""
python main.py --learning_rate 0.001 --model ResNetAE --loss l2 --optimizer adam --msg demo1
python main.py --learning_rate 0.001 --model ViTAE --loss l2 --optimizer adam --msg demo1 --paths 197 --zdim 384
"""
import argparse
import os
import logging
import datetime
import torch
import torch.nn as nn
import torch.n... | """
python main.py --learning_rate 0.001 --model ResNetAE --loss l2 --optimizer adam --msg demo1
python main.py --learning_rate 0.001 --model ViTAE --loss l2 --optimizer adam --msg demo1 --paths 197 --zdim 384
"""
import argparse
import os
import logging
import datetime
import torch
import torch.nn as nn
import torch.n... |
# -*- coding: utf-8 -*-
"""
The features module.
Extract useful features for training the model.
Created by Romain Mondon-Cancel on 2020-09-25 22:26:54
"""
import bisect
import functools as ft
import logging
import random
import typing as t
import pandas as pd
import sklearn.model_selection
from . import perf
log... | # -*- coding: utf-8 -*-
"""
The features module.
Extract useful features for training the model.
Created by Romain Mondon-Cancel on 2020-09-25 22:26:54
"""
import bisect
import functools as ft
import logging
import random
import typing as t
import pandas as pd
import sklearn.model_selection
from . import perf
log... |
import re
from collections import deque, UserDict
from dataclasses import dataclass
from decimal import Decimal
from typing import Generator
import questionary
class Constants:
MAX_TOPPINGS = 4
TOPPINGS = ['lettuce', 'mayo', 'cheese', 'rice', 'tomato', 'hot sauce', 'queso']
MEATS = ['pork', 'extra pork +... | import re
from collections import deque, UserDict
from dataclasses import dataclass
from decimal import Decimal
from typing import Generator
import questionary
class Constants:
MAX_TOPPINGS = 4
TOPPINGS = ['lettuce', 'mayo', 'cheese', 'rice', 'tomato', 'hot sauce', 'queso']
MEATS = ['pork', 'extra pork +... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module containing various sites direct links generators"""
import re
import urllib.parse
import json
impor... | # Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module containing various sites direct links generators"""
import re
import urllib.parse
import json
impor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import urllib.request
import urllib.parse
import logging
from pathlib import Path
from datetime import datetime
from multiprocessing import cpu_count
import rasterio
import geopandas as gpd
from shapely.wkt import loads
from ost.helpers import vector as vec, ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import urllib.request
import urllib.parse
import logging
from pathlib import Path
from datetime import datetime
from multiprocessing import cpu_count
import rasterio
import geopandas as gpd
from shapely.wkt import loads
from ost.helpers import vector as vec, ... |
from datetime import datetime as dt, timedelta as td
import boto3
from botocore.errorfactory import ClientError
def get_client():
return boto3.client('s3')
def get_prev_file_name(bucket, file_prefix, bookmark_file, baseline_file):
s3_client = get_client()
try:
bookmark_file = s3_client.get_objec... | from datetime import datetime as dt, timedelta as td
import boto3
from botocore.errorfactory import ClientError
def get_client():
return boto3.client('s3')
def get_prev_file_name(bucket, file_prefix, bookmark_file, baseline_file):
s3_client = get_client()
try:
bookmark_file = s3_client.get_objec... |
import ast
from dataclasses import Field, field, MISSING, FrozenInstanceError
import inspect
class TypedObjectMixin:
# pylint: disable=no-method-argument
def __new__(*args, **kw):
cls, *args = args
self = object.__new__(cls)
if getattr(cls, '__init__', None) is not cls.__init_fields__:... | import ast
from dataclasses import Field, field, MISSING, FrozenInstanceError
import inspect
class TypedObjectMixin:
# pylint: disable=no-method-argument
def __new__(*args, **kw):
cls, *args = args
self = object.__new__(cls)
if getattr(cls, '__init__', None) is not cls.__init_fields__:... |
"""
This module contains shared fixtures for web UI tests.
"""
import json
import pytest
from selenium.webdriver import Chrome, Firefox
CONFIG_PATH = 'tests/config.json'
DEFAULT_WAIT_TIME = 10
SUPPORTED_BROWSERS = ['chrome', 'firefox']
@pytest.fixture(scope='session')
def config():
# Read the JSON config file a... | """
This module contains shared fixtures for web UI tests.
"""
import json
import pytest
from selenium.webdriver import Chrome, Firefox
CONFIG_PATH = 'tests/config.json'
DEFAULT_WAIT_TIME = 10
SUPPORTED_BROWSERS = ['chrome', 'firefox']
@pytest.fixture(scope='session')
def config():
# Read the JSON config file a... |
"""Test Open Peer Power template helper methods."""
from datetime import datetime
import math
import random
from unittest.mock import patch
import pytest
import voluptuous as vol
from openpeerpower.components import group
from openpeerpower.config import async_process_op_core_config
from openpeerpower.const import (
... | """Test Open Peer Power template helper methods."""
from datetime import datetime
import math
import random
from unittest.mock import patch
import pytest
import voluptuous as vol
from openpeerpower.components import group
from openpeerpower.config import async_process_op_core_config
from openpeerpower.const import (
... |
# views.py - views for comments
#
# This file is part of debexpo
# https://salsa.debian.org/mentors.debian.net-team/debexpo
#
# Copyright © 2019 Baptiste Beauplat <lyknode@cilg.org>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentati... | # views.py - views for comments
#
# This file is part of debexpo
# https://salsa.debian.org/mentors.debian.net-team/debexpo
#
# Copyright © 2019 Baptiste Beauplat <lyknode@cilg.org>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentati... |
import json
from pathlib import Path
import pytest
SCOPES = ("global", "host", "environment", "os", "appliance")
# Need this because load can touch filesystem files.
@pytest.mark.usefixtures("revert_etc")
class TestLoad:
"""A test case to hold all the tests for `stack load`"""
@pytest.mark.parametrize("scope", SCO... | import json
from pathlib import Path
import pytest
SCOPES = ("global", "host", "environment", "os", "appliance")
# Need this because load can touch filesystem files.
@pytest.mark.usefixtures("revert_etc")
class TestLoad:
"""A test case to hold all the tests for `stack load`"""
@pytest.mark.parametrize("scope", SCO... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from asyncio import get_event_loop, ensure_future, gather, sleep
from datetime import datetime, timedelta
from pprint import pprint
from anticens import anticens
from imgcry import encrypt_image
from pixiv import PixivApi, JP_TZ
from weibo import WeiboApi
c... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from asyncio import get_event_loop, ensure_future, gather, sleep
from datetime import datetime, timedelta
from pprint import pprint
from anticens import anticens
from imgcry import encrypt_image
from pixiv import PixivApi, JP_TZ
from weibo import WeiboApi
c... |
import logging
import textwrap
from collections import ChainMap
from io import StringIO
from typing import Union
import discord
from discord import Color, Embed, Member, PartialMessage, RawReactionActionEvent, User
from discord.ext.commands import Cog, Context, group, has_any_role
from bot.api import ResponseCodeErro... | import logging
import textwrap
from collections import ChainMap
from io import StringIO
from typing import Union
import discord
from discord import Color, Embed, Member, PartialMessage, RawReactionActionEvent, User
from discord.ext.commands import Cog, Context, group, has_any_role
from bot.api import ResponseCodeErro... |
from turtle import pos
import browser
import page
import re
import json
PAGE_URL = 'https://www.facebook.com/groups/j2team.community/'
TOR_PATH = browser.TOR_PATH.NONE
BROWSER_OPTIONS = browser.BROWSER_OPTIONS.CHROME
USE_PROXY = False
PRIVATE = True
SPEED_UP = True
HEADLESS = False
SCROLL_DOWN = 1
FILTER_CMTS_BY = p... | from turtle import pos
import browser
import page
import re
import json
PAGE_URL = 'https://www.facebook.com/groups/j2team.community/'
TOR_PATH = browser.TOR_PATH.NONE
BROWSER_OPTIONS = browser.BROWSER_OPTIONS.CHROME
USE_PROXY = False
PRIVATE = True
SPEED_UP = True
HEADLESS = False
SCROLL_DOWN = 1
FILTER_CMTS_BY = p... |
"""
Most of this code comes from the timm library.
We tried to disentangle from the timm library version.
Adapted from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
"""
import math
import logging
import warnings
from functools import partial
from collections import O... | """
Most of this code comes from the timm library.
We tried to disentangle from the timm library version.
Adapted from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
"""
import math
import logging
import warnings
from functools import partial
from collections import O... |
# -*- coding: utf-8 -*-
__author__ = 'lundberg'
import urllib.parse
from contextlib import contextmanager
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, Iterator, List, Optional, Set
from flask import abort, current_app, request
from flask_lim... | # -*- coding: utf-8 -*-
__author__ = 'lundberg'
import urllib.parse
from contextlib import contextmanager
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, Iterator, List, Optional, Set
from flask import abort, current_app, request
from flask_lim... |
from enum import Enum
from typing import NewType, NamedTuple, Optional, Mapping, Sequence, Any, List
import typeit
from inflection import camelize
from typeit.schema import Invalid
__all__ = (
'TypeGenerator',
'ContentTypeTag',
'Ref',
'EmptyValue',
)
ContentTypeFormat = NewType('ContentTypeFormat',... | from enum import Enum
from typing import NewType, NamedTuple, Optional, Mapping, Sequence, Any, List
import typeit
from inflection import camelize
from typeit.schema import Invalid
__all__ = (
'TypeGenerator',
'ContentTypeTag',
'Ref',
'EmptyValue',
)
ContentTypeFormat = NewType('ContentTypeFormat',... |
# Copyright 2020 The GenoML Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | # Copyright 2020 The GenoML Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
"""This module defines the programmatic API that can be used to interact with `portray`
to generate and view documentation.
If you want to extend `portray` or use it directly from within Python - this is the place
to start.
"""
import os
import webbrowser
from typing import Dict, Optional, Union
import hug
i... | """This module defines the programmatic API that can be used to interact with `portray`
to generate and view documentation.
If you want to extend `portray` or use it directly from within Python - this is the place
to start.
"""
import os
import webbrowser
from typing import Dict, Optional, Union
import hug
i... |
import copy
import os
import tempfile
from functools import wraps
from itertools import groupby
from typing import List, Optional, Tuple, TypeVar, Union
import numpy as np
import pyarrow as pa
from . import config
from .utils.logging import get_logger
logger = get_logger(__name__)
def inject_arrow_table_documenta... | import copy
import os
import tempfile
from functools import wraps
from itertools import groupby
from typing import List, Optional, Tuple, TypeVar, Union
import numpy as np
import pyarrow as pa
from . import config
from .utils.logging import get_logger
logger = get_logger(__name__)
def inject_arrow_table_documenta... |
#!/usr/bin/env python3
import logging
import os
import shutil
import sys
from datetime import datetime
import pytest
from src.dependency import check_dependencies
from src.exif import Exif
from src.phockup import Phockup
os.chdir(os.path.dirname(__file__))
def test_check_dependencies(mocker):
mocker.patch('shu... | #!/usr/bin/env python3
import logging
import os
import shutil
import sys
from datetime import datetime
import pytest
from src.dependency import check_dependencies
from src.exif import Exif
from src.phockup import Phockup
os.chdir(os.path.dirname(__file__))
def test_check_dependencies(mocker):
mocker.patch('shu... |
__package__ = "blackhat.bin"
from hashlib import sha224
from ..helpers import Result, ResultMessages
from ..lib.input import ArgParser
from ..lib.output import output
__COMMAND__ = "sha256sum"
__DESCRIPTION__ = "compute and check SHA224 message digest"
__DESCRIPTION_LONG__ = "Print or check SHA224 (224-bit) checksum... | __package__ = "blackhat.bin"
from hashlib import sha224
from ..helpers import Result, ResultMessages
from ..lib.input import ArgParser
from ..lib.output import output
__COMMAND__ = "sha256sum"
__DESCRIPTION__ = "compute and check SHA224 message digest"
__DESCRIPTION_LONG__ = "Print or check SHA224 (224-bit) checksum... |
"""
Map is a generic Map class from which all other Map classes inherit from.
"""
import copy
import html
import textwrap
import warnings
import webbrowser
from io import BytesIO
from base64 import b64encode
from tempfile import NamedTemporaryFile
from collections import namedtuple
import matplotlib.pyplot as plt
impo... | """
Map is a generic Map class from which all other Map classes inherit from.
"""
import copy
import html
import textwrap
import warnings
import webbrowser
from io import BytesIO
from base64 import b64encode
from tempfile import NamedTemporaryFile
from collections import namedtuple
import matplotlib.pyplot as plt
impo... |
"""
For the multiprocessing to work property, it's best to pass around pure functions into workers instead
of methods of a class. Below functions have been designed with that in mind.
"""
from math import log10
import jesse.helpers as jh
from jesse.research.backtest import _isolated_backtest as isolated_backtest
from j... | """
For the multiprocessing to work property, it's best to pass around pure functions into workers instead
of methods of a class. Below functions have been designed with that in mind.
"""
from math import log10
import jesse.helpers as jh
from jesse.research.backtest import _isolated_backtest as isolated_backtest
from j... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# complexity documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# au... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# complexity documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# au... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
# Copyright 2020 Pulser Development Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | # Copyright 2020 Pulser Development Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
"""Test asyncpraw.models.subreddit."""
import socket
import sys
from asyncio import TimeoutError
from os.path import abspath, dirname, join
import pytest
from aiohttp import ClientResponse
from aiohttp.http_websocket import WebSocketError
from asyncprawcore import BadRequest, Forbidden, NotFound, TooLarge
from asyncte... | """Test asyncpraw.models.subreddit."""
import socket
import sys
from asyncio import TimeoutError
from os.path import abspath, dirname, join
import pytest
from aiohttp import ClientResponse
from aiohttp.http_websocket import WebSocketError
from asyncprawcore import BadRequest, Forbidden, NotFound, TooLarge
from asyncte... |
from discord import Role, TextChannel, VoiceChannel, Embed, Color, utils, Emoji, Member, User, File
from discord.ext.commands import command, group
from cassandra.bot import Union
from random import choice, randint, sample
from os import environ
from bs4 import BeautifulSoup
from enum import Enum
import asyncio
import ... | from discord import Role, TextChannel, VoiceChannel, Embed, Color, utils, Emoji, Member, User, File
from discord.ext.commands import command, group
from cassandra.bot import Union
from random import choice, randint, sample
from os import environ
from bs4 import BeautifulSoup
from enum import Enum
import asyncio
import ... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from functools import partial
import os
import sys
import aiohttp
import aiohttp_jinja2
from aiohttp import web
from aiohttp_security import check_authorized
import api.http
from app import admin_app, api_app, app as main_app
from config import config
from models import Room, User
from models.role import Role
from ut... | from functools import partial
import os
import sys
import aiohttp
import aiohttp_jinja2
from aiohttp import web
from aiohttp_security import check_authorized
import api.http
from app import admin_app, api_app, app as main_app
from config import config
from models import Room, User
from models.role import Role
from ut... |
import numpy as np
import cv2
import pandas as pd
male = pd.read_csv("data/names/herrenavn.csv")
female = pd.read_csv("data/names/kvinnenavn.csv")
maleLength = len(male['Navn'])
feMaleLength = len(female['Navn'])
def draw_information(image_total, loc, faces_df, analyzis_object, useRandomNames=False):
currentDf =... |
import numpy as np
import cv2
import pandas as pd
male = pd.read_csv("data/names/herrenavn.csv")
female = pd.read_csv("data/names/kvinnenavn.csv")
maleLength = len(male['Navn'])
feMaleLength = len(female['Navn'])
def draw_information(image_total, loc, faces_df, analyzis_object, useRandomNames=False):
currentDf =... |
"""Work with Note and Notebook classes."""
from datetime import datetime as dtime
import re
class Note:
"""Represent a note in a notebook."""
_id = 1
def __init__(self, memo: str, tags=[]):
"""Create a note with a certain id.
:param memo: a message of the note
:param tags: tags o... | """Work with Note and Notebook classes."""
from datetime import datetime as dtime
import re
class Note:
"""Represent a note in a notebook."""
_id = 1
def __init__(self, memo: str, tags=[]):
"""Create a note with a certain id.
:param memo: a message of the note
:param tags: tags o... |
"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... | """
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... |
import sys
import pathlib
import os
from sklearn.model_selection import train_test_split
from .datasets import Dataset
from ..log import logger
__all__ = [
'available_transformers'
]
_MODULE = sys.modules[__name__]
_MODULE_DIR = pathlib.Path(os.path.dirname(os.path.abspath(__file__)))
def available_transformers(... | import sys
import pathlib
import os
from sklearn.model_selection import train_test_split
from .datasets import Dataset
from ..log import logger
__all__ = [
'available_transformers'
]
_MODULE = sys.modules[__name__]
_MODULE_DIR = pathlib.Path(os.path.dirname(os.path.abspath(__file__)))
def available_transformers(... |
"""
Copyright 2020 Amazon.com, Inc. or its affiliates.
All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying thi... | """
Copyright 2020 Amazon.com, Inc. or its affiliates.
All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying thi... |
# app.py
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
import psycopg2
import os
import database
app = Flask(__name__)
# Eliminate CORS issue.
CORS(app)
@app.route('/waitlist', methods=['POST'])
def post_waitlist():
param = request.get_json()
print(param)
# You c... | # app.py
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
import psycopg2
import os
import database
app = Flask(__name__)
# Eliminate CORS issue.
CORS(app)
@app.route('/waitlist', methods=['POST'])
def post_waitlist():
param = request.get_json()
print(param)
# You c... |
import datetime
import lxml.etree as ET
import re
import requests
import cachetools.func
from settings import CACHE_TTL_SECS, CACHE_MAX_SIZE
from flask_restful import abort
from utils import server_log
@cachetools.func.ttl_cache(ttl=CACHE_TTL_SECS, maxsize=CACHE_MAX_SIZE)
def get_doi_content(user_doi):
"""
T... | import datetime
import lxml.etree as ET
import re
import requests
import cachetools.func
from settings import CACHE_TTL_SECS, CACHE_MAX_SIZE
from flask_restful import abort
from utils import server_log
@cachetools.func.ttl_cache(ttl=CACHE_TTL_SECS, maxsize=CACHE_MAX_SIZE)
def get_doi_content(user_doi):
"""
T... |
import functools
import inspect
import logging
import warnings
from typing import Union, Callable
from blizz import _inspect
from ._helpers import doublewrap
from ._primitives import Relation, Type, is_pandas_df, is_pyspark_df
try:
import pyspark
except ImportError: # pragma: no cover
pyspark = None # pragm... | import functools
import inspect
import logging
import warnings
from typing import Union, Callable
from blizz import _inspect
from ._helpers import doublewrap
from ._primitives import Relation, Type, is_pandas_df, is_pyspark_df
try:
import pyspark
except ImportError: # pragma: no cover
pyspark = None # pragm... |
import numpy as np
from suzieq.poller.services.service import Service
from ipaddress import ip_address, IPv4Interface
class OspfIfService(Service):
"""OSPF Interface service. Output needs to be munged"""
def _clean_linux_data(self, processed_data, raw_data):
for entry in processed_data:
... | import numpy as np
from suzieq.poller.services.service import Service
from ipaddress import ip_address, IPv4Interface
class OspfIfService(Service):
"""OSPF Interface service. Output needs to be munged"""
def _clean_linux_data(self, processed_data, raw_data):
for entry in processed_data:
... |
import torch
import random
import torchaudio
from pathlib import Path
from torch import Tensor
from torchaudio import transforms as T
from torch.nn import functional as F
from torch.utils.data import Dataset, DataLoader
from typing import Tuple
from .transforms import mixup_augment
class FSDKaggle2018(Dataset):
C... | import torch
import random
import torchaudio
from pathlib import Path
from torch import Tensor
from torchaudio import transforms as T
from torch.nn import functional as F
from torch.utils.data import Dataset, DataLoader
from typing import Tuple
from .transforms import mixup_augment
class FSDKaggle2018(Dataset):
C... |
# AUTOGENERATED! DO NOT EDIT! File to edit: Widgets.ipynb (unless otherwise specified).
__all__ = ['css_style', 'dark_colors', 'light_colors', 'simple_colors', 'default_colors', 'get_files_gui', 'InputGui',
'generate_summary', 'VasprunApp', 'KPathApp']
# Cell
import os, textwrap
import json
from time impor... | # AUTOGENERATED! DO NOT EDIT! File to edit: Widgets.ipynb (unless otherwise specified).
__all__ = ['css_style', 'dark_colors', 'light_colors', 'simple_colors', 'default_colors', 'get_files_gui', 'InputGui',
'generate_summary', 'VasprunApp', 'KPathApp']
# Cell
import os, textwrap
import json
from time impor... |
from os import path
from sys import argv
from pynput import keyboard
from pynput.keyboard import Controller
from pynput.keyboard import Key
from modules.audio_input import audioRecords
from modules.search import SearchACT
# default value if there is no **kwargs
PATH_OF_SCRIPT = path.dirname(argv[0])
PATH_DICT_DATA =... | from os import path
from sys import argv
from pynput import keyboard
from pynput.keyboard import Controller
from pynput.keyboard import Key
from modules.audio_input import audioRecords
from modules.search import SearchACT
# default value if there is no **kwargs
PATH_OF_SCRIPT = path.dirname(argv[0])
PATH_DICT_DATA =... |
# https://github.com/checktheroads/hyperglass
"""
Imports configuration varibles from configuration files and returns default values if undefined.
"""
# Standard Imports
import os
import math
import logging
# Module Imports
import toml
import logzero
from logzero import logger
# Project Imports
import hyperglass
# P... | # https://github.com/checktheroads/hyperglass
"""
Imports configuration varibles from configuration files and returns default values if undefined.
"""
# Standard Imports
import os
import math
import logging
# Module Imports
import toml
import logzero
from logzero import logger
# Project Imports
import hyperglass
# P... |
import random
import string
import traceback
from tests.cephfs.cephfs_utilsV1 import FsUtils
from utility.log import Log
log = Log(__name__)
def run(ceph_cluster, **kw):
"""
Pre-requisites :
1. create fs volume create cephfs and cephfs-ec
Subvolume Group Operations :
1. ceph fs subvolumegroup c... | import random
import string
import traceback
from tests.cephfs.cephfs_utilsV1 import FsUtils
from utility.log import Log
log = Log(__name__)
def run(ceph_cluster, **kw):
"""
Pre-requisites :
1. create fs volume create cephfs and cephfs-ec
Subvolume Group Operations :
1. ceph fs subvolumegroup c... |
# -*- coding: future_fstrings -*-
import json
import datetime
import adal
from .reports import Reports
from .datasets import Datasets
from .imports import Imports
from .groups import Groups
from .activity_logs import ActivityLogs
class PowerBIClient:
default_resource_url = 'https://analysis.windows.net/powerbi/... | # -*- coding: future_fstrings -*-
import json
import datetime
import adal
from .reports import Reports
from .datasets import Datasets
from .imports import Imports
from .groups import Groups
from .activity_logs import ActivityLogs
class PowerBIClient:
default_resource_url = 'https://analysis.windows.net/powerbi/... |
"""Covid View"""
__docformat__ = "numpy"
import os
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd
from rich.console import Console
import gamestonk_terminal.feature_flags as gtff
from gamestonk_terminal.alternative.covid import covid_model
from gamestonk_terminal.config_plot im... | """Covid View"""
__docformat__ = "numpy"
import os
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd
from rich.console import Console
import gamestonk_terminal.feature_flags as gtff
from gamestonk_terminal.alternative.covid import covid_model
from gamestonk_terminal.config_plot im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.