index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
2,800
9492142a569da1d21b1927e79d97f9cf6276efdc
#!/usr/bin/env python # -*- coding:utf-8 -*- # # Author : cold # E-mail : wh_linux@126.com # Date : 13/09/05 11:16:58 # Desc : # import twqq from setuptools import setup requires = ["tornado", "pycurl", "tornadohttpclient"] packages = ["twqq"] entry_points = { } setup( name = "twqq", ...
2,801
3e54d2ddddf6f8186137e5801ca4ba40d1061987
from binary_search_tree.gen_unique_bst import gen_unique_bst # The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. def max_depth(root): if not root: return 0 return max(max_depth(root.left), max_depth(root.right)) + 1 # The minimum depth...
2,802
e77c855ba87bc36ab09b0a3eca5c1b7123535794
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 1 17:08:06 2023 @author: Alice Wells Plotting script for Figure 10 in Wells et al., 2023 Aerosol extinction coefficient vertical profile averaged longitudinally. Averaged monthly CALIOP (centre) aerosol extinction coefficient vertical profiles ...
2,803
58f8924a9cd2af4106e54b163e96bcd8517282b5
import logging import azure.functions as func def main(event: func.EventHubEvent): logging.info('Python EventHub trigger processed an event: %s', event.get_body().decode('utf-8'))
2,804
b20bf203a89ed73cc65db50fdbef897667fe390f
from __future__ import division from __future__ import print_function import numpy import tables as PT import scipy.io import sys, math import tables.flavor from flydra_analysis.analysis.save_as_flydra_hdf5 import save_as_flydra_hdf5 tables.flavor.restrict_flavors(keep=["numpy"]) def main(): filename = sys.argv[...
2,805
143f6ee38413a0713c18281e9737c09d9947a61a
try: a = int(input("Enter a:")) b = int(input("Enter b:")) c = a/b except: print("Can't divide with zero")
2,806
a860e6670719a733e75c7580cf2e07765b0777eb
from clients.models import Budget from clients.models import Spend from datetime import date as datetimedate from datetime import datetime from datetime import timedelta from django.db import models from rest_framework.exceptions import ParseError import math import pandas as pd class CampaignPerformance: """ Get...
2,807
4bbf0a0fadc506ad3674912f1885525a94b5b1e9
#!d:\python_projects\env2\scripts\python.exe # EASY-INSTALL-DEV-SCRIPT: 'Django==2.1.dev20180209010235','django-admin.py' __requires__ = 'Django==2.1.dev20180209010235' __import__('pkg_resources').require('Django==2.1.dev20180209010235') __file__ = 'D:\\python_projects\\ENV2\\django\\django\\bin\\django-admin.py' exec(...
2,808
7f4c6e4a5627b44b9a700d2de4f9caca0ae8b17c
N=int(input("N=")) K=int() K=0 while N>=2: N=N/2 K=K+1 print("K=",K)
2,809
75ba2448897bed8388a7b8d876827461e1bc9dd7
import json import requests import itertools import logging from shared_code.config.setting import Settings from TailwindTraderFunc.cognitiveservices import CognitiveServices from shared_code.storage.storage import BlobStorageService class TailwindTraders(): def __init__(self, req): self._settings = Sett...
2,810
00a2992af78f9edadd3f4cbc7d073c1f74fcd9a2
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set() import bootcamp_utils import numba @numba.jit(nopython=True) def backtrack_steps(): """ Compute the number of steps it takes a 1d random walker starting at zero to get to +1. """ # Initialize p...
2,811
dbc599a03d91f369d862f6cc90c31221747ead80
################################################################################ # run_experiment.py # # Ian Marci 2017 # # Defines knn classifier and runs 4-fold cross validation on data in ...
2,812
5dca187cfe221f31189ca9a9309ece4b9144ac66
#!/usr/bin/python3 #coding:utf-8 """ Author: Xie Song Email: 18406508513@163.com Copyright: Xie Song License: MIT """ import torch def get_sgd_optimizer(args, model): opimizer = torch.optim.SGD(model.parameters(),lr=args.lr,weight_decay=1e-4) return opimizer
2,813
b93cd5ad957da37b1a4cca1d465a67723110e926
import sys import unittest import random from k_order_statistic import k_order_statistic test_case_find = [ ([0], 0, 0), ([-1, -1, -1, -1], 3, -1), ([-1, -1, -1, -1], 1, -1), ([-1, 0, 3, -10], 3, 3), ([-1, -2, -3, -4, -5], 0, -5), ([1, 2, 3, 4, 5], 1, 2), ([True, False, True], 2, True), ...
2,814
d698fa1b43387ee0b73687df2764c30e04ee6fd0
from django.db import models class ProdutoManager(models.Manager): def for_categoria(self, categoria): return self.filter(categoria=categoria)
2,815
f1aa12ec4ee2482db8abf1121a3443502544e1a2
import sys sys.setrecursionlimit(10**6) n, s = map(int, input().split()) value = list(map(int, input().split())) count = 0 def recursive(index,sum): global count if index == n: if sum == s: count += 1 return recursive(index+1, sum + value[index]) recursive(index+1, su...
2,816
10cefb1cf2392fdcd368f11d0d69774a9ffa73ec
# importing libraries import cv2 import numpy as np import argparse aq = argparse.ArgumentParser() aq.add_argument('-i', '--input', required=True, help="input image path") aq.add_argument('-o', '--output', help="path where you want to download the image") args = vars(aq.parse_args()) # reading image img = cv2....
2,817
e99a81a5600aad6111bb2694cbda02021ccfd71c
# -*- coding: utf-8 -*- print ("—— 七、Python爬虫实战演练:爬取百度百科1000个页面的数据 ——"); print ("—— 7.2、调度程序 ——"); print ("————— Python爬虫:1、总教程程序 ———————————————"); from Reptilian.baike_spider import url_manager, html_downloader, html_parser, html_outputer class SpiderMain(object): # 构造函数初始化各个对象 def __init__(self): ...
2,818
2c4fe8015968b8a78c7b2ea33ac5e21e01c82e6e
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import tinymce.models class Migration(migrations.Migration): dependencies = [ ('book', '0002_auto_20180402_2344'), ] operations = [ migrations.CreateModel( name='HeriInfo...
2,819
ea35180daecb8ca4b9bd351a949a4757b97322ec
#HOW TO BUILD A SIMPLE CALCULATOR #1.ADD #2.SUBTRACT #3.MULTIPLY #4.DIVIDE print("Select an operation to perform: ") print("1.ADD") print("2.SUBTRACT") print("3.MULTIPLY") print("4.DIVIDE") print("5.SQUARE ROOT") operation=input() if operation=="1": a=input("Enter first number: ") b=input("Enter sec...
2,820
2a1d31b2123c11af3fce571287d3dad00a9b0086
from django.db import models from django.utils import timezone class Test(models.Model): word1 = models.CharField(max_length=50) word2 = models.CharField(max_length=50) word3 = models.CharField(max_length=50) answer = models.CharField(max_length=50) #def __str__(self): # return self.word1, ...
2,821
8410ff0806766a09d346e930123a2696bebb4b60
# -*- coding: utf-8 -*- # # Copyright (C) Red Hat, 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 or ...
2,822
e50517910e191594034f60a021647f4415b6f1c4
from accounts.models import User from django.forms import ModelForm from django import forms from django.contrib.auth.forms import UserCreationForm class UserRegistrationForm(UserCreationForm): email = forms.EmailField(required=True) password1 = forms.CharField( widget=forms.PasswordInput, # help_text=password_...
2,823
8a192fc08a65c80b8733a9d07374156c09f36598
#!/usr/bin/env python3 # Lesson_5 Activity 2 Mailroom Part 2 import os def page_break(): """ Print a separator to distinguish new 'pages'""" print("_"*75+"\n") def get_amount(): """Get valid donation amount from user""" while True: try: amount = input("How much did they donate:...
2,824
c1c6db4dbd1e6719d30905babd6ccf5b1e76e75d
import json from iamport import Iamport from django.views import View from django.http import JsonResponse from share.decorators import check_auth_decorator class PaymentView(View): @check_auth_decorator def post(self, request): data = json.loads(request.body) try: user = request...
2,825
e53d4bb853eb54e4dfedf7126480e2c3e1af1378
# -*- coding: utf-8 -*- """TODO """ import logging import numpy import evo.gp.support import evo.sr import evo.utils.stats class RegressionFitness(evo.Fitness): LOG = logging.getLogger(__name__ + '.RegressionFitness') def __init__(self, train_inputs, train_output, error_fitness, handled_e...
2,826
3bdf3a48451b83347a6c9a9851b5b85b608f0b63
class BinarySearchTreeNode: def __init__(self, node_data): self.data = node_data self.left = None self.right = None def bst_contains(root: BinarySearchTreeNode, number): if root is None: return 0 if(root.data == number): return 1 elif(root.data < number): ...
2,827
3c193decc4a1f284de953003fbba434d6e798b24
from django.db.models import Q from django.contrib import messages from django.views.generic import ListView, DetailView from django.shortcuts import get_object_or_404, redirect, render from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.views.decorators.http im...
2,828
0f4864b745768994ea55a931e4d8b0681c058465
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/web_client_api/__init__.py from soft_exception import SoftException class WebCommandException(SoftException): def __init__(self, description): super(WebCommandException, self).__init__(description)
2,829
77c7ca3391426d1e56e15a93ef3e6227a45140fc
def fun(st,n): suffix=[0 for i in range(n)] prefix=[0 for i in range(n)] count=0 for i,val in enumerate(st): if(val=='*'): if(i==0): prefix[i]=0 count+=1 else: prefix[i]=prefix[i-1] count+=1 else: ...
2,830
2ec8d3853ea4a99d4e764c6c24d7b5a3afb64f63
# Generated by Django 2.1.7 on 2019-05-31 18:45 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), ('events', '0004_auto_2019...
2,831
1cc696410a5d2eaf294d032c04a96974d5ef5db0
"""2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ from fractions import gcd def smallest_divisible(nmax=20): smallest = 1 for i in range(1, nmax+1):...
2,832
8d5978bc579115eb3065dce1bae08f1790f2d83c
from setuptools import setup, find_packages from os.path import join, dirname, abspath import io here = abspath(dirname(__file__)) with open(join(here, 'VERSION')) as VERSION_FILE: __versionstr__ = VERSION_FILE.read().strip() with open(join(here, 'requirements.txt')) as REQUIREMENTS: INSTALL_REQUIRES = REQU...
2,833
56a41f432d332aaebbde15c52e133eee51b22ce1
import logging from queue import Queue import concurrent.futures """ Post processing decorater logic for FtpDownloader """ class FtpDownloaderPostProcess: def __init__(self, ftp_downloader, post_processor, num_workers=None, config_dict=None): self.post_processor = post_processor self.ftp_downlo...
2,834
0afb07d9b48ec91909aac6782dd3cf2fbe388fb4
input("") things = [] class thing(): def __init__(self, loc, mass = 1, xrad = 1, yrad = 1): global things things += [self] self.location = loc self.gravity = [0, -0.5] self.__velocity = [0, 0] self.mass = mass self.xrad = xrad self.yrad = yrad self.immobile = False self.collidab...
2,835
d2d04686b3d7f8d01ca195750ca625baa06ed098
import numpy as np import matplotlib.pyplot as plt def sample_1(N): numeros=np.array([-10, -5, 3, 9]) return np.random.choice(numeros, N, p=[0.1, 0.4, 0.2, 0.3])#devuelve distro aleatoria con las probabilidades indicadas def sample_2(N): return np.random.exponential(0.5,N)#devuelve numeros aleatorios con distro ex...
2,836
53b56cf9265a658d999388f0a1e03d7ceb186213
from newspaper import Article import random import string from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity import nltk import numpy as np import warnings import speech_recognition as sr warnings.filterwarnings('ignore') nltk.download('pun...
2,837
99c27d13349eba391866cfed25cc052b40910ea5
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-06-23 17:10 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('sepomex', '0006_auto_20151113_2154'), ] operations...
2,838
fa4ab3ed5c653633879b5ba2c078c896aa3eb0c6
"""Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.""" class Solution(object): def longestSubsequence(self, arr, difference): ...
2,839
3a2b1ddab422d450ad3b5684cbed1847d31fb8e6
from sys import stdin last_emp = emp_id = '' for line in stdin: data = line.strip().split(',') if last_emp != '' and last_emp != emp_id: print(f'{emp_id},{emp_surname},{emp_name},{position},{dep_id},{dep_id},{dep_name},{num_of_emp},{head}') if len(data) == 5: last_emp = emp_id em...
2,840
d120172e65f329b1137df38b693e5fe7145bc80d
#!/usr/bin/env python3 # -*- coding: utf-8 -*- "Widget for exporting the data" import asyncio from pathlib import Path from typing import List from bokeh.models import Div, CustomAction, CustomJS from view.dialog import FileDialog from utils.gui import startfile class ...
2,841
968cfcfe9d31adcd3a67a88a66e5ebe7b719be8d
#!C:\Python27\python print('Content-Type:text/html\n\n') print (""" <html> <head> <link href="iconTech.png" rel="icon"/> <meta name="viewport" content="width=device-width,intial-scale=1.0"/> <link href="../css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="../css/bootstrap-theme.min.css" rel=...
2,842
21a7fd5148f73ac47adafc9d5c2361ebe318ae59
from tree import Tree, createIntTree t = createIntTree() print('show', t.root.show()) print('sum', t.root.sum()) print('find 3', t.root.find(3) != False) print('evens', t.root.evens()) print('min depth', t.root.min_depth())
2,843
89a75ae980b7b48d33d0e8aa53ec92296dbfbc8e
import os import json import pytest from datetime import datetime from collections import OrderedDict import numpy as np import pandas as pd from sqlalchemy.exc import ProgrammingError import pawprint def test_create_table_with_default_options(pawprint_default_tracker_db): """Ensure the table is correctly crea...
2,844
97dfcce6e82ef33334b49de72bb126150dfef196
import os import numpy as np from . import tmp_dir_fixture from . import TEST_SAMPLE_DATA def test_tensor_dataset_functional(): from dtoolai.data import TensorDataSet tds_uri = os.path.join(TEST_SAMPLE_DATA, "example_tensor_dataset") tds = TensorDataSet(tds_uri) assert tds.name == "example_tenso...
2,845
f658959bf7fa5e02a577119930c9b9c1ef59f432
from src.testcase.case import Case from src.utils import * from src.protocol.register import get_conn from src.precondition import * class OneCase(object): """ Main flow of running one case's autotest """ PASS = True FAIL = False def __init__(self, case_path, *args, **kwargs): self._c...
2,846
2deb73c7d2588ea1a5b16eb1ed617583d41f0130
''' Applies the mish function element-wise: .. math:: mish(x) = x * tanh(softplus(x)) = x * tanh(ln(1 + e^{x})) ''' # import pytorch import torch from torch import nn # import activation functions import echoAI.Activation.Torch.functional as Func class Mish(nn.Module): ''' Applies the mish function ele...
2,847
2192e328bdfa454ff1d1f66a05fb6a322c48b244
from . import FixtureTest class GatesLineGeometry(FixtureTest): def test_linear_gate(self): # Add barrier:gates with line geometries in landuse # Line barrier:ghate feature self.load_fixtures(['http://www.openstreetmap.org/way/391260223']) self.assert_has_feature( 16, ...
2,848
d2da95f44e814accd3a91c5e8497ceff85c98711
import os import zipfile import cv2 import numpy as np from sklearn import svm from sklearn import cross_validation from sklearn.externals import joblib import matplotlib.pyplot as plt """ Global constants """ data_zip = "data.zip" # The zip archive clean_files = [".csv", ".jpg"] # File extensions ...
2,849
51563f52e700a286451663a6e837d56e104c2c72
from django.db import models from django.utils.text import slugify import misaka from django.urls import reverse from django.contrib.auth import get_user_model from django import template register=template.Library() User=get_user_model() #call things out of users current session # Create your models here. class G...
2,850
798d5c68a0aa2057c28d7f333905f20fef965d70
queries = [] for n in range(2, 51): for k in range(n, n*n+1): queries.append((n, k)) print(len(queries)) for n, k in queries: print(n, k)
2,851
34ccaaf5eb47afd556588cd94cddbddaee1f0b53
import matplotlib.pyplot as plt import cv2 # 0 img = cv2.imread('test.jpg', cv2.IMREAD_GRAYSCALE) # IMREAD_COLOR = 1 # IMREAD_UNCHANGED = -1 cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() # cv2.imwrite('watchgray,png', img) plt.imshow(img, cmap='gray', interpolation='bicu...
2,852
894ce07c6443208483be2d3ef1409f12f24d99f3
import json import glob import argparse from model.NewModel import runModel from collections import namedtuple import csv OutputFile = "./HealthSimOutputSheet.csv" parser = argparse.ArgumentParser(description='Select policy file') parser.add_argument('-p', type=str, default='default', help='name of a a policy file') ...
2,853
b3b4d27b60c71cbd979ad4887fa80408665ea1ac
import sqlite3 import os #Search for a patient name #Every doctor enter a name, it will find the patinet name that is similar to the patient name #Once a match is found, the system will output a list of matched patient names. #Then, the doctor select the patient to continue def patientSelect(CONN, staff): c = CONN...
2,854
398cb05218a9772a0b62fdfbacc465b26427827d
""" Exercise 3 from the Python tutorial Part 1 on: https://codeandwork.github.io/courses/prep/pythonTutorial1.html """ import math print("Give the length of each side in order to compute the area of a triangle.") lenA = float(input("Give the length of side A:")) lenB = float(input("Give the length of side B:")) len...
2,855
5e29c6d1034f6612b0081037f8dc679b49f1dbef
# Copyright 2016 Tesora, Inc. # 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 ...
2,856
d8befc4a79176aefcccd3dceddf04ca965601e5c
# ---------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License # ---------------------------------------------------------------------- """Contains the Plugin object""" import itertools import os import sys ...
2,857
cfcce8c760f6ba49ce450d78782cb8f3b5fc1188
import cv2 import numpy as np import copy imgpath = 'D:\\DIP-Project1/b.jpg' img = cv2.imread(imgpath) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.imshow('img', img) row = len(img) col = len(img[0]) def medianflt(img, i, j, msize, mr, mc): pxls = [] for a in range(msize): for b in range(msize): ...
2,858
cc637d14ce2106fcc3b8bbb54e497691e72a3f65
# This source code is part of the Biotite package and is distributed # under the 3-Clause BSD License. Please see 'LICENSE.rst' for further # information. import warnings from tempfile import TemporaryFile import glob from os.path import join import pytest import numpy as np import biotite.structure as struc import bi...
2,859
5bfb69d1608b397d6a19e663164a30089e4f67ad
""" GoldenTemplate based on the golden-layout library. """ from __future__ import annotations import pathlib from typing import TYPE_CHECKING, Literal import param from ...config import config from ...io.resources import JS_URLS from ..base import BasicTemplate if TYPE_CHECKING: from ...io.resources import Res...
2,860
f6d81387f61ac4150cd6279121780b7113517b1e
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 4 15:21:29 2021 @author: diego """ import subprocess import os import numpy as np if __name__ == "__main__": path_clusters = snakemake.input[0] path_clusters = "/".join(path_clusters.split("/")[:-1]) + "/" merge_vc...
2,861
c84175edb88f5b9219c22ec717ec30bb530982a2
#!/usr/bin/env python3 import sys from pathlib import Path def print_usage(): sys.stderr.write(''' Find the length of the biggest line in the file. Usage: ./biggestLine <delimiter> <field number - first element is 0> <file path> ''') def main(): if len(sys.argv) != 4: print_usage() ...
2,862
190f0bcbac946c410d964860fd5be8718011caa8
# -*- coding: utf-8 -*- import os import re import datetime import sys import codecs import logging import logging.handlers import fnmatch import time import argparse from antlr4 import * from antlr4.tree.Trees import Trees from lxml import etree from AknJudgementClass import AknJudgementXML from AknLega...
2,863
03270285c6dc99d8dcb9804270421f36b573048c
import time from selenium import webdriver import os from selenium.webdriver.common.by import By with open("file.txt", "w") as file: content = file.write("Tanyuhich") try: browser = webdriver.Chrome() browser.get("http://suninjuly.github.io/file_input.html") input1 = browser.find_element_by_name('...
2,864
69d7e7eb644a67ee921086005f0a55f39507f361
group = { 'A': 20, 'B': 15, 'C': 10 } def split_the_bill(x): owed_dict = {} sum = 0 people = 0 for key in x: sum = sum + x[key] people = people + 1 price_pp = sum/people for key in x: owed_value = x[key] - price_pp owed_dict[key] = rou...
2,865
be6a2e45f735fe578392b03c3030890b6cd5b4bc
""" Listing 1.36 Python extends the basic grouping syntax to add named groups. Using names to refer to groups makes it easier to modify the pattern over time, without having to also modify the code using the match results. To set the name of a group, use the syntax (?P<name>pattern) Use groupdict() to retrieve the d...
2,866
961643e93582bd92e148d00efebbfe38f99100fc
class SurveyRepository: def __init__(self): self._surveys = {} def get_survey(self, survey_id): if survey_id in self._surveys: return self._surveys[survey_id] def save(self, survey): self._surveys[survey.id] = survey
2,867
c4c068c7b50d1811f224701ad7e95d88f6734230
# -*- coding: utf-8 -*- """ This module provides a function for splitting datasets.""" from skmultilearn.model_selection import IterativeStratification def iterative_train_test(X, y, test_size): """ Iteratively splits data with stratification. This function is based on the iterative_train_test_split func...
2,868
e0ce8a8ad9c842b013bbb1ea1c585b6c4c2a68f5
# config {stack,buffer,label} def get_features_da(config,sent_dict): features = [] # TODO Improve Features if len(config[0]) > 0: # Top of stack. top = config[0][-1] top_stk_token_feature = 'TOP_STK_TOKEN_'+str(sent_dict['FORM'][top].lower()) features.append(t...
2,869
258b28153124ce42578c9eede429354069d8a7d6
#Opens the file that the user specifies fileopen = open(input("Please enter the name of the file that you wish to open."), 'r') #Reads the lines within the file and determines the length of the file lines = fileopen.readlines() count = len(lines) #Count is how long the file is, so number is the index values basically...
2,870
ab610af97d2b31575ea496b8fddda693353da8eb
import numpy as np import cv2 from PIL import Image import pytesseract as tess #Function to check the area range and width-height ratio def ratio(area, width,height): ratio = float(width)/float(height) if ratio < 1: ratio = 1/ ratio if (area<1063.62 or area> 73862.5) or (ratio<3 or ratio> 6): return False...
2,871
fcb0fb439db77c4d57c449ec8f720dbd3fef5abc
# Employee Table's Dictionary employee={ 1001:{ "empname":"Ashish", "Designation Code":'E', "Department":"R&D", "Basic": 20000, "HRA": 8000, "IT": 3000 }, 1002:{ "empname":"Sushma", "Designation Code":'C', "Department":"PM", "Ba...
2,872
82ce6304977d468945526824ade1500e10d25d09
import datetime def days_count(year, month, hour): point = datetime.datetime(year, month, hour, 0, 0, 0, 000000) now = datetime.datetime.now() interval_day = point - now return interval_day.days messages = { '猫钰钰 五月有砖搬': '距离 猫钰钰 上岗还有 {} 天'.format(days_count(2019, 6, 1)), # 6.1 上岗 'AD Zh': '...
2,873
1bebd3c18742f5362d2e5f22c539f6b13ad58d2a
class Point: def __init__(self,x,y): self.x=x self.y=y def __str__(self): return "({0},{1})".format(self.x,self.y) def __add__(self, other): self.x=self.x+other.x self.y=self.y+other.y return Point(self.x,self.y) p1=Point(1,2) p2=Point(3,4) p...
2,874
8503998fc881f47dc695d3ea4c7f56fa65a96e8a
from deuces.card import Card from deuces.deck import Deck from fast_utils.hand_strength.original_HS import * from fast_utils.hand_strength.nn_HS import encode_hs from fast_utils.expected_hand_strength.nn_EHS import * from keras.models import load_model def read_lookup_table(hole_cards, lookup_table): """ Reads...
2,875
cc9485dea0975a0974f037b129816a9359b2b622
# Copyright 2016 Huawei, Inc. 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 appli...
2,876
5f2110bcab465a85ad7db1b0e01a882b3ed305a5
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-04-12 14:41 from __future__ import unicode_literals import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('ashesiundergraduate', '0016_orphanage')...
2,877
0802aac57cd28104cdb6ff45d993aa224f80b830
from source.ga.population import create_population, random_genome def test_create_population(race_example): population = create_population(race_example, 20) assert population def test_random_genome(race_basic): genome = random_genome(race_basic) assert genome def test_random_genome_example(race_ex...
2,878
9a2b5b9b2b2f9532b5d0749147aca644c2ac26e3
import base64 import json class BaseTestCloudAuth: """ Required setup: initialize test case teardown: del items for test decode: check decoded token and assigned info """ ACCESS_TOKEN = "" SCOPE_ACCESS_TOKEN = "" ID_TOKEN = "" TESTCLIENT = None def assert_get_res...
2,879
d2325b07d11e64df0b26d0de9992a6f496e92a30
# -*- coding: utf-8 # @paidatocandeira # Acessa arquivo do CADASTRO NACIONAL DE EMPRESAS INIDÔNEAS E SUSPENSAS (CEIS) que está no portal da Transparência # import pandas as pd # Parte 2 - pode rodar no Jupyter para ver resultados # Método lendo direto o arquivo disponível para download (http://www.portaltransparencia...
2,880
e24c3f6ce2e65305f955dcede9edc0b497f6e74c
# def add(a,b): # x = a + b # # # the return value gets assigned to the "result" variable # result = add(3,5) # print result # this should print 8 # # def multiply(arr,num): # for x in range(len(arr)): # arr[x] *= num # return arr # # a = [2,4,10,16] # b = multiply(a,5) # print b # # # dog = ("Canis F...
2,881
b131107d2161634e2c09e0b3ab80dd322d13fbc2
# TODO: Add correct copyright header import io from unittest.mock import mock_open, patch from django.test import TestCase from importer.models import * from importer.tasks import * from importer.tests import mock_data class MockResponse: """ This class will be used by the mock to replace requests.get ...
2,882
c3aee5d822d48c9dc826f8f2f8d4a56e11513b9c
import os import torch from data_loader import FER from torch.utils.data import DataLoader from tqdm import tqdm # from tensorboardX import SummaryWriter import model as md # train_writer = SummaryWriter(log_dir="log_last_last_last/train") # valid_writer = SummaryWriter(log_dir="log_last_last_last/valid")...
2,883
ccdae522983ddc7c02e221ab5c1bc32683358a7b
#!/usr/bin/python -tt # snmp3_test # Claudia # PyCharm __author__ = "Claudia de Luna (claudia@indigowire.net)" __version__ = ": 1.0 $" __date__ = "10/23/16 11:25 AM" __copyright__ = "Copyright (c) 2015 Claudia de Luna" __license__ = "Python" #from __future__ import print_function import sys import snmp_helper # P...
2,884
9b88a3976d522bdfd38502e29eefc1f1a0c29ed2
# -*- coding: utf-8 -*- """ Created on Sun Apr 29 15:10:34 2018 @author: nit_n """ from gaussxw import gaussxwab from numpy import linspace, arange from pylab import plot, show, xlabel, ylabel from math import pi, exp, sqrt k = 1.38065e-23 # joules/kelvin h = 6.626e-34 # joules lam1 = 390e-9 # meters ...
2,885
92ee66565eb1d0e3cd8fa1ec16747f15e0d92be8
#!/usr/bin/env python3 import operator from functools import reduce import music21 def get_top_line(piece): top_part = piece.parts[0] if len(top_part.voices) > 0: top_part = top_part.voices[0] # replace all chords with top note of chord for item in top_part.notes: if isinstance(item...
2,886
984efa858e782777472d84aab85471616a05b0e0
import sys from io import BytesIO import telegram from flask import Flask, request, send_file from fsm import TocMachine API_TOKEN = '375541027:AAFvLkySNkMSGgOl7PtsPIsJgnxophQpllQ' WEBHOOK_URL = 'https://a140f4ad.ngrok.io/show-fsm' app = Flask(__name__) bot = telegram.Bot(token=API_TOKEN) machine = TocMachine( ...
2,887
09c6dd0f32b8d71dacdd8b10d995ea1575f91f6f
#!/usr/bin/env python import mincemeat import sys from mapinput import FileShardsMapInput from mapinput import JsonFileMapInput def mapfn(k, v): for w in v.split(): yield w, 1 def reducefn(k, vs): result = 0 for v in vs: result += v return result s = mincemeat.Server() s.map_input =...
2,888
5f48c7a68cb9734d84dee2cf8ff4d7be490cf328
# Bradley N. Miller, David L. Ranum # Introduction to Data Structures and Algorithms in Python # Copyright 2005 # __all__=['BinaryTree', 'Stack'] class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append...
2,889
5a2716fc7b4c0a56fbd0de5d45d71fb33320adf0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 4 20:28:44 2019 @author: nicholustintzaw """ #################################################################################################### ####################################################################################################...
2,890
b7f443521e165f327aae9ff5d7bbb7b8462abeb5
primos = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] # números entre (8 - 26) e (44 - 44) intervalo = list(range(8, 27)) + list(range(49, 50)) is_magic = [] for n in primos: quadrado = n ** 2 if quadrado in intervalo: is_magic.append(quadrado) print(len(is_magic)) # 3
2,891
d8c9e1098dde9d61341ebc3c55eada5592f4b71a
import cgi import os import math import sys from datetime import datetime sys.path.append(os.path.join(os.path.dirname(__file__), 'pygooglechart-0.2.1')) from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from pygooglechart import PieChart3D from LPData import Totals fr...
2,892
b78ad3a55eb27fd91f89c22db07fadca297640ab
"""Vista de Autorizaciones (Clientes/Especialistas/Vendedores).""" from django.shortcuts import render from dashboard.json2table import convert from django.utils.translation import ugettext_lazy as _ from api.connection import api from login.utils.tools import role_admin_check from django.utils.decorators import method...
2,893
281f2f47f9d7f0d87a354d37f9ff2c14a5598068
# -*- coding: utf-8 -*- """ Created on Mon Jan 7 15:26:08 2019 @author: Qlala """ import numpy as np; import random as rand; import os; #os.system("del test_frame2.txt") #frame=open("test_frame2.txt","w"); #ba=bytearray(rand.getrandbits(8) for _ in range(400000)) #frame.write("0"*1000000) #frame.close() #ba.decode('...
2,894
156b3e09a65402d4f964c2886b8f5519168eb13a
#! /usr/bin/python2.7 # -*- coding: utf-8 -*- import numpy as np import pandas as pd import pylab as pl x = range(1, 19) d = pd.read_csv('data.csv') pl.clf() pl.plot(x, d['reelection'], 'o-', label='reelection') pl.plot(x, d['rerun'], 'o-', label='rerun') pl.plot(x, d['ratio'], 'o-', label='incumbent ratio') pl.fill...
2,895
0018cbb1d945ad1b6469804e7993afee44406fd1
############################################################################## # Nombre : import.py # Descripción : It takes the information from Transfom.sh Initial Node # Final Node and HAVERSINE Formule # # Parámetros: # Realizado Por : # # HISTORIAL DE CAMB...
2,896
42fa0aa98e2d3336bdb56cba97596d8532d46cb4
l = int(input("Enter lower range: ")) u = int(input("Enter upper range: ")) if(l<=0): print "invalid" if (u<=0): print "invalid" for num in range(l,u+1): n = len(str(num)) sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** n ...
2,897
d02ef5fc27cde353e90dda4090905b89b5be5c49
#!/usr/bin/env python import fileinput #open the file with the matched DNA short reads #create a file with the modified version f1 = open('CompleteDNAsequence.txt', 'r') f2 = open('CompleteDNAsequence.txt.tmp', 'w') for line in f1: f2.write(line.replace('_', '\n')) #replaces _ with tab f1.close() f2.close() #ope...
2,898
5cfdb1f6b99f59a83a9bd42b7daf3e016eee94a8
from werkzeug.security import check_password_hash, generate_password_hash from datetime import datetime from app import db from app import login from flask_login import UserMixin @login.user_loader def load_user(id): return User.query.get(int(id)) class User(UserMixin, db.Model): user_id = db.Column(db.Integer, p...
2,899
89addbf2c49d568250cd5a48d3fdb73914ce50c4
def firstMissingPositive(nums): if len(nums) == 0: return 1 if len(nums) == 1: if nums[0] == 1: return 2 else: return 1 nums.sort() current = 1 nums = [ele for ele in nums if ele > 0] if len(nums) == 0: ...