text stringlengths 8 6.05M |
|---|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement
from cuisine import group_check as get
from cuisine import group_create as create
from cuisine import group_ensure as ensure
from cuisine import group_user_add as user_add
from cuisine import group_user_check as user_check
from c... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('flashcards', views.flashcards, name="flash"),
path('questions', views.questions, name="questions"),
path('interview', views.interview, name="interview"),
] |
import hashlib
import math
import pickle
import numpy as np
from pathlib import Path
from picp.util.geometry import intersection_between_segments, normalize
from picp.util.pose import Pose
from picp.util.position import Position
class SensorModel:
def apply_noise(self, origin: Position, intersection: Position):... |
from django.contrib import admin
from .models import *
#Register your models here.
#admin.site.register(UserAccount)
#admin.site.register(Manager)
admin.site.register(Employee)
admin.site.register(Judge)
admin.site.register(LowOfficer)
admin.site.register(Case)
admin.site.register(Shedule)
admin.site.register(Comment... |
#!/usr/bin/env python3
# Advent of code Year 2019 Day 25 solution
# Author = seven
# Date = December 2019
import sys
from os import path
sys.path.insert(0, path.dirname(path.dirname(path.abspath(__file__))))
from shared import vm
with open((__file__.rstrip("code.py") + "input.txt"), 'r') as input_file:
program =... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 9 04:47:12 2020
@author: lifecell
"""
def hello():
print("Hello World!!")
def hi(name):
print(f"Hello {name}!!!")
def hi2(name='Nahush'):
print(f"Hello {name}!!!")
def FibNum(num=20):
'''Calculates and returns the fibonacci ... |
import numpy as np
import operator
import matplotlib.pyplot as plt
allYears = ["09", "10", "11", "12", "13", "14", "15", "16"]
def make_the_plot(number_langs, sum_col, my_data, year_):
list_of_tuples = []
for i in range(number_langs):
name_lang = my_data[i][0]
total = 0.0
for index, ... |
from django.conf.urls import url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
### FLOW
## url is entered -> matches url -> goes into views calls a function -> Function does some computation -> Renders a new page
urlpatterns = [
url(r'^$', views.index, name='index'),
... |
# -*- coding: utf-8 -*-
class Solution:
def fairCandySwap(self, A, B):
difference = (sum(A) - sum(B)) // 2
setB = set(B)
for a in A:
if a - difference in setB:
return [a, a - difference]
if __name__ == "__main__":
solution = Solution()
assert [1, 2] ... |
import requests
import re
import time
import csv
import os
from bs4 import BeautifulSoup
url1 = "https://finance.naver.com/sise/sise_group.nhn?type=upjong"
res1 = requests.get(url1)
succece = res1.status_code
if succece == 200:
soup1 = BeautifulSoup(res1.text, "lxml")
jongAll = soup1.find_all("td", attrs={"st... |
class Solution(object):
def maxProfit(self, prices, fee):
"""
:type prices: List[int]
:type fee: int
:rtype: int
"""
answer = 0
buyPrice = float('inf')
for price in prices:
if price < buyPrice:
buyPrice = price
... |
from __future__ import with_statement
import os
import unittest
try:
from unittest import mock
except ImportError:
import mock # < PY33
from flake8 import engine
from flake8.util import is_windows
class IntegrationTestCase(unittest.TestCase):
"""Integration style tests to exercise different command lin... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import easy_thumbnails.fields
class Migration(migrations.Migration):
dependencies = [
('localizacao', '0001_initial'),
migrations.swappable_dependency(setting... |
from django.conf.urls import url
from django.contrib import admin
from django.urls import path
from MyApp import views as App_views
urlpatterns = [
]
|
# 一开始 topo + 排序,属于是惯性思维了,能做
# 实际上 bfs 从0开始,记录它的子节点包括孙子节点
# 需要每次维护set去重,这样依次从数小的节点给其所有的子节点加上祖先节点
# 最终实现的就是有序的
class Solution:
def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:
g = defaultdict(list)
for u, v in edges:
g[u].append(v)
ans = [[] for ... |
# Copyright (c) 2017-2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from collections.abc import Sequence as Seq
from os import PathLike
from typing import (
AsyncContextManager,
BinaryIO,
Callable,
... |
# -*- coding: utf-8 -*-
'''
Obtiene los usuarios de la base de datos principal que pertenecen a la oficina Cedlas y los sincroniza con el linux actual.
Tambien actualiza la clave en el samba
'''
import connection
import users
import groups
import systems
import logging
import datetime
import jsonpickle
if __na... |
class Solution:
def final_function(self, input):
if (input < 1):
result = 0
else:
flag = 0
for i in range(2,input):
if (input % i) == 0:
flag = 1
break
if (flag == 0):
result = 0
... |
import tensorflow as tf
from utils import read_data_file, creat_word_embedding, data_parse_one_direction
from CNN import Text_CNN
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_integer('embedding_dim', 100, 'dimension of word embedding')
tf.app.flags.DEFINE_integer('batch_size', 64, 'number of example per batch')
tf.... |
# Подключение модулей
import pygame
from random import randrange
# Константы
WINDOW_SIZE = WINDOW_WIDTH, WINDOW_HEIGHT = (300, 300)
OBJECT_SIZE = 10
# переменные и инициализация
pygame.init()
screen = pygame.display.set_mode(WINDOW_SIZE)
x = randrange(0, WINDOW_WIDTH, OBJECT_SIZE)
y = randrange(0, WINDOW_HEIGHT, OBJECT... |
from rest_framework import generics
from django.views.generic import TemplateView
from .models import Deputy, PoliticalParty
from .serializers import DeputySerializer, PoliticalPartySerializer
class IndexView(TemplateView):
template_name = 'index.html'
class DeputiesList(generics.ListCreateAPIView):
quer... |
#Central Limit Theorem
from math import e, erf, pi, sqrt
def f(x):
return (e**((x**2)/-2))/sqrt(2*pi)
def normal_distribution(mean, standard_deviation, x):
a = 1/standard_deviation
return a*f((x-mean)/standard_deviation)
def central_limit(mean,standard_deviation, n):
mean *= n
standard_deviation *= sqrt(n)
retu... |
class Calculator:
result = 0
intermediate_results = []
def add(self, a, b):
add = a + b
self.intermediate_results.append(add)
return add
def subtract(self, a, b):
subtract = a - b
self.intermediate_results.append(subtract)
return subtract
def divide... |
from IrreversibleDataType import explanations
class FileWriter(object):
"""
Writes lines to file
"""
@staticmethod
def writeToFile(path, lines):
"""
Write lines to file
:param path: to file
:param lines: of converted file
"""
with open(path, mode='... |
"""
fucntions that work on uPub data, but do not look at the data itself
"""
def get_paths_of_files( path ):
"""
- gets the paths of 5 files:
- uPub document
- supplement document
- GFF/GTF
- FASTA/FNA
- PEP/FAA
- returns dictionary
- INPUT: path to publishable model
- OUTPUT: dictionary of absolute p... |
import os
import warnings
import numpy as np
from manimlib.constants import *
from manimlib.mobject.mobject import Mobject
from manimlib.mobject.geometry import Circle
from manimlib.mobject.svg.drawings import ThoughtBubble
from manimlib.mobject.svg.svg_mobject import SVGMobject
from manimlib.mobject.svg.tex_mobject ... |
# Generated by Django 3.0.5 on 2020-04-20 03:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('todo', '0002_auto_20200419_1926'),
]
operations = [
migrations.AddField(
model_name='todo',
name='deleted',
... |
#!/usr/bin/env python3
from pwn import *
"""
Apparently, the stub is code is:
xor rax,rax
xor rbx,rbx
xor rcx,rcx
xor rdx,rdx
xor rsi,rsi
xor rdi,rdi
xor rbp,rbp
xor r8,r8
xor r9,r9
xor r10,r10
xor r11,r11
xor r12,r12
xor r13,r1... |
#Anton Danylenko
#SoftDev1 pd8
#16 No Trouble
#2018-10-05
import sqlite3 #enable control of an sqlite database
import csv #facilitates CSV I/O
DB_FILE="discobandit.db"
db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create
c = db.cursor() #facilitate db ops
#====================... |
"""
IQR Search sub-application module
"""
import base64
from io import BytesIO
import json
import os
import os.path as osp
import random
import shutil
import zipfile
import six
import flask
import PIL.Image
import requests
from smqtk.iqr import IqrSession
from smqtk.representation import get_data_set_impls
from smqt... |
# coding=utf-8
__author__ = 'Hanzhiyun'
# calculate the factorial
number = input("Enter a non-negative integer to take the factorial of: ")
product = 1
for i in range(number):
product *= (i + 1)
print(product)
|
import json
import base64
import cv2
import sys
import datetime
import time
import subprocess
import collections as cl
import csv
def res_cmd_lfeed(cmd):
return subprocess.Popen(
cmd, stdout=subprocess.PIPE,
shell=True).stdout.readlines()
def res_cmd_no_lfeed(cmd):
return [str(x).rstrip("\n") for x in res_cm... |
#!/usr/bin/env python
# coding: utf-8
import cv2
from dataset_explorer.io import FileType
from dataset_explorer.plugins import ImagePlugin
class LaplacianPlugin(ImagePlugin):
def __init__(self):
super(LaplacianPlugin, self).__init__("Laplacian Derivative", FileType.IMAGE, icon="border_clear")
def p... |
'''
Created on Dec 21, 2010
Mpl examples:
http://matplotlib.sourceforge.net/examples/user_interfaces/index.html
'''
import tempfile
import logging
import numpy as np
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
from matplotlib.backends import backend_wx
from matplotlib.figure import Figure
impor... |
from .king_bot import king_bot
from .settings import settings
|
#
#
#
#
# Functions to calculate the volume of a set of rules
#
#
#
#
from operator import itemgetter
# FUNCTION TO CALCULATE THE VOLUME OF A PARAMETER
def parameter_volume(parameter):
if type(parameter) == int or type(parameter) == float:
minimum = maximum = parameter
else:
minimum... |
import sqlite3, hashlib
import os
DIR = os.path.dirname(__file__)
DIR += '/'
m = DIR + "../data/database.db"
# Login - Returns true if successful, false otherwise
def login(username, password):
print "THIS IS M " + m
db = sqlite3.connect(m)
c = db.cursor()
c.execute("SELECT username, password FROM pro... |
nums=[10,202,12,121]
for num in nums:
if num%5==0:
print(num)
break
else:
print("Not Found") |
#!/usr/bin/env python
"""
scdist.py
=============
Used from Opticks scdist- bash functions.
"""
import os, logging, argparse
log = logging.getLogger(__name__)
from opticks.bin.dist import Dist
class SCDist(Dist):
"""
"""
exclude_dir_name = [
]
bases = [
'bin', ... |
from django.core.files import File
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.views.generic.edit import FormView
from django.utils import timezone
from .forms import FileUploadform
from .models import UploadData
from .pdf_utils import MergePDFs
import json... |
"""Treadmill app configurator daemon, subscribes to eventmgr events.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import click
from treadmill import appcfgmgr
def init():
"""Top level command handler."""... |
class Solution(object):
def max_profit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
profit = 0
total = 0
min_price = prices[0]
for price in prices:
# find the min so far
... |
import io
import csv
from beancount.core.number import D
from beancount.core import data
def identify(rd: io.TextIOBase, dialect: str, fields: [str]):
rd = csv.reader(rd, dialect=dialect)
for row in rd:
if set(row) != set(fields):
return False
break
return True
def make_pos... |
import json
from rest_framework import permissions
from django.core import serializers
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse, HttpResponseBadRequest, JsonResponse
from django.utils.datastructures import MultiValueDictKeyError
from django.views.decorators.csrf import... |
'''
Created on 2018/03/11
@author: yasushi
'''
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello)) |
import re
# 要匹配的字符串对象
import time
#
# a="被赋予汗水和欢笑的日子将会成为她成长道路上最宝贵的回忆,祝福母校未来一定会更好!合照东北石油大学六十周年华诞倒计时49天飞扬的歌声,吟唱难忘的岁月,凝聚心头不变的情节;今天,我们用歌声共同挽起友爱的臂膀,让明天来倾听我们爱心旋律的唱响;期盼您下期观看《报答》。策划:吴波,郭连峰(校友),彭艳秋(校友)导演:吴波协调:曹建刚剪辑:吴波,王霖(助理团),李天赐(助理团)文字:郭雨仙,李泽月(助理团),张悦琳(助理团)" \
# "大 学 生 新 闻 中 心 出 品\xa0图文编辑:刘\xa0\xa0\xa0岩责任编辑:王超颖审\u3000\u300... |
# A. Dungeon
t = int(input())
for _ in range(t):
a,b,c = map(int,input().split(' '))
s = a+b+c
d = s // 9
# applying the condition that sum is atleast equal to 9
# and is multiple of 9.
if s > 8 and s % 9 == 0:
# applying the condition that a,b and c are atleast
... |
str = 'Hello World!'
print str #prints whole tring
print str[0] #prints the first character
print str[2:5] #prints characters at 3rd to last position
print str[2:] #prints all characters from 3rd position onwards
print str + "Test" #prints out string concatenated by TEST
|
#!/usr/bin/env python
from flask import Flask, escape, request
from wgraph.summary import go
from wgraph.graph import load, apply_styles
app = Flask(__name__)
GRAPH = load("../graph.tsv")
@app.route("/")
def home():
return """
<form method="POST">
<input name="word">
<input type="submit" value="Enter ... |
def solution(n):
answer = ''
while n:
if n % 3:
answer += str(n % 3)
n //= 3
else:
answer += "4"
n = n//3 - 1
return answer[::-1]
from collections import deque
def solution(n):
answer = ''
country = deque()
while n:
if n %... |
#The range() Function
for i in range (5):
print (i)
print ('______________________________________')
for i in range(5, 10):
print(i)
print ('______________________________________')
for i in range(0, 10, 3):
print(i)
print ('______________________________________')
for i in range(-10, -100, -30):
print(... |
import sys
def parse_http_datetime(s):
datetime=""
month=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
if "GMT" in s and "-" not in s:
a=s.split(" ")
y= a[3]
if (month.index(a[2])+1)<10:
m= str("0"+str(month.index(a[2])+1))
else:
... |
# -*- coding: utf-8 -*-
from ProxyIP.utils.useragent import UAPOOL
# Scrapy settings for ProxyIP project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
... |
L=[]
with open("cuburi.txt") as f:
k=1
for i in f.readlines():
if k==1:
n=int(i)
k+=1
else:
j=i.split()
L.append((int(j[0]),j[1].strip("\n")))
L=sorted(L,key= lambda e: -e[0])
print (L)
with open("turn.txt","w") as g:
g.write(str(L... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-02-28 15:59
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('client_config', '0002_client_notice'),
]
operations = [
migrations.RenameField(
... |
from tkinter import *
import pickle
from tkinter import messagebox
from tkinter import filedialog
from tkinter.filedialog import askopenfilename
from reviewUtil import *
from clusterUtil import *
def Cluster():
game = textBox.get("1.0",END)
if len(game) > 1:
clusterResult = list(clusterTestGame(game))
... |
import unittest
from TFExamplesUtils import *
class TestTFExamplesUtils(unittest.TestCase):
def setUp(self):
self.tf_example_utils = TFExamplesUtils()
def test_bytes_feature(self):
a = self.tf_example_utils.bytes_feature(b"a")
print(a)
def test_float_feature(self):
a = s... |
from gensim import corpora, models, similarities
from gensim.models import word2vec
import logging
import gensim
import time
import random
from numpy.random import RandomState
from random import randint
import numpy
import pandas as pd
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=loggin... |
#coding:utf-8
print("Please input plain text")
plain = input()
print("Please input key(0~26)")
key = int(input())
code = list(map(lambda x:chr(ord(x)+ key), plain))
code = ''.join(code)
print(code)
|
"""Parses webcomic pages to identify their navigation links and locate archived and new comics"""
import urllib
from contextlib import closing
from lxml import etree
from lxml import html
def findLinks(source, target):
""" Locates all links from the source URL to the target URL, returning a list
of 2-elem... |
#!/usr/bin/env python
# Solution for http://adventofcode.com/2016/
def is_triange(a, b, c):
k = sorted([a, b, c])
return k[2] < k[0] + k[1]
print is_triange(5, 10, 25)
triangles = 0
with open('advent_2016_3.txt') as fp:
line1 = fp.readline()
line2 = fp.readline()
line3 = fp.readline()
w... |
#!/usr/bin/python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Provides read access to buildbot's global_variables.json .
"""
import json
import svn
_global_vars = None
class NoSuchGlobalVar... |
import sys
from pyspark.sql import SparkSession
def multiply(r,d):
if int(r[1]) in d:
return [(int(r[0]), float(r[2]) * d[int(r[1])])]
return []
if len(sys.argv) != 2:
print("Zle argumenty")
exit(1)
sp = SparkSession.builder.appName("zad1").getOrCreate()
file = sys.argv[1]
v_num = 4
dane = ... |
from django.contrib import admin
from django.utils.text import truncate_words
from snippets.models import Image, Markup, MediaType, Style
class ImageAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'author', 'title', 'dimensions', 'format')
def dimensions(self, image):
if image.width and i... |
from django.contrib import admin
# Register your models here.
from . import models
# Register your models here.
@admin.register(models.Tm_Service)
class Tm_ServiceAdim(admin.ModelAdmin):
list_display = ('id', 'department', 'service_name', 'upload_file', 'order', 'created', 'modified')
ordering = ('id',)
f... |
import numpy as np
import argparse
import copy
import os
import sys
import re
import projector
import pretrained_networks
from training import dataset
from training import misc
import dnnlib
from dnnlib import EasyDict
import dnnlib.tflib as tflib
import os
import glob
from metrics.metric_defaults import metric_def... |
## 항목수, 항목 내용, 몇번째 항목을 확인하고 싶은지 입력
pn = int(input('게임에 참가할 사람 수는?:'))
z = int(input('몇 번째 항목의 결과를 확인하시겠습니까?:'))
people = []
result = []
for i in range (0,pn):
name = str(input('게임에 참가하는 사람의 이름을 입력해주세요:'))
people.append(name)
def ladders():
import turtle
import random
global pn
## 세로줄 그리... |
import sys
import os
f = open("C:/Users/user/Documents/python/other/import.txt","r")
sys.stdin = f
# -*- coding: utf-8 -*-
cand = [1,2,3,4]
def dfs (i):
if i <= 0:
return [["1"],["2"],["3"],["4"]]
temp = []
for j in range(4**i):
for k in range(4):
tmp = dfs(i-1)... |
import numpy as np
# The signals initially arrive in a noisy state, so they must first be preprocessed using a
# moving average filter to smooth the signals and enable them to be used for feature extraction.
def movingavg(signal):
# The order of the moving average filter is set to 100.
N = 100
temp_sig... |
import speech_recognition as sr
import pyttsx3
listener = sr.Recognizer()
socio = pyttsx3.init()
voices = socio.getProperty('voices')
socio.setProperty('voices', voices[1].id)
def talk(text):
socio.say(text)
socio.runAndWait()
def take_command():
try:
with sr.Microphone() as source:
p... |
##자료 형변환방법
a = 10
b = 20
z = "10"
#자료형 변환 함수
# - bool()
# - int()
# - str()
# - float()
# 입력되는 데이터에 한해서 0인 경우 false,
# 0이 아닌 모든데이터는 True이다.
print(bool("")) |
from django.contrib import admin
from .models import Plan, ThumbnailSize
@admin.register(Plan)
class PlanAdmin(admin.ModelAdmin):
list_display = (
"name",
"has_access_to_org_img",
"can_generate_expiring_links",
"display_available_thumbnail_sizes",
)
@admin.register(ThumbnailS... |
"""RUTINA DPLL Y UNIT PROPAGATE"""
import copy
def is_unit_cl(lista): #Clausula unitaria es aquella en la que solo hay un átomo
for l in lista:
if len(l) == 1:
return True
elif len(l) == 2 and l[0]== "-":
return True
return False
def complemento(n): #El com... |
n = 1
while n > 0:
n = int(input("Digite um número natural:"))
fatorial = 1
if n < 0:
print ("O número digitado não é um número natural!")
else:
while n >= 1:
fatorial = n*fatorial
n = n - 1
print (fatorial)
|
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.11.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
... |
import os
import logging
logger = logging.getLogger(__name__)
registry = dict()
def backend(*args, **kwargs):
def deco_backend(f):
enabled = kwargs.get('enabled', True)
# Allow overriding enabled status of backends through environment variables
# Set REGISTRATOR_ETCD to true, 1 or enab... |
import board
import neopixel
import time
pixels = neopixel.NeoPixel(board.D18, 20)
pixels[5] = (10,0,0)
|
#!/usr/bin/env python
import argparse
import json
import os
import re
import sys
import time
#
# Global
#
CEPH_LOG_DIR = os.environ.get('CEPH_LOG_DIR') or \
'/var/log/ceph'
CEPHSTATS_LOG_DIR = os.environ.get('CEPHSTATS_LOG_DIR') or \
CEPH_LOG_DIR
CEPHSTATS_LOG_FILE = os.environ.get... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-25 07:38
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
... |
def dpMakeChange(coinValueList, change, minCoins):
for cents in range(1, change+1):
coinCount = cents
for j in [c for c in coinValueList if c <= cents]:
if minCoins[cents-j] + 1 < coinCount:
coinCount = minCoins[cents-j] + 1
minCoins[cents] = coinCount
return ... |
import pandas as pd
import requests
from multiprocessing import Pool
from urllib.parse import urljoin
FPL_URL = 'https://fantasy.premierleague.com/'
API = 'api/'
ENTRY = 'entry/'
HISTORY = 'history/'
SHARDS = 1024
CURR_WEEK = 6
NUM_PARTICIPANTS = 7338639
def get_entry_history(entry_id):
entry_path = API + ENT... |
from django.db import models
# Create your models here.
TYPE_SELECT = (('0', 'Female'),('1', 'male'),)
class Student(models.Model):
name = models.CharField(max_length=255,blank=True)
roll_no = models.IntegerField(null=True)
email = models.EmailField(unique=True)
mobile = models.CharField(max_length=2... |
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import RandomForestClassifier
# df_train = pd.read_csv('Kaggle_Datasets/Facebook/train.csv')
# df_test = pd.read_csv('https://s3-us-west-2.amazonaws.com/fbdataset/test.csv')
def run():
print 'Loading DataFrame'
d... |
#Functions take files and plots contents
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.patches import Circle
from pylab import savefig
#DECLARE FILE
filenumber = 41
text = 'positions/position_test%d.txt' % filenumber
def Parameter_builder(text):
fil... |
import copy
def fibHelper(x):
if x == 0:
return 0
elif x == 1:
return 1
return fibHelper(x-1) + fibHelper(x-2)
def fib(x):
return fibHelper(x)
def reverseStringHelper(s, reversedString):
if len(s) >= 1:
rs = s[0] + reversedString
string = s[1:]
else:
return reversedString
return reverseStringHelper(str... |
## install python libraries from terminal for pulling data out of HTML files.
# pip install bs4
# pip install requests
# step 1: import modules
# step 2: make requests instance and pass into URL
# step 3: Pass the requests into a BeautifulSoup() function
# step 4: Use 'img' tag to find them all tag ('src')
import req... |
from Bio.Blast import NCBIXML
import sys
import argparse
from glob import glob
#from joblib import Parallel, delayed
import os.path
#hsps with larger e-value are discarded
significant_e_value = 0.001
#if query coverage fraction is smaller then alignment is discarded
significant_query_fraction = 0.1
#if best_hit_qu... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
#!/usr/bin/env python3
r'''
./p01B-missing-number-sorted
This program finds the missing number in a list of integers. This
implementation is optimized for sorted lists through use of binary
search.
* by: Leomar Duran <https://github.com/lduran2>
* date: 2019-06-28T23:53ZQ
* for: https://dev.to/javinpaul/50-data-struc... |
from config import ConfigurationError
from config import PropertyFormatError
from config import PropertyNotExistError
from config import parse_config
from config import validate
class TestAdminConfig:
def test_valid_config(self):
errors = validate(parse_config('tests/fixtures/valid_config.yaml'))
... |
import sys
import matplotlib.pyplot as plt
import numpy as np
#PATH="\Users\maxen\Desktop\FORMATION\2A\INF442\projet\code\connected-components\data\"
#print(PATH)
PATH="data/"
#print(PATH)
def distance_2D(ax, ay, bx, by):
return np.sqrt( (ax - bx) ** 2 + (ay - by) ** 2)
def create_graph(n, p):
# Save coordi... |
# -*- coding: utf-8 -*-
import inject
import logging
import asyncio
from asyncio import coroutine
from autobahn.asyncio.wamp import ApplicationSession
from model.registry import Registry
from model.connection import connection
from model.positions.positions import Position
from model.serializer.utils import MySeria... |
import datetime
#the following function takes a letter and returns a number for its position.
def alphabet_position(letter):
alpha = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
for ctr in range(len(alpha)):
if alpha[ctr] == letter:
return int(ctr/2)
#the following function rotates a letter... |
# -*- coding: utf-8 -*-
from typing import List
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
return [
(nums[i // 2] if i % 2 == 0 else nums[i // 2 + n]) for i in range(2 * n)
]
if __name__ == "__main__":
solution = Solution()
assert [2, 3, 5, 4, ... |
# -*- coding: utf-8 -*-
import pytest
from django.template import Template, Context
from chloroform.models import Configuration
@pytest.mark.django_db
def test_chloroform_ttag():
Configuration.objects.create(name='default')
t = Template('{% load chloroform %}{% chloroform %}')
rendered = t.render(Conte... |
from Tools.Utilities.ObjectCounter import objectCounterUi as oCounter
reload(oCounter)
oCounter.create()
|
from .direct import DirectMethod
from .wilson import WilsonMethod
from .eratosthene import EratostheneMethod
|
def merge(parents, ranks, src, dst):
src_parent = get_parent(parents, src)
dst_parent = get_parent(parents, dst)
if src_parent == dst_parent:
return False
if ranks[src_parent] > ranks[dst_parent]:
parents[dst_parent] = src_parent
else:
parent... |
import cv2
import numpy as np
img1 = np.zeros((277, 576, 3), np.uint8)
img1 = cv2.rectangle(img1, (238, 0), (338, 100), (255, 255, 255), -1)
img2 = cv2.imread('image_1.jpg')
bit_and = cv2.bitwise_and(img2, img1)
bit_or = cv2.bitwise_or(img2, img1)
bit_xor = cv2.bitwise_xor(img2, img1)
bit_not1 = cv2.bitwise_not(img1)... |
import os, re
from twisted.python.filepath import FilePath
from twisted.internet.inotify import IN_MODIFY, IN_CREATE, INotify
from twisted.internet import reactor
import gallery
WATCH_DIRECTORY = os.path.abspath(os.path.dirname(__file__))
WATCH_DIR_LEN = len(WATCH_DIRECTORY)
galleries = {}
call_ids = {}
CALL_DELAY... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.