text stringlengths 38 1.54M |
|---|
"""Entry-point for the Celery application."""
from .factory import create_worker_app, celery_app
app = create_worker_app()
# celery_app.conf.result_backend = 'file:///tmp/foo'
# celery_app.conf.broker_url = 'memory://localhost/'
app.app_context().push() |
import angr
import logging
import IPython
fail = 0x401180
find = 0x000000000001179 + 0x400000
main = 0x000000000001080 + 0x400000
p = angr.Project('./FUNFUN', load_options={'auto_load_libs': False})
init = p.factory.blank_state(addr=main)
for i in range(400):
tmp = init.posix.files[0].read_from(1)
... |
nums = []
def findLengthOfLCIS(nums):
if not nums:
return 0
d = {}
count = 0
n = 0
for n in range(0,len(nums)-1):
if nums[n] < nums[n+1]:
count += 1
else:
d[count+1]=nums[n-count:n+1]
count = 0
d[count+1]=nums[n+1-count:n+2]
return ... |
from .profitcalc_nocomments import assets, rent_savings
from .vars_module import translate, vars_range
import copy
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from io import BytesIO
from base64 import b64encode
'''
I will now build a function that receives a parameter na... |
from Abstract.AActionSubclasses.ActionLine import ActionLine
import os,json
from TrainerPredictor import CTrainerPredictor
class CProcessSolutions(ActionLine):
def __init__(self,chatbot):
"""
Constructor de la Clase.
:param chatbot: Es el ChatBot que tiene como acción la instancia de esta ... |
#!/usr/bin/python3
#
# read a bunch of source light fields and write out
# training data for our autoencoder in useful chunks
#
# pre-preparation is necessary as the training data
# will be fed to the trainer in random order, and keeping
# several light fields in memory is impractical.
#
# WARNING: store data ... |
import requests
import json
host = 'localhost'
auth = ('Samir', 'Ge0ne!RDS')
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
params = {'any': 'Mr. Jakob Steiner',
'type': 'dataset',
'_content_type': 'json',
'fast': 'index',
'from': 1,
'resultTy... |
#!/usr/bin/env python
import sys
from os import path
sys.path.append(path.dirname(sys.path[0]) + '\\logparser\\Slop')
import Slop
input_dir = '../logs/HDFS/' # The input directory of log file
output_dir = 'Slop_result/' # The output directory of parsing results
log_file = 'HDFS_2k.log' # The input log fil... |
import krpc
import time
conn = krpc.connect(
name='Connection Test',
address='192.168.86.60',
rpc_port=50000, stream_port=50001)
vessel = conn.space_center.active_vessel
vessel.control.activate_next_stage()
vessel.auto_pilot.engage()
vessel.auto_pilot.target_pitch_and_heading(90, 90)
while True:
flight_info = ve... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import re
import calendar
import statistics
import pandas as pd
import seaborn
import pathlib
import matplotlib.pyplot as plt
from xml.etree import ElementTree
from jinja2 import Environment, PackageLoader, select_autoescape
from activity import Activi... |
def setup():
size(480, 120)
stroke(0, 102)
def draw():
weight = dist(mouseX, mouseY, pmouseX, pmouseY)
strokeWeight(weight)
line(mouseX, mouseY, pmouseX, pmouseY)
saveFrame("frames/SaveExample-####.png")
|
from DB import *
def main():
VENOM = DB
host = input("Enter the target \r\n ")
VENOM.HTML(VENOM, host)
if __name__ == "__main__":
main()
|
from tornado import gen
import random
import string
from .lib.basescraper import BaseScraper
def random_string(min_size, max_size):
length = random.randint(min_size, max_size)
chars = string.ascii_letters
return "".join(random.choice(chars) for _ in range(length))
class SampleScraper(BaseScraper):
... |
#Die Funktionion sind in eigenen Packages gespeichert
#über die main.py wird die Flask-App geladen und weitergeleitet
from flaskblog import app
if __name__ == '__main__':
app.run(debug=True) |
core = cutter.core()
highlighter = core.getBBHighlighter()
highlighter.highlight(0x00404b66, 0xff0000) |
"""
Napisati kod koji za date katete a i b (a < b) pravouglog trougla racuna povrinu
i zapreminu tijela koje se dobija rotacijom trougla oko manje katete.
"""
import math
a = 5
b = 7
c = math.sqrt(a*a + b*b)
#print(c)
baza = b * b * math.pi
#print(baza)
tijelo = c * b * math.pi
#print(tijelo)
povrsina... |
from django.test import TestCase
from django import forms as django_forms
import forms
class FieldsetRenderTestCase(TestCase):
def _test_form(self):
class TestForm(django_forms.Form, forms.FieldsetMixin):
test_field1 = django_forms.CharField()
test_field2 = django_forms.CharField()... |
import argparse
import boto3
"""Helper module to assist in AWS deployments"""
def get_lambda_client(
aws_access_key_id: str, aws_secret_access_key: str, aws_region: str
) -> boto3.client:
return boto3.client(
"lambda",
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_se... |
from classes import Dungeon, Player, Creature
def auto_map(level, key, w, h):
x = 0
y = 0
for row in key:
for col in row:
if x + 1 < w:
if key[x][y] == 1:
if key[x+1][y] == 1:
level.layout[x][y].north = True
if x... |
#!/usr/bin/python
#from difflib import *
from sys import stdin
#from math import sqrt
def input():
list = []
#list = stdin.read().split()
for item in stdin:
if item == "\n":
continue
list.append(float(item))
number = list.pop(0)
return number, list
def gapInList(dataLi... |
from django.db import models
from accounts.models.auth_user import AuthUser
from managers.base_manager import BaseManager
class User(models.Model):
auth_user = models.OneToOneField(
AuthUser,
on_delete=models.CASCADE,
related_name="additional_data",
primary_key=True,
)
date_birth = models.DateField()
ad... |
import argparse
import pandas as pd
from textlib.whatsapp import helper
from textlib.whatsapp import general
import emoji as em
from textlib.whatsapp import testhelper
from sklearn.preprocessing import LabelEncoder
from sklearn.feature_extraction.text import TfidfVectorizer
from xgboost import XGBClassifier
from sklea... |
from marshmallow import Schema, fields, EXCLUDE, validate
class SuccessSchema(Schema):
result = fields.String()
class BadRequestSchema(Schema):
error = fields.Integer()
class FibNumber(Schema):
N = fields.Integer()
class FibNumbersList(Schema):
fibonacci_sequence = fields.List(fields.Integer())
... |
from collections import deque
existing_food = int(input())
line = map(int, input().split())
customers = deque(line)
print(max(customers))
is_complete = True
while len(customers) > 0:
order = customers[0]
if order <= existing_food and is_complete:
existing_food -= order
customers.po... |
#-*- coding: utf-8 -*-
from scraping import bdd
from flask import Flask, request, jsonify, redirect
from flask_restful import Resource, Api, output_json
from scraping.lib import get_data
class UnicodeApi(Api):
def __init__(self, *args, **kwargs):
super(UnicodeApi, self).__init__(*args, **kwargs)
s... |
import numpy as np
import matplotlib.pyplot as plt
import pymc3 as pm
from pymc3 import DiscreteUniform, Normal, Exponential, Poisson, traceplot, Uniform, StudentT
from pymc3.math import switch
import scipy.stats as scs
from pymc3.backends.base import merge_traces
from pymc3 import *
import matplotlib
data2early = sc... |
from room import Room
from player import Player
# Instantiate rooms
rooms = {
'outside': Room("Outside Cave Entrance",
"North of you, the cave mount beckons"),
'foyer': Room("Foyer", """Dim light filters in from the south. Dusty
passages run north and east."""),
'overlook': Room(... |
from typing import List
from .candidatePath import CandidatePath
class Policy(object):
name: str
color: int
paths: List[CandidatePath]
def __init__(self,
name: str,
color: int,
paths: List[CandidatePath]):
self.name = name
self.color... |
import os
import pexpect
os.system("sudo useradd alice")
child = pexpect.spawn("sudo passwd alice")
child.expect("Enter new UNIX password: ")
child.sendline("password")
child.expect("Retype new UNIX password: ")
child.sendline("password")
#os.system("sudo chown -R alice /home/alice")
#os.system("sudo chgrp -R alice /h... |
import numpy as np
import pyvista as pv
from pyvista import examples
from operator import itemgetter
#mesh = examples.download_teapot()
#mesh.plot(cpos=[-1, 2, -5], show_edges=True)
# Configuration
'''
N = 3
GRID_SIZE = N * N * N
'''
# Extract points, bounds
# Define some helpers - ignore these and use your own data... |
import cv2
import numpy as np
img = cv2.imread('home.jpg')
''' file name : pyramids.py
Description : This sample shows how to downsample and upsample images
This is Python version of this tutorial : http://opencv.itseez.com/doc/tutorials/imgproc/pyramids/pyramids.html#pyramids
Level : Beginner
Benefits : Learn to... |
import os
import csv
import argparse
import sys
import pandas as pd
from scipy.spatial.transform import Rotation as R
from scipy.spatial.transform import Slerp
import numpy as np
TIME_COLUMN = 'TimeStamp'
INTERPOLABLE_VEL_COLUMNS = ['vx', 'vy', 'vz', 'vyaw']
INTERPOLABLE_QUAT_COLUMNS = ['odom.quaternion.x', 'odom.quat... |
from PySide2.QtCore import *
from PySide2.QtWidgets import *
from src.app.components.canvas import Canvas
from src.app.components.gauge import Gauge
from src.app.utils.styles import *
from src.app.components.constants import *
class DashboardWindow(object):
def setupUi(self, main_window):
self.parameter... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 14 20:12:21 2020
@author: Soham Shah
"""
class Solution:
def arrangeCoins(self, n: int) -> int:
ans = 0
if n <= 1:
return n
for i in range(0,n+1):
ans = (i*(i+1))//2
if ans > n:
return i-1 |
from binarytree import Node as Treenode
class Solution(object):
def __init__(self):
self.path = []
def k_path_sum(self, root, k):
if root is None:
return
#print 'Visiting {}'.format(root.value)
self.path.append(root.value)
self.k_path_sum(root.left, k)
... |
# %%
#--------------------------------- Importing library ---------------------------------#
# OS, IO
from scipy.io import wavfile
import os, sys, shutil
# Sound Processing library
import librosa
from pydub import AudioSegment
# Midi Processing library
from mido import MidiFile, MidiTrack, Message, MetaMessage
from... |
#!/usr/bin/python3
import os
import sys
import getopt
import subprocess
import requests
import pathlib
def main(argv):
global ipaddress
info = """Arguments:\n -i, --ip ==> IP Address\n -p, --port ==> Port Number\n -t, --type ==> Payload Type\n --update ==> Update To The Latest Version\n --install ... |
__author__ = 'ibrahim (at) sikilabs (dot) com'
__licence__ = 'MIT'
from django.shortcuts import RequestContext
from django.template import loader
from django.http import HttpResponse
from django.conf import settings
import datetime
import os
from main.unique.models import UniqueUrl
# import unique url object
modlist... |
def forward(x, W1, W2, W3, training=False):
z1 = np.dot(x, W1)
y1 = np.tanh(z1)
z2 = np.dot(y1, W2)
y2 = np.tanh(z2)
# Dropout in layer 2
if training:
m2 = np.random.binomial(1, 0.5, size=z2.shape)
else:
m2 = 0.5
y2 *= m2
z3 = np.dot(y2, W3)
y3 = z3 # linear o... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.networks.base_network import BaseNetwork
from models.networks.normalization import get_norm_layer
from models.networks.architecture import ResnetBlock as ResnetBlock
from models.networks.architecture import FADEResnetBlock as FADEResnetBlock... |
from tabulate import tabulate
entry1 = "* 1.0.192.0/18 157.130.10.233 0 701 38040 9737 i"
entry2 = "* 1.1.1.0/24 157.130.10.233 0 701 1299 15169 i"
entry3 = "* 1.1.42.0/24 157.130.10.233 0 701 9505 17408 2.1465 i"
entry4 = "* 1.0.192.0/19 157.130.10.233 0 701 6762 6762 6762 6762 38040... |
import pandas as pd
import re
import numpy as np
import os
import sys
from collections import OrderedDict
# parent_path = os.path.realpath(os.pardir)
# if sys.platform.startswith('win') or sys.platform.startswith('cygwin'):
# seseds_path = os.path.join(parent_path, 'MCM-ICM-2018-Problem-C\\data\\csv\\seseds.csv'... |
result = 0
with open('input.txt') as fp:
line = fp.readline()
while line:
result += (int(line)//3) - 2
line = fp.readline()
print(str(result))
|
import os
import uuid
import filecmp
import BaseHTTPServer
import threading
import functools
from ftw_compatible_tool import base
from ftw_compatible_tool import context
from ftw_compatible_tool import broker
from ftw_compatible_tool import database
from ftw_compatible_tool import traffic
import common
def warning_a... |
def digits_product(product):
import operator
import functools
num = product
num_ls = []
digits = [9, 8, 7, 6, 5, 4, 3, 2]
cont = 1
if product < 10:
return 10 + product
counter = 0
while cont == 1:
breaker = 0
counter += 1
for i in digits:
... |
from sqlalchemy import create_engine, Table, Column, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///database.db')
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class Query(Bas... |
#
# Copyright (c) 2019-present, Prometheus Research, LLC
#
from setuptools import setup, find_packages
setup(
name="rex.notebook",
version="1.0.0",
description="Jupyter Notebook integration for Rex Applications",
long_description=open("README.rst", "r").read(),
maintainer="Prometheus Research, L... |
dic = {'orange':20, 'apple':100}
print(dic.get('orange'))
print(dic.get('orange', 70))
#print(dic.get('berry', 50))
print(dic.setdefault('berry', 50))
print(dic)
|
#######################################
# Created by Alessandro Bigiotti
# import API_KEY from my_scopus file
from my_scopus import MY_API_KEY
#####################################################################################################################################
# POSSIBLE LINK FOR QUERY SEARCH
#... |
import numpy
class WordExtractor:
def __init__(self, sample):
""" Computes noise threshold using given sample """
avg = numpy.average(numpy.absolute(sample))
self.noise_threshold = avg
def detect_words(self, rate, data, hint = 0):
noise_array = self.__detect_noise(rate, data)
... |
# import sys
# N, K = map(int, input().split())
# lst = [int(sys.stdin.readline()) for _ in range(N)]
# lst.sort()
#
# start = 1
# end = max(lst)
# answer = 0
# while (start<=end) :
# count = 0
# mid = (start+end)//2
# for i in range(N) :
# mid = int((mid/10)*10)
# count += (lst[i]//mid)
# ... |
gifts = input().split(' ')
while True:
command = input().split(' ')
if (' '.join(command)) == 'No Money':
break
else:
if command[0] == 'OutOfStock':
gifts[:] = [None if x == command[1] else x for x in gifts]
elif command[0] == 'Required':
if 0 <= int(command[... |
# Originally made by Katherine Crowson (https://github.com/crowsonkb, https://twitter.com/RiversHaveWings)
# The original BigGAN+CLIP method was by https://twitter.com/advadnoun
# Adapted from https://github.com/nerdyrodent/VQGAN-CLIP/blob/main/generate.py
import argparse
import os
import random
from urllib.request im... |
import sys, shutil
template_name = sys.argv[1]
shutil.copy('bootstrap_template.css', 'bootstrap_%s.css' % name)
f = open('bootstrap_%s.css' % name, 'r')
text = f.read()
f.close()
colors = '5B4634 82634A 9B7759 A88160 E8B285'.split()
NOT FINISHED...
# Use color scheme from http://kuler.adobe.com/
f = open('bootstrap_... |
#!/usr/bin/env python3
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# ... |
# -*- coding: utf-8 -*-
# @Author: LC
# @Date: 2016-03-10 17:38:42
# @Last modified by: LC
# @Last Modified time: 2016-04-10 16:24:30
# @Email: liangchaowu5@gmail.com
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rt... |
import os # os.uname, os.getpid
import time # time.time
import datetime # datetime.timedelta
from ..handlers import CommandHandler
from ..dataclasses import Message
from .. import __version__
from .._i18n import _
# Example of a more sophisticated command
class InfoCommand(CommandHandler):
"""
Bot informatio... |
from Resources.resource_classes import ResourceClass
from Resources.resource_depart import ResourceDepart
from Resources.resource_students import ResourceStudent
class ResourceIn():
# 学院统一入口类
def get_depart(self):
return ResourceDepart()
# 班级统一入口类
def get_class(self):
return ResourceClas... |
from __future__ import annotations
import os
from typing import Literal
from prettyqt import core
from prettyqt.utils import bidict, datatypes
MatchModeStr = Literal["default", "extension", "content"]
MATCH_MODE: bidict[MatchModeStr, core.QMimeDatabase.MatchMode] = bidict(
default=core.QMimeDatabase.MatchMode... |
"""
Copyright 2016 Rackspace
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, software
dist... |
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.test import Client
from django.test import TestCase
from ckeditor_link.tests.test_app.models import TestModel, LinkModel
class ckeditor_linkDialogTests(TestCase):
fixtures = ['test_app.json', ]
def setUp(self):
self.tes... |
from django.db import models
from netutils.modelfields import NetIPAddressField, NetIPNetworkField
class Bras(models.Model):
name = models.CharField(max_length=200, db_index=True, unique=True)
management_ip = NetIPAddressField(blank=True, null=True)
class Meta:
verbose_name_plural = 'bras'
... |
# Créé par Nicolas, le 07/12/2015 en Python 3.2
#Le chiffrement atbash consite à inverser l'alphabet; a devient ainsi z, b devient y et ainsi de suite.
def atbash(lettre):
if lettre == "a" or lettre == "à":
return "z"
if lettre == "b":
return "y"
if lettre == "c" or lettre == "ç":
... |
def max_subarray(array):
n = len(array)
low = 0
high = 0
max_sum = array[0]
for i in range(n):
curr_sum = array[i]
if curr_sum >= max_sum:
max_sum = curr_sum
low = i
high = i
for j in range(i + 1, n):
curr_sum += array[j]
... |
import click
import os
from passlib.context import CryptContext
from wrappers.jirawrapper import MyJiraWrapper
from plugins.jira_workflow import (
start_issue_workflow,
start_create_pull_requests_workflow,
start_review_pull_requests_workflow
)
from utils.utils import (
echo_success,
echo_error,
... |
# Generated by Django 3.0 on 2019-12-11 23:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('landing', '0002_aluno_usuario'),
]
operations = [
migrations.RenameField(
model_name='aluno',
old_name='usuario',
... |
#Кругляши
num = input()
arr = []
count=0
for i in num:
a = int(i)
if a == 0 or a == 6 or a == 9:
count+=1
elif a == 8:
count+=2
print(count) |
#from django.urls import path, re_path
from django.conf.urls import url
from django.urls import path
from . import views
app_name = 'cal'
urlpatterns = [
url(r'^index/$', views.index, name='index'),
url(r'^calendar/$', views.CalendarView.as_view(), name='calendar'),
url(r'^event/new/$', views.event, nam... |
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from flask_jwt_extended import JWTManager, verify_jwt_in_request, get_jwt_claims
from datetime import timedelta
fr... |
import logging
import warnings
warnings.filterwarnings("ignore")
logger = logging.getLogger(__name__)
supported_trials = [
"categorical",
"discrete_uniform",
"float",
"int",
"loguniform",
"uniform",
]
def trial_suggest_loader(trial, config):
_type = config["type"]
assert (
... |
# -*- coding: utf-8 -*-
# 是/否
import json
from django.http import HttpResponse
TRUE = '1'
FALSE = '0'
TRUE_INT = 1
FALSE_INT = 0
CHANNEL_SORT_DEFAULT = '100'
# 图片/文件/附件 存储位置
PROPAGANDA_PIC = 'propaganda/' # 轮播宣传图
CATELORY_TITLE_PIC = 'catelory/title' # 栏目的题图图片存放位置
CATELORY_TYPE_INTRO_PIC ... |
from django.urls import path, include
from django.contrib.auth import views as auth_views
from .views import SignUpView
urlpatterns = [
path('signup/', SignUpView.as_view(), name='signup'),
path('password_reset/', auth_views.PasswordResetView.as_view(), name ='password_reset'),
]
# pathpatterns = [
# ... |
from decimal import Decimal
from pydantic import PositiveInt
class Mutation(str):
"""
Validate a mutation field.
A mutation field starts with + or - and is followed by a decimal
"""
def _get_sign(self):
"""
Parses the first character into an allowed sign
"""
if ... |
def bubble_sort(nums):
"""
Sorts a list of integers using bubble sort algorithm
:param nums:
:return: list
"""
n = len(nums)
if not nums:
return []
for i in range(n):
for j in range(i, n):
if nums[i] > nums[j]:
nums[i] = nums[i] + nums[j]
nums[j] = nums[i] - nums[j]
... |
#!/usr/bin/python3 -d
"""
This file is part of Linspector (https://linspector.org/)
Copyright (c) 2013-2023 Johannes Findeisen <you@hanez.org>. All Rights Reserved.
See LICENSE.
"""
# TODO: Make this a curses style TUI interface for Linspector using urwid or maybe some more modern
# framework like textual. Look at th... |
import hoi4
import os
import re
import collections
import pyradox
from PIL import Image
def compute_country_tag(filename):
m = re.match('.*([A-Z]{3})\s*-.*\.txt$', filename)
return m.group(1)
def compute_color(values):
if isinstance(values[0], int):
# rgb
r = values[0]
g = value... |
from django.db import connection
from django.db import models
class Lock(models.Model):
key = models.CharField(primary_key=True, max_length=25, unique=True)
def __enter__(self):
self.cursor = connection.cursor()
self.cursor.execute("SELECT count(*) FRO... |
from google.appengine.ext import db
class FlashImage(db.Model):
url = '/fupload/'
uploaded_data = db.BlobProperty()
date = db.DateTimeProperty(auto_now_add=True)
comment = db.TextProperty()
title = db.StringProperty()
filename = db.StringProperty(default = "uploaded_image.png")
def __u... |
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if (s is None) != (t is None):
return False
if len(s) != len(t):
return False
hash_map = {i:0 for i in t}
... |
def binarySearch(left,right,arr,searchKey,ans):
if left <= right:
mid = (left + right) // 2
if arr[mid] > searchKey:
# we save this and move to left to minimize it
ans[0] = arr[mid]
return binarySearch(left,mid-1,arr,searchKey,ans)
else:
# if char at mid is smaller than target we move ... |
import cv2
import numpy as np
cam = cv2.VideoCapture(0)
while True:
ret, im =cam.read()
cv2.imshow('im',im)
if cv2.waitKey(10)==ord('q'):
break
cam.release()
cv2.destroyAllWindows() |
import numpy as np
import cv2 as cv
def text_detection_MSER(img):
## Read image and change the color space
im_shape = img.shape
if len(im_shape) == 2:
img = cv.cvtColor(img, cv.COLOR_GRAY2RGB)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
## Get mser, and set parameters
mser = cv.MSER_cre... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os.path, json
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
from bs4 import BeautifulSoup
from estnltk import Text
from py2neo import Graph
from py2neo.ogm import GraphObject, Property, RelatedTo, RelatedFrom
from hashlib impor... |
"""
saving to and reading from pickle files
"""
from __future__ import annotations
from typing import Union, Dict, IO
try: # drop:py37 (backport)
from importlib.metadata import version
except ModuleNotFoundError:
from importlib_metadata import version
import pickle
def write_dict_pkl(fhandle: Union[str, IO],... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home_page, name='clubs_home_page'),
url(r'^(?P<slug>[-\w\d]+)/$', views.club_page, name='club_page'),
]
|
# package com.gwittit.client.example
import java
from java import *
from java.util.List import List
from pyjamas.ui import GWT
from com.google.gwt.event.dom.client.ClickEvent import ClickEvent
from com.google.gwt.event.dom.client.ClickHandler import ClickHandler
from pyjamas.rpc import AsyncCallback
from pyjamas.ui im... |
import F00,F01
def topup():
Jumlah = F00.banyakParam(F01.dataUser)
kolomUsername = 3
kolomSaldo = 6
tmpDataTopUp = F00.sliceArray(F01.dataUser,2,Jumlah)
username = input("Masukkan username: ")
topup = input("Masukkan saldo yang di-top up: ")
for idxDataUser in range(0,Jumlah-1):
... |
#!/usr/bin/env python3
import sys
import os
sys.path.append(os.getcwd())
# run.py - file to actually run
from GeometricModel import GeometricModel
from StraightWireModel import StraightWireModel
from PinkNoiseModel import PinkNoiseModel
from Electrode import Electrode
from helpers import *
import networkx as nx
from r... |
import pymysql
conn = pymysql.connect(host='localhost',user='root',password='root',db='bank')
a = conn.cursor()
sql = " SELECT * from 'customer'"
a.execute(sql)
countrow = a.execute(sql)
print ("number of row",countrow)
data = a.fetchone()
print(data)
|
""" testapp2 app configs """
from django.apps import AppConfig
class Testapp2Config(AppConfig):
name = 'testapp2'
|
import cv2
import numpy as np
import os
from argparse import ArgumentParser
from os.path import join
def get_canny_bounds(frame,
color=[36,255,12]):
"""
Возвращает изображение с границами Кённи
:param frame: путь к изображению
:param color: цвет границ
:return: ... |
def two_oldest_ages(ages):
arr1 = sorted(ages)[len(ages)-1]
arr2 = sorted(ages)[len(ages)-2]
return [arr2, arr1]
def two_oldest_ages_up(ages):
return sorted(ages)[-2:]
def two_oldest_ages_up2(ages):
ages.sort()
s = [ages[-2], ages[-1]]
return s
print(two_oldest_ages([1, 5, 87, 45, 8, ... |
class Node:
def __init__(self,data):
self.data = data
self.next= None
class LinkedList:
def __init__(self):
self.head = None
def push(self,new_data):
t = Node(new_data)
t.data = new_data
t.next = self.head
self.head = t
def printList(self):
temp = self.head
while temp:
print(temp.data,end=" ... |
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from phonenumber_field.modelfields import PhoneNumberField
from project_admin.models import development_methodology, Development_Tool
class ProjectDetail(models.Model):
profile_name = models.For... |
from django.shortcuts import render, HttpResponse, redirect
from django.views.generic import TemplateView, FormView, CreateView
from django.core.exceptions import ValidationError
from firstapp.forms import ContactUsForm, RegistrationFormSeller, RegistrationForm, RegistrationFormSeller2
from django.urls import reverse_l... |
# -*- coding: utf-8 -*-
#姓名
jjcc_clientName_xpath = 'xpath=//*[@id="clientName"]'
#身份证号
jjcc_idCard_xpath = 'xpath=//*[@id="idCard"]'
#查询
jjcc_cx_xpath = 'xpath=//*[@id="dynamic-table_wrapper"]/div/div[2]/label/button'
#确定
jjcc_qd_xpath = 'xpath=/html/body/div[8]/div/div/div[2]/button'
|
#!/usr/bin/env python
# publie la video filmee par la camera
import rospy
from sensor_msgs.msg import Image
import cv2
from cv_bridge import CvBridge, CvBridgeError
import numpy as np
def update_image(msg):
global frame, bridge, flag
frame = bridge.imgmsg_to_cv2(msg, "mono8")
if not flag:
flag... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from pdb import set_trace
class UserType(models.Model):
STUDENT = 1
RECOMMENDER = 2
COUNSELOR = 3
REVIEWER = 4
ADMIN = 5
ROLE_CHOICES = (
(STUD... |
import settings
import time
import tools
import random
from tkinter import *
from cells import Cell, Accident
root = Tk()
root.title('Evolution')
root.geometry('1265x720')
canvas = Canvas(root, width=1280, height=720, background='yellow')
canvas.pack()
grid = [[0]*settings.COL for g in range(settings.ROW)]
x1 = 0
y... |
j=int(input("enter a special character :"))
for i in range(0,6):
for k in range(i+1):
print(j, end=' ')
print()
# r=int(input("enter a row: "))
# a=input("enter a special character: ")
# no_of_spaces=2*r-2
# for i in range(0,r):
# for M in range(0,no_of_spaces):
# print(end=" ")
# no... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.