content
stringlengths
0
894k
type
stringclasses
2 values
class Solution: def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ lenh = len(haystack) lenn = len(needle) for i in range(lenh-lenn+1): if haystack[i:i+lenn] == needle: return i ...
python
###################################################################### # controller - deals with the UI concerns # 1. navigation # 2. preparing data elements in ui way for the screens # # It will not be referring to the business domain objects # - it will use the bl component to deal with the business logic ########...
python
import requests from env import QuerybookSettings from lib.notify.base_notifier import BaseNotifier class SlackNotifier(BaseNotifier): def __init__(self, token=None): self.token = ( token if token is not None else QuerybookSettings.QUERYBOOK_SLACK_TOKEN ) @property def notifie...
python
# # Copyright 2012 eNovance <licensing@enovance.com> # Copyright 2012 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 # # Unle...
python
""" Module docstring """ from copy import deepcopy from uuid import uuid4 from os import mkdir import numpy as np from scipy.integrate import solve_ivp class OmicsGenerator: """ Handles all omics generation. This class is used to specify omics generation parameters and generate synthetic data. Typical w...
python
#!/usr/bin/python3 # -*- coding: UTF-8 -*- """ This script defines the function to do the irq related analysis """ import csv import struct from config import TSC_FREQ TSC_BEGIN = 0 TSC_END = 0 VMEXIT_ENTRY = 0x10000 LIST_EVENTS = { 'VMEXIT_EXTERNAL_INTERRUPT': VMEXIT_ENTRY + 0x00000001, } IRQ_EXITS = {} #...
python
def Widget(self): return self
python
import unittest import torch from torchdrug import data, layers class GraphSamplerTest(unittest.TestCase): def setUp(self): self.num_node = 10 self.input_dim = 5 self.output_dim = 7 adjacency = torch.rand(self.num_node, self.num_node) threshold = adjacency.flatten().kthv...
python
""" Number 1. Integer 2. Floating point 3. Octal & Hexadecimal 1) Octal a = 0o828 a = 0O828 2) Hexadecimal a = 0x828 4. Operate +, -, *, / pow : ** mod : // remainder : % Contents Source : https://wikidocs.net/12 """
python
from sys import argv script, first, second = argv print "This script is called: ", script print "The first variable is: ", first print "The second variable is: ", second
python
# Generated by Django 3.2.4 on 2021-06-15 22:49 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("rules", "0001_initial")] operations = [ migrations.CreateModel( name="Ordinance", fields=[ ...
python
from Crypto.PublicKey import RSA from Crypto import Random #This one is important since it has the default function in RSA.generate() to generate random bytes! from Crypto.Cipher import PKCS1_OAEP import base64 #I'm leaving this function so that you understand how it works from encryption => decryption def rsa_encryp...
python
# -*- coding: utf-8 -*- from model.contact import Contact from fixture.application import Application import pytest from model.contact import Contact def test_add_contact(app): app.open_home_page() app.contact.add(Contact(firstname="dsf", dlename="gdfg", lastname="ew", nickname="gdf", title="wer", company="d...
python
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
python
from django.db import models from cloudinary.models import CloudinaryField class Image(models.Model): short_title = models.CharField(max_length=20) file = CloudinaryField('image', default="https://cdn.pixabay.com/photo/2016/06/16/03/49/befall-the-earth-quote-1460570_960_720.jpg") timeStamp = models.DateT...
python
def zigzag(n): '''zigzag rows''' def compare(xy): x, y = xy return (x + y, -y if (x + y) % 2 else y) xs = range(n) return {index: n for n, index in enumerate(sorted( ((x, y) for x in xs for y in xs), key=compare ))} def printzz(myarray): '''show zigzag rows as l...
python
import unittest import requests import time from vaurienclient import Client from vaurien.util import start_proxy, stop_proxy from vaurien.tests.support import start_simplehttp_server _PROXY = 'http://localhost:8000' # we should provide a way to set an option # for all behaviors at once # _OPTIONS = ['--behavior-d...
python
import os import unittest2 as unittest import json import sys from sendgrid import SendGridClient, Mail class TestSendGrid(unittest.TestCase): def setUp(self): self.sg = SendGridClient(os.getenv('SG_USER'), os.getenv('SG_PWD')) @unittest.skipUnless(sys.version_info < (3, 0), 'only for python2') de...
python
import os import torch from typing import Dict from catalyst.dl.fp16 import Fp16Wrap, copy_params, copy_grads from catalyst.dl.state import RunnerState from catalyst.dl.utils import UtilsFactory from catalyst.rl.registry import GRAD_CLIPPERS from .core import Callback from .utils import get_optimizer_momentum, schedul...
python
# O(N + M) time and space def sum_swap(a, b): a_sum = 0 a_s = {} b_sum = 0 b_s = {} for i, n in enumerate(a): a_sum += n a_s[n] = i for i, n in enumerate(b): b_sum += n b_s[n] = i diff = (a_sum - b_sum + 1) // 2 for i, n in enumerate(a): if n - dif...
python
from django import template register = template.Library() @register.inclusion_tag('registration/error_messages.html') def error_messages(errors): return {'errors': errors}
python
if __name__ == "__main__": user_inpu = int(input()) user_list = list(map(int, input().split())) user_list = set(user_list) n = int(input()) for _ in range(n): user_input = input().split() if user_input[0] == 'intersection_update': new_list = list(map(int, input().split())...
python
import serial, struct, traceback, sys from rhum.rhumlogging import get_logger from rhum.drivers.driver import Driver from rhum.drivers.enocean.messages.message import EnOceanMessage from rhum.drivers.enocean.messages.response.VersionMessage import VersionMessage from rhum.drivers.enocean.constants import Packe...
python
from tkinter import Frame, Label, Button, messagebox, filedialog as fd from tkinter.constants import DISABLED, E, NORMAL, RAISED, SUNKEN, X import pandas import requests from threading import Thread import json from messages import messages from utils import config from ibuki import Ibuki class TopFrame(Frame): d...
python
import os import torch, pickle from torch import nn import torch.nn.functional as F from dataloader import get_transform, get_dataset from model import get_model from utils import get_dirname_from_args # how are we going to name our checkpoint file def get_ckpt_path(args, epoch, loss): ckpt_name = get_dirname_fro...
python
import smtplib import datetime from email.mime.text import MIMEText from flask import current_app def notify(notifyType, message, all=True): # Only notify if less than 3 notifications in the past 24 hours sendNotification = True now = datetime.datetime.now() if current_app.config.get(notifyType) is Non...
python
#!/usr/bin/env python3 -u # -*- coding: utf-8 -*- # copyright: sktime developers, BSD-3-Clause License (see LICENSE file) __author__ = ["Markus Löning"] __all__ = ["test_gscv_fit", "test_rscv_fit"] import numpy as np import pytest from sklearn.base import clone from sklearn.linear_model import LinearRegression from s...
python
# Copyright 2018 Xanadu Quantum Technologies 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...
python
## @file test_git_dependency.py # Unit test suite for the GitDependency class. # ## # Copyright (c) Microsoft Corporation # # SPDX-License-Identifier: BSD-2-Clause-Patent ## import unittest from edk2toolext.environment import var_dict class TestVarDict(unittest.TestCase): def setUp(self): pass def te...
python
import os from os import listdir from os.path import isfile, join import cv2 import numpy as np number = 2 mypath = "pillPictures/" + str(number) savepath = "pillPictures/saved" onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] img_count = 0 for file in onlyfiles: img_count = img_count + 1 image_...
python
import numpy as np import cv2 from mss import mss from PIL import Image # There's no native way of handling the feature of getting the window "always on top" # It's OS dependent forcing it to not be cross platform # -> this is a windows way of handling things. Marked with TODOs #import os # signals and signal handler...
python
from overrides import overrides from typing import Dict, Iterator, List, Tuple import json from functools import reduce from operator import mul import os def compute_alignment_differences(align_str: str): aligns = align_str.split(" ") align_diff = 0. for align in aligns: i, j = align.split("-") ...
python
from rockstar import RockStar css_code = """body:before { content: "Hello, world!"; }""" rock_it_bro = RockStar(days=400, file_name='helloworld.css', code=css_code) rock_it_bro.make_me_a_rockstar()
python
"""Read command line argument. Assign to _x the string value of the first command line parameter, after the program name. Source: programming-idioms.org """ # Implementation author: nickname # Created on 2016-02-18T16:58:00.600634Z # Last modified on 2016-02-18T16:58:00.600634Z # Version 1 # argv[0] is the program ...
python
# -*- coding: utf-8 -*- """ Created on Tue Mar 20 11:24:29 2018 @author: mayank """ import numpy as np #import pandas as pd #from time import time from sklearn.model_selection import StratifiedKFold #import os #from sklearn.cluster import KMeans from sklearn.utils import resample from scipy.stats import...
python
#!/usr/local/Cellar/python/2.7.6/bin/python # -*- coding: utf-8 -*- import sys import scipy.misc, scipy.io, scipy.optimize from sklearn import svm, grid_search from numpy import * import pylab from matplotlib import pyplot, cm from mpl_toolkits.mplot3d import Axes3D import matplotlib.mlab as mlaba from util import U...
python
# # Copyright 2021 Red Hat Inc. # SPDX-License-Identifier: Apache-2.0 # """Test the OCPReportProcessor.""" import datetime from unittest.mock import patch from api.utils import DateHelper from masu.database import OCP_REPORT_TABLE_MAP from masu.database.ocp_report_db_accessor import OCPReportDBAccessor from masu.datab...
python
# MQTT import sensor # Shock sensor import RPi.GPIO as GPIO class ShockSensor(sensor.Sensor): def __init__(self): super(ShockSensor, self).__init__() GPIO.setmode(GPIO.BCM) self.SHOCK_PIN = 17 GPIO.setup(self.SHOCK_PIN, GPIO.IN) def get_value(self): # The vibration sensor is 1 when no vibration is detect...
python
from comm.ntlmrelayx.servers.httprelayserver import HTTPRelayServer from impacket.examples.ntlmrelayx.servers.smbrelayserver import SMBRelayServer
python
# Generated by Django 3.1.4 on 2021-01-10 00:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('resume', '0003_auto_20210109_1855'), ] operations = [ migrations.AlterField( model_name='resumesubsection', name='su...
python
#coding=utf-8 from django import forms from common.models import PersonTelephoneNumber, TelephoneNumber from django.core import validators from django.forms.models import ModelForm from personal.models import Firefighter class PersonPhoneForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput, required=Fa...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ """ from __future__ import unicode_literals from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import range from builtins import object from threading import Thread import socket import pickle a...
python
from django.core.management.base import BaseCommand from flatblocks.models import FlatBlock from camper.pages.models import Chunk class Command(BaseCommand): help = 'Copes FlatBlock content into new Chunk objects' def handle(self, *args, **options): for fb in FlatBlock.objects.all(): t...
python
__all__ = ["configreader"]
python
import discord from discord.ext import commands class Hater(commands.Cog): def __init__(self, client): self.client = client self.client.hated_list = [] @commands.command() async def hate(self, ctx, hated): hated_id = int(hated[3:-1]) hated_member = ctx.guild.get_member...
python
# Copyright 2018 NTRlab # # 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, softw...
python
#!/usr/bin/env python """This module provides functionality to create a custom preoptimization sequence from a directed acyclic graph (DAG) using topological sorting. In the current version the DAG have to be specified manually via constants. """ import multiprocessing import random import logging import polyjit.expe...
python
from typing import overload from UdonPie import System from UdonPie import UnityEngine from UdonPie.Undefined import * class AnimatorOverrideController: def __new__(cls, arg1=None): ''' :returns: AnimatorOverrideController :rtype: UnityEngine.AnimatorOverrideController ''' ...
python
from pydantic import BaseModel, Field class DOIDoc(BaseModel): """ DOIs to reference specific materials on Materials Project. """ doi: str = Field( None, description="DOI of the material.", ) bibtex: str = Field( None, description="Bibtex reference of the material.", ) ...
python
from flask import g, jsonify, request from app import auth from app.services.base.models import User, LoginLog from app.services.base.views import bp @bp.route('/login_logs') @auth.login_required def list_login_logs(): query = LoginLog.query \ .join(User, LoginLog.userIntID == User.id) \ .with_...
python
import json import os from typing import List from stonehenge.db.operations import Operation from stonehenge.db.migrations.exceptions import UnappliedMigrationException class Migration: def __init__( self, operations: List[Operation], migrations_dir: str, ): self.operations = ...
python
""" web server 为使用者提供一个类, 使用这可以快速的搭建web服务, 展示自己的网页 """ from socket import * from select import select # 主体功能 class HTTPServer: def __init__(self,host='0.0.0.0',port=8080,dir=None): self.host = host self.port = port self.dir = dir def start(self): pass if __name__ == '__main__...
python
## HOST and PORT info HOST = "127.0.0.1" PORT = 8000 ## Server name SERVER = "Lemon Server" ## folder config STATIC = "static" RENDER = "render" ## Token info for sessions token = "SessionToken" token_length = 100 #blacklist blacklist = [] #Temp Folder TEMP = "Temp" #File extension for files that can have vari...
python
# # Copyright 2018 Dynatrace LLC # # 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...
python
#!/usr/bin/python import sys import re import os fasta_file = sys.argv[1] fasta_file_AT_only = sys.argv[2] if not os.path.exists(os.path.dirname(fasta_file_AT_only)): try: os.makedirs(os.path.dirname(fasta_file_AT_only)) except OSError as exc: # Guard against race condition if exc.errno != er...
python
""" * Vehicle Routing Problem * Steps of the algorithm: 1. Creation of a given number of clusters 2. Creation of an optimal path (loop) for each cluster Graph Optimisation : basic 2-opt algorithm Clustering : centroid-based method """ from random import * from math import sqrt import matplotlib.pyplot as plt import ne...
python
def append_new_line(file_name, text_to_append): """Append given text as a new line at the end of file""" # Open the file in append & read mode ('a+') with open(file_name, "a+") as file_object: # Move read cursor to the start of file. file_object.seek(0) # If file is not empty then ap...
python
import discord import os import requests import json import random from replit import db from keepmealive import keep_alive client = discord.Client() sad_words=["sad","depressed","unhappy","lost","angry","miserable","depressing"] starter_encouragements=[ "cheer Up! ", "You are a great Guy!" ] def ge...
python
from copy import deepcopy import numpy from theano.gof.op import PureOp from theano.gof import Apply, generic, Container from theano.gof.link import LocalLinker, map_storage, add_clear_storage from theano import function, Mode from theano.ifelse import ifelse import theano.tensor as T class IfElseIfElseIf(PureOp): ...
python
import sqlite3 def connectTab(db_name: str = 'dados.db') -> sqlite3.Connection: conexao = sqlite3.connect(f'../{db_name}') conexao.row_factory = sqlite3.Row return conexao def createTab(tab_name: str = 'pessoas'): conexao = connectTab() print(type(conexao)) with conexao: cursor =...
python
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
python
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.base.exceptions import TaskError from pants.task.lint_task_mixin import LintTaskMixin from pants.contrib.go.tasks.go_fmt_task_base import GoFmtTaskBase class GoCheckstyle(Lin...
python
import yaml import torch from torch import package import sys sys.path.append('../../') import config class Punctuation(object): def __init__(self, model_path=config.model_path_punctuation, step=config.step_punctuation): self.model_path = model_path sel...
python
#! /usr/bin/env python from __future__ import print_function from FWCore.ParameterSet.pfnInPath import pfnInPath import FWCore.ParameterSet.Config as cms import sys import os import re if os.getenv('LOCAL_TOP_DIR') == None: print("The environment variable LOCAL_TOP_DIR must be set to run this script") print("...
python
# Copyright (c) 2018, Novo Nordisk Foundation Center for Biosustainability, # Technical University of Denmark. # # 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/lic...
python
#!/usr/bin/env python3 import unittest import subprocess as sub from astropy.time import Time from bin import epics_fetch class TestEPICSFetch(unittest.TestCase): def test_known_date(self): t = Time('2020-06-07T00:00', format='isot') data = epics_fetch.get_data(['25m:mcp:cwPositions'], t.datetime,...
python
""" Customfield. Do not edit this file by hand. This is generated by parsing api.html service doc. """ from ambra_sdk.exceptions.service import AccountNotFound from ambra_sdk.exceptions.service import FilterNotFound from ambra_sdk.exceptions.service import InvalidCondition from ambra_sdk.exceptions.service import Inva...
python
from adafruit_servokit import ServoKit from dcservo import DogCamServoBase # Don't export ServoLib __all__ = ("DogCamServoAda") # Bring in global instance ServoLib = ServoKit(channels=16) class DogCamServoAda(DogCamServoBase): def __init__(self, InName, InPin, ZeroAngle=0.0, Steps=1.0, LowerBounds=0.0, UpperBounds...
python
''' code by Tae Hwan Jung(Jeff Jung) @graykode ''' import tensorflow as tf import matplotlib.pyplot as plt import numpy as np tf.reset_default_graph() # 3 Words Sentence sentences = [ "i like dog", "i like cat", "i like animal", "dog cat animal", "apple cat dog like", "dog fish milk like", ...
python
import ply.lex as lex import ply.yacc as yacc KEYWORDS = ("run", "load", "save", "insert", "clear", "quit", "exit") PARAMS = ("topology", "width", "height") DOMAINS = ("'KleinBottle'", "'MoebiusBand'", "'Torus'", "'Cylinder'", "'Plane'") class Parser: """ Base class for a lexer/parser that has the rules defin...
python
""" Images should have the shape b x c x h x w. Masks attach an alpha channel with masking values in the range [0, 1], which can be consumed by other augmentation layers. Masks themselves consume alpha channels by multiplying the old with the new. """ import math import torch import torch.fft from torch import Tensor ...
python
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. PAD_WORD_ID = 0 UNK_WORD_ID = 1 END_WORD_ID = 2 PAD_CHAR = 261 BOW_CHAR = 259 EOW_CHAR = 260
python
import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt file_1 = '/ai4efs/models/object_detection/faster_rcnn_inception_resnet_v2_atrous/train_on_ss/predictions/eccv_train_per_cat_prec_recall_data.npz' data_1 = np.load(open(file_1,'r')) file_2 = '/ai4efs/models/object_detection/fast...
python
from pathlib import Path import pytest import git import json import os from conftest import TEST_DIR from masonry import main from cookiecutter.exceptions import FailedHookException, UndefinedVariableInTemplate @pytest.fixture(scope='module') def init_simple_project(tmpdir_factory): # Setup a basic project ...
python
# standard import os # BASE DIRECTORY BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # HEARTBEAT HEARTBEAT = 10 * 1000 # INTERNET INTERNET = { 'address': '1.1.1.1', 'port': 53, 'timeout': 3, 'interval': 5 * 1000 } # MODULES MODULES = ('fb', 'synker') MODULES_DIR = 'src.modules' MODULES_CO...
python
from django.db import models # Create your models here. class douban_top250(models.Model): serial_number=models.IntegerField() movie_name=models.CharField(max_length=255) introduce=models.CharField(max_length=255) star=models.FloatField(max_length=12) evaluate=models.CharField(max_length=255) ...
python
#!/usr/bin/env python3 import os import math import sys from abc import abstractmethod import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from nets import nets_factory, resnet_utils import aardvark import cv2 from tf_utils import * import cpp flags = tf.app.flags FLAGS = flags.FLAGS fl...
python
import os import sys import yaml import json import pprint import pathlib import logging import inspect import argparse import itertools import importlib from genie.metaparser import MetaParser IGNORE_DIR = ['.git', '__pycache__', 'template', 'tests'] IGNORE_FILE = ['__init__.py', 'base.py', 'utils.py'] AVAILABLE_FUN...
python
from nltk import tokenize from operator import itemgetter import math import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize stop_words = set(stopwords.words('english')) #nltk.download('stopwords') ## 2 Declare Variables doc = '''I am from speak english with vanessa da com.You are so ...
python
#!/usr/bin/env python """Provides Generic Classes to make an image analysis. """ from abc import ABC, abstractmethod import pandas as pd class InputData(ABC): def __init__(self, data): self._content = data @abstractmethod def read(self): pass class Cohort(InputData): def __init__(...
python
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from dataclasses import dataclass, field from typing import Dict, List, Optional import torch from fairseq.dataclass import Fa...
python
def cbrt(a): s = -1 if a < 0 else 1 return s * (a*s) ** (1/3) print(cbrt(-8)) # -2.0 print(cbrt(8)) # 2.0 print(cbrt(0)) # 0.0
python
import pytest from eth_account import Account from eth_keys import KeyAPI from eth_utils import is_same_address @pytest.fixture def c(w3, get_contract): a0, a1, a2, a3, a4, a5, a6 = w3.eth.accounts[:7] with open("examples/wallet/wallet.vy") as f: code = f.read() # Sends wei to the contract for fut...
python
from django.db import models # Create your models here. class Course(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, null=False) class Slot(models.Model): MON = 1 TUE = 2 WED = 3 THU = 4 FRI = 5 DAY_CHOICES = [ (MON, 'Mon'), ...
python
import Tkinter import tkinter class TkinterImplementation(object): def begin(self, wrappedIdleImage): self.root = tkinter.Tk() self.root.overrideredirect(True) self.root.geometry( "{0}x{1}+0+0".format(self.root.winfo_screenwidth(), self.root.winfo_screenheight())) self...
python
""" Some utility functions that are only used for unittests. Placing them in test/ directory seems to be against convention, so they are part of the library. """ from __future__ import print_function, division, absolute_import import random import copy import numpy as np import six.moves as sm # unittest.mock is not...
python
"""io Core IO Modules """ import os import json import pickle ############################################################### # Common I/O operations # ====================== # def makedirs(filepath): os.makedirs(os.path.dirname(filepath), exist_ok=True) def walk(source_dir): paths = list() for root, ...
python
from django.shortcuts import render from account.models import Account from datetime import datetime def home(request): # Editing Earl of the Day ID should update all data on home page earl_of_the_day_id = 2 month = datetime.today().month upcoming_birthdays = Account.objects.filter(birthday__month=mon...
python
from pyrk.materials.material import Material from pyrk.utilities.ur import units from pyrk.density_model import DensityModel from pyrk.inp import validation class LiquidMaterial(Material): ''' subclass of material for liquid''' def __init__(self, name=None, k=0 * units.watt ...
python
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incor...
python
#!/usr/bin/env python '''Generate a series of calibration frames using POV-ray.''' from __future__ import division import sys, os, math def do_scene (x, y, z, fn): '''Generate a frame with the camera at x,y,z into fn and render it.''' f = open (fn, 'w') print >>f, '#include "calibration_target.pov"' pr...
python
from pypeflow.common import * from pypeflow.data import PypeLocalFile, makePypeLocalFile, fn from pypeflow.task import PypeTask, PypeThreadTaskBase, PypeTaskBase from pypeflow.controller import PypeWorkflow, PypeThreadWorkflow import os import uuid import sys def run_script(job_data, job_type = "SGE" ): if job_t...
python
""" ray.py defines a class of rays that can be represented in space. A ray propagates in the optical system and can be refracted, reflected or dispersed. Each instantiation is hence described by several line segments in space which are determined by their endpoints and directions. The final segment determines the curr...
python
from django.views import View from django.http import JsonResponse from django.shortcuts import render, reverse from django.contrib.auth.mixins import LoginRequiredMixin from core.models import DesignDocument, UserDocumentDownload, UserDocumentFavorite class ProfileView(LoginRequiredMixin, View): template_name = ...
python
#Use emcee as a Metropolis-Hastings so we can avoid a lot of the difficulty of the ensemble sampler for the moment. import numpy as np import emcee #create our lnprob as a multidimensional Gaussian, where icov is C^{-1} def lnprob(x, mu, icov): diff = x-mu lnp = -np.dot(diff,np.dot(icov,diff))/2.0 print(...
python
temporario = list() principal = list() maior = menor = 0 while True: temporario.append(input("Nome: ").strip().title()) temporario.append(float(input("Peso: "))) if len(principal) == 0: maior = menor = temporario[1] else: if temporario[1] > maior: maior = temporar...
python
from setuptools import setup setup(name='myslice', version='2.0.0', description='MySlice version 2', url='http://myslice.info', author='Ciro Scognamiglio', author_email='ciro.scognamiglio@lip6.fr', license='MIT', packages=['myslice'], #install_requires=[ # 'torn...
python
import logging import operator import time from functools import reduce from typing import Optional, Union, Dict, Collection, Any logger = logging.getLogger(__name__) class Configuration(object): def __init__(self, c:Optional[Union['Configuration', Dict]]=None): """Create Configuration object py...
python
""" collection of helper functions """ from __future__ import print_function, division, absolute_import import os from glob import glob from collections import defaultdict import tables from .. import NcsFile, options def check_sorted(channel_dirname): """ check how many 'sorted_...' folder there are """ ...
python
# -*- coding: utf-8 -*- import unittest from hamlish_jinja import Hamlish, Output import testing_base class TestDebugOutput(testing_base.TestCase): def setUp(self): self.hamlish = Hamlish( Output(indent_string='', newline_string='', debug=False)) def test_pre_tags(self): s...
python