text string | size int64 | token_count int64 |
|---|---|---|
#! -*- coding: utf-8 -*-
# Keras implement of Glow
# Glow模型的Keras版
# https://blog.openai.com/glow/
from keras.layers import *
from keras.models import Model
from keras.datasets import cifar10
from keras.callbacks import Callback
from keras.optimizers import Adam
from flow_layers import *
import imageio
import numpy as... | 6,356 | 2,527 |
"""Module to take an existing r_map and replace all instances of ArrayedNode
with its children. Also fix addresses of AddressedNodes to save the tree lookup
penalty imposed within their address properties. This involves manipulating the
tree in memory and providing an overridden AddressedNode which can be used when
des... | 1,985 | 529 |
#Palindrome check for string s
s = ['d','o','g','G','o','d'] #need to define a string
s = [element.lower() for element in s] #convert each element to lowercase
def isPal(s):
print(' isPal called with', s ) #printing the string
if len(s) <= 1: #zero or one letter case
print('Base case is always true... | 488 | 174 |
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
#
# Pytorchで用いるDatasetの定義
#
from numpy.lib.arraypad import pad
import tensorflow as tf
# 数値演算用モジュール(numpy)をインポート
import numpy as np
# sysモジュールをインポート
import sys
import math
def build_dataset(feat_scp,
label_scp,
feat_mean,
... | 4,653 | 2,433 |
from __future__ import print_function, unicode_literals
from cba import components
from cba.base import CBAView
class TableRoot(components.Group):
def init_components(self):
self.initial_components = [
components.Group(
css_class="ui form container",
initial_co... | 2,901 | 628 |
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'pushes', views.PushViewSet)
| 137 | 42 |
import yaml
from aztk.error import AztkError, InvalidModelError
class ConfigurationBase:
"""
Base class for any configuration.
Include methods to help with validation
"""
@classmethod
def from_dict(cls, args: dict):
"""
Create a new model from a dict values
The dict is... | 1,410 | 407 |
#!/usr/bin/python3
#this is a comment .!/usr/bin/env python3
import feedparser
import pandas as pd
import time
import numpy as np
import sys
import logging
import csv
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
#from subprocess import check_output
#import sys
with... | 3,836 | 1,476 |
from .test_visualizer import *
| 31 | 10 |
#################################################
### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ###
#################################################
# file to edit: ./nb/timer.ipynb
import sys
if __name__ == '__main__': sys.path.append('..')
import xs_lib.common as common
import sure
from datetime import datetime
im... | 1,640 | 610 |
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import viewsets, mixins, status
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from core.models import Restaurant
from restaurants import ... | 809 | 214 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
import torch
from torch import nn, autograd
from torch.utils.data import DataLoader, Dataset
import numpy as np
import random
from sklearn import metrics
class DatasetSplit(Dataset):
def __init__(self, dataset, idxs):
self.dataset = data... | 2,269 | 691 |
from django.contrib import admin
from .models import Hashtag
admin.site.register(Hashtag)
| 92 | 29 |
import argparse
import gym
import ptan
import random
import torch
import torch.optim as optim
from ignite.engine import Engine
from lib import dqn_model, epsilon_tracker, hyper_params, utils
if __name__ == "__main__":
random.seed(hyper_params.SEED)
torch.manual_seed(hyper_params.SEED)
params = hyper_pa... | 1,996 | 688 |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Author(models.Model):
author= models.ForeignKey(User,on_delete=models.CASCADE, null=True, blank=True)
profile_pic = models.ImageField(upload_to='profile_pic',null=Tr... | 995 | 320 |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# Os dados utilizados referem-se à granulometria (tamanho de partícula) de um testemunho marinho;
# Valores negativos em y indicam a profundidade da coluna estratigráfica em metros, sendo y = 0 o topo do testemunho (início do assoalho oceânico);
# ... | 1,487 | 558 |
import pathlib
from setuptools import setup
#from distutils.core import setup
setup(
name = 'pandas_ui',
packages = ['pandas_ui'],
version = '0.1',
license='MIT License',
description = ' pandas_ui helps you wrangle & explore your data and create custom visualizations without digging through StackOver... | 1,221 | 383 |
class Board(object):
def __init__(self, lines):
assert(len(lines) == 5)
self.data = []
for line in lines:
self.data += [int(x) for x in line.split()]
assert(len(self.data) == 25)
self.drawn = [False for _ in self.data]
def score(self, drawn):
return sum([0 if self.drawn[idx] else self... | 1,644 | 626 |
import unittest.mock
import unittest
import os
import pathlib
from ons_csv_to_ctb_json_load import Loader
from helper_funcs import conditional_mock_open, build_test_file
HEADERS = ['Id', 'Database_Mnemonic', 'Variable_Mnemonic', 'Version', 'Lowest_Geog_Variable_Flag']
REQUIRED_FIELDS = {'Variable_Mnemonic': 'VAR1',
... | 2,944 | 990 |
#!/usr/bin/python
"""Sends a message that is read by the StillCaptureModule."""
import roslib; roslib.load_manifest('reefbot')
import rospy
from reefbot_msgs.msg import ImageCaptured
if __name__ == "__main__":
rospy.init_node('TestStillCaptureModule')
publisher = rospy.Publisher(
rospy.get_param('still_image... | 705 | 276 |
############################################################################
# Python Tkinter All List III Save and Open ToDo Lists
# Python Tkinter All List III Guardar y abrir listas de tareas pendientes
############################################################################
from tkinter import *
from tkinter.f... | 4,924 | 1,666 |
"""Coordinator for SleepIQ."""
from datetime import timedelta
import logging
from asyncsleepiq import AsyncSleepIQ
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
_LOGGER = logging.getLogger(__name__)
UPDATE_INTERVAL = timedelta(seconds=60)
c... | 848 | 260 |
from setuptools import setup, find_packages
with open("requirements.txt") as requirements:
setup(
name="supervisor-remote-logging",
version="0.0.3",
description="Stream supervisord logs various remote endpoints",
author="New Relic Site Engineering Team",
url="https://github.... | 815 | 224 |
from .association_rule import association_rule
from .association_rule import association_rule_visualization
from .als import als_train
from .als import als_predict
from .als import als_recommend
from .collaborative_filtering import collaborative_filtering_train
from .collaborative_filtering import collaborative_filteri... | 401 | 104 |
__author__ = 'avraham'
from xmlrpclib import ServerProxy
port = 9876
class Client(ServerProxy):
def __init__(self, ip='127.0.0.1'):
ServerProxy.__init__(self, ('http://{}:{}'.format(ip, port)))
def get_methods(self):
return [x for x in self.system.listMethods() if not x.startswith('sys')... | 322 | 114 |
#!/usr/bin/env python
__author__ = "Bolinooo"
def main():
L1 = [i for i in range(1, 10)]
L2 = [i * 2 for i in range(1, 10)]
print("Step 1: Import the correct algorithm")
print("Step 2: Try out the correct algorithm using the above lists or your own")
if __name__ == "__main__":
main()
| 311 | 118 |
# DROP TABLES
songplay_table_drop = "DROP TABLE IF EXISTS songplays;"
user_table_drop = "DROP TABLE IF EXISTS users;"
song_table_drop = "DROP TABLE IF EXISTS songs;"
artist_table_drop = "DROP TABLE IF EXISTS artists;"
time_table_drop = "DROP TABLE IF EXISTS \"time\";"
# CREATE TABLES
songplay_table_create = ("""
CRE... | 3,293 | 1,144 |
from pymongo import MongoClient
#change url
mongo_url = 'mongodb://127.0.0.1:27017/'
client = MongoClient()
db = client['obsco']
db.relations.insert_many([
{
'voter':12345671,
'voted':12345672,
'votes':[1,1,1,1,1,0,0,1,1]
},
{
'voter':12345671,
'voted':12345673,
... | 9,048 | 5,226 |
"""
Advent Of Code 2021
Day 9
Date: 09-12-2021
Site: https://adventofcode.com/2021/day/9
Author: Tayyrov
"""
def isValid(r, c):
return 0 <= c < cols and 0 <= r < rows
input_file = open('../input_files/day9_input', 'r')
matrix = input_file.readlines()
rows = len(matrix)
cols = len(matrix[0].s... | 822 | 334 |
import time
from tqdm import tqdm
import torch
import torch.nn.functional as F
from evkit.utils.losses import weighted_l1_loss, weighted_l2_loss, softmax_cross_entropy, dense_cross_entropy
from tlkit.models.lifelong_framework import LifelongSidetuneNetwork
from tlkit.data.datasets.taskonomy_dataset import get_lifelon... | 6,532 | 2,402 |
import spacy
nlp = spacy.blank("de")
# Importiere die Klasse Doc
from ____ import ____
# Erwarteter Text: "Na, alles klar?"
words = ["Na", ",", "alles", "klar", "?"]
spaces = [____, ____, ____, ____, ____]
# Erstelle ein Doc mit den Wörtern und Leerzeichen
doc = ____(____, ____=____, ____=____)
print(doc.text)
| 316 | 126 |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 10 11:00:53 2020
@author: Gabriel
"""
import chess
import chess.svg
import random
#Fonction qui demander un mouvement dans la console et le retourn sous la forme d'un chess move
def recup_move():
case_dep = input("Case départ :")
case_arr = input("Case arrivée ... | 2,602 | 850 |
__version__ = '0.5.15'
__author__ = 'C.W.'
| 43 | 24 |
import unittest
from coinplus_solo_redeem.common import wif_export_bitcoin, compute_public_key_sec256k1, address_from_publickey_bitcoin
class TestBitcoin(unittest.TestCase):
"""test of the bitcoin conversion from private key to wif"""
def setUp(self):
self.test_vector = [("28cb1bccdc33f93c94b73360cef14... | 3,748 | 2,269 |
import asyncio
@asyncio.coroutine
def main():
print('Hello from main')
yield from asyncio.sleep(1)
loop = asyncio.new_event_loop()
loop.run_until_complete(main())
loop.close()
#################################################################
import asyncio
async def main():
print('Hello from main')
... | 1,250 | 393 |
from django.apps import AppConfig
class Class2Config(AppConfig):
name = 'tutorials.class_2'
| 98 | 32 |
#!/usr/bin/env python3
from typing import (
Tuple,
)
from .character import Character
from .gen.player_class import PlayerClass
from .gen.player_stats import STATS_BY_PLAYER_CLASS
from .gen.equipment import GearType
from .stats import Stats
class Player(Character):
def __init__(
self,
userna... | 953 | 295 |
"""
m2wsgi.io.gevent: gevent-based I/O module for m2wsgi
=====================================================
This module provides subclasses of m2wsgi.WSGIHandler and related classes
that are specifically tuned for running under gevent. You can import
and use the classes directory from here, or you can select th... | 8,361 | 2,575 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# for use with Python 3
# text_buffer
#
# This program 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 2 of the License, or
# (at ... | 8,584 | 3,343 |
"""
This Lambda parses the output of ModelQualityStep to extract the value of a specific metric
"""
import json
import boto3
sm_client = boto3.client("sagemaker")
s3 = boto3.resource('s3')
def lambda_handler(event, context):
# model quality report URI
model_quality_report_uri = event['model_quality_report_u... | 886 | 313 |
from data_manager import DataManager, plot_fehpass_mention, plot_score_distribution
from scraper import Scraper
from datetime import date as dt
from cloud import Cloud
import sys
import json
def load_config():
with open("./ressources/config.json") as f:
config = json.load(f)
return config
def save_last_import()... | 2,383 | 864 |
#!/usr/bin/env python
"""
Edited from navigation.py in turtlebot2i_navigation module
"""
import rospy
import actionlib
from nav_msgs.msg import Odometry
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
import geometry_msgs.msg
from sensor_msgs.msg import LaserScan
from tf.transformations import quatern... | 4,679 | 1,644 |
# Stepper Motor Shield/Wing Driver
# Based on Adafruit Motorshield library:
# https://github.com/adafruit/Adafruit_Motor_Shield_V2_Library
# Author: Tony DiCola
import pca9685
# Constants that specify the direction and style of steps.
FORWARD = const(1)
BACKWARD = const(2)
SINGLE = const(1)
DOUBLE = const(2)
INTERLEA... | 6,320 | 2,361 |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from openapi_server.models.base_model_ import Model
from openapi_server import util
class OperationFilterKgraphTopNParameters(Model):
"""NOTE: This class is auto ... | 7,333 | 2,222 |
# Magic utility that "redirects" to pythoncomxx.dll
import pywintypes
pywintypes.__import_pywin32_system_module__("pythoncom", globals())
| 138 | 46 |
__all__ = [
"Metric",
"Metrics",
"MetricCreateRequest",
"MetricUpdateRequest",
"Result",
"Results",
"ResultCreateRequest",
"ResultUpdateRequest",
"EvaluationTable",
"EvaluationTables",
"EvaluationTableCreateRequest",
"EvaluationTableUpdateRequest",
"ResultSyncRequest"... | 1,119 | 334 |
#!/usr/bin/env python
#
# test_importall.py -
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#
import pkgutil
import importlib
import fsl
def test_importall():
def recurse(module):
path = module.__path__
name = module.__name__
submods = list(pkgutil.iter_modules(path, '{}.... | 530 | 190 |
# -*- coding: utf-8 -*-
#
# propagation module
#
import datetime
import os
from random import random
import re
import sys
import weakref
import traceback
import xml.sax.saxutils as saxutils
import dateutil.parser as date_parser
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.orm.session import o... | 14,285 | 4,423 |
from imdbTask1 import*
from imdbTask4 import*
def get_movie_list_details(api):
movieListDetails=[]
for i in api[:10]:
link=i["movieLink"]
movieUrl=Scrap_Movie_Detail(link)
new=movieUrl.copy() #They copy() method returns a shallow copy of the dictionary.
movieUrl.clear() #... | 517 | 155 |
from tkinter import *
class Animation(object):
DELAY = 20
# Override these methods when creating your own animation
def mousePressed(self, event): pass
def keyPressed(self, event): pass
def keyReleased(self,event):pass
def leftMouseReleased(self,event):pass
def mouseMotion(self,event):pass... | 2,084 | 600 |
import tqdm
import copy
import torch
import numpy as np
import cv2
from models import Baseline, loadWeights, BaselineSepDyBN
from datasets import WFLW256, datasetSize, kptNum
import time
from ptflops import get_model_complexity_info
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
def testWFLW256Baseline(mode, test... | 3,726 | 1,430 |
from collections import defaultdict
from itertools import product
from functools import lru_cache
from sys import setrecursionlimit
setrecursionlimit(10000)
@lru_cache(maxsize=6)
def p_outcomes(a_dice, d_dice):
total = 0
results = defaultdict(int)
for a_rolls in product(range(1,7), repeat=a_dice):
... | 1,365 | 509 |
#!/usr/bin/env python
"""
Puzzle Title: AoC 2021 Day 6: Lanternfish
Puzzle Link: https://adventofcode.com/2021/day/6
Solution Author: Luke Spademan <info@lukespademan.com>
Solution License: MIT
"""
import fileinput
from collections import Counter
import copy
def parse_input():
for line in fileinput.in... | 1,240 | 443 |
#!/usr/local/bin/python3
import math
class Particle():
def __init__(self, position, velocity, acceleration):
self.position = position
self.velocity = velocity
self.acceleration = acceleration
self.absA = self.__absoluteAccelleration()
def __absoluteAccelleration(self):
... | 2,082 | 678 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pcap
import sys
import socket
import struct
class BasicPacketInfo:
def __init__(
self,
src,
dst,
srcPort,
dstPort,
protocol,
timestamp,
generator,
):
# Info to generate flows from packer... | 5,591 | 1,766 |
#!python3
#!/usr/local/bin
# encoding: utf-8
import os
from re import *
import sys
from getopt import getopt
import pandas as pd
os.system("date")
#os.system("poetry -i misc2.txt -o result.json")
# pegar no ficheiro do poema
# retirar metadados e crirar .txt temporario só com poema
# usar coisa2 neste ficheiro, ret... | 1,414 | 597 |
import cv2
import numpy as np
import imutils
from matplotlib import pyplot as plt
img = cv2.imread('img1.png',0)
# color = ('b','g','r')
# for i,col in enumerate(color):
# histr = cv2.calcHist([img],[i],None,[256],[0,256])
# plt.plot(histr,color = col)
# plt.xlim([0,256])
# plt.show()
h... | 614 | 290 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 17 09:39:23 2020
@author: u0101486
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 5 12:26:49 2019
@author: u0101486
"""
# Aggregate QC measures
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
... | 25,083 | 10,296 |
import json
import os
import torch
from .distributed_backend import DistributedBackend
class DeepSpeedBackend(DistributedBackend):
"""Distributed backend using the DeepSpeed engine."""
BACKEND_MODULE_NAME = 'deepspeed'
BACKEND_NAME = 'DeepSpeed'
def wrap_arg_parser(self, parser):
if not se... | 5,987 | 1,618 |
from __future__ import annotations
from typing import Any
from .publisher import Publisher
class Just(Publisher):
def __init__(self, value: Any) -> None:
super().__init__()
self.value: Any = value
def dispatch(self) -> Any:
self.upstream(self.value)
def send(self, value: Any) ->... | 361 | 110 |
# Generated by Django 4.0 on 2021-12-24 04:20
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('student', '0002_student_clg_reg_no'),
]
operations = [
migrations.RemoveField(
model_name='student',
name='username',
... | 329 | 114 |
from ..protocol import Protocol
from .logs_protocol import LogsProtocol
class UserLogsProtocol(Protocol):
def __init__(self):
self.name = "UserLogsProtocol"
self.logs_protocol = LogsProtocol()
self.functions = {
"upload_log": self.logs_protocol.upload_log,
"delete_l... | 418 | 120 |
"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... | 9,514 | 3,604 |
#!/usr/bin/python3
""" Search API
"""
import requests
import sys
if __name__ == '__main__':
data = {'q': ''}
try:
data['q'] = sys.argv[1]
except:
pass
data = requests.post('http://0.0.0.0:5000/search_user', data)
try:
q_to_json = data.json()
if not q_to_json:
... | 484 | 178 |
import logging
from discovery.__version__ import __version__
log = logging.getLogger("discovery-client")
log.addHandler(logging.NullHandler())
| 145 | 41 |
def jHex(word):
jap = list(word)
List = []
for i in jap:
if i == " ":
List.append("9940")
elif i == ",":
List.append("9941")
elif i == ".":
List.append("9942")
elif i == "・":
List.append("9943")
elif i == ":":
... | 114,149 | 41,488 |
"""structure_tests
This module contains tests for the DGLM structures
"""
# pylint: disable=no-self-use
import unittest
from nose.tools import assert_equals, assert_almost_equal # type: ignore
from nose.tools.nontrivial import raises # type: ignore
import numpy as np
from pssm.dglm import NormalDLM
from pssm.structu... | 6,548 | 2,323 |
import flask
import numpy as np
buff = []
app = flask.Flask(__name__)
@app.route("/",methods=['POST'])
def index():
global buff
datas = flask.request.get_json(force=True)
buff.extend(datas["data"])
return "",200
@app.route("/save/",methods=['GET'])
def save():
np.save("record.npy", buff)
retu... | 356 | 138 |
# https://www.cefconnect.com/closed-end-funds-screener
# https://www.cefa.com/
# http://cefdata.com/funds/clm/
# https://www.cefconnect.com/fund/CLM
# https://www.cefchannel.com/clm/
from framework.utils import *
from framework.base import *
from framework.meta_data import *
from framework.stats_basic import *
from ... | 13,207 | 6,314 |
"""
Functions defined on vector valued fields
"""
import xarray as xr
import xgcm
from .ecco_utils import get_llc_grid
def UEVNfromUXVY(xfld,yfld,coords,grid=None):
"""Compute east, north facing vector field components from x, y components
by interpolating to cell centers and rotating by grid cell angle
... | 2,616 | 860 |
# -*- coding: UTF-8 -*-
import os
import logging
from logging.config import fileConfig
from util import DatabaseUtil as dbu
from util import ExportUtil as eu
fileConfig("logging_config.ini")
logger = logging.getLogger(__name__)
class StockExporter():
def __init__(self, export_dir, stock_code, start_date, end_da... | 2,409 | 776 |
from helpers import *
import copy
import pygame
import random
# Render vars
inst_x = 32
inst_width = 128
arrow_width = inst_x / 2
font_size = 10
font = pygame.font.SysFont('ubuntu', size = font_size)
large_font_size = 20
large_font = pygame.font.SysFont('ubuntu', size = large_font_size)
# Basic Avidian class. Handles... | 34,758 | 11,871 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Filters for the datasets. Natively implemented are the Kalman filter and
a single-pole low-pass filter.
There is also a base filter class created for subclassing to allow the
creation of custom filters.
"""
from . import kalman
from . import lowpass
__author__ = "Toby ... | 366 | 116 |
from abc import ABCMeta, abstractmethod
class AbstractTransformation:
__metaclass__ = ABCMeta
@abstractmethod
def transform_image(self, image): pass
@abstractmethod
def transform_position(self, x, y, width, height): pass
@abstractmethod
def generate_random(self): pass
| 302 | 86 |
#!/bin/env/python3
from types import ModuleType
from lc.models import torch as model_def
from utils import AverageMeter, Recorder, format_time, data_loader, compute_acc_loss
import argparse
import torch
from torch import optim
import torch.backends.cudnn as cudnn
import torch.nn as nn
import time
import os
if __name__... | 6,262 | 2,018 |
# ---------------------------------------------------------------------
# Copyright (C) 2007-2015 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
from noc.core.script.base import BaseScript
from noc.sa.interfaces.isyncvlans import ISyncVlans
class Sc... | 1,249 | 431 |
from types import new_class
from AoCUtils import *
result = 0
partNumber = "2"
writeToLog = True
if writeToLog:
logFile = open("log" + partNumber + ".txt", "w")
else:
logFile = "stdout"
printLog = printLogFactory(logFile)
start1 = 8
start2 = 9
# Example
# start1 = 4
# start2 = 8
score1 = 0
score2 = 0
di... | 1,875 | 719 |
# -*- coding: utf-8 -*-
"""
This module holds functions for displaying different kinds of menus.
All menus are reaction based.
"""
import asyncio
from copy import copy
from inspect import isawaitable
from typing import List, Optional, Union, Callable
import discord
from discord import Embed
from discord.ext import c... | 20,510 | 5,714 |
from __future__ import unicode_literals
import re
import importlib
from django.utils.translation import ugettext_lazy as _
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.functional import cached_property
from model_utils import Choices
from collections im... | 9,706 | 2,784 |
from .test_case_05 import TestCase05 | 36 | 14 |
import json
import os
import unittest
from pywink.api import get_devices_from_response_dict
from pywink.devices import types as device_types
class PowerstripTests(unittest.TestCase):
def test_state_powerstrip_state_should_be_true_if_one_outlet_is_true(self):
with open('{}/api_responses/pivot_power_geniu... | 2,686 | 881 |
'''
Created on Dec 4, 2012
@author: <a href="mailto:christian.grefe@cern.ch">Christian Grefe</a>
'''
import os
from pyLCIO.io.Reader import Reader
from pyLCIO import EVENT, IMPL, UTIL
class StdHepReader( Reader ):
''' Class to hold an LCStdHepRdr object '''
def __init__( self, fileName=None):
''' C... | 963 | 314 |
from contract import Forge,Validator,TOH,NDAO
from privateKey import my_address, private_key
# from web3.auto.infura.rinkeby import w3
from web3.auto import w3
import time # 引入time模块
another = "0x2E8b222CFac863Ec6D3446c78fD46aAEA289A9fb"
another_privateKey = "078e9ed558a9afd1e7e27b9884fbcc95f8fa406bd02de3a2a19fbac401... | 6,440 | 2,694 |
from asyncdb import AsyncDB, AsyncPool
import asyncio
loop = asyncio.get_event_loop()
asyncio.set_event_loop(loop)
params = {
"host": "127.0.0.1",
"port": "8086",
"database": 'testdb',
"user": "influxdata",
"password": "12345678"
}
DRIVER='influx'
async def test_connect(driver, params, event_lo... | 815 | 298 |
# coding: utf-8
"""
Director API
This is the oSparc's director API # noqa: E501
OpenAPI spec version: 0.1.0
Contact: support@simcore.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import simcore_director_sdk
from simcore_director_s... | 1,925 | 602 |
from .consts import *
L1_DOMAIN_RULES = [
{'type' : RULETYPE_EQUAL, 'text' : 'ru', 'action' : ACTION_FOLLOW, 'matcherkey' : 'r:net:domains_ru',
'entities' : [
{'name' : 'geo:ru:country/russia'},
]
},
{'type' : RULETYPE_EQUAL, 'text' : 'su', 'action' : ACTION_FOLLOW, 'matcherkey'... | 9,953 | 3,929 |
#Ui Widgets for pygame
#this is supposed to make it as easy as possible to make and use buttons and other widgets
#Documentation at 'https://github.com/TheBigKahuna353/PygameUI'
#All made by Jordan Withell
import pygame
#make screen quick
def Window(w = 500, h = 500):
pygame.init()
return pygame.dis... | 17,557 | 5,805 |
import discord
import blurple.io as io
class ReactionAddBasic(io.Reply):
"""An unopinionated, lower level class to wait for a user to add a reaction."""
event = "raw_reaction_add"
async def on_reply_init(self, message: discord.Message):
"""Sepcialized to pass message object."""
self.mess... | 2,108 | 607 |
# Generated by Django 3.2.7 on 2021-11-14 16:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('tasks', '0004_takeclass'),
]
operations = [
migrations.AlterUniqueTogether(
name='takeclass',
unique_together={('sid', 'cid'... | 341 | 122 |
from web3.auto import w3
import time
# from infura import *
import config
import json
with open("../build/contracts/EtherBank.json") as f:
ether_bank_json = json.load(f)
ether_bank_contract = w3.eth.contract(
address=config.ETHER_BANK_ADDR,
abi=ether_bank_json['abi']
)
accounts = w3.eth.accounts
def han... | 824 | 295 |
import argparse
import os
import shutil
import time
import random
import json
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchtext.vocab import GloVe
from progress.bar imp... | 14,316 | 5,043 |
from datetime import datetime, timedelta
from anubis.utils.cache import cache
from anubis.utils.data import is_debug, is_job
from anubis.utils.usage.users import get_platform_users
from anubis.utils.visuals.files import convert_fig_bytes
from anubis.utils.visuals.watermark import add_watermark
@cache.memoize(timeout... | 1,221 | 442 |
#!/usr/bin/python3
import sys
sys.argv[1:]
if len(sys.argv) < 2:
print("Off")
exit()
inp = sys.argv[1]
if(inp == '00000'):
print ("Off")
elif(inp == '10000'):
print ("Gas Auto Fan")
elif(inp == '01000'):
print ("Gas Slow Fan");
elif(inp == '00100'):
print ("Fan");
elif(inp == '00010'):
... | 438 | 208 |
from .CosineSimilarityLoss import *
from .SoftmaxLoss import *
from .MultipleNegativesRankingLoss import *
from .TripletLoss import *
from .MSELoss import *
from .ContrastiveLoss import *
from .OnlineContrastiveLoss import *
from .BatchHardTripletLoss import *
from .BatchHardSoftMarginTripletLoss import *
from .BatchS... | 420 | 151 |
"""empty message
Revision ID: b26b8edbe29a
Revises:
Create Date: 2018-11-28 21:01:53.633579
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b26b8edbe29a'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... | 2,876 | 999 |
from django.contrib import admin, messages
from django.contrib.auth.models import Group
from app.settings import GROUP_BY_DIVISION_NAME
from user.models import Division, History, Role, Team, User
from user.utils import send_imported, send_slack
def send_welcome(modeladmin, request, users):
for user in users:
... | 2,919 | 945 |
#!/usr/bin/env python
# -*- coding utf-8 -*-
import _io
import os
import time
import json
import requests
import urllib.parse
import tempfile
import shutil
import mlflow
import base64
import string
import numpy as np
from chassisml import __version__
from ._utils import zipdir,fix_dependencies,write_modzy_yaml,NumpyEn... | 11,584 | 3,432 |
#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a c... | 2,659 | 872 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
APT transport for a local OS accessible filesystem
"""
import os.path
import urllib.parse
from typing import IO
from apt.transport import Transport
from apt.transport.exceptions import URIMismatchError
from apt.transport.directorylisting import DirectoryListing
cl... | 2,667 | 794 |
import abc
import functools
import inspect
from typing import Any, Callable, Dict, List, Tuple, Type, Union
class PluginException(Exception):
def __init__(self, message, namespace: str = None, name: str = None) -> None:
super().__init__(message)
self.namespace = namespace
self.name = name
... | 7,213 | 1,983 |