content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# Copyright (c) 2011-2020 Eric Froemling
#
# 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, publish,... | python |
#!/usr/bin/env python
from avro.io import BinaryEncoder, BinaryDecoder
from avro.io import DatumWriter, DatumReader
import avro.schema
from io import BytesIO
import argo_ams_library
from argo_ams_library import ArgoMessagingService
import argparse
import base64
import logging
import logging.handlers
import sys
import ... | python |
from datetime import datetime
from itertools import chain
from random import randint
from django.contrib.auth.decorators import login_required
from django.contrib.formtools.wizard.views import SessionWizardView
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.utils.decorators impo... | python |
'''
visualize VIL-100 datasets in points form or curves form.
datasets name:vil-100
paper link: https://arxiv.org/abs/2108.08482
reference: https://github.com/yujun0-0/MMA-Net/tree/main/dataset
datasets structure:
VIL-100
|----Annotations
|----data
|----JPEGImages
|----Json
|----trai... | python |
from __future__ import print_function
import os
import re
import sqlite3
import sys
import traceback
import simpy
from vcd import VCDWriter
from . import probe
from .util import partial_format
from .timescale import parse_time, scale_time
from .queue import Queue
from .pool import Pool
class Tracer(object):
na... | python |
from pyhafas.profile import ProfileInterface
from pyhafas.profile.interfaces.helper.parse_lid import ParseLidHelperInterface
from pyhafas.types.fptf import Station
class BaseParseLidHelper(ParseLidHelperInterface):
def parse_lid(self: ProfileInterface, lid: str) -> dict:
"""
Converts the LID given... | python |
from __future__ import print_function, absolute_import
import torch
from torch.optim.lr_scheduler import _LRScheduler
from bisect import bisect_right
AVAI_SCH = ['single_step', 'multi_step', 'cosine', 'multi_step_warmup']
def build_lr_scheduler(optimizer,
lr_scheduler='single_step',
... | python |
"""
File: rocket.py
Name:Claire Lin
-----------------------
This program should implement a console program
that draws ASCII art - a rocket.
The size of rocket is determined by a constant
defined as SIZE at top of the file.
Output format should match what is shown in the sample
run in the Assignment 2 Handout.... | python |
from enum import Enum
class RecipeStyle(Enum):
"""
Class for allrecipes.com style labels
"""
diabetic = 'diabetic'
dairy_free = 'dairy_free'
sugar_free = 'sugar-free'
gluten_free = 'gluten_free'
low_cholesterol = 'low_cholesterol'
mediterranean = 'mediterranean'
chinese = 'chin... | python |
from typing import Union, List, Optional
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType
# This file is auto-generated by generate_schema so do not edit manually
# noinspection PyPep8Naming
class ImplementationGuide_PageSchema:
"""
A set of rules of how FHIR is used to ... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-15 01:52
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
... | python |
from rallf.sdk.logger import Logger
from rallf.sdk.network import Network
from rallf.sdk.listener import Listener
class Task:
def __init__(self, manifest, robot, input, output):
self.manifest = manifest
self.robot = robot
self.finished = False
self.status = "stopped"
self.... | python |
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^$',
views.IndexView.as_view(),
name='index'),
re_path(r'^(?P<pk>[-\w]+)/$',
views.PageDetailView.as_view(),
name='page_detail'),
]
| python |
import unittest
import time
from liquidtap.client import Client
class TestClient(unittest.TestCase):
def setUp(self) -> None:
self.client = Client()
self.client.pusher.connection.bind('pusher:connection_established', self._on_connect)
def _on_connect(self, data: str):
print('on_conne... | python |
class NopBackpressureManager:
def __init__(self):
pass
def register_pressure(self):
pass
def unregister_pressure(self):
pass
def reached(self) -> bool:
return False
class BackpressureManager:
def __init__(self, max):
self.max = max
self.pressure... | python |
import re
import croniter
from datetime import timedelta, datetime
from functools import partial
from airflow import DAG
from airflow.sensors.external_task import ExternalTaskSensor
from dagger import conf
from dagger.alerts.alert import airflow_task_fail_alerts
from dagger.dag_creator.airflow.operator_factory import... | python |
from __future__ import absolute_import
from collections import defaultdict, Sequence, OrderedDict
import operator
from string import capwords
import numpy as np
from .elements import ELEMENTS
# records
MODEL = 'MODEL '
ATOM = 'ATOM '
HETATM = 'HETATM'
TER = 'TER '
MODEL_LINE = 'MODEL ' + ' ' * 4 + '{:>4d}\n'
END... | python |
# Copyright 2017-2020 TensorHub, 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... | python |
"""Module for raceplan exceptions."""
class CompetitionFormatNotSupportedException(Exception):
"""Class representing custom exception for command."""
def __init__(self, message: str) -> None:
"""Initialize the error."""
# Call the base class constructor with the parameters it needs
su... | python |
################ Running: F:\users\emiwar\edited_new\catAtt.py #################
COM1
Serial<id=0x52b47f0, open=True>(port='COM1', baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=2.5, xonxoff=False, rtscts=False, dsrdtr=False)
492
1 False [('b', 1.378630934454577)]
1 finished.
2 desert [('b', 1.37283... | python |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: server_admin.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _... | python |
import tensorflow as tf
from tensorflow.keras.applications import InceptionV3
__all__ = ["inception_score"]
def inception_score(images):
r"""
Args:
images: a numpy array/tensor of images. Shape: NxHxWxC
Return:
inception score
"""
img_shape = images.shape
if img_shape[1] !=... | python |
from django.dispatch import receiver
from django.db.models.signals import post_save, post_delete
from django.core.mail import send_mail
from .models import Profile
from django.conf import settings
SUBJECT = 'WELCOME TO DEVCONNECT'
MESSAGE = """ Congratulation I have to say thank you for creating a new account
with our... | python |
"""
Setup file for installation of the dataduct code
"""
from setuptools import find_packages
from setuptools import setup
from dataduct import __version__ as version
setup(
name='dataduct',
version=version,
author='Coursera Inc.',
packages=find_packages(
exclude=["*.tests", "*.tests.*", "test... | python |
import re
f = open("regex.txt", "r")
content = f.readlines()
# s = 'A message from cs@uni.edu to is@uni.edu'
for i in range(len(content)):
if re.findall('[\w\.]+@[\w\.]+', content[i]):
print(content[i], end='') | python |
"""
Command-line interface implementing synthetic MDS Provider data generation:
- custom geographic area, device inventory, time periods
- generates complete "days" of service
- saves data as JSON files to container volume
All fully customizable through extensive parameterization and configuration options.
"""
... | python |
class Cache:
# private with __
__store = {}
# THIS BLOCK demo for PROTECTED if required - Single _
# _protected_store = {}
#
# @property
# def protected_store(self):
# return self._protected_store
def get(self, key):
if key:
try:
value_for_k... | python |
b = "Hello, World!"
print(b[:5])
| python |
#!/usr/bin/python3
import argparse
import os
import random
import logging
import tensorflow as tf
import numpy as np
from PIL import Image
from unet import UNet, Discriminator
from scripts.image_manips import resize
model_name = "matting"
logging.basicConfig(level=logging.INFO)
# Parse Arguments
def parse_args():... | python |
from setuptools import setup
setup(name='socialsent',
version='0.1.2',
description='Algorithms for inducing domain-specific sentiment lexicons from unlabeled corpora.',
url='https://github.com/williamleif/socialsent',
author='William Hamilton',
author_email='wleif@stanford.edu',
lic... | python |
########################################################################
# SwarmOps - Heuristic optimization for Python.
# Copyright (C) 2003-2016 Magnus Erik Hvass Pedersen.
# See the file README.md for instructions.
# See the file LICENSE.txt for license details.
# SwarmOps on the internet: http://www.Hvass-Labs.org/... | python |
# -*- coding: utf-8 -*-
"""
Created on Mar 23 11:57 2017
@author: Denis Tome'
"""
__all__ = [
'VISIBLE_PART',
'MIN_NUM_JOINTS',
'CENTER_TR',
'SIGMA',
'STRIDE',
'SIGMA_CENTER',
'INPUT_SIZE',
'OUTPUT_SIZE',
'NUM_JOINTS',
'NUM_OUTPUT',
'H36M_NUM_JOINTS',
'JOINT_DRAW_SIZE',... | python |
# coding: utf-8
"""
Ed-Fi Operational Data Store API
The Ed-Fi ODS / API enables applications to read and write education data stored in an Ed-Fi ODS through a secure REST interface. *** > *Note: Consumers of ODS / API information should sanitize all data for display and storage. The ODS / API provides reas... | python |
# -*- coding: utf-8 -*-
__doc__="返回选择物体的类型"
import rpw
from rpw import revit, DB, UI,db,doc
from System.Collections.Generic import List
import json
import subprocess as sp
#from MyLib.Adaptor import BAT_Wall
from Adaptor import BAT_ElementMaterial
from Helper import *
#根据Accessmbly Code 筛选构件
title="根据Accessmbly筛选构件价格... | python |
#!/usr/bin/env python
'''
This script will generate a convenient <.csv> detailing the nucleotide composition of
sequences in fasta format. This <.csv> may be imported and merged with other <.csv>s to build
a comprehensive data sheet.
'''
#Imports
from collections import Counter
from Bio import SeqIO
from Bio.Seq im... | python |
#7. Desarrolle el programa que determine el área y
# el perímetro de un rectángulo sabiendo que el área = b x h, perímetro = 2x (b+h).
B=float(input("Ingresa el B: "))
H=float(input("Ingresa el H: "))
area=(B*H)
perim=2*(B+H)
print("El Area es : ",area)
print("El perimetro es : ", perim)
| python |
from typing import List
from webdnn.backend.code_generator.allocator import MemoryLayout
from webdnn.backend.fallback.generator import FallbackDescriptorGenerator
from webdnn.backend.fallback.kernel import Kernel
from webdnn.graph.operators.concat import Concat
source = """
concat: function(input_arrays, output_array... | python |
import logging
import sys
import signal
import time
import os
from networktables import NetworkTables
import csv
from Adafruit_BNO055 import BNO055
import RPi.GPIO as GPIO
NetworkTables.initialize()
nt = NetworkTables.getTable("IMU_Data")
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(17, GPIO.OUT)
GPI... | python |
#2. Sorteie 20 inteiros entre 1 e 100 numa lista. Armazene os números
#pares na lista PAR e os números ímpares na lista IMPAR. Imprima as três listas.
import random
num = 0
controle = 0
pares = []
impares = []
todos = []
a , b = 0 , 0
while(controle <=19):
num = random.randrange(1,100)
todos.in... | python |
from material.frontend import Module
class Sample(Module):
icon = 'mdi-image-compare'
| python |
# -*- coding: utf-8 -*-
"""Submit a test calculation on localhost.
Usage: verdi run submit.py
"""
from __future__ import absolute_import
from __future__ import print_function
import os
from aiida_ce import tests, helpers
from aiida.plugins import DataFactory, CalculationFactory
from aiida.engine import run
# get code... | python |
# pylint: disable=C0103,R0201
from typing import Tuple, Union, Callable, Optional, Any
from django.http import HttpResponse
from django.urls import re_path, path, URLPattern, URLResolver
# in case of include we get a tuple
ViewType = Optional[Union[Callable[..., HttpResponse], Tuple[Any, Any, Any]]]
class url:
... | python |
import paho.mqtt.client as mqtt
import sqlite3
import datetime
broker_address = "127.0.0.1"
dataToPush = {}
changed = []
bedToSub = []
bedToId = {} # lookup dict
def getBeds(db):
"""
Populate the bedToSub list from the db
"""
global bedToSub
cursorDb = db.cursor()
command = "SELECT WardNo, B... | python |
import copy
import time
from .core import ProgramLearningAlgorithm
from program_graph import ProgramGraph
from utils.logging import log_and_print, print_program, print_program_dict
from utils.training import execute_and_train
class ENUMERATION(ProgramLearningAlgorithm):
def __init__(self, max_num_programs=100):... | python |
from __future__ import division
import sys, glob
sys.path.append('/home/richard/scicore/GROUP/data/2017_Karolinska_EV-D68/SVVC/src')
sys.path.append('/scicore/home/neher/GROUP/data/2017_Karolinska_EV-D68/SVVC/src')
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
#import seaborn as... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 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 ... | python |
# kakao api 사용=>계정등록=>앱생성=>인증키 발급(restful key)
from urllib.request import urlopen
import xmltodict
import pandas as pd
import datetime
from sqlalchemy import create_engine
def upload_data():
GEV_API = 'STUV378914'
url= 'http://api.gevolution.co.kr/rank/xml/?aCode={GEV_API}&market=g&appType=game&rankType=1&ra... | python |
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter, AutoMinorLocator
import matplotlib as mpl
# Make some style choices for plotting
color_wheel = ['#329932',
'#ff6961',
'b',
'#6a3d9a',
... | python |
customer = {
"name": "Fahad Hafeez",
"age": 30,
"is_verified": True,
}
customer["name"] = "Fahad Hafeez"
print(customer.get("birthdate", "Oct 18 2005")) | python |
#
# Turn off logging in extensions (too loud!)
import vb2py.extensions
import unittest
vb2py.extensions.disableLogging()
import vb2py.vbparser
vb2py.vbparser.log.setLevel(0) # Don't print all logging stuff
from vb2py.plugins.attributenames import TranslateAttributes
class TestAttributeNames(unittest.TestCase):
... | python |
"""
=============================================================
Bisecting K-Means and Regular K-Means Performance Comparison
=============================================================
This example shows differences between Regular K-Means algorithm and Bisecting K-Means.
While K-Means clusterings are different w... | python |
#!/usr/bin/env python2.7
'''
Copyright 2018 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 t... | python |
# python src/chapter11/chapter11note.py
# python3 src/chapter11/chapter11note.py
'''
Class Chapter11_1
Class Chapter11_2
Class Chapter11_3
Class Chapter11_4
Class Chapter11_5
'''
from __future__ import division, absolute_import, print_function
import sys as _sys
import math as _math
import random as _random
imp... | python |
from dataclasses import dataclass, field
from itertools import product as product_
from typing import (Callable, Dict, Iterable, Iterator, List, Optional, Tuple,
Union)
import pandas as pd
from ivory.common.context import np
from ivory.common.dataset import Dataset
from ivory.core.model import Mod... | python |
from __future__ import annotations
import pytest
import resist
class TestUser:
@pytest.fixture()
def client(self) -> resist.WebSocketClient:
return resist.WebSocketClient("REVOLT_TOKEN")
def test_attributes(self, client: resist.WebSocketClient) -> None:
user = resist.User(client, {"_id"... | python |
# -*- coding: utf-8 -*-
# @Time : 18/12/10 上午10:35
# @Author : Edward
# @Site :
# @File : DynamicPool.py
# @Software: PyCharm Community Edition
import time
from threading import Thread
from multiprocessing import Process
class Pool(object):
'''
阻塞动态线程池。
创建完线程池后,可以动态地往里面丢任务。不用预先构建完要执行的任务,可以边执行边... | python |
try:
import json
except ImportError:
import simplejson as json
from createsend import CreateSendBase, BadRequest
from utils import json_to_py
class Administrator(CreateSendBase):
"""Represents an administrator and associated functionality."""
def __init__(self, email_address=None):
self.email_address = em... | python |
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import json
import random
import logging
from datetime import datetime
gm_logger = logging.getLogger('grounding_mapper')
gm_logger.setLevel(logging.WARNING)
sm_logger = logging.getLogger('sitemapper')
s... | python |
from pandac.PandaModules import *
from direct.directnotify import DirectNotifyGlobal
from direct.showbase.DirectObject import DirectObject
from toontown.minigame import ToonBlitzGlobals
from toontown.minigame import TwoDSection
from toontown.minigame import TwoDSpawnPointMgr
from toontown.minigame import TwoDBlock
from... | python |
import numpy as np
"""
Solve the standard linear programming problem:
maximize c^{T}x
s. t. Ax <= b and x >= 0
by the simplex method.
Remind, enter A, b as usually, but enter -c into the varible c.
For example, try to minimize
x_{1} + x_{2}
s. t. ([1, 2], [3, 4])x <= (5, 6) and x >= 0
then
A = np.array([
... | python |
# -*- coding: utf-8 -*-
# Copyright 2018 Whitestack, LLC
# *************************************************************
# This file is part of OSM Monitoring module
# All Rights Reserved to Whitestack, LLC
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... | python |
from dataclasses import dataclass
from .flipper_output import FlipperOutput
@dataclass
class Paddle:
x: int = 0
y: int = 0
direction: int = 0
def update(self, output: FlipperOutput):
if self.x > output.x:
self.direction = -1
elif self.x < output.x:
self.direction... | python |
"""
Zendesk Proxy Configuration
"""
from django.apps import AppConfig
from edx_django_utils.plugins import PluginURLs, PluginSettings
from openedx.core.djangoapps.plugins.constants import ProjectType, SettingsType
class ZendeskProxyConfig(AppConfig):
"""
AppConfig for zendesk proxy app
"""
name = ... | python |
# Copyright 2014 Emmanuele Bassi
#
# SPDX-License-Identifier: MIT
#
# 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, cop... | python |
#!/usr/bin/python2.5
# Copyright (C) 2007 Google 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 la... | python |
from Session import Session
from Letter import Letter
from Word import Word
from Grid import Grid
from ApiException import ApiErrorCode, ApiException | python |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Venue.website'
db.alter_column(u'venues_venue', 'website', self.gf('django.db.models.fiel... | python |
import asyncio
import os
import fastapi
# noinspection PyPackageRequirements
import pytest
from jinja2.exceptions import TemplateNotFound
from starlette.requests import Request
import fastapi_jinja as fj
here = os.path.dirname(__file__)
folder = os.path.join(here, "templates")
fake_request = Request(scope={'type': ... | python |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 15 17:02:33 2020
@author: lenovo
"""
# AdaBoost
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.datasets import load_iris
from sklearn.ensemble import AdaBoostClassifier
X, y = load_iris(return_X_y=Tru... | python |
# native packs
import requests
import json
# installed packs
import pandas as pd
from pandas import json_normalize
auth_endpoint = "https://auth.emsicloud.com/connect/token" # auth endpoint
# replace 'your_client_id' with your client id from your api invite email
client_id = "5f379hywuvh7fvan"
# replace 'your_clien... | python |
from collections import Counter
def duplicate_sandwich(arr):
check=Counter(arr)
temp1=arr.index(check.most_common()[0][0])
temp2=arr[temp1+1:].index(check.most_common()[0][0])
return arr[temp1+1:temp2+temp1+1]
| python |
import math
from django.urls import reverse
from elasticsearch import Elasticsearch
from elasticsearch.client import IndicesClient
from .utils import escape_reserved_characters
MAIN_INDEX_NAME = 'main_index'
PAGE_SIZE = 10
class Elastic:
def __init__(self):
self.es = Elasticsearch(['http://elasticsearch... | python |
"""Module for storing coinchoose data in the database."""
import coinchoose
from datetime import datetime
from datetime import timedelta
from decimal import Decimal
import os
import psycopg2 as pg2
import psycopg2.extras as pg2ext
import random
import unittest
# Configuration variables
batchLimit = 1000
tables = {
... | python |
# ROS imports
import roslib; roslib.load_manifest('freemovr_engine')
import scipy.optimize
import imageio
from pymvg.camera_model import CameraModel
from pymvg.util import get_rotation_matrix_and_quaternion
import freemovr_engine.simple_geom as simple_geom
import numpy as np
import os
import cv2
PLOT=int(os.environ.g... | python |
# Generated by Django 2.2.20 on 2021-10-04 09:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('deeds', '0008_deed_target'),
]
operations = [
migrations.AddField(
model_name='deed',
name='enable_impact',
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import json
from .property import Property
from .util import text, unicode_obj
from .propertymapping import ConstantPropertyMapping, DirectPropertyMapping, ConcatPropertyMapping
__author__ = "nebula"
variable_meta_registry = dict(... | python |
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from config import config
from glob import glob
import imp
SQLALCHEMY_TRACK_MODIFICATIONS = False
plugins = []
bootstrap = Bootstrap()
db = SQLAlchemy()
login_manager = LoginManag... | python |
import gdb
def format_plan_tree(tree, indent=0):
'formats a plan (sub)tree, with custom indentation'
# if the pointer is NULL, just return (null) string
if (str(tree) == '0x0'):
return '-> (NULL)'
# format all the important fields (similarly to EXPLAIN)
retval = '''
-> %(type)s (cost=%(startup).3f...%(total).... | python |
# ptext module: place this in your import directory.
# ptext.draw(text, pos=None, **options)
# Please see README.md for explanation of options.
# https://github.com/cosmologicon/pygame-text
from __future__ import division, print_function
from math import ceil, sin, cos, radians, exp
from collections import namedtup... | python |
#it2.py
import json
import argparse
import funcy
import os, shutil
from sklearn.model_selection import train_test_split
'''
#train_dir = '/home/data/130/train_split.json'
#os.makedirs('train2017', exist_ok=True)
#test_dir = '/home/data/130/test_split.json'
#os.makedirs('test2017', exist_ok=True)
parser = argparse.Argu... | python |
import os.path, sys, re, cv2, glob, numpy as np
import os.path as osp
from tqdm import tqdm
from IPython import embed
import scipy
import matplotlib.pyplot as plt
from skimage.transform import resize
from mpl_toolkits.mplot3d import Axes3D
from sklearn.metrics import auc
from matplotlib.patches import Circle
import to... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2015,掌阅科技
All rights reserved.
摘 要: __init__.py
创 建 者: zhuangshixiong
创建日期: 2015-10-10
'''
if __name__ == '__main__':
pass
| python |
# Copyright (c) 2018 PaddlePaddle 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 app... | python |
import os
from foliant.preprocessors.apireferences.classes import BadConfigError
from foliant.preprocessors.apireferences.classes import WrongModeError
from foliant.preprocessors.apireferences.classes import get_api
from unittest import TestCase
def rel_name(path: str):
return os.path.join(os.path.dirname(__file... | python |
"""
translatory.py
Takes either english or french phrase and converts to french and english
"""
import json
from ibm_watson import LanguageTranslatorV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
import os
from dotenv import load_dotenv
load_dotenv()
"""translator_instance"""
apikey_lt = os.envir... | python |
from Crypto.Util.number import bytes_to_long, getPrime, inverse
m = b'flag{4cce551ng_th3_subc0nsc10us}'
p = getPrime(512)
q = getPrime(512)
N = p*q
e = 0x10001
d = inverse(e,(p-1)*(q-1))
c = pow(bytes_to_long(m),e,N)
print(f'Modulus: {N}\nOne factor of N: {p}\nPublic key: {e}\nCiphertext: {c}')
| python |
# BSD 2-Clause License
# Copyright (c) 2020, Allen Cheng
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
... | python |
import random
import pytest
import geomstats.backend as gs
from geomstats.geometry.hyperbolic import Hyperbolic
from geomstats.geometry.hyperboloid import Hyperboloid
from tests.data_generation import _LevelSetTestData, _RiemannianMetricTestData
# Tolerance for errors on predicted vectors, relative to the *norm*
# o... | python |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from mocker.endpoints import grpc_endpoint_pb2 as mocker_dot_endpoints_dot_grpc__endpoint__pb2
class MockServiceStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Con... | python |
# Description:
# Functions that deal with data generation/manipulation
# Imports:
import game_mechanics as gm
import GUI
import numpy as np
from keras.utils.np_utils import to_categorical
from _collections import deque
import os
# Constants:
board_len = 30
# Functions:
def moves_to_board(moves... | python |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... | python |
import numpy as np
import pandas as pd
import tensorflow as tf
import sys
import csv
import random
import os
from io import StringIO
import keras
from keras.layers import Input,Dense,concatenate,Dropout,LSTM
from keras.models import Model,load_model
from keras.optim... | python |
from django.test import TestCase
from hknweb.academics.tests.utils import ModelFactory
class QuestionModelTests(TestCase):
def setUp(self):
question = ModelFactory.create_question()
self.question = question
def test_basic(self):
pass
| python |
from modules.module_base import ModuleBase
import urllib.request
import json
from tools.limitator import Limitator, LimitatorLimitted, LimitatorMultiple
class ModuleAss(ModuleBase):
def __init__(self, bot):
ModuleBase.__init__(self, bot)
self.name = "ModuleAss"
self.Url = "http://api.obut... | python |
# @AUTHOR: Piplopp <https://github.com/Piplopp>
# @DATE: 05/2017
#
# @DESC This script generates a blank template for translation of the fire emblem
# heroes unit names, weapons, assit, special and passive skills for the
# feh-inheritance-tool <https://github.com/arghblargh/feh-inheritance-tool>.
#
# It will parse the ... | python |
from . import *
class AWS_OpsWorksCM_Server_EngineAttribute(CloudFormationProperty):
def write(self, w):
with w.block("engine_attribute"):
self.property(w, "Value", "value", StringValueConverter())
self.property(w, "Name", "name", StringValueConverter())
class AWS_OpsWorksCM_Server(CloudFormationRe... | python |
#!/usr/bin/env python
from PIL import Image, ImageDraw
import random as pyrandom
import sys
import os.path
import shutil
import re
import subprocess
import numpy as np
from glob import glob
import argparse
# from matplotlib.pyplot import imread
from scipy.ndimage import filters, interpolation, morphology, measurements... | python |
# Copyright 2017 Insurance Australia Group Limited
#
# 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... | python |
GROUPS_OF = """
CREATE OR REPLACE FUNCTION cognition.groupsof(username text)
RETURNS setof text AS $$
DECLARE rolename pg_roles.rolname%TYPE;
BEGIN
FOR rolename IN
SELECT a.rolname FROM pg_authid a
WHERE pg_has_role(username,... | python |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import os
import random
import numpy as np
import torch
import torchvision
import torchvision.datasets as datasets
import torchvision.transforms as transforms
# import splitfolders #only needed for train/test split folder creation
# In[3]:
#here's the line of code I... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.