content stringlengths 5 1.05M |
|---|
import os
import re
from datetime import datetime
import numpy as np
import pandas as pd
import pytz
from donfig import Config
from jira import JIRA
from loguru import logger
from db import dataframe_to_db
from tqdm import tqdm
config = Config("jira_reporting")
class Report:
def __init__(self, jql_filter: dict... |
# script for testing water level reading
# generates a self calibrated percentage of fullness.
#
# bar chart ref - https://alexwlchan.net/2018/05/ascii-bar-charts/
import machine
import time
# define pins
CAP_PIN = const(14)
# define starting values
min_value = 500
max_value = 800
bar_size = 25
# setup inputs and ... |
def get_secret (key):
file = open ("secrets.txt", 'r')
secrets = file.read().splitlines()
file.close()
for i in range (len (secrets)):
if secrets[i] == "# " + key:
return secrets[i+1]
print ("Invalid key!!")
def get_account_sid():
return get_secret ('account_sid')
def... |
# Copyright 2013 Cloudbase Solutions SRL
# Copyright 2013 Pedro Navarro Perez
# 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... |
from setuptools import setup
from setuptools import find_packages
setup(
name="l2a",
version="1.0.0",
description="Machine learning sample for integer addition",
author="Philippe Trempe",
author_email="ph.trempe@gmail.com",
url="https://github.com/PhTrempe/l2a",
license="MIT",
install_r... |
# Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
# Project developers. See the top-level LICENSE file for dates and other
# details. No copyright assignment is required to contribute to VisIt.
###############################################################################
# file: __init__.py... |
# -*- coding: utf-8 -*-
import random, re
from bot.core import Answer
def substitute(text, factsheet):
t = text
if factsheet is not None and len(factsheet) > 0:
for i in factsheet.get_facts():
t = t.replace('{%s}' % i.get_label(), i.get_value())
return t
def make_answer(templates, con... |
from __future__ import absolute_import
from __future__ import print_function
# Inspecting the numpy namespace and classifying numpy's functions
import numpy as np
from collections import defaultdict
import types
import inspect
import six
heading = lambda x : "-"*20 + str(x) + "-"*20
np_types = defaultdict(list)
for n... |
# Generated by Django 3.1.3 on 2021-09-02 01:02
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('aao_vender', '0011_auto_... |
from setuptools import setup
setup(name='aaron',
version='0.1',
description='python utils packages by aaron',
url='https://github.com/AaronTao1990/aaron.git',
author='Aaron',
author_email='aarontao1990@gmail.com',
license='MIT',
packages=['aaron'],
zip_safe=False)
|
from __future__ import annotations
import sys
import re as regex
from typing import List, Pattern, Dict
class Node:
"""
Decision tree node
"""
def __init__(self, depth: int, name: str = "") -> None:
"""
Creates a new decision tree node
:param depth: Depth of the tree from this... |
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (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.mozilla.org/MPL/
#
# Softwa... |
# This material was prepared as an account of work sponsored by an agency of the
# United States Government. Neither the United States Government nor the United
# States Department of Energy, nor Battelle, nor any of their employees, nor any
# jurisdiction or organization that has cooperated in the development of thes... |
#
# flp - Module to load fl forms from fd files
#
# Jack Jansen, December 1991
#
from warnings import warnpy3k
warnpy3k("the flp module has been removed in Python 3.0", stacklevel=2)
del warnpy3k
import string
import os
import sys
import FL
SPLITLINE = '--------------------'
FORMLINE = '=============== FORM =========... |
# Generated by Django 2.0.2 on 2018-12-04 00:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('products', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='product',
name='body',
),
m... |
from uliweb.core.template import BaseBlockNode
class PermissionNode(BaseBlockNode):
def generate(self, writer):
writer.write_line('if functions.has_permission(request.user, %s):' %
self.statement, self.line)
with writer.indent():
self.body.generate(writer)
... |
"""Add parameter to enable/disable support activity
Revision ID: e9e9adb7e801
Revises: b05231a3afda
Create Date: 2021-06-13 20:52:31.981823
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "e9e9adb7e801"
down_revision = "b05231a3afda"
branch_labels = None
depend... |
from . import category, common, group, junction
from . import junction_old
|
from http import HTTPStatus
import pytest
from app.model.recipes import Recipe
class TestRecipe:
@classmethod
def setup_class(cls):
Recipe.drop_collection()
@pytest.fixture()
def new_recipe(self):
return {"title": "ovo cozido", "ingredients": ["ovo", "água"], "howto": "cozinhe o ovo... |
import asyncio
import logging
from queue import Empty
from . import randomizer
logger = logging.getLogger(__name__)
class AnimaLiaison:
"""
Anima Liaison is responsible for the actual operation of our automaton
At its core is a state machine which queues and monitors jobs to be satisfied by the captain... |
import json
import os
import io
import sys
from string import Template
__version__ = "1.0.18"
__mode__ = "dev"
def read_kv_file(fileName):
myvars = {}
if os.path.isfile(fileName):
with open(fileName) as kvfile:
for line in kvfile:
name, var = line.partition("=")[::2]
... |
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.feature_selection import SelectPercentile, chi2, f_classif
from sklearn.cross_validation import train_test_split
from sklearn.naive_bayes import BernoulliNB
from sklearn.svm import LinearSVC, SVC
from sklearn.t... |
# %% 这是在这个项目里面测试的时候才跑的,修改当前目录到这个项目的主文件夹
import os
import sys
sys.path += [os.path.realpath('.')]
# %% 现在开始才是使用时应该用的内容
from pathlib import Path
import pickle
import warnings
import numpy as np
import pandas as pd
from pandas.core.common import SettingWithCopyWarning
import pytorch_lightning as pl
from pytorch_lightn... |
import random
import math
import datetime
def four_gamete_test(marker1,marker2,missing_char='N'):
if len(marker1)!=len(marker2):
raise ValueError, 'unequal number of genotypes'
gametes=[]
for i in xrange(len(marker1)):
if marker1[i]==missing_char or marker2[i]==missing_char:
continue
if (marker1[i],mark... |
import os
import numpy as np
import soundfile as sf
import glob
import librosa
from urllib.request import urlretrieve
EPS = np.finfo(float).eps
COEFS_SIG = np.array([9.651228012789436761e-01, 6.592637550310214145e-01,
7.572372955623894730e-02])
COEFS_BAK = np.array([-3.733460011101781717e+00,2.7... |
import pandas as pd
# Kind of data handled by pandas
df = pd.DataFrame({
"Name": ["Jenny", "Little", "Owens"],
"Age": [23, 45, 67],
"Favouratie_color": ["Red", "Blue", "Black"]
})
# geting data from a specific column
name_data = df["Name"]
# getting the maxiumum nuber in the colunm
bigge... |
# Imports -----------------------------------------------------------
import os
os.environ["PREFECT__FLOWS__CHECKPOINTING"] = "true"
from prefect import Flow, Parameter, task
from xpersist.prefect.result import XpersistResult
from cmip6_downscaling.config.config import ( # dask_executor,; kubernetes_run_config,; sto... |
import responses
from binance.spot import Spot as Client
from tests.util import mock_http_response
from tests.util import random_str
from binance.error import ParameterRequiredError
mock_item = {"key_1": "value_1", "key_2": "value_2"}
key = random_str()
secret = random_str()
params = {"asset": ["LTC", "EOS"]}
def t... |
# -*- coding: utf-8 -*-
"""
Return/control aspects of the grains data
Grains set or altered with this module are stored in the 'grains'
file on the minions. By default, this file is located at: ``/etc/salt/grains``
.. Note::
This does **NOT** override any grains set in the minion config file.
"""
import collecti... |
#############################################################################
# Copyright (c) 2007-2016 Balabit
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation, or (at your option) an... |
from disnake.appinfo import *
from disnake.appinfo import __dict__ as __original_dict__
locals().update(__original_dict__)
|
# This code will get all the odd birthdays and print it
birthdays = [12, 4, 21, 11, 24] # O(1)
odd_birthdays = [] # O(1)
for birthday in birthdays: # O(n)
if birthday % 2 == 1: # O(1)*O(n) = O(n)
odd_birthdays.append(birthday) # O(1)*O(n) = O(n)
print(odd_birthdays) # O(1)
# Sum = O(1) + O(1) + O(n... |
# https://leetcode.com/problems/two-sum/
# Given an array of integers nums and an integer target,
# return indices of the two numbers such that they add up to target.
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
# You can return the answer in any order.
i... |
from __future__ import absolute_import, division, print_function
import sys
import os
import shutil
from libtbx import subversion
from libtbx.option_parser import option_parser
import libtbx.file_clutter
def clean_clutter_in(files, tabsize=8):
if not files: return
for fname in files:
tmpname = fname + '.bak'
... |
from django.conf.urls import url, include
from rest_framework import routers
from .views import PlayerViewSet, TeamViewSet, CoachViewSet
router = routers.DefaultRouter()
router.register(r'players', PlayerViewSet)
router.register(r'teams', TeamViewSet)
router.register(r'coach', CoachViewSet)
urlpatterns = [
url(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 28 19:28:17 2019
@author: Wanling Song
"""
import mdtraj as md
import numpy as np
import pandas as pd
import argparse
import sys
from collections import defaultdict
import pickle
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.p... |
import logging
import os
import sys
from locust import Locust
from locust import TaskSet
from locust import task
from locust import HttpLocust
logger = logging.getLogger("dummy_locust")
# class MyTaskSet(TaskSet):
# @task
# def my_task(self):
# print('Locust instance (%r) executing "my_task"'.forma... |
import numpy as np
import joblib
import pprint
from utils.BaseModel import BaseModel, R2
from utils.SpecialPlotters import train_cv_analyzer_plotter
from utils.AwesomeTimeIt import timeit
from utils.RegressionReport import evaluate_regression
from utils.FeatureImportanceReport import report_feature_importance
import ... |
"""
[2016-12-05] Challenge #294 [Easy] Rack management 1
https://www.reddit.com/r/dailyprogrammer/comments/5go843/20161205_challenge_294_easy_rack_management_1/
# Description
Today's challenge is inspired by the board game Scrabble. Given a set of 7 letter tiles and a word, determine whether
you can make the given wo... |
import sys
import os
import re
def camel_to_sletter(filename):
""" transform function names of camel case to that of small letters """
o_filename = os.path.splitext(filename)[0] + "_converted.py"
print("input : ", os.path.splitext(filename))
print("output : ", o_filename)
# _regex_camel = re.co... |
#noinspection PyUnresolvedReferences
import sys
|
import pytest
from pre_commit_hooks.check_json import main
from testing.util import get_resource_path
@pytest.mark.parametrize(
('filename', 'expected_retval'), (
('bad_json.notjson', 1),
('bad_json_latin1.nonjson', 1),
('ok_json.json', 0),
('duplicate_key_json.json', 1),
),
)... |
#!/usr/bin/env python3
import argparse
import datetime
import re
import subprocess
import sys
from typing import Any, Tuple
parser = argparse.ArgumentParser(description="Tags and releases the next version of this project.")
parser.add_argument("tag", help="Semantic version number to use as the tag.")
parser.add_argu... |
"""Support routines for the qdyn_prop_gate utility"""
import re
import numpy as np
from .units import UnitFloat
def _isqrt(n):
"""Integer square root of n > 0
>>> _isqrt(1024**2)
1024
>>> _isqrt(10)
3
"""
assert n >= 0
x = n
y = (x + 1) // 2
while y < x:
x = y
... |
def rekurzivna_funkcija(s):
if len(s) ==0:
return s
else:
return rekurzivna_funkcija (s[1:])+s[0]
rez=rekurzivna_funkcija("programiranje")
print(rez)
|
import unittest
import torch
import numpy as np
from connectomics.data.augmentation import *
class TestModelBlock(unittest.TestCase):
def test_mixup(self):
"""Test mixup for numpy.ndarray and torch.Tensor.
"""
mixup_augmentor = MixupAugmentor(num_aug=2)
volume = np.ones((4,1,8,32,... |
import time
from setuptools import find_packages
from distutils.core import setup
patch_level = int(time.time())
ver = "0.1." + str(patch_level)[4:]
setup(
name = 'slackbot_ts',
packages = find_packages(),
version = ver,
description = 'Python Code for Tech Em Studios Classes',
author = 'Tech Em Studios',... |
from .base_bev_backbone import BaseBEVBackbone
from .hg_bev_backbone import HgBEVBackbone
__all__ = {
'BaseBEVBackbone': BaseBEVBackbone,
'HgBEVBackbone': HgBEVBackbone
}
|
import torch
import random
import inspect
import re
import logging
import types
import syft as sy
from ... import workers
from ... import utils
from . import utils as torch_utils
from .tensor import _SyftTensor, _LocalTensor, _PointerTensor, _FixedPrecisionTensor, _TorchTensor
from .tensor import _TorchVariable
class... |
import cv2
import time
import torch
import pprint
import numpy as np
from pathlib import Path
from psdet.utils.config import get_config
from psdet.utils.common import get_logger
from psdet.models.builder import build_model
def draw_parking_slot(image, pred_dicts):
slots_pred = pred_dicts['slots_pred']
width... |
#!/usr/bin/env python3
from QUBEKit.utils import constants
from collections import OrderedDict
from copy import deepcopy
import xml.etree.ElementTree as ET
class Parametrisation:
"""
Class of methods which perform the initial parametrisation for the molecule.
The Parameters will be stored into the mole... |
from .litmus import *
|
__version__ = '2.3.5'
|
"""
TODO:
Actors need to be able to reference each other.
* this means we need to be able to pass a reference
that can post a message to an actor's executor.
Actors need to be able to create more actors.
* This should be fairly simple if the first task is complete.
Idea:
m... |
#!/usr/bin/env python
from typing import List, Tuple
from bisect import bisect_left
"""
Code for https://leetcode.com/problems/search-in-rotated-sorted-array/
"""
def search(nums: List[int], target: int) -> int:
pivot_idx = find_pivot(nums, 0, len(nums) - 1)
if pivot_idx == -1:
return binary_search(... |
from typing import Dict, Optional, List
from torch.nn import Linear
import torch
from torch.autograd import Variable
from torch.nn.functional import normalize
from allennlp.common import Params
from allennlp.common.checks import check_dimensions_match
from allennlp.data import Vocabulary
from allennlp.models.model impo... |
# find the longest match in the running window
def findLongestMatch(searchSpace: bytes, matchBytes: bytes) -> tuple:
matchLength = len(matchBytes)
searchSize = len(searchSpace)
while matchLength > 0:
lookup = matchBytes[:matchLength]
if lookup in searchSpace:
return searchSize -... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2002-2004 Detlev Offenbach <detlev@die-offenbachs.de>
# Adapted for usage with Debian by Torsten Marek <shlomme@gmx.net>
# Changed by Gudjon, only to create qt apis
import os
import sys
#import PyQt4.pyqtconfig as pyqtconfig
import PyQt5.QtCore
apidir = sys... |
from math import factorial
from input_validator import validate_input
def Q_US(n, p, C, validate=True):
"""
:param n: zero or positive integer, depth
:param p: positive integer, number of atomics
:param C: dict, keys: positive integers (arities), values: sets of strings (constants of that arity)
... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import Any, List, Sized, Tuple
import torch as torch
import torch.nn as nn
from pytext.utils.cuda_utils import xaviervar
class Element:
"""
Generic element representing a token / non-terminal / sub-tree... |
'''
a basic character-level sequence to sequence model.
'''
# coding=utf-8
from keras.models import Model
from keras.layers import Input, LSTM, Dense
import numpy as np
# config
batch_size = 64
epochs = 1
hidden_dim = 256
num_samples = 10000
data_path = './fra-eng/fra.txt'
save_model_path = './s2s.h5'
# vector of data... |
import os
import subprocess
from tempfile import NamedTemporaryFile
from backuppy.location import SshTarget, SshSource
RESOURCE_PATH = '/'.join(
(os.path.dirname(os.path.abspath(__file__)), 'resources'))
CONFIGURATION_PATH = '/'.join((RESOURCE_PATH, 'configuration'))
def build_files_stage_1(path):
"""Build... |
from lecture_07.homework7.tasks.task1 import find_occurrences
example_tree = {
0: [("RED",), "BLUE", [], (), {}],
(1, 2): {
"simple_key": [False, "list", 800, {"RED", "set"}],
},
1: {
"abc": ("BLUE",),
("j", "h", "l"): "RED",
5: {
"key2": "RED",
(... |
#!/usr/bin/env python3
# Copyright (C) Daniel Carter 2019
# Licensed under the 2-clause BSD licence
# Web scraper for Android Vulnerability Bulletins
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from datetime import datetime, date
import os
import utils
import json
fro... |
# file test_fedora/test_cryptutil.py
#
# Copyright 2011 Emory University Libraries
#
# 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... |
import matplotlib.pyplot as plt
import numpy as np
import json
with open('../tokamaks.json') as f:
machines = json.load(f)
# by type of machine
plt.figure()
types_labels = ["Tokamaks", "Stellarators", "Inertial", "Others"]
types_machine = ["tokamak", "stellarator", "inertial", "alternate_concept"]
bottom = 0
cou... |
"""Global fixtures"""
import os
import shutil
from os.path import join
import pytest
from hdx.hdx_configuration import Configuration
@pytest.fixture(scope="function")
def configuration():
project_config_yaml = join("tests", "fixtures", "project_configuration.yml")
Configuration._create(
hdx_site="pro... |
import uuid
from django.db import models
from django.utils.translation import gettext_lazy as _
from heroku_connect.db import models as hc_models
__all__ = ("NumberModel", "OtherModel")
def frozen_uuid_generator():
return uuid.UUID(hex="653d1c6863404b9689b75fa930c9d0a0")
class NumberModel(hc_models.HerokuCon... |
import pickle
import os
files = ['logdeparture', 'cmass', 'tau', 'T', 'vturb']
folders = ['prd', 'prd_2']
destination_folder = 'prd_full'
if not os.path.exists(f'../data/{destination_folder}'):
os.makedirs(f'../data/{destination_folder}')
for file in files:
dataset = []
for folder in folders:
wit... |
import json
import requests
from requests.exceptions import RequestException
import re
import time
import random
def get_one_page(url):
try:
response = requests.get(url)
if response.status_code == 200:
response.encoding = 'utf-8'
return response.text
return None
... |
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
class GUI:
__gui_image = {}
__gui_image["moveBothHands"] = Image.open("Brain_Waves_Analysis/Training_Data_Acquisition/src/resources/moveBoth.png")
__gui_image["moveLeftHand"] = Image.open("Brain_Waves_Analysis/Training_Data_A... |
# from .optimization import *
# from .benchmarks import *
|
#!/usr/bin/env python
# coding: utf-8
import os
import pandas as pd
import logging
import json
from tqdm import tqdm
from datetime import datetime
logging.basicConfig(
level=logging.INFO,
filename='met_data_metadata.log',
filemode='w',
format='%(asctime)s - %(message)s',
datefmt='%d-%b-%y %H:%M:%... |
import unittest
# import HTMLTestRunner
import sys
sys.path.append("..")
import ascend
import numpy as np
import cv2
import os
def decode(heatmap, scale, offset, landmark, size, thresh=0.1):
heatmap = np.squeeze(heatmap[0])
scale0, scale1 = scale[0, 0, :, :], scale[0, 1, :, :]
offset0, offs... |
"""aws lambda function to download videos using youtube-dl to a S3 bucket.
use it for read/watch-it-later things or for archiving."""
import boto3
import youtube_dl
import os
# define s3 bucket
s3_bucket = os.environ["S3_BUCKET"]
region = os.environ["AWS_REGION"]
# define boto client
s3 = boto3.client("s3", region_na... |
n = int(input())
for a in range(1, n+1):
for b in range(1, n+1):
for c in range(1, n+1):
print(chr(96+a)+chr(96+b)+chr(96+c)) |
import numpy as np
from bsym.configuration import Configuration
def is_square( m ):
"""
Test whether a numpy matrix is square.
Args:
m (np.matrix): The matrix.
Returns:
(bool): True | False.
"""
return m.shape[0] == m.shape[1]
def is_permutation_matrix( m ):
"""
Test ... |
from tkinter import*
import sqlite3
user_pas=Tk()
user_pas.geometry("300x200")
user_pas.title("User_pas")
db=sqlite3.connect("user_pas.db")
#cursor
c=db.cursor()
#insert into tabels
c.execute("""CREATE TABLE user_pas(
username text,
password text
)""")
#commit_changes
db.commit()
#close conne... |
class Solution:
def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int:
idxes = list(range(len(values)))
ans = 0
m = collections.Counter()
for idx in sorted(idxes, key=lambda x : values[x], reverse=True):
label = labe... |
# coding: utf-8
"""
Scubawhere API Documentation
This is the documentation for scubawhere's RMS API. This API is only to be used by authorized parties with valid auth tokens. [Learn about scubawhere](http://www.scubawhere.com) to become an authorized consumer of our API
OpenAPI spec version: 1.0.0
... |
### Code: Lambda function to filter ec2, s3 and vpc events.
### Author: Nitin Sharma
### SDK: Python 3.6 boto3
### More info: Refer to 4hathacker.in
import json
import base64
import gzip
import boto3
import zlib
import base64
from datetime import datetime
from io import StringIO
import ast
import random
print('Loadi... |
from tests import BiTestCase as TestCase
class TestApp(TestCase):
def test_the_testing(self):
self.assertTrue(True)
|
import unittest
try:
from unittest.mock import Mock, patch
except:
from mock import Mock, patch
from ixnetwork_restpy.tests.fixtures.mocks import Mocks
from ixnetwork_restpy.testplatform.testplatform import TestPlatform
class TestConnect(unittest.TestCase):
@patch('ixnetwork_restpy.connection.Connection._... |
import sys
sys.path.append("..") # 先跳出当前目录
from bean.word_unit import WordUnit
class EntityCombine:
"""将分词词性标注后得到的words与netags进行合并"""
def combine(self, words, netags):
"""根据命名实体的B-I-E进行词合并
Args:
words: WordUnit list,分词与词性标注后得到的words
netags: list,命名实体识别结果
Returns... |
import os
import pytest
import yaml
from saucebindings.options import SauceOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver import __version__ as seleniumVersion
class TestInit(object):
def test_defaults(self):
sauce = SauceOptions.firefox()
... |
from typing import Optional, Tuple
from pandas.core.frame import DataFrame
from pandas.core.series import Series
from ..caller_base import CallerBase
from ..error.client_only_endpoint import client_only_endpoint
from ..error.illegal_attr_checker import IllegalAttrChecker
from ..error.uncallable_namespace import Uncal... |
# Copyright 2018 Google LLC. 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... |
import time
import subprocess
import socket
from datetime import datetime
def runSikuliScript(path):
filepath = path
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)
stdout, stderr = p.communicate()
print("Done Running Sikuli - " + str(datetime.now()))
def internet(host="8.8.8.8", ... |
#!/usr/bin/env python
import cgi
import cgitb
import re
import fcntl
def print_res():
print "Content-type: text/html\n\n"
f = open("../homework/w3/query/w3-query.dat")
fcntl.flock(f, fcntl.DN_ACCESS)
template = "".join(open("../homework/w3/src/table.html").readlines()).split("<!-- insert point-->")
... |
#
# Copyright (C) 2013 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 required by applicable law or agreed t... |
import taichi as ti
import numpy as np
import utils
from engine import mpm_solver
# Try to run on GPU
ti.init(arch=ti.cuda)
mpm = mpm_solver.MPMSolver(res=(24, 24, 24), size=1)
mpm.set_gravity((0, -20, 0))
mpm.add_sphere_collider(center=(0.25, 0.5, 0.5), radius=0.1, surface=mpm.surface_slip)
mpm.add_sphere_collider... |
from . import views as primer_views
from django.urls import path
from django.contrib.auth.decorators import login_required
urlpatterns = [
path('primerinput/', login_required(primer_views.PrimerFormView.as_view()), name='primerinput'),
path('primer/', primer_views.PrimerFilteredTableView.as_view(), name='pri... |
a = float(input("Digite o tamanho de um lado de um triangulo: "))
b = float(input("Digite o valor de um segundo lado do triangulo: "))
c = float(input("Digite o valor do terceiro lado do triangulo: "))
if b - c < a < b + c and a - c < b < a + c and a - b < c < a + b:
print("Pode ser um triangulo")
else:
print(... |
# -*- coding: utf-8 -*-
"""Helper utilities and decorators."""
from flask import flash, _request_ctx_stack
from functools import wraps
from flask_jwt import _jwt
import jwt
def jwt_optional(realm=None):
def wrapper(fn):
@wraps(fn)
def decorator(*args, **kwargs):
token = _jwt.request_ca... |
PRONUNCIATION_SEP = "\t"
SYMBOL_SEP = " "
INCLUDE_COUNTER = True
ENCODING = "UTF-8"
UNK_SYMBOL = "None" |
from .student import Student
|
'''
Podstawowe sposoby otwierania plików
r - Read (czytanie) - domyślne
w - Write (pisanie - jesli plik istniał to go usuniue, jeśli nie to stworzy
a - Append (dopisywanie)
rozszerzenie to tylko 'teskst' nadawany po to aby inne programy rozpoznawały plik w odpowiedni dla tych programów sposób
'''
try:
file = op... |
import asyncio
import base64
import hashlib
import os
import unittest
from unittest import mock
import aiohttp
from aiohttp import errors, hdrs, websocket, websocket_client
class TestWebSocketClient(unittest.TestCase):
def setUp(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import operator
import warnings
import numpy as np
from nevergrad.parametrization import parameter as p
from ... |
from .bfp import BFP
from .fpn import FPN
from .hrfpn import HRFPN
from .just_one_outs_neck import FPNLast, HRFPNLast, FPNCatLast, MyFPN, MyFPN3
__all__ = ['FPN', 'BFP', 'HRFPN', 'FPNLast', 'HRFPNLast', 'FPNCatLast', 'MyFPN', 'MyFPN3']
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.