content stringlengths 5 1.05M |
|---|
def hello_world():
print("Hello World!")
def hallo_welt():
print("Hallo Welt!")
def hola_mundo():
print("Hola Mundo!")
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader as Dataloader
import torchvision
import torchvision.transforms as transforms
import torch.optim as optim # Optimizer used to update weights.
import numpy as np
import matplotlib.pyplot as plt
#Download Dataset
to... |
# Generated by Django 3.0.6 on 2020-05-30 10:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('incident', '0010_auto_20200528_2355'),
]
operations = [
migrations.AddField(
model_name='incident',
name='latitude',... |
from labtex.measurement import Measurement, MeasurementList
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
class LinearRegression:
"Linearly regress two MeasurementLists."
def __init__(self,x : MeasurementList, y : MeasurementList):
self.x = x
self.y = y
assert... |
import numpy as np
import unittest
import os
from openmdao.api import Problem
from openmdao.utils.assert_utils import assert_near_equal, assert_check_partials
from pycycle.constants import AIR_ELEMENTS
from pycycle.mp_cycle import Cycle
from pycycle.thermo.cea.species_data import janaf
from pycycle.elements.compress... |
import discord
from asyncio import sleep
class Fun:
def __init__(self):
self.bot = None
def init(self, bot):
self.bot = bot
async def loop(self, ctx):
'''Infinite Loop'''
await sleep(0.5)
await self.bot.delete_message(ctx.message)
... |
"""
This code comes from https://github.com/rubenvillegas/cvpr2018nkn/blob/master/datasets/fbx2bvh.py
"""
import bpy
import numpy as np
from os import listdir
data_path = './Mixamo/'
directories = sorted([f for f in listdir(data_path) if not f.startswith(".")])
for d in directories:
files = sorted([f for f in li... |
from fastapi import APIRouter, Depends
from ..utils import engine, string_to_datetime, get_session
from sqlmodel import Session, select, SQLModel, or_
from ..utils import engine
from ..models.user import User
from ..models.timelog import TimeLog
router = APIRouter(prefix="/api/timelogs", tags=["timelog"])
@router.po... |
"""
@brief test log(time=1s)
"""
import os
import unittest
from pyquickhelper.loghelper import fLOG, noLOG
from pyquickhelper.pycode import get_temp_folder
from tkinterquickhelper.funcwin.default_functions import test_regular_expression, is_empty_string, IsEmptyString, file_head, file_grep
class TestWindows (uni... |
# -*- coding: utf-8 -*-
from simmate.workflow_engine import s3task_to_workflow
from simmate.calculators.vasp.tasks.relaxation import (
Quality00Relaxation as Quality00RelaxationTask,
)
from simmate.calculators.vasp.database.relaxation import (
Quality00Relaxation as Quality00RelaxationResults,
)
workflow = s3... |
from setuptools import setup
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(
name='term-forecast',
version='0.1.dev0',
author='Kevin Midboe',
author_email='support@kevinmidboe.com',
description='Terminal Forcast is a easily accessible terminal based weather forecaster',
url... |
#!/usr/bin/env python
from nose.tools import assert_equal, assert_true, assert_almost_equal, nottest
from os.path import isdir,isfile
from os import listdir
import os
import sys
import subprocess
import pandas as pd
file_path = os.path.realpath(__file__)
test_dir_path = os.path.dirname(file_path)
data_path = os.path.a... |
from botZap import Validar
validar = Validar(
'numerosUsados.json',
'numerosValidos.json'
)
validar.interface()
validar.gerarNumeros()
validar.apagarCookies()
validar.cookies()
validar.chrome()
validar.conectar()
validar.quit()
validar.iniciarNavegadorInvisivel()
validar.mudo()
validar.cookies()
validar.chromeWaCr... |
#!/usr/bin/env python
# coding: utf-8
from functools import wraps
import numpy as np
def nsample(shape):
def _1(function):
@wraps(function)
def _(*args,**kw):
mat = np.zeros(shape)
if 1==mat.ndim:
vlen = shape
else:
vlen = shape[0... |
""" views
Created at 10/07/20
"""
import logging
from django.utils.translation import ugettext, ugettext_lazy as _
from rest_framework import mixins, generics, status, viewsets, permissions
from rest_framework.response import Response
from email_builder.api.serializers import EmailBuilderTxtSerializer, EmailBuild... |
#!/usr/bin/env python
"""
s3-mix topology
"""
from mininet.cli import CLI
from mininet.net import Mininet
from mininet.topo import Topo
from mininet.node import Node
from mininet.log import setLogLevel, info
from utils import IP, MAC, NETMASK
from utils import IP_SWAT, MAC_SWAT, NETMASK_SWAT
from subprocess import ... |
import abc
import numpy as np
from src.graphic_interface.image_standardizer import ImageAligner, ImageCropper
class DataSet:
"""
Wrapper around both Dataset, which can apply a transformation prior to sending data, or apply
a reverse transformation after receiving data.
"""
def __init__(self, dat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2021 Nigel Small
#
# 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 scipy.stats import mode
import numpy as np
from imblearn.combine import SMOTEENN
from . import AbstractClassifier
class OversampleClassifier(AbstractClassifier):
"""Classifier which uses minority oversampling to balance minority class"""
def __init__(self, classifier, **kwargs):
super(Oversampl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/4/25 11:47
# @Author : Darren
# @Site :
# @File : config.py
# @Software: PyCharm
real_image_path = './data/train_images/'
fake_tps_image_path = './data/fake_images/tps_file/'
fake_transform_image_path = './data/fake_images/transform_fi... |
minha_idade = 32
print('Eu tenho',minha_idade, 'anos')
taxaUSD = 3.20
arroz = 17.30
feijao = 8.99
#Descubra os valores em USD
arrozUSA = arroz * taxaUSD
print(round(arrozUSA))
|
"""Top-level package for damitalia."""
__author__ = """Manuel Capel"""
__email__ = 'manuel.capel82@gmail.com'
__version__ = '0.1.0'
|
s = [2,4,3,1]
s.sort()
print(s)
s.reverse()
print(s)
s = ['1', '2', '12']
print(s)
s.sort()
print(s)
s.sort(key=lambda x:int(x))
print(s)
s.sort(reverse=True)
print(s)
s.sort(key=lambda x:int(x), reverse=True)
print(s)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-09 20:13
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('golf', '0018_auto_20170809_1155'),
]
... |
name = "proc"
import QNLP.proc.basis_check
import QNLP.proc.load_basis
import QNLP.proc.process_corpus
import QNLP.proc.DisCoCat
import QNLP.proc.VectorSpaceModel
import QNLP.proc.VerbGraph
import QNLP.proc.HammingDistance
__all__ = ["basis_check", "load_basis", "process_corpus", "DisCoCat", "VectorSpaceModel", "VerbG... |
import os
from tqdm import tqdm
import warnings
from multiprocessing import Queue, Process
from artm.wrapper.exceptions import ArtmException
from .strategy import BaseStrategy
from ..models.base_model import padd_model_name
from ..routine import get_timestamp_in_str_format
NUM_MODELS_ERROR = "Failed to retrive number... |
import multiprocessing
import os
import string
import dask
import numpy as np
import pytest
import xarray as xr
import xpartition
@pytest.mark.parametrize(
("block_indexers", "expected", "exception"),
[
({"x": slice(0, 3)}, {"x": slice(0, 6)}, None),
({"x": slice(1, 2)}, {"x": slice(2, 5)}, ... |
# -*- coding: utf-8 -*-
from blinker import Namespace
_namespace = Namespace()
add_blueprints = _namespace.signal("add-blueprints")
add_extensions = _namespace.signal("add-extensions")
|
#Julie Chang and Chris Metzler 2020
import abc
import tensorflow as tf
import numpy as np
from numpy.fft import ifftshift
import fractions
import poppy
##############################
# Helper functions
##############################
def get_zernike_volume(resolution, n_terms, scale_factor=1e-6):
zernike_volume ... |
from django.apps import AppConfig
class ClsConfig(AppConfig):
name = 'cls'
|
from traceback import format_exc
import cv2
from pathlib import Path
from PIL import Image
import numpy as np
def ImageToMatrix(file):
im = Image.open(file)
width, height = im.size
im = im.convert("L")
data = im.getdata()
data = np.matrix(data, dtype='float') / 255.0
new_data = np.reshape(da... |
# print('\n'.join(is_not_a_pkg_name('^.+py.+$')))
# print(is_not_a_pkg_name('.*py$'))
from pipoke.pkg_vs_words import *
def is_from_module(obj, module):
"""Check if an object "belongs" to a module.
>>> import collections
>>> is_from_module(collections.ChainMap, collections)
True
>>> is_from_modu... |
from apps.lean.filters.basicinfor_filters import *
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# ./create_JSON_file_of_sections_in_your_courses.py
#
# with the option "-v" or "--verbose" you get lots of output - showing in detail the operations of the program
#
# Can also be called with an alternative configuration file:
# ./create_JSON_file_of_sections_in_your_course... |
from qfengine.asset.equity import Equity
from qfengine.asset.cash import Cash
from typing import Union
assetClasses = Union[Equity,Cash] |
# Copyright 2014 Julia Eskew
# 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, sof... |
class HelloWorld(object):
def __init__(self):
self.hello_world = 'HelloWorld'
def gen_hello_world_msg(self, name: str):
return self.hello_world + ' ' + name
|
from ..core import Field, CapacityType, MillisecondsDatetimeType
from ..core.api.special_values import Autogenerate
from ..core.translators_and_types import MunchListType
from .system_object import InfiniBoxObject
from ..core.bindings import RelatedObjectNamedBinding, RelatedObjectBinding
class _Field(Field):
def... |
import os, sys
from errno import *
from stat import *
import fcntl
try:
import _find_fuse_parts
except ImportError:
pass
import fuse
from fuse import Fuse
from deeputil import Dummy
DUMMY_LOG = Dummy()
if not hasattr(fuse, '__version__'):
raise RuntimeError("your fuse-py doesn't know of fuse.__version__... |
import numpy as np
from vg.compat import v2 as vg
def indices_of_original_elements_after_applying_mask(mask):
"""
Given a mask that represents which of the original elements should be kept,
produce an array containing the new indices of the original elements. Returns
-1 as the index of the removed ele... |
import pandas as pd
from pandas.io import gbq
import logging
_LOGGER = logging.getLogger(__name__)
def test_vasopressor_units(dataset, project_id):
# verify vasopressors in expected units
units = {
'milrinone': 'mcg/kg/min',
'dobutamine': 'mcg/kg/min',
'dopamine': 'mcg/kg/min',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import requests_cache
from pydeflate import config
# Create session
expire_after = datetime.timedelta(days=3)
wb_session = requests_cache.CachedSession(
cache_name=config.paths.data + r"/wb_cache",
backend="sqlite",
expire_after=expire_aft... |
import logging
from typing import Optional
import shared.infrastructure.environment.globalvars as glob
from shared.domain.service.logging.logger import Logger
class FileLogger(Logger):
def __init__(self, name: Optional[str] = None, logfile: Optional[str] = None):
settings = glob.settings
if not ... |
import sys
from os import getgid, getuid
from pathlib import Path
from pwd import getpwuid
from click import INT
from typer import confirm, prompt
from kolombo.console import debug, enable_debug, finished, info, started, step
from kolombo.util import run
_virtual_configs = {
"addresses": "bob@example.com bob@exa... |
'''
codeml2tsv.py - analyze results from codeml kaks run
=============================================================
:Author: Andreas Heger
:Release: $Id$
:Date: |today|
:Tags: Python
Purpose
-------
Usage
-----
Example::
python codeml2tsv.py --help
Type::
python codeml2tsv.py --help
for command line h... |
from .franchise import Franchise
from .player import Player
from .season import Season
from .league import League
from .friv import Frivolities |
import pytest
from kopf import ActivityRegistry
from kopf import OperatorRegistry
from kopf import ResourceWatchingRegistry, ResourceChangingRegistry
from kopf import SimpleRegistry, GlobalRegistry # deprecated, but tested
from kopf.structs.handlers import HandlerId, ResourceChangingHandler
@pytest.fixture(params=[... |
from django.shortcuts import render,redirect
from django.contrib.auth.hashers import make_password,check_password
# Create your views here.
from user.forms import RegisterForm
from user.models import User
def register(request):
if request.method == "POST":
form = RegisterForm(request.POST,request.FILES)
... |
import logging
from django.http import (HttpResponseBadRequest, HttpResponseForbidden,
HttpResponseRedirect)
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.views.generic import CreateView, DeleteView, UpdateView
from rdmo.accounts.utils import is_si... |
import frappe
import logging
import logging.config
import os
import json
from pprint import pformat
class ContextFilter(logging.Filter):
"""
This is a filter which injects request information (if available) into the log.
"""
def filter(self, record):
record.form_dict = pformat(getattr(frappe.local, 'form_dict',... |
#
# @lc app=leetcode id=478 lang=python3
#
# [478] Generate Random Point in a Circle
#
# @lc code=start
import random
class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
self.x = x_center
self.y = y_center
self.r = radius
def randPoint(self) -> List[flo... |
import unittest
from linty_fresh.linters import android
from linty_fresh.problem import Problem
test_string = """\
<?xml version="1.0" encoding="UTF-8"?>
<issues format="4" by="lint 25.1.6">
<issue
id="ScrollViewSize"
severity="Error"
message="This LinearLayout should use `android:layout_... |
import os
import random
import numpy as np
import pandas as pd
from matplotlib import image
import skimage.color
from skimage.exposure import cumulative_distribution
from copy import deepcopy
from debiasmedimg.cyclegan.util import get_sample_from_path, get_filenames, normalize_for_evaluation, \
ssim_score, ... |
""" Basic cross-platform utility that launches HTTP server from the current directory.
Useful when sending static web apps/prototypes to non-technical people.
v1 """
import webbrowser, random, sys, os, re
from http.server import SimpleHTTPRequestHandler, HTTPServer
PORT = URL = httpd = None
# Get the path to... |
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from rapidsms.log.mixin import LoggerMixin
class BaseHandler(object, LoggerMixin):
def _logger_name(self):
app_label = self.__module__.split(".")[-3]
return "app/%s/%s" % (app_label, self.__class__.__name__)
@classmethod
def dispatch(cl... |
from flask import request, render_template, jsonify
from flask import Flask
from flask_cors import CORS
import numpy as np
import cv2
from custom_inference import run
import json
from utils.box_computations import corners_to_wh
import time
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
inferer =... |
import os
import platform
import pandas as pd
import pickle
import dill
def loadPickledData(filePath, default=["default"]):
"""
load an existing pickle file or make a pickle with default data
then return the pickled data
Parameters:
- filePath: the absolute path or the relative path
- default:... |
# --------------------------------------------------------
# This file is used to test all the algorithms performed
# on the graph's
# --------------------------------------------------------
from Graph import *
from colorama import Fore, Style
print("Depth First Search")
print(Fore.BLUE)
print("-------------------... |
from rest_framework.response import Response
from assessment.middlewares.validators.errors import raises_error
from re import sub
from assessment.middlewares.validators.constants import database_types, related_mapper
class QueryParser():
valid_include = ['children']
excluded_fields = ['score', 'questions', 'a... |
# Copyright 2019 Akiomi Kamakura
#
# 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 writi... |
"""A collection of models which outline the scope and options of a particular project.
"""
import abc
from typing import TYPE_CHECKING, List, Optional, Union
import requests
from pydantic import Field, conlist, root_validator, validator
from typing_extensions import Literal
from nonbonded.library.config import settin... |
from django.apps import AppConfig
class PetfinderConfig(AppConfig):
name = 'petfinder'
|
from collections import defaultdict
from itertools import product
from multiprocessing import Pool
def count_neighbors_3(cube, x, y, z):
count = 0
for dx, dy, dz in product(range(-1, 2), repeat=3):
if dx == 0 and dy == 0 and dz == 0:
continue
count += cube[x+dx,y+dy,z+dz]
return... |
import torch.nn as nn
import scipy.ndimage
import torch
import numpy as np
class GaussianFilter(nn.Module):
def __init__(self, channels, kernel_size, sigma, peak_to_one = False):
super().__init__()
padding = int(kernel_size/2)
self.pad = nn.ZeroPad2d(padding)
kernel = se... |
#This file contains the configuration variables for your app, such as database details.
import os
|
#/mpcfit/mpcfit/transformations.py
"""
--------------------------------------------------------------
Oct 2018
Payne
Functions for transformation between coordinate frames
To include covariance transformation capabilities
See Bernstein's orbit/transforms.c code for comparison
See B&K (2000) and/or Fa... |
# -*- coding: utf-8 -*-
# Copyright 2016-2018, Alexis de Lattre <alexis.delattre@akretion.com>
# 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 code must retain the... |
from brownie import network, config, accounts, MockV3Aggregator
from web3 import Web3
FORKED_LOCAL_ENVIRONMENT = ["mainnet-fork", "mainnet-fork-dev"]
LOCAL_BLOCKCHAIN_ENVIRONMENTS = ["development", "ganache-local"]
DECIMALS = 8
STARTING_PRICE = 200000000000
def get_account():
if network.show_active() in LOCAL_BL... |
from setuptools import find_packages, setup
with open("README.md", encoding="utf-8", mode="r") as file:
long_desc = file.read()
setup(
name='perspective.py',
packages=find_packages(include=['perspective']),
version='0.3.4',
description='An easy-to-use API wrapper for Perspective API written in Pyth... |
import numpy as np
import matplotlib.pyplot as plt
import sounddevice
from scipy.io import wavfile as wav
fs, wave = wav.read('piano1.wav')
#fs is sampling frequency
# fs = 20000
length = wave.shape[0] / fs
time = np.linspace(0,length,int(length*fs),endpoint=False)
# freq_signal = 1000
#wave is the sum of sine wave(... |
from ToonHood import ToonHood
from panda3d.core import *
from direct.directnotify.DirectNotifyGlobal import directNotify
from toontown.toonbase import ToontownGlobals
from toontown.safezone.TFSafeZoneLoader import TFSafeZoneLoader
from toontown.town.TFTownLoader import TFTownLoader
import SkyUtil
from direct.interval.I... |
#!/usr/bin/env python
"""
Util script to handle instance creation over Nova using HTTP APIs for
Nova Agent CI tasks.
"""
__author__ = "Shivaling Sannalli, abhishekkr"
import urllib2
import json
import time
import ConfigParser
import logging
import os
def _http_requests_json(url, headers={}, body=None):
""" Gen... |
from abc import ABCMeta, abstractmethod
from typing import Sequence
from misc.base_types import Controller
from environments.abstract_environments import GroundTruthSupportEnv
from .abstract_models import ForwardModelWithDefaults
from environments import env_from_string
import numpy as np
from misc.rolloutbuffer impor... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import sys
import random
import re
import unicodedata
import codecs
import math
import itertools
from io import open
import torch
import torchvision
# import ma... |
"""
Code for recording and logging stack traces of training scripts to help determine
how Python interfaces with native C libraries.
This code was useful for determining how Python calls into PyTorch; PyTorch
has multiple native shared libraries it calls into.
"""
import textwrap
import traceback
import contextlib
fro... |
from telegram import ReplyKeyboardMarkup, InlineKeyboardButton, InlineKeyboardMarkup
import os
def hr_keyboard():
return ReplyKeyboardMarkup(
[
['Просмотр резюме', 'Просмотр пользователей'],
['Создать ключ кандидата и сотрудника'],
['Вернуться в главное меню']
])... |
import os, sys
import gc
import pandas as pd
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
from sklearn.model_selection import KFold, cross_val_score, GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.linear_model import SGDClassifier, SGDRegressor
from sklearn.preprocessing import ... |
#!/usr/bin/env python3
import json
import time
import subprocess
import telegram_send
MAC_MONITORING_PATH = '/etc/hostapd/mac-monitoring.json'
STA = 'wlan0'
def get_connections(sta, monitoring):
""" Returns MACs is sta that are being monitored """
list_sta = subprocess.check_output(
["sudo", "hostap... |
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
res = [-1] * len(nums)
s = []
n = len(nums)
for i in range(2 * len(nums) - 1, -1, -1):
while len(s) != 0 and s[-1] <= nums[i % n]:
s.pop()
res[i % n] = -1 if ... |
from imread_from_url.imread_from_url import *
__version__ = "0.1.0" |
#
# Copyright 2020 The FLEX Authors. 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 appli... |
ix.enable_command_history()
ix.application.select_next_inputs(False)
ix.disable_command_history() |
from datetime import datetime, date, time
from typing import List
from uuid import uuid4
from PIL.Image import Image
from qrcode import QRCode
from qrcode.constants import ERROR_CORRECT_H
from rawa.commands.exceptions import CommandError
from rawa.models import db, Station, Token, UsedToken, User
def find_token(tok... |
"""
Tests for Admin Template Tags
"""
from django.contrib.auth.models import User
from django.template import Template, Context
from django.test import TestCase, override_settings
class TemplateTagAdminTestCase(TestCase):
"""
Test Template Tags
"""
# |-------------------------------------------------... |
# Problem description: Convert a number into a linked list of its digits.
# Solution time complexity: O(n)
# Comments: Notice that we prepend each subsequent digit node to the destination list's head.
# Otherwise the result will be in reverse, i.e. f(123) => 3->2->1.
#
im... |
import tempfile
import nox
nox.options.sessions = "lint", "tests"
locations = "microservice_demo", "tests", "noxfile.py"
def install_with_constraints(session, *args, **kwargs):
with tempfile.NamedTemporaryFile() as requirements:
session.run(
"poetry",
"export",
"--d... |
import matplotlib.pyplot as plt
from pydicom import dcmread
import pandas as pd
import numpy as np
import os
import csv
remove_tags = [
'PatientBirthDate',
'PatientID',
'PatientName',
'PatientSex', ]
save_info = {
# 'ImplementationVersionName': [0x0002,0x0013], #'OFFIS_DCMTK_360'
'ImageType... |
"""
Author: David O'Callaghan
"""
import numpy as np
import solver_utils
def solve(grid_in):
"""
This function contains the hand-coded solution for the data in
2dc579da.json of the Abstraction and Reasoning Corpus (ARC)
Transformation Description: The center row and center column of the input
g... |
#! /usr/bin/env python
"""
This script can be used to produce a standalone executable from
arbitrary Python code. You supply the name of the starting Python
file to import, and this script attempts to generate an executable
that will produce the same results as "python startfile.py".
This script is actually a wrapp... |
# TestSwiftRangeTypes.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONT... |
"""
Run this example to check if the GEKKO optimization package has been installed correctly
"""
from gekko import GEKKO
m = GEKKO(remote=False) # Initialize gekko
m.options.SOLVER = 1 # APOPT is an MINLP solver
# optional solver settings with APOPT
m.solver_options = ['minlp_maximum_iterations 500',
... |
import random
import pygame.draw as draw
import math
from pygame.sprite import Sprite
settings = None
screen = None
stats = None
def set_global_var(setts, scr, statistics):
global settings
global screen
global stats
settings = setts
screen = scr
stats = statistics
Ball.settings = setts
... |
#from asyncio.windows_events import NULL
from PIL import Image, ImageDraw, ImageFilter, ImageFont
import os
import glob
frame ={
"width": 150,
"height": 150,
"crops": True,
}
icon = {
"jpg":{ "isImage": True},
"gif":{ "isImage": True},
"png":{ "isImage": True},
"zip":{
"isImage": F... |
from matplotlib import rc
rc('text', usetex=True) # this is if you want to use latex to print text. If you do you can create strings that go on labels or titles like this for example (with an r in front): r"$n=$ " + str(int(n))
from numpy import *
from pylab import *
import random
from matplotlib.font_manager import Fo... |
import unittest
from lib import constants
class TestCaseForTestnet(unittest.TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
constants.set_testnet()
@classmethod
def tearDownClass(cls):
super().tearDownClass()
constants.set_mainnet()
|
import os
from fnmatch import fnmatch
def find_files(pattern: str, root: str):
paths = []
for path, subdirs, files in os.walk(root):
del subdirs
for name in files:
if fnmatch(name, pattern):
paths.append(os.path.join(path, name))
return paths
|
# Copyright (c) Yugabyte, 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, soft... |
"""
Objects emitted whilst a deprecated object is being used.
"""
import attr
def _qualname(obj):
"""
Return the (non-fully-)qualified name of the given object.
"""
return obj.__qualname__
@attr.s(eq=True, frozen=True, hash=True)
class Deprecation(object):
"""
A single emitted deprecation.
... |
# https://scikit-learn.org/stable/modules/feature_selection.html#
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_classif
from sklearn.feature_selection import f_regression
from sklearn.feature_selection import mutual_info_regression
import warnings
warnings.filterwarnings('ig... |
"""Helper module for handling network related commands."""
import os
import requests
from phytoolkit.exception.installationexception import InstallationException
class NetHelper:
"""Runs network commands."""
def __init__(self, config):
self.config = config
self.console = config.console
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.