content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-07-02 08:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pyday_calendar', '0001_initial'),
]
operations = [
migrations.RemoveField(
... |
import json
from copy import deepcopy
from dataclasses import asdict
from functools import wraps
from typing import TYPE_CHECKING
import numpy as np
import pyarrow as pa
import xxhash
from .info import DatasetInfo
from .utils.py_utils import dumps
if TYPE_CHECKING:
from .arrow_dataset import Dataset
def hashr... |
from genie.ops.base import Base
class Lisp(Base):
exclude = [] |
"""Correct for Earth rotation (Sagnac effect) drift
Description:
------------
This model is used for correcting Doppler shift observations by receiver velocity determinition (in Eq. 6-22 in
:cite:`zhang2007`). Correction is done either based on precise or broadcast orbits.
"""
# External library imports
import nump... |
"""
Copyright 2017-2019 Fizyr (https://fizyr.com)
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... |
import argparse
import logging
import logging.config
from logging import Logger
from .utils import split_urls
from . import settings
from .factories import MoneroFactory
from pathlib import Path, PurePath
settings.init()
path = str(PurePath(Path(__file__).parent.absolute(), settings.logging_config_file))
logging.co... |
from DeepRTS import Engine, Constants
from DeepRTS.python import GUI
from DeepRTS.python import Config
from DeepRTS.python import DeepRTSPlayer
import numpy as np
import random
import os
import argparse
import gym
dir_path = os.path.dirname(os.path.realpath(__file__))
class Game(Engine.Game):
def __init__(se... |
import os
os.system("make")
check_solution("python3 sol.py", flag)
|
# -*- coding:utf-8 -*-
"""
Author:
Weichen Shen,wcshen1994@163.com
"""
import tensorflow as tf
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.initializers import Zeros, glorot_normal
from tensorflow.python.keras.layers import Layer
from tensorflow.python.keras.regularizers import l... |
# Resolve the problem!!
import re
def run():
encoded_text = ""
with open('encoded.txt', 'r', encoding='utf-8') as f:
encoded_text = f.read()
character_find = re.findall("[a-z]",encoded_text)
hidden_word = ''.join(character_find)
print(hidden_word)
#[ESTE ES EL MENSAJE OCULTO] -> christi... |
# Generated by Django 2.0.13 on 2019-05-24 09:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [("terra_layer", "0001_initial")]
operations = [
migrations.AlterField(
model_name="filterfield",
... |
# -*- coding: utf-8 -*-
"""Command line interface for Axonius API Client."""
from ...context import CONTEXT_SETTINGS, click
from ...options import AUTH, add_options
OPTIONS = [
*AUTH,
click.option(
"--for-next-minutes",
"-fnm",
"for_next_minutes",
help="Consider data stable only... |
#coding:utf-8
import sys
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QApplication, QPushButton, QFileDialog, QStatusBar
from PySide6.QtCore import QFile, QIODevice
from PySide6 import QtGui
version = "1.0"
#Autoincrement & arrangement of int
def autoIncrementArrangement(list : list, line : st... |
#!/usr/bin/env python3
"""
Python command line tool for taking command of your crypto coins
Command line tool to fetch and display information from the coinmarketcap API
"""
import argparse
import os
import time
from modules import API
from modules import Displayer
__author__ = "Jasper Haasdijk"
__version__ = "1.0.... |
# 1493. Longest Subarray of 1's After Deleting One Element
# User Accepted:3497
# User Tried:3867
# Total Accepted:3616
# Total Submissions:6849
# Difficulty:Medium
# Given a binary array nums, you should delete one element from it.
# Return the size of the longest non-empty subarray containing only 1's in the resultin... |
from cemc.mcmc import MCObserver
from cemc.mcmc import ReactionCrdInitializer, ReactionCrdRangeConstraint
import numpy as np
class DiffractionUpdater(object):
"""
Utility class for all objects that require tracing of a fourier
reflection.
:param Atoms atoms: Atoms object
:param array k_vector: Fo... |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created: Mon Sep 2 09:51:50 2019
# by: The Resource Compiler for PySide2 (Qt v5.13.0)
#
# WARNING! All changes made in this file will be lost!
from PySide2 import QtCore
qt_resource_data = b"\
\x00\x00\x02\xa4\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\... |
import csv
import numpy as np
class CsvUtils:
@classmethod
def single_line_header_csv_to_dict(cls,
fname,
delimiter=","
):
header = None
data = None
with open(fname) as ... |
import os
import numpy as np
from ptsnet.simulation.sim import PTSNETSimulation
from ptsnet.utils.io import get_example_path
def test_initial_conditions():
sim = PTSNETSimulation(
inpfile = get_example_path('BWSN_F'),
settings = {
'time_step' : 0.0001,
'save_results' : Fal... |
# -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2010, Frank Scholz <dev@coherence-project.org>
# Copyright 2018, Pol Canelles <canellestudi@gmail.com>
'''
:class:`WANDeviceClient`
------------------------
A class representing an embedded device w... |
#
# spcam_dr.py -- Suprime-Cam data processing routines
#
# Eric Jeschke (eric@naoj.org)
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import os
import re, glob
import time
# 3rd party imports
import numpy
from ginga import AstroImage
from ginga.misc i... |
#!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... |
#!/usr/bin/python
import pygame, sys
from pygame.locals import *
#defining colors
RED = pygame.Color(255, 0, 0, 10)
GREEN = pygame.Color(0, 255, 0, 10)
BLUE = pygame.Color(0, 0, 255, 10)
WHITE = []
#defining an array of greyscales
for i in range(256):
WHITE.append(pygame.Color(i, i, i, i))
#defining window size
WIN... |
import numpy as np
from numpy import loadtxt
from scipy import interpolate
#
#global polar
#polar = np.load('polar.npy')
#
#def lift_coefficient(alpha):
# if alpha < polar[-1,0]:
# aoa = polar[:,0]
# cl_polar = polar[:,1]
# f = interpolate.interp1d(aoa[:], cl_polar[:], kind='linear')
# cl... |
import math # need for infinity and Nan
def gotoh(fasta_file_1, fasta_file_2, scores, is_dna=False, file_substitution_matrix=None):
"""Put your code here"""
algo = Gotoh(file_substitution_matrix, scores, is_dna)
alignment_score, alignments = algo.run(fasta_file_1, fasta_file_2)
return alignment_score... |
import falcon
import json
from pyfirmata import Arduino, util
l_motor_speed = 0
r_motor_speed = 0
l_motor
l_dir1 = 2
l_dir2 = 3
r_motor
r_dir1 = 4
r_dir2 = 5
board
left_dir1_pin
left_dir2_pin
left_pwm
right_dir1_pin
right_dir2_pin
right_pwm
def get_status():
return 'POST -> Left Motor: ' + str(l_motor_speed)... |
'''OpenGL extension NV.compute_program5
This module customises the behaviour of the
OpenGL.raw.GL.NV.compute_program5 to provide a more
Python-friendly API
Overview (from the spec)
This extension builds on the ARB_compute_shader extension to provide new
assembly compute program capability for OpenGL. ... |
import numpy as np
import numpy.random as npr
import sys
import cv2
import os
import numpy as np
import pickle as pickle
import pandas as pd
from sklearn.model_selection import train_test_split
# 验证集比例
val_ratio = 0.12
# 读取训练图片列表
all_data = pd.read_csv('data/label.csv')
# 分离训练集和测试集,stratify参数用于分层抽样... |
if __name__ == "__main__":
import sys
sys.path.append(".")
from webmining.bingapi_fetcher import BingAPIFetcher
import re
from Levenshtein import jaro_winkler
import unicodedata
import string
from urllib.parse import urlparse
VIADEO_URL = re.compile("https?://fr.viadeo\.com/fr/company/(?P<company>[^/]*)/?.*"... |
import pandas as pd
from src.data.data_query import StorageEngine
from src.data.plays_model import game_json_to_plays_list
def tidy_plays_df(years, augment=False):
def _tidy_plays_one_year(start_year, storage_engine, augment=False):
gamePk_list = storage_engine.get_all_season_gamePk(start_year)
g... |
import sink_settings as sinkSettings
import websocket
import kazoo
import time
import json
import math
import queue
import uuid
import os
import glob
import gzip
import ssl
import pathlib
from b2sdk.v1 import *
try:
import thread
except ImportError:
import _thread as thread
def construct_subscription(binding, ... |
import pytest
import os
import base64
import copy
import numpy
import shutil
from api.tests.utils.common_functions import get_section_from_config_file, get_config_file_json
# The line below is absolutely necessary. Fixtures are passed as arguments to test functions. That is why IDE could
# not recognized them.
from a... |
# coding: utf-8
"""
Copyright 2016 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applica... |
b="A a A a E e E e I i I i O o O o R r R r U u U u S s T t Y y H h N d Ou ou Z z A a E e O o O o O o O o Y y l n t j db qp A C c L T s z ? ? B U V E e J j Q q R r Y y a a a b o c d d e e er e e er e j g g G g u h h h i i I l l l lzh m m m n n N o OE o f r r r r r r r R R s sh j r sh t t u u v v w y Y z z zh zh ? ? ? c ... |
import abc
import typing
import pandas as pd
from automlToolkit.components.utils.utils import *
from automlToolkit.components.utils.constants import *
from automlToolkit.components.feature_engineering.transformation_graph import DataNode
class Transformer(object, metaclass=abc.ABCMeta):
"""
This is the paren... |
"""
Compute metrics on rendered images (after eval.py).
First computes per-object metric then reduces them. If --multicat is used
then also summarized per-categority metrics. Use --reduce_only to skip the
per-object computation step.
Note eval.py already outputs PSNR/SSIM.
This also computes LPIPS and is useful for do... |
from functools import lru_cache
from functools import singledispatch
from typing import Any
from typing import Type
from typing import TypeVar
from ..types import CannotDispatch
from ..types import Forge
from .functional import FunctionalDispatch
T = TypeVar("T")
def sentry(type_: Type[T], data: Any, build: Forge)... |
import urllib.request
import re
def get_url_content(url, timeout=1):
request = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
with urllib.request.urlopen(request, timeout=timeout) as resp:
return resp.read().decode(errors="ignore")
def remove_tags(text):
regular = re.compile... |
# -*- coding: utf-8 -*-
import pandas as pd
import MySQLdb as mysqldb
from MySQLdb import cursors
import numpy as np
import re
import easygui as eg
from tqdm import tqdm, tqdm_pandas
def init_sql_db():
def rd_pass():
return open('pass.pass','r').read()
HOST = "127.0.0.1"
LOGIN = "nseifert"
PA... |
# Copyright 2012 OpenStack Foundation
# 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 requ... |
from __future__ import print_function, division, absolute_import
import numpy as np
import abstract_rendering.core as core
from abstract_rendering._cntr import Cntr
class Contour(core.ShapeShader):
def __init__(self, x_range=None, y_range=None, levels=5, points=True):
"""
x/y_range arguments dete... |
import socket, menu
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("gopher.floodgap.com", 70))
sock.sendall("\r\n".encode("ascii"))
data = b""
while True:
temp = sock.recv(1024)
if not temp: break
data += temp
sock.close()
data = data.decode("ascii")
p = menu.Parse... |
# -*- coding: utf-8 -*-
"""
websiteconfig
~~~~~~~~~~~~~
default config for website.
"""
import os
class default_settings(object):
DEBUG = True
TESTING = True
SECRET_KEY = '\x7f\x89q\x87v~\x87~\x86U\xb1\xa8\xb5=v\xaf\xb0\xdcn\xfa\xea\xeb?\x99'
SQLALCHEMY_ECHO = True
SQLALCHEMY_DATAB... |
print("Sartu zenbakiak...")
a=int(input("Sartu lehenengo zenbakia: "))
b=int(input("Sartu bigarren zenbakia: "))
def baino_txikiagoa(a, b):
if a > b:
return("Bigarren zenbakia txikiagoa da.")
elif a < b:
return("Lehenengo zenbakia txikiagoa da.")
elif a == b:
return("Zenbaki berdi... |
import pytest
from sciwing.modules.embedders.bert_embedder import BertEmbedder
import itertools
from sciwing.utils.common import get_system_mem_in_gb
from sciwing.data.line import Line
import torch
bert_types = [
"bert-base-uncased",
"bert-base-cased",
"scibert-base-cased",
"scibert-sci-cased",
"sc... |
# -*- coding: utf-8 -*-
"""
@author: krakowiakpawel9@gmail.com
@site: e-smartdata.org
"""
import numpy as np
import pandas as pd
import seaborn as sns
sns.set()
df = pd.read_csv('./data/ten_d.csv', index_col=0)
df.columns = ['Open', 'High', 'Low', 'Close', 'Volume']
# %%
df_agg = df.rolling(window=10).agg(np.mean)... |
# coding=utf-8
from __future__ import absolute_import, division, print_function, \
unicode_literals
from typing import MutableMapping
__all__ = [
'with_context',
]
def with_context(exc, context):
# type: (Exception, dict) -> Exception
"""
Attaches a context dict to an exception, so that it can b... |
from ecs.workflow.models import NODE_TYPE_CATEGORY_SUBGRAPH, NODE_TYPE_CATEGORY_CONTROL, NODE_TYPE_CATEGORY_ACTIVITY
from ecs.tasks.models import TaskType
def make_dot(g, prefix='', embed_subgraphs=True, subgraph_id=''):
common_edge_attrs = {'fontname': 'Helvetica', 'style': 'bold'}
common_node_attrs = {'fontn... |
# Copyright 2016 Autodesk 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 writing... |
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.util as util
import benchexec.tools.template
import benchexec.result as r... |
# -*- coding: utf-8 -*-
#
# djangoplicity-contacts
# Copyright (c) 2007-2011, European Southern Observatory (ESO)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source ... |
class LineModel:
def __init__(self, conductors):
self._resistance = {}
self._geometric_mean_radius = {}
self._wire_positions = {}
self._phases = {}
for phase, (r, gmr, (x, y)) in conductors.items():
self._resistance[phase] = r
self._geometric_mean_rad... |
from Generators import Primes
def GetFactors(n):
'''Returns all factors of n greater than 0'''
if n < 1:
return []
return [x for x in range(1, n + 1) if n % x == 0]
def GetPrimeFactors(n):
'''
Returns all prime factors for n.
Return value is a dictionary of {prime: cardinality}. The ... |
from PIL import Image
import numpy as np
import os
import argparse
import sys
from sklearn import metrics
def mae(folder,path):
if folder:
orginal_image = os.path.join(folder,path)
else:
orginal_image = path
sal=Image.open(orginal_image)
GT=Image.open(os.path.join("Ground_Truth",pat... |
# Biogeme's Swissmetro example: https://github.com/michelbierlaire/biogeme/blob/master/examples/swissmetro/01logit.ipynb
# this code is copied and lightly modified from the Biogeme example, which is under the Biogeme open-source license
import pandas as pd
import biogeme.database as db
import biogeme.biogeme as bio
fr... |
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("Reports"),
"items": [
{
"type": "report",
"is_query_report": True,
"name": "Process Flow",
"doctype": "Product Line Process Flow"
},
{
... |
from rest_framework import serializers
from profiles_api import models
class HelloSerializer(serializers.Serializer):
"""Serializes a name field for testing our APIView"""
name = serializers.CharField(max_length=10)
class UserProfileSerializer(serializers.ModelSerializer):
"""serialize a user profile ob... |
import json
import re
import urllib2
import copy
api_server = kobitonServer['url']
username = kobitonServer['username']
api_key = kobitonServer['apiKey']
group_options = {
'cloudDevices': isCloud,
'privateDevices': isPrivate,
'favoriteDevices': isFavorite
}
platform_options = {
'Android': isAndroid,
'iOS':... |
import sys
from basket import Basket
from product_store import ProductStore
from offer_store import OfferStore
class CheckoutSystem(object):
def __init__(self):
self._product_store = ProductStore.load_from_config_file()
self._offer_store = OfferStore.load_from_config_file()
self._basket =... |
import docx2txt
from fulltext.util import BaseBackend
from fulltext.util import exiftool_title
from fulltext.util import assert_cmd_exists
class Backend(BaseBackend):
def check(self, title):
if title:
assert_cmd_exists('exiftool')
# Note: docx2txt does not support encoding.
def handl... |
import socket
from threading import Thread
byte = 0
status = ""
sock = socket.socket()
conn = None
address_file = ""
ip = ""
port = 0
def set_file():
global conn
f = open(address_file, 'r')
str_code = str(f.read())
f.close()
conn.send(str_code.encode("utf-8"))
print()
print("CODE:",str_code... |
from django.db import models
from django.conf import settings
from lib.manager import QuerySetBase
class ChernobylModelAbstract(models.Model):
"""
chernobyl base models
"""
objects = QuerySetBase.as_manager()
class Meta:
abstract = True
ordering = ['-id']
def save(self, ... |
# encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""... |
#
# Copyright (c) 2014-2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from wsme import types as wsme_types
import wsmeext.pecan as wsme_pecan
import pecan
import six
from pecan import rest
from sm_api.api.controllers.v1 import base
from sm_api.api.controllers.v1 import collection
from sm_api.... |
from rest_framework import serializers
class HelloSerializer(serializers.Serializer):
name=serializers.CharField(max_length=10)
|
class Solution:
def reverseStr(self, s: str, k: int) -> str:
return "".join([s[i:i+k][::-1] + s[i+k:i+2*k] for i in range(0, len(s), 2*k)]) |
# extensions.py file
# Import the necessary package and module
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from flask_uploads import UploadSet, IMAGES
from flask_caching import Cache
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
# Create an i... |
#!/usr/bin/env python
#############################################################################
### BindingDb Utilities
### http://www.bindingdb.org/bind/BindingDBRESTfulAPI.jsp
### XML output only.
#############################################################################
import sys,os,re,argparse,time,logging
... |
num = int(input('Digite um número para ver sua tabuada: '))
for c in range(0,11):
print(f'{num} x {c:2} = {num*c}') |
from nodeconductor.core import NodeConductorExtension
class InsightsExtension(NodeConductorExtension):
class Settings:
NODECONDUCTOR_INSIGHTS = {
'PROJECTED_COSTS_EXCESS': 20,
}
@staticmethod
def django_app():
return 'nodeconductor_plus.insights'
@staticmethod
... |
advec = (wind_vec * -grad_vec).sum(axis=-1)
print(advec.shape) |
from maintain_frontend import main
from flask_testing import TestCase
from unit_tests.utilities import Utilities
from unittest.mock import patch, MagicMock
from flask import url_for, g
from maintain_frontend.dependencies.session_api.session import Session
from maintain_frontend.constants.permissions import Permissions
... |
# Copyright 2015 Cisco Systems, 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 requi... |
from typing import Callable
import torch
from torch import nn
def initialize_weights(
init_func: Callable[[torch.Tensor], None]
) -> Callable[[nn.Module], None]:
"""
Returns a function that can be applied to a module to initializes the module
weights.
Args:
init_func: A function t... |
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext, Template
from django.template.loader import get_template, render_to_string
from django.contrib.auth.decorators import login_required
fro... |
"""
For use with Gabby Gums
"""
import math
import time
import json
import logging
import functools
import statistics as stats
from typing import List, Optional
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime, timedelta
import asyncpg
from discord import Inv... |
import torch
import torch.nn as nn
import numpy as np
import os
import matplotlib.pyplot as plt
import random
def KLZeroCenteredLevy(sigma_1, sigma_2):
A = sigma_2 / (2*sigma_1)
B = torch.log(torch.pow(sigma_1, 0.5)/2)
C = torch.log(torch.pow(sigma_2, 0.5)/2)
KL = A + B - C - 0.5
return KL
def ... |
class UnitGroup(Enum,IComparable,IFormattable,IConvertible):
"""
A group of related unit types,primarily classified by discipline.
enum UnitGroup,values: Common (0),Electrical (3),Energy (5),HVAC (2),Piping (4),Structural (1)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==y... |
"""Protcol write to write collected data to a tinydb db"""
import tinydb
from baseclasses.protocol import ProtocolBase
class TinyDBProtocol(ProtocolBase):
"""
Class to store collected data in a tinyDB db.
"""
def __init__(self, examiner, artifactid='', taskid=''):
super().__init__(artifacti... |
from django.db import models
from django.contrib.auth.models import User
import user_accounts
from user_accounts import exceptions
import uuid
class UserProfile(models.Model):
name = models.CharField(max_length=200, blank=True)
user = models.OneToOneField(User, on_delete=models.CASCADE,
... |
"""Datagrid utilies package."""
import logging
import sys
from gi.repository import Gtk, Gdk
def setup_logging_to_stdout():
"""Sets up logging to std out."""
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/8/23 10:37
# @Author : ‘DIY’
# @Site :
# @File : QuXianNiHe.py
# @Software: PyCharm Community Edition
import matplotlib.pyplot as plt
import numpy as np
#潘海东,2014/1/13
x = np.arange(1, 17, 1)
y = np.array([4.00, 6.40, 8.00, 8.80, 9.22, 9.50, 9.7... |
from librovers import * # import bindings.
import random
"""
A custom rover that:
uses orientation
computes a modified difference reward
implements a new sensing mechanism
"""
class PyRover (rovers.IRover):
def __init__(self, obs_radius=1.0, use_orientation=False):
super().__init__(obs_radius)
sel... |
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
import Crypto.Random
import binascii
class Wallet:
def __init__(self):
self.private_key = None
self.public_key = None
def create_keys(self):
private_key, public_key = self.generate_... |
#this code is inspired by
#https://github.com/sauravraghuvanshi/Udacity-Computer-Vision-Nanodegree-Program/blob/master/project_2_image_captioning_project/model.py
#https://github.com/ajamjoom/Image-Captions/blob/master/main.py
import socket
import torch
from torch import nn
import torchvision
def _load_resnet101_mode... |
"""Utility functions shared by all providers."""
from datetime import datetime, timedelta
import pytz
import requests
from bs4 import BeautifulSoup
def get_html_document(url):
"""Get HTML document of given URL."""
headers = {
"User-Agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) Appl... |
from django.db import models
class MetaTable(models.Model):
name = models.CharField(max_length=100)
verbose_name = models.CharField(max_length=100)
other_verbose_names = models.CharField(max_length=300)
def __str__(self):
return self.name
class MetaFields(models.Model):
table = model... |
import tensorflow as tf
from copy import deepcopy
from base import *
from lm import *
class RJMCMC(object):
def __init__(self, simulater, gamma, multiple_trial, sample_sub, end_token,
fun_logps, fun_propose_tag=None,
write_files=None,
pi_true=None):
# si... |
#!/usr/bin/env python
"""
Author: Adam White, Matthew Schlegel, Mohammad M. Ajallooeian, Sina Ghiassian
Purpose: Skeleton code for Monte Carlo Exploring Starts Control Agent
for use on A3 of Reinforcement learning course University of Alberta Fall 2017
"""
from utils import rand_in_range, rand_un
imp... |
#!/usr/bin/env python
## @file configSerialize.py
## @brief Format a python VMOMI object in config serializer format.
##
## Detailed description (for Doxygen goes here)
"""
Format a python VMOMI object in config serializer format.
Detailed description (for [e]pydoc goes here)
"""
from pyVmomi import VmomiSupport
fro... |
BLOCK_CHARACTER = '⊗'
FREE_CHARACTER = '✰'
PATH_CHARACTER = '✱'
START_CHARACTER = '☖'
END_CHARACTER = '☗'
|
# This file is part of the Extra-P software (http://www.scalasca.org/software/extra-p)
#
# Copyright (c) 2020, Technical University of Darmstadt, Germany
#
# This software may be modified and distributed under the terms of a BSD-style license.
# See the LICENSE file in the base directory for details.
from dataclasses ... |
"""
Including Libraries
"""
import csv
import cv2
import sklearn
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
"""
Defining Function
"""
def Image_Visualization(Images):
#Sort and Print Left, Center & Right Images
center_image_name = img_path + Images[50]... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import hypothesis.strategies as st
from hypothesis import given
import numpy as np
from caffe2.python import core, workspace
import caffe2.python.hypothes... |
import sys
import glob
sam_files = glob.glob("*magicblast*.sam")
print("alignment\tscore\tlength")
for sfile in sam_files:
for line in open(sfile):
la = line.strip().split("\t")
if (len(la)) == 14:
length = len(la[9])
score = la[12].split(":")[-1]
print("{}\t{}\... |
print('ola, isso é um teste de versionamento')
print('')
|
from setuptools import setup
setup(
name = 'tcedata',
packages = ['tcedata'],
version = '1.0',
license='MIT',
description = 'Tools to download data from storages hosted by UvA-TCE to user workspace.',
author = '@jiqicn',
author_email = 'qiji1988ben@gmail.com',
url = 'https://github.com/... |
# Copyright 2021 Uptimedog
#
# 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, s... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
if __name__ == '__main__':
class student:
x = 0
c = 0
def f(stu):
stu.x = 20
stu.c = 'c'
a = student
a.x = 3
a.c = 'a'
f(a)
print a.x, a.c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.