text stringlengths 38 1.54M |
|---|
def protein_database_parser(counter):
database = list()
file = open("Database.txt", "r")
temp = ""
read_flag = False
for line in file:
if counter == 0:
break
if not line:
continue
if line[0] == '>' and not read_flag:
read_flag = True
... |
## Copyright [2017-2018] UMR MISTEA INRA, UMR LEPSE INRA, ##
## UMR AGAP CIRAD, EPI Virtual Plants Inria ##
## Copyright [2015-2016] UMR AGAP CIRAD, EPI Virtual Plants Inria ##
## ##
## This file is ... |
while True:
num = int(input("Please write your number here: "))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(f"\n{num} is not a prime number\n")
print(f"{i} times {num//i} is {num}")
break
else:
pri... |
#
# Client
# Connects SUB socket to tcp://localhost:5556
# Menerima hasil
#
import zmq
import pickle
# Socket to talk to server
context = zmq.Context()
socket = context.socket(zmq.SUB)
print "ok"
socket.connect("tcp://localhost:5556")
socket.connect("tcp://localhost:5557")
# Subscribe to zipcode,... |
#!python3
inputFile = open("input.txt", "r")
outputFile = open("output.txt", "w")
testCases = int(inputFile.readline())
for testCase in range(1, testCases + 1):
phoneStr = inputFile.readline()
phoneStr = phoneStr.rstrip()
charCount = [0] * 26
numCount = [0] * 10
for index in range... |
import sys
sys.stdout = sys.stderr
# path is in vhost file, not here like in docs at.. http://flask.pocoo.org/docs/0.10/deploying/mod_wsgi/#creating-a-wsgi-file
# sys.path.insert(0, '/var/www/html/python/flask21xx')
from pdb218 import app as application |
from plone.app.contentrules.api import edit_rule_assignment
from plone.app.contentrules.testing import PLONE_APP_CONTENTRULES_FUNCTIONAL_TESTING
from plone.app.testing import applyProfile
from plone.app.testing import login
from plone.app.testing import setRoles
from plone.app.testing import TEST_USER_ID
from plone.app... |
# FUNCTIONS
'''
- *args **kwags
- returns extra arguments in tuples, and extra key word args in dictionaries
- extra arguments and keyword arguments
- positional arguments = args based on position in func call
- keyword args = keyword = value, when theres an arg in calling a func which has a var set to
it mean... |
import mdtraj as md
import sys
import numpy as np
xtc = sys.argv[1]
pdb = sys.argv[2]
traj = md.load_xtc(xtc, top=pdb)
pairs = traj.top.select_pairs('all','all')
d = md.compute_distances(traj,pairs)
print(np.max(d))
|
"""
Python mapping for the MetricKit framework.
This module does not contain docstrings for the wrapped code, check Apple's
documentation for details on how to use these functions and classes.
"""
import sys
import Foundation
import objc
from . import _metadata, _MetricKit
sys.modules["MetricKit"] = mod = objc.ObjC... |
class Solution:
def reverse(self, x: int) -> int:
"""Purpose: Reverses the digits of a 32-bit signed integer.
Note: Assume we may only store integers within 32-bit signed
integer range [-2^31, 2^31 - 1].
Example: -123 -> -321
1234 -> 4321
120 -> 21
"""
sign = 1
if ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 2 01:35:00 2020
@author: Seo
"""
import os
from mypyqtimports import *
class FileOpenWidget(QWidget):
def __init__(self, callingWidget):
super().__init__()
self.title = 'Open Database'
self.left = 10
self.top = 10
self.width... |
from flask_wtf import FlaskForm
from wtforms.validators import InputRequired, Length
from flask_login import UserMixin
from wtforms import StringField, PasswordField, BooleanField, SelectField, IntegerField, RadioField, DateField, TimeField, FloatField
from wtforms.widgets import TextArea
import helpers_constants
cla... |
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('https://www.dal.ca/academics/programs.html')
bs = BeautifulSoup(html, "html.parser")
complete_data = bs.find_all('div', { "class" : "autoSearcher section"})
f = open("Sub_programs.xml","w",encoding = "utf-8")
f.write('<?xml version="1.0" e... |
#!/usr/bin/env python
'''
a stupidly basic pipeline for testing
'''
import argparse
import os
import sys
import datetime
import subprocess
def log(sev, msg):
when = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
sys.stderr.write('{0}: {1} {2}\n'.format(when, sev, msg))
def run_command(line, command, con... |
## -*- coding: UTF8 -*-
## manager.py
##
## Copyright (c) 2019 analyzeDFIR
##
## Permission is hereby granted, free of charge, to any person obtaining a copy
## of this software and associated documentation files (the "Software"), to deal
## in the Software without restriction, including without limitation the rights
#... |
###########################################
# Desc: Converts Imperial measurements into metric measurements
#
# Author: Zach Slaunwhite
###########################################
#Ready for marking
def main():
# CONSTANTS
TONSCONVERTED = 35840
STONESCONVERTED = 224
POUNDSCONVERTED = 16
KILOSCONVE... |
# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import json
# BCM GPIO编号
pins = [17,18,27,22,23,24,25,4]
def gpio_setup():
# 采用BCM编号
GPIO.setmode(GPIO.BCM)
# 设置所有GPIO为输出状态,且输出低电平
for pin in pins:
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, GPIO.LOW)
... |
from odoo import api, fields, models, _
class ResUsers(models.Model):
_inherit = "res.users"
room_ids = fields.Many2many('medical.hospital.oprating.room', 'user_room_rel',
'room_id', 'user_id', "Allowed Room Columns")
physician_ids = fields.Many2many('medical.physician', '... |
import pymysql
cinema_db = pymysql.connect("baulne.paulf.tk", "anton", "medvedev", "cinema") #Connection à la database cinema
cursor = cinema_db.cursor()
sql_request = "SELECT * FROM Acteurs"
cursor.execute(sql_request)
response = cursor.fetchall()
print(response) |
import matplotlib.pyplot as plt
from nessai.samplers.importancesampler import ImportanceNestedSampler as INS
import numpy as np
import pytest
@pytest.fixture(autouse=True)
def auto_close_figures():
"""Automatically close all figures after each test"""
yield
plt.close("all")
def test_plot_state(ins, hist... |
from django.contrib import admin
from projects.models import Project,Person
# from .models import Person,Project
# Register your models here.
class ProjectsAdmin(admin.ModelAdmin):
"""
定制后台管理类
"""
#指定在修改(新增)中需要显示的字段
fields = ('name','leader','tester','programer','publish_app')
list_display = ['... |
import pylibimport
pylibimport.init_finder(download_dir='./sub/import_dir/', install_dir='./sub/target_dir')
import custom_0_0_0
print(custom_0_0_0.run_custom())
import dynamicmethod_1_0_2
import dynamicmethod_1_0_3
print(dynamicmethod_1_0_2)
print(dynamicmethod_1_0_3)
assert dynamicmethod_1_0_2 is not dynamicmeth... |
from django.urls import path, include
from AppTwo import views
urlpatterns = [
path('users/', views.user),
] |
#! /usr/bin/env python3
# import csv
import MySQLdb
import sys
# from datetime import datetime,date
con = MySQLdb.connect(host='localhost',port=3306,db='my_suppliers',\
user='root',passwd='root')
c = con.cursor()
c.execute("""insert into Suppliers values (%s,%s,%s,%s,%s);""",['haha_input','fun','990','1510.0','2008/0... |
import numpy as np
from ed import *
from scipy.sparse import spdiags
from scipy.sparse.linalg import eigsh
L = 4
U = 4
μ = 0
print("L is ", L)
print("U is ", U)
print("μ is ", μ)
H0 = H_free_apbc(L, μ=μ)
H02 = H_free(L, m=1)
HU = H_int(L, U=U)
E0, EU, v0 = energies(L, H02, HU)
print(
"\nExact ED energies are:... |
from movements import app, actions
from movements.forms import ClassForms
from flask import render_template, request, url_for, redirect
import sqlite3
from config import *
import requests
url_api_crypto = "https://pro-api.coinmarketcap.com/v1/tools/price-conversion?amount={}&symbol={}&convert={}&CMC_PRO_API_KEY={}"
... |
import os
import shutil
import unittest
from chariot.storage import Storage
def resolve(path):
return os.path.abspath(path)
class TestStorage(unittest.TestCase):
def test_path(self):
root = os.path.join(os.path.dirname(__file__), "../../data")
storage = Storage(root)
correct_path = ... |
# for (~하는 동안), range(a, b) - b는 불포함
# while (~하는 동안) - for와 용법이 다름
# for
for num in range(1, 10): # cf. [1, 2, 3][0:2]
print(num)
num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for num in num_list:
print(num)
# while
# while True: # 무한루프 - while의 특성이 False로 바뀔때까지 계속 출력
# print(1)
# 끝내려면 cmd + c
a = 1
while a <... |
from sys import argv, exit
height = int(argv[1])
width = int(argv[2])
n = int(argv[3])
def seek_point(x, y):
p = complex(3.0 * x / width - 2.0, 2.0 * y / height - 1.0)
z = complex(.0, .0)
for i in range(n):
z = z * z + p
if abs(z) >= 2.0:
break
return i
l = []
for y in x... |
import requests
def subset(a, b, present=[]):
subset = all((k in a and a[k] == v) for k, v in b.items())
present = all(key in a for key in present)
return subset and present
def post_subset(url, json, expected_subset, present):
r = requests.post(url, json=json)
assert r.status_code == requests.c... |
import random
from base64 import encodebytes
class CustomerProxyMiddleware(object):
def process_request(self, request, spider):
proxy = random.choice(PROXIES)
request.meta['proxy'] = "http://%s" % proxy['ip_port']
print("-----------Proxy-----------" + proxy['ip_port'])
PROXIES = [
{'i... |
from random import randint
game_running = True
game_results = []
one_time = True
one_time2 = True
one_time_game = True
def calculate_monster_attack(attack_min, attack_max):
return randint(attack_min, attack_max)
def calculate_player_heal(heal_min, heal_max):
return randint(heal_min, heal_max)
def game_end... |
#!/usr/bin/python
import errno
import git
from git.exc import InvalidGitRepositoryError
import os
from pathlib import Path
import platform
import shutil
import stat
import subprocess
from sys import argv
from twrpdtgen.misc import append_license
from twrpdtgen.misc import error
from twrpdtgen.misc import get_device_ar... |
"""
使用 xpath 将猫眼 100 的全部电影信息全部提取出来。
目标网址:https://maoyan.com/board/4?offset=90
name(电影名)
star(主演)
releasetime(上映时间)
score(评分)
"""
|
#! /usr/bin/env python3
#
# Copyright (c) 2016, 2017, 2018 Forschungszentrum Juelich GmbH
# Author: Yann Leprince <y.leprince@fz-juelich.de>
#
# This software is made available under the MIT licence, see LICENCE.txt.
"""Downscaling is used to create a multi-resolution image pyramid.
The central component here is the ... |
#!/usr/bin/python
import datetime
import getopt
import logging
import math
import pytz
import sys
from crate import client
from dateutil import parser
def main(argv):
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Setting up the connection to CrateDB (with command... |
import argparse
import pickle as pkl
import taichi as ti
import math
import numpy as np
import sklearn.cluster as cluster
from engine.mpm_solver import MPMSolver
import sys, os
sys.path.append(os.path.join(os.path.dirname("__file__"), '..', '..'))
from hgns.util import cluster_scene
def parse_mpm():
parser = arg... |
import fs_wrapper
from case_utility import *
from qrd_shared.case import *
from test_case_base import TestCaseBase
import logging_wrapper
############################################
#author:
# liqiang@cienet.com.cn
#function:
# use the foreground camera to take a VGA picture
#precondition:
# there is a mount... |
# Defines two classes, Point() and NonVerticalLine().
# An object for the second class is created by passing named arguments,
# point_1 and point_2, to its constructor.
# Such an object can be modified by changing one point or both points thanks to the
# function change_point_or_points().
# At any stage, the object mai... |
import sys
sys.stdin = open('6109.txt')
t = int(input())
def reset(dir):
global n
if dir == 'up':
for x in range(n):
temp = []
for y in range(n):
if data[y][x] != 0 :
temp.append(data[y][x])
temp.append(0)
new_temp=[]
for index in range(len(temp)-1):
if temp[index] == temp[index+1]:
... |
from ResNet import ResNet
from DenseNet import DenseNet
from SENet import SENet
from keras.datasets import mnist
from keras.utils import to_categorical
import numpy as np
import argparse
import json
parser = argparse.ArgumentParser(description='Process the data and parameters')
# LOG, MODEL
parser.add_argument('--mod... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 3 19:38:25 2018
@author: 王磊
"""
import numpy as np
import matplotlib.pyplot as plt
#t=np.arange(0.,5.,0.2)
#plt.plot(t,t,'r--',t,t**2,'bs',t,t**3,'g^')
#plt.show()
#
#
#plt.plot([1,2,3,4])
#plt.ylabel('some numbers')
#plt.show()
#
#plt.plot([1,2,3,4],[... |
from behave import *
import ast
from lib.kata_generator_templater import KataGeneratorTemplater
@given("kata name underscored")
def set_up_params_for_humanize_kata_name(context):
context.templater = KataGeneratorTemplater("underscored_kata_name", [])
@when("method 'humanize_kata_name' is called")
def execute_huma... |
def replace_spaces(s):
characters = list(s)
for i, c in enumerate(characters):
if c == " ":
characters[i] = "%20"
return "".join(characters)
print replace_spaces("Mr John Smith ")
|
# Store another array and copy over non-zero elements to that
# array, zero element increment a counter- append that many
# zeroes to the end of the array
# O(n) space
# O(n) runtime
# [1, 10, 0, 2, 8, 3, 0, 0, 6, 4, 0, 5, 7, 0]
# [1, 10, 2, 8, 3, 6, ]
# index of last non_zero element =
# count = 3
# O(n) time, O(1... |
import unittest
from tests.printer_test import TestPrinter
if __name__ == '__main__':
unittest.main()
|
l1 =["Arvind","Hema","Bhavya","pooja","Nazreen"]
l2 = ["Bangalore","Tirupathi","Kolar","Bangalore","Mumbai"]
for l3 in zip(l1,l2):
print(l3) |
import numpy as np
arr=np.array([[1,2,3,4,7,8,9,10],[11,12,13,14,17,18,19,20]])
print(arr.reshape(4,4))
arr1=np.array([1,2,3,4,5,6,7,8,9,10,11,12])
newarr=arr1.reshape(2,3,2)
print("3D Array is:")
print(newarr)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .depot import MAX_FILE_SIZE
from .model import Object, Member
from sqlalchemy import (
Column, Integer, String, ForeignKey, DateTime, Boolean, sql, LargeBinary)
import sqlalchemy.orm
class Keylist(Object):
"""Ein Eintrag im Schlüsselbuch."""... |
import argparse
import torch
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
batch_size = 64
train_dataset = datasets.MNIST(root='/data/', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = datasets.... |
# -*- coding:utf-8 -*-
# Author: LiuSha
import os
import croniter
import importlib.util as import_module
from uuid import uuid1
from datetime import datetime
from dateutil.tz import tzlocal, gettz
from rq import get_current_job, worker
from rq_scheduler.utils import to_unix
from rq_scheduler.scheduler import Sche... |
# -*- coding: utf-8 -*-
# pragma pylint: disable=unused-argument, no-self-use
# (c) Copyright IBM Corp. 2010, 2019. All Rights Reserved.
"""Function implementation"""
import logging
from resilient_circuits import ResilientComponent, function, handler, StatusMessage, FunctionResult, FunctionError
from fn_cb_protectio... |
# howdy/views.py
from django.shortcuts import render
from django.views.generic import TemplateView
from django.http import HttpResponseRedirect
from .forms import NameForm
# Create your views here.
class HomePageView(TemplateView):
def get(self, request, **kwargs):
form = NameForm()
return render(... |
#!/usr/bin/env python3
import argparse
import logging
import imageio
from tqdm import tqdm
import pickle
parser = argparse.ArgumentParser()
parser.add_argument('--video', '-v', type=argparse.FileType('rb'))
parser.add_argument('--output', '-o', type=argparse.FileType('wb'))
args = parser.parse_args()
logging.basic... |
import pyshark
import argparse
import itertools
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
fig = plt.figure()
ax = fig.add_subplot(111)
request_time = 0
response_time = 0
file_name = ""
timestamp_tls_phone_to_server = []
timestamp_tls_server_to_phone =... |
#! /usr/bin/env python
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import argparse
import imp
import os
import re
import sys
import textwrap
import types
# A mar... |
from setuptools import find_packages, setup
print(find_packages())
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='Analysis into the disproportionate impact of Covid-19 on different groups through the prism of race. ',
author='Quotennial',
license='MIT',
)
|
#!/usr/bin/python
#Libreria
import sys
#colores
end = "\033[0m"
red = "\033[1;91m"
green = "\033[92m"
yellow = "\033[33m"
b = "\033[1m"
#Dominio a usar
dominio = sys.argv[1]
#Detectar que comando ingresa
def command(x):
if x == "hola":
print "hola"
elif x == "1":
print "https://www.google.com.pe/search?&hl... |
class Gift:
def __init__(self, name, difficulty):
self.name = name
self.difficulty = difficulty
def __str__(self):
return self.name + ";" + str(self.difficulty) |
import dss
import pandas as pd
from Battery_Sizing import BatterySizing
class PVSizing:
def __init__(self, periods):
BASE = '/mnt/6840331B4032F004/Users/MARTINS/Documents/Texts/Acad/OAU/Part 5/Rain Semester/EEE502 - Final Year Project II/Work/IEEE Euro LV/Master_Control.dss'
ENG = dss.DSS
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from collections import deque
class bnn(object):
# * this network is utilized to generate the parameters(two parameters:mu & sigma)
def __init__(self, observation_dim, action_dim, hidden_dim, max_logvar, min_logvar)... |
#!/usr/bin/env python
from __future__ import print_function
import rospy
import time
from threading import Thread, Event
import websocket
import pyaudio
try:
import thread
except ImportError:
import _thread as thread
import time
import json
import rospy
from std_msgs.msg import String
# global variable as "co... |
"""
A set of classes to help with organizing our graph data into
- Individual points
- X/Y coordinates
- Line segments
- A set of 2 points
- Rectanges
- A set of 2 lines
"""
class Point:
"""
An individual point on a graph with X/Y coordinates
"""
def __init__(self, x:int, y:int):
... |
# coding=utf-8
# if __name__ == "__main__":
# pass
# %%
"""
本版本用于在夜神模拟器上爬取链接,以及用于用链接爬取音频
"""
# %%
# import requests
# from bs4 import BeautifulSoup as bs4
# import urllib3
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
import pyperclip
import codecs
import cs... |
pais = "Ecuador "
ciudad = "Loja"
fecha_independencia = "18 de noviembre"
print(pais)
print(ciudad)
print(fecha_independencia) |
"""
演示协程 gevent
1、gevent 并不像 greenlet 需要手动调用 switch()切换任务。
2、要自动切换任务,前提是 gevent 碰到 延时操作。
3、gevent.sleep(1) 自带的延时操作
"""
# import gevent
# import time
# from gevent import monkey # 打补丁,将time的延时操作,转化为gevent的延时操作。
#
# monkey.patch_all() #自动将time的延时操作,转化为gevent的延时操作。
# def sing():
# for i in range(1, 5):
# ... |
from app import app, db
from app.models import User, Post, District, Hashtag, Url
from datetime import datetime, date, timedelta
unfilled = db.session.query(Post).\
filter(Post.created_at_dt == None).all()
indexCount = 0
for row in unfilled:
row.created_at_dt = row.created_at
db.session.add(row)... |
import numpy as np
from ClassCorrelacaoPerseptron5 import CorrelacaoPerseptron5
if __name__ == '__main__':
caminho = "/home/guilherme/Downloads/Tracos/lame/trace_lame_larger.txt"
c2 = CorrelacaoPerseptron5(caminho)
print("Perceptron 5 treinando")
c2.treinaModelo() |
# standard imports
import unittest
# third party imports
# local imports
from ENDFtk.MF13 import TotalCrossSection
class Test_ENDFtk_MF13_TotalCrossSection( unittest.TestCase ) :
"""Unit test for the TotalCrossSection class."""
chunk = ( ' 0.000000+0 0.000000+0 0 0 1 2922... |
import numpy as np
import matplotlib.pyplot as plt
import random
def filter(X, y, k):
m,n = X.shape
theta = np.zeros([n,1])
for i in range(m):
x_i = X[i]
y_i = y[i]
# find x_nh and x_nm
x_nh = -1
nh_dist = 0
x_nm = -1
nm_dist = 0
for a in r... |
#!/usr/bin/env python
# coding: utf-8
# For python 2 compatibility
from __future__ import unicode_literals
import optparse
import gitli
if __name__ == '__main__':
parser = optparse.OptionParser(
usage="""Usage: git-li <command> [command-options]
Commands:
init Initialize the git r... |
#Faça um programa que leia o cateto oposto, cateto adjacente e nos devolva o valor da hipotenusa usando o modulo math
import math
#h2 = ca2 + co2
#50 = 25 + 25
oposto = float(input("Digite o comprimento do cateto oposto: "))
adjacente = float(input("Digite o comprimento do cateto adjacente: "))
hipotenusa = math.hypot... |
import numpy
import random
def fingdcircle(adjmat):
n=adjmat.shape[0]
x=numpy.array([0 for i in range(n)])
visited=numpy.array([0 for i in range(n)])
k=0
x[k]=0
visited[x[k]]=1
while(k<n):
while(True):
x[k] = x[k] + 1
if (x[k] >= n):
visited[x... |
# USAGE
# python train_network.py --dataset images --model santa_not_santa.model
# set the matplotlib backend so figures can be saved in the background
import matplotlib
matplotlib.use("Agg")
# import the necessary packages
from keras.preprocessing.image import ImageDataGenerator
from keras import models
from keras ... |
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class MainWindow( QWidget ):
workingThread = QThread()
def __init__(self, parent = None):
QWidget.__init__(self, parent = None)
self.workingThread.start()
def closeEvent(self, event):
self.workingThread.stop() |
#!/usr/bin/env cctools_python
# CCTOOLS_PYTHON_VERSION 2.7 2.6
# Copyright (c) 2010- The University of Notre Dame.
# This software is distributed under the GNU General Public License.
# See the file COPYING for details.
# This program is a very simple example of how to use Work Queue.
# It accepts a list of files on ... |
import abc
from typing import Dict
from typing import List
import pandas as pd
import requests
from dateutil import parser
from requests.auth import HTTPBasicAuth
# Base Class For Git Insights
class RepoInsightsClient(abc.ABC):
def __init__(self, organization: str, project: str, repos: List[str], teamId: str, pr... |
import d2lzh as d2l
from DL_model import Net
from process_dataset import load_mnist
if __name__ == '__main__':
#尝试使用GPU
ctx=d2l.try_gpu()
#加载数据集
train_images,train_labels,test_images,test_labels=load_mnist()
#初始化模型
model=Net(x_train=train_images,y_train=train_labels,\
x_test=test_im... |
import requests,sys,os
import time
import math
from autotrading.machine.base_machine import Machine
from autotrading.machine.xcoin_api_client import *
import configparser
import json
import base64
import hashlib
import hmac
import urllib
# cur_dir = os.path.abspath(os.curdir)
# sys.path.append(cur_dir)
# PROJECT_HOME ... |
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l = len(nums)
if l == 0:
return -1
if l == 1:
if nums[0] == target:
return 0
return -1
... |
from collections import namedtuple
MockedBoto3Request = namedtuple(
"MockedBoto3Request", ["method", "response", "expected_params", "generate_error", "error_code"]
)
# Set defaults for attributes of the namedtuple. Since fields with a default value must come after any fields without
# a default, the defaults are a... |
#!/usr/bin/env
# This program converts .libsvm sparse format into .arff sparse format
# Development has been inspired by the following converter: https://goo.gl/hp3Cke
import argparse
from collections import OrderedDict
argumentParser = argparse.ArgumentParser()
argumentParser.add_argument('-i', '--inputFile')
argum... |
class queue:
def __init__(self):
self.items = []
def clear(self):
self.items = []
def peek(self):
return self.items[len(self.items)-1]
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0,item)
... |
import unittest
from django.test import RequestFactory, TestCase
from django_pgschemas.middleware import TenantMiddleware
from django_pgschemas.utils import get_domain_model, get_tenant_model
TenantModel = get_tenant_model()
DomainModel = get_domain_model()
class TenantMiddlewareRedirectionTestCase(TestCase):
... |
import glob
import numpy
import os
import subprocess
someNonExistantString = "someNonExistantString"
def getFaultyMassIndexList(process, suffix) :
massPointFile = "output_genParam/" + process + "/massPointInfo.txt"
massPointList = numpy.loadtxt(massPointFile, delimiter = ",")
nMass = massPointList.... |
def calcula_metros(empresa: str, num_talla_S: int, num_talla_M: int, num_talla_L: int) -> str:
metros = (num_talla_S*2) + (num_talla_M*2.5) + (num_talla_L*3)
return f"Para fabricar {num_talla_S} trajes talla S, {num_talla_M} trajes talla M, {num_talla_L} trajes talla L, para la empresa {empresa} se necesitan ... |
import datetime
import time
Hours = 24 * 60 * 60
Minutes = 60 * 60
Seconds = 60
set_day = None
set_hour = None
set_minute = None
set_second = 3
# after_time = True
__all__ = ['GetSleepSec']
class GetSleepSec:
def __init__(self):
self.run_count = 0 # 执行几次
# self.cal_method = True # 是否使用短间断循... |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(requests):
return render(requests,'home.html');
def index(requests):
return render(requests,'index.html');
def add(request):
name=0
num1 = request.GET["n1"]
num2 = request.GET["n2"]
return render(request,... |
import googlemaps
google_url = 'https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Washington,DC&destinations=New+York+City,NY&key='
api_key = 'AIzaSyBnSI5louf-p4SxBGhonqHgL_NYpztZro4'
gmaps = googlemaps.Client(key='AIzaSyBnSI5louf-p4SxBGhonqHgL_NYpztZro4')
consulta = gmaps.distance_matri... |
# Octothorp
print("A FEW THINGS")
# tells me true or false
print(5 < 3)
# whole number
print(float(9 / 8))
# floating point whole number
print(float(9 / 9))
print(6 + 9 + 4 + 20 / 6 - 9)
# intiger
print(9 / 8)
# variable
cars = 100
space_in_car = 4.0
drivers = 30
passengers = 90
cars_driven = drivers
cars_not_drive... |
# https://leetcode.com/problems/reverse-integer/
def reverse(x):
print(x)
if x >= 0:
xString = str(x)
result = int(''.join(reversed(xString)))
else:
xString = str(x)
negXstring = xString.strip('-')
print(negXstring)
result = int('-' + (''.join(... |
from tkinter import *
w = Tk()
Bbt = Button(w, text='아래쪽', padx=10).pack(side=BOTTOM) # bottom은 먼저 해줘야 할 듯
Tbt = Button(w, text='위쪽', padx=10).pack()
Lbt = Button(w, text='왼쪽', padx=10).pack(side=LEFT)
Rbt = Button(w, text='오른쪽', padx=10).pack(side=LEFT)
w.mainloop()
|
import jieba
import sys
filename = sys.argv[2]
target_filename = sys.argv[1]
fn = open(target_filename, 'r', encoding='utf-8')
f = open(filename, 'w+', encoding='utf-8')
for line in fn.readlines():
words = jieba.cut(line)
line_seg = ' '.join(words)
f.write(line_seg+'\n')
f.close()
fn.close()
|
from SHIMON.api.error import error_200
from SHIMON.api.api_base import ApiBase
from typing import TYPE_CHECKING
from SHIMON import HttpResponse
if TYPE_CHECKING:
from SHIMON.shimon import Shimon
class ApiStatus(ApiBase):
callname = "status"
unlock_required = False
def __init__(self) -> None:
... |
'''
Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c.
Example 1:
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3
Output: False
'''
import unittest
class Solution:
def judgeSquareSum(self, c):
"""
:type c:... |
"""Domain-level storage interaction."""
import abc
from typing import AsyncContextManager
from jupiter.core.domain.auth.infra.auth_repository import AuthRepository
from jupiter.core.domain.big_plans.infra.big_plan_collection_repository import (
BigPlanCollectionRepository,
)
from jupiter.core.domain.big_plans.infr... |
import numpy as np
import pytest
from pyswallow.handlers.boundary_handler import (
StandardBH, NearestBH, ReflectiveBH, RandomBH
)
class TestBoundaryHandler:
@pytest.fixture
def standard_bh(self):
return StandardBH()
@pytest.fixture
def bounds(self):
lb = np.array([0, 0])
... |
class Grid(object):
cells = []
houses = []
def __init__(self, cellList, houseList):
self.cells = cellList
self.houses = houseList
def getCell(self, hor, vert):
def __cellMatches(cell):
return cell.horizontal == hor and cell.vertical == vert
... |
# =============================================================================
# Created By : Giannis Kostas Georgiou
# Project : Machine Learning for Fish Recognition (Individual Project)
# =============================================================================
# Description : File to load the saved mo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.