text stringlengths 8 6.05M |
|---|
import os
import json
import subprocess
from shutil import copyfile
from subprocess import PIPE, run as subprocess_run
from typing import List, Dict
from src.contracts.secret.secret_contract import swap_json
from src.util.config import Config
from src.util.logger import get_logger
logger = get_logger(logger_name="Sec... |
def innerProd(l1,l2):
if len(l1)==len(l2):
s = 0
for i in range(len(l1)):
s+= l1[i]*l2[i]
return s
def listScalarProd(l,s):
for i in range(len(l1)):
l1[i]=s*l1[i]
return l1
|
#!/usr/bin/env python
# -*-encoding:UTF-8-*-
from myutils.api import serializers
from myutils.api._serializers import UsernameSerializer
from .models import Announcement
class CreateAnnouncementSerializer(serializers.Serializer):
# 创建通知
title = serializers.CharField(max_length=64)
content = serializers.... |
def decrypt(encrypted_text, n):
if n < 1: return encrypted_text
output = ""
mid = len(encrypted_text)//2
e_text = encrypted_text
for x in range(n):
for i in range(mid):
output += e_text[mid+i]
output += e_text[i]
e_text = output
if n-1!=x:
... |
from django.http import HttpResponse
from django.shortcuts import render
# from rest_framework import status
from rest_framework import mixins
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework import filters
from rest_framework.pagination import PageNumberPagination # 分页功... |
"""
J7 VPAC specific configurations and methods.
"""
import os
import inspect
REPORT_CALLER = True
WAIT_ON_EXIT = False
AWB_MAX_IMG_CNT = 20
def init_params(sys_params):
# INITIALIZATION START
sys_params['LSC'] = {}
sys_params['AWB'] = {}
sys_params['AE'] = {}
sys_params['AE']['IMAGE'] = {... |
"""
The MyPaas setup script.
"""
import os
try:
import setuptools # noqa, analysis:ignore
except ImportError:
pass # setuptools allows for "develop", but it's not essential
from distutils.core import setup
def get_version_and_doc(filename):
ns = dict(__version__="", __doc__="")
docstatus = 0 # N... |
from enums import Direction, State, Symbol
def parse(f):
dic = {}
content = read(f)
transitions = content.split("\n\n")
print(transitions[0])
transitions = transitions[1:]
for t in transitions:
try:
src, dst = t.split("\n")
except:
if len(t.split("\n"))... |
# Generated by Django 3.0.4 on 2021-03-07 00:07
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0011_auto_20210307_0004'),
]
operations = [
migrations.AlterField(
model_name='answer',
... |
from math import sin, cos
import numpy as np
base = 10
def exact_sin_sum(K):
return .5 * (sin(K) - cos(.5) / sin(.5) * cos(K) + cos(.5) / sin(.5)) / K
def exact_sum(K):
"""Точное значение суммы всех элементов."""
return 1.
def samples_sin(N):
a = np.array([sin(i) / N for i in range(1, N + 1)])
... |
import numpy as np
from scipy.interpolate import RectBivariateSpline
z = np.ones((5,10))
z[3,3:5] = [1,2]
p = np.ones((2,1))
z=np.concatenate((p,p),axis=1)
print(z)
# x=np.arange(5)
# y=np.arange(7)
#
# func = RectBivariateSpline(x,y,z)
#
# x1 = np.linspace(1,4,3)
# y1 = np.linspace(2,5,5)
#
# print(x1)
# z1=func.__c... |
"""API v2 tests."""
from django.core.files.base import ContentFile
from django.urls import reverse
from django.utils.encoding import force_str
from rest_framework.authtoken.models import Token
from modoboa.admin import factories, models, constants
from modoboa.core import models as core_models
from modoboa.lib.tests... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 28 22:35:20 2019
@author: andrewbartels1
"""
import time
def tic():
#Homemade version of matlab tic and toc functions
global startTime_for_tictoc
startTime_for_tictoc = time.time()
def toc():
if 'startTime_for_tictoc' in globals():
print("Elapsed ... |
while True:
num = int(input('Quer ver a tabuada de qual valor? '))
if num < 0:
break
print('-' * 30)
for mult in range(1, 11, 1):
print(f'{num} x {mult} = {num * mult}')
print('-' * 30)
print('PROGRAMA TABUADA ENCERRADO. Volte sempre!')
|
"""
Converts pre-trained word embedding from stanford into hdf5 file.
http://nlp.stanford.edu/projects/glove/
"""
import sys
import h5py
import hashlib
import numpy as np
f = h5py.File("data/word_embeddint.hdf5", "w")
for p in sys.argv[1:]:
with open(p) as word_file:
for text_line in word_file:
... |
from Bio.Align.Applications import MuscleCommandline
from Bio import AlignIO
from Bio.Phylo.Applications import PhymlCommandline
from Bio import Phylo
import pylab
from Bio import SeqUtils
from Bio.SeqUtils import CodonUsageIndices, CodonUsage
import os
from Bio import SeqIO
def align(infile, outfile, clusta... |
import unreal
import AssetFunctions
def showAssetsInContentBrowser_EXAMPLE():
paths = ['/Game/Textures/MyTexture', '/Game/SkeletalMeshes/MySkeletalMesh', '/Game/Sounds/MySound']
AssetFunctions.showAssetsInContentBrowser(paths)
def openAssets_EXAMPLE():
paths = ['/Game/Textures/MyTexture', '/Game/Skeleta... |
# Generated by Django 3.1 on 2020-08-18 08:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0002_auto_20200817_1946'),
]
operations = [
migrations.AlterField(
model_name='post',
name='channelUsername',... |
from unittest import TestCase
from phi import field
from phi.field import Noise, CenteredGrid, StaggeredGrid
from phi.field._point_cloud import distribute_points
from phi.physics import advect
def _test_advection(adv):
s = CenteredGrid(Noise(), x=4, y=3)
v = CenteredGrid(Noise(vector='x,y'), x=4, y=3... |
# NAME: Derek Haugen
# CLASS: Compiler Construction - Hamer
# ASSIGN#: Assignment 1
# DESC: This is a simple lexical analyzer written to tokenize
# A subset of the C language. The lexer primarily utilizes
# regular expressions to match tokens from the input stream.
#
import re, sys, os
#These should be enum... |
#!/usr/bin/env python
import sys
import groovesparkb
from twisted.internet import reactor, defer
@defer.inlineCallbacks
def main(token):
gs = groovespark.GroovesharkAPI()
yield gs.initialize()
result = yield gs.send('getSongFromToken', dict(token=token), "more.php")
print result['SongID']
reactor... |
####################################################
##
## Projects suggested by CupOfCode01
## Name Generator using random, string
##
####################################################
import random, string, pprint, sys
#### quick create random string lowercase ascii of user selectable length
# length = input("h... |
import time
try:
import mysql.connector
except:
print("mysql-connector-python (installation reqd. - yes)")
time.sleep(3)
quit()
else:
pass
try:
import stdiomask
except:
print("stdiomask (installation reqd. - yes)")
time.sleep(3)
quit()
else:
pass
import ran... |
n = []
t = int(input())
while len(n) < 1000:
for c in range(0, t):
if len(n) < 1000:
n.append(c)
for i in range(len(n)):
print('N[{}] = {}'.format(i, n[i])) |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 29 22:44:40 2020
@author: HP
"""
a=float(input("enter the first number:"))
b=float(input("enter the second number:"))
c=float(input("enter the third number:"))
if(a>b and a>c):
print("first number is greather",a)
elif(b>c and b>a):
print("second numb... |
vvod = raw_input("input 4 numbers: ")
l = str(vvod)
sort = sorted(l)
print "sort of numbers: {}".format(sort)
a = sort[::-1]
print "revers of sort: {}".format(a)
res = int(l[0])*int(l[1])*int(l[2])*int(l[3])
print "mnozenna: {}".format(res)
|
from string import ascii_uppercase as alph
def caeser(message, key):
return ''.join(alph[(alph.index(x)+key)%26] if x.isalpha() else x for x in message.upper())
'''
You have invented a time-machine which has taken you back to ancient Rome. Caeser is impressed with
your programming skills and has appointed you to... |
"""Construct a profile with two hosts for testing ping
Instructions:
Wait for the profile to start,
run setupHost.sh on node1,
start additional monitoring if desired,
run experiment on node1,
collect data.
"""
# Boiler plate
import geni.portal as portal
import geni.rspec.pg as rspec
request = portal.context... |
"""
Robotritons testing version of compass navigation.
Purpose: Use a magnetometer to reliably steer the vehicle.
Requirements: An InvenSense MPU-9250. The python modules logging, sys, spidev, time, math, navio.util, VehiclePWMModule, and navio.mpu9250_better
Use: Input a desired direction and the vehicle will try to ... |
# GETTING HELPER FUNCTION AND LIBRARIES
from prediction_helper import *
import cv2 as cv
# reading image
path = input("Enter the path of the image : ")
path = f"{path}"
img = cv.imread(path)
if img.shape[0] > 1080 and img.shape[1] > 1920:
img = cv.resize(img,(img.shape[1]//3,img.shape[0]//3))
gray = cv.cvtColo... |
from django.core.management.base import BaseCommand
from django.db import connection
from organisations.models import (
DivisionGeographySubdivided,
OrganisationGeographySubdivided,
)
class Command(BaseCommand):
help = "Populate the subdivided tables"
def handle(self, *args, **options):
with ... |
class Solution:
def minDeletion(self, nums: List[int]) -> int:
n = len(nums)
res = 0
# 从左往右
# 如果遇到i%2==0, 且num[i] == num[i+1]
# 有两种选择一个是删除num[i],一个是删除num[i+1],且必须选择一个
# 因为两种选择对后面是等价的所以无所谓,属于是sb题了
# 注意删除后长度不是偶数的话,再在结尾删除一个就行
for i in range(n):
... |
#!/usr/bin/env python
"""
Author: Patrick Monnahan
Purpose: This script creates a bed file of NON-genic regions to be excluded in structural variant discovery
Takes the following arguments:
-gff : Full path to gff file containing gene locations (can contain other elements as well...these will just be ignored)
-b... |
#!/usr/bin/env python
#------------------------------------------------------------------------------
# Copyright 2008-2011 Istituto Nazionale di Fisica Nucleare (INFN)
#
# Licensed under the EUPL, Version 1.1 only (the "Licence").
# You may not use this work except in compliance with the Licence.
# You may obtain a co... |
import dash_bootstrap_components as dbc
from dash import html
pagination = html.Div(
dbc.Pagination(max_value=10),
)
|
#
# This file is part of LUNA.
#
# Adapted from lambdasoc.
# This file includes content Copyright (C) 2020 LambdaConcept.
#
# Per our BSD license, derivative files must include this license disclaimer.
#
# Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com>
# SPDX-License-Identifier: BSD-3-Clause
""" P... |
import requests, json, datetime
#records the initial game data
def record_data(game, date):
with open('data.json', 'r') as f:
data = json.load(f)
try:
data[date].append(game)
except KeyError:
data.update({date: [game]})
return data
#logs the summoner info and prints it out
def ... |
import sys
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.ticker
import seaborn as sns
plotfile = sys.argv[0].replace('.py', '.pdf')
sns.set_style('ticks')
fig, axes = plt.subplots(2, 3, figsize=(9, 6), sharex=True, sharey=True)
sin_inc_edges = np.linspace(0.0, 1.0, len(axes.flat)+1)
sin_... |
# -*- coding: utf-8 -*-
{
'name': "Boxwise Point-of-Sale",
'summary': """
POS for Free Shops
""",
'author': "Humanilog",
'website': "www.humanilog.org",
'category': 'Uncategorized',
'version': '11.0.1.0.0',
'depends': [
'pos',
],
'data': []
}
|
from flask import Blueprint, request, jsonify
from utils.decorators import ErrorHandler
from flask_jwt_extended import (
jwt_required,
jwt_refresh_token_required
)
from .responses import AuthenticationResponse, TokenResponse
from .permissions import admin_required, prohibitted
import logging
from flaskr import ... |
import sys
from pygments.formatters import HtmlFormatter
class CustomFormatter(HtmlFormatter):
def quote(self, tokensource):
for type, text in tokensource:
yield type, text.replace(' ', '{{{space}}}').replace('`', "{{{backtick}}}")
def format(self, tokensource, outfile):
source... |
from initial_prediction import *
from objective_function.main import *
import pandas as pd
"""
mark the data without optimization
"""
def mark2csv(filename,output_name,label):
with open("%s"%filename,'r') as f_read:
content = f_read.readlines()
marked_content = []
for each in content:
try:
... |
import pickle
infile = open('temptable.50-50','rb') #open the file temptable for reading('rb')
(temperatures, grainsizes, radii, Tdict) = pickle.load(infile) #Load in the 'pickled' file. This file returns a tuple (single item consisting of multiple values of potentially varying data types. In this case the first it... |
import json
from kafka import KafkaConsumer
TOPIC_NAME = 'test-topic'
# To consume latest messages and auto-commit offsets
# You can desable auto-commit with enable_auto_commit=False flag
# consume json messages
consumer = KafkaConsumer(TOPIC_NAME,
group_id='test-group',
... |
import json
with open('bus_routes/(1)kingCountyMetro.json') as kc_metro:
kc_data = json.load(kc_metro)
with open('bus_routes/(3)pierceTransit.json') as pierce:
pt_data = json.load(pierce)
with open('bus_routes/(19)intercityTransit.json') as intercity:
it_data = json.load(intercity)
with open('bus_routes/(2... |
import pdb
import random
import pylab as pl
from scipy.optimize import fmin_bfgs
import numpy as np
from gradDescent import basic_gradient_descent, approximate_gradient_descent
# X is an array of N data points (one dimensional for now), that is, NX1
# Y is a Nx1 column vector of data values
# order is the order of the... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from typing import ClassVar
from pants.bsp.protocol import BSPHandlerMapping
from pants.bsp.spec.lifecycle import (
BuildServerCapabilities,
Com... |
# ---------------------------------------------------------------------------
# extract_basin_prism_values.py
# Created on: 2014-07-22 18:30:25.00000 (generated by ArcGIS/ModelBuilder)
# Description: extract prism data from raster using basin shapefiles as mask
# and output a csv file for each basin
# UPDATED (8/4... |
monty_python = "Monty Python"
print(monty_python)
print(monty_python.lower())
print(monty_python.upper()) |
# -*- coding: utf-8 -*-
import uuid, datetime,psycopg2,inject
from model.systems.offices.offices import Offices
from model.systems.assistance.date import Date
class Issue:
date = inject.attr(Date)
offices = inject.attr(Offices)
# ---------------------------------------------------------------------------... |
import pandas as pd
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense, Dropout, BatchNormalization
from sklearn.metrics import accuracy_score
from keras.utils import to_categorical
import numpy as np
#붓꽃데이터 읽어들이기
colnames = ['SepalLength', 'SepalW... |
from . import admin, image_upload
|
# Copyright (c) 2017 UFCG-LSD.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
""" Regular packages
Import Base Store / BaseStoreMetaData
"""
from .base import BaseStores
__all__ = [
'BaseStores',
]
|
class Solution(object):
def generateMatrix(self, n):
A = [[0] * n for _ in range(n)]
i, j, di, dj = 0, 0, 0, 1
for k in xrange(n*n):
A[i][j] = k + 1
if A[(i+di)%n][(j+dj)%n]:
di, dj = dj, -di
i += di
j += dj
return A
cl... |
from mongo_db import MongoDB
def main():
# connect to mongodb
mongodb = MongoDB("iamr0b0tx", "DJ0Qb8XqulWFUXQK", "Cluster0", "business")
# mongodb = MongoDB("ds", "gg", "Cluster0", "business")
# create businesses
print(mongodb.create({'name': 'Kitchen', 'rating': 1, 'cuisine': 'Pizza'}))
# r... |
#!/usr/bin/env python3
"""unhang_console_by_Threads_SIGALRM.py
Author: Joseph Lin
Email : joseph.lin@aliyun.com
Social:
https://github.com/RDpWTeHM
https://blog.csdn.net/qq_29757283
Note:
signal.alarm(integer) ==> SIGALRM
alarm may can't not work well with sleep in some python version.
"""
# import sys
impo... |
'''
Class TextVisualization is defined in mesa/visualization
TextVisualization: Class meant to wrap around a Model object and render it in some way using Elements, in turn, renders a particular piece of information as text.
TextData: Uses getattr to get the value of a particular property of a model and prints it, alo... |
# ****************************************************************** #
# ************************* Byte of Python ************************* #
# ****************************************************************** #
########################
# using_sys
########################
# import sys
# print("The command ... |
import unittest
from katas.kyu_6.bit_counting import countBits
class CountBitsTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(countBits(0), 0)
def test_equals_2(self):
self.assertEqual(countBits(4), 1)
def test_equals_3(self):
self.assertEqual(countBits(7), ... |
'''
Identity Service tokens
'''
from . import credentials
def get():
""" Retrieve a keystone token """
return credentials.keystone().auth_token
|
expDir = '../exp'
nThreads = 4 |
# Import the random package to radomly select individuals
import random
# Import the superclass (also called base class), which is an abstract class,
# to implement the subclass ThresholdSelection
from SelectionOperator import *
# The subclass that inherits of SelectionOperator
class RouletteWheelSelection(SelectionO... |
# Copyright 2017 The Forseti Security 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 ap... |
t = int(input())
while t > 0:
n,m = map(int,input().split())
arr = []
for k in range(n):
a = list(map(str,input().split()))[:m]
arr.append(a)
for i in range(n):
for j in range(m):
if arr[i][j] == '*':
arr[i][j] = 1
elif arr... |
"""added sentiment column
Revision ID: 2c7915255466
Revises:
Create Date: 2019-07-16 12:14:55.838697
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2c7915255466'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 22:18:46 2018
@author: ck
"""
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import time
import random
import tweepy
import os
import json
import io
from datetime import datetime
import re
##... |
cont = 0
soma = 0
maior = 0
menor = 0
opc = ''
while opc != 'n':
num = int(input('Digite um número: '))
cont += 1
soma += num
if cont == 1:
maior = num
menor = num
else:
if maior < num:
maior = num
if menor > num:
menor = num
opc = str(inpu... |
#------------------------ LIBRERÍAS --------------------------------
import numpy as np
from PIL import Image
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from bs4 import BeautifulSoup
from urllib.request import Request
from tabulate import tabulate
from itertools import zip_longest
import requests
... |
# Generated by Django 3.0.6 on 2020-05-24 16:13
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mdpapp', '0002_auto_20200524_1557'),
]
operations = [
migrations.AlterModelOptions(
name='family',
options={'verbose_name_pl... |
def test_HDL_analysis():
from chol_analysis import HDL_analysis
answer = HDL_analysis(80)
expected = "normal"
assert answer == expected
def test_HDL_analysis():
from chol_analysis import HDL_analysis
answer = HDL_analysis(40)
expected = "borderline low"
assert answer == expected |
def triangular(n):
return (n**2+n)/2 if n>0 else 0
'''
Triangular numbers are so called because of the equilateral triangular shape that they occupy when laid out as dots. i.e.
1st (1) 2nd (3) 3rd (6)
* ** ***
* **
*
You need to return the nth trian... |
from unittest import TestCase
class TestBase(TestCase):
pass
|
n = int(input("Ingrese un numero: "))
if n==0:
print("Es neutro")
elif n>0:
print("Es positivo")
else:
print("Es negativo")
|
#!/usr/bin/env python3
# ----------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016, Heiko Möllerke
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to dea... |
#insertion sort demo
def insertionsort(arr):
n = len(arr)
for i in range(1, n):
ccard = arr[i]
j = i
while (j>0) and (arr[j-1] > ccard):
arr[j] = arr[j-1]
j = j - 1
arr[j] = ccard
return arr
def sort (arr,type):
if(type=='insertionsort'):
... |
import os
import platform
###########################
#Initial Input
"""Faculty list is used as initial input for the whole program.
This list is generated manually to make sure its accuracy. University
names and faculty names must be close to the names stored in the Scopus
database"""
faculty_list = "da... |
# coding=utf-8
"""Version related views."""
import logging
logger = logging.getLogger(__name__)
# noinspection PyUnresolvedReferences
import logging
logger = logging.getLogger(__name__)
import re
import zipfile
import StringIO
import pypandoc
from django.core.urlresolvers import reverse
from django.shortcuts import ... |
def multiplication_table(n):
"""prints multiplication table up to 10"""
for i in range(1, 11):
print(i, '*', n, '=', (i * n))
n = int(input("Enter the number"))
print("The multiplication Table of %d is"%n)
multiplication_table(n)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
update_nvl_polygon_element_query = """
UPDATE public.nvl_polygon AS npg SET
user_id = $2::BIGINT,
{}
deleted = TRUE
WHERE npg.location_id = $1::BIGINT RETURNING *;
"""
|
import csv
class Csvreader:
def __init__(self,csvfile):
self.csvfile = csvfile
def reader(self):
csvfileopen = open(self.csvfile,'rb')
reader = csv.reader(csvfileopen)
return reader
def dictOfAllApartments(self):
dictOfFlats = {}
read = self.reader()
... |
# *_* coding=utf8 *_*
#!/usr/bin/env python
config = [
("redis_host", "127.0.0.1"),
("debug", True),
("redis_cache_db", 0),
("redis_session_db", 1),
("redis_port", 6379),
("backend_expire_seconds", 300),
("http_listen_port", 80),
("site_host", "www.gg654.com"),
("session_expire_seco... |
# -*- coding: utf-8 -*-
__author__ = 'lish'
import bs4
import re,json,os,codecs,hashlib
import time,datetime
import urllib2,requests,MySQLdb
import StringIO, gzip
import sys
reload(sys)
sys.setdefaultencoding('utf8')
# base_path='/opt/www/ec_con'
base_url='http://s.haohuojun.com/'
base_path=os.path.split( os.path.realp... |
'''
Author: Aditi Nair (asn264)
Date: November 3rd 2015
'''
import sys
import math
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
class HealthDataAnalyzer(object):
'''Each instance of this class represents a tool for analyzing the NYC DoH data. It relies on the data-cleaning and grade... |
from django.db import models
from dataprocessing.models import Items
|
from flask import Flask, render_template,redirect,url_for,request
import twitterscraper
from twitterscraper import query_tweets
import datetime as dt
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import os
app = Flask(__name__)
@app.route('/')
def student():
return render_template('student.htm... |
from django.contrib import admin
from .models import FullSizeNPC, HeaderImage, Dialogue
@admin.register(FullSizeNPC, HeaderImage, Dialogue)
class MainAdmin(admin.ModelAdmin):
pass
|
from django.db import models
from django.core.validators import FileExtensionValidator
# Create your models here.
class UploadData(models.Model):
"""
Model to store uploaded data to a location MEDIA_ROOT/uploads/ folder
"""
upload = models.FileField(upload_to='')
|
#!/bin/env python
"""
ng -- gets the nearest galaxies
USAGE:
./ng.py [ra]
"""
import csv
import os
import sqlite3
import numpy, math
import geohash2
from math import sin, cos, radians, sqrt, atan2, degrees
import copy
__author__ = "Josh Bloom"
__version__ = "10 Nov 2008"
if os.environ.has_key("TCP_DIR"):
DATADIR... |
import os
n = 0
for root, dirs, files in os.walk('./'):
for name in files:
if(name.endswith(".png")):
n += 1
print(n)
os.remove(os.path.join(root, name))
|
s1,s2,s3=map(str,input().split())
a=int(s3)
count=0
for x in range(0,len(s1)):
if(s1[x]!=s2[x]):
count=count+1
if(count==a):
print("yes")
else:
print("no")
|
import logging
import numpy as np
class EnsembledModel(object):
"""Ensemble of multiple models."""
def __init__(self):
self._models = []
"""`list` of `model.Model`: List of models to be ensembled."""
def add_model(self, model):
"""Adds model to the list of models to be ensembled.... |
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from Database import Database
class MovieDialog(Gtk.Dialog):
def __init__(self, parent, action):
Gtk.Dialog.__init__(self, action + " a Movie", parent, Gtk.DialogFlags.MODAL, use_header_bar = True)
self.db = Database(Database.location)
... |
# KeypointCapture.py
# For storing captured keypoints from OpenPose
# Primarly taken from the work of Damon Gwinn, Clarkson University
import numpy as np
import glob
import json
import copy
import pdb
# Globals that define the order of the keypoints
ORDERED_KEYPOINTS_BODY = [
"Nose",
"Neck",
"RShoulder",
"RElbow",
"... |
# Python program for implementation
# of Bisection Method for
# solving equations
from sympy import *
import os.path
def func(expr, value, x):
return expr.subs(x, value)
# Prints root of func(x)
# with error of EPSILON
def bisection(a, b, expr, maxIteration, Epsilon, x):
print("In bisectiooon")
file = ope... |
from ABC.Instruction import Instruction
from ABC.NodeAST import NodeAST
from ST.Exception import Exception
from ST.SymbolTable import SymbolTable
from ST.Symbol import Symbol
from ST.Type import TYPE
from ST.Type import getTypeString
import copy
class ArrayDeclarationType2(Instruction):
def __init__(self, typeDec... |
class TicTacToe:
def __init__(self, beginner):
self.player = beginner
self.gf = [[None, None, None],
[None, None, None],
[None, None, None]]
def swap_player(self):
if self.player is "X":
self.player = "O"
elif self.player is "O":... |
from django import template
register = template.Library()
def include_filter(value,values):
return True if value in [int(str(x)) for x in values] else False
register.filter('include', include_filter) |
def most_frequent_item_count(collection):
return max([collection.count(i) for i in collection]) if len(collection) > 0 else 0
'''
Complete the function to find the count of the most frequent item of an array.
You can assume that input is an array of integers. For an empty array return 0
Example
input array: [3, ... |
import telegram
import logging
import json
import os
from flask import Flask
from flask import request
app = Flask(__name__)
app.secret_key = 'aYT>.L$kk2h>!'
bot = telegram.Bot(token=os.environ["BOT_TOKEN"])
chatID = os.environ["CHAT_ID"]
@app.route('/alert', methods=['POST'])
def postAlertmanager():
content = js... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.