index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
10,600 | 5fa2e7d4ff00b4e614f89284bd1fc10e1486b677 | from django.apps import AppConfig
class PersoAppConfig(AppConfig):
name = 'perso_app'
|
10,601 | 52c9a916cbf699ca1058e16f1cdb8b46ddee7a95 | from django.apps import AppConfig
class BbcConfig(AppConfig):
name = 'social_simulator.bbc'
|
10,602 | 337c33dd8415f0ff3294d6bfcfdbbc090638e118 | import task
task_1 = task.Task('MPI-1717', 'Create /filters endpoint and update postman collection', '6')
task_2 = task.Task('MPI-1717', 'Create business logic to handle user request', '8')
task_3 = task.Task('MPI-1717', 'Performance testing', '8')
task_4 = task.Task('MPI-1717', 'Performance testing', '8')
task_5 = ta... |
10,603 | 9771414251ba083612d9280a7c9879d03e3b0b54 | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
stack=[]
length=len(S)
res=""
for i in range(length):
if S[i] == "#" and len(stack)!=0:
stack.pop()
elif S[i]=="#" and len(stack)==0:
continue
else:... |
10,604 | ff3885413e65865b3c509532ed0e665549c1792d | import baostock as bs
import tushare as ts
import pandas as pd
import datetime
import os
class stock_data:
def __init__(self, ticker = "000001"):
if ticker[0] == '6':
ticker = 'sh.' + ticker
else:
ticker = 'sz.' + ticker
self.ticker = ticker
self.today = da... |
10,605 | a13dbe2c9770da51096c44ff5fc639ce89c249b6 | """ handlers """
from .editor_handler import EditorHandler
from .site_handler import SiteHandler
from .dir_handler import DirHandler
from .mark_handler import MarkHandler
from .s3_browser import S3Browser
from .static_files import StaticFiles
from .access_control import LoginHandler, LogoutHandler
|
10,606 | a5283dae232a2c6a5ecf631295f2b3272865de2b | import sys
import requests
import pprint
import ast
from nltk.sentiment.vader import SentimentIntensityAnalyzer
def classify_all_comments_sentiment(input_file, output_file):
'''
calculates the sentiment of each comment in given input_file
'''
sia = SentimentIntensityAnalyzer()
file = open(in... |
10,607 | 8b47d49fa3357c8c29479100287a6b9ce91cccad | class APIException(Exception):
""" Base exception for all API errors """
code = 0
message = 'API unknown error'
def __init__(self, text=None):
if text:
Exception.__init__(self, text)
else:
Exception.__init__(self, self.message)
class APIWrongMethod(APIExceptio... |
10,608 | 2da49c0ef434087c82c8b639fd21d6e10698073a |
while True:
try:
num_cows, num_cars, num_show = list(map(int, input().split()))
total = num_cars + num_cows
if num_show >= num_cows:
p = 1
else:
p = (num_cars / total) * ( (num_cars - 1) / (total - 1 - num_show ) )
p += (num_cows / total) * (num_cars / (total - 1 - num_show))
... |
10,609 | f08d831233553f4e33a9dbf7bd4acadd68fe7dad |
#pathName = '/Volumes/Transcend/cattle/828/WA03_2016_1_1_16_23_37_348162' #For test
#826 H 105 120
#pathName = '/Volumes/WA03-1/WA03 2016 1/826/WA03_2016_1_19_8_44_35_907763'
#pathName = '/Volumes/WA03-1/WA03 2016 1/826/WA03_2016_1_19_8_48_3_445332'
#pathName = '/Volumes/WA03-1/WA03 2016 1/826/WA03_2016_1_19_8_49_... |
10,610 | b72ae3b7912650bebc8d01dc976a0d9eee25b514 | from turtle import Turtle
class Score(Turtle):
def __init__(self):
super().__init__()
self.penup()
self.points = 0
self.color("white")
self.hideturtle()
def score_board(self):
self.clear()
self.setpos(-350,350)
self.write(f"Score: {self.points}"... |
10,611 | 3f0d04205a659fbc8f06b521f3c4b892331b18e6 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 8 12:15:25 2017
@author: IACJ
"""
import matplotlib.pyplot as plt
import numpy as np
from dtw import dtw
np.set_printoptions(threshold=999) #全部输出
x = np.array([0, 0, 1, 1, 2, 4, 2, 1, 2, 0]).reshape(-1, 1)
y = np.array([1, 1, 1, 2, 2, 2, 2, 3, 2, 0]).reshape(-1, 1)... |
10,612 | 13a4e4359707f7773dbca4ff38ec178dadcee912 | # Generated by Django 2.0.5 on 2018-05-14 05:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('crafting', '0002_auto_20180513_2301'),
]
operations = [
migrations.AddField(
model_name='machin... |
10,613 | a435bf611eb04f1c22abce52e5831dd46350a9eb | import json
import jsonpath
import ast
import re
from utils.requests_utils import RequestsUtils
#
# str1 = '{"grant_type":"client_credential","appid":"wx55614004f367f8ca","secret":"65515b46dd758dfdb09420bb7db2c67f"}'
# step_list = [{'测试用例编号': 'api_case_02', '测试用例名称': '创建标签接口测试', '用例执行': '是', '用例步骤': 'step_01', '接口名称': ... |
10,614 | c0723c96c3b404df7e5038a98626d5e5e1d07644 | import time
t1=time.time()
print("Hellooo")
print("India")
print("Corona")
for i in range(11):
print(i)
t2=time.time()
print(t2-t1)
|
10,615 | 47332c2ef2ed37c79fb319768763c58fc210a8d9 | import json
from pathlib import Path
import pandas as pd
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
from .augmentation import *
NB_CLASSES = 128
def default_loader(path):
return Image.open(path).convert('RGB')
class MyDataset(Dataset):
def __init__(self, txt... |
10,616 | 70013751ff1a8a6ed5dcb81a9546ec2abd9a011c | # Adds a csv file to the data directory of a specified dataset
# with relevance tags using that data directory's movie IDs
import pandas as pd
import numpy as np
from collections import defaultdict
import sys
try:
sys.argv[1]
except IndexError:
dim = 10
else:
dim = int(sys.argv[1])
try:
sys.argv[2]
e... |
10,617 | e5ecf5c8bcbe654d1ec03b811d8718f0ca8fb635 | #!/usr/bin/env python
import sys
import os
from os import path
def chase_link(file_path, indent=2):
indent_prefix = indent * ' '
print("{0}{1}".format(indent_prefix, file_path))
if path.islink(file_path):
target = os.readlink(file_path)
if not path.isabs(target):
base_dir = pa... |
10,618 | 55d9da172c02490df4d5f374b62da39ab9fd620f | import utils
from pylab import *
from random import shuffle
import matplotlib.pyplot as plt
zero_list = [0]*3000
one_list = [1]*1000
counts = zero_list + one_list
shuffle(counts)
noises = []
epsilon = 0.3
for i in range(4000):
noises.append(counts[i]+utils.laplace(1/epsilon))
myHist = plt.hist(noises, 10000, norme... |
10,619 | c5bb0320c55bc5eb1a6c178feda3a40985a457b6 | # coding: utf-8
"""
Bitbucket API
Code against the Bitbucket API to automate simple tasks, embed Bitbucket data into your own site, build mobile or desktop apps, or even add custom UI add-ons into Bitbucket itself using the Connect framework. # noqa: E501
The version of the OpenAPI document: 2.0
Con... |
10,620 | 6abd95931715d393333fa3d341f5a342e13eb248 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 27 10:40:20 2016
@author: Swan
"""
import pandas as pd
import datetime
###
### Step 1.0 Create URLS dataframe
###
#clean up urls
urls = pd.read_csv('url.csv', index_col = 0)
urls.x = urls.x.str.upper()
urls.x = urls.x.str.replace('HTTP://WWW.BEA.GOV/HISTDATA/RELEASES... |
10,621 | faf4ce22e90c5f69cf647ef2506775b904faa04c | #!/usr/bin/env python3
import math
# stack overflow for getting smallest multiple of all cycles
# https://stackoverflow.com/questions/51716916/built-in-module-to-calculate-least-common-multiple
def lcm(a, b):
return abs(a*b) // math.gcd(a, b)
with open('input.txt') as fp:
lines = fp.readlines()
moonpos = [... |
10,622 | f8d28146dd6c4c8950cc81c46eb00d43b12ac51a | my_list = [1 , 2.5, 'a']
print(my_list)
length = len(my_list)
print("The length of the list is: {}".format(length))
print("The contents of the list is:")
for item in my_list:
print(item)
hello_list = list('hello')
print(hello_list)
my_sentence = "I am a lumberjack and I am OK. I sleep all night and I work all !"
p... |
10,623 | 8e6f3cace93d0a62bb51387ba97435bfaf0d7f1a | import numpy as np
from alexnet import alexnet2, alexnet, customnet
WIDTH = 80
HEIGHT = 60
LR = 1e-3
EPOCHS = 8
MODELNAME = 'surfrider-{}-{}-{}-epochs'.format(LR, 'customnet', EPOCHS)
model = customnet(WIDTH, HEIGHT, LR)
trainData = np.load('training_data_v2.npy', allow_pickle=True)
train = trainData[:-500]
test = t... |
10,624 | 74fefd8d5cadc42ee96dcdc22b0e512a81d630a8 | import math
def sumaDivisoresPropios(numero):
n = numero
p =2
sum = 1
while pow(p, 2) <= n and n >1:
if not n%p:
j = pow(p,2)
n /= p
while not n%p:
j *= p
n /= p
sum *= (j-1)
sum /= (p-1)
if p == ... |
10,625 | bd12c3d9b3f3bc391bc17d386826ec8e38cb7d0d | # /////////////////////////////////////////////////////////////////////
#
# ocpdemo.py :
# In an endless loop, repeating every 5(?) seconds...
# For each port,
# Show fixed identifying keys, then scrolling other keys
#
# Just to show that we can, and give an idea of how much data is available
#
# Copy... |
10,626 | 8fe9a6f9f410b90c67e68240eec529556f76365b |
# coding: utf-8
# In[1]:
# import required Libraries
import numpy as np
import pandas as pd
#import seaborn as sns
import matplotlib.pyplot as plt
#sns.set(context="paper", font="monospace")
get_ipython().magic('matplotlib inline')
# In[2]:
#Data load
DF = pd.read_csv('http://localhost:8888/files/OneNote%20Notebo... |
10,627 | f62d0f648716e6fa814711a54825fb3562e41bb5 | # Generated by Django 3.2.5 on 2021-08-09 14:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sub_part', '0012_add_categories_database_status'),
]
operations = [
migrations.CreateModel(
name='reg2',
fields=[
... |
10,628 | 9f00cb67df731c5ea21e39f7a030c55dd2c4b831 | class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
res = 0
temp = 0
for i in s:
if i == ' ':
if res != 0:
temp = res
res = 0
else:
res += 1... |
10,629 | f41743d82727b23bc4d8a7faa27a7e7687286ca2 | # eventpy library
# Copyright (C) 2020 Wang Qi (wqking)
# Github: https://github.com/wqking/eventpy
# 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.... |
10,630 | 49a944b672a7210267bc6480a9f5e3f6466d0f4f | #!/usr/bin/env python
# coding: utf-8
# ___
#
# <a href='http://www.pieriandata.com'><img src='../Pierian_Data_Logo.png'/></a>
# ___
# <center><em>Copyright Pierian Data</em></center>
# <center><em>For more information, visit us at <a href='http://www.pieriandata.com'>www.pieriandata.com</a></em></center>
# # NumPy ... |
10,631 | 2c174c100656e0fe78a7ee9f61bdd032da221cde | n,k = map(int, input().split())
# ans = 0
# for right in range(k+1, n+1):
# for left in range(max(1,k), right):
# while left <= n:
# ans+=1
# left+=right
# print(ans, flush=True)
# TLE
ans = 0
for b in range(1,n+1):
ans += (n//b)*max(0,b-k) + max(n%b+1-k, 0)
if k==0:
... |
10,632 | f1ef92521dd62e7ce56efecab0ba6662a11d069a | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
import datetime
from django import template
from django.utils.safestring import mark_safe
from django.utils.html import conditional_... |
10,633 | a048718fc0da7a252e894eec2c93b2ed3ef7a343 | from django.contrib import admin
from .models import Employee, EmployeeAdmin
admin.site.register(Employee, EmployeeAdmin)
|
10,634 | 07691c5c28b381f1c0ff800089a6be048cf7ef8a | from django.test import TestCase
from per_ac.accounts_department.models import *
class CategoryTest(TestCase):
def setUp(self):
user = User.objects.create_user("test","test", "123")
user.is_staf = True
user.save()
prof = UserProfile(user=user)
prof.save()
self.cat = ... |
10,635 | 485e6df6d9e3795662613eb1882a9666cdb91a4e | #!/usr/bin/env python
from load import ROOT as R
import gna.constructors as C
constant = 1.2345
def make(nsources, ntargets):
sources=[C.Points([constant]) for i in range(nsources)]
targets=[R.DebugTransformation('debug_%02d'%i) for i in range(ntargets)]
return sources+targets
def check(*objs):
fo... |
10,636 | 10fdd97484c748b2fc95130fdcb87ec8eacdcc33 | from testit_pytest.plugin_manager import TestITPluginManager
from pluggy import HookimplMarker
hookimpl = HookimplMarker("testit")
__all__ = [
'TestITPluginManager',
'hookimpl'
]
|
10,637 | 24a54eaa290bd870541e9db587ce66e382f946cb | from selenium import webdriver
import unittest
import time
class TESTS(unittest.TestCase):
def test_1(self):
link = "http://suninjuly.github.io/registration1.html"
browser = webdriver.Chrome()
browser.get(link)
# Ваш код, который заполняет обязательные поля
input1 = browse... |
10,638 | 9196e0e29f5626b7af2e5870408d76f930e19aec | import torch
import pandas as pd
if __name__ == '__main__':
# tem = pd.DataFrame({'source': [0, 1, 2, 3], 'target': [1, 2, 3, 0]})
# node_dataframe = pd.DataFrame({'node': [0, 1, 2]})
# tem = tem[tem.apply(lambda x: (x['source'] in node_dataframe['node']) and (x['target'] in node_dataframe['node']),
#... |
10,639 | 6e799e03a075b7f186be80d21baa56083d7a558c | import webapp2
import jinja2
from google.appengine.api import users
from google.appengine.ext import ndb
import os
from myuser import MyUser
from ReviewModel import ReviewModel
JINJA_ENVIRONMENT= jinja2.Environment(
loader = jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.... |
10,640 | c30accf76df68a24e7331739218c78ce34b29be3 | # Generated by Django 2.2.1 on 2019-11-01 15:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('book_issuer', '0009_auto_20191101_2032'),
]
operations = [
migrations.RenameField(
model_name='student',
old_name='c... |
10,641 | 33efa2ac8fc3f12bef9b0c188f4889bcc3b38383 | from multipoll.models.approvalpoll import ApprovalPoll, FullApprovalVote, PartialApprovalVote
from multipoll.models.multipoll import FullMultiVote, MultiPoll, PartialMultiVote
from multipoll.models.pollbase import FullVoteBase, PartialVoteBase, PollBase
from multipoll.models.user import User
__all__ = ["ApprovalPoll",... |
10,642 | 94013cec03b960c3698f8f994dc6523a99b00ad7 | __package__ = "translate.learning.models.cnn"
__all__ = ["cnntranslate"]
__author__ = "Hassan S. Shavarani"
__copyright__ = "Copyright 2018, SFUTranslate Project"
__credits__ = ["Hassan S. Shavarani"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Hassan S. Shavarani"
__email__ = "sshavara@sfu.ca"
__status__... |
10,643 | 90aebf98ea1e46dbd5f22bf7c1c53eb4ddf72a3d | import tkinter
from collections import namedtuple
from tkinter import *
from tkinter.constants import *
from tkinter import ttk
from tkinter.ttk import *
import requests
import time
import datetime
import gui
import concurrent.futures
import logging
import json
import asyncio
logger = logging.getLogge... |
10,644 | 7e5abb5860717555ced163c62fa3cc50f8add39d | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='IngredientFlavorCompound',
fields=[
... |
10,645 | 2cabb1c2e05371835c97e77447e5afe9a1431a5f | # importing libraries
import matplotlib.pyplot as plt
import pandas as pd
import pickle
import numpy as np
import os
import glob
from keras.applications.resnet50 import ResNet50
from keras.optimizers import Adam
from keras.layers import Dense, Flatten,Input, Convolution2D, Dropout, LSTM, TimeDistributed, Embed... |
10,646 | 6d34a90a4ae3373e17f0309229597a5145264cb7 | # while loop
# print("hello world") 10 times
########################################################################
# i = 1
# while i <= 10:
# print("hello world")
# i +=1
########### Example:1 For loop same program #######################################
for i in range(10): ### range is 0 to 9 here... |
10,647 | 5d85454e89aed0c096b8e007e645fcbb59b95b12 | import os
import sys
from google.cloud import storage
from setup.init_client import create_client
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = './service_account.json'
def create_bucket(bucket_name):
"""create new bucket in specific location with storage class"""
# initialize client & get bucke... |
10,648 | bf0b968d16da6dd9db56d3381d2a07172a2f0238 | #comparing isoforms between single tissue analyses
#this will be easier that before as all of the single tissue analyses have the combined sexes isoform ID added to them, so I can just compare IDs rather than compare sequences, locations, etc.
#will use exon counts file for input for single tissues to remove any conver... |
10,649 | 5856239347d49d4b6d29de05118d6bd5637d040a | # Generated by Django 3.0.9 on 2020-08-07 12:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cases', '0003_auto_20200807_1021'),
]
operations = [
migrations.AlterField(
model_name='contact',
name='contact',
... |
10,650 | 236e9fa45550b8339bcbe7b10fee8b222abd8f62 | import pytest
from ipxeboot import main
from webtest import TestApp as WebTestApp
class Test_Root_IPXE_Agent:
def setup(self):
app = main()
self.testapp = WebTestApp(app)
def ipxeget(self, *args, **kwargs):
return self.testapp.get(
*args,
headers={'User-Agent'... |
10,651 | b649ef8e1c0685bb890cd47462cca13790127035 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 23 11:09:32 2021
@author: Administrator
"""
import utils
import numpy as np
import pandas as pd
import ot
import partial_gw as pgw
import matplotlib.pyplot as plt
n_unl = 800
n_pos = 400
nb_reps = 10
nb_dummies = 10
"""
prior = 0.518
perfs_mush... |
10,652 | 0aa6617efd3c64e894bb5f9d4812640a8191b5cb | from ddblog.celery import app
from tools.sms import YuoknTongXin
@app.task
def send_sms(phone,code):
aid = '8aaf0708773733a80177433d7c750705'
atoken = 'e0718509c4f942a29bfb9be971afedea'
appid = '8aaf0708773733a80177433d7d3f070b'
tid = '1'
# 1 创建云通信对象
x = YuoknTongXin(aid, atoken, appid, tid)
... |
10,653 | 75b6e93d055471cc6c2edb42021b1c7e0f279618 | ### Hacked together by Johnson Thomas
### Annotation UI created in Streamlit
### Can be used for binary or multilabel annotation
### Importing libraries
from streamlit.hashing import _CodeHasher
from streamlit.report_thread import get_report_ctx
from streamlit.server.server import Server
import streamlit a... |
10,654 | 65587455c046f7db6f0d61b7cd48290829ea48b8 | # -*- coding: utf-8 -*-
"""
# https://mp.weixin.qq.com/s/wlqvAvKvqPCclZm8AvkUSw
# hppts://github.com/miguelgrinberg/merry
pip3 install merry
"""
from merry import Merry
import requests
from requests import ConnectTimeout
# version 1.0
def process_v1_0(num1, num2, file):
result = num1 / num2
... |
10,655 | cfbc51929b383ff2de90e28c23a3e996ba59aac2 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import pickle
import os
import sys
import unittest
import networkx as nx
import numpy as np
from topologic.embedding import laplacian_embedding
class TestLaplacianSpectralEmbedding(unittest.TestCase):
def test_laplacian_embedding(self):
... |
10,656 | ffdf46791741184ea1adf52e8e404eeeaabef429 | from .provider import XingProvider as XingProvider
from allauth.socialaccount.providers.oauth.client import OAuth as OAuth
from allauth.socialaccount.providers.oauth.views import OAuthAdapter as OAuthAdapter, OAuthCallbackView as OAuthCallbackView, OAuthLoginView as OAuthLoginView
from typing import Any
class XingAPI(... |
10,657 | bcc4ab4af84f18df1a86a871391deba0118b5c1c | import math
import torch.nn as nn
__all__ = [
'ConvFC', 'ConvFCSimple'
]
class ConvFCBase(nn.Module):
def __init__(self, num_classes):
super(ConvFCBase, self).__init__()
self.conv_part = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=5, padding=2),
nn.ReLU(True),
... |
10,658 | 844a532c614176be173f7cbe75a187ee359b4c27 | import argparse
import numpy as np
from os.path import join
from train.models import DreyeveNet
from train.config import dreyeve_test_seq
from train.config import frames_per_seq
from train.config import h
from train.config import w
from tqdm import tqdm
from metrics.metrics import kld_numeric
from computer_vision_utils... |
10,659 | 0f2bbf29caa0f76c7be97df4b9aa039691515b35 | from .sopt_gateway import SoptGateway
|
10,660 | 11370b03c3ae80aade9d476511a4cd472af95d1a | #!/usr/bin/env python
"""
This script is used to parse the log in CFS sever
Example:
import cfsServerLogParser
missLogData = cfsServerLogParser.parseRatingMissLogFile("logfile")
print("Missing log file: " + missLogData["file"])
print("Missing log line count: " + str(missLogData["lineCount"]))... |
10,661 | 11b8b712d7612e17c6b39b0f26895bfc9fdedb9b | import numpy as np
import matplotlib.pyplot as plt
from decimal import *
plt.rcParams.update({'font.size': 22})
q2x = np.load('q2x.npy')
q2y = np.load('q2y.npy')
N = len(q2x)
x_poly = np.column_stack([np.ones((N,1)), q2x])
#q2(d)i
def unweighted_linear_regression(x_poly, y):
xTx = np.dot(np.transpose(x_poly), x_p... |
10,662 | 7af2daf51857ef17eec6362e4920fc4e25ea5fbf | import numpy as np
from scipy.linalg import lstsq
#temperature data
fahrenheit = np.array([5,14,23,32,41,50])
celsius = np.array([-15,-10,-5,0,5,10])
M = fahrenheit[:, np.newaxis]**[0, 1]
model, _, _, _ = lstsq(M,celsius)
print "Intercept =", model[0]
print "fahrenheit =", model[1]
|
10,663 | 7f9193d0534fb3a6119fb779ee06bdf27d91b222 | # -*- coding: utf-8 -*-
#---------------------------------------------------------------------------
# Copyright 2020 VMware, Inc. All rights reserved.
# AUTO GENERATED FILE -- DO NOT MODIFY!
#
# vAPI stub file for package com.vmware.nsx_policy.infra.
#-----------------------------------------------------------------... |
10,664 | 9e9d6e1407d7c2d3afa64cec0b484c4abcb6b7fe | #!/usr/bin/env python
#The line above tells Linux that this file is a Python script,
#and that the OS should use the Python interpreter in /usr/bin/env
#to run it. Don't forget to use "chmod +x [filename]" to make
#this script executable.
#Import the dependencies as described in example_pub.py
import rospy
from sensor... |
10,665 | f42169a8c1aa3be3171bf363762a7ce32c0bc935 | """Matmul layer test cases"""
from typing import (
List,
Callable
)
import sys
import copy
import logging
import cProfile
import numpy as np
from common.constant import (
TYPE_FLOAT,
TYPE_LABEL,
)
from common.function import (
softmax,
relu,
transform_X_T,
softmax_cross_entropy_log_loss,... |
10,666 | b100b28f2dbe2a7e638a9388d604311c28fc631f | import RPi.GPIO as GPIO
import subprocess
while True:
GPIO.cleanup()
subprocess.Popen("simpletest.py", shell=True)
# sensor = Adafruit_DHT.DHT11
# pin = 4
# ldr = LightSensor(17)
#
## while True:
#
#
# light = ldr.value
# print('Light Source={0:0.1f}%'.format(light*100))
# ... |
10,667 | bf50a4a64cc0a4cdabdcbd06be969a0da2a62b9f | # Generated by Django 2.1.15 on 2021-06-13 15:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0010_auto_20210612_2333'),
]
operations = [
migrations.AlterField(
model_name='author',
name='avatar',
... |
10,668 | 42607232f53547989eb434dd68eb844d3bb90ff1 | '''Problem statement¶
Given a string consisting of uppercase and lowercase ASCII
characters, write a function, case_sort, that sorts uppercase
and lowercase letters separately, such that if the $i$th place
in the original string had an uppercase character then it should
not have a lowercase character after bei... |
10,669 | 267bb550159efc9138f20430a5e6ac474479b5e8 | from networkx import Graph
from networkx import degree_centrality, closeness_centrality, eigenvector_centrality, betweenness_centrality
from networkx import find_cliques
import logging
import conf
import datetime
import numpy as np
import networkx as nx
from myexceptions import network_big
from google.appengine.ext im... |
10,670 | d4326d33136843481c5afef7195c914b25a51e53 | #!/usr/bin/python
#import ConfigParser
import icalendar,sys,os,datetime
import stripe
import pytz
import urllib
import json
from dateutil import tz
from ..templateCommon import *
def utctolocal(dt,endofdate=False):
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')
if isinstance(dt,datetime.... |
10,671 | a9fd036dbb9a431bf8c9105efac748799b818074 | class ConfigException(Exception): pass
|
10,672 | 4c68c08c86b78dde08254fadee83bc2204e2e282 | # -*- coding: utf8 -*-
#사람 객체 생성
class person():
#객체 생성과 동시에 나의 돈
def __init__(self):
self.my_money_dict = {5000 : 2 , 1000 : 1, 500 : 2 , 100 : 8}
class machine():
#객체 생성과 동시에 생기는 리스트
def __init__(self):
self.products_dict = {
'vita500' : {'price' : 500, 'numb... |
10,673 | 13dad9c6228912bca3a1edad3541a34cb0ac662f | # ngrams.py
# A program that tallies n-gram counts in given text files
# Eric Alexander
# CS 111
def getOneGrams(filename):
''' Function takes in a given text filename and counts one-grams in the file '''
oneGramCounts = {}
with open(filename, 'r') as f:
for line in f:
# C... |
10,674 | 57091a09fc93aa997c989747fef01adbdc10fd0f | import csv
import pprint
import matplotlib.pyplot as plt
import numpy as np
def analyzeSolution(fname):
#Dataformat: [[total, proper],[...]] index is difficulty level -1
data = [[[0,0] for givens in range(81)] for difficulty in range(4)]
with open(fname) as f:
c = csv.DictReader(f)
for r i... |
10,675 | 427223eb56f9fa066a85bb0de142eede918828d6 | import pickle
import numpy as np
ds_ans_dict = pickle.load(open("ds_ans_dict.dat","rb"))
ds_cluster_centers = pickle.load(open("ds_ans_cluster_centers.dat","rb"))
#ds_cluster_centers_indices = pickle.load(open("ds_cluster_centers_indices.dat","rb"))
num_clusters = ds_cluster_centers.shape
print("cluster_centers shape... |
10,676 | 1d0e8ceaae51a359def93f0d54a35054242d84fd | import pandas as pd
from sklearn import model_selection
from transformers import AdamW, get_linear_schedule_with_warmup
from torch.utils.data import DataLoader
from services.text_similarity.application.ai.model import BERTClassifier
from services.text_similarity.application.ai.training.src import utils
from services.t... |
10,677 | 118b36e79bf1f9e5f9fa9c548099ed0c423d77b1 | from prettytable import PrettyTable
XL, XU, x = .5, 2.5, 0
Xr = (XL + XU)/2
PE = abs((XU-XL)/(XU+XL)) * 100
def func(y):
return 1-(400/(9.81*(3*y+(y**2)/2)**3))*(3+y)
t = PrettyTable(["Iteration", "Xl", "XU", "F(XL)", "F(XU)", "F(XR)*F(XU)", "XR", "F(XR)", "PE"])
t.add_row([x, "%.4f" % XL, "%.4f" % XU, "%.4f"... |
10,678 | 11e6ebdefc55ef7ce723fd85efd857b2102c26e9 | from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='logomaker',
version='0.8.0',
description='Package for making Sequence Logos',
long_description=readme(),
classifiers=[
'Development Status :: 3 - Alpha',
'License ::... |
10,679 | b835e4c4512c10a0ca92ec1c232b370f74c60794 | n = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
##print(P)
#print(Q)
import itertools
X = []
for p in itertools.permutations(range(1, n+1)):
X.append(p)
#print(X)
for i in range(len(X)):
if P == X[i]:
a = i
break
for i in range(len(X)):
if Q == X[i]... |
10,680 | 30f3f8501096c8085ab41eee5d190ed6c3c238e1 | from flask import Blueprint, render_template, redirect, url_for, abort
from nsweb.models.analyses import (Analysis, AnalysisSet, TopicAnalysis,
TermAnalysis)
import json
import re
from flask_user import login_required, current_user
from nsweb.initializers import settings
from nsweb.co... |
10,681 | 00d41d0d2b9d48418a69bcbe63a36a621ca3d7bb | coords = [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
for loc in coords:
for coord in loc:
print(coord)
|
10,682 | 70150cf97cf8769c6d8eec559057afe7734f24b8 | """Blog Model."""
from flask_blog import db
class Blog(db.Model):
"""Blog Model Class."""
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
admin = db.Column(db.Integer, db.ForeignKey('author.id'))
def __init__(self, name, admin):
"""Initialize class object."""... |
10,683 | c3cbff41c932d247125efc896dbf2c90a6cc1f46 | from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
import settings
import circuits.views
import os
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'quantummechanic.views.home', name='home'),
# url(r'^blog/', include('blog.urls... |
10,684 | a0b0749cc43508d6bf17971f2ef67d178cfb2c36 | from .dict_menu import DictMenu
from .dict_table import DictTable
from .dict_dialog import DictDialog
from .dict_tree import DictTree
|
10,685 | 14f9a5f60836c4756c0857006e0637c840b58416 | vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
def decode(tone):
s = tone.lower()
pin = ''
for ch in s:
if ch in consonants:
idx = consonants.find(ch)
elif ch in vowels:
idx2 = vowels.find(ch)
line = 'pin {0} idx {1} idx2 {2}'.format(pin, idx, idx2)... |
10,686 | ab2747edf5ebe27a8ae0421704f9227ffce1a3bb | import numpy as np
import pandas as pd
import scipy.io as scio
import h5py
import sys
import datetime
open_file = sys.argv[1]
data_file = sys.argv[2]
save_file = sys.argv[3]
dataset_len = len(data_file.split('/')[-1])
dir_path = data_file[:-dataset_len]
cell_file = dir_path + 'cell_filtered.txt'
gene_file = dir_path ... |
10,687 | 606afbbe6ad09efeb45a098b83b867a3dc261a3d | import argparse
import sys
import os
import time
import math
import tensorflow as tf
NUM_CLASSES = 10
# 28x28
IMAGE_SIZE = 28
IMAGE_PIXELS = IMAGE_SIZE * IMAGE_SIZE
# function for creating Artificial neural network
def inference(images, hidden_units1,hidden_units2):
with tf.name_scope('H_layer_1'):
... |
10,688 | 40765a4c52795050ef81ebbed08c5d936e7957a7 | import unittest
import pytest
from os import environ
environ['CI'] = environ.get('CI') or 'true'
import rl
class DQNTest(unittest.TestCase):
def test_run_gym_tour(self):
problem = 'CartPole-v0'
param = {'e_anneal_steps': 10000,
'learning_rate': 0.01,
'n_epoch': 1... |
10,689 | 8b007fee129c90a6a7633853f66a1a08008ebb96 | import unittest
from unittest.mock import Mock, patch
from mstrio.microstrategy import Connection
import json
from nose.tools import assert_true
class TestMicrostrategy(unittest.TestCase):
@patch('mstrio.api.projects.projects', autospec=True)
@patch('mstrio.api.authentication.login', autospec=True)
def se... |
10,690 | 0541992af70daa6c3bfa01b0fb29e6a3e8b37cc8 | from keras.models import Model
from keras.optimizers import Adam
from keras.layers import *
def build_model(vectorizer, embed_dim, num_layers, recurrent_dim,
lr, dropout, num_classes=2):
input_ = Input(shape=(vectorizer.max_len,), dtype='int32')
m = Embedding(input_dim=len(vectorizer.syll... |
10,691 | c9cc4c0441410617309e45c5cbda271c10322c34 | import json
import os
from pathlib import Path
from shutil import rmtree
from subprocess import DEVNULL, PIPE, CalledProcessError, run # nosec
from tempfile import TemporaryDirectory
from typing import Any, Dict, Optional, Set
import click
import typer
from cookiecutter.generate import generate_files
from git import ... |
10,692 | 09cf5a787adbc13d732ee4edf840668a49668449 | '''
@Description:
@Author: wjx
@Date: 2018-09-23 17:06:51
@LastEditors: wjx
@LastEditTime: 2018-11-20 16:03:54
'''
# coding=utf-8
import pytest
from workspace.pages.login_page import LoginPage
from workspace.config.running_config import get_driver
class TestLoginCSC():
"""
登录CSC的测试用例
"""
@pyte... |
10,693 | 23278451016ae499af2608658c84d5dbe40db3fd | #!/usr/bin/env python
# send trace backs to log file
from asterisk import agitb
agitb.enable(display = False, logdir = '/var/log/asterisk/')
# import our libs
import sys
import asterisk.agi
import soundcloud
import random
# initilize the agi stuff, and update the trackback to use our agi handle
agi = asterisk.agi.... |
10,694 | 467c7e3749e31744e21071c70029ada028734501 | from django.views.generic import FormView
from api.admin.apis import IonicApi
from api.admin.forms import NotificationsIonicForm
class NotificationsIonic(FormView):
SUPPORTED_PAYLOAD_KEYS = []
template_name = 'admin/notifications/ionic.html'
form_class = NotificationsIonicForm
def form_valid(self, ... |
10,695 | 97d08a9e53b281969582916c1c33c57194a94f59 | import os
os.system('python exFefe.py')
os.system('clear')
os.system('python newMonth.py') |
10,696 | c8b7f44d0e2e6db6adce46abc5e7c72dbb156d63 | import sys, requests, json, datetime, argparse
from queryAPI import getSearch, getUTCtime
from FormatForDB import formatForDB
parser = argparse.ArgumentParser()
parser.add_argument("username")
parser.add_argument("password")
parser.add_argument("accountFqdn")
parser.add_argument("query")
parser.add_argument("outputFil... |
10,697 | 342a8597fe1161c488116661511097f165c00d5b | import xbmc, xbmcgui
import pigpio
import time
from os import system
class TimerDialogCallback:
def __init__(self, pi, gpio, timeout, text, callback):
self.pi = pi
self.gpio = gpio
self.timeout = timeout
self.text = text
self.callback = callback
self._last_tick = 0
pi.set_mode(self.gpio, pigpio.INPUT)
... |
10,698 | 1a5b99de232773aa8cd8fb9e2984c3a3d99efade | import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from scipy.interpolate import griddata
import h5py
plt.style.use('seaborn-paper')
class sim_avg:
def __init__(self,csv_filename,save_directory):
self.csv_filename=csv_filename
self.save_directory=save... |
10,699 | b64293706b7a460b67aeb31b1486f79fb72d8a2f | '''
网络测速模块
'''
import psutil
import time
def speed_test():
time.clock()
net_io = psutil.net_io_counters(pernic=True)
s1, s2 = 0, 0
for key in net_io.keys():
s1 += net_io[key].bytes_recv
time.sleep(1)
net_io = psutil.net_io_counters(pernic=True)
for key in net_io.keys():
s2 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.