text string | size int64 | token_count int64 |
|---|---|---|
from django.contrib.auth.models import User
from rest_framework import generics
from .serializers import UserSerializer
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
| 240 | 66 |
# Copyright 2017 Pavlo Penenko
#
# 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 writing... | 5,093 | 1,447 |
#!/usr/bin/python2.6
import os
import sys
import time
from optparse import OptionParser
from google.refine import refine
from clean_ads_affiliations import clean_ads_affs
assert sys.hexversion >= 0x02060000
SERVER = 'http://adsx.cfa.harvard.edu:3333'
def create_refine_project(path, name, pretend=False, verbose=0):... | 1,981 | 623 |
from django.http import JsonResponse, Http404
from django.views.decorators.csrf import csrf_exempt
from exponent_server_sdk import PushClient, PushMessage, DeviceNotRegisteredError
from .models import Group, User, Event
import hashlib, uuid
def getParams(request, tags):
print(request.POST)
return [request.POST... | 8,256 | 2,693 |
"""Implement this function across different project.
----ZY.2020.Oct.
"""
import os
from easydict import EasyDict
from torchvision.utils import save_image
from logging import Logger
from subprocess import call
def create_save_folders(root_folder, folder_list: list):
"""Create folders to save visualization image.
... | 3,572 | 1,156 |
from nose.tools import assert_equals, assert_true
from wikimetrics.metrics import metric_classes
from wikimetrics.models import (
MetricReport
)
from ..fixtures import DatabaseTest
class MetricReportTest(DatabaseTest):
def setUp(self):
DatabaseTest.setUp(self)
self.common_cohort_1()
d... | 1,465 | 501 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name="clut2dtstyle",
license="Unlicense",
version="0.1",
author="Manu Mannattil",
author_email="manu.mannattil@gmail.com",
description="Script to convert Hald CLUTs to darktable styles",
py_modules=["clut2dt... | 615 | 211 |
import meshzoo
import numpy as np
import xarray as xr
import xugrid
def transform(vertices, minx, maxx, miny):
"""
Transform vertices to fit within minx to maxx.
Maintains x:y aspect ratio.
"""
x, y = vertices.T
xmin = x.min()
xmax = x.max()
ymin = y.min()
ymax = y.max()
dx = ... | 1,903 | 812 |
# Generated by Django 3.2.5 on 2021-07-19 20:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('calendar_generator', '0005_alter_calendar_options'),
]
operations = [
migrations.CreateModel(
n... | 898 | 272 |
import ckan.plugins as plugins
import ckan.model as model
import ckan.logic as logic
import ckan.plugins.toolkit as toolkit
import ckan.lib.plugins as plugs
from pylons import c
NotFound = logic.NotFound
get_action = logic.get_action
class GroupPlugin(plugins.SingletonPlugin, plugs.DefaultGroupForm):
plugins.imp... | 2,492 | 744 |
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | 2,087 | 670 |
#Name: s2_convert.py
#Purpose: Convert PDFs to TXT format
#Invocation: python3 s2_convert.py <projName> <lng> <clss>
import codecs
import os
import re
import sys
#Name: valid_arguments
#Purpose: Check whether the command-line arguments are valid
#Parameters: sys.argv (globally defin... | 10,379 | 3,597 |
def test_greet_user(client, test_strings):
for s in test_strings:
_route = f"/api/v1/greeting/{s}"
r = client.get(_route)
assert r.status_code == 200
assert r.json == {"greeting": "Hello", "user": s}
def test_add_int_success(client, test_ints):
_data = {"add": test_ints}
r ... | 1,004 | 393 |
# -*-coding: utf-8-*-
from sdata.experiments import Test
class TensionTest(Test):
"""Tension test
"""
def __init__(self, name, **kwargs):
Test.__init__(self, name=name, **kwargs) | 200 | 71 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""The code implementation of SharedGradNet.
main0.py is for neural networks without hidden layer.
Some part from: https://jhui.github.io/2018/02/09/PyTorch-Variables-functionals-and-Autograd/
2019/06/17: Update with hyper-parameter tuning script.
2019/06/25: Committed mai... | 5,818 | 1,947 |
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Aug 8 2018)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
###########################################################################
impor... | 19,144 | 9,362 |
print("Hello World")
print(5+4)
print(5,"+",4,"=",5+4)
| 55 | 29 |
from django.core.management.base import BaseCommand, CommandError
import time
from hud_api_replace.models import CachedGeodata
class Command(BaseCommand):
help = 'Deletes geodata records that are expired.'
def handle(self, *args, **options):
CachedGeodata.objects.all().filter(expires__lte=time.time(... | 332 | 102 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import utils
class Protection(object):
# 2 = Alarm, 1 = Warning, 0 = Normal
def __init__(self):
self.voltage_high = None
self.voltage_low = None
self.voltage_cell_low = None
... | 7,694 | 2,450 |
import numpy as np
from scipy.special import logsumexp
from scipy.optimize import minimize
from functools import partial
from dataclasses import dataclass, field
import matplotlib.pyplot as plt
@dataclass
class BindingDwelltimesBootstrap:
"""Bootstrap distributions for a binding dwelltime model.
This class i... | 16,227 | 4,690 |
largura=float(input('digite qual a largura da sua parede:'))
comprimento=float(input('digite qual o comprimento da sua parede:'))
quantidade=((largura*comprimento)/2)
print('A area da sua parede é de',(largura*comprimento),'para pintar sua parede será necessario {} litros de tinta'.format(quantidade)) | 302 | 98 |
class Crab:
def __init__(self, crab_id, sex, species, color, damage, carapace, mass, epibiont, molt):
self.id = crab_id
self.sex = sex
self.species = species
self.color = color
self.damage = damage
self.carapace = carapace
self.mass = mass
self.epibion... | 508 | 173 |
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import, division, print_function, unicode_literals
import... | 2,821 | 918 |
#!/usr/bin/env python
# coding: utf-8
"""
Em
--
Em is a terminal tool that prints FILE(s), or standard input to standard
output and highlights the expressions that are matched the PATTERN.
The expression will be highlighted iff the terminal is ANSI-compatible.
Em is Cool
``````````
.. code:: bash
$ tail -f /p... | 3,040 | 998 |
import json
import os
import random
import string
import requests
from keep_alive import keep_alive
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import discord
client = discord.Client()
starter_motivator = [
"Cheer Up!",
"Always remember, I am here for you!",
"You are a great person. Reme... | 1,883 | 627 |
import cv2, os
import numpy as np
import csv
import glob
label = "Parasitized"
dirList = glob.glob("cell_images/" + label + "/*.png")
file = open("csv/dataset.csv", "a")
for img_path in dirList:
im = cv2.imread(img_path)
im = cv2.GaussianBlur(im, (5, 5), 2)
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY... | 1,655 | 710 |
import os
import numpy as np
def load_mnist(path='mnist'):
data_dir = os.path.join("./data", path)
fd = open(os.path.join(data_dir,'train-images-idx3-ubyte'))
loaded = np.fromfile(file=fd,dtype=np.uint8)
trX = loaded[16:].reshape((60000,28,28,1)).astype(np.float)
fd = open(os.path.join(data_dir,'... | 1,234 | 568 |
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
def iichome(request):
return render(request, 'iic/home.html')
| 180 | 53 |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sn
from utils import convert, iou
def average_pairwise_IOU(IOU_mat):
n = IOU_mat.shape[0]
mean_IOU = (np.sum(IOU_mat)-n)/(np.size(IOU_mat)-n)
return mean_IOU
def group_IOU_matrices(paths):
survey_names = [p.repl... | 2,210 | 847 |
from unittest import TestCase
class TestDebugger(TestCase):
def test_execute(self):
# self.fail()
pass
def test_parse_instr(self):
from zlua_prototype.debugger import _parse_instr
assert _parse_instr('f ')==('f','') | 257 | 81 |
"""
Compares spectrogram computations with TensorFlow and Vesper.
As of 2018-11-09, Vesper is a little more than three times faster than
TensorFlow at computing spectrograms with a DFT size of 128.
"""
import functools
import time
import numpy as np
import tensorflow as tf
import vesper.util.data_windows as data_w... | 3,033 | 1,106 |
import time
def main(request, response):
time.sleep(0.1)
return [("Content-Type", "text/plain")], "FAIL"
| 110 | 42 |
import os
from django.conf import settings
import django
def configure_settings():
settings.configure(
DEBUG=True,
INSTALLED_APPS=['npm'],
NPM_EXECUTABLE_PATH=os.environ.get('NPM_EXECUTABLE_PATH', 'npm'),
CACHES={
'default': {
'BACKEND': 'django.core.ca... | 401 | 131 |
from opentrons import protocol_api
import json
import os
import math
# metadata
metadata = {
'protocolName': 'V1 S14 Station A MagMax',
'author': 'Nick <protocols@opentrons.com>',
'source': 'Custom Protocol Request',
'apiLevel': '2.4'
}
NUM_SAMPLES = 64
SAMPLE_VOLUME = 100
TIP_TRACK = False
def run(... | 2,770 | 1,061 |
import logging
import numpy as np
from .efish_ephys_repro import EfishEphys
class Baseline(EfishEphys):
"""Represents the run of the Baseline repro of the efish plugin-set.
"""
_repro_name = "BaselineActivity"
def __init__(self, repro_run, traces, relacs_nix_version=1.1) -> None:
super().__i... | 2,683 | 790 |
# Generated by Django 3.2.3 on 2021-05-17 15:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Blogs',
fields=[
... | 1,258 | 362 |
# Reuters-21578 dataset downloader and parser
#
# Author: Eustache Diemert <eustache@diemert.fr>
# http://scikit-learn.org/stable/auto_examples/applications/plot_out_of_core_classification.html
#
# Modified by @herrfz, get pandas DataFrame from the orig SGML
# License: BSD 3 clause
from __future__ import print_funct... | 5,101 | 1,599 |
import numpy as np
import pandas as pd
from scipy.stats import expon, uniform
import sys
sys.path.append('../../well_mixed')
from well_mixed_death_clock import (WellMixedSimulator,
WellMixedSimulationData, exponential_ccm, uniform_ccm,
base_rate_death_signal)
# Exponential cell cycle model
tG1 = 50
tG2 = 50
... | 7,908 | 2,873 |
class Professor:
def __init__(self, ratemyprof_id: int, first_name: str, last_name: str, num_of_ratings: int, overall_rating):
self.ratemyprof_id = ratemyprof_id
self.name = f"{first_name} {last_name}"
self.first_name = first_name
self.last_name = last_name
self.num_of_rati... | 485 | 169 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 导入SQLite驱动:
import sqlite3
# 连接到SQLite数据库
# 数据库文件是test.db
# 如果文件不存在,会自动在当前目录创建:
conn = sqlite3.connect('hello.db')
# 创建一个Cursor:
cursor = conn.cursor()
cursor.execute('drop table user')
# 执行一条SQL语句,创建user表:
cursor.execute('create table user (id varchar(20) primary key, n... | 810 | 371 |
# imports
import requests, json
# beautifulsoup4
from bs4 import BeautifulSoup
def searchDisplay(username):
# base url for the data
url = 'https://www.instagram.com/{}/'.format(username)
try:
req = requests.get(url).content
soup=BeautifulSoup(req,"html.parser")
row=soup.f... | 1,324 | 399 |
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 2,369 | 785 |
# Generated by Django 2.2.5 on 2019-09-25 14:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0003_auto_20190629_1623'),
]
operations = [
migrations.AddField(
model_name='userdata',
name='primaryFie... | 507 | 183 |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def poppy():
http_archive(
name="Poppy" ,
build_file="//bazel/deps/Poppy:build.BUILD" ,
sha256="905921192994f6243e... | 580 | 294 |
class Rectangle3d(object,IEpsilonComparable[Rectangle3d]):
"""
Rectangle3d(plane: Plane,width: float,height: float)
Rectangle3d(plane: Plane,width: Interval,height: Interval)
Rectangle3d(plane: Plane,cornerA: Point3d,cornerB: Point3d)
"""
def ClosestPoint(self,point,includeInterior=None):
"""
Closes... | 4,023 | 1,523 |
# shouldn't apparently need this file, but here we are
from . import atommapping
from . import echo | 99 | 25 |
import os
import re
import pymongo
import pandas as pd
import numpy as np
import streamlit as st
from bokeh.plotting import figure
from bokeh.palettes import Set1_9, Set3_12, Inferno256
@st.cache(suppress_st_warning=True, allow_output_mutation=True)
def get_caudales():
"""Function to obtain the rivers basin flows... | 27,163 | 9,112 |
#!/usr/bin/env python3
"""Generator of the function to prohibit certain vowel sequences.
It creates ``_hb_preprocess_text_vowel_constraints``, which inserts dotted
circles into sequences prohibited by the USE script development spec.
This function should be used as the ``preprocess_text`` of an
``hb_ot_complex_shaper... | 5,930 | 1,811 |
from datetime import datetime, timedelta
import pytz
ALLOWED_AGE_PER_STATUS = {
"default": 5 * 60,
# LMS instruments can take a very long time to generate when the SPS is not cached
"started": 35 * 60,
"nifi_notified": 30 * 60,
}
COMPLETE_STATES = ["inactive", "in_arc"]
def slow_process(state_recor... | 1,719 | 550 |
import socket
import select
fd_to_socket = {}
READ_ONLY = ( select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR)
READ_WRITE = (READ_ONLY|select.POLLOUT)
poller = select.poll()
server = None
IP = '127.0.0.1'
Port = 7002
def getAddress ():
return IP, Port
def initServer(ip=IP, port=Port):
global se... | 2,229 | 683 |
#
# PySNMP MIB module A3COM-HUAWEI-SNA-DLSW-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-SNA-DLSW-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:52:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | 39,506 | 18,651 |
# Leetcode 98. Validate Binary Search Tree
#
# Link: https://leetcode.com/problems/validate-binary-search-tree/
# Difficulty: Medium
# Complexity:
# O(N) time | where N represent the number of elements in the input tree
# O(N) space | where N represent the number of elements in the input tree
# Definition for a bi... | 1,263 | 387 |
from setuptools import setup
version = open("ccb/__version__.py").read().strip('"\n')
setup_args = {
"name": "ccb",
"version": version,
"url": "https://github.com/earth-chris/ccb",
"license": "MIT",
"author": "Christopher Anderson",
"author_email": "cbanders@stanford.edu",
"description": "... | 763 | 277 |
# import time
#
# def reader():
# """A generator that fakes a read from a file, socket, etc."""
# for i in range(101):
# yield '<< %s' % i
#
# def consumer():
# r = ''
# while True:
# #但是Python的yield不但可以返回一个值,它还可以接收调用者发出的参数。
# #此处的n是接受参数
# n = yield from reader()
# ... | 1,576 | 719 |
import maya.cmds as mc
import maya.OpenMaya as OpenMaya
import glTools.utils.base
def transferComponentSelection(sourceSelection,targetMesh,threshold=0.0001):
'''
'''
# Check selection target mesh
if not mc.objExists(targetMesh):
raise Exception('Target mesh "'+targetMesh+'" does not exist!')
# Flatten selec... | 1,288 | 503 |
"""
A Python package for recipe parsing and management.
"""
import yaml
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
from .exceptions import LoadError, ParseError, PyprikaError, FieldError # noqa
from .ingredient import Ingredient # noqa
from .quantity import Quantity # n... | 3,289 | 969 |
def test_get_bond_infos(case_data):
"""
Test :meth:`.ConstructedMolecule.get_bond_infos`.
Parameters
----------
case_data : :class:`.CaseData`
A test case. Holds the constructed molecule to test and the
correct number of new bonds.
Returns
-------
None : :class:`NoneTyp... | 1,202 | 438 |
from django.apps import AppConfig
class BaseViewsConfig(AppConfig):
name = 'base_views'
| 94 | 29 |
import json
import praw
reddit = praw.Reddit("dwight-schrute-bot")
for submission in reddit.subreddit('all').rising(limit=15):
submission.comments.replace_more(limit=None)
print(submission.subreddit.display_name)
if not submission.over_18:
for comment in submission.comments.list():
pri... | 324 | 103 |
from pymavlink import mavutil
import time
# Create the connection
master = mavutil.mavlink_connection('udpin:0.0.0.0:14550')
# Wait a heartbeat before sending commands
master.wait_heartbeat()
# Send a positive x value, negative y, negative z,
# positive rotation and no button.
# http://mavlink.org/messages/common#MAN... | 1,311 | 474 |
# -*- coding: utf-8 -*-
#############################################################
# IMPORTS #
#############################################################
import os
from PIL import Image
import pyheif
#####################################################... | 1,734 | 474 |
import functools
import os
import ssl
import uuid
from typing import Any, Dict, List, Literal, Optional, Tuple
import jinja2
import pydantic
import yaml
from .exceptions import TplBuildException, TplBuildTemplateException
RESERVED_PROFILE_KEYS = {
"begin_stage",
"platform",
}
def _normalize_rel_path(path: ... | 17,863 | 5,070 |
#!/usr/bin/env python
from setuptools import setup
from distutils.command.build import build
from setuptools.command.develop import develop
class build_with_spurious(build):
def run(self):
import os
if "CC" in os.environ:
cc = os.environ['CC']
else:
cc = "cc"
... | 1,634 | 532 |
import sys
sys.path.append("/Library/Frameworks/GStreamer.framework/Versions/0.10/lib/python2.7/site-packages/")
import gobject
gobject.threads_init()
import pygst
pygst.require("0.10")
import gst
class Client(object):
def __init__(self):
self.pipeline = gst.Pipeline('client')
self.videotestsrc = s... | 1,126 | 414 |
from django.contrib.auth.models import User
from django.core import mail
from django.shortcuts import resolve_url
from django.test import TestCase
from InternetSemLimites.core.forms import ProviderForm
from InternetSemLimites.core.models import Provider, State
class TestPostValid(TestCase):
def setUp(self):
... | 3,852 | 1,217 |
from z3 import *
CONNECTIVE_OPS = [Z3_OP_NOT,Z3_OP_AND,Z3_OP_OR,Z3_OP_IMPLIES,Z3_OP_IFF,Z3_OP_ITE]
REL_OPS = [Z3_OP_EQ,Z3_OP_LE,Z3_OP_LT,Z3_OP_GE,Z3_OP_GT]
OPERATORS = CONNECTIVE_OPS + REL_OPS
# var is tuple (type, name)
def createVar(var):
t = var[0]
n = var[1]
if t=="int":
return Int('%s' % n)
elif t=="... | 2,780 | 1,043 |
import random
data_list = random.sample(range(100), 50)
def selectionSort(arr):
for index1 in range(len(arr) - 1):
lowestIndex = index1
for index2 in range(index1, len(arr)):
if(arr[lowestIndex] > arr[index2]):
lowestIndex = index2
arr[index1] = arr[lowestIndex]
return arr
print(sele... | 351 | 129 |
import logging
from typing import Any, Mapping
import redis
import conf
import ocular
import workers
from constants.experiment_jobs import get_experiment_job_uuid
from db.redis.containers import RedisJobContainers
from db.redis.statuses import RedisStatuses
from lifecycles.jobs import JobLifeCycle
from options.regi... | 12,045 | 3,464 |
import sys
import json
import numpy as np
import matplotlib.pyplot as plt
class Wing:
"""A class for modeling a finite wing using the sine-series solution to Prandtl's lifting-line equation.
Parameters
----------
planform : str
May be "elliptic" or "tapered".
b : float
Wingspan.... | 14,636 | 5,818 |
from django.db import models
class Task(models.Model):
title = models.CharField(max_length=40)
description = models.TextField(max_length=500)
date_created = models.DateTimeField(auto_now_add=True)
date_last_modified = models.DateTimeField(auto_now=True)
| 271 | 87 |
def elevate():
import ctypes, win32com, win32event, win32process, os, sys
outpath = r'%s\%s.out' % (os.environ["TEMP"], os.path.basename(__file__))
if ctypes.windll.shell32.IsUserAnAdmin():
if os.path.isfile(outpath):
sys.stderr = sys.stdout = open(outpath, 'w', 0)
return
wit... | 927 | 328 |
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
app_name = 'etikihead'
urlpatterns = [
path('', views.entry_mask, name='entrymask'),
path('contact/', views.contact, name='contact'),
path('privacy/', views.privacy, name='privac... | 629 | 213 |
# TC002 test case - Login in with new user data - exit
import data.data_tcA002 as da02
import func.func_01 as fu01
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
opti... | 1,070 | 362 |
"""Tests for the data utilities from lisc."""
from lisc.data.utils import *
###################################################################################################
###################################################################################################
def test_count_elements():
tdat = ['... | 966 | 298 |
from leapp import reporting
from leapp.actors import Actor
from leapp.models import FirewalldGlobalConfig, FirewallsFacts
from leapp.reporting import create_report, Report
from leapp.tags import ChecksPhaseTag, IPUWorkflowTag
class FirewalldCheckAllowZoneDrifting(Actor):
"""
This actor will check if AllowZone... | 2,316 | 644 |
import os
def run(path: str, return_full_path: bool = False):
"""Gets all files and folders from a path and stores them into $file_list
Arguments:
path {str} -- The path to get files and folders from
Keyword Arguments:
return_full_path {bool} -- True to return the full path of th... | 665 | 202 |
"""
Test for workspaces API
"""
# TODO: tests for authorization codes
import random
from collections.abc import Generator
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from wxc_sdk.rest import RestError
from wxc_sdk.all_types import *
from .base import TestCaseWithLog
TEST_WO... | 11,938 | 3,413 |
import tensorflow as tf
import glob
from configuration import OpenPoseCfg as cfg
from openpose.data.augmentation import Transformer
def get_tfrecord_filenames(path):
print("从"+path+"中提取TFRecords文件:")
tfrecord_files = glob.glob(path + "*")
tfrecord_files.sort()
if not tfrecord_files:
raise Va... | 1,935 | 659 |
dia = int(input('Quantos dias alugados? '))
km = float(input('Quantos KM rodados? '))
print('Como você ficou {} dias com ele e rodou {:.2f}KM, sua conta ficou em {:.2f}R$'.format(dia, km, (60*dia)+(0.15*km)))
| 209 | 93 |
""" Ip Info """
class Ip(object):
""" Ip Info """
def __init__(self, downspeed, online, upspeed, active, ip):
self._downspeed = downspeed
self._online = online
self._upspeed = upspeed
self._active = active
self._ip = ip
def get_downspeed(self):
return self... | 775 | 248 |
from django.shortcuts import render, redirect, HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse
def user_... | 1,608 | 437 |
from gbdxtools.images.worldview import WorldViewImage
from gbdxtools.images.geoeye01 import GeoEyeDriver
from gbdxtools.images.util import vector_services_query
band_types = {
'MS': 'BGRN',
'Panchromatic': 'PAN',
'Pan': 'PAN',
'pan': 'PAN'
}
class QB02Driver(GeoEyeDriver):
pass
class QB02(WorldVi... | 689 | 250 |
from meld import logger
def main():
logger.info('Starting move operation')
logger.info('Finished') | 102 | 32 |
import tensorflow as tf
def bpnet_model(seqlen=1000, numchars=4, num_dilated_convs=9, num_tasks=1,
name='bpnet_model'):
# original as per https://www.biorxiv.org/content/10.1101/737981v1.full.pdf
inp = tf.keras.layers.Input(shape=(seqlen, 4))
x = tf.keras.layers.Conv1D(
64, kernel_... | 1,137 | 454 |
#!/usr/bin/env python3
#-------------------------------------------------------------------------------
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedArrayToBST(self, nums)... | 801 | 216 |
# Generated by Django 3.2.6 on 2021-08-14 19:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('collect', '0005_alter_courseinfo_name'),
]
operations = [
migrations.AlterField(
model_name='courseinfo',
name='name... | 600 | 244 |
import numpy as np
import xobjects as xo
import xpart as xp
def test_basics():
for context in xo.context.get_test_contexts():
print(f"Test {context.__class__}")
p1 = xp.Particles(x=[1,2,3], px=[10, 20, 30],
mass0=xp.ELECTRON_MASS_EV,
_context=co... | 596 | 226 |
from utils.loader import Loader
from utils.model import DeepSNN
import torch
import os
def feature_extraction(prop):
name = prop["name"]
epochs_l1 = prop["epochs_l1"]
epochs_l2 = prop["epochs_l2"]
trainset, testset = Loader(name)
model = DeepSNN(prop)
# Training The First... | 4,550 | 1,859 |
"""集合基礎
集合内包表記の使い方
[説明ページ]
https://tech.nkhn37.net/python-set-comprehension/#i
[内包表記まとめページ]
https://tech.nkhn37.net/python-comprehension/
"""
data = [10, 15, 20, 25, 30, 35, 40, 45, 50, 10, 15, 20, 25, 30]
# 集合内包表記
data_set = {dt for dt in data if dt % 2 == 0}
print(f'data_set : {data_set}')
| 296 | 195 |
class Solution:
def halvesAreAlike(self, s: str) -> bool:
vowel = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
first = s[:int(len(s)/2)]
second = s[int(len(s)/2):]
firstsum = sum([1 for f in first if f in vowel])
secondsum = sum([1 for s in second if s in vowel])
... | 409 | 144 |
#!/usr/bin/env python
# * coding: utf8 *
'''
worker_bee.py
A module that contains logic for building traditional image-based caches.
'''
import os
import socket
import time
from os.path import join, dirname, realpath
from shutil import rmtree
import pygsheets
from datetime import date
import arcpy
from . import con... | 9,789 | 3,097 |
import taichi as ti
PI = 3.1415926
# http://www.glowinggoo.com/sph/bin/kelager.06.pdf
@ti.data_oriented
class W_poly6:
@staticmethod
@ti.func
def W(r_vec, h):
r2 = r_vec.dot(r_vec)
r2 = ti.max(r2, 1e-10)
k = 0.0
if r2 <= h ** 2:
k = ((h ** 2) - r2) ** 3
... | 4,418 | 2,184 |
import requests
import json
url_sehir = "https://ezanvakti.herokuapp.com/sehirler/2"
r = requests.get(url_sehir)
j = r.json()
sehir_adi = input("Şehir:")
ilce_adi = input("İlçe:")
for sehir in j:
if sehir_adi == sehir["SehirAdi"]:
ID = sehir["SehirID"]
print(ID)
url_ilce = "https://ezanva... | 747 | 339 |
#!/usr/bin/python3
"""
RobotArm API service config file
"""
import pathlib
from robotarm.armservice.views import api_views
from flask import (
Flask,
make_response,
jsonify
)
from robotarm.armservice import getenv
# initialize flask app
app = Flask(__name__)
# register/mount blueprint
app.register_bluepri... | 799 | 288 |
from xbrr.base.reader.base_element_schema import BaseElementSchema
from bs4.element import NavigableString, Tag
import bs4
class ElementSchema(BaseElementSchema):
def __init__(self,
name="", reference="", label="", alias="",
abstract="", data_type="",
period_type... | 4,685 | 1,438 |
from datetime import datetime
class Sources:
"""
Sources class to define sources object
"""
def __init__(self, id, name, description, url, category, country):
self.id = id
self.name = name
self.description = description
self.url = url
self.category = category
... | 817 | 235 |
# Generated by Django 3.1 on 2020-10-18 11:51
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('post', '0002_auto_20200920_1217'),
]
operations = [
... | 661 | 217 |
from .transcript_day import *
def test():
parsed = TranscriptDay(EXAMPLE_DATA)
print(parsed)
assert parsed.room_id == 11540
assert parsed.room_name == "Charcoal HQ"
assert parsed.first_day == datetime.date(2013, 11, 16)
assert parsed.previous_day == datetime.date(2017, 11, 16)
assert pa... | 70,946 | 25,445 |
"""
A set of functions required to pre-process TRNSYS simulation input files
"""
# Common imports
import os
import sys
import shutil
import re
# Custom imports
from pybps import util
# Handle Python 2/3 compatibility
from six.moves import configparser
import six
if six.PY2:
ConfigParser = configparser.SafeConfigP... | 4,709 | 1,501 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Game of Life console.
small play ground for leanning python, or just having fun.
To use the console with an empty grid:
python -i -mgof.console
or
bpython -i -mgof.console
To use the console with a pseudo animation:
python -i -mgof.demo
Avalailble varia... | 1,650 | 536 |