text stringlengths 38 1.54M |
|---|
from allennlp.data import Vocabulary
from allennlp.data.iterators import BasicIterator
from allennlp.data.token_indexers import ELMoTokenCharactersIndexer
from allennlp.predictors.predictor import Predictor
from allennlp.models.archival import load_archive
from gbi.gradient_inference import GradientBasedInference
from... |
##A panel is a 3D container of data.
##
##The names for the 3 axes are intended to give some semantic meaning to describing operations involving panel data. They are −
##
## items − axis 0, each item corresponds to a DataFrame contained inside.
##
## major_axis − axis 1, it is the index (rows) of each of t... |
import heapq
import sys
input = sys.stdin.readline
def dijkstra(start, end):
heap = []
distance = [[sys.maxsize]*(M) for _ in range(N)]
sx, sy = start
ex, ey = end
heapq.heappush(heap, (0, sx, sy))
distance[sx][sy] = 0
while heap:
weight, hsx, hsy = heapq.heappop(heap)
fo... |
import unittest
import list_avg
class testListAvg(unittest.TestCase):
def test_list_avg_good(self):
self.assertEqual(list_avg.list_avg([3, 4, 5, 6]), 4.5)
self.assertEqual(list_avg.list_avg([-3.5,3.5]), 0)
def test_list_avg_fail(self):
self.assertEqual(list_avg.list_avg([3,3,3]), 1... |
"""autoPost URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... |
import re
import json
from flask import request
from flamingo import app
from flamingo.model.order import Order
from flamingo.model.product import Product
# Integration with LeadGenic
@app.route('/api/leadgenic_notify', methods=['POST'])
def leadgenic_notify():
data = request.get_json()
m = re.match('^.*/pro... |
# key - value pair
from collections import defaultdict, ChainMap
dict1 = {}
print(dict1.get('foo', 'bar'))
print(dict1.setdefault('foo', 'bar'))
print(dict1)
d = defaultdict()
d['key'] = 5
d[1] = 2
print(d)
#Merging two doctionaries
fish = {'name': "Nemo", 'hands': "fins", 'special': "gills"}
dog = {'name': "Clif... |
#!/usr/bin/env python3
import sys
import matplotlib.pyplot as plt
allele_frequency = []
for line in open(sys.argv[1]):
if line.startswith("#"):
continue
field = line.rstrip("\n").split()
info = field[7]
allele_frequency_split = info.split("=")[1]
allele_frequency_split = allele_frequen... |
def checkio(first, second):
a = "{0:b}".format(first)
b = "{0:b}".format(second)
#print(a,b)
for i in a:
c1, c2, c3 = "", "", ""
for y in b:
print("{0} ==== {1}".format(i,y))
print(str(int(i) & int(y)))
print(str(int(i) | int(y)))
print(str... |
import numpy as np
from scipy.stats import chi2
class NormalInverseWishartDistribution(object):
def __init__(self, mu, lmbda, nu, psi):
self.mu = mu
self.lmbda = float(lmbda)
self.nu = nu
self.psi = psi
self.inv_psi = np.linalg.inv(psi)
self.cholesky = np.linalg.chol... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import argparse
APPID = '9a3675b6715bf378ff635db295ea7a2d' # place your APPID from openweathermap.org
day = {
u'01d': u'\u2600\ufe0f',
u'02d': u'\U0001f324',
u'03d': u'\U0001f325',
u'04d': u'\U0001f325',
u'09d': u'\U0001f326',
u'10d'... |
from bs4 import BeautifulSoup
import requests
import sys
import string
def main():
timestamp = "1556490705"
print("Hekathon 2019 donations since " + timestamp + ":")
donations = get_donations("hek19", timestamp)
for donation in donations:
print(donation)
def get_donations(marathon_uri, since... |
import sqlite3
from django.urls import reverse
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from libraryapp.models import Book, Library
# from libraryapp.models import model_factory
from ..connection import Connection
from ..helpers.get_book import get_book
... |
from web3 import Web3
from rappor import Rappor
import json
class Service_Provider:
def __init__(self):
self.rappor = Rappor()
with open('conf/privacy.conf') as f:
self.conf = json.load(f)
try:
w3 = Web3(Web3.HTTPProvider(self.conf['web3provider']))
... |
from . import conn as connection
from utils.datetime import get_current_epoch_ms
def browse():
with connection.connect() as conn:
results = conn.execute(
f'SELECT * FROM trade'
)
result = []
for r in results:
result.append(
{
'trade_id': r[0],
'original_id': r[1],
'original': r[2],
'pat... |
import os
from functools import lru_cache
from urllib.error import HTTPError
import geopandas as gpd
import pandas as pd
import requests
import unicodedata
from io import StringIO
from geobr.constants import DataTypes
MIRRORS = ["https://github.com/ipeaGIT/geobr/releases/download/v1.7.0/"]
def _get_unique_values(_... |
import math
class MaxHeap:
def __init__(self, capacity):
assert capacity > 0
self.__capacity = capacity
self.__arr = [None] * capacity
self.__count = 0
def __shiftDown(self, k = 0):
assert k < self.size() and k >= 0
e = self.__arr[k]
while True:
... |
import io
from unittest import TestCase
from unittest.mock import patch
from game import display_character_health
@patch('sys.stdout', new_callable=io.StringIO)
class TestDisplayCharacterHealth(TestCase):
def test_display_level_one_information(self, mock_stdout):
character = {'level_one_name': "Squirtle"... |
import unittest
import dojo
class listar(unittest.TestCase):
def testa_lista_size(self):
lista2 = dojo.umAcem()
self.assertEqual(
range(1, 101),
lista2
)
def testa_fizz(self):
lista = range(1, 4)
fizzTest = dojo.getElement(lista)
self.assertEqual(
"Fizz",
dojo.getElement(lista)
... |
"""
testing_processer
-----------------
The testing function for test the processer utilities.
"""
import os
from processer import Processer
from ..Logger import Logger
from processer import check_subprocess, create_empty_list_from_hierarchylist,\
store_time_subprocess, initial_message_creation
## Code a dummy... |
#!/usr/bin/python3
""" Contains the unittests for the Base class. """
import unittest
import os
from models.base import Base
from models.rectangle import Rectangle
from models.square import Square
class TestBaseClass(unittest.TestCase):
""" Tests the base class. """
def test_init(self):
""" Tests the ... |
from .pruner import LevelPruner, AGPruner, SensitivityPruner
from .quantizer import NaiveQuantizer, DoReFaQuantizer, QATquantizer
from ._nnimc_torch import TorchPruner, TorchQuantizer |
import os
import cProfile
import pstats
import subprocess
class Profiler(object):
'''
This class provides some convenience methods to start/stop
a code profiler and display statistics and a callgraph.
To generate and view the callgraph you should install gprof2dot
from the python package index and... |
from datetime import datetime
from django.db import models
from django.forms import model_to_dict
from apps.equipo_maquinaria.models import equipo_maquinaria
from apps.empleado.models import empleado
estado = (
(0, 'Devuelto'),
(1, 'Entregado')
)
class asig_eq_maq(models.Model):
fecha_asig = models.Date... |
# Markdown preprocessor
# equation, table, figure numbering
#
# reference,cite: @kind:label
# parse time: @time(format)
import sys,re
text=sys.stdin.read()
def parse_crossref(text):
"""
Cross reference
@kind:label -> numbers (sequential)
"""
count={}
queue={}
items=re.findall('(@(\w+):\w+)',text)
for item i... |
from tkinter import *
from dbhelper import DBHelper
from PIL import Image, ImageTk
from tkinter import messagebox
import qrcode
from datetime import date
class Bank():
def __init__(self):
# Connect to the database
self.db = DBHelper()
self.load_login_window()
... |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
from unittest.mock import patch
from destination_meilisearch.writer import MeiliWriter
@patch("meilisearch.Client")
def test_queue_write_operation(client):
writer = MeiliWriter(client, "steam_name", "primary_key")
writer.queue_write_operation({"a"... |
from itertools import repeat
import libsheetmusic.music as m
import libsheetmusic.util as u
@u.iterate
def scale(func_name, string_note):
note_in = u.from_scientific(string_note)
notes_out = m.scale(func_name, note_in)
return u.range_apply(u.to_scientific, notes_out)
@u.iterate
def chord(func_name, strin... |
from django import forms
class FacilitySearch(forms.Form):
facility_name = forms.CharField()
parent_company = forms.CharField()
def clean(self):
cleaned_data = super(facility_search, self).clean()
facility_name = cleaned_data.get('facility_name')
parent_company = cleaned_data.get('... |
#!/usr/bin/env python
# -*-coding:utf-8 -*-
# name = input('请输入名字:')
# age = input('请输入年龄:')
# job = input('请输入工作:')
# hobbie = input('请输入爱好:')
# msg = ''' ---------------info of %%s--------------
# Name : %s
# Age : %s
# Job : %s
# Hobbie : %s
# -----------------end--------------------
# '''% (name,age,job,hobbie)
#... |
from django.contrib import admin
from .models import Workout, Log, MemberComment
class WorkoutAdmin(admin.ModelAdmin):
fields = (
'workout_name',
'workout_is_wod',
'workout_type',
'workout_category',
'description',
)
list_display = (
'workout_name',
... |
from typing import AbstractSet, Iterator
from collections.abc import Collection
from abc import abstractmethod
from phantom.dag import Block
class DAG(Collection):
"""
An interface for a DAG based blockchain.
Some terminology:
Virtual block - a block that an "honest" miner would add to the top of the... |
__author__ = '7Winds'
from core.game.plugin import PluginManager
from core.game.model.entity.player import Player
def clickButton_33209(c):
c.sendMessage("It worked")
def clickButton_58253(c):
c.getActionSender().showInterface(15106)
c.getEquipment().writeBonus()
def clickButton_59004(c):
... |
def main():
N = int(input())
A = map(int, input().split())
ans = sum(a for a in sorted(A, reverse=True)[::2])
print(ans)
if __name__ == '__main__':
main()
|
import os
import sys
import sh
import re
class NetInterfaces:
sh.ifconfig(_out="/home/edita/scripting/interfaces")
def __init__(self):
pass
def read_write():
with open("interfaces", 'r', newline='') as f_in:
net_info = f_in.readlines()
with open('inet_status.csv','w') as f_out:
for line in net_info:... |
"""Module dedicated for postprocessing the input image."""
import typing as t
import numpy as np
import skimage.transform
import skimage.color
class Postprocessor:
"""Class with various methods for postprocessing the input image."""
def __init__(self):
"""."""
self.img_postprocessed = None ... |
first_name = 'Leandro'
last_name = 'Cotrim'
#parametros seguidos
print('Meu nome completo é {} {}'.format(first_name, last_name))
#parametros indexados
print('Meu último nome é {1}, e o primeiro é {0}'.format(first_name, last_name))
#parametros unpacking
print('As letras do meu primeiro nome é {} {} {} {} {} {} {}'... |
import argparse
import os
import torch
import cv2 as cv
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
PICS_PATH = "../data/train"
INDEX_PROVIN... |
from flask import (Blueprint, render_template)
bp = Blueprint('authors', __name__)
@bp.route('/authors/<author>')
def show(author):
return render_template('authors.html', data=search_author(author))
def get_authors():
return [
{'author':'ニュートン',
'bio':'「なぜリンゴが木から落ちるのかという疑問から万有引力の法則を発見した」という伝... |
from django.test import TestCase
from wagtail.test.utils import WagtailPageTestCase
from wagtail.models import Page
from .models import BlogPost, AllBlogPostsHomePage, ProgramBlogPostsPage
from home.models import HomePage, PostProgramRelationship
from programs.models import Program, Subprogram, Project
class BlogP... |
# https://leetcode.com/problems/remove-duplicate-letters/
# Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
class Solution:
def removeDuplicateLetters(self, s: str) -... |
from collections import namedtuple
Segment = namedtuple('Segment', 'start end')
def optimal_points(segments):
segments.sort(key= lambda x: x[1])
points=[]
while len(segments) != 0:
p = segments[0].end
for i in segments[:]:
if i.start <= p <= i.end:
segments.remo... |
import os
def get_engines():
db_engines = {}
# test if PyDbLite is installed
try:
import PyDbLite
db_engines['PyDbLite'] = PyDbLite
except ImportError:
pass
# test if sqlite is installed
sqlite = None
try:
from sqlite3 import dbapi2 as sqlite... |
import json
ws_lst = [
{"id":1001,"name":"python","year":"2019","status":1,"company":"heraizen"},
{"id":1002,"name":"web","year":"2018","status":1,"company":"spaneos"}
]
try:
with open("ws.json","w",newline='') as file:
json.dump(ws_lst,file,indent=4)
print(json.dumps(ws_lst))
exc... |
import numpy as np
from scipy import spatial, cluster
import cv2 as cv
import math
import re
import os
from collections import Counter
from matplotlib import pyplot as plot
def display_image(img, file_name=None, save_norm=True, save_type=np.uint8):
"""
Shows an image (max-min normalized to 0-255), and saves it... |
# Copyright 2016 The Streamer Authors. 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 required by applicabl... |
import numpy as np
import warnings
from matplotlib import pyplot as plt
def anisodiff(img, niter=1, kappa=50, gamma=0.1, step=(1., 1.), option=1):
"""
Anisotropic diffusion.
Usage:
imgout = anisodiff(im, niter, kappa, gamma, option)
Arguments:
img - input image
niter ... |
type_of_people=10
x=f"There are {type_of_people} types of people "
binary="binary"
do_not="don't"
y=f"Those who know {binary} and those who {do_not}."
print(x)
print(y)
hilarious=False
joke_evaluation="Isn't that joke o funny?!{}"
print(joke_evaluation.format(hilarious))#format接字符串,必须使用{}
w="This is the left ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Webapp
from fbone template_filter
https://github.com/imwilsonxu/fbone.git
"""
__author__ = "Kingshuk Dasgupta (rextrebat/kdasgupta)"
__version__ = "0.0pre0"
import MySQLdb
import pymongo
import pylibmc
from flask import Flask, g, render_template
from flask_debugtoolba... |
#!/usr/bin/python
import argparse
import sys
from subprocess import call
parser = argparse.ArgumentParser()
parser.add_argument("cores", help = "Enter the number of cores, you want to use for downloading here", type = int)
args = parser.parse_args()
quater_cores = args.cores/4
print(args.cores)
print(quater_cores)
... |
maiores = homens = mulheresmaiores = 0
while True:
print('-' * 45)
print(''' CADASTRE UMA PESSOA''')
print('-' * 45)
idade = int(input('Idade: '))
genero = ' '
while genero not in 'MF':
genero = input('Gênero: [M/F] ').strip().upper()[0]
print('-' * 45)
resposta... |
import os
objects_extensions = ['jpg', 'jpeg', 'png']
def getClasses(pair):
result = []
for annotation in pair['annotations']:
if annotation['emotion'] != None:
result.append(annotation['emotion'])
return result
def getAnnotationsData(files_metadata):
return None
def getAnnotations(object, all_annotations_... |
from numpy import array
def writeArray1(ar,name):
s=''
counter=0
for x in ar:
s+='%s[%i]=%f;\n'%(name,counter,x)
counter+=1
return s
def writeArray2(ar,name):
s=''
counterX=0
counterY=0
for x in ar:
counterY=0
for y in x:
s+='%s[%i][%i]=%f;\n'%(name,counterX,counterY,y)
counterY+=1
cou... |
from datetime import datetime
from django.core.urlresolvers import reverse
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.template.loader import render_to_string
from django.utils import simplejson ... |
"""
"""
import os.path
class TestContainer(dict):
"""
"""
def __init__(self, d):
self.update(d)
def add(self, type, name):
return self.setdefault(name, {}).setdefault(type, {})
def clear_test_file(ctx):
"""
"""
n = ctx.path.find_or_declare('tests.py')
n.delete()... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
def quicksort(list):
left=[]
middle=[]
right=[]
#list=left + middle + right
pivot = list[0]#第一個位置為基準點
if len(list) <2 :
pass
else:
for i in list:
if i < pivot:
left.append(i)
elif i > p... |
from django.forms import ModelForm
from movierater.models import Rating
class RatingForm(ModelForm):
class Meta:
model = Rating
fields = ('movie','rating',)
|
"""
3. Сформировать из введенного числа обратное по порядку входящих в него
цифр и вывести на экран. Например, если введено число 3486,
то надо вывести число 6843.
Подсказка:
На каждом шаге вам нужно 'доставать' из числа очередную цифру
Пока все числа не извлечены рекурсивные вызовы продолжаем
Условие завершения реку... |
#!/usr/bin/env python
"""
Wrapper for cppcheck that only passes through errors in lines that were added in
the passed diff FROM..TO .
"""
from __future__ import print_function
import argparse
import subprocess
import collections
import re
def diff_lines_to_file_lines(diff_lines):
"""
Pass an iterator of the ... |
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 OpenERP SA (<http://openerp.com>).
# Application developed by: Carlos Andrés Ordóñez P.
# Country: Ecuador
#
# This program is free so... |
import pymongo
import os
import json
from bson.json_util import dumps
import datetime
from datetime import date
today = date.today()
client = pymongo.MongoClient()
db = client.test
docs = []
cursor = db.readings.find()
for doc in cursor:
del doc['_id']
docs.append(doc)
|
#!/usr/bin/env python3
# Function to count the number of words before Sam appears
def count_sam(l_str):
count = 0
for word in l_str:
if word.lower() != 'sam':
count += 1
else:
count += 1
break
return count
words = ['a', 'joy', 'joey', 'liquor', 'x', 'y... |
import sys
def calculateMedian(intArray):
"""
Input: Sorted Array of Integers
Calculates the median
"""
lengthOfArray = len(intArray)
if lengthOfArray % 2 == 0:
median = (intArray[lengthOfArray/2] + intArray[(lengthOfArray/2)-1])/2.0
else:
median = intArray[lengthOfArray/2]
return median
def main(args=Non... |
# standard library
import sys
import os
import json
from collections import Counter
# 3rd party packages
from prettyprinter import pprint
# local source
from kmppti.grid import Grid
from kmppti.rtree import RTree
from kmppti.pandora_box import PandoraBox
from kmppti.skyline import dynamic_skyline, reverse_skyline
f... |
import sys
numCases = int(raw_input())
print("Number of cases: "+str(numCases))
while numCases > 0:
N, K = map(int, raw_input().split())
results = 0
runOfZeroes = 0
#print sys.stdin.read(1)
#print sys.stdin.read(1)
#print sys.stdin.read(1)
char = sys.stdin.read(1)
print("firs... |
import sys
# sys.stdin = open("input.txt", "r")
"""
중복순열 구하기
1부터 N까지 번호가 적힌 구슬이 있습니다. 이 중 중복을 허락하여 M번을 뽑아 일렬로 나열
하는 방법을 모두 출력합니다.
▣ 입력설명
첫 번째 줄에 자연수 N(3<=N<=10)과 M(2<=M<=N) 이 주어집니다.
▣ 출력설명
첫 번째 줄에 결과를 출력합니다. 맨 마지막 총 경우의 수를 출력합니다.
출력순서는 사전순으로 오름차순으로 출력합니다.
▣ 입력예제 1
3 2
▣ 출력예제 1
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
9
"... |
import os
import subprocess
import sys
proj = sys.argv[1]
src = sys.argv[2]
entry = sys.argv[3]
ticks = int(sys.argv[4])
dumps = "dumps3"
if not os.path.exists(dumps):
os.makedirs(dumps)
for i in range(0, ticks):
# time cabal run G2 tests/Liquid/ defs/PrimDefs.hs -- --liquid tests/Liquid/Peano.hs --liquid-fu... |
from lino.runtime import *
from django.utils import translation
from django.test import Client
import json
from bs4 import BeautifulSoup
from lino.utils import AttrDict
client = Client()
def get_json_soup(username, uri, fieldname, an='detail'):
url = '/api/{0}?fmt=json&an={1}'.format(uri, an)
res = client.get... |
class Car(object):
"""
blueprint for car
"""
def __init__(self, model, color, company, speed_limit):
self.color = color
self.company = company
self.speed_limit = speed_limit
self.model = model
def start(self):
print("started")
def stop(self):
print("stopped")
def accelarate(self):
print("accelarating...")... |
from typing import List
class Solution:
def lengthOfLastWord(self, s: str) -> int:
cur1 = -1
n = len(s)
mark = False
if n < 1:
return 0
for idx, char in enumerate(s):
if char == ' ':
mark = True
elif mark and char... |
from config.auth import auth_api
import json
import tweepy
api = auth_api()
perifacode_id = "1111232059387928577"
quebradev_id = "995429424312012801"
tecnogueto_id = "1002022507413757958"
class FavRtAccounts(tweepy.StreamListener):
def __init__(self, api):
self.api = api
self.me = api.me()
def ... |
import torch.nn as nn
import torch.nn.functional as F
from layers import GraphConvolution
class GCN(nn.Module):
def __init__(self, nfeat, nhid, nclass, dropout):
super(GCN, self).__init__()
self.gc1 = GraphConvolution(nfeat, nhid)
self.gc2 = GraphConvolution(nhid, nclass)
self.dro... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class LevelModel(models.Model):
name = models.CharField(max_length=100) # Name of the level
task = models.TextField() # Description of the tas... |
# coding: u8
import jinja2
class UndefinedSilently(jinja2.Undefined):
__unicode__ = __str__ = lambda *args, **kwargs: u''
__call__ = __getattr__ = lambda *args, **kwargs: UndefinedSilently()
class Render(object):
def __init__(self, template_path, **kw):
from jinja2 import Environment, FileSyste... |
#!/ usr /bin /python
# -*- coding: utf-8 -*-
#
# Author : Sriram Ka r thik Badam
# Date : Sep 26 , 2012
#
import sys , os
import cv2
import cv
import numpy as np
#image v a r i a b l e s
image1 = 0
image2 = 0
#c o n s t a n t s
WINDOW_SIZE = 5
TOTAL_FEATURES = 200
#Window size and Th re sh old s f o r s t e r e o.jp g... |
###### this is the second .py file ###########
####### write your code here ##########
print "Welcome to the Game!"
#matrix = "\n".join([" ".join(["0" for x in range(3)]) for x in range(3)])
#list1 = list(matrix)
player1 = [1,3,5,7,9]
player2 = [2,4,6,8]
list1 = [0,0,0,0,0,0,0,0,0]
def play_game(lst):
flag... |
"""
Defined here are the ProtoRPC message class definitions for the API.
"""
__author__ = 'Cesar'
from protorpc import messages, message_types
"""
USER
"""
class CreateUser(messages.Message):
"""
Message containing the information of a User
email: (String)
name: (String)
age: (Integ... |
import numpy as np
import cv2
import os
import torch
import torchvision
from torchvision import datasets, models, transforms
import matplotlib.pyplot as plt
import sklearn
#import sklearn.cross_validation
import sklearn.model_selection
#from sklearn.cross_validation import train_test_split
from sklearn.model_selection ... |
from .finances.finances import Finances
from .notifications.notifications import Notifications
from .orders.orders import Orders
from .product_fees.product_fees import ProductFees
from .sellers.sellers import Sellers
from .reports.reports import Reports
from .products.products import Products
from .sales.sales import S... |
from hashlib import sha512
from uuid import uuid4
from sqlite3 import connect
from random import choice, random, randint
from csv import reader, Sniffer
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def get_table(category):
conn = connect('dat... |
from django.urls import path
from comments.views import create_comment
app_name='comments'
urlpatterns=[
path("createdcomment", create_comment, name="createcomment")
] |
# importing the requests library
import requests
import time
# api-endpoint
URL = "http://smartmedicinecup.herokuapp.com/api/get_contact/"
# JSON FORMAT
# {
# id_copo: 1,
# partition: 1,
# moment: "2018-12-30 hh:mm",
# event: "tomou|não tomou|cadastrou|removeu",
# alarm_info: {
# start: {
# hour: 10,
# ... |
'''gff2gff.py - manipulate gff files
=================================
:Tags: Genomics Intervals GFF Manipulation
Purpose
-------
This scripts reads a :term:`gff` formatted file, applies a
transformation and outputs the new intervals in :term:`gff` format.
The type of transformation chosen is given through the `--m... |
from amuse.community import *
from amuse.community.interface.gd import GravitationalDynamicsInterface
from amuse.community.interface.gd import GravitationalDynamics
from amuse.units import units
# http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
class inttypes:
SHARED2 = 1... |
# coding:utf-8
from main.models import Result,Tasks_status
def check_status(target):
"""
:param target:
:return:
status:1 目标都已有扫描结果或正在扫描
status:200 可以去扫描
"""
status = 200
try:
scanning_target = Tasks_status.objects.filter(domains__contains=target)
scanned_target ... |
#!/usr/bin/env python3
import os
import sh
import shutil
import re
datadir = "/var/www/dokuwiki/data/"
repodir = "/path/to/repo/"
class Revision():
pass
def collect_revisions():
for i in os.walk(datadir + "pages"):
if i[0].split("/")[-1] in ["wiki", "playground"]:
continue
for ... |
import jarvisCore as jc
from bs4 import BeautifulSoup as soup
from core.orders.system.volume import *
from core.orders.system.notes import *
from core.orders.web_operations import scraping
from core.orders.constants import *
from core.orders.answer_operation.answer import getShellOutput
weatherLabels = [
{"label":... |
import datetime
from conf import conf
class ROOT_DATA():
base_task = None
last_task_id = 0
running_task_id = None
planned_tasks = None
class Task(object):
def __init__(self, task_id, parent_id, task):
self.task_id = task_id
self.parent_id = parent_id
self.task = task... |
int_ls = []
while True:
int_var = int(input())
if( int_var == 0 ):
break;
int_ls.append( list(range(1, int_var+1)) )
for x in range( 0, len(int_ls) ):
print( str(int_ls[x]).replace(", ", " ").replace("[", "").replace("]", "") ) |
"""
## Backspace String Compare
Given two strings S and T, return if they are equal when both are typed into empty text editors.
# means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
Example 1:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T bec... |
# -*- coding: utf-8 -*-
"""Items that can be associated with a GUID"""
import random
import uuid
from sqlalchemy import *
from sqlalchemy.orm import mapper, relation
from sqlalchemy import Table, ForeignKey, Column
from sqlalchemy.types import Integer, Unicode
#from sqlalchemy.orm import relation, backref
from media... |
"""
File Name: conserved_domain_search.py
Project: bioseq-learning
File Description:
"""
import os
import re
from io import StringIO
from typing import Optional
from subprocess import Popen, PIPE
import pandas as pd
from Bio.Blast.Applications import \
NcbirpstblastnCommandline, Ncbiblastform... |
"""
draft
"""
sample_set = '2' #'2'|''
max_components = 45
test_by_good_only = 1; #True|False
def kfold_group_count(n): return 10 #n|2|5
from numpy import array, load, arange, where, sqrt, power, empty_like
from linre_tools import find_peaks, PCA
from scipy.linalg import lstsq
from sklearn.cross_validation import K... |
from django import forms
from .models import Post, Blogger
from django.contrib.auth.models import User
class NewPostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'content',)
class ProfileEditForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_... |
import random
from enum import Enum, IntEnum, unique
from itertools import cycle, combinations, product
from collections import Counter
import numpy as np
import copy
import pickle
@unique
class Action(IntEnum):
TAKE = 0
SELL = 1
TRADE = 2
@unique
class Commodity(IntEnum):
CAMEL = 0
LEATHER = 1
... |
import argparse
import os
import sys
import glob
import numpy as np
import open3d as o3d
from PIL import Image
from pathlib import Path
from plyfile import PlyData, PlyElement
focalLength = 525.0
centerX = 319.5
centerY = 239.5
scalingFactor = 5000.0
for i in range(4):
directory = f"/home/kate/catkin_ws/src/DATAS... |
from torchsummary import summary
import torch
import torch.nn as nn
import torch.nn.functional as F
from eva4modeltrainer import ModelTrainer
class Net(nn.Module):
"""
Base network that defines helper functions, summary and mapping to device
"""
def conv2d(self, in_channels, out_channels, kernel_size=(... |
import game_framework
from pico2d import *
import main_state
import game_world
import random
import end_state
import victory_state
name = "title_state"
image = None
from penguin import Penguin
penguins = []
bgm = None
def enter():
global image
image = load_image('./image/title.png')
global penguins
... |
VERSION = 1.22
import sys
if sys.version_info[0] < 3 or sys.version_info[1] < 6:
raise ImportError("You are using python {}.{}. Python 3.6 or greater is required to use TPPFLUSH.\nYou can download the latest version of python from http://www.python.org.\n".format(sys.version_info[0],sys.version_info[1]))
import s... |
import numpy as np
from scipy.signal import find_peaks
import matplotlib.pyplot as plt
from numpy.fft import fft, ifft
from arr import between
from datetime import datetime
FILENAME = "data.txt"
DIST = 80
PROM = 100
START, END = 1900, 2900
REDMUL, IRMUL = 1,4
def peaks(input_signal):
peak, _ = find_peaks(input_si... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.