content stringlengths 5 1.05M |
|---|
import sys
import numpy as np
def main(argv):
matrix_file = argv[1]
output_filename = argv[2]
matrix = np.loadtxt(matrix_file)
def f(x): return 1 / float(x)
f = np.vectorize(f)
matrix = f(matrix)
transformed_matrix = [([0] * len(matrix[0])) for _ in xrange(len(matrix[0]))]
for i, row i... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from google.appengine.ext import ndb
from gallery.gallery_model import Gallery
from config.template_middleware import TemplateResponse
from gaecookie.decorator import no_csrf
from routes.gallerys import edit
from routes.gallerys.new import... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-10-03 18:18
from __future__ import unicode_literals
from django.db import migrations
def backwards_data(apps, schema_editor):
pass
def load_data(apps, schema_editor):
questionnaire_model = apps.get_model("experiments", "Questionnaire")
for ... |
#
import numpy as np
import itertools
import sys
import pdb
from itertools import product
import glob
import os
import math
path='./'
filename = os.path.join(path, '*.out')
for fname in glob.glob(filename):
print fname
P0 = []
P1 = []
P2 = []
with open(fname) as gout:
for line in gout:
if 'DIRECT LATT... |
# -*- coding: utf-8 -*-
"""Utilities for high-level API."""
import json
from typing import Optional
import bioversions
from ..utils.path import prefix_directory_join
__all__ = [
"get_version",
]
def get_version(prefix: str) -> Optional[str]:
"""Get the version for the resource, if available.
:param ... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^listing', views.listing, name='listing'),
url(r'^jsonlisting', views.jsonlisting, name='jsonlisting'),
url(r'^timingListing', views.timingListing, name='timingListing'),
url(r'^iterlist', vie... |
import hashlib
def open_file(path, mode = 'r'):
with open(path, mode) as source:
return source.read()
def encode(string, typ = "utf8"):
return string.encode(typ)
def generate_hash(data):
if not isinstance(data, (str, bytes)):
data = str(data)
if not isinstance(data, bytes):
data = data.encod... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ResourceResp:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is at... |
from .crawling_py.main_crawling import run_crawling
from .views import save_articles
# db에 저장
def article_crawling_job():
politic_article_list, economy_article_list, society_article_list = run_crawling()
print('run_crawling 끝!!')
try:
save_articles(politic_article_list, economy_article_list, society_article_lis... |
# This problem was asked by Facebook.
# Given a circular array, compute its maximum subarray sum in O(n) time. A subarray can be empty, and in this case the sum is 0.
# For example, given [8, -1, 3, 4], return 15 as we choose the numbers 3, 4, and 8 where the 8 is obtained from wrapping around.
# Given [-4, 5, 1, ... |
from __future__ import annotations
import typing
from ctc import spec
from . import erc20_metadata
async def async_normalize_erc20_quantity(
quantity: typing.SupportsFloat,
token: typing.Optional[spec.ERC20Address] = None,
provider: spec.ProviderSpec = None,
decimals: typing.Optional[typing.Support... |
"""
Laplacian of a compressed-sparse graph
"""
import numpy as np
from scipy.sparse import isspmatrix
from scipy.sparse.linalg import LinearOperator
###############################################################################
# Graph laplacian
def laplacian(
csgraph,
normed=False,
return_diag=False,
... |
import asyncio
import logging
import os
import tempfile
from typing import Any, Dict, Text
import gamla
import yaml
class _HelmException(Exception):
pass
async def _run_in_shell(args, path: str) -> Text:
logging.info(f"Running shell command: {args}.")
process = await asyncio.subprocess.create_subproces... |
WHITELIST_COUNTIES = [
"Kajiado",
"Nairobi",
]
_CONSTITUENCIES = "Constituencies"
_SUB_COUNTIES = "Sub Counties"
ADMINISTRATIVE_UNITS = {
"Nairobi": {
_CONSTITUENCIES: (
"Dagoretti North",
"Dagoretti South",
"Embakasi Central",
"Embakasi East",
... |
from flask import Flask, render_template, request,jsonify
import requests
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import LSTM
from keras.layers.core import Dense, Dropout
from keras.models import load_model
import os
# Create flask instance
app = Flask(__name__,stat... |
""" Tabulate the results """
import tabulate
import numpy as np
import pandas as pd
headers= ['model','precision','recall','accuracy','f1']
# Read result file
df=pd.read_json('results.json',lines=True)
df=df.drop(['model','time'],axis=1)
table=list(df.values)
table.sort(key=lambda r:r[-1], reverse=True)
... |
import pytest
from commits import get_min_max_amount_of_commits
@pytest.mark.parametrize('year, expected', [
(None, ('2018-02', '2017-01')), # parse the whole file
(2017, ('2017-11', '2017-01')),
(2018, ('2018-02', '2018-10')),
(2019, ('2019-01', '2019-03')),
])
def test_get_min_max_amount_of_commit... |
import os
from bot import Bot
token = os.getenv("TOKEN")
cvv_uname = os.getenv("CVV_UNAME")
cvv_passwd = os.getenv("CVV_PASSWD")
accu_weather_token = os.getenv("ACCU_WEATHER_TOKEN")
if token == "":
raise Exception("Invalid Token")
print("Started")
Bot(token, cvv_uname, cvv_passwd, accu_weather_token).start()
|
# -*- coding: utf-8 -*-
from protocols.ppatProtocol import Circuit,Gate,Worker,Client
from Crypto.Random.random import randint
import nizkproofs.nizkpok as nizk
import mathTools.invMatrix as iM
import mathTools.field as field
import math
import numpy
class LinearSystemPPATSWorker(Worker):
def makeCircuit(self):
... |
"""This module was made to fork the rogue access point."""
import os
import sys
import subprocess
import time
from subprocess import check_output
import roguehostapd.apctrl as apctrl
import roguehostapd.config.hostapdconfig as hostapdconfig
DNS_CONF_PATH = '/tmp/dnsmasq.conf'
DHCP_LEASE = "10.0.0.2,10.0.0.100,12h"
... |
# Generated by Django 3.2.7 on 2021-12-30 16:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ask_a_mentor', '0003_auto_20211230_2333'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='time'... |
from math import floor, ceil
HVal=2.0
def _normalize_vals(vals):
if len(vals) > 5: return ''
vals = [float(i) for i in vals]
mn = float(min(vals))
norm_vals = [ v-mn for v in vals ]
starter = norm_vals[0]
for i in range(5-len(norm_vals)):
norm_vals.insert(0, starter)
mx = float(ma... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
from statistical_modeling.distributions.discrete_uniform import (
Distribution,
Mean,
Variance
)
from typing import Final
import unittest
class TestDiscreteUniform(unittest.TestCase):
d: Final = Distribution(1, 100)
def test_distribution(self):
self.assertEqual(self.d.a, 1)
self... |
images_path = ""
|
from __future__ import absolute_import, division, print_function, unicode_literals
import argparse
import logging
import os
import sys
import re
import tensorflow as tf
tf.keras.backend.clear_session()
from callbacks import CallBacks
from model_factory import GetModel
from preprocess import Preprocess, format_example... |
import pickle
from ds import *
import pandas as pd
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import StandardScaler
from sklearn import metrics
import numpy as np
from sklearn.impute i... |
'''
思考路線:
1.找到PTT表特版網址,get表特版原始碼
2.由表特版的原始碼,匹配get各個文章網址列表
3.由各個文章原始碼,匹配單一文章中各個圖片網址列表
4.由各個圖片網址列表,下載儲存圖片(由二進位碼寫入檔案中儲存.jpg格式)
'''
from selenium import webdriver
from selenium.webdriver.common.by import By
import requests
import re
import os
from urllib.request import urlretrieve
from urllib import requ... |
# Takes a .json input file and formats it to a csv file
# Usage: python json_to_csv.py <input file>.json <output_file>.csv
import json
import sys
import html
# Simple argument handling
input_file = sys.argv[1]
output_file = sys.argv[2]
with open(input_file) as infile, open(output_file, 'w') as outfile:
data = js... |
#!/usr/bin/env python3
"""Test the configuration module."""
import multiprocessing
import os
import sys
import os.path
import unittest
import shutil
import random
import string
import tempfile
import yaml
# Try to create a working PYTHONPATH
TEST_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
SWITCHMAP_DIREC... |
import tensorflow as tf
from models.item_ranking.cdae import CDAE
from utils.evaluation.RankingMetrics import evaluate
class ModifiedCDAE(CDAE):
def __init__(self, sess, num_user, num_item, nn_factors=None, **kwds):
super(ModifiedCDAE, self).__init__(sess, num_user, num_item, **kwds)
self.nn_fact... |
#pre-processing for ON hospital data
#read shapefile, output csv
#limit ourselves to hospitals
#Also turn 'POINT' Geometry into lat and lon
import geopandas as gpd
import pandas as pd
#read shapefile with geopandas into geodataframe
sc1=gpd.read_file('/home/csis/codes/shape_to_csv/MOH_SERVICE_LOCATION.shp')
sc1=pd.D... |
import math
import numpy
def parenthesis_finder(str):
inner_str = str[str.find("(")+1:str.rfind(")")]
return inner_str
events = input("Enter event:")
balls = {
"blue":5.0,
"red":6.0,
"white":4.0
}
balls_list = list(balls.values())
total_balls = sum(balls_list)
inside_parenthesis = parenthesis_finder(events)
... |
"""docstring for models init file."""
|
#!/usr/bin/env python
from types import SimpleNamespace
from typing import List, Optional, Tuple
import re
def flatten_string_list(l: List[List[str]]) -> List[str]:
"""Flatten a list of list of str
Args:
l (List[List[str]]): [description]
Returns:
List[str]: [description]
"""
ret... |
"""Unit test package for shipflowmotionshelpers."""
import os
path = os.path.dirname(__file__)
path_test_project_1 = os.path.join(path,'test_project_1') |
### Importing libraries
import pandas as pd
import numpy as np
from datetime import datetime
from lightgbm import LGBMRegressor
# import gresearch_crypto
import traceback
import time
from datetime import datetime
import matplotlib.pyplot as plt
import plotly.graph_objects as go
from sklearn.model_selection import GridS... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import ofd
import config
class TestOFDYa(unittest.TestCase):
""" E2E unittest OFD-interactions """
OFD = None
@classmethod
def setUpClass(cls):
""" Setup """
config.debug = False
cls.OFD = ofd.OFDProvider(True).detect(... |
# Visit https://www.gluu.org/docs/gluu-server/user-management/scim-scripting/ to learn more
from org.gluu.model.custom.script.type.scim import ScimType
import java
class ScimEventHandler(ScimType):
def __init__(self, currentTimeMillis):
self.currentTimeMillis = currentTimeMillis
def init(self, confi... |
#coding=utf-8
from mongoengine import *
import logging
import datetime
from app.customer.models.user import User, UploadImage
from base.core.util.dateutils import datetime_to_timestamp
from django.db import models
from PIL import Image, ImageFilter
import multiprocessing
from base.settings import CHATPAMONGO
from app.c... |
import json
import time
import requests
from Lib import DocSegmentation
DOCKER = False
ENDPOINT = "http://localhost:8080/api/v1"
DOCUMENT = 'Document2'
'''
Post request
'''
def post_request(path, json, headers=None):
url = F'{ENDPOINT}/{path}'
headers = headers or {}
headers['Content-Type'] = 'appl... |
import pygame
class Ship():
def __init__(self, game_settings, screen):
"""Initialize ship and define ship start position"""
self.screen = screen
self.game_settings = game_settings
self.image = pygame.image.load("Images/kolmnurkvaike.bmp")
self.rect = self.image.get_rect()
... |
# -*- coding: utf-8 -*-
import logging
from pyramid.events import BeforeRender
from pyramid.events import subscriber
from pyramid.renderers import get_renderer
from amnesia import helpers
log = logging.getLogger(__name__) # pylint: disable=invalid-name
def includeme(config):
config.scan(__name__)
@subscrib... |
import asyncio
import logging
import time
from typing import Optional, Any, List, Dict
from collections.abc import Iterable
from .logger import setup_custom_logger
import ray
logger = setup_custom_logger(__name__)
class Empty(Exception):
pass
class Full(Exception):
pass
# TODO(Clark): Update docstrings ... |
class ThemeBoneColorSet:
active = None
normal = None
select = None
show_colored_constraints = None
|
counter = 0
while counter < 10:
counter += 1
if counter == 3:
continue
print("No teller vi: " + str(counter))
|
"""
572. Subtree of Another Tree
Example 1:
Given tree s:
3
/ \
4 5
/ \
1 2
Given tree t:
4
/ \
1 2
Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:
3
/ \
4 5
/ \
1 2
/
0
Given t... |
"""
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2012 Nathanael C. Fritz
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
from sleekxmpp.plugins.base import register_plugin
from sleekxmpp.features.feature_preapproval.preapproval import FeaturePreApproval
from sleek... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 2 11:18:20 2021
@author: h2jw
"""
import pandas as pd
# SELECT TEST VISUALIZATION NUMBER
nb = 4
#%%
topic_desc = f"/Users/h2jw/Documents/GitHub/NLP-FOMC/LDA_qje/LDA QJE test {nb}/topic_description.csv"
t_desc = pd.read_csv(topic_desc)
pres ... |
import numpy as np
v = np.array([1,2,3])
print("Vector")
print(v) # [1 2 3]
np.shape(v) # (3,)
# Creamos matriz columna
v[:, np.newaxis]
"""
v valdrá:
array([[1],
[2],
[3]])
"""
v[:,np.newaxis].shape # (3, 1)
# Matriz fila
v[np.newaxis,:].shape # (1, 3) |
"""
Given a circular array (the next element of the last element is the first
element of the array), print the Next Greater Number for every element. The
Next Greater Number of a number x is the first greater number to its
traversing-order next in the array, which means you could search circularly
to ... |
# Copyright 2018 BLEMUNDSBURY AI 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 agreed to ... |
#
# PySNMP MIB module JUNIPER-LSYSSP-NATDSTRULE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-LSYSSP-NATDSTRULE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:49:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ve... |
from django.shortcuts import render
from .models import Carousel, LearnLink, LearnPresentation
from play.models import Game
def homepage(request):
item_list = Carousel.objects.all()
game_list = Game.objects.all()
context = {
'game_list': game_list,
'item_list': item_list,
'item_id... |
# -*- coding:utf-8 -*-
import re
import os.path
def is_chinese(uchar):
"""判断一个unicode是否是汉字"""
if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
return True
else:
return False
f1=open('inf.txt','r')
f2=open('outf.txt','w')
with open('word.json','r') as dtf:
pydt=eva... |
# Copyright 2020 The KNIX Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... |
from unittest import TestCase
from earful.contacts import (
EmailAddress,
PhoneNumber,
HipChat,
Recipient,
Group,
)
class ContactInformationTest(TestCase):
def test_hipchat_defaults(self):
instance = HipChat('contactname', 'roomname')
self.assertEqual(instance.name, 'conta... |
#!/usr/bin/python
############################################################################
#
# mirror is a tool for handling MIRROR commands.
#
############################################################################
import argparse
import getopt
import json
import os
import re
import sys
import swsssdk
from ... |
from django.views.generic.base import ContextMixin
from django.utils.translation import ugettext_lazy
# pylint: disable=too-few-public-methods
class OrganizationContextMixin(ContextMixin):
"""
This mixin provides extra context for organization views
"""
extra_context = {
"delete_dialog_title":... |
#!/usr/bin/python
#
# Copyright (c) 2017, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
#
# All rights reserved.
#
# The Astrobee platform is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in comp... |
#!/usr/bin/env python
from cStringIO import StringIO
import requests
import tarfile
import sys
install_dir = "/usr/local"
print "Downloading a CheesePi install into "+install_dir+"..."
# Location of the most recent release of the CheesePi code
code_url = "http://cheesepi.sics.se/files/cheesepi.tar.gz"
response = No... |
import os
from glob import glob
from monty.serialization import loadfn
from propnet import logger
from propnet.core.symbols import Symbol
# Auto loading of all allowed properties
# stores all loaded properties as PropertyMetadata instances in a dictionary,
# mapped to their names
DEFAULT_SYMBOLS = {}
_DEFAULT_SYMB... |
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Empire_of_Movies.settings')
import django
django.setup()
from articles.models import Movie
movie_list = Movie.objects.all()
for movie in movie_list:
movie.update() |
# To generate password and overwrite setting manully
from notebook.auth import passwd
import os,re
print("Generating config")
config_path = os.path.expanduser('~/.jupyter/jupyter_notebook_config.py')
with open(config_path,'r') as f:
content = f.read()
if "disable_password" in os.environ and os.environ['disable_pas... |
from back.models import ClusterLogs
def test_post_model(session):
post = ClusterLogs(DeviceID="1")
session.add(post)
session.commit()
assert post.id > 0 |
from collections import Counter
with open('./inputs/02.txt') as f:
ids = f.readlines()
def count23(id):
count = Counter(id)
exactly_two = bool({k for k, v in count.items() if v == 2})
exactly_three = bool({k for k, v in count.items() if v == 3})
return exactly_two, exactly_three
def solve(ids):
... |
import time
from multiprocessing import cpu_count
import numpy as np
import pandas as pd
from mlforecast.core import TimeSeries
from mlforecast.forecast import Forecast
from sklearn.linear_model import LinearRegression
from window_ops.ewm import ewm_mean
from window_ops.expanding import expanding_mean
def main() -> ... |
import pytest
from asynctest import (
mock as async_mock,
TestCase as AsyncTestCase,
)
from ......messaging.request_context import RequestContext
from ......messaging.responder import MockResponder
from ......storage.error import StorageNotFoundError
from ......transport.inbound.receipt import MessageReceipt
... |
import asyncio
import json
import logging
from typing import Any, Dict
from urllib.parse import unquote
from anyio.exceptions import IncompleteRead
from p2pclient import Client as P2PClient
from p2pclient.pb.p2pd_pb2 import PSMessage
from p2pclient.utils import read_pbmsg_safe
from aleph.services.ipfs.pubsub import s... |
#!/usr/bin/python
from __future__ import unicode_literals, print_function, absolute_import
import gevent.monkey
gevent.monkey.patch_all()
import psycogreen.gevent
psycogreen.gevent.patch_psycopg()
import application
import logging
import os
import os.path
import json
import argparse
import gevent.wsgi
app = applicat... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.spectral_norm import spectral_norm
from torch.nn.utils.spectral_norm import remove_spectral_norm
from utils.utils import VGG16Partial, device
class ConvBlock(nn.Module):
'''(conv => BN => LeakyReLU)'''
def __init__(self, in_... |
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
import math
import re
from ml_pipeline_lch import isolate_noncategoricals
def view_dist(df, geo_columns):
'''
Plot distributions of non-categorical columns in a given dataframe
Inputs:
df: pandas dat... |
from django.core.management.base import BaseCommand
from django.core.serializers.base import ProgressBar
from django.core.cache import caches
from evap.evaluation.models import Evaluation
from evap.results.tools import collect_results
from evap.results.views import warm_up_template_cache
class Command(BaseCommand):
... |
prefixes = "JKLMNOPQ"
for letter in prefixes:
if letter[0] == "Q" or letter[0] == "O":
print(letter + "uack")
else:
print(letter + "ack")
#https://pt.stackoverflow.com/q/305011/101
|
import os
import glob
import sys
root_py_folder = "klampt"
if sys.version_info[0] == 2:
#python2 version has drifted from current Python3 version... maintain separate packages list for compatibility
root_py_folder = "python2_version/klampt"
subpackages = ['apps','io','math','model','model/create','plan','p... |
"""Extras URLs."""
# Django
from django.urls import include, path
# Django REST Framework
from rest_framework.routers import DefaultRouter
# Views
from compras import views
router = DefaultRouter()
router.register(r'compras/views/pasarela.html', views.CompraViewSet, basename='compras')
urlpatterns = [
path('',... |
#######################################################################################################
# Python program to create long biographies from the provided .csv file #
# Code adapted from Jia Zhang #
# Writte... |
import torch
import numpy as np
import torch.nn as nn
from torch.nn import init
import torch.optim as optim
import os
from torch.autograd import Variable
from torch.nn.functional import conv1d
from scipy import signal
import torch.nn.functional as F
import pdb
class ordLoss(nn.Module):
"""
Ordi... |
from django.conf.urls import include, patterns, url
from tastypie.api import Api
import mozillians.groups.api
import mozillians.users.api
v1_api = Api(api_name='v1')
v1_api.register(mozillians.users.api.UserResource())
v1_api.register(mozillians.groups.api.GroupResource())
v1_api.register(mozillians.groups.api.Skil... |
import random
import time
def temp_model(filename):
# ans : eval_image_classifier.py 로 넘기기
print('[ {} ]'.format(ans), flush=True)
return ans
|
import pytest
from k8_vmware.helpers.TestCase_VM import TestCase_VM
from k8_vmware.vsphere.Datastore import Datastore
from k8_vmware.vsphere.VM_Device import VM_Device
class test_VM_Device(TestCase_VM):
vm_name = f"tests__unit__" + __name__
def setUp(self) -> None:
self.vm_name = test_VM_Device.vm_na... |
# -*- coding: utf-8 -*-
from sqlalchemy import Column, String
from sqlalchemy.orm import declarative_base
from zvt.contract import Mixin
from zvt.contract.register import register_schema
NewsBase = declarative_base()
class StockNews(NewsBase, Mixin):
__tablename__ = "stock_news"
#: 新闻标题
news_title = Co... |
import smtplib
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
EMAIL = 'sender@gmail.com'
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
with open('... |
"""
transformDiagMatDemo: demo for transfDiagMagDemo
- source:https://github.com/flaberenne/python3rep/transformDiagMatDemo.py
- author:flaberenne
"""
import transformDiagMat as f
a=[[1 ,2 ,3, 4,5],[6 ,7 ,8 ,9, 10 ],[ 11 ,12 ,13,14,15],[16 ,17,18,19,20],[21,22,23,24,25]]
print("*************")
print("Orig... |
#!/usr/bin/python
import commands
import glob
import itertools
import Queue
import os
import os.path
import shutil
import subprocess
import sys
import threading
import time
import traceback
import zipfile
import class_cache
import symlink
BUILD_DIR = "build"
ICBM_PATH = os.path.abspath(os.path.dirname(__file__))
cl... |
from django.contrib import auth
from django.contrib.auth import logout
from django.shortcuts import redirect, render_to_response, RequestContext
from django.template.context_processors import csrf
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.contrib... |
import base64
import json
import zlib
from typing import Any, List
import pytest
from aws_lambda_powertools.utilities.parser import ValidationError, envelopes, event_parser
from aws_lambda_powertools.utilities.parser.models import CloudWatchLogsLogEvent, CloudWatchLogsModel
from aws_lambda_powertools.utilities.typing... |
#!/usr/bin/env python3
from copy import deepcopy
import os
from typing import List, Union
from .config import Config, ConfigDict
from .env import docker
class Image:
def __init__(
self,
name: str,
image_cfg: ConfigDict,
) -> None:
self.name = name
self.path = image_cf... |
# -*- coding: utf-8 -*-
import layers
import tensorflow as tf
from network import Network
class QNetwork(Network):
def __init__(self, conf):
super(QNetwork, self).__init__(conf)
with tf.variable_scope(self.name):
self.target_ph = tf.placeholder('float32', ... |
import ConfigParser, json, logging, socket, time
import pika
import pika.exceptions
from multiprocessing import Process, Queue
from Queue import Empty
from ssl import CERT_OPTIONAL
from monitor.delayqueue import *
import monitor.core
class Message(object):
"""
Data for a message to be pushed to RabbitMQ
... |
#! /usr/local/bin/python
"""
See LICENSE file for copyright and license details.
"""
from modules.constant import *
from sqlalchemy import Column, Integer, String, Numeric
from meta import Base
class V_FINANCE(Base):
""" V_FINANCE """
__tablename__ = View.FINANCE
__table_args__ = {'autoload':True}
... |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2017 beyond-blockchain.org.
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 l... |
import os
import pytest
from parso.utils import PythonVersionInfo
from jedi.inference.gradual import typeshed, stub_value
from jedi.inference.value import TreeInstance, BoundMethod, FunctionValue, \
MethodValue, ClassValue
TYPESHED_PYTHON3 = os.path.join(typeshed.TYPESHED_PATH, 'stdlib', '3')
def test_get_type... |
import re
import unidecode
from src import *
def clean_url(url_str):
"""
Cleans a given URL.
:param url_str: String formatted URL.
:return: Cleaned string formatted URL.
"""
url_str = url_str.lower()
url_str = url_str.strip()
return url_str
def clean_name(name_str):
"""
Clea... |
import pytest
from aioresponses import aioresponses
from demo_project.api.dependencies import azure_scheme
from demo_project.core.config import settings
from demo_project.main import app
from pytest_cases import parametrize_with_cases
from tests.utils import build_openid_keys, keys_url, openid_config_url, openid_config... |
# 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"); you m... |
# Read entries from JSON file; create new file with entries
# in a new (randomized) order
import json
import random
# Read in the file (assumes it is in current working directory)
with open('questions.json') as f:
questionDict = json.load(f)
# There is only the 1 list as the 1 object's value
questionList = list(... |
import torch
import torch.nn.functional as F
def reduce_mean(tensor, dim=None, keepdim=False, out=None):
"""
Returns the mean value of each row of the input tensor in the given dimension dim.
Support multi-dim mean
:param tensor: the input tensor
:type tensor: torch.Tensor
:param dim: the di... |
# Copyright 2017 Google 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 required by applicable law or a... |
# Copyright (c) 2020 Horizon Robotics. 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 applicab... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.