text stringlengths 38 1.54M |
|---|
with open('zoo.csv')as csv_file:
csv_reader = csv.reader(csv_file,delimiter=',')
next(csv_reader)
#to skip the header from csv file
for row in csv_reader:
#print(row)
if row[0] not in animal_dict.keys():
animal_dict[row[0]]= int(row[2])
else:
animal_dict... |
import unittest
from flask import url_for
from flask_testing import TestCase
from application import app, db
from application.models import Ingredients, Method, Recipe
class TestBase( TestCase ):
def create_app(self):
app.config.update( SQLALCHEMY_DATABASE_URI="sqlite:///",
SECRET_KEY='TE... |
#1. Подсчитать, сколько было выделено памяти под переменные в ранее разработанных
# программах в рамках первых трех уроков. Проанализировать результат и определить
# программы с наиболее эффективным использованием памяти.
#Вариант_1: Общая сумма занимаего места = 392
#Вариант_2: Общая сумма занимаего места = 22344
#Ва... |
def display_hangman(tries):
stages = [ # final state: head, torso, both arms, and both legs
"""
--------
| |
| O
| \\|/
| |
| / \\
-
... |
from os import system
exe = "lencod.exe"
cfg = "encoder_ldp.cfg"
videos = [["BasketballDrive_1920x1080_50","5","50","1920","1080"],["BQTerrace_1920x1080_60","5","60","1920","1080"],["Cactus_1920x1080_50","5","50","1920","1080"],["Jockey_3840x2160","5","120","3840","2160"],["ShakeNDry_3840x2160","5","120","3840","2160"... |
## Amanda Roberts 2017/08/01
#This code utilizes machine learning to make a prediction of LAI values at ORNL
#.tif files from the BRDF flight performed there are used to "train" the Random Forest Regressor
#The regressor then gets data from the full site and predicts LAI
#Import packages needed
import numpy as np
... |
import os
def loadfile(name):
count = 0
file = open(name, "r")
f = file.readlines()
mapKey = {}
for ind in range(len(f)):
f[ind]=f[ind].rstrip()
for row in range(len(f)):
for col in range(len(f[row])):
if f[row][col] not in mapKey:
mapKey[f[row][col]]... |
import argparse
from yacs.config import CfgNode as CN
from ..config import get_cfg
def default_argument_parser() -> argparse.Namespace:
parser = argparse.ArgumentParser(description='Segmentation Pipeline')
parser.add_argument("--config-file", default="", metavar="FILE",
help="path to ... |
import pymysql
db = pymysql.connect('localhost', 'root', 'root', 'student')
cursor = db.cursor()
sid = int(input('Enter student id: '))
daytomarkattendance = int(input('Enter day to mark attendance: '))
try:
r = cursor.execute('Update attendance set d' + str(daytomarkattendance) + ' = 1 where id = ' + str(sid))... |
#https://www.hackerrank.com/contests/projecteuler/challenges/euler244/problem
letter_code = {"L": 76, "R": 82, "U": 85, "D": 68}
def get_checksum(seq, i=0, checksum=0):
checksum = (checksum * 243 + letter_code[seq[i]]) % 100000007
i += 1
if i >= len(seq):
return checksum
return get_checksum(s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
if __name__ == '__main__':
test_1 = Singl... |
from django.urls import path
from website.views import LandindPageView
app_name = 'website'
urlpatterns = [
path('', LandindPageView.as_view(), name='landind_page')
]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 开始爬取图片的网址(一般为主站)
START_URL = 'http://www.juemei.com/mm/'
# 需要爬取的网址的正则表达式
URL_TO_SCAN_PATT = r'/mm/[^"\']+'
# 需要下载的图片的正则表达式
IMG_TO_DOWN_PATT = (r'http://img\.juemei\.com/\w+/'
r'\d{4}-\d{2}-\d{2}/\w{13}\.jpg')
|
from __future__ import print_function
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "2"
import torch, cv2
import torch.utils.data
from torch.autograd import Variable
import numpy as np
from data.kth import KTH_LIST_img_dyan
import skimage
rootDir = '/data/huaiyu/data/kt... |
"""
Simplistic non-optimized, native Python implementation showing the mechanics
of TimSort.
This code is designed to show how TimSort uses Insertion Sort and Merge Sort
as its constituent building blocks. It is not the actual sorting algorithm,
because of extra complexities that optimize this base algorithm even furt... |
from numpy import *
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import os
import pdb
from copy import deepcopy
# For heritage use of PyXFocus.
import PyXFocus.sources as src
import PyXFocus.transformations as trans
import PyXFocus.surfaces as surf
import PyXFocus.analyses as anal
import PyXFo... |
import math
"""program pro vypocet polohy jednotlivych poledniku a rovnobezek v danem zobrazeni"""
def zadani_osetreni_polomeru():
"""Vyzada od uzivatele polomer, pro hodnotu 0 je polomer definovany 6371.11km. Vystupem je polomer osetreny od chyb"""
while True:
polomerstr = input("zadej polomer v km:"... |
from loader import bot, storage
import os
import redis
import sqlite3
os.system('redis-server /etc/redis/6379.conf')
redis_control = redis.Redis()
db = sqlite3.connect('Words_Data_Base.db')
# "on_shutdown" function that called at the end of bot
async def on_shutdown(dp):
await bot.close()
await storage.clo... |
import sys
import textwrap
def wrap(text):
result = textwrap.wrap(text, width=10, replace_whitespace=False)
print('\n'.join(result))
if __name__ == '__main__':
wrap(sys.argv[1])
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
def traver... |
# Some questions about string, list and their methods.
# str.method() returns a copy of str.
# lst.method() changes the lst and returns None.
str = ' adfsdfsdf'
print(str)
str.strip()
print(str)
print(str.strip())
nstr = str.strip()
print(nstr)
lst = ['d','e','a','c']
print(lst)
lst.sort()
print(lst)
# 输... |
"""This module manages the views of the categories app."""
from rest_framework import generics, permissions, status
from rest_framework.response import Response
from rest_framework.views import APIView
from providers.models import Provider
from providers.serializers import ProviderListSerializer, ProviderSerializer
c... |
# importing the dependencies
import os
import sys
# from './build/account' import Account # isort: skip
# setup accounts
account1 = Account()
account2 = Account()
# Account 1 Transactions
account1.deposit(100.0)
account1.deposit(100.0)
account1.withdraw(50.0)
# Account 2 Transactions
account2.deposit(200.0)
accoun... |
from django.shortcuts import get_object_or_404, render, redirect, HttpResponse, render_to_response
from django.template import RequestContext
from models import *
import spotipy
from spotify_util import *
from django.contrib.auth.decorators import login_required
def index(request):
hot_albums = Album.objects.orde... |
import assertions
#####################################
# DTO
#####################################
class DTO(object):
def __init__(self,kw):
self._instance_version = self.code_version
d = dict(kw) # make (shallow) copy of d before changing it
d.pop('self', None)
clsna... |
def LiqEtlp_pT(P,T,x_N2):
x = (P-5.53901951e+02)/3.71707300e-01
y = (T--1.77479018e+02)/2.63824000e-02
z = (x_N2-9.59063881e-01)/4.39751219e-03
output = \
1*-9.65086300e+02
liq_etlp = output*1.00000000e+00+0.00000000e+00
return liq_etlp |
# This program converts JSON files to CSV, while dealing with encoding issues
import json
import csv
# Code altered from https://www.geeksforgeeks.org/convert-json-to-csv-in-python/
# and https://stackoverflow.com/questions/21058935/python-json-loads-shows-valueerror-extra-data/51830719
temp_storage = []
... |
# -*- coding: utf-8 -*-
'''
Simple RPC
Copyright (c) 2012-2013, LastSeal S.A.
'''
from simplerpc.base.SimpleRpcLogicBase import SimpleRpcLogicBase
from simplerpc.testing.exposed_api.TwinModulesManager import TwinModulesManager
from simplerpc.testing.exposed_api.ModuleUnitTestRunner import ModuleUnitTestRunner
from simp... |
from collections import defaultdict
from typing import List
import numpy as np
import xarray as xr
from ..utils.coding import set_time_encodings
from ..utils.log import _init_logger
# fmt: off
from .set_groups_base import SetGroupsBase
# fmt: on
logger = _init_logger(__name__)
class SetGroupsEK60(SetGroupsBase):... |
# Solution of;
# Project Euler Problem 244: Sliders
# https://projecteuler.net/problem=244
#
# You probably know the game Fifteen Puzzle. Here, instead of numbered tiles,
# we have seven red tiles and eight blue tiles. A move is denoted by the
# uppercase initial of the direction (Left, Right, Up, Down) in which the... |
import numpy as np
'''
Created on 2018年9月14日
@author: DELL
'''
class KD_node:
def __init__(self,elt=None,split=None,LL=None,RR=None):
self.elt = elt
self.split = split
self.LL = LL
self.RR = RR
def createKDTree(dataList):
if len(dataList) == 0:
... |
"""
Configuration file. All constants should go here.
"""
from .version import __version__, __build__, __date__, __commit__
class Config:
"""
This class contains the application configuration values
"""
version = __version__
build = __build__
date = __date__
commit = __commit__
|
from rest_framework.exceptions import APIException
from apps.endpoints.models import Recommendation, Song
from unittest import mock
from django.test import TestCase
from rest_framework.test import APIClient
from .test_utils import populate_full_db, getSingleSpotifyTrackJSON, getTestSpotifyRecommendationJSON
def get... |
london_co = {
"r1": {
"location": "21 New Globe Walk",
"vendor": "Cisco",
"model": "4451",
"ios": "15.4",
"ip": "10.255.0.1"
},
"r2": {
"location": "21 New Globe Walk",
"vendor": "Cisco",
"model": "4451",
"ios": "15.4",
"ip": "1... |
"""
Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code" -> False, "aab" -> True, "carerac" -> True.
"""
import string
def canPermutePalindrome(s):
"""
:type s: str
:rtype: bool
"""
aset = set()
odd_cnt = 0
for i in s:
# if the chara... |
# Endpoint for covid data api
COVID_ENDPT = 'https://api.covidtracking.com/v1/states/'
CONFIG_FILEPATH = 'config.ini'
KEYWORDS = {"covid", "coronavirus", "corona", "pandemic", "quarantine", "covid-19"}
|
"""
Plugins are defined here, because Airflow will import all modules in `plugins` dir but not packages (folders).
"""
from airflow.plugins_manager import AirflowPlugin
from .RedshiftTableConstraintOperator import RedshiftTableConstraintOperator
from .SQLTemplatedPythonOperator import SQLTemplatedPythonOperator
from .... |
print (" Willkommen zum ultimativen Lego-Treppen-Kalkulator!!!")
print (" # ")
print (" # # ")
print (" # # # ")
print (" # # # # ... |
import tensorflow as tf
import numpy as np
import cv2
import os
import matplotlib.pyplot as plt
import _config as cfg
import _util as util
import _model_2_100x30 as model
'''
1) config.py: dataDir
2) util.py: 적용 model
2) train_result.py: 적용 model
'''
''' ============================= '''
''' test set 읽기(... |
# coding=utf-8
'''
Created on 2020-4-2
@author: jiangao
Project: one piece 漫画爬取
'''
import requests
import threading
import sys
import io
import time
import os
import re
import socket
header = {
'Content-Type': 'text/plain; charset=UTF-8',
'User-Agent':'Chrome/80.0.3396.99 Safari/537.36'
... |
"""
Mohammad Rifat Arefin
ID: 1001877262
"""
import os
import tkinter as tk
import socket
import threading
import pickle
from orderedset import OrderedSet #FIFO data structure for lexicon
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfile
import time
server_por... |
from collections import Counter
N = int(input())
src = [int(input()) for i in range(N)]
ctr = Counter(src)
print(len(ctr.items()))
|
import matplotlib.pyplot as plt
import numpy as np
import pickle
import argparse
from os import path
import re, string, unicodedata
import nltk
from nltk import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
# Get the necessary class structure and connect to the... |
import json,pickle
import tesy_json
try:
f_date = pickle.loads(tesy_json.date)
t_date = pickle.loads(tesy_json.date3)
print(t_date)
except Exception as e:
print(e)
import hashlib
md5 = hashlib.md5
x = 'sjlkfjdslfd'
md5(x)
print(x)
|
import tensorflow as tf
from spectral_norm import SpectralNormalization
from tensorflow_addons.layers import InstanceNormalization
class ConvLayer(tf.keras.layers.Layer):
def __init__(self, out_channels, kernel_size, stride, padding=None, data_format="channels_last"):
super().__init__()
self.data_... |
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
# Email you want to send the update from (only works with gmail)
fromEmail = '******@gmail.com'
# You can generate an app password here to avoid storing your passw... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 1 12:12:42 2017
@author: Andrew
"""
# Write a program that counts up the number of vowels
# contained in the string s. Valid vowels are:
# 'a', 'e', 'i', 'o', and 'u'. For example, if
# s = 'azcbobobegghakl', your program should print:
# Number of vowels: 5
s = s... |
from .base import BaseProvider
from .address import Address
from .business import Business
from .clothing import ClothingSizes
from .code import Code
from .date import Datetime
from .development import Development
from .file import File
from .food import Food
from .hardware import Hardware
from .internet import Interne... |
# id=5192
# Use the Python console in order to evaluate the value of each one of the following expressions.
# Before you start, make sure you create the following two sets:
# a = [1,2,3]
# b = [5,6,7]
# c = [1,2,3,4,5,6,7,8,9]
# The expressions you should check their values are:
# a * 2
# b * 3
# 71/5
# 71//5
# ... |
'''
Enumeration class that defines the type of data sets that contain results from data analysis in terms of its persistence
@author: S41nz
'''
class DataSetType:
#Enumeration values
#The data set is cacheable
CACHEABLE = 0
#The data set is feed on streaming
STREAMING = 1
#The data set re... |
from django.contrib import admin
from .models import User,Class,Article,Comment
# Register my own models.
class ArticleAdmin(admin.ModelAdmin):
fields = ['article_title','article_simpledesc','article_class','article_publisher','article_pubdate','article_content']
list_display = ('article_title','articl... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 6 14:08:44 2020
@author: shino
"""
import numpy as np
import pandas as pd
def read_bin(filename, shape=None, **kwargs):
""" Read a _raw binary_ file and store all possible elements in pandas DataFrame.
If the shape of the array is known... |
from zope.interface import alsoProvides, implements
from zope.component import adapts
from zope import schema
from plone.directives import form
from plone.dexterity.interfaces import IDexterityContent
from plone.autoform.interfaces import IFormFieldProvider
from plone.namedfile import field as namedfile
from z3c.relat... |
from fastapi import FastAPI
app = FastAPI(
title = "Logg API",
description = "An API for all your logging needs.",
version = "2.0",
)
class Log(BaseModel):
queueId: str
message: str
logType: str
logDate: str
@app.get("/loggapi/v2/logs/{appId}")
async def Logs(appId: str):
results = ... |
def type_check(type_of_arg):
def decorator(fn):
def wrapper(arg):
if type(arg) != type_of_arg:
return "Bad Type"
else:
func = fn(arg)
return func
return wrapper
return decorator
# @type_check(int)
# def times2(num):
# ... |
# -*- coding: utf-8 -*-
import datetime
import feedparser
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django_jinja import library
from jinja2 import pass_context
def render_feed_list(feeds, template):
return mark_safe(render_to_string(template, {'feeds': fe... |
class BoardMap():
'''
BoardMap
'''
def __init__(self, map_name):
self.map_name = map_name
|
"""Test Metadata"""
# pylint: disable=protected-access, missing-function-docstring
import pytest
from appmap._implementation.metadata import Metadata
from appmap.test.helpers import DictIncluding
def test_missing_git(git, monkeypatch):
monkeypatch.setenv('PATH', '')
try:
metadata = Metadata(root_di... |
from django.core.management.base import BaseCommand
from django.core.management.color import no_style
from django.db import connection
from django.contrib.auth.models import ContentType
class Command(BaseCommand):
help = 'Clear Django tables'
def add_arguments(self, parser):
parser.add_argument(
... |
# Time -> How many numbers that contain the num-input.
num = int(input())
count = 0
for h in range(num + 1):
for m in range(60):
for s in range(60):
if '3' in str(h) + str(m) + str(s):
count += 1
print(count)
|
import json
import os
import spotipy
import spotipy.oauth2 as oauth2
file_name = "spotify.json"
def auth():
print("Autoryzowenie...")
try:
f = open(file_name)
data = json.load(f)
f.close()
if data == {}:
raise Exception
except Exception as e:
print("Ca... |
# Generated by Django 3.1.2 on 2020-10-21 20:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('accounts', '0003_remove_profile_current_save'),
]
operations = [
migrations.CreateModel... |
# Path sum: two ways
#
with open('../sources/matrix.txt') as f:
source = f.read()
mtx = [[int(n) for n in line.split(',')] for line in source.splitlines()]
for y in range(len(mtx)):
for x in range(len(mtx[y])):
if x == 0 and y == 0:
continue
if x == 0:
mtx[y][x] += mtx... |
# content of conftest.py
import pytest
TEST_USER="test@test.com"
url_genss = [
("api.user_worksheet", {"user": "test@test.com", "worksheet": "test"}),
("api.user_gene_table", {"user": "test@test.com", "worksheet": "test", "cluster_name": "4"}),
("api.user_cluster_scatterplot", {"user": "tes... |
import pandas as pd
from stockdata.technical_indicators.indicators import Indicators
def addIndicators(df):
return Indicators().createIndicators(df)
def addMA(df, n):
return Indicators().MA(df, n)
def addEMA(df, n):
return Indicators().EsssMA(df, n)
|
import shutil
import os
import datetime
now = datetime.datetime.now()
print(now)
before = now - datetime.timedelta(hours = 24)
print (before)
def moveFiles():
source = "C:/Users/Student/Desktop/foldera/"
files = os.listdir(source)
destination = "C:/Users/Student/Desktop/folderb/"
for f in files:
... |
#3
def same_length(ls1, ls2):
if len(ls1) == len(ls2):
size = True;
else:
size = False;
return size
def add_list(ls1, ls2):
size = same_length(ls1,ls2)
newsum = []
newsumstr = ""
if size:
for i in range(len(ls1)):
newsum.append(ls1[i... |
import numpy as np
import pylab as pl
from scipy import stats
# load the data in
data = np.genfromtxt('ship-nmpg-imp.csv', delimiter=",", names=True, dtype="f8,i8,f8,f8,f8,f8,i8,i8,S25")
varnames = data.dtype.names
# we loop through names[1:-1] to skip nmpg and uid
for name in varnames[1:-1]:
slope, intercept, r_v... |
#=================================#
#============Kanagawa==============#
#=======For Tokyo Studio=====#
#==========Written by Dugy========#
#===========Apr 25th 2017==========#
#==Do not use without permission==#
#=================================#
from math import *
import random
import Rhino.Geometry as rg
... |
# -*- coding: utf-8 -*-
###############################################################################
#
# CreateVolume
# Creates a new EBS volume that your EC2 instance can attach to.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");... |
# just look at phi(n)/n and reason that minimizer is smooth
from sympy import isprime, nextprime
def red(n, p):
while n % p == 0:
n /= p
return n
def f(n, primes):
v = 1
n_r = n
for p in primes:
if p > n_r:
break
n_r = red(n_r, p)
if n_r != n:
... |
'''
------DEVICE 1-------
'''
import socket as sk
import time
import datetime
import random
device1_ip = "192.168.1.2"
device1_mac = "10:AF:CB:EF:19:CF"
gateway_ip = "192.168.1.1"
gateway_mac = "05:10:0A:CB:24:EF"
gateway_port = 8100
gateway = ("localhost", gateway_port)
ethernet_header = de... |
# -*- coding: utf-8 -*-
# Imprimir os 100 primeiros pares
numeros_pares = 0
numero_atual = 0
while numeros_pares < 100:
numero_atual += 2
numeros_pares += 1
print(numero_atual) |
import torch
import os
import pandas as pd
import numpy as np
from my_image_classification.data import test_transform
from torch.utils.data import DataLoader
import cv2
import torch
import timm
import torch.nn as nn
def get_model(model_name, out_features, drop_rate=0.5):
model = timm.create_model(m... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 07 15:46:30 2016
@author: auort
"""
from PIL import Image
from pylab import *
from numpy import *
from numpy import random
from scipy.ndimage import filters
import scipy.misc
"""
Write code to generate and display a series difference of Gaussian images ... |
import requests
import json
import frappe
from six.moves.urllib.parse import urlparse
from six.moves.urllib.parse import parse_qs
@frappe.whitelist()
def get_container():
try:
query_string = urlparse(frappe.request.url).query
# print(query_string)
query = parse_qs(query_string)
prin... |
import pandas as pd
import os
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data')
def get_question_list(csv_filename):
csv_data = pd.read_csv(os.path.join(path, csv_filename))
question_list = csv_data['QUESTION'].values.tolist()
return question_list
# question_list = get_question_... |
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponseRedirect
from calculater.models import History
def home_page (request):
return render(request,'home.html')
def me_page (request):
return render(request,'me.html')
def calpost_page (request):
showhistory ... |
import sys
import argparse
import os
import json
import html, string, re
import spacy
from spacy.lemmatizer import Lemmatizer
from spacy.lang.en import LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES
indir = '/u/cs401/A1/data/'
abbFile = '/u/cs401/Wordlists/abbrev.english'
stopFile = '/u/cs401/Wordlists/StopWords'
nlp = spacy.loa... |
# Generated by Django 3.0.6 on 2021-02-03 18:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('issueTracker', '0004_auto_20210203_1530'),
]
operations = [
migrations.AlterField(
model_name='ocorrencia',
name='en... |
import requests
def get_price_list_daily(symbol,key): #Connect with API and get Daily prices for one symbol
r = requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=%s&apikey=%s' % (symbol,key))
price = r.json() #Convert to JSON
price_list = price["Time Series (Daily)"] #Get the V... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sn
from sklearn import metrics
class Results(object):
"""a class to obtain classification results of a set of NNModel instances"""
def __init__(self, models, activityNames):
self.models = models
... |
from drf_spectacular.utils import extend_schema
from rest_framework import serializers, status
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
TokenVerifyView,
)
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
class MyTokenObtainPairSerializer... |
"""Users admin classes"""
#Django
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib import admin
#Models
from django.contrib.auth.models import User
from posts.models import Post
# Register your models here.
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
"""admin.site... |
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from django.views.generic import TemplateView
from django.views.i18n import javascript_catalog
from solid_i18n.urls import solid_i18n_patterns
from apps.front.vi... |
#!/usr/bin/env python
## For determing the number of alignments of novel genes/lncRNAs to each species
## In conjunction with the RNA-seq projecy
import os,sys
outputfile = str(sys.argv[2])
f = [line.strip() for line in open(sys.argv[1])]
w = open(outputfile,'a')
print >>w, sys.argv[1], f
|
import sys
sys.stdin = open("input.txt")
T = int(input())
# 완전탐색으로 풀면 시간초과
def func(n, result) : # 몇번째까지 왔는지
result_arr.add(result)
if n ==N :
return
func(n+1, result)
func(n+1, result+inp_arr[n])
for tc in range(1, T+1):
N = int(input())
inp_arr = list(map(int, input().split()))
... |
import json
import math
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def findIndex(n) :
a, b = 0, 1
for _ in range(n):
a, b = b, a+b
return a
def make_response(data, status):
response = {}
for k, v in data.items():
response[k] = v
response["s... |
from django.db import models
from .connection import Connection
class ConnectionSsh(Connection):
class Meta:
verbose_name = "SSH Connection"
verbose_name_plural = "SSH Connections"
# Settings are explained here:
# https://guacamole.apache.org/doc/gug/configuring-guacamole.html#ssh
#... |
# -*- coding=UTF-8 -*-
# pyright: strict, reportTypeCommentUsage=none
from __future__ import absolute_import, division, print_function, unicode_literals
import nuke
import wulifang
import wulifang.nuke
from wulifang._util import (
cast_text,
)
def _on_user_create():
n = nuke.thisNode()
class_ = cast_te... |
# -*- coding: utf-8 -*-
#
# satcfe/alertas.py
#
# Copyright 2015 Base4 Sistemas Ltda ME
#
# 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
#
# ... |
#!/usr/bin/env python
# encoding: utf-8
"""
Institut Villebon-Charpak
"""
from math import * # package pour les fonctions mathématiques (pi, cos, exp,...)
from random import * # package pour les nombres (pseudo)-aléatoires
a = 1
b = 1024
continuer = True
while continuer:
secret = randrange(a,b)
prin... |
#
# struct_test.py
# Nazareno Bruschi <nazareno.bruschi@unibo.it>
#
# Copyright (C) 2019-2020 University of Bologna
#
# 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.o... |
import os
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import pandas
import flask
server = flask.Flask('app')
server.secret_key = os.environ.get('secret_key', 'secret')
app = dash.Dash('app', server=server)
app.title = 'WCBU 2017 Stati... |
from StarWars import views
from django.conf.urls import url
"""
This file maps the URLs with the view functions.
"""
urlpatterns = [
url(r'^$', views.Index, name='Index'),
url(r'^load_data/$', views.HomePage, name='HomePage'),
url(r'^Search_Planet/$', views.SearchPlanet, name='SearchPlanet'),
url(r'^D... |
import sys
def Graph(nodes):
graph={}
for i in range(nodes):
graph[i]=[]
return(graph)
def addPath(n1,n2,weight,graph):
graph[n1].append([n2,weight])
graph[n2].append([n1,weight])
return(graph)
def generateMST(graph,start):
temp_graph={}
for i in graph:
temp_graph[i]=graph[i]
n=len(graph)
visited=[Fal... |
"""
CDC vital statistics
Link
* http://www.cdc.gov/nchs/data_access/vitalstatsonline.htm
Prepared for Data Bootcamp course at NYU
* https://github.com/DaveBackus/Data_Bootcamp
* https://github.com/DaveBackus/Data_Bootcamp/Code/Lab
Written by Dave Backus, January 2016
Created with Python 3.5
"""
"""
import pac... |
from flask import Blueprint
routes = Blueprint('routes', __name__)
from .index import *
from .other import *
|
import platform
from .image import ImageFloatRGBA
from ..samplers import Sample
class Film:
def __init__(self, width, height, renderer):
self._image = ImageFloatRGBA(width, height)
self._height = height
self._renderer = renderer
self._ds = None
self.set_pass(0)
def set... |
'''
03 - Faça um algoritmo que calcule a área de um triângulo, considerando a
fórmula (base*altura)/2 . Utilize as variáveis AREA, BASE e ALTURA.
#PORTUGOL#
Defina: area, base, altura: Real
INICIO
escreva ("Qual o tamanho da base do triângulo? ")
leia (base)
escreva ("Qual o tamanho da altura do triângulo?")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.