text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
#
# Copyright (c) 2011 Polytechnic Institute of New York University
# Author: Adrian Sai-wah Tam <adrian.sw.tam@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#... |
def df1(n):
n1 = 1
n2 = 1
n3 = 1
L = []
if n <= 2:
for i in range(1,n+1):
L.append(1)
else:
L.extend([1,1])
while n > 2:
n3 = n1 + n2
n1 = n2
n2 = n3
n = n - 1
L.append(n3)
return L
ipt = input('输入正... |
# Generated by Django 3.1.3 on 2020-12-05 21:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rest_api', '0020_auto_20201206_0227'),
]
operations = [
migrations.AlterField(
model_name='tag',
name='publication',... |
from playwright.sync_api import Page
class TestCases:
def __init__(self, page: Page):
self.page = page
def check_test_exists(self, test_name: str):
return self.page.query_selector(f'css=tr >> text=\"{test_name}\"') is not None
def delete_test_by_name(self, test_name: str):
row = s... |
import matplotlib.pyplot as plt
import numpy as np
import uncertainties.unumpy as unp
import scipy.constants as con
from scipy.optimize import curve_fit
from scipy import stats
from uncertainties import ufloat
############################ SOLENOID GROSS ####################################
xG, BG = np.genfromtxt('da... |
from . mab import Bandit, SimpleBandit, GradientBandit
from . callback import Callback
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 12 14:00:59 2017
Code for degrading images - DO NOT RUN ON PPPXEE
@author: ppxee
"""
### Import required libraries ###
import matplotlib.pyplot as plt #for plotting
from astropy.io import fits #for handling fits
import numpy as np #for handling arr... |
# This is a sample script to operate a txt file.
class TxtFileOperate(object):
def __init__(self, fileName):
self.fileName = fileName
self.fp = open(fileName, 'w+')
def OpenFile(self, fileName):
self.fileName = fileName
self.fp = open(fileName, 'w+')
def Close... |
# this sign is used to write comment in your code in order to keep track of you code
#python most common version are 2 and 3
#To start with python is very easy
#the fist lesson [+,-,/,*]
#in order to write program here it litle bit different from python shell
#in order to print any word or number the word(print ... |
class Tool(object):
# 使用赋值语句定义类属性,记录所有工具对象的数量
count = 0
def __init__(self, name):
self.name = name
# 让类属性的值 +1
Tool.count += 1
# 创建工具对象
tool1 = Tool("刀")
tool2 = Tool("剑")
tool3 = Tool("钉")
# 输出工具对象的总数 类名.类属性
# print(Tool.count)
# 不推荐对象.类属性
tool3.count = 99
print("工具对象总数 %d" % ... |
import json
import sys
args = sys.argv
with open(args[1], "r") as f:
contents = json.load(f)
with open(args[2], "r") as f:
second = json.load(f)
contents["tests"].extend(second["tests"])
cleaned = {}
for m in contents['tests']:
l = cleaned.get(m['id'], [])
l.append(m)
cleaned[m['id']] = l
for k ... |
import graphics
from random import randint
STARTING_VELOCITY = 11
SHIELD_REGEN = 2.5
BASE_THRUST = 1
HEALTH_MODIFIER = 3
class Ship:
def __init__(self, h, a, s, p, t, r, n):
self.health = h * HEALTH_MODIFIER
self.max_health = self.health
self.armor = a
self.shields = s... |
import os, sys
print ("\033[1;32mlogin dulu gan,hubungi Author WA: +6285715209673")
username = 'djokers'
password = 'arsadganteng'
def restart():
ngulang = sys.executable
os.execl(ngulang, ngulang, *sys.argv)
def main():
uname = raw_input("username : ")
if uname == username:
pwd = raw_input("p... |
import os
import asyncio
from sanic import Sanic
KAFKA_BROKER_URL = os.environ.get('KAFKA_BROKER_URL')
APP = Sanic()
LOOP = asyncio.get_event_loop()
from routers import *
if __name__ == '__main__':
APP.run(host="0.0.0.0", port=5050)
|
from rest_framework.views import APIView
from .serializers import UserModelSerializer
import json
from .models import User
from django.contrib.auth import authenticate, login
from rest_framework import generics
class RegisterView(generics.CreateAPIView):
serializer_class = UserModelSerializer
queryset = User... |
# Average number of words
# Count the number of words in a sentence in text file
# Anatoli Penev
# 11.01.2018
def main():
file_name = input("Enter file name: ")
parse_file(file_name)
def avg_words(num_words, line_count):
return num_words/line_count
def parse_file(file_name):
num_wo... |
# Calculate the factorial of a number.
def Factorial(n):
# We know !1 is 1.
if n == 1:
return 1
# Because !5 is 5 * !4, we can say !n is n * !(n-1).
return n * Factorial(n-1)
|
import sys
import os
import asyncio
import string
import random
import time
import linecache
import operator
import tkinter
import datetime
# import in_place
from pubsub import Pub, Sub
from radio import Radio
from util import int2bytes, bytes2int, run
from free_port import get_free_tcp_port, get_free_t... |
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So you are %r old, %r tall and %r heavy." % (
age , height, weight)
print "input math number:"
num = int(raw_input())
print "So %r multiply is %r " % (num,num*num)
#... |
from _typeshed import Incomplete
def laplacian_spectrum(G, weight: str = "weight"): ...
def normalized_laplacian_spectrum(G, weight: str = "weight"): ...
def adjacency_spectrum(G, weight: str = "weight"): ...
def modularity_spectrum(G): ...
def bethe_hessian_spectrum(G, r: Incomplete | None = None): ...
|
import sys, random
menu = [['칼국수',6000],['비빔밥',5500],
['돼지국밥',7000],['돈까스',7000],['김밥',2000],['라면',2500]]
#1.
# for m in menu :
# if m[0] == '비빔밥' or m[0] == '돈까스':
# print(m[1])
#2.
while True:
check = False
a = input("메뉴 입력")
for m in menu :
if m[0] == a :
prin... |
from django import forms
from django.contrib.auth.models import User
class RegistrationForm(forms.Form):
username = forms.CharField(label='Username', max_length=100, widget=forms.TextInput)
password1 = forms.CharField(label='Password', max_length=10, min_length=6, widget=forms.TextInput)
password2 = forms.CharFiel... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 3 12:22:02 2019
@author: kj22643
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 27 15:11:10 2019
@author: kj22643
"""
%reset
import numpy as np
import pandas as pd
import os
import scanpy as sc
import seaborn as sns
f... |
import numpy as np
from scipy import sparse as sp
from app.ds.graph import base_graph
from app.utils.constant import GCN
from app.ds.graph.base_graph import symmetic_adj
class Graph(base_graph.Base_Graph):
'''Base class for the graph data structure'''
def __init__(self, model_name=GCN, sparse_features=True)... |
# find all numbers between 2000 and 3200, divisable by 7 but NOT multiple of 5
# solution should be comma separated on a single line
num = []
for i in range(2000, 2301):
if (i % 7 == 0) and (i % 5 != 0):
num.append(str(i))
print(','.join(num))
# compute the factorial of a given number, result printed i... |
#!/usr/bin/env python
import tensorflow as tf
# Model paramters
session = tf.Session()
W = tf.Variable([0.3])
b = tf.Variable([-0.3])
# Model inputs and outputs
x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
init = tf.global_variables_initializer()
# loss = reduce_sum((Wx +b)^2)
linear_model = W * x ... |
import numpy as np
import torch
from typing import Any
from torch import nn
from torch.utils.data import Dataset
def CustomImageDataset(Dataset):
def __init__(self):
pass
class GradientDescent:
def __init__(self, *args):
self.args = args
def __repr__(self) -> str:
return ... |
# from keras.models import Sequential
# from keras.layers import Dense, Activation
# model = Sequential()
# model.add(Dense(32, input_shape=(784,)))
# model.add(Activation('relu'))
# model.add(Dense(10))
# model.add(Activation('softmax'))
import cv2
import numpy as np
listArray = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]... |
'''5206.删除字符串中的所有相邻重复项'''
s = "deeedbbcccbdaa"
k = 3
i=0
n=len(s)
while(i+k<=n):
if s[i:i+k]==s[i]*k:
#1.采用切片结合字符串的乘法来进行对比处理
#2.或者将字符逐个对比,累计相同字符的个数然后与k对比
#3.或者将字符逐个添加到一个list中,进行set处理,看
#处理之后长度是否为1
#后面两种方法花费时间比第一种方法更长
s=s[:i]+s[i+k:]
n=n-k
if i-k>0:
i-=k
else:
i=0
else:
i+=1
print(s) |
from ._version import get_versions
__version__ = get_versions()["version"]
del get_versions
from rubicon_ml.client import ( # noqa: E402
Artifact,
Dataframe,
Experiment,
Feature,
Metric,
Parameter,
Project,
Rubicon,
)
from rubicon_ml.client.utils.exception_handling import set_failure_... |
n = int(input())
percentage = map(int, input().split())
print(sum(percentage)/n) |
#!/usr/bin/env python3
import re
regex = re.compile(r'^(\w+)\s*\((\d+)\)(?:\s*->\s*((?:\w+, )*\w+))?\s*$')
weights = {}
prgmap = {}
revmap = {}
#with open('test.txt', 'r') as f:
with open('input.txt', 'r') as f:
for line in f:
match = regex.match(line)
if match:
prgname, weight, childl... |
import json
from datetime import datetime
import requests
from django.conf import settings
def _get_default_whatsapp_config():
return {
"admin_report": {
"message": "Coronasafe Network",
"header": "Daily summary auto-generated from care.",
"footer": "Coronasafe Network... |
from django.contrib import admin
from django.urls import path,include
from Segment import views
urlpatterns = [
path('admin/', admin.site.urls),
path('Segment/', include('Segment.urls')),
path('mobileforecastleaf', views.mobile_forecast_leaf, name="mobileforecast_leaf"),
]
|
from django.conf.urls import url
from . import views
urlpatterns = [
# ex: /pas/
url(r'^$', views.index, name='index'),
url(r'^get/student/(?P<sid>[0-9]+)/$', views.student, name='student'),
url(r'^get/studentList/', views.studentList, name='studentList'),
url(r'^get/lecturer/(?P<lid>[0-9]+)/$', v... |
# Generated by Django 3.0.8 on 2020-08-16 06:19
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('eshop_products', '0011_auto_20200801_1726'),
]
operations = [
migrations.CreateModel(
name='Pro... |
"""
Author: Jason Eisele
Date: October 1, 2020
Email: jeisele@shipt.com
Scope: App for Tensorflow Doggo classifier
"""
from pydantic import BaseModel
class HousePredictionResult(BaseModel):
median_house_value: int
currency: str = "USD"
|
import psycopg2
conn = psycopg2.connect(database="probe_management_system", user = "postgres", password = "nikhil", host = "127.0.0.1", port = "5432")
print("Opened database successfully") |
# !/usr/bin/python3
"""
Description Bytes
-----------------------------
SOF: 0-3
Control: 4
Data Length: 5
MPix Temp: 6-9
RPI Temp: 10-13
Frame Counts: 14-17
Frame Dose Rate: 18-21
Frame Count ID: 22-25
... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
"""Static analysis tool for checking compliance with Python docstring conventions.
See https://www.pantsbuild.org/docs/python-linters-and-formatters and
http://www.pydocstyle.org/en/stabl... |
# python is happy
# make happy plots
import json
import matplotlib.pyplot as plt
import numpy as np
import argparse
try:
from scipy.optimize import curve_fit
except:
print "Cannot import curve_fit from scipy.optimize"
class Plotter:
def __init__(self, data_dir, plot_dir, get_data=True):
if data_di... |
from app.models import Location, City
class LocationBuilder(object):
def __init__(self, city_name, street='', support=0):
city = City.objects.create(name=city_name)
self.location = Location.objects.create(city=city, street=street, support=support)
def with_street(self, street):
self.l... |
"""
Write a program to capture any filename from the keyboard and display its filename and extension separately
Enter any filename : hello.py
Filename : hello
Extension : py
"""
filename = input("Enter the Filename with extention:")
data = (filename.split('.'))
print("Filename :", data[0])
print("extention :", dat... |
from Bio import SeqIO
import pandas as pd
'''
print("start?")
start = input('That is :')
print("end?")
end = input('That is :')
'''
aimseq = []
site = []
prid = []
n = 0
for seq_record in SeqIO.parse("TIR.fasta", "fasta"):
n = n + 1
for index,AA in enumerate(seq_record):
if... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
import random
from .models import *
from instagram import functions
from datetime import datetime, timezone,timedelta
now = da... |
# Inventory Categories
CAT_SKILLS = 16
# Market Groups We Care About
market_group_ammo = 11
market_group_drones = 157
market_group_implants = 24
market_group_ship_equipment = 9
market_group_ships = 4
market_groups_filter = [
market_group_ammo,
market_group_drones,
market_group_implants,
market_group... |
#!/usr/bin/python3
import sys
from server import *
from client import client
from time import sleep
# print ("This is the name of the script: ", sys.argv[0])
# print ("Number of arguments: ", len(sys.argv))
# print ("The arguments are: " , str(sys.argv))
if __name__ == "__main__":
global stopServer
stopServe... |
#진법 표현
print(0b10) # 2진법
print(0o10) # 8진법
print(10) # 10진법 -디폴트
print(0x10) # 16진법
print("{:b} {:o} {} {:x}".format(10,10,10,10)) |
import tempfile
import numpy as np
from flask import current_app
from scipy.io.wavfile import write
from app.main import synthesizer
from app.main import vocoder
from app.main import client
from app.main.util.transliterate import translit
from app.main.util.tacotron.model import Synthesizer
from app.main... |
import os
import downloadEmail
emailAddress = os.environ.get("python_email")
emailPw = os.environ.get("python_password")
downloadEmail.downloadEmails(emailAddress, emailPw, 'therealnicola@gmail.com')
|
'''
Created on Nov 1, 2011
@author: jason
'''
import simplejson
import MongoEncoder.MongoEncoder
from Map.BrowseTripHandler import BaseHandler
class RealTimeSearchAllHandler(BaseHandler):
def get(self, name):
_name = name.upper()
objects = []
users = self.syncdb.users.find({'lc_usernam... |
import requests
from bs4 import BeautifulSoup
import json
import time
import datetime
import pymysql
from config import *
def get_html(url,data):
'''
:param url:请求的url地址
:param data: 请求的参数
:return: 返回网页的源码html
'''
response = requests.get(url,data)
return response.text
def parse_html(html... |
# -*- coding:utf-8 -*-
'''
Created on 2016��3��31��
@author: huke
'''
def adventureFeature():
L = []
n = 1
while n <= 99:
L.append(n)
n+=2
print(L)
if __name__ == '__main__':
adventureFeature() |
import os
import numpy as np
import tensorflow as tf
from PIL import Image
from random import randint
import config
class dataSet:
def __init__(self, seed, tag, path, width=config.image_width, height=config.image_height):
self.seed = seed
self.tag = tag
self.img_set = os.listdi... |
from os.path import join
import sys
from invoke import ctask as task, Collection
# Underscored func name to avoid shadowing kwargs in build()
@task(name='clean')
def _clean(c):
"""
Nuke docs build target directory so next build is clean.
"""
c.run("rm -rf {0}".format(c.sphinx.target))
# Ditto
@task... |
import vk_api
import random
import os
from vk_api.longpoll import VkLongPoll, VkEventType
from vk_bot import vkBot
token = os.environ.get('BOT_TOKEN')
vk = vk_api.VkApi(token=token)
longpoll = VkLongPoll(vk)
def write_msg(user_id, message):
vk.method('messages.send', {'user_id': user_id, 'messa... |
# Four Codes that break Python
# Name Error
games()
#games is an undefined function
# Syntax Error
if 4 $ 5:
# "$" isn't an operator
# Type Error
games = 42
for i in games:
print i
# Not able to loop through an int
# Attribute Error
None.lower()
# None has no attribute to lower
|
#!/usr/bin/env python3
import rmt_py_wrapper
import json
import sys, getopt
import time
import psutil
import socket
def usage():
print("Usage:")
print("\t-g | --get_config")
print("\t-s | --set_config")
print("\t-n eth0 | --net-intf eth0")
print("\t--send_file")
print("\t--recv_file")
print... |
############################# Import Section ###########################################
from flask import Flask, request
from flask_restful import Resource, Api
import base64,cv2,os
import numpy as np
import pandas as pd
import pytesseract as pt
from pytesseract import Output
import requests,random,string
fro... |
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
import numpy as np
import random
import Tkinter as Tk
from grafica import Grafica
import vectorEntrenamiento as vE
root = Tk.Tk()
root.wm_title("... |
from django import forms
from main.models import Client
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm
class RegisterForm(UserChangeForm):
phone = forms.CharField(max_length=28)
real_name = forms.CharField(max_length=128, required=False)
class Meta:
... |
from flask import Flask, render_template, jsonify, redirect, flash, request, url_for, Response, Blueprint
import flask
from flask_login import LoginManager, login_required, login_user, logout_user, current_user
from flask_caching import Cache
# import bcrypt
from flask_bcrypt import Bcrypt
import logging
import random
... |
def median(arr):
arr = sorted(arr)
indx = len(arr)//2
if (len(arr)/2).is_integer():
return (arr[indx-1] + arr[indx]) / 2
return arr[indx]
'''
Description:
The mean (or average) is the most popular measure of central tendency; however
it does not behave very well when the data is skewed (i.e. ... |
##########################################################################################
# #
# ICT FaceKit #
# ... |
# Define variable
i = 4
d = 4.0
s = 'HackerRank '
# Receiving input
integer = int( input() )
double = float( input() )
string = input()
# Print output (1. Sum integer 2. Sum float 3. Concat string)
print(i+integer)
print(d+double)
print(s+string)
|
# from re import escape, findall, split
#
#
# def find(needle, haystack):
# if '_' not in needle:
# return haystack.find(needle)
# reg = [escape(a) if '_' not in a else '.{{{}}}'.format(len(a))
# for a in split('(_+)', needle)]
# matches = findall('({})'.format(''.join(reg)), haystack)
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygame, os, sys, random, pyganim
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
DIRECTIONS = [UP, RIGHT, DOWN, LEFT]
def load_image(nombre, dir_imagen, alpha=False):
ruta = os.path.join(dir_imagen, nombre)
try:
image = pygame.image.load(ruta)
except:
... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
# @File:kmeans_example.py
# @Author: Michael.liu
# @Date:2020/6/4 11:45
# @Desc: this code is ....
import codecs
import os
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer
from sklearn.cluster import KMeans
from... |
from flask import Flask,url_for,render_template
from Blog.config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
import os
app=Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
bcrypt=Bcrypt(app)
from Blog.users.routes import users
from Blog.auth.routes import a... |
#!/usr/bin/env python3
#
# This script is intended to illustrate the energy balance by
# plotting ohmic heating and radiative losses as a function of temperature
# at equilibrium ionization, similarly to figure 6 in Vallhagen et al JPP 2020.
# This is achieved by setting a prescribed temperature profile at the values... |
import numpy as np
import matplotlib.pyplot as plt
from scipy import linalg
from sklearn.decomposition import PCA, FactorAnalysis
from ICA_noise import FastICA
from sklearn.covariance import ShrunkCovariance, LedoitWolf
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchC... |
from django.db import models
class ItemLiturgia(models.Model):
titulo = models.CharField(max_length=255)
descricao = models.CharField(max_length=255, blank=True, null=True)
diaLiturgico = models.ForeignKey("DiaLiturgico")
posicao = models.PositiveSmallIntegerField()
class Meta:
app_label = "mpm"
def __str__(se... |
# run tests locally:
# $ export PYTHONPATH=`pwd`
# $ python3 tests/ticTacToeTest.py
# or use -m unittest:
# $ python3 -m unittest tests/ticTacToe.py
import unittest
from tictactoe.game.ticTacToe import TicTacToe
class TestTicTacToe(unittest.TestCase):
def setUp(self):
self.game = TicTacToe("X")
def ... |
def make_readable(seconds):
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
return '{:02}:{:02}:{:02}'.format(hours, minutes, seconds)
|
import autograd as ag
import click
import copy
import numpy as np
import logging
import pickle
from sklearn.cross_validation import train_test_split
from sklearn.metrics import roc_auc_score
from sklearn.preprocessing import RobustScaler
from sklearn.utils import check_random_state
from recnn.recnn import log_loss
fr... |
######################################################
# Multi-Layer Perceptron Classifier for MNIST dataset
# Mark Harvey
# Dec 2018
######################################################
import tensorflow as tf
import os
import sys
import shutil
#####################################################
# Se... |
from fields import *
import texttable
from collections import defaultdict
class Board:
col_map = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5}
def __init__(self):
self.matrix = [[FullHouse(), ThreeOfAKind(), FourOfAKind(), Straight(), One(), ThreeOfAKind()],
[Straight(), S... |
# Generated by Django 2.0 on 2017-12-14 02:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('yyfeed', '0003_auto_20170107_0937'),
]
operations = [
migrations.AlterField(
model_name='feed',
name='link',
... |
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import errno
import os
import unittest
import unittest.mock
from contextlib import contextmanager
from dataclasses import dataclass
from typing import I... |
from .example_net import ExampleNet
from .attention_net import AttenNet
from .best_net import BestNet
|
def list_all_run_instances(intent_request):
if intent_name == 'list_all_instances':
return list_all_instances(intent_request)
|
from .eod_data import EOD, Future_EOD, Charting, Technical
from .fundamental import Fundamental
from .index import Index, IndexSpecific
from .news import News
from .peers import Peers
from .sec import SEC
from .weekly import Weekly
from .sectors import Sectors
from .settings import Settings
from .ticker import Ticker
f... |
from matplotlib import pyplot as plt
import numpy as np
n = np.linspace(0,199,200)
#User-input x(n)
function_xn = input('Enter a function x(n): ') #NOTE: Test input is np.sin(((3*n*np.pi)/100))
def x(n):
fxn_x = eval(function_xn)
return fxn_x
#piecewise function y(n)
for a in range(200):
... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import Counter
total=0
s=[]
number_of_shoes = input()
all_shoes_size = Counter(list(input().split()))
num_customers = input()
for n in range(int(num_customers)):
s.append((input().split()))
if all_shoes_size[s[n... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import mics
import pandas as pd
plt.rcParams.update({'font.size':8})
fig = plt.figure('axes',figsize=(3.0,2.0))
ax = fig.add_subplot(111)
ax.set_xlabel('Time (ns)')
ax.set_ylabel('Total Energy (kcal/mol)')
timesteps =... |
# -*- coding: utf-8 -*-
from collections import deque
class Solution:
def isValid(self, s):
stack = deque()
for c in s:
if c == "(":
stack.append(")")
elif c == "[":
stack.append("]")
elif c == "{":
stack.append(... |
from django.contrib import admin
from .models import canditates,rounds_table,role_table
admin.site.register(canditates)
admin.site.register(role_table)
admin.site.register(rounds_table) |
"""Mocks used for testing."""
import httmock
# Modoboa API mocks
@httmock.urlmatch(
netloc=r"api\.modoboa\.org$", path=r"^/1/instances/search/", method="post")
def modo_api_instance_search(url, request):
"""Return empty response."""
return {"status_code": 404}
@httmock.urlmatch(
netloc=r"api\.modo... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
from flask import Blueprint, render_template, g
from scriptfan.models import *
postapp = Blueprint("post", __name__, url_prefix="/post")
@postapp.route('/')
def index():
g.posts = Post.objects.all()
return render_template('post/index.html')
|
USER_TOKENS = 'user_tokens'
ADMIN_TOKENS = 'admin_tokens'
TOKEN_VALUE = 'token_value'
USERNAME = 'username'
NAME = 'name'
EMAIL = 'email'
TOKENS = 'tokens'
UNKNOWN = 'unknown'
HOST = 'host'
PORT = 'port'
USE_SSL = 'use_ssl'
USE_WSGI = 'use_wsgi'
VALIDATE_SSL = 'validate_ssl'
USE_UWSGI = 'use_uwsgi'
CERT_PEM = 'cert_pem... |
import time
import xlsxwriter
from pyrebase import pyrebase
import firebaseConfigFile
# connect firebase
firebase = pyrebase.initialize_app(firebaseConfigFile.firebaseConfig)
storage = firebase.storage()
db = firebase.database()
# create excel file for answers
workbook = xlsxwriter.Workbook('Answer.xlsx')
worksheet =... |
# Config file with locations of various binaries, hostnames etc
#
# Change the SITE variable to run the experiments on different testbed setup
import argparse
import sys
import types
site_config_parser = argparse.ArgumentParser(description='Site config variables')
site_config_parser.add_argument('--var', dest='var',... |
class Solution():
def addtion(self, nums, t):
a = dict()
for i in range(len(nums)):
if (t - nums[i]) in a:
return i, a[(t-nums[i])]
else:
a[nums[i]] = i
nums = [1,'3',5,6]
t = 11
nums1 = range(10)
solu = Solution()
print(solu.addtion(nums, t)) |
"""
Goal:
* List open MR.
Todos:
* Make project and group arguments exclusive.
How to:
* Get help
- python list_mrs.py -h
* The Private Token can be given as environemnt variable GITLAB_PRIVATE_TOKEN
- I read the password using pass (cli password manager)
- GITLAB_PRIVATE_TOKEN=$(pass show work/CS... |
"""
run_models_.py
Purpose: Predict gene expression given graph structure and node features
Usage: python ./run_model_.py [-c <str>] [-rf <int>] [-me <int>] [-lr <float>]
[-cn <int] [-gs <int>] [-ln <int>] [-ls <int>]
Arguments:
'-c', '--cell_line', default='E116', type=str
'-rf', '--regression_flag', d... |
class Animal: #모든 동물의 공통 기능
def __init__(self, weight, sound):
self.weight = weight
self.sound = sound
def sleep(self):
print("코 잔다")
def speak(self):
print(self.sound)
def eat(self):
print("먹는다")
def show(self):
print("동물 : %.2fkg"%self.wei... |
# Copyright 2017 The Forseti Security Authors. 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 ap... |
"""
Problem Statement
Shashank likes strings in which consecutive characters are different. For
example, he likes ABABA, while he doesn't like ABAA. Given a string containing
characters A and B only, he wants to change it into a string he likes. To do
this, he is allowed to delete the characters in the string.
... |
"""Custom topology example
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
"""
from mininet.topo import Topo
class M... |
""" Generates random dice rolls, nothing special just a randint wrapper """
from random import randint
# Can't roll less than 1 die
MIN_DICE_COUNT = 1
# 10 is a pretty sensible maximum per turn
MAX_DICE_COUNT = 10
# Cannot have a 1 sided die
MIN_DICE_FACE_COUNT = 2
# Largest you'd ever want to roll is a d100
MAX_DICE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.