text stringlengths 8 6.05M |
|---|
import unittest
from katas.kyu_7.make_them_bark import Dog
class DogTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(
Dog('Apollo', 'Dobermann', 'male', '4').bark(), 'Woof!'
)
def test_equals_2(self):
self.assertEqual(
Dog('Zeus', 'Doberman... |
'''
Created on Jul 15, 2013
@author: emma
'''
from selenium import webdriver #imports selenium
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
from sele... |
from numpy import *
from matplotlib.pyplot import *
data = loadtxt('random.dat').transpose()
data[0] /= 1e6
plot(data[0],zeros_like(data[0]),'k--')
errorbar(data[0],data[1]-np.pi,data[2],label='drand48')
errorbar(data[0],data[3]-np.pi,data[4],label='mt19937')
legend()
xlabel('million samples')
ylabel('estimate - $\\pi... |
import _plotly_utils.basevalidators
class SliderValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(
self, plotly_name='sliderdefaults', parent_name='layout', **kwargs
):
super(SliderValidator, self).__init__(
plotly_name=plotly_name,
parent_name=pa... |
import ordenamiento as order
class Node:
def __init__(self, numero):
self.numero = numero
self.next = None
def get_data(self):
return numero
class Lista:
def __init__(self):
self.head = None
self.size = 0
# def ordenar(self):
# if self.vacio():
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
provides function to check if a string matches a regular expression
"""
from re import match
@staticmethod
def validate_by_regex(string, regex):
"""
checks if a string matches the regular expression
validate_by_regex(string, regex) -> (True|False)
str... |
# Generated by Django 2.1.5 on 2019-08-07 11:33
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('blog', '0074_auto_20190806_1315'),
]
operations = [
migrations.AlterField(
model_name='grouppost',
... |
# coding:utf-8
from socket import *
from time import ctime
import time
import struct
print("=====================时间戳TCP服务器=====================");
def ConfigServer():
HOST = '127.0.0.1' # 主机号为空白表示可以使用任何可用的地址。
PORT = 4444 # 端口号
BUFSIZ = 1024 # 接收数据缓冲大小
ADDR = (HOST, PORT)
tcpSerSock = socket(AF... |
"""Main app package."""
|
import unittest
from katas.kyu_7.noonerize_me import noonerize
class NoonerizeTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(noonerize([12, 34]), 18)
def test_equals_2(self):
self.assertEqual(noonerize([55, 63]), 12)
def test_equals_3(self):
self.assertEqua... |
# Generated by Django 3.2.4 on 2021-07-10 20:17
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('adminapp', '0009_auto_20210709_0156'),
]
operations = [
migrations.AlterModelOptions(
name='exhibit',
options={'verbose_name... |
import aiohttp
import requests
async def post_request(url, json, proxy=None):
async with aiohttp.ClientSession() as client:
try:
async with client.post(url, json=json, proxy=proxy, timeout=60) as response:
html = await response.text()
return {'html': html... |
#!/usr/bin/env python
__author__ = "Master Computer Vision. Team 02"
__license__ = "M6 Video Analysis"
# Import libraries
import os
import numpy as np
from util import *
from sort import *
from gaussian_back_sub import *
from train_color import *
from scipy import ndimage
import os.path
import numpy as np
dataset="o... |
from common.admin import create_admin
from starwars.models import ALL_MODELS
for model in ALL_MODELS:
create_admin(model)
|
from django.shortcuts import render
import requests
from rest_framework import viewsets
from .models import Weather
from .serialize import WeatherSerializer
# Create your views here.
class WeatherView(viewsets.ModelViewSet):
queryset = Weather.objects.all()
serializer_class = WeatherSerializer
|
from spack import *
import os
import distutils
class Madgraph5amcatnlo(Package):
homepage = "https://launchpad.net/mg5amcnlo/"
url = "http://cmsrep.cern.ch/cmssw/repos/cms/SOURCES/slc7_amd64_gcc810/external/madgraph5amcatnlo/2.6.0/MG5_aMC_v2.6.0.tar.gz"
version('2.6.0', sha256='ba182a2d85733b3652afa... |
import gffpandas.gffpandas as gffpd
import pandas as pd
import sys
import time
import multiprocessing as mp
import pysam
import itertools
bam=sys.argv[1]
cores=sys.argv[3]
gff=sys.argv[2]
#bam="data/120796AAligned.sortedByCoord.out.mkdup.bam"
#cores=4
#gff="data/Homo_sapiens.GRCh37.87.chr.gff3"
annotation = gffpd.r... |
from marshmallow_sqlalchemy import ModelConverter
from marshmallow import fields
from citext import CIText
class AppModelConverter(ModelConverter):
"""
Partly override the marshmallow_sqlalchemy converter.
"""
SQLA_TYPE_MAPPING = dict(
list(ModelConverter.SQLA_TYPE_MAPPING.items()) +
[(... |
class Chubs:
fat = 0 #pounds
name = 'generic chubs'
def eat(self, pounds_of_food):
self.fat = self.fat + pounds_of_food / 2
print("burp")
poop = pounds_of_food / 2
return poop
def __init__(self, pounds, name):
print('hit init')
self.fat = pounds
if... |
import matplotlib.pyplot as plt
import os.path as pth
import sys
# Pull data from log file
def GetData(logfile):
if not pth.exists(logfile): # checking of the existence of log file
print('Cannot read log file!')
return []
with open(logfile) as f: # reading of data from log file
data = f... |
"""
Created by Alex Wang on 2018-2-27
Poisson Rescontruct
https://gist.github.com/jackdoerner/b9b5e62a4c3893c76e4c
"""
import cv2
def mask_det(maskpath): # maskpath为截取的水印样本
img = cv2.imread(maskpath,0)
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0)
sobely = cv2.Sobel(img,cv2.CV_64F,0,1)
sobelxy = numpy.... |
import sys
import os
f = open("C:/Users/user/Documents/python/atcoder/ABC118/import.txt","r")
sys.stdin = f
# -*- coding: utf-8 -*-
n,m = map(int,input().split())
k = [0]
a = [[0]*(n+1)]*(n+1)
for i in range(1,n+1):
raw = list(map(int,input().split()))
k.append(raw[0])
tmp = [0] + raw[1:]
... |
from datetime import timedelta
def arrayfy_ls(ls):
return str(ls).replace('(', '[').replace(')', ']').replace("'", '"')
class BusTrip:
def __init__(self, from_row, to_row):
self.bus_id = []
self.bus_dr = []
for rw1 in from_row:
for rw2 in to_row:
if rw1[0... |
import os
import json
import datetime
from tqdm import tqdm
import csv
from datetime import datetime
directory = "messages/inbox"
folders = os.listdir(directory)
if ".DS_Store" in folders:
folders.remove(".DS_Store")
for folder in tqdm(folders):
print(folder)
for filename in os.listdir(os.path.join(dire... |
R1=float(input("R1= "))
R2=float(input("R2= "))
S1=3.14*(R1**2)
S2=3.14*(R2**2)
S3=S1-S2
if (R1>R2):
print(S1)
print(S2)
print(S3)
else:
print("It is not true!!!")
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('scrub_csv', '0005_uploader_user'),
]
operations = [
migrations.RemoveField(
model_name='document',
n... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('occ_survey', '0031_structure'),
]
operations = [
migrations.CreateModel(
name='ControlAdjustments',
... |
import random
import nltk
text="""A trade war is an economic conflict resulting from extreme protectionism in which states raise or create tariffs or other trade barriers against each other in response to trade barriers created by the other party.Increased protection causes both nations' output compositions to move tow... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Filename: step02_rerun_preliminary_regression
# @Date: 2020/3/10
# @Author: Mark Wang
# @Email: wangyouan@gamil.com
"""
python -m SortData.ConstructVariable.step02_rerun_preliminary_regression
"""
import os
from Constants import Constants as const
from Utilities.gene... |
import socket
import struct
import binascii
import sys, os
class ClientTable_Handler(object):
def validate_passkey(self,mac,passkey):
tbl = open("/var/www/cgi-bin/ClientTable.txt").readlines()
valid = False
keyID = None
for line in range(len(tbl)):
if mac in tbl[line]:
... |
from decimal import Decimal as Dec, getcontext
def PI(maxK=70):
getcontext().prec = (maxK*14) #For ther test values, between 14.19 and 14.4 - Wolfram says gains about 14 digits per term...
print "Ready to start:"
K, M, L, X, S = 6, 1, 13591409, 1, 13591409
for k in xrange(1, maxK+1):
M = (... |
# author: Shuaishuai Sun
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
app = Flask(__name__, template_folder='templates', static_folder='static')
app.config['SECRET_KEY'] = 'Thisissuppose... |
# 1.使用测试套件批量执行用例的顺序是?
# 如果是按照模块导入的方式将测试用例添加测试套件,执行顺序为添加先后顺序
# 如果是按照discover的方式将测试用例添加到测试套件,是按照ASCII码顺序从小到大执行的
#
# 2.将用例加载到测试套件中,有哪几种方式?
import unittest
# unittest.defaultTestLoader.discover() # 加载路径下所有以test开头的测试用例
# unittest.TestLoader.loadTestsFromModule() # 加载想要测试的模块下的测试用例
# 3.编写如下单元测试
# 将上一次作业中的两数相减测试类与两数相除测试类的... |
import json
import urllib
from django.http.response import HttpResponseRedirect
from django.contrib import messages
from django.http import Http404
from django.contrib.auth import login as auth_login
class LoginAjaxMixin(object):
"""
Mixin which authenticates user if request is an ajax request
"""
de... |
from django.test import TestCase, Client
from users.models import User
class WalletTestCase(TestCase):
def setUp(self) -> None:
c = Client()
url = '/api/user/create'
new_user = {
'email': 'newuser@email.com',
'username': 'NewUser',
'password': 'NewUserP... |
from src.contracts.ethereum.erc20 import Erc20
from src.contracts.ethereum.event_listener import EthEventListener
from src.contracts.ethereum.multisig_wallet import MultisigWallet
from src.signer.erc20.impl import _ERC20SignerImpl
from src.signer.eth.signer import EtherSigner
from src.util.common import Token
from src.... |
import pandas as pd
import numpy as np
import json
import os
# This script does four things :
# Delete recommended baskets with id 1111111111111
# Delete too old baskets for which we have no data available for training
# Delete useless columns
# Convert taffy to csv
def clean_taffy_liste(root_dir, director... |
#!/usr/bin/python
# coding=utf8
__author__ = "zhangchitc@gmail.com"
class Paper:
def __init__ (self, title, abst):
self.title = title
self.abst = abst
self.authors = []
def add_author (self, author):
self.authors.append (author)
def __str__ (self):
ret = "Title:... |
print("Ravi Hamse") |
''' Copyright 2012 Smartling, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this work except in compliance with the License.
* You may obtain a copy of the License in the LICENSE file, or at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by appli... |
import urllib.request, urllib.error, urllib.parse
import json
address = input("Enter a location: ")
serviceurl = 'http://py4e-data.dr-chuck.net/json?'
api_key = 42
parms = dict() # the dictionary is used to be a part the the URL later
parms['address'] = address
parms['key'] = api_key
url = serviceurl + urllib.parse... |
#!/usr/bin/python
count = 1
word = '<span class="word"><a class="swd" href="x-dictionary:r:'
a = '">'
wd = 'word</a></span>'
left = '<span class="left"><a class="slf" href="x-dictionary:r:'
lb = 'leftpage</a></span>'
right = '<span class="right"><a class="srt" href="x-dictionary:r:'
rb = 'right</a></span>'
while (count... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 04 10:16:17 2017
@author: liuka
"""
import cv2
import numpy as np
import os
import time
import pdb
import pyaudio
import wave
import utils
from array import array
class Audio(object):
def __init__(self):
None
#self._cap = cv2.Vid... |
from Pessoa import Pessoa
def insere_dados():
nome = input("Digite seu nome: ")
idade = int(input("Digite sua idade: "))
sexo = input("Digite seu sexo (M ou F): ")
cidade = input("Digite sua cidade: ")
estado = input("Digite seu estado (ex. CE): ")
return Pessoa(nome, idade, sexo, cidade, esta... |
import pandas as pd
def create_mock_pv_info():
"""Creates PV info data frame.
:return: (*pandas.DataFrame*) -- mock PV info.
"""
plant_code = [1, 2, 3, 4, 5]
state = ["UT", "WA", "CA", "CA", "CA"]
capacity = [10, 5, 1, 2, 3]
single = ["N", "Y", "Y", "Y", "Y"]
dual = ["Y", "N", "N", "N... |
#import rospy
#from nav_msgs.msg import Odometry
#from geometry_msgs.msg import Twist
import numpy as np
import torch
from torch.utils.data import TensorDataset, DataLoader
import time
import matplotlib.pyplot as plt
from numpy.linalg import inv
from torch.utils.data import TensorDataset, DataLoader
import anfis
from ... |
import sqlite3
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from kennelapp.models import Cat
from kennelapp.models import Kennel
# from kennelapp.models import model_factory
from ..connection import Connection
def get_cat(cat_id):
with sqlite3.connect(Connection.db... |
# VOWELS = 'aeiou'
#
#
# def disemvowel(string):
# return ''.join(a for a in string if not a.lower() in VOWELS)
def disemvowel(s):
return s.translate(None, 'aeiouAEIOU')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'chendaopeng'
import os, logging
logging.basicConfig(level=logging.INFO)
import asyncio, os, json, time
from datetime import datetime
from aiohttp import web
from datetime import datetime
from www.app.orm import createpool
from jinja2 import Environment, Fi... |
import sqlite3
import csv
import xlrd
import xlwt
import pandas as pd
# 返回所有对应的营销人员已离职的用户
class inertialTestersQuery:
'''
选择20190501~20190621
期间,跟投1次或2次即放弃的用户5名
'''
'''
找出所有在某一个日期之后有阿尔法跟投的用户
日期格式: 20190621
'''
# ['13917035937'...]
def getallInertialTestersMobile(self):
... |
#!/usr/bin/env python
# coding=utf-8
from torch.utils.data import DataLoader
import torch
from PA100KDataset import PA100KDataset
from HydraPlusNet import *
import numpy as np
from torchvision import transforms
from torch.autograd import Variable
test_batch_size = 1
load_path = "./weight/InceptionV3_5000.weight"
l... |
from main.page.base import BasePage
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
class InboxTalkPage(BasePage):
_pl = "inbox... |
def to_weird_case(string):
return ' '.join(''.join(a.upper() if i % 2 == 0 else a.lower() for i, a in
enumerate(word)) for word in string.split())
|
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from .models import Resource, Manager
def validate_manager_name(value):
managers = Manager.objects.filter(name=value)
if managers.count() > 0:
raise ValidationError('Manager with name "{}" alread... |
import json
import mock
from pygeoirish.geocoder import (
assemble_comparison,
base_filter,
read_townlands,
serialize,
extract_prefered_addresses,
geocode
)
from .fixtures import (
fixture_test_assemble_comparison,
fixture_assemble_comparison_onedistance_nexac,
fixture_items_base_fil... |
from metrics import full_wer
import sys
system = sys.argv[1]
code = sys.argv[2]
if system == "microsoft" or system == "msoft":
system = "msoft"
sub_dir = "msoft/"
elif system == "ibm":
sub_dir = "ibm/"
elif system == "google":
sub_dir = "google/"
else:
print("System not implemented") ## TODO Add e... |
''' download all relevant articles similar to original articles'''
#trainFile = '../data/tagged_data/whole_text_full_city/train.tag'
import sys, pickle, pdb
import query as query
from constants import int2tags
from train import load_data
NUM_ENTITIES = len(int2tags)
#EMA queries
#EXTRA_QUERY='( state | country | in... |
#!/usr/bin/env python
# -*- coding=utf-8 -*-
__author__ = 'jimit'
__CreateAt__ = '2019\3\7 15:28'
from django.contrib.auth.decorators import login_required
class LoginRequiredMixin(object):
@classmethod
def as_view(cls, **initialkwargs):
view = super(LoginRequiredMixin, cls).as_view(**initialkwargs)
... |
# coding=utf-8
# @Author: wjn
from api.browser.api_browser_action import BrowserAction # case需修改
from common.util import TYRequest
import unittest
from common.get_value import GetValue
from common.get_log import LogInfo
import json
import time
class TestBrowserActionAjax(unittest.TestCase, GetValue, LogInfo): # cas... |
import datetime
import hashlib
import logging
import os
import random
import re
import string
if __name__ == "__main__":
print('This script only contains functions and cannot be called directly. See demo scripts for usage examples.')
exit(1)
# Normalize path (replace '\' and '/' with '\\').
def normalize_pat... |
from django.urls import path
from . import views
app_name = 'invoices'
urlpatterns = [
path('', views.InvoiceListView.as_view(), name='invoice_list'),
path('create/', views.InvoiceCreateView.as_view(), name='invoice_create'),
path('update/<int:pk>/', views.InvoiceUpdateView.as_view(), name='invoice_update... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.task.chan... |
from .BaseEditor import BaseEditor
from .ScrubSpinBox import DoubleScrubSpinBox, MinVal, MaxVal
from PyQt5 import QtCore
class BaseVecEditor(BaseEditor):
class ComponentSpinBox(DoubleScrubSpinBox):
def __init__(self, editor, component):
DoubleScrubSpinBox.__init__(self, editor)
s... |
"""SensorGrid and Sensor Schema"""
from pydantic import Field, constr
from typing import Optional
from .._base import NoExtraBaseModel
from .wea import Wea
class _GlowHemisphere(NoExtraBaseModel):
"""Hidden base class for Ground and SkyHemisphere."""
r_emittance: float = Field(
default=1.0,
... |
import turtle
#Initialization
turtle.speed(0)
turtle.pu()
######
#changeColor variables
colorList = ["black","blue", "red", "green", "yellow", "magenta", "orange", "purple"]
currentColor = 1
#changeShape variables
shapeList = ["circle", "square", "triangle", "arrow"]
currentShape = 0
#changeSize
lengthSize = 1
widthSiz... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from textwrap import dedent
from typing import Callable
import pytest
from pants.backend.python.goals.publish import (
PublishPythonPackageFieldSe... |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
MAX_VOLUME = 100
BACK_FADE_VOLUME = 20
BACK_VOLUME = 30
FRONT_VOLUME = 120
import subprocess
from time import sleep
PWD = '/home/shhdup/fade_play/'
BACK_MUSIC = (
'back2.mp3',
'back1.mp3',
)
FRONT_MUSIC = (
('01.mp3', 'Чтобы стать настоящим'),
('02.mp3... |
# coding: utf-8
# In[1]:
import numpy as np
# In[2]:
X = np.loadtxt("./data/encoded_train_150.out"); # this is the latent space array
print "load data shape:", X.shape;
# In[3]:
#from sklearn.manifold import TSNE;
X1 = X[::10];
#X_embedded = TSNE(n_components=3).fit_transform(X1);
#print "after TSNE operati... |
try:
from tkinter import *
except:
from Tkinter import *
import sys
sys.path.append('../src/org')
from gameplay import PointItem as pi
from maps import Map1
from display import DrawingGenerics
import unittest
class test_PointItem(unittest.TestCase):
def setUp(self):
root = Tk()
gameC... |
# This is where the answers to Chapter 8 questions for the BSS Dev RampUp go
# Name: |
from __future__ import unicode_literals, print_function, division
__author__ = 'petrbouchal'
"""
Created on Jul 10, 2012
@author: petrbouchal
Collect all data from No. 10 business plan API, build a database with this data,
as well as with basic completion status data calculated, and deliver an analytical report on a... |
#!/usr/bin/env python3
import sys
def get_target(word, users, step):
if word[-1] in ':,':
word = word[:-1]
# Only count it if the user appeared recently
if step - users.get(word, -1000) < 200:
return word
else:
return None
def save_stats(stats, filename, ctime, msg_per_user, ... |
import logging
import os
from datetime import datetime
from flask import render_template, Blueprint, request, current_app
from app.user import User
from app.utils import allowed_file
from app.file_manager import FileManager
from app.queue_manager import QueueManager
api = Blueprint("api", __name__)
logger = logging... |
from django import forms
from django.utils.translation import gettext as _
from django.utils.safestring import mark_safe
PRESENCE_CONFIRMATION = (
(1, _('Yes of course :)')),
(0, _('No, unfortunately not :('))
)
HOTEL_CHOICES = (
(0, _('No')),
(1, _('Yes'))
)
class RsvpGuestsNumForm(forms.Form):
... |
class Solution(object):
def titleToNumber(self, columnTitle):
"""
https://leetcode.com/problems/excel-sheet-column-number/
26-base conversion to number does the trick here
"""
p = 1
x = 0
for i in range(len(columnTitle)-1, -1, -1):
c = ord(columnTi... |
VOWELS = set('aeiouAEIOU')
def consonant_count(s):
return sum(1 for a in s if a.isalpha() and a not in VOWELS)
|
import pdb
import argparse
#import calendar
import numpy as np
import matplotlib.pyplot as plt
import iris
import iris.plot as iplt
import iris.coord_categorisation
import cmdline_provenance as cmdprov
import cmocean
# next block would be self-published
def read_data(fname, month):
"""Read an input data file"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
import numpy as np
def default_number_of_knots(x):
return min(len(np.unique(x)) // 4, 35)
def add_boundary_knots(ks, p):
b0 = np.asarray([ks[0] for _ in range(p)])
b1 = np... |
'''
Digits
Given two integers, n and m, how many digits have nm?
Examples:
2 and 10 - 210 = 1024 - 4 digits
3 and 9 - 39 = 19683 - 5 digits
Input
The input is composed of several test cases. The first line has an integer C, representing the number of test cases.
The following C lines contain two integers N and M (1... |
from selenium.webdriver.remote.remote_connection import RemoteConnection as RemoteConnection
class FirefoxRemoteConnection(RemoteConnection):
def __init__(self, remote_server_addr, keep_alive: bool = ...) -> None: ...
|
# Generated by Django 3.2.5 on 2021-07-27 17:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('App', '0002_email_verification'),
]
operations = [
migrations.AddField(
model_name='profile',
name='image',
... |
import pandas as pd
from nipype.pipeline.engine import Node, Workflow, MapNode
import nipype.interfaces.utility as util
import nipype.interfaces.io as nio
import nipype.interfaces.fsl as fsl
import nipype.interfaces.freesurfer as fs
import nipype.interfaces.afni as afni
import nipype.interfaces.nipy as nipy
import nipy... |
import unittest
from katas.kyu_7.filter_long_words import filter_long_words
class FilterLongWordsTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(filter_long_words(
'The quick brown fox jumps over the lazy dog', 4),
['quick', 'brown', 'jumps'])
|
REST_HOST = '0.0.0.0'
REST_PORT = '5000' |
#!/usr/bin/python3
age = int(input("please input dog's age:"))
#print("")
if age < 0:
print("are you kidding me ?")
elif age == 1:
print("equal age 14 years old")
elif age == 2:
print("equal age 22 years old")
elif age > 2:
human = 22 + (age - 2)*5
print("equal human's age is: ", human)
# quit tip... |
import requests
import json
import numpy as np
import os
import re
threads = []
# url = 'http://srv-s2d16-22-01/es/'
url = 'http://srv-s2d16-22-01'
post = ':11001/'
get = '/es/'
dataindex = 'vdm'
# scroll_params = {
# 'size':100,
# 'scroll': '1m'
# }
# r = requests.get(url + get + 'data-' + dataindex + '/_sear... |
# Exercício 8.4 - Livro
def areaTriangulo (base, altura):
area = (base * altura) / 2
return area
at = areaTriangulo(5, 8)
print(at)
|
def how_much_coffee(lst):
result = sum(a.isalpha() if a.islower() else 2 * a.isalpha() for a in lst)
return 'You need extra sleep' if result > 3 else result
|
import arcade
arcade.open_window(600, 600, "Drawing Example")
arcade.set_background_color(arcade.color.COOL_BLACK)
arcade.start_render()
#Dibujar mar
arcade.draw_lrtb_rectangle_filled(0, 600, 250, 0, arcade.color.QUEEN_BLUE)
#Dibujar luna
arcade.draw_circle_filled(300,450,140,arcade.color.PLATINUM)
#Dib... |
file1 = open("data.csv", "r")
file2 = open("cleaned_data.csv", "w")
file2.write(file1.readline())
lines = file1.readlines()
lines2 = []
file1.close()
for line in lines:
line_first = line[0:line.find(',')]
line_second = line[line.find(',')+1:]
new_line = ""
for c in line_first:
if (".\/*-+?'!\... |
from time import sleep
findAlpha = list('abcdefghijklmnopqrstuvwxyz')
for x in range(26):
findAlpha[x] = findAlpha[x].upper()
class Piece():
def __init__(self, colour, position):
self.position = position
self.colour = colour
def checkKill(self, dest): # check if the move is ki... |
import random
import string
def random_string(minimum, maximum=None):
if maximum is None:
maximum = minimum
count = random.randint(minimum, maximum)
return "".join(random.choice(string.ascii_letters) for x in xrange(count))
def random_integer(digits):
start = 10 ** (digits - 1)
end = (10 ... |
#!/usr/bin/env python
import rospy
from hektar.msg import encoderPos, wheelVelocity, Move
from hektar.cfg import DeadReckonConfig
from dynamic_reconfigure.server import Server
from std_msgs.msg import Bool
MAX_SPEED = 127
class Dead_Reckon():
def __init__(self):
self.wheels_pub = rospy.Publisher("wheel_output",... |
# Generated by Django 3.0.5 on 2020-04-28 14:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='product',
name='price',
field=m... |
'''
Created on Jul 15, 2013
@author: emma
'''
from UnitTesting.page_objects.base_page_object import base_page_object
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
class acp_profi... |
import ast
from datetime import datetime, timezone, time
from decimal import Decimal, ROUND_HALF_UP
import datetime, pytz, time, json
import quicklook.calculations.garmin_calculation
from quicklook.calculations.converter.fitbit_to_garmin_converter import timestring_to_datetime
def apple_steps_minutly_to_quartly(summ... |
# Generated by Django 2.2.6 on 2019-11-11 17:42
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tasks', '0014_auto_20191111_1741'),
]
operations = [
migrations.AlterField(
model_name='task',
name=... |
import base64
import MySQLdb as mdb
from . import view_all
def main():
port='65535'
pwd='cnmf.net.cn'
group=''
con = None
ip=view_all.ip
try:
con = mdb.connect('127.0.0.1', 'root','xx', 'test')
cur = con.cursor()
cur.execute("select * from xx")
data = cur.... |
"""Supervisor definition anc control.
Linux:
Manages daemontools-like services inside the container.
For each application container there may be multiple services defined, which
are controlled by skarnet.org s6 supervision suite.
Application container is started in chrooted environment, and the root
directory struc... |
import itertools
class Card:
def __init__(self, suit, value):
self.mSuit = suit
self.mValue = value
self.mColor = ""
if suit == "clubs" or "spades":
self.mColor = "black"
else:
self.mColor = "red"
def get_value(self):
ret... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.