text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from .oauth2 import Oauth2
class Qq(Oauth2):
NAME = 'QQ'
AUTHORIZATION_URL = 'https://graph.qq.com/oauth2.0/authorize'
ACCESS_TOKEN_URL = 'https://graph.qq.com/oauth2.0/token'
GET_USERINFO_URL = 'https://graph.qq.com/oauth2.0/me'
def __i... |
"""
ghub - Package of the modules.
"""
|
#if 'LocalInputFileList' in locals():
# print "LocalInputFileList is already set"
#else:
# LocalInputFileList="Z.list"
##LocalInputFileList="local_valid_r9026.list"
##LocalInputFileList="r9311.list"
##LocalInputFileList="r9539_Zmumu.list"
##LocalInputFileList="r9573.list";
##LocalInputFileList="testData17.list";
... |
import sys
from numpy import *
from matplotlib import pyplot as plt
# string variable pointing to filesystem location of csv
fn="../data/data_provinces.csv"
# loading file with 3 columns
name=loadtxt(fn, unpack=True, delimiter=',', skiprows=1, dtype='a',
usecols=arange(1)) # array defined for the first column
region... |
from django.shortcuts import render,redirect
from django.contrib.auth import login
from django.views.generic import TemplateView,ListView, CreateView, UpdateView
from django.http import HttpResponse
from ..models import User,IndividualProfile,InstitutionProfile,City,State,EventModel,EventImage,Category,ApplyEventModel,... |
import os
import sys
sys.path.append(os.getenv('cf'))
import cartoforum_api
from cartoforum_api import config |
#
#3D Ising model on simple cubic lattice
#
#
import pyalps
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pyalps.plot
#%matplotlib inline
import numpy as np
from scipy import optimize
from scipy import interpolate
import pyalps.fit_wrapper as fw
numeratorfigs=1
#prepare the input pa... |
# Generated by Django 3.0 on 2019-12-30 04:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0004_remove_custm_user_sxj'),
]
operations = [
migrations.RemoveField(
model_name='custm_user',
name='createT... |
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy import API
from tweepy import Cursor
import twitter_credentials
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt, mpld3
import datetime as dt
import re
from textblob import TextBl... |
import random
names = input("enter the names separated by a comma ")
names = names.split(", ")
random_int = random.randint(0, len(names)-1)
print(f"{names[random_int]} should be paying the bill") |
from . import db,login_manager
from werkzeug.security import generate_password_hash,check_password_hash
from flask_login import UserMixin
from datetime import datetime
import os
|
import pyperclip
import pyautogui
scriptPath = r'C:\Users\Ramstein\PycharmProjects\Keras\Recognizing Handwritten Digits.py'
with open(scriptPath) as f:
lines = f.readlines()
for line in lines:
pyperclip.copy(line)
fromClipboard = pyautogui.hotkey('ctrl', 'v')
print(fromClip... |
# -*- coding:utf-8 -*-
class Solution:
# s, pattern都是字符串
def match(self, s, pattern):
# write code here
if not s and not pattern:
return True
if not pattern:
return False
if not s: # s不存在 a*, b**都可以消去
for i in range(len(pattern) - 1):
... |
import tkinter as tk
print("Start Program")
root = tk.Tk() #This builds your window
root.mainloop()
print("END PROGRAM") |
from node import *
class Searcher(object):
"""Searcher that manuplate searching process."""
def __init__(self, start, goal):
self.start = start
self.goal = goal
def print_path(self, state):
path = []
while state:
path.append(state)
state = state.prev... |
#-*- coding: utf-8 -*-
import zipfile
from xmind.tests import logging_configuration as lc
from xmind.tests import base
from xmlscomparator.xml_diff import create_xml_diff_from_strings
from xmlscomparator.comparators.type_comparator import TypeComparator
from xmlscomparator.comparators.text_comparator import TextCompara... |
import logging
import os
import threading
import time
from typing import *
import matplotlib.pyplot as plt
import schedule
from dotmap import DotMap
import charts
import log
import processor
from access import accessControl
from db import db, Const
from lib import app
accessdenied = 'accessdenied'
_macd_data = DotM... |
from pytriqs.gf.local import *
from pytriqs.archive import *
import numpy as np
import matplotlib.pyplot as plt
class TightBinding:
"""
With this class one can contruct and study a single or multi-band Hubbard model
either on a square or a cubic lattice.
"""
def __init__(self,lattice,numk,archive=N... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:
retur... |
import numpy as np
import matplotlib.pyplot as plt
#from scipy.optimize import fsolve
from scipy.optimize import newton
def euler(f,y0,a,h):
""" Calculates the Euler solution of the IVP
y'=f(t,y), with y(a)=y0, a[0]<=t<=a[1]. Using the
explicit Euler formula. If h<=1, then h is the step size
else h... |
from onegov.election_day import _
from onegov.election_day.formats.common import FileImportError
def unsupported_year_error(year):
return FileImportError(
_(
"The year ${year} is not yet supported", mapping={'year': year}
)
)
def set_locale(request):
""" Sets the locale of th... |
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import numpy
##usamos la semilla 35 para hacer nuestro proyecto producible
numpy.random.seed(35)
#Grafico de codo
def elbowPlot(data,maxKClusters):
inertias=list()
for i in range(1,maxKClusters+1):
myCluster=KMeans(... |
###### ITC 106 - Jarryd Keir - Student Number 11516086
import os.path
import traceback
import sys
#### Variable Section - ensure that variables are clear before starting ####
inputMarkAss1 = -1
inputMarkAss2 = -1
inputMarkExam = -1
outputMarkAss1 = 0
outputMarkAss2 = 0
outputMarkExam = 0
AssWeight1 = 20
AssWeight2 =... |
# Generated by Django 2.2.1 on 2019-06-27 09:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('faculty', '0012_auto_20190623_1030'),
]
operations = [
migrations.AddField(
model_name='loadshi... |
numbers = [10,100,30,-1,8,-13]
max_num,min_num,max_index,min_index = 0,0,0,0
for i in range(len(numbers)):
num = numbers[i]
if num > max_num:
max_num = num
max_index = i
if num < min_num:
min_num = num
min_index = i
numbers[max_index], numbers[min_index] = min_num, max_nu... |
""" Provides commands used to initialize gazette websites. """
import click
import transaction
from dateutil import parser
from onegov.core.cli import command_group
from onegov.core.cli import pass_group_context
from onegov.core.crypto import random_password
from onegov.core.csv import convert_excel_to_csv
from onego... |
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright 2015-2016 Nervana Systems Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'zhj'
import re
s1 = '<div class="address"><div class="houseInfo"><span class="houseIcon"></span><a href="https://wh.lianjia.com/xiaoqu/3711062825014/" target="_blank" data-log_index="1" data-el="region">保利城 </a> | 4室2厅 | 174平米 | 南 北 | 毛坯</div></div>'
s = """<... |
from dqn_agent import DQNAgent
from tetris import Tetris
from datetime import datetime
from statistics import mean, median
import random
from logs import CustomTensorBoard
from tqdm import tqdm
# Run dqn with Tetris
def dqn():
env = Tetris()
episodes = 2000
max_steps = None
epsil... |
def dfsCall(graph, start):
stack = [start]
seen = set()
seen.add(start)
while len(stack) > 0:
vertex = stack.pop()
nodes = graph[vertex]
for w in nodes:
if w not in seen:
stack.append(w)
seen.add(w)
print(vertex)
|
from onegov.core.orm.abstract import AdjacencyList
from onegov.core.orm.mixins import ContentMixin
from onegov.core.orm.mixins import TimestampMixin
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import or_
from sqlalchemy_utils import observes
from sqlalchemy.orm import object_session
c... |
#!/usr/bin/python2.7
from __future__ import unicode_literals
import os, errno
import sys
import time
import httplib2
import urllib2
from subprocess import Popen, PIPE, check_output
import webbrowser
# USE THIS: sudo pip install oauth2client==3.0.0
# Give full permissions to both .json credetial files
# DO NOT USE (th... |
# Generated by Django 3.1.7 on 2021-03-13 23:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('finalCristianGarcia', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='reserva',
name='fecha_de_... |
"""
dataset create
Author: Zhengwei Li
Date : 2018/12/24
"""
import cv2
import os
import random as r
import numpy as np
from PIL import Image, ImageEnhance
import torch
import torch.utils.data as data
def read_files(data_dir, file_name={}):
image_name = os.path.join(data_dir, 'image', file_name['image'])
... |
from dataclasses import dataclass
from typing import List, Optional
from apiclient import APIClient, endpoint, paginated, retry_request
from jsonmarshal import json_field
from apiclient_jsonmarshal import unmarshal_response
def by_query_params_callable(response, prev_params):
if "nextPage" in response and respo... |
# Runtime: 36 ms, faster than 82.24% of Python3 online submissions for Number of Lines To Write String.
# Memory Usage: 13.8 MB, less than 6.25% of Python3 online submissions for Number of Lines To Write String.
class Solution:
def numberOfLines(self, widths: List[int], S: str) -> List[int]:
chars = "abcde... |
import os
PARENT_PATH = os.getenv('PYMCTS_ROOT')
import tester
T = tester.Tester()
T.test(T.UCT, T.HEURISTIC, 0, 3, 20, "out/normal_vs_heuristic")
T.test(T.HEURISTIC, T.UCT, 0, 3, 20, "out/normal_vs_heuristic")
|
"""
Unit testing for freedson_adult_1998
@authors Dominic Létourneau
@date 24/04/2018
"""
import unittest
import libopenimu.algorithms.freedson_adult_1998 as freedson1998
class Freedson1998Test(unittest.TestCase):
def setUp(self):
pass
def thread_finished_callback(self):
pass... |
import rospy
from pid import PID
import math
from yaw_controller import YawController
#GAS_DENSITY = 2.858
#ONE_MPH = 0.44704
MAX_V_MPS = 44.7 # Maximum speed in meters_per_second
BRAKE_TORQUE_SCALE = 100000
YAW_SCALE = 8.2
class Controller(object):
def __init__(self, **kwargs):
# TODO: Implement
m... |
# -*- coding: utf-8 -*-
import os
from flask import g
from flask import current_app
from werkzeug.utils import secure_filename
from app.api import api
from ..parsers.uploadparser import upload_parser
from sql import db
from sql.importdata import ImportData
from app.utils.response_utils import response_error
from ... |
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0: return False
y=int(x)
i=0
while y>0:
i = i*10 + y%10
y //= 10
return i==x
print(Solution().isPalindrome(-5555)) |
from django import forms
class ProductForm(forms.Form):
name = forms.CharField(max_length=45)
desc = forms.CharField(widget=forms.Textarea(attrs={'rows': 4}),
label="Description")
category = forms.CharField(max_length=45)
price = forms.DecimalField(max_digits=9, decimal_plac... |
#/usr/bin/env python
import numpy
import math
import matplotlib.pyplot as pyplot
n = 1024
deltat = 1.0
t = numpy.arange(n) * deltat
whitenoise = numpy.random.normal(0.0, 1.0, n/2+1) + 1j*numpy.random.normal(0.0, 1.0, n/2+1)
whitenoise[0] = 0
freq = numpy.arange(n/2 + 1) / deltat / n
tau = 5.0
rcfilter = 1.0 / (1.0 ... |
import SocketServer
import time
from kafkaClass import Kafka_producer
class Server(SocketServer.BaseRequestHandler):
def handle(self):
conn=self.request
print(conn)
kafkaproducer=Kafka_producer('master:9092,slave1:9092,slave2:9092','HelloKafka')
error_flag=0
data_r=''
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os
import sys
base_dir = os.path.dirname(__file__)
src_dir = os.path.join(base_dir, "src")
sys.path.insert(0, src_dir)
about = {}
with open(os.path.join(src_dir, "sktutor", "__about__.py")) as f:
exec(f.read(), abou... |
# encoding: utf-8
import copy
class GreedyPlayer(object):
def __init__(self, name, color, board, rulebook):
self.name = name
self.color = color
self.board = board
self.rulebook = rulebook
def totalPieces(self, board, color):
total_my_color = 0
total_opponent_color = 0
for row in board:
for column... |
def returnTwo():
return 20,30
x,y = returnTwo()
print x,y
def mul(x,y):
return x*y
# Factorial
print reduce(mul, range(1,11))
def cubeFunc(x):
'''
:param x:
:return:the cube of the value passed in
'''
return x * x * x
print map(cubeFunc, range(1,11))
def myAdd(var1, var2 = 10):
return... |
# ==================================================================================================
# Copyright 2011 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
from lib.saga_service.job_submission_service import JobSubmissionService
import unittest
from mockito import Mock, verify, when, any
from mock import Mock as mock_Mock, patch, mock_open
class JobSubmissionServiceTest(unittest.TestCase):
def setUp(self):
self.current_time = 1123455.123
self.connect... |
'''
https://yandex.ru/tutor/subject/tag/problems/?ege_number_id=365&tag_id=19
'''
n = int(input())
m = 120
a = []
b = 0
c = 0
for i in range(n):
a.append(int(input()))
for i in range(n - 1):
for k in range(i + 1, n):
if (a[i] + a[k]) % m == 0 and (a[i] + a[k]) > b + c and a[i] > a[k]:
c = a[... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
class Operators:
def num(self,n1,n2):
self.n1=n1
self.n2=n2
print(self.n1+self.n2)
def num(self,n3):
self.n3=n3
print(self.n3)
np=Operators()
np.num(6,4)
#method overloading not happen in python
#latest method runs in python
#same mthod name different number of parameters |
from LCA import * # The code to test
import unittest # The test framework
class TestLCA(unittest.TestCase):
tree = BST()
tree.insert_node(2)
tree.insert_node(3)
tree.insert_node(1)
def test_search(self):
self.assertEqual(self.tree.search(3).data,3)
def test_root(self):
self.as... |
import tornado.web
from content import PAGES
def page_controller(handler_instance, path):
if path in PAGES:
handler_instance.write(PAGES[path].serialize())
else:
handler_instance.set_status(404)
handler_instance.write({
'message': 'A resource was not found for this path.'
})
|
from collections import deque
if __name__ == "__main__":
T = int(input())
for _ in range(T):
n = int(input())
cards = deque()
card = n
while card > 0:
cards.appendleft(card)
cards.rotate(card)
card -= 1
print(" ".join(map(str, card... |
from __future__ import print_function
__author__ = 'Roberto Estrada (a.k.a) paridin'
import urllib2
import sys, os
from subprocess import PIPE, Popen
class Pylocate:
"""
if you don't specify the port by default is 80
this function get the public ip for you server
@port: receive the specific port t... |
import requests
import os
import hashlib
import subprocess
import json
import pathlib
import urllib
import shutil
import time
import functools
from server_automation import utilities
from server_automation import logger
from server_automation import control
VERSION_MANIFEST_URL = "https://launchermeta.mojang.com/mc/g... |
from django.test.client import Client
from django.http import HttpRequest
from django.test import TestCase
from django.core.urlresolvers import resolve, reverse
from locations.views import home, datacenter_create
class TestExamples(TestCase):
def test_bad_maths(self):
self.assertEqual(1+2, 3)
class Test... |
def main(clientesOrdenadosHorarioTermino):
horariovisita = -1000
numVisita = 0
confirmados = {}
# print(clientesOrdenadosHorarioTermino)
for cliente in clientesOrdenadosHorarioTermino:
if(horariovisita <= int(cliente[1]['hInicioInt'])):
horariovisita = cliente[1]['hTerminoInt']
... |
from django.urls import path, include
from hod import views
urlpatterns = [
path('', views.index, name="hod_index"),
path('reservations',views.room_reservations,name="hod_room_reservations"),
path('reservations/api',views.events,name="hod_events_api"),
path('leaves',views.leave_history,name="leave_history"),
p... |
# Define a function overlapping() that takes two lists and returns True if they have at least one member in
# common, False otherwise. You may use your is_member() function, or the in operator, but for the sake
# of the exercise, you should (also) write it using two nested for loops
def overlapping():
list1 = [1, ... |
__author__ = 'mgarza'
# coding=UTF-8
import curses, logging, sys, subprocess, threading, time, math, random
import ui, JurassicParkTemplate, ending
class Gameplay(object):
"""
This class holds all the mechanics for playing the Jurassic Park Shooting Adventure
"""
def __init__(self, screen, file='Jur... |
# 打印100以内的质数
def judge(x):
for i in range(2,x):
if x % i == 0:
return False
return True
for i in range(2,101):
if judge(i):
print(i) |
#数学定理:假若p为质数,a为任意正整数,那么a^p-a可被p整除
import random
def feima():
#产生一个随机的正整数
a = random.randint(1,10000)
#求2到1000的质数
l=list(range(2,1000))
for n,i in enumerate(l):
for j in l[n+1:]:
if j%i==0:
l.remove(j)
#将列表中的整数转化为字符串,目的是为了能取出单个质数
for k in range(0,len(l)):
... |
import sqlite3
import logging
class DataStore:
'''Performs datbase operations'''
def __init__(self, database, flow_file):
self.database = database
self.flow_file = flow_file
def add_reading(self, reading):
try:
register = self.get_register(
nmi=reading... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
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... |
import requests
import re
from unicodedata import normalize
from bs4 import BeautifulSoup
from parser.course import Course
from parser.coursecode import CourseCode
from parser.unitrange import UnitRange
from parser.term import Term
class CourseParser:
def __init__(self):
self.COURSES_SOURCE = "http://cata... |
import torch
import torchvision
import torchvision.transforms as transforms
torch.manual_seed(17) # eliminate random.
batch_size = 100
# MNIST dataset
train_dataset = torchvision.datasets.MNIST(root='../../data',
train=True,
tran... |
from djangorestframework.resources import ModelResource
from shopback.base.serializer import ChartSerializer
class SearchResource(ModelResource):
""" docstring for SearchResource ModelResource """
fields = (('charts','ChartSerializer'),('item_dict',None))
#exclude = ('url',)
class RankResource(ModelResou... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import re
import sys
import io
from bs4 import BeautifulSoup
from urllib import request
import requests
import urllib.parse
import urllib.request
import http.cookiejar
# step one : login
def login_return_Cookie(authenticity_token):
# 登录后
# login_url ... |
import json
import operator
from collections import OrderedDict
from takwimu import settings
from takwimu.utils.medium import Medium
from takwimu.models.dashboard import ProfilePage, ProfileSectionPage
from takwimu.models.dashboard import TopicPage
def takwimu_countries(request):
return {
'countries': [... |
from PySide2.QtWidgets import *
import random
class Window(QWidget):
def __init__(self):
QWidget.__init__(self)
self.setMinimumSize(500,300)
self.liste = ["CSI","CIR","BIOST","CENT",'BIAST',"EST"]
self.layout = QVBoxLayout()
self.label = QLabel()
self.button = QPu... |
#!/usr/bin/env python
# coding:utf-8
# vi:tabstop=4:shiftwidth=4:expandtab:sts=4
#from pympler import tracker
#tr = tracker.SummaryTracker()
import deepstacks
from deepstacks.macros import *
from .macros import *
import pickle
#from memory_profiler import memory_usage
from StringIO import StringIO
#using_nolearn=Fa... |
"""
Project version queries
"""
from typing import Generator, List, Optional, Union
import warnings
from typeguard import typechecked
from ...helpers import Compatible, format_result, fragment_builder
from .queries import gql_project_version, GQL_PROJECT_VERSION_COUNT
from ...types import ProjectVersion as ProjectV... |
from django.urls import path
from apps.Game import views
urlpatterns = [
path('player/<int:p_id>', views.send_player_data),
path('game/<int:g_id>', views.send_game_data),
path('team/<int:t_id>', views.send_team_data),
] |
# -*- coding: utf-8 -*-
from rest_framework import permissions, viewsets
from authentication.models import Account
from authentication.permissions import IsAccountOwner
from authentication.serializers import AccountSerializer
import json
from django.contrib.auth import authenticate, login, logout
from rest_framework... |
from .models import *
from rest_framework import serializers
class ActiveCampaigns(serializers.ModelSerializer):
class Meta:
model = active_campaigns
fields = ("CAMPAIGN_ID", "ZIP" , "ADDRESS" , "CITY" , "STATE" , "COUNTRY" , "LONGITUDE", "LATITUDE", "CHAIN_ID" , "DATE" , "SLOTS")
def c... |
import uuid
from flask import request, jsonify, send_from_directory, Blueprint
from config import Config
import os
file = Blueprint("upload", __name__)
@file.route('/get/<filename>')
def get_img(filename):
return send_from_directory(Config.UPLOAD_FOLDER,filename)
@file.route('/upload/',methods=['P... |
"""Some utility functions for patterns common in Firecrown.
"""
def upper_triangle_indices(n: int):
"""generator that yields a sequence of tuples that carry the indices for an
(n x n) upper-triangular matrix. This is a replacement for the nested loops:
for i in range(n):
for j in range(i, n):
... |
#coding=utf-8
__author__ = 'love_huan'
from scipy import stats
import numpy as np
import pylab
x = np.array([1, 2, 5, 7, 10, 15])
y = np.array([2, 6, 7, 9, 14, 19])
slope, intercept, r_value, p_value, slope_std_error = stats.linregress(x, y)
predict_y = intercept + slope * x
pred_error = y - predict_y
degrees_of_freedo... |
#!/usr/bin/env python
from itertools import islice
import aiohttp
import asyncio
from async_timeout import timeout
import cachetools.func
from collections import defaultdict
from decimal import Decimal
from enum import Enum
import json
import logging
import pandas as pd
import requests
import time
from typing import (... |
# python 2.7.3
import sys
import math
n = input()
m = {}
for i in range(n):
num = input()
if num in m:
m[num] += 1
else:
m[num] = 1
cnt = 0
for k, v in m.iteritems():
if v >= 4:
cnt += v / 4
print cnt
|
from django.shortcuts import render
from django.views.generic import View
from django.http import JsonResponse
# Create your views here.
class PostView(View):
def post(self, request, *args, **kwargs):
return JsonResponse({'id': 3})
def get(self, request):
return render(request, 'posts/index.... |
# TEST :
# curl -v -X PUT -T <filepath to upload> http://127.0.0.1:8080/<optional filepath>
# Example : curl -v -X PUT -T test_wsgi1.txt http://127.0.0.1:8080/wsgi.txt
import pprint
import os
def sample_app(environ, start_response):
#pprint.pprint(environ)
# print
# The environment variable CONTENT_LENGTH may ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 21 22:11:38 2016
@author: amino
"""
import pytest
from ctip import GenParser
def test_single_var_single_val():
result = GenParser.parseFile("tests/resources/genfile1_single_var_single_arg.gen")
assert result["name"] == "bows"
assert len(result["schema"]) ... |
# Encoding: utf-8
import copy
class ProPlayer(object):
def __init__(self, name, color, board, rulebook):
self.name = name
self.color = color
self.board = board
self.rulebook = rulebook
self.weight_board = self.weightBoard()
self.depth = 5
def weightBoard(self):
board = [[4, -3, 2, 2, 2, 2, -3, 4],
... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle
import re
import pandas as pd
from textblob import TextBlob
model = pickle.load(open('Pickle_SVM_sameday_stock3.pkl', 'rb'))
#!pip install joblib
#from sklearn.exte... |
from pathlib import Path
import numpy as np
from scipy.io import wavfile
from tempfile import TemporaryDirectory
from subprocess import run, DEVNULL
import shutil
import torch
import torchaudio
import torch.nn.functional as F
torch.set_num_threads(1)
class Psycho:
def __init__(self, phi):
self.phi = phi
... |
# -*- coding:utf-8 -*-
"""输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
def recurse(node, list_):
... |
# import module
import sqlite3
# connect to localhost database
SQLiteConn = sqlite3.connect('/path/to/localhost/database/file.db')
# create a cursor
SQLiteCursor = SQLiteConn.cursor()
# Execute some queries
SQLiteCursor.execute('''CREATE TABLE example
(date text, trans text, symbol text, qty real, price r... |
"""
Django settings for course_rater project.
Generated by 'django-admin startproject' using Django 2.1.12.
"""
import os
if os.environ['ENVIRONMENT'] == 'circleci':
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if os.environ['ENVIRONMENT'] in ['development', 'ci... |
char=input("Enter an alphabet:")
if(char>='A')and(char<='Z'):
print("the alphabets is uppercase")
else:
print("the alphabets is lowercase")
|
import sqlite3
from PyQt4. QtCore import *
from PyQt4. QtGui import *
from qgis. core import *
from qgis. gui import *
from qgis. networkanalysis import *
conn = sqlite3.connect('C:\Users\Shubham\Desktop\DATABASE_SPATIALITE\DBSPatiaLite.sqlite')
c = conn.cursor()
conn.enable_load_extension(True)
c.execute("select loa... |
from tkinter import *
import Config
import Chart_plotter
class Gui:
def __init__(self):
self.root = Tk()
self.root.title("Currency prediction")
self.info = Label(self.root, text="Exchange rates from 2020", padx=10, pady=10, font='Helvetica 14 bold')
self.currency_label = Label(sel... |
# -*- coding: utf-8 -*-
from common import *
sier = {"init": "A", "replace": {"A": "B-A-B", "B": "A+B+A"}, "delta": pi / 3}
dragon = {"init": "FX", "replace": {"X": "X+YF", "Y": "FX-Y"}, "delta": pi / 2}
koch = {"init": "F", "replace": {"F": "F+F-F-F+F"}, "delta": pi / 2}
def fractal(n, ruleset):
dir = ruleset["i... |
# Retrieves data from Alberta Environment's website.
# Assumptions:
# 1. The station lists are up to date.
# 2. The url pattern for retrieving .csv data is up to date.
import os
import urllib
import datetime
# Declaration of each data category, url, and list of sites for streamflow,
# precipitation, snowpack, and ... |
#!/usr/bin/env python3
#
# Development Order #8:
#
# This file is called when perfSonar goes to print the result, which
# has been returned from the tool.
#
# To test this file, a result is needed. A sample one has been provided
# in this directory. Use the following syntax:
# cat example-result.json | ./result-format... |
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
from common import *
SIZE = 101
RESIZE = 128
PAD = 14
Y0, Y1, X0, X1 = PAD,PAD+SIZE,PAD,PAD+SIZE,
## preload resnet34
def load_old_pretrain_file(net, pretrain_file, skip=[]):
pretrain_state_dict = torch.load(pretrain_file)
state_dict = net.state_dict(... |
# This program 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 your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# b... |
#!/usr/bin/env python
#
# Very basic example of using Python 3 and IMAP to iterate over emails in an 1un1 folder/label. Extracts data regarding
# reservations from booking.com and puts them in a dict for further processing.
#
#
import copy
import json
import sys
import imaplib
import email
import email.header
import da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.