content stringlengths 5 1.05M |
|---|
"""
Stores customer, organization, and order information.
"""
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext, ugettext_lazy as _
from l10n.models import Country
from satchmo_store.contact import CUSTOMER_ID
import datetime
import logging
log = log... |
import unittest
from models import articles
Articles = articles.Articles
class NewsTest(unittest.TestCase):
def setUp(self):
self.new_source = Article('self','associated_press','Associated Press','Cant crush this: Beetle armor gives clues to tougher planes','http://apnnews.com','https://storage.googleapi... |
import numpy as np
# read data
with open('input.txt') as f:
data = [list(line.rstrip()) for line in f]
transposed = np.array(data).T.tolist()
# convert to numeric
numeric = [[ int(digit) for digit in l] for l in transposed ]
# find most common bits
common = [round(sum(x)/len(x)) for x in numeric]
gamma_string ... |
import pdb
import unittest
from reacher_env import ReacherEnvironment
from model import GaussianActorCritic
from agent_ppo import Agent
import torch
class TestAgentPPO(unittest.TestCase):
def setUp(self):
self.env = ReacherEnvironment()
self.device = torch.device('cuda:0' if torch.cuda.is_availabl... |
# _*_ coding:utf-8 _*_
"""
封装请求数据的
"""
class Request(object):
#2.1.2-2: 支持callback和meta参数
# 3.3.1-1: 能够支持重复请求的配置, 不过滤
def __init__(self, url, method="GET", headers={}, params={}, data={}, cookies={}, callback=None, meta={}, dont_filter=False):
self.url = url
self.method = method
s... |
#!/usr/bin/python3
from fbtor.FBoolectorTypes import FPType, RMode, WIDTH
from fbtor.FBoolector import FBoolector
from pyboolector import BTOR_OPT_MODEL_GEN
if __name__ == "__main__":
fptype = FPType.double
rmode = RMode.to_zero
# Try to solve a simple quadratic equation which is 0 at the following p... |
#!/usr/bin/env python3
from distutils.core import setup
from os.path import dirname, join
VERSION = "0.0.1"
install_requires = [
"aiohttp_jinja2",
"ipgetter",
"requests",
"irc3",
"markovify",
"discord.py",
"discord.py[voice]",
"sqlalchemy",
"youtube_dl"
]
setup(
name='roboto',... |
import torch.nn as nn
from state_processing_module import StateProcessingModule, ImageProcessingModule, InstructionProcessingModule, MultimodalFusionModule
from state_processing_module import ImageProcessingModuleAlt
from policy_module import PolicyModule, PolicyModuleAlt
class Solver(nn.Module):
def __init__(se... |
"""
Copyright 2015 Creare
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 applicable law or agreed to in writing... |
from viscum.plugin import (Module,
ModuleArgument,
ModuleCapabilities)
from viscum.exception import HookNotAvailableError
from viscum.hook import ModuleManagerHookActions as MMHookAct
from viscum.plugin.util import load_plugin_component
import re
import os.path
PER... |
# /usr/bin python
import os
from setuptools import setup
VERSION = "0.0.1"
PROJECT_NAME = "SoftwareHelper"
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
README = os.path.join(BASE_DIR, 'README.rst')
with open(README, 'r') as f:
long_description = f.read()
setup(
name='ProjectHelper',
version=V... |
from telegram import Update
from telegram.ext import CallbackContext
from telegram.ext import CommandHandler
from helpers.game import end_game
from helpers.wrappers import admin_only
@admin_only
def callback(update: Update, context: CallbackContext):
try:
end_game(context)
update.effective_messag... |
import subprocess as sp
from urllib.request import urlretrieve
import os
import platform
from .common import run
def apt_install(packages, recommends=False):
os.environ["DEBIAN_FRONTEND"] = "noninteractive"
sp.run(["sudo", "apt-get", "update"], check=True)
cmd = ["sudo", "apt-get", "install", "--yes"]
... |
#!/usr/bin/env python3
import os
import subprocess
import argparse
# The path to output generated files to.
GEN_PATH = "files/generated"
# The name of the boot image generated by bootgen
MESH_BIN_NAME = "MES.bin"
def build_system(bif):
"""Build the system according to the bif file using bootgen. Bootgen is a
... |
from pathlib import Path
BASE_DIR = Path(__file__).parent
LICENSE_DIR = BASE_DIR.joinpath("licenses")
LICENSE_FILE = Path(".").joinpath("LICENSE")
from . import cli
from . import models
from . import utils
|
#!/usr/bin/python
""" Autor: Jose Luis Osorio Quintero
Universidad Icesi 2017
Este script tiene como funcion la obtencion del trafico de red
de un conjunto de urls, tambien se obtiene informacion de la
capa de aplicacion """
import subprocess
import re
def examinate_with_thug(ruta):
""" Examina un... |
from copy import deepcopy
import re
import warnings
from lxml.etree import Element
from lxml import etree
from zipfile import ZipFile, ZIP_DEFLATED
from random import randint
from PIL import Image
import shlex
import mimetypes
import os.path
NAMESPACES = {
'w': 'http://schemas.openxmlformats.org/wordprocessingml/... |
from __future__ import absolute_import, print_function, division
import pytest
from coffee.base import *
from coffee.visitors import *
from collections import Counter
from functools import reduce
@pytest.mark.parametrize("key",
[lambda x: x.symbol,
lambda x: x,
... |
def convert_iso_to_json(dateString):
tempDateObject = dateString.split("-")
return {
"year": tempDateObject[0],
"month": tempDateObject[1],
"day": tempDateObject[2]
}
def convert_json_to_iso(json):
return "{0}-{1}-{2}".format(int(json['year']), int(json['month']), int(json['day'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from argparse import ArgumentParser
from functools import partial
from argparsetools.types import positive, odd
def parse_arguments(argv=None):
parser = ArgumentParser()
# mandatory:
# parser.add_argument("positional")
# optional:
parser.add_argument... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# test script for felapps package
# Tong Zhang, 2015-10-03
#
import felapps
import sys
def testApp(appname=None):
if appname == 'imageviewer':
felapps.imageviewer.run(maximize=True, logon=False, debug=True)
elif appname == 'felformula':
felapps.... |
# Copyright 2021 Sony Group Corporation.
#
# 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 applicable law or ag... |
import pandas as pd
import numpy as np
import seaborn as sns
def connecting_unprocessed(excel_file):
'''Taking excel spreadsheet and converting to .csv format'''
#Reading each sheet from the excel file
df1 = pd.read_excel(excel_file, sheet_name='PUF_2006', header=1)
df2 = pd.read_excel(excel_file, shee... |
from fastapi import FastAPI, File, UploadFile
from classifier.predictor import ImagePredictor
from app.settings import API_SETTINGS
# A: init API
app = FastAPI(
title=API_SETTINGS["title"],
description=API_SETTINGS["description"],
version=API_SETTINGS["version"],
openapi_tags=API_SETTINGS["openapi_tags... |
__author__ = "Prahlad Yeri"
__email__ = "prahladyeri@yahoo.com"
__copyright__ = "(c) 2019 Prahlad Yeri"
__license__ = "MIT"
__version__ = "0.0.1"
__title__ = 'pyinstinct'
__description__ = 'Number guessing game to test your instinct power'
|
import argparse
import logging
from pathlib import Path
from savona.binary.utils import html_arguments, parse_html_args
from savona.exporter.docx_ import DocxExporter
from savona.exporter.html import HTMLExporter
#from savona.exporter.LaTeX import LaTeXEporter
from savona.utils import merge
logging.basicConfig(level=... |
from IPython.display import HTML, display, clear_output
_canvas = """
<script type="text/javascript" src="./js/canvas.js"></script>
<div>
<canvas id="{0}" width="{1}" height="{2}" style="background:rgba(158, 167, 184, 0.2);" onclick='click_callback(this, event, "{3}")'></canvas>
</div>
<script> var {0}_canvas_object ... |
import csv
import nltk
import json
from unicodedata import normalize
nltk.download('punkt')
class CorretorNLP:
def __init__(self, text='') -> None:
self.text_tokenize = nltk.tokenize.word_tokenize(text)
self.listar_palavras_text = [i.lower() for i in self.text_tokenize if i.isalpha()]
sel... |
nome = str(input('Informe o seu nome : ')).strip()
print('A letra (a) tem no total de',nome.lower().count('a'))
print('A primeira letra (a) é',nome.lower().find('a')+1)
print('A ultima letra (a) é',nome.lower().rfind('a')) |
import numpy as np
import pandas as pd
from processInput import processInput
def handCodedOptimum_v4 ( ):
fileName = 'gifts.csv'
giftList, giftListSummary = processInput( fileName )
packedBags = []
for i in np.arange(1000):
print i
currentBag = []
i... |
# UNFINISHED, not referenced by any other files
# Script containing functions for plotting demo results
# Intended to have everything plotted in OpenCV
# For developing the GUI, it may be easier to have plotting occur in the GUI script?
#import cv2
import numpy as np
# Global dictionary containing class number : nam... |
#!/usr/bin/env python
# Filename: split_sub_images_test.py
"""
# run "pytest split_sub_images_test.py " or "pytest " for test, add " -s for allowing print out"
# "pytest can automatically search *_test.py files "
authors: Huang Lingcao
email:huanglingcao@gmail.com
add time: 13 February, 2021
"""
import os, sys
code_... |
import sys
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWidgets import QInputDialog
from board import Tank_chess
from rule import Rules
TANKS_DESCRIPTION = {'1': [5, (1, 0, 0), 1, 3, 2], '2': [4, (2, 1, 0), 2, 3, 2], '3': [3,... |
from setuptools import setup
from os import path
__version__ = 1.0
setup(name='pyBJD',
version=1.0,
description='A Very Basic JD to BJD conversion API',
url='https://github.com/tboudreaux/pyBJD',
author='Thomas Boudreaux',
author_email='thomas@boudreauxmail.com',
license='MIT',
classifiers=[
... |
from __future__ import absolute_import
import unittest
from anchoco import api
from anchoco.objects import Directive, Module
SRC = '''---
- name
tasks:
- shel
- name: comm
action: comm
- name: "{{ sample play }}"
host
dummy
'''
SRC2 = '''---
- block:
-
'''
SRC3 = '''---
- action: comm
'''
S... |
import peewee
db = peewee.SqliteDatabase('app.db')
db.connect()
class BaseModel(peewee.Model):
class Meta:
database = db
class User(BaseModel):
chat_id = peewee.IntegerField(primary_key=True)
name = peewee.CharField()
class Activity(BaseModel):
user = peewee.ForeignKeyField(model=User)
... |
from behave import *
from selenium.common.exceptions import NoSuchElementException
import re
import time
def click_button(context, text):
buttons = context.browser.find_elements_by_class_name('btn-primary')
for button in buttons:
if button.is_enabled() and button.is_displayed():
if button.... |
"""Engine parser."""
import numpy as np
import pandas as pd
from unify_idents.engine_parsers.base_parser import IdentBaseParser
class Omssa_Parser(IdentBaseParser):
"""File parser for OMSSA."""
def __init__(self, *args, **kwargs):
"""Initialize parser.
Reads in data file and provides mappi... |
input = "((((()(()(((((((()))(((()((((()())(())()(((()((((((()((()(()(((()(()((())))()((()()())))))))))()((((((())((()))(((((()(((((((((()()))((()(())()((())((()(()))((()))()))()(((((()(((()()))()())((()((((())()())()((((())()(()(()(((()(())(()(())(((((((())()()(((())(()(()(()(())))(()((((())((()))(((()(()()(((((()()((... |
from django.db import models
from wagtail.core.models import Page
from wagtail.core.fields import RichTextField
from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel
from wagtail.images.edit_handlers import ImageChooserPanel
class BlogPage(Page):
custom_title = models.CharField(
max_length=... |
import math
import os
import sys
import timeit
def get_files(directory):
return sorted(os.path.join(directory, f) for f in os.listdir(directory) if f.endswith('.gcode'))
def stats(file_path):
tic = timeit.default_timer()
with open(file_path, 'r') as fh:
last = None
total_x = 0
to... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 applicable law or agreed ... |
from flask_basicauth import BasicAuth
from flask_admin import Admin
from flask_admin.contrib.geoa import ModelView
from containers.models import Container, Term
from .exceptions import AuthException
def register_admin(app):
basic_auth = BasicAuth(app)
class MyView(ModelView):
can_delete = False
... |
"""Project: Eskapade - A python-based package for data analysis.
Class: ResampleEvaluation
Created: 2018-07-18
Description:
Algorithm to evaluate the statistical simularity between 2 data sets using a chiˆ2 test.
Authors:
KPMG Advanced Analytics & Big Data team, Amstelveen, The Netherlands
Redistribution a... |
from time import sleep
from itertools import chain
from solver import solve
def get_nums_list(task_elem):
tgs = task_elem.find_elements_by_class_name("task-group")
nums = []
for tg in tgs:
tcs = tg.find_elements_by_class_name("task-cell")
num_strings = [tc.text for tc in tcs if tc.text... |
def s(handle: int) -> int:
return handle + 2_00
|
from .standard import StandardMetric
from .utils import matirxscore2pairscore
__all__ = ['matirxscore2pairscore', 'StandardMetric']
|
# MIT License
#
# Copyright (c) 2020 Brett Graves
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge,... |
from __future__ import division
import numpy as np
import os
import cv2
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--dataset_dir", type=str, help="path to kitti scene flow multiview dataset")
parser.add_argument("--calib_dir", type=str, help="path to data_scene_flow_calib")
parser.add_ar... |
from discord.ext import commands
import asyncio
import traceback
import discord
import inspect
import textwrap
from contextlib import redirect_stdout
import io
# to expose to the eval command
import datetime
from collections import Counter
class Admin(commands.Cog):
"""Admin-only commands that make the bot dynami... |
# Renames functions in an IDA database to match the function names
# in the decompiled source code.
import csv
import idc
import os
from util import config
csv_path = config.get_functions_csv_path()
with open(csv_path, "r") as f:
reader = csv.reader(f)
# Skip headers
next(reader)
for fn in reader:
... |
my_friend = "rudolf"
friend = input("Enter your name: ")
if friend == my_friend:
print("hi {}, whats up?".format(my_friend))
elif friend == "":
print("you should enter the name and run again")
else:
print("hi {}, nice to meet you".format(friend))
# if statement on multi objects
friends = ["ralph", "dominic", "... |
'''
7. Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
|
| Have you thought about this?
| Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
|
| If ... |
#!/usr/bin/env python
# coding: utf-8
# Download data from [kaggle](https://www.kaggle.com/shivinder/googlestockpricing/data).
# In[2]:
import pandas as pd
df = pd.read_csv("../datasets/Google.csv")
df.index = pd.DatetimeIndex(df['Date'].values)
close = df["Close"]
# In[3]:
df.head()
# In[4]:
import numpy ... |
import grpc
from concurrent import futures
import time
import json
import proto.faiss_pb2_grpc as proto_server
import proto.faiss_pb2 as proto
from hfaiss.index import Faiss
faiss_ = Faiss()
from hannoy.index import Annoy
annoy_ = Annoy()
class FaissServicer (proto_server.FaissServiceServicer):
def initFaiss (s... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# 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.apach... |
import os
import time
import ujson as json
import requests
from dotenv import load_dotenv
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from discord.ext import commands
from dhooks import Webhook, Embed, File
from utils.global_utils import news_exists, matches_exists
load_dotenv()
patches_webhook = os.ge... |
# =============================================================================
# Here an example of an multilinear (Lasso) regression model is given that is
# based on the scikit-learn python package.
# =============================================================================
# ===================================... |
"""
... module:: qsdn
:platform: Unix, Windows
:synopsis: This module allows for parsing, validation and production of numeric literals, written with thousand separators through out the number. Often underlying system libraries for working with locales neglect to put thousand separators (commas) after the decimal p... |
# Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
#!/usr/bin/python3
#https://pythonprogramming.net/pygame-crashing-objects/?completed=/drawing-objects-pygame-tutorial/
#https://www.cs.ucsb.edu/~pconrad/cs5nm/topics/pygame/drawing/
import os
import pygame
from pygame import *
import pyganim
ICON_DIR = os.path.dirname(__file__) # Полный путь к каталогу с файлами
WIN_... |
import json
import graphene
from graphene import relay
from flask_security import current_user
from sqlalchemy.exc import IntegrityError
from contactista.models import db, Tag
from contactista.schema.types import UserError
from contactista.schema.types import Tag as TagType
from contactista.serializers import TagSerial... |
#!/usr//bin/env python
"""
Onsite script for creating a flat-field calibration file file to be run as a command line:
--> onsite_create_calibration_file
"""
import argparse
import os
import sys
from pathlib import Path
from lstchain.io.data_management import query_yes_no
import lstchain.visualization.plot_calib ... |
"""
Do not run this script in Windows, it will not work due to use of signal
"""
import os
import pickle
import re
import signal
class TimeoutException(Exception): # Custom exception class
pass
def timeout_handler(signum, frame): # Custom signal handler
raise TimeoutException
# Change the behavior of S... |
import torch
import torch.nn as nn
from torch.nn import init
import functools
class EncoderDecoderGenerator(nn.Module):
"""Create a EncoderDecoder-based generator"""
def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False):
"""Construct a Unet generator
... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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 applicable law or agreed to... |
# Synchronization components which can be plugged into a BeatClock
import math
import time
import datetime
from zope.interface import Interface, implements
class ISyncClock(Interface):
"""
Canonical source of tick/time information which can be plugged into a
BeatClock.
"""
def lastTick():
... |
import csv
import glob
import os
import pickle
import re
import sys
import zlib
import h5py
import numpy as np
REGEX = re.compile(".+(CRC\d+)_(\w+)_(\d+).singleC.cpg")
SUFFIX = "*.singleC.cpg.txt"
chr16 = []
chr_dict = {}
chr_np = {}
def read_file(fin):
with open(fin) as f:
csv_file = csv.DictReader(f,... |
#from distutils.core import setup
from setuptools import setup, find_packages
import os
# read the contents of your README file
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
long_des... |
import cloudinitd
from cloudinitd.exceptions import ServiceException, APIUsageException
import cloudinitd.nosetests
from cloudinitd.user_api import CloudInitD
import tempfile
import logging
import unittest
import os
class ServiceTests(unittest.TestCase):
def setUp(self):
self.plan_basedir = cloudinitd.... |
from pymongo import MongoClient
import pymongo
from collections import OrderedDict
from lxml import etree, html
import requests
import urllib2
import threading
NUM_OF_STUDENTS = 150
RESPONSE_COUNT = 0
NUM_OF_COLLEGES = 172
#BRANCH_CODES = ['bt', 'cv', 'ee', 'ec', 'te', 'is', 'cs', 'me']
BRANCH_CODES = ['is']
BASE... |
import discord
from discord.ext import commands
class Embeds(commands.Cog):
'''
A cog related to embedded messages.
'''
def __init__(self, client):
self.client = client
# Events
@commands.Cog.listener()
async def on_ready(self):
print('Embeds cog is ready.')
# Sends ... |
#!/usr/bin/env python
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
setup(name='epNamer',
version='0.11.5',
description='Names TV episode files in... |
import time
import pyautogui
def press(key, delay=0.1):
time.sleep(delay)
pyautogui.press(key)
def hold(key, duration=0.01, delay=0.1):
time.sleep(delay)
pyautogui.keyDown(key)
time.sleep(duration)
pyautogui.keyUp(key)
|
class Graph:
def __init__(self, Board):
Board[Board == 9] = 0
Board[Board == 7] = 0
self.edges = {}
for i in range(0, Board.shape[0]):
for j in range(0, Board.shape[1]):
possible_moves = []
if j + 1 < 10 and Board[i][j + 1] == 0:
... |
from PyDictionary import PyDictionary
import pandas as pd
df=pd.read_csv('vocab.csv',encoding='cp1252')
print(df.head())
# #dictionary=PyDictionary()
|
import numpy as np
from q_learn_linear_func_approx import execute
config = {
'MAX_EPISODES': 2500,
# 'MAX_STEPS_PER_EPISODE': 1000,
'LEARNING_RATE': 0.0005,
# 'DISCOUNT_RATE': 0.99,
'EXPLORATION_DECAY': 0.001,
'MIN_EXPLORATION_RATE': 0.01,
'DO_RENDER': True,
# 'SHOW_STATS_PLOT': True,
}
def reward_fun... |
import numpy as np
class PSignature:
# Potential signature of a cluster. It has points in multiple dimensions
# but still needs to be evaluated to confirm a cluster
def __init__(self, bins, assigned_points=[]):
self.bins = bins
self.bin_dict = {}
for _bin in bins:
self.b... |
import torch.nn as nn
from torch.nn.functional import log_softmax
PAD = 0
class Seq2Seq(nn.Module):
"""
Generic Seq2Seq module, with an encoder and a decoder.
"""
def __init__(self, encoder=None, decoder=None, batch_first=False):
"""
Constructor for the Seq2Seq module.
:para... |
import pickle as _pickle
from txamqp.content import Content
class PDU(Content):
pickleProtocol = _pickle.HIGHEST_PROTOCOL
def pickle(self, data):
return _pickle.dumps(data, self.pickleProtocol)
def __init__(self, body="", children=None, properties=None, pickleProtocol=_pickle.HIGHEST_PROTOCOL):... |
"""2017 - Day 8 Part 1: I Heard You Like Registers.
You receive a signal directly from the CPU. Because of your recent assistance
with jump instructions, it would like you to compute the result of a series of
unusual register instructions.
Each instruction consists of several parts: the register to modify, whether to... |
"""
Initializing Approver API's
"""
from .reports import Reports
from .projects import Projects
from .categories import Categories
from ..version import version
role = 'approver'
reports = Reports(version, role)
projects = Projects(version, role)
categories = Categories(version, role)
|
WPOD_NET_PATH = 'models/wpod-net.json'
TEST_IMAGE_PATH = 'photos/'
PROCES_PHOTO_FOLDER = 'process_photos/'
MODELS_PATH = 'models/'
PLOT_IMGS = False |
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
data_dir = "/home/jdw/projects/kaggle/data/city_lines/"
def get_df(fn):
path = os.path.join(data_dir, fn+".csv")
return pd.read_csv(path)
def pointstr2coord(pointstr):
pointstr = pointstr[6:-1]
x, y = pointstr.split(" ... |
from django.contrib import admin
from .models import Product, Cart, user_info
admin.site.register(Product)
admin.site.register(Cart)
# Register your models here.
admin.site.register(user_info)
|
import attr
from datetime import date
from typing import Any, Dict, List, Optional
from . import Agama
from . import FasilitasKesehatan
from . import KondisiPekerjaan
from . import PekerjaanUtama
from . import PendidikanTertinggi
from . import Penghasilan
from . import PenyakitDiderita
from . import StatusPernikahan
... |
from apscheduler.events import EVENT_JOB_ERROR, JobExecutionEvent
from apscheduler.schedulers.base import BaseScheduler
import settings
from hooks import discord_hook
def enable_job_exception_logging(scheduler: BaseScheduler):
def listener(event: JobExecutionEvent):
exception = repr(event.exception)
... |
/home/runner/.cache/pip/pool/a4/a7/2d/e7c1ba34f815dbc9aa2758c69e617c630a10252722061947f394cc0857 |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request
from work.items import ShopItem
import re
from scrapy_splash import SplashRequest
class A1865NevisportSpider(scrapy.Spider):
name = '1865_nevisport'
allowed_domains = ['www.nevisport.com']
start_urls = ['https://www.nevisport.com/']
... |
from datetime import datetime
from typing import Dict, List, Tuple
from elasticsearch_dsl import Document, Date, Integer, Keyword, Text, connections, Binary, Boolean
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk
import random
ELASTIC_USER = 'elastic'
ELASTIC_PASS = 'qNq0dMcBw3Zs1hAFGnT... |
import asyncio,base64,getpass,io,os,sys
import asyncssh
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
def generate_encrypted_key(pw,alg='ssh-ed25519'):
pk = asyncssh.generate_private_key(alg)
salt = ... |
import urllib
import HTMLParser
import django
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.encoding import smart_str, force_unicode
from oembed.core import replace
from oembed.models import StoredOEmbed
register = template.Library()
@register.filter
def unesca... |
import smtplib
from email.message import EmailMessage
def email_without_attachment(
message: str, subject: str, to_list: str, cc_list: str, login: str, password: str
):
"""Send email to given list of recipients. Uses Office 365 Port 587.
:param message: HTML String with Email message contained. See Examp... |
# Copyright (c) 2015 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... |
import pytest
from tclab import TCLabModel, TCLab
from tclab.tclab import AlreadyConnectedError
import os
TRAVIS = "TRAVIS" in os.environ
skip_on_travis = pytest.mark.skipif(TRAVIS,
reason="Can't run this test on Travis")
@pytest.fixture(scope="module",
params=[TC... |
from agent import Agent
from random import random, sample
from time import time
from itertools import combinations
from math import comb
from mission import Mission
class Bayes2(Agent):
'''
Maintains probabilities of all possible worlds.
Calculates the probabilty of each player being a spy from set of ... |
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# @File : RequestHandler.py
# @Created : 2020/11/2 6:10 下午
# @Software : PyCharm
#
# @Author : Liu.Qi
# @Contact : liuqi_0725@aliyun.com
#
# @Desc : 目的?
# ---------------------------------------------... |
# uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: pirates.kraken.Holder
from pandac.PandaModules import *
from direct.directnotify import DirectNotifyGlobal
from pirates.creature.Creatur... |
# Copyright (c) 2015 The Sippet Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'lua',
'type': 'static_library',
'include_dirs': [
'./source',
],
'defines': [
... |
# ---------- PROBLEM : SECRET STRING ----------
# Receive a uppercase string and then hide its meaning by turning it into a string of unicode
# Then translate it from unicode back into its original meaning
# Enter a string to hide in uppercase
# Secret Message : 34567890
# Original Message : HIDE
# Input string to be... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.