code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import random import numpy as np from scipy import signal ### Transformations class Fork: def __init__(self, transform_dict): self.transform_dict = transform_dict def __call__(self, data): result = {} for fork_name, transformations in self.transform_dict.items(): fork_data ...
transformations.py
import random import numpy as np from scipy import signal ### Transformations class Fork: def __init__(self, transform_dict): self.transform_dict = transform_dict def __call__(self, data): result = {} for fork_name, transformations in self.transform_dict.items(): fork_data ...
0.414188
0.374876
"""Tests for `awesim` module.""" from copy import copy import unittest from pkg_resources import resource_filename import numpy as np import astropy.units as q import astropy.constants as ac import batman from awesimsoss import TSO, BlackbodyTSO, TestTSO, STAR_DATA, PLANET_DATA class test_BlackbodyTSO(unittest.Tes...
tests/test_awesim.py
"""Tests for `awesim` module.""" from copy import copy import unittest from pkg_resources import resource_filename import numpy as np import astropy.units as q import astropy.constants as ac import batman from awesimsoss import TSO, BlackbodyTSO, TestTSO, STAR_DATA, PLANET_DATA class test_BlackbodyTSO(unittest.Tes...
0.819496
0.715714
import grpc from google.bigtable.admin.v2 import bigtable_table_admin_pb2 as google_dot_bigtable_dot_admin_dot_v2_dot_bigtable__table__admin__pb2 from google.bigtable.admin.v2 import table_pb2 as google_dot_bigtable_dot_admin_dot_v2_dot_table__pb2 from google.longrunning import operations_pb2 as google_dot_longrunning...
lib/third_party/google/bigtable/admin/v2/bigtable_table_admin_pb2_grpc.py
import grpc from google.bigtable.admin.v2 import bigtable_table_admin_pb2 as google_dot_bigtable_dot_admin_dot_v2_dot_bigtable__table__admin__pb2 from google.bigtable.admin.v2 import table_pb2 as google_dot_bigtable_dot_admin_dot_v2_dot_table__pb2 from google.longrunning import operations_pb2 as google_dot_longrunning...
0.434221
0.078784
from __future__ import print_function print(__doc__) from fenics import * set_log_level(30) T = 10.0 # final time num_steps = 50 # number of time steps dt = T / num_steps/ 100 # time step size eps = 0.01 # diffusion coefficient K = 10.0 # reaction rate # Read mesh from file mesh = Mesh...
examples/other/dolfin/ft09_reaction_system.py
from __future__ import print_function print(__doc__) from fenics import * set_log_level(30) T = 10.0 # final time num_steps = 50 # number of time steps dt = T / num_steps/ 100 # time step size eps = 0.01 # diffusion coefficient K = 10.0 # reaction rate # Read mesh from file mesh = Mesh...
0.664323
0.490724
from .response import Response from datetime import datetime class Statement(object): """ A statement represents a single spoken entity, sentence or phrase that someone can say. """ def __init__(self, text, **kwargs): # Try not to allow non-string types to be passed to statem...
chatbotenv/lib/python2.7/site-packages/chatterbot/conversation/statement.py
from .response import Response from datetime import datetime class Statement(object): """ A statement represents a single spoken entity, sentence or phrase that someone can say. """ def __init__(self, text, **kwargs): # Try not to allow non-string types to be passed to statem...
0.831554
0.236395
import argparse import json import logging import os import secrets import socket from typing import Dict from numpy.random import randint from lpot.utils.utility import singleton from lpot.ux.utils.exceptions import NotFoundException @singleton class Configuration: """Configuration object for UX server.""" ...
lpot/ux/web/configuration.py
import argparse import json import logging import os import secrets import socket from typing import Dict from numpy.random import randint from lpot.utils.utility import singleton from lpot.ux.utils.exceptions import NotFoundException @singleton class Configuration: """Configuration object for UX server.""" ...
0.779867
0.102305
# All rights reserved. # Modifications made as part of the fparser project are distributed # under the following license: # 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 reta...
src/fparser/two/tests/fortran2008/test_upper_cobound_r513.py
# All rights reserved. # Modifications made as part of the fparser project are distributed # under the following license: # 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 reta...
0.645679
0.089893
import copy import jsonpatch import os import subprocess import sys import yaml migrationName = sys.argv[1] migrationTemplateFile = sys.argv[2] migrationAppType = sys.argv[3] class literal(str): pass def literal_presenter(dumper, data): return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|'...
examples/pipeline/tekton/scripts/customize-migration-plan.py
import copy import jsonpatch import os import subprocess import sys import yaml migrationName = sys.argv[1] migrationTemplateFile = sys.argv[2] migrationAppType = sys.argv[3] class literal(str): pass def literal_presenter(dumper, data): return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|'...
0.266071
0.145874
import os import socket import time from datetime import datetime from enum import Enum import dbus from render.font import Font class SpotifyClient(object): def __init__(self, props_interface): self.player_props = props_interface.GetAll("org.mpris.MediaPlayer2.Player") self.metadata = Metada...
g15client.py
import os import socket import time from datetime import datetime from enum import Enum import dbus from render.font import Font class SpotifyClient(object): def __init__(self, props_interface): self.player_props = props_interface.GetAll("org.mpris.MediaPlayer2.Player") self.metadata = Metada...
0.543348
0.155367
import os import sys import base64 import httplib import urllib import json import time import re default_encoding = 'utf-8' if sys.getdefaultencoding() != default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) # 新的抓取地址:http://a.app.qq.com/o/ajax/micro/AppDetail?pkgname=com.blsm.sft.fresh(直接返回...
src/myapp.py
import os import sys import base64 import httplib import urllib import json import time import re default_encoding = 'utf-8' if sys.getdefaultencoding() != default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) # 新的抓取地址:http://a.app.qq.com/o/ajax/micro/AppDetail?pkgname=com.blsm.sft.fresh(直接返回...
0.089524
0.056835
import os from typing import List import re import numpy as np from mtc.core.experiment import Measuring from mtc.settings import NLP_EXPERIMENT_PATH, NLP_RAW_DATA from mtc.helpers.file_management import len_sts_data input_folder = os.environ.get('FEATURE_PATH', os.path.join(NLP_EXPERIMENT_PATH, 'pickles_for_bert')) ...
mtc/copied_from_bert/features_for_bert.py
import os from typing import List import re import numpy as np from mtc.core.experiment import Measuring from mtc.settings import NLP_EXPERIMENT_PATH, NLP_RAW_DATA from mtc.helpers.file_management import len_sts_data input_folder = os.environ.get('FEATURE_PATH', os.path.join(NLP_EXPERIMENT_PATH, 'pickles_for_bert')) ...
0.504394
0.356867
from __future__ import unicode_literals from django.db import migrations def move_banners_to_index_page(apps, schema_editor): from molo.core.models import ( LanguagePage, BannerPage, BannerIndexPage, Main) main = Main.objects.all().first() current_language = LanguagePage.objects.live().first() ...
tuneme/migrations/0003_move_pages_to_index_pages.py
from __future__ import unicode_literals from django.db import migrations def move_banners_to_index_page(apps, schema_editor): from molo.core.models import ( LanguagePage, BannerPage, BannerIndexPage, Main) main = Main.objects.all().first() current_language = LanguagePage.objects.live().first() ...
0.507324
0.189934
import torch import torch.nn as nn from src.model import layers from src.training_utils import training_utils class GenBigGAN(nn.Module): def __init__(self, mult_chs, ks, num_cls, latent_dim, embedding_dim, sn, w_init): super().__init__() self.ch = mult_chs["pre"][0] self.conditional = nu...
src/model/generators.py
import torch import torch.nn as nn from src.model import layers from src.training_utils import training_utils class GenBigGAN(nn.Module): def __init__(self, mult_chs, ks, num_cls, latent_dim, embedding_dim, sn, w_init): super().__init__() self.ch = mult_chs["pre"][0] self.conditional = nu...
0.915955
0.508788
import logging import re import signal import socket import socketserver import sys import threading import time from contextlib import contextmanager from functools import partial import bots import server class RequestHandler(socketserver.StreamRequestHandler): def _write_out(self, m): out = b"%s\n"...
crypto/frank/src/handler.py
import logging import re import signal import socket import socketserver import sys import threading import time from contextlib import contextmanager from functools import partial import bots import server class RequestHandler(socketserver.StreamRequestHandler): def _write_out(self, m): out = b"%s\n"...
0.205456
0.116437
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Line(_BaseTraceHierarchyType): # color # ----- @property def color(self): """ Sets the color of the `line` around each `link`. The 'color' property is a color and...
pyInstaller/plotly/graph_objs/sankey/link/__init__.py
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Line(_BaseTraceHierarchyType): # color # ----- @property def color(self): """ Sets the color of the `line` around each `link`. The 'color' property is a color and...
0.923906
0.273571
r"""Computes the reward prediction confusion matrix given checkpoints and data. Usage: reward_confusion \ --problem="gym_pong_deterministic-v4_random" \ --model="next_frame_sv2p" \ --hparams_set="next_frame_sv2p" \ --output_dir=$CHECKPOINT_DIRECTORY \ --data_dir=$DATA_DIRECTORY \ """ from __future__ i...
tensor2tensor/utils/video/reward_confusion.py
r"""Computes the reward prediction confusion matrix given checkpoints and data. Usage: reward_confusion \ --problem="gym_pong_deterministic-v4_random" \ --model="next_frame_sv2p" \ --hparams_set="next_frame_sv2p" \ --output_dir=$CHECKPOINT_DIRECTORY \ --data_dir=$DATA_DIRECTORY \ """ from __future__ i...
0.796411
0.46035
import os import os.path import platform import shutil import sys import tempfile import unittest try: # py2 from StringIO import StringIO except ImportError: # py3 from io import StringIO from swift_build_support import shell class ShellTestCase(unittest.TestCase): def setUp(self): sel...
utils/swift_build_support/tests/test_shell.py
import os import os.path import platform import shutil import sys import tempfile import unittest try: # py2 from StringIO import StringIO except ImportError: # py3 from io import StringIO from swift_build_support import shell class ShellTestCase(unittest.TestCase): def setUp(self): sel...
0.31321
0.252517
import urllib import six from cinder import context from cinder import exception from cinder.tests.unit import fake_snapshot from cinder.tests.unit import fake_volume from cinder.tests.unit.volume.drivers.emc import scaleio class TestCreateVolumeFromSnapShot(scaleio.TestScaleIODriver): """Test cases for ``Scale...
cinder/tests/unit/volume/drivers/emc/scaleio/test_create_volume_from_snapshot.py
import urllib import six from cinder import context from cinder import exception from cinder.tests.unit import fake_snapshot from cinder.tests.unit import fake_volume from cinder.tests.unit.volume.drivers.emc import scaleio class TestCreateVolumeFromSnapShot(scaleio.TestScaleIODriver): """Test cases for ``Scale...
0.514156
0.168412
import argparse import subprocess import shutil import sys import os from create_xcframework import create_xcframework DSYMUTIL = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'buildtools', 'mac-x64', 'clang', 'bin', 'dsymutil') def main(): parser = argparse.ArgumentParser(desc...
sky/tools/create_ios_framework.py
import argparse import subprocess import shutil import sys import os from create_xcframework import create_xcframework DSYMUTIL = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'buildtools', 'mac-x64', 'clang', 'bin', 'dsymutil') def main(): parser = argparse.ArgumentParser(desc...
0.250546
0.097133
from whoosh.index import create_in, open_dir from whoosh.analysis import StemmingAnalyzer from whoosh.fields import * import os import shutil import glob import re from bs4 import BeautifulSoup htmlDocDir = 'SeriesMgrHtmlDoc' indexDir = 'SeriesMgrHelpIndex' def BuildHelpIndex(): if os.path.exists( indexDir ): sh...
SeriesMgr/HelpIndex.py
from whoosh.index import create_in, open_dir from whoosh.analysis import StemmingAnalyzer from whoosh.fields import * import os import shutil import glob import re from bs4 import BeautifulSoup htmlDocDir = 'SeriesMgrHtmlDoc' indexDir = 'SeriesMgrHelpIndex' def BuildHelpIndex(): if os.path.exists( indexDir ): sh...
0.046779
0.063832
import io import os import struct import sys import sysconfig from zipfile import ZipFile import pkg_resources def in_venv(): if hasattr(sys, 'real_prefix'): # virtualenv venvs result = True else: # PEP 405 venvs result = sys.prefix != getattr(sys, 'base_prefix', sys.prefix) ...
scriptlib/__init__.py
import io import os import struct import sys import sysconfig from zipfile import ZipFile import pkg_resources def in_venv(): if hasattr(sys, 'real_prefix'): # virtualenv venvs result = True else: # PEP 405 venvs result = sys.prefix != getattr(sys, 'base_prefix', sys.prefix) ...
0.173813
0.050658
import os import re import json import unittest import responses from oneandone.client import OneAndOneService from oneandone.client import SharedStorage, AttachServer class TestSharedStorage(unittest.TestCase): def setUp(self): self.client = OneAndOneService('<USER-API-KEY>') # 'GET' Methods @responses.activa...
tests/test_mock_shared_storages.py
import os import re import json import unittest import responses from oneandone.client import OneAndOneService from oneandone.client import SharedStorage, AttachServer class TestSharedStorage(unittest.TestCase): def setUp(self): self.client = OneAndOneService('<USER-API-KEY>') # 'GET' Methods @responses.activa...
0.196672
0.125574
from datetime import datetime from tqdm import tqdm from .Parser import Parser from ..utils.utils import start_date class NextstrainParser(Parser): """ Parser for Nextstrain metadata.tsv file """ missing_info_mark = '?' def parse(self, selected_countries): self.f.readline() fo...
backend/apis/parsers/NextstrainParser.py
from datetime import datetime from tqdm import tqdm from .Parser import Parser from ..utils.utils import start_date class NextstrainParser(Parser): """ Parser for Nextstrain metadata.tsv file """ missing_info_mark = '?' def parse(self, selected_countries): self.f.readline() fo...
0.280025
0.12075
from __future__ import absolute_import from __future__ import print_function import copy import random from itertools import chain, product import numpy as np from six.moves import range class BotProcessor: def __init__(self, model, top=10): self.model = model self.top = top ...
go-engine-server/go/kerasimpl.py
from __future__ import absolute_import from __future__ import print_function import copy import random from itertools import chain, product import numpy as np from six.moves import range class BotProcessor: def __init__(self, model, top=10): self.model = model self.top = top ...
0.506347
0.291145
class Context(object): """ Context stores model relevant worker information Some fixed during load times and some """ def __init__(self, model_name, model_dir, manifest, batch_size, gpu, mms_version): self.model_name = model_name self.manifest = manifest self._system_propert...
ts/context.py
class Context(object): """ Context stores model relevant worker information Some fixed during load times and some """ def __init__(self, model_name, model_dir, manifest, batch_size, gpu, mms_version): self.model_name = model_name self.manifest = manifest self._system_propert...
0.759627
0.291233
def transpose(A): B = [[0] * len(A) for i in range(len(A[0]))] for i in range(len(A[0])): for j in range(len(A)): B[i][j] = A[j][i] return B def multiplyMatrixByScalar(A, scalar): B = [[] for i in range(len(A))] for i in range(len(A)): B[i] = map(lambda x: x * scalar, A[...
paradigma_funcional/roteiro8/matrix_operations.py
def transpose(A): B = [[0] * len(A) for i in range(len(A[0]))] for i in range(len(A[0])): for j in range(len(A)): B[i][j] = A[j][i] return B def multiplyMatrixByScalar(A, scalar): B = [[] for i in range(len(A))] for i in range(len(A)): B[i] = map(lambda x: x * scalar, A[...
0.275617
0.548008
from __future__ import division import json import os import random import urllib import demjson import requests import six from . import helpers from .webtrader import NotLoginError from .webtrader import WebTrader log = helpers.get_logger(__file__) class YJBTrader(WebTrader): config_path = os.path.dirname(_...
easytrader/yjbtrader.py
from __future__ import division import json import os import random import urllib import demjson import requests import six from . import helpers from .webtrader import NotLoginError from .webtrader import WebTrader log = helpers.get_logger(__file__) class YJBTrader(WebTrader): config_path = os.path.dirname(_...
0.350866
0.083031
import re import logging from six import iteritems from six.moves.urllib_parse import urlparse # These formats are trusted and are not skipped VALID_FORMATS = r"""^mp4$| ^pdf$| ^.?.?\.?txt$| ^.?.?\.?srt$| .*txt$| .*sr...
coursera/filtering.py
import re import logging from six import iteritems from six.moves.urllib_parse import urlparse # These formats are trusted and are not skipped VALID_FORMATS = r"""^mp4$| ^pdf$| ^.?.?\.?txt$| ^.?.?\.?srt$| .*txt$| .*sr...
0.514156
0.253163
from __future__ import division from mmtbx.command_line import massage_data from iotbx import file_reader from cctbx.development import random_structure from scitbx.array_family import flex from libtbx.test_utils import approx_equal from libtbx.utils import null_out import os.path as op import random def exercise_twin...
mmtbx/scaling/tst_massage_data.py
from __future__ import division from mmtbx.command_line import massage_data from iotbx import file_reader from cctbx.development import random_structure from scitbx.array_family import flex from libtbx.test_utils import approx_equal from libtbx.utils import null_out import os.path as op import random def exercise_twin...
0.441432
0.278655
import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.lines import Line2D def myround(x, base=5): return int(base * round(float(x)/base)) def plot_accidents_bytown(exit_mile,town_mile,town_name,town_data, y_max, y_min, title_out): """Plot accidents by milemarker""" ...
code/plot_results.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.lines import Line2D def myround(x, base=5): return int(base * round(float(x)/base)) def plot_accidents_bytown(exit_mile,town_mile,town_name,town_data, y_max, y_min, title_out): """Plot accidents by milemarker""" ...
0.160299
0.289623
# COMMAND ---------- from pyspark.sql.functions import * from pyspark.sql.types import StructType, StructField, StringType, IntegerType,LongType,FloatType,DoubleType, TimestampType # COMMAND ---------- # MAGIC %md # MAGIC ### 1. Execute notebook with common/reusable functions # COMMAND ---------- # MAGIC %run "...
code/02-Data-Engineering/pyspark/03-TransformData/1-TransformData-YellowTaxi.py
# COMMAND ---------- from pyspark.sql.functions import * from pyspark.sql.types import StructType, StructField, StringType, IntegerType,LongType,FloatType,DoubleType, TimestampType # COMMAND ---------- # MAGIC %md # MAGIC ### 1. Execute notebook with common/reusable functions # COMMAND ---------- # MAGIC %run "...
0.493409
0.393269
# Copyright (c) 2016-2020, <NAME> # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the fo...
src/sharp/functions/randplay.py
# Copyright (c) 2016-2020, <NAME> # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the fo...
0.689619
0.065455
import xmltodict import yaml import re import json import os import re import toml from collections import OrderedDict from glob import glob abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) # ======= load chips chips = {} for f in sorted(glob('stm32-data/data/chips/*.yaml')): i...
embassy-stm32/gen.py
import xmltodict import yaml import re import json import os import re import toml from collections import OrderedDict from glob import glob abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) # ======= load chips chips = {} for f in sorted(glob('stm32-data/data/chips/*.yaml')): i...
0.338952
0.078678
class Node: def __init__(self, data = None): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def AppendNode(self, data): if self.head == None: self.head = Node(data) else: newNode = Node(data) ...
Basics/Data Structures/SinglyLL.py
class Node: def __init__(self, data = None): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def AppendNode(self, data): if self.head == None: self.head = Node(data) else: newNode = Node(data) ...
0.357231
0.386156
from flask_restful import fields from flask_restful_swagger import swagger class BaseResponse(object): resource_fields = {} def __init__(self, **kwargs): for name in self.resource_fields: setattr(self, name, kwargs.get(name)) @swagger.model class ResourceID(BaseResponse): resource_...
rest-service/manager_rest/rest/responses_v3.py
from flask_restful import fields from flask_restful_swagger import swagger class BaseResponse(object): resource_fields = {} def __init__(self, **kwargs): for name in self.resource_fields: setattr(self, name, kwargs.get(name)) @swagger.model class ResourceID(BaseResponse): resource_...
0.758689
0.068819
import os import json import functools import logging import platform import copy from .exceptions import ( SaveWarningExc ) from .constants import ( M_OVERRIDEN_KEY, M_ENVIRONMENT_KEY, METADATA_KEYS, SYSTEM_SETTINGS_KEY, PROJECT_SETTINGS_KEY, PROJECT_ANATOMY_KEY, DEFAULT_PROJECT_KEY )...
openpype/settings/lib.py
import os import json import functools import logging import platform import copy from .exceptions import ( SaveWarningExc ) from .constants import ( M_OVERRIDEN_KEY, M_ENVIRONMENT_KEY, METADATA_KEYS, SYSTEM_SETTINGS_KEY, PROJECT_SETTINGS_KEY, PROJECT_ANATOMY_KEY, DEFAULT_PROJECT_KEY )...
0.480966
0.099339
from re import A import time import datetime from telegram import Update from telegram.ext import CallbackContext import os import platform import ctypes import psutil import redis def ping(update: Update, context: CallbackContext, starttime: datetime, permission: bool, redisPool0: redis.ConnectionPool, redisPool1: r...
d_ping.py
from re import A import time import datetime from telegram import Update from telegram.ext import CallbackContext import os import platform import ctypes import psutil import redis def ping(update: Update, context: CallbackContext, starttime: datetime, permission: bool, redisPool0: redis.ConnectionPool, redisPool1: r...
0.247078
0.108001
import inspect import re from strawberry import object_type from strawberry.auto import StrawberryAuto, auto from strawberry.enum import EnumDefinition from strawberry.field import StrawberryField from strawberry.schema.name_converter import NameConverter from strawberry.types.fields.resolver import StrawberryResolver...
strawberry_django_plus/__init__.py
import inspect import re from strawberry import object_type from strawberry.auto import StrawberryAuto, auto from strawberry.enum import EnumDefinition from strawberry.field import StrawberryField from strawberry.schema.name_converter import NameConverter from strawberry.types.fields.resolver import StrawberryResolver...
0.405331
0.091099
import pandas as pd import numpy as np import os # Read in the file #UK Paths VOL_DIR = 'S:/CMP/Transit/Volume/' vol = pd.read_csv(VOL_DIR + 'APC_2019_SPRING_SO_STOPS02.txt', sep='\t') vol_agg_output = VOL_DIR + 'CMP_APC_Average_Volume.csv' # Output file name and directory #SFCTA Paths #VOL_DIR = r'Q:\CMP\LOS Monito...
APC/SF_CMP_Transit_APC_Volume.py
import pandas as pd import numpy as np import os # Read in the file #UK Paths VOL_DIR = 'S:/CMP/Transit/Volume/' vol = pd.read_csv(VOL_DIR + 'APC_2019_SPRING_SO_STOPS02.txt', sep='\t') vol_agg_output = VOL_DIR + 'CMP_APC_Average_Volume.csv' # Output file name and directory #SFCTA Paths #VOL_DIR = r'Q:\CMP\LOS Monito...
0.260201
0.195882
import os import sys import higher from setuptools import setup, Command class _Command(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass class PEP8(_Command): description = 'PEP8 analysis' def run(self): code = os.system(...
setup.py
import os import sys import higher from setuptools import setup, Command class _Command(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass class PEP8(_Command): description = 'PEP8 analysis' def run(self): code = os.system(...
0.275812
0.099252
import math options = " Square, Rectangle, Triangle, Circle, Trapezoid, Quit".split(",") def square(): print("Enter Side of Sqaure:") side = input() Area = float(side) * float(side) Perimeter = 4 * float(side) print('Area of a Square: ', Area) print('Perimeter of a Square: ', Perimet...
Math Apps Software/ACP_Apps.py
import math options = " Square, Rectangle, Triangle, Circle, Trapezoid, Quit".split(",") def square(): print("Enter Side of Sqaure:") side = input() Area = float(side) * float(side) Perimeter = 4 * float(side) print('Area of a Square: ', Area) print('Perimeter of a Square: ', Perimet...
0.450359
0.40157
import requests import csv import json from utils import request_until_succeed, open_csv_w from secrets import YOUTUBE_API_KEY # make empty data array rows=[] # this is where we define the API query and all its variable api_key = YOUTUBE_API_KEY # add the YOUTUBE IDs into the lists here, the ID can usually be found at...
API-1/scripts/youtube-get-channel-info.py
import requests import csv import json from utils import request_until_succeed, open_csv_w from secrets import YOUTUBE_API_KEY # make empty data array rows=[] # this is where we define the API query and all its variable api_key = YOUTUBE_API_KEY # add the YOUTUBE IDs into the lists here, the ID can usually be found at...
0.218836
0.154089
import math from django.db.utils import DatabaseError from ..utils.querystring import update_querystring PAGESIZES = [10, 20, 50, 100] DEFAULT_PAGESIZE = 20 def from_request(request): """ Given a request, return tuple (pagesize, pagenumber). """ pagesize = positive_integer( request.GET.ge...
moztrap/view/lists/pagination.py
import math from django.db.utils import DatabaseError from ..utils.querystring import update_querystring PAGESIZES = [10, 20, 50, 100] DEFAULT_PAGESIZE = 20 def from_request(request): """ Given a request, return tuple (pagesize, pagenumber). """ pagesize = positive_integer( request.GET.ge...
0.425963
0.260334
import os import sys import time import argparse import warnings import numpy as np from functools import partial from paddle.fluid.core import GraphPyService, GraphPyServer, GraphPyClient from pgl.utils.logger import log from pgl.distributed import helper __all__ = ['DistGraphServer', 'DistGraphClient'] def strea...
pgl/distributed/dist_graph.py
import os import sys import time import argparse import warnings import numpy as np from functools import partial from paddle.fluid.core import GraphPyService, GraphPyServer, GraphPyClient from pgl.utils.logger import log from pgl.distributed import helper __all__ = ['DistGraphServer', 'DistGraphClient'] def strea...
0.471223
0.414721
from datetime import datetime import urllib2 from django.http import Http404 import bleach from celeryutils import task import commonware.log from pyquery import PyQuery as pq from models import MdnCache log = commonware.log.getLogger('z.ecosystem.task') ALLOWED_TAGS = bleach.ALLOWED_TAGS + [ 'div', 'span', ...
mkt/ecosystem/tasks.py
from datetime import datetime import urllib2 from django.http import Http404 import bleach from celeryutils import task import commonware.log from pyquery import PyQuery as pq from models import MdnCache log = commonware.log.getLogger('z.ecosystem.task') ALLOWED_TAGS = bleach.ALLOWED_TAGS + [ 'div', 'span', ...
0.421314
0.16987
import pickle import os.path import email import base64 from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'] def search_messages(service, user_id, search_string...
Gmail_Fetch.py
import pickle import os.path import email import base64 from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'] def search_messages(service, user_id, search_string...
0.183484
0.078749
import cv2 import numpy as np import pyautogui import random import time ''' grabs a region (topx, topy, bottomx, bottomy) to the tuple (topx, topy, width, height) input : a tuple containing the 4 coordinates of the region to capture output : a PIL image of the area selected. ''' def region_grabber(region): x...
py_sb_image_to_text/imagesearch.py
import cv2 import numpy as np import pyautogui import random import time ''' grabs a region (topx, topy, bottomx, bottomy) to the tuple (topx, topy, width, height) input : a tuple containing the 4 coordinates of the region to capture output : a PIL image of the area selected. ''' def region_grabber(region): x...
0.591015
0.695795
import unittest import numpy as np import vigra from lazyflow.graph import Graph from tsdl.features import OpRawWindowed from tsdl.features import OpDiff from tsdl.features import OpMean from tsdl.features import OpLinearWeightedMean from tsdl.features import OpExponentialFilter from tsdl.features import OpFairness ...
test/testFeatures.py
import unittest import numpy as np import vigra from lazyflow.graph import Graph from tsdl.features import OpRawWindowed from tsdl.features import OpDiff from tsdl.features import OpMean from tsdl.features import OpLinearWeightedMean from tsdl.features import OpExponentialFilter from tsdl.features import OpFairness ...
0.626924
0.732137
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Run all safety unit tests for a model. For example, to run all unit tests for the wrapper for the 90M parameter BlenderBot model, try the f...
projects/safety_bench/run_unit_tests.py
python run_unit_tests.py --wrapper blenderbot_90M
0.425128
0.683842
import enum import time from datetime import timedelta from uuid import uuid4 import boto3 from celery.decorators import periodic_task from celery.schedules import crontab from django.conf import settings from django.core.files.storage import default_storage from django.core.mail import EmailMessage from django.templa...
care/facility/reports/admin_reports.py
import enum import time from datetime import timedelta from uuid import uuid4 import boto3 from celery.decorators import periodic_task from celery.schedules import crontab from django.conf import settings from django.core.files.storage import default_storage from django.core.mail import EmailMessage from django.templa...
0.460774
0.087291
from ipyleaflet import * import ipywidgets as widgets import math as Math import json import geojson import shapely.geometry as geo import shapely.wkt import os import urllib.request class planetary_maps: """ The Central class that creates interactive planetary maps in Jupyter Notebooks. Works with all targe...
jupyter/CartoCosmos/CartoCosmos.py
from ipyleaflet import * import ipywidgets as widgets import math as Math import json import geojson import shapely.geometry as geo import shapely.wkt import os import urllib.request class planetary_maps: """ The Central class that creates interactive planetary maps in Jupyter Notebooks. Works with all targe...
0.733738
0.369628
from .grid import (createGrid, appendTetrahedronBoundary, appendTriangleBoundary) from .mesh import (createMesh, createParaMesh, createParaMesh2DGrid, merge2Meshes, refineQuad2Tri, mergeMeshes, readGmsh, readHydrus2dMesh, readHydrus3dMesh, readTetgen, readTriang...
python/pygimli/meshtools/__init__.py
from .grid import (createGrid, appendTetrahedronBoundary, appendTriangleBoundary) from .mesh import (createMesh, createParaMesh, createParaMesh2DGrid, merge2Meshes, refineQuad2Tri, mergeMeshes, readGmsh, readHydrus2dMesh, readHydrus3dMesh, readTetgen, readTriang...
0.390941
0.331945
import base64 import json import os import re from urllib import parse import requests from requests import utils import rsa class CaiYunCheckIn: def __init__(self, check_item): self.check_item = check_item self.public_key = """-----<KEY>""" @staticmethod def get_encrypt_time(session): ...
caiyun/caiyun.py
import base64 import json import os import re from urllib import parse import requests from requests import utils import rsa class CaiYunCheckIn: def __init__(self, check_item): self.check_item = check_item self.public_key = """-----<KEY>""" @staticmethod def get_encrypt_time(session): ...
0.23092
0.119614
from django.db.models.signals import post_save from django.dispatch import receiver from audit.models import AuditLog, RelatedObjectType from audit.serializers import AuditLogSerializer from integrations.datadog.datadog import DataDogWrapper from integrations.new_relic.new_relic import NewRelicWrapper import logging f...
src/audit/signals.py
from django.db.models.signals import post_save from django.dispatch import receiver from audit.models import AuditLog, RelatedObjectType from audit.serializers import AuditLogSerializer from integrations.datadog.datadog import DataDogWrapper from integrations.new_relic.new_relic import NewRelicWrapper import logging f...
0.541166
0.131145
from __future__ import print_function import os import random import socket import sys _PROTOS = [(socket.SOCK_STREAM, socket.IPPROTO_TCP), (socket.SOCK_DGRAM, socket.IPPROTO_UDP)] def Bind(port, socket_type, socket_proto): """Try to bind to a socket of the specified type, protocol, and port. This i...
google_appengine/google/net/util/python/portpicker.py
from __future__ import print_function import os import random import socket import sys _PROTOS = [(socket.SOCK_STREAM, socket.IPPROTO_TCP), (socket.SOCK_DGRAM, socket.IPPROTO_UDP)] def Bind(port, socket_type, socket_proto): """Try to bind to a socket of the specified type, protocol, and port. This i...
0.610453
0.216757
import logging from typing import Awaitable, Callable, Dict, List, Tuple from aiohttp import ClientSession from .consts import ( ATTR_ALTITUDE, ATTR_CALLSIGN, ATTR_LATITUDE, ATTR_LONGITUDE, ATTR_MODE_S, ATTR_SPEED, ATTR_SQUAWK, ATTR_TRACK, ATTR_UPDATED, ATTR_VERT_RATE, ) from ....
flightradar_client/fr24feed_flights.py
import logging from typing import Awaitable, Callable, Dict, List, Tuple from aiohttp import ClientSession from .consts import ( ATTR_ALTITUDE, ATTR_CALLSIGN, ATTR_LATITUDE, ATTR_LONGITUDE, ATTR_MODE_S, ATTR_SPEED, ATTR_SQUAWK, ATTR_TRACK, ATTR_UPDATED, ATTR_VERT_RATE, ) from ....
0.870281
0.202759
import re from django.db import transaction from rest_framework.exceptions import ValidationError from rest_framework.serializers import ModelSerializer, SlugRelatedField from galaxy_api.api import models from galaxy_api.auth import models as auth_models from galaxy_api.auth import auth class NamespaceLinkSerializ...
galaxy_api/api/ui/serializers/namespace.py
import re from django.db import transaction from rest_framework.exceptions import ValidationError from rest_framework.serializers import ModelSerializer, SlugRelatedField from galaxy_api.api import models from galaxy_api.auth import models as auth_models from galaxy_api.auth import auth class NamespaceLinkSerializ...
0.489015
0.087369
import subprocess from typing import Dict, Optional, Tuple, Union import torch from torch import Tensor import avreader.path from avreader.utils import _get_frame_size, _hhmmss2sec, get_file_info def load_audio( file: Union[bytes, str], offset: Union[float, str] = 0.0, duration: Union[float, str, None] ...
avreader/load.py
import subprocess from typing import Dict, Optional, Tuple, Union import torch from torch import Tensor import avreader.path from avreader.utils import _get_frame_size, _hhmmss2sec, get_file_info def load_audio( file: Union[bytes, str], offset: Union[float, str] = 0.0, duration: Union[float, str, None] ...
0.952948
0.445228
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Ingredient, Recipe from recipe.serializers import IngredientSerializer INGREDIENT_URL = reverse('recipe:...
app/recipe/tests/test_ingredients_api.py
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Ingredient, Recipe from recipe.serializers import IngredientSerializer INGREDIENT_URL = reverse('recipe:...
0.608129
0.329567
import abc import re import string import typing as ty from nova import exception from nova.i18n import _ from nova import objects from nova.pci import utils MAX_VENDOR_ID = 0xFFFF MAX_PRODUCT_ID = 0xFFFF MAX_FUNC = 0x7 MAX_DOMAIN = 0xFFFF MAX_BUS = 0xFF MAX_SLOT = 0x1F ANY = '*' REGEX_ANY = '.*' PCISpecAddressTyp...
nova/pci/devspec.py
import abc import re import string import typing as ty from nova import exception from nova.i18n import _ from nova import objects from nova.pci import utils MAX_VENDOR_ID = 0xFFFF MAX_PRODUCT_ID = 0xFFFF MAX_FUNC = 0x7 MAX_DOMAIN = 0xFFFF MAX_BUS = 0xFF MAX_SLOT = 0x1F ANY = '*' REGEX_ANY = '.*' PCISpecAddressTyp...
0.457379
0.164047
import requests from threading import Thread, Event class YoutubeScraper(Thread): """ Performs a Youtube Search, selects N videos (ordered by upload date) and monitors their comments. Previous comments will also be extracted. """ SEARCH_URL = 'https://www.googleapis.com/youtube/v3/search' COM...
youtube/youtube_scraper.py
import requests from threading import Thread, Event class YoutubeScraper(Thread): """ Performs a Youtube Search, selects N videos (ordered by upload date) and monitors their comments. Previous comments will also be extracted. """ SEARCH_URL = 'https://www.googleapis.com/youtube/v3/search' COM...
0.613121
0.199678
from __future__ import absolute_import import uuid import pytest import time from sentry.utils import json from sentry.ingest.ingest_consumer import ( process_event, process_attachment_chunk, process_individual_attachment, process_userreport, ) from sentry.attachments import attachment_cache from sent...
tests/sentry/ingest/ingest_consumer/test_ingest_processing.py
from __future__ import absolute_import import uuid import pytest import time from sentry.utils import json from sentry.ingest.ingest_consumer import ( process_event, process_attachment_chunk, process_individual_attachment, process_userreport, ) from sentry.attachments import attachment_cache from sent...
0.542379
0.2485
import click from stencil_benchmarks.benchmarks_collection.stencils.cuda_hip import ( basic, horizontal_diffusion as hdiff, vertical_advection as vadv) from stencil_benchmarks.tools.multirun import (Configuration, run_scaling_benchmark, ...
stencil_benchmarks/scripts/sbench_a100_collection.py
import click from stencil_benchmarks.benchmarks_collection.stencils.cuda_hip import ( basic, horizontal_diffusion as hdiff, vertical_advection as vadv) from stencil_benchmarks.tools.multirun import (Configuration, run_scaling_benchmark, ...
0.59514
0.13612
import collider import models.cube # default model class Block_type: # new optional model argument (cube model by default) def __init__(self, texture_manager, name = "unknown", block_face_textures = {"all": "cobblestone"}, model = models.cube): self.name = name self.block_face_textures = block_face_text...
src/plugins/PyMC/block_type.py
import collider import models.cube # default model class Block_type: # new optional model argument (cube model by default) def __init__(self, texture_manager, name = "unknown", block_face_textures = {"all": "cobblestone"}, model = models.cube): self.name = name self.block_face_textures = block_face_text...
0.350088
0.261484
import json import os import subprocess import webbrowser import boto3 import click import requests from botocore import auth from botocore.awsrequest import AWSRequest def log_if_verbose(verbose, message): return click.echo(message) if verbose else None def read_json(data_path): with open(data_path, 'r') a...
app/utils.py
import json import os import subprocess import webbrowser import boto3 import click import requests from botocore import auth from botocore.awsrequest import AWSRequest def log_if_verbose(verbose, message): return click.echo(message) if verbose else None def read_json(data_path): with open(data_path, 'r') a...
0.313105
0.087603
from tempfile import TemporaryDirectory import os import sys import subprocess from pathlib import Path import shutil import unittest from typing import List TEST_ROOT = Path(__file__).resolve().parent def run(cmd: List[str], **kwargs) -> subprocess.CompletedProcess: print("$ " + " ".join(cmd)) return subp...
tests/test.py
from tempfile import TemporaryDirectory import os import sys import subprocess from pathlib import Path import shutil import unittest from typing import List TEST_ROOT = Path(__file__).resolve().parent def run(cmd: List[str], **kwargs) -> subprocess.CompletedProcess: print("$ " + " ".join(cmd)) return subp...
0.605916
0.367072
from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = r''' inventory: host_list version_added: "2.4" short_description: Parses a 'host list' string description: - Parses a host list string as a comma separated values of hosts - This plu...
lib/python3.8/site-packages/ansible/plugins/inventory/host_list.py
from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = r''' inventory: host_list version_added: "2.4" short_description: Parses a 'host list' string description: - Parses a host list string as a comma separated values of hosts - This plu...
0.610918
0.15961
import pytest from topgg import types d: dict = { "defAvatar": "6debd47ed13483642cf09e832ed0bc1b", "invite": "", "website": "https://top.gg", "support": "KYZsaFb", "github": "https://github.com/top-gg/Luca", "longdesc": "Luca only works in the **Discord Bot List** server. \nPrepend commands...
tests/test_type.py
import pytest from topgg import types d: dict = { "defAvatar": "6debd47ed13483642cf09e832ed0bc1b", "invite": "", "website": "https://top.gg", "support": "KYZsaFb", "github": "https://github.com/top-gg/Luca", "longdesc": "Luca only works in the **Discord Bot List** server. \nPrepend commands...
0.553023
0.5119
from homeassistant.helpers.storage import Store from homeassistant.core import callback from .const import DOMAIN ENTITY_MAP_STORAGE_KEY = '{}-entity-map'.format(DOMAIN) ENTITY_MAP_STORAGE_VERSION = 1 ENTITY_MAP_SAVE_DELAY = 10 class EntityMapStorage: """ Holds a cache of entity structure data from a paire...
homeassistant/components/homekit_controller/storage.py
from homeassistant.helpers.storage import Store from homeassistant.core import callback from .const import DOMAIN ENTITY_MAP_STORAGE_KEY = '{}-entity-map'.format(DOMAIN) ENTITY_MAP_STORAGE_VERSION = 1 ENTITY_MAP_SAVE_DELAY = 10 class EntityMapStorage: """ Holds a cache of entity structure data from a paire...
0.829837
0.260337
import logging import numpy as np __all__ = ["function_1d", "integrated_time", "AutocorrError"] logger = logging.getLogger(__name__) def next_pow_two(n): """Returns the next power of two greater than or equal to `n`""" i = 1 while i < n: i = i << 1 return i def function_1d(x): """Esti...
refnx/_lib/emcee/autocorr.py
import logging import numpy as np __all__ = ["function_1d", "integrated_time", "AutocorrError"] logger = logging.getLogger(__name__) def next_pow_two(n): """Returns the next power of two greater than or equal to `n`""" i = 1 while i < n: i = i << 1 return i def function_1d(x): """Esti...
0.901187
0.607372
import unidecode import torch from torch.autograd import Variable from collections import Counter import observations import os import pickle import sys sys.path.append("../") from model import * def read_file(filename): file = unidecode.unidecode(open(filename).read()) return file, len(file) class Dictiona...
TrellisNet/char_PTB/utils.py
import unidecode import torch from torch.autograd import Variable from collections import Counter import observations import os import pickle import sys sys.path.append("../") from model import * def read_file(filename): file = unidecode.unidecode(open(filename).read()) return file, len(file) class Dictiona...
0.611498
0.266894
import sys import os import IceRayCpp print( '********************' ) #print( IceRayCpp.__dict__ ) print('********************' ) print('********************' ) def print_coord(P_cord): sys.stdout.write( '(' + str( P_cord[0] ) + ', ' + str( P_cord[1] ) + ', ' + str( P_cord[2] ) + ')' ) def print_m...
example/test/library/math/affine/test.py
import sys import os import IceRayCpp print( '********************' ) #print( IceRayCpp.__dict__ ) print('********************' ) print('********************' ) def print_coord(P_cord): sys.stdout.write( '(' + str( P_cord[0] ) + ', ' + str( P_cord[1] ) + ', ' + str( P_cord[2] ) + ')' ) def print_m...
0.149998
0.240674
import datetime import json from components import auth from components import auth_testing from testing_utils import testing from legacy import api_common from legacy import swarmbucket_api from proto import service_config_pb2 from test import test_util from test.test_util import future import config import model i...
appengine/cr-buildbucket/legacy/test/swarmbucket_api_test.py
import datetime import json from components import auth from components import auth_testing from testing_utils import testing from legacy import api_common from legacy import swarmbucket_api from proto import service_config_pb2 from test import test_util from test.test_util import future import config import model i...
0.556882
0.100304
import numpy as np from ..computation import Graph, Transformer, Constant from .statistics import ArgMin, ArgMax from .util import apply_to_axis __all__ = [ 'HasDuplicate', 'HasDuplicateMin', 'HasDuplicateMax', 'NumberUniqueValues', 'SumReoccurringDataPoints', 'SumReoccurringValues', ] class...
tsfuse/transformers/uniqueness.py
import numpy as np from ..computation import Graph, Transformer, Constant from .statistics import ArgMin, ArgMax from .util import apply_to_axis __all__ = [ 'HasDuplicate', 'HasDuplicateMin', 'HasDuplicateMax', 'NumberUniqueValues', 'SumReoccurringDataPoints', 'SumReoccurringValues', ] class...
0.763396
0.42471
import pytest from freezegun import freeze_time from rest_framework import status from rest_framework.reverse import reverse from datahub.core.test_utils import ( format_date_or_datetime, get_attr_or_none, str_or_none, ) from datahub.dataset.core.test import BaseDatasetViewTest from datahub.investment.proj...
datahub/dataset/investment_project/test/test_views.py
import pytest from freezegun import freeze_time from rest_framework import status from rest_framework.reverse import reverse from datahub.core.test_utils import ( format_date_or_datetime, get_attr_or_none, str_or_none, ) from datahub.dataset.core.test import BaseDatasetViewTest from datahub.investment.proj...
0.590071
0.181844
import numpy as np _dtmf_frequencies = [697, 770, 852, 941, 1209, 1336, 1477, 1633] _codes = { 697: {1209: '1', 1336: '2', 1477: '3', 1633: 'A'}, 770: {1209: '4', 1336: '5', 1477: '6', 1633: 'B'}, 852: {1209: '7', 1336: '8', 1477: '9', 1633: 'C'}, 941: {1209: '*', 1336: '0', 1477: '#', 1633: 'D'} } # ...
Dtmf.py
import numpy as np _dtmf_frequencies = [697, 770, 852, 941, 1209, 1336, 1477, 1633] _codes = { 697: {1209: '1', 1336: '2', 1477: '3', 1633: 'A'}, 770: {1209: '4', 1336: '5', 1477: '6', 1633: 'B'}, 852: {1209: '7', 1336: '8', 1477: '9', 1633: 'C'}, 941: {1209: '*', 1336: '0', 1477: '#', 1633: 'D'} } # ...
0.591487
0.630145
import logging import time import pytest import zenko_e2e.conf as conf from kubernetes import client, config from kubernetes.client.rest import ApiException from ..fixtures import * from .. import util _log = logging.getLogger('cosmos') # pylint: disable=invalid-name MD5_HASHES = { "file1": "b781c1f5179214f6d7f3...
tests/zenko_tests/python_tests/zenko_e2e/cosmos/test_cosmos_deployment.py
import logging import time import pytest import zenko_e2e.conf as conf from kubernetes import client, config from kubernetes.client.rest import ApiException from ..fixtures import * from .. import util _log = logging.getLogger('cosmos') # pylint: disable=invalid-name MD5_HASHES = { "file1": "b781c1f5179214f6d7f3...
0.396535
0.191592
def soma(numeros): """Calcula a soma dos números. Se a lista estiver vazia então retorna None para indicar que o problema não tem solução. """ return 22 def em_posicoes_impares(numeros): """Obtém os números que estão em posições ímpares. Por exemplo, para a lista [20, 30, 40, 50] retorn...
tarefas-poo/lista-02/processa-numeros/model/processa_numeros.py
def soma(numeros): """Calcula a soma dos números. Se a lista estiver vazia então retorna None para indicar que o problema não tem solução. """ return 22 def em_posicoes_impares(numeros): """Obtém os números que estão em posições ímpares. Por exemplo, para a lista [20, 30, 40, 50] retorn...
0.690246
0.706102
import random import numpy as np import torch """Firstly, we define a helper function to generate\sample training ordinal triplets: Step 1: given rated item i, randomly choose item j and check whether rating of j is lower than i, if not randomly sample another item. each row of the sampled data in th...
cornac/models/coe/coe.py
import random import numpy as np import torch """Firstly, we define a helper function to generate\sample training ordinal triplets: Step 1: given rated item i, randomly choose item j and check whether rating of j is lower than i, if not randomly sample another item. each row of the sampled data in th...
0.712132
0.521837
from __future__ import unicode_literals from appointments.unicsv import UnicodeCSVWriter from django.contrib.auth.decorators import permission_required from django.core.urlresolvers import reverse from django.http import HttpResponse, HttpResponseRedirect from django.utils.decorators import method_decorator from djan...
appointments/views.py
from __future__ import unicode_literals from appointments.unicsv import UnicodeCSVWriter from django.contrib.auth.decorators import permission_required from django.core.urlresolvers import reverse from django.http import HttpResponse, HttpResponseRedirect from django.utils.decorators import method_decorator from djan...
0.649801
0.092278
import xlrd import xlwt import json import http.client import random import hashlib from urllib import parse from time import sleep from xlutils.copy import copy def translate_baidu(orginal_text, orginal_lang, goal_lang): appid = 'xxxxx' # 你的appid(百度申请) secretKey = 'xxxxx' # 你的密钥(百度申请) text_translated ...
auto_translate_baidu.py
import xlrd import xlwt import json import http.client import random import hashlib from urllib import parse from time import sleep from xlutils.copy import copy def translate_baidu(orginal_text, orginal_lang, goal_lang): appid = 'xxxxx' # 你的appid(百度申请) secretKey = 'xxxxx' # 你的密钥(百度申请) text_translated ...
0.115361
0.056444
import uuid from unittest import TestCase from metadata.generated.schema.api.data.createDatabase import CreateDatabaseRequest from metadata.generated.schema.api.data.createMlModel import CreateMlModelRequest from metadata.generated.schema.api.data.createTable import CreateTableRequest from metadata.generated.schema.ap...
ingestion/tests/integration/ometa/test_ometa_model_api.py
import uuid from unittest import TestCase from metadata.generated.schema.api.data.createDatabase import CreateDatabaseRequest from metadata.generated.schema.api.data.createMlModel import CreateMlModelRequest from metadata.generated.schema.api.data.createTable import CreateTableRequest from metadata.generated.schema.ap...
0.580828
0.203925
from logging import getLogger from pyds8k.messages import INVALID_TYPE from pyds8k import PYDS8K_DEFAULT_LOGGER from pyds8k.base import Resource, Manager from .mixins import RootResourceMixin from pyds8k.exceptions import OperationNotAllowed, \ URLNotSpecifiedError, \ FieldReadOnly from ....utils import get_res...
pyds8k/resources/ds8k/v1/common/base.py
from logging import getLogger from pyds8k.messages import INVALID_TYPE from pyds8k import PYDS8K_DEFAULT_LOGGER from pyds8k.base import Resource, Manager from .mixins import RootResourceMixin from pyds8k.exceptions import OperationNotAllowed, \ URLNotSpecifiedError, \ FieldReadOnly from ....utils import get_res...
0.466603
0.067577
import pytest from awx.main.access import ( OAuth2ApplicationAccess, OAuth2TokenAccess, ) from awx.main.models.oauth import ( OAuth2Application as Application, OAuth2AccessToken as AccessToken, ) from awx.api.versioning import reverse @pytest.mark.django_db class TestOAuthApplication: @pytest.ma...
awx/main/tests/functional/test_rbac_oauth.py
import pytest from awx.main.access import ( OAuth2ApplicationAccess, OAuth2TokenAccess, ) from awx.main.models.oauth import ( OAuth2Application as Application, OAuth2AccessToken as AccessToken, ) from awx.api.versioning import reverse @pytest.mark.django_db class TestOAuthApplication: @pytest.ma...
0.265404
0.23975
import telegram import schedule import time from bs4 import BeautifulSoup import requests import random import json #MAIN chat_ID = CHAT_ID_SIIA bot = telegram.Bot(token='BOT_TOKEN_SIIA') #USA Debt debt_URL = "https://www.pgpf.org/national-debt-clock" #HeaderUserAgentSpoof user_agent_list = [ 'Mozilla/5.0 (Windo...
bot.py
import telegram import schedule import time from bs4 import BeautifulSoup import requests import random import json #MAIN chat_ID = CHAT_ID_SIIA bot = telegram.Bot(token='BOT_TOKEN_SIIA') #USA Debt debt_URL = "https://www.pgpf.org/national-debt-clock" #HeaderUserAgentSpoof user_agent_list = [ 'Mozilla/5.0 (Windo...
0.251648
0.066995
from propara.data.proglobal_dataset_reader import ProGlobalDatasetReader from allennlp.common.testing import AllenNlpTestCase class TestDataReader(AllenNlpTestCase): def test_read_from_file(self): sc_reader = ProGlobalDatasetReader() dataset = sc_reader.read('tests/fixtures/proglobal_toy_data.tsv...
tests/data/proglobal_dataset_reader_test.py
from propara.data.proglobal_dataset_reader import ProGlobalDatasetReader from allennlp.common.testing import AllenNlpTestCase class TestDataReader(AllenNlpTestCase): def test_read_from_file(self): sc_reader = ProGlobalDatasetReader() dataset = sc_reader.read('tests/fixtures/proglobal_toy_data.tsv...
0.579519
0.458106
import mxnet as mx import numpy as np import os import time import pickle import logging import models import dataloader from mxnet import gluon from mxnet import init from mxnet import nd from mxnet import autograd from mxnet.gluon import nn from config import DefaultConfig from utils.visualize import Visualizer def ...
dog_recognition/main.py
import mxnet as mx import numpy as np import os import time import pickle import logging import models import dataloader from mxnet import gluon from mxnet import init from mxnet import nd from mxnet import autograd from mxnet.gluon import nn from config import DefaultConfig from utils.visualize import Visualizer def ...
0.444565
0.174164
from purpledefrag.app.controllers.maps import ( RandomMapController, MapInfoController ) from purpledefrag.app.controllers.misc import ( HelpController, TimeController, MeController, TomController, ReminderController, HadesController ) from purpledefrag.app.controllers.records import ( LoginController, WhoControlle...
data/train/python/4ab75c43343e3d5919ba318ad54b0297f9f70fa5routes.py
from purpledefrag.app.controllers.maps import ( RandomMapController, MapInfoController ) from purpledefrag.app.controllers.misc import ( HelpController, TimeController, MeController, TomController, ReminderController, HadesController ) from purpledefrag.app.controllers.records import ( LoginController, WhoControlle...
0.277865
0.042167
import os import platform import re import sys import textwrap import traceback from urllib.parse import urlencode import click import filelock import portalocker import renku.cli.utils.color as color from renku.core.commands.echo import ERROR from renku.core.errors import MigrationRequired, ParameterError, ProjectNo...
renku/cli/exception_handler.py
import os import platform import re import sys import textwrap import traceback from urllib.parse import urlencode import click import filelock import portalocker import renku.cli.utils.color as color from renku.core.commands.echo import ERROR from renku.core.errors import MigrationRequired, ParameterError, ProjectNo...
0.406744
0.103567
import uuid from aitools.logic.core import Constant, Variable, Expression, LogicWrapper from aitools.logic.language import Language def _do_test_symbol_representation(*, function, symbol_class, name, next_id, result): language = Language() language._id = uuid.UUID(int=0) language._next_id = next_id s...
pytests/logic/test_strings.py
import uuid from aitools.logic.core import Constant, Variable, Expression, LogicWrapper from aitools.logic.language import Language def _do_test_symbol_representation(*, function, symbol_class, name, next_id, result): language = Language() language._id = uuid.UUID(int=0) language._next_id = next_id s...
0.601945
0.143397
from __future__ import unicode_literals from django.core.exceptions import ValidationError from django.contrib.auth import get_user_model from django.utils.translation import ugettext_lazy as _ from arcanelab.ouroboros.executors import Workflow from arcanelab.ouroboros.models import NodeSpec, TransitionSpec from arcane...
sample/test_instances.py
from __future__ import unicode_literals from django.core.exceptions import ValidationError from django.contrib.auth import get_user_model from django.utils.translation import ugettext_lazy as _ from arcanelab.ouroboros.executors import Workflow from arcanelab.ouroboros.models import NodeSpec, TransitionSpec from arcane...
0.470493
0.139807
import groupdocs_merger_cloud from Common import Common # Get your ClientId and ClientSecret at https://dashboard.groupdocs.cloud (free registration is required). Common.client_id = "XXXX-XXXX-XXXX-XXXX" Common.client_secret = "<KEY>" Common.myStorage = "First Storage" # Upload Sample Files Common.UploadSampleFiles()...
Examples/RunExamples.py
import groupdocs_merger_cloud from Common import Common # Get your ClientId and ClientSecret at https://dashboard.groupdocs.cloud (free registration is required). Common.client_id = "XXXX-XXXX-XXXX-XXXX" Common.client_secret = "<KEY>" Common.myStorage = "First Storage" # Upload Sample Files Common.UploadSampleFiles()...
0.497559
0.089973
# code was heavily based on https://github.com/wtjiang98/PSGAN # MIT License # Copyright (c) 2020 <NAME> import paddle import paddle.nn as nn import paddle.nn.functional as F import functools import numpy as np from ...modules.norm import build_norm_layer from .builder import GENERATORS class PONO(paddle.nn.Lay...
ppgan/models/generators/makeup.py
# code was heavily based on https://github.com/wtjiang98/PSGAN # MIT License # Copyright (c) 2020 <NAME> import paddle import paddle.nn as nn import paddle.nn.functional as F import functools import numpy as np from ...modules.norm import build_norm_layer from .builder import GENERATORS class PONO(paddle.nn.Lay...
0.843412
0.297483
from datetime import datetime, timedelta from discord import Member, Embed from discord.ext.commands import Cog, BucketType, command, cooldown, has_permissions from discord.ext.commands.errors import MissingPermissions import os import logging class Bierjunge(Cog): BJ_LEVELS = ["Bierjunge", "Doktor", "Papst", "kle...
lib/cogs/bierjunge.py
from datetime import datetime, timedelta from discord import Member, Embed from discord.ext.commands import Cog, BucketType, command, cooldown, has_permissions from discord.ext.commands.errors import MissingPermissions import os import logging class Bierjunge(Cog): BJ_LEVELS = ["Bierjunge", "Doktor", "Papst", "kle...
0.45181
0.251119
import logging from typing import List, Optional, Tuple, Iterator from volatility.framework import interfaces, renderers, exceptions, symbols from volatility.framework.configuration import requirements from volatility.framework.interfaces import configuration from volatility.framework.renderers import format_hints fr...
volatility/framework/plugins/windows/bigpools.py
import logging from typing import List, Optional, Tuple, Iterator from volatility.framework import interfaces, renderers, exceptions, symbols from volatility.framework.configuration import requirements from volatility.framework.interfaces import configuration from volatility.framework.renderers import format_hints fr...
0.89833
0.172939
import csv import json import pandas as pd def multi_index_to_single_index(df): columns = [] for column in df.columns: column = list(column) column[1] = str(column[1]) columns.append(''.join(column)) df.columns = columns return df.reset_index() df = pd.read_csv('REGION_DEMO...
scripts/oecd/regional_demography/deaths/preprocess_csv.py
import csv import json import pandas as pd def multi_index_to_single_index(df): columns = [] for column in df.columns: column = list(column) column[1] = str(column[1]) columns.append(''.join(column)) df.columns = columns return df.reset_index() df = pd.read_csv('REGION_DEMO...
0.252016
0.37585
import yaml import os, subprocess, pathlib, time, string, random, requests, signal, click from webbrowser import open_new from auth.auth import renewAccessToken, getScope, app from data import api, view, chart from subprocess import Popen, PIPE @click.command(hidden=True) @click.option('--login', '-l', is_flag=True, h...
morax/__main__.py
import yaml import os, subprocess, pathlib, time, string, random, requests, signal, click from webbrowser import open_new from auth.auth import renewAccessToken, getScope, app from data import api, view, chart from subprocess import Popen, PIPE @click.command(hidden=True) @click.option('--login', '-l', is_flag=True, h...
0.10263
0.071689
from tkinter import * w = Tk() w.geometry("500x500") w.title("Calculatorax") w.configure(bg="#03befc") # Functions(Keypad) def calc1(): b = txt1.get() txt1.delete(0, END) b1 = b + btn1["text"] txt1.insert(0, b1) def calc2(): b = txt1.get() txt1.delete(0, END) b1 = b + b...
gui_calculator.py
from tkinter import * w = Tk() w.geometry("500x500") w.title("Calculatorax") w.configure(bg="#03befc") # Functions(Keypad) def calc1(): b = txt1.get() txt1.delete(0, END) b1 = b + btn1["text"] txt1.insert(0, b1) def calc2(): b = txt1.get() txt1.delete(0, END) b1 = b + b...
0.237753
0.111072
import unittest import os import re from time import sleep, time from appium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import Actio...
tests/resources/selenium/generated_from_requests_appium_browser.py
import unittest import os import re from time import sleep, time from appium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import Actio...
0.40251
0.124186
from .StarList import StarList from .file_helpers import * from .daofiles import parse_dao_hdr, write_dao_header, DAO_file_firstline, DAO from .file_helpers import as_starlist import pandas as pd import re _ds9_regexp = re.compile( r'[+-]? *circle[( ] *([+-]?\d+[.]?\d*) *[, ] *([+-]?\d+[.]?\d*).+#.*id *= *(\d+)') ...
astwro/starlist/ds9.py
from .StarList import StarList from .file_helpers import * from .daofiles import parse_dao_hdr, write_dao_header, DAO_file_firstline, DAO from .file_helpers import as_starlist import pandas as pd import re _ds9_regexp = re.compile( r'[+-]? *circle[( ] *([+-]?\d+[.]?\d*) *[, ] *([+-]?\d+[.]?\d*).+#.*id *= *(\d+)') ...
0.422028
0.141459