text stringlengths 38 1.54M |
|---|
import demistomock as demisto
import json
def executeCommand(name, args=None):
if name == 'demisto-api-get' and args and 'uri' in args and args['uri'] == "/settings/integration-commands":
file_name = 'TestData/integration_commands.json'
elif name == 'demisto-api-post' and args and 'uri' in args and ar... |
# I want to be able to call nested_sum from main w/ various nested lists
# and I greatly desire that the function returns the sum.
# Ex. [1, 2, [3]]
# Verify you've tested w/ various nestings.
# In your final submission:
# - Do not print anything extraneous!
# - Do not put anything but pass in main()
###############... |
# waifu2xのupconv7と同様のモデル構造のモデルです
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from PIL import Image
from MMD2illust_util import tensor_to_pil
MODEL_PATH = "latest_960_1920.pth"
class waifu2x_processor(object):
def __init__(self):
super().__init__()
modules = [nn.... |
from allure_commons.types import AttachmentType
from selenium import webdriver
from selenium.webdriver.common.by import By
from Solarwinds_login.utilities.handy_wrappers import HandyWrappers
from Solarwinds_login.utilities.explicit_wait import ExplicitWaitType
import time
class solarwin_login():
baseUrl = "https:/... |
# Copyright (c) 2015
#
# All rights reserved.
#
# This file is distributed under the Clear BSD license.
# The full text can be found in LICENSE in the root directory.
from boardfarm.lib import common
from . import qcom_akronite_nand
class QcomDakotaRouterNAND(qcom_akronite_nand.QcomAkroniteRouterNAND):
"""QcomD... |
#!/usr/bin/env python3
# use sys to add a count from the command line. When entered on command line, comes in as a string, so you have to make it an int or float first.
import sys
count = int(sys.argv[1])
if count > 100:
print('True')
else:
print('False')
|
#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the PyMVPA package for the
# copyright and license terms.... |
#638. 大礼包
'''
在LeetCode商店中, 有许多在售的物品。
然而,也有一些大礼包,每个大礼包以优惠的价格捆绑销售一组物品。
现给定每个物品的价格,每个大礼包包含物品的清单,以及待购物品清单。请输出确切完成待购清单的最低花费。
每个大礼包的由一个数组中的一组数据描述,最后一个数字代表大礼包的价格,其他数字分别表示内含的其他种类物品的数量。
任意大礼包可无限次购买。
示例 1:
输入: [2,5], [[3,0,5],[1,2,10]], [3,2]
输出: 14
解释:
有A和B两种物品,价格分别为¥2和¥5。
大礼包1,你可以以¥5的价格购买3A和0B。
大礼包2, 你可以以¥10的价格购买1A和2B... |
# @Time : 2021/1/27 16:31
# @Author : DengZh
# @File : SVMDemo.py
# @Software: PyCharm
import numpy as np
from sklearn.svm import SVR
X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
# y = 1 * x_0 + 2 * x_1 + 3
y = np.dot(X, np.array([1, 2])) + 3
# model = SVR()
#调参 高斯核作为它的核函数,同时将核参数设为1,惩罚系数设为100
#调参后的svm模型
model = SV... |
# Generated by Django 2.1.2 on 2019-01-05 12:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rounds', '0011_auto_20190103_1743'),
]
operations = [
migrations.AddField(
model_name='assessment',
name='slug',
... |
"""WebReporter: OpenMM Reporter for live plotting of summary statistics
in the browser, using tornado, websockets, and google charts.
Authors: Robert McGibbon
License: GPLv3
"""
##############################################################################
# Imports
####################################################... |
class Pokemon:
def __init__(self,nome,tipo,descricao,ataques,nivel=0,poder_luta=0,brilhante=True):
self.nome = nome
self.tipo = tipo
self.descricao = descricao
self.ataques = ataques
self.nivel = nivel
self.poder_luta = poder_luta
self.brilhante = brilhante
... |
# Guide Schema
# id (text, required): unique id
# required_targets (list): An empty list will cause the guide to be shown regardless
# of page/targets presence.
# steps (list): List of steps
# Step Schema
# title (text, required): Title text. Tone should be active.
# message (text, optional): ... |
import numpy as np
import matplotlib.pyplot as plt
"""Example (modified) from http://matplotlib.org/users/recipes.html
"""
np.random.seed(1234)
fig, ax = plt.subplots(1)
x = 30*np.random.randn(10000)
mu = x.mean()
median = np.median(x)
sigma = x.std()
textstr = '$\mu=%.2f$\n$\mathrm{median}=%.2f$\n$\sigma=%.2f$'%(... |
class colors:
G = '\033[92m' # Green
Y = '\033[93m' # Yellow
R = '\033[91m' # Red
B = '\033[1m' # Bold
U = '\033[4m' # Underline
def color(msg, color):
return color + str(msg) +'\033[0m'
|
#!/usr/bin/python3
from flask import Flask
from flask_restful import Api
from transpec.resources.whoami import Whoami
app = Flask(__name__)
api = Api(app)
from security.providers.mock import MockAuthProvider
app.config['SECRET_KEY'] = 'super-secret'
auth_provider = MockAuthProvider(app)
auth_provider()
api.add_... |
# pylint:disable=line-too-long
"""
The tool to check the availability or syntax of domains, IPv4, IPv6 or URL.
::
██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗
██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝
██████╔╝ ╚████╔╝ ████... |
#! /usr/bin/env python3
#-*- coding: utf-8 -*-
"""
Game Saving MacGyver : this game is a simple labyrinth game with conditions of victory.
The movements will be made with the keyboard : right, left, up and down arrow keys.
The conditions of victory is simple : collect the 3 items on the map
before heading to the iss... |
# -*- coding: utf-8 -*-
# @File : 76_MinimumWindowSubstring.py
# @Author: ZRN
# @Date : 2019/5/14
"""
给定一个字符串 S 和一个字符串 T,请在 S 中找出包含 T 所有字母的最小子串。
示例:
输入: S = "ADOBECODEBANC", T = "ABC"
输出: "BANC"
"""
class Solution:
def minWindow(self, s: str, t: str) -> str:
letter_count = {}
cur_letter = {}
... |
class Person:
def set(self,name,age,adrs):
self.name=name
self.age=age
self.adrs=adrs
print(self.name,self.age,self.adrs)
class Employee(Person):
def setval(self,id,salary,dprtmnt):
self.id=id
self.salary=salary
self.dprtmnt=dprtmnt
pri... |
def read_varlen_quantity(string):
pass
def scale_num(num, from_bits, to_bits):
assert num <= (2**from_bits-1)
assert isinstance(num, int)
scale_factor = num / (2.0**from_bits-1)
fixed_number = scale_factor * (2.0**to_bits-1)
return int(fixed_number)
if __name__ == "__main__":
... |
import os
import subprocess
import sys
from .hdllogger import HDLLogger
class HDL:
hdd = ''
isoDirectoryPath = ''
hdlPath = ''
hdlCommand = ''
sliceIndex = '*u4'
logger = HDLLogger('LOG.log')
def __init__(self, hdd, isoDirectoryPath, hdlPath):
self.hdd = hdd
self.hdlPath =... |
'''
Developer: Ersin ÖZTÜRK
Date: 01.02.2020
Purpose of Software: Reinforcement of learned Python Code and Self-improvement
'''
fruits= ['apple','banana','cherry']
for x in fruits:
if x!=fruits[-1]:
print(x,end=',')
else:
print(x)
|
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser, UserManager
)
#
# class UserManager(BaseUserManager):
# def create_user(self, email, password=None):
# """
# Creates and saves a User with the given email and password.
# """
# ... |
import moviepy.editor
video = moviepy.editor.VideoFileClip("F:\AAFAQ RASHID\VIDEOS\Hindi and Urdu Songs\kabir.mp4")
audio = video.audio
audio.write_audiofile("result.mp3")
|
import numpy as np
from numpy import isnan
from yahooFinance import getQuote
def normcorrcoef(a,b):
return np.correlate(a,b)/np.sqrt(np.correlate(a,a)*np.correlate(b,b))[0]
def interpolate(self, method='linear'):
"""
Interpolate missing values (after the first valid value)
Parameters
----------
... |
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Conv2D, MaxPool2D, Flatten, BatchNormalization, Activation
from keras import activations
from math import floor
model = Sequential()
model.add(Conv2D(filters=8, kernel_size=(3, 3), kernel_initializer='normal', activation='relu', p... |
import pandas as pd
import numpy as np
class QlearningTable:
def __init__(self,action=[0,1,2,3],learning_rate = 0.01,reward_decay = 0.9, e_greddy = 0.9):
self.action = action
self.lr = learning_rate
self.gamma = reward_decay
self.epsilon = e_greddy
self.q_table = pd... |
from setuptools import setup
setup
{
name='twidder',
packages=['twidder'],
include_package_data=True,
install_requires=[
'flask', 'validate_email', 'app', 'gevent', 'flask_sockets'
],
}
|
#!/usr/bin/env python
# encoding: utf-8
from selenium import webdriver
from Util.oper_Browser import *
from Util.find_el import *
import time
class Tyzf:
def __init__(self):
self.driver=driver()
def rever(self,method,el):
#self.driver.set_window_siz(200,400)
get_url(self.driver,'https:/... |
'''
Created on Mar 8, 2015
@author: saur
'''
from pypower.api import ppoption, runpf
from case_modul import casemodul
from numpy import *
def adapt_case(node,power, time):
#input node is the node that the agent accesses, the power is in kW , the time is the timestep [0,96]
time = time % 96 # if the time inte... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import os
import json
from pathlib import Path
def get_project_root() -> Path:
"""Returns project root folder."""
return Path(__file__).parent.parent.parent
def keep_indices_in_seg_img(seg_img, indices_list):
img2keep = np.zeros(s... |
import os
import asyncio
from pathlib import Path
from contextlib import contextmanager
import pytest
from lonelyconnect import game, startup, shutdown, auth
def test_auth(requests, admin_token):
r = requests.get("/codes", headers={"Authorization": f"Bearer wrong"})
assert not r.ok
r = requests.get("/c... |
APIAI_CLIENT_ACCESS_TOKEN = 'e4bbf6d0e27547d281620e50d5d63d00'
OWM_CLIENT_ACCESS_TOKEN = 'f9070aef8910b5e6551d1816a02843a3'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2015-2016 by Gaik Tamazian
# gaik (dot) tamazian (at) gmail (dot) com
import logging
import pyfaidx
import random
import string
from bioformats.blast import BlastTab
from chromosomer.exception import MapError
from chromosomer.exception import AlignmentToMa... |
import matplotlib.pyplot as plt
import numpy as np
import math
g=9.8
l=9.8
wd=2.0/3
q=0.5
class Simple_pendulum:
def __init__(self,_theta0=0.2,_w=0,_t0=0,_dt=math.pi/1000,_tfinal=500):
self.theta=[]
self.theta.append(_theta0)
self.t=[]
self.t.append(_t0)
self.w=[]
s... |
"""Función recibe la palabra(parámetro) que imprime 1000 veces"""
def milPal(pal):
# Devuelve la palabra en pantalla 1000 veces
if str.isnumeric(pal):
raise ValueError
print((pal + " ")*1000)
return((pal + " ")*1000)
# Se pide la palabra
if __name__ == "__main__":
w... |
class Recipe:
def __init__(self,name,cooking_lvl,cooking_time,ingredients,description,recipe_type):
if name=='' or type(name)!=str:
raise ValueError
self.name=name
if type(cooking_lvl)!=int or not(1<=cooking_lvl<=5):
raise ValueError
self.cooking_lvl=cooking_l... |
python
###########
import numpy as np
import pandas as pd
# from pandas.plotting import scatter_matrix
from regression_tools.dftransformers import (
ColumnSelector,
Identity,
Intercept,
FeatureUnion,
MapFeature,
StandardScaler)
from scipy import stats
from plot_univariate import plot_one_uni... |
"""Represents a request to perform a menu action."""
from typing import Mapping
from marshmallow import EXCLUDE, fields
from .....messaging.agent_message import AgentMessage, AgentMessageSchema
from ..message_types import PERFORM, PROTOCOL_PACKAGE
HANDLER_CLASS = f"{PROTOCOL_PACKAGE}.handlers.perform_handler.Perfor... |
import math
import os
class Distancia:
def __init__(self,numero):
self.numero = numero
# Metros
def cm_to_m(self):
metros = self.numero/100
return metros
class Tiempo:
def __init__(self,distancia):
self.distancia = distancia
def calcular_tiempo(self):
tiem... |
# Generated by Django 2.0.1 on 2018-05-23 19:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('freshsheet', '0011_auto_20180523_1827'),
]
operations = [
migrations.AlterField(
model_name='fooditem',
name='case_c... |
import collections
import datetime
import re
regexes = {
'release': re.compile('(\w{3}\d{6})\s*(.*)\s*(\$(\d+\.\d+)|pi)', re.IGNORECASE),
'publisher': re.compile('^(dc comics|dark horse comics|idw publishing|image comics|marvel comics)$', re.IGNORECASE),
'series': re.compile('(.*?)#\d+(?!(.*poster)|.*(comb... |
#! /usr/bin/env python3
"""
코틀린 코드를 실행하는 숏컷.
PATH 경로에 넣어두면 편하다.
"""
import sys
import os
import shlex
import subprocess
def usage():
print("Usage: %s [InputFile.kt]" % sys.argv[0])
if len(sys.argv) != 2:
usage()
sys.exit(0)
filename = sys.argv[1]
if filename.endswith('.kt') == False:
usage()
sys.exit... |
'''
general work in chapter four
also, exercise 4-10. Slices:
print the first three items from a list
print three items from the middle of the list
print the last three items from a list
also, exercise 4-11. More Loops:
use for loops to print two of the food lists
'''
my_foods = ['mice', 'voles', 'grass... |
import pymysql
class Connect:
def __init__(self):
try:
self.conn = pymysql.connect(host = "localhost", user="root", password="zaq12wsx", db="Restauracja", port=3307,
charset='utf8')
print("polaczenie ustanowione")
self.wybor()
... |
from django.shortcuts import render
from shop.models import Shop
from django_user_agents.utils import get_user_agent
from django.http import HttpResponse,Http404
def index(request):
if get_user_agent(request).is_mobile:
templatePath = 'sp/index.html'
else:
templatePath = 'sp/index.html'
ret... |
# ComKom1b.py
html = "<html>\n <body>\n TigerJython Web Site\n </body>\n</html>"
print html
|
##-----------------------------
# Pycrash Course
# Eric Matthes
# Cap. 10 - Arquivos
# write_message.py, p.264
##-----------------------------
filename = 'programming.txt'
with open(filename, 'w') as file_obj:
file_obj.write('I love programming!')
with open(filename, 'r') as obj:
print(obj.read())... |
import preprocess
import pandas as pd
import os
from datetime import datetime
# labels / features of the dataframe
labels = ["BUILDER", "House ID", "DATE_BUILT", "DATE_PRICED", "LOCATION",
"DST_DOCK", "DST_CAPITAL", "DST_MARKET", "DST_TOWER",
"DST_RIVER", "DST_KNIGHT_HS", "FRNT_FARM_SZ", "GARDEN",
... |
from rest_framework import serializers
from strategy.models import Strategy
class StrategySerializers(serializers.ModelSerializer):
class Meta:
model = Strategy
fields = ('id', 'strategy_title', 'strategy_content', 'publish_date', 'browse_count', 'pay_count', 'user_id', 'is_pay_money') |
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
from pymongo import MongoClient
import re
cl... |
# Copyright (c) 2010 NORC
#
# 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, modify, merge, publish, distribute, su... |
#!/bin/env python3
"""
https://www.hackerrank.com/challenges/python-quest-1
INPUT:
int N, where 1 <= N <= 9
OUTPUT: N-1 lines
numerical triangle of height N-1 like
1
22
333
4444
55555
...
?
1
11 * 2
111 * 3
1111 * 4
11111 * 5
1 = 1
2 + 20 = 22
3 + 30 + 300 ... |
from flask import Blueprint
from flask_login import current_user
from .. import db
account = Blueprint('account', __name__)
from . import views # noqa
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# C++ version Copyright (c) 2006-2007 Erin Catto http://www.box2d.org
# Python version Copyright (c) 2010 kne / sirkne at gmail dot com
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable f... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome()
url ="http://github.com"
driver.get(url)
searchInput = driver.find_element_by_xpath("/html/body/div[1]/header/div/div[2]/div[2]/div/div/div/form/label/input[1]")
time.sleep(1)
searchInput.send_keys... |
from django.db import models
# Create your models here.
class Product(models.Model):
id = models.AutoField(primary_key=True)
author = models.CharField(max_length=100)
title = models.CharField(max_length=100)
image = models.CharField(max_length=500)
quantity = models.IntegerField()
price = model... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
from scrapy import Item, Field
class WeiboItem(Item):
# define the fields for your item here like:
# name = scrapy.Field()
table_name = 'weibo'
wei... |
'''
Módulo Collections - Counter
Collecions - High-Performance Contarners DataTypes
Counter -> Recebe um iterável como parâmetro e cria um objeto do tipo counter que é parecido com um
dicionário, contendo como chave os elementos da coleção passada e como valor a quantidade de ocorrências
desses elementos
'''
print(... |
'''
Created on May 29, 2013
@author: dough
'''
from playback_recording_response import PlaybackRecordingResponse
from playlist_factory import PlaylistFactory
class PlaybackRecordingController(object):
'''
classdocs
'''
def __init__(self, recordings_list):
'''
Constructor
'''
... |
message = 'we come to beijing'
print(message)
message2 = ' I come form china '
print(message2+message)
name ='lei kang is china '
''' title() 表示每个单词首字母大写'''
print(name.title())
name2 = 'Eric'
print('hello'+' '+name2 + ' ' +'would you like to learn some Python today')
name_3 ='eric losry'
# 输出名字小写
print('my name‘s :'+' ... |
# -*- coding: UTF-8 -*-
# For ubuntu env error: findfont: Font family ['Times New Roman'] not found. Falling back to DejaVu Sans.
# ```bash
# sudo apt-get install msttcorefonts
# rm -rf ~/.cache/matplotlib
# ```
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
x = [1, 2, 3, 4, 5, 6, 7, ... |
from math import sqrt
def PrimeArray(n):
from math import sqrt
A,B,C = [],[],[]
for i in range(int(n+1)):
A.append(i) #Initialize A, from 0 to 2000000
B.append(1) #Initialize B, containing all 1s from 0 to 2000000
# Remove 0 and 1 from A
if n == 0:
return([])
if n =... |
from typing import List
class Solution:
def hIndex(self, citations: List[int]) -> int:
# left, right = 0, len(citations) - 1
# while left < right:
# middle = (left + right) // 2
# index = len(citations) - middle
# if citations[middle] >= index:
# ... |
import argparse
def build_map(input):
map = []
for index in range(0, len(input)):
row = []
for i in input[index]:
row.append(i)
map.append(row)
return map
class Slope:
def __init__(self, x, y):
self.x = x
self.y = y
def apply(self, x_0, y_0):... |
import numpy as np
import os, sys, json
import PIL
import pandas as pd
from pathlib import Path
import matplotlib.pyplot as plt
# img_dir = '../../rf-chess-data/roboflow/export/'
# img_fns = os.listdir(img_dir)
# output_dir = 'data/rf-annotate/'
annotate_dir = '../../../other-chess-data/regulation-pieces-3/originals/d... |
import numpy as np
from numpy import ndarray
from pprint import pformat
from reconstruct.quaternion import Quaternion
class Matrix4:
# shape (4, 4)
value: ndarray
def __init__(self):
self.value = np.identity(4, dtype=np.float32)
def __getitem__(self, index):
return self.value[index]
... |
# -*- coding: utf-8 -*-
from EXOSIMS.util.vprint import vprint
from EXOSIMS.util.get_module import get_module
from EXOSIMS.util.get_dirs import get_cache_dir
import numpy as np
import astropy.units as u
class Completeness(object):
""":ref:`Completeness` Prototype
Args:
minComp (float):
... |
TRACK_TERMS = ["#Huracan",
"#Lamborghini",
"#Aventador",
"#Lambo",
"#urus",
"#gallardo",
"#V10",
"#V12",
"#murcielago",
"#AventadorSVJ",
"#huracantalk",
... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
import collections
from filters import Filters
from utilities import ImageUtilities
BG_COLOR = 0
UNKNOWN_COLOR = 1
FG_COLOR = 2
EDGE_COLOR = 3
TRACK_START_COLOR = 4
TRACK_END_COLOR = 10
def flood_fill(seeds, img, background_val, fill_val):
"""
... |
import os
from client import Client
class SendJson(Client):
def __init__(self, TCP, host, port, path):
Client.__init__(self, TCP, host, port)
self.path = path
def run(self):
while(self.continuer):
try:
data = self.sock.recv(1024)
sel... |
# -*- coding: utf-8 -*-
"""
City Mania
version: You have to start somewhere right?
"""
import engine
import region
import sys
sys.path.append("..")
import common.protocol_pb2 as proto
import chat
import filesystem
from threading import Lock
import users
import simulator
from network import Network
# TODO: These value... |
# Generated by Django 3.1.5 on 2021-03-08 02:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userauth', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='address',
... |
from django.test import TestCase
from products.models import Location, Warehouse
class LocationTest(TestCase):
def setUp(self):
self.warehouse = Warehouse.objects.create(name="Test")
def test_add_location(self):
location = Location.objects.create(
name="Test",
wareho... |
from django.contrib.auth.decorators import login_required
from django.contrib.admin import AdminSite
from django.contrib.auth.models import User
from django.shortcuts import redirect
from SputnikIDE.models import Project, Version
class MyAdminSite(AdminSite):
def each_context(self, request):
context = su... |
#################################################
# Bootstrapping to solve local vol by tenor
# Input: r_quotes, r_tenors, rf_quotes, rf_tenors, imp_vol_quotes, imp_vol_tenors, imp_vol_strikes
# Output: loc_vol_surface
#################################################
import numpy as np
import matplotlib.pyplot as pl... |
#108303540 Feb/23/2021 18:59UTC+5.5 Shan_XD 546A - Soldier and Bananas PyPy 3 Accepted 93 ms 0 KB
k,n, w= input().split()
k=int(k)
n=int(n)
w=int(w)
price= int(k*w*(w+1)/2 - n)
if price>0:
print(price)
else:
print(0)
|
import unittest
from GoMore import GoMore
#The following testclass is for the non firebase version of the program.
class TestGoMore(unittest.TestCase):
def setUp(self):
self.myGoMore = GoMore()
self.myGoMore.appendRide("Odense Copenhagen 2018-10-01 4".split())
self.myGoMore.appendRide("Cop... |
# Linear Discriminant Analysis (LDA)
# Importing libraries
from sklearn.metrics import confusion_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import tr... |
#!/usr/bin/python3
#-*-coding:utf-8-*-
data_file_name_1 = 'data/1_Poisy-ParcDesGlaisins.txt'
data_file_name_2 = 'data/2_Piscine-Patinoire_Campus.txt'
fichier = [data_file_name_1, data_file_name_2]
try:
with open(data_file_name_1, 'r') as f :
content1 = f.read()
with open(data_file_name_2, 'r') ... |
# Program to find the greatest number jn a list
arr=[1,2,3,4,5]
max=arr[0]
#comparing the max variable with rest of the array
for i in range(0,len(arr)):
if arr[i]>max:
max=arr[i]
print(max)
|
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
if not n:
return [0]
res = [0, 1]
# start with n = 1, we have 0000 0001
# n = 2: 0000 0001 0011 0010
# n = 3: 0000 0001 0011 0010 0110 0111 0101 0... |
import math
import numpy
import random
import logging
import pprint
import time
from genepy import ga
from genepy import generate
from genepy import mutate
from genepy import crossover
_logger = logging.getLogger(__name__)
def _create_fitness(target):
def _fitness(genepool):
fitness = {}
for in... |
"""
大麦网的活动简单获取
"""
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
import pandas as pd
URL = "https://search.damai.cn/search.html?keyword=&spm=a2oeg.home.searchtxt.dsearchbtn2"
citys, titles, addresss, dates, details = [],... |
def zero(s):
if s[0] == '0':
return s[1:]
def one(s):
if s[0] == '1':
return s[1:]
def rule_sequence(s, rules):
# for rule in rules:
# s = rule(s)
# if s == None:
# break
# return s
if s == None or not rules:
return s
else:
ret... |
from math import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
from tkinter import *
import matplotlib.pyplot as plt
import numpy
root = Tk()
root.title('Полет тела')
g = 9.80665
dx = 0.01
v = IntVar()
an = IntVar()
x0 = IntVar... |
from tkinter import *
root =Tk()
label_1 = Label(root, text="Name")
label_2 = Label(root, text="Password")
entry_1=Entry(root)
entry_2=Entry(root)
label_1.grid(row=0, sticky=E)
label_2.grid(row=1, sticky=E)
entry_1.grid(row=0,column=1)
entry_2.grid(row=1,column=1)
root.mainloop() |
#!/usr/bin/python
# Katacoda to Instruqt converter
# v. 0.0.3
# Support for notes in first challenge, fix NodePort
#
# v. 0.0.2
# Support for bulk migrate with git submodule
#
# v. 0.0.1
# First draft
#
import os
import json
import yaml
import re
import shutil
# Instruqt will order the YAML and sanitize the YAML ... |
from threading import Thread
import time
import json
from django.conf import settings
from crawler.celery_tasks import downloader
from utils import Downloader
import requests
class CrawlerManager:
def __init__(self, seeds=None, qs=10):
"""
Initiate the crawler with the seeds provided. If the se... |
default_app_config = 'tenant_report.apps.TenantReportConfig'
'''
#TODO: UNIT TEST
tenant_report/__init__.py 2 0 100%
tenant_report/apps.py 3 0 100%
tenant_report/tests.py ... |
import re
class CppParser:
def __init__(self):
self.num_of_class = 0
self.num_of_inherited_class = 0
self.num_of_constructors = 0
self.num_of_operator_over = 0
self.num_of_objects = 0
self.class_names = list()
self.inherited_class_names = list()
se... |
from flask import Flask, request, url_for,render_template,flash,redirect
from flask_pymongo import PyMongo,MongoClient
import bcrypt
app = Flask(__name__)
client = MongoClient("mongodb://localhost:27017/")
db = client["register"]
users = db["users"]
def verifypw(user, password):
pw = users.find({'Username':user}... |
#-*-coding:utf-8-*-
#导入模块,初始化屏幕
import turtle as t
screen = t.Screen()
screen.title("极客中心")
screen.bgcolor('white')
screen.setup(800,600)
screen.tracer()
#cpc党旗的类
class PartyFlag(object):
#初始化党旗属性
def __init__(self,x,y,extend):
self.x = x
self.y = y
self.extend = extend
self.fr... |
from collections import Counter
def matching_strings(strings, queries):
counts = Counter(strings)
results = [counts.get(q_str, 0) for q_str in queries]
return results
|
from activation_functions import sigmoid_function, tanh_function, linear_function,\
LReLU_function, ReLU_function, elliot_function, symmetric_elliot_function,softmax_function,dropout,add_bias
from neuralnet import NeuralNet
import numpy as np
import cPickle
f=open('/Users/yanshen/Downlo... |
# This function prints above list of lists in a sudoku format.
def print_sudoku(sudoku):
print("-------------------------------")
for i_row in range(len(sudoku)):
if i_row % 3 == 0 and i_row != 0:
print("|---------|---------|---------|")
for i_col in range(len(sudoku[i_row])):
... |
from discrete_maze.maze import ExploreTask
from loggy import Log
from schedules import ExploreCreatorSchedule as ECS
from schedules import GridMazeSchedule as GMS
import random
import numpy as np
from tqdm import tqdm
# Run this from project root as:
# python -m utils.maze_terminate_test
class TotallyRandomAgent:
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/emiliano/Qt/Test1/mainwindow.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, Mai... |
###############################################################################
# Copyright (c) 2015-2017, Lawrence Livermore National Security, LLC.
#
# Produced at the Lawrence Livermore National Laboratory
#
# LLNL-CODE-716457
#
# All rights reserved.
#
# This file is part of Ascent.
#
# For details, see: http://asc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.