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
Java
UTF-8
1,891
2.71875
3
[]
no_license
package com.study.week5.spring; import com.study.week5.spring.bean.Kclass; import com.study.week5.spring.bean.ManualSpringBean; import com.study.week5.spring.bean.School; import com.study.week5.spring.bean.Student; import com.study.week5.spring.manualwired.ManualSpringBeanConfig; import org.junit.jupiter.api.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * //TODO 添加类/接口功能描述 * * @author me-ht * @date 2021-06-01 */ public class SpringTest { @Test public void test() { //注解 annotationConfigBean(); //自定义schema cSchema(); } private static void annotationConfigBean() { AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(ManualSpringBeanConfig.class); ManualSpringBean annotationSpringBean = annotationConfigApplicationContext.getBean(ManualSpringBean.class); System.out.println("annotationSpringBean--->" + annotationSpringBean.getId() + ", " + annotationSpringBean.getName()); } private static void cSchema() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("week5/spring-cbean.xml"); Student student = applicationContext.getBean(Student.class); System.out.println("student--->" + student.getId() + ", " + student.getName() + ", " + student.getSex()); School school = applicationContext.getBean(School.class); System.out.println("school--->" + school.getId() + ", " + school.getName()); Kclass kclass = applicationContext.getBean(Kclass.class); System.out.println("kclass--->" + kclass.getId() + ", " + kclass.getName()); } }
Python
UTF-8
2,544
3.75
4
[]
no_license
# Udacity Data Structures and Algorithms # Part 2 - Data Structures # Project 2 - Problem #2 - File Recursion import os def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be. Args: suffix(str): suffix if the file name to be found path(str): path of the file system Returns: a list of paths """ if not os.path.exists(path): # Checks path string print("Invalid path.") return [] suffix = suffix.strip(".") # Strips out the dot from suffix param # Initialize a structure to accumulate .c files that are found found_dirs = set() # creates a list of entries in current path directory current_list = os.listdir(path) for entry in current_list: # formats a pathname including current directory and entry pathname = "{}\\{}".format(path, entry) # If the entry is a directory, it calls find_files() recursively if os.path.isdir(pathname): found_dirs = found_dirs.union(find_files(suffix, pathname)) # If the entry is a file and it has the given suffix, accumulate result if os.path.isfile(pathname): file_name, file_suffix = entry.rsplit(".", 1) if file_suffix == suffix: found_dirs.add(pathname) return found_dirs # Helper function to print the test results def print_result(result, description): print("\n\n") print(description) for item in result: print(item) description = "# Test Case 1: Testing the problem giving example" result = find_files(".c", ".\\2_Project\\P2 File Recursion\\testdir") print_result(result, description) description = "# Test Case 2: Other example" result = find_files(".c", ".\\2_Project\\P2 File Recursion\\testdir2") print_result(result, description) description = "# Test Case 2:Very deep file extrucute" result = find_files(".c", ".\\2_Project\\P2 File Recursion\\testdir3") print_result(result, description) description = "# Test Case 4: Empty directory" result = find_files(".c", ".\\2_Project\\P2 File Recursion\\testdir4") print_result(result, description) print("Nothing expected.") print("\n\n") print("# Test Case 5: Invalid path string. Directory does not exist.") result = find_files(".c", ".\\2_Project\\P2 File Recursion\\testdir5") print("Error message expected.") print("\n\n")
PHP
UTF-8
1,668
2.609375
3
[]
no_license
<?php $host = 'localhost'; $basededatos = 'toldosmty'; $usuario = 'root'; $contraseña = ''; $conexion = new mysqli($host, $usuario,$contraseña, $basededatos); if ($conexion -> connect_errno) { die("Fallo la conexion:(".$conexion -> mysqli_connect_errno().")".$conexion-> mysqli_connect_error()); } $tabla=""; $query="SELECT * FROM proveedor ORDER BY id_proveedor"; if(isset($_POST['alumnos'])) { $q=$conexion->real_escape_string($_POST['alumnos']); $query="SELECT * FROM proveedor WHERE id_proveedor LIKE '%".$q."%' OR nombre LIKE '%".$q."%' OR apellido LIKE '%".$q."%' OR referencia LIKE '%".$q."%' OR telefono LIKE '%".$q."%'"; } $buscarAlumnos=$conexion->query($query); if ($buscarAlumnos->num_rows > 0) { $tabla.= '<table class="table"> <tr class="bg-primary"> <td>Id Proveedor</td> <td>Nombre</td> <td>Apellido</td> <td>Referencia</td> <td>Telefono</td> <td>email</td> <td>Cargo</td> <td colspan="2">Acciones</td> </tr>'; while($filaAlumnos= $buscarAlumnos->fetch_assoc()) { $tabla.= '<tr> <td>'.$filaAlumnos['id_proveedor'].'</td> <td>'.$filaAlumnos['nombre'].'</td> <td>'.$filaAlumnos['apellido'].'</td> <td>'.$filaAlumnos['referencia'].'</td> <td>'.$filaAlumnos['telefono'].'</td> <td>'.$filaAlumnos['email'].'</td> <td>'.$filaAlumnos['cargo'].'</td> <td><a href="assets/update_prov.php?id='.$filaAlumnos["id_proveedor"].'">Modificar</a></td> <td><a href="assets/delprov.php?id='.$filaAlumnos["id_proveedor"].'">Eliminar</a></td> </tr> '; } $tabla.='</table>'; } else { $tabla="No se encontraron coincidencias con sus criterios de búsqueda."; } echo $tabla; ?>
Java
UTF-8
1,864
2.5
2
[]
no_license
package com.marsassignment.dto; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; @Entity public class PersonDTO implements Serializable{ /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) //@Column(name="pid") private Long pid; private String firstName; private String lastName; @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "person") private AddressDTO address; public PersonDTO() { } public PersonDTO(Long pid,String firstName,String lastName) { this.pid = pid; this.firstName = firstName; this.lastName = lastName; } public PersonDTO(String firstName,String lastName) { this.firstName = firstName; this.lastName = lastName; } public Long getPid() { return pid; } public void setPid(Long pid) { this.pid = pid; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public AddressDTO getAddress() { return address; } public void setAddress(AddressDTO address) { this.address = address; } @Override public String toString() { return "Person{" + "id=" + pid + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '}'; } }
Go
UTF-8
689
3.890625
4
[]
no_license
// You can think of it as an counterpart of try and catch in python package main import ("time" "fmt" "sync") var wg sync.WaitGroup func cleanup(){ defer wg.Done() if r:= recover(); r!=nil{// We assign recover() to r and check if it is nil or not fmt.Println("Recovered in cleanup", r) } } func say(s string){ defer cleanup() for i:=0; i<3; i++{ fmt.Println(s) time.Sleep(time.Millisecond*100) if i == 2 { panic("Oh dear a 2") } } } func main() { wg.Add(1)//Add a waitgroup before the go routine go say("Hey") wg.Add(1) go say("There") wg.Wait() wg.Add(1) go say("Hi") wg.Wait() }
C++
UTF-8
6,672
4.0625
4
[]
no_license
#include <iostream> using namespace std; //Node structure struct Node { int data; struct Node *lchild; struct Node *rchild; struct Node *parent; }; //Class for node functions and root initialization class bst { private: Node *root; public: bst() { root = NULL; } //Function to get the root node struct Node *getroot(){ return root; } //Function to create new node //Takes the integer value to be stored as a parameter void newnode (int new_data) { Node *tmp = new Node; tmp->data = new_data; tmp->lchild = tmp->rchild =NULL; if (root == NULL) { root = tmp; } else { //Inserts new node and passes root node insertnode(root, tmp); } } //Function to insert new node //Takes two node pointers as parameters void insertnode(struct Node *tmp1, struct Node *tmp2) { //If tmp1 is greater insert on left side if(tmp1->data > tmp2->data) { //If tmp1 has no left child insert as tmp1 lchild if(tmp1->lchild == NULL) { tmp1->lchild = tmp2; tmp2->parent = tmp1; } else { //Recursive call if tmp1 has lchild already return insertnode(tmp1->lchild, tmp2); } } //If tmp1 is less insert on right side if(tmp1->data <= tmp2->data) { if(tmp1->rchild == NULL) { tmp1->rchild = tmp2; tmp2->parent = tmp1; } else { //Recursive call if tmp1 has rchild already return insertnode(tmp1->rchild, tmp2); } } } //Function to traverse bst inorder //Takes node pointer as parameter void inordertraverse(struct Node *tmp) { if(tmp != NULL ) { inordertraverse(tmp->lchild); cout << tmp->data << " "; inordertraverse(tmp->rchild); } } //Function to find max //Takes node pointer as parameter //Returns max node pointer struct Node *maxnode(struct Node *tmp) { struct Node *tl; struct Node *tr; if(tmp->lchild == NULL && tmp->rchild == NULL) { return tmp; } if(tmp->lchild == NULL) { tl = tmp; } else { tl = maxnode(tmp->lchild); } if (tmp->rchild == NULL) { tr = tmp; } else { tr = maxnode(tmp->rchild); } if (tl->data > tr->data && tl->data > tmp->data) { return tl; } if (tr->data > tl->data && tr->data > tmp->data) { return tr; } else { return tmp; } } //Fuction to delete node using predecessor //Takes node pointer as a parameter void deletenode (struct Node *tmp) { //Check if tmp is a leaf or only node if(tmp->lchild == NULL && tmp->rchild == NULL) { if (tmp->parent->lchild == tmp) { tmp->parent->lchild = NULL; } else { tmp->parent->rchild = NULL; } tmp->parent = NULL; } //Check if tmp has a left child else if(tmp->lchild != NULL) { struct Node *max = maxnode(tmp->lchild); tmp->data = max->data; //If max has a left child if(max->lchild != NULL && max->rchild == NULL) { max->lchild->parent = max->parent; max->parent->rchild = max->lchild; } //If max has no children if (max->lchild == NULL && max->rchild == NULL) { if (max->parent->lchild == max) { max->parent->lchild = NULL; } else { max->parent->rchild = NULL; } max->parent = NULL; } } //If tmp only has a right child else { tmp->rchild->parent = tmp->parent; tmp->parent->lchild = tmp->rchild; tmp = NULL; } } //Function to find node //Takes starting node pointer and integer value of interest as parameters //Returns the pointer to the node of interest struct Node *findnode(struct Node *tmp, int val) { if(val > tmp->data) { return findnode(tmp->rchild, val); } if (val < tmp->data) { return findnode(tmp->lchild, val); } else { return tmp; } } }; int main() { //Initialize class with root pointer set to null bst bst1; //Create 15 node (50, 40, 80, 20, 45, 60, 100, 70, 65, 42, 44, 30, 25, 35, 33) bst bst1.newnode(50); bst1.newnode(40); bst1.newnode(80); bst1.newnode(20); bst1.newnode(45); bst1.newnode(60); bst1.newnode(100); bst1.newnode(70); bst1.newnode(65); bst1.newnode(42); bst1.newnode(44); bst1.newnode(30); bst1.newnode(25); bst1.newnode(35); bst1.newnode(33); //Get root node struct Node *root = bst1.getroot(); //Inorder traversal cout << "Inorder traversal: " << endl; bst1.inordertraverse(root); cout << endl; cout << endl; //Delete root cout << "Inorder traversal after deleting root (50): " << endl; bst1.deletenode(root); bst1.inordertraverse(root); cout << endl; cout << endl; //Find node and delete struct Node *delete40 = bst1.findnode(root, 40); cout << "Node to be deleted: " << delete40->data << endl; bst1.deletenode(delete40); cout << "Inorder traversal after deleting node 40: " << endl; bst1.inordertraverse(root); cout << endl; cout << endl; //Find node and delete struct Node *delete65 = bst1.findnode(root, 65); cout << "Node to be deleted: " << delete65->data << endl; bst1.deletenode(delete65); cout << "Inorder traversal after deleting node 65: " << endl; bst1.inordertraverse(root); cout << endl; cout << endl; //Find node and delete struct Node *delete35 = bst1.findnode(root, 35); cout << "Node to be deleted: " << delete35->data << endl; bst1.deletenode(delete35); cout << "Inorder traversal after deleting node 35: " << endl; bst1.inordertraverse(root); cout << endl; cout << endl; return 0; }
Java
UTF-8
873
2.765625
3
[]
no_license
package extension; import java.util.*; import org.joda.time.DateTime; import org.joda.time.Minutes; import org.joda.time.Seconds; import play.templates.BaseTemplate.RawData; import play.templates.JavaExtensions; import utils.*; public class CustomExtensions extends JavaExtensions{ public static String removeNewLine(RawData inS){ String temp; temp = inS.toString().replace("\n", ""); return temp; } public static String removeNewLine(String inS){ String temp; temp = inS.replace("\n", ""); return temp; } public static String diff(Date base, Date comp) { DateTime end = new DateTime(base); DateTime start = new DateTime(comp); int mins = Minutes.minutesBetween(end, start).getMinutes(); int secs = Seconds.secondsBetween(end, start).minus(mins*60).getSeconds(); return (mins > 0 ? mins + " Minutes and " : "") + secs + " Seconds"; } }
C++
UTF-8
2,269
2.796875
3
[]
no_license
#include "primitives/triangle.h" Triangle::Triangle(Vector3 p0, Vector3 p1, Vector3 p2, QObject *parent) : Figure(parent), p0(std::move(p0)), p1(std::move(p1)), p2(std::move(p2)), l0(p1 - p0), l1(p2 - p1), l2(p0 - p2) { normal = Vector3::crossProduct(p1 - p0, p2 - p0).normalized(); mD = Vector3::dotProduct(normal, p0); xmin = std::min(std::min(p0.x(), p1.x()), p2.x()) - 10e-3f; xmax = std::max(std::max(p0.x(), p1.x()), p2.x()) + 10e-3f; ymin = std::min(std::min(p0.y(), p1.y()), p2.y()) - 10e-3f; ymax = std::max(std::max(p0.y(), p1.y()), p2.y()) + 10e-3f; zmin = std::min(std::min(p0.z(), p1.z()), p2.z()) - 10e-3f; zmax = std::max(std::max(p0.z(), p1.z()), p2.z()) + 10e-3f; wireframe.resize(1); auto &w = wireframe[0]; w.push_back(convertVector3(p0)); w.push_back(convertVector3(p1)); w.push_back(convertVector3(p2)); } void Triangle::correctBox(float &xmin, float &xmax, float &ymin, float &ymax, float &zmin, float &zmax) const { xmin = std::min(xmin, this->xmin); xmax = std::max(xmax, this->xmax); ymin = std::min(ymin, this->ymin); ymax = std::max(ymax, this->ymax); zmin = std::min(zmin, this->zmin); zmax = std::max(zmax, this->zmax); } bool Triangle::checkIntersect(const Vector3 &eye, const Vector3 &dir, float &x, float &y, float &z) const { float vd = Vector3::dotProduct(normal, dir); if (vd >= 0) return false; float v0 = -Vector3::dotProduct(normal, eye) + mD; float t = v0 / vd; if (t < 0) return false; Vector3 P = eye + t * dir; if (P.x() < xmin || P.x() > xmax || P.y() < ymin || P.y() > ymax || P.z() < zmin || P.z() > zmax) return false; if (Vector3::dotProduct(Vector3::crossProduct(l0, P - p0), normal) < 0) return false; if (Vector3::dotProduct(Vector3::crossProduct(l1, P - p1), normal) < 0) return false; if (Vector3::dotProduct(Vector3::crossProduct(l2, P - p2), normal) < 0) return false; x = P.x(); y = P.y(); z = P.z(); return true; } Vector3 Triangle::getNormal(const Vector3 &P) const { return normal; } bool Triangle::isContains(const Vector3 &P) const { return std::abs(Vector3::dotProduct(normal, P) - mD) < 10e-6f; }
Java
UTF-8
966
2
2
[]
no_license
package nuc.gml.mall.service; import com.baomidou.mybatisplus.extension.service.IService; import nuc.gml.mall.dataobject.CartDO; import nuc.gml.mall.dataobject.SysUserDO; import nuc.gml.mall.error.BusinessException; import nuc.gml.mall.service.model.CartModel; import java.util.List; public interface CartService extends IService<CartDO> { void addCart(CartDO cartDO) throws BusinessException; List<CartModel> getCardList(Long userId); void addItemCount(CartDO cartDO); void deleteCartItem(Integer cartId); /** * 根据id的集合查询购物车商品的集合 * @Param: cartId * @return java.util.List<nuc.rwenjie.modules.sys.service.model.CartModel> **/ CartModel getCartById(Integer cartId); /** * 根据id的集合查询购物车商品的集合 * @Param: cartId * @return java.util.List<nuc.rwenjie.modules.sys.service.model.CartModel> **/ List<CartModel> getCartListByIds(Integer[] cartId); }
Go
UTF-8
310
2.96875
3
[]
no_license
package main import ( "fmt" "net" ) //获取随机端口 func getPort() int { laddr := net.TCPAddr{IP:net.IPv4(127,0,0,1),Port:0} l,err := net.ListenTCP("tcp4", &laddr) if err == nil { addr := l.Addr() return addr.(*net.TCPAddr).Port }else { return 0 } } func main() { fmt.Println(getPort()) }
C
UTF-8
624
2.796875
3
[]
no_license
#include <stdio.h> #include "y.tab.h" #include "lex.yy.c" extern int yylex(void); extern char *yytext; int main(int argc,char** argv) { int token; while (token = yylex()) { if(token>=283 && token<=305) { printf("<KEYWORD, %s >\n",yytext); } else if(token==IDENTIFIER) printf("<IDENTIFIER, %s >\n",yytext); else if(token==CONSTANT) printf("<CONSTANT, %s >\n",yytext); else if(token== STRING_LITERAL ) printf("<STRING_LITERAL, %s >\n",yytext); else if(token > 0 ) { printf("<PUNCTUATOR, %s >\n",yytext); } else { printf(" <ERROR > line no = %d \n",yylineno ); } } }
Java
UTF-8
1,817
3.90625
4
[]
no_license
package creature; import java.util.*; import creature.calabash.*; public class CreatureSort { /** * Sort a LinkedList consists of CalabashBoys * @param list The LinkedList which consists of CalabashBoys to be sorted. * @param type Define the Sort operation: 0 is for Ascending, 1 is for Descending, 2 is for Shuffle. */ public static void doCalabashSort(LinkedList<Calabash> list, int type){ CalabashBoys cBoys = new CalabashBoys(list); cBoys.sort(type); list = cBoys.set; } public static void doCreatureSort(LinkedList<Creature> list, int type){ switch(type){ case 0: CreatureAscendingComparator<Creature> ascending = new CreatureAscendingComparator<Creature>(); Collections.sort(list, ascending); System.out.println("正序排序后的队列:"); for (Creature creature: list) { System.out.print(creature.name + " "); } break; case 1: CreatureDescendingComparator<Creature> descending = new CreatureDescendingComparator<Creature>(); Collections.sort(list, descending); System.out.println("反序排序后的队列:"); for (Creature creature: list) { System.out.print(creature.name + " "); } break; case 2: Collections.shuffle(list); System.out.println("乱序排序后的队列:"); for (Creature creature: list) { System.out.print(creature.name + " "); } break; default: break; } System.out.println(); System.out.println(); } }
Python
UTF-8
2,557
2.59375
3
[]
no_license
from objects import Raquete, Bola, bolaDir class GameCore: def __init__(self): self.score = { '1': 0, '2': 0, } self.sets = { '1': 0, '2': 0, } self.deuce = False self.pausado = False self.numOfSets = 5 self.switchSet = False self.storedRaqSpeed = 0 self.storedDirection = 0 self.winner = 0 def playerScored(self, playerFor, playerAgainst): if int(self.score[str(playerFor)]) == 9 and int(self.score[str(playerAgainst)]) == 10: self.deuce = True self.score = { '1': 0, '2': 0 } self.add_score(playerFor) return if self.deuce: self.add_score(playerFor) if int(self.score[str(playerFor)]) - int(self.score[str(playerAgainst)]) == 2: self.fecha_set(playerFor, playerAgainst) return if int(self.score[str(playerFor)]) == 10: self.fecha_set(playerFor, playerAgainst) return self.add_score(playerFor) return def add_score(self, player): self.score[str(player)] = int(self.score[str(player)]) + 1 return def add_set(self, player): self.sets[str(player)] = int(self.sets[str(player)]) + 1 return def fecha_set(self, playerFor, playerAgainst): self.add_set(playerFor) self.score = { '1': 0, '2': 0 } self.deuce = False self.troca_lados() if int(self.sets[str(playerFor)]) + int(self.sets[str(playerAgainst)]) == self.numOfSets: self.winner = playerFor self.pausado = True return else: return def troca_lados(self): sets_a = self.sets['1'] sets_b = self.sets['2'] self.sets = { '1': sets_b, '2': sets_a } if self.switchSet: self.switchSet = False else: self.switchSet = True return def reset_game(self): self.score = { '1': 0, '2': 0, } self.sets = { '1': 0, '2': 0, } self.deuce = False self.pausado = False self.numOfSets = 5 self.switchSet = False self.storedRaqSpeed = 0 self.storedDirection = 0 self.winner = 0 return
Java
UTF-8
1,178
3.703125
4
[]
no_license
//Complete this code or write your own from scratch import java.util.*; import java.io.*; class Solution{ private Hashtable<String, Integer> phonebook; public Solution(int n){ this.phonebook = new Hashtable<>(n); } public void addEntry(String name, Integer number){ this.phonebook.put(name, number); } public String getnumber(String name){ //System.out.println(this.phonebook); //System.out.println("'" + name + "'"); //System.out.println(this.phonebook.contains(name)); if (this.phonebook.get(name) != null){ return name + "=" + this.phonebook.get(name); } return "Not found"; } public static void main(String []argh){ Scanner in = new Scanner(System.in); int n = in.nextInt(); Solution phonebook = new Solution(n); for(int i = 0; i < n; i++){ String name = in.next(); int phone = in.nextInt(); phonebook.addEntry(name, phone); } while(in.hasNext()){ String s = in.next(); System.out.println(phonebook.getnumber(s)); } in.close(); } }
C
UTF-8
41,368
2.53125
3
[]
no_license
#include "umc.h" void leerArchivoConfig() { system("clear"); t_config *config = config_create("config.conf"); if (config == NULL) { log_error(logger, "Error al leer archivo config.conf\n"); free(config); abort(); } infoConfig.ip = config_get_string_value(config, "IP_SWAP"); infoConfig.puertoUMC = config_get_string_value(config, "PUERTO"); infoConfig.puertoSWAP = config_get_string_value(config, "PUERTO_SWAP"); infoConfig.algoritmo = config_get_string_value(config, "ALGORITMO"); infoMemoria.marcos = config_get_int_value(config, "MARCOS"); infoMemoria.tamanioDeMarcos = config_get_int_value(config, "MARCO_SIZE"); infoMemoria.maxMarcosPorPrograma = config_get_int_value(config,"MARCO_X_PROC"); infoMemoria.entradasTLB = config_get_int_value(config,"ENTRADAS_TLB"); infoMemoria.retardo = config_get_int_value(config,"RETARDO"); free(config->path); free(config); return; } struct sockaddr_in setDireccionUMC() { struct sockaddr_in direccion; direccion.sin_family = AF_INET; direccion.sin_addr.s_addr = INADDR_ANY; direccion.sin_port = htons (atoi(infoConfig.puertoUMC)); memset(&(direccion.sin_zero), '\0', 8); return direccion; } struct sockaddr_in setDireccionSWAP() { struct sockaddr_in direccion; direccion.sin_family = AF_INET; direccion.sin_addr.s_addr = inet_addr(infoConfig.ip); direccion.sin_port = htons (atoi(infoConfig.puertoSWAP)); memset(&(direccion.sin_zero), '\0', 8); return direccion; } void destruirTLB(t_entradaTLB* entradaTLB) { free(entradaTLB); } void destruirTablaPaginas(t_tablaDePaginas* entradaTablaPagina) { free(entradaTablaPagina->entradaTablaPaginas); free(entradaTablaPagina->paginasEnMemoria); free(entradaTablaPagina); } void finalizarUMC() { pthread_mutex_lock(&mutexClientes); pthread_mutex_lock(&mutexClock); pthread_mutex_lock(&mutexMemoria); pthread_mutex_lock(&mutexTLB); pthread_mutex_lock(&mutexTablaPaginas); log_trace(logger,"Nucleo desconectado se finaliza la UMC "); free(memoriaPrincipal); list_destroy_and_destroy_elements(TLB,(void*)destruirTLB); list_destroy_and_destroy_elements(tablasDePaginas,(void*)destruirTablaPaginas); abort(); return; } void inicializarMarcos() { unsigned marco; for(marco=0;marco < infoMemoria.marcos;marco++) { marcoDisponible[marco] = 0; marcoAsignadoA[marco] = 0; } return; } void inicializarEstructuras() { logger = log_create("UMC_TEST.txt", "UMC", 0, LOG_LEVEL_TRACE); loggerVariables = log_create("UMC_VAR.txt","UMC",0,LOG_LEVEL_TRACE); logger1 = log_create("UMC_CONSOLA.txt","UMC",1,LOG_LEVEL_TRACE); loggerTLB = log_create("UMC_TLB.txt","UMC",0,LOG_LEVEL_TRACE); loggerClock = log_create("UMC_CLOCK.txt","UMC",0,LOG_LEVEL_TRACE); clienteNucleo = 10; memoriaPrincipal = malloc(infoMemoria.marcos * infoMemoria.tamanioDeMarcos); TLB = list_create(); tablasDePaginas = list_create(); marcoAsignadoA = malloc(infoMemoria.marcos*sizeof(int)); marcoDisponible = malloc(infoMemoria.marcos*sizeof(int)); inicializarMarcos(); paginaVariablesTest = 99999; return; } void clienteDesconectado(int clienteUMC) { pthread_mutex_lock(&mutexClientes); FD_CLR(clienteUMC, &master); pthread_mutex_unlock(&mutexClientes); if(clienteUMC == clienteNucleo){ close(clienteUMC); finalizarUMC(); } log_trace(logger,"CPU desconectado,Se borra el hilo"); close(clienteUMC); pthread_exit(NULL); //pthreadexit fijate! return; } void pedirReservaDeEspacio(unsigned pid,unsigned paginasSolicitadas) { //Reservar espacio en el SWAP t_mensaje reserva; unsigned parametrosParaReservar [2]; reserva.head.codigo = RESERVE_SPACE; reserva.head.cantidad_parametros = 2; parametrosParaReservar[0] = pid; parametrosParaReservar[1] = paginasSolicitadas; reserva.head.tam_extra = 0; reserva.mensaje_extra = NULL; reserva.parametros = parametrosParaReservar; enviarMensaje(clienteSWAP,reserva); } void empaquetarYEnviar(t_mensaje mensaje,int clienteUMC) { enviarMensaje(clienteUMC, mensaje); return; } void enviarProgramaAlSWAP(unsigned pid, unsigned paginasSolicitadas, unsigned tamanioCodigo, char* codigoPrograma) { t_mensaje codigo; unsigned parametrosParaEnviar[1]; //Enviar programa al SWAP codigo.head.codigo = SAVE_PROGRAM; codigo.head.cantidad_parametros = 1; parametrosParaEnviar[0] = pid; codigo.parametros = parametrosParaEnviar; codigo.head.tam_extra = paginasSolicitadas * infoMemoria.tamanioDeMarcos; codigo.mensaje_extra = codigoPrograma; log_trace(logger,"%s", codigo.mensaje_extra); enviarMensaje(clienteSWAP, codigo); //free(codigo.mensaje_extra); } void enviarSuficienteEspacio(int clienteUMC, int codigo) { t_mensaje noEspacio; unsigned parametros[1]; parametros[0] = 1; noEspacio.head.codigo = codigo; noEspacio.head.cantidad_parametros = 1; noEspacio.head.tam_extra = 0; noEspacio.parametros = parametros; empaquetarYEnviar(noEspacio,clienteUMC); } unsigned enviarCodigoAlSwap(unsigned paginasSolicitadas,char* codigoPrograma,unsigned pid,unsigned tamanioCodigo,int clienteUMC) { t_mensaje respuesta,respuestaSaveProgram; pthread_mutex_lock(&mutexClientes); //Reservar espacio en el SWAP log_trace(logger,"Pide espacio para reservar el programa al SWAP"); pedirReservaDeEspacio(pid, paginasSolicitadas); //fijarse si pudo reservar recibirMensaje(clienteSWAP,&respuesta); if(respuesta.head.codigo == NOT_ENOUGH_SPACE) { log_trace(logger,"No hay suficiente espacio para almacenar el programa"); pthread_mutex_unlock(&mutexClientes); enviarSuficienteEspacio(clienteUMC,ALMACENAR_FAILED); free(codigoPrograma); freeMensaje(&respuesta); return 0; } //Enviar programa al SWAP log_trace(logger,"Hay suficiente espacio, se envia el programa al SWAP"); enviarProgramaAlSWAP(pid, paginasSolicitadas, tamanioCodigo, codigoPrograma); recibirMensaje(clienteSWAP,&respuestaSaveProgram); pthread_mutex_unlock(&mutexClientes); free(codigoPrograma); freeMensaje(&respuesta); freeMensaje(&respuestaSaveProgram); return 1; } void crearTablaDePaginas(unsigned pid,unsigned paginasSolicitadas) { log_trace(logger,"Se crea una tabla de paginas PID:%d, Paginas:%d",pid,paginasSolicitadas); int pagina; t_tablaDePaginas *tablaPaginas = malloc(sizeof(t_tablaDePaginas)); t_entradaTablaPaginas *entradaTablaPaginas = calloc(paginasSolicitadas,sizeof(t_entradaTablaPaginas)); tablaPaginas->pid = pid; tablaPaginas->punteroClock = 0; tablaPaginas->entradaTablaPaginas = entradaTablaPaginas; tablaPaginas->cantidadEntradasTablaPagina = paginasSolicitadas; if(paginasSolicitadas > infoMemoria.maxMarcosPorPrograma){ tablaPaginas->paginasEnMemoria = calloc(infoMemoria.maxMarcosPorPrograma,sizeof(int)); tablaPaginas->cantidadEntradasMemoria = infoMemoria.maxMarcosPorPrograma; for(pagina = 0; pagina < infoMemoria.maxMarcosPorPrograma;pagina++) tablaPaginas->paginasEnMemoria[pagina]= -1; } else{ tablaPaginas->paginasEnMemoria = calloc(paginasSolicitadas,sizeof(int)); tablaPaginas->cantidadEntradasMemoria = paginasSolicitadas; for(pagina=0;pagina < paginasSolicitadas;pagina++) tablaPaginas->paginasEnMemoria[pagina] = -1; } for(pagina=0;pagina < paginasSolicitadas; pagina++) { tablaPaginas->entradaTablaPaginas[pagina].estaEnMemoria = 0; tablaPaginas->entradaTablaPaginas[pagina].fueModificado = 0; } usleep(infoMemoria.retardo); pthread_mutex_lock(&mutexTablaPaginas); list_add(tablasDePaginas,tablaPaginas); pthread_mutex_unlock(&mutexTablaPaginas); return; } void mostrarTLB() { pthread_mutex_lock(&mutexTLB); unsigned index ; t_entradaTLB *entradaTLB; log_trace(loggerTLB,"======================="); log_trace(loggerTLB,"Entradas en TLB:"); for(index = 0; index < list_size(TLB) ; index++) { entradaTLB = list_get(TLB,index); log_trace(loggerTLB,"pid:%d \n pagina:%d \n marco:%d",entradaTLB->pid,entradaTLB->marco); } log_trace(loggerTLB,"======================="); pthread_mutex_unlock(&mutexTLB); return; } void borrarEntradasTLBSegun(unsigned pidActivo) { pthread_mutex_lock(&mutexTLB); unsigned entrada = 0; t_entradaTLB *entradaTLB; log_trace(loggerTLB,"Se borran las entradas del pid:%d",pidActivo); while(list_size(TLB) != 0) { if(entrada == list_size(TLB)) { pthread_mutex_unlock(&mutexTLB); mostrarTLB(); return; } entradaTLB = list_get(TLB,entrada); if(entradaTLB->pid == pidActivo) { log_trace("Se borra la entradaTLB PID:%d Pagina:%d Marco:%d",entradaTLB->pid,entradaTLB->pagina,entradaTLB->marco); list_remove(TLB,entrada); } else entrada++; } pthread_mutex_unlock(&mutexTLB); mostrarTLB(); return; } t_tablaDePaginas* buscarTabla(unsigned pidActivo,unsigned *indice,unsigned *seEncontro) { pthread_mutex_lock(&mutexTablaPaginas); t_tablaDePaginas *tablaBuscada = NULL; for(*indice = 0; *indice < list_size(tablasDePaginas); *indice = *indice+1) { tablaBuscada = list_get(tablasDePaginas,*indice); if(tablaBuscada->pid==pidActivo) { pthread_mutex_unlock(&mutexTablaPaginas); *seEncontro = 1; return tablaBuscada; } } pthread_mutex_unlock(&mutexTablaPaginas); *seEncontro = 0; return tablaBuscada; } t_tablaDePaginas* buscarTablaSegun(unsigned pidActivo,unsigned *indice) { t_tablaDePaginas*tablaBuscada = NULL; unsigned seEncontro; tablaBuscada = buscarTabla(pidActivo,indice,&seEncontro); if(seEncontro == 0) { pthread_exit(NULL); } return tablaBuscada; } t_tablaDePaginas* cambioProcesoActivo(unsigned pid,unsigned pidActivo) { log_trace(logger,"======Se cambia de proceso======"); log_trace(logger,"PID:%d por PID:%d",pid,pidActivo); unsigned indice; usleep(infoMemoria.retardo); t_tablaDePaginas* procesoActivo = buscarTablaSegun(pid,&indice); if(pidActivo > 0) { log_trace(logger,"Se borran las entradas de la TLB del pid anterior"); borrarEntradasTLBSegun(pidActivo); } log_trace(logger,"================================================="); return procesoActivo ; } void inicializarPrograma(t_mensaje mensaje,int clienteUMC) { unsigned pid = mensaje.parametros[0]; unsigned paginasSolicitadas = mensaje.parametros[1]; char* codigoPrograma = malloc(paginasSolicitadas*infoMemoria.tamanioDeMarcos); memcpy(codigoPrograma, mensaje.mensaje_extra, mensaje.head.tam_extra); unsigned tamanioCodigo=mensaje.head.tam_extra ; log_trace(logger,"======Se Inicializa un nuevo Proceso======",pid,paginasSolicitadas); log_trace(logger,"-PID: %d",pid); log_trace(logger,"-Paginas: %d",paginasSolicitadas); if(enviarCodigoAlSwap(paginasSolicitadas,codigoPrograma,pid,tamanioCodigo,clienteUMC) == 1){ crearTablaDePaginas(pid,paginasSolicitadas); enviarSuficienteEspacio(clienteUMC,ALMACENAR_OK); } log_trace(logger,"==========================================="); return; } void liberarMarcos(t_tablaDePaginas *proceso) { int pagina; int paginaAPuntada; for(pagina = 0; pagina < proceso->cantidadEntradasMemoria;pagina++) { paginaAPuntada = proceso->paginasEnMemoria[pagina]; if(paginaAPuntada != -1) { log_trace(logger,"Se libera el marco:%d",proceso->entradaTablaPaginas[paginaAPuntada].marco); marcoDisponible[proceso->entradaTablaPaginas[paginaAPuntada].marco] = 0; marcoAsignadoA[proceso->entradaTablaPaginas[paginaAPuntada].marco] = 0; } } return; } void eliminarDeMemoria(unsigned pid,unsigned* huboFallo) { t_tablaDePaginas *buscador; unsigned index; unsigned seEncontro; usleep(infoMemoria.retardo); buscador = buscarTabla(pid,&index,&seEncontro); if(seEncontro == 1) { pthread_mutex_lock(&mutexTablaPaginas); liberarMarcos(buscador); log_trace(logger,"Se destruye la tabla de paginas PID:%d",pid); list_remove_and_destroy_element(tablasDePaginas,index,(void*)destruirTablaPaginas); pthread_mutex_unlock(&mutexTablaPaginas); } else { log_error(logger,"El nucleo envio un PID ya eliminado"); *huboFallo = 1; } return; } void finPrograma(t_mensaje finalizarProg) { log_trace(logger,"======Se finaliza un Programa======"); unsigned huboFallo = 0; unsigned pid = finalizarProg.parametros[0]; log_trace(logger,"-PID:%d",pid); eliminarDeMemoria(pid,&huboFallo); if(huboFallo == 0) enviarMensaje(clienteSWAP,finalizarProg); log_trace(logger,"==================================="); return; } void borrarEntradaTLB(int marco) { pthread_mutex_lock(&mutexTLB); unsigned entrada; t_entradaTLB* entradaTLB; for(entrada = 0 ; entrada < list_size(TLB); entrada++) { entradaTLB = list_get(TLB,entrada); if(entradaTLB->marco == marco) { log_trace(loggerTLB,"Se borra la entradaTLB que contiene el marco:%d",marco); list_remove_and_destroy_element(TLB,entrada,(void*)destruirTLB); pthread_mutex_unlock(&mutexTLB); return; } } pthread_mutex_unlock(&mutexTLB); return; } void falloPagina(t_tablaDePaginas* procesoActivo,unsigned paginaApuntada) { log_trace(loggerClock,"Fallo de Pagina: Pagina:%d PID:%d",paginaApuntada,procesoActivo->pid); void* codigoDelMarco = malloc(infoMemoria.tamanioDeMarcos); unsigned marco = procesoActivo->entradaTablaPaginas[paginaApuntada].marco ; //Copio el codigo del marco usleep(infoMemoria.retardo); pthread_mutex_lock(&mutexMemoria); memcpy(codigoDelMarco, memoriaPrincipal+infoMemoria.tamanioDeMarcos*marco , infoMemoria.tamanioDeMarcos); pthread_mutex_unlock(&mutexMemoria); //TEST if(paginaApuntada== paginaVariablesTest) { int offset; log_trace(loggerVariables,"Fallo Pagina: Pagina %d",paginaApuntada); for(offset = 0; offset < 9;offset=offset+4){ void* codigoTest = malloc(4); memcpy(codigoTest,codigoDelMarco+offset,4); log_trace(loggerVariables,"Var %d: int:%d",offset/4,*((int*)codigoTest)); } } //-- //LLevo la pagina al SWAP log_trace(logger,"Se envia la Pagina:%d del Proceso:%d al SWAP",paginaApuntada,procesoActivo->pid); enviarPaginaAlSWAP(paginaApuntada,codigoDelMarco,procesoActivo->pid); free(codigoDelMarco); return; } int paginaEnEntrada(unsigned pagina,t_tablaDePaginas* tablaBuscada) { unsigned posicionPagina; for(posicionPagina = 0 ; posicionPagina < tablaBuscada->cantidadEntradasMemoria; posicionPagina++) { if(tablaBuscada->paginasEnMemoria[posicionPagina] == pagina) return posicionPagina; } return -1; } unsigned avanzaPunteroClock(t_tablaDePaginas *tablaPaginas, unsigned punteroClock) { if(punteroClock == tablaPaginas->cantidadEntradasMemoria -1 ) { punteroClock=0; log_trace(loggerClock,"Avanza Puntero clock:%d PID:%d",punteroClock,tablaPaginas->pid); } else { punteroClock++; log_trace(loggerClock,"Avanza Puntero clock:%d PID:%d",punteroClock,tablaPaginas->pid); } return punteroClock; } int buscarMarcoDisponible() { int marco; for(marco = 0 ; marco < infoMemoria.marcos; marco++) { if(marcoDisponible[marco] == 0 && marcoAsignadoA[marco] == 0) { return marco; } } return -1; } //Busca Bit presencia = 0 && bit Modificado = 0 int buscaNoPresenciaNoModificado(t_tablaDePaginas *procesoActivo,unsigned *punteroClock,unsigned pagina,int *paginaSiYaEstabaEnMemoria) { unsigned paginaApuntada; *paginaSiYaEstabaEnMemoria = paginaEnEntrada(pagina,procesoActivo); int marco = buscarMarcoDisponible(); //La pagina a reemplazar ya estaba en la tabla de las paginas en memoria if(*paginaSiYaEstabaEnMemoria != -1) return 1; for(pagina = 0 ; pagina < procesoActivo->cantidadEntradasMemoria;pagina++ ) { //No hay pagina cargada => no hay reemplazo paginaApuntada = procesoActivo->paginasEnMemoria[*punteroClock]; if(paginaApuntada == -1) { if(marco != -1) { log_trace(loggerClock,"Encuentra un marco vacio"); return 1; } else { *punteroClock = avanzaPunteroClock(procesoActivo,*punteroClock); } } else { //Busca una pagina que no fue modificada ni que este en memoria if(procesoActivo->entradaTablaPaginas[paginaApuntada].estaEnMemoria == 0) if(procesoActivo->entradaTablaPaginas[paginaApuntada].fueModificado == 0) { log_trace(loggerClock,"Encuentra una Pagina Bit Presencia = 0 & Bit Modificado = 0"); return 1; } *punteroClock = avanzaPunteroClock(procesoActivo,*punteroClock); } } return 0 ; } //Busca Bit presencia = 0 && bit Modificado = 1 int buscaNoPresenciaSiModificado(t_tablaDePaginas *tablaBuscada,unsigned *punteroClock) { unsigned paginaApuntada; unsigned pagina; int marco; for(pagina = 0 ; pagina < tablaBuscada->cantidadEntradasMemoria;pagina++ ) { marco = buscarMarcoDisponible(); paginaApuntada = tablaBuscada->paginasEnMemoria[*punteroClock]; //Busca si hay alguna pagina libre if(tablaBuscada->entradaTablaPaginas[paginaApuntada].estaEnMemoria == 0) if(tablaBuscada->entradaTablaPaginas[paginaApuntada].fueModificado == 1) { log_trace(loggerClock,"Encuentra una Pagina Bit Presencia = 0 & Bit Modificado = 1"); return 1; } //Si esta en memoria la libera if(tablaBuscada->entradaTablaPaginas[paginaApuntada].estaEnMemoria == 1) { log_trace(loggerClock,"Bit Presencia Pagina:%d se pone en 0",paginaApuntada); tablaBuscada->entradaTablaPaginas[paginaApuntada].estaEnMemoria = 0; borrarEntradaTLB(tablaBuscada->entradaTablaPaginas[paginaApuntada].marco); } *punteroClock = avanzaPunteroClock(tablaBuscada,*punteroClock); } return 0; } unsigned algoritmoClockMejorado(t_tablaDePaginas*procesoActivo,unsigned pagina,int *paginaSiYaEstabaEnMemoria) { log_trace(loggerClock,"===========INICIO=CLOCK-MEJORADO==================="); unsigned punteroClock; punteroClock = procesoActivo->punteroClock; log_trace(loggerClock,"Puntero clock:%d PID:%d",punteroClock,procesoActivo->pid); while(1) { if(buscaNoPresenciaNoModificado(procesoActivo,&punteroClock,pagina,paginaSiYaEstabaEnMemoria) == 1) return punteroClock; if(buscaNoPresenciaSiModificado(procesoActivo,&punteroClock) == 1) return punteroClock; } log_trace(loggerClock,"===========FIN=CLOCK-MEJORADO==================="); return punteroClock; } void enviarPaginaAlSWAP(unsigned pagina,void* codigoDelMarco,unsigned pidActivo) { t_mensaje aEnviar; aEnviar.head.codigo = SAVE_PAGE; unsigned parametros[2]; parametros[0] = pidActivo; parametros[1] = pagina; aEnviar.head.cantidad_parametros = 2; aEnviar.head.tam_extra = infoMemoria.tamanioDeMarcos; aEnviar.parametros = parametros; aEnviar.mensaje_extra = codigoDelMarco; enviarMensaje(clienteSWAP,aEnviar); return; } void abortarSiNoHayPaginasEnMemoria(t_tablaDePaginas* procesoActivo,int clienteUMC,int* noHayMarcos) { unsigned pagina; for(pagina=0;pagina < procesoActivo->cantidadEntradasMemoria ; pagina++) { if(procesoActivo->paginasEnMemoria[pagina] != -1) return; } log_error(logger,"No hay marcos disponibles, se notifica al CPU"); pthread_mutex_unlock(&mutexClock); *noHayMarcos = 1; } unsigned algoritmoclock(t_tablaDePaginas*procesoActivo,unsigned pagina,int *paginaSiYaEstabaEnMemoria) { log_trace(loggerClock,"===========INICIO=CLOCK==================="); unsigned punteroClock = procesoActivo->punteroClock; unsigned paginaApuntada; int marco = buscarMarcoDisponible(); log_trace(loggerClock,"-Puntero clock:%d PID:%d",punteroClock,procesoActivo->pid); *paginaSiYaEstabaEnMemoria = paginaEnEntrada(pagina,procesoActivo); //La pagina a reemplazar ya estaba en la tabla de las paginas en memoria if(*paginaSiYaEstabaEnMemoria != -1 ) { log_trace(loggerClock,"==============FIN=CLOCK==================\n"); return punteroClock; } while(1) { //marco = buscarMarcoDisponible(); paginaApuntada = procesoActivo->paginasEnMemoria[punteroClock]; if(paginaApuntada == -1 ) { if( marco != -1) { log_trace(loggerClock,"Encuentra un marco vacio"); log_trace(loggerClock,"==============FIN=CLOCK==================\n"); return punteroClock; } else punteroClock = avanzaPunteroClock(procesoActivo,punteroClock); } else { if(procesoActivo->entradaTablaPaginas[paginaApuntada].estaEnMemoria == 1) { log_trace(loggerClock,"Bit Presencia Pagina:%d se pone en 0",paginaApuntada); procesoActivo->entradaTablaPaginas[paginaApuntada].estaEnMemoria = 0; borrarEntradaTLB(procesoActivo->entradaTablaPaginas[paginaApuntada].marco); punteroClock = avanzaPunteroClock(procesoActivo,punteroClock); } else { log_trace(loggerClock,"==============FIN=CLOCK==================\n"); return punteroClock; } } } log_trace(loggerClock,"==============FIN=CLOCK==================\n"); return punteroClock; } void actualizarTablaDePaginas(t_tablaDePaginas*procesoActivo) { unsigned indice; buscarTablaSegun(procesoActivo->pid,&indice); pthread_mutex_lock(&mutexTablaPaginas); list_replace(tablasDePaginas,indice,procesoActivo); pthread_mutex_unlock(&mutexTablaPaginas); return; } unsigned actualizaPagina(unsigned pagina,t_tablaDePaginas* procesoActivo,int clienteUMC,int paginaEstabaEnMemoria) { unsigned punteroClock = procesoActivo->punteroClock; unsigned paginaVieja; int marco; if(paginaEstabaEnMemoria == -1) { //Se actualiza la nueva pagina a las entradas en memoria paginaVieja = procesoActivo->paginasEnMemoria[punteroClock]; if(paginaVieja != -1) { falloPagina(procesoActivo,paginaVieja); procesoActivo->entradaTablaPaginas[pagina].marco = procesoActivo->entradaTablaPaginas[paginaVieja].marco; } else { marco = buscarMarcoDisponible(); procesoActivo->entradaTablaPaginas[pagina].marco = marco; marcoAsignadoA[marco] = procesoActivo->pid; marcoDisponible[marco] = -1; } procesoActivo->paginasEnMemoria[punteroClock] = pagina; procesoActivo->entradaTablaPaginas[pagina].estaEnMemoria = 1; procesoActivo->punteroClock = avanzaPunteroClock(procesoActivo,punteroClock); log_trace(loggerClock,"El puntero clock luego del algortimo:%d",procesoActivo->punteroClock); } else procesoActivo->entradaTablaPaginas[pagina].estaEnMemoria = 1; //Actualizar la tabla de paginas actualizarTablaDePaginas(procesoActivo); return procesoActivo->entradaTablaPaginas[pagina].marco; } void escribirEnMemoria(void* codigoPrograma,unsigned tamanioPrograma, unsigned pagina,t_tablaDePaginas*procesoActivo,int clienteUMC,int paginaEstabaEnMemoria) { unsigned marco = actualizaPagina(pagina,procesoActivo,clienteUMC,paginaEstabaEnMemoria); if(paginaEstabaEnMemoria != -1) return; usleep(infoMemoria.retardo); pthread_mutex_lock(&mutexMemoria); memcpy(memoriaPrincipal + infoMemoria.tamanioDeMarcos*marco,codigoPrograma,tamanioPrograma); pthread_mutex_unlock(&mutexMemoria); free(codigoPrograma); return; } void mostrarTablaDePaginas(t_tablaDePaginas* procesoActivo) { unsigned indice; log_trace(loggerClock,"======Tabla De Paginas PID:%d =====",procesoActivo->pid); log_trace(loggerClock,"------Paginas-----"); for(indice = 0; indice < procesoActivo->cantidadEntradasTablaPagina; indice ++) log_trace(loggerClock,"Pagina:%d EstaEnMemoria:%d FueModificado:%d", indice,procesoActivo->entradaTablaPaginas[indice].estaEnMemoria,procesoActivo->entradaTablaPaginas[indice].fueModificado); log_trace(loggerClock,"==================================="); return; } void algoritmoDeReemplazo(void* codigoPrograma,unsigned tamanioPrograma,unsigned pagina,t_tablaDePaginas* procesoActivo,int clienteUMC,int*noHayMarcos) { pthread_mutex_lock(&mutexClock); unsigned punteroClock = 0; int paginaEstabaEnMemoria; unsigned marco = buscarMarcoDisponible(); //Si no hay marcos disponibles if(marco == -1) { abortarSiNoHayPaginasEnMemoria(procesoActivo,clienteUMC,noHayMarcos); //nunca se carga el proceso a memoria if(*noHayMarcos == 1) { free(codigoPrograma); return; } } //Eleccion entre Algoritmos if(!strcmp("CLOCK",infoConfig.algoritmo)) punteroClock = algoritmoclock(procesoActivo,pagina,&paginaEstabaEnMemoria); if(!strcmp("CLOCK-M",infoConfig.algoritmo)) punteroClock = algoritmoClockMejorado(procesoActivo,pagina,&paginaEstabaEnMemoria); procesoActivo->punteroClock = punteroClock; //Escribe en memoria la nueva pagina que mando el SWAP escribirEnMemoria(codigoPrograma,tamanioPrograma,pagina,procesoActivo,clienteUMC,paginaEstabaEnMemoria); //mostrarTablaDePaginas(procesoActivo); pthread_mutex_unlock(&mutexClock); return ; } void pedirPagAlSWAP(unsigned pagina,unsigned pidActual) { //Pedimos pagina al SWAP t_mensaje aEnviar; aEnviar.head.codigo = BRING_PAGE_TO_UMC; unsigned parametros[2]; parametros[0] = pidActual; parametros[1] = pagina; aEnviar.head.cantidad_parametros = 2; aEnviar.parametros = parametros; aEnviar.mensaje_extra = NULL; aEnviar.head.tam_extra = 0; enviarMensaje(clienteSWAP, aEnviar); } void traerPaginaAMemoria(unsigned pagina,t_tablaDePaginas* procesoActivo,int clienteUMC,int* noHayMarcos) { t_mensaje aRecibir; //Pedimos pagina al SWAP log_trace(logger,"Pide al SWAP la pagina:%d pid:%d",procesoActivo->pid,pagina); pthread_mutex_lock(&mutexClientes); pedirPagAlSWAP(pagina,procesoActivo->pid); //Recibimos pagina del SWAP recibirMensaje(clienteSWAP, &aRecibir); pthread_mutex_unlock(&mutexClientes); //TEST if(pagina == paginaVariablesTest) { int offset; log_trace(loggerVariables,"Trae a Memoria Pagina:%d Tamaño:%d",pagina,aRecibir.head.tam_extra); for(offset = 0; offset < 9;offset=offset+4){ void* codigoTest = malloc(4); memcpy(codigoTest,aRecibir.mensaje_extra+offset,4); log_trace(loggerVariables,"Var %d: int:%d",offset/4,*((int*)codigoTest)); } } //-- log_trace(logger,"Se Ejecuta el Algoritmo de reemplazo"); algoritmoDeReemplazo(aRecibir.mensaje_extra,aRecibir.head.tam_extra,pagina,procesoActivo,clienteUMC,noHayMarcos); return; } void algoritmoLRU(t_entradaTLB *entradaTLB) { log_trace(loggerTLB,"Se agrega entrada: pid:%d pagina:%d marco:%d",entradaTLB->pid,entradaTLB->pagina,entradaTLB->marco); pthread_mutex_lock(&mutexTLB); int tamanioMaximoTLB = infoMemoria.entradasTLB; int tamanioTLB = list_size(TLB); if(tamanioTLB == tamanioMaximoTLB) { log_trace(loggerTLB,"Se borra la entradaTLB:%d (la menos usada)",tamanioMaximoTLB-1); log_trace(loggerTLB,"Se pone la nueva entradaTLB: PID:%d,Pagina:%d,Marco:%d al principio de la lista",entradaTLB->pid,entradaTLB->pagina,entradaTLB->marco); list_add_in_index(TLB,0,entradaTLB); list_remove_and_destroy_element(TLB,tamanioMaximoTLB,(void*)destruirTLB); } else{ log_trace(loggerTLB,"Se pone la nueva entradaTLB: PID:%d,Pagina:%d,Marco:%d al principio de la lista",entradaTLB->pid,entradaTLB->pagina,entradaTLB->marco); list_add_in_index(TLB,0,entradaTLB); } pthread_mutex_unlock(&mutexTLB); return; } void actualizarTLB(t_entradaTablaPaginas entradaDePaginas,unsigned pagina,unsigned pidActual) { if(infoMemoria.entradasTLB == 0) return; log_trace(loggerTLB,"Se agrega una entrada a la TLB"); t_entradaTLB *entradaTLB = malloc(sizeof(t_entradaTLB)); entradaTLB->pid = pidActual; entradaTLB->pagina = pagina; entradaTLB->estaEnMemoria = entradaDePaginas.estaEnMemoria; entradaTLB->fueModificado = entradaDePaginas.fueModificado; entradaTLB->marco = entradaDePaginas.marco; log_trace(loggerTLB,"PID:%d",entradaTLB->pid); log_trace(loggerTLB,"Pagina:%d",entradaTLB->pagina); log_trace(loggerTLB,"Marco:%d",entradaTLB->marco); algoritmoLRU(entradaTLB); mostrarTLB(); return; } int buscarEnTLB(unsigned paginaBuscada,unsigned pidActual) { pthread_mutex_lock(&mutexTLB); int indice; int marco; t_entradaTLB *entradaTLB; if(infoMemoria.entradasTLB == 0) { pthread_mutex_unlock(&mutexTLB); return -1; } for(indice=0;indice < list_size(TLB);indice++) { entradaTLB = list_get(TLB,indice); if(entradaTLB->pid == pidActual && entradaTLB->pagina == paginaBuscada) { marco = entradaTLB->marco; log_trace(loggerTLB,"Se accedio a al indice: %d de la TLB",indice); log_trace(loggerTLB,"-PID:%d",entradaTLB->pid); log_trace(loggerTLB,"-Pagina:%d",entradaTLB->pagina); log_trace(loggerTLB,"-Marco :%d",entradaTLB->marco); log_trace(loggerTLB,"Se introduce la entradaTLB al inicio de la lista"); //Sacar la entrada y ponerla inicio de la lista list_remove(TLB,indice); list_add_in_index(TLB,0,entradaTLB); pthread_mutex_unlock(&mutexTLB); mostrarTLB(); return marco; } } log_trace(logger,"-TLB: miss"); log_trace(logger1,"-TLB: miss"); pthread_mutex_unlock(&mutexTLB); return -1; } void traducirPaginaAMarco(unsigned pagina,int *marco,t_tablaDePaginas*procesoActivo,int clienteUMC,int* noHayMarcos) { //Buscar en TLB *marco = buscarEnTLB(pagina,procesoActivo->pid); if(*marco != -1) { log_trace(logger,"-TLB: hit -> Marco: %d",*marco); return; } //Buscar en tabla de paginas usleep(infoMemoria.retardo); if(procesoActivo->entradaTablaPaginas[pagina].estaEnMemoria == 1) { //Esta en memoria se copia el marco *marco = procesoActivo->entradaTablaPaginas[pagina].marco; log_trace(logger,"Pagina en Memoria:SI -> Marco:%d", *marco); log_trace(logger,"Se actualiza la TLB"); actualizarTLB(procesoActivo->entradaTablaPaginas[pagina],pagina,procesoActivo->pid); return; } else { // Buscar en swap log_trace(logger,"Pagina en Memoria: NO"); log_trace(logger,"Se trae la pagina del SWAP"); traerPaginaAMemoria(pagina,procesoActivo,clienteUMC,noHayMarcos); *marco = procesoActivo->entradaTablaPaginas[pagina].marco; log_trace(logger,"PID:%d->Pagina:%d->Marco:%d",procesoActivo->pid,pagina,*marco); return; } return; } void procesosEnTabla() { unsigned proceso; pthread_mutex_lock(&mutexTablaPaginas); t_tablaDePaginas *tabla; unsigned pagina; if(list_size(tablasDePaginas) == 0){ pthread_mutex_unlock(&mutexTablaPaginas); return; } log_trace(logger1,"============================"); log_trace(logger1,"Procesos en Tablas:"); for(proceso= 0; proceso < list_size(tablasDePaginas);proceso++) { tabla = list_get(tablasDePaginas,proceso); log_trace(logger1,"--------------------------------"); log_trace(logger1,"Proceso PID: %d \n Paginas:%d \n PunteroClock:%d",tabla->pid,tabla->cantidadEntradasTablaPagina,tabla->punteroClock); log_trace(logger1,"Paginas:"); for(pagina = 0;pagina < tabla->cantidadEntradasTablaPagina;pagina++) { if(tabla->entradaTablaPaginas[pagina].estaEnMemoria == 1) log_trace(logger1,"-Pagina:%d -> Marco:%d",pagina,tabla->entradaTablaPaginas[pagina].marco); else log_trace(logger1,"-Pagina:%d -> Marco:NULL",pagina); } log_trace(logger1,"--------------------------------"); } log_trace(logger1,"============================"); pthread_mutex_unlock(&mutexTablaPaginas); return; } void enviarCodigoAlCPU(char* codigoAEnviar, unsigned tamanio,int clienteUMC,unsigned estado) { t_mensaje mensaje; unsigned parametros[1]; parametros[0] = estado; mensaje.head.codigo = RETURN_OK; mensaje.head.cantidad_parametros = 1; mensaje.head.tam_extra = tamanio; mensaje.parametros = parametros; mensaje.mensaje_extra = codigoAEnviar; empaquetarYEnviar(mensaje,clienteUMC); return; } unsigned paginasARecorrer(unsigned offset, unsigned tamanio) { unsigned tamanioTotal = offset+tamanio; if(tamanioTotal % infoMemoria.tamanioDeMarcos == 0) return tamanioTotal / infoMemoria.tamanioDeMarcos; else return tamanioTotal / infoMemoria.tamanioDeMarcos + 1; } unsigned copiarCodigo(unsigned paginaDondeEmpieza,unsigned paginasALeer,t_tablaDePaginas* procesoActivo,int clienteUMC,unsigned tamanio,unsigned offset,void* codigoAEnviar) { unsigned offsetTest = offset; //TEST unsigned paginaATraducir; int marco; int noHayMarcos = 0; unsigned tamanioACopiar; if(paginasALeer == 1) tamanioACopiar = tamanio; else tamanioACopiar = infoMemoria.tamanioDeMarcos - offset; unsigned seLeyo = 0; if(paginaDondeEmpieza + paginasALeer <= procesoActivo->cantidadEntradasTablaPagina) { for(paginaATraducir = 0; paginaATraducir < paginasALeer;paginaATraducir++) { log_trace(logger,"Se traduce la Pagina: %d Pid:%d al marco correspondiente" ,paginaDondeEmpieza+paginaATraducir,procesoActivo->pid); traducirPaginaAMarco(paginaDondeEmpieza+paginaATraducir,&marco,procesoActivo,clienteUMC,&noHayMarcos); if(noHayMarcos == 1) return 3; usleep(infoMemoria.retardo); pthread_mutex_lock(&mutexMemoria); memcpy(codigoAEnviar+seLeyo,memoriaPrincipal+infoMemoria.tamanioDeMarcos*marco+offset,tamanioACopiar); pthread_mutex_unlock(&mutexMemoria); offset = 0; seLeyo = seLeyo + tamanioACopiar; tamanio = tamanio - tamanioACopiar; //Se fija si esta por leer la ultima pagina if(paginaATraducir < paginasALeer -2) { tamanioACopiar = infoMemoria.tamanioDeMarcos; } else { tamanioACopiar = tamanio; } } log_trace(logger,"Se copia el codigo a enviar"); usleep(infoMemoria.retardo); //TEST if(seLeyo == 4 && paginasALeer == 1) { log_trace(loggerVariables,"Envio Variable:Pagina %d var:%d",paginaDondeEmpieza,offsetTest/4); log_trace(loggerVariables,"Var en void*:%s",codigoAEnviar); log_trace(loggerVariables,"Var en int :%d\n",*((int*)codigoAEnviar)); } //-- return 1; } else { log_error(logger,"Paginas fuera de segmento, se notifica al CPU"); return 2; } } unsigned guardarCodigo(unsigned paginaDondeEmpieza,unsigned paginasALeer,t_tablaDePaginas*procesoActivo,int clienteUMC,unsigned tamanio,unsigned offset,void* codigoAGuardar) { unsigned offsetTest = offset; //TEST unsigned paginaATraducir; int marco; int noHayMarcos=0; unsigned tamanioACopiar; unsigned seLeyo = 0; if(paginasALeer == 1) tamanioACopiar = tamanio; else tamanioACopiar = infoMemoria.tamanioDeMarcos - offset; if(paginaDondeEmpieza + paginasALeer <= procesoActivo->cantidadEntradasTablaPagina) { for(paginaATraducir = 0; paginaATraducir < paginasALeer;paginaATraducir++) { log_trace(logger,"Se traduce la pagina: %d con pid:%d al marco correspondiente \n" ,paginaDondeEmpieza+paginaATraducir,procesoActivo->pid); traducirPaginaAMarco(paginaDondeEmpieza+paginaATraducir,&marco,procesoActivo,clienteUMC,&noHayMarcos); if(noHayMarcos == 1) return 3; log_trace(logger,"Se copia el contenido en la pagina:%d pid:%d marco:%d",paginaDondeEmpieza+paginaATraducir,procesoActivo->pid,marco); usleep(infoMemoria.retardo); pthread_mutex_lock(&mutexMemoria); memcpy(memoriaPrincipal+infoMemoria.tamanioDeMarcos*marco+offset,codigoAGuardar+seLeyo,tamanioACopiar); pthread_mutex_unlock(&mutexMemoria); offset = 0; seLeyo = seLeyo + tamanioACopiar; tamanio = tamanio - tamanioACopiar; procesoActivo->entradaTablaPaginas[paginaDondeEmpieza+paginaATraducir].fueModificado = 1; //Se fija si esta por leer la ultima pagina if(paginaATraducir < paginasALeer -2) tamanioACopiar = infoMemoria.tamanioDeMarcos; else tamanioACopiar = tamanio; } actualizarTablaDePaginas(procesoActivo); //TEST if(seLeyo == 4 && paginasALeer == 1) { log_trace(loggerVariables,"Guardar Variable:Pagina %d var:%d",paginaDondeEmpieza,offsetTest/4); log_trace(loggerVariables,"Var en void*:%s",codigoAGuardar); log_trace(loggerVariables,"Var en int :%d\n",*((int*)codigoAGuardar)); } //-- return 1; } else { log_error(logger,"Paginas fuera del stack, se notifica al CPU"); return 2; } } void almacenarBytesEnPagina(t_mensaje mensaje,t_tablaDePaginas* procesoActivo, int clienteUMC) { log_trace(logger,"=======Peticion de almacenaje de Variable ========"); unsigned pagina = mensaje.parametros[0]; unsigned offset = mensaje.parametros[1]; unsigned tamanio = mensaje.parametros[2]; void* codigo = malloc(tamanio); log_trace(logger,"-Pagina:%d",pagina); log_trace(logger,"-Offset:%d",offset); log_trace(logger,"-Tamano:%d",tamanio); memcpy(codigo,&mensaje.parametros[3],tamanio); unsigned paginasALeer = paginasARecorrer(offset,tamanio); //TEST if(paginasALeer == 1) paginaVariablesTest = pagina; //-- unsigned estado = guardarCodigo(pagina,paginasALeer,procesoActivo,clienteUMC,tamanio,offset,codigo); enviarCodigoAlCPU(NULL,0,clienteUMC,estado); free(codigo); log_trace(logger,"===================================================="); return; } void enviarBytesDeUnaPagina(t_mensaje mensaje,int clienteUMC,t_tablaDePaginas* procesoActivo) { log_trace(logger,"=======Peticion de envio de codigo al CPU======"); unsigned pagina = mensaje.parametros[0]; unsigned offset = mensaje.parametros[1]; unsigned tamanio = mensaje.parametros[2]; unsigned paginasALeer = paginasARecorrer(offset,tamanio); void* codigoAEnviar = malloc(tamanio); log_trace(logger,"-Pagina:%d",pagina); log_trace(logger,"-Offset:%d",offset); log_trace(logger,"-Tamano:%d",tamanio); unsigned estado = copiarCodigo(pagina,paginasALeer,procesoActivo,clienteUMC,tamanio,offset,codigoAEnviar); log_trace(logger,"Se envia la instruccion al CPU"); enviarCodigoAlCPU(codigoAEnviar,tamanio,clienteUMC,estado); log_trace(logger,"==============================================="); free(codigoAEnviar); return; } void enviarTamanioDePagina(int clienteUMC) { log_trace(logger,"Se envia el tamano de pagina"); t_mensaje mensaje; unsigned parametros[1]; parametros[0] = infoMemoria.tamanioDeMarcos; mensaje.head.codigo = RETURN_TAM_PAGINA; mensaje.head.cantidad_parametros = 1; mensaje.head.tam_extra = 0; mensaje.parametros = parametros; mensaje.mensaje_extra = NULL; empaquetarYEnviar(mensaje,clienteUMC); return; } void accionSegunCabecera(int clienteUMC) { log_trace(logger,"Se creo un Hilo"); unsigned pidActivo = 0; t_tablaDePaginas*procesoActivo = NULL; int cabeceraDelMensaje; t_mensaje mensaje; while(1){ // procesosEnTabla(); if(recibirMensaje(clienteUMC,&mensaje) <= 0){ clienteDesconectado(clienteUMC); freeMensaje(&mensaje); } usleep(infoMemoria.retardo); cabeceraDelMensaje = mensaje.head.codigo; switch(cabeceraDelMensaje){ case INIT_PROG: inicializarPrograma(mensaje,clienteUMC); break; case FIN_PROG: finPrograma(mensaje); break; case GET_DATA: enviarBytesDeUnaPagina(mensaje,clienteUMC,procesoActivo); break; case GET_TAM_PAGINA: enviarTamanioDePagina(clienteUMC); break; case CAMBIO_PROCESO: procesoActivo = cambioProcesoActivo(mensaje.parametros[0],pidActivo); pidActivo = procesoActivo->pid; break; case RECORD_DATA: almacenarBytesEnPagina(mensaje,procesoActivo, clienteUMC); break; } freeMensaje(&mensaje); } return; } int recibirConexiones() { direccionServidorUMC = setDireccionUMC(); servidorUMC = socket(AF_INET, SOCK_STREAM, 0); int activado = 1; setsockopt(servidorUMC, SOL_SOCKET, SO_REUSEADDR, &activado, sizeof(activado)); //para reutilizar dirreciones if (bind(servidorUMC, (void*) &direccionServidorUMC, sizeof(direccionServidorUMC)) != 0) { perror("Falló asociando el puerto\n"); abort(); } printf("Esperando al Nucleo\n"); listen(servidorUMC, 100); FD_SET(servidorUMC,&master); return servidorUMC; } int aceptarConexion() { int clienteUMC; struct sockaddr_in direccion; //del cpu o del nucleo unsigned int tamanioDireccion; clienteUMC = accept(servidorUMC, (void*) &direccion, &tamanioDireccion); return clienteUMC ; } int recibir(void *buffer,unsigned tamanioDelMensaje,int clienteUMC) { int bytesRecibidos = recv(clienteUMC, buffer, tamanioDelMensaje, 0); if (bytesRecibidos <= 0) { perror("El cliente se desconecto\n"); close(clienteUMC); pthread_mutex_lock(&mutexClientes); FD_CLR(clienteUMC, &master); pthread_mutex_unlock(&mutexClientes); return 0; } return bytesRecibidos; } void conectarAlSWAP() { direccionServidorSWAP = setDireccionSWAP(); clienteSWAP = socket(AF_INET, SOCK_STREAM, 0); if (connect(clienteSWAP, (void*) &direccionServidorSWAP, sizeof(direccionServidorSWAP)) != 0) { log_error(logger,"La UMC fallo al conectarse al SWAP"); abort(); } log_trace(logger,"La UMC se conecto con exito al SWAP"); return ; } void enviar(void *buffer,int cliente) { send(cliente, buffer, sizeof(buffer), 0); free(buffer); return; } void gestionarConexiones() { fd_set fdsParaLectura; int maximoFD; int fdBuscador; pthread_t cliente; int clienteUMC; pthread_mutex_init(&mutexClientes,NULL); pthread_mutex_init(&mutexMemoria,NULL); pthread_mutex_init(&mutexTablaPaginas,NULL); pthread_mutex_init(&mutexTLB,NULL); FD_ZERO(&master); FD_ZERO(&fdsParaLectura); maximoFD = recibirConexiones(); while(1){ fdsParaLectura = master; if ( select(maximoFD+1,&fdsParaLectura,NULL,NULL,NULL) == -1 ){ //comprobar si el select funciona perror("Error en el select"); abort(); } for(fdBuscador=3; fdBuscador <= maximoFD; fdBuscador++) // explora los FDs que estan listos para leer { if( FD_ISSET(fdBuscador,&fdsParaLectura) ) //entra una conexion, o hay datos entrantes { if(fdBuscador == servidorUMC) { clienteUMC = aceptarConexion(); FD_SET(clienteUMC, &master); if(clienteUMC > maximoFD) //Actualzar el maximo fd maximoFD = clienteUMC; pthread_create(&cliente, NULL, (void *)accionSegunCabecera, (void *) clienteUMC); } else //Se recibieron datos de otro tipo { //Hacer lo que haga falta } } else { } } } return; } /* int main(){ //Config leerArchivoConfig(); inicializarEstructuras(); conectarAlSWAP(); //servidor gestionarConexiones(); return 0; } /* //Pruebas commons t_list *hola = list_create(); t_tablaDePaginas *tabla = malloc(sizeof(t_tablaDePaginas)); t_tablaDePaginas *aux; tabla->pid = 2; list_add(hola,tabla); aux = list_remove(hola,0); free(aux); printf("hola"); return 0; }*/
Java
UTF-8
2,167
2.171875
2
[]
no_license
package softikoda.com.ourculture; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.TextView; import android.widget.Toast; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.squareup.picasso.Picasso; import org.json.JSONException; import org.json.JSONObject; /** * Created by johnolwamba on 3/1/2016. */ public class TranslatorListAdapter extends ArrayAdapter<String> { private String[] phone; private String[] distance; private String[] name; private Activity context; public TranslatorListAdapter(Activity context, String[] name, String[] phone, String[] distance) { super(context, R.layout.fragmentlist, name); this.context = context; this.name = name; this.phone = phone; this.distance = distance; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); final View listViewItem = inflater.inflate(R.layout.custom_translator_list, null, true); TextView textViewName= (TextView) listViewItem.findViewById(R.id.textView2); //TextView textViewPhone = (TextView) listViewItem.findViewById(R.id.textView3); TextView textViewDistance = (TextView) listViewItem.findViewById(R.id.textView5); textViewName.setText(name[position]); //textViewPhone.setText(phone[position]); Double mydistance = Double.parseDouble(distance[position]); Integer dista = mydistance.intValue(); textViewDistance.setText(""+dista+" KMs away."); return listViewItem; } }
Markdown
UTF-8
2,121
3.09375
3
[]
no_license
--- layout: post title: REST and Software Architecture --- ## REST Resource Methods * Roy Fielding has never mentioned any recommendation around which method to be used in which condition. All he emphasizes is that it should be <font color=red>uniform interface</font>. * E.g.: GET/PUT/POST/DELETE * Ideally, everything that is needed to <font color=red>change the resource state</font> shall be part of API response for that resource – including methods and in what state they will leave the representation. ## <font color=red>REST != HTTP</font> * In the <font color=red>REST</font> architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs).  * RESTful applications should be simple, lightweight, and fast. * Resources are decoupled from their representation so that their content can be accessed in a <font color=red>variety of formats</font>, such as HTML, XML, plain text, PDF, JPEG, JSON, and others. <font color=red>Metadata</font> about the resource is available and used, for example, to control caching, detect transmission errors, negotiate the appropriate representation format, and perform authentication or access control. And most importantly, every interaction with a resource is <font color=red>stateless</font>. * The resources are acted upon by using a set of simple, <font color=red>well-defined operations</font> (e.g. GET/POST). The clients and servers exchange representations of resources by using a standardized interface and protocol – typically <font color=red>HTTP</font>. ## PostgreSQL and Flask * Example 45: <https://github.com/ruiwu1990/db_docker> ## REST Data Elements ![](data.png) ## REST Connectors ![](connectors.png) ## REST Components ![](components.png) ## REST: Three views * Process view: how do components interact? * Processes connect in a pipe-and-filter style, each request may include different processes * Connector view: how do components communicate? * Data view: what is the application state as data flows through the components? |||[Index](../../)||| [Prev](../part4/)|||
Shell
UTF-8
5,460
2.96875
3
[]
no_license
#!/bin/bash # # #Get the current board type. BOARD_TYPE=`dmidecode | grep "Product Name:" | sed -n "1p" | awk -F ' ' '{print $NF}'` #Automated data files exported in test cases. TEST_CASE_DB_FILE="data/sas_test_case.table" #Test case execution result save file. OUTPUT_TEST_DB_FILE="data/report.csv" #700k performance data sheet file FIO_IOPS_DB_FILE="data/iops700k.csv" #Test case execution switch. TEST_CASE_FUNCTION_SWITCH="" #Test case execution function name. TEST_CASE_FUNCTION_NAME="" TEST_CASE_ID="" #Test case execution result. MESSAGE="" # SYS_TYPE=`cat /etc/hostname` if [ x"${SYS_TYPE}" = x"estuary" ] then DEVMEM="devmem" else DEVMEM="devmem2" fi # The PHY number of the controller EFFECTIVE_PHY_NUM=11 # log file ERROR_INFO="error_info.log" # fio tools configuration file FIO_CONFG="fio.conf" # Common tools directory path COMMON_TOOL_PATH="common_tool" # Test case code directory path TEST_CASE_PATH="sas_autotest/case_script" # phy path PHY_FILE_PATH="/sys/class/sas_phy" # Save all disk partition names declare -a ALL_DISK_PART_NAME # FIO tools IO size FIO_BS=("4M" "4K" "512B") # FIO tools IO Read and write mode FIO_RW=("randread" "randwrite" "read" "write" "randrw") # FIO tools mixed read and write ratio. IO_RATIO=("10" "50" "90") # FIO tool parameter list FIO_PARAMETER_LIST=" [global] rw=read direct=1 ramp_time=1 ioengine=psync iodepth=64 numjobs=1 bs=4k ;zero_buffers=1 group_reporting=1 ;ioscheduler=noop ;gtod_reduce=1 ;iodepth_batch=2 ;iodepth_batch_complete=2 runtime=20 ;thread loops=10 " #phy address PHY_ADDR_VALUE=( "0xa2002000" "0xa2002400" "0xa2002800" "0xa2002c00" "0xa2003000" "0xa2003400" "0xa2003800" "0xa2003c00" ) #Judge the current environment, directly connected environment or expander environment register address. CURR_ENV_REG_ADDR="0xa2000028" ### Test case parameter configuration. ## 2 - physical_data_rate # negotiated link rate value, Multiple please use the symbol "|" split, Default Value is '1.5|3|6|12', Unit: Gbit. DISK_NEGOTIATED_LINKRATE_VALUE='1.5|3|6|12' ## 3 - stable_2GB_file_transfer # Disk file data consistency test, File comparison times, Default Value is 500. COMPARISON_NUMBER=5 ## 4 - No cable unplug OOPs # Long time read / write disk, Default Value is 0. #IS_LONG_TIME_IO_READ_WRITE=0 # Long time read and write disk time, Default Value is 14400ms. FIO_LONG_RUN_TIME=10 # Repeat read / write disk, Default Value is 0. #IS_REPEAT_IO_READ_WRITE=0 # Repeat read and write disks. Default value is 100 second. REPEAT_RW_NUMBER=5 # FIO tool to read the cycle time. REPEAT_RM_TIME=2 ## 5 - phy_control_through_sysfs # loop Rate set up function switch, 1 - oepn test, 0 - close test, Default Value is 0. #IS_LOOP_RATE_SET_UP=0 # loop Rate set up number, Default Value is 10000. LOOP_RATE_SET_UP_NUMBER=5 # Maximum disk phy, Default Value is "6.0 Gbit". MAXIMUM_LINK_VALUE="6.0 Gbit" # Minimum disk phy, Default Value is "3.0 Gbit". MINIMUM_LINK_VALUE="3.0 Gbit" ## 6 - support_available_sas_cores # BSRANGE="4k-4M" # BSSPLIT="4k/30:8k/40:16k/30" ## 7 - support full sas function on all available phys # cycle the number of all proximal phy switches, Default value is 100. LOOP_PHY_COUNT=2 # cycle reset distal phy number, Default value is 1000. RESET_PHY_COUNT=2 # fio tool business run time. LOOP_PHY_TIME=10 ## 8 - Support SAS Narrow and Wide Ports. # fio tool business run time. FIO_RESET_TIME=10 # Reset the number of Hart_rest or link_reset FIO_RESET_COUNT=5 ## 9 - support hotplug # fio tool business run time. FIO_ENABLE_TIME=180 ## 10 - support smart # query enable smart keyword. SUPPORT_SMART_KEYWORD="Enabled" DISABLED_SMART_KEYWORD="Disabled" ENABLED_SMART_KEYWORD="Enabled" STATUS_SMART_KEYWORD="PASSED|OK" ## 12 - support Max devices # The number of disks. MAX_DEV_NUM=14 ## 13 - RAS support # 1bit error injection, injection CFG_ECCERR_INJECT0_EN register value. #ECC_1BIT_REG_INJECT0_VALUE=( #"0x1" "0x2" "0x4" "0x8" "0x10" "0x20" "0x40" "0x80" "0x100" "0x200" "0x400""0x800" #"0x1000" "0x2000" "0x4000" "0x8000" "0x10000" "0x20000" "0x40000" "0x80000" "0x100000" #) # 1bit error injection, injection CFG_ECCERR_INJECT1_EN register value. #ECC_1BIT_REG_INJECT1_VALUE=( #"0x1" "0x4" "0x10" "0x40" "0x100" "0x400" "0x1000" "0x4000" "0x10000" #) # 2bit error injection, injection CFG_ECCERR_INJECT1_EN register value. #ECC_3BIT_REG_INJECT1_VALUE=( #"0x2" "0x8" "0x20" "0x80" "0x200" "0x800" "0x2000" "0x8000" "0x20000" #) # Value of SAS_ECCERR_MASK0 register address MASK_REG_ADDR_VALUE="0xa20001F0" # Value of CFG_ECCERR_INJECT0_EN register address INJECT0_REG_ADDR_VALUE="0xa2000200" # Value of CFG_ECCERR_INJECT1_EN register address INJECT1_REG_ADDR_VALUE="0xa2000204" # CNT_REG_ADDR_VALUE="0xa2006014" # TRSHDC_REG_ADDR_VALUE="0xa2006018" # BIT_ECC_TIME=30 # ECC_INFO_KEY_QUERIES="hgc_dqe_acc1b_intr" ## 14 - support module load and uninstall. # Need to load the ko file name, multiple ko file format "a.ko|b.ko", default is empty, that does not load. MODULE_KO_FILE="" # load ko after the success of the test disk file, for example "/dev/sda1", default is empty. MODULE_DISK_FILE="" ## 15 - the driver should support 700k iops per controller. # FIO_IOPS_IODEPTH="1024" # IOPS_THRESHOLD="17" # FIO_IODEPTH_LIST=("1" "2" "4" "8" "16" "32" "64" "128" "256" "512" "1024" "2048" "4096") ## 16 - controller reset for ECC error. # CONTROLLER_ECC_RESET_ADDR="0xa2000200" # CONTROLLER_ECC_ERROR="0xa20001F0" # CONTROLLER_ECC_IO_TIME=60
JavaScript
UTF-8
222
3.171875
3
[]
no_license
'use strict'; const names = ['María', 'Lucía', 'Susana', 'Rocío', 'Inmaculada']; const helloName = (name) => (name = `Bienvenida ${name}`); const helloMessage = names.map(helloName); console.log(helloMessage);
PHP
UTF-8
966
2.75
3
[ "MIT", "BSD-4-Clause-UC", "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "TCL", "ISC", "Zlib", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "blessing" ]
permissive
--TEST-- ob_start(): Ensure unerasable buffer cannot be erased by ob_clean(), ob_end_clean() or ob_end_flush(). --FILE-- <?php function callback($string) { static $callback_invocations; $callback_invocations++; return "[callback:$callback_invocations]$string\n"; } ob_start('callback', 0, false); echo "All of the following calls will fail to clean/remove the topmost buffer:\n"; var_dump(ob_clean()); var_dump(ob_end_clean()); var_dump(ob_end_flush()); echo "The OB nesting will still be 1 level deep:\n"; var_dump(ob_get_level()); ?> --EXPECTF-- [callback:1]All of the following calls will fail to clean/remove the topmost buffer: Notice: ob_clean(): failed to delete buffer of callback (0) in %s on line 11 bool(false) Notice: ob_end_clean(): failed to discard buffer of callback (0) in %s on line 12 bool(false) Notice: ob_end_flush(): failed to send buffer of callback (0) in %s on line 13 bool(false) The OB nesting will still be 1 level deep: int(1)
PHP
UTF-8
1,713
2.59375
3
[ "Apache-2.0" ]
permissive
<?php /** * 彩色瓶子表白生成器 * * @author chenfenghua<843958575@qq.com> * @copyright Copyright 2014-2017 * @version 2.0 */ namespace app\play\controller; use think\Request; class Pingzi { /** * 入口页 */ public function index() { $this->data['title'] = '彩色瓶子表白生成器'; $this->render('index', $this->data); } /** * 生成图 */ public function image(Request $req) { header("content-type:image/jpeg"); $name = $req->get('param1', "装B君"); $select1 = $req->get('param2', "好想你"); $im = imagecreatetruecolor(580, 774); $bg = imagecreatefromjpeg(IA_ROOT.'/example/pingzi/main.jpg'); imagecopy($im,$bg,0,0,0,0,580,774); imagedestroy($bg); $black = imagecolorallocate($im, 204, 179, 174); $font = IA_ROOT.'/static/fonts/zkklt.ttf'; $arr = $this->ch2arr($name); $arr2 = $this->ch2arr($select1); #彩色瓶子表白生成器 imagettftext($im, 50, 0, 140, 190, $black, $font, $arr[0]); imagettftext($im, 50, 0, 290, 190, $black, $font, $arr[1]); imagettftext($im, 50, 0, 440, 190, $black, $font, $arr[2]); imagettftext($im, 50, 0, 140, 260, $black, $font, $arr2[0]); imagettftext($im, 50, 0, 290, 260, $black, $font, $arr2[1]); imagettftext($im, 50, 0, 440, 260, $black, $font, $arr2[2]); imagejpeg($im); imagedestroy($im); } function ch2arr($str) { $length = mb_strlen($str, 'utf-8'); $array = []; for ($i=0; $i<$length; $i++) $array[] = mb_substr($str, $i, 1, 'utf-8'); return $array; } }
Java
UTF-8
1,265
1.90625
2
[]
no_license
package com.travisgray.foodchain; import android.content.res.AssetManager; import android.content.res.Resources; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.Locale; public class MainActivity extends AppCompatActivity { Button btnSignIn,btnSignUp; TextView txtSlogan,logo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnSignIn = (Button)findViewById(R.id.btnSignIn); btnSignUp = (Button)findViewById(R.id.btnSignUp); txtSlogan = (TextView) findViewById(R.id.txtSlogan); logo = (TextView) findViewById(R.id.logo); btnSignUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); btnSignIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); } }
Swift
UTF-8
415
2.65625
3
[]
no_license
// // Protocols.swift // DiscoveryTest // // Created by Jason Chitla on 5/18/16. // Copyright © 2016 Jason Chitla. All rights reserved. // import UIKit protocol TableViewCellReusable { static var reuseableIdentifier: String { get } } extension TableViewCellReusable where Self: UITableViewCell { static var reuseableIdentifier: String { return String(self).componentsSeparatedByString(".").last! } }
C++
UTF-8
812
4
4
[]
no_license
#include <iostream> #include <string> #include <cstddef> using namespace std; void count_substr(string str1, string substring); int main() { string str1; string substr; cout << "Enter a string: "; getline(cin, str1); cout << "Enter the substring: "; getline(cin, substr); count_substr(str1, substr); } void count_substr(string str1, string substring) { int cnt = 0; for (int i = 0; i < str1.length(); i++) { if(str1.substr(i, substring.length()) == substring) { cnt++; } } if(cnt == 0){ cout << "There are no occurances of \"" << substring << "\" in \"" << str1 << "\"\n"; } else{ cout << "Number of occurances of \"" << substring << "\" in \"" << str1 << "\" is: " << cnt << "\n"; } }
Ruby
UTF-8
460
2.75
3
[]
no_license
require_relative './require_helper' require_relative './find' require 'csv' class Directory attr_accessor :directory include Find def initialize end def load_content(file_name) csv_data = CSV.open "data/" + "#{file_name}", headers: true, header_converters: :symbol @directory = csv_data.map do |row| Contact.new(row) end end def file_exist?(file_name) File.exist? "#{file_name}" end end
Java
UTF-8
1,714
3.140625
3
[]
no_license
package com.syntax.java.homework; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class PersonalInfoRead { public static void main(String[] args) throws IOException { //1. we need to have a path String filePath=System.getProperty("user.dir")+"/excel/Book1.xlsx"; //2. we need to put our paht into FileInputStream FileInputStream fis=new FileInputStream(filePath); //3.we need to build an obg of workbook as we work with excel Workbook book=new XSSFWorkbook(fis); //4. we need to get sheet named "facebook" Sheet sheet1=book.getSheet("facebook"); //5. so, right now we just need to find number of rows and colums in order to get info int rows=sheet1.getPhysicalNumberOfRows(); int colums=sheet1.getRow(0).getLastCellNum(); //6. we need to create an empty collection as we are going to add our maps that are in exel // EVERY ROW IS INDIVIDUAL MAP List <Map<String, String>> listMap=new ArrayList<>(); for (int r=1; r<rows; r++) { // here we started from 1 as 0 index is fixed Map <String,String> map=new LinkedHashMap<>(); for (int c=0;c<colums;c++) { String key=sheet1.getRow(0).getCell(c).toString(); String value=sheet1.getRow(r).getCell(c).toString(); map.put(key, value); } listMap.add(map); } System.out.println(listMap); } }
Python
UTF-8
4,103
3.3125
3
[]
no_license
class Item(object): def __init__(self, name): self.name = name class Weapon(Item): def __init__(self, name, damage): super(Weapon, self).__init__(name) self.damage = damage class Knife(Weapon): def __init__(self): # Dam. Dura. super(Knife, self).__init__("Knife", 7) class BrowningHipoint(Weapon): def __init__(self): super(BrowningHipoint, self).__init__("Browning_Hi_point", 21) class Rustyscissors(Weapon): def __init__(self): super(Rustyscissors, self).__init__("rusty_Scissors", 3) class P90BShot(Weapon): def __init__(self): super(P90BShot, self).__init__("P90_B_Shot", 29) class Spoon(Weapon): def __init__(self): super(Spoon, self).__init__("spoon", 40) class Armor(Item): def __init__(self, name, defence, durability): super(Armor, self).__init__(name) self.defence = defence self.durability = durability class Woodenchestplate(Armor): def __init__(self): super(Woodenchestplate, self).__init__("wooden chest plate", 10, 25) class Woodenhelmet(Armor): def __init__(self): super(Woodenhelmet, self).__init__("wooden helmet", 5, 20) class Woodenleggings(Armor): def __init(self): super(Woodenleggings, self).__init__("wooden leggings", 10, 25) class Steelchestplate(Armor): def __init__(self): super(Steelchestplate, self).__init__("steel chest plate", 20, 50) class Steelhelmet(Armor): def __init__(self): super(Steelhelmet, self).__init__("steel helmet", 15, 40) class Steelleggings(Armor): def __init__(self): super(Steelleggings, self).__init__("steel leggings", 20, 45) class Potion(Item): def __init__(self, name, health_healed, shield, attack_potion): super(Potion, self).__init__(name) self.health_healed = health_healed self.shield = shield self.attack_potion = attack_potion class Healthpotion(Potion): def __init__(self): super(Healthpotion, self).__init__("health_potion", 25, 0, 0) class Shieldpotion(Potion): def __init__(self): super(Shieldpotion, self).__init__("shield potion", 0, 25, 0) class Attackpotion(Potion): def __init__(self): super(Attackpotion, self).__init__("attack potion", 0, 0, 20) class Character(object): def __init__(self, name, health, weapon, armor): self.name = name self.health = health self.weapon = weapon self.armor = armor def take_damage(self, damage: int): if self.armor.defence > damage: print("You take no damage just because.") else: self.health -= damage - self.armor.defence if self.health < 0: self.health = 0 print("%s has fallen" % self.name) print("%s has %s health left" % (self.name, self.health)) def attack(self, target): if target.health <= 0: print("They are already dead.") return print("%s attacks %s for %s damage" % (self.name, target.name, self.weapon.damage)) target.take_damage(self.weapon.damage) # Items knife = Weapon("Knife", 7) browningHipoint = Weapon("Browning Hi Point", 21) rustyscissors = Weapon("Rusty scissors", 3) p90BShot = Weapon("P90 Burst Shot", 29) spoon = Weapon("Spoon", 40) claw = Weapon("Claw", 4) fist = Weapon("Fist", 1) # Armor woodenchestplate = Armor("Wooden chest plate", 10, 25) woodenhelmet = Armor("Wooden helmet", 5, 20) woodenleggings = Armor("Wooden leggings", 10, 25) steelchestplate = Armor("Steel chest plate", 20, 50) steelhelmet = Armor("Steel helmet", 15, 40) steelleggings = Armor("Steel leggings", 20, 45) # Potion healthpotion = Potion("Health potion", 25, 0, 0) shieldpotion = Potion("Shield potion", 0, 25, 0) attackpotion = Potion("Attack potion", 0, 0, 25) # Characters orc = Character("Orc1", 100, spoon, Armor("Steel chest plate", 40, 500)) orc2 = Character("Wiebe", 10000, spoon, Armor("Steel chest plate", 40, 500)) orc.attack(orc2) orc2.attack(orc) orc2.attack(orc)
C++
UTF-8
2,881
2.734375
3
[ "BSD-3-Clause" ]
permissive
#include "oclint/AbstractASTVisitorRule.h" #include "oclint/RuleSet.h" #include<fstream> using namespace std; using namespace clang; using namespace oclint; class LowerPriorityOfConditionalExpressionRule : public AbstractASTVisitorRule<LowerPriorityOfConditionalExpressionRule> { public: virtual const string name() const override { return "lower priority of conditional expression"; } virtual int priority() const override { return 3; } virtual const string category() const override { return "custom"; } #ifdef DOCGEN virtual const std::string since() const override { return "0.12"; } virtual const std::string description() const override { return ""; // TODO: fill in the description of the rule. } virtual const std::string example() const override { return R"rst( .. code-block:: cpp void example() { // TODO: modify the example for this rule. } )rst"; } /* fill in the file name only when it does not match the rule identifier virtual const std::string fileName() const override { return ""; } */ /* add each threshold's key, description, and its default value to the map. virtual const std::map<std::string, std::string> thresholds() const override { std::map<std::string, std::string> thresholdMapping; return thresholdMapping; } */ /* add additional document for the rule, like references, notes, etc. virtual const std::string additionalDocument() const override { return ""; } */ /* uncomment this method when the rule is enabled to be suppressed. virtual bool enableSuppress() const override { return true; } */ #endif virtual void setUp() override { } virtual void tearDown() override { } /* Visit ConditionalOperator */ bool VisitConditionalOperator(ConditionalOperator *node) { Expr* condExpr = node->getCond(); if(isa<ImplicitCastExpr>(condExpr)){ ImplicitCastExpr* implicitCastExpr = dyn_cast_or_null<ImplicitCastExpr>(condExpr); condExpr = implicitCastExpr->getSubExpr(); } if(isa<BinaryOperator>(condExpr)){//条件表达式条件是二元是,可能存在优先级问题 BinaryOperator* binaryOperator = dyn_cast_or_null<BinaryOperator>(condExpr); string opcStr = binaryOperator->getOpcodeStr(); string message = "Perhaps the '?:' operator works in a different way than it was expected.The '?:' operator has a lower priority than the '"+opcStr+"' operator."; addViolation(node, this, message); } return true; } private: }; static RuleSet rules(new LowerPriorityOfConditionalExpressionRule());
Java
UTF-8
5,112
3.328125
3
[]
no_license
import java.util.Random; public class Virus { //parametri sanitari della simulazione //infettivita' del virus private static int INFETTIVITA; //letalita' del virus private static int LETALITA; //sintomaticita' del virus private static int SINTOMATICITA; //durata della malattia private static int DURATA; //variabile di tipo random per determinare gli esiti dei lanci dei dadi del contagio, della sintomaticita', della mortalita' //e per stabilire i giorni in cui gli ultimi due vanno lanciati private static Random r = new Random(); //campi dell'oggetto virus //riferimento al giorno attuale della simulazione private Giorno giorno; //il giorno in cui questo oggetto "entra" nella persona private int giornoContagio; //il giorno in cui l'incubazione finisce private int giornoFineIncubazione; //il giorno in cui va lanciato il dado della sintomaticita' private int giornoDadoS; //il giorno in cui va lanciato il dado della mortalita' private int giornoDadoM; //costruttore public Virus(Giorno giorno) { this.giorno = giorno; giornoContagio = giorno.getValore(); } //controlla se il periodo di incubazione e' terminato public boolean isIncubazioneFinita() { if (giorno.getValore() == giornoFineIncubazione) { return true; } return false; } //controlla se il giorno della simulazione e' quello in cui va lanciato il dado della sintomaticita' public boolean isGiornoDadoS() { if (giorno.getValore() == giornoDadoS) return true; return false; } //controlla se il giorno della simulazione e' quello in cui va lanciato il dado della mortalita' public boolean isGiornoDadoM() { if (giorno.getValore() == giornoDadoM) return true; return false; } //controlla se il giorno della simulazione e' quello in cui la malattia termina public boolean isMalattiaFinita() { if (giorno.getValore() == giornoContagio + DURATA) return true; return false; } //calcola il giorno in cui l'incubazione del virus e' finita e la persona diventa contagiosa public void calcola_giornoFineIncubazione() { giornoFineIncubazione = giornoContagio + (DURATA / 6); } //calcola il giorno in cui va lanciato il dado della sintomaticita' public void calcola_giornoDadoS() { int bound = (giornoContagio + DURATA / 3) - giornoFineIncubazione; int g = (bound == 0 ? giornoFineIncubazione : giornoFineIncubazione + r.nextInt(bound)); setGiornoDadoS(g); } //calcola il giorno in cui va lanciato il dado della mortalita' public void calcola_giornoDadoM() { int bound = (giornoContagio + DURATA) - giornoDadoS; int g = (bound == 0 ? giornoDadoS : giornoDadoS + r.nextInt(bound)); setGiornoDadoM(g); } //determina l'esito del lancio del dado del contagio (invocato quando c'e' un contatto tra due persone) public boolean dadoContagio() { if ( r.nextInt(101) <= INFETTIVITA) return true; return false; } //determina l'esito del lancio del dado della sintomaticita' public boolean dadoS() { int x = r.nextInt(101); if (x <= SINTOMATICITA) { return true; } return false; } //determina l'esito del lancio del dado della mortalita' public boolean dadoM() { int x = r.nextInt(101); if (x <= LETALITA) return true; return false; } //static getter public static int getI() { return INFETTIVITA; } public static int getL() { return LETALITA; } public static int getS() { return SINTOMATICITA; } public static int getD() { return DURATA; } //getter public Giorno getGiorno() { return giorno; } //static setter //vanno aggiunti i controlli sulla correttezza dei parametri public static void setI(int i) { INFETTIVITA = i; } public static void setL(int l) { LETALITA = l; } public static void setS(int s) { SINTOMATICITA = s; } public static void setD(int d) { DURATA = d; } //setter public void setGiorno(Giorno giorno) { this.giorno = giorno; } public void setGiornoFineIncubazione(int giornoFineIncubazione) { if (giornoFineIncubazione < giornoContagio) throw new IllegalArgumentException("Il giornoFineIncubazione non deve essere prima del giorno contagio"); this.giornoFineIncubazione = giornoFineIncubazione; } public void setGiornoDadoS(int giornoDadoS) { if (giornoDadoS < giornoFineIncubazione) throw new IllegalArgumentException("Il giornoDadoS non deve essere prima del giorno in cui finisce l'incubazione"); this.giornoDadoS = giornoDadoS; } public void setGiornoDadoM(int giornoDadoM) { if (giornoDadoM < giornoDadoS) throw new IllegalArgumentException("Il giornoDadoM non deve essere prima del giornoDadoS"); this.giornoDadoM = giornoDadoM; } }
Python
UTF-8
1,791
2.78125
3
[]
no_license
import numpy as np import featureVector as fvec # Size of label groups = 0 with open("../data/newsgrouplabels.txt",'r') as f: for line in f: groups += 1 f.closed # Size of vocabulary voca = 0 with open("../data/vocabulary.txt",'r') as f: for line in f: voca += 1 f.closed # Load training data and label trainData = np.loadtxt("../data/train.data", delimiter=' ', dtype=int) trainLabel = np.loadtxt("../data/train.label", delimiter=' ', dtype=int) # Label list labels = np.arange(1,groups+2) # Num of docs for each label numDocsY = np.histogram(trainLabel, bins=labels)[0] # Learn p(y) using MLE for different labels probY = np.histogram(trainLabel, bins=labels, density=True)[0] # Bernoulli: Count the number of docs containing word i for each label # Multinomial: Count the number of word i for each label vectors = fvec.featureCount(trainData, trainLabel, groups, voca) berVectors = vectors[0] mulVectors = vectors[1] numDocs = len(trainLabel) # Learn Pi|y for i = 1,...,|V| using Laplace smoothing for both models probIyBer = (berVectors+1)/(numDocsY[:,np.newaxis]+numDocs) probIyMul = (mulVectors+1)/(np.sum(mulVectors,axis=1)[:,np.newaxis]+voca) # Control the priors with Dirichlet distribution alpRan = 6 alpha = [10**i for i in range(-5,1)] probIyMulAlpha = np.zeros((alpRan,groups,voca)) for index,alp in enumerate(alpha): probIyMulAlpha[index] = (mulVectors+alp)/(np.sum(mulVectors,axis=1)[:,np.newaxis]+voca*alp) # Save Pi|y for both models params = np.array([groups,voca]) np.savez("learnBer.npz", probIyBer=probIyBer, probY=probY, params=params) np.savez("learnMul.npz", probIyMul=probIyMul, probY=probY, params=params) np.savez("learnMulAlp.npz", probIyMulAlpha=probIyMulAlpha, probY=probY, params=params)
Markdown
UTF-8
16,331
2.90625
3
[]
no_license
<h1># 作者:single430 时间:2016.10.11</h1> <p> &nbsp; &nbsp; <span style="color: rgb(12, 12, 12); font-size: 20px;"><strong>一,首先(Linux环境)</strong></span> </p> <p> &nbsp;&nbsp;&nbsp;&nbsp;<span style="font-size: 18px; color: rgb(31, 73, 125);">(1):先来记录一下最近的一个项目,登录注册注销</span> </p> <p> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(0, 176, 240);">1: 首先我们需要建立一个工程,前提是你已经安装了Django and Python,使用如下命令创建:</span> </p> <p> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(255, 0, 0);">django-admin startproject mylogin</span> </p> <p> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(0, 176, 240);">2: OK,这样你就在当前路径下创建了mylogin,其结构如下,使用 <span style="color: rgb(255, 0, 0);">tree mylogin </span>查看:</span> </p> <p> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mylogin/<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── manage.py<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;└── mylogin<br/>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── __init__.py<br/>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── settings.py<br/>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── urls.py<br/>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;└── wsgi.py<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1 directory, 5 files </p> <p> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(0, 176, 240);">3: 接下来我们来创建app,对就是app,只不过我们这样创建:</span> </p> <p> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(255, 0, 0);">&nbsp;cd mylogin</span> </p> <p> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(255, 0, 0);">python manage.py startapp online</span> </p> <p> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(0, 176, 240);">&nbsp;4:&nbsp; 恩的,来看下online目录结构<span style="color: rgb(255, 0, 0);"> tree online</span>:</span> </p> <p> <span style="color: rgb(0, 176, 240);">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(0, 0, 0);">online/<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── admin.py<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── apps.py<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── __init__.py<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── migrations<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp; └── __init__.py<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── models.py<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├── tests.py<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;└── views.py<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1 directory, 7 files</span></span> </p> <p> <span style="color: rgb(0, 176, 240);">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;5: 上面的步骤结束后,请确保你是跟我一样的,然后我们打来 <span style="color: rgb(255, 0, 0);">mylogin/settings.py</span>&nbsp; 添加一些东西:&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;</span> </p> <pre style="background-color:#ffffff;color:#000000;font-family:&#39;DejaVu Sans Mono&#39;;font-size:9.0pt;"> INSTALLED_APPS = [ &#39;django.contrib.admin&#39;, &#39;django.contrib.auth&#39;, &#39;django.contrib.contenttypes&#39;, &#39;django.contrib.sessions&#39;, &#39;django.contrib.messages&#39;, &#39;django.contrib.staticfiles&#39;, &#39;online&#39;, # 对就是添加的这个 ]</pre> <p> <span style="color: rgb(0, 176, 240);">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;6: 这里我们提前加入一些东西,还是在<span style="color: rgb(255, 0, 0);">settings.py</span>中:</span> </p> <p> <span style="color: rgb(0, 176, 240);">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;首先在你的online文件夹下新建文件夹templates:<span style="color: rgb(255, 0, 0);">mkdir&nbsp; templates</span></span> </p> <p> <span style="color: rgb(0, 176, 240);">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;然后在<span style="color: rgb(255, 0, 0);">templates</span>目录下新建三个html文件:</span> </p> <p> <span style="color: rgb(0, 176, 240);">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(255, 0, 0);">account.html:</span></span> </p> <pre style="background-color:#ffffff;color:#000000;font-family:&#39;DejaVu Sans Mono&#39;;font-size:12px"> &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;注册&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;注册页面:&lt;/h1&gt; &lt;form method = &#39;post&#39; enctype=&quot;multipart/form-data&quot;&gt; {% csrf_token %} {{uf.as_p}} &lt;input type=&quot;submit&quot; value = &quot;注 册&quot; /&gt; {% if success_message %}&lt;p&gt;&lt;strong style=&quot;color: red&quot;&gt;{{ success_message }}&lt;/strong&gt;&lt;/p&gt;{% endif %} &lt;/form&gt;&lt;br&gt;&lt;a href=&quot;{% url &#39;online:mylogin&#39; %}&quot;&gt;登 陆&lt;/a&gt; &lt;/body&gt;&lt;/html&gt; index.html &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;登录成功&lt;/title&gt; &lt;/head&gt;&lt;body&gt; &lt;h1&gt;welcome {{username}} !&lt;/h1&gt;&lt;br&gt; &lt;a href=&quot;{% url &#39;online:logout&#39; %}&quot;&gt;注 销&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; login.html &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;登录&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;登陆页面:&lt;/h1&gt; {% if success_message %}&lt;p&gt;&lt;strong style=&quot;color: red&quot;&gt;{{ success_message }}&lt;/strong&gt;&lt;/p&gt;{% endif %} &lt;form method = &#39;post&#39; enctype=&quot;multipart/form-data&quot;&gt; {% csrf_token %} {{uf.as_p}} &lt;input type=&quot;submit&quot; value = &quot;登 录&quot; /&gt;&lt;/form&gt;&lt;br&gt; &lt;a href=&quot;{% url &#39;online:account&#39; %}&quot;&gt;注 册&lt;/a&gt; &lt;/body&gt; &lt;/html&gt;</pre> settings.py <pre style="background-color:#ffffff;color:#000000;font-family:&#39;DejaVu Sans Mono&#39;;font-size:9.0pt;"> TEMPLATES = [ { &#39;BACKEND&#39;: &#39;django.template.backends.django.DjangoTemplates&#39;, &#39;DIRS&#39;: [os.path.join(BASE_DIR), &#39;online/templates&#39;], # 这里,这是将你的模板引进来 ....</pre> <p> &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(0, 176, 240);">&nbsp;7: 这里我们不动数据库的选项,默认使用sqlite3数据库,等会我们需要生成数据库,名字是<span style="color: rgb(255, 0, 0);">db.sqlite3,在同manage.py同路径下的目录中</span>;</span> </p> <p> <br/> </p> <p> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(0, 176, 240);">8:&nbsp; 打开<span style="color: rgb(255, 0, 0);">mylogin目录下的urls.py</span>,改成这个样子:</span> </p> <pre style="background-color:#ffffff;color:#000000;font-family:&#39;DejaVu Sans Mono&#39;;font-size:9.0pt;"> from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r&#39;^admin/&#39;, include(admin.site.urls)), url(r&#39;^online/&#39;, include(&#39;online.urls&#39;, namespace=&quot;online&quot;)), ]</pre> <p> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(0, 176, 240);">9: 在<span style="color: rgb(255, 0, 0);">online目录下新建一个urls.py</span>, 添加如下内容:</span> </p> <pre style="background-color:#ffffff;color:#000000;font-family:&#39;DejaVu Sans Mono&#39;;font-size:9.0pt;"> from django.conf.urls import url from online import views urlpatterns = [ url(r&#39;^$&#39;, views.mylogin, name=&#39;mylogin&#39;), # 登录页面网址 url(r&#39;^login/$&#39;, views.mylogin, name=&#39;mylogin&#39;), # 登录页面网址 url(r&#39;^logout/$&#39;, views.logout, name=&#39;logout&#39;), # 注销页面网址 url(r&#39;^account/$&#39;, views.account, name=&#39;account&#39;), # 注销页面网址 url(r&#39;^index/$&#39;, views.index, name=&#39;index&#39;), # 登录成功页面网址 ]</pre> <p> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(0, 176, 240);">10: 接下来是在<span style="color: rgb(255, 0, 0);">online/models.py</span>中添加数据库(这里我们只添加用户名和密码):</span> </p> <pre style="background-color:#ffffff;color:#000000;font-family:&#39;DejaVu Sans Mono&#39;;font-size:9.0pt;"> from __future__ import unicode_literals from django.db import models # Create your models here. class MyUser(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) def __unicode__(self): return self.username</pre> <p> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: rgb(0, 176, 240);">&nbsp;11: 最后我们要在视图中添加urls.py对应的函数了<span style="color: rgb(255, 0, 0);">online/views.py</span>:</span> </p> <pre style="background-color:#ffffff;color:#000000;font-family:&#39;DejaVu Sans Mono&#39;;font-size:9.0pt;"> # coding=utf-8 from django.shortcuts import render, redirect, render_to_response from django.http import HttpResponse, HttpResponseRedirect from django import forms from django.template import RequestContext from models import MyUser # Create your views here. # 表单 class UserForm(forms.Form): username = forms.CharField(label=&#39;用户名&#39;, max_length=100) password = forms.CharField(label=&#39;密 码&#39;, widget=forms.PasswordInput()) # 登录 def mylogin(request): if request.method == &#39;POST&#39;: uf = UserForm(request.POST) if uf.is_valid(): # 获取表单用户密码 username = uf.cleaned_data[&#39;username&#39;] password = uf.cleaned_data[&#39;password&#39;] # 获取的表单数据与数据库进行比较 user = MyUser.objects.filter(username__exact=username, password__exact=password) if user: # 比较成功,跳转index response = HttpResponseRedirect(&#39;/online/index/&#39;) # 将username写入浏览器cookie,失效时间为3600 response.set_cookie(&#39;username&#39;, username, 3600) return response else: # 比较失败,还在login return HttpResponseRedirect(&#39;/online/login/&#39;) else: uf = UserForm() return render(request, &#39;login.html&#39;, {&#39;uf&#39;: uf}) # 注册 def account(request): if request.method == &#39;POST&#39;: uf = UserForm(request.POST) if uf.is_valid(): # 获得表单数据 username = uf.cleaned_data[&#39;username&#39;] password = uf.cleaned_data[&#39;password&#39;] # 添加到数据库 MyUser.objects.create(username= username, password=password) # return HttpResponse(&#39;注册成功!!&#39;) return render(request, &#39;account.html&#39;, {&#39;uf&#39;: uf, &#39;success_message&#39;: &quot;注册成功!!&quot;}) else: uf = UserForm() return render(request, &#39;account.html&#39;, {&#39;uf&#39;: uf}) # 登录成功 def index(request): username = request.COOKIES.get(&#39;username&#39;) if bool(username): return render_to_response(&#39;index.html&#39;, {&#39;username&#39;: username}) else: uf = UserForm() return render(request, &#39;login.html&#39;, {&#39;uf&#39;: uf}) # 注销 def logout(request): response = HttpResponse(&#39;Logout!!&#39;) # 清理cookie里保存username response.delete_cookie(&#39;username&#39;) # response.delete_cookie(&#39;sessionid&#39;) return response</pre> <p> <br/> </p>
TypeScript
UTF-8
930
3.171875
3
[ "MIT" ]
permissive
export const padStart = ( num: any, len: number = 2, ch: string = "0" ): string => { let output = `${num}`; while (output.length < len) { output = `${ch}${output}`; } return output; }; export const getFormatDate = ( d?: string | number | Date | null, format: string = "YYYY-MM-DD" ): string => { let date: Date; if (/[0-9]+/.test(d as string)) { d = Number(d); date = new Date(d > 1500000000 * 100 ? Math.ceil(d / 1000) : d); } else if (d instanceof Date) { date = d; } else { date = new Date(); } return format .replace("YYYY", date.getFullYear().toString()) .replace("MM", padStart(date.getMonth() + 1)) .replace("DD", padStart(date.getDate())) .replace("HH", padStart(date.getHours())) .replace("mm", padStart(date.getMinutes())) .replace("ss", padStart(date.getSeconds())); };
PHP
UTF-8
2,018
2.609375
3
[]
no_license
<?php namespace Siakad\Scheduling\Infrastructure; use Phalcon\Db\Column; use Siakad\Scheduling\Domain\Model\Dosen; use Siakad\Scheduling\Domain\Model\Mahasiswa; use Siakad\Scheduling\Domain\Model\MahasiswaPerwalianRepository; use Siakad\Scheduling\Exception\MahasiswaPerwalianNotFoundException; class SqlMahasiswaPerwalianRepository implements MahasiswaPerwalianRepository { private $connection; private $statement; private $statementTypes; const INDEX_NRP = 0, INDEX_NAMA = 1, INDEX_ID_DOSEN_WALI = 2, INDEX_NAMA_DOSEN_WALI = 3; public function __construct($di) { $this->connection = $di->get('db'); $this->statement = [ 'find_by_dosen_wali' => $this->connection->prepare(" SELECT `nrp`, mahasiswa.`nama`, `id_dosen_wali`, `dosen`.`nama` AS `nama_dosen_wali` FROM `mahasiswa` INNER JOIN `dosen` WHERE `mahasiswa`.`id_dosen_wali` = `dosen`.`id` AND `dosen`.`id` = :dosenId; ") ]; $this->statementTypes = [ 'find_by_dosen_wali' => [ 'dosenId' => Column::BIND_PARAM_INT ] ]; } public static function transformResultSetToEntity($item) { return new Mahasiswa( $item[self::INDEX_NRP], $item[self::INDEX_NAMA], new Dosen( $item[self::INDEX_ID_DOSEN_WALI], $item[self::INDEX_NAMA_DOSEN_WALI] ) ); } public function findByDosenWali($dosenId) { $statementData = [ 'dosenId' => $dosenId ]; $result = $this->connection->executePrepared( $this->statement['find_by_dosen_wali'], $statementData, $this->statementTypes['find_by_dosen_wali'] ); $mahasiswaPerwalian = array(); foreach ($result as $item) { array_push($mahasiswaPerwalian, self::transformResultSetToEntity($item)); } return $mahasiswaPerwalian; } }
Java
UTF-8
3,321
2.09375
2
[]
no_license
package myfirstapp.miguel.com.tvapp; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.method.ScrollingMovementMethod; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import java.util.concurrent.atomic.AtomicBoolean; public class InfoActivity extends AppCompatActivity { private static final AtomicBoolean FINISHED = new AtomicBoolean(false); public static void setFinished() { FINISHED.set(true); } public static boolean getFinished() { return FINISHED.get(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.info_layout); final ResultInfo infoObject = (ResultInfo) getIntent().getSerializableExtra("info"); final ImageView poster = (ImageView) findViewById(R.id.poster); final TextView title = (TextView) findViewById(R.id.movieName); final TextView plot = (TextView) findViewById(R.id.plot); final TextView director = (TextView) findViewById(R.id.director); final TextView genre = (TextView) findViewById(R.id.genre); final TextView rating = (TextView) findViewById(R.id.rating); final TextView released = (TextView) findViewById(R.id.released); final TextView writer = (TextView) findViewById(R.id.writers); final TextView runTime = (TextView) findViewById(R.id.runTime); final TextView votes = (TextView) findViewById(R.id.votes); final TextView type = (TextView) findViewById(R.id.type); final TextView awards = (TextView) findViewById(R.id.awards); final TextView actors = (TextView) findViewById(R.id.actors); final TextView episodes = (TextView) findViewById(R.id.episodes); final String actorNames = infoObject.info[12].replaceAll(", ", "\n"); if(infoObject.info[9].equals("series")) { episodes.setVisibility(View.VISIBLE); final String url = "http://www.omdbapi.com/?t=" + infoObject.info[0].trim().replace(" ", "+"); new SearchSeasonsThread().execute(url); episodes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(InfoActivity.this, EpisodesAndSeasonsActivity.class); intent.putExtra("title", infoObject.info[0]); startActivity(intent); } }); } plot.setMovementMethod(new ScrollingMovementMethod()); title.setText(infoObject.info[0]); plot.setText(infoObject.info[1]); rating.setText(infoObject.info[2]); released.setText(infoObject.info[3]); runTime.setText(infoObject.info[4]); genre.setText(infoObject.info[5]); director.setText(infoObject.info[6]); writer.setText(infoObject.info[7]); type.setText(infoObject.info[9]); votes.setText(infoObject.info[10]); awards.setText(infoObject.info[11]); actors.setText(actorNames); poster.setImageBitmap(Request.cover); } }
JavaScript
UTF-8
2,335
2.765625
3
[]
no_license
var R = require('ramda'); var firstAnswer; module.exports = [ function(input) { module.exports.wires = input.reduce(parseLine, {}); firstAnswer = module.exports.wires.a(); return firstAnswer; }, function(input) { module.exports.wires = input.reduce(parseLine, {}); module.exports.wires.b = literal(firstAnswer); return module.exports.wires.a && module.exports.wires.a(); } ]; function parseLine(wires, line) { var commandParts = line.split(' -> '); var command = commandParts[0], dest = commandParts[1]; wires[dest] = R.memoize(assignInput(wires, command)); return wires; } function assignInput(wires, command) { var tokens = command.split(' '); var wireGet = R.curry(lookup)(wires); if ('AND' === tokens[1]) { var firstArg; if (/\d+/.test(tokens[0])) { firstArg = literal(parseInt(tokens[0], 10)); } else { firstArg = wireGet(tokens[0]); } return and(firstArg, wireGet(tokens[2])); } if ('OR' === tokens[1]) { return or(wireGet(tokens[0]), wireGet(tokens[2])); } if ('LSHIFT' === tokens[1]) { return lshift(wireGet(tokens[0]), parseInt(tokens[2], 10)); } if ('RSHIFT' === tokens[1]) { return rshift(wireGet(tokens[0]), parseInt(tokens[2], 10)); } if ('NOT' === tokens[0]) { return not(wireGet(tokens[1])); } if (/^\d+$/.test(command)) { return literal(parseInt(command, 10)); } else { return wireGet(command); } throw Error('Unknown command: ' + command); } function lookup(wires, a) { return function innerLookup() { return wires[a](); } } function literal(a) { return function innerLiteral() { return a; } } function and(a, b) { return function innerAnd() { return a() & b(); } } function or(a, b) { return function innerOr() { return a() | b(); } } function lshift(a, n) { return function innerLshift() { return a() << n; } } function rshift(a, n) { return function innerRshift() { return a() >> n; } } var TO_32BIT = 65535 function not(a) { return function innerNot() { return (~a()) & TO_32BIT; } }
Python
UTF-8
154
4.03125
4
[]
no_license
a = int(input("Unesi broj a: ")) b = int(input("Unesi broj b: ")) zbroj = a + b print("Zbroj brojeva {0} i {1} iznosi {2}".format(a, b, zbroj))
Python
UTF-8
1,462
2.8125
3
[ "MIT" ]
permissive
import os from arff2pandas import a2p import pandas as pd DATASET_DIR = './tests/data/datasets/' def get_dataset_path(dataset_filename): return os.path.join(DATASET_DIR, dataset_filename) def _read_arff_dataset(infile_path): """ Loads and ARFF file to a pandas dataframe and drops meta-info on column type. """ with open(infile_path) as fh: df = a2p.load(fh) # Default column names follow ARFF, e.g. petalwidth@REAL, class@{a,b,c} df.columns = [col.split('@')[0] for col in df.columns] return df def _read_csv_dataset(path, index_col_name): return pd.read_csv(path, index_col=index_col_name) def read_dataset(dataset_metadata): """ Loads a csv or arff file (provided they are named *.{csv|arff}) """ dataset_filename = dataset_metadata["filename"] target_class_name = dataset_metadata["target_class_name"] index_col_name = dataset_metadata.get("index_col_name", None) column_types = dataset_metadata.get("column_types", None) dataset_path = get_dataset_path(dataset_filename) ext = dataset_path.split(".")[-1] if ext == "arff": dataframe = _read_arff_dataset(dataset_path) elif ext == "csv": dataframe = _read_csv_dataset(dataset_path, index_col_name) else: raise ValueError("load file type '{}' not implemented".format(ext)) X = dataframe.drop(columns=[target_class_name], axis=1) Y = dataframe[target_class_name] return X, Y, column_types
SQL
UTF-8
157
3.203125
3
[]
no_license
USE exercise; -- SELECT Email FROM email GROUP BY Email HAVING COUNT(*)>1; SELECT Email, COUNT(*) AS Duplicate FROM email GROUP BY Email HAVING COUNT(*)>1;
Python
UTF-8
259
2.671875
3
[]
no_license
from kuankr_utils.dicts import * def test_recursive_merge_with_list(): a = [{'a': 3}, {'b': [1,2,3]}] b = [{'b': 5}, {'c': 6, 'b': ['a']}, []] c = recursive_merge_with_list(a, b) assert c == [{'a': 3, 'b': 5}, {'c': 6, 'b': ['a', 2, 3]}, []]
Java
UTF-8
8,135
2.234375
2
[ "Apache-2.0" ]
permissive
package de.codescape.jira.plugins.scrumpoker.service; import com.atlassian.jira.user.ApplicationUser; import com.atlassian.jira.user.util.UserManager; import com.atlassian.plugin.spring.scanner.annotation.component.Scanned; import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport; import de.codescape.jira.plugins.scrumpoker.ao.ScrumPokerSession; import de.codescape.jira.plugins.scrumpoker.ao.ScrumPokerVote; import de.codescape.jira.plugins.scrumpoker.rest.entities.CardEntity; import de.codescape.jira.plugins.scrumpoker.rest.entities.SessionEntity; import de.codescape.jira.plugins.scrumpoker.rest.entities.VoteEntity; import org.apache.commons.lang3.math.NumberUtils; import javax.inject.Inject; import javax.inject.Named; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import static de.codescape.jira.plugins.scrumpoker.model.ScrumPokerCard.QUESTION_MARK; import static de.codescape.jira.plugins.scrumpoker.model.ScrumPokerCard.getDeck; import static java.util.Arrays.stream; import static org.apache.commons.lang3.math.NumberUtils.isNumber; /** * Service that allows to transform a {@link ScrumPokerSession} into a {@link SessionEntity}. This service creates a * model that can be used and transferred as a REST resource and is optimized for a logic less templating mechanism. */ @Scanned @Named public class SessionEntityTransformer { @ComponentImport private final UserManager userManager; @Inject public SessionEntityTransformer(UserManager userManager) { this.userManager = userManager; } /** * Transform a given {@link ScrumPokerSession} into a {@link SessionEntity}. * * @param scrumPokerSession {@link ScrumPokerSession} to transform * @param userKey key of the user * @return transformed {@link SessionEntity} */ public SessionEntity build(ScrumPokerSession scrumPokerSession, String userKey) { return new SessionEntity() .withIssueKey(scrumPokerSession.getIssueKey()) .withConfirmedVote(scrumPokerSession.getConfirmedVote()) .withVisible(scrumPokerSession.isVisible()) .withCancelled(scrumPokerSession.isCancelled()) .withBoundedVotes(boundedVotes(scrumPokerSession.getVotes())) .withVotes(votes(scrumPokerSession)) .withCards(cards(scrumPokerSession, userKey)) .withAllowReveal(allowReveal(scrumPokerSession)) .withAllowReset(allowReset(scrumPokerSession)) .withAllowCancel(allowCancel(scrumPokerSession, userKey)) .withAgreementReached(agreementReached(scrumPokerSession)) .withCreator(displayName(scrumPokerSession.getCreatorUserKey())) .withCreateDate(scrumPokerSession.getCreateDate()); } /** * Cancellation of a Scrum poker session is only allowed for the user who started the session. */ private boolean allowCancel(ScrumPokerSession scrumPokerSession, String userKey) { return scrumPokerSession.getCreatorUserKey() != null && scrumPokerSession.getCreatorUserKey().equals(userKey); } /** * Resetting a Scrum poker session is allowed when minimum one vote is given and the votes are visible. */ private boolean allowReset(ScrumPokerSession scrumPokerSession) { return scrumPokerSession.isVisible() && scrumPokerSession.getVotes().length > 0; } /** * Revealing a Scrum poker session is allowed when minimum one vote is given and the votes are hidden. */ private boolean allowReveal(ScrumPokerSession scrumPokerSession) { return !scrumPokerSession.isVisible() && scrumPokerSession.getVotes().length > 0; } /** * Returns that an agreement is reached when more than one vote is given, the votes are visible, there is no * question mark and the minimum and maximum vote are equal. */ private boolean agreementReached(ScrumPokerSession scrumPokerSession) { ScrumPokerVote[] votes = scrumPokerSession.getVotes(); return scrumPokerSession.isVisible() && votes.length > 1 && getMaximumVote(votes).equals(getMinimumVote(votes)) && stream(votes).noneMatch(scrumPokerVote -> scrumPokerVote.getVote().equals(QUESTION_MARK.getName())); } /** * Returns the cards and if the current user has provided a vote highlights the selected card. */ private List<CardEntity> cards(ScrumPokerSession scrumPokerSession, String userKey) { String chosenValue = cardForUser(scrumPokerSession.getVotes(), userKey); return getDeck().stream() .map(card -> new CardEntity(card.getName(), card.getName().equals(chosenValue))) .collect(Collectors.toList()); } /** * Returns the value of the card the current user has selected or null if the user has not voted. */ private String cardForUser(ScrumPokerVote[] votes, String userKey) { Optional<ScrumPokerVote> match = stream(votes) .filter(vote -> vote.getUserKey().equals(userKey)) .findFirst(); return match.map(ScrumPokerVote::getVote).orElse(null); } /** * Returns all votes and marks all votes that need to talk. If the deck is currently hidden only returns a question * mark instead of the correct values in order to not leak them to the clients. */ private List<VoteEntity> votes(ScrumPokerSession scrumPokerSession) { return stream(scrumPokerSession.getVotes()) .map(vote -> new VoteEntity( displayName(vote.getUserKey()), scrumPokerSession.isVisible() ? vote.getVote() : "?", needToTalk(vote.getVote(), scrumPokerSession))) .collect(Collectors.toList()); } /** * Returns whether the current vote needs to talk or not depending on the status of the Scrum poker session and the * other votes provided. */ private boolean needToTalk(String vote, ScrumPokerSession scrumPokerSession) { if (!scrumPokerSession.isVisible()) return false; if (agreementReached(scrumPokerSession)) return false; if (scrumPokerSession.getVotes().length == 1) return false; if (!isNumber(vote)) return true; Integer current = Integer.valueOf(vote); return current.equals(getMaximumVote(scrumPokerSession.getVotes())) || current.equals(getMinimumVote(scrumPokerSession.getVotes())); } /** * Returns the list of cards between and including the minimum and maximum vote. */ private List<Integer> boundedVotes(ScrumPokerVote[] votes) { return getDeck().stream() .filter(scrumPokerCard -> isNumber(scrumPokerCard.getName())) .map(scrumPokerCard -> Integer.valueOf(scrumPokerCard.getName())) .filter(value -> value >= getMinimumVote(votes) && value <= getMaximumVote(votes)) .collect(Collectors.toList()); } /** * Returns the minimum vote from the given list of votes. */ private Integer getMinimumVote(ScrumPokerVote[] votes) { return numericValues(votes).stream().reduce(Integer::min).orElse(0); } /** * Returns the maximum vote from the given list of votes. */ private Integer getMaximumVote(ScrumPokerVote[] votes) { return numericValues(votes).stream().reduce(Integer::max).orElse(100); } /** * Reduces the list of votes to only numeric votes removing all other values from the list. */ private List<Integer> numericValues(ScrumPokerVote[] votes) { return stream(votes).map(ScrumPokerVote::getVote) .filter(NumberUtils::isNumber) .map(Integer::valueOf) .collect(Collectors.toList()); } /** * Returns the display name of a user associated by the given user key. */ private String displayName(String key) { ApplicationUser user = userManager.getUserByKey(key); return user != null ? user.getDisplayName() : key; } }
Java
UTF-8
2,800
2.09375
2
[]
no_license
package com.rezalwp.training.activity.ui.tambahTraining; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import com.rezalwp.training.R; import com.rezalwp.training.model.ResponseErrorModel; public class TambahTrainingFragment extends Fragment { private TambahTrainingViewModel tambahTrainingViewModel; private EditText edtKodeTraining; private EditText edtNamaTraining; private EditText edtTipeTraining; private EditText edtKuotaTraining; private EditText edtHargaTraining; private EditText edtGambarTraining; private Button btnTraining; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { tambahTrainingViewModel = ViewModelProviders.of(this).get(TambahTrainingViewModel.class); View root = inflater.inflate(R.layout.fragment_tambah_training, container, false); edtKodeTraining = root.findViewById(R.id.edt_kode_training); edtNamaTraining = root.findViewById(R.id.edt_nama_training); edtTipeTraining = root.findViewById(R.id.edt_tipe_training); edtKuotaTraining = root.findViewById(R.id.edt_kuota_training); edtHargaTraining = root.findViewById(R.id.edt_harga_training); edtGambarTraining = root.findViewById(R.id.edt_gambar_training); btnTraining = root.findViewById(R.id.btn_training); btnTraining.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { tambahTrainingViewModel.postDataTrainings( edtKodeTraining.getText().toString().trim(), edtNamaTraining.getText().toString().trim(), edtTipeTraining.getText().toString().trim(), edtKuotaTraining.getText().toString().trim(), edtHargaTraining.getText().toString().trim(), "xx-xx-xx", edtGambarTraining.getText().toString().trim()).observe(getActivity(), new Observer<ResponseErrorModel>() { @Override public void onChanged(ResponseErrorModel trainingResponse) { Toast.makeText(getActivity(), "Sukses", Toast.LENGTH_SHORT).show(); } }); } }); return root; } }
Python
UTF-8
884
3.1875
3
[]
no_license
import spacy nlp = spacy.load('en') doc = nlp(u'The elderly Bruno knows he is not far from death. One of his last wishes is to contact his estranged son, Miles, whose marriage to an Indian woman drove a decades-long wedge between father and son. When Miles comes back into his father’s life, Bruno must confront his guilt, and his family must overcome the tension that grew during his long absence. Set against an enchanting London backdrop, Murdoch’s complex family drama is a poignant exploration of love, remorse, and the power of emotional redemption.Mark and John are sincere employees at Google.') noun_adj_pairs = [] for i,token in enumerate(doc): if token.pos_ not in ('PROPN'): continue for j in range(i+1,len(doc)): if doc[j].pos_ == 'ADJ': noun_adj_pairs.append((token,doc[j])) break print (noun_adj_pairs)
C
UTF-8
6,086
3.921875
4
[]
no_license
/** * @file test_main.c */ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <assert.h> #include <string.h> #include "libresistance.h" /** * @brief Defines the red colour */ #define ANSI_COLOR_RED "\x1b[31m" /** * @brief Defines the green colour */ #define ANSI_COLOR_GREEN "\x1b[32m" /** * @brief Define the original color, used when going back to default console colour. */ #define ANSI_COLOR_RESET "\x1b[0m" /** * @brief To avoid having to use 1 and 0, there is an enum definition that mimics true and false.*/ typedef enum { FALSE = 0, /**< The same as 0.*/ TRUE /**< The same as 1. */ } boolean; /** * @brief Prints a text with a given colour and a list of arguments * * A wrapper around printf that simplifies printing out test result text in different colours. * @param testName The name of the test * @param text The text message to print out * @param colour The colour of the text to print * @param args The arguments for the text output, it's a va_list so provide it in the same way as for a printf call * @return void **/ void printTestText(char* testName, char* text, char* colour, va_list args){ char* message; char* delimiter = ": "; char* newLine = "\n"; message = malloc(strlen(testName) + strlen(delimiter) + strlen(text) + strlen(colour) + strlen(newLine)); strcpy(message, colour); strcat(message, testName); strcat(message, delimiter); strcat(message, text); strcat(message, newLine); vprintf( message, args ); printf(ANSI_COLOR_RESET); va_end( args ); } /** * @brief Prints failing test messages * * Calls printTestText function with red text as pre defined and provide the parameters sent in * @param testName The name of the test * @param text The text message to print out * @return void **/ void printFailedTestText(char* testName, char* text,...){ va_list args; va_start( args, text ); printTestText(testName, text, ANSI_COLOR_RED, args); } /** * @brief Prints successful test messages * * Calls printTestText function with green text as pre defined and provide the parameters sent in * @param testName The name of the test * @param text The text message to print out * @return void **/ void printSuccessTestText(char* testName, char* text,...){ va_list args; va_start( args, text ); printTestText(testName, text, ANSI_COLOR_GREEN, args); } /** * @brief Test method that is used to check if two floats are the same * * Compare two float values and returns 1 if it's the same and 0 if it's not. It allso makes an assert(expected == given). * @param testName The name of the test * @param expected The value to expect * @param given The value returned by the test * @return Returns 1(TRUE) if the test is ok and 0(FALSE) if it's not **/ unsigned assertIsTheSame(char* testName,float expected, float given){ if(expected == given){ return TRUE; } else{ printFailedTestText(testName, "The numbers are not the same. Should be %f but was %f", expected, given); assert(expected == given); return FALSE; } } /** * @brief Test method that is used to check if two floats are not the same * * Compare two float values and returns 1 if it's not the same and 0 if it is. It allso makes an assert(expected != given). * @param testName The name of the test * @param expected The value to expect * @param given The value returned by the test * @return Returns 1(TRUE) if the test is ok and 0(FALSE) if it's not **/ unsigned assertIsNotTheSame(char* testName, float expected, float given){ if(expected != given){ return TRUE; } else{ printFailedTestText(testName, "The numbers are the same. Should not be %f but was %f", expected, given); assert(expected != given); return FALSE; } } /** * @brief Runs all the tests * * Runs all the tests and returns 0 if it's ok and 1 if it's not * @return Returns 0 if it's ok and 1 if it's not ok. **/ int main(){ unsigned int testResult = TRUE; float returnValue; int INVALID_ARGUMENT = -1; float testArray[2] = {1,2}; int testArraySize = sizeof(testArray)/sizeof(testArray[0]); returnValue = calc_resistance(0,'P',0); testResult = assertIsTheSame("Check that count 0 is not allowed", INVALID_ARGUMENT, returnValue); returnValue = calc_resistance(-1,'P',0); testResult = assertIsTheSame("Check that count lower than 0 is not allowed",INVALID_ARGUMENT, returnValue); returnValue = calc_resistance(testArraySize, 'V', testArray); testResult = assertIsTheSame("Sending in V in conn and should get -1 as a result", INVALID_ARGUMENT, returnValue); float* nullPointer = 0; returnValue = calc_resistance(4, 'P', nullPointer); testResult = assertIsTheSame("Sending in the array with a null pointer gives -1 as result", INVALID_ARGUMENT, returnValue); float testArrayWithOneZeroItem[3] = {0,1,2}; returnValue = calc_resistance(testArraySize, 'P', testArrayWithOneZeroItem); testResult = assertIsTheSame("Sending in one array item with 0 and P should give return value 0", 0, returnValue); returnValue = calc_resistance(testArraySize, 'S', testArrayWithOneZeroItem); testResult = assertIsNotTheSame("Sending in one array item with 0 and S should not give return value 0", 0, returnValue); returnValue = calc_resistance(testArraySize, 'S', testArray); testResult = assertIsTheSame("Verify that summary of resistance items for S is working", 3, returnValue); float testArrayWithRealResistanceScenario[2] = {150,300}; returnValue = calc_resistance(sizeof(testArrayWithRealResistanceScenario)/sizeof(testArrayWithRealResistanceScenario[0]), 'P', testArrayWithRealResistanceScenario); testResult = assertIsTheSame("Verify that summary of resistance items for P is working", 100, returnValue); if(testResult != TRUE){ printFailedTestText("All", "There were tests failing, se above for more information"); return 1; } else { printSuccessTestText("All","All tests were ok!"); return 0; } }
Python
UTF-8
985
4.46875
4
[]
no_license
""" Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number. """ #initialize the variable for count and sum. count = 0 sum = 0 #iteration with whil loop to ask user to enter the value till 'done'. while True: #try and except used to get the int value in command prompt. try: num = input('Enter a number: ') if num == 'done': break num = int(num) except: print('Invalid input') continue # get count in every iteration. count = count + 1 #get sum for every iteration. sum = sum + num #get average between total sum and total count. average = sum/count # print total values for sum,count,average. print(sum,count,average)
PHP
UTF-8
1,472
2.71875
3
[]
no_license
<?php require './config/config.php'; require_once './hooks/signup.hook.php'; require_once './hooks/login.hook.php'; if ($_SERVER['REQUEST_METHOD'] == 'POST') { if(isset($_POST['login_form'])){ //process the login $email = $_POST['email']; $password = md5($_POST['password']); if(verifyUser(['username' => $email, 'password' => $password])){ echo "You have been logged in successfully"; } else { echo "Please enter valid username and password"; } } elseif(isset($_POST['signup_form'])) { // proccess the signup $email = $_POST['email']; if(checkUser($email)){ header('Location: ./signup.php?err=' . $email . ' has already been taken'); exit(); } $password = md5($_POST['password']); if(saveUser(['username' => $email, "password" => $password])){ header('location: ../blog.php'); exit(); } else { $error_msg = "Please try agin letter"; $error_msg = base64_encode($error_msg); header('location: ../some_thing_went_wrong.php?err=' .$error_msg); exit(); } } else{ //something was wrong echo "No form has been submitted"; var_dump($_POST); } } else { //redirect the user to the home page header("location: ".BASE_URL); }
Markdown
UTF-8
2,075
2.546875
3
[ "MIT" ]
permissive
# dev 🤓 Contains some hopefully helpful scripts for development. - [Usage](#usage) - [checkBuild](#checkbuild) - [checkCoverage](#checkcoverage) - [checkForFlaggedTests](#checkforflaggedtests) ## Usage To make use of these scripts you can clone this repository to your preferred location like: git clone https://github.com/tweetjay/dev.git and add the path to your shell `PATH` environment variable. For the 🦄 `fish`-shell this would look like: set -g fish_user_paths $fish_user_paths "$HOME/.dev" Afterwards you should be able to call the script from every place, e.g.: $: checkDebug.sh <library> ## checkBuild 🚧 This script is currently intended to be used with libraries build for iOS. It can be used to check iOS build artifacts for various unwanted stuff. The following functions will check: - `__check_architectures`: if the artifact contains only the valid architectures - `__check_coverage_symbols`: if the artifact contains code coverage symbols - `__check_profiling_data`: if the artifact contains profiling symbols - `__check_encryption`: if encryption information is present - `__check_bitcode_availability`: if bitcode is enabled - `__check_for_assertion`: if the artifact contains assertion symbols - `__check_debug_symbols`: if the artifact contains debug symbols The script takes one parameter which is the path to the artifact to check: $: checkDebug.sh <library> If you check a build artifact with this script it will look like: ![checkBuild.sh](./images/shell-checkBuild.png "checkBuild.sh") ## checkCoverage This script is intended to be used for Xcode schemes which will be build and calls xcrun to view the coverage reports. ## checkForFlaggedTests This script is intended to be used with Swift or Objective C written tests. It should be called in the folder where the tests are placed or at least in the project folder. It will search all `.swift` and `.m` files for patterns like `fit()` ### Requirements - This script needs the famous [silver searcher](https://github.com/ggreer/the_silver_searcher)
Swift
UTF-8
1,089
2.859375
3
[]
no_license
// // Users+CoreDataClass.swift // // // Created by Kiarash Teymoury on 6/20/17. // // import Foundation import CoreData @objc(Users) public class Users: NSManagedObject { convenience init(dictionary:NSDictionary, insertIntoManagedObjectContext context: NSManagedObjectContext) { let entityName = NSEntityDescription.entity(forEntityName: "Users", in: context) self.init(entity: entityName!, insertInto: context) } class func fetchUsersForEvent(event:Events) -> Users { let usersRequest: NSFetchRequest<Users> = Users.fetchRequest() usersRequest.predicate = NSPredicate(format: "events.event_id = %@", event.event_id!) do { let users = try context.fetch(usersRequest) for user in users { print(user.owner_name ?? "") return user } } catch { fatalError("Error Fetching Users") } return Users(context: context) } }
C#
UTF-8
1,097
2.515625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace FitBull.WebService { /// <summary> /// WebService için özet açıklama /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // Bu Web Hizmeti'nin, ASP.NET AJAX kullanılarak komut dosyasından çağrılmasına, aşağıdaki satırı açıklamadan kaldırmasına olanak vermek için. // [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { FitBull.DataAccess.FitBullEntities ent = new DataAccess.FitBullEntities(); [WebMethod] public List<FitBull.DataAccess.Antrenman> Antrenmanlar() { var antrenman = ent.Antrenman.ToList(); return antrenman; } public List<FitBull.DataAccess.Diyet> Diyetler() { var diyet = ent.Diyet.ToList(); return diyet; } } }
Python
UTF-8
28,709
3.046875
3
[]
no_license
#coding:utf-8 import sys, os sys.path.append(os.getcwd()) from server import Post, User, db def add_data(): db.drop_all() db.create_all() user1 = User("leiyi") user2 = User("leiyi2") user2.id = 2222 db.session.add(user1) db.session.add(user2) db.session.commit() post1 = Post("a") post1.user_id = user1.id post1.text = "asdfsg" post2 = Post("b") post2.user_id = user1.id post2.text = u'''目录 1 为什么要记录特征转换行为? 2 有哪些特征转换的方式? 3 特征转换的组合 4 sklearn源码分析   4.1 一对一映射   4.2 一对多映射   4.3 多对多映射 5 实践 6 总结 7 参考资料 1 为什么要记录特征转换行为?   使用机器学习算法和模型进行数据挖掘,有时难免事与愿违:我们依仗对业务的理解,对数据的分析,以及工作经验提出了一些特征,但是在模型训练完成后,某些特征可能“身微言轻”——我们认为相关性高的特征并不重要,这时我们便要反思这样的特征提出是否合理;某些特征甚至“南辕北辙”——我们认为正相关的特征结果变成了负相关,造成这种情况很有可能是抽样与整体不相符,模型过于复杂,导致了过拟合。然而,我们怎么判断先前的假设和最后的结果之间的差异呢?   线性模型通常有含有属性coef_,当系数值大于0时为正相关,当系数值小于0时为负相关;另外一些模型含有属性feature_importances_,顾名思义,表示特征的重要性。根据以上两个属性,便可以与先前假设中的特征的相关性(或重要性)进行对比了。但是,理想是丰满的,现实是骨感的。经过复杂的特征转换之后,特征矩阵X已不再是原来的样子:哑变量使特征变多了,特征选择使特征变少了,降维使特征映射到另一个维度中。   累觉不爱了吗?如果,我们能够将最后的特征与原特征对应起来,那么分析特征的系数和重要性又有了意义了。所以,在训练过程(或者转换过程)中,记录下所有特征转换行为是一个有意义的工作。可惜,sklearn暂时并没有提供这样的功能。在这篇博文中,我们尝试对一些常见的转换功能进行行为记录,读者可以在此基础进行进一步的拓展。 2 有哪些特征转换的方式?   《使用sklearn做单机特征工程》一文概括了若干常见的转换功能: 类名 功能 说明 StandardScaler 数据预处理(无量纲化) 标准化,基于特征矩阵的列,将特征值转换至服从标准正态分布 MinMaxScaler 数据预处理(无量纲化) 区间缩放,基于最大最小值,将特征值转换到[0, 1]区间上 Normalizer 数据预处理(归一化) 基于特征矩阵的行,将样本向量转换为“单位向量” Binarizer 数据预处理(二值化) 基于给定阈值,将定量特征按阈值划分 OneHotEncoder 数据预处理(哑编码) 将定性数据编码为定量数据 Imputer 数据预处理(缺失值计算) 计算缺失值,缺失值可填充为均值等 PolynomialFeatures 数据预处理(多项式数据转换) 多项式数据转换 FunctionTransformer 数据预处理(自定义单元数据转换) 使用单变元的函数来转换数据 VarianceThreshold 特征选择(Filter) 方差选择法 SelectKBest 特征选择(Filter) 可选关联系数、卡方校验、最大信息系数作为得分计算的方法 RFE 特征选择(Wrapper) 递归地训练基模型,将权值系数较小的特征从特征集合中消除 SelectFromModel 特征选择(Embedded) 训练基模型,选择权值系数较高的特征 PCA 降维(无监督) 主成分分析法 LDA 降维(有监督) 线性判别分析法   按照特征数量是否发生变化,这些转换类可分为: 无变化:StandardScaler,MinMaxScaler,Normalizer,Binarizer,Imputer,FunctionTransformer* 有变化:OneHotEncoder,PolynomialFeatures,VarianceThreshold,SelectKBest,RFE,SelectFromModel,PCA,LDA FunctionTransformer*:自定义的转换函数通常不会使特征数量发生变化   对于不造成特征数量变化的转换类,我们只需要保持特征不变即可。在此,我们主要研究那些有变化的转换类,其他转换类都默认为无变化。按照映射的形式,可将以上有变化的转换类可分为: 一对一:VarianceThreshold,SelectKBest,RFE,SelectFromModel 一对多:OneHotEncoder 多对多:PolynomialFeatures,PCA,LDA   原特征与新特征为一对一映射通常发生在特征选择时,若原特征被选择则直接变成新特征,否则抛弃。哑编码为典型的一对多映射,需要哑编码的原特征将会转换为多个新特征。多对多的映射中PolynomialFeatures并不要求每一个新特征都与原特征建立映射关系,例如阶为2的多项式转换,第一个新特征只由第一个原特征生成(平方)。降维的本质在于将原特征矩阵X映射到维度更低的空间中,使用的技术通常是矩阵乘法,所以它既要求每一个原特征映射到所有新特征,同时也要求每一个新特征被所有原特征映射。 3 特征转换的组合   在《使用sklearn优雅地进行数据挖掘》一文中,我们看到一个基本的数据挖掘场景:   特征转换行为通常是流水线型和并行型结合的。所以,我们考虑重新设计流水线处理类Pipeline和并行处理类FeatureUnion,使其能够根据不同的特征转换类,记录下转换行为“日志”。“日志”的表示形式也是重要的,由上图可知,集成后的特征转换过程呈现无环网状,故使用网络来描述“日志”是合适的。在网络中,节点表示特征,有向连线表示特征转换。   为此,我们新增两个类型Feature和Transfrom来构造网络结构,Feature类型表示网络中的节点,Transform表示网络中的有向边。python的networkx库可以很好地表述网络和操作网络,我这是要重新造轮子吗?其实并不是,现在考虑代表新特征的节点怎么命名的问题,显然,不能与网络中任意节点同名,否则会发生混淆。然而,由于sklearn的训练过程存在并行过程(线程),直接使用network来构造网络的话,将难以处理节点重复命名的问题。所以,我才新增两个新的类型来描述网络结构,这时网络中的节点名是可以重复的。最后,对这网络进行广度遍历,生成基于networkx库的网络,因为这个过程是串行的,故可以使用“当前节点数”作为新增节点的序号了。这两个类的代码(feature.py)设计如下: 复制代码 1 import numpy as np 2 3 class Transform(object): 4 def __init__(self, label, feature): 5 super(Transform, self).__init__() 6 #边标签名,使用networkx等库画图时将用到 7 self.label = label 8 #该边指向的节点 9 self.feature = feature 10 11 class Feature(object): 12 def __init__(self, name): 13 super(Feature, self).__init__() 14 #节点名称,该名称在网络中不唯一,在某些映射中,该名称需要直接传给新特征 15 self.name = name 16 #节点标签名,该名称在网络中唯一,使用networkx等库画图时将用到 17 self.label = '%s[%d]' % (self.name, id(self)) 18 #从本节点发出的有向边列表 19 self.transformList = np.array([]) 20 21 #建立从self到feature的有向边 22 def transform(self, label, feature): 23 self.transformList = np.append(self.transformList, Transform(label, feature)) 24 25 #深度遍历输出以本节点为源节点的网络 26 def printTree(self): 27 print self.label 28 for transform in self.transformList: 29 feature = transform.feature 30 print '--%s-->' % transform.label, 31 feature.printTree() 32 33 def __str__(self): 34 return self.label 复制代码 4 sklearn源码分析   我们可以统一地记录不改变特征数量的转换行为:在“日志”网络中,从代表原特征的节点,引伸出连线连上唯一的代表新特征的节点。然而,对于改变特征数量的转换行为来说,需要针对每个转换类编写不同的“日志”记录(网络生成)代码。为不改变特征数量的转换行为设计代码(default.py)如下: 复制代码 1 import numpy as np 2 from feature import Feature 3 4 def doWithDefault(model, featureList): 5 leaves = np.array([]) 6 7 n_features = len(featureList) 8 9 #为每一个输入的原节点,新建一个新节点,并建立映射 10 for i in range(n_features): 11 feature = featureList[i] 12 newFeature = Feature(feature.name) 13 feature.transform(model.__class__.__name__, newFeature) 14 leaves = np.append(leaves, newFeature) 15 16 #返回新节点列表,之所以该变量取名叫leaves,是因为其是网络的边缘节点 17 return leaves 复制代码 4.1 一对一映射   映射形式为一对一时,转换类通常为特征选择类。在这种映射下,原特征要么只转化为一个新特征,要么不转化。通过分析sklearn源码不难发现,特征选择类都混入了特质sklearn.feature_selection.base.SelectorMixin,因此这些类都有方法get_support来获取哪些特征转换信息:   所以,在设计“日志”记录模块时,判断转换类是否混入了该特征,若是则直接调用get_support方法来得到被筛选的特征的掩码或者下标,如此我们便可从被筛选的特征引伸出连线连上新特征。为此,我们设计代码(one2one.py)如下: 复制代码 1 import numpy as np 2 from sklearn.feature_selection.base import SelectorMixin 3 from feature import Feature 4 5 def doWithSelector(model, featureList): 6 assert(isinstance(model, SelectorMixin)) 7 8 leaves = np.array([]) 9 10 n_features = len(featureList) 11 12 #新节点的掩码 13 mask_features = model.get_support() 14 15 for i in range(n_features): 16 feature = featureList[i] 17 #原节点被选择,生成新节点,并建立映射 18 if mask_features[i]: 19 newFeature = Feature(feature.name) 20 feature.transform(model.__class__.__name__, newFeature) 21 leaves = np.append(leaves, newFeature) 22 #原节点被抛弃,生成一个名为Abandomed的新节点,建立映射,但是这个特征不加入下一步继续生长的节点列表 23 else: 24 newFeature = Feature('Abandomed') 25 feature.transform(model.__class__.__name__, newFeature) 26 27 return leaves 复制代码 4.2 一对多映射   OneHotEncoder是典型的一对多映射转换类,其提供了两个属性结合两个参数来表示转换信息: n_values:定性特征的值数量,若为auto则直接从训练集中获取,若为整数则表示所有定性特征的值数量+1,若为数组则分别表示每个定性特征的数量+1 categorical_features:定性特征的掩码或下标 active_features_:有效值(在n_values为auto时有用),假设A属性取值范围为(1,2,3),但是实际上训练样本中只有(1,2),假设B属性取值范围为(2,3,4),训练样本中只有(2,4),那么有效值为(1,2,5,7)。是不是感到奇怪了,为什么有效值不是(1,2,2,4)?OneHotEncoder在这里做了巧妙的设计:有效值被转换成了一个递增的序列,这样方便于配合属性n_features快速地算出每个原特征转换成了哪些新特征,转换依据的真实有效值是什么。 feature_indices_:每个定性特征的有效值范围,例如第i个定性特征,其有效值范围为feature_indices_[i]至feature_indices_[i+1],sklearn官方文档在此描述有误,该数组的长度应为n_features+1。在上例中,feature_indices_等于(0,3,8)。故下标为0的定性特征,其有效值范围为大于0小于3,则有效值为1和2;下标为1的定性特征,其有效值范围为大于3小于8,则有效值为5和7。下标为0的定性特征,其两个真实有效值为1-0=1和2-0=2;下标为1的定性特征,其两个真实有效值为5-3=2和7-3=4。这样一来就可以得到(1,2,2,4)的真实有效值了。   综上,我们设计处理OneHotEncoder类的代码(one2many.py)如下: 复制代码 1 import numpy as np 2 from sklearn.preprocessing import OneHotEncoder 3 from feature import Feature 4 5 def doWithOneHotEncoder(model, featureList): 6 assert(isinstance(model, OneHotEncoder)) 7 assert(hasattr(model, 'feature_indices_')) 8 9 leaves = np.array([]) 10 11 n_features = len(featureList) 12 13 #定性特征的掩码 14 if model.categorical_features == 'all': 15 mask_features = np.ones(n_features) 16 else: 17 mask_features = np.zeros(n_features) 18 mask_features[self.categorical_features] = 1 19 20 #定性特征的数量 21 n_qualitativeFeatures = len(model.feature_indices_) - 1 22 #如果定性特征的取值个数是自动的,即从训练数据中生成 23 if model.n_values == 'auto': 24 #定性特征的有效取值列表 25 n_activeFeatures = len(model.active_features_) 26 #变量j为定性特征的下标,变量k为有效值的下标 27 j = k = 0 28 for i in range(n_features): 29 feature = featureList[i] 30 #如果是定性特征 31 if mask_features[i]: 32 if model.n_values == 'auto': 33 #为属于第j个定性特征的每个有效值生成一个新节点,建立映射关系 34 while k < n_activeFeatures and model.active_features_[k] < model.feature_indices_[j+1]: 35 newFeature = Feature(feature.name) 36 feature.transform('%s[%d]' % (model.__class__.__name__, model.active_features_[k] - model.feature_indices_[j]), newFeature) 37 leaves = np.append(leaves, newFeature) 38 k += 1 39 else: 40 #为属于第j个定性特征的每个有效值生成一个新节点,建立映射关系 41 for k in range(model.feature_indices_[j]+1, model.feature_indices_[j+1]): 42 newFeature = Feature(feature.name) 43 feature.transform('%s[%d]' % (model.__class__.__name__, k - model.feature_indices_[j]), newFeature) 44 leaves = np.append(leaves, newFeature) 45 j += 1 46 #如果不是定性特征,则直接根据原节点生成新节点 47 else: 48 newFeature = Feature(feature.name) 49 feature.transform('%s[r]' % model.__class__.__name__, newFeature) 50 leaves = append(leaves, newFeatures) 51 52 return leaves 复制代码 4.3 多对多映射   PCA类是典型的多对多映射的转换类,其提供了参数n_components_来表示转换后新特征的个数。之前说过降维的转换类,其既要求每一个原特征映射到所有新特征,也要求每一个新特征被所有原特征映射。故,我们设计处理PCA类的代码(many2many.py)如下: 复制代码 1 import numpy as np 2 from sklearn.decomposition import PCA 3 from feature import Feature 4 5 def doWithPCA(model, featureList): 6 leaves = np.array([]) 7 8 n_features = len(featureList) 9 10 #按照主成分数生成新节点 11 for i in range(model.n_components_): 12 newFeature = Feature(model.__class__.__name__) 13 leaves = np.append(leaves, newFeature) 14 15 #为每一个原节点与每一个新节点建立映射 16 for i in range(n_features): 17 feature = featureList[i] 18 for j in range(model.n_components_): 19 newFeature = leaves[j] 20 feature.transform(model.__class__.__name__, newFeature) 21 22 return leaves 复制代码 5 实践   到此,我们可以专注改进流水线处理和并行处理的模块了。为了不破坏Pipeline类和FeatureUnion类的核心功能,我们分别派生出两个类PipelineExt和FeatureUnionExt。其次,为这两个类增加私有方法getFeatureList,这个方法有只有一个参数featureList表示输入流水线处理或并行处理的特征列表(元素为feature.Feature类的对象),输出经过流水线处理或并行处理后的特征列表。设计内部方法_doWithModel,其被getFeatureList方法调用,其提供了一个公共的入口,将根据流水线上或者并行中的转换类的不同,具体调用不同的处理方法(这些不同的处理方法在one2one.py,one2many.py,many2many.py中定义)。在者,我们还需要一个initRoot方法来初始化网络结构,返回一个根节点。最后,我们尝试用networkx库读取自定义的网络结构,基于matplotlib的对网络进行图形化显示。以上部分的代码(ple.py)如下: 复制代码 1 from sklearn.feature_selection.base import SelectorMixin 2 from sklearn.preprocessing import OneHotEncoder 3 from sklearn.decomposition import PCA 4 from sklearn.pipeline import Pipeline, FeatureUnion, _fit_one_transformer, _fit_transform_one, _transform_one 5 from sklearn.externals.joblib import Parallel, delayed 6 from scipy import sparse 7 import numpy as np 8 import networkx as nx 9 from matplotlib import pyplot as plt 10 from default import doWithDefault 11 from one2one import doWithSelector 12 from one2many import doWithOneHotEncoder 13 from many2many import doWithPCA 14 from feature import Feature 15 16 #派生Pipeline类 17 class PipelineExt(Pipeline): 18 def _pre_get_featues(self, featureList): 19 leaves = featureList 20 for name, transform in self.steps[:-1]: 21 leaves = _doWithModel(transform, leaves) 22 return leaves 23 24 #定义getFeatureList方法 25 def getFeatureList(self, featureList): 26 leaves = self._pre_get_featues(featureList) 27 model = self.steps[-1][-1] 28 if hasattr(model, 'fit_transform') or hasattr(model, 'transform'): 29 leaves = _doWithModel(model, leaves) 30 return leaves 31 32 #派生FeatureUnion类,该类不仅记录了转换行为,同时也支持部分数据处理 33 class FeatureUnionExt(FeatureUnion): 34 def __init__(self, transformer_list, idx_list, n_jobs=1, transformer_weights=None): 35 self.idx_list = idx_list 36 FeatureUnion.__init__(self, transformer_list=map(lambda trans:(trans[0], trans[1]), transformer_list), n_jobs=n_jobs, transformer_weights=transformer_weights) 37 38 def fit(self, X, y=None): 39 transformer_idx_list = map(lambda trans, idx:(trans[0], trans[1], idx), self.transformer_list, self.idx_list) 40 transformers = Parallel(n_jobs=self.n_jobs)( 41 delayed(_fit_one_transformer)(trans, X[:,idx], y) 42 for name, trans, idx in transformer_idx_list) 43 self._update_transformer_list(transformers) 44 return self 45 46 def fit_transform(self, X, y=None, **fit_params): 47 transformer_idx_list = map(lambda trans, idx:(trans[0], trans[1], idx), self.transformer_list, self.idx_list) 48 result = Parallel(n_jobs=self.n_jobs)( 49 delayed(_fit_transform_one)(trans, name, X[:,idx], y, 50 self.transformer_weights, **fit_params) 51 for name, trans, idx in transformer_idx_list) 52 53 Xs, transformers = zip(*result) 54 self._update_transformer_list(transformers) 55 if any(sparse.issparse(f) for f in Xs): 56 Xs = sparse.hstack(Xs).tocsr() 57 else: 58 Xs = np.hstack(Xs) 59 return Xs 60 61 def transform(self, X): 62 transformer_idx_list = map(lambda trans, idx:(trans[0], trans[1], idx), self.transformer_list, self.idx_list) 63 Xs = Parallel(n_jobs=self.n_jobs)( 64 delayed(_transform_one)(trans, name, X[:,idx], self.transformer_weights) 65 for name, trans, idx in transformer_idx_list) 66 if any(sparse.issparse(f) for f in Xs): 67 Xs = sparse.hstack(Xs).tocsr() 68 else: 69 Xs = np.hstack(Xs) 70 return Xs 71 72 #定义getFeatureList方法 73 def getFeatureList(self, featureList): 74 transformer_idx_list = map(lambda trans, idx:(trans[0], trans[1], idx), self.transformer_list, self.idx_list) 75 leaves = np.array(Parallel(n_jobs=self.n_jobs)( 76 delayed(_doWithModel)(trans, featureList[idx]) 77 for name, trans, idx in transformer_idx_list)) 78 leaves = np.hstack(leaves) 79 return leaves 80 81 #定义为每个模型进行转换记录的总入口方法,该方法将根据不同的转换类调用不同的处理方法 82 def _doWithModel(model, featureList): 83 if isinstance(model, SelectorMixin): 84 return doWithSelector(model, featureList) 85 elif isinstance(model, OneHotEncoder): 86 return doWithOneHotEncoder(model, featureList) 87 elif isinstance(model, PCA): 88 return doWithPCA(model, featureList) 89 elif isinstance(model, FeatureUnionExt) or isinstance(model, PipelineExt): 90 return model.getFeatureList(featureList) 91 else: 92 return doWithDefault(model, featureList) 93 94 #初始化网络的根节点,输入参数为原始特征的名称 95 def initRoot(featureNameList): 96 root = Feature('root') 97 for featureName in featureNameList: 98 newFeature = Feature(featureName) 99 root.transform('init', newFeature) 100 return root 复制代码   现在,我们需要验证一下成果了,不妨继续使用博文《使用sklearn优雅地进行数据挖掘》中提供的场景来进行测试: 复制代码 1 import numpy as np 2 from sklearn.datasets import load_iris 3 from sklearn.preprocessing import Imputer 4 from sklearn.preprocessing import OneHotEncoder 5 from sklearn.preprocessing import FunctionTransformer 6 from sklearn.preprocessing import Binarizer 7 from sklearn.preprocessing import MinMaxScaler 8 from sklearn.feature_selection import SelectKBest 9 from sklearn.feature_selection import chi2 10 from sklearn.decomposition import PCA 11 from sklearn.linear_model import LogisticRegression 12 from sklearn.pipeline import Pipeline, FeatureUnion 13 from ple import PipelineExt, FeatureUnionExt, initRoot 14 15 def datamining(iris, featureList): 16 step1 = ('Imputer', Imputer()) 17 step2_1 = ('OneHotEncoder', OneHotEncoder(sparse=False)) 18 step2_2 = ('ToLog', FunctionTransformer(np.log1p)) 19 step2_3 = ('ToBinary', Binarizer()) 20 step2 = ('FeatureUnionExt', FeatureUnionExt(transformer_list=[step2_1, step2_2, step2_3], idx_list=[[0], [1, 2, 3], [4]])) 21 step3 = ('MinMaxScaler', MinMaxScaler()) 22 step4 = ('SelectKBest', SelectKBest(chi2, k=3)) 23 step5 = ('PCA', PCA(n_components=2)) 24 step6 = ('LogisticRegression', LogisticRegression(penalty='l2')) 25 pipeline = PipelineExt(steps=[step1, step2, step3, step4, step5, step6]) 26 pipeline.fit(iris.data, iris.target) 27 #最终的特征列表 28 leaves = pipeline.getFeatureList(featureList) 29 #为最终的特征输出对应的系数 30 for i in range(len(leaves)): 31 print leaves[i], pipeline.steps[-1][-1].coef_[i] 32 33 def main(): 34 iris = load_iris() 35 iris.data = np.hstack((np.random.choice([0, 1, 2], size=iris.data.shape[0]+1).reshape(-1,1), np.vstack((iris.data, np.full(4, np.nan).reshape(1,-1))))) 36 iris.target = np.hstack((iris.target, np.array([np.median(iris.target)]))) 37 root = initRoot(['color', 'Sepal.Length', 'Sepal.Width', 'Petal.Length', 'Petal.Width']) 38 featureList = np.array([transform.feature for transform in root.transformList]) 39 40 datamining(iris, featureList) 41 42 root.printTree() 43 44 if __name__ == '__main__': 45 main() 复制代码   运行程序,最终的特征及对应的系数输出如下:   输出网络结构的深度遍历(部分截图):   为了更好的展示转换行为构成的网络,我们还可以基于networkx构建有向图,通过matplotlib进行展示(ple.py): 复制代码 1 #递归的方式进行深度遍历,生成基于networkx的有向图 2 def _draw(G, root, nodeLabelDict, edgeLabelDict): 3 nodeLabelDict[root.label] = root.name 4 for transform in root.transformList: 5 G.add_edge(root.label, transform.feature.label) 6 edgeLabelDict[(root.label, transform.feature.label)] = transform.label 7 _draw(G, transform.feature, nodeLabelDict, edgeLabelDict) 8 9 #判断是否图是否存在环 10 def _isCyclic(root, walked): 11 if root in walked: 12 return True 13 else: 14 walked.add(root) 15 for transform in root.transformList: 16 ret = _isCyclic(transform.feature, walked) 17 if ret: 18 return True 19 walked.remove(root) 20 return False 21 22 #广度遍历生成瀑布式布局 23 def fall_layout(root, x_space=1, y_space=1): 24 layout = {} 25 if _isCyclic(root, set()): 26 raise Exception('Graph is cyclic') 27 28 queue = [None, root] 29 nodeDict = {} 30 levelDict = {} 31 level = 0 32 while len(queue) > 0: 33 head = queue.pop() 34 if head is None: 35 if len(queue) > 0: 36 level += 1 37 queue.insert(0, None) 38 else: 39 if head in nodeDict: 40 levelDict[nodeDict[head]].remove(head) 41 nodeDict[head] = level 42 levelDict[level] = levelDict.get(level, []) + [head] 43 for transform in head.transformList: 44 queue.insert(0, transform.feature) 45 46 for level in levelDict.keys(): 47 nodeList = levelDict[level] 48 n_nodes = len(nodeList) 49 offset = - n_nodes / 2 50 for i in range(n_nodes): 51 layout[nodeList[i].label] = (level * x_space, (i + offset) * y_space) 52 53 return layout 54 55 def draw(root): 56 G = nx.DiGraph() 57 nodeLabelDict = {} 58 edgeLabelDict = {} 59 60 _draw(G, root, nodeLabelDict, edgeLabelDict) 61 #设定网络布局方式为瀑布式 62 pos = fall_layout(root) 63 64 nx.draw_networkx_nodes(G,pos,node_size=100, node_color="white") 65 nx.draw_networkx_edges(G,pos, width=1,alpha=0.5,edge_color='black') 66 #设置网络中节点的标签内容及格式 67 nx.draw_networkx_labels(G,pos,labels=nodeLabelDict, font_size=10,font_family='sans-serif') 68 #设置网络中边的标签内容及格式 69 nx.draw_networkx_edge_labels(G, pos, edgeLabelDict) 70 71 plt.show() 复制代码   以图形界面展示网络的结构: 6 总结   聪明的读者你肯定发现了,记录下特征转换行为的最好时机其实是转换的同时。可惜的是,sklearn目前并不支持这样的功能。在本文中,我将这一功能集中到流水线处理和并行处理的模块当中,只能算是一个临时的手段,但聊胜于无吧。另外,本文也是抛砖引玉,还有其他的转换类,在原特征与新特征之间的映射关系上,百家争鸣。所以,我在Github上新建了个库,包含本文实例中所有的转换类处理的代码,在之后,我会慢慢地填这个坑,直到世界的尽头,抑或sklearn加入该功能。 7 参考资料 ''' print(post2.text) db.session.add(post1) db.session.add(post2) db.session.commit() def delete_all_data(): db.drop_all() db.create_all() user1 = User("leiyi") db.session.add(user1) db.session.commit() post1 = Post("a") db.session.add(post1) db.session.commit() db.session.delete(user1) db.session.commit() db.session.delete(post1) db.session.commit() if __name__ == "__main__": delete_all_data() add_data()
Markdown
UTF-8
2,210
3.375
3
[]
no_license
# Codice Rest Esempio di "Hello World" REST Il codice seguente crea un servizio Web RESTful utilizzando il framework Node.js Express. Un singolo / ciao / endpoint risponde alle richieste GET. --- Assicurati di aver installato Node.js, quindi crea una nuova cartella chiamata restapi. Crea un nuovo file package.json all'interno di quella cartella con il seguente contenuto: ```javascript { "name": "restapi", "version": "1.0.0", "description": "REST test", "scripts": { "start": "node ./index.js" }, "dependencies": { "express": "4.17.1" } } ``` --- Esegui npm install dalla riga di comando per recuperare le dipendenze, quindi crea un file index.js con il seguente codice: ```javascript // simple Express.js RESTful API 'use strict'; // initialize const port = 8888, express = require('express'), app = express(); // /hello/ GET request app.get('/hello/:name?', (req, res) => res.json( { message: `Hello ${req.params.name || 'world'}!` } ) ); // start server app.listen(port, () => console.log(`Server started on port ${port}`); ); ``` --- Avvia l'applicazione dalla riga di comando utilizzando npm start e apri http://localhost:8888/hello/ in un browser. Il seguente JSON viene visualizzato in risposta alla richiesta GET: ```javascript { "message": "Hello world!" } ``` --- L'API consente anche un nome personalizzato, quindi http://localhost:8888/hello/everyone/ restituisce: ```javascript { "message": "Hello everyone!" } ``` ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>REST test</title> </head> <body> <script> fetch('http://localhost:8888/hello/') .then((response) => { return response.json(); }) .then((json) => { console.log(json); }); </script> </body> </html> ``` --- ## CORS ```javascript // /hello/ GET request app.get('/hello/:name?', (req, res) => res .append('Access-Control-Allow-Origin', '*') .json( { message: `Hello ${req.params.name || 'world'}!` } ) ); ``` --- ### Alternatively (Express.js) ```javascript // enable CORS app.use((req, res, next) => { res.append('Access-Control-Allow-Origin', '*'); next(); }); // /hello/ GET request // ... ```
Python
UTF-8
1,542
3.796875
4
[]
no_license
# Write a function to return the maximum number of fruits in both the baskets. Same as Longest substring with K chars but k=2 def fruits_into_baskets(fruits): start_ptr = 0 baskets = {} max_number_of_fruits = 0 current_number_of_fruits = 0 for end_ptr in range(len(fruits)): if fruits[end_ptr] not in baskets: if len(baskets) >= 2: current_number_of_fruits -= baskets[fruits[start_ptr]] del baskets[fruits[start_ptr]] while True: start_ptr += 1 if fruits[start_ptr-1] != fruits[start_ptr]: break baskets[fruits[end_ptr]] = 1 current_number_of_fruits += 1 max_number_of_fruits = max( max_number_of_fruits, current_number_of_fruits) else: baskets[fruits[end_ptr]] = 1 current_number_of_fruits += 1 max_number_of_fruits = max( max_number_of_fruits, current_number_of_fruits) else: baskets[fruits[end_ptr]] += 1 current_number_of_fruits += 1 max_number_of_fruits = max( current_number_of_fruits, max_number_of_fruits) return max_number_of_fruits def main(): print("Maximum number of fruits: " + str(fruits_into_baskets(['A', 'B', 'C', 'A', 'C']))) print("Maximum number of fruits: " + str(fruits_into_baskets(['A', 'B', 'C', 'B', 'B', 'C']))) main()
Python
UTF-8
3,699
2.890625
3
[ "Apache-2.0" ]
permissive
""" Generate the "Releases" table on the main readme. Update the versions lists, run this script, and copy the output into the markdown file. """ from distutils.version import LooseVersion from datetime import datetime from typing import NamedTuple def table_line(display_name, name, date, bold=False): bold_str = "**" if bold else "" # For release_X branches, docs are on a separate tag. if name.startswith("release"): docs_name = name + "_docs" else: docs_name = name return f"| **{display_name}** | {bold_str}{date}{bold_str} | {bold_str}[source](https://github.com/Unity-Technologies/ml-agents/tree/{name}){bold_str} | {bold_str}[docs](https://github.com/Unity-Technologies/ml-agents/tree/{docs_name}/docs/Readme.md){bold_str} | {bold_str}[download](https://github.com/Unity-Technologies/ml-agents/archive/{name}.zip){bold_str} |" # noqa class ReleaseInfo(NamedTuple): release_tag: str csharp_version: str python_verion: str release_date: str @staticmethod def from_simple_tag(release_tag: str, release_date: str) -> "ReleaseInfo": """ Generate the ReleaseInfo for "old style" releases, where the tag and versions were all the same. """ return ReleaseInfo(release_tag, release_tag, release_tag, release_date) @property def loose_version(self) -> LooseVersion: return LooseVersion(self.python_verion) @property def elapsed_days(self) -> int: """ Days since this version was released. :return: """ return ( datetime.today() - datetime.strptime(self.release_date, "%B %d, %Y") ).days @property def display_name(self) -> str: """ Clean up the tag name for display, e.g. "release_1" -> "Release 1" :return: """ return self.release_tag.replace("_", " ").title() versions = [ ReleaseInfo.from_simple_tag("0.10.0", "September 30, 2019"), ReleaseInfo.from_simple_tag("0.10.1", "October 9, 2019"), ReleaseInfo.from_simple_tag("0.11.0", "November 4, 2019"), ReleaseInfo.from_simple_tag("0.12.0", "December 2, 2019"), ReleaseInfo.from_simple_tag("0.12.1", "December 11, 2019"), ReleaseInfo.from_simple_tag("0.13.0", "January 8, 2020"), ReleaseInfo.from_simple_tag("0.13.1", "January 21, 2020"), ReleaseInfo.from_simple_tag("0.14.0", "February 13, 2020"), ReleaseInfo.from_simple_tag("0.14.1", "February 26, 2020"), ReleaseInfo.from_simple_tag("0.15.0", "March 18, 2020"), ReleaseInfo.from_simple_tag("0.15.1", "March 30, 2020"), ReleaseInfo("release_1", "1.0.0", "0.16.0", "April 30, 2020"), ReleaseInfo("release_2", "1.0.2", "0.16.1", "May 20, 2020"), ReleaseInfo("release_3", "1.1.0", "0.17.0", "June 10, 2020"), ReleaseInfo("release_4", "1.2.0", "0.18.0", "July 15, 2020"), ReleaseInfo("release_5", "1.2.1", "0.18.1", "July 31, 2020"), ReleaseInfo("release_6", "1.3.0", "0.19.0", "August 12, 2020"), ReleaseInfo("release_7", "1.4.0", "0.20.0", "September 16, 2020"), ] MAX_DAYS = 150 # do not print releases older than this many days sorted_versions = sorted(versions, key=lambda x: x.loose_version, reverse=True) print(table_line("master (unstable)", "master", "--")) highlight = True # whether to bold the line or not for version_info in sorted_versions: if version_info.elapsed_days <= MAX_DAYS: print( table_line( version_info.display_name, version_info.release_tag, version_info.release_date, highlight, ) ) highlight = False # only bold the first stable release
Java
UTF-8
1,294
2.453125
2
[]
no_license
package yummycherrypie.dal.default_records; import java.util.Date; import java.util.Random; import yummycherrypie.base_classes.BookingMan; import yummycherrypie.business_logic.Extensions.LogExtension; import yummycherrypie.dal.DBHelper; /** * Created by Nikolay_Piskarev on 12/1/2015. */ public class BookingMenDefaultRecords extends DataBaseDefaultRecords{ public BookingMenDefaultRecords(DBHelper dbh){ super(dbh); } /** * создание заказчиков по умолчанию */ public void createDefaultRecords(boolean isDebug){ dbr.deleteAll(DBHelper.TABLE_BOOKING_MEN); if(isDebug) { Random r = new Random(); String[] profiles = { "https://vk.com/evgeny_shevnin", "https://vk.com/faridada", "https://vk.com/milad", "https://vk.com/id262042732", "https://vk.com/id293061255" }; for (int i = 0; i < 25; i++) { BookingMan bm = new BookingMan("Заказчик №" + (i + 1), "891294863" + i, profiles[r.nextInt(profiles.length)]); bm.setCreateDate(new Date().getTime()); dbr.insert(DBHelper.TABLE_BOOKING_MEN, bm.getInsertedColumns()); LogExtension.Debug("Record created: " + bm.toString()); } } } }
Java
UTF-8
102
2.125
2
[]
no_license
package design.pattern.abstracted.factory.model; public interface Model { String getMessage(); }
C#
UTF-8
1,076
2.796875
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MH4U_Database.Database { public class Sharpness { public int Red { get; set; } public int Orange { get; set; } public int Yellow { get; set; } public int Green { get; set; } public int Blue { get; set; } public int White { get; set; } public int Purple { get; set; } public int Black { get { return 70 - (Red + Orange + Yellow + Green + Blue + White + Purple); } } public int Red1 { get; set; } public int Orange1 { get; set; } public int Yellow1 { get; set; } public int Green1 { get; set; } public int Blue1 { get; set; } public int White1 { get; set; } public int Purple1 { get; set; } public int Black1 { get { return 70 - (Red1 + Orange1 + Yellow1 + Green1 + Blue1 + White1 + Purple1); } } } }
C++
UTF-8
2,248
3.171875
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <queue> #include <cstring> using namespace std; int Answer; class Line{ public: short next[2002]; short end[2002]; Line(){ memset(next, -1, sizeof(short)*2002); memset(end, -1, sizeof(short)*2002); } }; int go(Line* lines, int here, int cursor, int k){ Line& l = *(lines+here); while(l.next[cursor] == -1 && cursor <= k){ cursor++; } if(cursor > k) return here; if(l.end[cursor] != -1) return l.end[cursor]; else{ int next = l.next[cursor]; int result = go(lines, next, cursor + 1, k); l.end[cursor] = result; return result; } } int dfs_go(Line* lines, int here, int goal, int cursor, int k, int count){ if(go(lines, here, cursor, k) == goal){ return count; } else{ int cnt1 = dfs_go(lines, here, goal, cursor+1, k, count+1); int cnt2 = 5000; Line& l = *(lines+here); while(l.next[cursor] == -1 && cursor <= k){ cursor++; } if(cursor < k) cnt2 = dfs_go(lines, l.next[cursor], goal, cursor+1, k, count); if(cnt1 < cnt2) return cnt1; return cnt2; } } int solve(){ int N, k, m; cin >> N >> k >> m; Line lines[N+1]; int x, y; for(int i = 0; i < k; i++){ cin >> x >> y; lines[x].next[i] = y; lines[y].next[i] = x; } for(int i = 0; i < N; i++){ // cout << "start at = " << i+1 << ", "; int res = go(lines, i+1, 0, k); // cout << "return result = " << res << endl; } int start, end; int result = 0; for(int i = 0; i < m; i++){ cin >> start >> end; int cnt = dfs_go(lines, start, end, 0, k, 0); if(cnt == 5000) result -= 1; else result += cnt; } return result; } int main(int argc, char** argv) { int T, test_case; cin >> T; for(test_case = 0; test_case < T; test_case++) { Answer = solve(); cout << "Case #" << test_case+1 << endl; cout << Answer << endl; } return 0;//Your program should return 0 on normal termination. }
Markdown
UTF-8
994
2.609375
3
[]
no_license
# js javascript 是一种具有头等函数的轻量级解释型或即时编译型的编程语言,是一种基于原型编程、多范式的动态脚本语言,并且支持面向对象、命令式和声明式(如函数式编程) > 一种编程语言被称为具有头等函数时,语言中的函数将会像任何其他变量一样被对待。例如, 在这样的语言中, 一个函数可以作为参数传递给其他函数,可以被当作返回值被另一个函数返回,可以当作值指定给一个变量 ## 基本数据类型 undefined,null,string,boolean,number 对undefined,null的理解涉及两者有啥不同,三等和双等返回的布尔值 对string的理解涉及string和其他类型诸如数组,json转化,正则 对number类型的理解涉及其包括哪些值,针对NaN不等于本身的考察,浮点运算的考察,双精度存储的考察 ## 原型继承 ## 闭包 ## 事件机制 ## 异步 ## es6 新增属性 ## es7 新增属性
Java
UTF-8
3,292
3.484375
3
[]
no_license
public class NQueens { private int[][] board; private int size; //Constructor public NQueens(int n) {//Constructor this.size = n; this.board = new int[n][n]; } public boolean isSafe(int row, int col){ if(board[row][col]==0){ //Checks the vertical and horizontal for (int i = 0; i < this.board.length; i++) { if(this.board[row][i] != 0 || this.board[i][col] != 0) return false; } //This checks the up-right diagonal for(int i=(row - 1), j=(col + 1); i>=0 && j<this.board[i].length; i--, j++){ if (this.board[i][j] != 0) return false; } //This checks the up-left diagonal for(int i=(row - 1), j=(col - 1); i>=0 && j>=0; i--, j--){ if (this.board[i][j] != 0) return false; } //This checks the down-right diagonal for(int i=(row + 1), j=(col + 1); i<this.board.length && j<this.board[i].length; i++, j++){ if (this.board[i][j] != 0) return false; } //This checks the down-left diagonal for(int i=(row + 1), j=(col - 1); i<this.board.length && j>=0; i++, j--){ if (this.board[i][j] != 0) return false; } return true; } return false; } public boolean FindingSolution(int row){ //This checks if the function passed through all the rows successfully if(row >= board.length) return true; //This for loop allows a Queen to be placed in every column in the row for(int col=0; col < board.length; col++){ //This checks if the queen is safe to be placed in that square if(isSafe(row, col)){ //This places the queen in that space board[row][col] = 1; /*This is the recursive function that checks and places queens in all the next safe squares in those rows. If all the rows are satisified, then it will have a solution.*/ if(FindingSolution(row+1) == true) return true; /*If all rows are not satisfied, then this next statement will go back to the original row and place the queen in the next available column.*/ board[row][col] = 0; } } return false; } public boolean placeNQueens() throws Exception{ try { if (this.size <= 0) throw new Exception("Invalid size"); else return (FindingSolution(0) == true); } catch(Exception e){ System.out.println(e); throw e; } } public void printToConsole() { for (int row = 0; row < this.board.length; row++) { for (int col = 0; col < this.board[row].length; col++) { if(this.board[row][col]==1) System.out.print("Q "); else System.out.print("_ "); System.out.println(); } System.out.println(); } } }
Python
UTF-8
772
3.21875
3
[]
no_license
dikt = dict() def add(n, v): if n in dikt : dikt[n].append(v) else: dikt[n]= [v] def create(n, p): for k,v in dikt.items(): if k == p: dikt[k].append(n) def get(n, p): for k, v in dikt.items(): if (n, p) == (k, [v]): if k == p: print(k) return k def find_path(dikt, start, end, path= []): path = path + [start] if start == end: return path if start not in dikt.keys(): return None for node in dikt[start]: if node not in path: newpath = find_path(dikt, node, end, path) if newpath: return newpath return None add('global', 'a') create('foo', 'global') add('foo', 'b') get('foo', 'a') get('foo', 'c') create('bar', 'foo') add('bar', 'a') get('bar', 'a') get('bar', 'b') print(find_path(dikt, 'a', 'bar')) print(dikt)
JavaScript
UTF-8
2,995
2.984375
3
[]
no_license
import React from 'react'; import Person from './components/Person'; import HeartRate from './components/HeartRate'; import Water from './components/Water'; import Slider from './components/core/Slider'; import Icon from './components/core/Icon'; import Temperature from './components/Temperature'; import '../src/css/bootstrap.min.css'; import '../src/css/styles.css'; const MIN_TEMPERATURE = -20; const MAX_TEMPERATURE = 40; const MIN_HEART = 80; const MAX_HEART = 180; const MIN_STEPS = 0; const MAX_STEPS = 50000; class App extends React.Component { constructor() { super() this.state = { water: 1.5, heart: 120, temperature: -10, steps: 3000 } this.onHeartChange = this.onHeartChange.bind(this) this.onStepsChange = this.onStepsChange.bind(this) this.onTemperatureChange = this.onTemperatureChange.bind(this) this.calculateWater = this.calculateWater.bind(this) } onHeartChange(val) { let newWater = this.calculateWater(this.state); this.setState({ heart: val, water: newWater }) } onStepsChange(val) { let newWater = this.calculateWater(this.state); this.setState({ steps: val, water: newWater }) } onTemperatureChange(val) { let newWater = this.calculateWater(this.state); this.setState({ temperature: val, water: newWater }) } calculateWater(obj) { //obj.steps //obj.heart //obj.temperature //on initialise le nb de litre au début: let liters = 1.5 let newWater = this.state.water if (obj.temperature > 20) { let upTemp = obj.temperature - 20 // on ajoute a 'liters' le nb de l en + en fonction de la temp. au dessus de 20°C: liters += upTemp * 0.02 } else if (obj.heart > 120) { let upHeart = obj.heart - 120 liters += upHeart * 0.0008 //newWater = this.state.water + (0.0008 * (this.state.heart - 120)) } else if (obj.steps > 10000) { let upSteps = obj.steps - 10000 liters += upSteps * 0.00002 //newWater = this.state.water + (0.00002 * (this.state.steps - 10000)) } console.log(liters) // au lieu de "return liters", on ajoute Math.round pour arrondir le nb return Math.round(liters * 100) /100 } render() { return ( <div className="container-fluid"> <Water water={this.state.water}> </Water> <Person steps={this.state.steps} min={MIN_STEPS} max={MAX_STEPS} onChange={this.onStepsChange}> </Person> <HeartRate heart={this.state.heart} min={MIN_HEART} max={MAX_HEART} onChange={this.onHeartChange}> </HeartRate> <Temperature temperature={this.state.temperature} min={MIN_TEMPERATURE} max={MAX_TEMPERATURE} onChange={this.onTemperatureChange}> </Temperature> </div> ); } } export default App;
Java
UTF-8
7,979
1.820313
2
[]
no_license
package com.qcloud.component.goods.web.controller.admin; import com.qcloud.component.goods.model.AttributeDefinition; import com.qcloud.component.goods.model.ClassifySpecifications; import com.qcloud.component.goods.model.key.TypeEnum; import com.qcloud.component.goods.service.AttributeDefinitionService; import com.qcloud.component.goods.service.ClassifySpecificationsService; import com.qcloud.component.goods.web.handler.AttributeDefinitionHandler; import com.qcloud.component.goods.web.handler.ClassifySpecificationsHandler; import com.qcloud.component.goods.web.vo.admin.AdminAttributeDefinitionVO; import com.qcloud.component.goods.web.vo.admin.AdminClassifySpecificationsVO; import com.qcloud.component.publicdata.PublicdataClient; import com.qcloud.component.publicdata.model.Classify; import com.qcloud.pirates.mvc.AceAjaxView; import com.qcloud.pirates.util.AssertUtil; import com.qcloud.pirates.web.security.annotation.NoReferer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import java.util.HashMap; import java.util.List; @Controller @RequestMapping(value = "/" + AdminClassifySpecificationsController.DIR) public class AdminClassifySpecificationsController { public static final String DIR = "admin/classifySpecifications"; @Autowired private ClassifySpecificationsService classifySpecificationsService; @Autowired private ClassifySpecificationsHandler classifySpecificationsHandler; @Autowired private PublicdataClient publicdataClient; @Autowired private AttributeDefinitionService attributeDefinitionService; @Autowired private AttributeDefinitionHandler attributeDefinitionHandler; @RequestMapping @NoReferer public ModelAndView list(Long classifyId) { AssertUtil.assertTrue(classifyId > 0, "分类ID错误"); HashMap where = new HashMap(); where.put("classifyId", classifyId); List<ClassifySpecifications> list = classifySpecificationsService.list(where); List<AdminClassifySpecificationsVO> voList = classifySpecificationsHandler.toDetailVOList4Admin(list); ModelAndView model = new ModelAndView("/admin/goods-ClassifySpecifications-list"); model.addObject("result", voList); model.addObject("classifyId", classifyId); return model; } @RequestMapping public ModelAndView toAdd(Long classifyId) { AssertUtil.assertTrue(classifyId > 0, "分类ID错误"); Classify classify = publicdataClient.getClassify(classifyId); AssertUtil.assertNotNull(classify, "分类不存在"); ModelAndView model = new ModelAndView("/admin/goods-ClassifySpecifications-add"); model.addObject("classify", classify); return model; } @RequestMapping public AceAjaxView add(ClassifySpecifications classifySpecifications) { AssertUtil.assertNotNull(classifySpecifications.getAttributeId(), "请选择属性"); classifySpecificationsService.add(classifySpecifications); AceAjaxView aceAjaxView = new AceAjaxView(); aceAjaxView.setMessage("添加成功"); // aceAjaxView.setUrl(DIR + "/list"); return aceAjaxView; } @RequestMapping public ModelAndView toEdit(Long id) { AssertUtil.assertNotNull(id, "ID不能为空"); ClassifySpecifications classifySpecifications = classifySpecificationsService.get(id); AdminClassifySpecificationsVO vo = classifySpecificationsHandler.toVO4Admin(classifySpecifications); Classify classify = publicdataClient.getClassify(classifySpecifications.getClassifyId()); AssertUtil.assertNotNull(classify, "分类不存在"); ModelAndView model = new ModelAndView("/admin/goods-ClassifySpecifications-edit"); model.addObject("classifySpecifications", vo); model.addObject("classify", classify); return model; } @RequestMapping public AceAjaxView edit(ClassifySpecifications classifySpecifications) { classifySpecificationsService.update(classifySpecifications); AceAjaxView aceAjaxView = new AceAjaxView(); aceAjaxView.setMessage("编辑成功"); // aceAjaxView.setUrl(DIR + "/list"); return aceAjaxView; } @RequestMapping public AceAjaxView delete(Long id) { AssertUtil.assertNotNull(id, "ID不能为空"); classifySpecificationsService.delete(id); AceAjaxView aceAjaxView = new AceAjaxView(); aceAjaxView.setMessage("删除成功"); aceAjaxView.setUrl(DIR + "/list"); return aceAjaxView; } // 10-13 类目列表整合属性/规格添加 /*****************************************************************************************/ @RequestMapping public ModelAndView toAddClassifySpec(Long classifyId) { ModelAndView model = new ModelAndView("/admin/goods-ClassifySpecifications-addSpec"); model.addObject("classifyId", classifyId); return model; } @RequestMapping public ModelAndView addClassifySpec(AttributeDefinition attributeDefinition, ClassifySpecifications specifications) { AssertUtil.assertNotNull(specifications.getClassifyId(), "分类id不能为空"); Classify classify = publicdataClient.getClassify(specifications.getClassifyId()); AssertUtil.assertNotNull(classify, "分类不存在"); attributeDefinition.setType(String.valueOf(TypeEnum.AttrType.spec.getKey())); attributeDefinition.setValueType("-1"); attributeDefinition.setValue(attributeDefinition.getValue().replace("×", ",")); Long attrId = attributeDefinitionService.add(attributeDefinition); specifications.setAttributeId(attrId); classifySpecificationsService.add(specifications); AceAjaxView model = new AceAjaxView(); model.setMessage("添加成功"); return model; } @RequestMapping public ModelAndView toEditClassifySpec(Long id) { AssertUtil.assertNotNull(id, "id不能为空"); ClassifySpecifications specifications = classifySpecificationsService.get(id); AssertUtil.assertNotNull(specifications, "分类规格不存在"); AttributeDefinition attributeDefinition = attributeDefinitionService.get(specifications.getAttributeId()); AdminAttributeDefinitionVO vo = attributeDefinitionHandler.toVO4Admin(attributeDefinition); ModelAndView model = new ModelAndView("/admin/goods-ClassifySpecifications-editSpec"); model.addObject("result", vo); model.addObject("specifications", specifications); return model; } @RequestMapping public ModelAndView editClassifySpec(AttributeDefinition attributeDefinition, Long classifyId, Long specificationId, int sort, int uploadImage) { AssertUtil.assertNotNull(specificationId, "id不能为空"); ClassifySpecifications specifications = classifySpecificationsService.get(specificationId); AssertUtil.assertNotNull(specifications, "分类规格不存在"); attributeDefinition.setType(String.valueOf(TypeEnum.AttrType.spec.getKey())); attributeDefinition.setValueType("-1"); attributeDefinition.setValue(attributeDefinition.getValue().replace("×", ",")); attributeDefinitionService.update(attributeDefinition); specifications.setSort(sort); specifications.setUploadImage(uploadImage); classifySpecificationsService.update(specifications); AceAjaxView model = new AceAjaxView(); model.setMessage("修改成功"); return model; } }
Shell
UTF-8
549
3.375
3
[ "MIT" ]
permissive
#!/bin/sh -e start() { docker run --name="shiny" -p 80:3838 -d \ -v /home/shiny-server/shinyapps/:/srv/shiny-server/ \ -v /home/shiny-server/log/:/var/log/ \ -v /home/shiny-server/templates/:/etc/shiny-server/templates/ \ oncogenetics-shiny:latest } stop() { docker stop shiny docker rm shiny } case "$1" in start) start ;; restart) stop start ;; stop) stop ;; *) echo "usage: $0 start|restart|stop" exit 1 esac
Java
UTF-8
1,306
2.28125
2
[]
no_license
package modelo; import java.util.ArrayList; import modelo.Abono; import modelo.Actividad; import modelo.InscripcionCorporativa; import modelo.PagoMensual; import modelo.Socio; public abstract class Inscripcion { private String fecha; private Socio socio; private ArrayList<Actividad> actividades; private Abono abono; private ArrayList<PagoMensual> pagos; private InscripcionCorporativa inscripCorp; public void Inscripcion(){ this.fecha = "01.01.2000"; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } public Socio getSocio() { return socio; } public void setSocio(Socio socio) { this.socio = socio; } public ArrayList<Actividad> getActividades() { return actividades; } public void setActividades(ArrayList<Actividad> actividades) { this.actividades = actividades; } public Abono getAbono() { return abono; } public void setAbono(Abono abono) { this.abono = abono; } public ArrayList<PagoMensual> getPagos() { return pagos; } public void setPagos(ArrayList<PagoMensual> pagos) { this.pagos = pagos; } public InscripcionCorporativa getInscripCorp() { return inscripCorp; } public void setInscripCorp(InscripcionCorporativa inscripCorp) { this.inscripCorp = inscripCorp; } }
Java
UTF-8
3,270
2.921875
3
[]
no_license
package com.camels.simulator; import org.jgrapht.Graph; import org.jgrapht.Graphs; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.SimpleGraph; import java.util.ArrayList; import java.util.Set; public class Map { private int aisles = 0; private int sections = 0; private int shelves = 0; Graph<String, DefaultEdge> map = new SimpleGraph<>(DefaultEdge.class); ArrayList<Vertex> vertices = new ArrayList<Vertex>(); ArrayList<Vertex> packingAreas = new ArrayList<Vertex>(); public void setMap(int aisles, int sections, int shelves, ArrayList packingAreas){ this.aisles = aisles; this.sections = sections; this.shelves = shelves; createMap(); for(int i=0;i<packingAreas.size();i++){ String pa = packingAreas.get(i).toString(); for(int v=0;v<vertices.size();v++){ if(vertices.get(v).getName().equals(pa)){ Vertex tempVertex = vertices.get(v); tempVertex.setAvailability(Boolean.FALSE, 0); this.packingAreas.add(tempVertex); } } } System.out.println("check packing areas: "+this.packingAreas); } public void createMap(){ for(int a=1; a<=aisles; a++){ int s; for(s=0; s<=sections+1; s++){ Vertex v = new Vertex("a"+a+"."+s, shelves); map.addVertex(v.getName()); vertices.add(v); if(s==0){v.setAvailability(Boolean.FALSE, 0);} if(s>0){ map.addEdge("a"+a+"."+(s-1), "a"+a+"."+s); } } if(a>1){ map.addEdge("a"+(a-1)+".0", "a"+a+".0"); map.addEdge("a"+(a-1)+"."+(s-1), "a"+a+"."+(s-1)); } } System.out.println("Map Created: "+map); //System.out.println("Vertices List: "+vertices.toString()); } public String getMap(){ return map.toString(); } public Set<String> getVertices(){ //System.out.println("Getting vertices: "+map.vertexSet()); return map.vertexSet(); } public ArrayList getVertexItems(String vertex){ for(int i=0; i<vertices.size();i++){ Vertex temp = vertices.get(i); if(temp.getName().equals(vertex)){ return temp.getVertexItems(); } } return null; } public Set<DefaultEdge> getEdges(){ //System.out.println("Getting Edges: "+map.edgeSet()); return map.edgeSet(); } public ArrayList<String> getOpposites(String vertexId) { return (ArrayList<String>) Graphs.neighborListOf(map, vertexId); } public int getAisles() { return aisles; } public int getSections() { return sections; } public int getShelves() { return shelves; } public ArrayList<String> getPackingAreasArray() { ArrayList packingAreasArray = new ArrayList(); for(Vertex pa: packingAreas){ packingAreasArray.add(pa.getName()); } return packingAreasArray; } public ArrayList<Vertex> getVerticesArray() { return vertices; } }
Java
UTF-8
13,404
1.773438
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2014 The Android Open Source Project * * 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 androidx.leanback.widget; import android.content.Context; import android.graphics.drawable.ClipDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.MarginLayoutParams; import android.widget.FrameLayout; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.ColorInt; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.leanback.R; import androidx.leanback.util.MathUtil; /** * A presenter for a control bar that supports "more actions", * and toggling the set of controls between primary and secondary * sets of {@link Actions}. */ class PlaybackControlsPresenter extends ControlBarPresenter { /** * The data type expected by this presenter. */ static class BoundData extends ControlBarPresenter.BoundData { /** * The adapter containing secondary actions. */ ObjectAdapter secondaryActionsAdapter; } class ViewHolder extends ControlBarPresenter.ViewHolder { ObjectAdapter mMoreActionsAdapter; ObjectAdapter.DataObserver mMoreActionsObserver; final FrameLayout mMoreActionsDock; Presenter.ViewHolder mMoreActionsViewHolder; boolean mMoreActionsShowing; final TextView mCurrentTime; final TextView mTotalTime; final ProgressBar mProgressBar; long mCurrentTimeInMs = -1; // Hold current time in milliseconds long mTotalTimeInMs = -1; // Hold total time in milliseconds long mSecondaryProgressInMs = -1; // Hold secondary progress in milliseconds StringBuilder mTotalTimeStringBuilder = new StringBuilder(); StringBuilder mCurrentTimeStringBuilder = new StringBuilder(); int mCurrentTimeMarginStart; int mTotalTimeMarginEnd; ViewHolder(View rootView) { super(rootView); mMoreActionsDock = (FrameLayout) rootView.findViewById(R.id.more_actions_dock); mCurrentTime = (TextView) rootView.findViewById(R.id.current_time); mTotalTime = (TextView) rootView.findViewById(R.id.total_time); mProgressBar = (ProgressBar) rootView.findViewById(R.id.playback_progress); mMoreActionsObserver = new ObjectAdapter.DataObserver() { @Override public void onChanged() { if (mMoreActionsShowing) { showControls(mPresenter); } } @Override public void onItemRangeChanged(int positionStart, int itemCount) { if (mMoreActionsShowing) { for (int i = 0; i < itemCount; i++) { bindControlToAction(positionStart + i, mPresenter); } } } }; mCurrentTimeMarginStart = ((MarginLayoutParams) mCurrentTime.getLayoutParams()).getMarginStart(); mTotalTimeMarginEnd = ((MarginLayoutParams) mTotalTime.getLayoutParams()).getMarginEnd(); } void showMoreActions(boolean show) { if (show) { if (mMoreActionsViewHolder == null) { Action action = new PlaybackControlsRow.MoreActions(mMoreActionsDock.getContext()); mMoreActionsViewHolder = mPresenter.onCreateViewHolder(mMoreActionsDock); mPresenter.onBindViewHolder(mMoreActionsViewHolder, action); mPresenter.setOnClickListener(mMoreActionsViewHolder, new View.OnClickListener() { @Override public void onClick(View v) { toggleMoreActions(); } }); } if (mMoreActionsViewHolder.view.getParent() == null) { mMoreActionsDock.addView(mMoreActionsViewHolder.view); } } else if (mMoreActionsViewHolder != null && mMoreActionsViewHolder.view.getParent() != null) { mMoreActionsDock.removeView(mMoreActionsViewHolder.view); } } void toggleMoreActions() { mMoreActionsShowing = !mMoreActionsShowing; showControls(mPresenter); } @Override ObjectAdapter getDisplayedAdapter() { return mMoreActionsShowing ? mMoreActionsAdapter : mAdapter; } @Override int getChildMarginFromCenter(Context context, int numControls) { int margin = getControlIconWidth(context); if (numControls < 4) { margin += getChildMarginBiggest(context); } else if (numControls < 6) { margin += getChildMarginBigger(context); } else { margin += getChildMarginDefault(context); } return margin; } void setTotalTime(long totalTimeMs) { if (totalTimeMs <= 0) { mTotalTime.setVisibility(View.GONE); mProgressBar.setVisibility(View.GONE); } else { mTotalTime.setVisibility(View.VISIBLE); mProgressBar.setVisibility(View.VISIBLE); mTotalTimeInMs = totalTimeMs; formatTime(totalTimeMs / 1000, mTotalTimeStringBuilder); mTotalTime.setText(mTotalTimeStringBuilder.toString()); mProgressBar.setMax(Integer.MAX_VALUE);//current progress will be a fraction of this } } long getTotalTime() { return mTotalTimeInMs; } void setCurrentTime(long currentTimeMs) { long seconds = currentTimeMs / 1000; if (currentTimeMs != mCurrentTimeInMs) { mCurrentTimeInMs = currentTimeMs; formatTime(seconds, mCurrentTimeStringBuilder); mCurrentTime.setText(mCurrentTimeStringBuilder.toString()); } // Use ratio to represent current progres double ratio = (double) mCurrentTimeInMs / mTotalTimeInMs; // Range: [0, 1] double progressRatio = ratio * Integer.MAX_VALUE; // Could safely cast to int mProgressBar.setProgress((int)progressRatio); } long getCurrentTime() { return mTotalTimeInMs; } void setSecondaryProgress(long progressMs) { mSecondaryProgressInMs = progressMs; // Solve the progress bar by using ratio double ratio = (double) progressMs / mTotalTimeInMs; // Range: [0, 1] double progressRatio = ratio * Integer.MAX_VALUE; // Could safely cast to int mProgressBar.setSecondaryProgress((int) progressRatio); } long getSecondaryProgress() { return mSecondaryProgressInMs; } } static void formatTime(long seconds, StringBuilder sb) { long minutes = seconds / 60; long hours = minutes / 60; seconds -= minutes * 60; minutes -= hours * 60; sb.setLength(0); if (hours > 0) { sb.append(hours).append(':'); if (minutes < 10) { sb.append('0'); } } sb.append(minutes).append(':'); if (seconds < 10) { sb.append('0'); } sb.append(seconds); } private boolean mMoreActionsEnabled = true; private static int sChildMarginBigger; private static int sChildMarginBiggest; /** * Constructor for a PlaybackControlsRowPresenter. * * @param layoutResourceId The resource id of the layout for this presenter. */ public PlaybackControlsPresenter(int layoutResourceId) { super(layoutResourceId); } /** * Enables the display of secondary actions. * A "more actions" button will be displayed. When "more actions" is selected, * the primary actions are replaced with the secondary actions. */ public void enableSecondaryActions(boolean enable) { mMoreActionsEnabled = enable; } /** * Returns true if secondary actions are enabled. */ public boolean areMoreActionsEnabled() { return mMoreActionsEnabled; } public void setProgressColor(ViewHolder vh, @ColorInt int color) { Drawable drawable = new ClipDrawable(new ColorDrawable(color), Gravity.LEFT, ClipDrawable.HORIZONTAL); ((LayerDrawable) vh.mProgressBar.getProgressDrawable()) .setDrawableByLayerId(android.R.id.progress, drawable); } public void setTotalTime(ViewHolder vh, int ms) { setTotalTimeLong(vh, (long) ms); } public void setTotalTimeLong(ViewHolder vh, long ms) { vh.setTotalTime(ms); } public int getTotalTime(ViewHolder vh) { return MathUtil.safeLongToInt(getTotalTimeLong(vh)); } public long getTotalTimeLong(ViewHolder vh) { return vh.getTotalTime(); } public void setCurrentTime(ViewHolder vh, int ms) { setCurrentTimeLong(vh, (long) ms); } public void setCurrentTimeLong(ViewHolder vh, long ms) { vh.setCurrentTime(ms); } public int getCurrentTime(ViewHolder vh) { return MathUtil.safeLongToInt(getCurrentTimeLong(vh)); } public long getCurrentTimeLong(ViewHolder vh) { return vh.getCurrentTime(); } public void setSecondaryProgress(ViewHolder vh, int progressMs) { setSecondaryProgressLong(vh, (long) progressMs); } public void setSecondaryProgressLong(ViewHolder vh, long progressMs) { vh.setSecondaryProgress(progressMs); } public int getSecondaryProgress(ViewHolder vh) { return MathUtil.safeLongToInt(getSecondaryProgressLong(vh)); } public long getSecondaryProgressLong(ViewHolder vh) { return vh.getSecondaryProgress(); } public void showPrimaryActions(ViewHolder vh) { if (vh.mMoreActionsShowing) { vh.toggleMoreActions(); } } public void resetFocus(ViewHolder vh) { vh.mControlBar.requestFocus(); } public void enableTimeMargins(ViewHolder vh, boolean enable) { MarginLayoutParams lp; lp = (MarginLayoutParams) vh.mCurrentTime.getLayoutParams(); lp.setMarginStart(enable ? vh.mCurrentTimeMarginStart : 0); vh.mCurrentTime.setLayoutParams(lp); lp = (MarginLayoutParams) vh.mTotalTime.getLayoutParams(); lp.setMarginEnd(enable ? vh.mTotalTimeMarginEnd : 0); vh.mTotalTime.setLayoutParams(lp); } @NonNull @Override public Presenter.ViewHolder onCreateViewHolder(ViewGroup parent) { View v = LayoutInflater.from(parent.getContext()) .inflate(getLayoutResourceId(), parent, false); return new ViewHolder(v); } @Override public void onBindViewHolder(@NonNull Presenter.ViewHolder holder, @Nullable Object item) { ViewHolder vh = (ViewHolder) holder; BoundData data = (BoundData) item; // If binding to a new adapter, display primary actions. if (vh.mMoreActionsAdapter != data.secondaryActionsAdapter) { vh.mMoreActionsAdapter = data.secondaryActionsAdapter; vh.mMoreActionsAdapter.registerObserver(vh.mMoreActionsObserver); vh.mMoreActionsShowing = false; } super.onBindViewHolder(holder, item); vh.showMoreActions(mMoreActionsEnabled); } @Override public void onUnbindViewHolder(@NonNull Presenter.ViewHolder holder) { super.onUnbindViewHolder(holder); ViewHolder vh = (ViewHolder) holder; if (vh.mMoreActionsAdapter != null) { vh.mMoreActionsAdapter.unregisterObserver(vh.mMoreActionsObserver); vh.mMoreActionsAdapter = null; } } int getChildMarginBigger(Context context) { if (sChildMarginBigger == 0) { sChildMarginBigger = context.getResources().getDimensionPixelSize( R.dimen.lb_playback_controls_child_margin_bigger); } return sChildMarginBigger; } int getChildMarginBiggest(Context context) { if (sChildMarginBiggest == 0) { sChildMarginBiggest = context.getResources().getDimensionPixelSize( R.dimen.lb_playback_controls_child_margin_biggest); } return sChildMarginBiggest; } }
Markdown
UTF-8
952
2.828125
3
[]
permissive
# My Personal Portfolio Website 🚀 My name is Parth Bhagvanbhai Shingala, and I have a passion for designing and developing applications that have a meaningful impact on people's lives. I am a Full-Stack developer with expertise in building and architecting exceptional digital experiences. My approach is characterized by a strong work ethic and a hands-on mindset, as demonstrated through my extensive experience. My objective is to secure a developer role within an organization that resonates with my values and passions. I am currently pursuing my Master's of Science in Computer Science and Engineering at The State University of New York (SUNY) at Buffalo, USA. For the past two years, I have been employed at Morgan Stanley Capital International (MSCI) as a Software Developer. During this time, I have been an integral part of the Equity Index Calculation Team, contributing to the development of index computing applications utilizing the Spring framework. .
Java
UTF-8
2,107
2.4375
2
[]
no_license
package com.epam.training.ticketservice.repository.impl; import com.epam.training.ticketservice.dataaccess.dao.ScreeningDao; import com.epam.training.ticketservice.dataaccess.projection.ScreeningProjection; import com.epam.training.ticketservice.domain.interfaces.Screening; import com.epam.training.ticketservice.domain.interfaces.impl.SimpleScreening; import com.epam.training.ticketservice.repository.ScreeningRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.stream.Collectors; @Repository public class JpaScreeningRepository implements ScreeningRepository { private ScreeningDao screeningDao; public JpaScreeningRepository(ScreeningDao screeningDao) { this.screeningDao = screeningDao; } @Override public void saveScreening(Screening screening) { screeningDao.save(mapScreening(screening)); } @Override public void removeScreening(Screening screeningToDelete) { screeningDao.deleteByTitleAndRoomNameAndStartTime( screeningToDelete.getTitle(), screeningToDelete.getRoomName(), screeningToDelete.getStartTime() ); } @Override public List<Screening> getAllScreening() { List<ScreeningProjection> screeningProjections = screeningDao.findAll(); return mapScreeningProjections(screeningProjections); } private ScreeningProjection mapScreening(Screening screening) { return new ScreeningProjection(screening.getTitle(), screening.getRoomName(), screening.getStartTime()); } private List<Screening> mapScreeningProjections( List<ScreeningProjection> screeningProjections) { return screeningProjections.stream() .map(this::mapScreeningProjection) .collect(Collectors.toList()); } private Screening mapScreeningProjection(ScreeningProjection screeningProjection) { return new SimpleScreening(screeningProjection.getTitle(), screeningProjection.getRoomName(), screeningProjection.getStartTime()); } }
Java
UTF-8
1,063
2.40625
2
[]
no_license
package com.baobaotao.proxy; import java.lang.reflect.Proxy; /** * Created with IntelliJ IDEA. * User: vuclip123 * Date: 1/22/14 * Time: 10:26 PM * To change this template use File | Settings | File Templates. */ public class TestForumService { public static void main(String[] args) { /*ForumService forumService = new ForumServiceImpl(); forumService.removeForum(10); forumService.removeTopic(1012);*/ /*ForumService target = new ForumServiceImpl(); PerformanceHandler handler = new PerformanceHandler(target); ForumService proxy = (ForumService)Proxy.newProxyInstance( target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler); proxy.removeForum(10); proxy.removeTopic(1012);*/ CglibProxy proxy = new CglibProxy(); ForumServiceImpl forumService = (ForumServiceImpl) proxy.getProxy(ForumServiceImpl.class); forumService.removeForum(10); forumService.removeTopic(1012); } }
PHP
UTF-8
11,074
2.515625
3
[ "PHP-3.0", "Apache-2.0" ]
permissive
<?php namespace app\index\controller; use app\admin\model\Classz; use app\admin\model\Examdata; use app\admin\model\Paper; use app\admin\model\Question; use think\Controller; use think\Request; class Exam extends Controller { /** * 显示资源列表 * * @return \think\Response */ public function index() { // // 获取个人信息 $user = session('user') ; $id = session('user')['id'] ; if (!$user){ $this->error('请先登录', url('/login'), '', '1') ; } // 当前时间日期字符串 $date_str = date('Y-m-d', time()) ; $class_id = $user['class_id'] ; //查找试卷 $pagesize = \think\facade\Config::get('pagesize'); // $paper = Paper::where('start_date', $date_str)->paginate($pagesize) ; // $paper = Paper::where('start_date', $date_str)->where('class_id','like' , '%' . $class_id . '%')->select(); $paper = Paper::where('class_id','like' , '%' . $class_id . '%')->where('status',1)->order('start_time_stamp', 'desc')->select(); $my_exam = [] ; // foreach ($paper as $k=>$v){ // $class_id_arr = explode(',' , $v['class_id']) ; // // if (in_array($class_id, $class_id_arr)) { // // 到时后再通过考试记录表过滤已经考过的试卷 // $my_exam[] = $v; // } // } // // dump($paper) ; // // exit() ; $now_timestamp = time() ; foreach ($paper as $k=>$v){ $edata = Examdata::where('paper_id', $v['id'])->where('user_id',$id)->find() ; if ($v['start_time_stamp'] < $now_timestamp){ // 超过考试时间的考试试卷 $v['timeout'] = 1 ; }else{ $v['timeout'] = 0 ; } if ($edata['status'] != 1){ $my_exam[] = $v ; } } return view('exam',[ 'id' => $id, 'exams' => $my_exam ]) ; } /** * * @return \think\response\View * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\ModelNotFoundException * @throws \think\exception\DbException */ public function history(){ $user = session('user') ; $id = session('user')['id'] ; if (!$user){ $this->error('请先登录', url('/login'), '', '1') ; } // 当前时间日期字符串 $date_str = date('Y-m-d', time()) ; $class_id = $user['class_id'] ; $paper = Paper::where('class_id','like' , '%' . $class_id . '%')->select(); $my_exam = [] ; foreach ($paper as $k=>$v){ $edata = Examdata::where('paper_id', $v['id'])->where('user_id',$id)->find() ; if ($edata['status'] == 1){ $my_exam[] = $v ; } } // 获取试卷考试成绩 foreach ($my_exam as $v){ $exam_info = Examdata::where('paper_id', $v['id'])->where('user_id', $id)->find() ; $v['score'] = $exam_info['score'] ; } return view('history',[ 'id' => $id, 'exams' => $my_exam ]) ; } /** * 开始答题 * @param $id * @return \think\response\View|void * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\ModelNotFoundException * @throws \think\exception\DbException */ public function doExam($id){ $user = session('user') ; $user_id = session('user')['id'] ; // 读取试卷信息 $paper = Paper::where('id', $id)->find() ; if (!$paper){ return ; } // 查看考试时间 if ($paper['end_time_stamp'] < time()){ return $this->error('考试时间已经结束!', url('/exam'), '', '10' ) ; } // 重复考试验证 $exam = new Examdata() ; $einfo = $exam->where('paper_id', $paper['id'])->where('user_id', $user_id)->find() ; if ($einfo['status'] == 1){ return $this->error('你已经完成这次考试了!', url('/exam'), '', '10' ) ; } $paper_data = json_decode( $paper['data'], true) ; if (isset($paper_data['sessions'])){ // 把题目json data转成数组 foreach ($paper_data['sessions'] as $k=>$session){ foreach ($session['questions'] as $j=>$qsn){ $paper_data['sessions'][$k]['questions'][$j]['data'] = json_decode( $paper_data['sessions'][$k]['questions'][$j]['data'] , true); } } } // dump($paper_data) ; // exit() ; // 查询使用班级 $class_id = $paper['class_id'] ; $classes = Classz::where('id', 'in' , explode(',' , $class_id))->select() ; $classes_str = "" ; foreach ($classes as $clz){ $classes_str .= $clz['name'] . ',' ; } $classes_str = rtrim($classes_str, ',') ; if (!$user){ $this->error('请先登录', url('/login'), '', '1') ; } return view('doExam',[ 'id' => $user_id, 'paper' => $paper, 'paper_data' => $paper_data, 'classes' => $classes_str, 'user' => $user ]) ; } public function detail($id){ $user = session('user') ; $user_id = session('user')['id'] ; // 读取试卷信息 $paper = Paper::where('id', $id)->find() ; if (!$paper){ return ; } // 查询使用班级 $class_id = $paper['class_id'] ; $classes = Classz::where('id', 'in' , explode(',' , $class_id))->select() ; $classes_str = "" ; foreach ($classes as $clz){ $classes_str .= $clz['name'] . ',' ; } $classes_str = rtrim($classes_str, ',') ; // 考试信息 $exam_info = Examdata::where('paper_id', $id)->where('user_id', $user_id)->find() ; $exam_data_array = json_decode($exam_info['data'] , true) ; // dump($exam_data_array) ; // exit() ; // 有些填空题是多个填空项的 需要把数组转成字符串输出到html foreach ($exam_data_array as $k=>$v){ if (is_array($v)){ if (is_array($v['ukey'])){ $exam_data_array[$k]['ukey'] = implode(',' , $v['ukey']) ; } } } // dump($exam_data_array) ; // exit() ; $paper_data = json_decode( $paper['data'], true) ; if (isset($paper_data['sessions'])){ // 把题目json data转成数组 foreach ($paper_data['sessions'] as $k=>$session){ foreach ($session['questions'] as $j=>$qsn){ $paper_data['sessions'][$k]['questions'][$j]['data'] = json_decode( $paper_data['sessions'][$k]['questions'][$j]['data'] , true); } } } // dump($paper_data) ; // exit() ; // return view('detail',[ 'id' => $user_id, 'paper' => $paper, 'classes' => $classes_str, 'examInfo' => $exam_info, 'user' => $user, 'paper_data' => $paper_data, 'exam_data' => $exam_data_array ]) ; } /** * 交卷 */ public function submit(){ $input = input() ; // dump($input) ; // exit() ; $input_data = $input ; // 这个保存原来状态数据 不改变 // 假装过滤数据了 // 填空题 答案转字符串 foreach ($input as $k=>$v){ if (is_array($v)){ if (is_array($v['ukey'])){ $input[$k]['ukey'] = implode(',', $input[$k]['ukey']); } } } $user_id = session('user')['id'] ; $exam_id = uniqid() ; $data['id'] = $exam_id ; $data['user_id'] = $user_id ; $data['paper_id'] = $input['id'] ; unset($input['id']) ; $data['data'] = json_encode($input_data,true) ; $data['status'] = 1 ; // 批改试卷 unset($input_data['id']) ; $total_score = 0 ; $exam = new Examdata() ; $einfo = $exam->where('paper_id', $data['paper_id'])->where('user_id', $user_id)->find() ; if ($einfo['status'] == 1){ return $this->error('试卷已经提交过不能再次提交', url('/exam'), '', '10' ) ; } if($exam->allowField(true)->save($data) ){ foreach ($input_data as $k=>$v){ $q = Question::where('id', $k)->find() ; // array('key'=>value) if ($q['type'] != 5 && $q['type'] != 4){ // 简答题手动批改 // echo $v['ukey'] . '===' . $q['key'] ; if ($v['ukey'] == $q['key']){ // 答题正确 $total_score += intval($v['score']) ; // echo $total_score .'<br>' ; } } if ($q['type'] == 4){ // 填空题批改 $ukey = implode(',', $v['ukey'] ) ; // echo $ukey . "--->" . $q['key'] ; if ($ukey == $q['key']){ $total_score += intval($v['score']) ; // echo $total_score .'<br>'; } } } // 保存分数 $exam->where('id' , $exam_id)->update(['score'=>$total_score]) ; $this->success('提交成功', url('/exam'), '', '10' ) ; }else{ $this->success('提交失败', url('/exam'), '', '10' ) ; } } /** * 显示创建资源表单页. * * @return \think\Response */ public function create() { // } /** * 保存新建的资源 * * @param \think\Request $request * @return \think\Response */ public function save(Request $request) { // } /** * 显示指定的资源 * * @param int $id * @return \think\Response */ public function read($id) { // } /** * 显示编辑资源表单页. * * @param int $id * @return \think\Response */ public function edit($id) { // } /** * 保存更新的资源 * * @param \think\Request $request * @param int $id * @return \think\Response */ public function update(Request $request, $id) { // } /** * 删除指定资源 * * @param int $id * @return \think\Response */ public function delete($id) { // } }
C++
UTF-8
9,122
2.578125
3
[ "MIT" ]
permissive
#include <eepp/ui/css/stylesheetselector.hpp> #include <eepp/ui/css/stylesheetelement.hpp> namespace EE { namespace UI { namespace CSS { StyleSheetSelector::StyleSheetSelector() : mName( "*" ), mSpecificity(0), mCacheable(true) { parseSelector( mName ); } StyleSheetSelector::StyleSheetSelector( const std::string& selectorName ) : mName( String::toLower( selectorName ) ), mSpecificity(0), mCacheable(true) { parseSelector( mName ); } const std::string &StyleSheetSelector::getName() const { return mName; } const std::string& StyleSheetSelector::getPseudoClass() const { return mPseudoClass; } const Uint32& StyleSheetSelector::getSpecificity() const { return mSpecificity; } void removeExtraSpaces( std::string& string ) { // @TODO: Optimize this string = String::trim( string ); String::replaceAll( string, " ", " " ); String::replaceAll( string, " ", " " ); String::replaceAll( string, " > ", ">" ); String::replaceAll( string, " + ", "+" ); String::replaceAll( string, " ~ ", "~" ); } void StyleSheetSelector::addSelectorRule(std::string& buffer, StyleSheetSelectorRule::PatternMatch& curPatternMatch , const StyleSheetSelectorRule::PatternMatch& newPatternMatch ) { StyleSheetSelectorRule selectorRule( buffer, curPatternMatch ); mSelectorRules.push_back( selectorRule ); curPatternMatch = newPatternMatch; buffer.clear(); mSpecificity += selectorRule.getSpecificity(); } void StyleSheetSelector::parseSelector( std::string selector ) { if ( !selector.empty() ) { // Remove spaces that means nothing to the selector logic // for example: // Element > .class #id // shold be // Element>.class #id removeExtraSpaces( selector ); std::string buffer; StyleSheetSelectorRule::PatternMatch curPatternMatch = StyleSheetSelectorRule::ANY; for ( auto charIt = selector.rbegin(); charIt != selector.rend(); ++charIt ) { char curChar = *charIt; switch ( curChar ) { case StyleSheetSelectorRule::DESCENDANT: addSelectorRule( buffer, curPatternMatch, StyleSheetSelectorRule::DESCENDANT ); break; case StyleSheetSelectorRule::CHILD: addSelectorRule( buffer, curPatternMatch, StyleSheetSelectorRule::CHILD ); break; case StyleSheetSelectorRule::DIRECT_SIBLING: addSelectorRule( buffer, curPatternMatch, StyleSheetSelectorRule::DIRECT_SIBLING ); break; case StyleSheetSelectorRule::SIBLING: addSelectorRule( buffer, curPatternMatch, StyleSheetSelectorRule::SIBLING ); break; default: buffer = curChar + buffer; break; } } if ( !buffer.empty() ) { addSelectorRule( buffer, curPatternMatch, StyleSheetSelectorRule::ANY ); buffer.clear(); } if ( !mSelectorRules.empty() && mSelectorRules[0].hasPseudoClasses() ) { mPseudoClass = mSelectorRules[0].getPseudoClasses()[0]; } if ( !mSelectorRules.empty() && mSelectorRules.size() > 1 ) { mCacheable = true; for ( size_t i = 1; i < mSelectorRules.size(); i++ ) { if ( mSelectorRules[i].hasPseudoClasses() || mSelectorRules[i].hasStructuralPseudoClasses() ) { mCacheable = false; break; } } } } } const bool &StyleSheetSelector::isCacheable() const { return mCacheable; } bool StyleSheetSelector::hasPseudoClass( const std::string& cls ) const { return mSelectorRules.empty() ? false : ( cls.empty() ? true : mSelectorRules[0].hasPseudoClass( cls ) ); } bool StyleSheetSelector::hasPseudoClasses() const { return mSelectorRules.empty() || mSelectorRules[0].hasPseudoClasses(); } bool StyleSheetSelector::select( StyleSheetElement * element, const bool& applyPseudo ) const { if ( mSelectorRules.empty() ) return false; StyleSheetElement * curElement = element; for ( size_t i = 0; i < mSelectorRules.size(); i++ ) { const StyleSheetSelectorRule& selectorRule = mSelectorRules[i]; switch ( selectorRule.getPatternMatch() ) { case StyleSheetSelectorRule::ANY: { if ( !selectorRule.matches( curElement, applyPseudo ) ) return false; break; // continue evaluating } case StyleSheetSelectorRule::DESCENDANT: { bool foundDescendant = false; curElement = curElement->getStyleSheetParentElement(); while ( NULL != curElement && !foundDescendant ) { if ( selectorRule.matches( curElement, applyPseudo ) ) { foundDescendant = true; } else { curElement = curElement->getStyleSheetParentElement(); } } if ( !foundDescendant ) return false; break; // continue evaluating } case StyleSheetSelectorRule::CHILD: { curElement = curElement->getStyleSheetParentElement(); if ( NULL == curElement || !selectorRule.matches( curElement, applyPseudo ) ) return false; break; // continue evaluating } case StyleSheetSelectorRule::DIRECT_SIBLING: { curElement = curElement->getStyleSheetPreviousSiblingElement(); if ( NULL == curElement || !selectorRule.matches( curElement, applyPseudo ) ) return false; break; // continue evaluating } case StyleSheetSelectorRule::SIBLING: { bool foundSibling = false; StyleSheetElement * prevSibling = curElement->getStyleSheetPreviousSiblingElement(); StyleSheetElement * nextSibling = curElement->getStyleSheetNextSiblingElement(); while ( NULL != prevSibling && !foundSibling ) { if ( selectorRule.matches( prevSibling, applyPseudo ) ) { foundSibling = true; } else { prevSibling = prevSibling->getStyleSheetPreviousSiblingElement(); } } if ( !foundSibling ) { while ( NULL != nextSibling && !foundSibling ) { if ( selectorRule.matches( nextSibling, applyPseudo ) ) { foundSibling = true; } else { nextSibling = nextSibling->getStyleSheetNextSiblingElement(); } } } if ( !foundSibling ) return false; break; // continue evaluating } } } return true; } std::vector<StyleSheetElement*> StyleSheetSelector::getRelatedElements( StyleSheetElement * element, const bool& applyPseudo ) const { static std::vector<StyleSheetElement*> EMPTY_ELEMENTS; std::vector<StyleSheetElement*> elements; if ( mSelectorRules.empty() ) return elements; StyleSheetElement * curElement = element; for ( size_t i = 0; i < mSelectorRules.size(); i++ ) { const StyleSheetSelectorRule& selectorRule = mSelectorRules[i]; switch ( selectorRule.getPatternMatch() ) { case StyleSheetSelectorRule::ANY: { if ( !selectorRule.matches( curElement, applyPseudo ) ) return EMPTY_ELEMENTS; break; // continue evaluating } case StyleSheetSelectorRule::DESCENDANT: { bool foundDescendant = false; curElement = curElement->getStyleSheetParentElement(); while ( NULL != curElement && !foundDescendant ) { if ( selectorRule.matches( curElement, applyPseudo ) ) { foundDescendant = true; } else { curElement = curElement->getStyleSheetParentElement(); } } if ( !foundDescendant ) return EMPTY_ELEMENTS; if ( 0 != i && ( selectorRule.hasPseudoClasses() || selectorRule.hasStructuralPseudoClasses() ) ) { elements.push_back( curElement ); } break; // continue evaluating } case StyleSheetSelectorRule::CHILD: { curElement = curElement->getStyleSheetParentElement(); if ( NULL == curElement || !selectorRule.matches( curElement, applyPseudo ) ) return EMPTY_ELEMENTS; if ( 0 != i && ( selectorRule.hasPseudoClasses() || selectorRule.hasStructuralPseudoClasses() ) ) { elements.push_back( curElement ); } break; // continue evaluating } case StyleSheetSelectorRule::DIRECT_SIBLING: { curElement = curElement->getStyleSheetPreviousSiblingElement(); if ( NULL == curElement || !selectorRule.matches( curElement, applyPseudo ) ) return EMPTY_ELEMENTS; if ( 0 != i && ( selectorRule.hasPseudoClasses() || selectorRule.hasStructuralPseudoClasses() ) ) { elements.push_back( curElement ); } break; // continue evaluating } case StyleSheetSelectorRule::SIBLING: { bool foundSibling = false; StyleSheetElement * prevSibling = curElement->getStyleSheetPreviousSiblingElement(); StyleSheetElement * nextSibling = curElement->getStyleSheetNextSiblingElement(); while ( NULL != prevSibling && !foundSibling ) { if ( selectorRule.matches( prevSibling, applyPseudo ) ) { foundSibling = true; curElement = prevSibling; } else { prevSibling = prevSibling->getStyleSheetPreviousSiblingElement(); } } if ( !foundSibling ) { while ( NULL != nextSibling && !foundSibling ) { if ( selectorRule.matches( nextSibling, applyPseudo ) ) { foundSibling = true; curElement = nextSibling; } else { nextSibling = nextSibling->getStyleSheetNextSiblingElement(); } } } if ( !foundSibling ) return EMPTY_ELEMENTS; if ( 0 != i && ( selectorRule.hasPseudoClasses() || selectorRule.hasStructuralPseudoClasses() ) ) { elements.push_back( curElement ); } break; // continue evaluating } } } return elements; } }}}
Java
UTF-8
4,347
1.992188
2
[]
no_license
package com.ad.tibi.lib; import android.app.Application; import android.util.Log; import com.ad.tibi.lib.imgad.ImageAdEntity; import com.ad.tibi.lib.util.AdNameType; import com.bytedance.sdk.openadsdk.TTAdConfig; import com.bytedance.sdk.openadsdk.TTAdConstant; import com.bytedance.sdk.openadsdk.TTAdSdk; import com.qq.e.comm.managers.GDTADManager; import java.util.HashMap; import java.util.Map; /** * 广告初始化 */ public class AdInit { static AdInit singleAdInit; /** * 位ID的Map */ private Map<String, String> idMapBaidu = new HashMap<>(); private Map<String, String> idMapGDT = new HashMap<>(); private Map<String, String> idMapCsj = new HashMap<>(); /** * 保存application */ private Application mContext; /** * 广点通的 AppId */ private String appIdGDT = ""; /** * 超时时间 */ private long timeOutMillis = 5000; /** * 前贴 */ private int preMoivePaddingSize = 0; /** * 广告信息 */ private ImageAdEntity imageAdEntity; public static AdInit getSingleAdInit() { if (singleAdInit == null) { synchronized (AdInit.class) { // 避免不必要的同步 if (singleAdInit == null) { // 在null的情况下创建实例 singleAdInit = new AdInit(); } } } return singleAdInit; } /** * 初始化广告 */ //广点通 public void initGDTAd(Application context, String gdtAdAppId, Map<String, String> gdtIdMap) { mContext = context; idMapGDT = gdtIdMap; appIdGDT = gdtAdAppId; GDTADManager.getInstance().initWith(context, gdtAdAppId); Log.i("initGDTAd", "初始化:" + AdNameType.GDT); } //穿山甲 public void initCsjAd(Application context, String csjAdAppId, String appName, Map<String, String> csjIdMap, boolean useTextureView) { Log.i("initCsjAd", "初始化:" + AdNameType.CSJ); mContext = context; idMapCsj = csjIdMap; //强烈建议在应用对应的Application#onCreate()方法中调用,避免出现content为null的异常 TTAdSdk.init(context, new TTAdConfig.Builder() .appId(csjAdAppId) .appName(appName) .useTextureView(useTextureView) //使用TextureView控件播放视频,默认为SurfaceView,当有SurfaceView冲突的场景,可以使用TextureView .titleBarTheme(TTAdConstant.TITLE_BAR_THEME_DARK) .allowShowNotify(true) //是否允许sdk展示通知栏提示 .allowShowPageWhenScreenLock(true) //是否在锁屏场景支持展示广告落地页 .debug(BuildConfig.DEBUG) //测试阶段打开,可以通过日志排查问题,上线时去除该调用 .directDownloadNetworkType(TTAdConstant.NETWORK_STATE_WIFI) //允许直接下载的网络状态集合 .supportMultiProcess(false) //是否支持多进程,true支持 // .httpStack(new MyOkStack3())//自定义网络库,demo中给出了okhttp3版本的样例,其余请自行开发或者咨询工作人员。 .build() ); Log.i("AdInit", "初始化:" + AdNameType.CSJ); } public void setAdTimeOutMillis(long millis) { timeOutMillis = millis; Log.i("AdInit", "全局设置超时时间:" + millis); } public long getTimeOutMillis() { return timeOutMillis; } public void setPreMoiveMarginTopSize(int height) { preMoivePaddingSize = height; } public Map<String, String> getIdMapBaidu() { return idMapBaidu; } public Map<String, String> getIdMapGDT() { return idMapGDT; } public Map<String, String> getIdMapCsj() { return idMapCsj; } public String getAppIdGDT() { return appIdGDT; } public void setAppIdGDT(String appIdGDT) { this.appIdGDT = appIdGDT; } public ImageAdEntity getImageAdEntity() { return imageAdEntity; } public void setImageAdEntity(ImageAdEntity imageAdEntity) { this.imageAdEntity = imageAdEntity; } }
Java
UTF-8
128
1.6875
2
[]
no_license
package com.miikaah.kitarakauppaclient; public interface IOnItemSelectedListener { public void onItemSelected(Object item); }
C++
UTF-8
5,424
2.703125
3
[ "MIT" ]
permissive
#include <application/application.hpp> #include <boost/regex.hpp> using namespace express; application::application() { } void application::get(const routePath route,const routeHandler rHandler) { register_route(http_verb::get,route,rHandler); } void application::post(const routePath route,const routeHandler rHandler) { register_route(http_verb::post,route,rHandler); } void application::put(const routePath route,const routeHandler rHandler) { register_route(http_verb::put,route,rHandler); } void application::del(const routePath route,const routeHandler rHandler) { register_route(http_verb::del,route,rHandler); } void application::register_route(const http_verb verb,const routePath route,const routeHandler rHandler) { actions _actions; handler _handler; _handler.func = rHandler; //extracting route parameters boost::regex params_regex(regxParam); boost::sregex_iterator next(route.begin(), route.end(), params_regex); boost::sregex_iterator end; //first element is for complete path _handler.params.push_back("path"); while (next != end) { boost::smatch match = *next; _handler.params.push_back(match.str(1)); next++; } //handling trailing edge //rewriting route as regular regex std::string regex_route = boost::regex_replace(route,params_regex,regxURI); _actions.insert(std::make_pair(verb,_handler)); _routing.insert(std::make_pair(regex_route,_actions)); } void application::listen(int port, std::string address) { HttpServer server(port,8); server.config.address=address; server.default_resource["GET"]=[&](std::shared_ptr<HttpServer::Response> res, std::shared_ptr<HttpServer::Request> req) { connect_route(http_verb::get,res,req); }; server.default_resource["POST"]=[&](std::shared_ptr<HttpServer::Response> res, std::shared_ptr<HttpServer::Request> req) { connect_route(http_verb::post,res,req); }; server.default_resource["PUT"]=[&](std::shared_ptr<HttpServer::Response> res, std::shared_ptr<HttpServer::Request> req) { connect_route(http_verb::put,res,req); }; server.default_resource["DELETE"]=[&](std::shared_ptr<HttpServer::Response> res, std::shared_ptr<HttpServer::Request> req) { connect_route(http_verb::del,res,req); }; std::thread server_thread([&server](){ server.start(); }); server_thread.join(); } void application::static_(const boost::filesystem::path rootPath) { namespace fs = boost::filesystem; if(!(fs::exists(rootPath) && fs::is_directory(rootPath))) return; _static_routes.push_back(rootPath); } void application::default_(const default_file def) { _default_file = def; } void application::connect_route(const http_verb verb, std::shared_ptr<HttpServer::Response> res, std::shared_ptr<HttpServer::Request> req) { express::response _res(res); paramMap pMap; std::string in_path(req->path); queryMap query; //match for queries if(verb == http_verb::get) { extract_query(in_path, query); } //matching for regular routes for(auto &rt : _routing) { auto route = rt.first; if((_routing[route].find(verb) != _routing[route].end()) && boost::regex_match(in_path,boost::regex(route))) { extract_parameters(in_path, route,_routing[route][verb].params,pMap); express::request::header_map h(req->header.begin(),req->header.end()); express::request _req(req,pMap,query,h); _routing[route][verb].func(_req,_res); return; } } if(!match_file(_res,req->path)) _res.sendStatus(http_status::http_not_found); } void application::extract_query(routePath &clientPath,queryMap &query) { //extracting route parameters boost::regex params_regex(regxQuery); boost::regex query_remove(regxQueryRemove); boost::sregex_iterator next(clientPath.begin(), clientPath.end(), params_regex); boost::sregex_iterator end; while (next != end) { boost::smatch match = *next; query.insert(std::make_pair(match.str(2),match.str(3))); next++; } clientPath = boost::regex_replace(clientPath,query_remove,""); } bool application::match_file(express::response &_res,std::string path) { //matching for files bool match = false; std::for_each(_static_routes.begin(),_static_routes.end(),[&](boost::filesystem::path p){ boost::filesystem::path file(p.string()+path); if(!boost::filesystem::is_directory(file) && boost::filesystem::exists(file)) { _res.sendFile(file); match = true; } else { boost::filesystem::path d_file(p.string()+path+"/"+_default_file); if(boost::filesystem::exists(d_file)) { _res.sendFile(d_file); match = true; } } }); return match; } void application::extract_parameters(const routePath clientPath,const routePath serverRegx,regx_params &regParamList,paramMap& pMap) { boost::regex regx(serverRegx); boost::smatch match; boost::regex_search(clientPath, match, regx); if (regParamList.size() == match.size()) { for (size_t i = 0; i < match.size(); ++i) { pMap.insert(std::make_pair(regParamList[i], match[i])); } } }
Java
UTF-8
6,511
2.78125
3
[]
no_license
package org.gyf.dao; import org.gyf.common.Info; import org.gyf.common.UserInfo; import java.sql.*; import java.util.ArrayList; /** * 对UserInfo表的增删查改操作 * 增改参数为对应UserInfo类对象 * 查可以按id查对应UserInfo信息,也可不加参数返回所有User信息 * 增删操作只有管理员有权执行,增删方法考虑与其他数据库一致性 * 查询更新操作不维护与其他数据库一致性 */ public class UserMysqlDaoImpl implements MysqlDao { public boolean Insert(Info term) { String InsertCmd = "INSERT INTO UserInfo (UserID, UserPassword, Gender, NickName, Age) VALUES (?,?,?,?,?)"; try { Connection MysqlConn = new MysqlConnection().getConnection(); PreparedStatement InsertStmt = MysqlConn.prepareStatement(InsertCmd); UserInfo user = (UserInfo) term; InsertStmt.setString(1, user.getId()); InsertStmt.setString(2, user.getKey()); InsertStmt.setString(3, user.getGender()); InsertStmt.setString(4, user.getNickname()); InsertStmt.setInt(5, user.getAge()); InsertStmt.executeUpdate(); MysqlConn.close(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } public boolean Update(Info term) { UserInfo user = (UserInfo) term; String id = user.getId(); String password = user.getKey(); String bike = user.getBike(); int balance = user.getBalance(); long time = user.getTime(); String UpdateActionCmd = "UPDATE UserInfo SET Balance=?, RendTime=?, RendBikeID=?, UserPassword=? WHERE UserID=?"; try { Connection MysqlConn = new MysqlConnection().getConnection(); PreparedStatement UpdateActionStmt = MysqlConn.prepareCall(UpdateActionCmd); UpdateActionStmt.setInt(1,balance); UpdateActionStmt.setLong(2, time); if(bike.equals("")) UpdateActionStmt.setNull(3, Types.CHAR); else UpdateActionStmt.setString(3, bike); UpdateActionStmt.setString(4, password); UpdateActionStmt.setString(5, id); UpdateActionStmt.executeUpdate(); MysqlConn.close(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } public Info Query(String mainkey) { String QueryCmd = "SELECT * FROM UserInfo WHERE UserID=?"; try { Connection MysqlConn = new MysqlConnection().getConnection(); PreparedStatement QueryStmt = MysqlConn.prepareStatement(QueryCmd); QueryStmt.setString(1,mainkey); ResultSet result = QueryStmt.executeQuery(); if(!result.next()){ MysqlConn.close(); return null; } else{ String id = result.getString("UserID"); String password = result.getString("UserPassword"); int balance = result.getInt("Balance"); long time = result.getLong("RendTime"); String Gender = result.getString("Gender"); String NickName = result.getString("NickName"); int age = result.getInt("Age"); String bike = result.getString("RendBikeID"); if(result.wasNull()) bike = ""; UserInfo user = new UserInfo(); user.setTime(time); user.setBalance(balance); user.setBike(bike); user.setId(id); user.setKey(password); user.setGender(Gender); user.setNickname(NickName); user.setAge(age); MysqlConn.close(); return user; } } catch (SQLException e) { e.printStackTrace(); return null; } } public ArrayList<UserInfo> Query() { String QueryCmd = "SELECT * FROM UserInfo"; ArrayList<UserInfo> userInfos = new ArrayList<UserInfo>(); try { Connection MysqlConn = new MysqlConnection().getConnection(); Statement QueryStmt = MysqlConn.createStatement(); ResultSet result = QueryStmt.executeQuery(QueryCmd); while(result.next()){ String id = result.getString("UserID"); String password = result.getString("UserPassword"); int balance = result.getInt("Balance"); long time = result.getLong("RendTime"); String bike = result.getString("RendBikeID"); if(result.wasNull()) bike = ""; String Gender = result.getString("Gender"); String NickName = result.getString("NickName"); int age = result.getInt("Age"); UserInfo user = new UserInfo(); user.setTime(time); user.setBalance(balance); user.setBike(bike); user.setId(id); user.setKey(password); user.setGender(Gender); user.setNickname(NickName); user.setAge(age); userInfos.add(user); } MysqlConn.close(); } catch (SQLException e) { e.printStackTrace(); } return userInfos; } public boolean Remove(String mainkey) { Connection MysqlConn = new MysqlConnection().getConnection(); UserMysqlDaoImpl userMysqlDao = new UserMysqlDaoImpl(); UserInfo userInfo = (UserInfo) userMysqlDao.Query(mainkey); if(userInfo == null || !userInfo.getBike().equals("") || userInfo.getBalance() != 0) return false; String RemoveCmd = "DELETE FROM UserInfo WHERE UserID=?"; try { PreparedStatement RemoveStmt = MysqlConn.prepareStatement(RemoveCmd); RemoveStmt.setString(1, mainkey); RemoveStmt.executeUpdate(); MysqlConn.close(); return true; } catch (SQLException e) { e.printStackTrace(); } return false; } }
C#
UTF-8
1,038
3.140625
3
[]
no_license
using Problem_8._Military_Elite.Interfaces; using System; using System.Collections.Generic; using System.Text; using System.Linq; public class LeutenantGeneral : ISoldier, IPrivate { public string Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Corps { get; set; } public double Salary { get; set; } public List<Private> privates; public LeutenantGeneral() { } public LeutenantGeneral(string id, string firstName, string lastName, double salary) : this() { this.privates = new List<Private>(); this.Id = id; this.FirstName = firstName; this.LastName = lastName; this.Salary = salary; } public void AddPrivates(Private pr) { this.privates.Add(pr); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendLine($"Name: {FirstName} {LastName} Id: {Id} Salary: {Salary}") .AppendLine($"Privates:"); foreach (var soldier in privates) { sb.Append(soldier.ToString()); } return sb.ToString(); } }
Ruby
UTF-8
511
2.9375
3
[]
no_license
module JsonFileReader # Reads a file with expected format (see note below), replaces line terminators # with commas and transforms into an array, so we can parse file content as JSON. # # Expects a file formatted with one object per line, and \n as a line terminator. # This restriction means the functionality may break for files created on systems # with alternate line terminators. def read_file(file) File .read(file) .gsub("}\n{", "},{") .prepend("[") << "]" end end
Java
UTF-8
511
3.390625
3
[]
no_license
import java.util.Scanner; import java.util.Stack; public class WipeAllCouples { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.next(); Stack<Character> stc = new Stack<>(); for (char i : str.toCharArray()) { if (stc.empty() || (i != stc.peek())) stc.push(i); else if (i == stc.peek()) stc.pop(); } for (Character i : stc) System.out.print(i); } }
Python
UTF-8
968
2.65625
3
[]
no_license
from math import floor, sqrt from collections import defaultdict def factors(n): d = defaultdict(int) for i in range(2,floor(sqrt(n))+1): while n % i == 0: n //= i d[i] += 1 if n == 1: break if n != 1: d[n] += 1 return d def inv(x, mod): k = mod - 2 ret = 1 while k > 0: if k&1: ret = (ret*x) % mod x = (x*x) % mod k >>= 1 return ret N, M = map(int,input().split()) mod = 10**9+7 dic = factors(M) K = len(dic) SIZE = N+max(dic.values()) if dic.values() else N fact = [None]*(SIZE+1) finv = [None]*(SIZE+1) fact[0] = 1 for i in range(1,SIZE+1): fact[i] = (fact[i-1]*i) % mod finv[SIZE] = inv(fact[SIZE], mod=mod) for i in range(SIZE, 0, -1): finv[i-1] = (finv[i]*i) % mod def comb(n,k): tmp = (finv[k]*finv[n-k]) % mod return (fact[n]*tmp) % mod ans = 1 for p in dic: ans = (ans*comb(dic[p]+N-1, dic[p])) % mod print(ans)
Java
UTF-8
2,826
2.25
2
[]
no_license
package com.gerrywen.seckill.model; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.Date; public class MiaoshaUser implements Serializable { @ApiModelProperty(value = "用户id, 手机号码") private Long id; @ApiModelProperty(value = "用户昵称") private String nickname; @ApiModelProperty(value = "MD5(MD5(password+salt)+salt)") private String password; @ApiModelProperty(value = "盐") private String salt; @ApiModelProperty(value = "头像, 云存储id") private String head; @ApiModelProperty(value = "注册时间") private Date redisterDate; @ApiModelProperty(value = "上次登录时间") private Date lastLoginDate; @ApiModelProperty(value = "总登录次数") private Integer loginCount; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public String getHead() { return head; } public void setHead(String head) { this.head = head; } public Date getRedisterDate() { return redisterDate; } public void setRedisterDate(Date redisterDate) { this.redisterDate = redisterDate; } public Date getLastLoginDate() { return lastLoginDate; } public void setLastLoginDate(Date lastLoginDate) { this.lastLoginDate = lastLoginDate; } public Integer getLoginCount() { return loginCount; } public void setLoginCount(Integer loginCount) { this.loginCount = loginCount; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", nickname=").append(nickname); sb.append(", password=").append(password); sb.append(", salt=").append(salt); sb.append(", head=").append(head); sb.append(", redisterDate=").append(redisterDate); sb.append(", lastLoginDate=").append(lastLoginDate); sb.append(", loginCount=").append(loginCount); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
Python
UTF-8
132
2.75
3
[]
no_license
with open("input_data/problem013.txt", "r") as f: cifre = list(map(int, f.read().splitlines())) print(str(sum(cifre))[:10])
Java
UTF-8
5,250
1.914063
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 edu.sena.entitty.recuperacion; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * * @author Julian Paredes */ @Entity @Table(name = "datospersonales") @NamedQueries({ @NamedQuery(name = "Datospersonales.findAll", query = "SELECT d FROM Datospersonales d")}) public class Datospersonales implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "idDatosPersonales") private Integer idDatosPersonales; @Size(max = 45) @Column(name = "tipoDocumento") private String tipoDocumento; @Size(max = 45) @Column(name = "primer_nombre") private String primerNombre; @Size(max = 45) @Column(name = "segundo_nombre") private String segundoNombre; @Size(max = 45) @Column(name = "primer_Apellido") private String primerApellido; @Size(max = 45) @Column(name = "segundo_Apellido") private String segundoApellido; @Size(max = 45) @Column(name = "telefono") private String telefono; @Size(max = 45) @Column(name = "correo") private String correo; @JoinColumn(name = "usuario_idUsuario", referencedColumnName = "idUsuario") @ManyToOne(optional = false, fetch = FetchType.LAZY) private Usuario usuarioidUsuario; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idDatosPersonales", fetch = FetchType.LAZY) private Collection<Vehiculos> vehiculosCollection; public Datospersonales() { } public Datospersonales(Integer idDatosPersonales) { this.idDatosPersonales = idDatosPersonales; } public Integer getIdDatosPersonales() { return idDatosPersonales; } public void setIdDatosPersonales(Integer idDatosPersonales) { this.idDatosPersonales = idDatosPersonales; } public String getTipoDocumento() { return tipoDocumento; } public void setTipoDocumento(String tipoDocumento) { this.tipoDocumento = tipoDocumento; } public String getPrimerNombre() { return primerNombre; } public void setPrimerNombre(String primerNombre) { this.primerNombre = primerNombre; } public String getSegundoNombre() { return segundoNombre; } public void setSegundoNombre(String segundoNombre) { this.segundoNombre = segundoNombre; } public String getPrimerApellido() { return primerApellido; } public void setPrimerApellido(String primerApellido) { this.primerApellido = primerApellido; } public String getSegundoApellido() { return segundoApellido; } public void setSegundoApellido(String segundoApellido) { this.segundoApellido = segundoApellido; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public String getCorreo() { return correo; } public void setCorreo(String correo) { this.correo = correo; } public Usuario getUsuarioidUsuario() { return usuarioidUsuario; } public void setUsuarioidUsuario(Usuario usuarioidUsuario) { this.usuarioidUsuario = usuarioidUsuario; } public Collection<Vehiculos> getVehiculosCollection() { return vehiculosCollection; } public void setVehiculosCollection(Collection<Vehiculos> vehiculosCollection) { this.vehiculosCollection = vehiculosCollection; } @Override public int hashCode() { int hash = 0; hash += (idDatosPersonales != null ? idDatosPersonales.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Datospersonales)) { return false; } Datospersonales other = (Datospersonales) object; if ((this.idDatosPersonales == null && other.idDatosPersonales != null) || (this.idDatosPersonales != null && !this.idDatosPersonales.equals(other.idDatosPersonales))) { return false; } return true; } @Override public String toString() { return "edu.sena.entitty.recuperacion.Datospersonales[ idDatosPersonales=" + idDatosPersonales + " ]"; } }
Java
UTF-8
1,561
3.53125
4
[]
no_license
package Manager; public class CheckInput { public static final String CORRECT = "correct"; /** * This method checks, whether length of the given password is more than 4 * and less than 16. If so, it returns string "correct" if not it returns * string "password" so we know, what error occured. * * @param password */ public static String checkPassword(String password) { if (password.length() == 0 || password.length() < 4 || password.length() > 16) { return "password"; } return CORRECT; } /** * This method checks, name consists of all the letters. If so, it returns * string "correct" if not it returns string errorName, which is given as a * variable so we know, what error occured. * * @param password */ public static String checkName(String name, String errorName) { if (name.length() == 0) { return errorName; } for (int i = 0; i < name.length(); i++) { if (!Character.isLetter(name.charAt(i))) { return errorName; } } return CORRECT; } /** * This method checks, whether entered Integer is equal to the given size * and all the symbols are digit. If so, it returns string "correct" if not * it returns string "password" so we know, what error occured. * * @param password */ public static String checkEnteredInteger(String personalId, int size, String errorName) { if (personalId.length() != size) { return errorName; } for (int i = 0; i < size; i++) { if (!Character.isDigit(personalId.charAt(i))) { return errorName; } } return CORRECT; } }
JavaScript
UTF-8
6,236
2.703125
3
[]
no_license
let wallCanvas = new OffscreenCanvas(canvas.width,canvas.height); let wallCtx = wallCanvas.getContext('2d'); function render(){ if(tiled){ renderTiled(); }else{ renderMarched(); } } function renderTiled(){ //ctx.fillStyle="black"; //ctx.fillRect(0,0,canvas.width,canvas.height); let rendered = 0; for(let x =0;x<GRID_WIDTH;x++){ for(let y =0;y<GRID_HEIGHT;y++){ let type = level[x][y]; if(type!=lastRendered[x][y]){ if(type==LIQUID){ ctx.fillStyle="blue"; }else if(type==AIR){ ctx.fillStyle="white"; }else if(type==WALL){ ctx.fillStyle="black"; } rendered++; lastRendered[x][y] = type; ctx.fillRect(x*TILE_SIZE,y*TILE_SIZE,TILE_SIZE,TILE_SIZE); } } } if(clock%30==0)console.log(rendered); } function renderMarched(){ if(!fill){ ctx.fillStyle="white"; ctx.fillRect(0,0,canvas.width,canvas.height); } ctx.beginPath(); calcMarch(LIQUID,ctx); ctx.fillStyle="blue"; ctx.strokeStyle="blue"; if(fill){ ctx.fill(); }else{ ctx.stroke(); } if(fill){ wallCtx.beginPath(); calcMarch(WALL,wallCtx); wallCtx.fillStyle="black"; wallCtx.strokeStyle="black"; wallCtx.fill(); ctx.drawImage(wallCanvas,0,0); }else{ ctx.beginPath(); calcMarch(WALL,ctx); ctx.fillStyle="black"; ctx.strokeStyle="black"; ctx.stroke(); } } function renderMarchCI(p1x,p1y,p2x,p2y,p3x,p3y,p4x,p4y,ctx){ //corners internes (3joints) let pax = (p1x+p4x)/2; let pay = (p1y+p4y)/2; let pbx = (p1x+p2x)/2; let pby = (p1y+p2y)/2; ctx.moveTo(pax*TILE_SIZE,pay*TILE_SIZE); ctx.lineTo(pbx*TILE_SIZE,pby*TILE_SIZE); if(fill){ ctx.lineTo(p2x*TILE_SIZE,p2y*TILE_SIZE); ctx.lineTo(p3x*TILE_SIZE,p3y*TILE_SIZE); ctx.lineTo(p4x*TILE_SIZE,p4y*TILE_SIZE); } } function renderMarchCE(p1x,p1y,p2x,p2y,p3x,p3y,p4x,p4y,ctx){ //corners externes (1seul joint) let pax = (p1x+p4x)/2; let pay = (p1y+p4y)/2; let pbx = (p1x+p2x)/2; let pby = (p1y+p2y)/2; ctx.moveTo(pax*TILE_SIZE,pay*TILE_SIZE); ctx.lineTo(pbx*TILE_SIZE,pby*TILE_SIZE); if(fill)ctx.lineTo(p1x*TILE_SIZE,p1y*TILE_SIZE); } function renderMarchM(p1x,p1y,p2x,p2y,p3x,p3y,p4x,p4y,ctx){ //Mid line let pax = (p1x+p4x)/2; let pay = (p1y+p4y)/2; let pbx = (p2x+p3x)/2; let pby = (p2y+p3y)/2; ctx.moveTo(pax*TILE_SIZE,pay*TILE_SIZE); ctx.lineTo(pbx*TILE_SIZE,pby*TILE_SIZE); if(fill){ ctx.lineTo(p2x*TILE_SIZE,p2y*TILE_SIZE); ctx.lineTo(p1x*TILE_SIZE,p1y*TILE_SIZE); } } function renderMarchF(p1x,p1y,p2x,p2y,p3x,p3y,p4x,p4y,ctx){ //Filled let pax1 = (p1x+p4x)/2; let pay1 = (p1y+p4y)/2; let pbx1 = (p3x+p4x)/2; let pby1 = (p3y+p4y)/2; let pax2 = (p1x+p2x)/2; let pay2 = (p1y+p2y)/2; let pbx2 = (p2x+p3x)/2; let pby2 = (p2y+p3y)/2; ctx.moveTo(pax1*TILE_SIZE,pay1*TILE_SIZE); ctx.lineTo(pbx1*TILE_SIZE,pby1*TILE_SIZE); if(fill){ ctx.lineTo(p3x*TILE_SIZE,p3y*TILE_SIZE); ctx.lineTo(pbx2*TILE_SIZE,pby2*TILE_SIZE); }else{ ctx.moveTo(pbx2*TILE_SIZE,pby2*TILE_SIZE); } ctx.lineTo(pax2*TILE_SIZE,pay2*TILE_SIZE); if(fill)ctx.lineTo(p1x*TILE_SIZE,p1y*TILE_SIZE); } function calcMarch(type,ctx){ //let rendered = 0; for(let x =0;x<GRID_WIDTH-1;x++){ for(let y =0;y<GRID_HEIGHT-1;y++){ //for(let i =0;i<changedTile.length;i++){ //let x = changedTile[i].x; //let y = changedTile[i].y; if(fill&&changedTile[x][y]==0)continue; let res = 0; if(type==LIQUID){ if(level[x][y+1]!=AIR)res+=1; if(level[x+1][y+1]!=AIR)res+=2; if(level[x+1][y]!=AIR)res+=4; if(level[x][y]!=AIR)res+=8; }else{ if(level[x][y+1]==type)res+=1; if(level[x+1][y+1]==type)res+=2; if(level[x+1][y]==type)res+=4; if(level[x][y]==type)res+=8; } if(!fill||res!=(type==WALL?lastRenderedWalls[x][y]:lastRendered[x][y])){ if(fill){ ctx.fillStyle="white"; ctx.clearRect(x*TILE_SIZE,y*TILE_SIZE,TILE_SIZE,TILE_SIZE); } if(type==LIQUID){ lastRendered[x][y] =res; }else{ lastRenderedWalls[x][y] =res; } switch(res){ case 0: break; case 1: renderMarchCE(x,y+1,x+1,y+1,x+1,y,x,y,ctx); break; case 2: renderMarchCE(x+1,y+1,x+1,y,x,y,x,y+1,ctx); break; case 3: renderMarchM(x,y+1,x+1,y+1,x+1,y,x,y,ctx);// break; case 4: renderMarchCE(x+1,y,x,y,x,y+1,x+1,y+1,ctx); break; case 5: renderMarchF(x,y+1,x+1,y+1,x+1,y,x,y,ctx);// break; case 6: renderMarchM(x+1,y+1,x+1,y,x,y,x,y+1,ctx);// break; case 7: renderMarchCI(x,y,x,y+1,x+1,y+1,x+1,y,ctx);//---dans autre sens break; case 8: renderMarchCE(x,y,x,y+1,x+1,y+1,x+1,y,ctx); break; case 9: renderMarchM(x,y,x,y+1,x+1,y+1,x+1,y,ctx);// break; case 10: renderMarchF(x+1,y+1,x+1,y,x,y,x,y+1,ctx);// break; case 11: renderMarchCI(x+1,y,x,y,x,y+1,x+1,y+1,ctx);//---dans autre sens break; case 12: renderMarchM(x+1,y,x,y,x,y+1,x+1,y+1,ctx);// break; case 13: renderMarchCI(x+1,y+1,x+1,y,x,y,x,y+1,ctx);//---dans autre sens break; case 14: renderMarchCI(x,y+1,x+1,y+1,x+1,y,x,y,ctx);//---dans autre sens break; case 15: if(fill){ ctx.moveTo(x*TILE_SIZE,y*TILE_SIZE); ctx.lineTo((x+1)*TILE_SIZE,y*TILE_SIZE); ctx.lineTo((x+1)*TILE_SIZE,(y+1)*TILE_SIZE); ctx.lineTo(x*TILE_SIZE,(y+1)*TILE_SIZE); } } } } } //if(clock%30==0)console.log(rendered); } function refresh(){ ctx.clearRect(0,0,canvas.width,canvas.height); wallCtx.clearRect(0,0,canvas.width,canvas.height); ctx.fillStyle= "black"; ctx.font= "10px Arial"; ctx.fillText("Render mode : " + (tiled?"Normal":"Smoothed"),1,47); ctx.font= "15px Arial"; ctx.fillText("Left click to add liquid",1,90); ctx.fillText("Right click to add wall",1,108); for(let x =0;x<GRID_WIDTH;x++){ for(let y =0;y<GRID_HEIGHT;y++){ lastRendered[x][y] = 0; lastRenderedWalls[x][y] = 0; changedTile[x][y] = 1; } } }
Python
UTF-8
66
3.390625
3
[]
no_license
n = int(input()) while (n>0) : print(n) n = n - 1
Java
UTF-8
3,175
2.25
2
[]
no_license
package com.bezkoder.springjwt.controllers; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.bezkoder.springjwt.exception.NotFoundException; import com.bezkoder.springjwt.repository.ArbitreRepository; import com.bezkoder.springjwt.repository.MatchRepository; import com.bezkoder.springjwt.models.Arbitre; @RestController @RequestMapping("/api") public class ArbitreController { @Autowired private ArbitreRepository arbitreRepository; @Autowired private MatchRepository matchRepository; @GetMapping("/matchs/{matchId}/arbitres") public List<Arbitre> getContactByMatchId(@PathVariable Long matchId) { if(!matchRepository.existsById(matchId)) { throw new NotFoundException("Match not found!"); } return arbitreRepository.findByMatchId(matchId); } @PostMapping("/matchs/{matchId}/arbitres") public Arbitre addArbitre(@PathVariable Long matchId, @Valid @RequestBody Arbitre arbitre) { return matchRepository.findById(matchId) .map(match -> { arbitre.setMatch(match); return arbitreRepository.save(arbitre); }).orElseThrow(() -> new NotFoundException("Match not found!")); } @PutMapping("/matchs/{matchId}/arbitres/{arbitreId}") public Arbitre updateArbitre(@PathVariable Long matchId, @PathVariable Long arbitreId, @Valid @RequestBody Arbitre arbitreUpdated) { if(!matchRepository.existsById(matchId)) { throw new NotFoundException("Match not found!"); } return arbitreRepository.findById(arbitreId) .map(arbitre -> { arbitre.setName(arbitreUpdated.getName()); arbitre.setAge(arbitreUpdated.getAge()); return arbitreRepository.save(arbitre); }).orElseThrow(() -> new NotFoundException("Arbitre not found!")); } @DeleteMapping("/matchs/{matchId}/arbitres/{arbitreId}") public String deleteArbitre(@PathVariable Long matchId, @PathVariable Long arbitreId) { if(!matchRepository.existsById(matchId)) { throw new NotFoundException("Match not found!"); } return arbitreRepository.findById(arbitreId) .map(arbitre -> { arbitreRepository.delete(arbitre); return "Deleted Successfully!"; }).orElseThrow(() -> new NotFoundException("Contact not found!")); } }
Java
UTF-8
2,038
2.484375
2
[]
no_license
package testA; import com.company.entity.Order; import com.company.entity.User; import com.company.mysql.MySQLOrderDao; import com.company.mysql.MySQLProductDao; import com.company.mysql.MySQLUserDao; import org.junit.Ignore; import org.junit.Test; import java.util.ArrayList; import java.util.List; /** * Created by Ira on 29.01.2016. */ public class TestDB { @Test public void testAddUser(){ MySQLOrderDao mySQLOrderDao = new MySQLOrderDao(); Order order = mySQLOrderDao.findById(14); System.out.println(order.getIdProduct()); // MySQLUserDao mySQLMySQLUserDao = new MySQLUserDao(); // System.out.println(mySQLMySQLUserDao.findByLoginPass("ivan", "pass").getName()); /* MySQLOrderDao mySQLOrderDao = new MySQLOrderDao(); List<Order> basket = mySQLOrderDao.findByIdUser(9); System.out.println(basket.size());*/ /* Order order = new Order(); order.setId(1); order.initOrder(1,1,1,false); mySQLOrderDao.delete(1); */ // mySQLOrderDao.save(order); /*String name = "имя"; String surname = "фамилия"; String login = "login"; String password = "password"; // TODO: save to DB new user User user = new User(); user.initUser(name,surname,login,password,false); mySQLMySQLUserDao.save(user); */ /* MySQLUserDao mySQLUserDao = new MySQLUserDao(); MySQLOrderDao mySQLOrderDao = new MySQLOrderDao(); MySQLProductDao mySQLProductDao = new MySQLProductDao(); List<User> userList = mySQLUserDao.findAll(); List<Double> debtList = new ArrayList<>(); double debt = 0.0; for(User user: userList){ List<Order> orderList = mySQLOrderDao.findByIdUser(user.getId()); for(Order order: orderList){ debt+= (mySQLProductDao.findById(order.getIdProduct()).getPrice()*order.getNumber()); } debtList.add(debt); }*/ } }
Shell
UTF-8
613
3.828125
4
[]
no_license
#!/bin/bash date=$(date +%Y_%m_%d) if [ -f /root/.ssh/id_rsa ] then echo "Creating backups for $date" mkdir $date mysql -u$DB_USER -p$DB_PASSWORD -h$DB_HOST -N -e 'show databases' | while read dbname do echo "Dumping database $dbname" mysqldump -u"$DB_USER" -p"$DB_PASSWORD" -h$DB_HOST "$dbname" > "$date/$dbname".sql done echo "Copying backups to $TARGET" rsync -va $date $TARGET echo "Done, cleaning up" rm -rf ./$date else echo "Please create SSH keys and copy them to the backup target" if [ -t 1 ] then ssh-keygen host=$(echo $TARGET | sed "s/\(.*\):.*/\1/") ssh-copy-id $host fi fi
Python
UTF-8
5,038
2.5625
3
[]
no_license
# Python 3.5.2 using Keras with the Tensorflow Backend. # Created on 12.08.2018, by Huy-Hieu PHAM, Cerema & IRIT, France. # Import libraries and packages. import os import math import numpy as np import tensorflow as tf from keras import optimizers from keras.optimizers import Adam from keras.layers import Dense, Dropout, Activation, Flatten, Lambda, BatchNormalization from keras.layers import Convolution2D, MaxPooling2D, AveragePooling2D, merge from keras.engine import Input, Model from keras.layers.advanced_activations import ELU from keras.optimizers import SGD from keras.callbacks import Callback, LearningRateScheduler, ModelCheckpoint, EarlyStopping from keras.preprocessing.image import ImageDataGenerator from keras.utils import np_utils import matplotlib.pyplot as plt from keras.utils import plot_model import keras.backend as K import json import time # Number of action classes on the combination dataset. nb_classes = 21 # Learning rate schedule. def step_decay(epoch): initial_lrate = 3e-4 drop = 0.5 epochs_drop = 20 lrate = initial_lrate * math.pow(drop, math.floor((1+epoch)/epochs_drop)) return lrate # 2539 for training and 2536 for testing. img_width, img_height = 32, 32 train_data_dir = 'data/combination-dataset/train' validation_data_dir = 'data/combination-dataset/validation' nb_train_samples = 12611 nb_validation_samples = 12611 epochs = 250 batch_size = 64 if K.image_data_format() == 'channels_first': input_shape = (3, img_width, img_height) else: input_shape = (img_width, img_height, 3) # Construct DenseNet architeture. model = densenet.DenseNet(nb_classes, input_shape, 40, # Depth: int -- how many layers; "Depth must be 3*N + 4" 3, # nb_dense_block: int -- number of dense blocks to add to end 12, # growth_rate: int -- number of filters to add 16, # nb_filter: int -- number of filters dropout_rate=0.2, weight_decay=0.0001) # Model output. model.summary() # Compile the model. model.compile(optimizer=Adam(lr=0.0003, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0), loss = 'sparse_categorical_crossentropy', metrics = ['accuracy']) # learning schedule callback lrate = LearningRateScheduler(step_decay) callbacks_list = [lrate] # Data augmentation. train_datagen = ImageDataGenerator(rescale = 1./255) test_datagen = ImageDataGenerator(rescale = 1./255) train_generator = train_datagen.flow_from_directory(train_data_dir, target_size = (img_width, img_height), batch_size = batch_size, class_mode = 'sparse') validation_generator = test_datagen.flow_from_directory(validation_data_dir, target_size = (img_width, img_height), batch_size = batch_size, class_mode = 'sparse') # Fit model. history = model.fit_generator(train_generator, steps_per_epoch=nb_train_samples // batch_size, epochs=epochs, validation_data=validation_generator, validation_steps=nb_validation_samples // batch_size, callbacks=callbacks_list, verbose=2) # Saving weight. model.save_weights('DenseNet-40-Tisseo.h5') # List all data in history. print(history.history.keys()) # grab the history object dictionary H = history.history last_train_acc = history.history['acc'][-1] * 100 last_train_loss = history.history['loss'][-1] last_train_acc = round(last_train_acc, 2) last_train_loss = round(last_train_loss, 6) train_loss = 'Training Loss, min = ' + str(last_train_loss) train_acc = 'Training Accuracy, max = ' + str(last_train_acc) +' (%)' # plot the training loss and accuracy N = np.arange(0, len(H["loss"])) plt.style.use("ggplot") plt.figure() axes = plt.gca() axes.set_ylim([0.0,1.2]) plt.plot(N, H['loss'],linewidth=2.5,label=train_loss,color='blue') plt.plot(N, H['acc'],linewidth=2.5, label=train_acc,color='red') #plt.plot(N, H['acc'],linewidth=2.5, label="Training Accuracy") plt.title('Enhanced-SPMF DenseNet-40 on MSR Action3D + NTU-RGB+D',fontsize=10, fontweight='bold',color = 'Gray') plt.xlabel('Number of Epochs',fontsize=10, fontweight='bold',color = 'Gray') plt.ylabel('Training Loss and Accuracy',fontsize=10, fontweight='bold',color = 'Gray') plt.legend() # Save the figureL plt.savefig('output/tisseo/Enhanced-SPMF-DenseNet-40.png') plt.show()
Python
UTF-8
6,038
3.625
4
[ "MIT" ]
permissive
# coding=utf-8 class SearchProblem(object): '''Abstract base class to represent and manipulate the search space of a problem. In this class, the search space is meant to be represented implicitly as a graph. Each state corresponds with a problem state (ie, a valid configuration) and each problem action (ie, a valid transformation to a configuracion) corresponds with an edge. To use this class with a problem seen as a graph search you should at least implement: `actions`, `result` and `is_goal`. Optionally, it might be useful to also implement `cost`. To use this class with a problem seen as an optimization over target function you should at least implement: `actions`, `result` and `value`. ''' def __init__(self, initial_state): self.initial_state = initial_state def actions(self, state): '''Returns the actions available to perform from `state`. The returned value is an iterable over actions. Actions are problem-specific and no assumption should be made about them. ''' raise NotImplementedError def result(self, state, action): '''Returns the resulting state of applying `action` to `state`.''' raise NotImplementedError def cost(self, state, action, state2): '''Returns the cost of applying `action` from `state` to `state2`. The returned value is a number (integer or floating point). By default this function returns `1`. ''' return 1 def is_goal(self, state): '''Returns `True` if `state` is a goal state and `False` otherwise''' raise NotImplementedError def value(self, state): '''Returns the value of `state` as it is needed by optimization problems. Value is a number (integer or floating point).''' raise NotImplementedError def heuristic(self, state): '''Returns an estimate of the cost remaining to reach the solution from `state`.''' return 0 def crossover(self, state1, state2): """ Crossover method for genetic search. It should return a new state that is the 'mix' (somehow) of `state1` and `state2`. """ raise NotImplementedError def mutate(self, state): """ Mutation method for genetic search. It should return a new state that is a slight random variation of `state`. """ raise NotImplementedError def generate_random_state(self): """ Generates a random state for genetic search. It's mainly used for the seed states in the initilization of genetic search. """ raise NotImplementedError def state_representation(self, state): """ Returns a string representation of a state. By default it returns repr(state). """ return repr(state) class SearchNode(object): '''Node of a search process.''' def __init__(self, state, parent=None, action=None, cost=0, problem=None, depth=0): self.state = state self.parent = parent self.action = action self.cost = cost self.problem = problem or parent.problem self.depth = depth def expand(self, local_search=False): '''Create successors.''' new_nodes = [] for action in self.problem.actions(self.state): new_state = self.problem.result(self.state, action) cost = self.problem.cost(self.state, action, new_state) nodefactory = self.__class__ new_nodes.append(nodefactory(state=new_state, parent=None if local_search else self, problem=self.problem, action=action, cost=self.cost + cost, depth=self.depth + 1)) return new_nodes def path(self): '''Path (list of nodes and actions) from root to this node.''' node = self path = [] while node: path.append((node.action, node.state)) node = node.parent return list(reversed(path)) def value(self): return self.problem.value(self.state) def __eq__(self, other): return isinstance(other, SearchNode) and self.state == other.state def __repr__(self): return 'Node <%s>' % self.problem.state_representation(self.state) class SearchNodeCostOrdered(SearchNode): def __lt__(self, other): return self.cost < other.cost class SearchNodeValueOrdered(SearchNode): def __lt__(self, other): # value must work inverted, because heapq sorts 1-9 # and we need 9-1 sorting return -self.value() < -other.value() class SearchNodeHeuristicOrdered(SearchNode): def __lt__(self, other): return self.problem.heuristic(self.state) < \ self.problem.heuristic(other.state) class SearchNodeStarOrdered(SearchNode): def __lt__(self, other): return self.problem.heuristic(self.state) + self.cost < \ self.problem.heuristic(other.state) + other.cost class CspProblem(object): def __init__(self, variables, domains, constraints): self.variables = variables self.domains = domains self.constraints = constraints # variable-based constraints dict self.var_contraints = dict([(v, [constraint for constraint in constraints if v in constraint[0]]) for v in variables]) # calculate degree of each variable self.var_degrees = dict([(v, len(self.var_contraints[v])) for v in variables])
JavaScript
UTF-8
3,190
2.765625
3
[]
no_license
import React, { Component } from "react"; import "./Details.scss"; import Container from "../../components/Container"; import TextBox from "../../components/TextBox"; class Details extends Component { state = { deets: [{ id: 1, img: "./images/react-logo.png", heading: "Built With React.js", text1: "React.js is a JavaScript library for creating dynamic, single page, and modularized web applications", text2: "To take full advantage of React, I created many reuseable stateless and stateful components. Calling these premade components in various places allowed me to make my portfolio lightweight and cohesive", text3: "I also utilized the react-router-dom npm package to simulate dynamic url addresses, and backend routing" }, { id: 2, img: "./images/d3.svg", heading: "Animated With D3.js", text1: "D3.js is a JavaScript library for creating custom animations and data visualiztions", text2: "I'm sure that by now you've noticed the animated background, well I made it using D3. Everything from the num of the circles to all of their properties (i.e color, size, opacity and position) are randomly generated, and then displayed on a svg background element. Then using D3's lifecycle methods, the data selection (the circles in this case) is updated every 5 seconds, leading to a random assortment of entering, updating and exiting circles", text3: "More good stuff is currently in the works!" }, { id: 3, img: "./images/sass-logo.png", heading: "Styled With Sass", text1: "Sass is a CSS preprocessor that allows for JavaScript-like styling and functionality", text2: "With Sass I was able to define variables in my stylesheets, which were than able to be called throughout my scss files. One example of this is my use of variables to make my color theming easy and consistant", text3: "In addition to defining variables, Sass also allows for CSS properties to be derived from JavaScript-like functions. I used this bit of functionality most widely when determining size properties of certain container elements" }] } render() { return ( <Container> <h2 className="detailsTitle">Portfolio Details Page</h2> <div className="detailsBox"> {this.state.deets.map(deet => ( <div className="deet" key={deet.id}> <img className="deetImage" src={deet.img} alt=""/> <h3>{deet.heading}</h3> <ul> <li>{deet.text1}</li> <li>•••</li> <li>{deet.text2}</li> <li>•••</li> <li>{deet.text3}</li> </ul> </div> ))} </div> </Container> ) } } export default Details;
Shell
UTF-8
4,345
3.640625
4
[]
no_license
# https://docs.aws.amazon.com/cli/latest/reference/logs/filter-log-events.html function aws:logs:filter_events { local start_time end_time filter local limit="1000" local group_name="" local stream_names=() local executor="execute_with_confirm" local pager="| less" local help="$( cat <<-HELP aws:logs:filter_events {parameters} *Parameter* *Required?* *Default* *Note* *Example* --start-time required JST --start-time '2022-02-02 02:00:00' --end-time required JST --end-time '2022-02-02 02:00:00' --filter required --filter '{ $.demand_id = "123456" || $.params = "*123456*" }' --limit optional 1000 --limit 100 --group-name optional (Select) --group-name example_group --stream-names optional (Select) --stream-names example_stream.1.log example_stream.2.log See https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html for filter syntaxes. HELP )" while (("${#@}" > 0)); do case "$1" in --start-time) start_time="${2:?}" shift 2 ;; --end-time) end_time="${2:?}" shift 2 ;; --filter) filter="${2:?}" shift 2 ;; --limit) limit="${2:?}" shift 2 ;; --group-name) group_name="${2:?}" shift 2 ;; --stream-names) shift 1 while (("${#@}" > 0)) && [[ ! "$1" =~ ^- ]]; do stream_names+=("${1:?}") shift 1 done ;; # Undocumented options --force | --no-confirm | --yes) executor="execute_with_echo" shift 1 ;; --no-pager) pager="" shift 1 ;; -h | --help) echo "${help}" return 0 ;; *) echo:error "Unknown option/argument: $1" return 1 esac done if [ -z "${start_time}" ] || [ -z "${end_time}" ] || [ -z "${filter}" ]; then echo "${help}" return 1 fi if [ -z "${group_name}" ]; then group_name="$(aws:logs:select_group)" fi if [ -z "${group_name}" ]; then echo:error "No log group name specified." return 1 fi if [ -z "${stream_names[*]}" ]; then stream_names=("${(@f)$(aws:logs:select_streams "${group_name}")}") fi if [ -z "${stream_names[*]}" ]; then echo:error "No log stream names specified." return 1 fi local aws_logs_options=( --log-group-name "${group_name}" --log-stream-names "'${(j:' ':)stream_names}'" --start-time "$(($(date -j -f '%F %T' "${start_time}" '+%s') * 1000))" --end-time "$(($(date -j -f '%F %T' "${end_time}" '+%s') * 1000))" --filter "'${filter}'" --query "'events[]'" --page-size "${limit}" --max-items "${limit}" --output json ) local jq_arg=".[] | [( .timestamp / 1000 | localtime | todateiso8601 ), ( .message | fromjson )]" local outpath="/tmp/aws-logs-filter_events-result-$(date '+%Y%m%d-%H%M%S').txt" # shellcheck disable=SC2034 local filtering_commands=( "aws logs filter-log-events ${aws_logs_options[*]}" "jq --compact-output --monochrome-output '${jq_arg}'" ) local start_time="$(date '+%s')" "${executor}" "${(j: | :)filtering_commands} > ${outpath}" local finish_time="$(date '+%s')" local notify_options=(--title "aws:logs:filter_events") if ((finish_time - start_time < 15)); then notify_options+=(--nostay) fi notify "Filtering has been completed." "${notify_options[@]}" execute_with_echo "jq --color-output . ${outpath} ${pager}" echo echo "See the result in \`${outpath}\`." } # https://docs.aws.amazon.com/cli/latest/reference/logs/describe-log-groups.html function aws:logs:select_group { aws logs describe-log-groups --output json | jq '.logGroups[].logGroupName' --raw-output | filter --preview-window "hidden" --prompt "Select a log group> " --no-multi } # https://docs.aws.amazon.com/cli/latest/reference/logs/describe-log-streams.html function aws:logs:select_streams { local group_name="${1:?}" aws logs describe-log-streams --log-group-name "${group_name}" | jq '.logStreams[].logStreamName' --raw-output | filter --preview-window "hidden" --prompt "Select log streams> " }
PHP
UTF-8
1,774
2.75
3
[]
no_license
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class JohnnyController extends Controller { /** * JohnnyController constructor. */ public function __construct() { $this->imageDir = public_path().'/images'; } public function index(Request $request) { return view('johnny.editor.editor'); } public function images(Request $request) { return $this->recursiveDirectoryIterator($this->imageDir); } /** * @param string $directory * @param array $files * * @return array */ private function recursiveDirectoryIterator($directory = null, $files = []) { $iterator = new \DirectoryIterator ($directory); foreach ($iterator as $info) { if ($info->isFile()) { if ($info->getBasename()[0] == '.') { continue; } $path = str_replace($this->imageDir.'/', '', $info->getPath()); $files [] = [ 'caption' => $path.'/'.$info->getBasename(), 'file' => $path.'/'.$info->getBasename(), ]; //$info; } elseif (! $info->isDot()) { //$list = [ // $info->__toString() => $this->recursiveDirectoryIterator($directory.DIRECTORY_SEPARATOR.$info->__toString()), //]; $list = $this->recursiveDirectoryIterator($directory.DIRECTORY_SEPARATOR.$info->__toString()); if (! empty($files)) { $files = array_merge_recursive($files, $list); } else { $files = $list; } } } return $files; } }
C++
UTF-8
1,796
3
3
[ "MIT" ]
permissive
#include "BinaryFileWriter.h" using namespace std; using namespace SPH; ofstream BinaryFileWriter::m_file; bool BinaryFileWriter::openMeshFile(const char *fileName) { m_file.open (fileName, ios::out | ios::binary); if(!m_file.is_open()) { cout << "Cannot open file."; return false; } return true; } void BinaryFileWriter::closeMeshFile() { m_file.close(); } void BinaryFileWriter::writeBuffer(const char *buffer, size_t size) { m_file.write(buffer, size); } void BinaryFileWriter::writeBool( const bool b ) { writeBuffer((char*) &b, sizeof(bool)); } void BinaryFileWriter::writeFloat( const float v ) { writeBuffer((char*) &v, sizeof(float)); } void BinaryFileWriter::writeInt( const int i ) { writeBuffer((char*) &i, sizeof(int)); } void BinaryFileWriter::writeUInt( const unsigned int i ) { writeBuffer((char*) &i, sizeof(unsigned int)); } void BinaryFileWriter::writeChar( const char c ) { writeBuffer(&c, sizeof(char)); } void BinaryFileWriter::writeDouble( const double v ) { writeBuffer((char*) &v, sizeof(double)); } void BinaryFileWriter::writeMatrix3f(const Eigen::Matrix3f &m) { for (unsigned int i=0; i < 3; i++) { for (unsigned int j=0; j < 3; j++) { writeFloat(m(i,j)); } } } void BinaryFileWriter::writeMatrix3d(const Eigen::Matrix3d &m) { for (unsigned int i = 0; i < 3; i++) { for (unsigned int j = 0; j < 3; j++) { writeDouble(m(i, j)); } } } void BinaryFileWriter::writeVector3f(const Eigen::Vector3f &v) { for (unsigned int j=0; j < 3; j++) { writeFloat(v[j]); } } void BinaryFileWriter::writeVector3d(const Eigen::Vector3d &v) { for (unsigned int j = 0; j < 3; j++) { writeDouble(v[j]); } } void BinaryFileWriter::writeString( const string &str ) { writeBuffer(str.c_str(), str.size()); writeChar(0); }
Java
UTF-8
1,781
1.976563
2
[]
no_license
package com.coxandkings.travel.operations.model.accountsummary; import com.fasterxml.jackson.annotation.JsonIgnore; import java.math.BigDecimal; import java.util.List; public class BookingPaymentAdviseInfo { private String supplierName; private BigDecimal netPayableToSupplier; private String paymentCurrency; @JsonIgnore private String supplierID; private String productType; private List<PaymentAdvisePaymentDetails> paymentAdviseDetailsList; public BookingPaymentAdviseInfo() { } public String getProductType() { return productType; } public void setProductType(String productType) { this.productType = productType; } public String getSupplierID() { return supplierID; } public void setSupplierID(String supplierID) { this.supplierID = supplierID; } public String getSupplierName() { return supplierName; } public void setSupplierName(String supplierName) { this.supplierName = supplierName; } public BigDecimal getNetPayableToSupplier() { return netPayableToSupplier; } public void setNetPayableToSupplier(BigDecimal netPayableToSupplier) { this.netPayableToSupplier = netPayableToSupplier; } public String getPaymentCurrency() { return paymentCurrency; } public void setPaymentCurrency(String paymentCurrency) { this.paymentCurrency = paymentCurrency; } public List<PaymentAdvisePaymentDetails> getPaymentAdviseDetailsList() { return paymentAdviseDetailsList; } public void setPaymentAdviseDetailsList(List<PaymentAdvisePaymentDetails> paymentAdviseDetailsList) { this.paymentAdviseDetailsList = paymentAdviseDetailsList; } }
Markdown
UTF-8
954
2.671875
3
[]
no_license
# 对象依赖循环性检查 ### 调用方式: POST ### 接口地址: ``` https://api.freelog.com/v2/storages/objects/{objectIdOrName}/cycleDependencyCheck ``` ### url传入参数说明: | 参数 | 必选 | 类型及范围 | 说明 | | :--- | :--- | :--- | :--- | | objectIdOrName | 可选 | string | 存储对象ID或者全名,需要URL编码 | ### body传入参数说明: | 参数 | 必选 | 类型及范围 | 说明 | | :--- | :--- | :--- | :--- | | dependencies | 可选 | object[] | 依赖项 | | **name | 必选 | string | 依赖的object或者resource名称 | | **type | 必选 | string | 依赖项类型,object或者resource二选一 | | **versionRange | 可选 | string | 依赖的资源版本范围 | ### 返回说明: | 返回值字段 | 字段类型 | 字段说明 | | :--- | :--- | :--- | | [data] | boolean | 是否校验成功 | ### 示例 ```json { "ret":0, "errcode":0, "msg":"success", "data":true } ```
Java
UTF-8
645
2.71875
3
[]
no_license
package EmploymentMarket01; public class Company { public String Name; public String WebPage; public CompanyType Sector; public Company(String name, String webPage, CompanyType sector) { super(); Name = name; WebPage = webPage; Sector = sector; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getWebPage() { return WebPage; } public void setWebPage(String webPage) { WebPage = webPage; } public CompanyType getSector() { return Sector; } public void setSector(CompanyType sector) { Sector = sector; } }
C++
UTF-8
1,301
3.875
4
[]
no_license
//program to find if a string has balanced parenthesis //parenthesis used for this program - () #include<iostream> #include<stack> #include<string> using namespace std; bool isbalanced(string s) //func returning 1/o based on inpur string { stack <char> st; //char stack declared int i=0; bool ans=true; string temp; for(i=0;i<s.length();i++) //loop to iterate over the string { if(s[i]=='(') { st.push(s[i]); } else if (s[i]==')') { if(!st.empty()&& st.top()=='(') st.pop(); else { ans=false; break; } } } if(!st.empty()) //important to address one of the corner cases, when string is left with only opening brackets return false; return ans; } int main() { string s; cout<<"Enter the parenthesis string here. "; getline(cin,s); //input the parenthesis string if(isbalanced(s)) cout<<"Balanced string"; else cout<<"Unbalanced string"; }
JavaScript
UTF-8
1,559
3.015625
3
[]
no_license
import {crearCURegistro} from "../../src/usuarios/negocio/crearRegistro.js" function crearDaoUsuariosTest() { const usuarios = [] return { add: (usuario, claveUnica) => { const existe = usuarios.some(u => { return u[claveUnica] === usuario[claveUnica] }) if (existe) { console.log(`El usuario ${usuario.nombre} no se ha registrado. Ya existe`) return { added: 0 } } else { usuarios.push(usuario) console.log(`El usuario ${usuario.nombre} se ha registrado`) return { added: 1 } } } } } const daoUsuarios = crearDaoUsuariosTest() const enviadorDeMails = { enviarConHtml: async (to, subject, html) => { console.log(`Mail enviado a ${to} asunto: ${subject} HTML a enviar: ${html} `) }, } const socio1 = { nombre: 'eze1', apellido: 'salo', email: 'clubortemail@gmail.com', dni: '333', password: 'eze1' } const socio2 = { nombre: 'eze2', apellido: 'salo', email: 'clubortemail@gmail.com', dni: '45', password: 'eze1' } function generarCuerpoMailRegistro(datos){ return `<h1> Hola ${datos.nombre}, bienvenido a Ort Club!</h1>` } const CU_registro = crearCURegistro(daoUsuarios, enviadorDeMails, 'test asunto', generarCuerpoMailRegistro) await CU_registro.ejecutar(socio1) await CU_registro.ejecutar(socio2)
Python
UTF-8
290
2.640625
3
[]
no_license
import csv lines = [] with open('dic_v3_2.txt', 'r') as readFile: for line in readFile: if line[-1] == '\n': line = line[:-1] lines.append([line]) with open('dic2205.csv', 'w') as writeFile: writer = csv.writer(writeFile) writer.writerows(lines)
Python
UTF-8
457
3.625
4
[]
no_license
#Global Variable """ a=10 def demo(): print(a) demo() print(a) #O/p:10 10 """ """ a=10 def demo(): a=20 print(a) demo() print(a) #o/p:20 10 """ """ a=10 def demo(): print(a) a+=10 print(a) demo() print(a) #Output:UnboundLocalError: local variable 'a' referenced before assignment """ a=10 def demo(): global a a+=10 print(a) demo() print(a) #Output:20 # 20