index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
996,200 | a201be721c3d8897518e621c3bd3db3a2b762a8c | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from .models import Gallery, CONFIG
from .admin import PhotoInline
class GalleryPlugin(CMSPluginBase):
"""
... |
996,201 | 73de3f8c74c25463c3bb35cb493a7d98a6174feb |
'''
print('hello word')
#变量
message="hello python"
print(message)
message="hello python2"
print(message)
#修改字符串大小写
message='adfB'
print(message.title())
print(message.upper())
print(message.lower())
#通过\t 添加空白
print("a\tpython")
#通过\n换行
print("语言包含:\nC#\nPython\nJava")
print("Languages:\n\tC#\n\tPython\n\tJava")... |
996,202 | 42b64e510cb52daf1295dbbe023c925cb5f858ea | s = 'madam'
flag = True
j = -1
size = len(s)
for i in range(size):
if s[i] != s[j]:
flag = False
break
else:
j -= 1
if flag:
print('Palindrome')
else:
print('Not palindrome')
|
996,203 | fd170bb0968d71439ef4f11c0a200892cf83fe41 | import warnings
warnings.filterwarnings('ignore')
import sys
import os
from astroquery.skyview import SkyView
from astropy.coordinates import SkyCoord
import astropy.units as u
import aplpy
import matplotlib.pyplot as plt
from astropy.io import fits
import astropy
def coords_from_name(field_name):
"""Get ra, dec c... |
996,204 | 562939e275d106ec8186af3406c98443016b92f1 | from cv2 import imread
from cv2 import imshow
from cv2 import VideoWriter
from cv2 import waitKey
from cv2 import destroyAllWindows
from cv2 import VideoWriter_fourcc
frame = imread("tests/hello.png")
print (frame)
width, height, layer = frame.shape
out = VideoWriter("tests/out.avi", VideoWriter_fourcc(*'DIVX'), 15.0... |
996,205 | c34462d31a31287e3f72d222d739a5949cf69fa2 | # ch20_5.py
import requests, bs4, json
from pprint import pprint
url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=25.0329694,121.5654177&radius=3500&type=school&key=YOUR_API_KEY'
gmap = requests.get(url)
gsoup = bs4.BeautifulSoup(gmap.text, 'lxml')
g_info = json.loads(gsoup.text)
schools = ... |
996,206 | ecf276e9ad6017cd6d559f557c179db352695a8b | from time import sleep
while True:
try:
a=int(input('Qual o valor deseja sacar?\n'))
print(f'''Serão:
{a//50} notas de 50;
{a%50//20} nota(s) de 20 reais;
{a%50%20//10} nota(s) de 10 reais;
{a%50%20%10//5} nota(s) de 5 reais;
{a%50%20%10%5//1} nota(... |
996,207 | 10572a58c8007500dd34586e2c0ea48c9107f611 | import printinbetweenPrimeNumbers_m_less_than
def test_two_even_numbers():
#rearrange
m = 8
n = 10
excepted = "There is no Prime Numbers exsist"
#act
actual = printinbetweenPrimeNumbers_m_less_than.inbetweenPrimeNumbers(m,n)
#assert
assert excepted == actual
def test_one_and_two():
... |
996,208 | 35e3e8ce9f1013bde5217de5f487c098e9f089a8 | """Pretraining on GPUs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, sys
os.environ['CUDA_VISIBLE_DEVICES'] = '3'
import math
import json
import time
import numpy as np
from absl import flags
import absl.logging as _logging
import tensorf... |
996,209 | f4ffa0d46f866a650672e7ba23f9d4a57dd846da | from __future__ import unicode_literals
from django.utils import timezone
from datetime import datetime
from django.db import transaction
from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin, BaseUserManager)
from django.db import models
import pytz
utc=pytz.UTC
# timezone.localtime(timezone.now... |
996,210 | 84b416028543a1586fe8cd4fc3b22562da0e1b17 | from .rfc3414_key_derivation import snmpv3_key_from_password, derive_intermediate_key, localize_intermediate_key
__all__ = [snmpv3_key_from_password, derive_intermediate_key, localize_intermediate_key]
|
996,211 | a18266f1853e36443d85ac1b4e286eb1fb07b53a | from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import TemplateView
from .views import *
urlpatterns = [
url(r'^register$', User_Register.as_view(), name='register'),
url(r'^login$', User_Login.as_view(), name='login'),
url(r'^logout/$', user_logout, nam... |
996,212 | 0fc67cace663793a6f823e771cbcdea5d770980e | """
Quantitative MRI
=======================================
This example shows how to build quantitative maps of R1 and R2* and semi-quantitative
PD from a MP2RAGEME dataset by performing the following steps:
1. Download a downsampled MP2RAGEME dataset using
:func:`nighres.data.download_MP2RAGEME_testdata` [1]_... |
996,213 | 16775618c9a7f80a355a1293528fed7541b4b81a | #
# Solved problems in Geostatistics
#
# ------------------------------------------------
# Script for lesson 4.1
# "Impact of the central limit theorem"
# ------------------------------------------------
from numpy import *
from geo import *
from matplotlib import *
from scipy import *
from pylab import *... |
996,214 | ef4953bc2e368c188a200bb41b78b905460b9ef9 | Name = 'FlipImageDataAxii'
Label = 'Flip ImageData Axii'
FilterCategory = 'CSM Geophysics Filters'
Help = 'This filter will flip ImageData on any of the three cartesian axii. A checkbox is provided for each axis on which you may desire to flip the data.'
NumberOfInputs = 1
InputDataType = 'vtkImageData'
OutputDataType... |
996,215 | cc03da02349f49ec8d295701660536697ec29bd7 | #Creating Node class for doubly linked list
class DNode():
def __init__(self, data, west=None, east=None):
self.data = data
self.west = west
self.east = east
class TrainRoute:
def __init__(self):
self.head = None
self.tail = None
#Record all the s... |
996,216 | 304628cfa8626e7c94693008cc2afdc741e29212 | import networkx as nx
import matplotlib.pyplot as plt
import random
'''
第三章 小世界理论
生成小世界模型 及 各种中心度量
'''
def generate_regular_network(n,k):
'''
'''
k = k // 2
edges = []
for i in range(20):
for j in range(i-k,i):
if j < 0: edges.append((i,j+n))
else: edges.append((i,j... |
996,217 | be28de2a7031628ec7544aad26715a0c8e154a4d | from django.shortcuts import render, redirect
from authy.forms import SignupForm, ChangePasswordForm
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.auth import update_session_auth_hash
# Create your views here.
def Signup(request):
if reques... |
996,218 | 9232c4e80fb3d084c74c1cef6eb5d49a5948a0e7 | import math
import numpy as np
from numpy.random import normal
from hyperspy.misc.utils import isiterable
from atomap.sublattice import Sublattice
from atomap.atom_position import Atom_Position
from atomap.atom_lattice import Atom_Lattice
class MakeTestData(object):
def __init__(self, image_x, image_y, sublattic... |
996,219 | ed53b4a0c85a80ed5d122dba00289cf2d69fd3f1 | class User:
def __init__(self, name, email):
self.accounts = []
self.name = name
self.email = email
def make_new_account(self, int_rate=0.02, balance=0):
new_acc = BankAccount(int_rate, balance)
self.accounts.append(new_acc)
def transfer_money(self, other_user, amount... |
996,220 | 1224a059c2f9125571564bf94870b250eb3203d6 | #!/usr/bin/python
#coding: utf-8
import httplib
import MySQLdb
import time
import sys
import copy
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import COMMASPACE,formatdate
import traceback
execfile("/mnt/xvdb/scripts/send_mail.py")
stock_dict = {}
yes_s... |
996,221 | 50ccc36af5f33cee9f87a92cf9b4aa49f53debf3 | def merge(A, B, size_a):
a_index = size_a - 1
b_index = len(B) - 1
merge_index = size_a + len(B) - 1
while a_index >= 0 and b_index >= 0:
if A[a_index] > B[b_index]:
A[merge_index] = A[a_index]
a_index -= 1
else:
A[merge_index] = B[b_index]
... |
996,222 | 568a21c14eb116b2dc77ba7202c26100e5493d1d | # ====================================
# @Project : Python_Demo
# @Author : fengjm
# @Time : 2018/1/24 10:55
# ====================================
# # 参数不固定的使用方式: *args 会把多传入的参数变成一个元组形式, **kwargs 会把多传入的参数变成一个dict形式
# def stu_register(name,age,*args): # *args 会把多传入的参数变成一个元组形式
# print(name,age,args)
#
# st... |
996,223 | 5f78c1b352f147fb11fdfb76c2051d44b3ca6389 | from tkinter import *
class TopMenu(object):
def __init__(self, frame):
self._root = frame
def main_func(self):
self.menuone = Menu( self._root )
self.filemenu = Menu( self.menuone, tearoff=False )
self.filemenu.add_command( label="查看最近三十天的数据",command=self.read30data)
se... |
996,224 | ec7156eb2ba38fcf5aa491a41b1f90577fe9e252 | #!/usr/bin/env python
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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 require... |
996,225 | 3b3907c37886bfd5016e39544896abcc6d184a21 | from django.db import models
from django.contrib.auth.models import User
from django.db.models.fields.related import ManyToManyField
class Tag(models.Model):
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.name
class Collection(models.Model):
name = models.Ch... |
996,226 | 5321cf1e4bdc9d0193d1ae208bb35918bbb29c98 | from nltk.classify.naivebayes import NaiveBayesClassifier
import os
def extract_features(sentence):
words = sentence.lower().split()
featureset = dict([('contains-word(%s)' % w, True) for w in words])
#featureset['contains-phrase(%s %s)'% (words[0],words[1])] = True
featureset['first-word(%s)'%words[0]] = True... |
996,227 | c525448eafcb8f3875e65d3932bf64b9f8d237b2 |
from xai.brain.wordbase.nouns._length import _LENGTH
#calss header
class _LENGTHS(_LENGTH, ):
def __init__(self,):
_LENGTH.__init__(self)
self.name = "LENGTHS"
self.specie = 'nouns'
self.basic = "length"
self.jsondata = {}
|
996,228 | 75a6754b4ec4b7cae099e164cb90a73e1bc62d1e | # -*- coding: utf-8 -*-
# @Time : 2019/7/25 10:47 AM
# @Author : nJcx
# @Email : njcx86@gmail.com
# @File : observer_pattern_dev.py
from test import get
from test import html_detail
header = {'content-type': 'application/json',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '
... |
996,229 | 8f8aefd1759ccc41b99e1155ba0058b413d1a9fb | #!/usr/bin/env python3
# Imports
from aoc import AdventOfCode
# Input Parse
puzzle = AdventOfCode(year=2019, day=2)
puzzle_input = puzzle.get_input()
# Actual Code
program = [int(code) for code in puzzle_input.split(",")]
program[1] = 12
program[2] = 2
idx = 0
while program[idx] != 99:
assert program[idx] in {1,... |
996,230 | 9ca2fdf26d6dd5f20cd4473725e94201a343bf18 | def show():
for i in range(1,1000):
print i,2,i,1
print 1998
show()
show()
|
996,231 | 4d9657011d3911c538613d51d56853f213d1b903 | """
Upload files to jupyter server location or to Python callback using jp_proxy.
"""
import jp_proxy_widget
from jp_proxy_widget import hex_codec
from IPython.display import display
from traitlets import Unicode, HasTraits
js_files = ["js/simple_upload_button.js"]
def _load_required_js(widget):
widget.load_js_f... |
996,232 | 7a51dd06843cab2bea4b69ce42114490493777f4 | import unittest
from .common import JinsiTestCase
class JinsiConditionals(JinsiTestCase):
def test_conditional_with_let(self):
doc = """\
::let:
a: 1
::when:
::get: a == 1
::then:
foo: one
::else:
... |
996,233 | 05d3a0eb8c18a3bcaaed724da769b007681a9519 | list=[1,2,3,4,5,6,7,8,9,"damien","ivy"]
print("the list of the objects")
print("\n After removing 5")
list.remove(5)
print(list)
print('\n After removing damien')
list.remove("damien")
print(list)
print("\n After removing ivy")
list.remove("ivy")
print(list)
print("\n After removing 9")
list.remove(9)
print(list)
list1... |
996,234 | 7db333ece83a9771cfd8aa3ecefeec24e3143d02 | import math
from typing import List, Tuple, Callable
Vector = List[float]
Matrix = List[List[float]]
def add(v: Vector, w: Vector) -> Vector:
"""Adds two vectors together using the principles of vector addition. Returns the sum
of both vectors. Checks if both vectors have the same length.
Arguments:
... |
996,235 | 2ccad80d6d79d15a707a36dbe95c835f017c7e21 | #!/usr/bin/python
# docco-husky cannot parse CoffeeScript block comments so we have to manually
# transform them to single line ones while preserving the tab space
import sys
from os import walk
def isComment(line):
return "###" in line
def main(argv):
path = argv[0]
for (path, dirs, files) in walk(path... |
996,236 | 178b3a0db35b7abcf7730ec1f1334969d5c8e4f0 | # Generated by Django 3.2.6 on 2021-08-29 14:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bloom', '0016_auto_20210827_1720'),
]
operations = [
migrations.AlterField(
model_name='company',
name='url',
... |
996,237 | 3ddc482976aa181df8c63e6fa1a606abd89132b7 | """empty message
Revision ID: d24d61a0c751
Revises: d7371b87f023
Create Date: 2021-11-08 09:52:07.690171
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd24d61a0c751'
down_revision = 'd7371b87f023'
branch_labels = None
depends_on = None
def upgrade():
# ... |
996,238 | 7cb6dfb4dde80445d8feaea50994a4a043af89ef | import flask
from flask import Flask, url_for, render_template, request, g
import model
from model import Movie
from model import User
from model import Rating
import movies
app = Flask(__name__)
@app.before_request
def before_request():
g.db = movies.connect()
@app.route("/")
def home():
return render_template("... |
996,239 | 90ec16899d3c32ec3fcfd50aa9fcf1126a0b4151 |
# -*- coding: utf-8 -*-
"""
ORIGINAL PROGRAM SOURCE CODE:
1: # coding=utf-8
2: __doc__ = "range builtin is invoked, but a class is used instead of an instance"
3:
4: if __name__ == '__main__':
5: # Call options
6: # (Integer) -> <built-in function range>
7: # (Overloads__trunc__) -> <built-in function ra... |
996,240 | 62a3efe51366effbf3468b77c580d7fe52e91d6f | m = len(matrix)
n = len(matrix[0])
zombies = deque([])
for i in range(m):
for j in range(n):
if matrix[i][j] == 1:
zombies.append((i, j))
if len(zombies) == 0:
return -1
visited = set()
days = 0
while zombies:
p = len(zombies)
for _ in range(p):
i, j = zombies.popleft()
... |
996,241 | 942f164741209540ad82a9d437018d5c53c634bc | from itertools import product
print([
'B{}C{}S{}P{}'.format(b,c,s,p) for b,c,s,p in product(
range(1, 3), range(1, 4), range(1, 3), range(1, 4)
)
])
|
996,242 | cb32067e16281ff0215ef5c56f6f61cbaf8f70c8 | #!/usr/bin/python2
import commands
import cgi
import cgitb
cgitb.enable()
print "content-type: text/html"
print
data=cgi.FormContent()
NNIP=data['nn'][0]
JTIP=data['jt'][0]
u=data['client'][0]
network=commands.getoutput('route -n | grep 255 |cut -d" " -f1')
host1 = commands.getoutput("arp-scan --interface=eth0 %... |
996,243 | 9023a092e33b1d0a4c43019a2bc19c51c1d8c0f3 | import torch as pt
import numpy as np
from model.PFSeg import PFSeg3D
from medpy.metric.binary import jc,hd95
from dataset.GuidedBraTSDataset3D import GuidedBraTSDataset3D
# from loss.FALoss3D import FALoss3D
import cv2
from loss.TaskFusionLoss import TaskFusionLoss
from loss.DiceLoss import BinaryDiceLoss
from config ... |
996,244 | c5401efd0be6401c95fbbef61723894f01909381 | # 161. One Edit Distance
from functools import lru_cache
class Solution:
def isOneEditDistance(self, s: str, t: str) -> bool:
if not s and not t:
return False
if not s:
return len(t) == 1
if not t:
return len(s) == 1
sN, tN = len(s), len(t... |
996,245 | 91022c6a6006403e91dc954751981f7e10121637 | # -*- coding: utf-8 -*-
"""
__title__="chekc"
__author__="ngc7293"
__mtime__="2020/9/20"
"""
import os
import numpy as np
import pandas as pd
import time
from tqdm import tqdm
from gensim.scripts.glove2word2vec import glove2word2vec
from gensim.models import KeyedVectors, Word2Vec
glove_file = "../data/pre/glove.42B.... |
996,246 | 23bc051b66729db9f0075d1155b96aab78b4e7d2 | def rules(x, y, serial_number):
rack_id = x + 10
power_level = rack_id * y
power_level += serial_number
power_level *= rack_id
power_level = int((power_level - int(power_level / 1000) * 1000) / 100)
power_level -= 5
return power_level
assert rules(3,5,8) == 4
assert rules(122,79,57) == -5
a... |
996,247 | 850a182622eb0d6c5fa4e32b8af7dd6fbd1ab638 | A = b'ABC'
B = b'DEF'
C = [A, B]
C.append(3)
print(C)
print(type(C))
for i in range(2):
C.append(A)
print(C) |
996,248 | ea8e8ab4e55922a8068b60d5b5180f3e91e38c84 | from zipfile import ZipFile
with ZipFile('input.zip') as myzip:
for z in myzip.filelist:
name = z.filename
# print(name)
if name[-1] == '/': # каталог
print(' ' * (name.count('/') - 1) + z.orig_filename.split('/')[-2])
else:
print(' ' * (name.count('/')) +... |
996,249 | 19c6f792a3b100dfb8e8e5289fb88e00923c663f | """ Reading and writing of spectra
"""
from __future__ import print_function, absolute_import, division, unicode_literals
from six import itervalues
try: # Python 2 & 3 compatibility
basestring
except NameError:
basestring = str
# Import libraries
import numpy as np
import warnings
import os, pdb
import jso... |
996,250 | 75e9ef5735ca09bd771fd5a3d02aee50babf947f | import os
import socket
import time
import contextlib
from threading import Thread
from threading import Event
from threading import Lock
import json
import subprocess
from contextlib import contextmanager
import pytest
import mock
import requests
from urllib3.util.retry import Retry
from requests.adapters import HTTP... |
996,251 | 71bc9672bea10c99bae8c5a3c5b8401f646b441c | import streamlit as st
import pandas as pd
import numpy as np
import simplejson as json
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Rectangle, Arc
st.title("Shot Chart Visualization")
st.subheader("Shot charts for all All Stars for the 2019-2020 season plus the top 3 d... |
996,252 | c4ef7e007b8d86f0c6562eb1b910d0e7fcdf9293 | from io import StringIO
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world!')
print(f.getvalue())
t=StringIO('hello\nworld!')
while 1:
str=t.readline()
if str=='':
break
else :
print(str.strip()) |
996,253 | d524919ca80e228805f622d76db00912086be1fe | #!/usr/bin/python3
"""
This init imports fib.py only
fib.py contains the function fib(a,b=None)
"""
from .fib import fib
|
996,254 | 7f4837aa1698477bcb580e82c814a80df4a95352 | from django.conf.urls import include, url
from django.contrib import admin
from swautocheckin import views
urlpatterns = [
url(r'^$', views.email_view, name='email'),
url(r'^passenger/(?P<passenger_uuid>[^/]+)/create-reservation$', views.reservation_view, name='reservation'),
url(r'^reservation/(?P<reserva... |
996,255 | 8a4a833124f1e2b127866ede5a839806d9b31156 | set24 = {"1", "2", "3", "4", "6", "8", "12", "24"}
set36 = {"1"",2", "3", "4", "6", "9", "12", "18", "36"}
set24_1 = {"24", "48", "72", "96", "120"}
set36_1 = {"36", "72", "108", "142", "178"}
print("24和36的最大公约数为:%s" % max(set24.intersection(set36)))
print("24和36的最小公倍数为:%s" % min(set24_1.intersection(set36_1)))
|
996,256 | a1d4427d54b500203ae2190c32d5d75896b55791 | from os.path import isfile, join
from os import listdir
import allVariables
myDirectory = allVariables.pathToTrain
#fonction récursive permettant d'ecrire dans chaque fichier sa categorie
def fichier_rec(myDirectory):
for f in listdir(myDirectory):
chemin = join(myDirectory, f)
if isfile(chemin):
... |
996,257 | 06722fcea789ea111b87a575534f767187bea904 | import os
import datetime
import pickle
import json
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
from dotenv import find_dotenv, load_dotenv
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import Pipeline
from zenitai.u... |
996,258 | 89fe6e137826fe24d8bd745409caf0e27b6ae673 | import unittest
import graph
from test_data import nations_of_the_world
class testAStar( unittest.TestCase ):
"""
Test some very basic graph functions
"""
def setUp(self):
self.G = graph.graph()
nations_of_the_world(self.G)
def testBasic1(self):
"""
Retrieve all th... |
996,259 | 08f67a7783d8c5a9f83930da6dfbfa655c8fa8a0 | import unittest
import pandas as pd
import operator as op
import pandas.util.testing as pdt
from data import DrinkData
class TestCase(unittest.TestCase):
# Create instance with test data
test_isd = DrinkData("testing_data.csv")
def test_search_criteria(self):
"""Test for search_criteria."""
... |
996,260 | 167ef20099fcaf5b9a24fde6ea635339e4a15dc9 | from setuptools import setup
setup(
name='cffi-lz4frame',
version='0.0.0',
author='nathants',
author_email='me@nathants.com',
url='http://github.com/nathants/cffi-lz4frame/',
packages=['lz4frame'],
install_requires=['cffi>=1.0.0'],
cffi_modules=["lz4frame/__init__.py:ffibuilder"],
s... |
996,261 | 39491ce054bb9bca67cda670b3c41d372f497e5b | def verifica_velocidade(velocidade):
if(velocidade >= 70):
velocidade = velocidade-70
pontos = int(velocidade/5)
print("Pontos: "+ str(pontos))
if(pontos > 12):
print("Licença suspensa")
else:
print("ok")
verifica_velocidade(int(input("Digite a velocidade em km/h: ")))
|
996,262 | faba85e6d651917f2a592e417022d7396a5e5527 | demo_list = [1, 'hello', 1.34, True, [1, 2, 3]]
colors = ['red', 'green', 'blue']
numbers_list = list((1, 2, 3, 4, 5, 6))
print(list(range(1, 100)))
print(dir(colors))
print(len(demo_list))
print(colors[1])
print('green' in colors)
print(8 in colors)
colors.append('black')
colors.extend(('violet', 'yellow'))
co... |
996,263 | f4c83dbc632e5aa9efe6fa4d3af6b3d254801656 | import unittest
from src.rock_paper_scissors import RockPaperScissorsGame
class TestGame(unittest.TestCase):
def setUp(self):
self.game = RockPaperScissorsGame()
def test_rock_beats_scissors(self):
assert self.game.beats("rock", "scissors") == True
def test_scissors_does_not_beat_rock(s... |
996,264 | a543cff1122402336755ca2c6454aa92670c81bb | import logging
from typing import Dict, List, Tuple, Set
from meltano.core.permissions.utils.snowflake_connector import SnowflakeConnector
GRANT_ROLE_TEMPLATE = "GRANT ROLE {role_name} TO {type} {entity_name}"
GRANT_PRIVILEGES_TEMPLATE = (
"GRANT {privileges} ON {resource_type} {resource_name} TO ROLE {role}"
... |
996,265 | e1edba78e5647a73bf221cc45f6bb49be72a2d38 | from gevent import monkey; monkey.patch_all()
from webrecorder.utils import load_wr_config, init_logging
from webrecorder.rec.webrecrecorder import WebRecRecorder
import gevent
try:
import uwsgi
from uwsgidecorators import postfork
except:
postfork = None
pass
# ====================================... |
996,266 | e9f6df0f18357cd4ff7c4f6e9a8cf89d2d3ce262 | import turtle
turtle.shape("turtle")
turtle.speed(10)
turtle.pencolor("blue")
turtle.width(2)
for i in range(30):
turtle.forward(10 * i)
turtle.left(90)
turtle.forward(10 * i)
turtle.left(90)
turtle.exitonclick()
# Weird Pyramid (Cool)
#
# for i in range(100):
# # turtle.left(60)
# turtle.forward(5 * ... |
996,267 | 544c65dd49e3e5fef86d547ed8a05932ac20d6f7 | import argparse
from collections import defaultdict
from operator import itemgetter
import pickle
import os
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import numpy as np
from actiondatasets.gteagazeplus import GTEAGazePlus
def get_confmat(path):
"""Processes ... |
996,268 | 91c46843aadf746f73020f85db9e4c945a400fe6 | from django.test import TestCase
from django.test import Client
from django.contrib.auth import login
from linkup.models import Profile,Event,Poll
from django.contrib.auth.models import User
class CsrTest(TestCase):
# Tests if csrfmiddlewaretoken is in the login page
def login(self):
client = Client(... |
996,269 | 4c95527cecf8db01d4d5151a34863f68f14a6e8c | from gm2 import np
class Spikes(object):
def __init__(self, phis=None, freqs=None, th=None):
self.debug = True
if (freqs is not None):
self.init(phis, freqs, th)
def init(self, phis, freqs, th):
self.th = th
self.rm = np.zeros([freqs.shape[-1]])
self.freq = ... |
996,270 | 27a24bef73ea98b1613f650567545c06602c8b13 | import datetime
import os
import psycopg2
from flask import Flask, render_template
app = Flask(__name__)
app.secret_key = os.environ['APP_SECRET_KEY']
@app.route("/", methods=('GET', 'POST'))
def index():
# Connect to database
conn = psycopg2.connect(host=os.environ['POSTGRES_HOST'], database=os.environ['POS... |
996,271 | 63dd569b40c411677b4c98481f25f8ec150b1fe1 | import numpy as np
import numpy
from PIL import Image
from numpy import genfromtxt
training_n = 5
image_width=7
image_height = 9
# Cantidad de input units
input_n = image_width * image_height
# Cantidad de output units
output_n = 7
threshold = 0
b = np.zeros(output_n)
w = np.zeros((input_n, output_n))
t = np.zeros... |
996,272 | aaa376f81743ef85262d438edc3c7929450d4c3c | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 5 20:55:24 2019
@author: Erdo
"""
# %% libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# %%
""" Data Import """
data = pd.read_excel('Iris.xls')
data.head()
#%%
x_data = data.iloc[:,0:4].values
y_data = data.iloc[:,-1:].values
#%%
fr... |
996,273 | 4e379cb2f26bd97a87f5eeb960b4cc8be631b775 | import random
pri = input('Digite a primeira pessoa: ')
seg = input('Digite a segunda pessoa: ')
terc = input('Digite a terceira pessoa: ')
qua = input('Digite a quarta pessoa: ')
lista = [pri, seg, terc, qua]
'''escolhido = random.choice(lista)
# no caso de querer escolher um
# numa lista
print('A pessoa sorteada foi... |
996,274 | 58ce94c10e0fbbb2822078b5e4e9db4d7c957a02 | #-*-coding:utf-8-*-
#@Time :2019/2/25 16:44
#@Author:xiaoqi
#@File :task_01.py
#1:写一个类 类的作用是完成Excel数据的读写 新建表单的操作
# 函数一:读取指定表单的数据,
# 有一个列表row_list,把每一行的每一个单元格的数据存到row_list里面去。
# 每一行都有 一个单独的row_list [[1,2,3],[4,5,6]] #每一行数据读取完毕后,把row_list存到大列表all_row_list
# 函数二:在指定的单元格写入指定的数据,并保存到当前Excel
# 函数三:新建一个Excel
from open... |
996,275 | f87f513756961fea7320465e4dda865ff9f97c8f | from distutils.core import setup
from setuptools import find_packages
with open('requirements.txt') as f:
requirements = f.readlines()
# https://www.geeksforgeeks.org/command-line-scripts-python-packaging/
setup(name='mlpipe',
version='1.0',
packages=find_packages(),
entry_points = {
... |
996,276 | 518de3be7065742a194355b616627e523d8b07de | import json
def get_json_info(file):
with open(file) as json_file:
data = json.load(json_file)
return data
def set_json_info(file, data):
with open(file, 'w') as outfile:
json.dump(data, outfile)
def write_aircraft_to_csv(craft):
output_str = '\n{},{},{},{},{}'.format(
cr... |
996,277 | 30a5ac6123afa72452ae46cce88b499ac061a0a7 | # -*- coding:utf-8 -*-
# 思路:遍历所有的叶子,看是否等于sum
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:ty... |
996,278 | 2f1f821dac7bb6355a5b9a261fdd13470052d90a | # -*- coding: utf-8 -*-
# @Time : 2019/1/14 11:23 AM
# @Author : scl
# @Email : 1163820757@qq.com
# @File : K-Means算法.py
# @Software: PyCharm
import matplotlib
matplotlib.use("TkAgg")
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import sklearn.datasets as ds
import matplotlib.co... |
996,279 | de321dbed3348b2bdea5840cfb97e70854ca8884 | #
from __future__ import print_function
import os, sys
import time
import seaborn as sns
import pandas
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import tensorflow as tf
import keras as ks
from keras import Sequential
from keras.layers import Dense
from keras.callback... |
996,280 | 3601e212f67c75b9d93a1a435e8da3a9bc331372 | import os
import SimpleITK as sitk
import matplotlib.pyplot as plt
import pydicom
from pydicom.data import get_testdata_files
import numpy as np
if __name__ == '__main__':
path = 'LUNGx-CT003/03-23-2006-6667-CT NON-INFUSED CHEST-15464/5-HIGH RES-37154'
filenames = os.listdir(path)
# for file in filenames... |
996,281 | 15ccc8263f6ce2211973289b2105f88dda4ed424 | import os
import pycurl
import magic
import requests
from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor
from src.classes.Config import Config
mime = magic.Magic(mime=True)
def download(url):
return requests.get(url, allow_redirects=True).content
# Class which holds a file reference and t... |
996,282 | bd6837f684b2689b1e3fc632d05060bea93a33d7 | # -*-coding:utf-8 -*-
import numpy as np
def cos_similarity(vec1, vec2):
#
cos_theta = np.sum(vec1 * vec2) / \
(np.sqrt(np.sum(vec1 ** 2)) * \
np.sqrt(np.sum(vec2 ** 2)))
#
return cos_theta
def hist_similarity(X1, X2):
'''
To evaluate the similarity of X1 an... |
996,283 | 0738f5a7f0bdc5598aceddcf6adb526bd1c0eac0 | api = dict(
url="",
token=""
)
location = "Ambient"
|
996,284 | 1b643c9ac2da65e238e8dd0cdf564e403a699a4e | def longestvalidparanthesis(self,s):
if not s:
return 0
stack = []
dp = [0]*len(s)
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
continue
if stack:
leftIndex = stack.pop()
dp[i] = i-leftIndex+1+dp[leftIndex-... |
996,285 | 0ae904d50310da31ccd7ba8b2c36f0aa5ffea412 | from pyfam.mcmc import MCMC
import numpy as np
import matplotlib.pyplot as plt
#Define a model function to use when fitting data.
# For this example, that's a gaussian function plus a linear offset.
def f(x, p):
a, b, c, d, e = p
return a*np.exp(-(x-b)**2/(2*c**2)) + d*x + e
#Make some fake data with adde... |
996,286 | 5cb54209bc5478b8232c3c7b2e102206349ece62 | def transposed(matrix):
return list(map(list, zip(*matrix)))
def snail_path(matrix):
result = []
while len(matrix) > 0: # noqa: WPS507
result.extend(matrix.pop(0))
matrix = transposed(list(map(reversed, matrix)))
print(matrix)
return result
|
996,287 | 907f44ea6cf8c54b382a17119f408d087c840928 | def remove_emoji(data):
"""
去除表情
:param data:
:return:
"""
if not data:
return data
if not isinstance(data, basestring):
return data
try:
# UCS-4
patt = re.compile(u'([\U00002600-\U000027BF])|([\U0001f300-\U0001f64F])|([\U0001f680-\U0001f6FF])')
except re.... |
996,288 | 46a040fb6f1e88fd557ffbab9075c825bad579a8 | from django.core.files.storage import FileSystemStorage
from django.shortcuts import render ,HttpResponse,redirect
from firstapp.forms import userDataForm
from django.contrib.auth.hashers import make_password,check_password
from firstapp.models import userData
# Create your views here.
def index(request):
return H... |
996,289 | 617059eb099282dbf684f5cdfeaba07a5e740fa4 | from copy import deepcopy
import json
from openshift.dynamic.exceptions import NotFoundError
LAST_APPLIED_CONFIG_ANNOTATION = 'kubectl.kubernetes.io/last-applied-configuration'
def apply_object(resource, definition):
desired_annotation = dict(
metadata=dict(
annotations={
LAST... |
996,290 | 84df7539f1ce6c27bd06d0b702f0a8b182e6836f | #https://app.codility.com/demo/results/trainingE4UNAA-Y9B/
def cyclic_rotation_1(arr, k):
if k < 0 or k > 100:
raise ValueError
al = len(arr)
if al == 0:
return []
k = k % al
if k == 0:
return arr
return (arr * 2)[al-k:al + al-k]
#print(cyclic_rotation_1([3, 8, 9, 7... |
996,291 | 01b3c1d7a4138ebea4dbed6ce6a0cd0e11425b05 | import time
class DateManager(object):
def getDate(self):
return time.strftime("%Y/%m/%d")
def getYear(self):
return time.strftime("%Y")
def getMonth(self):
return time.strftime("%m")
def getDay(self):
return time.strftime("%d")
def getCr... |
996,292 | 7f445bc512445c06e32c5a4db94fa6ac9def13b0 | def make_car(Manufacturer, model, **user_info):
car = {'type': 'SUV', 'sent': "20W"}
car['Manufacturer_name'] = Manufacturer
car['Model'] = model
for key, value in user_info.items():
car[key] = value
return car
# print(car)
car = make_car('subaru', 'outback', color='blue', tow_package=... |
996,293 | 1fea998e4fa8245cacab11c5b9a99091e6416a77 |
import streamlit as st
import pandas as pd
import json
import matplotlib.pyplot as plt
import matplotlib
from text_data_analysis import analysis
from documentation import docs
menuItems = [
'Text Data Analysis',
'Automatic Data Analysis',
'Documentation']
st.sidebar.title('Eas... |
996,294 | 06c5730648d03b6c536e8fa30d00ac35d8e39bf0 | import bpy
from bpy.types import Node
from mn_node_base import AnimationNode
from mn_execution import nodePropertyChanged
from mn_utils import *
class SubProgramNode(Node, AnimationNode):
bl_idname = "SubProgramNode"
bl_label = "Sub-Program"
def init(self, context):
self.inputs.new("SubProgramSocket", "Sub-Prog... |
996,295 | 8aee4b214c262b69d1c957b91ee772702b5dd289 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 17 00:20:30 2020
@author: MADHURIMA
"""
"""def arrayManipulation(n,queries):
a=[0]*(n+1)
a=a[1:]
for i in queries:
for j in range(i[0],(i[1]+1)):
a[j-1] += i[2]
return max(a)
n,m=[int(i) for ... |
996,296 | 3de53f0effe4a8fba889294ba2d7c4a92f6660ee | # https://www.acmicpc.net/problem/2381
import sys
if __name__ == '__main__':
n_num = int(sys.stdin.readline())
calc = [[[0, i] for i in range(n_num)], [[0, i] for i in range(n_num)]] # [x+y, seq], [x-y, seq]
for i in range(n_num):
x, y = map(int, sys.stdin.readline().split())
calc[0][... |
996,297 | ac43d23ed4128be7ab4df66cf42c84c3cf2f895b |
###########################
# PANTELIDIS NIKOS AM2787 #
###########################
from spatial_search import *
from text_search import *
# THESE FILE CONTAINS THE FUNCTIONS OF PART 3 AND
# SOME OF THE TEXTUAL AND SPATIAL SEARCH FUNCTIONS
# BUT APPROPRIATELY MODIFIED TO PIPELINE THE RESULTS
# OF THE FIRST SEARCH IN... |
996,298 | d4871c484fe17df258ece744d1964e08a9c0b37b | """基于字典元素中特定值对应的键生成列表"""
def keys_of(dic: dict, val: 'value') -> list:
"""返回一个列表,该列表的元素是字典dic中值为val的元素的键"""
return [k for k, v in dic.items() if v == val]
txt = input('字符串:')
count = {ch: txt.count(ch) for ch in txt}
print('分布=', count)
num = int(input('字符数量:'))
print('{}个字符={}'.format(num, keys_of(c... |
996,299 | df92e059a519b9cb16bca08b470b54c7aefe1154 | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# 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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.