text stringlengths 38 1.54M |
|---|
import pandas as pd
import yaml
class Dict2Class(object):
def __init__(self, dvar, def_topvar):
if not isinstance(dvar, dict) or not dvar:
setattr(self, def_topvar, None)
return
for key in dvar:
if isinstance(dvar[key], list):
nested_dclass = []... |
import configparser
import datetime
import sys
import time
import json
from threading import Thread
from web3 import Web3
from web3.middleware import geth_poa_middleware
from systemstats import SystemStats
class Mchain_Monitor():
def __init__(self):
self.record = {}
self.sys_stat = SystemStats()... |
class Encapsulation:
a = "hello"
_a = "python"
__a = "welcome"
print(Encapsulation.a)#hello
print(Encapsulation._a)#python
#print(Encapsulation.__a) we cant print private variable out side of a class |
from flask import Flask, render_template, jsonify, request, redirect, url_for, jsonify
host = 'localhost'
port = 5000
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///aurora.db'
@app.route('/')
def index():
return redirect(url_for... |
import os
from tensorflow.python.keras.datasets import mnist
from tensorflow.python.keras import models
from tensorflow.python.keras import layers
from tensorflow.python.keras.utils import to_categorical
os.environ['TF_CPP_MIN_LONG_LEVEL'] = '2'
# Loading data
(train_images, train_labels), (test_images, test_labe... |
from db_handling.connect import connect
import random
name = ["Andrei","Rebekah","Jacob","Simeon","Alistair","Hamza","Michael","Joab","Brogan","Fahid","Jawad","Danesh","Daniel","Harry","Shameela","Chenyse","Maryama","Jazz","Abdur"]
quirk = ["Fast", "strong", "earth", "Fire", "Water", "Rasengun", "Trump", "Biden", "Sup... |
inputArr = ["5 6",
"1 2 3",
"1 3 4",
"4 2 6",
"5 2 2",
"2 3 5",
"3 5 7",
"1"
]
def input():
return inputArr.pop(0)
n, m = input().split()
n, m = int(n), int(m)
graph = dict()
for i in range(m+1):
graph[i+1] = set()
for i in range(m):
st, en... |
from setuptools import setup, find_packages
import os.path
# Get the long description from the relevant file
__here__ = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(__here__, 'README.rst'), 'r') as f:
long_description = f.read()
setup(
name='capgains',
version='0.0.1dev',
# Note:... |
from django.views.generic import ListView, DetailView
from django.views.generic.edit import UpdateView, DeleteView, CreateView
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import PermissionDenied
from .models import CustomUser
from rosters.m... |
from django.db import models
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver
class Video(models.Model):
video = models.FileField()
image = models.ImageField()
@receiver(pre_delete, sender=Video)
def video_delete(sender, instance, **kwargs):
instance.video.... |
import logging
import os
import random
import shutil
import time
import warnings
import collections
import pickle
from scipy import sparse
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
import torch.optim
import torch.u... |
# encoding: utf8
__author__ = 'lgl'
from __init__ import PyTest
class TestEncode(object):
def test_dump(self):
d = {}
self.loadDict(d)
self.assertEqual(self.dump(), u'{}')
def test_encode_truefalse(self):
d = {'True': False, 'False': True, 'None': None}
self.loadDict(d... |
#!/usr/bin/env python
"""
Requirements:
- requests (installation: pip install requests)
- lxml (installation: pip install lxml)
"""
import requests
import lxml.html
import os
def download_file(file_name, url):
#file_name = url.split('/')[-1]
# NOTE the stream=True parameter
r = requests.get(ur... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import datetime
import pytest
import requests_mock
from factory import Factory
from ollehtv import (
OllehTV,
OllehTVButton,
OllehTVError,
OllehTVState,
)
class OllehTVFactory(Factory):
class Meta:
model ... |
'''
Date:2019-2-7
Author:SaulZhang
Description:Webๅฏ่งๅ็้ขไธๆจกๅไบคไบ็ๆฅๅฃ,็จไบ้ขๆตๅๆกๆฐๆฎๅๆน้็ๆฐๆฎ
'''
from keras.preprocessing.sequence import pad_sequences
import pandas as pd
import jieba
import pickle,pprint
import string
#ๅฐๅไธชๅฅๅญ่ฝฌๅไธบword2idx็ๅฝขๅผ
def processSingleExample(string,word2idx,maxlen):
sample = string.strip()
sa... |
import os
import socket
s = socket.socket()#socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.10.111'
#print(host)
port = 65432
s.bind((host, port))
s.listen()
print('server started')
#while True:
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
... |
n = input()
dd = {}
num = input().split()
for i in range(len(num)):
num[i] = abs(int(num[i])-(i+1))
for i in num:
if i in dd.keys():
dd[i]+=1
else:
dd[i] = 1
tt = list(dd.keys())
tt.sort(reverse = True)
for i in tt:
if dd[i]>1:
print(i,dd[i])
|
# On utilise les corrdonnรฉes sphรฉriques pour placer les points et satellites :
# la longitude et la colatitude (angle depuis le meridien de Greenwich et le pole Nord)
# Distances en km
# Angles en radian
## Importations
import pygame as pg
from math import sin, cos, sqrt, pi
from random import randint
import matplotl... |
print('Import package...')
import numpy as np
import functools
from pathlib import Path
import tensorflow as tf
from tensorflow.contrib import predictor
from utils import *
import time
import matplotlib.pyplot as plt
# %matplotlib inline
print('Have done!')
class get_model():
def __init__(self,para):
... |
import json
import csv
from shapely.geometry import shape, Point
import datetime as dt
from operator import itemgetter
# depending on your version, use: from shapely.geometry import shape, Point
# load GeoJSON file containing sectors
with open('Neighborhoods.geo.json') as f:
js = json.load(f)
# construct point ba... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright ยฉ 2018 Ryan Collins <rlcollins@g.harvard.edu>
# Distributed under terms of the MIT license.
"""
Extract & classify trio allele counts for all complete sets of non-null genotypes
"""
import argparse
import sys
from collections import defaultdict
import pysam
... |
"""Unit tests for the stats app"""
from django.contrib.auth.models import User, Permission
from django.test import TestCase, Client
from courses.models import Course, Lesson, Section, Task
from stats import utils
from stats.models import UserOnTask
class StatsTestCase(TestCase):
"""Test case for stats"""
... |
# ๅนณ่กก็น้ฎ้ข
def getPoint(arr):
"""get ponit"""
if len(arr) < 2:
return
tag = 1
help = []
while tag < len(arr):
sum = 0
sum_after = 0
for i in range(tag):
sum += arr[i]
for i in range(tag+1, len(arr)):
sum_after += arr[i]
if sum == ... |
def greet(name):
print("Welcome " +name)
def mySum(s1, s2):
add = s1 + s2
return add
name = input("Enter your name ")
s1 = int(input("Enter first number"))
s2 = int(input("Enter second number"))
addition = mySum(s1, s2)
print(addition)
greet(name)
|
from django.shortcuts import render
# Create your views here.
from .models import Samsung
from .serializers import SamsungSerialization
from rest_framework.viewsets import ModelViewSet
#GET GET/{id} POST PUT PATCH DELETE
class SamsungOperations(ModelViewSet):
queryset = Samsung.objects.all()
serializer_class ... |
# Uses python3
# Task: Given an integer ๐, find the last digit of the ๐th Fibonacci number ๐น๐ (that is, ๐น๐ mod 10).
# Solution: Iterate from 0-n summing previous immediate 2 to make up next list member and return
# the last digit of the last number in sequence
def get_fibonacci_last_digit(n):
if ... |
from django.conf.urls import url, patterns
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = patterns('Website.views',
url(r'^$', 'index'),
url(r'^index/$', 'index')
)
|
import calendar
import datetime
# month, day, year = raw_input().split()
month, day, year = (int(x) for x in raw_input().split())
# print(list(calendar.day_name)[calendar.weekday(year, month, day)].upper())
# datetime(year, day, month).weekday()
# datetime.datetime.today().weekday()
ans = datetime.date(year, month, ... |
def find_ternary(num): #2
quotient = num/3 #3
remainder = num%3
if quotient == 0: #4
return ""
else:
return find_ternary(int(quotient)) + str(int(remainder)) #5
#1
def toDec (a, base):
ans = 0 # output sum
inc = 1 # incrementing n... |
# Copyright 2019 The PytorX Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
from typing import Mapping, Union
import numpy as np
from .operation import Operation
from .op_placeholder import OpPlaceholder
class OpInTrainPhase(Operation):
"""Whether it is in training phase."""
def __init__(self, **kwargs):
self.inputs = []
self.params = {}
self.shape = ()
... |
import numpy as np
import sys
if sys.version_info.major == 2:
input = raw_input
def read_matrix(N, M):
matrix = np.empty((N, M), dtype=np.float32)
for i in range(N):
matrix[i, :] = list(map(float, input().rstrip().split(" ")))
return matrix
def read_data():
cur_row_idx = 0
n_sampl... |
# Generated by Django 3.0.3 on 2020-12-08 19:00
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('class', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='chd',
name='Education',
),
]
|
import imaplib
import email
from email.header import decode_header
import os
import re
import traceback
import datetime
def log(login, password):
reg_exp = re.compile(r'@\w+.\w+')
domain = reg_exp.findall(login)
domain = str(domain).replace('@', "").replace('[', "").replace(']', "").replace("'", "")
i... |
from astropy.io import fits
import spectrum
from matplotlib import pyplot as plt
import numpy as np
from astropy.stats import biweight_midvariance as bwtmv
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--incube", type=str,
help="Input data cube.")
parser.... |
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
from hamcrest import assert_that, equal_to
import requests
from pathlib import Path
import hashlib
def file_as_bytes(file):
with file:
return file.read()
driver = Chrome()
driver.maximize_window()
driver.get('https://line.m... |
from django.shortcuts import render,redirect
from django.contrib import messages
from django.contrib.auth import authenticate,login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm
from .forms import UserRegisterForm
from django.core.mail import send_mai... |
from lesson05_appium.page.app import App
from lesson05_appium.util.util_info import Utilinfo
class TestWechatPo:
def setup_class(self):
self.app = App()
self.info = Utilinfo()
self.name = self.info.get_name()
self.phone_num = self.info.get_phone_num()
def set_up(self):
... |
# -*- coding: utf-8 -*-
import json
import sys
from random import sample
from instapy import InstaPy
from pprint import pprint
from selenium.common.exceptions import NoSuchElementException
try:
with open(sys.argv[1]) as f:
data = json.load(f)
insta_username = data['Account']['Username']
in... |
# SPDX-FileCopyrightText: 2020 Lukas Schrangl <lukas.schrangl@tuwien.ac.at>
#
# SPDX-License-Identifier: BSD-3-Clause
import sys
from . import app
ret = app.run(sys.argv)
sys.exit(ret)
|
import logging
import os
import json
from datetime import datetime
from pytorch_pretrained_bert.bert_trainer_apex import Hypers
logger = logging.getLogger(__name__)
class HypersRC(Hypers):
def __init__(self, args):
super().__init__(args)
self.two_layer_span_predict = True
self.max_seq_le... |
from tkinter import *
root = Tk()
root.title("RPA for SWPart")
# ํ์ผ ํ๋ ์ (ํ์ผ ์ถ๊ฐ, ์ ํ ์ญ์ )
file_frame = Frame(root)
file_frame.pack()
btn_add_file = Button(file_frame, padx=5, pady=5, width=12, text="ํ์ผ์ถ๊ฐ")
btn_add_file.pack(side="left")
btn_del_file = Button(file_frame, padx=5, pady=5, width=12, text="์ ํ์ญ์ ")
btn_del_f... |
'''
various methods to help analyze the location tweets
first we get the tweets from the user_mention_map.
'''
import cjson
import re
import nltk
from nltk.corpus import stopwords
from library.mrjobwrapper import ModifiedMRJob
class TweetsGeoAnalysis(ModifiedMRJob):
DEFAULT_INPUT_PROTOCOL = 'raw_value'
def __init_... |
# Copyright 2020 Lorna Authors. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
from Mysql import *
from dico import *
import time
class Main:
def Mysql(self):
pass
def dictionnaire(self):
dico = Dico()
dico.question()
dico.dictionnaire()
if __name__ == "__main__":
Main_prog = Main()
Main_prog.dictionnaire()
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Stephen Po-Chedley 9 May 2019
Script (in development) to take data in an "extension" directory
and organize it adhering to normal CMIP path conventions so that it
can be scanned using xagg.
PJD 15 May 2020 - Update to extract mip_era from file global atts
PJD 17 Jun... |
class RingBuffer:
def __init__(self, capacity):
self.capacity = capacity
self.storage = [None] * capacity
self.pointer = 0
def append(self, item):
# if there is no capacity
if self.capacity == 0:
return
# add initial items
self.storage[self.... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 7 11:28:43 2019
@author: Juan Esteban Cepeda
"""
import numpy as np
lista = [1, 2, 3]
print(max(lista)) |
def multilevel_selection_sort(elements, sort_by_list):
for sort_by in sort_by_list[-1::-1]:
for i in range(len(elements)):
min_index = i
for j in range(min_index + 1, len(elements)):
if elements[j][sort_by] < elements[min_index][sort_by]:
min_index... |
import sys
sys.path.append("Structures/")
sys.path.append("Algorithms/")
from sys import argv
from bfs import Bfs
from bf import Bf
from fw import Fw
from scc import Scc
from dk import Dk
from graph import Graph
def main():
G = Graph()
G.buildGraph(argv[2])
if argv[1] == 'bfs':
s = G.getInitVe... |
import numpy as np
t_0=np.array(50,dtype=np.int32)
print(t_0)
t_1=np.array([b"aaaaaa",b"bbbbbbbbb",b"cccccc"])
t_2=np.array([[True,False,False],
[True,False,False],
[True,False,False]])
t_3=np.array([[[0,0],[0,1],[0,2]],
[[0,0],[0,1],[0,2]],
[[0,0],[0,... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-28 20:02
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('UGP', '0018_eukaryotestablenew2'),
]
operations = [
migrations.DeleteModel(
... |
def solve(line):
return line.count("(") - line.count(")")
def parse(file_name):
with open(file_name, "r") as f:
return f.readline()
if __name__ == '__main__':
print(solve(parse("data.txt")))
|
from collections import Counter
class Solution:
def makeSubKSumEqual(self, arr, k: int) -> int:
if len(arr) == k:
return 0
n = len(arr)
pr = [0] * (n + 1)
for i in range(n):
pr[i + 1] = pr[i] + arr[i]
cur_sum = pr[k]
eq_sum = True
for ... |
class Stats(object):
attack=0.0
defense=0.0
speed=0.0
maxHealth=0.0
currentHealth=0.0
maxMagic=0.0
currentMagic=0.0
accuracy=0.0
evasion=0.0
statusEffect=[]
money=0.0
credits=0.0
#overrides for multiplication and addition for applying single operations across all states.
def __mul__(self, other):
self.... |
from core.things import Thing
from random import choice
""""Base Agent"""
class Agent(Thing):
def __init__(self, actions):
self.actions = actions
def decide_action(self, percept):
raise NotImplementedError
def interpret_input(self, percept):
return percept
""""Agent Structur... |
#------------------------------------------------------------------------------
# Name: search_directory.py
# Author: Kevin Harris
# Last Modified: 02/13/04
# Description: This Python script demonstrates how to use os.path.walk()
# and a call-back function to recursively walk ... |
#ITM 313 - Naveed Mustafa Hussain hw1
# Takes name input and then displays a greeting message
name = input("Please enter your full name: ")
print("Hello, ", name, ", nice meeting you.")
# Takes temperature input in Fahrenheit
temp_f = eval(input("\nEnter temperature in Fahrenheit: "))
celcius = 5.0/9.0 * (temp_f - 32... |
import wx
from wx.lib.dialogs import messageDialog, singleChoiceDialog
def open_file(wcd, message="Select a file", path=""):
application = wx.PySimpleApp()
# Create an open file dialog
dialog = wx.FileDialog(None, message, defaultDir=path, wildcard=wcd, style=wx.OPEN)
# Show the dialog and get user in... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import copy
import logging
import random
from collections import defaultdict, namedtuple, deque
import io
import numpy as np
import typing
from n... |
#!/usr/bin/env python3
from __future__ import absolute_import, division, print_function, unicode_literals
from dist_optimizer_test import DistOptimizerTest
from common_distributed import MultiProcessTestCase
from common_utils import run_tests
class DistOptimizerTestWithFork(MultiProcessTestCase, DistOptimizerTest):
... |
from testdata.list_resource import single_resource_response_code as srrc,single_resource_data
import allure
@allure.step('single_resource_response code')
def test_single_resource_response_code():
assert srrc == 200
@allure.step('single_resource_response data not empty')
def test_single_resource_data_not_empty()... |
# import sys
# sys.path.append('C:/Users/mande/Desktop/New folder/SMS/User')
# import request
from User import request
def tech_work():
print("Tech Package --> work Module")
print("tech_work Function")
print()
request.user_request()
|
import logging
from hbmqtt.client import MQTTClient
class MqttClient:
def __init__(self, config):
self.config = config
self.client = MQTTClient(
client_id=config.mqtt_client_id,
config={
'keep_alive': config.mqtt_keep_alive,
},
)
as... |
from io import BytesIO
from struct import unpack, pack
from os.path import getmtime, isfile, join, dirname
from os import utime, mkdir
import errno
from PIL import Image
import lxml.etree as etree
from kbinxml import KBinXML
from . import GenericFile
from . import lz77
from .ImageDecoders import image_formats, cachab... |
from django.contrib import admin
from sobreviventes.models import Localidade, Itens, Sobrevivente, RelatoContaminacao, Recurso
admin.site.register(Localidade)
admin.site.register(Itens)
admin.site.register(Sobrevivente)
admin.site.register(RelatoContaminacao)
admin.site.register(Recurso) |
#!/usr/bin/python3
"""
get_allcategories.py
MediaWiki Action API Code Samples
Demo of Allcategories module: GET request to list all categories
on the English Wikipedia, starting from "15th-century caliphs".
MIT license
"""
import json
import pandas
import requests
wikipedia_url = "http://en.wik... |
import operator
from copy import deepcopy
from django.core.exceptions import MultipleObjectsReturned
from django.db.models import QuerySet
def in_operator(field, values):
return field in values
def not_in_operator(field, values):
return field not in values
class InMemoryCache(object):
"""
Mutable... |
import multiprocessing
from os.path import join
from copy import copy
import numpy as np
from PIL import Image
import visual_words
def get_feature_from_wordmap(opts, wordmap):
'''
Compute histogram of visual words.
[input]
* opts : options
* wordmap : numpy.ndarray of sha... |
import helper
textFile = open('./assets/testData.txt', 'r')
for line in textFile:
helper.analyzer(line)
textFile.close()
helper.graph() |
# Copyright (C) 2019 Braiins Systems s.r.o.
#
# This file is part of Braiins Open-Source Initiative (BOSI).
#
# BOSI is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at y... |
import csv
with open('contacts.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=",")
print(csv_reader)
for data in csv_reader:
print(data)
|
import os
import cv2
import time
import numpy as np
import skimage
import vip_hci as vip
import matplotlib.pyplot as plt
from hciplot import plot_frames, plot_cubes
def start_and_end_program(start):
'''
Args:
start : a boolean. If it is the start of the program
Return:
None
'''
lo... |
from api.component import Component
class Finger(Component):
def defComponents(self):
self.addSubcomponent("lbot","Beam")
self.addSubcomponent("ltop","Beam")
self.addSubcomponent("hinge","Hinge")
#self.addSubcomponent("tetra","Tetrahedron")
def defParameters(self):
... |
import sys
import os
import re
import itertools
import jsonlines
import json
from pathlib import Path
from graph_tool.all import *
import xml.etree.cElementTree as etree
sys.path.append(str(Path('.').absolute()))
from concite.embedding.node2vec_wrapper import Node2VecEmb
class AclExtractor:
def __init__(self, js... |
# A Python "namespace package" http://www.python.org/dev/peps/pep-0382/
# This always goes inside of a namespace package's __init__.py
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
|
import dateutil.parser
import re
from findImage import findImage
def discardEmptyLine(line):
if (re.search(r'^\s*$', line)):
return 1
else:
return 0
def parseDate(line):
try:
yourdate = dateutil.parser.parse(line)
except:
yourdate=0
return yourdate
f=open("si... |
"""
Django settings for BusinessHRMS project.
Generated by 'django-admin startproject' using Django 3.1.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
""... |
row = int(input("Enter the number of rows:"))
k = 0
for i in range(0, row):
for j in range(k, row - 1):
print(' ', end='')
print("*", end='')
for j in range(k * 2 - 1):
print(' ', end='')
if i is not 0:
print("*", end="")
print()
k += 1
|
from django.contrib import admin
from .models import Level, Session, Text, SessionText, Comment
# Register your models here.
class LevelAdmin(admin.ModelAdmin):
list_display = ('name','description')
list_filter = ['name']
class SessionAdmin(admin.ModelAdmin):
list_display = ('name','instructions','level')
list_f... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Enterprise Management Solution
# GRP Estado Uruguay
# Copyright (C) 2017 Quanam (ATEL SA., Uruguay)
#
# This program is free software: you can redistribute it and/or modify
# it... |
from app import app, db
from models import User
# db.create_all()
# admin = User(username='admin', email='admin@example.com')
# guest = User(username='guest', email='guest@example.com')
#
# db.session.add(admin)
# db.session.add(guest)
# db.session.commit()
|
import sys
import traceback
import warnings
from queue import PriorityQueue, Empty
import numpy as np
from sim import debug
from sim.devices.components import powerPolicy
from sim.experiments.scenario import RANDOM_SCENARIO_RANDOM
from sim.learning.agent.minimalTableAgent import minimalTableAgent
from sim.learning.st... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 08 23:29:58 2017
@author: Kitty
"""
#coding=utf-8
import pandas as pd
import numpy as np
from datetime import *
import matplotlib.pyplot as plt
import matplotlib as mpl
import datetime
from pylab import *
from WindPy import *
from sklearn.decomposition import PCA
import ... |
from fuzzywuzzy import fuzz
import csv
import re
#from datetime import datetime
from nltk.tokenize import TweetTokenizer
from nltk.corpus import stopwords
import nltk
import unicodedata
import string
import re
from collections import Counter
from fuzzywuzzy import fuzz
from nltk.stem.snowball import SnowballStemmer
imp... |
# crie uma lista chamada numeros e duas funรงรตes chamadas sorteio e somaPar a sorteio vai sortear 5 numeros
# colocar na lista e a somaPar vai somar todos os pares sorteados
from random import randint
numeros = []
def sorteio(database):
for c in range(0,5):
database.append(randint(1, 60))
sorteio(numero... |
#Hello!Welcome to File 1
#Function Coding Facilities.
def mymin(anyarray):
min = anyarray[0]
for value in anyarray:
if value < min:
min = value
return min
def mymax(anyarray):
max = anyarray[0]
for value in anyarray:
if value > max:
max = value
retu... |
# import libraries
import pandas as pd
import numpy as np
# Load the data
df = pd.read_csv('stocks.csv')
# Set the tickers as the index
df = df.set_index('Tickers')
# Print data
print(df)
# Calculate & show the mean P/E Ratio
PE_Ratio_Mean = df.PE_Ratio.mean()
# Calculate and show fair market value
df['Fair_Market_... |
from flask import Flask, request, jsonify
from flask_restful import Resource, Api, reqparse, abort
from topo.distributed.topobuilder import TopoBuilder
import json
import atexit
import threading
from utils.log_utils import debug, info, err
app = Flask(__name__)
api = Api(app)
builder: TopoBuilder = None
def start_n... |
"""
A dictionary is mutable and is another container type that can store any number of Python objects,
including other container types. Dictionaries consist of pairs (called items) of keys and their corresponding values.
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
"""
def main():
"""
Declares a di... |
import scipy.io as sio
from binascii import hexlify
from datetime import timedelta, datetime
from glob import glob
from logging import getLogger
from math import ceil
from os import environ, makedirs, SEEK_END
from os.path import basename, expanduser, join, exists, splitext
from platform import system
from re ... |
# -*- coding: utf-8 -*-
"""The FAT format analyzer helper implementation."""
from dfvfs.analyzer import analyzer
from dfvfs.analyzer import analyzer_helper
from dfvfs.analyzer import specification
from dfvfs.lib import definitions
class FATAnalyzerHelper(analyzer_helper.AnalyzerHelper):
"""FAT analyzer helper."""
... |
'''Write a program which accepts a string as input to print "Yes" if the string is
"yes" or "YES" or "Yes", otherwise print "No".'''
string = input("Digite a palavra: ")
if string == 'Yes' or string == 'YES' or string == 'yes':
print("Yes")
else:
print("No") |
# coding: utf8
# Python implementation of the Fibonacci Series
# Author: Eric Alcaide
def fibonacci(n):
prev, actual = 0, 1
if(n>0):
print("0")
for q in range(n):
actual, prev = actual+prev, actual
print(actual)
def main():
n = input("Enter the number of terms of fibonacci numb... |
from usuario_denuncia.models import UsuarioDenuncia
from rest_framework import viewsets, permissions
from .serializers import AllDenunciasSerializer
#Denuncia ViewSet
class AllDenunciasViewSet(viewsets.ModelViewSet):
permission_classes = [
permissions.AllowAny
]
serializer_class = AllDenunciasSeri... |
import sys
num = int(sys.stdin.readline().rstrip())
num_li = list(map(int, sys.stdin.readline().rstrip()))
# print(num)
# print(num_li)
multi = 1
result = 0
for i in range(len(num_li) - 1, -1, -1):
tmp = num * num_li[i]
print(tmp)
result += tmp * multi
multi *= 10
print(result)
|
from django.contrib.auth.models import User
from django.http import JsonResponse
import pytz
from UserActions.models import ActivityPeriod
def get_activity_periods_utc(request):
response = {"ok": True, "members": []}
is_utc = request.GET.get('utc', True)
is_utc = False if is_utc == 'False' else True
... |
# -*- coding:utf-8 -*-
import json
import re
import pymysql
import scrapy
from jobs.items import Company
from jobs.spiders.util import CompanyScale
class LagouCompanySpider(scrapy.Spider):
login = False
name = 'lagou_company'
allowed_domains = ['lagou.com']
def start_requests(self):
urls = ... |
# Exercise 4
# 1
Dictionary_Story_Time = {
'Start': 'Once upon a time there was a girl named Goldilocks.',
'Middle': 'She entered a family of bears\' house.',
'End': 'So they ate her... The End.'
}
# 2
print(Dictionary_Story_Time)
# 3
print(type(Dictionary_Story_Time))
# 4
print(Dictionary_Story_Time.keys... |
import re
import riffyn_nexus_sdk_v1 as api
import requests
from lib import riffyn, utils
from plugins import registry
from plugins.riffyn.config import PluginConfig
from src.triggers import trigger
cfg = PluginConfig()
class Watcher(registry.Watcher):
def __init__(self, logger, cache, queue, done):
su... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.