content stringlengths 5 1.05M |
|---|
employes = {
"id01": {"prenom": "Paul", "nom": "Dupont", "age": 32},
"id02": {"prenom": "Julie", "nom": "Dupuit", "age": 25},
"id03": {"prenom": "Patrick", "nom": "Ferrand", "age": 36}
}
print (employes)
if "id03" in employes:
del employes["id03"]
if "id02" in employes:
employes["id02"]["age"]=26
... |
import sys
import cubey
def main(serialPort):
cube = cubey.Cube(serialPort)
print "Listening, Ctrl-C to stop..."
try:
while True:
rawMessage = cube.sendCommand("m n u")
printMessage(rawMessage)
except KeyboardInterrupt:
print
cube.breakOut()
print "D... |
import commands
import numpy as np
import matplotlib
import pkg_resources as p
matplotlib.use('Agg')
import os
import nipype.pipeline.engine as pe
from nipype.interfaces import afni
import nipype.interfaces.utility as util
def append_to_files_in_dict_way(list_files, file_):
"""Combine files so at each resource in... |
#!/usr/bin/env python
# Test of relationship between system and ros time
import time
import rospy
from bdbd_common.utils import fstr
from nav_msgs.msg import Odometry
def odom_cb(odometry):
global ros_start
global sys_start
now = float(odometry.header.stamp.secs + 1.0e-9 * odometry.header.stamp.nsecs)
... |
import metastore.backend as metastore
from migrate_metadata import migrator
def test_migrate_datasets_migrates_only_of_type_dataset():
datasets = [
{"name": "test_pkg_0", "author": "test_user", "type": "dataset"},
{"name": "test_pkg_1", "author": "test_user", "type": "showcase"},
{"name": ... |
import torch
from pytorch_lightning.utilities.types import STEP_OUTPUT
from torch import nn, cat
import torch.nn.functional as F
import pytorch_lightning as pl
from torch.optim import Adam
from teach.logger import create_logger
logger = create_logger(__name__)
class NaiveMultiModalModel(pl.LightningModule):
def... |
import os
import cv2
import face_recognition
import PySimpleGUI as sg
# Initial setting
tolerance = 0.5
frame_drop = 0
vcap = cv2.VideoCapture('img/video.mp4', cv2.CAP_FFMPEG)
# Mosaic function
def mosaic(src, ratio):
small = cv2.resize(src, None, fx=ratio, fy=ratio, interpolation=cv2.INTER_NEAREST)
return c... |
import os
import re
import collections
import base64
import gzip
import datetime as dt
import pandas as pd
import simplejson as json
from .flexbox import FlexboxCSS
class Util:
@staticmethod
def data_to_json(value, widget):
dump = json.dumps(value, default=Util.json_serial, ignore_nan=True)
... |
from .classic_measures import *
from .truediversity import * |
"""
The View classes render the data returned by a Source as a Panel
object.
"""
import sys
from io import StringIO
from weakref import WeakKeyDictionary
import numpy as np
import param
import panel as pn
from bokeh.models import NumeralTickFormatter
from panel.pane.base import PaneBase
from panel.pane.perspective ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
script for generating cache
"""
import argparse
import sys
import aioredis
import asyncio
import asyncpg
def argument_parser():
parser = argparse.ArgumentParser(description='generate cache')
parser.add_argument(
'database', nargs='?', help='database n... |
# Copyright 2018 Ericsson
#
# 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... |
import configdualbot
import psycopg2
import csv
import player
import collections
import logging
import datetime
import json
from psycopg2.extras import RealDictCursor
logging.basicConfig(
filename=f'logs/{datetime.datetime.utcnow().strftime("%Y-%m-%d-%H-%M-%S")}.log',
filemode='w',
format='PostgreSQL -... |
# Bruce Maxwell
# Revised for spring 2013
# Tested for Python 3 fall 2017
# test function 1 for lab 9
import turtle_interpreter
import random
def main():
""" draw a 4x4 square of alternating filled and unfilled squares """
terp = turtle_interpreter.TurtleInterpreter()
square = 'F-F-F-F-'
fsquare = '{... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.python.rules import (
download_pex_bin,
pex,
pex_from_target_closure,
prepare_chrooted_python_sources,
repl,
)
from pants.backend.python.rules.repl i... |
# encoding=utf8
from matplotlib import pyplot as plt
from scipy.interpolate import spline
import numpy as np
U = [
-1,
50,
100,
150,
200,
250,
300,
350,
400,
450,
500,
550,
600,
650,
700,
750... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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 ... |
import os
import random
import glob
import numpy as np
import cv2
import torch
from skimage import io, transform
from torch.utils.data import Dataset, DataLoader
class DogCat(Dataset):
def __init__(self, root_path, training=False):
self.image_file_list = glob.glob(os.path.join(root_path, "*.jpg"))
de... |
import sys
print('version is', sys.version) |
from .dawa import DAWA
|
"""
Quartic Polynomial
"""
import numpy as np
class QuarticPolynomial:
def __init__(self, x0, v0, a0, v1, a1, T):
A = np.array([[3 * T ** 2, 4 * T ** 3],
[6 * T, 12 * T ** 2]])
b = np.array([v1 - v0 - a0 * T,
a1 - a0])
X = np.linalg.solve(A, b)
... |
import re
import unittest
import helpers as h
class Md2htmlTemplateIntegralTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.OUTPUT_DIR = h.prepare_output_directory(cls.__name__)
def test_empty_title(self):
root = h.execute_simple(f'{h.INPUT_DIR}/any_content.tx... |
#!/usr/bin/env python
from __future__ import print_function
from __future__ import unicode_literals
try:
from unittest import mock
except ImportError:
import mock
import pytest
from tdclient import api
from tdclient.test.test_helper import *
def setup_function(function):
unset_environ()
def test_grant_... |
from gazette.spiders.base.fecam import FecamGazetteSpider
class ScCorreiaPintoSpider(FecamGazetteSpider):
name = "sc_correia_pinto"
FECAM_QUERY = "cod_entidade:77"
TERRITORY_ID = "4204558"
|
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础计算平台 available.
Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may o... |
# Spells and abilities
import pyglet
import logging
import math
import os
import glob
# from main import logging, pyglet
from functions import *
from enemy import Enemy
from dungeon_generator import Wall, Collidable
ROOT = os.path.dirname(__file__)
ABILITY_PATH = os.path.join(ROOT, "ability_files/")
class UsableAbili... |
v1 = float(input('Qual o preço do produto? '))
print(('O preço com desconto é R${:.2f}').format(v1*0.95)) |
# -*- coding: utf-8 -*-
"""
Define a number of distributions that can be used by the sampler to draw
lensing parameters.
This module contains classes that define distributions that can be effecitvely
sampled from.
"""
import numpy as np
from scipy.stats import truncnorm
class MultivariateLogNormal():
"""Class for d... |
__________________________________________________________________________________________________
sample 32 ms submission
from functools import lru_cache
class Solution(object):
def leastOpsExpressTarget(self, x, target):
cost = list(range(40))
cost[0] = 2
@lru_cache(None)
def dp(... |
import jwt
import datetime
from django.conf import settings
from rest_framework import authentication, exceptions
from .models import User
def generate_jwt_token(username):
"""
This method generates a jwt string with username encoded in it.
:params str username: A unique name for every user in the syst... |
import numpy as np
from acnportal.acnsim.interface import InfrastructureInfo, SessionInfo
def infrastructure_constraints_feasible(
rates: np.ndarray,
infrastructure: InfrastructureInfo,
linear: bool = False,
violation_tolerance: float = 1e-5,
relative_tolerance: float = 1e-7,
) -> bool:
""" R... |
from tezos_etl import settings
from tezos_etl.session import (
setup_logging,
setup_gcs_buckets,
)
from tezos_etl.tezos_client import TezosClient
from tezos_etl.manage import (
get_last_block_number,
get_last_block_number_locally,
update_last_block_number,
update_last_block_number_locally,
i... |
import numba
import numpy as np
@numba.jit(nopython=True, parallel=True)
def plsa_numba(dt_row, dt_col, dt_val, topic_doc, term_topic, n_iter):
n_docs, n_topics = topic_doc.shape
n_terms = term_topic.shape[1]
nnz = len(dt_val)
topic_full = np.zeros((nnz, n_topics))
term_sum = np.zeros((n_topics)... |
import os
import sys
import argparse
def create_file(integrator, scene, accelerator, npixelsamples, extra_args=[]):
path = str(sys.argv[0]).split("create_base_pbrt.py")[0]
path += "../../../scenes/" + scene
if os.path.exists(path + "/" + scene + ".pbrt"):
f = open(path + "/eval_base.pbrt", "w")
... |
from .base import BaseNetwork
from .registry import registry
@registry.register('litecoin', 'LTC')
class Litecoin(BaseNetwork):
pubkey_address_prefix = 0x30
|
import base64
import six
from mongoengine import DictField, IntField, StringField, \
EmailField, BooleanField
from mongoengine.queryset import OperationError
from social_core.storage import UserMixin, AssociationMixin, NonceMixin, \
CodeMixin, PartialMixin, Base... |
# Copyright 2016 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 or agreed to in writing, ... |
# Natural Language Toolkit: Aligners
#
# Copyright (C) 2001-2011 NLTK Project
# Author:
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
"""
Classes and interfaces for aligning text.
"""
from api import *
from gale_church import *
__all__ = []
|
# incorrect solution
def get_neighbors(row_index, column_index, width, length):
neighbors = []
if row_index - 1 >= 0:
neighbors.append((row_index - 1, column_index))
if row_index + 1 < width:
neighbors.append((row_index + 1, column_index))
if column_index - 1 >= 0:
neighbors.ap... |
"""Run control side-effect handler."""
import pytest
from decoy import Decoy
from opentrons.protocol_engine.state import StateStore, PauseAction
from opentrons.protocol_engine.execution.run_control import RunControlHandler
@pytest.fixture
def state_store(decoy: Decoy) -> StateStore:
"""Get a mocked out StateStor... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.loader.processors import Join, MapCompose, TakeFirst
from w3lib.html import remove_tags
class RevistaforumItem(scrapy.Item):
site = scr... |
import os
import matplotlib.pyplot as plt
import numpy as np
from heuslertools.cristallography import Crystal
from heuslertools.cristallography.mcif_parser import MCIFParser
from heuslertools.cristallography.mcrystal import MCrystal
from heuslertools.plotting import plot_functions
from heuslertools.plotting.mpl_helper... |
import numpy as np
import os
import sys
import glob
import cv2
import scipy.io
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def read_img(img_dir, img1_name, img2_name):
# print(os.path.join(img_dir, img1_name + '.png'))
return cv2.imread(os.path.join(img_dir, img1_name + '.png')), cv2.i... |
from game.roles.villager import Villager
from game.text_template import *
class Cupid(Villager):
def __init__(self, interface, player_id, player_name):
super().__init__(interface, player_id, player_name)
self.power = 1
def get_power(self):
return self.power
def on_use_power(self):... |
import numpy as np
from numpy.random import rand
# Import the new module.
from cython_ftridiag import cytridiag as ct
# Construct arguments to pass to the function.
n=10
a, b, c, x = rand(n-1), rand(n), rand(n-1), rand(n)
# Construct a matrix A to test that the result is correct.
A = np.zeros((n,n))
A.ravel()[A.shape[... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# FileName :froms.py
# Author :zheng xingtao
# Date :2021/1/13 11:21
from django import forms
from markdownx.fields import MarkdownxFormField
from zanhu.qa.models import Question
class QuestionForm(forms.ModelForm):
"""用户提出问题的表单"""
status = forms.CharField... |
import datetime
from threading import Thread
from multiprocessing import Pipe, Process
from .utils import Packet
from .base import BaseDispatcher
class MulticoreDispatcher(BaseDispatcher):
def __init__(self, workers=1, timeout=None):
"""
Initializes a MulticoreDispatcher with a configurable number of core... |
import subprocess
from test.python.functional_tests.conftest import DATA_PATH, LocalCommandBuilder
def test_inspect_file_works(local_command: LocalCommandBuilder):
file_path = DATA_PATH / 'file_or_project' / 'file.py'
local_command.path = file_path
process = subprocess.run(
local_command.build()... |
import os
import tempfile
class Config(object):
AUTH0_AUDIENCE = "https://libcellml.org/mps/api"
AUTH0_DOMAIN = os.environ.get('MPS_AUTH0_DOMAIN')
AUTH0_SECRET = os.environ.get('MPS_AUTH0_SECRET')
CLIENT_ORIGIN_URL = os.environ.get("MPS_CLIENT_ORIGIN_URL", "http://localhost:4040")
CLIENT_WORKING_D... |
import numpy as np
import astropy.units as u
import csv
from functools import wraps
from time import time
import collections
from astropy.wcs import WCS, WCSSUB_SPECTRAL
"""
This is just an assortment of possibly useful tools that can be called
from anywhere. Mostly to keep clean.
"""
def timeit(f, *args, **kwargs):... |
#!/usr/bin/env python3
"""
The script merges calls from DeepVariant, HaplotypeCaller and Strelka2
"""
# at some point, stop using print statements to log and use an actual logging framework.
import argparse
import csv
import datetime
import re
import sys
# global variables:
# VCF structure (used instead of index nu... |
# Copyright (c) 2020, eQualit.ie inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import asyncio
import json
import traceback
from baskerville.db.dashboard_models import Message, PendingWork
from baskerville.... |
"""
T: O(N)
S: O(1)
Remember previous calls and pop the ones that have happened too long ago. The
space complexity can be considered constant since the target period is
constant.
"""
import collections
class RecentCounter:
CUT_OFF_TIME = 3000
def __init__(self):
self.pings = collections.deque()
... |
"""
Find Where to Expand in Minesweeper
Implement a function that turns revealed cells into -2 given a location the user wants to click.
For simplicity, only reveal cells that have 0 in them.
- If the user clicks on any other type of cell (for example, -1 / bomb or 1, 2, or 3), just ignore the click an... |
class A(object):
__X = 1
_<ref>_X # must resolve
|
import os
path1 = "outputs"
path2 = "outputs/_imgs"
path3 = "outputs/max_sharpe_weights"
path4 = "outputs/opt_portfolio_trades"
try:
os.mkdir(path1)
except OSError:
print ("Директория %s уже создана" % path1)
else:
print ("Успешно создана директория %s " % path1)
try:
os.makedirs(path2)
os.makedi... |
SSID="wifi_ssid_here"
WIFI_PASS="wifi_password_here"
|
from typing import List
from xinaprocessor.constants import *
import re
import emoji
import random
from collections import Counter
def replace_list(list_chars, text, replace_with=""):
chars = "".join(list_chars)
return re.sub(f"[{chars}]", replace_with, text)
def remove_extra_spaces(text: str, keep_spaces=1... |
# IDA Sync Server User Management Class
# Copyright (C) 2005 Pedram Amini <pedram.amini@gmail.com>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at... |
import pynput
from datetime import datetime
from .common import Event, EventKind
class KeyboardRecorder:
def __init__(self):
self.recordPress = True
self.recordRelease = True
self.listener = None
self.events = []
def on_press(self, key):
self.events.append(Event(datetim... |
import boto3
import datetime
import logging
import os
import pytz
events = boto3.client('events')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
TOGGLE = os.environ.get("TOGGLE", "LocalTime")
DISABLE_PUT = os.environ.get("DISABLE_PUT", "false")
def lambda_handler(event=None, context=None):
if event[... |
from librabbitmq import Connection
import argparse
import paramiko
import sys
import time
import os
import shutil
python_exe = "python"
if os.system("grep \'centos\' /etc/issue -i -q") == 0:
python_exe = "python2.7"
def get_ssh_client(ip, username=None, password=None, timeout=10):
client = None
try:
... |
from common import *
class TestBasics(TestCase):
def test_envvars(self):
self.assertTrue('aaa', run('siteconfig KEY', env={'SITECONFIG_KEY': 'aaa'}))
self.assertTrue('bbb', run('siteconfig KEY', env={'FICONFIG_KEY': 'bbb'}))
def test_example_loaded_python(self):
for name in 'A', 'B',... |
sum = 0
flag = 1
while flag == 1:
data = int(raw_input("Enter the number or press 0 to quit :"))
if data == 0:
flag =0
sum = sum+data
print "Sum is ", sum |
# Code for KiU-Net
# Author: Jeya Maria Jose
import torch
import torchvision
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.utils import save_image
from torchvision.datasets import MNIST
import torch.nn.functional as F... |
import time
import datetime
import requests
import lxml.etree as ET
class XMLReader():
""" Class to parse, preprocess and save XML/TEI
:param xml: An XML Document, either a File Path, an URL to an XML or an XML string
:type xml: str
:return: A XMLReader instance
:rtype: `xml.XMLReader`
"""... |
# Copyright (c) 2021 PaddlePaddle 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... |
#!flask/bin/python
import http.client
from urllib import request, parse, error
from flask import url_for
import base64
import traceback
import sys
from pyserver.imagedata import *
class ImageAnalysis(object):
def __init__(self, app):
self.app = app
self.apikey = self.app.config['MSVAPIKEY']
... |
"""
@author: dhoomakethu
"""
from setuptools import setup
from apocalypse import __version__
import platform
PSUTIL_ALPINE_LINUX = "4.1.0"
long_description = None
with (open('README.md')) as readme:
long_description = readme.read()
def fix_ps_util(install_requires):
for i, req in enumerate(install_requires... |
# TODO: Make deck_berry_py a package
# Placeholder for deck_berry_py |
import json
import time
#from win10toast_click import ToastNotifier
import threading
import psutil
from PyQt5 import QtCore, QtGui
#from PyQt5.uic.properties import QtCore, QtGui
from PyQt5 import QtWidgets
import sys
import encrypte
from PyQt5.QtCore import QPropertyAnimation
# GUI FILE
from AppGraphic.appQtDesigner... |
# Cookie处理
import requests
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent': user_agent}
r = requests.get('https://baidu.com', headers=headers)
# 遍历所有的Cookie字段的值
for cookie in r.cookies.keys():
print(cookie+':'+r.cookies.get(cookie))
# 如果想自定义Cookie值发出去,可以使用以下方式... |
import sys
from PIL import Image
def main():
f = open(sys.argv[1], 'rb')
data = f.read()
f.close()
use_bits = True
BYTESPERLINE = 128
BITSPERLINE = BYTESPERLINE * 8
if use_bits:
width = BITSPERLINE
height = (len(data) * 8 + BITSPERLINE - 1) / BITSPERLINE
else:
width = BYTESPERLINE
height = (len(data... |
import plotly.figure_factory as ff
import plotly.graph_objects as go
import statistics
import random
import pandas as pd
import csv
df = pd.read_csv("data.csv")
data = df["temp"].tolist()
population_mean=statistics.mean(data)
std_deviaton=statistics.stdev(data)
fig=ff.create_distplot([data],["temp"],s... |
"""
Testing aoe2record-to-json core functionality.
"""
import json
import unittest
from a2j.commands import get_commands
from tests.util import execute
class test_a2j(unittest.TestCase):
parsed = execute([
"curl",
"http://localhost:8080/a2j/v1/parse/" + "/".join(get_commands().keys()) + "/?record... |
import sys, getopt
print('Number of args:', len(sys.argv), 'arguments.')
print('Argument list :', str(sys.argv))
print()
#input("\n\nPress Enter to exit.")
# [Getopt] tuts
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv, "hi:o", ["ifile=", "ofile="])
except g... |
##########################
# Imports
##########################
import tensorflow as tf
import tensorflow.keras.backend as K
import tensorflow_addons as tfa
##########################
# Function
##########################
def _pairwise_distances(embeddings: tf.Tensor):
"""Compute the 2D matrix of distances be... |
import pathlib
from flask import request, current_app, make_response
from carp_api import endpoint, signal
from carp_api.common import logic
class Ping(endpoint.BaseEndpoint):
"""Ping to get response: "pong".
Used for health check.
"""
url = 'ping'
name = 'ping'
def action(self): # pylin... |
# -*- coding: utf-8 -*-
"""
solace.views.kb
~~~~~~~~~~~~~~~
The knowledge base views.
:copyright: (c) 2010 by the Solace Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from sqlalchemy.orm import eagerload
from werkzeug import Response, redirect
from werkzeug.e... |
# -*- coding: utf-8 -*-
#
# Copyright 2017-2020 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... |
# Copyright 2008 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 or agreed to in writing, ... |
from .scm import SCM, Variable, HiddenVariable, inverse , exp, log, negative, sqrt, square, power, sin, cos, tan, scale, add, subtract, multiply, matmul, divide, reduce_sum, reduce_prod, func
#from .math import *
import pycausal.distributions as stats
import pycausal.problems as problems
from numpy import seterr
sete... |
#!/usr/bin/env python3
"""
created: 2022-03-25 20:50:18
@author: seraph★776
contact: seraph776@gmail.com
details: Convert to camel_case
"""
import re
def split_upper(s):
s = list(filter(None, re.split("([A-Z][^A-Z]*)", s)))
return '_'.join(s).lower()
word = 'MyFunctionName'
print(split_upper(word))
|
import lab as B
from algebra import OneFunction
from . import _dispatch
from ..mean import Mean
from ..util import num_elements, uprank
__all__ = ["OneMean"]
class OneMean(Mean, OneFunction):
"""Constant mean of `1`."""
@_dispatch
def __call__(self, x: B.Numeric):
return B.ones(B.dtype(x), *B.s... |
# @Author ZhangGJ
# @Date 2020/12/24 08:04
|
from database import User
def get_user(username):
user = User.query.filter_by(username=username).first()
return f'{user}'
|
from os.path import join
import pytest
from sympy import atan, sqrt, symbols
from sympy.printing.printer import Printer
from sympy.printing.str import StrPrinter
from qalgebra.core.operator_algebra import LocalSigma
from qalgebra.core.state_algebra import BasisKet
from qalgebra.printing import (
ascii,
config... |
import bpy
import Blender
from Blender.Mathutils import *
from myFunction import *
from commandLib import *
import random
import os
#from bump_to_normal import *
#print 'meshLib'
def GetAlphaFromImage(path):
sys=Sys(path)
image = Blender.Image.Load(path)
imagedepth=image.getDepth()
imagesize = image.getSize(... |
import threading
import os,time
from django.conf.urls import url, include
from django.conf import settings
from django.conf import urls
from importlib import import_module
from . import globalVal
from .pluginListener import FileEventHandler
from watchdog.observers import Observer
from watchdog.events import *
class Pl... |
from extruder_turtle import ExtruderTurtle
import math
t = ExtruderTurtle()
t.name("horizontal-brush.gcode")
t.setup(x=200, y=100)
t.rate(700)
t.set_density(0.05)
for l in range(100):
t.forward(5)
t.right(math.pi/2)
t.forward(20)
t.right(math.pi/2)
t.forward(5)
t.right(math.pi/2)
if l%5 =... |
from sc2.ids.unit_typeid import UnitTypeId
from bot.economy import economy
from bot.opponent.strategy import Strategy
from bot.util import util
class Builder:
def __init__(self, bot):
self.bot = bot
self.logger = bot.logger
self.opponent = bot.opponent
self.army = bot.army
asy... |
from django import forms
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import gettext_lazy as _
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.core.mail import send_mail
from django.db.models import Q
fro... |
import logging
from django.contrib.auth.signals import user_logged_in, user_logged_out
from django.dispatch import receiver
# reference : https://wikidocs.net/10566
"""
@receiver 데코레이터를 이용해 sig_user_logged_in() 함수 이름으로
user_logged_in 시그널을 처리하는 함수를 만든다.
참고로 django/contrib/auth/__init__.py 파일의
login(request, user, b... |
import json
import pathlib
from http import HTTPStatus
from mock import AsyncMock, MagicMock, patch
import pytest
from tornado.httpclient import HTTPClientError
from tornado.web import HTTPError
from jupyterlab_pullrequests.managers.github import GitHubManager
HERE = pathlib.Path(__file__).parent.resolve()
def rea... |
from loginapp import app, db
if __name__ == '__main__':
db.create_all() # first we need to create table other wise HUGE ERROR. Wasted-24hr :(
app.run(debug=True, port=8000)
|
import shlex
import subprocess
from .base import PluginBase
# Examples:
# CommandLinePlugin(
# "Output to file",
# 8123,
# "touch testfile.txt",
# "rm testfile.txt",
# state_cmd = "ls testfile.txt"
# )
#
# CommandLinePlugin(
# "Output to file",
# 8123,
# "touch testfile.txt",
# "rm testfile.txt",
# ... |
import Sofa
from Compliant import Rigid, Tools, Frame
mesh_path = Tools.path( __file__ )
scale = 1
# parts of the mechanism
parts = [
["Corps","Corps.msh","1.36 0 0.0268 0 0 0 1","0 0 0 0 0 0 1","22.8 751 737", "2.1e+11","0.28","7.8e+3",1291.453/scale,"TetrahedronFEMForceField","Rigid","Vec3d","TLineModel","TP... |
# Generated by Django 3.1 on 2020-08-18 23:20
import ckeditor.fields
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Education',
... |
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import inspect
import socket
import unittest
import unittest.mock
from pants.util.socket import RecvBufferedSocket, is_readable
PATCH_OPTS = dict(autospec=True, spec_set=True)
class T... |
import logging
import re
from collections import defaultdict
from typing import Callable, TextIO
from .schemas import Score, Note, Metadata
logger = logging.getLogger(__name__)
def process_metadata(lines: list[tuple[str]]) -> Metadata:
result = {}
for line in lines:
if len(line) == 2:
key... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.