edited_code stringlengths 17 978k | original_code stringlengths 17 978k |
|---|---|
import cv2
from tqdm import tqdm
from itertools import chain as iterchain
from ..raw import CK
from ..raw import JAFFE
from ..raw import FER2013
from ...paths import PATH_DATA_PROCESSED
from ...utils import *
def iter_preproc_datasets(**kwargs):
dataset1 = CK(**kwargs)
dataset2 = JAFFE(**kwargs)
dataset = ... | import cv2
from tqdm import tqdm
from itertools import chain as iterchain
from ..raw import CK
from ..raw import JAFFE
from ..raw import FER2013
from ...paths import PATH_DATA_PROCESSED
from ...utils import *
def iter_preproc_datasets(**kwargs):
dataset1 = CK(**kwargs)
dataset2 = JAFFE(**kwargs)
dataset = ... |
import math
import re
import warnings
from decimal import Decimal
from enum import Enum
from pathlib import Path
from types import new_class
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
List,
Optional,
Pattern,
Set,
Type,
TypeVar,
Union,
cast,
)
... | import math
import re
import warnings
from decimal import Decimal
from enum import Enum
from pathlib import Path
from types import new_class
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
List,
Optional,
Pattern,
Set,
Type,
TypeVar,
Union,
cast,
)
... |
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2021 Scipp contributors (https://github.com/scipp)
"""
This script generates input parameters to test whether arithmetic
operations are consistent with Python.
It takes the output file as its only command line argument.
"""
from itertools import product
import s... | # SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2021 Scipp contributors (https://github.com/scipp)
"""
This script generates input parameters to test whether arithmetic
operations are consistent with Python.
It takes the output file as its only command line argument.
"""
from itertools import product
import s... |
word = input("Enter a word: ")
print(f"The word in exchanged case is: {word.swapcase()}")
print("----------------------------------")
alt_word = [word[i].upper() if not i % 2 else word[i].lower() for i in range(len(word))]
print(f"The word in alternating upper and lower case is: {"".join(alt_word)}")
print("... |
word = input("Enter a word: ")
print(f"The word in exchanged case is: {word.swapcase()}")
print("----------------------------------")
alt_word = [word[i].upper() if not i % 2 else word[i].lower() for i in range(len(word))]
print(f"The word in alternating upper and lower case is: {''.join(alt_word)}")
print("... |
import os.path
from copy import copy
from pathlib import Path
import numpy as np
from qtpy.QtCore import QCoreApplication, QSize, Qt
from qtpy.QtGui import QCursor, QGuiApplication
from qtpy.QtWidgets import (
QFileDialog,
QMessageBox,
QSplitter,
QVBoxLayout,
QWidget,
)
from vispy.scene import Arcb... | import os.path
from copy import copy
from pathlib import Path
import numpy as np
from qtpy.QtCore import QCoreApplication, QSize, Qt
from qtpy.QtGui import QCursor, QGuiApplication
from qtpy.QtWidgets import (
QFileDialog,
QMessageBox,
QSplitter,
QVBoxLayout,
QWidget,
)
from vispy.scene import Arcb... |
from functools import wraps, partial
from itertools import product, chain, islice
import itertools
import collections
import copy
from enum import Enum
import operator
import random
import unittest
import math
import torch
import numpy as np
from torch._six import inf
import collections.abc
from typing import Any, Ca... | from functools import wraps, partial
from itertools import product, chain, islice
import itertools
import collections
import copy
from enum import Enum
import operator
import random
import unittest
import math
import torch
import numpy as np
from torch._six import inf
import collections.abc
from typing import Any, Ca... |
#!/usr/bin/env python3
from argparse import ArgumentParser
from os import path
import sys
import time
try:
sys.path.insert(0, path.abspath(path.join(path.dirname(__file__), "..")))
from scraper import __version__
from scraper import main
except ModuleNotFoundError as e:
print(f"[x] {e}")
sys.exit... | #!/usr/bin/env python3
from argparse import ArgumentParser
from os import path
import sys
import time
try:
sys.path.insert(0, path.abspath(path.join(path.dirname(__file__), "..")))
from scraper import __version__
from scraper import main
except ModuleNotFoundError as e:
print(f"[x] {e}")
sys.exit... |
import json
from ssh_keyword_tools import checkQuit
from ssh_keyword_json import ManageJson
from ssh_keyword_newconnection import CreateConnection
class Connection(object):
'Manage connections'
def __init__(self, ip='0'):
self.ip = ip
self.fJson = ManageJson()
def setConnection(self):
... | import json
from ssh_keyword_tools import checkQuit
from ssh_keyword_json import ManageJson
from ssh_keyword_newconnection import CreateConnection
class Connection(object):
'Manage connections'
def __init__(self, ip='0'):
self.ip = ip
self.fJson = ManageJson()
def setConnection(self):
... |
#!/usr/bin/env python3
###########################################################################
# #
# Program purpose: Determines if a list of integer is an Arithmetic #
# or Geometric progression. ... | #!/usr/bin/env python3
###########################################################################
# #
# Program purpose: Determines if a list of integer is an Arithmetic #
# or Geometric progression. ... |
import argparse
import sys
import os
from datetime import timedelta
import time
from itertools import zip_longest
import torch
from torch.utils import data
from tqdm.auto import tqdm
from transformers import get_linear_schedule_with_warmup
import nlp2
import tfkit
import tfkit.utility.tok as tok
from tfkit.utility.dat... | import argparse
import sys
import os
from datetime import timedelta
import time
from itertools import zip_longest
import torch
from torch.utils import data
from tqdm.auto import tqdm
from transformers import get_linear_schedule_with_warmup
import nlp2
import tfkit
import tfkit.utility.tok as tok
from tfkit.utility.dat... |
import functools
from typing import Dict
import base64
import streamlit as st # type: ignore
import wikipedia # type: ignore
from transformers import Pipeline, pipeline # type: ignore
from config import config
def conditional_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
i... | import functools
from typing import Dict
import base64
import streamlit as st # type: ignore
import wikipedia # type: ignore
from transformers import Pipeline, pipeline # type: ignore
from config import config
def conditional_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
i... |
import discord
import json
import http3
class currency():
async def currencyConverter(self, message):
messageArray = message.content.split(" ")
if(not len(message.content.split(" ")) == 3):
await message.channel.send("Incorrect number of parameters! Format currency requests as `>currency... | import discord
import json
import http3
class currency():
async def currencyConverter(self, message):
messageArray = message.content.split(" ")
if(not len(message.content.split(" ")) == 3):
await message.channel.send("Incorrect number of parameters! Format currency requests as `>currency... |
from django.utils import timezone
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from care.facility.api.serializers import TIMESTAMP_FIELDS
from care.facility.api.serializers.facility import FacilityBasicInfoSerializer
from care.facility.models import PatientConsultation, ... | from django.utils import timezone
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from care.facility.api.serializers import TIMESTAMP_FIELDS
from care.facility.api.serializers.facility import FacilityBasicInfoSerializer
from care.facility.models import PatientConsultation, ... |
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import datetime
from datetime import timedelta
app = dash.Dash()
x_data = ['DSL', 'Gas', 'Electricty']
start = go.Bar(
x=[datetime.datetime(y, m, d) for (y, m, d) in [(2015, ... | # -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import datetime
from datetime import timedelta
app = dash.Dash()
x_data = ['DSL', 'Gas', 'Electricty']
start = go.Bar(
x=[datetime.datetime(y, m, d) for (y, m, d) in [(2015, ... |
#!/usr/bin/env python3
from argparse import ArgumentParser, FileType
from datetime import datetime
import json
import os
def ensure_dup(inp, out, inp_key, out_key):
'''
If the out dictionary does not contain a value for out_key update it
to be equal to the inp dictionaries inp_key value, if it does exist... | #!/usr/bin/env python3
from argparse import ArgumentParser, FileType
from datetime import datetime
import json
import os
def ensure_dup(inp, out, inp_key, out_key):
'''
If the out dictionary does not contain a value for out_key update it
to be equal to the inp dictionaries inp_key value, if it does exist... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import base64
from abc import ABC
from typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Tuple
from urllib.parse import parse_qsl, urlparse
import requests
from airbyte_cdk.models import SyncMode
from airbyte_cdk.sources import Abstract... | #
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import base64
from abc import ABC
from typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Tuple
from urllib.parse import parse_qsl, urlparse
import requests
from airbyte_cdk.models import SyncMode
from airbyte_cdk.sources import Abstract... |
"""Configs for VisDA17 experiments."""
def get_weighting_config_class_pareto(alpha, reverse, seed):
return {
'name': 'class_pareto',
'kwargs': {
'alpha': alpha,
'reverse': reverse,
'seed': seed
},
}
def get_dataset_config_visda17_pareto_target_imba... | """Configs for VisDA17 experiments."""
def get_weighting_config_class_pareto(alpha, reverse, seed):
return {
'name': 'class_pareto',
'kwargs': {
'alpha': alpha,
'reverse': reverse,
'seed': seed
},
}
def get_dataset_config_visda17_pareto_target_imba... |
import asyncio
import difflib
import itertools
import typing as t
from datetime import datetime, timezone
from itertools import zip_longest
import discord
from dateutil.relativedelta import relativedelta
from deepdiff import DeepDiff
from discord import Colour, Message, Thread
from discord.abc import GuildChannel
from... | import asyncio
import difflib
import itertools
import typing as t
from datetime import datetime, timezone
from itertools import zip_longest
import discord
from dateutil.relativedelta import relativedelta
from deepdiff import DeepDiff
from discord import Colour, Message, Thread
from discord.abc import GuildChannel
from... |
import random
import uuid
import time
import re
from datetime import datetime
from slack import WebClient
from slack.errors import SlackApiError
def n_even_chunks(lst, n):
"""Yield n as even chunks as possible from lst."""
last = 0
for i in range(1, n + 1):
cur = int(round(i * (len(lst) / n)))
... | import random
import uuid
import time
import re
from datetime import datetime
from slack import WebClient
from slack.errors import SlackApiError
def n_even_chunks(lst, n):
"""Yield n as even chunks as possible from lst."""
last = 0
for i in range(1, n + 1):
cur = int(round(i * (len(lst) / n)))
... |
"""This is a cog for a discord.py bot.
It drops random cheese for people to pick up
"""
from collections import defaultdict
from datetime import datetime as dt
from discord import Activity, Client, DMChannel, Embed, Message
from discord.ext import commands
import asyncio
import json
import random
class Cheese(command... | """This is a cog for a discord.py bot.
It drops random cheese for people to pick up
"""
from collections import defaultdict
from datetime import datetime as dt
from discord import Activity, Client, DMChannel, Embed, Message
from discord.ext import commands
import asyncio
import json
import random
class Cheese(command... |
"""Semantic Role Labeling related modeling class"""
from copy import deepcopy
from typing import List, Optional
from pororo.tasks.utils.base import PororoFactoryBase, PororoSimpleBase
class PororoSrlFactory(PororoFactoryBase):
"""
Conduct semantic role labeling
Korean (`charbert.base.ko.srl`)
... | """Semantic Role Labeling related modeling class"""
from copy import deepcopy
from typing import List, Optional
from pororo.tasks.utils.base import PororoFactoryBase, PororoSimpleBase
class PororoSrlFactory(PororoFactoryBase):
"""
Conduct semantic role labeling
Korean (`charbert.base.ko.srl`)
... |
#!/usr/bin/env python3
"""
Script to create MongoDb users for X-Road Metrics tools.
"""
# The MIT License
# Copyright (c) 2021- Nordic Institute for Interoperability Solutions (NIIS)
# Copyright (c) 2017-2020 Estonian Information System Authority (RIA)
#
# Permission is hereby granted, free of charge, to any pers... | #!/usr/bin/env python3
"""
Script to create MongoDb users for X-Road Metrics tools.
"""
# The MIT License
# Copyright (c) 2021- Nordic Institute for Interoperability Solutions (NIIS)
# Copyright (c) 2017-2020 Estonian Information System Authority (RIA)
#
# Permission is hereby granted, free of charge, to any pers... |
#Author-Thomas Axelsson, ZXYNINE
#Description-Blocks Component Dragging in parametric mode
# This file is part of NoComponentDrag, a Fusion 360 add-in for blocking
# component drags.
#
# Copyright (c) 2020 Thomas Axelsson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softw... | #Author-Thomas Axelsson, ZXYNINE
#Description-Blocks Component Dragging in parametric mode
# This file is part of NoComponentDrag, a Fusion 360 add-in for blocking
# component drags.
#
# Copyright (c) 2020 Thomas Axelsson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softw... |
import contextlib
from io import StringIO
import logging
import pathlib
import click
import flake8.main.application
import toml
from ni_python_styleguide import _acknowledge_existing_errors
def _qs_or_vs(verbosity):
if verbosity != 0:
return f"-{"v" * verbosity if verbosity > 0 else "q" * abs(verbosity)... | import contextlib
from io import StringIO
import logging
import pathlib
import click
import flake8.main.application
import toml
from ni_python_styleguide import _acknowledge_existing_errors
def _qs_or_vs(verbosity):
if verbosity != 0:
return f"-{'v' * verbosity if verbosity > 0 else 'q' * abs(verbosity)... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2022 Valory AG
# Copyright 2018-2020 Fetch.AI Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# ... | # -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2022 Valory AG
# Copyright 2018-2020 Fetch.AI Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# ... |
import requests
from time import sleep
from lib.constants import *
def log_request(targetNode):
url = HTTP + targetNode.get_address() + '/log'
return requests.get(url)
def join_request(targetNode, port, ip):
sleep(2)
url = HTTP + targetNode.get_address() + '/join'
params = f'{PORT}={port}&{IP}={ip... | import requests
from time import sleep
from lib.constants import *
def log_request(targetNode):
url = HTTP + targetNode.get_address() + '/log'
return requests.get(url)
def join_request(targetNode, port, ip):
sleep(2)
url = HTTP + targetNode.get_address() + '/join'
params = f'{PORT}={port}&{IP}={ip... |
from __future__ import annotations
from typing import Sequence, Union
from .benchmarking import Benchmark, Benchmarker, NullBenchmarkReporter, SimulBenchmarker
from .boards import Scoreboard
from .engine import Engine, SimulEngine
from .enums import SolverType
from .factory import create_models
from .solver import En... | from __future__ import annotations
from typing import Sequence, Union
from .benchmarking import Benchmark, Benchmarker, NullBenchmarkReporter, SimulBenchmarker
from .boards import Scoreboard
from .engine import Engine, SimulEngine
from .enums import SolverType
from .factory import create_models
from .solver import En... |
# -*- mode:python; coding:utf-8 -*-
# Copyright (c) 2020 IBM Corp. 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
... | # -*- mode:python; coding:utf-8 -*-
# Copyright (c) 2020 IBM Corp. 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
... |
"""
On languages and kernels
------------------------
NotebookSource represents source code in a Jupyter notebook format (language
agnostic). Apart from .ipynb, we also support any other extension supported
by jupytext.
Given a notebook, we have to know which language it is written in to extract
upstream/product varia... | """
On languages and kernels
------------------------
NotebookSource represents source code in a Jupyter notebook format (language
agnostic). Apart from .ipynb, we also support any other extension supported
by jupytext.
Given a notebook, we have to know which language it is written in to extract
upstream/product varia... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 14 15:14:54 2018
@author: Weber Sébastien
@email: seba.weber@gmail.com
"""
from PyQt5.QtCore import pyqtSignal, QTimer, QThread
from easydict import EasyDict as edict
from pymodaq.daq_utils.daq_utils import ThreadCommand, getLineInfo, DataFromPlugins, set_logger, get_modu... | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 14 15:14:54 2018
@author: Weber Sébastien
@email: seba.weber@gmail.com
"""
from PyQt5.QtCore import pyqtSignal, QTimer, QThread
from easydict import EasyDict as edict
from pymodaq.daq_utils.daq_utils import ThreadCommand, getLineInfo, DataFromPlugins, set_logger, get_modu... |
import datetime
import json
import re
import time
from pathlib import Path
import numpy as np
import pandas as pd
from bokeh.io import reset_output
from bokeh.layouts import column, widgetbox
from bokeh.models import HoverTool, PointDrawTool, Span
from bokeh.models.widgets import DataTable, TableColumn
fro... | import datetime
import json
import re
import time
from pathlib import Path
import numpy as np
import pandas as pd
from bokeh.io import reset_output
from bokeh.layouts import column, widgetbox
from bokeh.models import HoverTool, PointDrawTool, Span
from bokeh.models.widgets import DataTable, TableColumn
fro... |
import torch
from fairseq.models.bart import BARTModel
import argparse
from pprint import pprint
from tqdm import tqdm
import os
from os.path import join
import shutil
import logging
import numpy as np
import json
import random
import string
import files2rouge
import time
def test_rouge(cand, ref, outpath=None, tmp_d... | import torch
from fairseq.models.bart import BARTModel
import argparse
from pprint import pprint
from tqdm import tqdm
import os
from os.path import join
import shutil
import logging
import numpy as np
import json
import random
import string
import files2rouge
import time
def test_rouge(cand, ref, outpath=None, tmp_d... |
import torch
from collections import Counter
from os import path as osp
from torch import distributed as dist
from tqdm import tqdm
from basicsr.metrics import calculate_metric
from basicsr.utils import get_root_logger, imwrite, tensor2img
from basicsr.utils.dist_util import get_dist_info
from basicsr.utils.registry i... | import torch
from collections import Counter
from os import path as osp
from torch import distributed as dist
from tqdm import tqdm
from basicsr.metrics import calculate_metric
from basicsr.utils import get_root_logger, imwrite, tensor2img
from basicsr.utils.dist_util import get_dist_info
from basicsr.utils.registry i... |
ficha = list()
while True:
nome = str(input('Nome: '))
nota1 = float(input('Nota 01: '))
nota2 = float(input('Nota 02: '))
media = (nota1 + nota2) / 2
ficha.append([nome, nota1, nota2, media])
resp = str(input('Quer continuar? (S/N) '))
if resp in 'Nn':
break
print('-=' * 30)
print(... | ficha = list()
while True:
nome = str(input('Nome: '))
nota1 = float(input('Nota 01: '))
nota2 = float(input('Nota 02: '))
media = (nota1 + nota2) / 2
ficha.append([nome, nota1, nota2, media])
resp = str(input('Quer continuar? (S/N) '))
if resp in 'Nn':
break
print('-=' * 30)
print(... |
import logging # use instead of print for more control
from pathlib import Path # filesystem related stuff
import numpy as np # numerical computations
from matplotlib.pyplot import subplots, figure, savefig
import matplotlib.pyplot as plt
from astropy.stats import sigma_clipped_stats # calcua... | import logging # use instead of print for more control
from pathlib import Path # filesystem related stuff
import numpy as np # numerical computations
from matplotlib.pyplot import subplots, figure, savefig
import matplotlib.pyplot as plt
from astropy.stats import sigma_clipped_stats # calcua... |
import socket, threading, hashlib, os, datetime, time, sqlite3, shutil, urllib.request, json, sys
class BotNet:
"""Main Class for the BotNet. Every single line of server code, payload code is inside of this class.
There are many functions inside of the class, where they have many different uses. They vary ... | import socket, threading, hashlib, os, datetime, time, sqlite3, shutil, urllib.request, json, sys
class BotNet:
"""Main Class for the BotNet. Every single line of server code, payload code is inside of this class.
There are many functions inside of the class, where they have many different uses. They vary ... |
import argparse
import torch
import numpy as np
import pathlib
from train_active import finetune_on_queries
from incremental import Incremental
from inference import Predictor
from score import Scorer
import util
import copy
from collections import defaultdict
import logging
import json
from eval_all import ALL
def l... | import argparse
import torch
import numpy as np
import pathlib
from train_active import finetune_on_queries
from incremental import Incremental
from inference import Predictor
from score import Scorer
import util
import copy
from collections import defaultdict
import logging
import json
from eval_all import ALL
def l... |
from _collections import defaultdict
words_with_synonyms = defaultdict(list)
n = int(input())
for _ in range(n):
word = input()
synonym = input()
words_with_synonyms[word].append(synonym)
for word, synonyms in words_with_synonyms.items():
print(f'{word} - {', '.join(synonyms)}')
| from _collections import defaultdict
words_with_synonyms = defaultdict(list)
n = int(input())
for _ in range(n):
word = input()
synonym = input()
words_with_synonyms[word].append(synonym)
for word, synonyms in words_with_synonyms.items():
print(f'{word} - {", ".join(synonyms)}')
|
import functools
import hashlib
import importlib
import json
import multiprocessing
import os
import runpy
import sys
import time
import traceback
import glob
from collections import Counter, defaultdict
from types import ModuleType
from typing import Union, NamedTuple, List, Dict, Iterator, Tuple
import marshmallow
i... | import functools
import hashlib
import importlib
import json
import multiprocessing
import os
import runpy
import sys
import time
import traceback
import glob
from collections import Counter, defaultdict
from types import ModuleType
from typing import Union, NamedTuple, List, Dict, Iterator, Tuple
import marshmallow
i... |
import boto3
import rasterio
import os
import numpy as np
from osgeo import gdal
from botocore.handlers import disable_signing
from typing import List
from datetime import datetime
DATASET_TMP_PATH = "/tmp/tmp.grib2"
GDAL_TMP_FILE = "/tmp/temp.tiff"
FINAL_IMG = "/tmp/final.jpeg"
NOAA_BUCKET = 'noaa-gfs-bdp-pds'
PROCES... | import boto3
import rasterio
import os
import numpy as np
from osgeo import gdal
from botocore.handlers import disable_signing
from typing import List
from datetime import datetime
DATASET_TMP_PATH = "/tmp/tmp.grib2"
GDAL_TMP_FILE = "/tmp/temp.tiff"
FINAL_IMG = "/tmp/final.jpeg"
NOAA_BUCKET = 'noaa-gfs-bdp-pds'
PROCES... |
import os
import poppy
import poppy.utils
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from astropy.table import Table
import astropy.io.fits as fits
import astropy.units as units
from scipy.interpolate import griddata, RegularGridInterpolator
from scipy.ndimage import rotate
from . import ut... | import os
import poppy
import poppy.utils
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from astropy.table import Table
import astropy.io.fits as fits
import astropy.units as units
from scipy.interpolate import griddata, RegularGridInterpolator
from scipy.ndimage import rotate
from . import ut... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from pathlib import Path
import argparse
import json
import math
import os
import sys
import time
import torch
import to... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from pathlib import Path
import argparse
import json
import math
import os
import sys
import time
import torch
import to... |
"""Amazon Redshift Module."""
# pylint: disable=too-many-lines
import logging
import uuid
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
import boto3
import botocore
import pandas as pd
import pyarrow as pa
import redshift_connector
from awswrangler import _data_types
from awswrangler import _d... | """Amazon Redshift Module."""
# pylint: disable=too-many-lines
import logging
import uuid
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
import boto3
import botocore
import pandas as pd
import pyarrow as pa
import redshift_connector
from awswrangler import _data_types
from awswrangler import _d... |
# Copyright 2021 The Layout Parser team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2021 The Layout Parser team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# -*- coding: UTF-8 -*-
"""
@author: hhyo、yyukai
@license: Apache Licence
@file: pgsql.py
@time: 2019/03/29
"""
import re
import psycopg2
import logging
import traceback
import sqlparse
from . import EngineBase
from .models import ResultSet
__author__ = 'hhyo、yyukai'
logger = logging.getLogger('default')
class ... | # -*- coding: UTF-8 -*-
"""
@author: hhyo、yyukai
@license: Apache Licence
@file: pgsql.py
@time: 2019/03/29
"""
import re
import psycopg2
import logging
import traceback
import sqlparse
from . import EngineBase
from .models import ResultSet
__author__ = 'hhyo、yyukai'
logger = logging.getLogger('default')
class ... |
import logging
from stix_shifter_utils.stix_translation.src.json_to_stix import json_to_stix_translator
from stix_shifter.stix_translation import stix_translation
from stix_shifter_modules.splunk.entry_point import EntryPoint
from stix2validator import validate_instance
from stix_shifter_modules.splunk.stix_translation... | import logging
from stix_shifter_utils.stix_translation.src.json_to_stix import json_to_stix_translator
from stix_shifter.stix_translation import stix_translation
from stix_shifter_modules.splunk.entry_point import EntryPoint
from stix2validator import validate_instance
from stix_shifter_modules.splunk.stix_translation... |
import os
from pathlib import Path
from textwrap import dedent
import pytest
from osa.configs import options
from osa.configs.config import cfg
extra_files = Path(os.getenv("OSA_TEST_DATA", "extra"))
datasequence_history_file = extra_files / "history_files/sequence_LST1_04185.0010.history"
calibration_history_file =... | import os
from pathlib import Path
from textwrap import dedent
import pytest
from osa.configs import options
from osa.configs.config import cfg
extra_files = Path(os.getenv("OSA_TEST_DATA", "extra"))
datasequence_history_file = extra_files / "history_files/sequence_LST1_04185.0010.history"
calibration_history_file =... |
import click
import gitlab
import os
import toml
from zipfile import ZipFile
from yaspin import yaspin
from appdirs import user_config_dir, user_data_dir
from pathlib import Path
import platform
import subprocess
CONFIG_FILE_NAME = "glap.toml"
CONFIG_PATH = user_config_dir("glap") + "/" + CONFIG_FILE_NAME
TMP_PATH = u... | import click
import gitlab
import os
import toml
from zipfile import ZipFile
from yaspin import yaspin
from appdirs import user_config_dir, user_data_dir
from pathlib import Path
import platform
import subprocess
CONFIG_FILE_NAME = "glap.toml"
CONFIG_PATH = user_config_dir("glap") + "/" + CONFIG_FILE_NAME
TMP_PATH = u... |
# syntax_style for the console must be one of the supported styles from
# pygments - see here for examples https://help.farbox.com/pygments.html
import re
import warnings
from ast import literal_eval
from typing import Union
from pydantic import validator
from pydantic.color import Color
try:
from qtpy import QT_... | # syntax_style for the console must be one of the supported styles from
# pygments - see here for examples https://help.farbox.com/pygments.html
import re
import warnings
from ast import literal_eval
from typing import Union
from pydantic import validator
from pydantic.color import Color
try:
from qtpy import QT_... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | # Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... |
import unittest
import utils
import parser
import syntax
import mypyvy
import os
from pathlib import Path
import shlex
import subprocess
from typing import List
PROJECT_ROOT = Path(__file__).resolve().parent.parent
class SyntaxTests(unittest.TestCase):
def setUp(self) -> None:
utils.args = mypyvy.parse... | import unittest
import utils
import parser
import syntax
import mypyvy
import os
from pathlib import Path
import shlex
import subprocess
from typing import List
PROJECT_ROOT = Path(__file__).resolve().parent.parent
class SyntaxTests(unittest.TestCase):
def setUp(self) -> None:
utils.args = mypyvy.parse... |
import json
import os
import confuse
import boto3
from botocore.exceptions import ClientError
from cachetools import Cache
required_credentials = [
'aws_access_key',
'aws_secret_key',
'lwa_app_id',
'lwa_client_secret'
]
class MissingCredentials(Exception):
"""
Credentials are missing, see th... | import json
import os
import confuse
import boto3
from botocore.exceptions import ClientError
from cachetools import Cache
required_credentials = [
'aws_access_key',
'aws_secret_key',
'lwa_app_id',
'lwa_client_secret'
]
class MissingCredentials(Exception):
"""
Credentials are missing, see th... |
#!/usr/bin/env python3
"""
Analyze docstrings to detect errors.
If no argument is provided, it does a quick check of docstrings and returns
a csv with all API functions and results of basic checks.
If a function or method is provided in the form "pandas.function",
"pandas.module.class.method", etc. a list of all erro... | #!/usr/bin/env python3
"""
Analyze docstrings to detect errors.
If no argument is provided, it does a quick check of docstrings and returns
a csv with all API functions and results of basic checks.
If a function or method is provided in the form "pandas.function",
"pandas.module.class.method", etc. a list of all erro... |
# -*- coding: utf-8 -*-
"""BigQuery Load Task."""
from pathlib import Path
from typing import Dict, List
from google.cloud import bigquery
from luft.common.column import Column
from luft.common.config import (
BQ_DATA_TYPES, BQ_HIST_DEFAULT_TEMPLATE, BQ_STAGE_DEFAULT_TEMPLATE,
BQ_STAGE_SCHEMA_FORM, GCS_BUCKET... | # -*- coding: utf-8 -*-
"""BigQuery Load Task."""
from pathlib import Path
from typing import Dict, List
from google.cloud import bigquery
from luft.common.column import Column
from luft.common.config import (
BQ_DATA_TYPES, BQ_HIST_DEFAULT_TEMPLATE, BQ_STAGE_DEFAULT_TEMPLATE,
BQ_STAGE_SCHEMA_FORM, GCS_BUCKET... |
from dataclasses import dataclass
from typing import Any, List, Union
import inspect
import itertools
import warnings
import types
import requests
from flask_discord_interactions.models import (
LoadableDataclass, Member, Channel, Role, User, CommandOptionType, ApplicationCommandType, Message
)
@dataclass
class... | from dataclasses import dataclass
from typing import Any, List, Union
import inspect
import itertools
import warnings
import types
import requests
from flask_discord_interactions.models import (
LoadableDataclass, Member, Channel, Role, User, CommandOptionType, ApplicationCommandType, Message
)
@dataclass
class... |
from flask import Flask, request, url_for
app = Flask(__name__)
import html
import json
###############################
###############################
import sys
from os import environ as env
sys.path.append(env['SOAR_HOME'])
import Python_sml_ClientInterface as sml
kernel = sml.Kernel_CreateKernelInCurrentThread... | from flask import Flask, request, url_for
app = Flask(__name__)
import html
import json
###############################
###############################
import sys
from os import environ as env
sys.path.append(env['SOAR_HOME'])
import Python_sml_ClientInterface as sml
kernel = sml.Kernel_CreateKernelInCurrentThread... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
#!/usr/bin/env python3
from pathlib import Path
import csv
import fontTools.ttLib.woff2
import functools
import io
import itertools
import logging
import math
import multiprocessing
import sys
import argparse
FONT_BASE_NAMES = {
"noto": "Noto Color Emoji",
"noto_noflags": "Noto Color Emoji except flags",
... | #!/usr/bin/env python3
from pathlib import Path
import csv
import fontTools.ttLib.woff2
import functools
import io
import itertools
import logging
import math
import multiprocessing
import sys
import argparse
FONT_BASE_NAMES = {
"noto": "Noto Color Emoji",
"noto_noflags": "Noto Color Emoji except flags",
... |
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
import gym
import random
from collections import deque, namedtuple
import logging
from tqdm import tqdm
import argparse
import os
import time
import yaml
im... | import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
import gym
import random
from collections import deque, namedtuple
import logging
from tqdm import tqdm
import argparse
import os
import time
import yaml
im... |
import json
import time
from functools import lru_cache
from multiprocessing import Pool, Process
from threading import Thread, Timer
from typing import Any, Dict, List
from datetime import datetime
import hashlib
import inspect
import requests
import waitress
from bottle import BaseTemplate, Bottle, request, response,... | import json
import time
from functools import lru_cache
from multiprocessing import Pool, Process
from threading import Thread, Timer
from typing import Any, Dict, List
from datetime import datetime
import hashlib
import inspect
import requests
import waitress
from bottle import BaseTemplate, Bottle, request, response,... |
import discord
from discord.ext import commands
import asyncio
import functools
import itertools
import random
import youtube_dl
import async_timeout
try:
import uvloop
except ImportError:
pass
else:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
class VoiceError(Exception):
... | import discord
from discord.ext import commands
import asyncio
import functools
import itertools
import random
import youtube_dl
import async_timeout
try:
import uvloop
except ImportError:
pass
else:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
class VoiceError(Exception):
... |
from typing import Dict, Iterable, List, Optional, Tuple
from discord import Member, Message
async def apply(
last_message: Message, recent_messages: List[Message], config: Dict[str, int]
) -> Optional[Tuple[str, Iterable[Member], Iterable[Message]]]:
"""Detects total mentions exceeding the limit sent by a s... | from typing import Dict, Iterable, List, Optional, Tuple
from discord import Member, Message
async def apply(
last_message: Message, recent_messages: List[Message], config: Dict[str, int]
) -> Optional[Tuple[str, Iterable[Member], Iterable[Message]]]:
"""Detects total mentions exceeding the limit sent by a s... |
# -*- coding: utf-8 -*-
"""
jishaku.paginators
~~~~~~~~~~~~~~~~~~
Paginator-related tools and interfaces for Jishaku.
:copyright: (c) 2020 Devon (Gorialis) R
:license: MIT, see LICENSE for more details.
"""
import asyncio
import collections
import re
import discord
from discord.ext import commands
from jishaku.h... | # -*- coding: utf-8 -*-
"""
jishaku.paginators
~~~~~~~~~~~~~~~~~~
Paginator-related tools and interfaces for Jishaku.
:copyright: (c) 2020 Devon (Gorialis) R
:license: MIT, see LICENSE for more details.
"""
import asyncio
import collections
import re
import discord
from discord.ext import commands
from jishaku.h... |
import json
import zipfile
import vtk
import re
import struct
from .synchronizable_serializer import arrayTypesMapping
METHODS_RENAME = {
"AddTexture": "SetTexture",
"SetUseGradientOpacity": None,
"SetRGBTransferFunction": "SetColor",
}
WRAP_ID_RE = re.compile(r"instance:\${([^}]+)}")
ARRAY_TYPES = {
... | import json
import zipfile
import vtk
import re
import struct
from .synchronizable_serializer import arrayTypesMapping
METHODS_RENAME = {
"AddTexture": "SetTexture",
"SetUseGradientOpacity": None,
"SetRGBTransferFunction": "SetColor",
}
WRAP_ID_RE = re.compile(r"instance:\${([^}]+)}")
ARRAY_TYPES = {
... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright © 2019, SAS Institute Inc., Cary, NC, USA. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import pytest
from six.moves import mock
from sasctl.core import RestObj
from sasctl._services.model_repository import ModelRepository
def test_sklearn_metadata... | #!/usr/bin/env python
# encoding: utf-8
#
# Copyright © 2019, SAS Institute Inc., Cary, NC, USA. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import pytest
from six.moves import mock
from sasctl.core import RestObj
from sasctl._services.model_repository import ModelRepository
def test_sklearn_metadata... |
# ***************************************************************
# Copyright (c) 2021 Jittor. All Rights Reserved.
# Maintainers: Dun Liang <randonlang@gmail.com>.
# This file is subject to the terms and conditions defined in
# file 'LICENSE.txt', which is part of this source code package.
# ************************... | # ***************************************************************
# Copyright (c) 2021 Jittor. All Rights Reserved.
# Maintainers: Dun Liang <randonlang@gmail.com>.
# This file is subject to the terms and conditions defined in
# file 'LICENSE.txt', which is part of this source code package.
# ************************... |
# -*- coding: utf-8 -*-
# Autogenerated by Sphinx on Wed Jan 6 03:48:54 2016
topics = {'assert': u'\nThe "assert" statement\n**********************\n\nAssert statements are a convenient way to insert debugging assertions\ninto a program:\n\n assert_stmt ::= "assert" expression ["," expression]\n\nThe simple form, "a... | # -*- coding: utf-8 -*-
# Autogenerated by Sphinx on Wed Jan 6 03:48:54 2016
topics = {'assert': u'\nThe "assert" statement\n**********************\n\nAssert statements are a convenient way to insert debugging assertions\ninto a program:\n\n assert_stmt ::= "assert" expression ["," expression]\n\nThe simple form, "a... |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2012 thomasv@gitorious
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including witho... | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2012 thomasv@gitorious
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including witho... |
from datetime import datetime
from telegram import Bot
import requests
import tenacity
from tenacity import (
stop_after_attempt,
wait_exponential,
)
import os
from src.util.audio import convert_to_mp3
from src.util.vars import (
TELEGRAM_BOT_TOKEN,
TELEGRAM_ID,
TELEGRAM_INTERVAL_SECONDS,
logge... | from datetime import datetime
from telegram import Bot
import requests
import tenacity
from tenacity import (
stop_after_attempt,
wait_exponential,
)
import os
from src.util.audio import convert_to_mp3
from src.util.vars import (
TELEGRAM_BOT_TOKEN,
TELEGRAM_ID,
TELEGRAM_INTERVAL_SECONDS,
logge... |
import re
import sys
import copy
import types
import inspect
import keyword
import builtins
import functools
import abc
import _thread
from types import FunctionType, GenericAlias
__all__ = ['dataclass',
'field',
'Field',
'FrozenInstanceError',
'InitVar',
'KW_ONL... | import re
import sys
import copy
import types
import inspect
import keyword
import builtins
import functools
import abc
import _thread
from types import FunctionType, GenericAlias
__all__ = ['dataclass',
'field',
'Field',
'FrozenInstanceError',
'InitVar',
'KW_ONL... |
from dataclasses import dataclass
from typing import Optional
from pydub import AudioSegment
from cyberpunk.exceptions import (
TransformationInputParseException,
TransformationProcessException,
)
from cyberpunk.transformations import TransformationInput
@dataclass
class SliceInput:
start: Optional[int... | from dataclasses import dataclass
from typing import Optional
from pydub import AudioSegment
from cyberpunk.exceptions import (
TransformationInputParseException,
TransformationProcessException,
)
from cyberpunk.transformations import TransformationInput
@dataclass
class SliceInput:
start: Optional[int... |
#------IMPORTS-----
#Packages for ETA backend
import json
import etabackend.eta #Available at: https://github.com/timetag/ETA, https://eta.readthedocs.io/en/latest/
import etabackend.tk as etatk
#Packages used for analysis
import numpy as np
from pathlib import Path
import os
import time as t
import LIDAR... | #------IMPORTS-----
#Packages for ETA backend
import json
import etabackend.eta #Available at: https://github.com/timetag/ETA, https://eta.readthedocs.io/en/latest/
import etabackend.tk as etatk
#Packages used for analysis
import numpy as np
from pathlib import Path
import os
import time as t
import LIDAR... |
"""
The :mod:`sklearn.model_selection._validation` module includes classes and
functions to validate the model.
"""
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Gael Varoquaux <gael.varoquaux@normalesup.org>
# Olivier Grisel <olivier.grisel@ensta.org>
# Raghav RV <rvraghav93@gma... | """
The :mod:`sklearn.model_selection._validation` module includes classes and
functions to validate the model.
"""
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Gael Varoquaux <gael.varoquaux@normalesup.org>
# Olivier Grisel <olivier.grisel@ensta.org>
# Raghav RV <rvraghav93@gma... |
import os
import re
import pathlib
import h5py as h5
import numpy as np
from decimal import Decimal
from tqdm import tqdm
import glob
import datajoint as dj
from pipeline import (reference, subject, acquisition, intracellular, behavior, stimulation, virus, utilities)
path = pathlib.Path(dj.config['custom'].get('data_... | import os
import re
import pathlib
import h5py as h5
import numpy as np
from decimal import Decimal
from tqdm import tqdm
import glob
import datajoint as dj
from pipeline import (reference, subject, acquisition, intracellular, behavior, stimulation, virus, utilities)
path = pathlib.Path(dj.config['custom'].get('data_... |
class Customer:
def __init__(self, name, age, id):
self.name = name
self.age = age
self.id = id
self.rented_dvds = []
def __repr__(self):
result = f"{self.id}: {self.name} of age {self.age}" \
f" has {len(self.rented_dvds)} rented DVD"s ({", ".join([x.na... | class Customer:
def __init__(self, name, age, id):
self.name = name
self.age = age
self.id = id
self.rented_dvds = []
def __repr__(self):
result = f"{self.id}: {self.name} of age {self.age}" \
f" has {len(self.rented_dvds)} rented DVD's ({', '.join([x.na... |
import docs
import hashlib
import json
import os
import sys
import util
FLAG_NAME_MAP={"check_output":"Check Output","optimizable":"Optimizable"}
IGNORE_FLAG_NAME=["func","var","var_arg"]
def _add_data(nm,dt):
nm=nm.replace("\\","/")[:255].encode("ascii","ignore")
dt=dt[:16777215]
if (nm[-5:]==b".html"):
dt=... | import docs
import hashlib
import json
import os
import sys
import util
FLAG_NAME_MAP={"check_output":"Check Output","optimizable":"Optimizable"}
IGNORE_FLAG_NAME=["func","var","var_arg"]
def _add_data(nm,dt):
nm=nm.replace("\\","/")[:255].encode("ascii","ignore")
dt=dt[:16777215]
if (nm[-5:]==b".html"):
dt=... |
#!/usr/bin/env python3
# Copyright (c) 2013-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Generate seeds.txt from Pieter's DNS seeder
#
import re
import sys
import dns.resolver
import collect... | #!/usr/bin/env python3
# Copyright (c) 2013-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Generate seeds.txt from Pieter's DNS seeder
#
import re
import sys
import dns.resolver
import collect... |
"""
Optimade support.
"""
import logging
import sys
from collections import namedtuple
from os.path import join
from typing import Dict, Union, List, Optional
from urllib.parse import urlparse
import requests
#from retrying import retry
from pymatgen.core.periodic_table import DummySpecies
from pymatgen.core.structu... | """
Optimade support.
"""
import logging
import sys
from collections import namedtuple
from os.path import join
from typing import Dict, Union, List, Optional
from urllib.parse import urlparse
import requests
#from retrying import retry
from pymatgen.core.periodic_table import DummySpecies
from pymatgen.core.structu... |
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merg... | """
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merg... |
import asyncio
import discord
import html
import json
import random
import time
from random import shuffle
from redbot.core import commands
from redbot.core.data_manager import bundled_data_path
class CardsAgainstHumanity(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.games = []
... | import asyncio
import discord
import html
import json
import random
import time
from random import shuffle
from redbot.core import commands
from redbot.core.data_manager import bundled_data_path
class CardsAgainstHumanity(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.games = []
... |
#!/usr/bin/python3
import os
from UIBox import pkg
def Results(parent):
data = os.popen("apt-cache search " + parent.text, "r").readlines()
if not parent.text:
return [{
"title" : "Start typing the package name",
"subtitle" : "Remember, you can use regular expresions For exampl... | #!/usr/bin/python3
import os
from UIBox import pkg
def Results(parent):
data = os.popen("apt-cache search " + parent.text, "r").readlines()
if not parent.text:
return [{
"title" : "Start typing the package name",
"subtitle" : "Remember, you can use regular expresions For exampl... |
""" Class for writing SNPs.
"""
"""
BSD 3-Clause License
Copyright (c) 2019, Andrew Riha
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyri... | """ Class for writing SNPs.
"""
"""
BSD 3-Clause License
Copyright (c) 2019, Andrew Riha
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyri... |
import re
from typing import Union, List, Callable, Match, Optional
__all__ = ["create_validator"]
def create_validator(
valid_characters: Union[str, List[str]], case_sensitive: bool = True
) -> Callable[[str], Optional[Match[str]]]:
"""Function that generates a callable, regular-expression based sequence va... | import re
from typing import Union, List, Callable, Match, Optional
__all__ = ["create_validator"]
def create_validator(
valid_characters: Union[str, List[str]], case_sensitive: bool = True
) -> Callable[[str], Optional[Match[str]]]:
"""Function that generates a callable, regular-expression based sequence va... |
# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and
# Technical University of Darmstadt.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source ... | # Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and
# Technical University of Darmstadt.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source ... |
# 73
# Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre: a) Os 5 primeiros times. b) Os últimos 4 colocados. c) Times em ordem alfabética. d) Em que posição está o time da Chapecoense.
times = ('Corinthians', 'Palmeiras', 'Santo... | # 73
# Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre: a) Os 5 primeiros times. b) Os últimos 4 colocados. c) Times em ordem alfabética. d) Em que posição está o time da Chapecoense.
times = ('Corinthians', 'Palmeiras', 'Santo... |
#!/usr/bin/env python3.9
"""
This program returns a complete list of all the runs awaiting verificaiton for a given game
(argv[1]) and optionally a second given game (argv[2]).
"""
from datetime import timedelta
from sys import argv, exit, stderr
from traceback import print_exception
from typing import Literal
from ... | #!/usr/bin/env python3.9
"""
This program returns a complete list of all the runs awaiting verificaiton for a given game
(argv[1]) and optionally a second given game (argv[2]).
"""
from datetime import timedelta
from sys import argv, exit, stderr
from traceback import print_exception
from typing import Literal
from ... |
import lvgl as lv
import ujson as json
from cdp import fsm, group, scr, _users_list, motor_pines, turn_counter
from cdp.classes import Usuario
from utime import sleep, sleep_ms
import lodepng as png
from imagetools import get_png_info, open_png
def draw_calib_screen(which):
group.remove_all_objs()
lv.obj.clea... | import lvgl as lv
import ujson as json
from cdp import fsm, group, scr, _users_list, motor_pines, turn_counter
from cdp.classes import Usuario
from utime import sleep, sleep_ms
import lodepng as png
from imagetools import get_png_info, open_png
def draw_calib_screen(which):
group.remove_all_objs()
lv.obj.clea... |
"""
pyaud.utils
===========
Utility classes and functions.
"""
from __future__ import annotations
import functools as _functools
import hashlib as _hashlib
import logging as _logging
import os as _os
import shutil as _shutil
import sys as _sys
from pathlib import Path as _Path
from subprocess import PIPE as _PIPE
fro... | """
pyaud.utils
===========
Utility classes and functions.
"""
from __future__ import annotations
import functools as _functools
import hashlib as _hashlib
import logging as _logging
import os as _os
import shutil as _shutil
import sys as _sys
from pathlib import Path as _Path
from subprocess import PIPE as _PIPE
fro... |
#Libraries
import base64
import datetime
from io import BytesIO, StringIO
import os
import pandas as pd
import streamlit as st
import plotly
import yfinance as yf
from technical_analysis import download_data, portfolio_return, benchmark_return, wealth_plot,accumulated_return_plot, drawdawn_plot, allocation_plot, day_r... | #Libraries
import base64
import datetime
from io import BytesIO, StringIO
import os
import pandas as pd
import streamlit as st
import plotly
import yfinance as yf
from technical_analysis import download_data, portfolio_return, benchmark_return, wealth_plot,accumulated_return_plot, drawdawn_plot, allocation_plot, day_r... |
import aiohttp
import asyncio
import json
import logging
import pytest
import pytest_asyncio
from chia.daemon.server import WebSocketServer
from chia.server.outbound_message import NodeType
from chia.types.peer_info import PeerInfo
from tests.block_tools import BlockTools, create_block_tools_async
from chia.util.ints ... | import aiohttp
import asyncio
import json
import logging
import pytest
import pytest_asyncio
from chia.daemon.server import WebSocketServer
from chia.server.outbound_message import NodeType
from chia.types.peer_info import PeerInfo
from tests.block_tools import BlockTools, create_block_tools_async
from chia.util.ints ... |
from datetime import timezone
from typing import Dict, Tuple
import dateparser
import urllib3
from CommonServerPython import *
''' IMPORTS '''
# Disable insecure warnings
urllib3.disable_warnings()
OCCURRED_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
REQUEST_HEADERS = {
'Accept': 'application/json,text/html,application/xht... | from datetime import timezone
from typing import Dict, Tuple
import dateparser
import urllib3
from CommonServerPython import *
''' IMPORTS '''
# Disable insecure warnings
urllib3.disable_warnings()
OCCURRED_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
REQUEST_HEADERS = {
'Accept': 'application/json,text/html,application/xht... |
from enum import Enum
import numpy as np
import casadi
from casadi import dot, sum1
from .penalty import PenaltyType, PenaltyFunctionAbstract
from ..misc.enums import Instant
from ..misc.options_lists import OptionList, OptionGeneric
class ObjectiveOption(OptionGeneric):
def __init__(
self, objective, in... | from enum import Enum
import numpy as np
import casadi
from casadi import dot, sum1
from .penalty import PenaltyType, PenaltyFunctionAbstract
from ..misc.enums import Instant
from ..misc.options_lists import OptionList, OptionGeneric
class ObjectiveOption(OptionGeneric):
def __init__(
self, objective, in... |
'''
Kattis - onechicken
Just do.
Time: O(1), Space: O(1)
'''
a, b = map(int, input().split())
if b > a:
print(f"Dr. Chaz will have {b-a} piece{"s" if b-a > 1 else ""} of chicken left over!")
else:
print(f"Dr. Chaz needs {a-b} more piece{"s" if a-b > 1 else ""} of chicken!") | '''
Kattis - onechicken
Just do.
Time: O(1), Space: O(1)
'''
a, b = map(int, input().split())
if b > a:
print(f"Dr. Chaz will have {b-a} piece{'s' if b-a > 1 else ''} of chicken left over!")
else:
print(f"Dr. Chaz needs {a-b} more piece{'s' if a-b > 1 else ''} of chicken!") |
# -*- coding: utf-8 -*-
from abc import ABC
from pathlib import Path
import pandas as pd
import scrapy
from src.crawl.utils import cleanup
from settings import YEAR, CRAWLING_OUTPUT_FOLDER
BASE_URl = "http://progcours.hers.be/cocoon/cours/{}.html"
PROG_DATA_PATH = Path(__file__).parent.absolute().joinpath(
f'../... | # -*- coding: utf-8 -*-
from abc import ABC
from pathlib import Path
import pandas as pd
import scrapy
from src.crawl.utils import cleanup
from settings import YEAR, CRAWLING_OUTPUT_FOLDER
BASE_URl = "http://progcours.hers.be/cocoon/cours/{}.html"
PROG_DATA_PATH = Path(__file__).parent.absolute().joinpath(
f'../... |
# Copyright 2022 The Sigstore Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | # Copyright 2022 The Sigstore Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
"""
EBuild Daemon (ebd), main high level interface to ebuild execution env.
Wraps :obj:`pkgcore.ebuild.processor` functionality into a higher level
api, for example per phase methods.
"""
__all__ = (
"ebd", "setup_mixin", "install_op", "uninstall_op", "replace_op",
"buildable", "binpkg_localize")
import errn... | """
EBuild Daemon (ebd), main high level interface to ebuild execution env.
Wraps :obj:`pkgcore.ebuild.processor` functionality into a higher level
api, for example per phase methods.
"""
__all__ = (
"ebd", "setup_mixin", "install_op", "uninstall_op", "replace_op",
"buildable", "binpkg_localize")
import errn... |
"""jc - JSON CLI output utility `vmstat` command output parser
Options supported: `-a`, `-w`, `-d`, `-t`
The `epoch` calculated timestamp field is naive (i.e. based on the local time of the system the parser is run on)
The `epoch_utc` calculated timestamp field is timezone-aware and is only available if the timezone... | """jc - JSON CLI output utility `vmstat` command output parser
Options supported: `-a`, `-w`, `-d`, `-t`
The `epoch` calculated timestamp field is naive (i.e. based on the local time of the system the parser is run on)
The `epoch_utc` calculated timestamp field is timezone-aware and is only available if the timezone... |
import os
import argparse
from glob import glob
def list_models():
parser = argparse.ArgumentParser(description= 'list available trained models for pyapetnet')
parser.add_argument('--model_path', help = 'absolute path of directory containing trained models',
default = None)
... | import os
import argparse
from glob import glob
def list_models():
parser = argparse.ArgumentParser(description= 'list available trained models for pyapetnet')
parser.add_argument('--model_path', help = 'absolute path of directory containing trained models',
default = None)
... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... | # -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
import copy
import logging
from http import HTTPStatus
from typing import Any, Dict, List, Optional
import requests
from flask import current_app as app
from lighthouse.constants import (
FIELD_COG_BARCODE,
FIELD_COORDINATE,
FIELD_DART_CONTROL,
FIELD_DART_DESTINATION_BARCODE,
FIELD_DART_DESTINATION... | import copy
import logging
from http import HTTPStatus
from typing import Any, Dict, List, Optional
import requests
from flask import current_app as app
from lighthouse.constants import (
FIELD_COG_BARCODE,
FIELD_COORDINATE,
FIELD_DART_CONTROL,
FIELD_DART_DESTINATION_BARCODE,
FIELD_DART_DESTINATION... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.