file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
dicer.py | import numpy as np
import cv2
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
gpios = True
try: # Wenn Programm nicht auf einem Raspberry läuft, GPIOS nicht benutzen
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
G... | 2.imwrite('frame.png',frame)
# Bildausschnitte von Würfel und Positionserkennung
y = 160
h = 240
x = 220
w = 240
dice_image = frame[y:y + h, x:x + w]
grey = cv2.cvtColor(dice_image, cv2.COLOR_BGR2GRAY)
#cv2.imshow('input', grey)
#cv2.imwrite('real_image.png',frame)
y = 120
... | e = cap.read()
#cv | conditional_block |
dicer.py | import numpy as np
import cv2
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
gpios = True
try: # Wenn Programm nicht auf einem Raspberry läuft, GPIOS nicht benutzen
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
G... | or i in range(5):
ret, frame = cap.read()
#cv2.imwrite('frame.png',frame)
# Bildausschnitte von Würfel und Positionserkennung
y = 160
h = 240
x = 220
w = 240
dice_image = frame[y:y + h, x:x + w]
grey = cv2.cvtColor(dice_image, cv2.COLOR_BGR2GRAY)
#cv2.imshow('input', grey)... | s():
f | identifier_name |
dicer.py | import numpy as np
import cv2
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
gpios = True
try: # Wenn Programm nicht auf einem Raspberry läuft, GPIOS nicht benutzen
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
G... | .time()
if dicer_ready is True: # Interrupt initialisieren
GPIO.add_event_detect(18, GPIO.FALLING, callback = interr, bouncetime = 200)
print('Starting...')
while dicer_ready is True:
#localtime = time.localtime(time.time())
#if localtime.tm_hour >= endtime_hr and localtime.tm_min >= endtime_min: # A... | two = all_numbers[1]
three = all_numbers[2]
four = all_numbers[3]
five = all_numbers[4]
six = all_numbers[5]
errorcnt = all_numbers[6]
success_rolls= all_numbers[7]
detector = cv2.SimpleBlobDetector_create(blob_params)
keypoints = detector.detect(image)
img_with_keypoints = cv2.... | identifier_body |
dicer.py | import numpy as np
import cv2
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
gpios = True
try: # Wenn Programm nicht auf einem Raspberry läuft, GPIOS nicht benutzen
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
G... |
log_name = 'log_seite2' # Name der Log Datei (Zusammenfassung der Messreihe): Wird NICHT fortgesetzt
raw_numbers_name = 'raw_seite2' # Name der Datei, in der alle Würfe einzeln gespeichert werden: Wird fortgesetzt
email_header = 'dicer - seite2' # Emailbetreff
darknumbers = False # Dunkle Würfelaugen?
send_email = ... | random_line_split | |
repository.go | package say
import (
"crypto/rand"
"database/sql"
"errors"
"fmt"
"io"
"math"
"math/big"
"strconv"
"strings"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
)
const (
maxInsertRetries = 16
convoIDPrefix = "cv_"
lineIDPrefix = "ln_"
dbErrDupUnique = "23505"
dbErrFKViolation = "23503"
listMoods... |
}
var rec moodRec
err := r.findMood.Get(&rec, struct{ UserID, Name string }{userID, name})
if err == sql.ErrNoRows {
return nil, nil
} else if err != nil {
return nil, fmt.Errorf("getting user mood: %v", err)
}
rec.UserDefined = true
rec.id = rec.IntID
return &rec.Mood, nil
}
func (r *repository) SetMo... | {
// Copy to prevent modifying builtins by the caller
mood := *builtin
return &mood, nil
} | conditional_block |
repository.go | package say
import (
"crypto/rand"
"database/sql"
"errors"
"fmt"
"io"
"math"
"math/big"
"strconv"
"strings"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
)
const (
maxInsertRetries = 16
convoIDPrefix = "cv_"
lineIDPrefix = "ln_"
dbErrDupUnique = "23505"
dbErrFKViolation = "23503"
listMoods... | (args listArgs) bool {
return args.After != "" || args.Before == ""
}
func doDelete(stmt *sqlx.NamedStmt, args interface{}) error {
res, err := stmt.Exec(args)
if err != nil {
return err
}
cnt, err := res.RowsAffected()
if err != nil {
return err
}
if cnt == 0 {
return errRecordNotFound
}
return nil
... | sortAsc | identifier_name |
repository.go | package say
import (
"crypto/rand"
"database/sql"
"errors"
"fmt"
"io"
"math"
"math/big"
"strconv"
"strings"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
)
const (
maxInsertRetries = 16
convoIDPrefix = "cv_"
lineIDPrefix = "ln_"
dbErrDupUnique = "23505"
dbErrFKViolation = "23503"
listMoods... | return false
}
func sortAsc(args listArgs) bool {
return args.After != "" || args.Before == ""
}
func doDelete(stmt *sqlx.NamedStmt, args interface{}) error {
res, err := stmt.Exec(args)
if err != nil {
return err
}
cnt, err := res.RowsAffected()
if err != nil {
return err
}
if cnt == 0 {
return errRe... | random_line_split | |
repository.go | package say
import (
"crypto/rand"
"database/sql"
"errors"
"fmt"
"io"
"math"
"math/big"
"strconv"
"strings"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
)
const (
maxInsertRetries = 16
convoIDPrefix = "cv_"
lineIDPrefix = "ln_"
dbErrDupUnique = "23505"
dbErrFKViolation = "23503"
listMoods... |
func (r *repository) ListConversations(userID string, args listArgs) ([]Conversation, bool, error) {
var convos []Conversation
cursor := args.After
query := r.listConvosAsc
if !sortAsc(args) {
cursor = args.Before
query = r.listConvosDesc
}
cursorID := -1
if cursor != "" {
var convo convoRec
err := ... | {
if isBuiltin(name) {
return errBuiltinMood
}
queryArgs := struct{ UserID, Name string }{userID, name}
if err := doDelete(r.deleteMood, queryArgs); err != nil {
if dbErr, ok := err.(*pq.Error); !ok || dbErr.Code != dbErrFKViolation {
return err
}
// List the lines that are preventing us from deleting ... | identifier_body |
The Movies Database.py | import sys
import re
import numpy as np
import pandas as pd
from numpy import dot
from numpy.linalg import norm
from operator import add
from pyspark import SparkContext
from pyspark.sql.functions import when, explode, col, desc
import matplotlib.pyplot as plt
from pyspark.mllib.classification import LogisticRegress... |
#tmdb_movies = sc.textFile('tmdb_5000_movies.csv')
tmdb_movies = sc.textFile(sys.argv[1], 1)
#Remove header and split data
header = tmdb_movies.first()
#Split by , followed by non-whitespace
regex = re.compile(',(?=\\S)')
tmdb_movies = tmdb_movies.filter(lambda x: x != header).map(lambda x: regex.split(x))
print('N... | if (float(p[0])>0 and float(p[8])>0 and float(p[12])>0 and float(p[13])>0 and float(p[18])>0):
if (len(p[1])>2 and len(p[9])>2):
return p | conditional_block |
The Movies Database.py | import sys
import re
import numpy as np
import pandas as pd
from numpy import dot
from numpy.linalg import norm
from operator import add
from pyspark import SparkContext
from pyspark.sql.functions import when, explode, col, desc
import matplotlib.pyplot as plt
from pyspark.mllib.classification import LogisticRegress... | # Revenue(x[5])
# Profit (x[6])
# Runtime(x[7])
# Average Rating(x[8])
## Top 10 Most Profitable Movie Titles
profit_title = tmdb_movies_filtered.map(lambda x: (x[0], x[6])).\
reduceByKey(add)
profit_title_top = profit_title.top(20, lambda x: x[1])
print('Titles sorted based on Pro... | # Popularity(x[3])
# Release Date(x[4]) | random_line_split |
The Movies Database.py | import sys
import re
import numpy as np
import pandas as pd
from numpy import dot
from numpy.linalg import norm
from operator import add
from pyspark import SparkContext
from pyspark.sql.functions import when, explode, col, desc
import matplotlib.pyplot as plt
from pyspark.mllib.classification import LogisticRegress... |
logitTrainParsed = logitTrain.map(parsePoint)
# Build the model
model = LogisticRegressionWithLBFGS.train(logitTrainParsed)
logitTestParsed = logitTest.map(parsePoint)
ytest_ypred = logitTestParsed.map(lambda x: (float(model.predict(x.features)), x.label))
metrics = BinaryClassificationMetrics(ytest_ypred)
print(... | return LabeledPoint(line[0], line[1]) | identifier_body |
The Movies Database.py | import sys
import re
import numpy as np
import pandas as pd
from numpy import dot
from numpy.linalg import norm
from operator import add
from pyspark import SparkContext
from pyspark.sql.functions import when, explode, col, desc
import matplotlib.pyplot as plt
from pyspark.mllib.classification import LogisticRegress... | (line):
return LabeledPoint(line[0], line[1])
logitTrainParsed = logitTrain.map(parsePoint)
# Build the model
model = LogisticRegressionWithLBFGS.train(logitTrainParsed)
logitTestParsed = logitTest.map(parsePoint)
ytest_ypred = logitTestParsed.map(lambda x: (float(model.predict(x.features)), x.label))
metrics =... | parsePoint | identifier_name |
network.py | # TO-DO
# [ ] Find a way to train a model with 2 datasets
# [ ] Implement a training to the model for characters
import sys
import utils
import os
import logging
from logging import handlers
import tensorflow as tf
import emnist
import h5py
import cv2
import numpy as np
import matplotlib.pyplot as plt
from keras.model... |
def load_trained_model():
#######################################################
################### Network setup #####################
n_classes = 62
train_size = 697932
test_size = 116323
v_length = 784
# split the emnist data into train and test
trainData, trainLabels = emnist.ex... | epochs = u_epochs
n_classes = 62
batch_size = 256
train_size = 697932
test_size = 116323
v_length = 784
# split the emnist data into train and test
trainData, trainLabels = emnist.extract_training_samples('byclass')
testData, testLabels = emnist.extract_test_samples('byclass')
# p... | identifier_body |
network.py | # TO-DO
# [ ] Find a way to train a model with 2 datasets
# [ ] Implement a training to the model for characters
import sys
import utils
import os
import logging
from logging import handlers
import tensorflow as tf
import emnist
import h5py
import cv2
import numpy as np
import matplotlib.pyplot as plt
from keras.model... | (u_epochs):
#######################################################
################### Network setup #####################
# batch_size - Number of images given to the model at a particular instance
# v_length - Dimension of flattened input image size i.e. if input image size is [28x28], then v_length... | train_emnist | identifier_name |
network.py | # TO-DO
# [ ] Find a way to train a model with 2 datasets
# [ ] Implement a training to the model for characters
import sys
import utils
import os
import logging
from logging import handlers
import tensorflow as tf
import emnist
import h5py
import cv2
import numpy as np
import matplotlib.pyplot as plt
from keras.model... |
plate = ''
for char in plate_predictions:
plate += char
# output the recognized plate
logger.debug("The car plate is: {}".format(plate))
logger.debug("Now the system will show each predicted picture and it's respective prediction")
logger.debug("NOTE: Press any key to close img wi... | original_img = test_image
# reshape the test image to [1x784] format so that our model understands
test_image = test_image.reshape(1, 784)
# make prediction on test image using our trained model
prediction = model.predict_classes(test_image, verbose=0)
plate_pre... | conditional_block |
network.py | # TO-DO
# [ ] Find a way to train a model with 2 datasets
# [ ] Implement a training to the model for characters
import sys
import utils
import os
import logging
from logging import handlers
import tensorflow as tf
import emnist
import h5py
import cv2
import numpy as np
import matplotlib.pyplot as plt
from keras.model... |
# params: 1- mlmodel, 2- root path to the prediction imgs, 3- how many imgs we have in imgs_path
def identify_plate(model, imgs_path, test_size):
# EMNIST output infos as numbers, so I created a label dict, so it will output it respective class
label_value = {'0':'0', '1':'1', '2':'2', '3':'3', '4':'4', '5':'5... | plt.subplot(220+i)
plt.imshow(org_image, cmap=plt.get_cmap('gray'))
logger.debug('Press Q to close')
plt.show() | random_line_split |
HOG_SVM_FaceDetection.py | #!/usr/bin/env python
# coding: utf-8
# # <font style = "color:rgb(50,120,229)">Face Detection using HOG + SVM</font>
#
# In the previous module we learned how to use HOG descriptor with SVM to train a classifier. In this module we will learn how to use a HOG + SVM classifier for Object Detection.
#
# # <font styl... | der, classLabel):
#change image sizes to match
width = 128
height = 128
dim = (width, height)
images = []
labels = []
imagePaths = getImagePaths(folder, ['.jpg', '.png', '.jpeg'])
for imagePath in imagePaths:
# print(imagePath)
im = cv2.imread(imagePath, cv2.IMREAD_COLOR)
resized = cv2.re... | ataset(fol | identifier_name |
HOG_SVM_FaceDetection.py | #!/usr/bin/env python
# coding: utf-8
# # <font style = "color:rgb(50,120,229)">Face Detection using HOG + SVM</font>
#
# In the previous module we learned how to use HOG descriptor with SVM to train a classifier. In this module we will learn how to use a HOG + SVM classifier for Object Detection.
#
# # <font styl... | #
# 4. [http://www.pyimagesearch.com/2015/11/09/pedestrian-detection-opencv/](http://www.pyimagesearch.com/2015/11/09/pedestrian-detection-opencv/)
#
# 5. http://blog.dlib.net/2014/02/dlib-186-released-make-your-own-object.html
# In[ ]: | #
# 1. [https://lear.inrialpes.fr/people/triggs/pubs/Dalal-cvpr05.pdf](https://lear.inrialpes.fr/people/triggs/pubs/Dalal-cvpr05.pdf)
#
# 3. [https://en.wikipedia.org/wiki/Support_vector_machine](https://en.wikipedia.org/wiki/Support_vector_machine) | random_line_split |
HOG_SVM_FaceDetection.py | #!/usr/bin/env python
# coding: utf-8
# # <font style = "color:rgb(50,120,229)">Face Detection using HOG + SVM</font>
#
# In the previous module we learned how to use HOG descriptor with SVM to train a classifier. In this module we will learn how to use a HOG + SVM classifier for Object Detection.
#
# # <font styl... | eturn imagePaths
#change image sizes to match
width = 128
height = 128
dim = (width, height)
# read images in a folder
# return list of images and labels
def getDataset(folder, classLabel):
#change image sizes to match
width = 128
height = 128
dim = (width, height)
images = []
labels = []
imagePaths ... | h = os.path.join(folder, x)
if os.path.splitext(xPath)[1] in imgExts:
imagePaths.append(xPath)
r | conditional_block |
HOG_SVM_FaceDetection.py | #!/usr/bin/env python
# coding: utf-8
# # <font style = "color:rgb(50,120,229)">Face Detection using HOG + SVM</font>
#
# In the previous module we learned how to use HOG descriptor with SVM to train a classifier. In this module we will learn how to use a HOG + SVM classifier for Object Detection.
#
# # <font styl... | redict labels for given samples
def svmPredict(model, samples):
return model.predict(samples)[1]
# evaluate a model by comparing
# predicted labels and ground truth
def svmEvaluate(model, samples, labels):
labels = labels[:, np.newaxis]
pred = model.predict(samples)[1]
correct = np.sum((labels == pred))
err... | train(samples, cv2.ml.ROW_SAMPLE, labels)
# p | identifier_body |
cli.py | #!/usr/bin/env python3
"""
MIT License
Copyright (c) 2020 Srevin Saju
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, mo... | expose_value=False, is_eager=True)
@click.option('--license', '--lic', is_flag=True, callback=show_license,
expose_value=False, is_eager=True)
def cli():
""" 🗲 Zap: A command line interface to install appimages"""
pass
@cli.command('install')
@click.argument('appname')
@click.opti... | ctx.exit()
@click.group()
@click.option('--version', is_flag=True, callback=show_version, | random_line_split |
cli.py | #!/usr/bin/env python3
"""
MIT License
Copyright (c) 2020 Srevin Saju
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, mo... | elif p_url.netloc == 'remove':
z.remove()
else:
print("Invalid url")
@cli.command()
@click.argument('appname')
def get_md5(appname):
"""Get md5 of an appimage"""
z = Zap(appname)
z.get_md5()
@cli.command()
@click.argument('appname')
def is_integrated(appname):
"""Checks if appi... | nt(tag, asset_id)
z.install(tag_name=tag,
download_file_in_tag=asset_id,
downloader=gtk_zap_downloader, always_proceed=True)
| conditional_block |
cli.py | #!/usr/bin/env python3
"""
MIT License
Copyright (c) 2020 Srevin Saju
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, mo... |
"""Upgrade all appimages using AppImageUpdate"""
config = ConfigManager()
apps = config['apps']
for i, app in progressbar(enumerate(apps), redirect_stdout=True):
z = Zap(app)
if i == 0:
z.update(show_spinner=False)
else:
z.update(check_appimage_update=Fal... | rade(): | identifier_name |
cli.py | #!/usr/bin/env python3
"""
MIT License
Copyright (c) 2020 Srevin Saju
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, mo... | @cli.command()
@click.argument('appname')
def is_integrated(appname):
"""Checks if appimage is integrated with the desktop"""
z = Zap(appname)
z.is_integrated()
@cli.command('list')
def ls():
"""Lists all the appimages"""
cfgmgr = ConfigManager()
apps = cfgmgr['apps']
for i in apps:
... | Get md5 of an appimage"""
z = Zap(appname)
z.get_md5()
| identifier_body |
cmpH5Sort.py | #!/usr/bin/env python
import os
import sys
import tempfile
import shutil
import datetime
import h5py as H5
from numpy import *
from optparse import OptionParser
from dmtk.io.cmph5.CmpH5SortingTools import *
from dmtk.io.cmph5 import CmpH5Factory
__VERSION__ = ".64"
def __pathExists(h5, path):
try:
h5[p... |
def write(self, msg, level):
if (self.level >= level): sys.stderr.write(str(msg) + "\n")
def error(self, msg): self.write(msg, 0)
def warn(self, msg): self.write(msg, 1)
def msg(self, msg): self.write(msg, 2)
def main():
usage = \
""" %prog [options] input-file [output-file]
... | self.level = level | identifier_body |
cmpH5Sort.py | #!/usr/bin/env python
import os
import sys
import tempfile
import shutil
import datetime
import h5py as H5
from numpy import *
from optparse import OptionParser
from dmtk.io.cmph5.CmpH5SortingTools import *
from dmtk.io.cmph5 import CmpH5Factory
__VERSION__ = ".64"
def __pathExists(h5, path):
try:
h5[p... | (inFile, outFile, deep, jobs, log):
"""
This routine takes a cmp.h5 file and sorts the AlignmentIndex
table adding two additional columns for fast access. In addition,
a new top-level attribute is added to the indicate that the file
has been sorted, as well as a table to indicate the blocks of the
... | sortCmpH5 | identifier_name |
cmpH5Sort.py | #!/usr/bin/env python
import os
import sys
import tempfile
import shutil
import datetime
import h5py as H5
from numpy import *
from optparse import OptionParser
from dmtk.io.cmph5.CmpH5SortingTools import *
from dmtk.io.cmph5 import CmpH5Factory
__VERSION__ = ".64"
def __pathExists(h5, path):
try:
h5[p... |
if __name__ == "__main__":
main()
| cmpH5 = CmpH5Factory.factory.create(outfile, 'a')
cmpH5.log("cmpH5Sort.py", __VERSION__, str(datetime.datetime.now()), ' '.join(sys.argv), "Sorting")
cmpH5.close()
if (len(args) < 2):
shutil.copyfile(outfile, infile)
ofile.close()
exit(0) | conditional_block |
cmpH5Sort.py | #!/usr/bin/env python
import os
import sys
import tempfile
import shutil
import datetime
import h5py as H5
from numpy import *
from optparse import OptionParser
from dmtk.io.cmph5.CmpH5SortingTools import *
from dmtk.io.cmph5 import CmpH5Factory
__VERSION__ = ".64"
def __pathExists(h5, path):
try:
h5[p... | ## Don't really have to do anything if there are no references
## which aligned.
if (lRow == fRow):
continue
## Make a new Group.
newGroup = getRefGroup(offsets[row, 0]).create_group(SORTED)
log.msg("Created new read group: %s" % SORTED)
## Go throu... |
fRow = int(offsets[row, 1])
lRow = int(offsets[row, 2])
| random_line_split |
main.rs | #![allow(unused)]
#![allow(non_snake_case)]
use crate::db::MyDbContext;
use serenity::model::prelude::*;
use sqlx::Result;
use serenity::{
async_trait,
client::bridge::gateway::{GatewayIntents, ShardId, ShardManager},
framework::standard::{
buckets::{LimitedFor, RevertBucket},
help_commands... | (ctx: &Context, msg: &Message, error: DispatchError) {
if let DispatchError::Ratelimited(info) = error {
// We notify them only once.
if info.is_first_try {
let _ = msg
.channel_id
.say(
&ctx.http,
&format!("Try this... | dispatch_error | identifier_name |
main.rs | #![allow(unused)]
#![allow(non_snake_case)]
use crate::db::MyDbContext;
use serenity::model::prelude::*;
use sqlx::Result;
use serenity::{
async_trait,
client::bridge::gateway::{GatewayIntents, ShardId, ShardManager},
framework::standard::{
buckets::{LimitedFor, RevertBucket},
help_commands... | else {
Some(out)
}
}
async fn greet_new_guild(ctx: &Context, guild: &Guild) {
println!("h");
if let Some(channelvec) = better_default_channel(guild, UserId(802019556801511424_u64)).await {
println!("i");
for channel in channelvec {
println!("{}", channel.name);
... | {
None
} | conditional_block |
main.rs | #![allow(unused)]
#![allow(non_snake_case)]
use crate::db::MyDbContext;
use serenity::model::prelude::*;
use sqlx::Result;
use serenity::{
async_trait,
client::bridge::gateway::{GatewayIntents, ShardId, ShardManager},
framework::standard::{
buckets::{LimitedFor, RevertBucket},
help_commands... | pub async fn better_default_channel(guild: &Guild, uid: UserId) -> Option<Vec<&GuildChannel>> {
let member = guild.members.get(&uid)?;
let mut out = vec![];
for channel in guild.channels.values() {
if channel.kind == ChannelType::Text
&& guild
.user_permissions_in(channe... | random_line_split | |
charisma.js | $(document).ready(function(){
//themes, change CSS with JS
//default theme(CSS) is cerulean, change it if needed
$.cookie('project_title', _project_title, {expires:365});
var current_theme = $.cookie('current_theme')==null ? 'cerulean' :$.cookie('current_theme');
switch_theme(current_theme);
//ajax menu c... | 'span10');
}
//highlight current / active link
$('ul.main-menu li a').each(function(){
if($($(this))[0].href==String(window.location))
$(this).parent().addClass('active');
});
//establish history variables
var
History = window.History, // Note: We are using a capital H instead of a lower h
State... | removeClass( | identifier_name |
charisma.js | $(document).ready(function(){
//themes, change CSS with JS
//default theme(CSS) is cerulean, change it if needed
$.cookie('project_title', _project_title, {expires:365});
var current_theme = $.cookie('current_theme')==null ? 'cerulean' :$.cookie('current_theme');
switch_theme(current_theme);
//ajax menu c... | $('li:last', an[i]).removeClass('disabled');
}
}
}
}
}); | }
if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
$('li:last', an[i]).addClass('disabled');
} else { | random_line_split |
charisma.js | $(document).ready(function(){
//themes, change CSS with JS
//default theme(CSS) is cerulean, change it if needed
$.cookie('project_title', _project_title, {expires:365});
var current_theme = $.cookie('current_theme')==null ? 'cerulean' :$.cookie('current_theme');
switch_theme(current_theme);
//ajax menu c... |
// do a random walk
while (data.length < totalPoints) {
var prev = data.length > 0 ? data[data.length - 1] : 50;
var y = prev + Math.random() * 10 - 5;
if (y < 0)
y = 0;
if (y > 100)
y = 100;
data.push(y);
}
// zip the generated y values with the x values
var res = [];
for (var i = ... | }
// we use an inline data source in the example, usually data would
// be fetched from a server
var data = [], totalPoints = 300;
function getRandomData() {
if (data.length > 0)
data = data.slice(1);
| identifier_body |
api_op_CreateRoute.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package ec2
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
smithyendpoint... |
func (m *opCreateRouteResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
if awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
return next.HandleSerialize(ctx, i... | {
return "ResolveEndpointV2"
} | identifier_body |
api_op_CreateRoute.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package ec2
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
smithyendpoint... | for k := range resolvedEndpoint.Headers {
req.Header.Set(
k,
resolvedEndpoint.Headers.Get(k),
)
}
authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties)
if err != nil {
var nfe *internalauth.NoAuthenticationSchemesFoundError
if errors.As(err, &nfe) {
// if no auth ... | req.URL = &resolvedEndpoint.URI
| random_line_split |
api_op_CreateRoute.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package ec2
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
smithyendpoint... | else {
signingName = *v4Scheme.SigningName
}
if v4Scheme.SigningRegion == nil {
signingRegion = m.BuiltInResolver.(*builtInResolver).Region
} else {
signingRegion = *v4Scheme.SigningRegion
}
if v4Scheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initi... | {
signingName = "ec2"
} | conditional_block |
api_op_CreateRoute.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package ec2
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
smithyendpoint... | (stack *middleware.Stack, options Options) (err error) {
err = stack.Serialize.Add(&awsEc2query_serializeOpCreateRoute{}, middleware.After)
if err != nil {
return err
}
err = stack.Deserialize.Add(&awsEc2query_deserializeOpCreateRoute{}, middleware.After)
if err != nil {
return err
}
if err = addlegacyEndpoi... | addOperationCreateRouteMiddlewares | identifier_name |
irc_comm.rs | use super::bot_cmd;
use super::irc_msgs::is_msg_to_nick;
use super::irc_msgs::OwningMsgPrefix;
use super::irc_send::push_to_outbox;
use super::irc_send::OutboxPort;
use super::parse_msg_to_nick;
use super::pkg_info;
use super::reaction::LibReaction;
use super::trigger;
use super::BotCmdResult;
use super::ErrorKind;
use... |
fn compose_msgs<S1, S2, M>(
&self,
dest: MsgDest,
addressee: S1,
msgs: M,
) -> Result<Option<LibReaction<Message>>>
where
S1: Borrow<str>,
S2: Display,
M: IntoIterator<Item = S2>,
{
// Not `SmallVec`, because we're guessing that the calle... | {
let final_msg = format!(
"{}{}{}",
addressee.borrow(),
if addressee.borrow().is_empty() {
""
} else {
&self.addressee_suffix
},
msg,
);
info!("Sending message to {:?}: {:?}", dest, final_ms... | identifier_body |
irc_comm.rs | use super::bot_cmd;
use super::irc_msgs::is_msg_to_nick;
use super::irc_msgs::OwningMsgPrefix;
use super::irc_send::push_to_outbox;
use super::irc_send::OutboxPort;
use super::parse_msg_to_nick;
use super::pkg_info;
use super::reaction::LibReaction;
use super::trigger;
use super::BotCmdResult;
use super::ErrorKind;
use... | <'a>(msg: Option<Cow<'a, str>>) -> LibReaction<Message> {
let quit = aatxe::Command::QUIT(
msg.map(Cow::into_owned)
.or_else(|| Some(pkg_info::BRIEF_CREDITS_STRING.clone())),
).into();
LibReaction::RawMsg(quit)
}
pub(super) fn handle_msg(
state: &Arc<State>,
server_id: ServerId... | mk_quit | identifier_name |
irc_comm.rs | use super::bot_cmd;
use super::irc_msgs::is_msg_to_nick;
use super::irc_msgs::OwningMsgPrefix;
use super::irc_send::push_to_outbox;
use super::irc_send::OutboxPort;
use super::parse_msg_to_nick;
use super::pkg_info;
use super::reaction::LibReaction;
use super::trigger;
use super::BotCmdResult;
use super::ErrorKind;
use... | state: &Arc<State>,
server_id: ServerId,
outbox: &OutboxPort,
prefix: OwningMsgPrefix,
target: String,
msg: String,
) -> Result<()> {
trace!(
"[{}] Handling PRIVMSG: {:?}",
state.server_socket_addr_dbg_string(server_id),
msg
);
let bot_nick = state.nick(serve... | random_line_split | |
irc_comm.rs | use super::bot_cmd;
use super::irc_msgs::is_msg_to_nick;
use super::irc_msgs::OwningMsgPrefix;
use super::irc_send::push_to_outbox;
use super::irc_send::OutboxPort;
use super::parse_msg_to_nick;
use super::pkg_info;
use super::reaction::LibReaction;
use super::trigger;
use super::BotCmdResult;
use super::ErrorKind;
use... |
_ => Ok(()),
}
}
fn handle_privmsg(
state: &Arc<State>,
server_id: ServerId,
outbox: &OutboxPort,
prefix: OwningMsgPrefix,
target: String,
msg: String,
) -> Result<()> {
trace!(
"[{}] Handling PRIVMSG: {:?}",
state.server_socket_addr_dbg_string(server_id),
... | {
push_to_outbox(outbox, server_id, handle_004(state, server_id)?);
Ok(())
} | conditional_block |
wechat_mp.go | package mp
import (
"bytes"
"encoding/base64"
"encoding/binary"
"encoding/xml"
"fmt"
"github.com/BruceMaa/Panda/wechat/common"
"io/ioutil"
"net/http"
"strconv"
"time"
)
const (
WechatRequestEchostr = "echostr" // 微信认证服务器请求参数:返回字符串
WechatRequestTimestamp = "timestamp" // 微信服务器请求参数... | ck := CheckWechatAuthSign(msg_signature, timestamp, nonce, wm.Configure.Token, msgEncryptRequest.Encrypt)
var message []byte
if check {
// 验证成功,解密消息,返回正文的二进制数组格式
message, err = wm.aesDecryptMessage(msgEncryptRequest.Encrypt)
if err != nil {
fmt.Fprintf(common.WechatErrorLoggerWriter, "checkMessageSourc... | st
if err = xml.Unmarshal(body, &msgEncryptRequest); err != nil {
fmt.Fprintf(common.WechatErrorLoggerWriter, "checkMessageSource xml.Unmarshal(body, &msgEncryptBody) error: %+v\n", err)
return false, nil
}
che | identifier_body |
wechat_mp.go | package mp
import (
"bytes"
"encoding/base64"
"encoding/binary"
"encoding/xml"
"fmt"
"github.com/BruceMaa/Panda/wechat/common"
"io/ioutil"
"net/http"
"strconv"
"time"
)
const (
WechatRequestEchostr = "echostr" // 微信认证服务器请求参数:返回字符串
WechatRequestTimestamp = "timestamp" // 微信服务器请求参数... | identifier_name | ||
wechat_mp.go | package mp
import (
"bytes"
"encoding/base64"
"encoding/binary"
"encoding/xml"
"fmt"
"github.com/BruceMaa/Panda/wechat/common"
"io/ioutil"
"net/http"
"strconv"
"time"
)
const (
WechatRequestEchostr = "echostr" // 微信认证服务器请求参数:返回字符串
WechatRequestTimestamp = "timestamp" // 微信服务器请求参数... | lerFunc(handlerFunc ImageMessageHandlerFunc) {
wm.ImageMessageHandler = handlerFunc
}
// 设置处理微信voice消息事件方法
func (wm *WechatMp) SetVoiceHandlerFunc(handlerFunc VoiceMessageHandlerFunc) {
wm.VoiceMessageHandler = handlerFunc
}
// 设置处理微信video消息事件方法
func (wm *WechatMp) SetVideoHandlerFunc(handlerFunc VideoMessageHandle... | SetTextHandlerFunc(handlerFunc TextMessageHandlerFunc) {
wm.TextMessageHandler = handlerFunc
}
// 设置处理微信image消息事件方法
func (wm *WechatMp) SetImageHand | conditional_block |
wechat_mp.go | package mp
import (
"bytes"
"encoding/base64"
"encoding/binary"
"encoding/xml"
"fmt"
"github.com/BruceMaa/Panda/wechat/common"
"io/ioutil"
"net/http"
"strconv"
"time"
)
const (
WechatRequestEchostr = "echostr" // 微信认证服务器请求参数:返回字符串
WechatRequestTimestamp = "timestamp" // 微信服务器请求参数... | // 如果消息未加密
signature := r.FormValue(WechatRequestSignature)
return CheckWechatAuthSign(signature, wm.Configure.Token, timestamp, nonce), body
}
// 加密后的微信消息结构
type MsgEncryptRequest struct {
XMLName xml.Name `xml:"xml"`
ToUserName string // 开发者微信号
Encrypt string // 加密的消息正文
}
// 响应加密消息的结构
type MsgEncryp... | }
return check, message
} | random_line_split |
utils.py | import os
import numpy as np
import pydicom as dicom
import cv2
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
import scipy.ndimage as ndimage
import h5py
import pandas as pd
import time
import os
import numpy as np
import pydicom as dicom
import cv2
import matplotlib.pyplot as plt
from ouluknee... |
'''
Code below is from OULU lab. It includes how they did the preprocessing and extract knee from
images
'''
def process_file(data,pad):
raw_img = data.pixel_array
r_, c_ = raw_img.shape
img = interpolate_resolution(data).astype(np.float64)
photoInterpretation = data[0x28, 0x04].value # return a str... | '''
Extrack knee part from image array
:param image_array:
:param side: 0: left knee; 1: right knee
:param offset: if does not work, you can manually change the shape
:return:
'''
#print('Dimensions of image: ', image_array.shape)
# Compute the sum of each row and column
col_sums = ... | identifier_body |
utils.py | import os
import numpy as np
import pydicom as dicom
import cv2
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
import scipy.ndimage as ndimage
import h5py
import pandas as pd
import time
import os
import numpy as np
import pydicom as dicom
import cv2
import matplotlib.pyplot as plt
from ouluknee... | # get data from Dicom file
tmp,ratio_c,ratio_r = process_file(data,pad)
I = tmp
# left knee coordinates
x1, y1, x2, y2 = bbox[:4] # apply padding to the frame of knee
cx = x1 + (x2 - x1) // 2 # compute center of x
cy = y1 + (y2 - y1) // 2 # compute cneter of y
# time the ratio
c... | if -1 in bbox: # if the algorithm says there is no knee in the figure.
return None,None
# process_xray | random_line_split |
utils.py | import os
import numpy as np
import pydicom as dicom
import cv2
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
import scipy.ndimage as ndimage
import h5py
import pandas as pd
import time
import os
import numpy as np
import pydicom as dicom
import cv2
import matplotlib.pyplot as plt
from ouluknee... | (image_dicom, scaling_factor=0.2):
'''
Obtain fixed resolution from image dicom
:param image_dicom:
:param scaling_factor:
:return:
'''
print('Obtain Fix Resolution:')
image_array = image_dicom.pixel_array
print(image_array.shape,np.mean(image_array),np.min(image_array),np.max(image_... | interpolate_resolution | identifier_name |
utils.py | import os
import numpy as np
import pydicom as dicom
import cv2
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
import scipy.ndimage as ndimage
import h5py
import pandas as pd
import time
import os
import numpy as np
import pydicom as dicom
import cv2
import matplotlib.pyplot as plt
from ouluknee... |
else:
before_x,after_x = 0,0
if y_padding > 0:
before_y,after_y = y_padding // 2, y_padding - y_padding // 2
else:
before_y,after_y = 0,0
return np.pad(img,((before_x,after_x),(before_y,after_y)),'constant'),before_x,before_y
def global_contrast_normalization_oulu(img,lim1,mult... | before_x,after_x = x_padding // 2, x_padding - x_padding // 2 | conditional_block |
Assignment 3 notes.py | import numpy as np
import pandas as pd
# Question 1 (20%)
def read_and_clean_energy_dataframe():
# ToDo: verify existance of data file
data_file = 'Energy Indicators.xls'
# Create energy dataframe
energy = pd.DataFrame()
# take only the country records and drop the unwanted first two colu... | # group and get stats
csize = pd.DataFrame(pop_stats.groupby('Continent')['Population Estimate'].size())
csum = pd.DataFrame(pop_stats.groupby('Continent')['Population Estimate'].sum())
cmean = pd.DataFrame(pop_stats.groupby('Continent')['Population Estimate'].mean())
cstd = pd.DataFrame(pop_stats... | """ Terribly ugly solution, but it works """ | random_line_split |
Assignment 3 notes.py | import numpy as np
import pandas as pd
# Question 1 (20%)
def read_and_clean_energy_dataframe():
# ToDo: verify existance of data file
data_file = 'Energy Indicators.xls'
# Create energy dataframe
energy = pd.DataFrame()
# take only the country records and drop the unwanted first two colu... | return res
print(test_gdp(GDP['Country']))
"""
# Alternative merge strategy
# merge the first two, then the third in the requested order
merged2 = pd.merge(ScimEn, energy, how='inner', left_index=True, right_index=True)
merged3 = pd.merge(merged2, GDP, how='inner', left_index=True, right_index=True)
result = (Sci... | s += '\nMismatched countries:\n'
mismatch = GDP.loc[GDP['tested'] != (GDP['actual']), [
'original', 'Country', 'tested', 'actual']].values.tolist()
res += '\n'.join('"{:}" miss-cleaned as "{:}"'.format(o, r)
for o, r, s, v in mismatch)
| conditional_block |
Assignment 3 notes.py | import numpy as np
import pandas as pd
# Question 1 (20%)
def read_and_clean_energy_dataframe():
# ToDo: verify existance of data file
data_file = 'Energy Indicators.xls'
# Create energy dataframe
energy = pd.DataFrame()
# take only the country records and drop the unwanted first two colu... | ():
# get the dataframes; all indexed to
energy = read_and_clean_energy_dataframe()
GDP = read_and_clean_GDP_dataframe()
ScimEn = read_and_clean_ScimEn_dataframe()
# merge sequence to get columns in the requested order
result = ScimEn.merge(energy, on='Country').merge(GDP, on='Country')
... | answer_one | identifier_name |
Assignment 3 notes.py | import numpy as np
import pandas as pd
# Question 1 (20%)
def read_and_clean_energy_dataframe():
# ToDo: verify existance of data file
data_file = 'Energy Indicators.xls'
# Create energy dataframe
energy = pd.DataFrame()
# take only the country records and drop the unwanted first two colu... | nswer_eight()
# Question 9 (6.6%)
"""
Create a column that estimates the number of citable documents per person. What is the correlation between the number of citable documents per capita and the energy supply per capita? Use the .corr() method, (Pearson's correlation).
This function should return a single number.
(... | 15 = answer_one()
Top15['Population Estimate'] = Top15['Energy Supply'] / Top15['Energy Supply per Capita']
Top15.sort_values('Population Estimate', ascending=False, inplace=True)
return Top15.iloc[2].name
a | identifier_body |
estimator.py | import collections
import datetime
import gin
import numpy as np
import os
import pprint
import re
import shutil
import tensorflow as tf
from absl import flags
from absl import logging
from thin.estimator_specs import TrainSpec
from thin.estimator_specs import EvalSpec
from thin.estimator_specs import PredictSpec
fro... | (self, batch_size, mode):
if mode == tf.estimator.ModeKeys.TRAIN:
return self._input_fn_train_or_eval(
training=True, batch_size=batch_size)
elif mode == tf.estimator.ModeKeys.EVAL:
return self._input_fn_train_or_eval(
training=False, batch_size=b... | input_fn | identifier_name |
estimator.py | import collections
import datetime
import gin
import numpy as np
import os
import pprint
import re
import shutil
import tensorflow as tf
from absl import flags
from absl import logging
from thin.estimator_specs import TrainSpec
from thin.estimator_specs import EvalSpec
from thin.estimator_specs import PredictSpec
fro... |
else:
gin_paths = []
gin.parse_config_files_and_bindings(gin_paths, FLAGS.gin_param)
estimator = Estimator()
getattr(estimator, FLAGS.do)()
class InputFn(object):
@staticmethod
def create_dir(base_dir):
dir_path = os.path.join(
base_dir,
datetime.date... | checkpoint_dir = FLAGS.checkpoint_dir
if checkpoint_dir is None:
checkpoint_dir = os.path.dirname(FLAGS.checkpoint_path)
gin_paths = [os.path.join(checkpoint_dir, _CONFIG_GIN)] | conditional_block |
estimator.py | import collections
import datetime
import gin
import numpy as np
import os
import pprint
import re
import shutil
import tensorflow as tf
from absl import flags
from absl import logging
from thin.estimator_specs import TrainSpec
from thin.estimator_specs import EvalSpec
from thin.estimator_specs import PredictSpec
fro... | return self._input_fn_train_or_eval(
training=False, batch_size=batch_size)
elif mode == tf.estimator.ModeKeys.PREDICT:
return self._input_fn_predict(
batch_size=batch_size)
class ModelFn(object):
def _get_global_step(self):
return tf_v1.tra... | if mode == tf.estimator.ModeKeys.TRAIN:
return self._input_fn_train_or_eval(
training=True, batch_size=batch_size)
elif mode == tf.estimator.ModeKeys.EVAL: | random_line_split |
estimator.py | import collections
import datetime
import gin
import numpy as np
import os
import pprint
import re
import shutil
import tensorflow as tf
from absl import flags
from absl import logging
from thin.estimator_specs import TrainSpec
from thin.estimator_specs import EvalSpec
from thin.estimator_specs import PredictSpec
fro... |
@property
def result_dir_root(self):
return os.path.join(self.root_dir, 'results')
@property
def split_dir_root(self):
return os.path.join(self.data_dir, 'splits')
@property
def tfrecord_dir_root(self):
return os.path.join(self.data_dir, 'tfrecords')
def _write_t... | return os.path.join(self.root_dir, 'models') | identifier_body |
settings.rs | use super::{
AddCertToStore, AddExtraChainCert, DerExportError, FileOpenFailed, FileReadFailed, MaybeTls,
NewStoreBuilder, ParsePkcs12, Pkcs12Error, PrivateKeyParseError, Result, SetCertificate,
SetPrivateKey, SetVerifyCert, TlsError, TlsIdentityError, X509ParseError,
};
use openssl::{
pkcs12::{ParsedPk... |
#[test]
fn from_options_ca() {
let options = TlsOptions {
ca_path: Some("tests/data/Vector_CA.crt".into()),
..Default::default()
};
let settings = TlsSettings::from_options(&Some(options))
.expect("Failed to load authority certificate");
asse... | {
let options = TlsOptions {
crt_path: Some(TEST_PEM_CRT.into()),
key_path: Some(TEST_PEM_KEY.into()),
..Default::default()
};
let settings =
TlsSettings::from_options(&Some(options)).expect("Failed to load PEM certificate");
assert!(settin... | identifier_body |
settings.rs | use super::{
AddCertToStore, AddExtraChainCert, DerExportError, FileOpenFailed, FileReadFailed, MaybeTls,
NewStoreBuilder, ParsePkcs12, Pkcs12Error, PrivateKeyParseError, Result, SetCertificate,
SetPrivateKey, SetVerifyCert, TlsError, TlsIdentityError, X509ParseError,
};
use openssl::{
pkcs12::{ParsedPk... | () {
let options = TlsOptions {
crt_path: Some(TEST_PKCS12.into()),
key_pass: Some("NOPASS".into()),
..Default::default()
};
let settings =
TlsSettings::from_options(&Some(options)).expect("Failed to load PKCS#12 certificate");
assert!(sett... | from_options_pkcs12 | identifier_name |
settings.rs | use super::{
AddCertToStore, AddExtraChainCert, DerExportError, FileOpenFailed, FileReadFailed, MaybeTls,
NewStoreBuilder, ParsePkcs12, Pkcs12Error, PrivateKeyParseError, Result, SetCertificate,
SetPrivateKey, SetVerifyCert, TlsError, TlsIdentityError, X509ParseError,
};
use openssl::{
pkcs12::{ParsedPk... | let name = crt_path.to_string_lossy().to_string();
let cert_data = open_read(crt_path, "certificate")?;
let key_pass: &str = options.key_pass.as_ref().map(|s| s.as_str()).unwrap_or("");
match Pkcs12::from_der(&cert_data) {
// Certifica... | let identity = match options.crt_path {
None => None,
Some(ref crt_path) => { | random_line_split |
calculate_profiles.py | import os
import re
import time
import numpy as np
import pandas as pd
from sklearn.cluster import AgglomerativeClustering
import math
import edlib
from progress.bar import IncrementalBar as Bar
from multiprocessing import Pool
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--pools",
... | (df_group, l, dst=dst_func):
sqs = df_group.reset_index()['sq']
n = len(sqs)
if n <= 1:
return np.zeros(n)
dst_matrix = np.zeros((n, n))
for i in range(n):
for j in range(i):
d = dst(sqs[i], sqs[j])
dst_matrix[i, j] = d
dst_matrix[j, i] = d
... | cluster_group | identifier_name |
calculate_profiles.py | import os
import re
import time
import numpy as np
import pandas as pd
from sklearn.cluster import AgglomerativeClustering
import math
import edlib
from progress.bar import IncrementalBar as Bar
from multiprocessing import Pool
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--pools",
... |
start = time.time()
# print(df.groupby(by='length').get_group(longest))
# print("running on shorter")
with Bar("Processing length groups...", max=len(unique_lengths) - 1) as bar:
for length in unique_lengths[1:]:
bar.next()
df_group = groups.get_group(length).copy()
def getDistanceAndAl... | against.append(alignment)
# df.loc[df['sq'].isin(cluster_df['sq']), 'alignment'] = alignment.ident
# to each sequence | random_line_split |
calculate_profiles.py | import os
import re
import time
import numpy as np
import pandas as pd
from sklearn.cluster import AgglomerativeClustering
import math
import edlib
from progress.bar import IncrementalBar as Bar
from multiprocessing import Pool
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--pools",
... |
def cluster_group(df_group, l, dst=dst_func):
sqs = df_group.reset_index()['sq']
n = len(sqs)
if n <= 1:
return np.zeros(n)
dst_matrix = np.zeros((n, n))
for i in range(n):
for j in range(i):
d = dst(sqs[i], sqs[j])
dst_matrix[i, j] = d
dst_m... | for line in open(filename):
sq, count = line.strip('\n').split(';')
yield sq, np.array([int(x) for x in count.split(',')]), count | identifier_body |
calculate_profiles.py | import os
import re
import time
import numpy as np
import pandas as pd
from sklearn.cluster import AgglomerativeClustering
import math
import edlib
from progress.bar import IncrementalBar as Bar
from multiprocessing import Pool
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--pools",
... |
i = offset
for base, count in zip(aligned_query, new_counts):
x[bases[base], i] += count
i += 1
self.profile = x
# store new sequence alignment
added_alignment = -np.ones(self.profile.shape[1])
for i, char in enumerate(nice['target_aligned']):
... | value = new_counts[index]
new_counts = np.insert(new_counts, index, value, axis=0) | conditional_block |
game.py | import os
import random
import sys
import numpy as np
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtCore import QCoreApplication, pyqtSlot, QSettings, Qt, QPoint, QByteArray, QSize, QObject
from PyQt5.QtGui import QFontDatabase, QFont, QMovie, QPixmap, QCursor
from PyQt5.QtWidgets import QMainWindow, QLabel
... | self.matrix, done = logic.down(self.matrix)
if done:
self.stateOfGame()
strokes.clear()
else:
return True
return self.frame.eventFilter(source, event)
# Μέθοδος για την αναπαραγωγή των ήχων
def playSound(self, sound):
... | if done:
self.stateOfGame()
elif strokeText == "D":
| conditional_block |
game.py | import os
import random
import sys
import numpy as np
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtCore import QCoreApplication, pyqtSlot, QSettings, Qt, QPoint, QByteArray, QSize, QObject
from PyQt5.QtGui import QFontDatabase, QFont, QMovie, QPixmap, QCursor
from PyQt5.QtWidgets import QMainWindow, QLabel
... | ockSignals(False)
self.init_grid()
c.SCORE = 0
self.lScore.setText(str(c.SCORE))
self.matrix = logic.new_game(c.GRID_LEN)
self.history_matrixs = []
self.update_grid_cells()
pyqtSlot()
def on_bExit_clicked(self):
self.saveStates()
self.movie.jumpTo... | -1]
else:
lst=self.settings().value("gameState")
nums=[]
for i in range(len(lst)):
for j in range(len(lst[0])):
if lst[i][j]!=0:
nums.append(lst[i][j])
print(nums)
return nums
def bHelpClicked(self):
helpDlg... | identifier_body |
game.py | import os
import random
import sys
import numpy as np
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtCore import QCoreApplication, pyqtSlot, QSettings, Qt, QPoint, QByteArray, QSize, QObject
from PyQt5.QtGui import QFontDatabase, QFont, QMovie, QPixmap, QCursor
from PyQt5.QtWidgets import QMainWindow, QLabel
... | def __init__(self, parent=None):
# Αρχικοποίηση του γραφικού περιβάλλοντος
super(Game, self).__init__(parent)
print(APP_FOLDER)
self.setupUi(self)
c.SCORE=self.settings().value("score", 0, type=int)
# Μεταβλητές
self.points = []
self.speed = 30
... |
def settings(self):
settings = QSettings()
return settings
| random_line_split |
game.py | import os
import random
import sys
import numpy as np
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtCore import QCoreApplication, pyqtSlot, QSettings, Qt, QPoint, QByteArray, QSize, QObject
from PyQt5.QtGui import QFontDatabase, QFont, QMovie, QPixmap, QCursor
from PyQt5.QtWidgets import QMainWindow, QLabel
... | history_matrixs[-1]
else:
lst=self.settings().value("gameState")
nums=[]
for i in range(len(lst)):
for j in range(len(lst[0])):
if lst[i][j]!=0:
nums.append(lst[i][j])
print(nums)
return nums
def bHelpClicked(self):... | = self. | identifier_name |
key.go | package keyvault
import (
"artificer/pkg/api/renderings"
"artificer/pkg/config"
"artificer/pkg/iam"
"artificer/pkg/util"
"context"
b64 "encoding/base64"
"errors"
"fmt"
"sort"
"strings"
"time"
"log"
"github.com/Azure/azure-sdk-for-go/services/keyvault/v7.0/keyvault"
azKeyvault "github.com/Azure/azure-sd... |
func DoKeyvaultBackground() (err error) {
now := time.Now().UTC()
fmt.Println(fmt.Sprintf("Start-DoKeyvaultBackground:%s", now))
ctx := context.Background()
activeKeys, currentKeyBundle, err := GetActiveKeysVersion(ctx)
if err != nil {
return
}
resp := renderings.WellKnownOpenidConfigurationJwksResponse{}
... | {
var cachedItem interface{}
var found bool
cachedItem, found = cache.Get(cacheKey)
if !found {
err = DoKeyvaultBackground()
if err != nil {
log.Fatalf("failed to DoKeyvaultBackground: %v\n", err.Error())
return
}
cachedItem, found = cache.Get(cacheKey)
if !found {
err = errors.New("critical f... | identifier_body |
key.go | package keyvault
import (
"artificer/pkg/api/renderings"
"artificer/pkg/config"
"artificer/pkg/iam"
"artificer/pkg/util"
"context"
b64 "encoding/base64"
"errors"
"fmt"
"sort"
"strings"
"time"
"log"
"github.com/Azure/azure-sdk-for-go/services/keyvault/v7.0/keyvault"
azKeyvault "github.com/Azure/azure-sd... | (base64EncodedE string) string {
sDec, _ := b64.StdEncoding.DecodeString(base64EncodedE)
sDec = forceByteArrayLength(sDec, 4)
sEnc := b64.StdEncoding.EncodeToString(sDec)
parts := strings.Split(sEnc, "=")
sEnc = parts[0]
return sEnc
}
func forceByteArrayLength(slice []byte, requireLength int) []byte {
n := len(... | fixE | identifier_name |
key.go | package keyvault
import (
"artificer/pkg/api/renderings"
"artificer/pkg/config"
"artificer/pkg/iam"
"artificer/pkg/util"
"context"
b64 "encoding/base64"
"errors"
"fmt"
"sort"
"strings"
"time"
"log"
"github.com/Azure/azure-sdk-for-go/services/keyvault/v7.0/keyvault"
azKeyvault "github.com/Azure/azure-sd... | azKeyvault.Encrypt,
azKeyvault.Decrypt,
},
Kty: azKeyvault.EC,
})
}
func fixE(base64EncodedE string) string {
sDec, _ := b64.StdEncoding.DecodeString(base64EncodedE)
sDec = forceByteArrayLength(sDec, 4)
sEnc := b64.StdEncoding.EncodeToString(sDec)
parts := strings.Split(sEnc, "=")
sEnc = parts[0]
... | Enabled: to.BoolPtr(true),
},
KeySize: to.Int32Ptr(2048), // As of writing this sample, 2048 is the only supported KeySize.
KeyOps: &[]azKeyvault.JSONWebKeyOperation{ | random_line_split |
key.go | package keyvault
import (
"artificer/pkg/api/renderings"
"artificer/pkg/config"
"artificer/pkg/iam"
"artificer/pkg/util"
"context"
b64 "encoding/base64"
"errors"
"fmt"
"sort"
"strings"
"time"
"log"
"github.com/Azure/azure-sdk-for-go/services/keyvault/v7.0/keyvault"
azKeyvault "github.com/Azure/azure-sd... |
}
}
if !pageResult.NotDone() {
break
}
err = pageResult.Next()
if err != nil {
return
}
}
sort.Slice(finalResult[:], func(i, j int) bool {
notBeforeA := time.Time(*finalResult[i].Attributes.NotBefore)
notBeforeB := time.Time(*finalResult[j].Attributes.NotBefore)
return notBeforeA.After(n... | {
parts := strings.Split(*element.Kid, "/")
lastItemVersion := parts[len(parts)-1]
keyBundle, er := keyClient.GetKey(ctx,
keyVaultUrl,
keyIdentifier,
lastItemVersion)
if er != nil {
err = er
return
}
fixedE := fixE(*keyBundle.Key.E)
*keyBundle.Key.E = fi... | conditional_block |
layout_rope.rs | //! A rope-based vector of layouts.
use std::ops::Range;
use std::sync::Arc;
use druid::piet::{PietTextLayout, TextLayout};
use xi_rope::interval::{Interval, IntervalBounds};
use xi_rope::tree::{Cursor, DefaultMetric, Leaf, Metric, Node, NodeInfo, TreeBuilder};
/// A type representing a height measure.
///
/// Inte... | (&mut self, index: usize) {
let mut b = TreeBuilder::new();
self.push_subseq(&mut b, Interval::new(0, index));
self.push_subseq(&mut b, Interval::new(index + 1, self.len()));
self.0 = b.build();
}
pub fn set(&mut self, index: usize, item: Layout) {
let mut b = TreeBuilde... | remove | identifier_name |
layout_rope.rs | //! A rope-based vector of layouts.
use std::ops::Range;
use std::sync::Arc;
use druid::piet::{PietTextLayout, TextLayout};
use xi_rope::interval::{Interval, IntervalBounds};
use xi_rope::tree::{Cursor, DefaultMetric, Leaf, Metric, Node, NodeInfo, TreeBuilder};
/// A type representing a height measure.
///
/// Inte... |
fn push_subseq(&self, b: &mut TreeBuilder<LayoutInfo>, iv: Interval) {
// TODO: if we make the push_subseq method in xi-rope public, we can save some
// allocations.
b.push(self.0.subseq(iv));
}
}
impl LayoutRopeBuilder {
pub fn new() -> LayoutRopeBuilder {
LayoutRopeBuild... | {
self.0
.count_base_units::<HeightMetric>(height.as_raw_frac())
} | identifier_body |
layout_rope.rs | //! A rope-based vector of layouts.
use std::ops::Range;
use std::sync::Arc;
use druid::piet::{PietTextLayout, TextLayout};
use xi_rope::interval::{Interval, IntervalBounds};
use xi_rope::tree::{Cursor, DefaultMetric, Leaf, Metric, Node, NodeInfo, TreeBuilder};
/// A type representing a height measure.
///
/// Inte... |
}
}
impl From<Vec<(Height, Arc<Layout>)>> for LayoutRope {
fn from(v: Vec<(Height, Arc<Layout>)>) -> Self {
LayoutRope(Node::from_leaf(LayoutLeaf { data: v }))
}
}
impl LayoutRope {
/// The number of layouts in the rope.
pub fn len(&self) -> usize {
self.0.len()
}
/// The... | {
let splitpoint = self.len() / 2;
let right_vec = self.data.split_off(splitpoint);
Some(LayoutLeaf { data: right_vec })
} | conditional_block |
layout_rope.rs | //! A rope-based vector of layouts.
use std::ops::Range;
use std::sync::Arc;
use druid::piet::{PietTextLayout, TextLayout};
use xi_rope::interval::{Interval, IntervalBounds};
use xi_rope::tree::{Cursor, DefaultMetric, Leaf, Metric, Node, NodeInfo, TreeBuilder};
/// A type representing a height measure.
///
/// Inte... | type Output = Self;
fn add(self, other: Self) -> Self {
Height(self.0 + other.0)
}
}
impl std::ops::AddAssign for Height {
fn add_assign(&mut self, other: Self) {
self.0 += other.0
}
}
impl Height {
/// The number of fractional bits in the representation.
pub const HEIGHT_... | random_line_split | |
switching_utils.py | """
Utility functions for setting up, conducting, and analyzing
model switching experiments.
"""
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import tensorflow as tf
import pickle
import datetime
import contextlib
import time
from interact_drive.car import PlannerCar
with co... | (reward_ts, model_ts):
'''
Displays reward for each time step gained by the car
in a plot. Color codes by model used and presents
an appropriate legend.
'''
plt.title("Reward by Model")
start_time = 0
cur_model = model_ts[0]
used_models = [cur_model]
for t, model in enumerate(m... | display_rewards | identifier_name |
switching_utils.py | """
Utility functions for setting up, conducting, and analyzing
model switching experiments.
"""
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import tensorflow as tf
import pickle
import datetime
import contextlib
import time
from interact_drive.car import PlannerCar
with co... |
return planner_type, planner_args
| raise Exception(f"Invalid Experiment Type: {exp_type}") | conditional_block |
switching_utils.py | """
Utility functions for setting up, conducting, and analyzing
model switching experiments.
"""
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import tensorflow as tf
import pickle
import datetime
import contextlib
import time
from interact_drive.car import PlannerCar
with co... | def execute_many_experiments(exp_name, world, time_steps, experiment_args,
ms_car_index = 0):
switching_parameters = {"comp_times": {"Naive": experiment_args.naive_ct,
"Turn": experiment_args.turn_ct,
... | clip.speedx(0.5).write_gif(f"{exp_name}.gif", program="ffmpeg")
#return np.mean(reward_ts), avg_step_times['overall'][-1], model_usage
return reward_ts
| random_line_split |
switching_utils.py | """
Utility functions for setting up, conducting, and analyzing
model switching experiments.
"""
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import tensorflow as tf
import pickle
import datetime
import contextlib
import time
from interact_drive.car import PlannerCar
with co... |
def display_rewards(reward_ts, model_ts):
'''
Displays reward for each time step gained by the car
in a plot. Color codes by model used and presents
an appropriate legend.
'''
plt.title("Reward by Model")
start_time = 0
cur_model = model_ts[0]
used_models = [cur_model]
for t... | switching_parameters = {"comp_times": {"Naive": experiment_args.naive_ct,
"Turn": experiment_args.turn_ct,
"Tom": experiment_args.tom_ct},
"cooldowns": {"up": experiment_args.up_cd,
... | identifier_body |
sectioning.js | var app = angular.module('sectioningStation', ['ui.bootstrap','ngCookies']);
app.controller('SectionController',function($scope,$http,$window,$cookieStore)
{
//var URL_BASE="http://10.11.3.3:8080/Sample_Tracker/webapi/";
//var URL_BASE="http://pushd.healthelife.in:8080/Sample_Tracker/webapi/";
var URL_BASE="h... | $scope.assetTasksTable=data;
console.log($scope.assetTable);
})
}
$scope.getCompletedTasks=function()
{
$scope.scanTissue=false;
$scope.completedTissue=true;
$scope.pendingTissue=false;
$scope.label="Completed Assets";
$scope.as... | $http.get(url)
.success(function (data) { | random_line_split |
Object_detection_image.py | #Author: Supun Sethsara
#Based on folowing methods following works
#https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10
# Author: Evan Juras
# Date: 1/15/18
# Description:
# This program uses a TensorFlow-trained classifier to perform object detection.
# It l... |
# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")
# Import utilites(utils folder)
from utils import label_map_util
from utils import visualization_utils as vis_util
#CGFC_functions folder
from CGFC_functions import colorDetector as color_Detector
from CGFC_functions ... | #import__color recognition
from sklearn.cluster import KMeans
from sklearn import metrics
| random_line_split |
Object_detection_image.py | #Author: Supun Sethsara
#Based on folowing methods following works
#https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10
# Author: Evan Juras
# Date: 1/15/18
# Description:
# This program uses a TensorFlow-trained classifier to perform object detection.
# It l... |
#Cloth detection whole process start from here
def ClothDetectionAnalyse(image,tagData,gender):
min_score_thresh=CGFCConfig.min_score_thresh
detectedData=Detect_Cloths(image)
boxes=detectedData['boxes'][0]
scores=detectedData['scores'][0]
classes=detectedData['classes'][0]
print("##########... | dominet_colors=color_Detector.dominant_color_detector(crop_img,3) | identifier_body |
Object_detection_image.py | #Author: Supun Sethsara
#Based on folowing methods following works
#https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10
# Author: Evan Juras
# Date: 1/15/18
# Description:
# This program uses a TensorFlow-trained classifier to perform object detection.
# It l... | (image,tagData,gender):
min_score_thresh=CGFCConfig.min_score_thresh
detectedData=Detect_Cloths(image)
boxes=detectedData['boxes'][0]
scores=detectedData['scores'][0]
classes=detectedData['classes'][0]
print("###################################################################################")... | ClothDetectionAnalyse | identifier_name |
Object_detection_image.py | #Author: Supun Sethsara
#Based on folowing methods following works
#https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10
# Author: Evan Juras
# Date: 1/15/18
# Description:
# This program uses a TensorFlow-trained classifier to perform object detection.
# It l... |
crop_image_Data = pd.DataFrame()
for index,bbox in enumerate(bestBBox):
crop_img=cropDetectedCloths(image,bbox)
dominet_colors=color_Detector.dominant_color_detector(crop_img,3)
colors=[]
colorMax=dominet_colors[0]
#print("dominet_colors ... | if ((score>=min_score_thresh) &(className in category_Dic.Attributes)):
bestResults.append(index)
bestBBox.append(normBBoxes[index])
bestScores.append(score)
bestClasses.append(normClasses[index]) | conditional_block |
all8a54.js | ;(function($) {
"use strict";
/*============================*/
/* SWIPER SLIDE */
/*============================*/
var swipers = [], winW, winH, winScr, _isresponsive, smPoint = 480, mdPoint = 992, lgPoint = 1200, addPoint = 1600, _ismobile = navigator.userAgent.match(/Android/i) || navigator.userAgent.matc... | (data){
if (data.status == 'ok') {
var popup_cont = '';
if (data.type == 'ajax') {
if (data.thumbnail) popup_cont += data.thumbnail;
popup_cont += '<div class="team-desc">';
popup_cont += ' <div class="title">';
popup_cont += ' <h4>' + data.time + '</h4>';
popup_cont += ' <h2>' + data.... | render_content | identifier_name |
all8a54.js | ;(function($) {
"use strict";
/*============================*/
/* SWIPER SLIDE */
/*============================*/
var swipers = [], winW, winH, winScr, _isresponsive, smPoint = 480, mdPoint = 992, lgPoint = 1200, addPoint = 1600, _ismobile = navigator.userAgent.match(/Android/i) || navigator.userAgent.matc... |
if ($('.home-slider.anime-slide').length) {
$('.home-slider.anime-slide').closest('.vc_row').addClass('nrg-prod-row-full-height');
};
if ($('.home-slider.arrow-center').length) {
$('.home-slider.arrow-center').closest('.vc_row').addClass('nrg-prod-row-full-height');
};
pageCalculations();
function upda... | {
winW = $(window).width();
winH = $(window).height();
} | identifier_body |
all8a54.js | ;(function($) {
"use strict";
/*============================*/
/* SWIPER SLIDE */
/*============================*/
var swipers = [], winW, winH, winScr, _isresponsive, smPoint = 480, mdPoint = 992, lgPoint = 1200, addPoint = 1600, _ismobile = navigator.userAgent.match(/Android/i) || navigator.userAgent.matc... |
})(jQuery); | {
var pageNum = parseInt(load_more_post.startPage) + 1;
// The maximum number of pages the current query can return.
var max = parseInt(load_more_post.maxPages);
// The link of the next page of posts.
var nextLink = load_more_post.nextLink;
$('.load-more').on('click', function () ... | conditional_block |
all8a54.js | ;(function($) {
"use strict";
/*============================*/
/* SWIPER SLIDE */
/*============================*/
var swipers = [], winW, winH, winScr, _isresponsive, smPoint = 480, mdPoint = 992, lgPoint = 1200, addPoint = 1600, _ismobile = navigator.userAgent.match(/Android/i) || navigator.userAgent.matc... |
$('#pop_up').find('.popup').html('<div class="team-desc"><div class="title"><h1>'+data.error+'</h1></div></div>');
$('.preload').fadeOut();
$.fancybox( '#pop_up');
}
}
if ($(".fancybox").length){
// open popup. use fancybox
$(document).on('click','.fancybox', function(){
$.fancybox.close();
... | }
} );
} else { | random_line_split |
test_dbinterface.py | """Test DBInterface."""
import os
import re
import sys
import time
import errno
import shutil
import logging
import pymongo
import unittest
import pdb
import tensorflow as tf
import mnist_data as data
sys.path.insert(0, "..")
import tfutils.base as base
import tfutils.model as model
import tfutils.optimizer as opti... |
def test_filter_var_list(self):
var_list = {var.op.name: var for var in tf.global_variables()}
# Test None
self.dbinterface.to_restore = None
filtered_var_list = self.dbinterface.filter_var_list(var_list)
self.assertEqual(filtered_var_list, var_list)
# Test list ... | self.log.info('(name, var.name): ({}, {})'.format(name, var.name))
self.assertEqual(var.op.name, mapping[name]) | conditional_block |
test_dbinterface.py | """Test DBInterface."""
import os
import re
import sys
import time
import errno
import shutil
import logging
import pymongo
import unittest
import pdb
import tensorflow as tf
import mnist_data as data
sys.path.insert(0, "..")
import tfutils.base as base
import tfutils.model as model
import tfutils.optimizer as opti... | """
self.setup_model()
self.sess = tf.Session(
config=tf.ConfigProto(
allow_soft_placement=True,
gpu_options=tf.GPUOptions(allow_growth=True),
log_device_placement=self.params['log_device_placement'],
))
# TODO:... |
Creates a tensorflow session and instantiates a dbinterface.
| random_line_split |
test_dbinterface.py | """Test DBInterface."""
import os
import re
import sys
import time
import errno
import shutil
import logging
import pymongo
import unittest
import pdb
import tensorflow as tf
import mnist_data as data
sys.path.insert(0, "..")
import tfutils.base as base
import tfutils.model as model
import tfutils.optimizer as opti... | (self):
self.log.info('Saving checkpoint to {}'.format(self.save_path))
saved_checkpoint_path = self.dbinterface.tf_saver.save(self.sess,
save_path=self.save_path,
global_step=se... | save_test_checkpoint | identifier_name |
test_dbinterface.py | """Test DBInterface."""
import os
import re
import sys
import time
import errno
import shutil
import logging
import pymongo
import unittest
import pdb
import tensorflow as tf
import mnist_data as data
sys.path.insert(0, "..")
import tfutils.base as base
import tfutils.model as model
import tfutils.optimizer as opti... |
def tearDownModule():
"""Tear down module after all TestCases are run."""
pass
# logPoint('module %s' % __name__)
class TestDBInterface(unittest.TestCase):
PORT = 29101
HOST = 'localhost'
EXP_ID = 'TEST_EXP_ID'
DATABASE_NAME = 'TFUTILS_TESTDB'
COLLECTION_NAME = 'TFUTILS_TESTCOL'
... | """Set up module once, before any TestCases are run."""
logging.basicConfig()
# logPoint('module %s' % __name__) | identifier_body |
space_invaders.py | #!/usr/local/bin/python3
from time import time
import pygame
#
SECONDS_TO_MICRO_SECONDS = 1000000
#
TUPLE_COLOR_BLACK = (0, 0, 0)
TUPLE_COLOR_GREEN = (0, 226, 143)
TUPLE_COLOR_RED = (226, 70, 70)
#
IMAGE_BIG_MAC = "big_mac_small.png"
IMAGE_RICHARD_SIMMONS = "richard_simmons_small_2.png"
# Frames per second
TIME_TICK_... |
# Return front ships
def get_front_line_ships(self):
return self.front_line
# Evenly space out ships within initial allowed range
def setup_ships(self):
start_bottom_edge = int(
float(HEIGHT_FRAME_OPPONENTS) * FACTOR_HEIGHT_FRAME_OPPONENTS)
horizontal_separation = ... | self.direction = DIRECTION_RIGHT
self.direction_previous = self.direction
self.screen = screen
self.row_and_column_size = row_and_column_size
self.ships = {}
self.left = {}
self.right = {}
self.front_line = {}
self.setup_ships() | identifier_body |
space_invaders.py | #!/usr/local/bin/python3
from time import time
import pygame
#
SECONDS_TO_MICRO_SECONDS = 1000000
#
TUPLE_COLOR_BLACK = (0, 0, 0)
TUPLE_COLOR_GREEN = (0, 226, 143)
TUPLE_COLOR_RED = (226, 70, 70)
#
IMAGE_BIG_MAC = "big_mac_small.png"
IMAGE_RICHARD_SIMMONS = "richard_simmons_small_2.png"
# Frames per second
TIME_TICK_... |
if r == (self.row_and_column_size - 1):
self.right[id] = ship
if c == (self.row_and_column_size - 1):
self.front_line[id] = ship
self.ships[id] = ship
# Check whether left or right ships reached allowed edge/coordinates
de... | self.left[id] = ship | conditional_block |
space_invaders.py | #!/usr/local/bin/python3
from time import time
import pygame
#
SECONDS_TO_MICRO_SECONDS = 1000000
#
TUPLE_COLOR_BLACK = (0, 0, 0)
TUPLE_COLOR_GREEN = (0, 226, 143)
TUPLE_COLOR_RED = (226, 70, 70)
#
IMAGE_BIG_MAC = "big_mac_small.png"
IMAGE_RICHARD_SIMMONS = "richard_simmons_small_2.png"
# Frames per second
TIME_TICK_... | self.winner_text.set_location(
WIDTH_SCREEN // 2, HEIGHT_SCREEN // 2)
def update(self):
self.background.redraw()
#
self.update_winner()
if self.winner == WINNER_NONE:
#
self.check_collisions()
self.clean_up()
... | self.screen, text, color, "arial", 60) | random_line_split |
space_invaders.py | #!/usr/local/bin/python3
from time import time
import pygame
#
SECONDS_TO_MICRO_SECONDS = 1000000
#
TUPLE_COLOR_BLACK = (0, 0, 0)
TUPLE_COLOR_GREEN = (0, 226, 143)
TUPLE_COLOR_RED = (226, 70, 70)
#
IMAGE_BIG_MAC = "big_mac_small.png"
IMAGE_RICHARD_SIMMONS = "richard_simmons_small_2.png"
# Frames per second
TIME_TICK_... | (self):
pygame.init()
self.init_winner()
self.init_screen()
self.init_human_ship()
self.init_opponent_squadron()
def init_winner(self):
self.winner = WINNER_NONE
self.winner_text = None
def init_screen(self):
self.screen = pygame.display.set_mode... | __init__ | identifier_name |
full-site.js | var failCount = 0;
var onLogoutRemoveIds = [];
var reoloadPageForChat = false;
/**
* @author Gehad Mohamed
*/
function showLoginPopUp(){
if(!isLoggedIn){
$('#login-popup').lightcase('start',{
href: "#login-popup",
liveResize:true,
maxHeight:1000,
onClo... | function sharePopup(url, w, h) {
var left = (screen.width / 2) - (w / 2);
var top = (screen.height / 2) - (h / 2);
return window.open(url, "share window", 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, copyhistory=no, width=' + w + ', height=' + h + ', top='... | });
| random_line_split |
full-site.js | var failCount = 0;
var onLogoutRemoveIds = [];
var reoloadPageForChat = false;
/**
* @author Gehad Mohamed
*/
function showLoginPopUp(){
if(!isLoggedIn){
$('#login-popup').lightcase('start',{
href: "#login-popup",
liveResize:true,
maxHeight:1000,
onClo... |
function getprayerTimeData() {
$.ajax({
url: getPrayerInfoUrl,
success: preparePrayerTimeWidget
});
}
// increaseFontSize and decreaseFontSize
var min = 16;
var max = 20;
function increaseFontSize() {
var p = $('.details-text');
for (i = 0; i < p.length; i++... | {
document.getElementById('form_email').value = "";
// $('#form_email').css('text-indent', '35px');
$('#form-modal .help-error').remove();
$('#form-modal .form-group').removeClass('is-invalid');
$('#form-modal').modal('show');
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.