text stringlengths 8 6.05M |
|---|
import urllib2
from BeautifulSoup import BeautifulSoup
#the text of news stories are usually hidden in a mess of html
#for ads, comments, and related stories. The trick here is to find
#a unique marker for where a story begins, and then grab all of the
#stories text and images (without any extra junk).
def NPR_news_... |
"""A set of native python APIs to create a network model and run
network simulations."""
from .circuit import Circuit # noqa: F401
from .demand import Demand # noqa: F401
from .interface import Interface # noqa: F401
from .model import Model # noqa: F401
from .exceptions import ModelException # noqa: F401
from .n... |
from datetime import datetime
from struct import unpack
from typing import Any
from typing import Dict
from typing import List
from typing import Union
import serial
class ChannelNotFoundError(Exception):
'''Raised when the logger channel is not found'''
pass
class ChannelError(Exception):
'''Raised wh... |
#!/usr/bin/env python
import unittest
from asyncdnspy.tcp_client import TCPClient
from asyncdnspy.dns_raw_message import DNSRawMessage
from asyncdnspy.dnspy_enum import RecordType, SocketType
class TCPClientTest(unittest.TestCase):
def test_send(self):
tcp_client = TCPClient('8.8.8.8', 53)
tcp_... |
from pydantic.version import VERSION as PYDANTIC_VERSION
PYDANTIC2 = PYDANTIC_VERSION.startswith("2")
__all__ = [
"BaseModel",
"ValidationError",
"Field",
"root_validator",
"AnyUrl",
"BaseSettings",
"EmailStr",
"validator",
]
if PYDANTIC2:
from pydantic.v1 import (
AnyUrl,... |
from ex107 import moeda
p = int(input('Digite um número: '))
moeda.resumo(p, 80, 35) |
from ftplib import FTP
import os
host = "pcredit.ayz.pl"
user = "pcredit"
password = "OE06jiai"
File2Send = "C:\\Users\\sjaku\\Desktop\\linuxpl\\"
MacOSx2Send = "//Users//szymon//Downloads//[Dla_sklepu]//banery//slider_baner//"
FTP_Server = "//domains//kreatywneklocki.pl//public_html//img//lego//"
ftp = FTP(host)
... |
import unittest
import doctest
from zeam.form.ztk.testing import FunctionalLayer
def test_suite():
optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
globs= {}
suite = unittest.TestSuite()
for filename in ['fields.txt', 'validation.txt']:
test = doctest.DocFileSuite(
op... |
import random
print("'Spanzuratoarea' cu cifre.")
print("Doriti sa jucati? ")
dorinta = input()
bucla3 = 1
if dorinta == "da":
while bucla3 == 1:
print('Ghiceste prima cifra:')
incercare = 10
nums_0 = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
nums_1 = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
... |
from django.db import models
from ..users.models import User
from ..authors.models import Author
# Create your models here.
class BookManager(models.Manager):
def book_valid(self, postData):
errors = {}
if len(postData['title']) < 1: # null
errors['bad_title'] = "Oops, you forgot to ent... |
import itertools
DEFAULT_SIGN = '_'
def get_player(current_player):
if current_player == 'X':
print 'Player 1, your sign is %s: ' % current_player
else:
print 'Player 2, your sign is %s: ' % current_player
def get_field(board, current_player):
while True:
try:
row = ... |
from django.urls import path
from . import views
urlpatterns = [
path('',views.Homepage, name='home'),
path('count/',views.countfunction, name='COUNTIT'), #'count/ is the urlname'
path('about/',views.aboutpage, name='about')
]
|
from pico2d import *
import game_framework
from boy import Boy
# from enum import Enum
# BOYS_COUNT = 1000
class Grass:
def __init__(self):
self.image = load_image('../res/grass.png')
print(self.image)
def draw(self):
self.image.draw(400, 30)
def handle_events():
global boy
g... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#######################
import os
import sys
import indigo
import math
import decimal
import datetime
import socket
import subprocess
from ghpu import GitHubPluginUpdater
class Plugin(indigo.PluginBase):
def __init__(self, pluginId, pluginDisplayName, pluginVersion,... |
class Persona:
_siguiente = 0
def __init__(self, nombre ="Invitado", activo=True):
Persona._siguiente = Persona._siguiente + 1
self.__codigo = Persona._siguiente
self.__nombre = __nombre_Mayuscula(nomb)
self.activo = activo
#prvado con gion bajo
@property
def no... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 29 15:14:17 2019
@author: KelvinOX25
"""
import pyvisa
import time
import logging
import numpy as np
import struct
from qcodes import VisaInstrument, validators as vals
class Keithley_6220(VisaInstrument):
def __init__(self, name, address, **kw):
... |
import pandas as pd
from utils import Example, Indexer, pos
import random
def spooky_authorship_data(args, test_split=0.7, max_char_length=500, postags=False):
with open("data/spooky-authorship/train.csv", encoding='utf-8') as f:
train_df = pd.read_csv(f)
train_df.applymap(lambda s: s[1:-1] if s.star... |
import os
from managers.core import CoreManager
import config
os.system("export GOOGLE_APPLICATION_CREDENTIALS='service_account.json'")
core_manager = CoreManager(config.params)
core_manager.translate()
|
import mysql.connector
from mysql.connector import Error
import xlsxwriter
def insert_profile(term,gre_date,work_experience_months,ug_score,ug_score_pattern,en_exam_pattern,en_exam_score,
gre_score,status,course_name,university_name,gre_verbal_score,gre_quant_score,
gre_awa_sc... |
import argparse
import webbrowser
import colorama
from colorama import Fore
from . import scraper
def print_data(data) :
for num, i in enumerate(data, start=1) :
title = Fore.BLUE + i["title"]
store = Fore.YELLOW + i["store"]
print(f"{num}. {title} - {store}")
def ope... |
from unittest import TestLoader, TestSuite
from pyunitreport import HTMLTestRunner
from assertion import AssertionsTest
from searchtest import SearchTests
assertionTest = TestLoader().loadTestsFromTestCase(AssertionsTest)
searchTest = TestLoader().loadTestsFromTestCase(SearchTests)
smokeTest = TestSuite([assertionTes... |
# -*- coding: UTF-8 -*-
# 如果制定了当前编码为utf8 编码,则该文件中的汉字都是byte string格式。
# 在函数中取数来的字符串一般是unicode string格式
# 文件操作的步骤:打开文件-操作文件-关闭文件
import io
# 读取文件的两种方法
# 1, 拿到文件描述器,将文件加入到内存中,适合小文件 f.readLines(),在生产环境中尽量少用readLines()方法
f = io.open("onePoem", "r", encoding="utf-8")
for i in f.readlines():
print(i.strip())
# 2,拿到文件描述器... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 16 16:29:58 2021
@author: chanchanchan
"""
#Variables in Bender Element Analyisis:
#Fast Fourior Transform:
#Input Signal
Input_Signal_kHz = 3
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import DissertationPlotwithDat... |
from datetime import datetime
from db_config import db, ma
class PerformanceAnalysis(db.Model):
__tablename__ = "performance_analysis"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
start_date = db.Column(db.DateTime, nullable=False, default=datetime.now)
end_date = db.Column(db.Date... |
import requests
def _url(path):
return 'http://104.199.18.3:8080'+path
def get_containers() :
return requests.get(_url('/containers'))
def get_containers_running() :
return requests.get(_url('/containers?state=running'))
def get_services():
return requests.get(_url('/services'))
def get_nodes():
... |
import datetime
import random
def wishMe():
hour = int(datetime.datetime.now().hour)
wish = ""
if hour >= 0 and hour < 12:
wish = "Good Morning!"
elif hour >= 12 and hour < 18:
wish = "Good Afternoon!"
else:
wish = "Good Evening!"
return f"{wish} I am Shaktiman, How ca... |
import urllib
from django.contrib.auth import authenticate, login
from rest_framework import serializers, status
from rest_framework.authentication import BasicAuthentication
from rest_framework.response import Response
import json
from edtech.apis.api_error_response import APIErrorResponse
from edtech.apis.edtech_ap... |
from datetime import datetime
from income import Income
from expense import Expense
class MoneyTracker:
def __init__(self, aggregated_object):
self.aggregated_object = aggregated_object
def show_expenses_for_date(self, date, expenses):
for expense in expenses:
if expense.date == d... |
from redis import Redis
redis_connection = Redis()
key = "some-key"
value = "some-val"
redis_connection.set(key, value)
print(redis_connection.get(key)) |
'''
Created on Feb 12, 2013
@author: Christian M Brodbeck
'''
from itertools import izip
import os
from mne.label import _get_annot_fname
from mne.utils import get_subjects_dir
from nibabel.freesurfer import read_annot, write_annot
def fix_annot_names(subject, parc, clean_subject=None, clean_parc=None,
... |
age = 1
if age > 0 and age != 1:
print 'abc'
elif age == 1:
print 1
else:
print 'ddd'
arr = [1, 2, 3]
for e in arr:
print e
print range(5)
|
#!/usr/bin/env python3
import os
def main():
cmd = "python3 -m pip install --upgrade fx_bin"
print(cmd)
os.system(cmd)
if __name__ == '__main__':
main()
|
#import zmq
import logging
import sys
import os
import time
import datetime
from .PlatformClient import PlatformClient
from . import PlatformStructs as Pstruct
from . import helper
POLLING_INTERVAL = 1 # seconds
class Solver(PlatformClient):
def __init__(self,index):
super().__init__()
self.logg... |
# -*- coding:utf-8 -*-
import requests
import json
import common
from lxml import etree
def extract_product_json(cjson):
if cjson['Msg'] != 'success':
print 'get product json error\n'
return None
product_sum = cjson['PkgsCount']
products = cjson['Pkgs']
item = {}
for product in pr... |
#!/usr/bin/env python
import sys
sys.path.append("..")
import math
from game.base.entity import Entity
from game.base.signal import Signal
import weakref
import glm
def test_scene():
scene = Signal()
ent = Entity(None, scene)
slot = scene.connect(ent)
ent.slot = weakref.ref(slot)
assert len(sc... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 22 11:07:15 2017
@author: jte-sre
"""
from __future__ import division
def reference_building(building):
"""
This function calculates parameters for a reference building with the
dimensions of the examined building. Especially the values for the primary
ene... |
def pattern(n):
nums = map(str, xrange(n, 0, -1))
return '\n'.join(''.join(nums[:a]) for a in xrange(n, 0, -1))
|
'''
输出10行的杨辉三角
'''
row=10 #行数
triangle= [[0 for i in range(row)] for i in range(row)] #10行10列数组
for i in range(row): #行
for j in range(row): #列
if j==0 or j==i:
triangle[i][j]=1
else:
triangle[i][j]=triangle[i-1][j]+triangle[i-1][j-1]
# if tr... |
#!/usr/bin/env python3
from sympy import isprime
n = 1
total_primes = 0
while True:
donji_lijevi = (2*n + 1)**2 - 2*n
gornji_lijevi = donji_lijevi - 2*n
gornji_desni = gornji_lijevi - 2*n
if isprime(donji_lijevi):
total_primes += 1
if isprime(gornji_lijevi):
total_primes += 1
... |
from random import randint
print("You only have 3 chances to guess")
bil = randint(0, 30)
chance = 3
for chances in range(chance):
#Input number
number = int(input("input numbers 0 to 30="))
if number == bil:
print("hore,your prediction is right")
break;
elif number < bil:
print("a little more you... |
#!/usr/bin/env python
Donators = {
u"James Hemmaplardh": [10, 50, 900],
u"Bill Gates": [999, 9999, 999],
u"The Batman": [1],
u"Dash Berlin": [10, 5],
u"Avicii Levels": [69, 99, 101]
}
def send_thankyou():
while True:
name = raw_input(u"Enter 'list' for a list of donor names. Ente... |
'''
created by shadysource
MIT license
'''
## this preparation tool is created for my data
# it could be used as inspiration for other datasets
# copyright 2018 shadySource
# MIT license
import os
from os.path import join
import cv2
import numpy as np
from PIL import Image
def preprocess_image(x):
x = x.astype... |
def BuscaBin(list, item):
prim = 0
ult = len(list) -1
found = False
while prim <= ult and not found:
meio = (prim + ult) // 2
if list[meio] == item:
found = True
else:
if item < list[meio]:
ult = meio - 1
else:
... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# In[2]:
#Lettura Excel del foglio users.
users = pd.read_excel('keystroke_51_Aggiornato.xls','users')
#users
users.shape
# In[3]:
users.columns
# In[4]:
#per filtrare i dati utilizziamo ... |
#!/usr/bin/python
# -*-coding:gbk-*-
import json
from json import JSONDecodeError
from helper.Grep import Grep
from urllib import parse
import os
import sys
from functools import reduce
import requests
class anjuke():
timesleep = 1
def __init__(self, timesleep):
self.timesleep = timesleep
def ... |
"""
Utilities for importing the LANDFIRE dataset into LandscapeSim.
The ST-Sim model library uses the BPS_MODEL code as the name, which is not suitable for display.
The goal here is to use the existing metadata to import the appropriate name for the model name, but leave the
model library untouched.
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-02-06 09:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('web', '0001_initial'),
]
operations = [
migrations.CreateModel(
... |
"""A demo shows how to use binary focal loss."""
import numpy as np
from keras.datasets import imdb
from keras.layers import Dense
from keras.models import Input, Model
from keras.regularizers import l2
from sklearn.utils import compute_class_weight
from losses.focal_loss import binary_focal_loss
def crea... |
from django.shortcuts import render, redirect
from .models import Contact
from login.decorators import login_required
def intro(request):
return render(request, 'about/intro.html')
# @login_required
def contact(request):
if request.method == 'GET':
return render(request, 'about/contact.html')
elif... |
class Solution:
def parse_roman_numerals(self, input):
new = list()
for char in input:
if char == "M":
new.append(1000)
elif char == "D":
new.append(500)
elif char == "C":
new.append(100)
... |
from django.conf.urls import url
from .views import views,garmin_views
app_name = 'user_input'
urlpatterns = [
url(r'^daily_input/$',views.UserDailyInputView.as_view(),
name='user_daily_input'),
url(r'^daily_input/item/$',views.UserDailyInputItemView.as_view(),
name='user_daily_input_item'),
url(... |
#!/usr/bin/python
import math
arr = []
ans = {}
for i in range(1000):
arr.append(i ** 2)
for i in range(1, 1000):
for j in range(i, 1000):
k = math.sqrt(arr[i] + arr[j])
if int(k) == k:
p = k + math.sqrt(arr[i]) + math.sqrt(arr[j])
if p in ans:
ans[p] +=... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import Tk, Text, Scrollbar, Menu, messagebox, filedialog, BooleanVar, Checkbutton, Label, Entry, StringVar, Grid, Frame
import os, subprocess, json, string
class Editor():
def __init__(self, root):
self.root = root
self.TITLE = "W... |
# ###### this is simple ML program with use of Classification Tree method
# ###### this program learn sex of people from ghad, vazn, kafsh, and predict base on them
import csv
from sklearn import tree
x = []
y = []
with open('somefile_withdataforlearning.csv', 'r') as fin:
data = csv.reader(fin)
for line in ... |
from .models import Role, UserRole, Permission
from shop.models import Shop
from account.models import User
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework import generics, pagination
from rest_framework.response import Response
from .serializers import RoleSerialize... |
from urllib import request
from treadmill.infra import connection
def _get_ip(anywhere):
if anywhere:
_ip = '0.0.0.0/0'
else:
_ip = request.urlopen(
'http://ip.42.pl/raw'
).read().decode('utf-8') + '/32'
return _ip
def enable(port, group_id, protocol='tcp', anywhere=T... |
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
... |
import xadmin as admin
from teaman.tea import models
class SupplierAdmin(object):
list_display=('name','tel')
class ProductTypeAdmin(object):
list_display=('name',)
class ProductAdmin(object):
list_display=('name','supplier','status','price','pub_date','year','type','last_modify')
list_filter=('status','type','s... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import dataclasses
import re
from dataclasses import dataclass
from typing import Iterable
from urllib.parse import quote_plus as url_quote_plus
from p... |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
def findmax_depth(root):
if not root:
return 0
else:
return 1 + max(findmax_depth(root.left), findmax_depth... |
import requests
from bs4 import BeautifulSoup
import pymysql
kc_list = [
'hEX Lite',
'hEX',
'RB2011iL-RM',
'RB2011UiAS-RM',
'CCR1009-7G-1C-1S+',
'CCR1016-12G',
'CCR1016-12S-1S+',
'CCR1036-12G-4S',
'CCR1036-8G-2S+',
'CCR1072-1G-8S+',
'RB450',
'RB450G',
'CRS326-24G-2S+... |
msg=input("Enter a string:")
z=msg.split()
print(z)
i=0
for x in z:
m=x.split()
for y in m:
if y in "aeiou":
del x[i]
i+=1
print(msg)
|
#!/usr/bin/python
import os
import sys
from logic.parking import Parking
class Commands(object):
"""
class to handle command line operations
"""
def __init__(self):
self.parking = Parking()
@staticmethod
def script_usage():
"""
script usage
:return:
"... |
#!/usr/bin/env python2
import __builtin__
import os
__builtin__.process = 'client'
# Temporary hack patch:
__builtin__.__dict__.update(__import__('pandac.PandaModules', fromlist = ['*']).__dict__)
from direct.extensions_native import HTTPChannel_extensions
from direct.extensions_native import Mat3_extensions
from dir... |
# Generated by Django 2.1.7 on 2019-03-09 11:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('milliard', '0003_auto_20190309_1422'),
]
operations = [
migrations.AlterField(
model_name='choi... |
#!/usr/bin/python3
def printinfo( arg1, *vartuple ):
print("output: ")
print(arg1)
for var in vartuple:
print(var)
return
# call printinfo method
printinfo(10)
printinfo(70, 60, 50) |
arr = [16,10,3,20,11]
print(arr.index(min(arr)))
print(arr.index(max(arr)))
|
from django.apps import AppConfig
class TusomeConfig(AppConfig):
name = 'tusome'
|
import unittest
from katas.beta.kontti_language import kontti
class KonttiTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(kontti('lamppu'), 'komppu-lantti')
def test_equals_2(self):
self.assertEqual(kontti('lamppu sofia'), 'komppu-lantti kofia-sontti')
def test_equa... |
import random
import string
import pyperclip
def generate(Number: int, Symbols: str):
return ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits + Symbols) for _ in range(Number))
def copy(Variable: vars):
pyperclip.copy(Variable) |
# encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
import numpy as np
from fastai.vision import *
from fastai.vision.image import *
__all__ = ['RandomErasing']
def _random_erasing(x, probability=0.5, sl=0.02, sh=0.4, r1=0.3,
mean=(np.array(imagenet_stats[1]) + 1) ... |
"""Top-level package for SALT API Server."""
__author__ = """SALT Astronomy"""
__version__ = "0.1.0"
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, current_app
from flask_sqlalchemy import SQLAlchemy
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration... |
from rest_framework import serializers
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email')
class RegisterSerializer(serializers.ModelSerializer):
class Meta:
model = User
f... |
"""Tests for the 'the' plugin"""
import unittest
from test import _common
from beets import config
from beetsplug.the import ThePlugin, PATTERN_A, PATTERN_THE, FORMAT
class ThePluginTest(_common.TestCase):
def test_unthe_with_default_patterns(self):
self.assertEqual(ThePlugin().unthe('', PATTERN_THE), ... |
from flask import Flask, request, jsonify
from github import Github, GithubException
app = Flask(__name__)
@app.route("/", methods = ['POST'])
def createFiles():
PostData = request.json
templateAttr = PostData.get("struct")
g = Github(PostData.get("username"), PostData.get("password"))
user = g.get_user... |
import os
import subprocess
import logging
from math import floor
from itertools import repeat
from pymongo import MongoClient
from multiprocessing.dummy import Pool
from tqdm import tqdm
def main():
db = db_connect()
outdir = './'
threads = 4
process_list = []
for element in db.find():
pr... |
def write_list_to_file(fname, lst):
fo = open(fname, "a+") #append
for w in lst:
fo.write("%s\n" % w)
fo.close()
def write_dict_to_file(fname, _dict):
fo = open(fname, "a+") #append
for k,v in _dict.items():
fo.write(" %s , %s\n " % (k , v))
fo.write("\n")
fo.close()
def print_... |
#! /usr/bin/env python3
import datetime, sys, glob, os, re, subprocess, numpy as np
# prints error to std error
def eprint( *args, **kwargs ):
print(*args, file = sys.stderr, **kwargs )
def collect_files(directory = './', filetype = '*', recursive = True, verbose = False):
if verbose == True:
print(... |
import os
import sys
import subprocess
import shutil
sys.path.insert(0, 'scripts')
sys.path.insert(0, 'tools/families')
import fam
import experiments as exp
def uncompress(archive):
archive_name = os.path.basename(os.path.normpath(archive)).replace(".tar.gz", "")
datadir = fam.get_datadir(archive_name)
families... |
#!/usr/bin/python -tt
#
# Copyright (c) 2008, 2009, 2010, 2011 Intel, Inc.
#
# 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; version 2 of the License
#
# This program is distributed in the hope ... |
import numpy as np
import re
import os
import gudhi as gd
import time
#import dionysus as d
#from scipy.spatial.distance import squareform
import sys
import csv
import argparse
import networkx as nx
def read_raw_HiC_data(file):
resolution=re.split('[_.]',os.path.basename(file).strip())[1]
if(resolution[-2:]=='... |
#hw6 problem 2
#I pledge my honor that I have abided by the Stevens honor system -Maya O
def main():
weight = int(input("Please enter your weight in pounds: "))
height = int(input("Please enter your height in inches: "))
bmi = (720 * weight)/(height ** 2)
print()
if bmi <19:
print("Based o... |
from flask_api import status
from family_foto.app import add_user
from family_foto.models import db
from family_foto.models.photo import Photo
from tests.base_login_test_case import BaseLoginTestCase
from tests.base_photo_test_case import BasePhotoTestCase
class ImageViewTestCase(BaseLoginTestCase, BasePhotoTestCase... |
#!/usr/bin/python
import sys, os, os.path
import simplejson as json
from urllib import urlopen
"""
this scripts the commandlinefu's from the site, commandlinefu.com in
json format and displays them in a neat fashion.
"""
def fetchcommands(command):
""" fetch the commadline snippets based on the command passd."""
... |
# vim: encoding=utf-8
""" Localization table
"""
LITS = {
'en': ["New Moon", "First Quarter", "Full Moon", "Last Quarter"],
'be': ["Маладзік", "Першая чвэрць", "Поўня", "Апошняя чвэрць"],
'bg': ["Новолуние", "Първа четвърт", "Пълнолуние", "Последна четвърт"],
'ca': ["Noviluni", "Quart creixent", "Pleni... |
data = []
with open("../phrase-table.hi-en") as f:
for line in f:
temp = line.strip().split(" ||| ")
scores = temp[2]
direct_phrase_translation_probability = float(scores.split()[2].strip())
data.append((direct_phrase_translation_probability, line))
data.sort()
with open("../sorted_phrase_table.hi-en", "w") a... |
class LaserDiode:
# not implemented
pass |
#/usr/bin/python
import vault_utils
import time
from prometheus_client import start_http_server
from prometheus_client.core import GaugeMetricFamily, CounterMetricFamily, REGISTRY
import argparse
parser = argparse.ArgumentParser(description='Vault Exporter')
parser.add_argument('--cert','-c', help='Client certificat... |
dictionary = [["线", "长方形", "正方形", "圆", "多边形", "線", "長方形", "正方形", "円", "多辺形","line", "rectangle", "square", "circle", "polygon"],
["画", "描", "Draw", "为", "是", "在", "从",
"到", "は", "を", "に", "から", "まで", "is","at","the","from","to"],
["宽", "高", "颜色", "大小", "背景色", "底色", "半径", "位置", ... |
import clustering.scripts as clustering_scripts
import numpy as np
import bisect
import classes
from globals import (
BATTERY_LIMIT,
LOST_TRIP_REWARD,
ITERATION_LENGTH_MINUTES,
WHITE,
DISCOUNT_RATE,
)
from decision.get_policy import get_policy
from progress.bar import IncrementalBar
class World:
... |
import pygame
import random
from math import *
from yume import *
from yume import gfx
from yume.gfx import get_gfx
from yume.resource import *
from pygame import Rect
class Projectile(gfx.Drawable):
def __init__(self, origin, target):
gfx.Drawable.__init__(self)
self.origin = origin
self.target = target... |
"""
Various utils to retreive from database and export to file
"""
import config
from lib.Database import Database
import os
import shutil
from uuid import UUID
from dateutil.parser import parse as dateparse
async def main(args):
if len(args) == 0:
print("What you want to export to? [syncrude|pymot|pa... |
"""Live tests"""
import unittest
import json
from heatmiserV3 import heatmiser, connection
class TestLiveHeatmiserThermostat(unittest.TestCase):
"""Testing an actual thermostat"""
def setUp(self):
"""Creates serial con and thermostat"""
self.con = connection.hmserial('192.168.1.57', '102')
... |
from ortools.constraint_solver import pywrapcp
import pudb
# pudb.set_trace()
def main():
# Create Solver
solver = pywrapcp.Solver("ProcessOrder")
# Data Feed
machines_count = 1
all_machines = range(0, machines_count)
# ["Knife", 5] means it takes 5 minutes to setup machine M1 for production
... |
import verifier
import sys
import time
def main(argv):
for k in range(83, 100):
start = time.time()
verifier.main(['microvisor.hex', '/dev/ttyACM0', 1])
print(int(k) + ":" + str(time.time() - start))
if __name__ == "__main__":
main(sys.argv[1:])
|
import zmq
import sys
import threading
global user
global lastUser
lastUser = ""
def sendRequest(): # to send message requests to server
context = zmq.Context()
sock = context.socket(zmq.PUSH) #list of queued items need to be routed for the one asking for it
sock.connect("tcp://127.0.0.1:5678")
while... |
from __future__ import print_function
from __future__ import division
from pyLM import *
from pyLM.units import *
from pySTDLM import *
from pySTDLM.PostProcessing import *
from pySTDLM.StandardReactionSystems import *
# from pySTDLM.StandardCells import *
import h5py
import numpy as np
import os
from lib.lmUtils imp... |
import os
import queue
import collections
import random
from enum import Enum, unique
import alive_util
import util_channel as channel
import alive_mem as am
@unique
class FsTargetEnum(Enum):
unknown = 0
regular_file = 1
directory = 2
@unique
class FsCommandEnum(Enum):
reset = 0
get_prop = 2
... |
from django.contrib import admin
from serial_configuration.models import SerialPort
class SerialPortAdmin(admin.ModelAdmin):
readonly_fields = ('device_file',)
fieldsets = [
('Serial Options', {'fields' : ['device_file', 'block_mode', 'lock_file', 'baud', 'raw_mode', 'echo_mode']}),
('TCP Loggi... |
#!/usr/bin/env python
import argparse
from ace import core
from ace import plugins
parser = argparse.ArgumentParser()
parser.add_argument('command')
parser.add_argument('subcommand',nargs='?',default='__default__')
parser.add_argument('--endpoint',dest='endpoint',default='https://www.axilent.net') # for debugging
c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.