text stringlengths 8 6.05M |
|---|
import os
import sys
import pandas as pd
# for GUI Version
from appJar import gui
appg=None
csv_path=None
df=None
df_select=None
def intro():
'''
Shows description of this program.
'''
# os.get_terminal_size is some os class type. See it's attributes
# using dir(size). The one we needed here was column... |
A=int(input("A= "))
hundred=int(A/100)
tens=int(A/10%10)
ones=int(A%10)
print(hundred*10+tens*100+ones) |
import pygame as py
import dice_chess
import random
from network import Network
"""
Placed this part of code in server file
qw = dice_chess.queen(7, 3, 0)
qb = dice_chess.queen(0, 3, 1)
kw = dice_chess.king(7, 4, 0)
kb = dice_chess.king(0, 4, 1)
rw1 = dice_chess.rook(7, 0, 0)
rw2 = dice_chess.rook(7, 7... |
#!/usr/bin/env python
import unittest
from xml.dom.minidom import parseString
import xml.etree.ElementTree as ET
from decimal import Decimal
from gomatic import GoCdConfigurator, FetchArtifactDir, RakeTask, ExecTask, FetchArtifactTask, \
FetchArtifactFile, Tab, GitMaterial, PipelineMaterial, Pipeline, PackageMat... |
from random import randint
from time import sleep
from mass_whois.config import get_config
from django.core.management.base import BaseCommand
import requests
def main_loop():
coserver_endpoint = get_config('COSERVER_ENDPOINT')
#'http://127.0.0.1:8000/coserver/'
print 'get data from' + coserver_endpo... |
import numpy as np
import cv2
from clize import run
def convert_HSV_to_IJSV(img_arr):
height, width, depth = img_arr.shape
res = np.zeros((height, width, 4), np.uint8)
hue = img_arr[:,:,0]
sat = img_arr[:,:,1]
val = img_arr[:,:,2]
res[:,:,2] = sat
res[:,:,3] = val
y = 0
while y < height:
row = np.multiply(h... |
# -*- coding: utf-8 -*-
import command
from django.core.management.base import BaseCommand
class SubCommand(command.SubCommand):
pass
class Command(BaseCommand, command.Command):
def run_from_argv(self, argv):
return self.run(argv[1:])
|
from .abstract_repository_analyzer import AbstractRepositoryAnalyzer
from git import Repo
from git import InvalidGitRepositoryError
import subprocess
import os
import logging
class GitRepositoryAnalyzer(AbstractRepositoryAnalyzer):
"""
Analysis plug-in for Git-Repositories.
"""
def count_repo_branche... |
# ่ช็ถๆฐNใใณใใณใใฉใคใณๅผๆฐใชใฉใฎๆๆฎตใงๅใๅใ๏ผๅ
ฅๅใฎใใกๆซๅฐพใฎN่กใ ใใ่กจ็คบใใ
# ็ขบ่ชใซใฏtailใณใใณใใ็จใใ๏ผ
#!usr/bin/env python
# -*- coding:utf-8 -*-
import sys
N=sys.argv[1]
assert len(sys.argv) is 2,"[usage]: python nock_14.py N"
lines = [line for line in open("hightemp.txt","r")]
print(''.join(lines[-int(N):]),end="")
# with open("hightemp.txt") as f:
# ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 19 14:26:12 2021
@author: Sotiris
"""
import os
import numpy as np
import pandas as pd
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import TensorDataset, DataLoader
import imageio
from random import seed
from sklea... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.search, name="search"),
path('photo/', views.photo, name="search_photo"),
path('design/', views.design, name="search_design"),
path('photo/<int:pk>/', views.photoByid, name="search_photo"),
path('design/<int:pk>/', view... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""System Information Gathering Script
"""
import subprocess
from sys import stdout
def uname():
"""uname command function"""
print "\n\n"
uname = "uname -a"
printline1 = """
\rGathering system information using `{0}` command\r
""".format(uname... |
import pandas as pd
import numpy as np
import requests
tickers = ['eth','ada','btc','xmr','xrp','ltc']
coin_info = {}
for ticker in tickers:
tmp = requests.get('https://coinmetrics.io/data/'+ticker+'.csv')
df = pd.read_csv(pd.compat.StringIO(tmp.text))
df = df.reset_index()
df.columns = np.appe... |
from responses.conf import settings
from responses.models import Response
from responses.serializers import ResponseSerializer
from responses.tasks import add_survey_response, publish_survey_data
from responses.utils.importers import import_class
from rest_framework.views import APIView
from rest_framework.response imp... |
import pygame
from pygame.locals import *
import random
import time
## Type "pygame.display.quit()" in the GUI to exit
## The first center is 87x87
## The second center is 187x187
## The third center is 287x287
class Game_Info_1(object):
## Enter tile info here
bList = ['Jason','Hercules','Theseus','Odesseus'... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import unittest
import pytx3.common
class TestCommon(unittest.TestCase):
def test_camel_case_to_underscore(self):
assert pytx3.common.camel_case_to_underscore("AbcXyz") == "abc_xyz"
|
"""
ai-architecture-template - test_notebooks.py
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
"""
import pytest
from azure_utils.dev_ops.testing_utilities import run_notebook
from notebooks import directory
@pytest.mark.parametrize(
"notebook",
['00_AMLConfigura... |
from utils import read_plaintext_to_stream, convert_stream_to_plaintext
from cipher import cipher
from inv_cipher import inv_cipher
from key_expansion import key_expansion
import logger
def encrypt_decrypt(plaintext, key, decrypt=False):
logger.plaintext(plaintext)
logger.key(key)
data = read_plaintext_to... |
#!/usr/bin/env python
import os
import sys
# Using below code for tornado
import tornado.httpserver
import tornado.ioloop
import tornado.wsgi
import django.core.handlers.wsgi
from django.core.wsgi import get_wsgi_application
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "blog.setti... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 29 11:10:11 2020
@author: user
"""
import numpy as np
import pandas as pd
import os
import cv2
import random
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling... |
from flexp.browser import MainHandler
from os import path
class FeaturesHandler(MainHandler):
def initialize(self, experiments_folder, html_chain):
self.experiments_folder = experiments_folder
self.html_chain = html_chain
def create_title(self, experiment_folder, data):
annotation_id... |
# -*- coding: utf-8 -*-
from django.conf.urls import url, include
from adminapp.views import index, bienvenido
from adminapp.views import conexion_new, conexion_list, conexion_edit, conexion_delete
from adminapp.views import servicio_new, servicio_list, servicio_edit
from adminapp.views import directorio_new, directori... |
"""
Types, identify yourself!
Even if you are a function/mono-type/monad!
It's somewhat about static type and Py-skell layer of type
"""
from Pyskell.Language.HMTypeSystem import *
import types
__python_builtins__ = {
types.BooleanType, types.BufferType, types.BuiltinFunctionType,
types.BuiltinMethodType, type... |
# Generated by Django 3.2.6 on 2021-08-24 17:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ip_address', '0003_measurement'),
]
operations = [
migrations.AddField(
model_name='visitor',
name='latitud',
... |
# Method 1 --> 344ms (Using Binary Search and List as Data Structure) || 17700 kb
import bisect
class MyHashSet:
def __init__(self):
self.hashset = []
def present(self, key: int):
if self.hashset:
l = 0
u = len(self.hashset)-1
flag = False
... |
from google.cloud import translate
from managers.cache import CacheManager
class TranslateManager(object):
def __init__(self,langs=[],params={}):
self.params = params
print(self.params)
print(params)
self.langs = langs
self.client = translate.Client()
self.cache_ma... |
from easystruct import *
class S(EasyStructBase):
s: EasyStruct('10s')
ull: EasyStruct('Q')
c: EasyStruct('s')
class A(EasyStructBase):
a: EasyStruct('<4H')
b: EasyStruct('<12s')
class C(A):
a: A
b: EasyStruct('H')
def _create(cls, *args):
print(80 * '=')
c = cls(*args)
p... |
from threading import Thread
from MathFunctions import *
class WieferichThread(Thread):
def __init__(self, range_start, range_end):
Thread.__init__(self)
self.range_start = range_start
self.range_end = range_end
def run(self):
self.search_wieferich()
def search_wieferich(... |
# coding: utf-8
import sys
from os.path import dirname, abspath
sys.path.append(dirname(dirname(abspath(__file__))))
import struct
import logging
logging.basicConfig(level=logging.INFO)
import zmq
from modules.constants import *
ids = ["1", "2"]
msg_id = 0
identities = []
identity_backend = {}
backend_dict = {}
he... |
import os
# info, warning ์ ๊ฑฐ
os.environ['TF_CPP_MIN_LOG_LEVEL'] ='2'
import tensorflow as tf
import pandas as pd
import numpy as np
import datetime
from distutils.dir_util import copy_tree
import shutil
import json
import requests
import math
import joblib
import sys
model_dir = './model/'
m_pred_dir =... |
import numpy as np
import sys
from environments.openai_environment import OpenAIEnvironment
from algorithms.deep_q_learning import DeepQLearning
from absl import flags
def main():
"""Cartpole example"""
# Load environment
env = OpenAIEnvironment('CartPole-v0')
algorithm = DeepQLearning(gamma = 0.95,... |
class Solution:
def maxIceCream(self, costs: List[int], coins: int) -> int:
costs.sort()
ic = 0
while coins>0 and len(costs)!=0:
c = costs.pop(0)
if c<=coins:
ic+=1
coins-=c
else:
break
return ic
... |
# coding:utf-8
__author__ = "golden"
__date__ = '2018/6/29'
PID_FILE = "jspider.pid"
LOG_PATH = "log"
SPIDER_PATH = 'spiders'
WEB_DOMAIN = '193.168.4.101'
WEB_SERVER = {
'host': '0.0.0.0',
'port': 8081,
'debug': True,
'ssl': None,
'sock': None,
'protocol': None,
'backlog': 100,
'stop_e... |
import pymysql
import datetime
import re
class Db:
db = None
cursor = None
@staticmethod
def table_exists(con, table_name):
sql = "show tables;"
con.execute(sql)
tables = [con.fetchall()]
table_list = re.findall('(\'.*?\')', str(tables))
table_list = [re.sub("'"... |
def is_palindrome(word):
length = len(word)
for i in range(0, length//2):
if word[i] == word[length - i - 1]:
continue
else:
return 0
return 1
word = input()
print(is_palindrome(word))
|
# ่ฟญไปฃๅจไธ็ๆๅจ
from collections import Iterator
isinstance((x for x in range(10)), Iterator)
# iter()ๅฝๆฐ่ทๅพไธไธชIteratorๅฏน่ฑกใ
it = iter([1, 2, 3, 4, 5])
while True:
try:
# ่ทๅพไธไธไธชๅผ:
x = next(it)
except StopIteration:
# ้ๅฐStopIterationๅฐฑ้ๅบๅพช็ฏ
break
# ไธ่พนๅพช็ฏไธ่พน่ฎก็ฎ็ๆบๅถ๏ผ็งฐไธบ็ๆๅจ
def fib(max):
n, a, b... |
#!usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
__author__ = 'Sapocaly'
from utils import DBconfig
import xmlrpclib
import utils.PathHelper
utils.PathHelper.configure_dir()
import src.DB.Entry as Entry
import src.DB.DAL as DAL
#DB saving related
# config = DBconfig.DBConfig("conf/byyy_ba_db.cfg")
# c... |
"""
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
"""
class Solution(object):
def letterComb... |
#!/usr/bin/env python
#Bao Dang
#Assignment 2
"""Fot this problem, since the list python starts at 0, the forest is supposed to start at 0 """
class huffman_algorithm:
def __init__(self):
self.FOREST = []
self.ALPHABET = []
self.TREE = []
self.least = 0
self.secon... |
# ็ฌฌไธ็ง๏ผfor in
tuple1 = ("a", "1", 1, "b", "c", "c")
for value in tuple1:
print("value=", value)
print("--------------------")
# ็ฌฌไบ็ง๏ผไฝฟ็จๅ
็ฝฎๅฝๆฐenumerate()
tuple2 = ("a", "1", 1, "b", "c", "c")
for index, value in enumerate(tuple2):
print("index=", index, "value=", value)
print("-------------------- ")
# ็ฌฌไธ็ง๏ผไฝฟ็จrange... |
from flask import Flask, render_template, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from datatables import ColumnDT, DataTables
import datetime
import random
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sites.db'
db = SQLAlchemy(app)
class User(db.Model) :
__tablename__ ... |
import json
from asyncio import sleep
from collections import defaultdict
from aiotg import TgBot
from secrets import token, botan
from atlantis.translations import en, ru
bot = TgBot(token, botan_token=botan)
users = defaultdict(dict)
@bot.command(r'/start')
async def start(chat, match):
users[chat.id] = Atl... |
import numpy as np
def rss(y_true, y_pred, df=None):
return ((y_true - y_pred) ** 2).sum()
def cv(y_true, y_pred, df):
return (((y_true - y_pred) / (1 - df)) ** 2).sum()
def gcv(y_true, y_pred, df):
return rss(y_true, y_pred) / ((1 - (df / len(y_true))) ** 2)
def aic(y_true, y_pred, df):
return ... |
#!/usr/bin/python
import time
import numpy as np
import sys
#tos stuff
from DecodedMsg import *
from tinyos.message import MoteIF
class MyClass:
def __init__(self,N):
self.prevtime = time.time()
self.N = N
self.A = make_A_matrix(self.N)
self.current_row = 0;
# Create a MoteIF
self.mif = MoteIF.MoteIF()
... |
def get_number_from_string(strng):
return int(''.join(a for a in strng if a.isdigit()))
|
import ConfigParser
import os
import sys
configurationFile = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'../config/main.ini')
if not os.path.exists(configurationFile):
print 'Could not find configuration file: %s' % configurationFile
sys.exit(1)
try:
config = ConfigParser.RawConfigPa... |
# ๋ฌธ์ ์ค๋ช
# ์ ์ฌ์๊ฐ์ ๋๋์ด ๋ค์ด, ์ผ๋ถ ํ์์ด ์ฒด์ก๋ณต์ ๋๋๋นํ์ต๋๋ค. ๋คํํ ์ฌ๋ฒ ์ฒด์ก๋ณต์ด ์๋ ํ์์ด ์ด๋ค์๊ฒ ์ฒด์ก๋ณต์ ๋น๋ ค์ฃผ๋ ค ํฉ๋๋ค. ํ์๋ค์ ๋ฒํธ๋ ์ฒด๊ฒฉ ์์ผ๋ก ๋งค๊ฒจ์ ธ ์์ด, ๋ฐ๋ก ์๋ฒํธ์ ํ์์ด๋ ๋ฐ๋ก ๋ท๋ฒํธ์ ํ์์๊ฒ๋ง ์ฒด์ก๋ณต์ ๋น๋ ค์ค ์ ์์ต๋๋ค. ์๋ฅผ ๋ค์ด, 4๋ฒ ํ์์ 3๋ฒ ํ์์ด๋ 5๋ฒ ํ์์๊ฒ๋ง ์ฒด์ก๋ณต์ ๋น๋ ค์ค ์ ์์ต๋๋ค. ์ฒด์ก๋ณต์ด ์์ผ๋ฉด ์์
์ ๋ค์ ์ ์๊ธฐ ๋๋ฌธ์ ์ฒด์ก๋ณต์ ์ ์ ํ ๋น๋ ค ์ต๋ํ ๋ง์ ํ์์ด ์ฒด์ก์์
์ ๋ค์ด์ผ ํฉ๋๋ค.
# ์ ์ฒด ํ์์ ์ n, ์ฒด์ก๋ณต์ ๋๋๋นํ ํ์๋ค์ ๋ฒํธ๊ฐ ๋ด๊ธด ๋ฐฐ์ด lost, ์ฌ๋ฒ์ ์ฒด์ก๋ณต์ ๊ฐ์ ธ... |
#Nombre: Bianca Munteanu
#Asignatura: Programaciรณn para el tratamiento de datos
# Ejercicio 1, ejercicio 2 y ejercicio 3 de la PEC2
# Ejercicio 2: Realizar un programa que guarde los elementos en comรบn que tienen dos listas.
#modulos
def comunes_listas(list1, list2):
""" list1() + list2() --> list3()
... |
from itertools import cycle
def phase(seq, n):
base = [0, 1, 0, -1]
mod_seq = [x for x in seq]
pattern_iter = cycle(base)
new_seq = []
v = 0
next(pattern_iter)
for i in range(1, n+1):
v = 0
mul = next(pattern_iter)
for s in mod_seq:
v += s * mul
... |
from _typeshed import Incomplete
def newman_betweenness_centrality(
G,
v: Incomplete | None = None,
cutoff: Incomplete | None = None,
normalized: bool = True,
weight: Incomplete | None = None,
): ...
def edge_load_centrality(G, cutoff: bool = False): ...
|
__author__ = "Narwhale"
# import copy
#
# a = 'a'
# b = copy.copy(a)
# print(b)
###################################
# def multipliers():
# return [lambda x:i*x for i in range(4)]
# print([m(2) for m in multipliers()])
# a = [lambda x:i*x for i in range(4)]
# print(a)
# for i in a:
# print(i(2))
##########... |
def array_diff(a, b):
b = set(b)
return [c for c in a if c not in b]
|
#1
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import seaborn as sns
%matplotlib inline
np.random.seed(2)
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import itertools
from keras.utils.np_utils import to_c... |
class Solution:
def lengthOfLastWord(self, s: str) -> int:
if not s:
return 0
i = len(s) - 1
ret = 0
while s[i] == " " and i >= 0:
i -= 1
continue
while s[i] != " " and i >= 0:
ret += 1
i -= 1
while s[i] == "... |
# import sys,os
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#
# print(BASE_DIR)
# import os
# import random
#
# files_path = "data/img"
# assert os.path.exists(files_path), "path: '{}' does not exist.".format(files_path)
#
# val_rate = 0.5
#
# files_name = sorted([file.split(".")[0] for f... |
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('level.urls'))
]
admin.site.site_header = 'Password administration'
admin.site.site_title = 'Password administration'
admin.site.index_title = 'Password administration'
... |
import tarfile
import gzip
import numpy as np
import pandas as pd
import os
import dask.dataframe as dd
from sklearn.cluster import KMeans
pd.set_option('display.width', 500)
pd.set_option('display.max_columns', 40)
class Extractor:
def __init__(self, source_path):
self.source_path = source_path
... |
VALID = set(xrange(1, 10))
def validSolution(board):
""" valid_solution == PEP8 (forced mixedCase by CodeWars)
:param board: List of lists, 9 x 9 Sudoku grid
:return: Boolean indicating if the grid is a valid solution
"""
boxes = [[] for _ in xrange(9)]
columns = zip(*board)
for i, row in ... |
import os
import numpy as np
import torch
import json
import math
def temp2coco():
basicPath = os.sys.path[0]
trainPath = os.path.join(basicPath, "train")
valPath = os.path.join(basicPath, "val")
annoPath = os.path.join(basicPath, "train_annotations.json")
classList = ['i2', 'i4', 'i5', 'io', 'ip... |
# coding=utf8
from opener import Opener
from funcs import coroutine
from funcs import get_cst
import logging, time, datetime, itertools, multiprocessing
logging.basicConfig(format='[%(asctime)s] %(message)s')
class Corp(multiprocessing.Process):
def __init__(self, corplist_url, corp_url, info_from, cor... |
from django.contrib import auth
from django.contrib.auth.models import User
from django.contrib import messages
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from products.models import Product
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as anim
import ffmpeg
def init_episode():
start_state = np.array([-0.6+np.random.random()/5,0])
start_action = np.random.choice(ACTIONS)
episode_state = False
return start_state,start... |
from re import compile, search
from string import ascii_letters, digits
NAME = compile(r'<(.+)>')
PHONE = compile(r'\+(\d\d?-\d{3}-\d{3}-\d{4})')
VALID = set(ascii_letters + digits + ' .-')
def phone(strng, num):
result = {}
for a in strng.rstrip().split('\n'):
name = search(NAME, a).group(1)
... |
# -*- coding: utf-8 -*-
import scrapy
import requests
from lxml import etree
from sina import items
from scrapy.spiders import CrawlSpider,Rule #CrawlSpiders:ๅฎไนไบไธไบ่งๅ่ท่ฟlink
from scrapy.linkextractors import LinkExtractor #ๆๅ้พๆฅ
class MysinaSpider(CrawlSpider):
name = 'mysina'
allowed_domains = ['sina.com.cn']... |
from Code.Python.robot_calc_functions import Magnitude, matmult, TransInv, Adjoint, FKinSpace, JacobianSpace, TransToRp, so3ToVec, VecToso3, MatrixLog3, RotInv
import numpy as np
from math import acos, tan, pi
# There was an error found in the source code for IKinSpace and IKinBody. The and condition in the if statem... |
def balanced_brackets(s):
brackets = {'(': ')', '[': ']', '{':'}'}
stack = []
for c in s:
if c in brackets:
stack.append(c)
elif c in list(brackets.values()):
if not stack:
return False
opener = stack.pop()
expected = brackets[o... |
# -*- coding: utf-8 -*-
from sqlalchemy.schema import Column, ForeignKey, UniqueConstraint
from sqlalchemy.types import Integer, String, Text, DateTime
from ..extensions import db
from ..utils import get_current_time
class Repo(db.Model):
__tablename__ = "repos"
id = Column(Integer, primary_key=True)
us... |
#to reverse the element of the list
fr=['bhvaya','komal','khushi','akshuni','divya','komal']
print('before the reverse operation of fr value are:=',fr)
fr.reverse()
print('after the reverse opertion of fr value are:=',fr)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `web-platform-compat` fields module."""
from datetime import datetime
from pytz import UTC
from django.contrib.auth.models import User
from django.test.utils import override_settings
from webplatformcompat.cache import Cache
from webplatformcompat.history imp... |
import json
import requests
import datetime
class Boosters:
def __init__(self, gamemode: str):
self.gamemode = gamemode
self.get_boosters_link = requests.get(f'https://api.slothpixel.me/api/boosters/{self.gamemode}')
self.boosters_data = json.loads(self.get_boosters_link.text)
self... |
"""
Copyright 1999 Illinois Institute of Technology
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 to use, copy, modify, merge, publis... |
# Generated by Django 2.1.3 on 2018-11-06 14:52
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0035_auto_20181107_0348'),
]
operations = [
migrations.RemoveField(
model_name='employee',
name='phone',
),
... |
import json
import requests
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from weather.average import average
from weather.parser import parse_weather
from django.views.decorators.cache import cache_page
def index(request):
return HttpResponseRedirect('/weather/')... |
class Road:
def __init__(self, id, length, speed_limit, lane_counts, start_id, end_id,
is_bothway):
self.__id = id
self.__length = length
self.__speed_limit = speed_limit
self.__lane_counts = lane_counts
self.__start_id = start_id
self.__end_id = end_... |
#this is the example of file using python
wertwteryadfg
def game():
return int(input("enter score "))
score=game()
with open("Highscore.txt") as f:ertewt
hiScortyeteStr=f.read()
if hiScoreStr=='':yer
asfh
adf
gh
adrgh
ad
hjryj
ast
gae
g
eagod ge
if
sad
f
as
fias gaer
t
a4ger
yet
with open("High... |
from django.conf.urls import patterns, include, url
import xadmin
from xadmin.plugins import xversion
xadmin.autodiscover()
xversion.register_models()
urlpatterns = patterns('',
url(r'^admin/', include(xadmin.site.urls)),
url(r'^tea/',include('teaman.tea.urls')),
url(r'^$',include('teaman.tea.urls')),
)
|
import xmltodict
import cPickle as pickle
import sys,os
import re
class ForumPost(object):
def __init__(self,xml_file_name):
with open(xml_file_name,'r') as data:
parsed_data = xmltodict.parse(data.read())
self.post_type = parsed_data.keys()[0]
self.message_type = parsed_data[self.post_type][u'message']... |
POSTGRES_ADAPTER = 'postgres'
DB_QUERY_LIMIT = 10
|
#!/usr/bin/env python3.5
#coding: utf-8
import licant
from licant.core import core
from licant.modules import module, submodule
from licant.cxx_modules import make as make_module
from licant.make import make as make
import licant.util as gu
from licant.scripter import scriptq
scriptq.execute("../../gxx.g.py")
modul... |
# Generated by Django 3.2.7 on 2021-09-24 07:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('courses', '0002_lectureclasssession'),
]
operations = [
migrations.AddField(
model_name='lecturer',
name='mail',
... |
"""
Application setup and initialization code
"""
import os
import logging
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
from .routes import api, pages
|
#Libraries
import RPi.GPIO as GPIO
import sys
import telepot
import time
#IMPORT LIBRARY OS
import os
import telepot
text = 'AIR HABIS'
text1 = 'AIR TERSEDIA'
chat_id = CHATID
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BCM) # Use physical pin numberi
GPIO.setup(15, GPIO.IN, pull_up_down=GPI... |
class Party:
def __init__(self, number_of_persons, budget):
self.number_of_persons = number_of_persons
self.budget = budget
self.left_over_money = budget
self.left_over_pieces = 0
self.cake_count = 0
self.cost = 0
def reset(self):
self.left_over_pieces =... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 20 17:08:46 2017
@author: dgratz
"""
import PyLongQt as pylqt
from multiprocessing import Pool
settings = pylqt.Misc.SettingsIO.getInstance()
proto = pylqt.Protocols.GridProtocol()
settings.readSettings(proto,'D:/synchrony-data/2SAN1RandLogNormal.x... |
import datetime
import json
import pdb
from django.http import HttpResponse, HttpResponseBadRequest
from django.http.response import HttpResponseServerError
from django.shortcuts import get_object_or_404
from zeep import Client, Transport
from zeep.cache import SqliteCache
from django.conf import settings
from zeep.hel... |
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Schema( Base ):
__tablename__ = 'db_schema'
uuid = Column( Text, primary_key = True )
schema = Column( Text, nullable = False )
ver = Column( Integer, nullable = False )
rev = Column( Integer, nullable = False... |
def hash_kilian(string):
output = [0,42,69]
index = 0
for char in string:
#output[index] = output[index] ^ (ord(char)+index) % 256
output[index] = output[index] ^ (ord(char)+index) % 256
index = (index + 1) % 3
o = (output[0] + output[1] + output[2]) % 256
return o
def hash_johan(string):
val = [19,46,67,... |
from os import listdir;
import markdown
import re
import json
from datetime import datetime, date
from collections import defaultdict
import pytz
from feedgen.feed import FeedGenerator
from framework import generateFuncTemplate
"""
logic goes:
# Go through each markdown file
# Create post data object
# ... |
import pymysql
db=pymysql.connect('localhost','root','123456','python')
cur=db.cursor()
a='show tables;'
b='show databases;'
#cur.execute('create table t3 (id int);')
cur.execute('show tables;')
print(cur.fetchall())
db.commit()
cur.close()
db.close()
|
from tornado.testing import AsyncHTTPTestCase
import web
login_data_user_valid = {
'email': 's.ivanov@lab15.ru',
'password': 'UserPassword123',
}
login_data_user_invalid = {
'email': 's.ivanov@lab15.ru',
'password': '000000000000000',
}
login_data_admin_valid = {
'email': 'a.anisimov@lab15.ru',
... |
from script.base_api.service_science.versionInfo import *
|
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('DBStorage/', include('DBStorage.urls')),
path('DBCalls/', include('DBCalls.urls')),
path('admin/', admin.site.urls),
]
|
# coding: utf-8
# In[2]:
import pandas as pd
#reading csv file
ec = pd.read_csv("Data/employee_compensation.csv")
# In[3]:
result = ec.groupby(['Organization Group','Department']).mean().reset_index()
final_result = result[['Organization Group','Department','Total Compensation']]
final_result
# In[5]:
#sort... |
#!/usr/bin/env python3
import os
from ctypes import CDLL
from time import sleep, monotonic, process_time
from operator import itemgetter
from sys import stdout, stderr, argv, exit
from re import search
from sre_constants import error as invalid_re
from signal import signal, SIGKILL, SIGTERM, SIGINT, SIGQUIT, SIGHUP, S... |
# Turn ON this...
# https://myaccount.google.com/lesssecureapps?pli=1&rapt=AEjHL4Nr-cE8QbO3xnA0PuHG2regofVD-TQMQzdCLV-4vlaJkS64k33ZgTWGY7dIhRxBJggs_iNb4gBjz7J9LU9evV4rEuQbDA
# Python code to illustrate Sending mail from
# your Gmail account
def send(sub = 'COVID19 Slot Notification',
data = '...DATA...',
... |
from django.db import models
# TODO: remember that JSON output will inflate this data model
# - adding @type (left implicit here)
# - amenityFeature needs several more attributes autopopulated
# note that a lot of fields listed as REQUIRED in the specification
# are given as optional (blank=True) ... |
from __future__ import print_function, division
import astropy.io.fits as pyfits
import numpy as np
import sys
import subprocess
from scipy import signal
import weightedstats as ws
from skimage.filters.rank import median as skmed
"""
__author__ = 'Will Hartley'
Code to clean up the VISTA VIDEO single-chip coadds' bac... |
# -*- coding: utf-8 -*-
'''
Obtiene los usuarios de la base de datos principal y los crea dentro de la base del correo.
Crea los usuarios si es que no existen en la base del dovecot y la base del sogo.
Para el proceso de actualizaciรณn solo chequea los usuarios con claves que hayan cambiado posteriormente a ... |
from QPlayer import QPlayer
from SpindelTable import Table
import random
import json
from Deck import Card
# Run 100 games
wonGames = 0
N = 100
qPlayer = QPlayer(None, loadFromFile = False)
for i in range(N):
print("Game: " + str(i))
table = Table(1)
table.piles = []
for stack in table.stacks:
... |
# -*- coding: utf-8 -*-
import cv2
from numpy import*
import random
import matplotlib.pyplot as plt
import sys
import copy
def read(filename):
img = cv2.imread(filename,0)
return img
def get_matlist(img):
m,n = img.shape
# print m,n
result = []
row_counts8 = m/8
column_counts8 = n/8
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.