content stringlengths 5 1.05M |
|---|
__all__ = ["data_commands", "print"] |
import os.path
import numpy as np
from itertools import chain
from argparse import ArgumentParser
from sklearn.preprocessing import StandardScaler
from typing import Iterable, Dict, Any
from utils.constants import TEST, INPUTS, OUTPUT, SAMPLE_ID, TIMESTAMP, TRAIN
from utils.file_utils import iterate_files, read_by_fil... |
BBBBBBB BBBBBBBBBBBBBBBBB
BBBB BBBBBBBBBBBBBB
BBBBB BBBBBBBBBBBB
BBBBBBBB
XXXX XXXXXXXXXXXXXXBBBBB BBBBBBBBBBXX BBBBBBBB XXXXXXXX
BBBBB BBBB
XXXXXX
BBBBBBBB BBBBBBBBBBBBBBBBBBBBBBBBB
FFFFFFFFFFFFFFFFFFFF
BBBBBBBBBBB
BBBBBBBB
BBBBB BBBBBBBBBBBBB
BBBBBBBB
|
"""
skfuzzy.control subpackage, providing a high-level API for fuzzy system design.
"""
__all__ = ['Antecedent',
'Consequent',
'CrispValueCalculatorError',
'DefuzzifyError',
'EmptyMembershipError',
'NoTermMembershipsError',
'ControlSystem',
... |
"""ADB-related exceptions.
"""
from . import constants
class AdbCommandFailureException(Exception):
"""A ``b'FAIL'`` packet was received.
"""
class DeviceAuthError(Exception):
"""Device authentication failed.
"""
def __init__(self, message, *args):
message %= args
super(Devi... |
valores = []
while True:
valor = (int(input('Digite um valor: ')))
if valor in valores:
print(f'\033[:31mO valor {valor} já existi na lista! Não vou adicionar...\033[m')
else:
valores.append(valor)
print('Valor adicionado com sucesso...')
perg = ' '
while perg not in 'SN':
... |
# -*- coding: utf-8 -*-
"""
DEFAULT PARAMETERS OF SPAFHY FOR A SINGLE CATCHMENT AND POINT-SCALE SIMULATIONS
Created on Mon Jun 25 18:34:12 2018
@author: slauniai
Last edit: 11.5.2020 / SL: canopygrid can now have multiple vegetation types.
Phenology is common to all, LAI-cycle common to all deciduous
"""
def param... |
import logging
from typing import TYPE_CHECKING, Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Union
from rotkehlchen.accounting.structures import Balance
from rotkehlchen.assets.asset import Asset, EthereumToken
from rotkehlchen.chain.ethereum.makerdao.common import RAY
from rotkehlchen.chain.ethereum.struc... |
#!/usr/bin/env python3.6
# -*- coding: utf8 -*-
'''
ELQuent.modifier
Massive modification suite for multiple assets
Mateusz Dąbrowski
github.com/MateuszDabrowski
linkedin.com/in/mateusz-dabrowski-marketing/
'''
# Python imports
import os
import csv
import sys
import json
from colorama import Fore, Style, init
# ELQ... |
#!/usr/bin/python
import logging
import optparse
import os
import time
from progress.bar import Bar, ShadyBar
from nmj.updater import NMJUpdater
_LOGGER = logging.getLogger("nmj")
def get_lock(root_dir):
while os.path.isfile(os.path.join(root_dir, "pynmj.lock")):
time.sleep(0.5)
fd = open(os.path.join(root_dir, "... |
'''
Init file for pydanfossair
'''
from . import *
__version__ = '0.1.0'
|
from getratings.models.ratings import Ratings
class NA_XinZhao_Jng_Aatrox(Ratings):
pass
class NA_XinZhao_Jng_Ahri(Ratings):
pass
class NA_XinZhao_Jng_Akali(Ratings):
pass
class NA_XinZhao_Jng_Alistar(Ratings):
pass
class NA_XinZhao_Jng_Amumu(Ratings):
pass
class NA_XinZhao_Jng_Anivia(Rating... |
# coding= utf-8
import os, sys, io, re, json, glob
from collections import OrderedDict
def listdir_nohidden(path):
return glob.glob(os.path.join(path, '*'))
mapp_ordlistor = 'ordlistorText/'
ordlistor = listdir_nohidden(mapp_ordlistor)
mapp_data = 'data/'
fillista = listdir_nohidden(mapp_data)
for filnamn in f... |
import numpy as np
import pandas as pd
import descarteslabs as dl
LS = "landsat:LC08:01:RT:TOAR"
S2 = "sentinel-2:L1C"
def get_bands_from_platform(platform):
if platform == S2:
bands=["blue","green","red", "red-edge-2","nir","water-vapor","ndvi", "alpha"]
scales=[[0, 10000, 0, 1],
... |
from django.urls import path
from . import views
from .views import IndexView, PythonCreateView
urlpatterns = [
path('', IndexView.as_view(), name="index"),
path('create/', PythonCreateView.as_view(), name="create"),
]
|
# coding: utf-8
# ### 1. 数据预处理
# In[1]:
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D
from keras import backend as K
num_classes = 10
img_rows, img_cols = 28, 28
# 通过Keras封装好的API加载MNIST数据。其中trainX就是一个60000 * 28 * 2... |
# DeepSpeed note, some parts of code taken & adapted from commit c368a9fd1b2c9dee4cc94de9a6bb0be3d447be41
# https://github.com/ptillet/torch-blocksparse/blob/master/tests/test_softmax.py
# https://github.com/ptillet/torch-blocksparse/blob/master/tests/test_matmul.py
# https://github.com/ptillet/torch-blocksparse/blob/m... |
#!/usr/bin/env python3
# coding: utf-8
from rdbox.rdbox_node_formatter import RdboxNodeFormatter
import rdbox.config
from logging import getLogger
r_logger = getLogger('rdbox_cli')
r_print = getLogger('rdbox_cli').getChild("stdout")
class BlockstoreRdboxNodeFormatter(RdboxNodeFormatter):
def output_report(self,... |
import argparse
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from cakechat.utils.env import init_cuda_env
init_cuda_env()
from cakechat.dialog_model.factory import get_reverse_model
from cakechat.dialog_model.model import CakeChatModel
from cakechat.dialog_model.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 21 13:12:03 2021
@author: jane_hsieh
Goal: Find out the potential anomalies of variable –"Tran Count", and visualize the results
Here we use a person's bank account transaction record, in the case of 'Japan', 'Australia',or 'USA'
Resource... |
from random import randint
class MyPlayer(object):
'''
Random reversi player class.
'''
move_i = 0
def __init__(self, my_color, opponent_color):
self.name = 'random'
self.my_color = my_color
self.opponentColor = opponent_color
self.moveCount = 1
def mo... |
import socket
import sys
def is_hostname_reverse_resolving_correctly():
'''Check if the primary IP addr for our host reverse-resolves correctly. Also returns true
if no reverse resolve defined. This is useful for server processes like Java that sometimes
use the '''
my_hostname = socket.gethostna... |
"""! This script has been borrowed and adapted. Original script:
https://github.com/pumpikano/tf-dann/blob/master/create_mnistm.py.
It creatse the MNIST-M dataset based on MNIST
"""
import tarfile
from typing import Any
import numpy as np
import skimage # type: ignore
import skimage.io # type: ignore
import skimage... |
''' show_authentication_sessions.py
IOSXE parsers for the following show commands:
* show authentication sessions
* show authentication sessions interface {intf}
* show authentication sessions interface {intf} details
'''
# Python
import re
# Metaparser
from genie.metaparser import MetaParser
from genie.... |
import random
import os
from lib.flight import Flight
from lib.passenger import Passenger
import time
class Booker:
def __init__(self, destinations_list=None):
if destinations_list == None:
self.destinations = ["New York", "Paris", "London", "Tokyo"]
else:
self.destinations... |
"""Update a single file in an already published Zenodo deposition and collect the new version of the DOI."""
####
#### Update a single file in an already published Zenodo deposition
#### and collect the new version of the DOI.
####
#### Example usage to operate in Zenodo:
#### python3 ./scripts/zenodo-version-update.p... |
class Store(object):
"""
An object that can be used to keep track of state
"""
def __init__(self, *args, **kwargs):
self._storage = {}
for item in args:
if isinstance(item, dict):
self._storage.update(item)
self._storage.update(kwargs)
def set(se... |
# coding: utf-8
import webiopi
import time
import RPi.GPIO as GPIO
webiopi.setDebug()
GPIO.setwarnings(False)
#initial setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.OUT,initial=GPIO.LOW)
GPIO.setup(15,GPIO.OUT,initial=GPIO.LOW)
GPIO.setup(18,GPIO.OUT,initial=GPIO.LOW)
GPIO.setup(24,GPIO.OUT,initial=GPIO.LOW)
GPIO.s... |
from lewis.core import approaches
from lewis.core.statemachine import State
class UninitializedState(State):
NAME = "UninitializedState"
def on_entry(self, dt):
print("Entering uninitialized state")
class InitializedState(State):
NAME = "InitializedState"
def on_entry(self, dt):
pr... |
M = 998244353
n = int(input())
a = [int(x) for x in input().split()]
from math import log
"""l = len(str(a[0]))"""
ans = 0
"""for i in range(l+1):
for j in range(len(a)):
ans+= (10**(2*i))*(a[j]%10)%M
a[j]//=10
print((n*11*ans)%M)"""
def op(n):
out = 0
if(n==0):
return 0
d = int(log(n,10))+1
for i in r... |
import os, sys
sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics.context import *
from nodebox.graphics import *
img = Image("creature.png")
def draw(canvas):
canvas.clear()
translate(250, 250)
scale(0.5)
t = canvas.frame % 100 * 0.01 # A number between 0.0 and 1.0.
t = smo... |
from ..imports import *
from .. import utils as U
from . import preprocessor as tpp
MAX_FEATURES = 20000
MAXLEN = 400
def texts_from_folder(datadir, classes=None,
max_features=MAX_FEATURES, maxlen=MAXLEN,
ngram_range=1,
train_test_names=['train',... |
"""
Copyright 2013 Rackspace, 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, software... |
#! /usr/bin/env python
import argparse
import sys
import geopandas as gpd
import numpy as np
import pandas as pd
from shapely.geometry import Point
############################
# set the command line argument parser
parser = argparse.ArgumentParser(description="Converts vector data to maxent format csv data")
# set ... |
import pytest
from sfa_dash.conftest import BASE_URL
@pytest.fixture
def upload_routes(forecast_id, observation_id, cdf_forecast_id):
return [
f'/forecasts/single/{forecast_id}/upload',
f'/observations/{observation_id}/upload',
f'/forecasts/cdf/single/{cdf_forecast_id}/upload']
@pytest... |
from abc import abstractmethod
from typing import Union, Callable
import numpy as np
import scipy.integrate as integrate
from beartype import beartype
from UQpy.distributions.baseclass import Distribution
import warnings
from UQpy.distributions.collection import Uniform, Normal
warnings.filterwarnings('ignore')
c... |
#factorial(N) = N * factorial(N-1)
# 예 factorial(4) = 4 * factorical(3)
#...
#factoral(1) = 1
def factorial(n):
if n == 1:
return 1
# 이 부분을 채워보세요!
return n * factorial(n-1)
print(factorial(5))
|
# encoding: utf-8
from django.db import models
from cool.model import descriptors
class ForeignKey(models.ForeignKey):
"""
外键字段自动使用缓存获取数据
"""
forward_related_accessor_class = descriptors.ForwardManyToOneCacheDescriptor
class OneToOneField(models.OneToOneField):
"""
一对一字段自动使用缓存获取数据
"""
... |
# Copyright 2020 Efabless Corporation
#
# 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... |
del (*x,)
|
from collections import Counter
from functools import reduce
import logging
from operator import add
import os
from pathlib import Path
from typing import Any, Dict, Optional
import calvin_agent
from calvin_agent.training import is_multi_gpu_training, log_rank_0
import hydra
import numpy as np
from omegaconf import Di... |
import numpy as np
'''
np.dot(a, b) # 计算矩阵a和矩阵b的点积
np.linalg.inv(a) # 矩阵a的逆矩阵
'''
# GPS定位
def main():
i = 0
c = 0.299792458
x = np.zeros((6, 4)) # 存储6个卫星的(x, y, z, t)参数
while i < 6:
temp = input()
x[i - 1] = temp.split()
j = 0
while j < 4:
x[i-1][j] = float(... |
"""
OpenVINO DL Workbench
Parameters for Model Optimizer related endpoints
Copyright (c) 2018 Intel Corporation
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/lic... |
from utils.reddit import Reddit
|
def build_endpoint_description_strings(
host=None, port=None, unix_socket=None, file_descriptor=None
):
"""
Build a list of twisted endpoint description strings that the server will listen on.
This is to streamline the generation of twisted endpoint description strings from easier
to use command lin... |
import sys
import zmq
import numpy as np
# from marl_agent import ma_messages_pb2 as pb
import ma_messages_pb2 as pb
import time
from collections import defaultdict
class RealNeSZmqBridge(object):
"""
Python interface base class for the simulator. Includes information about the port numbers for communication ... |
# Copyright 2014 - Rackspace Hosting
#
# 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 ... |
# -*- encoding:ascii -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 6
_modified_time = 1384542354.113604
_template_filename=u'templates/webapps/galaxy/base_panels.mako'
_template_uri=u'/webapps/galaxy/base_panels.mako'
_temp... |
# Exercise 4.5
# Author: Noah Waterfield Price
import sys
val = eval(sys.argv[1])
print '%s is a Python %s object' % (val, type(val))
"""
Sample run:
python objects_cml.py 1
1 is a Python <type 'int'> object
python objects_cml.py 1.0
1.0 is a Python <type 'float'> object
python objects_cml.py 1 + 1j
(1 + 1j) is a Pyt... |
#!/bin/env python
##
# @file
# This file is part of SeisSol.
#
# @author Alexander Breuer (breuer AT mytum.de, http://www5.in.tum.de/wiki/index.php/Dipl.-Math._Alexander_Breuer)
#
# @section LICENSE
# Copyright (c) 2014, SeisSol Group
# All rights reserved.
#
# Redistribution and use in source and binary forms, with o... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/distributed.models.lgb.ipynb (unless otherwise specified).
__all__ = ['LGBMForecast']
# Cell
import warnings
import lightgbm as lgb
# Cell
class LGBMForecast(lgb.dask.DaskLGBMRegressor):
if lgb.__version__ <= '3.2.1':
warnings.warn(
"It is rec... |
#!/usr/bin/python
import socket
import sys
import os
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = int(os.environ['PORT'])
server_address = ('0.0.0.0', port)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
sock.listen(1)
while True:
print >>sys.stderr,... |
a = [3, 4, 5]
b = [i for i in a if i > 4]
# Or:
b = filter(lambda x: x > 4, a)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import cv2
def gene_file_list(filename, num):
with open(filename, 'w') as f:
for i in range(num):
if i % 5:
continue
f.write('img/%.6d.png ' % i)
f.write('img/%.6d.png\n' % i)
f.cl... |
vel = int(input("Velocidade: "))
if vel > 80:
x = int(vel - 80)
val = float(x*7.00)
print("Você foi multado em R${:.2f}, por excesso de velocidade".format(val))
else:
print("Você não possui multas!")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try: # for pip >= 10
from pip._internal.req import parse_requirements
except ImportError: # for pip <= 9.0.3
from pip.req import parse_requirements
from setuptools import setup, find_packages
if sys.version_info < (3, 6):
sys.exit('Sor... |
import wx
from src.ui.menubar import MenuBar
from src.ui.download_list import DownloadList
class MainApplication(wx.Frame):
def __init__(self, *args, **kwargs):
super(MainApplication, self).__init__(*args, **kwargs)
menubar = MenuBar(master=self)
self.download_list = DownloadList(self)
... |
from granite.utils.functional import boost_fn, bf, Function, dump_map, fwd, apply, return_function
from pampy import match, _
from collections.abc import Iterable, Iterator, Mapping
from types import GeneratorType
def make_bench(bench, format):
def make_bench_impl(fn, *args, **kwargs):
return bf(format) ... |
class Solution:
def minCostClimbingStairs(self, cost):
cost_len = len(cost)
table_len = cost_len + 2
table = [10 ** 6] * table_len
table[0] = 0
for i in range(1, table_len):
prev = table[i-1]
table[i] = min(
table[i],
pr... |
acumulador = 0
MaisVelho = 0
contador = 0
NomeDoMaisVelho = ''
for p in range(1,5):
print(f'-----{p}ª PESSOA-----')
nome = str(input('Nome:')).strip()
idade = int(input('Idade:'))
sexo = str(input('Sexo [M/F]:')).lower().strip()
acumulador += idade
if p == 1 and sexo in 'Mm':
MaisVelho ... |
#!/usr/bin/env python
#process the qkids.tsv file to create qkis_score data
#*NB* these athletic idiots are unable to process times properly
#so their spreadsheet had 3.50 for 3:50 and 0.01 instead of 0:01
#bah :(
import sys, os, re, time
medir = os.path.dirname(sys.argv[0])
if not medir: medir = os.getcwd()
try:
f... |
#!/usr/bin/env python3
import os
import io
import sys
import re
import argparse
import json
import xml.etree.ElementTree as ET
# on msys, use crlf output
nl = None
if sys.platform == 'msys':
nl = "\r\n"
# Get the file, relative to this script's location (same directory)
# that way we're not sensitive to CWD
... |
from time import sleep
nome = input('Digite um nome: ')
print('Vamos verificar se seu nome tem Silva...')
sleep(3)
if 'Silva' in nome and nome.upper() and nome.lower():
print('Sim')
else:
print('Não')
|
import os
import sys
import numpy as np
import pandas as pd
from classes.Signal import Signal
from classes.DataSource import DataSource
from classes.SignalClassifier import SignalClassifier
import matplotlib.pyplot as plt
ds = DataSource()
# Load initial labeled training set T
labeled_ds = ds.load_or_process_labeled_d... |
import os
import yaml
def configure():
# Load the config and get the headers setup
config = os.environ.get('GITISSUEBOT_CONFIG', None)
if not config:
return
with open('config.yml', 'r') as stream:
config = yaml.load(stream)
return config
config = configure() |
import unittest
import openmdao.api as om
from openmdao.utils.assert_utils import assert_check_partials, assert_near_equal
import dymos as dm
from dymos.transcriptions.explicit_shooting.test.test_rk_integration_comp import SimpleODE
from dymos.transcriptions.explicit_shooting.ode_evaluation_group import ODEEvaluation... |
import pytest
from salary_calculator.models import Payout
@pytest.mark.salary_calculator_signals
class TestSignals:
def test_update_payout_monthly_earnings(self, day):
day.bonus = 140
day.save()
payout = Payout.objects.get(month=day.month)
assert payout.monthly_earnings == 140
... |
import numpy
def calculate(data, baseline, baselag, cusumFlag, cusumK, minSigma, thresh):
"""
function to implement ears algorithm
data: list of numbers of on which algorithm is applied
baseline: 7 days for each algorithm
baselag: 0 for C1 and 2 for both C2 and C3
cusumFlag: 0 for both C1 and... |
from django import forms
class EmailNotificationForm(forms.Form):
enabled = forms.BooleanField(required=False)
channel_id = forms.EmailField(required=True, label="Send emails to")
notification_id = forms.CharField(widget=forms.HiddenInput(), required=True)
class TelegramNotificationForm(forms.Form):
e... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import SimpleTestCase
from django.utils import translation
from ...utils import setup
class I18nFiltersTests(SimpleTestCase):
libraries = {
'custom': 'template_tests.templatetags.custom',
'i18n': 'django.templatetag... |
from validation import vworkspace
with vworkspace() as w:
w.activate('must_regions')
w.props.constant_path_effects = False
w.all_functions.display('PRINT_CODE_REGIONS')
w.all_functions.display('PRINT_CODE_IN_REGIONS')
w.all_functions.display('PRINT_CODE_OUT_REGIONS')
|
from ._additive_attention import AdditiveAttention
__all__ = ["AdditiveAttention"]
|
def are_anagrams(s1, s2):
if len(s1) != len(s2):
return False
return sorted(s1) == sorted(s2)
s1 = "nameless"
s2 = "salesman"
str1 = "name"
str2 = "mane" |
import os
def loadCredentialsFile(filePath):
data = None
with open(filePath, "r") as f:
data = f.read().splitlines()
if not data:
raise FileNotFoundError
credentials_list = []
for line in data:
username, password = line.split(" ", 1)
new_login = {}
new_... |
from JumpScale import j
descr = """
Sets network for LXC machine
"""
name = "vfs_setnetwork"
category = "vfw"
organization = "jumpscale"
author = "zains@incubaid.com"
license = "bsd"
version = "1.0"
roles = []
def action(name, vxlanid, pubips, dmzips):
import JumpScale.lib.lxc
import JumpScale.baselib.remot... |
import pytest
@pytest.fixture()
def source_simple():
source_simple = "\n".join(["begin\npy{{a=1}}e{{a;b}}end"])
return source_simple
def test_render_inline_code(jupyter, source_simple):
splitter = jupyter.parser.split(source_simple)
next(splitter)
cell = next(splitter)
assert cell.context["c... |
from WordVecDict import WordVecDict
import numpy as np
def readTestDataFile(filename, prefix):
data = []
for line in open(filename, 'r').readlines():
if len(line) == 0:
continue
sentence = []
for w in line.split():
sentence.append(prefix + w)
data.appe... |
#!/usr/bin/python3
# By NOMO
from netmiko import Netmiko
from getpass import getpass
from pprint import pprint
import re
import sys
'''
All of this functions take at least the host_dict parameter.
This is expected to be a dict just like this:
host1 = {
'host': '10.20.20.100',
'username': 'cisco',
'passw... |
import pandas as pd
import glob
import os
# df = pd.read_csv('/home/ec2-user/data/raw/OKEX-BTC-THIS-WEEK-TRADES.csv.2018-09-07.gz',
# compression='gzip',
# )
# print(df.head())
# 1536278411140 0 1411803432779778 BID 6484.75 6.0
# 0 1536278417993 0 1411803879014401 ASK 6... |
# Adapted from score written by wkentaro
# https://github.com/wkentaro/pytorch-fcn/blob/master/torchfcn/utils.py
import numpy as np
class runningScore(object):
def __init__(self, n_classes):
self.n_classes = n_classes
self.confusion_matrix = np.zeros((n_classes, n_classes))
def _fast_hist(se... |
# --------------------------------------------------------
# FPN
# Copyright (c) 2017 BUPT-PRIV
# Licensed under The MIT License [see LICENSE for details]
# Written by Soeaver Yang
# --------------------------------------------------------
import caffe
import numpy as np
import yaml
from fast_rcnn.config import cfg
d... |
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
# lon_0, lat_0 are the center point of the projection.
# resolution = 'l' means use low resolution coastlines.
m = Basemap(projection='ortho',lon_0=-105,lat_0=40,resolution='l')
m.drawcoastlines()
m.fillcontinents(color='coral',... |
from liquer import Q
class B:
bar = 'Hello World!'
baz = 1
class A:
foo = B()
a = A()
q = Q(foo__bar='Hello World!') | Q(foo__bar__istartswith='hello',
foo__baz__gt=1)
assert q(a)
a.foo.bar = 'Hello 2013!'
assert not q(a)
a.foo.baz = 2
assert q(a)
|
from setuptools import setup
setup(
name='nimiq-api-python',
version='0.0.1',
description='A python client for the Nimiq JSON-RPC API',
url='http://github.com/jgraef/nimiq-api-python',
author='Janosch Gräf',
author_email='janosch.graef@cispa.saarland',
license='MIT',
packages=['nimiqrpc... |
import torch
torch.cuda.current_device()
import torch.nn as nn
import torchvision
import random
import pytorch_batch_sinkhorn as spc
# Decide which device we want to run on
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class PixelLoss(nn.Module):
def __init__(self, p=1):
... |
import os
import requests
import time
#download method
def download_file(url, filename):
''' Downloads file from the url and save it as filename '''
# check if file already exists
if not os.path.isfile(filename):
print('Downloading File')
response = requests.get(url)
# Check if the ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__version__ = "0.1.0"
__author__ = "Angus Alves"
__credits__ = "Props to my peeps"
__copyright__ = "(C) 2016-2016 Angus Alves. MIT"
import sys,os,shutil,date
class PythonWrastler:
def __init__(self,packagename=None,author=None,credits=None,created=None,crholder=None,licen... |
#! /usr/bin/python
import sys
import string
import psyco
import gc
#my_data=[line.split for line in file('data.txt')]
from psyco.classes import *
psyco.full()
fileName="data.txt"
thresNum=5
thresProb=0.5
Gcnt=0
class Rule:
def __init__(self,cond=(),rslt=(),prob=0.0,cosn=0.0,lift=1.0):
self.cond=cond
self.rslt=rs... |
from setuptools import setup, find_packages
import re
VERSIONFILE = "Solos/_version.py"
verstrline = open(VERSIONFILE, "rt").read()
VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(VSRE, verstrline, re.M)
if mo:
verstr = mo.group(1)
else:
raise RuntimeError("Unable to find version string in %s." % (... |
"""Package for retrieving and uploading product quantities to Opencart."""
import copy
import json
import logging
import requests
from errors import Error, NotFoundError, MultipleResultsError, CommunicationError
_LIST_PRODUCTS_ENDPOINT = 'module/store_sync/listlocalproducts'
# TODO(nmcapule): Endpoint
_UPDATE_PRODU... |
from datetime import datetime
from django.contrib.auth.models import User
from rest_framework import routers
from rest_framework import serializers
from rest_framework import viewsets
from rest_framework import status
from rest_framework import permissions
from rest_framework.decorators import detail_route
from rest_... |
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
try:
driver.get("https://the-internet.herokuapp.com/javascript_alerts")
button1 = driver.find_element(By.CSS_SELECTOR, '#content > div > ul > li:nth-child(1) > button')
button1.click()
d... |
__author__ = 'Antony Cherepanov'
import pickle
import json
import os
def save_dict_to_file_via_pickle():
print("\nsave_dict_to_file_via_pickle()")
simple_dict = {"key1": 224, "kkl": "strong"}
print("Our dict: " + str(simple_dict))
print("Let's serialise it and save to file")
test_... |
from django.http import JsonResponse
from django.db.models import Count, Q
from django.contrib import messages
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render, get_object_or_404, redirect, reverse
from django.views.generic import View, ListView, DetailView, C... |
#coding:utf-8
#
# id: bugs.core_5970
# title: Built-in cryptographic functions
# decription:
# Issues found during implementing this test - see CORE-6185, CORE-6186.
# This test checks only ability to call ENCRYPT()/DECRYPT() functions with different parameters.
# ... |
class DynamicArray(object):
def __init__(self, capacity=0):
self.capacity = capacity
if not capacity:
self.arr = None
self.len = 0
else:
self.len = 0
self.arr = []
def size(self):
return self.len
def isEmpty(self):
return self.len == 0
def get(self, index):
if ... |
# Time: O(1)
# Space: O(1)
class Solution(object):
def totalMoney(self, n):
"""
:type n: int
:rtype: int
"""
def arithmetic_sequence_sum(a, d, n):
return (2*a + (n-1)*d) * n //2
cost, day = 1, 7
first_week_cost = arithmetic_sequence_sum(cost, co... |
from arch.univariate.mean import ConstantMean
from arrays import ArrayDateIndex
from api_wrap import ApiWrapper
from garch import MyGARCH
from stock import Stock
from utils import Utils
import datetime
import unittest
class MyTestGarch(unittest.TestCase):
def setUp(self):
# S&P 500
self.company = ... |
import json
import os
import time
import numpy as np
import pyUSRP as u
from flask_socketio import emit
from flask_login import current_user
from app import socketio, check_connection, measure_manager, job_manager, app
from diagnostic_text import *
from models import filename_to_abs_path, check_db_measure
from multipro... |
"Cloud service related functionality."
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import concurrent.futures
import requests
import json
OK = 0
ERROR = 1
CONNECT_ERROR = 2
AUTH_ERROR = 3
UPLOAD_ERROR = 4
class Logger(object):
def register_tuner... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.