text
stringlengths
38
1.54M
from pyramid.testing import DummyRequest from ptmscout.config import strings from tests.PTMScoutTestCase import IntegrationTestCase, UnitTestCase from ptmscout.views.files import compendia from mock import Mock class TestCompendiaDownloadIntegration(IntegrationTestCase): def test_compendia_list_should_fail_for_non...
import numpy as np from unittest import TestCase from ezyrb import POD, GPR, RBF, Database from ezyrb import KNeighborsRegressor, RadiusNeighborsRegressor, Linear from ezyrb import ReducedOrderModel as ROM snapshots = np.load('tests/test_datasets/p_snapshots.npy').T pred_sol_tst = np.load('tests/test_datasets/p_preds...
def qsort(l): if l==[]: return [] return qsort([x for x in l[1:] if x<l[0]]) + l[0:1] + qsort([x for x in l[1:] if x>=l[0]]) ls = [23,12,45,99,2,6,1,0] print(qsort(ls))
# -*- coding: utf-8 -*- """Tests for `adguardhome.stats`.""" import aiohttp import pytest from adguardhome import AdGuardHome from adguardhome.exceptions import AdGuardHomeError @pytest.mark.asyncio async def test_dns_queries(event_loop, aresponses): """Test requesting AdGuard Home DNS query stats.""" arespon...
import pywt cA, cD = pywt.dwt([1, 2, 3, 4], wavelet='db1') print('cA:', cA) print('cD', cD) print('done')
filename = "test.txt" file = open(filename, 'r') lines = file.readlines() wordcount = 0 for line in lines: for word in lines.split: wordcount += 1 print(wordcount)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('cms', '0003_auto_20140926_2347'), ] operations = [ migrations.CreateModel( name='PressContact', fiel...
import os import subprocess from glob import glob cur_dir = os.path.split(os.path.realpath(__file__))[0] class testTask(object): def __init__(self, lon, lat, year, targetloc): self.lon = lon self.lat = lat self.year = year self.targetloc = targetloc self.cancelflag = None...
#!/usr/bin/env python3 from ROOT import TCanvas, TFile, TH1F,TH2F,TH3F, TF1, TGraph, gROOT import os import re import glob import sys gROOT.SetBatch(True) dirName = '/sphenix/user/shulga/Work/TpcPadPlane_phi_coresoftware/coresoftware/calibrations/tpc/fillDigitalCurrentMaps/Files/' #bXs = [1508071, 3016509, 4524020, 6...
#!/usr/bin/env python # -*- coding: utf-8 -* # # File: test_lpcli.py # # Copyright (C) 2012 Hsin-Yi Chen (hychen) # Author(s): Hsin-Yi Chen (hychen) <ossug.hychen@gmail.com> # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Soft...
import unittest import os import uuid import names import random from services.topic_service import TopicService from services.user_service import UserService from dotenv import load_dotenv load_dotenv() class TestGetTopics(unittest.TestCase): LOCAL_DB_FILE = '/data//datastores/local_test.sqlite3' def setUp(s...
import pandas as pd import pygal from pygal.style import LightStyle render = pd.read_csv("op.csv") #Scatter Plot xy_chart = pygal.XY(stroke=False) xy_chart.title = 'Depth versus Magnitude where Earthquake magnitude was between 3.0 & 6.0' for index, row in render.iterrows(): xy_chart.add('', [(row["l...
#!/usr/bin/env python # encoding: utf-8 """ @author: Tmomy @time: 2018/1/10 17:26 """ from flask import request from flask_app import app from service.base.opration_record import opr_list from const import msg from util.common import build_ret @app.route("/opr/list", methods=["GET"]) def opr_search(): parameter ...
import npyscreen import curses class BoxTitleColor(npyscreen.BoxTitle): def update(self, clear=True): super(BoxTitleColor, self).update(clear=clear) HEIGHT = self.height - 1 WIDTH = self.width - 1 box_attributes = curses.A_NORMAL if self.do_colors() and not self.editing...
""" Split and join huge files """ import os import sys import math def split_list(data_list, max_size, file_size): splits = [] amount_splits = math.ceil(max_size/file_size) split_index = math.ceil(len(data_list)/amount_splits) for split in range(0, amount_splits): ...
# .. Find the maximum total from top to bottom of the triangle .. import networkx class TriangleRoutes: def __init__(self, filename): self.triangle = self.read_triangle(filename) def max_path(self): print "generating graph.." graph = self.build_graph() print "generating all s...
#SERVICE CODES services = { 'netflix': 10000000 } # GENRE CODES genre_codes = { 'action': 100000, 'anime': 200000, 'comedy': 300000, 'drama': 400000, 'horror': 500000, 'musical': 600000, 'romance': 700000, 'scifi': 800000, 'thriller': 900000 } service_genre_sizes = { 'netflix_action_size': 168, 'netflix_anime_si...
#!/usr/bin/env python _author_ = "rifatul.islam" n = int(input().strip()) arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] rev_arr = [] i = 0 while n > 0: rev_arr.append(arr[n-1]) n -= 1 for x in rev_arr: print(x, end=" ")
# Import Dependencies import pytesseract import argparse import cv2 import os import numpy as np import pandas as pd import time from pdf2image import convert_from_path from PIL import Image # Set pytesseract path on local machine pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tes...
# Generated by Django 3.0.8 on 2020-09-27 21:08 import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL)...
import pytest from thefuck.rules.omnienv_no_such_command import get_new_command, match from thefuck.types import Command @pytest.fixture def output(pyenv_cmd): return "pyenv: no such command `{}'".format(pyenv_cmd) @pytest.fixture(autouse=True) def Popen(mocker): mock = mocker.patch('thefuck.rules.omnienv_...
#!/usr/bin/env python3 import unittest from simple_match_test import SimpleMatchTest from simple_search_test import SimpleSearchTest from simple_findall_test import SimpleFindallTest from simple_sub_test import SimpleSubTest from advanced_sub_test import AdvancedSubTest if __name__ == '__main__': ...
# -*- coding: utf-8 -*- class ResponseBase(object): _allow_keys = ['result'] def __setattr__(self, key, value): if key not in self._allow_keys: return False self.__dict__[key] = value class ResponseAddTopic(ResponseBase): pass class ResponseGetTopicList(ResponseBase): ...
import json import http from backend.models import AnnotationProject, EvaluationProject,\ ProjectCategory, ProjectType from tests.fixture import init_db, test_client def create_proj_resp(test_client, project_type, name, project_category=''): if project_type.lower() == ProjectType.ANNOTATION.value.lower(): ...
import numpy as np from numpy import random class GeneticAlgorithm(object): def __init__(self, population_size, pop_turn_over=0.2, diversification=0.05, mutation_prob=0.01, seed=1): """ This is how we define a genetic algorithm, independently of its methods ...
# # @lc app=leetcode.cn id=94 lang=python # # [94] 二叉树的中序遍历 # # @lc code=start # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None import collections from typing import List class Solution(object): def ino...
import subprocess import datetime import sys import os from utils import get_files,move_files,clean_dir from make_html import make_html # Python wrapper to the check_anaTrees script when trying to run by-hand (instead of via lobster) # Alias function pjoin = os.path.join USER_DIR = os.path.expanduser('~') CMSSW_DIR...
import numpy as np import cvxopt from src.svm.utils import calculate_util MULTIPLIER = 1e-5 COEF = 0.1 class Predictor: def __init__(self, bazis, weights, vectors, labels): self.bazis = bazis self.weights = weights self.vectors = vectors self.labels = labels def predict(sel...
import socket import threading import sqlite3 from time import time_ns ''' Connection Codes: 00 <- Client Requesting Connection 01 -> Connection Successful 02 <- Request Clients 03 <-> Ready 04 <- Complete 05 <- Client 06 <- Message from Sender 07 -> Message to Receipient 08 -> Conf...
# -*- coding: utf-8 -*- import xlrd import base64 from odoo import models, fields, api, _, exceptions from odoo.exceptions import UserError import datetime class GetAllDataImport(models.TransientModel): _name = 'get.all.data.import' xls_file = fields.Binary('File') @api.multi def import_data_partner...
"""The command for archiving a vacation.""" from dataclasses import dataclass from typing import Iterable from jupiter.core.domain.features import Feature from jupiter.core.framework.base.entity_id import EntityId from jupiter.core.framework.event import EventSource from jupiter.core.framework.use_case import ( Pr...
import numpy as np import sys import torch class BouncingMNISTDataHandler(object): """Data Handler that creates Bouncing MNIST dataset on the fly.""" def __init__(self, batch_size, num_digits): self.seq_length_ = 20 self.batch_size_ = batch_size self.image_size_ = 64 self.num_d...
from rdflib import Graph from oldman import SPARQLDataStore, ClientResourceManager, parse_graph_safely from oldman.rest.controller import HTTPController from os import path import unittest schema_graph = Graph() schema_file = path.join(path.dirname(__file__), "controller-schema.ttl") schema_graph = parse_graph_safely(...
from util_interval import make_interval, lower_bound, upper_bound, print_interval from util_interval import add_interval, sub_interval, mul_interval, div_interval def interval_width(x): return (upper_bound(x) - lower_bound(x)) / 2 z1 = make_interval(2, 5) z2 = make_interval(7, 3) z3 = add_interval(z1, z2) z4 = su...
# imos 法 from sys import stdin from itertools import accumulate from operator import itemgetter readline = stdin.readline N, C = map(int, readline().split()) stc = [tuple(map(int, readline().split())) for _ in range(N)] stc.sort(key=itemgetter(2, 0)) a = [0] * (10 ** 5 + 1) pt, pc = -1, -1 for s, t, c in stc: if...
from typing import List # YET TO FIGURE OUT DFS BASED SOLUTION FOR TOPOLOGICAL SORT THAT TAKES CARE OF THE CYCLES AS WELL # class Solution: # def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: # adjlist = {i: set() for i in range(numCourses)} # for prereq in prerequ...
from django.shortcuts import render from .RemoteModel.HomeStatistics import HomeStatistics def index(request): HomeParameters=dict() HomeParameters["statistic"]=HomeStatistics() HomeParameters["Controls"]=tuple(range(30)) return render(request,"RemoteApp/main.html", context=HomeParameters) # Creat...
import requests import base64 import pytest import hashlib from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP from Crypto.Hash import SHA256 URL = 'http://localhost:8181' CREATE_URL = URL + "/v1-secrets/secrets/create" REWRAP_URL = URL + "/v1-secrets/secrets/rewrap" secret_data = { "type":...
import discord import random from discord.ext import commands rfooter = [":(", "Press F to pay respects", "RIP", "no u", "Uhh...", "this is awkward", "'aight Imma head out"] class ErrorHandler(commands.Cog): def __init__(self, bot): bot.self = bot @commands.Cog.listener() async def on_command_error(self, ...
""" In this module determines metadata of data base Also it contains declaration of Base Object for ORM objects in Application Base object contains custom methods shared by every model. Attributes: NAMING_CONVENTION (dict): naming convention for SQLAlchemy auto name generation. metadata: SQLAlchemy obje...
from collections import OrderedDict def getPlotInfo(): ''' Define all plot information: * comparisons * binning info * variables info 1. Variable information 1.1. Key synthax of the dictionary plotInfo["varInfo"]: Possible key syntax: * <var> e.g. MET, Jet_m...
# version 1.1 import numpy as np import pandas as pd import seaborn as sn import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.metrics import calinski_harabaz_score, silhouette_score,davies_bouldin_score import warnings warnings.filterwarnings('ignore') def cluster_range(X, cluste...
from abc import ABCMeta, abstractmethod from typing import List, TypeVar, Type, Dict, Union from common.database import Database # T must be a model or one of its subclasses T = TypeVar('T', bound='Model') class Model(metaclass=ABCMeta): # collection and _id will be string in the subclass collection: str ...
from django.db import models from ckeditor.fields import RichTextField # Create your models here. class IndexSectionOne(models.Model): class Meta: verbose_name_plural = 'Index Section One' title = models.CharField(max_length=250) description = RichTextField(blank=True) def __str__(self): ...
import pandas as pd import tensorflow as tf import numpy as np class LogisticClassifier: start = 0 def __init__(self, nfeatures): self.nfeatures = nfeatures def __createBatch(self,features,labels,batch_size): self.end = self.start + batch_size batch...
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt import math from heapq import * import sys import rospy from geometry_msgs.msg import Twist from nav_msgs.msg import Odometry # extra = 0 res = 1 r = 3.3 # wheels l = 28.7 clr = 15 # clearance from the boundaries extra = 22+clr dt = 1 obstacle_...
C64_TABLE = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6'...
# imports try: import tkinter as tk except ImportError: import Tkinter as tk import os, urllib.request,subprocess, sys, tkinter.filedialog as fd, moviepy.editor as mp, time, glob, re from tkinter import messagebox, Button, Entry, Label, Frame, Canvas, Listbox from pytube import YouTube from bs4 import B...
#!/usr/bin/env python3 # Hardware Probe # Copyright (c) 2020-2023, Simon Peter <probono@puredarwin.org> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must ...
from ex115.lib.interface import * def arquivoExiste(nome): # Função para verificar se o arquivo existe try: # Função interna do Python para tratamentos de erro que vai tentar fazer algo a = open(nome, 'rt') # Open tenta abrir o arquivo com o parâmteros 'rt' que é reed(r) e text(t) a.close() # ...
n = int(input()) even_matrix = [[int(x) for x in input().split(',') if int(x) % 2 == 0] for _ in range(n)] print(even_matrix)
import pyttsx3 import speech_recognition as sr import datetime import wikipedia import webbrowser import os import pywhatkit as kit machine = pyttsx3.init('sapi5') voices = machine.getProperty('voices') machine.setProperty('voice',voices[1].id) def speak(audio): machine.say(audio) machine.runA...
from django.conf import settings from django.contrib.sites.models import Site, SiteManager from django.db import models class SiteManager(SiteManager): def get_current(self): if settings.DEBUG: self.clear_cache() return super().get_current() class Site(Site): contact_email = mode...
#DAY 11 #Problem : https://www.hackerrank.com/challenges/text-alignment/problem thickness = int(input()) c = 'H' # Top Cone for i in range(thickness): print((c * i).rjust(thickness - 1) + c + (c * i).ljust(thickness - 1)) # Top Pillars for i in range(thickness + 1): print((c * thickness).center(thicknes...
from datetime import datetime, timedelta, tzinfo from dateutil.parser import parse class OneHot: def __init__(self): print("init") @staticmethod def clamp(n, smallest, largest): return max(smallest, min(n, largest)) @staticmethod def vec_from_pos(pos, value_width, wi...
import datetime from pushbullet import Pushbullet pb = Pushbullet('o.cLhE1SyrpsZYocwqDrTHUPbHGqrW8L74') # crontab # * * * * * /usr/bin/python3 /home/pi/weather/crontest.py t = str(datetime.datetime.now().time()) f = open('crontab.txt','a') wrdata = f.write(t) f.close() push = pb.push_note('Cron Update', 'Cron worked'...
import re def part_1(): input_file = open('./input','r',newline='\n') size = 1000 elf_map = [[[] for x in range(size)] for y in range(size)] for line in input_file: elems = re.split('@ |, |: |x |\n', line) offset = elems[1].split(',') sizes = elems[2].split('x') p...
# Enter your code here. Read input from STDIN. Print output to STDOUT from itertools import product print(*list(product(list(map(int,input().split())),list(map(int,input().split())))))
def split_bytes(word): return [word >> 8, word & 0xFF] def uint_to_bytevec(num, byte_count = 0): result = [] while num > 0 or byte_count > 0: result.insert(0, num & 0xFF) num = num >> 8 byte_count -= 1 return result def bytevec_to_uint(bytelist): result = 0 for byte in...
# -*- coding: utf-8 -*- """ Created on Tue Jul 14 16:07:45 2020 @author: Soham Shah """ class Solution: def uniquePaths(self, m: int, n: int) -> int: dp = [[0 for i in range(m)] for i in range(n)] for i in range(len(dp)): if i==0: dp[i] = [1 for i in range(m)] ...
import secret from bs4 import BeautifulSoup from selenium import webdriver # chromedriver 설정 driver = webdriver.Chrome('/Users/choehansol/Downloads/chromedriver') driver.implicitly_wait(3) # 네이버 로그인 페이지로 이동 driver.get('https://nid.naver.com/nidlogin.login') # id와 password 입력 driver.find_element_by_name('id').send_ke...
# SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:noway_5@47.101.140.135:3306/liar' # local db SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost:3306/liar' SQLALCHEMY_COMMIT_ON_TEARDOWN = True CSRF_ENABLED = True SECRET_KEY = 'you-will-never-guess' SQLALCHEMY_TRACK_MODIFICATIONS = False JSON_AS_...
#!/usr/bin/env python3 ## ## GOOGLE KICK START, 2020 ## ROUND H #! j = int(input()) for i in range(1, j + 1): max_l, cur_l, sword = map(int, input().split(" ")) max_l2, cur_l2, sword2 = max_l, cur_l, sword cur_t = cur_l nb_l = 0 nb_l = cur_l - sword cur_l = sword nb_l += max_l - cur_l + cur...
#!/usr/bin/python3 import asyncio import os import traceback import discord from googleapiclient import discovery from discord.ext import commands BOT_TOKEN = os.getenv('BOT_TOKEN') INIT_EXT = [ 'cogs.manage', 'cogs.debug' ] class MC_Server(commands.Bot): def __init__(self, command_prefix): # ...
#!/usr/bin/env python from geometry_msgs.msg import Twist, Vector3, Pose, Point from sensor_msgs.msg import LaserScan from neato_node.msg import Bump from visualization_msgs.msg import Marker from nav_msgs.msg import Odometry import rospy from math import sin, cos, pi from tf.transformations import euler_from_quaterni...
#-*- coding: utf-8 -*- # 수정 필요 (데이터의 개수) from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import LSTM, Dense, Dropout, BatchNormalization from keras.callbacks import EarlyStopping import pandas as pd ...
import SocketServer import logging import threading import yaml import os import time import sys import sudoku buffer_size = 2048 global total_workload total_workload = 0 SEPERATOR = ',' streamformat = "%(asctime)s %(name)s %(levelname)s: %(message)s" logging.basicConfig(level=logging.DEBUG, for...
import math import torch import numpy as np from . import functional as F class BBoxer: def __init__( self, image_size, areas, aspect_ratios, scale_ratios, backbone_strides, iou_threshold, score_threshold, nms_threshold, class_independent_nms, ignore_threshold=0.4 ): self.ignor...
# coding: utf-8 # In[39]: import sys file = open('/Users/sathish/misc/subboard_crawler/listing_all.csv') from random import randint import re import json import re import requests mapsapiurl = 'https://maps.googleapis.com/maps/api/geocode/json?address=[[origin]]' def sanitizeAddress2(address): address = ad...
# Generated by Django 2.0.2 on 2019-10-20 12:17 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('eLearning', '0007_auto_20191020_1621'), ] operations = [ migrations.AlterField( model_name='course', ...
import maya.cmds as cmds import maya.mel as mel import glTools.rig.utils import glTools.utils.channelState import glTools.utils.curve class ControlBuilder(object): def __init__(self): """ ControlBuilder Class Initializer """ # Colour Override self.overrideId = {'lf': 14, ...
# -*- coding: utf-8 -*- """ Created on Sat Jul 1 22:18:39 2017 @author: Administrator """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from collections import Counter from sklearn.cluster import DBSCAN from sklearn import metrics from sklearn.preprocessing import StandardScaler...
n = int(input()) while(n!=0): a = input().split(" ") print(int(a[0])+int(a[1])) n=n-1
#!/usr/bin/env python #all imports import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.openid import OpenID from flask.ext.mail import Mail from flask.ext.babel import Babel, lazy_gettext from config import basedir, ADMINS, MAIL_SERVER, ...
import pymysql connection = pymysql.connect(host='localhost', user='root', password='', database='teste', cursorclass=pymysql.cursors.DictCursor) cursor = connection.cursor() delete_query = "delete from...
raw_word = str(input('')) size = len(raw_word) list = [] counter = 0 for items in raw_word: if counter == 0: item = items.upper() counter = counter+1 list.insert(len(list),item) else: list.insert(len(list),items) w = '' for items in list: w = w+str(items) print(w,end='')
from typing import List from tinkoff.investments.api.base import BaseTinkoffInvestmentsAPI from tinkoff.investments.model.portfolio import ( Currencies, CurrencyPosition, Portfolio, PortfolioPosition, ) from tinkoff.investments.model.user.accounts import BrokerAccountID class PortfolioAPI(BaseTinkoff...
import json import re import os import datetime from pprint import pprint today_day = datetime.datetime.now() day_of_the_week = today_day.strftime("%A") final_feature = {} trigger_list = [] verify_list = [] def read_input(filename,day_of_the_week): try: with open(filename, 'r') as data_file: d...
from kafka import KafkaProducer import requests import json import time producer = KafkaProducer(bootstrap_servers = 'localhost:9099') cities=['London', 'Paris', 'Bern', 'Stockholm', 'Madrid', 'Vienna'] while True: for i in range(len(cities)): api_address = 'http://api.openweathermap.org/data/2.5/weather?q...
""" Ronda 1 problema 1 """ def dameRes(casoActual): palabra = casoActual posta = "" posta += palabra[0] for c in palabra[1:]: if c >= posta[0]: posta = c+posta else: posta += c return posta t = int(raw_input()) for ti in range(1, t+1): casoActual = [s ...
"""Log some information about a specific construction file""" import sys from construction import ConstructionReader def get_info(construction_file): with ConstructionReader(construction_file) as construction: print(f'Section count: {len(construction.sections)}') for i, selection in enumerate(con...
class Vector(): """ A vector tools class """ def __init__(self, values): if type(values) == list: self._initList(values) elif type(values) == int: self._initInt(values) elif type(values) == tuple: self._initTuple(values) else: ...
number = int(input('Enter number : ')) count = 0 counter = 1 while counter <= number: if number % counter ==0: count +=1 counter +=1 if count == 2: print(number, ' is a prime') else: print(number, 'is not a prime')
from django.db import models # Create your models here. class User(models.Model): name = models.CharField(max_length=45) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) #objects object # one to many relationship # owns = [Car objects] #...
my_dict = {'color':'red','value':5,'distance':16.50} for key,value in my_dict.items(): print(key) print(value) my_list = ['jimmy','reza','sohag','nayeem'] for name in my_list: print("My name is "+name) print("playing with git")
# TO DO: # -Let cpu choose a random item and make it the only correct answer. # -Instead of "Guess a word", give a hint about an item like "It's a fruit and it's red. What am I thinking about?" def GuessWork(): print("Welcome to \"Guesswork\" game.\n") GameOn = True while GameOn: wo...
import time from library import * setSqlVerbose(False) iterations = 250 def benchmarkQuery(query, *indexes): for table, index in indexes: try: # Delete index if it exists sqlQuery('ALTER TABLE ' + sqlBackticks(table) + ' DROP INDEX ' + sqlBackticks(index)) except: # Index probably didn't exist pass print...
from __future__ import division, print_function, absolute_import from gym.envs.registration import register import numpy as np from NGSIM_env import utils from NGSIM_env.envs.common.observation import observation_factory from NGSIM_env import utils from NGSIM_env.envs.common.abstract import AbstractEnv from NGSIM_env....
a = 11113 b =23 ret=a%b print('<%d>를 <%d>로 나누면 <%d>가 나머지로 남습니다.'%(a,b,ret))
class Optimizer: """Base optimizer class.""" def __init__(self, cost_function, ftol): """ Initialize base Optimizer class. Args: cost_function: one dimensional function to optimize. ftol: cost function tolerance. """ self.f_evals = 0 self.c...
# Nicholas Land / land.nicholas@outlook.com # 10/5/2018 # Plight of friction #TODO add more spells in ability selection and add them into level up function import random import json # GAME MECHANICS def welcome(mainCharList): # the reason why theres a list as the parameter is because nick is a...
from django.contrib import admin from django.urls import path from bandas import views urlpatterns = [ path("", views.HomeView.as_view(), name="home"), path("bandas/", views.IndexView.as_view(), name="index"), path("albuns/", views.AlbunsView.as_view(), name="albuns"), path("bandas/<int:pk>", views.det...
#!/usr/bin/env python import os import argparse from FileProcessing import ProcessFile def run_deamon(args): directories = validate_args(args) # Get a list of files from the input directory that need to be processed file_names = os.listdir(directories["input"]) file_paths_to_process = [os.path.joi...
""" Copyright (c) 2016-2020 Keith Sterling http://www.keithsterling.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, m...
outdir='WP_plots' import os os.system('mkdir -p '+outdir) outdir+='/' from testing import makeEffPlots_async dfudsprob='prob_isB+prob_isBB+prob_isLeptB' infile='/eos/cms/store/cmst3/group/dehep/DeepJet/Predictions/Jan/DF_FT_fullRec_reg_BN/ttbar/tree_association.txt' TWP = '>0.825' MWP = '>0.345' LWP = '>0.055' ...
import json from flask import Blueprint, render_template, request, redirect, url_for from src.models.lessons.lesson import Lesson from src.models.teachers.teacher import Teacher from src.models.attendance.attendance import Attendance __author__ = 'ahosha' lesson_blueprint = Blueprint('lessons', __name__) @lesson_...
#!/usr/bin/env python3 # Documentation: https://docs.python.org/3/library/socket.html import socket, json, sys sys.path.append("..") import socket_utils import requests HOST = "" # Empty string means to listen on all IP's on the machine, also works with IPv6. # Note "0.0.0.0" also works but only with I...
import pymel.core as pm from PyFlow.Core.Common import * from PyFlow.Core import FunctionLibraryBase from PyFlow.Core import IMPLEMENT_NODE class MayaDisplayLib(FunctionLibraryBase): def __init__(self, packageName): super(MayaDisplayLib, self).__init__(packageName) @staticmethod @IMPLEMENT_NODE(...
import FWCore.ParameterSet.Config as cms process = cms.Process("METCLEAN") process.load("FWCore.MessageService.MessageLogger_cfi") process.MessageLogger.cerr.FwkReport.reportEvery = 100 process.TFileService = cms.Service("TFileService", fileName = cms.string("metcleaningcomparison.root"), closeFileFast = cm...
class GPU_Discrete: def __init__(self): self.name = self.__name() self.temp_label = 'GPU Discrete' self.temp_row = [] def get_name(self): return self.name def get_temp_label(self): return self.temp_label def get_temperature(self): self.__temperatu...