content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
import torch
from classy_vision.generic.util import get_torch_version
from classy_vision.models import... |
n=int(input('enter a number : '))
for i in range(n):
for j in range(n):
print(j+1,end=" ")
print()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/3/4 15:03
# @Author : DaiPuWei
# E-Mail : 771830171@qq.com
# blog : https://blog.csdn.net/qq_30091945
# @Site : 中国民航大学北教25-506实验室
# @File : WineQuality_Reduction.py
# @Software: PyCharm
import numpy as np
import pandas as pd
impor... |
""" test elstruct.writer
"""
from elstruct import writer
def test__programs():
""" test writer.programs
"""
assert set(writer.programs()) >= {
'cfour2', 'gaussian09', 'gaussian16', 'molpro2015', 'mrcc2018', 'psi4'}
def test__optimization_programs():
""" test writer.optimization_programs
... |
#coding:utf-8
a = open('subtopic.csv','r')
b = open('NoVec_but_subtopic.csv','r')
c = open('NoVec_and_bin.csv','r')
dict_topic_sub = {}#key=topic, value=set_of_subtopic
num=0
for i in a:
num+=1
if num>1:
LINE = i.rstrip().split(',')
topic = LINE[3]
sub = LINE[5]
if sub != '100':
dict_topic_sub.setdefau... |
from typing import TypeVar, Union
from .base import Matcher
from .equal import equal_to
T = TypeVar("T")
def as_matcher(value: Union[Matcher[T], T]) -> Matcher[T]:
if isinstance(value, Matcher):
return value
else:
return equal_to(value)
|
# -*- coding: utf-8 -*-
# 导入模块
import sys
from PyQt5.QtWidgets import QMainWindow , QApplication
from PyQt5.QtCore import Qt
### 自定义窗口类
class MyWindow( QMainWindow):
'''自定义窗口类'''
### 构造函数
def __init__(self,parent=None):
'''构造函数'''
# 调用父类构造函数
super(MyWindow,self).__init__(parent... |
from ..core.uuid import uuid_from_func
from ..core.files import load_object, save_object
from typing import Optional
from loguru import logger
from pathlib import Path
from ..core.paramconverter import ParameterConverter
def _fscache(func, directory='./.tmp', paramconverter: Optional[ParameterConverter] = None, json:b... |
from microbit import *
import Robit_stepper
theBoard = Robit_stepper.Robit()
while True:
if button_a.is_pressed():
theBoard.StepperDegree(1, 500, "W")
elif button_b.is_pressed():
theBoard.StepperDegree(1, -500, "W")
else:
theBoard.MotorStopAll()
|
class Length:
__metric ={"mm": 0.001, "cm":0.01, "m":1, "km":1000, "in":0.0254, "ft":0.3048, "yd":0.9144, "mi":1609.344}
def init (self, value, unit="m"):
self.value = value
self.unit = unit
def conver2metre(self):
return self.value * Length.__metric[self.unit]
def a... |
# GENERATED BY KOMAND SDK - DO NOT EDIT
import komand
import json
class Component:
DESCRIPTION = "Get information about a user"
class Input:
ID = "id"
class Output:
_ID = "_id"
_TYPE = "_type"
CREATEDAT = "createdAt"
CREATEDBY = "createdBy"
HASKEY = "hasKey"
ID = "id"
NAME ... |
import os
import onnx
import torch
from src.anti_spoof_predict import AntiSpoofPredict
import argparse
from onnxsim import simplify
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--weights_file', type=str, default='./resources/anti_spoof_models/2.7_80x80_MiniFASNetV2.pth',
... |
# Pensar em inteface
# Projetar interface |
from testify import *
import datetime
import pytz
from dmc import (
Time,
TimeInterval,
TimeSpan,
TimeIterator,
TimeSpanIterator)
class InitTimeTestCase(TestCase):
def test_direct(self):
d = Time(2014, 4, 18, 17, 50, 21)
assert_equal(d.year, 2014)
assert_equal(d.month... |
import torch
from torch import nn
class ConvEncoder(nn.Module):
def __init__(self, num_channels, ngf=512, **kwargs):
super().__init__()
self.net = nn.Sequential(
nn.Conv2d(num_channels, ngf // 8, 3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(ngf // 8),
nn.... |
from pytorch_trainer.training import extensions # NOQA
from pytorch_trainer.training import triggers # NOQA
from pytorch_trainer.training import updaters # NOQA
from pytorch_trainer.training import util # NOQA
# import classes and functions
from pytorch_trainer.training.extension import Extension # NOQA
from pyto... |
"""This module tests the ConstantUnitaryGate class."""
from __future__ import annotations
from hypothesis import given
from bqskit.ir.gates import ConstantUnitaryGate
from bqskit.qis.unitary.unitarymatrix import UnitaryMatrix
from bqskit.utils.test.strategies import unitaries
@given(unitaries())
def test_constant_u... |
from numpy import inf, nan
from sklearn.linear_model import ElasticNetCV as Op
from lale.docstrings import set_docstrings
from lale.operators import make_operator
class ElasticNetCVImpl:
def __init__(self, **hyperparams):
self._hyperparams = hyperparams
self._wrapped_model = Op(**self._hyperparam... |
from flask import Flask, render_template
from flask import request, abort, url_for
import json
import html
from json2html import *
app = Flask(__name__)
# read file
with open('./data/products.json', 'r') as myfile:
pro_data = myfile.read()
@app.route("/products")
def products():
"""Products page for web app... |
# GENERATED BY KOMAND SDK - DO NOT EDIT
from .calculate.action import Calculate
from .max.action import Max
|
CHAINS = [
{
"chain_code": "btc",
"shortname": "BTC",
"fee_coin": "btc",
"name": "Bitcoin",
"chain_model": "utxo",
"curve": "secp256k1",
"chain_affinity": "btc",
"qr_code_prefix": "bitcoin",
"bip44_coin_type": 0,
"bip44_last_hardened_le... |
from iotempower import *
# general init
w = wifi("ehdemo-iotempire", "internetofthings", reset=False)
mqtt("192.168.10.254", "testfloor/devkit1-01", user="homeassistant", password="internetofthings",
client_id="devkit1-01")
# devkit1 button/led shield
button("lower", d0, "depressed", "pressed")
button("left", d3... |
import torch
from torchvision import transforms, datasets
from torchvision.datasets.folder import find_classes
from .sampler import BalancedSubsetRandomSampler, RandomSampler
def folder(root, num_workers=2, batch_size=64, img_size=224, sample_per_class=-1, data_augmentation=False):
base_transform = transforms.Co... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.template.loader import render_to_string
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.svm import SVC
from sklearn import neig... |
import os
import torch
import torch.utils.ffi
from torch.utils.ffi import create_extension
strBasepath = os.path.split(os.path.abspath(__file__))[0] + '/'
print("strBasepath")
print(strBasepath)
strHeaders = ['src/my_lib.h']
strSources = ['src/my_lib.c']
strDefines = []
strObjects = []
if torch.cuda.i... |
import numpy as np
import cv2
import os
#SEBASTIAN DE LA CRUZ GUTIERREZ PUJ
class colorImage: #Crear clase
def __init__(self,path_file): #se define el constructor
self.image = cv2.imread(path_file,1) #se carga la imagen via opencv
def displayProperties(self): #se define el metodo p... |
import pygame as pg
import sys
from game_of_life import GameOfLife
class InputBox:
def __init__(self, x, y, w, h, text=''):
self.rect = pg.Rect(x, y, w, h)
self.color = (255, 255, 255)
self.text = text
self.font = pg.font.Font("assets/ARCADECLASSIC.ttf", 50)
self.txt_surfa... |
import mysql.connector
import datetime
import common, secure
def create_connection(dbname):
db_host = secure.host() or "127.0.0.1"
cnx = mysql.connector.connect(user=secure.username(),
password=secure.password(),
host=db_host... |
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views as account_management_views
from .forms import (
FantasySportsAuthenticationForm,
FantasySportsChangePasswordForm,
FantasySportsPasswordResetForm,
FantasySportsSetPasswordForm,
)
urlpatterns = [
... |
from shared import OPAYGOShared
from shared_extended import OPAYGOSharedExtended
class OPAYGODecoder(object):
MAX_TOKEN_JUMP = 64
MAX_TOKEN_JUMP_COUNTER_SYNC = 100
MAX_UNUSED_OLDER_TOKENS = 8*2
@classmethod
def get_activation_value_count_and_type_from_token(cls, token, starting_code, key, last_co... |
# -*- coding: utf-8 -*-
def test_cub_download():
from africanus.util.cub import cub_dir
cub_dir()
|
import pandas as pd
import csv
filepath = "../data/merged/watersheds_drainage_within_5percent.csv"
watershed_stats_df = pd.read_csv("../data/scrape_results/watershed_stats.csv")
indexNames = watershed_stats_df[((watershed_stats_df['drainage_area'] / watershed_stats_df['drainage_area_gross']) - 1).abs() <= 0.05].inde... |
# # def get_equipment_that_has_offensive_bonuses(player_stats, ignore, equipment_data=get_equipment_data()):
# # e = defaultdict(list)
# # for slot, slot_equipment in equipment_data.items():
# # for ID, equipment in slot_equipment.items():
# # if equipment['name'] in ignore:
# # continue
# # if any(... |
import logging
from typing import Any, Dict, Optional, Tuple
import lumos.numpy as lnp
from lumos.models.base import model_io, ModelReturn
from lumos.models.tires.base import BaseTire
logger = logging.getLogger(__name__)
@model_io(
inputs=(
"Fz", # vertical load
"kappa", # slip ratio
"... |
from time import sleep
print(" ")
print("░█████╗░░█████╗░██╗░░░░░░█████╗░██╗░░░██╗██████╗░██╗░░░██╗")
print("██╔══██╗██╔══██╗██║░░░░░██╔══██╗██║░░░██║██╔══██╗╚██╗░██╔╝")
print("██║░░╚═╝███████║██║░░░░░██║░░... |
import os
import re
import pandas as pd
from pyBigstick.orbits import df_orbits
import numpy as np
nuclear_data = pd.read_json('pyBigstick/nuclear_data.json')
# script comments
option_comment = '! create densities\n'
name_comment = '! output file name\n'
sps_comment = '! orbit information\n'
valence_comment = '! # of... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 22 10:20:05 2021
@author: qizhe
"""
from collections import defaultdict
from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
"""
读题
1、这题本身不难,建个字典统计一下就是了
2、进阶里面让空间复杂O1
3、其实,最多只需要返回2个数,最... |
import os
import sys
from setuptools import find_packages, setup
IS_RTD = os.environ.get("READTHEDOCS", None)
version = "0.4.0b14.dev0"
long_description = open(os.path.join(os.path.dirname(__file__), "README.rst")).read()
install_requires = [
"morepath==0.19",
"alembic",
"rulez>=0.1.4,<0.2.0",
"inv... |
l = [1,2,1,1,3,2]
print(l)
l = list(set(l))
print(l) |
# 017 -calcule o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo e
# mostre o comprimento da hipotenusa
import math
cateto1 = float(input('Cateto 1:'))
cateto2 = float(input('Cateto 2:'))
print('O valor da hipotenusa é: {:.2f}' .format(math.hypot(cateto1, cateto2)))
|
#!/usr/bin/env python3
import argparse, os
import qrcode.console_scripts as qr
# Change to script directory:
current_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(current_path)
filename = f'{current_path}/authenticator.txt'
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", help="pa... |
# modify from clovaai
import logging
import os
import re
import cv2
from torch.utils.data import Dataset
class BaseDataset(Dataset):
def __init__(self, root, gt_txt=None, transform=None, character='abcdefghijklmnopqrstuvwxyz0123456789',
batch_max_length=100000, data_filter=True):
assert... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from contextlib import ExitStack
from torch.distributions import biject_to
from torch.distributions.transforms import ComposeTransform
import pyro
import pyro.distributions as dist
from pyro.poutine.plate_messenger import block_plate... |
#!/usr/bin/env python3
import logging
import re
import subprocess
# from collections import namedtuple
import xml.etree.ElementTree as ET
import random
import string
import os
import requests
logger = logging.getLogger(__name__)
def bx_login(endpoint, user, pwd, account, resource_group = 'Default'):
'''Blumix log... |
import logging
import time
from django.conf import settings
from .collector import statsd
PROCESSING_TIME_METRIC_PREFIX = getattr(
settings, 'PROCESSING_TIME_METRIC_PREFIX', 'processing_time'
)
REQUESTS_COUNTER_METRIC_PREFIX = getattr(
settings, 'REQUESTS_COUNTER_METRIC_PREFIX', 'requests_count'
)
METRIC_NA... |
"""
Copyright 2020 Goldman Sachs.
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 di... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 Red Hat, 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 requir... |
__all__ = [
'FileLoadingException',
'NodeRemovalException',
'NodeReferenceException',
]
class FileLoadingException(Exception):
pass
class NodeRemovalException(Exception):
pass
class NodeReferenceException(Exception):
pass
|
# Generated by Django 2.1.2 on 2019-03-27 09:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wiki', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='documentversion',
... |
# B2053-求一元二次方程
a, b, c = map(float, input().split())
delta = (b ** 2 - 4 * a * c)
if delta < 0:
print('No answer!')
elif delta == 0:
aaaa = ((-b + delta ** 0.5) / (2 * a))
print('x1=x2=' + '%.5f' % (aaaa))
elif delta > 0:
aaaa = ((-b + delta ** 0.5) / (2 * a))
bbbb = ((-b - delta ** 0.5) ... |
# Title : Linked list implementation in python
# Author : Kiran raj R.
# Date : 30:10:2020
class Node:
"""Create a node with value provided, the pointer to next is set to None"""
def __init__(self, value):
self.value = value
self.next = None
class Simply_linked_list:
"""create a empty... |
#!/usr/bin/env python3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from codecs import open
from os import path
import sys
import re
import csv
import os
# OptionParser imports
from optparse import OptionParser
from optparse import OptionGroup
# Pytho... |
# Copyright (C) 2014 SignalFuse, Inc.
# Copyright (C) 2015 SignalFx, Inc.
# Maestro extension that can be used for wrapping the execution of a
# long-running service with log management scaffolding, potentially sending the
# log output to a file, or through Pipestash, or both, depending on the use
# case and parameter... |
# 由真值和预测值的txt文档得到混淆矩阵
import numpy as np
def mixmatrix():
# 初始化,a矩阵用来存结果
a = np.zeros((7,7), dtype = int)
try:
f_pred = open('predvalue.txt', mode='r')
f_true = open('truevalue.txt', mode='r')
lines_t = f_true.readlines()
lines_p = f_pred.readlines()
f... |
import tempfile
import os
from PIL import Image
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Recipe, Tag, Ingredient
from recipe.serializers import ... |
"""train a handwritten digit classifier."""
from typing import List, Mapping, Tuple
import jax
import jax.numpy as jnp
import opax
import pax
import tensorflow_datasets as tfds
from tqdm.auto import tqdm
Batch = Mapping[str, jnp.ndarray]
class ConvNet(pax.Module):
"""ConvNet module."""
layers: List[Tuple[... |
from enum import IntEnum
class TriggerCategory(IntEnum):
Undefined = -1
Cause = 0,
Condition = 1,
Area = 3,
Filter = 4,
Effect = 5 |
#Code for training the model
# WRITTEN BY:
# John Torr (john.torr@cantab.net)
#standard library imports
import argparse
import copy
import os
from numpy import float64
from time import strftime
from typing import DefaultDict, List, Tuple
#third party imports
import torch.optim as optim
from sklearn.metrics import ... |
import functools
import inspect
from types import MappingProxyType
from typing import Any, Callable, Dict, List, Optional, Tuple
def autoincrement(fn: Optional[Callable] = None, *, start: int = 1): # pragma: no cover
"""Decorate registered callables to provide them with a source of uniqueness.
Args:
... |
"""
Module for jenkinsapi Node class
"""
import json
import logging
import xml.etree.ElementTree as ET
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.custom_exceptions import PostRequired
from jenkinsapi.custom_exceptions import JenkinsAPIException
from six.moves.urllib.parse import quote as urlquote
... |
# -*- coding: utf-8 -*-
"""
Part of the voitools package
Copyright 2015 Board of Regents of the University of Wisconsin System
Licensed under the MIT license; see LICENSE at the root of the package.
Authored by Nate Vack <njvack@wisc.edu> at the Waisman Laboratory for Brain
Imaging and Behavior.
This contains tests f... |
# Generated by Django 3.1.6 on 2021-02-07 22:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('data', '0007_auto_20201028_1405'),
]
operations = [
migrations.AddField(
model_name='resizedredirect',
name='name',
... |
"""Defines a time simulation responsible for executing any registered
producers
"""
import datetime
import time
from enum import IntEnum
import logging
import logging.config
from pathlib import Path
import pandas as pd
# Import logging before models to ensure configuration is picked up
logging.config.fileConfig(f"{Pa... |
from __future__ import print_function
try:
basestring
except NameError:
basestring = str
try:
# noinspection PyShadowingBuiltins
input = raw_input
except NameError:
pass
import getpass
import json
import os
import shutil
import subprocess
import sys
import tempfile
from abc import ABCMeta
from collecti... |
from sqlalchemy import Table, Column, ForeignKey, String, Integer, Float
from sqlalchemy.orm import relationship
from database import Base
boardgame_categories = Table('boardgame_categories', Base.metadata,
Column('id', Integer, nullable=False, primary_key=True),
... |
from sklearn.ensemble import RandomForestClassifier, VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, roc_auc_score
def objective_function( X, y, weights: list) -> list:
"""This is the vector of ob... |
import secrets
class Authenticator:
def __init__(self, api_token: str) -> None:
self.api_token = api_token
def authenticate(self, user_token: str) -> bool:
return secrets.compare_digest(user_token, self.api_token)
|
# Generated by Django 2.2.1 on 2019-06-11 19:13
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('jobs', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='job',
n... |
# -*- coding: utf-8 -*-
# cython: language_level=3
# BSD 3-Clause License
#
# Copyright (c) 2020-2021, Faster Speeding
# 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 sour... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Independent Variables
fail_rate = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, .00001, .00001, .00001, .001, .001, .001, .01, .01, .01, .01, .01, .01, .01, .01, .01]
join_leave_rate = [.0001, .0001, .0001, .0001, .0001, .001, .001, .001, .0... |
#!/usr/bin/env python
# example helloworld.py
import subprocess
import gtk
import pygtk
pygtk.require('2.0')
class TextEntry(gtk.Entry):
def __init__(self, window):
gtk.Entry.__init__(self)
self.keyboard = window.keyboard
self.connect("focus-in-event", self.on_focus_in)
self.co... |
from django.apps import AppConfig
class DjangoTimestampsConfig(AppConfig):
name = 'django_timestamps'
|
#! /usr/bin/env python
# vim: set fileencoding=utf-8
# Python 2 or 3
# TODO: handle encoding/decoding in main()
"""syllable_count_eng_bf.py -- count syllables in English word.
This version uses Bloom filters to fix up counts that the
basic version gets wrong.
"""
## Copyright © 2018 Raymond D. Gardner
## Licensed ... |
"""
Module Info Message
:author: Zilvinas Binisevicius <zilvinas@binis.me>
"""
import json
import domipy
class InfoMessage(domipy.Message):
"""
Generic info message
"""
def __init__(self, moduleType=None, data=None):
domipy.Message.__init__(self)
self._message = ''
self.modul... |
#!/usr/bin/env python
import os
import tempfile
from pathlib import Path
import requests
from telegram import Document, Update
from telegram.ext import CallbackContext, ConversationHandler, Defaults, \
MessageHandler, Updater, CommandHandler, Filters
from depixlib.LoadedImage import *
from depixlib.functions imp... |
# This function returns pointer to LCA of two given
# values n1 and n2
# This function assumes that n1 and n2 are present in
# Binary Tree
def findLCA(root, n1, n2):
# Base Case
if root is None:
return None
# If either n1 or n2 matches with root's key, report
# the presence by returning root ... |
# Lista os procuradores do estado de São Paulo
# Perceba que para extrair as informações, foi necessário antes entender a estrutura ao qual o dado estava armazenada
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('https://sismpconsultapublica.mpsp.mp.br/ConsultarDistribuicao/ObterFilt... |
#!/usr/bin/env python3
"""
This is an example of how the pytradfri-library can be used to pair new
devices.
To run the script, do the following:
$ pip3 install pytradfri
$ Download this file (example_pair.py)
$ python3 example_pair.py <IP>
Where <IP> is the address to your IKEA gateway. The first time
running you wil... |
# MIT License
#
# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# r... |
"""Provides helpers for Z-Wave JS device automations."""
from __future__ import annotations
from typing import cast
import voluptuous as vol
from zwave_js_server.const import ConfigurationValueType
from zwave_js_server.model.node import Node
from zwave_js_server.model.value import ConfigurationValue
from homeassista... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 03 12:12:46 2017
@author: tony.withers@uwo.ca
Functions to calculate H2O molar volume (PSvolume) and fugacity (PSfug)
using the Pitzer and Sterner equation of state.
Pitzer, K.S. and Sterner, S.M., 1994. Equations of state valid
continuously from zero to extreme pressur... |
from typing import Any, Dict
from cyan.event import Event, EventInfo, Intent
from cyan.model.member import Member
class _MemberEvent(Event):
async def _parse_data(self, data: Dict[str, Any]) -> Member:
guild_identifier = data["guild_id"]
guild = await self._bot.get_guild(guild_identifier)
... |
# coding=utf-8
from setuptools import setup, find_packages
from os.path import realpath, dirname
from os import listdir
root_dir = dirname(realpath(__file__))
# data_path = '/countryinfo/data'
data_dir = root_dir+'/countryinfo/data'
# read readme file
with open('README.rst', encoding='utf-8') as f:
long_descripti... |
import gzip
import os
import pickle
from typing import Dict, List
import jsonlines # type: ignore
from csvnpm.binary.dire_types import TypeLib
from csvnpm.binary.function import CollectedFunction, Function
from csvnpm.binary.ida_ast import AST
from csvnpm.ida import ida_lines
from csvnpm.ida import idaapi as ida
from... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse, os, re, subprocess
from collections import defaultdict
script_path = os.path.dirname(os.path.realpath(__file__))
root_dir = os.path.dirname(os.path.dirname(os.path.dirname(script_path)))
projects = ['alfresco-community-repo', 'alfresco-enterprise-repo',... |
from django.urls import path
from label import views
#from label import processing
import os
urlpatterns = [
path('', views.index, name='index'),
path('home/', views.homepage, name='homepage'),
path('user_login/', views.user_login, name='user_login'),
path('development_tracker/', views.development_... |
from django.conf import settings
from django.test import TestCase, override_settings
from recruitment.templatetags.instructorrecruitment import (
is_instructor_recruitment_enabled,
)
class TestInstructorRecruitmentTemplateTags(TestCase):
def test_feature_flag_enabled(self) -> None:
with self.settings... |
import pandas as pd
import numpy as np
from keras.models import Sequential
import tensorflow as tf
import os
from Bio import SeqIO
from keras.preprocessing.text import text_to_word_sequence
from keras.preprocessing.text import one_hot
from keras.preprocessing import sequence
# load and preprocess
# insert here the csv... |
#!/usr/bin/env python
# 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... |
import logging
import autograd.numpy as np
from autograd import grad
from mla.base import BaseEstimator
from mla.metrics.metrics import mean_squared_error, binary_crossentropy
np.random.seed(1000)
class BasicRegression(BaseEstimator):
def __init__(self, lr=0.001, penalty="None", C=0.01, tolerance=0.0001, max_i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: Olivier Noguès
from app import db
import datetime
# -------------------------------------------------------------------------------------------------------------------
# SECTION DEDICATED TO THE DOCUMENTATION
#
class AresDoc(db.Model)... |
"""
timestamp is part of the AndroidGeodata project,
see the project page for more information https://github.com/robiame/AndroidGeodata.
timestamp is a class that collects methods to manage the conversion among the different date formats.
Copyright (C) 2016 Roberto Amelio
This file is part of AndroidGeod... |
"""Abstract collection for UserContent and sub-classes of StaticSection, HiglassViewConfig, etc."""
from uuid import uuid4
from snovault import (
abstract_collection,
calculated_property,
collection,
load_schema
)
from snovault.interfaces import STORAGE
from .base import (
Item,
ALLOW_CURRENT,
... |
from ...frontend.entry import ScatteringEntry
class ScatteringEntry1D(ScatteringEntry):
def __init__(self, *args, **kwargs):
super().__init__(name='1D', class_name='scattering1d', *args, **kwargs)
__all__ = ['ScatteringEntry1D']
|
import pyttsx3 as pyttsx
class speech():
def __init__(self):
self.voice = 0
self.se = pyttsx.init('sapi5')
self.se.setProperty('rate', 200)
self.voices = self.se.getProperty('voices')
def speak(self, text, print_text=True):
if print_text:
print(text)
self.se.say(text)
self.se.runAndWai... |
import json
import hashlib
import pytest
@pytest.mark.skip('datasets')
@pytest.mark.models(
'backends/postgres/report/:dataset/test',
)
def test_push_same_model(model, app):
app.authmodel(model, ['insert'])
data = [
{'_op': 'insert', '_type': model, 'status': 'ok'},
{'_op': 'insert', '_ty... |
"""Contains functionality related to retrieving the content to check against
certain rules.
This module includes content providers, which are classes that know how to
look for information from Github, that is necessary for performing checks.
Ideally this should be abstracted so that it does not depend on Github,
but ... |
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
sys.path.append(os.path.relpath("."))
from tools import parse_json_output, check_results
import warnings
warnings.simplefilter("ignore")
nb_runs = 3
algos = ["ucb_ds2", "ucb_ds", "ucb_d", "ucb"]
algos_names = ["UCB-MS2", "UCB-MS", "UCB-M", "UCB"] ... |
"""GraphQL Schema."""
from ariadne import gql
TYPE_DEFS = gql("""
type Query {
map(name: String!): Map
maps: [Map]
civilization(id: Int!, dataset_id: Int!): Civilization
civilizations(dataset_id: Int!): [Civilization]
stats: Stats
match(id: Int!): Match
search: SearchResult
search_opti... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module to provide abstract Empower socket
"""
import socket
import argparse
import logging
import logging.config
import yaml
import coloredlogs
__author__ = 'Giuseppe Cogoni'
__author__ = 'Brent Maranzano'
__license__ = 'MIT'
class Empower(object):
""" Mock Wate... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.