content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/python
# coding: utf8
from __future__ import print_function
try:
from itertools import izip as zip
except ImportError: # will be 3.x series
pass
from enum import Enum
from collections import MutableSequence
from collections import namedtuple
from collections import OrderedDict
from itertools impor... | python |
'''
Code Challenge: Solve the Eulerian Cycle Problem.
Input: The adjacency list of an Eulerian directed graph.
Output: An Eulerian cycle in this graph.
'''
import random
import copy
with open('test1.txt','r') as f:
#with open('dataset_203_2.txt','r') as f:
adjacency_list = dict()
eulerian_edge_len ... | python |
"""Comic Rereading Discord Bot"""
from .rereadbot import *
async def setup(bot):
"""Setup the DoA Cogs"""
bot.add_cog(DoaRereadCog(bot, envfile="./.env"))
| python |
from datetime import datetime, timezone
import requests
from schemas import Contest
from spider.utils import update_platform
def main():
headers = {"x-requested-with": "XMLHttpRequest"}
resp = requests.get("https://csacademy.com/contests/", headers=headers)
json_data = resp.json()
data = []
tz... | python |
#
# This source code is licensed under the Apache 2 license found in the
# LICENSE file in the root directory of this source tree.
#
import json
import cPickle as pickle
import numpy as np
import h5py
import random
import pandas as pd
from nltk.tokenize import TweetTokenizer
word_tokenize = TweetTokenizer().tokenize
... | python |
# Generated by Django 2.1.11 on 2019-11-18 19:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [("course_catalog", "0052_userlistitem_contenttypes")]
operations = [
migrations.CreateModel(
name="Playlist",... | python |
"""Helpers to integrate the process on controlling profiles."""
from dataclasses import dataclass
from typing import List, Set, Optional
from bson import ObjectId
from flags import ProfilePermission, PermissionLevel
from mongodb.factory import ProfileManager, ChannelManager
from mongodb.helper import IdentitySearcher... | python |
import uos
import network
import socket
import select
import time
from machine import UART, Pin
ap_mode = False
recvPollers = []
sockets = []
clients = []
def socketSend(message):
for socket in sockets:
try:
socket.sendall(message)
except:
socket.close()
def ge... | python |
from importlib import import_module
def load_extensions(app):
for extension in app.config["EXTENSIONS"]:
module_name, factory = extension.split(":")
ext = import_module(module_name)
getattr(ext, factory)(app)
def load_blueprints(app):
for extension in app.config["BLUEPRINTS"]:
... | python |
#let's work on dictionaries
'''stuff = {'name':'Vivek', 'age':18, 'height':6*2}
print(stuff['name'])
print(stuff['age'])
print(stuff)
'''
'''
state = {
'Oregon' : 'OR',
'Florida' : 'FL',
'California': 'CA',
'New York' : 'NY',
'Michigan' : 'MI'
}
cities = {
'CA': 'California',
'NY' ... | python |
from dataclasses import dataclass, field
from typing import Optional
from .geometry import Geometry
__NAMESPACE__ = "sdformat/v1.3/collision.xsd"
@dataclass
class Collision:
"""The collision properties of a link.
Note that this can be different from the visual properties of a
link, for example, simpler ... | python |
import trio
from socket import (
inet_aton,
)
import pytest
import pytest_trio
from async_service import background_trio_service
from p2p.discv5.channel_services import (
DatagramReceiver,
DatagramSender,
Endpoint,
IncomingDatagram,
OutgoingDatagram,
OutgoingPacket,
PacketDecoder,
... | python |
# -*- coding: utf-8 -*-
from dataclasses import dataclass
from dataclasses_io import dataclass_io
from pathlib import Path
_TEST_PATH = Path(__file__).parent
@dataclass_io
@dataclass
class _MyDataclass:
id: int
name: str
memo: str
if __name__ == "__main__":
dataclass1 = _MyDataclass(id=42, name="... | python |
# 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组。如果不存在符合条件的连续子数组,返回 0。
#
# 示例:
#
# 输入: s = 7, nums = [2,3,1,2,4,3]
# 输出: 2
# 解释: 子数组 [4,3] 是该条件下的长度最小的连续子数组。
# 进阶:
#
# 如果你已经完成了O(n) 时间复杂度的解法, 请尝试 O(n log n) 时间复杂度的解法。
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/minimum-size-subarray-sum
# 著作权归领扣网络所有。商... | python |
"""
Clean and validate a DataFrame column containing country names.
"""
from functools import lru_cache
from operator import itemgetter
from os import path
from typing import Any, Union
import dask
import dask.dataframe as dd
import numpy as np
import pandas as pd
import regex as re
from ..progress_bar import Progres... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-11-15 02:47
from __future__ import unicode_literals
from django.db import migrations, models
import jobs.models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0008_auto_20161115_0222'),
]
operations = [
migra... | python |
from normality import normalize
def text_parts(text):
text = normalize(text, latinize=True)
if text is None:
return set()
return set(text.split(' '))
def index_text(proxy):
texts = set()
for name in proxy.names:
texts.update(text_parts(name))
return ' '.join(texts)
| python |
import torch
import torch.nn as nn
from nn_blocks import *
from torch import optim
import time
class DApredictModel(nn.Module):
def __init__(self, utt_vocab, da_vocab, tod_bert, config):
super(DApredictModel, self).__init__()
if config['DApred']['use_da']:
self.da_encoder = DAEncoder(d... | python |
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime.now(),
'email': ['chris@fregly.com'],
'email_on_failure': False,
'email_on_retry': Fals... | python |
from typing import Any, Tuple, Union
from lf3py.lang.annotation import FunctionAnnotation
from lf3py.routing.errors import UnresolvedArgumentsError
from lf3py.routing.types import Middleware
from lf3py.serialization.deserializer import Deserializer
from lf3py.serialization.errors import DeserializeError
from lf3py.tas... | python |
#!/usr/bin/env python
# coding=utf8
from __future__ import unicode_literals
from datetime import timedelta
import collections
import functools
import os
import re
import string
from io import StringIO
import pytest
from hypothesis import given, settings, HealthCheck, assume
import hypothesis.strategies as st
import ... | python |
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))
import argparse
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import numpy as np
import numpy
import scipy.stats
import torch
import torch.optim as optim
import jammy_flows
from jamm... | python |
from m5.params import *
from m5.SimObject import SimObject
from Controller import RubyController
class PMMU(RubyController):
type = 'PMMU'
cxx_class = 'PMMU'
cxx_header = "mem/spm/pmmu.hh"
# version = Param.Int("");
page_size_bytes = Param.Int(512,"Size of a SPM page in bytes")
ruby_system = Par... | python |
import requests
import mimetypes
import hashlib
class Tebi:
def __init__(self, bucket, **kwargs):
self.bucket = "https://" + bucket
self.auth = kwargs.get('auth', None)
if (self.auth):
self.auth = "TB-PLAIN " + self.auth
def GetObject(self, key):
headers = {}
... | python |
from __future__ import absolute_import, print_function, unicode_literals
import cwltool.main
import pkg_resources
import signal
import sys
import logging
from cwl_tes.tes import TESWorkflow
from cwl_tes.__init__ import __version__
log = logging.getLogger("tes-backend")
log.setLevel(logging.INFO)
console = logging.S... | python |
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404
from django.utils.timezone import now
from rest_framework import generics
from bluebottle.bluebottle_drf2.pagination import BluebottlePagination
from bluebottle.clients import properties
from .models i... | python |
from networkx.algorithms import bipartite
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
class BipartiteGraphState(QuantumCircuit):
def __init__(self, bipartite_graph):
super().__init__()
self.graph = bipartite_graph
# Create a quantum register based on the number o... | python |
# pylint: disable=no-name-in-module
from collections import deque
from typing import Deque
from pydantic import BaseModel
from ..core.constants import Interval
from .timeframe import TimeFrame
class Window(BaseModel):
"""Holds a sequence of timeframes and additional metadata."""
interval: ... | python |
#!/usr/bin/env python3
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GLib
# keyboard lib
from pynput.keyboard import Key, Listener, Controller
# capslock status
from capslock_status import status
# pop up time in ms
time = 700
# ... | python |
from mix import save_color_image, brightness_limitization
import os
import shutil
from argparse import ArgumentParser
import json
from utils import change_datatype
from utils import timestamp_to_datetime
from utils import Bands
def parse_arguments():
parser = ArgumentParser(description='Create colored images and ... | python |
def deleteWhitespaces(inputStr):
nonWhitespaces = inputStr.split(' ')
return ''.join(nonWhitespaces)
| python |
"""Graph implementation using adjacency lists."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, Set, Optional, Union, Tuple
from collections.abc import Iterable
@dataclass
class Node:
"""This class can be used standalone or with a Graph
(if fast acce... | python |
# encoding = utf-8
"""Wrapper for API calls to ExtraHop."""
# COPYRIGHT 2020 BY EXTRAHOP NETWORKS, INC.
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE', which is part of this source code package.
# This file is part of an ExtraHop Supported Integration. Make NO MODIFICATIONS below this ... | python |
from distutils.core import setup
DESCRIPTION = ('Python interface to the Refinitiv Datastream (former Thomson '
'Reuters Datastream) API via Datastream Web Services (DSWS)')
# Long description to be published in PyPi
LONG_DESCRIPTION = """
**PyDatastream** is a Python interface to the Refinitiv Datastr... | python |
from django.conf import settings
from django.contrib import admin
from django.template.response import TemplateResponse
from django.urls import path, resolve, reverse
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.views.generic import View
from constance import conf... | python |
from robo_navegador import *
from dados_ritmistas import ler_dados
from alterar_docs import *
nomes = ('Matheus Delaqua Rocha De Jesus',
'Cecília')
if __name__ == '__main__':
renomear(nome_atual_pasta='Credenciamento TABU (File responses)')
mover(path=('Arquivo do Documento (File responses)', 'Compro... | python |
import argparse
from pathlib import Path
from event_types import event_types
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=(
'Train event classes models.'
'Results are saved in the models directory.'
)
)
args = parser.parse_args()
n... | python |
#-*- coding: utf-8 -*-
#!/usr/bin/python3
"""
Copyright (c) 2020 LG Electronics Inc.
SPDX-License-Identifier: MIT
"""
import argparse
import copy
import logging
import os
import sys
import textwrap
from .tool_wrapper import get_tool_list, get_tool_wrapper, load_tools
from .context import WrapperContext
from .report ... | python |
from sqlalchemy import (
create_engine as create_engine,
MetaData, Table,
Column, Integer, Sequence,
String, ForeignKey, DateTime,
select, delete, insert, update, func
)
from sqlalchemy.sql import and_
from tornado import concurrent, ioloop
import datetime
import tornado
import sqlite3
#from concurr... | python |
inp = open("input/day6.txt", "r")
prvotne_ribe = [int(x) for x in inp.readline().split(",")]
inp.close()
prvotna_populacija = [0 for _ in range(9)]
for riba in prvotne_ribe:
prvotna_populacija[riba] += 1
def zivljenje(N):
populacija = prvotna_populacija
for _ in range(N):
nova_populacija = [0 for ... | python |
import sys
import pandas as pd
import matplotlib.pyplot as plt
def main():
dfpath = 'nr_dataframes/final.pkl'
df = pd.read_pickle(dfpath)
df.hist(column='length', bins=100)
df = df[df[show] > 400]
plt.show()
if __name__=="__main__":
show = sys.argv[1]
main()
| python |
from selenium import webdriver
import datetime
from . import helper
class NewVisitorTest(helper.FunctionalTestBase):
def setUp(self):
self.browser = webdriver.Firefox()
self.data = {
"dhuha": "4",
"tilawah_from": "1",
"tilawah_to": "20",
"ql": "5",
... | python |
# Generated by Django 2.0.6 on 2018-06-14 08:09
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('course', '0007_auto_2018... | python |
# Generated by Django 3.2.9 on 2021-11-24 15:56
from django.db import migrations
EVENT_TYPES = (
(1, "CREATED", "Created the resourcing request"),
(2, "UPDATED", "Updated the resourcing request"),
(3, "SENT_FOR_APPROVAL", "Sent the resourcing request for approval"),
(4, "AMENDING", "Amending the reso... | python |
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from ckeditor_uploader.fields import RichTextUploadingField
# Create your models here.
class RemoteProfile(models.Model):
host = models.URLField(max_length=200)
api_key = models.CharField(max_length=128... | python |
#!/usr/bin/env python
# $Id: mailtrim.py,v 1.1 2002/05/31 04:57:44 msoulier Exp $
"""The purpose of this script is to trim a standard Unix mbox file. If the
main function is called, it expects two parameters in argv. The first is the
number of most recent messages to keep. The second is the path to the mbox
file."""
... | python |
# 'hello_module.py'
def helloworld():
print ("Hello World!")
def goodbye():
print ("Good Bye Dear!")
| python |
from django.conf.urls import url
from django.views.decorators.csrf import csrf_exempt
from .views import OrderView, PayNotifyView, OrderQueryView
urlpatterns = [
url(r"^order/$", OrderView.as_view(), name="order"),
url(r"^notify/$", csrf_exempt(PayNotifyView.as_view()), name="notify"),
url(r"^orderquery/$... | python |
import flickr_api
import win32api, win32con, win32gui
username = 'NASA Goddard Photo and Video'
flickr_api.set_keys(api_key='73ec08be7826d8b0a608151ce5faaf9d', api_secret='fbb2fcd772ce44a6')
user = flickr_api.Person.findByUserName(username)
photos = user.getPublicPhotos()
print photos[0]
photos[0].save(photos[0].ti... | python |
import math
from error import Error
from dataclasses import dataclass
class Value:
def add(self, other):
self.illegal_operation()
def subtract(self, other):
self.illegal_operation()
def multiply(self, other):
self.illegal_operation()
def divide(self, other):
self... | python |
#
# Memento
# Backend
# Notification Models
#
import re
from datetime import datetime
from sqlalchemy.orm import validates
from ..app import db
# defines a channel where notifications are sent
class Channel(db.Model):
# kinds/types
class Kind:
Task = "task"
Event = "event"
Notice = ... | python |
import unittest
from unittest.mock import Mock
from pydictionaria import sfm_lib
from clldutils.sfm import SFM, Entry
def test_normalize():
from pydictionaria.sfm_lib import normalize
sfm = SFM([Entry([('sd', 'a__b')])])
sfm.visit(normalize)
assert sfm[0].get('sd') == 'a b'
def test_split_join():
... | python |
# shuffle can randomly shuffles a list, and choice make a choice from a set of different items !
from random import choice, shuffle
# use external module termcolor for genarate beautiful colors
from termcolor import colored, cprint
# using pyfiglet, external module -> we can draw ascii_art very easily !
import pyf... | python |
from setuptools import setup
setup(
name='COERbuoyOne',
version='0.2.0',
author='Simon H. Thomas',
author_email='simon.thomas.2021@mumail.ie',
packages=['COERbuoyOne'],
url='http://coerbuoy.maynoothuniversity.ie',
license='LICENSE.txt',
description='A realistic benchmark for Wave Enegery Conver... | python |
from setuptools import setup
setup(
name='ShapeWorld',
version='0.1',
description='A new test methodology for multimodal language understanding',
author='Alexander Kuhnle',
author_email='aok25@cam.ac.uk',
keywords=[],
license='MIT',
url='https://github.com/AlexKuhnle/ShapeWorld',
p... | python |
class Solution:
def validWordSquare(self, words):
"""
:type words: List[str]
:rtype: bool
"""
m = len(words)
if m != 0:
n = len(words[0])
else:
n = 0
if m != n:
return False
for x in range(m):
n... | python |
import matplotlib.pyplot as plt
from models import *
device="cuda:0" if torch.cuda.is_available() else "cpu"
def plot_random():
"""
Plots a random character from the Normal Distribution N[0,5).
No arguments
"""
# dec.eval()
samp=(torch.randn(1,8)*5).float().to(device)
plt.imshow(dec(samp).... | python |
duration_seconds = int(input())
seconds = duration_seconds % 60
temp = duration_seconds // 60
minutes = temp % 60
temp = temp // 60
hours = temp % 60
print(f"{hours}:{minutes}:{seconds}")
| python |
import pickle
import os
import sys
import genetic_algorithm as ga
import game
import pygame
import numpy as np
import snake
def save(generation, details, filename="generation"):
"""
Saves a snakes generation after checking if a file with same name
already exists (also asks for a new name before exiting)
"""
if ... | python |
from bs4 import BeautifulSoup
from urllib.request import urlopen, Request
from time import gmtime, strftime
# Get the data from the source
url = "https://www.house.gov/representatives"
url_req = urlopen(Request(url, headers={'User-Agent': 'Mozilla'}))
raw_html = BeautifulSoup(url_req, "lxml")
html = raw_html.prettify(... | python |
#PasswordGenerator GGearing314 01/10/19
from random import *
case=randint(1,2)
number=randint(1,99)
animals=("ant","alligator","baboon","badger","barb","bat","beagle","bear","beaver","bird","bison","bombay","bongo","booby","butterfly","bee","camel","cat","caterpillar","catfish","cheetah","chicken","chipmunk","cow","cra... | python |
from thundra import constants
from thundra.context.execution_context_manager import ExecutionContextManager
from thundra.wrappers.fastapi.fastapi_wrapper import FastapiWrapper
from thundra.context.tracing_execution_context_provider import TracingExecutionContextProvider
from thundra.context.global_execution_context_pro... | python |
import lanelines
from compgraph import CompGraph, CompGraphRunner
import numpy as np
import cv2
func_dict = {
'warp': lanelines.warp,
'gray': lanelines.gray,
'get_HLS': lanelines.get_hls_channels,
'weighted_HLS_sum': lanelines.weighted_HLS,
'threshold_gray': lanelines.mask_threashold_range,
'th... | python |
import time
import typing as t
from huey import crontab
from app.db.session import db_session
from app.db.crud.server import get_server_with_ports_usage
from app.db.crud.port_forward import get_forward_rule, get_all_expire_rules
from app.db.models.port import Port
from .config import huey
from tasks.ansible import an... | python |
# This is an exact clone of identification.py with functions renamed for clarity and all code relating to creating an
# alignment removed
from typing import Tuple
import sys
import os
path_to_src = (os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
sys.path.append(path_to_src)
from src.objects import Da... | python |
from .base import NextcloudManager
class NextcloudGroupManager(NextcloudManager):
def all(self, search=None):
"""
Get all nextcloud groups
"""
request = self.api.get_groups(search=search)
self.check_request(request)
objs = []
for name i... | python |
import numpy as np
import matplotlib.pyplot as plt
from soundsig.plots import multi_plot
"""
Implementation of S. Zayd Enam's STRF modeling stuff:
S. Zayd Enam, Michael R. DeWeese, "Spectro-Temporal Models of Inferior Colliculus Neuron Receptive Fields"
http://users.soe.ucsc.edu/~afletcher/hdnips2013/papers/strfmode... | python |
import binascii
import pytest
from random import random
import jmap
from jmap import errors
@pytest.mark.asyncio
async def test_mailbox_get_all(account, idmap):
response = await account.mailbox_get(idmap)
assert response['accountId'] == account.id
assert int(response['state']) > 0
assert isinstance(... | python |
from ocha.libs import utils
import os, yaml
from ocha.libs import setting
def create_production_env(data_env, app_path):
host = data_env['app']['host']
port = data_env['app']['port']
f=open(app_path+"/production.sh", "a+")
f.write("gunicorn production:app -b "+str(host)+":"+str(port)+" -w 2 --chdir "+... | python |
import os
import sys
import openpype
from openpype.api import Logger
log = Logger().get_logger(__name__)
def main(env):
from openpype.hosts.fusion.api import menu
import avalon.fusion
# Registers pype's Global pyblish plugins
openpype.install()
# activate resolve from pype
avalon.api.instal... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
import math
import numpy as np
VELOCITIES = np.array([
(1, 0),
(np.sqrt(1/2+np.sqrt(1/8)), np.sqrt(1/6-np.sqrt(1/72))),
(np.sqrt(1/2), np.sqrt(1/6)),
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import hashlib
import json
import psycopg2
import psycopg2.extras
import re
import transforms
import signal
import sys
from get_pg_conn import get_pg_conn
# see https://filosophy.org/code/python-function-execution-deadlines---in-simple-examples/
class TimedOutExc(Except... | python |
# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
import unittest
from karmia import KarmiaContext
class TestKarmiaContextSet(unittest.TestCase):
def test_parameter(self):
context = KarmiaContext()
key = 'key'
value = 'value'
context.set(key, value)
self.assert... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
# Copyright (c) 2018-2021 Nicolas Iooss
#
# 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, inc... | python |
# import argv variable so we can take command line arguments
from sys import argv
# extract the command line arguments from argv and store them in variables
script, filename = argv
# print a formatted string with the filename command line arugment inserted
print(f"We're going to erase {filename}")
# print a string
pr... | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from django.conf.urls import include, url
from django.contrib import admin
from s_analyzer.apps.rest.api import router
from s_analyzer.site.views import HomeView
urlpatterns = [
url(r'^admin/', admin.site.urls),
... | python |
from django.db import models
from re import sub
# Create your models here.
class Movie(models.Model):
movie_name = models.CharField(max_length=250, unique=True, blank=False, null=False)
movie_year = models.IntegerField()
imdb_rating = models.DecimalField(max_digits=3, decimal_places=2, blank=True... | python |
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from datetime import datetime
from helper.utils import TestUtils as tu
from mushroom_rl.core import Agent
from mushroom_rl.algorithms.actor_critic import SAC
from mushroom_rl.core import Core
from mushro... | python |
# Copyright 2016 Google Inc. 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 applicable law or ... | python |
from table import Table
class CSVTable(Table):
def __init__(self, savepath):
self.savepath = savepath
self.file_created = False
super().__init__()
def _table_add(self):
fieldnames = [column.generate_header() for column in self.columns]
with open(self.savepath, mode="w... | python |
# -*- coding: utf-8 -*-
import csv
from pathlib import Path
import tkinter as tk
import argparse
import json
def matchKeyToName(pathToJsonfile:str, key : str):
cityKeysFile = json.load(open(pathToJsonfile))
return cityKeysFile[key]['Town']
def main():
parser = argparse.ArgumentParser()
pa... | python |
"""Events that are emitted during pipeline execution"""
import abc
import datetime
import json
import enum
class Event():
def __init__(self) -> None:
"""
Base class for events that are emitted from mara.
"""
def to_json(self):
return json.dumps({field: value.isoformat() if i... | python |
# An implementation of reference learning for the game TicTacToe
| python |
from enum import Enum
import numpy as np
class TypeData(Enum):
BODY = 0
HAND = 1
class HandJointType(Enum):
BAMB_0 = 0
BAMB_1 = 1
BIG_TOE = 2
BIG_TOE_1 = 3
BIG_TOE_2 = 4
FINGER_1 = 5
FINGER_1_1 = 6
FINGER_1_2 = 7
FINGER_1_3 = 8
FINGER_2 = 9
FINGER_2_1 = 10
FING... | python |
import tensorflow as tf
import time
import os
import sys
import model_nature as model
base = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(base,'../../'))
import datasets.Img2ImgPipeLine as train_dataset
physical_devices = tf.config.experimental.list_physical_devices(device_type='GPU')
t... | python |
#
# Hangman
# Python Techdegree
#
# Created by Dulio Denis on 2/9/17.
# Copyright (c) 2017 ddApps. All rights reserved.
# ------------------------------------------------
# Guess what word the computer picked.
#
import random
import os
import sys
# make a list of words
words = [
'apple',
'... | python |
#!/usr/bin/python3
from shutil import copyfile
from shutil import move
from os import remove
from os import environ
import os
import os.path
import sys
import subprocess
homedir = os.environ['HOME']
bash_target_file = homedir + "/.bashrc"
bash_backup_file = homedir + "/.backup-bashrc"
bash_new_file = homedir + "/.newb... | python |
import json
import uuid
import factory
import mock
from django.test import TestCase
from facility_profile.models import Facility
from facility_profile.models import MyUser
from facility_profile.models import SummaryLog
from test.support import EnvironmentVarGuard
from .helpers import serialized_facility_factory
from ... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os,sys
import inquirer
import untangle
import requests
import platform
from colors import *
#If you want to use the program using an alias
#uncomment the following line and write your correct path
#os.chdir("/home/user/test/tunein-cli/")
type={}
station={}
headers = { '... | python |
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
# Allows to drag parent widget when holding pushbutton
# To use it you need to set screen_geometry in your QWidget first
class DragButton(QPushButton):
def __init__(self, parent: QWidget, constant_x0: bool):
super(DragButto... | python |
from csv import reader
from . import Destination
from . import DestinationPro
from . import ProtocolPort
def read_prot_port_info(info):
prot_info = {"HTTP": ["1", "1", "1"], "HTTPS": ["1", "0", "1"]}
with open(info, "r") as f:
csv_reader = reader(f)
next(csv_reader)
for row in csv_rea... | python |
# 執行時自行註解掉不需要的段落
# 自動型別
var = 'Hello World' # string
print(var)
var = 100 # int
print(var+10)
print('-----')
# 沒有 overflow
var = 17**3000 # 17的3000次方
print(var)
print('-----')
# swap
a=1
b=2
c=3
print(a,b,c)
c,a,b=b,c,a
print(a,b,c)
print('-----')
# string index
var1 = 'Hello World'
var2 = "Python Prog... | python |
import os, sys, inspect
# use this if you want to include modules from a subforder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"../")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
import simulation_parameters
impo... | python |
# %%
# ml + loss vs inner steps (Sigmoid best val)
import numpy as np
import matplotlib.pyplot as plt
from pylab import MaxNLocator
from pathlib import Path
print('running')
save_plot = True
# save_plot = False
# - data for distance
inner_steps_for_dist = [1, 2, 4, 8, 16, 32]
meta_test_cca = [0.2801, 0.2866, 0.2... | python |
# -*- coding: utf-8 -*-
"""
Password generator to generate a password based on the specified pattern.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2018 - 2019 by rgb-24bit.
:license: MIT, see LICENSE for more details.
"""
from .__version__ import __version__, __... | python |
"""Module :mod:`perslay.archi` implement the persistence layer."""
# Authors: Mathieu Carriere <mathieu.carriere3@gmail.com>
# License: MIT
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
# Post-processing opera... | python |
from sqlalchemy.dialects.postgresql import UUID
from app.common.sqlalchemy_extensions import utcnow
from database import db
class BaseModel(db.Model):
__abstract__ = True
id = db.Column(
UUID,
primary_key=True,
server_default=db.func.uuid_generate_v4())
created = db.Column(db.Dat... | python |
"""
Edge Detection.
A high-pass filter sharpens an image. This program analyzes every
pixel in an image in relation to the neighboring pixels to sharpen
the image.
"""
kernel = [[-1, -1, -1],
[-1, 9, -1],
[-1, -1, -1]]
img = None
def setup():
size(640, 360)
img = loadImage("moon.jpg")... | python |
"""
关于dfs,bfs的解释
https://zhuanlan.zhihu.com/p/50187643
"""
class Solution:
def minDepth(self,root):
if not root:
return 0
l = self.minDepth(root.left)
r = self.minDepth(root.right)
return 1 + r + 1 if l == 0 or r == 0 else min(l,r)+1 | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 爬取 春暖花开 论坛帖子中的图片
import os
import fake_useragent
import re
import requests
import time
from bs4 import BeautifulSoup
class Picture:
def all_url(self, url):
"""一个页面有许多图集,而这样的页面有很多,该方法是根据传入的根url,获取所有的页面url"""
list_str = url.split('-')
html = ... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.