content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
from pythainlp.tokenize import etcc
print(etcc.etcc('คืนความสุข')) # /คืน/ความสุข |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __eq__(self, other):
"""Overrides the default implementation"""
if isinstance(other, ListNode):
return self.val == other.val and self.next == other.n... |
# Generated by Django 2.2 on 2019-04-25 08:42
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Todo',
fields=[
('id', models.AutoField(auto_... |
from logic import judicator
judicator.activate()
|
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2021 Clyde McQueen
#
# 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 ... |
import datetime
from jcudc24ingesterapi.ingester_exceptions import UnknownParameterError
from jcudc24ingesterapi import typed, APIDomainObject, format_timestamp
from jcudc24ingesterapi.models.locations import LocationOffset
__author__ = 'Casey Bajema'
class DataEntry(APIDomainObject):
"""
Base class for indiv... |
from setuptools import setup
from setuptools import find_packages
setup(name='DDrop',
version='0.0.7',
description='Mathematical Dropconnect',
author='Derek Khu, Andrea Santilli',
author_email='derek.khu@gmail.com',
license='MIT',
install_requires=['keras'],
packages=find_pac... |
attribute = 42
|
# Generated by Django 2.0.2 on 2018-03-12 11:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vigil', '0015_auto_20180228_1503'),
]
operations = [
migrations.AddField(
model_name='alertchannel',
name='set_activ... |
# -*- coding: utf-8 -*-
import lemoncheesecake.api as lcc
@lcc.suite("ProposedTransactions")
@lcc.tags("database_api_second_pipeline")
class ProposedTransactions:
pass
|
"""Combine code coverage files."""
from __future__ import annotations
import os
import json
import typing as t
from ...target import (
walk_compile_targets,
walk_powershell_targets,
)
from ...io import (
read_text_file,
)
from ...util import (
ANSIBLE_TEST_TOOLS_ROOT,
display,
ApplicationErr... |
import configparser # python 3.x
import yaml
# BASIC_SCRIPT = 'configs/basic_config.yaml'
# RUNNING_SCRIPT = 'configs/train_deform.yaml'
# with open(BASIC_SCRIPT,'r') as f:
# bconfig = yaml.load(f)
# with open(RUNNING_SCRIPT,'r') as f:
# sconfig = yaml.load(f)
### UVBW Training
UVBW_TEST = True
UVBW_TRAIN ... |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
"""
try except
"""
try:
a = 1 / 2
except:
print("Something went wrong")
try:
a = 1 / 0
except:
print("Something went wrong")
else: # Executes if no exceptions are raised
print("Everithings Ok.")
|
from django.urls import path
from .views import (
home,
personList,
newPerson,
updatePerson,
vehicleList,
newVehicle,
updateVehicle,
rotaryMotion,
newRotaryMotion,
updateRotaryMotion,
monthly,
newMonthly,
updateMonthly,
rotaryMonthly,
newRotaryMonthly,
up... |
from django.db import models
class CityCountyStateCode(models.Model):
feature_id = models.IntegerField()
feature_name = models.TextField(blank=True, null=True)
feature_class = models.TextField(blank=True, null=True)
census_code = models.TextField(blank=True, null=True)
census_class_code = models.T... |
#
# @lc app=leetcode id=1299 lang=python3
#
# [1299] Replace Elements with Greatest Element on Right Side
#
import unittest
from typing import List
# @lc code=start
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
"""Start from the back and replace elements with the observ... |
import turtle
turtle.bgcolor(0,0,0) # set the background of the window to black
# use RGB color to control the turtle pen color
turtle.colormode(255) # values for red, green, blue range from 0-255
R = 165
G = 42
B = 42
turtle.pencolor(R,G,B)
for i in range(4):
turtle.forward(100)
turtle.right(90)
|
import json
import yaml
from collections import OrderedDict
def from_json(json_str):
"""Reads a JSON string into an OrderedDict.
:param json_str: a JSON string
:returns: an OrderedDict of the JSON contents
"""
argsdict = json.loads(json_str, object_pairs_hook=OrderedDict)
return argsdict
def from_yaml(yaml_str... |
# Assignment base class
#
# @author: Kyle Benson
# (c) Kyle Benson 2012
from AgraderWorkflow import AgraderWorkflow
class Assignment(AgraderWorkflow):
'''Represents a single assignment (or submassignment) in the view of a single submission,
being possibly composed of different subassignments.
Support... |
import numpy as np
from time import time
from qiskit.circuit import QuantumCircuit, ParameterVector
from qiskit.circuit.library import RealAmplitudes
from surfer.qfi import StochasticApproximation, LinearCombination, ReverseQFI
circuit = RealAmplitudes(5, reps=15)
values = np.ones(circuit.num_parameters)
print(circu... |
#!/opt/manager/env/bin/python
import os
from datetime import datetime
from manager_rest import constants
from manager_rest.storage import models
from manager_rest.storage.models_base import db
from manager_rest.flask_utils import setup_flask_app
def create_system_filters():
with setup_flask_app().app_context():... |
"""
@author: gcanco
Takes line sketch (input.png from input folder) and outputs painterly rendering (output.png into output folder)
"""
from msa.predictor import Predictor
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import cv2
import numpy as np
#read input
def run_pix2pix():
img_in = cv2.imread("input/... |
from __future__ import unicode_literals
import json
from django.db import models
import requests
# Create your models here.
class Recommender(models.Model):
url = models.URLField()
name = models.CharField(max_length=120, default='my-recommender', unique=True)
def __str__(self):
return '{0} - {... |
from itertools import product
from numbers import Number
import numpy as np
import pandas as pd
from skimage.feature import blob_log
from starfish.constants import Indices
from starfish.image import ImageStack
from starfish.munge import dataframe_to_multiindex
from starfish.intensity_table import IntensityTable
from ... |
# -*- coding: utf-8 -*-
"""mcpyrate-enabled `code.InteractiveConsole`.
Special commands:
- `obj?` shows obj's docstring, `obj??` shows its source code.
- `macros?` shows macro bindings.
- `macro(f)` binds a function as a macro. Works also as a decorator.
"""
# Based on `imacropy.console.MacroConsole` by Juha J... |
"""
test for the module `handle_charges`
derived from MolVS's tests: https://github.com/mcs07/MolVS/blob/master/tests/test_charge.py
"""
import pytest
import sys
from rdkit import Chem
from opencadd.compounds.standardization import handle_charges
def _uncharge_smiles(smiles):
"""Utility function that returns t... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020~2999 - Cologler <skyoflw@gmail.com>
# ----------
#
# ----------
def test_find_gist_id():
from gistsync.utils import find_gist_id
assert '8b5d44890d95c58ab41b0fb85cb05dce' == find_gist_id('8b5d44890d95c58ab41b0fb85cb05dce')
assert '8b5d44890d95c58ab41b0fb85cb05... |
from flask import Flask, request
from pymessenger.bot import Bot
from decouple import config
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = f'postgresql://{config("DB_USER")}:{config("DB_PASSWORD")}@{config("DB_HOST")}:5432/{config("DB_NAME")}'
db = SQLAlchemy(ap... |
# -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# 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,... |
from django.apps import AppConfig
class BasicdeviceConfig(AppConfig):
name = 'card_reader'
|
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 5 12:35:23 2017
@author: Flame
"""
from enum import Enum
from colorama import Fore
#from colorama import init
#init(autoreset=False)
EMTY_SYMBOL = '*'
def paint(string, pointer):
out = ""
for i in range(len(string)):
if i == pointer:
out = o... |
# coding=utf-8
# Copyright 2022 The ML Fairness Gym 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... |
"""
This splitter split data for each user separately
"""
from typing import Optional, Union
import pyspark.sql.functions as sf
from pyspark.sql import DataFrame, Window
from replay.constants import AnyDataFrame
from replay.splitters.base_splitter import Splitter, SplitterReturnType
from replay.utils import convert2s... |
"""## The Home Page of awesome-panel.org"""
import pathlib
from panel import Column
from awesome_panel.express._pane._panes import Markdown
HOME_PATH = pathlib.Path(__file__).parent / "home.md"
def view() -> Column:
"""The home view of awesome-panel.org"""
return Column(Markdown(path=HOME_PATH), name="Home... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2020 Lucas Heitzmann Gabrielli.
# This file is part of gdstk, distributed under the terms of the
# Boost Software License - Version 1.0. See the accompanying
# LICENSE file or <http://www.boost.org/LICENSE_1_0.txt>
import gdstk
def test_properties():
fo... |
# -*- coding: utf-8 -*-
import sys
import os
import timeit
import signal
from collections import deque
from operator import methodcaller
timer = timeit.default_timer
class NotMainThreadError(Exception):
'''pyinstrument must be used on the main thread in signal mode'''
def __init__(self, message=''):
... |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... |
import re
def find_patterns(patterns, string):
'''
Takes in a list of regex patterns
Prints a list of all matches
'''
print(f"Searching the string: '{string}'.")
for pattern in patterns:
print(f"\nWith the regex: {pattern}")
print(f"Result: {re.findall(pattern, string)}")
str... |
from ds.tree.binary_tree import BinaryTreeNode
from ds.tree.tree_core import Tree
import math
'''
Given a binary tree in which each node element contains a number.
Find the maximum possible sum from one leaf node to another.
'''
def get_max_path_leaves(root: BinaryTreeNode):
'''
Returns (first, second) where
... |
iot23_scenarios_dir = 'E:\\machine-learning\\datasets\\iot23\\1_scenarios\\'
iot23_attacks_dir = 'E:\\machine-learning\\datasets\\iot23\\2_attacks\\'
iot23_data_dir = 'E:\\machine-learning\\datasets\\iot23\\3_data_v2\\'
iot23_experiments_dir = 'E:\\machine-learning\\datasets\\iot23\\4_experiments_v2\\'
|
"""
PRIME1 - Prime Generator
Peter wants to generate some prime numbers for his crypto-system. Help him! Your task is to generate all prime numbers
between two given numbers!
Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two
numbers m and n (1 <=... |
number = int(input())
sum = 0
while number > 0:
digit = number % 10
sum += digit
number = number // 10
print(sum) |
import ctypes
from pyparallelproj.config import lib_parallelproj_c, lib_parallelproj_cuda, n_visible_gpus
def calc_chunks(nLORs, n_chunks):
""" calculate indices to split an array of length nLORs into n_chunks chunks
example: splitting an array of length 10 into 3 chunks returns [0,4,7,10]
"""
rem = nLOR... |
import random
import math
import logging
from slime_mind.engine.plant import Plant
from slime_mind.engine.slime import Slime
class Sprite_man():
def __init__(self, map, config):
self.map = map
self.conf = config
def check_for_dead(self):
for x in range(self.map.columns):
fo... |
ix.enable_command_history()
app = ix.application
ix.api.SdkHelpers.record_offsets_items_selected(app)
ix.disable_command_history()
|
from contextlib import ExitStack
import contextlib
@contextlib.contextmanager
def first():
print('First')
yield
@contextlib.contextmanager
def second():
print('Second')
yield
for n in range(5):
with ExitStack() as stack:
stack.enter_context(first())
if n % 2 == 0:
stac... |
import sys
sys.path.append(r"C:\src\business-library\python")
from mundusinvicte.networking.sockets.TcpClient import TcpClient
import socket
import os
class WebClient(TcpClient):
def __init__(self, socket, addr):
self.sock = socket
self.addr = addr
self.context = {} |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'selectcert.ui'
#
# Created: Mon Nov 13 12:04:45 2017
# by: PyQt4 UI code generator 4.6.2
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_CertForm(object):
def setupUi(self, CertFor... |
range_list = []
while (line := input()) != '':
_, value_text = line.split(': ')
first_range, second_range = value_text.split(' or ')
a, b = map(int, first_range.split('-'))
c, d = map(int, second_range.split('-'))
range_list.append((a, b))
range_list.append((c, d))
range_list.sort()
_ = inpu... |
from ....models.models import Committee
from ...generics.delete import DeleteAction
from ...util.default_schema import DefaultSchema
from ...util.register import register_action
@register_action("committee.delete")
class CommitteeDeleteAction(DeleteAction):
"""
Action to delete a committee.
"""
model... |
import db
import time
import configs
from sqlalchemy import Column, Integer
from sqlalchemy.orm import declarative_base, Session
class Test(declarative_base()):
__tablename__ = 'test'
id = Column(Integer, primary_key=True, autoincrement=True)
state = Column(Integer, nullable=False)
config = configs.co... |
from ci_framework import FlopyTestSetup, base_test_dir
import flopy
base_dir = base_test_dir(__file__, rel_path="temp", verbose=True)
def test_vdf_vsc():
model_ws = f"{base_dir}_test_vdf_vsc"
test_setup = FlopyTestSetup(verbose=True, test_dirs=model_ws)
nlay = 3
nrow = 4
ncol = 5
nper = 3
... |
"""Miscellaneous functions used in mechpy."""
import numpy as np
def matrix_minor(matrix, indices):
"""Return the minor of a 2D ``numpy.ndarray``.
Parameters
----------
matrix : 2D numpy.ndarray
the matrix from which to find a minor
indices : tuple of ints
a tuple of two values i... |
"""
This file copied from the OpenAI Baseline and slightly adjusted (for stable loss function, see results -> ppo2)
Source: https://github.com/openai/baselines
"""
import tensorflow as tf
import numpy as np
def ortho_init(scale=1.0):
def _ortho_init(shape, dtype):
# lasagne ortho init for tf
s... |
import json
import os
import shutil
import typing as t
from abc import ABC, abstractmethod
import boto3
import requests
from botocore.config import Config
from pydantic import BaseModel
from test.config import FIRESTORE_EMULATOR_HOST
def load_json_file(path) -> t.Any:
with open(path) as f:
return json.l... |
from django.db import models
import random
# Create your models here.
class PostEntryQuery(models.QuerySet):
def published(self):
return self.filter(published=True)
def randomPost(self):
return self.published().order_by('?')[:4]
def getFeaturedPost(self):
return random.choice(self.published())
# c... |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth.models import User
from django.shortcuts import reverse
from django.test import TestCase
from rest_framework.test import APIClient
from ...views.index_views import user_login
from app.models import TheUser
# ------------... |
from xml.dom import minidom
from lxml import etree
import xml.etree.ElementTree as ET
from io import StringIO
import copy
import random
###TODO when update, also put in node thingy
# https://kite.com/python/examples/3486/xml-set-attributes-of-an-xml-element
# https://kite.com/python/examples/3491/xml-add-an-element-a... |
#!/usr/bin/python
# Copyright (c) 2018, Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for detail... |
# -*- coding: iso-8859-1 -*-
"""Output module.
"""
# Copyright (C) 2004, 2005, 2006, 2010 Juan M. Bello Rivas <jmbr@superadditive.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either... |
import torch.nn as nn
import pretrainedmodels
from mlcomp.contrib.torch.layers import LambdaLayer
class Pretrained(nn.Module):
def __init__(self, variant, num_classes, pretrained=True, activation=None):
super().__init__()
params = {'num_classes': 1000}
if not pretrained:
para... |
from typing import List
from fastapi import File, UploadFile
from pydantic import BaseModel
class Text(BaseModel):
text: str
class Words(BaseModel):
words: List[str]
class ImageFile(BaseModel):
file: UploadFile = File(...)
class ExtractedNER(BaseModel):
text: str
start: int
end: int
... |
# -*- coding: utf-8 -*-
"""
:author @CAB233
:url https://github.com/CAB233/everphoto_checkin
cron: 3 22 * * *
new Env('时光相册');
"""
import json
import requests
from notify_mtr import send
from utils import get_data
class EverPhoto:
def __init__(self, check_items):
self.check_items = check_items
def... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Initialise '.
Must be called before using '.
This commands should be called from the top directory of your project or with
the path to the top directory as an argument.
The command will create a hidden directory called .and copy the default
settings into this director... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2017, AGB & GC
# Full license can be found in License.md
# ----------------------------------------------------------------------------
""" Functions that specify the boundary location as a function of MLT
Functions
---------
circular(mlt, [r_add])
Retu... |
# -*- coding: utf-8 -*-
#
# Copyright (C)2006-2009 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consis... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Description :Dump data to file
@Time :2020/08/27 16:01:59
@Author :sam.qi
@Version :1.0
'''
import traceback
from mp.dump.dump import Dump
class FileDump(Dump):
def __init__(self, filepath):
super().__init__()
self.fi... |
# coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
from unittest import TestCase
from mock import patch
from pyqrllib.pyqrllib import sha2_256
from tests.misc.helper import get_alice_xmss, get_bob_xmss
from qrl.core im... |
from django.shortcuts import render
from rest_framework import viewsets
# Create your views here.
from employees.serializers import EmployeeSerializer
from employees.models import Employee
from employees.pagination import MyPagination
class EmployeeViewSet(viewsets.ModelViewSet):
queryset = Employee.objects.al... |
from output.models.sun_data.mgroup.particles.particles00303m.particles00303m1_xsd.particles00303m1 import A
__all__ = [
"A",
]
|
import os.path
import pandas as pd
from pathlib import Path
old_file = "data/nmdc_test_data_valid.tsv"
extension_val = ".tsv"
suffix_val = "_lowercased"
path_prefix = "artifacts"
basename = Path(old_file).stem
with_extension = basename + suffix_val + extension_val
with_path = os.path.join(path_prefix, with_extensi... |
# -*- coding:utf-8 -*-
"""
@version: 1.0
@author: kevin
@license: Apache Licence
@contact: liujiezhang@bupt.edu.cn
@site:
@software: PyCharm Community Edition
@file: adios_train.py
@time: 17/05/03 17:39
"""
import json
import os
import time
from math import ceil
import numpy as np
import tensorflow as tf
import yaml
f... |
"""A (very) simple banning & rate limiting extension for Flask.
"""
from inspect import signature
import time
from collections import deque
from functools import wraps
from flask import request
class IP:
def __init__(self, ban_count, rate_count):
"""IP record that keeps track of reports and requests made... |
'''
png2svg.py - arrange several bitmat images into a single image
==============================================================
:Author: Andreas Heger
:Release: $Id$
:Date: |today|
:Tags: Python
Purpose
-------
This script takes a collection of .png files and outputs an .svg file
arranging the images side by side ... |
"""
Django forms for the JASMIN services app.
"""
__author__ = "Matt Pryor"
__copyright__ = "Copyright 2015 UK Science and Technology Facilities Council"
from django import forms
from django.contrib.contenttypes.models import ContentType
from .models import Metadatum
class MetadataForm(forms.Form):
"""
For... |
# -*- coding: utf-8 -*-
# @Author: yulidong
# @Date: 2018-07-31 20:35:41
# @Last Modified by: yulidong
# @Last Modified time: 2018-08-07 21:21:19
import os
import numpy as np
from sklearn.cluster import MeanShift, estimate_bandwidth
import time
import cv2
import torch
COLOR=[np.array([255,0,0]),
np.array([0... |
# -*- coding: utf8 -*-
from qrcodeocr.app import api_statistics
from qrcodeocr.test.test_base import TestBase
class TestApiStatistics(TestBase):
def test_ApiFundStats(self):
"""
test fund statistics api
:return:
"""
res = api_statistics.get_fund_stats(howfund_id=self.h... |
from tensorflow.keras.layers import Input, Conv2D, LeakyReLU, Concatenate
from tensorflow.keras.models import Model
import tensorflow.keras.backend as K
from convhole import ConvHole2D
def get_blindspot_model(input_shape, out_channels, depth=11, kernel_initializer=None, bias_initializer=None):
inputs = Input(shap... |
# Mininet defaults
from mininet.node import OVSSwitch
from mininet.node import UserSwitch
# from mininet.node import OVSLegacyKernelSwitch
# Custom switches
|
from datetime import date, timedelta
from dateutil.parser import parse
def working_days(year, weekend=(5, 6), holidays=tuple()):
year_start, year_end = date(year, 1, 1), date(year, 12, 31)
year_range = range((year_end - year_start).days + 1)
year_dates = (year_start + timedelta(x) for x in year_range)
... |
import os
import pickle
import numpy as np
from PIL import Image
def unpickle(fp):
load_dict = 0
with open(fp, 'rb') as fid:
load_dict = pickle.load(fid, encoding = 'bytes')
return load_dict
'''
https://github.com/amir-saniyan/AlexNet/blob/master/dataset_helper.py
'''
def get_cifar_10(image_wi... |
# -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, with_statement
import datetime
import json
from copy import deepcopy
from bson.objectid import ObjectId
from turbo.util import escape, basestring_type
from util import unittest
class EscapeTest(unittest.TestCase):
def te... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 10
@author: jaehyuk
"""
from random import random
import numpy as np
import scipy.stats as ss
import scipy.optimize as sopt
import pyfeng as pf
import scipy.integrate as spint
from . import bsm
'''
MC model class for Beta=1
'''
class ModelBsmMC:
beta = 1.0 # fixed ... |
empty = object() |
#!/usr/bin/env python
"""
MegaPBTree, non-redundant set of gene annotations for
combining collapsed GFFs from mulitiple smaples.
The original file name: combine_abundance_across_samples.py
"""
import copy
from collections import defaultdict
from pbtranscript.collapsing import IntervalTree, compare_fuzzy_junctions
from... |
import torch
from UnarySim.kernel import FSUMul
from UnarySim.stream import RNG, BinGen, BSGen
from UnarySim.metric import ProgError
import matplotlib.pyplot as plt
import time
import math
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def test_fsumul_in_stream():
bitwidth = 12
depth ... |
# -*- coding: UTF-8 -*-
import sys
import textwrap
import click
import tweepy
from blabbr.config import Config
from blabbr.model import ModelBuilder, TwitterDigger
from blabbr.twitter import TwitterClient
from blabbr.bot import Bot
class Cli:
def __init__(self, cfg=None, model=None, **kw):
self.cfg = C... |
from heapq import heappush, heappop
class Solution:
def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
if not nums1 or not nums2:
return []
heap = [(nums1[0] + nums2[0], 0, 0)]
seen = set((0, 0))
result = []
... |
from ..code.web.scraper.scrap.walmart import get_url_walmart, scrap_walmart
from . import setup_get_driver_details
def test_get_url_walmart_1():
item_name = "SAMSUNG Galaxy Tab A7 32GB"
assert (
get_url_walmart(item_name)
== "https://www.walmart.com/search?q=SAMSUNG+Galaxy+Tab+A7+32GB"
)
... |
#!/usr/bin/env python
"""
Download interface for data from RAOB network
"""
import sys
import cgi
import datetime
import pytz
from pyiem.util import get_dbconn, ssw
from pyiem.network import Table as NetworkTable
def m(val):
"""Helper"""
if val is None:
return 'M'
return val
def fetcher(station... |
#!/usr/bin/env python
#
# Copyright (C) 2006-2008 Async Open Source
# Henrique Romano <henrique@async.com.br>
# Johan Dahlin <jdahlin@async.com.br>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Publ... |
##
# 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, software
# distributed under the... |
# Copyright 2016 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LI... |
cities=['北京北', '北京东', '北京', '北京南', '北京西', '广州南', '重庆北', '重庆', '重庆南', '广州东', '上海', '上海南', '上海虹桥', '上海西', '
天津北', '天津', '天津南', '天津西', '长春', '长春南', '长春西', '成都东', '成都南', '成都', '长沙', '长沙南', '福州', '福州南', '贵阳', '广州', '广
州西', '哈尔滨', '哈尔滨东', '哈尔滨西', '合肥', '合肥西', '呼和浩特东', '呼和浩特', '口东', '海口东', '海口', '杭州东', '杭州', '杭州南', '济南', '
济... |
# Copyright The PyTorch Lightning 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 i... |
from fly_behavior import FlyBehavior
class FlyWithWings(FlyBehavior):
def fly(self):
print('I\'m flying')
|
import base64
import inspect
class Private(object):
"""
This class attempts to keep private information.
Clearly this is python so we cannot actually achieve that aim.
Any attacker could easily monkey patch out any of this code rendering it
useless.
The point of this is to make the code less... |
import compas_rrc as rrc
if __name__ == "__main__":
# Create Ros Client
ros = rrc.RosClient()
ros.run()
# Create ABB Client
abb = rrc.AbbClient(ros, "/rob1")
print("Connected.")
# Stop the motion tast
future = abb.send(rrc.Stop(feedback_level=rrc.FeedbackLevel.DONE))
# Execute o... |
sword_left='''
.
;-{<>===>
`'''
sword_right='''
.
<===<>}-;
´''' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.