content stringlengths 5 1.05M |
|---|
class Person:
id_counter = 0
def __init__(self, name: str, surname: str):
self.name = name
self.surname = surname
self.id = Person.id_counter
Person.id_counter += 1
def __add__(self, other):
return Person(self.name, other.surname)
def __repr__(self):
re... |
# -*- coding: utf-8 -*-
'''load metrics input module
'''
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
with_statement,
)
import logging
import re
from metricol.inputs import MetricInput
LOG = logging.getLogger(__name__)
METRIC_RE = re.compile(r'^([.0-9]... |
# coding: utf-8
import os
import sys
sys.path.append('..')
from Natural_Language_Processing.common.np import *
import pickle
from Natural_Language_Processing.common.util import create_contexts_target, to_cpu, to_gpu
dataset_dir = os.path.dirname(os.path.abspath(__file__))
def load_vocab():
vocab_path =... |
from glob import glob
import json
import torch
import re
import numpy as np
from collections import Counter
from cytoolz import curry, concat
@curry
def to_sep(s,p):
return p[0].sub('_',p[1].sub('',s)).strip().split('_')
sepf= to_sep(p=[re.compile("[\^\`]"), re.compile("\s+")])
cwords = set("' . ' ( ) ·".split()+[... |
import pickle, shelve
from pathlib import Path
import sys, re
def load_kb(kb_file='kb_no_empties.pickle'):
if not Path(kb_file).is_file():
print("Error: No KB file found", file=sys.stderr)
return
with open(kb_file, "rb") as pf:
d = pickle.load(pf)
syscalls = pickle.load(pf)
... |
import sys
import numpy as np
input_file = sys.argv[1]
V = float(input_file.split('_V')[1].split('_T')[0])
T = float(input_file.split('_T')[1].split('.dat')[0])
mean_gce = V * T*T*T / (3.141592635**2 * 0.197327053**3)
nevents = 0
mult = []
with open(input_file, 'r') as f:
# header
f.readline()
f.readline()... |
import os
import pytest
import parsl
from parsl import bash_app
from parsl.tests.configs.local_threads import fresh_config
def half_handler(*args):
"""Cost 0.5 for each retry, not the default of 1"""
return 0.5
local_config = fresh_config()
local_config.retries = 2
local_config.retry_handler = half_handler... |
import multiprocessing
import sys
import argparse
from PolTools.utils.get_region_length import determine_region_length
from PolTools.utils.make_transcripts_dict import build_transcripts_dict
from PolTools.utils.print_tab_delimited import print_tab_delimited
from PolTools.utils.verify_region_length_is_even import verif... |
from typing import Optional, List
from sharpy.plans.acts import ActBase
from sharpy.managers.roles import UnitTask
from sc2 import UnitTypeId, Race, AbilityId
from sc2.unit import Unit
from sharpy.tools import IntervalFunc
class WorkerRallyPoint(ActBase):
"""Handles setting worker rally points"""
ability: A... |
import time
start_time = time.time()
n=100000
while True:
n = n+1
str_n_sorted = sorted(str(n))
len_n = len(str_n_sorted)
str_6n = str(6*n)
if len_n != len(str_6n):
# We can skip every number from this to the next order or magnitude
new_str_n = ''
for i in range(len_n)... |
import sys
import binascii
import os
def printProgressBar(progress):
i = int(progress * 20)
sys.stdout.write('\r')
sys.stdout.write("[%-20s] %d%%" % ('='*i, 5*i))
sys.stdout.flush()
def openFileToByte_generator(filename , chunkSize = 128):
fileSize = os.stat(filename).st_size
readBytes = 0.0
... |
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from calculations.WinterHighflow import WinterHighflowPOR
start_date = '10/1'
directory_name = 'tests/testFiles'
end_with = 'Case_1.csv'
class_number = 3
gauge_numbers = [11475560]
print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$... |
from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.graphics.tsaplots import plot_pacf
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
__author__ = "Jose Fernando Montoya Cardona"
__credits__ = ["Jose Fernando Montoya Cardona"]
__email__ = "jomon... |
"""
pirple/python/hw3/main.py
Homework Assignment #3
Create function that determines if 2 or more of the passed
parameter values are equal (including strings with numbers
as their value)
"""
def two_are_equal(a, b, c):
if int(a) == int(b):
result = True
elif int(a) == int(c):
result = True
... |
#!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
"""
Name : server_manager_status.py
Author : Abhay Joshi
Description : This file contains code that provides REST api interface to
configure, get and manage configurations for servers which
are part of the cont... |
#!/usr/bin/env python
import os
import optparse
from traj import MeasurementsTable
from glob import glob
def meas2mat(filename,outfilename='',label='_meas'):
# Determine files input
if isinstance(filename, basestring):
filename = [filename]
for name in filename:
if os.path.isdir(name): # dire... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# #######################################################################################
# ---------------------------------------------------------------------------------------
# File: __init__.py
# Author: Luis Monteiro
#
# Created on nov 11, 2019, 22:00 PM
# ------------------------------------------------------... |
### Value Iteration on Tree(n children) MDP
import random
import numpy as np
import argparse
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import PillowWriter
parser = argparse.ArgumentParser()
parser.add_argument("--n_children", type=int, default= 2, help="number ... |
import Print
import os
import shutil
import sq_tools
import io
import sys
import subprocess
import listmanager
import csv
from Drive import Private as DrivePrivate
from Drive import Public as DrivePublic
from Drive import DriveTools
import requests
from workers import concurrent_scrapper
from mtpinstaller... |
"""Utilities for fieldmap estimation."""
from pathlib import Path
from enum import Enum, auto
from collections import defaultdict
import re
import attr
from json import loads
from bids.layout import parse_file_entities
from bids.utils import listify
from niworkflows.utils.bids import relative_to_root
from .utils.bimap ... |
import rpc_util.rpc as rpc
def createrawtransaction(transactions={'': 0}, amounts={'',0.0}):
'''
The createrawtransaction method creates a transaction, spending
the given inputs and sending to the given addresses.
:param transactions: {string, number} a dictinary of txid (string)
as key ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from wireviz.DataClasses import Connector, Cable
from graphviz import Graph
from wireviz import wv_colors
from wireviz.wv_helper import awg_equiv, mm2_equiv, tuplelist2tsv, nested, flatten2d
from collections import Counter
from typing import List
class Harness:
def ... |
from __future__ import unicode_literals
import traceback
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
from django.conf import settings
from django.contrib.postgres.fields import JSONField, IntegerRangeField
from ledger.payments.bpay.models import BpayTransaction, ... |
from django.contrib import admin
from django_mptt_admin.admin import DjangoMpttAdmin
from .models import Category
class CategoryAdmin(DjangoMpttAdmin):
list_display = ["title", "created", "updated"]
list_filter = ["created"]
admin.site.register(Category, CategoryAdmin)
|
import json
import os
import subprocess
import pytest
from playwright.sync_api import sync_playwright
from src.git_graph_automation.git_command import invoke_git_log
from src.git_graph_automation.log_parser import parse_json_output
from src.git_graph_automation.renderer import render_html
def test_full_rendering_la... |
# Copyright 2020 - 2021 MONAI Consortium
# 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 wri... |
from unittest import TestCase
# from unittest.mock import MagicMock
from reconcile.utils.mr.auto_promoter import AutoPromoter
from reconcile.utils.mr.auto_promoter import ParentSaasConfigPromotion
from reconcile.utils.mr.auto_promoter import TARGET_CONFIG_HASH
# from .fixtures import Fixtures
class TestPromotions(... |
BASE_URL = "https://multichannel.qiscus.com"
APP_ID = "ufmqr-r5xsdquolzawmfz"
APP_SECRET = "2674b4fc2496dc4414fa3286ceacbbb2"
|
#!/usr/bin/python
import sys
import string
import blambert_util as bl
if len(sys.argv) != 2:
print "Usage: %s <transcript file>"%os.path.basename(sys.argv[0])
exit(1)
with open(sys.argv[1]) as f:
lines = f.readlines()
for line in lines:
line = line[:-1]
line = line.replace(" CAN NOT ", " CANNOT ... |
"""OdinAPI"""
|
import pandas as pd
import numpy as np
import unittest
import math
# sys.path.append('src/main/python/')
# sys.path.append('../../main/python/')
from assess import *
class TestAssess(unittest.TestCase):
def test_difference(self):
X = pd.DataFrame([1, 2, 3])
Y = pd.DataFrame([4, 5, 6])
res ... |
from app import create_app
from app.models import Answer, Student, Task, Teacher, User
from ext import db
import click
app = create_app()
@app.shell_context_processor
def make_shell_context():
return {'db': db, 'User': User, 'Student': Student, 'Teacher': Teacher, 'Task': Task, 'Answer': Answer}
if __name__ == '... |
from unittest import mock
def test_unvalidated_input(new_command):
"If the user enters text and there's no validation, the text is returned"
new_command.input = mock.MagicMock(return_value='hello')
value = new_command.input_text(
intro="Some introduction",
variable="my variable",
... |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Michael A.G. Aivazis
# California Institute of Technology
# (C) 1998-2003 All Rights Reserved
#
# <LicenseText>
#
# ~~~~~~~~~~~~~~~~~~~~~~~~... |
# 1
# 2
# 3
# 2 2
# 5
# 2 3
# 7
# 2 2 2
# 3 3
# 2 5
# 11
# 2 2 3
# 13
# 2 7
# 3 5
# 2 2 2 2
# 17
# 2 3 3
# 19
# 2 2 5
#
# 2: 4
# 3: 2
# 5: 1
# 7: 1
# 11: 1
# 13: 1
# 17: 1
# 19: 1
#
# => 2 * 2 * 2 * 2 * 3 * 3 * 5 * 7 * 11 * 13 * 17 * 19 = 232792560
import math
num = 232792560
... |
"""Tests for `repository_has_cookiecutter_json` function."""
import pytest
from cookiecutter.repository import repository_has_cookiecutter_json
def test_valid_repository():
"""Validate correct response if `cookiecutter.json` file exist."""
assert repository_has_cookiecutter_json('tests/fixtures/fake-repo')
... |
#!/usr/bin/python
import os
# Populate list with items
L = []
for r,d,f in os.walk("."):
for file in f:
if file.endswith("_tb.vhd"):
testbench = file.rstrip(".vhd")
L.append( [r, testbench, None] )
# Run testbenches
i = iter(L)
while True:
try:
item = i.next()
exc... |
from django.conf.urls import patterns, url
from api import views
urlpatterns = patterns('',
url(r'start', views.start, name='start'),
url(r'status', views.status, name='status'),
url(r'stop', views.stop, name='stop'),
url(r'diff', views.diff, name='diff'),
url(r'^$', views.index, name='index'),
)
|
import re
from random import randint
from typing import Match
from typing import Optional
from retrying import retry
import apysc as ap
from apysc._expression import var_names
from tests.testing_helper import assert_attrs
class TestPathMoveTo:
@retry(stop_max_attempt_number=15, wait_fixed=randint... |
import gym
from goexplore.cell import base_returning_info
class BasePolicy(object):
"""A class that represents a returning policy for Go-Explore"""
def __init__(self, environment: gym.Env):
self._environment = environment
def return_to_cell(self,
expected_cell: base_return... |
"""Config flow for Netatmo."""
import logging
from homeassistant import config_entries
from homeassistant.helpers import config_entry_oauth2_flow
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
class NetatmoFlowHandler(
config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN
):
""... |
from pathlib import Path
from typing import List, Union
import numpy as np
import pandas as pd
from xarray.core.dataarray import DataArray
from xarray.core.dataset import Dataset
def load_hydroatlas_attributes(data_dir: Path, basins: List[str] = []) -> pd.DataFrame:
"""Load HydroATLAS attributes into a pandas Da... |
#!/usr/bin/env python
import itertools as it
import json
import os
from collections import defaultdict
from operator import itemgetter
TEMPLATE = """<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="author" content="Joe Brown" />
<title>covdist</title>
<link href="https://fonts.goo... |
import smart_imports
smart_imports.all()
default = renderer.Renderer(tags=[tags.TAG.b,
tags.TAG.i,
tags.TAG.u,
tags.TAG.s,
tags.TAG.quote,
tags.TA... |
from nyoka.reconstruct.pmml_to_pipeline import generate_skl_pipeline
import unittest
class TestMethods(unittest.TestCase):
def test_sklearn_01(self):
recon_pipeline = generate_skl_pipeline("svc_pmml.pmml")
model_obj = recon_pipeline.steps[-1][-1]
self.assertEqual(model_obj.__class__.__name... |
"""
Script to generate translate dictionary.
Copyright (c) 2018 Qualcomm Technologies, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the
limitations in the disclaimer below) provided that the following conditions are met:
... |
import sys
class Solution:
def EatFish(self, n, m):
n = sorted(n)
for k in range(m):
j = 1
while n[0] == n[j]:
j += 1
n[j] += n[0]
del n[0]
n.sort()
print(n)
return n[0]
if __name__ == "__main__":
... |
# -*- coding: utf-8 -*-
COMMON_DOCUMENT_SUBJECTS = frozenset([
'10 recettes pdf ebook',
'100 conseils pdf ebook',
'100 ides pdf ebook',
'100 recettes pdf ebook',
'101 questions pdf ebook',
'101 things pdf ebook',
'1997 ford pdf ebooks',
'1998 yamaha pdf ebooks',
'1999 ford pdf ebook... |
import os
from itertools import zip_longest
import cv2
import numpy as np
import torch
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
from gazenet.utils.registrar import *
from gazenet.models.gaze_following.videogaze... |
from injector import inject
from pdip.api.base import ResourceBase
from pdip.cqrs import Dispatcher
from pdi.application.operation.GetDataOperationJobExecution.GetDataOperationJobExecutionQuery import \
GetDataOperationJobExecutionQuery
from pdi.application.operation.GetDataOperationJobExecution.GetDataOperationJo... |
import json
from django.contrib import messages
from django.http import Http404
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.translation import gettext_lazy as _ # NoQA
from pretix.base.models import Event, LogEntry, Order
from pretix.control.views.event import (
EventSet... |
"""Timer"""
import time
import functools
from threading import Thread
class Chronometer:
"""Simple chronometer with context manager support
# Properties
partial: float, current couting in seconds
running: boolean, chronometer current state
# Example
```python
import time
ch... |
from abc import ABCMeta, abstractmethod
#Interface handler de la que heredan todos los de mas Handlers
class CajeroHandler(metaclass=ABCMeta):
#Se implementa el sucesor siguiente para la cadena
def next_succesor(self, next=None):
self._next = next
#metodo abstracto handle principal
@abst... |
from django.shortcuts import render
from django.views.generic import TemplateView
from django.http.response import JsonResponse
from django.utils.html import escape
from argulib.dialog import Dialog
def homepage(request):
return render(request, 'socrates/base.html')
def demo(request):
return render(request... |
import torch
import numpy as np
np.random.seed(0)
import random
random.seed(0)
torch.manual_seed(0)
from src.MOBO_reg import MOBO
from test_functions.vlmop2 import problem, bounds
bounds = bounds()#np.array([[-np.pi, -5.,-5.],[np.pi,5.,5.]])
MOBO_TRY = MOBO(problem, bounds,minimize=True, N_iteration=25)
hvs_qeh... |
import unittest
import numpy
from axis_speeds import AxisSpeeds
class TestAxisSpeeds(unittest.TestCase):
def test_zero(self):
speeds = AxisSpeeds()
speeds.axis_rotation_speeds[0] = 0 # roll axis
speeds.axis_rotation_speeds[1] = 0 # yaw axis
speeds.axis_rotation_speeds[2] = 0 # pitc... |
import glob
import json
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
def get_cols():
cols = {
'C1': [],
'C2': [],
'C3': [],
'C4': [],
'W1': [],
'W2': [],
'W3': [],... |
from typing import Any
from typing import List
from typing import Sequence
import pytest
from brownie.network.account import Account
from brownie.network.contract import ContractContainer
from brownie.network.web3 import Web3
from eth_utils import decode_hex
ERC_1820_DEPLOYMENT_TX = decode_hex(
"0xf90a38808517487... |
import numpy as np
import pytest
import pp
from pp.drc import check_inclusion
def get_device(inclusion, width=0.5, layer1=(1, 0), layer2=(2, 0)):
c = pp.Component()
r1 = c << pp.c.rectangle(size=(width, width), layer=layer1)
r2 = c << pp.c.rectangle(
size=(width - 2 * inclusion, width - 2 * inclu... |
from typing import Any, Dict, Union, Tuple
import numpy as np
import pandas as pd
from catboost import CatBoostClassifier, Pool
from lightgbm import LGBMClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, f1_score, roc_auc_score
from sklearn.model_selection import... |
from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,SelectField,SubmitField
from wtforms.validators import Required
class UpdateProfile(FlaskForm):
bio = TextAreaField('Tell us about you.',validators = [Required()])
submit = SubmitField('Submit')
class AddPitch(FlaskForm):
title ... |
import time
import base64
from pytz import timezone
import pytz.reference
from izaber.wamp.zerp.controller import ZERP
from izaber import config, app_config
from izaber.startup import request_initialize, initializer
from izaber.wamp import wamp
__version__ = '2.7.20200424'
CONFIG_BASE = """
default:
wamp:
... |
import os
import torch
from torch import nn
from torch.autograd import Function
from torch.utils.cpp_extension import load
__all__ = ["p2i"]
module_path = os.path.dirname(os.path.abspath(__file__))
ext = load(
"ext",
sources=[
os.path.join(module_path, "ext.cpp"),
os.path.join(module_path, "p... |
from cloudshell.devices.standards.base import AbstractResource
from cloudshell.devices.standards.validators import attr_length_validator
AVAILABLE_SHELL_TYPES = ["CS_VirtualTrafficGeneratorChassis", "CS_VirtualTrafficGeneratorPort"]
class Chassis(AbstractResource):
RESOURCE_MODEL = "Virtual Traffic Generator Ch... |
# Copyright (c) 2008-2011 by Enthought, Inc.
# All rights reserved.
|
import os
import shutil
import tarfile
import pandas as pd
import progressbar
import requests
from download_images import DownloadData
from tf_utils import XML_TO_CSV, GenerateTFRecords, GeneratePaths
bar = progressbar.ProgressBar()
IMAGENET_WORDS_URL = "http://image-net.org/archive/words.txt"
IMAGENET_TAR_URL = "h... |
# pylint: disable=dangerous-default-value
"""
Various routines for dealing with generating input and processing output
for abstracted records of experimental tests.
These routines do things like:
* Convert simplified descriptions of tests into strain/strain time
histories that the models can use
*... |
from .utils import classproperty
from .session import SessionMixin
from .inspection import InspectionMixin
class ModelNotFoundError(ValueError):
pass
class ActiveRecordMixin(InspectionMixin, SessionMixin):
__abstract__ = True
@classproperty
def settable_attributes(cls):
return cls.columns +... |
from django.shortcuts import render
from rest_framework import generics, status
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from .serializers import *
# Create your views here.
def index(request):
return render(request, "frontend/index.html")
cla... |
#! /usr/bin/env python2
import configparser
import sys
from modules import BaseClasses,GetFlows
import exceptions
from collections import defaultdict
default_config={
'date_offset':24 # hours to look for messages
}
config = configparser.ConfigParser(default_config)
class FlowData():
messages={}
user... |
from .data import WebDataset
from .augmentation import AutoAugmenter
|
from django.shortcuts import render,redirect
from django.http import HttpResponse,Http404
import datetime as dt
from .models import Image,Location,Category
# Create your views here.
def index(request):
photos=Image.get_photos()
return render(request,'index.html',{"photos":photos})
def today_photos(request)... |
__author__ = 'Sean Yu'
'''created @2015/9/14'''
import unittest
import os
import sys
pardir =os.path.dirname(os.path.realpath(os.getcwd()))
#pardir= os.path.sep.join(pardir.split(os.path.sep)[:-1])
sys.path.append(os.path.sep.join([pardir,'lib']))
logpath = './log'
cmd = 'telnet 192.168.1.113'
#cmd = 'telnet cdc-da... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 26 10:06:10 2020
@author: david
"""
import pandas as pd
import sister
import numpy as np
import os
# plongement lexicaux - words embenddings
# embedder = sister.MeanEmbedding(lang="en")
from fuzzywuzzy import process
import pickle
from tqdm import tqdm
# Lecture du fich... |
URL = "https://r.nikkei.com/search?keyword=%E9%99%A2%E5%86%85%E6%84%9F%E6%9F%93" # <= ここにスクレイピングしたい対象URLを書いてください
Selector = "h1.nl-Hero_title" # <= ここにスクレイピングしたい対象のCSSセレクタを書いてください
# 必須
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import W... |
from datetime import datetime
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseNotFound
from django.shortcuts import render
from django.views import View
from minigest.anagrafica.models import SoggettoFiscale as Azienda
from minigest.docfisc.models import Fattura
class F... |
from abc import ABC, abstractmethod
from typing import List
from app.schemas.pose import Person
class Engine(ABC):
@abstractmethod
def infer_image(self, image) -> List[Person]:
return []
|
import numpy as np
from tqdm import tqdm
def SpectrumKernel(X, Y, d_l=[5, 12]):
"""Compute the K matrix in the case of the Spectrum kernel."""
# Shape of X
n = len(X)
d = len(Y)
# Length of the sequences
len_seq = len(X[0])
# Resulting array
result = np.zeros((n, d))
# Loop ove... |
#len() 方法返回对象(字符、列表、元组等)长度
#数组类型
print(len([1, 2, 3, 4, 5, 6]))
#元祖类型
print(len((1, 2, 3, 4, 5, )))
#字典类型
print(len({'id': 1, "user": "admin", "password": "123465"}))
#字符串类型
print(len('efarg gg g')) |
import math as m
a=int(raw_input())
b=int(raw_input())
c=int(raw_input())
l=(b*b-(4*a*c))
h=((-b+m.sqrt(l))/2*a)
i=((-b-m.sqrt(l))/2*a)
print(h)
print("\n")
print(i)
|
#connecting with MySQL_database to store details.
import mysql.connector as sql
mycon=sql.connect(host="localhost",user="root",passwd="sanju123",database="Exam_Analysis")
cursor=mycon.cursor()
#for GUI
from tkinter import *
from tkinter import messagebox
#showing graphs for analysing their performance
impor... |
#!/usr/bin/env python3
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from math_helpers import rotations, vectors, quaternions, matrices
from traj import conics, transfers
import numpy as np
def test_keplerian():
"""tests Keplerian class, and get_orbital_elements... |
from django.db import models
# Create your models here.
from django.db import models
from django.utils import timezone
class Endpoint(models.Model):
VERB_CHOICES = (
('GET', 'GET'),
('POST', 'POST'),
)
CONTENT_TP_CHOICES = (
('text/plain', 'text/plain'),
('text/html', 'te... |
from datetime import datetime
from django.db import models
# Create your models here.
class Banner(models.Model):
product_name = models.CharField(max_length=10, null=True, blank=True, verbose_name="归属产品", help_text="归属产品")
image = models.CharField(max_length=300, null=True, blank=True, verbose_name="图片地址", h... |
import os
import subprocess
def parrot(code):
with open('in.pir', 'w') as f:
f.write(code)
output = subprocess.Popen(['parrot', 'in.pir'],
stdout=subprocess.PIPE).communicate()[0]
os.remove('in.pir')
return output
|
from qobuz import api, Track
class Playlist(object):
"""This class represents a playlist from the Qobuz-API.
Parameters
----------
playlist_item: dict
Dictionary as returned from the JSON-API to represent a playist
Keys should include:
'id', 'name', 'description', 'duration',... |
# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory
# 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/LICEN... |
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import os
import pytest
import datetime
import time
import openvino.opset8 as ops
from openvino import Core, AsyncInferQueue, Tensor, ProfilingInfo, Function
from ..conftest import model_path, read_image
is_myriad = os.e... |
# Copyright 2020 Adap GmbH. 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 ag... |
import os
from conans import ConanFile, CMake, tools
class LoggerConan(ConanFile):
name = "logger"
version = "0.1.0"
license = "MIT"
url = "https://github.com/Rechip/logger"
homepage = "https://github/Rechip/logger"
description = "Modular logger"
topics = ("logger", "cpp")
settings = "o... |
# Copyright (c) 2016, Fundacion Dr. Manuel Sadosky
# 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
# list of condit... |
# File: 08-color.py
# Author: David Lechner
# Date: 11/5/2019
'''How to change the color in turtle graphics'''
import turtle
# We can use string with the name of a color to say what color to use when
# drawing.
turtle.pencolor('red')
turtle.forward(100)
|
import psycopg2
from datetime import datetime
from psycopg2 import sql
from est.fltr import county_return
from est.db.cur import con_cur
import numpy as np
import pandas as pd
def comp_find(est, a, b):
temp1 = est
temp2 = np.array(temp1[0])
county = temp2[0].strip()
state = temp2[1].strip()
cur, c... |
def leftrotate(arr, n, k):
k = k % n
g = gcd(n, k)
for i in range(g):
temp = arr[i]
j = i
while(1):
d = (j+k) % n
if(d == i):
break
a[j] = arr[d]
j = d
arr[j] = temp
def gcd(n, k):
if(k == 0):
retur... |
import numpy as np
import torch
from torch import nn, optim
from torch.nn import functional as F
# Inference Network
class InferenceNet(nn.Module):
def __init__(self, v_dim, h_dim, w_dim, n_classes):
super(InferenceNet, self).__init__()
self.h_dim = h_dim
self.v_dim = v_dim
self.w_... |
# =========================================================================
# Copyright 2021-present ShanHe, Inc.
# -------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compliance with the Licens... |
#!/usr/bin/env python
######################################################################################
## a_graph.py
#
# Author: Michele Berselli
# University of Padova
# berselli.michele@gmail.com
#
######################################################################################
######################... |
from django.conf import settings
from django.template import Library
from tag_parser import template_tag
from tag_parser.basetags import BaseAssignmentOrOutputNode
register = Library()
FaqPage = None
HAS_APP_URLS = 'fluent_pages' in settings.INSTALLED_APPS
if HAS_APP_URLS:
# HACK: accessing FaqPage directly. Apps... |
"""
Find serial devices and update serial device IDs
"""
from .. util import log
CONNECT_MESSAGE = """
Connect just one Serial device (AllPixel) and press enter..."""
def run(args):
from ..drivers.serial.driver import Serial
from ..drivers.serial.devices import Devices
import serial
run = True
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.