index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
986,100 | 4c8f9c3c68e17f0d362349ffce53e1ce2c3502bd | import requests
import secrets
base_url = 'https://newsapi.org/v2/top-headlines'
params = {
"apiKey": secrets.NEWSAPI_KEY,
"country": "us",
"q": "new hampshire"
}
response = requests.get(base_url, params)
result = response.json()
#print(result)
#print(result['articles'])
for article in result['articles'... |
986,101 | ccf897450b3a69387a40ab3f9923e5335a5f94eb | def sieve_flavius(min_n, max_n) -> set:
"""
Return set with lucky numbers.
"""
pointer = 1
lst = list(range(1, max_n + 1, 2))
while pointer < len(lst):
new_lst = []
num = lst[pointer]
for i in range(len(lst)):
if (i + 1) % num != 0:
new_lst.app... |
986,102 | 2bb4195d434dd14ac1f501325f655e52c8f7a413 | '''
==============
3D quiver plot
==============
Demonstrates plotting directional arrows at points on a 3d meshgrid.
'''
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
import numpy as np
fig = p... |
986,103 | 375af454734cba9450428d84a303f559b87b8c50 | from PyQt5 import QtCore
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from PyQt5.QtWidgets import *
import sys
import math
import threading
import time
from server import Server
class Updates(QThread):
is_active = False
_signal = pyqtSignal(str)
_msg_queue = []
def __init__(self):
super(Up... |
986,104 | 2cd8d6a508aea75427a6e317f32b76c5ebb5b12e | # Generated by Django 3.1 on 2020-12-07 00:34
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
opera... |
986,105 | cf7665a9328afbd06c8ffec3ebe7ca4f4622e32b | from __future__ import annotations
from typing import Generic, TypeVar
_T = TypeVar('_T')
__all__ = ('Result',)
class Result(Generic[_T]):
"""
A class to encapsulate the result of an operation
This is useful for operations which can either return a value
or an error message.
Args:
ok:... |
986,106 | 3da660c5130b2a32457e0a16fe78294d5e28ccc5 | import postgresql
db = postgresql.open("pq://postgres:123456@localhost/rc3")
consultar = db.prepare("SELECT * from cep")
dados = consultar()
for row in dados:
print("CEP: {} MUNICIPIO: {}".format(row["cep"], row["municipio"])) |
986,107 | ec1b77901e40d8d7b90e0c2a4da0857fdb5e3025 | def catchpa(input):
stringInput = str(input)
stringLength = len(stringInput)
total = 0
halfwayRound = stringLength / 2
for x in range(stringLength):
# check the number halfway around
if x + halfwayRound > stringLength - 1:
if stringInput[x] == stringInput[x - halfwayRoun... |
986,108 | 0b31d6a4efd7287b7ae5147e348f5dc6170551ec | # %% Defines functions needed for the rest of the program
import matplotlib.pylab as plt
import numpy as np
import scipy
#import seaborn as sns #uncomment these for nicer plots
#sns.set('talk')
#Get Hartree potential from electron density
def getVH(ns,N,Rmax):
h = Rmax/N
A = np.diag(-2*np.ones(N),0)+... |
986,109 | 401fb2a79c5924994551f6a718782dfa7ac44c66 | numeropositivo = -1
potencia = -1
while (numeropositivo <= 0 or potencia <= 0):
numeropositivo = int(input("Digite una base: "))
potencia = int(input("Digite una potencia: "))
if(numeropositivo <= 0 or potencia <= 0):
print ("Error. solo numeros positivos")
acumulador = numeropositivo
while (pot... |
986,110 | 171bf28c36f1d241e9d1d7a196080539b90aa4eb | from django.db import models
from django.forms import ModelForm
from django.contrib.auth.hashers import make_password
import datetime
# Create your models here.
class UserEntity(models.Model):
entity_type_id = models.IntegerField(max_length=2, default='0')
group_id = models.IntegerField(max_length=2, default='0')
... |
986,111 | 43feabb3520bcbee81a1293ed9807c2038f43750 | import dash
import dash_bootstrap_components as dbc
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output,State
from app import app
from app import server
from apps import stock_forecasting,world_gdp_analysis,home,tweet_analysis,topic_modeling
app.layout ... |
986,112 | ff8b3cdc92449cf3a1913c83667f4f3aa472b630 | # Generated by Django 3.1.3 on 2020-11-20 15:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('results_app', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='results',
name='link',
... |
986,113 | f68a30fb549c95a1492d70c52ea66909bfac9057 | # consider a problem that online game designers and internet radio providers face:
# This is important in gaming because every players can communicate and listeners can tuned in and getting all the data
# It is a typical boardcast problem
# 1. the boardcast host has some information that the listeners all need to reci... |
986,114 | cc5d404284687ae931868341da3a266027667285 | import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
class SI:
"""
Only consider susceptibles and infectives.
Infectives can't recover.
"""
def __init__(self,
N: int,
r: int,
beta: float,
I0: in... |
986,115 | 6e03f793e2c26189e2231deb0264c2428b7bfe04 | from numpy import *
from scipy.optimize import minimize
from random import random
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.pyplot import *
'''
O SQP é um modela um problema de otimização não linear para uma dada iteração x_k, em um
subproblema de Programação Quadrática (QP), uma vez resolvido esta instâ... |
986,116 | 4eebd7d87d4773b136f09d993396fca1889c5f48 | import numpy as np
import matplotlib.pyplot as plt
import biorbd_casadi as biorbd
from bioptim import OdeSolver, CostType, Solver, PlotType, SolutionIntegrator, Shooting
from transcriptions import HumanoidOCP, Models
def main():
n_shooting = 30
# ode_solver = OdeSolver.RK4(n_integration_steps=5)
# ode_s... |
986,117 | 1fbdc52c71560c1eaeccddcbf7caf752567625e5 | # days = int(input("How many days:"))
# years = days // 365
# weeks = (days % 365) // 7
# days = days - ((years * 365) + (weeks * 7))
# print("Years:", years)
# print("Weeks:", weeks)
# print("Days:", days)
user_input = input()
number = int(user_input)
binary = bin(number)
print(binary) |
986,118 | 9dd50a9ed058363baa58fb0f35670cf2628c6479 | from urllib import request
from bs4 import BeautifulSoup
import os
def main():
dic=load_in().split("\n")
print("Display all words")
display(dic)
ans=merriam_webster(dic)
print("Display definitions")
display(ans)
write_in(ans)
def load_in():
try:
f = open('./txt/input.txt', 'r')
dic=f.read()
f.close()
r... |
986,119 | 92ef595636fc08ab2da87744dfc249e6c97a3171 | # -*- coding: utf-8 -*-
import time
import scrapy
from copy import deepcopy
import json
import re
import requests
from requests.adapters import HTTPAdapter
from .s3_upload import UploatS3
from urllib.parse import urlparse
from selenium.webdriver import Chrome
s = requests.Session()
s.mount('http://', HTTPAdapter(max_... |
986,120 | 62a8c18039dc787519dd4d5a772dfa81abe7a324 | from rest_framework.views import APIView, Response
from myapp.models import User, File, UserBrowseFile, UserKeptFile, Team, TeamMember
from myapp.views import chk_token
from myapp.serializers import TeamMemberSer, TeamSer
class CreateTeam(APIView):
def post(self, request):
token = request.META.get('HTTP_T... |
986,121 | 3f9d3f46bbb47439615b89e1dc0e2bcf44a074c4 | from .models import *
import random
from django.shortcuts import get_object_or_404
from django.http import Http404
from itertools import chain
from django.contrib.auth import get_user_model
import numpy as np
def get_probes(outline_with_rubrics, assign, strategy='random'):
subs = assign.assign_submissions.all()
... |
986,122 | ec3a382e2bba261bec4b90d7eb0a5beb42517a8e | import os
import secrets
from conf.settings import BASE_DIR
WORKING_DIR = os.path.join(BASE_DIR, 'temp_files')
def random_str():
return secrets.token_hex(nbytes=16)
def get_random_name(extension):
return os.path.join(WORKING_DIR, '{}.{}'.format(random_str(), extension))
|
986,123 | 8ac31755e29f27a216333fb3005b67e117c9b82e | from data_structure import TreeNode, build_binary_tree, ds_print
class Solution:
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
def flatten_append(node, append_node):
if node is None:
... |
986,124 | 1ac35417b642bcd55580447ee8ad3c639b97b8b2 | from PySide2.QtCore import QObject, Signal
from sos.core.database_manager import DatabaseManager
class DatabaseModel(QObject, DatabaseManager):
modelUpdated = Signal()
def __init__(self):
QObject.__init__(self)
DatabaseManager.__init__(self)
def notify_admin(self):
self.modelUp... |
986,125 | 25e2dacc6b6afabcef447b17c3f5c2ff24dae914 |
class LoanParameter(object):
registry = {}
def __init__(self, name):
self.name = name
self.totals_loan = 0
self.count = 1
@classmethod
def create_item(cls, x):
try:
return cls.registry[x]
except KeyError:
new_item = cls(x)
cls.registry[x] = new_item
... |
986,126 | 4c14a10ee7c7c4faea1e6e2608f512ff52a064b8 | #!/usr/bin/env python3
import config
config.Daemon().run()
|
986,127 | c6de61af0880ca6dbea614d2a9a29a762e6a639e | # Generated by Django 2.1.3 on 2018-12-04 07:05
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Blog', '0001_initial'),
]
operations = [
migrations.RenameModel(
old_name='Blog',
new_name='BlogModel',
),
m... |
986,128 | 51b684f69b0c6f4da64fde9f8fc587bbdc3a65a1 | #!/usr/bin/env python
import sys
import time
import getopt
import socket
import threading
import numpy as np
from pyMonster import Client
def usage():
print """
Usage: ./run_client_monster.py [options]
Options:
-h, --help show this help message and exit
-a, --address host IP address (def... |
986,129 | 9eda6dbde478c58ac20fb4831e84784e5600b481 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
**testsQWidgetComponent.py**
**Platform:**
Windows, Linux, Mac Os X.
**Description:**
This module defines units tests for :mod:`manager.qwidgetComponent` module.
**Others:**
"""
#***********************************************************************************... |
986,130 | 13ec7a492b1b9c900a6d2662ae49cd578d44dc21 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from types import *
import pygame
import os
import cPickle
import random
import gzip
from MAP import mapgen, mazegen, generalmap
from UTIL import queue, const, colors, eztext, load_image, misc
from IMG import images
displayOpts = ['fore', 'back', 'both']
# Eztext cou... |
986,131 | 803a88f791f56e99c0f79d4bfde827304cc5f5f5 | import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from eralchemy import render_er
Base = declarative_base()
fav_characters = Table('user_people', Ba... |
986,132 | 47f2bef63b1a952feffeabfe7fad38a1bef4885a | """
|**********************************************************************;
* Project : VYPcode compiler 2019
* Authors : Michal Horky (xhorky23), Matus Mucka (xmucka03)
|**********************************************************************;
"""
from tests.testBase import TestBaseCases
class Ba... |
986,133 | 2e530849050a210c5857bc2ad264cd9323533513 | from click import echo, style
from json_database.database_api import DatabaseAPI
from json_database.recognizer.DatabaseListener import DatabaseListener
from json_database.recognizer.DatabaseParser import DatabaseParser
def value_converter(value):
try:
return int(value)
except ValueError:
try:... |
986,134 | b4525fbf70100111b7d2a9b3d6ba28c883985d74 | ########################################################################################################################
# @author Oriol Aranda (https://github.com/oriolaranda/)
# @date Oct 2021
########################################################################################################################
imp... |
986,135 | 1e5b1ceb407181ac8907752e38ffbe099d7307b1 | ######################################################
### Setting additional software licenses and paths ###
######################################################
############################
## Gurobi Solver Software ##
############################
# Once Gurobi is installed, license path can be retrieved
# by ente... |
986,136 | 793129d38b549a390c4c7f4860cbb53eb0f99a36 | class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
for c in tokens:
if c not in ["+", "-", "*", "/"]:#c.lstrip('+-').isdigit():
stack.append(int(c))
else:
... |
986,137 | 822f1702e3995f88d38c42330928460c0c0dd4c8 | import glob
from os import path
import wave
from m3u8 import M3U8
from src.utils import eprint
CONCAT_WAV = "concat.wav"
def create_combined_wav(folder_path: str, wav_file_path: str) -> wave.Wave_write:
sample: wave.Wave_read = wave.open(wav_file_path, 'rb')
concat_wav: wave.Wave_write = wave.open(path.joi... |
986,138 | a1132ab22c14ed343349d26f24dcbfac09daf3b0 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
from turbomail.control import interface
from turbomail import Message
from_ = (('Asset Summary', 'Asset.Summary@cn.flextronics.com'))
debug_list = ['Colin.Qi', 'Sucre.Su']
email_config = {'mail.on': True,
'mail.transport': "smtp",
'mail.smtp... |
986,139 | 86bc865ca7d52fc61e01688d82fab3da12f8590f | import hmac
import hashlib
import base64
import json
from typing import Optional
from fastapi import FastAPI, Cookie, Body
from fastapi.responses import Response
from fake_db import USERS
from fake_settings import SECRET_KEY, PASSWORD_SALT
app = FastAPI()
secret_key = SECRET_KEY
pswd_salt = PASSWORD_SALT
users = USER... |
986,140 | 67a4ea54cd5e6c930cc53b79b3174bc5919dbd9b | square =[]
for i in range(1, 11):
square.append(i**2)
print(square)
fav_numbers = {'eric': 17, 'ever': 4}
for name, number in fav_numbers.items():
print(name + ' loves ' + str(number)) |
986,141 | 7db8faa9f7f7a4bfcc6449b9fcbd92545949cbe4 | import hashlib
import time
def createHash():
for i in range(10000000):
md5 = hashlib.md5()
md5.update(str(i).encode('utf-8'))
yield (md5.hexdigest(),i)
def checkHash(hash,cHash):
if(hash==cHash[0]):
print("找到密码:",cHash[1])
return 1
else:
return 0
def main():
hash=input("请输入要破解的md5密文\n")
md5s = hashl... |
986,142 | d3efbbcbbcd1757d214f9917fe2b7394e457928b | #Extremely simple text adventure
#by me :)
#Sorry coause it's in spanish, hope you get what the code is about
import time
import sys
import cmd
pagina0 = ['Te despierta un rayo de luz proveniendo de la entrada a la cueva.', 'derecha', 'izquierda', 'pagina1', 'pagina2']
pagina1 = ['moriste','Oyes un sonido ex... |
986,143 | d6f3179bcccdc1b9f9f80453f06f7d240221b0be | import os
def createdb(name):
try:
if not os.path.isdir('database/' + name):
os.mkdir("database/" + name)
return True
else:
return "DB already exist"
except OSError:
return "Os error except while create " + name + " db"
def getfrdb(name):... |
986,144 | 8522870e2b5ab31ac5976d5892d5cf0251d3e2d2 | #!python
import os, sys, string, time, BaseHTTPServer, getopt, re, subprocess, webbrowser
from datetime import date
from datetime import time
from datetime import datetime
from operator import itemgetter
import multiprocessing
import hashlib
shellv = os.environ["SHELL"]
_BINARY_DIST = False
def resource_path(relative_... |
986,145 | 116e9973aaf03e09104f6308d754fc9ccea6f497 | import numpy as np
import nibabel as nib
from pathlib import Path
from collections import namedtuple
from utils.dataset_structuring import acdc, general
import constants
Info = namedtuple('Info', ['affine', 'header'])
def get_train_val_paths(dataset_name, k_split):
"""
This function splits the samples from ... |
986,146 | 6d24e55d11a7a734568fc1a934e028a27d5852d1 | def comb(k, start):
global card_comb
if k == 3:
card_comb.append(choose.copy())
return
for i in range(start, len(cards)):
choose.append(cards[i])
comb(k + 1, i + 1)
choose.pop()
n, m = map(int, input().split())
cards = list(map(int, input().split()))
card_comb = ... |
986,147 | c05e1c3142d99e92478cbb30ae97b403677aa9f0 | # pyspark --executor-memory 3g --num-executors 12 --packages com.databricks:spark-avro_2.11:4.0.0
from pyspark import SparkContext
from pyspark.python.pyspark.shell import spark
from pyspark.sql import SQLContext
sc = SparkContext(appName="Parquet2Avro")
sqlContext = SQLContext(sc)
# sqlContext.setConf('spark.drive... |
986,148 | 1a5106db9557b40616bc75d268df4bdaed23faf1 | from django import forms
from users.models import Profile
class RegisterForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('first_name', 'last_name', 'bio',)
widgets = {
'first_name': forms.TextInput(attrs={'placeHolder':'First Name'}),
'last_name': forms... |
986,149 | 6db4ffc5e2938c438ae8aff486db3e5eeeba8495 | '''
cachenone.py
'''
import heapq
import numpy as np
from scipy.stats import entropy
from sklearn.ensemble import RandomForestClassifier
import helper
class CacheNone:
def __init__(self):
# pairs assigned to this node
self.pairs = None # list of (ltable_id, rtable_id)
self.features... |
986,150 | c9787a6254b47238c59f177ffc57b0087000b410 | import datetime
import json
from decimal import Decimal
import pendulum
def json_dumps(obj):
def to_json(python_object):
if isinstance(python_object, (pendulum.Pendulum, datetime.datetime)):
return python_object.timestamp()
if isinstance(python_object, Decimal):
return flo... |
986,151 | aae63355b5efae5c1cb53bd45c98bf39f7a22f75 | from pigeon.channels import Channel
from pigeon.utils import json_dumps, json_loads
class InvalidActionError(Exception):
pass
class Action(object):
type_mapper = {
'subscribe': 'on_subscribe',
'unsubscribe': 'on_unsubscribe',
}
def __init__(self, action_type, channel):
self... |
986,152 | 47e4cb0eb544ee98663ebccc1d2382c60c095e69 | # pylint: disable=missing-docstring
from dpgv4 import create_screenshot, create_thumbnail
from .util import sample_filename
def test_screenshot() -> None:
input_file = sample_filename("Test Image - 2141.mp4")
expected_output_file = sample_filename("Test Image - 2141.screenshot")
with open(input_file, "rb"... |
986,153 | 16ffa7e540b2a45213341d912cfecb8d1a3b2bae | import time
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import We... |
986,154 | fddcbcd9c19926856b326190da4570d4dc553af0 | """ Close to possible approach """
# _end_ = '_end_'
#
#
# class Solution(object):
# # @param A : string
# # @param B : list of strings
# # @return an integer
# def wordBreak(self, A, B):
# if len(A) == 0:
# return 0
# if len(B) == 0:
# return 0
# trie = ... |
986,155 | e240380dda3b30c4632258e4b4eb8a5dc4c14360 | from cumulusci.core.exceptions import CumulusCIException
class GithubIssuesError(CumulusCIException):
pass
class LastReleaseTagNotFoundError(CumulusCIException):
pass
|
986,156 | ff55c33641148fc01c096f4fa60e9b76ac6f4047 | import numpy as np
from scipy.signal import gaussian
def add_distortions(spectra: np.ndarray, level: float = 0.1, seed: int = 42) -> np.ndarray:
"""
Adds random distortions with max height of "level" to the set of spectra.
:param spectra: (N, M) array, M-1 spectra with N wavenumbers, wavenumbers in first ... |
986,157 | c0832b4f081c43cc37b6cf3332f666eb4ad8f9db | # -*- coding: utf-8 -*-
from sage.all import shuffle, randint, ceil, next_prime, log, cputime, mean, variance, set_random_seed, sqrt
from copy import copy
from sage.all import GF, ZZ
from sage.all import random_matrix, random_vector, vector, matrix, identity_matrix
from sage.stats.distributions.discrete_gaussian_integ... |
986,158 | 91cf833cf2d5ef32ee0b43f8f2a542c41849defe | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import dados_comuns as dados
import statistics
ROOT_PATH = '/Users/regisalbuquerque/Documents/drive/regis/mestrado/resultados/comp_v12_LB_DDM_DDD__allbases/'
TAM = 30
bases = dados.bases_sinteticas
#Adiciona os métodos (DESDD + baselines)
meto... |
986,159 | 038963cf323efeb842975098e63d94932e6fe15e | from django.forms import ModelForm, TextInput, CharField
from .models import City
class CityForm(ModelForm):
#name = CharField(max_length=25)
class Meta:
model = City
fields = ['name']
widgets = {'name': TextInput(attrs={'class':'input', 'placeholder':'City Name'})} |
986,160 | 27194ec08fb723048b28067d272337320a76f801 | def resolve():
a,b=input().split()
if a==b:
print('H')
else:
print('D')
resolve() |
986,161 | ad94dbd61f67c8874a88cf3055cffc1574c85294 | from player import HumanPlayer, AutoPilot, StillLearning
from prompts import full_turn
from random import shuffle, choice
import jsonlog
p1 = HumanPlayer("Player 1")
p2 = AutoPilot("Player 2")
p1.opponent = p2
p2.opponent = p1
players = (p1, p2)
jsonlog.initiate_game(players, 1)
for player in players:
shuffle(pl... |
986,162 | 369c2ea37f9cad2c22ee70b57600d08e5c6139df | import pandas as pd
import os
def obtain_txt_train_images_file(csv_file_path, txt_path, files_path):
if not os.path.isfile(csv_file_path):
print('.csv file does not exists.')
return
print('Creating annotations in txt format.. \n')
print('Reading csv file...')
train = pd.read_csv(csv_f... |
986,163 | 8e55700f8d59271d63f2e7fa1eadc1872d2c13f7 | from time import sleep
from time import time
import numpy as np
import time, random, threading, sys
import multiprocessing
from Worker import *
import Constants
import os
tf.reset_default_graph()
if len(sys.argv) > 1:
Constants.MODE = int(sys.argv[1])
Constants.EMBED_METHOD = int(sys.argv[2])
Constants.LAYERS = in... |
986,164 | 6ef72d5b365d931bd71ce6e666f424310bbca9b2 |
# Import Splinter and BeautifulSoup
from splinter import Browser
from bs4 import BeautifulSoup as soup
from webdriver_manager.chrome import ChromeDriverManager
import pandas as pd
import datetime as dt
# Defining scrape all function to connect to mongo and establish communication between our code and db
# Set up Spli... |
986,165 | 4c3cef5cc030cd9d5f7c0ac23e10d7a8f5f15c27 | import os
from tool.IO_Handle import IO
from tool.tool_base.base import base
class setting(base):
BASE_DIR = os.path.dirname(os.path.abspath("__file__"))
input_path = os.path.join(BASE_DIR,"input")
output_path = os.path.join(BASE_DIR, "output")
input_type = 'md'
output_type = "txt"
if __name__ =... |
986,166 | 410ffbd7099b66b7fcf5221f23923ed01858435e | # 컴퓨터과학의 농담중에 문제 하나를 정규표현식으로 풀게되면 문제가 2개가 된다. 라는 말이있다.
gusik = """
정규표현식(regular expression) :
정규표현식은 일정한 규칙을 가진 문자열을 표현하는 방법으로, 그러한 문자열을 식별할 때 사용함.
문자열 규칙의 집합이 복잡해지면, 외계어?가 되며, 문자열을 다룰때 매우 유용하지만 읽고 해석하기에는 매우 난해하긴함.
하지만 정규표현식도 여러개로 나열한 규칙들의 모임이라, 하나하나 쪼개보면 어렵지 않음.
"""
# 정규 표현식 > 문자열 판단
"""
^ : 이 기호 뒤에 오는 문자, 문자열, 하위... |
986,167 | 93e174187f2b5da69499b86eb4df86a147ac8104 | # -*-coding:utf-8-*-
from .solver import model
def irt(src, theta_bnds=[-4, 4],
alpha_bnds=[0.25, 2], beta_bnds=[-2, 2], in_guess_param='default',
model_spec='2PL',
mode='memory', is_mount=False, user_name=None):
if model_spec == '2PL':
mod = model.IRT_MMLE_2PL()
else:
... |
986,168 | 9c385ab58c308a59a3d5c8707dafecb1b3e3dbc4 | import pygame
import locations
from scenes.effect_scene import EffectScene
class PopeScene(EffectScene):
def __init__(self, screen, font, text):
super().__init__(screen, font, text)
self.pope_sprite = pygame.transform.scale(pygame.image.load('images/pope.png'), (192, 192))
def show_enemy_st... |
986,169 | 0fed66b75610646f70389872ca09f697e94a2e86 | import user_info
import policy_checker
import password_checker
import report_gen
import database_store
import passgenerator
import user_info_checker
import sys
import getpass
class UserClass:
def __init__(self, data):
self.first_name = data[0]
self.last_name = data[1]
self.birthday = data[... |
986,170 | f829e731fb85bed58be5bee9b53c5771f670e95a | from pathlib import Path
cross_domain_settings = ['laptops_to_restaurants', 'restaurants_to_laptops']
in_domain_settings = ['laptops14', 'restaurants14', 'restaurants15']
all_settings = cross_domain_settings + in_domain_settings
num_splits = 3
base = str(Path.home()) + '/private-nlp-architect/nlp_architect/models/absa... |
986,171 | 5c90a350261802e7fd3d5cfce0bba2685dbaed93 | #!/usr/bin/env python
########################################################
#
# Python version of the Time-independent Free Energy
# reconstruction script (a.k.a. reweight) based on the
# algorithm proposed by Tiwary and Parrinello
# JPCB 2014 doi:10.1021/jp504920s.
#
# The script is meant to be used as an ana... |
986,172 | ac690c794a8449208d78500bb383220ed9369e5e | """
the string "ABC" in binary is:
2^x 7654 3210
A: 0b 0100 0001
B: 0b 0100 0010
C: 0b 0100 0011
together:
0b | 0100 0001 | 0100 0010 | 0100 0011
or without spaces
0b010000010100001001000011
to convert it to base 64 (which is 2^6) we need to split
binary representation by 6 bits instead of 8 (as above)
0b | 010000 | ... |
986,173 | d0c8f4bcb658002bc57739c550a51a025e9dda61 | from flask import Flask, json, jsonify, redirect, render_template, request
import statistics
# Configure application
app = Flask(__name__)
numbers = []
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
# Get user input one number at a time
number = r... |
986,174 | 2c7bead58afc936f3ef8fa35b662199e01b2a865 | # -*- coding: utf-8 -*-
from Autodesk.Revit import DB, UI
import pickle
import os
from tempfile import gettempdir
uiapp = __revit__ # noqa F821
uidoc = uiapp.ActiveUIDocument
app = uiapp.Application
doc = uidoc.Document
class CustomISelectionFilter(UI.Selection.ISelectionFilter):
def __init__(self, nom_class):
... |
986,175 | 026431be29cdbf37806b324616ceee3cb8651849 | primera = str(input('Dime una frase'))
ultima= str(input('Letra que quieres buscar'))
a = (primera.find(ultima))
z = (primera.rfind(ultima))
if(a == -1):
print('')
else:
print(a, z) |
986,176 | 19d57c6228503ff5568464df9cb3750ee85540ea |
# A very simple Flask Hello World app for you to get started with...
from flask import Flask, redirect, render_template, request, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_login import login_user, LoginManager, UserMixin,logout_user,login_required,current_user
from werkzeug.security import check_passw... |
986,177 | 62767d21486edb46505dcc74f5fe916f84a7d73f | # -*- coding: utf-8 -*-
import os
from pathlib import Path
import pytest
from brainhacker.utils.download import _url_to_local_path, _fetch_file, mne_data_path
def test_url_to_local_path(tmpdir):
url = 'https://www.google.com/'
with pytest.raises(ValueError):
_url_to_local_path(url, tmpdir)
url = '... |
986,178 | 0c9e72f91f3336880c1765cad86a566e5d9edf65 | #
# Copyright 2020, by the California Institute of Technology. ALL RIGHTS
# RESERVED. United States Government Sponsorship acknowledged. Any commercial
# use must be negotiated with the Office of Technology Transfer at the
# California Institute of Technology.
#
"""
================
doi_validator.py
==============... |
986,179 | e3ebcbec2bcf22959d4c4ef070ef06f2d1b3e055 | #python
#
# UVIslandPack
#
# Author: Mark Rossi (small update by Cristobal Vila for Modo 11.x)
# Version: .4
# Compatibility: Modo 11.x
#
# Purpose: To fit every UV island in the selected UV map to 0-1 range and then array them in a grid so that each island has its own
# discrete range in UV space.
#
# Use: Se... |
986,180 | b2190bbb93b35040f0a7c77cb438287387d9c0ae | # Generated by Django 2.1.11 on 2019-12-03 00:54
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('producers', '0003_auto_20181218_1934'),
]
operations = [
migrations.RemoveField(
model_name='producer',
name='competition_c... |
986,181 | 7d994ed5babce160bad2d1a945577c947e914da5 | def merge_data(env):
print(env.file["train_file_list"]) |
986,182 | 24e134709ed3db9766bd87b94196681162323986 | """
Question:
We have n chips, where the position of the ith chip is position[i].
We need to move all the chips to the same position. In one step, we can change the position
of the ith chip from position[i] to:
position[i] + 2 or position[i] - 2 with cost = 0.
position[i] + 1 or position[i] - 1 with cost = 1.
Return... |
986,183 | 8d886b3951eb019c6a2bdb75fdef366931baf499 | # -*- encoding: utf-8 -*-
"""
8.6.1 k均值聚类
"""
from sklearn import datasets as dss
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['FangSong']
plt.rcParams['axes.unicode_minus'] = False
X_blob, y_blob = dss.make_blobs(n_samples=[300,400,300], n_features=2)
X_circ... |
986,184 | 6b5bb2ef5b4bf3d294f8b37478ce302921401e2a | from urllib.parse import urlsplit, urlunsplit, unquote, parse_qs
from pathlib import PurePosixPath
from types import SimpleNamespace
from .gpm import gpm_url_to_data
from .spoofy import get_spoofy_url_or_none
# For a given list of URLs, each URL is converted into an object containing data about the item the URL refer... |
986,185 | 3905899f5312fb402fd15819ae8ed246e5969787 | from . import global_values as g
from . import utilities as util
from . import entities
from . import levels
import math as m
import random as r
class Creature(entities.Entity):
def __init__(self, name, rect, animation_system, max_health, move_speed, max_move_speed, **_kwargs):
kwargs = {"solid":True, "co... |
986,186 | ab160636b3728daaed472d88d996b4403968b736 | #!/usr/bin/env python
# coding: utf-8
# # Assignment - 5
# # Question 1
# # Perform Bubble sort using function in python.
# # Solution:
# In[1]:
def bubble_sort(l):
n= len(l)
for i in range(0,n):
swapped = 0
for j in range(0,n-1-i):
if l[j] > l[j+1]:
l[j],l[j+1... |
986,187 | 3b5066a7fba0001982977d5c389228bd2d8d67e8 |
#ImportModules
import ShareYourSystem as SYS
#Definition of an instance
MyProducer=SYS.ProducerClass().produce(
"Catchers",
['First','Second','Third','Four'],
SYS.CatcherClass,
)
#Catch with a relative path
MyProducer['<Catchers>FirstCatcher'].grasp(
'/NodePointDeriveNoder/<Catchers>SecondCatcher'
).catch(
... |
986,188 | 2c11edbc40e6827175a12d880f070f2f2976f8df | import pygame
'''
A reimplementation of the knots and crosses game - this time using the
pygame module to create an interactive user interface, allowing players
to use the mouse instead.
'''
pygame.font.init()
white_colour = (255, 255, 255)
clock = pygame.time.Clock()
tick_rate = 60
font = pygame.fon... |
986,189 | cc513bcc3509e52440a984ab7078738692715f59 | #encrypt
#import rand in registration
def encrypt(string,j):
s=[]
for i in range(len(string)):
s.append(str(ord(string[i])-j))
s=str("".join(s))
return s
def regencrypt(string,rand):
x=[]
for i in range(len(string)):
x.append(str(ord(string[i])-rand))
x=str("".join(x))
return x
|
986,190 | 19a999c9809051c298b4057ec323d4e0f8d862fb | # -*- coding:utf-8 -*-
import unittest
from database.core import DatabaeTemplate
import database.core
from database.factory import OracleConnectionFactory
CONNECT_URL = 'epayment/Epay789*QWE@localhost:15211/tyzf'
HOST = 'localhost'
USERNAME = 'epayment'
PASSWORD = 'Epay789*QWE'
PORT = 15215
SERVICE = 'tyzf'
class D... |
986,191 | 2402dfa0dc83c2277c92a3cc3c11129e36282635 | #chapter03\prime2.py
import math
m = int(input("请输入一个整数(>1):"))
k = int(math.sqrt(m))
flag = True #先假设所输整数为素数
i = 2
while (i <= k and flag == True):
if (m % i == 0): flag = False #可以整除,肯定不是素数,结束循环
else: i += 1
if (flag == True): print(m, "是素数!")
else: print(m, "是合数!")
input()
|
986,192 | 668b59fd627e7df23f3617e696a0bc787a067798 | """Exceptions used in pyparam"""
class PyParamException(Exception):
"""Base exception for pyparam"""
class PyParamTypeError(PyParamException):
"""When parameter type is not supported"""
class PyParamValueError(PyParamException):
"""When parameter value is improper"""
class PyParamNameError(PyParamEx... |
986,193 | 9b25135be1688019781c69a16d63a64f6161d721 | import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import math
from util.gen_sal_map import vid_sal_map
#from util.solver import _gaussian_distribution2d as gauss_dist2d
def KLDiv(MDN_outputs, fix_data):
sal_map = gen_sal_map(*MDN_outputs)
fix_data = fix_data.data.cpu... |
986,194 | 625ab6d2dc40752b3b2456136e3d1a3ef21d32e7 | '''
Code to investigate environment dependence on the
line-of-sight displacement
Author(s): ChangHoon Hahn
'''
import numpy as np
import scipy as sp
import os.path
import cosmolopy as cosmos
# --- Local ---
from dlos import Dlos
from corr_spec.corr_corrdata import CorrCorrData
class DlosPhotoz(Dlos):
def ... |
986,195 | 14a0b3961a3de532130d8a875c931a6f8b503300 | #! /usr/bin/env python
top = '..'
def build(bld):
bld.program(
source = 'test.c',
target = 'test_recontext',
use = 'recontext',
rpath = bld.top_dir + '/build/src',
install_path = None,
)
|
986,196 | 59f98f0a9f61e0a9294b4c4da5f031bd1735fd81 | '''
Import selected columns of the GGSN CSV data to pandas.
python globul_ggsn_select_to_pandas.py /path/to/ggsn.h5 /path/to/ggsn.csv
Author: Axel.Tidemann@telenor.com
'''
import sys
import pandas as pd
from globul_to_pandas import to_hdf5
usecols = ['IMSI', 'cell_ID', 'recordType', 'recordOpeningDate', 'recordOp... |
986,197 | e76e1f0dceee1e716fc549e33da6e4ccd177bc98 | from __future__ import division, print_function
import os
import cStringIO as StringIO
from subprocess import Popen, PIPE
from pymatgen.util.io_utils import which
from pymatgen.util.string_utils import list_strings
import logging
logger = logging.getLogger(__name__)
__author__ = "Matteo Giantomassi"
__copyright__ =... |
986,198 | 408f3543bda73edb679b8fea93389153da6e623a | import torch
import torch.nn as nn
from transformer1.layers import PostitionalandWordEncoding , DecoderBlock
class Decoder(nn.Module):
def __init__(self , output_vocab ,embedding_dim , num_head , num_layers):
super(Decoder , self).__init__()
self.embdding_dim = embedding_dim
self.n... |
986,199 | 188b0fced5305d1ddf9ce19f78a32357a14cc570 | from parsers.MainParser import Parser
from config import *
import re
import os
def create_cache(lines):
with open(CACHE, 'a') as file:
file.write('\n'.join(lines))
def get_cache():
if os.path.exists(CACHE):
lines = open(CACHE, 'r').readlines()
return lines
else:
return []
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.