content stringlengths 5 1.05M |
|---|
import sys, os
#--------------------------------------------------------------------------------------------------
if len(sys.argv) != 2:
raise Exception('Usage: python ./mob_uploader.py input_path')
if not os.path.exists(sys.argv[1]):
raise Exception('Path does not exist: ' + sys.argv[1])
if not os.path.exists... |
import numpy as np
import pandas as pd
import torch
import torchvision
import torch.nn.functional as F
from torchvision import datasets,transforms,models
import matplotlib.pyplot as plt
#from train import get_pretrained_model
from torch import nn,optim
from PIL import Image
#%matplotlib inline
def load_dataset(data_di... |
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython
"""
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
def load_data(min: int = 0, max: int = 10, size: int = 20) -> np.ndarray:
return np.random.randint(min, max, size=size)
def statistics(ser: pd.Series) -> None:
for _ ... |
__copyright__ = "Copyright (C) 2019 Zachary J Weiner"
__license__ = """
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 rights
to use, c... |
"""
vmagnify.py : abstract class for the processing of the data.
"""
class VMagnify:
""" VMagnify is an abstract class for the processing of the data """
EDSR_MODEL_X2_PATH = "static/models/EDSR/EDSR_x2.pb"
EDSR_MODEL_X3_PATH = "static/models/EDSR/EDSR_x3.pb"
EDSR_MODEL_X4_PATH = "static/models/EDSR/E... |
"""
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
import glob
import os
import subprocess as sp
import sys
from pathlib import Path
from typing import List # @UnusedImport
import pytest
from pde.tools.misc import module_available
PACKAGE_PATH = Path(__file__).resolve().parents[2]
EXAMPLES = glob.glob... |
import pytest
from traitlets.tests.utils import check_help_all_output
from jupyter_server.utils import url_escape, url_unescape
def test_help_output():
check_help_all_output('jupyter_server')
@pytest.mark.parametrize(
'unescaped,escaped',
[
(
'/this is a test/for spaces/',
... |
import re
with open('input.txt', 'r') as fh:
lines = [l.strip() for l in fh.readlines()]
vowels = 'aeiou'
bad = ['ab', 'cd', 'pq', 'xy']
def nice(word):
vowel_count = sum(word.count(v) for v in vowels) >= 3
double = re.match('.*(([a-z])\\2{1}).*', word) is not None
no_bads = not any(b in word for b... |
import komand
from .schema import FindIssuesInput, FindIssuesOutput, Input, Output, Component
# Custom imports below
from ...util import *
class FindIssues(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name='find_issues',
description=Component.DESCRIPTI... |
#!/usr/bin/env python3
import numpy as np
import random
import os
from scipy.io import loadmat
from PIL import Image
from collections import defaultdict
from sklearn.model_selection import train_test_split
import cv2
from sklearn.utils import shuffle
import imgaug.augmenters as iaa
from few_shot.constants import DATA_... |
import tensorflow as tf
from keras.callbacks import LearningRateScheduler
from callbacks import *
from help_functions import *
from plots import *
from networks import *
from dataset_preparation import get_dataset
def train_model(model, X_train, y_train, X_test, y_test, num_of_epochs, nn_cnn, batch_size=32, validatio... |
# encoding: utf8
from test_base import DisplaySDKTest
from utils import *
SLEEP_INTERVAL = 2
class MRAIDTest(DisplaySDKTest):
def test_mraid_single_expand(self):
self.driver.orientation = 'PORTRAIT'
set_channel_id(self, "24338")
click_load_ad_btn(self, "BANNER")
accept_locati... |
#Q1: WAP to check if the entered character is a vowel or a consonant
def Ques1():
ch = raw_input("Enter a letter: ");
if (ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u' or ch=='A' or ch=='E' or ch=='I' or ch=='O' or ch=='U'):
print ch,"is a vowel";
else:
print ch,"is a consonant";
#Q2:... |
#
# from shell import main as run |
import math
import sys
def hours_to_min_sec(time, milliseconds=False, txt=False):
hours = math.floor(time)
minutes = (time - hours) * 60
seconds = (minutes % 1) * 60
data = {
"hours": int(hours),
"minutes": int(math.floor(minutes)),
"seconds": int(math.floor(seconds))
}
... |
import requests
import urllib3
import json
from global_secrets import api_get_url,api_default_group
#Disable warning if not using certificate:
verify=False
if verify !=True :
urllib3.disable_warnings()
def _url(path):
url=api_get_url()
return url + path
#Operations on authorization
#Authenticat... |
import os
from modulefinder import Module
from pathlib import Path
from typing import Iterable
import fiona
import geopandas as gpd
import pyproj
import rasterio
from fiona.errors import DriverError
from rasterio.errors import RasterioIOError
from shapely.geometry import Polygon, box
from arcpy2foss.utils import repr... |
# -*- coding: utf-8 -*-
import json
from oauthlib.oauth2 import RequestValidator
from oauthlib.oauth2.rfc6749 import errors, utils
from oauthlib.oauth2.rfc6749.grant_types.base import GrantTypeBase
import logging
log = logging.getLogger(__name__)
JWT_BEARER = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
class JWT... |
{
"targets": [
{
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")",
"lib/emokit-c/include",
"/usr/local/include"
],
"dependencies": [
"<!(node -p \"require('node-addon-api').gyp\")"
],
"target_name": "emotiv",
"sources": [
... |
import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import count
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: mnmcount <file>", file=sys.stderr)
sys.exit(-1)
spark = (SparkSession
.builder
.appName("PythonMnMCount")
.getOrCreate())
mnm_file =... |
from django.contrib import admin
from leaflet.admin import LeafletGeoAdmin
from pothole.models import Pothole, PotholeRepair
# Register your models here.
admin.site.register(Pothole, LeafletGeoAdmin)
admin.site.register(PotholeRepair) |
from typing import TypeVar, Generic, Callable, Type, cast
from PySide2.QtCore import Signal
_T = TypeVar('_T')
class SimpleSignal:
def __init__(self):
pass
def emit(self):
pass
def connect(self, c: Callable[[], None]):
pass
class TypedSignal(Generic[_T]):
def __init__(sel... |
import sys
# Models
from lokki.model import AdaBoost
from lokki.model import GradientBoosting
from lokki.model import RandomForest
from lokki.model import LogisticRegressionModel
from lokki.model import RidgeClassifierModel
from lokki.model import SVM
from lokki.model import DecisionTree
from lokki.model import Ext... |
# coding: utf-8
# Copyright (c) Henniggroup.
# Distributed under the terms of the MIT License.
from __future__ import division, print_function, unicode_literals, \
absolute_import
"""
This script demonstrates the usage of the module
mpinterfaces/calibrate.py to setup and run vasp jobs
"""
import os
from math imp... |
from pathlib import Path
from time import sleep
from kubernetes import client, config
from kubernetes.client.rest import ApiException
from kubernetes.config.config_exception import ConfigException
from retrying import retry
SIG_DIR = '.openmpi-controller'
SIG_TERM = f'{SIG_DIR}/term.sig'
POLL_STATUS_INTERVAL = 10
TER... |
import os
import time
import shutil
import logging
import subprocess
import torch
def init_dist(args):
args.distributed = False
if 'WORLD_SIZE' in os.environ:
args.distributed = int(os.environ['WORLD_SIZE']) > 1
if args.slurm:
args.distributed = True
if not args.distributed:
# ... |
import os
import sys
import BaseHTTPServer
import threading
sys.path.append(os.path.join(os.path.dirname(
__file__), '../../../libbeat/tests/system'))
from beat.beat import TestCase
class BaseTest(TestCase):
@classmethod
def setUpClass(self):
self.beat_name = "heartbeat"
self.beat_path ... |
import os
import json
import re
import os.path as op
from pathlib import Path
from itertools import product
from collections import defaultdict
from types import SimpleNamespace
from typing import Callable, Dict, List
# --------------------------------------------------------------------------
# Map the function to ... |
"""Author Md Abed Rahman: mdabed@cs.ualberta.ca"""
"""This method iteratively prunes outliers using
both LOF and LSCP based outlier detection methods improve HDBSCAN’s performance"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.neighbors import LocalOutlierFactor
from sklea... |
import spacy
import torch
from pathlib import Path
from utils import read_multinli
from torch.autograd import Variable
from decomposable_attention import build_model
from spacy_hook import get_embeddings, get_word_ids
DATA_PATH = '../data/sample.jsonl'
def main():
sample_path = Path.cwd() / DATA_PATH
sam... |
#-- In python, if you define a function and then define a global variable it is visible to the function unless
# you do some hackaround. The following example gives you an idea of what this code is all about.
# link to the original answer: https://stackoverflow.com/questions/31023060/disable-global-variable-lookup-in-... |
#!/usr/bin/env python
# Copyright 2015 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... |
import os, zbarlight, sys
from PIL import Image
from datetime import datetime
def scan():
qr_count = len(os.listdir('resources/qr_codes'))
qr_countup = qr_count
print('Taking picture..')
try:
scan = True
for i in range(0,3):
os.system('sudo fswebcam -d /dev/video0 -r 800... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2022 Hibikino-Musashi@Home
# 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 above c... |
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
nums = list(set(nums))
if len(nums) < 3:
return max(nums)
from heapq import heappush, heappop
heap ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ ... |
#!/usr/bin/env python2.6
# Copyright 2011 Google 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... |
# Copyright Amazon.com, Inc. or its affiliates. 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
#
# Unl... |
from flask import Blueprint
from app.api.v1 import index
def create_blueprint_v1():
bp_v1 = Blueprint('v1', __name__)
index.api.register(bp_v1)
return bp_v1
|
import torch.nn as nn
import torch.nn.init as init
class MLP(nn.Module):
def __init__(self, input_dim, num_hidden_layers, hidden_dim, dropout=0.5, activation_fn=nn.ReLU):
super(MLP, self).__init__()
self.num_hidden_layers = num_hidden_layers
self.input_to_hidden = nn.Sequential(
nn.Dropout(p=dropout),
n... |
import tkinter
from pytube import YouTube
root = tkinter.Tk()
root.geometry('500x300')
root.resizable(0,0)
root.title("Youtube Video Downloader")
link = tkinter.StringVar()
tkinter.Label(root, text ='Paste Link Here:', font ='arial 15 bold').place(x= 160, y = 60)
link_enter = tkinter.Entry(root, width = 7... |
"""
Deploy Artifacts to Anaconda and Quay
"""
import os
import subprocess as sp
import logging
from . import utils
logger = logging.getLogger(__name__)
def anaconda_upload(package: str, token: str = None, label: str = None) -> bool:
"""
Upload a package to anaconda.
Args:
package: Filename to buil... |
import os, py
from rpython.memory.gc import env
from rpython.rlib.rarithmetic import r_uint
from rpython.tool.udir import udir
class FakeEnviron:
def __init__(self, value):
self._value = value
def get(self, varname):
assert varname == 'FOOBAR'
return self._value
def check_equal(x, y):... |
'''
@uthor: saleem
Minimal Scheduler for running functions at set interval.
'''
import time
class scheduler:
def __init__(self, h=0, m=0, s=0):
self.h = h
self.m = m
self.s = s
def runit(self, fn, *args):
time_step = self.h*3600 + self.m*60 + self.s
while True:
... |
# try-finally support
import sys
# Basic finally support:
print "basic_finally"
def basic_finally(n):
try:
1/n
print "1"
except:
print "2"
else:
print "3"
finally:
print "4"
print "5"
print basic_finally(1)
print basic_finally(0)
print
# If we return from i... |
xh = input("Enter Hours: ")
xr = input("Enter Rate: ")
xp = float(xh) * float(xr)
print("Pay: ") |
from polyphony import pure
from polyphony import testbench
@pure
def rand(seed, x, y):
import random
random.seed(seed)
return random.randint(x, y)
@testbench
def test():
assert rand(0, 1, 1000) == rand(0, 1, 1000)
assert rand(0, -1000, 1000) == rand(0, -1000, 1000)
test()
|
from django.contrib import admin
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from basic import viewsets
from drf_triad_permissions.views import triad_permissions_js
router = DefaultRouter()
router.register("users", viewsets.UserViewSet)
router.register(r"entities-by-user/... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2015, René Moser <mail@renemoser.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
import asyncio
from typing import Optional
from tests import APITestCase, MAINNET_WS_URI, WEBSOCKET_TIMEOUT_GET_REQUEST
from tradehub.websocket_client import DemexWebsocket
class TestWSGetRecentTrades(APITestCase):
def test_get_recent_trades_structure(self):
"""
Check if response match expected ... |
from datetime import datetime, date
import os
import re
import subprocess
import yaml
from boto.s3.connection import S3Connection
bucket_name = 'canvas_public_ugc'
results_bucket_name = 'canvas-ugc-backup-logging'
bucket_path = 'original'
base_dest = '/Volumes/Backup/ugc-backups'
prefix_dir_length = 3
use_date_direct... |
from django.contrib import admin
from django.utils.translation import ugettext
from django.utils.encoding import force_unicode
from models import LogEntry, LogAggregate
from djangologdb import settings as djangologdb_settings
class LogEntryInline(admin.TabularInline):
model = LogEntry
class LogAggregat... |
# compute_rnaQuast.py
#
# Laura Tung
#
# Usage: compute_rnaQuast.py <result_dir>
#
# <result_dir> is the directory containing rnaQUAST_output and rnaQUAST_output_1
import sys
import numpy as np
def load_data(dataset):
loaded_isoform = np.loadtxt(dataset+"/isoform_data", dtype='int', usecols=(2, 3, 4))
loa... |
import csv
import os
import random
import tempfile
from itertools import groupby
from operator import itemgetter
from django.conf import settings
from django_rq import job
from datetime import datetime
from terra.utils import gsutilCopy
from estimators.models import Annotation, Estimator, ImageTile
from tasks.models ... |
import unittest
from intuitquickbooks.helpers import qb_date_format, qb_datetime_format, qb_datetime_utc_offset_format
from datetime import datetime, date
class HelpersTests(unittest.TestCase):
def test_qb_date_format(self):
result = qb_date_format(date(2016, 7, 22))
self.assertEquals(result, '20... |
import re
import json
import math
import time
import random
import pandas as pd
import bs4
import requests
from tqdm.notebook import tqdm
from .formatting.text_tools import title_to_snake_case
from .pandas.data import dict_to_col
pd.set_option('mode.chained_assignment', None)
# Objects included in this file:
# grade... |
from django.http import HttpResponse
import datetime
def hello(request):
return HttpResponse("Hello World")
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
def hours_ahead(request,offset):
try:
# offset = int(offset)... |
# pylint: disable=missing-docstring,no-self-use
import re
import pytest
from context import esperanto_analyzer
from esperanto_analyzer.speech import Preposition
from esperanto_analyzer.analyzers.morphological import PrepositionMorphologicalAnalyzer
class TestPrepositionMorphologicalAnalyzerBasic():
TEST_WORD = ... |
class PC:
def __init__(self, Name, Combat_Class, Race, Eye_Color, Skin_Tone, Hair_Color, Size, Weight, Trademarks, STR, DEX, CON, INT, WIS, CHA, Muscle, Wrestle, Brawl, Coordination, Finesse, Sleight_of_Hand, Stealth, Endurance, Concentration, Vitality, Academic, Arcana, Culture, Analyze, Nature, Aggressive, Suav... |
from collections import defaultdict
import os
with open(os.path.join(os.path.dirname(__file__), "input.txt"), "r") as file:
report_lines = [l.strip() for l in file.readlines()]
def count_occurances(report_numbers):
counts = defaultdict(lambda: {"0": 0, "1": 0})
for line in report_numbers:
for id... |
from azure_storage.methods import client_prep, delete_container, delete_file, delete_folder, extract_account_name
from azure_storage.azure_delete import AzureDelete, cli, container_delete, file_delete, \
folder_delete
from unittest.mock import patch
import argparse
import pytest
import azure
import os
@... |
from django.core.management.base import BaseCommand, CommandError
from extractor.models import DocumentationUnit, MappingUnitToUser
import random
from django.contrib.auth.models import User
"""
map each unit to 2 different users
"""
class Command(BaseCommand):
help = 'maps a sample to the 7 students with their id... |
# -*- coding: utf-8 -*-
import argparse
import multiprocessing
from tox import hookimpl
@hookimpl
def tox_addoption(parser):
def positive_integer(value):
ivalue = int(value)
if ivalue <= 0:
raise argparse.ArgumentTypeError(
"%s is an invalid positive int value" % valu... |
import pyaudio
p = pyaudio.PyAudio()
def getValidDevicesList():
output = []
for i in range(p.get_device_count()):
currentDevice = p.get_device_info_by_index(i)
isInput = currentDevice["maxInputChannels"] > 0
isWASAPI = (p.get_host_api_info_by_index(
currentDevice["hostApi"... |
import socket
import os
from six.moves import urllib
import netifaces
def guess_external_ip():
gateways = netifaces.gateways()
try:
ifnet = gateways['default'][netifaces.AF_INET][1]
return netifaces.ifaddresses(ifnet)[netifaces.AF_INET][0]['addr']
except (KeyError, IndexError):
re... |
[print('\n'.join(" "*abs(c)+"* "*(a-abs(c))for c in range(-a+1,a)))for a in[int(__import__('sys').argv[1])]]
|
import argparse
import os
from PIL import Image
import numpy as np
def read_grayscale(input_file, width):
"""
Reads the raw bytes from the input_file and returns a 2d numpy array of np.int8 pixel values.
"""
with open(input_file, 'rb') as file:
raw_bytes = file.read()
flat_integers = [int... |
import unittest
import sys
import os
sys.path.append('../../')
from etk.core import Core
import json
import codecs
class TestTableExtractions(unittest.TestCase):
def setUp(self):
self.e_config = {
"document_id": "doc_id",
"extraction_policy": "replace",
"error_handling... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from .web_view import VizSeqWebView
from .data_view import VizSeqDataPageView, DEFAULT_PAGE_SIZE, DEFAULT_PAGE_NO
from .d... |
from typing import DefaultDict, List
import itertools
class CachedParamMixin:
data: DefaultDict[float, List[float]] = None
def __init__(self):
self._all_keys = None
self._keysmax = None
self._keysmin = None
self._valmax = None
self._valmin = None
@property
def ... |
# Python Object Oriented Programming by Joe Marini course example
# Using composition to build complex objects
# Inheritance is a - is type of relationship.
# composition is different from inheritance. When using composition, we build objects out of other objects and this model is more of a has a relationship. B. ok o... |
from dns.rdtypes.ANY.TXT import TXT
def query(records):
context = {}
context['i'] = -1
def mockable(_, __, ___):
if context['i'] + 1 < len(records):
context['i'] += 1
rdclass = 1
rdtype = 1
strings = records[context['i']]
return [
TXT(rdcl... |
import numpy as np
import matplotlib.pyplot as plt
from random import randint
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils
from sklearn.model_selection import cross_val_score
from sklearn.model_sel... |
import re
class DisambiguatorPrefixRule19(object):
"""Disambiguate Prefix Rule 19
Original Rule 19 : mempV -> mem-pV where V != 'e'
Modified Rule 19 by ECS : mempA -> mem-pA where A != 'e' in order to stem memproteksi
"""
def disambiguate(self, word):
"""Disambiguate Prefix Rule 19
... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015 Cisco Systems, Inc. and others. 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... |
"""Tests for citrine.informatics.rows."""
import pytest
from citrine.gemtables.rows import MaterialRunByTemplate, Row
from gemd.entity.link_by_uid import LinkByUID
@pytest.fixture(params=[
MaterialRunByTemplate(templates=[
LinkByUID(scope="templates", id="density"), LinkByUID(scope="templates", id="ingre... |
#!/usr/bin/env python3
# Copyright (C) 2019 Freie Universität Berlin
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.
import sys
from testrunner import run
def testfunc(child):
child.expect_e... |
"""
Check that multiple BEP can be assigned to a single cast listener.
"""
import support
from java import awt
support.compileJava("test006j.java")
import test006j
def f(evt):
pass
m = test006j()
m.componentShown = f
m.componentHidden = f
m.fireComponentShown(awt.event.ComponentEvent(awt.Container(), 0))
m... |
import sys
from configparser import ConfigParser
from steam.client import SteamClient
from dota2.client import Dota2Client
import logging
from random import randint
import os
#-> Mudar diretorio aqui se necessário
paginaspath = os.path.dirname(os.path.abspath(__file__))
botspath = os.path.join(paginaspath, 'bots.ini')... |
from collections import defaultdict
from dataclasses import dataclass
from math import ceil
from typing import Dict, List
@dataclass
class Reactant:
quantity: int
ID: str
@dataclass
class Reaction:
output: Reactant
dependencies: List[Reactant]
def ore_required_for(target: Reactant, reactions: Dict... |
from .di import DiContainer as _DiContainer
def di_container(main_file_path):
"""
:type main_file_path: str
:rtype: gold_digger.di.DiContainer
"""
return _DiContainer(main_file_path)
_DiContainer.set_up_root_logger()
|
import os
import sys
import boto3
from dateutil import parser
from botocore.exceptions import ClientError
def get_latest_ami(ec2_conn, ami_filter, nodetype):
try:
latest = None
response = ec2_conn.describe_images(Filters=ami_filter)
if len(response['Images']) != 0:
print('[INFO] AMIs found:')
... |
#Оператор цикла for
for i in range(5):
print("Hello")#В результате “Hello” будет выведено пять раз
lst = [1, 3, 5, 7, 9]
for i in lst:
print(i ** 2) #Также можно пройти по всем буквам в строке.
word_str = "Hello, world!"
for l in word_str:
print(l) #Строка “Hello, world!” будет напечатана в столбик.
|
import pandas as pd
import os
import numpy as np
import json
import glob
import sys
import time
#from git import Repo
def find_range(x,a,b,option='within'):
"""
Find indices of data within or outside range [a,b]
Inputs:
-------
x - numpy.ndarray
Data to search
a - float or int
... |
#!/usr/bin/env python
import sys
from setuptools import find_packages, setup
requirements = ['torch']
assert sys.version_info[0] == 3
if sys.version_info[1] < 7:
requirements.append('dataclasses')
dev_requirements = {'dev': ['mypy>=0.660', 'pycodestyle>=2.4.0']}
test_requirements = ['pytest>=4.1.1']
setup(
... |
import os
from meaningless.bible_base_extractor import BaseExtractor
from meaningless.utilities import xml_file_interface
class XMLExtractor(BaseExtractor):
"""
An base extractor object that retrieves Bible passages from an XML file
"""
def __init__(self, translation='NIV', show_passage_numbers=True, ... |
from sympy.core.numbers import RealNumber
from ..syms import syms
import numpy as np
from sklearn.linear_model.base import LinearRegression
from ..sym_predict import register_sym_predict
def sym_predict_linear(estimator):
if hasattr(estimator, 'intercept_'):
expression = RealNumber(estimator.intercept_[0])... |
import sys
sys.path.append("../")
from settings import (NES_PALETTE_HEX, animation_settings)
from core import sprite
ColScottOConnorWalkRight01 = sprite(
palette = {
"b":NES_PALETTE_HEX[0, 13],
"d":NES_PALETTE_HEX[0, 6],
"l":NES_PALETTE_HEX[1, 6],
"w":NES_PALETTE_HEX[3, 0],
},
... |
"""Numerical timestepping methods for stochastic differential equation (SDE) systems."""
import sympy
import symnum.numpy as snp
import symnum.diffops.symbolic as diffops
def euler_maruyama_step(drift_func, diff_coeff):
"""Construct Euler-Maruyama integrator step function."""
def forward_func(z, x, v, δ):
... |
__author__ = 'lorenzo'
import dtk
import pickle
import sentence_encoder
import dataset_reader
from tree import Tree
import numpy
class DatasetCreator:
def __init__(self, file = "/Users/lorenzo/Documents/Universita/PHD/Lavori/DSTK/RTE/RTE3_dev_processed.xml.svm",
dtk_params={"LAMBDA":1.0, "dimens... |
from decouple import config
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = config('POSTGRES')
db = SQLAlchemy(app)
# entity needs to be placed after app and db is created
from entity.output import Output
from entity.input import ... |
"""Diagnostics support for Synology DSM."""
from __future__ import annotations
from synology_dsm.api.surveillance_station.camera import SynoCamera
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF... |
# Copyright 2018-2021 The glTF-Blender-IO 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 ... |
import smartpy as sp
class SoccerBetFactory(sp.Contract):
def __init__(self, admin):
self.init(
admin=admin,
games=sp.map(tkey=sp.TInt),
archived_games = sp.map(tkey = sp.TInt),
remainder=sp.tez(0)
)
@sp.entry_point
def new_game(self, params... |
# Generated by Django 2.2.1 on 2019-05-01 16:13
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mapper', '0002_auto_20190430_2053'),
]
operations = [
migrations.CreateModel(
name='Peptide',
... |
from .abt_buy import AbtBuyBenchmark # noqa: F401
from .amazon_google import AmazonGoogleBenchmark # noqa: F401
from .beer import BeerBenchmark # noqa: F401
from .company import CompanyBenchmark # noqa: F401
from .dblp_acm_structured import DBLP_ACM_StructuredBenchmark # noqa: F401
from .dblp_scholar_structured im... |
import time
import ipaddress
from nubia import command, argument
import pandas as pd
from suzieq.cli.sqcmds.command import SqCommand
from suzieq.sqobjects.routes import RoutesObj
@command("route", help="Act on Routes")
class RouteCmd(SqCommand):
def __init__(
self,
engine: str = "",
hostn... |
"""
Author: Anthony Perez
A collection of ImageDatasource classes which allow loading of generic image collections by name.
"""
import ee
from gee_tools.datasources.interface import MultiImageDatasource, GlobalImageDatasource, SingleImageDatasource, DatasourceError
class GenericSingleImageDatasource(SingleImageDataso... |
import abc
import os
class Config:
BASE_DIR = os.path.dirname(__file__)
DATA_DIR = os.path.join(BASE_DIR, 'data')
VOCABS_DIR = os.path.join(DATA_DIR, 'vocabs')
CHECKPOINTS_DIR = os.path.join(DATA_DIR, 'checkpoints')
class UniEnViConfig:
PROBLEM = 'uni_en_vi'
MODEL = 'transformer'
CHECKPO... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def tree2str(self, t: TreeNode) -> str:
def dfs(root):
if not root:
return ''
# 左子树为空右子树不... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.