content stringlengths 5 1.05M |
|---|
"""
benchmarking et plotting some results for quarto mcts
"""
import time
import statistics
import sys
import os
import pytest
import matplotlib.pyplot as plt
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), "src"))
from logic.quarto_logic import Quarto
from logic.mcts import MCTS
from logic.... |
import logging
import os
import platform
import sys
from collections import OrderedDict
from datetime import datetime
import django
import psutil
from django.conf import settings
from django.urls.exceptions import NoReverseMatch
from rest_framework.response import Response
from rest_framework.reverse import reverse
fr... |
# Copyright 2018 The TensorFlow Authors. 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
class Test(object):
num_of_instance = 0
def __init__(self, name):
self.name = name
self.num_of_instance += 1 #实例对象
if __name__ == '__main__':
print (Test.num_of_instance) # 0
t1 = Test('jack')
print (Test.num_of_instance) # 1
t2 = Test('lucy')
print (t1.nam... |
# Generated by Django 3.2.6 on 2021-09-04 10:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('store', '0007_delete_productdetail'),
]
operations = [
migrations.AddField(
model_name='product',
name='description'... |
METADATA = "metadata"
CNR_LIST = "cnr_list"
|
import json
from typing import Any, Dict, List
import settings
# ---------- Constants ----------
RESOURCES: Dict[str, Dict[str, str]] = {}
# ---------- Functions ----------
def get_resource(resource_key: str, formats: List[Any] = None, language_key: str = 'en') -> str:
if language_key not in RESOURCES.key... |
import torch
import torch.nn as nn
def _nms(heat, kernel=3):
pad = (kernel - 1) // 2
hmax = nn.functional.max_pool2d(
heat, (kernel, kernel), stride=1, padding=pad)
keep = (hmax == heat).float()
return heat * keep
def _sigmoid(x):
y = torch.clamp(x.sigmoid_(), min=1e-4, max=1-1e-4)
retur... |
import paho.mqtt.client as mqtt
import time
import grovepi
import grove_rgb_lcd
from grove_rgb_lcd import *
import statistics
buzzer = 3
button = 4
grovepi.pinMode(button,"INPUT")
tones = {
"B0": 31,
"B1": 62,
"C2": 65,
"CS2": 69,
"D2": 73,
"DS2": 78,
"E2": 82,
"F2": 87,
"FS2": 93,
"G2": 98,
"GS2": 104,
"A2": 110,
"AS... |
class Table:
def __init__(self, dictionary = {}):
self.name = dictionary.get("name")
self.description = dictionary.get("description")
self.fields = []
self.constraints = []
self.indices = []
# Props
self.add = dictionary.get("add", False)
self.edit ... |
# AES Key expansion in python with blocksize of 16
AESBlockSize = 16
def expand(self, input, AES_BLOCKSIZE):
return input + (AES_BLOCKSIZE - len(input) % AES_BLOCKSIZE) * chr(AES_BLOCKSIZE - len(input) % AES_BLOCKSIZE) |
from quart import Quart
from discord.ext import commands
import discord
import asyncio
class Ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.shutdown_event = asyncio.Event()
def _signal_handler(self, *_) -> None:
shutdown_event.set()
@commands.Cog.listener()
... |
import logging
import os
from pprint import pprint
from zipfile import ZipFile
import berlin_hp
import deflex
import pandas as pd
import requests
from oemof.tools import logger
from reegis import config as cfg
from reegis_phd import __file__ as my_regis_file
from reegis_phd import alternative_scenarios as alt
from re... |
from edgar_crawler.items import CompanyItem
import scrapy
def LastNlines(fname, N):
# assert statement check
# a condition
assert N >= 0
# declaring variable
# to implement
# exponential search
pos = N + 1
# list to store
# last N lines
lines = []
... |
class BuildingSiteExportOptions(object):
"""
Building Site Export options.
BuildingSiteExportOptions()
"""
AreaPerPerson = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""Custom value for Area Per Person value.
Get: AreaPerPerson(self: Bui... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
.vtr reader.
@author: CHEN Yongxin
"""
import vtk
import numpy as np
def reader(file, point_in=None, cell_in=None, display=True):
"""
Paraview .vtr file reader.
Parameters
----------
file: string
Name of .vtr file.
point_in: list... |
import os, sys, argparse, multiprocessing, icebridge_common
'''
Run the premet tool on all the files in a directory in parallel.
- This creates the .premet and .spo files.
'''
SOFTWARE_FOLDER = '/u/smcmich1/icebridge/upload_software'
def runCommand(command):
'''Run one of the commands from the file'''
print... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Ivan Andreev <ivandeex@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version'... |
from django.db import models
from django.contrib.auth.models import User
from app.areadeinvestigacion.models import area, GrupoInvestigacion
from django.contrib.auth.models import User
# Create your models here.
RESULTADO_P = (
('Estudiante', 'Estudiante'),
('Asesor', 'Asesor'),
('Directivo', 'Directivo')... |
"""SQLalchemy models for twitoff
$FLASK_APP=twitoff.APP FLASK_ENV=development flask shell
from twitoff.models import DB, User, Tweet
t1=Tweet(text='my first tweet')
t2 =Tweet(text='my second tweet')
u1=User(username='jing')
u1.tweets.append(t1)
u1.tweets.append(t2)
DB.session.add(u1)
DB.session.commit()
"""
from fla... |
import requests
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''Trendnet AC2600 TEW-827DRU - Unauthenticated Admin Password Change''',
"description": '''Trendnet AC2600 TEW-827DRU version 2.08B01 contains an authentication bypass vulnerability. It is possible for a... |
from random import randint
from os import system
def game():
def printHead(L:int):
print(' '*(L-7) + 'Life Game v2.0' + ' '*(L-7) + '\n\n')
print('-'*L*2 + '┐')
printHead(20)
print('1.Random init matrix.')
print('2.custome init matrix(0/1).')
ch,qt,table = -1,['q','Q','quit'... |
"""
File: CreatePools.py
Author: Daniel Stancl
Description: The script which creates a pool available to invest.
utf-8
"""
###########################
### SET HYPERPARAMETERS ###
###########################
data_path = '/mnt/c/Data/UCL/bonds_DATA.yaml'
bond_path = '/mnt/c/Data/UCL/companies_bonds_list_1.csv'
output_p... |
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
from requre.online_replacing import record_requests_for_all_methods
from tests.integration.gitlab.base import GitlabTests
from ogr.exceptions import OperationNotSupported
@record_requests_for_all_methods()
class Forks(GitlabTests):
d... |
import sys, random, time
import threading
from core import settings
def loadingHack(importlib):
chaine = "[*]"+' Start LittleBrother...'
charspec = "$*.X^%_/\\#~!?;"
while importlib.is_alive():
chainehack = ""
for c in chaine:
chainehack += c
r = random.choice(charspec)+random.choice(charspec)+random.ch... |
import json
import os
import sys
import argparse
sys.path.append(os.getcwd())
import torch
import pandas as pd
import numpy as np
from sklearn.metrics import classification_report
from torch import nn
from torch.optim import Adam
from torch.utils.data import DataLoader
from torch.optim.lr_scheduler import Exponential... |
from operator import add, sub, mul, truediv
def calc_type(a, b, res) -> str:
operations: dict = {'addition': add,
'subtraction': sub,
'multiplication': mul,
'division': truediv
}
return ', '.join([k for k, v in ope... |
import os
import pyodbc
import sys
from contextlib import contextmanager
server = os.environ['dbUrl']
database = os.environ['db']
username = os.environ['dbUser']
password = os.environ['dbUserPassword']
driver = '{ODBC Driver 17 for SQL Server}'
connection_str = 'DRIVER=' + driver + ';SERVER=' + server + \
... |
import os
from transliterate import translit, get_available_language_codes
from googletrans import Translator
import pandas as pd
import cyrtranslit
from transformers import AutoModel, BertTokenizerFast,BertModel,AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained('DeepPavlov/rubert-base-cased')
translator=Translat... |
from output.models.nist_data.list_pkg.positive_integer.schema_instance.nistschema_sv_iv_list_positive_integer_max_length_2_xsd.nistschema_sv_iv_list_positive_integer_max_length_2 import NistschemaSvIvListPositiveIntegerMaxLength2
__all__ = [
"NistschemaSvIvListPositiveIntegerMaxLength2",
]
|
"""Types of fees"""
from enum import Enum
class Fee(Enum):
"""
Fee types
"""
EXCHANGE = "exchange"
NETWORK = "network"
|
# -*- coding: utf-8 -*-
from argparse import ArgumentParser
from datetime import datetime
import os
import subprocess
import sys
import logging
import traceback
import shutil
import random
import string
import re
import json
import getpass
# All branch build folders pointed by the following symbolic links must be reta... |
"Things to do when TurboGears is imported."
import os
import errno
import logging
import sys
import time
import atexit
import signal
import newrelic.agent
import pkg_resources
import cherrypy
from cherrypy import _cputil, request, server
from formencode.variabledecode import NestedVariables
from cherrypy._cpwsgi impo... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
import decisionTree
import inspection
import matplotlib.pyplot as plt
import sys
if __name__ == '__main__':
assert len(sys.argv) == 1 + 3
train_file_path = sys.argv[1]
test_file_path = sys.argv[2]
plot_out_path = sys.argv[3]
print(f'{train_file_path = }')
print(f'{test_file_path = }')
pr... |
from datetime import datetime
from json import load
from os.path import exists
from common import checkFolders
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill
from math import floor
checkFolders()
jsonPath = './inputs/translation.json'
outputPath = f'./outputs/exported-xlsx/translation-{f... |
"""
@file
@brief OnnxInferenceNode definition.
"""
import pprint
import numpy
from onnx import onnx_pb as onnx_proto
from .ops import load_op
class OnnxInferenceNode:
"""
A node to execute.
"""
def __init__(self, onnx_node, desc):
"""
@param onnx_node onnx_node
@par... |
import unittest
from copy import deepcopy
from palmnet.core.faustizer import Faustizer
from palmnet.core.layer_replacer_faust import LayerReplacerFaust
from palmnet.core.layer_replacer_palm import LayerReplacerPalm
from palmnet.core.palminizer import Palminizer
from palmnet.core.palminizable import Palminizable
from p... |
#!/usr/bin/env python3
# PYTHON_ARGCOMPLETE_OK
# -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2014-2015 Jérémy Bobbio <lunar@debian.org>
# Copyright © 2017 Chris Lamb <lamby@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modif... |
from __future__ import division
import csv
import numpy
from copy import deepcopy
import argparse
from deep_disfluency.utils.tools import \
convert_from_eval_tags_to_inc_disfluency_tags
def wer(r, h, macro=False):
"""
Calculation of WER with Levenshtein distance.
O(nm) time ans space complexit... |
#!/bin/env python
from gempython.utils.gemlogger import getGEMLogger,printRed,printYellow
import logging
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description="Queries the DB for calibration info for all VFATs on given (shelf,slot,gtx)")
parser.add_argument("shelf",type=i... |
"""
credit: https://hackaday.io/project/171456-diy-hobby-servos-quadruped-robot
"""
import numpy as np
import IK
import Matrices
L = 0.52
W = 0.15
coxa = 0.18
femur = 0.29
tibia = 0.31
def Kinematic_Model(coord, rotation, translation):
oriToFR = np.array([ L/2, -W/2, 0])
oriToFL = np.array([ L/2, W/2, 0])
... |
import os
import json
import pytest
import shutil
# Getting absolute paths, names and regexes
TEST_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(TEST_DIR)
SERVICE_CONFIG_NAME = "service_manifest.yml"
SERVICE_CONFIG_PATH = os.path.join(ROOT_DIR, SERVICE_CONFIG_NAME)
TEMP_SERVICE_CONFIG_PAT... |
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t; python-indent: 4 -*-
"""
A simple multiprocessed plugin that echoes the content received to the parent
"""
from yapsy.IMultiprocessChildPlugin import IMultiprocessChildPlugin
class LegacyMultiprocessPlugin(IMultiprocessChildPlugin):
"""
Only trigger the expec... |
from __future__ import division
import numpy as np
import chainer
import chainer.functions as F
import chainer.links as L
from chainer import ChainList
from chainercv.links.model.ssd import Multibox
from chainercv.links.model.ssd import Normalize
from chainercv.links.model.ssd import SSD
from chainercv.links.model.s... |
from studentBasic.models import studentBasic
from studentBasic.serializers import studentBasicSerializer, ImageSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.parsers import MultiPartParser, FormParser, FileUploadParser... |
# Copyright (c) 2019-2020 Manfred Moitzi
# License: MIT License
# Created 2019-03-08
from typing import TYPE_CHECKING, List, Tuple, Union, Sequence, Iterable, Optional
from contextlib import contextmanager
import math
import copy
import warnings
from ezdxf.math import Vector, Vec2, Matrix44, angle_to_param, param_to_an... |
import asyncio
import aiozmq.rpc
import logging
from collections import OrderedDict
class Handler(aiozmq.rpc.AttrHandler):
def __init__(self, events, *, logger=None):
self.events = events
self.logger = logger or logging.getLogger(__name__)
@aiozmq.rpc.method
def bump(self, who):
... |
import cv2
import os
def draw_face_landmark(name, landmarkToPaint,image_directory):
point_size = 1
point_color = (0, 0, 255)
thickness = 4
_DEAFAULT_JPG_QUALITY = 95
img_crop =cv2.imread(name)
image_draw = img_crop
for landmark in landmarkToPaint:
for i in range(0, len(landmark), 2... |
'''
This script is for automatic run command of PadestrianSlayer.py after raspPi reboots
'''
import PedestrianSlayer
ps = PedestrianSlayer.PedestrianSlayer()
ps.run()
|
"""Authors: Cody Baker."""
import numpy as np
from scipy.io import loadmat
from pynwb import NWBFile
from nwb_conversion_tools.basedatainterface import BaseDataInterface
class PoissonClicksProcessedInterface(BaseDataInterface):
"""Conversion class for processed behavioral data parsed from raw 'saved history'."""... |
__all__=["downloader"] |
# Copyright 2014 OpenStack Foundation
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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/LICENS... |
# -*- coding: utf-8 -*-
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright 2002 Ben Escoto <ben@emerose.org>
# Copyright 2007 Kenneth Loafman <kenneth@loafman.com>
#
# This file is part of duplicity.
#
# Duplicity is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License... |
# Copyright (c) 2015 Microsoft Corporation
"""
Testing floating-point operations
>>> from z3 import *
>>> nz = FPVal(-0.0, Float32())
>>> z = FPVal(0.0, Float32())
>>> x = FP('x', Float32())
>>> solve(fpNeg(x) != nz - x)
no solution
>>> solve(fpNeg(x) != z - x)
[x = +0.0]
>>> solve(nz == z)
no solution
>>> solve(fpEQ(n... |
#!/usr/bin/env python3
import yasl
import argparse
def main():
desc = """
Draw bar graphs from input data. By default, it draws a vertical bar
chart, but you can also draw a horizontal bar chart if you want.
"""
parser = argparse.ArgumentParser(
description=desc,
# formatter_clas... |
import numpy as np
from torch.utils.data.sampler import BatchSampler, SubsetRandomSampler
import torch as th
from torch import nn
from typing import Generator, Optional, Union, Tuple, NamedTuple
from gym import spaces
def init(module, weight_init, bias_init, gain=1):
weight_init(module.weight.data, gain=gain)
... |
from poop.hfdp.facade.home_theater.amplifier import Amplifier
from poop.hfdp.facade.home_theater.cd_player import CDPlayer
from poop.hfdp.facade.home_theater.popcorn_popper import PopcornPopper
from poop.hfdp.facade.home_theater.projector import Projector
from poop.hfdp.facade.home_theater.screen import Screen
from poo... |
# from .nx import XELK
from .transformer import XELK
|
"""This module contains the general information for MailRecipient ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class MailRecipientConsts:
ADMIN_ACTION_CLEAR = "clear"
ADMIN_ACTION_SEND_TEST_MAIL = "send-test-mail"
... |
#
import pandas as pd
import numpy as np
from operator import itemgetter
import random
import time
import pytest
from sklearn.metrics.pairwise import cosine_similarity
from cosine_similarity import cosine_sim
#
movies = pd.read_csv('data/initial_list.csv', index_col=0)
identifier_df = pd.read_csv('data/movie_title_a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of Karesansui Core.
#
# Copyright (C) 2009-2012 HDE, 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 restric... |
import random
import typing
from stests.core import factory
from stests.core.cache.model import CountIncrementKey
from stests.core.cache.model import Item
from stests.core.cache.model import ItemKey
from stests.core.cache.model import SearchKey
from stests.core.cache.model import StoreOperation
from stests.core.cache.... |
import json,os,sys
from threading import Thread
from PyQt6.QtCore import Qt,pyqtSignal
from PyQt6.QtGui import QAction
from PyQt6.QtWidgets import QApplication,QInputDialog,QMainWindow,QMenu,QMessageBox,QStyle,QSystemTrayIcon
import fgoCore
from fgoIniParser import IniParser
from fgoMainWindow import Ui_fgoMainWindow
... |
import pyautogui
import keyboard
import time
from concurrent.futures import ThreadPoolExecutor # Đa luồng
def prunning(arr):
# Cắt tỉa vị trí trùng lặp
count_p = 0
for i in range(len(arr)):
for j in range(1, len(arr)):
if i == j:
continue
try:
... |
#!/usr/bin/env python3
# coding: utf-8
import json
from pathlib import Path
from typing import BinaryIO, Dict, Tuple
import requests
from requests import Response
from genpei.type import RunRequest
URL: str = "localhost:8080"
SCRIPT_DIR: Path = \
Path(__file__).parent.resolve()
RES_D: Path = \
SCRIPT_DIR.par... |
# Le professeur a visiblement chiffré l'accès en écriture sur les fichiers de résultats pour s'assurer que personne ne
# tricherait. Le message suivant apparaît :
# qzrtxoevztjtdqufnggzfczadnolyknmeaokcxkxzydvmp.qufnvzpbpujpnuchgtnaedrtnkcgkcvinjacxongggdkcXZCG+K+E+Bvzpxczsaggnzxwzltxntzxoztzokdnacxkejxodtlokfm
#
# Voi... |
#!/usr/bin/env python
# enable debugging
import cgi
import cgitb
cgitb.enable()
cgitb.enable(display=0, logdir='/tmp')
from control_roku import get_output
if __name__ == '__main__':
form = cgi.FieldStorage()
if "cmd" not in form:
print "<H1>Error</H1>"
print "Please fill in the cmd field."
... |
# GENERATED BY KOMAND SDK - DO NOT EDIT
from .create_saved_search.action import CreateSavedSearch
from .delete_saved_search.action import DeleteSavedSearch
from .display_search_results.action import DisplaySearchResults
from .get_saved_search_job_history.action import GetSavedSearchJobHistory
from .insert.action import... |
"""
The Device class is intended to be used for:
* store general information about the device (including connectivity graph)
and references to qubit objects
* store two-qubit gate parameters
The structure is chosen to resemble the one of the QuDev_transmon class. As such, the two-qubit gate parameters
ar... |
"""Parse the meta model."""
from typing import Tuple, Optional
import asttokens
from aas_core_codegen.parse import _types, _translate, _stringify
TypeAnnotation = _types.TypeAnnotation
AtomicTypeAnnotation = _types.AtomicTypeAnnotation
SelfTypeAnnotation = _types.SelfTypeAnnotation
SubscriptedTypeAnnotation = _types... |
from metaflow import FlowSpec, step, Parameter
class PlayListFlow(FlowSpec):
"""
The next version of our playlist generator that uses the statistics
generated from 'Episode 02' to improve the title recommendations.
The flow performs the following steps:
1) Load the genre specific statistics from... |
# sorted list
#students = ['Nelson', 'Moses', 'kuria', 'Betty', 'paul']
#students.sort()
#for student in students:
# print(student, end= " ")
my_tuple = 3,4.6, "dog"
a,b,c = my_tuple
print(a)
print(b)
print(c)
|
#!/usr/bin/env python
import schemabase
from leginon import leginondata, ddinfo
class SchemaUpdate17916(schemabase.SchemaUpdate):
'''
This schema adds probe as a field in related calibration so that we can add nanoprobe, too.
'''
def upgradeLeginonDB(self):
if not self.leginon_dbupgrade.tableExists('EucentricF... |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import copy
from mo.graph.graph import Node, Graph
from mo.ops.op import Op
class SpatialTransformOp(Op):
op = 'SpatialTransformer'
def __init__(self, graph: Graph, attrs: dict):
mandatory_props = {
'type'... |
from firebase import Firebase
class FirebaseLogger:
config = {
"apiKey": "",
"authDomain": "",
"databaseURL": "",
"storageBucket": ""
}
firebase = Firebase(config)
db = firebase.database()
current_num_people = 0
total_num_people = 0
did_someone_leave = False
de... |
# -*- coding: utf-8 -*-
"""
Data generation for figure 05c
"""
import sys
sys.path.append("../main/")
from ODEdrop import *
# Heterogeneity
def g(x,y):
return 1.2+a*(-np.tanh(50*(x+1.5))+np.tanh(50*(x-1.5))-np.tanh(50*(x-1.75)))
# Volume variations
def V(t):
return ( np.pi*(1+2*np.tanh(2*np.pi*t/100)), np.pi*... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 19 14:06:32 2021
@author: maita
Checking differences between years in admin areas
"""
import pandas as pd
import geopandas as gpd
import numpy as np
datadir = "/home/maita/Nextcloud/Documents/Work/Gap_Map/out/"
scopes = ["all","fv"]
levels = ["ge... |
import scrapy
import re
import json
from locations.items import GeojsonPointItem
class DairyQueenSpider(scrapy.Spider):
name = "dairyqueen"
item_attributes = { 'brand': "Dairy Queen", 'brand_wikidata': "Q1141226" }
allowed_domains = ["www.dairyqueen.com"]
start_urls = (
'https://www.dairyquee... |
# Copyright 2015 Planet Labs, Inc.
#
# 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 writ... |
'''
Created by Aleksandar Damnjanovic
Date: 13.11.2021
Last edit: 22.11.2021
'''
from io import FileIO
import os
import docx2txt
import pdfplumber
import string
class alphaSwap:
def __init__(self) -> None:
self.d= self.parseCSV()
def parseCSV(self):
file= open('dictionary.csv', 'r')
... |
import pandas as pd
def framer(data):
print("------> From Dict to Dataframe | wait!")
frames_list = []
for post in data:
frame = pd.DataFrame({
"owner_username": post["owner_username"],
"owner_id": post["owner_id"],
"post_date": post["post_date"],
... |
import random
import string
import json
import requests
import os
from datetime import datetime, timedelta
from http import HTTPStatus
import pytest
from dotenv import load_dotenv
from pydantic.networks import HttpUrl
from service.models.employer.employer_job import EmployerJob, JobScope
from tests.helpers.environment... |
__author__ = 'tobias'
import math as m
import numpy as np
def rotation_matrix(axis, theta):
"""
Return the rotation matrix associated with counterclockwise rotation about
the given axis by theta radians.
"""
axis = np.asarray(axis)
theta = np.asarray(theta)
axis = axis/m.sqrt(np.dot(axis, a... |
#!/usr/bin/env python
# This python scripts takes raw json tweets and extract the usernames out of it.
""" To analyse the word freq of people who are using abusive language/are drunk in tweets."""
import sys
import os
import json
import gzip
import time
import pandas as pd
# =============================
# Do not mod... |
from typing import List, Iterable, Sequence, TypeVar, Type
def arg_sort(unsorted_iterable: Iterable) -> List[int]:
"""Argument-sort an iterable.
:param unsorted_iterable: An iterable of unsorted items.
:return: A list of sorted items' indices.
"""
return [i[0] for i in sorted(enumerate(unsorted_i... |
import csv
import json
import requests
from entorno_list import enderecos
def pega_cep(logradouro):
url_api = f'http://www.viacep.com.br/ws/{logradouro}/json'
req = requests.get(url_api)
if req.status_code == 200:
dados_json = json.loads(req.text)
return dados_json
with open('enderecos... |
#!/usr/bin/env python
# coding: utf-8
from __future__ import print_function
import codecs
import os
import re
import sys
import requests
re_font_url = re.compile(r'url\((http[^\)]+/([^/\)]+))\)')
def download_css(url):
print('Downloading CSS:', url)
r = requests.get(url)
r.raise_for_status()
conte... |
score = list(map(int, input("컴마와 띄어쓰기를 구분으로 점수를 입력하세요 : ").split(", ")))
avg = int(sum(score)/len(score))
print("학점의 평균은 :",round(avg,0)) |
"""Teams view."""
import json
import logging
from auvsi_suas.models.takeoff_or_landing_event import TakeoffOrLandingEvent
from auvsi_suas.models.uas_telemetry import UasTelemetry
from auvsi_suas.views.decorators import require_superuser
from auvsi_suas.views.missions import active_mission
from django.contrib.auth.mode... |
from google.appengine.ext import webapp as wa
from google.appengine.ext.zipserve import ZipHandler, main
application = wa.WSGIApplication([('/([^/]+)/(.*)', ZipHandler)])
if __name__ == '__main__':
main()
|
from django.apps import AppConfig
class MatchAppConfig(AppConfig):
name = 'match_app'
|
CREATE_MOVIE_TABLE = '''
CREATE TABLE IF NOT EXISTS MOVIE (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME VARCHAR(255) NOT NULL,
RATING REAL NOT NULL DEFAULT 0
)
'''
CREATE_PROJECTION_TABLE = '''
CREATE TABLE IF NOT EXISTS PROJECTION (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
... |
#
# Copyright 2018 PyWren Team
#
# 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... |
#!/usr/bin/python3
import argparse
import flickrapi
import json
import sqlite3
import os.path
def _display_user_auth_info( user_auth_info ):
print( f"User auth info:\n{json.dumps(user_auth_info, indent=4, sort_keys=True)}" )
def _get_user_auth_info( args ):
sqlite_file_path = os.path.join( args.token_cach... |
"""
The goal of this module is to practice running code on the EV3.
Authors: David Mutchler, Vibha Alangar, Dave Fisher, and PUT_YOUR_NAME_HERE.
""" # TODO: 1. PUT YOUR NAME IN THE ABOVE LINE.
import time
# -----------------------------------------------------------------------------
# TODO: 2. Put your own name w... |
"""Test Cases"""
from dataStructures.balanced_tree import is_balanced
from dataStructures.data_types_bst import BinaryTreeNode
def test_chain_not_balanced():
root = BinaryTreeNode(1)
root.left = BinaryTreeNode(2)
root.left.left = BinaryTreeNode(3)
assert not is_balanced(root)
def test_root_balanc... |
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from sklearn.metrics import confusion_matrix
import time
from datetime import timedelta
import math
import os
import prettytensor as pt
from tensorflow.examples.tutorials.mnist import input_data
data = input_data.read_data_sets('data/MNIST',one... |
import logging
log = logging.getLogger(__name__)
from pyramid.response import Response
from pyramid.renderers import render_to_response
from pyramid.view import (view_config, view_defaults)
from pyramid.httpexceptions import HTTPFound, HTTPNotFound, HTTPSeeOther
from configparser import ConfigParser
config = ConfigPar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.