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
|
|---|---|---|---|---|---|---|---|
C#
|
UTF-8
| 1,755
| 2.78125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Airline.Models;
namespace Airline.Tests
{
[TestClass]
public class FlightTests : IDisposable
{
public FlightTests()
{
DBConfiguration.ConnectionString = "server=localhost;user id=root;password=root;port=8889;database=airline_test;";
}
public void Dispose()
{
City.DeleteAll();
Flight.DeleteAll();
}
[TestMethod]
public void Delete_DeletesFlightAssociationFromDatabase_FlightList()
{
//Arrange
City testCity = new City("Seattle");
testCity.Save();
DateTime newDate = new DateTime(2018, 09, 25);
Flight testFlight = new Flight("Portland", "Seattle", "On Time", newDate);
testFlight.Save();
//Act
testFlight.AddCity(testCity);
testFlight.Delete();
List<Flight> resultCityFlights = testCity.GetFlight();
List<Flight> testCityFlights = new List<Flight> {};
//Assert
CollectionAssert.AreEqual(testCityFlights, resultCityFlights);
}
[TestMethod]
public void Test_AddCity_AddsCityToFlights()
{
//Arrange
DateTime newDate = new DateTime(2018, 09, 25);
Flight testFlight = new Flight("Portland", "Seattle", "On Time", newDate);
testFlight.Save();
City testCity1 = new City("Seattle");
testCity1.Save();
City testCity2 = new City("Portland");
testCity2.Save();
//Act
testFlight.AddCity(testCity1);
testFlight.AddCity(testCity2);
List<City> result = testFlight.GetCity();
List<City> testList = new List<City>{testCity1, testCity2};
//Assert
CollectionAssert.AreEqual(result, testList);
}
}
}
|
Java
|
UTF-8
| 475
| 1.929688
| 2
|
[
"Apache-2.0"
] |
permissive
|
/* The Adama Programming Language For Board Games!
* See http://www.adama-lang.org/ for more information.
* (c) copyright 2020 Jeffrey M. Barber (http://jeffrey.io) */
package org.adamalang.runtime.logger;
import org.junit.Test;
public class TransactionTests {
@Test
public void flow() {
new Transaction(-1, "{}", "{\"x\":1}", new TransactionResult(true, 0, 0)).toString();
new Transaction(-1, "{}", "{\"x\":1}", new TransactionResult(false, 0, 0)).toString();
}
}
|
Python
|
UTF-8
| 1,744
| 3.0625
| 3
|
[] |
no_license
|
import csv
# lists to load with data
expPlayers = []
nonPlayers = []
dragons = []
sharks = []
raptors = []
if __name__ == "__main__":
with open('soccer_players.csv', newline='') as csvfile:
rdr = csv.reader(csvfile, delimiter=',')
rows = list(rdr)[1:]
for row in rows:
#if player is experienced
if row[2] == "YES":
expPlayers.append({'name': row[0], 'height': row[1], 'experience': row[2], 'guardians': row[3]})
#if played is not experienced
else:
nonPlayers.append({'name': row[0], 'height': row[1], 'experience': row[2], 'guardians': row[3]})
ind = 0
# distribute experienced players evenly
for p in expPlayers:
if ind % 3 == 0:
dragons.append(p)
elif ind % 3 == 1:
sharks.append(p)
elif ind % 3 == 2:
raptors.append(p)
ind += 1
ind = 0
# distribute unexperienced players evenly
for p in nonPlayers:
if ind % 3 == 0:
dragons.append(p)
elif ind % 3 == 1:
sharks.append(p)
elif ind % 3 == 2:
raptors.append(p)
ind += 1
with open('teams.txt', "w") as teamsfile:
#write sharks to file
teamsfile.write("Sharks\n")
for p in sharks:
val = ""
val += p['name']
val += ", "
val += p['experience']
val += ", "
val += p['guardians']
val += '\n'
teamsfile.write(val)
#write dragons to file
teamsfile.write("Dragons\n")
for p in dragons:
val = ""
val += p['name']
val += ", "
val += p['experience']
val += ", "
val += p['guardians']
val += '\n'
teamsfile.write(val)
#write raptors to file
teamsfile.write("Raptors\n")
for p in raptors:
val = ""
val += p['name']
val += ", "
val += p['experience']
val += ", "
val += p['guardians']
val += '\n'
teamsfile.write(val)
|
Go
|
UTF-8
| 521
| 3.34375
| 3
|
[
"MIT"
] |
permissive
|
package vm
import (
"fmt"
"reflect"
)
type OpCode struct {
Code int
Movement int
Data interface{}
}
func (o OpCode) Similar(p OpCode) bool {
return o.Code == p.Code && o.Movement == p.Movement && reflect.TypeOf(o.Data) == reflect.TypeOf(p.Data)
}
func (o OpCode) Identical(p OpCode) bool {
return reflect.DeepEqual(o, p)
}
func (o *OpCode) Replace(p *OpCode) {
o.Code = p.Code
o.Movement = p.Movement
o.Data = p.Data
}
func (o *OpCode) String() string {
return fmt.Sprintf("%v: %v", o.Code, o.Data)
}
|
C
|
UTF-8
| 10,570
| 3.828125
| 4
|
[] |
no_license
|
#include <stdlib.h>
#include "tp3.h"
int get_int_len(int value)
{
int length=1;
while(value>9){ length++; value/=10; }
return length;
}
element * newelement(element * suivant, int col,int valeur)
{
element *pointeur;
pointeur=malloc(sizeof(element));
if (pointeur == NULL )
{
fprintf(stderr,"Allocation impossible \n");
exit(EXIT_FAILURE);
}
pointeur->colonne=col;
pointeur->valeur=valeur;
pointeur->suivant =suivant;
return pointeur;
}
// Fonction pour saisir les éléments non-nuls d'une matrice creuse
int remplirMat(matrice_creuse *m, int N, int M) {
int i, j;
int first_elem; //first_elem sera un drapeau qui nous permettra de déterminer si le premier élément a été saisi ou non
int saisie;
int longestlength=1,digitlength=1;
element *elem, *temp = NULL;
m->tableauLignes = malloc(N*sizeof(liste_lignes)); //on alloue de la mémoire aux N lignes
if ( m->tableauLignes == NULL )
{
fprintf(stderr,"Allocation impossible \n");
exit(EXIT_FAILURE);
}
m->Ncolonnes = M;
m->Nlignes = N;
for (i=0; i<N; i++) {
first_elem = 0; //on initialise notre drapeau à 0 à chaque itération de i donc à chaque nouvelle ligne
m->tableauLignes[i] = NULL; //on initialise la liste à NULL au cas ou il n'y'ait aucun élément
for(j=0;j<M; j++) {
printf("Veuillez saisir l'élément à la case (%d,%d) : ",i,j);
scanf("%d",&saisie);
if(saisie!=0) {
digitlength=get_int_len(saisie);
if (digitlength > longestlength)
{
longestlength=digitlength;
printf("longest length = %d\n",longestlength);
}
elem=newelement(NULL,j,saisie);//on alloue de la mémoire à l'élément qui est non nul
//on ne sait pas si notre élément sera le dernier élément de la liste donc on initialise toujours elem->suivant à NUL
if (first_elem == 1) //si notre élément n'est pas le premier de la ligne
temp->suivant = elem;
else { //si notre élément est le premier élément de notre ligne
m->tableauLignes[i] = elem;
first_elem = 1;
}
temp=elem; //on garde en mémoire cet élément afin de pouvoir le lier au suivant
}
}
}
return(longestlength);
}
void PrintBorder(int j,int longestlength) //affiche border du matrice
{
int i,k;
for (k=0; k <j; k++)
{
printf("|--");
for (i=0; i<longestlength; i++)
{
printf("-");
}
}
printf("|\n");
}
void PrintRow(int num_espaces,int valeur) //affiche border du matrice
{
int k,split_espaces;
split_espaces=num_espaces/2;
for ( k = 0; k<split_espaces; k++){
printf(" ");
}
printf("%d",valeur);
for ( k = split_espaces; k<= num_espaces; k++){
printf(" ");
}
}
// Fonction pour afficher une matrice creuse
void afficherMat(matrice_creuse m, int longest_chiffre) {
int i,j;
for (i=0; i<m.Nlignes; i++) {
element *pointeur = m.tableauLignes[i]; //pour chaque ligne on assigne un pointeur de type élément
PrintBorder(m.Ncolonnes,longest_chiffre);
for (j=0; j<m.Ncolonnes; j++ ) {
printf("| ");
if ((pointeur != NULL ) && (pointeur->colonne == j)) { //si la ligne n'est pas vide et que le pointeur est à la bonne colonne
PrintRow((longest_chiffre-get_int_len(pointeur->valeur)),pointeur->valeur);
pointeur = pointeur->suivant; //on passe à l'élément suivant
}
else //si le pointeur n'est pas à la bonne position ou si il est NULL alors l'élément est égal à 0
PrintRow((longest_chiffre-1),0);
}
printf("|\n");
}
PrintBorder(m.Ncolonnes,longest_chiffre);
}
void addMat(matrice_creuse m1, matrice_creuse m2) {
int i,j;
element *elem, *prec = NULL;
if ((m1.Nlignes != m2.Nlignes) || (m1.Ncolonnes != m2.Ncolonnes))
printf("Erreur: les deux matrices doivent être de mêmes dimensions");
else{
for (i=0; i<m1.Nlignes; i++) {
element *pt1 = m1.tableauLignes[i];
element *pt2 = m2.tableauLignes[i];
if ( (pt2 == NULL) )
continue; // on n'a pas besoin de passer à la boucle sur les colonnes, 'continue' ici va passer à l'itération de ligne suivante
else if (pt1 == NULL) {//si la ligne de m1 ne comporte que des 0
m1.tableauLignes[i] = pt2;
continue;
}
for (j=0; j<m1.Nlignes; j++) {
if (pt2 == NULL) //si l'élément de la 2ème matrice est NULL alors on sort de cette boucle car il n'y'a plus d'élément dans m2
break;
else if (pt1 == NULL) {
prec->suivant = pt2;
break;
}
if (pt1->colonne == pt2->colonne) { // 1er cas
pt1->valeur += pt2->valeur;
prec = pt1;
pt1 = pt1->suivant;
pt2= pt2->suivant;
}
else if (pt1->colonne < pt2->colonne) { //2ème cas
prec = pt1;
pt1 = pt1->suivant;
} else if (pt2->colonne < pt1->colonne) { //3ème cas
elem=newelement(pt1,pt1->colonne,pt1->valeur);
//on alloue de la mémoire à un nouveau élément dans m1
//on loue le nouvel élément à pt1 qui sera le suivant
if (pt1 == m1.tableauLignes[i]) //si c'est notre premier élément dans m1
m1.tableauLignes[i]=elem; //notre nouvel élément devient le premier de la ligne
else
prec->suivant=elem; //on lie le nouvel élément au précedent
prec = elem;
pt2 = pt2->suivant;
}
}
}
}
}
//Fonction pour afficher une valeur d'une ligne et colonne données
int getValue(matrice_creuse m, int i, int j) {
element *elem = m.tableauLignes[i];
if ( (elem == NULL) || ((elem->colonne < j) && (elem->suivant == NULL)) || (elem->colonne > j) ) //les cas pour lesquels l'élement que l'on veut retourner est égal à 0
return 0;
else {
if (elem->colonne < j)
while ( (elem->colonne < j) && (elem->suivant != NULL))
elem = elem->suivant;
if (elem->colonne == j)
return elem->valeur;
else
return 0;
}
}
//Fonction pour mettre à jour ou ajouter une valeur dans notre matrice
void putValue(matrice_creuse m, int i, int j, int val) {
element *prec = NULL, *tmp = NULL, *elem = m.tableauLignes[i];
if (elem == NULL) {
tmp=newelement(NULL,j,val);
m.tableauLignes[i] = tmp;
}
else {
if (elem->colonne == j) //1er cas
elem->valeur = val;
else if (elem->colonne > j) { //2ème cas
tmp=newelement(elem,j,val);
m.tableauLignes[i] = tmp;
}
else if (elem->colonne < j) { //3ème cas
while ((elem->colonne < j) && (elem->suivant != NULL)) {
prec = elem;
elem = elem->suivant;
}
if (elem->colonne > j) {
tmp=newelement(elem,j,val);
prec->suivant = tmp;
}
else if (elem->colonne == j)
elem->valeur = val;
else {
tmp=newelement(NULL,j,val);
elem->suivant = tmp;
}
}
}
}
//Fonction pour déterminer le nb d'octets gagnés
int nombreOctetsGagnes(matrice_creuse m1)
{
int i, j, somme_elem=m1.Nlignes, taille_elem, taille_matrice, nbOctetsGagnes, temp;
for(i=0; i<m1.Nlignes; i++) {
element *elem = m1.tableauLignes[i];
if (elem == NULL) //si la ligne ne contient que des 0
continue;
somme_elem--;
while(elem != NULL){
somme_elem++;
elem = elem->suivant;
}
}
taille_elem = somme_elem*sizeof(element);
taille_matrice = m1.Nlignes*m1.Ncolonnes*sizeof(int);
nbOctetsGagnes = taille_matrice-taille_elem;
return nbOctetsGagnes;
}
void freeMat(matrice_creuse *m)
{
int i, j;
element *pointeur,*tmp;
for (i=0; i<m->Nlignes;i++){
pointeur=m->tableauLignes[i];
if(m->tableauLignes[i]==NULL){
free(m->tableauLignes[i]);
printf("NULL colonne %d\n",j++);
}
else {
tmp=pointeur->suivant;
while (pointeur!=NULL){
pointeur=tmp->suivant;
free(tmp);
tmp=pointeur;
printf("%d\n",j++);
}
printf("Free colonne \n");
free(m->tableauLignes[i]);
}
}
}
|
Python
|
UTF-8
| 221
| 3.65625
| 4
|
[] |
no_license
|
x=int(input("Podaj rok z przedziału 1900 - 2099: "))
a=x%19
b=x%4
c=x%7
d=(a*19+24)%30
e=(2*b+4*c+6*d+5)%7
if d+e<10:
print("Wielkanoc jest", d+e+22, "marca")
else:
print("Wielkanoc jest", d+e-9, "kwietnia")
|
Python
|
UTF-8
| 912
| 2.8125
| 3
|
[
"Apache-2.0"
] |
permissive
|
class Feature(object):
def __init__(self, feature_id, features, aux):
self.feature_id = feature_id
self.features = features
self.aux = aux
def reprJSON(self):
return {
"feature_id": dict(self.feature_id._asdict()),
"features": self.features,
"aux": self.aux,
}
def reprSimpleJSON(self):
return {
"feature_id": dict(self.feature_id._asdict()),
"features": self.features,
"aux": dict()
}
@staticmethod
def fromJSON(d):
return Feature(d['feature_id'], d['features'], d['aux'])
def __eq__(self, other):
if type(other) is not type(self):
return False
return other.feature_id == self.feature_id
def __hash__(self):
return (self.feature_id).__hash__()
def drop_features(self):
self.features = None
|
Markdown
|
UTF-8
| 173
| 2.640625
| 3
|
[] |
no_license
|
# Advent of Code: 2020
My solutions to the [Advent of Code](https://adventofcode.com/2020).
They won't be super-optimised or anything; I just had fun solving the problems!
|
Java
|
UTF-8
| 2,150
| 3.359375
| 3
|
[] |
no_license
|
package client;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
import ItemProduct.ItemProduct;
public class ClientApp {
public static void main(String[] args) throws ClassNotFoundException {
System.out.println("ClientApp: Demo of Object Stream\n");
// Request data
//ItemProduct itemproduct = new ItemProduct();
//String item = input.nextLine();
//itemproduct.setName(item);
try {
//Scanner input = new Scanner(System.in);
ItemProduct itemproduct = new ItemProduct();
// Data to establish connection to server
int portNo = 4228;
InetAddress serverAddress = InetAddress.getLocalHost();
// Connect to the server at localhost, port 4228
Socket socket = new Socket(serverAddress, portNo);
//System.out.println("Please enter product name :- ");
//String item = input.nextLine();
itemproduct.setName("Gardenia White Bread");
// Open stream to send object
ObjectOutputStream objectOS = new ObjectOutputStream(socket.getOutputStream());
// Send request to server
System.out.println("Send object to server: " + itemproduct);
objectOS.writeObject(itemproduct);
objectOS.flush();
// Open stream to receive object
ObjectInputStream objectIS = new ObjectInputStream(socket.getInputStream());
// Get object from stream and display details
itemproduct = (ItemProduct) objectIS.readObject();
System.out.println ("\n ID | Product Name | Price") ;
System.out.println ("--------------------------------------------");
System.out.println ( " " + itemproduct.getItemProductId() + " " +
itemproduct.getName() + " RM" + itemproduct.getPrice());
// Close all closeable objects
objectOS.close();
objectIS.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("\nClientApp: End of application.\n");
}
}
|
Java
|
UTF-8
| 1,337
| 2.171875
| 2
|
[] |
no_license
|
2
https://raw.githubusercontent.com/gardle/gardle-web/master/src/main/java/com/gardle/domain/AbstractDeletableAuditingEntity.java
package com.gardle.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
import java.time.Instant;
/**
* For entities which will hold the general information of an AuditingEntity but also can be (soft) deleted
*/
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@Getter
@Setter
public abstract class AbstractDeletableAuditingEntity extends AbstractAuditingEntity implements Serializable {
// see https://docs.jboss.org/hibernate/search/5.10/reference/en-US/html_single/#field-annotation-indexNullAs
private static final String MAX_LONG_VALUE_FOR_NULL_PLACEHOLDER = "9223372036854775807";
private static final long serialVersionUID = 1L;
@JsonIgnore
@Column(name = "deleted")
@Field(indexNullAs = MAX_LONG_VALUE_FOR_NULL_PLACEHOLDER, analyze = Analyze.NO)
private Instant deleted = null;
}
|
Java
|
UTF-8
| 5,547
| 2.03125
| 2
|
[] |
no_license
|
package com.tencent.filechecker.logic;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.tencent.filechecker.entity.DetectConfig;
import java.util.ArrayList;
import java.util.List;
/**
* Created by haoozhou on 2016/5/16.
*/
public class FileDetectManager {
private static FileDetectManager instance = new FileDetectManager();
private FileDetectManager(){}
public static FileDetectManager getInstance(){
return instance;
}
public static final int ERR_MD5RESULT_COPY_FAILED = 1;
public static final int MSG_DETECT_STARTED = 1;
//public static final int MSG_COPY_OR_CHECK_FAILED = 2;
public static final int MSG_DETECT_PROGRESS = 3;
public static final int MSG_DETECT_COMPLETED = 5;
public static final int MSG_DETECT_CANCELED = 6;
public static final int MSG_DETECT_ERROR = 7;
private Handler mUIHandler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case MSG_DETECT_STARTED:
//mFileCount = msg.arg1;
//notifyDetectStarted(mFileCount);
notifyDetectStarted(msg.arg1);
break;
/*case MSG_COPY_OR_CHECK_FAILED:
mCurtProgress++;
notifyDetectProgressChanged(mCurtProgress, mFileCount);
notifyCopyOrCheckFailed((CheckDiff) msg.obj);
break;*/
case MSG_DETECT_PROGRESS:
notifyDetectProgressChanged(msg.arg1, msg.arg2);
break;
case MSG_DETECT_COMPLETED:
mFileDetectThread = null;
notifyDetectCompleted();
break;
case MSG_DETECT_ERROR:
int err = msg.arg1;
notifyDetectError(err);
break;
case MSG_DETECT_CANCELED:
notifyDetectCanceled();
break;
}
}
};
//private int mFileCount = 0;
//private int mCurtProgress = 0;
FileDetectThread mFileDetectThread;
public void startDetect(DetectConfig config){
if (mFileDetectThread != null){
//mFileDetectThread.cancel();
mFileDetectThread = null;
}
//mFileCount = -1;
//mCurtProgress = 0;
mFileDetectThread = new FileDetectThread(config, mUIHandler);
mFileDetectThread.start();
}
public void cancelCopy(){
if (mFileDetectThread != null){
//mFileDetectThread.cancel();
mFileDetectThread = null;
}
}
private List<FileDetectListener> mFileDetectListeners;
public synchronized void registerFileDetectListener(FileDetectListener listener){
if (mFileDetectListeners == null){
mFileDetectListeners = new ArrayList<>();
}
if (listener != null && !mFileDetectListeners.contains(listener)){
mFileDetectListeners.add(listener);
}
}
public synchronized void unregisterFileDetectListener(FileDetectListener listener){
if (mFileDetectListeners == null){
mFileDetectListeners = new ArrayList<>();
}
if (listener != null && mFileDetectListeners.contains(listener)){
mFileDetectListeners.remove(listener);
}
}
private synchronized void notifyDetectStarted(int fileCount){
if (mFileDetectListeners != null){
for (FileDetectListener listener : mFileDetectListeners){
listener.onDetectStarted(fileCount);
}
}
}
private synchronized void notifyDetectProgressChanged(int completed, int total){
if (mFileDetectListeners != null){
for (FileDetectListener listener : mFileDetectListeners){
listener.onDetectProgressChanged(completed, total);
}
}
}
/*private synchronized void notifyCopyOrCheckFailed(CheckDiff diff){
if (mFileDetectListeners != null){
for (FileDetectListener listener : mFileDetectListeners){
listener.onCopyOrCheckFailed(diff);
}
}
}*/
private synchronized void notifyDetectCompleted(){
if (mFileDetectListeners != null){
for (FileDetectListener listener : mFileDetectListeners){
listener.onDetectCompleted();
}
}
}
private synchronized void notifyDetectError(int err){
if (mFileDetectListeners != null){
for (FileDetectListener listener : mFileDetectListeners){
listener.onDetectError(err);
}
}
}
private synchronized void notifyDetectCanceled(){
if (mFileDetectListeners != null){
for (FileDetectListener listener : mFileDetectListeners){
listener.onDetectCanceled();
}
}
}
public interface FileDetectListener {
void onDetectStarted(int size);
void onDetectProgressChanged(int completed, int total);
/**
* 拷贝单个文件失败或校验单个文件失败
* @param diff
*/
//void onCopyOrCheckFailed(CheckDiff diff);
/**
* 拷贝任务失败
* @param err
*/
void onDetectError(int err);
void onDetectCompleted();
void onDetectCanceled();
}
}
|
Java
|
UTF-8
| 3,596
| 2.28125
| 2
|
[] |
no_license
|
package BookController;
import java.awt.Image;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import com.sun.jimi.core.Jimi;
import com.sun.jimi.core.JimiUtils;
import DAO.BookDAO;
import model.BookBean;
@WebServlet("/book/book_posting.do")
@MultipartConfig(
fileSizeThreshold=0,
location="C:\\JSP\\portfolio2\\WebContent\\bookUpload"
)
public class Book_posting extends HttpServlet {
private static final long serialVersionUID = 1L;
public Book_posting() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doAll(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doAll(request, response);
}
protected void doAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String title = request.getParameter("title");
String genre = request.getParameter("genre");
String subject = request.getParameter("subject");
String contents = request.getParameter("contents");
HttpSession session = request.getSession();
String session_name = (String)session.getAttribute("session_name");
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String signdate = sdf.format(date);
String img1="";
String thumImg="";
for(Part part:request.getParts())
{
Date today = new Date();
SimpleDateFormat timer = new SimpleDateFormat("yyyyMMddHHmmss");
String clock = timer.format(today);
if((part.getName().equals("img_1"))&&part.getSize()>0) {
String contentDisposition = part.getHeader("content-disposition");
String fileName = clock+"_"+getUploadFileName(contentDisposition);
part.write(fileName);
if(part.getName().equals("img_1")) {
img1 = fileName;
}
String filePath = "C:\\JSP\\portfolio2\\WebContent\\bookUpload\\";
String orgImg = filePath+img1;
thumImg = "thumb_"+img1;
String thumbImg = filePath+thumImg;
int thumWidth = 180;
int thumHeight = 180;
try {
Image thumbnail = JimiUtils.getThumbnail(orgImg, thumWidth, thumHeight, Jimi.IN_MEMORY);
Jimi.putImage(thumbnail, thumbImg);
}catch (Exception e) {
e.printStackTrace();
}
}
}
BookBean bean = new BookBean();
bean.setBook_title(title);
bean.setBook_genre(genre);
bean.setBook_subject(subject);
bean.setBook_contents(contents);
bean.setBook_writer(session_name);
bean.setBook_signdate(signdate);
bean.setBook_img1(img1);
bean.setBook_thumb(thumImg);
BookDAO dao = new BookDAO();
dao.book_posting(bean);
response.sendRedirect("/book/book_page.go?title="+title+"");
}
private String getUploadFileName(String contentDisposition) {
String uploadFileName = null;
String[] contentSplitStr = contentDisposition.split(";");
int firstQutosIndex = contentSplitStr[2].indexOf("\"");
int lastQutosIndex = contentSplitStr[2].lastIndexOf("\"");
uploadFileName=contentSplitStr[2].substring(firstQutosIndex+1,lastQutosIndex);
return uploadFileName;
}
}
|
Ruby
|
UTF-8
| 1,034
| 2.796875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# class MyValidator < ActiveModel::Validator
# #if a song with the same title and same year exists --> error message
# #if released = true and released_year == nil --> error message
# #if release_year > current_year --> error message
# #otherwise, error message << false
# def validate(record)
# if Song.all.detect {|song| song.title == record.title} && Song.all.detect {|song| song.release_year == record.release_year}
# record.errors[:title] << 'A song with this title for this year already exists'
# end
# if record.released == true && record.release_year == nil
# record.errors[:release_year] << 'Must include release year'
# end
# if record.release_year > Time.now.year
# record.errors[:release_year] << 'Release year cannot be in the future'
# end
# if record.errors[:title].empty? && record.errors[:release_year].empty?
# record.errors[:title] << false
# record.errors[:release_year] << false
# end
# end
# end
|
Java
|
UTF-8
| 384
| 2.03125
| 2
|
[] |
no_license
|
package com.ly.art.advice;
import org.springframework.util.StringUtils;
import java.beans.PropertyEditorSupport;
public class EmptyStrConverter extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (!StringUtils.hasText(text))
setValue(null);
else
setValue(text);
}
}
|
C#
|
UTF-8
| 1,739
| 2.5625
| 3
|
[] |
no_license
|
using System;
using System.Configuration;
using System.Net;
using System.Net.Mail;
namespace Negocio.Managers.Shared
{
public class EnvioEmailManager
{
private const string sender = "transporteflexible@gmail.com";
private const string senderPassword = "fleXI!123";
private readonly SmtpClient smtpClient = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(sender, senderPassword)
};
private void EnviarEmail(string to, string subject, string body)
{
try
{
MailMessage mm = new MailMessage();
mm.To.Add(to);
mm.From = new MailAddress(sender);
mm.Subject = subject;
mm.Body = body;
mm.IsBodyHtml = false;
mm.Priority = MailPriority.Normal;
smtpClient.Send(mm);
mm.Dispose();
}
catch (Exception e)
{
throw e;
}
}
public void EnviarEmailRegistro(string receiver, string idEncriptado)
{
try
{
string subject = "REGISTRO T-FLEX";
string body = "Hola bienvenido a T-FLEX, para poder activar tu usuario debes hacer click en el siguiente Link: "
+ ConfigurationManager.AppSettings["validarEmailLink"] + "?id=" + idEncriptado.Replace("+", "%2B");
EnviarEmail(receiver, subject, body);
}
catch (Exception e)
{
throw e;
}
}
}
}
|
C++
|
GB18030
| 1,908
| 2.96875
| 3
|
[] |
no_license
|
#include "MyIniBase.h"
#include <fstream>
#include <iostream>
std::tuple<bool, std::string> CIniBase::GetJsonStr(const std::string & strPath)
{
//ǸܴĶд洢ıļô
char buf[1024]; //ʱȡļ
//std::string str;
std::ifstream infile;
infile.open(strPath.c_str());
if (infile.is_open()) //ļɹ,˵д
{
std::string str((std::istreambuf_iterator<char>(infile)), (std::istreambuf_iterator<char>()));
infile.close();
return std::make_tuple(true, str);
}
else
{
std::cout << "error: find " << strPath << " fail." << std::endl;
std::cin.get();
return std::make_tuple(false, "");
}
}
bool CIniBase::SaveText(const std::string & str, const std::string & strPath)
{
//ǸܴĶд洢ıļô
std::ofstream outfile;
outfile.open(strPath.c_str(), std::ios::out/*|std::ios::app*/);
if (outfile.is_open()) //ļɹ,˵д
{
outfile << str;
outfile.close();
return true;
}
else
{
std::cout << "error:find " << strPath << " fail." << std::endl;
std::cin.get();
return false;
}
}
bool CIniBase::ParseDBinfo(CMyJson::JsonRoot & json, DatabaseInfo & dbinfo)
{
if (!(json.isNull()))
{
dbinfo.name = CMyJson::GetStrValue(json, "name");
dbinfo.host = CMyJson::GetStrValue(json, "host");
dbinfo.user = CMyJson::GetStrValue(json, "user");
dbinfo.password = CMyJson::GetStrValue(json, "password");
return true;
}
return false;
}
bool CIniBase::ReadText(const std::string & path, CallBack call)
{
std::tuple<bool, std::string> tup = GetJsonStr(path);
if (std::get<0>(tup))
{
return call(std::get<1>(tup));
}
else
{
return false;
}
}
|
Python
|
UTF-8
| 3,125
| 2.953125
| 3
|
[] |
no_license
|
"""suggestion_dialog.py."""
from src.dialog import Dialog
from src.picker import Picker
from src.card import Card
from src.cardtype import CardType
from src.suggestion import Suggestion
import pygame
import os
import json
class SuggestionDialog(Dialog):
def __init__(self, x, y):
super(SuggestionDialog, self).__init__(x, y)
# Initialize pickers
dir = os.path.dirname(__file__)
filename = os.path.join(dir, '../data/cards.json')
with open(filename) as data_file:
card_data = json.load(data_file)
# Build separate card decks
self._characters = []
self._weapons = []
self._rooms = []
for c in card_data['cards']:
if c['type'] == 'suspect':
card = Card(c['card_id'], CardType.SUSPECT)
self._characters.append(card)
elif c['type'] == 'weapon':
card = Card(c['card_id'], CardType.WEAPON)
self._weapons.append(card)
else:
card = Card(c['card_id'], CardType.ROOM)
self._rooms.append(card)
# Build pickers
self._character_picker = Picker(self._characters, 110 + self._coords[0], 45 + self._coords[1])
self._room_picker = Picker(self._rooms, 350 + self._coords[0], 45 + self._coords[1])
self._weapon_picker = Picker(self._weapons, 590 + self._coords[0], 45 + self._coords[1])
# Add pickers to view
self.add_view(self._character_picker)
self.add_view(self._room_picker)
self.add_view(self._weapon_picker)
def cancel(args):
sugg_dialog = args['d']
sugg_dialog.set_is_visible(False)
# self._top_button.set_on_click(confirm, {'d': self })
self._bottom_button.set_on_click(cancel, {'d': self })
# set background image
self._background_image = pygame.image.load('resources/suggestionselect.jpg')
# Override draw method to include background image
def draw(self, event, display):
if (self._is_visible):
display.blit(self._background_image, (self._coords[0], self._coords[1]))
super(SuggestionDialog, self).draw(event, display)
def set_is_visible(self, is_visible):
# If this is being set as visible, clear all selections
if is_visible:
self._character_picker.deselect_all_except(-1)
self._room_picker.deselect_all_except(-1)
self._weapon_picker.deselect_all_except(-1)
super(SuggestionDialog, self).set_is_visible(is_visible)
def get_suggestion(self):
room = self._room_picker.get_selected()
weapon = self._weapon_picker.get_selected()
character = self._character_picker.get_selected()
if room and character and weapon:
return Suggestion(room, weapon, character)
else:
return None
def set_room_id(self, room_card_id):
self._room_picker.enable_all()
for i, c in enumerate(self._rooms):
if c.get_id() != room_card_id:
self._room_picker.disable_button(i)
|
C++
|
WINDOWS-1250
| 1,723
| 3.53125
| 4
|
[] |
no_license
|
/*
Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of
the characters without disturbing the relative positions of the remaining characters.
(ie, ACE is a subsequence of ABCDE while AEC is not).
Here is an example:
S = rabbbit, T = rabbit
*/
class Solution {
public:
int numDistinct(string S, string T) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return FindNum(S,T);
}
private:
map<string ,map<string,int> > record;
int FindNum(string & s, string & t)
{
if(record.find(t) != record.end() && record[t].find(s) != record[t].end())
return record[t][s];
int ret = 0;
for( size_t i = 0 ; i < s.size();)
{
size_t pos ;
if(( pos = s.find(t[0],i)) != string::npos)
{
if(t.size() == 1)
ret += 1;
else
{
if(pos == s.size())
{
if(record.find(t) == record.end())
{
map<string,int> m;
m[s] = ret;
record[t] = m;
}
else
record[t][s]= ret;
return ret;
}
string s1= s.substr(pos+1);
string t1= t.substr(1);
ret += FindNum(s1,t1);
}
i = pos+1;
}
else
{
if(record.find(t) == record.end())
{
map<string,int> m;
m[s] = ret;
record[t] = m;
}
else
record[t][s]= ret;
return ret;
}
}
if(record.find(t) == record.end())
{
map<string,int> m;
m[s] = ret;
record[t] = m;
}
else
record[t][s]= ret;
return ret;
}
};
|
C#
|
UTF-8
| 1,002
| 2.921875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace PSRT.Astra
{
public static class ConcurrencyUtils
{
public static Task RunOnDedicatedThreadAsync(Action action, string threadName = null)
{
var source = new TaskCompletionSource<bool>();
var thread = new Thread(() =>
{
try
{
action();
source.SetResult(true);
}
catch (OperationCanceledException)
{
source.SetCanceled();
}
catch (Exception ex)
{
source.SetException(ex);
}
});
if (!string.IsNullOrWhiteSpace(threadName))
thread.Name = threadName;
thread.Start();
return source.Task;
}
}
}
|
Markdown
|
UTF-8
| 2,318
| 3.125
| 3
|
[] |
no_license
|
# ContactsRealmWebApp
Application to demonstrate how to use Realm Sync with a Web App to do basic operations (CRUD)
# Live Example
This is the live example of the Web application running
[](https://i.imgur.com/TSMRjOI.gif)
# Description
This application will list a table of contacts added to Mongo Realm and will synchronize the data with Realm Sync.
Operation allowed:
1. Log in with Email/Password or Google
2. Show list of contacts
3. Create a new contact
4. Update contact
5. Delete contact
## Dependencies & Prerequisites
This application is self-contained in a Docker container. You need to set several things in order to build and run this application.
### Mongo Realm & Docker
1. You need to add your Realm Id to `api.files/routes/app.js` file in order to be able to open a Realm with your Realm Cloud.
For this, this project uses the library `dotenv` to be able to load *secrets* to your application. This library is listed in the `package.json`.
2. To be able to use this project, you will need to create a `.env` file. You could use the `.env.template` as a template. You will need:
3. Change `.env` variables to match your working directory.
1. `CLIENT_PATH:` Is the directory where you've clone this project plus the folder `/api.files`.
2. `BACKEND_PATH:` Is the directory where you've clone this project.
3. `NGINX_APIX_LOGS:` Is the directory where you want to store the client logs file
4. `APP_ID` From your Realm Cloud App.
5. `CLIENT_ID` From your Google Credentials Project.
Example of a `.env` file:
```
# Application's path (absolute or relative)
CLIENT_PATH={{current-directory}}/api.files/
BACKEND_PATH={{current-directory}}
# Logs path
NGINX_APIX_LOGS={{current-directory}}/logs/nginx/
# Secrets
CLIENT_ID=
APP_ID=
```
### Packages needed
This project is based on NodeJS and Bootstrap. These are the libraries used in this project:
- npm
- express
- nodemon
- realm
- socket
- cors
- bson
All these libraries are in the `package.json`.
When executing a `docker-compose up --build -d` all the packages are automatically installed.
# Step by Step
Follow the link to the [Wiki](https://github.com/josmanperez/ContactsRealmWebApp/wiki) page for a step by step instruccionts on how to run this application.
|
Java
|
UTF-8
| 1,889
| 3.734375
| 4
|
[
"MIT"
] |
permissive
|
package basic.sort;
import java.util.Arrays;
/**
* 源数组,假设有n个数
* |_______|_______| 划分成n/2
* |___|___|___|___| 划分成n/4
* |_|_|_|_|_|_|_|_| 划分成n/8
* 直到划分成1个数
* 递归层数最多有log n
* 处理每一层都是O(N)
* 所以时间复杂度是O(N log n)
* 空间复杂度是O(N)
* 需要辅助数组
* 开始l,r指向两个区间的区间首
* 区间首元素较小者放进辅助数组,维护双指针之一
* 重复如上操作
* 直到有一个区间没有数了,直接把另一个还有数的区间放在辅助数组的后面
* 最后把排好序(未完全排好)的数组放回源数组
*/
public class mergeSort {
public static void main(String[] args) {
mergeSort(0, q.length - 1);
System.out.println(Arrays.toString(q));
}
static int[] q = {2, 4, 1, 5, 7, 2, 123, 12, 3, 1};
static int[] temp = new int[1000];
static void mergeSort(int l, int r) {
if (l == r) return;//如果只有1个数或者没有数,就不需要排序
int mid = l + r >> 1;
mergeSort(l, mid);//合并左半部分
mergeSort(mid + 1, r);//合并右半部分
//有一个辅助数组
//k代表源数组取到什么位置
//把排序后(不完全有序)的数组放进辅助数组
int k = 0, i = l, j = mid + 1;
while (i <= mid && j <= r) {
if (q[i] <= q[j]) {
temp[k++] = q[i++];
} else {
temp[k++] = q[j++];
}
}
//左半部分如果还有元素,有且只有一个还有元素
while (i <= mid) temp[k++] = q[i++];
//右半部分如果还有元素,有且只有一个还有元素
while (j <= r) temp[k++] = q[j++];
//放回原数组
for (i = l, j = 0; i <= r; i++, j++) {
q[i] = temp[j];
}
}
}
|
JavaScript
|
UTF-8
| 1,323
| 2.765625
| 3
|
[] |
no_license
|
import * as ACTIONS from '../actions/actionTypes';
const initState = {
profileImageError: null,
profileImageSent: null,
profileInfoError: null,
profileInfoSent: null
}
const profileReducer = (state = initState, action) => {
if(action.type === ACTIONS.UPDATE_PROIMG_SUCCESS) {
console.log('Image uploaded successfully!');
return {
...state,
profileImageError: null,
profileImageSent: true
}
}
else if(action.type === ACTIONS.UPDATE_PROIMG_ERR) {
console.log('Image upload failed!');
return {
...state,
profileImageError: action.payload,
profileImageSent: null
}
}
if(action.type === ACTIONS.UPDATE_INFO_SUCCESS) {
console.log('Info updated successfully!');
return {
...state,
profileInfoError: null,
profileInfoSent: true
}
}
else if(action.type === ACTIONS.UPDATE_INFO_ERR) {
console.log('Info update failed!');
return {
...state,
profileInfoError: action.payload,
profileInfoSent: null
}
}
else if(action.type === ACTIONS.PROFILE_NOTE_RESET) {
return {
...state,
profileImageError: null,
profileImageSent: null,
profileInfoSent: null,
profileInfoError: null
}
}
else {
return state;
}
}
export default profileReducer;
|
Java
|
UTF-8
| 287
| 2.28125
| 2
|
[] |
no_license
|
package com.swad.cppatm.exceptions;
public class AccountDoesNotExist extends Exception {
// Parameterless Constructor
public AccountDoesNotExist() {}
// Constructor that accepts a message
public AccountDoesNotExist(String message)
{
super(message);
}
}
|
JavaScript
|
UTF-8
| 365
| 3.09375
| 3
|
[] |
no_license
|
let post = {
name: "Kamala Harris",
title: "Vice President",
likes:85000000,
message: "First Female, Black, Asian American Vice President of the United States of America",
AddLike:function(){
this.likes+=1;
}
}
post.message = "Congratulations!"
console.log(post.name)
console.log(post.likes)
post.AddLike()
console.log(post.likes)
|
C++
|
UTF-8
| 1,897
| 2.890625
| 3
|
[] |
no_license
|
#ifndef __TC_CALLBACK_DETAIL_H__
#define __TC_CALLBACK_DETAIL_H__
#include "tc_scoped_ptr.h"
namespace taf
{
namespace detail
{
class TC_BindStateBase {
public:
virtual ~TC_BindStateBase() { }
};
// This is a typetraits object that's used to take an argument type, and
// extract a suitable type for storing and forwarding arguments.
template <typename T>
struct TC_CallbackParamTraits {
typedef const T& ForwardType;
typedef T StorageType;
};
template <typename T>
struct TC_CallbackParamTraits<T&> {
typedef T& ForwardType;
typedef T StorageType;
};
template <typename T>
struct TC_CallbackParamTraits<const T&> {
typedef const T& ForwardType;
typedef T StorageType;
};
// Note that for array types, we implicitly add a const in the conversion. This
// means that it is not possible to bind array arguments to functions that take
// a non-const pointer. Trying to specialize the template based on a "const
// T[n]" does not seem to match correctly, so we are stuck with this
// restriction.
template <typename T>
struct TC_CallbackParamTraits<T[]> {
typedef const T* ForwardType;
typedef const T* StorageType;
};
template <typename T, size_t n>
struct TC_CallbackParamTraits<T[n]> {
typedef const T* ForwardType;
typedef const T* StorageType;
};
// Parameter traits for movable-but-not-copyable scopers.
template <typename T>
struct TC_CallbackParamTraits<TC_ScopedPtr<T> > {
typedef TC_ScopedPtr<T> ForwardType;
typedef TC_ScopedPtr<T> StorageType;
};
} // namespace detail
}
#endif
|
TypeScript
|
UTF-8
| 8,695
| 3
| 3
|
[
"MIT"
] |
permissive
|
import type { TransitionType } from '../../transition';
declare type Value = {
name?: any;
value?: string;
selected?: boolean;
};
export interface DropdownSettings {
/** When specified allows you to initialize dropdown with specific values. See usage guide for details. */
values?: Value[];
/** Event used to trigger dropdown (Hover, Click, Custom Event) */
on?: boolean;
/** Whether the dropdown value can be cleared by the user after being selected. */
clearable?: boolean;
/** Whether values with non matching cases should be treated as identical when adding them to a dropdown. */
ignoreCase?: boolean;
/** Whether values with non matching cases should be treated as identical when filtering the items. */
ignoreSearchCase?: boolean;
/** When set to true will fire onChange even when the value a user select matches the currently selected value. */
allowReselection?: boolean;
/** Whether search selection should allow users to add their own selections, works for single or multiselect. */
allowAdditions?: boolean;
/** If disabled user additions will appear in the dropdown's menu using a specially formatted selection item formatted by templates.addition. */
hideAdditions?: boolean;
/**
* Sets a default action to occur. (See usage guide) .
* activate (default) Updates dropdown text with selected value, sets element state to active, updates any hidden fields if available.
* select activates menu and updates input fields, but does not change current text.
* combo changes text of previous sibling element.
* nothing no action occurs.
* hide Dropdown menu is hidden.
* function(text, value, element){} custom function is executed with values specified in callback
**/
action?: 'activate' | 'select' | 'combo' | 'nothing' | 'hide' | ((text: string, value: any, element: HTMLElement) => void);
/** The minimum characters for a search to begin showing results */
minCharacters?: number;
/** When using search selection specifies how to match values.
* both Matches against text and value
* value matches against value only
* text matches against text only */
match?: 'both' | 'value' | 'text';
/** Whether dropdown should select new option when using keyboard shortcuts. Setting to false will require enter or left click to confirm a choice. */
selectOnKeydown?: boolean;
/** Whether search selection will force currently selected choice when element is blurred. */
forceSelection?: boolean;
/** Whether menu items with sub-menus (categories) should be selectable */
allowCategorySelection?: boolean;
/**
* auto Convert option with "" (blank string) value to placeholder text
* value Sets string value to placeholder text, leaves "" value
* false Leaves "" value as a selectable option
**/
placeholder?: 'auto' | 'value' | false;
/** When activated, searches will also match results for base diacritic letters. For example when searching for 'a', it will also match 'á' or 'â' or 'å' and so on... It will also ignore diacritics for the searchterm, so if searching for 'ó', it will match 'ó', but also 'o', 'ô' or 'õ' and so on... */
ignoreDiacritics?: boolean;
/** Can be set to an object to specify API settings for retrieving remote selection menu content from an API endpoint */
apiSettings?: boolean;
/** List mapping dropdown content to JSON Property when using API */
fields?: {};
/** Whether results returned from API should be filtered by query before being displayed */
filterRemoteData?: boolean;
/** When enabled, will automatically store selected name/value pairs in sessionStorage to preserve user selection on page refresh. Disabling will clear remote dropdown values on refresh. */
saveRemoteData?: boolean;
/** Whether multiselect should use labels. Must be set to true when allowAdditions is true */
useLabels?: boolean;
/** When set to a number, sets the maximum number of selections */
maxSelections?: boolean;
/** Maximum glyph width, used to calculate search size. This is usually size of a "W" in your font in em */
glyphWidth?: number;
/** Allows customization of multi-select labels */
label?: {
tansition?: TransitionType;
duration?: number;
variation?: boolean;
};
/** When set to auto determines direction based on whether dropdown can fit on screen. Set to upward or downward to always force a direction. */
direction?: 'auto' | 'upward' | 'downward';
/** Whether dropdown should try to keep itself on screen by checking whether menus display position in its context (Default context is page). */
keepOnScreen?: boolean;
/** Element context to use when checking whether can show when keepOnScreen: true */
context?: HTMLElement | Window | string;
/** Specifying to "true" will use a fuzzy full text search, setting to "exact" will force the exact search to be matched somewhere in the string, setting to "false" will only match start of string. */
fullTextSearch?: boolean;
/**
* How to handle dividers in the dropdown while searching. Dividers are defined as all siblings of items that match the divider selector
* false Dividers are not hidden
* true All dividers are automatically hidden
* empty All dividers not followed by a visible item are hidden (divider siblings are treated as a group)
**/
hideDividers?: boolean | 'empty';
/** Whether HTML included in dropdown values should be preserved. (Allows icons to show up in selected value) */
preserveHTML?: boolean;
/**
* Whether to sort values when creating a dropdown automatically from a select element.
* true Sort by name [A, B, C, a, b, c]
* natural Sort by lowercase name [A, a, B, b, C, c]
* function(a, b){} custom sort function is executed
*/
sortSelect?: boolean;
/** Whether to show dropdown menu automatically on element focus. */
showOnFocus?: boolean;
/** Whether to allow the element to be navigable by keyboard, by automatically creating a tabindex */
allowTab?: boolean;
/** Named transition to use when animating menu in and out. Defaults to slide down or slide up depending on dropdown direction. Fade and slide down are available without including ui transitions */
transition?: TransitionType;
/** Duration of animation events */
duration?: number;
/** The keycode used to represent keyboard shortcuts. To avoid issues with some foreign languages, you can pass false for comma delimiter's value */
keys?: {
backspace?: number | false;
delimiter?: number | false;
deleteKey?: number | false;
enter?: number | false;
escape?: number | false;
pageUp?: number | false;
pageDown?: number | false;
leftArrow?: number | false;
upArrow?: number | false;
rightArrow?: number | false;
downArrow?: number | false;
};
/** Time in milliseconds to debounce show or hide behavior when on: hover is used, or when touch is used. */
delay?: {
hide?: number;
show?: number;
search?: number;
touch?: number;
};
/** Is called after a dropdown value changes. Receives the name and value of selection and the active menu element */
onChange?: (value: any, text: any, $choice: any) => void;
/** Is called after a dropdown selection is added using a multiple select dropdown, only receives the added value */
onAdd?: (addedValue: any, addedText: any, $addedChoice: any) => void;
/** Is called after a dropdown selection is removed using a multiple select dropdown, only receives the removed value */
onRemove?: (removedValue: any, removedText: any, $removedChoice: any) => void;
/** Allows you to modify a label before it is added. Expects the jQ DOM element for a label to be returned. */
onLabelCreate?: (value: any, text: any) => any;
/** Called when a label is remove, return false; will prevent the label from being removed. */
onLabelRemove?: (value: any) => boolean;
/** Is called after a label is selected by a user */
onLabelSelect?: ($selectedLabels: any) => void;
/** Is called after a dropdown is searched with no matching values */
onNoResults?: (searchValue: any) => void;
/** Is called before a dropdown is shown. If false is returned, dropdown will not be shown. */
onShow?: () => boolean;
/** Is called before a dropdown is hidden. If false is returned, dropdown will not be hidden. */
onHide?: () => boolean;
}
export {};
|
Markdown
|
UTF-8
| 3,324
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
---
layout: page
title: "现实"
subtitle: "现实总有人给你上一课"
date: 2016-05-20 21:21:21 +0530
categories: 随笔
---
现实告诉你,没钱连你最亲的人都会瞧不起你。
不要以为你放不下的人同样也会放不下你。
鱼没有了水会死,水没有了鱼却会更清澈。
生活告诉你,有什么别有病。
感情告诉你,不要以为你想的人同样也会想你。
别人睡觉的时候要懂得安静。
不要没经过同意就随便看别人手机,别人拿手机给你看照片的时候,你好好看着就行,不要手贱划下一张。
不要试着用自己的秘密去交换一个朋友,别把秘密告诉风,风会吹过整片森林。
所谓的人生就是听不完的谎言,看不透的人心,尽力不完的酸甜苦辣。
你行的时候怎么都行,你不行的时候什么都不行,所以你一定要行,不行也得行。
稍微一亲近就口无遮拦的毛病必须改,多吧“你听懂了没”换成“我讲明白了没”。
和谁都别熟的太快,不要以为刚开始话题一致,共同点很多,你们就是相见恨晚的知音。语言很多时候都是假的,一起经历的才是真的。
我见过纹身大汉在公交车上让座,我也见过穿西服打领带的禽兽拿着公款大吃大喝,这个时代穿的靓丽帅气的不一定就是绅士。打扮的非常暴露的不一定就是婊子,不要以貌取人。
千万不要去认识你女友的闺蜜,因为她闺蜜不喜欢你,你们会分手,她闺蜜喜欢你,你们还是会分手。
人前不应该说的话,背后也别说。用“谢谢你”代替“谢谢”,虽然只是多了一个字,但是诚恳很多很多。
有两种人值得信任,二话不说借你钱的人,信守承诺还你钱的人。
交浅别言深,情深别刻薄。逢人只说三分话,不可全抛一片心。大多数人口中的“怎么了”,只是满足好奇心,并没有要帮助你的意思。在拒绝这件事上,越简单越好,明明是别人需求自己帮忙,解释半天变成自己亏欠别人的感觉,帮得上想帮就帮,帮不上就拒绝,人际交往,简单明了有时最恰当,懂得拒绝,才可以洒脱不纠结。
去别人家做客,别人让你看电视的时候,你就该走了。面试时,老板脚一直抖的话,说明对你说的话不感兴趣。一旦停下抖动的腿,说明你说的他感兴趣了。你在和别人交谈的时,别人一旦深呼吸,那就表示他不想听正在强压下自己对你的态度。
不熟的人别乱开玩笑,熟的人也是。别对朋友说狠话,恶语最伤人。请对待服务行业的人员态度好点,在愤怒时忍住最伤对方的那句话,不说狠话,不做软事,别人可以自嘲,但是你千万不能附和。大多数人都不喜欢心直口快,目光放远一点,你就不伤心了。别有事没事跟别人诉苦,这世上能感同身受的人很少,大部分人听听也就烦了,还有少部分人会当做笑柄到处去宣传。
永远不要对一个人的努力嗤之以鼻。三人行,一人系鞋带,你俩等他一下。
不要为了人际关系,逼着自己做好人,要做一个经常做好事的坏人,而不是一个不能做坏事的好人。
|
Markdown
|
UTF-8
| 1,137
| 2.765625
| 3
|
[] |
no_license
|
## 09b_glfw
## Synopsis
09b_glfw is an application to demonstrate use of GLFW and OpenGL.
It opens a window and animates a number of rotating pyramids.
## Motivation
This project was written from the ground up to understand the
operation of GLFW 3 and OpenGL 2, and to design an object-oriented
methodology for OpenGL programming. There are a number of other programs
that were written in that process, hence the funny program name. OpenGL2 was
an easy entry into graphics programming but is deprecated, and this code
will eventually be ported to WebGL.
## Installation
You may need to install libglfw3, g++, or other dependencies to get it to build
if your machine is particularly vanilla. Welcome to Linux.
Copy the code, go into the code directory, and type
make
on the command line. The executable will be in the current directory.
## Running
Type
./09b_glfw
on the command line to execute the program.
## Sample
To see a short video of the program in operation, open `./video/09b_glfw_video.mp4`
## Contributors
This code does not need maintaining at this time.
## License
(C) 2016 Blair Houghton
All rights reserved.
|
Java
|
UTF-8
| 2,390
| 2.921875
| 3
|
[] |
no_license
|
package hr.fer.zemris.java.fractals;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import hr.fer.zemris.java.fractals.viewer.IFractalProducer;
import hr.fer.zemris.java.fractals.viewer.IFractalResultObserver;
import hr.fer.zemris.math.ComplexRootedPolynomial;
/**
* Implementation of the IFractalProducer interface
*
* @author Rafael Josip Penić
*
*/
public class IFractalProducerImpl implements IFractalProducer {
/**
* Pool of threads used for thread synchronization.
*/
private static ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(),
new DaemonThreadFactory());
private static final int NUMBER_OF_ITERATIONS = 16 * 16 * 16;
private static final int NUMBER_OF_LANES = 8;
/**
* Polynomial that determines which fractal will be drawn
*/
private ComplexRootedPolynomial poly;
/**
* Constructor for IFractalProducer objects
*
* @param poly
* polynomial that will be used for drawing a fractal
*/
public IFractalProducerImpl(ComplexRootedPolynomial poly) {
this.poly = poly;
}
@Override
public void produce(double reMin, double reMax, double imMin, double imMax, int width, int height, long requestNo,
IFractalResultObserver observer) {
int m = NUMBER_OF_ITERATIONS;
short[] data = new short[width * height];
final int lanes = NUMBER_OF_LANES * Runtime.getRuntime().availableProcessors();
int numberOfYPerLane = height / lanes;
List<Future<Void>> results = new ArrayList<>();
for (int i = 0; i < lanes; i++) {
int yMin = i * numberOfYPerLane;
int yMax = (i + 1) * numberOfYPerLane - 1;
if (i == lanes - 1) {
yMax = height - 1;
}
CalculatingProcess work = new CalculatingProcess(reMin, reMax, imMin, imMax, width, height, yMin, yMax, m,
data, poly);
results.add(pool.submit(work));
}
for (Future<Void> tempWork : results) {
try {
tempWork.get();
} catch (InterruptedException | ExecutionException ex) {
throw new RuntimeException("Error while waiting for the result.");
}
}
observer.acceptResult(data, (short) (poly.toComplexPolynom().order() + 1), requestNo);
}
}
|
Java
|
UTF-8
| 1,126
| 2.453125
| 2
|
[] |
no_license
|
package avaliacao3bimestre;
import java.util.ArrayList;
public abstract class Candidato {
protected String nome;
protected String email;
protected String dataNascimento;
protected String codigo;
public Candidato() {
}
public Candidato(String nome, String email, String dataNascimento, String codigo) {
this.nome = nome;
this.email = email;
this.dataNascimento = dataNascimento;
this.codigo = codigo;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(String dataNascimento) {
this.dataNascimento = dataNascimento;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
Java
|
UTF-8
| 691
| 1.726563
| 2
|
[] |
no_license
|
package ro.cosu.vampires.client.executors.fork;
import com.google.inject.Inject;
import org.hyperic.sigar.Sigar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ro.cosu.vampires.client.executors.ExecutorMetricsCollector;
import ro.cosu.vampires.server.workload.Metrics;
public class ForkExecutorMetricsCollector implements ExecutorMetricsCollector{
static final Logger LOG = LoggerFactory.getLogger(ForkExecutorMetricsCollector.class);
@Inject
Sigar sigar;
@Override
public void startMonitoring(String id) {
}
@Override
public void stopMonitoring() {
}
@Override
public Metrics getMetrics() {
return null;
}
}
|
C#
|
UTF-8
| 7,724
| 2.578125
| 3
|
[] |
no_license
|
using System;
using System.Data.SqlClient;
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 Eventos
{
public partial class AgregarEmpleado : Form
{
Empleado empleado;
Direccion dir;
public AgregarEmpleado()
{
InitializeComponent();
empleado = new Empleado();
dir = new Direccion();
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void button1Guardar_Click(object sender, EventArgs e)
{
//obtengo el genero seleccionado en la pantalla
char genero = ' ';
//El control radiobutton tiene la propiedad Checked en true si este se encuentra seleccionado
if (radioButton1F.Checked)
{
genero = 'F';
}
else if (radioButton2M.Checked)
{
genero = 'M';
}
/*Mediante el objeto de tipo Estudiante podemos agregar un nuevo estudiante con el método agregarEstudiante, el cual recibe por parámetro todos los valores de la tabla Estudiante*/
int resultado = 1;
if (textBoxCed.Text == "")
{
MessageBox.Show("Agrege numero de cedula ");
}
else
{
string idempleado = empleado.obtenerNuevoId();
resultado = empleado.agregarEmpleado(textBoxCed.Text, textBoxNom.Text, textBoxApe1.Text, textBoxApe2.Text, textBoxCorreo.Text, dateTimePicker1FecNac.Value.ToString("yyyy-MM-dd"), genero, idempleado, textBoxEncargado.Text, textBoxSucursal.Text, textBoxTel.Text);
}
if (comboBoxPais.Text != "Seleccione" && comboBoxPro.Text != "Seleccione" && comboBoxCan.Text != "Seleccione")
{
string tipo = "casa";
string codPais = dir.obtenerCodPais(comboBoxPais.Text);
string codProvincia = dir.obtenerCodProvincia(comboBoxPro.Text);
string codCanton = dir.obtenerCodCanton(comboBoxCan.Text);
int resultadodir = dir.agregarDireccion(textBoxCed.Text, tipo, codPais, codProvincia, codCanton, textBoxDesc.Text);
}
//Si la inserción devuelve un 0 la inserción fue exitosa, por lo que se muestra un mensaje de éxito
if (resultado == 0)
{
MessageBox.Show("El empleado ha sido agregado exitosamente", "Resultados", MessageBoxButtons.OK, MessageBoxIcon.None);
//Se limpian las cajas de texto para permitir al usuario añadir un nuevo estudiante cuando lo desee
textBoxNom.Clear();
textBoxApe1.Clear();
textBoxApe2.Clear();
textBoxCorreo.Clear();
textBoxCed.Clear();
textBoxTel.Clear();
textBoxSucursal.Clear();
textBoxSucursal.Clear();
textBoxEncargado.Clear();
} //si la inserción devuelve un código de error se puede validar con un mensaje de error personalizado
else if (resultado == 2627)
{
MessageBox.Show("Ya existe un cliente asociado a este numero de cedula en el sistema", "Resultados", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void label12_Click(object sender, EventArgs e)
{
}
private void llenarComboboxPais(ComboBox combobox)
{ //Se obtiene un dataReader con todos los nombres de los empleados de la base de datos
SqlDataReader datos = dir.obtenerPaises();
/*Si existen datos en la base de datos se carga como primer elemento del combobox un dato "Seleccione" y luego se cargan todos los datos de la base de datos*/
if (datos != null)
{
combobox.Items.Add("Seleccione");
while (datos.Read())
{
combobox.Items.Add(datos.GetValue(0));
}
} /*Si no hay tuplas en la base de datos se limpia el combobox y se carga unicamente el valor "Seleccione"*/
else
{
combobox.Items.Clear();
combobox.Items.Add("Seleccione");
}
combobox.SelectedIndex = 0;
}
private void llenarComboboxProvincia(ComboBox combobox)
{ //Se obtiene un dataReader con todos los nombres de los empleados de la base de datos
SqlDataReader datos = dir.obtenerProvincias();
/*Si existen datos en la base de datos se carga como primer elemento del combobox un dato "Seleccione" y luego se cargan todos los datos de la base de datos*/
if (datos != null)
{
combobox.Items.Add("Seleccione");
while (datos.Read())
{
combobox.Items.Add(datos.GetValue(0));
}
} /*Si no hay tuplas en la base de datos se limpia el combobox y se carga unicamente el valor "Seleccione"*/
else
{
combobox.Items.Clear();
combobox.Items.Add("Seleccione");
}
combobox.SelectedIndex = 0;
}
private void llenarComboboxCantones(ComboBox combobox)
{
SqlDataReader datos = dir.obtenerCantones();
if(comboBoxPro.Text !=null && comboBoxPro.Text != "Seleccione")
{
string codProvincia = dir.obtenerCodProvincia(comboBoxPro.Text);
datos = dir.obtenerCantonesP(codProvincia);
}
/*Si existen datos en la base de datos se carga como primer elemento del combobox un dato "Seleccione" y luego se cargan todos los datos de la base de datos*/
if (datos != null)
{
combobox.Items.Add("Seleccione");
while (datos.Read())
{
combobox.Items.Add(datos.GetValue(0));
}
} /*Si no hay tuplas en la base de datos se limpia el combobox y se carga unicamente el valor "Seleccione"*/
else
{
combobox.Items.Clear();
combobox.Items.Add("Seleccione");
}
combobox.SelectedIndex = 0;
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Menu ag = new Menu();
ag.Show();
this.Hide();
}
private void AgregarEmpleado_Load(object sender, EventArgs e)
{
llenarComboboxPais(comboBoxPais);
llenarComboboxProvincia(comboBoxPro);
llenarComboboxCantones(comboBoxCan);
}
private void button1_Click(object sender, EventArgs e)
{
Menu m = new Menu();
m.Show();
this.Hide();
}
private void AgregarEmpleado_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
private void comboBoxPro_SelectedIndexChanged(object sender, EventArgs e)
{
llenarComboboxCantones(comboBoxCan);
}
}
}
|
Python
|
UTF-8
| 3,242
| 2.5625
| 3
|
[] |
no_license
|
from itertools import combinations, chain
import shutil
from django.conf import settings
from django.core.management.base import BaseCommand
from os.path import join, isfile, exists
from random import randint
from stonedb.models import Texture, Color, Classification, Country, Stone
"""
Find one stone picture for each possible search option combination and copy it
to "stoneimages/country-texture-color-classifiction.jpg", for example
- stoneimages/canada-medium-grained-grey-anorthosite.jpg
- stoneimages/veined-green-marble.jpg
- stoneimages/brail-blue.jpg
- stoneimages/coarse-grained-granite.jpg
- stoneimages/grey-limestone.jpg
etc.
"""
sd = 'stonedb/stonesimages'
src_dir = join(settings.BASE_DIR, sd, 'stonespics')
trg_dir = join(settings.BASE_DIR, sd, 'stonesbrowse')
order = ['country', 'texture', 'color', 'classification']
def copy_stone_pic(stone, kv):
kvd = dict(kv)
src_fn = stone.get_pic_fname()
trg_fn = '{}.jpg'.format('-'.join([kvd[x] for x in order if x in kvd]))
# print('{} --> {}'.format(src_fn, trg_fn))
src = join(src_dir, src_fn)
trg = join(trg_dir, trg_fn)
# Do not overwrite existing!
if exists(trg):
print('o', end='', flush=True)
return True
try:
shutil.copy(src, trg)
print('.', end='', flush=True)
return True
except FileNotFoundError:
print('E', end='', flush=True)
return False
def get_random_stone(stones_qs):
count = stones_qs.count()
if count < 1:
return None
stone = None
for i in range(5):
idx = randint(0, count - 1)
stone = stones_qs[idx]
fn = stone.get_pic_fname()
src = join(src_dir, fn)
if isfile(src):
break
return stone
def make_props(props, stones_qs=None, stones_kv=None):
if stones_qs is None and stones_kv is None:
stones_qs = Stone.objects.all()
stones_kv = []
my_props = props.copy()
keyname, qs = my_props.popitem()
for item in qs:
this_qs = stones_qs.filter(**{keyname: item})
this_kv = stones_kv + [(keyname, item.slug)]
if len(my_props) > 0:
make_props(my_props, this_qs, this_kv)
else:
stone = get_random_stone(this_qs)
if stone:
copy_stone_pic(stone, this_kv)
class Command(BaseCommand):
args = ""
help = ('Copy one stone picture for each possible search option combination'
' to "stoneimages/country-texture-color-classifiction.jpg".')
def handle(self, *args, **options):
prop_dict = {
'classification': Classification.objects.all(),
'color': Color.objects.all(),
'country': Country.objects.all(),
'texture': Texture.objects.all(),
}
# Create all unique combinations of `prop_dict` keys.
prop_keys = list(chain.from_iterable(
[list(combinations(prop_dict, n+1)) for n in range(4)]))
# Fetch a sample stone for each unique combination of stone properties.
for prop_key in prop_keys:
prop_qss = {k: prop_dict[k] for k in prop_key}
print('--> {}'.format(prop_qss.keys()))
make_props(prop_qss)
|
C#
|
UTF-8
| 1,345
| 2.71875
| 3
|
[
"MIT",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
using System.Collections.Generic;
namespace Smellyriver.TankInspector.Pro.Data.Entities
{
public sealed class TankClassComparer : IComparer<string>, IComparer<TankClass>
{
private static readonly Dictionary<string, int> s_classKeySortIndices
= new Dictionary<string, int>
{
{TankClassHelper.ObserverClassKey, 0},
{TankClassHelper.LightTankClassKey, 1},
{TankClassHelper.MediumTankClassKey, 2},
{TankClassHelper.HeavyTankClassKey, 3},
{TankClassHelper.ATSPGClassKey, 4},
{TankClassHelper.SPGClassKey, 5},
};
private const int c_unknownValue = 6;
public static int GetClassSortIndex(string classKey)
{
int value;
return s_classKeySortIndices.TryGetValue(classKey, out value) ? value : c_unknownValue;
}
public int Compare(string x, string y)
{
var xValue = TankClassComparer.GetClassSortIndex(x);
var yValue = TankClassComparer.GetClassSortIndex(y);
if (xValue == yValue)
return string.Compare(x, y);
return xValue - yValue;
}
public int Compare(TankClass x, TankClass y)
{
return (int)x - (int)y;
}
}
}
|
Java
|
UTF-8
| 522
| 2.28125
| 2
|
[] |
no_license
|
package kg.online.book.store.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "delivery_method")
public class DeliveryMethod extends BaseEntity{
@Column(name = "delivery_name", nullable = false)
private String deliveryName;
@Column(name = "delivery_cost")
private Integer deliveryCost;
}
|
Python
|
UTF-8
| 1,314
| 3.203125
| 3
|
[] |
no_license
|
from math import gamma
import math
import matplotlib.pyplot as plt
from modules.pairwisecoverage import area
# Function that computes the expected distance to the nth furthest point sampled unifomly over cirle of radius R
def expectiation(n,N,R):
return R*(gamma(n + 1/2)/gamma(n))/(gamma(N+1+1/2)/gamma(N+1))
def compute_weight(d,a,b):
return area({"x":0,"y":0,"r":math.sqrt(a/math.pi)},{"x":d,"y":0,"r":math.sqrt(b/math.pi)})/a
a = 400 # area of smaller disk
b = 500 # area of largest disk
N = 16 # number of agents
R = 50 # Radius being unifomly sampled over
weight_sum = 0
max_weight = compute_weight(expectiation(1,N,R),a,b) #Expected Weight of closest element
weights = []
# Loop over the rest of the selected elements from closest to furthest and then compute there sum
for i in range(2,N):
weights.append(compute_weight(expectiation(i,N,R),a,b))
weight_sum += weights[-1]
epsilion = weight_sum/(1-max_weight) #calcualate the ratio between the closest and the rest of the sum
print("weight sum: ",weight_sum)
print("max_weight",max_weight)
print("must be less than ",1-max_weight)
print("eps",epsilion)
gamma = epsilion/(1-epsilion) #compute Gamma
print("1+Gamma",1+gamma)
l = [w for w in weights if w >0] # compute the neighbor hood
print("size of L:",len(l))
#plt.show()
|
PHP
|
UTF-8
| 3,968
| 2.640625
| 3
|
[] |
no_license
|
<?php
require __DIR__ . '/__cred.php';
require __DIR__. '/__connect_db.php';
header('Content-Type: application/json');
$result = [
'success' => false,
'errorCode' => 0,
'errorMsg' => '資料輸入不完整',
'post' => [], // 做 echo 檢查
];
$mNo = isset($_POST['mNo']) ? intval($_POST['mNo']) : 0;
if(isset($_POST['mName']) and !empty($mNo)){ //name本身勢必填欄位 在此看它有沒有被設定過
//轉換以後,mNo不能是0
$mName = $_POST['mName'];
$mAccount = $_POST['mAccount'];
$mPwd = $_POST['mPwd'];
$mPhone = $_POST['mPhone'];
$mPhoto = $_POST['mPhoto'];
$mEmail = $_POST['mEmail'];
$mAddress = $_POST['mAddress'];
$mBirthday = $_POST['mBirthday'];
$mId = $_POST['mId'];
$mGender = $_POST['mGender'];
$result['post'] = $_POST; // 做 echo 檢查
if(empty($mName) or empty($mAccount) or empty($mPwd)){
$result['errorCode'] = 400;
echo json_encode($result, JSON_UNESCAPED_UNICODE);
exit;
}
// TODO: 檢查 name 長度
// 檢查 email 格式
if(! filter_var($mEmail, FILTER_VALIDATE_EMAIL)){
$result['errorCode'] = 405;
$result['errorMsg'] = 'Email 格式不正確';
echo json_encode($result, JSON_UNESCAPED_UNICODE);
exit;
}
// TODO: 檢查 mobile 格式
// 1. 修改資料之前可以先確認該筆資料是否存在
// 2. Email 有沒有跟別筆的資料相同
$s_sql = "SELECT * FROM `lessee` WHERE `mNo`=? OR `mAccount`=?"; //在此用欲修改的email去做檢查
//如果出現兩筆,表示有重複的email
$s_stmt = $pdo->prepare($s_sql);
$s_stmt->execute([$mNo, $_POST['mAccount']]); //放兩個值 一個是mNo 一個是傳進來的mEmail
switch($s_stmt->rowCount()){
case 0:
$result['errorCode'] = 410;
$result['errorMsg'] = '該筆資料不存在';
echo json_encode($result, JSON_UNESCAPED_UNICODE);
exit;
//break;
case 2:
$result['errorCode'] = 420;
$result['errorMsg'] = '帳號已存在';
echo json_encode($result, JSON_UNESCAPED_UNICODE);
exit;
case 1:
$row = $s_stmt->fetch(PDO::FETCH_ASSOC);
if($row['mNo']!=$mNo){ //檢查現在拿到的mNo跟資料庫的mNo是不是一樣
$result['errorCode'] = 430;
$result['errorMsg'] = '該筆資料不存在';
echo json_encode($result, JSON_UNESCAPED_UNICODE);
exit;
}
}
$sql = "UPDATE `lessee` SET
`mName`=?,
`mAccount`=?,
`mPwd`=?,
`mPhone`=?,
`mPhoto`=?,
`mEmail`=?,
`mAddress`=?,
`mBirthday`=?,
`mId`=?,
`mGender`=?
WHERE `mNo`=?";
try {
$stmt = $pdo->prepare($sql);
$stmt->execute([
$_POST['mName'],
$_POST['mAccount'],
$_POST['mPwd'],
$_POST['mPhone'],
$_POST['mPhoto'],
$_POST['mEmail'],
$_POST['mAddress'],
$_POST['mBirthday'],
$_POST['mId'],
$_POST['mGender'],
$mNo
]);
if($stmt->rowCount()==1) { //rowCount() 是有修改的資料筆數 有可能是1或0
$result['success'] = true;
$result['errorCode'] = 200;
$result['errorMsg'] = '';
} else {
$result['errorCode'] = 402;
$result['errorMsg'] = '資料沒有修改';
}
} catch(PDOException $ex){
$result['errorCode'] = 403;
$result['errorMsg'] = '資料更新發生錯誤';
}
}
echo json_encode($result, JSON_UNESCAPED_UNICODE);
|
Java
|
UTF-8
| 343
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
package algo.tzashinorpu.SecondRound.Chapter12;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class maxProfit_309Test {
@Test
void maxProfit() {
maxProfit_309 ins = new maxProfit_309();
int[] prices = {1, 2, 3, 0, 2};
System.out.println(ins.maxProfit(prices));
}
}
|
Java
|
UTF-8
| 1,903
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
package md.shape;
import heli.htweener.Ease;
import heli.htweener.HT;
import heli.htweener.tween.ICallable;
import javafx.scene.paint.Color;
public class MDProgressText extends MDButton {
private boolean isRun = false;
private ICallable onRunStop;
public MDProgressText(String text, Color minColor, Color maxColor, Color finalColor, double size) {
super(text, maxColor, minColor, finalColor, size);
setInactive();
setLocked(true);
}
@Override
protected void registerMouseEvents() {
}
public void run(ICallable onUpdate) {
isRun = true;
nextRun(onUpdate);
}
private void nextRun(ICallable onUpdate) {
if (isRun) {
if (getScaleX() == 1f) {
HT.to(this, 600, Ease.sineInOut).s(2).color(colorRegular).onUpdate(ratio -> {
if (onUpdate != null) onUpdate.call();
}).onComplete(() -> nextRun(onUpdate));
} else {
HT.to(this, 600, Ease.sineInOut).s(1).color(colorInactive).onUpdate(ratio -> {
if (onUpdate != null) onUpdate.call();
}).onComplete(() -> nextRun(onUpdate));
}
} else {
//if (getScaleX() == 1f) {
HT.to(this, 1000, Ease.sineInOut).color(colorHovered);
HT.to(this, 600, Ease.sineInOut).s(1.5).onComplete(() -> {
HT.to(400).onComplete(() -> {
if (onRunStop != null) onRunStop.call();
});
});
//} else {
// HT.to(this, 1000, Ease.sineInOut).color(colorHovered).onComplete(() -> {
// if (onRunStop != null) onRunStop.call();
// });
//}
}
}
public void stop(ICallable onComplete) {
isRun = false;
onRunStop = onComplete;
}
}
|
Java
|
UTF-8
| 5,727
| 2.15625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package leap.webunit.client;
import leap.junit.TestBase;
import leap.lang.Charsets;
import leap.lang.Strings;
import leap.lang.exception.NestedIOException;
import leap.lang.http.HTTP;
import leap.lang.http.Headers;
import leap.lang.http.MimeType;
import leap.lang.http.MimeTypes;
import leap.lang.io.IO;
import leap.lang.jsoup.Jsoup;
import leap.lang.jsoup.nodes.Document;
import java.io.InputStream;
import java.nio.charset.Charset;
abstract class THttpResponseBase<C extends THttpClient> implements THttpResponse {
protected static final leap.lang.http.Header[] EMPTY_HEADER_ARRAY = new leap.lang.http.Header[]{};
protected final THttpRequestBase<C> request;
protected MimeType contentType;
protected String content;
protected Document htmlDocument;
protected THttpResponseBase(THttpRequestBase<C> request) {
this.request = request;
}
@Override
public THttpRequest request() {
return request;
}
@Override
public boolean isOk(){
return getStatus() == HTTP.SC_OK;
}
@Override
public boolean isSuccess(){
return 200 <= getStatus() && getStatus() < 300;
}
@Override
public boolean isFailure() {
return getStatus() >= 300;
}
@Override
public String getLocation(){
return getHeader(Headers.LOCATION);
}
@Override
public String getMediaType(){
MimeType contentType = getContentType();
return null == contentType ? null : contentType.getMediaType();
}
@Override
public String getCharset(){
MimeType contentType = getContentType();
return null == contentType ? null : contentType.getCharset();
}
@Override
public String getContent() throws NestedIOException {
if(null == content){
InputStream is = getInputStream();
content = null == is ? null : IO.readStringAndClose(is, charset());
}
return content;
}
@Override
public Document getDocument() throws NestedIOException {
if(null == htmlDocument){
String html = getContent();
htmlDocument = Jsoup.parse(html);
}
return htmlDocument;
}
@Override
public THttpResponse assertStatusEquals(int status){
TestBase.assertEquals((Integer)status, getStatus());
return this;
}
@Override
public THttpResponse assertContentEquals(String expectedContent){
TestBase.assertEquals(expectedContent, getContent());
return this;
}
@Override
public THttpResponse assertContentEmpty() {
TestBase.assertEmpty(getContent());
return this;
}
@Override
public THttpResponse assertContentNotEmpty() {
TestBase.assertNotEmpty(getContent());
return this;
}
@Override
public THttpResponse assertContentContains(String containsContent){
TestBase.assertContains(getContent(),containsContent);
return this;
}
@Override
public THttpResponse assertSuccess(){
TestBase.assertTrue(isSuccess());
return this;
}
@Override
public THttpResponse assertFailure() {
TestBase.assertFalse(isSuccess());
return this;
}
@Override
public THttpResponse assertOk(){
TestBase.assertTrue("The response status should be 200, but is " + getStatus(),isOk());
return this;
}
@Override
public THttpResponse assertNotOk() {
TestBase.assertFalse("The response status should not be 200", isOk());
return this;
}
@Override
public THttpResponse assertContentTypeHtml(){
TestBase.assertEquals(MimeTypes.TEXT_HTML,getMediaType());
return this;
}
@Override
public THttpResponse assertContentTypeText(){
TestBase.assertEquals(MimeTypes.TEXT_PLAIN,getMediaType());
return this;
}
@Override
public THttpResponse assertContentTypeEquals(String mediaType){
TestBase.assertEquals(mediaType,getMediaType());
return this;
}
@Override
public THttpResponse assertContentTypeEquals(String mediaType,String charset){
TestBase.assertEquals(mediaType,getMediaType());
TestBase.assertEquals(Strings.upperCase(charset),Strings.upperCase(getCharset()));
return this;
}
@Override
public THttpResponse assertContentTypePresent(){
TestBase.assertNotNull(getContentType());
return this;
}
@Override
public THttpResponse assertHeaderEquals(String headerName,String expectedValue){
TestBase.assertEquals(expectedValue, getHeader(headerName));
return this;
}
@Override
public THttpResponse assertCharsetEquals(String expectedCharset){
TestBase.assertEquals(expectedCharset,getCharset());
return this;
}
protected Charset charset(){
MimeType contentType = getContentType();
String charset = null == contentType ? null : contentType.getCharset();
return null == charset ? Charsets.UTF_8 : Charsets.forName(charset);
}
}
|
C#
|
UTF-8
| 996
| 2.71875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PSLAManager
{
class Fact : Table
{
public Fact(String tabName, List<Attribute> tabAttr, List<String> tabListOfSel, Attribute tabPrimaryKey, int tabSize)
: base(tabName, tabAttr, tabListOfSel, tabPrimaryKey, tabSize) {}
public Fact(String tabName, List<Attribute> tabAttr, List<String> tabListOfSel, List<Attribute> tabCompositeKeys, int tabSize)
: base(tabName, tabAttr, tabListOfSel, tabCompositeKeys, tabSize) {}
//if composite key, return the string
public string getCompositeKeys()
{
string stringConcat = String.Empty;
foreach (var v in this.tableCompositeKeys) {
stringConcat += v;
if (v != this.tableCompositeKeys.Last())
stringConcat += ",";
}
return stringConcat;
}
}
}
|
TypeScript
|
UTF-8
| 1,244
| 2.78125
| 3
|
[
"Apache-2.0"
] |
permissive
|
import { Argv } from "yargs";
import { MspCommandHandler } from "../../../commandHandlers/msp";
interface Arguments {
organization: string;
admin: string;
root: string;
tlsroot: string;
}
export const command = "fromFiles";
export const desc = "Imports organization certificates from files.";
export const builder = (yargs: Argv): Arguments =>
yargs
.option("organization", { demandOption: true, requiresArg: true, type: "string", description: "The organization name.", alias: "o" })
.option("admin", { demandOption: true, requiresArg: true, type: "string", description: "The path to the admin certificate file.", alias: "a" })
.option("root", { demandOption: true, requiresArg: true, type: "string", description: "The path to the CA root certificate file.", alias: "r" })
.option("tlsroot", { demandOption: true, requiresArg: true, type: "string", description: "The path to the TLS CA root certificate file.", alias: "t" })
.argv;
export const handler = async (argv: Arguments): Promise<void> => {
try {
await new MspCommandHandler().importFromFiles(argv.organization, argv.admin, argv.root, argv.tlsroot);
} catch (error) {
console.error(error);
}
};
|
Python
|
UTF-8
| 168
| 3.046875
| 3
|
[] |
no_license
|
#!/usr/bin/env python
l=set(x*(3*x-1)/2 for x in xrange(1,2500))
for i in l:
for j in l:
if i>j and i+j in l and abs(i-j) in l:
print abs(i-j)
|
Python
|
UTF-8
| 552
| 3.328125
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""Exercise 3.
Split the dataset based on the given ratio.
"""
import numpy as np
def split_data(x, y, ratio, seed=1):
np.random.seed(seed)
shuffle_indices = np.random.permutation(np.arange(len(y)))
shuffled_y = y[shuffle_indices]
shuffled_x = x[shuffle_indices]
x_train = shuffled_x[0:int(len(x)*ratio)]
x_test = shuffled_x[int(len(x)*ratio):]
y_train = shuffled_y[0:int(len(y)*ratio)]
y_test = shuffled_y[int(len(y)*ratio):]
return x_train,x_test,y_train,y_test
|
Markdown
|
UTF-8
| 1,632
| 2.828125
| 3
|
[] |
no_license
|
## Installation guide for Vue.js frontend
If you're using Vue.js single page application (SPA), you can add our script using below method:
```
<template>
<div>
<button class="open-hashcharger">Click me</button>
</div>
</template>
<script>
export default {
mounted: function() {
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/gh/warigroup/hashcharger@1/hashcharger.js';
script.id = 'hashcharger';
script.setAttribute('token', 'a46KwFe23rgtrgaAfrggWo');
// pass in your dynamic subuser and stratum config here.
script.setAttribute('subuser', `${subuser}`);
script.setAttribute('stratum-host', `${hostaddress}`);
script.setAttribute('stratum-port', `${port}`);
script.setAttribute('stratum-username', `${username}`);
script.setAttribute('stratum-password', `${password}`);
script.setAttribute('algorithm', 'equihash-zcash');
script.setAttribute('theme-navbg', '3626a5');
script.setAttribute('theme-navtexts', 'ffffff');
script.setAttribute('theme-primary', '3626a5');
script.setAttribute('theme-secondary', '233f5c');
script.setAttribute('theme-buttontexts', 'ffffff');
script.setAttribute('theme-tabletexts', 'ffffff');
document.body.appendChild(script);
},
destroyed: function() {
// (optional) remove your script when component unmounts
const script = document.getElementById('hashcharger');
document.body.removeChild(script);
}
};
</script>
```
Please use setAttribute() to add attributes to script tag.
https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
|
Python
|
UTF-8
| 996
| 2.953125
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
import numpy as np
def measure_angle(i, seq, outcome_array, input_angle, computation_angle):
"""Angle to measrue qubit i
:i: qubit to measure
:outcome_array: list of qubit outcomes
:input_angle: random angle in radians that was generated for measuring
:computation_angle: actual computation angle in radians (hidden by input_angle)
"""
c = 0
s = 0
for gate in seq:
if gate.type == "X" and gate.qubit == i:
c += outcome_array[i]
elif gate.type == "Z" and gate.qubit == i:
s += outcome_array[i]
elif gate.type=="M" and gate.qubit==i:
c+=gate.X_idxs #takes into account the extra arrays of M which contained xtra Xs due to commutation
elif gate.type=="M" and gate.qubit==i:
s+=gate.Z_idxs #same for Z
return input_angle + (((-1) ** c) * (computation_angle) + (s * 128) #SimulaQron takes one step of angle as pi/255, hence the given description
|
Java
|
UTF-8
| 5,152
| 3.71875
| 4
|
[
"Apache-2.0"
] |
permissive
|
package com.djs.learn;
import java.util.Arrays;
// https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/
public class FindFirstAndLastPositionOfElementInSortedArray
{
public int[] internal_searchRange_1(int[] nums, int startPos, int endPos, int target){
int[] index = {-1, -1};
if (startPos == endPos) { // Only 1 element.
if (nums[startPos] == target) { // Only 1 match.
index[0] = index[1] = startPos;
}
} else if (startPos < endPos) { // More than 1 element.
int midPos = (endPos + startPos) / 2;
if (target < nums[midPos]) {
// Target may be in lower half.
index = internal_searchRange_1(nums, 0, midPos - 1, target);
} else if (target > nums[midPos]) {
// Target may be in upper half.
index = internal_searchRange_1(nums, midPos + 1, endPos, target);
} else // target == nums[midPos] // Mid is target.
{
// Target just around mid.
// Maybe some in lower half.
int[] index_l = internal_searchRange_1(nums, 0, midPos - 1, target);
// Maybe some in upper half.
int[] index_h = internal_searchRange_1(nums, midPos + 1, endPos, target);
if (index_l[1] == -1) index[0] = midPos;
else index[0] = index_l[0];
if (index_h[0] == -1) index[1] = midPos;
else index[1] = index_h[1];
}
}
return index;
}
public int[] searchRange_1(int[] nums, int target){
int[] index = {-1, -1};
if (nums.length > 0) {
index = internal_searchRange_1(nums, 0, nums.length - 1, target);
}
return index;
}
public int[] internal_searchRange(int[] nums, int startPos, int endPos, int target, int midMatchedFlag){
int[] index = {-1, -1};
if (startPos == endPos) { // Only 1 element.
if (nums[startPos] == target) { // Only 1 match.
index[0] = index[1] = startPos;
}
} else if (startPos < endPos) { // More than 1 element.
int midPos = (endPos + startPos) / 2;
if (target < nums[midPos]) {
// Target may be in lower half.
index = internal_searchRange(nums, 0, midPos - 1, target, 0);
} else if (target > nums[midPos]) {
// Target may be in upper half.
index = internal_searchRange(nums, midPos + 1, endPos, target, 0);
} else // target == nums[midPos] // Mid is target.
{
index[0] = index[1] = midPos;
boolean checkLowerHalf = false;
boolean checkUpperHalf = false;
// Target just around mid.
if (midMatchedFlag == -1) {
// Maybe some in lower half.
checkLowerHalf = true;
} else if (midMatchedFlag == 1) {
// Maybe some in upper half.
checkUpperHalf = true;
} else { // midMatchedFlag == 0
// Maybe some in lower half.
checkLowerHalf = true;
// Maybe some in upper half.
checkUpperHalf = true;
}
if (checkLowerHalf) {
int[] index_l = internal_searchRange(nums, 0, midPos - 1, target, -1);
if (index_l[1] != -1) index[0] = index_l[0];
}
if (checkUpperHalf) {
int[] index_h = internal_searchRange(nums, midPos + 1, endPos, target, 1);
if (index_h[0] != -1) index[1] = index_h[1];
}
}
}
return index;
}
public int[] searchRange_2(int[] nums, int target){
int[] index = {-1, -1};
if (nums.length > 0) {
index = internal_searchRange(nums, 0, nums.length - 1, target, 0);
}
return index;
}
public void test_searchRange_1(int[] nums, int target){
System.out.println("Array / Target = " + Arrays.toString(nums) + " / " + target);
long startTime = System.currentTimeMillis();
int[] result = searchRange_1(nums, target);
long stopTime = System.currentTimeMillis();
System.out.println("Result = " + Arrays.toString(result));
System.out.println("Time (ms) = " + (stopTime - startTime + 1));
System.out.println("----------------------------------------");
}
public void test_searchRange_2(int[] nums, int target){
System.out.println("Array / Target = " + Arrays.toString(nums) + " / " + target);
long startTime = System.currentTimeMillis();
int[] result = searchRange_2(nums, target);
long stopTime = System.currentTimeMillis();
System.out.println("Result = " + Arrays.toString(result));
System.out.println("Time (ms) = " + (stopTime - startTime + 1));
System.out.println("----------------------------------------");
}
public static void main(String[] args){
FindFirstAndLastPositionOfElementInSortedArray solution = new FindFirstAndLastPositionOfElementInSortedArray();
{
int[] nums = {5, 7, 7, 8, 8, 10};
solution.test_searchRange_1(nums, 8);
}
{
int[] nums = {5, 7, 7, 8, 8, 10};
solution.test_searchRange_1(nums, 6);
}
{
int[] nums = {1, 2, 3, 3, 3, 3, 4, 5, 9};
solution.test_searchRange_1(nums, 3);
}
{
int[] nums = {5, 5, 5, 5, 5, 5, 5, 5, 5, 5};
solution.test_searchRange_1(nums, 5);
}
{
int[] nums = {5, 7, 7, 8, 8, 10};
solution.test_searchRange_2(nums, 8);
}
{
int[] nums = {5, 7, 7, 8, 8, 10};
solution.test_searchRange_2(nums, 6);
}
{
int[] nums = {1, 2, 3, 3, 3, 3, 4, 5, 9};
solution.test_searchRange_2(nums, 3);
}
{
int[] nums = {5, 5, 5, 5, 5, 5, 5, 5, 5, 5};
solution.test_searchRange_2(nums, 5);
}
}
}
|
SQL
|
UTF-8
| 578
| 3.734375
| 4
|
[
"CC-BY-2.5",
"CC-BY-2.5-AU",
"CC0-1.0"
] |
permissive
|
-- This script will produce a mapping of which Postal Areas overlap with with
-- State Suburbs and vice versa.
-- To the extent possible under law, the person who associated CC0
-- with this work has waived all copyright and related or neighboring
-- rights to this work.
-- http://creativecommons.org/publicdomain/zero/1.0/
SELECT
poa.name AS poa_name,
ssc.code AS ssc_code,
ssc.name AS ssc_name
FROM asgs_2011.poa AS poa
JOIN asgs_2011.ssc AS ssc
ON ST_Intersects(poa.geom, ssc.geom) AND
ST_Relate(poa.geom, ssc.geom, 'T********'); -- interiors intersect
|
TypeScript
|
UTF-8
| 853
| 3.625
| 4
|
[] |
no_license
|
export interface FailureConditions<U> {
testError?: (a: any) => boolean;
testResult?: (a: U) => boolean;
}
/**
* Provides checking capability for failure through two
* user-provided failureConditions which are simple predicates
* on U
*/
export class FailTester<U> {
constructor(private failureConditions: FailureConditions<U> = {}) {}
/**
* Is a result a failure case?
*/
public isFailureResult = (a: U): boolean => {
return this.failureConditions.testResult
? this.failureConditions.testResult(a)
: false;
};
/**
* Is an error a failure case?
* If no specific test, then it is.
*/
public isFailureError = (a: any): boolean => {
return this.failureConditions.testError
? this.failureConditions.testError(a)
: true;
};
}
|
TypeScript
|
UTF-8
| 1,088
| 4.0625
| 4
|
[] |
no_license
|
// What digit is at the given place value in num?
const getDigitFrom3 = (num: number, place: number) => {
const numbers = num.toString().split('');
return numbers[place - 1];
};
// console.log(getDigitFrom(12345, 1));
// console.log(getDigitFrom(12345, 2));
// console.log(getDigitFrom(12345, 3));
// console.log(getDigitFrom(12345, 4));
// console.log(getDigitFrom(12345, 5));
// How many digits are in num?
const getIntLength1 = (num: number) => {
let count = 0;
const numbers = num.toString().split('');
numbers.forEach((num) => {
count += 1;
});
return count;
};
// console.log(getIntLength(12345)); // 5
// console.log(getIntLength(123456)); // 6
// console.log(getIntLength(1234567)); // 7
// How many digits does the integer with the most digits have?
const getMaxDigits2 = (nums: Array<number>) => {
let currentMax = 0;
let currentNumMax = 0;
nums.forEach((num) => {
currentNumMax += 1;
});
if (currentNumMax > currentMax) {
currentMax = currentNumMax;
}
return currentMax;
};
console.log(getMaxDigits([1, 22, 333, 4444, 55555]));
|
Java
|
UTF-8
| 1,610
| 2.015625
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sp.managedBean;
import com.sp.entity.Operationtype;
import com.sp.repository.OperationTypeRepository;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* @author Oguzhan
*/
@ManagedBean(name = "operationTypeController")
@RequestScoped
public class OperationTypeController {
private Operationtype operationType;
private List<Operationtype> operationTypes;
public OperationTypeController() {
OperationTypeRepository operationTypeRepository = new OperationTypeRepository();
setOperationTypes(operationTypeRepository.findAll(operationType));
}
public void addOperationType(){
operationType = new Operationtype();
}
public void save(){
OperationTypeRepository operationTypeRepository = new OperationTypeRepository();
operationTypeRepository.create(operationType);
}
public Operationtype getOperationType() {
return operationType;
}
public void setOperationType(Operationtype operationType) {
this.operationType = operationType;
}
public List<Operationtype> getOperationTypes() {
return operationTypes;
}
public void setOperationTypes(List<Operationtype> operationTypes) {
this.operationTypes = operationTypes;
}
}
|
JavaScript
|
UTF-8
| 1,872
| 2.703125
| 3
|
[] |
no_license
|
"use strict"
const cart = {
template: `
<p class="title">Cart Mate</p>
<form class="add2cart" ng-submit="$ctrl.addItem(newItem)">
<input ng-model="newItem.product" placeholder="Product Name" type="text"></input>
<input ng-model="newItem.price" placeholder="Price" type="number"></input>
<input ng-model="newItem.quantity" placeholder="Quantity" type="number"></input>
<button>Add New Item</button>
</form>
<section>
<div class="cartitems" ng-repeat="item in $ctrl.items">
<p>SKU: {{item.id}}</p>
<p>Product: {{item.product}}</p>
<p>Price: {{item.price | currency}}</p>
<p>Quantity: {{item.quantity}}</p>
<form>
<button ng-click="$ctrl.updateItem()">+</button>
<input type="number"></input>
<button ng-click="$ctrl.updateItem()">-</button>
<button ng-click="$ctrl.removeItem(item.id)">Delete Item</button>
<button ng-click="$ctrl.updateItem(item.id, newItem)">Update Item</button>
</form>
</div>
</section>
`,
controller: ["CartService", function(CartService) {
const vm = this;
CartService.getItems().then(response => {
vm.items = response.data;
console.log(vm.items);
});
vm.addItem = function(newitem) {
CartService.addItem(newitem).then(response => {
vm.items = response.data;
});
};
vm.removeItem = function(id) {
CartService.removeItem(id).then(response => {
vm.items = response.data;
});
};
vm.updateItem = function(id, newItem) {
CartService.updateItem(id, newItem).then(response => {
vm.items = response.data;
});
};
}]
};
angular.module("App").component("cart", cart);
|
Python
|
UTF-8
| 1,020
| 3.515625
| 4
|
[
"Apache-2.0"
] |
permissive
|
import re
from Crypto.Hash import keccak
def is_checksum_address(address):
address = address.replace('0x', '')
address_hash = keccak.new(digest_bits=256)
address_hash = address_hash.update(address.lower().encode('utf-8')).hexdigest()
for i in range(0, 40):
# The nth letter should be uppercase if the nth digit of casemap is 1
if ((int(address_hash[i], 16) > 7 and address[i].upper() != address[i]) or
(int(address_hash[i], 16) <= 7 and address[i].lower() != address[i])):
return False
return True
def is_address(address):
if not re.match(r'^(0x)?[0-9a-f]{40}$', address, flags=re.IGNORECASE):
# Check if it has the basic requirements of an address
return False
elif re.match(r'^(0x)?[0-9a-f]{40}$', address) or re.match(r'^(0x)?[0-9A-F]{40}$', address):
# If it's all small caps or all all caps, return true
return True
else:
# Otherwise check each case
return is_checksum_address(address)
|
C#
|
UTF-8
| 3,693
| 2.828125
| 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 MatLeverans
{
public partial class Form1 : Form
{
private ICustomer register;
public static BindingList<Customer> customer;
public static string selectedUser;
public static int Index;
public Form1()
{
InitializeComponent();
register = new Customer();
customer = new BindingList<Customer>();
button1.Text = ("Register");
button2.Text = ("Edit");
button3.Text = ("Delete");
button4.Text = ("Search");
textBox1.Text = ("Social security number...");
label1.Text = ("Status: ");
listBox1.DataSource = customer;
button1.Click += new EventHandler(DoRegister);
button2.Click += new EventHandler(Edit);
button3.Click += new EventHandler(Delete);
button4.Click += new EventHandler(Search);
textBox1.GotFocus += new EventHandler(RemoveText);
textBox1.LostFocus += new EventHandler(AddText);
}
private void DoRegister(object sender, EventArgs e)
{
RegisterUser registerUser = new RegisterUser();
registerUser.Show();
}
private void Edit(object sender, EventArgs e)
{
selectedUser = listBox1.GetItemText(listBox1.SelectedItem);
foreach (Customer c in customer)
{
if (c.socialSec == selectedUser)
{
RegisterUser registerUser = new RegisterUser();
registerUser.Close();
EditUser editUser = new EditUser();
editUser.Show();
listBox1.SelectedItems.Clear();
return;
}
}
MessageBox.Show("You need an item selected!");
}
private void Delete(object sender, EventArgs e)
{
selectedUser = listBox1.GetItemText(listBox1.SelectedItem);
foreach(Customer c in customer)
{
if(c.socialSec == selectedUser)
{
Index = customer.IndexOf(customer.Single(i => i.socialSec == selectedUser));
customer.RemoveAt(Index);
return;
}
}
MessageBox.Show("You need an item selected!");
}
private void AddText(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text))
{
textBox1.Text = ("Social security number...");
}
}
private void RemoveText(object sender, EventArgs e)
{
textBox1.Text = ("");
}
private void Search(object sender, EventArgs e)
{
listBox1.SelectedItems.Clear();
int currentIndex = -1;
foreach (Customer c in customer)
{
currentIndex++;
if (c.socialSec == textBox1.Text)
{
Index = customer.IndexOf(customer.Single(i => i.socialSec == textBox1.Text));
listBox1.SetSelected(Index, true);
label1.Text = "Status: " + listBox1.SelectedItems.Count.ToString() + " items found";
return;
}
}
label1.Text = "Status: 0 items found";
}
}
}
|
Java
|
WINDOWS-1252
| 350
| 3
| 3
|
[] |
no_license
|
package desafioModulo;
import java.util.Scanner;
public class Exercicio2 {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
System.out.println("Em que ano estamos?");
int ano = entrada.nextInt();
if(ano %4 ==0) {
System.out.println(" ano bissexto");
}
entrada.close();
System.out.println("FIM");
}
}
|
Markdown
|
UTF-8
| 30,699
| 2.71875
| 3
|
[] |
no_license
|
## 第六 梵天相应
### 第一 梵天品
#### 第一 劝请
如是我闻。尔时,世尊住优留毗罗尼连禅河边之阿阇波罗尼俱律陀树下。时,已成等正觉。
时,世尊独坐禅思,而起此思惟。
依我所证得此法,甚深难见、难悟。寂静微妙,超越思念之领域。深妙唯贤者始知。又,此诸人等乐阿赖耶 ,喜阿赖耶,跳跃阿赖耶。诸人依于乐阿赖耶,喜阿赖耶,跳跃阿赖耶,而难见此理。此理者,即所谓依缘、缘起是。此理亦难见。此理者,即一切行之止静,一切依之舍离、爱尽、离、灭、涅盘是。我若说法,诸人难了解我所说者,我是应所疲劳而烦扰。
又,此以前未曾有闻之偈,世尊显示:
艰难我所证 今此实难说
败于欲嗔者 难得悟此法
逆世之常流 微妙而甚深
微细极难见 贪欲之所污
闇蕴所蔽者 不得见此法
世尊作如是思惟,即踌躇不说法。
时,梵天 沙巷婆提,犹如有力者之伸屈腕,或屈伸腕顷,如是没于梵天界,现于世尊之前。
时,梵天沙巷婆提偏袒一肩、右膝着地,合掌礼敬,如是白世尊曰:
‘世尊!请说法!善逝!请说法![世间]有不少众生,为眼尘所蔽。彼等不得闻法而衰退。[世间]应有法之了解者。’
梵天沙巷婆提白此言已,更唱此言:
于摩揭陀国 不净法垢秽
依此心思惟 开此甘露门
依无垢之心 今闻悟此法
上立山顶岩 如见周诸众
贤者全眼者 卿起慈悲心
立法城宫楼 以观沉悲惨
生老败诸众 请起立英雄
战立胜利者 无债商队主
请游此世间 请世尊说法
必有知解者
时,世尊知梵天之劝请,对众生起哀怜,以佛眼观世间。
世尊依佛眼观世间,见众生眼有蔽多、蔽少,有利根者、钝根者,有善相者、恶相者,有易教者、难教者,其中或有众人见来世罪之怖畏而住。
犹如于莲池之青莲华、黄莲华、白莲华。有青莲华、黄莲华、白莲华、生于水中、长于水中、不出水面,沈育于水中。有青莲华、黄莲华、白莲华,生于水中、长于水中,出立于水,不为水所湿。如是世尊,依眼观世间,见众生眼有蔽多、蔽少,有利根者、钝根者,有善相者、恶相者,有易教者、难教者,其中或有诸众见来世罪之怖畏而住。
见已,以偈答梵天沙巷婆提:
为于彼等众 开启甘露门
有耳之众人 舍离其他信
梵天我思惑 不说微妙法
时,梵天沙巷婆提,愿我说法,世尊许允,而礼敬世尊,右绕,于此没其身形。
#### 第二 恭敬
如是我闻。尔时,世尊住优留毗罗林,尼连禅河边,阿阇波罗尼俱律陀树下。时已成等正觉。
尔时,世尊独坐静观,生如是思惟:‘无所尊敬、恭敬之生活,是苦恼。我如何尊敬婆罗门而予近住耶?’
时,世尊生如是思惟:‘为成就未满之戒蕴,应尊敬其他沙门、婆罗门而予近住。但我于天界、魔界、梵天界所含之世界。于沙门、婆罗门、人、天所含之众中,不见如我成就戒者,以尊敬其他沙门、婆罗门而住。
为成就未满之定蕴……[乃至]……未满之慧蕴……乃至……未满之解脱蕴……乃至……未满之解脱知见蕴,应尊敬其他沙门、婆罗门而近住。但我于天界、魔界、梵天界所含之世界。于沙门,婆罗门、人、天所含之众中,不见如我成就解脱知见者,以尊敬其他沙门、婆罗门而近住。
我宁可对我所悟之法,尊敬此法而予近住。’
时,梵天沙巷婆提于心,知世尊心之思惟,犹如男子力士之伸屈腕、屈伸腕顷,没于梵天界,现于世尊前。
时,梵天沙巷婆提,偏袒一肩、含掌礼世尊,如是白世尊曰:
‘世尊!如是,善逝!如是。世尊!过去之应供、正觉者、世尊亦恭敬、尊重、亲近法而住。未来之应供、正觉者、世尊亦恭敬、尊重、亲近法而住。今之应供、正觉者、世尊亦恭敬、尊重、亲近法而住。’
梵天沙巷婆提说此已。又作此曰:
过去正觉者 未来之诸佛
今之正觉者 灭众生忧恼
悉皆敬正法 而住今亦住
又未来亦住 此诸佛法然
故愿自己利 以望伟大者
忆念佛之教 不无敬正法
#### 第三 梵天
如是我闻。尔时,世尊住舍卫城只树给孤独园。
其时,又有婆罗门女之子梵天,于世尊处出家而无家。
时,尊者梵天单独隐栖,不放逸、虔诚、精进而住、不久此良家之子,当为由家于无家而出家,于现法成就其无上梵行,自知、实证、证入而住。‘知生已尽,梵行已立,所作已办,不受后有。’尊者梵天,成阿罗汉。
时,尊者梵天清晨,着衣持钵,于舍卫城乞食,于舍卫城户户乞食,近至母家。
其时,尊者梵天之母婆罗门女,常以供牲供梵天。
时,梵天沙巷婆提生如是思念:‘此尊者梵天之母婆罗门女,常以供牲供梵天,我当往警觉。’
时,梵天沙巷婆提,犹如力士之伸屈腕、屈伸腕,没形于梵天界,现身于尊者梵天之母家。
时,梵天沙巷婆提立于空中,对尊者梵天之母婆罗门女唱偈曰:
婆罗门女者 汝常为供食
因此离梵天 婆罗门女者
此非梵天食 不知梵天道
而汝何牢骚 婆罗门女者
汝梵天比丘 已至无依着
以达胜天境 已无所有处
无养之比丘 今乞入汝家
相应于供养 积修达圣道
堪为人天供 除恶无秽污
乞食清威仪 彼亦无前后
寂静绝嗔烟 无闷亦无欲
于弱于强者 无用于暴力
令彼以得汝 第一之供养
无烦恼魔袭 心静无欲污
如调顺象行 戒行善圆满
心解脱比丘 令彼以得汝
第一之供养 婆罗门女者
今汝超瀑流 以见牟尼佛
对彼信不动 相应于供养
以行是功德 未来得安乐
婆罗门女今 已超越瀑流
以见于圣者 以持不动信
相应于供养 以行是功德
未来得安乐
#### 第四 婆迦梵天
如是我闻。尔时世尊住舍卫城只树给孤独园。
时,又有婆迦梵天,生如是恶见:‘此是常,此是恒常。此是常住,此是完全,此是不变之法。何以故,此不衰、不老、不萎、不灭、不生故。由此以上无有其他之出离。’
时,世尊知婆迦梵天心中之所念,犹如力士之伸屈腕、屈伸腕、没形于只园、现身于梵天界。
婆迦梵天、见世尊从远而来。见已,以此白世尊曰:‘友!来!友!善来耶!友!久违!何以来此耶?友!此是常,此是恒常,此是常住,此是完全,此是不变之法。何以故,此是不衰、不老、不萎、不灭、不生故。由此以上无有其他之出离。’
如是言已,世尊告此婆迦梵天曰:‘婆迦梵天乃被无明所困惑。婆迦梵天乃被无明所困惑。何以故?以无常者言常,以非恒常者言恒常,以非常住者言常住。以非完全者言完全,以变易之法言不变易之法。以衰、老、萎、灭、生者言不衰、不老、不萎、不灭、不生。由此以上有其他之出离,以言由此以上无有其他之出离故。’
[婆迦:]
我等七十二 依于功德业
为世统治者 超越生与老
以生此梵天 是为最后生
我乃通吠陀 是故诸众人
尊崇称赞我
[世尊:]
此生寿是短 婆迦思为长
我知梵天寿 百年或亿年
[婆迦:]
世尊以为我 是无边见者
云越老死悲 如何以语我
善行古禁戒 我愿欲知此
[世尊:]
汝苦于渴古 炎热于烦恼
予水于诸众 此乃汝古之
善行及禁戒 如是我记忆
如眠之醒觉 放救耶尼河
两岸囚众人 令脱捕虏者
此乃汝古之 善根及禁戒
如是我记忆 如眠之醒觉
于恒伽河流 怜愍诸众人
舟被狂龙打 此乃汝古之
善根及禁戒 如是我记忆
如眠之醒觉 古我汝弟子
名呼为劫波 圣智汝认我
此乃汝古之 善根及禁戒
如是我记忆 如眠之觉醒
[婆迦:]
汝实知我寿 又亦知其他
佛陀如是在 若实如是在
汝光辉威力 照耀于梵界
#### 第五 他见
舍卫城因缘。
其时,有梵天生如是恶见。‘无有可来此之沙门、婆罗门。’
时,世尊知彼梵天之所念,犹如力士,伸屈腕、屈伸腕,没形于只园,现身于梵天界。
时,世尊趺坐于此梵天头上之虚空,入于火定。
时,尊者大目犍连生如是思惟:‘今世尊在何处耶?’
大目犍连依超人清净之天眼,见世尊趺坐于梵天头上之虚空,入于火定。见已,如力士之伸屈腕、屈伸腕,没形于只园,现身于梵天界。
时,尊者大目犍连,从东方低于世尊在梵天头上之虚空趺坐,入于火定。
时,尊者大迦叶生如是思惟:‘世尊今住何处耶?’尊者大迦叶依超人清净之天眼,见世尊趺坐于梵天头上之虚空,入于火定。见已,犹如力士之伸屈腕、屈伸腕,没形于只园,现身于梵天界。如是尊者大迦叶,从南方低于世尊,于梵天头上之虚空趺坐,入于火定。
时,尊者大劫宾那,坐如是思惟:‘世尊今住何处耶?’尊者大劫宾那……[乃至]……如是尊者大劫宾那,从西方低于世尊,于梵天头上之虚空趺坐,入于火定。
时,尊者阿那律……[乃至]……如是尊者阿那律从北方低于世尊,于梵天头上之虚空趺坐,入于火定。
时,尊者大目犍连,以偈语梵天曰:
友汝今亦犹 前之所持见
胜梵界之光 见其明光耶
[梵天:]
友我于今日 尝不持是见
胜梵界之光 以见其明光
如何我今日 得云常住恒
如是,世尊为令梵天界之惊异,犹如力士之伸屈腕、屈伸腕,没形于梵天界,现身于只园。
时,有梵天呼其他梵众天:‘友!来!汝诣尊者大目犍连。如是语尊者大目犍连:‘友!目犍连!世尊之弟子中,其他有如目犍连、迦叶、劫宾那、阿那律之大神通、大威力耶?’
‘友!唯然!’其梵众天答覆梵天,而诣尊者大目犍连处。
诣已,以此语大目犍连曰:‘友目犍连!世尊之弟子中,其他有如目犍连、迦叶、劫宾那、阿那律之大神通、大威力耶?’
时,尊者大目犍连,以偈语梵天众曰:
三明达神通 巧妙知他心
漏尽阿罗汉 佛陀弟子中
其数有众多
时,梵众天欢喜于尊者大目犍连之所说,往诣彼大梵天。诣已,以此语梵天曰:‘友!尊者大目犍连,如是曰:
三明达神通 巧妙知他心
漏尽阿罗汉 佛陀弟子中
其数有众多
彼梵众天如是云已,梵天欢喜于梵众天之所说。
#### 第六 放逸
舍卫城因缘。
时,世尊又往日住坐独坐。
时,辟支梵天之须梵与辟支梵天之净居,往诣世尊之处。诣已,各立于门边。
时,辟支梵天须梵,以此谓辟支梵天净居曰:‘友!今不应侍奉世尊。世尊在行日住之独坐。彼处繁荣有梵天界,梵天于此住于放逸住。友!我等诣彼梵天。诣已,令惊惑彼梵天。’
‘友!唯然。’辟支梵天净居回答辟支梵天须梵。
时,辟支梵天须梵与辟支梵天净居,犹如力士之伸屈腕、屈仲腕,没形于世尊前,现身彼世界。
彼梵天见彼等梵天从远而来。见已,以此谓彼等梵天曰:‘友!卿等从何处来耶?’
‘友!我等从彼世尊、应供、正等觉者之处来。友!卿亦能往侍奉世尊、应供、正等觉者实为善。’
彼言已,其梵天不诺彼言,即化为千度形,以此谓辟支梵天须梵曰:‘友!卿兄我如是之神通威力否?’
‘友!我见卿如是神通威力。’
‘友!我有如是之神通威力,如何往侍奉其他沙门或婆罗门耶?’
时,辟支梵天须梵,化为二千度形,以此谓其梵天曰:‘友!卿见如是神通威力否?’
‘友!我见卿如是神通威力。’
‘友!彼世尊比卿与我具更大神通威力。友!往侍奉彼世尊、应供、正等觉者为善!’
时,彼梵天以偈谓辟支梵天须梵曰:
我宫殿有三 百列金翅乌
四百列白鸟 五百虎雕刻
梵天此宫殿 赫赫耀北方
[须梵:]
如何汝宫殿 赫耀于北方
贤者常见色 诤乱与动乱
故不乐于色
时,辟支梵天须梵与辟支梵天净居,为惊惑此梵天,于此没其身形。
如是其梵天,于其他之时,为侍奉世尊、应供、正等觉者而去。
#### 第七 瞿迦利迦
[尔时,世尊]住舍卫城……
时,世尊又行日住之独坐。
时,辟支梵天须梵与辟支梵天净居诣世尊处。诣已,各立门边。
时,辟支梵天须梵,对瞿迦利比丘,于世尊前唱此偈曰:
以量不可量 此谁知分别
以量不可量 我思无智者
唯有为混乱
#### 第八 低沙迦
[尔时,世尊]住舍卫城……
时,世尊行日住之独坐。
时,辟支梵天须梵与辟支梵天净居诣世尊处。诣已,各立门边。
时,辟支梵天净居,对迦达摩达迦低沙迦比丘,于世尊前唱此偈曰:
以量不可量 此谁知分别
以量不可量 我思无智者
唯有为混乱
#### 第九 都头梵天
[尔时,世尊]住舍卫城……
时、瞿迦利迦比丘生病而痛苦,其病严重。
时,辟支梵天都头 于夜更以其胜光辉耀只园,诣瞿迦利迦比丘处。
诣已,立于空中,以此语瞿迦利迦比丘曰:‘瞿迦利迦比丘!以信乐舍利弗与目犍连!舍利弗与目犍连是稳和者 。’
‘友!汝谁耶?’
‘我乃辟支梵天都头是。’
‘友!汝莫非依世尊记别为不还者耶?此时何故还来此耶?汝见犯过误,看!’
[都头:]
人之出生时 斧实生口中
愚人语于恶 其斧斩自己
以赞应责者 以责应赞者
依口重恶运 依恶不得乐
博奕为致富 失己犹不运
污心于善逝 不运更增大
企恶于口意 贬责圣人者
于百千垓年 三十六垓年
五秭年地狱 堕之受痛苦
#### 第十 瞿迦利迦
[尔时,世尊]住舍卫城……
时,瞿迦利迦诣世尊处。诣已礼敬世尊,于一面坐。
一面坐之瞿迦利迦比丘白世尊曰:‘世尊!舍利弗与目犍连是恶欲者。是受恶欲所支配者。’
言已。世尊以此告瞿迦利迦比丘曰:‘瞿迦利迦!勿作如是言;瞿迦利迦!勿作如是言。瞿迦利迦!勿作如是言。瞿迦利迦,应信乐舍利弗与目犍连。舍利弗与目犍连是稳和者。’
复次……[乃至]……
瞿迦利迦三度告世尊曰:‘世尊,舍利弗与目犍连是恶欲者,是受恶欲所支配者。’
世尊三度告瞿迦利迦曰:‘瞿迦利迦!勿作如是言,瞿迦利迦!勿作如是言。瞿迦利迦!应信乐舍利弗与目犍连,舍利弗与目犍连是稳和者。’
时,瞿迦利迦比丘,即从坐起,礼敬世尊,右绕而去。
瞿迦利迦比丘去后不久,全身生如芥子粒之疮。芥子粒即渐成豆粒;豆粒成如大豆,大豆成如枣核大,枣核而成如枣大,枣而成如阿摩罗果大,阿摩罗果而成如未熟之橡果大,成如未熟之橡果大,于此破裂流出脓血。
时,瞿迦利迦比丘,于此病而死。死矣之瞿迦利迦比丘,因对舍利弗与目犍连敌意,而堕红莲地狱。
时,梵天沙巷婆提于黎明更以其胜光,辉耀全园,诣于世尊处。诣已,礼敬世尊,立于一面。
立于一面之梵天沙巷婆提,以此白世尊曰:‘世尊!瞿迦利迦比丘死矣。因对舍利弗与目犍连怀敌意,死堕红莲地狱。’
梵天沙巷婆提,作此言已,礼敬世尊,右绕没形于此。
时,世尊于当夜过后,呼诸比丘曰:‘诸比丘!此夜梵天沙巷婆提,于黎明以其胜光,辉耀全只园,诣我处。诣已,礼我立于一面。诸比丘!立于一面之梵天沙巷婆提告我曰:‘世尊!瞿迦利迦比丘死矣。因对舍利弗与目犍连怀敌意,死而堕入红莲地狱。’诸比丘!梵天沙巷婆提作此言已,礼敬我,右绕,于此没其身形。’
如是言已,有比丘以此白世尊曰:‘世尊!红莲地狱之寿量有几何耶?’
‘比丘!红莲地狱之寿量甚长。难数为几年、几百年、几千年、几百千年。’
‘世尊,可譬喻说之耶?’
世尊曰:‘比丘!得如是说:譬喻此拘萨罗国有二十加厘菜种子,各过百年,取一粒菜种子,且以此方法,于拘萨罗国取尽二十加厘菜种子,亦不尽阿浮陀地狱之寿量。诸比丘!二十阿浮陀地狱为一尼罗浮陀地狱。二十尼罗浮陀地狱为一阿婆婆地狱。二十阿婆婆地狱为一阿吒吒地狱。二十阿吒吒地狱为一阿诃诃地狱。二十阿诃诃地狱为一水莲地狱。二十水莲地狱为一青睡莲地狱。二十青睡莲地狱为一青莲地狱。二十青莲地狱为一白莲地狱。二十白莲地狱为一红莲地狱。比丘!瞿迦利迦比丘对舍利弗与目犍连怀敌意,堕此红莲地狱。’
世尊如是说已。善逝又唱此偈曰.
人之出生时 斧实生口中
……乃至……(同前经之偈。)
此嗢陀南:
劝请及恭敬 梵婆迦梵天
他邪见放逸 与瞿迦利迦
乃至低沙迦 都头梵天及
他瞿迦利迦
### 第二 梵天品
#### 第一 常童子
如是我闻。尔时,世尊住王舍城叶毗尼河边。
时,梵天常童子 ,于黎明光辉照叶毗尼河边,以诣世尊处。诣已礼敬世尊,立于一面。
立一面之梵天常童子,于世尊处唱此偈曰:
氏姓人中尊 殊胜刹帝利
明行具足者 人天中殊胜
梵天常童子言已,请师嘉赏。
时、梵天常童子、知依师受嘉赏,礼敬世尊,右绕而去。
#### 第二 提婆达多
尔时,世尊于提婆达多离去不久,住王舍城灵鹫山。
时,梵天沙巷婆提于黎明时,辉耀全灵鹫出,以诣世尊处。诣而礼敬世尊,立于一面。
立一面之梵天沙巷婆提,对提婆达多于世尊处唱此偈曰:
芭萨竹及苇 生果实则萎
如驴生子死 恶人名誉杀
#### 第三 阎陀迦频陀
尔时,世尊住摩揭陀国之闇陀频陀。
尔时,世尊于夜闇中坐于露地,天降雨。
时,梵天沙巷婆提于黎明时,辉耀全闇陀迦频陀,以诣世尊处。诣已,礼敬世尊,立于一面。
立于一面之梵天沙巷婆提,于世尊处,唱此偈曰:
住于离市里 游方犹离缚
若有心不乐 应护于诸根
正念住僧伽 家家行乞时
护根谨正念 住于离市里
无惧得解脱 回忆惧毒蛇
电光鸣天雷 于夜闇比丘
独坐离恐怖 我眼实当见
非是传所闻 在于一法教
以脱千人死 有当五百多
于百之十培 于其十培数
皆悉入预流 超畜生趣者
此外之诸人 对于得功德
我心难堪数 恐人云妄语
#### 第四 阿卢那越提
如是我闻。尔时,世尊住舍卫城。
时,世尊呼诸比丘:‘诸比丘!’
‘唯然!世尊、’彼等诸比丘应答世尊。
尊如此宣说:
‘诸比丘!昔有阿卢那远多王。其王有阿卢那越提之都。尸弃世尊、应供、正等觉者,住其阿卢那越提王都。
诸比丘!又,尸弃世尊,应供、正等觉者,有一对上足弟子:名为阿毗浮、参跋婆。
时,诸比丘!尸弃世尊呼阿毗浮比丘:‘来!婆罗门!至于食时,到某梵天界。’
‘唯然!世尊!’阿毗浮比丘奉答尸弃世尊。
时,诸比丘!尸弃世尊与阿毗浮比丘,犹如力士之伸屈腕、屈伸腕,没于阿卢那越提王都,现身于梵天界。
时,诸比丘!尸弃如来呼毗浮比丘:‘婆罗门!而此梵天、梵辅天、梵众天说法语。’
‘唯然!世尊!’阿毗浮比丘奉答尸弃世尊、向梵天、梵辅天、梵众天、说法语、教诚、勉励,令其欢喜。
尔时,诸比丘!梵天与梵辅天及梵众天相说细语、还复牢骚说愚痴:‘实希有,未得曾有,如何弟子于师前说法耶?’
时,诸比丘!尸弃世尊呼阿毗浮比丘曰:‘婆罗门!梵天与梵辅天及梵众天,牢骚说细语、云愚痴:‘实希有,得未曾有,何以弟子于师前说法耶?’婆罗门!是故汝越更警醒于梵天与梵辅及梵众天。’
‘唯然!世尊。’诸比丘!阿毗浮比丘奉答尸弃世尊,以现身说法,不现身说法,现下半身说法,现上半身说法。
于此,诸比丘!梵天与梵辅天及梵众天起希有,得未曾有心:‘沙门之大神通大威力,实是希有,实是未曾有。’
时,阿毗浮比丘以此白尸弃世尊曰:‘世尊!知我于比丘僧伽中,如立于梵天界,依用音声,令得闻于千世界。’
‘婆罗门!汝应立梵天界,令千世界闻汝音声之时。’
诸比丘!‘唯然!世尊。’阿毗浮比丘奉答尸弃世尊,立于梵天界,以唱此偈曰:
精勤及勉励 从顺佛陀教
拂败恶魔军 如象破苇屋
此法与戒律 住不放逸者
弃生死轮回 应尽苦边际
诸比丘!时,尸弃世尊与阿毗浮比丘,警醒梵天与梵辅天及梵众天。犹如力士之伸屈腕、屈伸腕。没形于梵天界,现身于阿卢那越提。
诸比丘!时尸弃世尊呼诸比丘曰:‘诸比丘!汝等闻阿毗浮比丘立于梵天唱此偈否?’
‘世尊!我等闻阿毗浮比丘,立于梵天界之所唱此偈。’
‘诸比丘!汝等闻阿毗浮比丘,立梵天界唱如何偈耶?’‘世尊!我等如是闻:
精勤及勉励 从顺佛陀教
拂败恶魔军 如象破苇屋
此法与戒律 住不放逸者
弃生死轮回 应尽苦边际
世尊!我等闻如是偈。’
‘善哉!善哉!诸比丘!汝等闻阿毗浮比丘,立梵天界唱,善哉!’’
世尊宣说已。彼等诸比丘!欢喜世尊之所说。
#### 第五 般涅盘
尔时,世尊于俱尸那罗末罗族之恕跋单沙罗林 ,沙罗 双树间,入涅盘时。
时,世尊呼诸比丘曰:‘诸比丘!我今语汝等。精勤不放逸!诸行乃生灭之法。’此是如来最后之言教。
时,世尊入于第一禅,由第一禅起,入第二禅。由第二禅起,入第三禅。由第三禅起,入第四禅。由第四禅起,入虚空无边处定。由虚空无边处定起,入识无边处定。由识无边处起,入无所有处定。由无所有处定起,入非想非非想处定。
由非想非非想定起,入无所有处定。由无所有处定起,入识无边处定。由识无边定起,入虚空无边处定。由虚空无边处定起,入第四禅。由第四禅起,入第三禅。由第三禅起,入第二禅。由第二禅起,入第一禅。由第一禅起,入第二禅。由第二禅起,入第三禅。由第三禅起,入第四禅。由第四禅之等无间,世尊入于涅盘。
世尊入涅盘耶!于其入涅盘时,梵天沙巷婆提即唱此偈曰:
世间诸有情 迟早舍身此
世间无比者 如来得力者
正觉者大师 已入于涅盘
世尊入涅盘耶!于其入涅盘时,天帝释即唱此偈曰:
诸行实无常 是为生灭性
生者必有灭 以寂灭为乐
世尊入涅盘耶!于其入涅盘时,尊者阿难唱此偈曰:
其时我恐怖 我毛发竖立
一切胜相具 觉者入涅盘
世尊入涅盘耶!于其入涅盘时,尊者阿那律唱此偈曰:
出息入息无 心确立于定
无欲污寂静 有眼者涅盘
无着心宽广 堪于死苦恼
如灯之消逝 是心之辞脱
此嗢陀南:
梵天常童子 与提婆达多
闇陀迦频陀 阿卢那越提
依于般涅盘 说梵天五经
|
Java
|
UTF-8
| 1,568
| 2.28125
| 2
|
[] |
no_license
|
package com.example.newsapi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity implements Callback<BaseObject> {
private Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://newsapi.org/v2/")
.addConverterFactory(GsonConverterFactory.create())
.build();
NewsApi api = retrofit.create(NewsApi.class);
api.news().enqueue(this);
}
@Override
public void onResponse(Call<BaseObject> call, Response<BaseObject> response) {
BaseObject obj = response.body();
if(obj.status.equals("ok")){
RecyclerView recyclerView = findViewById(R.id.listOfArticles);
DataAdapter adapter = new DataAdapter(context, obj.articles);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setAdapter(adapter);
}
}
@Override
public void onFailure(Call<BaseObject> call, Throwable t) {
}
}
|
Python
|
UTF-8
| 2,114
| 3.21875
| 3
|
[] |
no_license
|
"""
This module perform the functionality of creating the Login forms and Sign up forms.
It makes use of the functionality of built in wtforms modules adopted for the
Flask applications.
"""
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField,BooleanField
from wtforms.validators import DataRequired,ValidationError, Email, EqualTo
from app.models import User
class LoginForm(FlaskForm):
"""
Creates components for a login form for flask app.
"""
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Sign In')
class RegistrationForm(FlaskForm):
"""
This class creates components for a Sign up form
"""
username = StringField('Username', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
password2 = PasswordField('Repeat Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Register')
def validate_username(self, username):
"""
Validates the username. If the username exists already then returns an error message.
@username: username for a given user.
"""
user = User.query.filter_by(username=username.data).first()
if user is not None:
raise ValidationError('Please use a different username because this username is already taken.')
def validate_email(self, email):
"""
Validates the email address of the user. If the email address is registered with some other user in the
database then returns an error message in string form.
@email: email address of the user.
"""
user = User.query.filter_by(email=email.data).first()
if user is not None:
raise ValidationError('Please use a different email address because this email address is already registered with some other user.')
|
Python
|
UTF-8
| 321
| 4.21875
| 4
|
[] |
no_license
|
'''写代码实现一个整数加法计算器(两个数相加)。需求:提示用户输入:5+9或5+9或5+9,计算出两个值的和(提示:先分割再转换为整型,再相加)'''
enter = input("输入n+n格式的内容").strip()
data = enter.split("+")
sum = int(data[0]) + int(data[1])
print(sum)
|
C#
|
UTF-8
| 438
| 2.59375
| 3
|
[] |
no_license
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/*
Attach to an object with an animator so you can call function to play particles from the animation.
Probably mostly useful for particle systems that play a burst of particles rather than a stream.
*/
public class PlayParticlesFromAnimation : MonoBehaviour
{
public ParticleSystem particles;
public void playParticles()
{
particles.Play();
}
}
|
Python
|
UTF-8
| 1,130
| 3.5
| 4
|
[
"MIT"
] |
permissive
|
# Solution of;
# Project Euler Problem 162: Hexadecimal numbers
# https://projecteuler.net/problem=162
#
# In the hexadecimal number system numbers are represented using 16 different
# digits:0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,FThe hexadecimal number AF when written
# in the decimal number system equals 10x16+15=175. In the 3-digit hexadecimal
# numbers 10A, 1A0, A10, and A01 the digits 0,1 and A are all present. Like
# numbers written in base ten we write hexadecimal numbers without leading
# zeroes. How many hexadecimal numbers containing at most sixteen hexadecimal
# digits exist with all of the digits 0,1, and A present at least once?Give
# your answer as a hexadecimal number. (A,B,C,D,E and F in upper case, without
# any leading or trailing code that marks the number as hexadecimal and
# without leading zeroes , e. g. 1A3F and not: 1a3f and not 0x1a3f and not
# $1A3F and not #1A3F and not 0000001A3F)
#
# by lcsm29 http://github.com/lcsm29/project-euler
import timed
def dummy(n):
pass
if __name__ == '__main__':
n = 1000
i = 10000
prob_id = 162
timed.caller(dummy, n, i, prob_id)
|
Java
|
ISO-8859-2
| 346
| 1.882813
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TankGame;
import GUI_Pack.GUI;
/**
* TankTrouble++
* @author Hegyi Smuel, Horvth Gyz, Szab Dniel
*/
public class Main {
public static void main(String[] args) {
StateMachine SM = new StateMachine();
GUI g = new GUI(SM);
SM.setGui(g);
}
}
|
Markdown
|
UTF-8
| 5,377
| 2.8125
| 3
|
[] |
no_license
|
- We walk by faith, not by sight.
- For to me, to live is Christ and to die is gain.
- If God is for us, who can be against us?
- It’s not how good you are. It’s how bad you want it.
- I press on toward the goal to win the prize for which God has called me heavenward in Christ Jesus.
- Whatever you do, work at it with all your heart...
- Do not be conformed to this world, but be transformed by the renewing of your minds.
- In everything give thanks.
- Hope does not disappoint.
- For when I am powerless, it is then that I am strong...
- Bad company ruins good morals.
- Remember this: Whoever sows sparingly will also reap sparingly, and whoever sows generously will also reap generously.
- Be kind and compassionate to one another, forgiving each other, just as in Christ God forgave you.
- If it is possible, as far as it depends on you, live at peace with everyone.
- For you died, and your life is hidden with Christ in God.
- If I could speak all the languages of earth and of angels, but didn’t love others, I would only be a noisy gong or a clanging cymbal.
- For the moment all discipline seems painful rather than pleasant; later it yields the peaceful fruit of righteousness to those who have been trained by it.
- Every Scripture is God-breathed and profitable for teaching, for reproof, for correction, and for instruction in righteousness, that the man of God may be complete, thoroughly equipped for every good work.
- The man who thinks he knows something does not yet know as he ought to know.
- There is no longer Jew or Greek, there is no longer slave or free, there is no longer male and female; for all of you are one in Christ Jesus.
- Let us not become weary in doing good, for at the proper time we will reap a harvest if we do not give up.
- Modesty is the key to success.
- So, then, let us pursue the things making for peace and the things that are upbuilding to one another.
- You can’t fall off the floor.
- If in this life only we have hope in Christ, we are of all men the most pitiable.
- Use your heads as you live and work among outsiders. Don’t miss a trick. Make the most of every opportunity. Be gracious in your speech. The goal is to bring out the best in others in a conversation, not put them down, not cut them out.
- Owe nothing to anyone, except to love one another.
- There is nothing love cannot face; there is limit to its faith, its hope and endurance.
- Walk in the Spirit, and ye shall not fulfil the lust of the flesh, for the flesh lusteth against the Spirit, and the Spirit against the flesh: and these are contrary the one to the other: so that ye cannot do the things that ye would.
- Absent in body, but present in spirit.
- They that will be rich fall into temptation and a snare, and into many foolish and hurtful lusts, which drown men in destruction and perdition. For the love of money is the root of all evil.
- I died to the law so that I might live for God.
- Beware of the dogs, beware of the evil workers, beware of those who mutilate the flesh!
- But fornication and all uncleanness or covetousness, let it not even be named among you, as is fitting for saints; neither filthiness, nor foolish talking, nor coarse jesting, which are not fitting, but rather giving of thanks.
- Your teaching must have the integrity of serious, sound words to which no one can take exception. If it does, no opponent will be able to find anything bad to say about us, and hostility will yield to shame.
- If any man defile the temple of God, him shall God destroy, for the temple of God is holy, which temple ye are.
- Wherefore, if meat causeth my brother to stumble, I will eat no flesh for evermore, that I cause not my brother to stumble.
- Therefore, I exhort first of all that supplications, prayers, intercessions, and giving of thanks be made for all men, for kings and all who are in authority, that we may lead a quiet and peaceable life in all godliness and reverence.
- The natural man receiveth not the things of the Spirit of God: for they are foolishness unto him: neither can he know them, because they are spiritually discerned. But he that is spiritual judgeth all things, yet he himself is judged of no man.
- Then each of you will control his own body and live in holiness and honor- not in lustful passion like the pagans who do not know God and his ways.
- Brethren, do not become children in sense: but in malice be children, and in sense be perfect.
- There are, for example, so many kinds of tongues in this world; and none is without voice. If then I know not the power of the voice, I shall be to him to whom I speak a barbarian; and he that speaketh, a barbarian to me.
- And thus I aspire to preach the gospel, not where Christ was already named so that I would not build on another man’s foundation.
- Even so husbands should love their wives as their own bodies. He who loves his wife loves himself.
- It’s amazing how insults in most languages sound the same.
- For if the truth of God hath more abounded through my lie unto his glory; why yet am I also judged as a sinner?
- The wife hath not power of her own body, but the husband. And in like manner the husband also hath not power of his own body, but the wife.
- Let the husband render to his wife the affection owed her, and likewise also the wife to her husband.
48 quotes
|
Python
|
UTF-8
| 5,007
| 2.84375
| 3
|
[] |
no_license
|
import arcade
import arcade.gui
import menuHandler
import button
import game as gm
EASY = 0
MODERATE = 1
HARD = 2
class Menu():
def __init__(self):
self.buttons = list()
self.texts = arcade.SpriteList()
self.accents = arcade.SpriteList()
def add_button(self, text, x, y, on_click):
newbutt = button.TextButton(x, y, 250, 45, text, on_click)
self.buttons.append(newbutt)
def add_text(self, text, x, y, width = 250):
text_box = arcade.gui.UILabel(text, center_x = x, center_y = y, width = width)
self.texts.append(text_box)
def add_accent(self, x, y, image):
accent = arcade.Sprite(image)
accent.center_x = x
accent.center_y = y
self.accents.append(accent)
def draw(self):
for button in self.buttons:
button.draw()
self.texts.draw()
self.accents.draw()
def remove_button(self, button):
for b in self.buttons:
if b.text == button:
self.buttons.remove(b)
def remove_text(self, text):
for t in self.texts:
if t.text == text:
self.texts.remove(t)
class MainMenu(Menu):
def __init__(self, game, handler):
super().__init__()
self.game = game
self.handler = handler
self.add_button('Start', 750, 500, self.click)
self.add_text('A Nameless Dungeon Crawler', 750, 800, 500)
self.add_button('Options', 750, 300, self.option_click)
def click(self):
self.game.start_game()
def option_click(self):
self.handler.set_menu(menuHandler.OPTIONS)
class PauseMenu(Menu):
def __init__(self, game, handler):
super().__init__()
self.game = game
self.handler = handler
self.add_button('Resume', 750, 450, self.resume_click)
self.add_button('Main Menu', 750, 300, self.main_click)
self.add_button('Quit', 750, 150, self.quit_click)
self.add_text('A Nameless Dungeon Crawler', 750, 800, 500)
self.add_text('PAUSED', 750, 650)
def quit_click(self):
self.game.quit_game()
def main_click(self):
self.handler.set_menu(menuHandler.MAIN)
def resume_click(self):
self.game.resume_game()
class GameOverMenu(Menu):
def __init__(self, game, handler):
super().__init__()
self.handler = handler
self.game = game
self.add_button('Main Menu', 750, 450, self.main_click)
self.add_button('Quit', 750, 300, self.quit_click)
self.add_text('GAME OVER', 750, 600)
def main_click(self):
self.handler.set_menu(menuHandler.MAIN)
def quit_click(self):
self.game.quit_game()
class WinMenu(Menu):
def __init__(self, game, handler):
super().__init__()
self.game = game
self.handler = handler
self.add_button('Main Menu', 750, 250, self.main_click)
self.add_button('Quit', 750, 450, self.quit_click)
self.add_text('VICTORY', 750, 600)
def main_click(self):
self.handler.set_menu(menuHandler.MAIN)
def quit_click(self):
self.game.quit_game()
class OptionMenu(Menu):
def __init__(self, game, handler):
super().__init__()
self.game = game
self.handler = handler
self.current_difficulty = MODERATE
self.add_button('Easy', 400, 500, self.easy_click)
self.add_text('Moderate', 750, 500)
self.add_button('Hard', 1100, 500, self.hard_click)
self.add_button('Main Menu', 750, 300, self.main_click)
def easy_click(self):
self.game.set_difficulty(gm.EASY)
self.add_difficulty_button(EASY)
self.current_difficulty = EASY
def moderate_click(self):
self.game.set_difficulty(gm.MODERATE)
self.add_difficulty_button(MODERATE)
self.current_difficulty = MODERATE
def hard_click(self):
self.game.set_difficulty(gm.HARD)
self.add_difficulty_button(HARD)
self.current_difficulty = HARD
def main_click(self):
self.handler.set_menu(menuHandler.MAIN)
def add_difficulty_button(self, difficulty):
if self.current_difficulty == EASY:
self.remove_text('Easy')
self.add_button('Easy', 400, 500, self.easy_click)
elif self.current_difficulty == MODERATE:
self.remove_text('Moderate')
self.add_button('Moderate', 750, 500, self.moderate_click)
elif self.current_difficulty == HARD:
self.remove_text('Hard')
self.add_button('Hard', 1100, 500, self.hard_click)
if difficulty == EASY:
self.remove_button('Easy')
self.add_text('Easy', 400, 500)
elif difficulty == MODERATE:
self.remove_button('Moderate')
self.add_text('Moderate', 750, 500)
elif difficulty == HARD:
self.remove_button('Hard')
self.add_text('Hard', 1100, 500)
|
Markdown
|
UTF-8
| 4,143
| 3.578125
| 4
|
[] |
no_license
|
# 初识React中的High Order Component
我们都知道,如果使用ES6 Component语法写React组件的话,mixin是不支持的。而mixin作为一种抽象和共用代码的方案,许多库(比如react-router)都依赖这一功能,自己的项目中可能都或多或少有用到mixin来尽量少写重复代码。
如果希望使用ES6 Component,有希望可以用一个像mixin一样的方案的话,可以使用react-mixin这样的库,就有种hack的感觉。这里介绍一个新的方案:High Order Component。
## 一、什么是High Order Component
High Order Component,下面统一简称为HOC。我理解的HOC实际上是这样一个函数
```javascript
hoc :: ReactComponent -> ReactComponent
```
它接受一个ReactComponent,并返回一个新的ReactComponent,这一点颇有函数式编程的味道。由于是一个抽象和公用代码的方案,这个新的ReactComponent主要包含一些共用代码的逻辑或者是状态,用一个例子来解释更加直观
```javascript
const connect = (mapStateFromStore) => (WrappedComponent) => {
class InnerComponent extends Component {
static contextTypes = {
store: T.object
}
state = {
others: {}
}
componentDidMount () {
const { store } = this.context
this.unSubscribe = store.subscribe(() => {
this.setState({ others: mapStateFromStore(store.getState()) }
})
}
componentWillUnmount () {
this.unSubscribe()
}
render () {
const { others } = this.state
const props = {
...this.props,
...others
}
return <WrappedComponent {...props} />
}
}
return InnerComponent
}
```
这个例子中定义的connect函数其实和react-redux中的connect差不多,我们发现它在内部定义了一个新的ReactComponent并将其返回,它的职责是在订阅store的改变,并将改变传递给子组件,在unmount的时候擦好屁股。这个case和常用的StoreMixin和类似。
## 二、始终要记住的是,HOC最终返回的是一个新的ReactComponent
要使用HOC的话可以这样:
```javascript
class MyContainer extends Component {
...
}
export connect(() => ({}))(MyContainer)
```
其实我们还发现HOC的函数类型和class decorator是一样的,所以可以这样:
```javascript
@connect(() => ({}))
class MyContainer extends Component {
...
}
export MyContainer
```
但是HOC不是decorator,不能保证decorator最终一定进入ES的规范中,然而HOC始终是那个函数
## 三、与mixin作比较
既然HOC的目的和mixin类似,那么我们来比较下这两种方案的区别:
首先,mixin是react亲生的,而HOC是社区实践的产物。其实这一点无关紧要,关键是讨论方案是否给开发带来便利,而且从趋势来看,并不看好mixin
不过我们还是先来看下mixin的使用场景
>* Lifecycle Hook
>* State Provider
第一个应用场景Lifecycle Hook通常是在React组件生命周期函数中做文章,最典型的就是对Store的监听和保证unmount时候取消监听。第二个应用场景State Provider,典型的例子就是react-router,它所提供的几个mixin都是route信息的提供者。复杂的mixin则是两者的结合了。
回到HOC,对于Lifecycle Hook而言,由于本身就返回一个新的ReactComponent,这一点毫无压力。对于State Provider而言,可以通过新的ReactComponent的state来维护。
**两者在生命周期上有差异**。这是我的测试结果,其中hoc表示HOC返回的新的ReactComponent,app表示的是WrappedComponent
```javascript
hoc componentWillMount
app componentWillMount
app componentDidMount
hoc componentDidMount
```
注:这里的componentWillMount是在constructor中输出的。
然后如果在HOC返回的新组件中更新状态的话:
```javascript
hoc componentWillUpdate
app componentWillReceiveProps
app componentWillUpdate
app componentDidUpdate
hoc componentDidUpdate
```
最后是unmount的部分
```javascript
hoc componentWillUnmount
app componentWillUnmount
```
|
SQL
|
UTF-8
| 534
| 2.96875
| 3
|
[] |
no_license
|
CREATE TABLE product (
product_id INT NOT NULL AUTO_INCREMENT,
product_name VARCHAR(50),
product_description VARCHAR(255),
PRIMARY KEY ( product_id )
);
CREATE TABLE user_detail (
id INT NOT NULL AUTO_INCREMENT,
username VARCHAR(50),
role VARCHAR(50),
password VARCHAR(60),
PRIMARY KEY (id )
);
-- used Bcrypt Hash as password.
INSERT INTO user_detail (username,role,password) VALUES ('admin','ADMIN','$2a$06$FTv7qeF6qQ2WLimkgQpsw.4DZm7t6rVOuitvML17MJFXmqS20IB9W');
INSERT INTO user_detail (username,role,password) VALUES ('hemanth','USER','$2a$06$FTv7qeF6qQ2WLimkgQpsw.4DZm7t6rVOuitvML17MJFXmqS20IB9W');
|
JavaScript
|
UTF-8
| 403
| 2.578125
| 3
|
[] |
no_license
|
const initState = {
allProduct: [],
searchedProducts: [],
}
const productReducers = (state = initState, action) => {
switch (action.type) {
case "FETCH_SEARCHED_PRODUCT":
return {
...state,
searchedProducts: action.payload.searchedProducts,
}
default:
return { ...state };
}
}
export default productReducers;
|
C
|
UTF-8
| 262
| 3.953125
| 4
|
[] |
no_license
|
#include <stdio.h>
void cuadrado(float x);
int main()
{
float x;
printf("Introduce un número para elevar al cuadrado:");
scanf("%f", &x);
cuadrado(x);
return 0;
}
void cuadrado(float x)
{
float x2;
x2=x*x;
printf("El cuadrado de %f es %f\n", x, x2);
}
|
C++
|
UTF-8
| 2,818
| 2.828125
| 3
|
[] |
no_license
|
// command.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
// Behavior design pattern
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
using namespace std;
class ActionEvent
{
};
class ButtonPressed : public ActionEvent
{
};
class ActionListener // COMMAND!
{
public:
virtual void actionPerformed(const ActionEvent& event) = 0;
//virtual void addActionListener(ActionListener* listener) = 0;
};
class Widget
{
public:
virtual void eventOccured(const ActionEvent& event) = 0;
};
class Button : public Widget
{
public:
virtual void eventOccured(const ActionEvent& event) override
{
pressed = !pressed;
if (listener != nullptr)
listener->actionPerformed(event); // callback when event happens (client code!)
}
//register caalback
virtual void addActionListener(ActionListener* listener)
{
this->listener = listener;
}
private:
bool pressed{}; // false
ActionListener *listener{};
};
//client code (start)
class OkActionListener : public ActionListener
{
virtual void actionPerformed(const ActionEvent& e)
{
thread t{ []() { cout << this_thread::get_id()<< ":OK\n"; } };
t.join();
}
};
class Cancel : public ActionListener
{
virtual void actionPerformed(const ActionEvent& e)
{
thread t{ []() {cout << this_thread::get_id() << "cancel\n"; } };
t.join();
}
};
int main()
{
//client code (start)
Button ok{};
Button cancel{};
OkActionListener oal{};
Cancel cal{};
ok.addActionListener(&oal);
cancel.addActionListener(&cal);
//client code (end)
//platform code
this_thread::sleep_for(500ms);
thread t{ [&ok, &cancel]() {
for (int i = 0; i < 100; i++) {
ok.eventOccured(ButtonPressed{});
cancel.eventOccured(ButtonPressed{});
this_thread::sleep_for(30ms);
}
}
};
//[](){};--se declara un lamda(o functie anonima)
t.join();
return 0;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
|
Python
|
UTF-8
| 3,713
| 3.546875
| 4
|
[] |
no_license
|
##Run The Program Through The Interface File
from tkinter import *
#Displays the users most played song, and its total plays
class Song_Stat_Window():
def __init__(self, stats, song, plays, artist):
self.master = stats
self.song = song
self.plays = plays
self.artist = artist
stats.title("Song Stats")
stats.geometry("300x150+100+100")
label = Label(stats, text = 'Song Statistics')
label.grid(row = 0, pady=10)
label2 = Label(stats, text="Your most played song is:")
label2.grid(row=1,pady=5)
label3 = Label(stats, text=f"{song} by {artist}")
label3.grid(row=2)
label4 = Label(stats, text=f"Total Listens: {plays}")
label4.grid(row=3,pady=10)
# displays the most played artist, how many total listens and most frequent song
class Artist_Stats_Window():
def __init__(self, stats, artist, times, song):
self.master = stats
self.artist = artist
self.times = times
self.song = song
stats.title('Artist Stats')
stats.geometry("350x200+100+100")
label = Label(stats, text='Artist Statistics')
label.grid(row=0, pady=10)
label2 = Label(stats, text="Your most played artist is:")
label2.grid(row=1, pady=5)
label3 = Label(stats, text=f"{artist}")
label3.grid(row=2)
label4 = Label(stats, text=f"Total time: {times}")
label4.grid(row=3, pady=10)
label5 = Label(stats, text=f"Your most played song by {artist} is:")
label5.grid(row=4, pady=5)
label6 = Label(stats, text=f"{song}")
label6.grid(row=5)
#shows most listened to album and most listened to song on the album
class Album_Stats_Window():
def __init__(self, stats, album, artist, song):
self.master = stats
self.song = song
self.album = album
self.artist = artist
stats.title("Album Statistics")
stats.geometry("300x200+100+100")
label = Label(stats, text = 'Album Statistics')
label.grid(row = 0, pady=10)
label2 = Label(stats, text="Your most played album is:")
label2.grid(row=1,pady=5)
label3 = Label(stats, text=f"{album} \n by {artist}")
label3.grid(row=2)
label4 = Label(stats, text=f"Your most listened to song on {album} is {song}")
label4.grid(row=3,pady=10)
# shows most played song for the selected source
class Source_Details():
def __init__(self,stats,source,song, plays):
self.master = stats
self.source = source
self.song = song
stats.title("Source Statistics")
stats.geometry("300x200+100+100")
label = Label(stats, text=f'{source} Statistics')
label.grid(row=0, pady=10)
label3 = Label(stats, text=f"Your most frequent song on {source} is:")
label3.grid(row=2)
label4 = Label(stats, text=f"{song} with {plays} plays")
label4.grid(row=3)
# Displays most played song for each session
class Session_Details():
def __init__(self,stats,session,song, plays):
self.master = stats
self.session = session
self.song = song
stats.title("Session Statistics")
stats.geometry("300x200+100+100")
label = Label(stats, text=f'{session} Statistics')
label.grid(row=0, pady=10)
label3 = Label(stats, text=f"Your most frequent song during {session} was:")
label3.grid(row=2)
label4 = Label(stats, text=f"{song} with {plays} plays")
label4.grid(row=3)
|
PHP
|
UTF-8
| 504
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* Created by PhpStorm.
* User: dgreenberg
* Date: 4/6/16
* Time: 9:37 AM
*/
namespace Code_Alchemy\DateTime;
use Code_Alchemy\Core\Boolean_Value;
/**
* Class Is_Date_Past
* @package Code_Alchemy\DateTime
*
* Is this date in the past?
*/
class Is_Date_Past extends Boolean_Value{
/**
* Is_Date_Past constructor.
* @param $datestring
*/
public function __construct( $datestring ) {
$this->boolean_value = $datestring < date('Y-m-d H:i:s');
}
}
|
TypeScript
|
UTF-8
| 3,710
| 2.59375
| 3
|
[] |
no_license
|
import * as sqlite3 from "sqlite3";
import * as moment from "moment";
import { Conf } from "./conf";
//sqlite3.verbose();
export class Pagesdb {
private static tabname = "pages";
private static filename = "pages.db";
private static db;
static init() {
return new Promise(resolve => {
sqlite3.verbose();
this.db = new sqlite3.Database(Pagesdb.filename);
let db = this.db;
let exists = 0;
db.serialize(() => {
db.all("SELECT * FROM sqlite_master WHERE name='" + Pagesdb.tabname + "' AND type='table'", (err: Error, rows: any[]) => {
exists = rows.length;
if (exists <= 0) {
db.run("CREATE TABLE " + Pagesdb.tabname + " (url TEXT PRIMARY KEY, created TEXT)", (e) => {
if (e != null) {
Conf.procLog("pagesdb", "cannot create table");
Conf.pdException("pagesdb", e);
}
resolve("init");
});
} else {
resolve("no");
}
});
});
});
}
static putPage(url: string) {
return new Promise(resolve => {
let db = Pagesdb.db;
db.serialize(() => {
// 登録なのでstateはpre
let q = "INSERT INTO " + Pagesdb.tabname + " (url, created) VALUES ('" + url + "', '" + moment().format("YYYY-MM-DD HH:mm:ss") + "')";
db.run(q, (e) => {
if (e != null) {
Conf.pdException("pagesdb", "err ins : " + e + " " + q);
}
Conf.procLog("pagesdb", "ins : " + q);
resolve();
});
});
});
}
static noPage(url: string) {
return new Promise(resolve => {
let db = Pagesdb.db;
let q = "SELECT * FROM " + Pagesdb.tabname + " WHERE url = '" + url + "'";
db.serialize(() => {
db.get(q, (err: Error, row: any) => {
Conf.procLog("pagesdb", "has ? " + q);
if (err == null) {
if (row == undefined) {
resolve(true); // 行が見つからなかったので初めて。
} else {
resolve(false); // 行が見つかったので既知。
}
} else {
Conf.pdException("pagesdb", err);
resolve(false); // エラーは既知扱い
}
});
});
});
}
static close() {
Pagesdb.db.close();
}
static run(q: string): Promise<any> {
return new Promise(resolve => {
let db = Pagesdb.db;
db.serialize(() => {
db.run(q, (e) => {
if (e != null) {
Conf.pdException("pagesdb", "err ins : " + e + " " + q);
}
Conf.procLog("pagesdb", "ins : " + q);
resolve();
});
});
});
}
static all(q: string): Promise<any> {
return new Promise(resolve => {
let db = Pagesdb.db;
db.serialize(() => {
db.all(q, (err: Error, rows: any) => {
for(let row of rows) {
console.log(row);
}
});
});
});
}
}
|
Java
|
UTF-8
| 166
| 1.867188
| 2
|
[] |
no_license
|
package ae.co.comtrust.payment.IPG.SPIj;
public class TransactionException
extends Exception
{
public TransactionException(String msg)
{
super(msg);
}
}
|
Python
|
UTF-8
| 357
| 3.3125
| 3
|
[] |
no_license
|
#!/usr/bin/env python3
import pandas as pd
def subsetting_by_positions():
df = pd.read_csv("UK-top40-1964-1-2.tsv", sep='\t',
usecols=["Title", "Artist"])
return df.iloc[0:10]
def main():
top_10 = subsetting_by_positions()
print(top_10)
print(f"Shape = {top_10.shape}")
if __name__ == "__main__":
main()
|
Ruby
|
UTF-8
| 237
| 2.734375
| 3
|
[] |
no_license
|
h,w,k = gets.chomp.split.map(&:to_i)
chos = h.times.map{gets.chomp.split.map(&:to_i)}
(2 ** (h-1)).times do |n|
sum = 0
idx = Array.new(h, 0)
(h-1).times do |j|
sum += n[j]
idx[j+1] = idx[j] + n[j]
end
p sum
p idx
end
|
Python
|
UTF-8
| 5,125
| 2.625
| 3
|
[] |
no_license
|
import datetime
from typing import List
from flask import Flask, jsonify, request, abort
from recommender.RecommenderClient import RecommenderClient
from data_import.AmadeusClient import AmadeusClient
from planner.PlannerClient import GoogleMapsClient
import pickle
import settings
import sys
import json
import logging
app = Flask(__name__)
logger = logging.getLogger(__name__)
settings.load_dotenv()
client = RecommenderClient()
ac = AmadeusClient()
google = GoogleMapsClient()
data = pickle.load(open("final_data.pkl", "rb"))
client.add_data(data.get("data"), create_model=True)
client.cities_added.union(data.get("cities"))
def checkCitysAndAdd(city_iatas: List[str]) -> List[str]:
"""Checks if cities contained in recommender data and add data
:param city_iatas: iata codes for cities to add to recommender
:return:
"""
city_names = []
for city in city_iatas:
if not city in client.cities_added:
logger.debug(f"City {city} not in data, performing lookup and adding to data")
city_name = ac.get_city_iata(city)
city_names.append(city_name)
lat_long = google.getLatLongCity(city_name)
tmp_data = ac.get_poi(lon=lat_long.get("lng"), lat=lat_long.get("lat"), name=city)
data['data'] += tmp_data
data['cities'] += city
client.add_data(tmp_data, city=city, create_model=False)
else:
logger.debug(f"City {city} is already contained in recommenderModel")
logger.debug("Storing new data in pkl file")
pickle.dump(data, open("final_data.pkl", "wb"))
logger.debug("Creating model with new data")
client.create_model()
return city_names
@app.route("/")
def index():
return "Take a look a the Readme.md :]"
@app.route("/getPOI")
def getPOI() -> List[dict]:
"""
:keyword limit: set limit for returned POI's, defaults to 10
:return: List of POI's
"""
limit = request.args.get("limit", 10)
return jsonify(client.cold_start(k=limit))
@app.route("/getRecommendations")
def getRecommendations():
likes = request.args.get("likes")
limit = request.args.get("limit", 10)
if not likes:
abort(400, "Missing parameter likes")
try:
likes = json.loads(likes)
except json.JSONDecodeError as e:
print(e)
abort(400, "Invalid data in likes parameter")
result = client.suggest(k=limit, likes=likes)
return jsonify(client.recs2data(result, df=False))
@app.route("/getIATA")
def getIATA():
"""Returns IATA code for given city
:keyword: city: city to return IATA code for
"""
return ac.get_iata_city(request.args.get("city"))
@app.route("/getCITY")
def getCITY():
"""Returns city name for given IATA code
:keyword: iata: iata code to get city for
"""
return ac.get_city_iata(request.args.get("iata"))
@app.route("/generateInspiration")
def generateInspiration():
"""
:keyword: likes: List of likes corresponing with indecies of POI's
:keyword: origin: IATA Code from where flight should originate from, defaults to LON
:keyword: budget: limit recommended flights to flights inside budget
:keyword: limit_activities: limit amount of recommended activities per city, defaults to 10
:keyword: limit_inspirations: limit amount of inspirations, defaults to 10
:return: -
"""
likes = request.args.get("likes")
origin = request.args.get("origin", "LON")
budget = request.args.get("budget")
limit_inspirations = int(request.args.get("limit_inspirations", 10))
limit_activities = int(request.args.get("limit_activities", 10))
startdate = request.args.get("startdate")
if not likes:
abort(400, "Missing parameter likes")
try:
likes = json.loads(likes)
except json.JSONDecodeError as e:
print(e)
abort(400, "Invalid data in likes parameter")
if startdate:
startdate = datetime.datetime.strptime(startdate, "%Y-%m-%d")
cities = ac.get_inspiration(origin, maxPrice=budget, limit=limit_inspirations,
startdate=startdate)
city_iata_codes = [city.get("destination") for city in cities]
city_names = checkCitysAndAdd(city_iata_codes)
for index, city in enumerate(cities):
cities[index]["city-name"] = city_names[index]
recommendations = client.suggest(likes=likes, cities=city.get("destination"), k=limit_activities)
recommendations_dict = client.recs2data(recommendations, df=False)
cities[index]["activities"] = recommendations_dict
cities[index]["itinerary"] = google.generate_itinerary(recommendations_dict)
return jsonify(cities)
if __name__ == "__main__":
root = logging.getLogger()
root.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
root.addHandler(handler)
app.run("0.0.0.0", 8080, debug=False, threaded=True)
|
Java
|
UTF-8
| 3,366
| 2.25
| 2
|
[] |
no_license
|
package com.familyedu.student;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.familyedu.ActivityBase;
import com.familyedu.R;
import com.familyedu.tools.Utilities;
/**
*
* @author Administrator
* 提问
*/
public class EduQuizActivity extends ActivityBase implements OnClickListener{
private Button back, go_composition; // 返回, 写作文
private Button grade, subject; // 年级, 学科
private EditText iTitle, iCon; // 问题标题, 问题内容
private Button addPic, addrecord; // 添加图片, 录音
private ImageView picflag, recordflag; // 添加图片标识,添加录音标识
private Button save, submit; // 保存问题, 提交问题
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.student_quiz);
initView();
}
private void initView() {
back = (Button) findViewById(R.id.back); // 返回
back.setOnClickListener(this);
go_composition = (Button) findViewById(R.id.go_composition); // 写作文
go_composition.setOnClickListener(this);
grade = (Button) findViewById(R.id.grade); // 年级
grade.setOnClickListener(this);
subject = (Button) findViewById(R.id.subject); // 学科
subject.setOnClickListener(this);
iTitle = (EditText) findViewById(R.id.iTitle); // 问题标题
iCon = (EditText) findViewById(R.id.iCon); // 问题内容
addPic = (Button) findViewById(R.id.addPic); // 添加图片
addPic.setOnClickListener(this);
addrecord = (Button) findViewById(R.id.addrecord); // 添加录音
addrecord.setOnClickListener(this);
picflag = (ImageView) findViewById(R.id.picflag); // 添加图片标识
recordflag = (ImageView) findViewById(R.id.recordflag); // 添加录音标识
save = (Button) findViewById(R.id.save); // 保存问题
save.setOnClickListener(this);
submit = (Button) findViewById(R.id.submit); // 提交问题
submit.setOnClickListener(this);
}
// 捕捉回退键,是否真的退出该程序
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK){
return false;
}else{
return super.onKeyDown(keyCode, event);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.back: // 返回
this.finish();
break;
case R.id.go_composition: // 写作文
startActivity(new Intent(this,EduCompositionActivity.class ));
break;
case R.id.grade: // 年级
Utilities.showToast(this, "年级");
break;
case R.id.subject: // 学科
Utilities.showToast(this, "学科");
break;
case R.id.addPic: // 添加图片
Utilities.showToast(this, "添加图片");
break;
case R.id.addrecord: // 添加录音
Utilities.showToast(this, "添加录音");
break;
case R.id.save: // 保存问题
Utilities.showToast(this, "保存问题");
break;
case R.id.submit: // 提交问题
Utilities.showToast(this, "提交问题");
break;
default:
break;
}
}
}
|
Python
|
UTF-8
| 2,388
| 2.921875
| 3
|
[
"MIT",
"LicenseRef-scancode-w3c-03-bsd-license",
"BSD-3-Clause",
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"Apache-2.0"
] |
permissive
|
# -*- coding: utf-8 -*-
from __future__ import generators
import py
import sys
saferepr = py.io.saferepr
class TestSafeRepr:
def test_simple_repr(self):
assert saferepr(1) == '1'
assert saferepr(None) == 'None'
def test_maxsize(self):
s = saferepr('x'*50, maxsize=25)
assert len(s) == 25
expected = repr('x'*10 + '...' + 'x'*10)
assert s == expected
def test_maxsize_error_on_instance(self):
class A:
def __repr__(self):
raise ValueError('...')
s = saferepr(('*'*50, A()), maxsize=25)
assert len(s) == 25
assert s[0] == '(' and s[-1] == ')'
def test_exceptions(self):
class BrokenRepr:
def __init__(self, ex):
self.ex = ex
foo = 0
def __repr__(self):
raise self.ex
class BrokenReprException(Exception):
__str__ = None
__repr__ = None
assert 'Exception' in saferepr(BrokenRepr(Exception("broken")))
s = saferepr(BrokenReprException("really broken"))
assert 'TypeError' in s
if py.std.sys.version_info < (2,6):
assert 'unknown' in saferepr(BrokenRepr("string"))
else:
assert 'TypeError' in saferepr(BrokenRepr("string"))
s2 = saferepr(BrokenRepr(BrokenReprException('omg even worse')))
assert 'NameError' not in s2
assert 'unknown' in s2
def test_big_repr(self):
from py._io.saferepr import SafeRepr
assert len(saferepr(range(1000))) <= \
len('[' + SafeRepr().maxlist * "1000" + ']')
def test_repr_on_newstyle(self):
class Function(object):
def __repr__(self):
return "<%s>" %(self.name)
try:
s = saferepr(Function())
except Exception:
py.test.fail("saferepr failed for newstyle class")
def test_unicode(self):
val = py.builtin._totext('£€', 'utf-8')
reprval = py.builtin._totext("'£€'", 'utf-8')
assert saferepr(val) == reprval
def test_unicode_handling():
value = py.builtin._totext('\xc4\x85\xc4\x87\n', 'utf-8').encode('utf8')
def f():
raise Exception(value)
excinfo = py.test.raises(Exception, f)
s = str(excinfo)
if sys.version_info[0] < 3:
u = unicode(excinfo)
|
Java
|
UTF-8
| 1,748
| 2.390625
| 2
|
[] |
no_license
|
package domain;
import java.util.Date;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
@Access(AccessType.PROPERTY)
public class Invoice extends DomainEntity {
// Constructors -----------------------------------------------------------
public Invoice() {
super();
}
// Attributes -------------------------------------------------------------
private Date authoredMoment;
private String vatNumber;
private String information;
private String details;
private Double total;
@NotNull
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "dd/MM/yyyy HH:mm")
public Date getAuthoredMoment() {
return authoredMoment;
}
public void setAuthoredMoment(Date authoredMoment) {
this.authoredMoment = authoredMoment;
}
@NotBlank
public String getVatNumber() {
return vatNumber;
}
public void setVatNumber(String vatNumber) {
this.vatNumber = vatNumber;
}
public String getInformation() {
return information;
}
public void setInformation(String information) {
this.information = information;
}
@NotBlank
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
@NotNull
public Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
// Relationships ----------------------------------------------------------
}
|
Markdown
|
UTF-8
| 4,121
| 2.671875
| 3
|
[] |
no_license
|
---
description: "Step-by-Step Guide to Make Perfect Boneless Root Beer Pork Ribs"
title: "Step-by-Step Guide to Make Perfect Boneless Root Beer Pork Ribs"
slug: 1535-step-by-step-guide-to-make-perfect-boneless-root-beer-pork-ribs
date: 2020-09-14T15:34:32.937Z
image: https://img-global.cpcdn.com/recipes/5968677107138560/751x532cq70/boneless-root-beer-pork-ribs-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/5968677107138560/751x532cq70/boneless-root-beer-pork-ribs-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/5968677107138560/751x532cq70/boneless-root-beer-pork-ribs-recipe-main-photo.jpg
author: Lida Wong
ratingvalue: 4.4
reviewcount: 14256
recipeingredient:
- "8 thick finger sized boneless country pork ribs"
- "2 cup root beer"
- "1 tbsp malt vinegar"
- "2 tsp onion powder"
- "2 tsp garlic powder"
- "1 1/2 tsp vanilla extract"
- "1/2 tsp ground cardamom"
- "1/2 tsp ground coriander seed"
- "1/2 tsp white pepper"
- "3/4 cup rum"
- "2/3 cup bbq sauce"
- "1 pinch salt"
- "1 vegetable oil as needed"
recipeinstructions:
- "Marinate pork in one cup of root beer for 4-48 hours. Drain and pat dry."
- "Reduce rum in a saucepan by 1/2. Be careful of the flames! Add one cup of root beer, vanilla extract, and vinegar. Reduce by 1/2. Add bbq sauce and stir to incorporate."
- "Place pork in a large mixing bowl. Toss with enough oil to cover. Add dried spices. Grill until pork reaches desired doneness. Brush with bbq sauce."
- "Variations; Coconut, horseradish, parsley, cilantro, mustard, cola, espresso powder, tamarind, coffee,"
categories:
- Recipe
tags:
- boneless
- root
- beer
katakunci: boneless root beer
nutrition: 108 calories
recipecuisine: American
preptime: "PT12M"
cooktime: "PT56M"
recipeyield: "1"
recipecategory: Dessert
---

Hello everybody, I hope you're having an amazing day today. Today, we're going to prepare a special dish, boneless root beer pork ribs. One of my favorites. This time, I'm gonna make it a bit unique. This will be really delicious.
Boneless Root Beer Pork Ribs is one of the most favored of recent trending foods on earth. It is appreciated by millions every day. It is simple, it's fast, it tastes yummy. They are nice and they look wonderful. Boneless Root Beer Pork Ribs is something which I have loved my entire life.
To get started with this recipe, we have to first prepare a few ingredients. You can have boneless root beer pork ribs using 13 ingredients and 4 steps. Here is how you can achieve it.
<!--inarticleads1-->
##### The ingredients needed to make Boneless Root Beer Pork Ribs:
1. Prepare 8 thick finger sized boneless country pork ribs
1. Get 2 cup root beer
1. Take 1 tbsp malt vinegar
1. Make ready 2 tsp onion powder
1. Prepare 2 tsp garlic powder
1. Get 1 1/2 tsp vanilla extract
1. Take 1/2 tsp ground cardamom
1. Prepare 1/2 tsp ground coriander seed
1. Prepare 1/2 tsp white pepper
1. Take 3/4 cup rum
1. Take 2/3 cup bbq sauce
1. Make ready 1 pinch salt
1. Get 1 vegetable oil; as needed
<!--inarticleads2-->
##### Steps to make Boneless Root Beer Pork Ribs:
1. Marinate pork in one cup of root beer for 4-48 hours. Drain and pat dry.
1. Reduce rum in a saucepan by 1/2. Be careful of the flames! Add one cup of root beer, vanilla extract, and vinegar. Reduce by 1/2. Add bbq sauce and stir to incorporate.
1. Place pork in a large mixing bowl. Toss with enough oil to cover. Add dried spices. Grill until pork reaches desired doneness. Brush with bbq sauce.
1. Variations; Coconut, horseradish, parsley, cilantro, mustard, cola, espresso powder, tamarind, coffee,
So that's going to wrap it up for this special food boneless root beer pork ribs recipe. Thanks so much for reading. I am sure that you will make this at home. There is gonna be interesting food at home recipes coming up. Don't forget to save this page on your browser, and share it to your family, friends and colleague. Thank you for reading. Go on get cooking!
|
Markdown
|
UTF-8
| 2,626
| 2.828125
| 3
|
[] |
no_license
|
---
title: Excel2013:[46]如何绘制半圆饼图
date: 2015-01-23 18:03:03
tags: [excel]
author: mlln.cn
---
很多时候需要美化你的图表这样才能让人感觉你是一个有创意的员工,是一个对工作有激情的员工。额。。好吧,其实这句话我也不信,但信不信由你,我现在开始讲如何绘制一个半圆的饼图。
- 先来看一下我的数据,下面要对这些数据绘制半圆饼图;先选中这些数据
{% asset_img 245e8bcad1c8a786a48d52616509c93d71cf50fe.jpg Excel2013:[46]如何绘制半圆饼图 %}
- 在插入一个饼图
{% asset_img eab9044c510fd9f9d6a84d06272dd42a2934a4e6.jpg Excel2013:[46]如何绘制半圆饼图 %}
- 这里是自动生成的一个饼图
{% asset_img 61183b2dd42a283432192e6459b5c9ea14cebfe6.jpg Excel2013:[46]如何绘制半圆饼图 %}
- 点击两次半圆的【总计】部分,选中它,然后右键单击它,选择填充【白色】
{% asset_img 3a86813df8dcd100cc3be04e708b4710b8122ffe.jpg Excel2013:[46]如何绘制半圆饼图 %}
- 好了,半圆饼图的雏形已经有了,我们接着要删除【总计】这个标签了。
{% asset_img bbe0d311728b4710c388e5a3c1cec3fdfd0323fe.jpg Excel2013:[46]如何绘制半圆饼图 %}
- 右键单击饼图,然后我们在这里可以看到有一个【设置图表区域格式】
{% asset_img 1a94b36eddc451da0a7c1484b4fd5266d1163293.jpg Excel2013:[46]如何绘制半圆饼图 %}
- 如何旋转饼图:来到这里,设置系列选项,我们设置第一扇区起始角度为270
{% asset_img 4651a712c8fcc3cebe67d15c9045d688d53f20fe.jpg Excel2013:[46]如何绘制半圆饼图 %}
- 看一下这一步我们的效果喽
{% asset_img b853d6fcc3cec3fd8299bf1ad488d43f869427fe.jpg Excel2013:[46]如何绘制半圆饼图 %}
- 如果你给它添加上标签会更好看
{% asset_img b74124f33a87e95024a8eb0312385343faf2b4e6.jpg Excel2013:[46]如何绘制半圆饼图 %}
- 接着可以再设置一下数据标签格式,也是在右键菜单中
{% asset_img d7c9ca3f8794a4c2f984ff440cf41bd5ac6e39fe.jpg Excel2013:[46]如何绘制半圆饼图 %}
- 在打开的选项中,我们设置为【值】而不是【百分比】,因为百分比是错误的百分比呀!
{% asset_img c71d0e385343fbf2a493be4cb27eca8064388fe6.jpg Excel2013:[46]如何绘制半圆饼图 %}
- 最终的效果就是它了。
{% asset_img 5202e5f2b2119313a8fce7df67380cd790238de6.jpg Excel2013:[46]如何绘制半圆饼图 %}
> 转载请注明来自[DataScience](http://mlln.cn).
> 邮箱: 675495787@qq.com
|
C
|
UTF-8
| 254
| 2.921875
| 3
|
[] |
no_license
|
#include <stdlib.h>
#include <stdio.h>
int main(){
char vendedor[30];
double salario, TOTAL;
scanf("%s %lf %lf", vendedor, &salario, &TOTAL);
TOTAL = TOTAL* 0.15 + salario;
printf("TOTAL = R$ %.2lf\n", TOTAL);
return 0;
}
|
SQL
|
UTF-8
| 2,828
| 3.65625
| 4
|
[
"MIT"
] |
permissive
|
CREATE DATABASE IF NOT EXISTS red_social;
USE red_social;
CREATE TABLE IF NOT EXISTS users (
id int(255) auto_increment not null,
role varchar(50),
name varchar(100),
surname varchar(100),
nick varchar(100),
email varchar(255),
password varchar(255),
image varchar(255),
created_at datetime,
updated_at datetime,
remember_token varchar(255),
CONSTRAINT pk_users PRIMARY KEY (id)
)Engine=InnoDb;
INSERT INTO users VALUES(
null,'user', 'Tomas', 'Marsili', 'tomas8801', 'tomasmarsili@hotmail.com', '123', null, CURTIME(), CURTIME(), null
);
INSERT INTO users VALUES(
null,'user', 'Emanuel', 'Marinelli', 'ema10', 'emanuel@hotmail.com', '1233', null, CURTIME(), CURTIME(), null
);
INSERT INTO users VALUES(
null,'user', 'Leandro', 'Mendez', 'lean20', 'leandromendez@hotmail.com', '1232', null, CURTIME(), CURTIME(), null
);
CREATE TABLE IF NOT EXISTS images (
id int(255) auto_increment not null,
user_id int(255),
image_path varchar(255),
description text,
created_at datetime,
updated_at datetime,
CONSTRAINT pk_images PRIMARY KEY(id),
CONSTRAINT fk_images_users FOREIGN KEY (user_id) REFERENCES users(id)
)Engine=InnoDb;
INSERT INTO images VALUES(
null, 1, 'yo.jpg','descripcion de prueba', CURTIME(), CURTIME()
);
INSERT INTO images VALUES(
null, 1, 'hola.jpg','otra descripcion', CURTIME(), CURTIME()
);
INSERT INTO images VALUES(
null, 2, 'caca.jpg','description yeah', CURTIME(), CURTIME()
);
INSERT INTO images VALUES(
null, 2, 'caca.jpg','description yeah', CURTIME(), CURTIME()
);
INSERT INTO images VALUES(
null, 3, 'see.jpg','description raaaal', CURTIME(), CURTIME()
);
CREATE TABLE IF NOT EXISTS comments (
id int(255) auto_increment not null,
user_id int(255),
image_id int(255),
content text,
created_at datetime,
updated_at datetime,
CONSTRAINT pk_comments PRIMARY KEY(id),
CONSTRAINT fk_comments_users FOREIGN KEY (user_id) REFERENCES users(id),
CONSTRAINT fk_comments_images FOREIGN KEY (image_id) REFERENCES images(id)
)Engine=InnoDb;
INSERT INTO comments VALUES(
null, 1, 4, 'Buena foto!!', CURTIME(), CURTIME()
);
INSERT INTO comments VALUES(
null, 1, 3, 'Lindoooo', CURTIME(), CURTIME()
);
INSERT INTO comments VALUES(
null, 2, 4, 'Que buena ondaaa', CURTIME(), CURTIME()
);
INSERT INTO comments VALUES(
null, 3, 2, 'Sos hermosooo', CURTIME(), CURTIME()
);
CREATE TABLE IF NOT EXISTS likes (
id int(255) auto_increment not null,
user_id int(255),
image_id int(255),
created_at datetime,
updated_at datetime,
CONSTRAINT pk_likes PRIMARY KEY(id),
CONSTRAINT fk_likes_users FOREIGN KEY (user_id) REFERENCES users(id),
CONSTRAINT fk_likes_images FOREIGN KEY (image_id) REFERENCES images(id)
)Engine=InnoDb;
INSERT INTO likes VALUES(
null, 1, 2,CURTIME(), CURTIME()
);
INSERT INTO likes VALUES(
null, 1, 3,CURTIME(), CURTIME()
);
INSERT INTO likes VALUES(
null, 2, 1,CURTIME(), CURTIME()
);
INSERT INTO likes VALUES(
null, 3, 2,CURTIME(), CURTIME()
);
|
SQL
|
UTF-8
| 3,773
| 3.734375
| 4
|
[] |
no_license
|
create schema if not exists securestore;
use securestore;
create table if not exists game (
game_id int(11) not null auto_increment primary key,
title varchar(50) not null,
esrb_rating varchar(50) not null,
description varchar(255) not null,
price decimal(5, 2) not null,
studio varchar(50) not null,
quantity int(11)
);
create table if not exists console (
console_id int(11) not null auto_increment primary key,
model varchar(50) not null,
manufacturer varchar(50) not null,
memory_amount varchar(20),
processor varchar(20),
price decimal(5, 2) not null,
quantity int(11) not null
);
create table if not exists t_shirt (
t_shirt_id int(11) not null auto_increment primary key,
size varchar(20) not null,
color varchar(20) not null,
description varchar(255) not null,
price decimal(5,2) not null,
quantity int(11) not null
);
create table if not exists invoice (
invoice_id int(11) not null auto_increment primary key,
name varchar(80) not null,
street varchar(30) not null,
city varchar(30) not null,
state varchar(30) not null,
zipcode varchar(5) not null,
item_type varchar(20) not null,
item_id int(11) not null,
unit_price decimal(5,2) not null,
quantity int(11) not null,
subtotal decimal(5,2) not null,
tax decimal(5,2) not null,
processing_fee decimal (5,2) not null,
total decimal(5,2) not null
);
create table if not exists sales_tax_rate (
state char(2) not null,
rate decimal(3,2) not null
);
create unique index ix_state_rate on sales_tax_rate (state, rate);
create table if not exists processing_fee (
product_type varchar(20) not null,
fee decimal (4,2)
);
create unique index ix_product_type_fee on processing_fee (product_type, fee);
INSERT into sales_tax_rate (state, rate) values ('AL', .05), ('AK', 06), ('AZ', .04), ('AR', .06), ('CA', .06), ('CO', .04), ('CT', .03),
('DE', .05), ('FL', .06), ('GA', .07), ('HI', .05), ('ID', .03), ('IL', .05), ('IN', .05), ('IA', .04), ('KS', .06), ('KY', .04), ('LA', .05),
('ME', .03), ('MD', .07), ('MA', .05), ('MI', .06), ('MN', .06), ('MS', .05), ('MO', .05), ('MT', .03), ('NE', .04), ('NV', .04), ('NH', .06), ('NJ', .05), ('NM', .05),
('NY', .06), ('NC', .05), ('ND', .05), ('OH', .04), ('OK', .04), ('OR', .07), ('PA', .06), ('RI', .06), ('SC', .06), ('SD', .06), ('TN', .05), ('TX', .03),
('UT', .04), ('VT', .07), ('VA', .06), ('WA', .05), ('WV', .05), ('WI', .03), ('WY', .04);
INSERT into processing_fee (product_type, fee) values ('Consoles', 14.99), ('T-Shirts', 1.98), ('Games', 1.49);
create table if not exists users(
username varchar(50) not null primary key,
password varchar(100) not null,
enabled boolean not null
);
create table if not exists authorities (
username varchar(50) not null,
authority varchar(50) not null,
constraint fk_authorities_users foreign key(username) references users(username));
create unique index ix_auth_username on authorities (username,authority
);
insert into users (username, password, enabled) values ('manager1103', '$2a$10$QPnaeWBWz1BdDglni2CLzO2YMeifVXtQDPgUOVNETTcj8cEGwqiym', true);
insert into users (username, password, enabled) values ('admin0321', '$2a$10$Hc878CPLJ4hOtwyzt6V7..LHtzhcR3zqcXOAPseY9QGg05ZxcsTR6', true);
insert into users (username, password, enabled) values ('staff1121', '$2a$10$KxTc8SYbIB/IaXCWz6NA4ug1pkAYM/e.P.0YQFGE3Ua4FZ6Qf842a', true);
insert into authorities (username, authority) values ('manager1103', 'ROLE_MANAGER');
insert into authorities (username, authority) values ('manager1103', 'ROLE_STAFF');
insert into authorities (username, authority) values ('admin0321', 'ROLE_ADMIN');
insert into authorities (username, authority) values ('admin0321', 'ROLE_STAFF');
insert into authorities (username, authority) values ('staff1121', 'ROLE_STAFF');
|
Java
|
UTF-8
| 562
| 1.84375
| 2
|
[] |
no_license
|
package com.wntime.customer.region;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.gemfire.mapping.annotation.Region;
/**
* @author 79448
* @date 2020/10/29 15:22
*/
@Setter
@Getter
@Region("bus_drive_station_info")
public class BusDriveStationInfo{
@Id
private Long busId;
private Long companyLineId;
private Long stationId;
/**
* 途经站点状态 0 在当前站 1 驶离当前站
*/
private int stationStatus;
}
|
Python
|
UTF-8
| 2,893
| 3.3125
| 3
|
[] |
no_license
|
"""
Various utility functions for os and numpy related stuff
"""
import os
import sys
import numpy as np
# Numpy
def mysincf(x):
"""Numerically stable sinc function (sin(x)/x)
Input: x (float)
Output: z (float) - sin(x)/x, numerically stable around 0
"""
z = x if x != 0 else 1e-16
return np.sin(z) / z
def mysinc(x):
"""Numerically stable sinc function (sin(x)/x)
Input: x (numpy array)
Output: z (numpy array) - sin(x)/x, numerically stable around 0
"""
z = np.select(x == 0, 1e-16, x)
return np.sin(z) / z
def normalize(x):
"""Return the unit vector in the direction of x"""
return x / (1e-16 + np.linalg.norm(x))
def sph_rot(x):
"""Takes unit vector and create rotation matrix from it
Input: x (3x1 or 1x3 matrix)
Output:
- R (3x3 matrix) - rotation matrix such that dot(R,x) = x (not
deterministically made)
"""
x = x.reshape(-1)
u = normalize(np.random.randn(3))
R = np.array([
normalize(np.cross(np.cross(u,x),x)),
normalize(np.cross(u,x)),
x,
])
return R
def dim_norm(X):
"""Norms of the vectors along the last dimension of X
Input: X (NxM numpy array)
Output: X_norm (Nx1 numpy array) - norm of each row of X
"""
return np.expand_dims(np.sqrt(np.sum(X**2, axis=-1)), axis=-1)
def dim_normalize(X):
"""Return X with vectors along last dimension normalized to unit length
Input: X (NxM numpy array)
Output: X_norm (Nx1 numpy array) - norm of each row of X
"""
return X / dim_norm(X)
def planer_proj(X):
"""Return X divided by the last element of its dimension
Input: X (NxM numpy array)
Output: X_proj (NxM numpy array) - X with each row divided by its last element
"""
return X / np.expand_dims(X[...,-1], axis=-1)
# Miscellaneous
def str2bool(v):
"""Convert a string into a boolean
Input: v (string) - string to convert to boolean
Output: v_bool (boolean) - appropriate boolean matching the string
"""
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
import argparse
raise argparse.ArgumentTypeError('Boolean value expected.')
def next_file(directory, fname, suffix):
"""Returns name of file in directory with a number suffix incremented.
Input:
- directory (string) - name of directory that file will be in
- fname (string) - prefix to the number that will get incremented
- suffix (string) - file suffix (e.g. .png, .jpg, .txt)
Output: None
When this is called, it will check all files in directory with prefix fname
in order (i.e. fname000.png, fname001.png, etc.) until it hits the highest
number and then returns the value with a number 1 higher than that.
"""
fidx = 1
name = lambda i: os.path.join(directory,"{}{:03d}{}".format(fname,i,suffix))
while os.path.exists(name(fidx)):
fidx += 1
return name(fidx)
|
Markdown
|
UTF-8
| 2,448
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
# axios-case-converter
[](https://badge.fury.io/js/axios-case-converter)
[](https://travis-ci.org/mpyw/axios-case-converter)
Axios transformer/interceptor that converts _snake_case/camelCase_
- Converts outgoing `data` `params` object keys into _snake_case_
- Converts incoming `data` object keys into _camelCase_
- Converts outgoing `headers` object keys into _Header-Case_
- Converts incoming `headers` object keys into _camelCase_
## Usage
You can fully use _camelCase_.
```js
import applyConverters from 'axios-case-converter';
import axios from 'axios';
(async () => {
const client = applyConverters(axios.create());
const { data } = await client.post(
'https://example.com/api/endpoint',
{
targetId: 1
},
{
params: { userId: 1 },
headers: { userAgent: 'Mozilla' }
}
);
console.log(data.actionResult.users[0].screenName);
})();
```
## Attention
### `FormData` compatibility
If you use `FormData` on **Internet Explorer** or **Safari**, you need polyfill of `FormData.prototype.entries()`.
- [jimmywarting/FormData: HTML5 `FormData` polyfill for Browsers.](https://github.com/jimmywarting/FormData)
If you use `FormData` on **React Native**, please ignore the following warnings after confirming that polyfill is **impossible**.
```js
// RN >= 0.52
import { YellowBox } from 'react-native';
YellowBox.ignoreWarnings([
'Be careful that FormData cannot be transformed on React Native.'
]);
// RN < 0.52
console.ignoredYellowBox = [
'Be careful that FormData cannot be transformed on React Native.'
];
```
### `Symbol` compatibility
If you use **React Native** for **Android** development, you should use **Symbol** polyfill from `core-js` to avoid bugs with iterators:
1. Create `polyfill.js` in root directory with code:
```js
global.Symbol = require('core-js/es6/symbol');
require('core-js/fn/symbol/iterator');
```
2. Include `polyfill.js` in entry point of your app (e.g. `app.js`):
```js
import { Platform } from 'react-native';
// ...
if (Platform.OS === 'android') {
require('./polyfill.js');
}
```
cf. [undefined is not a function(evaluating '_iterator\[typeof Symbol === "function"?Symbol.iterator:"@@iterator"\]()') · Issue #15902 · facebook/react-native](https://github.com/facebook/react-native/issues/15902)
|
Python
|
UTF-8
| 41
| 2.609375
| 3
|
[] |
no_license
|
# int 类型
i = 5
print(i.bit_length())
|
Java
|
UTF-8
| 813
| 2.21875
| 2
|
[] |
no_license
|
package co.edu.uniandes.centralAbastos.vos;
public class PedidoLocalValue
{
String idPedido;
double cantdadNeta;
String deadline;
String correoAdmin;
String codigoLocal;
public PedidoLocalValue(String idPedido, double cantdadNeta,
String deadline, String correoAdmin, String codigoLocal) {
super();
this.idPedido = idPedido;
this.cantdadNeta = cantdadNeta;
this.deadline = deadline;
this.correoAdmin = correoAdmin;
this.codigoLocal = codigoLocal;
}
public String getIdPedido() {
return idPedido;
}
public double getCantdadNeta() {
return cantdadNeta;
}
public String getDeadline() {
return deadline;
}
public String getCorreoAdmin() {
return correoAdmin;
}
public String getCodigoLocal() {
return codigoLocal;
}
}
|
Java
|
UTF-8
| 9,191
| 2.234375
| 2
|
[] |
no_license
|
package com.example.carnote;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.carnote.model.AutoData;
import com.example.carnote.model.TankUpRecord;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class GasTankUpActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener
{
public static final String NEW_TANKUP_RECORD = "NEW_TANKUP_RECORD";
private static final String AUTO_DATA_OBJ = "AUTO_DATA_OBJ";
private EditText dateEditText;
private EditText mileageEditText;
private TextView litersEditTextLabel;
private EditText litersEditText;
private TextView costEditTextLabel;
private EditText costEditText;
private Button confirmButton;
private AutoData autoData;
private DateFormat dateFormat;
private TextView mileageEditTextLabel;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.gas_tank_up_layout);
obtainExtras();
if (savedInstanceState!=null)
{
autoData = (AutoData) savedInstanceState.get(AUTO_DATA_OBJ);
}
viewInit();
setTitle(getResources().getString(R.string.new_tankup));
}
private void obtainExtras() {
autoData = (AutoData) getIntent().getExtras().getSerializable(MainMenuActivity.SPECIAL_DATA);
}
private void viewInit() {
dateEditText = (EditText) findViewById(R.id.date);
mileageEditText = (EditText) findViewById(R.id.mileage);
mileageEditTextLabel = (TextView) findViewById(R.id.mileage_label);
litersEditText = (EditText) findViewById(R.id.liters);
litersEditTextLabel = (TextView) findViewById(R.id.liters_label);
costEditText = (EditText) findViewById(R.id.cost);
costEditTextLabel = (TextView) findViewById(R.id.cost_label);
confirmButton = (Button) findViewById(R.id.confirm);
dateEditText.setText(getCurrentDate());
dateEditText.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(GasTankUpActivity.this, GasTankUpActivity.this, year, month, day);
datePickerDialog.show();
}
});
confirmButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (validateMileage())
{
TankUpRecord tank = new TankUpRecord(getDateEditTextDate(), getMileageInteger(), getLitersInteger(), getCostInteger());
Intent intent = new Intent();
intent.putExtra(NEW_TANKUP_RECORD, tank);
setResult(Activity.RESULT_OK, intent);
finish();
}
}
});
mileageEditText.setOnFocusChangeListener(new View.OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
//Wyjscie z kontrolki
if (hasFocus == false)
{
validateMileage();
}
}
});
costEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus == false)
{
validateCost();
}
}
});
litersEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus == false)
{
validateLiters();
}
}
});
}
private boolean validateLiters()
{
if (TextUtils.isEmpty(litersEditText.getText().toString()))
{
litersEditTextLabel.setText("Podaj ilosć dolanych litrów");
litersEditTextLabel.setTextColor(getResources().getColor(R.color.red));
return false;
}else if (Integer.valueOf(litersEditText.getText().toString()) <= 0)
{
litersEditTextLabel.setText("Dolane litry musza być wartością dodatnią");
litersEditTextLabel.setTextColor(getResources().getColor(R.color.red));
return false;
} else
{
litersEditTextLabel.setText(getResources().getString(R.string.added_liters));
litersEditTextLabel.setTextColor(getResources().getColor(R.color.black));
return true;
}
}
private boolean validateCost()
{
if (TextUtils.isEmpty(costEditText.getText().toString()))
{
costEditTextLabel.setText("Podaj koszt");
costEditTextLabel.setTextColor(getResources().getColor(R.color.red));
return false;
}else if (Integer.valueOf(costEditText.getText().toString()) <= 0)
{
costEditTextLabel.setText("Podawaj zawsze dodatnią wartosć tankowania");
costEditTextLabel.setTextColor(getResources().getColor(R.color.red));
return false;
} else
{
costEditTextLabel.setText(getResources().getString(R.string.tank_cost));
costEditTextLabel.setTextColor(getResources().getColor(R.color.black));
return true;
}
}
private boolean validateMileage()
{
if (TextUtils.isEmpty(mileageEditText.getText().toString()))
{
mileageEditTextLabel.setText("Podaj przebieg");
mileageEditTextLabel.setTextColor(getResources().getColor(R.color.red));
return false;
}
if (Integer.valueOf(mileageEditText.getText().toString()) <=0)
{
mileageEditTextLabel.setText("Podaj wartość dodatnią przebiegu");
mileageEditTextLabel.setTextColor(getResources().getColor(R.color.red));
return false;
}
int size = autoData.getTankUpRecord().size();
if (autoData.getTankUpRecord().size()!=0)
{
Integer newMileage = Integer.valueOf(mileageEditText.getText().toString());
Integer oldMileage = autoData.getTankUpRecord().get(size - 1).getMileage();
if (newMileage <= oldMileage)
{
mileageEditTextLabel.setText("Wprowadzony przebieg jest równy lub mniejszy od wartości podanej w poprzendim tankowaniu, nie ma takiego cofania licznika!");
mileageEditTextLabel.setTextColor(getResources().getColor(R.color.red));
return false;
}else
{
mileageEditTextLabel.setText(getResources().getString(R.string.mileage));
mileageEditTextLabel.setTextColor(getResources().getColor(R.color.black));
return true;
}
}
return true;
}
private Date getDateEditTextDate()
{
try {
return dateFormat.parse(dateEditText.getText().toString());
} catch (ParseException e)
{
e.printStackTrace();
}
dateFormat = DateFormat.getDateInstance();
Date date = new Date();
return date;
}
private Integer getCostInteger() {
return Integer.valueOf(costEditText.getText().toString());
}
private Integer getLitersInteger() {
return Integer.valueOf(litersEditText.getText().toString());
}
private Integer getMileageInteger() {
return Integer.valueOf(mileageEditText.getText().toString());
}
private String getCurrentDate()
{
dateFormat = DateFormat.getDateInstance();
Date date = new Date();
return dateFormat.format(date);
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
outState.putSerializable(AUTO_DATA_OBJ, autoData);
super.onSaveInstanceState(outState);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth)
{
Calendar calendar = new GregorianCalendar(year, month, dayOfMonth);
dateEditText.setText(dateFormat.format(calendar.getTime()));
}
}
|
C++
|
UTF-8
| 1,457
| 3.265625
| 3
|
[] |
no_license
|
#include <iostream>
#include <vector>
#include <range/v3/all.hpp>
template <typename T>
std::string print_vector (std::vector<T> & v)
{
std::cerr << "{ ";
for (auto & x : v) {
std::cerr << x << ", ";
}
std::cerr << '}';
return "";
}
//template <typename I, typename O>
//O sum (I range)
//{
// return ranges::accumulate(range, 0, std::plus<>());
//}
int main (void)
{
std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };
auto r1 = ranges::accumulate(v, 0, std::plus<>());
auto r2 = ranges::accumulate(v, 1, std::multiplies<>());
auto r3 = ranges::accumulate(v
| ranges::views::transform([] (int x) { return 2 * x; }),
0,
std::plus<>());
auto r4 = ranges::accumulate(v
| ranges::views::filter([] (int n) { return !(n & 0x1); })
| ranges::views::transform([] (int _) { (void)_; return 1; }),
0,
std::plus<>());
auto r5 = ranges::accumulate(v, 0, [] (int r, int _) { (void)_; return r + 1; });
std::cerr
<< "v = " << print_vector(v) << std::endl
<< "foldl (+) 0 v = " << r1 << std::endl
<< "foldl (*) 1 v = " << r2 << std::endl
<< "foldl (+) 0 . map (*2) $ v = " << r3 << std::endl
<< "foldl (+) 0 . map (const 1) . filter ((==0) . (flip mod 2)) $ v = " << r4 << std::endl
<< "foldl (curry ((+1) . fst)) 0 v = " << r5 << std::endl;
;
return 0;
}
|
C++
|
UTF-8
| 722
| 2.828125
| 3
|
[] |
no_license
|
/*
* CompositeGameObject.cpp
*
* Created on: May 1, 2012
* Author: max
*/
#include "CompositeGameObject.h"
CompositeGameObject::CompositeGameObject() :
// sorting algorithm: by z-index, then by ptr value (who cares)
gameObjects(
[](GameObjectShared a, GameObjectShared b) {
return a->getZ() < b->getZ() ? true : a < b;
}
)
{ }
CompositeGameObject::~CompositeGameObject() {
for(GameObjectShared gameObject : gameObjects)
gameObject->setParent(0);
}
void CompositeGameObject::paint() {
for(auto& gameObject : gameObjects)
gameObject->paint();
}
void CompositeGameObject::addChild(const GameObjectShared& s) {
gameObjects.insert(s);
s->setParent(shared_from_this());
}
|
Java
|
UTF-8
| 4,203
| 2.09375
| 2
|
[] |
no_license
|
package myApp.service.sys;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import myApp.client.sys.model.RoleMenuModel;
import myApp.frame.service.ServiceRequest;
import myApp.frame.service.ServiceResult;
import myApp.frame.ui.AbstractDataModel;
public class RoleMenu {
String mapperName = "sys07_role_menu";
public void selectByUserId(SqlSession sqlSession, ServiceRequest request,
ServiceResult result) {
Long userId = request.getLong("userId");
List<AbstractDataModel> roleMenuList = getChildByUserId(sqlSession, userId, Long.parseLong("0"));
result.setRetrieveResult(roleMenuList.size(), "사용자별 메뉴 조회", roleMenuList);
}
private List<AbstractDataModel> getChildByUserId(SqlSession sqlSession, Long userId, Long parentId ){
Map<String, Long> param = new HashMap<String, Long>();
param.put("userId", userId);
param.put("parentId", parentId);
List<AbstractDataModel> roleMenuList
= sqlSession.selectList(this.mapperName + ".selectByUserId", param);
for(AbstractDataModel child : roleMenuList){
RoleMenuModel roleMenuModel = (RoleMenuModel)child;
List<AbstractDataModel> childList = getChildByUserId(sqlSession, userId, roleMenuModel.getMenuId());
roleMenuModel.setChildList(childList);
}
return roleMenuList ;
}
public void selectByCheckedRoot(SqlSession sqlSession, ServiceRequest request, ServiceResult result) {
// 전체 메뉴 리스트에 해당 role에서 사용할 수 있는 정보를 추가로 받는다.
Long roleId = request.getLong("roleId");
List<AbstractDataModel> roleObjectList = getCheckedChild(sqlSession, Long.parseLong("0"), roleId);
result.setRetrieveResult(roleObjectList.size(), "하위메뉴 조회", roleObjectList);
}
private List<AbstractDataModel> getCheckedChild(SqlSession sqlSession, Long parentId, Long roleId ){
Map<String, Long> param = new HashMap<String, Long>();
param.put("parentId", parentId);
param.put("roleId", roleId);
List<AbstractDataModel> roleObjectList
= sqlSession.selectList(mapperName + ".selectByCheckedRole", param);
for(AbstractDataModel child : roleObjectList){
RoleMenuModel roleMenuModel = (RoleMenuModel)child;
List<AbstractDataModel> childList = getCheckedChild(sqlSession, roleMenuModel.getMenuId(), roleId);
roleMenuModel.setChildList(childList);
}
return roleObjectList ;
}
public void update(SqlSession sqlSession, ServiceRequest request, ServiceResult result) {
Long roleId = request.getLong("roleId");
System.out.println("role id is " + roleId);
List <AbstractDataModel> list = request.getList();
List<AbstractDataModel> updateList = new ArrayList<AbstractDataModel>();
for(AbstractDataModel data : list){
RoleMenuModel roleMenuModel = (RoleMenuModel)data;
Map<String, Object> updateModel = new HashMap<String, Object>();
if(roleMenuModel.getRoleMenuId() == null){
// insert role menu
roleMenuModel.setRoleMenuId(sqlSession.selectOne("getSeq"));
roleMenuModel.setRoleId(roleId);
updateModel.put("roleMenuId", roleMenuModel.getRoleMenuId());
updateModel.put("roleId", roleMenuModel.getRoleId());
updateModel.put("menuId", roleMenuModel.getMenuId());
updateModel.put("useYn", roleMenuModel.getUseYn());
updateModel.put("note", roleMenuModel.getMenuName());
sqlSession.insert(this.mapperName + ".insert", updateModel);
}
else {
// update
updateModel.put("roleMenuId", roleMenuModel.getRoleMenuId());
updateModel.put("roleId", roleMenuModel.getRoleId());
updateModel.put("menuId", roleMenuModel.getMenuId());
updateModel.put("useYn", roleMenuModel.getUseYn());
updateModel.put("note", roleMenuModel.getMenuName());
sqlSession.update(this.mapperName + ".update", updateModel);
}
updateList.add(sqlSession.selectOne(mapperName + ".selectById", roleMenuModel.getRoleMenuId()));
}
result.setRetrieveResult(1, "update success!", updateList);
}
}
|
Markdown
|
UTF-8
| 1,355
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
---
title: A new blog!
date: 2019-05-06
path: /new-blog
excerpt: Fingers crossed I can do something cool going forward.
draft: false
---
I've been rebuilding this site/blog for a little while. Moving from [Hugo](https://gohugo.io/) to [Gatsby](https://www.gatsbyjs.org/).
Hugo is absolutely excellent and I strongly encourage anyone to give it a try, but I personally prefer React as a UI framework and JSX as a templating language. Especially since it's what I spend most of my time at my day job using. So it made sense to re-write the blog using React, but it doesn't _really_ make sense to use for something like a blog that's not partocularly dynamic. Gatsby is a great static site generator and an excellent way to use React as a tool for component management and templating while maintaining speed and simplicity on the client.
That doesn't necessarily mean I'll only be writing about React (tho it'll probably be a lot of that). This is really just a platform to talk, mostly about web programming/platform stuff but possibly about a variety of other things. At the moment I've got a few projects underway: making my own keyboard, building a little thing to automatically performance test a website regularly, and making a little plant watering reminder. Those are what I've got so far but I'm sure more things will come along, they always do.
|
Go
|
UTF-8
| 1,004
| 3.5
| 4
|
[] |
no_license
|
package main
import (
"bufio"
"fmt"
"io"
"log"
"net/http"
"strconv"
"strings"
)
func sumFloatField(r io.Reader, s byte, p int) (int, float64) {
var (
count int
sum float64
)
reader := bufio.NewReader(r)
line, err := reader.ReadBytes(s) // avoid header
for {
line, err = reader.ReadBytes(s)
if err != nil {
break
}
strTip := strings.Split(string(line), ",")[p]
partialTip, err := strconv.ParseFloat(strTip, 64)
if err != nil {
log.Fatalf("can not convert to float")
return 0, 0.0
}
sum += partialTip
count++
}
return count, sum
}
// StreamSimple takes an URL and process their content by streaming
// count all lines and get average tip_amount (15th field of csv)
func StreamSimple(URL string) {
resp, err := http.Get(URL)
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
count, sum := sumFloatField(resp.Body, '\n', 15)
fmt.Printf("\nTotal lines: %d", count)
fmt.Printf("\nAverage Tip amount %0.4f\n", sum/float64(count))
}
|
Java
|
UTF-8
| 1,003
| 1.679688
| 2
|
[] |
no_license
|
package cc.dfsoft.project.biz.base.maintain.dao.impl;
import cc.dfsoft.project.biz.base.maintain.dao.AbandonedRecordDao;
import cc.dfsoft.project.biz.base.maintain.dao.DataCollationDao;
import cc.dfsoft.project.biz.base.maintain.dto.AbandonedRecordReq;
import cc.dfsoft.project.biz.base.maintain.entity.AbandonedRecord;
import cc.dfsoft.project.biz.base.maintain.entity.MenuDocument;
import cc.dfsoft.uexpress.common.dao.NewBaseDAO;
import cc.dfsoft.uexpress.common.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Desc: 类描述
* @Auther: zhangnx
* @Date: 2019/3/25 22:16
* @Version:1.0
*/
@Repository
public class dataCollationDaoImpl extends NewBaseDAO<MenuDocument, String> implements DataCollationDao {
}
|
PHP
|
UTF-8
| 2,492
| 2.703125
| 3
|
[] |
no_license
|
<!DOCTYPE html>
<html>
<head>
<title> Transcript </title>
<link rel="icon" type="image/png" href="images/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="images/favicon-16x16.png" sizes="16x16" />
<link rel = "stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<div style="display: inline-block;" class="menu-button">
<form action="menu.php"><input type="submit" value="Menu"/></form>
</div>
<h3> Search for Student Transcripts </h3>
<hr>
<form action="viewTransAdmin.php" method="post">
Enter student ID: <input type="text" name="uid">
<input type="submit" name="search" value="Search"> <br>
</form>
<?php
session_start();
// Send to login page if user is not logged in
if(!$_SESSION['loggedin']) {
header("Location: login.php");
die();
}
// Connect to database
$connection = mysqli_connect("localhost", "ARGv", "CSCI2541_sp19", "ARGv");
// Check connection
if(!$conn){
die("Connection failed: " . mysqli_connect_error());
}
// Declare empty variables for uid validation
$uid = "";
$uidErr = $tempErr = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["uid"])) {
$uidErr = "Please enter a UID";
} else {
$uid = test_value($_POST["uid"]);
// TODO: validate UID --> verify by database
}
}
// Search database for courses that match with input uid
$query = "select C.credits, C.section, C.name, C.courseno, C.day, C.tme, C.instructor, C.crn, C.location FROM course C, transcript T where '".$uid."'=T.uid AND T.crn=C.crn;";
$result = mysqli_query($conn, $query);
// Echo all courses associated with input uid
if(isset($_POST['search'])){
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
echo print_r($row) . "<br>";
}
} else {
$tempErr = "No courses registered";
echo $tempErr;
}
}
// Function to validate uid input
function test_value($input) {
$input = htmlspecialchars($input);
$input = stripslashes($input);
$input = trim($input);
return $input;
}
?>
</body>
</html>
|
Python
|
UTF-8
| 859
| 3.84375
| 4
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
反转链表
解题思路将使用虚拟before指针,将head的值依次传递给before,最终形成反转链表。
https://leetcode.com/explore/featured/card/recursion-i/251/scenario-i-recurrence-relation/2378/
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverse_list(self, head: ListNode) -> ListNode:
before = None
while head:
temp = head.next
head.next = before
before = head
head = temp
return before
# 测试方法
if __name__ == '__main__':
headNode = ListNode(1)
add = headNode
for i in range(2, 6):
add.next = ListNode(i)
add = add.next
solution = Solution()
solution.reverse_list(headNode)
|
C++
|
UTF-8
| 4,672
| 2.65625
| 3
|
[] |
no_license
|
#include "../include/menu.hpp"
#include "../include/game.hpp"
#include "../include/item.hpp"
#include <SFML/Graphics/Color.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Window/Mouse.hpp>
#include <cstdlib>
extern state currentState;
MainMenu::MainMenu(Game *game,sf::RenderWindow *window,std::string titleString,float titlePos_y,sf::Vector2f buttonPos,int padding) {
set(game,window, titleString, titlePos_y, buttonPos, padding);
}
void Menu::set(Game *game,sf::RenderWindow *window,std::string titleString,float titlePos_y,sf::Vector2f buttonPos,int padding) {
this->window = window;
this->padding = padding;
this->game = game;
this->titlePos_y = titlePos_y;
sourceCode.loadFromFile("Assets/SourceCodePro-SemiBoldItalic.ttf");
liberationMono.loadFromFile("Assets/LiberationMono-Regular.ttf");
adjustTittle(sf::Vector2f(window->getSize().x/2.0,titlePos_y),titleString);
addButtons();
adjustButtons(buttonPos - sf::Vector2f(0,Buttons[0]->getSize().y/2.0), padding);
}
void MainMenu::addButtons(){
int padding = 15;
Buttons.push_back(new Button(game,Exit,window,"Exit"));
Buttons.push_back(new Button(game,About,window, "About"));
Buttons.push_back(new Button(game,Level_Select,window, "Select Level"));
Buttons.push_back(new Button(game,Play,window, "Play"));
Items.push_back(new Item(window, sf::Vector2f(90.0, 45.0), "Assets/toggle.png", itemType::DayNight, sf::Vector2f(game->Width - padding - 45.0, game->Height - padding - 22.5)));
}
void Menu::adjustTittle(sf::Vector2f pos,std::string titleString,int size){
title = sf::Text(titleString, sourceCode, size);
title.setFillColor(game->getTextColor());
title.setLetterSpacing(0.75);
centerText(title, pos);
}
void Menu::centerText(sf::Text &txt, sf::Vector2f pos){
auto tmp = txt.getLocalBounds();
txt.setOrigin(tmp.left+tmp.width/2.0,tmp.top+tmp.height/2.0);
txt.setPosition(pos);
}
void Menu::adjustButtons(sf::Vector2f pos,int padding){
for(auto btn : Buttons) {
btn->setFont(liberationMono);
btn->setTextColor(game->curTextCol);
btn->setFontSize(40);
btn->setLetterSpacing(.75);
btn->fitBox();
btn->setPosition(pos);
pos.y -= btn->getSize().y + padding;
}
}
void Menu::draw() {
window->clear(game->getBGCol());
window->draw(title);
for(auto btn:Buttons)
btn->draw();
for(auto item:Items)
item->draw();
}
void MainMenu::action() {
mousePos = sf::Mouse::getPosition(*window);
for(auto btn:Buttons) {
if(btn->checkHover(mousePos) and sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
switch (btn->getButtonType()) {
case Play:
game->playButtonClicked = 1;
game->setState(state::inPlay);
break;
case Level_Select:
game->setState(state::inLevelSelect);
break;
case About:
game->setState(state::inAbout);
break;
case Exit:
game->setState(state::endProgram);
break;
default:
break;
}
}
}
for(auto item:Items) {
if(item->contains(mousePos) and sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
while(sf::Mouse::isButtonPressed(sf::Mouse::Left));
game->toggleDayNight();
item->setTextureRect(!game->day);
title.setFillColor(game->getTextColor());
}
}
}
Menu::~Menu() {
for(auto btn:Buttons)
delete btn;
for(auto item:Items)
delete item;
}
void MainMenu::setAboutPageText(){
std::string t = " A Way Out is a puzzle game where the\n player has to get to an end point from\n a starting point following a path\n that fills the whole 2D grid,\n in technical terms, the player\n has to find a hamiltonian path\n when the cells of the grid are\n nodes of a graph.";
adjustTittle(sf::Vector2f(window->getSize())/2.0f,t,20);
Item backBtn = Item(window,sf::Vector2f(40,40),"Assets/back.png",Back,sf::Vector2f(50,50));
window->draw(title);
if(backBtn.contains(sf::Mouse::getPosition(*window))){
backBtn.setTextureRect(1);
if(sf::Mouse::isButtonPressed(sf::Mouse::Left)){
adjustTittle(sf::Vector2f(window->getSize().x/2.0,titlePos_y), "A Way Out",62);
window->draw(title);
game->setState(state::inMenu);
}
} else {
backBtn.setTextureRect();
}
backBtn.draw();
}
|
JavaScript
|
UTF-8
| 550
| 2.75
| 3
|
[] |
no_license
|
describe("normalizeData", function () {
it("normalizeData function unit test", function () {
var personInfo1 = '{"Name": "Maria", "Id": 2111858,"Age":25}';
var personInfo2 = '{"Name": "Smith", "Id": 2234324,"Age":30}';
var norm1 = normalizeData(personInfo1);
var norm2 = normalizeData(personInfo2);
expect(norm1.name).toEqual("Maria");
expect(norm1.id).toEqual(2111858);
expect(norm2.name).toEqual("Maria");
expect(norm2.id).toEqual(2111858);
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.