text stringlengths 38 1.54M |
|---|
from tkinter import *
window = Tk()
window.geometry("310x150")
name = Entry(window, width=25)
frstgrade = Entry(window, width=25)
secgrade = Entry(window, width=25)
trdgrade = Entry(window, width=25)
resultbx = Text(window, height=1, width=25)
lbnme = Label(window, text="Name:")
lbfst = Label(window, text="First grad... |
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_lib_svn_home_dir(host):
f = host.file('/srv/svn/repos/libsvn')
assert f.exists
assert f.user == 'svn'
assert f.group =... |
import os
def GetParentPath(path, layer):
for i in range(layer):
path = os.path.dirname(path)
return path
class Config:
STAGE_ID = "pre"
PWR_MAXN = 2999999999
TIME_MAXN = 30
SCORE_MAXN = PWR_MAXN * TIME_MAXN + TIME_MAX... |
#!/usr/bin/env python
import roslib; roslib.load_manifest('kurt_base')
import rospy
from sensor_msgs.msg import JointState
def fake_wheel_publisher():
pub = rospy.Publisher('/joint_states', JointState, queue_size=100)
rospy.init_node('fake_wheel_publisher')
while not rospy.is_shutdown():
js = JointS... |
#-*- coding: utf-8 -*-
import requests
import pandas
from bs4 import BeautifulSoup
from collections import defaultdict
'''
spider is crawler bot
'''
def spider():
cfp_dic = defaultdict(lambda: defaultdict(str))
k = 0
url = 'https://research.cs.wisc.edu/dbworld/browse.html' #์์งํ๋ ค๋ ํํ์ด์ง ์ฃผ... |
"""Extract data on near-Earth objects and close approaches from CSV and JSON files.
The `load_neos` function extracts NEO data from a CSV file, formatted as
described in the project instructions, into a collection of `NearEarthObject`s.
The `load_approaches` function extracts close approach data from a JSON file,
for... |
#!/usr/bin/env python
from folds import Vertex, Edge, collinear, foot_of_altitude, quadrance
v1 = Vertex(0, 0, 0)
v2 = Vertex(0, 1, 0)
assert quadrance(v1, v2) == 1
e1 = Edge(v1, v2)
assert e1.quadrance() == 1
v3 = Vertex(0, 2, 0)
v4 = Vertex(1, 0, 0)
assert collinear(v1, v2, v3) is True
assert collinear(v1, ... |
# coding: utf-8
# In[ ]:
### Downloads and Uploads data from AWS Earth Program and uploads to GCS. Super inefficient but it works.
# In[1]:
ec2_input_path = "/volumes/data/hackathon_for_good/input"
# In[2]:
ec2_output_path = "/volumes/data/hackathon_for_good/output"
# In[3]:
get_ipython().system('mkdir -p ... |
f=open('Table.txt','w')
for i in range(1,11):
for j in range(1,11):
f.write(str(i*j)+'\t')
print(i*j ,end='\t')
f.write('\n')
print()
f.close()
|
# -*- coding: utf-8 -*-
# Copyright (C) 2015-2019 by Brendt Wohlberg <brendt@ieee.org>
# All rights reserved. BSD 3-clause License.
# This file is part of the SPORCO package. Details of the copyright
# and user license can be found in the 'LICENSE.txt' file distributed
# with the package.
"""Classes for ADMM algorithm... |
from django.contrib import admin
from django.contrib.auth.models import User as AuthUser
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from django.template.defaultfilters import truncatechars
from django.urls import reverse
from django.utils.html import format_html
from . import models
from blog.lib... |
print("made by xXFireShadow700Xx")
from time import sleep
sleep(9)
print(''' _____ ____ ____ __ ___
/ ___/| \ / | / ] / _]
( \_ | o ) o | / / / [_
\__ || _/| |/ / | _]
/ \ || | | _ / \_ | [_
\ || | | | \ || |
\___|... |
"""
872. Leaf-Similar Trees
Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
Two binary trees are considered leaf-similar if their leaf value sequence is the sa... |
class ExamplePolicy:
@staticmethod
def getParamValue(paramIndex) :
return 1 + paramIndex
def __init__(self, paramValue):
self.paramValue = paramValue
self.nTested = 0
def getNextSize(self):
return 5
def recordResponse(self, size, ans):
self.nTested += 1
def isDone(self):
return self.nTested > 1
... |
from lib.BeautifulSoup import BeautifulSoup
import re
def strip_search(html):
form_html = BeautifulSoup(html).find('form', action='http://websoc.reg.uci.edu/')
#replace form submit with our own link
form_html['action'] = '/schedules'
#remove 'Display Text Results' button
text_buttons = form_html.findAll(attrs... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# FILE: app/alc_etm_searcher.py
# AUTHOR: haya14busa
# License: MIT license
#
# 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... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#Fox Ning
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import basic
#Three dictionaries for show types of map or unit
NumToMapType = {0:"ๅนณๅ",1:"ๅฑฑๅฐ",2:"ๆฃฎๆ",3:"ๅฑ้",4:"็ฎๅก",
5:"้่ฟน",6:"ไผ ้้จ"}
NumToUnitType = {0:"ๅๅฃซ",1:"็ชๅปๆ",2:"็ๅปๆ",3:"ๆๆๆบ",
4:"่ๆ่
", 5:"ๆฒป็ๅธ", 6:"... |
import sys
from pylab import *
N = 30
X = np.random.rand(N)
Y = np.random.rand(N)
clusterCentreX = np.random.rand(3)
clusterCentreY = np.random.rand(3)
clusters = [[], [], []]
colors = ["red", "blue", "green"]
size = 50
def plotCentre(ax):
ax.scatter(clusterCentreX, clusterCentreY,
marker = "D"... |
from django.db import models
from django.conf import settings
from django.urls import reverse
import photograph
import campi
class Directory(
campi.models.labeledModel,
campi.models.descriptionModel,
campi.models.userModifiedModel,
):
"""
A directory from the original image filesystem. Photographs... |
import os
import sys
path = os.getcwd()
sys.path.append(path)
def calculate_filled_utilities(rated_products, product_num):
count_size = 0
for user_id in rated_products:
count_size += len(rated_products[user_id])
return count_size / (len(rated_products)) / product_num
|
import redis
REDIS_HOST = "localhost"
REDIS_PORT = 6379
REDIS_PWD = ""
def hello_redis():
"""Example Hello Redis Program"""
# Redis Connection object
try:
# The decode_repsonses flag here directs the client to convert
# the responses from Redis into Python strings
# using the defa... |
#First *fork* your copy. Then copy-paste your code below this line ๐
#Finally click "Run" to execute the tests
#Imports the ceil function from the math module
from math import ceil
#Defines the function paint_calc with 3 parameters : height of the wall, width of the wall and coverage
def paint_calc(height, width, co... |
"""
Do not change the input and output format.
If our script cannot run your code or the format is improper, your code will not be graded.
The only functions you need to implement in this template is linear_regression_noreg, linear_regression_invertible๏ผregularized_linear_regression,
tune_lambda, test_error and mappin... |
import random
from datetime import datetime
from datetime import timezone
from senor_octopus.types import Stream
async def rand(events: int = 10, prefix: str = "hub.random") -> Stream:
"""
Generate random numbers between 0 and 1.
This source will generate random numbers between 0 and 1
when schedule... |
import copy
from PIL import Image
import numpy as np
from numpy.core.multiarray import ndarray
from scipy.fftpack import dctn
from scipy.fftpack import idctn
import math
import matplotlib.pyplot as plt
class Dct:
# bs_n is blocksize n.
#imagepath is the input of n.
def __init__(self,imagepath,bs_n):
sel... |
from gaiatest import GaiaTestCase
from OWDTestToolkit.utils.utils import UTILS
from OWDTestToolkit.apps.messages import Messages
class test_main(GaiaTestCase):
test_str = "abcdefghijklmnopqrstuvwxyz"
def setUp(self):
# Set up child objects...
GaiaTestCase.setUp(self)
self.UTILS = UT... |
# coding: utf-8
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx
from sets import Set
import random as rd
# In[132]:
class_CBO = np.genfromtxt('class_weight.txt', dtype=None)
#class_CBO = list(class_CBO)
class_History = np.genfromtxt('history_list.txt', dtype=... |
# coding=utf-8
from django.conf.urls import url
from . import views
urlpatterns=[url(r'^$',views.index_views),
url(r'^login/$',views.login_views),
url(r'^register/$',views.register_views),
url(r'^01-temp/$',views.temp_views),
url(r'02-var1/',views.var_views),
... |
#!/usr/bin/env python
#
# Copyright (c), 2018-2021, SISSA (International School for Advanced Studies).
# All rights reserved.
# This file is distributed under the terms of the MIT License.
# See the file 'LICENSE' in the root directory of the present
# distribution, or http://opensource.org/licenses/MIT.
#
# @author Da... |
# -*- coding: utf-8 -*-
import codecs
import os
import sys
from ltp_parse import LTP_parse
import time
import threading
#initial LTP_parse()
ltp_parser = LTP_parse()
names = locals()
class Sub_Pre:
def __init__(self, file_dir, sub_list, pre_list):
#load dict
sub_name = 'sub'
pre_name = '... |
n, m = map(int, input().split())
mp = []
for i in range(n):
mp.append(list(map(int, input().split())))
d = [[[0 for _ in range(3)] for __ in range(m)] for ___ in range(n + 1)]
ans = 987654321
def minn(a, b):
if a< b:
return a
return b
for i in range(m):
for j in range(3):
d[0][i][j] = ... |
# This one was largely unsuccesful
# I'm guessing the problem lies in me trying to use just positive or negative words to train an ai to classify sentences
# Refer to sentiment1.py for working version
# Train NaiveBayes classifier from text files
import nltk
import os
import sys
# from senticnet4 import senticnet
#... |
# make svr model
import pandas as pd
import numpy as np
from sklearn.model_selection import KFold
import itertools
import ast
import sys
import libsvm.svmutil as svmutil
import os
import concurrent.futures as cc
import functools
import math
from tqdm import tqdm
# Wrapper function, accept param dictionary
def init_tr... |
# noinspection SpellCheckingInspection
PickerRightArrowIconKey = "00B2D882:00000000:38D63245CC037C1F" # type: str
# noinspection SpellCheckingInspection
PickerGearIconKey = "00B2D882:00000000:188D7F9F936DEAA6" # type: str
# noinspection SpellCheckingInspection
PickerLockIconKey = "00B2D882:00000000:144FA1139F00C553... |
from model import firebase_token as token
import web
import pyrebase
render=web.template.render('./views/')
class Insert:
def GET(self):
#Redireccionar al archivo insert.html
try:
return render.insert()
except Exception as e:
result=[]
result.append(... |
from intuitlib.client import AuthClient
from quickbooks import QuickBooks
from quickbooks.objects.customer import Customer
from quickbooks.objects.account import Account
import json
CLIENT_ID = "ABGA9WMqhlrmpP39UxG5Q3H2227bLiXsIWVTeoq0UnQVW2B8fw"
CLIENT_SECRET = "risgBjg1RqjqK8AVDHnYmbwnY46vG0K45v6kG3FH"
# REDIRECT_UR... |
from typing import Mapping, Optional, Type
import numpy as np
import pytest
from starfish import Log
from starfish.image import Filter
from starfish.types import ArrayLike, Axes, Coordinates, Number
from ..label_image import AttrKeys, CURRENT_VERSION, DOCTYPE_STRING, LabelImage
@pytest.mark.parametrize(
"array,... |
"""Eine Sammlung von Verschlรผsselungsfunktionen"""
def text_verschluesseln(text):
"""Verschlรผsselt den รผbergebenen Text und gibt ihn zurรผck"""
verschluesselung = text[::-1]
verschluesselung = verschluesselung.replace("e", "#")
verschluesselung = verschluesselung.replace("a", "?")
return verschlue... |
from datetime import date
ano_nascimento = int(input('ANO DE NASCIMENTO?'))
idade = date.today().year-ano_nascimento
if idade <= 9:
print('Vocรช vai competir em: INFANTIS ')
elif 9 < idade <= 14:
print('Vocรช vai competir em: INICIADOS')
elif 14 < idade <= 19:
print('Vocรช vai competir em: JUNIORES')
... |
# -*- coding: utf-8 -*-
# TODO: Rewrite combinatorically a + b - (a \and b)
def run_problem(n=1000, multiple_set={3, 5}):
total = 0
for num in range(n):
if any_divides(num=num, multiple_set=multiple_set):
total += num
return total
def any_divides(num, multiple_set):
for x in mult... |
from django.db.models.signals import post_save
from django.conf import settings
from django.db import models
from django.db.models import Sum
from django.shortcuts import reverse
from django_countries.fields import CountryField
CATEGORY_CHOICES =(
('S','Shirt'),
('SW','Sport Wear'),
('OW','Outwear')
)
LABE... |
# Copyright 2019 Google LLC. 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 applicable law or a... |
from django.core.files.storage import FileSystemStorage
from django.db import models
from django.core.files import File
fs = FileSystemStorage(location='/media/photos')
class images(models.Model):
Title = models.CharField(max_length=10)
content_image = models.ImageField(upload_to='fs', null=True, bl... |
import libreria
def AgregarSubOpcionA():
#1. pedir contraseรฑa
#2. Guardadr datos en contraseรฑas.txt
universidad=libreria.pedir_nombre("Ingrese universidad: ")
ciudad=libreria.pedir_nombre("Ingrese ciudad de la universidad: ")
contenido = universidad + "-" + ciudad + "\n"
libreria.guardar_datos(... |
import numpy as np
from numpy import *
import os, sys, argparse
import glob
import astropy
from astropy.io import fits
import astropy
from astropy.cosmology import Planck15 as cosmo
from joblib import Parallel, delayed
import scipy
from scipy.interpolate import UnivariateSpline
import yt
#This file will be used to st... |
from django.contrib import admin
from ..models import Board
__all__ = [
'BoardAdmin'
]
@admin.register(Board)
class BoardAdmin(admin.ModelAdmin):
readonly_fields = ('created', 'modified')
|
import sys
file_name = str(sys.argv[1])
f = open(file_name)
output = []
for i in range(3):
f.readline()
num_atoms = f.readline().split()[0]
output.append(str(num_atoms + '\n' + '\n'))
for i in range(int(num_atoms)):
line = f.readline().split()
output.append(line[3] + '\t')
for i in range(3):
... |
#coding ๏ผutf-8
from selenium import webdriver
from chandao_demo.common.Base import Base
"'ๅฐ่ฃ
ๆทปๅ BUG็ๆนๆณ " \
"1.็ปๅฝ " \
" 2.ๆทปๅ BUG " \
"3.ๅคๆญๆฏๅฆๆทปๅ ๆๅ '"
class ZenTaoBug(Base): #็ปงๆฟBase็ๆๆๆนๆณ
url='http://pro.demo.zentao.net/bug-browse-20.html'
#ๅฎไฝ็ปๅฝ
admin_name=('id','account')
admin_pwd=('name','password')... |
# coding: utf-8
from os import *
from Net import *
from signal import *
from BaseModule import *
from GM import *
global server
def usr1Handler(signo, frame):
global server
GM().getLogMgr().logI("่ฟ็จๅ
ณ้ญ")
server.stop()
class Server:
def __init__(self, config):
GM().setServer(self)
... |
#Exercise: combine two lists/arrays
def combine(list_1, list_2):
len1 = len(list_1)
len2 = len(list_2)
join = []
if len1 > len2:
for list in range(len2):
join.append(list_1[list])
join.append(list_2[list])
for remaining_index in range(list,len1):
joi... |
__author__ = 'cynthia_odonnell'
import urllib2
import sys
import numpy as np
import pylab
import scipy.stats as stats
#read data from uci data repository
target_url = ("https://archive.ics.uci.edu/ml/machine-learning-databases/undocumented/connectionist-bench/sonar/sonar.all-data")
data = urllib2.urlopen(target_url)
... |
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (http://tiny.be). All Rights Reserved
#
#
# This program is free software: you can redistribute it and/or modify
# it ... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({'figure.max_open_warning': 0})
from mpl_toolkits.mplot3d import Axes3D
from datetime import date
# REPORTLAB
from reportlab.pdfgen import canvas
from PIL import Image
from io import BytesIO
from reportlab.lib.units import inch, ... |
#Jonathan Poch
#CS 3923
testFile = open("Password Hashes/AshleyMadison.txt", 'r+')
for line in testFile.readlines():
list = line.split(",")
print(line.rstrip() + " " + list[3])
|
class Solution:
def myAtoi(self,str1):
MAX_INT = 2147483647
MIN_INT = -2147483648
n,result,i,sign=len(str1),0,0,1
while i<n and str1[i]==" ":
i+=1
if i<n and str1[i]=="-":
sign=-1
i+=1
elif i<n and str1[i]=="+":
... |
import sys
from collections import deque
NOT_VISITED = -1
# ์
๋ ฅ ๋ฐ๊ธฐ
t = int(sys.stdin.readline().rstrip())
answer = []
dx = [-1, -2, -2, -1, 1, 2, 2, 1]
dy = [-2, -1, 1, 2, -2, -1, 1, 2]
# ํ์ ๊ฐ๋ฅํ ์ขํ์ธ์ง ํ์ธ
def isSearchableCoordiante(x, y, len):
if 0 <= x < len and 0 <= y < len:
return True
# ์ฒด์คํ์ ์ด๋ ๊ฑฐ๋ฆฌ ๊ณ์ฐ... |
from functools import wraps
from flask import g, request
from flask_restx import Resource as RestResource
from core.db import session
from core.exceptions import AuthError, AuthorizationError, BadRequestError
from services import services
def get_current_user():
token = request.headers.get("TOKEN")
if not t... |
from django.contrib import admin
# Register your models here.
from .models import pharmacogenes, drug, snp, star_allele, study
admin.site.register(pharmacogenes)
admin.site.register(drug)
admin.site.register(snp)
admin.site.register(star_allele)
admin.site.register(study)
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import csv
from operator import itemgetter
def getYearMean(df, year):
df = df.query("year ==" + str(year))
return df.price.mean()
def getLinkedProduct(product):
linked_products = pd.read_csv('Linked_products.csv', encoding='UTF-8', delimiter=";... |
class No:
conteudo=""
prox=None
class LSE:
cabeca=None
cauda= None
tam=0 #tamanho da lista
def tamanho(self):
return self.tam
def inserirInicio(self,novo):
if (self.cabeca==None):
self.cabeca=novo
self.cauda=novo
else:
novo.prox=s... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-03-04 14:16
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations... |
# coding:utf-8
from __future__ import unicode_literals
from gensim.models.word2vec import Word2Vec
from datetime import timedelta
from glob import glob
import numpy as np
import codecs
import time
import os
def current_time():
"""
่ทๅๅฝๅๆถ้ด๏ผๅนดๆๆฅๆถๅ็ง
:return:
"""
ct = datetime.datetime.now().strftime(... |
#coding: utf-8
#-------------------------------------------------------------------
# Um programa que recebe dois valores e retorna a soma entre eles.
#-------------------------------------------------------------------
# Somando no Python - Exercรญcio #003
#------------------------------------------------------------... |
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if len(nums) == 0:
return nums
max_so_far = -99999999999999999999999999999999999999999999999
max_ending_here = 0
for i in range(0, len(nums)):
max_ending_here = max_ending_here + n... |
import pygame
import time
import random
from math import sqrt
pygame.init()
screenwidth = 1600
screenheight = 720
#These are the limits for the in-game wall so that players, enemies or bullets can go outside of the walls.
wall_limit_x1 =405
wall_limit_x2 = 1520
wall_limit_y1 = 50
wall_limit_y2 = 665
... |
import pygame as pg
import math
from settings import *
import pytmx
vec = pg.math.Vector2
class TiledMap:
def __init__(self, filename):
tm = pytmx.load_pygame(filename, pixelalpha = True)
self.width = tm.width * tm.tilewidth
self.height = tm.height * tm.tileheight
self.tmxdata = tm
... |
import pandas as pd
from table_detect import table_detect, colfilter
import ast
def get_annotations_xlsx(path):
df = pd.read_csv(path, header=None)
annotate_dict = {}
number_of_rows = df.shape[0]
for r in range(0,number_of_rows-1):
row1 = df.iloc[r,:]
curr_row = row1.tolist()
pr... |
#!/usr/bin/python3
from math import cos,sin,exp
# Initial variables and constants
t=0
h=0.05
# Function to integrate
def f(t,y):
return exp(-0.5*t*t)-y*t
# Starting values for modified Euler, improved Euler, and Ralston
yme=0
yie=0
yre=0
# Apply timesteps until t>6
while t<=6:
# Analytical solution
yex... |
'''
็ฉ้ต็ธไน
'''
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# ไธค่กไธๅ้ถ็ฉ้ต
mat0 = tf.constant([[0,0,0],[0,0,0]])
# ไธค่กไธๅ้ถ็ฉ้ต
mat1 = tf.zeros([2,3])
# ไธ่กไธคๅไธ็ฉ้ต
mat2 = tf.ones([3,2])
# ไธค่กไธๅๅกซๅ
็ฉ้ต(15)
mat3 = tf.fill([2,3],15)
with tf.Session() as sess:
print(sess.run(mat0))
print('*********... |
# -*- coding: utf-8 -*-
#################################################################################
#
# Copyright (c) 2016-Present site-module Software Pvt. Ltd. (<https://site-module.com/>)
# See LICENSE file for full copyright and licensing details.
#########################################################... |
from __future__ import unicode_literals
import frappe
from frappe.model.db_query import DatabaseQuery
from frappe.utils import nowdate
from frappe.utils import flt
from verp.stock.utils import get_stock_balance
@frappe.whitelist()
def get_data(item_code=None, warehouse=None, parent_warehouse=None,
company=None, star... |
"""enterprise URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-ba... |
import random
import logging
class NameAlreadyExists(Exception):
def __init__(self, eventName):
self.name = eventName
def __str__(self):
return self.name
class trackVerification():
def __init__(self, userlist):
self.users = {}
for item in userlist:
self.users[it... |
from tqdm import tqdm
import sys
_ = input()
LEN, J = (int(i) for i in input().split())
def change_base(n, base):
if base == 2:
return n
res = 0
for i in range(33):
if (2**i) & n:
res += base**i
return res
import sympy
def check_number(n):
if sympy.ntheory.primetest.isp... |
#from sklearn.externals import joblib
#clf = joblib.load('classifier.pkl')
#def predict(a):
# predicted = clf.predict(a) # predicted is 1x1 numpy array
# return int(predicted[0])
from flask import Flask,render_template,url_for,request
import pickle
from sklearn.externals import joblib
app = Flask(__name__) #... |
from mrjob.job import MRJob
from mrjob.step import MRStep
from itertools import combinations
import sys
from math import*
import statistics
class ContentBasedRecommendation(MRJob):
SORT_VALUES = True
def steps(self):
return [
MRStep(mapper=self.mapper_phase1, reducer=self.reducer_phase1... |
def swap_case(s):
chars = list(s)
result = []
for c in chars:
if str(c).islower():
result.append(str(c).upper())
elif str(c).isupper():
result.append(str(c).lower())
else:
result.append(c)
return ''.join(result)
#v2: Using List comprehensi... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
DOCUMENTATION = '''
---
module: fail2ban_jail
options:
name:
description: The name of the jail to configure.
required: True
aliases: []
enabled:
description: Whether the jail is enabled or not.
choices: [true, false]
default: true
alias: [state]... |
from smoke.features.steps.openshift import Openshift
from kubernetes import client, config
oc = Openshift()
v1 = client.CoreV1Api()
@then(u'we delete deploymentconfig.apps.openshift.io "jenkins"')
def del_dc(context):
res = oc.delete("deploymentconfig","jenkins",context.current_project)
if res == None:
... |
# -*- coding=UTF-8 -*-
# pyright: strict, reportTypeCommentUsage=false
from __future__ import absolute_import, division, print_function, unicode_literals
import os
TYPE_CHECKING = False
if TYPE_CHECKING:
from typing import Text
_DIR = os.path.dirname(os.path.abspath(__file__))
_ROOT = os.path.dirname(os.path.di... |
# coding:utf-8
'''
@time: Created on 2021-04-05 17:12:34
@author: Xinqi Chen
@Func: CNN_LSTM model and train-val-test
'''
from tensorflow.python.keras.models import Sequential, Model
from tensorflow.python.keras.layers import Dense, Lambda, Input, Reshape
from tensorflow.python.keras.optimizers import Adam
impo... |
# Generated by Django 2.1.11 on 2020-02-13 20:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tracking', '0006_auto_20200213_1716'),
]
operations = [
migrations.AlterField(
model_name='device',
name='hidden',
... |
import os
import numpy as np
from sklearn import metrics
import pandas as pd
import joblib
from sklearn.metrics import roc_curve,precision_recall_curve,auc
import networkx as nx
from optparse import OptionParser
def get_graph_distance(graph, row):
graph_restricted = nx.restricted_view(graph, [], [(row.from_motif... |
import splitfolders
splitfolders.ratio("..Files/BdSL/BdSL_digits/main",
output="..Files/BdSL/BdSL_digits/split", seed=13, ratio=(.8, .1, .1), group_prefix=None)
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
import chromedriver_binary
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import W... |
#!/usr/bin/env python #
# #
# Autor: Michela Negro, University of Torino. #
# On behalf of the Fermi-LAT Collaboration. ... |
# Imports
import json, time, sys, requests
# Colors
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
# Decision Prompt
yes = set(['yes','y', 'ye', ''])
no = set(['no'... |
# -*- coding: utf-8 -*-
# Copyright European Organization for Nuclear Research (CERN) since 2012
#
# 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-... |
from django.shortcuts import render
from django.http import HttpResponse
def home(request):
return render(request, "home.html")
def about(request):
return render(request, "about.html")
def registeration(request):
return render(request, "registeration.html")
def login(request):
return render(request,... |
import xlrd
wb = xlrd.open_workbook("C:\Users\subbu\Desktop\Book.xlsx")
sheet = wb.sheet_by_index(0)
rows = sheet.nrows
for row in range(rows):
print sheet.cell_value(row,0) + sheet.cell_value(row,1)
|
# Generated by Django 3.2.4 on 2021-09-03 01:12
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('paper', '0012_auto_20210... |
"""
Button
click and response
option: command
func() -> call a function, get the returned value
"""
from tkinter import *
def response():
print("I was clicked!")
root = Tk()
root.title('Python GUI - Button')
root.geometry('640x480+300+300')
root.config(bg='#ddddff')
btn1 = Button(root, text='Click me', com... |
# Flask==1.1.1
# praw==6.5.1
# https://towardsdatascience.com/scraping-reddit-data-1c0af3040768
# https://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask
import praw
# from praw.models import MoreComments
import pandas as pd
import json
from flask import Flask, request, jsonify
from flask_c... |
from custom_modules import messages as m
from custom_modules import stock_data as s
from custom_modules import finviz as f
from custom_modules import more_stock_data as z
from custom_modules import investors_hub as ih
class Scraper:
def symbol_getter(self):
self.symbol = input("Enter stock symbol: ")
d... |
"""Forms"""
from flask_wtf import FlaskForm
from wtforms.fields import (
HiddenField,
PasswordField,
SelectField,
StringField,
SubmitField,
)
from wtforms.validators import (
DataRequired,
EqualTo,
Length,
)
from .models import ActionType
class LoginForm(FlaskForm):
"""Login form""... |
import requests
import json
from sys import argv
import os
from dotenv import load_dotenv
load_dotenv()
WEBHOOK_URL_FIBERMC = os.getenv("WEBHOOK_URL_FIBERMC")
post_headers = {
"content-type": "application/json",
}
with open(argv[1]) as f:
post_data = json.load(f)
res = requests.post(WEBHOOK_URL_FIBERMC, j... |
from array import array
import math
class Vector2d0:
typecode = 'd'
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def __iter__(self):
return (i for i in (self.x, self.y))
def __repr__(self):
class_name = type(self).__name__
return '{}({!r}, {!... |
from qt_core import *
# CUSTOM LEFT MENU
class PyDiv(QWidget):
def __init__(self, color):
super().__init__()
self.layout = QHBoxLayout(self)
self.layout.setContentsMargins(0,5,0,5)
self.frame_line = QFrame()
self.frame_line.setStyleSheet(f"background: {color};")
sel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from TechParser.query import *
from TechParser import db, get_conf
import uuid
from Crypto import Random
def remove_from_blacklist(link):
"""Remove article from blacklist by link"""
db.Database.main_database.execute_query(Q_DELETE_FROM_BLACKLIST, [(link,)])
def remov... |
from d7a.system_files.access_profile import AccessProfileFile
from d7a.system_files.dll_config import DllConfigFile
from d7a.system_files.firmware_version import FirmwareVersionFile
from d7a.system_files.system_file_ids import SystemFileIds
from d7a.system_files.uid import UidFile
class SystemFiles:
files = {
S... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.