text string | size int64 | token_count int64 |
|---|---|---|
import emcee
import numpy as np
from matplotlib import pyplot as plt
from remu import binning, likelihood, likelihood_utils, plotting
with open("../01/reco-binning.yml") as f:
reco_binning = binning.yaml.full_load(f)
with open("../01/optimised-truth-binning.yml") as f:
truth_binning = binning.yaml.full_load(f... | 4,211 | 1,734 |
import numpy as np
from data.tracking.sampler.SiamFC.type import SiamesePairSamplingMethod
from data.tracking.sampler._sampling_algos.stateless.random import sampling_multiple_indices_with_range_and_mask
from data.tracking.sampler._sampling_algos.sequence_sampling.common._algo import sample_one_positive
def do_triple... | 4,464 | 1,418 |
import pandas as pd
import numpy as np
import csv
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from sklearn.model_selection import train_test_split
from keras import regularizers
from keras.models import Sequential
from keras.layers import Dense, Flatten, Lambda, Cropping2D, Conv2D, MaxPooling2D, Ac... | 6,887 | 2,594 |
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
is_jobSeeker = models.BooleanField(default=False)
is_recruiter = models.BooleanField(default=False)
class Recruiter(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, relate... | 1,183 | 391 |
BPM_1 = 120.000
BPM_2 = 150.000
BPM_3 = 128.000
BPM_4 = 180.000
SEC_BEAT_1 = 60. / BPM_1
SEC_BEAT_2 = 60. / BPM_2
SEC_BEAT_3 = 60. / BPM_3
SEC_BEAT_4 = 60. / BPM_4
N_DANCER = 8
N_PART = 16
'''
2019_eenight_bpm (v9)
00:00.00 - 01:22.00 BPM = 120 (41*4拍)
01:22.00 - 01:58.80 BPM = 150 (23*4拍)
01:58.80 - 02:40.05 BPM = 1... | 4,069 | 2,094 |
# proxy module
from __future__ import absolute_import
from envisage.plugin_event import *
| 90 | 26 |
# Copyright (C) 2010 Chris Jerdonek (cjerdonek@webkit.org)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and... | 5,538 | 1,781 |
import hikari
import tanjun
from avgamah.core.client import Client
pussy_component = tanjun.Component()
@pussy_component.with_slash_command
@tanjun.with_own_permission_check(
hikari.Permissions.SEND_MESSAGES
| hikari.Permissions.VIEW_CHANNEL
| hikari.Permissions.EMBED_LINKS
)
@tanjun.with_nsfw_check
@ta... | 581 | 235 |
from jenga import Tower, Layer
from bots import StatBot
def layer_suite():
subjects = {Layer(): (3, (1, 1.0)),
Layer(False, False): (1, (1, 0.0))}
for subject in subjects:
if subject.get_mass() != subjects[subject][0]:
print("Failed: Expected {}".format(subjects[subj... | 564 | 210 |
from transducer import Transducer
def test_transducer():
Transducer
pass
| 83 | 28 |
from math import pi
from math import tan
def polysum(n, s):
perimeter = n * s
area = (0.25 * n * (s **2))/ (tan(pi/n))
result = perimeter**2 + area
return result
| 179 | 69 |
# pylint: skip-file
import copy
import random
from tellus.configuration import TELLUS_INTERNAL
from tellus.tell import Tell, SRC_TELLUS_USER
from tellus.tellus_sources.socializer import Socializer, CoffeeBot
from tellus.tellus_utils import datetime_from_string
from tellus.users import UserManager
from test.tells_test ... | 20,863 | 6,944 |
# proxy module
from pyface.ui.qt4.python_shell import *
| 56 | 20 |
from typing import Any
from aiohttp import ClientSession
from .common import Item, strip_html
API = "https://weibo.com/ajax/statuses/hot_band"
IMG = "https://wx4.sinaimg.cn/large/{}.jpg"
SEARCH = "https://s.weibo.com/weibo?q=%23{}%23"
def get_image(data: Any) -> str:
try: return IMG.format(data["mblog"]["pic_ids"][... | 1,149 | 449 |
"""
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water
and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid
are all surrounded by water.
"""
def numIslands(grid):
if grid is None and len(gri... | 955 | 375 |
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
"""Helper functions for writing tests."""
import logging
from typing import Dict
from pytest_operator.plugin import OpsTest
log = logging.getLogger(__name__)
async def get_unit_address(ops_test: OpsTest, app_name: str, unit_num: int) -> str... | 2,607 | 898 |
from .chart_component import ChartComponentList
class Regions(ChartComponentList):
"""
Highlight selected regions on the chart.
Parameters
----------
axes : c3py.axes.Axes
The chart's Axes object.
"""
def __init__(self, axes):
super(Regions, self).__init__()
se... | 1,841 | 507 |
import tensorflow as tf
import numpy as np
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.models import Sequential
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
#====================== DATA
import sys
sys.path.append("../Data")
from DataRegression import X, X_test, X_trai... | 4,420 | 1,643 |
import random
import tensorflow as tf
class Sequential:
def __init__(self, augments, seed=random.randint(0, 2 ** 32), n_augments=1, keypoints_format='xy', bboxes_format='xyxy'):
self.augments = augments
for aug in augments:
aug._set_formats(keypoints_format, bboxes_format)
self.... | 2,551 | 844 |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, ifitwala and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import json
from frappe import _
from frappe.utils import get_link_to_form, today, getdate, formatdate, date_diff, cint
from frappe.model.docum... | 6,585 | 2,160 |
#!/usr/bin/python
"""
Agent that monitors and reports the state of critical components of the framework
"""
import platform
from typing import Optional, List
from cloudadapter.client import Client
from cloudadapter.constants import LOGGERCONFIG
from cloudadapter.exceptions import BadConfigError
from cloudadapter.uti... | 2,824 | 796 |
# ===============================================================================
# Copyright 2018 gabe-parrish
#
# 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/licen... | 4,106 | 1,372 |
from typing import Union
import logging
from ...utitlities import create_list_from_dict
from ..configuration import LabelConfiguration, MetricConfiguration
def default(value) -> float:
if isinstance(value, list):
return default(value[0])
return 0 if value is None else float(value)
def is_ok(boolean:... | 5,947 | 1,872 |
from tandem.shared.io.proxies.base import ProxyBase
from tandem.shared.utils.fragment import FragmentUtils
class FragmentProxy(ProxyBase):
def __init__(self, max_message_length=512):
self._max_message_length = max_message_length
def pre_generate_io_data(self, params):
args, kwargs = params
... | 1,492 | 392 |
__all__ = ['IntegreSQL', 'DBInfo', 'Database', 'Template']
import hashlib
import http.client
import os
import pathlib
import sys
from typing import Optional, NoReturn, Union, List
import requests
from . import errors
__version__ = '0.9.2'
ENV_INTEGRESQL_CLIENT_BASE_URL = 'INTEGRESQL_CLIENT_BASE_URL'
ENV_INTEGRESQL_... | 8,888 | 2,810 |
from aws_resources.dynamo import table
def test_table():
db = table()
assert db != None
| 97 | 31 |
# In this problem we look at 2^n-digit binary strings and the n-digit substrings of these.
# We are given that n = 5, so we are looking at windows of 5 bits in 32-bit strings.
#
# There are of course 32 possible cyclic windows in a 32-bit string.
# We want each of these windows to be a unique 5-bit string. There are ex... | 1,653 | 577 |
__author__ = 'Peris'
#!/usr/bin/env python
#coding: utf-8
import argparse
from subprocess import call
import os
import shutil
import glob
from Bio import SeqIO
helptext="""
This script is to map reads to a reference assembly to generate an alignment for population genomics.
The output requires to convert N sites to ... | 17,727 | 7,388 |
# Copyright 2013 Lars Butler & individual contributors
#
# 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 applicab... | 25,099 | 8,924 |
nums = [5,2,31,2,5,7, 9, 10]
def bubble_sort(nums):
for i in range(len(nums)-1, 0, -1):
for j in range(i):
if nums[j] > nums[j+1]:
temp = nums[j]
nums[j] = nums[j+1]
nums[j+1] = temp
return nums
bubble_sort(nums) | 292 | 133 |
from __future__ import annotations
from unittest import TestCase
from jsonclasses.excs import UnauthorizedActionException
from tests.classes.gs_product import GSProduct, GSProductUser, GSTProduct
from tests.classes.gm_product import GMProduct, GMProductUser
class TestCanDelete(TestCase):
def test_guards_raises_i... | 2,104 | 669 |
# encoding=utf-8
# 解题思路:
# 依旧用了空间换时间的思路,记录找到的每个没有重复的子串的长度,然后求这些长度的最大值。
# 这里需要注意发现字符a已经在上一个子串中的时候,下一个子串应该是从上一个子串的a的下一位开始,而不是从a开始。
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
first = [0]
now = ""
for index, ... | 715 | 311 |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FuncFormatter
def millions(x, pos):
return '%1.1fM' % (x * 1e-6)
formatter = FuncFormatter(millions)
txt = """
4 381682 159258 1.61E+06
8 773030 366397 3.00E+06
12 1103917 519834 4.30E+06
16 1358805 740740 5.67E+06
... | 2,112 | 1,008 |
#!/usr/bin/env python3
import json
import textwrap
from collections import defaultdict
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Callable, Dict, List, Optional
import click
import pygments
import pygments.formatters
import pygments.lexers
import requests_ca... | 11,741 | 3,726 |
#!/usr/bin/env python
from backup_nanny.util.env_loader import ENVLoader
from backup_nanny.util.log import Log
from backup_nanny.util.backup_helper import BackupHelper
def handler(event, context):
main(event)
def main(event):
log = Log()
try:
backup_helper = BackupHelper(log=log)
backup_... | 688 | 235 |
# -*- coding:utf-8 -*-
import json
from django.test import TestCase
from unittest.mock import patch, MagicMock
from msn.events import EventTurnex
class EventTurnexTest(TestCase):
def setUp(self):
self.events = EventTurnex()
@patch('msn.events.EventTurnex.valid')
def test_process_with_v... | 4,179 | 1,263 |
from aiohttp import web
from aiohttp_security import remember, forget
async def test_remember(loop, test_client):
async def do_remember(request):
response = web.Response()
await remember(request, response, 'Andrew')
app = web.Application(loop=loop)
app.router.add_route('POST', '/', do_re... | 1,044 | 309 |
# *-* coding:utf-8 *-*
import tensorflow as tf
import numpy as np
import os
import cv2
import random
# 生成整数型的属性
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
# 生成字符串型的属性
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[... | 5,385 | 2,191 |
import rpncalc
#import readline
import curses
import sys
import os
import math
import pkgutil
import settings
STACK = 0
GRAPH_XY = 1
GRAPH_X = 2
mode = STACK
screen = curses.initscr()
screen.keypad(1)
YMAX, XMAX = screen.getmaxyx()
curses.noecho()
stackbox = curses.newwin(YMAX-4,XMAX -1,0,0)
inputbox = curses.newwi... | 9,694 | 4,350 |
valores = []
c = 0
resp = 'S'
cinco = 0
while resp in 'Ss':
v = valores.append(int(input('Digite um valor:')))
resp = str(input('Quer continuar? [S/N]:')).upper().strip()[0]
c+=1
print(f'Você digitou {c} valores')# ou len(valores)
valores.sort(reverse=True)
print(f'Os valores em ordem decrescente são {valor... | 452 | 180 |
"""
Base settings to build other settings files upon.
"""
import os
from pathlib import Path
import environ
# ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent.parent
ROOT_DIR = (environ.Path(__file__) - 3)
APPS_DIR = ROOT_DIR.path("shawty")
NUXT_APP_DIR = ROOT_DIR.path('client')
env = environ.Env()
READ_... | 6,649 | 2,362 |
# Clairmeta - (C) YMAGIS S.A.
# See LICENSE for more information
LOG_SETTINGS = {
'level': 'INFO',
'enable_console': True,
'enable_file': True,
'file_name': '~/Library/Logs/clairmeta.log',
'file_size': 1e6,
'file_count': 10,
}
DCP_SETTINGS = {
# ISDCF Naming Convention enforced
'naming... | 7,468 | 3,225 |
#!/usr/bin/env python3
"""This is an example to train a task with REPS algorithm.
Here it runs gym CartPole env with 100 iterations.
Results:
AverageReturn: 100 +/- 40
RiseTime: itr 10 +/- 5
"""
import gym
from garage import wrap_experiment
from garage.envs import GarageEnv
from garage.experiment import Lo... | 1,465 | 489 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
sys.path.insert(0, '../../../build/lib')
import numpy as np
import matplotlib.pyplot as plt
from py_aff3ct.module.py_module import Py_Module
class Display(Py_Module):
def plot(self, x):
if self.i_plt % 50 == 0:
self.line.set_data(x[0,::2], x[0,1::2])
... | 869 | 427 |
#!/usr/bin/env python -O
# -*- coding: utf-8 -*-
#
# tests.unit._dao.TestRTKEnvironment.py is part of The RTK Project
#
# All rights reserved.
"""
This is the test class for testing the RTKEnvironment module algorithms and
models.
"""
import sys
from os.path import dirname
sys.path.insert(
0,
dirname(d... | 3,906 | 1,282 |
# Copyright (c) Gorilla Lab, SCUT.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Dual Pose Network with Refined Learning of Pose Consistency.
Author: Jiehong Lin
"""
import os
import tensorflow as tf
import numpy as np
... | 30,297 | 10,125 |
# Copyright 2018 Joseph Wright <joseph@cloudboss.co>
#
# 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, mer... | 1,652 | 563 |
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
out = bin(n)[2:].split('0') #bin binarizes into form '0b----' where ---- is binary representataion
out = len(max(out)) # choosing maximum length of string as '11' > ... | 341 | 128 |
# -*- coding=utf-8 -*-
import pika
import sys
import numpy as np
import pickle
credentials = pika.PlainCredentials('myuser', 'mypassword')
with pika.BlockingConnection(
pika.ConnectionParameters('ice-P910',5672,'myvhost',
credentials)) as connection:
# connection = pika.BlockingConnection(pika.Connection... | 836 | 276 |
from rest_framework_json_api import serializers
__all__ = ('ShareSerializer', )
class ShareSerializer(serializers.ModelSerializer):
pass # Use as base for all serializers in case we need customizations in the future
| 225 | 60 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
DATABASE = 'db/user.db'
DEBUG = True
SECRET_KEY = 'secret_key_1'
| 114 | 54 |
import sys
lines = [l.rstrip() for l in open(sys.argv[1]).readlines() if len(l.rstrip()) > 0]
if len(lines) > 64:
print "Max 64 lines"
sys.exit(1)
lines.extend([""] * (64 % len(lines))) # Pad out to 64 lines
cols = max(len(l) for l in lines)
if cols > 128:
print "Max 128 columns"
sys.exit(1)
for i in ... | 599 | 235 |
import pandas as pd
import numpy as np
from sklearn.pipeline import Pipeline
import category_encoders as ce
from scipy.spatial.distance import cdist
from sklearn.externals import joblib
from db_helper import DbHelper
cols = ['column_a', 'player', 'all_nba', 'all_star', 'draft_yr','pk','team', 'college', 'yrs', 'gam... | 2,704 | 956 |
from third_party.molvs.charge import AcidBasePair
from rdkit import Chem
pair_string = """Nitro [C,c,N,n,O,o:1]-[NX3:2](=[O:3])-[O-1:4] [C,c,N,n,O,o:1]-[NX3:2](=[O:3])-[O:4]-[H] 3
Sulfate [SX4:1](=[O:2])(=[O:3])([O:4]-[C,c,N,n:5])-[O-1:6] [SX4:1](=[O:2])(=[O:3])([O:4]-[C,c,N,n:5])-[OX2:6]-[H] 5
Sulfonate [SX4:1](=[O:2... | 5,692 | 3,809 |
import cv2
from os import listdir
from os.path import isfile, join
import numpy as np
from math import sin, pi
paths = [f for f in listdir('combined_videos') if isfile(join('combined_videos', f))]
preds = np.load('agg_preds.npy')
preds = np.sqrt(preds)
for i in range(len(paths)):
ps = preds[i, :]
cap = cv2.V... | 854 | 314 |
from django.utils.importlib import import_module
from reversion import default_revision_manager
class InitialRevisionManagerMixin(object):
def _save_initial_revision(self, obj):
# try to load admin
try:
import_module("%s.admin" % obj.__module__.rsplit('.', 1)[0])
except Impor... | 701 | 193 |
from .bind import bind # noqa
__version__ = '3.0.0' # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT
| 120 | 51 |
#!/usr/bin/python3
'''
This module consists of three parts:
1.send_beans_email: a function to send email to remind users of their beans.
2.ApplicationMgr: a class that will deal with users' requests about beans application.
3.ApprovalRobot: a automatic robot to examine and approve users' applications.
'''
import t... | 5,909 | 1,784 |
#!/usr/bin/env python3
import requests
import json
url='http://172.16.1.90/ins'
switchuser='cisco'
switchpassword='cisco'
myheaders={'content-type':'application/json-rpc'}
payload=[
{
"jsonrpc": "2.0",
"method": "cli",
"params": {
"cmd": "interface ethernet 2/12",
"version": 1.2
},
... | 863 | 359 |
"""This policy contains classes for modal policies.
"""
import numpy as np
from sklearn.cluster import KMeans
#from sklearn.svm import SVC, SVR
#from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors.kde import KernelDensity
from poli import importance_sa... | 7,684 | 2,507 |
from os import path, environ
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
# Define a new database below
db = SQLAlchemy()
DB_NAME = "site.db"
login_manager = LoginManager()
def create_app():
# database configuration
app = Flask(__name__)
app.config['... | 1,510 | 465 |
from .dataloader import Dataset | 31 | 10 |
# This test checks that the developer doesn't pass a MIMEText instance to a MIMEMultipart initializer via the subparts parameter.
from flask import Flask, request
import json
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
app = Flask(__name__)
@app.route... | 1,230 | 386 |
# -*- coding: utf-8 -*-
"""
Created on 2020.12.19
@author: MiniUFO
Copyright 2018. All rights reserved. Use is subject to license terms.
"""
#%% load data
import xarray as xr
import numpy as np
nx, ny = 100, 100
gridx = xr.DataArray(np.arange(nx), dims=['X'], coords={'X': np.arange(nx)})
gridy = xr.DataArray(np.aran... | 1,072 | 487 |
# Generated by Django 3.0.10 on 2021-01-16 00:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0006_auto_20201001_0931'),
]
operations = [
migrations.AlterModelOptions(
name='auctionlot',
options={'orde... | 867 | 293 |
import argparse
import os
import sys
import json
import pylab as pl
import numpy as np
def main(args):
for solution_file in args.solution_files:
with open(solution_file, 'r') as f:
print(solution_file)
data = json.load(f)
t0 = data['t_0']
n_steps = data['n_s... | 1,451 | 479 |
import pymysql
import time
from lottery.conf import common_data
class MySqlUtil:
def __init__(self):
try:
config = common_data.readDBConf()
self._conn = pymysql.connect(host=config[0],
user=config[1],
... | 2,275 | 700 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-08 15:20
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('operacion', '0004_turno_hora_inicio'),
]
operations = [
migrations.RemoveField(
... | 398 | 145 |
import time
import threading
def current_time_millis():
return int(round(time.time() * 1000))
def get_class(kls):
parts = kls.split('.')
module = ".".join(parts[:-1])
m = __import__(module)
for comp in parts[1:]:
m = getattr(m, comp)
return m
def get_class_name(instance):
retur... | 1,381 | 460 |
# Heliodex 2021/08/24
# Last edited 2022/02/16 -- count number of steps and add reverse mode
# edit of vatRemover
# uses Short Method
print("Calculates amount after adding a percentage a number of times")
while True:
c = input("1 for normal, 2 for reverse, 3 for catchup ")
if c == "1":
val =... | 2,493 | 852 |
"""
Create an initial orthography profile, seeded from the forms created by a first run
of lexibank.makecldf.
"""
from lingpy import Wordlist
from lingpy.sequence import profile
from cldfbench.cli_util import get_dataset, add_catalog_spec
from csvw.dsv import UnicodeWriter
from clldutils.clilib import ParserError
from... | 2,623 | 844 |
# Copyright 2014 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.
"""Module to implement the JSON-RPC protocol.
This module uses xmlrpclib as the base and only overrides those
portions that implement the XML-RPC protocol. ... | 9,537 | 2,893 |
#!/usr/bin/env python
#
# Copyright 2014 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.
from __future__ import print_function
import collections
import multiprocessing
import optparse
import os
import platform
import re
... | 21,838 | 7,296 |
import requests
# 处理cookie的一个模板
# 会话
session = requests.session()
data = {
"账号" : "########",
"密码" : "########"
}
url = ""
res = session.post(url, data=data)
print(res.text)
res = session.get(url)
# resquests
header = {
"user-agent" : "dddd",
"Cookie" : "url"
}
resp = requests.get(url,headers=heade... | 340 | 146 |
#! /usr/bin/env python3
"""process which runs inside the docker daemon
the purpose of the doctor damon process is to allow the set up of
an environment which will support the deep speech recognition engine
to run on any recent nvidia Ubuntu host.
the basic operation of the demon is to create a named pipe
in the users... | 13,891 | 3,973 |
from intcode import *
def solve(instr, part):
input_instruction = 1 if part == 1 else 5
comp = Computer(instr, len(instr))
comp.receive(input_instruction)
comp.run()
return comp.out_queue[-1]
instructions = read_intcode_input(5)
print(solve(instructions, 1))
print(solve(instructions, 2))
| 314 | 121 |
import logging
import threading
import time
import pinylib
log = logging.getLogger(__name__)
def main():
room_name = raw_input('Enter room name: ').strip()
if pinylib.CONFIG.ACCOUNT and pinylib.CONFIG.PASSWORD:
client = pinylib.TinychatRTCClient(room=room_name, account=pinylib.CONFIG.ACCOUNT,
... | 3,736 | 1,092 |
"""
Session, a convenient wrapper around the low-level _NiFpga class.
Copyright (c) 2017 National Instruments
"""
from .nifpga import (_SessionType, _IrqContextType, _NiFpga, DataType,
OPEN_ATTRIBUTE_NO_RUN, RUN_ATTRIBUTE_WAIT_UNTIL_DONE,
CLOSE_ATTRIBUTE_NO_RESET_IF_LAST_SESS... | 23,645 | 6,463 |
TOTAL = 1000
def calc_stats(defRat, eleRat, resRat, p = True):
DEF = TOTAL * (0.75 + 0.025 * defRat)
OFF = TOTAL - DEF
ENE = OFF * (0.5 + 0.05 * eleRat)
STR = OFF - ENE
RES = DEF * (0.167 + 0.033 * resRat)
HP = DEF - RES
if p:
print ""
print ""
print "HP: " + str(HP)
print "STR: " + str(STR)
pri... | 1,822 | 898 |
""" JSON Web Token implementation
Minimum implementation based on this spec:
http://self-issued.info/docs/draft-jones-json-web-token-01.html
"""
import base64
import hashlib
import hmac
try:
import json
except ImportError:
import simplejson as json
__all__ = ['encode', 'decode', 'DecodeError']
class Dec... | 2,439 | 783 |
from .. import db
user_tag_associations_table = db.Table(
'user_tag_associations', db.Model.metadata,
db.Column('tag_id', db.Integer, db.ForeignKey('tags.id')),
db.Column('user_id', db.Integer, db.ForeignKey('users.id'))
)
resource_tag_associations_table = db.Table(
'resource_tag_associations', db.Mod... | 4,931 | 1,395 |
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
import numpy
x = torch.unsqueeze(torch.linspace(-1, 1, 300), dim=1) # x data (tensor), shape=(100, 1)
print(x)
y = x.pow(2) + 0.2 * torch.rand(x.size()) # noisy y data (tensor), shape=(100, 1)
plt.scatter(x.data.numpy(), y.data.numpy())
plt... | 2,631 | 1,502 |
import codewars_test as test
def persistence(n):
times = 0
if len(str(n)) == 1:
return times
else:
while len(str(n)) > 1:
multiple = 1
for x in str(n):
multiple *= int(x)
times += 1
n = multiple
return times
# import o... | 650 | 230 |
"""
kinds of modifiers
1. Ability Passive
- stat mods
- act damage up/down
- punisher
2. Action condtion (and Aura)
- there's a lot of crap here but they r all additive if same field
- str aura is same as _RateAttack
- certain fields (crit, crit dmg, punisher) are same bracket for w/e reason
3. hitattr
- independent... | 7,440 | 2,497 |
# -*- coding: utf-8; -*-
# Stolen from: http://bugs.python.org/issue12806
import argparse
import re
import textwrap
class FlexiFormatter(argparse.RawTextHelpFormatter):
"""FlexiFormatter which respects new line formatting and wraps the rest
Example:
>>> parser = argparse.ArgumentParser(formatter_... | 4,154 | 1,017 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
This script contains basic functions for Conv Neural Nets.
foward conv and pooling
backward conv and pooling
@author: xuping
"""
import numpy as np
import h5py
import matplotlib.pyplot as plt
def Conv_forward(A_prev, W, b, para):
'''
This is the forward prop... | 6,997 | 2,432 |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#hide
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
# In[2]:
# default_exp core
# In[3]:
#export
from nbdev.export import check_re,read_nb
from pathlib import Path
import re
import os
import platform
# #... | 6,682 | 2,288 |
"""Interoperability with `DSHARP <https://github.com/QuMuLab/dsharp>`_.
``load`` and ``loads`` can be used to parse files created by DSHARP's
``-Fnnf`` option.
``compile`` invokes DSHARP directly to compile a sentence. This requires
having DSHARP installed.
The parser was derived by studying DSHARP's output and sour... | 4,974 | 1,569 |
import pandas as pd
import matplotlib.pyplot as plt
from data import games
# Select All Plays
# In the file called offense.py in the stats folder you will find similar imports as the last module.
# Import the games DataFrame from data.
# Now that we have access to the games DataFrame.
# Select all rows that have a type... | 4,513 | 1,286 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# stdlib imports
import os
from gmprocess.io.read import read_data, _get_format, _validate_format
from gmprocess.utils.test_utils import read_data_dir
from gmprocess.utils.config import get_config
def test_read():
config = get_config()
cosmos_files, _ = read_dat... | 2,156 | 849 |
# third party
import torch as th
# syft absolute
import syft as sy
from syft.core.common.uid import UID
from syft.lib.python import String
def test_device() -> None:
device = th.device("cuda")
assert device.type == "cuda"
assert device.index is None
def test_device_init() -> None:
bob = sy.VirtualM... | 633 | 214 |
# Copyright 2021 The CLU Authors.
#
# 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... | 8,495 | 3,077 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Read the posts and return a tuple that consisting of
Front Matter and its line number.
© 2018-2019 Cotes Chung
MIT License
'''
def get_yaml(path):
end = False
yaml = ""
num = 0
with open(path, 'r') as f:
for line in f.readlines():
... | 570 | 176 |
from django.conf import settings
from django.db.models import Max
from datetime import datetime, timedelta
from me2ushop.models import Order, OrderItem
def remove_old_cart_items():
print('Removing old carts')
print('session age:', settings.SESSION_AGE_DAYS)
# calculate date of session age days ago
rem... | 1,014 | 316 |
from datetime import datetime
import isodate
import re
import traceback
def to_list(val):
return [val] if not hasattr(val, 'reverse') else val
# Add duration to end date using
# ISO 8601 duration keys
def determine_end_date(key, date):
return date + isodate.parse_duration(key)
# This method takes a layer and... | 3,658 | 1,182 |
from typing import Union, Callable
from . import heuristics
from .active_loop import ActiveLearningLoop
from .dataset import ActiveLearningDataset
from .file_dataset import FileDataset
def get_heuristic(
name: str, shuffle_prop: float = 0.0, reduction: Union[str, Callable] = "none", **kwargs
) -> heuristics.Abst... | 1,162 | 360 |
"""empty message
Revision ID: e454b1597ab0
Revises:
Create Date: 2021-01-19 11:50:17.899068
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e454b1597ab0'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... | 1,916 | 698 |
from django.apps import AppConfig
class QacConfig(AppConfig):
name = 'qac'
| 81 | 28 |
from os import getenv
from pathlib import Path
from dotenv import load_dotenv
base_path = Path('.') # Fully qualified path to the project root
env_path = base_path / '.env' # Fully qualified path to the enviroment file
app_path = base_path.joinpath('app') # The fully qualified path to the app fold... | 3,249 | 722 |
import os
import itertools
from pytest import raises, mark
import h5py
import datetime
import numpy as np
from numpy.testing import assert_equal
from .helpers import setup_vfile
from ..backend import DEFAULT_CHUNK_SIZE
from ..api import VersionedHDF5File
from ..versions import TIMESTAMP_FMT
from ..wrappers import ... | 72,964 | 26,202 |