text stringlengths 957 885k |
|---|
<gh_stars>0
#!/usr/bin/python3
import sys
sys.path.insert(0, '..') # make '..' first in the lib search path
from collections import Counter, defaultdict
import nltk
import spacy
from MiscUtils import loadNLTKCorpus, ProgressBar
# Create an empty overrides file before importing pyinflect.
# Normally the overrrid... |
import os
import time
import numpy as np
import cupy as cp
class pyMatrix:
'''
Naive Python Implementation of Matrix, initialized with NumPy arrays. Contains basic Matrix Operations for
Performance Evaluations.
Members
------------
- arr : the matrix, initialized by a NumPy Array
- nrows ... |
<reponame>Abdelrahman0W/lisa<gh_stars>0
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from dataclasses import dataclass, field
from pathlib import PurePosixPath
from typing import Any, Dict, List, Type, cast
from azure.mgmt.compute.models import GrantAccessData # type: ignore
from dataclas... |
#!/usr/bin/env python3
import os
import sys
import argparse
import numpy as np
import scipy.optimize
from pyscf import gto,df,dft
import pyscf.data
from functions import *
def energy(x):
exponents = np.exp(x)
newbasis = exp2basis(exponents, myelements, basis)
E = 0.0
for m in moldata:
E += energy_mol(ne... |
<gh_stars>0
"""Base backend for Arduino Uno and its derivatives."""
from typing import Mapping, Optional, Type
from j5.backends import Backend
from j5.backends.console import Console
from j5.components import GPIOPinInterface, GPIOPinMode, LEDInterface
class PinData:
"""Contains data about a pin."""
mode: ... |
<gh_stars>10-100
# THIS SCRIPT IS SUPPOSED TO RUN IN A JUPYTER NOTEBOOK (WE USED VS CODE)
# %%
import pandas as pd
import numpy as np
from sklearn.preprocessing import PowerTransformer
from sklearn.covariance import MinCovDet
from scipy.stats import chi2
import seaborn as sb
import matplotlib.pyplot as plt
# %%
de... |
import sys
from decimal import *
class Convertor:
def convert(self,score,settings):
pass
class MidiConvertor(Convertor):
# does noteOff affect the output at all? test again, because i might need it for cymbals
volumeMap = {
"P": .20,
"MP": .40, # pianissimo
"MF": .60, # mezzo-forte
"F": .80, # forte
"... |
from datetime import datetime
from bs4 import BeautifulSoup
from config import *
'''
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
https://docs.python.org/3/library/random.html
'''
#import pdfkit
# Template of Worksheets (#1, #2) on either side of a section
section_template = '''<div id=section-{} class="co... |
<reponame>ministryofjustice/opg-ansible-roles
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option)... |
<reponame>utkarsh512/Ad-hominem-fallacies
# create a distance matrix between threads
from datetime import datetime
import os
from nltk import TreebankWordTokenizer
import unicodedata
import multiprocessing
import pickle
from multiprocessing import Manager
import math
from RedditThread import RedditThread
from Semanti... |
<filename>files/management/commands/check_files.py
from django.core.management.base import BaseCommand, CommandError
from files.models import File,VCF
import os
from django.conf import settings
import time
from django.core.exceptions import ObjectDoesNotExist
import glob
from django.contrib.auth.models import User
from... |
<gh_stars>1-10
#!/usr/bin/env python3
#
# Short description of the program/script's operation/function.
#
import sys
import argparse
import subprocess
import os
FILENAME = sys.argv[0]
class ArgumentParserUsage(argparse.ArgumentParser):
"""Argparse override to print usage to stderr on argument error."""
def e... |
<filename>src/pipeformer/internal/templates/codepipeline.py<gh_stars>1-10
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at... |
# ----------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License
# ----------------------------------------------------------------------
"""Contains the StringTypeInfo object"""
import os
import textwrap
imp... |
#!/usr/bin/python
# coding=utf8
"""
================================================================================
LingSync-to-OLD Migrator
================================================================================
This is a command-line utility that migrates a LingSync corpus to an Online
Linguistic Databa... |
# coding: utf-8
# # 欢迎来到线性回归项目
#
# 若项目中的题目有困难没完成也没关系,我们鼓励你带着问题提交项目,评审人会给予你诸多帮助。
#
# 所有选做题都可以不做,不影响项目通过。如果你做了,那么项目评审会帮你批改,也会因为选做部分做错而判定为不通过。
#
# 其中非代码题可以提交手写后扫描的 pdf 文件,或使用 Latex 在文档中直接回答。
# ### 目录:
# [1 矩阵运算](#1-矩阵运算)
# [2 Gaussian Jordan 消元法](#2-Gaussian-Jordan-消元法)
# [3 线性回归](#3-线性回归)
# In[40]:
# 任意选一... |
# Published Jan 2013
# Author : <NAME>, <EMAIL>
# Multiple contributors : see https://github.com/philippelt/netatmo-api-python
# License : GPL V3
"""
This API provides access to the Netatmo weather station or/and the Welcome camera
This package can be used with Python2 or Python3 applications and do not
require anythin... |
import datetime
import typing
import unittest.mock
from flask import Flask
from pytest import fixture, mark
from pytest_localserver.http import WSGIServer
from requests.exceptions import ConnectionError, Timeout
from requests_mock import Mocker, mock
from sqlalchemy.orm.scoping import scoped_session
from sqlalchemy.or... |
import sys, os
import unittest
os.environ["TF_NUM_INTEROP_THREADS"] = "8"
os.environ["TF_NUM_INTRAOP_THREADS"] = "8"
os.environ["ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS"] = "8"
import tempfile
import shutil
import tensorflow as tf
import antspymm
import antspyt1w
import antspynet
import ants
import numpy as np
# FIX... |
import torch
import numpy as np
from torch import nn
class Fusion2(nn.Module):
"""
lr = 0.01 tanh 4.80%
lr = 0.005 tanh 4.64%
"""
def __init__(self):
super(Fusion2, self).__init__()
self.elayer = nn.Sequential(nn.Linear(11, 30),
... |
<filename>MULTITASK_FILES/RETINANET_FILES/src/pytorch-retinanet/retinanet/dataloader.py
from __future__ import print_function, division
import sys
import os
import torch
import numpy as np
import random
import csv
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from torch.uti... |
<filename>RESOURCES/search.py
import sys
import copy
import re
import elist.elist as elel
import tlist.tlist as tltl
import estring.estring as eses
import edict.edict as eded
import xdict.CrtableLib.crtable as xcr
from xdict.jprint import pdir
from xdict.jprint import pobj
import navegador5.file_toolset as nvft
#h... |
# 14. sls/remove_list
# Method is GET (but ought to be POST or DELETE)
# I can't tell from the old documentation what this service is supposed to do.
import sys, unittest, json
sys.path.append('./')
sys.path.append('../')
import webapp, lists
service = webapp.get_service(5005, 'sls/remove_list')
http_method = 'POST'... |
import operator
from datetime import date, timedelta
from functools import reduce
from django.contrib.postgres.search import SearchQuery, SearchVector
from django.db.models import Q
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import SearchForm
from .models import Listi... |
import datetime
import json
import os
import sys
import random
import time
from subprocess import call
import uuid
import threading
import requests
import platform
import re
#含有信息打印的延迟
def waitingSeconds(sleepNumber):
print("请等待{}s".format(sleepNumber))
time.sleep(sleepNumber)
#power为0.001时为毫秒级延... |
<reponame>micferr/ADM_HW3
import csv
import os
from datetime import datetime
from typing import Tuple, Optional
import bs4
import re
from bs4 import BeautifulSoup
from pathlib import Path
from constants import ANIMES_DIRECTORY, PARSED_ANIMES_DIRECTORY
from utils import Anime, prepare_to_download, parsed_anime_filenam... |
#my colormap
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import numpy as np
import splat
import pandas as pd
import splat.empirical as spem
import statsmodels.nonparametric.kernel_density as kde
import numba
from astropy.io import ascii
import matplotlib
from astropy import stats as astrostats
f... |
<filename>filters/pandoc_listof.py
#!/usr/bin/env python
"""
Pandoc filter to create lists of all kinds
"""
from pandocfilters import toJSONFilters, walk, Str, Plain, Link, BulletList, Para, RawInline
from functools import reduce
from copy import deepcopy
import io
import sys
import codecs
import json
import re
impor... |
<reponame>igkins/beeswithmachineguns
"""
"""
from collections import namedtuple
import logging
import re
class Tester(object):
"""
Abstract base class for tester implementations.
"""
def get_command(self, num_requests, concurrent_requests, is_keepalive, url):
"""
Generate a command ... |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
<filename>Scripts/uniq_strain_tax_2_jsons.py
#!/usr/bin/python
from __future__ import print_function
import re,sys,os
import json
# Copyright {2019} <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a c... |
import pytest
from postcodes.uk import PostCodeUK
def test_postcodes_uk_uppercase_normalization():
raw_postcode = 'aa9a 9aa'
postcode = PostCodeUK(raw_postcode)
assert postcode.raw_postcode == raw_postcode
assert postcode.full_postcode == 'AA9A 9AA'
def test_postcodes_uk_outward_and_inward_validatio... |
<filename>main.py
import cv2
import time
import argparse
from detectors.cnn_dlib import CNNFaceDetector
from detectors.hog_dlib import HoGFaceDetector
from detectors.haarcascade import FaceDetectorHaar
from detectors.ssd_face_detector import FaceDetector
import line_profiler
import atexit
profile = line_profiler.LineP... |
from scipy.interpolate import interp1d
import numpy as np
def series_interp(data = []):
y = [k for k in data if k >= 0]
x = [i for i in range(len(data)) if data[i] >= 0 ]
if 0 not in x:
y = [0] + y
x = [0] + x
f = interp1d(x,y,kind='quadratic')
return [data[i] if data[i] >= 0 else f... |
<reponame>soleneulmer/FADE
import warnings
import time
import datetime
import pandas as pd
from . import format_dataset as fd
from pprint import pprint
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from scipy.stats import spearmanr, pea... |
<gh_stars>1-10
import sys;
import re;
import os;
import ldap;
import time;
from common import *
#test configuration
source_host = 'gary-sles'
target_host = 'gary-testvm'
source_port = '11711'
target_port = '11711'
source_domain = 'bellevue'
target_domain = 'csp'
source_username = 'administrator'
target_username = '... |
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("Payment"),
"items": [
{
"type": "doctype",
"name": "Wharf Payment Entry",
"onboard": 1,
"description": _("Wharf Payment Entry"),
},
{
"type": "doctype",
"name": "Bulk P... |
import os
import re
import sys
import uuid
import tempfile
import subprocess
import datetime as dt
import traceback
from functools import total_ordering, lru_cache
from pathlib import Path
try:
import numpy as np
except ImportError:
np = None
try:
import matplotlib as mpl
import matplotlib.pyplot as p... |
#!/usr/bin/env python
# author: combofish
# Filename: CoordinateConversion.py
import openpyxl
import os
import datetime
from datetime import date
import time
import configparser
import wx
APP_TITTLE = '坐标转换工具 V1.3'
APP_ICON = 'well.ico' # 请更换成你的icon
Usage = """>>> 软件使用
* 点击 ‘开始转换’ 按钮开始处理文件。
* 默认的数据读取目录在 Da... |
<reponame>yuanqing-wang/sake<gh_stars>1-10
import jax
import jax.numpy as jnp
from jax.experimental.ode import odeint
from flax import linen as nn
from .models import DenseSAKEModel
from functools import partial
import math
from typing import Callable
T = jnp.array((0.0, 1.0))
class CenteredGaussian(object):
@sta... |
import logging
import pathlib
import webbrowser
from typing import List
from sqlalchemy import Column, ForeignKey, Integer, Table, Text, create_engine, desc
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
logger = logging.getLogger(__name__)
Base = declar... |
import random
from math import atan2, pi
import cv2
import numpy as np
from albumentations import VerticalFlip, RandomResizedCrop, Compose, normalize_bbox, denormalize_bbox
from albumentations.augmentations import functional as F
from albumentations.augmentations.crops import functional as crop_f
from albumentations.c... |
import json
import pytest
import time
from delphi.apps.rest_api import create_app, db
from delphi.apps.rest_api.models import DelphiModel, CauseMosAsyncExperimentResult, ExperimentResult
@pytest.fixture(scope="module")
def app():
app = create_app(debug=True)
app.testing = True
app.config["SQLALCHEMY_TRA... |
<gh_stars>1-10
# multiAgents.py
# --------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http:... |
<filename>operators_gen2/utils/dtype_converter/script.py
# For more information about the Python3Operator, drag it to the graph canvas,
# right click on it, and click on "Open Documentation".
# To uncomment the snippets below you can highlight the relevant lines and
# press Ctrl+/ on Windows and Linux or Cmd+/ on Mac.... |
import pandas as pd
from .utils import (
is_series, is_dataframe, is_categorical, is_numeric,
contains_categorical, contains_only_categorical, is_temporal)
def get_applicable_methods(data=None):
"""Informs about the imputation methods that are applicable to a given
data frame or series, based on the ... |
import numpy as np
import os, sys, glob
#from sklearn.externals import joblib
import joblib
"""
Contains The LSQ generation algorithm that returns a list of permutations to build a Latin Square.
Also contains methods to transform these lsqs to a representation that can be used for the
belief propagation a... |
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from django.db import models
from django.utils.html import escape
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from rapidsms.models import ExtensibleModelBase
class Point(models.Model):
"""
This ... |
<gh_stars>1-10
__author__ = 'max'
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..nn import ChainCRF, VarMaskedGRU, VarMaskedRNN, VarMaskedLSTM
from ..nn import Embedding
from ..nn import utils
class BiRecurrentConv(nn.Module):
def __init__(self, word_dim, num_words, char_dim, num_chars... |
""" Protocol Test Helpers """
from contextlib import contextmanager
from typing import Dict, Iterable, Union
import copy
import json
import uuid
from aries_staticagent import StaticConnection, Message, Module, crypto
from voluptuous import Any
from .backchannel import Backchannel
from .provider import Provider
from .s... |
import argparse, pulp
import networkx as nx
import numpy as np
import random
def gen_graph(max_n, min_n, g_type='erdos_renyi', edge=4):
# choose a random number of vertices in the graph between max_n and min_n
cur_n = np.random.randint(max_n - min_n + 1) + min_n
g = None
# create the right correspon... |
<reponame>jianzhangcs/DenoiSeg
import numpy as np
from numba import jit
from scipy import ndimage
from tqdm import tqdm, tqdm_notebook
@jit
def pixel_sharing_bipartite(lab1, lab2):
assert lab1.shape == lab2.shape
psg = np.zeros((lab1.max() + 1, lab2.max() + 1), dtype=np.int)
for i in range(lab1.size):
... |
<filename>compiler/characterizer/measurements.py
# See LICENSE for licensing information.
#
# Copyright (c) 2016-2019 Regents of the University of California and The Board
# of Regents for the Oklahoma Agricultural and Mechanical College
# (acting for and on behalf of Oklahoma State University)
# All rights reserved.
#... |
import argparse
import os
import pathlib
import platform
import re
import shutil
import sys
import tarfile
from functools import cached_property
from typing import List, Optional
from colorama import Fore, Style # type:ignore
from sphinx.cmd.build import main as sphinx_build # type:ignore
from aio.run import runne... |
<gh_stars>0
#!/usr/bin/python
#encoding: utf-8
import sys
import os
from base_generator import *
baseNS = "AtomScript"
def gen_all_expr():
out_dir = "../AtomScript/AST/Expression/"
ns = baseNS + ".AST.Expression"
usingGeneric = "System.Collections.Generic"
# 基类
c = CommonClass(ns, "Expr", "IVis... |
<filename>tests/rnn_gen.py
# coding: utf-8
# In[18]:
from fuel.datasets import Dataset
from librnn.pylearn2.datasets.music import MusicSequence
from blocks.bricks import Sigmoid, Tanh, MLP, Linear, Rectifier
from blocks.bricks.recurrent import SimpleRecurrent, GatedRecurrent, LSTM
from blocks.bricks import recurrent... |
from src.gilded_rose import GildedRose
from src.item import Item
from src.item_types import ItemTypes
import pytest
def test_negative_quality():
gildedrose = GildedRose([Item(name="Other", sell_in=0, quality=0)])
gildedrose.update_quality()
item = gildedrose.items[0]
assert item.quality == 0
gil... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
Documentation Test
"""
import logging
import json
import os
import csv
import requests
from typing import Union
from mapswipe_workers.utils import error_handling
from mapswipe_workers.utils import slack
from mapswipe_workers.definitions import DATA_PATH
from mapswi... |
<filename>tests/python_to_cpp/other/1.n5110_BMP_converter.py
# [https://github.com/weewStack/Python-projects/blob/master/000-BMP-Converter/n5110_BMP_converter.py <- https://github.com/weewStack/Python-projects <- https://youtu.be/0Kwqdkhgbfw <- https://stackoverflow.com/questions/10439104/reading-bmp-files-in-python <-... |
<filename>metashare/accounts/forms.py
from django import forms
from metashare.accounts.models import UserProfile, EditorGroupApplication, \
OrganizationApplication, Organization, OrganizationManagers, EditorGroup, \
EditorGroupManagers
from django.conf import settings
from django.contrib.admin import widgets
fr... |
<gh_stars>10-100
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2016-2021 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ... |
<filename>Lib/site-packages/hackedit/app/index/db.py
"""
Low level api for managing the file/symbols index.
"""
import logging
import os
import sqlite3
import sys
import re
from hackedit.api import system
#: Version of the database (will be appended to the db filename)
DB_VERSION = '0.1'
#: File name of the databa... |
""" Production environment setup:
- setup static files
- setup template files """
import os
import sys
import importlib.util
import shutil
import pathlib
import subprocess
import boto3
import gzip
import hashlib
import time
def load_module(name, path):
spec = importlib.util.spec_from_file_location(name, path)... |
<gh_stars>1-10
"""
The controllers module provides different controller classes,
applicable to different simulations.
A controller object's job is to control simulations-
At a high level a controller objects accepts a list of
parameters and chromosomes and (usually) returns
corresponding simulation data.
This is impl... |
# <NAME>
# CPSC 386 FALL 2016
# Project 5 (Final Project)
# <EMAIL>
# Armada.py is a top-down space shooter game made using Python 3.4 and Pygame 1.9.
import sys, random, time, pygame
from pygame.locals import *
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0 )
RED = (255, 0, 0 )
GREEN = (0, 255, 0 ... |
# Script for generating .xml files containing information about government coalitions. Based on Wikipedia data and far from complete. Needs manual checking after running!!
import re, string,os
from glob import glob as gb
import pandas as pd
from tqdm import tqdm
from collections import Counter
import datetime as dt
im... |
<reponame>jaimecruz21/lifeloopweb<filename>lifeloopweb/decorators.py<gh_stars>0
from functools import wraps
import flask
from lifeloopweb import logging
from lifeloopweb.db import models
LOG = logging.get_logger(__name__)
def can_search_users(current_user):
def decorator(f):
@wraps(f)
def decora... |
from qaoa.util.finite_difference import check_derivative
import numpy
def check_gradient(obj,theta,dtheta,h,order=1):
"""
Evaluate the discrepency of a circuit objective's first
directional derivative using finite differences
Using an m-point finite difference approximation with offsets d1,..,dm
a... |
from uuid import uuid4
from flask_cors import CORS
import requests
from flask import Flask, jsonify, request
import json
import datetime
from blockchain import Blockchain
# Instantiate the Node
app = Flask(__name__)
CORS(app)
# Generate a globally unique address for this node
node_identifier = str(uuid4()).replace('-... |
# uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: direct.controls.GravityWalker
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.showbase import DirectObject
f... |
<reponame>alpv95/MemeProject
import os
import numpy as np
from PIL import Image
import tensorflow as tf
from alexnet import AlexNet
from random import shuffle
#mean of imagenet dataset in BGR
imagenet_mean = np.array([104., 117., 124.], dtype=np.float32)
current_dir = os.getcwd()
image_dir = os.path.join(current_di... |
import os
import json
import joblib
import matplotlib.pyplot as plt
import numpy as np
import gym
import torch
from .data_structures.Config import Config
from environments import CPS_env
from environments.Open_AI_Wrappers import TimeLimit
def init_config(args):
config = Config()
config.seed = args.see... |
#!/usr/bin/env python3
"""Unit tests for spawneditor."""
import itertools
import os
import pathlib
import tempfile
import typing
import unittest
import unittest.mock
import spawneditor
class FakePosixPath(pathlib.PurePosixPath):
"""
Fake version of `pathlib.PosixPath` that can run on non-POSIX systems.
... |
#! /use/bin/env python
import numpy as np
import tables as tb
from enthought.mayavi import mlab
pippo = tb.openFile('prova.h5', 'r')
maxes = pippo.root.tree._v_attrs.maxes
mins = pippo.root.tree._v_attrs.mins
x_M = maxes[0]
y_M = maxes[1]
z_M = maxes[2]
x_m = mins[0]
y_m = mins[1]
z_m = mins[2]
floor_x = np.array([... |
<reponame>joelnb/duckyPad<filename>resources/color_tests/randomcolour.py
import os
import random
import colorsys
# for x in range(1,13):
# os.system("echo F" + str(x) + ' > key' + str(x) + '_F' + str(x) + '.txt')
# for x in range(1,13):
# os.system('touch key' + str(x) + '_test' + str(x) + '.txt')
# for x in range(... |
from datalab_cohorts import (
StudyDefinition,
patients,
codelist_from_csv,
codelist,
filter_codes_by_category,
)
## CODE LISTS
# All codelist are held within the codelist/ folder.
covid_codelist = codelist(["U071", "U072"], system="icd10")
aplastic_codes = codelist_from_csv(
"codelists/open... |
<reponame>SergeyRom-23/MB-Lab-master-RU
# MB-Lab
#
# Сайт ветки MB-Lab: https://github.com/animate1978/MB-Lab
# Сайт ветки перевода на русский язык MB-Lab: https://github.com/SergeyRom-23/MB-Lab-master-RU
#
# ##### НАЧАЛО ЛИЦЕНЗИОННОГО БЛОКА GPL #####
#
# Эта программа является свободным программным обеспечением... |
from __future__ import annotations
from abc import abstractproperty, ABCMeta
from datetime import datetime, timedelta
from json import JSONDecodeError
import os
import typing as t
import warnings
from piccolo.apps.user.tables import BaseUser
from starlette.exceptions import HTTPException
from starlette.endpoints impor... |
#!/usr/bin/env python3
import argparse
import copy
import sys
import os
import hglib
import git
import logging
import importlib.machinery
import types
import re
from multiprocessing import Pool
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.DEBUG)
format = '[%(asctime)s.%(msecs)03d] [%(name)s] [%(levelname)s] ' ... |
<filename>zstacklib/zstacklib/utils/jsonobject.py
'''
@author: frank
'''
import simplejson
import json
import types
import inspect
class NoneSupportedTypeError(Exception):
'''not supported type error'''
class JsonObject(object):
def __init__(self):
pass
def put(self, name, val):
set... |
<gh_stars>10-100
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2018-04-05 23:20
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
... |
<reponame>hmedal/speu2<filename>src/objects/experiments.py
'''
Created on Jul 11, 2016
@author: hmedal
'''
import os
import xml.etree.cElementTree as ET
import unittest
import json
from src.objects import computationalresource, outputtable
def convertHoursToTimeString(hours):
seconds = hours * 3600
m, s = d... |
<reponame>Snewmy/swordie
# Staff <NAME> (2010000) | Orbis Park (200000200)
from net.swordie.ms.enums import InvType
import random
exchangeList = [4000073, 4000070, 4000071, 4000072, 4000059, 4000060, 4000061, 4000058, 4000062,
4000081, 4000048, 4000055, 4000050, 4000057, 4000051, 4000052,
4000049, 4000056, 4000053, 4... |
<reponame>h-tab/nighthawk
"""@package integration_test_fixtures
Base classes for Nighthawk integration tests
"""
import json
import logging
import os
import requests
import socket
import subprocess
import sys
import threading
import time
import pytest
from test.integration.common import IpVersion, NighthawkException
... |
<filename>workflow/workflow.py
from os import path
import time
import logging
import argparse
from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession
from pyspark.ml import Pipeline
from pyspark.ml.feature import RegexTokenizer, Word2Vec
from transformers import StringConcatenator
def main(arg... |
<reponame>apuc/django-rest-framework<filename>userapi/settings.py<gh_stars>0
from datetime import timedelta
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for prod... |
<filename>src/cipolla/game/room/room_map_mode_state.py
from twisted.internet import defer # type: ignore
from twisted.internet.defer import Deferred # type: ignore
from cube2common.constants import INTERMISSIONLEN # type: ignore
from cipolla.game.client.exceptions import GenericError
from cipolla.game.map.map_rotatio... |
<filename>citysimtoenergyplus.py<gh_stars>1-10
'''
citysimtoenergyplus.py
Extract an EnergyPlus model (IDF) from a CitySim scene.
A template for the HVAC is provided, so this module is just
concerned with geometry, materials and construction.
'''
import numpy as np
from . import polygons
reload(polygons)
def extract... |
"""
Utilities to manage different data input files.
"""
import logging
from collections import namedtuple
from xml.etree.ElementTree import ElementTree
from tqdm import tqdm
from .schema import MentionInstance
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
class Provenance(namedtuple("Provenanc... |
<filename>scripts/crawling.py
# Authors: <NAME> <<EMAIL>>
import argparse
import sys
import logging
import os
from geol.utils import utils
from geol.geometry.squaregrid import SquareGrid
from geol.crawler import foursquare_crawler
os.environ['NO_PROXY'] = "nominatim.openstreetmap.org"
logger = logging.getLogger(__na... |
"""
Misc utility functions and constants
"""
import functools
import inspect
import os
import warnings
from textwrap import dedent
import six
from hvac import exceptions
def raise_for_error(status_code, message=None, errors=None):
"""Helper method to raise exceptions based on the status code of a response rece... |
<gh_stars>0
# pylint: disable=wildcard-import
# pylint: disable=unused-wildcard-import
import os
import random
import hashlib
import itertools
import pylev
import pytest
from sbk.mnemonic import *
def _print_words(wl):
for i, word in enumerate(sorted(wl)):
print(f"{word:<9} ", end=" ")
if (i + ... |
#!/usr/bin/env python
from genericpath import exists
import numpy as np
import glob
from distort_calibration import *
from cartesian import *
from registration_3d import *
from optical_tracking import *
from em_tracking import *
from eval import *
from pathlib import Path
import argparse
import csv
from improved_em_tr... |
import numpy as np
import math
import tempfile
import numba as nb
import pickle, gzip
import os
''' Important functions which can be used throughout the package '''
def num2vect(num,node_num):
'''Converts a binary number into Vector.'''
string = format(num, 'b').zfill(node_num)
arr = np.fromiter(string, ... |
<reponame>TheCoder777/Python-Report-Booklet-Writer
# system modules
import datetime
import time
# internal modules
from ..defines import configs
def __current_year():
return int(time.strftime("%Y"))
def __calc_start(week: int, year: int) -> str:
"""
Calculates the start date using an iso calender
... |
<filename>openstackclient/identity/v3/user.py
# Copyright 2012-2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICE... |
<gh_stars>1-10
from time import sleep
from threading import Thread
import requests
import sys
import select
import telepot
def get_api_key() -> str:
api_key = ""
with open("api_key.txt", 'r') as file:
api_key = file.readline()
return api_key
def get_id() -> int:
id = ""
... |
<filename>tests/integration/cattletest/core/test_svc_volume_template.py
from common_fixtures import * # NOQA
from cattle import ApiError
import yaml
def test_create_volume_template(client):
opts = {'foo': 'true', 'bar': 'true'}
stack = client.create_stack(name=random_str())
stack = client.wait_success(st... |
import logging
from abc import ABC
from autoconf import conf
from autofit.mapper.prior_model.abstract import AbstractPriorModel
from autofit.mapper.prior_model.collection import CollectionPriorModel
from autofit.non_linear.analysis.multiprocessing import AnalysisPool
from autofit.non_linear.paths.abstract import Abstr... |
<reponame>bodastage/bts-ce-api
from flask import Blueprint, request, render_template, \
flash, g, session, redirect, url_for, \
jsonify, make_response, send_file
from btsapi.modules.reports.models import Report, ReportCategory, ReportCategoryMASchema, DummyTable, ReportsTaskLog, Repo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.