index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
2,200
5055743c9ed8c92bcfab5379162f28315409ff91
from pull_links import pull_links from scrape_lyrics import scrape_lyrics from vader_sentiment import getSentimentScores import sys import os import shutil # Get user input for artist -> capitalize it artist = sys.argv[1].title() pull_links(artist) # Dictionary w/ song name as key and lyrics as value lyrics = scrape_...
2,201
8cd290dc1e682222c97172a0f23e5b93c54838a7
# Generated by Django 2.1.3 on 2019-01-02 12:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('leasing', '0037_make_lease_basis_of_rent_archivable'), ] operations = [ migrations.AddField( model_name='invoicepayment', ...
2,202
6175ce6534d44d703df6cdef94fc2b1285e25f49
import unittest import shapely.geometry as gm from alphaBetaLab.abRectangularGridBuilder import abRectangularGridBuilder class testAbRectangularGridBuilder(unittest.TestCase): def getMockHiResAlphaMtxAndCstCellDet(self, posCellCentroids = None): class _mockClass: def __init__(self, posCellCentroids): ...
2,203
37b23dc520abc7cbb6798f41063696916065626f
#listas lista=[] print(lista) #lista semana listasemana=["Lunes","Martes","Miercoles","Jueves","Viernes"] print(listasemana[0]) #lista semana listasemana=["Lunes","Martes","Miercoles","Jueves","Viernes"] print(listasemana[-1]) #lista semana listasemana=["Lunes","Martes","Miercoles","Jueves","Viernes"] print(listase...
2,204
32c18bd578bbf91c76604f063421a65a4f7a8b63
''' Created on Mar 7, 2019 @author: hzhang0418 ''' import pymp from v6.mono import Mono class BruteForce(Mono): def __init__(self, features, labels, params): super(BruteForce, self).__init__(features, labels, params) def _count_inconsistencies(self): if self.num_cores==1: ...
2,205
736b84bbcf1d5954b491068be4060edeade2c1c5
# "Time Warner Python" Salma Hashem netid: sh5640 #Design costumer service application by asking users series of questions, and based on the customers' answers to the questions, provide them with instructions. #Ask the user to choose from the following options print("Choose from the following options: ") #assign each...
2,206
72e03e7199044f3ed1d562db622a7b884fa186b0
import os from flask import request, jsonify from flask_api import FlaskAPI from flask_api.exceptions import NotAcceptable from dotenv import load_dotenv load_dotenv(dotenv_path='./.env') from src.service.jira import jira from src.service.helper import helper application = FlaskAPI(__name__) jiraservice = jira() help...
2,207
2eecc852a6438db19e0ed55ba6cc6610d76c6ed0
from flask import Flask, render_template from config import Config from flask_bootstrap import Bootstrap from config import config_options from flask_login import LoginManager from flask_wtf.csrf import CSRFProtect from flask_sqlalchemy import SQLAlchemy login_manager = LoginManager() login_manager.session_protection ...
2,208
1c085ea8f9b21ea7bef94ad4ecbb1771a57f697a
# SPDX-FileCopyrightText: 2023 spdx contributors # # SPDX-License-Identifier: Apache-2.0 from dataclasses import field from beartype.typing import List, Optional from spdx_tools.common.typing.dataclass_with_properties import dataclass_with_properties from spdx_tools.common.typing.type_checks import check_types_and_se...
2,209
5aebebb7f22e094a1a897b3266ff07d59400b76c
"""Admin module for Django.""" from django.contrib import admin from django.utils.translation import gettext_lazy as _ from django_q.conf import Conf, croniter from django_q.models import Failure, OrmQ, Schedule, Success from django_q.tasks import async_task class TaskAdmin(admin.ModelAdmin): """model admin for ...
2,210
d91bacfd4b45832a79189c0f1ec4f4cb3ef14851
# 14. Sort dataframe (birds) first by the values in the 'age' in decending order, then by the value in the 'visits' column in ascending order. import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["divya_db"] mycol = mydb["vani_data"] # age column in decending order myquery = my...
2,211
6be2cc99d03596715d76cda41d63b8c91c829498
# coding: utf-8 from sqlalchemy import Column, DateTime, Integer, String from sqlalchemy.schema import FetchedValue from application import db class BmExam(db.Model): __tablename__ = 'bm_exam' id = db.Column(db.Integer, primary_key=True) status = db.Column(db.Integer, nullable=False, server_default=db.Fe...
2,212
1450d3b8cc4cef1c5f802e4d84e2211b7467fe12
import iotsim.readers as readers import iotsim.networks as networks import iotsim.constructors as contructors import yaml _inventory = dict( assembly=dict( Flatline=contructors.Flatline, Seasaw=contructors.Seesaw, Pulser=contructors.Pulser, SimpleActuator=contructors.SimpleActuat...
2,213
426396c981fe56230e39b81e156e7c6877e39055
import os timeslices = ['0_' + str(x) + '_' + str(y) for x in range(30,100) for y in range(0,6)] #print timeslices def make_Folders(names): for n in names: if not os.path.exists(n): os.makedirs(n) make_Folders(timeslices)
2,214
82bfdb46e1da96e5db91d66c3a060d8bf7747d07
from discord import Message, ChannelType from discord.ext.commands import Bot, Cog, command, Context from ccbot import repo from shared import fetch_tools import os class Submissions(Cog): def __init__(self, bot: Bot) -> None: self.bot = bot @command() async def current(self, ctx: Context) -> None...
2,215
b4bcf9903f4a34c8b256c65cada29e952a436f74
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'VideoAd.compress' db.add_column(u'main_videoad', 'compres...
2,216
200deda300e39b07e0e558277a340b7ad01c7dee
class State: def __init__(self, id): self.id = id def NotinClosed(problem, node): #restituisce 1 se lo stato non è stato già visitato (al netto di controlli sulla depth) è quindi bisogna aggiungerlo NotVisited = 1 for tuple in problem.closed: if node.state.id == tuple[0].id and node.depth...
2,217
237a647e7bf0b1c12abd78b1ef6e293e73232a6c
from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen import subprocess import socket from kivy.uix.button import Button from kivy.uix.button import Label from kivy.uix.boxlayout import BoxLayout Builder.load_string(""" <MenuScreen>: BoxLayout: orie...
2,218
78178ec8474a3deb876ab7d3950cd427d7a795d5
#-*- coding:UTF-8 -*- year = int(input('请输入一个年份:')) """ if(year % 4) == 0: if(year % 100) == 0: if(year % 400) == 0: print('{0}是润年'.format(year)) else: print('{0}不是润年'.format(year)) else: print('{0}是润年'.format(year)) else: print('{0}不是润年'.format(year)) ...
2,219
d8482da6b9983d990da980c3a5edab0c49a28229
x = int(input('masukkan')) y = int(input('masukkan')) def jumlah(x,y): hasil = x+y return hasil print('hasil dari',x,'+',y,'=', jumlah(x,y)) k = jumlah(2,4)+1 print(k)
2,220
23150f359db97e1e0ce3f12a173cd7015ad22cd4
version https://git-lfs.github.com/spec/v1 oid sha256:839b1a9cc0c676f388ebfe8d8f2e89ad7c39a6f0aa50fa76b2236703bf1a8264 size 62
2,221
a2eabf4dae931d82e4e9eda87d79031711faf1aa
table = None width = 1000 height = 1000 def setup(): global table table = loadTable("flights.csv", "header") size(width, height) noLoop() noStroke() def draw(): global table background(255, 255, 255) for row in table.rows(): from_x = map(row.getFloat('from_long'), -180, 1...
2,222
65ef3b2ed5eef3d9d9e682ca18cf84457e929df2
import hashlib import hmac import time def hmac_sha1_token(): timestamp = str(time.time()) hmac_pass = hmac.new(b'some very secret string', timestamp.encode('utf-8'), hashlib.sha1).hexdigest() token = '%s:%s' % (timestamp, hmac_pass) return token
2,223
e48a6a84268a0fe64e90714bd32712665934fc39
import csv #ratings.csv must be in the same directory skipped_header = False with open("ratings.csv") as in_file: csvreader = csv.reader(in_file) #read each row of ratings.csv (userId,movieId,rating,timestamp) with open("ratings_train.csv", 'w') as train_out: with open("ratings_test.csv", 'w...
2,224
454d210c1b1a41e4a645ef7ccb24f80ee20a451c
from django.db import models from home.models import MainUser from product.models import Product # Create your models here. class Cart(models.Model): user = models.ForeignKey(MainUser,on_delete=models.CASCADE) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerFiel...
2,225
7ef0bb3e8cbba4a29249a09cf7bc91e053411361
from urllib import request import time import random from useragents import ua_list import re import os class MaoyanSpider(object): def __init__(self): self.url = 'https://maoyan.com/board/4?offset={}' # 请求功能函数 - html def get_html(self,url): headers = { 'User-Agent':random.choi...
2,226
96cfee85194c9c30b3d74bbddc2a31b6933eb032
def check(root, a, b): if root: if (root.left == a and root.right == b) or (root.left ==b and root.right==a): return False return check(root.left, a, b) and check(root.right, a, b) return True def isCousin(root, a, b): # Your code here if check(root, a, b)==False: ret...
2,227
f2a508ae99697d6ba320b158a1000379b975d568
word=input() letter,digit=0,0 for i in word: if('a'<=i and i<='z') or ('A'<=i and i<='Z'): letter+=1 if '0'<=i and i<='9': digit+=1 print("LETTERS {0} \n DIGITS {1}".format(letter,digit))
2,228
2a65287588fe1337ba1a6f7c2e15e0505611d739
text = input('Ввести имя файла: ') def a(): lines = 0 words = 0 letters = 0 for line in open(f'{text}.txt', 'r'): lines += 1 letters += len(line.strip('.,:-()!?;)"\'\n}')) words += len(line.split()) return f'Lines = {lines}, words = {words}, letters = {letters}' print(a())
2,229
c93bd042340a6e1d0124d8f6176bdf17ab56e405
#!/usr/bin/env python """ Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5: 22=4, 23=8, 24=16, 25=32 32=9, 33=27, 34=81, 35=243 42=16, 43=64, 44=256, 45=1024 52=25, 53=125, 54=625, 55=3125 If they are then placed in numerical order, with any repeats removed, we get the following seq...
2,230
bfd31d0b80511721ee5117daced04eaf63679fd8
from scipy.stats import mannwhitneyu import matplotlib.patches as patches import os import numpy import pandas from matplotlib.gridspec import GridSpec from scipy.cluster.hierarchy import fcluster, linkage, dendrogram from scipy.spatial.distance import squareform import seaborn as sns from scipy.stats import spearmanr ...
2,231
e2b439974b66e45a899605bc7234850783c3dfb0
from django.core.validators import RegexValidator from django.db import models from .image import Image class AffiliatedStoreManager(models.Manager): def get_queryset(self): return super().get_queryset() \ .select_related('icon') \ .select_related('icon__image_type') def fin...
2,232
f35569e2d8d26f43d4b2395b5088902c6cd3b826
from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtSql import * from DatabaseHandler import send_answer class PW(QWidget): def __init__(self, index, question, pid): super().__init__() self.question = question self.pid = pid self.maxim = len(self.questi...
2,233
2185d332f7cd4cbf17d6b72a19297d156c2182a1
from typing import List import scrapy from cssselect import Selector class RwidSpider(scrapy.Spider): name = 'rwid' allowed_domains = ['0.0.0.0'] # REQUEST LOGIN DARI URLS start_urls = ['http://0.0.0.0:9999/'] # LOGIN DISINI def parse(self, response): # apa bedanya yield & return ...
2,234
87e5a615157db59d1eac4967c321829c878d00a5
""" - input: is a 'special' array (heavily nested array) - output: return the product sum - notes: - special array is a non-empty array that contains either integers or other 'special' arrays - product sum of a special array is the sum of its elements, where 'special' arrays inside are summed themselves and then mu...
2,235
c6170678b523a105312d8ce316853859657d3c94
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-02-26 13:14 from __future__ import unicode_literals import datetime from django.db import migrations, models import django.db.models.deletion from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('user...
2,236
ab38371ee3941e214344497b7e56786908a9b3d1
from django.contrib import admin from .models import Sport from .models import Action admin.site.register(Sport) admin.site.register(Action)
2,237
e67f27eec53901f27ba5a7ee7e2a20bbb1e8f7f9
from fbchat import Client class IBehaviourBase(Client): BreakFlag = False def __init__(self,email,password, kwargs): """"abstract class being parent of every user implemented behaviour; it handles logging in and tasks on behaviour loader side""" self.kwargs=kwargs Client.__init_...
2,238
7026f4549019c25cb736af556fe46fd360fba46f
from .test_function import * from .support_funcs import * table_DIXMAAN = dict() table_DIXMAAN['A'] = (1, 0, 0.125, 0.125, 0, 0, 0, 0) table_DIXMAAN['B'] = (1, 0.0625, 0.0625, 0.0625, 0, 0, 0, 1) table_DIXMAAN['C'] = (1, 0.125, 0.125, 0.125, 0, 0, 0, 0) table_DIXMAAN['D'] = (1, 0.26, 0.26, 0.26, 0, 0, 0, 0) table_DIXM...
2,239
e3c9487f3221ca89b9014b2e6470ca9d4dbc925a
import numpy as np import cv2 as cv import methods as meth from numpy.fft import fft2, fftshift, ifft2, ifftshift import pandas import os import noGPU as h import matplotlib.pyplot as plt class fullSys(): def __init__(self, dir, file, size, line): csv_reader = pandas.read_csv(file, index_col='Objective') ...
2,240
5c7c90717f2e98c26675fec6390b4ea9797d6a4e
class TrieNode: def __init__(self): self.children = [None for i in range(26)] self.isEndOfWord = 0 class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def insert(self, key): root = self.root length = len(key) for level in range(length): index = ord(key[le...
2,241
e08fddefabf1b92aa97b939e05bb31d888df4e6a
# -*- coding: utf-8 -*- """ Created on Sun Apr 19 12:28:39 2020 @author: Ксения """ import serial import time import serial.tools.list_ports as lp def get_comports_list(): ports=list(lp.comports(include_links=False)) for p in ports: print(p.device) return ports def read_while_LF(com, timeout...
2,242
e7239b4bc3db9bd427b9be888621f66e81b5edeb
from azfs.az_file_client import ( AzFileClient, export_decorator ) from azfs.az_file_system import AzFileSystem from azfs.utils import BlobPathDecoder from .table_storage import ( TableStorage, TableStorageWrapper ) # comparable tuple VERSION = (0, 2, 14) # generate __version__ via VERSION tuple __ve...
2,243
1ab69874a89311b22220dda541dfe03462a98a55
import discord, requests from random import choice TOKEN = 'TOKEN' CONTACT_EMAIL = None #'Contact email for getting 10000 words/day instead of 1000' translate_command = '$t' id_start = '<@!' client = discord.Client() def unescape(text): return text.replace('&#39;', '\'').replace('&lt;','<').replace(...
2,244
0188355f84054143bd4ff9da63f1128e9eb5b23b
from flask_restful import Resource from flask import jsonify, make_response, request from ..models.Users import UsersModel from ..models.Incidents import IncidentsModel from app.api.validations.validations import Validations class UsersView(Resource): def __init__(self): self.db = UsersModel() def...
2,245
d499b4e189a0c3c6efa6a07871dbc6c2996a2dcb
import logging from abc import ABC from thraxisgamespatterns.application.handler_map_factory import TGHandlerMapFactory from thraxisgamespatterns.eventhandling.event_distributor import TGEventDistributor from thraxisgamespatterns.factories.logging_rule_engine_factory import TGLoggingRuleEngineFactory class T...
2,246
36ab827b889adcd4d54296e7da432d3b39d5a2e6
from cobra.model.fabric import HIfPol from createMo import * DEFAULT_AUTO_NEGOTIATION = 'on' DEFAULT_SPEED = '10G' DEFAULT_LINK_DEBOUNCE_INTERVAL = 100 AUTO_NEGOTIATION_CHOICES = ['on', 'off'] SPEED_CHOICES = ['100M', '1G', '10G', '40G'] def input_key_args(msg='\nPlease Specify Link Level Policy:'): print msg ...
2,247
fac60a8967354e4f306b95fdb5c75d02dc2c1455
# Generated by Django 3.2.6 on 2021-08-19 22:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('chat', '0005_user_image'), ] operations = [ migrations.AlterField( model_name='user', name='first_name', ...
2,248
39d82267f966ca106ee384e540c31a3e5e433318
""" Task. Given two integers a and b, find their greatest common divisor. Input Format. The two integers a, b are given in the same line separated by space. Constraints. 1<=a,b<=2·109. Output Format. Output GCD(a, b). """ def EuclidGCD(a, b): if b == 0: return a else: a = a%b return Euc...
2,249
7d0b0cb19e22ff338104e0c2061da94ba04d4f16
from __future__ import division import numpy as np import scipy.stats from tms import read_and_transform __author__ = 'Diego' def estimate_vrpn_clock_drift(points): # clocks = [map(np.datetime64,(p.date,p.ref_date,p.point_date)) for p in points] clocks = [(p.date, p.ref_date, p.point_date) for p in points...
2,250
732478fd826e09cf304760dfcc30cd077f74d83e
import pandas as pd import numpy as np #import data df = pd.read_csv('../.gitignore/PPP_data_to_150k.csv') counties = pd.read_csv('../data/zip_code_database.csv') demographics = pd.read_csv('../data/counties.csv') #filter out all unanswered ethnicities df2 = df[~df.RaceEthnicity.str.contains("Unanswered")] #drop non...
2,251
673d6bb02ec666dbdbecb5fd7fd5041da1941cf8
import mosquitto import json import time device_id = "868850013067326" # The callback for when the client receives a CONNACK response from the server. def on_connect(mosq, userdata, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # r...
2,252
2a69aa0cd9d0e39ad82d6a354e956bdad0648797
from django.apps import AppConfig class ActivityConfig(AppConfig): name = 'apps.activity'
2,253
2ab3adb4d0ed7e6e48afb2a8dab8f9250d335723
class A(object): _a ='d' @staticmethod def func_1(): A._a = 'b' print A._a @classmethod def func_3(cls): print cls._a def func_2(self): # self._a = 'c' print self._a # print A._a # # class B(object): # @staticmethod # def func_1(): # ...
2,254
6eb59f62a1623f308e0eda4e616be4177a421179
import sys import pysolr import requests import logging import json import datetime from urlparse import urlparse from django.conf import settings from django.utils.html import strip_tags from aggregator.utils import mercator_to_llbbox def get_date(layer): """ Returns a date for Solr. A date can be detected...
2,255
8180dac5d33334d7f16ab6bef41f1fe800879ca7
# -*- coding: utf-8 -*- import datetime from urllib import parse import scrapy from scrapy import Request from BrexitNews.items import BrexitNewsItem def check_url(url): if url is not None: url = url.strip() if url != '' and url != 'None': return True return False class Theguar...
2,256
6297256bce1954f041915a1ce0aa0546689850f3
# Feito por Kelvin Schneider #12 numero = input("Digite um numero de telefone: ") numero = numero.replace("-","") if (len(numero) < 8): while len(numero) < 8: numero = "3" + numero numero = numero[:4] + "-" + numero[4:] print("Numero: ", numero) elif (len(numero) > 8): print("Numero invalido...
2,257
4e38ad17ad66ac71b0df3cbcaa33cb546e96ce9d
import pymel.core as PM import socket def getShadingGroupMembership(): ''' Get a dictionary of shading group set information {'shadingGroup': [assignmnet1, assignment2...]} ''' result = {} #sgs = PM.ls(sl= 1, et='shadingEngine') sgs = PM.listConnections(s= 1, t='shadingEngine') for sg i...
2,258
b186ae7a48afbb70edf3be0d9697deed4f31e542
# -*- coding: utf-8 -*- """ ------------------------------------------------- # @Project :experiment9 # @File :text1 # @Date :2020/10/28 09:13 # @Author :施嘉伟 # @Email :1138128021@qq.com # @Software :PyCharm ------------------------------------------------- """ import urllib.request # 发出请求,得到响应 response=ur...
2,259
63be96c0d1231f836bbec9ce93f06bda32775511
import re import numpy as np # only read pgm file def readfile(filename:str)->tuple: '''read given pgm file''' col = 0 row = 0 lst = list() with open(filename, 'rb') as file: header = list() ls = list() # remove first line header.append((file.readline()).decode("utf-...
2,260
f960c95afe1f7a161e0144bb523bfaca117ae61e
try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup def find_packages(): return ['sqlpython'] classifiers = """Development Status :: 4 - Beta Intended Audience :: Information Technology License :: OSI Approved :: MIT License Programming Language...
2,261
53e397068fcf88bbbce4dcc1bf1b441a2fbbee48
#Write a Python program to get the maximum and minimum value in a dictionary. d1={6: 10, 2: 20, 5: 30, 4: 40, 1: 50, 3: 60} print(max(d1.values())) print(min(d1.values()))
2,262
8560c0068eff894e5aa1d0788bd9e5ad05c14997
""" sed_thermal.py Author: Joshua Lande <joshualande@gmail.com> """ import numpy as np from scipy import integrate from . sed_integrate import logsimps from . sed_spectrum import Spectrum from . import sed_config from . import units as u class ThermalSpectrum(Spectrum): vectorized = True def __init__(s...
2,263
a49c00dab8d445ce0b08fd31a4a41d6c8976d662
#!/usr/bin/python import sys BLACK = '\033[30;0m' RED = '\033[31;0m' GREEN = '\033[32;0m' YELLOW = '\033[33;0m' BLUE = '\033[34;0m' PINK = '\033[35;0m' CBLUE = '\033[36;0m' WHITE = '\033[37;0m' def colorPrint(color, str): print(color + str + '\033[0m'); def main(): if sys.argv.__len__() < ...
2,264
2bce18354a53c49274f7dd017e1f65c9ff1327b9
<<<<<<< HEAD """Module docstring""" import os import numpy as np from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold from sklearn.metrics import accuracy_score ======= #!/usr/bin/python """Module docstring"""...
2,265
da30cea4cfb1ffccabe708fe15e5a633b06d299f
import sys from PyQt5 import uic from PyQt5.QtWidgets import QWidget from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap class Instruction(QWidget): def __init__(self): super().__init__() # Set UI file uic.loadUi('../ui/instruction.ui', self) # Connect handlers of buttons...
2,266
8980ac4db2657d3dbd2b70b33a4d13a077d4590e
from flask import Flask, jsonify, request, send_file, render_template from flask_cors import CORS from twilio.rest import Client import autocomplete from gtts import gTTS import os # Set up the model. autocomplete.load() app = Flask(__name__) CORS(app) # The application @app.route("/") def index(): return render_tem...
2,267
eb5256543d6095668d6eeaf6cfdc9f744d7c73c5
# -*- coding: utf-8 - # # This file is part of gaffer. See the NOTICE for more information. import os from .base import Command from ...httpclient import Server class Load(Command): """\ Load a Procfile application to gafferd ====================================== This command allows you...
2,268
dacd4334433eb323ce732c96f680fb7b9333721a
# -*- coding: utf-8 -*- import sys import xlrd import numpy as np import matplotlib.pyplot as plt if __name__ == "__main__": param = sys.argv print "Hello:" + param[0] # ファイルのオープン book = xlrd.open_workbook('sample.xls') # シートの選択 sheet = book.sheet_by_name(u"Sheet1") # sheet = book.sheet_by_index(0) plot_x =...
2,269
7599f13d1cabe73d876ff97722962f2fcf9a9940
import logging import os.path from day03.code.main import traverse_map, get_map_cell, traverse_map_multiple_slopes logger = logging.getLogger(__name__) local_path = os.path.abspath(os.path.dirname(__file__)) def test_get_map_cell(): map_template = """..##....... #...#...#.. .#....#..#. ..#.#...#.# .#...##..#. ....
2,270
ec9f27b4313f72ae6eb7e8280d47de226aeb6bb1
import numpy from scipy.spatial.distance import cosine def similarity_metric(embedding1: numpy.ndarray, embedding2: numpy.ndarray) -> float: return numpy.nan_to_num(1 - cosine(embedding1, embedding2), 0)
2,271
967c8348352c805b926643617b88b03a62df2d16
from access.ssh.session import Client from access.ssh.datachannel import DataChannel
2,272
7c39b3927bc0702818c54875785b4657c20c441e
# Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ if len(s)...
2,273
4605a3f88c73b43fa7611a10a400ad2d4d7c6dfc
# !/usr/bin/env python # coding: utf-8 __author__ = 'zhouhenglc' TIME_FORMAT = '%Y-%m-%d %H:%M:%S' ENCODING = 'utf-8' # exam mode # G_SELECT_MODE # 待废弃,逐步完善使用classes.objects.question_type # G_SELECT_MODE = ["无", "选择题", "名词解释", "简答题", "计算题", "论述题", "多选题", "判断题"] G_MULTI_MODE = [6, ] # 多选题型 多选题=6 # G_DEF_OPTIONS...
2,274
3e48de2e3b12965de1b3b5cb6c3cf68c90ec6212
import sys heights = [] for i in range(10): line = sys.stdin.readline() height = int(line) heights.append(height) heights.sort() heights.reverse() for i in range(3): print (heights[i])
2,275
fbd5400823a8148adf358a2acc58fde146a25313
# coding=utf8 # encoding: utf-8 import os import platform import re import signal import sys import traceback from subprocess import Popen, PIPE from threading import Thread, current_thread from Queue import Queue from util.log import get_logger, log from video.models import Video, KeywordVideoId from django.db.mode...
2,276
e735529eddd3a46ea335e593e5937558b50b142d
# -*- coding: utf-8 -*- import time import datetime def get_second_long(time_str=None): if time_str is None: return long(time.time()) time_array = time.strptime(time_str, "%Y-%m-%d %H:%M:%S") return long(time.mktime(time_array)) def get_curtime_str(): return datetime.datetime.now() def ge...
2,277
7dc7c7598c9069e5fbb336bb97161ebb7c74366e
#!/usr/bin/env python from imgproc import * from time import sleep # open the webcam #camera = Camera(640, 480) camera = Camera(320, 240) #camera = Camera(160, 120) #while True: # grab an image from the camera frame = camera.grabImage() print frame[x,y] # open a view, setting the view to the size of the captur...
2,278
02b20c3f5941873dfd22a7fbedb825e66c613ace
Xeval[[1,2],:] # *** Spyder Python Console History Log *** Xeval[:,:] optfunc.P(Xeval[:,:]) optfunc.P(Xeval) optfunc.P(Xeval[[0,1,2,3,4],:]) optfunc.P(Xeval[[0,1,],:]) optfunc.P(Xeval[[0,1],:]) optfunc.P(Xeval[[0,1,2,3],:]) optfunc.P(Xeval[[0,1,2,3,4],:]) optfunc.P(Xeval[[0,1,2],:]) Xeval[[0,1,2,3,4],:] Xev...
2,279
2ff398e38b49d95fdc8a36a08eeb5950aaea1bc9
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0. from awscrt import http, io from awsiot import mqtt_connection_builder from utils.command_line_utils import CommandLineUtils # This sample shows how to create a MQTT connection using a certificate file and key ...
2,280
4b44f4343da1677b5436ec2b153e573fda3c0cee
# Code Rodrigo ''' This script, basically generates all he possible combinations to be analyzed according to the Dempster Shafer Theory. It requires to define beforehand, the combination of variables that lead to the higher and lower bound for a given combination of random sets, via the sensitivity analysis ''' impo...
2,281
6ece524c82521b175cc7791e22c8249dd24dc714
import datetime import matplotlib.pyplot as plt import numpy as np import statsmodels.api as sm import xlrd from pandas import * from xlrd import xldate #since I messed up when first scraping the data, I have the dates and viewcounts in separate files #need to create a dictionary of 'author-title':[viewcount, date] ...
2,282
bf49893fee79b0c3e34340cf1633c1797ce1bf41
#MenuTitle: Check for open paths in selected glyphs """ Checks for open paths in selected glyphs (or all glyphs if no selection). Output appears in Macro Window (Option-Command-M). """ # FIXME: test with masters and instances -- may not work Font = Glyphs.font Doc = Glyphs.currentDocument selectedGlyphs = [ x.parent f...
2,283
1fad591fde707c73bd52aa8518828c8b8be9cd32
from __future__ import annotations import typing import requests import heapq from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.text import TfidfVectorizer from bs4 import BeautifulSoup from wikiAPI import get_JSON, get_intro, compare_titles from typing import List, Type, Callable ...
2,284
a7d11f130e0d5d6c9b4ac7c5d3a804fb9f79b943
import time from wxpy import * bot = Bot(cache_path='wxpy.pkl') def get(i): with open('晚安.txt', 'r', encoding='utf-8') as f: line = f.readlines()[i] return line def send(i): myfriend = bot.friends().search('微信好友昵称')[0] myfriend.send(get(i)) i += 1 def main(): for i in...
2,285
e49c5c6475a1210a9657d7bbd0490c8d20863718
from conans import * class GlibConan(ConanFile): name = "glib" description = "Common C routines used by Gtk+ and other libs" license = "LGPL" settings = {"os": ["Linux"], "arch": ["x86_64", "armv8"]} build_requires = ( "generators/1.0.0", "autotools/1.0.0", ) requires = ( ...
2,286
b041e9577af72d2bcee3dda0cc78fa12800d53bd
#!/usr/bin/env python # -*- coding: utf-8 -*- __doc__ = """\ A MiniFrame is a Frame with a small title bar. It is suitable for floating toolbars that must not take up too much screen area. In other respects, it's the same as a wx.Frame. """ __wxPyOnlineDocs__ = 'https://wxpython.org/Phoenix/docs/html/wx.MiniFrame.htm...
2,287
c336bb6cdadfb836ab68ebd5bbb210f63af3d084
"""Calculator is built using "ping pong" algorithm, without eval() etc. Main final function: calculate_expression(). calculate_expression() uses two functions in utils.py: clear_and_convert() and calculator_without_parentheses(). calculator_without_parentheses() uses two remaining functions: math_operation() -> ping_ca...
2,288
c08e6cee61e9f32a9f067a9554c74bb2ddbd7cf3
import control.matlab as ctrl import matplotlib.pylab as plt def process_data(num11, den11, num21, den21): w11 = ctrl.tf(num11, den11) w21 = ctrl.tf(num21, den21) print('результат w11={} w21={}'.format(w11, w21)) TimeLine = [] for i in range (1, 3000): TimeLine.append(i/1000) plt.figur...
2,289
d32f009f373249b7b602ac36f29982273a2ed192
from . import resources from jsonschema import validate from jsonschema.exceptions import ValidationError import aiohttp_client import importlib.resources as pkg_resources import json import logging log = logging.getLogger("amplitude-client") API_URL = "https://api.amplitude.com/2/httpapi" class AmplitudeLogger: ...
2,290
caa28bd64141c8d2f3212b5e4e77129d81d24c71
from flask import Flask, render_template app = Flask(__name__) @app.route('/',methods=["GET","POST"]) def inicio(): nombre = "jose" return render_template("inicio.html",nombre=nombre) app.run(debug=True)
2,291
a048396019aa7603a20535a3ce4bc9770509097d
# Generated by Django 3.2 on 2021-04-20 13:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('excursions', '0003_auto_20210420_1608'), ] operations = [ migrations.AlterField( model_name='exscursion', name='type',...
2,292
a745f72081e06ff3399f9d7f65a30d7eef594689
#!/usr/bin/env python """add_columns.py: This script reads an SCEC ETAS forecast directory name and extracts key fields that are then added as attributes in the SCEC Deriva schema. This script is an example of how the ERD used by Deriva is extended as additional information or metadata is added to the asset descri...
2,293
50ed1512b0e6ff8e01f5d4aa034406fa78850176
""" Creates a ResNeXt Model as defined in: Xie, S., Girshick, R., Dollar, P., Tu, Z., & He, K. (2016). Aggregated residual transformations for deep neural networks. arXiv preprint arXiv:1611.05431. import from https://github.com/prlz77/ResNeXt.pytorch/blob/master/models/model.py """ import torch import torch.nn as nn ...
2,294
32b961f3971819fdbbe1a30fd7cf1883353c1854
w = int(input("Width ?")) h= int(input("Height ?")) for b in range(1,w+1): print ("*", end='') print("") for i in range(1,h-1): print ("*", end='') for j in range(1,w-1): print (" ", end='') print ("*", end='') print("") for b in range(1,w+1): print ("*", end='') print("")
2,295
bac3f78b8eb9c4595bc9e8b85587819f92329729
#!/usr/bin/env python """ Calculate trigger efficiency error """ __author__ = "XIAO Suyu<xiaosuyu@ihep.ac.cn>" __copyright__ = "Copyright (c) XIAO Suyu" __created__ = "[2018-02-06 Tue 15:25]" import math n1 = 4212.0 n2 = 4237.0 N = 5000.0 eff = n1 / n2 err = math.sqrt(eff*(1-eff)/N) print 'trig_eff = %.4f +- %f' ...
2,296
18391df9a3e52400fe4fc54d6381b9ce21e25f0b
""" Templating support library and renderer configuration. """ from restish import templating class Templating(templating.Templating): """ Application-specific templating implementation. Overriding "args" methods makes it trivial to push extra, application-wide data to the templates without any assis...
2,297
f15bc62fad2c47fed2e9e5d269284ebe7487b789
#!/bin/python3 import sys # import numpy as np def _get_change_making_matrix(set_of_coins, r): matrix = [[0 for _ in range(r + 1)] for _ in range(len(set_of_coins) + 1)] # matrix = np.array(matrix) for i in range(1,len(set_of_coins) + 1): matrix[i][0] = i return matrix def change_making(co...
2,298
2dcf0466c84c952c60dcfce86498f063f43726f3
#!/usr/bin/python import socket import threading import signal import sys class Proxy: #initialise server socket def __init__(self): self.serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1...
2,299
1db866ca73bc264d474d5e5086c4a047d7e46546
"""Toggle the proof color. Like operating in the menu: **View** > **Proof Colors** (Ctrl + Y) """ # Import local modules from photoshop import Session with Session() as ps: ps.app.runMenuItem(ps.app.stringIDToTypeID("toggleProofColors"))