text stringlengths 8 6.05M |
|---|
N, B, C = map(int, input().split())
arr = list(map(int, input().split()))
curr_b = B
curr_c = C
answer = 0
for i in range(N):
if arr[i] == 0:
if curr_b == 0:
# Must wash clothes
curr_b = B
curr_c = C
answer += 1
curr_b -= 1
else:
if curr_c... |
# Generated by Django 2.2.12 on 2020-05-12 15:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('artical', '0004_auto_20200512_1504'),
]
operations = [
migrations.AlterField(
model_name='blog',
name='content',
... |
for rooster in range(0,20):
for hen in range(0,33):
chick = 100-rooster-hen
if chick/3 + rooster * 5 + hen *3==100:
print('公鸡有:%d只,母鸡有%d只,小鸡有%d只.' % (rooster,hen,chick))
|
from django.db import models
from catalog.models import Specification
from django.contrib.auth.models import User
from accounts.models import Address
from django.db import connection, transaction
def get_number():
cursor = connection.cursor()
cursor.execute("SELECT nextval('comm_order_number')")
return in... |
import cv2
import integral_images as ii
from patches import Patches
import numpy as np
class FragTracker:
DEFAULT_VIDEO_PATH = "videos/times_square2.mp4"
DEFAULT_SPLIT = (10, 10)
DEFAULT_RADIUS = 20
def __init__(self, video_path=DEFAULT_VIDEO_PATH, split=DEFAULT_SPLIT, radius=DEFAULT_RAD... |
import random
import pygame
if __name__ == '__main__':
# Create a pygame window
pygame.init()
width = 640
height = 480
screen = pygame.display.set_mode([width, height])
screen.fill([255, 255, 255])
#########################
# Actual drawing here...
#########################
fo... |
# -*- coding: utf-8 -*-
# list, Indentation
langs = [
'Python',
'Java',
'Swift'
]
for lang in langs:
print(lang)
# tuple
company_names = (
'Google',
'Apple',
'Amazon'
)
print('len(company_names) =', len(company_names)) # 3
print('company_names[0] =', company_names[0]) # Google
print('com... |
'''
A frog wants to cross a river that is 11 feet across.
There are 10 stones in a line leading across the river, separated by 1 foot,
and the frog is only ever able to jump one foot forward to the next stone,
or two feet forward to the stone after the next.
In how many different ways can he jump exactly 11 feet to... |
import flask
import pandas as pd
import numpy as np
# Initialize the app
app = flask.Flask(__name__)
# HTTP extension
@app.route("/")
def hello():
return "Flask app works!"
@app.route("/predict", methods=["POST"])
def predict():
df = pd.read_pickle("test.pkl")
input_data = flask.request.json
country = input_dat... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2019-08-13 11:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0025_auto_20190711_1357'),
]
operations = [
migrations.AddField(
... |
from __future__ import unicode_literals
import re, bcrypt
from django.db import models
from datetime import datetime, date
# email regex for use later on
# edit, not actually used in this project
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
class UserManager(models.Manager):
def v... |
#!/usr/bin/env python3
import matplotlib.pyplot as plt
from functions_script import noisy_sine
import numpy as np
def y(X, W):
WT = np.transpose(W)
return np.product(WT, X)
def main(*args, **kwargs):
X = noisy_sine(samples=10, precision=10)
# Normally MxN where M is the rows, N is the cols
N =... |
"""
This type stub file was generated by pyright.
"""
from typing import Callable, TypeVar
from marshmallow.schema import Schema
RT = TypeVar("RT")
"""ETag feature"""
class EtagMixin:
"""Extend Blueprint to add ETag handling"""
METHODS_CHECKING_NOT_MODIFIED = ...
METHODS_NEEDING_CHECK_ETAG = ...
... |
from collections import defaultdict
from typing import List, Tuple, DefaultDict
class SCCFinder():
"""
Kosaraju's two-pass algorithm to find strongly connected components;
probably not the most concise/efficient Python implementation of the
Kosaraju algorithm.
"""
def __init__(self, graph: Lis... |
import pandas as pd
url = "data_v3.csv"
insider = pd.read_csv(url, header=0)
print insider.shape
row_num = insider['side'].count()+1
train_num = int(row_num /3*2)
test_num = -1*int(row_num /3)
print "Training size: %d, Testing size: %d" % (train_num, test_num)
col_list = ['side', 'return_t5', "return_t3... |
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from err import ExceptionMiddleware
sys.path.insert(0, '/home/bao/public_html')
os.environ['DJANGO_SETTINGS_MODULE'] = 'bao.settings'
import django.core.handlers.wsgi
@ExceptionMiddleware
def application(environ, start_response):
t = django.core.... |
import numpy as np
import cv2
import pickle
DxyvUxy = []
cap = cv2.VideoCapture('slow_traffic_small.mp4')
# params for ShiTomasi corner detection
feature_params = dict( maxCorners = 100,
qualityLevel = 0.3,
minDistance = 7,
blockSize = 7 )
# Paramet... |
# -*- coding: utf-8 -*-
"""Amazon SQS message implementation."""
from __future__ import absolute_import, unicode_literals
from .ext import (
RawMessage, Message, MHMessage, EncodedMHMessage, JSONMessage,
)
__all__ = [
'BaseAsyncMessage', 'AsyncRawMessage', 'AsyncMessage',
'AsyncMHMessage', 'AsyncEncodedMH... |
#!/usr/bin/env python
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies *_wrapper in environment.
"""
import os
import sys
import TestGyp
test_format = ['ninja']
os.environ['CC_wrapper'] = 'distcc... |
from collections import defaultdict
from datetime import datetime, timedelta
import json
from django.core.exceptions import SuspiciousOperation
from django.http import HttpResponse
from django.utils.functional import cached_property
from django.views import View
from django.views.generic import TemplateView
from gim.... |
n = []
while True:
su = int(input())
if su == 0:
break
n.append(su)
big_one = max(n)
sosu = [0 for i in range(2*big_one+1)]
for i in range(2, 2*big_one+1):
if sosu[i] == 0:
sosu[i] = 1
else:
continue
for j in range(2, 2*big_one+1):
if i*j > 2*big_one:
... |
import pandas as pd
import numpy as np
all_data = pd.read_csv('datasets/New_all_data_Pollutors_legitimate.csv')
all_data.rename(columns={'No.1': 'UserID', 'char_count': 'TweetLen'}, inplace=True)
print(all_data)
legitimate_new = pd.read_csv('datasets/Legitimate_New.csv')
print(legitimate_new.head())
poll... |
import threading
import connection
import socket
class networkThread(threading.Thread):
def __init__(self, pyccConnection, inputQueue, notifyEvent):
threading.Thread.__init__(self)
self.pyccConnection = pyccConnection
self.inputQueue = inputQueue
self.notifyEvent = notifyEvent
def run(self):
''' main loo... |
#!/usr/bin/python3
def safe_print_list(my_list=[], x=0):
try:
if x == 0:
print()
return 0
else:
for i in range(x):
print("{}".format(my_list[i]), end='')
print()
return i + 1
except:
print()
return i
|
import pygame
import time
import random
'''Game initialization with pygame'''
pygame.init()
'''Screen Display size'''
display_width = 400
display_height = 400
display = pygame.display.set_mode((display_width,display_height))
''' Background color RGB'''
white=(255,255,255)
''' Snake Color RGB'''
black=(0,0,0)
'''Te... |
import discord
import random
from discord.ext import commands
class Guess(commands.Cog):
def __init__(self,client):
self.client = client
@commands.command()
async def guess(self, ctx):
pick = random.randint(1,10)
await ctx.send(f'Pick a number between 1 and 10. {ctx.author.mentio... |
from django.apps import AppConfig
class MoodleAdminConfig(AppConfig):
name = 'moodle_admin'
|
import test
if __name__ == '__main__':
a=open("num_tests.txt","r")
num = a.readline().strip("\n")
test.sss(num) |
# ====== main code ====================================== #
word = input() + ' запретил букву'
b = ['а', 'б', 'в', 'г', 'д', 'е', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я']
exclu = 0
while word.strip() != '':
if word == wor... |
import util
etfs = util.getFromHoldings()
ivv = set(util.getStocks("IVV"))
common = set()
test = set()
path = "etf_report"
with open(path, "w") as f:
for etf in etfs:
if etf == "IVV" or etf == "USRT" or etf == "VLUE":
continue
other = set(util.getStocks(etf))
f.write ("ivv - {}\n... |
from argparse import ArgumentParser
import penman as pp
import json, re
from penman import Graph
def main(args):
pattern = re.compile(r'''[\s()":/,\\'#]+''')
with open(args.input, encoding='utf-8') as f, open(args.output, mode='w', encoding='utf-8') as out:
for amr_data in f.readlines():
... |
# Agar stringda biz index larni chiqarmoqchi bulsak masalan berilgan o'zgaruvchidagi A xarfi nechinti tartib raqam ostida joylashgan
a="Khamzayev Jamshid is wonderfull Python programmer!!!"
print(a.find('J')) # bu yerda " find " methodidan foydalanamiz |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 30 13:44:14 2019
@author: se14
"""
import pandas as pd
import os
# script to merge results for all folds
print('Merging the results from all folds')
out_foldr = 'final_results/'
if (not os.path.exists(out_foldr)) & (out_foldr != ""):
os.maked... |
# DKats 2021
#
#---Thanks to---
# PySimpleGUI module from MikeTheWatchGuy at https://pypi.org/project/PySimpleGUI/
# executable's icon downloaded from www.freeiconspng.com
import PySimpleGUI as sg
import json
import sqlite3
import datetime
from datetime import timezone, datetime
import os
import webbrowser... |
#!/usr/bin/env python
# coding=utf-8
try:
#assert 1==0,"1 != 0"
print("pass")
except:
import time
time.sleep(1)
print("retry")
assert 1==0,"1 != 0"
print("succ") |
# -*- coding: utf-8 -*-
import json
import time
import logging
from uuid import uuid4
import base64
import datetime
from tornado import web
from tornado import gen
from webchat.handlers.base import BaseHandler, BaseSocketHandler
from webchat.modules.room import Rooms
from webchat.utils.pytea import str_encrypt, str_... |
# Generated by Django 2.2.13 on 2020-07-09 17:14
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('shop', '0025_auto_20200709_2238'),
]
operations = [
migrations.AddField(
model_name='about',
... |
from . import _internal # usort: skip
from ._dataset import Dataset
from ._encoded import EncodedData, EncodedImage
from ._resource import GDriveResource, HttpResource, KaggleDownloadResource, ManualDownloadResource, OnlineResource
|
from django.urls import include, path,re_path
from rest_framework import routers, urls
from django.conf.urls import url
from rest_framework_jwt.views import obtain_jwt_token
from .views import RegisterView
from . import views
urlpatterns = [
path("login/", obtain_jwt_token),
path("register/", RegisterView.as_... |
from flask import Blueprint
from flask import jsonify
from shutil import copyfile, move
from google.cloud import storage
from google.cloud import bigquery
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
from flask import request
import dataflow_pipeline.workforce.w... |
import pandas as pd
import seaborn as sns
import numpy as np
import re
import matplotlib.pyplot as plt
raw_data = pd.read_csv('menu.csv')
menu_data = raw_data[['Category', 'Serving Size', 'Calories']]
# Parse numerical data.
for index, row in menu_data.iterrows():
weight = (re.search('\\((\\d+) g\\)', row['Servin... |
# book = dict()
book = {}
book["apple"] = 0.67
book["milk"] = 1.69
book["avocado"] = 1.49
print(book)
print(book["apple"]) |
class ResID:
def __init__(self, setChainID, setSeqNum, setICode):
self.chainID = setChainID
self.seqNum = setSeqNum
self.iCode = setICode
def __lt__(self, other):
return ((self.chainID, self.seqNum, self.iCode) <
(other.chainID, other.seqNum, other.iCode))
de... |
# -*- coding: utf-8 -*-
import pytz
import datetime
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from django.utils import timezone
def get_timezone_aware(_date):
tzinfo=pytz.timezone("Asia/Kathmandu")
try:
... |
# Generated by Django 3.2.5 on 2021-07-24 09:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main_app', '0007_rename_searchedwords_searchedword'),
]
operations = [
migrations.AlterField(
model_name='movie',
na... |
from flask_marshmallow import Marshmallow
marsh = Marshmallow()
def init(app):
marsh.init_app(app) |
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.tools.taplo import rules as taplo_rules
def rules():
return [
*taplo_rules.rules(),
]
|
#!/usr/bin/env python
import time
import roslib; roslib.load_manifest('rtg_proje')
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
from cv_bridge import CvBridge
import rospy # Python library for ROS
from sensor_msgs.msg import Image # Image is the message type
from cv_bridge import CvB... |
"""
---TASK DETAILS---
--- Day 2: Bathroom Security ---
You arrive at Easter Bunny Headquarters under cover of darkness.
However, you left in such a rush that you forgot to use the bathroom!
Fancy office buildings like this one usually have keypad locks on their bathrooms, so you search the front desk for the code.
"... |
# coding: utf-8
# In[1]:
import cv2
import numpy as np
import imutils
# In[15]:
img = cv2.imread('./datasets/flower3.jpg')
logo_img = cv2.imread('./datasets/pyimagesearch_logo_github.png')
car_img = cv2.imread('./datasets/licence_plate1.jpg')
gray_car = cv2.cvtColor(car_img, cv2.COLOR_BGR2GRAY)
car_img_light = c... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 7 09:39:43 2019
@author: HP
"""
def swap(a,b):
temp=arr[a]
arr[a]=arr[b]
arr[b]=temp
def InsertionSort():
for i in range(1,len(arr)):
j=i
while(arr[j-1]>arr[j] and j-1>=0):
swap(j-1,j)
j=j-1
arr=[5,7,8... |
import os
from collections import defaultdict
from configparser import ConfigParser, _UNSET, NoSectionError, NoOptionError
from functools import partial
MY_DIR = os.path.dirname(__file__)
def absdir(path):
return os.path.abspath(os.path.join(MY_DIR, path))
# -------------------------------------------
# Subclass ... |
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView
from django.views.generic.list import ListView
from .models import ExamLibItem, ExamItem, Paper, ExamResult
from .forms import PaperForm, ExamItemForm, Te... |
import json
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext, ugettext_lazy as _
SOURCE_TELEGRAM = 'telegram'
SOURCE_SAHAMYAB = 'sahamyab'
SOURCE_CHOICES = (
(SOURCE_TELEGRAM, 'Telegram'),
(SOURCE_SAHAMYAB, 'Sahamyab')
)
SENTIMENT_NEUTRAL = 'neutral'
... |
import re
import sys
from typing import List
from datetime import datetime
from openpyxl import load_workbook
from openpyxl.workbook import Workbook
from openpyxl.worksheet.worksheet import Worksheet
from rich import print
from rich.prompt import Confirm
"""
This class is for exporting the all the important informati... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
from web_backend.nvlserver.module import nvl_meta
from sqlalchemy import BigInteger, String, Column, Boolean, ForeignKey, DateTime, Table
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.sql.functions import func
user = Table(
... |
# coding: utf-8
# ---
#
# _You are currently looking at **version 1.0** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-data-analysis/resources/0dhYG) course resource._
#
... |
import torch
from torch import nn
import torch.nn.functional as F
from utils import (
get_same_padding_conv2d,
Swish,
MemoryEfficientSwish,
round_filters,
round_repeats,
drop_connect,
efficientnet_params,
load_pretrained_weights,
get_model_params
)
class MBConvBlock(nn.Module):
... |
import tkinter as tk
from tkinter import ttk
def clickMe():
clickMe_Button.configure(text = 'Hello ' + name_Entry.get() +
' ' + number.get())
clickMe_Button.configure(state = 'disabled')
win = tk.Tk()
win.title('The gui excerise')
clickMe_Button = ttk.Button(win, text = 'Click me... |
import os
import pytest
from ai.backend.client.config import APIConfig, set_config
@pytest.fixture(autouse=True)
def defconfig():
endpoint = os.environ.get('BACKEND_TEST_ENDPOINT', 'http://127.0.0.1:8081')
access_key = os.environ.get('BACKEND_TEST_ADMIN_ACCESS_KEY',
'AKIAIOSF... |
class calisan():
def __init__(self, isim, soyisim,maas,departman, yas = 10):
print("çalışan sınıfının yapıcı metodu çalıştı")
self.isim = isim
self.soyisim = soyisim
self.yas = yas
self.maas = maas
self.departman = departman
def __str__(self):
return "{}... |
from django.contrib import admin
from .models import Blog, Tags
# Register your models here.
@admin.register(Blog)
class BlogAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'blog_type', 'creat_date', 'reads', 'likes')
list_filter = ['creat_date']
search_fields = ['name']
@admin.register(Tags)
cla... |
import pygame
from pygame.locals import *
import numpy as np
import sys
#
# X=600
# Y=600
# cell_size=15
# pygame.init()
# screen=pygame.display.set_mode((X,Y))
# pygame.display.set_caption("LIFE GAME")
# while(1):
# screen.fill((0,0,0))
# A=np.zeros((int(X/cell_size),int(Y/cell_size)))
# pygame.draw.rect(s... |
import json
import os
import sys
import warnings
import deepsecurity as api
from deepsecurity.rest import ApiException
from datetime import datetime
def format_for_csv(line_item):
"""Converts a list into a string of comma-separated values, ending with a newline character.
:param line_item: The list of lists t... |
from django.shortcuts import render
from django.contrib.auth.forms import AuthenticationForm
from mainapp.models import Category, Board
def index(request):
return render(request, 'mainapp/index.html')
def catalog(request):
categories = Category.objects.all()
context = {
'categories': categori... |
# coding: utf-8
# Use semantic versioning: MAJOR.MINOR.PATCH
__version__ = '0.5.1'
|
import time
from datetime import datetime
from utils.requests import generate_query_string, make_get_request
FACEIT_API_BASE_URL = 'https://open.faceit.com/data/v4/'
FACEIT_API_ENDPOINTS = {
'players': 'players',
'players_matches': 'players/:player_id:/history'
}
def get_player(parent, api_key... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
In memory key value store based on python dict with TCP interface and
basic language parsing.
"""
__author__ = "Niall O'Connor zechs dot marquie at gmail"
__version__ = "1.0"
import cPickle
from functools import wraps
from hashlib import sha1
import logging
import re... |
import os
from pathlib import Path
from ipaddress import IPv4Network
from urllib.request import urlretrieve
import pytest
from ips import (ServiceIPRange, parse_ipv4_service_ranges,
get_aws_service_range)
URL = "https://bites-data.s3.us-east-2.amazonaws.com/ip-ranges.json"
TMP = os.getenv... |
class man_player:
def __init__(self, name, id, comm_module, position=None, team=None, game=None, cards=None):
self.name = name
self.id = id
self.team = team
self.cards = cards
self.position = position
self.game = game
self.comm = comm_module
def set_game... |
class Solution(object):
def isPalindrome(self, s):
"""
https://leetcode.com/problems/valid-palindrome/
should have used alnum() function
"""
x = ''
for i in range(len(s)):
if (s[i] >= 'A' and s[i] <= 'Z') or (s[i] >= 'a' and s[i] <= 'z') or (s[i] >='0' and... |
#!/usr/bin/env python
from auth import get_cred, test_auth
if __name__ == '__main__':
import argh
argh.dispatch_commands([test_auth, get_cred])
|
class Car:
def __init__(self,model, regno, no_gears):
self.model = model
self.regno = regno
self.no_gears = no_gears
self.is_started = False
self.c_gear = 0
def start(self):
if self.is_started:
print(f"{self.model} with reg_no: {self.regno} is alread... |
#!/usr/bin/python
# Copyright 2014 Symantec.
#
# 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 agree... |
#multi dimensional list 2
import math
import random
listTable = [[0] * 10 for i in range(10)]
for i in range(10):
for j in range(10):
listTable[i][j] = "{} : {}" .format(i,j)
for i in range(10):
for j in range(10):
print(listTable[i][j], end = " || ")
print()
|
# -*- coding: utf-8 -*-
from decimal import Decimal
from django.db import models
from django.conf import settings
from django_extensions.db.fields import AutoSlugField
from model_utils import Choices
from abs_models import Abs_titulado_slugfy
from Corretor.utils import get_corretor_choices, get_corretor_por_id
from C... |
"""Defining the benchmarks for OoD generalization in time-series"""
import os
import copy
import h5py
from PIL import Image
import warnings
import scipy.io
import numpy as np
from scipy import fft
import matplotlib.pyplot as plt
import torch
from torch import nn, optim
from torch.utils.data import Dataset, DataLoade... |
#If you were going to draw a regular polygon with 18 sides, what angle would you need to turn the turtle at each corner?
#360/18=20 degrees turn |
"""Contains methods related to manipulation of xarray datasets in a test
environment.
"""
def make_on_variable(dataframe, variable):
"""Returns a new dataset created on the specified variable of the dataframe.
"""
return dataframe[variable]
def get_statistic_function(statistic):
"""Returns the appropr... |
# -*- coding: utf-8 -*-
age=input('age:')
if age.isdigit() == False:
print('wrong')
else:
age=int(age)
if age<4:
price=0
elif age<18:
price=5
elif age<65:
price=10
elif age>=65:
price=5
print("Your admission cost is $"+str(price)+".") |
# Functions
print("Start")
def kahihi(kka):
username = a.split(" ")
print(username)
username = "Satyen Deshpande"
#kahihi(username)
a = ("string", "number", "symbol")
b1 = ["string", "number", "symbol"]
b = [56, 32, 98712]
print(type(a))
print(type(b))
total = 0
for i in b:
total = b[i] + total
... |
import yaml
class NomenclatureEntry(yaml.YAMLObject):
def __init__(self, label, text):
self.label = label
self.text = text
def __repr__(self):
return ('Nom(%r, %r)' % (self.label, self.text))
class Symbol(yaml.YAMLObject):
yaml_tag = u'!Symbol'
def __init__(self, symbol, t... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
""" BaseHandler Class
All handlers must be inherit form this class
"""
__all__ = [
'BaseHandler'
]
class BaseHandler:
""" Base of all handler class
"""
@classmethod
def handler_name(cls) -> str:
""" Return handler name, ... |
import logging
import re
import time
from datetime import datetime
import pytest
from django.contrib.auth import get_user_model
from django.template.loader import render_to_string
from django.utils.http import int_to_base36, base36_to_int
from django_email_verification import send_email
from django_email_verification... |
import pyodbc
# conn_str = (
# "DRIVER={PostgreSQL Unicode};"
# "DATABASE=postgres;"
# "UID=postgres;"
# "PWD=whatever;"
# "SERVER=localhost;"
# "PORT=5432;"
# )
# conn = pyodbc.connect(conn_str)
conn = pyodbc.connect(dsn="my_driver")
crsr = conn.cursor()
# Open and read the file as a sing... |
import botocore
import sys
import unittest
import urllib3
from mock import Mock, patch
from collections import namedtuple
from patroni.scripts.aws import AWSConnection, main as _main
class MockVolumes(object):
@staticmethod
def filter(*args, **kwargs):
oid = namedtuple('Volume', 'id')
return... |
from django.db.models.loading import get_models
import os
import xmltodict
class ModelGenerator:
def __init__(self, file):
self.file = file
def run(self):
try:
doc = xmltodict.parse(self.file.read())
except:
return False
result, admin, form = self.parseXML(doc)
mfile = open('dynamic/models.py',... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Filename: step12_generate_country_level_regression_file
# @Date: 2020/4/16
# @Author: Mark Wang
# @Email: wangyouan@gamil.com
"""
python -m ConstructRegressionFile.Stata.step12_generate_country_level_regression_file
"""
import os
import pandas as pd
from pandas impor... |
import socket
import json
import requests
import self as self
"""
client_socket = socket.socket()
client_socket.connect(('127.0.0.1', 6457))#ip of the localhost
#nb = str(input('Choose a number: '))
client_socket.send(bytes("shir","utf-8"))
data = client_socket.recv(1024)
print("The server sen... |
from bst import BinarySearchTree
from vpython import *
bst = BinarySearchTree()
a=[1,2,4,5,6,7]
pos=vector(0,0,0)
leftstartteta=pi
rightstartteta=0
bst.createTree(a,pos,1)
bst.insertElement(3)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from head import *
def gene_django_frame(head, version, json_inst):
Body = json.dumps(json_inst)
Version = '{:{fill}{width}{base}}'.format(version, fill = '0', width = 2 * D_version_byte, base = 'x')
Length = '{:{fill}{width}{base}}'.format(len(Body), fill = '... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import re
import pytest
from pants.backend.python.macros.python_artifact import _normalize_entry_points
from pants.testutil.pytest_util import no_exception
@pytest.mark.parametrize(
... |
import pandas as pd
import os
import numpy as np
import statsmodels.formula.api as smf
###############################################################################
def get_data():
df = pd.read_stata("data/ReplicationDataset_ThePriceofForcedAttendance.dta")
df["grade"] = df["grade"].astype(float)
# tre... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @return the head node in the linked list
def reorderList(self, A):
if not A or not A.next or not A.next.next:... |
#!/usr/bin/env python
"""
v0.1 Given a source-id & XML fpath (to be created),
query RDBs and form, write XML.
NOTE: To be called by PHP script.
TODO: test this code (form VOSource.xml) for pairitel, tcptutor, sdss
"""
import sys, os
"""
sys.path.append(os.path.abspath(os.environ.get("TCP_DIR") + \
... |
import os
from datetime import datetime
import json
import webapp2
import jinja2
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.api import mail
class NewHandler(webapp2.RequestHandler):
def post(self):
title = self.request.get('title')
tag = self.request.... |
# app/models.py
from werkzeug.security import generate_password_hash, check_password_hash
from flask import current_app
from flask_login import UserMixin
from datetime import datetime
from app import db, login
import rq
import sys
"""
This module shall contain the tables of the database
"""
class User(UserMixin, d... |
import datetime
import json
import websockets
from typing import Dict, Callable, List
import logging
from websockets import WebSocketClientProtocol
from bitmex_futures_arbitrage.is_running import is_running
from bitmex_futures_arbitrage.models import Quote
logger = logging.getLogger()
class BitmexQuotesTracker:
... |
import os
import glob
from flask import request, Blueprint, current_app
from flask.json import jsonify
from ckanpackager import logic
actions = Blueprint('actions', __name__)
@actions.route('/clear_caches', methods=['POST'])
def clear_caches():
logic.authorize_request(request.form)
matching_files = os.path.j... |
"""
Defines the preset values in the mimic api.
"""
from __future__ import absolute_import, division, unicode_literals
get_presets = {"loadbalancers": {"lb_building": "On create load balancer, keeps the load balancer in "
"building state for given seconds",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.