text stringlengths 38 1.54M |
|---|
import json
import os
import re
import shutil
from collections import MutableSequence
from functools import total_ordering
from . import utils
from .constants import FORMATS, VALID_EXTENSIONS
from .contents import Contents
from .extract import _extract
from .parse import Parser
from .search import Searcher
from .slic... |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class LlcPPP(Base):
__slots__ = ()
_SDM_NAME = "llcPPP"
_SDM_ATT_MAP = {
"LlcPPPHheaderLlcHeader": "llcPPP.llcPPPHheader.llcHeader-1",
"LlcPPPHheaderNlpid": "llcPPP.llcPPPHheader.nlpid-2",
"LlcPPPHheade... |
import logging
import os
import numpy as np
import xrloc.map.covisible as covisible
# from solver import prior_guided_pnp
from xrprimer.data_structure import VectorDouble
from xrprimer.ops import prior_guided_pnp
from xrloc.features.extractor import Extractor
from xrloc.map.reconstruction import Reconstruction
from ... |
'''identificaremso si un numero es o no primo'''
def es_primo(x):
if x <= 1:#menor o igual a uno NO ES PRIMO
return(False)
c=0#contador
for i in range(1,x):#del 1 al x(por ejemplo 2)
if x%i==0:#si la division en el recorrido da 0 residuo e sun numero divisible
c+=1
if c>1:
return(... |
import cPickle as pickle
def read_pickle(file_path, type):
with open(file_path, type) as f:
obj = pickle.load(f)
f.close()
return obj |
#!/usr/bin/env python3
"""
Input your IISER email in format name-rollno@iiserkol.ac.in, extract the name,
roll no using split() and print them.
"""
email = input("Enter your email in the format name-rollno@iiserkol.ac.in : ")
try:
name_roll, domain = email.split("@")
name, rollno = name_roll.split("-")
pr... |
from validate import validateOn, model
from algorithm.Methods import methods
from algorithm.decomposition import nameAssemble
for gram in ('gram-1', 'gram-2','gram-3','gram-mix'):
for decomp in nameAssemble:
for method_name in methods:
validateOn(method_name, decomp, gram)
|
import os
import sys
import cv2
import panorama
import utils
if __name__ == '__main__':
ROOT_DIR = sys.argv[1]
focal_len = float(sys.argv[2])
scale = 1 if len(sys.argv) <= 3 else float(sys.argv[3])
pano = panorama.stitch_panorama(utils.load_series(ROOT_DIR, scale), focal_len)
utils.show_image(pa... |
#!/usr/bin/python
# hmmlearn.py HMM model data
# Usage:
# hmmlearn.py input_filename1
# This program reads the input file, tokenizes each input line, calculate transition and emission probability
# and write the model parameters into the file
import sys
from collections import Counter, defaultdict
from decimal import ... |
# Ceci est un commentaire !
# ces lignes ne seront pas execute
# pour le bien de ce tutoriel, python3 et non python2 sera utilise
# Aussi pour la clarte, l'avertissement E501 Line too long sera ignorer ( pour les plus avance )
# chaque lignes dans un fichier python est execute une apres l'autre
# pour execute un un ... |
from pyrosetta import *
import os
import sys
import argparse
from movemap import MOVEMAP
def exists(tag, dir):
for filename in os.listdir(dir):
if ".movemap" in filename:
if tag == filename.split(".movemap")[0]:
return True
return False
if __name__ == "__main__":
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-22 05:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('server', '0005_auto_20171022_0452'),
]
operations = [
migrations.RemoveField(
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 14 15:32:30 2017
@author: yansenxu
lesson 4 numpy
"""
#%%
import os
os.getcwd()#查看环境位置
import numpy as np#导入numpy库,简写为np
np.array #查看说明
c=np.array([[1,2,3,4],[5,6,7,8],[7,8,9,0]])
a=np.array([1,2,3,4])
b=np.array((1,2,3,4))
a.dtype
a.shape
b.shape
c.shape=4,3#修改为4行3列数组
c... |
import requests
# http status code of 200 means positive response
# Will get a ConnectionError for invalid domain
def request(url):
try:
return requests.get("http://"+url) # get simulates clicking on a link
except Exception:
pass # Do nothing
target_url = "iitk.ac.in"
with open("s... |
n=input()
ans=''
for p in range(1,n+1):
t=raw_input()
d=0
l=list(t)
while '-' in l:
i=0
o=l[0]
while l[i]==o:
i+=1
if i>len(l)-2:
break
a=l[:i]
b=l[i+1:]
a=a[::-1]
for q in range(len(a)):
... |
# Tuple is a collection which is ordered and unchanegable. Allows duplicate members
#Create tuple
fruits = ('Apples', 'Oranges', 'Grapes')
# fruits2 = tuple(('Apples', 'Oranges', 'Grapes'))
#Single value need a trailing comma
fruits2 = ('Apples',)
#Delte tuple
del fruits2
# print(len(fruits2))
# fruits[0] = 'Pea... |
from utils import fizzbuzz, check_fizzbuzz
def test_assert_true():
assert True
def test_string_len():
assert len("1") == 1
# Todo : remove it at refactor phase
# def test_can_call_fizzbuzz():
# fizzbuzz(1)
def test_returns_1_with_1_passed():
check_fizzbuzz(1, "1")
def test_returns_2_with_2_pas... |
import numpy as np
import tensorflow as tf
import setting as st
class model_def:
def __init__(self):
self.fm = 64
self.fcnode = 64
# Modules
def init_weight_bias(self, name, shape, filtercnt, trainable):
weights = tf.get_variable(name=name + "w", shape=shape,
... |
# Generated by Django 2.0 on 2018-02-06 02:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Food',
fields=[
... |
# Imports file from FIMS: Tools -> System Utilities -> Admin Utilities -> User Permissions Report.
# Parses file, writes results to a normalized, tab-delimited *.CSV file.
# Note: Import file structure: First 61 characters are the "Activity" column, remaining
# characters contain comma-separated list of user IDs.... |
from __future__ import absolute_import, division, print_function
import signal
from contextlib import contextmanager
class TimeoutError(Exception):
pass
@contextmanager
def timeout(seconds):
def signal_handler(signum, frame):
raise TimeoutError("Timed out!")
if seconds > 0:
signal.sign... |
# coding: latin-1
'''
Created on 3 may. 2019
Propuesta 2 (con complicaciones adicionales explicadas en informe)
@author: Antonio Pérez Oviedo
Librerías extra:
- pygame (1.9.6): para la interfaz gráfica,en este caso para que nuestra clase herede de la
clase Sprites y así encapsular la imagen asociada a la carta en la c... |
from django.contrib import admin
# Register your models here.
from mainapp.models import Colors
admin.site.register(Colors)
|
from keras.layers import Conv2D, Input, MaxPooling2D, BatchNormalization
from keras.layers.advanced_activations import LeakyReLU
from baseModel import BaseModel
from keras.models import Model
class YoloV1Tiny(BaseModel):
def __init__(self,input_size):
# tensorflow format :(None,w,h,c)
inpu... |
#Dataframe manipulation library
import pandas as pd
#Math functions, we'll only need the sqrt function so let's import only that
from math import sqrt
import numpy as np
import matplotlib.pyplot as plt
# Step 1: Get the data
movies_df = pd.read_csv("movies.csv")
ratings_df = pd.read_csv("ratings.csv")
# These are so... |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 04 15:58:34 2017
@author: tolic
"""
import numpy as np
from sklearn.decomposition import PCA
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
iris = datasets.load_iris();
X_data = iris.data
y_data = iris.target
"""
Step 1.
"""
scaler = Stan... |
from plotutils import *
samples=[Sample('t#bar{t} spring15 powheg',ROOT.kBlue,'/nfs/dust/cms/user/kelmorab/Spring15_Base16thJuly/forTraining/ttbar/ttbar_nominal.root','') ,
Sample('t#bar{t} spring15 amcNLO',ROOT.kRed,'/nfs/dust/cms/user/kelmorab/Spring15_Base16thJuly/forLimit/ttbar/ttbar_nominal.root',''),
... |
import os
import shutil
import glob
masterdir = "/media/spl/D/MicroCT data/4th batch bone mets loading study/w0w0composite"
mvstldir = os.path.join(masterdir,"..","STL files")
if not os.path.exists(mvstldir):
os.mkdir(mvstldir)
for fd in os.listdir(masterdir):
if "week" in fd:
sampleID = f... |
from flask import Flask
from flask_sqlalchemy_core import FlaskSQLAlchemy
import os
from flask_login import LoginManager
app = Flask(__name__)
# Grabs the folder where the script runs.
basedir = os.path.abspath(os.path.dirname(__file__))
# Enable debug mode.
app.config["DEBUG"] = True
# Secret key for session mana... |
# Assignment: Checkerboard
# Write a program that prints a 'checkerboard' pattern to the console.
for i in range(4):
print ("* " * 4)
print(' *' * 4)
|
""" A standard twisted tap file for an exposed service for txbonjour"""
from zope.interface import implements, implementer
from twisted.python import log, usage
from twisted.plugin import IPlugin
from twisted.internet import reactor
from twisted.application.service import IServiceMaker, MultiService
from txbonjour im... |
from src.point import Point
class Triangle:
def __init__(self, a, b, c):
"""
:type: a: Point
:type: b: Point
:type: c: Point
"""
self.a = a
self.b = b
self.c = c
def __contains__(self, point):
"""
:type point: Point
"""
... |
from openload import OpenLoad
import csv
import random
line = ["Title","EmbedCod","Video Duration","Thumbnail","Categories","Tags"]
output = "openload_out.csv"
with open(output, 'w', newline='') as file1:
writer = csv.writer(file1, delimiter=',')
writer.writerow(line)
user_folder = input("please input folde... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2017-11-19 11:28
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import djangocms_text_ckeditor.fields
import filer.fields.image
class Migration(migrations.Migration):
dependencies = [
... |
from contextlib import contextmanager
from ctypes import CDLL, c_int, c_int32, c_double, POINTER
from warnings import warn
from . import _dll
from .error import _error_handler
_dll.openmc_calculate_volumes.restype = None
_dll.openmc_finalize.restype = None
_dll.openmc_find.argtypes = [POINTER(c_double*3), c_int, POI... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@file: JosnUtil.py
@time: 2020/5/20 23:24
@software: PyCharm
@desc: json tool
"""
import json
class JsonUtils:
def __init__(self):
pass
def json_dumps(self,data):
"""
将 Python 对象编码成 JSON 字符串
:param data:
:return:
"""... |
"""operators in python
Arithmetic operators
Assignment operators
comparison operators
logical operators
Identity operators
bitwise operators"""
"""print("Arithmetic Operators")
print("5 + 7 is", 5 + 7)
print("5 - 7 is", 5 - 7)
print("5 * 7 is", 5 * 7)
print("5 / 7 is", 5 / 7)
print("5 // 7 is", 5 // 7)
pri... |
#! usr/bin/env python3
# -*- coding: utf-8 -*-
# author: Kwinner Chen
# python: v 3.6.4
import re
import json
from lxml import etree
from urllib.parse import urljoin, urlsplit
from datetime import datetime
from downloader import page_downloader
# 该方法需要返回一个跟踪链接,和一个新闻链接可迭代对象
# 无跟踪链接返回None不作为停止信号(以免列队之后还有可用链接而被终止)
def... |
number_of_pair = 0
list_number_of_pair = []
for month in range(5):
if month == 0:
number_of_pair = 1
list_number_of_pair.append(number_of_pair)
elif month == 1:
number_of_pair = 2
list_number_of_pair.append(number_of_pair)
else:
number_of_pair = list_number_of_pair[mo... |
'''
函数:
1. 功能性, 一个函数一定有某种功能
2. 隐藏细节, 内部实现如何复杂, 不关外部调用的关系
3. 复用性
'''
num = 1.244333;
result = round(num, 2); # 保留小数点后若干位 会根据后面的数字 四舍五入
print(result) |
from machine import Pin, SPI
from micropython import const
class RN8302B():
RN8302B_RMS_IA = const(0x0B)
RN8302B_RMS_IB = const(0x0C)
RN8302B_RMS_IC = const(0x0D)
RN8302B_RMS_IN = const(0x0E)
RN8302B_REG_GSIA = const(0x16)
RN8302B_REG_GSIB = const(0x17)
RN8302B_REG_GSIC = const(0x18)
RN... |
import csv
import numpy as np
import matplotlib.pyplot as plt
import gzip
import random
import neural
def readfile(data):
with open(data,"r") as csvfile:
item = list(csv.reader(csvfile))
for i in range(len(item)):
item[i] = [float(x) for x in item[i]]
return np.array(item)
if... |
import unittest
from unittest.mock import Mock
from rescan import scanner
class TestScanner(unittest.TestCase):
"""core test cases."""
def test_mergeAreas_handle_holes(self):
colorCode = 'BLACK'
colorAreaA = Mock()
colorAreaA.getBoundingRectangle.return_value = (0, -1, 10, -... |
#%%
"Preamble for importing libraries"
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
from scipy import stats
import seaborn as sns
import matplotlib as mlib
import matplotlib.pyplot as plt
import sklearn
from sklearn.metrics import accuracy_score
from sklearn.model_selection import... |
import plotly.tools as to
import plotly.graph_objs as go
from plotly.offline import plot
from random import randint
from collections import OrderedDict
from plotly import tools
import re
from screeninfo import get_monitors
class Plot:
def __init__(self):
self.first = []
self.second = []
se... |
#from git import git_pull, git_change
from capture import Camera
#git_pull()
dl = Camera('dl', 'dl_2021_01_09')
dl.capture_image()
dl.create_json_from_images()
dl.add_json_to_js()
#git_change()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#--wxPython Imports.
import wx
from wx.lib.combotreebox import ComboTreeBox
#- wxPython Demo --------------------------------------------------------------
__wxPyOnlineDocs__ = 'https://wxpython.org/Phoenix/docs/html/wx.lib.combotreebox.html'
__wxPyDemoPanel__ = 'TestComb... |
import bs4
import os
import pandas as pd
import output
import numpy as np
from sklearn.preprocessing import MinMaxScaler
def get_source(semester) :
semester = str(semester)
path = os.getcwd() + "/" + semester + "/"
dir = os.listdir(path)
source_lst = []
dpt_lst = ["Information Engineering" , "Finance... |
import paddle
import paddle.nn as nn
import paddle.vision.transforms as T
from ppim.units import load_model
from ppim.models.vit import VisionTransformer
from ppim.models.common import add_parameter
from ppim.models.common import trunc_normal_
def get_transforms(resize, crop):
transforms = T.Compose([
T.... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-31 13:48
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('flickr', '0003_auto_20170731_0952'),
]
op... |
from sage.all import *
import ast, sys
#################################################################
#This file verifies Proposition 5.1 parts (1) and (2) of
#''A local-global principle for isogenies of composite degree''
#by Isabel Vogt
#Part (3) is verified by the computing the genus of each of the
#subgroups ... |
#!/usr/bin/python
# Gibson Vector Designer 2015, an open source project for biologists
import sys
import re
import time
import os
from Bio import SeqIO
import sqlite3 as lite
from PySide.QtCore import *
from PySide import QtGui
from PySide import QtCore
import collections
import itertools
import inputmessage
# Func... |
from threading import Thread
from rest_framework import status
from rest_framework.decorators import detail_route
from rest_framework.filters import SearchFilter
from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated
from rest_framework.response import Response
from api.apps import ApiCli
f... |
import sys, os
import numpy as np
import cv2
from sklearn.decomposition import IncrementalPCA
from sklearn.cluster import MiniBatchKMeans
import cPickle as pickle
import math
############################################
# Autor: Pascual Andres Carrasco Gomez
# Entorno: python2.7
# Descripcion: Deteccion facial
# Algor... |
import yaml, json
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
ic()
from yaml import Loader, Dumper
import pretty_errors
import sys, os
from icecream import ic
import re
from contextlib import contextmanager
class Configurator():
def __init__(self, config_path: str, au... |
# Unpacking Argument Lists...!
def arbitraryArgument(*args):
print(f"*args : {args}")
print(f"type(*args) : {type(args)}")
print(f"iterable value : ",end="")
for i in args:
print(i, end=" ")
arbitraryArgument(1, 2, 3, 4, 5)
print("\n__________________________________________")
tuple = (1, 2, ... |
from django.contrib.auth.models import AbstractUser
from django.db import models
class Languages(models.Model):
name = models.CharField(max_length=5)
def __str__(self):
return self.name
class User(AbstractUser):
is_labeler = models.BooleanField(default=False)
is_manager = models.BooleanField(d... |
# Use the file name mbox-short.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
def getConfidence(line):
di = line.find("0");
return float(line[di:]);
s = 0.0;
c = 0;
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
s += getConfidence(line);
c +... |
#!/usr/bin/python3
def common_elements(set_1, set_2):
if set_1 is None or set_2 is None:
return
nl = set()
for dat in set_1:
for dat2 in set_2:
if dat2 in dat:
nl.add(dat2)
return(nl)
|
# sequence of values, qualquer tipo, elementos da lista
list1 = [1, 2, 3, 4, 5, 6]
list2 = ['banana', 'pera', 'maca', 'uva']
list3 = ['uva', 0.1, 3, 'hello']
list4 = ['vi', 21, [17.123]]
empty_list = []
# unlike strings, lists are mutable, can be change the value of an element
print(list1[0])
list1[0] = 0
print(list1)... |
import os
from net import Net
def make_softmax_net():
params = []
layer1 = {}
layer1["batch"] = 200
layer1["name"] = "Data"
layer1["type"] = "MnistDataLayer"
layer1["bottom"] = []
layer1["top"] = ["data", "label"]
params.append(layer1)
layer2 = {}
layer2["output"] ... |
# Databricks notebook source
# MAGIC %md
# MAGIC # 01_04_Analysis_Whole_Data
# COMMAND ----------
# MAGIC %md
# MAGIC The goal of this notebook is to conduct some basic analysis on the whole dataset.<br>
# MAGIC It is based on the code from https://github.com/HansjoergW/bfh_cas_bgd_fs2020_sa/blob/master/01_04_Analysi... |
import sys
import Class.SeleniumBrowser
import Module.Algorithms
import Module.Utility
import Module.logger
import Module.getObject
import Module.CleanUp
import Module.Report
import Class.UserDefinedException
def clickOnLink(driverObject,lnkName):
Excep = Class.UserDefinedException.UserDefinedException()
succe... |
from django import forms
from models import ManPower,Employee,Project,Salary,Shift
from django.contrib.admin import widgets
SHIFT_CHOICES=(('abc','def'),('ghi','gkl'))
class ManPowerForm(forms.ModelForm):
employee=forms.ModelChoiceField(queryset=Employee.objects.all())
project=forms.ModelChoiceField(queryset=Projec... |
vel = float(input('Digite a velocidade do veiculo em km/h: '))
if vel > 80:
print('Você foi multado devido a está acima do limite de 80 km/h')
mul = (vel - 80) * 7
print('A multa vai custar R${:.2f}'.format(mul))
else:
print('Você está andando na velocidade correta') |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: GreenJedi
# @Date: 2018-01-31 12:40:10
# @Last Modified by: JJLasher
# @Last Modified time: 2018-01-31 13:12:49
from flask import render_template
from app import app
@app.route('/')
@app.route('/index')
def index():
return render_template("index.html")
|
#!/usr/bin/env python
#
# simple test of classes and gamestate
import sys
import os
import time
import unittest
from Distances import *
class Camp:
def __init__(self,x,y, owner):
self.X=x
self.Y=y
self.owner=owner
def getX(self):
return self.X
def getY(self):
... |
import socket
import threading
from debugging import print
class CommunicationThread(threading.Thread):
def __init__(self, connection, addr, shareGameData, id):
super().__init__(name="CommunicationThread to " + str(addr))
# todo : check id limit and print error
self.connection =... |
import argparse
import ast
import csv
import math
import os
import sys
from operator import add
import tqdm
from protgraph.graph_statistics import _add_lists
csv.field_size_limit(sys.maxsize)
def _check_if_file_exists(s: str):
""" checks if a file exists. If not: raise Exception """
# TODO copied from prot... |
#!/usr/bin/env python
import ROOT
import sys
import os
import glob
import re
from array import array
from math import sqrt
def process_time(rootFile):
times_tree = ROOT.TNtuple("arrival_time", "Detection Time", "time")
tf = ROOT.TFile(rootFile, "READ")
tf.ReadAll()
trees = list(tf.GetList())
for... |
# -*- coding: utf-8 -*-
"""Definition of the Exam content type.
"""
from zope.interface import implements
from Products.Archetypes import atapi
from Products.ATContentTypes.content import folder
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from eduintelligent.evaluation.utility import hide... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('coronacases.csv', sep=',')
data = data[['id','cases']]
print(data.head())
#prepare data
x = np.array(data['id']).reshape(-1,1)
y = np.array(data['cases']).reshape(-1,1)
plt.plot(y,'-m')
#plt.show()
from sklearn.preprocessing im... |
import tensorflow
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.vgg19 import VGG19
from tensorflow.keras.layers import *
from tensorflow.keras.models import Model, load_model
from tensorflow.keras import backend as K
from numpy.random import seed
from tensorflow import set_ran... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# bucketstorage.py - Waqas Bhatti (wbhatti@astro.princeton.edu) - Apr 2019
# License: MIT - see the LICENSE file for the full text.
"""This contains functions that handle AWS S3/Digital Ocean
Spaces/S3-compatible bucket operations.
"""
#############
## LOGGING ##
#######... |
# Generated by Django 2.2.5 on 2019-10-15 09:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('home', '0005_auto_20191015_0952'),
]
operations = [
migrations.AlterField(
model_name='project'... |
def swap_case(s):
name=list(s)
for i in range(0,len(s)):
if s[i].islower():
name[i]=s[i].upper()
elif s[i].isupper():
name[i]=s[i].lower()
else:
name[i]=s[i]
name = ''.join(name)
return name
if __name__ == '__main__': |
import lxml.etree
import lxml.builder
E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.doc
component = E.component
packagename = E.packagename
conponentname = E.conponentname
action = E.action
the_doc = ROOT(
DOC(component(
packagename('ch.smalltech.battery.free'),
conponentname('ch.smalltech.battery.free.HomeFre... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 14 14:08:54 2020
@author: andyb
dist, ss, phi, psi = {domain}_Y.pt
dist: tensor of size LxL containing integers from 0 to 32
ss: tensor of size 1xL containing integers from 0 to 7
phi: tensor of size 1xL containing integers from 0 to 36
psi: tensor... |
import reactor
import atom
import copy
def genEmptyMap():
return [["E" for Y in range(0,8)] for X in range(0,10)]
r = reactor.Reactor()
r.setVerbose(True)
blueArrowMap = genEmptyMap()
redArrowMap = genEmptyMap()
blueActionMap = genEmptyMap()
redActionMap = genEmptyMap()
# gen of puzzle
redArrowMap[... |
import random
import datetime
class Task:
# taskid: int
# it is the id of the taskid
# taskWeightage: int of chois 1, 2, 3
# where 1 is highWeightage, 2 is mediumWeightage and 3 is lowEighatge
# masDelay: float
# it is the maximum delay tolarable by Task
# arrivalTime: datetime
... |
# Daydream
S = "erasedream"
add_d = ['dream', 'dreamer', 'erase', 'eraser']
T = []
# Sからadd_dを確認し
# add_dに該当した場合、文字数分Sから削除する
# 文字数が減ったSについて再度 add_dに該当するか確認する。
for i in range(len(S)):
if S[-3] == add_d[i][-3]:
T.insert(0, add_d[i])
if len(S) == len(T):
print('YES')
exit()... |
i = 0
while i < 10:
print("————————————————++++++++++%d"%i)
i += 1
i = 1
num = 0
while i <= 100:
num += i
i += 1
print(f"1~100的和是: {num}")
ii = 1
jj = 1
while ii <= 7:
jj = 1
while jj <= ii:
print(f"*", end=" ")
jj += 1
print()
ii += 1
# jj = 1
# while jj <= 7:
# ... |
# while loop are used to execute an instruction until a given condition is satisfied
count = 0
while count < 3:
count = count + 1
print("Hello")
# using else statement with while loop
# count = 0
# while count < 3:
# count = count + 1
# print("Hello world")
# else:
# print("world")
#
# # break stat... |
from typing import List
from collections import Counter
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
if len(words) < 1 or len(chars) < 1:
return 0
char_dic = Counter(chars)
res = 0
for w in words:
tmp = Counter(w)
... |
import requests
from bs4 import BeautifulSoup
from src import config
from src.RentalObject import RentalObject
from src.dao import base, write_dao
def parse_main_page(str):
if str == "bostad":
session_requests = requests.session()
response = session_requests.get(config.BU_LOGIN_URL)
soup =... |
#10-3
filename = "guest_book.txt"
"""
userName = input("Please enter your full name (q to quit):\n")
with open(filename, "a") as guestFile:
while userName != 'q':
guestFile.write(f"\n{userName}")
print(f"Welcome, {userName}. Thank you for joining us.")
userName = input("Please en... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2016-12-10 19:10
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('fb', '0002_register_total'),
]
operations = [
migrations.RemoveField(
m... |
from __future__ import unicode_literals
from builtins import str as text
from .utils import concat_args, concat_commands, zpl_bool
class Command(bytes):
"""
Convenience class for generating bytes to be sent to a ZPL2 printer.
"""
ENCODING = 'cp1252'
COMMAND_TYPE_CONTROL = b'~'
COMMAND_TYPE_... |
import socket
from django.contrib import admin
from app.RecursosHumanos.models import Persona
from app.RecursosHumanos.models import PersonaTelefono
from app.RecursosHumanos.models import Trabajador
from app.RecursosHumanos.models import Area
from app.RecursosHumanos.models import Puesto
# from app.RecursosHumanos.mod... |
"""
finger_bing.py
Copyright 2006 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope that... |
import math
from qlazy import QState
def measure(phase):
qs = QState(1)
qs.h(0)
freq_list = qs.m([0], shots=100, angle=0.5, phase=phase).frq
prob = freq_list[0] / 100
print("===")
print("phase = {0:.4f} PI".format(phase))
print("[measured] prob. of up-spin = {0:.4f}".format(prob))
pri... |
"""Created on Fri Oct 30 10:07:23 2020.
@author: Guilherme Bresciani de Azevedo
"""
# TO DO
# Try to format value got from excel based on 'CELL.NumberFormat' info.
import os
import time
import sys
import tkinter as tk
from tkinter import filedialog
import logging
from PIL import ImageGrab
import win32com.client as cl... |
from flask import Blueprint, render_template, abort, current_app, request, redirect, url_for, jsonify, session
from flask.ext.misaka import Misaka
from models import *
import hashlib, json
import Routes, Config
blog = Blueprint("blog", __name__, template_folder=Config.template_folder, static_folder=Config.static... |
print(1>3>4)
# since 1 is not greater than 3 and 3 is not greater than 4 and even 1 is not greater than 4 it prints false
print(4>2>3)
#in this 4 is greater than 2 and 2 is not greater then 3 hence false
print(4>3>2)
#in this all condition are satisfied hence true |
from pathlib import Path
import random
random.seed(0)
N = 400 * 3
category_ratio = {
"food": 0.3,
"utility": 0.1,
"transport": 0.1,
"hobby": 0.2,
"socializing": 0.2,
"daily_miscellaneous": 0.1,
}
expense_ratio = {
100: 0.6,
1000: 0.3,
10000: 0.1,
}
categories = []
for k, v i... |
#!/usr/bin/env python3
"""
Author : Yukun Feng
Date : 2018/07/01
Email : yukunfg@gmail.com
Description : Misc utils
"""
import logging
import torch
import numpy as np
def get_logger(log_file=None):
"""
Logger from opennmt
"""
log_format = logging.Formatter("[%(asctime)s %(levelnam... |
from collections import defaultdict
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root
@return: all the values with the highest frequency in any order
"""
def findFr... |
import sys
#------------------------------------------------------------------------#
def load_log_file(filename, start_step):
f = open(filename)
# read lines in log file until the thermo data is reached
line = 0
for i in range(start_step-1):
f.readline()
# load in data (1000 steps is about 1 K)
data = []
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 24 18:04:25 2017
@author: Mehdi
"""
from bs4 import BeautifulSoup
import requests
import pandas as pd
import re
df1=pd.read_csv('video_dates.csv')
videoids=df1['videId']
all_video_captions=pd.DataFrame(columns=['videoid','caption','link_in_caption'])
for videoid in video... |
import argparse
import datetime
import logging
import os
from multiprocessing import Pool
import pandas as pd
from git import GitCommandError, Repo
from termcolor import colored
def git_clone(number, name, url, output_dir):
dirname = number + '_' + name
into = os.path.join(output_dir, dirname)
try:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.