text
stringlengths
38
1.54M
# 4014. [모의 SW 역량테스트] 활주로 건설 # https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWIeW7FakkUDFAVH def check(temp): global prev, flag, count if prev == temp: count += 1 if not flag and count == x: count = 0 flag = 1 elif prev - temp == 1 an...
#Suggest best suitable synset for words which are not already present in any synset to 'suggestions2.txt' import gensim def main(): funi = open('outputs/testunigram2.txt','r') fsyn = open('outputs/synset.txt','r') out = open('outputs/suggestions2.txt','w') model = gensim.models.Word2Vec.load('vecmodel') unigram =...
import pytest from pytest_tutorial import is_prime # hard coded multi tests def test_2_is_prime(): assert is_prime(2) def test_3_is_prime(): assert is_prime(3) def test_43_is_prime(): assert is_prime(43) def test_1_is_not_prime(): assert not is_prime(1) def test_4_is_not_prime(): assert ...
# Author:Lithlu #面向对象 --->类 ----->class #面向过程 --->过程---->def (没有返回值)但是在Python中,过程被当成函数 #函数式编程-->函数---->def #函数 def func1(): '''testing 定义函数''' print("in the func1") return 0 #过程 def func2(): '''testing 定义过程''' print("in the func2") x = func1() y = func2() print(x) print(y)
from django.views.generic.base import TemplateView from django.views.generic import ListView from django.contrib.auth import get_user_model class AppStageView(TemplateView): template_name = "common/index.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ...
import FWCore.ParameterSet.Config as cms import RecoEcal.EgammaClusterProducers.particleFlowSuperClusterECALMustache_cfi as _mod particleFlowSuperClusterECALBox = _mod.particleFlowSuperClusterECALMustache.clone( # verbosity verbose = False, # clustering type: "Box" or "Mustache" ClusteringType = "Box",...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Licensed under the GNU General Public License, version 2. # See the file http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt from pisi.actionsapi import pisitools def install(): for data in ["wink","Backgrounds","Buttons","Callouts","FlashControlBars","FlashPreloader...
import MySQLdb import pandas as pd import plotly.plotly as py import plotly.graph_objs as go from plotly.graph_objs import * py.sign_in("ibrahim713", "0LRxZRWw04gEYwULmu8e") trace0 = go.Scatter( x=[1, 2, 3, 4], y=[10, 11, 12, 13], mode='markers', marker=dict( size=[40, 60, 80, 100], ) ) data = [trace0] py.iplot(data, ...
#https://programmers.co.kr/learn/courses/30/lessons/42746?language=python3 numbers = [3, 30, 34, 547, 9,1000] n = len(numbers) #%%뻘짓.. str_list = list(map(str, numbers)) str_len = list(map(len, str_list)) max_len = len(max(str_list, key = len)) for i in range(n) : for j in range(max_len-str_len[i]) : ...
from .checkpoint import * from .distributed import * from .functions import * from .meters import * from .metrics import * from .misc import * from .nested import * from .tensor import *
""" Process station info from WA Dept. of Ecology CTD casts, and save the results for future use. """ import pandas as pd # where the data is, and where results will be stored dir0 = '../../ptools_data/ecology/' # file with station info (good for all years?) sta_fn = dir0 + 'raw/ParkerMacCreadyCoreStationInfoFeb201...
import cal import history import population print("CHOICES:\n 1)Open Calculator \n 2)Show Full History \n 3)Show Specific Line In History\n 4)Clear History \n " "5)Load population \n 6)Insert into database \n 7)Clear database \n 8)Search \n 9)Exit") choices=("1","2","3","4","5","6","7","8","9") while True: t...
# -*- coding: utf-8 -*- """ Created on Sun Mar 11 23:52:26 2018 @author: Ibo Turk """ from keras.preprocessing.image import ImageDataGenerator as IDG from IboTurk_part0 import data as x_train from IboTurk_part0 import data_values as y_train from matplotlib import pyplot as plt from keras.utils import np_ut...
# coding: utf-8 # Author: fengjianbo@wifipix.com # Creadted Time: 2021/1/6 17:54 from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField from wtforms.validators import DataRequired class LoginForm(FlaskForm): username = StringField("Username", validators=[Data...
#!/usr/bin/python import csv import json import os import sys import time import subprocess import datetime import socket from optparse import OptionParser import math import base64 ''' this script reads reporting interval and prev endtime config2 and opens daily log file and reports header + rows within window of re...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.AliveSubtitleExt import AliveSubtitleExt class AntfortuneContentCommunitySubtitleQueryResponse(AlipayResponse): def __init__(self): super(AntfortuneConte...
#!/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 from invoice2data import extract_data from invoice2data.extract.loader import read_templates import json import sys file = sys.argv[1] filename = '/Applications/XAMPP/xamppfiles/htdocs/invoice-app/admin/' + file templates = read_templates('/Users/krzem...
import sys _module = sys.modules[__name__] del sys anuvada = _module datasets = _module data_loader = _module models = _module classification_attention_rnn = _module classification_cnn = _module fit_module_cnn = _module fit_module_rnn = _module utils = _module from _paritybench_helpers import _mock_config, patch_funct...
# Example 2-10. Named tuple attributes and methods (continued from the previous example) from collections import namedtuple City = namedtuple('City', 'name country population coordinates') tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667)) LatLong = namedtuple('LatLong', 'lat long') delhi_data = ('Delhi NCR'...
from duze_cyfry import dajCyfre from turtle import * tracer(4,0) n = 20 def dlc(liczba): liczba = str(liczba) liczbaTable = [] for i in range(len(liczba)): liczbaTable += [dajCyfre(int(liczba[i]))] lineTable = [[] for x in range(5)] for i in range(len(liczbaTable...
# The Trial class represents a single row in the trials table. class Trial: def __init__(self, experiment_id, trial_num, system, ts): self.experiment_id = experiment_id self.trial_num = trial_num self.system = system self.ts = ts def tup(self): return (self.experiment_id, self.trial_num, self.s...
from django.test import TestCase class CoreModelTest(TestCase): # def test_스모크(self): # assert 1 is not 1, "당연히 1 == 1 이죠..." pass
from turtle import Turtle, Screen import random screen = Screen() screen.setup(width=500, height=400) user_input = screen.textinput(title="Make your bet", prompt="Which turtle will win the race (red/blue/green/yellow)") if user_input: is_race_on = True def setup_turtles(): colors = ["red", "orange", "yellow"...
# -*- coding: utf-8 -*- from textminer.errors import MinerError from textminer.main import compile, extract, extract_from_url MinerError = MinerError compile = compile extract = extract extract_from_url = extract_from_url
# -*- coding: utf-8 -*- """ Created on Sun Apr 4 11:09:10 2021 @author: Irfan """ import pandas as pd from sklearn.cluster import KMeans import matplotlib.pyplot as plt import seaborn as sns Mall_Cus=pd.read_csv('Mall_Customers.csv') Mall_Customer=Mall_Cus.drop(['CustomerID','Genre'],axis=1) Mall_Customer.columns ...
class Query(object): def __init__(self, flight_from, flight_to, departure_date, arrival_date, oneway, adult, child, infant): self.flight_from = flight_from self.flight_to = flight_to self.departure_date = departure_date self.arrival_date = arrival_date self.oneway = oneway ...
class User: def __init__(self,id=None, name=None, email=None, password=None, password_hash=None, posts=[]) self.id = id self.name = name self.email = email self.password = password self.password_hash = password_hash self.posts = posts
from knowledge import * def input(path): f = open(path,"r") lines = f.readlines() alpha = lines[0][:-1] N = int(lines[1]) PLs = lines[2:2+N] for i in range(len(PLs)-1): PLs[i] = PLs[i][:-1] return alpha,knowledge(PLs) def output(path,flag, PLs): f = open(path,"w") if...
mujeres=int(input("Cuál es el número de mujeres inscritas?")) hombres=int(input("Cuál es el número de hombres inscritos?")) TotalAlumnos=mujeres+hombres PorcentajeMujeres=(mujeres*100)/TotalAlumnos PorcentajeHombres=(hombres*100)/TotalAlumnos print("Total inscritos: %.02f"%TotalAlumnos,"\nPorcentaje mujeres: %.02...
#!/usr/bin/env python3 import os import sys import time PSU_TYPE = [ "MAINS", "BATTERY", "USB", ] PSU_PROPS = [ "STATUS", "CHARGE_TYPE", "HEALTH", "PRESENT", "ONLINE", "TECHNOLOGY", "CYCLE_COUNT", "VOLTAGE_MAX", "VOLTAGE_MIN", "VOLTAGE_MAX_DESIGN", "VOLTAGE_MIN...
from http.server import HTTPServer, CGIHTTPRequestHandler from http import HTTPStatus import sys import threading import os # This application is docker-hadoop agent which runs script when it receives request. # Actualy this is written to run script remotely, hence there is security leak # But it's no problem because ...
"""Sign-up & log-in forms.""" from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, FileField, TextAreaField from wtforms.validators import ( DataRequired, Email, EqualTo, Length, Optional, ValidationError ) from app.models import User class SignupForm(F...
import time from datetime import datetime as dt hosts_path=r"C:\Windows\System32\drivers\etc\hosts" redirect="127.0.0.1" website_list1='www.cam4.in www.darering.com www.drtuber.com www.babosas.com www.89.com www.xvideos.com www.pinkworld.com' website_list=website_list1.split() with open(hosts_path,'r+') a...
# -*- coding: utf-8 -*- class Module: def __init__(self, cmd, process): self.cmd = cmd self.process = process def GetProcess(): return self.process def ReplaceProcess():
""" Use string formatting to produce the output: (Notice where the values go and also the float formatting / number of decimal places.) 1922 Gibson L-5 CES for about $16,035! Using a for loop with the range function and string formatting (do not use a list), produce the following output (right-aligned numbers): 0 50...
""" Note -: This Module require chromium-chrome driver to work correctly Install using command "apt install chromium-chromedriver" consist routines for text scrapping from websites """ from bs4 import BeautifulSoup from bs4.element import Comment from tldextract import extract from selenium i...
# Generated by Django 2.2.6 on 2021-08-09 13:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Notes', '0011_notes'), ] operations = [ migrations.AlterField( model_name='notes', name='module1', field...
class Node: def __init__(self,val): self.val=val self.lchild=None self.rchild=None class BiTree: def __init__(self): self.root=None self.lchild=None self.rchild=None ###利用队列新建一棵树 def createTree(self,nums): queue=[] cur_pos=0 if ...
from django.urls import path from . import views urlpatterns = [ path('choice/<int:choice_id>/<slug:choice_slug>/' , views.choice , name='choice'), path('poll/<int:poll_id>/<slug:poll_slug>/' , views.poll , name='poll'), path('unvote/<int:choice_id>/<slug:choice_slug>/' , views.unvote , name='unvote'), path(...
# Q1. """ 请实现 2个python list 的 ‘cross product’ function. 要求按照Numpy 中cross product的效果: https://numpy.org/doc/stable/reference/generated/numpy.cross.html 只实现 1-d list 的情况即可. x = [1, 2, 0] y = [4, 5, 6] cross(x, y) > [12, -6, -3] def crossProduct(x: [int], y: [int]) -> [int]: return [x[1] * y[2] - x[2] * y[1], x[2] *...
""" # Author : GS Oh # Experiment : PRECOG_Carla # Note : Utility functions used to save & load & etc. """ # Import pytorch libraries import torch from torch.distributions import MultivariateNormal # Import ETC import numpy as np def load_state(path): print('Loading model_state_dict, optimizer_state...
print('-=-'*10) print('''\033[7m DESAFIO 05 \033[m''') print('-=-'*10) saudação = str(input('Olá tudo bem? ')).strip() p1 = str(input('Qual é o seu nome? ')).strip() if saudação == 'Sim, é você?': print('Estou bem {}, obrigado por perguntar, meu noome e Zoe.'.format(p1)) else: print('Que...
import re def truncate(number: float, digits: int) -> float: pow10 = 10 ** digits return number * pow10 // 1 / pow10 def yes_or_no(question): # used to start and end loop reply = str(input(question + ' (y/n): ')).lower().strip() if reply[0] == 'y': return if reply[0] == 'n':...
##Fibonacci using recursion def fibo_recursion(n): if n<=1: return n else: return(fibo_recursion(n-1) + fibo_recursion(n-2)) term = int(input("Please enter value -> ")) if term<=0: print("Error, please input positive value.") else: print("Fibonacci sequence: \t") for i in range(t...
import hashlib import unittest class MD5Test(unittest.TestCase): def test_md5(self): m = hashlib.md5() m.update("zxcvzxcvgithub.com".encode(encoding="utf-8")) self.assertEqual(m.hexdigest(), "dd1d964df1f16b047d6c814fd5037674") m2 = hashlib.md5() m2.update(b'zxcvzxcv163.com...
# Copyright 2014 Baidu, 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 agreed to in writing, softwa...
# Generated by Django 2.2.4 on 2019-11-19 17:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('product', '0002_auto_20191025_1347'), ] operations = [ migrations.AlterField( model_name='product', name='eng_name',...
# Complete the libraryFine function below. def libraryFine(d2, m2, y2, d1, m1, y1): if y2 <= y1: if y2<y1: return 0 if m2 <= m1: if m2<m1: return 0 if d2 <= d1: if d2<d1: return 0 return 0 ...
''' Created on 27/03/2014 @author: Beto ''' import os def directoryPlay(): print os.curdir print os.path print os.pathsep print os.listdir('.') for node in os.listdir('.'): print node print os.path.isdir('../tests') print os.path.isfile('test2') dirList = os.list...
#!/usr/bin/env python # coding=utf-8 # # <bitbar.title>Slack Notification</bitbar.title> # <bitbar.version>v1.1</bitbar.version> # <bitbar.author>mgjo5899</bitbar.author> # <bitbar.author.github>mgjo5899</bitbar.author.github> # <bitbar.desc>Displays number of unread Slack messages</bitbar.desc> # <bitbar.image>https:/...
import django_filters from mgmnt.models import Directors, Genres, Movies class IMDBBaseFilter(django_filters.FilterSet): """ IMDB Base class filter """ from_date = django_filters.DateTimeFilter(name='created_ts', lookup_type='gte') class MoviesFilter(IMDBBaseFilter): """ Create filter criter...
import torch from .utils import foveal2mask import warnings warnings.filterwarnings("ignore", category=UserWarning) class IRL_Env4LHF: """ Environment for low- and high-res DCB under inverse reinforcement learning """ def __init__(self, pa, max_step, ...
import shutil, pathlib, sys, os top = pathlib.Path(sys.argv[0]).absolute() top = os.sep.join(str(top).split(os.sep)[:-2]) for root, directory, file in os.walk(top): for branch in directory: if '__pycache__' in branch: print(os.path.join(root, branch)) shutil.rmtree(os.path.join(roo...
from socket import * # import socket import threading import random def udpServer(): serverPort = 12000 sequenceNum = '0' serverSocket = socket(AF_INET, SOCK_DGRAM) serverSocket.bind(('', serverPort)) print("The server is ready to receive") while True: # loop forever received = random...
import json from Classes.Person import Person class Administrator(Person): def __init__(self, _id, firstName, lastName, email, createdOn, lastEdit, password, ): super(Administrator, self).__init__(_id, firstName, lastName, email, createdOn, lastEdit) self._id = _id self._firstName = first...
#place this file in get_user_idadir() #the next line is set by install.cmd CUSTOM_SCRIPT_DIR='F:/NOTES/re/ida_python' #don't touch the previous line import sys sys.path.append(CUSTOM_SCRIPT_DIR) import idaapi idaapi.require('hexnum') idaapi.enable_extlang_python(True)
from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from comment import views app_name = 'comments-api' urlpatterns = [ path('', views.CommentListAPIView.as_view(), name="list"), path('create/', views.CommentCreateAPIView.as_view(), name="create"), path('<int:comment...
nums = [-1, 0, 1, 2, -1, -4] if len(nums)<3: print(False) res=[] nums.sort() print(nums) i,j=0,len(nums)
""" compare the efficiency of list comprehension and append """ import time n_list = [10**3, 10**4, 10**5] for n in n_list: t1 = time.time() a1 = [i for i in range(n)] t2 = time.time() a2 = [] for i in range(n): a2.append(i) t3 = time.time() del a1, a2 print("length={}, list compre...
#!/home/dario/PycharmProjects/django01-basico/venv/bin/python from django.core import management if __name__ == "__main__": management.execute_from_command_line()
# -*- coding: utf-8 -*- """ Created on Wed Mar 27 11:24:43 2019 @author: tqc268 """ import sys import pandas as pd import os sys.path.insert(0,r'../../pydaisy/') from datetime import datetime from pydaisy.Daisy import DaisyDlf import numpy as np grain = ['SB', 'Winter Wheat JG','Vinterbyg','Rug','Winter Rape PA','Spri...
import PyQt5.QtWidgets as qtw import PyQt5.QtCore as qtc import PyQt5.QtGui as qtg from mate.ui.views.map.layer.lineData_config_view \ import Ui_LineDataConfig from mate.ui.views.map.layer.layer_config import LayerConfig, LayerConfigMeta import mate.net.utils as net_utils import mate.ui.utils as ui_utils import mat...
COMFORTABLE_STEERING_ACTIONS = { 0: 'IDLE', # Zero steer, zero accel # Based on simple heuristic solution to the single waypoint env where # steering set to 10% of the delta between current and desired heading # smoothly steers towards the waypoint. Here we expect the net to use # the large and sm...
from services.apps.service.models import Service def before_feature(context, feature): context.fixtures = ['services.json']
from unittest import TestCase from unittest.mock import patch from reconcile.utils.ocm import OCM class TestVersionBlocked(TestCase): @patch.object(OCM, '_init_access_token') @patch.object(OCM, '_init_request_headers') @patch.object(OCM, '_init_clusters') # pylint: disable=arguments-differ def se...
#!/usr/bin/python3 def uniq_add(my_list=[]): nl = [] i = 0 for item in my_list: if item not in nl: i += item nl.append(item) return(i)
def count_words(filename): """jisuan""" try: with open(filename) as f: contents = f.read() except FileNotFoundError: msg = "sorry about" + filename print (msg) else: word = contents.split() len1 = len(word) #print(filename+wo...
import calendar print(calendar.calendar(2020)) print(calendar.month(2020,4)) print("the first week day: ",end="") print(calendar.firstweekday()) print(calendar.monthlen(2020,5)) print(calendar.isleap(2020)) print(calendar.monthcalendar(2020,2)) print(calendar.leapdays(1999,2020))
#!/usr/bin/env python # -*- coding: utf-8 -*- import xml.etree.ElementTree as ET; import re; import zipfile; import os; import json; import shutil; import shapefile; class RusRegisterConverter: cs_definitions = {} cs_aliases = {} def __init__(self): logger = None self.load_coord_system_...
import sqlparse from quest.exception import QuestOperationNotAllowedException # User-provided hierarchies. from quest.config import drilldown_parent2child, rollup_child2parent def drilldown(query, parent_attribute): """ Takes a query and parent attribute to drilldown on -- i.e. return a query with the par...
import os #outputdirname="Raman/SkimmedTuples/V12_Puppi_V3_NoTriggerOnData/" outputdirname="Raman/SkimmedTuples/testing" #outputdirname="Raman/AnalysisTuples_2016DataMC_V5/TTBar/" inputprefix="--input-dir=root://cmsxrootd.hep.wisc.edu//store/user/khurana/" cmsswpath="/afs/hep.wisc.edu/cms/khurana/MonoH2016MCProductio...
import k8s_auth from kubernetes import watch def main(): # Configs can be set in Configuration class directly or using helper # utility. If no argument provided, the config will be loaded from # default location. api_v1 = k8s_auth.login() count = 10 w = watch.Watch() for event in w.stream(...
from rest_framework import serializers from .models import Upscale class UpscaleSerializer(serializers.ModelSerializer): gt = serializers.ImageField(allow_empty_file=False) name = serializers.CharField( required=False, allow_blank=True, max_length=100) upscale_model = serializers.ChoiceField( ...
#!/usr/bin/env python3 from argparse import ArgumentParser def imagenoop(filename): results = None image = filename return (results, image) def coverage_summary(filename): resultsname = 'coverage_summary' results = {resultsname : {}} with open(filename) as f: lines = [] for li...
import csv import pandas as pd import plotly.graph_objects as go import plotly.figure_factory as ff import statistics as st import random file_data = pd.read_csv('/Users/prathamarora/Downloads/Python_Projects/sampling_distribution/medium_data.csv') data = file_data['reading_time'].to_list() standard_deviation = st.st...
"""Functions to validate user-input""" import numpy as np from astropy.coordinates import SkyCoord def compute_baselines(n_core, n_remote, n_int, hba_mode): """For a given number of core, remote, and international stations and the HBA mode, compute the number of baselines formed by the array. The nu...
import pandas as pd import sys import numpy as np import re if len(sys.argv) != 3: print('Invalid') if len(sys.argv) == 3: try: df = pd.read_csv(sys.argv[1]).to_numpy().tolist() text = list(pd.read_csv(sys.argv[2]))[0] dna = list(pd.read_csv(sys.argv[1]))[1:] count_dna = [] ...
from django.db.models.signals import post_save from django.dispatch import receiver from experchat.models.users import Expert, ExpertProfile @receiver(post_save, sender=Expert) def create_expert_profile(sender, **kwargs): """ After creating expert, create expert profile. """ if kwargs['created']: ...
# Import the modules import sys while True: userchoice = input("Encrypt or Decrypt [Enter to quit]? ").upper() if userchoice.startswith("E"): prompt = "What is the plaintext to encrypt? " sign = 1 elif userchoice.startswith("D"): prompt = "What is the ciphertext to decrypt? " ...
""" The I_downarrow unique measure, proposed by Griffith et al, and shown to be inconsistent. The idea is to measure unique information as the intrinsic mutual information between and source and the target, given the other sources. It turns out that these unique values are inconsistent, in that they produce differing ...
# file "bld_key_build.py" from pygroupsig.common_build import ffibuilder ffibuilder.cdef(""" typedef groupsig_key_init_f bld_key_init_f; """) ffibuilder.cdef("""typedef groupsig_key_free_f bld_key_free_f;""") ffibuilder.cdef("""typedef groupsig_key_copy_f bld_key_copy_f;""") ffibuilder.cdef(""" typedef groupsig_ke...
import string class Token: replace_proper_noun = False def __init__(self, token): self.set(token) def set(self, token): self.token = token def __str__(self): return self.token def __eq__(self, other): return str(self) == str(other) class CheckingToken(Token): def __init__(self, token): assert self...
from node import Node class LinkedList: def __init__(self): self.head = None self._size = 0 def append(self,e): if self.head: #inserção quando já possui elementos pointer = self.head while(pointer.next): pointer = pointer.next ...
# -*- coding: utf-8 -*- from StringIO import StringIO from cgi import FieldStorage from decorated.base.context import Context from decorated.base.dict import Dict from metaweb.impls import webpy from metaweb.impls.webpy import WebpyFileField from testutil import TestCase from web.utils import threadeddict class WebpyF...
from selenium import webdriver link = "http://suninjuly.github.io/selects1.html" browser = webdriver.Chrome() browser.get(link) x = browser.find_element_by_css_selector("#num1") #x1 = x.get_attribute("span") y = browser.find_element_by_css_selector("#num2") x = int (x.text) y = int (y.text) z = str (x+y) print (z) from...
age= 15 if(age>18): print("you are eligibe") elif(age<18): print("you are not eligible")
# Python's math module has functions called sin, cos, and tan # as well as the constant "pi" (which we will find useful shortly) from math import sin, cos, tan, pi # Run this cell. What do you expect the output to be? print(sin(60)) from math import pi def deg2rad(theta): """Converts degrees to radians""" # ...
from git import Repo from itertools import islice, chain from subprocess import run, PIPE import json keywords = ['fix', 'bug', 'error', 'fail'] def is_contains_whole_word(message, word): message = message.replace('\n', ' ').lower() return message.startswith(word) or message.endswith(word) or ' {} '.format(wo...
from flask import Flask,render_template,request import json import os import cv2 import numpy as np import shutil import time import pytesseract as py import urllib.parse print ("starting!!!!!!!") IMAGE_UPLOADS = "./static/images" OUTPUT_UPLOADS= "./static/images/output" import os, sys base_dir = '.' if hasattr(sys, '...
import PythonQt from PythonQt import QtCore, QtGui, QtUiTools def addWidgetsToDict(widgets, d): for widget in widgets: if widget.objectName: d[str(widget.objectName)] = widget addWidgetsToDict(widget.children(), d) class WidgetDict(object): def __init__(self, widgets): add...
print("contador de pares e impares") valores = int(input('cuantos valores vas a introducir??')) if valores < 1: print('imposible') else: pares = 0 for i in range (0, valores): numero = int(input('escribe el valor ' + str(i) + " ")) if numero % 2 == 0: pares += 1 print("ha escrito " + str(p...
#!/usr/bin/env python3 # http://adventofcode.com/2017 def difference(row): l = [] for item in row.split(): l.append(int(item)) return max(l) - min(l) def evenly_divided(row): from itertools import permutations for pair in permutations(row.split(), 2): if int(pair[0]) % int(pair[...
from user import models def test_models_insert(): models.insert('마이콜', 'michol@gmail.com', '1234', 'male') def test_models_findby_email_and_password(): result = models.findby_email_and_password('michol@gmail.com', '1234') print(result) # test_models_insert() test_models_findby_email_and_password()
# -*- coding: utf-8 -*- """ Created on 02/09/2021 @author: Kelvin @github: gitpinto """ #Importing required libraries from pymongo import MongoClient from static import constants import tweepy import pytumblr #MongoDB Connections client = MongoClient(constants.mongo.CONN_STRING) db = client.get_database(constants.mo...
import pandas as pd from fairness.data.objects.Data import Data class Ricci(Data): def __init__(self): Data.__init__(self) self.dataset_name = 'ricci' # Class attribute will not be created until data_specific_processing is run. self.class_attr = 'Class' self.positive_class_...
# # 따라하며 배우는 파이썬과 데이터과학(생능출판사 2020) # 12.12 새로운 열을 쉽게 생성해 보자, 319쪽 # import pandas as pd import matplotlib.pyplot as plt countries_df = pd.read_csv('d:/data/countries.csv', index_col = 0) countries_df['density'] = countries_df['population'] / countries_df['area'] print(countries_df)
# # -*- coding: utf-8 -*- # # Copyright (c) 2018 Intel Corporation # # 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 app...
import time import cv2 import os import pickle def video_to_frames(input_path, output_path): """Function to extract frames from an input video file and save them as separate frames in an output directory. Args: input_path: Path to video file. output_path: Path to save the frames. Retur...
from ...biotools import ( load_record, write_record, sequence_to_biopython_record, find_specification_label_in_feature, sequences_differences_segments, ) from ...Specification.Specification import Specification from ...Location import Location class RecordRepresentationMixin: """Mixin for DnaO...
import urllib2, lxml.html import settings from urlparse import urlparse from torrent_handler import TorrentHandler class ElitetorrentSpider(): def __init__(self, url): self.url = url parsed_uri = urlparse(url) self.domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri) self...