language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 1,256 | 3.09375 | 3 |
[] |
no_license
|
#!/bin/python
print ('Counselor? Andrea[a] / Eric[e]')
x2 = raw_input()
if x2 == 'a':
counselorname = "Andrea Montague"
counseloremail = "andrea.montague@du.edu"
else:
counselorname = "Eric Bono"
counseloremail = "eric.bono@du.edu"
print('Time?')
apptime = raw_input().strip()
print('AM/PM?')
appampm = raw_input().strip()
print('Student Name?')
studentname = raw_input().strip()
print ('Date?')
appdate = raw_input().strip()
print("Now for the results . . .")
print("The counselor is "+counselorname)
print(appdate)
print(apptime)
print(appampm)
print("The student is "+studentname)
#
# with open('rawappt.txt') as f:
# lines = f.readlines()
# apptint = 0
# for line in lines:
# x,y = line.split(':', 1)
# print(y.strip())
# apptint += 1
# if apptint == 1:
# counselorname = y.strip()
# elif apptint == 2:
# apprawtime, appdate = y.strip().split("on")
# apptime, appampm = apprawtime.strip().split(" ")
# elif apptint == 3:
# studentname = y.strip()
#
# print("Now for the results . . .")
# print("The counselor is "+counselorname)
# print(appdate)
# print(apptime)
# print(appampm)
# print("The student is "+studentname)
|
Python
|
UTF-8
| 1,560 | 2.546875 | 3 |
[] |
no_license
|
#! /usr/bin/env python
import os, sys, re, glob, argparse
import zopy.dictation as d
file = sys.argv[1]
# ---------------------------------------------------------------
# prints
# ---------------------------------------------------------------
def print1 ( d ):
for key, val in d.items():
print key, "-->", val
print
def print2 ( d ):
for key, d2 in d.items():
print key
for key2, val in d2.items():
print " ", key2, "-->", val
print
# ---------------------------------------------------------------
# col2dict tests
# ---------------------------------------------------------------
print "col2dict tests"
os.system( "head %s" % ( file ) )
print1( d.col2dict( file ) )
print1( d.col2dict( file, headers=True ) )
print1( d.col2dict( file, key=1, headers=True ) )
print1( d.col2dict( file, key=1, value=2, headers=True ) )
print1( d.col2dict( file, key=1, func=lambda row: float( row[2] ), headers=True ) )
# ---------------------------------------------------------------
# col2dict2 tests
# ---------------------------------------------------------------
print "col2dict2 tests"
os.system( "head %s" % ( file ) )
print2( d.col2dict2( file ) )
print2( d.col2dict2( file, headers=True, mirror=True ) )
print2( d.col2dict2( file, headers=True, mirror=True, func=lambda row: float( row[2] ) ) )
print1( d.col2dict2( file, headers=True, func=lambda row: float( row[2] ), tupledict=True ) )
print1( d.col2dict2( file, headers=True, func=lambda row: float( row[2] ), tupledict=True, mirror=True ) )
|
Markdown
|
UTF-8
| 7,987 | 2.796875 | 3 |
[] |
no_license
|
# EsameGennaio2020
Repository dedicata all'esame di Programmazione ad Oggetti del 20 gennaio 2020.
È stata effettuata una revisione del codice precedentemente caricato (Dicembre 2019). In particolare:
È stata migliorata l'organizzazione nei package; le classi AppService e Filters sono state modificate tramite l'aggiunta di nuovi metodi e una revisione dei precedenti; i vecchi diagrammi UML sono stati sostituiti; sono state inoltre aggiunte nuove funzionalità per le rotte di tipo POST e DELETE.
Il progetto in questione fornisce un'applicazione WEB in JAVA, implementata attraverso l'utilizzo di SpringBoot, che prevede la modellazione di un dataset in formato TSV reperibile al seguente URL: http://data.europa.eu/euodp/data/api/3/action/package_show?id=3h1d8YdPl3KCgkeQNbjkA
# Inizializzazione Dataset
All’avvio del programma viene eseguita l’elaborazione del dataset attraverso la classe _Utils_, che decodifica il JSON dell'URL sopra indicato per poi effettuarne il download e successivamente il parsing.
Il risultato è l’organizzazione dei dati in una tabella le cui righe rappresentano gli elementi del dataset in questione.
Ogni riga (elemento) è contraddistinta da un indice che ne precisa la rispettiva posizione all'interno della struttura dati e contiene dei valori riguardanti informazioni statistiche sulla popolazione; tali informazioni sono organizzate come segue:
• I primi cinque campi di ogni elemento contengono attributi di tipo stringa e sono identificati da
`duration deg_urb sex age unit`
• Il campo `timegeo` contiene attributi di tipo int.
• I successivi campi contengono attributi di tipo float.
`EU28 BE BG CZ DK DE EE IE EL ES FR HR IT CY LV LT LU HU MT NL AT PL PT RO SI SK FI SE UK IS NO TR`
# Avvio
L’applicazione avvia un web-server in locale sulla porta 8080 che rimane in attesa di richieste.
Selezionando la rotta desiderata (GET, POST o DELETE) è possibile inserire delle richieste che prevedono la restituzione di particolari dati a seconda del comando desiderato.
URL per l’applicazione:
> _/http//localhost:8080_
# GET
Selezionando la rotta GET si possono immettere i seguenti comandi:
**Restituzione Dati**
• ` /data` -> restituisce tutti gli elementi del dataset, ognuno con le rispettive specifiche.
• ` /data/{index}` -> restituisce le specifiche dell’i-esimo elemento.
• ` /metadata` -> restituisce i metadati, evidenziando il nome dei rispettivi campi (field) e il tipo di valore contenuto al suo interno.
**Restituzione Statistiche**
Per ogni campo contenente un valore di tipo _float_ è possibile eseguire delle operazioni matematiche tramite le seguenti richieste:
• `/sum/{field}` -> restituisce la somma di tutti i valori contraddistinti dal campo _field_
• `/min/{field}` -> restituisce il minimo tra tutti i valori contraddistinti dal campo _field_
• `/max/{field}` -> restituisce il massimo tra tutti i valori contraddistinti dal campo _field_
• `/avg/{field}` -> restituisce la media aritmetica dei valori contraddistinti dal campo _field_
• `/devstd/{field}` -> restituisce la deviazione standard dei valori contraddistinti dal campo _field_
• `/stats/{field}`-> restituisce l'elenco delle statistiche sopra riportate per il _field_ scelto
Esempio:
>_/min/EU28_ = 1.3 -> restituisce il più piccolo dei valori contenuti nella colonna EU28
> _/average/IT_ = 44.705803 -> restituisce la media dei valori presenti nella colonna IT
**Filtri semplici:**
Al contrario delle statistiche, le operazioni di filtraggio possono essere eseguite per tutti i campi. In particolare è possibile effettuare le seguenti richieste:
- Per attributi di tipo stringa -> `/stringFilter/{field}/{word}`
Restituisce tutti gli elementi che contengono nel rispettivo campo _field_ la stringa _word_
Esempio:
> _/stringFilter/EU28/NEV_' -> restituisce tutti gli elementi contenenti la stringa NEV nella colonna EU28.
- Per gli attributi numerici -> `/valueFilter/{field}/{operator}/{value}`
_operator_ rappresenta l’operatore di confronto; può essere scelto **>**, **<**, **=**.
_value_ rappresenta il valore di soglia da confrontare.
Restituisce tutti gli elementi che rispettano la condizione imposta dal confronto.
Esempio:
> _/valueFilter/EU28/>/50_ -> restituisce tutti gli elementi i cui valori nella colonna EU28 sono maggiori di 50.
> _/valueFilter/timegeo/=/2014_ -> restituisce tutti gli elementi i cui valori nella colonna timegeo sono uguali 2014.
**Filtri combinati:**
- Filtro numerico -> `/valueFilter/{field}/{operator1}/{value1}/{logicOperator}/{operator2}/{value2}`
Rappresenta una combinazione di due filtri numerici mostrati sopra.
• _logicOperator_ indica l'operatore logico; può essere scelto **and** o **or** a seconda che si vogliano rispettare entrambe le condizioni o solamente una delle due (intersezione o unione degli elementi filtrati).
• _operator1_ e _operator2_ sono gli operatori di confronto precedentemente indicati.
• _value1_ _value2_ sono i valori da confrontare.
Restituisce l'elenco degli elementi che soddisfano i requisiti imposti.
Esempio:
> _/valueFilter/EU28/>/50/or/</20_ -> restituisce gli elementi i cui valori nella colonna EU28 sono maggiori di 50 o minori di 20
> _/valueFilter/EU28/>/50/and/</20_ -> restituisce gli elementi i cui valori nella colonna EU28 sono contemporaneamente maggiori di 50 e minori di 20
- Filtro combinato -> `/filter/{field1}/{word}/{field2}/{operator}/{value}`
Rappresenta una combinazione di un filtro numerico e un filtro stringa.
• _field1_ e _field2_ sono i campi contenenti rispettivamente attributi di tipo stringa e attributi numerici.
• _word_ rappresenta la stringa da confrontare mentre _value_ rappresenta il valore di soglia.
Restituisce l'elenco di elementi che contengono la stringa _word_ nella colonna _field1_ e allo stesso tempo rispettano la condizione imposta dal confronto numerico.
Esempio:
> _/filter/duration/NEV/EU28/</50_ -> restituisce tutti gli elementi che contengono NEV nella colonna duration e allo stesso tempo contengono un valore minore di 50 nella colonna EU28
# POST
Selezionando la rotta POST è possibile **inserire nuovi dati** in formato JSON tramite la richiesta: `/data`
Una volta inviata, occorre spostarsi nel campo **Body** selezionare **raw** e scegliere il formato JSON nel menu **Text**; fatto ciò basterà scrivere i nuovi dati racchiusi da parentesi graffe, come da esempio:
{"duration":"word1","deg_urb":"word2","sex":"word3" ... }
Dove _word1_, _word2_, _word3_ rappresentano i nuovi valori da inserire
# DELETE
Attraverso la rotta DELETE è possibile eliminare uno o più elementi del dataset, a seconda delle specifiche richieste.
**Eliminazione di un singolo elemento**
`/deleteElement/{index}`
• _index_ rappresenta la posizione dell'elemento da eliminare
Dopo averlo rimosso dal dataset, restituisce l'elemento identificato dall'indice i
**Eliminazione di più elementi filtrati**
`/deletefilter/{field}/{operator}/{value}`
• _field_ rappresenta il campo su cui effettuare il filtraggio
• _operator_ rappresenta l’operatore di confronto; può essere scelto **>**, **<**, **=**.
• _value_ rappresenta il valore di soglia da confrontare.
Dopo aver effettuato l'operazione di filtraggio, come sopra riportato, gli elementi che soddisfano le condizioni imposte vengono rimossi dal dataset.
Questa richiesta restituisce l'elenco di elementi rimanenti nel dataset.
# Diagrammi:
[Diagramma delle classi](https://github.com/hdmd/EsameDicembre2019/blob/master/Diagramma%20delle%20classi.png)
[Diagramma dei casi d'uso](https://github.com/hdmd/EsameDicembre2019/blob/master/Diagramma%20dei%20casi%20d'uso.PNG)
|
Go
|
UTF-8
| 1,799 | 2.796875 | 3 |
[] |
no_license
|
package main
import (
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"time"
)
// User ...
type User struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
Name string `json:"name,omitempty" bson:"name,omitempty"`
DateOfBirth string `json:"dateOfBirth,omitempty" bson:"dateOfBirth,omitempty"`
PhoneNo string `json:"phoneNo,omitempty" bson:"phoneNo,omitempty"`
EmailAddress string `json:"emailAddress,omitempty" bson:"emailAddress,omitempty"`
CreationTimeStamp time.Time `json:"creationTimeStamp,omitempty" bson:"creationTimeStamp,omitempty"`
}
var userCollectionName = "users"
func getUsers(db *mongo.Database, start, count int) ([]User, error) {
col := usersCollection(db)
ctx := dbContext(30)
cursor, err := col.Find(ctx, bson.M{}) // find all
if err != nil {
return nil, err
}
defer cursor.Close(ctx)
var users []User
for cursor.Next(ctx) {
var user User
cursor.Decode(&user)
users = append(users, user)
}
if err := cursor.Err(); err != nil {
return nil, err
}
return users[start : start + count], nil
}
func (user *User) getUser(db *mongo.Database) error {
col := usersCollection(db)
ctx := dbContext(30)
filter := bson.M{"_id": user.ID}
err := col.FindOne(ctx, filter).Decode(&user)
return err
}
func (user *User) createUser(db *mongo.Database) (*mongo.InsertOneResult, error) {
col := usersCollection(db)
ctx := dbContext(30)
user.CreationTimeStamp = time.Now()
result, err := col.InsertOne(ctx, user)
return result, err
}
// helpers
func usersCollection(db *mongo.Database) *mongo.Collection {
return db.Collection(userCollectionName)
}
|
Rust
|
UTF-8
| 2,035 | 4.40625 | 4 |
[
"MIT"
] |
permissive
|
/// Given a sorted array and a value, this function parses the collection and returns the
/// index where that value resides via a linear search
///
/// If the value is not present within the array `None` is returned
///
/// - Time Complexity: **O**(n)
/// - Space Complexity: **O**(1)
///
/// ```rust
/// use searching::linear_search::linear_search;
///
/// let result = linear_search(&vec![10, 15, 20, 25, 30], 15);
/// assert_eq!(result, Some(1));
/// ```
pub fn linear_search<T>(collection: &[T], target_value: T) -> Option<usize>
where
T: PartialEq,
{
collection.iter().position(|el| el == &target_value)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_middle() {
let result = linear_search(&vec![9, 8, 7, 6, 5, 4, 3, 2, 1, 0], 4);
assert_eq!(result, Some(5));
}
#[test]
fn test_single_element() {
let result = linear_search(&vec![100], 100);
assert_eq!(result, Some(0));
}
#[test]
fn test_not_in_array() {
let result = linear_search(&vec![1, 2, 3, 4, 5], 6);
assert_eq!(result, None);
}
#[test]
fn test_not_in_array_2() {
let result = linear_search(&vec![10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0], 11);
assert_eq!(result, None);
}
#[test]
fn test_empty_array() {
let result = linear_search(&vec![], 10);
assert_eq!(result, None);
}
#[test]
fn test_str_array() {
let result = linear_search(&vec!["test", "this", "array"], "this");
assert_eq!(result, Some(1));
}
#[test]
fn test_string_array() {
let result = linear_search(
&vec![
String::from("test"),
String::from("this"),
String::from("array"),
],
String::from("this"),
);
assert_eq!(result, Some(1));
}
#[test]
fn test_not_in_str_array() {
let result = linear_search(&vec!["test", "this", "array"], "value");
assert_eq!(result, None);
}
}
|
Shell
|
UTF-8
| 1,662 | 3.90625 | 4 |
[] |
no_license
|
#!/bin/bash
#########################################################################
# $? 代表上一个命令执行是否成功的标志,如果执行成功则$? 为0,否则不为0
# 使用 保存结果的变量名=`需要执行的linux命令` 这种方式来获取命令的输出时,注意的情况总结如下:
# 1)保证反单引号内的命令执行时成功的,也就是所命令执行后$?的输出必须是0,否则获取不到命令的输出
# 2)即便是命令的返回值是0,也需要保证结果是通过标准输出来输出的,而不是标准错误输出,否则需要重定向
# 因此我们推荐使用 保存结果的变量名=`需要执行的linux命令 2>&1 `的方式来获取命令的执行结果。
abc = ""
doErrorExit () {
exit 1
}
echo ">>>>>> push changes to iOS git"
echo ">>>>>> 1) git add files..."
git add .
echo ">>>>>> 2) git commit..."
git commit -m "rn debug"
echo ">>>>>> 3) git remote update..."
# git remote update
if [[ "$?" != "0" ]]; then
echo ">>>>>> git remote update Failed!!! ...."
doErrorExit
fi
echo ">>>>>> git remote update ok!!! ...."
echo ">>>>>> 4) git rebase..."
# git rebase origin/master
if [ true ]; then
echo ">>>>>> 5) start to push"
# 保存结果的变量名=`需要执行的linux命令 2>&1 `的方式来获取命令的执行结果
abc=`./push.sh master 2>&1`
echo $?
echo "push返回值: "${abc}
# echo ">>>>>> 6) end to push"
echo $?
if [[ "$?" != "0" ]]; then
echo ">>>>>> GIT PUSH Failed!!! ...."
doErrorExit
fi
echo ">>>>>> PUSH ok!!"
fi
echo ">>>>>> SUCCESS!!"
|
Python
|
UTF-8
| 1,070 | 2.859375 | 3 |
[] |
no_license
|
import base64
from PIL import Image
from django.core.files.base import ContentFile
def save_base64_to_file(file_name, data, save_file):
file_format, img_str = data.split(';base64,')
ext = file_format.split('/')[-1]
content_file = ContentFile(base64.b64decode(img_str))
save_file(f'{file_name}.{ext}', content_file)
def make_square_image(image_path):
img = Image.open(image_path)
if img.height != img.width:
size = min(img.height, img.width)
img = img.resize((size, size))
img.save(image_path)
# def compress_image(image_path):
# img = Image.open(image_path)
# if img.height > 512 or img.width > 512:
# output_size = (512, 512)
# img = img.resize(output_size)
# img.save(image_path)
def compress_image(image_path):
img = Image.open(image_path)
if img.height > 1024 or img.width > 1024:
output_size = (
int(img.width / 2), int(img.height / 2)
)
img = img.resize(output_size)
img.save(image_path)
compress_image(image_path)
|
Python
|
UTF-8
| 2,243 | 2.53125 | 3 |
[
"Unlicense"
] |
permissive
|
from . import oauth2 as FalconAuth
banner = """
,---. | ,--. |
|__. ,---.| ,---.,---.,---.| |,---.|---.. .,---.
| ,---|| | | || || ||---'| || || |
` `---^`---'`---'`---'` '`--' `---'`---'`---'`---|
`---'
CrowdStrike Python 3 Debug Interface
This shell-like interface allows for quick learning,
demoing, and prototyping of API operations using
the CrowdStrike FalconPy SDK and Python 3.
Please type help() to learn more.
|
_____________ __ -+- _____________
\\_____ / /_ \\ | \\ _____/
\\_____ \\____/ \\____/ _____/
\\_____ FalconPy _____/
\\___________ ___________/
/____\\
"""
python_help = help
def help(item=None):
text = """
This is interactive Python shell. Python help is available under python_help()
If you have FALCON_CLIENT_ID FALCON_CLIENT_SECRET environment variable set. This
shell will authenticate at the start up and the 'debug_token' variable will be
filled in with your OAuth2 token.
"""
if item is None:
print(text)
elif callable(getattr(item, 'help', None)):
item.help()
else:
print(item.__doc__)
def embed():
from IPython.terminal.embed import InteractiveShellEmbed
ipshell = InteractiveShellEmbed(banner1=banner)
ipshell.confirm_exit = False
ipshell()
def startup(dbg_falcon_client_id: str, dbg_falcon_client_secret: str):
dbg_authorization = FalconAuth.OAuth2(creds={
'client_id': dbg_falcon_client_id,
'client_secret': dbg_falcon_client_secret
})
try:
debug_token = dbg_authorization.token()["body"]["access_token"]
except Exception:
debug_token = False
return debug_token
def init(dbg_falcon_client_id: str = None, dbg_falcon_client_secret: str = None, creds: dict = None):
if creds:
dbg_falcon_client_id = creds["falcon_client_id"]
dbg_falcon_client_secret = creds["falcon_client_secret"]
global debug_token
debug_token = startup(dbg_falcon_client_id, dbg_falcon_client_secret)
embed()
debug_token = False
|
Java
|
UTF-8
| 201 | 2.296875 | 2 |
[
"MIT"
] |
permissive
|
package List;
/**
* Created by pmazurek on 07.04.2017.
*/
public interface Iterator {
public void next();
public void first();
public boolean isDone();
public Object current();
}
|
PHP
|
UTF-8
| 1,116 | 2.734375 | 3 |
[] |
no_license
|
<?php
//Various includes
include join(DIRECTORY_SEPARATOR, ["..", "src", "item.class.php"]);
include join(DIRECTORY_SEPARATOR, ["..", "src", "fridge.class.php"]);
include join(DIRECTORY_SEPARATOR, ["..", "src", "recipe.class.php"]);
include join(DIRECTORY_SEPARATOR, ["..", "src", "dataloader.class.php"]);
include join(DIRECTORY_SEPARATOR, ["..", "src", "finder.class.php"]);
/*
Get command line options
--csv: location of the CSV file
--json: location of the JSON file
*/
$options = getopt("c:j:t", ["csv:", "json:"]);
if (!empty($options['csv']) && !empty($options['json'])) {
//Initialize a RecipeFinder object based on command line args
$finder = new RecipeFinder($options['csv'], $options['json']);
$finder->find();
} else {
//Print help texts and tests
print("Welcome to Recipe Finder!\r\n");
print("Usage:\r\n\r\n");
print("--csv:\tRequired\tThe location of the CSV Fridge items file\r\n");
print("--json:\tRequired\tThe location of the JSON Recipes file\r\n\r\n");
print("In order to run the unit tests, please navigate to app > tests directory and run \"phpunit --verbose tests.php\"\r\n");
}
?>
|
Ruby
|
UTF-8
| 173 | 3.46875 | 3 |
[] |
no_license
|
puts 'what is your favorite number?'
favorite = gets.chomp
puts 'your favorite number is ' + favorite
better = favorite.to_i + 1
puts better.to_s + ' may be a better number'
|
C#
|
UTF-8
| 2,693 | 2.875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PizzaDesigner
{
public partial class MenuForm : Form
{
private BindingList<string> _vegetarianPizzas;
private BindingList<string> _nonVegetarianPizzas;
private const int ITEM_MARGIN = 10;
public MenuForm(BindingList<Tuple<string, bool>> pizzas)
{
InitializeComponent();
UpdateMenu(pizzas);
_vegetarianPizzaListBox.ClearSelected();
_nonVegetarianPizzaListBox.ClearSelected();
}
public void UpdateMenu(BindingList<Tuple<string, bool>> pizzas)
{
_vegetarianPizzas = new BindingList<string>();
_nonVegetarianPizzas = new BindingList<string>();
foreach (Tuple<string, bool> pizza in pizzas)
{
string text = pizza.Item1;
if (pizza.Item2)
{
_vegetarianPizzas.Add(text);
}
else
{
_nonVegetarianPizzas.Add(text);
}
}
_vegetarianPizzaListBox.DataSource = _vegetarianPizzas;
_nonVegetarianPizzaListBox.DataSource = _nonVegetarianPizzas;
}
private void VegetarianPizzaListBoxDrawItem(object sender, DrawItemEventArgs e)
{
DrawItem(e, true);
}
private void VegetarianPizzaListBoxMeasureItem(object sender, MeasureItemEventArgs e)
{
MeasureItem(e, true);
}
private void NonVegetarianPizzaListBoxDrawItem(object sender, DrawItemEventArgs e)
{
DrawItem(e, false);
}
private void NonVegetarianPizzaListBoxMeasureItem(object sender, MeasureItemEventArgs e)
{
MeasureItem(e, false);
}
private void DrawItem(DrawItemEventArgs e, bool vegetarian)
{
e.DrawBackground();
e.DrawFocusRectangle();
int index = e.Index;
if (index >= 0)
{
string pizza;
Font font;
if (vegetarian)
{
pizza = _vegetarianPizzas[index];
font = _vegetarianPizzaListBox.Font;
}
else
{
pizza = _nonVegetarianPizzas[index];
font = _nonVegetarianPizzaListBox.Font;
}
Brush brush = new SolidBrush(e.ForeColor);
Graphics graphics = e.Graphics;
graphics.DrawString(pizza, font, brush, e.Bounds.Left, e.Bounds.Top + ITEM_MARGIN);
}
}
// The following code was copied from http://csharphelper.com/blog/2014/11/make-an-owner-drawn-listbox-in-c/
private void MeasureItem(MeasureItemEventArgs e, bool vegetarian)
{
int index = e.Index;
if (index >= 0)
{
string pizza;
if (vegetarian)
{
pizza = _vegetarianPizzas[index];
}
else
{
pizza = _nonVegetarianPizzas[index];
}
SizeF text_size = e.Graphics.MeasureString(pizza, this.Font);
e.ItemHeight = (int)text_size.Height + (2 * ITEM_MARGIN);
}
}
// End of copied code
}
}
|
C++
|
UTF-8
| 1,435 | 2.890625 | 3 |
[] |
no_license
|
#include <cstdlib>
#include <ncurses.h>
using namespace std;
bool GameOver;
const int width = 20;
const int height = 20;
int x,y, fruitX, fruitY, score;
enum eDirection {STOP = 0, LEFT, RIGHT, UP, DOWN};
eDirection dir;
void Setup(){
initscr();
clear();
noecho();
cbreak();
curs_set(0);
GameOver = false;
dir = STOP;
x = width/2;
y = height/2;
fruitX = rand()%width+1;
fruitY = rand()%height+1;
score = 0;
}
void Draw(){
clear();
for(int i = 0; i<width+2; i++){
mvprintw(0,i, "#");
}
for(int i=0; i<height+2;i++){
for(int j=0;j<width+2;j++){
if (i == 0 | i ==21)
mvprintw(i, j, "#");
else if (j == 0 | j == 21)
mvprintw(i, j, "+");
else if (i == y && j == x)
mvprintw(i, j, "0");
else if (i == fruitY && j == fruitX)
mvprintw(i, j, "0");
}
}
refresh();
}
void Input(){
keypad(stdscr, TRUE);
halfdelay(1);
int c = getch();
switch(c){
case 'w':
dir = UP;
break;
case 'a':
dir = LEFT;
break;
case 's':
dir = DOWN;
break;
case 'd':
dir = RIGHT;
break;
case 'q':
GameOver = true;
default:
break;
}
}
void Logic(){
switch(dir){
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
}
}
int main(){
Setup();
while(!GameOver){
Draw();
Input();
Logic();
}
return 0;
}
|
Java
|
UTF-8
| 111 | 2.34375 | 2 |
[] |
no_license
|
package javaIterator;
import java.util.Iterator;
public interface Menu {
public Iterator getIterator();
}
|
Go
|
UTF-8
| 1,546 | 2.78125 | 3 |
[] |
no_license
|
package streams
import (
"encoding/json"
"fmt"
"gopkg.in/jcelliott/turnpike.v2"
)
// TickerStream holds state for a Poloniex 'ticker' firehose
type OrderStream struct {
broadcaster OrderBroadcaster
RecieveDone chan bool
}
// NewTickerStream connects to the Poloniex 'ticker' firehose.
func NewOrderStream(market string) (os OrderStream, err error) {
c, err := turnpike.NewWebsocketClient(turnpike.JSON, poloniexWebsocketAddress, nil)
if err != nil {
return os, fmt.Errorf("Unable to open websocket: %v", err)
}
_, err = c.JoinRealm(poloniexWebsocketRealm, nil)
if err != nil {
return os, fmt.Errorf("Unable to join realm: %v", err)
}
c.ReceiveDone = make(chan bool)
broadcaster := newOrderBroadcaster()
// TODO Unmarshal the proper ticker event
err = c.Subscribe(market, handleOrder(broadcaster))
if err != nil {
return os, fmt.Errorf("Subscription to %v failed: %v", poloniexWebsocketTopic, err)
}
return OrderStream{
broadcaster: broadcaster,
RecieveDone: c.ReceiveDone,
}, nil
}
func (os OrderStream) Subscribe() OrderChan {
return os.broadcaster.Listen()
}
func handleOrder(b OrderBroadcaster) turnpike.EventHandler {
return func(args []interface{}, kwargs map[string]interface{}) {
order := Order{}
for _, v := range args {
str, err := json.Marshal(v)
if err != nil {
fmt.Println("Error encoding JSON")
return
}
errUnmarshal := json.Unmarshal([]byte(str), &order)
if errUnmarshal != nil {
fmt.Println(errUnmarshal)
}
fmt.Println(order)
b.Write(order)
}
}
}
|
C
|
UTF-8
| 480 | 3.734375 | 4 |
[] |
no_license
|
/**
* Todos los numeros primos que hay en n
**/
#include <stdio.h>
int main()
{
int n, j=2, primo = 1;
printf("Escribe un numero entero positivo: ");
scanf("%d", &n);
for(int i=2; i<=n; i++){
while(j<i && primo==1){
primo = i%j == 0 ? 0 : 1;
j++;
}
if(primo==1){
printf("%d\n", j);
}else{
primo=1;
}
j=2;
}
return 0;
}
|
Java
|
UTF-8
| 4,686 | 2.921875 | 3 |
[] |
no_license
|
package com.sy.huangniao.common.Util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/**
* MD5校验工具类
*/
public class MD5Utils {
/**
* MD5加密字符串
*
* @param str 目标字符串
* @return MD5加密后的字符串
*/
public static String getMD5String(String str) {
return EncryptUtils.md5(str);
}
/**
* 校验密码与其MD5是否一致
*
* @param pwd 密码字符串
* @param md5 基准MD5值
* @return 检验结果
*/
public static boolean checkPassword(String pwd, String md5) {
return EncryptUtils.md5(pwd).equalsIgnoreCase(md5);
}
/**
* 校验密码与其MD5是否一致
*
* @param pwd 以字符数组表示的密码
* @param md5 基准MD5值
* @return 检验结果
*/
public static boolean checkPassword(char[] pwd, String md5) {
return checkPassword(new String(pwd), md5);
}
/**
* 检验文件的MD5值
*
* @param file 目标文件
* @param md5 基准MD5值
* @return 检验结果
*/
public static boolean checkFileMD5(File file, String md5) {
return EncryptUtils.md5(file).equalsIgnoreCase(md5);
}
/**
* 检验文件的MD5值
*
* @param fileName 目标文件的完整名称
* @param md5 基准MD5值
* @return 检验结果
*/
public static boolean checkFileMD5(String fileName, String md5) {
return checkFileMD5(new File(fileName), md5);
}
/**
* 按照加密方法
* 1、para按照key进行排序,然后组成字符串
* 2、字符串儿的末尾加上key
* 3、md5
* 4、小写转大写
*/
public static String encryption(Map<String,String> para, String key){
StringBuffer retMsgB = new StringBuffer();
TreeMap<String,String> tm = new TreeMap<String,String>();
tm.putAll(para);
for (Map.Entry<String, String> entry : tm.entrySet()) {
String mkey = entry.getKey();
String mvalue = entry.getValue();
if(!StringUtils.isBlank(mkey)&&!StringUtils.isBlank(mvalue)){
String temValue = new String(mvalue);
//如果 mvalue 包含转移 \ 去除
if(temValue.contains("\\")){
temValue = temValue.replace("\\", "");
}
retMsgB.append(mkey+"="+temValue+"&");
}
}
String retMsg = retMsgB.toString();
if(retMsg.charAt(retMsg.length()-1)=='&'){
retMsg = retMsg.substring(0,retMsg.length()-1);
}
retMsg = retMsg+key;
System.out.println("验签字符串为: " + retMsg);
/** 加密 、转大写 */
retMsg = getMD5String(retMsg).toUpperCase();
System.out.println("加密验签字符串为: " + retMsg);
return retMsg.toString();
}
public static String encryption(String string, String key){
StringBuffer retMsgB = new StringBuffer();
retMsgB.append(string).append(key);
System.out.println("验签字符串为: " + retMsgB.toString());
/** 加密 、转大写 */
String retMsg = getMD5String(retMsgB.toString()).toUpperCase();
System.out.println("加密验签字符串为: " + retMsg);
return retMsg;
}
public static JSONObject encryption(JSONObject jsonObject, String key){
Map<String,String> maps = (Map)JSON.parse(jsonObject.toJSONString());
jsonObject.put("sign",encryption(maps,key));
return jsonObject;
}
/**
* 验证签名
* @param json
* @param key
* @return
*/
public static boolean checkEncryption(JSONObject json, String key, String sign){
Map<String,String> maps = (Map)JSON.parse(json.toJSONString());
if(encryption(maps,key).equals(sign)){
return true;
}else {
return false;
}
}
/**
* 验证签名
* @param maps
* @param key
* @return
*/
public static boolean checkEncryption(Map<String,String> maps, String key, String sign){
if(encryption(maps,key).equals(sign)){
return true;
}else {
return false;
}
}
public static boolean checkEncryption(String string, String key, String sign){
if(encryption(string,key).equals(sign)){
return true;
}else {
return false;
}
}
}
|
C
|
UTF-8
| 185 | 3.375 | 3 |
[] |
no_license
|
//table of n
#include <stdio.h>
int main ()
{
int n,i;
printf("Ban muon bang cuu chuong may: " );
scanf("%d",&n);
for (i=1; i<=10;i++)
{
printf(" %d x %d = %d\n",n,i,n*i);
}
}
|
Java
|
UTF-8
| 2,571 | 2.515625 | 3 |
[] |
no_license
|
package com.mitsurin.tools.creating_best_party.model.compatibility;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class CompatibilityXMLReader {
private Document document;
private Element root;
public CompatibilityXMLReader(String request) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
} catch(ParserConfigurationException e) {
e.printStackTrace();
}
try {
this.document = builder.parse("http://localhost"+request);
} catch(IOException | SAXException | IllegalArgumentException e) {
e.printStackTrace();
}
this.root = this.document.getDocumentElement();
}
private Compatibility convertCompatibility(Node compatibilityNode) {
Element type = (Element)(((Element)compatibilityNode).getElementsByTagName("type").item(0));
NodeList weakpointNodeList = ((Element)compatibilityNode).getElementsByTagName("weakpoint");
Type[] t1t2 = new Type[2];
t1t2[0] = Type.getTypeByTypeName(type.getAttribute("t1"));
t1t2[1] = Type.getTypeByTypeName(type.getAttribute("t2"));
Map<Type, Integer> weakpointMap = new HashMap<>();
for(int i = 0; i < weakpointNodeList.getLength(); i++) {
Element weakpoint = (Element)(weakpointNodeList.item(i));
Type weakType = Type.getTypeByTypeName(weakpoint.getAttribute("type"));
int level = Integer.parseInt(weakpoint.getAttribute("level"));
weakpointMap.put(weakType, level);
}
return new Compatibility(t1t2, weakpointMap);
}
public Compatibility[] getCompatibilities() {
NodeList compatibilityNodeList = this.root.getElementsByTagName("compatibility");
Compatibility[] compatibilities = new Compatibility[compatibilityNodeList.getLength()];
for(int i = 0; i < compatibilityNodeList.getLength(); i++) {
Node compatibilityNode = compatibilityNodeList.item(i);
compatibilities[i] = convertCompatibility(compatibilityNode);
}
return compatibilities;
}
}
|
Java
|
GB18030
| 1,374 | 2.328125 | 2 |
[] |
no_license
|
package ajaxaction;
import com.opensymphony.xwork2.ActionSupport;
import bean.Exam;
import tool.ORMTool;
public class TeacherToManager extends ActionSupport{
private String teachernumber;
private String btntext;
public String getTeachernumber() {
return teachernumber;
}
public void setTeachernumber(String teachernumber) {
this.teachernumber = teachernumber;
}
public String getBtntext() {
return btntext;
}
public void setBtntext(String btntext) {
this.btntext = btntext;
}
public String execute()
{
if (this.btntext.equals("ΪԱ")) {
ORMTool ormtool = new ORMTool();
String hql = "update Teacher t set t.isadmin = :newarg where t.teachernumber = :oldNumber";
ormtool.initSession();
int update = ormtool.getSession().createQuery(hql).setString("newarg", "").setString("oldNumber", this.teachernumber)
.executeUpdate();
ormtool.getTranscation().commit();
ormtool.closeSession();
}
else
{
ORMTool ormtool = new ORMTool();
String hql = "update Teacher t set t.isadmin = :newarg where t.teachernumber = :oldNumber";
ormtool.initSession();
int update = ormtool.getSession().createQuery(hql)
.setString("newarg", "")
.setString("oldNumber", this.teachernumber)
.executeUpdate();
ormtool.getTranscation().commit();
ormtool.closeSession();
}
return SUCCESS;
}
}
|
Java
|
UTF-8
| 3,754 | 1.960938 | 2 |
[] |
no_license
|
package com.stee.emer.webService.client.sms;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>sendedAndBlaInfo complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType name="sendedAndBlaInfo">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="message" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="overage" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="payinfo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="returnstatus" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="sendTotal" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sendedAndBlaInfo", propOrder = {
"message",
"overage",
"payinfo",
"returnstatus",
"sendTotal"
})
public class SendedAndBlaInfo {
protected String message;
protected String overage;
protected String payinfo;
protected String returnstatus;
protected String sendTotal;
/**
* 获取message属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getMessage() {
return message;
}
/**
* 设置message属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessage(String value) {
this.message = value;
}
/**
* 获取overage属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getOverage() {
return overage;
}
/**
* 设置overage属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOverage(String value) {
this.overage = value;
}
/**
* 获取payinfo属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getPayinfo() {
return payinfo;
}
/**
* 设置payinfo属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPayinfo(String value) {
this.payinfo = value;
}
/**
* 获取returnstatus属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getReturnstatus() {
return returnstatus;
}
/**
* 设置returnstatus属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReturnstatus(String value) {
this.returnstatus = value;
}
/**
* 获取sendTotal属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getSendTotal() {
return sendTotal;
}
/**
* 设置sendTotal属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSendTotal(String value) {
this.sendTotal = value;
}
}
|
C#
|
UTF-8
| 2,334 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
namespace BattleShip.Windows {
using System.Windows;
using System.Windows.Controls;
using Algorithms;
internal class GameOver : Window {
private bool _checked;
public GameOver() {
Calculation.GetScreenCenter(this);
var grid = new Grid();
this.Content = grid;
var replayButton = new Button {
Padding = new Thickness(25, 12, 25, 12),
Content = "Play again",
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Left,
Margin = new Thickness(100, 0, 0, 0)
};
replayButton.Click += this.CallMainWindow;
grid.Children.Add(replayButton);
var changeSettingsCheckbox = new CheckBox {
Content = "Change settings before replay?",
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Left,
Margin = new Thickness(0, 50, 0, 0)
};
changeSettingsCheckbox.Click += this.ToggleSettingsBox;
grid.Children.Add(changeSettingsCheckbox);
var finishButton = new Button {
Padding = new Thickness(25, 12, 25, 12),
Content = "Exit",
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Right,
Margin = new Thickness(0, 0, 100, 0)
};
finishButton.Click += this.ExitGame;
grid.Children.Add(finishButton);
}
private void CallMainWindow(object sender, RoutedEventArgs e) {
Window window;
if (this._checked) {
var settingsWindow = new Settings();
window = settingsWindow;
} else {
var mainWindow = new MainWindow();
window = mainWindow;
}
this.Close();
window.Show();
}
private void ExitGame(object sender, RoutedEventArgs e) {
Application.Current.Shutdown();
}
private void ToggleSettingsBox(object sender, RoutedEventArgs e) {
this._checked = ((CheckBox)sender).IsChecked ?? false;
}
}
}
|
Java
|
UTF-8
| 1,987 | 1.859375 | 2 |
[] |
no_license
|
package com.jjg.member.model.vo;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* <p>
* 后台会员列表
* </p>
*
* @author lins 1220316142@qq.com
* @since 2019-06-04
*/
@Data
@Api
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class EsAdminMemberVO implements Serializable {
/**
* 会员id
*/
@ApiModelProperty(required = false,value = "会员id",example = "1")
private Long id;
/**
* 手机号
*/
@ApiModelProperty(required = false,value = "手机号",example = "15056015220")
private String mobile;
/**
* 邮箱
*/
@ApiModelProperty(required = false,value = "邮箱",example = "1220316123@qq.com")
private String email;
/**
* 会员等级
*/
@ApiModelProperty(required = false,value = "会员等级")
private String memberLevel;
/**
* 签约公司
*/
@ApiModelProperty(required = false,value = "签约公司名称")
private String company;
/**
* 账号余额
*/
@ApiModelProperty(required = false,value = "账号余额")
private Double money;
/**
* 注册时间
*/
@ApiModelProperty(required = false,value ="注册时间",example = "123456789")
private Long registerTime;
/**
*登陆时间
*/
@ApiModelProperty(required = false,value = "登陆时间",example = "12345678")
private Long loginTime;
/**
* 会员状态
*/
@ApiModelProperty(required = false,value = "会员状态")
private String state;
/**
* 成长值
*/
@ApiModelProperty(required = false,value = "成长值",example = "1")
private Integer grade;
/**
* 名称
*/
@ApiModelProperty(required = false,value = "名称")
private String name;
@ApiModelProperty(required = false,value = "最后登录时间")
private Long lastLogin;
}
|
Shell
|
UTF-8
| 302 | 2.6875 | 3 |
[] |
no_license
|
#!/bin/bash
for ip in `cat $1`
do
{
/tmp/sshpass-1.06/sshpass -p '1qaz2wsx3edc' scp -p -r -P 22 -o StrictHostKeyChecking=no $2 hadoop@$ip:$3 &>/dev/null
if [ $? -eq 0 ]; then
echo $ip OK
else
echo $ip FAIL
fi
}
done
wait
|
Python
|
UTF-8
| 573 | 3.390625 | 3 |
[] |
no_license
|
total_num_of_students = int(input("enter total number of students:"))
print ("you entered %s students" %total_num_of_students)
student_info = {}
student_data = [ 'rollno', 'age', 'gender']
for i in range(0,total_num_of_students):
student_name = input("Name :")
student_info[student_name] = {}
for j in student_data:
student_info[student_name][j] = input(j)
name = input("to find info enter valid student name")
if name in student_info.keys():
print (student_info[student_name])
else:
print("please enter valid name")
|
C++
|
UTF-8
| 1,048 | 3.09375 | 3 |
[] |
no_license
|
/*~~@@@@ timeObject.h @@@@~~
Library to convert times between millis()
& times converted from starting values.
outputs that count up & down.
Returns: Micros, Millis, Seconds, Minutes, Hours, Days, Weeks, Years.
Simple & Complex Mode
Easy way to implement clocks & countdown timers
*/
#include "timeObject.h"
timeObject simpleClock;
#define INITAL_HOURS 0
#define INITAL_MINS 0
#define INITAL_SECS 10
#define PRINT_DELAY 1000
#define FORCE_PRINT_CLOCK false
void setup() {
Serial.begin(115200);
delay(100);
simpleClock.countdownSetup(INITAL_HOURS, INITAL_MINS, INITAL_SECS);
simpleClock.countdownStart();
}
void loop() {
// Call in every loop
simpleClock.countdownLoop();
// Prints the clock every time seconds change.
//Can be forced to print by passing true as an argument
simpleClock.countdownPrint(FORCE_PRINT_CLOCK);
// To Pause the countdown:
// simpleClock.countdownStop();
// To Change time left on countdown Timer:
// simpleClock.countdownSetup(1, 3, 42);
}
|
JavaScript
|
UTF-8
| 1,754 | 2.78125 | 3 |
[] |
no_license
|
let stompClient = null;
init();
connect();
function connect() {
const socket = new SockJS('/endpoint');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
stompClient.subscribe('/app/private', function (msg) {
onMessage(JSON.parse(msg.body));
});
}, function () {
window.setTimeout(connect, 3000);
});
}
function onMessage(msg) {
if (msg.type === "info") {
updateList(msg);
}
}
function init(){
const lis = [...document.querySelector("#robots").children];
lis.forEach(li => {
li.querySelector("#delete").addEventListener("click", () => deleteDevice(li.id.replace("id", "")));
setStatus(li, li.dataset.status);
});
}
function updateList(message) {
const id = message.robotId;
const status = message.status.toString();
const list = document.querySelector("#robots");
const li = list.querySelector(`#id${id}`);
setStatus(li, status);
}
function setStatus(listItem, status){
const btn = listItem.querySelector("button");
const lamp = btn.querySelector("canvas");
switch (status){
case "0":
btn.disabled = true;
lamp.className = "lamp-red";
break;
case "1":
btn.disabled = false;
lamp.className = "lamp-green";
break;
case "2":
btn.disabled = true;
lamp.className = "lamp-blue";
break;
}
}
function deleteDevice(id){
if(confirm("Sure delete?")){
fetch("/user/delete?robotId=" + id,
{}).then(resp => {
if(resp.ok){
document.querySelector("#id" + id).remove();
}
})
}
}
|
Java
|
UTF-8
| 4,047 | 2.34375 | 2 |
[] |
no_license
|
package com.example.kevin.watsoninnovation;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.github.paolorotolo.appintro.AppIntro2;
import com.github.paolorotolo.appintro.AppIntroFragment;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.github.paolorotolo.appintro.AppIntro;
import com.github.paolorotolo.appintro.AppIntro2;
import com.github.paolorotolo.appintro.AppIntroFragment;
public class IntroActivity extends AppIntro2 {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
//setContentView(R.layout.activity_intro);
// Note here that we DO NOT use setContentView();
// Add your slide fragments here.
// AppIntro will automatically generate the dots indicator and buttons.
/*addSlide(firstFragment);
addSlide(secondFragment);
addSlide(thirdFragment);
addSlide(fourthFragment);*/
// Instead of fragments, you can also use our default slide
// Just set a title, description, background and image. AppIntro will do the rest.
String title = "Welcome to Escape the Crowd";
String description = "This app will help you explore the wider area of Amsterdam!";
int image = R.drawable.logo;
int backgroundColor = Color.parseColor("#FFAB91");
addSlide(AppIntroFragment.newInstance(title, description, image, backgroundColor));
image = R.drawable.rsz_tut_1;
title = "First step";
description = "Before you start we want to get to know you. \n " +
"So please sign in using either Google or Facebook";
addSlide(AppIntroFragment.newInstance(title, description, image, backgroundColor));
image = R.drawable.rsz_tut_2;
title = "Second Step";
description = "Tell us what you want to do during your trip";
addSlide(AppIntroFragment.newInstance(title, description, image, backgroundColor));
image = R.drawable.rsz_tut_3;
title = "Start exploring";
description = "Based on what you selected, we offer you personalized challenges. \n"
+"Just click on the markers on the map and start escaping the crowd!";
addSlide(AppIntroFragment.newInstance(title, description, image, backgroundColor));
// OPTIONAL METHODS
// Override bar/separator color.
//setBarColor(Color.parseColor("#3F51B5"));
// Hide Skip/Done button.
showSkipButton(true);
setProgressButtonEnabled(true);
// Turn vibration on and set intensity.
// NOTE: you will probably need to ask VIBRATE permission in Manifest.
setVibrate(false);
setVibrateIntensity(30);
}
@Override
public void onSkipPressed(Fragment currentFragment) {
super.onSkipPressed(currentFragment);
finish();
//Intent intent = new Intent(this, MapsActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Call the AppIntro java class
//startActivity(intent);
}
@Override
public void onDonePressed(Fragment currentFragment) {
super.onDonePressed(currentFragment);
finish();
//Intent intent = new Intent(this, MapsActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // Call the AppIntro java class
//startActivity(intent);
}
@Override
public void onSlideChanged(@Nullable Fragment oldFragment, @Nullable Fragment newFragment) {
super.onSlideChanged(oldFragment, newFragment);
// Do something when the slide changes.
}
}
|
Markdown
|
UTF-8
| 1,953 | 2.84375 | 3 |
[] |
no_license
|
```yaml
area: Cambridgeshire
og:
description: Paula Willis was first diagnosed with throat cancer in September 2018.
publish:
date: 12 Sep 2019
title: Cancer surviving Demand Hub worker completes gruelling charity challenge
url: https://www.cambs.police.uk/news-and-appeals/charity-walk-raises-money-for-cancer-Cambridgeshire-constabulary-demand-hub
```
A Demand Hub worker who is bravely fighting cancer has completed a 26-mile walk in aid of a charity that is closest to her heart.
Paula Willis was first diagnosed with throat cancer in September 2018. Since then, the cancer spread to Paula's lymph nodes and she has battled through surgery, six sessions of chemotherapy and 30 rounds of radiotherapy.
Fast forwarding nine months, Paula is now coping with the aftermath of the harsh side effects and has returned to work.
Whilst waiting to hear back on whether any more treatment is needed, Paula set her sights on walking round Rutland Water with supportive family and friends in a bid to raise funds for Throat Cancer Foundation.
On Tuesday this week (10 September), Paula smashed her goal and completed the walk in just over nine hours.
Talking about the challenge, Paula said: "It was one of the hardest things I've done in a long while but to be able to complete it with friends and raise awareness of throat cancer was all worth the pain.
"So far we have raised £1,502 which is an amazing amount and I'm so grateful for everyone who has donated. The JustGiving page is still live and I would be so thankful to anyone else who wishes to sponsor this great charity which supports so many other people in my position."
Paula initially set out a target of raising £1000 but has far exceeded this aim and has currently raised £1,500, an additional 50% over her initial fundraising goal.
Anyone still wishing to donate to Paula should visit her JustGiving page here.
For more information about the Throat Cancer Foundation, visit their website.
|
Java
|
ISO-8859-1
| 4,702 | 2.796875 | 3 |
[] |
no_license
|
package mall.objects;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.LinkedList;
import mall.framework.GameObject;
import mall.framework.ObjectID;
import mall.framework.Textures;
import mall.window.Animation;
import mall.window.Camera;
import mall.window.Game;
import mall.window.Handler;
public class Player extends GameObject { // denna class har allt med playern att
// gra, obviously
private float width = 48, height = 96;
private float gravity = 0.5f;
private final float MAX_SPEED = 10;
// 1 = right
// -1 = left
private Handler handler;
private Camera cam;
Textures tex = Game.getInstance();
private Animation playerWalk, playerWalkLeft;
public Player(float x, float y, Handler handler, Camera cam,ObjectID id) {
super(x, y, id);
this.handler = handler;
this.cam = cam;
// man hoppar ver idle d den inte dr idle nr man gr
playerWalk = new Animation(5, tex.player[1], tex.player[2], tex.player[3], tex.player[4], tex.player[5], tex.player[6]);
playerWalkLeft = new Animation(5, tex.player[8], tex.player[9], tex.player[10], tex.player[11], tex.player[12], tex.player[13]);
}
public void tick(LinkedList<GameObject> object) {
x += velX;
y += velY;
if (velX < 0)
facing = -1;
else if (velX > 0)
facing = 1;
if (falling || jumping) {
velY += gravity;
// denna r fr att kontrollera att de inte gr fr fort.
if (velY > MAX_SPEED) {
velY = MAX_SPEED;
}
}
Collision(object);
playerWalk.runAnimation();
playerWalkLeft.runAnimation();
}
private void Collision(LinkedList<GameObject> object) {
for (int i = 0; i < handler.object.size(); i++) {
GameObject tempObject = handler.object.get(i);
if (tempObject.getID() == ObjectID.Block) { // om denna
// class(player) nuddar
// Block, gr ngot
if (getBounds().intersects(tempObject.getBounds())) // bara
// bottom
// half (se
// metheods
// nedan)
{
y = tempObject.getY() - height + 1; // s att den landar
// perfekt
velY = 0;
falling = false;
jumping = false;
} else
falling = true;
if (getBoundsRight().intersects(tempObject.getBounds())) {
x = tempObject.getX() - width;
}
if (getBoundsLeft().intersects(tempObject.getBounds())) {
x = tempObject.getX() + 32;
}
if (getBoundsTop().intersects(tempObject.getBounds())) {
y = tempObject.getY() + 32;
velY = 0;
}
} else if (tempObject.getID() == ObjectID.Flag) {
// switch levels
if (getBounds().intersects(tempObject.getBounds())){
handler.switchLevel();
}
}
}
}
public void render(Graphics g) {
g.setColor(Color.blue);
if (jumping) {
if (facing == 1) {
g.drawImage(tex.playerJump[2], (int) x, (int) y, 48, 96, null);
} else if (facing == -1) {
g.drawImage(tex.playerJump[3], (int) x, (int) y, 48, 96, null);
}
} else {
if (velX != 0) {
if (facing == 1)
playerWalk.drawAnimation(g, (int) x, (int) y, 48, 96);
else
playerWalkLeft.drawAnimation(g, (int) x, (int) y, 48, 96);
} else {// om man inte gr str den stilla, duh
if (facing == 1)
g.drawImage(tex.player[0], (int) x, (int) y, 48, 96, null);
else if (facing == -1)
g.drawImage(tex.player[7], (int) x, (int) y, 48, 96, null);
}
}
// denna r fr att rita gubben i
g.setColor(Color.red);
/*
* Graphics2D g2d = (Graphics2D) g; // detta r s att man kan rita i 2d
*
* g2d.draw(getBounds()); g2d.draw(getBoundsRight());
* g2d.draw(getBoundsLeft()); g2d.draw(getBoundsTop());
*/
}
public Rectangle getBounds() {
return new Rectangle((int) ((int) x + (width / 2) - ((width / 2) / 2)), (int) ((int) y + (height / 2)), (int) width / 2, (int) height / 2);
// denna rectangle r fr att se collision
}
public Rectangle getBoundsTop() {
return new Rectangle((int) ((int) x + (width / 2) - ((width / 2) / 2)), (int) y, (int) width / 2, (int) height / 2);
// denna rectangle r fr att se collision
}
public Rectangle getBoundsRight() {
return new Rectangle((int) ((int) x + (width - 5)), (int) y + 5, (int) 5, (int) height - 10);
// denna rectangle r fr att se collision
}
public Rectangle getBoundsLeft() {
return new Rectangle((int) x, (int) y + 5, (int) 5, (int) height - 10);
// denna rectangle r fr att se collision
} // DETTA MSTE JAG KOLLA UPP VARFR MAN GR S
}
|
Python
|
UTF-8
| 426 | 3.828125 | 4 |
[] |
no_license
|
'''
Write a script that reads in the contents of words.txt and writes the contents in reverse
to a new file words_reverse.txt.
'''
wordlist = []
with open('words.txt', 'r') as fin:
for word in fin:
word = word.rstrip()
wordlist.append(word)
# print(wordlist)
wordlist.reverse()
with open('reversewords.txt', 'w') as fout:
for word in wordlist:
fout.write(f"{word}\n")
|
Java
|
UTF-8
| 1,240 | 3.046875 | 3 |
[] |
no_license
|
package com.springtest.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author admin
* @desc
* @date 2019/7/23 10:35
*/
public class JdkProxyExam implements InvocationHandler {
//真实对象
private Object target = null;
/**
* 建立代理对象和真实对象的代理关系,返回代理对象
*
* @param target
* @return
*/
public Object bind(Object target) {
this.target = target;
Object proxy = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
return proxy;
}
/**
* @param proxy 代理对象
* @param method 当前调度方法
* @param args 方法参数
* @return 返回代理结果
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("进入代理逻辑");
System.out.println("调用真实对象之前");
Object obj = method.invoke(target, args);
System.out.println("调用真实对象之后");
return obj;
}
}
|
Rust
|
UTF-8
| 1,091 | 3.578125 | 4 |
[] |
no_license
|
pub fn hours_bigger_than_twelve_formatter(hour: i32) -> String {
let hours_key: i32 = hour - 12;
if hours_key < 10 {
if hours_key < 0 {
return "0".to_string();
}
return format!("0{}", hours_key).to_string();
}
return format!("{}", &hours_key).to_string();
}
//todo: this function should take in a struct instead
pub fn oh_clock_formatter(
parsed_hours: Option<&str>,
parsed_minute_map_lookup: &str,
am_pm: &str,
) -> String {
return format!(
"It's {} oh {} {}",
parsed_hours.unwrap(),
parsed_minute_map_lookup,
am_pm
);
}
#[test]
fn test_hour_formatter() {
assert_eq!(hours_bigger_than_twelve_formatter(13), "01");
assert_eq!(hours_bigger_than_twelve_formatter(23), "11");
assert_eq!(hours_bigger_than_twelve_formatter(0), "0");
}
#[test]
fn oh_clock_formatter_test() {
let parsed_hours = Some("four");
let parsed_minutes = "five";
let under_test = oh_clock_formatter(parsed_hours, parsed_minutes, "PM");
assert_eq!(under_test, "It's four oh five PM");
}
|
JavaScript
|
UTF-8
| 1,915 | 3.140625 | 3 |
[] |
no_license
|
// https://github.com/ttezel/twit for examples
//version 1.0
//Author: Chris Roach
console.log("the bot is starting up:");
var Twit = require("twit");
var array = require("./array.js");
var Quotation = array.Quotation;
var T = new Twit({
consumer_key:
consumer_secret:
access_token:
access_token_secret:
});
function favorited(eventMsg) {
console.log("favorited!");
var name = eventMsg.source.name;
var screenName = eventMsg.source.screen_name;
favoriteIt("@" + screenName + " Thanks for favoriting! it means so much!");
}
function followed(eventMsg) {
console.log("followed!");
var name = eventMsg.source.name;
var screenName = eventMsg.source.screen_name;
followIt("@" + screenName + " thanks for the follow! :) ");
}
function tweetIt() {
var whichQuotation = Quotation[Math.floor(Math.random() * Quotation.length)];
var tweet = {
status: whichQuotation
};
T.post("statuses/update", tweet, tweeted);
function tweeted(err, data, response) {
if (err) {
console.log("Something went wrong!");
} else {
console.log("It worked!");
}
}
}
function favoriteIt(txt) {
var tweet = {
status: txt
};
T.post("statuses/update", tweet, tweeted);
function tweeted(err, data, response) {
if (err) {
console.log("Favorite went wrong!");
} else {
console.log("Favorite responded to!");
}
}
}
function followIt(txt) {
var tweet = {
status: txt
};
T.post("statuses/update", tweet, tweeted);
function tweeted(err, data, response) {
if (err) {
console.log("Follow went wrong!");
} else {
console.log("Follow responded to!");
}
}
}
//setting up a user stream
var stream = T.stream("user");
//anytime someone favorites me
stream.on("favorite", favorited);
stream.on("follow", followed);
setInterval(tweetIt, 1000 * 60 * 60 * 6); //milliseconds 1000 = 1 second *60 = 60 seconds etc....
|
Java
|
GB18030
| 9,556 | 2.5625 | 3 |
[] |
no_license
|
package com.ecpss.action.pay.dcc;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.text.ParseException;
public class Client extends Thread{
private Socket sock;
// public Client(Socket socket) {
// sock = socket;
// }
public void run() {
byte[] lenbuf = new byte[2];
try {
//For high volume apps you will be better off only reading the stream in one thread
//and then using another thread to parse the buffers and process the responses
//Otherwise the network buffer might fill up and you can miss a message.
while (sock != null && sock.isConnected() && !isInterrupted()) {
sock.getInputStream().read(lenbuf);
int size = ((lenbuf[0] & 0xff) << 8) | (lenbuf[1] & 0xff);
byte[] buf = new byte[size];
//We're not expecting ETX in this case
if (sock.getInputStream().read(buf) == size) {
try {
} catch (Exception ex) {
}
} else {
return;
}
}
} catch (IOException ex) {
} finally {
try {
sock.close();
} catch (IOException ex) {};
}
}
/**
* @param args
*/
public static void main(String[] args) {
//ѯͨ
// DCCMessage msg=new DCCMessage();
// msg.setMessageType("0800");
// msg.setPrimary_Account_Number("4000000000000002");
// msg.setProcessing_Code("970000");
// msg.setAmount_Transaction_Local("000000102050");
// msg.setSYSTEMS_TRACE_AUDIT_NUMBER("865454");
// msg.setDATE_EXPIRATION("0506");
// msg.setPOINT_OF_SERVICE_ENTRY_CODE("012");
// msg.setNETWORK_INTL_IDENTIFIER("098");
// msg.setPOS_CONDITION_CODE("00");
// msg.setCARD_ACCEPTOR_TERMINAL_ID("985652565236523");
// msg.setCARD_ACCEPTOR_ID_CODE("85858585");
// msg.setInvoice_Number("856958");
//ײѯ
DCCMessage dcc=new DCCMessage();
dcc.setMessageType("0800");//
dcc.setPrimary_Account_Number("4447961117443552");//˺2
dcc.setProcessing_Code("970000");//3
dcc.setAmount_Transaction_Local("000000032190");//4 ؽ
dcc.setSYSTEMS_TRACE_AUDIT_NUMBER("000005");//11 ˮ
dcc.setDATE_EXPIRATION("1201");//14 Ч
dcc.setPOINT_OF_SERVICE_ENTRY_CODE("0012");//22 POSģʽ
dcc.setNETWORK_INTL_IDENTIFIER("0098");//24 յ̻
dcc.setPOS_CONDITION_CODE("00");//25 ̻
dcc.setCARD_ACCEPTOR_TERMINAL_ID("22222222");//41 ̻ն˺
dcc.setCARD_ACCEPTOR_ID_CODE("021209999000000");//42 ̻
dcc.setInvoice_Number("000005");//62
//S
DCCMessage msg2=new DCCMessage();
msg2.setMessageType("0200");//
msg2.setPrimary_Account_Number("4447961117443552");//˺2
msg2.setProcessing_Code("000000");//3
msg2.setAmount_Transaction_Local("000000032190");//4 ؽ
msg2.setAmount_Transaction_Foreign("000000004867");//5 0810
msg2.setConversion_Rate("71511880");//9 0810
msg2.setSYSTEMS_TRACE_AUDIT_NUMBER("000005");//11 ˮ
msg2.setDATE_EXPIRATION("1201");//14 Ч
msg2.setPOINT_OF_SERVICE_ENTRY_CODE("0012");//22 POSģʽ
msg2.setNETWORK_INTL_IDENTIFIER("0017");//24 յ̻
msg2.setPOS_CONDITION_CODE("00");//25 ̻
msg2.setRETRIEVAL_REFERENCE_NUMBER("101180000032");//37
msg2.setCARD_ACCEPTOR_TERMINAL_ID("22222222");//41 ̻ն˺
msg2.setCARD_ACCEPTOR_ID_CODE("021209999000000");//42 ̻
msg2.setCurrency_Code_Foreign("840");//49 Ҵ-----0810
msg2.setCVV2_OR_CVC2("778");//cv2
msg2.setInvoice_Number("000005");//62
DCCMessage dcc3=new DCCMessage();
dcc3.setMessageType("0200");//
dcc3.setPrimary_Account_Number("164402602810763408");//˺2
dcc3.setProcessing_Code("000000");//3
dcc3.setAmount_Transaction_Local("000000000100");//4 ؽ
dcc3.setSYSTEMS_TRACE_AUDIT_NUMBER("000006");//11 ˮ
dcc3.setDATE_EXPIRATION("0810");//14 Ч
dcc3.setPOINT_OF_SERVICE_ENTRY_CODE("0012");//22 POSģʽ
dcc3.setNETWORK_INTL_IDENTIFIER("0017");//24 յ̻
dcc3.setCARD_ACCEPTOR_TERMINAL_ID("88885500");//41 ̻ն˺
dcc3.setCARD_ACCEPTOR_ID_CODE("021801055000001");//42 ̻
dcc3.setCVV2_OR_CVC2("218");//cv2 61
dcc3.setInvoice_Number("000006");//62
// byte [] byt=msg.getMessage();
// byte [] biaozhu="0800".getBytes();
// byte [] byts=new byte[byt.length+biaozhu.length];
// System.arraycopy(biaozhu, 0, byts, 0, biaozhu.length);
// System.arraycopy(byt, 0, byts,biaozhu.length,byt.length);
String temssss="005c6000173000020078a4058000c0800c1644026028107634080000000000000001000000000000117114964800000608100012001700383838383535303030323138303130353530303030303139373800033231380006303030303036";
String temss222="004a600098300008007024058000c000041644026028107634089700000000000001000000050810001200980038383838353530303032313830313035353030303030310006303030303035";
String temsss333="0041600098300008007024018000c000041644026028107634089700000000000001000000051105098003838383835353030303231383031303535303030303031303036303030303035";
String test="004f600017300002007024050000c0000c16523265457854521400000000000000010000000608100012001738353435323132333032313132313231323132313231320003303331330006303030303036";
byte [] byts=msg2.getMessage();
// byte [] byts=DCCMessageUtil.str2Bcd(temssss);
InputStream in = null;
OutputStream outs=null;
try {
Socket sockets = new Socket("222.92.198.164", 6500);
if (sockets.isConnected()) {
Client.printHexString(byts);
outs = sockets.getOutputStream();
outs.write(byts);
in = sockets.getInputStream();
byte[] bytss=new byte[300];
in.read(bytss);
System.out.println(DCCMessageUtil.bcd2Str(byts)+"\n");
Client.printHexString(bytss);
System.out.println("\n"+Client.getHexString(bytss));
// Client.printHexString(bytss);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
outs.close();
in.close();
} catch (IOException e) {
// e.printStackTrace();
}
}
// Client cli=new Client();
// String ask= cli.communicateHost("222.92.198.164", 6500,"720000003080000016530998787654534290000000000000010020030802063132333435360009123456001083938373635343332");
// System.out.println(ask);
}
// ʵʱ(socket ͻͨ)
public String communicateHost(String socket_ip,int socket_port,String msg) {
// socketipַ
// socket˿
Socket socket = null;
BufferedReader in = null;
PrintWriter out = null;
//
String answerMSG="";
try {
socket = new Socket(socket_ip, socket_port);
if (socket.isConnected()) {
in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
//
out.println(msg);
// Ӧ
answerMSG = in.readLine();
}
} catch (UnknownHostException e) {
// System.err.println("δ֪λã" + socket_ip);
// e.printStackTrace();
} catch (IOException e) {
// System.err.println("IO쳣");
// e.printStackTrace();
} finally {
try {
in.close();
out.close();
socket.close();
} catch (IOException e) {
// e.printStackTrace();
}
}
return answerMSG;
}
public static void printHexString( byte[] b) {
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
System.out.print(hex.toUpperCase() );
}
}
public static String getHexString( byte[] b) {
String tem="";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
tem+=hex.toUpperCase();
}
return tem;
}
}
//ͽָ
//DCCMessage msg2=new DCCMessage();
//msg2.setPrimary_Account_Number("512345013100138189");
//msg2.setProcessing_Code("000000");
//msg2.setAmount_Transaction_Local("000000102050");
//msg2.setAmount_Transaction_Foreign("000001102050");
//msg2.setSYSTEMS_TRACE_AUDIT_NUMBER("985654");
//msg2.setConversion_Rate("0.65");
//msg2.setDATE_EXPIRATION("1002");
//msg2.setPOINT_OF_SERVICE_ENTRY_CODE("012");
//msg2.setNETWORK_INTL_IDENTIFIER("017");
//msg2.setPOS_CONDITION_CODE("00");
//msg2.setRETRIEVAL_REFERENCE_NUMBER("123652458574");
//msg2.setCARD_ACCEPTOR_TERMINAL_ID("88888888");
//msg2.setCARD_ACCEPTOR_ID_CODE("700888558541125");
//msg2.setCurrency_Code_Foreign("784");
//msg2.setCVV2_OR_CVC2("569");
//msg2.setInvoice_Number("885454");
|
Shell
|
UTF-8
| 3,820 | 4.125 | 4 |
[
"MIT"
] |
permissive
|
#!/bin/sh
# Copyright 2015-2023 Yury Gribov
#
# Use of this source code is governed by MIT license that can be
# found in the LICENSE.txt file.
# Configure and build LLVM in current directory.
set -eu
absolutize() {
realpath -s "$1"
}
error() {
echo >&2 "$(basename $0): error: $@"
exit 1
}
print_short_help() {
cat <<EOF
Usage: $(basename $0) [options] src-dir [cmake-options]
Run \`$(basename $0) -h' for more details.
EOF
}
print_help() {
cat <<EOF
Usage: $(basename $0) [options] src-dir [cmake-options]
Configure and build LLVM in current directory with typical development options.
Options:
-h, --help Print help and exit.
-C dir Build in dir.
-j N, -jN Number of jobs to run (default is 1.5 * number-of-cores).
--clean Force clean of build directory.
--install Install after build (off by default).
-g, --debug Build unoptimized compiler (for debugging).
-t, --targets 't1;...' List of targets to build (or "all"); default is x64 only.
-p, --projects 'p1;...' List of projects to build (or "all"); default is clang.
--test Run check-all after successful build.
EOF
}
NJOBS=$((3 * $(nproc) / 2))
INSTALL_DIR=$HOME/install/$(basename $PWD)
CMAKE_FLAGS="-DCMAKE_VERBOSE_MAKEFILE=ON -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_INSTALL_PREFIX=$INSTALL_DIR -DLLVM_ENABLE_ASSERTIONS=ON -DBUILD_SHARED_LIBS=ON -DLLVM_OPTIMIZED_TABLEGEN=ON -DLLVM_TARGETS_TO_BUILD=X86 -DCOMPILER_RT_BUILD_SHARED_ASAN=ON -DLLVM_PARALLEL_LINK_JOBS=1 -DLLVM_USE_SPLIT_DWARF=ON -DLLVM_APPEND_VC_REV=OFF"
if which lld > /dev/null 2>&1; then
CMAKE_FLAGS="$CMAKE_FLAGS -DLLVM_USE_LINKER=lld"
fi
if which ninja > /dev/null 2>&1; then
CMAKE_FLAGS="$CMAKE_FLAGS -G Ninja"
fi
BUILD_DIR=$PWD
PROJECTS=clang
CLEAN=
INSTALL=
TEST=
while true; do
case "$1" in
-C)
BUILD_DIR=$2
mkdir -p $BUILD_DIR
shift 2
;;
-g|--debug)
CMAKE_FLAGS="$CMAKE_FLAGS -DCMAKE_BUILD_TYPE=Debug -DCOMPILER_RT_DEBUG=ON"
shift
;;
--clean)
CLEAN=1
shift
;;
--install)
INSTALL=1
shift
;;
--test)
TEST=1
shift
;;
--projects | -p)
PROJECTS="$2"
shift 2
;;
--targets | -t)
CMAKE_FLAGS="$CMAKE_FLAGS -DLLVM_TARGETS_TO_BUILD='$2'"
shift 2
;;
--help | -h)
print_help
exit 1
;;
-j)
NJOBS=$2
shift 2
;;
-j*)
NJOBS=$(echo "$1" | sed -e 's/^-j//')
shift
;;
-*)
error "unknown option: $1"
;;
*)
break
;;
esac
done
if test -n "$PROJECTS"; then
CMAKE_FLAGS="$CMAKE_FLAGS -DLLVM_ENABLE_PROJECTS='$PROJECTS'"
fi
if [ $# -lt 1 ]; then
print_short_help >&2
exit 1
fi
SRC=$(absolutize $1)
shift
if [ ! -f $SRC/CMakeLists.txt ]; then
error "file $SRC/CMakeLists.txt is missing"
fi
cd $BUILD_DIR
if [ $(ls | wc -l) -gt 0 ]; then
if [ -z "$CLEAN" ]; then
error "Build must be performed in empty directory; do `rm -rf *` in $BUILD_DIR or run with --clean"
else
# Be cautious
test -f ./CMakeCache.txt \
|| error "cowardly refusing to clean $BUILD_DIR which does not look like a build dir"
rm -rf *
fi
fi
HOST=x86_64-unknown-linux-gnu
TIME_START=$(date +%s)
#module load gcc/pc/483 # LLVM wants GCC 4.8+
LOG=$(basename $0).log
echo "cmake $CMAKE_FLAGS \"$@\" $SRC" >> cmake_command.log
eval cmake $CMAKE_FLAGS \
"$@" $SRC | tee $LOG
if test -f Makefile; then
MAKE=make
elif test -f build.ninja; then
MAKE=ninja
fi
export VERBOSE=1
nice $MAKE -j$NJOBS 2>&1 | tee -a $LOG
if test -n "$INSTALL"; then
nice $MAKE install 2>&1 | tee -a $LOG
fi
if test -n "$TEST"; then
nice $MAKE check-all 2>&1 | tee -a $LOG
fi
DT=$(($(date +%s) - TIME_START))
echo "Total time is $((DT / 60)) minutes (using $NJOBS cores)." > times.log
|
Markdown
|
UTF-8
| 6,849 | 3.421875 | 3 |
[
"MIT"
] |
permissive
|
---
title: Protect WordPress Login Page
description: Learn how to protect WordPress login page from brute force attack by changing the login URL, limiting the number of failed login attempts, and more.
published_at: 2017-11-08T19:39:07+00:00
tags: ['How To', 'Security', 'WordPress', 'WordPress Plugin']
---
Being the number one [^fn1] CMS in the world, websites running WordPress are a great target for hackers who want to take control of other people's websites. Hackers will ask for a ransom, sell personal information that belongs to the site’s owner/s and it’s users, distribute malware, send spam or simply, to eliminate competitors.
One very popular way of getting administrative access to a WordPress site is by attacking the login page.
Thy name is wp-login.php.
We all know it and you should know that everyone knows it. Hackers will use it since it's the gateway to your site and you should do your best to Protect your WordPress Login Page.
Using a technique called Brute Force Attack, hackers take advantage of a few weak points that come with every WordPress installation. You should harden those weak points as soon as possible to keep intruders outside and your site safe and protected.
In this tutorial, you will learn How to Protect WordPress Login Page from Brute Force Attack
Brute Force Attack aims at being the simplest kind of method to gain access to a site: it tries usernames and passwords, over and over again, until it gets in. Often deemed 'inelegant', they can be very successful when people use passwords like '123456' and usernames like 'admin.'. [WordPress Codex][1]
### Things a hacker needs to brute force into your WordPress site.
There are 3 simple things that a hacker needs in order to brute force into your WordPress site:
* Username
* Password
* WordPress Login URL
### Weak points that hackers can take advantage of.
With every WordPress installation, there come a few weak points that you should modify right away to make your site harder to brute force into.
* Known WordPress username.
* Easy to crack passwords.
* Knows WordPress login page URL.
* Unlimited amount of failed attempts.
Let’s work our way from the top and strengthen each one of these weak points in order to protect WordPress login page.
## 1. Change WordPress admin username
Running an old WordPress site? Chances are, the main WordPress username is called **Admin** and that one is used against you to take control of your site.
In order to fix this issue, you have to:
1. Go to your WordPress Dashboard
2. Click on Users > Add new
3. Fill all the necessary info and pick the role of the new user as Administrator.
4. Log out of your admin account and sign in to your new account.
5. Click on Users > All Users
6. Hover the mouse over the old user and click on delete.
7. Select _Attribute all content to_ and select the newly created account and click on _Confirm Deletion_.
## 2. Create a stronger password.
This is the easiest thing to do and it can be done in a matter of seconds.
Either invest in a password manager like 1Password and generate a strong password using it.
Or, use an online [Password Generator][2] by LastPass
In order to change your password, you need to go to Users > Your Profile > New Password.
## 3. Limit login attempts
Think about it, how many attempts do you need to enter your password?
2 times if you're entering it from your memory and one time if you're using a password manager. That's 3 attempts in total.
Then why give a hacker unlimited amount of attempts until they manage to access your site?
You can easily lock it down with a plug-in like [Wordfence][3] which among other great security features, allows you to [lock someone out of your website][4] after a number of failed attempts that you set.
The reason I picked Wordfence instead of other plugins like Limit Login Attempts is that the latter hasn’t been updated in 5 years and it’s not recommended to use an outdated plugin.
Choosing Wordfence is a much better option because it contains many great security features and it keeps getting updated and getting better.
## 4. Protect WordPress Login Page by changing the URL
Like I said in the beginning, everyone knows about wp-login.php. It’s the gateway to your site admin area. So it's obvious that you should learn how to protect it.
The best way to Protect WordPress Login Page is by changing the URL and you can do that by using the [WPS Hide Login.][6]
1. Go to Plugins > Add new
2. Search for **WPS Hide Login**. Install and Activate.
3. Go to Settings > General.
4. Scroll down to WPS Hide Login. That’s where you will see the place where you enter the new URL.
Now that your new login page URL had changed, when a hacker tries and visits domain.tld/wp-login.php they will be taken to your 404 page instead.

As you see from the screenshot above taken from Wordfence real-time traffic scan of News47ell, there are a lot of people interested in logging into my site from all over the world.
They all trying to visit wp-login.php, a non-existent page thanks to WPS Hide Login.
And in case you forgot your new secure URL, delete the plugin, and reinstall it again. It's that simple.
## 5. Enable Two Factor Authentication
Let’s say that the hacker found out your new and unique login URL and even found out your username and password, having two factor authentication enabled would be great since it will prevent the hacker from logging in to your site because they don’t have the ‘something you have’ element.
## Conclusion:
You can also do two more things to make your site even more secure by choosing a secure host, like Lightning Base which I have been using for….scroll down a bit and see the number, Lightning Base offers many great security features to protect your WordPress site which you can [read more about it here.][12]
Plus, you can use Cloudflare which also offers a [suite of security features][13] that will increase the security of your site even more.
As you can see, it's not that hard to Protect WordPress Login Page and it doesn’t cost you anything. So go ahead and install these plugins to protect your WordPress login page today for a safer future…too cheesy?
[^fn1]: 28.7% of websites around the world use WordPress.
[1]: https://codex.wordpress.org/Brute_Force_Attacks
[2]: https://lastpass.com/generatepassword.php
[3]: https://wordpress.org/plugins/wordfence/
[4]: https://docs.wordfence.com/en/Wordfence_options#Lock_out_after_how_many_login_failures
[6]: https://wordpress.org/plugins/wps-hide-login/ "WPS Hide Login — WordPress Plugins"
[12]: https://lightningbase.com/wordpress-hosting/features/#security
[13]: https://www.cloudflare.com/security/
|
Python
|
UTF-8
| 487 | 2.84375 | 3 |
[] |
no_license
|
#!/usr/bin/python3
""" Script that handles SQL injection """
import MySQLdb
from sys import argv
if __name__ == "__main__":
db = MySQLdb.connect(host="localhost", port=3306, user=argv[1],
passwd=argv[2], db=argv[3], charset="utf8")
c = db.cursor()
c.execute("SELECT * FROM states WHERE \
states.name =%s ORDER BY id ASC", (argv[4],))
states_rows = c.fetchall()
for state in states_rows:
print(state)
c.close()
db.close()
|
JavaScript
|
UTF-8
| 6,822 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
import React from 'react';
import './Styles/CreateAd.css';
import CreateAdButton from '../../Components/Button/Button.js';
import BannerAds from '../../Pictures/BannerAds.png';
import PostAds from '../../Pictures/PostAds.png';
import VideoAds from'../../Pictures/VideoAds.png';
import EstimatesComp from '../EstimatesComp/EstimatesComp';
import { faTintSlash } from '@fortawesome/free-solid-svg-icons';
// This is the the loading component that is rendered onto the page when we are doing work on the backend
let reach = 0;
let myWeeks = 0;
class CreateAd extends React.Component {
constructor(props) {
super(props);
this.state = {
bannerAds: false,
postAds: false,
videoAds: false,
reach: 10000,
budget: 0,
weeks: 0,
reach: 0
}
this.onClickHandler = this.onClickHandler.bind(this);
this.sliderHandler = this.sliderHandler.bind(this);
this.bannerAdsHandler = this.bannerAdsHandler.bind(this);
this.postAdsHandler = this.postAdsHandler.bind(this);
this.videoAdsHandler = this.videoAdsHandler.bind(this);
this.confirmButtonClicked = this.confirmButtonClicked.bind(this);
}
sliderHandler() {
var slider = document.getElementById("SMLessonPage_createAd_card_middle_sliders_slider1_input");
var output = document.getElementById("output1");
output.innerHTML = "$" + slider.value;
var slider2 = document.getElementById("SMLessonPage_createAd_card_middle_sliders_slider2_input");
var output2 = document.getElementById("output2");
output2.innerHTML = slider2.value + " weeks";
this.setState({
budget: slider.value,
weeks: slider2.value
});
}
setEstimatedReach(estimatedReach, weeks) {
reach = estimatedReach;
myWeeks = weeks;
}
confirmButtonClicked() {
console.log(reach);
this.props.onCreateAdClicked(3,reach, myWeeks);
}
bannerAdsHandler() {
this.setState({
bannerAds: !this.state.bannerAds
})
console.log(this.state.bannerAds);
}
postAdsHandler() {
this.setState({
postAds:!this.state.postAds
})
}
videoAdsHandler() {
this.setState({
videoAds:!this.state.videoAds
})
}
onClickHandler = (e) => {
console.log(e.target.innerText);
this.props.onAdwordClicked(2, e.target.innerText);
}
render() {
return (
<div id="SMLessonPage_createAd">
<div id="SMLessonPage_createAd_card">
<div id="SMLessonPage_createAd_card_top">
<div id="SMLessonPage_createAd_card_header">
<p> {this.props.selectedWord} </p>
<p> Let's See How Far of a Reach You Can Create </p>
<p> <span> Select an Ad Type: </span> </p>
</div>
<div id="SMLessonPage_createAd_card_adTypes">
<div id="SMLessonPage_createAd_card_bannerAds">
<img src={BannerAds} alt="BannerAds"/>
<div id="SMLessonPage_createAd_card_checkboxes">
<input type="checkbox" id="SMLessonPage_createAd_card_bannerAds_banner" onChange={this.bannerAdsHandler}></input>
<label for="vehicle1" id="SMLessonPage_createAd_card_bannerAds_banner_Text"> BannerAds </label>
</div>
</div>
<div id="SMLessonPage_createAd_card_bannerAds">
<img src={PostAds} alt="PostAds"/>
<div id="SMLessonPage_createAd_card_checkboxes">
<input type="checkbox" id="SMLessonPage_createAd_card_postAds_post" onClick={this.postAdsHandler}></input>
<label for="vehicle1" id="SMLessonPage_createAd_card_postAds_post_Text"> PostAds </label>
</div>
</div>
<div id="SMLessonPage_createAd_card_bannerAds">
<img src={VideoAds} alt="VideoAds"/>
<div id="SMLessonPage_createAd_card_checkboxes">
<input type="checkbox" id="SMLessonPage_createAd_card_videoAds_video" onClick={this.videoAdsHandler}></input>
<label for="vehicle1" id="SMLessonPage_createAd_card_videoAds_video_Text"> VideoAds </label>
</div>
</div>
</div>
</div>
<hr/>
<div id="SMLessonPage_createAd_card_middle">
<div id="SMLessonPage_createAd_card_middle_sliders">
<header> Now let's choose how much you want to spend and how long: </header>
<div id="SMLessonPage_createAd_card_middle_sliders_slider1">
<p>Advertising Budget:</p>
<input id="SMLessonPage_createAd_card_middle_sliders_slider1_input" onChange={this.sliderHandler} type="range" min="1" max="100000"></input>
<p>Value: <span id="output1"></span></p>
</div>
<div id="SMLessonPage_createAd_card_middle_sliders_slider2">
<p>Duration of Campaign:</p>
<input id="SMLessonPage_createAd_card_middle_sliders_slider2_input" onChange={this.sliderHandler} type="range" min="1" max="25"></input>
<p>Value: <span id="output2"></span></p>
</div>
</div>
<div id="SMLessonPage_createAd_card_middle_numbers">
<EstimatesComp bannerAds={this.state.bannerAds} postAds={this.state.postAds} videoAds={this.state.videoAds} budget={this.state.budget} weeks={this.state.weeks} setEstimatedReach={(estimatedReach,weeks) => this.setEstimatedReach(estimatedReach, weeks)} />
</div>
</div>
<hr/>
<div id="SMLessonPage_createAd_card_bottom">
<header> Once you're ready to run, just hit confirm and we will take it from there! </header>
<button type="submit" onClick={this.confirmButtonClicked} style={{marginTop:"40px", marginLeft:"600px", fontFamily:'Lato'}}> Confirm </button>
</div>
</div>
</div>
);
}
}
export default CreateAd;
|
C#
|
UTF-8
| 1,188 | 3.296875 | 3 |
[] |
no_license
|
using System;
namespace TddChessEngineLib
{
public class Elefant
{
public string curentPosition {get; private set;}
public Elefant(string position)
{
char[] pos = position.ToCharArray();
if(pos[0] == 'P')
{
throw new ArgumentException("cant craete elefante there");
}
else if(Convert.ToInt32(pos[1].ToString()) < 9 && Convert.ToInt32(pos[1].ToString()) > 0)
{
curentPosition = position;
}
else
{
throw new ArgumentException("cant craete elefante there");
}
}
public void Turn(string startPosition , string finishPosition)
{
if(startPosition == curentPosition)
{
if(startPosition == "E2" && finishPosition == "F2")
{
throw new ArgumentException("cant go there");
}
else if(startPosition == "E2" && finishPosition == "F3")
{
curentPosition = finishPosition;
}
}
}
}
}
|
C
|
UTF-8
| 7,331 | 2.515625 | 3 |
[
"MIT-Modern-Variant",
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
/**CFile****************************************************************
FileName [acecNorm.c]
SystemName [ABC: Logic synthesis and verification system.]
PackageName [CEC for arithmetic circuits.]
Synopsis [Adder tree normalization.]
Author [Alan Mishchenko]
Affiliation [UC Berkeley]
Date [Ver. 1.0. Started - June 20, 2005.]
Revision [$Id: acecNorm.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $]
***********************************************************************/
#include "acecInt.h"
ABC_NAMESPACE_IMPL_START
////////////////////////////////////////////////////////////////////////
/// DECLARATIONS ///
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/// FUNCTION DEFINITIONS ///
////////////////////////////////////////////////////////////////////////
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Acec_InsertHadd( Gia_Man_t * pNew, int In[2], int Out[2] )
{
int And, Or;
Out[1] = Gia_ManAppendAnd2( pNew, In[0], In[1] );
And = Gia_ManAppendAnd2( pNew, Abc_LitNot(In[0]), Abc_LitNot(In[1]) );
Or = Gia_ManAppendOr2( pNew, Out[1], And );
Out[0] = Abc_LitNot( Or );
}
void Acec_InsertFadd( Gia_Man_t * pNew, int In[3], int Out[2] )
{
int In2[2], Out1[2], Out2[2];
Acec_InsertHadd( pNew, In, Out1 );
In2[0] = Out1[0];
In2[1] = In[2];
Acec_InsertHadd( pNew, In2, Out2 );
Out[0] = Out2[0];
Out[1] = Gia_ManAppendOr2( pNew, Out1[1], Out2[1] );
}
Vec_Int_t * Acec_InsertTree( Gia_Man_t * pNew, Vec_Wec_t * vLeafMap )
{
Vec_Int_t * vRootRanks = Vec_IntAlloc( Vec_WecSize(vLeafMap) + 5 );
Vec_Int_t * vLevel;
int i, In[3], Out[2];
Vec_WecForEachLevel( vLeafMap, vLevel, i )
{
if ( Vec_IntSize(vLevel) == 0 )
{
Vec_IntPush( vRootRanks, 0 );
continue;
}
while ( Vec_IntSize(vLevel) > 1 )
{
if ( Vec_IntSize(vLevel) == 2 )
Vec_IntPush( vLevel, 0 );
//In[2] = Vec_IntPop( vLevel );
//In[1] = Vec_IntPop( vLevel );
//In[0] = Vec_IntPop( vLevel );
In[0] = Vec_IntEntry( vLevel, 0 );
Vec_IntDrop( vLevel, 0 );
In[1] = Vec_IntEntry( vLevel, 0 );
Vec_IntDrop( vLevel, 0 );
In[2] = Vec_IntEntry( vLevel, 0 );
Vec_IntDrop( vLevel, 0 );
Acec_InsertFadd( pNew, In, Out );
Vec_IntPush( vLevel, Out[0] );
if ( i+1 < Vec_WecSize(vLeafMap) )
vLevel = Vec_WecEntry(vLeafMap, i+1);
else
vLevel = Vec_WecPushLevel(vLeafMap);
Vec_IntPush( vLevel, Out[1] );
vLevel = Vec_WecEntry(vLeafMap, i);
}
assert( Vec_IntSize(vLevel) == 1 );
Vec_IntPush( vRootRanks, Vec_IntEntry(vLevel, 0) );
}
return vRootRanks;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
int Acec_InsertBox_rec( Gia_Man_t * pNew, Gia_Man_t * p, Gia_Obj_t * pObj )
{
if ( ~pObj->Value )
return pObj->Value;
assert( Gia_ObjIsAnd(pObj) );
Acec_InsertBox_rec( pNew, p, Gia_ObjFanin0(pObj) );
Acec_InsertBox_rec( pNew, p, Gia_ObjFanin1(pObj) );
return (pObj->Value = Gia_ManAppendAnd2( pNew, Gia_ObjFanin0Copy(pObj), Gia_ObjFanin1Copy(pObj) ));
}
Vec_Int_t * Acec_BuildTree( Gia_Man_t * pNew, Gia_Man_t * p, Vec_Wec_t * vLeafLits, Vec_Int_t * vRootLits )
{
Vec_Wec_t * vLeafMap = Vec_WecStart( Vec_WecSize(vLeafLits) );
Vec_Int_t * vLevel, * vRootRanks;
int i, k, iLit, iLitNew;
// add roo literals
if ( vRootLits )
Vec_IntForEachEntry( vRootLits, iLit, i )
{
if ( i < Vec_WecSize(vLeafMap) )
vLevel = Vec_WecEntry(vLeafMap, i);
else
vLevel = Vec_WecPushLevel(vLeafMap);
Vec_IntPush( vLevel, iLit );
}
// add other literals
Vec_WecForEachLevel( vLeafLits, vLevel, i )
Vec_IntForEachEntry( vLevel, iLit, k )
{
Gia_Obj_t * pObj = Gia_ManObj( p, Abc_Lit2Var(iLit) );
iLitNew = Acec_InsertBox_rec( pNew, p, pObj );
iLitNew = Abc_LitNotCond( iLitNew, Abc_LitIsCompl(iLit) );
Vec_WecPush( vLeafMap, i, iLitNew );
}
// construct map of root literals
vRootRanks = Acec_InsertTree( pNew, vLeafMap );
Vec_WecFree( vLeafMap );
return vRootRanks;
}
Gia_Man_t * Acec_InsertBox( Acec_Box_t * pBox, int fAll )
{
Gia_Man_t * p = pBox->pGia;
Gia_Man_t * pNew;
Gia_Obj_t * pObj;
Vec_Int_t * vRootRanks, * vLevel, * vTemp;
int i, k, iLit, iLitNew;
pNew = Gia_ManStart( Gia_ManObjNum(p) );
pNew->pName = Abc_UtilStrsav( p->pName );
pNew->pSpec = Abc_UtilStrsav( p->pSpec );
Gia_ManFillValue(p);
Gia_ManConst0(p)->Value = 0;
Gia_ManForEachCi( p, pObj, i )
pObj->Value = Gia_ManAppendCi( pNew );
// implement tree
if ( fAll )
vRootRanks = Acec_BuildTree( pNew, p, pBox->vLeafLits, NULL );
else
{
assert( pBox->vShared != NULL );
assert( pBox->vUnique != NULL );
vRootRanks = Acec_BuildTree( pNew, p, pBox->vShared, NULL );
vRootRanks = Acec_BuildTree( pNew, p, pBox->vUnique, vTemp = vRootRanks );
Vec_IntFree( vTemp );
}
// update polarity of literals
Vec_WecForEachLevel( pBox->vRootLits, vLevel, i )
Vec_IntForEachEntry( vLevel, iLit, k )
{
pObj = Gia_ManObj( p, Abc_Lit2Var(iLit) );
iLitNew = k ? 0 : Vec_IntEntry( vRootRanks, i );
pObj->Value = Abc_LitNotCond( iLitNew, Abc_LitIsCompl(iLit) );
}
Vec_IntFree( vRootRanks );
// construct the outputs
Gia_ManForEachCo( p, pObj, i )
Acec_InsertBox_rec( pNew, p, Gia_ObjFanin0(pObj) );
Gia_ManForEachCo( p, pObj, i )
pObj->Value = Gia_ManAppendCo( pNew, Gia_ObjFanin0Copy(pObj) );
Gia_ManSetRegNum( pNew, Gia_ManRegNum(p) );
return pNew;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Gia_Man_t * Acec_Normalize( Gia_Man_t * pGia, int fBooth, int fVerbose )
{
Vec_Bit_t * vIgnore = fBooth ? Acec_BoothFindPPG( pGia ) : NULL;
Acec_Box_t * pBox = Acec_DeriveBox( pGia, vIgnore, 0, 0, fVerbose );
Gia_Man_t * pNew = Acec_InsertBox( pBox, 1 );
Acec_BoxFreeP( &pBox );
Vec_BitFreeP( &vIgnore );
return pNew;
}
////////////////////////////////////////////////////////////////////////
/// END OF FILE ///
////////////////////////////////////////////////////////////////////////
ABC_NAMESPACE_IMPL_END
|
Python
|
UTF-8
| 10,214 | 2.546875 | 3 |
[] |
no_license
|
'''
Created 10/2019 Python 3.7 (2.7 has a problem with sqlalchemy-access)
Updated 01/2020
@author: Peter Vos VU IT for Research
Retrieve image and pdf file lists from mounted webdav connection and update the database with urls
Make sure to:
pip install SQLAlchemy
pip install sqlalchemy-access
set the correct paths in updater_scripts/config.py
'''
import updater_scripts.access as access
import updater_scripts.file_list_builder as file_list_builder
import re
def access_link(url):
return '#%s#' % url
def picture_id_list(file_list):
id_list = {}
for f in file_list:
basename = f
url = file_list[f][1]
#L10_2015_IMG_0035_43711885095_6b1fb97fe5_o.jpg
#L10_2015_IMG_0036_21436345845_o.jpg
s=re.search(r'(.+)_(\d{11})(_.+)?_o', basename)
if s:
picture_id = s.group(1)
else:
picture_id = basename
id_list[picture_id] = url
return id_list
def update_picture_urls(tbl, file_list):
print('update table %s' % tbl.__table__.name)
id_list = picture_id_list(file_list)
session = access.Session()
rows = session.query(tbl)
print('%s records in table' % rows.count())
total_db = 0
for row in rows.all():
if row is not None:
if row.Picture_ID.strip() in id_list:
total_db = total_db + 1
row.picture_url = access_link(id_list[row.Picture_ID.strip()])
print('%s picture_urls set in db' % (total_db))
print('commit changes')
session.commit()
session.close()
def update_drawing_urls(tbl, file_list):
print('update table %s' % tbl.__table__.name)
session = access.Session()
rows = session.query(tbl)
print('%s records in table' % rows.count())
total_db = 0
id_list = {}
# Drawing_No should be first 2 parts of filename
for f in file_list:
url = file_list[f][1]
a = f.split('_')
id = '%s_%s' % (a[0], a[1])
id_list[id] = url
for row in rows.all():
if row is not None:
if row.Drawing_No in id_list:
total_db = total_db + 1
row.Drawing_url = access_link(id_list[row.Drawing_No])
print('%s drawing_urls set in db' % (total_db))
print('commit changes')
session.commit()
session.close()
def update_lot_forms(tbl, file_list):
print('update table %s' % tbl.__table__.name)
session = access.Session()
rows = session.query(tbl)
print('%s records in table' % rows.count())
total_db = 0
for row in rows.all():
if row is not None:
try:
id = '%s_%s_%s_lot_form' % (row.Trench, row.Date.year, int(row.Lot))
if id in file_list:
total_db = total_db + 1
row.Link_to_scanned_lot_form = access_link(file_list[id][1])
else:
row.Link_to_scanned_lot_form = ''
except:
print('error, no Date in database?')
print('Trench %s | Lot %s | Date %s' % (row.Trench, int(row.Lot), row.Date))
session.commit()
print('%s link_to_scanned_lot_forms set in db' % (total_db))
print('commit changes')
session.close()
def update_daily_reports(tbl, file_list):
print('update table %s' % tbl.__table__.name)
session = access.Session()
rows = session.query(tbl)
print('%s records in table' % rows.count())
total_db = 0
for row in rows.all():
if row is not None:
try:
id = '%s_%s_%s_%s_daily_report' % (
row.Trench, '{:02}'.format(row.Date.day), '{:02}'.format(row.Date.month), row.Date.year)
if id in file_list:
total_db = total_db + 1
row.Link_to_daily_report = access_link(file_list[id][1])
else:
row.Link_to_daily_report = ''
except:
print('error, no Date in database?')
print('Trench %s | Date %s' % (row.Trench, row.Date))
session.commit()
print('%s link_to_daily_reports set in db' % (total_db))
print('commit changes')
session.close()
def update_daily_sketches(tbl, file_list):
print('update table %s' % tbl.__table__.name)
session = access.Session()
rows = session.query(tbl)
print('%s records in table' % rows.count())
total_db = 0
for row in rows.all():
if row is not None:
try:
id = '%s_%s_%s_%s_daily_sketch' % (
row.Trench, '{:02}'.format(row.Date.day), '{:02}'.format(row.Date.month), row.Date.year)
if id in file_list:
total_db = total_db + 1
row.Link_to_scanned_daily_sketch = access_link(file_list[id][1])
else:
row.Link_to_scanned_daily_sketch = ''
except:
print('error, no Date in database?')
print('Trench %s | Lot %s | Date %s' % (row.Trench, int(row.Lot), row.Date))
session.commit()
print('%s link_to_daily_sketches set in db' % (total_db))
print('commit changes')
session.close()
def update_bh_picture_urls(tbl, file_list, url_changed = False):
print('update table %s' % tbl.__table__.name)
session = access.Session()
total_db = 0
for f in file_list:
m = re.match(r'^BH(\d+)_.+', f)
if m:
url = file_list[f][1]
bhnum = m.group(1)
if url_changed:
q=session.query(tbl).filter(tbl.BH_Number == bhnum)
q.delete()
# a BH_Number can have more than one picture, so the combination is unique
q = session.query(tbl).filter(tbl.BH_Number == bhnum, tbl.picture_url == access_link(url))
if q.count() == 0: # new record
bh = tbl(
BH_Number=bhnum,
picture_url=access_link(url)
)
session.add(bh)
total_db = total_db + 1
session.commit()
print('%s picture_urls set in db' % (total_db))
print('commit changes')
session.close()
def update_bh_drawing_urls(tbl, file_list, url_changed = False):
print('update table %s' % tbl.__table__.name)
session = access.Session()
total_db = 0
for f in file_list:
m = re.match(r'^BH(\d+)_.+', f)
if m:
url = file_list[f][1]
bhnum = m.group(1)
if url_changed:
q=session.query(tbl).filter(tbl.BH_number == bhnum)
q.delete()
# a BH_Number can have more than one picture, so the combination is unique
q = session.query(tbl).filter(tbl.BH_number == bhnum, tbl.Link_to_BH_drawing == access_link(url))
if q.count() == 0: # new record
bh = tbl(
BH_number=bhnum,
Link_to_BH_drawing=access_link(url)
)
session.add(bh)
total_db = total_db + 1
session.commit()
print('%s drawing_urls set in db' % (total_db))
print('commit changes')
session.close()
def update_trench_reports(tbl, file_list, url_changed = False):
print('update table %s' % tbl.__table__.name)
session = access.Session()
total_db = 0
for f in file_list:
m = re.match(r'^([A-Z].+)_(\d{4})_trench_report', f)
if m:
url = file_list[f][1]
trench = m.group(1)
year = m.group(2)
q = session.query(tbl).filter(tbl.Trench == trench, tbl.Trench_Year == year)
if url_changed:
q.delete()
q = session.query(tbl).filter(tbl.Trench == trench, tbl.Trench_Year == year)
if q.count() == 0: # new record
tr = tbl(
Trench=trench,
Trench_Year=year,
Trench_report_URL=access_link(url)
)
session.add(tr)
total_db = total_db + 1
session.commit()
print('%s trench_report_urls set in db' % (total_db))
print('commit changes')
session.close()
list_rebuild = True
if input("Get new directory listing? (y/n)") == "n":
list_rebuild = False
url_changed = False
if input("Has the root YODA WebDAV url changed? (y/n)") == "y":
url_changed = True
# UPDATE 1
file_list = file_list_builder.get_file_list('PLANS', list_rebuild)
print('%s files found in PLANS' % len(file_list))
update_drawing_urls(access.locus_drawings, file_list)
# UPDATE 2
update_drawing_urls(access.drawings_fieldwork, file_list)
print()
# UPDATE 3
file_list = file_list_builder.get_file_list('LOT_FORMS', list_rebuild)
print('%s files found in LOT_FORMS' % len(file_list))
update_lot_forms(access.lot, file_list)
print()
# UPDATE 4
file_list = file_list_builder.get_file_list('DAILY_REPORTS', list_rebuild)
print('%s files found in DAILY_REPORTS' % len(file_list))
update_daily_reports(access.lot, file_list)
print()
# UPDATE 5
file_list = file_list_builder.get_file_list('SKETCHES', list_rebuild)
print('%s files found in SKETCHES' % len(file_list))
update_daily_sketches(access.lot, file_list)
print()
# UPDATE 6
file_list = file_list_builder.get_file_list('PICTURES', list_rebuild)
print('%s files found in PICTURES' % len(file_list))
update_picture_urls(access.pictures_fieldwork, file_list)
update_picture_urls(access.pictures_fieldwork_BH, file_list)
update_picture_urls(access.pictures_fieldwork_Locus, file_list)
update_picture_urls(access.pictures_fieldwork_Nails, file_list)
update_picture_urls(access.pictures_fieldwork_Structure, file_list)
update_picture_urls(access.pictures_fieldwork_Locus_Lot, file_list)
# UPDATE 7
update_bh_picture_urls(access.BH_pictures, file_list, url_changed)
# UPDATE 8
file_list = file_list_builder.get_file_list('OBJECT_DRAWINGS', list_rebuild)
print('%s files found in OBJECT_DRAWINGS' % len(file_list))
update_bh_drawing_urls(access.BH_drawings, file_list, url_changed)
# UPDATE 9
file_list = file_list_builder.get_file_list('TRENCH_REPORTS', list_rebuild)
print('%s files found in TRENCH_REPORTS' % len(file_list))
update_trench_reports(access.trench, file_list, url_changed)
|
Java
|
UTF-8
| 1,074 | 3.328125 | 3 |
[] |
no_license
|
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int [][]graph = new int[n][n];
for (int i = 0; i < m; i++) {
int v1 = sc.nextInt();
int v2 = sc.nextInt();
graph[v1 - 1][v2 - 1] = 1;
graph[v2 - 1][v1 - 1] = 1;
}
output(graph);
System.out.println(components(graph, 0));
}
public static void output (int [][]arr) {
for (int []x: arr) {
for (int n: x) {
System.out.print(n+" ");
}
System.out.println();
}
}
public static int components (int [][]graph, int v) {
int comp = 0;
for (int i = 0; i < graph.length; i++) {
if (graph[v][i] == 1) {
graph[v][i] = 0;
graph[i][v] = 0;
comp += components(graph, i);
}
}
return comp;
}
}
|
Rust
|
UTF-8
| 5,706 | 2.984375 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
/*!
# Introduction
`logdog` is a program that gathers logs from various places on a Bottlerocket host and combines them
into a tarball for easy export.
Usage example:
```shell
$ logdog
logs are at: /var/log/support/bottlerocket-logs.tar.gz
```
# Logs
For the log requests used to gather logs, please see the following:
* [log_request](src/log_request.rs)
* [logdog.common.conf](conf/logdog.common.conf)
* And the variant-specific files in [conf](conf/), one of which is selected by [build.rs](build.rs)
based on the value of the `VARIANT` environment variable at build time.
*/
mod create_tarball;
mod error;
mod log_request;
use create_tarball::create_tarball;
use error::Result;
use log_request::{handle_log_request, log_requests};
use snafu::{ErrorCompat, ResultExt};
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::{env, process};
use tempfile::TempDir;
const ERROR_FILENAME: &str = "logdog.errors";
const OUTPUT_FILENAME: &str = "bottlerocket-logs.tar.gz";
const OUTPUT_DIRNAME: &str = "/var/log/support";
const TARBALL_DIRNAME: &str = "bottlerocket-logs";
/// Prints a usage message in the event a bad arg is passed.
fn usage() -> ! {
let program_name = env::args().next().unwrap_or_else(|| "program".to_string());
eprintln!(
r"Usage: {}
[ --output PATH ] where to write archived logs
",
program_name,
);
process::exit(2);
}
/// Prints a more specific message before exiting through usage().
fn usage_msg(msg: &str) -> ! {
eprintln!("{}\n", msg);
usage();
}
/// Parses the command line arguments.
fn parse_args(args: env::Args) -> PathBuf {
let mut output_arg = None;
let mut iter = args.skip(1);
while let Some(arg) = iter.next() {
match arg.as_ref() {
"--output" => {
output_arg = Some(
iter.next()
.unwrap_or_else(|| usage_msg("Did not give argument to --output")),
)
}
_ => usage(),
}
}
match output_arg {
Some(path) => PathBuf::from(path),
None => PathBuf::from(OUTPUT_DIRNAME).join(OUTPUT_FILENAME),
}
}
/// Runs a list of log requests and writes their output into files in `outdir`. Any failures are
/// noted in the file named by `ERROR_FILENAME`. Note: In the case of `exec` log requests, non-zero
/// exit codes are not considered errors and the command's stdout and stderr will be still be
/// written.
pub(crate) async fn collect_logs<P: AsRef<Path>>(log_requests: &[&str], outdir: P) -> Result<()> {
// if a command fails, we will pipe its error here and continue.
let outdir = outdir.as_ref();
let error_path = outdir.join(crate::ERROR_FILENAME);
let mut error_file = File::create(&error_path).context(error::ErrorFileSnafu {
path: error_path.clone(),
})?;
for &log_request in log_requests {
// show the user what command we are running
println!("Running: {}", log_request);
if let Err(e) = handle_log_request(log_request, &outdir).await {
// ignore the error, but make note of it in the error file.
writeln!(
&mut error_file,
"Error running command '{}': '{}'",
log_request, e
)
.context(error::ErrorWriteSnafu {
path: error_path.clone(),
})?;
}
}
Ok(())
}
/// Runs the bulk of the program's logic, main wraps this.
async fn run(outfile: &Path, commands: &[&str]) -> Result<()> {
let temp_dir = TempDir::new().context(error::TempDirCreateSnafu)?;
collect_logs(commands, &temp_dir.path().to_path_buf()).await?;
create_tarball(temp_dir.path(), outfile)?;
println!("logs are at: {}", outfile.display());
Ok(())
}
#[tokio::main]
async fn main() -> ! {
let outpath = parse_args(env::args());
let log_requests = log_requests();
process::exit(match run(&outpath, &log_requests).await {
Ok(()) => 0,
Err(err) => {
eprintln!("{}", err);
if let Some(var) = env::var_os("RUST_BACKTRACE") {
if var != "0" {
if let Some(backtrace) = err.backtrace() {
eprintln!("\n{:?}", backtrace);
}
}
}
1
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use flate2::read::GzDecoder;
use std::fs::File;
use tar::Archive;
#[tokio::test]
async fn test_program() {
let output_tempdir = TempDir::new().unwrap();
let outfile = output_tempdir.path().join("logstest");
// we assume that `echo` will not do something unexpected on the machine running this test.
let commands = vec!["exec hello.txt echo hello world"];
run(&outfile, &commands).await.unwrap();
// this function will panic if the given path is not found in the tarball.
let find = |path_to_find: &PathBuf| {
let tar_gz = File::open(&outfile).unwrap();
let tar = GzDecoder::new(tar_gz);
let mut archive = Archive::new(tar);
let mut entries = archive.entries().unwrap();
let _found = entries
.find(|item| {
let entry = item.as_ref().unwrap();
let path = entry.path().unwrap();
path == *path_to_find
})
.unwrap()
.unwrap();
};
// assert that the expected paths exist in the tarball
find(&PathBuf::from(TARBALL_DIRNAME));
find(&PathBuf::from(TARBALL_DIRNAME).join("hello.txt"));
}
}
|
Java
|
WINDOWS-1251
| 2,864 | 4.21875 | 4 |
[] |
no_license
|
package ua.edu.uabs.author.task2;
public class Dean {
private String FirstName, SecondName, LastName;
private int age, stud;
//Getter Setter ( ) ,
//Getter
//SEtter
// public, private.
//public
//private -
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getSecondName() {
return SecondName;
}
public void setSecondName(String secondName) {
SecondName = secondName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public int getAge() {
return age;
}
// if , 25 70,
public void setAge(int age) {
if(age>=25 && age<=70){
this.age = age;
}
else{
System.out.println(" .");
System.exit(0);//
}
}
public int getStud() {
return stud;
}
public void setStud(int stud) {
this.stud = stud;
}
// ( )
public void ShortOutput(){
System.out.println(": "+LastName+" "+FirstName+" "+SecondName+", : "+age+", - : "+stud+".");
}
// ( , .toUpperCase())
public void UpperOutput(){
System.out.println(": "+LastName.toUpperCase()+" "+FirstName.toUpperCase()+" "+SecondName.toUpperCase()+", ²: "+age+", - : "+stud+".");
}
// , , Setters
public Dean(){};
//
public Dean(String firstName, String secondName, String lastName, int age, int stud) {
this.FirstName = firstName;
this.SecondName = secondName;
this.LastName = lastName;
this.setAge(age);
this.stud = stud;
}
}
|
Java
|
UTF-8
| 327 | 2.015625 | 2 |
[
"BSD-2-Clause"
] |
permissive
|
package com.gmail.jannyboy11.customrecipes.api.crafting.custom.recipe;
import com.gmail.jannyboy11.customrecipes.api.crafting.vanilla.recipe.ShapedRecipe;
/**
* Represents an NBT recipe.
* The items in the choices list take NBT data into account.
*
* @author Jan
*/
public interface NBTRecipe extends ShapedRecipe {
}
|
PHP
|
UTF-8
| 2,318 | 2.90625 | 3 |
[] |
no_license
|
<?php
require_once '../models/MovieModel.php';
require_once '../bl/Movie_BLL.php';
class MovieController {
function getAll_Movies() {
$movie_bll = new Movie_BLL();
$resultSet = $movie_bll->get_movies();
$allMovies = array();
//$errorInInput will contain any problems found in data retrieved from db () creating MovieModel
//object automatically validates the data - at this stage no further processing occurs with any faulty
//db data
$errorInInput = "";
while ($row = $resultSet->fetch())
{
array_push($allMovies, new MovieModel([ "movie_id" => $row['movie_id'],
"movie_name" => $row['movie_name'],
"director_id" => $row['director_id'],
"director_name" => $row['director_name']],
$errorInInput));
}
return $allMovies;
}
function create_update_Movie($params, $method, &$applicationError) {
$Movie = new MovieModel($params, $applicationError);
if ($applicationError != "") { //error found in data members of movie object - faulty user input
return;
}
$movie_bll = new Movie_BLL();
//insert => if movie already exists $applicationError will contain corresponding message and movies-api.php will send apropriate message back to client
$movie_bll->insert_update_movie($params, $method, $applicationError);
}
function delete_Movie($params) {
$movie_bll = new Movie_BLL();
$movie_bll->delete_movie($params);
}
function getMovieByNameDirector($params) { //used for js remote validation
$movie_bll = new Movie_BLL();
$movie_id = $movie_bll->check_movie_exists($params);
if ($movie_id == false){ //no movie found with given movie name and director ID
$movie_id = ["id" => -1];
}
return $movie_id;
}
}
?>
|
Markdown
|
UTF-8
| 2,200 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
+++
date = "2021-07-25"
title = "Phase Field Models of the Growth of Tumors Embedded in an Evolving Vascular Network: Dynamic 1D-3D Models of Angiogenesis"
abstract = "In this talk, we present a coupled 3D-1D model of tumor growth within a dynamically changing vascular network to facilitate realistic simulations of angiogenesis. Additionally, the model includes ECM erosion, interstitial flow, and coupled flow in vessels and tissue. We employ continuum mixture theory with stochastic Cahn–Hilliard type phase-field models of tumor growth. The interstitial flow is governed by a mesoscale version of Darcy’s law. The flow in the blood vessels is controlled by Poiseuille flow, and Starling’s law is applied to model the mass transfer in and out of blood vessels. The evolution of the network of blood vessels is orchestrated by the concentration of the tumor angiogenesis factor (TAF) by growing towards increasing TAF concentration. The process is not deterministic, allowing random growth of blood vessels and, therefore, due to the coupling of nutrients in tissue and vessels, stochastic tumor growth. We demonstrate the performance of the model by applying it to a variety of scenarios. Numerical experiments illustrate the flexibility of the model and its ability to generate satellite tumors. Simulations of the effects of angiogenesis on tumor growth are presented as well as sample-independent features of cancer. This is joint work with Dr. J. T. Oden at the University of Texas at Austin, M. Fritz, Dr. T. Köppl, A. Wagner, and Dr. B. Wohlmuth at the Technical University of Munich. The work of PKJ and JTO was supported by the U.S. Department of Energy, Office of Science, Office of Advanced Scientific Computing Research, Mathematical Multifaceted Integrated Capability Centers (MMICCS), under Award Number DE-SC0019303."
abstract_short = ""
event = "USNCCM16 2021"
event_url = "http://16.usnccm.org/"
location = "Virtual Conference"
selected = true
math = false
#url_pdf = ""
#url_slides = ""
#url_video = ""
# Optional featured image (relative to `static/img/` folder).
#[header]
#image = ""
#caption = "My caption:"
+++
> This work will be presented by a co-author Marvin Fritz (TUM, Germany).
|
C++
|
WINDOWS-1250
| 1,565 | 3 | 3 |
[] |
no_license
|
// Zadanie 2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <conio.h> //Dodanie bibliotek.
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
double long x, y, wy, wx, w; //Deklaracja zmiennych zmiennoprzecinkowych.
int a, b, c, d, e, f; //Deklaracja zmiennych cakowitych.
cout << "\n\t\tProgram obliczaj\245cy \n\t\tuk\210ad r\242wna\344 liniowych";
cout << "\n\t\tPostaci:\n\tax + by = e\n\tcx + dy = f\n\n";
cout << "\t\tPodaj wsp\242\210czynnik a: "; cin >> a;
cout << "\t\tPodaj wsp\242\210czynnik b: "; cin >> b;
cout << "\t\tPodaj wsp\242\210czynnik e: "; cin >> e;
cout << "\t\tPodaj wsp\242\210czynnik c: "; cin >> c;
cout << "\t\tPodaj wsp\242\210czynnik d: "; cin >> d;
cout << "\t\tPodaj wsp\242\210czynnik f: "; cin >> f;
cout << "\n\t" << a << "x+" << b << "y=" << e;
cout << "\n\t" << c << "x+" << d << "y=" << f; //Opis dziaania programu, i pobranie danych.
w = a*d - b*c;
wx = e*d - b*f;
wy = a*f - e*c; //Wykonanie dziaa.
if (w == 0 && (wx != 0 || wy != 0)) //Sprawdzanie, czy ukad nie jest sprzeczny.
cout << "Uk\210ad jest sprzeczny";
else if (w == 0 && wx == 0 && wy == 0) //Sprawdzanie, czy ukad jest oznaczony.
cout << "Uk\210ad jest nieoznaczony";
else
{
x = wx / w;
y = wy / w; //Obliczenie x i y.
cout << "\n\t\tx=" << x;
cout << "\n\t\ty=" << y; //Wypisanie wyniku.
}
_getch();
return 0;
}
|
Python
|
UTF-8
| 4,002 | 2.703125 | 3 |
[] |
no_license
|
import pyaudio
import ssl
import socket
import pprint
import multiprocessing
import os
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
class Audio:
def __init__(self):
self.p = None
self.in_stream = None
self.out_stream = None
def start_audio(self):
self.p = pyaudio.PyAudio()
self.in_stream = self.p.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
input = True,
frames_per_buffer = CHUNK)
self.out_stream = self.p.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
output = True)
def close_audio(self):
self.out_stream.stop_stream()
self.out_stream.close()
self.in_stream.stop_stream()
self.in_stream.close()
self.p.terminate()
def record_audio(self):
data = self.in_stream.read(CHUNK)
return data
def play_audio(self, data):
self.out_stream.write(data)
def loop_chunk(self):
self.play_audio(self.record_audio())
def prepare_client():
c_ctx = ssl.SSLContext(protocol = ssl.PROTOCOL_TLSv1_2)
c_ctx.verify_mode = ssl.CERT_REQUIRED
c_ctx.check_hostname = False
c_ctx.load_cert_chain(certfile = 'build/client_ec.crt',
keyfile = 'build/client_ec')
c_ctx.load_verify_locations(cafile = 'build/server_ec.crt')
return c_ctx
def prepare_server():
s_ctx = ssl.SSLContext(protocol = ssl.PROTOCOL_TLSv1_2)
s_ctx.verify_mode = ssl.CERT_REQUIRED
s_ctx.check_hostname = False
s_ctx.load_cert_chain(certfile = 'build/server_ec.crt',
keyfile = 'build/server_ec')
s_ctx.load_verify_locations(cafile = 'build/client_ec.crt')
return s_ctx
def create_client(c_ctx):
a = Audio()
c_conn = c_ctx.wrap_socket(socket.socket(socket.AF_INET),
server_hostname = os.environ['CLIENT_HOST'])
c_conn.connect(("localhost", int(os.environ['CLIENT_PORT'])))
try:
c_cert = c_conn.getpeercert()
pprint.pprint(c_cert)
a.start_audio()
while True:
c_conn.send(a.record_audio())
finally:
a.close_audio()
c_conn.shutdown(socket.SHUT_RDWR)
c_conn.close()
def create_server(s_ctx):
a = Audio()
s_conn = socket.socket()
s_conn.bind((os.environ['SERVER_HOST'],
int(os.environ['SERVER_PORT'])))
s_conn.listen(5)
while True:
s_newsocket, s_fromaddr = s_conn.accept()
s_connstream = s_ctx.wrap_socket(s_newsocket, server_side = True)
try:
a.start_audio()
data = s_connstream.recv(CHUNK)
while data:
a.play_audio(data)
data = s_connstream.recv(CHUNK)
finally:
a.close_audio()
s_connstream.shutdown(socket.SHUT_RDWR)
s_connstream.close()
def test1():
a = Audio()
a.start_audio()
for k in range(1000):
a.loop_chunk()
a.close_audio()
def test2():
try:
s = multiprocessing.Process(target = create_server,
args = (prepare_server(),))
c = multiprocessing.Process(target = create_client,
args = (prepare_client(),))
s.start()
c.start()
finally:
s.join()
c.join()
def test3():
try:
s = multiprocessing.Process(target = create_server,
args = (prepare_server(),))
s.start()
finally:
s.join()
def test4():
try:
c = multiprocessing.Process(target = create_client,
args = (prepare_client(),))
c.start()
finally:
c.join()
|
Java
|
UTF-8
| 1,841 | 1.992188 | 2 |
[] |
no_license
|
package com.qf.group6.service;
import com.qf.group6.entity.*;
import java.util.List;
/**
* @Author: ZongMan
* @Date: 2019/2/11 0011
* @Time: 15:01
* @Vsersion: 1.0
**/
public interface CommunityService {
/**
* 通过当前用户的id查看关注的所有人的id
* @param userId 当前用户的id
* @return List集合
*/
List<TopicUser> findByUserId(Integer userId);
/**
* 通过被关注人的id查看被关注的动态
* @param userId 被关注人id
* @return TopicUser对象
*/
TopicUser findByBeUserId(Integer userId);
/**
* 通过用户id来查看话题详情页面
* @param userId 用户id
* @return TopicInfo对象
*/
List<TopicInfo> findTopicInfoByUserId(Integer userId);
/**
*
* @param userId
* @return
*/
TopicInfo findTopicByUserId(Integer userId);
/**
* 通过话题id查询评论列表
* @param topicId 话题id
* @return list列表
*/
List<TopicInfo> findCommentByUserId(int topicId);
/**
* 添加评论
* @param topicUser
* @return
*/
int addComment(TopicUser topicUser);
/**
* 关注或者取消关注功能
* @param userFocusUser
* @return
*/
int focus(UserFocusUser userFocusUser);
/**
* 通过用户id查看用户信息
* @param userId 用户id
* @return UserInfo对象
*/
UserInfo findUserInfoByUserId(Integer userId);
/**
* 发布动态
* @param dynInfo 动态信息
* @return 1成功
*/
int myArtPublish(DynInfo dynInfo);
/**
* 精选查询
* @return
*/
List<TopicInfo> findAll();
/**
* 个人模块
* @param userId 用户id
* @return
*/
List<TopicInfo> findByTopicInfo(Integer userId);
}
|
JavaScript
|
UTF-8
| 1,483 | 2.59375 | 3 |
[] |
no_license
|
// ==UserScript==
// @name LibraryThing add ten authors at a time
// @description A shortcut for adding multiple "Other authors" inputs at once
// @namespace http://userscripts.org/users/maxstarkenburg
// @include http*://*librarything.tld/work/*edit/*
// @include http*://*librarything.com/work/*edit/*
// @include http*://*librarything.tld/addnew.php*
// @include http*://*librarything.com/addnew.php*
// @version 1.1
// @grant none
// ==/UserScript==
// Find the "add another author" link and put a "add another 10 authors" link next to it
var addAnotherAuthor = document.evaluate(
'//div[@id="addPersonControl"]//a',
document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
if (addAnotherAuthor.snapshotLength > 0) {
addAnotherAuthor = addAnotherAuthor.snapshotItem(0);
addTenAuthors = document.createElement('span');
addTenAuthors.innerHTML = ' | <a href="javascript:addTenPersons();">add another 10 authors</a>'
var par = addAnotherAuthor.parentNode;
par.insertBefore(addTenAuthors, addAnotherAuthor.nextSibling);
}
// Append to the document body the function that repeats addPerson() 10 times
var body = document.getElementsByTagName("body")[0];
var script = document.createElement("script");
script.type = "text/javascript";
script.innerHTML = '\
function addTenPersons() {\
for (var i=0; i<10; i++) {\
addPerson();\
}\
}\
';
body.appendChild(script);
|
Swift
|
UTF-8
| 1,289 | 2.65625 | 3 |
[] |
no_license
|
//
// MoyaResponse+Toast.swift
// Smakfull
//
// Created by Magdusz on 04.04.2018.
// Copyright © 2018 com.mcpusz.smakfull. All rights reserved.
//
import Foundation
import Moya
import MCToast
extension Moya.Response {
func printToast() {
if let request = self.request {
var toastText = "Response Status Code: \(self.statusCode)"
if let responseBody = try? JSONSerialization.jsonObject(with: self.data, options: []) {
toastText += " \nResponse Body: \(responseBody)"
}
if let method = request.httpMethod {
toastText += " \nRequest Method: \(method)"
}
if let url = request.url {
toastText += " \nRequest URL: \(url)"
}
if let fields = request.allHTTPHeaderFields {
toastText += " \nRequest HTTP Fields: \(fields)"
}
if let requestBodyData = request.httpBody, let requestBodyJson = try? JSONSerialization.jsonObject(with: requestBodyData, options: []) {
toastText += " \nRequest Body: \(requestBodyJson)"
}
_ = MCToast(text: toastText)
print(toastText)
//quack
}
}
}
|
C#
|
UTF-8
| 1,254 | 3.25 | 3 |
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
string myString = null ;
Operation myOperation = new Operation();
myDescription = ServiceDescription.Read("Operation_2_Input_CS.wsdl");
Message[] myMessage = new Message[ myDescription.Messages.Count ] ;
// Copy the messages from the service description.
myDescription.Messages.CopyTo( myMessage, 0 );
for( int i = 0 ; i < myDescription.Messages.Count; i++ )
{
MessagePart[] myMessagePart =
new MessagePart[ myMessage[i].Parts.Count ];
// Copy the message parts into a MessagePart.
myMessage[i].Parts.CopyTo( myMessagePart, 0 );
for( int j = 0 ; j < myMessage[i].Parts.Count; j++ )
{
myString += myMessagePart[j].Name;
myString += " " ;
}
}
// Set the ParameterOrderString equal to the list of
// message part names.
myOperation.ParameterOrderString = myString;
string[] myString1 = myOperation.ParameterOrder;
int k = 0 ;
Console.WriteLine("The list of message part names is as follows:");
while( k<5 )
{
Console.WriteLine( myString1[k] );
k++;
}
|
C++
|
UTF-8
| 4,027 | 2.78125 | 3 |
[] |
no_license
|
#ifndef CHESS_SYSTEM_H
#define CHESS_SYSTEM_H
#include"System.h"
#include"Board.h"
#include"Pawn.h"
#include"Queen.h"
#include"Rook.h"
#include"Bishop.h"
#include"Knight.h"
#include"King.h"
#include"ChessCamera.h"
#include"LightPanel.h"
//keys for loaded shaders
#define TEXTURE_SHADER "textureShader"
#define LIGHT_SHADER "lightShader"
//keys for loaded textures
#define LIGHT_PANEL "lightPanel"
#define BLACK_TEXTURE "black"
#define WHITE_TEXTURE "white"
#define BOARD_TEXTURE "board"
//how many tiles are on a chess board
#define TILE_COUNT 64
class ChessSystem : public GlSystem {
public:
/*
Safely initialize member variables
*/
ChessSystem();
/*
@see GlSystem::initialize()
*/
virtual GLboolean initialize(const size_t& width, const size_t& height, const bool fullscreen);
/*
Compiles the models into the engine's binary format
*/
static void install();
/*
Deletes system resources
*/
virtual ~ChessSystem();
private:
/*
Adds a piece to the boards internal memory, this class will delete the object
when it is destroyed
@param piece
piece to be added
*/
void addPiece(ChessPiece* piece);
/*
Adds a board to the system internal memory, this class will delete the object
when it is destroyed
@param board
board to be used
*/
void addBoard(Board* board);
/*
Builds the shaders and textures for the game
*/
void buildAssets();
/*
Adds all the openGL object onto into the game
*/
void addObjects();
/*
Adds all the pawns to the board
*/
void addPawns();
/*
Adds all the rooks to the board
*/
void addRooks();
/*
Adds all the knights to the board
*/
void addKnights();
/*
Adds all the bishops to the board
*/
void addBishops();
/*
Adds all the queens to the board
*/
void addQueens();
/*
Adds all the kings to the board
*/
void addKings();
/*
Adds all the direction panels to the board
*/
void addPanels();
/*
Runs a single frame of the application
*/
virtual const bool frame();
/*
Processes user input and game logic
*/
void processGameLogic();
/*
Moves the currently bound piece to the mouse location
*/
void moveGrabbedPiece();
/*
Attempts to grab a piece from the mouse and binds it to this object
*/
void grabPiece();
/*
Clears the bound piece and places back onto the board,
if the user selected move is illegal, returns the piece to its initial position
checks for capture,
checks for entering check
*/
void releasePiece();
/*
Remove the provided piece completely from the system
@param piece
The piece to remove
*/
void removePieceFromSystem(ChessPiece* piece);
/*
Highlights all of the provided moves on the board
@param moves
the vector of moves to make
*/
void highlightMoves(const std::vector<Move> moves);
/*
Clears all of the highlighted moves
*/
void clearHighlightedMoves();
/*
The object (piece) currently bound to the cursor, null if none is set
*/
ChessPiece* pGrabbed;
/*
The position in model space that the currently bound piece was grabbed on,
this is used to keep the piece allignment when dragging
*/
glm::vec3 grabLocation;
/*
Reference to the board
*/
Board* pBoard;
/*
The pieces on the board
*/
std::vector<ChessPiece*> pieces;
/*
The left mouse button state during the last frame, this is used to detect when a click occurrs
*/
GLboolean lastMouseState;
/*
Which colors turn it is
*/
GLboolean whoseTurn;
/*
A vector of places to put point lights
*/
std::vector<glm::vec3>* lights;
/*
A vector of the panels, the panel under 8x + z is at (x, z)
*/
std::vector<LightPanel*> lightPanels;
/*
Shaders to use then delete
*/
std::map<std::string, Shader*> shaders;
/*
Textures to use then delete
*/
std::map<std::string, Texture*> textures;
};
#endif
|
Markdown
|
UTF-8
| 1,579 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
# Readings in Databases
A list of papers studied in CS380D Distributed Systems.
[Google spreadsheet view](https://docs.google.com/spreadsheets/d/1fdh8zYxRyJtNtfOwcS0-mMpAyhmjckaGP8vA3NWsTRU/edit#gid=0)
is maintained by [Prof.Vijay Chidambaram](http://www.cs.utexas.edu/~vijay/).
## <a name='TOC'>Table of Contents</a>
1. [Introduction](#intro)
2. [Clocks, State Machines, and Consistency Models](#consistency)
3. [Update Propogation](#update)
4. [Consensus](#consensus)
5. [Distributed Transactions](#trans)
6. [Decentralized Systems, Byzantine Fault Tolerance](#fault)
7. [Distributed Storage Systems](#storage)
8. [Cloud Programming Models and Datacenters](#datacenters)
9. [Machine Learning in Distributed Systems](#ml)
10. [Cryptocurrencies](#crypt)
## <a name='intro'> Introduction
* [Introduction to Distributed System Design](http://www.hpcs.cs.tsukuba.ac.jp/~tatebe/lecture/h23/dsys/dsd-tutorial.html).
## <a name='consistency'> Clocks, State Machines, and Consistency Models
## <a name='update'> Update Propogation
## <a name='consensus'> Consensus
## <a name='trans'> Distributed Transactions
## <a name='fault'> Decentralized Systems, Byzantine Fault Tolerance
## <a name='storage'> Distributed Storage Systems
## <a name='datacenters'> Cloud Programming Models and Datacenters
## <a name='ml'> Machine Learning in Distributed Systems
## <a name='crypt'> Cryptocurrencies
# Credits
The organization of this doc steals from Reynold Xin ([@rxin](http://twitter.com/rxin))'s [Readings in Databases](https://github.com/rxin/db-readings).
|
Python
|
UTF-8
| 12,630 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env python3
# PROGRAMMER: Krishang Naikar
# DATE CREATED: 10/23/2020
# REVISED DATE:
# Imports here
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
import os
import time
import helper
from workspace_utils import active_session
from collections import OrderedDict
import json
import argparse
from PIL import Image
arch_ins = {"vgg16":25088,
"densenet121":1024
}
def get_input_args():
"""
This function parses the command line arguments
Command Line Arguments:
1. Train Image Folder as --data_dir
2. Folder to save the training data as --save_dir with default value current working dir
2. Model Architecture as --arch with default value 'vgg'
3. Hyperparameters as --learning_rate 0.001 --hidden_units 512 --epochs 20 with respective defaults
4. Use of device as --gpu with default as "cpu"
This function returns these arguments as an ArgumentParser object.
Parameters:
None - simply using argparse module to create & store command line arguments
Returns:
parse_args() -data structure that stores the command line arguments object
"""
# Create Parse using ArgumentParser
parser = argparse.ArgumentParser()
# Create 3 command line arguments as mentioned above using add_argument() from ArguementParser method
parser.add_argument('--data_dir', type = str, default = 'flowers', required=True,
help = 'path to the folder of training images eg: flowers')
parser.add_argument('--save_dir', type = str, default ='./checkpoint.pth',
help = 'path to the folder and file_name to save the trained model')
parser.add_argument('--arch', type = str, default = 'vgg16',
help = 'Which CNN architecture you want to use? -- densenet121, alexnet, or vgg16')
parser.add_argument('--learning_rate', type = float, default = '0.001',
help = 'learning rate for Gradient descent')
parser.add_argument('--hid_units1', type = int, default = '1024',
help = '# of input units for hidden unite#1')
parser.add_argument('--hid_units2', type = int, default = '512',
help = '# of input units for hidden unite#2')
parser.add_argument('--epochs', type = int, default = '5',
help = 'epochs times to run the training model')
parser.add_argument('--device', type = str, default = 'cpu',
help = 'device the model to run on i.e GPU/CPU')
parser.add_argument('--dropout', type = float, default = '0.5',
help = 'Drop out for the model')
in_arg = parser.parse_args()
# Replace None with parser.parse_args() parsed argument collection that
# you created with this function
return in_arg
def data_loader(data_dir):
train_dir = data_dir + '/train'
valid_dir = data_dir + '/valid'
test_dir = data_dir + '/test'
train_transforms = transforms.Compose([transforms.RandomRotation(30),
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])])
test_transforms = transforms.Compose([transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])
])
valid_transforms = transforms.Compose([transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])
])
# TODO: Load the datasets with ImageFolder
#image_datasets =
train_data = datasets.ImageFolder(train_dir, transform=train_transforms)
test_data = datasets.ImageFolder(test_dir, transform=test_transforms)
valid_data = datasets.ImageFolder(valid_dir, transform=valid_transforms)
# TODO: Using the image datasets and the trainforms, define the dataloaders
#dataloaders =
trainloader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)
testloader = torch.utils.data.DataLoader(test_data, batch_size=64)
validloader = torch.utils.data.DataLoader(valid_data, batch_size=64)
return trainloader, validloader, testloader, train_data.class_to_idx
def network(arch='vgg16', dropout=0.5, hidden_layer1 = 1024, hidden_layer2 = 512, lr = 0.001, device='cpu'):
# load the model based on the selected Model Architecture
if arch == 'vgg16':
#print("Arch", arch)
model = models.vgg16(pretrained=True)
elif arch == 'densenet121':
#print("Arch", arch)
model = models.densenet121(pretrained=True)
else :
print("ERROR: Please use one of these Architecture only -- densenet121, or vgg16")
#print("Initial Model:", model)
for param in model.parameters():
param.requires_grad = False
classifier = nn.Sequential(OrderedDict([
('fc1', nn.Linear(arch_ins[arch],hidden_layer1)),
('relu1', nn.ReLU()),
('n_out1',nn.Dropout(dropout)),
('fc2', nn.Linear(hidden_layer1, hidden_layer2)),
('relu2', nn.ReLU()),
('n_out2',nn.Dropout(dropout)),
('fc3', nn.Linear(hidden_layer2, 102)),
('output', nn.LogSoftmax(dim=1))
]))
model.classifier = classifier
#model.class_to_idx = train_data.class_to_idx
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.classifier.parameters(), lr )
if torch.cuda.is_available() and device == 'gpu':
model.cuda()
#model.to(device);
return model, criterion, optimizer
def train_model(model, criterion, optimizer, epochs, trainloader, validloader, device):
train_losses, valid_losses = [], []
with active_session():
# do long-running work here
for e in range(epochs):
#print("Starting epoch #", e)
running_loss = 0
start = time.time()
for images, labels in trainloader:
if torch.cuda.is_available() and device =='gpu':
images, labels = images.to('cuda'), labels.to('cuda')
optimizer.zero_grad()
log_ps = model.forward(images)
loss = criterion(log_ps, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
else:
valid_loss = 0
valid_accuracy = 0
# Turn off gradients for validation, saves memory and computations
with torch.no_grad():
model.eval()
for images, labels in validloader:
if torch.cuda.is_available() and device =='gpu':
images, labels = images.to('cuda'), labels.to('cuda')
model.to('cuda')
log_ps = model(images)
valid_loss += criterion(log_ps, labels)
ps = torch.exp(log_ps)
top_p, top_class = ps.topk(1, dim=1)
equals = top_class == labels.view(*top_class.shape)
valid_accuracy += torch.mean(equals.type(torch.FloatTensor))
model.train()
train_losses.append(running_loss/len(trainloader))
valid_losses.append(valid_loss/len(validloader))
print("Epoch: {}/{}.. ".format(e+1, epochs),
"Training Loss: {:.3f}.. ".format(running_loss/len(trainloader)),
"Validation Loss: {:.3f}.. ".format(valid_loss/len(validloader)),
"Validation Accuracy: {:.3f}".format((valid_accuracy/len(validloader))*100),
f"Time per-epoch: {(time.time() - start):.3f} seconds")
def save_checkpoint(model, path , arch, hidden_layer1, hidden_layer2, dropout, lr, epochs, class_to_idx):
model.class_to_idx = class_to_idx
model.cpu
torch.save({'arch' :arch,
'hidden_layer1':hidden_layer1,
'hidden_layer2':hidden_layer2,
'dropout':dropout,
'lr':lr,
'nb_of_epochs':epochs,
'state_dict':model.state_dict(),
'class_to_idx':model.class_to_idx},
path)
print("Done Saving the CheckPoint as:", path)
#Quick Validation
state_dict = torch.load(path)
#print(state_dict.values())
print(state_dict.keys())
def load_checkpoint(filepath, device):
if device == 'gpu':
checkpoint = torch.load(filepath)
else:
checkpoint = torch.load(filepath, map_location="cpu")
arch = checkpoint['arch']
hidden_layer1 = checkpoint['hidden_layer1']
hidden_layer2 = checkpoint['hidden_layer2']
dropout = checkpoint['dropout']
learning_rate = checkpoint['lr']
epochs = checkpoint['nb_of_epochs']
state_dict = checkpoint['state_dict']
class_to_idx = checkpoint['class_to_idx']
model, criterion, optimizer = network(arch, dropout, hidden_layer1, hidden_layer2, learning_rate)
model.class_to_idx = checkpoint['class_to_idx']
model.load_state_dict(checkpoint['state_dict'])
return model
def process_image(image):
# Using the shoter methods than manual steps as in part1
proc_img = Image.open(image)
process_img = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
processed_image = process_img(proc_img)
return processed_image
def predict_image(image_file, model, topk, class_name, device):
with open(class_name, 'r') as f:
cat_to_name = json.load(f)
if torch.cuda.is_available() and device =='gpu':
model.to('cuda')
proces_image = process_image(image_file)
#image = torch.from_numpy(proces_image).type(torch.FloatTensor)
#used to make size of torch as expected. as forward method is working with batches,
#doing that we will have batch size = 1
image = proces_image.unsqueeze (dim = 0)
with torch.no_grad():
model.eval()
if device == 'gpu':
log_ps = model(image.cuda())
else:
log_ps = model(image)
ps = torch.exp(log_ps)
top_probabilities, top_classes = ps.topk(topk)
#print("top_probabilities", top_probabilities)
#print("top_classes", top_classes)
top_probabilities_list = top_probabilities.tolist()[0]
top_classes_list = top_classes.tolist()[0]
#print("top_probabilities_list", top_probabilities_list)
#print("top_classes_list", top_classes_list)
idx_to_class = {val: key for key, val in model.class_to_idx.items() }
#print("cat_to_name[i]:", cat_to_name['91'])
#print("idx_to_class ", idx_to_class )
#print(type(top_classes_list))
#print("model.class_to_idx.items()", model.class_to_idx)
top_label = [idx_to_class[i] for i in top_classes_list]
top_flower = [cat_to_name[str(i)] for i in top_label]
return top_probabilities_list, top_classes_list, top_label, top_flower
|
TypeScript
|
UTF-8
| 1,339 | 3.015625 | 3 |
[] |
no_license
|
import { Reducer } from 'redux';
export interface FSA<TPayload, TMeta = {}> {
type: string;
payload: TPayload;
error?: boolean;
meta?: TMeta;
}
export type FSACreator<TPayload> = (payload: TPayload) => FSA<TPayload>;
export interface Slice<S> {
reducer: Reducer<S>;
configureAction: <P>(
type: string,
reduce: (payload: P) => (state: S) => S,
) => FSACreator<P>;
update: <K extends keyof S>(updates: Pick<S, K>) => FSA<Pick<S, K>>;
}
export const createSlice = <S>(initialState: S, prefix: string): Slice<S> => {
// tslint:disable-next-line no-any
const handlerMap: Record<string, (payload: any) => (state: S) => S> = {};
const configureAction: Slice<S>['configureAction'] = (type, reduce) => {
const prefixedType = `${prefix}/${type}`;
handlerMap[prefixedType] = reduce;
return payload => ({ type: prefixedType, payload });
};
const slice: Slice<S> = {
configureAction,
reducer: (state = initialState, action) => {
const handler = handlerMap[action.type];
if (handler) {
return handler(action.payload)(state);
}
return state;
},
update: configureAction('UPDATE', updates => state => ({ ...state, ...updates })),
};
return slice;
};
|
Python
|
UTF-8
| 1,459 | 2.796875 | 3 |
[] |
no_license
|
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
def send_mail(
sender,
password,
recipient,
title,
content,
mail_host="smtp.163.com",
port=25,
file=None,
):
"""
发送邮件函数,默认使用163smtp
:param sender: 邮箱账号 xx@163.com
:param password: 邮箱密码
:param recipient: 邮箱接收人地址,多个账号以逗号隔开
:param title: 邮件标题
:param content: 邮件内容
:param mail_host: 邮箱服务器
:param port: 端口号
:return:
"""
if file:
msg = MIMEMultipart()
# 构建正文
part_text = MIMEText(content)
msg.attach(part_text) # 把正文加到邮件体里面去
# 构建邮件附件
part_attach = MIMEApplication(open(file, "rb").read()) # 打开附件
part_attach.add_header(
"Content-Disposition", "attachment", filename="capture.mp4"
) # 为附件命名
msg.attach(part_attach) # 添加附件
else:
msg = MIMEText(content) # 邮件内容
msg["Subject"] = title # 邮件主题
msg["From"] = sender # 发送者账号
msg["To"] = recipient # 接收者账号列表
smtp = smtplib.SMTP(mail_host, port=port)
smtp.login(sender, password) # 登录
smtp.sendmail(sender, recipient, msg.as_string())
smtp.quit()
|
Python
|
UTF-8
| 1,255 | 3.984375 | 4 |
[] |
no_license
|
'''
Given a string S, return the "reversed" string where all characters
that are not a letter stay in the same place, and all letters reverse their positions.
Example 1:
Input: "ab-cd"
Output: "dc-ba"
Example 2:
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:
Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"
Note:
S.length <= 100
33 <= S[i].ASCIIcode <= 122
S doesn't contain \ or "
'''
class Solution:
def reverseOnlyLetters(self, S):
icon, S_list = [], []
for ii in range(len(S)):
# A(65) - Z(90)
# a(97) - z(122)
if ord(S[ii]) in range(65, 91) or \
ord(S[ii]) in range(97, 123):
S_list += S[ii]
else:
icon.append(ii)
# reverse letters
S_list = S_list[::-1]
for ic in icon:
S_list.insert(ic, S[ic])
return "".join(S_list)
if __name__ == "__main__":
solu = Solution()
input_1 = "ab-cd"
input_2 = "a-bC-dEf-ghIj"
input_3 = "Test1ng-Leet=code-Q!"
print(input_1, "ANSWER IS", solu.reverseOnlyLetters(input_1))
print(input_2, "ANSWER IS", solu.reverseOnlyLetters(input_2))
print(input_3, "ANSWER IS", solu.reverseOnlyLetters(input_3))
|
Java
|
UTF-8
| 1,035 | 2.078125 | 2 |
[] |
no_license
|
package com.kozlovruzudzhenkkovalova.library.serviceTests;
import com.kozlovruzudzhenkkovalova.library.entity.Role;
import com.kozlovruzudzhenkkovalova.library.repositories.RoleRepository;
import com.kozlovruzudzhenkkovalova.library.service.RoleService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Optional;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class RoleServiceTest {
@Mock
private RoleRepository roleRepository;
@InjectMocks
private RoleService roleService;
@Test
public void shouldCallFindByName1Time() {
when(roleRepository.findByName("admin")).thenReturn(Optional.of(Role.builder().name("admin").build()));
roleService.findRoleByName("admin");
verify(roleRepository, times(1)).findByName("admin");
}
}
|
Python
|
UTF-8
| 2,519 | 2.609375 | 3 |
[
"Apache-2.0"
] |
permissive
|
import glob
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import re
import json
global CSVHEADER
global VENDOR
CSVHEADER = 'datetime,download,upload,ping\n'
VENDOR = 'MAGENTA Kabelinternet + TV'
def toCSV(filename):
try:
with open(filename, 'r') as filePointer:
with open(filename + '.csv', 'w+') as filePointerCSV:
filePointerCSV.write(CSVHEADER)
lineNo = 0
for line in filePointer:
try:
lineNo += 1
dateTime = re.search('#(.*)#', line)
lineJsonS = line[(dateTime.span()[1]+1):(len(line))]
lineJson = json.loads(lineJsonS)
csv_line = '"{}",{},{},{}\n'.format(dateTime.group(1), round(lineJson['download']/1000000, 2), round(lineJson['upload']/1000000, 2), round(lineJson['ping'], 2))
filePointerCSV.write(csv_line)
except Exception as Ex:
print('Excetion during line-parsing to CSV! LineNo. {} Ex: {}'.format(lineNo, str(Ex)))
except Exception as Ex:
print('Excetion during convertion to CSV! Ex: %s' % str(Ex))
def parseLogFiles(FileDirectory):
try:
# parse logfile
filenames = glob.glob(FileDirectory+'*.log')
for filename in filenames:
toCSV(filename)
except Exception as Ex:
print('Error parsing files! Ex: %s' % str(Ex))
def main():
try:
parseLogFiles('./logs/')
filenames = glob.glob('./logs/*.csv')
for filename in filenames:
df = pd.read_csv(filename)
df_long = pd.melt(df, id_vars=['datetime'],
value_vars=['download', 'upload', 'ping'])
fig = px.line(df_long, x='datetime', y='value', color='variable',
title='SPEEDTEST - {}'.format(VENDOR))
for figData in fig.data:
if figData.name == 'ping':
figData.name += ' [ms]'
else:
figData.name += ' [MBit/s]'
fig.update_traces(mode="markers+lines", hovertemplate=None)
fig.update_layout(hovermode="x unified", hoverlabel=dict(namelength=-1))
fig.write_html('.{}.html'.format(filename.split('.')[1]))
# fig.show()
except Exception as Ex:
print('Exception: %s' % str(Ex))
if __name__ == '__main__':
main()
|
Python
|
UTF-8
| 857 | 3.890625 | 4 |
[] |
no_license
|
# Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei),
# find the minimum number of conference rooms required.
# Input: [[0, 30],[5, 10],[15, 20]]
# Output: 2
def minMeetingRooms(intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
if not intervals:
return 0
start_time = []
end_time = []
for meeting in intervals:
start_time.append(meeting[0])
end_time.append(meeting[1])
start_time.sort()
end_time.sort()
usedRoom = 0
st = 0
et = 0
while st < len(start_time):
if start_time[st] > end_time[et]:
usedRoom -= 1
et += 1
usedRoom += 1
st += 1
return usedRoom
print(minMeetingRooms([[7, 10], [2, 4]]))
print(minMeetingRooms([[0, 30], [5, 10], [15, 20]]))
|
Markdown
|
UTF-8
| 863 | 2.609375 | 3 |
[] |
no_license
|
学习笔记
# 轮播组件
## 手势与动画应用
组件的状态如果不需要外部传入的话,也可以使用render函数的一个局部变量
组件的状态和属性都可以作为私有变量,前者主要给业务开发者使用,后者给组件开发者使用
组件中可以通过在属性中指定 onXxx 属性接受用户传入的回调函数,组件的设计者负责在组件运行的适当时机调用该函数
组件可以传入两种children:
一种是文本型,这种可以包装进组件内部的一个span标签中
另一种是模板型,在JSX中,模板型的children不能直接写为组件元素的内嵌元素,而是要以回调函数的形式(一般会接受一个属性中传递的数据,并返回一个标签模板), 在组件的重载appendChild方法和render方法里处理为 element list,再渲染出来
|
Java
|
UTF-8
| 442 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
package org.gendut.iterator;
import org.gendut.seq.Seq;
//!Iterator Wrapper for Sequences
/*<literate>*/
/**
* Iterator wrapper for sequences.
*/
public final class IteratorFromSeq<E> implements ForwardIterator<E> {
private Seq<E> S;
public IteratorFromSeq(Seq<E> S) { this.S = S; }
public E next() {
E x = S.first();
S = S.rest();
return x;
}
public boolean hasNext() {
return (!S.isEmpty());
}
}//`class`
|
Python
|
UTF-8
| 3,715 | 2.890625 | 3 |
[
"Apache-2.0"
] |
permissive
|
import ast
import dateutil.parser as dp
import logging
logger = logging.getLogger('CryptoArbitrageApp')
class PriceStore:
def __init__(self, priceTTL=60):
self.price = {}
self.priceTTL = priceTTL
def isOrderbookEmpty(self, ob):
if len(ob) == 0:
return True
else:
if len(ob[0]) == 0:
return True
return False
def updatePriceFromForex(self, forexTicker):
symbolsplit = forexTicker['instrument'].split('_')
symbol_base = ('forex', symbolsplit[0])
symbol_quote = ('forex', symbolsplit[1])
timestamp = int(dp.parse(forexTicker['time']).strftime('%s'))
key1 = (symbol_quote, symbol_base)
key2 = (symbol_base, symbol_quote)
self.price[key1] = (timestamp, 1 / forexTicker['ask'])
self.price[key2] = (timestamp, forexTicker['bid'])
def updatePriceFromCoinmarketcap(self, ticker):
# self.price.clear()
for symbol, tickeritem in ticker.items():
try:
symbolsplit = symbol.split('/')
symbol_base = ('coinmarketcap', symbolsplit[0])
symbol_quote = ('coinmarketcap', symbolsplit[1])
price = tickeritem['last']
timestamp = tickeritem['timestamp']/1000
if price is not None:
if price > 0:
key1 = (symbol_quote, symbol_base)
key2 = (symbol_base, symbol_quote)
self.price[key1] = (timestamp, 1 / price)
self.price[key2] = (timestamp, price)
except Exception as e:
logger.error("Error occured parsing CMC ticker " + symbol + " " + str(e.args))
def updatePriceFromOrderBook(self, symbol, exchangename, asks, bids,
timestamp):
self.symbol = symbol
if isinstance(asks, str):
asks = list(ast.literal_eval(asks))
if isinstance(bids, str):
bids = list(ast.literal_eval(bids))
if self.isOrderbookEmpty(asks) or self.isOrderbookEmpty(bids):
return
price = (asks[0][0] + bids[0][0]) / 2
symbolsplit = symbol.split('/')
if len(symbolsplit) != 2:
return
symbol_base = (exchangename, symbolsplit[0])
symbol_quote = (exchangename, symbolsplit[1])
key1 = (symbol_quote, symbol_base)
key2 = (symbol_base, symbol_quote)
self.price[key1] = (timestamp, 1 / price)
self.price[key2] = (timestamp, price)
def getMeanPrice(self, symbol_base_ref, symbol_quote_ref, timestamp):
acc = 0
cntr = 0
if symbol_base_ref == symbol_quote_ref:
return 1
for k, v in self.price.items():
symbol_base = k[0][1]
exchange_base = k[0][0]
symbol_quote = k[1][1]
exchange_quote = k[1][0]
ts = v[0]
rate = v[1]
if symbol_base_ref == symbol_base \
and symbol_quote_ref == symbol_quote \
and exchange_base == exchange_quote \
and (timestamp-ts) <= self.priceTTL \
and timestamp >= ts:
acc += rate
cntr += 1
priceage = timestamp-ts
if cntr != 0:
logger.info('Price information found for %s/%s timestamp %f (age: %3.1fs)' %(symbol_base_ref, symbol_quote_ref, timestamp,priceage))
return acc / cntr
else:
logger.warning('Price information not available for %s/%s timestamp %f' %(symbol_base_ref, symbol_quote_ref, timestamp))
return None
|
Python
|
UTF-8
| 577 | 2.6875 | 3 |
[] |
no_license
|
import sqlite3 as sql
from itertools import cycle
def xor(message, key):
return bytes(a ^ b for a, b in zip(message, cycle(key)))
def pass_cipher(password):
key1 = b'this_is_key'
key2 = b'also_here_another'
result = xor(password.encode(), key1)
return xor(result, key2)
con = sql.connect('user_list.db')
cur = con.cursor()
cur.execute("""INSERT INTO 'user_list' VALUES (?, ?, ?, ?);""",
('Admin', pass_cipher('1-2-3Admin3-2-1'), 'Admin', True))
con.commit()
cur.close()
# Login - Admin
# Password - 1-2-3Admin3-2-1
|
TypeScript
|
UTF-8
| 727 | 2.5625 | 3 |
[] |
no_license
|
namespace view {
export function displayMessage(title: string, msg: string, spanId?: string) {
var messageArea = document.getElementById("messageArea");
messageArea.innerHTML = `<h2> ${title} </h2> <h3><span id = ${spanId}> </span> ${msg} </h3>`;
}
export function displayHit(location: string) {
//var cell = document.getElementById(location);
document.getElementById(location).setAttribute("class", "hit");
}
export function displayMiss(location: string) {
//var cell = document.getElementById(location);
document.getElementById(location).setAttribute("class", "miss");
}
}
//export { displayMessage, displayHit, displayMiss }
|
C++
|
UTF-8
| 387 | 2.609375 | 3 |
[] |
no_license
|
#ifndef SOLDIERCHILDGUN_H
#define SOLDIERCHILDGUN_H
#include <string>
#include <vector>
#include <iostream>
#include "soldier.h"
class SoldierChildGun : Soldier {
private:
std::string ability;
std::vector<std::string> abilitiesList;
public:
SoldierChildGun();
virtual void printInfo();
std::vector<std::string> getSoldierAbilities();
};
#endif // !SOLDIERCHILDGUN_H
|
Markdown
|
UTF-8
| 1,265 | 2.9375 | 3 |
[] |
no_license
|
# veradalta
CRUD SQLEXPRES in android
ESPAÑOL
Esta aplicacion fue realizada para un proyecto escolar en la Universidad Tecnologica de Morelia.
Basicamente la aplicacion hace el CRUD (Create, Read, Update and Delet) en SQLEXPRESS.
Lo interesante del proyecto fue que trabajar con este tipo de base de datos.
Tiene el metodo para hacer la conexion, login, se llenan spinners desde la base de datos.
Y se trabaja con los datepickery time picker.
Espero sea de gran utilidad.
Junto con ello se subio la bd de todo el proyecto, aun que en esta app solo se utiliza la tabla reservaciones.
mis datos de contacto gera.rodriguez391@gmail.com
a sus ordenes.
saludos.
INGLES
This application was made for a school project at the Technological University of Morelia.
Basically the application does the CRUD (Create, Read, Update and Delet) in SQLEXPRESS.
The interesting thing about the project was that you work with this type of database.
It has the method to make the connection, login, spinners are filled from the database.
And it works with the datepickery time picker.
Hope will be useful.
Along with this the bd of the whole project was uploaded, even though in this app only the reservation table is used.
my contact information gera.rodriguez391@gmail.com
at your service.
Greetings.
|
PHP
|
UTF-8
| 1,583 | 2.640625 | 3 |
[] |
no_license
|
<?php
namespace App\Http\Controllers\ApiAuth;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Contracts\Auth\CanResetPassword;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class ResetPasswordController extends Controller
{
use ResetsPasswords;
public function verifyPasswordReset(Request $request)
{
return $this->reset($request);
}
/**
* Get the response for a successful password reset.
*
* @param Request $request
* @param string $response
* @return RedirectResponse|JsonResponse
*/
protected function sendResetResponse(Request $request, $response)
{
return response()->json(['message' => 'Password reset successfully.']);
}
/**
* Get the response for a failed password reset.
*
* @param Request $request
* @param string $response
* @return RedirectResponse|JsonResponse
*/
protected function sendResetFailedResponse(Request $request, $response)
{
return response()->json(['message' => 'Failed, Invalid Token.']);
}
/**
* Reset the given user's password.
*
* @param CanResetPassword $user
* @param string $password
* @return void
*/
protected function resetPassword($user, $password)
{
/** @var User $user */
$user->password = $password;
$user->save();
event(new PasswordReset($user));
}
}
|
Java
|
UTF-8
| 3,775 | 2.046875 | 2 |
[] |
no_license
|
package org.reverse;
// Generated Oct 20, 2010 10:21:56 AM by Hibernate Tools 3.4.0.Beta1
import java.util.Date;
/**
* SnpPromoMecobId generated by hbm2java
*/
public class SnpPromoMecobId implements java.io.Serializable {
private long idPromocion;
private String idMedioCobro;
private String usrAlta;
private Date FAlta;
private String usrModi;
private Date FModi;
public SnpPromoMecobId() {
}
public SnpPromoMecobId(long idPromocion, String idMedioCobro, String usrAlta, Date FAlta) {
this.idPromocion = idPromocion;
this.idMedioCobro = idMedioCobro;
this.usrAlta = usrAlta;
this.FAlta = FAlta;
}
public SnpPromoMecobId(long idPromocion, String idMedioCobro, String usrAlta, Date FAlta, String usrModi, Date FModi) {
this.idPromocion = idPromocion;
this.idMedioCobro = idMedioCobro;
this.usrAlta = usrAlta;
this.FAlta = FAlta;
this.usrModi = usrModi;
this.FModi = FModi;
}
public long getIdPromocion() {
return this.idPromocion;
}
public void setIdPromocion(long idPromocion) {
this.idPromocion = idPromocion;
}
public String getIdMedioCobro() {
return this.idMedioCobro;
}
public void setIdMedioCobro(String idMedioCobro) {
this.idMedioCobro = idMedioCobro;
}
public String getUsrAlta() {
return this.usrAlta;
}
public void setUsrAlta(String usrAlta) {
this.usrAlta = usrAlta;
}
public Date getFAlta() {
return this.FAlta;
}
public void setFAlta(Date FAlta) {
this.FAlta = FAlta;
}
public String getUsrModi() {
return this.usrModi;
}
public void setUsrModi(String usrModi) {
this.usrModi = usrModi;
}
public Date getFModi() {
return this.FModi;
}
public void setFModi(Date FModi) {
this.FModi = FModi;
}
public boolean equals(Object other) {
if ( (this == other ) ) return true;
if ( (other == null ) ) return false;
if ( !(other instanceof SnpPromoMecobId) ) return false;
SnpPromoMecobId castOther = ( SnpPromoMecobId ) other;
return (this.getIdPromocion()==castOther.getIdPromocion())
&& ( (this.getIdMedioCobro()==castOther.getIdMedioCobro()) || ( this.getIdMedioCobro()!=null && castOther.getIdMedioCobro()!=null && this.getIdMedioCobro().equals(castOther.getIdMedioCobro()) ) )
&& ( (this.getUsrAlta()==castOther.getUsrAlta()) || ( this.getUsrAlta()!=null && castOther.getUsrAlta()!=null && this.getUsrAlta().equals(castOther.getUsrAlta()) ) )
&& ( (this.getFAlta()==castOther.getFAlta()) || ( this.getFAlta()!=null && castOther.getFAlta()!=null && this.getFAlta().equals(castOther.getFAlta()) ) )
&& ( (this.getUsrModi()==castOther.getUsrModi()) || ( this.getUsrModi()!=null && castOther.getUsrModi()!=null && this.getUsrModi().equals(castOther.getUsrModi()) ) )
&& ( (this.getFModi()==castOther.getFModi()) || ( this.getFModi()!=null && castOther.getFModi()!=null && this.getFModi().equals(castOther.getFModi()) ) );
}
public int hashCode() {
int result = 17;
result = 37 * result + (int) this.getIdPromocion();
result = 37 * result + ( getIdMedioCobro() == null ? 0 : this.getIdMedioCobro().hashCode() );
result = 37 * result + ( getUsrAlta() == null ? 0 : this.getUsrAlta().hashCode() );
result = 37 * result + ( getFAlta() == null ? 0 : this.getFAlta().hashCode() );
result = 37 * result + ( getUsrModi() == null ? 0 : this.getUsrModi().hashCode() );
result = 37 * result + ( getFModi() == null ? 0 : this.getFModi().hashCode() );
return result;
}
}
|
PHP
|
UTF-8
| 2,373 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
<?php namespace Codesleeve\Generator\Support;
use RecursiveIteratorIterator, RecursiveDirectoryIterator;
use Codesleeve\Generator\Interfaces\FilesystemInterface;
use Codesleeve\Generator\Exceptions\FileNotFoundException;
class Filesystem extends \Symfony\Component\Filesystem\Filesystem implements FilesystemInterface
{
/**
* This is the root of the file system
* and can be used to inject in vfsStream for testing.
*
* It is also useful for having paths all relative to the
* root directory
*
* @var [type]
*/
private $root;
/**
* Create a new filesystem wrapper
*
* @param string $root
*/
public function __construct($root = '')
{
$this->root = $root;
}
/**
* Open a file and return the contents
*
* @return string
*/
public function get($file)
{
if (!$this->exists($this->path($file)))
{
throw new FileNotFoundException("File not found at $file");
}
return file_get_contents($this->path($file));
}
/**
* Create this file for us and set content
*
*/
public function put($filename, $content)
{
$directory = $this->directory($filename);
if (!$this->exists($directory))
{
$this->mkdir($directory);
}
return file_put_contents($this->path($filename), $content);
}
/**
* Return the directory for this $file
*
* @param string $file
* @return string
*/
public function directory($file)
{
return dirname($this->path($file));
}
/**
* Returns an array of file content from given directory
*
* @param string $directory
* @return array
*/
public function getFileContentsFromDirectory($directory)
{
$directory = $this->path($directory);
$contents = array();
foreach (new RecursiveIteratorIterator (new RecursiveDirectoryIterator($directory)) as $filename)
{
if ($filename->isFile())
{
$relativePath = $this->makeRelativePath($filename, $directory);
$contents[$relativePath] = file_get_contents($filename);
}
}
return $contents;
}
/**
* Strip off the base directory
*
* @param string $path
* @param string $base
* @return string
*/
public function makeRelativePath($path, $base)
{
return str_replace($base . '/', '', $path);
}
/**
* Return the path wrapper (for testing purposes mainly)
*
* @param string $path
* @return string
*/
protected function path($path)
{
return $this->root . $path;
}
}
|
Markdown
|
UTF-8
| 2,211 | 3.375 | 3 |
[] |
no_license
|
Title: 6÷2(1+2)=?
Date: 2011-05-02 03:03
Slug: six-divided-by-two-bracket-one-plus-two
> 6÷2(1+2)=?
It's a question that comes around in Facebook recently (I've also read
it somewhere in the past). There are two major answers: "1" and "9".
For "1", (Assuming “multiplication by juxtaposition” has higher
precedence than regular division. Whether the assumption is true, is
depending on which literature is being referred to. If you don't agree
on it, the answer is simply 9)
```text
6÷(2×(1+2))
=6÷(2×3)
=6÷6
=1
```
For "9",
```text
6/2*(1+2)
=6/2*3
=3*3
=9
```
Notice the question is interpreted differently, you can tell it from
looking at the symbols. One is mathematical notation, another is program
operator notation.
The difference between mathematics and programming shown above is that,
they use different kind of symbols(operators), so they have different
[order of operation][].
Google thinks that is 9:<br>
[](http://www.google.com.hk/search?q=6%C3%B72(1%2B2))
WolframAlpha thinks that is 9:<br>
[](http://www.wolframalpha.com/input/?i=6%C3%B72%281%2B2%29)
My Casio calculator thinks that is 1:<br>

One interesting thing is, even in programming, different programming
languages may have different order of operation, i.e. they have different
operator precedence (or [operator associativity][]). The difference is
mostly on bitwise operations(e.g. `<<`, `&`, `|`), and it has been
a nightmare for programmers who want to port algorithms between
languages. And luckily [haXe][], the language I'm in love with, that
outputs C++/JS/PHP and others, already abstracted the different by
inserting the necessary brackets in the output automatically([see
here][]). So I'm happily writing codes in haXe and share the same result
in different platforms ;)
[order of operation]: http://en.wikipedia.org/wiki/Order_of_operations
[operator associativity]: http://en.wikipedia.org/wiki/Operator_associativity
[haXe]: http://haxe.org/
[see here]: http://haxe.org/manual/operators
|
PHP
|
UTF-8
| 447 | 3.546875 | 4 |
[] |
no_license
|
<?php // Singleton.php
class hoge { // テスト用
}
//
class Singleton {
//
private function __construct() {
}
//
static public function getInstance() {
static $obj = null;
if (null === $obj) {
$obj = new static;
}
return $obj;
}
}
//
$obj = new hoge();
$obj2 = new hoge();
var_dump($obj, $obj2);
//
$obj = Singleton::getInstance();
$obj2 = Singleton::getInstance();
var_dump($obj, $obj2);
|
Python
|
UTF-8
| 1,302 | 2.984375 | 3 |
[] |
no_license
|
import pygame,time,random
#running = True
joon=3
dir=1
width=600
height=600
screen = pygame.display.set_mode((width,height))
clock = pygame.time.Clock()
bgcolor =0,80,20
screen.fill(bgcolor)
#score = 0
############################################
class Mar:
def __init__(self,surface,x,y,length,color):
self.surface = surface
self.x = x
self.y = y
self.length = length
self.dir_x = 0
self.dir_y = -1
self.body = []
self.grow_to=50
self.crashed = False
self.color=color
def eat(self):
self.grow_to +=25
def move(self):
self.x += self.dir_x
self.y += self.dir_y
if (self.x , self.y) in self.body:
self.crashed = True
self.body.insert(0, (self.x ,self.y))
if (self.grow_to >self.length):
self.length +=1
if len(self.body) > self.length:
self.body.pop()
def draw(self):
x , y = self.body[0]
self.surface.set_at((x, y), self.color)
x, y =self.body[-1]
self.surface.set_at((x, y), bgcolor)
def barkhord(self,a,b):
if (a,b) in self.body:
return True
return False
|
Python
|
UTF-8
| 469 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
import io
import geopandas as gpd
from genomicsurveillance.config import Files
def get_geo_data(geo_data: bytes = Files.GEO_JSON):
"""
Loads a UK GeoJson file and returns the corresponding geopandas
dataframe. Requires the optional dependency geopandas.
:param geo_data: uk geojson data, defaults uk.geojson
in the data dir of the package
:returns: geopandas dataframe
"""
uk = gpd.read_file(io.BytesIO(geo_data))
return uk
|
C++
|
UTF-8
| 3,971 | 2.671875 | 3 |
[] |
no_license
|
#include "ManipulatorGoalRegion.hpp"
#include <fstream>
#include <string>
using std::cout;
using std::endl;
namespace shared {
ManipulatorGoalRegion::ManipulatorGoalRegion(const ompl::base::SpaceInformationPtr &si,
boost::shared_ptr<shared::Robot> robot,
std::vector<std::vector<double>> &goal_states,
std::vector<double> &ee_goal_position,
double &ee_goal_threshold,
bool dynamics):
ompl::base::GoalSampleableRegion(si),
robot_(robot),
state_space_information_(si),
state_dimension_(si->getStateDimension()),
goal_states_(goal_states),
ee_goal_position_(ee_goal_position),
ee_goal_threshold_(ee_goal_threshold)
{
if (dynamics) {
state_dimension_ = si->getStateDimension() / 2;
}
}
double ManipulatorGoalRegion::euclideanDistance(const std::vector<double> &vec1, const std::vector<double> &vec2) const{
double sum = 0.0;
for (size_t i = 0; i < vec1.size(); i++) {
sum += pow(vec2[i] - vec1[i], 2);
}
return sqrt(sum);
}
double ManipulatorGoalRegion::distanceGoal(const ompl::base::State *st) const
{
std::vector<double> v1;
double* v = st->as<ompl::base::RealVectorStateSpace::StateType>()->values;
for (unsigned int i = 0; i < state_dimension_; i++) {
v1.push_back(v[i]);
}
std::vector<double> ee_position;
robot_->getEndEffectorPosition(v1, ee_position);
/**std::vector<double> ee_g;
for (size_t i = 0; i < ee_goal_position_.size(); i++) {
ee_g.push_back(ee_goal_position_[i]);
}*/
double distance = euclideanDistance(ee_position, ee_goal_position_);
return distance;
}
double ManipulatorGoalRegion::getThreshold() const {
cout << "GETTING THRESHOLD" << endl;
sleep(10);
return ee_goal_threshold_;
}
void ManipulatorGoalRegion::sampleGoal(ompl::base::State *st) const
{
ompl::RNG rng;
int rd = rng.uniformInt(0, goal_states_.size() - 1);
double* v = st->as<ompl::base::RealVectorStateSpace::StateType>()->values;
for (unsigned int i = 0; i < state_dimension_; i++) {
v[i] = goal_states_[rd][i];
}
}
std::vector<double> ManipulatorGoalRegion::sampleGoalVec() const {
ompl::RNG rng;
std::vector<double> v;
int rd = rng.uniformInt(0, goal_states_.size() - 1);
//int rd = 0;
if (goal_states_.size() == 0) {cout << "wtf"<<endl;}
for (unsigned int i = 0; i < state_dimension_; i++) {
v.push_back(goal_states_[rd][i]);
}
return v;
}
unsigned int ManipulatorGoalRegion::maxSampleCount() const
{
return goal_states_.size();
}
bool ManipulatorGoalRegion::isSatisfied(const ompl::base::State *st) const {
cout << "IS SATISFIED" << endl;
std::vector<double> joint_angles;
for (unsigned int i = 0; i < state_dimension_; i++) {
joint_angles.push_back(st->as<ompl::base::RealVectorStateSpace::StateType>()->values[i]);
}
std::vector<double> ee_position;
robot_->getEndEffectorPosition(joint_angles, ee_position);
double sum(0.0);
for (unsigned int i = 0; i < joint_angles.size(); i++) {
sum += pow(ee_position[i] - ee_goal_position_[i], 2);
}
sum = sqrt(sum);
if (sum < ee_goal_threshold_ - 0.01) {
return true;
}
return false;
}
}
|
Rust
|
UTF-8
| 14,741 | 2.703125 | 3 |
[] |
no_license
|
use encoding::{DecoderTrap, Encoding};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::fs::{read_to_string, File};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::{fs, mem};
use structopt::StructOpt;
fn google_auth_token() -> String {
let output = Command::new("cmd")
.args(&[
"/C",
"gcloud",
"auth",
"application-default",
"print-access-token",
])
.output()
.expect("gcloud failed.")
.stdout;
String::from_utf8(output)
.expect("invalid utf8?")
.trim()
.to_string()
}
struct PreparedTranslateInput {
text: String,
comments: VecDeque<(usize, String)>,
line_count_name: VecDeque<(usize, String)>,
}
impl PreparedTranslateInput {
fn new(names_contents: &[(String, String)]) -> Self {
// All this just because I could not get the gcloud working on windows in rust? ..
// Why not just use vm? oh well we are almost there...
let mut sanitized = String::new();
let mut comments = VecDeque::new();
let mut line_count_name = VecDeque::new();
let mut line_no = 0;
for (filename, contents) in names_contents {
let contents = contents.trim();
let line_no_before = line_no;
for line in contents.lines() {
if line.starts_with("#") {
comments.push_back((line_no, line.to_string()));
} else {
if !sanitized.is_empty() {
sanitized.push_str("\n");
}
sanitized.push_str(line);
}
line_no += 1;
}
let line_count = line_no - line_no_before;
line_count_name.push_back((line_count, filename.to_string()));
}
PreparedTranslateInput {
text: sanitized,
comments,
line_count_name,
}
}
fn reverse(mut self, response: &str) -> Vec<(String, String)> {
let mut lines = response.lines();
let mut text = String::new();
let mut line_no = 0;
let mut current_file_count = 0;
let mut result = Vec::new();
loop {
let (file_original_line_count, filename) = self.line_count_name.front().unwrap();
if current_file_count == *file_original_line_count {
text.pop();
result.push((filename.to_owned(), text.to_string()));
text.clear();
current_file_count = 0;
self.line_count_name.pop_front().unwrap();
if self.line_count_name.is_empty() {
break;
}
}
if let Some((comment_line, comment)) = self.comments.front() {
if *comment_line == line_no {
text.push_str(comment);
text.push_str("\n");
line_no += 1;
current_file_count += 1;
self.comments.pop_front();
continue;
}
}
if let Some(line) = lines.next() {
text.push_str(line);
text.push_str("\n");
line_no += 1;
current_file_count += 1;
} else {
break;
}
}
result
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ResponseTranslation {
translated_text: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Response {
data: HashMap<String, Vec<ResponseTranslation>>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Request {
q: String,
source: String,
target: String,
format: String,
}
fn translate_text(
token: &str,
target_lang: &str,
names_contents: &[(String, String)],
) -> Vec<(String, String)> {
let sanitized = PreparedTranslateInput::new(names_contents);
let request = Request {
q: sanitized.text.clone(),
source: "ru".into(),
target: target_lang.into(),
format: "text".into(),
};
std::fs::write("request.json", serde_json::to_string(&request).unwrap())
.expect("couldn't write request.json");
let mut cmd = Command::new("curl");
cmd.args(&[
"-X",
"POST",
"-H",
&format!("Authorization: Bearer {}", token),
"-H",
"Content-Type: application/json; charset=utf-8",
"-d",
"@request.json",
"https://translation.googleapis.com/language/translate/v2",
]);
let output = cmd.output().unwrap();
assert!(output.status.success());
let response = String::from_utf8(output.stdout).expect("curl failed");
let response: Response = serde_json::from_str(&response).expect("Failed to deserialize");
let response = &response.data.get("translations").unwrap()[0].translated_text;
sanitized.reverse(&response)
}
#[derive(StructOpt)]
#[structopt(rename_all = "kebab_case")]
struct VerifyOptions {}
#[derive(StructOpt)]
#[structopt(rename_all = "kebab_case")]
struct TranslateOptions {
#[structopt(long)]
target_lang_key: String,
#[structopt(long)]
mod_name: String,
}
#[derive(StructOpt)]
#[structopt(rename_all = "kebab_case")]
enum Options {
Verify(VerifyOptions),
Translate(TranslateOptions),
}
struct Translation {
path: PathBuf,
lang_key: String,
}
fn path_to_name_contents(path: &Path) -> (String, String) {
let mut buff = Vec::new();
File::open(path).unwrap().read_to_end(&mut buff).unwrap();
let contents = encoding::decode(&buff, DecoderTrap::Strict, encoding::all::WINDOWS_1251)
.0
.unwrap();
(
path.file_name().unwrap().to_str().unwrap().to_owned(),
contents,
)
}
fn verify_translations(baseline: Translation, translations: &[Translation]) {
println!("Proceeding to verify translation");
// encoding::all::WINDOWS_1251.decode()
let baseline_files: Vec<_> = fs::read_dir(&baseline.path)
.unwrap()
.map(|e| e.unwrap())
.collect();
let baseline_files: HashMap<_, _> = baseline_files
.iter()
.map(|de| {
let name = de.file_name().to_str().unwrap().to_owned();
let mut buff = Vec::new();
let mut file = File::open(de.path()).unwrap().read(&mut buff);
let decoded = encoding::all::WINDOWS_1251
.decode(&buff, DecoderTrap::Strict)
.expect("Decoding failed");
(
name,
decoded.lines().map(|l| l.to_string()).collect::<Vec<_>>(),
)
})
.collect();
for t in translations {
println!("Doing stuff on: {}", t.lang_key);
let files: Vec<_> = fs::read_dir(&t.path).unwrap().map(|e| e.unwrap()).collect();
let files: HashMap<_, _> = files
.iter()
.map(|de| {
let name = de.file_name().to_str().unwrap().to_owned();
let content = fs::read_to_string(de.path()).expect("Failed to read file");
(
name,
content.lines().map(|l| l.to_string()).collect::<Vec<_>>(),
)
})
.collect();
if baseline_files.len() != files.len() {
println!("Mismatch file count in translation: {}", t.lang_key);
for filename in baseline_files.keys() {
if !files.contains_key(filename) {
println!(
"File: {:?} present in base translation(ru) but not in translation({})",
filename, t.lang_key
)
}
}
for filename in files.keys() {
if !baseline_files.contains_key(filename) {
println!(
"File: {:?} present in translation: {} but not in base translation(ru)",
filename, t.lang_key
)
}
}
panic!("Integrity verification failed.");
}
}
}
fn verify() {
let paths = fs::read_dir("translate").unwrap();
for path in paths {
let path = path.unwrap();
let metadata = path.metadata().unwrap();
if metadata.is_dir() {
println!("Will verify: {:?}", path.file_name());
let paths: Vec<_> = fs::read_dir(path.path())
.unwrap()
.filter_map(|rd| {
let rd = rd.unwrap();
if rd.metadata().unwrap().is_dir() {
Some(rd.path())
} else {
None
}
})
.collect();
let mut baseline_translation = None;
let mut translations = vec![];
for path in paths.into_iter() {
let file_name = path.file_name().unwrap().to_str().unwrap();
assert!(
file_name.starts_with("texts") && file_name.ends_with("_res"),
"Unexpected dir name: {:?}",
file_name
);
let lang_key = &file_name[file_name.len() - 6..file_name.len() - 4];
let translation = Translation {
path: path.clone(),
lang_key: lang_key.to_owned(),
};
if lang_key == "ru" {
baseline_translation = Some(translation);
} else {
translations.push(translation);
}
}
let baseline_translation =
baseline_translation.expect("Russian is a base translation its always required");
println!(
"There are {} translation available: ru,{}",
translations.len() + 1,
translations.iter().map(|t| &t.lang_key).join(",")
);
verify_translations(baseline_translation, &translations);
}
}
}
fn translate(opts: &TranslateOptions) {
let mut path = Path::new("translate").join(&opts.mod_name);
let paths: Vec<_> = fs::read_dir(&path).unwrap().map(|de| de.unwrap()).collect();
let mut baseline = None;
for p in paths {
let filename = p.file_name();
let filename = filename.to_str().unwrap();
if filename.contains("_ru_") {
baseline = Some(p.path());
}
}
let baseline = baseline.expect("No russian translation available for chosen mod");
let target = path.clone().join(
baseline
.file_name()
.unwrap()
.to_str()
.unwrap()
.replace("_ru_", &format!("_{}_", opts.target_lang_key)),
);
fs::create_dir_all(&target).expect("Could not create target translation");
let token = google_auth_token();
let mut total_length = 0;
let mut to_translate = Vec::new();
let mut cache = HashMap::new();
let mut caches_hit = 0;
for f in baseline.read_dir().unwrap() {
let f = f.unwrap();
let (source_name, source_contents) = path_to_name_contents(&f.path());
if source_contents.len() == 0 || source_name.contains(".") {
fs::remove_file(target.join(f.file_name()));
fs::copy(f.path(), target.join(f.file_name()));
println!("Copied: {}", f.path().display())
} else if !target.join(f.file_name()).exists() {
println!("fname is: {:?}", f);
if let Some(cached_result) = cache.get(&source_contents) {
let path = target.join(&source_name);
fs::write(&path, cached_result).unwrap();
caches_hit += 1;
println!(
"Cache hit in: {} total hit: {}",
f.path().display(),
caches_hit
);
} else {
total_length += source_contents.len();
to_translate.push((source_name, source_contents));
if total_length > 10000 {
let response = translate_text(&token, &opts.target_lang_key, &to_translate);
for ((filename, contents), (_, original_contents)) in
response.into_iter().zip(to_translate.iter())
{
cache.insert(original_contents.clone(), contents.clone());
let path = target.join(filename);
fs::write(&path, contents).unwrap();
}
to_translate.clear();
total_length = 0;
}
}
}
}
if !to_translate.is_empty() {
let response = translate_text(&token, &opts.target_lang_key, &to_translate);
for (filename, contents) in response {
let path = target.join(filename);
fs::write(&path, contents).unwrap();
}
}
}
fn main() {
assert!(
fs::metadata("translate")
.expect("translate dir does not exists")
.is_dir(),
"translate dir should exist in the dir you are running the tool from"
);
let opt = Options::from_args();
match opt {
Options::Verify(opts) => {
verify();
}
Options::Translate(opts) => {
translate(&opts);
}
}
}
#[cfg(test)]
mod tests {
use crate::{PreparedTranslateInput, Response};
#[test]
fn prepare_input() {
let mut test_input = Vec::new();
for _ in 0..100 {
let file1 = (
"abc".to_string(),
r#"заброшенная земля
#potato
заброшенная земля"#
.to_string(),
);
let file2 = (
"bca".to_string(),
r#"green potato
#potato
that's flying"#
.to_string(),
);
test_input.push(file1);
test_input.push(file2);
}
let prepared = PreparedTranslateInput::new(&test_input);
assert!(prepared.text.len() > 1);
let exact_response = prepared.text.clone();
assert_eq!(test_input, prepared.reverse(&exact_response));
}
#[test]
fn deser_response_test() {
let response = r#"{
"data": {
"translations": [
{
"translatedText": "Gipat"
}
]
}
}"#;
let response: Response = serde_json::from_str(response).unwrap();
}
}
|
PHP
|
UTF-8
| 538 | 3.203125 | 3 |
[] |
no_license
|
// expects dates in the form of "MM/DD/YYYY"
function pc_date_sort($a, $b) {
list($a_month, $a_day, $a_year) = explode('/', $a);
list($b_month, $b_day, $b_year) = explode('/', $b);
if ($a_year > $b_year ) return 1;
if ($a_year < $b_year ) return -1;
if ($a_month > $b_month) return 1;
if ($a_month < $b_month) return -1;
if ($a_day > $b_day ) return 1;
if ($a_day < $b_day ) return -1;
return 0;
}
$dates = array('12/14/2000', '08/10/2001', '08/07/1999');
usort($dates, 'pc_date_sort');
|
PHP
|
UTF-8
| 5,464 | 2.53125 | 3 |
[] |
no_license
|
<?php
include 'connect.php';
$sqlcustomer = "SELECT * FROM tblcustomer";
$querycustomer = mysqli_query($connect,$sqlcustomer) or die (mysqli_error($connect));
$sqlcar = "SELECT * FROM tblcars WHERE Car_Availability = 'YES'";
$querycar = mysqli_query($connect,$sqlcar) or die (mysqli_error($connect));
$sqlcar2 = "SELECT * FROM tblcars";
$querycar2 = mysqli_query($connect,$sqlcar2) or die (mysqli_error($connect));
$r = mysqli_fetch_assoc($querycar2);
?>
<link rel="stylesheet" href="assets/css/style2.css">
<br/><br/><br/> <br/><center>
<div class="form">
<h2>Make A Reservation</h2></br></br>
<form method="POST" action="reserve_confirm.php?mileage=<?php echo $r['Total_Mileage'];?>">
<div class="form_content">
Who is the one making a reservation? <br/>
<select name="customer">
<option> </option>
<?php
while($rcustomer=mysqli_fetch_assoc($querycustomer))
{
?>
<option value="<?php echo $rcustomer['CustomerID'];?>" /required> <?php echo $rcustomer['Customer_Firstname'];?> <?php echo $rcustomer['Customer_Lastname'];?> </option>
<?php
}
?>
</select>
<br/> <br/>
Which car are they going to reserve? <br/>
<select name="car">
<option> </option>
<?php
while($rcar=mysqli_fetch_assoc($querycar))
{
?>
<option value="<?php echo $rcar['CarID'];?>"> <?php echo $rcar['Car'];?> </option>
<?php
}
?>
</select>
<br/> <br/>
When are they going to rent it? <input type="date" name="startdate" /required>
<br/> <br/>
When are they going to return it? <input type="date" name="enddate" /required>
<br/> <br/>
Starting Route? <br/>
<select name="pickup" /required>
<option value="Bacolod">Bacolod </option>
<option value="Bago"> Bago</option>
<option value="Binalbagan"> Binalbagan </option>
<option value="Cadiz"> Cadiz </option>
<option value="Calatrava"> Calatrava </option>
<option value="Candoni"> Candoni </option>
<option value="Cauayan"> Cauayan </option>
<option value="Enrique B. Magalona "> Enrique B. Magalona (Saravia) </option>
<option value="Escalante"> Escalante </option>
<option value="Himamaylan"> Himamaylan </option>
<option value="Hinigaran"> Hinigaran </option>
<option value="Hinoba-an"> Hinoba-an </option>
<option value="Ilog"> Ilog </option>
<option value="Isabela"> Isabela </option>
<option value="Kabankalan"> Kabankalan </option>
<option value="La Carlota"> La Carlota </option>
<option value="La Castellana"> La Castellana </option>
<option value="Manapla"> Manapla </option>
<option value="Moises Padilla"> Moises Padilla </option>
<option value="Murcia"> Murcia </option>
<option value="Pontevedra"> Pontevedra </option>
<option value="Pulupandan"> Pulupandan </option>
<option value="Sagay"> Sagay </option>
<option value="Salvador Benedicto"> Salvador Benedicto </option>
<option value="San Carlos"> San Carlos </option>
<option value="San Enrique"> San Enrique </option>
<option value="Silay"> Silay </option>
<option value="Sipalay"> Sipalay </option>
<option value="Talisay"> Talisay </option>
<option value="Toboso"> Toboso </option>
<option value="Valladolid"> Valladolid </option>
<option value="Victorias"> Victorias </option>
</select>
<br/> <br/>
End Route? <br/>
<select name="dropoff" /required>
<option value="Bacolod">Bacolod </option>
<option value="Bago"> Bago</option>
<option value="Binalbagan"> Binalbagan </option>
<option value="Cadiz"> Cadiz </option>
<option value="Calatrava"> Calatrava </option>
<option value="Candoni"> Candoni </option>
<option value="Cauayan"> Cauayan </option>
<option value="Enrique B. Magalona "> Enrique B. Magalona (Saravia) </option>
<option value="Escalante"> Escalante </option>
<option value="Himamaylan"> Himamaylan </option>
<option value="Hinigaran"> Hinigaran </option>
<option value="Hinoba-an"> Hinoba-an </option>
<option value="Ilog"> Ilog </option>
<option value="Isabela"> Isabela </option>
<option value="Kabankalan"> Kabankalan </option>
<option value="La Carlota"> La Carlota </option>
<option value="La Castellana"> La Castellana </option>
<option value="Manapla"> Manapla </option>
<option value="Moises Padilla"> Moises Padilla </option>
<option value="Murcia"> Murcia </option>
<option value="Pontevedra"> Pontevedra </option>
<option value="Pulupandan"> Pulupandan </option>
<option value="Sagay"> Sagay </option>
<option value="Salvador Benedicto"> Salvador Benedicto </option>
<option value="San Carlos"> San Carlos </option>
<option value="San Enrique"> San Enrique </option>
<option value="Silay"> Silay </option>
<option value="Sipalay"> Sipalay </option>
<option value="Talisay"> Talisay </option>
<option value="Toboso"> Toboso </option>
<option value="Valladolid"> Valladolid </option>
<option value="Victorias"> Victorias </option>
</select>
<br/> <br/>
<br/> <br/>
</div>
<input type="submit" name="submit" value="Reserve">
</form>
</div></center>
|
Python
|
UTF-8
| 856 | 2.8125 | 3 |
[] |
no_license
|
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('../images/fourierHist2.jpg',cv2.IMREAD_GRAYSCALE)
thresholder = 70
whiteValue = 255
blur = cv2.GaussianBlur(img,(5,5),0)
# global thresholding
ret1,th1 = cv2.threshold(blur,thresholder,whiteValue,cv2.THRESH_BINARY)
images = [blur, 0, th1]
titles = ['Original Noisy Image','Histogram','Threshold (v=' + str(thresholder) + ')']
for i in range(1):
plt.subplot(1,3,i*3+1),plt.imshow(images[i*3],'gray')
plt.title(titles[i*3]), plt.xticks([]), plt.yticks([])
plt.subplot(1,3,i*3+2),plt.hist(images[i*3].ravel(),256)
plt.title(titles[i*3+1]), plt.xticks([]), plt.yticks([])
plt.subplot(1,3,i*3+3),plt.imshow(images[i*3+2],'gray')
plt.title(titles[i*3+2]), plt.xticks([]), plt.yticks([])
cv2.imwrite('../images/bluredFouier2.jpg',th1)
plt.show()
|
C#
|
UTF-8
| 4,353 | 3.078125 | 3 |
[] |
no_license
|
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
public class ModulesManager : Singleton<ModulesManager>
{
/// <summary>
/// This multi-map array stores all links from a module to its levels
/// </summary>
private readonly Dictionary<ModuleInfo, List<LevelInfo>> moduleLevelMap = new Dictionary<ModuleInfo, List<LevelInfo>>();
/// <summary>
/// Adds a module to the module list
/// </summary>
/// <param name="module">The module info</param>
public void AddModule(ModuleInfo module)
{
moduleLevelMap.Add(
module,
new List<LevelInfo>()
);
}
/// <summary>
/// Adds a level to the module multimap
/// </summary>
/// <param name="module">The module the level is in</param>
/// <param name="level">The level name</param>
public void AddLevel(ModuleInfo module, LevelInfo level)
{
// If the map doesn't contain the module, abort.
if (!moduleLevelMap.ContainsKey(module))
return;
moduleLevelMap[module].Add(level);
moduleLevelMap[module].Sort((l, r) =>
{
if (int.TryParse(l.Name, out int lInt) &&
int.TryParse(r.Name, out int rInt))
return lInt.CompareTo(rInt);
return l.Name.CompareTo(r.Name);
});
}
/// <summary>
/// Gets all the levels of a selected module
/// </summary>
/// <param name="module">The module</param>
/// <returns>An enumerator with all the levels.</returns>
public IEnumerable<LevelInfo> GetAllLevelsFor(ModuleInfo module)
{
if (!moduleLevelMap.ContainsKey(module))
yield break;
foreach (var level in moduleLevelMap[module])
yield return level;
}
/// <summary>
/// Tries to find a level from a given module, with the predicate
/// acting as a judge on which level to find.
/// </summary>
/// <param name="module">The module</param>
/// <param name="predicate">The predicate with which we're finding the level</param>
/// <returns>Null if the level wasn't found. LevelInfo if we found the level.</returns>
public LevelInfo FindLevelFromModule(ModuleInfo module, Predicate<LevelInfo> predicate)
{
if (!moduleLevelMap.ContainsKey(module))
return null;
foreach (var level in moduleLevelMap[module])
if (predicate(level))
return level;
return null;
}
/// <summary>
/// Gets a random level with a given difficulty
/// </summary>
/// <param name="module">The module</param>
/// <returns>Either a level or nothing.</returns>
public LevelInfo GetRandomLevelOfDifficulty(ModuleInfo module, Level.Difficulty difficulty)
{
if (!moduleLevelMap.ContainsKey(module))
return null;
// Temporarily allocate an array to clone the module level set
var asArray = moduleLevelMap[module].ToArray();
var counter = 0;
// I'll run for 50 tries
while (counter < 50)
{
var level = asArray[UnityEngine.Random.Range(0, asArray.Length)];
if (level.Difficulty == difficulty)
return level;
counter++;
}
return null;
}
/// <summary>
/// Finds a module with the predicate.
/// </summary>
/// <param name="predicate">The predicate that decides on the module</param>
/// <returns>Null if the module wasn't found. ModuleInfo if we found the level.</returns>
public ModuleInfo FindModule(Predicate<ModuleInfo> predicate)
{
foreach (var module in moduleLevelMap.Keys)
if (predicate(module))
return module;
return null;
}
/// <summary>
/// Removes a level from a module
/// </summary>
/// <param name="module">The module the level is in</param>
/// <param name="levelInfo">The level</param>
public void RemoveLevel(ModuleInfo module, LevelInfo levelInfo)
{
var moduleFolderPath = Path.Combine(Application.streamingAssetsPath, "Modules", module.Directory);
File.Delete(Path.Combine(moduleFolderPath, $"{levelInfo.Id}.info"));
File.Delete(Path.Combine(moduleFolderPath, $"{levelInfo.Id}.map"));
}
}
|
JavaScript
|
UTF-8
| 4,784 | 2.671875 | 3 |
[] |
no_license
|
import config from '../configs/urlAppProposta'
const URL_USUARIOS = `${config.URL_APPPROPOSTA}/usuarios`
////////////////////////////////////////////////////////////////////////
// REFRESH TOKEN
function refreshToken() {
const URL = `${config.URL_APPPROPOSTA}/refresh-token`
const refreshToken = localStorage.getItem('refreshToken')
console.log("========== No refreshToken ==========")
console.log("URL=", URL)
console.log("refreshToken=", refreshToken)
return fetch(URL, {
method: 'POST',
headers: {
Authorization: JSON.parse(refreshToken),
'Content-type': 'application/json'
}
})
.then(async (response) => {
console.log("response=", response)
if (response.ok) {
const resposta = await response.json()
console.log("resposta=", resposta)
localStorage.setItem('accessToken', JSON.stringify(resposta.accessToken))
return true
}
if (response.status === 401) {
console.log("Passou pelo 401 no refreshToken")
return false
} else {
console.log("Não é 401 no refreshToken")
throw new Error('Sem conexão com o servidor (refresh token)')
}
})
}
////////////////////////////////////////////////////////////////////////
// API GENÉRICO
function getGenerico(pesquisa, refreshTokenJaUsado) {
const URL = `${config.URL_APPPROPOSTA}/api-generico`
const token = localStorage.getItem('accessToken')
/* console.log("========== No getGenerico ==========")
console.log("URL=", URL)
console.log("pesquisa=", pesquisa)
*/
return fetch(URL, {
method: 'POST',
headers: {
Authorization: JSON.parse(token),
'Content-type': 'application/json'
},
body: JSON.stringify(pesquisa)
})
.then(async (response) => {
// console.log("response=", response)
if (response.ok) {
const resposta = await response.json()
// console.log("resposta=", resposta)
return resposta
}
if (response.status === 401) {
let respostaAposRefreshToken = null
// console.log("refreshTokenJaUsado=", refreshTokenJaUsado)
if (refreshTokenJaUsado) {
throw new Error('401 - Usuário deve fazer login')
} else {
refreshTokenJaUsado = true
await refreshToken()
.then(async (refreshTokenOk) => {
// console.log("refreshTokenOk=", refreshTokenOk)
if (!refreshTokenOk) {
// console.log("refresh Token não funcionou")
throw new Error('401 - Usuário deve fazer login')
} else {
await getGenerico(bd, id, refreshTokenJaUsado)
.then(async (resposta) => {
respostaAposRefreshToken = resposta
// console.log("refresh Token funcionou!!!")
// console.log("resposta após refresh Token=", respostaAposRefreshToken)
})
}
})
}
return await respostaAposRefreshToken
} else throw new Error('Sem conexão com o servidor')
})
}
////////////////////////////////////////////////////////////////////////
// CRIA EMPRESA
function createEmpresa(registro) {
return fetch(URL_EMPRESAS, {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(registro)
})
.then(async (response) => {
if (response.ok) {
const resposta = await response.json()
return resposta
}
throw new Error('Não conseguiu criar a empresa')
})
}
////////////////////////////////////////////////////////////////////////
// Acesso à coleção USUÁRIOS - getUsuarios deverá ser eliminada
function getUsuarios(token, id) {
const URL = !id ? `${URL_USUARIOS}/all` : `${URL_USUARIOS}/${id}`
return fetch(URL, {
method: 'GET',
headers: {
'x-access-token': token,
'Content-type': 'application/json'
}
})
.then(async (response) => {
if (response.ok) {
const resposta = await response.json()
return resposta
}
throw new Error('Sem conexão com o servidor (db: usuários)')
})
}
function createUsuario(registro) {
return fetch(URL_USUARIOS, {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(registro)
})
.then(async (response) => {
if (response.ok) {
const resposta = await response.json()
return resposta
}
if (response.status === 409) throw new Error('409 - Usuário já cadastrado')
else throw new Error('404 - Não conseguiu criar a empresa')
})
}
export default {
getGenerico,
createEmpresa,
getUsuarios,
createUsuario
}
|
Java
|
UTF-8
| 409 | 2.21875 | 2 |
[] |
no_license
|
package th.ac.kku.charoenkitsupat.chanyanood.managementforsugarapp;
/**
* Created by Panya on 23/7/2560.
*/
public class EmployeeModel {
private String id, password;
EmployeeModel(String id, String password) {
this.id = id;
this.password = password;
}
public String getId() {
return id;
}
public String getPassword() {
return password;
}
}
|
PHP
|
UTF-8
| 2,883 | 2.625 | 3 |
[] |
no_license
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
class AuctionProduct extends Model
{
const AUCTION_STATUS_PREPARING = 'preparing'; // 尚未开始
const AUCTION_STATUS_BIDDING = 'bidding'; // 拍卖进行中
const AUCTION_STATUS_SIGNED = 'signed'; // 成交
const AUCTION_STATUS_ABORTIVE = 'abortive'; // 流拍
public static $auctionStatusMap = [
self::AUCTION_STATUS_PREPARING => '尚未开始',
self::AUCTION_STATUS_BIDDING => '拍卖进行中',
self::AUCTION_STATUS_SIGNED => '成交',
self::AUCTION_STATUS_ABORTIVE => '流拍'
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'product_id',
'trigger_price',
'current_price',
'final_price',
'step',
'max_participant_number',
'max_deal_number',
'status',
'started_at',
'stopped_at'
];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [
'started_at',
'stopped_at'
];
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = [
// 'product_name',
// 'status_name',
// 'length',
// 'bids'
];
/* Accessors */
/*public function getProductNameAttribute()
{
return Product::find($this->attributes['product_id'])->name_en;
}*/
public function getStatusNameAttribute()
{
$auction_status_map = [
'preparing' => '尚未开始',
'bidding' => '拍卖进行中',
'signed' => '成交',
'abortive' => '流拍'
];
return $auction_status_map[$this->attributes['status']];
}
public function getLengthAttribute()
{
return Carbon::make($this->attributes['started_at'])->diffInRealSeconds($this->attributes['stopped_at']);
}
public function getBidsAttribute()
{
return ProductAuctionLog::where('auction_product_id', $this->attributes['id'])->count();
}
/* Mutators */
/*public function setProductNameAttribute($value)
{
unset($this->attributes['product_name']);
}*/
public function setStatusNameAttribute($value)
{
unset($this->attributes['status_name']);
}
public function setLengthAttribute($value)
{
unset($this->attributes['length']);
}
public function setBidsAttribute($value)
{
unset($this->attributes['bids']);
}
/* Eloquent Relationships */
public function product()
{
return $this->belongsTo(Product::class);
}
public function auction_logs()
{
return $this->hasMany(ProductAuctionLog::class);
}
}
|
C++
|
UTF-8
| 4,533 | 2.890625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include "smove.h"
#include <conio.h>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <windows.h>
using namespace std;
bool ifdead(const vector<vector<char> >& map, Point head)
{
bool GAMEOVER= false;
short ErrorRow= START_ROW + 4;
if (map[head.row_i][head.col_i] == '+') {
goto_RowCol(ErrorRow, 2);
cout << "Eat self!";
goto_RowCol(START_ROW + map.size(), START_COL + map[0].size() / 2 - 1);
system("color 40&pause");
GAMEOVER= true;
}
if (map[head.row_i][head.col_i] == '#') {
goto_RowCol(ErrorRow, 2);
cout << "wall!";
goto_RowCol(START_ROW + map.size(), START_COL + map[0].size() / 2 - 1);
system("color 40&pause");
GAMEOVER= true;
}
return GAMEOVER;
}
inline bool ifgrow(const vector<vector<char> >& map, Point head)
{
if (map[head.row_i][head.col_i] == '*')
return true;
else
return false;
}
void grow(vector<vector<char> >& map, vector<Point>& snake, int& score,
Point head, bool& FoodExist)
{
snake.insert(snake.begin(), head);
goto_RowCol(START_ROW + head.row_i, START_COL + head.col_i);
cout << '@';
map[snake[1].row_i][snake[1].col_i]= '+';
goto_RowCol(START_ROW + snake[1].row_i, START_COL + snake[1].col_i);
cout << '+';
score++;
FoodExist= false;
}
void goon(vector<vector<char> >& map, vector<Point>& snake, Point head)
{
{
snake.insert(snake.begin(), head);
goto_RowCol(START_ROW + head.row_i, START_COL + head.col_i);
cout << '@';
}
{
map[snake[1].row_i][snake[1].col_i]= '+';
goto_RowCol(START_ROW + snake[1].row_i, START_COL + snake[1].col_i);
cout << '+';
}
{
map[snake[snake.size() - 1].row_i][snake[snake.size() - 1].col_i]= ' ';
goto_RowCol(START_ROW + snake[snake.size() - 1].row_i,
START_COL + snake[snake.size() - 1].col_i);
cout << ' ';
snake.erase(snake.end() - 1);
}
}
bool smove(vector<vector<char> >& map, vector<Point>& snake,
Direction direction, int& score, bool& FoodExist)
{
Point head= snake[0];
switch (direction) {
case LEFT:
head.col_i-= 1;
if (head.col_i >= 0) {
if (ifdead(map, head)) {
// goto_RowCol(ErrorRow, 2);
// cout << "Can not back";
return true;
} else if (ifgrow(map, head)) {
grow(map, snake, score, head, FoodExist);
} else {
goon(map, snake, head);
}
} else {
short ErrorRow= START_ROW + 4;
goto_RowCol(ErrorRow, 2);
cout << "wall!";
goto_RowCol(START_ROW + map.size(),
START_COL + map[0].size() / 2 - 1);
system("color 40&pause");
return true;
}
break;
case RIGHT:
head.col_i+= 1;
if (head.col_i < map[0].size()) {
if (ifdead(map, head)) {
return true;
} else if (ifgrow(map, head)) {
grow(map, snake, score, head, FoodExist);
} else {
goon(map, snake, head);
}
} else {
short ErrorRow= START_ROW + 4;
goto_RowCol(ErrorRow, 2);
cout << "wall!";
goto_RowCol(START_ROW + map.size(),
START_COL + map[0].size() / 2 - 1);
system("color 40&pause");
return true;
}
break;
case UP:
head.row_i-= 1;
if (ifdead(map, head)) {
return true;
} else if (ifgrow(map, head)) {
grow(map, snake, score, head, FoodExist);
} else {
goon(map, snake, head);
}
break;
case DOWN:
head.row_i+= 1;
if (ifdead(map, head)) {
return true;
} else if (ifgrow(map, head)) {
grow(map, snake, score, head, FoodExist);
} else {
goon(map, snake, head);
}
break;
default: break;
};
return false;
}
|
JavaScript
|
UTF-8
| 1,427 | 2.515625 | 3 |
[] |
no_license
|
define('RemoteTemplate', ['env', 'AjaxForm', '../Utilities/OptionsParser', 'jquery', 'underscore'], function(env, AjaxForm, OptionsParser, $, _){
var postData = {
communityId : $('#remote-template-script').attr('community-id'),
requests : []
};
var init = function(){
// set postData.requests
$('div[remote-template]').each(function(){
postData.requests.push(generateRequest($(this)));
});
$.ajax({
url : env.apiUrl+'remote-template',
type : 'post',
data : postData,
success : dispatchTemplates,
error : function(r){ console.log(r); }
});
}
var generateRequest = function(elem){
return {
name : elem.attr('remote-template'),
options : OptionsParser(elem.attr('remote-template-options'))
}
}
var dispatchTemplates = function(templates){
var template;
for(var i=0;i<templates.length;i++){
template = templates[i];
// Incase two templates are used on the same page,
// we have to make sure we inject the html into the proper remote-template div
// we do this by checking className:name in remote-template-options attr
_.each($('div[remote-template="'+template.name+'"]'), function(remoteTemplate){
var rtOptions = $(remoteTemplate).attr('remote-template-options');
if(rtOptions.match("className:"+template.templateRequest.options.className)){
$(remoteTemplate).html(template.html);
}
});
}
}
return {
init : init
};
});
|
C++
|
UTF-8
| 2,655 | 2.84375 | 3 |
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Form.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jereligi <jereligi@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/10/19 14:39:13 by jereligi #+# #+# */
/* Updated: 2020/10/20 17:52:10 by jereligi ### ########.fr */
/* */
/* ************************************************************************** */
#include "Form.hpp"
Form::Form(std::string name, int signGrade, int execGrade) : name(name),
signGrade(signGrade), execGrade(execGrade)
{
if (this->signGrade < 1 || this->execGrade < 1)
throw Form::GradeTooHighException();
else if (this->signGrade > 150 || this->execGrade > 150)
throw Form::GradeTooLowException();
this->sign = false;
return ;
}
Form::Form(Form const &src) : name(src.name), sign(src.sign),
signGrade(src.signGrade), execGrade(src.execGrade)
{
return ;
}
Form::~Form(void)
{
return ;
}
Form &Form::operator=(Form const &src)
{
this->sign = src.sign;
return (*this);
}
std::string const Form::getName(void) const
{
return this->name;
}
bool Form::getSign(void) const
{
return this->sign;
}
int Form::getSignGrade(void) const
{
return this->signGrade;
}
int Form::getSignExec(void) const
{
return this->execGrade;
}
const char *Form::GradeTooHighException::what() const throw()
{
return "Error: Grade too high.";
}
const char *Form::GradeTooLowException::what() const throw()
{
return "Error: Grade too low.";
}
const char *Form::UnsignedForm::what() const throw()
{
return "Error: Unsigned form";
}
void Form::beSigned(Bureaucrat &bureaucrat)
{
if (bureaucrat.getGrade() > this->signGrade)
throw Form::GradeTooLowException();
this->sign = true;
}
void Form::execute(Bureaucrat const &executor) const
{
if (executor.getGrade() > this->execGrade)
throw Form::GradeTooLowException();
else if (this->sign == false)
throw Form::UnsignedForm();
}
std::ostream &operator<<(std::ostream &o, Form const &i)
{
o << "Form: " << i.getName() << std::endl << "signed: " << i.getSign() \
<< std::endl << "signature grade: " << i.getSignGrade() << std::endl \
<< "execution grade: " << i.getSignExec();
return o;
}
|
Markdown
|
UTF-8
| 3,889 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
# Intelligent Human Computer Interaction Game
*Human Computer Interaction Game by using OpenCV and Processing:* Control the game character's velocity through the speed and direction of your fist or palm(hand)! Fist&palm(hand) is detected using [Haar-Cascade Classifier](http://docs.opencv.org/2.4/modules/objdetect/doc/cascade_classification.html) is implemented with OpenCV on java. The trained Haar-Cascade Classifier XML files can be accessible in [here](https://github.com/ahmetozlu/intelligent-human-computer-interaction-game/tree/master/src/mario). ***Please contact if you need professional human-computer inteaction based projects with the super high accuracy.***
<p align="center">
<img src="https://user-images.githubusercontent.com/22610163/29653050-ee737c04-88b0-11e7-8b3e-3404b592732c.gif">
</p>
## Introduction
- **The Game Scenario:** The game character's (Super Mario's) velocity depends on the speed and direction someone's fist or palm(hand) (as user's choise) movements by using the computer's front-facing web camera. The 'stage' is just a 2D platform, with random holes on the ground and random clouds on sky. There is a timer upon game start, and that timer stops when the character collide to one of those holes or clouds (game end). A button resets the game stage.
- **The Main Aim of The Game:** The main aim of this proof-of concept game is that incentivizing the users to move/sport for keeping them healthy while they are having fun by playing a human - computer interaction game.
- *Games for human health, wellbeing, and fitness:* I have recently begun to focus on making sports, physiological exercise, health, and wellbeing applications more playful, especially in light of the recent increase in sensor use and the quantified self movement.
## Theory
**1. Front-End**
The 'stage' is just a 2D platform, with random holes on the ground and random clouds on sky and it was created by using Processing 3.0 with the images that are available in [data folder](https://github.com/ahmetozlu/intelligent-human-computer-interaction-game/tree/master/src/mario/data).
**2. Back-End**
[Haar-Cascade Classifier](http://docs.opencv.org/2.4/modules/objdetect/doc/cascade_classification.html) was used for fist and palm(hand) detection. The trained Haar-Cascade Classifier XML files are available in [here](https://github.com/ahmetozlu/intelligent-human-computer-interaction-game/tree/master/src/mario).
<p align="center">
<img src="https://user-images.githubusercontent.com/22610163/29589421-e895550a-879d-11e7-9e3f-b04546cd9ece.png">
</p>
*A human–machine interface usually involves peripheral hardware for the INPUT and for the OUTPUT. Often, there is an additional component implemented in software, like e.g. a graphical user interface.*
## Project Demo
- The demo video of this project is available on YouTube: https://www.youtube.com/watch?v=HpzLbTf2OQk
## Installation
**Dependencies:**
It is developed with "[Processing 3.0](https://processing.org/download/)" and it requires these library;
1. Video | GStreamer-based video library for Processing
2. OpenCV for Processing | Computer Vision with OpenCV for Processing
These libraries can be added on Processing 3.0 IDE --- follow this path: "*Tools-> Add Tool->Libraries*"
**How to build and run this source?**
1. Clone repository to your local and import project into Processing 3.0 IDE
2. Install the dependencies which are given at above
3. Build and run the project
## Citation
If you use this code for your publications, please cite it as:
@ONLINE{vdtc,
author = "Ahmet Özlü",
title = "Intelligent Human Computer Interaction Game",
year = "2017",
url = "https://github.com/ahmetozlu/human_computer_interaction"
}
## Author
Ahmet Özlü
## License
This system is available under the MIT license. See the LICENSE file for more info.
|
Python
|
UTF-8
| 2,108 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
import csv
from monsoonanalyzer import TransmitSegment
class TransmitData():
def __init__(self, cpu_cores, cpu_freq, filename):
self.cpu_cores = cpu_cores
self.cpu_freq = cpu_freq
self.src_rates = []
self.transmit_segment_dict = {}
with open(filename, newline='') as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
for entry in csv_reader:
expected_src_rate = int(entry[0])
start_time = int(float(entry[1]))
end_time = int(float(entry[2]))
total_time = int(float(entry[3]))
packets_sent = int(entry[4])
self.transmit_segment_dict[expected_src_rate] = TransmitSegment(
expected_src_rate,
start_time,
end_time,
total_time,
packets_sent)
self.src_rates = sorted(list(self.transmit_segment_dict.keys()))
# def normalize_timing(self, full_transmission_end_time):
# cur_time = full_transmission_end_time
# for src_rate in reversed(self.src_rates):
# transmit_segment = self.transmit_segment_dict[src_rate]
# transmit_segment.end_time = cur_time
# cur_time -= transmit_segment.total_time
# transmit_segment.start_time = cur_time
# cur_time -= 3000000
def normalize_timing(self, full_transmission_end_time):
cur_time = full_transmission_end_time
for i,src_rate in enumerate(reversed(self.src_rates)):
transmit_segment = self.transmit_segment_dict[src_rate]
pred_diff = 0
if i != len(self.src_rates) - 1:
pred_segment = self.transmit_segment_dict[self.src_rates[len(self.src_rates) - i - 2]]
pred_diff = transmit_segment.start_time - pred_segment.end_time
transmit_segment.end_time = cur_time
cur_time -= transmit_segment.total_time
transmit_segment.start_time = cur_time
cur_time -= pred_diff
|
Java
|
UTF-8
| 557 | 3.71875 | 4 |
[] |
no_license
|
package handledning1;
import java.util.Scanner;
public class Calculator2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Skriv ett tal: ");
double tal1 = scan.nextDouble();
System.out.println("Skriv ett till tal: ");
double tal2 = scan.nextDouble();
System.out.println("Addition: " + (tal1 + tal2));
System.out.println("Subtraktion: " + (tal1 - tal2));
System.out.println("Multiplikation: " + (tal1 * tal2));
System.out.println("Division: " + (tal1 / tal2));
}
}
|
C#
|
UTF-8
| 2,128 | 3.78125 | 4 |
[] |
no_license
|
using Distributions.Generators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Distributions
{
public abstract class Distribution
{
#region Variables
/// <summary>
/// The generator used to obtain the initial random numbers
/// </summary>
public Generator Random = new DefaultGenerator();
/// <summary>
/// The tolerance allowed for numbers counting as 0
/// </summary>
public static double Tolerance = 1E-6;
#endregion Variables
#region Abstract Methods
/// <summary>
/// Obtains a sample number from the distribution using a random number generated via the Random variable.
/// </summary>
/// <returns></returns>
public abstract double Sample();
/// <summary>
/// Checks if the parameters for the distribution were set correctly
/// </summary>
/// <returns></returns>
public abstract bool AreParametersValid();
#endregion Abstract Methods
#region Static Methods
/// <summary>
/// Returns true if the number is between 0 and the tolerance variable
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static bool IsNearZero(double x)
{
return x > -Tolerance && x < Tolerance;
}
/// <summary>
/// Squares the number quickly
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static double Square(double x)
{
return IsNearZero(x) ? 0.0 : x * x;
}
/// <summary>
/// Checks if the two numbers are equal (within the tolerance value of eachother)
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static bool AreEqual(double x, double y)
{
return IsNearZero(x - y);
}
#endregion Static Methods
}
}
|
JavaScript
|
UTF-8
| 161 | 2.5625 | 3 |
[] |
no_license
|
function covfefe(str){
if(str.toLowerCase().includes('coverage')) {
return str.replace(/(c)overage/gi, '$1ovfefe');
} else {
return str + ' covfefe';
}
}
|
C++
|
UTF-8
| 634 | 3.921875 | 4 |
[] |
no_license
|
// Write a program that asks the user to type in numbers. After each entry, the
//program should report the cumulative sum of the entries to date. The program should
//terminate when the user enters 0.
#include <iostream>
int main()
{
using namespace std;
int input;
cout << "Enter numbers: ";
cout << "(Enter 0 to terminate.)";
cin >> input;
int sum = 0;
while (cin.good() & input != 0)
{
sum += input;
cout << "The sum now is: " << sum << endl;
cin >> input;
}
if (cin.fail() && cin.peek() != ' ' && cin.peek() != '\n')
cerr << "Error: Invalid Input." << endl;
return 0;
}
|
C++
|
UTF-8
| 682 | 2.96875 | 3 |
[] |
no_license
|
#include "LL.h"
#include <iostream>
using namespace std;
void LL::sort()
{
if(head==NULL)
return;
head = head->sort();
}
LLN *LLN::sort()
{
if(this == NULL || next==NULL)
return this;
LLN *b = split();
LLN *a = sort();
b = b->sort();
return a->merge(b);
}
LLN *LLN::split()
{
if (this == NULL || next == NULL)
return NULL;
LLN *b = next;
next = b->next;
b->next = next->split();
return b;
}
LLN *LLN::merge(LLN *b)
{
if (this == NULL)
return b;
if (b == NULL)
return this;
if (s < b->s)
{
next = next->merge(b);
return this;
}
else
{
b->next = b->next->merge(this);
return b;
}
}
|
PHP
|
UTF-8
| 898 | 2.59375 | 3 |
[] |
no_license
|
<?php
require_once("phpmailer/class.phpmailer.php");
class mail
{
public static function sendmail($user_email, $user_name, $subject, $body)
{
$mail = new PHPMail();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->CharSet = "utf-8";
$mail->Username = "xxxxxx@xxxxxx";
$mail->Password = "ur password";
//$mail->AddAttachment("");
$mail->Subject = $subject;
$mail->From = "xxxxxx@xxxxxx";
$mail->FromName = "xxxxxxxxx";
$mail->Body = $body;
$mail->IsHTML(true);
$mail->AddAddress($user_email, $user_name);
if (!$mail->Send()) {
echo 'OOPs!! Fail to send email'.$mail->ErrorInfo;
return $this->noview();
} else {
//
}
}
}
|
Java
|
UTF-8
| 9,095 | 1.757813 | 2 |
[] |
no_license
|
package com.robo.store;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.apache.http.Header;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.robo.store.adapter.HomeListViewAdapter;
import com.robo.store.adapter.HomeMenuGridViewAdapter;
import com.robo.store.dao.GetShopInfoResponse;
import com.robo.store.dao.GoodsBase;
import com.robo.store.dao.GoodsType;
import com.robo.store.http.HttpParameter;
import com.robo.store.http.RoboHttpClient;
import com.robo.store.http.TextHttpResponseHandler;
import com.robo.store.util.HomeUtil;
import com.robo.store.util.KeyUtil;
import com.robo.store.util.LogUtil;
import com.robo.store.util.ResultParse;
import com.robo.store.util.Settings;
import com.robo.store.util.ToastUtil;
import com.robo.store.view.MyGridView;
public class ShopDetailActivity extends BaseActivity implements OnClickListener{
private LayoutInflater inflater;
private ListView mListView;
private FrameLayout search_cover;
private Button check_shop_location_btn;
private HomeMenuGridViewAdapter mMenuAdapter;
private List<GoodsType> mGoodsTypeList;
private HomeListViewAdapter mHomeListViewAdapter;
private List<GoodsBase> goodsList;
private GetShopInfoResponse mGetGoodsListResponse;
private View headerView,footerView;
private LinearLayout load_more_data;
private TextView no_more_data;
private MyGridView mGridView;
private String goodType = "0";
public int pageIndex = 0;
private boolean isLoadMoreData;
private boolean isFinishloadData = true;
private String shopId;
private boolean isInitFooterView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle();
setContentView(R.layout.activity_shop_detail);
init();
onCreateShowProgressbar();
RequestData();
}
private void setTitle(){
Bundle mBundle = getIntent().getBundleExtra(KeyUtil.BundleKey);
if(mBundle != null){
shopId = mBundle.getString(KeyUtil.ShopDetailIdKey);
String title = mBundle.getString(KeyUtil.ShopDetailTitleKey);
setTitle(title);
}
}
private void init(){
inflater = LayoutInflater.from(this);
mGoodsTypeList = new ArrayList<GoodsType>();
goodsList = new ArrayList<GoodsBase>();
mHomeListViewAdapter = new HomeListViewAdapter(this, inflater, goodsList);
mMenuAdapter = new HomeMenuGridViewAdapter(this, inflater, mGoodsTypeList);
initSwipeRefresh();
search_cover = (FrameLayout) findViewById(R.id.search_cover);
mListView = (ListView) findViewById(R.id.content_lv);
check_shop_location_btn = (Button) findViewById(R.id.check_shop_location_btn);
footerView = inflater.inflate(R.layout.list_footer_view, null);
load_more_data = (LinearLayout) footerView.findViewById(R.id.load_more_data);
no_more_data = (TextView) footerView.findViewById(R.id.no_more_data);
footerView.setVisibility(View.GONE);
headerView = inflater.inflate(R.layout.shop_list_header, null);
mGridView = (MyGridView) headerView.findViewById(R.id.gridview);
mGridView.setAdapter(mMenuAdapter);
mGridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
if(mGoodsTypeList.size() > 8 && position == 7 && !mMenuAdapter.isShowAll()){
mMenuAdapter.setShowAll(true);
mMenuAdapter.notifyDataSetChanged();
}else if(position == mGoodsTypeList.size()){
mMenuAdapter.setShowAll(false);
mMenuAdapter.notifyDataSetChanged();
}else{
GoodsType mGoodsType = mGoodsTypeList.get(position);
goodType = mGoodsType.getGoodsTypeId();
HomeUtil.setSelectedMenu(mGoodsTypeList, goodType);
mMenuAdapter.notifyDataSetChanged();
clearList();
mSwipeRefreshLayout.setRefreshing(true);
RequestData();
}
}
});
setListOnScrollListener();
mListView.addHeaderView(headerView);
mListView.setAdapter(mHomeListViewAdapter);
search_cover.setOnClickListener(this);
check_shop_location_btn.setOnClickListener(this);
}
public void setListOnScrollListener(){
mListView.setOnScrollListener(new OnScrollListener() {
private int lastItemIndex;
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && lastItemIndex == mHomeListViewAdapter.getCount() - 1) {
LogUtil.DefalutLog("onScrollStateChanged---update");
if(isLoadMoreData){
RequestData();
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
lastItemIndex = firstVisibleItem + visibleItemCount - 3;
}
});
}
public void onSwipeRefreshLayoutRefresh(){
clearList();
RequestData();
}
@Override
public void onClickEmptyLayoutRefresh() {
mSwipeRefreshLayout.setRefreshing(true);
onSwipeRefreshLayoutRefresh();
}
public void clearList(){
pageIndex = 0;
goodsList.clear();
isInitFooterView = false;
footerView.setVisibility(View.GONE);
mHomeListViewAdapter.notifyDataSetChanged();
load_more_data.setVisibility(View.VISIBLE);
no_more_data.setVisibility(View.GONE);
mListView.removeFooterView(footerView);
}
private void RequestData(){
if(isFinishloadData){
mGridView.setEnabled(false);
isFinishloadData = false;
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("shopId", shopId);
params.put("type", goodType);
params.put("pageIndex", pageIndex);
params.put("pageCount", Settings.pageCount);
RoboHttpClient.post(HttpParameter.goodUrl,"getShopInfo", params, new TextHttpResponseHandler(){
@Override
public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
showEmptyLayout_Error();
ToastUtil.diaplayMesLong(ShopDetailActivity.this, ShopDetailActivity.this.getResources().getString(R.string.connet_fail));
}
@Override
public void onSuccess(int arg0, Header[] arg1, String result) {
mGetGoodsListResponse = (GetShopInfoResponse) ResultParse.parseResult(result,GetShopInfoResponse.class);
if(ResultParse.handleResutl(ShopDetailActivity.this, mGetGoodsListResponse)){
List<GoodsType> typeList = mGetGoodsListResponse.getTypeList();
Collections.reverse(typeList);
mGoodsTypeList.clear();
mGoodsTypeList.addAll(typeList);
HomeUtil.setSelectedMenu(mGoodsTypeList, goodType);
List<GoodsBase> mGoodsList = mGetGoodsListResponse.getGoodsList();
goodsList.addAll(mGoodsList);
mMenuAdapter.notifyDataSetChanged();
mHomeListViewAdapter.notifyDataSetChanged();
if(mGoodsList.size() > 0){
if(mGoodsList.size() < Settings.pageCount && pageIndex == 0){
isLoadMoreData = false;
}else{
initFooterView();
footerView.setVisibility(View.VISIBLE);
isLoadMoreData = true;
pageIndex++;
}
}else{
isLoadMoreData = false;
load_more_data.setVisibility(View.GONE);
no_more_data.setVisibility(View.VISIBLE);
}
}
}
@Override
public void onFinish() {
isFinishloadData = true;
mSwipeRefreshLayout.setRefreshing(false);
mProgressbar.setVisibility(View.GONE);
mGridView.setEnabled(true);
}
});
}
}
private void initFooterView(){
if(!isInitFooterView){
isInitFooterView = true;
mListView.addFooterView(footerView);
}
}
@Override
public void onClick(View v) {
super.onClick(v);
switch(v.getId()){
case R.id.search_cover:
toSearchActivity();
break;
case R.id.check_shop_location_btn:
toMapActivity();
break;
}
}
private void toSearchActivity(){
Bundle mBundle = new Bundle();
mBundle.putString(KeyUtil.SearchTypeKey, SearchActivity.SearchGoods);
mBundle.putString(KeyUtil.ShopDetailIdKey, shopId);
toActivity(SearchActivity.class, mBundle);
}
private void toMapActivity(){
if(!TextUtils.isEmpty(mGetGoodsListResponse.getLatitude()) && !TextUtils.isEmpty(mGetGoodsListResponse.getLongitude())){
Bundle mBundle = new Bundle();
mBundle.putString(KeyUtil.LatitudeKey, mGetGoodsListResponse.getLatitude());
mBundle.putString(KeyUtil.LongitudeKey, mGetGoodsListResponse.getLongitude());
mBundle.putString(KeyUtil.ShopMemoKey, mGetGoodsListResponse.getShopMemo());
toActivity(ShopLocationActivity.class, mBundle);
}
}
}
|
Python
|
UTF-8
| 944 | 2.5625 | 3 |
[] |
no_license
|
import sys
from pyspark import SparkContext
from pyspark.sql import SQLContext
sc = SparkContext("local", "task-2")
sql_context = SQLContext(sc)
word, k, df_path_1, df_path_2 = sys.argv[1:]
k = int(k)
df1 = sql_context.read.csv(df_path_1, header=True)
df1 = df1.filter(df1.word == word)
df1 = df1.repartition(df1.key_id) #Co partition
df2 = sql_context.read.csv(df_path_2, header=True)
df2 = df2.filter((df2.word == word) & (df2.Total_Strokes <= k)
& (df2.recognized == "False"))
df2 = df2.repartition(df2.key_id) #Co partition
joined_df = df1.join(df2, df1.key_id == df2.key_id)
counts_by_rec = joined_df.groupBy(joined_df.countrycode).agg(
{"countrycode": "count"}).collect()
counts_by_rec = sorted(list(map(lambda x: (x[0], x[1]), counts_by_rec)))
if len(counts_by_rec) == 0:
print(0)
else:
for country_code, count in counts_by_rec:
if count != 0:
print(f"{country_code},{count}")
|
C#
|
UTF-8
| 7,651 | 2.65625 | 3 |
[] |
no_license
|
using System;
using System.Drawing;
using System.Text;
using Microsoft.DirectX.Direct3D;
using Microsoft.DirectX.Generic;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D.CustomVertex;
namespace LJM.Similization.Client.DirectX.Controls
{
public static class CustomPainters
{
/// <summary>
/// Creates a <i>VertexBuffer</i> that can used to draw colored rectangles.
/// </summary>
/// <param name="device"></param>
/// <returns></returns>
public static VertexBuffer CreateColoredBuffer(Device device)
{
return VertexBuffer.CreateGeneric<TransformedColored>(
device,
4,
Usage.WriteOnly,
TransformedColored.Format,
Pool.Managed,
null);
}
/// <summary>
/// Creates a <i>VertexBuffer</i> that can be used to draw colored triangles.
/// </summary>
/// <param name="device"></param>
/// <returns></returns>
public static VertexBuffer CreateColoredTriangleBuffer(Device device)
{
return VertexBuffer.CreateGeneric<TransformedColored>(
device,
3,
Usage.WriteOnly,
TransformedColored.Format,
Pool.Managed,
null);
}
/// <summary>
/// Creates a <i>VertexBuffer</i> that can be used to render a texture on a rectangle.
/// </summary>
/// <param name="device"></param>
/// <returns></returns>
public static VertexBuffer CreateTexturedBuffer(Device device)
{
return VertexBuffer.CreateGeneric<TransformedTextured>(
device,
4,
Usage.WriteOnly,
TransformedTextured.Format,
Pool.Managed,
null);
}
/// <summary>
/// Paints a triangle onto the screen.
/// </summary>
/// <param name="device"></param>
/// <param name="region"></param>
/// <param name="buffer"></param>
/// <param name="fillColor"></param>
public static void PaintColoredTriangle(Device device, Rectangle rectangle, VertexBuffer buffer, Color fillColor)
{
GraphicsBuffer<TransformedColored> data = buffer.Lock<TransformedColored>(0, 3, LockFlags.None);
buffer.Unlock();
data[0] = new TransformedColored(rectangle.X, rectangle.Y, .5f, 0, fillColor);
data[1] = new TransformedColored(rectangle.Right, rectangle.Y, .5f, 0, fillColor);
data[2] = new TransformedColored((rectangle.X + rectangle.Right) / 2, rectangle.Bottom, .5f, 0, fillColor);
device.RenderState.ZBufferWriteEnable = false;
device.RenderState.AlphaBlendEnable = true;
device.RenderState.CullMode = Cull.None;
device.VertexFormat = TransformedColored.Format;
device.SetStreamSource(0, buffer, 0);
device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 1);
}
/// <summary>
/// Paints a the specified rectangle with the colors specified.
/// </summary>
/// <param name="device"></param>
/// <param name="rectangle"></param>
/// <param name="buffer"></param>
/// <param name="color1"></param>
/// <param name="color2"></param>
/// <param name="gradientDirection"></param>
public static void PaintColoredRectangle(Device device, Rectangle rectangle, VertexBuffer buffer, Color color1, Color color2, GradientDirection gradientDirection)
{
GraphicsBuffer<TransformedColored> data = buffer.Lock<TransformedColored>(0, 4, LockFlags.None);
int topLeftColor = color1.ToArgb();
int topRightColor = gradientDirection == GradientDirection.Horizontal ? color2.ToArgb() : color1.ToArgb();
int bottomLeftColor = gradientDirection == GradientDirection.Horizontal ? color1.ToArgb() : color2.ToArgb();
int bottomRightColor = color2.ToArgb();
data[0] = new TransformedColored(rectangle.X, rectangle.Y, .5f, 0, topLeftColor);
data[1] = new TransformedColored(rectangle.Right, rectangle.Y, .5f, 0, topRightColor);
data[2] = new TransformedColored(rectangle.X, rectangle.Bottom, .5f, 0, bottomLeftColor);
data[3] = new TransformedColored(rectangle.Right, rectangle.Bottom, .5f, 0, bottomRightColor);
buffer.Unlock();
device.RenderState.ZBufferWriteEnable = false;
device.RenderState.AlphaBlendEnable = false;
device.RenderState.CullMode = Cull.None;
device.VertexFormat = TransformedColored.Format;
device.SetStreamSource(0, buffer, 0);
device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
}
/// <summary>
/// Paints the specified rectangle with the color specified.
/// </summary>
/// <param name="device"></param>
/// <param name="rectangle"></param>
/// <param name="buffer"></param>
/// <param name="color"></param>
public static void PaintColoredRectangle(Device device, Rectangle rectangle, VertexBuffer buffer, Color color)
{
PaintColoredRectangle(device, rectangle, buffer, color, color, GradientDirection.Horizontal);
}
/// <summary>
/// Paints the specified texture on the specified rectangle.
/// </summary>
/// <param name="rectangle"></param>
/// <param name="buffer"></param>
/// <param name="texture"></param>
public static void PaintTexturedRectangle(Device device, Rectangle rectangle, VertexBuffer buffer, Texture texture)
{
GraphicsBuffer<TransformedTextured> graphicsBuffer = buffer.Lock<TransformedTextured>(0, 4, LockFlags.None);
graphicsBuffer[0] = new TransformedTextured(rectangle.X, rectangle.Y, .5f, 0f, 0f, 0f);
graphicsBuffer[1] = new TransformedTextured(rectangle.Right, rectangle.Y, .5f, 0f, 1f, 0f);
graphicsBuffer[2] = new TransformedTextured(rectangle.X, rectangle.Bottom, .5f, 0f, 0f, 1f);
graphicsBuffer[3] = new TransformedTextured(rectangle.Right, rectangle.Bottom, .5f, 0f, 1f, 1f);
buffer.Unlock();
device.VertexFormat = TransformedTextured.Format;
device.RenderState.ZBufferWriteEnable = false;
device.RenderState.CullMode = Cull.None;
device.SetTexture(0, texture);
device.SetStreamSource(0, buffer, 0);
device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
}
/// <summary>
/// Draws a rectangle with the specified color.
/// </summary>
/// <param name="rectangle"></param>
/// <param name="color"></param>
public static void DrawBoundingRectangle(IDirectXControlHost controlHost, Rectangle rectangle, Color color)
{
Vector2[] verts = new Vector2[] {
new Vector2(rectangle.X, rectangle.Y),
new Vector2(rectangle.Right, rectangle.Y),
new Vector2(rectangle.Right, rectangle.Bottom),
new Vector2(rectangle.X, rectangle.Bottom),
new Vector2(rectangle.X, rectangle.Y),
};
controlHost.DrawLine(verts, color);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.