text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
"""
#
# By: Charles Brandt [code at charlesbrandt dot com]
# On: *2014.12.19 11:02:13
# License: MIT
# Requires:
#
# Description:
#
initially adapted from moments.server code
"""
from __future__ import print_function
from builtins import str
from builtins import range
import os, sys, codecs,... |
from django.urls import path
from . import views
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
path('computations/discount/view', views.discount_view, name='discount-view'),
path('api/discount/data', views.get_data, name='get-data'),
path('computations/cost/view', views.cost_view, na... |
from tensorflow.keras.preprocessing.sequence import pad_sequences
import re#regular expression
import numpy as np
import pandas as pd
from nltk.corpus import stopwords
STOPWORDS = set(stopwords.words('english'))
from tensorflow.keras.models import load_model
import pickle
import trstop
from string import digits
import... |
from collections import deque
d=deque()
ops = int(input())
for i in range(ops):
inp = input().split()
command = inp[0]
values = inp[1:]
execute = 'd.' + command + "(" + ",".join(values) + ")"
eval(execute)
# Enter your code here. Read input from STDIN. Print output to STDOUT
print(*d)
|
import psycopg2
import sys
import csv
ADD_SONG = '''
INSERT INTO myschema.tracks(spotifyID, title, artist)
VALUES
(%s, %s, %s)
'''
ADD_RANKING = '''
INSERT INTO myschema.charts(spotifyID, chartDate, ranking)
VALUES
(%s, %s, %s)
'''
UPDATE_SPOTIFY_SONG_INFO = '''
UPDATE myschema.tr... |
# Must be loaded first, else 'free()' error
from dagster import ModeDefinition, PresetDefinition, execute_pipeline, pipeline, solid
import os
from typing import Union
import boto3
import modAL
import numpy as np
import pandas as pd
import sklearn
from modAL.models import ActiveLearner
from modAL.uncertainty import un... |
from django import forms
from .models import Autor
import datetime
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
class AutorForm(forms.Form):
imie = forms.CharField(label='Imie', max_length=200, required=True)
nazwisko = forms.CharField(label='Nazwis... |
#-*- coding:utf-8 -*-
import os,xlrd,sys
from fileUtils import getSuffis,createFiles,fixXlsName
from check import checkNumEquals
templates=' <string name="varName">varValue</string>'
nodeHeader='<resources xmlns:android="http://schemas.android.com/apk/res/android" \n xmlns:xliff="urn:oasis:names:tc:xliff... |
# coding: utf-8
import os, json
import xlrd
from sys import exit, argv
import string
#from string import Template
fileConfigMain = "../configMain.json"
preFileName = "ZL"
OUT_PATH = "model/"
EXCEL_FILE_NAME = "../test.xlsx"
MODELH_FILE_NAME = "template/modelNormal.h"
ALLH_FILE_NAME = "template/modelH_normal.h"
ALLH_F... |
from time import gmtime, strftime
import os
import time
basket1 = [
["Baked Beans",0.89,50],
["Loaf of bread",0.99,0],
["6 x Cans of cola",2.99,0],
["Pasta",0.75,10],
["Rice",1.98,50],
["Flour",0.94,0],
["Breakfast cereal",1.49,0]
]
# making the quit screen
def QuitScreen():
os.system("cls")
print("BYE")
tim... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Mayank Singh
"""
import re
import datetime
import string
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import RidgeClassifier
from sklearn.linear_model import SGDClassif... |
import cv2
import mediapipe as mp
import threading
import asyncio
import socket
import json
num_landmarks = 0
last_data = None
# web_stream_url = 'https://vdo.ninja/?view=anton_op5t'
web_stream_url = 'https://vdo.ninja/?view=anton_win10'
webcam_index = 1
use_webcam = True
use_web_stream = False
use_static_image = Fal... |
import unittest
import decision_tree_classifier as dtc
class DecisionTreeClassifierTest(unittest.TestCase):
"""DecisionTreeClassifierTest is a unit test for the decision tree"""
def test_entropy(self):
ent = dtc.entropy
self.assertEqual(ent([0,0,0]), 0)
self.assertEqual(ent([]), 0)
... |
import json
from django.http.response import HttpResponse, HttpResponseBadRequest, JsonResponse
from django.contrib.auth import get_user_model, login, authenticate, logout
from django.contrib.auth.views import login_required
from django.middleware import csrf
from django.views.decorators.http import require_POST
from ... |
#ex10: What was that?
#using the escape character '\'
print "I am 5'6\" tall." # escape double-quote inside string
print 'I am 5\'6" tall.\n'
#using triple quotes """ to spread text across lines without \n
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat... |
import json, os
from whatsapp.models.contact import Contact
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Add initial contact information derived from HaloPinjam Project'
def __init__(self):
pass
def handle(self, *args, **options):
s... |
from __future__ import print_function
from httplib2 import Http
import os
from apiclient.discovery import build
from oauth2client import client, tools, file
from datetime import datetime
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = Non... |
from spacy.lang.en import English
tokenizer = English().tokenizer
from config import base_config
import sys
import torch
from torch import nn
from datetime import datetime
import random as rand
import os
import traceback
import pickle
import ujson
import numpy as np
class RNetConfig():
def __init__(self):
... |
import aioredis
import config
class RedisWrappper:
def __init__(self, host, port, password, db=0):
self.url = f'redis://{host}:{port}/{db}'
self.password = password
self.redis = None
async def setup(self):
try:
self.redis = await aioredis.create_redis_pool(self.u... |
year = 2004
while year < 2100:
print(year, end=' ')
year = year +4
|
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
from sqlalchemy.orm import Query
from typing import Any, Literal, TypeVar, Union
from typing_extensions import NotRequired, TypeAlias, TypedDict
from onegov.server.types import (
JSON, JSON_ro,... |
"""
similar to q11, but more simplier
"""
n = 20
data = [[1]*n for _ in range(n)]
total = sum(sum(sub_list) for sub_list in data)
print(total) |
from decimal import Decimal
from quickbats.shared import csv_rows
from quickbats.shared import to_dec
def test_csv_rows():
for row in csv_rows("tests/data/iris.csv"):
assert "sepal_length" in row
def test_stop_after():
for i, row in enumerate(csv_rows("tests/data/iris.csv", stop_after=10)):
... |
import numpy as np
from collections import namedtuple, deque
import torch
torch.manual_seed(0) # set random seed
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical
from agents.policy_search import PolicySearch_Agent
BUFFER_SIZE = int(1e6) # ... |
from django.contrib import admin
from lists import models
admin.site.register(models.ItemList)
admin.site.register(models.Item)
|
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
a = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
num = 0
s = s + 'I' # 随便加个a中存在的Key,防止下面a[s[i+1]] outofrange...
for i in range(len(s)-1):
if a[s[i]] < a... |
#-*- coding:utf8 -*-
import os
import datetime
from django.conf import settings
from django.db.models import Q
from .handler import BaseHandler
from shopback import paramconfig as pcfg
from shopback.base import log_action,User, ADDITION, CHANGE
from common.modelutils import update_model_fields
class RegularSaleHand... |
import tornado
import tornado.web
import tornado.websocket
import tornado.escape
import json
import datetime
import random
import string
import qpython.qconnection
import perspective
class ManagerMixin(object):
def check_origin(self, origin):
return True
def set_default_headers(self):
self.se... |
# -*- coding: utf-8 -*-
#
# Copyleft (c) 2011 André Filipe A. Brito e contribuidores
#
#
# Conselhos is free software under terms of the GNU Affero General Public
# License version 3 (AGPLv3) as published by the Free
# Software Foundation. See the file README for copying conditions.
#
from django.shortcuts import ... |
import matplotlib.pyplot as plt
import csv
value_loss=[]
with open('progress.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in reader:
print row[0]
print type(row[0])
try:
value_loss.append(float(row[0]))
except Value... |
from flask import Blueprint, request, render_template , jsonify
from app.database.smdb import DataManager
dm = DataManager()
ind_module = Blueprint('ind',__name__)
@ind_module.route('/edit_inds' , methods=['GET','POST'])
def edit_inds():
records = dm.GetIndsWithGroup()
return jsonify(records)
@ind_modu... |
import math
def main():
a = float(input("qual seu a? "))
b = float(input("qual seu b? "))
c = float(input("qual seu c? "))
def bhaskara(a,b,c):
#a*(x**2) + b*x + c = 0
delta = b**2 - 4*a*c
if delta > 0 :
xmais = ((-b) + math.sqrt(delta))/(2*a)
xmenos = ((-b) - math.sqrt(delta))/(2*a)
print("as raí... |
#a
val = 0
i = 1
while i != n + 1:
val = val + i
i = i + 1
# loop invariant: val is sum of first n positive-integer
# function first_n_sum that inputs n and ouputs the sum of first n positive integers
#b
val = -1
i = 0
while i < len(L):
if val < L[i]:
val = L[i]
i = i + 1
# loop invariant: va... |
import nltk
from nltk.classify.scikitlearn import SklearnClassifier
from nltk.corpus.reader.sentiwordnet
import pickle
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.svm import SVC, LinearSVC, NuSVC
from nltk.classify imp... |
#!/usr/bin/env python
from datetime import datetime
from sqlalchemy import or_
from app import app, SqlDB as db
from app.helpers.hashhelper import HashHelper
from app.models import Users
class AuthHelper():
tag = ""
messages = ""
errors = ""
def __init__(self):
return None
def login_us... |
from andrimne.common import run_shell_command
import andrimne.config as config
def run():
version = config.read('version')
prefix = config.read('module_prefix')
modules = config.read_or_default('code_modules', [])
for module in modules:
filename = u'{0}{1}/target/{0}{1}-{2}.war'.format(prefix... |
from libra.key_factory import new_sha3_256
import canoser
LIBRA_HASH_SUFFIX = b"@@$$LIBRA$$@@";
class HashValue(canoser.DelegateT):
LENGTH = 32
LENGTH_IN_BITS = LENGTH * 8
LENGTH_IN_NIBBLES = LENGTH * 2
delegate_type = [canoser.Uint8, LENGTH]
def uint8_to_bits(uint8):
return format(ui... |
#!/usr/bin/env python
import os
import sys
import socket
from deptx.secrets import PRODUCTION_HOSTNAME
try:
HOSTNAME = socket.gethostname()
except:
HOSTNAME = 'exception'
#print HOSTNAME
if __name__ == "__main__":
if HOSTNAME == PRODUCTION_HOSTNAME:
#print 'production'
os.environ.setdefau... |
#-*- coding:utf-8 -*-
'''
要点:
1.数组size为0时返回4个None
2.var的值为b2/(n-1)
3.数组size为1时var=None,skew=0.0,kurt=-3
4.不要忘了round
'''
class Solution():
def describe(self, a):
sum=0.0
n=len(a)
if n==0:
return [None,None,None,None]
else:
for t1 in a:
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: Chuan
def main():
index=0
amount=0
lst=['白菜','萝卜','西红柿','甲鱼','龙虾','生姜','白芍','西柚','牛肉','水饺']
lst.append('莴笋')
lst.append('青菜')
lst.append('鱼')
lst2=lst[4:9]
print '老妈来到菜市场 '
for index,lst_item in enumerate(lst2):
if index%2==0:
amount=ind... |
from ED6ScenarioHelper import *
def main():
# 蔡斯
CreateScenaFile(
FileName = 'C3514 ._SN',
MapName = 'Zeiss',
Location = 'C3514.x',
MapIndex = 1,
MapDefaultBGM = "ed60033",
Flags = 0,
En... |
import pygame
from pygame.locals import *
from math import *
class Robot(pygame.sprite.Sprite):
def __init__(self, isYellow, id):
self.path = "sprites/azul/"
self.name = "azul"+str(id+1)
if(isYellow):
self.path = "sprites/amarelo/"
self.name = "amarelo"+str(id+1)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import time
from pkg.acfun import AcFun
def start_recorder(room, path):
while True:
session = requests.session()
recorder = AcFun(session, room, path)
if not recorder.try_record():
time.sleep(5 * 60) # 5分钟执行一次
i... |
#!/usr/bin/env python
# ZBWarDrive
# rmspeers 2010-13
# ZigBee/802.15.4 WarDriving Platform
from time import sleep
from usb import USBError
from killerbee import KillerBee, kbutils
from db import ZBScanDB
from scanning import doScan
# GPS Poller
def gpsdPoller(currentGPS):
'''
@type currentGPS multiprocessi... |
def proximate_sort(A, k):
'''
Return an array containing the elements of
input tuple A appearing in sorted order.
Input: k | an integer < len(A)
A | a k-proximate tuple
'''
B = list(A)
Q = []
result = []
def insert(Q, v):
Q.append(v)
min_heapify_up(Q, le... |
import json
import boto3
import datetime
import requests
import time
# Change before demo #
es_url = 'https://search-photos-bnrbmus63teifn3tn5obq24pjq.us-east-1.es.amazonaws.com'
def lambda_handler(event, context):
rekognition = boto3.client('rekognition')
s3 = boto3.client('s3')
for rec in event['R... |
from user import User
user_kjell = User("Kjell", "Vos", "DarkRanger99", "12-12-2012")
user_loser = User("Lo", "ser", "IAmLoser", '69-69-6969')
user_kjell.describe_user()
user_kjell.greet_user()
user_loser.describe_user()
user_loser.greet_user() |
from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse, request
from .models import (RfqCustomerHeader, RfqCustomerDetail,
QuotationHeaderCustomer, QuotationDetailCustomer,
PoHeaderCustomer, PoDetailCustomer,
DcHeaderC... |
from gen.builder import Builder
from gen.writer import Writer
b = Builder("./config.yml")
b.clearBuildDirectory()
b.copyStaticAssets()
b.processPosts()
w = Writer("./config.yml", b.graph)
|
import json
import logging
import threading
from configparser import ConfigParser
from queue import Queue
from socket import socket, AF_INET, SOCK_STREAM
class TCPComm(object):
def __init__(self):
self.logger = logging.getLogger('COMM')
self.logger.info("[+] Initializing Communication")
... |
# -*- coding: utf-8 -*-
import nysol._nysolshell_core as n_core
from nysol.mcmd.nysollib.core import NysolMOD_CORE
from nysol.mcmd.nysollib import nysolutil as nutil
class Nysol_List2Csv(NysolMOD_CORE):
_kwd = [["i","o","header"],[]]
_inkwd = ["i"]
_outkwd = ["o"]
def __init__(self,*args, **kw_args) :
if le... |
import numpy as np
from pysat.solvers import Glucose4
from itertools import product
ids = ['207829581', '322277179']
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
def get_directions(i, j):
ret = []
for direction in directions:
x = i + direction[0]
y = j + direction[1]
ret.append((x,... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-11-14 08:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nova', '0036_auto_20171111_0032'),
]
operations = [
migrations.AddField(
... |
# coding:utf-8
from publicMethods import *
import numpy as np
import copy
def loadCarCount():
conn = pymysql.connect(host='47.99.116.136',user='root',passwd='3H1passwd',port=3306,db='car_test',charset='utf8')
cursor=conn.cursor()
sql_sentence='select car_id,num from car_market'
cursor.execute(sql_sente... |
"""
EEGAnalysis module
author: Yizhan Miao
email: yzmiao@protonmail.com
last update: Oct 15 2018
"""
from .container import create_epoch_bymarker, create_1d_epoch_bymarker
from .decomposition import *
from .io import *
from .datamanager import DataManager
from .electrodes import Electrodes
from .behaviors import... |
from bs4 import BeautifulSoup
import requests
http = requests.get("http://www.tatasky.com/wps/portal/TataSky/channels/findyourchannel")
http_doc = http.text
open("tatasky_channels.html", "w").write(http.text)
http_doc = open("tatasky_channels.html", "r").read()
soup = BeautifulSoup(http_doc, "html.parser")
channels ... |
#!/usr/bin/env python3
from setuptools import setup
NAME = 'komodo-python3-dbgp'
setup(
name=NAME,
version='11.0.0',
description='The ActiveState Komodo DBGP server',
author="Shane Caraveo, Trent Mick",
author_email="komodo-feedback@ActiveState.com",
maintainer='Kevin Velghe',
maintainer_... |
from PIL import Image
from io import BytesIO
import numpy as np
import base64
def base64_to_image(encoding):
content = encoding.split(';')[1]
image_encoded = content.split(',')[1]
return Image.open(BytesIO(base64.b64decode(image_encoded)))
def array_to_base64(image_array):
with BytesIO() as output_b... |
"""Tests alternate OBOReader."""
import sys
import timeit
import datetime
# Test local version of goatools
sys.path.insert(0, '..')
from goatools.obo_parser import GODag
#################################################################
# Sub-routines to tests
#########################################################... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: Guoshushu
# Day2 - 为了大家能够做好这一次的第一个作业
# 继续深化变量的练习
#
# homework2
def main():
#01.int
apple_number = 5
apple_price = 4.8
pie_number = 6
pie_price = 6.7
#02. * /
apple_total_price = apple_number * apple_price
pie_total_price = pie_n... |
import azure.cognitiveservices.speech as speechsdk
import librosa
import tempfile
class MicrosoftSTT():
def __init__(self, key, region, sample_rate):
self.key = key
self.region = region
self.sample_rate = sample_rate
def speech_recognize_once_from_file(self, audio_path):
spee... |
def read_input():
with open('input-5') as input_file:
return input_file.read().strip()
def annihilate(polymer):
stack = [polymer[0]]
i = 1
while i < len(polymer):
if stack and abs(ord(polymer[i]) - ord(stack[-1])) == 32:
stack.pop()
else:
stack.append(po... |
class Point:
class_attribute = "Should be treated as constant of global config for all classes"
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def zero(cls):
return cls(0, 0)
def draw(self):
print(f"draw ({self.x}, {self.y})")
point = Point(1, 2)
p... |
#!/usr/bin/env python
import argparse
import numpy as np
from fractions import Fraction
from phonopy.structure.atoms import atom_data, symbol_map
from vasp.poscar import Poscar
from primitive_axis import PrimitiveAxis
from .band_path import BandPath
phonopy_conf_order = [
"ATOM_NAME",
"EIGENVECTORS",
"MAS... |
import logging
from argparse import Namespace
from typing import Tuple
import torch
import wandb
from torch_geometric.loader import DataLoader
from data.dataset import TestUnits
from experiments.early_stopping import EarlyStoppingCriterion
from experiments.evaluate import test_evaluation, valid_evaluation
from experi... |
import asyncio
from collections import OrderedDict
from decimal import Decimal
from eth_account import Account
from eth_account.signers.local import LocalAccount
from eth_account.messages import defunct_hash_message
from hexbytes import HexBytes
import logging
import math
import time
from typing import (
Any,
L... |
from wtforms.fields.choices import *
from wtforms.fields.choices import SelectFieldBase as SelectFieldBase
from wtforms.fields.core import Field as Field, Flags as Flags, Label as Label
from wtforms.fields.datetime import *
from wtforms.fields.form import *
from wtforms.fields.list import *
from wtforms.fields.numeric ... |
from docker import Client
from mako.template import Template
import yaml
import os
DOCKER_HOST = os.environ.get('DOCKER_HOST', "unix://var/run/docker.sock")
swarm = Client(base_url=DOCKER_HOST)
config = yaml.load(open('confgen.yml'))
cmdlines_to_run = []
def run(cmdline):
"""Schedule a command line after config ... |
# @Title: 整数拆分 (Integer Break)
# @Author: 2464512446@qq.com
# @Date: 2020-05-07 17:42:17
# @Runtime: 44 ms
# @Memory: 13.4 MB
class Solution:
def integerBreak(self, n: int) -> int:
if n<2:
return 0
if n == 2:
return 1
if n == 3:
return 2
res = [0... |
# def merge(left, right, a):
# i = 0
# j = 0
# k = 0
# while i < len(left) and j < len(right):
# if left[i] > right[j]:
# a[k] = right[j]
# k += 1
# j += 1
# else:
# a[k] = left[i]
# k += 1
# i += 1
# while i < ... |
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
from distutils.core import setup
setup(
name='autokeras',
packages=['autokeras'], # this must be the same as the name above
install_requires=['pytest', 'numpy', 'keras', 'scikit-learn', 'tensorflow', 'scipy'],
version='0.1.1',
description='Automated Machine Learning with Keras',
author='Haifen... |
#!/usr/local/bin/python3
import i3ipc
i3 = i3ipc.Connection()
nodes = []
def process_node(node):
global nodes
nodes.append(node)
for sel_node in node.nodes:
process_node(sel_node)
process_node(i3.get_tree())
wine_nodes = [x for x in nodes if x.window_class = "Thunderbird"]
wine_nodes[0].com... |
# coding:utf-8
import torch
import torch.utils.data as Data
import torchvision
import torchvision.transforms as transforms
from utils import datasets
def get_trainloader_sample():
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
)
... |
from python_algorithm.Graph.GraphABC import GraphABC
from typing import List, Union, Dict, Optional, Iterator, Tuple, Any
from copy import copy, deepcopy
def out_edge(matrix_row: List[int],
unconn: Union[int, float] = 0,
nodes_map: Dict[int, int] = None):
edge_list = []
for i in node... |
from multiprocessing import Process, Pipe
from os import getpid
from datetime import datetime
class Proc():
def __init__(self, name, id_):
self.name = name
self.id = id_
def __call__(self, f, *args, **kwargs):
f(self, *args, **kwargs)
def local_time(self, counter):
retur... |
from django import template
from django.conf import settings
from django.utils.safestring import mark_safe
register = template.Library()
"""
{% load ga %}
{% ga %}
"""
@register.simple_tag
def google_analytics():
GA_ID = getattr(settings,"GA_ID")
html = """
<!-- Google Analytics -->
<script async src="http... |
from bs4 import BeautifulSoup
from share.transform.chain.links import AbstractLink
from share.transform.chain import ChainTransformer
class SoupXMLDict:
def __init__(self, data=None, soup=None):
self.soup = soup or BeautifulSoup(data, 'lxml').html
def __getitem__(self, key):
if key[0] == '@'... |
import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt
import pickle
import math
import cv2
import random
import torch
import torch.utils.data
from torch import nn, optim
from torch.nn import functional as F
from torchvision import datasets, transforms
from torchvision.utils import save_image
fr... |
import bpy
import bmesh
def flatten(context, axis):
obj = context.active_object
if obj.mode == 'EDIT':
bm = bmesh.from_edit_mesh(obj.data)
verts = [v for v in bm.verts if v.select]
min_y = min(map(lambda y : y.co[axis], verts))
max_y = max(map(lambda y : y.co[axis], ver... |
import datetime
from airflow import models
from airflow.operators.bash_operator import BashOperator
default_dag_args = {
# https://airflow.apache.org/faq.html#what-s-the-deal-with-start-date
'start_date': datetime.datetime(2019, 4, 1)
}
raw_dataset = 'econ_raw' # dataset with raw tables
crypto_dat... |
from django.shortcuts import render, redirect
"""
separating dashboard views
"""
def dashboard(request):
current_component = request.GET.get('c', '')
studentConfig = {
'title': 'Student Dashboard',
'current_component': current_component,
'dashboard': {
'title': 'Team Util... |
from alphabet import *
import numpy as np
import sys
class interesting_base:
def __init__(self, id, reference, correct_value = None):
self.id = id
self.reference_value = reference[id]
if correct_value == None:
self.real_value = self.reference_value
else:
self.real_value = correct_value
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# this script is the main entrance to the
# backend code.
#
# @author Yuan JIN
# @contact chengdujin@gmail.com
# @since 2012.03.22
# @latest 2012.03.22
#
# reload the script encoding
import sys
reload(sys)
sys.setdefaultencoding('UTF-8')
def get():
'''1. get the se... |
import time
from os import system
import os
import datetime
import jishaku
from keep_alive import keep_alive
system('pip install pynacl')
system('python3 -m pip install -U "discord.py[voice]"')
system('pip install pygicord')
from discord.ext import commands
import traceback, sys
import __main__
import discord, asyncio... |
from flask_restful import Resource
from flask import request
from models.users import FoodieUser
from api.schemas.user import NewUserSchema
from api.utils import validates_post_schema
from api.schemas.deliveries import DeliveryStatusSchema
from models.deliveries import DeliveryStatus
from api.utils.auth import requires... |
#Implement k stacks in one array
class KStacks():
def __init__(self , k , n):
self.top = [-1] * n
#self.next = [0] * n
self.next = [x + 1 for x in range(n - 1)]
self.next.append(-1)
print(self.next)
self.arr ... |
import os
import time
import torch
import argparse
import foolbox
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib
from torchvision import transforms
from torchvision.datasets import MNIST
from torch.utils.data import DataLoader
from collections import defau... |
from Configs import DADOS_EMAIL, DADOS_DB
from db.createConnection import createConnection
from db.createDatabase import createDatabase
from db.createTable import createTable
from db.insertData import insertData
from mail.message import createMessage
from mail.send import sendEmail
import sys
import csv
import json
i... |
# http://www.bmfbovespa.com.br/pt_br/servicos/market-data/historico/mercado-a-vista/cotacoes-historicas/
import pandas
import datetime, shelve
import collections
import bovespa
import numpy as np
from sklearn.externals import joblib
from sklearn.preprocessing import Normalizer
def ReadData(filePath):
## This fu... |
# python 2.7.3
import sys
import math
k = input()
data = sys.stdin.readline().split()
for i in range(len(data)):
data[i] = int(data[i])
data.sort()
cnt = 0
for pos in range((k + 1) / 2):
cnt += (data[pos] + 1) / 2
print cnt
|
from mycroft import MycroftSkill, intent_file_handler
class TestEntity(MycroftSkill):
def __init__(self):
MycroftSkill.__init__(self)
@intent_file_handler('entity.test.intent')
def handle_entity_test(self, message):
code = message.data.get('code')
self.speak_dialog('entity.test',... |
import numpy as np
from kaggle_environments import make
env = make("connectx", debug=True)
print(list(env.agents))
|
from Pencil import Pencil
import pygame
from Timer import Timer
from Vector2 import Vector2
import matplotlib.pyplot as plt
class World:
def __init__(self, world_bg, WIDTH_HEIGHT, image_class, WHOLE_MAP_SIZE):
self.world_bg = world_bg
self.entity_group = {}
self.entity_id = 0
self... |
# encoding: utf-8
from wsgiref.simple_server import make_server
import datetime
import csv
def count_visitors():
"""Подсчитывает общее количество просмотров страницы"""
with open("/home/arello/Projects/Python/sparta/mission_19/visitors.txt", "r") as f:
counter = int(f.readline())
with open("/home... |
import sys
class Metrics:
def __init__(self, verbose=False):
self.verbose = verbose
self.number_of_backtracks = 0
self.number_of_flips = 0
self.number_of_var_picks = 0
self.simplifications = 0
def simplify(self, modifications):
self.simplifications += modificat... |
def prime_factors(n):
if n in [2, 3, 5, 7, 11, 13, 17, 19, 23, 31]:
return [n]
prime_fac = []
d = 2
while d * d <= n:
while (n % d) == 0:
prime_fac.append(d) # supposing you want multiple factors repeated
n //= d
d += 1
if n > 1:
prime_fac.app... |
import sys, string, math
n1 = int(input())
L1 = list(map(int,input().split()))
L3 = []
for i in range(n1) :
if L1[i] == i :
L3.append(i)
L = sorted(L3)
if len(L) == 0 :
print(-1)
else :
print(*L)
|
#!/usr/bin/env python3
import elasticsearch
import pymongo
import connector_security as sec
es = elasticsearch.Elasticsearch(sec.ELASTICSEARCH_HOST)
mongo = pymongo.MongoClient(host=sec.MONGO_URI, tz_aware=True)
mongo_coll = mongo[sec.MONGO_DATABASE][sec.MONGO_COLLECTION]
def extract_mongo_id(document):
return ... |
# Pencil module
# Code designed by: Mohammed Nurul Hoque (andrewID: mnurulho)
#
# 15-112: Principles of Programming and Computer Science at Carnegie Mellon University in Qatar
# Term Project
#
# File created on: Sunday 13th of November 2016, 7:30 PM
# Modification History
# Start: End:
# 13/11/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.