text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
import sys
import psutil
# change the command to match the full path of the executable
command = '/usr/lib/ddb/erts-7.2/bin/beam.smp'
def _bytes_to_mb(num):
return round(float(num) / 1024 / 1024, 2)
def _bytes_to_gb(num):
return round(float(num) / 1024 / 1024 / 1024, 2)
try:
perf... |
#!/usr/bin/env python
import sys
InFileName = sys.argv[1] # alignment file
OutFileName = sys.argv[2] # in group FASTA file
OutFile2Name = sys.argv[3] # out group FASTA file
numSeqs = int(sys.argv[4]) # total number of sequences
outGroup = int(sys.argv[5]) # location of the outgroup sequence
InFile =... |
#_*_coding:utf-8_*_
import logging,json,os
from django.http import Http404
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import (require_POST,require_GET)
from django.core.urlresolvers import reverse
from django.http imp... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class GrupoConfig(AppConfig):
name = 'Grupo'
|
s=input()
if(len(s.split('.'))==2):
a,b=s.split('.')
x,y=b.split(' ')
c=len(x)
if(a!='0'):
d=int(a+x)**int(y)
print(str(d)[:-c*int(y)]+'.'+str(d)[-c*int(y):])
else:
d=str(int(x)**int(y))
while len(d)<c*int(y): d='0'+d
print("0."+d)
else:
p,q=map(int,s.spli... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import io, sys
from argparse import ArgumentParser
#this script takes a text file with tab delimited columns
#and adds every column except the first line-wise to the target file.
#Both files should ideally have the same number of lines.
#The script will terminate once either ... |
from distutils.core import setup, Extension
from Cython.Build import cythonize
import numpy
ext = Extension("GMMModel",
sources=["GMMModel.pyx"],
extra_objects = ['../slgr_engine/slgr_lib.a'],
language="c++"
,include_dirs = ['../slgr_engine/',numpy.get_include(... |
from django.contrib import admin
from . import models
admin.site.register(models.RelatedResource1)
admin.site.register(models.RelatedResource2)
admin.site.register(models.TestResource)
|
# -*- coding: utf-8 -*-
import os
import datetime
import sys
import pandas as pd
from time import localtime, strftime
from collections import OrderedDict
from konlpy.tag import Twitter
from apyori import apriori
DATADIR = 'C:/Users/planit/Desktop/bigdata/'
NEWFILE = ''
def read_newfile():
dir = DATADIR
files... |
from typing import List, Tuple, Optional
from flask import Blueprint, render_template
from models import Venue, Contest
VENUE_MOD = Blueprint('venue_mod', __name__)
@VENUE_MOD.route('/')
def all_venues() -> str:
breadcrumb = [
{'path': '/', 'name': '首頁'},
{'name': '場地'}
]
venues = Venue... |
import turtle as trtl
# ----- maze and turtle config variables
screen_h = 400
screen_w = 420
startx = -100
starty = -100
turtle_scale = 1.5
# ------ robot commands
def move(times: int = 1):
i = 0
while i < times:
robot.dot(10)
robot.fd(50)
i += 1
def turn_left(times: int = 1):
i... |
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from libs.yuntongxun.sms import CCP
from user... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 2 08:42:48 2021
@author: Jose Luis Robledo
Comprensión de listas
Es un tipo de construcción que consta de una expresión que determina cómo
modificar los elementos de una lista, seguida de una o varias clausulas for y,
opcionalmente, una o varias clausulas... |
"""
#------------------------------------------------------------------------------
# Create ZV-IC Shaper
#
# This script will take a generalized input from an undamped second order system subject
# to nonzero initial conditions and solve the minimum-time ZV shaper using optimization
#
# Created: 6/20/17 - Daniel Newm... |
import os
import re
import cv2
import pickle
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from helper import save_obj
from pose_block import initial_pose_estimation
from create_renderings import create_refinement_inputs
from pose_refinement import trai... |
from . import *
from sqlalchemy.orm import column_property
class Artist(Base):
__tablename__ = 'artist'
id = Column(Integer, primary_key=True)
name = Column(String(255))
prefix = Column(String(32))
Index(name)
Index(prefix)
__table_args__ = {'mysql_engine':'MyISAM'}
def __str__(self):... |
from tkinter import *
import smtplib
import email.mime.multipart
from email.mime.text import MIMEText
import xlrd
import win32ui
def sendmail():
#登陆邮箱
head=t4.get()
subject=t5.get()
fmail='changnl@chinaunicom.cn'
psd='CNLcw198608'
smtp=smtplib
smtp=smtplib.SMTP()
smtp.connect('10.11.158.13','25')
smtp... |
#快速排序
# 思路与答案基本一致,答案的写法更加简洁,python语音用的更加灵活
def quick_sort_result(array):
if (len(array) <2):
return array
else:
pivot = array[0]
less = [i for i in array[1:] if i<= pivot]
greater = [i for i in array[1:] if i> pivot]
return quicksort(less) + [pivot] + quick_sort_result(g... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
import urllib.error
import random
from time import sleep
from src.librecatastro.domain.geometry.geo_polygon import GeoPolygon
from src.librecatastro.scrapping.searcher import Searcher
from src.settings import config
from src.utils.catastro_logger imp... |
# inspiration from https://github.com/spatialaudio/jackclient-python/issues/59
# 1.) play a sound into output
import numpy as np
try:
import queue # Python 3.x
except ImportError:
import Queue as queue # Python 2.x
queuesize = 4000
qout = queue.Queue(maxsize=queuesize)
qin = queue.Queue(maxsize=queuesize)
... |
# Uses python3
import sys
def get_fibonacci_last_digit(n):
# arr = [1,1]
if (n <= 1):
return n
else:
last_digits = [0]*60
last_digits[0] = 0
last_digits[1] = 1
for i in range(2, 60):
last_digits[i] = (last_digits[i-1] + last_digits[i-2]) % 10
r... |
import discord
from discord.ext import commands
from discord.ext.commands import cog
from pymongo import MongoClient
import os
from dotenv import load_dotenv
import asyncio
from tools import _db, embeds, combat, _json, tools, _c
import asyncio
from discord_components import DiscordComponents, Button, ButtonStyle, Inter... |
from rest_framework import permissions
from rest_framework import viewsets, status, mixins
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response
from posts.api import serializers
from posts.api.pagination import PostPagination, LikePagination
from posts.api.serializers impo... |
import numpy as np
import pandas as pd
import sys, requests, time
root_path = '/home/samir/Statistics/football/'
sys.path.append(root_path)
from football_utilities import split_espn_plr
def get_espn_proj_wk(wk):
url_str = 'http://games.espn.com/ffl/tools/projections?&scoringPeriodId=%d&seasonId=2016&slotCategory... |
#!~/anaconda3/bin/python3.6
# encoding: utf-8
"""
@author: Yongbo Wang
@file: ToxicClassification - Tune_dropout_rate.py
@time: 9/2/18 8:30 AM
"""
import numpy as np
import pandas as pd
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense... |
from behave import given, when, then
@given('character creation is "{state}"')
def step_impl(context, state):
if (state == 'shown') != context.browser.find_element_by_css_selector('form.char-form').is_displayed():
context.browser.find_element_by_id('add-char').click()
@when('user toggles character creat... |
#054: Introduction to Pattern Matching
#http://rosalind.info/problems/trie/
#Given: A list of at most 100 DNA strings of length at most 100 bp, none of which is a prefix of another.
L = ['ATAGA', 'ATC', 'GAT']
#L = ['apple', 'apropos', 'banana', 'bandana', 'orange']
#If parsing from file:
f = open('rosalind_trie.txt... |
#! python3
'''
To add a prefix to the start of the filename, such as adding spam_ to
rename eggs.txt to spam_eggs.txt
'''
import os, shutil
#TODO:ask user for prefix
filename_prefix = input('Enter the prefix that you want to add:\n')
#TODO:list all the files from the directory and rename them with prefix ad... |
import unittest
import elektra
import pandas as pd
import datetime as dt
class ElektraTests(unittest.TestCase):
def test_hello_elektra(self):
# simple test to verify tests are executing
result = elektra.hello()
self.assertEqual(result, 'elektra says hi')
def test_create_price_method(self):
# happ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-03-28 09:29
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coddy', '0006_auto_20180327_1710'),
]
operations = [
migrat... |
# python 2.7.3
import sys
import math
n = input()
a = 2
for i in range(2, n + 1):
if a % (2 ** i) == 0:
a += 2 * 10 ** (i - 1)
else:
a += 10 ** (i - 1)
print a
|
"""
多进程文件计数
"""
import os
import atexit
import multiprocessing
import json
import time
class Count(object):
def __init__(self, n):
self.n = n
self.num = 0
# atexit.register(self.dump_file)
def _count(self, path, count_type='.mp3'):
path = os.path.abspath(path)... |
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def activate(context, *paths):
"""
For use in navigation. Returns "active" if the navigation page
is the same as the page requested.
The 'django.template.context_processors.request' context processor
... |
#!/bin/python3
def game_of_thrones_i(s):
letters = [0] * 26
for char in s:
letters[ord(char)-97] += 1
letters = [x for x in letters if x % 2 != 0]
return 'YES' if len(letters) <= 1 else 'NO'
def main():
print(game_of_thrones_i(input().strip()))
main() |
import os
from process_handle_ps import ProcessHandlePs
from process_provider import ProcessProvider
class ProcessProvider_PS(ProcessProvider):
"""
Process provider on top of the "ps" utility.
"""
def _collect_all(self):
return os.popen('ps ax -o %s' % (','.join(ProcessHandlePs.ATTRS))).readlines()
de... |
from flask import Flask, jsonify, request
from sklearn.externals import joblib
import pandas as pd
import os
app = Flask(__name__)
#route our app to domain/predictiris , accept POST requests
@app.route('/predictiris', methods=['POST'])
def irisapi():
'''our main function that handles our requests and d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import lylidatabase
l = lylidatabase.LyliDatabase('links.txt', 'access.log')
while True:
print l.request(raw_input())
|
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="keys.json"
from bq_helper import BigQueryHelper
import plotly.graph_objs as go
from plotly.offline import plot
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="keys.json"
bq_assistant = BigQueryHelper('bigquery-public-data', 'san_francisco')
QUERY = """
SEL... |
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(21, GPIO.OUT)
GPIO.output(22,True)
GPIO.output(23,True)
GPIO.output(24, True)
time.sleep(2)
GPIO.output(24, False)
time.sleep(2)
|
import numpy as np
import random as random
import math
import re
import sys
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
def generate_flips(N,theta):
gen_values = np.array([random.random() for i in range(N)])
output = (gen_values < theta)*1
return output
def make_data_flips(N... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""测试基本类型"""
from typing import Any
import pytest
from smorest_sfs.extensions.marshal.bases import (
BaseIntListSchema,
BaseMsgSchema,
BasePageSchema,
)
class TestBasesMaClass:
def test_base_msg(self) -> None:
schema = BaseMsgSchema()
da... |
#!/usr/bin/env python
def test():
print 'This is a test.'
return
test()
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from pwn import *
context(arch='i386', os='linux', terminal=['tmux', 'neww'])
if args['REMOTE']:
io = remote('pwn.chal.csaw.io', 7478)
elf, libc = ELF('./minesweeper'), None
else:
io = remote('localhost', 31337)
elf, libc = ELF('./minesweeper'), None
# i... |
'''
Testing Flexible Beam
'''
import sys
from scipy.integrate import odeint
from scipy.misc import derivative
from scipy import integrate
from scipy.optimize import root
from numpy.linalg import inv
import os
import pdb
from matplotlib import pyplot as plt
import numpy as np
from scipy import optimize
sys.path.append... |
file = open('hipster_ipsum.txt')
def wordFreq ():
glutenFreeMentions = 0
coffeeMentions = 0
wokeMentions = 0
freqs = []
for word in file.read().split():
if word == str('coffee'):
coffeeMentions += 1
if word == str('Gluten-free'):
glutenFreeMentions +... |
# python 2.7.3
import sys
import math
ans = [0] * 10
def f(s):
s = str(s)
r = 0
for c in s:
r += int(c)
return r
for i in range(1, 10):
if i % 2 == 0:
m = {}
for j in range(100):
m[j] = 0
for j in range(10 ** (i / 2)):
m[f(j)] += 1
c... |
import shutil
from tqdm import tqdm_notebook as tqdm
import gzip
from youconfigme import AutoConfig
import pandas as pd
from pathlib import Path
import os
import requests
# taken from youconfigme's cast_utils
def ensure_path(path):
"""Create a path if it does not exist."""
path = Path(path)
path.mkdir(par... |
from tensorflow import keras
import numpy as np
import pandas as pd
import cv2
import random
from math import pi
import tensorflow as tf
# import os
# os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
train_samples = pd.read_csv('data/train.csv')
def rotate_images(X_imgs, start_angle, end_angle, n_images):
X_rotate = [... |
import uuid
from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
class Hospital(models.Model):
hospital_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.TextField()
address = models.TextField()
phone = models.TextField()
open... |
from maya import cmds as mc
from ..common import fk
class TongueComponent(fk):
def __init__(self, side, name, joints, parent, visibilityAttr):
self.visibilityAttr = visibilityAttr
super(TongueComponent, self).__init__(side, name, joints, parent)
def build(self, side, name, joints, parent):
... |
# Generated by Django 2.0 on 2018-10-01 09:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mili', '0004_auto_20181001_0958'),
]
operations = [
migrations.AlterField(
model_name='registration',
name='roll',
... |
from typing import Callable, Optional
import torch
from torch import nn
class NonLinear(nn.Module):
def __init__(self,
in_features: int,
out_features: int,
activation: Optional[Callable] = None,
init_func: Optional[Callable] = None) -> Non... |
import re
import unicodedata
from django import template
register = template.Library()
CENSUS = {
'tanzania': '2012',
'kenya': '2009',
'nigeria': '2006',
'senegal': '2013',
'ethiopia': '2007',
'south africa': '2011',
}
LEVEL1_NAMES = {
'tanzania': 'Region',
'kenya': 'County',
'ni... |
from enum import Enum
from typing import List, NamedTuple, Callable, Optional
import random
from math import sqrt
from core.maze.generic_search import dfs, bfs, astar,node_to_path, Node
import time
import timeit
'''
Serão ilustrados os problemas de busca em profundidade e busca em largura em um labirinto
O Labirinto é ... |
from django.db import models
from django_countries.fields import CountryField
class StudentModel(models.Model):
name = models.CharField(max_length=50)
age = models.IntegerField()
gender = models.CharField(max_length=50)
#skills = models.ManyToManyField()
country = CountryField()
remarks = model... |
from __future__ import print_function, absolute_import, division
import KratosMultiphysics as Kratos
import KratosMultiphysics.RANSApplication as KratosRANS
from KratosMultiphysics.RANSApplication.adjoint_turbulence_eddy_viscosity_model_configuration import AdjointTurbulenceEddyViscosityModelConfiguration
class Adjoi... |
from http.server import *
import random, string, ssl
"""
this is used to generate random session cookie value.
"""
chars = string.ascii_letters + string.digits
session_value = ''.join(random.choice(chars) for i in range(20))
"""
c2server class has accepts two HTTP methods.
1. GET : This method is used to se... |
import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager,Screen
from kivy.properties import ObjectProperty
from kivy.uix.button import Button
import pyrebase
import json
import requests
kezz = []
class Si... |
import random
f = open("data/occupations.csv", "r").readlines()
f = [x.strip("\r\n") for x in f]
f = f[1:-1]
def parse(elem):
occ = ""
i = 0
while i < len(elem):
if elem[i] == '"':
occ += elem[i]
i += 1
while elem[i] != '"':
occ += elem[i]
... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.seqlist = []
def __str__(self):
self.inorder(self)
return ' '.join(str(x) for x in self.seqlist)
def inorder(self, curr):... |
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
def setSpeed(motor, speed):
motor.ChangeDutyCycle(speed)
def stopMotors(lmotor,rmotor):
lmotor.stop()
rmotor.stop()
def startMotors(lmotor,rmotor):
lmotor.start(0)
rmotor.start(0)
def initMotor(pwm,in1,in2, freq):
#freq in Hz
GPIO.setup... |
# downloads youtube videos and (maybe) upload them to s3
from pytube import YouTube
import json
import subprocess
from multiprocessing import Pool
def downloadvid(url):
print("Downloading {}".format(url))
try:
yt = YouTube(url)
id_idx = url.find('watch?v=') + 8
vid_id = url[id_idx:].rstrip('/')
... |
#!/usr/bin/python
import youtube_dl
import toolbelt
import os
import sys
import re
import hashtag
import code
import importlib
import configparser
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
#from hashtag.hashtag import HashTagger
HashTagger = hashtag.HashTagger
class Y... |
from django import forms
from django.contrib.auth.models import User
dep=(
("CSE", "Computer Science and Engineering"),
("ECE", "Electronics and Communication Engineering"),
("MECH", "Mechanical Engineering"),
("EEE", "Electrical and Electronics Engineering"),
("MECT", "Mechatronics"),
("I... |
import os
import sys
import logging
import opentracing
import datetime
import aiohttp
import time
import json
import traceback as tb
import functools
import socket
from sanic.request import Request
from basictracer.recorder import SpanRecorder
from config import utils
STANDARD_ANNOTATIONS = {"client": {"cs": [], "c... |
import RPi.GPIO as GPIO
import time
import math
#Code that plays the interesting game Cyclone.
class cycleTimer(object):
def __init__(self, initTime, cycleLength,actionsPerCycle):
self.actionTime=float(cycleLength)/float(actionsPerCycle)
self.cycleLength=cycleLength
self.initTime=initTime
self.actionsP... |
from flask import Flask, json, request, jsonify, redirect, url_for
from flask_cors import CORS
from pymongo import MongoClient
from name_ge import NameGenerator
from verify_file import verify_file
import os
import uuid
import config
import datetime
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
CORS(app)
cf... |
import pytest
from share.models import SourceConfig
data = r'''
{
"record": [
"OpenTeQ - Opening the black box of Teacher Quality",
"https://www.socialscienceregistry.org/trials/1638",
"June 06, 2017",
"2017-06-06 11:59:10 -0400",
"2017-06-06",
"AEARCTR-0001638",
... |
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if len(nums)==0:
return 0
i = 0
j = 0
while(j<len(nums) and i<len(nums)):
while(j<len(nums) and (nums[j]==nums[i])):
j+=1
... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import yaml
with open('_data/seminars.yml', 'r') as data_stream:
try:
data = yaml.safe_load(data_stream)
for record in reversed(data):
print('<p>\n{}'.format(record['date']), end='')
if 'author' in record:
prin... |
from django.contrib import admin
from .models import WeatherModels
admin.site.register(WeatherModels) |
import urllib
import httplib
from BeautifulSoup import BeautifulSoup, SoupStrainer
def getHtml(url, fpath):
try:
retval = urllib.urlretrieve(url, fpath)
except (IOError, httplib.InvalidURL) as e:
retval = ('*** error: bad url "%s" : %s') % (url, e)
return retval
# def getHtml2(url):
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Bootstrap helps you to test pyFAI scripts without installing them
by patching your PYTHONPATH on the fly
example: ./bootstrap.py pyFAI-integrate test/testimages/Pilatus1M.edf
"""
__authors__ = ["Frédéric-Emmanuel Picca", "Jérôme Kieffer"]
__contact__ = "jerome.kief... |
import math
class Camera:
def __init__(self, pos_x, pos_y, angle, fov):
self.pos_x = pos_x
self.pos_y = pos_y
self.fov = fov
self.angle = angle
self.dir_x = math.cos(math.radians(angle))
self.dir_y = math.sin(math.radians(angle))
self.plane_x = self.dir_y * ... |
#coding = utf-8
from selenium import webdriver
from time import sleep, ctime
import os
options = webdriver.ChromeOptions()
options.binary_location = "C:/Users/ASUS/AppData/Local/Google/Chrome/Application/chrome.exe"
chrome_driver_binary = "C:/Users/ASUS/AppData/Local/Google/Chrome/Application/chromedriver"
driver = we... |
from django.db import models
from django.contrib.auth.models import User
class Project(models.Model):
choices_project = (
('completed' , 'Completed'),
('collab' , "Looking for Collaboration")
)
title = models.CharField(max_length = 100)
description = models.TextField()
status = mode... |
#!/usr/bin/python
import sys
sys.path.append('/usr/local/share/osckar/lib/')
import comm as c
import socket
comm = c.Comm()
class Osckar:
def __init__(self):
return
def connect(self,host,port):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect(('localho... |
__author__ = 'Dejust'
__name__ = 'engine'
|
"""
back.app.routes.alerts
This module contains the different services for the alerts table.
"""
from flask import jsonify, request, Blueprint
from .. import app, db
from ..models.alerts import Alerts
from ..utils import required_fields
alerts_blueprint = Blueprint('alerts', __name__)
@alerts_blueprint.route('/his... |
#coding=utf8
import httplib2
from BeautifulSoup import BeautifulSoup
from datetime import *
import random
import time
from fake_useragent import UserAgent
def processPage(head, content):
soup = BeautifulSoup(content)
acList = soup.find("ul", {"class" : "events-list events-list-pic100 events-list-psmall"}).find... |
EPOCHS = 9 # Number of epochs
BATCH_SIZE = 1
SHUFFLE_DATA = True
NUM_WORKERS = 6
EMBEDDING_DIM = 256
HIDDEN_DIM = 512
MAX_LENGTH = 100
MODEL_NAME = "entity-extraction2"
|
Your input
10
3
Output
3
Expected
3
Your input
11
3
Output
3
Expected
3 |
"""Brain Calc game logic."""
import operator
import random
from typing import Tuple
MIN_NUMBER = 0
MAX_NUMBER = 10
DESCRIPTION = 'What is the result of the expression?'
def calculate(operand1: int, operand2: int, operator_sign: str) -> int:
"""
Calculate the result of applying the operation to operands.
... |
"""
Python Wechaty - https://github.com/wechaty/python-wechaty
Authors: Huan LI (李卓桓) <https://github.com/huan>
Jingjing WU (吴京京) <https://github.com/wj-Mcat>
2020-now @ Copyright Wechaty
Licensed under the Apache License, Version 2.0 (the 'License');
you may not use this file except in compliance wit... |
# Generated by Django 3.1.6 on 2021-03-24 20:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Account',
fields=[
... |
#!/usr/bin/env python3
import sqlite3
import os.path
import os
import re
import hashlib
with sqlite3.Connection('wikileaks.db') as db:
try:
cur = db.cursor()
##
# Add the original_name field
##
# for r in cur.execute('SELECT * FROM podesta_emails').fetchall():
# cur.execute('INSERT INTO podesta_emai... |
def inspect(item, grammar_name='G', mapper=None):
try:
return mapper[item]
except (TypeError, KeyError ):
if isinstance(item, dict):
items = ',\n '.join(f'{inspect(key, grammar_name, mapper)}: {inspect(value, grammar_name, mapper)}' for key, value in item.items() )
re... |
# Generated by Django 2.1.7 on 2019-08-18 19:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('frame', '0003_auto_20190818_1930'),
]
operations = [
migrations.AlterField(
model_name='framemodel',
name='mean',
... |
from sirmoDBMSnew import DBaccess
SirmoDB = DBaccess("SirmotechBMS")
SirmoDB.connectDB()
SirmoDB.addNewConsultant('Niki', 'White', '2019-02-03', '1979-10-25', '4','3')
SirmoDB.addNewConsultant('Sandy', 'Thompson', '2015-04-10', '1986-11-05', '1','1')
SirmoDB.removeConsultant("Niki","White")
SirmoDB.getMinHourlyRateA... |
__module_name__ = 'care.py'
__module_version__ = '1.0'
__module_description__ = 'Sajoin to #care Plugin'
__module_author__ = 'Ferus'
import xchat
def isChan():
net = (xchat.get_context()).get_info('network')
if net == 'DatNode':
return True
else:
return False
def lols(word, word_eol, userdata):
if isChan():
... |
# import tkinter
# import
import matplotlib.pyplot as plt
# import matplotlib
import numpy as np
# plt.ion()
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots(nrows=2, ncols=2)
# fig, ax = plt.subplots()
ax[0,1].plot(t, s)
ax[0,1].set(xlabel='time', ylabel='voltage', title='about as... |
favorite_languages = {
'jen' : 'Python',
'sarah' : 'c',
'edward' : 'ruby',
'phil' : 'Python'
}
# para descobrir se uma pessoa em particular participou da enquete.
if 'Alex' not in favorite_languages.keys():
print('Desculpe seu nome nao está na lista')
print('Por favor participe de nossa enque... |
# !/usr/bin/#!/usr/bin/env python3
print("Content-type: text/html")
print()
print("<h1> Hello stranger</h1>")
|
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'vlanSync.settings'
import django
django.setup()
from sync.SyncHandler import SyncHandler
from sync.models import LocalVlans, RemoteVlans, Tmp
def main():
SyncHandler.startSync()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# "Unless you know the code, it has no meaning." ~ John Connolly
__author__ = "hero24"
# Python 2 Memoization example:
def fib(n,mem=[0]):
# Example of fibonacci sequence with use of memoization
if n < len(mem):
return mem[n]
else:
if n < 2:
res = n
... |
#!/usr/bin/python
"""
-----------------------------------------------
Auto Layer Shadow Render Layers
Written By: Colton Fetters
Version: 1.0
First release: 2/17/2017
-----------------------------------------------
"""
import os
import maya.cmds as cmds
import maya.mel as mel
import render_layers as ren... |
ids = ['315880575', '205847932']
def get_neighbors(coordinates, board_size, exclude=tuple()):
# gets the coordinates of the neighboring tile
neighbors = list()
if coordinates[0] != 0 and (coordinates[0] - 1, coordinates[1]) not in exclude:
neighbors.append((coordinates[0] - 1, coordinates[1]))
... |
def valid_parentheses(pairs):
results = []
def inner(prefix, remain_pairs, extra_close):
assert remain_pairs >= 1
new_prefix_base = prefix + '(' # Always add an '(' at the begining
max_close = extra_close + 1
new_remain_pairs = remain_pairs - 1
if new_rema... |
# Generated by Django 3.2 on 2021-04-18 20:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('oauth', '0007_profile_profile_photo'),
]
operations = [
migrations.AlterModelOptions(
name='profile',
options={'orderi... |
# Problem 1
# My solution
x = 0
while (x <= 10):
x += 2
print x
print 'Goodbye!'
# Best practice
num = 2
while num < 11:
print num
num += 2
print "Goodbye!"
# Problem 2
print "Hello!"
num = 10
while num > 0:
print num # print the num first
num -= 2
# Problem 3
total = 0
current... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.