text stringlengths 38 1.54M |
|---|
from pathlib import Path
from postgis_helpers import PostgreSQL
def import_shapefiles(folder: Path, db: PostgreSQL):
""" Import all shapefiles within a folder into SQL.
"""
endings = [".shp", ".SHP"]
for ending in endings:
for shp_path in folder.rglob(f"*{ending}"):
print(shp_pa... |
__all__ = ["AMFError", "RTMPError", "RTMPTimeoutError"]
class AMFError(Exception):
pass
class RTMPError(IOError):
pass
class RTMPTimeoutError(RTMPError):
pass
|
from bird_interface import BirdInterface
from swimming_interface import SwimmingBirdInterface
class Penguin(BirdInterface, SwimmingBirdInterface):
def eat(self):
return 'I can eat!'
def swim(self):
return 'I can swim!' |
#!/usr/bin/python
import logging
logging.basicConfig(level=logging.INFO, format='%(message)s')
import os
import sys
sys.path.extend([os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')])
try:
from grow import submodules
submodules.fix_imports()
except ImportError:
pass
from google.apputils import ... |
import torch
from torch.nn.functional import conv1d, mse_loss
import torch.nn.functional as F
import torch.nn as nn
from nnAudio import Spectrogram
from .constants import *
from model.utils import Normalization
batchNorm_momentum = 0.1
num_instruments = 1
class block(nn.Module):
def __init__(self, inp, out, ksiz... |
#Cagil Benibol
#2212637 , cagil.benibol@metu.edu.tr, cagil.benibol@gmail.com
#python 3.7.4
import numpy as np
import math as m
import matplotlib.pyplot as plt
#funcs
#ODE
def f(t,v):
return 1 - 2*(v**2) - t
#analytically v''(t) = -4*v*v'-1
def f2nd(t,v):
return -4*v*(f(t,v))-1
#analytically v'''(t) = -4*v'-4*v*... |
#!/usr/bin/env python
# -*- coding=utf-8 -*-
import web
urls = (
r'/([\w\-]+(?:\.\w+)?)$', 'ShowCode',
r'/static/([\w\-]+(?:\.\w+)?)$', 'StaticFile'
)
app = web.application(urls, globals())
# for template render
common_globals = {
'str': str,
}
render = web.template.render('template/', globals=common_glo... |
from django.db import models
# Create your models here.
class Subjects(models.Model):
tamil = models.IntegerField()
telugu = models.IntegerField()
english = models.IntegerField()
maths = models.IntegerField()
science = models.IntegerField()
social = models.IntegerField()
class Staff(models.... |
from __future__ import annotations
import ctypes
import ctypes.util
import sys
import traceback
from functools import partial
from itertools import count
from threading import Lock, Thread
from typing import Any, Callable, Generic, TypeVar
import outcome
RetT = TypeVar("RetT")
def _to_os_thread_name(name: str) -> ... |
import threading
import time
#参数定义了最多几个线程可以使用资源
semaphore = threading.Semaphore(3)
def func():
if semaphore.acquire():
for i in range(2):
print(threading.current_thread().getName() + "get semapore")
time.sleep(5)
semaphore.release()
print(threading.current_thread().getN... |
from nsepy import get_history
from datetime import date
#data = get_history(symbol="SBIN", start=date(2015,1,1), end=date(2015,1,31))
nifty_pe = get_history(symbol="NIFTY", start=date(2009,3,31), end=date(2009,3,31), index=True)
print(nifty_pe)
nifty_pe = get_history(symbol="NIFTY", start=date(2010,3,31), end=date(2... |
judges_count = int(input())
presentation_name = input()
all_grades = 0
presentations_count = 0
while presentation_name != 'Finish':
presentation_grades = 0
presentations_count += 1
for judge in range(judges_count):
grade = float(input())
presentation_grades += grade
all_grades += gr... |
from numpy import *
n=array([[1,2,3],[4,5,6]])
n.shape=(6,1)
m=n.reshape(1,6)
print(m)
print()
a=arange(24)
a.shape=(6,4)
print(a)
b=array([1,2,3,4,5])
print(a.itemsize)
c=zeros(5)
print(c)
c=zeros(5,int)
print(c)
c=ones(5,int)
print(c)
c=ones((3,3),int)
print(c)
d=array([1,2,3,4,5,6.0])
print(d.size)
d=array([1,2... |
import tqdm
from scipy.spatial import distance
from skimage.transform import resize
import tensorflow as tf
import numpy as np
from pathlib import Path
import imageio
from src.facenet.facenet.src import facenet
from src.facenet.facenet.src.align import detect_face
MODEL_DIR = str(Path('/media/neuroscout-data/scratch/f... |
import pygame
class Window:
def __init__(self, title, width, height, scale=1, flags=0):
self.title = title
self.width = width
self.height = height
self.scale = scale
self.widthScaled = self.width // self.scale
self.heigthScaled = self.height // self.scale
sel... |
from flask import Flask, redirect, url_for, request,render_template
app = Flask(__name__)
@app.route('/log/<sum>')
def log(name):
return render_template('log.html', name = sum)
@app.route('/login',methods = ['POST','GET'])
def login():
if request.method == 'POST':
user = request.form['nm']
user1 =re... |
import sys
import cv
import math
import numpy
#import time
import bSpline
import argparse
import os # for retriving live picture
import pygame
global inputParser # just a reminder, it's used as a global variable
global inputArgs # just a reminder, it's used as a global variable
global screen # just a reminder, i... |
from .team import (
Team, Profile, PublicInfo, MembershipInfo, Group, UserRole
)
from .board import (
BoardSettings, Board, ItemStatus, Column, Sprint, ColumnTemplate
)
from .items import (
Item, ItemStatus, Assignee, Vote, Comment
)
|
#!/usr/bin/env python
import cv2, time
import numpy as np
cap = cv2.VideoCapture('track2.avi')
threshold_60 = 150
threshold_100 = 100
width_640 = 640
scan_width_200, scan_height_20 = 200, 20
lmid_200, rmid_440 = scan_width_200, width_640 - scan_width_200
area_width_20, area_height_10 = 20, 10
vertical_430 = 430
row... |
"""
Codes are modifeid from PyTorch and Tensorflow Versions of VGG:
https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py, and
https://github.com/keras-team/keras-applications/blob/master/keras_applications/vgg16.py
"""
import tensorflow as tf
import numpy as np
import pdb
from tensorflow.keras.app... |
import os
from django.db import models
from django.db.models import Max
from django.core.exceptions import ValidationError
from django.utils import timezone
from django.conf import settings
from config.storage import PrivateMediaStorage
from tag.models import Tag
def storage():
if not settings.DEBUG:
r... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class ItemUnitInfo(object):
def __init__(self):
self._amount = None
self._price = None
self._spec = None
self._title = None
self._unit = None
@property
... |
from sys import stdin, stdout
from fractions import Fraction
# searches linearly for thumb position in 0..H-2 that satisfies
# reasonable (but wrong) constraint
W, H, L, N = map(int, stdin.readline().split())
text = ' '.join([stdin.readline().strip() for _ in range(N)])
words = text.split()
i = 0
typesettext = list(... |
from setuptools import setup, find_packages
from os import path
VERSION = '1.1'
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'readme.md'), encoding='utf-8') as f:
long_description = f.read()
# Setting up
setup(
name='kitsupy',
version=VERSION,
author='MetaS... |
ap,bp=map(int,input().split())
c=list(map(int,input().split()))
d=[[abs(i-bp),i] for i in c]
d.sort()
d=d[1:]
e=[i[1] for i in d[:3]]
print(*e)
|
import asyncio
import aiohttp
import sys
import json
import time
import re
routes = {
"Goloman": ["Hands", "Holiday", "Wilkes"],
"Hands": ["Goloman", "Wilkes"],
"Holiday": ["Goloman", "Wilkes", "Welsh"],
"Wilkes": ["Goloman", "Hands", "Holiday"],
"Welsh": ["Holiday"]... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import sqlite3
from flask import render_template, flash, redirect, session, url_for, request, g
#from flask.ext.login import login_user, logout_user, current_user, login_required
from app import app, DATABASE, STORYDIR
... |
from common import *
def draw(**kwargs):
sq=np.array((256,)*2)
imgsz=sq*6
k=8 # try 128
h,v=map(lambda im: im//k%2, meshgrid_euclidean(imgsz))
c=checkerboard(imgsz,sq)
im=c*h+(1-c)*(1-v)
return im
if __name__ == '__main__':
im=draw()
imshow(im)
imsave(im,'p20.png')
|
# 同一行内输入
line = input('输入3个数(空格分隔):')
l = line.split(' ')
for i, item in enumerate(l):
l[i] = int(item)
l.sort()
print(l)
|
from .identifier import Keyword
__all__ = [
'As',
'Create',
'Delete',
'Drop',
'Exists',
'From',
'If',
'Insert',
'Into',
'Join',
'Key',
'Not',
'On',
'Primary',
'Select',
'SetKw',
'Table',
'Update',
'Values',
'Where',
]
class As(Keyword):
... |
from N4_using_dataset_to_read_the_tfrecord import *
from N0_set_config import *
from tqdm import tqdm
# from N5_1_AlexNet_with_batchnorm import *
from N5_2_slim_alexnet import *
# from N5_3_slim_vgg16 import *
def main():
train_file_name = 'E:/111project/tfrecord/train.tfrecords'
validation_file_name = 'E:/11... |
"""
Find a pair in an array of size 'n', whose sum is X
There are at most 2 operations performed on every element:
(a) the element is added to the curr_sum
(b) the element is subtracted from curr_sum.
So the upper bound on number of operations is 2n which is O(n).
"""
def find_sub_array(a,sum):
curr_su... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 4 15:20:14 2021
@author: Gerry
"""
teksten = ""
tekstlinje = input("Skriv inn første linje: ")
while tekstlinje != "":
teksten = teksten + tekstlinje + "\n"
# \n er newline, altså enter, altså hver linje du skriver
#inn kommer på en ny linje
tekstlinje... |
'''class Solution:
def maxProfit(self, prices):
ans = 0
for i in range(1, len(prices)):
if prices[i] - prices[i - 1] >0:
ans = ans + (prices[i] - prices[i - 1])
return ans
obj = Solution()
print(obj.maxProfit([7,1,5,3,6,4]))
'''
p = [7, 5, 3, 6, 4]
... |
import requests
import urllib
import urllib.parse
def executeQuery(query, token):
return requests.post(_url('Query/execute'), json=query, headers={'Authorization': 'Bearer ' + token})
def getAuthToken(apikey, username, password):
return requests.post(_url('Users/getAuthToken'), json={
'ApiKey': apik... |
from __future__ import print_function
from dronekit import connect, Vehicle
from my_vehicle import MyVehicle #Our custom vehicle class
import time
def raw_imu_callback(self, attr_name, value):
# attr_name == 'raw_imu'
# value == vehicle.raw_imu
print(value)
connection_string = '/dev/ttyACM0'#args.connect... |
import requests
# Login
req = {
'email': 'ppark9553@naver.com',
'password': '123123'
}
res = requests.post('http://127.0.0.1:8000/api/token/', data=req)
result = res.json()
# Auth page access
refresh_token = result['refresh']
access_token = result['access']
header = {
'Authorization': f'Bearer {access_... |
from utils_convert_coord import coord_regular_to_decimal, coord_decimal_to_regular
import cv2
def debug_decimal_coord(img, coord_decimal, prob = None, class_id = None):
img_cp = img.copy()
img_ht, img_wid, nchannels = img.shape
coord_regular = coord_decimal_to_regular(coord_decimal, img_wid, img_ht)
... |
#
# Copyright (c) 2013 crcache contributors
#
# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
# license at the users choice. A copy of both licenses are available in the
# project source as Apache-2.0 and BSD. You may not use this file except in
# compliance with one of these two licences.
... |
from enemy import Bounty_Hunter
from player import Player
from enemy import Sith
from enemy import Stomtrooper
class Game:
def setup(self):
self.player = Player()
self.enemies = [
Stomtrooper(),
Bounty_Hunter(),
Sith()
]
def get_next_enemy(self):
try:
return self.enemies.pop(0)
except In... |
import math
import bpy
import yerface_blender.DriverUtilities as dru
class YerFaceSceneUpdater:
def __init__(self, context, myReader, fps):
self.props = context.scene.yerFaceBlenderProperties
self.keyframeHelper = dru.KeyframeHelper()
self.translationTarget = context.scene.objects.get(s... |
import torch
from torch import nn
from torch import optim
from torch.utils import data
import torch.nn.functional as F
import numpy as np
import pandas as pd
import os
class Dataset(data.Dataset):
def __init__(self, input_file, output_file):
self.input = pd.read_csv(input_file).values
self.output ... |
from django.urls import path
from user import views
app_name = 'user'
urlpatterns = [
path('register_page/', views.register_page, name='register_page'),
path('check_username/', views.check_username, name='check_username'),
path('check_captcha/', views.check_captcha, name='check_captcha'),
path('regist... |
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs)==0:
return ""
if len(strs)==1:
return strs[0]
#intially consider first element of list as prefix
strs.sort(key=len)
prefix=strs[0]
prefix_length=len(prefix)
... |
from PyQt5.QtWidgets import QPushButton, QWidget
from PyQt5.QtGui import QFont
class Dashboard(QWidget):
def __init__(self, parent = None):
super(Dashboard, self).__init__(parent)
self.initDashboardUI()
def initDashboardUI(self):
self.setGeometry(525, 225, 1080, 720)
#initializ... |
# Como importar diccionarios en Python 3.5+
diccionario_x = {'nombre': 'Javier', 'Edad': 34, 'Ciudad': 'Santiago'}
diccionario_y = {'nombre': 'Claudia', 'Edad': 29}
merge_diccionarios = {**diccionario_x, **diccionario_y}
print(merge_diccionarios)
|
#!/usr/bin/python
#lmx2322 freq set
# CK PA5
# DI PA7
# LOAD PA4
# EN PA3
from __future__ import print_function
from uakeh import Uakeh
import sys
import os
import struct
import time
gp_config_str = ["gp setcfg a 4 out pp 10",
"gp setcfg a 5 out pp 10",
"gp setcfg a 7 out pp 10",
... |
import json
import argparse
import random
import sys
import requests
BIGHUGELABS_API_KEY = 'f79909b74265ba8593daf87741f3c874'
buzzWords = ['alignment','bot', 'collusion', 'derivative', 'engagement', 'focus', 'gathering' ,'housing','liability','management','nomenclature','operation','procedure','reduction','strategic... |
s = input()
letters = "hello"
i = 0
for c in s:
if c == letters[i]:
i += 1
if i == 5:
break
if i == 5:
print("YES")
else:
print("NO")
|
from django.urls import reverse
from restaurants.models import Restaurant
def test_list(client, db, make_restaurant):
make_restaurant()
response = client.get(reverse("restaurant-list"))
assert response.status_code == 200
assert response.json() == [{"name": "Fifolino"}]
def test_post(client, db):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 18 11:04:19 2020
@author: chandan
"""
import time
import random
import pandas as pd
from Optimizer.solution import Solution
from Optimizer.coordinator import CoOrdinator
from Optimizer.Genetic_alg import GASelectionEnum
from Optimizer.data_fjs impor... |
import aws_encryption_sdk
from aws_encryption_sdk.key_providers.raw import RawMasterKey
from aws_encryption_sdk.internal.crypto.wrapping_keys import WrappingKey
from aws_encryption_sdk.key_providers.raw import RawMasterKeyProvider
from aws_encryption_sdk.identifiers import CommitmentPolicy, EncryptionKeyType, WrappingA... |
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved.
import gzip
import os
import struct
import numpy as np
import PIL.Image
from downloader import DataDownloader
class MnistDownloader(DataDownloader):
"""
See details about the MNIST dataset here:
http://yann.lecun.com/exdb/mnist/
"... |
import tkinter as tk
from PIL import Image,ImageTk
import os
from tkinter import filedialog
#GUI Application window
win = tk.Tk()
win.title("Image to pdf converter")
win.geometry("700x600")
win.iconphoto(False, tk.PhotoImage(file = 'pdf.png'))
win.resizable(0,0)
#Krishna_Image
can = tk.Canvas(win,bg = "yellow", widt... |
def getSeq(x):
n = [x]
tmp = x
while tmp > 9:
print tmp
tmp2 = 0
for i in str(tmp):
tmp2 += int(i)**2
tmp = tmp2
n.append(tmp)
return n
maks = 10 ** 7
dic = {}
def juletall(x):
if x in dic:
return dic[x] == 1
tmp = x
while tmp > ... |
from django.contrib import admin
from .models import ProfileEvaluation,Registration
# Register your models here.
#username:prima
#owd:1234
admin.site.register(Registration)
admin.site.register(ProfileEvaluation) |
import sys
from typing import NamedTuple, Tuple, List, Dict, Set
class Food(NamedTuple):
ingredients: Tuple[str, ...]
allergens: Tuple[str, ...]
def parse_food(line: str) -> Food:
"""Return a valid Food from the given line."""
left, right = line.strip().split(" (contains ")
foods: List[str] = [... |
import pytest
from darklyrics import get_lyrics, LyricsNotFound, get_albums, get_songs, get_all_lyrics
def test_not_found():
with pytest.raises(LyricsNotFound):
get_lyrics('fakesong', 'fakeartist')
get_albums('fakeartist')
def test_song_only():
lyric = get_lyrics('your familiar face')
a... |
import os
import cv2
from scipy.io import savemat
n_authentic_trained = 7000
n_tampered_trained = 4000
dict = {}
ntest =500
# todo: authentic images testing
au_folder = 'Casia2/au/images'
test_data_folder = 'test_data'
count = 0
for filename in os.listdir(au_folder):
count += 1
if count <= ... |
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import classification_report, confusion_matrix
from question_b import df, df_1, df_2, df_3, df_4, df_5
# X is the dataset that contains the required features (all columns except s... |
#!/usr/bin/env python
# -*- encoding=utf-8 -*-
########################################################
# DataSave Class to save daily curves and 5-min curves #
########################################################
import os
import time
import threading
# import json
import sqlite3
import arrow
# import datetime
#... |
from typing import (
Any,
Sequence,
Tuple,
Type,
)
from eth_utils.toolz import accumulate
from p2p.abc import (
CommandAPI,
ProtocolAPI,
TransportAPI,
)
from p2p.constants import P2P_PROTOCOL_COMMAND_LENGTH
from p2p.typing import Capability
from p2p._utils import get_logger
class BasePro... |
#!/usr/bin/env python3
import sys
import argparse
import h5py
import math
import scipy
from scipy import ndimage
from scipy import integrate
import numpy as np
import pandas as pd
import datetime
import time
import matplotlib
import matplotlib.pyplot as plt
import os
from mpl_toolkits.mplot3d import Axes3D
from mpl_to... |
# Generated by Django 3.0.8 on 2020-07-15 12:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('service_chat', '0002_auto_20200715_1205'),
]
operations = [
migrations.AlterField(
model_name='message',
name='autho... |
# Generated by Django 3.0.5 on 2021-08-04 22:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('erp', '0033_auto_20210804_1728'),
]
operations = [
migrations.AlterModelOptions(
name='proveedor',
options={'orderin... |
"""
Constants for application
"""
USER_NAME = "Имя"
USER_NAME_HELP_TEXT = "Ваше имя. Заполнять не обязательно."
LAST_NAME = "Фамилия"
LAST_NAME_HELP_TEXT = "Ваша фамилия. Заполнять не обязательно."
PASSWD1 = "Пароль"
PASSWD1_HELP_TEXT = "Введите пароль."
PASSWD2 = "Введите пароль еще раз"
PASSWD2_HELP_TEXT = "Введите п... |
# -*- coding: utf-8 -*-
import datetime
import os
import pyowm
from app import config
CITY = "Ann Arbor"
def get_weather_description():
api_key = os.environ.get("WEATHERMAP_KEY") or config['weather']['api_key']
weather = pyowm.OWM(api_key)
forecast = weather.three_hours_forecast(CITY)
# Discard wea... |
import sys
ref=[sys.argv[1]]
rfh=open(sys.argv[1].split('/')[-1]+'_summary.txt','w')
rfh.write('Sample\tSequenced_Read-pair\tMapped_Read-pair\tNonclonal_Read-pair\tIntra_less\tIntra_more\tInter\tCpG_met\tCHG_met\tCHH_met\n')
for fn in ref:
fn=fn.split()[-1].split('/')[-1]
dfh1=open(fn+'_trimmed_bismark_... |
from django.conf.urls import patterns, url
from django.views.generic import RedirectView
from django.conf.urls import patterns, include, url
from rest_framework import routers
from messages.views import InboxListView, SentListView, ComposeMessageObjView
from messages.views import DeletedListView, DeleteMessageObjView,... |
# Austin Zebrowski
# E.Cloudmesh.Common.3
# Develop a program that demonstrates the use of FlatDict
from cloudmesh.common.FlatDict import FlatDict
mydictionary = {
"name": "Katelyn"
, "type": "Student"
, "biometrics": {
"height": 5.5,
"weight": 120,
"eye": "brown"
}
}
mydicti... |
from django.contrib import admin
from authentication.models import Account
admin.site.register(Account)
|
import numpy as np
from PIL import Image
import scipy.io
#calculate the intersection over union
#box format : [x_left,y_top, width, height]
def get_iou(a, b):
xmin = min(a[0],b[0])
xmax = max(a[2]+a[0],b[2]+b[0])
ymin = min(a[1]-a[3], b[1]-b[3])
ymax = max(a[1],b[1])
union = max(0, xmax - xmin) *... |
from ..models import *
from rest_framework import serializers
class SponsorSerializers(serializers.ModelSerializer):
class Meta:
model = Sponsor
fields = ('name', 'description', 'url', 'image')
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ysgxuyu', '0005_auto_20150218_1622'),
('wyxbcga', '0004_remove_xqjugixefj_xvbpvsvwrw'),
]
operations = [
migrations.... |
"""
This challenge asks you to redefine the mysum function we defined in chapter 1, such that it can take any number of arguments. The arguments must all be of the same type and know how to respond to the + operator. (Thus, the function should work with numbers, strings, lists, and tuples, but not with sets and diction... |
"""
NBComet: Jupyter Notebook extension to track full notebook history
"""
import os
import nbformat
# TODO see if we can use nbdime to do diff, or continue using our own code
def get_nb_diff(action_data, dest_fname, compare_outputs = False):
"""
find diff between two notebooks
action_data: (dict) new n... |
from Analyzer import *
file = open('file.txt', 'r')
parse(file)
#TODO:
# add code to iterate something |
# https://github.com/LambdaSchool/DS-Unit-4-Sprint-1-NLP/tree/master/module4-topic-modeling
# https://learn.lambdaschool.com/ds/module/recbYIWnPYs2J4AWC/
#
# Topic Modeling
#
# At the end of this module, you should be able to:
# + describe the latent dirichlet allocation process
# + implement a topic model using th... |
# coding: utf-8
#import ipdb
import pyrax
#ipdb.set_trace()
pyrax.set_credential_file("/home/admin/pyrax_credentials")
cs_syd = pyrax.connect_to_cloudservers(region="SYD")
sydservers = cs_syd.servers.list()
sydimages = cs_syd.images.list()
#
print sydimages[0]
sydimages[0]
type(sydimages[0])
sydimages[0].id
sydimages... |
import numpy as np
import pandas as pd
from sklearn.cluster import MeanShift
from collections import Counter
def out(filename, s):
f = open(filename, 'w')
f.write(s)
f.close()
raw_data = pd.read_csv('checkins.csv')
raw_data.columns = [c.strip() for c in raw_data.columns]
data = raw_data[['latitude', 'longitude']... |
import json
import csv
import sys
import re
import text_to_vector
import pandas as pd
import nltk
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from functools import reduce
from nltk.corpus import stopwords
nltk.download('stopwords')
import string
if len(sys.argv) < 3:
print("USAGE <input-tw... |
import turtle
import hd
steps = 50
numbers = list()
turtle.speed(100)
turtle.ht()
turtle.tracer(0,0)
def genfib():
global numbers
a = 0
numbers.append(1)
numbers.append(1)
while a < steps:
a += 1
b = numbers.__len__()
c = b - 1
d = b - 2
num... |
# How to deal with nested dict??
#
from collections import defaultdict
class Node(object):
def __init__(self, val, parent, child=None):
self.val = val
self.parent = parent
self.child = dict() if not child else child
def update_node(self, val):
if val not in self.child:
... |
#!/usr/bin/env python
# encoding=utf-8
# maintainer: rgaudin
import urllib
import thread
import logging
from django.http import HttpResponse, Http404
from django.shortcuts import redirect
from nosms.models import Message
from nosms.utils import process_incoming_message
logger = logging.getLogger(__name__)
def han... |
import tensorflow
import tensorflow.keras as k
import os
import pandas as pd
import numpy as np
import subprocess
from sklearn.linear_model import LinearRegression
from termcolor import colored
import config
import sys
import scipy
from sklearn.model_selection import train_test_split
os.system('color')
... |
from time import sleep
print('Hello annonymous user, let me get to know you.')
sleep(1.5)
name = raw_input('What is your name? ')
print('Hello ' + name + '!')
sleep(1)
print('My name is a secret')
sleep(1)
def askpermission(question):
answer = raw_input(question).lower()
if answer == 'yes':
return True
... |
n, k = map(int, input().split())
coins = [int(input()) for _ in range(n)]
total = 0
while True:
n -= 1
if k == 0:
break
if coins[n] <= k:
total += k//coins[n]
k -= (k//coins[n])*coins[n]
print(total) |
#Aaina Vannan
#12/4/18
#holds html code
<html>
<head>
{% if title %} #when variable is avaliable
<title>{{ title }} - Microblog</title>
{% else %} #when variable is not avaliable
<title>Welcome to Microblog!</title>
{% endif %}
</head>
<body>
<div>Microblog:
<a href... |
import pytest
from easyci.hooks.hooks_manager import get_hook, HookNotFoundError
def test_get_hook():
assert get_hook('pre-commit')
with pytest.raises(HookNotFoundError):
get_hook('doesnotexist')
|
'''
자료형
type( a ) # type( 변수명 ) : 자료형
isinstance( 42, int ) # isinstance( 값, 자료형 ) : 자료형 검사
클래스
함수나 변수들을 모아 놓은 집합체
인스턴스
클래스에 의해 생성된 객체
인스턴스 각자 자신의 값을 가지고 있다.
클래스 선언
class Human( ):
'''사람'''
인스턴스 생성
person1 = Human( )
person2 = Human( )
클래스와 인스턴스를 이용하면 데이터와 코드를 사람이 이해하기 쉽게 포장할 수 있다.
모델링(modeling)
클래스로 현실의 개념을 표현... |
import io
import os
from google.cloud import vision_v1
from google.cloud.vision_v1 import types
import pandas as pd
#Set the os GCP APP Variable
os.environ['GOOGLE_APPLICATION_CREDENTIALS']=r'ENTER JSON FILE HERE.json'
#client for image annotate vision
client = vision_v1.ImageAnnotatorClient()
file_name = os.path.a... |
#! /usr/bin/env python
# utils/sorting.py
"""This module provides common sorting functionality for a variety of structures.
"""
import os, os.path
import files
def by_size(paths, reverse=False):
"Sorts a list of files/folders by their sizes."
return [filename for filename, filesize in
sorted([(pat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 10 22:43:07 2019
@author: larry1285
"""
import keras
import numpy as np
np.random.seed(1337)
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense,Activation,Convolution2... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
--- Part Two ---
During the second Go / No Go poll, the Elf in charge of the Rocket Equation Double-Checker
stops the launch sequence. Apparently, you forgot to include additional fuel for the fuel
you just added.
Fuel itself requires fuel just like a module - take it... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
import argparse
import re
import itertools
from time import sleep
__author__ = 'n30'
class WracostArgs():
def __init__(self): # Initial checks
self.parser = argparse.ArgumentParser(description="Web Race Condition and Stress Tester")
self.args = self.get_a... |
from utils.mesh_convert_helper import *
from utils.data_io import *
from utils.CoMA_dataloader import *
from utils.KNU_dataloader import *
# from utils.tf_helper import *
from utils.sort import *
from utils.dataloader_factory import * |
"""Utility functions for Markive."""
import datetime
import os
import yaml
def get_current_entry(markive_folder: str, date=None) -> str:
"""Get the current entry based on today's date.
Arguments:
markive_folder: String path of where entries are stored
Returns:
entry: Today's entry as ... |
from .. import db
class Users(db.Document):
full_name = db.StringField(required=True)
phone_no = db.StringField(required=True)
photo_url = db.StringField(required=True)
is_verify = db.BooleanField(request=True) |
# -*- coding: utf-8 -*-
__author__ = 'chuter'
import os
from django.conf import settings
from core.jsonresponse import create_response
from core.exceptionutil import unicode_full_stack
from modules.member import util as member_util
from market_tools.prize.module_api import *
from models import *
def create_ballot... |
import re
def main():
"""
6 or 7 で構成されるラッキーナンバー
下一桁: 2,3,4(6+6,6+7,7+7)
2: (3,4,5): (2,3,4) + 繰り上げ1
3: (3,4,5): (2,3,4) + 繰り上げ1
最上位: (1) : 繰り上げ1
or (6,7,8): (6,7) + 繰り上げ(0/1)
66| 666| 6666
+ 66|+ 66|+ 66
----------------
132| 732| 6732
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.