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
def CalculateHowManyRelationsWithShortestPathInDataset (Sentences): POS_NEG_DICT = {"Positives":0 , "Negatives":0}; CLASS_TP_DICT = {"NEG":0} ; for sentence in Sentences: for pair in sentence["PAIRS"]: if (pair.has_key("TOPKP")) and (pair.has_key("TOPKP_Features")): if ...
ANN_Systems/TSDPTSVMCore/SharedFunctions.py
def CalculateHowManyRelationsWithShortestPathInDataset (Sentences): POS_NEG_DICT = {"Positives":0 , "Negatives":0}; CLASS_TP_DICT = {"NEG":0} ; for sentence in Sentences: for pair in sentence["PAIRS"]: if (pair.has_key("TOPKP")) and (pair.has_key("TOPKP_Features")): if ...
0.147709
0.311584
import torch from torch import nn from core.modules import LayerNorm from typing import Optional import torch.nn.functional as F class UtteranceEncoder(nn.Module): def __init__(self, idim: int, n_layers: int = 2, n_chans: int = 256, kernel_size: int = 5, ...
core/acoustic_encoder.py
import torch from torch import nn from core.modules import LayerNorm from typing import Optional import torch.nn.functional as F class UtteranceEncoder(nn.Module): def __init__(self, idim: int, n_layers: int = 2, n_chans: int = 256, kernel_size: int = 5, ...
0.961071
0.44089
from __future__ import annotations import collections import functools import pickle import sys from abc import ABC, abstractmethod from concurrent.futures.thread import ThreadPoolExecutor from typing import Callable, Dict, Union, Any, List, Sequence, Optional import json import logging import re import threading fro...
src/sensai/util/cache_azure.py
from __future__ import annotations import collections import functools import pickle import sys from abc import ABC, abstractmethod from concurrent.futures.thread import ThreadPoolExecutor from typing import Callable, Dict, Union, Any, List, Sequence, Optional import json import logging import re import threading fro...
0.781247
0.200675
from commons.conversion import utc_timestamp_to_datetime from commons.model import Model def build_weather_5_day_forecast_object(weather_dict): """ :type weather_dict: :rtype: commons.weather.Weather5DayForecast """ forecast_timestamp = int(weather_dict.get("dt")) temperature = float(weather_d...
commons/commons/weather.py
from commons.conversion import utc_timestamp_to_datetime from commons.model import Model def build_weather_5_day_forecast_object(weather_dict): """ :type weather_dict: :rtype: commons.weather.Weather5DayForecast """ forecast_timestamp = int(weather_dict.get("dt")) temperature = float(weather_d...
0.814201
0.227008
import pytz from django.conf import settings from django.test import TestCase from unittest.mock import patch # Import module from backend.exporter import * class ExportFilterTest(TestCase): def setUp(self) -> None: """ Create a folder, clip, project and filter. """ self.rid = cr...
backend/test/test_integration/test_exporter.py
import pytz from django.conf import settings from django.test import TestCase from unittest.mock import patch # Import module from backend.exporter import * class ExportFilterTest(TestCase): def setUp(self) -> None: """ Create a folder, clip, project and filter. """ self.rid = cr...
0.394551
0.357147
import unittest from BlastApi import BlastSearchValidator from tests.Validator.TestCase import TestCase, _NOT_NONE_ERROR, _NOT_EMPTY_ERROR, _PROGRAMS, _INVALID_ERROR class BlastSearchValidatorTest(TestCase): validator = BlastSearchValidator() def test_required_params(self): params = {'QUERY': 'test'...
tests/Validator/BlastSearchValidatorTest.py
import unittest from BlastApi import BlastSearchValidator from tests.Validator.TestCase import TestCase, _NOT_NONE_ERROR, _NOT_EMPTY_ERROR, _PROGRAMS, _INVALID_ERROR class BlastSearchValidatorTest(TestCase): validator = BlastSearchValidator() def test_required_params(self): params = {'QUERY': 'test'...
0.531209
0.39289
from PIL import Image, ImageDraw, ImageFont # pip install pillow import numpy import cv2 import sys, os FONT_MARGIN = 2 COLOR_MAP = { '1': (255, 35, 11), '0': (16, 194, 20), 'C': (136, 0, 21), 'D': (7, 92, 10)} OUTPATH = 'output' def get_attr(info, default=None, isBoolean=False): value = in...
zealots/zealots_animation_maker.py
from PIL import Image, ImageDraw, ImageFont # pip install pillow import numpy import cv2 import sys, os FONT_MARGIN = 2 COLOR_MAP = { '1': (255, 35, 11), '0': (16, 194, 20), 'C': (136, 0, 21), 'D': (7, 92, 10)} OUTPATH = 'output' def get_attr(info, default=None, isBoolean=False): value = in...
0.156911
0.170473
import argparse import os, sys import random, struct import cPickle as pickle import time, socket, select from Queue import Queue from threading import Thread, RLock, Lock, Condition, Timer, Semaphore from concoord.enums import * from concoord.nameserver import Nameserver from concoord.exception import ConnectionError ...
concoord/node.py
import argparse import os, sys import random, struct import cPickle as pickle import time, socket, select from Queue import Queue from threading import Thread, RLock, Lock, Condition, Timer, Semaphore from concoord.enums import * from concoord.nameserver import Nameserver from concoord.exception import ConnectionError ...
0.238284
0.060641
from typing import Optional from aiogram.types import Update from aiogram.types import ParseMode from aiogram.utils.exceptions import MessageCantBeDeleted from aiogram.utils.exceptions import MessageCantBeEdited from aiogram.utils.exceptions import MessageIdInvalid from aiogram.utils.exceptions import MessageNotModif...
bot/platforms/telegram/commands/creator/errors_handler.py
from typing import Optional from aiogram.types import Update from aiogram.types import ParseMode from aiogram.utils.exceptions import MessageCantBeDeleted from aiogram.utils.exceptions import MessageCantBeEdited from aiogram.utils.exceptions import MessageIdInvalid from aiogram.utils.exceptions import MessageNotModif...
0.656988
0.206494
import os import ctypes import pyttsx3 import speech_recognition as sr import math import traceback from pyttsx3.drivers import sapi5 import random import threading import datetime import PySimpleGUI as sg from stat import S_IWUSR, S_IREAD import matplotlib.pyplot as plt import wx global log try: fr...
Diagnostify.py
import os import ctypes import pyttsx3 import speech_recognition as sr import math import traceback from pyttsx3.drivers import sapi5 import random import threading import datetime import PySimpleGUI as sg from stat import S_IWUSR, S_IREAD import matplotlib.pyplot as plt import wx global log try: fr...
0.38769
0.144179
import os import shutil import subprocess from pathlib import Path output_dir = "projects/fs_vid2vid/output/face_forensics" def preprocess(image_path, video_path): test_data_dir = "projects/fs_vid2vid/test_data/faceForensics" video_filename, video_parent = Path(video_path).stem, Path(video_path).parent ...
src/fsvid2vid.py
import os import shutil import subprocess from pathlib import Path output_dir = "projects/fs_vid2vid/output/face_forensics" def preprocess(image_path, video_path): test_data_dir = "projects/fs_vid2vid/test_data/faceForensics" video_filename, video_parent = Path(video_path).stem, Path(video_path).parent ...
0.438064
0.286219
import os from instascrape.utils import to_datetime from instascrape.commands import COOKIES_DIR, error_print, dump_cookie, load_cookie, load_obj from colorama import Fore, Style def cookies_handler(**args): action = args.get("action") insta = load_obj() cookies = [f for f in os.listdir(COOKIES_DIR) if ...
instascrape/commands/cookies.py
import os from instascrape.utils import to_datetime from instascrape.commands import COOKIES_DIR, error_print, dump_cookie, load_cookie, load_obj from colorama import Fore, Style def cookies_handler(**args): action = args.get("action") insta = load_obj() cookies = [f for f in os.listdir(COOKIES_DIR) if ...
0.053837
0.093927
import argparse import contextlib import errno import io import json import os import re import shutil import subprocess import sys import tempfile import time import unittest sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), os.path.pardir)) import backups_lib __package__ = backups_lib.__package__ from . i...
checkpoint_lib_test.py
import argparse import contextlib import errno import io import json import os import re import shutil import subprocess import sys import tempfile import time import unittest sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), os.path.pardir)) import backups_lib __package__ = backups_lib.__package__ from . i...
0.296349
0.168823
__version__ = "1.0" __author__ = "<NAME>" __copyright__ = "Copyright 2021, <NAME>" __license__ = "Apache 2.0" import pyaudio, serial, time from scipy.interpolate import interp1d from numpy import cos, pi, zeros, frombuffer, float32, roll, average from acoustic_trilateration import get_time_shift, trilateration, butte...
acoustic_fixture/acoustic_fixture.py
__version__ = "1.0" __author__ = "<NAME>" __copyright__ = "Copyright 2021, <NAME>" __license__ = "Apache 2.0" import pyaudio, serial, time from scipy.interpolate import interp1d from numpy import cos, pi, zeros, frombuffer, float32, roll, average from acoustic_trilateration import get_time_shift, trilateration, butte...
0.338514
0.199756
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler import tensorflow as tf def reshape_array_and_save_to_path(arr_data, arr_label, path, timesteps, target_hour, data_type="Train"): # reshaping the array from 3D # matrice to 2D matrice. arr_data_reshaped = arr_data.resha...
src/data/create_load_transform_processed_data.py
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler import tensorflow as tf def reshape_array_and_save_to_path(arr_data, arr_label, path, timesteps, target_hour, data_type="Train"): # reshaping the array from 3D # matrice to 2D matrice. arr_data_reshaped = arr_data.resha...
0.404625
0.534248
from moviepy.editor import * import cv2 from utils.image_utils import * import math class Gif_TO_VIDEO(object): def __init__(self, gifs_path, bgm_path): # gif目录 self.gifs_path = gifs_path # BGM目录 self.bgm_path = bgm_path # 视频帧率 self.fps = 10 self.img_size...
video_auto/制作GIF视频/gif_make_video.py
from moviepy.editor import * import cv2 from utils.image_utils import * import math class Gif_TO_VIDEO(object): def __init__(self, gifs_path, bgm_path): # gif目录 self.gifs_path = gifs_path # BGM目录 self.bgm_path = bgm_path # 视频帧率 self.fps = 10 self.img_size...
0.187467
0.131563
from tkinter import ttk import tkinter as tk import cartopy.crs as ccrs import eosim.gui.helpwindow as helpwindow class Mercator(ttk.Frame): def __init__(self, parent, controller): ttk.Frame.__init__(self, parent) mercator_proj_frame = ttk.Frame(self) mercator_proj_frame.grid(row...
eosim/gui/mapprojections.py
from tkinter import ttk import tkinter as tk import cartopy.crs as ccrs import eosim.gui.helpwindow as helpwindow class Mercator(ttk.Frame): def __init__(self, parent, controller): ttk.Frame.__init__(self, parent) mercator_proj_frame = ttk.Frame(self) mercator_proj_frame.grid(row...
0.506591
0.211946
# <pep8 compliant> # Generic Panels (Independent of DataType) # NOTE: # The specialized panel types are derived in their respective UI modules # don't register these classes since they are only helpers. class MotionPathButtonsPanel(): bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_label = "M...
release/scripts/startup/bl_ui/properties_animviz.py
# <pep8 compliant> # Generic Panels (Independent of DataType) # NOTE: # The specialized panel types are derived in their respective UI modules # don't register these classes since they are only helpers. class MotionPathButtonsPanel(): bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_label = "M...
0.31279
0.225214
import numpy as np from skimage import io, color, exposure, transform from sklearn.model_selection import train_test_split import os import glob import h5py import numpy as np from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.layers import Activation from tensorflow.keras.models...
train_gtsrb.py
import numpy as np from skimage import io, color, exposure, transform from sklearn.model_selection import train_test_split import os import glob import h5py import numpy as np from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.layers import Activation from tensorflow.keras.models...
0.667473
0.404978
from typing import Iterable, Optional, TypeVar from stock_indicators._cslib import CsIndicator from stock_indicators._cstypes import List as CsList from stock_indicators.indicators.common.results import IndicatorResults, ResultBase from stock_indicators.indicators.common.quote import Quote def get_prs(base_history: ...
stock_indicators/indicators/prs.py
from typing import Iterable, Optional, TypeVar from stock_indicators._cslib import CsIndicator from stock_indicators._cstypes import List as CsList from stock_indicators.indicators.common.results import IndicatorResults, ResultBase from stock_indicators.indicators.common.quote import Quote def get_prs(base_history: ...
0.947491
0.499207
from thrift.Thrift import TType, TMessageType, TException, TApplicationException from ttypes import * from thrift.Thrift import TProcessor from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol try: from thrift.protocol import fastbinary except: fastbinary = None class Ifa...
examples/python/flurry/Flurry.py
from thrift.Thrift import TType, TMessageType, TException, TApplicationException from ttypes import * from thrift.Thrift import TProcessor from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol try: from thrift.protocol import fastbinary except: fastbinary = None class Ifa...
0.485112
0.065665
import logging import tensorflow as tf class AlexNet: SEED = 42 def __init__(self, nb_classes=3): self.initializer = tf.initializers.glorot_uniform(seed=AlexNet.SEED) self.weight_shapes = [ [11, 11, 1, 96], [5, 5, 96, 256], [3, 3, 256, 384], [...
deep_cluster/convnet/alexnet.py
import logging import tensorflow as tf class AlexNet: SEED = 42 def __init__(self, nb_classes=3): self.initializer = tf.initializers.glorot_uniform(seed=AlexNet.SEED) self.weight_shapes = [ [11, 11, 1, 96], [5, 5, 96, 256], [3, 3, 256, 384], [...
0.890574
0.35782
import numpy as np import pandas as pd import csv from sklearn.feature_extraction.text import CountVectorizer from sklearn.linear_model import LogisticRegression # Load data about each article in a dataframe df = pd.read_csv("Data/node_information.csv") print(df.head()) # Read training data train_ids = list() y_train...
text_baseline.py
import numpy as np import pandas as pd import csv from sklearn.feature_extraction.text import CountVectorizer from sklearn.linear_model import LogisticRegression # Load data about each article in a dataframe df = pd.read_csv("Data/node_information.csv") print(df.head()) # Read training data train_ids = list() y_train...
0.629547
0.439026
import os import sys import h5py from matplotlib import rcParams import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit from presto.utils import rotate_opt rcParams['figure.dpi'] = 108.8 if len(sys.argv) == 2: load_filename = sys.argv[1] print(f"Loading: {os.path.realpath(lo...
load_ramsey.py
import os import sys import h5py from matplotlib import rcParams import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit from presto.utils import rotate_opt rcParams['figure.dpi'] = 108.8 if len(sys.argv) == 2: load_filename = sys.argv[1] print(f"Loading: {os.path.realpath(lo...
0.400398
0.36077
from odin.utils.trainable_models import TrainableModel from odin.utils.gaussian_processes import GaussianProcess from odin.utils.tensorflow_optimizer import ExtendedScipyOptimizerInterface import numpy as np import tensorflow as tf from typing import Union, Tuple import time class ODERiskMinimization(object): """ ...
odin/core/ODE_risk_minimization.py
from odin.utils.trainable_models import TrainableModel from odin.utils.gaussian_processes import GaussianProcess from odin.utils.tensorflow_optimizer import ExtendedScipyOptimizerInterface import numpy as np import tensorflow as tf from typing import Union, Tuple import time class ODERiskMinimization(object): """ ...
0.906473
0.529385
import datetime import traceback # this is modified code from a private project class Lesson: def __init__( self, name: str, teacher: str, ausfall: bool, student_id: int, student_data: dict, ): self.data = {} self.deletion_candiate = False ...
demonstration_bot/stundenplan.py
import datetime import traceback # this is modified code from a private project class Lesson: def __init__( self, name: str, teacher: str, ausfall: bool, student_id: int, student_data: dict, ): self.data = {} self.deletion_candiate = False ...
0.285671
0.272761
import sys sys.path.append('../utils') from ops import dense_sum_list, get_shape from np_op import convert2list import tensorflow as tf import numpy as np import os def test1(id_=0): ''' dense_sum_list test Results : =================Round1=================== const : [4, 2] [[ 1. ...
tfops/ops_test.py
import sys sys.path.append('../utils') from ops import dense_sum_list, get_shape from np_op import convert2list import tensorflow as tf import numpy as np import os def test1(id_=0): ''' dense_sum_list test Results : =================Round1=================== const : [4, 2] [[ 1. ...
0.270095
0.332852
from dataclasses import dataclass from datetime import date, datetime import mock from pdfminer.layout import LTChar, LTCurve, LTFigure, LTImage, LTTextBoxHorizontal, LTTextLineHorizontal from typing import List from rdr_service.services.consent import files from tests.helpers.unittest_base import BaseTestCase class...
tests/service_tests/consent_tests/test_consent_file_parsing.py
from dataclasses import dataclass from datetime import date, datetime import mock from pdfminer.layout import LTChar, LTCurve, LTFigure, LTImage, LTTextBoxHorizontal, LTTextLineHorizontal from typing import List from rdr_service.services.consent import files from tests.helpers.unittest_base import BaseTestCase class...
0.832951
0.174445
import os import re import platform from datetime import datetime, timezone, timedelta, date import requests from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.support import expected_conditions from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import W...
MovieScheduleParser/parser.py
import os import re import platform from datetime import datetime, timezone, timedelta, date import requests from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.support import expected_conditions from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import W...
0.63307
0.092196
from apps.bot.classes.Command import Command from apps.bot.classes.consts.Consts import Role from apps.service.models import MilanaTranslate class Discord(Command): name = "милана" names = ["милок", "мил"] help_text = "переводчик с языка Миланы" help_texts = [ "- (пересланное сообщение) - пер...
apps/bot/commands/TrustedCommands/Milana.py
from apps.bot.classes.Command import Command from apps.bot.classes.consts.Consts import Role from apps.service.models import MilanaTranslate class Discord(Command): name = "милана" names = ["милок", "мил"] help_text = "переводчик с языка Миланы" help_texts = [ "- (пересланное сообщение) - пер...
0.365117
0.178114
__author__ = "<NAME>" __version__ = "CS224u, Stanford, Spring 2016" import sys import csv import numpy as np import torch def build(src_filename, delimiter=',', header=True, quoting=csv.QUOTE_MINIMAL): """Reads in matrices from CSV or space-delimited files. Parameters ---------- src_filename : str ...
glove_utils.py
__author__ = "<NAME>" __version__ = "CS224u, Stanford, Spring 2016" import sys import csv import numpy as np import torch def build(src_filename, delimiter=',', header=True, quoting=csv.QUOTE_MINIMAL): """Reads in matrices from CSV or space-delimited files. Parameters ---------- src_filename : str ...
0.696991
0.454291
import tilemapbase as tmb import matplotlib.pyplot as plt import matplotlib.lines as lines import folium from .maputil import copyright_osm import numpy as np import re tmb.init(create=True) def _extend(m, M, p): w = M - m return m - p*w, M + p*w def _expand(ex, p): xmin, xmax = _extend(ex.xmin, ex.xma...
dtws1/trajectory.py
import tilemapbase as tmb import matplotlib.pyplot as plt import matplotlib.lines as lines import folium from .maputil import copyright_osm import numpy as np import re tmb.init(create=True) def _extend(m, M, p): w = M - m return m - p*w, M + p*w def _expand(ex, p): xmin, xmax = _extend(ex.xmin, ex.xma...
0.410166
0.404802
from ..utils import file_json_utils as json_util def get_review_threads_by_pr(pr_detail_file_path): reply_review_inline_comment_template = {"id": "id", "url": "url", "bodyText": "bodyText", "author": "author.login", "createdAt": "createdAt", "replyToReviewId": "replyTo.id"} ...
lib/github/PRsDataManager.py
from ..utils import file_json_utils as json_util def get_review_threads_by_pr(pr_detail_file_path): reply_review_inline_comment_template = {"id": "id", "url": "url", "bodyText": "bodyText", "author": "author.login", "createdAt": "createdAt", "replyToReviewId": "replyTo.id"} ...
0.233532
0.16228
from marshmallow import Schema, fields, validate, pre_load, ValidationError import ipaddress class NETunnelSchema(Schema): """ Base schema for netunnel objects For backwards compatibility to marshmallow 2.X, we're using self.dump3 and self.load3 instead of self.dump & self.load to make them as similar as possib...
netunnel/server/schemas.py
from marshmallow import Schema, fields, validate, pre_load, ValidationError import ipaddress class NETunnelSchema(Schema): """ Base schema for netunnel objects For backwards compatibility to marshmallow 2.X, we're using self.dump3 and self.load3 instead of self.dump & self.load to make them as similar as possib...
0.511229
0.21032
from _math import Vector3 from timeit import itertools from elements import GeneratorElement from interactions.constraints import Circle, Constraint, create_constraint_set from interactions.utils.routing import PlanRoute, FollowPath from objects.components.types import ROUTING_COMPONENT from server_commands.argument_he...
S4/S4 Library/simulation/routing/routing_commands.py
from _math import Vector3 from timeit import itertools from elements import GeneratorElement from interactions.constraints import Circle, Constraint, create_constraint_set from interactions.utils.routing import PlanRoute, FollowPath from objects.components.types import ROUTING_COMPONENT from server_commands.argument_he...
0.524882
0.167389
import unittest from source.utilities.transformer import Transformer from source.utilities.graph import Graph from source.utilities.solver import Solver from source.dataStructures import Vector class Solver_test(unittest.TestCase): def test_solver_can_check_for_a_solution(self): (zeroGraph, vectorLi...
source/tests/solver_test.py
import unittest from source.utilities.transformer import Transformer from source.utilities.graph import Graph from source.utilities.solver import Solver from source.dataStructures import Vector class Solver_test(unittest.TestCase): def test_solver_can_check_for_a_solution(self): (zeroGraph, vectorLi...
0.557123
0.627723
import os from PIL import Image import numpy as np from scipy.interpolate import griddata import cv2 import argparse def getSymXYcoordinates(iuv, resolution=256, dp_uv_lookup_256_np=None): if dp_uv_lookup_256_np is None: dp_uv_lookup_256_np = np.load('util/dp_uv_lookup_256.npy') xy, xyMask = getXYcoor(...
util/dp2coor.py
import os from PIL import Image import numpy as np from scipy.interpolate import griddata import cv2 import argparse def getSymXYcoordinates(iuv, resolution=256, dp_uv_lookup_256_np=None): if dp_uv_lookup_256_np is None: dp_uv_lookup_256_np = np.load('util/dp_uv_lookup_256.npy') xy, xyMask = getXYcoor(...
0.397003
0.320449
import os from enum import IntEnum import random import re import time from study_tool.card import Card, CardSide, SourceLocation from study_tool.card_attributes import CardAttributes from study_tool.external import googledocs from study_tool.russian.types import * from study_tool.russian.word import * from study_tool....
study_tool/card_set.py
import os from enum import IntEnum import random import re import time from study_tool.card import Card, CardSide, SourceLocation from study_tool.card_attributes import CardAttributes from study_tool.external import googledocs from study_tool.russian.types import * from study_tool.russian.word import * from study_tool....
0.602529
0.153708
from knowledge_graph.graph_indexer import GraphIndexer from knowledge_graph.config import DB_IDS class SimilarityWeightsTest(GraphIndexer): """ Used to create the relations (calls the insert for every article) Used to test the relations """ def __init__(self, db_ids): GraphIndexer.__init...
scripts/index_article_graph.py
from knowledge_graph.graph_indexer import GraphIndexer from knowledge_graph.config import DB_IDS class SimilarityWeightsTest(GraphIndexer): """ Used to create the relations (calls the insert for every article) Used to test the relations """ def __init__(self, db_ids): GraphIndexer.__init...
0.610802
0.219515
START = """ Hey 🌍!! Tudo tranquilo?? Bem vindo ao Corona-Tracker! Para visualizar os comandos, registre-se em nossa base com o comando /register. """ # ============================================================================= # REGISTER MESSAGE # =================================================================...
code/constants/conversations.py
START = """ Hey 🌍!! Tudo tranquilo?? Bem vindo ao Corona-Tracker! Para visualizar os comandos, registre-se em nossa base com o comando /register. """ # ============================================================================= # REGISTER MESSAGE # =================================================================...
0.278551
0.34054
import ast import pycodestyle from flake8 import utils as stdin_utils __version__ = "0.1.0" ERROR_CODE = "OW100" class OsWalkVisitor(ast.NodeVisitor): def __init__(self, *args, **kwargs): super(OsWalkVisitor, self).__init__(*args, **kwargs) self.violations = [] def visit_Call(self, node): ...
flake8_os_walk/checker.py
import ast import pycodestyle from flake8 import utils as stdin_utils __version__ = "0.1.0" ERROR_CODE = "OW100" class OsWalkVisitor(ast.NodeVisitor): def __init__(self, *args, **kwargs): super(OsWalkVisitor, self).__init__(*args, **kwargs) self.violations = [] def visit_Call(self, node): ...
0.449876
0.106924
from collections.abc import Mapping, Sequence class EventFilter: def __init__(self, tags=None, event_type=None, routing_key=None): self.tags = frozenset(tags) if tags is not None else tags self.event_type = frozenset(event_type) if event_type is not None else event_type self.routing_key = ...
zentral/core/events/filter.py
from collections.abc import Mapping, Sequence class EventFilter: def __init__(self, tags=None, event_type=None, routing_key=None): self.tags = frozenset(tags) if tags is not None else tags self.event_type = frozenset(event_type) if event_type is not None else event_type self.routing_key = ...
0.867864
0.118131
from pydes.core.simulation.model.controller import ControllerAlgorithm from pydes.core.simulation.model.scope import SystemScope, TaskScope from pydes.core.utils.csv_utils import read_csv from pydes.core.utils.report import SimpleReport as Report INDICES = ["population", "response", "throughput"] SYSTEM_SCOPES = [scop...
src/pydes/core/simulation/result_validator.py
from pydes.core.simulation.model.controller import ControllerAlgorithm from pydes.core.simulation.model.scope import SystemScope, TaskScope from pydes.core.utils.csv_utils import read_csv from pydes.core.utils.report import SimpleReport as Report INDICES = ["population", "response", "throughput"] SYSTEM_SCOPES = [scop...
0.769124
0.468365
import rclpy from rclpy.node import Node from darknet_ros_msgs.msg import BoundingBoxes from object_analytics_msgs.msg import TrackedObjects, TrackedObject from sensor_msgs.msg import RegionOfInterest from object_tracking.tracking import Tracker class ObjectTrackingNode(Node): def __init__(self): super(...
src/object_tracking/object_tracking_node.py
import rclpy from rclpy.node import Node from darknet_ros_msgs.msg import BoundingBoxes from object_analytics_msgs.msg import TrackedObjects, TrackedObject from sensor_msgs.msg import RegionOfInterest from object_tracking.tracking import Tracker class ObjectTrackingNode(Node): def __init__(self): super(...
0.636353
0.178974
from pyspark.ml.pipeline import Pipeline as SparkPipeline from pyspark.ml.feature import OneHotEncoder, StandardScaler, MinMaxScaler, OneHotEncoderEstimator from pyspark.ml.feature import PCA, Imputer from pyspark.ml.feature import VectorAssembler, StringIndexer def since(version): """ A decorator that annot...
transformer.py
from pyspark.ml.pipeline import Pipeline as SparkPipeline from pyspark.ml.feature import OneHotEncoder, StandardScaler, MinMaxScaler, OneHotEncoderEstimator from pyspark.ml.feature import PCA, Imputer from pyspark.ml.feature import VectorAssembler, StringIndexer def since(version): """ A decorator that annot...
0.883198
0.390534
from tkinter import Tk, Toplevel, RAISED, Button, Label, messagebox, Entry, PhotoImage, Radiobutton, StringVar ,INSERT, scrolledtext import functions, pprint, io, contextlib #Functions def openWindow(windowName): mainWindow.withdraw() if (windowName == "infoMsgBox"): mainWindow.deiconify() messagebox.showinfo("I...
main.py
from tkinter import Tk, Toplevel, RAISED, Button, Label, messagebox, Entry, PhotoImage, Radiobutton, StringVar ,INSERT, scrolledtext import functions, pprint, io, contextlib #Functions def openWindow(windowName): mainWindow.withdraw() if (windowName == "infoMsgBox"): mainWindow.deiconify() messagebox.showinfo("I...
0.192539
0.114369
import warnings import numpy as np import scipy.sparse as sp def flip_adj(adj, flips, undirected=True): if isinstance(adj, (np.ndarray, np.matrix)): if undirected: flips = np.vstack([flips, flips[:, [1,0]]]) return flip_x(adj, flips) elif not sp.isspmatrix(adj): raise Value...
graphadv/utils/data_utils.py
import warnings import numpy as np import scipy.sparse as sp def flip_adj(adj, flips, undirected=True): if isinstance(adj, (np.ndarray, np.matrix)): if undirected: flips = np.vstack([flips, flips[:, [1,0]]]) return flip_x(adj, flips) elif not sp.isspmatrix(adj): raise Value...
0.569972
0.588505
from .constants import PDS_NS_URI, PRODUCT_COLLECTION_TAG from lxml import etree import logging, hashlib, os.path, functools, urllib, re # Logging # ------- _logger = logging.getLogger(__name__) # Private Constants # ----------------- _bufsiz = 512 # Byte buffer _xmlCache...
src/pds/aipgen/utils.py
from .constants import PDS_NS_URI, PRODUCT_COLLECTION_TAG from lxml import etree import logging, hashlib, os.path, functools, urllib, re # Logging # ------- _logger = logging.getLogger(__name__) # Private Constants # ----------------- _bufsiz = 512 # Byte buffer _xmlCache...
0.559531
0.122313
from __future__ import unicode_literals import frappe from frappe import msgprint, _ from datetime import date, timedelta,time def execute(filters=None): columns, data = [], [] planned_bc_count = planned_cl_count = 0 qr_details = get_qr_details(filters.shift_type,filters.date) columns = [ _("L...
thaisummit/thaisummit/report/qr_checkin_report/qr_checkin_report.py
from __future__ import unicode_literals import frappe from frappe import msgprint, _ from datetime import date, timedelta,time def execute(filters=None): columns, data = [], [] planned_bc_count = planned_cl_count = 0 qr_details = get_qr_details(filters.shift_type,filters.date) columns = [ _("L...
0.321993
0.109491
import heapq import random from typing import Dict, List, NamedTuple, Tuple from torch.utils.data import Sampler from utils import ceildiv class DeviceBucket(NamedTuple): """ Metadata for a device within a particular TokenBucket """ total_length: int # must be first so heap sorts based on it d...
data/sampler.py
import heapq import random from typing import Dict, List, NamedTuple, Tuple from torch.utils.data import Sampler from utils import ceildiv class DeviceBucket(NamedTuple): """ Metadata for a device within a particular TokenBucket """ total_length: int # must be first so heap sorts based on it d...
0.884371
0.34981
from sklearn.tree.export import _DOTTreeExporter from sklearn.tree import _tree from sklearn.ensemble import IsolationForest from io import StringIO import numpy as np class _DOTIFTreeExporter(_DOTTreeExporter): def __init__(self, meta_data, out_file=None): super().__init__(out_file=out_file, ...
ifgraphviz/ifgraphviz.py
from sklearn.tree.export import _DOTTreeExporter from sklearn.tree import _tree from sklearn.ensemble import IsolationForest from io import StringIO import numpy as np class _DOTIFTreeExporter(_DOTTreeExporter): def __init__(self, meta_data, out_file=None): super().__init__(out_file=out_file, ...
0.595257
0.246363
import os import random import discord from discord.ext import commands class ExamCommands(commands.Cog): def __init__(self, client): self.client = client @staticmethod def write_data(data): with open('data.txt', 'a+') as file: for key, value in data.items(): file.write(f'{key}: {value}\n') @staticme...
cogs/ExamCommands.py
import os import random import discord from discord.ext import commands class ExamCommands(commands.Cog): def __init__(self, client): self.client = client @staticmethod def write_data(data): with open('data.txt', 'a+') as file: for key, value in data.items(): file.write(f'{key}: {value}\n') @staticme...
0.084533
0.089973
import json import aiohttp from aquavalet import streams, provider, exceptions from aquavalet.providers.utils import require_group, require_match message_no_internal_provider = "No internal provider in url, path must follow pattern ^\/(?P<internal_provider>(?:\w|\d)+)?\/(?P<resource>[a-zA-Z0-9]{5,})?(?P<path>\/.*)?" ...
aquavalet/providers/osfstyle/provider.py
import json import aiohttp from aquavalet import streams, provider, exceptions from aquavalet.providers.utils import require_group, require_match message_no_internal_provider = "No internal provider in url, path must follow pattern ^\/(?P<internal_provider>(?:\w|\d)+)?\/(?P<resource>[a-zA-Z0-9]{5,})?(?P<path>\/.*)?" ...
0.407687
0.081739
from __future__ import unicode_literals from django.db import models, migrations import bitfield.models import django.core.validators import mptt.fields import uuidfield.fields import timezone_field.fields class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.Creat...
geo/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import models, migrations import bitfield.models import django.core.validators import mptt.fields import uuidfield.fields import timezone_field.fields class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.Creat...
0.569254
0.167763
import RPi.GPIO as GPIO import queue, threading class LedBeeper: """ Handler-Klasse für die LED und den Piepser. Empfängt die Messwerte vom Ultraschallsensor und lässt die LED und den Piepser immer schneller blinken und tönen, je geringer der Abstand ist. Regaiert auf folgende Ereignisse: ...
03 Python/Einparkhilfe/loesung/src/myapp/hardware/led_beeper.py
import RPi.GPIO as GPIO import queue, threading class LedBeeper: """ Handler-Klasse für die LED und den Piepser. Empfängt die Messwerte vom Ultraschallsensor und lässt die LED und den Piepser immer schneller blinken und tönen, je geringer der Abstand ist. Regaiert auf folgende Ereignisse: ...
0.576423
0.228167
import os import boto3 import structlog from cfn_custom_resource import CloudFormationCustomResource from _metadata import CUSTOM_RESOURCE_NAME REGION = os.environ['AWS_REGION'] structlog.configure(processors=[structlog.processors.JSONRenderer()]) def dict_element_copy_if_exists( source_dict: dict, source...
lambda_code/ec2/FindAmi/index.py
import os import boto3 import structlog from cfn_custom_resource import CloudFormationCustomResource from _metadata import CUSTOM_RESOURCE_NAME REGION = os.environ['AWS_REGION'] structlog.configure(processors=[structlog.processors.JSONRenderer()]) def dict_element_copy_if_exists( source_dict: dict, source...
0.327131
0.068819
import datetime import scrapy.http from event.items import EventItem import event.util as util class SoleburyTroutEventPipeline(object): def process_item(self, item, spider): def parseDate(datestring): m_name, d, y = datestring.replace(',', '').split() m = datetime.datetime.str...
event/event/spiders/solebury_trout/pipelines.py
import datetime import scrapy.http from event.items import EventItem import event.util as util class SoleburyTroutEventPipeline(object): def process_item(self, item, spider): def parseDate(datestring): m_name, d, y = datestring.replace(',', '').split() m = datetime.datetime.str...
0.168891
0.149252
import argparse import os import codecs import datetime from html.parser import HTMLParser from html.entities import name2codepoint from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine, Integer, DateTime, Text, String, Column name2code...
history_converter.py
import argparse import os import codecs import datetime from html.parser import HTMLParser from html.entities import name2codepoint from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine, Integer, DateTime, Text, String, Column name2code...
0.352871
0.107134
# [START imports] import os import urllib from google.appengine.ext import ndb from google.appengine.api import app_identity import logging import os import jinja2 import webapp2 import uuid import StringIO from PIL import Image from PIL import ImageFont from PIL import ImageDraw JINJA_ENVIRONMENT = jinja2.Enviro...
captionit.py
# [START imports] import os import urllib from google.appengine.ext import ndb from google.appengine.api import app_identity import logging import os import jinja2 import webapp2 import uuid import StringIO from PIL import Image from PIL import ImageFont from PIL import ImageDraw JINJA_ENVIRONMENT = jinja2.Enviro...
0.491456
0.157363
import logging import requests from app.slack.slack_client import SlackClient from app.util.chunker import chunker logger = logging.getLogger('default') help_message = """``` Returns matching results from sc2ladder sorted by MMR. Usage: > .mmr <query> <filters...> Arguments: - query: will match battlenet or sc2 ...
app/commands/mmr_command.py
Returns matching results from sc2ladder sorted by MMR. Usage: > .mmr <query> <filters...> Arguments: - query: will match battlenet or sc2 in game names - filters: can be server, race, or number of results. these can be in any order. Examples: > .mmr avilo > .mmr avilo na terran 5 > .mmr showtime protoss 1 eu > .mmr...
0.709321
0.501892
import json from alipay.aop.api.constant.ParamConstants import * class SpiDetectionDetail(object): def __init__(self): self._code = None self._content = None self._data_id = None self._details = None self._label = None self._msg = None self._rate = None ...
alipay/aop/api/domain/SpiDetectionDetail.py
import json from alipay.aop.api.constant.ParamConstants import * class SpiDetectionDetail(object): def __init__(self): self._code = None self._content = None self._data_id = None self._details = None self._label = None self._msg = None self._rate = None ...
0.511473
0.102844
import pygame import os import sys import time import math from audio import Audio from bell import Bell from button import Button from keyPress import KeyPress from log import Log class RingingScreen(KeyPress, Log): def __init__(self, network, width, height, font, frameRate, logFile, config): if getattr...
src/ringingScreen.py
import pygame import os import sys import time import math from audio import Audio from bell import Bell from button import Button from keyPress import KeyPress from log import Log class RingingScreen(KeyPress, Log): def __init__(self, network, width, height, font, frameRate, logFile, config): if getattr...
0.149283
0.102036
import re import datetime from django.conf import settings class Contest: def __init__(self, serve_cfg_name): self.serve_cfg = self.read_serve_cfg(serve_cfg_name) self.problems = self.extract_problems_from_serve_cfg(self.serve_cfg) self.start_time = settings.CONTEST_START_TIME s...
src/ejudge/models.py
import re import datetime from django.conf import settings class Contest: def __init__(self, serve_cfg_name): self.serve_cfg = self.read_serve_cfg(serve_cfg_name) self.problems = self.extract_problems_from_serve_cfg(self.serve_cfg) self.start_time = settings.CONTEST_START_TIME s...
0.512937
0.123551
import urllib.request import random from bs4 import BeautifulSoup import sys def user_agent(): useragent = [ "Mozilla/5.0 CK={ } (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.372...
proxyParsertd.py
import urllib.request import random from bs4 import BeautifulSoup import sys def user_agent(): useragent = [ "Mozilla/5.0 CK={ } (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.372...
0.114876
0.105073
import os import gym import argparse import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from dqn import * from sac import * from utils import * from config import config from codecarbon import EmissionsTracker tracker = EmissionsTracker() tracker.start() import os impo...
main.py
import os import gym import argparse import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from dqn import * from sac import * from utils import * from config import config from codecarbon import EmissionsTracker tracker = EmissionsTracker() tracker.start() import os impo...
0.567218
0.113162
import pytest from pathlib import Path import pytest_mock from experiment_server._process_config import verify_config, get_sections, process_config_file MAIN_CONFIG_KEYS = ["buttonSize","trialsPerItem","conditionId","relativePosition", "participant_id", "step_name"] @pytest.mark.parametrize( "f, expected",[ ...
test/test_process_config.py
import pytest from pathlib import Path import pytest_mock from experiment_server._process_config import verify_config, get_sections, process_config_file MAIN_CONFIG_KEYS = ["buttonSize","trialsPerItem","conditionId","relativePosition", "participant_id", "step_name"] @pytest.mark.parametrize( "f, expected",[ ...
0.350088
0.367696
import base64 import zlib from google.protobuf import descriptor_pb2 # Includes description of the go.chromium.org/luci/buildbucket/proto/builds_service.proto and all of its transitive # dependencies. Includes source code info. FILE_DESCRIPTOR_SET = descriptor_pb2.FileDescriptorSet() FILE_DESCRIPTOR_SET.ParseFromStr...
python_pb2/go/chromium/org/luci/buildbucket/proto/builds_service_prpc_pb2.py
import base64 import zlib from google.protobuf import descriptor_pb2 # Includes description of the go.chromium.org/luci/buildbucket/proto/builds_service.proto and all of its transitive # dependencies. Includes source code info. FILE_DESCRIPTOR_SET = descriptor_pb2.FileDescriptorSet() FILE_DESCRIPTOR_SET.ParseFromStr...
0.214116
0.097605
import inspect from functools import update_wrapper from multiprocessing import Manager __all__ = ["SingleProcessCache", "MultiProcessCache"] class SingleProcessCache: """ >>> class A: >>> @SingleProcessCache(key="index") >>> def method(self,index): """ def __init__(self, key=None) -...
deepclustering/decorator/cache_decorator.py
import inspect from functools import update_wrapper from multiprocessing import Manager __all__ = ["SingleProcessCache", "MultiProcessCache"] class SingleProcessCache: """ >>> class A: >>> @SingleProcessCache(key="index") >>> def method(self,index): """ def __init__(self, key=None) -...
0.511961
0.147156
import pygame import json from loguru import logger class SpriteSheet(): """Manages the work with the given spritesheet """ def __init__(self, file): """loads the spritesheet Note: Inspired by: https://www.youtube.com/watch?v=ePiMYe7JpJo Args: file...
src/spritesheet.py
import pygame import json from loguru import logger class SpriteSheet(): """Manages the work with the given spritesheet """ def __init__(self, file): """loads the spritesheet Note: Inspired by: https://www.youtube.com/watch?v=ePiMYe7JpJo Args: file...
0.842539
0.417628
import sys import zmq import tnetstring import unittest import time sys.path.append('../') from src.item import Item from src.format import Format import src.zmqpubcontrolclient as zmqpcc class TestFormatSubClass(Format): def name(self): return 'name' def export(self): return {'body': 'bodyvalue'} pollin_respo...
tests/zmqpubcontrolclient_tests.py
import sys import zmq import tnetstring import unittest import time sys.path.append('../') from src.item import Item from src.format import Format import src.zmqpubcontrolclient as zmqpcc class TestFormatSubClass(Format): def name(self): return 'name' def export(self): return {'body': 'bodyvalue'} pollin_respo...
0.184841
0.107063
import jwt import datetime from project.server import app, db, bcrypt from .blacklistToken import BlacklistToken from .favourite import Favourite from .tmdb import Tmdb from .show import Show class User(db.Model): """ User Model for storing user related details """ __tablename__ = "users" id = db.Colum...
project/server/models/user.py
import jwt import datetime from project.server import app, db, bcrypt from .blacklistToken import BlacklistToken from .favourite import Favourite from .tmdb import Tmdb from .show import Show class User(db.Model): """ User Model for storing user related details """ __tablename__ = "users" id = db.Colum...
0.457137
0.071074
import csv import cv2 import numpy as np import random import sklearn from sklearn.model_selection import train_test_split samples = [] with open('./data/driving_log.csv') as csvfile: reader = csv.reader(csvfile) for line in reader: samples.append(line) train_samples, validation_samples = train_test_s...
clone.py
import csv import cv2 import numpy as np import random import sklearn from sklearn.model_selection import train_test_split samples = [] with open('./data/driving_log.csv') as csvfile: reader = csv.reader(csvfile) for line in reader: samples.append(line) train_samples, validation_samples = train_test_s...
0.551091
0.431105
import numpy as np def find_unimodal_range(x0, h, f): l = x0 - h r = x0 + h m = x0 step = 1 fm = f(x0) fl = f(l) fr = f(r) if fl > fm and fm < fr: return l, r elif fm > fr: while True: l = m m = r fm = fr step *= 2 ...
dz2/opty/algy.py
import numpy as np def find_unimodal_range(x0, h, f): l = x0 - h r = x0 + h m = x0 step = 1 fm = f(x0) fl = f(l) fr = f(r) if fl > fm and fm < fr: return l, r elif fm > fr: while True: l = m m = r fm = fr step *= 2 ...
0.25992
0.4474
import argparse import os import Config as c import pandas as pd from pandas_utils import group_categoricals_tail from sklearn.model_selection import RandomizedSearchCV def main(): # Load cli params parser = argparse.ArgumentParser(prog="grid") parser.add_argument("-d", "--data", dest="data", required=Tru...
gbtboilerplate/code/grid.py
import argparse import os import Config as c import pandas as pd from pandas_utils import group_categoricals_tail from sklearn.model_selection import RandomizedSearchCV def main(): # Load cli params parser = argparse.ArgumentParser(prog="grid") parser.add_argument("-d", "--data", dest="data", required=Tru...
0.537041
0.235586
from typing import Dict from ..base_category import BaseCategory # CD錄音帶 cd-and-tape class CdAndTape(object): def cd_and_tape() -> Dict[str, Dict[str, str]]: list = {} list['name'] = 'CD錄音帶' list['id'] = 'cd-and-tape' cd_and_tape = {} cd_and_tape['CD-tapes-manufacturers'] = 'CD片、錄音帶製造...
const/sub_categories/service/media.py
from typing import Dict from ..base_category import BaseCategory # CD錄音帶 cd-and-tape class CdAndTape(object): def cd_and_tape() -> Dict[str, Dict[str, str]]: list = {} list['name'] = 'CD錄音帶' list['id'] = 'cd-and-tape' cd_and_tape = {} cd_and_tape['CD-tapes-manufacturers'] = 'CD片、錄音帶製造...
0.293506
0.076132
import os import sparv.util as util from sparv import Annotation, Config, Document, Export, ExportAnnotations, SourceAnnotations, exporter logger = util.get_logger(__name__) @exporter("CSV export", config=[ Config("csv_export.delimiter", default="\t", description="Delimiter separating fields."), Config("cs...
sparv/modules/csv_export/csv_export.py
import os import sparv.util as util from sparv import Annotation, Config, Document, Export, ExportAnnotations, SourceAnnotations, exporter logger = util.get_logger(__name__) @exporter("CSV export", config=[ Config("csv_export.delimiter", default="\t", description="Delimiter separating fields."), Config("cs...
0.566618
0.23267
import datetime import cv2 import numpy as np from numpy.linalg import norm import os SZ = 20 # 训练图片长宽 def deskew(img): m = cv2.moments(img) if abs(m['mu02']) < 1e-2: return img.copy() skew = m['mu11'] / m['mu02'] M = np.float32([[1, skew, -0.5 * SZ * skew], [0, 1, 0]]) img = cv2.warpAff...
opencv_test1/svm_demo_chi.py
import datetime import cv2 import numpy as np from numpy.linalg import norm import os SZ = 20 # 训练图片长宽 def deskew(img): m = cv2.moments(img) if abs(m['mu02']) < 1e-2: return img.copy() skew = m['mu11'] / m['mu02'] M = np.float32([[1, skew, -0.5 * SZ * skew], [0, 1, 0]]) img = cv2.warpAff...
0.437343
0.42919
from UKF_SNMPC import * import numpy as np from casadi import * UKF_SNMPC = UKF_SNMPC() solver = UKF_SNMPC.solver U_pasts, Xd_pasts, Xa_pasts, Conp_pasts, Cont_pasts, xu_pasts, MeanSEx_pasts,\ CovSEx_pasts, t_pasts = UKF_SNMPC.initialization() number_of_repeats = UKF_SNMPC.nu...
Simulation_UKF_SNMPC.py
from UKF_SNMPC import * import numpy as np from casadi import * UKF_SNMPC = UKF_SNMPC() solver = UKF_SNMPC.solver U_pasts, Xd_pasts, Xa_pasts, Conp_pasts, Cont_pasts, xu_pasts, MeanSEx_pasts,\ CovSEx_pasts, t_pasts = UKF_SNMPC.initialization() number_of_repeats = UKF_SNMPC.nu...
0.469034
0.277021
from __future__ import unicode_literals import frappe def execute_0(filters=None): if not filters: filters ={} columns = [ "Item:Link/Item:300", "Item Group:Link/Item Group:140", "Customer:Link/Customer:200", "Qty:Float:50", "Amount:Currency:150" ] conditions = "" if filters.get("from_date"): condi...
tools_box/_selling/report/sales_by_product/sales_by_product.py
from __future__ import unicode_literals import frappe def execute_0(filters=None): if not filters: filters ={} columns = [ "Item:Link/Item:300", "Item Group:Link/Item Group:140", "Customer:Link/Customer:200", "Qty:Float:50", "Amount:Currency:150" ] conditions = "" if filters.get("from_date"): condi...
0.427397
0.153644
import gc import os import re import ssl import sys import time import trio import uuid import math import ftfy import ujson import shutil import random import hashlib import tarfile import requests import numpy as np import pandas as pd import pycld2 as cld2 from glob import glob from _thread import * from uuid impor...
ccpreprocessor.py
import gc import os import re import ssl import sys import time import trio import uuid import math import ftfy import ujson import shutil import random import hashlib import tarfile import requests import numpy as np import pandas as pd import pycld2 as cld2 from glob import glob from _thread import * from uuid impor...
0.245356
0.106737
import unittest import os import timeit import _test_utils from brotlidecpy import decompress from brotli import decompress as brotlidecompress class TestDecompress(_test_utils.TestCase): def _test_decompress(self, test_data): """This performs the same decompression tests as in the Python bindings of br...
test/test_decompress.py
import unittest import os import timeit import _test_utils from brotlidecpy import decompress from brotli import decompress as brotlidecompress class TestDecompress(_test_utils.TestCase): def _test_decompress(self, test_data): """This performs the same decompression tests as in the Python bindings of br...
0.451085
0.525369
from django.http.response import HttpResponse from django.views.generic import TemplateView,ListView,DetailView from rest_framework.views import APIView from rest_framework.response import Response from django.shortcuts import redirect, render from bitcoin.models import Hour,Day,Week,Month,Year from .forms import Cryp...
CryptoPrice/views.py
from django.http.response import HttpResponse from django.views.generic import TemplateView,ListView,DetailView from rest_framework.views import APIView from rest_framework.response import Response from django.shortcuts import redirect, render from bitcoin.models import Hour,Day,Week,Month,Year from .forms import Cryp...
0.385028
0.15428
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.alert import Alert from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.excep...
Update Trash/interpark_v.3.py
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.alert import Alert from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.excep...
0.180251
0.110759
import os import numpy as np import pandas as pd import hashlib import time import shutil from scipy.sparse import coo_matrix import multiprocessing as mp import MNMAPI class DODE(object): def __init__(self, nb, config): self.config = config self.nb = nb self.num_assign_interval = nb.config.config_dict...
src/pylib/DODE.py
import os import numpy as np import pandas as pd import hashlib import time import shutil from scipy.sparse import coo_matrix import multiprocessing as mp import MNMAPI class DODE(object): def __init__(self, nb, config): self.config = config self.nb = nb self.num_assign_interval = nb.config.config_dict...
0.27914
0.282437
from mlapp.handlers.wrappers.wrapper_interface import WrapperInterface class FileStorageWrapper(WrapperInterface): def init(self): """ Initializes the Wrapper for all handlers of `file_storage` type. """ super(FileStorageWrapper, self).init('file_storage') def download_file(se...
mlapp/handlers/wrappers/file_storage_wrapper.py
from mlapp.handlers.wrappers.wrapper_interface import WrapperInterface class FileStorageWrapper(WrapperInterface): def init(self): """ Initializes the Wrapper for all handlers of `file_storage` type. """ super(FileStorageWrapper, self).init('file_storage') def download_file(se...
0.771801
0.109135
import json import importlib import os import urllib2 def get_libs(): """ Get all of the libraries defined in lib/definitions. This is called automatically when the package is imported. """ print(">> Checking for libraries to download..") definitions = os.listdir("lib/definitions") tri...
lib/__init__.py
import json import importlib import os import urllib2 def get_libs(): """ Get all of the libraries defined in lib/definitions. This is called automatically when the package is imported. """ print(">> Checking for libraries to download..") definitions = os.listdir("lib/definitions") tri...
0.196325
0.102619
import os import logging import grpc from athera.sync.sirius.services import service_pb2 from athera.sync.sirius.services import service_pb2_grpc import sys import io ONE_MB = 1024 * 1024 MAX_CHUNK_SIZE = 1 * ONE_MB REGION_URLS = { "us-west1": "us-west1.files.athera.io:443", "europe-west1": "files.athera.io:...
athera/sync/client.py
import os import logging import grpc from athera.sync.sirius.services import service_pb2 from athera.sync.sirius.services import service_pb2_grpc import sys import io ONE_MB = 1024 * 1024 MAX_CHUNK_SIZE = 1 * ONE_MB REGION_URLS = { "us-west1": "us-west1.files.athera.io:443", "europe-west1": "files.athera.io:...
0.491212
0.214383
import collections import os import re import subprocess import time GHOSTLY_PATH = '/usr/bin/ghostly' ALLIE_DBG = '../target/debug/allie' # Old versions ALLIE_1_1 = './bin/allie_v1.1' ALLIE_1_0 = './bin/allie_v1.0' ALLIE_0_9 = './bin/allie_v0.9' ALLIE_0_8 = './bin/allie_v0.8' ALLIE_0_7 = './bin/allie_v0.7' ALLIE_0...
benchmarker/bench.py
import collections import os import re import subprocess import time GHOSTLY_PATH = '/usr/bin/ghostly' ALLIE_DBG = '../target/debug/allie' # Old versions ALLIE_1_1 = './bin/allie_v1.1' ALLIE_1_0 = './bin/allie_v1.0' ALLIE_0_9 = './bin/allie_v0.9' ALLIE_0_8 = './bin/allie_v0.8' ALLIE_0_7 = './bin/allie_v0.7' ALLIE_0...
0.329931
0.044101
from collections import Counter, namedtuple from xldlib.definitions import ZIP from xldlib.general import sequence from xldlib.qt.objects import base from xldlib.utils import logger, modtools # DATA # ---- CHARS = [ 'd', 'u' ] # OBJECTS # ------- @sequence.serializable("XLIdentifier") class XLIdentifier...
xldlib/xlpy/tools/frozen.py
from collections import Counter, namedtuple from xldlib.definitions import ZIP from xldlib.general import sequence from xldlib.qt.objects import base from xldlib.utils import logger, modtools # DATA # ---- CHARS = [ 'd', 'u' ] # OBJECTS # ------- @sequence.serializable("XLIdentifier") class XLIdentifier...
0.765944
0.252568
import unittest from utils.rpg.shadowrun3e.parser import Sr3CharacterParser class TestSr3eCharacterParser(unittest.TestCase): def setUp(self): self.parser = Sr3CharacterParser def test_roll_attribute_parse(self): """ Verifies that the attribute roll parsing works properly """ ...
tests/test_sr3_character_parser.py
import unittest from utils.rpg.shadowrun3e.parser import Sr3CharacterParser class TestSr3eCharacterParser(unittest.TestCase): def setUp(self): self.parser = Sr3CharacterParser def test_roll_attribute_parse(self): """ Verifies that the attribute roll parsing works properly """ ...
0.751375
0.61783
from setuptools import setup, find_packages import glob import sys, os.path ## Ensure that ``./autogen.sh`` is run prior to using ``setup.py`` if "2.0.0".startswith("%%"): import os, subprocess if not os.path.exists('./autogen.sh'): sys.stderr.write( "This source repository was not configu...
setup.py
from setuptools import setup, find_packages import glob import sys, os.path ## Ensure that ``./autogen.sh`` is run prior to using ``setup.py`` if "2.0.0".startswith("%%"): import os, subprocess if not os.path.exists('./autogen.sh'): sys.stderr.write( "This source repository was not configu...
0.338296
0.133105
from .config import * from scipy.optimize import curve_fit def appearance_energy(data, savedir=None): """ This function finds the appearance energy of all amu species present in the data by means of linear fit. Parameters ---------- data: string or Pandas DataFrame This should be a str...
qmspy/appearance_energy.py
from .config import * from scipy.optimize import curve_fit def appearance_energy(data, savedir=None): """ This function finds the appearance energy of all amu species present in the data by means of linear fit. Parameters ---------- data: string or Pandas DataFrame This should be a str...
0.784071
0.618896
"""Get the version string from the git tag.""" from __future__ import print_function import subprocess __all__ = ['get_gitversion'] TEMPLATES = { 'python': """\ \"""Do not edit this file because it will be overwritten before packaging. The output of git describe was: {git_describe} \""" __version__ = '{git_ta...
tools/appveyor/gitversion.py
"""Get the version string from the git tag.""" from __future__ import print_function import subprocess __all__ = ['get_gitversion'] TEMPLATES = { 'python': """\ \"""Do not edit this file because it will be overwritten before packaging. The output of git describe was: {git_describe} \""" __version__ = '{git_ta...
0.761272
0.221372
from __future__ import unicode_literals import django.core.validators import django.db.models.deletion import versions.models from django.conf import settings from django.contrib.auth.hashers import make_password from django.db import migrations, models import pretix.base.i18n import pretix.base.models def initial_...
src/pretix/base/migrations/0001_initial.py
from __future__ import unicode_literals import django.core.validators import django.db.models.deletion import versions.models from django.conf import settings from django.contrib.auth.hashers import make_password from django.db import migrations, models import pretix.base.i18n import pretix.base.models def initial_...
0.498535
0.076753
import grpc from google.ads.google_ads.v3.proto.resources import expanded_landing_page_view_pb2 as google_dot_ads_dot_googleads__v3_dot_proto_dot_resources_dot_expanded__landing__page__view__pb2 from google.ads.google_ads.v3.proto.services import expanded_landing_page_view_service_pb2 as google_dot_ads_dot_googleads__...
google/ads/google_ads/v3/proto/services/expanded_landing_page_view_service_pb2_grpc.py
import grpc from google.ads.google_ads.v3.proto.resources import expanded_landing_page_view_pb2 as google_dot_ads_dot_googleads__v3_dot_proto_dot_resources_dot_expanded__landing__page__view__pb2 from google.ads.google_ads.v3.proto.services import expanded_landing_page_view_service_pb2 as google_dot_ads_dot_googleads__...
0.658747
0.061565
import tensorflow as tf def _append_homog(tensor): rank = len(tensor.shape.as_list()) shape = tf.concat([tf.shape(tensor)[:-1], [1]], axis=0) ones = tf.ones(shape, dtype=tensor.dtype) return tf.concat([tensor, ones], axis=rank - 1) def dense(inputs, weights, batch_norm, is_training, particles=1): ...
misc/layers.py
import tensorflow as tf def _append_homog(tensor): rank = len(tensor.shape.as_list()) shape = tf.concat([tf.shape(tensor)[:-1], [1]], axis=0) ones = tf.ones(shape, dtype=tensor.dtype) return tf.concat([tensor, ones], axis=rank - 1) def dense(inputs, weights, batch_norm, is_training, particles=1): ...
0.626124
0.393909
import base64 import logging import sys logger = logging.getLogger(__name__.split('.')[-1]) import pandas as pd import matplotlib.pyplot as plt import io TRUNCATE_CUTOFF = 40 _HEADER = """ <!DOCTYPE html> <html lang="en"> <head> <title>{title}</title> <link rel="stylesheet" href="https://fonts.go...
amalia/tools/ReportWriter.py
import base64 import logging import sys logger = logging.getLogger(__name__.split('.')[-1]) import pandas as pd import matplotlib.pyplot as plt import io TRUNCATE_CUTOFF = 40 _HEADER = """ <!DOCTYPE html> <html lang="en"> <head> <title>{title}</title> <link rel="stylesheet" href="https://fonts.go...
0.357231
0.070304
import os from pathlib import Path from .logger import CustomisedJSONFormatter # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment...
src/Demo/settings.py
import os from pathlib import Path from .logger import CustomisedJSONFormatter # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment...
0.434581
0.100569
from collections import OrderedDict from copy import deepcopy from simtk import openmm from simtk import unit kB = unit.BOLTZMANN_CONSTANT_kB*unit.AVOGADRO_CONSTANT_NA class InputError(Exception): def __init__(self, msg): super(InputError, self).__init__('\033[1;31m' + msg + '\033[0m') def countDegree...
src/atomsmm/utils.py
from collections import OrderedDict from copy import deepcopy from simtk import openmm from simtk import unit kB = unit.BOLTZMANN_CONSTANT_kB*unit.AVOGADRO_CONSTANT_NA class InputError(Exception): def __init__(self, msg): super(InputError, self).__init__('\033[1;31m' + msg + '\033[0m') def countDegree...
0.874091
0.51379
from datetime import datetime from dataclasses import dataclass from typing import List import string import requests from flask import Blueprint, Response, request, url_for, redirect from flask.views import MethodView from flask_babelplus import gettext as _ from flask_login import current_user, login_required from ...
modules/hub/hub/features/donations/views.py
from datetime import datetime from dataclasses import dataclass from typing import List import string import requests from flask import Blueprint, Response, request, url_for, redirect from flask.views import MethodView from flask_babelplus import gettext as _ from flask_login import current_user, login_required from ...
0.657318
0.132655