text stringlengths 8 6.05M |
|---|
import re
###### Feature Production ######
def misc_features(sentence, index, features):
# Positioning, etc.
features["beginning_sent"] = (index == 0)
features["end_sent"] = (index == len(sentence) - 1)
def lexical_local(sentence, index, features):
# Returns dict, s.t. {feature_name: feature_value}
... |
## 프로그래머스 모의 고사 문제
# 수포자는 수학을 포기한 사람의 준말입니다.
# 수포자 삼인방은 모의고사에 수학 문제를 전부 찍으려 합니다. 수포자는 1번 문제부터 마지막 문제까지 다음과 같이 찍습니다.
# 1번 수포자가 찍는 방식: 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
# 2번 수포자가 찍는 방식: 2, 1, 2, 3, 2, 4, 2, 5, 2, 1, 2, 3, 2, 4, 2, 5, ...
# 3번 수포자가 찍는 방식: 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, ...
... |
import numpy as np
import pandas as pd
data = pd.read_csv('../data/computer-configuration.csv')
cores = data['cores']
frenquecy_per_core = data['frenquecy.per.core']
video_mem = data['video.mem']
ram = data['ram']
print 'Simple Mean Results'
print '* *'
print 'CORES -> {r}'.format(r=np.mean(cores... |
from pymongo import MongoClient
conn = MongoClient()
db = conn.foo
def confidenceFromPair(pair):
pairName = pair['_id']
pairOccurrences = pair['value']
items = pairName.split('+')
item1 = items[0]
firstTermOccurrences = db.single_counts.find_one({"_id":item1})['value']
return(pairOccurre... |
while 1:
print("Press Ctrl + C to stop")
|
import sys
from scipy.special import comb
from numpy import zeros
from math import log10
if __name__ == "__main__":
'''
Given: Two positive integers N and m, followed by an array A containing k integers between 0 and 2N. A[j] represents
the number of recessive alleles for the j-th factor in a population o... |
from django.apps import AppConfig
class TushuguanliConfig(AppConfig):
name = 'tushuguanli'
|
from setuptools import setup
from install import *
setup(
name="pyja",
version="0.1",
author="Jaime A. Pavlich-Mariscal",
author_email="jaime.pavlich@gmail.com",
packages=["pyja"],
install_requires=["jpype1",],
include_package_data=True,
license="MIT",
description="Analyze java code... |
#
# Серверное приложение для соединений
#
import asyncio
from asyncio import transports
from collections import deque
class ServerProtocol(asyncio.Protocol):
login: str = None
server: 'Server'
transport: transports.Transport
def __init__(self, server: 'Server'):
self.server = server
def ... |
import requests
#import json
from Get_code_Tools import get_code
from fake_useragent import UserAgent
def get_image():
code_url = 'http://www.yundama.com/index/captcha?'
image=s.get(code_url)
with open("code.jpg",'wb') as f:
#写入的不是response 必须是content
f.write(image.content)
code=get_co... |
import sys
import random
import pygame
from pygame.sprite import Group
from star import Star
def run_game():
# Initialize game and create a screen object.
pygame.init()
screen = pygame.display.set_mode((1024, 768))
pygame.display.set_caption("Stars")
star_image = pygame.image.load("star.png")
... |
"""
Breakout
Run from cmd line or main()
"""
from campy.gui.events.timer import pause
from breakoutgraphics import BreakoutGraphics
FRAME_RATE = 1000 / 120 # 120 frames per second.
NUM_LIVES = 3
def main():
graphics = BreakoutGraphics()
lives = NUM_LIVES
bricks = 100
while True:
if graphics.... |
import itertools
import logging
import re
from bs4 import BeautifulSoup, Comment
from furl import furl
from share.harvest import BaseHarvester
logger = logging.getLogger(__name__)
class SWHarvester(BaseHarvester):
"""
"""
VERSION = 1
def _do_fetch(self, start, end, list_url):
end_date = ... |
from onegov.core.security import Public
from onegov.org import _, OrgApp
from onegov.org.elements import Link
from onegov.org.layout import DefaultLayout
from onegov.org.models import AtoZ
@OrgApp.html(model=AtoZ, template='atoz.pt', permission=Public)
def atoz(self, request, layout=None):
layout = layout or Def... |
1# -*- coding: utf-8 -*-
"""
Created on Sat Jul 21 15:51:26 2018
@author: anilmenta
"""
import pyodbc
import pandas as pd
import glob
import re
import locale
import sys
import datetime
import shutil
import os
from datetime import datetime
server = 'SERVERRB\TIGERPOS'
database = 'POSDB'
username = 'TigerTest'
passwo... |
import pandas as pd
from math import log,exp
#epl = pd.read_csv("http://www.football-data.co.uk/mmz4281/1718/E0.csv")
epl = pd.read_csv("E0.csv")
epl = epl[['HomeTeam','AwayTeam','FTHG','FTAG']]
epl = epl.rename(columns={'FTHG': 'HomeGoals', 'FTAG': 'AwayGoals'})
teams = set(epl['HomeTeam'])
# Every team starts O = ... |
s = 1
a = int(input()) +1
for i in list(range(1, a)):
s = s*i
print(s)
s = str(s)
b = input()
f = open('факториал.txt', 'w')
f.write(s)
f.close()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import pickle
from PRW import ProjectedRobustWasserstein
from SRW import SubspaceRobustWasserstein
from Optimization.RiemannianBCD import RiemannianBlockCoordinateDescent
from Optimizat... |
#!/bin/python
import imaging
from snark.version import __version__ |
from pypoly import X
import numpy as np
def sust_adelante(A, b):
"""
Entrada: Una matriz A (cuadrada nxn) triangular inferior y un vector b nx1
Salida: x como la solucion de Ax = b, con metodo de sustitucion sucesiva hacia adelante
"""
n = len(A)
x = [0] * n
x[0] = b[0]/A[0][0]
for i i... |
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums:
return nums.index(target)
else:
for i in nums:
if i >= target:
retu... |
# -*- coding: utf-8 -*-
# @Author: Eliot Ayache
# @Date: 2020-01-14 08:01:05
# @Last Modified by: Eliot Ayache
# @Last Modified time: 2020-01-14 12:33:45
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
# Adding parent to Pythonpath
import matplotlib.pypl... |
"""
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
"""
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: ... |
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.urls import path
from planner.custom_decorators import access_private_garden, custom_login_required
from .views import *
app_name = 'planner'
urlpatterns = [
path('', index, name='index'),
# Authentications view... |
# # # # # # # # # # # # # # #
# Author: Mustafa Mert Tunalı
# ---------------------------
# ---------------------------
# Deep Learning Training GUI - Config Page
# ---------------------------
# ---------------------------
# # # # # # # # # # # # # # #
import numpy as np
# In Development For Object Detection
clas... |
#! /usr/bin/env python
from java.lang import Double
from math import fabs
centroids = []
@outputSchema("closestCentroid:double")
def get_closest_centroid(val, centroids_string):
if not centroids:
for centroid in centroids_string.split(":"):
centroids.append(float(centroid))
min_di... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 3 12:06:01 2018
@author: pasca
"""
import base64
from flask import Flask, render_template
from graphviz import Graph
import os
os.environ["PATH"] += os.pathsep + 'C:/ProgramData/Miniconda3/Library/bin/graphviz'
#%%
app = Flask(__name__)
@app.route('/')
def svgtes... |
# coding=UTF-8
def crc8(_bytes):
if not isinstance(_bytes, (bytes, bytearray)):
raise TypeError("object supporting the buffer API required")
crc = 0
for b in _bytes:
if b < 0:
b += 256
for i in range(8):
odd = ((b ^ crc) & 1) == 1
crc >>= 1
... |
#! /usr/bin/env python3
# Export smart playlists from "iTunes Music Library.xml" to text files
import os
import sys
# import json
import traceback
# import base64
import re
# Try to import from parent directory
include = os.path.relpath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, i... |
# Program to calculate sum of digits from 1 to n
# Returns sum of all digits from 1 to n
def sumOfDigitsFrom1ToN(n):
result = 0 # initialize result
# Calculate sum of digits 1 number at a time from number from 1 to n
for x in range(1, n+1):
result = result + sumOfDigits(x)
return result
... |
#Data Tinggi Badan Mahasiswa
A = int(input("Data tinggi badan mahasiswa 1 : "))
B = int(input("Data tinggi badan mahasiswa 2 : "))
C = int(input("Data tinggi badan mahasiswa 3 : "))
if A > B and A > C:
print("Data tinggi badan tertinggi adalah: ", A)
if B > A and B > C:
print("Data tinggi badan t... |
"""
Copyright Matt DeMartino (Stravajiaxen)
Licensed under MIT License -- do whatever you want with this, just don't sue me!
This code attempts to solve Project Euler (projecteuler.net)
Problem #12 Highly divisible triangular number
The sequence of triangle numbers is generated by adding the natural numbers.
So the ... |
from .truewho import main
main()
|
# # To Convert a camelCase form into a user-friendly field name.
# In[1]:
import pandas as pd
# In[18]:
def getter(text):
result=[]
pos=0
#checks if text starts with get and has alphabets only
if text.startswith('get') and text.isalpha():
#stores the text starting from the 4th character in va... |
from django.shortcuts import render
from .models import Etiqueta
from .tables import EtiquetaTable
def etiqueta_list(request):
etiqueta_table = EtiquetaTable(Etiqueta.objects.all())
return render(request, 'etiqueta_list.html', {'etiqueta_table': etiqueta_table})
|
free = True
node_id = '762'
node_password = '656531'
local_path = ''
code_done = False
|
import numpy as np
a = np.array([1,3])
b = np.array([3,0])
d = np.array([1,3,2])
e = np.array([3,0,2])
#perkalian dot dua dimensi atau 2 titik
c = np.dot(a,b)
print (c)
#perkalian dot tiga dimensi atau 3 titik
f = np.dot(d,e)
print(f) |
import pytest
from rv.api import Project, m
@pytest.fixture
def project():
return Project()
def test_initial_project(project):
assert isinstance(project.output, m.Output)
assert len(project.modules) == 1
assert project.modules[0] is project.output
assert len(project.patterns) == 0
assert pro... |
#!/usr/bin/env python3
import sys, os
import string
import subprocess
import copy
import glob
import datetime
import shutil
import logging
if sys.version_info.major < 3:
from xml.sax.saxutils import quoteattr as htmlEscaped
else:
from html import escape as htmlEscaped
import yaml
def get_logger(name=__name_... |
from web3 import Web3
w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545"))
for i in range(3, 11):
print(w3.eth.accounts[i])
|
# -*- coding: utf-8 -*-
"""
Created on Sat May 23 19:06:14 2015
@author: abhisheksen
"""
import numpy as np
import scipy as sc
import scipy.sparse as sp
import scipy.linalg as sl
import scipy.sparse.linalg as spl
"""
An implementation of Orthogonal rank-one matrix pursuit as appears in
http://arxiv.org/pdf/1404... |
from typing import List
from collections import defaultdict
class Solution:
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
map_count = defaultdict(int)
for i in arr:
map_count[i] += 1
a2 = sorted(map_count.values())
count = 0
for i in a2:
... |
import operator
import numpy as np
import torch
import os
from data import create_dataset
from models import networks
from models.base_model import BaseModel
from models_search.controller import Controller
from utils.inception_score import get_inception_score
from utils.utils import load_saves
class C... |
from openspending.logic import classifier
from openspending.logic import dimension
from openspending.logic import entry
from openspending.logic import flag |
import numpy as np
import scipy.special
from math import sqrt
###########################################
# FORECASTING OF THE DATA USING A MIXED KERNEL (Mixed Kernel = Periodic Kernel * SE Kernel + Linear Kernel)
#
# A. Implementation of different kernels
# B. Implementation of the covariance matrix
# C. Annexe... |
import tkinter as tk
def callback(ev):
print(ev.x, ev.y)
root = tk.Tk()
frame = tk.Frame(root, width=320, height=240)
frame.bind('<Motion>', callback)
frame.pack()
root.mainloop()
|
import numpy as np
import matplotlib #redundant with Jupyter
#matplotlib.use("Agg")
import matplotlib.pyplot as plt #will not be in the exam
import numpy as np
import scipy.stats as ss
#Black and Scholes
def d1(S0, K, r, sigma, T):
return (np.log(S0/K) + (r + sigma**2 / 2) * T)/(sigma * np.sqrt(T))
def d2(S0,... |
from odoo.tests import tagged, TransactionCase
from ..lib.format import format_name
@tagged("first_last_name")
class TestUsers(TransactionCase):
def setUp(self):
super(TestUsers, self).setUp()
self.first = "1"
self.last = "2"
self.user = self.env['res.users'].create({
... |
import unittest
from wingedsheep.carcassonne.carcassonne_game_state import CarcassonneGameState
from wingedsheep.carcassonne.objects.coordinate import Coordinate
from wingedsheep.carcassonne.objects.coordinate_with_side import CoordinateWithSide
from wingedsheep.carcassonne.objects.road import Road
from wingedsheep.ca... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-06-21 16:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lists', '0002_item_text'),
]
operations = [
migrations.CreateModel(
... |
########################################################################################
########################################################################################
##
## DATA PRE PROCESSING TECHNIQUES
##
########################################################################################
#############... |
import mne
import numpy as np
import scipy.signal as signal
from numpy import concatenate, ndarray
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import StandardScaler
class LogVariance(BaseEstimator, TransformerMixin):
"""LogVariance transformer."""
def fit(self, X, y):
... |
from django.shortcuts import render, redirect
from django.contrib import messages
from django.views import generic
import json
from ast import literal_eval
import base64
import xml.etree.cElementTree as et
# from data_load.services import get_photos_by_group_id, download_images, create_table, insert_into_db
f... |
from django.urls import path
from .views import *
urlpatterns = [
path('', PostList.as_view(), name='blog_post_list'),
path('<year>/<month>/<slug>/')
] |
# def stream(self):
# print("Starting streaming")
# self.frame.ser.write(b"AS|")
# eof = False
# d = self.frame.ser.read(2)
# #while(self.frame.ser.in_waiting > 0 and not str(d) == b''):
# d = self.frame.ser.read(2)
# val = int.from_bytes(d,"little",signed=True)
# print("Data... |
import torch
import os
import math
from Posit import posit
def param2posit(input_data, dsize, posit_type="p8_1", is_matrix=True):
output_str = ""
if posit_type == "p4_0":
tmp = posit.PositN4E0()
elif posit_type == "p8_0":
tmp = posit.PositN8E0()
elif posit_type == "p8_2":
tmp ... |
from django.conf.urls import patterns, include, url
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib import admin
from django.views.decorators.csrf import csrf_exempt
import www.views as www
import ipam.views as ipam
import reports.views as reports
import reports.accid... |
import cv2,matplotlib
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import tifffile
import sklearn
from sklearn.cluster import KMeans
def main():
size = 600
slide_size = int(size * 0.8)
count = 0
v_count = 1
h_count = 1
img_default = tifffile.imread("../../Desktop/O... |
import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, optimizers, datasets
'''
base_loging 屏蔽信息 输出信息
“0” INFO 无 INFO + WARNING + ERROR + FATAL
“1” WARNING INFO WARNING + ERROR + FATAL
“2” ERROR INFO + WARNING ERROR + F... |
import threading
import argparse
import json
from time import sleep
from datetime import datetime
import logzero
from logzero import logger
from twisted.internet import reactor, task
from neoNode import neoBlockchain
logzero.logfile("/var/log/neo/neo-contract-event.log", maxBytes=1e6, backupCount=3)
contract_sh = '5... |
#oef3
jaar = int(input("Geef je geboortejaar op: "))
import datetime
leeftijd = datetime.datetime.now().year - jaar
if (leeftijd >= 18):
print("U bent nu {} jaar oud, en oud genoeg.".format(leeftijd))
else:
print("U bent nnu {} jaar oud, en nog niet oud genoeg.".format(leeftijd)) |
from oxicord.oxicord import * |
#reduce是累积函数,lambda是匿名函数
from functools import reduce
n=5
result=reduce(lambda x,y:x*y,range(1,n+1))
print(result)
def add(x,y):
return x+y
result_add=reduce(add,[1,2,3,4,5])
result_add_lambda=reduce(lambda x,y:x+y,[1,2,3,4,5])
print(result_add)
print(result_add_lambda) |
#!/usr/bin/env python3
"""
Copyright 2019 INESC TEC
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... |
#!usr/bin/env python
from Queue import PriorityQueue
class State(object):
def __init__(self, value, parent, start=0, goal=0):
self.children = []
self.parent = parent
self.value = value
self.dist = 0
if parent:
self.path = parent.path[:]
self.path.ap... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os,sys
def parse_and_apply(algo):
try:
infile,outfile = algo.split()
print algo
print infile
print outfile
main(infile, outfile)
except Exception, e: raise e
def parse_options_and_apply(directori, options):
infil... |
#!/usr/bin/python2.7
__module_name__ = "trap.py"
__module_version__ = "2.2"
__module_description__ = "Channel Trap Plugin"
__module_author__ = "Ferus"
import xchat
from random import randint
server = 'DatNode'
channel = '#ItsATrap'
def isChan():
if (xchat.get_context()).get_info("network") == server:
if(xchat.get... |
primeNum = 1000000
primeCheck = [True] * primeNum
primes = []
def sieveAlg(x):
for y in range(2*x,primeNum,x):
primeCheck[y] = False
for y in range(2,int(primeNum**0.5)+1):
if primeCheck[y]:
sieveAlg(y)
for x in range(2,primeNum):
if primeCheck[x]:
primes.append(x)
###############... |
#_*_coding:utf-8_*_
from django.db import models
from apps.kx.models import KxUser
from rest_framework import serializers
# Create your models here.
class UserShortSerializer(serializers.ModelSerializer):
class Meta:
model = KxUser
fields = ('id', 'email', 'nick', 'avatar', 'status', 'login_statu... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import HtmlResponse
from hh.items import HhItem
from scrapy.loader import ItemLoader
class HhSpider(scrapy.Spider):
name = 'hhspider'
allowed_domains = ['perm.hh.ru']
start_urls = [
'https://perm.hh.ru/search/vacancy?clusters=true&enable_snipp... |
#Ejercicio 03
def twosum(array):
for i in range(len(array)):
for j in range(len(array)):
if i!=j and array[i] + array[j] == 10:
return True
return False
print(twosum([1,2,3,4,5,6]))
|
#!/usr/bin/env python
print(" Hello World! This is a test script.")
|
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict
np.set_printoptions(precision=3, suppress=True)
"""
Code adapted from Aman Ahuja (https://github.com/amanahuja/change-detection-tutorial/)
"""
def dict_to_arrays(ddict):
"""
Convenience function u... |
import cv2
img=cv2.imread("C:\\Users\\agup0013\\Desktop\\pp.jpg")
print("matrix of image", type(img))
print("type of image", type(img))
print("shape of image", img.shape)
resize = cv2.resize(img, (int(img.shape[1]/2),int(img.shape[0]/2)))
cv2.imshow("Legend", resize)
#cv2.imshow("Legend", img)
cv2.waitKey(0... |
#!/usr/bin/python3
""" Provides a class to represent squares
"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
""" Definition of fixed-size square
"""
def __init__(self, size):
""" Instantiate a square
"""
try:
super().__init__(size, size)
... |
# -*- coding:utf-8 -*-.
from django.db import models
# Create your models here.
class PaintAccount(models.Model):
account_name = models.CharField(max_length=64,unique=True,blank=True,verbose_name=u'账号')
customer_id = models.IntegerField(default=0,verbose_name=u'来源订单号')
password = models.CharField(max_len... |
import hashlib
import json
import mmap
import os
import random
from bitarray import bitarray
class TorrentFile(object):
def __init__(self, json_file):
self.json_path = json_file # JSON file at the same execution director
json_str = self.read(json_file) # Read raw text
self.obj = json.l... |
import datetime
from datetime import timedelta
from freezegun import freeze_time
from onegov.agency.collections import ExtendedAgencyCollection
from onegov.agency.collections import ExtendedPersonCollection
from onegov.agency.collections import PaginatedAgencyCollection
from onegov.agency.collections import PaginatedM... |
#coding=utf-8
dict={}
a=[]
b=[]
while True:
x=input('输入键名:')
y=input('输入键值:')
if x==0 and y==0:
break
dict[x]=y
a.append(x)
b.append(y)
print '字典为:',dict
print '键名为:',a
print '键值为:',b
|
#!/usr/bin/env python3
import json, time, sys, base64, os
from TanCD import tanrest
from pprint import pprint as pp
from time import sleep
import getpass
import getopt
import subprocess
def usage():
print("""
Usage:
tanium_put.py [options]
Description:
Uploads test package to the Tan... |
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from torch.utils import data
import torch.utils.model_zoo as model_zoo
from torchvision import models
class GC(nn.Module):
def __init__(self, inplanes, planes, kh=7, kw=7):
su... |
from enum import Enum
# Clase con la configuración del juego
class GameConfig:
def __init__(self):
"""
Init function
Set variables to privates to use getters and setters.
"""
# La matriz del juego
self.__matrix = []
# El modo del juego, por defecto en alfabé... |
from numpy import *
import matplotlib.pyplot as plt
D = genfromtxt("datos_placas.txt", delimiter=',')
II = ~any(isnan(D),0)
D = D[:,II] # Quitar Nans
print(shape(D))
n = int(size(D,0)/3)
II,JJ = meshgrid(linspace(0,n,n),linspace(0,n,n))
f = plt.figure()
plt.contourf(II,JJ,D[:n,:], 20)
plt.colorbar()
plt.streamplot(... |
# A script to implement a module of creating the classifier. The methods include getting all the files from the directory,
# and finding the word count for all the words in all the files in that directory.
import os
import nltk
# A function to get the files in a directory and store it in a list which is returned.
# @... |
[counter1, counter2, nm_list] = [0, 1, []]
limit = int(input('Enter the limit of spiral: '))
while counter1 < limit:
nm_list.append([])
counter1 += 1
for i in nm_list:
for j in range(1, limit +1 ):
i.append(0)
number_limit = limit**2, len_list = len(nm_list)
# while counter2 <= number_limit:
# ... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import logging
from block_zoo.BaseLayer import BaseConf
from utils.DocInherit import DocInherit
from ... |
# Client
import socket # for building TCP conneciton
import subprocess # to start the shell in the system
import os # needed for file operations
import ctypes # to edit file attributes (make file hidden)
import shutil # needed for file copying
from _winreg import * # needed for editing registry
import time
... |
import GetOldTweets3 as got
import re
import datetime
import json
# global variable declarations
username = 'DailyMLBLineup' # twitter account username
positions = ['1B', '2B', '3B', 'SS', 'LF', 'CF', 'RF', 'DH']
# download recent tweets
def getTweets(date):
global user_tweets
month, day, year = date.split('... |
import pygame
import random
from project.constants import ECRAN
#(self.rect.left, self.rect.top)
class Boss(pygame.sprite.Sprite):
vitesse = 1
vie = 7
animcycle = 12
images = []
direction = 2
def __init__(self):
pygame.sprite.Sprite.__init__(self, self.containers)
self.rect = ... |
#import sys
#input = sys.stdin.readline
from collections import defaultdict
def main():
N = int(input())
S = [ input() for _ in range(N)]
d = defaultdict(lambda : False)
for s in S:
d[s] = True
for s in S:
if s[0] != "!":
if d["!"+s]:
print(s)
... |
#!/bin/python
import sys
import copy
import re
def parseInput():
infile = open(sys.argv[1], "r")
directions = []
for l in infile:
dirs = []
holder = None
for c in l:
if holder == None and (c == 'e' or c == 'w'):
dirs.append(c)
else:
... |
"""Stuff
** WIP **
"""
import os
import sys
import fbx
from brenfbx.fbxsdk.scene.constraint import bfConstraint
from brenpy.qt.bpQtImportUtils import QtCore
from brenpy.qt.bpQtImportUtils import QtWidgets
from brenpy.qt.bpQtImportUtils import QtGui
from brenfbx.core import bfCore
from brenfbx.core import bfIO
fr... |
NOTIFIES = {
'any': '.humane-jackedup',
'red': '.humane-jackedup-error',
'blue': '.humane-jackedup-info',
}
|
"""
This is a simple application for sentence embeddings: semantic search
We have a corpus with various sentences. Then, for a given query sentence,
we want to find the most similar sentence in this corpus.
This script outputs for various queries the top 5 most similar sentences in the corpus.
"""
# -*- coding: utf-... |
import re
import os
import sys
from _release_tools import (up_to_date,
create_size_dictionary,
extract_dot_git,
release)
from _exception_classes import ReleaseError
if __name__ == '__main__':
# Ensure that the d... |
# 259. 3Sum Smaller
#
# Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n
#
# that satisfy the condition nums[i] + nums[j] + nums[k] < target.
#
# For example, given nums = [-2, 0, 1, 3], and target = 2.
#
# Return 2. Because there are two triplets wh... |
""""
Graph search implemented to find mutual movie actors.
This project will help us to understand how graph search works. Movie is an edge and actor is node
@author: Segni Habulu
"""
from Graph import Graph, Edge
from Queue import Queue as Queue
from Node import Node
import time
# we will use the following list to... |
import sys
def max(a,b):
return a if (a > b) else b
def cutRod(price,n):
if (n <= 0):
return 0
max_val = -sys.maxsize - 1
for i in range(0,n):
max_val = max(max_val,price[i] + cutRod(price,n-i-1))
return max_val
arr = [1,5,8,9,10,17,17,20]
size = len(arr)
print('Maximum Obtainabl... |
#!/usr/bin/python
#library imports
import serial, sys, time, MySQLdb
NUMBEROFLINESTOREAD = 10 #Number of lines on the serial line
count = 0 #counter
serial_data = [[None]] * NUMBEROFLINESTOREAD # store the received data here
# here we read custom data from the serial port
def readlineCR(port):
count_line = 0 #coun... |
import sys
import os
import dlib
import glob
import cv2 #opencv 사용
import pandas as pd
import numpy as np
import copy
from scipy.interpolate import interp1d
def swapRGB2BGR(rgb):
r, g, b = cv2.split(img)
bgr = cv2.merge([b,g,r])
return bgr
total = []
predictor_path = sys.argv[1] #얼굴 특징점 모델 파일 지정
faces_fol... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.