text
stringlengths
38
1.54M
""" Street codes parser File: 'br63trf.stcode' """ from struct import Struct from csv import DictWriter from sys import stdin, stdout from .layouts import STREET_CODES_LAYOUT from .util import construct_layout, get_active_header, get_stdin_bytes def main(): layout = construct_layout(STREET_CODES_LAYOUT) heade...
def new_func(): onetoday = open("one-today.txt") print (onetoday.read()) onetoday.close()
import os import sqlite3 conn = sqlite3.connect('/home/parajuli/Desktop/chatbot-api/chatModel/datasets/user_log.db',check_same_thread=False) conn.row_factory = sqlite3.Row # Make a convenience function for running SQL queries def sql_query(query): cur = conn.cursor() cur.execute(query) rows = cur.fetchal...
""" tests of Variable object Variable objects are mostly tested implicitly in other tests, but good to have a few explicitly for the Variable object """ from __future__ import absolute_import, division, print_function, unicode_literals import os import netCDF4 from .utilities import get_test_file_dir from gridded i...
from django.test import TestCase from students.models import Student from students.tests.factories import StudentFactory from subjects.tests.factories import SemesterFactory, SubjectFactory from classes.tests.factories import ClassFactory class BaseModelTest(TestCase): def setUp(self): student = StudentFa...
#!/usr/bin/env python """Operate VMs on the remote ESXi server Usage: vm <args> Available commands: vm all # show all VMs vm state <labname> # show state of VMs vm <poweron|poweroff|reboot> <vmid> # operate VM, vmid can be got by running 'vm state [labname]' or 'vm all' """ __author__ = 'sanpingz (sanping.zha...
import amqplib.client_0_8 as amqp def callback(msg): for key, val in msg.properties.items(): print '%s: %s' % (key, str(val)) for key, val in msg.delivery_info.items(): print '> %s: %s' % (key, str(val)) print '' print msg.body print '-------' msg.channel.basic_ack(msg.deliver...
from optparse import make_option import os import subprocess from django.conf import settings from django.core.management.base import BaseCommand from fun.utils.context import cd # List of edx-platform/fun-apps tuples that indicate relative paths of templates to override. OVERRIDDEN_TEMPLATES = [ ( "cms/...
import pymel.core as pm import logging logging.basicConfig() logger = logging.getLogger('FbxExporterShelf:') logger.setLevel(logging.INFO) def FbxExporterInstall(): DTag = 'FbxExporter' icLab = 'FbxExp' ann = 'Click export, Double click UI' shelf = 'JAShelf' icon = 'fbxReview.png' command...
from django.urls import path app_name = "Infos" urlpatterns = [ #path("infos/", name="infos"), ]
import os import numpy as np import cv2 import socket class VideostreamImages(object): def __init__(self, host, port): self.sock = socket.socket() self.sock.bind((host, port)) self.sock.listen(0) self.conn, self.addr = self.sock.accept() self.conn = self.conn.makefile('r...
# Copyright 2016 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 by applicable law or agreed ...
import builtins, math, fractions, unittest from expressy.expression import Expression from expressy.importer import importer from expressy import value NO_SYMBOLS = {}.__getitem__ class ExpressionTest(unittest.TestCase): def assert_eval(self, s, symbols=None): self.assertEqual(Expression.parse(s)(symbols...
# Generated by Django 3.2.6 on 2021-08-29 20:54 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Application', fields=[ ...
import time import transaction from BTrees.LOBTree import LOBTree # 64-bit integer as key / value: Object from chess_server.database.models.game import Game from chess_server.database.models.user import User from chess_server.database.managers.user_manager import UserManager from chess_server.error.database_error imp...
import random import math # moves the particle # param displace: multiplier for displacement # param coord: array of starting coordinates # returns array of moved particle def move( maxDis, coord ): disX = coord[0] + maxDis*(random.random() - .5) disY = coord[1] + maxDis*(random.random() - .5) ...
''' 有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。 给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存, 所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500。 ''' class TreePrinter: def printTree(self, root): queue=[] line=[] res=[] if root == None: return res queue.append(root) nlast=last...
from selenium import webdriver import time from bs4 import BeautifulSoup from urllib.request import urlopen import pandas as pd from urllib.request import urlretrieve url = 'https://www.buscape.com.br/search?q=cerveja+heineken' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebK...
""" This is for morphological classification of galaxies by CNN, By Kenji Bekki, on 2017/11/15 """ import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras import backend as K from kera...
from core.feature_support import FeatureSupport, SupportedFeatureNumber class LightSupport(FeatureSupport): BRIGHTNESS = 1 COLOR_TEMP = 2 EFFECT = 4 FLASH = 8 COLOR = 16 TRANSITION = 32 WHITE_VALUE = 128 def __init__(self, number: SupportedFeatureNumber) -> None: super().__ini...
# -*- coding:utf-8 -*- from collections import Counter def function(filename): file = open(filename, 'r').readlines() c = Counter(file) for i in c: print(i , c[i], '\n') def getSATDNumber(): projects = open('projects', 'r').readlines() labels = open('labels', 'r').readlines() SATD = {} ALL = {} for i in r...
# Filename: simple-function-object.py def hello(who): print 'Hello', who def goodbye(who): print 'Goodbye', who funclist = [hello, goodbye] # Some time later for func in funclist: func('Hugo')
from collections import Counter import json ##fileobj = open("HSN_products.json") ##fileobj1 = open("HSN_products_2.json") fileobj = open("HSN_products_3.json") count=0 data = fileobj.read() for i in data.split(): count+=1 c = Counter(data.split()) keyValues = list(c.keys()) print("Unique words :" ,len(keyValues)) ...
import os # Detectron imports from detectron2.data import MetadataCatalog from detectron2.data.datasets import register_coco_instances # Project imports import core.datasets.metadata as metadata def setup_all_datasets(dataset_dir): """ Registers all datasets as instances from COCO Args: dataset...
def even(iterable): result = [] for val in iterable: if not val % 2: result.append(val) return result
from aiopg.sa import create_engine from sqlalchemy.schema import CreateTable, DropTable from tree.models import tree_table async def init_db(app): settings = app['conf']['db'] app['db'] = await create_engine(**settings, echo=True) async def close_db(app): app['db'].close() await app['db'].wait_clos...
# -*- coding: utf-8 -*- """ Created on Sun Sep 13 23:10:08 2020 @author: User """ from torch.utils.data import Dataset import matplotlib.pyplot as plt import scipy.io as sio import torch from torch import nn from tasnet_v2_1 import ConvTasNet from utils import sizeof_fmt import numpy as np import timeit from torch.ut...
import requests from bs4 import BeautifulSoup def get_html(url): response = requests.get(url) return response.text def get_user_agents(html): soup=BeautifulSoup(html,'lxml') user_agents=[] user_agents_Tables=soup.findAll(class_='row_name') for i in user_agents_Tables: if(i.find('a').te...
from mowgli_etl.model.kg_edge import KgEdge from mowgli_etl.model.kg_node import KgNode from mowgli_etl.loader.cskg_csv.cskg_csv_loader import CskgCsvLoader _EXPECTED_NODE_HEADER = 'id\tlabel\taliases\tpos\tdatasource\tother' _EXPECTED_EDGE_HEADER = 'subject\tpredicate\tobject\tdatasource\tweight\tother' def test_wr...
#!/usr/bin/env python3 """Unit testing class. """ import argparse def parse_cli_args(): """Define parser w/arguments. """ parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument("--mg-to-mmol", help="mg/dl to mmol/l", nargs='+', type=float) group.a...
from utils import eucledian_distance, is_in_area from ortools.linear_solver import pywraplp from genetics import genetics from DP import DPSolver def MIP(units, areas_demand, budget, radius, cpd, r): M = int(1e5) n = len(units) num_areas = len(areas_demand) solver = pywraplp.Solver.CreateSolver('SCIP'...
from sklearn.tree import DecisionTreeClassifier from sklearn import preprocessing from sklearn.model_selection import train_test_split import numpy as np import pandas as pd from sklearn.metrics import confusion_matrix import seaborn as sns from sklearn.metrics import classification_report from sklearn.metrics import a...
# -*- coding : utf-8 -*- to_metros = lambda valor : valor / 100.0 altura_pessoa = float(input("Sua altura: ")) sombra_pessoa = float(input("Comprimento da sua sombra ( em cm ): ")) sombra_predio = float(input("Qual a sombra do prédio(em metros): ")) ''' altura_pessoa -> sombra_pessoa altura_predio -> sombra_predi...
# Generated from c:\Users\16904\Desktop\Kylin\src\parse\kylin.g4 by ANTLR 4.8 from antlr4 import * if __name__ is not None and "." in __name__: from .kylinParser import kylinParser else: from kylinParser import kylinParser # This class defines a complete generic visitor for a parse tree produced by kylinParser...
import threading import serial import time import os import pyfirmata from boards import BOARDS def get_the_board(layout=BOARDS['arduino'], base_dir='/dev/', identifier='tty.usbserial',): """ Helper function to get the one and only board connected to the computer running this. It assumes a normal arduino l...
import pyrealsense2 as rs import numpy as np import cv2 import os import pickle # 사용법 : # 키보드의 s key로 카메라로 비추고 있는 사진 캡처하여 저장. # 키보드의 q key로 프로그램 종료. config = rs.config() config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30) config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30) pipeline = rs...
# Given a binary tree, flatten it to a linked list in-place. # For example, # Given # 1 # / \ # 2 5 # / \ \ # 3 4 6 # The flattened tree should look like: # 1 # \ # 2 # \ # 3 # \ # 4 # \ # 5 # \ ...
import re import logging import os import struct import time from .definitions import * from enum import IntEnum from threading import Event from .exceptions import RileyLinkError from bluepy.btle import Peripheral, Scanner, BTLEException XGATT_BATTERYSERVICE_UUID = "180f" XGATT_BATTERY_CHAR_UUID = "2a19" RILEYLINK_S...
mynumber = [1, 2, 3, 4 ,5 ,6 ,7 ,8] # continie for number in mynumber : if number == 4 : continue print(number) print('=' * 50) # break for number in mynumber : if number == 3 : break print(number) print('=' * 50) # pass for number in mynumber : if number ...
message = input(">") words = message.split(' ') emojis = { ':)' : '😊', ':(' : '☹', ':))' : '😂' } output = "" for each in words: # for a in emojis: # if each == a: Đây là cách của Huy! # each = emojis.get(a) output += emojis.get(each, each) + " " print(ou...
import os import pandas as pd import seaborn as sns def GetFilelist(subname): result = {} for root, _, files in os.walk('.', topdown=False): for name in files: if name.find(subname) != -1: result[os.path.join(root, name)] = int(name[5:7]) return result def MergeCsv(fil...
from enum import Enum class HeartbeatAction(Enum): """ Action to be performed when a threshold period has expired without a Pulse having been received. :var CancelOrders: cancel all unmatched orders. :var SuspendOrders: suspend all unmatched orders. :var SuspendPunter: suspend punter. ""...
""" Constants ========= Package-wide consistent constant definitions. """ from enum import Enum from typing import Callable, Literal, Tuple, Union ############################################################################### # ENSEMBLE PREDICTOR = 'predictor' PREDICTION_ID = 'prediction_id' PREDICTION_RESULTS = 'p...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 30 17:58:30 2021 @author: aarshil """ body { font-family: Arial; } * { box-sizing: border-box; } form.example input[type=text] { padding: 10px; font-size: 17px; border: 1px solid grey; float: left; width: 80%; background: #f1f1f1; }...
import termcolor print(termcolor.colored("hello world",color="magenta",on_color="on_blue",attrs=["blink"]))
from itertools import product import types import openpyxl from openpyxl import worksheet from openpyxl.utils import range_boundaries def patch_worksheet(): """This monkeypatches Worksheet.merge_cells to remove cell deletion bug https://bitbucket.org/openpyxl/openpyxl/issues/365/styling-merged-cells-isnt-work...
from __future__ import unicode_literals import json import re import os import subprocess from collections import OrderedDict from distutils.spawn import find_executable from functools import partial from itertools import chain from typing import Text, Iterable, Union, Dict, Set, Sequence, Any import six import yaml ...
import random my_file_names = ['doyle-27.txt', 'doyle-case-27.txt', 'alice-27.txt', 'london-call-27.txt', 'melville-billy-27.txt', 'twain-adventures-27.txt'] my_dictionary = {} class Entry: def __init__(self, the_entry_word: str): self.word = the_entry_word self.count = 1 class...
import os from twisted.internet import defer from igs_tx.utils import defer_pipe from igs_tx.utils import defer_utils from vappio_tx.utils import queue from vappio_tx.www_client import clusters as clusters_client class Error(Exception): pass class CredentialInUseError(Error): pass @defer_utils.timeIt ...
### Hi there! ### Check out Jiri's blog http://blog.hubacek.uk for more data-related stuff & check Sarka's blog not only for a post about this piece of code http://sarka.hubacek.uk/ ### Use responsibly. import os.path import sys import logging from pathlib import Path my_path = os.path.abspath(os.path.dirname(__file_...
# coding: utf-8 # In[1]: import pandas as pd # In[2]: # Importando base de dados base = pd.read_csv('census.csv') # In[3]: # Dividir entre previsores e classe previsores = base.iloc[:, 0:14].values classe = base.iloc[:, 14].values # In[4]: # Transformando atributos nominais em atributos discretos from ...
numArray = map(int, input().split()) # Get the input sum_integer = 0 # write your logic to add these 4 numbers here sum_integer = sum(numArray) print(sum_integer) # Print the sum
################################################################################# # WaterTAP Copyright (c) 2020-2023, The Regents of the University of California, # through Lawrence Berkeley National Laboratory, Oak Ridge National Laboratory, # National Renewable Energy Laboratory, and National Energy Technology # Labo...
from gen_person import gen_person from random import randint def gen_generations(population): for person in population: if person.age < 33 and person.spouse: for spouse in population: if person.spouse == spouse: person.age += 17 s...
""" Author: Shameer Sathar Description: A module of functions for easy configuration. """ import os import numpy as np import scipy.io as sio #datFileName = '/media/hpc/codes/GitLab/event_analyser/utils/python_read_data/CM_20120414_ALL_markedData.mat' #datFileName = '/media/hpc/codes/GitLab/event_analyser/uti...
import logging, coloredlogs logging.basicConfig( filename="debug.log", filemode="w", level=logging.INFO, format="%(asctime)s.%(msecs)d %(levelname)s %(module)s/%(funcName)s at %(lineno)d: %(message)s", datefmt="%H:%M:%S", ) log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) fieldstyle ...
# https://leetcode.com/problems/text-justification/ from typing import List class Solution: def fullJustify(self, words: List[str], maxWidth: int) -> List[str]: output = [] i = 0 while i < len(words): line = Solution.getNextLine(words, i, maxWidth) i += len(line) ...
import csv import codecs # def write_to_csv(datalist, header): # pass def write_data(datalist, header, file_name='data.csv'): # 指定编码为 utf-8, 避免写 csv 文件出现中文乱码 with codecs.open(file_name, 'w+', 'utf-8') as csvfile: # filednames = ['书名', '页面地址', '图片地址'] writer = csv.DictWriter(csvfile, fieldn...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import mat4py as mp import scipy as sc import signal as sg if not 'EEGdatacsv' in locals(): EEGdatacsv = pd.read_csv(r"C:\Users\Arno\OneDrive\Documents\Stage Hopital\Data\2018-02-16_09.04.05\eeg.txt",sep=';',decimal='.') #%% Reduce siz...
import numpy as np a = np.array([1, 2, 3]) b = np.array([2, 3, 4]) c = np.subtract(a,b) c = np.ndarray(shape = (2,3)) c[0] = a c[1] = b print c
""" Sudoku is a puzzle where you're given a partially-filled 9 by 9 grid with digits. The objective is to fill the grid with the constraint that every row, column, and box (3 by 3 subgrid) must contain all of the digits from 1 to 9. Implement an efficient sudoku solver """ N = 3 # denoting a 3 x 3 grid # Utility metho...
from DataClassification.FeaturePreprocessorPatient import FeaturePreprocessorPatient __author__ = 'Agnieszka' from DataClassification.FeaturePreprocessor import FeaturePreprocessor __author__ = 'Agnieszka' import gc __author__ = 'Agnieszka' import numpy as np import matplotlib.pyplot as plt from sklearn import svm...
import numpy as np import cv2 import glob import matplotlib.pyplot as plt import matplotlib.image as mpimg import pickle def abs_sobel_thresh(image, orient='x', sobel_kernel=3, thresh=(0, 255), switch_gray=True): # Calculate directional gradient # 1) Convert to grayscale if switch_gray: ...
import numpy as np import pandas as pd from sklearn import metrics from sklearn.linear_model import LogisticRegressionCV from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import GridSearchCV from sklearn.prep...
import ipaddress import pandas as pd import random import numpy as np import time # Class initiated to perform count min sketch. class CountMinSketch(): def __init__(self, delta, epsilon): self.w = int(np.ceil(2 / epsilon)) self.d = int(np.ceil(np.log(1 / delta))) self.count_array = np.ze...
class RoleMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, *view_args, **view_kargs): if request.user.is_auth...
import coip,proxy import getlink,from,proxy import id,proxy @coip "s102sy71h7101b726c71a628".\n"flb2/Bur.py"; @gitlink_from("flp2/Bur.py")
# 魔术方法 # __init__:初始化魔术方法 # 触发时机:初始化对象时触发(不是实例化触发,但是和实例化在一个操作中) # __new__: 实例化的魔术方法 # 触发时机: 在实例化对时触发 # __call__: 对象调用方法 # 触发时机: 将对象当成函数使用的时候,会默认调用此函数中内容 # __del__: delete的缩写 析构魔术方法 # 触发时机:当对象没有用(没有任何变量引用)的时候被触发 class Person: def __new__(cls, *args, **kwargs): # __new__ 向内存要空间 ---》 地址 ...
class GameBoardEntityEnum(object): Empty = " " Food = "F" SnakeHead = "H" Obstacle = "O" Collectable = "C" SnakeTail = "T"
import os from datetime import datetime import pytest from starlette.config import environ from starlette.testclient import TestClient from app.main import app from database import mongo_db_client from database.schemas import Chips from database.schemas import Drink from database.schemas import ExtraCheese from datab...
from django.http import HttpResponse from django.shortcuts import render from django.contrib.auth import authenticate, login from django.shortcuts import render_to_response from django.views import View from django.shortcuts import redirect from django.template.context import RequestContext from django.contrib.auth.dec...
from tkinter import * fen=Tk() fen.title("Question 6") fen.configure(width=100,height=100) fen.configure(background="red")
from PIL import Image,ImageOps import numpy as np from matplotlib import pyplot as plt from skimage.draw import line_aa import argparse def dira(img,imd,d):#gradient will distribute to 2 closest bin with waightage as its distance from the bin m,n=np.shape(img) p=np.zeros(d) for i in range(m): ...
import torch from torch import nn import torch.nn.functional as F from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence from core.config import cfg as config from dataset.datasets.pentathlon_dataset import UNK class ResLayer(torch.nn.Module): def __init__(self, in_dim, out_dim): super(Re...
from ibapi.client import EClient from ibapi.wrapper import EWrapper import threading import time from ibapi.contract import Contract #from ibapi.ticktype import TickTypeEnum class IBapi(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) def tickPrice(self, reqId, tickType, price, attr...
import tempfile import base64 import hashlib import datetime import zlib import six from socket import gethostname from io import BytesIO from warcio.utils import to_native_str, BUFF_SIZE from warcio.timeutils import datetime_to_iso_date from warcio.statusandheaders import StatusAndHeadersParser, StatusAndHeaders f...
from discord.ext.menus import Menu, button from discord.ext.commands import Paginator import discord import asyncio class TagMenu(Menu): def __init__(self): super().__init__(timeout=30, delete_message_after=True) self.pages = [] self.page = 0 @property def embed(self): em...
from regression_tests import * class TestBase(Test): def test_produce_expected_output(self): self.assert_c_produces_output_when_run( input='0', expected_return_code=0, expected_output=' 0 after 0 after 0 after 0 after 0 after 0 after 0 0 22 after before 0 after ' ...
import json from flask import Blueprint, request, Response from datetime import datetime, timedelta from ..repository import memory from ..use_cases.tlru_interact import TLRU_Interaction from ..serializers.cache_serialize import CacheJsonEncoder from ..use_cases import response blueprint = Blueprint('cache', __name_...
# -*- coding: utf-8 -*- from odoo import api, fields, models from odoo.exceptions import UserError class ReceiveReturnCheque(models.TransientModel): _name = "receive.return.cheque" date_return = fields.Date(string='Cheque Return Date', default=fields.Date.context_today, required=True) comment = fields.T...
import opt import numpy as np from scipy import interpolate, stats, optimize import json import pandas as pd from datetime import datetime import pandas as pd import math from itertools import permutations, combinations import matplotlib.pyplot as plt # Object of this test exercise is to use FR cashflow data, and then...
def no_continuous(s): if len(s)>0: return [s[0]]+[s[i+1] for i in range(len(s)-1) if s[i]!=s[i+1]] else: return[] a = input() print(no_continuous(a))
########################### # Tests Event creation functionality ########################### import discord from utils import wait_for_msg async def test_create_assignment_valid(testing_bot, commands_channel): async def wait(content): await wait_for_msg(testing_bot, commands_channel, content) await co...
from collections import Counter import wikipedia from textblob import TextBlob ma = wikipedia.WikipediaPage(title='Marcus Aurelius').summary def analize_sentiment(sentence): analysis = TextBlob(sentence) if analysis.sentiment.polarity > 0: return 'pos' elif analysis.sentiment.polarity == 0: ...
import csv, os, io, contextlib from botocore.client import Config from botocore.exceptions import ClientError import boto3 from datapackage_pipelines_knesset.common import utils import json import datetime def get_s3(): url, key, secret = map(os.environ.get, ["S3_ENDPOINT_URL", "AWS_ACCESS_KEY_ID", "AWS_SECRET_AC...
''' Written by Antonio Carlos L. Ortiz. Updated: 04/05/2015 Input: None Output: Same as the one in the scraper and is also used to call the database. ''' DATABASE = { 'drivername': 'postgres', 'host': 'localhost', 'port': '5432', 'username': '', 'password': '', 'database': '' } try: from .local_settings import...
# -*- coding: utf-8 -*- # Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest from verp.stock.doctype.item.test_item import make_item from verp.stock.get_item_details import get_conversion_factor from verp.stock.docty...
#!/usr/bin/env python from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.ssl_ import create_urllib3_context from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor from requests_toolbelt.adapters.fingerprint import FingerprintAdapter from hashlib import sha256 import contextli...
""" Common functions for command line interfaces """ from hypernets_processor.version import __version__ import argparse """___Authorship___""" __author__ = "Sam Hunt" __created__ = "26/3/2020" __version__ = __version__ __maintainer__ = "Sam Hunt" __email__ = "sam.hunt@npl.co.uk" __status__ = "Development" def con...
import pandas as pd import numpy as np import os import config # Contains Params import argparse import random import matplotlib.pyplot as plt def separate_and_add_noise(args): df = pd.read_csv(args.path) measurement_df = df[["ts","wx",'wy','wz','ax','ay','az']] length = 24000 p = np.zeros((3, length...
# -*- coding: utf-8 -*- # /usr/bin/env/python3 from utils.IAgeData_v1 import prepare_dataset from losses.face_losses import arcface_loss from nets.AgeNet import inference as inference_AgeNet # from nets.inception_resnet_v1 import inference as inference_AgeNet from verification import evaluate from scipy.optimize imp...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 21 17:32:19 2019 @author: mithurangajendran """ #P######################################## PATH import os os.chdir('/Users/mithurangajendran/Documents/PPE_GIT/Python') #Mithuran #os.chdir('D:/Users/Pierre/Documents/8 - Scolarite/ECE/PPE/PPE_GIT/...
import pandas as pd import numpy as np # drought is defined as a continuous period of at least 3 months where SSI_6 < 0 and hits -1 # SSI is computed as the 24-week (6mo) rolling mean of standarized lognormal streamflows def find_droughts(df): # http://stackoverflow.com/questions/24281936/delimiting-contiguous-regio...
#ex03.py #coding:utf-8 print("I will now count my chickens") print('Hens %s' %(25 + 30 / 6)) print('Roosters %s'%(100-25*3%4)) print('Now I will count the eggs') print('Is it true that 2+3 < 5-7') print(2+3 < 5-7) print("Is it less or equal? %s"%(5 <= -2))
from operator import itemgetter import nose.tools from winfarction import Session import settings wbf = Session(settings.webfaction_user, settings.webfaction_password) class StaticApp(wbf.App): name = 'tym_static' type_ = 'static' class FlaskApp(wbf.App): name = 'tym_flask' type_ =...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
import Simulation as sim import MatlabInputFileCreator as mtlbio import json import ast OCCURRENCE_OF_SIM = 15 SIMULATION_LIFE_TIME_IN_SECONDS = 86400 SF_TO_SUPER_GROUP_PERIOD_IN_SEC = {7: 3600, 8: 3600, 9: 3600, 10: 3600, 11: 3600, 12: 3600} def autorun1(): SF_TO_MAC_PAYLOAD_IN_BYTEs = {'Min': {7: 10, 8: 10, 9:...
import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) K = int(input()) S = input().strip() T = input().strip() from collections import Counter remains = [0] + [K] * 9 sc = Counter(S[:-1]) sc = {int(k):sc[k] for k in sc} tc = Counter(T[:-1]) tc = {int(k):tc[k] for k in tc} s_card = [0] + [0] * 9 t_card ...
# -*- coding: utf-8 -*- """ Created on Sun Nov 22 19:13:21 2020 @author: ANIRUDH """ """ Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-pla...
print("开始游戏!") money = 5000 print("您有",money,"个金币") import random num = random.randint(1,100) t = 0 b = money - 500 while t < 16 and b > -500: number = input("请输入您要猜的数:") number = int(number) if number > num: print("大了!") print("剩余",b,"个金币") t = t + 1 elif numbe...