text
stringlengths
8
6.05M
# I pledge my honor that I have abided by the Stevens Honor System # Gabrielle Armetta # A function which accepts a list of numbers # and modifies the list by squaring each entry def main(): l = list() for i in range (1,11): l.append(i**2) print(l) main() # accepts list of numbers 1 through 10 #...
# Generated by Django 2.2.2 on 2019-06-07 21:46 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('mornings', '0004_city_last_update'), ] operations = [ migrations.AddField( ...
"""Functions for IAM policies in Blueprints.""" import awacs.sts from awacs.aws import Allow, Policy, Principal, Statement def assumerolepolicy(service): """Return boilerplate AWS service assume role policy document.""" return Policy( Version='2012-10-17', Statement=[ Statement( ...
import euslime from setuptools import find_packages from setuptools import setup setup( name=euslime.__name__, description=euslime.__doc__, long_description=open('README.md').read(), version=euslime.__version__, author=euslime.__author__, url='https://github.com/furushchev/euslime', licens...
# written by all, debugged by Zhiwen Wang from .neural_network import NeuralNetwork import time import sys if sys.version_info[0] == 2: from urllib import urlopen else: from urllib.request import urlopen import subprocess import numpy as np from sklearn.svm import SVR from datetime import datetime from itertool...
#!/usr/bin/env python3 # install aws-cli and enter credentials import boto3 import yaml from collections import defaultdict class AWS(): def __init__(self): self.ec2 = boto3.resource('ec2') self.ec2info = self.get_ec2info() def get_ec2info(self): ec2info = defaultdict() runn...
from spack import * import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import write_scram_toolfile class RivetToolfile(Package): url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml' version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f017615...
import subprocess import os import sys import re sys.path.insert(0, os.path.join("tools", "families")) import fam_data from run_all import RunFilter import run_all_species from run_all_species import SpeciesRunFilter datasets = [] cores = 40 if (True): datasets = [] subst_model = "GTR" datasets.append("ssim...
# Generated by Django 2.1 on 2018-12-16 00:05 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('translations', '0003_language_keys'), ] operations = [ migrations.AlterField( model_name='transla...
import unittest from katas.beta.fractions_class import Fraction class FractionTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(Fraction(1, 8) + Fraction(4, 5), Fraction(37, 40)) def test_equal_2(self): self.assertEqual(Fraction(911, 920) + Fraction(980, 906), ...
# adding a new file in the child process print("Inside child branch")
import sys import glob import os import collections model = "nbmodel.txt" output = "nboutput.txt" input_path = sys.argv[1] all_files = glob.glob(os.path.join(input_path, '*/*/*/*.txt')) # for file in all_files: # class1, class2, fold, file_name = file.split('/')[-4:] # if "positive" in class1: # clas...
#####coding=utf-8 import re import urllib.request def getHtml(url): page = urllib.request.urlopen(url) ## print(type(page.info())) ## print(page.info()) for i in range(0, 5): print(i) else: pass reg = r'charset=(\w+-\d+)\n' print(reg) imgre = re.compile(reg) imglist =...
class Animals: def vakvak(self): return self.strings['VakVakVak'] def tuylu(self): return self.strings['Tuyum_var'] def havhav(self): return self.strings['Vahvah'] def kurk(self): return self.strings['Kürk'] def meow(self): return self.strings['Meov'] cl...
""" Tests for formatter.py """ import unittest from app import formatter class TestFormatter(unittest.TestCase): """ Formatter test cases """ def setUp(self): self.fm = formatter.Formatter() self.contents = self.fm.read_file('../data/sample-Liz.in') self._entries = self.fm.g...
import time,threading balance=0 lock=threading.Lock() def change_it(n): global balance balance=balance+n balance=balance-n def run_thread(n): for i in range(10000000): try:lock.acquire() change_it(n) finally: lock.release() t1=threading.Thread...
"""DEV-54 Decouple SpacedRep from Card Revision ID: 16795b2ee0df Revises: c08bce10bc7b Create Date: 2021-03-04 23:20:03.885792 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "16795b2ee0df" down_revision = "c08bce10bc7b" branch_labels = None depends_on = None ...
## Copyright 2013 Sean McKenna ## ## 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 l...
from django.conf.urls import patterns, include, url from django.conf import settings urlpatterns = patterns('lok.views', url(r'^story/$', 'story'), url(r'^create/$', 'create_character'), url(r'^party/$', 'party'), url(r'^invite_friend/$', 'invite_friend'), url(r'^leave_party/$', 'leave_party'), url(r'^dismiss_me...
#!/usr/bin/env python # Script info at the bottom import os, time, glob, subprocess from datetime import datetime protocol = 'afp' # set your connection protocol, afp by default tm_share = 'afp://tm:pass@10.1.1.1/TimeMachine' # user:pass @ ip address /share mount_path = '/Volumes/TimeMachine' # Set your mount path f...
from ..utils.user_nested_exclude_list import USER_NESTED_FIELDS_EXCLUDES from ..extensions import marshmallow from .tag import TagSchema from .user import UserSchema from marshmallow import fields class SnippetSchema(marshmallow.Schema): class Meta: fields = ('id', 'filename', 'body', 'description', ...
import multiprocessing def test(sample, to_add): sample.append(to_add) print(f'Process {id(sample)}: {sample}') # Normally processes doesn't exchange data x = [1, 2, 3] proc1 = multiprocessing.Process(target=test, args=(x, 1)) proc2 = multiprocessing.Process(target=test, args=(x, 2)) proc1.start() proc2.sta...
import numpy def div(a, b): if b == 0: print("Warning! \n Denominator cannot be zero") return numpy.inf else: return (a/b) def add(a, b): return (a+b)
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-08-27 14:17 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True depend...
# # This file is part of LUNA. # # Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com> # SPDX-License-Identifier: BSD-3-Clause """ Header Packet data interfacing definitions.""" import operator import functools from enum import IntEnum from amaranth import * from amaranth.hdl.rec import L...
n = int(input("Please enter a four digit number: ")) already_seen = list() while n not in already_seen: already_seen.append(n) n = int(str(n * n).zfill(8)[2:6]) print(n) print('periodicity = ', len(already_seen) - already_seen.index(n))
import pygmsh from pyfr_wrapper import msh2pyfrm from pyfr_wrapper import pyfr_run from pyfr_wrapper import pyfr_export import configparser from flask import Flask, render_template, redirect, request, send_file, url_for from model import Average from werkzeug import secure_filename import os import meshio import numpy...
if key_press == 'c': sendmsg('command') if key_press == 'w': sendmsg('forward 20') elif key_press == 's': sendmsg('back 20') elif key_press == 'right': sendmsg('cw 5') elif key_press == 'left': sendmsg('ccw 5') elif key_press == 'up': sendmsg('up 20')...
## First written at local import numpy as np ## Second written at github x = [1, 2, 3, 4] ## Third written at github ## Fourth written at local y = np.log(x) ## Fifth written at github branch_0 plot(x, y) ## Sixth written at merge boxplot(x, y)
import urllib.request import json import dml import prov.model import datetime import uuid import re from alyu_sharontj_yuxiao_yzhang11.Util.Util import * class education_trans_avg(dml.Algorithm): contributor = 'alyu_sharontj_yuxiao_yzhang11' reads = ['alyu_sharontj_yuxiao_yzhang11.education', '...
import random suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'Kin...
#!/bin/python3 import math import os import random import re import sys from collections import defaultdict # start with 1-indexed array of zeros and a list of operations # [0 0 0 0 0] # input: # 5 3 // 5: length array 3: number of subsequent lines # 1 2 100 // add 100 to elements [1:2] inclussive # ...
from django.core.management.base import BaseCommand from django.utils import timezone from announcements.models import Announcement from datetime import datetime from notification.models import Notification from django.utils import timezone from push_notifications.models import GCMDevice class Command(BaseComman...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import inspect from typing import Dict, List, Optional, Tuple, Union import torch import copy from torch import nn import math import numpy as np import torch.nn.functional as F from detectron2.config import configurable from detectron2....
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division import time import os import sys import serial import argparse """ Read sensor values from an Arduino with a Piezo sensor. This script will read in values from a serial connection with the Arduino and calculate the walking speed or the nu...
import json from django.apps import apps from syncasync import sync_to_async @sync_to_async def getBookCount(book): return book.objects.all().count() async def websocket_application(scope, receive, send): Book = apps.get_model('book', 'Book') while True: event = await receive() if ev...
from rest_framework import serializers from .models import TeamMember from .utils import ChoiceField class TeamMemberSerializer(serializers.ModelSerializer): role = ChoiceField(choices=TeamMember.ROLE_CHOICES) class Meta: model = TeamMember fields = ('email', 'first_name', 'last_name', 'phone...
#coding: utf-8 from __future__ import print_function, absolute_import import logging import re import json import requests import uuid import time import os import argparse import uuid import datetime import socket import apache_beam as beam from apache_beam.io import ReadFromText from apache_beam.io import WriteToT...
# -*- coding: utf-8 -*- # @Time : 2019/11/28 15:00 # @Author : Jeff Wang # @Email : jeffwang987@163.com OR wangxiaofeng2020@ia.ac.cn # @Software: PyCharm import cv2 import numpy as np image = cv2.imread("dinosaur.jpg") cv2.imshow("Original",image) cv2.waitKey(0) (b, g, r) = image[0][0] # 颜色是tuple信息 ...
# -*- coding: utf-8 -*- """ Created on 2017/3/19 @author: will4906 """ import json from copy import deepcopy import requests from entity.QueryItem import QueryItem, DateSelect, And, ItemGroup, Or, Not if __name__ == '__main__': inventorList = [ItemGroup(And("陈思平", "董磊")), "陈昕", "汪天富", "谭力海", "彭珏", "但果", "叶继伦", ...
# I pledge my Honor that I have abided by the Stevens Honor System. # I understand that I may access the course textbook and course lecture notes # but I am not to access any other resource. I also pledge that I worked # alone on this exam. # Eshita Jain # Quiz two Part two def main(): try: n = int(input("...
# Copyright (c) 2020 Yul HR Kang. hk2699 at caa dot columbia dot edu. from collections import OrderedDict as odict from copy import deepcopy from typing import Union, Type, List, Dict, Iterable, Tuple import numpy as np import numpy_groupies as npg import torch from matplotlib import pyplot as plt from a0_dtb impor...
from .clustering import AutoencoderTSNE from .autoencoder import Autoencoder
import os import sys import string import pyspark import itertools conf = pyspark.SparkConf() sc = pyspark.SparkContext(conf=conf) datafiles_folder = sys.argv[1] stopwords_file_path = sys.argv[2] out_file_path = sys.argv[3] stopwords = [w.strip("\n") for w in open(stopwords_file_path, "r").readlines()] def remove_s...
import sys sys.path.append('..') import os import time import tensorflow as tf import numpy as np from PIL import Image from matplotlib import pyplot as plt import cv2 from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as vis_util import random import imageio import...
import importlib import argparse _parser = argparse.ArgumentParser(prog='bond') _subparsers = _parser.add_subparsers(dest='subparser_name', help='sub-command help') _parser.set_defaults(func=lambda x: None) def load_commands(COMMANDS): for COMMAND in COMMANDS: command_module = importlib.import_module(...
from environs import Env env = Env() env.read_env() BOT_TOKEN = env.str("BOT_TOKEN") IP = env.str("ip") DB_USER = env.str('DB_USER') DB_PASS = env.str('DB_PASS') DB_NAME = env.str('DB_NAME') DB_HOST = env.str('DB_HOST')
def MN_matris (n,m):#n=row and m=colums for i0 in range (1,n+1): for i1 in range (1,m+1): item=i1*i0 print(item," ",end="") print ('\n') MN_matris(4,4)
from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm from django.http import JsonResponse from django.shortcuts import render, redirect from django.views.generic.base import View from app.models import UserMoney, Transaction # Create your views here. class Home(V...
from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest, HttpResponseForbidden from django.core.urlresolvers import reverse from django.shortcuts import render from django.db.models i...
from requests import get import socket import os pubIP = get('https://api.ipify.org').text print ("Public IP is", pubIP) print (pubIP)
# JTSK-350112 # circle.py # Taiyr Begeyev # t.begeyev@jacobs-university.de """ File: circle.py Resources to manage circles """ import math class Circle(object): """Represents Circle""" def __init__(self, radius = 1.0, color = "red"): """ takes a float argument for radius and a string argu...
#!/usr/bin/python2.7 # -*- coding:utf-8 -*- ''' 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。 输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007 ''' class Solution: count = 0 def InversePairs(self, data): self.MergeSort(data) return self.count % 1000000007 def MergeSort(self, lists)...
from asm import disassemble, assemble, lex prog = [0x7c01, 0x0030, 0x7de1, 0x1000, 0x0020, 0x7803, 0x1000, 0xc00d, 0x7dc1, 0x001a, 0xa861, 0x7c01, 0x2000, 0x2161, 0x2000, 0x8463, 0x806d, 0x7dc1, 0x000d, 0x9031, 0x7c10, 0x0018, 0x7dc1, 0x001a, 0x9037, 0x61c1, 0x7dc1, 0x001a, 0x0000, 0x0000, 0x00...
#!/usr/bin/python def meme(): md = {} with open('./data/1.dat') as f: price_dict = {} for line in f.readlines(): row = line.strip().split('\t') apt_name = row[4] key = apt_name + "_" + row[5].replace(' ','') if key in md: price_dict[key].append(long(row[8].replace(' ', '').replace(',',''))) ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-01 09:34 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('application', '0003_album'), ] operations = [ migrations.RemoveField( m...
# -*- coding: utf-8 -*- import numpy as np import cv2 video_capture = cv2.VideoCapture(0) while(1): ret, image = video_capture.read() boundaries = [ ([0, 0, 128], [155, 120, 255]) ] for (lower, upper) in boundaries: lower = np.array(lower, dtype="uint8") upper = np.array(upp...
"""This module is aimed specifically at gathering experiences from FireCommanderV2 by using parallel worker-simulators to gather experiences from specific states. The goal is to obtain state-value estimates of all (or at least the most relevant) states. """ import numpy as np import multiprocessing as mp import time im...
#!/usr/bin/env python from __future__ import print_function import os.path import urlparse import urllib2 import bs4 import datetime import PyRSS2Gen import re url = "http://www.koka36.de/neu_im_vorverkauf.php" def make_external(url): return urlparse.urljoin("http://www.koka36.de", url) def main(): html ...
a, b, rest = [1, 2, 3] print(a, b, rest) s = [1, 2, 3, 4, 5, 6] i = 0 i = s[i] = 3 print(i) print(s) foo = 'anyu' foo *= 2 print(foo)
from .util.debug import dodebug from .log import logger, debug from .process import process, process_output from .errors import MooException, TException from .user_input import YesNo from .config import (Configurations, ConfigClient, lazy_configurable, Config, configurable) from tek.run import cli ...
from .project import Project, ProjectCreate, ProjectUpdate from .user import User, UserCreate, UserUpdate from .item import Item, ItemCreate, ItemDeleted, ItemUpdate
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from unittest import TestCase import nltk from nlp.pos_tagger import PosTagger class TestPosTagger(TestCase): def setUp(self): self.sentence = 'the food was amazing' self.PosTagger = PosTagger(self.sentence) def test_pos_tag(self): extr...
from __future__ import print_function import sys, os sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) # A package for reading user and password from a configuration file. import util # cpapi is a library that handles the communication with the Check Point management server. from cpapi ...
from .wrapper import cli
''' Fit plots of energy resolution vs pt for data from 2012 Vecbos ntuples run with PHOSPHOR method. 28 August 2013 Valere Lambert ''' import ROOT import JPsi.MuMu.common.roofit as roo import JPsi.MuMu.common.cmsstyle as cmsstyle import JPsi.MuMu.common.canvases as canvases from JPsi.MuMu.common.xychi2fitter import X...
input = sorted(list(map(int, open('data/10.txt').read().split('\n')))) input.append(max(input) + 3) last_num = 0 tmp = 0 possibilities = 0 dp = [0] * len(input) diff = [] for i, num in enumerate(input): diff.append(num - last_num) while tmp < i and input[tmp] < num - 3: possibilities -= dp[tmp] ...
# merge_elevation_slope_summary.py # by Ryan Spies (7/22/2014) # ryan.spies@amec.com # AMEC # Description: merges elevation and slope data from individual basin .csv files # output from ArcGIS Model Builder or automated python script: P:\NWS\GIS\Models\python\extract_basin_DEM_statistics.py #import script modu...
# JTSK-350112 # a1_p6.py # Taiyr Begeyev # t.begeyev@jacobs-university.de """ Priority queue with list """ def is_empty(pq): """ check whether the pq has no elements """ return pq == [] def insert_with_priority(pq, x, p): """ add the element x to pq with a priority p """ ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 17 11:30:28 2018 @author: Arthur """ #-------------------------------------------------------------------# # Code for Multidisciplinary Nuclear Scenarios Simulations (CMNSS) # # Version 0.1 - 12/17/18 # #...
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import os import re import signal import time from pathlib import Path from typing import List, Tuple import pytest from pants.base.build_environment import get_buildroot from pants.base...
import heapq a=[] heapq.heappush(a,1) heapq.heappush(a,3) heapq.heappush(a,2) print(a) k=heapq.heappop(a) print(k) print("a ",a) k=heapq.heappop(a) print(k) print("a ",a) k=heapq.heappop(a) print(k)
def seqlist(first,c,l): output = [first] for x in range(l-1): output.append(first+c) first += c return output ''' In this kata, you will write an arithmetic list which is basically a list that contains consecutive terms in the sequence. You will be given three parameters : first the fi...
from typing import Dict, List, Optional, Tuple, Union import torch import torchvision from torch import nn, Tensor from torchvision import ops from torchvision.transforms import functional as F, InterpolationMode, transforms as T def _flip_coco_person_keypoints(kps, width): flip_inds = [0, 2, 1, 4, 3, 6, 5, 8, 7...
from django.utils import timezone from django.utils.text import gettext_lazy as _ class Placeholder(object): name = "John" first_name = "John" last_name = "Doe" middle_name = "Samantha" fullname = "Jane Doe" phone = "+44 0000 00000" email = "mail@email.com" year = timezone.now().year ...
import string i=input("Enter the range of upper bound : ") print("\nsuper5 number which contains 5 5s together\n") for n in range(int(i)): x=5*n**5 if (str.find(str(x),'55555')!=-1): print(n,x) """ deepak@deepak-Lenovo-ideapad-320-15IKB:~/mycglab$ python3 super5.py Enter the range of upper boun...
#!/usr/bin/env python # coding:utf-8 from __future__ import absolute_import, unicode_literals from jspider.cli import cli __author__ = "golden" __date__ = '2018/6/9' if __name__ == '__main__': cli()
from unittest import TestCase from blog import manage
from appconfig.tasks import * init() @task_app_from_environment def shutdown(app): stop.execute_inner(app, maintenance_hours=None) upload_db_to_cdstar(app) @task_app_from_environment def backup_to_cdstar(app): upload_db_to_cdstar(app)
''' Created on Nov 5, 2011 @author: jason ''' import hmac import bson from bson import BSON import datetime import MongoEncoder.MongoEncoder import unicodedata import simplejson import json import urllib import tornado import tornado.auth from functools import wraps from Map.BrowseTripHandler import BaseHandler from C...
import tensorflow as tf def create_model(): model = tf.keras.models.Sequential([ tf.keras.layers.Dense(4096,kernel_initializer='normal', activation=tf.nn.relu, input_shape=(2714,)), # tf.keras.layers.Dense(4096,kernel_initializer='normal', activation=tf.nn.relu), tf.keras.layers.Dropout(0....
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import logging from typing import Iterable from pants.base.specs import Specs from pants.core.goals.fix import AbstractFixRequest, FixFilesRequest, Fix...
from django.urls import path from .views import index, newpost, post_detail, like, favorite, tags urlpatterns = [ path('', index, name='index'), path('newpost/', newpost, name='newpost',), path('<uuid:post_id>/', post_detail, name='postdetails'), path('<uuid:post_id>/like', like, name='postlikes'), path('<uuid:...
#!/user/bin/python2.7 import pandas as pd import numpy as np ################################################################################## # This class imports a data table, transform it # and apply featue extractions according to costum # periods. ###############################################################...
import pygame from bullet_alien import BulletAlienDos class TriPattern: """A pattern class for shooting boolets in a straightline of 3""" def __init__(self, main_game, shooter): self.main_game = main_game self.screen = main_game.screen self.settings = main_game.settings self.sh...
import sqlite3,os data=sqlite3.connect("kamu.db") db="kamu.db" im=data.cursor() im.execute("""CREATE TABLE IF NOT EXISTS personel( ad TEXT, soyad TEXT, maas INTEGER )""") print "(1)Veri Ekleme" print "(2)Tablo Goruntulemek icin" secim=raw_input("Lutfen bir secim yapin :") if secim=="1": ad=raw_input...
import argparse import uuid import simplejson import logging from Setup_Manager import Setup def get_queue_by_name(sqs, queue_name): queues = list(sqs.queues.filter(QueueNamePrefix=queue_name)) if len(queues) == 0: raise Exception return queues[0] def parse_arguments(): parser = argparse.Arg...
import tkinter as tk import tkinter.font as tkFont import GetImage as GM from tkinter import messagebox from tkinter.messagebox import askokcancel, showinfo, WARNING def main(root,token): root.title("User Login") width=750; height=500 screenwidth = root.winfo_screenwidth() screenheight = root.w...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 18 03:12:08 2019 @author: tboydev This program calculates the distance of the voyager from the sun from 9/25/2009 """ voyager_speed = 32241 #miles per hour current_distance = 16_637_000_000 days_travelled = int(input("Enter number of days travelled...
# 趁热打铁 class Solution: def reversePairs(self, nums: List[int]) -> int: def add(x, n): while x <= n: t[x] += 1 x += (x & (-x)) def query(x): res = 0 while x: res += t[x] x -= (x & (-x)) re...
a = [1, 2, 3, 4, 5, 6] for i in a: print(i**2)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __version__ = '1.0.1' # import os import ujson import datetime import iso8601 from sanic import Blueprint from sanic import response from sanic.log import logger from sanic.request import Request from sanic_jwt import inject_user, protected, scoped from web_backend.n...
from ._title import Title from plotly.graph_objs.pie import title from ._textfont import Textfont from ._stream import Stream from ._outsidetextfont import Outsidetextfont from ._marker import Marker from plotly.graph_objs.pie import marker from ._insidetextfont import Insidetextfont from ._hoverlabel import Hoverlabel...
""" module to create an ensight compatible file to visualize your data""" import os import h5py import numpy as np from lxml import etree NSMAP = {"xi": "http://www.w3.org/2001/XInclude"} # pylint: disable=c-extension-no-member class NpArray2Xmf(): """ main class for data output in XDMF format """...
import cv2 import dlib def eyeRatio(landmarks): # calculate eye height l_height = landmarks[40].y - landmarks[38].y r_height = landmarks[47].y - landmarks[43].y # calculate eye width l_width = landmarks[39].x - landmarks[36].x r_width = landmarks[45].x - landmarks[42].x # calculate eye ra...
import pickle from fastapi import FastAPI from pydantic import BaseModel class Person(BaseModel): Sex: int Age: float Lifeboat: int Pclass: int app = FastAPI() @app.post("/model") ## Coloque seu codigo na função abaixo def titanic(person: Person): with open("model/Titanic.pkl", "rb") as fid: ...
import maze import dfs import bfs import a import time import json max_dimensions = { "dfs" : None, "bfs" : None, "a*" : None, } search_functions = { "dfs" : dfs.dfs, "bfs" : bfs.bfs, "a*" : a.a } tries = 10 density = .3 size_increment = 100 def get_largest_dim(name): current_size = [100...
from tempfile import TemporaryFile with TemporaryFile('w+t') as f: f.write('Hello World\n') f.write('Testing\n') f.seek(0) data = f.read() print data from tempfile import NamedTemporaryFile with NamedTemporaryFile('w+t') as f: print 'filename is:', f.name with NamedTemporaryFile('w+t', dele...
# Generated by Django 2.2.13 on 2020-07-10 07:06 import ckeditor_uploader.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0046_auto_20200710_1230'), ] operations = [ migrations.RemoveField( model_name='contact...
from isolation import Board from sample_players import GreedyPlayer from sample_players import RandomPlayer from game_agent import CustomPlayer from sample_players import null_score player1 = CustomPlayer(3, null_score, True, 'minimax') player2 = GreedyPlayer() game = Board(player1, player2) game.apply_move((2, 3))...