text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
from __future__ import print_function
import json
import os
import ssl
import subprocess
import sys
import urllib2
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
def check_tls(verbose):
process = subprocess.Popen(
'node lib/tls',
cwd=os.p... |
import datetime
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator
from django.db.models import Count
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from blog... |
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static, serve
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
urlpatterns = [
url(r'^$', views.AgendaView.as_view(), name='event_list'),
url(r'^(?P<path>.*)$', serve, ... |
import os
import json
import time
# connect mysql db
from cr_1111.myConnect import myConnect
"""
IEK URL 合併回 mysql ieknews
"""
if __name__ == "__main__":
cnt = 0
# mysql connect
mydb = myConnect()
urldir = r'E:\專題\crawler_data\iek_url'
# os.walk 會走到檔案才停下來
for dir_path, dir_names, file_names... |
# -*- coding: utf-8 -*-
'''
Copyright of DasPy:
Author - Xujun Han (Forschungszentrum Jülich, Germany)
x.han@fz-juelich.de, xujunhan@gmail.com
DasPy was funded by:
1. Forschungszentrum Jülich, Agrosphere (IBG 3), Jülich, Germany
2. Cold and Arid Regions Environmental and Engineering Research Institute, Chinese Academ... |
from Features import Features
from sklearn import svm
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import BernoulliNB
from sklearn.naive_bayes import MultinomialNB
from sklearn import tree
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from ... |
# -*-coding:utf-8-*-
#这是表单文件
from flask_wtf import Form
from wtforms import StringField,SubmitField,TextAreaField,BooleanField,SelectField
from wtforms.validators import Required,Length,Email,Regexp
from ..models import Role,User
from flask_pagedown.fields import PageDownField
class PostForm(Form):
body=PageDown... |
import time
class HeapSort:
def heapify(arr, n, i):
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i], arr[largest] = arr[lar... |
from django.db import models
from django.contrib.auth.models import User
type_choices = (('0', 'PIN'),
('1', 'PASSWORD'))
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_profile")
coins = models.IntegerField(default=0)
class Pa... |
Number=int(input())
Reverse=0
while(Number>0):
Reminder=Number%10
Reverse=(Reverse*10)+Reminder
Number=Number//10
print(Reverse)
|
#!/usr/bin/env python3
#
# finger_counting.py
#
#
# Parameters: /robot_description URDF
#
import rospy
import numpy as np
from numpy.linalg import inv
from hw6code.kinematics import Kinematics #Check if this library actually exists or if you need to make a setup.py for it
from sensor_msgs.msg import Joint... |
c = 1
while True:
try:
n = 1
a = int(input())
for i in range(a + 1):
n += i
if n == 1:
print('Caso {}: {} numero'.format(c, n))
else:
print('Caso {}: {} numeros'.format(c, n))
if a == 0:
print(0)
else:... |
from unittest import TestCase
from unittest import main as run_tests
from mock import mock_open, patch, MagicMock
from ..firestarter.firestarter import FireStarter
from ..firestarter.readers import HttpApi
from ..firestarter.igniters import Lighter
from ..firestarter.writers import HadoopFileSystem
from ..firest... |
import smbus
BUS = 1 # Which smbus to use, i.e /dev/i2c-1 is bus = 1
ADDRESS = 0x48 # Address of the device to talk to over I2C/smbus
#Setup SMBus access
bus = smbus.SMBus(BUS)
# Read two bytes from register 01, the config register
config = bus.read_word_data(ADDRESS, 0x01) & 0xFFFF
print('Config value: ... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
from .make_coffee import MakeCoffee
__all__ = [
'MakeCoffee',
]
|
# -*- coding: utf-8 -*-
from struct import pack, unpack
class Field(object):
LENGTH = None
def contribute_to_class(self, cls, name):
cls._meta.add_field(self, name)
@classmethod
def guess_length(cls, data):
return cls.LENGTH
@classmethod
def decode(cls, data):
raise ... |
from django.db import models
from django.db.models.query import QuerySet
from django.utils.translation import ugettext_lazy as _
from teams.models import Team
class MatchMixin(object):
pass
class MatchQuerySet(QuerySet, MatchMixin):
pass
class MatchManager(models.Manager, MatchMixin):
def get_querys... |
import requests
import string
base_url = 'http://jh2i.com:50019'
empty_size = 0
req = requests.get(base_url + '/?search=asdf')
empty_size = len(req.content)
def attribFinder(attrib):
req = requests.get(base_url + '/?search=*)(' + attrib + '=*')
size = len(req.content)
if size != empty_size:
prin... |
from cryptography.fernet import Fernet
from django.conf import settings
def encryption_key(val):
f = Fernet(settings.CRYPTOGRAPHY_KEY)
encrypted_token = f.encrypt(str(val).encode())
return encrypted_token
def decryption_key(val):
f = Fernet(settings.CRYPTOGRAPHY_KEY)
decrypted_token = f.decrypt(va... |
def add_two(x, y):
return x + y
lambda x, y: x + y
add_two(10, 5) # 15
(lambda x, y: x + y)(10, 5) # 15
def who(data, identify):
return identify(data)
def my_identifier_function(data):
return data['name']
user = {'name': 'Damiano', 'surname': 'Alves'}
print(who(user, my_identifier_function))
... |
g = {
0: (1,),
1: (0,2,3),
2: (1,3,4),
3: (1,2),
4: (2,6),
5: (6,),
6: (5,4)
}
def DFSUtil(v, visited):
# Mark the current node as visited
visited.add(v)
print(v, end=' ')
# Recur for all the vertices adjacent to this vertex
for neighbor in g[v]:
if... |
from pyfiles.db import position
from pyfiles.model import map
from pony.orm import Required, Optional, db_session
class Overworld(map.Map):
OVERWORLD_SIZE_X = 22
OVERWORLD_SIZE_Y = 22
# Returns the starting position for all characters on the map
@db_session
def get_starting_pos(self) -> (int, int... |
from PyPDF2 import PdfFileWriter, PdfFileReader, PdfFileMerger
from reportlab.pdfgen import canvas
import random
import string
import time
from canvasapi import Canvas as Lms
API_URL = "https://canvas.oregonstate.edu/"
# Canvas API key
API_KEY = "1002~m1ShsxLu5bZY6SbSd5KlXjN9ejluixXwRFVYDvVQhGjIMx46dLJqS81NfZtCeTRJ"
... |
from django.contrib import admin
from .models import Artist, By, Song, User
admin.site.register(User)
admin.site.register(Song)
admin.site.register(Artist)
admin.site.register(By)
|
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
'''video_to_image_and_split_into_four_parts program captures image from webcam and cuts it into four equal parts.
The VideoCapture object is named video.
The webcam port can be changed according to the need by changing the value of "web_cam_port" in line 54 to -1 or 1 for default webcam.
it is usually 0 When the ... |
#Copyright (c) 2017 Joseph D. Steinmeyer (jodalyst)
#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, m... |
#!/usr/bin/env python3
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com>
# SPDX-License-Identifier: BSD-3-Clause
import sys
from amaranth import Signal, Module, Elaboratable, ClockDomain, ClockSignal, Cat, Array
from luna import top_level_c... |
import os
import sys
import unittest
import tempfile
"""
Shifter, Copyright (c) 2016, The Regents of the University of California,
through Lawrence Berkeley National Laboratory (subject to receipt of any
required approvals from the U.S. Dept. of Energy). All rights reserved.
Redistribution and use in source and bina... |
#!/usr/bin/env python3
"""
desc: Chunk class, defines how to create and write data to a chunk
Chunks are binary files. The last 20 bytes of a chunk is the header that can be used to seek to specific
documents in the chunk.
"""
import os
import logging
class Chunk:
def __init__(self, chunk_i... |
"""Implementation of treadmill admin ldap CLI partition plugin.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import click
from ldap3.core import exceptions as ldap_exceptions
import six
from t... |
import numpy as np
import pylab
from scipy import stats
#https://www.cnblogs.com/kylinlin/p/5309703.html
#未完待续:https://www.zhihu.com/question/25949022
|
# Copyright (C) 2010-2013 Claudio Guarnieri.
# Copyright (C) 2014-2016 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
from lib.common.abstracts import Package
from lib.common.rand import random_string
class Generic(Package)... |
from django.shortcuts import get_object_or_404
from rest_framework import mixins
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from .models import Category, Product, ProductPicture
from .serializers import CategorySerializer, ProductSer... |
from typing import List, Union
from dataclasses import dataclass
@dataclass
class Sentence:
tokens: List[str]
raw: str
imgid: int
sentid: int |
# pylint: disable=C0302
"""
TestRail API categories
"""
from pathlib import Path
from typing import List, Optional, Union
from ._enums import METHODS
class _MetaCategory:
"""Meta Category"""
def __init__(self, session) -> None:
self._session = session
class Cases(_MetaCategory):
"""http://doc... |
import pygame
from Board.Buildings.Building import Building
class Base(Building):
def __init__(self, player, tile):
self.Textures = [
pygame.transform.scale(pygame.image.load('images/buildings/baseGreen.png').convert_alpha(), [45, 45]),
pygame.transform.scale(pygame.image.load('im... |
print("Primul curs") |
import numpy as np
import pickle
from experiments.dev import sampling
from scipy.optimize import linear_sum_assignment
import torch
import matplotlib.pyplot as plt
from tqdm import tqdm, trange
def predict_segmentations(dataset, model, device, iou_threshold, min_objprob, num_proposals):
"""Predict the segmentation... |
import turtle
import math
import random
bob = turtle.Turtle()
bob.speed(15)
turtle.getscreen().bgcolor("black")
turtle.hideturtle()
colors = ["yellow", "red", "green", "blue", "orange", "violet", "indigo"]
for i in range(30):
if i%2 == 0:
bob.hideturtle()
bob.circle(100)
bo... |
# Generated by Django 3.0 on 2020-03-20 09:15
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='... |
from tornado import gen, testing
from tornado.testing import gen_test
import tornado
import tornado.ioloop
import tornado.httpclient
import ujson as json
class MyTestCase(testing.AsyncTestCase):
client = testing.AsyncHTTPClient()
name = 'mercedes15'
url = "http://localhost:8098/types/cars/buckets/sport/ke... |
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from torch.autograd import Variable
import numpy as np
import os
from PIL import Image
import torchvision.datasets as dset
import torch.nn.functional as F
from torch.utils.data import DataLoader,Dataset
import random
impo... |
"""
Tests of neo.rawio.axographrawio
"""
import unittest
from neo.rawio.axographrawio import AxographRawIO
from neo.test.rawiotest.common_rawio_test import BaseTestRawIO
class TestAxographRawIO(BaseTestRawIO, unittest.TestCase):
rawioclass = AxographRawIO
files_to_download = [
'AxoGraph_Graph_File',... |
import sys, os, re
import xml.etree.ElementTree as ET
from functools import reduce
def cleanXML(filename, results_dir=""):
origf = open(filename)
temp = open("temp.txt", "w+")
tagf = open(results_dir + filename[filename.rindex('\\') + 1:len(filename) - 3] + "diff", "w+")
loc = 0
c = origf.read(1)... |
import requests
import json
def GET():
name=raw_input("Enter the name u want to search for: ")
uri= "http://localhost:8081/mainhand"
payload={"name":name}
r = requests.get(uri,payload)
print r.status_code
print r.text
def POST():
name=raw_input("Enter the name u want to insert: ")
uri= "http://localhost:8081... |
import sys
import math
def PrintMat(x, transpose):
if transpose:
x = map(list,zip(*x))
s = str(x)
s = s.replace("[","{")
s = s.replace("]","}")
s = s.replace("}, ","}, \n")
print "float fakeMat[4][4] = "
print s + ";"
angle = float(sys.argv[1])
axis = sys.argv[2]
xTranslation = 0... |
# Helper functions
import glob
import os
import numpy as np
import warnings
import autodisc as ad
from io import BytesIO
from PIL import Image
def create_colormap(colors, is_marker_w=True):
MARKER_COLORS_W = [0x5F,0x5F,0x5F,0x7F,0x7F,0x7F,0xFF,0xFF,0xFF]
MARKER_COLORS_B = [0x9F,0x9F,0x9F,0x7F,0x7F,0x7F,0x0F,0x... |
def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code
if __name__ == "__main__":
arr = [12, 65, 23, 87, 55, 13, 18]
bubbleSort(arr)
print("Sorted array is:")
for i in range(len(arr)):
print("%d" % arr[i], e... |
"""Partial derivatives for cross-entropy loss."""
from math import sqrt
from torch import diag, diag_embed, einsum, multinomial, ones_like, softmax
from torch import sqrt as torchsqrt
from torch.nn.functional import one_hot
from backpack.core.derivatives.basederivatives import BaseLossDerivatives
class CrossEntropy... |
"""Projection of conic sections (ellipses ... hyperbolae)
"""
from __future__ import print_function
import numpy as np
class Conic(object):
"""Bowshock shape - surface of revolution of a plane conic section
As the shape parameter `th_conic` is varied, this gives a sequence
from (`th_conic` = 45 - 90) obl... |
# In views.py
#Requests ---> from pydub import AudioSegment
# The convertor voice recognition can work together with another convertor (audio convertor)
@login_required() # an user can only convert a file if is logged in
def fileupload(request): #upload file function plus call the convert program and generates the tx... |
import os
JwtConfig = {
'key' : os.environ.get('JWT_KEY', 'mysecretkey')
}
|
# for python 3.5+, use math.inf for lower versions float("inf")
# If you dont want to use infinity as sentinel, then just find the largest element in the array and add one to it
def mSort(A):
if len(A) == 0:
return A
elif len(A) == 1:
return A
else:
m = (len(A)-1)//2
L = mS... |
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import (View,TemplateView,
ListView,DetailView,
CreateView,UpdateView,
DeleteView)
from . import models
# Pretty simpl... |
# coding: utf-8
# In[1]:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import math
# In[2]:
def define_mask():
mask = [[1,1,1],[1,1,1],[1,1,1]]
for i in range(3):
for j in range(3):
print(mask[i][j], end=" ")
print()
return mask
... |
import os
import re
import math
import sys
import copy
from fnmatch import fnmatch
pattern = "*.txt"
word_list = []
spam = 1
ham = 0
dict_spam = {}
dict_ham = {}
lw = []
pre = {}
listwords = {}
lrate = 0.5
iterations = 3
lambda_value = sys.argv[1]
cwd = os.getcwd()
with open('stopwords.txt') as f:
stop_words = f.... |
# master branch modification test
import xml.etree.ElementTree as ET
import sqlite3
conn = sqlite3.connect('trackdb.sqlite')
cur = conn.cursor()
# make some fresh table using executescript()
cur.executescript('''
DROP TABLE IF EXISTS Artist;
DROP TABLE IF EXISTS Album;
DROP TABLE IF EXISTS Track;
CREATE TABLE Artist... |
import glob
import os
import numpy as np
import scipy
import torchaudio
from speechbrain.pretrained import EncoderClassifier
from tqdm import tqdm
from sklearn.metrics import roc_curve
from scipy.optimize import brentq
from scipy.interpolate import interp1d
from matplotlib import pyplot as plt
import argpars... |
import tensorflow as tf
import pandas as pd
import numpy as np
from sample_generator import sampleGenerator
pse_data_loc = 'data/pse_data.csv'
wb_data_loc = 'data/wb_data.csv'
labels_loc = 'data/output_data.csv'
def calc_inference(pse_data, wb_data):
pse_data = tf.reshape(pse_data, [-1, 90, 412, 1])
wb_data ... |
import math, random
import pygame as pg
from pygame.sprite import *
from player import Bullet
from utils import DamageBar, random_pos, media_path
TRANSPARENT = (0, 0, 0, 0)
class EnemySpawner:
""" Spawn new enemy objects every spawn interval"""
def __init__(self):
self.time = 0
... |
# Import dependencies
import numpy as np
import pandas as pd
import datetime as dt
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
#################################################
# Datab... |
# -*- python -*-
# Assignment: Making and Reading from Dictionaries
# Create a dictionary containing some information about yourself.
# The keys should include name, age, country of birth, favorite language.
my_info = {
'name': 'Firstname Lastname',
'age': 25,
'country of birth': 'USA',
'favorite lang... |
# Assignment "Tic-Tac-Toe" by Federico Pregnolato
# Create a Tic-Tac-Toe game to play in Python
import math
from typing import Counter
def main():
grid_squared = int(input('How many squares do you want on your grid? '))
max_val = grid_squared**2
n_digits = int(math.log10(max_val)) + 1
grid = create_gr... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 12 15:56:48 2017
@author: modellav
"""
# Image Processing
# Import packages
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from skimage import img_as_float
from skimage.restoration import nl_means_denoising
from scipy import misc
from scip... |
class Solution:
# @param A : list of list of integers
# @return an integer
def minPathSum(self, A):
for r in range(len(A) - 1, -1, -1):
for c in range(len(A[0]) - 1, -1, -1):
if r < len(A) - 1 and c < len(A[0]) - 1:
A[r][c] += min(A[r + 1][c], A[r][c +... |
def remove_url_anchor(url):
try:
return url[:url.index("#")]
except ValueError:
return url
'''
Complete the function/method so that it returns the url with
anything after the anchor (#) removed.
Examples:
# returns 'www.codewars.com'
remove_url_anchor('www.codewars.com#about')
# returns 'ww... |
import os
import torch
import torch.nn as nn
import numpy as np
from easydict import EasyDict as edict
import logging
import cv2
import time
from network_factory import get_network
from datasets.loader_factory import get_loader
from utils import load_test_checkpoints, CalculateAcc, \
SelfData, load... |
import time
import base64
#Retrieve Squid proxy info
HOST_IP = input("[+] Enter squid host IP : ") or "10.10.10.200"
HOST_PORT = int(input("[+] Enter squid PORT (Default 3128) : ") or 3128)
CMD = input("[+] Enter command to execute (menu) : ") #or "menu"
#Default ones
HOST = "Host: " + HOST_IP
USER_AGENT = "User-Age... |
import urllib
from urllib.request import urlopen
import re
import http.cookiejar
from http.cookiejar import CookieJar
import time
import html5lib
import requests
import webbrowser
from bs4 import BeautifulSoup
#begin = input('Enter beginning number ')
#end = input('Enter ending number ')
begin = 300
end = 399
mgh_li... |
""" Script to read the 'original' ROOT file from Julia's GENIE simulation and convert it to a ROOT-file, which can be
read from the DSNB-NC.exe generator of the JUNO offline software.
The ROOT-file, which is generated with this script can be used as input for the DSNB-NC.exe generator.
"""
# import ROOT
im... |
# -*- coding: utf-8 -*-
num1=[]
num2=[]
print("Create tuple1:")
while True:
num=int(input())
if num == -9999:
break
num1.append(num)
print("Create tuple2:")
while True:
num=int(input())
if num == -9999:
break
num2.append(num)
numtotal=num1[:]
numtotal.extend(num2)
numsort=nu... |
from .birthday import Birthday
def setup(bot):
bot.add_cog(Birthday(bot))
|
#import module argv for command line input
from sys import argv
#assign variables from command line input
script, filename = argv
#assign var txt to function open(). opens filename variable from command-line input
txt = open(filename)
#simple print of the name of the textfile
print "Here's your file %r:" % filename
... |
from django.conf.urls import *
from media.views import *
from django.conf import settings
from django.contrib import admin
import os.path
from django.views.generic import TemplateView
from django.conf.urls.static import static
from media import rest
from media.rest import *
from rest_framework import routers
from rest_... |
from agrupamento.kmeans import AlgoritmoDeKMeans
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler
import numpy as np
import pandas as pd
print("Agrupamento de vendas de jogos com k-means")
print("Receba indicações de games para jogar com base na plataforma e no gêner... |
import numpy as np
import osmo_camera.rgb.convert as module
def test_convert_to_bgr():
image = np.array(
[
[["r1", "g1", "b1"], ["r2", "g2", "b2"]],
[["r3", "g3", "b3"], ["r4", "g4", "b4"]],
]
)
expected = np.array(
[
[["b1", "g1", "r1"], ["b2"... |
#!/usr/bin/python3
#minimalist python pe library
import sys
import argparse
import struct
from Utils import spaces
import DOSHeader
import PEImageOptHeader
import DOSHeaderDecoder
import PEHeaderDecoder
import PEDataDirDecoder
class PEDataDirHeader:
__PEDataDirHeader_fmt_dict = {\
"VirtualAddress":"I",\... |
#common elements finder function
#define a functions which take 2 list as input and return a list
#which contains common elements of both lists
#example input [1,2,5,8], [1,2,7,6]
#output [1,2]
def common_elements(lista1,lista2):
listaEnd=[]
a=[]
if len(lista1)>len(lista2):
a=lista1
else:
a=lista2
for i in a... |
import dash_bootstrap_components as dbc
from dash import Input, Output, html
accordion = html.Div(
[
dbc.Accordion(
[
dbc.AccordionItem(
"This is the content of the first section. It has a "
"default ID of item-0.",
tit... |
"""This module contains a class which has method to clean the data """
import numpy as np
import pandas as pd
#author: Muhe Xie
#netID: mx419
#date: 11/26/2015
class Clean_Raw_Data:
''' This class contains the origin data and a method to clean the data'''
def __init__(self,origin_data):
'''the constru... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from textwrap import dedent
import pytest
from pants.backend.docker.target_types import (
DockerImageTags,
DockerImageTagsRequest,
DockerI... |
from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
from .models import UserProfile
class RegistrationForm(ModelForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'password']
widgets = {
'user... |
#!/usr/bin/env python
import logging
import os
import json
import boto3
from aws import update_ssm_params
logging.getLogger("boto3").setLevel(logging.ERROR)
logging.getLogger("botocore").setLevel(logging.ERROR)
LOGFMT = (
"[%(levelname)s] %(asctime)s.%(msecs)dZ {aws_request_id} " "%(thread)d %(message)s"
)
DATEFMT... |
from requests import get
def getgeo():
ip=raw_input('Enter ip or hostname to locate: ')
if ip=='': ip=get('https://api.ipify.org').content
for (k,v) in eval(get('https://freegeoip.net/json/'+ip).content).iteritems():
print '{:<13}: {}'.format(k.replace('_',' ').title(),v) |
def pig_latin(word):
return word[1:] + word[0] + 'ay' if len(word) > 3 else word
'''
Task:
Make a function that converts a word to pig latin. The rules of pig latin are:
If the word has more than 3 letters:
1. Take the first letter of a word and move it to the end
2. Add -ay to the word
Otherwise leave the w... |
class Solution(object):
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if m == n:
return m
result = m
for num in range(m+1, n+1):
result &= num
return result
obj = Solution... |
# Generated by Django 2.2.7 on 2019-11-26 19:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('info', '0009_auto_20191123_2357'),
]
operations = [
migrations.AddField(
model_name='category',
name='url',
... |
Dial = input()
ans = 0
for i in Dial:
if ord(i) in [65,66,67]:
ans += 3
elif ord(i) in [68,69,70]:
ans += 4
elif ord(i) in [71,72,73]:
ans += 5
elif ord(i) in [74,75,76]:
ans += 6
elif ord(i) in [77,78,79]:
ans += 7
elif ord(i) in [80,81,82,83]:
an... |
# Import all required libaries
import streamlit as st
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
import numpy as np
import cv2
import os
from PIL import Image
import matplotlib.image... |
import os
import ucfg_utils
import ucfg_use
'''
This class is an entry point for reconfiguration utilities.
'''
class ConfigUtilities(object):
def __init__(self, options, component):
self.options = options
self.component = component
self.backedup = set([])
def setJavaProperty(s... |
'''
Created on Jul 3, 2013
@author: padelstein
'''
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from robot.libraries.BuiltIn import BuiltIn
class RecommendModal():
ROBOT_LIBRARY_S... |
from sklearn import linear_model
import pandas as pd
import numpy as np
from sklearn.datasets import load_boston
from sklearn.cross_validation import train_test_split
boston=load_boston()
print "here is the data",boston
df_x=pd.DataFrame(boston.data,columns=boston.feature_names)
df_y=pd.DataFrame(boston.target)
pri... |
from unittest import TestCase
import simplejson as S
class TestDefault(TestCase):
def test_default(self):
self.assertEquals(
S.dumps(type, default=repr),
S.dumps(repr(type)))
|
__author__ = 'pawan'
import csv
import sys
from collections import defaultdict
from collections import Counter
import random
import math
def prepare_topic_likelihood_data(filename):
"""Generates the prior for the topicID and data structure
The likelihood dict contains the topicID count for each user i.e n... |
name = input().strip()
code = [1] + [ord(i) - 96 for i in name]
no_moves = 0
for i in range(len(code) - 1):
no_moves += min(abs(code[i] - code[i+1]), 26 - abs(code[i] - code[i+1]))
print(no_moves)
|
from unittest.case import TestCase
from pythonbrasil.lista_2_estrutura_de_decisao.ex_11_organizacoes_tabajara import obter_porcentagem_de_aumento
class ObterPorcentagemDeAumentoTests(TestCase):
def test_salario_igual_ou_abaixo_de_280(self):
porcentagem = obter_porcentagem_de_aumento(200)
self.as... |
import os
import logging
import argparse
import numpy as np
from train_and_evaluate import evaluate, train
from model.net import Generator, Discriminator
from data_loader import fetch_dataloader
import utils
import torch
parser = argparse.ArgumentParser()
parser.add_argument('--output_dir', default='Result',
... |
# CHAPTER 1
# Figure 1.1
import numpy as np
import matplotlib.pyplot as plt
p = 1/2
n = np.arange(0,10)
X = np.power(p,n)
plt.bar(n,X)
# Binomial Theorem
from scipy.special import comb, factorial
n = 10
k = 2
comb(n, k)
factorial(k)
# Python code to perform an inner product
import numpy as np
x = np.array([[1],[0],[... |
from enum import Enum
class Element(Enum):
WATER = "water"
EARTH = "earth"
FIRE = "fire"
LIGHT = "light"
DARK = "dark"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.