index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
13,500 | 128d115d39ba8e9ba386c20137ca281bb42eafd8 | from django import forms
from . import models
class SongForm(forms.ModelForm):
class Meta:
model = models.Song
fields = ["title", "artist", "remixer", "url", "file", "genre", "tags"]
|
13,501 | 0f40ee5b37f046a40a84d6c510e38915412eabc8 | # Generated by Django 2.0.1 on 2019-05-23 07:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ticket', '0007_ticketfile_title'),
]
operations = [
migrations.AlterField(
model_name='ticket',... |
13,502 | e6f4ea9449b9397cfed0e1f34f6a80a0801583d9 | STOP_WORDS = [
'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'has', 'he',
'i', 'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the', 'to', 'were',
'will', 'with'
]
def print_word_freq(file):
"""Read in `file` and print out the frequency of words in that file."""
text_file = op... |
13,503 | 67f6018639176696321814533edf05784f1c3dd2 | import re
def abbreviate(words):
return "".join(word[0].upper() for word in re.sub("-", " ", words).split(" "))
|
13,504 | b331230bbbfea89fd8cb80dc4b917c302e6a186f | from django.test import TestCase
from datetime import datetime
from .models import *
# Create your tests here.
class MenuItemsTest(TestCase):
def setUp(self) -> None:
cat1 = Category.objects.create(name='irani')
cat2 = Category.objects.create(name='fast food')
menu_item1 = MenuItems.obje... |
13,505 | 4e66f86f60eaf39db1f9ff43814cb0fe00391d9e | """
Robert Matthews
CS 1400
Section 002
Exercise 3
3.4
Chapter 3, Programming Exercises #2, pg. 79. Write a program to calculate the cost/sq. inch of a circular pizza given
the diameter and total price. Submit the code as your answer. Do not submit results.
"""
def main():
import math
pizzaCostRaw = eval(inp... |
13,506 | 2f0528a3c75b723becd5fe53046faaa5c4fc091b | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-10-14 20:10
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Create... |
13,507 | 51929c81591dea78d13a982d8a8b348b7b058031 | #encoding:utf-8
'''
Created on 2014-8-13
测试产品管理
@author: 张文硕
'''
from hhplt.testengine.autoTrigger import EmptyTrigger
class ProductTestSuite():
@staticmethod
def emptyFun(product):
'''空方法,用于没有定义set和rollback方法的测试用例集模块'''
pass
'''产品测试项'''
def __init__(self,testSuiteModule):
... |
13,508 | c222bfb856c0f5176275be533f1ed788b630cde5 | """
@author: Payam Dibaeinia
"""
import torch
import torch.nn as nn
from collections import OrderedDict
from ResidualBlock import ResNetBlock
class generator(nn.Module):
"""
According to the cycleGAN paper, reflection padding and instance normalization was used.
Also all dimensions including number of ch... |
13,509 | 79a057497d2a5940ecac8e25a853ab7b079f2b66 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def main():
startpoint = [ i for i in input()]
endpoint =[ j for j in input()]
x_distance = ord(startpoint[0]) - ord(endpoint[0])
y_distance = int(startpoint[1]) - int(endpoint[1])
x_abs_distance = abs(ord(startpoint[0]) - ord(endpoint[0]))
y_a... |
13,510 | 3f7b939d6d4d12439643523c47f22bab9dcb0f0c | from flask import Flask, render_template, redirect, url_for, request, jsonify, session
from initQuestionfiles import initBiology, initComputing, initNorwegian, optionList
app = Flask(__name__)
#secret key is required for the use of sessions.
app.secret_key = 'A0Zr98j /3 yX R~XHH!jmN]LWX / ,? RT'
#initialising the pre... |
13,511 | be0c81b34583cb5e1de518eaa04733de53703806 | from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.all_blog, name='all_blog'),
path('<int:bid>/', views.view_blog, name='view_blog'),
] |
13,512 | 8e02ec109a8473825968e6358dfdf61c47e42b5d | # Sample of simple LFSR
def shift(startstate, tap_1, tap_2):
counter = 0
cipherbits = []
register = startstate.copy()
while (True):
cipherbits.append(register[-1])
counter += 1
register = [(int(register[tap_1] != register[tap_2]))] + register[:-1]
if register == startsta... |
13,513 | b4318ba59ab797d4d14cea21bf48a61746b17d05 | class Solution:
def binaryGap(self, N):
"""
:type N: int
:rtype: int
"""
l = len(bin(N)[2:])
position = -1
while l > 0 :
if N % 2 == 1:
if position == -1:
position = l
max_gap = 0
... |
13,514 | fdb03d958558555cd8f088a4d4ea2bc3c53a2b53 | """
Retrieves the permissions on the file that are assigned to the current user.
"""
from pprint import pprint
from office365.sharepoint.client_context import ClientContext
from tests import test_team_site_url, test_client_credentials
ctx = ClientContext(test_team_site_url).with_credentials(test_client_credentials)
f... |
13,515 | 86a42db959d27797df27dc7edbfda69f4cc78bc5 | import numpy as np
import pandas as pd
df=pd.read_csv("/home/ghanshyam/Machine Learning/movie_data.csv",encoding='utf-8')
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import TfidfVectoriz... |
13,516 | 91f1527b97b6198c6ec162166af1b6d530ba8716 | from collections import namedtuple
from ibanity import Ibanity
def get_list(params={}):
uri = Ibanity.client.api_schema["sandbox"]["users"].replace("{sandboxUserId}", "")
response = Ibanity.client.get(uri, params, None)
return list(
map(
lambda user:
__create_user_named_tup... |
13,517 | b195afe4e187b614894648a3e6bd353ebedf2c50 | import quandl
import pandas as pd
api_key = '2LWMTZKKbDgy5Zqycxjq'
#df = quandl.get('FMAC/HPI_AK', authtoken=api_key, start_date="1999-01-31")
#print(df.head())
fiddy_states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states')
#This is a list:
#print(fiddy_states)
#This is a datafra... |
13,518 | d939670aeabc3cec9fefc5e29b57614dd79b2bd3 | """Stores constants for all modules."""
import os
# Directories
PACKAGE_BASE_DIR = os.path.dirname(os.path.abspath(__file__))
PROCESSED_DATA_DIR = os.path.join(PACKAGE_BASE_DIR, "data")
# Option constants
ALPHA = "alpha"
LOWER = "lower"
|
13,519 | edf4eb25316ca438a6a3f65240a0e6680a163702 | import pyautogui
import time
rgb = pyautogui.pixelMatchesColor(31, 615, (0, 55, 132), tolerance=5)
while rgb == True:
pyautogui.hotkey('ctrl', 'win', '1')
time.sleep(1)
rgb = pyautogui.pixelMatchesColor(31, 615, (0, 55, 132), tolerance=5)
time.sleep(1)
pyautogui.moveTo(1250, 400) # Çanta2
time.sle... |
13,520 | 2288534bec9853055ee9e029ab3da6b51b72cac7 | from utils.Tree import letterTree
def depth_limited_search_r(problem, goal, limit):
if problem.value == goal:
return True
elif problem.depth == limit:
return 'cutoff'
elif problem.children is not None:
cutoff_occurred = False
for child in problem.children:
resu... |
13,521 | db9a03106dc3c908c3e295080c5baffcefe6a6f1 | # coding=utf8
# 并行模拟器应使用多进程的方式进行模拟
# 如果要启动大量的子进程,可以用进程池的方式批量创建子进程:
from multiprocessing import Pool
import os, time, random
import BigGatewatPut2_2
def long_time_task(url, apikey, data):
print 'Run task %s (%s)...' % (apikey, os.getpid())
start = time.time()
time.sleep(random.random() * 3)
end = time.... |
13,522 | 96928a8553438253bac21e87eaf932db3057080b | import collections
import re
from queue import PriorityQueue
test_inputs = [
"inputs/day7"
]
line_pattern = re.compile(r"Step\s*(\w*)\s+must.*step\s+(\w*)\s+can.*")
def interpret(rules):
pred = collections.defaultdict(set)
succ = collections.defaultdict(set)
domain = set()
for rule in rules:
... |
13,523 | 71a56ca9f7b895ac3cda7d0cde73ba9f9408b150 | def main():
import sys
input = sys.stdin.readline
N, K = map(int, input().split())
d = [0]*K
A = [0]*K
for i in range(K):
d[i] = int(input())
A[i] = list(map(int, input().split()))
have = []
for a in A:
have[len(have):] = set(a)
print(N - len(set(have)))
... |
13,524 | b97c8671bdb6bc6547f88efd80627bd07829a0b1 | import os
import math
import datetime
import logging
from itertools import chain
import pyaml
import torch
from torch.nn import ModuleDict
from torch.optim import Adam, SGD, RMSprop
def path_to_config(name):
return os.path.join(os.path.dirname(os.path.dirname(__file__)), "config", name)
def path_to_output(nam... |
13,525 | c22b259266af181656e8b2baf44999718a40c5ed | from flask import Flask, request, jsonify
import tensorflow as tf
app = Flask(__name__)
available_fps = [3, 4, 5]
models = {fps: tf.keras.models.load_model(f'model/fps_{fps}') for fps in available_fps}
class_labels = ['push-up-arms-not-bent-enough', 'push-up-normal', 'push-up-waist-too-low', 'sit-up-normal', 'sit-up-... |
13,526 | 969dd71121a604a65681fbfd148f5e896826e31c | import flask
from flask import Flask, request
import requests
from flask.logging import default_handler
from py_zipkin.transport import SimpleHTTPTransport
from py_zipkin.zipkin import zipkin_span, create_http_headers_for_new_span, ZipkinAttrs, Kind, zipkin_client_span
from py_zipkin.request_helpers import create... |
13,527 | ebcdee546958e9e5292c3d5ee3d34bc6be4b6d20 |
import boto3
"""
Note: code is for reference only (taken from an online course)
"""
if __name__ == '__main__':
# Generate the boto3 client for interacting with translate (for
# translation of text into another language)
translate = boto3.client('translate', region_name='us-east-1',
... |
13,528 | 6493ae482d2bf2a066bf9cbe9ef68239cc2802e6 | # -*- coding: utf-8 -*-
# Scrapy settings for newcar_new 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
# https://docs.scrapy.org/en/latest/... |
13,529 | 99c79d0646471ac8209f385d57c946a7caf8d0c7 | from __future__ import unicode_literals
__version__ = "5.0.29"
|
13,530 | ef3bcccb936e67d88cb08a3c8d368bf4fafb8780 | #!/urs/bin/env python
# coding:utf-8
#
'''
对爬取cnblogs.com上的文章并保存为本地pdf文档进行优化,
1.最开始采用requests模块进网页爬取,因为前一个版本使用的的是urllib,这个版本才用一种新的模块。
2.在爬取的时候发现爬取的某一篇文章呈现布局和浏览器中呈现的不一样
3.查找原因,结果是该html中嵌套了javascript代码,直接爬取的html代码当然和浏览器解析过不一样
4.这个问题其实也很简单找一个能够解析html中嵌套js代码的“非传统浏览器”即可,经过一番goole之后发现还真用这样的浏览器(方式)
5.PhantomJS与chrome headless... |
13,531 | 51be17e9ae03909eb7e155af59bf1c3891655f52 | # Program: Algoritmo237_Para64.py
# Author: Ramon R. Valeriano
# Descritption:
# Developed: 02/04/2020 - 23:04
# Updated:
number = int(input("Enter with the number: "))
sum_ = 1
for e in range(2, number+1):
if number%2==0:
sum_-=(1/number)
else:
sum_+=(1/number)
print("\n", sum_)
|
13,532 | a317e54bcee51f836cdf45c3ea24bee88af46ca1 | #!/usr/bin/env python
from http.server import BaseHTTPRequestHandler, HTTPServer
import urllib
from os import curdir, sep
import functools
import datetime
from enum import Enum
from urllib.parse import urlparse
import traceback
import configparser
import os
from config import Config
from common import Page
from ack i... |
13,533 | e6fe262d292e7b7fdad96b190fbbfb6ce32972b2 | from behave import *
import requests
import json
@given('I have user authentication credentials')
def step_impl(context):
context.url = 'https://api.withleaf.io/api/authenticate'
context.headers = {'content-type': 'application/json'}
context.data = {"username": "fernandosdba@gmail.com", "password": "940844... |
13,534 | ead60a83f114c9433ca47f619d9ac5a336cda5ae | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the Apache License Version 2.0.You may not use
this file except in compliance with the License.
This progra... |
13,535 | 8c5972d22855a5caf53cb1aedf828309d39b91f3 | # (c) 2017 Apstra Inc, <community@apstra.com>
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: aos_bp_security_zone
author: ryan@apstra.com (@that1guy15)
version_added: "2.7"
short_description: Ma... |
13,536 | dd8202c5fcd5796cf68e9a927a57a8140bd45b38 | class Koło:
def pole(r):
pole = 3.14*r*r
print('Pole = ',pole)
def obwod(r):
obwod = 2*3.14*r
print('Obwód = ',obwod)
Koło.pole(3) |
13,537 | 90431950df772012bc87bc0b1a47d2156fa1e811 | import re
import datetime
from pyspark.sql import Row
month_map = {'Jan': 1, 'Feb': 2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7,
'Aug':8, 'Sep': 9, 'Oct':10, 'Nov': 11, 'Dec': 12}
def parse_apache_time(s):
""" Convert Apache time format into a Python datetime object
Args:
s (str): date and tim... |
13,538 | 3852d22c98dbdfc3ab64af8c3a00ab2cec8e62af | # -*- coding: utf-8 -*-
"""Views for PyBEL-Web."""
from .base_view import ModelView
__all__ = [
'ReportView',
'ExperimentView',
'QueryView',
]
class ReportView(ModelView):
"""View for reports."""
column_exclude_list = ['source', 'calculations', 'source_hash']
column_display_pk = True
c... |
13,539 | 322f604b1aec80d402a812506dbe5319d96db7a8 | import os
import glob
path = "dets/*.*"
last_created_file = (max(glob.glob(path), key=os.path.getmtime)).split('/')[1][:-4]
for i in range(int(last_created_file)):
if not os.path.isfile('dets/'+str(i)+'.txt'):
with open('dets/'+str(i) + '.txt', 'a') as logfile:
continue # create empty file if ... |
13,540 | cdfe6d82b852420bfbcc7fbb96cd0b96af5002c6 | def CountDigit(number,digit ):
str_numbers = str(number)
str_number = str(digit)
count = 0
for i in str_numbers:
if i == str_number:
count+=1
return count |
13,541 | fc42cf1245a694017ca0a47e3c01d6bb28d128b4 | import pandas as pd
import numpy as np
iris_data = pd.read_excel('iris_data.xlxs')
print(iris_data) |
13,542 | ab693173dc8b37c6db4a3d56da5a8dfb8fb91f25 | '''
Sample Input:
2
Sun 10 May 2015 13:54:36 -0700
Sun 10 May 2015 13:54:36 -0000
Sat 02 May 2015 19:54:36 +0530
Fri 01 May 2015 13:54:36 -0000
Sample Output:
25200
88200
Explaination:
In the first query, when we compare the time in UTC for both the time stamps,
we see a difference of 7 hours. which is 7x3600 second... |
13,543 | 548b7995312997f028e6887a612e96757c4a6042 | #------------------------------------------------------------------------------+
# Villian Class
#
# Villians are characters very similar like players. The main difference is
# that they are controlled by the game.
#
#------------------------------------------------------------------------------+
import pygame, custom_... |
13,544 | 1d3074a3c07c32edfc085ebf8641c5196937ba4f | #https://open.kattis.com/problems/apaxiaaans
name = input()
newname = ""
for i in range(len(name)-1):
if name[i] != name[i+1]:
newname += name[i]
print(newname + name[-1])
|
13,545 | 062b6a942784bdbbe0ed88c50b15933fd32783da | 'bag predictions from imputed data sets'
import numpy as np
from glob import glob
input_pattern = '/path/to/many/predictions/dir/*.csv'
output_file = '/path/to/where/you/want/p_imputed_bagged.csv'
# in case we re-run the script in ipython
p = None
files = glob( input_pattern )
for input_file in files:
print input... |
13,546 | bee83d4ef4b05bc65febb540853bbcff003bcc6e | import numpy as np
import matplotlib.pyplot as plt
def quantile_exponential_distribution(lambda_param, y):
return -np.log(1-y) / lambda_param
def main():
n = 10000
exponential_samples = np.random.exponential(1,n)
plt.hist(exponential_samples)
plt.show()
uniform_samples = np.random.uniform(0... |
13,547 | 3ff09d4c5b6e62687e2beba5b0ad5e44bd75a1ae | # Generated by Django 2.2.7 on 2019-11-27 15:30
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('desecapi', '0011_user_id_to_uuid'),
]
operations = [
migrations.AlterModelOptions(
name='donation',
options={'managed': Fals... |
13,548 | d093c80fed7a3dfc8f74e017ada74d4d5ae81723 | class TransactionOutputRow:
def __init__(self, transaction_output, row_index):
self.transaction_output = transaction_output
self.row_index = row_index
def __getitem__(self, item):
return self.transaction_output.data[item][self.row_index]
def __contains__(self, item):
return... |
13,549 | c5869fd46cd70044af9687ae3ce7e0bb0854c570 | import re
def get_link_from_query(query):
m = re.findall("(https?://\S+)", query)
if len(m) > 0:
return m[0]
return None
def validate_query(query):
return get_link_from_query(query) or re.search("aliexpress", query) or is_digits(query)
def is_digits(query):
return re.search("^\d+$", qu... |
13,550 | 957d73101d1315fd1061eda5bfd4c38e063cd58d | """ Setup dependencies """
# TODO...
|
13,551 | 564da178e367fd93d75ef9dcdd0d63877bc48ccc | from scipy.stats import norm
from scipy.stats.mstats import mquantiles
from numpy.random import choice,seed
from numpy import array
seed(756)
Den=[ 0.08015092, 0.10789958, 0.12167541, 0.21219431, 0.07920235, 0.19467892, 0.5431346, 0.13779066]
MnWgt=norm(2.804086007439/2.2,0.02273154621778/2.2)
class BedArea(... |
13,552 | f55a2fdad886867945580c168fc99fba6d352558 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
xls2001 = pd.read_excel("./2001.xls")
xls2002 = pd.read_excel("./2002.xls")
xls2003 = pd.read_excel("./2003.xls")
xls2004 = pd.read_excel("./2004.xls")
xls2005 = pd.read_excel("./2005.xls")
xls2006 = pd.read_excel("./2006.xls... |
13,553 | 1342ed1686f80f6e8681a6f8f359a5b7a34b1d91 | from django.contrib import admin
from tagbase.models import *
admin.site.register(FunctionTag)
admin.site.register(NounTag)
admin.site.register(VerbTag)
autorobo, success = User.objects.get_or_create(username='autorobo', password='autorobo')
def import_tags():
HUB_FILE_PATH = 'tagbase/fixtures/wired_hubs.txt'
... |
13,554 | 5d2f821c06c8641574f8e53e4200c7c35e92ae49 | from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import relationship
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import Integer, String, Date, CLOB, Float
from src.sgd.model import EqualityByIDMixin
from src.sgd.model.bud import Base
from feature import Feature
class S... |
13,555 | 526e1768d904d15bd5b92091bb64df8a7e71070a | from mnis.mnislib import \
getCurrentCommonsMembers, \
getCommonsMembersOn, \
getCommonsMembersBetween, \
getCommonsMembersAtElection, \
getCommonsMembers, \
getIdForMember, \
getListNameForMember, \
getGenderForMember, \
getDateOfBirthForMember, \
getConstituencyForMember, \
getPartyForMember, \
getService... |
13,556 | 3fa6e4f865210bbbd58ff82871fabc50ad399f6b | import tensorflow as tf
import keras.backend.tensorflow_backend as K
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Conv1D
from keras.layers.pooling import MaxPooling1D
from keras.optimizers import SGD
from keras.layers.normaliz... |
13,557 | f79c1efe561f22a348d2774ec02c630759cdcd42 | from hurley.server import app
|
13,558 | 6f62bb245df6da4e660f68cc18f3bef80e452106 | from enum import Enum
class Currencies(Enum):
USD = "$ US Dollar"
GBP = "£ Pound Sterling"
EUR = "€ Euro"
|
13,559 | 31618f55a14b74f1e7ec067890e19263fbf3aa27 | from typing import Dict
# Path to Google's pre-trained word2vec model (.bin file)
WORD2VEC_MODEL_FQN: str = "models/word2vec/GoogleNews-vectors-negative300.bin"
# Path to Stanford's pre-trained GloVe model (.txt file)
GLOVE_MODEL_FQN: str = "models/glove/glove.840B.300d.txt"
# Dimension of each embedding.
F: Dict[st... |
13,560 | 45c93b61fe2caced9b39340962ad31497ce53a04 | import turtle
from random import randrange
def draw_tree(branch_len: float, t: turtle.Turtle):
if branch_len > 5:
t.width(width=int(branch_len) // 10)
t.pencolor((0.15, (150 - branch_len) / 150, 0.25))
t.forward(branch_len)
t.right(20)
draw_tree(branch_len=branch_len - 15, ... |
13,561 | e79b731baf4fab3d4019971dd124c92beba2148f | from .env import Env
|
13,562 | edbdb9c336216bda071e46253c9a4a61093711e9 | __author__ = 'Koh Wen Yao'
from collections import OrderedDict
########################################################################
# General Constants
########################################################################
SCRIPT_RUN_INTERVAL_MINUTES = 1
DATA_RETRIEVAL_BUFFER_MINUTES = 3
MONITORING_TIME_MINUTE... |
13,563 | 4f9177860a247b3c4326f0d9dc9c43c69aa9c2d4 | import logics_func
print("Привет. Я буду загадывать тебе примеры а ты разгадывай.")
# запуск первой функции модуля logics_func (и последующие запуски функций)
logics_func.multiplication()
|
13,564 | 006e4ca3abac2de5bbfeac47d9afed9d3d3869f5 | from keras import applications
from keras.models import Sequential
from keras.models import Model
from keras.layers import Dropout, Flatten, Dense, Activation, AveragePooling1D
from keras.callbacks import CSVLogger
import tensorflow as tf
from scipy.ndimage import imread
import numpy as np
import random
from keras.laye... |
13,565 | 582c42eab1774056e10ab6df6e156fff64c6605e | import matplotlib.pylab as plt
import numpy as np
x = np.arange(-8, 8, 0.1)
# # Basic Sigmoid
# f = 1 / (1 + np.exp(-x))
# plt.plot(x, f)
# plt.xlabel('x')
# plt.ylabel('f(x)')
# plt.show()
# # With weights
# w1 = 0.5
# w2 = 1.0
# w3 = 2.0
# l1 = 'w= 0.5'
# l2 = 'w = 1.0'
# l3 = 'w= 2.0'
# for w,l in [(w1,l1),(w2... |
13,566 | ab17cbd085336c24e3cb565645f371988ada74ac | import pandas as pd
import numpy as np
import os
import sys
def find_project_dir():
if os.path.isdir("project_git_repo"):
return os.path.realpath("project_git_repo/cpd35-clustering-demo")
else:
return os.getcwd()
PROJECT_DIR = find_project_dir()
SCRIPT_DIR = os.path.join(PROJECT_DIR, "assets... |
13,567 | 2e84960c6072e9e7bb0ed101aee68140327958b4 | #!/usr/bin/env python
"""
ARepA: Automated Repository Acquisition
ARepA is licensed under the MIT license.
Copyright (C) 2013 Yo Sup Moon, Daniela Boernigen, Levi Waldron, Eric Franzosa, Xochitl Morgan, and Curtis Huttenhower
Permission is hereby granted, free of charge, to any person obtaining a copy of this soft... |
13,568 | a284a20dd9a00bef8f5875da4d86017cf6d0f129 | import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set(style="ticks")
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(7.5, 8.8))
fig.subplots_adjust(
left=0.13,
right=0.97, # {Define as distâncias entre os extremos}
botto... |
13,569 | 0152690f3d971d595431e38385e644a5f7cfb45f | import sys
import matplotlib.pyplot as plt
import random
import numpy as np
import argparse
from CSVManager import CSVManager
from KMeans import KMeans
import pandas as pd
import os
from SimplifiedSilhoutte import SimplifiedSilhouette
def main():
path = sys.argv[1]
csvManager = CSVManager()
df = csvManag... |
13,570 | 94e4eb97fbcfe2beef57258ffe3878978928f328 | a = int(input())
b = int(input())
l = []
def isPrime(n):
if n == 1:
return False
for j in range(2, int(n ** (1 / 2)) + 1):
if n % j == 0:
return False
else:
return True
def findMinArray(arr):
m = arr[0]
for i in arr:
if m > i:
m = i
r... |
13,571 | 5872b3a54e1ac66069991f563e0e7c261425d661 | import random
desserts = ["red velvet cake", "souffle", "ice cream", "macaron", "sundae", "flan", "tarimisu"]
desertaa = random.choice(desserts)
print("A dessert" + dessertaa)
#2 months on SL! Thank ya'll!
import random
first = ("Super", "Retarded", "Great", "Sexy", "Vegan", "Brave", "Shy", "Cool", "Poor", ... |
13,572 | f277d633b979e2f37bd7f74cb07d5cf80821b5c1 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score
... |
13,573 | 744c53c51e0dc2ae98f1f7a72c88a0cb6dbac056 | from django.views.generic import TemplateView
from toko.apps.products.models import Product
class HomeView(TemplateView):
template_name = 'pages/home.html'
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['featured_products'] = Product.o... |
13,574 | 78e7591bd1e29421e798e49a4eff45b5ccfa11ec | print("Choi")
print("33age")
print("wear : glasses")
print("키 : 170cm")
print("서울 거주")
|
13,575 | 94ea009891366ffa8f1b8eb025f4acfa8998c740 | """
line_text_edit
tbd
author: Michael Redmond
"""
from __future__ import print_function, absolute_import
from .line_text_widget import LineTextWidget
|
13,576 | 57582f251fcd7124a21d7d94c07da8d2433e04fb | # Copyright (c) 2019 Ezybaas by Bhavik Shah.
# CTO @ Susthitsoft Technologies Private Limited.
# All rights reserved.
# Please see the LICENSE.txt included as part of this package.
# EZYBAAS RELEASE CONFIG
EZYBAAS_RELEASE_NAME = 'EzyBaaS'
EZYBAAS_RELEASE_AUTHOR = 'Bhavik Shah CTO @ SusthitSoft Technologies'
EZYBAAS_RE... |
13,577 | 104913f96a427954ae8b9417b2f88b2267d62431 | import xml.etree.ElementTree as ET
import pandas as pd
import wget
import urllib.request
# Downloading dataset
#urllib.request.urlretrieve("https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%205/data/Sample-employee-XML-file.xml", "new_... |
13,578 | d5b95c26b3d18df6d57dfe9e2f46f81da13c5b7e | class Monad:
def __init__(self, value):
self._value = value
@classmethod
def unit(cls, val):
"""Lifts a single value into the elevated world
Signature: a -> E<a>
Alternative names: return, pure, unit, yield, point"""
raise NotImplementedError
@classmethod
de... |
13,579 | 67877075e0f8a318be0753a038ed5518cebdfa9e | """
https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem
A semaphore manages an internal counter
acquire() count -= 1
release() count += 1
The counter can never go below zero
when acquire() finds that it is zero, it blocks, waiting until some other thread
calls release().
works fine when there is only ... |
13,580 | 4f81da715bfa6a044dd172f30445ad341e37f1c1 | """
Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Your input will ... |
13,581 | 55378cb769b7fbbe9cb6e24e6185813954b45346 | from datetime import datetime
from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, redirect
from .forms import CreateQuizForm, CreateQuestionForm
from .models import Quiz, Riddle
from django.views.generic import ListView
from users.models import Profile
fr... |
13,582 | 01a7bb956b3c316cb0da6736eb96face97ffe26f | # -*- coding: utf-8 -*-
"""
flask.ext.social.datastore
~~~~~~~~~~~~~~~~~~~~~~~~~~
This module contains an abstracted social connection datastore.
:copyright: (c) 2012 by Matt Wright.
:license: MIT, see LICENSE for more details.
"""
from flask_security.datastore import SQLAlchemyDatastore, MongoEn... |
13,583 | de83ceb34fd17635f0ba2d41a2b24ea2a191fd14 | import logging
import re
import socket
import struct
import time
import uuid
from threading import Timer
from urllib.parse import quote
import zeroconf
import config
from plugin import GetPlugin
SHARE_TEMPLATE = '/TiVoConnect?Command=QueryContainer&Container=%s'
PLATFORM_MAIN = 'pyTivo'
PLATFORM_VIDEO = 'pc/pyTivo' ... |
13,584 | 0d97cac9b3173506e33be3584b14af9f3ee3657d | """This module provides classes to search in the obs.
Currently only the search for requests is supported.
"""
from lxml import etree
from osc2.remote import Request, RemoteProject, RemotePackage
from osc2.util.xml import fromstring, OscElement
from osc2.core import Osc
class ProjectCollection(OscElement):
""... |
13,585 | edb66e83f93365aa737e09c6f79808c3319db83c | """Tests for the various features from the code generation templates."""
import importlib
import pytest
from pyecore.ecore import EPackage, EClass, EReference, EEnum, EAttribute, EInt, EOperation, \
EParameter, EString, EDataType, EAnnotation
from pyecoregen.ecore import EcoreGenerator
def generate_meta_model(m... |
13,586 | 08fe545b271999c17dcb0ed9563fcbfa7e1fda82 | import os
from flask import Flask, render_template
import logging
from logging.handlers import RotatingFileHandler
app = Flask(__name__)
app.debug = True
cwd = os.getcwd()
@app.route('/')
def index():
return 'Simple vault app for files and images'
if __name__ == '__main__':
# Log http requests
logging.basi... |
13,587 | 7499afe3eec54cf693d57f431c91b57d6f246a19 | import logging
import re
from .const import *
from homeassistant.const import (
CONF_NAME,
CONF_ICON,
CONF_DEVICE_CLASS,
CONF_UNIT_OF_MEASUREMENT,
)
from homeassistant.helpers.entity import Entity
_LOGGER = logging.getLogger(__name__)
class IpxDevice(Entity):
"""Representation of a IPX800 generic... |
13,588 | 2bc184495e198a1fcf060e6433329f645c27a798 | # 1. Напишите функции уравнений:
# - x в степени 4 + 4 в степени x,
# - y в степени 4 + 4 в степени x
def ur1(x):
return x ** 4 + 4 ** x
def ur2(x, y):
return y ** 4 + 4 ** x
x = int(input("Vvedite 2 chisla:\n #1: "))
y = int(input(" #2: "))
print("Rezultat 1 uravnenija =", ur1(x))
print("... |
13,589 | 34bf1aae06fbfca55826f47d8e3c18fa1a867705 | class Solution:
m=0
n=0
count=0
rotten=[]
minutes=0
def rot(self,grid,r,c,time):
if r>=0 and r< self.m and c>=0 and c < self.n and grid[r][c] == 1:
grid[r][c]=2
self.rotten.append((r*self.n+c,time+1))
self.minutes=max(time+1,self.... |
13,590 | c84cd50341e6b3783effd3e1fa16f21f78afa8b8 | import numpy as np
import sys,os
import time
import os
import re
import cv2
import argparse
import functools
import subprocess
import numpy as np
from PIL import Image
import moviepy.editor as mpy
import torch.nn.parallel
import torch.optim
from models import TSN
from transforms import *
import datasets_video
from tor... |
13,591 | ab47bf1a68815483d5536735e6e11c0a85b3b284 | import sys
import re
import urllib.request
def checkurl(url):
match = re.search(r'\s*http://.*txt',str(url))
if match:
try:
req = urllib.request.Request(match.group())
with urllib.request.urlopen(req) as open_file:
lines = open_file.readlines()
re... |
13,592 | 7d4df9a5b63bd5383bba39a956dd6e99e09bfa8d | from open_publishing.core.enums import ValueStatus, FieldKind
from open_publishing.core import SequenceItem, SequenceField
from open_publishing.core import DatabaseObject, SimpleField, FieldDescriptor
class Genre(DatabaseObject):
_object_class = 'realm_genre'
def __init__(self,
context,
... |
13,593 | 4178d2259e79ca5f908150f26d85acd945521b1c | """
Given an array, rotate the array to the right by k steps, where k is non-negative.
Follow up:
Try to come up as many solutions as you can, there are at least 3 different
ways to solve this problem.
Could you do it in-place with O(1) extra space?
"""
from typing import List
class Solution:
def ro... |
13,594 | d5a6d231b0a3173e488aa45f503fe4f5ec0919c5 | #coding:utf-8
import math
n= 20000000
def get_pr(n):
list_num = []
for x in range(2, n):
for num in range(2,int(math.sqrt(x))+1 ):
if (x%num == 0 and x != num ):
break
elif x % num != 0 and num == int(sqrt(x)):
list_num.append(x)
return list_num
print math.sqrt(9)... |
13,595 | 4929f9d2007c35288bbe1d032c40eef02c2ab7b5 | import json
from typing import Iterator
from selenium.webdriver.remote.webdriver import WebDriver
from fdc.model import Ticket
from fdc.utils.browser import Browser
from fdc.utils.table import parse_table, Table
class Config(object):
def __init__(self, file_name: str):
with open(file_name, 'r') as file:... |
13,596 | 9f332ab3b6ee3d493927135ff9a9f8cfca45d532 | import sys
import configparser
from datetime import datetime as dt
from my_vocabulary.flashcard_dialog import FlashCardDialog
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from PyQt5.QtWidgets import QApplication
from models.general import (
Entry,
Note,
Tray,
FlashCard,... |
13,597 | ff2810cd09f7945573a05984c02aa9f54ad90f0c | # Generated by Django 3.1.3 on 2020-11-18 21:01
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Ad',
fields=[
('id', models.AutoField(auto_... |
13,598 | b350e52c0cf67e6f322152c1adb353597a407f79 | __author__ = 'Yanyi'
fp = open("Data/vh_sorted_train.txt", "r")
fw = open("Data/re_vh_sorted_train.txt", "w")
childFathers = {}
for line in fp.readlines():
lineNumbers = line[:-1].split('\t')
children = lineNumbers[1:]
if children[0] == "":
continue
for c in children:
if c not in chil... |
13,599 | f021567911646137f6921e44b3bc5ad1464e7c59 | #!/usr/bin/python
"""
4Sum
Given an array S of n integers, are there elements a, b, c, and d in S such
that a + b + c + d = target? Find all unique quadruplets in the array which
gives the sum of target.
Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order.
(ie, a <= b <= c <= d)
The solution ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.