index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
999,100
a1aaa1eff27e7d8b857707cfc810c10014a039e5
from pyspark import SparkConf, SparkContext import string conf = SparkConf().setMaster('local').setAppName('P23_spark') sc = SparkContext(conf = conf) def calcmedia(line): med = (line[1]+line[2]+line[3]+line[4])/4 return (line[0], med) # ['2008',152.830978] def formatear(line): return ((line[0].split('-'))[0],f...
999,101
25ab797620e6a15d944ea95565d18f2b5d8c34ee
n=[] while len(n) <5: x=int(input("ingrese un numero ")) n.append(x) def menor_en_arreglo(): for i in n: menor = i< i print (menor) menor_en_arreglo()
999,102
b7661508808a09f519ccb88155183f788e6a5baa
#!/usr/bin/env python # coding: utf-8 # In[89]: import numpy as np import matplotlib.pyplot as plt import imageio # # Convolution = Intutively # In[90]: url = 'https://source.unsplash.com/U66avewmxJk/400x300' # In[91]: cheetah = imageio.imread(url) # In[92]: plt.imshow(cheetah) plt.show() # In[93]: ...
999,103
7c117e0374b2959a9179b4e074484dd858f9151f
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class Firm(scrapy.Item): """firm's general information""" firm_id = scrapy.Field() name = scrapy.Field() rank = scrapy.Field() tax_c...
999,104
a8737764f994d4e572c907256611a9fea3588a9e
import csv with open("merge_yes.csv", "r") as f: first = {rows[0]: rows[1:] for rows in list(csv.reader(f))} with open("house_prices.csv", "r") as f: for row in csv.reader(f): #print(row[1]) if row[0] in first: first[row[0]].append(row[1]) #converting dictionary back to list merged = [(k,) + tuple(v) for k, ...
999,105
1caf52070e17177651d268f7cb88e749611d00e4
# -*- coding: utf-8 -*- # @Author: Alexander Sharov import json def json2poly(file): with open(file, 'r', encoding='utf8') as data_file: data = json.load(data_file) points = data['features'][0]['geometry']['coordinates'][0] print(points) count = len(points) print('%d 2 0 0' % count) ...
999,106
a795d1171f585b4cd10f4ace1d6643977a8010a1
""" we will cover tkinter event handling in this part. In this scenario, we are adding a quit event to our quit button, which currently does nothing when clicked on. In basically every circumstance, we're going to want to have our buttons actually do something or perform an action rather than just appear there. This is...
999,107
1b8b5c9c74943c6c3d1c15fdafe4fa6660474a69
# -*- coding: utf-8 -*- import threading import time from route import * #Importer le module training.py pour faire la VOD | nPVR from checkConfig import * allgo = threading.Condition() class Process(threading.Thread): def __init__(self): threading.Thread.__init__(self) def execution(self): ...
999,108
dd3c7e202d1119d07af63db8b796565ca2db0c3d
# Generated by Django 3.0.3 on 2020-04-02 13:55 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blog', '0026_comments_email'), ] operations = [ migrations.RenameField( model_name='comments', old_name='approved_comment', ...
999,109
765119ee3b2b58f614b85836621332a13b02194d
import mesh import mesh_library import mesh_processing # import the packages import numpy as np import tensorflow as tf from scipy.optimize import minimize import scipy.stats as stats import time import random import CGAL from CGAL import CGAL_Kernel from CGAL import CGAL_Polyhedron_3 from CGAL import CGAL_Polygon_me...
999,110
303c4317584c641f895c481082e5281c256e76be
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2020 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by #...
999,111
d0599d3f4b5b96854728285d6a464e274b030988
#! /usr/bin/python from __future__ import print_function from dronekit import connect, VehicleMode, LocationGlobalRelative, Command from pymavlink import mavutil # Connect vehicle print("Connect to vehicle") vehicle = connect("127.0.0.1:14551", wait_ready=True) # Check arming state print(vehicle.armed) ...
999,112
c12f8d70a4f84967481d632d2d1ade86acec4786
from city import City from zoo import Zoo vienna = City("vienna") assert vienna.zoo assert isinstance(vienna.zoo, Zoo) assert vienna.zoo.size == 130 assert vienna.zoo._owner_name == "Mrs Zoo Keeper" print( f"City: {vienna.name}\n" f"Zoo owner: {vienna.zoo._owner_name}\n" f"Zoo's size: {vienna.zoo.size}\...
999,113
3582ad4b77c1a2eaef0460a2b3b8e80146f71ebc
from openerp import models, fields, api class ConciliacionBancaria(models.TransientModel): _name = "wizard.conciliacionbancaria" _description = "Conciliacion Bancaria" conciliacion_id = fields.Many2one('bank.reconciliation', string='Conciliacion Bancaria', required=True) imprime_movimientos_conci...
999,114
87d65075db946aa39f44d1570340f9b96360180f
# -*- coding: utf-8 -*- import arcpy import os class ConflictDuongBinhDo: def __init__(self): self.pathProcessGDB = r"C:\Generalize_25_50\50K_Process.gdb" self.pathDuongBoNuoc = r"C:\Generalize_25_50\50K_Process.gdb\ThuyHe\DuongBoNuoc" self.pathDuongBoNuocTemp = r"C:\Generalize_25_50\50K_P...
999,115
97c5abca28a76b57841d92ecdb1c00215b2717c3
import unittest from dnnamo.framework.tf import TFFramework from dnnamo.loader import TFFathomLiteLoader try: import fathomlite _FATHOMLITE = True except ImportError: _FATHOMLITE = False @unittest.skipUnless(_FATHOMLITE, 'No Fathom module found.') class TestTFFathomLiteLoader(unittest.TestCase): #_models = ...
999,116
a7ae39608433ec03c43b4c77d038138b72cc546c
import csv from itertools import islice myreader = csv.DictReader(open('/Users/qiaoli/Downloads/allCustNumVisitsRangeLifecycle.csv')) i=3 list=[] with open('/Users/qiaoli/Downloads/allCustNumVisitsRangeLifecycle.csv') as inFH: csvReader = csv.reader(inFH) for row in csvReader: if csvReader.li...
999,117
fe1e87b7d2dde99314f90e108f18e53dcf89486e
from java.util import HashMap from java.util import HashSet from java.util import Collections from java.util import ArrayList from java.io import FileInputStream from com.bea.wli.config import TypeIds from com.bea.wli.config.customization import Customization from com.bea.wli.sb.management.importexport import ...
999,118
2c07a99ab27ddd2dda8818d543eebaa4e7b8f089
#在Python程序中,分别使用未定义变量、访问列表不存在的索引、访问字典不存在的关键字观察系统提示的错误信息 # 使用未定义变量 # i+j # 访问列表不存在的索引 # list_a = ['a',1,'c'] # print(list_a[4]) # 访问字典不存在的key # dict_a = {'a':1,'b':2} # print(dict_a['c']) #通过Python程序产生IndexError,并用try捕获异常处理 try: list_b = ['a','b','c'] print(list_b[3]) except Exception as a: print(' 发生错...
999,119
6e22a82f53cc1ef0f7e7d35347a78a18a4cf7f42
import sys sys.path.append("../") import config import logging from os.path import join def get_line_offset(filepath): ''' For each file, return list of new line offsets :param filepath: path of the file to be read :return: list of line offsets ''' try: fread = open(filepath, 'r', 1) ...
999,120
22d1a75ebdcc4fd61a6174faca3ab3eeff09bce4
import sys,math;a,b,c,e=[int(i)for i in raw_input().split()] while 1: h='';i='' if c>a:h='W';c+=1 elif c<a:h='E';c-=1 if e>b:i='N';e-=1 elif e<b:i='S';e+=1 print i+h
999,121
82f577a60afa442bc6e8187b0a536b13ee11045b
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Listens to audio from microphone and waits for the configured wake word. Once the wake word is detected, the program records audio and sends it to Google for converting to text. When text is received, it is sent to an executor function which checks configured actions and ...
999,122
b155504d7a49a0fc02e5650510aad7762f2dc25c
import sys while True: line = sys.stdin.readline().rstrip() if line == ".": break true_flag = 1 stack = [] for i in range(len(line)): if line[i] == "(": stack.append("(") elif line[i] == ")": if stack and stack[-1] == "(": stack.pop...
999,123
67543d815fc48f63b490b2c396e8ad4b57368d91
import torch.nn as nn import torch import pyro.distributions as distribution import torch.nn.functional as F import copy class MeanFieldNormal(nn.Module): def __init__(self, shape, loc=None, scale=None, event=1): super(MeanFieldNormal, self).__init__() self.event = event if loc is None: ...
999,124
eefc8b540201446b49bd284c08b28652131534a8
"""darkbox.util.osutil""" import distro import platform def get_platform(): plat = platform.system() if plat == 'Darwin': return 'mac' elif plat == 'Windows': return 'win' elif plat == 'Linux': return 'nix' else: return 'unk' def get_distro(): """ From pl...
999,125
7cc044bee1657f5d490828a0c34bd06317dfd81f
#!/usr/bin/env python # coding: utf-8 from cx_Freeze import setup, Executable import sys,os build_exe_options = {"packages": ["os"], "includes":["tkinter", "tkinter.ttk"]} base=None if sys.platform == "win32": base = "Win32GUI" setup(name="Timer", version="1.0", description="Countdown timer", opti...
999,126
90bb83c86f1989004f08869f65d30c835e9a30b4
from __future__ import division import numpy as np import itertools import logging from .endclasses import endarray, lton, wc from .energetics_basic import EnergeticsBasic LOGGER = logging.getLogger(__name__) def values_chunked(items, endtype, chunk_dim=10): """ Given a list of lists of acceptable numbers f...
999,127
42ec590228d9c1af3dd94910cea963c38b4b862b
from django.shortcuts import render, redirect from django.views.generic import TemplateView, CreateView, ListView, DetailView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from .models import * from django.core.exceptions import PermissionDenied from django.db import connection from django.d...
999,128
64c6f1d63d761614cdaaaaecb0432da3c97c281d
n1 = float(input('Digite a n1: ')) n2 = float(input('Digite a n2: ')) calcNota = (n1+n2)/2 if calcNota < 5.0: print('Sua média é {:.1f}, você foi reprovado'.format(calcNota)) elif calcNota == 5.0 and calcNota < 6.9: print('Sua média foi {:.1f}, você tá na recuperação'.format(calcNota)) else: print('Sua méd...
999,129
0758176e6a487a375069b6cec7f378d49cd5063d
### LED THINGS BELOW # Turn backlight off #lcd.backlight = False #user input to switch this variable from datetime import datetime calibration = False def CalibrateSensor(): if calibration == True: print('Calibrating Black...') CalibState = 0 else: minR = minG = minB = 0 max...
999,130
47aa3b6908fa830274bf219f816ff1df89914491
def greet(): print("Hey there") print("Welcome Beatriz") greet()
999,131
e9ba567ee6fa84faf987d8053d7601af34f912ca
import heapq def solve(k, xs): ys = [-x for x in xs] heapq.heapify(ys) count = 0 for _ in range(k): count += -ys[0] heapq.heapreplace(ys, -((-ys[0]) / 2)) return count if __name__ == '__main__': for _ in range(int(raw_input())): _, k = map(int, raw_input().split()) ...
999,132
65d16497374188369e76c754cdbfeb6c96b73b4e
import event_handling from MathMan import variables def reset(new_game): variables.ghost_reset = True event_handling.my_hero.direction = None variables.math_man_buff = False variables.buff_timer = 0 variables.fruit_timer = int(variables.speed_setting) * 60 variables.grid = [['BDR'...
999,133
55169f46e53af88d023f59e945dd249d5a0d1629
fist_number, second_number, third_number = [int(input()) for _ in range(3)] if 1 <= fist_number <= 9 and 1 <= second_number <= 9 and 1 <= third_number <= 9: for a in range(2, fist_number + 1, 2): for b in range(2, second_number + 1): for c in range(2, third_number + 1, 2): if b ...
999,134
5dcebc13fdfe250e37e578b3c4ddc22c08acbafd
from django.db import models # from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): company_name = models.CharField(max_length=200) description = models.TextField(max_length=200) owner = models.CharField(max_length=200) password = models.CharField(max_leng...
999,135
90bf5a045e9343fc9b7c976994c63d8d5cf58a47
# Generated by Django 3.1.5 on 2021-05-23 11:03 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
999,136
97fdc4031bfb2d296e56728c208a44ccec5ebafd
import random class Credito: def __init__(self, score, renda): self.score = score self.renda = renda self.REGRA_LIMITE = { range(1, 300): self._reprovado, range(300, 600): self._mil, range(600, 800): self._valor_minimo_se_cinquenta_porcento, ...
999,137
e96a2e664a69e970a8ca55604bdd28f6fbdc0672
from django import forms from django.utils.safestring import mark_safe from django.template.loader import render_to_string from django.utils.html import conditional_escape from django.utils.encoding import force_str from django import VERSION as DJANGO_VERSION if DJANGO_VERSION < (1, 8): from django.forms.util impo...
999,138
62a328bc46a06d2a5ac72926faabd72237f458e9
import os import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formataddr from email.header import Header def send_automail(mail_name,stock_name,result_str,status_result,set_price,cur_val,update_time): #send via Gmail, replace None to your us...
999,139
20aed1c454a54c3e53a475c898416d85ba1c5938
def sum_odd_fib(n): prev_n = 0 curr_n = 1 result = 0 while (curr_n <= n): if curr_n % 2 != 0: result += curr_n curr_n += prev_n prev_n = curr_n - prev_n return result # Test print(sum_odd_fib(10)) # 10 print(sum_odd_fib(1000)) # 1785 print(sum_odd_fib(40000...
999,140
e25ef9991dc71ea5fe6ead1df4f354bd4606aa21
from sqlite3 import * from random import * import os def convert(k): """Entier -> str avec un zéro devant""" if k<10: return '0'+str(k) else : return str(k) def conv_time(t): """Convertit un temps t en seconde (depuis minuit) au format hh:mm:ss""" h,m = t // 3600, t % 3600 m,s...
999,141
433b1353644740b4810f955d5812583417c5a2b2
names_list = ["Adam", "Anne", "Barry", "Barry", "Brianne", "Charlie", "Cassandra", "David", "Dana"] # Converts names to uppercase uppercase_names = (name.upper() for name in names_list) print(names_list) print(uppercase_names) print(list(uppercase_names))
999,142
945346c3b81a7b5e94746211a4230ebb0334ba25
# -*- coding: utf-8 -*- import sklearn from sklearn.feature_extraction.text import CountVectorizer from sklearn.externals import joblib from collections import Counter import re import nltk # from nltk.corpus import stopwords import pandas as pd # import numpy as np # stopwords = set(stopwords.words("english")) stopw...
999,143
96523090c18b275a912ff90eca815704620bfb61
import os files = os.listdir("/home/hamza/MEGA/new/allTrain/labels/") # print(files) for file in files: with open("/home/hamza/MEGA/new/allTrain/labels/"+file, "r") as f: lines = f.readlines() #reads one line at a time with open("/home/hamza/MEGA/new/allTrain/labels/"+file, "w") as f: for line ...
999,144
e3182248083442fc8e2be38fc232701cf4564810
import tinys3 from threading import Thread from flask import current_app def send_async_file(app, filename): with app.app_context(): AWS_ACCESS_KEY = current_app.config['AWS_ACCESS_KEY'] AWS_SECRET_KEY = current_app.config['AWS_SECRET_KEY'] PAPER_BUCKET = current_app.config['PAPER_BUCKET']...
999,145
991e771c104583fd339864de810fecc29d4cf57a
class Data(object): def __init__(self): self.path = [] self.poisition = (0,0) def fed_data(self,data): self.path = data def get_path(self): return self.path def get_position(self): return self.poisition class Calc(object): def __init__(self): ...
999,146
e0de855ad17a4abe30abeec2ea3b73516fee9b89
import os.path import io_evd.tsv import data_transform.nMer import classify.per_epitope class ReadOptions: def __init__(self, \ cdr3b_seq_field=None, \ cdr3a_seq_field=None, \ vb_gene_field=None, \ db_gene_field=None, \ jb_gene_fi...
999,147
9984f4b14db8416c3d69d9b2b635e87e17675918
../hashUtils.py
999,148
f524bebbb0db85ba79d864dae83ae08063a310c6
#!/usr/bin/env python # coding: utf-8 # In[1]: import spacy import os import pickle from train_model import add_vectors, evaluate, main, train_spacy_model_from_zero from train_model import preprocess_annotations, fit_dataframe from sklearn.model_selection import train_test_split import pandas as pd import seaborn a...
999,149
40c0f31f4137be2c8ffbc3565e2884a635616a22
import sys import re import os import shutil import atexit import json import sys import gc import write_to_file import first import follow import LL1 import Queue import copy import SLR_1_parser_table import LR_0_parser_table #import matplotlib.pyplot as plt result_str = "" visited = [] graph = {} set_terminal = ...
999,150
c50c2d1c6ac773a25a01c58cde373a9c935b38a7
import datetime from sqlalchemy import Column, String, Integer, DateTime, Table, ForeignKey from .constants import STRING_SIZE class CustomBase(object): ''' Define base atribuetes for all table ''' id = Column(Integer, primary_key=True, autoincrement=True) create_date = Column(DateTime(timezone=Fals...
999,151
a857acf390c0de60415ae500804b33efa31e943f
# waiting for imports_1, please do not remove this line from flask import Flask # waiting for imports_2, please do not remove this line app = Flask(__name__) from mfm import routes
999,152
c5179bea04cc56131bf1e76756e279ecbb4e0d6e
from __future__ import annotations from typing import TYPE_CHECKING, Any, Dict, Literal, Optional import numpy as np from great_expectations.compatibility.typing_extensions import override from great_expectations.execution_engine import ( ExecutionEngine, PandasExecutionEngine, SparkDFExecutionEngine, ...
999,153
90324a4b0f808253e5ee37784baa772c7bb40f11
# coding: utf-8 # This function computes the body mass index (BMI), # given the height (in meter) and weight (in kg) of a person. def bodyMassIndex(height, weight): # Complete the function definition... bmi = ... return bmi # This function returns the BMI category acording to this table: # BMI: <1...
999,154
2fd34374181728550ac2d8207fbc1c3949228b10
import pygame, os, sys, random black = ( 0, 0, 0) white = ( 255, 255, 255) red = ( 255, 0, 0) lime = ( 0, 255, 0) blue = ( 0, 0, 255) yellow = ( 255, 255, 0) cyan = ( 0, 255, 255) magenta = ( 255, 0, 255) silver = ( 192, 192, 192) gray = ( 128, 128, 128) darkred ...
999,155
72a409dda74a302b76fe8111fca0b28455e58a8a
import numpy as np from Galois_Field_mod_2.functions import strip_zeros, check_type def xor(a, b): return np.logical_xor(a, b, dtype='uint8').astype("uint8") def gf2_add(a, b): a, b = check_type(a, b) a, b = strip_zeros(a), strip_zeros(b) N = len(a) D = len(b) if N == D: res = xor(a, b...
999,156
04164c3107e662d651802db5247909ac39d78282
''' Estimate the P matrix: Form the A matrix : 2N x 12 matrix Estimate P with the right singular vector of V in svd(A) Update with a nonlinear estimation routine Predict on still balls on the table ''' import pickle import numpy as np import scipy.linalg as linalg import json import os import sys #from sklearn import ...
999,157
c80910b0c472dbd65479834c97eac0f0a05df648
# -*- coding: utf-8 -*- ''' This module holds unit tests. It has nothing to do with the grader tests. ''' from django.conf import settings from django.test import TestCase from access.config import ConfigParser from util.shell import invoke_script class ConfigTestCase(TestCase): def setUp(self): self.co...
999,158
4baa497c9ef6ccb7c46c2c241f48335bc6350342
import re grammar = """ value : lst | var | pair lst : "[" [value ("," value)*] "]" pair : "(" value ":" value ")" var : /[a-z]+/ """ class Token(str): kind : str def __new__(cls, value, kind): tk = str.__new__(cls, value) tk.kind = kind return tk def __repr__(self): value = super().__rep...
999,159
7f14711244619ae9057ce85058e0609fa2975af9
number = range(1,10) numbers = list(number) print(numbers) print('The first three items in the list are:'+str(numbers[:3])) print('Three items from the middle of the list are:'+str(numbers[3:6])) print('The last three items in the list are:'+str(numbers[-3:]))
999,160
2a6b39c05c7e64d4b30bca80220d89393080131a
from aiohttp import web from openapi_core.validation.request.validators import RequestValidator from openapi_core.validation.response.validators import ResponseValidator from .openapi_wrappers import ( PATH_KEY, QUERY_KEY, AiohttpOpenAPIRequest, AiohttpOpenAPIResponse, ) from .rest_oas import OpenApiSp...
999,161
088fd5dd7956d41e6f024a10d58e5644fba3defc
import math def HitungLuasSegitiga(alas,tinggi): return 0.5*alas*tinggi def HitungLuasLingkaran(jari): return math.pi * jari *jari
999,162
db55a4e346527b8fa3bf90b63b4b54badef0a817
# # PySNMP MIB module RADLAN-HWENVIROMENT (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-HWENVIROMENT # Produced by pysmi-0.3.4 at Wed May 1 13:01:22 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
999,163
e7a339b8496a3d69f9f65ae35f74dfe4a931eb97
# -*- coding: utf-8 -*- import sys from distutils.core import setup # заглушка, если distutils не поддеерживает команду test if __name__ == '__main__' and sys.argv[1] == 'test': exit() with open('README.md') as readme: long_description = readme.read() setup( name='sentry-server', version='', auth...
999,164
88762bbb4c10153c5f0ddd8671e74bfacb40edb9
""" Object detection using Pretrained Tensorflow Model Credits: This code is modified from the online TensorFlow object detection tutorial available here: https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb """ #Imports import numpy as np import os import six.m...
999,165
2edcfc584bcca9bca7e5c87634d45e56a0fa1188
import os import mysql.connector from dotenv import load_dotenv from Loggers import logger load_dotenv() class joins: def __init__(self): host=os.getenv('HOST') user=os.getenv('USER1') passwd=os.getenv('PASSWD') auth_plugin=os.getenv('AUTH_PLUGIN') self.db_connection...
999,166
e564f265b15bf29abe33554e15aeb1608ceea1de
import tensorflow as tf import pickle def build_estimator(model_dir, model_type="combined"): """Build an estimator.""" # Sparse base columns. with open('list_articles.txt', 'rb') as f: list_articles = pickle.load(f) with open('list_productgroup.txt', 'rb') as f: list_productgr...
999,167
80cf6eb92061c666a496c93336cac9a38f195e15
from django.http.response import HttpResponse, HttpResponseRedirect from django.contrib.auth.models import Group from django.shortcuts import render,redirect from vehicles import forms,models from django.contrib.auth.decorators import login_required,user_passes_test from django.db.models import Q,Sum ##################...
999,168
ea536a9a1353cb1f90c85851641dbae242a225d8
# coding = utf-8 ''' @author = super_fazai @File : simple_menu.py @Time : 2017/8/14 19:30 @connect : superonesfazai@gmail.com ''' """ 创建一个菜单栏, 该菜单栏有一个退出操作的菜单 """ ''' (Mac OS以不同的方式处理菜单栏) 要获得类似的结果, 我们可以添加以下行: menubar.setNativeMenuBar(False) ''' import sys from PyQt5.QtWidgets import (QMainWindow, QAction, qApp,...
999,169
c14c5db50cb5b6d4180c2db0684324bc5d288965
import asyncio import json import typer from hue import Light from hue.cli.console import console app = typer.Typer() @app.command() def info( id: int = typer.Argument(1), ip: str = typer.Option(..., "--ip", "-i", envvar="HUE_BRIDGE_IP"), user: str = typer.Option(..., "--user", "-u", envvar="HUE_BRIDGE...
999,170
d4a8930ad54e6051b09c91174f2e8a00003b2ea5
# face detection with mtcnn on a photograph. this code is to identify lips portion in face and fetch color of it. # Then verify the selected lipstick color is matched with lips color after the lipstick has been applied. import re import time import allure import cv2 from PIL import Image from allure_commons.types impo...
999,171
4dc402b498528e4a0afe87d51497a954b24a3bcb
import logging from typing import Tuple, Callable, Any, Generator, NamedTuple, Union, List import numpy as np import pandas as pd from pandas_ml_common.sampling.cross_validation import PartitionedOnRowMultiIndexCV from pandas_ml_common.utils import call_callable_dynamic_args, intersection_of_index, loc_if_not_none, e...
999,172
a6d5faa7b7cb27185b88e8e8c541c5bb3040923d
# Importing necessary dependencies import numpy as np import pandas as pd import matplotlib.pyplot as plt import pyflux as pf filename = "Arun_Valley_export.csv" #Name of file holding CSV data of stock values and Date data = pd.read_csv(filename) data['Date'] = pd.to_datetime(data['Date']) #Converting Data in mm...
999,173
bad588d0b6fd4e8c1704d83f5cbd615eb8e201cc
import numpy as np grid = 9424 ma = np.zeros([300,300]) for i in range(300): for j in range(300): x = i+1 y = j+1 ma[i,j] = int(((x+10)*y + grid) * (x+10)/100)%10-5 max_n = -45 for i in range(300-2): for j in range(300-2): su_n = 0 for k in range(3): for l i...
999,174
7771c610ac7b1f571f35e1ba919e376887bf8d68
from libs.crawler import crawl from bs4 import BeautifulSoup import requests, re ''' 1.매출액-시총 >=0 2.(영업이익*10)배 - 시총 >=0 3.bps >=0 --- 0 4.bps-현재가 >=0 --- 0 5.(유보율:부채비율 = 5:1)<= 20% 6.이익잉여금 >=0 7.이익잉여금-시총 >=0 8.영업이익증가율 >=0 9.per <=10 10.roe >=0 11.roa >=0 12.pbr <=1 13.eps >=0 ''' url = 'https://finance.naver.com/...
999,175
e803b309ae80132bd8e0f10db1bd4a0093affe56
from visual import * from math import * # background alpha=0.1 shape=Polygon([(-0.5,-0.5),(-0.5,0.5),(0.5,0.5),(0.5,-0.5)]) path=[] for i in range(181): newx=20*cos(i*pi/180) newz=alpha*20+20*sin(i*pi/180) path.append((newx,0,newz)) for j in range(181): newx=20*cos(pi+(j*pi)/180) new...
999,176
ef9f7ccce6c7249b905f40ea5d89841a2a3e44fe
from django.shortcuts import render,redirect , get_object_or_404 from .models import Core_committee def teams(request): comittee=Core_committee.objects return render(request, 'teams/team.html',{'committee':comittee})
999,177
fb683bfcee3018dab15e95b8143df040cb6fe20c
import os import pickle import random import numpy as np import torch from PIL import Image from nltk.corpus import wordnet from torchvision import transforms from tqdm import tqdm def get_img_paths(imagenet_dir='/hal9000/datasets/imagenet/image/'): try: image_paths = pickle.load(open('/h/19/jadeleiyu/fr...
999,178
1b90288c4851159841d9cdd9ffac55bcc00c7479
""" Question 12 Question: Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number.The numbers obtained should be printed in a comma-separated sequence on a single line. Hints: In case of input data being supplied to the question, it s...
999,179
90156693c03746423b486b14eda69bb8a3f9c4a9
# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-10-16 20:08 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('smarthome', '0001_initial'), ] ...
999,180
39b0e79699167704fc080c00adaf41869e14d385
#-* coding:UTF-8 -* #!/usr/bin/env python import threading class mythread(threading.Thread): def __init__(self, num): threading.Thread.__init__(self) self.num = num def run(self): print 'I am', self.num t1 = mythread(1) t2 = mythread(2) t3 = mythread(3) t1.start() t2.start() t3.st...
999,181
0985717b7344df1ba53fce97491a2b95640de963
from scipy import stats import numpy as np n = int(input()) arr = list(map(int, input().rstrip().split())) a = sorted(arr) sum = 0 for i in a: sum +=i print(sum/n) #print(np.mean(arr)) print mean length = int(len(a)/2) x4 = a[length-1] x5 = a[length] median = (x4+x5) print(median/2) #calulating median #print(np.me...
999,182
34f106c35ef5de2013d0f80af745a0f835a975e3
numero = abs(int(input("Digite um número: "))) for i in range(0, numero + 1): print(i)
999,183
46f6af88cb685469beb2d863f863a69a532d815d
n = int(input()) if n == 0: print(0) exit(0) mylist = [] for _ in range(n): mylist.append(list(map(int, input().split()))) mylist = sorted(mylist, key = lambda x: x[0], reverse = True) maxday = max(list(zip(*mylist))[1]) lec = [0]*(maxday+1) for idx in range(n): for i in range(maxday, 0, -1): if mylist...
999,184
f83ba4a60bd5f7ba87ae5ef5031f49c02a8a184c
import numpy as np class ex_1_1_33: def productoPunto(self,x,y): res=0 # print(len(x)) if (len(x)!=len(y)): return -1 for i in range(0,len(x)): print(x[i]*y[i],i) res+=x[i]*y[i] print(res) def productoMatricial(self,m1,m2): # comprobacion...
999,185
ba246d2c1e012e5bc6cf161226aafd33df69828b
import requests import base64 from django.conf import settings def get_content_informations(nodeId, token): auth = bytes('Basic ', "utf-8") headers = {'Accept': 'application/pdf' , 'Authorization' : auth + base64.b64encode(bytes(token, "utf-8"))} results = [] try: response ...
999,186
c4111a6d06d7833ab7d443de1e772fbc92bb2e7c
from rest_framework import serializers from .. import models from .tag import TagsSerializer class EnvironmentDetailSerializer(serializers.ModelSerializer): client = serializers.StringRelatedField() tags = TagsSerializer(read_only=True, many=True) tags_id = serializers.PrimaryKeyRelatedField( query...
999,187
ccc7bb4479e1faf65a334543d49fa7ff30097603
from flaskel.ext import default database = default.Database()
999,188
4c4075b71b39896e0235a27fbd7ffb93554da953
import turtle import math import random def draw(): window = turtle.Screen() window.bgcolor("black") denny = turtle.Turtle() denny.color("white") denny.speed(0) rotate=int(360) def draw_circle(t, size): for i in range(10): t.circle(size) size-=4 def draw...
999,189
70bc5e2b840ec438209fa9ff1226e85547f26a9e
import matplotlib matplotlib.use('Agg') import numpy as np import pylab as plt import csv import datetime times = [] repos = {} fname='loc.txt' with open(fname, 'r') as csvfile: r = csv.reader(csvfile, delimiter=' ', quotechar='"') for row in r: print row if int(row[1]) not in times: times.append(in...
999,190
be54afaea13b75afed7d2cc77d5cc2368311e46b
import random import string class Regex: def generate_text(self, cost): raise NotImplementedError def make_nfa(self): raise NotImplementedError def to_int(self): raise NotImplementedError def __repr__(self): return self.__str__() class RegexASCII(Regex): def __in...
999,191
b6d00271e19fe0a69c1ab90b7402c273a43ef9ba
from django.test import TestCase from corehq.apps.linked_domain.models import DomainLink from corehq.apps.fixtures.models import ( LookupTable, LookupTableRow, TypeField, Field, ) from corehq.apps.linked_domain.exceptions import UnsupportedActionError from corehq.apps.linked_domain.updates import update...
999,192
00c075e36eed82a4847a70750934edf5dd15ffbc
import numpy as np class Calculator: @staticmethod def nozzle_area(nozzle_diam): return np.pi * ((nozzle_diam/2) ** 2) #check valid 10/06/18 - Thomas Slusser @staticmethod def potential_height(mass, height, velocity): #return height + 0.5 * mass * velocity ** 2 return he...
999,193
817c82cefbe342e4c9fe2d476d8e1ab493f6c0b7
from unittest.mock import MagicMock, patch import pytest from prereise.cli.data_sources.tests.conftest import ( CURRENT_DIRECTORY_FILEPATH, STRING_DATE_2021_5_1, STRING_DATE_2021_12_1, TEXAS_REGION_LIST, VALID_GRID_MODEL, ) from prereise.cli.data_sources.wind_data import WindDataRapidRefresh NO_I...
999,194
4993934cbe0f28ebfc60596187d5cb933a15c303
import FWCore.ParameterSet.Config as cms # Producer for Hybrid BasicClusters and SuperClusters from RecoEgamma.PhotonIdentification.photonId_cfi import * # photonID sequence photonIDSequence = cms.Sequence(PhotonIDProd)
999,195
c6bef7afda542f010d4ea2e87b8612d3db4d834a
# returns all numbers that can be written as the sum of "power" powers of their digits def digit_power(power): numbers = [] powers = {} for digit in range(0, 10): powers[digit] = digit ** power # limit of one digit digit_max = 9 ** power # we can get a n-digit number from that limit_digits = len(str...
999,196
76fa78728a58c6053035de4d640250fbc06e4f3c
import MySQLdb from cassandra.cluster import Cluster db = MySQLdb.connect("localhost","root","root","Enmetric" ) cursor = db.cursor() cluster = Cluster(['localhost']) session = cluster.connect('enmetric') cursor.execute("select IF(guid IS NULL,'NULL',guid) AS guid,power_avg,power_min,power_max,power_sum,num_measurem...
999,197
f7c89af8d18e5432dfb3508b0016f9acd16427b9
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 OpenStack Foundation. 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.apach...
999,198
0ca98922eda0c34020eacad44f195e123d2cd553
""" Este script se encarga de la lectura del archivo de configuracion .ini leyendo cada una de las propiedades correspondiente a la conexion a la base de datos. Siendo así más centralizado y modular el programa. """ from configparser import ConfigParser # Obtener archivo de configuracion y leer sus pr...
999,199
6a1029882f8d4014a4f872dff54ca85cc161e8db
import logging l = logging.getLogger("claripy.ops") # # AST creation # def AbstractLocation(*args, **kwargs): # pylint:disable=no-self-use aloc = vsa.AbstractLocation(*args, **kwargs) return aloc # # Some operations # # # sigh # # pylint:disable=wildcard-import,unused-wildcard-import from .ast.base im...