text stringlengths 38 1.54M |
|---|
import DNA
import settings
from PIL import Image, ImageDraw
class Polygon(object):
def __init__(self, dna=None, fitness=None):
if(dna and fitness):
self.dna = dna;
self.fitness = fitness;
elif(dna):
self.dna = dna;
else:
self.dna = DNA.DNA();
def createImageFromGenes(self):
img = []
draw = [... |
def taint_class(klass, methods):
class tklass(klass):
def __new__(cls, *args, **kwargs):
self = super(tklass, cls).__new__(cls, *args, **kwargs)
self.taints = set()
return self
d = klass.__dict__
for name, attr in [(m, d[m]) for m in methods]:
if inspect.ismethod(... |
#!/usr/bin/env/ python
from os import listdir
import os
class PNGList:
from os import listdir
def __init__(self):
self.list=0
def ListGet(self, path):
self.list=[f for f in listdir(path) if f.split('.')[-1]=='png']
return self.list
def CAGHeader(gps_start, gps_end, dur, srate, stri... |
from django.core.management.base import BaseCommand
from ...utils import update_topology
class Command(BaseCommand):
help = 'Update network topology'
def add_arguments(self, parser):
parser.add_argument('--label',
action='store',
default=None,
... |
from flask import Flask
from flask_restful import Api, Resource, reqparse
app = Flask(__name__)
api = Api(app)
class CustomerAPI(Resource):
def get(self):
pass
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.ad... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-07-11 18:29
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('promises', '0001_initial'),
('c... |
r = open("hello.txt","r")
print(r.read())
temp2 = r.readlines()
a = []
for li in temp2:
a.append(li.strip())
print(a)
r.close() |
def make_shirt(tamanho,texto):
print("Camiseta tamanho " + tamanho + ". Com o texto: " + texto)
make_shirt("M","Shrek é amor")
make_shirt(tamanho="G",texto="Shrek é vida") #A ordem não faz diferença
make_shirt(texto="Shrek é vida",tamanho="G")
|
'''
Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).
Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points ar... |
def create_reviewers_table(a_cursor):
a_cursor.execute("CREATE TABLE reviewers("
"reviewer_id uuid default uuid_generate_v4() not null constraint reviewers_pkey primary key,"
"first_name varchar(10) not null,"
"last_name varchar(10) not null,"
... |
# -*- coding: UTF-8 -*-
#
# =======================================================================
#
# Copyright (C) 2018, Hisilicon Technologies Co., Ltd. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions ... |
#!/usr/bin/env python3
### IMPORTS ###
import datetime
import enum
import uuid
from sqlalchemy import BigInteger, Column, DateTime, Enum, Integer, String
from sqlalchemy.orm import relationship
#from sqlalchemy.sql import func
from .base import Base, GUID
### GLOBALS ###
### FUNCTIONS ###
### CLASSES ###
class Me... |
CONFIG = {
'STATIC': '/blog/static/',
'JS': '/blog/static/js/',
'CSS': '/blog/static/css/',
}
|
""" The old dungeon """
from tkinter import Tk,Canvas
import math
g=0
prngNum = int(input("What is the seed? "))
resolution = int(input('What is the resolution (10 is recommended): '))
roomamt= int(input("how many rooms? "))
Idtbl=[[0 for i in range(resolution)] for i in range(resolution)]
cantouch=[[0 for i in range... |
# Generated by Django 2.0 on 2018-04-10 12:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tasks', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='task',
name='status',
field=mod... |
'''
Contains all of the information for the current library.
'''
class LibraryDef:
def __init__(self, field_types, field_list, table_columns, true_columns):
self.field_types = field_types
self.field_list = field_list
self.table_columns = table_columns
self.true_columns = true_colum... |
from game.utils.cmd_line_functions import wait, cls
from game.utils.shared_functions import text
def frame(_text, seconds=0.15):
text(f'\n {_text}')
wait(seconds)
cls()
|
class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
tokens = []
len_s = len(s)
i = 0
ch0 = ord('0')
ch9 = ord('9')
while i < len_s:
if s[i] == '+' or s[i] == '-' or s[i] == '(' or s[i] == ')':
... |
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework.authtoken.views import obtain_auth_token
# from rest_framework_simplejwt import views as jwt_views
from . import views
urlpatterns = [
# path('token/', jwt_views.TokenObtainPairView.as_view(), name='token... |
from src import db
from werkzeug.security import generate_password_hash, check_password_hash
import json
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
role = db.Column(db.String(10), nullable=True)
name = db.Column(db.String(50), nullable=False)
email = d... |
"""clic setup file."""
from __future__ import with_statement
import inspect
import os
# Import Setuptools
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
name_ = 'clic'
version_ = '0.1'
description_ = "CLiC Project"
# Inspect to find current path
setuppath = inspect.getfile(inspe... |
from abc import ABCMeta, abstractmethod
class node_base():
__metaclass__ = ABCMeta
def __init__(self, id=0, value=None):
super().__init__()
self.value = value
self.id = id
|
#Filename: print_logs.py
from functools import wraps
def logit(level):
import logging
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
'''decorator docs'''
logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message... |
from django.contrib import admin
from django.urls import path, include
from mywork.views import *
app_name = 'mywork'
urlpatterns = [
path('create/', ProductCreateView.as_view()),
path('all/', ProductListView.as_view()),
path('detail/<int:pk>/', ProductDetailView.as_view()),
] |
# "Stopwatch: The Game" by Todd Demone
import simplegui
# define global variables
time = 0
is_running = False
total_stops = 0
successful_stops = 0
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
minutes = t / 600
seconds = t % 600 / 10
... |
# -*- coding: utf-8 -*-
from random import randrange, uniform
class Fighter:
"""The base class of a Fighter"""
def __init__(self, name, description):
self.__name = name
self.__description = description
self.__agility = randrange (1,9)
self.__healthPoints = 100 # Lors de la créati... |
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
import selenium.common.exceptions
from selenium.webdriver.support import expected_conditions as EC
def find_element(id):
return driver.find_element_by_id(id)
def wait_exp(xpath):
... |
from Actions.ActionGroup import ActionGroup
class ActionBase:
def __init__(self, text, act_id):
self.__act_text = text
self.__act_id = act_id
self.__follow_up_action_group = None
self.__my_player = None
self.__my_game_round = None
def get_act_text(self):
return... |
nq = "2 5"
#nq = input().strip()
parts = nq.split(' ')
n = int(parts[0])
q = int(parts[1])
instructions = ['1 0 5',
'1 1 7',
'1 0 3',
'2 1 0',
'2 1 1'
]
#instructions = [x for x in input().strip()]
last_ans = 0
seq_list = list()
for i in range(0, n):
seq_list.append(list())
for instruction in instructions:
... |
#!/usr/bin/env python
import sys
import os
import time
import threading
from threading import Lock
from threading import Condition
import uuid
import simplejson
import Queue
import shelve
import signal
import argparse
import pika
from pika.adapters import select_connection
import tornado.ioloop
import tornado.web
fro... |
'''
For those who're confused with problem statement. Here's an outline of how to get solution.
"You have a sample of n values from a population with mean m and with standard deviation s."
Means you have sample: x1, ..., xn of random variable with some unknown distribution with known mean m and standard deviation s.
... |
# Generated by Django 2.2.7 on 2019-12-26 15:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='blogpost',
name='description',
... |
#@author - Ankur
import argparse
import numpy as np
import os
from os.path import join, exists
import sys
import time
import torch
import torch.utils.data
from torch.utils.data import Dataset , DataLoader
from torch.nn import functional as F
from torchvision import transforms
import torch.nn as nn
import pandas as pd
... |
__author__ = 'tdwilkinson'
class by_mag_comparison():
def __init__(self, ref_magnitude, ref_sn, ref_exptime, target_sn, array_magnitudes):
exptime = (target_sn * ref_exptime) / ref_sn
print 'recommended exp time:', exptime
# use ref_magnitude and array_magnitudes to do a comparison
... |
from django.contrib.auth.models import AbstractUser
from django.db import models
from accounts import constants
from common.models import BaseModel
class User(BaseModel, AbstractUser):
loyalty_level = models.CharField(
max_length=6, choices=constants.LOYALTY_LEVEL_CHOICES)
|
'''
reverseWords:
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。
为简单起见,标点符号和普通字母一样处理。
例如输入字符串"I am a student. ",则输出"student. a am I"。
'''
'''
reverseLeftWords
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。
请定义一个函数实现字符串左旋转操作的功能。
比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"
'''
'''
py 赖皮
'''
class Solution:
... |
from django.test import TestCase, Client
from django.urls import resolve
from .views import home, about, services
# Create your tests here.
class UnitTest(TestCase):
# home
def test_main_url_exists(self):
response = Client().get("")
self.assertEqual(response.status_code, 200)
def test... |
from django.shortcuts import render, get_object_or_404, redirect
from django.conf import settings
from rent.models import Game, Order, Rent
from user.models import User
from rent.views import rent_game, empty_cart
from payment.models import Contend
from payment.forms import newContend
import stripe
from django.core.mai... |
from refractor.framework_swig.named_spectrum import ObserverPtrNamedSpectrum
from .strategy_executor import StrategyExecutor
from ..output.base import OutputBase
class CaptureRadiance(ObserverPtrNamedSpectrum, OutputBase):
def __init__(self):
# Required to initialize director
ObserverPtrNamedSpect... |
from psychopy import visual, core, event, sound, monitors
import numpy, pygame, string, sys
from EyeLinkCoreGraphicsPsychoPyAnimatedTarget_Other import EyeLinkCoreGraphicsPsychoPy
import pickle
import random
import csv
import time
import pylink
import keyboard
from datetime import datetime
from random import ... |
# Generated by Django 2.0.1 on 2019-03-07 00:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('myapp', '0005_remove_usersave_is_active'),
]
operations = [
migrations.RemoveField(
model_name='doctor',
name='profile_photo... |
"""
Script: 01-Apply-Sentiment
Purpose: Add rule-based TextBlob and VADER sentiment polarity scores to Tweets from CrowdFlower data
Input: https://www.crowdflower.com/wp-content/uploads/2016/03/Airline-Sentiment-2-w-AA.csv
(Annotated CrowdFlower Data - learn more about crowdflower here: https://www.cro... |
import os, time
from todoist.api import TodoistAPI
API_WAIT_TIME = 3 # seconds
class Project:
def __init__(self):
self.token = os.getenv('TOKEN')
self.api = TodoistAPI(self.token)
self.api.sync()
self.project_id = None
def create_project(self, project_name: str):
"""... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from handlers import *
command_handlers = {
# 'command': handler_func,
'start': start,
'help': help_h
}
conversation_handlers = [
# test_ch
]
button_handlers = {
# 'btn_name': handler_func,
'show help': help_h
}
callback_handlers = {
# 'callb... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class NodeMenuError(Exception): pass
class NodePropertyError(Exception): pass
class NodeWidgetError(Exception): pass
class NodeRegistrationError(Exception): pass
class PortRegistrationError(Exception): pass
|
from db import db
import datetime
import time
def _get_date():
return datetime.datetime.now()
# return datetime.datetime.now(datetime.timezone.utc)
# return time
class LogModel(db.Model):
__tablename__ = 'logs'
id = db.Column(db.Integer, primary_key=True)
action_name = db.Column(db.String(4... |
import mingus.core.notes as notes
import mingus.core.chords as chords
import mingus.core.value as value
from mingus.containers import Bar, NoteContainer, Track, Composition
import mingus.extra.lilypond as LilyPond
from mingus.midi import midi_file_out
# NOTE: Must install lilypond.exe (for Windows), LilyPond in the $P... |
from datetime import datetime
from sqlalchemy_example.models import *
def load_categories(session):
for category_id, category_name in [(1,'Children Bicycles'), (2,'Comfort Bicycles'),
(3,'Cruisers Bicycles'), (4,'Cyclocross Bicycles'),
(... |
#!/usr/bin/env python
import heapq
from collections import deque
class Graph(object):
class AdjNode(object):
def __init__(self, src, dst, cst=1):
self.source = src
self.destination = dst
self.cost = cst
self.next = None
class AdjList(object):... |
from src.Objetos.Vetor import Vetor
from src.FerramentasBasicas.produtoEscalar import produtoEscalar
def saoOrtogonais (vetor1, vetor2):
if type(vetor1) is not Vetor: raise Exception("vetor1 não é um vetor valido")
if type(vetor2) is not Vetor: raise Exception("vetor2 não é um vetor valido")
return prod... |
import numpy as np
def softmax(x):
"""Compute the softmax function for each row of the input x.
It is crucial that this function is optimized for speed because
it will be used frequently in later code. You might find numpy
functions np.exp, np.sum, np.reshape, np.max, and numpy
broadcasting usefu... |
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from flask_jwt import JWT, jwt_required
from security import authenticate, identity
app = Flask(__name__)
app.secret_key = 'number1'
api = Api(app)
jwt = JWT(app, authenticate, identity) # create /auth endpoint
items = []
class Ite... |
from BribeNet.bribery.static.briber import StaticBriber
from BribeNet.helpers.override import override
class InfluentialNodeBriber(StaticBriber):
def __init__(self, u0, k=0.1):
super().__init__(u0)
self._k = k # will be reassigned when graph set
@override
def _set_graph(self, g):
... |
# coding:utf-8
class stu(object):
def __init__(self,n):
self.name = n
def say(self):
print self.name
def ceshi(a):
print a
print __name__
if __name__ is "__main__":
ceshi("aasd") |
import os
import pytest
from src import create_app
@pytest.fixture(scope="function")
def test_app():
"""
fixture for the test classes, set the environmental variable to testing
:return:
"""
app = create_app()
app.config.from_object("src.config.TestingConfig")
os.environ["TESTING"] = "1"
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
__doc__ = '''\
Дополнения к структуре БД для передачи в 1С назначений ЛС
'''
def upgrade(conn):
global config
c = conn.cursor()
c.execute(u'''DROP TRIGGER IF EXISTS `onUpdateDrugChart`''')
c.execute... |
import os.path as osp
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import json
# from core.encoders import *
from torch_geometric.datasets import TUDataset
from torch_geometric.data import DataLoader
import sys
import json
from torch import o... |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager
class User(AbstractBaseUser, PermissionsMixin):
"""Model definition for User."""
first_name = models.CharField(max_length=150, blank=True, default="", null=True)
last_name = models.CharFiel... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import operator_benchmark as op_bench
from pt import ( # noqa
add_test, batchnorm_test, cat_test, chunk_test, conv_test, # noqa
gather_test, linear_test, matmul_... |
# Written by Kamran Bigdely
# Example for Compose Methods: Extract Method.
import math
def distance_between_two_circle(circle1x, circle1y, circle2x, circle2y):
# Calculate the distance between the two circles
distance = math.sqrt((circle1x-circle2x)**2 + (circle1y - circle2y)**2)
print('distance', distance)
d... |
#
# Copyright (c) 2012-2023 Snowflake Computing Inc. All rights reserved.
#
import enum
import pytest
from sqlalchemy import Column, Enum, ForeignKey, Integer, Sequence, String, text
from sqlalchemy.orm import Session, declarative_base, relationship
def test_basic_orm(engine_testaccount, run_v20_sqlalchemy):
""... |
# coding: utf-8
from __future__ import print_function, unicode_literals
from .utils import extract_text, normalize_whitespace
class Article(object):
def __init__(
self,
id,
title,
categories,
link,
published=None,
content=None,
author=None,
... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from gym.spaces import Box
from shared.constants import PPODirectories
from shared.shared_utils import ind, sample_Xi, copy_attributes
class MultiAgentAlmgrenChriss:
"""
Initial Parameters:
Real-World Example: Opti... |
import shutil
import os
shutil.move('C:\ERP\Dados\gas\DADOS.FDB', 'C:\ERP\Dados')
os.system('C:\ERP\Retaguarda.exe')
os.system("taskkill /im Retaguarda.exe")
os.system("taskkill /im backup.exe")
shutil.move('C:\ERP\Dados\DADOS.FDB', 'C:\ERP\Dados\gas')
quit()
|
import random
import datetime
import requests
import math
from multiprocessing import Pool
from statistics import quantiles
from pprint import pprint as pp
from .globals import bitcoin
from .dijkstra import Graph
from .helpers import get_txo_amount, BTC
def run_day(db):
# discover the day we're in and which bloc... |
Vigilante_Phone_Book = {
"Frank Castle" : "(666) 119-1212",
"Bruce Wayne" : "(021) 201-3114",
"Clark Kent" : "(019) 211-6518"
}
def Dict_tuple(dic):
new_tuple = dic.items()
print new_tuple
Dict_tuple(Vigilante_Phone_Book) |
import scrapy
import pandas as pd
csv_input = pd.read_csv('lol.csv')
content=csv_input['moneycontrol_link'][:3]
links=[company for company in content]
l=[]
class BrickSetSpider(scrapy.Spider):
name = "h2"
start_urls = ['http://www.moneycontrol.com/india/stockpricequote/computers-software/tataconsultancy... |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
import json
# JSON file
f = open('data/data.json', "r", encoding="utf8")
# Reading from file
data = json.loads(f.read())
d = dict()
counter = 0
test_data = []
for i in data:
json_data = i
tag = json_data["tag"]
try:
d[tag] += 1
except:
d[tag] = 0
counter = coun... |
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:entry>", views.entry, name = "wiki"),
path("search", views.search, name="search"),
path("create", views.create, name="create"), # returns the html page to create a new entry
path("... |
import pandas as pd
import numpy as np
from math import pi
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
for activity in ["eating", "cooking"]:
if(activity == "eating"):
activity_name = "eatfood"
filename = "eating_features.csv"... |
# -*- coding: utf-8 -*-
#
# Copyright 2018 Amir Hadifar. 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 req... |
import numpy as np
a = np.arange(10)
print(a)
b = np.insert(a, 3, 10)
print(b)
x = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])
print(x)
print()
y = np.insert(x, 1, 10, axis=0)
print(y)
y = np.insert(x, 1, 10, axis=1)
print(y) |
#!/usr/bin/env python3
"""
Generates random txt files
Usage :
python3 fileGenerator.py 9999 # Generates file data.txt with 9999 characters
"""
import sys
import random
import string
size = int(sys.argv[1])
alphabet = string.ascii_lowercase
special_chars = "\n" + "\t" + " "
chars = alphabet + special_chars
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#Author: xiaojian
#Time: 2018/10/11 21:26
#测试用例 = 页面对象当中的页面功能 + 测试数据
import unittest
from selenium import webdriver
from PageObjects.login_page import LoginPage
from PageObjects.index_page import IndexPage
#测试数据
from TestDatas.login_datas import *
from TestDatas.CommonDatas ... |
import os
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from email.MIMEImage import MIMEImage
from reg.models import Sale
import html2text
import threading
from django.contrib.staticfiles.storage import staticfiles_storage
def send_html_email(subject, html_con... |
import pandas as pd
import pandas_datareader.data as web
import datetime
import matplotlib.pyplot as plt
start = datetime.datetime(2020,1,15)
end = datetime.datetime(2021,2,15)
gs = web.DataReader("078930.KS","yahoo",start,end)
ma5 = gs["Adj Close"].rolling(window=5).mean()
ma20 = gs["Adj Close"].rolling(window=20)... |
#!/usr/bin/env python3
# De-duplicate bash history
# NOTE: creates new file in current directory, does not copy over existing history file itself
import os
existing = list()
unique = 0
dupe = 0
with open(f"{os.getenv('HOME')}/.bash_history", 'r') as hist:
with open('bash_history', 'wb') as filtered:
for l... |
"""
day: 2020-08-21
url: https://leetcode-cn.com/leetbook/read/top-interview-questions-medium/xv11yj/
题目名: 搜索旋转排序数组
题目描述: 假设按照升序排序的数组在预先未知的某个点上进行了旋转
例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2]
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1
你的算法时间复杂度必须是 O(log n) 级别
示例:
输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
思路... |
"""Write information about paste.ofcode.org as json to stdout."""
import html.parser
import json
import sys
import requests
class PasteOfCodeParser(html.parser.HTMLParser):
"""Extract syntax highlighting choices out of the paste page."""
def handle_starttag(self, tag, attrs):
"""The parser enters a... |
#Pandas02_03_FunEx08_신동혁
'''
함수 안에서 선언한 변수의 효력 범위
함수 안에서 사용하는 매개변수는 지역변수이다.
전역변수 : 함수 밖에서 선언
- 모든함수가 같이 공유
지역변수 : 함수 내에서 선언
- 함수와 생명력을 같이 한다.
'''
a = 1 # 함수 밖의 변수 == 전역변수
def vartest(a) :
a += 1
print(a)
vartest(a)
print("-"*20)
print(a) # 10라인에 있던 1이 출력된다. Why? a는 함수 밖에서 선언... |
#3. Longest Substring Without Repeating Characters
'''
Given a string,
find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
'''
#Hash Table, Two Pointers, Strin... |
#/usr/bin/env python
import unittest
from assignment19 import BuckleyLeverett
class TestSolution(unittest.TestCase):
def setUp(self):
self.inputs = {
'reservoir': {
'oil': {
'residual saturation': 0.2,
'corey-brooks e... |
"""
A Practical Implementation of the Faster R - CNN Algorithm for Object Detection(Part 2 – with Python codes)
https: // www.analyticsvidhya.com / blog / 2018 / 11 / implementation - faster - r - cnn - python - object - detection /
# Setting up the System
Add in requirement.txt
pandas
matplotlib
tensorflow
keras – ... |
import eulerian.cycle
import eulerian.util
def test_parse_edges():
input_lines = ['0 -> 3', '1 -> 0', '2 -> 1,6', '3 -> 2', '4 -> 2', '5 -> 4', '6 -> 5,8', '7 -> 9', '8 -> 7',
'9 -> 6']
expected = {
0: [3],
1: [0],
2: [1, 6],
3: [2],
4: [2],
... |
from secrets import token_hex
from flask import render_template, url_for, redirect, flash, request
from app import app, db
from flask_login import current_user, login_user, logout_user, login_required
from app.forms import LoginForm, DoctorRegister, PatientRegister, AppointmentForm, confirmAppointment, rejectAppointmen... |
import re
from Bio import SeqIO
def pattern(DNA):
r = r"^%s"
return re.compile(r % str(DNA[-3:]))
if __name__=="__main__":
DNAs = []
f = open('rosalind_grph.txt', 'r')
[DNAs.append((i.id, i.seq.tostring())) for i in SeqIO.parse(f, 'fasta')]
f.close()
for i in range(len(DNAs)):
... |
# -*- coding: utf-8 -*-
"""
@Author : Xu
@Software: PyCharm
@File : exceptions.py
@Time : 2021/4/15 3:54 下午
@Desc : 异常处理
"""
from typing import Text
from wechatter.shared.exceptions import WechatterException
class ModelNotFound(WechatterException):
"""Raised when a model is not fou... |
"""Tests recognition of architectures and file formats by fileinfo."""
# IMPORTANT:
#
# The emitted architectures and file formats are parsed in the decompilation
# service. If you want to change them, consult this with Petr Zemek.
#
from regression_tests import *
base_settings = TestSettings(
tool='fileinfo... |
from blueprints import db
from flask_restful import fields
from sqlalchemy import func
from sqlalchemy.sql.expression import text
from datetime import datetime
from sqlalchemy import ForeignKey
from sqlalchemy import Table, Column, Integer
from blueprints.exam.model import Exams
from blueprints.mentee.model import Me... |
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers
class Keypad:
def __init__(self, keys, rowPins, colPins, Lcd):
self.ROW = rowPins
self.COL = colPins
self.keys = keys
self.Lcd = Lcd
self.key = set()
for j in range(4):
GPIO.setup(self.COL[... |
import requests
r = requests.get("https://www.qtyd.com/favicon.ico")
with open('favicon.ico','wb') as f:
f.write(r.content) |
from os import path, remove
from glob import glob
from bioprocs.utils import runcmd, cmdargs
indir = {{i.indir | quote}}
outfile = {{o.outfile | quote}}
plink = {{args.plink | quote}}
gz = {{args.gz | repr}}
samid = {{args.samid | quote}}
chroms = {{args.chroms | repr}}
recode = ['vcf-fid' if samid == 'fi... |
# -*- coding: utf-8 -*-
from model import AppInfo
from database import db_session
def fmt_data(data, cat_lev1, cat_lev2):
base = data.get('base', {})
app = AppInfo(
crawl_platform='OPPO',
app_name=base.get('appName', ''),
app_package_name=base.get('pkgName', ''),
dowload_link=... |
# Generated by Django 2.0.1 on 2018-01-19 03:07
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('clinicaltrials', '0002_remove_clinicaltrial_startdate'),
]
operations = [
migrations.AddField(
mode... |
from types import BeaverException, Variable, Uri, Value, updated_context
from statement import Statement
from command import Command, PrefixCommand
from parser import parse_string, parse_file, parse_stream
import sys
import urllib2
default = [
PrefixCommand('rdf', Uri('http://www.w3.org/1999/02/22-rdf-synt... |
import pyaudio
import wave
import audioop
form_1 = pyaudio.paInt16 # 16-bit resolution
chans = 1 # 1 channel
samp_rate = 44100 # 44.1kHz sampling rate
chunk = 4096 # 2^12 samples for buffer
#device index found by p.get_device_info_by_index(ii)
dev_1 = 2
# dev_2 = 3
# dev_3 = 4
audio = pyaudio.PyAudio() # create pyaud... |
# Generated by Django 2.2.4 on 2019-08-19 03:58
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('language', '0053_auto_20... |
from edflow.iterators.model_iterator import PyHookedModelIterator
from edflow.data.dataset import DatasetMixin
import numpy as np
class DebugModel(object):
def __init__(self, *a, **k):
pass
def __call__(self, *args, **kwargs):
pass
def debug_step_op(model, *args, **kwargs):
if "val" not... |
#https://www.codewars.com/kata/5878520d52628a092f0002d0/train/python
def string_transformer(s):
#The Plan
#Split it into multiple parts
#Iterate backwards over those multiple parts
#While iterating backwords iterate over each letter to alternate casing
splitList = s.split()
returnString =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.