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 csv
import datetime
date_index_status = 0
date_index_comment = 0
posts_by_week ={}
posts_by_day = {}
with open('occupy_democrats_all.csv', 'rb') as csvfile:
file_reader = csv.reader(csvfile, delimiter=',')
header = file_reader.next()
for i in range (0, len(header)):
if header[i] == "status_... | occupy_democrats_posts.py | import csv
import datetime
date_index_status = 0
date_index_comment = 0
posts_by_week ={}
posts_by_day = {}
with open('occupy_democrats_all.csv', 'rb') as csvfile:
file_reader = csv.reader(csvfile, delimiter=',')
header = file_reader.next()
for i in range (0, len(header)):
if header[i] == "status_... | 0.071393 | 0.156846 |
from tests.helm_template_generator import render_chart
import pytest
from . import supported_k8s_versions
@pytest.mark.parametrize(
"kube_version",
supported_k8s_versions,
)
class TestStanStatefulSet:
def test_stan_statefulset_defaults(self, kube_version):
"""Test that stan statefulset is good wit... | tests/test_stan_sts.py | from tests.helm_template_generator import render_chart
import pytest
from . import supported_k8s_versions
@pytest.mark.parametrize(
"kube_version",
supported_k8s_versions,
)
class TestStanStatefulSet:
def test_stan_statefulset_defaults(self, kube_version):
"""Test that stan statefulset is good wit... | 0.723895 | 0.494568 |
from __future__ import unicode_literals
from django.shortcuts import render, redirect, get_object_or_404
from ticksys.forms import RegistrationForm, ProfielEditForm
from ticksys.models import Ticket
from django.views.generic.edit import CreateView, UpdateView
from django.core.urlresolvers import reverse_lazy
def inde... | Ticketing_System/ticksys/views.py | from __future__ import unicode_literals
from django.shortcuts import render, redirect, get_object_or_404
from ticksys.forms import RegistrationForm, ProfielEditForm
from ticksys.models import Ticket
from django.views.generic.edit import CreateView, UpdateView
from django.core.urlresolvers import reverse_lazy
def inde... | 0.474875 | 0.089415 |
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import norm
from sklearn.datasets import make_regression
from sklearn.model_selection import KFold
import celer
from libsvmdata import fetch_libsvm
from sparse_ho import ImplicitForward
from sparse_ho import grad_search, hyperopt_wrapper
from sparse... | expes/expe_lasso/plot_lasso_pred.py | import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import norm
from sklearn.datasets import make_regression
from sklearn.model_selection import KFold
import celer
from libsvmdata import fetch_libsvm
from sparse_ho import ImplicitForward
from sparse_ho import grad_search, hyperopt_wrapper
from sparse... | 0.76533 | 0.446072 |
import collections
import functools
import ipaddress
import itertools
import random
from . import data
__all__ = ['encode', 'decode']
__version__ = '0.1.3'
utf8_lengths = [(0, 7), (8, 11), (12, 16), (17, 21)]
confusion_constraints = {
'multi-octet': lambda bytestr: any(num >= 0b11000000 for num in bytestr)... | i_dunno/__init__.py | import collections
import functools
import ipaddress
import itertools
import random
from . import data
__all__ = ['encode', 'decode']
__version__ = '0.1.3'
utf8_lengths = [(0, 7), (8, 11), (12, 16), (17, 21)]
confusion_constraints = {
'multi-octet': lambda bytestr: any(num >= 0b11000000 for num in bytestr)... | 0.461017 | 0.293493 |
import os
clear = lambda: os.system("cls")
import time
import string
import random
## Program
def main():
clear()
print("Welcome to Password Generator!!")
print("Please enter in integer values (1 to 100) to generate your random password!")
userPrompt = "Y"
try:
while(userPrompt == "Y"):
... | Project15_PasswordGenerator/passwordGenerator.py | import os
clear = lambda: os.system("cls")
import time
import string
import random
## Program
def main():
clear()
print("Welcome to Password Generator!!")
print("Please enter in integer values (1 to 100) to generate your random password!")
userPrompt = "Y"
try:
while(userPrompt == "Y"):
... | 0.125977 | 0.12603 |
from os import stat
import numpy as np
import math
L2 = np.linalg.norm # defaults to L2
class Rotation:
@staticmethod
def _cross(u):
# cross product matrix
# https://stackoverflow.com/questions/66707295/
return np.cross(u, -np.identity(3))
def Rho(self, theta, u):
# Rot... | alt.py | from os import stat
import numpy as np
import math
L2 = np.linalg.norm # defaults to L2
class Rotation:
@staticmethod
def _cross(u):
# cross product matrix
# https://stackoverflow.com/questions/66707295/
return np.cross(u, -np.identity(3))
def Rho(self, theta, u):
# Rot... | 0.787278 | 0.549157 |
from cv2 import (Sobel, Laplacian, Canny, CV_64F, normalize,
NORM_MINMAX, add, filter2D)
from numpy import array, abs
from PyQt5.QtWidgets import QDialog
from PyQt5.QtCore import QCoreApplication
from src.constants import BORDER_TYPES
from ..operation import Operation
from .edge_detection_ui import Ed... | src/operations/local/edge_detection.py | from cv2 import (Sobel, Laplacian, Canny, CV_64F, normalize,
NORM_MINMAX, add, filter2D)
from numpy import array, abs
from PyQt5.QtWidgets import QDialog
from PyQt5.QtCore import QCoreApplication
from src.constants import BORDER_TYPES
from ..operation import Operation
from .edge_detection_ui import Ed... | 0.865707 | 0.431225 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import modelcluster.fields
class Migration(migrations.Migration):
dependencies = [
('wagtailforms', '0004_add_verbose_name_plural'),
('team', '0016_profile_image'),
('wagtailcore', ... | roster/migrations/0002_auto_20200610_2210.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import modelcluster.fields
class Migration(migrations.Migration):
dependencies = [
('wagtailforms', '0004_add_verbose_name_plural'),
('team', '0016_profile_image'),
('wagtailcore', ... | 0.48121 | 0.131591 |
import cv2
import numpy as np
def BGR2BGRA(img, ones=True, alpha=255):
"""
Apply BGR to BGRA conversion
-----------
Parameters
:img: np.ndarray type
:ones: (default=True) - to be removed #TODO
:alpha: (default=100) - for transparency
-----------
Returns
:img: np.ndarray type (4... | utils/utils.py | import cv2
import numpy as np
def BGR2BGRA(img, ones=True, alpha=255):
"""
Apply BGR to BGRA conversion
-----------
Parameters
:img: np.ndarray type
:ones: (default=True) - to be removed #TODO
:alpha: (default=100) - for transparency
-----------
Returns
:img: np.ndarray type (4... | 0.380068 | 0.434641 |
import argparse
import mmap
import subprocess
from ctypes import c_uint32
from time import sleep
"""
Class to provide FPGA related operations to manage the QSFP module
"""
class FpgaDevice:
def __init__(self):
# Find the FPGA devices on PCI bus, get the bus info of all devices
pciBusStr = subpro... | fboss/util/qsfp/wedge400_qsfp_util.py | import argparse
import mmap
import subprocess
from ctypes import c_uint32
from time import sleep
"""
Class to provide FPGA related operations to manage the QSFP module
"""
class FpgaDevice:
def __init__(self):
# Find the FPGA devices on PCI bus, get the bus info of all devices
pciBusStr = subpro... | 0.408631 | 0.157914 |
import logging
from http import HTTPStatus
from typing import Mapping, Optional
from aiohttp.web_exceptions import (
HTTPBadRequest, HTTPException, HTTPInternalServerError,
)
from aiohttp.web_middlewares import middleware
from aiohttp.web_request import Request
from marshmallow import ValidationError
from analyze... | analyzer_service/api/middleware.py | import logging
from http import HTTPStatus
from typing import Mapping, Optional
from aiohttp.web_exceptions import (
HTTPBadRequest, HTTPException, HTTPInternalServerError,
)
from aiohttp.web_middlewares import middleware
from aiohttp.web_request import Request
from marshmallow import ValidationError
from analyze... | 0.704058 | 0.070432 |
import pyyed
import xml.etree.ElementTree as xml
def test_graph_added_node_has_default_fill():
g = pyyed.Graph()
g.add_node('N1')
assert "#FF0000" == g.nodes['N1'].shape_fill
def test_graph_added_node_keeps_custom_fill():
g = pyyed.Graph()
g.add_node('N1', shape_fill="#99CC00")
assert "#99CC... | tests/test_pyyed.py | import pyyed
import xml.etree.ElementTree as xml
def test_graph_added_node_has_default_fill():
g = pyyed.Graph()
g.add_node('N1')
assert "#FF0000" == g.nodes['N1'].shape_fill
def test_graph_added_node_keeps_custom_fill():
g = pyyed.Graph()
g.add_node('N1', shape_fill="#99CC00")
assert "#99CC... | 0.647575 | 0.653459 |
import unittest
from payfacMPSdk import payfac_agreement, generatedClass, utils
from dateutil.parser import parse
class TestAgreement(unittest.TestCase):
def test_get_by_legalEntityId(self):
response = payfac_agreement.get_by_legalEntityId("1000293")
self.assertEquals("1000293", response["legalEnt... | test/functional/test_payfac_agreement.py | import unittest
from payfacMPSdk import payfac_agreement, generatedClass, utils
from dateutil.parser import parse
class TestAgreement(unittest.TestCase):
def test_get_by_legalEntityId(self):
response = payfac_agreement.get_by_legalEntityId("1000293")
self.assertEquals("1000293", response["legalEnt... | 0.400749 | 0.196788 |
import asyncio
import datetime
import json
import random
import aiohttp
from bs4 import BeautifulSoup
# HQBuff started recording quizes here
START_DATE = datetime.datetime(2018, 5, 9)
COUNTRY_UK = "uk"
COUNTRY_US = "us"
_API_ADDR = "https://hqbuff.com/api"
async def get_quiz(date, game_num, country=COUNTRY_US):
... | HQsimulator/hqbuff.py | import asyncio
import datetime
import json
import random
import aiohttp
from bs4 import BeautifulSoup
# HQBuff started recording quizes here
START_DATE = datetime.datetime(2018, 5, 9)
COUNTRY_UK = "uk"
COUNTRY_US = "us"
_API_ADDR = "https://hqbuff.com/api"
async def get_quiz(date, game_num, country=COUNTRY_US):
... | 0.245718 | 0.189484 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn as sk
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score, roc_auc_score,f1_score
import torch
import torch.nn as nn
import torc... | learning-algorithm-stochastic/run_stochastic_typical_clf.py | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn as sk
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score, roc_auc_score,f1_score
import torch
import torch.nn as nn
import torc... | 0.604632 | 0.540075 |
import json
from datetime import timedelta
from django.contrib.auth.models import User, Permission
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from news.models import Article, Event, TimePlace
class ... | news/tests.py | import json
from datetime import timedelta
from django.contrib.auth.models import User, Permission
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from news.models import Article, Event, TimePlace
class ... | 0.498535 | 0.25892 |
import numpy as np
import torch
from fastai.callback.core import Callback
__all__ = [
"SomTrainer",
"LinearDecaySomTrainer",
"TwoPhaseSomTrainer",
"ExperimentalSomTrainer",
]
class SomTrainer(Callback):
"""Base class for SOM training strategies."""
pass
class LinearDecaySomTrainer(SomTraine... | fastsom/callback/training.py | import numpy as np
import torch
from fastai.callback.core import Callback
__all__ = [
"SomTrainer",
"LinearDecaySomTrainer",
"TwoPhaseSomTrainer",
"ExperimentalSomTrainer",
]
class SomTrainer(Callback):
"""Base class for SOM training strategies."""
pass
class LinearDecaySomTrainer(SomTraine... | 0.887954 | 0.52342 |
MAX_WIDTH = 26
text_words = {
"Attack " : b"\xD6\x00",
"Angel " : b"\xD6\x01",
"After " : b"\xD6\x02",
"Aura " : b"\xD6\x03",
"Ankor " : b"\xD6\x04",
"Black " : b"\xD6\x05",
"Bill: " : b"\xD6\x06",
"Crystal " : b"\xD6\x07",
"City " : b"\xD6\x08",
"Come " : b"\xD6\x09",... | src/randomizer/randomizer/quintet_text.py | MAX_WIDTH = 26
text_words = {
"Attack " : b"\xD6\x00",
"Angel " : b"\xD6\x01",
"After " : b"\xD6\x02",
"Aura " : b"\xD6\x03",
"Ankor " : b"\xD6\x04",
"Black " : b"\xD6\x05",
"Bill: " : b"\xD6\x06",
"Crystal " : b"\xD6\x07",
"City " : b"\xD6\x08",
"Come " : b"\xD6\x09",... | 0.146301 | 0.366306 |
"""Univariate Optimisation"""
# Golden Search Technique for finding the Maximum
import numpy as np
def gsection(ftn, xl, xm, xr, tol = 1e-9):
# applies the golden-section algorithm to maximise ftn
# we assume that ftn is a function of a single variable
# and that x.l < x.m < x.r and ftn(x.l), ft... | Lecture_13_tasks.py | """Univariate Optimisation"""
# Golden Search Technique for finding the Maximum
import numpy as np
def gsection(ftn, xl, xm, xr, tol = 1e-9):
# applies the golden-section algorithm to maximise ftn
# we assume that ftn is a function of a single variable
# and that x.l < x.m < x.r and ftn(x.l), ft... | 0.579995 | 0.561335 |
import argparse
import datetime
import fileinput
import os
import re
import sys
import traceback
import uuid
import requests
RELATIVE_TIME_PATTERN = re.compile(
r'^(?:\+|in | )?([0-9]+) ?(m|h|d|s)(.*)$'
)
TIME_UNITS = {
'd': 'days',
'm': 'minutes',
'h': 'hours',
's': 'seconds'
}
DATE_FMT = '%Y-%... | cli/snotty/send_message.py |
import argparse
import datetime
import fileinput
import os
import re
import sys
import traceback
import uuid
import requests
RELATIVE_TIME_PATTERN = re.compile(
r'^(?:\+|in | )?([0-9]+) ?(m|h|d|s)(.*)$'
)
TIME_UNITS = {
'd': 'days',
'm': 'minutes',
'h': 'hours',
's': 'seconds'
}
DATE_FMT = '%Y-%... | 0.356671 | 0.109016 |
from tkinter import *
from tkinter import ttk
import os
import ctypes
import sys
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
class c_Cleaner():
def __init__(self):
self.local = os.path.dirname(os.path.abspath(__file__))
self.dow... | clean.py | from tkinter import *
from tkinter import ttk
import os
import ctypes
import sys
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
class c_Cleaner():
def __init__(self):
self.local = os.path.dirname(os.path.abspath(__file__))
self.dow... | 0.234056 | 0.083516 |
import json
import unittest
from slack.web.classes.elements import UserMultiSelectElement, PlainTextElement
from slack.web.classes.modals import ModalBuilder
from slack.web.classes.objects import PlainTextObject
class TestModals(unittest.TestCase):
def test_json_form(self):
modal = ModalBuilder() \
... | tests/web/classes/test_modals.py | import json
import unittest
from slack.web.classes.elements import UserMultiSelectElement, PlainTextElement
from slack.web.classes.modals import ModalBuilder
from slack.web.classes.objects import PlainTextObject
class TestModals(unittest.TestCase):
def test_json_form(self):
modal = ModalBuilder() \
... | 0.368519 | 0.227019 |
import ply.lex as lex
###### TOKEN LISTS ######
literals = ['+', '-', '*', '/', ':', ';', '(', ')', '{', '}', '@', '.', ',']
reserved = {
'CLASS',
'INHERITS',
'IF',
'THEN',
'ELSE',
'FI',
'WHILE',
'LOOP',
'POOL',
'LET',
'IN',
'CASE',
'OF',
'ESAC',
'NEW',
'ISVOID',
}
ignored =... | src/cool/lexer.py | import ply.lex as lex
###### TOKEN LISTS ######
literals = ['+', '-', '*', '/', ':', ';', '(', ')', '{', '}', '@', '.', ',']
reserved = {
'CLASS',
'INHERITS',
'IF',
'THEN',
'ELSE',
'FI',
'WHILE',
'LOOP',
'POOL',
'LET',
'IN',
'CASE',
'OF',
'ESAC',
'NEW',
'ISVOID',
}
ignored =... | 0.193909 | 0.153137 |
import vdomr as vd
class SelectBox(vd.Component):
def __init__(self,options=[]):
vd.Component.__init__(self)
self._on_change_handlers=[]
self._value=None
self.setOptions(options)
def setOptions(self,options):
self._options=options
if self._value not in o... | spikeforest/sfselectwidget.py | import vdomr as vd
class SelectBox(vd.Component):
def __init__(self,options=[]):
vd.Component.__init__(self)
self._on_change_handlers=[]
self._value=None
self.setOptions(options)
def setOptions(self,options):
self._options=options
if self._value not in o... | 0.282691 | 0.06354 |
import queue
import stack
class Graph:
def __init__(self):
self.order = 0
self.vertList = {}
def addVertex(self, vertKey):
self.order += 1
vertex = Vertex(vertKey)
self.vertList[vertKey] = vertex
def addEdge(self, srcKey, dstKey):
src = self.vertList[srcKe... | dataStructures/graph.py | import queue
import stack
class Graph:
def __init__(self):
self.order = 0
self.vertList = {}
def addVertex(self, vertKey):
self.order += 1
vertex = Vertex(vertKey)
self.vertList[vertKey] = vertex
def addEdge(self, srcKey, dstKey):
src = self.vertList[srcKe... | 0.343892 | 0.390941 |
import typing
from abc import abstractmethod
from .x_node import XNode as XNode_83fb09a5
if typing.TYPE_CHECKING:
from .x_attr import XAttr as XAttr_840309ba
from .x_node_list import XNodeList as XNodeList_ae540b41
class XElement(XNode_83fb09a5):
"""
See Also:
`API XElement <https://api.libreo... | ooobuild/lo/xml/dom/x_element.py | import typing
from abc import abstractmethod
from .x_node import XNode as XNode_83fb09a5
if typing.TYPE_CHECKING:
from .x_attr import XAttr as XAttr_840309ba
from .x_node_list import XNodeList as XNodeList_ae540b41
class XElement(XNode_83fb09a5):
"""
See Also:
`API XElement <https://api.libreo... | 0.78469 | 0.23231 |
from graph.helper import make_cycle, make_cok4, make_clique
from graph import DalGraph
import os
from generator import Generator2
from file import File
import logging
from pprint import PrettyPrinter
pp = PrettyPrinter(indent = 4)
from multiprocessing import Process, Lock, Queue
from queue import Empty
import time
FOR... | utility/find_critical.py | from graph.helper import make_cycle, make_cok4, make_clique
from graph import DalGraph
import os
from generator import Generator2
from file import File
import logging
from pprint import PrettyPrinter
pp = PrettyPrinter(indent = 4)
from multiprocessing import Process, Lock, Queue
from queue import Empty
import time
FOR... | 0.207938 | 0.063628 |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
import imp
import yaml
import time
from PIL import Image
import __init__ as booger
import collections
import copy
import cv2
import os
import numpy as np
from matplotlib impor... | train/tasks/semantic/modules/trainer.py |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
import imp
import yaml
import time
from PIL import Image
import __init__ as booger
import collections
import copy
import cv2
import os
import numpy as np
from matplotlib impor... | 0.728459 | 0.164785 |
from unittest import TestCase
import ipaddress
from ddns_updater_aws.adapters import IpProviderFailure
from ddns_updater_aws.adapters import ipprovider_opendns
from flexmock import flexmock
from mock import patch, MagicMock, Mock
class TestGetIp(TestCase):
def test_getIp(self):
actual_ip = ipprovider_ope... | test/adapters/test_ipprovider_opendns.py | from unittest import TestCase
import ipaddress
from ddns_updater_aws.adapters import IpProviderFailure
from ddns_updater_aws.adapters import ipprovider_opendns
from flexmock import flexmock
from mock import patch, MagicMock, Mock
class TestGetIp(TestCase):
def test_getIp(self):
actual_ip = ipprovider_ope... | 0.821725 | 0.42322 |
from typing import Optional
from vkbottle.rule import FromMe
from vkbottle.user import Blueprint, Message
from logger import logger_decorator
from objects import RolePlayCommand, Database
from utils import edit_message
user = Blueprint(
name='role_play_commands_blueprint'
)
async def get_role_play_message(
... | commands/role_play_commands.py | from typing import Optional
from vkbottle.rule import FromMe
from vkbottle.user import Blueprint, Message
from logger import logger_decorator
from objects import RolePlayCommand, Database
from utils import edit_message
user = Blueprint(
name='role_play_commands_blueprint'
)
async def get_role_play_message(
... | 0.735831 | 0.068257 |
from wpg.generators import build_gauss_wavefront_xy as construct_gaussian
from felpy.model.wavefront import Wavefront
from wpg.wpg_uti_wf import plot_intensity_map
from .examples.NFS.cylinder_phase_mask import phase, cylinder_thickness
import numpy as np
from felpy.utils.opt_utils import ekev2wav
from felpy.model.to... | felpy/examples/NFS/analytical_w_propagation.py |
from wpg.generators import build_gauss_wavefront_xy as construct_gaussian
from felpy.model.wavefront import Wavefront
from wpg.wpg_uti_wf import plot_intensity_map
from .examples.NFS.cylinder_phase_mask import phase, cylinder_thickness
import numpy as np
from felpy.utils.opt_utils import ekev2wav
from felpy.model.to... | 0.498291 | 0.46642 |
from sputnik.dir_package import DirPackage
from sputnik.package_list import (PackageNotFoundException,
CompatiblePackageNotFoundException)
import sputnik
from . import about
def get_package(data_dir):
if not isinstance(data_dir, six.string_types):
raise RuntimeError('dat... | spacy/deprecated.py | from sputnik.dir_package import DirPackage
from sputnik.package_list import (PackageNotFoundException,
CompatiblePackageNotFoundException)
import sputnik
from . import about
def get_package(data_dir):
if not isinstance(data_dir, six.string_types):
raise RuntimeError('dat... | 0.433981 | 0.163746 |
import random, re
import anydbm
import os, sys
from flask import Flask, render_template, request, make_response
app = Flask(__name__)
IGNORED = 'ignored'
INTERESTING = 'interesting'
PENDING_FILES = set()
WAV_DIR = 'static/wav'
IGNORED_WAV_DIRS = ('doc-kiwi',
'doc-morepork', 'rfpt-15m',
... | server.py |
import random, re
import anydbm
import os, sys
from flask import Flask, render_template, request, make_response
app = Flask(__name__)
IGNORED = 'ignored'
INTERESTING = 'interesting'
PENDING_FILES = set()
WAV_DIR = 'static/wav'
IGNORED_WAV_DIRS = ('doc-kiwi',
'doc-morepork', 'rfpt-15m',
... | 0.1844 | 0.062217 |
from __future__ import print_function
import numpy as np
from param import Param
from netCDF4 import Dataset
import os
class Output(Param):
def __init__(self, param, grid, diag, flxlist=None):
self.list_param = ['expname', 'myrank', 'nbproc',
'nx', 'ny', 'npx', 'npy', 'nprint',
... | Fluid2d/core/output.py | from __future__ import print_function
import numpy as np
from param import Param
from netCDF4 import Dataset
import os
class Output(Param):
def __init__(self, param, grid, diag, flxlist=None):
self.list_param = ['expname', 'myrank', 'nbproc',
'nx', 'ny', 'npx', 'npy', 'nprint',
... | 0.456894 | 0.196788 |
from __future__ import absolute_import
from abc import abstractmethod
from Qt import QtCore
import construct
import traceback
from construct_ui.views import View
from construct_ui import dialogs
class ActionForm(View):
'''An interface to run an Action.
The data of an ActionForm is either the current construc... | construct_ui/forms/actionform.py | from __future__ import absolute_import
from abc import abstractmethod
from Qt import QtCore
import construct
import traceback
from construct_ui.views import View
from construct_ui import dialogs
class ActionForm(View):
'''An interface to run an Action.
The data of an ActionForm is either the current construc... | 0.654784 | 0.090494 |
import logging
from res.biz.base import BaseService
from res.pub.exceptions import VNFRESException
from res.pub.exceptions import NotFoundException
from res.pub.database.models import NfInstModel
from res.pub.database.models import StorageInstModel
from res.pub.database.models import NetworkInstModel
from res.... | res/res/biz/vnfs_get.py | import logging
from res.biz.base import BaseService
from res.pub.exceptions import VNFRESException
from res.pub.exceptions import NotFoundException
from res.pub.database.models import NfInstModel
from res.pub.database.models import StorageInstModel
from res.pub.database.models import NetworkInstModel
from res.... | 0.42919 | 0.077622 |
import numpy as np
import math
def generate_graph(size = 10, fully_connected = False, random = False):
""" Generate a graph for graph bipartitioning problem
Args:
size (int, optional): The number of vertices for the generated graph. Defaults to 10.
fully_connected (bool, optional): If is s... | graph_tools/generator.py | import numpy as np
import math
def generate_graph(size = 10, fully_connected = False, random = False):
""" Generate a graph for graph bipartitioning problem
Args:
size (int, optional): The number of vertices for the generated graph. Defaults to 10.
fully_connected (bool, optional): If is s... | 0.599485 | 0.557665 |
from django.views.generic.base import RedirectView
from django.views import View
from .. import forms
from django.views.generic import DetailView, ListView
from .. import models
from django.views.generic.edit import UpdateView, FormView
from django.urls import reverse_lazy
from django.contrib.contenttypes.models import... | judge/views/user.py | from django.views.generic.base import RedirectView
from django.views import View
from .. import forms
from django.views.generic import DetailView, ListView
from .. import models
from django.views.generic.edit import UpdateView, FormView
from django.urls import reverse_lazy
from django.contrib.contenttypes.models import... | 0.510985 | 0.064713 |
import dpkt
import pandas as pd
import re
import datetime
import socket
from dpkt.compat import compat_ord
def mac_addr(address):
"""Convert a MAC address to a readable/printable string
Args:
address (str): a MAC address in hex form (e.g. '\x01\x02\x03\x04\x05\x06')
Returns:
s... | clustering_proxy_log/Transform_pcap.py | import dpkt
import pandas as pd
import re
import datetime
import socket
from dpkt.compat import compat_ord
def mac_addr(address):
"""Convert a MAC address to a readable/printable string
Args:
address (str): a MAC address in hex form (e.g. '\x01\x02\x03\x04\x05\x06')
Returns:
s... | 0.284675 | 0.277756 |
import chainer
import numpy as np
from test.util import generate_kernel_test_case, wrap_template
from webdnn.graph.placeholder import Placeholder
from webdnn.frontend.chainer.converter import ChainerConverter
from webdnn.frontend.chainer.placeholder_variable import PlaceholderVariable
@wrap_template
def template(ksi... | test/runtime/frontend_test/chainer_test/functions_test/connection_test/dilated_convolution_2d_function_test.py | import chainer
import numpy as np
from test.util import generate_kernel_test_case, wrap_template
from webdnn.graph.placeholder import Placeholder
from webdnn.frontend.chainer.converter import ChainerConverter
from webdnn.frontend.chainer.placeholder_variable import PlaceholderVariable
@wrap_template
def template(ksi... | 0.592902 | 0.393298 |
import os
import sys
import ctypes
from ctypes.util import find_library
from ctypes import c_char, c_char_p, c_void_p, c_int, c_long, c_longlong, Structure, POINTER
from enum import IntEnum
_DYLIB_SUFFIX = '.so'
if sys.platform.lower() == 'darwin':
_DYLIB_SUFFIX = '.dylib'
elif sys.platform.lower() == 'win32':
... | rocketmq/ffi.py | import os
import sys
import ctypes
from ctypes.util import find_library
from ctypes import c_char, c_char_p, c_void_p, c_int, c_long, c_longlong, Structure, POINTER
from enum import IntEnum
_DYLIB_SUFFIX = '.so'
if sys.platform.lower() == 'darwin':
_DYLIB_SUFFIX = '.dylib'
elif sys.platform.lower() == 'win32':
... | 0.246533 | 0.059921 |
from flask import g
from flask_restful import Resource, inputs
from flask_restful.reqparse import RequestParser
from sqlalchemy.exc import SQLAlchemyError
from app import hash_ids
from common.utils import get_order_code
from common import code, pretty_result
from models.orders import OrdersModel
from models.products i... | backend/resources/orders.py |
from flask import g
from flask_restful import Resource, inputs
from flask_restful.reqparse import RequestParser
from sqlalchemy.exc import SQLAlchemyError
from app import hash_ids
from common.utils import get_order_code
from common import code, pretty_result
from models.orders import OrdersModel
from models.products i... | 0.402744 | 0.066387 |
# Python modules
import re
# NOC modules
from noc.core.script.base import BaseScript
from noc.sa.interfaces.igetinventory import IGetInventory
class Script(BaseScript):
name = "NSN.TIMOS.get_inventory"
interface = IGetInventory
rx_iom = re.compile(
r"^(?P<number>\d+)\s+(?P<name>iom\S+)\s+(?:up|... | sa/profiles/NSN/TIMOS/get_inventory.py |
# Python modules
import re
# NOC modules
from noc.core.script.base import BaseScript
from noc.sa.interfaces.igetinventory import IGetInventory
class Script(BaseScript):
name = "NSN.TIMOS.get_inventory"
interface = IGetInventory
rx_iom = re.compile(
r"^(?P<number>\d+)\s+(?P<name>iom\S+)\s+(?:up|... | 0.219505 | 0.184859 |
import os
import csv
import shutil
import logging
import glob
import datetime
from django.db import transaction
from django.core.files import File
from annoying.functions import get_object_or_None
from documents.models import Document
from documents.utils import save_document_forms
from transmittals.validation impor... | src/transmittals/imports.py | import os
import csv
import shutil
import logging
import glob
import datetime
from django.db import transaction
from django.core.files import File
from annoying.functions import get_object_or_None
from documents.models import Document
from documents.utils import save_document_forms
from transmittals.validation impor... | 0.639849 | 0.132852 |
import boto3
from enum import Enum
import json
import logging
from config import region_name, thing_name
from config import response_fallback, response_on, response_off
from config import response_fan_speed, response_error
# Initialize IoT client
client = boto3.client('iot-data', region_name=region_name)
class FanSp... | quietcool_aws_lambda/lambda_function.py | import boto3
from enum import Enum
import json
import logging
from config import region_name, thing_name
from config import response_fallback, response_on, response_off
from config import response_fan_speed, response_error
# Initialize IoT client
client = boto3.client('iot-data', region_name=region_name)
class FanSp... | 0.404978 | 0.099295 |
import unittest, sys
sys.path.extend(['.','..','../..','py'])
import os
import h2o2 as h2o
import h2o_cmd, h2o_import as h2i, h2o_browse as h2b
from h2o_test import find_file, dump_json, verboseprint
expectedZeros = [0 for i in range(11)]
CAUSE_FAIL = False
def assertEqualMsg(a, b): assert a == b, "%s %s" % (a, b)
... | py2/testdir_single_jvm/test_parse_nfs.py | import unittest, sys
sys.path.extend(['.','..','../..','py'])
import os
import h2o2 as h2o
import h2o_cmd, h2o_import as h2i, h2o_browse as h2b
from h2o_test import find_file, dump_json, verboseprint
expectedZeros = [0 for i in range(11)]
CAUSE_FAIL = False
def assertEqualMsg(a, b): assert a == b, "%s %s" % (a, b)
... | 0.243912 | 0.334426 |
import sys
import MySQLdb
import uuid
import subprocess
from datetime import datetime,timedelta
reload(sys)
sys.setdefaultencoding('utf-8')
dataname = "leodb"
host='127.0.0.1'
def updata_watch_todb(nums,error_for):
conn= MySQLdb.connect(
host= host,
port = 3306,
user='root',
passwd... | app/tianwang/mysqltmp/opereat.py | import sys
import MySQLdb
import uuid
import subprocess
from datetime import datetime,timedelta
reload(sys)
sys.setdefaultencoding('utf-8')
dataname = "leodb"
host='127.0.0.1'
def updata_watch_todb(nums,error_for):
conn= MySQLdb.connect(
host= host,
port = 3306,
user='root',
passwd... | 0.056055 | 0.086748 |
import sys
import time
from scipy.special import binom as binom
from timer import Timer
from util import *
import numpy as np
class SATCounter:
def __init__(self, sat_problem, verbose=True, use_regular=False):
""" Each SATCounter solves a specific sat problem that must be specified at creation """
... | SATModelCount/sat_counter.py | import sys
import time
from scipy.special import binom as binom
from timer import Timer
from util import *
import numpy as np
class SATCounter:
def __init__(self, sat_problem, verbose=True, use_regular=False):
""" Each SATCounter solves a specific sat problem that must be specified at creation """
... | 0.53048 | 0.544983 |
import math
from queue import Queue
from IPython import embed
import torch
import torch.distributed as dist
import torch.cuda.comm as comm
from torch.autograd.function import once_differentiable
from torch.nn.modules.batchnorm import _BatchNorm
import torch.nn.functional as F
import syncbn_gpu
class DistributedSync... | det/maskrcnn_benchmark/distributed_syncbn/syncbn.py | import math
from queue import Queue
from IPython import embed
import torch
import torch.distributed as dist
import torch.cuda.comm as comm
from torch.autograd.function import once_differentiable
from torch.nn.modules.batchnorm import _BatchNorm
import torch.nn.functional as F
import syncbn_gpu
class DistributedSync... | 0.719482 | 0.211437 |
import os
from sqlalchemy import select, text
import pandas as pd
from ... import io
from .. import colnames as cn
from . import filenames as fn
SEG_INFO_COLUMNS = [cn.seg_id, cn.size, *cn.centroid_cols, *cn.bbox_cols]
CHUNK_START_COLUMNS = [cn.chunk_tag, cn.chunk_bx, cn.chunk_by, cn.chunk_bz]
CHUNKED_TABLENAME = "... | synaptor/proc/io/seginfo.py | import os
from sqlalchemy import select, text
import pandas as pd
from ... import io
from .. import colnames as cn
from . import filenames as fn
SEG_INFO_COLUMNS = [cn.seg_id, cn.size, *cn.centroid_cols, *cn.bbox_cols]
CHUNK_START_COLUMNS = [cn.chunk_tag, cn.chunk_bx, cn.chunk_by, cn.chunk_bz]
CHUNKED_TABLENAME = "... | 0.39036 | 0.245922 |
import sys
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.opengl as gl
import numpy as np
import sounddevice as sd
import scipy.signal as signal
def calc_rms(in_sig):
rms_sig = np.sqrt(np.mean(in_sig**2))
return(rms_sig)
def calc_delay(two_ch,ba_filt,fs=44100):
... | pyqtgraph_aoa.py | import sys
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.opengl as gl
import numpy as np
import sounddevice as sd
import scipy.signal as signal
def calc_rms(in_sig):
rms_sig = np.sqrt(np.mean(in_sig**2))
return(rms_sig)
def calc_delay(two_ch,ba_filt,fs=44100):
... | 0.317215 | 0.221572 |
import aiohttp
import requests
class Response:
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class Excusor:
def __init__(self):
self.base_url = "https://excuser.herokuapp.com/v1/excuse"
self.categories = ['family', 'office', 'children', 'co... | public_apis/Categories/Entertainment/excusor.py | import aiohttp
import requests
class Response:
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class Excusor:
def __init__(self):
self.base_url = "https://excuser.herokuapp.com/v1/excuse"
self.categories = ['family', 'office', 'children', 'co... | 0.226099 | 0.072472 |
import typing
from .miscmodels import try_enum, Achievement, Troop, Hero, Spell, Label, League, LegendStatistics
from .enums import (
Role,
HERO_ORDER,
BUILDER_TROOPS_ORDER,
HOME_TROOP_ORDER,
SPELL_ORDER,
SIEGE_MACHINE_ORDER,
UNRANKED_LEAGUE_DATA,
ACHIEVEMENT_ORDER,
SUPER_TROOP_ORD... | coc/players.py | import typing
from .miscmodels import try_enum, Achievement, Troop, Hero, Spell, Label, League, LegendStatistics
from .enums import (
Role,
HERO_ORDER,
BUILDER_TROOPS_ORDER,
HOME_TROOP_ORDER,
SPELL_ORDER,
SIEGE_MACHINE_ORDER,
UNRANKED_LEAGUE_DATA,
ACHIEVEMENT_ORDER,
SUPER_TROOP_ORD... | 0.860281 | 0.282988 |
from django.contrib import admin
from server.models import Location, Hospital , Account, Profile, Action, Appointment, MedicalTest
class LocationAdmin(admin.ModelAdmin):
fields = ['city', 'zip', 'state', 'country', 'address']
list_display = ('address', 'city', 'state', 'country', 'zip')
admin.site.register(... | server/admin.py | from django.contrib import admin
from server.models import Location, Hospital , Account, Profile, Action, Appointment, MedicalTest
class LocationAdmin(admin.ModelAdmin):
fields = ['city', 'zip', 'state', 'country', 'address']
list_display = ('address', 'city', 'state', 'country', 'zip')
admin.site.register(... | 0.404272 | 0.135175 |
import sys
import os
import re
import argparse
import errno
__version__ = '0.0.1'
EXIT_SUCCESS = 0
EXIT_FAILURE = 1
APP_PATH = os.path.dirname(os.path.realpath(__file__))
APP_CWD = os.getcwd()
def args_parsing():
parser = argparse.ArgumentParser(prog='qlmm', description='LQMM, Quick and Light Memos Manager', e... | qlmm.py |
import sys
import os
import re
import argparse
import errno
__version__ = '0.0.1'
EXIT_SUCCESS = 0
EXIT_FAILURE = 1
APP_PATH = os.path.dirname(os.path.realpath(__file__))
APP_CWD = os.getcwd()
def args_parsing():
parser = argparse.ArgumentParser(prog='qlmm', description='LQMM, Quick and Light Memos Manager', e... | 0.306423 | 0.054299 |
import os
import sys
from bentoml.saved_bundle import load_bento_service_metadata
from bentoml.configuration import LAST_PYPI_RELEASE_VERSION
from utils import (
get_configuration_value,
run_shell_command,
build_docker_image,
push_docker_image_to_repository,
)
from azure import generate_azure_functio... | update.py | import os
import sys
from bentoml.saved_bundle import load_bento_service_metadata
from bentoml.configuration import LAST_PYPI_RELEASE_VERSION
from utils import (
get_configuration_value,
run_shell_command,
build_docker_image,
push_docker_image_to_repository,
)
from azure import generate_azure_functio... | 0.223716 | 0.138345 |
lei_test = {"records":[{
"LEI" : {
"$" : "001GPB6A9XPE8XJICC14"
},
"Entity" : {
"LegalName" : {
"$" : "FIDELITY ADVISOR SERIES I - Fidelity Advisor Leveraged Company Stock Fund"
},
"OtherEntityNames" : {
"OtherEntityName" : [ {
"@type" ... | engage-analytics/tests/lei/test_cons.py | lei_test = {"records":[{
"LEI" : {
"$" : "001GPB6A9XPE8XJICC14"
},
"Entity" : {
"LegalName" : {
"$" : "FIDELITY ADVISOR SERIES I - Fidelity Advisor Leveraged Company Stock Fund"
},
"OtherEntityNames" : {
"OtherEntityName" : [ {
"@type" ... | 0.360939 | 0.290761 |
import logging
import os
import sys
def find_project_dir():
"""
Go through the path, and look for app.yaml
"""
for path in sys.path:
abs_path = os.path.join(os.path.abspath(path), "app.yaml")
if os.path.exists(abs_path):
return os.path.dirname(abs_path)
raise Runtim... | djangoappengine/boot.py | import logging
import os
import sys
def find_project_dir():
"""
Go through the path, and look for app.yaml
"""
for path in sys.path:
abs_path = os.path.join(os.path.abspath(path), "app.yaml")
if os.path.exists(abs_path):
return os.path.dirname(abs_path)
raise Runtim... | 0.307462 | 0.10235 |
import sys, urllib, os, traceback
import logging
from optparse import OptionParser
from video_mapping import video_mapping
log = logging.getLogger(__name__)
FORMATS = ['.mp4','.ogg','.flv']
ARCHIVE_URL = "http://www.archive.org/download/KhanAcademy"
def urlretrieve(urlfile, fpath):
chunk = 2**20
f = o... | code/download.py | import sys, urllib, os, traceback
import logging
from optparse import OptionParser
from video_mapping import video_mapping
log = logging.getLogger(__name__)
FORMATS = ['.mp4','.ogg','.flv']
ARCHIVE_URL = "http://www.archive.org/download/KhanAcademy"
def urlretrieve(urlfile, fpath):
chunk = 2**20
f = o... | 0.254694 | 0.113089 |
import streamlit as st
# Page Configuration
st.set_page_config(page_title="Carbonify Tool",page_icon="🌎",layout="wide",initial_sidebar_state="expanded")
from carbonify import BaseCarbone
#------------------------------------------------------------------------------------------
# PARAMETERS
#----------------------... | index.py | import streamlit as st
# Page Configuration
st.set_page_config(page_title="Carbonify Tool",page_icon="🌎",layout="wide",initial_sidebar_state="expanded")
from carbonify import BaseCarbone
#------------------------------------------------------------------------------------------
# PARAMETERS
#----------------------... | 0.462959 | 0.193642 |
from collections import deque
import logging
from lib.aws import requests
from lib.aws.exception import AccessDeniedException
from lib.iam.exception import IamEntityAlreadyExistsException, IamLimitExceededException
from lib.utility import misc
from scli import api_wrapper, prompt
from scli.constants import EbDefault, ... | libs/eb/scli/terminal/iam_terminal.py | from collections import deque
import logging
from lib.aws import requests
from lib.aws.exception import AccessDeniedException
from lib.iam.exception import IamEntityAlreadyExistsException, IamLimitExceededException
from lib.utility import misc
from scli import api_wrapper, prompt
from scli.constants import EbDefault, ... | 0.316264 | 0.079675 |
import uuid
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
import hacktheback.core.models
import hacktheback.validators
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_... | hacktheback/forms/migrations/0001_initial.py |
import uuid
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
import hacktheback.core.models
import hacktheback.validators
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_... | 0.453262 | 0.087916 |
import hashlib
import shutil
from pathlib import Path
from typing import Optional
from urllib.parse import urlparse
import aiofiles
import aiohttp
from aiohttp.client_exceptions import ClientConnectionError, InvalidURL
from datafiles import datafile, field
from sanic import Sanic
from sanic.log import logger
from spon... | app/models.py | import hashlib
import shutil
from pathlib import Path
from typing import Optional
from urllib.parse import urlparse
import aiofiles
import aiohttp
from aiohttp.client_exceptions import ClientConnectionError, InvalidURL
from datafiles import datafile, field
from sanic import Sanic
from sanic.log import logger
from spon... | 0.762954 | 0.295795 |
from transformers import BertModel, BertTokenizer
from torch import nn
import torch
import torch.nn.functional as F
class BertBaseLinear(nn.Module):
"""bert-base-chinese with Linear output"""
def __init__(self, model_path):
super().__init__()
self.bert_base = BertModel.from_pretrained(model_p... | models/models.py | from transformers import BertModel, BertTokenizer
from torch import nn
import torch
import torch.nn.functional as F
class BertBaseLinear(nn.Module):
"""bert-base-chinese with Linear output"""
def __init__(self, model_path):
super().__init__()
self.bert_base = BertModel.from_pretrained(model_p... | 0.927149 | 0.369656 |
import asyncio
import datetime as dt
import logging
import random
import re
from typing import Tuple
import discord
from discord.ext import commands
from cogs.utils.database import DbChar
from nabbot import NabBot
from .utils import CogUtils, config, context, errors, join_list, database, timing
log = logging.getLog... | cogs/core.py |
import asyncio
import datetime as dt
import logging
import random
import re
from typing import Tuple
import discord
from discord.ext import commands
from cogs.utils.database import DbChar
from nabbot import NabBot
from .utils import CogUtils, config, context, errors, join_list, database, timing
log = logging.getLog... | 0.58166 | 0.161717 |
import os, time
from core import execute
from core import slack
from core import utils
class IPSpace(object):
''' Scanning vulnerable service based version '''
def __init__(self, options):
utils.print_banner("IP Discovery")
utils.make_directory(options['WORKSPACE'] + '/ipspace')
self.mo... | modules/ipspace.py | import os, time
from core import execute
from core import slack
from core import utils
class IPSpace(object):
''' Scanning vulnerable service based version '''
def __init__(self, options):
utils.print_banner("IP Discovery")
utils.make_directory(options['WORKSPACE'] + '/ipspace')
self.mo... | 0.086715 | 0.072933 |
from enum import Enum
from typing import NamedTuple
from selenium.webdriver.common.by import By
class SelectorsEnum(Enum):
@property
def by(self):
return self.value.by
@property
def selector(self):
return self.value.selector
@property
def type(self):
return self.valu... | tests/browser/common_selectors.py | from enum import Enum
from typing import NamedTuple
from selenium.webdriver.common.by import By
class SelectorsEnum(Enum):
@property
def by(self):
return self.value.by
@property
def selector(self):
return self.value.selector
@property
def type(self):
return self.valu... | 0.69368 | 0.132486 |
from splinter import Browser
from bs4 import BeautifulSoup as bs
from webdriver_manager.chrome import ChromeDriverManager
import pandas as pd
import time
def scrape_info():
executable_path = {'executable_path': ChromeDriverManager().install()}
browser = Browser('chrome', **executable_path, headless=False)
... | Missions_to_Mars/scrape_mars.py | from splinter import Browser
from bs4 import BeautifulSoup as bs
from webdriver_manager.chrome import ChromeDriverManager
import pandas as pd
import time
def scrape_info():
executable_path = {'executable_path': ChromeDriverManager().install()}
browser = Browser('chrome', **executable_path, headless=False)
... | 0.416797 | 0.269249 |
# importing essentials
from tkinter import *
from tkinter import messagebox
import os
import urllib.parse
import urllib.request
import getpass
import socket
import json
# CONSTANTS
GAMES_PLAYED = 1
HEALING = 0
DEATHS = 2
DAMAGE = 3
ELIMINATIONS = 9
# ##############################################... | main.py |
# importing essentials
from tkinter import *
from tkinter import messagebox
import os
import urllib.parse
import urllib.request
import getpass
import socket
import json
# CONSTANTS
GAMES_PLAYED = 1
HEALING = 0
DEATHS = 2
DAMAGE = 3
ELIMINATIONS = 9
# ##############################################... | 0.217421 | 0.121321 |
import random
def Movie_guess():
# You can add more movie names if you want!
movie_list=["Avengers","Avengers Endgame","Wandavision","Loki","Jab We Met","Dil","<NAME>","Ramleela","<NAME>","Padmavat","<NAME>"]
movie=random.choice(movie_list)
movie=movie.replace(" ","")
movie=list(movie.lower())
length=len(... | Code/game_projects/Movie_guess_game_2_players/movie_guess_game.py | import random
def Movie_guess():
# You can add more movie names if you want!
movie_list=["Avengers","Avengers Endgame","Wandavision","Loki","Jab We Met","Dil","<NAME>","Ramleela","<NAME>","Padmavat","<NAME>"]
movie=random.choice(movie_list)
movie=movie.replace(" ","")
movie=list(movie.lower())
length=len(... | 0.111217 | 0.201735 |
import numpy as np
class Ising_mat(object):
def __init__(self,h,w, T ,J = 1):
self.h = h
self.w = w
self.N = h*w
self.J = J
self.T = T
self.mat = np.ones([self.h, self.w], int)
def random_state(self):
self.mat = np.random.randint(0, 2, (self.h,se... | Ising.py | import numpy as np
class Ising_mat(object):
def __init__(self,h,w, T ,J = 1):
self.h = h
self.w = w
self.N = h*w
self.J = J
self.T = T
self.mat = np.ones([self.h, self.w], int)
def random_state(self):
self.mat = np.random.randint(0, 2, (self.h,se... | 0.281307 | 0.322046 |
def price_model():
"""
This function is to generate Machiene learning model.
It will generate file in cvs format.
It will generate Lasso and Ridge regression Coe.
"""
listing=pd.read_csv('all.csv')
df=listing[['host_response_rate','host_response_time','host_acceptance_rate',
'host_is_superhost','neigh... | AirbnbViz/code/price.py | def price_model():
"""
This function is to generate Machiene learning model.
It will generate file in cvs format.
It will generate Lasso and Ridge regression Coe.
"""
listing=pd.read_csv('all.csv')
df=listing[['host_response_rate','host_response_time','host_acceptance_rate',
'host_is_superhost','neigh... | 0.320077 | 0.387603 |
import unittest
import numpy
import chainer
from chainer.backends import cuda
import chainer.functions as F
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.utils import conv
@testing.parameterize(*testing.product({
'in_shape': [(4, 3, 6, 8), (4, 3, 5,... | tests/chainer_tests/functions_tests/pooling_tests/test_upsampling_2d.py | import unittest
import numpy
import chainer
from chainer.backends import cuda
import chainer.functions as F
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.utils import conv
@testing.parameterize(*testing.product({
'in_shape': [(4, 3, 6, 8), (4, 3, 5,... | 0.562657 | 0.499939 |
try:
from ._models_py3 import AFDDomain
from ._models_py3 import AFDDomainHttpsParameters
from ._models_py3 import AFDDomainListResult
from ._models_py3 import AFDDomainProperties
from ._models_py3 import AFDDomainUpdateParameters
from ._models_py3 import AFDDomainUpdatePropertiesParameters
... | sdk/cdn/azure-mgmt-cdn/azure/mgmt/cdn/models/__init__.py |
try:
from ._models_py3 import AFDDomain
from ._models_py3 import AFDDomainHttpsParameters
from ._models_py3 import AFDDomainListResult
from ._models_py3 import AFDDomainProperties
from ._models_py3 import AFDDomainUpdateParameters
from ._models_py3 import AFDDomainUpdatePropertiesParameters
... | 0.461745 | 0.0559 |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as anim
def figure_to_rgb(figure, grayscale = False):
"""
Converts a matplotlib figure into a 3-channel numpy array.
Figures are returned by
gcf(), figure() or subplots() can be used as input.
--------------------------... | plot_utilities.py |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as anim
def figure_to_rgb(figure, grayscale = False):
"""
Converts a matplotlib figure into a 3-channel numpy array.
Figures are returned by
gcf(), figure() or subplots() can be used as input.
--------------------------... | 0.813831 | 0.700594 |
import click
import titanic.scripts.download_data
import titanic.scripts.run_notebooks
import titanic.scripts.make_features
import titanic.scripts.cross_validate_models
import titanic.scripts.make_submission
import titanic.scripts.clean_generated_files
@click.group(help='CLI entry point of project Titani... | src/titanic/cli.py |
import click
import titanic.scripts.download_data
import titanic.scripts.run_notebooks
import titanic.scripts.make_features
import titanic.scripts.cross_validate_models
import titanic.scripts.make_submission
import titanic.scripts.clean_generated_files
@click.group(help='CLI entry point of project Titani... | 0.459561 | 0.134037 |
import logging
import math
import traceback
from enum import Enum
from threading import Thread
import cv2
import numpy as np
import pywintypes
import win32gui
from PIL import ImageGrab
from win32api import GetSystemMetrics
from fishy.helper.config import config
class Status(Enum):
CRASHED = -1
STOPPED = 0
... | fishy/engine/common/window_server.py | import logging
import math
import traceback
from enum import Enum
from threading import Thread
import cv2
import numpy as np
import pywintypes
import win32gui
from PIL import ImageGrab
from win32api import GetSystemMetrics
from fishy.helper.config import config
class Status(Enum):
CRASHED = -1
STOPPED = 0
... | 0.307254 | 0.117446 |
import pytest
from marshmallow import ValidationError
from nr_events.marshmallow import EventsMetadataSchemaV1
class TestNameOriginal:
def test_name_original_1(self, app, db, taxonomy_tree, base_json, base_json_dereferenced,
base_event, base_event_dereferenced):
content = "Če... | tests/test_marshmallow.py | import pytest
from marshmallow import ValidationError
from nr_events.marshmallow import EventsMetadataSchemaV1
class TestNameOriginal:
def test_name_original_1(self, app, db, taxonomy_tree, base_json, base_json_dereferenced,
base_event, base_event_dereferenced):
content = "Če... | 0.423935 | 0.157979 |
import cohesity_management_sdk.models.smb_permission
import cohesity_management_sdk.models.subnet
class Share(object):
"""Implementation of the 'Share' model.
Specifies the share details when request is made for list of shares
filtered by ShareName parameter.
Attributes:
all_smb_mount_paths... | cohesity_management_sdk/models/share.py |
import cohesity_management_sdk.models.smb_permission
import cohesity_management_sdk.models.subnet
class Share(object):
"""Implementation of the 'Share' model.
Specifies the share details when request is made for list of shares
filtered by ShareName parameter.
Attributes:
all_smb_mount_paths... | 0.705481 | 0.181717 |
from tkinter import *
import sqlite3
import tkinter.messagebox as tkMessageBox
class FormCariProduk(Toplevel):
def __init__(self, parent):
Toplevel.__init__(self, parent)
self.geometry("+%d+%d" % (parent.winfo_rootx()+80,
parent.winfo_rooty()+50))
... | formCariProduk.py |
from tkinter import *
import sqlite3
import tkinter.messagebox as tkMessageBox
class FormCariProduk(Toplevel):
def __init__(self, parent):
Toplevel.__init__(self, parent)
self.geometry("+%d+%d" % (parent.winfo_rootx()+80,
parent.winfo_rooty()+50))
... | 0.209712 | 0.108048 |
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def getRoot(self):
return self.root
def add(self,data):
if not self.root:
self.root = Node(data)
... | algorithms/data-structures/trees/min_height_bst.py | class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def getRoot(self):
return self.root
def add(self,data):
if not self.root:
self.root = Node(data)
... | 0.446857 | 0.304507 |
import requests, json, time
# College football constant variables
CFB_YEAR, GAMES, VEGAS_LINES = 2019, 'games', 'lines'
REGULAR_SEASON, POST_SEASON = 'regular', 'postseason'
## Requests and saves regular/post season stats [games] or Vegas lines [lines]
def cfb_stats(date, metric, season):
results = requests.get(f... | cfb_season_json_import.py | import requests, json, time
# College football constant variables
CFB_YEAR, GAMES, VEGAS_LINES = 2019, 'games', 'lines'
REGULAR_SEASON, POST_SEASON = 'regular', 'postseason'
## Requests and saves regular/post season stats [games] or Vegas lines [lines]
def cfb_stats(date, metric, season):
results = requests.get(f... | 0.495361 | 0.249382 |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# M... | vega/algorithms/nas/modnas/metrics/predefined/stats.py |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# M... | 0.916292 | 0.145996 |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
depends_on = (
('reversion', '0001_initial'),
)
def forwards(self, orm):
# Adding model 'BatchPushItem'
db.create_table('nudge_batchpushitem'... | src/nudge/migrations/0001_initial.py | import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
depends_on = (
('reversion', '0001_initial'),
)
def forwards(self, orm):
# Adding model 'BatchPushItem'
db.create_table('nudge_batchpushitem'... | 0.488527 | 0.074736 |
import cgmsquared.clustering2 as c2
import numpy as np
from cgmsquared import clustering as cgm2_cluster
class Model:
"""This model of the covering fraction/probability of hitting logNHI > 10**14 is based on
using r0 ~ Rvir.
This one takes in data that should be an array of values/arrays and optionally ... | haloclustering/models.py | import cgmsquared.clustering2 as c2
import numpy as np
from cgmsquared import clustering as cgm2_cluster
class Model:
"""This model of the covering fraction/probability of hitting logNHI > 10**14 is based on
using r0 ~ Rvir.
This one takes in data that should be an array of values/arrays and optionally ... | 0.762866 | 0.712357 |
__author__ = 'florianseidl'
from collector import *
from urllib.error import HTTPError
from unittest import TestCase
from unittest.mock import Mock, DEFAULT
from types import SimpleNamespace
from concurrent import futures
class TestHttpClient(TestCase):
json_str = '{ "foo": "bar" }'
def test_ok(self):
... | tests/test_collector.py | __author__ = 'florianseidl'
from collector import *
from urllib.error import HTTPError
from unittest import TestCase
from unittest.mock import Mock, DEFAULT
from types import SimpleNamespace
from concurrent import futures
class TestHttpClient(TestCase):
json_str = '{ "foo": "bar" }'
def test_ok(self):
... | 0.47658 | 0.227748 |
import base64
import binascii
import datetime
import random
import string
import sys
import traceback
import six
import hszinc
from hszinc import VER_3_0, Grid, MODE_ZINC, MODE_JSON, XStr
from .pint_enable import to_pint
STR_CHARSET = string.ascii_letters + string.digits + '\n\r\t\f\b'
GENERATION_NUMBER = 1 # FIXME... | tests/test_acid.py | import base64
import binascii
import datetime
import random
import string
import sys
import traceback
import six
import hszinc
from hszinc import VER_3_0, Grid, MODE_ZINC, MODE_JSON, XStr
from .pint_enable import to_pint
STR_CHARSET = string.ascii_letters + string.digits + '\n\r\t\f\b'
GENERATION_NUMBER = 1 # FIXME... | 0.315314 | 0.167593 |
import pytest
from responsibleai import ModelAnalysis
from ..common_utils import create_iris_data, create_lightgbm_classifier
class TestCounterfactualAdvancedFeatures(object):
@pytest.mark.parametrize('vary_all_features', [True, False])
@pytest.mark.parametrize('feature_importance', [True, False])
def... | responsibleai/tests/counterfactual/test_counterfactual_advanced_features.py |
import pytest
from responsibleai import ModelAnalysis
from ..common_utils import create_iris_data, create_lightgbm_classifier
class TestCounterfactualAdvancedFeatures(object):
@pytest.mark.parametrize('vary_all_features', [True, False])
@pytest.mark.parametrize('feature_importance', [True, False])
def... | 0.476823 | 0.602939 |
import unittest
import numpy as np
from lander.environment import MarsLanderEnv
class MarsLanderEnvTest(unittest.TestCase):
def test_detection_landing_area(self):
# https://www.codingame.com/ide/puzzle/mars-lander - Initial speed, correct side
ground = np.array(
[
[... | lander/environment_test.py | import unittest
import numpy as np
from lander.environment import MarsLanderEnv
class MarsLanderEnvTest(unittest.TestCase):
def test_detection_landing_area(self):
# https://www.codingame.com/ide/puzzle/mars-lander - Initial speed, correct side
ground = np.array(
[
[... | 0.575827 | 0.688161 |
import logging, os
from libavg import player
from configs import config_app
from configs.config_app import kinect_data_ip
from configs.config_study import LoggingDefaults
from logging_base.body_tracking.skeleton_manager import SkeletonManager
from logging_base.body_tracking.skeleton import OSCKinectJoint
class LogFi... | logging_base/study_logging.py | import logging, os
from libavg import player
from configs import config_app
from configs.config_app import kinect_data_ip
from configs.config_study import LoggingDefaults
from logging_base.body_tracking.skeleton_manager import SkeletonManager
from logging_base.body_tracking.skeleton import OSCKinectJoint
class LogFi... | 0.444806 | 0.07658 |
import re
from pathlib import Path
from pymystem3 import Mystem
import pymorphy2
from constants import ASSETS_PATH
from core_utils.article import Article, ArtifactType
class EmptyDirectoryError(Exception):
"""
No data to process
"""
class InconsistentDatasetError(Exception):
"""
Corrupt data:
... | pipeline.py | import re
from pathlib import Path
from pymystem3 import Mystem
import pymorphy2
from constants import ASSETS_PATH
from core_utils.article import Article, ArtifactType
class EmptyDirectoryError(Exception):
"""
No data to process
"""
class InconsistentDatasetError(Exception):
"""
Corrupt data:
... | 0.741487 | 0.318856 |
import sys
from collections import defaultdict
def load_data(filename):
data = []
fd = open(filename,'r')
for line in fd:
fields = line.strip().split('\t')
if len(fields) == 3:
label = fields[0]
tokens = fields[1].split(' ')
ids = fields[2].split(' ')
... | evaluate_entities.py |
import sys
from collections import defaultdict
def load_data(filename):
data = []
fd = open(filename,'r')
for line in fd:
fields = line.strip().split('\t')
if len(fields) == 3:
label = fields[0]
tokens = fields[1].split(' ')
ids = fields[2].split(' ')
... | 0.223971 | 0.20951 |
import os
import subprocess
import sys
import tempfile
def stop_err(msg):
sys.stderr.write(msg)
sys.exit()
def main():
infile1 = sys.argv[1]
infile2 = sys.argv[2]
field1 = int(sys.argv[3])
field2 = int(sys.argv[4])
mode = sys.argv[5]
outfile = sys.argv[6]
tmpfile1 = tempfile.Nam... | tools/filters/joinWrapper.py | import os
import subprocess
import sys
import tempfile
def stop_err(msg):
sys.stderr.write(msg)
sys.exit()
def main():
infile1 = sys.argv[1]
infile2 = sys.argv[2]
field1 = int(sys.argv[3])
field2 = int(sys.argv[4])
mode = sys.argv[5]
outfile = sys.argv[6]
tmpfile1 = tempfile.Nam... | 0.102355 | 0.111701 |
from __future__ import absolute_import
import os
import atexit
from fstrings import f
from scrim.globals import (
SHELLS,
SCRIM_AUTO_WRITE,
SCRIM_PATH,
SCRIM_SHELL,
SCRIM_SCRIPT
)
from scrim.commands import CommandExecutor, Command, RawCommand
from scrim.utils import init_attr
__all__ = ['Scrim', 'g... | scrim/api.py | from __future__ import absolute_import
import os
import atexit
from fstrings import f
from scrim.globals import (
SHELLS,
SCRIM_AUTO_WRITE,
SCRIM_PATH,
SCRIM_SHELL,
SCRIM_SCRIPT
)
from scrim.commands import CommandExecutor, Command, RawCommand
from scrim.utils import init_attr
__all__ = ['Scrim', 'g... | 0.644113 | 0.131982 |
import numpy as np
from librosa.core import load
from librosa.core import stft as rose_stft
from librosa.core import istft as rose_istft
from librosa.output import write_wav as rose_write_wav
from librosa.feature import mfcc
import glob
import os
def read_wav(filename, sr=16000):
'''
load the data from a ... | single_channel/utils.py | import numpy as np
from librosa.core import load
from librosa.core import stft as rose_stft
from librosa.core import istft as rose_istft
from librosa.output import write_wav as rose_write_wav
from librosa.feature import mfcc
import glob
import os
def read_wav(filename, sr=16000):
'''
load the data from a ... | 0.629091 | 0.337913 |
import inspect
from collections.abc import Callable, Awaitable
from typing import Any
from bolinette.exceptions import InternalError
def _parse_params(function, *args, **kwargs):
cur_arg = 0
arg_cnt = len(args)
out_args = []
out_kwargs = {}
for key, param in inspect.signature(function).parameters... | bolinette/utils/functions.py | import inspect
from collections.abc import Callable, Awaitable
from typing import Any
from bolinette.exceptions import InternalError
def _parse_params(function, *args, **kwargs):
cur_arg = 0
arg_cnt = len(args)
out_args = []
out_kwargs = {}
for key, param in inspect.signature(function).parameters... | 0.467332 | 0.130424 |
from copy import deepcopy
from typing import Dict, List
import pytest
from github.Organization import Organization
from github.Repository import Repository
from github.Team import Team
from repo_manager._groups import teams
from repo_manager._util import HandlerRequest
from ..integration_test_utils import agithub_cl... | test/integration/groups/test_teams.py | from copy import deepcopy
from typing import Dict, List
import pytest
from github.Organization import Organization
from github.Repository import Repository
from github.Team import Team
from repo_manager._groups import teams
from repo_manager._util import HandlerRequest
from ..integration_test_utils import agithub_cl... | 0.498535 | 0.373533 |
# (x, y width, height)
# Left Paddle position: <rect(0, 267, 37, 266)>
import pygame
pygame.init()
from pygame.sprite import Sprite
class Bottom_Paddle(Sprite):
def __init__(self, ai_settings, screen):
"""Create the Bottom_Paddle and set its starting position."""
... | bottom_paddle.py |
# (x, y width, height)
# Left Paddle position: <rect(0, 267, 37, 266)>
import pygame
pygame.init()
from pygame.sprite import Sprite
class Bottom_Paddle(Sprite):
def __init__(self, ai_settings, screen):
"""Create the Bottom_Paddle and set its starting position."""
... | 0.476092 | 0.151184 |
from pygame.sprite import Sprite
from pygame import Surface
import pygame
class BasicBlock(Sprite):
def __init__(self, color, startx, starty, width, height, name):
super(BasicBlock, self).__init__()
self.image = Surface([width, height])
self.image.fill(color)
self.image.convert()
... | htc_client/build_a_network/entity.py | from pygame.sprite import Sprite
from pygame import Surface
import pygame
class BasicBlock(Sprite):
def __init__(self, color, startx, starty, width, height, name):
super(BasicBlock, self).__init__()
self.image = Surface([width, height])
self.image.fill(color)
self.image.convert()
... | 0.511473 | 0.263561 |