branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>lexycole/serverless-application-model<file_sep>/samtranslator/__init__.py __version__ = "1.36.0"
7c765cd1abbcb63746e18472050cea98aba34225
[ "Python" ]
1
Python
lexycole/serverless-application-model
a3a99d3b8d4c6b0d86a703ab41cf06b58a43d30e
77a80ee59b34143113d3adb3d5ef98a46a77799d
refs/heads/master
<repo_name>alexmilano/pollbag<file_sep>/mobile/php/lib/plugin.class.php <?php class Plugin{ static function get_plugin_by_alias($alias){ if(file_exists("php/".$alias.".php")){ require_once("php/".$alias.".php"); if(class_exists(ucfirst($alias))) eval ("$"."plugin = new ".ucfirst($alias)."();"); }else { require_once 'php/not_found.php'; global $lang_switch; //$link = Util::sql2obj('SELECT * FROM secciones WHERE es_alias = "'.$alias.'" OR en_alias = "'.$alias.'"'); $link = Util::sql2obj('SELECT * FROM secciones WHERE '.$lang_switch->actual_lang.'_alias = "'.$alias.'"'); if(!is_object($link)) return new NotFound(); if(file_exists("php/".$link->seccion.".php")){ require_once("php/".$link->seccion.".php"); if(class_exists(ucfirst($link->seccion))) eval ("$"."plugin = new ".ucfirst($link->seccion)."();"); else return new NotFound(); }else return new NotFound(); } return $plugin; } static function get_localized_link($seccion, $loc = ''){ require_once 'lib/util.class.php'; global $lang_switch, $liveSite; $ls = (strpos($liveSite,'https') === false)?$liveSite: str_replace('https','http',$liveSite); $loc = ($loc == '')?$lang_switch->actual_lang:$loc; $link = Util::sql2obj('SELECT '.$loc.'_alias alias FROM secciones WHERE seccion = "'.$seccion.'" OR es_alias ="'.$seccion.'" OR en_alias ="'.$seccion.'" '); $alias = is_object($link)? $link->alias: $seccion; $lang = ($loc == $lang_switch->def_lang) ? '':$loc.'/'; return ($ls.$lang.Util::canonize($alias).'/'); } } ?><file_sep>/mobile/php/gatewayFB.php <?php class GatewayFB{ var $contentType = ""; function getContenido($a) { switch ($a) { case "post_auturozida": $this->post_auturozida(); break; case "connect": if(isset($_GET['xd_receiver'])) $this->xd_receiver(); else $this->connect(); break; case "xd_receiver": $this->xd_receiver(); break; case "post_connect": $this->post_connect(); break; case "obtener_amigos": $this->obtener_amigos(); default: $this->connect(); } } function post_connect(){ echo "post_connect"; ?> <?php $this->obtener_amigos(); } function obtener_amigos(){ ini_set("display_errors", true); global $appapikey, $appsecret, $GA; require_once 'php/lib/fb/facebook.php'; //require_once 'php/copies.php'; $facebook = new Facebook($appapikey, $appsecret); $user_id = $facebook->require_login(); $user_id = $_GET['id']; echo "obtener_amigos( $user_id )"; //$facebook->require_frame(); echo "<pre>"; //$sql= "select uid2 from friend where uid1 = $user_id";//"select aid, name from album where owner IN ( select uid2 from friend where uid1 = $user_id ) and size > 0 LIMIT 0, 100"; $sql = "select aid, name from album where owner = 761087785"; echo $sql."<br>"; $friends = $facebook->api_client->fql_query($sql); $amigos = array(); if($friends != NULL) { foreach ($friends as $friend) { $amigos[] = $friend['uid2']; } } echo "amigos: ".implode(",",$amigos)."<hr>"; $sql = "select aid, name from album where owner IN( ".implode(",",$amigos).") and size > 0 ";//"select aid, name from album where owner IN ( select uid2 from friend where uid1 = $user_id ) and size > 0 LIMIT 0, 100"; echo $sql."<br>"; $albumes = $facebook->api_client->fql_query($sql); $users = array(); if($albumes != NULL) { foreach ($albumes as $album) { print_r($album); } } echo "queris..."; //$queries = array('{ "q_amigos":"select uid2 from friend where uid1 = $user_id)"}'); $queries = '{ "q_amigos":"select uid2 from friend where uid1 = $user_id)", "q_albumes":"select aid, name from album where owner IN ( select uid2 from friend where uid1 = $user_id ) and size > 0", "q_fotos":"select src_small, src_big FROM photo where aid IN ( SELECT aid FROM #query2 ) ORDER BY created" }'; echo "calling.."; try{ $response = $facebook->api_client->fql_multiquery(array($queries)); }catch(Exception $e){ echo "Erorrr"; print_r($e); } print_r($response); exit; $sql= "SELECT uid FROM user WHERE is_app_user = 1 AND uid IN (SELECT uid2 FROM friend WHERE uid1 = $user_id) LIMIT 0, 500"; $friends = $facebook->api_client->fql_query($sql); $users = array(); } function post_auturozida(){ //TODO: insertar el id_facebook a la base de datos global $appapikey, $appsecret, $GA; require_once 'php/lib/fb/facebook.php'; require_once 'php/html/polla_app.html.php'; $facebook = new Facebook($appapikey, $appsecret); $facebook->require_frame(); $user_id = $facebook->require_login(); Polla_appHTML::multi_invite_form($facebook); Polla_appHTML::analytics($GA); //$sql = "INSERT INTO registro (id_facebook, facebook_app_instalada ) VALUES ($user_id, 1)"; //$result = mysql_query($sql); //TODO: Vincular los UID del sitio con los de Facebook, ??? //echo "post_auturozida ".$user_id; } function connect(){ /* ini_set("display_errors", true); global $appapikey, $appsecret, $GA; require_once 'php/lib/fb/facebook.php'; $facebook = new Facebook($appapikey, $appsecret); $user_id = $facebook->require_login(); echo "USERID: $user_id"; */ global $appapikey, $appsecret, $GA; require_once 'php/lib/fb/facebook.php'; ////////// require_once("lib/fb/facebook.php"); $config = array(); $config['appId'] = $appapikey; $config['secret'] = $appsecret; $config['fileUpload'] = false; // optional $facebook = new Facebook($config); //////// //$facebook = new Facebook($appapikey, $appsecret); require_once("html/facebook_connect.html.php"); FacebookConnectHTML::connect(); } function xd_receiver(){ require_once("html/facebook_connect.html.php"); FacebookConnectHTML::xd_receiver(); } } ?><file_sep>/mobile/php/lib/control.class.php <?php class Control{ var $label = ""; var $value = ""; var $required = true; var $enabled = true; var $tipo = 0; var $data_source = false; function Control($tipo){ $this->tipo = $tipo; } function render(){ require_once 'php/lib/control.html.php'; switch($this->tipo){ case 1: ControlHTML::render_text_field($this->label, $this->value, $this->required, $this->enabled); break; case 2: ControlHTML::render_text($this->label, $this->value, $this->required, $this->enabled);; break; case 3: ControlHTML::render_html_text($this->label, $this->value, $this->required, $this->enabled);; break; case 4: ControlHTML::render_password($this->label, $this->value, $this->required, $this->enabled);; break; case 5: ControlHTML::render_email($this->label, $this->value, $this->required, $this->enabled);; break; case 6: $val = ($this->value == '')?date('Y/m/d H:i:s'):$this->value; ControlHTML::render_fecha($this->label, $val, $this->required, $this->enabled);; break; case 7: ControlHTML::render_archivo($this->label, $this->value, $this->required, $this->enabled);; break; case 8: if(is_array($this->data_source)){ $sql = "SELECT ".$this->data_source['label'].", ".$this->data_source['id']." FROM ".$this->data_source['tabla']; $result = mysql_query($sql) or die(mysql_error()); $opciones = array(); while($o = mysql_fetch_assoc($result)){ $opciones[] = array('label' => $o[$this->data_source['label']], 'id' => $o[$this->data_source['id']]); } }else{ $opciones = array(); $partes = explode(';',$this->data_source); $labels = explode(',', $partes[0]); $ids = explode(',', $partes[1]); $i = 0; foreach($labels as $l){ $opciones[] = array('label' => $l, 'id' => $ids[$i]); $i++; } } ControlHTML::render_lista($this->label, $this->value, $opciones, $this->required, $this->enabled);; break; case 9: if(is_array($this->data_source)){ $sql = "SELECT ".$this->data_source['label'].", ".$this->data_source['id']." FROM ".$this->data_source['tabla']; $result = mysql_query($sql) or die(mysql_error()); $opciones = array(); while($o = mysql_fetch_assoc($result)){ $opciones[] = array('label' => $o[$this->data_source['label']], 'id' => $o[$this->data_source['id']]); } }else{ $opciones = array(); $partes = explode(';',$this->data_source); $labels = explode(',', $partes[0]); $ids = explode(',', $partes[1]); $i = 0; foreach($labels as $l){ $opciones[] = array('label' => $l, 'id' => $ids[$i]); $i++; } } ControlHTML::render_lista_multiple($this->label, $this->value, $opciones, $this->required, $this->enabled);; break; } } } ?><file_sep>/mobile/php/mainconn.php <?php $conexion = mysql_connect($hostname,$username,$pass) or die("Error de conexión el servidor mysql ha dicho: <em>".mysql_error()."</em>"); mysql_select_db($dbname, $conexion) or die("Error seleccionando la DB $dbname: <em>".mysql_error()."</em>"); ?><file_sep>/mobile/php/lib/mailer.class.php <?php class Mailer{ static function send_mail($cuerpo, $from, $from_name, $to, $to_name, $subject){ require_once('class.phpmailer.php'); $mailTemp = new PHPMailer(); /* $mailTemp->IsSMTP(); $mailTemp->SMTPDebug = 2; $mailTemp->Host = "ssl://mail.gangasinc.com"; $mailTemp->Port = 465; $mailTemp->SMTPAuth = true; $mailTemp->Username = "<EMAIL>"; $mailTemp->Password = "****"; */ $mailTemp->IsMail(); $mailTemp->SetLanguage("es",getcwd()."/php/language/"); $mailTemp->IsHTML(true); $mailTemp->SetFrom($from, $from_name); //$mailTemp->From = $from; //$mailTemp->SetFrom = $from_name; $mailTemp->Subject = $subject; $mailTemp->AddAddress($to, $to_name); $mailTemp->AltBody = "Para ver este mensaje utilice un cliente de correo compatible con HTML!"; // optional, comment out and test $mailTemp->MsgHTML($cuerpo); $envio = $mailTemp->Send(); if($envio){ return true; }else{ return $mailTemp->ErrorInfo; } } function enviarEmailRemoto($cuerpo, $from, $from_name, $to, $to_name, $subject , $host_remoto) { $fp = fsockopen($host_remoto, 80, $errno, $errstr, 30); if (!$fp){ echo "resultado=error&msj=Error inesperado&t=$errstr ($errno)\n"; }else{ $key = "k=".base64_encode(("cuerpo=".base64_encode($cuerpo)."&from=".$from."&from_name=".$from_name."&to=".$to."&to_name=".$to_name."&subject=".$subject)); //fwrite($fp, "GET /mailing_bohemia/response.php?k=$key HTTP/1.0\r\nHost: www.netbangers.com\r\n\r\n"); $http = "POST /mailing_remoto/response.php HTTP/1.1\r\n"; $http .= "Host: ".$this->host_remoto."\r\n"; $http .= "User-Agent: " . $_SERVER['HTTP_USER_AGENT'] . "\r\n"; $http .= "Content-Type: application/x-www-form-urlencoded\r\n"; $http .= "Content-length: " . strlen($key) . "\r\n"; $http .= "Connection: close\r\n\r\n"; $http .= $key. "\r\n\r\n"; fwrite($fp, $http); $data = ""; while (!feof($fp)){ $data.=fgets($fp,64000); } fclose($fp); $data = substr($data, strpos($data, "}")+1); return $data; //print ($data); } } } ?><file_sep>/mobile/php/html/config_a.html.php <?php class ConfigHTML{ static function acciones(){ global $liveSite; ?> <div id="actions" class="container_12"> <div class="grid_3 prefix_9"> <h2>Config</h2> </div> <div class="grid_7 prefix_5"> <a href="<?php echo $liveSite; ?>admin/config/">Ver tablas</a> </div> <hr class="grid_12" /> <div class="clear"></div> </div> <?php } static function listado($tablas){ global $liveSite; ?> <div class="container_12"> <div class="grid_2 prefix_1"><h3>Nombre</h3></div> <div class="grid_1">&nbsp;</div> <div class="grid_1">&nbsp;</div> <div class="clear"></div> </div> <div class="container_12"> <?php $class = 'dark'; foreach($tablas as $t){ ?> <div class="fila fila_<?php echo $class; ?>"> <div class="grid_2 prefix_1"><?php echo $t->nombre; ?>&nbsp;</div> <div class="grid_3"><a href="<?php echo $liveSite; ?>admin/config/?a_=crear_objeto&tabla=<?php echo $t->nombre; ?>" > <?php if( $t->file == 0) {?> Crear clases <?php } else { ?> Volver a crear <small>(Se perderan las modificaciones hechas!!)</small> <?php } ?> </a> </div> <div class="grid_1"> &nbsp; </div> <div class="clear"></div> </div> <div class="clear"></div> <?php $class = ($class == 'light') ? 'dark' : 'light'; } ?> </div> <?php } static function form($tabla, $fields, $tablas){ // echo "<pre>"; print_r ($tablas); echo "</pre>"; global $liveSite; ?> <div class="container_12"> <form action="<?php echo $liveSite; ?>admin/config/?a_=guardar" method="post" id="config_form" name="config_form" enctype="application/x-www-form-urlencoded"> <h2 class="grid_12"><?php echo ucfirst($tabla); ?></h2> <div class="grid_12"> <label for="admin">Crear clase admin: </label> <input type="checkbox" name="admin" /> <label for="adminHTML">Crear clase adminHTML: </label> <input type="checkbox" name="adminHTML" /> <br /> <label for="public">Crear clase public: </label> <input type="checkbox" name="public" /> <label for="publicHTML">Crear clase publicHTML: </label> <input type="checkbox" name="publicHTML" /> <div class="clear"></div> <br /> </div> <div class="grid_12"> <label for="objeto">Nombre objeto: </label><br /> <input type="text" name="objeto" class="validate['required']" /> <div class="clear"></div> <br /> </div> <div class="grid_2"><h3>Campo</h3></div> <div class="grid_1"><h3>Id</h3></div> <div class="grid_1"><h3>Activo</h3></div> <div class="grid_1"><h3>Listado</h3></div> <div class="grid_2"><h3>Administrar</h3></div> <div class="grid_2"><h3>Tipo</h3></div> <div class="clear"></div> <?php foreach($fields as $f){ ?> <div class="grid_2"><?php echo $f; ?></div> <div class="grid_1"><input name="campo_id" value="<?php echo $f; ?>" type="radio" class="validate['required']" /></div> <div class="grid_1"><input name="campo_publicado" value="<?php echo $f; ?>" type="radio" class="validate['required']" /></div> <div class="grid_1"><input name="campos_lista[]" value="<?php echo $f; ?>" type="checkbox" /></div> <div class="grid_2"><input name="campos_form[]" value="<?php echo $f; ?>" type="checkbox" /></div> <div class="grid_2"> <select name="tipo_<?php echo $f; ?>" id="tipo_<?php echo $f; ?>" onchange="verificar(this)"> <option value="1">Texto corto</option> <option value="2">Texto plano</option> <option value="3">Texto HTML</option> <option value="4">Password</option> <option value="5">Email</option> <option value="6">Fecha</option> <option value="7">Archivo</option> <option value="8">Lista</option> <option value="9" disabled>Opciones múltiples</option> <option value="10" disabled>Opciones únicas</option> </select> </div> <div class="clear"></div> <div class="list_options" id="opciones_tipo_<?php echo $f; ?>"> <div class="grid_2"> <label>Estático</label> </div> <div class="grid_1"> <input name="estatico_<?php echo $f; ?>" type="radio" value="1" /> </div> <div class="grid_1">Labels</div> <div class="grid_2"><input type="text" name="estatico_labels_<?php echo $f; ?>" /></div> <div class="grid_1">Valores</div> <div class="grid_2"><input type="text" name="estatico_values_<?php echo $f; ?>" /></div> <div class="clear"></div> <br /> <div class="grid_2"> <label>Dinámico</label> </div> <div class="grid_1"> <input name="estatico_<?php echo $f; ?>" type="radio" value="2" /> </div> <div class="grid_1">Tabla</div> <div class="grid_2"> <select name="tabla_<?php echo $f; ?>" id="tabla_<?php echo $f; ?>" onchange="llenar_campos_tabla(this)"> <option value="">Selecciones...</option> <?php foreach($tablas as $t){?> <option value="<?php echo $t->nombre; ?>"><?php echo $t->nombre; ?></option> <?php } ?> </select> <script type="text/javascript"> <?php foreach($tablas as $t){?> var campos_<?php echo $t->nombre; ?> = new Array(); <?php foreach($t->fields as $field){?> campos_<?php echo $t->nombre; ?>.push('<?php echo $field; ?>'); <?php } ?> <?php } ?> </script> </div> <div class="grid_1">Label</div> <div class="grid_2"> <select name="label_tabla_<?php echo $f; ?>" id="label_tabla_<?php echo $f; ?>" > <option value="">Selecciones...</option> </select> </div> <div class="grid_1">Id</div> <div class="grid_2"> <select name="campo_tabla_<?php echo $f; ?>" id="campo_tabla_<?php echo $f; ?>" > <option value="">Selecciones...</option> </select> </div> <div class="clear"></div> <br /> </div> <script type="text/javascript"> var original_tipo_<?php echo $f; ?> = ''; window.addEvent('domready',function(){ original_tipo_<?php echo $f; ?> = $('opciones_tipo_<?php echo $f; ?>').getStyle('height'); $('opciones_tipo_<?php echo $f; ?>').setStyle('height', '0px'); }); </script> <?php } ?> <br /> <div class="grid_12"> <input type="hidden" name="tabla" value="<?php echo $tabla; ?>" /> <br /><br /> <input type="submit" name="" value="Crear.." /> </div> </form> <script type="text/javascript"> window.addEvent('domready',function(){ var formcheck = new FormCheck('config_form', { trimValue: true, showErrors: 1, indicateErrors: 1, onSubmit: function(){tinyMCE.triggerSave(); } }); }); function verificar(lista){ if(lista.value == 8){ var alto = eval('original_'+lista.id); var morph = new Fx.Morph('opciones_'+lista.id); morph.start({ height: alto }); }else{ var morph = new Fx.Morph('opciones_'+lista.id); morph.start({ height: '0px' }); } } function llenar_campos_tabla(tabla){ var arreglo = eval('campos_'+tabla.value ); $('label_'+tabla.id).options.length = 1; arreglo.each(function(el, index){ $('label_'+tabla.id).options[index+1] = new Option(el, el, false, false); $('campo_'+tabla.id).options[index+1] = new Option(el, el, false, false); }); } </script> </div> <?php } } ?><file_sep>/mobile/php/ordenes.admin.php <?php class Ordenes{ var $contentType = ""; var $tabla = "ordenes"; var $campos_form = array('id_orden' => 0, 'activo' => 0, 'UID' => 8, 'id_estado' => 8, 'fecha' => 1, 'codigo' => 1, 'tipo_pago' => 1, 'fecha_envio' => 1, 'total' => 1, 'moneda' => 1, 'estado_pol' => 1, 'codigo_respuesta_pol' => 1, 'respuesta' => 1, 'confirmacion' => 1); var $campos_listado = array('id_orden' => 0, 'codigo' => 1, 'UID' => 8, 'activo' => 0, 'id_estado' => 8, 'fecha' => 1);//, 'total' => 1 var $data_sources = array('id_orden' => 0, 'activo' => 0, 'UID' => array('tabla'=> 'registro', 'label' => 'email', 'id' => 'UID'), 'id_estado' => array('tabla'=> 'ordenes_estados', 'label' => 'nombre', 'id' => 'id_estado'), 'fecha' => 0, 'codigo' => 0, 'tipo_pago' => 0, 'fecha_envio' => 0, 'total' => 0, 'moneda' => 0, 'raw' => 0, 'respuesta' => 0, 'confirmacion' => 0, 'estado_pol' => 0, 'codigo_respuesta_pol' => 0); function getContenido($a) { if(session_name() != 'admin'){ require_once 'php/lib/not_found.exception.php'; throw new NotFoundException(); } switch ($a) { case "crear_orden": $this->crear_orden(); break; /*case "guardar_orden": $this->guardar_orden(); break;*/ case "despachar_orden": $this->despachar_orden(); break; case "editar_orden": $this->editar_orden(); break; case "nuevo_orden": $this->form(); break; case "publicar_orden": $this->activar_orden(); break; case "despublicar_orden": $this->desactivar_orden(); break; case "despachar": $this->despachar(); break; case "cerrar": $this->cerrar(); break; case "verificar": $this->verificar(); break; case '': $this->listado(); break; default: //require_once 'php/lib/not_found.exception.php'; throw new NotFoundException(); } } function listado(){ global $liveSite; $this->contentType = "html"; require_once 'lib/paginacion.class.php'; $campos = array(); $join = ''; foreach($this->campos_listado as $label => $tipo){ if($tipo == 8){ if(is_array($this->data_sources[$label])){ $t = $this->data_sources[$label]['tabla']; $l = $this->data_sources[$label]['label']; $id = $this->data_sources[$label]['id']; $join .= " LEFT JOIN ".$t." ON ".$t.'.'.$id." = ".$this->tabla.".".$label; $campos[] = $t.'.'.$l.' as '.$label; }else $campos[] = $this->tabla.".".$label; }else $campos[] = $this->tabla.".".$label; } $s = "SELECT ".implode(", ",$campos); $f = " FROM $this->tabla ".$join; $o = " ORDER BY id_orden DESC"; $w = ''; $b = ""; if(isset($_GET['filtro'])){ $value = Util::secureValue($_GET['filtro']); foreach($this->campos_form as $label => $tipo){ //$w = " WHERE $this->tabla.$id = '".$value."'"; $w .= ($w == '')?" WHERE $this->tabla.$label LIKE '%".$value."%'":" OR $this->tabla.$label LIKE '%".$value."%'"; } $b = '?filtro='.$value; } $paginador = new Paginacion($s, $f,$w, $o); $objetos = $paginador->fetch_object_list(); require_once 'html/ordenes_a.html.php'; OrdenesHTML::acciones(); $paginador->mostrarPaginacion($liveSite.'admin/ordenes/'.$b); OrdenesHTML::listado($objetos, $this->campos_listado); } function crear_orden(){ global $liveSite; $campos = array(); $values = array(); $uploads = array(); foreach($this->campos_form as $label => $tipo){ if($label == 'id_orden') continue; if($tipo == 7){ $uploads[] = $label; }else{ $campos[] = $label; $values[] = "'".Util::secureValue($_POST[$label])."'"; } } $sql = "INSERT INTO $this->tabla (".implode(', ', $campos )." ) VALUES ( ".implode(', ', $values )." )"; $result = Util::query($sql);; $id_creado = mysql_insert_id(); foreach($uploads as $u){ if(isset($_FILES["$u"]['tmp_name']) && strlen($_FILES["$u"]['tmp_name']) > 0){ $s = Util::guardar_archivo($_FILES["$u"]['tmp_name'], 'imagenes/ordenes/'.$id_creado.'.jpg'); $sql = "UPDATE $this->tabla SET $u = '".$id_creado.".jpg' WHERE id_orden = '".$id_creado."' LIMIT 1"; $result = Util::query($sql);; } } $this->redirect_listado(); } function editar_orden(){ require_once 'html/ordenes_a.html.php'; require_once 'lib/control.class.php'; require_once 'lib/orden.class.php'; $id = Util::secureValue($_GET['id_orden']); $campos = array(); $tipos = array(); foreach($this->campos_form as $label => $tipo){ $campos[] = 'o.'.$label; $tipos[] = $tipo; } $sql = "SELECT ".implode(', ', $campos).", o.raw, o.codigo_respuesta_pol, o.estado_pol, e.nombre estado, ep.mensaje msj_estado_pol, cp.mensaje respuesta_pol FROM $this->tabla o LEFT JOIN ordenes_estados e ON e.id_estado = o.id_estado LEFT JOIN ordenes_estados_pol ep ON ep.codigo = o.estado_pol LEFT JOIN ordenes_codigos_pol cp ON cp.codigo = o.codigo_respuesta_pol WHERE id_orden = '$id'"; $obj = Util::sql2obj($sql); if(!$obj){ require_once 'php/lib/not_found.exception.php'; throw new NotFoundException(); } $or = unserialize($obj->raw); $obj->orden = $or; $sql_user = "SELECT env_ciudad, env_direccion, env_telefono, fac_documento documento, nombre, apellidos, email FROM registro WHERE UID = '".$obj->UID."' LIMIT 1"; $user = Util::sql2obj($sql_user); $this->contentType = "html"; OrdenesHTML::acciones(); OrdenesHTML::form($obj, $user); } function despachar(){ global $liveSite; $id_orden = Util::secureValue($_GET['id']); $sql = "UPDATE $this->tabla SET id_estado = 4 WHERE id_orden = '".$id_orden."' LIMIT 1"; $result = Util::query($sql); echo "<script>window.location.href = '".$liveSite."admin/ordenes/?a_=editar_orden&id_orden=$id_orden';</script>"; } function cerrar(){ global $liveSite; $id_orden = Util::secureValue($_GET['id']); $sql = "UPDATE $this->tabla SET id_estado = 5 WHERE id_orden = '".$id_orden."' LIMIT 1"; $result = Util::query($sql); echo "<script>window.location.href = '".$liveSite."admin/ordenes/?a_=editar_orden&id_orden=$id_orden';</script>"; } function guardar_orden(){ global $liveSite; $id_orden = Util::secureValue($_POST['id_orden']); $campos = array(); $uploads = array(); foreach($this->campos_form as $label => $tipo){ if($label == 'id_orden') continue; if($tipo == 7){ $uploads[] = $label; }else $campos[] = $label." = '".Util::secureValue($_POST[$label])."'"; } $sql = "UPDATE $this->tabla SET ".implode(',', $campos )." WHERE id_orden = '".$id_orden."' LIMIT 1"; $result = Util::query($sql); foreach($uploads as $u){ if(isset($_FILES["$u"]['tmp_name']) && strlen($_FILES["$u"]['tmp_name']) > 0){ $s = Util::guardar_archivo($_FILES["$u"]['tmp_name'], 'imagenes/ordenes/'.$id_orden.'.jpg'); $sql = "UPDATE $this->tabla SET $u = '".$id_orden.".jpg' WHERE id_orden = '".$id_orden."' LIMIT 1"; $result = Util::query($sql); } } $this->redirect_listado(); } function activar_orden(){ global $liveSite; $sql = "UPDATE $this->tabla SET activo = 1 WHERE id_orden = ".Util::secureValue($_GET['id_orden']); $result = Util::query($sql); $this->redirect_listado(); } function desactivar_orden(){ global $liveSite; $sql = "UPDATE $this->tabla SET activo = 0 WHERE id_orden = ".Util::secureValue($_GET['id_orden']); $result = Util::query($sql); $this->redirect_listado(); } function verificar(){ global $liveSite; global $id_pagos, $web_service_url; $orden = Util::sql2obj("SELECT * FROM ordenes WHERE id_orden = '".Util::secureValue($_GET['id'])."'"); if(!is_object($orden)){ throw new NotFoundException(); return; } $parametros=array(); //parametros de la llamada $parametros['IdComercioElectronico']= $id_pagos;; $parametros['Factura']= $orden->codigo; try { $x = @new SoapClient($web_service_url,array("exceptions" => 1)); $result = $x->ConsultarTransaccion($parametros); $parts = explode(';', $result->ConsultarTransaccionResult); print_r($parts); $cod = intval($parts[0]); if($cod == 0){ Util::query("UPDATE ordenes SET id_estado = 3, confirmacion = '".$parts[1]."' WHERE codigo = '$orden->codigo'"); if($orden->estado_pol == 0){ $or = unserialize($orden->raw); $or->descargar(); } }else{ Util::query("UPDATE ordenes SET id_estado = 6, confirmacion = '".$parts[1]."' WHERE codigo = '$orden->codigo'"); } $_SESSION['msj'] = "<br /><h2>Verificada</h2><p>Orden verificada con éxito!</p>"; } catch (SoapFault $E) { $_SESSION['msj'] = "<br /><h2>Error</h2><p>Ha ocurrido un error contactando la plataforma de pagos, no se pudo verificar la orden en:<br /> [ <strong>".$web_service_url." </strong>] </p>"; //echo $E->faultstring; } echo "<script>window.location.href = '".$liveSite."admin/ordenes/?a_=editar_orden&id_orden=".$orden->id_orden."';</script>"; } function redirect_listado(){ if(isset($_REQUEST['next'])) echo "<script>window.location.href = '".$_REQUEST['next']."';</script>"; else if(isset($_SERVER['HTTP_REFERER'])) echo "<script>window.location.href = '".$_SERVER['HTTP_REFERER']."';</script>"; else echo "<script>window.location.href = '".$liveSite."admin/ordenes/';</script>"; } } ?><file_sep>/mobile/php/menu.php <?php class Menu{ var $contentType = ""; function getContenido($a = '') { switch ($a) { case "admin": $this->nav_admin(); break; default: $this->nav(); } } function nav_admin() { require_once("html/menu.html.php"); MenuHTML::nav_admin(); } function nav()//TODO: dinámico! { require_once("lib/util.class.php"); require_once("html/menu.html.php"); require_once 'lib/plugin.class.php'; global $lang_switch; MenuHTML::nav(); } } ?><file_sep>/mobile/php/html/not_found.html.php <?php class NotFoundHTML{ static function _404() { global $liveSite, $siteTitle; ?> <header> <div class="container"> <div class="row"> <br /> <div class="hero-unit white"> <h1>Not found <small>Error (404)</small></h1> <p> Al parecer est&aacute;s buscando algo que no existe, o ya no est&aacute; disponible. </p> <p> <a href="<?php echo $liveSite; ?>" title="<?php echo $siteTitle ?>" class="btn btn-primary btn-large">Regresa al inicio »</a></p> </div> </div> </div> </header> <div class="clear"></div> <?php } } ?><file_sep>/mobile/php/html/polls.html.php <?php class pollsHTML{ static function make_poll() { global $liveSite, $cw; require_once 'lib/plugin.class.php'; //Plugin::get_localized_link('contacto'); ?> <div class="curtain"> <img name="" src="<?php echo $liveSite; ?>imagenes/loading.gif" width="32" height="32" alt="Loading..." /> </div> <div class="container"> <section> <div class="row"> <h6 class="credits">Actual credits: 0</h6> <div class="progress progress-succes progress-striped active" style="margin-bottom: 9px;"> <div class="bar credit-bar" style="width: 0%"></div> </div> </div> </section> </div> <div> <div class="container"> <section> <div class="row"> <div class="span12"> <div class="hero-unit white"> <p class="enunciado">Mi red social favorita es:</p> </div> <hr /> </div> <div class="span12 opciones"> </div> </div> </section> </div> </div> <script> var refresh_srv = "../../web/crud.php?view=credits&action=getMyPoints"; var answer_srv = "../../web/crud.php?view=consumer&action=votePoll";//&ans=123&poll=34 var poll_srv = "../../web/crud.php?view=consumer&action=getJSONPoll"; !function ($) { function hidecurt(){ $('.curtain').hide(); } function showcurt(){ $('.curtain').show(); } function refresh_credit(){ $.ajax({ type: "POST", url: refresh_srv, dataType: "json", data: { } }).done(function( data ) { if(data.code == 200){ //ok $('.credits').empty(); $('.credits').html("Tu crédito actual :"+data.data); $('.credit-bar').css('width',(data.data*100/20)+"%"); load_poll(); }else{ alert("Uppss something terrible happened :/"); } }); } function answer(e){ var b = $('#'+e.target.id); responder(b.data('poll'), e.target.id, b.data('answer')); //alert(e.target.id+" "+b.data('answer')); } function responder(id_poll, id_answer, answer){ showcurt(); $('.enunciado').empty(); $('.opciones').empty(); $.ajax({ type: "POST", url: answer_srv+"&ans="+id_answer+"&poll="+id_poll, dataType: "json", data: { } }).done(function( data ) { if(data.code == 200){ //ok refresh_credit(); }else{ alert("Uppss something terrible happened :/"); } }); } function load_poll(){ showcurt(); $.getJSON(poll_srv,function(res) { if(res.code == 200){ //OK if(res.data.options != undefined && res.data.options.length > 0){ $('.enunciado').empty(); $('.opciones').empty(); items = new Array(); $('.enunciado').html(res.data.poll.question); $.each(res.data.options, function(i,o) { items.push("<li ><button id='"+o.id+"' class='btn btn-primary opcion' data-poll='"+res.data.poll.id+"' data-answer='"+o.answer+"'>"+o.answer+"</button></li>"); }); $('<ul/>', { 'class': 'options-list', html: items.join('') }).appendTo('.opciones'); $('body').on('click', '.btn.opcion', answer); hidecurt(); }else{ $('.enunciado').html("No more polls at this time for you, keep having fun and come back soon!"); hidecurt(); } } }); } load_poll(); }(window.jQuery) </script> <?php } static function about() { global $liveSite, $cw; require_once 'lib/plugin.class.php'; //Plugin::get_localized_link('contacto'); ?> <div> <div class="container"> <section> <div class="row"> <div class="span12"> <div class="hero-unit white"> <h1>PollBag</h1> <p class="enunciado">Mi red social favorita es:</p> </div> <hr /> </div> <div class="span12 opciones"> </div> </div> </section> </div> </div> <?php } } ?><file_sep>/mobile/php/not_found.php <?php class NotFound{ var $contentType = "html"; function getContenido() { $this->_404(); } function _404(){ global $pathway; $pathway->add_last_branch("Error 404"); require_once 'php/lib/not_found.exception.php'; new NotFoundException(); require_once 'html/not_found.html.php'; NotFoundHTML::_404(); } } ?><file_sep>/web/model/generated/BaseUserPoll.php <?php // Connection Component Binding /** * BaseUserPoll * * This class has been auto-generated by the Doctrine ORM Framework * * @property integer $user_id * @property integer $poll_id * @property float $earned * * @package ##PACKAGE## * @subpackage ##SUBPACKAGE## * @author ##NAME## <##EMAIL##> * @version SVN: $Id: Builder.php 6820 2009-11-30 17:27:49Z jwage $ */ abstract class BaseUserPoll extends Doctrine_Record { public function setTableDefinition() { $this->setTableName('user_poll'); $this->hasColumn('id', 'integer', 8, array( 'type' => 'integer', 'length' => 8, 'fixed' => false, 'unsigned' => false, 'primary' => false, 'notnull' => true, 'autoincrement' => true, )); $this->hasColumn('user_id', 'integer', 8, array( 'type' => 'integer', 'length' => 8, 'fixed' => false, 'unsigned' => false, 'primary' => false, 'notnull' => true, 'autoincrement' => false, )); $this->hasColumn('poll_id', 'integer', 8, array( 'type' => 'integer', 'length' => 8, 'fixed' => false, 'unsigned' => false, 'primary' => false, 'notnull' => true, 'autoincrement' => false, )); $this->hasColumn('earned', 'integer', 20, array( 'type' => 'float', 'length' => 20, 'fixed' => false, 'unsigned' => false, 'primary' => false, 'notnull' => false, 'autoincrement' => false, )); $this->hasColumn('createdate', 'timestamp', null, array( 'type' => 'timestamp', 'fixed' => false, 'unsigned' => false, 'primary' => false, 'notnull' => false, 'autoincrement' => false, )); } public function setUp() { parent::setUp(); $this->hasOne('User', array('local' => 'user_id','foreign' => 'id')); $this->hasOne('Poll', array('local' => 'poll_id','foreign' => 'id')); } }<file_sep>/mobile/php/config.php <?php //GLOBAL// $debug = true; $proyect = "pollbag";//EN MINUSCULAS(LOWERCASE) $liveSites = array("http://poopub.com/mobile/", "http://localhost/pollbag/mobile/", "http://localhost/pollbag/mobile/"); $site_type = 1; // 1 => html , 2 => gaia //SEO $siteName = "Pollbag"; $siteTitle = utf8_encode("Pollbag"); $siteDescription = utf8_encode("Your ocio time is gold, go for it!"); $siteKeywords = utf8_encode(""); //$GA = "UA-18887116-1"; //Codigo analitycs!! $GA = ""; //MAILING// $emailFrom = "<EMAIL>"; $nombreFrom = utf8_encode("Pollbag"); $subjectRegistro = utf8_encode("Bienvenido a $proyect"); $subjectContrasegna = utf8_encode("Tu contraseņa a $proyect"); //FB $appID = '114354315304121'; $appapikey = 'ddaec8681af79d79326aefb11656ac84'; $appsecret = ''; $ogDescription = $siteDescription; $ogTitle = $siteTitle; $ogImage = "imagenes/logo.png"; //DB// $hostname = "localhost"; $username = "root"; $pass = "<PASSWORD>"; //$pass = "<PASSWORD>"; $dbname = "pollbag"; //TPL $def_tpl = "plantilla.php"; //SEC $session_limit = 1000; $ssl = false; ?><file_sep>/mobile/php/html/paginacion.html.php <?php class PaginacionHTML{ static function paginacion($pagina, $total_paginas, $total_registros, $paginasMostrar, $base) { global $liveSite; $joint = (strpos($base,"?")===false)?"?":"&"; ?> <div class="grid_12"> <small><strong>P&aacute;gina <?php echo $pagina; ?> de <?php echo $total_paginas ?> / Registros total <?php echo $total_registros; ?></strong></small> <br /> <table width="80%" border="0" cellspacing="0" cellpadding="0"> <tr> <td><? if(isset ($_GET["pagina"]) && $_GET["pagina"]!=0){ $pagina = $_GET["pagina"]; }else{ $pagina = 1; } $i=1; $limiteInf = 1; $limiteSup = $limiteInf + ($paginasMostrar-1); $bloque = ceil($pagina/$paginasMostrar); $paginadesde = ($bloque*$paginasMostrar) - ($paginasMostrar-1); $paginahasta = ($bloque*$paginasMostrar); if($paginahasta > $total_paginas) $paginahasta = $total_paginas; if ($total_paginas > 1){?> <table align="center" cellpadding="5" cellspacing="2"> <tr> <?php if ($pagina > $paginasMostrar){?> <td class="anterior"> <a href="<?php echo $base.$joint; ?>pagina=<?php echo $paginadesde-1;?>" onfocus="this.blur()" > ... </a>&nbsp;&nbsp; </td> <?php } if ($pagina > 1){?> <td class="anterior"> <a href="<?php echo $base.$joint; ?>pagina=<?php echo $pagina-1;?>" class="paginacion">&lt;</a>&nbsp;&nbsp; </td> <?php } ?> <td> <?php for ($i=$paginadesde;$i<=$paginahasta;$i++) { ?> <a href="<?php echo $base.$joint; ?>pagina=<?php echo $i; ?>" onfocus="this.blur()" class="paginacion <?php if ($pagina == $i) echo "paginacion_activo"; else echo "paginacion_inactivo"; ?>"> <?php echo $i;?> </a>&nbsp;&nbsp; <?php } ?> </td> <?php if ( $pagina < $total_paginas){?> <td class="anterior"> <a href="<?php echo $base.$joint; ?>pagina=<?php echo $pagina+1;?>" onfocus="this.blur()" class="paginacion"> &gt; </a> </td> <?php } if ( $paginahasta < $total_paginas){?> <td class="anterior"> &nbsp;&nbsp; <a href="<?php echo $base.$joint; ?>pagina=<?php echo $paginahasta+1;?>" onfocus="this.blur()" > ... </a> </td> <?php } ?> </tr> </table> <?php }else{ ?> <table align="center"> <tr> <td> <span class="buscar_paginacion"><?php if ($total_paginas ==1){echo $total_paginas;} ?> </span> </td> </tr> </table> <?php } ?> </td> </tr> </table> <br /> </div> <?php } static function publicPaginacion($pagina, $total_paginas, $total_registros, $paginasMostrar, $base, $order_by,$registros_x_pagina, $base_x_pagina) { global $liveSite; $joint = (strpos($base,"?")===false)?"?":"&"; ?> <div class="paginas"> <div class="order_by"> <?php if($order_by){?> Ordernar por <select name="order" onchange="set_order(this)"> <option value="1" <?php if(intval($_COOKIE['order_by'])==1){?> selected="selected"<?php }?>>A-Z</option> <option value="2" <?php if(intval($_COOKIE['order_by'])==2){?> selected="selected"<?php }?>>$ - $$$</option> <option value="3" <?php if(intval($_COOKIE['order_by'])==3){?> selected="selected"<?php }?>>$$$ - $</option> </select> <script type="text/javascript"> if(set_order == undefined){ var set_order = function(e){ document.cookie = 'order_by='+(e.options[e.selectedIndex].value); window.top.location.href = '<?php echo $base ?>'; } } </script> <?php }else{ ?> &nbsp; <?php } ?> </div> <div class="por_pag"> No. por pag <select name="por_pag" onchange="set_x_page(this)"> <?php for($i = $base_x_pagina; $i < ($base_x_pagina * 5); $i+=$base_x_pagina){?> <option value="<?php echo $i; ?>" <?php if(intval($registros_x_pagina)==$i){?> selected="selected"<?php }?>><?php echo $i; ?></option> <?php } ?> </select> <script type="text/javascript"> if(set_x_page == undefined){ var set_x_page = function(e){ document.cookie = 'registros_x_pagina='+(e.options[e.selectedIndex].value); window.top.location.href = '<?php echo $base ?>'; } } </script> </div> <div class="links"> <div class="numbers"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td><? if(isset ($_GET["pagina"]) && $_GET["pagina"]!=0){ $pagina = $_GET["pagina"]; }else{ $pagina = 1; } $i=1; $limiteInf = 1; $limiteSup = $limiteInf + ($paginasMostrar-1); $bloque = ceil($pagina/$paginasMostrar); $paginadesde = ($bloque*$paginasMostrar) - ($paginasMostrar-1); $paginahasta = ($bloque*$paginasMostrar); if($paginahasta > $total_paginas) $paginahasta = $total_paginas; if ($total_paginas > 1){?> <table align="center" cellpadding="5" cellspacing="2"> <tr> <?php if ($pagina > $paginasMostrar){?> <td class="anterior"> <a href="<?php echo $base.$joint; ?>pagina=<?php echo $paginadesde-1;?>" onfocus="this.blur()" > ... </a>&nbsp; </td> <?php } if ($pagina > 1){?> <td class="anterior"> <a href="<?php echo $base.$joint; ?>pagina=<?php echo $pagina-1;?>" class="paginacion">&lt;</a>&nbsp; </td> <?php } ?> <td> <?php for ($i=$paginadesde;$i<=$paginahasta;$i++){ ?><a href="<?php echo $base.$joint; ?>pagina=<?php echo $i; ?>" onfocus="this.blur()" class="paginacion <?php if ($pagina == $i) echo "paginacion_activo"; else echo "paginacion_inactivo"; ?>"><?php echo $i;?></a><?php }?> </td> <?php if ( $pagina < $total_paginas){?> <td class="anterior"> <a href="<?php echo $base.$joint; ?>pagina=<?php echo $pagina+1;?>" onfocus="this.blur()" class="paginacion"> &gt; </a> </td> <?php } if ( $paginahasta < $total_paginas){?> <td class="anterior"> &nbsp; <a href="<?php echo $base.$joint; ?>pagina=<?php echo $paginahasta+1;?>" onfocus="this.blur()" > ... </a> </td> <?php } ?> </tr> </table> <?php }else{ ?> <table align="center"> <tr> <td> <span class="paginacion paginacion_activo"><?php if ($total_paginas ==1){echo $total_paginas;} ?> </span> </td> </tr> </table> <?php } ?> </td> </tr> </table> </div> <div class="pags"> <?php echo ($pagina*$registros_x_pagina)-$registros_x_pagina+1; ?>&minus;<?php echo $pagina*$registros_x_pagina; ?> de <?php echo $total_registros; ?> </div> <div class="clear"></div> </div> </div> <div class="clear"></div> <?php } } ?><file_sep>/web/view/poll/insert_polls.php <script> var aux = 3; $(document).ready(function(){ $("#mascampos").generaNuevosCampos("Option", "option", aux); }); jQuery.fn.generaNuevosCampos = function(etiqueta, nombreCampo, indice){ $(this).each(function(){ elem = $(this); elem.data("etiqueta",etiqueta); elem.data("nombreCampo",nombreCampo); elem.data("indice",indice); elem.click(function(e){ e.preventDefault(); elem = $(this); etiqueta = elem.data("etiqueta"); nombreCampo = elem.data("nombreCampo"); indice = elem.data("indice"); texto_insertar = '<p id = "option-'+indice+'">' + etiqueta + ' ' + aux + ':<br><input type="text" name="options[]" /> <a href="#" onClick="deleteElement(\'option-'+indice+'\')">Delete</a></p>'; indice ++; aux ++; elem.data("indice",indice); nuevo_campo = $(texto_insertar); elem.before(nuevo_campo); }); }); return this; } function deleteElement(elemento){ $("#"+elemento).remove(); aux --; } </script> <div id="main-content"> <div class="alert-message error" id="alert-message" style="display:none;"> <p id="standardError">Best check yo self, you’re not looking too good.</p> </div> <form action="<?php echo $GLOBALS['baseURL'];?>crud.php" id="theform" method="post" > <input name="view" type="hidden" value="insert_polls"/> <input name="action" type="hidden" value="insertPoll" /> <fieldset id="poll-content"> <legend>Create Poll</legend> <div class="clearfix"> <label for="user">Min Age: </label> <div class="input"> <input name="min-age" id="poll-min-age" type="text" title="Min Age" /> <strong class="error" id="countryerror"></strong> </div> </div> <div class="clearfix"> <label for="user">Max Age: </label> <div class="input"> <input name="max-age" id="poll-max-age" type="text" title="Max Age" /> <strong class="error" id="countryerror"></strong> </div> </div> <div class="clearfix"> <label for="user">Gender: </label> <div class="input"> <select name="gender" id="poll-gender"> <option value="m">Males</option> <option value="f">Females</option> <option value="b">Both</option> </select> <strong class="error" id="countryerror"></strong> </div> </div> <div class="clearfix"> <label for="user">Country: </label> <div class="input"> <select name="country" id="poll-country"> <option value="1">Venezuela</option> </select> <strong class="error" id="countryerror"></strong> </div> </div> <div class="clearfix"> <label for="user">State: </label> <div class="input"> <select name="state" id="poll-state"> <option value="1">Miranda</option> </select> <strong class="error" id="stateerror"></strong> </div> </div> <div class="clearfix"> <label for="user">Munincipality: </label> <div class="input"> <select name="munincipality" id="poll-munincipality"> <option value="1">Sucre</option> </select> <strong class="error" id="munincipalityerror"></strong> </div> </div> <div class="clearfix"> <label for="user">Zone: </label> <div class="input"> <select name="parish" id="poll-parish"> <option value="1">Petare</option> </select> <strong class="error" id="parisherror"></strong> </div> </div> <div class="clearfix"> <label for="user">Postal Code: </label> <div class="input"> <input name="postal_code" id="poll-postal-code" type="text" title="Postal Code" /> <strong class="error" id="postalcodeError"></strong> </div> </div> <div class="clearfix"> <label for="user">Question: </label> <div class="input"> <input name="poll-question" id="poll-question" type="text" title="Question" /> <strong class="error" id="userError"></strong> </div> </div> <div class="clearfix"> <label>Option 1: </label> <div class="input"> <input id="question-option" type='text' name='options[]' /> <strong class="error" id="userError"></strong> </div> </div> <div class="clearfix"> <label>Option 2: </label> <div class="input"> <input id="question-option" type='text' name='options[]' /> <strong class="error" id="userError"></strong> </div> </div> <a href="#" id="mascampos">Agregar opci&oacute;n</a> <div class="actions"> <input name="" type="submit" class="btn medium blue" value="Crear" /> </div> </form> </div><file_sep>/mobile/index.php <?php date_default_timezone_set('America/Bogota'); $dir = getcwd(); $dirphp = $dir.DIRECTORY_SEPARATOR."php"; $dirphp .= PATH_SEPARATOR.$dir.DIRECTORY_SEPARATOR."php".DIRECTORY_SEPARATOR."lib"; //$dirphp .= '..'.PATH_SEPARATOR."web".PATH_SEPARATOR."phputils"; set_include_path(get_include_path() . PATH_SEPARATOR . $dir . PATH_SEPARATOR . $dirphp); require_once("php/config.php"); require_once("php/common.php"); require_once("php/mainconn.php"); session_name($proyect); session_start(); //session_destroy(); die(); if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") $ruta = "http://".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; else $ruta = "https://".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; $redirect = true; foreach($liveSites as $host){ if(strpos($ruta, $host) === 0){ $liveSite = $host; $redirect = false; break; } } if($redirect){ header($_SERVER['SERVER_PROTOCOL'].' 301 Moved Permanently'); header("Location: $liveSites[0]"); exit; } Loger::log("<hr />Running from: ".$liveSite); Loger::log("<hr />Cookie: ".print_r($_COOKIE, true)); Loger::log("<hr />Request: ".print_r($_REQUEST, true)); Loger::log("<hr />Session (".session_name()."): ".print_r($_SESSION, true)); $lang_switch = new LangSwitch(); $cw = new CopyWriter(); $pathway = new Pathway(); $plug = new Plugin(); if (isset ($_POST["opcion"])){ $seccion = mysql_real_escape_string($_POST["opcion"]); $accion = $_POST["a"]; }else if (isset ($_GET["opcion"])){ $seccion = mysql_real_escape_string($_GET["opcion"]); $accion = $_GET["a"]; }else {//Rewrite URL Loger::log("<hr />Inicia Rewrite URL..."); $params = $_SERVER["REQUEST_URI"]; Loger::log("<hr />$ _SERVER[REQUEST_URI]: ".$_SERVER["REQUEST_URI"]); $params = str_replace("?".$_SERVER['QUERY_STRING'], "", $params); Loger::log("<hr />Params: $params"); $last = strrpos($params, '/') + 1; $chars = strlen($params); if($last != $chars){ if(strlen($_SERVER['QUERY_STRING'])) $qs = '?'.$_SERVER['QUERY_STRING']; else $qs = ''; header($_SERVER['SERVER_PROTOCOL'].' 301 Moved Permanently'); header("Location: ".$params .'/'.$qs); exit; } $deepest_folder = explode("/", $liveSite); Loger::log("<hr />Deepesth folder: $deepest_folder <pre>".print_r($deepest_folder, true)."</pre>"); $deepest_folder = $deepest_folder[(count($deepest_folder)-2)];//-2 : explode siempre deja un elemento final vacio Loger::log("<hr />Deepesth folder: $deepest_folder"); if( strpos($_SERVER["REQUEST_URI"], "$deepest_folder") ){// ! in domain root Loger::log("<hr />No en la raiz"); Loger::log("<hr />$ _SERVER[REQUEST_URI]: ".$_SERVER["REQUEST_URI"]); $params = substr($params, strpos($params, "$deepest_folder")+strlen($deepest_folder)+1);// +1 remueve el slash final del liveSite Loger::log("<hr />Params: $params"); }else{//REVISAR..... Loger::log("<hr />Removiendo slash.. $params"); $params = substr($params, 1,strlen($params));//TODO: quitar solo los slash // Loger::log("<hr />Params: $params"); } if(strlen($params) > 0){//TODO: aquí detecto si entro al idioma /es $params = explode("/", $params); Loger::log("<hr />Params: $params"); if($params[0] == 'es' && count($params) > 2){ $_COOKIE['lang'] = 'es'; $seccion = $params[1]; $accion = $params[2]; }else if($params[0] == 'es' && count($params) == 2){ $_COOKIE['lang'] = 'es'; $seccion = "inicio"; $accion = ""; }else{ $_COOKIE['lang'] = 'en'; $seccion = $params[0]; $accion = $params[1]; } }else{ $seccion = "inicio"; $accion = ''; } $lang = isset($_COOKIE['lang'])?Util::secureValue($_COOKIE['lang']):'es'; $lang_switch->set_lang($lang); } $plugin = $plug->get_plugin_by_alias($seccion); Loger::log("<hr />Seccion by alias: $seccion - Accion: $accion .."); Loger::log("<hr />Empieza LOG "); try{ ob_start(); $plugin->getContenido($accion); }catch(NotFoundException $e){ header($_SERVER['SERVER_PROTOCOL'].' 404 Not found'); $plugin = new NotFound(); $plugin->getContenido(); }catch(Exception $e){ die("<h1>Error interno.</h1>"); } $contenido = ob_get_contents(); ob_end_clean(); ob_start(); if($plugin->contentType == "html") { if($site_type == 1) require($def_tpl); else require("php/plantilla_gaia.php"); }else { echo $contenido; } ob_flush(); exit; ?> <file_sep>/mobile/php/registro.php <?php class Registro{ var $contentType = ""; function getContenido($a) { switch ($a) { case "registrar": $this->check_ssl(); $this->registrar(); break; case "guardar": $this->check_ssl(); $this->guardar(); break; case "terminos": $this->terminos(); break; case "privacidad": $this->privacidad(); break; case "activar": $this->activar(); break; case "activado": $this->activado(); break; case "fin_registro": $this->registrado(); break; default: $this->check_ssl(); $this->form(); } } function check_ssl(){ global $ssl; if($ssl) if ($_SERVER['HTTPS'] != "on") { $url = "https://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; header("Location: $url"); exit; } } function terminos(){ global $pathway, $liveSite; $pathway->add_branch('Registro', $liveSite."registro/", 'Registro'); $pathway->add_last_branch('T&eacute;rminos'); global $siteTitle, $siteDescription, $ogDescription, $ogTitle, $ogImage; $siteTitle = "Términos" . ' - '. $siteTitle; $ogTitle = "Términos"; $siteDescription = $ogDescription = 'Conoce los términos y condiciones de nuestra tienda on-line de ropa para hombre'; require_once 'lib/util.class.php'; $terms = Util::sql2obj("SELECT * FROM contenidos WHERE id_contenido = '14'"); $this->contentType = "html"; require_once("html/registro.html.php"); RegistroHTML::terminos($terms); } function privacidad(){ global $pathway, $liveSite; $pathway->add_branch('Registro', $liveSite."registro/", 'Registro'); $pathway->add_last_branch('Privacidad'); global $siteTitle, $siteDescription, $ogDescription, $ogTitle, $ogImage; $siteTitle = "Privacidad" . ' - '. $siteTitle; $ogTitle = "Privacidad"; $siteDescription = $ogDescription = 'Conoce nuestra política de privacidad, para enterarte del manejo que le damos a tu información personal'; $priv = Util::sql2obj("SELECT * FROM contenidos WHERE id_contenido = '15'"); $this->contentType = "html"; require_once("html/registro.html.php"); RegistroHTML::privacidad($priv); } function form() { header("Location: /"); return; } function mi_cuenta() { global $pathway; $pathway->add_last_branch('Mi cuenta'); require_once 'lib/util.class.php'; global $siteTitle, $siteDescription, $ogDescription, $ogTitle, $ogImage; $siteTitle = "Mi cuenta"; $ogTitle = "Mi cuenta"; $siteDescription = $ogDescription = 'Datos de tu cuenta'; $user = Util::sql2obj("SELECT * FROM registro WHERE UID = '".$_SESSION['public_UID']."'"); $this->contentType = "html"; require_once("html/registro.html.php"); RegistroHTML::mi_cuenta($user); } function registrado($uid) { $sql = "SELECT uid FROM user_profile WHERE uid = '$uid'"; $result = Util::query($sql); if(mysql_num_rows($result) > 0) return true; else return false; } function registrar(){ global $liveSite, $emailFrom, $nombreFrom, $subjectRegistro; foreach($_POST as $k => $v) { if(!is_array($v)) eval("$".mysql_real_escape_string($k)."='".(mysql_real_escape_string($v))."';"); else eval("$".mysql_real_escape_string($k)."='".(mysql_real_escape_string(json_encode($v)))."';"); } $birthday_date = isset($birthday_date)?$birthday_date:""; $birthday = isset($birthday)?$birthday:""; $hometown_location = isset($hometown_location)?$hometown_location:""; $pic = isset($pic)?$pic:""; if(! $this->registrado(mysql_real_escape_string($id))) { $sql = "INSERT INTO `user` ( `id` , `provider` , `oauth_id` , `email` , `password` , `locationid` , `roleid` , `status` , `validation_code` , `createdate` ) VALUES ( NULL , 'facebook', '$id', '$email', NULL , '1', '2', 'valid', '', NOW() );"; $result = Util::query($sql); $creado = mysql_insert_id(); //ALTER TABLE `user_profile` ADD `oauth_id` VARCHAR( 255 ) NOT NULL AFTER `uid` ; $sql = "INSERT INTO user_profile (`uid`, `email`, `first_name`, `last_name`, `timezone`, `birthday_date`, `birthday`, `sex`, `hometown_location`, `pic`, `fecha_connect`) VALUES ('$creado', '$email', '$first_name', '$last_name', '$timezone', '$birthday_date', '$birthday', '$gender', '$hometown_location', '$pic', NOW())"; $result = Util::query($sql); $this->login($id); }else{ $this->login($id); } } function login($id){ global $liveSite; $_SESSION['user'] = new CocoasUser(); $_SESSION['user']->status = 'valid'; $_SESSION['user']->roleName = 'consumer'; $_SESSION['user']->id = $id; $_SESSION['user']->qr = $_SESSION['qr']; unset($_SESSION['qr']); echo "top.location.href = '".$liveSite."polls/';"; } function secureValue($theValue) { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); return $theValue; } } ?><file_sep>/mobile/php/common.php <?php require_once 'php/lib/util.class.php'; require_once('php/lib/loger.class.php'); require_once('php/lib/lang_switch.class.php'); require_once('php/lib/copy_writer.class.php'); require_once 'php/pathway.php'; require_once('php/lib/plugin.class.php'); require_once 'php/lib/not_found.exception.php'; require_once 'php/lib/no_disponible.exception.php'; require_once 'php/not_found.php'; require_once('../web/phputils/CocoasUser.class.php'); $gestor_errores = set_error_handler("tuer_avec_ellegance"); error_reporting(E_ALL); ini_set("display_errors", 0); register_shutdown_function('shutdownFunction'); function tuer_avec_ellegance($errno, $errstr, $errfile, $errline){ $seccion = ""; //die("$errno, $errstr, $errfile, $errline avec ellegance.."); global $debug; if($debug == true){ switch ($errno) { case E_USER_ERROR: Loger::log("<font color='#f33'><b>RUNTIME ERROR</b> [$errno] $errstr<br /></font>\n"); Loger::log(" Error fatal en la l&iacute;nea <strong>$errline</strong> en el archivo <strong>$errfile</strong>"); Loger::log(", PHP " . PHP_VERSION . " (" . PHP_OS ." EOL:".PHP_EOL. ")<br />\n"); Loger::log(print_r(debug_backtrace(),true)); case E_USER_WARNING: Loger::log("<font color='#f33'><b>Mi WARNING</b> [$errno] $errstr<br /></font>\n".print_r(debug_backtrace(),true)); Loger::log(" Error en la l&iacute;nea <strong>$errline</strong> en el archivo <strong>$errfile</strong>"); Loger::log(", PHP " . PHP_VERSION . " (" . PHP_OS ." EOL:".PHP_EOL. ")<br />\n"); break; case E_USER_NOTICE: Loger::log("<font color='#f33'><b>Mi NOTICE</b> [$errno] $errstr<br /></font>\n".print_r(debug_backtrace(),true)); Loger::log(" Error en la l&iacute;nea <strong>$errline</strong> en el archivo <strong>$errfile</strong>"); Loger::log(", PHP " . PHP_VERSION . " (" . PHP_OS." EOL:".PHP_EOL . ")<br />\n"); break; default: Loger::log("<font color='#f33'><b>RUNTIME ERROR</b> [$errno] $errstr<br /></font>\n"); Loger::log(" Error fatal en la l&iacute;nea <strong>$errline</strong> en el archivo <strong>$errfile</strong>"); Loger::log(", PHP " . PHP_VERSION . " (" . PHP_OS ." EOL:".PHP_EOL. ")<br />\n"); Loger::log(print_r(debug_backtrace(),true)); break; } } return false; } function shutDownFunction(){ $buffer = ob_get_length(); if($buffer != false && $buffer > 0) ob_end_clean(); global $debug,$liveSite; $error = error_get_last(); if ($error !== null){ if($debug == true){ Loger::log("<font color='#f33'><b>RUNTIME ERROR</b> ".print_r($error,true)."<br /></font>\n"); Loger::log(", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n"); //Loger::log(print_r(debug_backtrace(),true)); echo "<html><head><link href='".$liveSite."css/layout.css' type='text/css' rel='stylesheet'></head><body class='shut_down'> <div class='grid_10'> <div class='debug'><h2>LOG:</h2><pre>".Loger::$_log."</ pre> </div> </div> <div class='clear'></div> </body></html>"; }else{ header($_SERVER['SERVER_PROTOCOL'].' 500 Internal Server Error', true, 500); $contenido = "<h1>Oooopspss parece que algo anda mal por aqu&iacute;, nuestro equipo t&eacute;cnico ya est&aacute; en camino regresa en unos instantes.</h1>"; echo "<html><head><link href='".$liveSite."css/layout.css' type='text/css' rel='stylesheet'></head><body class='shut_down'> <div class='grid_10'> <div class='debug'>".$contenido." </div> </div> <div class='clear'></div> </body></html>"; } } } ?><file_sep>/mobile/php/lib/not_found.exception.php <?php class NotFoundException extends Exception { function NotFoundException(){ $this->code = 404; $this->message = "No se encuentra."; } } ?><file_sep>/mobile/assets/js/application.js // NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT // IT'S ALL JUST JUNK FOR OUR DOCS! // ++++++++++++++++++++++++++++++++++++++++++ !function ($) { $('.modal').hide(); }(window.jQuery) function obtenerDatos(){ var q_user_data = "SELECT email , first_name , first_name, middle_name, last_name, timezone, birthday_date, birthday, sex, hometown_location, pic FROM user WHERE uid = "+uid; var datos = api.fql_query(q_user_data,almacenarDatos); } function almacenarDatos(result, exception){ if(!result){ alert("Exception: "+exception); }else{ alert("send ajax to server: "+result); //getMovie().almacenarDatos(result, uid); obtenerAmigos(); } } <file_sep>/web/model/generated/BaseQRCode.php <?php /** * BaseUser * * This class has been auto-generated by the Doctrine ORM Framework * * @property integer $id * @property string $email * @property string $password * @property integer $location_id * @property integer $role_id * @property string $status * @property integer $validation_code * @property Location $Location * @property Role $Role * * @package ##PACKAGE## * @subpackage ##SUBPACKAGE## * @author ##NAME## <##EMAIL##> * @version SVN: $Id: Builder.php 6820 2009-11-30 17:27:49Z jwage $ */ abstract class BaseQRCode extends Doctrine_Record { public function setTableDefinition() { $this->setTableName('qrcode'); $this->hasColumn('id', 'integer', 8, array( 'type' => 'integer', 'fixed' => 0, 'unsigned' => false, 'primary' => true, 'autoincrement' => true, 'length' => '8', )); $this->hasColumn('location_name', 'string', 100, array( 'type' => 'string', 'fixed' => 0, 'unsigned' => false, 'primary' => false, 'notnull' => true, 'default' => null, 'autoincrement' => false, 'length' => '100', )); $this->hasColumn('url', 'string', 100, array( 'type' => 'string', 'fixed' => 0, 'unsigned' => false, 'primary' => false, 'notnull' => false, 'default' => null, 'autoincrement' => false, 'length' => '100', )); $this->hasColumn('big_url', 'string', 250, array( 'type' => 'string', 'fixed' => 0, 'unsigned' => false, 'primary' => false, 'notnull' => false, 'default' => null, 'autoincrement' => false, 'length' => '100', )); $this->hasColumn('bitly_hash', 'string', 100, array( 'type' => 'string', 'fixed' => 0, 'unsigned' => false, 'primary' => false, 'notnull' => false, 'default' => null, 'autoincrement' => false, 'length' => '100', )); $this->hasColumn('latitude', 'string', 100, array( 'type' => 'string', 'fixed' => 0, 'unsigned' => false, 'primary' => false, 'notnull' => true, 'autoincrement' => false, 'length' => '100', )); $this->hasColumn('longitude', 'string', 100, array( 'type' => 'string', 'fixed' => 0, 'unsigned' => false, 'primary' => false, 'notnull' => true, 'autoincrement' => false, 'length' => '100', )); $this->hasColumn('location_type', 'enum', 13, array( 'type' => 'enum', 'length' => 13, 'fixed' => false, 'unsigned' => false, 'values' => array( 0 => 'otra', 1 => 'oficina', 2 => 'centro_comercial', 3 => 'universidad', 4 => 'bomba' ), 'primary' => false, 'default' => 'no_definido', 'notnull' => true, 'autoincrement' => false, )); $this->hasColumn('type', 'enum', 13, array( 'type' => 'enum', 'length' => 13, 'fixed' => false, 'unsigned' => false, 'values' => array( 0 => 'mixto', 1 => 'mujer', 2 => 'hombre' ), 'primary' => false, 'default' => 'no_definido', 'notnull' => true, 'autoincrement' => false, )); $this->hasColumn('instalation_date', 'timestamp', null, array( 'type' => 'timestamp', 'fixed' => false, 'unsigned' => false, 'primary' => false, 'notnull' => false, 'autoincrement' => false, )); $this->hasColumn('last_maintenance', 'timestamp', null, array( 'type' => 'timestamp', 'fixed' => false, 'unsigned' => false, 'primary' => false, 'notnull' => false, 'autoincrement' => false, )); $this->hasColumn('last_scan', 'timestamp', null, array( 'type' => 'timestamp', 'fixed' => false, 'unsigned' => false, 'primary' => false, 'notnull' => false, 'autoincrement' => false, )); $this->hasColumn('country', 'integer', 20, array( 'type' => 'integer', 'fixed' => 0, 'unsigned' => false, 'primary' => false, 'default' => '1', 'notnull' => true, 'autoincrement' => false, 'length' => '20', )); $this->hasColumn('state', 'integer', 20, array( 'type' => 'integer', 'fixed' => 0, 'unsigned' => false, 'primary' => false, 'default' => '1', 'notnull' => true, 'autoincrement' => false, 'length' => '20', )); $this->hasColumn('munincipality', 'integer', 20, array( 'type' => 'integer', 'fixed' => 0, 'unsigned' => false, 'primary' => false, 'default' => '1', 'notnull' => true, 'autoincrement' => false, 'length' => '20', )); $this->hasColumn('zone', 'integer', 20, array( 'type' => 'integer', 'fixed' => 0, 'unsigned' => false, 'primary' => false, 'default' => '1', 'notnull' => true, 'autoincrement' => false, 'length' => '20', )); } public function setUp() { parent::setUp(); $this->hasOne('Country', array( 'local' => 'country', 'foreign' => 'id')); $this->hasOne('State', array( 'local' => 'state', 'foreign' => 'id')); $this->hasOne('Munincipality', array( 'local' => 'munincipality', 'foreign' => 'id')); $this->hasOne('Zone', array( 'local' => 'zone', 'foreign' => 'id')); } }<file_sep>/mobile/php/lib/copy_writer.class.php <?php class CopyWriter{ function wr($id, $write = true){ require_once 'util.class.php'; global $lang_switch; $copie = Util::sql2obj('SELECT '.$lang_switch->actual_lang.' alias FROM site_lang_copies WHERE copie = "'.$id.'"'); if($write)echo $copie->alias; else return $copie->alias; } } ?><file_sep>/mobile/php/lib/paginacion.class.php <?php class Paginacion{ var $base_x_pagina = 10; var $registros_x_pagina = 10; var $links_numericos = 4; var $paginas_total = 0; var $registros_total = 0; var $sql = ""; var $inicio = 0; var $fin = 0; var $pagina = 1; var $show_order = true; function Paginacion($select, $from, $where = "", $group_by ="", $order_by ="" ) { require_once 'php/lib/util.class.php'; $this->sql = "$select $from $where $group_by $order_by"; if(isset($_GET['pagina'])){ $this->pagina = intval(Util::SecureValue($_GET['pagina'])); }else{ $this->pagina = 1; $this->inicio = 0; } } function fetch_object_list($registros = 0){ require_once 'lib/util.class.php'; $this->registros_x_pagina = ($registros == 0) ? $this->registros_x_pagina : $registros; $this->inicio = ($this->pagina-1) * $this->registros_x_pagina; $result = Util::query ($this->sql); $this->registros_total = (mysql_num_rows($result) > 0) ? mysql_num_rows($result) : 0; $this->paginas_total = ceil($this->registros_total/ $this->registros_x_pagina); $sql = $this->sql." LIMIT ".$this->inicio.", ".$this->registros_x_pagina; $result = Util::query($sql); $objs = array(); while($obj = mysql_fetch_object($result)){ $objs[] = $obj; } return $objs; } function mostrarPaginacion($base =""){ $base = ($base == "")? $this->base:$base; require_once 'php/html/paginacion.html.php'; PaginacionHTML::paginacion($this->pagina, $this->paginas_total, $this->registros_total, $this->links_numericos, $base); } function mostrarPaginacionPublic($base =""){ $base = ($base == "")? $this->base:$base; require_once 'php/html/paginacion.html.php'; PaginacionHTML::publicPaginacion($this->pagina, $this->paginas_total, $this->registros_total, $this->links_numericos, $base,$this->show_order,$this->registros_x_pagina, $this->base_x_pagina); } } ?><file_sep>/mobile/php/html/admin.html.php <?php class AdminHTML{ static function form_sql(){ global $liveSite; ?> <form action="<?php echo $liveSite; ?>admin/sql/" method="post"> <label for="sql">SQL</label> <textarea name="sql" id="sql" cols="45" rows="5"></textarea> <br /> <input type="checkbox" name="tablas" id="tablas" /> <label for="tablas">Tablas</label> <br /> <input type="submit" name="button" id="button" value="Submit" /> </form> <?php } static function home_admin($mensajes){ global $liveSite; ?> <div class="container_12"> <div class="grid_3 prefix_9"> <h2>Administrador</h2> </div> <hr class="grid_12" /> <div class="clear"></div> </div> <div class="container_12"> <div class="grid_5 prefix_1"> <ul class="inicio"> <li><a href="<?php echo $liveSite; ?>admin/banners/">Destacados</a></li> <li><a href="<?php echo $liveSite; ?>admin/contenidos/">Contenidos</a></li> <li><a href="<?php echo $liveSite; ?>admin/galeria/">Galeria fotos</a></li> <li><a href="<?php echo $liveSite; ?>admin/usuarios/">Usuarios</a></li> </ul> </div> <div class="grid_6"> &nbsp; </div> <div class="clear"></div> </div> <?php } static function login_form($msj = ""){ global $liveSite; ?> <div class="container_12"> <div class="grid_4 prefix_4 sufix_4"> <h2>Ingreso</h2> <h3><?php if($msj !== false){ echo $msj; } ?></h3> <form name="login_form" id="login_form" method="post" action="<?php echo $liveSite; ?>admin/login/"> <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td><label for="user">Usuario</label></td> <td><input type="text" class="validate['required','email']" name="user" id="user" /></td> </tr> <tr> <td><label for="password">Password</label></td> <td><input type="password" class="validate['required']" name="password" id="password" /></td> </tr> </table> <p> <input type="submit" value="Ingresar"> </p> </form> </div> <div class="clear"></div> </div> <script type="text/javascript"> window.addEvent('domready',function(){ var formcheck = new FormCheck('login_form', { trimValue: true, showErrors: 1, indicateErrors: 1 }); }); </script> <?php } } ?><file_sep>/web/view/qrcode/print.php <?php if($vars["qr"]) { ?> <h1 id="qrtitle">Earn money while losing time, straight from your phone!</h1> <div id="qr-container"> <img id="qr" src="<?php echo $vars["qr"]->url; ?>.qrcode" /> </div> <?php } else { ?> <h1>No se encontró el QR</h1> <?php } ?><file_sep>/mobile/php/lib/basepublichtmlobject.tpl.php <?php class {CLASS_NAME}HTML{ function inicio($objs){ ?> <h1>{nombre_seccion}</h1> <?php foreach($objs as $o){ ?> <pre><?phpprint_r($o); ?></pre> <hr /> <?php } } function detalle($obj){ ?> <h1>{nombre_seccion}</h1> <pre><?phpprint_r($obj); ?></pre> <div class="clear"></div> <?php } } ?><file_sep>/mobile/php/lib/data_source.class.php <?php class DataSource{ function DataSource($ds){ } } ?><file_sep>/mobile/plantilla.php <!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="<?php echo $lang_switch->actual_lang; ?>"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="<?php echo $lang_switch->actual_lang; ?>"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang="<?php echo $lang_switch->actual_lang; ?>"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="<?php echo $lang_switch->actual_lang; ?>"> <!--<![endif]--><head> <meta charset="utf-8"> <title><?php echo $siteTitle; ?></title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content="<NAME>"> <meta property="og:title" content="<?php echo $ogTitle; ?>"/> <meta property="og:type" content="product"/> <meta property="og:image" content="<?php echo $liveSite.$ogImage; ?>"/> <meta property="og:site_name" content="<?php echo $siteName; ?>"/> <meta property="og:description" content="<?php echo $ogDescription; ?>"/> <meta property="fb:admins" content="761087785"/> <meta http-equiv="description" name="description" content="<?php echo $siteDescription; ?>" /> <meta http-equiv="keywords" name="keywords" content="<?php echo $siteKeywords; ?>" /> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="<?php echo $liveSite; ?>assets/js/jquery.js"><\/script>')</script> <?php if(isset($GA) && $GA != ""){ ?> <!-- GA --> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', '<?php echo $GA;?>']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <?php } ?> <script> var liveSite = '<?php echo $liveSite; ?>'; </script> <!-- Le styles --> <link href='http://fonts.googleapis.com/css?family=Open+Sans|Bree+Serif' rel='stylesheet' type='text/css'> <link href="<?php echo $liveSite; ?>assets/css/bootstrap.css" rel="stylesheet" /> <link href="<?php echo $liveSite; ?>assets/css/bootstrap-responsive.css" rel="stylesheet" /> <link href="<?php echo $liveSite; ?>assets/css/app.css" rel="stylesheet" /> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- Le fav and touch icons --> <link rel="shortcut icon" href="<?php echo $liveSite; ?>imagenes/favicon.ico"> </head> <body> <?php require_once('php/menu.php'); $m = new Menu(); $m->getContenido(); ?> <!-- Comienza Contenido --> <?php echo $contenido; ?> <!-- Fin Contenido --> <footer> <div class="container"> <div class="row"> <div class="span12 footer"> <center> &copy; <strong>Pollbags </strong>2012 born in hackaton PulsoConf 2012 </center> </div> </div> </div> </footer> <!-- /footer --> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="<?php echo $liveSite; ?>assets/js/bootstrap-transition.js"></script> <script src="<?php echo $liveSite; ?>assets/js/bootstrap-alert.js"></script> <script src="<?php echo $liveSite; ?>assets/js/bootstrap-modal.js"></script> <script src="<?php echo $liveSite; ?>assets/js/bootstrap-dropdown.js"></script> <script src="<?php echo $liveSite; ?>assets/js/bootstrap-scrollspy.js"></script> <script src="<?php echo $liveSite; ?>assets/js/bootstrap-tab.js"></script> <script src="<?php echo $liveSite; ?>assets/js/bootstrap-tooltip.js"></script> <script src="<?php echo $liveSite; ?>assets/js/bootstrap-popover.js"></script> <script src="<?php echo $liveSite; ?>assets/js/bootstrap-button.js"></script> <script src="<?php echo $liveSite; ?>assets/js/bootstrap-collapse.js"></script> <script src="<?php echo $liveSite; ?>assets/js/bootstrap-carousel.js"></script> <script src="<?php echo $liveSite; ?>assets/js/bootstrap-typeahead.js"></script> <script src="<?php echo $liveSite; ?>assets/js/jquery.validate.min.js"></script> <script src="<?php echo $liveSite; ?>assets/js/application.js"></script> <?php if(isset($_SESSION['msj'])){ ?> <script> mostrarAlerta('<?php echo $_SESSION['msj']; ?>'); </script> <?php unset($_SESSION['msj']); }?> </body> </html> <file_sep>/web/delegate/PollDelegate.delegate.php <?php require_once('BaseDelegate.delegate.php'); class PollDelegate extends BaseDelegate { public function getMyPolls($validator) { $id = $_SESSION["user"]->id;//67; //TODO Change! $records = Doctrine::getTable("Poll")->findByid_user($id); return $records; } public function getPoll($validator) { $id = $validator->getOptionalVar("id"); //TODO Change! $records = Doctrine::getTable("Poll")->find($id); if ($records) return $records; else return ""; } public function getMyPollResults($validator) { $id = $validator->getOptionalVar("id"); if (is_numeric($id)){ $q = Doctrine_Manager::getInstance()->connection(); $result = $q->execute(" SELECT o.answer,count(a.id_option) as count FROM answer as a, poll_option as o where a.id_poll = ".$id." and o.id = a.id_option group by a.id_option having count >= 0 "); $results = $result->fetchAll(); return $results; } } public function GetPollOptions($validator) { //$id = $validator->getVar("idPoll"); $id = $validator->getVar("id"); if(empty($id))//Means that the user is creating a new poll return null; $records = Doctrine::getTable("PollOption")->findBy("id_poll",$id); return $records; } public function votePoll($validator) { header('Content-type: application/json'); $id = $_SESSION['user']->id; $option = $validator->getVar("ans"); $poll = $validator->getVar("poll"); $qrcode = $_SESSION['user']->qr; $q = Doctrine_Query::create() ->from('Answer a') ->where("a.identifier = '$id'") ->andWhere("a.id_poll = ".$poll); $rows = $q->execute(); if (count($rows)==0){ $entity2 = new Answer(); $entity2->type = "web"; $entity2->id_poll = $poll; $entity2->id_option = $option; $entity2->identifier = $id; $entity2->qr_id = $_SESSION["user"]->qr; $entity2->datetime = $today = date("Y-m-d H:m:s"); try { $entity2->save(); /*try{ //$pUser = new UserPoll(); //$pUser->user_id = $id; //$pUser->poll_id = $poll; //$pUser->earned = 1; //$pUser->save(); } catch(Exception $e){ $entity2->delete(); $result = array( "code" => 500, "message" => "Error procesing vote ".$e->getMessage() ); echo json_encode($result); return 'void'; }*/ $result = array( "code" => 200, "message" => "ok", "data" => $this->getNextPoll($qrcode) ); echo json_encode($result); } catch(Exception $e) { $result = array( "code" => 500, "message" => "Error procesing vote.".$e->getMessage() ); echo json_encode($result); } return 'void'; } else { $result = array( "code" => 500, "message" => "There is no poll with id ".$poll ); echo json_encode($result); return 'void'; } } function createPoll($validator) { //$nombre = $validator->getVar("Nombre"); $gender = $validator->getVar("gender"); $country = $validator->getVar("country"); $state = $validator->getVar("state"); $municipality = $validator->getVar("munincipality"); $zone = $validator->getVar("zone"); $code = $validator->getVar("postal_code"); $age_from = $validator->getVar("min-age"); $age_to = $validator->getVar("max-age"); $civil = $validator->getVar("civil-state"); //$education = $validator->getVar("education"); $amount = $validator->getVar("amount"); $question = $validator->getVar("questions"); $options = $_REQUEST["options"]; $user = $validator->getVar("user"); //$nombre = $validator->getVar(""); $poll = new Poll; $poll->question = $question; $poll->status = "active"; $poll->min_age = $age_from; $poll->max_age = $age_to; $poll->gender = $gender; $poll->Country = Doctrine::getTable('Country')->find($country); $poll->State = Doctrine::getTable('State')->find($state); $poll->Munincipality = Doctrine::getTable('Munincipality')->find($municipality); $poll->Zone = Doctrine::getTable('Zone')->find($zone); $poll->User = Doctrine::getTable('User')->find($user); $poll->postal_code = $code; $poll->createdate = date("Y-m-d"); //$poll->education_level = $poll->amount = $amount; $poll->save(); foreach ($options as $value) { $newPoll = new PollOption; $newPoll->answer = $value; $newPoll->id_poll = $poll->id; $newPoll->save(); } //echo "true"; return "producer"; } function setPollState($validator){ $pollGet = $validator->getVar("Poll"); $status = $validator->getVar("Status"); $poll = Doctrine::getTable('Poll')->find($pollGet); if($status == "true") { $poll->status = "active"; }else{ $poll->status = "deactive"; } $poll->save(); echo "true"; return "void"; } function getNextPoll($validator) { $userId = $_SESSION["user"]->id; $qrcode = $_SESSION["user"]->qr; $connection = Doctrine_Manager::getInstance()->connection(); $query = ' SELECT p.id FROM poll p, qrcode q, user_profile u WHERE p.id NOT IN (SELECT a.id_poll FROM answer AS a WHERE a.identifier = '.$userId.') AND p.status = \'active\' AND q.id = '.$qrcode.' AND (p.country_id IS NULL OR (p.country_id IS NOT NULL AND p.country_id=q.country)) AND (p.state_id IS NULL OR (p.state_id IS NOT NULL AND p.state_id=q.state)) AND (p.munincipality_id IS NULL OR (p.munincipality_id IS NOT NULL AND p.munincipality_id=q.munincipality)) AND (p.zone_id IS NULL OR (p.zone_id IS NOT NULL AND p.zone_id=q.zone)) AND (p.gender IS NULL OR (p.gender IS NOT NULL AND p.gender = u.sex)) '; $q = $connection->execute($query); $records = $q->fetchAll(); $total = count($records); if ($total>0) return $records[rand(0,$total-1)]["id"]; else return -1; } function getPollStatus($validator){ $poll = $validator->getVar("poll"); return $poll->status; } public function getJSONPoll($validator) { //$id = $validator->getVar("idPoll"); $id = $this->getNextPoll(11); if($id<=0) { $result = array( "code" => 200, "message" => "No votes for this user ".$_SESSION["user"]->id, "data" => null ); echo json_encode($result); return 'void'; } $poll = Doctrine::getTable("Poll")->find($id); if($poll) { $q = Doctrine_Query::create()->from("PollOption o") ->where("o.id_poll = ?", $id); $records = $q->execute(); $options = $records->toArray(); $poll = $poll->toArray(); $finalPoll["poll"] = $poll; $finalPoll["options"] = $options; $result = array( "code" => 200, "message" => "ok", "data" => $finalPoll ); echo json_encode($result); } return 'void'; } //End getPoll } ?><file_sep>/mobile/php/lib/lang_switch.class.php <?php class LangSwitch{ var $actual_lang; var $langs; var $def_lang = 'es'; var $actual_url = array(); function LangSwitch(){ require_once 'lib/util.class.php'; /* $langs_r = Util::query('SELECT * FROM site_lang WHERE publico = 1'); $this->langs = array(); while($l = mysql_fetch_object($langs_r)){ $this->langs[$l->shortname]['nombre'] = $l->nombre;///flip $this->langs[$l->shortname]['shortname'] = $l->shortname; $this->langs[$l->shortname]['imagen'] = $l->imagen; } */ $this->langs = array(); $this->langs['es']['nombre'] = 'español';///flip $this->langs['es']['shortname'] = 'es'; $this->langs['es']['imagen'] = '1.jpg'; $this->detec_lang(); } function detec_lang(){ if(isset($_COOKIE['lang'])) if($this->lang_avaible($_COOKIE['lang'])) $this->actual_lang = $_COOKIE['lang']; else{ $this->actual_lang = $this->def_lang; $_COOKIE['lang'] = $this->actual_lang; } else{ $this->actual_lang = $this->def_lang; $_COOKIE['lang'] = $this->actual_lang; } } function lang_avaible($l){ return isset( $this->langs[$l]); } function set_lang($lang){ if($this->lang_avaible($lang)) $this->actual_lang = $lang; else{ $this->actual_lang = $this->def_lang; $_COOKIE['lang'] = $this->actual_lang; } if($this->actual_lang == 'es'){ $loc = setlocale(LC_ALL, 'es_CO', 'es_ES', 'Español', 'ESP', 'Spanish'); }else if($this->actual_lang == 'en'){ $loc = setlocale(LC_ALL, 'en_US', 'American', 'ENG', 'English'); } } function add_actual_localized($loc, $url){ $this->actual_url[$loc] = $url; } function render_switch(){ global $liveSite; require_once 'lib/lang_switch.html.php'; $langs = array(); foreach($this->langs as $l){ if($l['shortname'] != $this->actual_lang){ $lang = array(); $lang['lang'] = $l['nombre']; $lang['class'] = $l['shortname']; $lang['imagen'] = $l['imagen']; if(isset($this->actual_url[$l['shortname']])) $lang['href'] = $this->actual_url[$l['shortname']]; else $lang['href'] = ($this->def_lang == $l['shortname'])?$liveSite:$liveSite.$l['shortname'].'/'; $langs[] = $lang; } } LangSwitchHTML::render_switch($langs); } function get_local_home(){ global $liveSite; return ($this->def_lang == $this->actual_lang)?$liveSite:$liveSite.$this->actual_lang.'/'; } } ?><file_sep>/mobile/php/html/path.html.php <?php class PathHTML{ static function make_path($branchs, $last){ $first = true; ?><p><?php foreach($branchs as $b){ if(!$first){ ?> <span class="separador">&gt;</span> <?php } if($first) $first = false; ?><a id="<?php echo ($b->copie); ?>" title="<?php echo ($b->title); ?>" href="<?php echo $b->url; ?>"><?php echo ($b->copie); ?></a><?php } echo ' <span class="separador">&gt;</span> '.($last); ?></p><?php } } ?><file_sep>/mobile/php/lib/util.class.php <?php class Util{ static $queries = array(); static $results = array(); static $objects = array(); static function guardar_archivo($archivo = "", $uploadDir = 'imagenes/temp/') { copy($archivo, $uploadDir); } static function guardar_imagen($archivo = "", $newWidth = 800, $newHeight = 600, $uploadDir = 'imagenes/temp/', $newName = "") { if(!isset($archivo)) exit; //$archivo = $_FILES["Filedata"]['tmp_name']; $image_info = getimagesize($archivo); $image_type = $image_info[2]; if( $image_type == IMAGETYPE_JPEG ) { $original = imagecreatefromjpeg($archivo); } elseif( $image_type == IMAGETYPE_GIF ) { $original = imagecreatefromgif($archivo); } elseif( $image_type == IMAGETYPE_PNG ) { $original = imagecreatefrompng($archivo); } //$fileReName = $_GET['SID'].".jpg"; if($newName == "") $newName = time().".jpg"; $nombre_foto = mysql_escape_string($_GET['nombre']); $destino = $uploadDir.$newName; //if(file_exists($destino)) //@unlink($destino); list($width,$height) = getimagesize($archivo); if($width >= $height){ if($width > $newWidth) { $newHeight = ($height/$width)*$newWidth; } else { $newWidth = $width; $newHeight = $height; } }else{ if($height > $newHeight) { $newWidth = ($width/$height)*$newHeight; }else { $newWidth = $width; $newHeight = $height; } } $tmp = imagecreatetruecolor($newWidth,$newHeight); $blanco = imagecolorallocate($tmp, 255, 255, 255); imagefill($tmp, 0, 0, $blanco); imagecopyresampled($tmp,$original,0,0,0,0,$newWidth,$newHeight,$width,$height); imagejpeg($tmp,$destino,80); imagedestroy($tmp); imagedestroy($original); return true; } static function secureValue($theValue, $html = false) { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); $theValue = $html ? $theValue : strip_tags($theValue); return $theValue; } static function query($s){ require_once('loger.class.php'); if(!in_array($s,Util::$queries)){ Loger::log('<strong>Util::query</strong>('.$s.')'); $r = mysql_query($s) or trigger_error(mysql_error().' - '.$s, E_USER_ERROR); Util::$queries[] = $s; Util::$results[$s] = $r; return $r; }else{ Loger::log('<font color="green">Caché para => Util::sql2obj</font>('.$s.')'); if(mysql_num_rows(Util::$results[$s]) > 0) mysql_data_seek( Util::$results[$s] , 0);//Reset del apuntador para el result return Util::$results[$s]; } } static function sql2obj($s){ if($r = Util::query($s)) return mysql_fetch_object($r); else return false; /* require_once('loger.class.php'); if(!in_array($s,Util::$queries)){ Loger::log('Util::sql2obj('.$s.')'); $r = Util::query($s); $o = mysql_fetch_object($r); Loger::log('Obj('.print_r($o, true).')'); Util::$objects[$s] = $o; return $o; }else{ Loger::log('<font color="green">Caché para => Util::sql2obj</font>('.$s.')'); Loger::log('Obj('.print_r(Util::$objects[$s], true).')'); mysql_data_seek( Util::$results[$s] , 0); return Util::$objects[$s]; }*/ } static function sql2array($s){ $result = Util::query($s); $objects = array(); if($result){ while($o = mysql_fetch_object($result)) $objects[] = $o; } return $objects; } /** * Send a POST requst using cURL * @param string $url to request * @param array $post values to send * @param array $options for cURL * @return string */ static function curl_post($url, array $post = NULL, array $options = array()) { $defaults = array( CURLOPT_POST => 1, CURLOPT_HEADER => 0, CURLOPT_URL => $url, CURLOPT_FRESH_CONNECT => 1, CURLOPT_RETURNTRANSFER => 1, CURLOPT_FORBID_REUSE => 1, CURLOPT_TIMEOUT => 4, CURLOPT_POSTFIELDS => http_build_query($post) ); $ch = curl_init(); curl_setopt_array($ch, ($options + $defaults)); if( ! $result = curl_exec($ch)) { trigger_error(curl_error($ch)); } curl_close($ch); return $result; } /** * Send a GET requst using cURL * @param string $url to request * @param array $get values to send * @param array $options for cURL * @return string */ static function curl_get($url, array $get = NULL, array $options = array()) { $defaults = array( CURLOPT_URL => $url. (strpos($url, '?') === FALSE ? '?' : ''). http_build_query($get), CURLOPT_HEADER => 0, CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_TIMEOUT => 4 ); $ch = curl_init(); curl_setopt_array($ch, ($options + $defaults)); if( ! $result = curl_exec($ch)) { trigger_error(curl_error($ch)); } curl_close($ch); return $result; } /** * Format URL to a URL-friendly version * @param string $url to format * @return string */ static function canonize_($url) { $url = strtolower($url); $url = str_replace(" ","-",$url); $url = strtr($url, 'áéíóúñ ', 'aeioun-'); $url = preg_replace('/[^a-z0-9\-]/i','', $url); return $url; } static function canonize($toClean) { $normalizeChars = array( 'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj','Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss','à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y', 'ƒ'=>'f' ); $toClean = str_replace('&', '-and-', $toClean); //$toClean = trim(preg_replace('/[^\w\d_ -]/si', '', $toClean));//remove all illegal chars $toClean = strtr($toClean, $normalizeChars); $toClean = str_replace(' ', '-', $toClean); $toClean = trim(preg_replace('/[^a-z0-9\-]/i', '', $toClean)); $toClean = str_replace('--', '-', $toClean); return strtolower($toClean); } } ?><file_sep>/mobile/php/lib/loger.class.php <?php class Loger{ static $_log; static function log($l){ Loger::$_log .= $l."\n"; } } ?><file_sep>/web/view/qrcode/view.php <?php if($vars["qr"]) { ?> <script type="text/javascript"> $(document).ready(function(){ $('#zone').val(<?php echo $vars["qr"]->Zone->id; ?>); }); </script> <form action="crud.php" method="POST"> <input type="hidden" name="action" value="edit" /> <input type="hidden" name="view" value="qr" /> <input type="hidden" name="id" value="<?php echo $vars["qr"]->id; ?>" /> <div class="row-fluid"> <div class="span12"> <h1>Datos del QR #<?php echo $vars["qr"]->id; ?></h1> <div class="row-fluid"> <div class="span6"> Lleva al URL: <input type="text" value="<?php echo $vars["qr"]->big_url; ?>" /> <h2>Ubicación</h2> <p>País: <?php echo $vars["qr"]->Country->name; ?> <select id="countries" name="country"> <?php foreach($vars["countries"] as $country) { ?> <option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option> <?php } ?> </select> </p> <p>Estado: <?php echo $vars["qr"]->State->name; ?> <select id="states" name="state"> <?php foreach($vars["states"] as $country) { ?> <option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option> <?php } ?> </select> </p> <p>Municipio: <?php echo $vars["qr"]->Munincipality->name; ?> <select id="munincipalities" name="munincipality"> <?php foreach($vars["munincipalities"] as $country) { ?> <option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option> <?php } ?> </select> </p> <p>Zona: <select id="zone" name="zone"> <?php foreach($vars["zone"] as $country) { ?> <option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option> <?php } ?> </select> </p> </div> <div class="span6"> <a href="<?php echo $GLOBALS["baseURL"]; ?>crud.php?view=qr&action=delete&id=<?php echo $vars["qr"]->id; ?>">Delete</a> | <a href="<?php echo $GLOBALS["baseURL"]; ?>print-qr&id=<?php echo $vars["qr"]->id; ?>">Print</a> | <a href="#">Stats</a> <h2>Updates</h2> <div> <p>Fecha de instalación: <?php echo $vars["qr"]->instalation_date; ?> <?php if(!$vars["qr"]->instalation_date) { ?> <a href="<?php echo $GLOBALS["baseURL"]; ?>crud.php?action=markInstalled&view=qr&id=<?php echo $vars["qr"]->id; ?>">Marcar como instalado</a> <?php } ?> </p> <p>Fecha de ultimo mantenimiento: <?php echo $vars["qr"]->last_maintenance; ?> <a href="<?php echo $GLOBALS["baseURL"]; ?>crud.php?action=markInstalled&view=qr&id=<?php echo $vars["qr"]->id; ?>">Actualizar</a></p> <p>Ultimo scan: <?php echo $vars["qr"]->last_scan; ?></p> </div> <h2>QR Code</h2> <img src="<?php echo $vars["qr"]->url; ?>.qrcode" /> </div> </div> </div> </div> <input type="submit" value="Guardar" class="btn primary" /> </form> <script> $(document).ready(function(){ $('#countries').val(<?php echo $vars["qr"]->Country->id; ?>); $('#states').val(<?php echo $vars["qr"]->State->id; ?>); $('#munincipalities').val(<?php echo $vars["qr"]->Munincipality->id; ?>); $('#parish').val(<?php echo $vars["qr"]->Parish->id; ?>); }); </script> <?php } else { ?> <h1>No se encontró el QR</h1> <?php } ?><file_sep>/mobile/php/pathway.php <?php class Pathway{ var $branchs = array(); var $last = ""; function Pathway(){ global $liveSite, $siteTitle, $cw, $lang_switch; $this->add_branch($siteTitle, $lang_switch->get_local_home(), $cw->wr('inicio', false)); } function add_branch($title, $url, $copie){ $b = new stdClass(); $b->title = "$title"; $b->url = "$url"; $b->copie = "$copie"; $this->branchs[] = $b; } function add_last_branch($copie){ global $siteTitle; $siteTitle = $copie.' - '.$siteTitle; $this->last = $copie; } function make_path(){ require_once 'html/path.html.php'; return PathHTML::make_path($this->branchs, $this->last); } } ?><file_sep>/web/view/empresas.php <script type="text/javascript"> var chart; var total = 0; var aux = 3; $(document).ready(function() { var categories = [] var i = 0; <?php if (count($vars["options"])>0){ foreach ($vars["options"] as $option){?> categories[i]= "<?php echo $option->answer; ?>"; i++; <?php } } ?> //$("#mascampos").generaNuevosCampos("Option", "option", aux); $("#new-poll").hide(); $("#tab-opc2").click( function(){ $("#my-polls").hide(); $("#new-poll").show(); $("#myTab li:first").removeClass("active"); $("#myTab li:last").addClass("active"); } ); $("#tab-opc1").click( function(){ $("#new-poll").hide(); $("#my-polls").show(); $("#myTab li:last").removeClass("active"); $("#myTab li:first").addClass("active"); } ); $.ajax({ type: "POST", url: "<?php echo $GLOBALS["baseURL"]; ?>crud.php", data: "view=producer&action=getMyPollResults&id"+$('#asunto').val()+"", error:function (xhr, ajaxOptions, thrownError){ //var $barraMsj = anchoResolucion <= 1024 ? $("#msg-row") : $("#msg_box"); alert("error"); }, success: function(msg){ //alert(msg); } }); $("#mascampos").generaNuevosCampos("Option", "option", aux); var colors = Highcharts.getOptions().colors, name = 'Browser brands', data = [], j=0; <?php if (count($vars["results"])>0){ foreach($vars["results"] as $r){?> data[j] = {y:<?php echo $r["count"]; ?>,color: colors[j],} total += <?php echo $r["count"]; ?>; j++; <?php }} ?> function setChart(name, categories, data, color) { chart.xAxis[0].setCategories(categories, false); chart.series[0].remove(false); chart.addSeries({ name: name, data: data, color: color || 'white' }, false); chart.redraw(); } chart = new Highcharts.Chart({ chart: { renderTo: 'container', type: 'column' }, title: { text: '<?php if ($vars["poll"] != ""){ echo $vars["poll"]->question; }?>' }, xAxis: { categories: categories }, yAxis: { title: { text: 'Total of votes' } }, plotOptions: { column: { cursor: 'pointer', point: { events: { click: function() { var drilldown = this.drilldown; if (drilldown) { // drill down setChart(drilldown.name, drilldown.categories, drilldown.data, drilldown.color); } else { // restore setChart(name, categories, data); } } } }, dataLabels: { enabled: true, color: colors[0], style: { fontWeight: 'bold' }, formatter: function() { return (this.y*100)/total +'%'; } } } }, tooltip: { formatter: function() { var point = this.point, s = this.x +':<b>'+ this.y +'% market share</b><br/>'; if (point.drilldown) { s += 'Click to view '+ point.category +' versions'; } else { s += 'Click to return to browser brands'; } return s; } }, series: [{ name: name, data: data, color: 'white' }], exporting: { enabled: false } }); }); function getResults(id){ var value = id.options[id.selectedIndex].value; location.href="<?php echo $GLOBALS["baseURL"];?>producer&id="+value; } jQuery.fn.generaNuevosCampos = function(etiqueta, nombreCampo, indice){ //$(this).each(function(){ elem = $(this); elem.data("etiqueta",etiqueta); elem.data("nombreCampo",nombreCampo); elem.data("indice",indice); elem.click(function(e){ e.preventDefault(); elem = $(this); etiqueta = elem.data("etiqueta"); nombreCampo = elem.data("nombreCampo"); indice = elem.data("indice"); texto_insertar = '<p id = "option-'+indice+'">' + etiqueta + ' ' + aux + ':<br><input type="text" name="options[]" /> <a href="#" onClick="deleteElement(\'option-'+indice+'\')">Delete</a></p>'; indice ++; aux ++; elem.data("indice",indice); nuevo_campo = $(texto_insertar); elem.before(nuevo_campo); }); //}); return this; } function deleteElement(elemento){ $("#"+elemento).remove(); aux --; } $('#theform').ajaxForm({ target: '#alert-message', success: function(message) { $("#standardError").html(message); $("#alert-message").show().fadeOut(3000); } }); $("#statusCheckbox").live('change',function(){ $.ajax({ type: "POST", url: "<?php echo $GLOBALS["baseURL"]; ?>crud.php", data: "view=producer&action=setPollState&Poll="+$("#pollSelector").val()+"&Status="+$("#statusCheckbox").is(":Checked"), error:function (xhr, ajaxOptions, thrownError){ //var $barraMsj = anchoResolucion <= 1024 ? $("#msg-row") : $("#msg_box"); alert("error"); }, success: function(data){ alert(data); } }); }); </script> <section id="int-header"> <div id="info-user"> <legend>Bienvenido </legend> <a id="user-name"></a> </div> </section> <div class="tabbable"> <ul id="myTab" class="nav nav-pills"> <li class="active"> <a id="tab-opc1" href="#" >My Polls</a> </li> <li> <a id="tab-opc2" href="#" >New Poll</a> </li> </ul> <div class="tab-content"> <div id="my-polls"> <legend>Select a Poll</legend> <SELECT class="btn-group" onchange="getResults(this)" name="asunto" SIZE=1> <?php foreach($vars["polls"] as $poll){ if($_GET["id"] == $poll->id){?> <OPTION selected class="opvalue" VALUE="<?php echo $poll->id; ?>"><?php echo $poll->question;?></OPTION> <?php }else{ ?> <OPTION class="opvalue" VALUE="<?php echo $poll->id; ?>"><?php echo $poll->question;?></OPTION> <?php } } ?> </SELECT> <?php if (count($vars["results"])>0){ ?> <div id="container" style="width: 50%; height: 400px"></div> <?php }else { ?> There's no votes yet!.. <?php } ?> <label class="checkbox"> <input id="statusCheckbox" type="checkbox" value="active"> {Act/deact}ivate this poll. </label> </div> <!-- <div> <label class="label label-info" id="s-min-age"for="user" style="width:100px">Min age</label><a></a> <label class="label label-info" id="s-max-age"for="user" style="width:100px">Max age</label><a></a> <label class="label label-info" id="s-gender"for="user" style="width:100px">Gender</label><a></a> <label class="label label-info" id="s-civil-state"for="user" style="width:100px">Civil state</label><a></a> <label class="label label-info" id="s-education"for="user" style="width:100px">Education</label><a></a> <label class="label label-info" id="s-country"for="user" style="width:100px">Country</label><a></a> <label class="label label-info" id="s-state"for="user" style="width:100px">State</label><a></a> <label class="label label-info" id="s-municipality"for="user" style="width:100px">Municipality</label><a></a> <label class="label label-info" id="s-zone"for="user" style="width:100px">Zone</label><a></a> <label class="label label-info" id="s-postal-code"for="user" style="width:100px">Postal Code</label><a></a> <label class="label label-info" id="s-poll-reach"for="user" style="width:100px">Poll reach</label><a></a> </div>--> <div id="new-poll"> <!-- insert_polis --> <div id="main-content"> <div class="alert-message error" id="alert-message" style="display:none;"> <p id="standardError">Best check yo self, you’re not looking too good.</p> </div> <form action="<?php echo $GLOBALS['baseURL'];?>crud.php" id="theform" method="post" > <input name="view" type="hidden" value="producer"/> <input name="action" type="hidden" value="createPoll" /> <input name="user" type="hidden" value="<?php print_r($_SESSION["user"]->id); ?>" /> <fieldset id="poll-content"> <legend>Create Poll</legend> <div class="clearfix"> <label for="user">Min Age: </label> <div class="input"> <input name="min-age" id="poll-min-age" type="text" title="Min Age" /> <strong class="error" id="countryerror"></strong> </div> </div> <div class="clearfix"> <label for="user">Max Age: </label> <div class="input"> <input name="max-age" id="poll-max-age" type="text" title="Max Age" /> <strong class="error" id="countryerror"></strong> </div> </div> <div class="clearfix"> <label for="user">Gender: </label> <div class="input"> <select name="gender" id="poll-gender"> <option value="male">male</option> <option value="women">female</option> <option value="both">both</option> </select> <strong class="error" id="countryerror"></strong> </div> </div> <div class="clearfix"> <label for="user">Civil State: </label> <div class="input"> <select name="civil-state" id="poll-civilstate"> <option value="single">single</option> <option value="married">married</option> <option value="divorced">divorced</option> <option value="widow">widow</option> </select> <strong class="error" id="countryerror"></strong> </div> </div> <!--<div class="clearfix"> <label for="user">Education: </label> <div class="input"> <select name="education" id="poll-education"> <option value="hs">High school</option> <option value="b">Bachelor</option> <option value="d">Doctorate</option> <option value="d">Master</option> </select> <strong class="error" id="countryerror"></strong> </div> </div> --> <div class="clearfix"> <label for="user">Country: </label> <div class="input"> <!-- Agregación PHP --> <select id="poll-country" class="btn-group" name="country"> <?php foreach ($vars["countries"] as $value) {?> <option class="optvalue" value="<?php echo $value["id"]; ?>"><?php echo $value["name"] ?></option> <?php } ?> </select> <strong class="error" id="countryerror"></strong> </div> </div> <div class="clearfix"> <label for="user">State: </label> <div class="input"> <select id="poll-state" class="btn-group" name="state"> <?php foreach ($vars["states"] as $value) {?> <option class="optvalue" value="<?php echo $value["id"]; ?>"><?php echo $value["name"] ?></option> <?php } ?> </select> <strong class="error" id="stateerror"></strong> </div> </div> <div class="clearfix"> <label for="user">Munincipality: </label> <div class="input"> <select id="poll-munincipality" class="btn-group" name="munincipality"> <?php foreach ($vars["munincipalities"] as $value) {?> <option class="optvalue" value="<?php echo $value["id"]; ?>"><?php echo $value["name"] ?></option> <?php } ?> </select> <strong class="error" id="munincipalityerror"></strong> </div> </div> <div class="clearfix"> <label for="user">Zone: </label> <div class="input"> <select id="poll-parish" class="btn-group" name="zone"> <?php foreach ($vars["zone"] as $value) {?> <option class="optvalue" value="<?php echo $value["id"]; ?>"><?php echo $value["name"] ?></option> <?php } ?> </select> <strong class="error" id="parisherror"></strong> </div> </div> <div class="clearfix"> <label for="user">Postal Code: </label> <div class="input"> <input name="postal_code" id="poll-postal-code" type="text" title="Postal Code" /> <strong class="error" id="postalcodeError"></strong> </div> </div> <div class="clearfix"> <label for="user">Poll reach </label> <input id="num" name="amount" type="number" required> </div> <div class="clearfix"> <label for="user">Question: </label> <div class="input"> <input name="questions" id="poll-question" type="text" title="Question" /> <strong class="error" id="userError"></strong> </div> </div> <div class="clearfix"> <label>Option 1: </label> <div class="input"> <input id="question-option" type='text' name='options[]' /> <strong class="error" id="userError"></strong> </div> </div> <div class="clearfix"> <label>Option 2: </label> <div class="input"> <input id="question-option" type='text' name='options[]' /> <strong class="error" id="userError"></strong> </div> </div> <div id="newOptionsDiv" > </div> <div> <button id="mascampos" class="btn medium blue">Agregar opci&oacute;n</button> </div> <div class="actions"> <input name="" type="submit" class="btn medium blue" value="Crear" /> </div> </form> </div> </div> </div> <file_sep>/mobile/php/lib/baseobject.tpl.php <?php class {CLASS_NAME}{ var $contentType = ""; var $tabla = "{tabla}"; var $campos_form = array({campos_form}); var $campos_listado = array({campos_listado}); var $data_sources = array({data_sources}); function getContenido($a) { if(session_name() != 'admin'){ require_once 'php/lib/not_found.exception.php'; throw new NotFoundException(); } switch ($a) { case "crear_{objeto}": $this->crear_{objeto}(); break; case "guardar_{objeto}": $this->guardar_{objeto}(); break; case "editar_{objeto}": $this->editar_{objeto}(); break; case "nuevo_{objeto}": $this->form(); break; case "publicar_{objeto}": $this->activar_{objeto}(); break; case "despublicar_{objeto}": $this->desactivar_{objeto}(); break; case "borrar_{objeto}": $this->borrar_{objeto}(); break; case '': $this->listado(); break; default: require_once 'php/lib/not_found.exception.php'; throw new NotFoundException(); } } function listado(){ global $liveSite; $this->contentType = "html"; require_once 'lib/paginacion.class.php'; $campos = array(); $joins = 0; $join = ''; foreach($this->campos_listado as $label => $tipo){ if($tipo == 8){ if(is_array($this->data_sources[$label])){ $joins++; $t = $this->data_sources[$label]['tabla']; $l = $this->data_sources[$label]['label']; $id = $this->data_sources[$label]['id']; $join = "LEFT JOIN ".$t." j_".$joins." ON j_".$joins.".".$id." = ".$this->tabla.".".$label; $campos[] = "j_".$joins.'.'.$l.' as '.$label; }else $campos[] = $this->tabla.".".$label; }else $campos[] = $this->tabla.".".$label; } $s = "SELECT ".implode(", ",$campos); $f = " FROM $this->tabla ".$join; $paginador = new Paginacion($s, $f); $objetos = $paginador->fetch_object_list(); require_once 'html/{html_file}_a.html.php'; {html_class}HTML::acciones(); $paginador->mostrarPaginacion($liveSite.'admin/{nombre_seccion}/'); {html_class}HTML::listado($objetos, $this->campos_listado); } function form($obj = false, $controles = array()){ $this->contentType = "html"; require_once 'html/{html_file}_a.html.php'; {html_class}HTML::acciones(); if(!$obj){ require_once 'lib/control.class.php'; $controles = array(); foreach($this->campos_form as $label => $tipo){ if($label == '{campo_id}' || $label == '{campo_publicado}') continue; $control = new Control($tipo); $control->label = $label; $control->value = ''; if($tipo == 8){ $control->data_source = $this->data_sources[$label]; } $controles[] = $control; } } {html_class}HTML::form($obj, $controles); } function crear_{objeto}(){ global $liveSite; $campos = array(); $values = array(); $uploads = array(); foreach($this->campos_form as $label => $tipo){ if($label == '{campo_id}') continue; if($tipo == 7){ $uploads[] = $label; }else{ $html = ($tipo == 3)?true:false; $campos[] = $label; $values[] = "'".Util::secureValue($_POST[$label],$html)."'"; } } $sql = "INSERT INTO $this->tabla (".implode(', ', $campos )." ) VALUES ( ".implode(', ', $values )." )"; $result = Util::query($sql); $id_creado = mysql_insert_id(); foreach($uploads as $u){ if(isset($_FILES["$u"]['tmp_name']) && strlen($_FILES["$u"]['tmp_name']) > 0){ $s = Util::guardar_archivo($_FILES["$u"]['tmp_name'], 'imagenes/{nombre_seccion}/'.$id_creado.'.jpg'); $sql = "UPDATE $this->tabla SET $u = '".$id_creado.".jpg' WHERE {campo_id} = '".$id_creado."' LIMIT 1"; $result = Util::query($sql); } } $this->redirect_listado(); } function editar_{objeto}(){ global $liveSite; require_once 'lib/control.class.php'; $id = Util::secureValue($_GET['{campo_id}']); $campos = array(); $tipos = array(); foreach($this->campos_form as $label => $tipo){ $campos[] = $label; $tipos[] = $tipo; } $sql = "SELECT ".implode(', ', $campos)." FROM $this->tabla WHERE {campo_id} = '$id'"; $obj = Util::sql2obj($sql); if(!is_object($obj)) throw new NotFoundException(); $controles = array(); foreach($this->campos_form as $label => $tipo){ if($label == '{campo_id}' || $label == '{campo_publicado}') continue; $control = new Control($tipo); $control->label = $label; $control->value = $obj->$label; if($tipo == 7){ $control->value = $liveSite.'imagenes/{nombre_seccion}/'.$obj->{campo_id}.'.jpg'; $control->required = false; }else $control->value = $obj->$label; if($tipo == 8){ $control->data_source = $this->data_sources[$label]; } $controles[] = $control; } $this->form($obj, $controles); } function guardar_{objeto}(){ global $liveSite; $id_{objeto} = Util::secureValue($_POST['{campo_id}']); $campos = array(); $uploads = array(); foreach($this->campos_form as $label => $tipo){ if($label == '{campo_id}') continue; if($tipo == 7){ $uploads[] = $label; }else{ $html = ($tipo == 3)?true:false; $campos[] = $label." = '".Util::secureValue($_POST[$label],$html)."'"; } } $sql = "UPDATE $this->tabla SET ".implode(',', $campos )." WHERE {campo_id} = '".$id_{objeto}."' LIMIT 1"; $result = Util::query($sql); foreach($uploads as $u){ if(isset($_FILES["$u"]['tmp_name']) && strlen($_FILES["$u"]['tmp_name']) > 0){ $s = Util::guardar_archivo($_FILES["$u"]['tmp_name'], 'imagenes/{nombre_seccion}/'.$id_{objeto}.'.jpg'); $sql = "UPDATE $this->tabla SET $u = '".$id_{objeto}.".jpg' WHERE {campo_id} = '".$id_{objeto}."' LIMIT 1"; $result = Util::query($sql); } } $this->redirect_listado(); } function activar_{objeto}(){ global $liveSite; $sql = "UPDATE $this->tabla SET {campo_publicado} = 1 WHERE {campo_id} = ".Util::secureValue($_GET['{campo_id}']); $result = Util::query($sql); $this->redirect_listado(); } function desactivar_{objeto}(){ global $liveSite; $sql = "UPDATE $this->tabla SET {campo_publicado} = 0 WHERE {campo_id} = ".Util::secureValue($_GET['{campo_id}']); $result = Util::query($sql); $this->redirect_listado(); } function borrar_{objeto}(){ global $liveSite; $sql = "DELETE FROM $this->tabla WHERE {campo_id} = ".Util::secureValue($_GET['{campo_id}']); $result = Util::query($sql); $this->redirect_listado(); } function redirect_listado(){ if(isset($_REQUEST['next'])) echo "<script>window.location.href = '".$_REQUEST['next']."';</script>"; else if(isset($_SERVER['HTTP_REFERER'])) echo "<script>window.location.href = '".$_SERVER['HTTP_REFERER']."';</script>"; else echo "<script>window.location.href = '".$liveSite."admin/{nombre_seccion}/';</script>"; } } ?><file_sep>/mobile/php/html/inicio.html.php <?php class inicioHTML{ static function sing_ing() { global $liveSite, $cw, $appapikey, $appID; require_once 'lib/plugin.class.php'; //Plugin::get_localized_link('contacto'); ?> <div id="fb-root"></div> <script> var channel_path = '<?php echo $liveSite; ?>?opcion=gatewayFB&a=connect&xd_receiver=true'; window.fbAsyncInit = function() { FB.init({ appId : '<?php echo $appID; ?>', // App ID channelUrl : channel_path, // Channel File status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true // parse XFBML }); // Additional initialization code here }; // Load the SDK Asynchronously (function(d){ var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true; js.src = "http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php";//"//connect.facebook.net/en_US/all.js"; //js.src = "//connect.facebook.net/en_US/all.js"; ref.parentNode.insertBefore(js, ref); }(document)); !function ($) { $('body').on('click', '.btn', handler_func) function handler_func (){ FB.login(function(response) { if (response.authResponse) { console.log('Welcome! Fetching your information.... '); FB.api('/me', function(response) { var json_obj = JSON.stringify(response, null, 2); console.log("sendign: "+json_obj); $.ajax({ type: 'POST', url: '<?php echo $liveSite; ?>registro/registrar/', data: response, dataType: 'script', }).success(function(res) { //alert(res); console.log('succes, redirecting to polls!!'); //top.location.href = '<?php echo $liveSite; ?>polls/'; }).complete(function(a, b){ //alert("complete.."+a+" "+b) }); }); } else { console.log('User cancelled login or did not fully authorize.'); } }, {scope: 'email'}); } }(window.jQuery) </script> <header> <div class="container"> <section> <div class="row"> <div class="hero-unit white"> <h1>Pollbag</h1> <p>Cause your free time is Gold.</p> <button id="sing-in" class="btn btn-large btn-primary">Sign in whit Facebook</button> </div> </div> </section> </div> </header> <?php } static function polls() { global $liveSite, $cw; require_once 'lib/plugin.class.php'; //Plugin::get_localized_link('contacto'); ?> <div class="verde"> <div class="container"> <section> <div class="row"> </div> </section> </div> </div> <?php } static function account() { global $liveSite, $cw; require_once 'lib/plugin.class.php'; //Plugin::get_localized_link('contacto'); ?> <div class="verde"> <div class="container"> <section> <div class="row"> </div> </section> </div> </div> <?php } } ?><file_sep>/mobile/php/lib/baseobjectHTML.tpl.php <?php class {CLASS_NAME}HTML{ static function acciones(){ global $liveSite; ?> <div id="actions" class="container_12"> <div class="grid_3 prefix_9"> <h2><?php echo ucfirst('{nombre_seccion}'); ?></h2> </div> <div class="grid_7 prefix_5"> <a href="<?php echo $liveSite; ?>admin/{nombre_seccion}/">Ver {objeto}s</a> <a href="<?php echo $liveSite; ?>admin/{nombre_seccion}/?a_=nuevo_{objeto}">Crear {objeto}</a> </div> <hr class="grid_12" /> <div class="clear"></div> </div> <?php } static function listado(${objeto}s, $campos){ global $liveSite; ?> <script type="text/javascript"> function borrar_objeto(id){ var c = confirm('Está seguro que desea borrar este elemento? \nNo podrá deshacer esta acción.'); if(c){ window.location.href = '<?php echo $liveSite;?>admin/{nombre_seccion}/?a_=borrar_{objeto}&{campo_id}='+id; } } </script> <div class="container_12"> <?php foreach($campos as $c => $t){ if($c == '{campo_publicado}') continue;?> <div class="grid_2"><h3><?php echo ($c == '{campo_id}')? 'ID':$c; ?></h3></div> <?php } ?> <div class="grid_1">Publico</div> <div class="grid_1">Editar</div> <div class="grid_1">Borrar</div> <div class="clear"></div> </div> <div class="container_12"> <?php $class = 'dark'; foreach(${objeto}s as ${objeto}){ ?> <div class="fila fila_<?php echo $class; ?>"> <?php foreach($campos as $c => $t){ if($c == '{campo_publicado}') continue; else{ ?> <div class="grid_2"><?php echo ${objeto}->$c; ?></div> <?php } } ?> <div class="grid_1"> <?php if(${objeto}->{campo_publicado} == 0){ ?> <a href="<?php echo $liveSite; ?>admin/{nombre_seccion}/?a_=publicar_{objeto}&{campo_id}=<?php echo ${objeto}->{campo_id}; ?>" class="unpublish">Publicar</a> <?php }else{ ?> <a href="<?php echo $liveSite; ?>admin/{nombre_seccion}/?a_=despublicar_{objeto}&{campo_id}=<?php echo ${objeto}->{campo_id}; ?>" class="publish">Despublicar</a> <?php } ?> </div> <div class="grid_1"> <a href="<?php echo $liveSite; ?>admin/{nombre_seccion}/?a_=editar_{objeto}&{campo_id}=<?php echo ${objeto}->{campo_id}; ?>" class="editar" title="Editar">Editar</a> </div> <div class="grid_1"> <a href="javascript:borrar_objeto(<?php echo ${objeto}->{campo_id}; ?>);" class="borrar" title="Borrar">Borrar</a> </div> <div class="clear"></div> </div> <div class="clear"></div> <?php $class = ($class == 'light') ? 'dark' : 'light'; } ?> </div> <?php } static function form(${objeto} = false, $controles){ global $liveSite; if(${objeto}) $action = $liveSite."admin/{nombre_seccion}/?a_=guardar_{objeto}"; else $action = $liveSite."admin/{nombre_seccion}/?a_=crear_{objeto}"; ?> <div class="grid_12"> <h3 class="grid_4 sufix_7">Edici&oacute;n {objeto}</h3> <div class="grid_10 prefix_1"> <form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" name="form_{objeto}" id="form_{objeto}"> <?php foreach($controles as $control){ $control->render(); } ?> <div class="grid_2 alpha"> <label for="publicado">P&uacute;blico</label><br /><br /> </div> <div class="grid_8 omega"> <input type="radio" name="{campo_publicado}" id="{campo_publicado}_1" value="1" <?php if(${objeto} && ${objeto}->{campo_publicado} == 1){ ?> checked="checked"<?php } ?> class="validate['required']"><label>Si</label><br /> <input type="radio" name="{campo_publicado}" id="{campo_publicado}_2" value="0" <?php if(${objeto} && ${objeto}->{campo_publicado} == 0){ ?> checked="checked"<?php } ?> class="validate['required']"><label>No</label> </div> <div class="clear"></div> <br /><br /> <?php if(${objeto}){ ?> <input name="{campo_id}" type="hidden" value="<?php echo ${objeto}->{campo_id}; ?>"> <?php } ?> <input name="next" type="hidden" value="<?php echo $liveSite; ?>admin/{nombre_seccion}/"> <div class="grid_2"> <input type="submit" name="" id="enviar" value="Terminar"> </div> </form> </div> </div> <script type="text/javascript"> window.addEvent('domready',function(){ var formcheck = new FormCheck('form_{objeto}', { trimValue: true, showErrors: 1, indicateErrors: 1, onSubmit: function(){if(tinyMCE != undefined )tinyMCE.triggerSave(); } }); }); </script> <script type="text/javascript"> tinyOnDemand();</script> <?php } } ?><file_sep>/mobile/php/config.admin.php <?php class Config{ var $contentType = ""; function getContenido($a) { if(session_name() != 'admin'){ //require_once 'php/lib/not_found.exception.php'; //throw new NotFoundException(); } switch ($a) { case "crear_objeto": $this->crear(); break; case "guardar": $this->guardar(); break; default: $this->inicio(); } } function inicio(){ $this->contentType = "html"; $this->contentType = "html"; require_once 'html/config_a.html.php'; ConfigHTML::acciones(); ConfigHTML::listado($this->listado_tablas()); } function listado_tablas(){ $sql = "SHOW TABLES"; $r = mysql_query($sql); $tablas = array(); while($t = mysql_fetch_array($r)){ if(strpos($t[0], "admin_") !== 0 && $t[0] != 'mensajes'){ $tabla = new stdClass(); $tabla->nombre = $t[0]; $tabla->file = file_exists('php/'.$t[0].'.admin.php')? 1:0; $sql_ = "SHOW COLUMNS FROM ".$tabla->nombre; $r_ = mysql_query($sql_); $fields = array(); while($f = mysql_fetch_array($r_)){ $fields[] = $f[0]; } $tabla->fields = $fields; $tablas [] = $tabla; } } return $tablas; } function crear(){ require_once 'lib/util.class.php'; $tabla = Util::secureValue($_GET['tabla']); $sql = "SHOW COLUMNS FROM ".$tabla; $r = mysql_query($sql); $fields = array(); while($f = mysql_fetch_array($r)){ $fields[] = $f[0]; } $this->contentType = "html"; require_once 'html/config_a.html.php'; ConfigHTML::acciones(); ConfigHTML::form($tabla, $fields, $this->listado_tablas()); } function guardar(){ global $liveSite; require_once 'lib/util.class.php'; //{CLASS_NAME} //{objeto} //{campos_listado} //{campos_form} //{tabla} //{html_file} //{html_class} //{nombre_seccion} //{campo_publicado} //{campo_id} $tabla = $nombre_seccion = Util::secureValue($_POST['tabla']); $objeto = Util::secureValue($_POST['objeto']); $classname = ucfirst($tabla); $html_file = $nombre_seccion; $html_class = ucfirst($nombre_seccion); $campo_id = Util::secureValue($_POST['campo_id']); $campo_publicado = Util::secureValue($_POST['campo_publicado']); //$campos_listado = implode(', ', ($_POST['campos_lista'])); $campos = array(); $campos [] = "'$campo_id' => 0"; $campos [] = "'$campo_publicado' => 0"; foreach($_POST['campos_lista'] as $c){ if($c == $campo_id || $c == $campo_publicado) continue; $campos [] = "'".Util::secureValue($c)."' => ".$_POST['tipo_'.$c];//"'".Util::secureValue($c)."'"; } $campos_listado = implode(', ', $campos); $data_sources = array(); $data_sources [] = "'$campo_id' => 0"; $data_sources [] = "'$campo_publicado' => 0"; $campos = array(); $campos [] = "'$campo_id' => 0"; $campos [] = "'$campo_publicado' => 0"; foreach($_POST['campos_form'] as $c){ if($c == $campo_id || $c == $campo_publicado) continue; $campos [] = "'".Util::secureValue($c)."' => ".$_POST['tipo_'.$c]; if($_POST['tipo_'.$c] == 8){//LISTA if($_POST['estatico_'.$c] == 1){ $data_sources[] = "'$c' => '".$_POST['estatico_labels_'.$c].";".$_POST['estatico_values_'.$c]."'"; $_POST['estatico_'.$c]; }else{ $data_sources[] = "'$c' => array('tabla'=> '".$_POST['tabla_'.$c]."', 'label' => '".$_POST['label_tabla_'.$c]."', 'id' => '".$_POST['campo_tabla_'.$c]."')"; } }else{ $data_sources [] = "'$c' => 0"; } } $data_sources = implode(', ', $data_sources); $campos_form = implode(', ', $campos); echo "<h2>Escribiendo clases para $classname </h2>"; if(isset($_POST['admin'])){ $control = file_get_contents('php/lib/baseobject.tpl.php'); $control = str_replace('{CLASS_NAME}', $classname, $control); $control = str_replace('{objeto}', $objeto, $control); $control = str_replace('{campos_listado}', $campos_listado, $control); $control = str_replace('{campos_form}', $campos_form, $control); $control = str_replace('{data_sources}', $data_sources, $control); $control = str_replace('{tabla}', $tabla, $control); $control = str_replace('{html_file}', $html_file, $control); $control = str_replace('{html_class}', $html_class, $control); $control = str_replace('{nombre_seccion}', $nombre_seccion, $control); $control = str_replace('{campo_publicado}', $campo_publicado, $control); $control = str_replace('{campo_id}', $campo_id, $control); echo "escribiendo admin => php/".$nombre_seccion.".admin.php <br />"; $clase = fopen("php/".$nombre_seccion.".admin.php", "w"); fwrite($clase, $control); } if(isset($_POST['adminHTML'])){ $vista = file_get_contents('php/lib/baseobjectHTML.tpl.php'); $vista = str_replace('{CLASS_NAME}', $classname, $vista); $vista = str_replace('{objeto}', $objeto, $vista); $vista = str_replace('{nombre_seccion}', $nombre_seccion, $vista); $vista = str_replace('{campo_publicado}', $campo_publicado, $vista); $vista = str_replace('{campo_id}', $campo_id, $vista); echo "escribiendo adminHTML => php/html/".$nombre_seccion."_a.html.php <br />"; $clase = fopen("php/html/".$nombre_seccion."_a.html.php", "w"); fwrite($clase, $vista); } if(isset($_POST['public'])){ $public = file_get_contents('php/lib/basepublicobject.tpl.php'); $public = str_replace('{CLASS_NAME}', $classname, $public); $public = str_replace('{html_file}', $html_file, $public); $public = str_replace('{tabla}', $tabla, $public); $public = str_replace('{campo_publicado}', $campo_publicado, $public); $public = str_replace('{nombre_seccion}', $nombre_seccion, $public); echo "escribiendo public => php/".$nombre_seccion.".php <br />"; $clase = fopen("php/".$nombre_seccion.".php", "w"); fwrite($clase, $public); } if(isset($_POST['publicHTML'])){ $publichtml = file_get_contents('php/lib/basepublichtmlobject.tpl.php'); $publichtml = str_replace('{CLASS_NAME}', $classname, $publichtml); $publichtml = str_replace('{html_file}', $html_file, $publichtml); $publichtml = str_replace('{tabla}', $tabla, $publichtml); $publichtml = str_replace('{campo_publicado}', $campo_publicado, $publichtml); $publichtml = str_replace('{nombre_seccion}', $nombre_seccion, $publichtml); echo "escribiendo publicHTML => php/html/".$nombre_seccion.".html.php <br />"; $clase = fopen("php/html/".$nombre_seccion.".html.php", "w"); fwrite($clase, $publichtml); } $this->contentType = 'html'; echo "<a href='".$liveSite."admin/config/'>Continuar</a>"; } } ?><file_sep>/web/view/home.php <script type="text/javascript"> var users = 5544; $(document).ready(function(){ parse_users(users); setTimeout("checkUsers()",60000); /*var token = localStorage["ch_token"]; if(typeof token == "undefined"){ get_channel(); }else{ open_channel(); }*/ }); /*function get_channel(){ $.get( "/view/get_token/", function(data){ localStorage["ch_token"] = data.token; open_channel(); } ) .error(function(){ get_channel(); }) }*/ function parse_users(users){ us = pad2(users); $('#t7_m').html(us.substr(7,2)); $('#t7_h').html(us.substr(4,3)); $('#t7_d').html(us.substr(0,4)); } /*function open_channel(){ var channel = new goog.appengine.Channel(localStorage["ch_token"]); var socket = channel.open(); socket.onerror = function(){ get_channel(); } socket.onclose = function(){ get_channel(); } socket.onmessage = function(msg){ var data = JSON.parse(msg.data); parse_users(data.users); } }*/ function checkUsers(){ $.get( "/users/registred-users/", function(data){ users = data.count_users; parse_users(data.count_users); setTimeout("checkUsers()",60000); } ); } function pad2(number) { if (number < 10) return '00000000' + number; else if (number < 100) return '0000000' + number; if (number < 1000) return '000000' + number; if (number < 10000) return '00000' + number; if (number < 100000) return '0000' + number; if (number < 1000000) return '000' + number; if (number < 10000000) return '00' + number; if (number < 100000000) return '0' + number; } </script> <div id="header"> <h1 id="home-title">PollBag</h1> <h2>Know your market in minutes.. reach more people, with less money.</h2> </div> <!-- end header --> <!-- Coda slider wrapper --> <div class="coda-slider-wrapper"> <!-- Coda slider --> <div class="coda-slider" id="coda-slider-1" style="height: 147px; "> <!-- COUNT DOWN PANEL --> <div class="panel-container" style="width: 2880px; "> <div class="panel" style="display: block; "> <div class="panel-wrapper"> <div id="defaultCountdown" class="hasCountdown"> <div id="t7_timer"> <div id="t7_vals"> <div id="t7_d" class="t7_numbs">0000</div> <div class="colon">&nbsp;</div> <div id="t7_h" class="t7_numbs">000</div> <div class="colon">&nbsp;</div> <div id="t7_m" class="t7_numbs">00</div> </div> <div id="t7_timer_over"></div> </div> </div> </div> </div> <div class="panel" style="display: block; "></div> <div class="panel" style="display: block; "></div> </div> </div><!-- End coda-slider --> </div><!-- End coda-slider-wrapper --> <span id="description">People answering right now</span> <div style="text-align: center;"> <a href="<?php $GLOBALS["baseURL"] ?>signup" class="btn btn-warning btn-large">Start asking for free</a> </div> <file_sep>/mobile/php/inicio.php <?php class inicio{ var $contentType = ""; function getContenido($a) { switch ($a) { default: $this->home(); } } function home() { global $lang_switch, $cw, $siteDescription, $siteKeywords, $liveSite, $appapikey, $appID; require_once 'lib/util.class.php'; require_once 'lib/plugin.class.php'; $siteDescription = $cw->wr('siteDescription', false); $siteKeywords = $cw->wr('siteKeywords', false); require_once("lib/fb/facebook.php"); $config = array(); $config['appId'] = $appID; $config['secret'] = $appapikey; $config['fileUpload'] = false; // optional $facebook = new Facebook($config); try { $me = $facebook->api('/me'); if ($me) { if(isset($_SESSION['user']) && $_SESSION['user']->roleName == "consumer"){//user logeado header('Location: '.$liveSite.'polls/'); }else{//user no logeado $this->sign_in_form(); } }else{ $this->sign_in_form(); } }catch (FacebookApiException $e){ $this->sign_in_form(); } } function sign_in_form(){ $this->contentType = "html"; require_once("html/inicio.html.php"); inicioHTML::sing_ing(); } } ?><file_sep>/mobile/php/html/facebook_connect.html.php <?php class FacebookConnectHTML { static function connect(){ global $appapikey, $liveSite; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"> <body> <div id="fb-root"></div> <script> var channel_path = '<?php echo $liveSite; ?>?opcion=gatewayFB&a=connect&xd_receiver=true'; window.fbAsyncInit = function() { FB.init({ appId : '<?php echo $appapikey; ?>', // App ID channelUrl : channel_path, // Channel File status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true // parse XFBML }); FB.login(function(response) { if (response.authResponse) { console.log('Welcome! Fetching your information.... '); FB.api('/me', function(response) { console.log('Good to see you, ' + response.name + '.'); }); } else { console.log('User cancelled login or did not fully authorize.'); } }); /* FB.Event.subscribe('auth.login', function (response) { // do something with response alert("login success"); }); FB.Event.subscribe('auth.logout', function (response) { // do something with response alert("logout success"); }); */ // Additional initialization code here }; // Load the SDK Asynchronously (function(d){ var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true; js.src = "http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php";//"//connect.facebook.net/en_US/all.js"; ref.parentNode.insertBefore(js, ref); }(document)); </script> <div class="fb-login-button" data-show-faces="false" data-width="200" data-max-rows="1"></div> </body> </html> <?php } static function incluirPermisos($fb) { global $GA, $siteTitle, $appID, $appapikey, $appsecret, $liveSite; ?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"> <head> </head> <body> <div id="fb-root"></div> <script> window.fbAsyncInit = function() { FB.init({ appId : '<?php echo $appapikey; ?>', // App ID channelUrl : channel_path, // Channel File status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true // parse XFBML }); // Additional initialization code here }; // Load the SDK Asynchronously (function(d){ var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_US/all.js"; ref.parentNode.insertBefore(js, ref); }(document)); </script> <script type="text/javascript"> FB.login(function(response) { alert("login...") }, {scope: 'email,user_likes'}); </script> </body> </html> <?php } static function xd_receiver() { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>xd</title> </head> <body> <script src="//connect.facebook.net/en_US/all.js"></script> </body> </html> <?php } } ?><file_sep>/mobile/plantilla_admin.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="es"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="description" name="description" content="<?php echo $siteDescription; ?>" /> <meta http-equiv="keywords" name="keywords" content="<?php echo $siteKeywords; ?>" /> <title>Administrador - <?php echo $siteTitle; ?></title> <link rel="shortcut icon" href="<?php echo $liveSite; ?>imagenes/favicon.ico"> <script> var liveSite = '<?php echo $liveSite; ?>'; </script> <script type="text/javascript" src="<?php echo $liveSite; ?>js/swfobject.js"></script> <script type="text/javascript" src="<?php echo $liveSite; ?>js/swfaddress.js"></script> <script type="text/javascript" src="<?php echo $liveSite; ?>js/mootools-1.2.4.js"></script> <script type="text/javascript" src="<?php echo $liveSite; ?>js/mootools-1.2.4.2-more.js"></script> <script type="text/javascript" src="<?php echo $liveSite; ?>js/light_box.js"></script> <script type="text/javascript" src="<?php echo $liveSite; ?>js/utilities.js"></script> <script type="text/javascript" src="<?php echo $liveSite; ?>js/tinymce/tiny_mce.js"></script> <script type="text/javascript" src="<?php echo $liveSite; ?>js/tinyMCEconf.js" ></script> <script type="text/javascript" src="<?php echo $liveSite; ?>js/datepicker.js"></script> <link rel="stylesheet" href="<?php echo $liveSite; ?>css/reset.css" /> <link rel="stylesheet" href="<?php echo $liveSite; ?>css/text.css" /> <link rel="stylesheet" href="<?php echo $liveSite; ?>css/960.css" /> <link rel="stylesheet" href="<?php echo $liveSite; ?>css/layout.css" /> <link rel="stylesheet" href="<?php echo $liveSite; ?>css/admin.css" /> <link rel="stylesheet" href="<?php echo $liveSite; ?>css/menu.css" /> <link rel="stylesheet" type="text/css" href="<?php echo $liveSite; ?>css/light_box_alertas.css" /> <link href="<?php echo $liveSite; ?>css/datepicker/datepicker_dashboard.css" rel="stylesheet" type="text/css" media="screen" /> <link rel="stylesheet" href="<?php echo $liveSite; ?>css/formcheck/theme/red/formcheck.css" type="text/css" media="screen" /> <script type="text/javascript" src="<?php echo $liveSite; ?>js/formcheck/lang/es.js"> </script> <script type="text/javascript" src="<?php echo $liveSite; ?>js/formcheck/formcheck.js"> </script> </head> <body class="wood"> <div id="brand" class="container_12"> <div id="logo_cont" class="grid_3"> <h1 title="<?php echo $siteTitle; ?>" id="logo" class="grid_3 alpha"> <a href="<?php echo $liveSite; ?>admin/"> <img src="<?php echo $liveSite; ?>imagenes/logo.png" width="300" border="0" height="83" alt="<?php echo $siteTitle; ?>"/> </a> </h1> </div> <div class="grid_9"> <div class="grid_4 alpha"> &nbsp; </div> <div id="top_search" class="grid_5 omega"> <?php if($_SESSION['admin_logeado']){ require_once 'php/admin.php'; $admin = new Admin(); $mensajes = $admin->get_inbox(); ?> Bienvenido <strong><?php echo $_SESSION['admin_nombre']; ?></strong> - <a href="<?php echo $liveSite; ?>admin/inbox/"><strong><?php echo count($mensajes); ?></strong> mensajes nuevos</a> - <a href="<?php echo $liveSite; ?>admin/salir/">Salir</a> <?php } ?> </div> </div> <?php if ($_SESSION['admin_logeado']){ ?> <div class="main_menu grid_12"> <?php require_once('php/menu.php'); $m = new Menu(); $m->getContenido('admin'); ?> </div> <?php } ?> <div class="clear" ></div> </div> </div> <div class="contenido container_12"> <br /> <!-- COmienza COntenido --> <?php echo $contenido; ?> <!-- Fin Contenido --> <hr class="grid_12" /> <div class="clear"></div> <center> <a href="http://mail.gangasinc.com" target="_blank">Email</a> - <a href="http://calendar.gangasinc.com" target="_blank">Calendario</a> - <a href="http://docs.gangasinc.com" target="_blank">Documentos</a> </center> <br /> </div> <?php if(isset($_SESSION['msj'])){ ?> <script> mostrarAlerta('<?php echo $_SESSION['msj']; ?>'); </script> <?php unset($_SESSION['msj']); }?> </body> </html><file_sep>/web/delegate/QRDelegate.delegate.php <?php require_once('BaseDelegate.delegate.php'); require_once('plugins/bitly/bitly.php'); class QRDelegate extends BaseDelegate { function generate($validator) { $latitude = $validator->getVar("latitude"); $longitude = $validator->getVar("longitude"); $locationType = $validator->getVar("location_type"); $locationName = $validator->getVar("location_name"); $type = $validator->getVar("type"); $installed = $validator->getCheckbox("installed"); $qr = new QRCode(); $qr->latitude = $latitude; $qr->longitude = $longitude; $qr->location_type = $locationType; $qr->location_name = $locationName; $qr->type = $type; $qr->country = 1; $qr->state = 1; $qr->munincipality = 1; $qr->zone = 1; $qr->save(); try { $bigURL = 'http://poopub.com/web/scan/'.$qr->id; $response = bitly_v3_shorten($bigURL); if($response) { $url = $response["url"]; $hash = $response["hash"]; $qr->url = $url; $qr->big_url = $bigURL; $qr->bitly_hash = $hash; $qr->save(); } else throw new Exception("Error creating QR"); } catch(Exception $e) { echo $e->getMessage(); } return $GLOBALS["baseURL"].'qr&id='.$qr->id; } function scan($validator) { require_once("phputils/browser.php"); $browser = new Browser(); $id = $validator->getVar("id"); $qr = Doctrine::getTable('QRCode')->find($id); if($qr) { try { $qr->last_scan = date("Y-m-d H:i:s"); $qr->save(); $sc = new Scan(); $sc->id_wc = $id; $sc->IP = $this->getRealIP(); $sc->platform = $browser->getPlatform(); $sc->user_agent = $browser->getUserAgent(); $sc->browser = $browser->getBrowser(); $sc->save(); return 'http://poopub.com/mobile/polls/'.$qr->id; } catch(Exception $e) { header('HTTP/1.0 404 Not Found'); } } header('HTTP/1.0 404 Not Found'); } function getRealIP() { $ip = 0; if (!empty($_SERVER["HTTP_CLIENT_IP"])) $ip = $_SERVER["HTTP_CLIENT_IP"]; if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) { $iplist = explode(", ", $_SERVER["HTTP_X_FORWARDED_FOR"]); if ($ip) { array_unshift($iplist, $ip); $ip = 0; } foreach($iplist as $v) if (!eregi("^(192\.168|172\.16|10|224|240|127|0)\.", $v)) return $v; } return ($ip) ? $ip : $_SERVER["REMOTE_ADDR"]; } function getQR($validator) { $id = $validator->getVar("id"); $qr = Doctrine::getTable('QRCode')->find($id); if($qr) return $qr; else return null; } function getInstalled($validator) { $q = Doctrine_Query::create()->from("QRCode q") ->where("q.instalation_date is not NULL"); $records = $q->execute(); return $records->toArray(); } function getPending($validator) { $q = Doctrine_Query::create()->from("QRCode q") ->where("q.instalation_date is NULL"); $records = $q->execute(); return $records->toArray(); } function delete($validator) { $id = $validator->getVar("id"); $qr = Doctrine::getTable('QRCode')->find($id); if($qr) { $qr->delete(); return $GLOBALS["baseURL"].'list-qr'; } else return $GLOBALS["baseURL"].'qr&id='.$qr->id; } function markInstalled($validator) { $id = $validator->getVar("id"); $qr = Doctrine::getTable('QRCode')->find($id); if($qr) { $qr->instalation_date = date("Y-m-d H:i:s"); $qr->last_maintenance = date("Y-m-d H:i:s"); $qr->save(); return $GLOBALS["baseURL"].'qr&id='.$qr->id; } else return $GLOBALS["baseURL"].'qr&id='.$qr->id; } function edit($validator) { $id = $validator->getVar("id"); $qr = Doctrine::getTable('QRCode')->find($id); if($qr) { try { $qr->state = $validator->getVar("state"); $qr->zone = $validator->getVar("zone"); $qr->country = $validator->getVar("country"); $qr->munincipality = $validator->getVar("munincipality"); $qr->save(); }catch(Exception $e) { die($e->getMessage()); } return $GLOBALS["baseURL"].'qr&id='.$qr->id; } echo "No se obtuvo el id"; } } ?><file_sep>/mobile/php/lib/basepublicobject.tpl.php <?php class {CLASS_NAME}{ var $contentType = ""; function getContenido($a) { switch ($a) { case '': $this->inicio_{nombre_seccion}(); break; default: require_once 'php/lib/not_found.exception.php'; throw new NotFoundException(); } } function inicio_{nombre_seccion}(){ require_once 'lib/util.class.php'; global $pathway; $pathway->add_last_branch(__CLASS__); $result = Util::query("SELECT * FROM {tabla} WHERE {campo_publicado} = 1"); $objs = array(); while($o = mysql_fetch_object($result)){ $objs[] = $o; } $this->contentType = "html"; require_once 'php/html/{html_file}.html.php'; {CLASS_NAME}HTML::inicio($objs); echo __CLASS__; } function detalle(){ require_once 'lib/util.class.php'; $obj = Util::sql2obj("SELECT * FROM {tabla} WHERE {campo_id} = ".Util::secureValue($_GET['id'])." and publicado = 1"); if(is_object($obj)) { global $pathway; $pathway->add_branch('{CLASS_NAME}', $liveSite.'{nombre_seccion}/', '{CLASS_NAME}'); //$pathway->add_last_branch($obj->titulo); $this->contentType = "html"; require_once 'html/{nombre_seccion}.html.php'; {CLASS_NAME}HTML::detalle($obj); }else { require_once 'php/lib/not_found.exception.php'; throw new NotFoundException(); } } } ?><file_sep>/mobile/php/lib/no_disponible.exception.php <?php class NoDisponibleException extends Exception { function NoDisponibleException($id, $disp, $cant){ $this->code = "NO_DISP"; $this->id_articulo = $id; $this->id_disponible = $disp; $this->cant = $cant; $this->message = "No hay existencias disponibles para el articulo ".$this->id_articulo; } public function __toString() { return __CLASS__ . ": [{$this->code}::{$this->id_articulo}]: {$this->message}\n"; } } ?><file_sep>/mobile/php/polls.php <?php class polls{ var $contentType = ""; function getContenido($a) { switch ($a) { case "": $this->make_poll(); break; case "poll_data": $this->poll_data(); break; case "answer": $this->answer(); break; case "about": $this->about(); break; case "refresh_credit": $this->refresh_credit(); break; default: $this->parse_qr($a); } } function about(){ global $liveSite; $this->contentType = "html"; require_once("html/polls.html.php"); pollsHTML::about(); } function parse_qr($cod){ global $liveSite; $qr = Util::secureValue($cod); //echo "QR: $qr ---"; $_SESSION['qr'] = $qr; //echo "sesss"; //print_r($_SESSION); //echo "por aquí<a href='".$liveSite."?".$qr."'>continuar...</a>"; //echo "Funcioonaaaaa!!"; header("Location: ".$liveSite); } function answer(){ $poll = new StdClass(); $poll->id = 1; $poll->codigo = 200; echo json_encode($poll); } function poll_data(){ $poll = new StdClass(); $poll->id = 1; $poll->code = 200; $poll->data = new StdClass(); $poll->data->poll = new StdClass(); $poll->data->poll->id= "123"; $poll->data->poll->question= "Mi red social favorita es:"; $poll->data->options = array(); $nets = array("Facebook", "Twitter", "Pinterest"); for($i =0; $i < 3; $i++){ $o = new StdClass(); $o->id = $i+1; $o->answer = $nets[$i]; $poll->data->options[] = $o; } echo json_encode($poll); } function refresh_credit(){ $poll = new StdClass(); $poll->code = 200; $poll->data = 14; echo json_encode($poll); } function make_poll() { global $appID, $appapikey, $liveSite; /* require_once("lib/fb/facebook.php"); $facebook = new Facebook(array( 'appId' => $appID, 'secret' => $appapikey, )); $user = $facebook->getUser(); print_r($user); print_r($_REQUEST); return; if (!$user){ header('Location: '.$liveSite); } try { // Proceed knowing you have a logged in user who's authenticated. $user_profile = $facebook->api('/me'); } catch (FacebookApiException $e) { error_log($e); $user = null; } */ global $lang_switch, $cw, $siteDescription, $siteKeywords, $liveSite; require_once 'lib/util.class.php'; require_once 'lib/plugin.class.php'; $siteDescription = $cw->wr('siteDescription', false); $siteKeywords = $cw->wr('siteKeywords', false); require_once('../web/phputils/CocoasUser.class.php'); if(isset($_SESSION['user']) && $_SESSION['user']->roleName == "consumer"){//user logeado $this->contentType = "html"; require_once("html/polls.html.php"); pollsHTML::make_poll(); }else{//user no logeado header("Location: ".$liveSite); } } } ?><file_sep>/mobile/php/lib/control.html.php <?php class ControlHTML{ static function render_text_field($label, $value, $required = true, $enabled =true){ ?> <div class="grid_2 alpha"> <label for="<?php echo $label; ?>"><?php echo $label; ?></label> <br /> </div> <div class="grid_8 omega"> <input name="<?php echo $label; ?>" type="text" class="<?php if($required){ ?>validate['required']<?php } ?>" <?php if(!$enabled){ ?>disabled="disabled"<?php } ?> id="<?php echo $label; ?>" size="50" value="<?php echo $value; ?>"> <br /> <br /> </div> <div class="clear"></div> <?php } static function render_fecha($label, $value, $required = true, $enabled =true){ ?> <div class="grid_2 alpha"> <label for="<?php echo $label; ?>"><?php echo $label; ?></label> <br /> </div> <div class="grid_8 omega"> <input id="<?php echo $label; ?>" name="<?php echo $label; ?>" type="text" size="50" class="picker_field_<?php echo $label; ?> <?php if($required){ ?>validate['required']<?php } ?>" value="<?php echo $value; ?>"> <br /> <br /> </div> <div class="clear"></div> <script type="text/javascript"> window.addEvent('domready', function(){ new DatePicker($$('.picker_field_<?php echo $label; ?>'), { pickerClass: 'datepicker_dashboard', startView: 'decades', timePicker: false, inputOutputFormat: 'Y/m/d H:i:s', format: 'Y/m/d H:i:s', days: ['Domingo', 'Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado'], months: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'], allowEmpty: true }); }); </script> <?php } static function render_text($label, $value, $required = true, $enabled =true){ ?> <div class="grid_2 alpha"> <label for="<?php echo $label; ?>"><?php echo $label; ?></label> </div> <div class="grid_8 omega"> <textarea name="<?php echo $label; ?>" cols="50" rows="10" <?php if(!$enabled){ ?>disabled="disabled"<?php } ?> class="<?php if($required){ ?>validate['required']<?php } ?>" id="<?php echo $label; ?>"><?php echo $value; ?></textarea> <br /><br /> </div> <div class="clear"></div> <?php } static function render_password($label, $value, $required = true, $enabled =true){ ?> <div class="grid_2 alpha"> <label for="<?php echo $label; ?>"><?php echo $label; ?></label> <br /> </div> <div class="grid_8 omega"> <input name="<?php echo $label; ?>" type="password" class="<?php if($required){ ?>validate['required']<?php } ?>" <?php if(!$enabled){ ?>disabled="disabled"<?php } ?> id="<?php echo $label; ?>" size="50" value="<?php echo $value; ?>"> <br /> <br /> </div> <div class="clear"></div> <?php } static function render_email($label, $value, $required = true, $enabled =true){ ?> <div class="grid_2 alpha"> <label for="<?php echo $label; ?>"><?php echo $label; ?></label> <br /> </div> <div class="grid_8 omega"> <input name="<?php echo $label; ?>" type="password" class="validate[<?php if($required){ ?>'required',<?php } ?>'email']" <?php if(!$enabled){ ?>disabled="disabled"<?php } ?> id="<?php echo $label; ?>" size="50" value="<?php echo $value; ?>"> <br /> <br /> </div> <div class="clear"></div> <?php } static function render_html_text($label, $value, $required = true, $enabled =true){ ?> <div class="grid_2 alpha"> <label for="<?php echo $label; ?>"><?php echo $label; ?></label> </div> <div class="grid_8 omega"> <textarea name="<?php echo $label; ?>" cols="50" rows="10" class="<?php if($required){ ?>validate['required']<?php } ?>" <?php if(!$enabled){ ?>disabled="disabled"<?php } ?> id="<?php echo $label; ?>"><?php echo $value; ?></textarea> <br /><br /> </div> <div class="clear"></div> <script type="text/javascript"> html_areas = (html_areas == "") ? '<?php echo $label; ?>': html_areas+',<?php echo $label; ?>'; </script> <?php } static function render_lista($label, $value, $opciones, $required = true, $enabled =true){ ?> <div class="grid_2 alpha"> <label for="<?php echo $label; ?>"><?php echo $label; ?></label> </div> <div class="grid_8 omega"> <select name="<?php echo $label; ?>" id="<?php echo $label; ?>" class="<?php if($required){ ?>validate['required']<?php } ?>" <?php if(!$enabled){ ?>disabled="disabled"<?php } ?>> <option value="">-- Seleccione --</option> <?php foreach($opciones as $o){?> <option value="<?php echo $o['id']; ?>" <?php if($o['id'] == $value){?> selected="selected" <?php }?>><?php echo $o['label']; ?></option> <?php } ?> </select> <br /><br /> </div> <div class="clear"></div> <?php } static function render_lista_multiple($label, $value, $opciones, $required = true, $enabled =true){ ?> <div class="grid_2 alpha"> <label for="<?php echo $label; ?>"><?php echo $label; ?></label> </div> <div class="grid_8 omega"> <select name="<?php echo $label; ?>[]" id="<?php echo $label; ?>" multiple="multiple" class="<?php if($required){ ?>validate['required']<?php } ?>" <?php if(!$enabled){ ?>disabled="disabled"<?php } ?>> <?php foreach($opciones as $o){ ?> <option value="<?php echo $o['id']; ?>" <?php if( in_array($o['id'],$value)){?> selected="selected" <?php }?>><?php echo $o['label']; ?></option> <?php } ?> </select> <br /><br /> </div> <div class="clear"></div> <?php } static function render_archivo($label, $value, $required = true, $enabled =true){ global $liveSite; ?> <div class="grid_2 alpha"> <label for="<?php echo $label; ?>"><?php echo $label; ?></label> <br /> </div> <div class="grid_8 omega"> <input type="file" name="<?php echo $label; ?>" id="<?php echo $label; ?>" class="<?php if($required){ ?>validate['required']<?php } ?>" <?php if(!$enabled){ ?>disabled="disabled"<?php } ?> /> <?php if(!$required) { ?> <a href="<?php echo $value; ?>" target="_blank">Ver actual</a> <?php } ?> <br /> <br /> </div> <div class="clear"></div> <?php } } ?><file_sep>/web/view/qrcode/list.php <h1 style="text-align: right;"><a href="<?php echo $GLOBALS["baseURL"] ?>create">Create QRCode</a></h1> <h2>Pending installations</h2> <?php if($vars["pending_wcs"]) { ?> <?php foreach($vars["pending_wcs"] as $wc) { ?> <p> <a href="<?php echo $GLOBALS["baseURL"] ?>qr&id=<?php echo $wc["id"]; ?>">Nombre: <?php echo $wc["location_name"]; ?></a> </p> <?php } ?> <?php } else { ?> <p>No QRCodes.</p> <?php } ?> <h2>Installed QRCodes</h2> <?php if($vars["installed_wcs"]) { ?> <?php foreach($vars["installed_wcs"] as $wc) { ?> <p> <a href="<?php echo $GLOBALS["baseURL"] ?>qr&id=<?php echo $wc["id"]; ?>">Nombre: <?php echo $wc["location_name"]; ?></a> </p> <?php } ?> <?php } else { ?> <p>No se encontró ningún QR instalado.</p> <?php } ?><file_sep>/mobile/php/admin.php <?php class Admin{ var $contentType = ""; var $session_limit = 600; function Admin(){ global $session_limit; if(isset($session_limit)) $this->session_limit = $session_limit; require_once 'lib/util.class.php'; } function getContenido($a) { global $def_tpl; session_write_close(); session_name("admin"); session_start(); $def_tpl = "plantilla_admin.php"; if($a == "login"){ $this->login(); }else{ $logeado = $this->verificar_login(); if($logeado === true){ switch ($a) { case "salir": $this->salir(); break; case "inbox": $this->inbox(); break; case "usuarios": $this->usuarios(); break; case "": $this->home_admin(); break; default: $this->find_seccion($a); } }else $this->login_form($logeado); } } function find_seccion($secc){ if(file_exists('php/'.$secc.'.admin.php')){ require_once $secc.'.admin.php'; $class = ucfirst($secc); $i = new $class(); if(isset($_GET['a_'])) $i->getContenido($_GET['a_']); else $i->getContenido(""); $this->contentType = $i->contentType; }else{ require_once 'php/lib/not_found.exception.php'; throw new NotFoundException(); } } /* Usuarios */ function usuarios(){ require_once 'usuarios.php'; $i = new Usuarios(); if(isset($_GET['a_'])) $i->getContenido(Util::secureValue($_GET['a_'])); else $i->getContenido(""); $this->contentType = $i->contentType; } /* Contenidos */ function contenidos(){ require_once 'contenidos.php'; $i = new Contenidos(); if(isset($_GET['contenidos_a'])) $i->getContenido($_GET['contenidos_a']); else $i->getContenido(""); $this->contentType = $i->contentType; } /* Inbox */ function inbox(){ require_once 'inbox.php'; $i = new Inbox(); if(isset($_GET['inbox_a'])) $i->getContenido($_GET['inbox_a']); else $i->getContenido(""); $this->contentType = $i->contentType; } function home_admin(){ $this->contentType = "html"; require_once 'html/admin.html.php'; AdminHTML::home_admin($this->get_inbox()); } function get_inbox(){ //$sql = "SELECT * FROM mensajes WHERE estado = 0 LIMIT 0, 10"; //$mensajes = Util::sql2array($sql); return array();//$mensajes; } /* Login */ function login(){ if(!isset($_POST['user'])){ global $liveSite; header("Location: ".$liveSite."admin/"); exit; } require_once 'lib/util.class.php'; $sql = "SELECT * FROM admin_usuarios WHERE email like '".Util::secureValue($_POST['user'])."'"; $result = Util::query($sql); if(mysql_num_rows($result) == 0){ $this->login_form("Usuario inexistente"); return; } $user = mysql_fetch_object($result); if($user->password == md5(Util::secureValue($_POST['password']))) { if($user->estado == 0) { $this->login_form("Usuario bloqueado"); return; } $_SESSION['admin_nombre'] = $user->nombre." ".$user->apellido; $_SESSION['admin_logeado'] = true; $_SESSION['admin_UID'] = $user->id_usuario; $_SESSION['admin_last_seen'] = time(); global $liveSite; header ('Location: '.$liveSite.'admin/'); }else{ $this->login_form("Password incorrecto"); return; } } function logout(){ $_SESSION['admin_logeado'] = false; $_SESSION['admin_last_seen'] = 0; unset($_SESSION['admin_last_seen']); $_SESSION['admin_nombre'] = ""; unset($_SESSION['admin_nombre']); session_write_close(); } function salir(){ $this->logout(); global $liveSite; header("Location: ".$liveSite."admin/"); exit; } function login_form($msj = ""){ $this->contentType = "html"; //$this->logout(); require_once 'html/admin.html.php'; AdminHTML::login_form($msj); } function verificar_login(){ //echo "verificando login.."; if(isset($_SESSION['admin_logeado']) && isset($_SESSION['admin_last_seen'])){ $now = time(); $limit = $_SESSION['admin_last_seen'] + $this->session_limit; if( $limit > $now ) { $_SESSION['admin_last_seen'] = time(); return true; }else{ $this->logout(); return false; } }else{ $this->logout(); return false; } } } ?><file_sep>/mobile/php/lib/orden.class.php <?php class Orden{ var $articulos = array(); private $total = 0; var $id_orden; var $tipo_pago; var $tipo_envio; var $UID; var $id_estado; var $estado; var $fecha_creacion; var $fecha_envio; var $moneda; var $ref = ""; var $descuento = 0; var $descuento_tipo = 0; var $descuento_porcentaje = 0; var $id_cupon = 0; var $codigo_cupon = ''; var $stored = false; function Orden(){ $this->fecha_creacion = date("Y/m/d h:i:s"); $this->tipo_envio = 1; } function gastos_envio(){ if($this->tipo_envio == 1){ if($this->total_orden() > 300000) return 0; else if($this->total_orden() < 150000) return 7000; else if( $this->total_orden() > 150000 && $this->total_orden() < 300000) return 11000; }else{ return 0; } } function total_articulos(){ $t = 0; foreach($this->articulos as $a){ $t += array_sum($a->items); } return $t; } function recalcular_precio(){ $this->total = 0; foreach($this->articulos as $a){ $this->total += (array_sum($a->items) * $a->costo_unitario); } if($this->id_cupon != 0) $this->total = $this->total-$this->descuento; } function total_orden(){ $this->recalcular_precio(); return $this->total; } function iva(){ return 0; //$total = $this->total_orden()+$this->gastos_envio(); //return number_format ( $total - ($total / 1.16), 0 ,'.',''); } function base_iva(){ return 0;//$this->total_orden()+$this->gastos_envio(); //return number_format ( $total, 0 ,'.',''); //return number_format ( $total / 1.16, 0 ,'.',''); } function add_articulo($articulo,$disp){ $added = false; foreach ($this->articulos as $a){ if($a->id == $articulo->id){ $added = true; $a->fundir($articulo); } } if(!$added){ $this->articulos[] = $articulo; } $this->total += $articulo->costo; if($this->stored) $this->store(); } function remove($articulo){ $i = 0; foreach ($this->articulos as $a){ if($articulo->id == $a->id) unset($this->articulos[$i]); $i++; } if($this->stored) $this->store(); } function get_referencia(){ if(isset($_SESSION['public_UID'])){ $this->UID = $_SESSION['public_UID']; if($this->ref == '') return $this->crear_ref(); else return $this->ref; //return strtotime($this->fecha_creacion)."-".$this->UID; } else return 'Ingrese..'; } function crear_ref(){ $ors = Util::sql2obj("SELECT COUNT(id_orden) total FROM ordenes"); $this->ref = $ors->total; return $this->ref; } function llenar_existencias(){ foreach($this->articulos as $a){ $a->llenar_existencias(); } } function firma_pagos_online(){ global $enc_key, $id_pagos; $firma = "$enc_key~".$id_pagos."~".$this->get_referencia()."~".$this->total_orden()."~".$this->moneda; return md5($firma); } function descargar(){ if($this->id_cupon != 0){ $usos = Util::query("INSERT INTO cupones_usos (id_cupon, id_orden, fecha, descuento) VALUES ('$this->id_cupon', '$this->id_orden', NOW(), '$this->descuento')"); } foreach ($this->articulos as $a){ $a->descargar(); } } function aplicar_descuento($codigo){ if($this->id_cupon != 0) return false; $cupon = Util::sql2obj("SELECT * FROM cupones WHERE codigo = '$codigo'"); if(is_object($cupon)){ $usos = Util::sql2obj("SELECT COUNT(*) usos FROM cupones_usos WHERE id_cupon = '$cupon->id_cupon'"); if($cupon->usos == 0 || ( $cupon->usos > 0 && $usos->usos < $cupon->usos)){ if($cupon->por_fecha == 1){ $now = time(); $ini = strtotime($cupon->fecha_ini); $fin = strtotime($cupon->fecha_fin); if($ini < $now && $now < $fin){ return $this->aplicar_cupon($cupon); } }else{ return $this->aplicar_cupon($cupon); } }else return false; }else return false; } function aplicar_cupon($cupon){ if(intval($cupon->por_porcentaje) === 1){ $this->descuento_tipo = 1; $this->descuento_porcentaje = $cupon->valor; $this->descuento = $this->total_orden() * ($cupon->valor/100); }else{ if($this->total_orden() > $cupon->valor){//el cupón no puede valer mas $this->descuento_tipo = 0; $this->descuento = $cupon->valor; }else{ $_SESSION['msj']= "<br><br><p><strong>El precio del cupón no puede ser inferior al de la compra</strong></p><br><br><h2>Error</h2>"; return false; } } $this->id_cupon = $cupon->id_cupon; $this->codigo_cupon = $cupon->codigo; return true; } function store(){ $this->stored = true; $or_existente = Util::sql2obj("SELECT codigo FROM ordenes WHERE codigo = '".$this->get_referencia()."' LIMIT 1"); if($or_existente){ $or = Util::query("UPDATE ordenes SET id_estado = 1, fecha = NOW(), total = '".$this->total_orden()."', moneda = '".$this->moneda."', raw = '".$_SESSION['orden']."' WHERE codigo = '".$this->get_referencia()."' LIMIT 1"); }else{ $or = Util::query("INSERT INTO ordenes (UID, id_estado, fecha, codigo, tipo_pago, fecha_envio, total, moneda, raw) VALUES('".$_SESSION['public_UID']."', 1, now(), '".$this->get_referencia()."','1', '', '".$this->total_orden()."', '".$this->moneda."', '".$_SESSION['orden']."' )"); $this->id_orden = mysql_insert_id(); } } } class Articulo{ var $id = ""; var $costo_unitario = 0; var $costo = 0; var $foto = ""; var $descripcion = ""; var $nombre = ""; var $marca = ""; var $referencia = ""; var $items = array(); //var $cantidades = array(); //var $tallas = array(); var $existencias = array(); private $apuntador = 0; function Articulo($p, $disp,$cantidad){ global $liveSite; if($disp->cantidad < $cantidad){ require_once 'no_disponible.exception.php'; throw new NoDisponibleException($id, $color, $cantidad, $talla); } $this->id = $p->id; if(!$p->descuento) $this->costo_unitario = $p->precio; else $this->costo_unitario = $p->precio_descuento; $this->nombre = $p->nombre; $this->marca = $p->marca; $this->descripcion = $p->descripcion; //$this->referencia = $p->referencia;//TDOD: poner referencias de producto $foto = Util::sql2obj("SELECT * FROM productos_fotos WHERE id_producto = '".$this->id."' AND publico = 1 LIMIT 1"); if(is_object($foto)) $this->foto = $liveSite."imagenes/productos/".$p->id.'_'.$foto->id_foto.'.jpg'; else $this->foto = $liveSite."imagenes/productos/generica.jpg"; $this->add_item($p, $disp, $cantidad); } function llenar_existencias(){ $this->existencias = array(); $existencias = Util::sql2array("SELECT * FROM productos_disponibles WHERE id_producto = '".$this->id."'"); foreach($existencias as $e){ if($e->cantidad > 0) $this->existencias[$e->id_disponible] = $e; } } function add_item($p, $disp, $cant){ $this->llenar_existencias(); if( !$this->existe($disp->id_disponible, $cant)){ throw new NoDisponibleException($this->id, $disp->id_disponible, $cant); } if(!in_array($disp->id_disponible, $this->items)){ $this->items[$disp->id_disponible] = $cant; //$this->cantidades[$disp->id_disponible] = $cant; }else{ $this->items[$disp->id_disponible] += $cant; //$this->cantidades[$disp->id_disponible] += $cant; } //$this->costo = $this->costo_unitario * $cant; $this->recalcular_precio(); } function fundir($a){ $this->llenar_existencias(); foreach($a->items as $k => $i){ if(isset($this->items[$k])){ if($this->existe($k, intval($i+$this->items[$k]))) $this->items[$k] += intval($i); else throw new NoDisponibleException($this->id, $k, intval($i)); }else{ if($this->existe($k, intval($i))) $this->items[$k] = $i; else throw new NoDisponibleException($this->id, $k,intval($i)); } } //$this->costo += $a->costo; $this->recalcular_precio(); } function fetch_next_item(){ if($this->apuntador >= count($this->items)){ $this->apuntador = 0; return false; } $i = 0; foreach($this->items as $t => $it){ if($i == $this->apuntador) { $item = new stdClass(); $item->caracteristicas = json_decode($this->existencias[$t]->caracteristicas); $item->id_disponible = $this->existencias[$t]->id_disponible; $item->cantidad = $it; } $i++; } $this->apuntador++; return $item; } function edit_item($d, $cant){ if(!array_key_exists($d, $this->items)){ throw new Exception(); } foreach($this->items as $t => $it){ if(intval($t) === intval($d)){ if($this->existe($t, intval($cant))){ $this->items[$t] = intval($cant); $this->recalcular_precio(); }else throw new NoDisponibleException($this->id, $t,intval($cant)); } } } function delete_item($d){ foreach($this->items as $t => $it){ if(intval($t) === intval($d)){ unset($this->items[$t]); } } $this->recalcular_precio(); } function existe($item, $cantidad){ if(isset($this->existencias[$item])) //foreach($this->existencias as $e){ if($this->existencias[$item]->id_disponible == $item){ return ($this->existencias[$item]->cantidad >= $cantidad); //} }else return false; } function recalcular_precio(){ $this->costo = array_sum($this->items) * $this->costo_unitario; } function descargar(){ while($i = $this->fetch_next_item()){ $r = Util::query("UPDATE productos_disponibles SET cantidad = (cantidad-".$i->cantidad.") WHERE id_disponible = '$i->id_disponible'"); } } } ?><file_sep>/mobile/php/html/menu.html.php <?php class MenuHTML{ static function nav() { global $liveSite, $siteTitle, $siteName,$seccion; $opc = ($seccion =='portafolio' && (isset($_GET['id']) && intval($_GET['id']) === 1 )) ?true:false; $apoyo = ($seccion =='portafolio' && (isset($_GET['id']) && intval($_GET['id']) === 2 )) ?true:false; $training = ($seccion =='portafolio' && (isset($_GET['id']) && intval($_GET['id']) === 3 )) ?true:false; ?> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="<?php echo $liveSite; ?>"><?php echo $siteName; ?></a> <div class="nav-collapse"> <ul class="nav"> <li <?php if($seccion =='inicio'){?>class="active"<?php }?>><a href="<?php echo $liveSite; ?>">About</a></li> <li <?php if($seccion =='about'){?>class="active"<?php }?>><a href="<?php echo $liveSite; ?>polls/about/">My Account</a></li> </ul> </div><!--/.nav-collapse --> </div> </div> </div> <?php } static function nav_admin() { global $liveSite; ?> <ul id="main_nav"> <li><a href="<?php echo $liveSite; ?>admin/">Inicio</a></li> <li><a href="<?php echo $liveSite; ?>admin/contenidos/">Contenidos</a> <ul> <li><a href="<?php echo $liveSite; ?>admin/contenidos_categorias/">Categorias</a></li> </ul> </li> <li><a href="<?php echo $liveSite; ?>admin/banners/">Destacados</a></li> <li><a href="<?php echo $liveSite; ?>admin/galeria/">Fotos</a></li> <li><a href="<?php echo $liveSite; ?>admin/usuarios/">Usuarios</a></li> <?php if($_SESSION['admin_UID'] == 1){?> <li><a href="<?php echo $liveSite; ?>admin/secciones/">Secciones</a> <ul> <li><a href="<?php echo $liveSite; ?>admin/site_lang/">Idiomas</a></li> <li><a href="<?php echo $liveSite; ?>admin/site_lang_copies/">Copies</a></li> </ul> </li> <li><a href="<?php echo $liveSite; ?>admin/config/">Config</a></li> <?php } ?> </ul> <?php } } ?><file_sep>/web/delegate/UserDelegate.delegate.php <?php class UserDelegate { function getMyPoints() { $id = $_SESSION["user"]->id; $q = Doctrine_Query::create() ->from('UserPoll up') ->where("up.user_id = ?",$id); $rows = $q->execute(); $total = count($rows)*0.2; $result = array( "code" => 200, "message" => "ok", "data" => $total ); echo json_encode($result); } } ?><file_sep>/web/delegate/BaseDelegate.delegate.php <?php class BaseDelegate { var $api; function BaseDelegate() { } function getCountries($validator) { $q = Doctrine_Query::create()->from("Country"); $records = $q->execute(); return $records->toArray(); } function getStates($validator) { $q = Doctrine_Query::create()->from("State"); $records = $q->execute(); return $records->toArray(); } function getMunincipalities($validator) { $q = Doctrine_Query::create()->from("Munincipality"); $records = $q->execute(); return $records->toArray(); } function getZone($validator) { $q = Doctrine_Query::create()->from("Zone"); $records = $q->execute(); return $records->toArray(); } } ?><file_sep>/web/delegate/ValidateDelegate.delegate.php <?php class PollDelegate { } ?><file_sep>/mobile/php/html/registro.html.php <?php class registroHTML{ static function sing_ing() { global $liveSite, $cw, $appapikey; require_once 'lib/plugin.class.php'; //Plugin::get_localized_link('contacto'); ?> <div id="fb-root"></div> <script> var channel_path = '<?php echo $liveSite; ?>?opcion=gatewayFB&a=connect&xd_receiver=true'; window.fbAsyncInit = function() { FB.init({ appId : '<?php echo $appapikey; ?>', // App ID channelUrl : channel_path, // Channel File status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true // parse XFBML }); /*FB.login(function(response) { if (response.authResponse) { console.log('Welcome! Fetching your information.... '); FB.api('/me', function(response) { console.log('Good to see you, ' + response.name + '.'); }); } else { console.log('User cancelled login or did not fully authorize.'); } });*/ /* FB.Event.subscribe('auth.login', function (response) { // do something with response alert("login success"); }); FB.Event.subscribe('auth.logout', function (response) { // do something with response alert("logout success"); }); */ // Additional initialization code here }; // Load the SDK Asynchronously (function(d){ var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true; js.src = "http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php";//"//connect.facebook.net/en_US/all.js"; // js.src = "//connect.facebook.net/en_US/all.js"; ref.parentNode.insertBefore(js, ref); }(document)); !function ($) { $('body').on('click', '.btn', handler_func) function handler_func (){ FB.login(function(response) { if (response.authResponse) { console.log('Welcome! Fetching your information.... '); //top.location.href = "polls/"; FB.api('/me', function(response) { $.ajax({ type: 'POST', url: 'registro/', data: JSON.stringify(response, null, 2) }).success(function() { alert("second success"); alert('succes!!'); }).done(function() { alert('done!!'); $(this).addClass("done"); }); console.log('Good to see you, ' + response.name + '.'); for(var prop in response){ console.log(prop+": "+response[prop]); } console.log("Response: "+response); }); } else { console.log('User cancelled login or did not fully authorize.'); } }); } }(window.jQuery) </script> <header> <div class="container"> <section> <div class="row"> <div class="hero-unit white"> <h1>Bienvenido a Pollbag</h1> <p>La mejor forma de invertir tu tiempo libre.</p> <button id="sing-in" class="btn btn-large btn-primary">Ingresar con Facebook</button> </div> </div> </section> </div> </header> <?php } static function polls() { global $liveSite, $cw; require_once 'lib/plugin.class.php'; //Plugin::get_localized_link('contacto'); ?> <div class="verde"> <div class="container"> <section> <div class="row"> </div> </section> </div> </div> <?php } static function account() { global $liveSite, $cw; require_once 'lib/plugin.class.php'; //Plugin::get_localized_link('contacto'); ?> <div class="verde"> <div class="container"> <section> <div class="row"> </div> </section> </div> </div> <?php } } ?><file_sep>/mobile/php/login.php <?php class Login{ var $contentType = ""; function getContenido($a) { switch ($a) { case "ingresar": $this->ingresar(); break; case "salir": $this->salir(); break; case "recuperar": $this->recuperar(); break; case "reset_password": $this->reset_password(); break; case "reset_form": $this->reset_form(); break; case "request_form": $this->request_form(); break; case "reset_sent": $this->reset_sent(); break; case "reset_done": $this->reset_done(); break; case "verify_reset": $this->verify_reset(); break; case "password_reseted": $this->password_reseted(); break; default: $this->login_form(); /* require_once 'php/lib/not_found.exception.php'; throw new NotFoundException(); */ } } function ingresar() { global $liveSite; $_email = Util::secureValue($_POST['email']); $sql = "SELECT * FROM registro WHERE email = '".$_email."' LIMIT 1"; $result = Util::query($sql); if(mysql_num_rows($result) == 0){ echo "<script>alert('Usuario no registrado');top.location.href = '$liveSite';</script>"; return; } $user = mysql_fetch_object($result); if($user->password == md5(Util::secureValue($_POST['password']))) { if($user->intentos_fallidos >= 3){ echo "<script>alert('Usuario bloqueado por intentos de ingreso fallidos'); top.location.href = '$liveSite';</script>"; return; } $_SESSION['public_logeado'] = true; $_SESSION['public_UID'] = $user->UID; $_SESSION['public_nombre'] = $user->nombre." ".$user->apellidos; $_SESSION['public_primer_nombre'] = strpos($user->nombre,' ') ? substr($user->nombre,0, strpos($user->nombre,' ')): $user->nombre; $_SESSION['public_apellido'] = strpos($user->apellidos,' ') ? substr($user->apellidos,0, strpos($user->apellidos,' ')): $user->apellidos; $_SESSION['public_email'] = $user->email; $_SESSION['public_documento'] = $user->fac_documento; if(isset($_SESSION['orden'])) echo "<script>window.top.location.href = '".$liveSite."compras/' </script>"; else echo "<script>window.top.location.href = '$liveSite' </script>"; }else{ $result = Util::query("UPDATE registro SET intentos_fallidos = intentos_fallidos+1 WHERE email = '".$_email."' LIMIT 1"); echo "<script>alert('Password incorrecto');window.history.go(-1);</script>"; } } function salir(){ $_SESSION['public_logeado'] = false; unset($_SESSION['public_logeado']); $_SESSION['public_UID'] = 0; unset($_SESSION['public_UID']); $_SESSION['public_nombre'] = ""; unset($_SESSION['public_nombre']); echo "<script>window.history.go(-1); </script>"; } function recuperar(){ if(isset($_SESSION['k']))unset($_SESSION['k']); $this->contentType = "html"; require_once 'html/login.html.php'; LoginHTML::reset_form(); } function reset_password(){ //TODO: capturar mail verificar si existe enviar link para pasar a segundo paso de reset_password if(isset($_SESSION['k']))unset($_SESSION['k']); $email = Util::secureValue($_POST['email']); $user = Util::sql2obj("SELECT UID, nombre, email, password FROM registro WHERE email = '$email'"); if($user){ $time = date('Y-m-d H:i:s',time()); $request = Util::query("UPDATE registro set reset_request = '$time' WHERE email = '$email' LIMIT 1"); global $liveSite, $cuerpo, $emailFrom,$nombreFrom, $siteTitle; require_once('lib/mailer.class.php'); $subject = "Reestablecimiento contraseña Gangas Inc"; $key = md5($user->email.'~'.$user->nombre.'~'.$user->password.'~'.$time); $key = base64_encode($key."-".$user->UID); $link = $liveSite.'login/request_form/?key='.$key; //die($link); $cuerpo = file_get_contents('mailings/contrasena/contrasena.html'); $liveSite_ = str_replace('https','http',$liveSite); $cuerpo = str_replace('{liveSite}',$liveSite_, $cuerpo ); $cuerpo = str_replace('{nombre}',$user->nombre, $cuerpo ); $cuerpo = str_replace('{link}',$link, $cuerpo ); $sent = Mailer::send_mail($cuerpo,$emailFrom,$nombreFrom,$email,$user->nombre,$subject); if($sent) echo "<script>window.location.href = '".$liveSite."login/reset_sent/';</script>"; else trigger_error($envio,E_USER_ERROR); }else{ global $pathway,$liveSite; $pathway->add_branch('Reestablecer contrase&ntilde;a', $liveSite."login/recuperar/", 'Reestablecer contrase&ntilde;a'); $pathway->add_last_branch('Error usuario desconocido'); $this->contentType = "html"; require_once 'html/login.html.php'; LoginHTML::not_known(); } } function request_form(){ global $liveSite; if(isset($_GET['key'])){ $k_link = Util::secureValue($_GET['key']); $k = base64_decode($k_link); $k = explode('-',$k); $user = Util::sql2obj('SELECT UID, email, password, nombre, estado, reset_request FROM registro WHERE UID = "'.intval($k[1]).'"'); if(!$user){ echo "<script>alert('Este link ya no tiene validez. Debe iniciar de nuevo el proceso de reestablecimiento.'); top.location.href = '".$liveSite."';</script>"; } $key = md5($user->email.'~'.$user->nombre.'~'.$user->password.'~'.$user->reset_request); if($key === $k[0]){ $request = Util::query("UPDATE registro set reset_request = '0000-00-00 00:00:00' WHERE email = '$user->email' LIMIT 1"); $_SESSION['k'] = $k_link; global $pathway; $pathway->add_last_branch('Reestablezca su contrase&ntilde;a'); $this->contentType = "html"; require_once 'html/login.html.php'; LoginHTML::request_form(); }else{ echo "<script>alert('Este link ya no tiene validez. Debe iniciar de nuevo el proceso de reestablecimiento.'); top.location.href = '".$liveSite."';</script>"; } } } function reset_form(){ $this->contentType = "html"; require_once 'html/login.html.php'; LoginHTML::reset_form(); } function verify_reset(){ global $liveSite; if(isset($_SESSION['k']) && isset($_POST['password'])) { $k = base64_decode(Util::secureValue($_SESSION['k'])); unset($_SESSION['k']); $k = explode('-',$k); $user = Util::sql2obj('SELECT UID, email, password, nombre, estado FROM registro WHERE UID = "'.intval($k[1]).'"'); if(!$user){ echo "<script>alert('Este link ya no tiene validez. Debe iniciar de nuevo el proceso de reestablecimiento.'); top.location.href = '".$liveSite."';</script>"; return; } if($user->estado != 1)//TODO: verificar... $r = Util::query('UPDATE registro SET estado = 1 WHERE UID = "'.$user->UID.'" LIMIT 1'); $r = Util::query('UPDATE registro SET password = MD5("'.Util::secureValue($_POST['password']).'") WHERE UID = "'.$user->UID.'" LIMIT 1'); if($r) echo "<script>window.top.location.href = '".$liveSite."login/reset_done/';</script>"; else trigger_error("Error interno del sistema",E_USER_ERROR); }else{ echo "<script>window.top.location.href = '".$liveSite."login/recuperar/';</script>"; return; } } function reset_done(){ global $pathway; $pathway->add_last_branch('Contrase&ntilde;a reestablecida'); $this->contentType = "html"; require_once 'html/login.html.php'; LoginHTML::reset_done(); } function reset_sent(){ global $pathway; $pathway->add_last_branch('Reestablecimiento de contrase&ntilde;a iniciado'); $this->contentType = "html"; require_once 'html/login.html.php'; LoginHTML::reset_sent(); } function login_form(){ global $pathway; $pathway->add_last_branch('Ingreso'); $this->contentType = "html"; require_once 'html/login.html.php'; LoginHTML::login_form(); } /*function password_reseted(){ global $pathway; $pathway->add_last_branch('Reestablecimiento de contrase&ntilde;a iniciado'); $this->contentType = "html"; require_once 'html/login.html.php'; LoginHTML::password_reseted(); }*/ } ?><file_sep>/mobile/php/lib/lang_switch.html.php <?php class LangSwitchHTML{ function render_switch($langs){ global $liveSite; foreach($langs as $l){ ?> <a href="<?php echo $l['href']; ?>" class="<?php echo $l['class']; ?>" style="background-image: url(<?php echo $liveSite; ?>imagenes/site_lang/<?php echo $l['imagen'];?>);" title="<?php echo $l['nombre']; ?>"><?php echo $l['lang'];?></a> <?php } } } ?>
908c5a777dbbe688967e2399281c07df3e2b6ad8
[ "JavaScript", "PHP" ]
59
PHP
alexmilano/pollbag
cf8d7cd1a37c474e65737f3610739a27b16546f2
3022566090f81e1db928256c4ab3c85a8c5f2c09
refs/heads/master
<file_sep>#!/bin/sh oracle_id=$1 install_path=`pwd`"/definitions" log_file=`basename $0 | awk -F '.' '{print $1}'`".log" lct_file='' # ------------------------------------------- # Function # Set_Nls_Lang # Purpose # Set NLS_LANG between utf8 and gbk # ------------------------------------------- Set_Nls_Lang() { if [ "$1" = "utf8" ]; then NLS_LANG="AMERICAN_AMERICA.AL32UTF8" elif [ "$1" = "gbk" ]; then NLS_LANG="AMERICAN_AMERICA.ZHS16GBK" fi export NLS_LANG } # ------------------------------------------- # Function # Set_Nls_Lang # Purpose # Set NLS_LANG between utf8 and gbk # ------------------------------------------- Get_Lct_Filename() { cfg_prefix=$1 echo "Executing command: sed -n '/^$cfg_prefix=/p' run_fndload.cfg | awk -F'=' '{print \$2}'" >> $log_file lct_file=`sed -n "/^${cfg_prefix}=/p" run_fndload.cfg | awk -F'=' '{print $2}'` lct_file=`eval echo $lct_file` echo "Get lct file $lct_file" >> $log_file } echo "Start uploading..." ls definitions/*.ldt | while read ldt_file do ldt_file_name=`basename $ldt_file` ldt_prefix=`echo $ldt_file_name | awk -F'_' '{print $1}'` lct_file='' echo "-----------------------------------------------" >> $log_file echo " Processing file $ldt_file_name" >> $log_file echo "-----------------------------------------------" >> $log_file # Get corresponding control file name Get_Lct_Filename "$ldt_prefix" if [ -z $lct_file ]; then printf "\n Unsupported ldt prefix: $ldt_prefix\n\n" >> $log_file else # Detect file encoding file_encoding=`file -bi $install_path/$ldt_file_name | awk -F'=' '{print $2}'` echo "File encoding is $file_encoding" >> $log_file # Switch NLS_LANG if [ $file_encoding = 'us-ascii' ] || [ $file_encoding = 'utf-8' ]; then Set_Nls_Lang "utf8" else Set_Nls_Lang "gbk" fi echo "Executing command: " >> $log_file echo "FNDLOAD apps/**** 0 Y UPLOAD $lct_file $install_path/$ldt_file_name CUSTOM_MODE=FORCE" >> $log_file FNDLOAD $oracle_id 0 Y UPLOAD $lct_file $install_path/$ldt_file_name CUSTOM_MODE=FORCE >> $log_file 2>&1 fi done echo 'Moving log files to log folder...' if [ ! -d log ]; then mkdir log fi mv *.log ./log printf 'Upload complete.\n\n' <file_sep>fndload-utils ============= 小工具一枚,可以对文件夹内的ldt文件进行批量FNDLOAD上传。 使用方法 ------------- sh ./fndload-utils.sh <apps>/<PASSWORD> 特点 ------------- * 批量执行 * 根据配置文件fndload-utils.cfg对ldt文件根据文件名前缀进行分类,以获取正确的控制文件(*.lct) 举例,比如要上传FND Message数据,那么文件名应以MSG作为前缀,如MSG_XXAP_SAMPLE_MSG.ldt,以此类推,详细请参考配置文件fndload-utils.cfg
fcf3602c9a1c9c430cc6289a82eb3e9c21fd55e6
[ "Markdown", "Shell" ]
2
Shell
eliu/fndload-utils
d19260456f4834b26931884ff875c40d20a062ad
aad1c8e8f855286e041d8f8b4fda01641df25a5c
refs/heads/master
<repo_name>mindaugasdirg/keeper-server<file_sep>/source/Keeper.WebApi/Services/IUsersService.cs using System.Threading.Tasks; using Keeper.WebApi.Models; namespace Keeper.WebApi.Services { public interface IUsersService { Task<string> CreateAsync(string secret); Task<bool> ExistsAsync(string username); Task<string> LoginAsync(LoginForm login); } }<file_sep>/source/Keeper.WebApi/Models/LoginForm.cs namespace Keeper.WebApi.Models { public class LoginForm { public string Key { get; set; } public string Secret { get; set; } } }<file_sep>/source/Keeper.WebApi/Models/Transaction.cs using System.ComponentModel.DataAnnotations; using System.Text.Json.Serialization; using Microsoft.AspNetCore.Identity; namespace Keeper.WebApi.Models { public class Transaction { [Required] [Key] public int Id { get; set; } [Required] public string Data { get; set; } [Required] [JsonIgnore] public IdentityUser Profile { get; set; } [Required] [JsonIgnore] public string ProfileId { get; set; } } }<file_sep>/source/Keeper.WebApi/DatabaseContext.cs using Keeper.WebApi.Models; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace Keeper.WebApi { public class DatabaseContext : IdentityDbContext { public DbSet<Transaction> Transactions { get; set; } public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options) { } } }<file_sep>/source/Keeper.WebApi/Services/ITransactionsService.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Keeper.WebApi.Models; using Microsoft.AspNetCore.Identity; namespace Keeper.WebApi.Services { public interface ITransactionsService { Task<int> AddAsync(string id, string newTransaction); IEnumerable<Transaction> GetTransactionsFrom(string userId, int id); } }<file_sep>/source/Keeper.WebApi/Constants.cs namespace Keeper.WebApi { public static class Constants { public const string CONN_STR = "DATABASE_URL"; } }<file_sep>/source/Keeper.WebApi/Startup.cs using System; using System.Text; using Keeper.WebApi.Services; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; namespace Keeper.WebApi { public class Startup { public Startup(IConfiguration configuration, IWebHostEnvironment env) { Configuration = configuration; Env = env; } public IConfiguration Configuration { get; } public IWebHostEnvironment Env { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { if(Env.IsDevelopment()) services.AddDbContext<DatabaseContext>(options => options.UseInMemoryDatabase("InMemory")); else services.AddDbContext<DatabaseContext>(options => options.UseNpgsql(GetConnectionString())); Console.WriteLine(GetConnectionString()); services.AddDefaultIdentity<IdentityUser>(options => { options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; }) .AddEntityFrameworkStores<DatabaseContext>() .AddDefaultTokenProviders(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = Configuration["Issuer"], ValidAudience = Configuration["Issuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"])), ClockSkew = TimeSpan.Zero }; }); services.AddTransient<ITransactionsService, TransactionsService>(); services.AddTransient<IUsersService, UsersService>(); services.AddTransient<ISecurityService, SecurityService>(); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); if (!(Environment.GetEnvironmentVariable(Constants.CONN_STR) is null)) UpdateDatabase(app); } private void UpdateDatabase(IApplicationBuilder app) { Console.WriteLine("Applying migrations"); using (var serviceScope = app.ApplicationServices .GetRequiredService<IServiceScopeFactory>() .CreateScope()) { using (var context = serviceScope.ServiceProvider.GetService<DatabaseContext>()) { context.Database.Migrate(); } } Console.WriteLine("Migrations applied"); } private string GetConnectionString() { var address = new Uri(Environment.GetEnvironmentVariable(Constants.CONN_STR)); var user = address.UserInfo.Split(":")[0]; var pass = address.UserInfo.Split(":")[1]; var host = address.Host; var port = address.Port; var database = address.PathAndQuery.Trim('/'); return string.Format("Host={0};Port={1};Database={2};Username={3};Password={4}", host, port, database, user, pass); } } } <file_sep>/source/Keeper.WebApi/Services/ISecurityService.cs using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; namespace Keeper.WebApi.Services { public interface ISecurityService { string GetRandomString(int minLength, int maxLength); char GetRandomSymbol(); int GetRandomInt(int min, int max); byte GetRandomByte(byte max); string GenerateJwtToken(IdentityUser user); } }<file_sep>/source/Keeper.WebApi/Controllers/TransactionsController.cs using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Keeper.WebApi.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace Keeper.WebApi.Controllers { [ApiController] [Route("[controller]")] [Authorize] public class TransactionsController : ControllerBase { private ITransactionsService transactionsService; public TransactionsController(ITransactionsService _transactionsService) { transactionsService = _transactionsService; } [HttpPost] public async Task<IActionResult> Add([FromBody] string newTransaction) { if(!ModelState.IsValid) return BadRequest(ModelState); var userId = GetUserId(); if(string.IsNullOrWhiteSpace(userId)) return Unauthorized("Token is invalid"); var result = await transactionsService.AddAsync(userId, newTransaction); if(result <= 0) return StatusCode(500, "Error has occured while adding transaction"); return Ok(result); } [HttpGet("{id}")] public IActionResult GetFrom(int id) { if(!ModelState.IsValid) return BadRequest(ModelState); var userId = GetUserId(); if(string.IsNullOrWhiteSpace(userId)) return Unauthorized("Token is invalid"); var transactions = transactionsService.GetTransactionsFrom(userId, id); return Ok(transactions); } private string GetUserId() => User.Claims.Where(c => c.Type == ClaimTypes.Name).Select(c => c.Value).FirstOrDefault(); } }<file_sep>/source/Keeper.WebApi/Models/NewTransaction.cs namespace Keeper.WebApi.Models { public class NewTransaction { public string Secret { get; set; } public string Data { get; set; } } }<file_sep>/Dockerfile FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster WORKDIR /app # copy published app COPY ./output . ENV ASPNETCORE_URLS=http://0.0.0.0:PORT CMD dotnet Keeper.WebApi.dll --urls http://*:$PORT<file_sep>/tests/Keeper.WebApi.Tests/Controllers/TransactionsControllerTests.cs using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using Keeper.WebApi.Controllers; using Keeper.WebApi.Services; using Microsoft.AspNetCore.Mvc; using Moq; using NUnit.Framework; using Shouldly; namespace Keeper.WebApi.Tests.Controllers { class TransactionsControllerTests { private Mock<ITransactionsService> transactionsServiceMock; [SetUp] public void Setup() { transactionsServiceMock = new Mock<ITransactionsService>(); } [Test] public async Task AddWhenModelStateIsNotValidShouldReturnBadRequest() { var controller = TransactionsController(transactionsServiceMock.Object); controller.ModelState.AddError("Error", "Error"); var result = (BadRequestObjectResult)await controller.Add("transactions"); result.ShouldNotBeNull(); } [Test] public async Task AddWhenUserIsNotAuthenticatedShouldReturnUnauthorized() { var user = new ClaimsPrincipal(); var controller = TransactionsController(transactionsServiceMock.Object); controller.User = user; var result = (UnauthorizedObjectResult)await controller.Add("transactions"); result.ShouldNotBeNull(); result.Value.ShouldBe("Token is invalid"); } [Test] public async Task AddWhenSavingFailedShouldReturnStatusCode500() { transactionsServiceMock.Setup(s => s.AddAsync("user", "transactions")).Returns(-1); var user = new ClaimsPrincipal(new List<Claim>() { new Claim(ClaimTypes.Name, "user")}); var controller = TransactionsController(transactionsServiceMock.Object); controller.User = user; var result = (ObjectResult)await controller.Add("transactions"); result.ShouldNotBeNull(); result.StatusCode.Value.ShouldBe(500); result.Value.ShouldBe("Error has occured while adding transaction"); } [Test] public async Task AddWhenTransactionIsAddedShouldReturnOk() { transactionsServiceMock.Setup(s => s.AddAsync("user", "transactions")).Returns(10); var user = new ClaimsPrincipal(new List<Claim>() { new Claim(ClaimTypes.Name, "user")}); var controller = TransactionsController(transactionsServiceMock.Object); controller.User = user; var result = (OkObjectResult)await controller.Add("transactions"); result.ShouldNotBeNull(); result.Value.ShouldBe(10); } } } <file_sep>/source/Keeper.WebApi/Controllers/ProfileController.cs using System.Threading.Tasks; using Keeper.WebApi.Models; using Keeper.WebApi.Services; using Microsoft.AspNetCore.Mvc; namespace Keeper.WebApi.Controllers { [ApiController] [Route("[controller]")] public class ProfileController : ControllerBase { private IUsersService usersService; public ProfileController(IUsersService _usersService) { usersService = _usersService; } [HttpPost] public async Task<IActionResult> CreateAsync([FromBody] string secret) { if(string.IsNullOrWhiteSpace(secret)) return BadRequest("Missing profile's secret"); var key = await usersService.CreateAsync(secret); if(string.IsNullOrWhiteSpace(key)) return StatusCode(500, "Unable to create new synchronization profile"); return Ok(key); } [HttpGet("check/{key}")] public async Task<IActionResult> ExistsAsync(string key) { if(!ModelState.IsValid) return BadRequest(ModelState); if(await usersService.ExistsAsync(key)) return Ok(); return NotFound(); } [HttpPost("login")] public async Task<IActionResult> LoginAsync([FromBody] LoginForm login) { if(!ModelState.IsValid) return BadRequest(ModelState); if (login is null || string.IsNullOrWhiteSpace(login.Key) || string.IsNullOrWhiteSpace(login.Secret)) return BadRequest("Login object must have key and secret properties"); var result = await usersService.LoginAsync(login); if(string.IsNullOrWhiteSpace(result)) return Unauthorized("Incorrect credentials"); return Ok(result); } } }<file_sep>/source/Keeper.WebApi/Services/UsersService.cs using System.Threading.Tasks; using Keeper.WebApi.Models; using Microsoft.AspNetCore.Identity; namespace Keeper.WebApi.Services { public class UsersService : IUsersService { private DatabaseContext context; private SignInManager<IdentityUser> signInManager; private UserManager<IdentityUser> usersManager; private ISecurityService securityService; public UsersService(DatabaseContext _context, SignInManager<IdentityUser> _signInManager, UserManager<IdentityUser> _usersManager, ISecurityService _securityService) { context = _context; signInManager = _signInManager; usersManager = _usersManager; securityService = _securityService; } public async Task<string> CreateAsync(string secret) { var username = string.Empty; var foundNew = false; while(!foundNew) { username = securityService.GetRandomString(10, 15); foundNew = await usersManager.FindByNameAsync(username) is null; } var user = new IdentityUser() { UserName = username }; var result = await usersManager.CreateAsync(user, secret); if(result.Succeeded) return username; return string.Empty; } public async Task<bool> ExistsAsync(string username) { var found = await usersManager.FindByNameAsync(username); return !(found is null); } public async Task<string> LoginAsync(LoginForm login) { var result = await signInManager.PasswordSignInAsync(login.Key, login.Secret, false, false); if(!result.Succeeded) return ""; var user = await usersManager.FindByNameAsync(login.Key); return securityService.GenerateJwtToken(user); } } }<file_sep>/source/Keeper.WebApi/Services/SecurityService.cs using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; namespace Keeper.WebApi.Services { public class SecurityService : ISecurityService { private const string usernameSymbols = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider(); private IConfiguration configuration; public SecurityService(IConfiguration _configuration) { configuration = _configuration; } public string GetRandomString(int minLength, int maxLength) { var length = GetRandomInt(minLength, maxLength); var str = new StringBuilder(); for(int i = 0; i < length; ++i) { str.Append(GetRandomSymbol()); } return str.ToString(); } public char GetRandomSymbol() => usernameSymbols[GetRandomByte(Convert.ToByte(usernameSymbols.Length))]; public int GetRandomInt(int min, int max) { var boundries = BitConverter.GetBytes(max - min); var value = new byte[boundries.Length]; for(int i = 0; i < value.Length; ++i) { value[i] = GetRandomByte(boundries[i]); } return BitConverter.ToInt32(value) + min; } public byte GetRandomByte(byte max) { if(max == 0) // interval is [0; 0] return 0; var value = new byte[1]; var fair = false; while(!fair) { rand.GetBytes(value); fair = IsFair(value[0], max); } return (byte)((int)value[0] % (int)max); } public string GenerateJwtToken(IdentityUser user) { var claims = new List<Claim>() { new Claim(JwtRegisteredClaimNames.Sub, user.Id), new Claim(ClaimTypes.Name, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["SecurityKey"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken(configuration["Issuer"], configuration["Issuer"], claims, DateTime.Now, DateTime.Now.Add(TimeSpan.FromHours(2)), creds); return new JwtSecurityTokenHandler().WriteToken(token); } private bool IsFair(byte value, byte maxValue) { int sets = byte.MaxValue / maxValue; return value < sets * maxValue; } } }<file_sep>/tests/Keeper.WebApi.Tests/Controllers/ProfileControllerTests.cs using NUnit.Framework; using Keeper.WebApi.Controllers; using Moq; using Keeper.WebApi.Services; using System.Threading.Tasks; using Shouldly; using Microsoft.AspNetCore.Mvc; using System; using Keeper.WebApi.Models; namespace Keeper.WebApi.Tests.Controllers { public class ProfileControllerTests { private Mock<IUsersService> usersServiceMock; [SetUp] public void Setup() { usersServiceMock = new Mock<IUsersService>(); } [Test] public async Task CreateAsyncWhenSecretIsProvidedShouldCreateUser() { usersServiceMock.Setup(s => s.CreateAsync("secret")).Returns(Task.FromResult("key")); var controller = new ProfileController(usersServiceMock.Object); var result = (OkObjectResult)await controller.CreateAsync("secret"); result.ShouldNotBeNull(); result.Value.ShouldBe("key"); } [Test] public async Task CreateAsyncWhenSecretIsMissingShouldReturnBadRequest() { var controller = new ProfileController(usersServiceMock.Object); var result = (BadRequestObjectResult)await controller.CreateAsync(""); result.ShouldNotBeNull(); result.Value.ShouldBe("Missing profile's secret"); } [Test] public async Task CreateAsyncWhenSavingFailsShouldReturnStatusCode500() { usersServiceMock.Setup(s => s.CreateAsync("secret")).Returns(Task.FromResult("")); var controller = new ProfileController(usersServiceMock.Object); var result = (ObjectResult)await controller.CreateAsync("secret"); result.ShouldNotBeNull(); result.StatusCode.Value.ShouldBe(500); result.Value.ShouldBe("Unable to create new synchronization profile"); } [Test] public async Task ExistsAsyncWhenModelStateIsNotValidShouldReturnBadRequest() { var controller = new ProfileController(usersServiceMock.Object); controller.ModelState.AddModelError("Model error", "Error message"); var result = (BadRequestObjectResult)await controller.ExistsAsync(""); result.ShouldNotBeNull(); } [TestCase(true, typeof(OkResult))] [TestCase(false, typeof(NotFoundResult))] public async Task ExistsAsyncWhenKeyIsProvidedShouldReturnCorrectResult(bool exists, Type returnType) { usersServiceMock.Setup(s => s.ExistsAsync("key")).Returns(Task.FromResult(exists)); var controller = new ProfileController(usersServiceMock.Object); var result = await controller.ExistsAsync("key"); result.ShouldBeOfType(returnType); } [Test] public async Task LoginAsyncWhenModelStateIsNotValidShouldReturnBadRequest() { var controller = new ProfileController(usersServiceMock.Object); controller.ModelState.AddModelError("Error", "Error"); var result = (BadRequestObjectResult)await controller.LoginAsync(null); result.ShouldNotBeNull(); } [TestCase(null, "secret")] [TestCase("key", null)] public async Task LoginAsyncWhenLoginParametersAreMissinShouldReturnBadRequest(string key, string secret) { var loginObj = new LoginForm() { Key = key, Secret = secret }; var controller = new ProfileController(usersServiceMock.Object); var result = (BadRequestObjectResult)await controller.LoginAsync(loginObj); result.ShouldNotBeNull(); result.Value.ShouldBe("Login object must have key and secret properties"); } [Test] public async Task LoginAsyncWhenLoginCredentialsAreIncorrectShouldReturnUnauthorized() { var loginObj = new LoginForm() { Key = "key", Secret = "secret" }; usersServiceMock.Setup(s => s.LoginAsync(loginObj)).Returns(Task.FromResult(string.Empty)); var controller = new ProfileController(usersServiceMock.Object); var result = (UnauthorizedObjectResult)await controller.LoginAsync(loginObj); result.ShouldNotBeNull(); result.Value.ShouldBe("Incorrect credentials"); } [Test] public async Task LoginAsyncWhenLoginCredentialsAreCorrectShouldReturnOk() { var loginObj = new LoginForm() { Key = "key", Secret = "secret" }; usersServiceMock.Setup(s => s.LoginAsync(loginObj)).Returns(Task.FromResult("token")); var controller = new ProfileController(usersServiceMock.Object); var result = (OkObjectResult)await controller.LoginAsync(loginObj); result.ShouldNotBeNull(); result.Value.ShouldBe("token"); } } }<file_sep>/source/Keeper.WebApi/Services/TransactionsService.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Keeper.WebApi.Models; using Microsoft.AspNetCore.Identity; namespace Keeper.WebApi.Services { public class TransactionsService : ITransactionsService { private DatabaseContext context; public TransactionsService(DatabaseContext _context) { context = _context; } public async Task<int> AddAsync(string id, string newTransaction) { if(id is null) throw new ArgumentNullException(nameof(id)); var added = context.Transactions.Add(new Transaction() { Data = newTransaction, ProfileId = id }); var result = await context.SaveChangesAsync().ConfigureAwait(false); if(result <= 0) return result; return added.Entity.Id; } public IEnumerable<Transaction> GetTransactionsFrom(string userId, int id) => context.Transactions.Where(t => t.ProfileId == userId && t.Id > id).ToList(); } }
e6615ba4e4bb3b7fbf01038e1c7320232f14c873
[ "C#", "Dockerfile" ]
17
C#
mindaugasdirg/keeper-server
060c1dd4c2561b8375fd74d41d5682d664f9ce29
6cdae5b894249ac1562180c3073b52bb8d4b511e
refs/heads/master
<file_sep>/* SecuencialLed.h - Libreria de secuencias de leds. Creado por Mandragora Tools 24-12-2016 Esta libreria es de dominio publico */ #ifndef SecuencialLed_h #define SecuencialLed_h #include "Arduino.h" class SecuencialLed { public: void ledPins(int npins,int pins[]){ _npins=npins; for (int i=0;i<npins;i++){ _pins[i]=pins[i]; } for (int i=0;i<npins;i++){ pinMode(pins[i],OUTPUT); } } void ascendente(){ compvelocidad(); for (int i=0;i<_npins;i++){ digitalWrite(_pins[i],HIGH); delay(_velocidad); digitalWrite(_pins[i],LOW); } } bool cumulAsc(){ compvelocidad(); for (int i=0;i<_n2;i++){ digitalWrite(_pins[i],HIGH); digitalWrite(_pins[i-1],LOW); delay(_velocidad); } _n2--; if(_n2<=0){_n2=_npins; return true; }else{return false;} } void ascDos(){ compvelocidad(); for (int i=0;i<_npins;i++){ digitalWrite(_pins[i],HIGH); digitalWrite(_pins[i+1],HIGH); delay(_velocidad); digitalWrite(_pins[i],LOW); digitalWrite(_pins[i+1],LOW); } } void ascInvert(){ compvelocidad(); for (int i=0;i<_npins;i++){ digitalWrite(_pins[i],HIGH); } for (int i=0;i<_npins;i++){ digitalWrite(_pins[i],LOW); delay(_velocidad); digitalWrite(_pins[i],HIGH); } } void progresAsc(){ compvelocidad(); for (int i=0;i<_npins;i++){ digitalWrite(_pins[i],HIGH); delay(_velocidad); } } void progresInvAsc(){ compvelocidad(); for (int i=0;i<_npins;i++){ digitalWrite(_pins[i],LOW); delay(_velocidad); } } void descendente(){ compvelocidad(); for (int i=_npins;i>-1;i--){ digitalWrite(_pins[i],HIGH); delay(_velocidad); digitalWrite(_pins[i],LOW); } } bool cumulDesc(){ compvelocidad(); for (int i=_npins;i>_n3;i--){ digitalWrite(_pins[i],HIGH); digitalWrite(_pins[i+1],LOW); delay(_velocidad); } _n3++; if(_n3>=_npins){ _n3=-1; return true; }else{ return false; } } void descDos(){ compvelocidad(); for (int i=_npins;i>-1;i--){ digitalWrite(_pins[i],HIGH); digitalWrite(_pins[i+1],HIGH); delay(_velocidad); digitalWrite(_pins[i],LOW); digitalWrite(_pins[i+1],LOW); } } void descInvert(){ compvelocidad(); for (int i=_npins;i>-1;i--){ digitalWrite(_pins[i],HIGH); } for (int i=_npins;i>-1;i--){ digitalWrite(_pins[i],LOW); delay(_velocidad); digitalWrite(_pins[i],HIGH); } } void progresDesc(){ compvelocidad(); for (int i=_npins;i>-1;i--){ digitalWrite(_pins[i],HIGH); delay(_velocidad); } } void progresInvDesc(){ compvelocidad(); for (int i=_npins;i>-1;i--){ digitalWrite(_pins[i],LOW); delay(_velocidad); } } void aleatorio(){ compvelocidad(); byte rand=random(0,_npins); digitalWrite(_pins[rand],HIGH); delay(_velocidad); digitalWrite(_pins[rand],LOW); } void ascPar(){ compvelocidad(); for (int i=0;i<_npins;i++){ if(i & 0x01){ }else{digitalWrite(_pins[i*1],HIGH); delay(_velocidad); digitalWrite(_pins[i*1],LOW); } } } void ascImpar(){ compvelocidad(); for (int i=0;i<_npins;i++){ if(i & 0x01){ digitalWrite(_pins[i*1],HIGH); delay(_velocidad); digitalWrite(_pins[i*1],LOW); } } } void velocidad(int veloz){ _velocidad=veloz; } private: int _pins[12]; int _npins; int _velocidad=0; int _n; int _n2=_npins; int _n3=-1; void compvelocidad(){ if(_velocidad==0){ _velocidad=1000; } } }; #endif <file_sep>//| SecuencialLed(Beta)>> Ejemplo de secuencias especiales "cumulAsc" y "cumulDesc". | //| Creado por: Mandragora Tools 2016 | //| | //| *Para usar estas secuencias conbinadas con otras es necesario hacer lo que muestra el ejemplo, con el objetivo| //| de que las secuencias sean completadas y no se crucen entre ellas. | //|_______________________________________________________________________________________________________________| #include <SecuencialLed.h> //Declaramos dos variables de tipo boolean y a la que queramos que comience primero la iniciaremos con "true" bool b1=true; bool b2=false; //Definimos los pines que usaremos para nuestros leds int pins[]={2,3,4,5,6,7,8,9,10}; //Declaramos la instancia de SecuencialLed SecuencialLed leds1; void setup() { //Inicializamos SecuencialLed pasandole la cantidad de leds y los pines correspondientes leds1.ledPins(9,pins); //Declaramos la velocidad deseada (si esta no se especifica por defecto será de 1000 milisegundos) leds1.velocidad(100); } void loop() { //Ejecutamos la secuencia cumulDesc cuando cumulAsc haya sido completada if(b1==true){ if(leds1.cumulDesc()){ b2=true; b1=false; } } //Ejecutamos la secuencia cumulAsc cuando cumulDesc haya sido completada if(b2==true){ if(leds1.cumulAsc()){ b1=true; b2=false; } } } <file_sep># SecuencialLeds(Beta) Copyrigth (c) <NAME> 2016 <EMAIL> http://bit.ly/mandragoratools #¿Que es SecuencialLeds? SecuencialLeds es una libreria para Arduino, que nos sirve para gestionar secuencias de leds de una forma muy simplificada. En esta versión Beta hemos incorporado unas cuantas funciones disponibles listas para usar en nuestros proyectos. *Esta libreria está especialmente enfocada a leds, aunque podria usarse otro tipo de dispositivos como por ejemplo relays. #Referencia: Declaramos e inicializamos la instancia de SecuencialLeds usando: - **SecuencialLed led1;** Definimos los pines donde irán conectados los leds usando para ello un Array de tipo int: - **int leds[]={2,3,4,5,6,7,8,9,10};** Declaramos la cantidad de leds que vamos a usar y los pines asociados a los mismos: - **led1.ledPins(9,leds);** Definimos la velocidad de las secuencias: - **led1.velocidad(1000);** Y por ultimo en el void loop usaremos las secuencias que esta libreria incorpora, combinandolas según lo que queramos: *** **ascendente();** Secuencia ascendente **descendente();** Secuencia descendente **ascInvert();** Secuencia ascendente invertida **descInvert();** Secuencia descendente invertida **progresAsc();** Progresión ascendente **progresDesc();** Progresión descendente **progresInvAsc();** Progresión invertida ascendente **progresInvDesc();** Progresión invertida descendente **ascInvert();** Secueencia ascendente invertida **descInvert();** Secuencia descendente invertida **ascPar();** Secuendia ascendente solo de leds pares **ascImpar();** Secuencia ascendente solo de leds impares **cumulAsc();** Secuencia de acumulación ascendente **cumulDesc();** Secuencia de acumulación descendente **aleatorio();** Secuencia aleatoria *** #Ejemplo de uso: *** ```arduino #include <SecuencialLed.h> int leds[]={2,3,4,5,6,7,8,9,10}; SecuencialLed led1; void setup() { led1.ledPins(9,leds); led1.velocidad(1000); } void loop() { led1.ascendente(); led1.descendente(); } ``` *** [<img width='100%' heigth='100%' src='/secuencialleds.png'/>](/secuencialleds.png) <file_sep>//| SecuencialLed(Beta)>> Ejemplo básico "ascendente" y "descendente". | //| Creado por: <NAME> 2016 | | //|________________________________________________________________________| #include <SecuencialLed.h> //Definimos los pines que usaremos para nuestros leds int leds[]={2,3,4,5,6,7,8,9,10}; //Declaramos la instancia de SecuencialLed SecuencialLed led1; void setup() { //Inicializamos SecuencialLed pasandole la cantidad de leds y los pines correspondientes led1.ledPins(9,leds); //Declaramos la velocidad deseada (si esta no se especifica por defecto será de 1000 milisegundos) led1.velocidad(300); } void loop() { //Ejacutamos las secuencias led1.ascendente(); led1.descendente(); }
75191043a8be69428915d9553d58d8d1c6082269
[ "Markdown", "C++" ]
4
C++
Mandragoratools/SecuencialLeds
4a852a3df01c27e2458d0bdf64c3d63d0ff4fab5
7793fcc59e71c722d1ff6de484bfef0a5ebacfe3
refs/heads/master
<repo_name>Uji789/Dijital-project<file_sep>/app/js/draft/common.js document.addEventListener('DOMContentLoaded', function(){ // mobile menu const hamburger = document.querySelector(".hamburger"); const mobileMenu = document.querySelector(".mobile__menu"); function toggleMobileMenu (){ hamburger.classList.toggle("is-active"); mobileMenu.classList.toggle("mobile__menu--active"); document.body.classList.toggle("no-scroll"); } hamburger.addEventListener("click", toggleMobileMenu); // slider const swiper = new Swiper('.swiper-container', { pagination: { el: '.swiper-pagination', type: 'fraction', }, navigation: { nextEl: '.control__img-right', prevEl: '.control__img-left', }, }); });<file_sep>/gulpfile.js const {src, dest, watch, parallel, series} = require("gulp"); const scss = require("gulp-sass"); const autoprefixer = require("gulp-autoprefixer"); const syncbrow = require("browser-sync").create(); const imgmin = require("gulp-imagemin"); const fs = require("fs"); const ttf2woff = require("gulp-ttf2woff"); const ttf2woff2 = require("gulp-ttf2woff2"); const fileinclude = require("gulp-file-include"); const htmlmin = require("gulp-htmlmin"); const webphtml = require("gulp-webp-html"); // const webpCss = require("gulp-webp-css"); const toWebp = require("gulp-webp"); // ! Creating folders and files function folders (){ return src("*.*", {read: false}) .pipe(dest("./dist/scss/")) .pipe(dest("./dist/js/")) .pipe(dest("./dist/js/draft/")) .pipe(dest("./dist/img/")) .pipe(dest("./dist/fonts/")) }; function files (){ folders(); setTimeout (() => { fs.writeFile("project/index.html", "!", function (err) { if (err) { throw err; } console.log("File creation finished."); }); fs.writeFile("project/scss/style.scss", "", function (err) { if (err) { throw err; } console.log("File creation finished."); }); fs.writeFile("project/js/draft/common.js", "", function (err) { if (err) { throw err; } console.log("File creation finished."); }); },500); }; // ! Development // * Конвертация scss в css function stylesConvert (){ return src("app/scss/style.scss") .pipe(scss( { outputStyle: "compressed" } )) .pipe(autoprefixer( { cascade: true } )) .pipe(dest("app/css")); }; // * Watcher function watchFiles (){ watch("app/scss/**/*.scss", stylesConvert); watch("app/img", compressedImg); watch("app/pages/**/*.html", includeFile); watch("app/fonts/*.ttf", series(convertFonts, fontsStyle)); watch("app/*.html").on("change", syncbrow.reload); watch("app/css/*.css").on("change", syncbrow.reload); watch("app/js/*.js").on("change", syncbrow.reload); watch("app/pages/**/*.html").on("change", syncbrow.reload); }; // * Browser-sync function browserSync (){ syncbrow.init({ server: { baseDir: "app", open: "local" } }); }; // * Convert imades to webp function convertImgs (){ return src("app/img/*.jpg") .pipe(toWebp()) .pipe(dest("app/img")) }; // * Сonvert TTF fonts exports.cFonts = series(convertFonts, fontsStyle); // * converting ttf in WOFF and WOFF2 function convertFonts (){ src(['app/fonts/**.ttf']) .pipe(ttf2woff()) .pipe(dest('app/fonts/')); return src(['app/fonts/**.ttf']) .pipe(ttf2woff2()) .pipe(dest('app/fonts/')) }; // * Font-face for fonts const cb = () => {}; let srcFonts = "app/scss/_fonts.scss"; let appFonts = "app/fonts"; function fontsStyle (){ let file_content = fs.readFileSync(srcFonts); fs.writeFile(srcFonts, "", cb); fs.readdir(appFonts, function (err, items) { if (items) { let c_fontname; for (let i = 0; i < items.length; i++) { let fontname = items[i].split("."); fontname = fontname[0]; if (c_fontname != fontname) { fs.appendFile( srcFonts, '@include font-face("' + fontname + '", "' + fontname + '", 400);', cb ); } c_fontname = fontname; } } }); }; // * HTML parts. File-include const includeFile = function (){ return src("app/pages/*.html") .pipe( fileinclude({ prefix: "@@", basepath: "@file" }) ) .pipe(dest("app")) } // scss в css exports.stylesConvert = stylesConvert; // Watcher exports.watchFiles = watchFiles; // Browser-sync exports.browserSync = browserSync; // Compressed Images exports.compressedImg = compressedImg; // Creating folders and files exports.struct = files; // Fonts exports.fontStyle = fontsStyle; exports.convertFonts = convertFonts; // File-include, HTML parts exports.includeFile = includeFile; // * Convert imades to webp exports.convertImgs = convertImgs; exports.default = parallel(includeFile, stylesConvert, browserSync, watchFiles, convertImgs); // ! Build function moveHtml (){ return src("app/*.html") .pipe(webphtml()) .pipe(htmlmin( { collapseWhitespace: true, removeComments: true } )) .pipe(dest("dist")) }; function moveCss (){ return src("app/css/*.css") // .pipe(webpCss()) .pipe(dest("dist/css")) }; function moveFonts (){ return src("app/fonts/**") .pipe(dest("dist/fonts")) }; function moveJs (){ return src("app/js/*.js") .pipe(dest("dist/js")) }; // * Image Compressed function compressedImg (){ return src("app/img/**") .pipe(imgmin()) .pipe(dest("dist/img")) }; exports.moveHtml = moveHtml; exports.moveCss = moveCss; exports.moveJs = moveJs; exports.compressedImg = compressedImg; exports.moveFonts = moveFonts exports.build = series(moveHtml, moveCss, moveJs, moveFonts, compressedImg);
fefe51e41e07c20cc6c2a5b7a9f16510e80301fe
[ "JavaScript" ]
2
JavaScript
Uji789/Dijital-project
7ef7055f4f6708a63441305f1c472f961c9fcd16
ede3fb8144f12f65414af29881774da2d1267ba9
refs/heads/master
<file_sep>package com.example.newsapi.ui.main; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.newsapi.Adapters.TopHeadlinesAdapter; import com.example.newsapi.Network.NetworkUtil; import com.example.newsapi.R; import com.example.newsapi.Utils.Constants; import com.example.newsapi.retrofit.response.TopHeadlinesResponse; import java.util.ArrayList; import java.util.Arrays; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import rx.subscriptions.CompositeSubscription; /** * A placeholder fragment containing a simple view. */ public class PlaceholderFragment extends Fragment { private static final String ARG_SECTION_NUMBER = "section_number"; private CompositeSubscription mTopHeadlinesSubscription; private RecyclerView recyclerView; private String country ; public static PlaceholderFragment newInstance(String country) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle bundle = new Bundle(); bundle.putString(ARG_SECTION_NUMBER, country); fragment.setArguments(bundle); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTopHeadlinesSubscription = new CompositeSubscription(); } private void handleResponseTopHeadlines(TopHeadlinesResponse topHeadlinesResponse) { Log.d(Constants.TAG,topHeadlinesResponse.toString()); TopHeadlinesAdapter topHeadlinesAdapter = new TopHeadlinesAdapter(new ArrayList<>(Arrays.asList(topHeadlinesResponse.getArticles())),getActivity(),getActivity().getSupportFragmentManager()); recyclerView.setAdapter(topHeadlinesAdapter); topHeadlinesAdapter.notifyDataSetChanged(); } private void handleErrorTopHeadlines(Throwable throwable) { Log.e(Constants.TAG,throwable.toString()); } @Override public View onCreateView( @NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_main, container, false); recyclerView = root.findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); if (getArguments() != null) { country = getArguments().getString(ARG_SECTION_NUMBER); } if(country!=null){ mTopHeadlinesSubscription.add(NetworkUtil.getRetrofit().topHeadlines(country, Constants.API_KEY) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(this::handleResponseTopHeadlines,this::handleErrorTopHeadlines)); } return root; } }<file_sep>package com.example.newsapi.Network; import com.example.newsapi.Utils.Constants; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.schedulers.Schedulers; public class NetworkUtil { public static RetrofitInterface getRetrofit(){ RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()); return new Retrofit.Builder() .baseUrl(Constants.BASE_URL) .addCallAdapterFactory(rxAdapter) .addConverterFactory(GsonConverterFactory.create()) .build().create(RetrofitInterface.class); } } <file_sep>package com.example.newsapi; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import android.os.Bundle; import com.example.newsapi.ui.main.SearchFragment; public class SearchActivity extends AppCompatActivity { String search; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); search = getIntent().getExtras().getString("search"); // Create new fragment and transaction Fragment newFragment = SearchFragment.newInstance(search); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack if needed transaction.replace(R.id.search_frame, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit(); } @Override public void onBackPressed() { super.onBackPressed(); finish(); } }<file_sep>package com.example.newsapi.Network; import com.example.newsapi.retrofit.response.TopHeadlinesResponse; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Query; import rx.Observable; public interface RetrofitInterface { @GET("top-headlines") Observable<TopHeadlinesResponse> topHeadlines(@Query("country") String country, @Query("apiKey") String apikey); @GET("everything") Observable<TopHeadlinesResponse> everything(@Query("q") String search, @Query("apiKey") String apikey); } <file_sep>package com.example.newsapi.ui.main; import android.content.Context; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import com.example.newsapi.Models.Country; import com.example.newsapi.R; import java.util.ArrayList; public class SectionsPagerAdapter extends FragmentPagerAdapter { ArrayList<Country> countries; public SectionsPagerAdapter( ArrayList<Country> countries, FragmentManager fm) { super(fm); this.countries = countries; } @Override public Fragment getItem(int position) { return PlaceholderFragment.newInstance(countries.get(position).getCode()); } @Nullable @Override public CharSequence getPageTitle(int position) { return countries.get(position).getName(); } @Override public int getCount() { // Show 2 total pages. return countries.size(); } }
519e5c15f73c687c84319430af2f5d7984185e5c
[ "Java" ]
5
Java
SAM33RG/newsAPI
b65cab8b94638ec2998e40b8ac9b7723380911f4
2c6fd8bfb35a95aa7f78d30548fae5861ce6ed3b
refs/heads/master
<repo_name>developers-cosmos/Socket-Programming<file_sep>/README.md # Chat Application - ## Socket Programming Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket (node) listens on a particular port at an IP, while another socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server. Socket programs are used to communicate between various processes usually running on the same or different systems. It is mostly used to create a client-server environment. <img src="Images/server_client1.jpg" width="500" height="300"> - ## Background So before getting started let's try to understand some basic keywords that we are going to talk about. - ### Network The network is an advanced broadcast communications arrangement for sharing assets between nodes, which are computing devices that use a common telecommunications technology. <img src="Images/network.jpg" width="500" height="300"> - ### Protocol In telecommunication, a communication protocol is a system of rules that allow two or more entities of a communications system to transmit information via any kind of variation of a physical quantity. <img src="Images/protocol.jpg" width="500" height="300"> - ### IP address An Internet Protocol address is a numerical label assigned to each device connected to a computer network that uses the Internet Protocol for communication. An IP address serves two main functions: host or network interface identification and location addressing. 1. Static means the IP address never changes as long as you stay with the same provider or same server. 2. Dynamic means the IP address can change from time-to-time. 3. Public means the IP address can be visited from any computer in the world. 4. Private means the IP address can only be used by those on the same network. - ### Port In computer networking, a port is a communication endpoint. At the software level, within an operating system, a port is a logical construct that identifies a specific process or a type of network service. <img src="Images/port_forwarding.jpg" width="500" height="300"> Port forwarding or port mapping is an application of network address translation that redirects a communication request from one address and port number combination to another while the packets are traversing a network gateway, such as a router or firewall. - ### Firewall A Firewall is a network security system that monitors and controls incoming and outgoing network traffic based on predetermined security rules. A firewall typically establishes a barrier between a trusted internal network and untrusted external network, such as the Internet. <img src="Images/firewall.jpg" width="500" height="300"> - ### Socket A network socket is an internal endpoint for sending or receiving data within a node on a computer network. Concretely, it is a representation of this endpoint in networking software, such as an entry in a table, and is a form of system resource. <img src="Images/socket.jpg" width="500" height="300"> - ### Types of Internet Sockets * Stream Sockets (SOCK_STREAM) 1. Connection oriented 2. Rely on TCP to provide reliable two-way connected communication * Datagram Sockets (SOCK_DGRAM) 1. Rely on UDP 2. Connection is unreliable - ## Server - Client Architecture <img src="Images/server_client.jpg" width="500" height="300"> - ### Server Side Programming A server is a type of computer or device on a network that manages network resources. Servers are often dedicated, meaning that they perform no other tasks besides their server tasks. On multiprocessing operating systems, however, a single computer can execute several programs at once. * Socket Creation * bind() what port am I on? * listen() - Call me please! * accept() - Thank you for calling ! * send() and recv() - Let's talk! - ### Client Side programming A client is a piece of computer hardware or software that accesses a service made available by a server. The server is often on another computer system, in which case the client accesses the service by way of a network. * Socket Creation * connect() - Hello! * send() and recv() - Let's talk! <img src="Images/server_client2.jpg" width="500" height="200"> - ## How does a web work? <img src="Images/webwork.jpg" width="500" height="200"> <file_sep>/CPP Example/ClientSocket.cpp #include <iostream> #include <windows.h> #include <winsock2.h> #include <ws2tcpip.h> using namespace std; #define PORT 5555 DWORD WINAPI sendFunction(LPVOID lpParam) { char buffer[1024]; SOCKET server = *(SOCKET *)lpParam; while(true){ cin.getline(buffer, sizeof(buffer)); send(server, buffer, sizeof(buffer), 0); if(!strcmp(buffer,"bye")){ return 0; } } return 0; } DWORD WINAPI recvFunction(LPVOID lpParam) { char buffer[1024]; SOCKET server = *(SOCKET *)lpParam; while(true){ recv(server, buffer, sizeof(buffer), 0); cout << "\t\t\t\t"; cout << buffer << endl; if(!strcmp(buffer,"bye")){ return 0; } } return 0; } int main() { WSADATA WSAData; SOCKET server; SOCKADDR_IN address; HANDLE sendThread, recvThread; DWORD sendThreadID, recvThreadID; char buffer[1024]; WSAStartup(MAKEWORD(2,0), &WSAData); server = socket(AF_INET, SOCK_STREAM, 0); if(server == INVALID_SOCKET){ cout << "Socket Creation failed" << endl; WSACleanup(); return -1; } address.sin_addr.s_addr = inet_addr("127.0.0.1"); address.sin_family = AF_INET; address.sin_port = htons(PORT); int connectID = connect(server, (SOCKADDR *)&address, sizeof(address)); if(connectID == -1){ cout << "Connection failed" << endl; closesocket(server); WSACleanup(); return -1; } cout << "Connected to server!" << endl; sendThread = CreateThread(NULL, 0, sendFunction, (LPVOID)&server, 0, &sendThreadID); if(sendThread == NULL){ cout << "Error in Sending Messages" <<endl; closesocket(server); CloseHandle(sendThread); WSACleanup(); return -1; } recvThread = CreateThread(NULL, 0, recvFunction, (LPVOID)&server, 0, &recvThreadID); if(recvThread == NULL){ cout << "Error in Receiving Messages" <<endl; closesocket(server); CloseHandle(recvThread); WSACleanup(); return -1; } HANDLE h[2]; h[0]=sendThread; h[1]=recvThread; // WaitForSingleObject(sendThread,INFINITE); // WaitForSingleObject(recvThread,INFINITE); DWORD dw = WaitForMultipleObjects(2,h,FALSE,INFINITE); switch(dw-WAIT_OBJECT_0){ case 0:if(!TerminateThread(recvThread,(DWORD)NULL)) cout<<"Error due to Terimanation!"<<endl; break; case 1:if(!TerminateThread(sendThread,(DWORD)NULL)) cout<<"Error due to Terimanation!"<<endl; break; } CloseHandle(sendThread); CloseHandle(recvThread); closesocket(server); WSACleanup(); cout << "Socket closed." << endl; }<file_sep>/CPP Example/ServerSocket.cpp #include <iostream> #include <windows.h> #include <winsock2.h> #include <ws2tcpip.h> using namespace std; #define PORT 5555 DWORD WINAPI sendFunction(LPVOID lpParam) { char buffer[1024]; SOCKET client = *(SOCKET *)lpParam; while(true){ cin.getline(buffer, sizeof(buffer)); send(client, buffer, sizeof(buffer), 0); if(!strcmp(buffer,"bye")){ return 0; } } return 0; } DWORD WINAPI recvFunction(LPVOID lpParam) { char buffer[1024]; SOCKET client = *(SOCKET *)lpParam; while(true){ recv(client, buffer, sizeof(buffer), 0); cout << "\t\t\t\t"; cout << buffer << endl; if(!strcmp(buffer,"bye")){ return 0; } } return 0; } int main() { WSADATA WSAData; SOCKET server, client; SOCKADDR_IN serverAddress, clientAddress; HANDLE sendThread, recvThread; DWORD sendThreadID, recvThreadID; WSAStartup(MAKEWORD(2,0), &WSAData); server = socket(AF_INET, SOCK_STREAM, 0); if(server == INVALID_SOCKET){ cout << "Socket Creation failed" << endl; WSACleanup(); return -1; } serverAddress.sin_addr.s_addr = INADDR_ANY; serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(PORT); int bindID = bind(server, (SOCKADDR *)&serverAddress, sizeof(serverAddress)); if(bindID == -1){ cout << "Binding failed" << endl; closesocket(client); WSACleanup(); return -1; } int listenID = listen(server, 0); if(listenID == -1){ cout << "Listening failed" << endl; closesocket(client); WSACleanup(); return -1; } cout << "Listening for incoming connections..." << endl; int clientAddressLength = sizeof(clientAddress); client = accept(server, (SOCKADDR *)&clientAddress, &clientAddressLength); if(client == INVALID_SOCKET){ cout << "Accepting failed" << endl; closesocket(client); cout << "Client disconnected." << endl; WSACleanup(); return -1; } cout << "Client connected!" << endl; sendThread = CreateThread(NULL, 0, sendFunction, (LPVOID)&client, 0, &sendThreadID); if(sendThread == NULL){ cout << "Error in Sending Messages" <<endl; closesocket(client); CloseHandle(sendThread); WSACleanup(); return -1; } recvThread = CreateThread(NULL, 0, recvFunction, (LPVOID)&client, 0, &recvThreadID); if(recvThread == NULL){ cout << "Error in Receiving Messages" <<endl; closesocket(client); CloseHandle(recvThread); WSACleanup(); return -1; } HANDLE h[2]; h[0]=sendThread; h[1]=recvThread; // WaitForSingleObject(sendThread,INFINITE); // WaitForSingleObject(recvThread,INFINITE); DWORD dw = WaitForMultipleObjects(2,h,FALSE,INFINITE); switch(dw-WAIT_OBJECT_0){ case 0:if(!TerminateThread(recvThread,(DWORD)NULL)) cout<<"Error due to Terimanation!"<<endl; break; case 1:if(!TerminateThread(sendThread,(DWORD)NULL)) cout<<"Error due to Terimanation!"<<endl; break; } CloseHandle(sendThread); CloseHandle(recvThread); closesocket(client); cout << "Client disconnected." << endl; WSACleanup(); return 0; }
2edcc48e1abce73b0cc2e9af2f8a8c95feed13c4
[ "Markdown", "C++" ]
3
Markdown
developers-cosmos/Socket-Programming
46fb3bf65f96baeacdaf4f3d0e16f102e78909f1
6da84dfe020a6769296a95bd2df074d159a6503b
refs/heads/master
<file_sep>using IttezanPos.Models; using IttezanPos.Resources; using Rg.Plugins.Popup.Extensions; using Rg.Plugins.Popup.Pages; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.PurchasingPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class purchasePopUpPage : PopupPage { private Product selectedro; private DateTime expire_date; public purchasePopUpPage() { InitializeComponent(); } public purchasePopUpPage(Product selectedro) { InitializeComponent(); this.selectedro = selectedro; Old_Purchaselbl.Text = selectedro.purchase_price.ToString("0.00"); Old_salelbl.Text = selectedro.sale_price.ToString("0.00"); Stocklbl.Text = selectedro.stock.ToString(); pronamelbl.Text = selectedro.name; } private async void Next_Tapped(object sender, EventArgs e) { if (expire_date != null) { MessagingCenter.Send(new ValuePercent() { Value = Double.Parse(New_salelbl.Text), Percentage = Double.Parse(New_Purchaselbl.Text), expiredate = expire_date }, "PopUpData"); await Navigation.PopPopupAsync(); } else { await DisplayAlert(AppResources.Alert, AppResources.SelectExireDate, AppResources.Ok); datepi.Focus(); } } private async void Closelbl_Clicked(object sender, EventArgs e) { await Navigation.PopPopupAsync(); } private void DatePicker_DateSelected(object sender, DateChangedEventArgs e) { expire_date= e.NewDate; } } }<file_sep>using Plugin.Settings; using Plugin.Settings.Abstractions; using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Helpers { public static class Settings { private static ISettings AppSettings { get { return CrossSettings.Current; } } private const string LastGravity = "last_Gravity_key"; private static readonly string GravitySettings = string.Empty; public static string LastUserGravity { get => AppSettings.GetValueOrDefault(LastGravity, GravitySettings); set => AppSettings.AddOrUpdateValue(LastGravity, value); } } } <file_sep>using IttezanPos.Models; using Refit; using Rg.Plugins.Popup.Extensions; using Rg.Plugins.Popup.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.InventoryPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AddingClassificationPage : ContentPage { public AddingClassificationPage() { InitializeComponent(); } private async void AddCategory_Clicked(object sender, EventArgs e) { await Navigation.PushPopupAsync(new AddCategoryPopUpPage()); } protected override void OnAppearing() { base.OnAppearing(); } } }<file_sep>using Microsoft.Extensions.DependencyInjection; using Shiny; namespace IttezanPos.Helpers { public class ShinyAppStartup : Shiny.ShinyStartup { public override void ConfigureServices(IServiceCollection services) { // for general client functionality services.UseBleCentral(); // for client functionality in the background // services.UseBleCentral<YourBleDelegate>(); // for GATT server services.UseBlePeripherals(); } } } <file_sep>using IttezanPos.Helpers; using IttezanPos.Models; using IttezanPos.Resources; using IttezanPos.Services; using IttezanPos.Views.ClientPages; using Plugin.Connectivity; using Refit; using Rg.Plugins.Popup.Pages; using SQLite; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.SalesPages.SalesPopups { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ClientPopup : ContentPage { private ObservableCollection<Client> clients = new ObservableCollection<Client>(); public ObservableCollection<Client> Clients { get { return clients; } set { clients = value; OnPropertyChanged(nameof(clients)); } } public ClientPopup() { InitializeComponent(); FlowDirectionPage(); } private void FlowDirectionPage() { FlowDirection = (Helpers.Settings.LastUserGravity == "Arabic") ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultures(CultureTypes.NeutralCultures).ToList(). First(element => element.EnglishName.Contains(Helpers.Settings.LastUserGravity)); AppResources.Culture = Thread.CurrentThread.CurrentUICulture; GravityClass.Grav(); } protected override void OnAppearing() { GetData(); base.OnAppearing(); } async Task GetData() { try { ActiveIn.IsRunning = true; if (CrossConnectivity.Current.IsConnected) { var nsAPI = RestService.For<IApiService>("https://ittezanmobilepos.com/"); RootObject data = await nsAPI.GetSettings(); Clients = new ObservableCollection<Client>(data.message.clients); if (Device.RuntimePlatform == Device.iOS) { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Client"); if (!info.Any()) { db.CreateTable<Client>(); } else { db.DropTable<Client>(); db.CreateTable<Client>(); } db.InsertAll(Clients); } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Client"); if (!info.Any()) { db.CreateTable<Client>(); } else { db.DropTable<Client>(); db.CreateTable<Client>(); } // Clients = new ObservableCollection<Client>(db.Table<Client>().ToList()); // db.CreateTable<Client>(); db.InsertAll(Clients); } listviewwww.ItemsSource = Clients; ActiveIn.IsRunning = false; } else { ActiveIn.IsRunning = false; if (Device.RuntimePlatform == Device.iOS) { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Client"); if (!info.Any()) db.CreateTable<Client>(); Clients = new ObservableCollection<Client>(db.Table<Client>().ToList()); } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Client"); Clients = new ObservableCollection<Client>(db.Table<Client>().ToList()); } listviewwww.ItemsSource = Clients; // await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } catch (ValidationApiException validationException) { // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } catch (ApiException exception) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } private async void Listviewwww_ItemTapped(object sender, ItemTappedEventArgs e) { var content = e.Item as Client; MessagingCenter.Send(new Client() { name = content.name }, "PopUpData"); await Navigation.PopAsync(); } private void SearchBar_SearchButtonPressed(object sender, EventArgs e) { var keyword = SearchBar.Text; listviewwww.ItemsSource = Clients.Where(product => product.name.ToLower().Contains(keyword.ToLower())); } void OnTextChanged(object sender, EventArgs e) { SearchBar searchBar = (SearchBar)sender; var keyword = SearchBar.Text; listviewwww.ItemsSource = Clients.Where(product => product.name.ToLower().Contains(keyword.ToLower())); } private async void AddClient_Tapped(object sender, EventArgs e) { await Navigation.PushAsync(new AddingClientPage()); } } }<file_sep>using IttezanPos.Models; using IttezanPos.Services; using Plugin.Connectivity; using Refit; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using IttezanPos.Helpers; using Xamarin.Forms; using Xamarin.Forms.Xaml; using Settings = IttezanPos.Helpers.Settings; using System.IO; using SQLite; using Syncfusion.Pdf; using Syncfusion.Pdf.Grid; using Syncfusion.Pdf.Graphics; using Syncfusion.Drawing; using Color = Syncfusion.Drawing.Color; using System.Data; using IttezanPos.DependencyServices; using System.Reflection; using Syncfusion.Pdf.Tables; namespace IttezanPos.Views.SupplierPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SuppliersPage : ContentPage { private ObservableCollection<Supplier> suppliers = new ObservableCollection<Supplier>(); public ObservableCollection<Supplier> Suppliers { get { return suppliers; } set { suppliers = value; OnPropertyChanged(nameof(suppliers)); } } public SuppliersPage() { InitializeComponent(); ArabicListView.ItemsSource = Suppliers; Englishlistview.ItemsSource = Suppliers; if (IttezanPos.Helpers.Settings.LastUserGravity == "Arabic") { // listheaderlistv.FlowDirection = FlowDirection.RightToLeft; ArabicListView.IsVisible = true; Englishlistview.IsVisible = false; } else { // listheaderlistv.FlowDirection = FlowDirection.LeftToRight; ArabicListView.IsVisible = false; Englishlistview.IsVisible = true; } } public SuppliersPage(ObservableCollection<Supplier> suppliers) { InitializeComponent(); ArabicListView.ItemsSource = suppliers; Englishlistview.ItemsSource = suppliers; if (IttezanPos.Helpers.Settings.LastUserGravity == "Arabic") { // listheaderlistv.FlowDirection = FlowDirection.RightToLeft; ArabicListView.IsVisible = true; Englishlistview.IsVisible = false; } else { // listheaderlistv.FlowDirection = FlowDirection.LeftToRight; ArabicListView.IsVisible = false; Englishlistview.IsVisible = true; } this.suppliers = suppliers; } private void SearchBar_SearchButtonPressed(object sender, EventArgs e) { var keyword = SearchBar.Text; Englishlistview.ItemsSource = suppliers.Where(product => product.enname.ToLower().Contains(keyword.ToLower())); ArabicListView.ItemsSource = suppliers.Where(product => product.name.ToLower().Contains(keyword.ToLower())); } void OnTextChanged(object sender, EventArgs e) { SearchBar searchBar = (SearchBar)sender; var keyword = SearchBar.Text; Englishlistview.ItemsSource = suppliers.Where(product => product.enname.ToLower().Contains(keyword.ToLower())); ArabicListView.ItemsSource = suppliers.Where(product => product.name.ToLower().Contains(keyword.ToLower())); } private async void Listviewwww_ItemTapped(object sender, ItemTappedEventArgs e) { var content = e.Item as Supplier; await Navigation.PushAsync(new AddingSupplierPage(content)); } private async void Button_Clicked(object sender, EventArgs e) { //Create a new PDF document. PdfDocument doc = new PdfDocument(); //Add a page. PdfPage page = doc.Pages.Add(); Stream fontStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("IttezanPos.Assets.arial.ttf"); PdfTemplate header = PdfHelper.AddHeader(doc, "تقرير الموردين", "Ittezan Pos" + " " + DateTime.Now.ToString()); PdfCellStyle headerStyle = new PdfCellStyle(); headerStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center); page.Graphics.DrawPdfTemplate(header, new PointF()); //Create a PdfGrid. PdfGrid pdfGrid = new PdfGrid(); //String format // PdfFont pdfFont = new PdfTrueTypeFont(fontStream1, 12); //Create a DataTable. DataTable dataTable = new DataTable("EmpDetails"); List<Customer> customerDetails = new List<Customer>(); //Add columns to the DataTable dataTable.Columns.Add("ID"); dataTable.Columns.Add("Name"); dataTable.Columns.Add("Address"); //Add rows to the DataTable. foreach (var item in suppliers) { Customer customer = new Customer(); customer.ID = item.id; customer.Name = item.name; customer.Address = item.address; customerDetails.Add(customer); dataTable.Rows.Add(new string[] { customer.ID.ToString(), customer.Name, customer.Address }); } //Assign data source. pdfGrid.DataSource = dataTable; pdfGrid.Headers.Add(1); PdfGridRow pdfGridRowHeader = pdfGrid.Headers[0]; pdfGridRowHeader.Cells[0].Value = "رقم المورد"; pdfGridRowHeader.Cells[1].Value = "إسم المورد"; pdfGridRowHeader.Cells[2].Value = "عنوان المورد"; PdfGridStyle pdfGridStyle = new PdfGridStyle(); pdfGridStyle.Font = new PdfTrueTypeFont(fontStream, 12); PdfGridLayoutFormat format1 = new PdfGridLayoutFormat(); format1.Break = PdfLayoutBreakType.FitPage; format1.Layout = PdfLayoutType.Paginate; PdfStringFormat format = new PdfStringFormat(); format.TextDirection = PdfTextDirection.RightToLeft; format.Alignment = PdfTextAlignment.Center; format.LineAlignment = PdfVerticalAlignment.Middle; pdfGrid.Columns[0].Format = format; pdfGrid.Columns[1].Format = format; pdfGrid.Columns[2].Format = format; pdfGrid.Style = pdfGridStyle; //Draw grid to the page of PDF document. pdfGrid.Draw(page, new Syncfusion.Drawing.Point(0, (int)header.Height + 10), format1); MemoryStream stream = new MemoryStream(); //Save the document. doc.Save(stream); //close the document doc.Close(true); await Xamarin.Forms.DependencyService.Get<ISave>().SaveAndView("تقرير الموردين.pdf", "application/pdf", stream); } } }<file_sep>using IttezanPos.Helpers; using IttezanPos.Models; using IttezanPos.Resources; using Rg.Plugins.Popup.Extensions; using Rg.Plugins.Popup.Pages; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.SalesPages.SalesPopups { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CalculatorPage : PopupPage { private double percent; private double value; private bool check; private SaleProduct selectedprp; private double alldisc; public CalculatorPage() { InitializeComponent(); FlowDirectionPage(); check = true; } public CalculatorPage(SaleProduct selectedprp) { InitializeComponent(); FlowDirectionPage(); check = true; this.selectedprp = selectedprp; } public CalculatorPage(double alldisc) { InitializeComponent(); FlowDirectionPage(); check = true; this.alldisc = alldisc; } private void FlowDirectionPage() { FlowDirection = (Helpers.Settings.LastUserGravity == "Arabic") ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultures(CultureTypes.NeutralCultures).ToList(). First(element => element.EnglishName.Contains(Helpers.Settings.LastUserGravity)); AppResources.Culture = Thread.CurrentThread.CurrentUICulture; GravityClass.Grav(); } private async void Closelbl_Tapped(object sender, EventArgs e) { await Navigation.PopPopupAsync(); } private void One_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "1"; } private void two_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "2"; } private void three_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "3"; } private void four_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "4"; } private void five_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "5"; } private void six_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "6"; } private void seven_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "7"; } private void eight_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "8"; } private void nine_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "9"; } private void Zero_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "0"; } private void dot_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "."; } private void Clear_Tapped(object sender, EventArgs e) { if (Resultlbl.Text.Length != 0) { Resultlbl.Text = Resultlbl.Text.Remove(Resultlbl.Text.Length - 1, 1); } } private async void Next_Tapped(object sender, EventArgs e) { if (Resultlbl.Text!="") { if (selectedprp == null) { if (check == true) { value = Double.Parse(Resultlbl.Text); percent = 0; } else { value = 0; percent = (double.Parse(Resultlbl.Text) / 100); } MessagingCenter.Send(new ValuePercent() { Value = value, Percentage = percent, alldisc = alldisc }, "PopUpData"); await Navigation.PopPopupAsync(); } else { if (Resultlbl.Text != "") { if (check == true) { value = Double.Parse(Resultlbl.Text); percent = 0; } else { value = 0; percent = (double.Parse(Resultlbl.Text) / 100); } MessagingCenter.Send(new ValuePercentitem() { Value = value, Percentage = percent , product = selectedprp }, "PopUpDataitem"); await Navigation.PopPopupAsync(); } } } } private void Valuebtn_Clicked(object sender, EventArgs e) { check = true; } private void Percentagebtn_Clicked(object sender, EventArgs e) { check = false; } } } <file_sep>using IttezanPos.Models; using SQLite; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Text; using System.Threading.Tasks; namespace IttezanPos.Services { public class OfflineDataBase { public OfflineDataBase() { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); db.CreateTable<Client>(); } } } <file_sep>using Newtonsoft.Json; using SQLite; using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models { public class Client { [JsonProperty("client_id")] public int client_id { get; set; } [JsonProperty("id")] [PrimaryKey,AutoIncrement] public int id { get; set; } [JsonProperty("name")] public string name { get; set; } [JsonProperty("enname")] public string enname { get; set; } [JsonProperty("phone")] public string phone { get; set; } [JsonProperty("email")] public string email { get; set; } [JsonProperty("note")] public string note { get; set; } [JsonProperty("limitt")] public double limitt { get; set; } [JsonProperty("total_amount")] public double total_amount { get; set; } [JsonProperty("paidtotal")] public double paidtotal { get; set; } [JsonProperty("remaining")] public double remaining { get; set; } [JsonProperty("creditorit")] public double creditorit { get; set; } [JsonProperty("address")] public string address { get; set; } [JsonProperty("created_at")] public string created_at { get; set; } [JsonProperty("updated_at")] public string updated_at { get; set; } } public class AddClient { public bool success { get; set; } public Client data { get; set; } public string message { get; set; } } public class AddSupplier { public bool success { get; set; } public Supplier data { get; set; } public string message { get; set; } } public class AddClientError { public bool success { get; set; } public ErrorData data { get; set; } } public class AddSupplierError { public bool success { get; set; } public ErrorData data { get; set; } } public class ErrorData { public List<string> email { get; set; } } public class DelResponse { public bool success { get; set; } public string data { get; set; } public string message { get; set; } } } <file_sep>using SQLite; using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models { public class Box { [PrimaryKey,AutoIncrement] public int id { get; set; } public int type_operation { get; set; } public string balance { get; set; } public string amount { get; set; } public string note { get; set; } public string date { get; set; } public int add_sales_clients { get; set; } public int disc_purchasing_suppliers { get; set; } public int disc_expenses { get; set; } } } <file_sep>using Plugin.Connectivity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using IttezanPos.Helpers; using Xamarin.Forms; using Xamarin.Forms.Xaml; using IttezanPos.Views.MainPage; using IttezanPos.Views.Master; using System.Threading; using System.Globalization; using IttezanPos.Resources; namespace IttezanPos.Views.SettingsPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class GeneralSettings : ContentPage { public GeneralSettings() { InitializeComponent(); } private void Button_Clicked(object sender, EventArgs e) { Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultures(CultureTypes.NeutralCultures).ToList() .First(element => element.EnglishName.Contains("English")); AppResources.Culture = Thread.CurrentThread.CurrentUICulture; Settings.LastUserGravity = "English"; Application.Current.MainPage = new NavigationPage(new MasterPage()); } private void Button_Clicked_1(object sender, EventArgs e) { var language = Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultures(CultureTypes.NeutralCultures).ToList() .First(element => element.EnglishName.Contains("Arabic")); Thread.CurrentThread.CurrentUICulture = language; AppResources.Culture = language; Settings.LastUserGravity = "Arabic"; GravityClass.Grav(); Application.Current.MainPage = new NavigationPage(new MasterPage()); } } }<file_sep>using SQLite; using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models { public class addexpense { [PrimaryKey,AutoIncrement] public int id { get; set; } public double amount { get; set; } public string date { get; set; } public string statement { get; set; } public int user_id { get; set; } } public class AddexpenseData { public string user_id { get; set; } public string amount { get; set; } public string statement { get; set; } public string date { get; set; } public string updated_at { get; set; } public string created_at { get; set; } public int id { get; set; } } public class ExpenseRootObject { public bool success { get; set; } public AddexpenseData data { get; set; } public string message { get; set; } } } <file_sep>using System; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using Android.Print; using Android.Content; using IttezanPos.Droid; using IttezanPos.DependencyServices; using System.IO; [assembly: Dependency(typeof(PrintService))] namespace IttezanPos.Droid { class PrintService : IPrintService { public void Print(Stream inputStream, string fileName) { if (inputStream.CanSeek) //Reset the position of PDF document stream to be printed inputStream.Position = 0; //Create a new file in the Personal folder with the given name string createdFilePath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), fileName); //Save the stream to the created file using (var dest = System.IO.File.OpenWrite(createdFilePath)) inputStream.CopyTo(dest); string filePath = createdFilePath; var activity = Xamarin.Essentials.Platform.CurrentActivity; PrintManager printManager = (PrintManager)activity.GetSystemService(Context.PrintService); PrintDocumentAdapter pda = new CustomPrintDocumentAdapter(filePath); //Print with null PrintAttributes printManager.Print(fileName, pda, null); } } //public class DroidPrintService : IPrintService //{ // public DroidPrintService() // { // } // public void Print(WebView viewToPrint) // { // var droidViewToPrint = Platform.CreateRenderer(viewToPrint).ViewGroup.GetChildAt(0) as Android.Webkit.WebView; // if (droidViewToPrint != null) // { // // Only valid for API 19+ // var version = Android.OS.Build.VERSION.SdkInt; // if (version >= Android.OS.BuildVersionCodes.Kitkat) // { // var printMgr = (PrintManager)Forms.Context.GetSystemService(Context.PrintService); // printMgr.Print("Forms-EZ-Print", droidViewToPrint.CreatePrintDocumentAdapter(), null); // } // } // } //} }<file_sep>using SQLite; using SQLiteNetExtensions.Attributes; using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models { public class Product { [PrimaryKey,AutoIncrement] public int id { get; set; } [ForeignKey(typeof(Category2))] public int category2Id { get; set; } public string barcode { get; set; } public string user_id { get; set; } public string catname { get; set; } public int category_id { get; set; } public int purchasing_order { get; set; } public string product_name { get; set; } public int product_id { get; set; } public double quantity { get; set; } public double discount { get; set; } public string user { get; set; } public string name { get; set; } public string Enname { get; set; } public string locale { get; set; } public string image { get; set; } public double purchase_price { get; set; } public double total_price { get; set; } public double sale_price { get; set; } public int stock { get; set; } public string profit_percent { get; set; } public string description { get; set; } public DateTimeOffset? created_at { get; set; } public DateTimeOffset? expiration_date { get; set; } public DateTimeOffset? updated_at { get; set; } [OneToMany(CascadeOperations = CascadeOperation.All),Ignore] public List<Translation> translations { get; set; } } public class AddProduct { public bool success { get; set; } public string data { get; set; } public string message { get; set; } } public class SaleProduct : Product { [ForeignKey(typeof(OrderItem))] public int orderId { get; set; } [ForeignKey(typeof(HoldProduct))] public int holdrId { get; set; } public int client_id { get; set; } public string payment_type { get; set; } public string amount_paid { get; set; } public int remaining_amount { get; set; } } public class HoldProduct { [PrimaryKey, AutoIncrement] public int id { get; set; } [ForeignKey(typeof(SaleProduct))] public int saleproductid { get; set; } public string total { get; set; } public string subtotal { get; set; } public string discount { get; set; } public string number { get; set; } public DateTimeOffset? created_at { get; set; } public DateTimeOffset? updated_at { get; set; } [OneToMany(CascadeOperations = CascadeOperation.All), Ignore] public List<SaleProduct> saleProducts { get; set; } } } <file_sep>using IttezanPos.Models; using Refit; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace IttezanPos.ViewModels { public class InventoryViewModel { [Headers("Content-Type: application/json")] public interface IUpdateService { [Post("/api/updateprice")] Task<RootObjectUpdate> UpdatePrice(Updateprice client); [Post("/api/addexpense")] Task<ExpenseRootObject> addexpense(addexpense client); } } } <file_sep>using Newtonsoft.Json; using SQLite; using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models.OfflineModel { public class AddClientOffline : Client { } public class UpdateClientOffline { [JsonProperty("client_id")] public int client_id { get; set; } [JsonProperty("id")] [PrimaryKey, AutoIncrement] public int id { get; set; } [JsonProperty("name")] public string name { get; set; } [JsonProperty("enname")] public string enname { get; set; } [JsonProperty("phone")] public string phone { get; set; } [JsonProperty("email")] public string email { get; set; } [JsonProperty("note")] public string note { get; set; } [JsonProperty("limitt")] public double limitt { get; set; } [JsonProperty("address")] public string address { get; set; } } public class DeleteClientOffline : Client { } public class OfflineClientAdded { public bool success { get; set; } public List<Client> data { get; set; } public string message { get; set; } } } <file_sep>using IttezanPos.Views.Master; using Plugin.Connectivity; using System.Linq; using Xamarin.Forms; using IttezanPos.Helpers; using IttezanPos.Views.SettingsPages; using IttezanPos.Views.MainPage; using DLToolkit.Forms.Controls; namespace IttezanPos { public partial class App : Application { public App() { InitializeComponent(); Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("<KEY>"); FlowListView.Init(); FlowDirectionPage(); MainPage = new NavigationPage( new MasterPage()); } private void FlowDirectionPage() { _ = Settings.LastUserGravity == "English"; } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } } <file_sep>using IttezanPos.Models; using IttezanPos.Models.OfflineModel; using IttezanPos.Resources; using IttezanPos.Services; using Plugin.Connectivity; using Refit; using Rg.Plugins.Popup.Extensions; using Rg.Plugins.Popup.Services; using SQLite; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using static IttezanPos.ViewModels.SupplierViewModel; namespace IttezanPos.Views.SupplierPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AddingSupplierPage : ContentPage { private Supplier content; private string edite; public ObservableCollection<Supplier> Suppliers { get; private set; } public AddingSupplierPage() { InitializeComponent(); } public AddingSupplierPage(Supplier content) { InitializeComponent(); this.content = content; SupplierNameArentry.Text = content.name; SupplierEnnamenentry.Text = content.enname; SupplierAddressentry.Text = content.address; SupplierEmailentry.Text = content.email; SupplierPhoneentry.Text = content.phone; SupplierNotesentry.Text = content.note; Detailsstk.IsVisible = true; savrbtn.IsVisible = false; } private async void Button_Clicked(object sender, EventArgs e) { try { ActiveIn.IsVisible = true; if (CrossConnectivity.Current.IsConnected) { Supplier supplier = new Supplier { name = SupplierNameArentry.Text, enname = SupplierEnnamenentry.Text, address = SupplierAddressentry.Text, email = SupplierEmailentry.Text, phone = SupplierPhoneentry.Text, note = SupplierNotesentry.Text, }; var nsAPI = RestService.For<ISupplierService>("https://ittezanmobilepos.com"); try { var data = await nsAPI.AddSupplier(supplier); if (data.success == true) { ActiveIn.IsVisible = false; await Navigation.PushPopupAsync(new SupplierAddedPopup()); } } catch { ActiveIn.IsVisible = false; var data = await nsAPI.AddSupplierError(supplier); await Navigation.PushPopupAsync(new SupplierAddedPopup(data.data.email.First())); SupplierEmailentry.Focus(); } } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Supplier"); if (!info.Any()) db.CreateTable<Supplier>(); db.CreateTable<AddSupplierOffline>(); Supplier client = new Supplier { name = SupplierNameArentry.Text, enname = SupplierEnnamenentry.Text, address = SupplierAddressentry.Text, email = SupplierEmailentry.Text, phone = SupplierPhoneentry.Text, note = SupplierNotesentry.Text, created_at = DateTime.Now.ToString() }; Suppliers = new ObservableCollection<Supplier>(db.Table<Supplier>().ToList()); var udatedclient = Suppliers. Where(i => i.email == client.email).ToList(); // var udatedclient = db.Table<Supplier>().Where(i => i.email == client.email).First(); if (udatedclient .Count== 0) { ActiveIn.IsVisible = false; AddSupplierOffline supplierOffline = new AddSupplierOffline { name = SupplierNameArentry.Text, enname = SupplierEnnamenentry.Text, address = SupplierAddressentry.Text, email = SupplierEmailentry.Text, phone = SupplierPhoneentry.Text, note = SupplierNotesentry.Text, created_at = DateTime.Now.ToString() }; db.Insert(supplierOffline); db.Insert(client); await Navigation.PushPopupAsync(new SupplierAddedPopup()); await Navigation.PopAsync(); } else { ActiveIn.IsVisible = false; await Navigation.PushPopupAsync(new SupplierAddedPopup("قيمة البريد الالكتروني مُستخدمة من قبل")); SupplierEmailentry.Focus(); } } } catch (ValidationApiException validationException) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 } catch (ApiException exception) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } private async void Update_Clicked(object sender, EventArgs e) { try { ActiveIn.IsVisible = true; if (CrossConnectivity.Current.IsConnected) { Supplier supplier = new Supplier { id = content.id, name = SupplierNameArentry.Text, enname = SupplierEnnamenentry.Text, address = SupplierAddressentry.Text, email = SupplierEmailentry.Text, phone = SupplierPhoneentry.Text, note = SupplierNotesentry.Text, }; var nsAPI = RestService.For<ISupplierService>("https://ittezanmobilepos.com"); var data = await nsAPI.UpdateSupplier(supplier); if (data.success == true) { ActiveIn.IsVisible = false; await Navigation.PushPopupAsync(new SupplierAddedPopup(edite)); await Navigation.PopAsync(); } } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Supplier"); if (!info.Any()) db.CreateTable<Supplier>(); db.CreateTable<UpdateSupplierOffline>(); Supplier client = new Supplier { id = content.id, name = SupplierNameArentry.Text, enname = SupplierEnnamenentry.Text, address = SupplierAddressentry.Text, email = SupplierEmailentry.Text, phone = SupplierPhoneentry.Text, note = SupplierNotesentry.Text, updated_at = DateTime.Now.ToString() }; var udatedclient = db.Table<Supplier>().Where(i => i.email == client.email).First(); UpdateSupplierOffline supplierOffline = new UpdateSupplierOffline { supplier_id= content.supplier_id, name = SupplierNameArentry.Text, enname = SupplierEnnamenentry.Text, address = SupplierAddressentry.Text, email = SupplierEmailentry.Text, phone = SupplierPhoneentry.Text, note = SupplierNotesentry.Text, }; db.Insert(supplierOffline); db.Update(client); ActiveIn.IsVisible = false; await Navigation.PushPopupAsync(new SupplierAddedPopup(edite)); await Navigation.PopAsync(); } } catch (ValidationApiException validationException) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 } catch (ApiException exception) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } private async void Deletebtn_Clicked(object sender, EventArgs e) { try { ActiveIn.IsVisible = true; if (CrossConnectivity.Current.IsConnected) { var nsAPI = RestService.For<ISupplierService>("https://ittezanmobilepos.com"); var data = await nsAPI.DeleteSupplier(content.id); if (data.success == true) { ActiveIn.IsVisible = false; await Navigation.PushPopupAsync(new SupplierAddedPopup(content.id)); await Navigation.PopAsync(); } } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Supplier"); if (!info.Any()) db.CreateTable<Supplier>(); db.CreateTable<DeleteSupplierOffline>(); Supplier client = new Supplier { id = content.id, name = SupplierNameArentry.Text, enname = SupplierEnnamenentry.Text, address = SupplierAddressentry.Text, email = SupplierEmailentry.Text, phone = SupplierPhoneentry.Text, note = SupplierNotesentry.Text, }; // var udatedclient = db.Table<Client>().Where(i => i.email == client.email).First(); DeleteSupplierOffline supplierOffline = new DeleteSupplierOffline { name = SupplierNameArentry.Text, enname = SupplierEnnamenentry.Text, address = SupplierAddressentry.Text, email = SupplierEmailentry.Text, phone = SupplierPhoneentry.Text, note = SupplierNotesentry.Text, created_at = DateTime.Now.ToString(), updated_at = DateTime.Now.ToString(), }; db.Insert(supplierOffline); db.Delete(client); ActiveIn.IsVisible = false; await Navigation.PushPopupAsync(new SupplierAddedPopup(content.id)); await Navigation.PopAsync(); } } catch (ValidationApiException validationException) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 } catch (ApiException exception) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { ActiveIn.IsVisible = false; await DisplayAlert(IttezanPos.Resources.AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } }<file_sep>using IttezanPos.Resources; using Rg.Plugins.Popup.Pages; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.SupplierPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SupplierAddedPopup : PopupPage { private string edite; private int id; public SupplierAddedPopup() { InitializeComponent(); Frame.BorderColor = Color.FromHex("#33b54b"); } public SupplierAddedPopup(string edite) { InitializeComponent(); if (edite == "قيمة البريد الالكتروني مُستخدمة من قبل") { Frame.BorderColor = Color.Red; Supplierlbl.Text = AppResources.UsedEmail; } else { Frame.BorderColor = Color.FromHex("#33b54b"); Supplierlbl.Text = AppResources.UpdatedSupplier; } } public SupplierAddedPopup(int id) { InitializeComponent(); Frame.BorderColor = Color.Red; Supplierlbl.Text = AppResources.DeletedSupplier; this.id = id; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using IttezanPos.Models; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class RecieptPage : ContentPage { private List<OrderItem> products; private List<Product> saleproducts; private string paymentname; public RecieptPage() { InitializeComponent(); } public RecieptPage(List<OrderItem> products, List<Product> saleproducts, string paymentname) { InitializeComponent(); this.products = products; this.saleproducts = saleproducts; this.paymentname = paymentname; Invoiceidlbl.Text = products[0].id.ToString(); Datelbl.Text = DateTime.Now.ToLongDateString(); paymenttypelbl.Text = paymentname; Amountlbl.Text= products[0].amount_paid; ; RecieptList.ItemsSource = saleproducts; } protected override bool OnBackButtonPressed() { return true; } } }<file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using IttezanPos.Helpers; using IttezanPos.Resources; using Plugin.Connectivity; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.Master { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SideMenuPage : ContentPage { public SideMenuPage() { InitializeComponent(); FlowDirectionPage(); } private void FlowDirectionPage() { FlowDirection = (Settings.LastUserGravity == "Arabic") ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultures(CultureTypes.NeutralCultures).ToList(). First(element => element.EnglishName.Contains(Settings.LastUserGravity)); AppResources.Culture = Thread.CurrentThread.CurrentUICulture; GravityClass.Grav(); } } } <file_sep>using Plugin.Permissions.Abstractions; using Plugin.Permissions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using ZXing.Net.Mobile.Forms; using Plugin.Connectivity; using Refit; using IttezanPos.Models; using System.Collections.ObjectModel; using IttezanPos.Services; using System.IO; using SQLite; using Rg.Plugins.Popup.Extensions; using IttezanPos.Views.SalesPages.SalesPopups; using IttezanPos.Resources; namespace IttezanPos.Views.PurchasingPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class PurchasePage : ContentPage { private List<Product> products = new List<Product>(); public List<Product> Products { get { return products; } set { products = value; OnPropertyChanged(nameof(products)); } } private ObservableCollection<Category> categories = new ObservableCollection<Category>(); public ObservableCollection<Category> Categories { get { return categories; } set { categories = value; OnPropertyChanged(nameof(categories)); } } private List<Product> purchaseproducts = new List<Product>(); public List<Product> PurchaseProducts { get { return purchaseproducts; } set { products = value; OnPropertyChanged(nameof(purchaseproducts)); } } private ObservableCollection<Product> purchasesro = new ObservableCollection<Product>(); public ObservableCollection<Product> purchasero { get { return purchasesro; } set { purchasesro = value; OnPropertyChanged(nameof(purchasesro)); } } public PurchasePage() { InitializeComponent(); } private void Scan_Tapped(object sender, EventArgs e) { Scanner(); } public async void Scanner() { var ScannerPage = new ZXingScannerPage(); _ = Navigation.PushAsync(ScannerPage); try { var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera); if (status != PermissionStatus.Granted) { if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Camera)) { await DisplayAlert(AppResources.Alert, AppResources.NeedCamera, AppResources.Ok); } var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Camera); status = results[Permission.Location]; } if (status == PermissionStatus.Granted) { ScannerPage.OnScanResult += (result) => { Device.BeginInvokeOnMainThread(() => { _ = Navigation.PopAsync(); }); }; } else { await DisplayAlert(AppResources.Alert, AppResources.PermissionsDenied, AppResources.Ok); //On iOS you may want to send your user to the settings screen. CrossPermissions.Current.OpenAppSettings(); } } catch (Exception ex) { await DisplayAlert(AppResources.Alert, AppResources.PermissionsDenied, AppResources.Ok); //On iOS you may want to send your user to the settings screen. CrossPermissions.Current.OpenAppSettings(); } } private void Master_Tapped(object sender, EventArgs e) { var page = (App.Current.MainPage as NavigationPage).CurrentPage; (page as MasterDetailPage).IsPresented = true; } protected override void OnAppearing() { _ = GetData(); base.OnAppearing(); } async Task GetData() { try { ActiveIn.IsVisible = true; if (CrossConnectivity.Current.IsConnected) { var nsAPI = RestService.For<IApiService>("https://ittezanmobilepos.com/"); RootObject data = await nsAPI.GetSettings(); var eachCategories = new ObservableCollection<Category>(data.message.categories); Categories = eachCategories; foreach (var item in eachCategories) { foreach (var item2 in item.category.list_of_products) { item2.product_id = item2.id; } Products.AddRange(item.category.list_of_products); } if (Device.RuntimePlatform == Device.iOS) { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Product"); if (!info.Any()) { db.CreateTable<Product>(); } else { db.CreateTable<Product>(); } db.DeleteAll<Product>(); db.InsertAll(Products); } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Product"); db.DeleteAll<Product>(); db.CreateTable<Product>(); db.CreateTable<Category>(); foreach (var item in Products) { db.InsertOrReplace(item); } db.InsertAll(Categories); } ProductsList.FlowItemsSource = products; ActiveIn.IsVisible = false; } else { ActiveIn.IsVisible = false; if (Device.RuntimePlatform == Device.iOS) { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Product"); if (!info.Any()) db.CreateTable<Product>(); db.CreateTable<Category>(); Products = (db.Table<Product>().ToList()); Categories = new ObservableCollection<Category>(db.Table<Category>().ToList()); } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Product"); var info2 = db.GetTableInfo("Category"); Products = (db.Table<Product>().ToList()); Categories = new ObservableCollection<Category>(db.Table<Category>().ToList()); } ProductsList.FlowItemsSource = Products; } } catch (ValidationApiException validationException) { // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } catch (ApiException exception) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } private void ShowProductlistbtn_Clicked(object sender, EventArgs e) { if (ProductsList.IsVisible == true) { ProductsList.IsVisible = false; } else { ProductsList.IsVisible = true; } } private void ProductsList_FlowItemTapped(object sender, ItemTappedEventArgs e) { var saleproduct = ProductsList.FlowLastTappedItem as Product; saleproduct.total_price = saleproduct.purchase_price * saleproduct.quantity; totallbl.Text= (double.Parse(totallbl.Text) - double.Parse(saleproduct.total_price.ToString())).ToString("0.00"); saleproduct.quantity++; saleproduct.total_price = saleproduct.purchase_price * saleproduct.quantity; if (purchaseproducts.Count() == 0) { purchaseproducts.Add(saleproduct); cartnolbl.Text = (int.Parse(cartnolbl.Text) + 1).ToString(); totallbl.Text= (double.Parse(totallbl.Text) + double.Parse(saleproduct.total_price.ToString())).ToString("0.00"); } else { var obj = PurchaseProducts.Find(x => x.id == saleproduct.id); if (obj != null) { cartnolbl.Text = (int.Parse(cartnolbl.Text) + 1).ToString(); totallbl.Text = (double.Parse(totallbl.Text) + double.Parse(saleproduct.total_price.ToString())).ToString("0.00"); } else { cartnolbl.Text = (int.Parse(cartnolbl.Text) + 1).ToString(); totallbl.Text = (double.Parse(totallbl.Text) + double.Parse(saleproduct.total_price.ToString())).ToString("0.00"); PurchaseProducts.Add(saleproduct); } } purchasero = new ObservableCollection<Product>(PurchaseProducts); SalesList.ItemsSource = purchasero; } private void CustomEntry_TextChanged(object sender, TextChangedEventArgs e) { if (((sender as Entry).BindingContext is Product _selectedUser)) { if (e.OldTextValue != null) { if (e.OldTextValue == "") { cartnolbl.Text = int.Parse(cartnolbl.Text).ToString(); } else { cartnolbl.Text = (int.Parse(cartnolbl.Text) - int.Parse(e.OldTextValue)).ToString(); totallbl.Text = (double.Parse(totallbl.Text) - double.Parse(_selectedUser.total_price.ToString())).ToString("0.00"); } // totallbl.Text = total.ToString(); if (e.NewTextValue != "") { if (e.NewTextValue != "1") { cartnolbl.Text = (int.Parse(cartnolbl.Text) + _selectedUser.quantity).ToString(); _selectedUser.quantity = int.Parse(e.NewTextValue); _selectedUser.total_price = _selectedUser.purchase_price * _selectedUser.quantity; totallbl.Text = (double.Parse(totallbl.Text) + _selectedUser.total_price).ToString("0.00"); purchasero = new ObservableCollection<Product>(PurchaseProducts); SalesList.ItemsSource = purchasero; } else { cartnolbl.Text = (int.Parse(cartnolbl.Text) + _selectedUser.quantity).ToString(); _selectedUser.quantity = int.Parse(e.NewTextValue); _selectedUser.total_price = _selectedUser.purchase_price * _selectedUser.quantity; totallbl.Text = (double.Parse(totallbl.Text) + _selectedUser.total_price).ToString("0.00"); purchasero = new ObservableCollection<Product>(PurchaseProducts); SalesList.ItemsSource = purchasero; } } } } } private async void cost_Tapped(object sender, EventArgs e) { if (((sender as Label).BindingContext is Product _selectedro)) { await Navigation.PushPopupAsync(new purchasePopUpPage(_selectedro)); MessagingCenter.Subscribe<ValuePercent>(this, "PopUpData", (value) => { _selectedro.sale_price = value.Value; _selectedro.purchase_price = value.Percentage; _selectedro.total_price = _selectedro.purchase_price * _selectedro.quantity; purchasero = new ObservableCollection<Product>(PurchaseProducts); SalesList.ItemsSource = purchasero; }); } } private void delete_Clicked(object sender, EventArgs e) { if (((sender as Button).BindingContext is Product _selectedro)) { _selectedro.total_price = _selectedro.purchase_price * _selectedro.quantity; cartnolbl.Text = (int.Parse(cartnolbl.Text) - _selectedro.quantity).ToString(); _selectedro.quantity = 0; totallbl.Text = (double.Parse(totallbl.Text) - _selectedro.total_price).ToString("0.00"); PurchaseProducts.Remove(_selectedro); purchasero.Remove(_selectedro); purchasero = new ObservableCollection<Product>(PurchaseProducts); SalesList.ItemsSource = purchasero; } } private async void Nextage_Tapped(object sender, EventArgs e) { if (PurchaseProducts.Count() == 0) { await DisplayAlert(AppResources.Alert, AppResources.SelectProduct, AppResources.Ok); } else { await Navigation.PushAsync(new PurchaseCheckout(PurchaseProducts, totallbl.Text)); } } } }<file_sep>using Newtonsoft.Json; using SQLite; using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models { public class Updateprice { [PrimaryKey, AutoIncrement] public int id { get; set; } public int up_down { get; set; } public int purchase_sale { get; set; } public int value_ratio { get; set; } public int category_id { get; set; } public double amount { get; set; } } public class RootObjectUpdate { [JsonProperty("success")] public bool success { get; set; } [JsonProperty("data")] public string data { get; set; } [JsonProperty("message")] public string message { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Text; using Xamarin.Forms; namespace IttezanPos.DependencyServices { public interface IPrintService { // void Print(WebView viewToPrint); void Print(Stream inputStream, string fileName); } } <file_sep>using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; namespace IttezanPos.Helpers { public class PdfHelper { public static PdfTemplate AddHeader(PdfDocument doc, string title, string description) { SizeF rect = new SizeF(doc.Pages[0].GetClientSize().Width, 50); //Create page template PdfTemplate header = new PdfTemplate(rect); PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 24); float doubleHeight = font.Height * 2; Color activeColor = Color.LimeGreen; SizeF imageSize = new SizeF(110f, 35f); //Locating the logo on the right corner of the drawing surface PointF imageLocation = new PointF(doc.Pages[0].GetClientSize().Width - imageSize.Width - 20, 5); PdfSolidBrush brush = new PdfSolidBrush(activeColor); PdfPen pen = new PdfPen(Color.LimeGreen, 3f); Stream fontStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("IttezanPos.Assets.arial.ttf"); // font = new PdfStandardFont(PdfFontFamily.Helvetica, 16, PdfFontStyle.Bold); PdfFont pdfFont = new PdfTrueTypeFont(fontStream, 12); //Set formatting for the text PdfStringFormat format = new PdfStringFormat(); format.TextDirection = PdfTextDirection.RightToLeft; format.Alignment = PdfTextAlignment.Center; format.LineAlignment = PdfVerticalAlignment.Middle; //Draw title header.Graphics.DrawString(title, pdfFont, brush, new RectangleF(0, 0, header.Width, header.Height), format); brush = new PdfSolidBrush(Color.Gray); font = new PdfStandardFont(PdfFontFamily.Helvetica, 6, PdfFontStyle.Bold); format = new PdfStringFormat(); format.TextDirection = PdfTextDirection.RightToLeft; format.Alignment = PdfTextAlignment.Center; format.LineAlignment = PdfVerticalAlignment.Bottom; //Draw description header.Graphics.DrawString(description, font, brush, new RectangleF(0, 0, header.Width, header.Height - 8), format); //Draw some lines in the header pen = new PdfPen(Color.LimeGreen, 0.7f); header.Graphics.DrawLine(pen, 0, 0, header.Width, 0); pen = new PdfPen(Color.LimeGreen, 2f); header.Graphics.DrawLine(pen, 0, 03, header.Width + 3, 03); pen = new PdfPen(Color.LimeGreen, 2f); header.Graphics.DrawLine(pen, 0, header.Height - 3, header.Width, header.Height - 3); header.Graphics.DrawLine(pen, 0, header.Height, header.Width, header.Height); return header; } } } <file_sep>using Newtonsoft.Json; using SQLite; using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models { public class Supplier { public int supplier_id { get; set; } [PrimaryKey, AutoIncrement] public int id { get; set; } public string name { get; set; } [JsonProperty("enname")] public string enname { get; set; } public string address { get; set; } public string phone { get; set; } public string email { get; set; } public string note { get; set; } [JsonProperty("total_amount")] public double total_amount { get; set; } [JsonProperty("paid_amount")] public double paid_amount { get; set; } [JsonProperty("remaining")] public double remaining { get; set; } [JsonProperty("creditorit")] public double creditorit { get; set; } public string created_at { get; set; } public string updated_at { get; set; } } public class SuplierTotalAmount { public string name { get; set; } public double remaining { get; set; } public double creditorit { get; set; } public double paid_amount { get; set; } public double total_amount { get; set; } } } <file_sep>using Newtonsoft.Json; using SQLite; using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models.OfflineModel { public class OfflineProduct { [JsonProperty("category_id")] [PrimaryKey] public int category_id { get; set; } public string name { get; set; } public string enname { get; set; } public string barcode { get; set; } public double purchase_price { get; set; } public double sale_price { get; set; } public double stock { get; set; } public string image { get; set; } public int user_id { get; set; } public string notes { get; set; } public string expiredate { get; set; } public int trackinstore { get; set; } public int type { get; set; } public string description { get; set; } } public class UpdateOfflineProduct { [JsonProperty("product_id")] [PrimaryKey, AutoIncrement] public int product_id { get; set; } [JsonProperty("category_id")] public int category_id { get; set; } public string name { get; set; } public string enname { get; set; } public string barcode { get; set; } public double purchase_price { get; set; } public double sale_price { get; set; } public double stock { get; set; } public string image { get; set; } public int user_id { get; set; } public string notes { get; set; } public string expiredate { get; set; } public int trackinstore { get; set; } public int type { get; set; } public string description { get; set; } } public class DeleteOfflineProduct : Product { } } <file_sep>using IttezanPos.Models; using Refit; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace IttezanPos.ViewModels { public class ClientViewModel { [Headers("Content-Type: application/json")] public interface IClientService { [Post("/api/addclient")] Task<RootObject> AddClient(Client client); [Post("/api/addclient")] Task<AddClientError> AddClientError(Client client); [Post("/api/updateclient")] Task<RootObject> UpdateClient(Client client); [Post("/api/delclient")] Task<DelResponse> DeleteClient(int client_id); } } } <file_sep>using IttezanPos.Helpers; using IttezanPos.Resources; using IttezanPos.Views.Master; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.SalesPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SalesMaster : MasterDetailPage { public SalesMaster() { InitializeComponent(); if (Device.Idiom == TargetIdiom.Tablet) MasterBehavior = MasterBehavior.Popover; FlowDirectionPage(); SaleNewMenu.listView.ItemSelected += OnItemSelected; SaleNewMenu.newlist.ItemSelected += OnItemSelected; SaleNewMenu.listhelp.ItemSelected += OnItemSelected; } private void FlowDirectionPage() { FlowDirection = (Settings.LastUserGravity == "Arabic") ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultures(CultureTypes.NeutralCultures).ToList(). First(element => element.EnglishName.Contains(Settings.LastUserGravity)); AppResources.Culture = Thread.CurrentThread.CurrentUICulture; GravityClass.Grav(); } void OnItemSelected(object sender, SelectedItemChangedEventArgs e) { var item = e.SelectedItem as MasterPageItem; if (item != null) { Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType)); SaleNewMenu.listView.SelectedItem = null; SaleNewMenu.newlist.SelectedItem = null; SaleNewMenu.listhelp.SelectedItem = null; SaleNewMenu.listhelp.SelectedItem = null; IsPresented = false; } } } }<file_sep>using Newtonsoft.Json; using SQLite; using SQLiteNetExtensions.Attributes; using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models { public class Category { [PrimaryKey,AutoIncrement,] public int Id { get; set; } [ForeignKey(typeof(Category2))] public int category2Id { get; set; } [ManyToOne] public Category2 category { get; set; } } public class Settings { public int id { get; set; } public string name { get; set; } public string enname { get; set; } public string about { get; set; } public string enabout { get; set; } public string policy { get; set; } public string enpolicy { get; set; } public string logo { get; set; } public object how_used { get; set; } public object connect_us { get; set; } public string phone { get; set; } public object mobile { get; set; } public string Address { get; set; } public string email { get; set; } public string price1 { get; set; } public string price2 { get; set; } public string price3 { get; set; } public object client_video { get; set; } public object company_video { get; set; } public object comp_cond { get; set; } public object ecomp_cond { get; set; } public object comp_policy { get; set; } public object ecomp_policy { get; set; } public object comp_connect { get; set; } public object ecomp_connect { get; set; } public object created_at { get; set; } public string updated_at { get; set; } } public class Category2 { [PrimaryKey, AutoIncrement] public int id { get; set; } [OneToMany(CascadeOperations = CascadeOperation.All)] public List<Category> categories { get; set; } [JsonProperty("created_at")] public DateTimeOffset created_at { get; set; } [JsonProperty("updated_at")] public DateTimeOffset updated_at { get; set; } [OneToMany(CascadeOperations = CascadeOperation.All)] [JsonProperty("list_of_products")] public List<Product> list_of_products { get; set; } [JsonProperty("name")] public string name { get; set; } [JsonProperty("enname")] public string enname { get; set; } [OneToMany(CascadeOperations = CascadeOperation.All)] public List<Translation> translations { get; set; } } public class Message { [JsonProperty("settings")] public Settings settings { get; set; } [JsonProperty("clients")] public List<Client> clients { get; set; } [JsonProperty("suppliers")] public List<Supplier> suppliers { get; set; } [JsonProperty("box")] public Box box { get; set; } [JsonProperty("payments")] public List<Payment> payments { get; set; } [JsonProperty("users")] public List<User> users { get; set; } [JsonProperty("categories")] public List<Category> categories { get; set; } } public class Payment { [JsonProperty("id")] [PrimaryKey] public int Id { get; set; } [JsonProperty("payment_type")] public string PaymentType { get; set; } [JsonProperty("payment_type_enname")] public string PaymentTypeEnname { get; set; } [JsonProperty("created_at")] public DateTimeOffset CreatedAt { get; set; } [JsonProperty("updated_at")] public DateTimeOffset UpdatedAt { get; set; } } public class RootObject { [JsonProperty("success")] public bool success { get; set; } [JsonProperty("data")] public string data { get; set; } [JsonProperty("message")] public Message message { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using IttezanPos.Helpers; using System.Linq; using System.Text; using System.Threading.Tasks; using IttezanPos.Models; using IttezanPos.Services; using IttezanPos.Views.SalesPages.SalesPopups; using Plugin.Connectivity; using Refit; using Rg.Plugins.Popup.Services; using SQLite; using Xamarin.Forms; using Xamarin.Forms.Xaml; using static IttezanPos.ViewModels.SalesViewModel; using System.Net.Http; using Newtonsoft.Json; using IttezanPos.Resources; using Plugin.Toast; using SQLiteNetExtensions.Extensions; using System.Threading; using System.Globalization; namespace IttezanPos.Views.SalesPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CheckOutPage : ContentPage { public List<SaleProduct> saleproducts; private string text1; private string text2; private string text3; private string paymentid = "1"; private string paymentname= "cash"; private string paymentarname = "كاش"; private string clienttid = null; private string amount_paid; public ObservableCollection<Payment> payments; private List<OrderItem> orderitems; private List<Product> Products; public CheckOutPage(List<SaleProduct> saleproducts, string text1, string text2, string text3, ObservableCollection<Payment> payments, List<Product> Products) { InitializeComponent(); FlowDirectionPage(); PaymentListar.ItemsSource = PaymentListen.ItemsSource = payments; Amountpaidentry.Text = text2; if (IttezanPos.Helpers.Settings.LastUserGravity == "Arabic") { PaymentListar.IsVisible = true; PaymentListen.IsVisible = false; } else { PaymentListar.IsVisible = false; PaymentListen.IsVisible = true; } MessagingCenter.Subscribe<Client>(this, "PopUpData", (value) => { CustName.Text = value.name; clienttid= value.id.ToString(); }); this.saleproducts = saleproducts; this.text2= totallbl.Text = text2; this.text1= Disclbl.Text = text1; this.text3= subtotallbl.Text = text3; this.Products = Products; } private void FlowDirectionPage() { FlowDirection = (Helpers.Settings.LastUserGravity == "Arabic") ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultures(CultureTypes.NeutralCultures).ToList(). First(element => element.EnglishName.Contains(Helpers.Settings.LastUserGravity)); AppResources.Culture = Thread.CurrentThread.CurrentUICulture; GravityClass.Grav(); } private async void Customer_Tapped(object sender, EventArgs e) { await Navigation.PushAsync(new ClientPopup()); } private void PaymentList_SelectedIndexChanged(object sender, EventArgs e) { var payment = PaymentListen.SelectedItem as Payment; paymentname = paymentlbl.Text = payment.PaymentTypeEnname; paymentid = payment.Id.ToString(); } private void PaymentListar_SelectedIndexChanged(object sender, EventArgs e) { var payment = PaymentListar.SelectedItem as Payment; paymentname = paymentlbl.Text = payment.PaymentType; paymentid = payment.Id.ToString(); } private async void Nextbtn_Clicked(object sender, EventArgs e) { if (paymentid == "3" && clienttid == null) { await DisplayAlert(AppResources.Alert, AppResources.ChooseCustomer, AppResources.Ok); await Navigation.PushAsync(new ClientPopup()); } else if (paymentid == "3" && clienttid != null) { ActiveIn.IsRunning = true; if (Amountpaidentry.Text != "") { amount_paid = Amountpaidentry.Text; } else { amount_paid = "0"; } OrderItem product = new OrderItem { discount = text1, products = saleproducts, total_price = text2, amount_paid = amount_paid, client_id = clienttid, user_id = 3, payment_type = paymentid }; var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("OrderItem"); if (!info.Any()) { db.CreateTable<OrderItem>(); db.CreateTable<SaleProduct>(); db.InsertAll(saleproducts); db.InsertWithChildren(product); } else { db.DeleteAll(saleproducts); db.InsertAll(saleproducts); db.InsertWithChildren(product); } orderitems = (db.GetAllWithChildren<OrderItem>().ToList()); var client = (db.Table<Client>().ToList().Where(clien => clien.id == int.Parse(clienttid)).FirstOrDefault()); client.paidtotal = client.paidtotal + double.Parse(amount_paid); var amount = (double.Parse(text2) - double.Parse(amount_paid)); if (amount >= 0) { client.remaining = client.remaining + amount; } else { client.creditorit = client.creditorit + amount; } client.total_amount = client.total_amount + double.Parse(text2); client.updated_at = DateTime.Now.ToString(); foreach (var item in Products) { foreach (var itemp in saleproducts) { if (item.id == itemp.id) { item.stock = item.stock - int.Parse(itemp.quantity.ToString()); } } } db.Update(client); db.UpdateAll(Products); await Navigation.PushAsync(new SuccessfulReciep(product, paymentname)); } else { ActiveIn.IsRunning = true; if (Amountpaidentry.Text != "" && double.Parse(Amountpaidentry.Text) >= double.Parse(text2.ToString())) { amount_paid = Amountpaidentry.Text; OrderItem orderItem = new OrderItem(); orderItem.amount_paid = amount_paid; orderItem.client_id = clienttid; orderItem.created_at = DateTime.Now; orderItem.discount = text1; orderItem.products = saleproducts; orderItem.total_price = text2; orderItem.user_id = 3; orderItem.payment_type = paymentid; var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("SaleObject"); if (!info.Any()) { db.CreateTable<OrderItem>(); db.CreateTable<SaleProduct>(); // db.InsertAll(saleproducts); db.InsertWithChildren(orderItem); } else { db.InsertWithChildren(orderItem); } orderitems = (db.GetAllWithChildren<OrderItem>().ToList()); if (clienttid != null) { var client = (db.Table<Client>().ToList().Where(clien => clien.id == int.Parse(clienttid)).FirstOrDefault()); if (client != null) { client.paidtotal = client.paidtotal + double.Parse(amount_paid); // client.remaining = client.remaining+ 0; client.total_amount = client.total_amount + double.Parse(text2); // client.creditorit = client.creditorit client.updated_at = DateTime.Now.ToString(); db.Update(client); } } foreach (var item in Products) { foreach (var itemp in saleproducts) { if (item.product_id == itemp.product_id) { item.stock = item.stock - int.Parse(itemp.quantity.ToString()); item.quantity = 0; item.discount = 0; item.total_price = 0; } } } db.UpdateAll(Products); App.Current.MainPage = new NavigationPage(new SuccessfulReciep(orderItem, paymentname)); } else { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.Addsaleserror, AppResources.Ok); Amountpaidentry.Focus(); } } } } }<file_sep>using IttezanPos.Helpers; using IttezanPos.Models; using IttezanPos.Resources; using SQLite; using SQLiteNetExtensions.Extensions; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.SalesPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class HoldListPage : ContentPage { private ObservableCollection<HoldProduct> holdList = new ObservableCollection<HoldProduct>(); public ObservableCollection<HoldProduct> HoldList { get { return holdList; } set { holdList = value; OnPropertyChanged(nameof(holdList)); } } public HoldListPage() { InitializeComponent(); FlowDirectionPage(); GetData(); } private void FlowDirectionPage() { FlowDirection = (Helpers.Settings.LastUserGravity == "Arabic") ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultures(CultureTypes.NeutralCultures).ToList(). First(element => element.EnglishName.Contains(Helpers.Settings.LastUserGravity)); AppResources.Culture = Thread.CurrentThread.CurrentUICulture; GravityClass.Grav(); } private void GetData() { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("HoldProduct"); if (!info.Any()) { db.CreateTable<HoldProduct>(); } HoldList = new ObservableCollection<HoldProduct>(db.GetAllWithChildren<HoldProduct>().ToList()); listhold.ItemsSource = HoldList; } private async void Edite_Tapped(object sender, EventArgs e) { if (((sender as Frame).BindingContext is HoldProduct saleproduct)) { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("HoldProduct"); var sale = db.GetAllWithChildren<HoldProduct>().ToList().Where(clien => clien.id == saleproduct.id).FirstOrDefault(); db.Delete(sale); MessagingCenter.Send(new SaleHold() { product = saleproduct }, "SaleHold"); await Navigation.PopAsync(); } } private void Delete_Tapped(object sender, EventArgs e) { if (((sender as Frame).BindingContext is HoldProduct saleproduct)) { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("HoldProduct"); var sale = db.GetAllWithChildren<HoldProduct>().ToList().Where(clien => clien.id == saleproduct.id).FirstOrDefault(); db.Delete(sale); HoldList = new ObservableCollection<HoldProduct>(db.GetAllWithChildren<HoldProduct>().ToList()); listhold.ItemsSource = HoldList; } } } }<file_sep>using IttezanPos.Models; using Refit; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace IttezanPos.ViewModels { public class ProductViewModel { [Headers("Content-Type: application/json")] public interface IProductService { [Multipart] [Post("/api/addproduct")] Task<AddProduct> AddProduct(int id, string name, string user_id, int category_id, string locale, int purchase_price , int sale_price, int stock, string description, [AliasAs("image")] StreamPart stream); [Post("/api/addproduct")] Task<AddProduct> AddProductError(Product product); [Post("/api/updateproduct")] Task<AddProduct> UpdateProduct(Product product); [Post("/api/delproduct")] Task<DelResponse> DeleteClient(int product_id); } } } <file_sep>using IttezanPos.Models; using Rg.Plugins.Popup.Extensions; using Rg.Plugins.Popup.Pages; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.SalesPages.SalesPopups { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Quantitypop : PopupPage { private SaleProduct selectedprp; private Double Quantity; public Quantitypop(SaleProduct selectedprp) { InitializeComponent(); this.selectedprp = selectedprp; } private async void Next_Tapped(object sender, EventArgs e) { if (Resultlbl.Text != "") { Quantity = double.Parse(Resultlbl.Text); MessagingCenter.Send(new ValueQuantity() { Quantity = Quantity, product = selectedprp }, "PopUpData1"); await Navigation.PopPopupAsync(); } } private async void Closelbl_Tapped(object sender, EventArgs e) { await Navigation.PopPopupAsync(); } private void One_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "1"; } private void two_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "2"; } private void three_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "3"; } private void four_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "4"; } private void five_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "5"; } private void six_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "6"; } private void seven_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "7"; } private void eight_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "8"; } private void nine_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "9"; } private void Zero_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "0"; } private void dot_Tapped(object sender, EventArgs e) { Resultlbl.Text = Resultlbl.Text + "."; } private void Clear_Tapped(object sender, EventArgs e) { if (Resultlbl.Text.Length != 0) { Resultlbl.Text = Resultlbl.Text.Remove(Resultlbl.Text.Length - 1, 1); } } } }<file_sep>using IttezanPos.Models; using IttezanPos.Models.OfflineModel; using IttezanPos.Resources; using IttezanPos.Services; using IttezanPos.Views.InventoryPages.InventoryPopups; using Plugin.Connectivity; using Refit; using Rg.Plugins.Popup.Extensions; using SQLite; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using static IttezanPos.ViewModels.ClientViewModel; namespace IttezanPos.Views.ClientPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AddingClientPage : ContentPage { private Client content; private string edite; private int limit; public ObservableCollection<Client> Clients { get; private set; } public AddingClientPage() { InitializeComponent(); } public AddingClientPage(Client content) { InitializeComponent(); this.content = content; ClientNameArentry.Text = content.name; ClientEnnamenentry.Text = content.enname; ClientAddressentry.Text = content.address; Emailentry.Text = content.email; phoneentry.Text = content.phone; Notesentry.Text = content.note; Limitentry.Text = content.limitt.ToString(); Detailsstk.IsVisible = true; Savebtn.IsVisible = false; } private async void Button_Clicked(object sender, EventArgs e) { if (Limitentry.Text == "") { limit = 0; } else { limit = int.Parse(Limitentry.Text); } try { ActiveIn.IsVisible = true; if (CrossConnectivity.Current.IsConnected) { Client client = new Client { name = ClientNameArentry.Text, enname = ClientEnnamenentry.Text, address =ClientAddressentry.Text, email=Emailentry.Text, phone=phoneentry.Text, note=Notesentry.Text, limitt= limit }; var nsAPI = RestService.For<IClientService>("https://ittezanmobilepos.com"); try { var data = await nsAPI.AddClient(client); if (data.success == true) { ActiveIn.IsVisible = false; await Navigation.PushPopupAsync(new ClientAdded()); await Navigation.PopAsync(); } } catch (Exception ex) { ActiveIn.IsVisible = false; var data = await nsAPI.AddClientError(client); await Navigation.PushPopupAsync(new ClientAdded(data.data.email.First())); Emailentry.Focus(); } } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Client"); if (!info.Any()) db.CreateTable<Client>(); db.CreateTable<AddClientOffline>(); Client client = new Client { name = ClientNameArentry.Text, enname = ClientEnnamenentry.Text, address = ClientAddressentry.Text, email = Emailentry.Text, phone = phoneentry.Text, note = Notesentry.Text, limitt = limit, created_at = DateTime.Now.ToString() }; var udatedclient = db.Table<Client>().Where(i => i.email == client.email).ToList(); if (udatedclient.Count== 0) { ActiveIn.IsVisible = false; AddClientOffline clientOffline = new AddClientOffline { name = ClientNameArentry.Text, enname = ClientEnnamenentry.Text, address = ClientAddressentry.Text, email = Emailentry.Text, phone = phoneentry.Text, note = Notesentry.Text, limitt = limit, created_at = DateTime.Now.ToString() }; db.Insert(clientOffline); db.Insert(client); await Navigation.PushPopupAsync(new ClientAdded()); await Navigation.PopAsync(); } else { ActiveIn.IsVisible = false; await Navigation.PushPopupAsync(new ClientAdded("قيمة البريد الالكتروني مُستخدمة من قبل")); Emailentry.Focus(); } } } catch (ValidationApiException validationException) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 } catch (ApiException exception) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } } private async void Update_Clicked(object sender, EventArgs e) { if (Limitentry.Text == "") { limit = 0; } else { limit = int.Parse(Limitentry.Text); } try { ActiveIn.IsVisible = true; if (CrossConnectivity.Current.IsConnected) { Client client = new Client { client_id = content.client_id, name = ClientNameArentry.Text, enname = ClientEnnamenentry.Text, address = ClientAddressentry.Text, email = Emailentry.Text, phone = phoneentry.Text, note = Notesentry.Text, id = content.id, limitt= limit, }; var nsAPI = RestService.For<IClientService>("https://ittezanmobilepos.com"); var data = await nsAPI.UpdateClient(client); if (data.success == true) { ActiveIn.IsVisible = false; await Navigation.PushPopupAsync(new ClientAdded(edite)); await Navigation.PopAsync(); } } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Client"); if (!info.Any()) db.CreateTable<Client>(); db.CreateTable<UpdateClientOffline>(); Client client = new Client { client_id = content.client_id, id = content.client_id, name = ClientNameArentry.Text, enname = ClientEnnamenentry.Text, address = ClientAddressentry.Text, email = Emailentry.Text, phone = phoneentry.Text, note = Notesentry.Text, limitt = limit, updated_at = DateTime.Now.ToString() }; var udatedclient= db.Table<Client>().Where(i => i.email == client.email).First(); UpdateClientOffline clientOffline = new UpdateClientOffline { id = content.client_id, client_id= content.client_id, name = ClientNameArentry.Text, enname = ClientEnnamenentry.Text, address = ClientAddressentry.Text, email = Emailentry.Text, phone = phoneentry.Text, note = Notesentry.Text, limitt = limit, }; db.Insert(clientOffline); db.Update(client); ActiveIn.IsVisible = false; await Navigation.PushPopupAsync(new ClientAdded(edite)); await Navigation.PopAsync(); } } catch (ValidationApiException validationException) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 } catch (ApiException exception) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } private async void Deletebtn_Clicked(object sender, EventArgs e) { try { ActiveIn.IsVisible = true; if (CrossConnectivity.Current.IsConnected) { var nsAPI = RestService.For<IClientService>("https://ittezanmobilepos.com"); var data = await nsAPI.DeleteClient(content.client_id); if (data.success == true) { ActiveIn.IsVisible = false; await Navigation.PushPopupAsync(new ClientAdded(content.id)); await Navigation.PopAsync(); } } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Client"); if (!info.Any()) db.CreateTable<Client>(); db.CreateTable<DeleteClientOffline>(); Client client = new Client { client_id = content.client_id, id = content.id, name = ClientNameArentry.Text, enname = ClientEnnamenentry.Text, address = ClientAddressentry.Text, email = Emailentry.Text, phone = phoneentry.Text, note = Notesentry.Text, limitt = limit }; var udatedclient = db.Table<Client>().Where(i => i.id == client.id).First(); DeleteClientOffline clientOffline = new DeleteClientOffline { id = content.client_id, client_id = content.client_id, name = ClientNameArentry.Text, enname = ClientEnnamenentry.Text, address = ClientAddressentry.Text, email = Emailentry.Text, phone = phoneentry.Text, note = Notesentry.Text, limitt = limit, created_at = DateTime.Now.ToString() }; db.Insert(clientOffline); db.Delete(client); ActiveIn.IsVisible = false; await Navigation.PushPopupAsync(new ClientAdded(content.id)); await Navigation.PopAsync(); } } catch (ValidationApiException validationException) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 } catch (ApiException exception) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } }<file_sep>using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models { public class ValuePercent { public double Value { get; set; } public double Percentage { get; set; } public double alldisc { get; set; } public DateTime expiredate { get; set; } } public class ValuePercentitem { public double Value { get; set; } public double Percentage { get; set; } public SaleProduct product { get; set; } } public class ValueQuantity { public double Quantity { get; set; } public SaleProduct product { get; set; } } public class SaleHold { public HoldProduct product { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models.OfflineModel { public class OfflineExpense { public bool success { get; set; } public List<Datum> data { get; set; } public string message { get; set; } } public class Datum { public int user_id { get; set; } public int amount { get; set; } public string statement { get; set; } public string date { get; set; } public string updated_at { get; set; } public string created_at { get; set; } public int id { get; set; } } } <file_sep>using IttezanPos.DependencyServices; using IttezanPos.Helpers; using IttezanPos.Models; using IttezanPos.Resources; using SQLite; using SQLiteNetExtensions.Extensions; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Grid; using Syncfusion.Pdf.Interactive; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.SalesPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SalePreviousReciepts : ContentPage { private ObservableCollection<OrderItem> ordersList = new ObservableCollection<OrderItem>(); public ObservableCollection<OrderItem> OrdersList { get { return ordersList; } set { ordersList = value; OnPropertyChanged(nameof(ordersList)); } } public SalePreviousReciepts() { InitializeComponent(); FlowDirectionPage(); GetData(); } private void FlowDirectionPage() { FlowDirection = (Helpers.Settings.LastUserGravity == "Arabic") ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultures(CultureTypes.NeutralCultures).ToList(). First(element => element.EnglishName.Contains(Helpers.Settings.LastUserGravity)); Header.FlowDirection = (Helpers.Settings.LastUserGravity == "Arabic") ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; AppResources.Culture = Thread.CurrentThread.CurrentUICulture; GravityClass.Grav(); } private void GetData() { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("OrderItem"); if (!info.Any()) { db.CreateTable<OrderItem>(); } OrdersList = new ObservableCollection<OrderItem>(db.GetAllWithChildren<OrderItem>().ToList()); listpreview.ItemsSource = OrdersList; } private async void listpreview_ItemSelected(object sender, SelectedItemChangedEventArgs e) { var Orderproduct = listpreview.SelectedItem as OrderItem; // await Navigation.PushAsync(new NavigationPage(new RecieptPage(products,saleproducts, paymentname)) ); #region Fields //Create border color PdfColor borderColor = new PdfColor(Syncfusion.Drawing.Color.FromArgb(255, 51, 181, 75)); PdfBrush lightGreenBrush = new PdfSolidBrush(new PdfColor(Syncfusion.Drawing.Color.FromArgb(255, 218, 218, 221))); PdfBrush darkGreenBrush = new PdfSolidBrush(new PdfColor(Syncfusion.Drawing.Color.FromArgb(255, 51, 181, 75))); PdfBrush whiteBrush = new PdfSolidBrush(new PdfColor(Syncfusion.Drawing.Color.FromArgb(255, 255, 255, 255))); PdfPen borderPen = new PdfPen(borderColor, 1f); Stream fontStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("IttezanPos.Assets.arial.ttf"); //Create TrueType font PdfTrueTypeFont headerFont = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Bold); PdfTrueTypeFont arialRegularFont = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Regular); PdfTrueTypeFont arialBoldFont = new PdfTrueTypeFont(fontStream, 11, PdfFontStyle.Bold); const float margin = 30; const float lineSpace = 7; const float headerHeight = 90; #endregion #region header and buyer infomation //Create PDF with PDF/A-3b conformance PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A3B); //Set ZUGFeRD profile document.ZugferdConformanceLevel = ZugferdConformanceLevel.Basic; //Add page to the PDF PdfPage page = document.Pages.Add(); PdfGraphics graphics = page.Graphics; //Get the page width and height float pageWidth = page.GetClientSize().Width; float pageHeight = page.GetClientSize().Height; //Draw page border graphics.DrawRectangle(borderPen, new RectangleF(0, 0, pageWidth, pageHeight)); //Fill the header with light Brush graphics.DrawRectangle(lightGreenBrush, new RectangleF(0, 0, pageWidth, headerHeight)); RectangleF headerAmountBounds = new RectangleF(400, 0, pageWidth - 400, headerHeight); graphics.DrawString("INVOICE", headerFont, whiteBrush, new PointF(margin, headerAmountBounds.Height / 3)); Stream imageStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("IttezanPos.Assets.ic_launcher.png"); //Create a new PdfBitmap instance PdfBitmap image = new PdfBitmap(imageStream); //Draw the image graphics.DrawImage(image, new PointF(margin + 90, headerAmountBounds.Height / 2)); graphics.DrawRectangle(darkGreenBrush, headerAmountBounds); graphics.DrawString("Amount", arialRegularFont, whiteBrush, headerAmountBounds, new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)); graphics.DrawString("$" + Orderproduct.amount_paid.ToString(), arialBoldFont, whiteBrush, new RectangleF(400, lineSpace, pageWidth - 400, headerHeight + 15), new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)); PdfTextElement textElement = new PdfTextElement("Invoice Number: " + Orderproduct.id.ToString(), arialRegularFont); PdfLayoutResult layoutResult = textElement.Draw(page, new PointF(headerAmountBounds.X - margin, 120)); textElement.Text = "Date : " + DateTime.Now.ToString("dddd dd, MMMM yyyy"); textElement.Draw(page, new PointF(layoutResult.Bounds.X, layoutResult.Bounds.Bottom + lineSpace)); var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); if (Orderproduct.client_id != null) { var client = (db.Table<Client>().ToList().Where(clien => clien.id == int.Parse(Orderproduct.client_id)).FirstOrDefault()); textElement.Text = "Bill To:"; layoutResult = textElement.Draw(page, new PointF(margin, 120)); textElement.Text = client.enname; layoutResult = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace)); textElement.Text = client.address; layoutResult = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace)); textElement.Text = client.email; layoutResult = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace)); textElement.Text = client.phone; layoutResult = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace)); } #endregion #region Invoice data PdfGrid grid = new PdfGrid(); DataTable dataTable = new DataTable("EmpDetails"); List<Product> customerDetails = new List<Product>(); //Add columns to the DataTable dataTable.Columns.Add("ID"); dataTable.Columns.Add("Name"); dataTable.Columns.Add("Price"); dataTable.Columns.Add("Qty"); dataTable.Columns.Add("Disc"); dataTable.Columns.Add("Total"); //Add rows to the DataTable. foreach (var item in Orderproduct.products) { Product customer = new Product(); customer.id = Orderproduct.products.IndexOf(item)+1; customer.Enname = item.Enname; customer.sale_price = item.sale_price; customer.quantity = item.quantity; customer.discount = item.discount; customer.total_price = item.total_price; customerDetails.Add(customer); dataTable.Rows.Add(new string[] { customer.id.ToString(), customer.Enname, customer.sale_price.ToString(), customer.quantity.ToString(), customer.discount.ToString(), customer.total_price.ToString()}); } //Assign data source. grid.DataSource = dataTable; grid.Columns[1].Width = 150; grid.Style.Font = arialRegularFont; grid.Style.CellPadding.All = 5; grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable1Light); layoutResult = grid.Draw(page, new PointF(0, layoutResult.Bounds.Bottom + 40)); textElement.Text = "Grand Total: "; textElement.Font = arialBoldFont; layoutResult = textElement.Draw(page, new PointF(headerAmountBounds.X - 40, layoutResult.Bounds.Bottom + lineSpace)); float totalAmount = float.Parse(Orderproduct.total_price); textElement.Text = "$" + totalAmount.ToString(); layoutResult = textElement.Draw(page, new PointF(layoutResult.Bounds.Right + 4, layoutResult.Bounds.Y)); //graphics.DrawString("$" + totalAmount.ToString(), arialBoldFont, whiteBrush, // new RectangleF(400, lineSpace, pageWidth - 400, headerHeight + 15), new // PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)); textElement.Text = "Total Discount: "; textElement.Font = arialBoldFont; layoutResult = textElement.Draw(page, new PointF(headerAmountBounds.X - 40, layoutResult.Bounds.Bottom + lineSpace)); float totalDisc = float.Parse(Orderproduct.discount); textElement.Text = "$" + totalDisc.ToString(); layoutResult = textElement.Draw(page, new PointF(layoutResult.Bounds.Right + 4, layoutResult.Bounds.Y)); //graphics.DrawString("$" + totalDisc.ToString(), arialBoldFont, whiteBrush, // new RectangleF(400, lineSpace, pageWidth - 400, headerHeight + 15), new // PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)); #endregion #region Seller information borderPen.DashStyle = PdfDashStyle.Custom; borderPen.DashPattern = new float[] { 3, 3 }; PdfLine line = new PdfLine(borderPen, new PointF(0, 0), new PointF(pageWidth, 0)); layoutResult = line.Draw(page, new PointF(0, pageHeight - 100)); textElement.Text = "IttezanPos"; textElement.Font = arialRegularFont; layoutResult = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + (lineSpace * 3))); textElement.Text = "Buradah, AlQassim, <NAME>"; layoutResult = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace)); textElement.Text = "Any Questions? ittezan.com"; layoutResult = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace)); #endregion //#region Create ZUGFeRD XML ////Create //ZUGFeRD Invoice //ZugferdInvoice invoice = new ZugferdInvoice("2058557939", DateTime.Now, CurrencyCodes.USD); ////Set ZUGFeRD profile to basic //invoice.Profile = ZugferdProfile.Basic; ////Add buyer details //invoice.Buyer = new UserDetails //{ // ID = "Abraham_12", // Name = "<NAME>", // ContactName = "Swearegin", // City = "United States, California", // Postcode = "9920", // Country = CountryCodes.US, // Street = "9920 BridgePointe Parkway" //}; ////Add seller details //invoice.Seller = new UserDetails //{ // ID = "Adventure_123", // Name = "AdventureWorks", // ContactName = "<NAME>", // City = "Austin,TX", // Postcode = "78721", // Country = CountryCodes.US, // Street = "800 Interchange Blvd" //}; //IEnumerable<Product> products = saleproducts; //foreach (Product product in products) // invoice.AddProduct(product); //invoice.TotalAmount = totalAmount; //MemoryStream zugferdXML = new MemoryStream(); //invoice.Save(zugferdXML); //#endregion #region Embed ZUGFeRD XML to PDF //Attach ZUGFeRD XML to PDF //PdfAttachment attachment = new PdfAttachment("ZUGFeRD-invoice.xml", zugferdXML); //attachment.Relationship = PdfAttachmentRelationship.Alternative; //attachment.ModificationDate = DateTime.Now; //attachment.Description = "ZUGFeRD-invoice"; //attachment.MimeType = "application/xml"; //document.Attachments.Add(attachment); #endregion //Creates an attachment MemoryStream stream = new MemoryStream(); // Stream invoiceStream = typeof(MainPage).GetTypeInfo().Assembly.GetManifestResourceStream("Sample.Assets.Data.ZUGFeRD-invoice.xml"); PdfAttachment attachment = new PdfAttachment("ZUGFeRD-invoice.xml", stream); attachment.Relationship = PdfAttachmentRelationship.Alternative; attachment.ModificationDate = DateTime.Now; attachment.Description = "ZUGFeRD-invoice"; attachment.MimeType = "application/xml"; document.Attachments.Add(attachment); //Save the document into memory stream document.Save(stream); //Close the document document.Close(true); await Xamarin.Forms.DependencyService.Get<ISave>().SaveAndView("تقرير العملاء.pdf", "application/pdf", stream); } } }<file_sep>using IttezanPos.Resources; using Rg.Plugins.Popup.Pages; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.InventoryPages.InventoryPopups { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ProductAddedPage : PopupPage { private int id; private string edite; public ProductAddedPage() { InitializeComponent(); } public ProductAddedPage(int id) { InitializeComponent(); Frame.BorderColor = Color.Red; Supplierlbl.Text = AppResources.DeletedProduct; this.id = id; } public ProductAddedPage(string edite) { InitializeComponent(); Frame.BorderColor = Color.FromHex("#33b54b"); Supplierlbl.Text = AppResources.UpdatedProduct; this.edite = edite; } } }<file_sep>using IttezanPos.Helpers; using IttezanPos.Models; using IttezanPos.Models.OfflineModel; using IttezanPos.Resources; using Newtonsoft.Json; using Plugin.Connectivity; using Refit; using SQLite; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.Xaml; using static IttezanPos.Helpers.CurrencyInfo; using static IttezanPos.ViewModels.InventoryViewModel; namespace IttezanPos.Views.ExpensesPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ExpensePage : ContentPage { public List<addexpense> Expenses { get; private set; } public Box box { get; private set; } public ExpensePage() { InitializeComponent(); GetExpenses(); } private async void GetExpenses() { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("addexpense"); if (!info.Any()) db.CreateTable<addexpense>(); Expenses = (db.Table<addexpense>().ToList()); if (Expenses.Count!=0) { if (CrossConnectivity.Current.IsConnected) { using (var client = new HttpClient()) { // var products = orderitems.ToArray(); var content = new MultipartFormDataContent(); var jsoncategoryArray = JsonConvert.SerializeObject(Expenses); var values = new Dictionary<string, string> { {"expenses",jsoncategoryArray } }; var req = new HttpRequestMessage(HttpMethod.Post, "https://ittezanmobilepos.com/api/off-add-expense") { Content = new FormUrlEncodedContent(values) }; var response = await client.SendAsync(req); if (response.IsSuccessStatusCode) { var serverResponse = response.Content.ReadAsStringAsync().Result.ToString(); ActiveIn.IsRunning = false; var json = JsonConvert.DeserializeObject<OfflineExpense>(serverResponse); Expenses.Clear(); db.DropTable<addexpense>(); // await Navigation.PushAsync(new SuccessfulReciep(json.message, saleproducts, paymentname)); } else { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } } } private void CustomEntry_TextChanged(object sender, TextChangedEventArgs e) { if (e.NewTextValue != "" ) { ToWord toWord2 = new ToWord(Convert.ToDecimal(e.NewTextValue), new CurrencyInfo(Currencies.SaudiArabia)); switch (Helpers.Settings.LastUserGravity) { case "Arabic": NumbertoTextlbl.Text = toWord2.ConvertToArabic(); break; case "English": NumbertoTextlbl.Text = toWord2.ConvertToEnglish(); break; } } else { NumbertoTextlbl.Text = AppResources.ZeroText; } } private async void Button_Clicked(object sender, EventArgs e) { try { ActiveIn.IsRunning = true; // var jsoncategoryArray = JsonConvert.SerializeObject(Expenses); if (CrossConnectivity.Current.IsConnected) { addexpense expense = new addexpense { date = DatePicker.Date.ToShortDateString(), statement = Statmententry.Text, user_id = 3, amount = double.Parse(amountentry.Text) }; var nsAPI = RestService.For<IUpdateService>("https://ittezanmobilepos.com"); try { var data = await nsAPI.addexpense(expense); if (data.success == true) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ExpnseAdded, AppResources.Ok); await Navigation.PopAsync(); } } catch (Exception ex) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // var data = await nsAPI.AddClientError(client); // await Navigation.PushPopupAsync(new ClientAdded(data)); // Emailentry.Focus(); } } else { addexpense expense = new addexpense { date = DatePicker.Date.ToShortDateString(), statement = Statmententry.Text, user_id = 3, amount = double.Parse(amountentry.Text) }; var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("addexpense"); if (!info.Any()) db.CreateTable<addexpense>(); db.Insert(expense); await DisplayAlert(AppResources.Alert, AppResources.ExpnseAdded, AppResources.Ok); var info2 = db.GetTableInfo("Box"); if (!info.Any()) db.CreateTable<Box>(); ActiveIn.IsRunning = false; var boxs = (db.Table<Box>().ToList()); if (boxs.Count!=0) { box = db.Get<Box>(0); var disc_expenses = Preferences.Get("disc_expenses", 0); if (disc_expenses == 1) { box.balance = (Convert.ToDouble(box.balance) - expense.amount).ToString("0.00"); } db.Update(box); } } } catch (ValidationApiException validationException) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 } catch (ApiException exception) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } } } }<file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using IttezanPos.Helpers; using IttezanPos.Resources; using Plugin.Connectivity; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.Master { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MasterPage : MasterDetailPage { public MasterPage() { InitializeComponent(); if (Device.Idiom == TargetIdiom.Tablet) MasterBehavior = MasterBehavior.Popover; FlowDirectionPage(); masterPage.listView.ItemSelected += OnItemSelected; masterPage.newlist.ItemSelected += OnItemSelected; masterPage.listhelp.ItemSelected += OnItemSelected; } private void FlowDirectionPage() { FlowDirection = (Settings.LastUserGravity == "Arabic") ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultures(CultureTypes.NeutralCultures).ToList(). First(element => element.EnglishName.Contains(Settings.LastUserGravity)); AppResources.Culture = Thread.CurrentThread.CurrentUICulture; GravityClass.Grav(); } void OnItemSelected(object sender, SelectedItemChangedEventArgs e) { var item = e.SelectedItem as MasterPageItem; if (item != null) { Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType)); masterPage.listView.SelectedItem = null; masterPage.newlist.SelectedItem = null; masterPage.listhelp.SelectedItem = null; IsPresented = false; } } } }<file_sep>using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms; namespace IttezanPos.CustomControls { public class CustomEditor : Editor { } } <file_sep>using Rg.Plugins.Popup.Extensions; using Rg.Plugins.Popup.Pages; using Rg.Plugins.Popup.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.InventoryPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AddCategoryPopUpPage : PopupPage { public AddCategoryPopUpPage() { InitializeComponent(); } private void RedColor_Tapped(object sender, EventArgs e) { RedColorlbl.Text = "✔"; Bluelbl.Text = ""; Voiletlbl.Text = ""; IndigoColor.Text = ""; GreenColor.Text = ""; Yellowlbl.Text = ""; Orangelbl.Text = ""; Cyanlbl.Text = ""; Brownlbl.Text = ""; DarkBlue.Text = ""; } private void BlueColor_Tapped(object sender, EventArgs e) { Bluelbl.Text = "✔"; RedColorlbl.Text = ""; Voiletlbl.Text = ""; IndigoColor.Text = ""; GreenColor.Text = ""; Yellowlbl.Text = ""; Orangelbl.Text = ""; Cyanlbl.Text = ""; Brownlbl.Text = ""; DarkBlue.Text = ""; } private void VoiletColor_Tapped(object sender, EventArgs e) { Voiletlbl.Text = "✔"; RedColorlbl.Text = ""; Bluelbl.Text = ""; IndigoColor.Text = ""; GreenColor.Text = ""; Yellowlbl.Text = ""; Orangelbl.Text = ""; Cyanlbl.Text = ""; Brownlbl.Text = ""; DarkBlue.Text = ""; } private void IndigoColor_Tapped(object sender, EventArgs e) { IndigoColor.Text = "✔"; RedColorlbl.Text = ""; Bluelbl.Text = ""; Voiletlbl.Text = ""; GreenColor.Text = ""; Yellowlbl.Text = ""; Orangelbl.Text = ""; Cyanlbl.Text = ""; Brownlbl.Text = ""; DarkBlue.Text = ""; } private void GreenColor_Tapped(object sender, EventArgs e) { GreenColor.Text = "✔"; RedColorlbl.Text = ""; Bluelbl.Text = ""; Voiletlbl.Text = ""; IndigoColor.Text = ""; Yellowlbl.Text = ""; Orangelbl.Text = ""; Cyanlbl.Text = ""; Brownlbl.Text = ""; DarkBlue.Text = ""; } private void YellowColor_Tapped(object sender, EventArgs e) { Yellowlbl.Text = "✔"; RedColorlbl.Text = ""; Bluelbl.Text = ""; Voiletlbl.Text = ""; IndigoColor.Text = ""; GreenColor.Text = ""; Orangelbl.Text = ""; Cyanlbl.Text = ""; Brownlbl.Text = ""; DarkBlue.Text = ""; } private void OrangeColor_Tapped(object sender, EventArgs e) { Orangelbl.Text = "✔"; RedColorlbl.Text = ""; Bluelbl.Text = ""; Voiletlbl.Text = ""; IndigoColor.Text = ""; GreenColor.Text = ""; Yellowlbl.Text = ""; Cyanlbl.Text = ""; Brownlbl.Text = ""; DarkBlue.Text = ""; } private void CyanColor_Tapped(object sender, EventArgs e) { Cyanlbl.Text = "✔"; RedColorlbl.Text = ""; Bluelbl.Text = ""; Voiletlbl.Text = ""; IndigoColor.Text = ""; GreenColor.Text = ""; Yellowlbl.Text = ""; Orangelbl.Text = ""; Brownlbl.Text = ""; DarkBlue.Text = ""; } private void BrownColor_Tapped(object sender, EventArgs e) { Brownlbl.Text= "✔"; RedColorlbl.Text = ""; Bluelbl.Text = ""; Voiletlbl.Text = ""; IndigoColor.Text = ""; GreenColor.Text = ""; Yellowlbl.Text = ""; Orangelbl.Text = ""; Cyanlbl.Text = ""; DarkBlue.Text = ""; } private void DarkBlueColor_Tapped(object sender, EventArgs e) { DarkBlue.Text = "✔"; RedColorlbl.Text = ""; Bluelbl.Text = ""; Voiletlbl.Text = ""; IndigoColor.Text = ""; GreenColor.Text = ""; Yellowlbl.Text = ""; Orangelbl.Text = ""; Cyanlbl.Text = ""; Brownlbl.Text = ""; } private async void ClosePage_Tapped(object sender, EventArgs e) { await Navigation.PopPopupAsync(); } } }<file_sep>using IttezanPos.Models; using IttezanPos.Models.OfflineModel; using IttezanPos.Resources; using IttezanPos.Services; using IttezanPos.Views.InventoryPages.InventoryPopups; using Newtonsoft.Json; using Plugin.Connectivity; using Plugin.Media.Abstractions; using Plugin.Permissions; using Plugin.Permissions.Abstractions; using Refit; using Rg.Plugins.Popup.Extensions; using Rg.Plugins.Popup.Services; using SQLite; using SQLiteNetExtensions.Extensions; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.Xaml; using ZXing.Net.Mobile.Forms; using static IttezanPos.ViewModels.ProductViewModel; using PermissionStatus = Plugin.Permissions.Abstractions.PermissionStatus; namespace IttezanPos.Views.InventoryPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AddingProductPage : ContentPage { private ObservableCollection<Category> categories = new ObservableCollection<Category>(); private int category_Id; private MediaFile image ; private Product product; private int product_Id; private string text; private string barcode; public ObservableCollection<AddClientOffline> AddedClients { get; private set; } public ObservableCollection<UpdateOfflineProduct> UpdatedClients { get; private set; } public ObservableCollection<DeleteClientOffline> DeletedClients { get; private set; } public ObservableCollection<Category> Categories { get { return categories; } set { categories = value; OnPropertyChanged(nameof(categories)); } } public AddingProductPage() { InitializeComponent(); MessagingCenter.Subscribe<PopUpPassParameter>(this, "PopUpData", (value) => { Stream receivedData = value.Myvalue; image = value.mediaFile; Color color = value.productcolor; productimg.BackgroundColor = color; productimg.Source = ImageSource.FromStream(() => { return receivedData; }); }); } public AddingProductPage(Product product) { InitializeComponent(); Savebtn.IsVisible = false; Detailsstk.IsVisible = true; MessagingCenter.Subscribe<PopUpPassParameter>(this, "PopUpData", (value) => { Stream receivedData = value.Myvalue; image = value.mediaFile; Color color = value.productcolor; productimg.BackgroundColor = color; productimg.Source = ImageSource.FromStream(() => { return receivedData; }); }); this.product = product; EntryName.Text = product.name; NotesEntry.Text = product.description; category_Id = product.category_id; PurchaseEntry.Text = product.purchase_price.ToString(); SellEntry.SetBinding(Entry.TextProperty, new Binding(product.sale_price.ToString(), stringFormat: "{0.00}")); // SellEntry.Text = product.sale_price.ToString(); StockQuantity.Text = product.stock.ToString(); // CategoryListar.Title = product.catname; // CategoryListen.Title = product.catname; //if (product.expiration_date.Value.DateTime != null) //{ // Datepicker.Date = product.expiration_date.Value.DateTime; //} //else //{ // Datepicker.Date = DateTime.Now; //} // Datepicker.Date = product.expiration_date.Value.DateTime != null ? product.expiration_date.Value.DateTime : DateTime.Now; productimg.Source = "https://ittezanmobilepos.com/dashboard_files/imgss/"+ product.image; product_Id = product.id; EnglishEnnamentry.Text = product.Enname; } protected override bool OnBackButtonPressed() { CategoryListen.Unfocus(); CategoryListar.Unfocus(); return base.OnBackButtonPressed(); } protected override void OnAppearing() { GetData(); base.OnAppearing(); } //async Task GetOfflineDelete() //{ // var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); // var db = new SQLiteConnection(dbpath); // var info = db.GetTableInfo("DeleteClientOffline"); // if (!info.Any()) // db.CreateTable<DeleteClientOffline>(); // DeletedClients = new ObservableCollection<DeleteClientOffline>(db.Table<DeleteClientOffline>().ToList()); // if (DeletedClients.Count != 0) // { // if (CrossConnectivity.Current.IsConnected) // { // using (var client = new HttpClient()) // { // // var products = orderitems.ToArray(); // var content = new MultipartFormDataContent(); // foreach (var item in DeletedClients) // { // client_ids.Add(item.client_id); // } // var jsoncategoryArray = JsonConvert.SerializeObject(client_ids); // var values = new Dictionary<string, string> // { // {"client_ids",jsoncategoryArray } // }; // var req = new HttpRequestMessage(HttpMethod.Post, "https://ittezanmobilepos.com/api/off-delclient") // { Content = new FormUrlEncodedContent(values) }; // var response = await client.SendAsync(req); // if (response.IsSuccessStatusCode) // { // var serverResponse = response.Content.ReadAsStringAsync().Result.ToString(); // ActiveIn.IsVisible = false; // // var json = JsonConvert.DeserializeObject<OfflineClientAdded>(serverResponse); // AddedClients.Clear(); // db.DropTable<DeleteClientOffline>(); // // await Navigation.PushAsync(new SuccessfulReciep(json.message, saleproducts, paymentname)); // } // else // { // ActiveIn.IsVisible = false; // await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // } // } // } // } //} async Task GetOffline() { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("AddClientOffline"); if (!info.Any()) db.CreateTable<AddClientOffline>(); AddedClients = new ObservableCollection<AddClientOffline>(db.Table<AddClientOffline>().ToList()); if (AddedClients.Count != 0) { if (CrossConnectivity.Current.IsConnected) { using (var client = new HttpClient()) { // var products = orderitems.ToArray(); var content = new MultipartFormDataContent(); var jsoncategoryArray = JsonConvert.SerializeObject(AddedClients); var values = new Dictionary<string, string> { {"clients",jsoncategoryArray } }; var req = new HttpRequestMessage(HttpMethod.Post, "https://ittezanmobilepos.com/api/off-addclient") { Content = new FormUrlEncodedContent(values) }; var response = await client.SendAsync(req); if (response.IsSuccessStatusCode) { var serverResponse = response.Content.ReadAsStringAsync().Result.ToString(); ActiveIn.IsVisible = false; // var json = JsonConvert.DeserializeObject<OfflineClientAdded>(serverResponse); AddedClients.Clear(); db.DropTable<AddClientOffline>(); // await Navigation.PushAsync(new SuccessfulReciep(json.message, saleproducts, paymentname)); } else { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } } } async Task GetData() { try { ActiveIn.IsRunning = true; var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); Categories = new ObservableCollection<Category>(db.GetAllWithChildren<Category>().ToList()); CategoryListar.ItemsSource = Categories; CategoryListen.ItemsSource = Categories; ActiveIn.IsRunning = false; } catch (ValidationApiException validationException) { // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } catch (ApiException exception) { await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } private void CategoryList_SelectedIndexChanged(object sender, EventArgs e) { var category = CategoryListar.SelectedItem as Category; category_Id = category.category.id; } private void CategoryListen_SelectedIndexChanged(object sender, EventArgs e) { var category = CategoryListen.SelectedItem as Category; category_Id = category.category.id; } private void ByQuantity_Tapped(object sender, EventArgs e) { ByQuantitystk.BackgroundColor = Color.FromHex("#33b54b"); ByQuantitylbl.TextColor = Color.White; ByQuantityimg.Source = "waitwhit.png"; ByUnitstk.BackgroundColor = Color.Default; ByUnitlbl.TextColor = Color.FromHex("#33b54b"); ByUniteimg.Source = "unitgreen.png"; } private void ByUnit_Tapped(object sender, EventArgs e) { ByQuantitystk.BackgroundColor = Color.Default; ByQuantitylbl.TextColor = Color.FromHex("#33b54b"); ByQuantityimg.Source = "waitgreen.png"; ByUnitstk.BackgroundColor = Color.FromHex("#33b54b"); ByUnitlbl.TextColor = Color.White; ByUniteimg.Source = "unitWhit.png"; } private async void ChooseImage_Tapped(object sender, EventArgs e) { await Navigation.PushPopupAsync(new AddProductImagePopUpPage()); } private void Trackinstore_Toggled(object sender, ToggledEventArgs e) { Preferences.Set("stock", "my_value"); } private async void AddCategorybtn_Clicked(object sender, EventArgs e) { await Navigation.PushPopupAsync(new AddCategoryPopUpPage()); } private void SellEntry_TextChanged(object sender, TextChangedEventArgs e) { if (PurchaseEntry.Text != null) { if (e.NewTextValue != "" && int.Parse(e.NewTextValue) < int.Parse(PurchaseEntry.Text)) { salsesErrorlbl.IsVisible = true; } else { salsesErrorlbl.IsVisible = false; } } else { salsesErrorlbl.IsVisible = true; } } private void Scan_Tapped(object sender, EventArgs e) { Scanner(); } public async void Scanner() { var ScannerPage = new ZXingScannerPage(); _ = Navigation.PushAsync(ScannerPage); try { var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera); if (status != PermissionStatus.Granted) { if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Camera)) { await DisplayAlert(AppResources.Alert, AppResources.NeedCamera, AppResources.Ok); } var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Camera); status = results[Permission.Location]; } if (status == PermissionStatus.Granted) { ScannerPage.OnScanResult += (result) => { Device.BeginInvokeOnMainThread(() => { barcode = result.Text; _ = Navigation.PopAsync(); }); }; } else { await DisplayAlert(AppResources.Alert, AppResources.PermissionsDenied, AppResources.Ok); //On iOS you may want to send your user to the settings screen. CrossPermissions.Current.OpenAppSettings(); } } catch (Exception ex) { await DisplayAlert(AppResources.Alert, AppResources.PermissionsDenied, AppResources.Ok); //On iOS you may want to send your user to the settings screen. CrossPermissions.Current.OpenAppSettings(); } } private bool AllNeeded() { if (image==null ) { ActiveIn.IsRunning = false; DisplayAlert(AppResources.Error, AppResources.AddImage, AppResources.Ok); OpenImagePopup(); return false; } else if (category_Id== 0) { ActiveIn.IsRunning = false; DisplayAlert(AppResources.Error, AppResources.ChooseCategory, AppResources.Ok); CategoryListen.Focus(); CategoryListar.Focus(); return false; } return true; } private async void OpenImagePopup() { await Navigation.PushPopupAsync(new AddProductImagePopUpPage()); } private async void Savebtn_Clicked(object sender, EventArgs e) { ActiveIn.IsRunning = true; if (AllNeeded() == true) { Product product = new Product { name = EntryName.Text, Enname=EnglishEnnamentry.Text, category_id = category_Id, description = NotesEntry.Text, sale_price = int.Parse(SellEntry.Text), purchase_price = int.Parse(PurchaseEntry.Text), barcode = barcode, locale = "ar", stock = int.Parse(PurchaseEntry.Text), user_id="2" }; if (CrossConnectivity.Current.IsConnected) { StringContent name = new StringContent(product.name); StringContent Enname = new StringContent(product.Enname); StringContent category_id = new StringContent(product.category_id.ToString()); StringContent description = new StringContent(product.description); StringContent sale_price = new StringContent(product.sale_price.ToString()); StringContent purchase_price = new StringContent(product.purchase_price.ToString()); StringContent locale = new StringContent(product.locale); StringContent barcode = new StringContent(product.barcode); StringContent user_id = new StringContent(product.user_id); StringContent stock = new StringContent(product.stock.ToString()); var content = new MultipartFormDataContent(); content.Add(name, "name"); content.Add(Enname, "Enname"); content.Add(category_id, "category_id"); content.Add(description, "description"); content.Add(sale_price, "sale_price"); content.Add(purchase_price, "purchase_price"); content.Add(locale, "locale"); content.Add(user_id, "user_id"); content.Add(stock, "stock"); content.Add(barcode, "barcode"); content.Add(new StreamContent(image.GetStream()), "image", $"{image.Path}"); HttpClient httpClient = new HttpClient(); try { var httpResponseMessage = await httpClient.PostAsync("https://ittezanmobilepos.com/api/addproduct", content); var serverResponse = httpResponseMessage.Content.ReadAsStringAsync().Result.ToString(); if (serverResponse == "false") { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } else { try { try { ActiveIn.IsRunning = false; var JsonResponse = JsonConvert.DeserializeObject<AddProduct>(serverResponse); if (JsonResponse.success == true) { await PopupNavigation.Instance.PushAsync(new ProductAddedPage()); await Navigation.PushAsync(new InventoryMainPage()); } } catch (Exception ex) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); //var JsonResponse = JsonConvert.DeserializeObject<RegisterResponse>(serverResponse); //if (JsonResponse.success == false) //{ // ActiveIn.IsRunning = false; // await PopupNavigation.Instance.PushAsync(new RegisterPopup(JsonResponse.data)); //} } } catch (Exception ex) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); return; } } } catch (Exception ex) { await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("OfflineProduct"); if (!info.Any()) db.CreateTable<OfflineProduct>(); OfflineProduct supplierOffline = new OfflineProduct { name = product.name, enname = product.Enname, barcode = product.barcode, category_id = product.category_id, description = product.description, expiredate = product.expiration_date.ToString(), image = product.image, notes = product.description, purchase_price = product.purchase_price, sale_price = product.sale_price, stock = product.stock, trackinstore = 1, type = 1, user_id = 2, }; db.Insert(supplierOffline); ActiveIn.IsRunning = false; await PopupNavigation.Instance.PushAsync(new ProductAddedPage()); await Navigation.PopModalAsync(); } } } private async void Updatebtn_Clicked(object sender, EventArgs e) { Product product = new Product { id = product_Id, name = EntryName.Text, Enname = EnglishEnnamentry.Text, category_id = category_Id, description = NotesEntry.Text, sale_price = int.Parse(SellEntry.Text), purchase_price = int.Parse(PurchaseEntry.Text), barcode = barcode, locale = "ar", stock = int.Parse(StockQuantity.Text), user_id = "2" }; if (CrossConnectivity.Current.IsConnected) { StringContent product_id = new StringContent(product.id.ToString()); StringContent name = new StringContent(product.name); StringContent Enname = new StringContent(product.Enname); StringContent category_id = new StringContent(product.category_id.ToString()); StringContent description = new StringContent(product.description); StringContent sale_price = new StringContent(product.sale_price.ToString()); StringContent purchase_price = new StringContent(product.purchase_price.ToString()); StringContent locale = new StringContent(product.locale); StringContent user_id = new StringContent(product.user_id); StringContent stock = new StringContent(product.stock.ToString()); var content = new MultipartFormDataContent(); content.Add(product_id, "product_id"); content.Add(name, "name"); content.Add(Enname, "Enname"); content.Add(category_id, "category_id"); content.Add(description, "description"); content.Add(sale_price, "sale_price"); content.Add(purchase_price, "purchase_price"); content.Add(locale, "locale"); content.Add(user_id, "user_id"); content.Add(stock, "stock"); if (image != null) { content.Add(new StreamContent(image.GetStream()), "image", $"{image.Path}"); } HttpClient httpClient = new HttpClient(); try { var httpResponseMessage = await httpClient.PostAsync("https://ittezanmobilepos.com/api/updateproduct", content); var serverResponse = httpResponseMessage.Content.ReadAsStringAsync().Result.ToString(); if (serverResponse == "false") { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } else { try { try { ActiveIn.IsRunning = false; var JsonResponse = JsonConvert.DeserializeObject<RootObject>(serverResponse); if (JsonResponse.success == true) { await PopupNavigation.Instance.PushAsync(new ProductAddedPage(text)); await Navigation.PushAsync(new InventoryMainPage()); } } catch (Exception ex) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); //var JsonResponse = JsonConvert.DeserializeObject<RegisterResponse>(serverResponse); //if (JsonResponse.success == false) //{ // ActiveIn.IsRunning = false; // await PopupNavigation.Instance.PushAsync(new RegisterPopup(JsonResponse.data)); //} } } catch (Exception ex) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); return; } } } catch (Exception ex) { await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("UpdateOfflineProduct"); if (!info.Any()) db.CreateTable<UpdateOfflineProduct>(); var udatedclient = db.Table<Product>().Where(i => i.id == product.id).First(); UpdateOfflineProduct supplierOffline = new UpdateOfflineProduct { product_id = product.product_id, name = product.name, enname = product.Enname, barcode = product.barcode, category_id = product.category_id, description = product.description, expiredate = product.expiration_date.ToString(), image = product.image, notes = product.description, purchase_price = product.purchase_price, sale_price = product.sale_price, stock =product.stock, trackinstore = 1, type=1, user_id =2, }; db.Insert(supplierOffline); db.Update(product); ActiveIn.IsVisible = false; await PopupNavigation.Instance.PushAsync(new ProductAddedPage(text)); await Navigation.PopAsync(); } } private async void Deletebtn_Clicked(object sender, EventArgs e) { try { ActiveIn.IsRunning = true; if (CrossConnectivity.Current.IsConnected) { var nsAPI = RestService.For<IProductService>("https://ittezanmobilepos.com"); var data = await nsAPI.DeleteClient(product.id); if (data.success == true) { ActiveIn.IsRunning = false; await Navigation.PushPopupAsync(new ProductAddedPage(product.id)); await Navigation.PopAsync(); } } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Product"); if (!info.Any()) db.CreateTable<Product>(); db.CreateTable<DeleteOfflineProduct>(); //Product client = new Product //{ // id = product.id, // name = product.name, // Enname = SupplierEnnamenentry.Text, // address = SupplierAddressentry.Text, // email = SupplierEmailentry.Text, // phone = SupplierPhoneentry.Text, // note = SupplierNotesentry.Text, //}; var udatedclient = db.Table<Product>().Where(i => i.id == product.id).First(); DeleteOfflineProduct supplierOffline = new DeleteOfflineProduct { id = udatedclient.id, product_id = udatedclient.product_id, name = udatedclient.name, Enname = udatedclient.Enname, created_at = DateTime.Now, updated_at = DateTime.Now, }; db.Insert(supplierOffline); db.Delete(udatedclient); ActiveIn.IsVisible = false; await Navigation.PushPopupAsync(new ProductAddedPage(product.id)); await Navigation.PopAsync(); } } catch (ValidationApiException validationException) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 } catch (ApiException exception) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using XamEffects; namespace IttezanPos.Views.InventoryPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class InventoryMainPage : ContentPage { public InventoryMainPage() { InitializeComponent(); Commandss(); } private void Commandss() { Commands.SetTap(AddProductGrid, new Command(() => { AddingProductPageNav(); })); Commands.SetTap(ViewProductsGrid, new Command(() => { ProductsPageNav(); })); Commands.SetTap(AddingNewClassificationGrid, new Command(() => { AddingClassificationPageNav(); })); Commands.SetTap(EdittingSalariesGrid, new Command(() => { EdditingSalariesNav(); })); } private async void AddingProductPageNav() { await Navigation.PushAsync(new AddingProductPage()); } private async void ProductsPageNav() { await Navigation.PushAsync(new ViewProductsPage()); } private async void AddingClassificationPageNav() { await Navigation.PushAsync(new AddingClassificationPage()); } private async void EdditingSalariesNav() { await Navigation.PushAsync(new EditingProductSalaryPage()); } } }<file_sep>using IttezanPos.Models; using Refit; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace IttezanPos.ViewModels { public class BoxViewModel { [Headers("Content-Type: application/json")] public interface IBoxService { [Post("/api/intrprocessTreasury")] Task<RootObject> Addinterproccess(Box box); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.SettingsPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class PrintersPages : ContentPage { public PrintersPages() { InitializeComponent(); } } }<file_sep>using IttezanPos.Models; using Refit; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace IttezanPos.ViewModels { public class SalesViewModel { [Headers("Content-Type: application/json")] public interface ISalesService { [Post("/api/makeOrder")] Task<SaleObject> AddSale(OrderItem item); // [Post("/api/addclient")] // Task<AddClientError> AddClientError(Client client); [Post("/api/updateclient")] Task<RootObject> UpdateClient(Client client); [Post("/api/delclient")] Task<DelResponse> DeleteClient(int client_id); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using XamEffects; using Xamarin.Forms; using Xamarin.Forms.Xaml; using IttezanPos.Views.SupplierPages; using Plugin.Connectivity; using Refit; using IttezanPos.Services; using IttezanPos.Models; using System.Collections.ObjectModel; using System.IO; using SQLite; using Syncfusion.Pdf; using System.Reflection; using System.Data; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Grid; using Syncfusion.Pdf.Tables; using IttezanPos.Helpers; using Syncfusion.Drawing; using IttezanPos.DependencyServices; using IttezanPos.Resources; using System.Net.Http; using Newtonsoft.Json; using IttezanPos.Models.OfflineModel; namespace IttezanPos.Views.SupplierPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MainSuppliersPage : ContentPage { private ObservableCollection<Supplier> suppliers = new ObservableCollection<Supplier>(); public ObservableCollection<Supplier> Suppliers { get { return suppliers; } set { suppliers = value; OnPropertyChanged(nameof(suppliers)); } } public ObservableCollection<AddSupplierOffline> AddedSuppliers { get; private set; } private List<int> supplier_ids = new List<int>(); public ObservableCollection<UpdateSupplierOffline> UpdatedSuppliers { get; private set; } public ObservableCollection<DeleteSupplierOffline> DeletedClients { get; private set; } public MainSuppliersPage() { InitializeComponent(); _ = GetOffline(); _ = GetOfflineUpdate(); _ = GetOfflineDelete(); _ = GetData(); Commandss(); } async Task GetOfflineUpdate() { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("UpdateSupplierOffline"); if (!info.Any()) db.CreateTable<UpdateSupplierOffline>(); UpdatedSuppliers = new ObservableCollection<UpdateSupplierOffline>(db.Table<UpdateSupplierOffline>().ToList()); if (UpdatedSuppliers.Count != 0) { if (CrossConnectivity.Current.IsConnected) { using (var client = new HttpClient()) { // var products = orderitems.ToArray(); var content = new MultipartFormDataContent(); var jsoncategoryArray = JsonConvert.SerializeObject(UpdatedSuppliers); var values = new Dictionary<string, string> { {"suppliers",jsoncategoryArray } }; var req = new HttpRequestMessage(HttpMethod.Post, "https://ittezanmobilepos.com/api/off-updatesupplier") { Content = new FormUrlEncodedContent(values) }; var response = await client.SendAsync(req); if (response.IsSuccessStatusCode) { var serverResponse = response.Content.ReadAsStringAsync().Result.ToString(); ActiveIn.IsVisible = false; var json = JsonConvert.DeserializeObject<RootObject>(serverResponse); Suppliers = new ObservableCollection<Supplier>(json.message.suppliers); UpdatedSuppliers.Clear(); db.DropTable<UpdateSupplierOffline>(); // await Navigation.PushAsync(new SuccessfulReciep(json.message, saleproducts, paymentname)); } else { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } } } async Task GetOfflineDelete() { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("DeleteClientOffline"); if (!info.Any()) db.CreateTable<DeleteClientOffline>(); DeletedClients = new ObservableCollection<DeleteSupplierOffline>(db.Table<DeleteSupplierOffline>().ToList()); if (DeletedClients.Count != 0) { if (CrossConnectivity.Current.IsConnected) { using (var client = new HttpClient()) { // var products = orderitems.ToArray(); var content = new MultipartFormDataContent(); foreach (var item in DeletedClients) { supplier_ids.Add(item.id); } var jsoncategoryArray = JsonConvert.SerializeObject(supplier_ids); var values = new Dictionary<string, string> { {"supplier_ids",jsoncategoryArray } }; var req = new HttpRequestMessage(HttpMethod.Post, "https://ittezanmobilepos.com/api/off-delsupplier") { Content = new FormUrlEncodedContent(values) }; var response = await client.SendAsync(req); if (response.IsSuccessStatusCode) { var serverResponse = response.Content.ReadAsStringAsync().Result.ToString(); ActiveIn.IsVisible = false; // var json = JsonConvert.DeserializeObject<OfflineClientAdded>(serverResponse); DeletedClients.Clear(); db.DropTable<DeleteSupplierOffline>(); // await Navigation.PushAsync(new SuccessfulReciep(json.message, saleproducts, paymentname)); } else { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } } } async Task GetOffline() { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("AddSupplierOffline"); if (!info.Any()) db.CreateTable<AddSupplierOffline>(); AddedSuppliers = new ObservableCollection<AddSupplierOffline>(db.Table<AddSupplierOffline>().ToList()); if (AddedSuppliers.Count != 0) { if (CrossConnectivity.Current.IsConnected) { using (var client = new HttpClient()) { // var products = orderitems.ToArray(); var content = new MultipartFormDataContent(); var jsoncategoryArray = JsonConvert.SerializeObject(AddedSuppliers); var values = new Dictionary<string, string> { {"suppliers",jsoncategoryArray } }; var req = new HttpRequestMessage(HttpMethod.Post, "https://ittezanmobilepos.com/api/off-addsupplier") { Content = new FormUrlEncodedContent(values) }; var response = await client.SendAsync(req); if (response.IsSuccessStatusCode) { var serverResponse = response.Content.ReadAsStringAsync().Result.ToString(); ActiveIn.IsVisible = false; // var json = JsonConvert.DeserializeObject<OfflineBox>(serverResponse); AddedSuppliers.Clear(); db.DropTable<AddSupplierOffline>(); // await Navigation.PushAsync(new SuccessfulReciep(json.message, saleproducts, paymentname)); } else { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } } } async Task GetData() { try { ActiveIn.IsVisible = true; if (CrossConnectivity.Current.IsConnected) { var nsAPI = RestService.For<IApiService>("https://ittezanmobilepos.com/"); RootObject data = await nsAPI.GetSettings(); Suppliers = new ObservableCollection<Supplier>(data.message.suppliers); foreach (var item in Suppliers) { item.supplier_id = item.id; } var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Supplier"); if (!info.Any()) { db.CreateTable<Supplier>(); } else { db.DropTable<Supplier>(); db.CreateTable<Supplier>(); } // Clients = new ObservableCollection<Client>(db.Table<Client>().ToList()); // db.CreateTable<Client>(); db.InsertAll(Suppliers); // listviewwww.ItemsSource = Suppliers; ActiveIn.IsVisible = false; } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Supplier"); if (!info.Any()) { db.CreateTable<Supplier>(); } Suppliers = new ObservableCollection<Supplier>(db.Table<Supplier>().ToList()); ActiveIn.IsVisible = false; // listviewwww.ItemsSource = Suppliers; } } catch (ValidationApiException validationException) { // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } catch (ApiException exception) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } private void Commandss() { Commands.SetTap(AddClientGrid, new Command(() => { AddingClientPageNav(); })); Commands.SetTap(ViewClientGrid, new Command(() => { ClientsPageNav(); })); Commands.SetTap(CustomeropeningbalancesGrid, new Command(() => { OpeningbalancesPageNav(); })); Commands.SetTap(ViewCustomerreceivablesGrid, new Command(() => { ClientRecievableNav(); })); Commands.SetTap(CustomerreceivablesGrid, new Command(() => { ViewReport(); })); } private async void ViewReport() { //Create a new PDF document. PdfDocument doc = new PdfDocument(); //Add a page. PdfPage page = doc.Pages.Add(); Stream fontStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("IttezanPos.Assets.arial.ttf"); PdfTemplate header = PdfHelper.AddHeader(doc, "تقرير ذمم الموردين", "Ittezan Pos" + " " + DateTime.Now.ToString()); PdfCellStyle headerStyle = new PdfCellStyle(); headerStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center); page.Graphics.DrawPdfTemplate(header, new PointF()); //Create a PdfGrid. PdfGrid pdfGrid = new PdfGrid(); //String format // PdfFont pdfFont = new PdfTrueTypeFont(fontStream1, 12); //Create a DataTable. DataTable dataTable = new DataTable("EmpDetails"); List<SuplierTotalAmount> customerDetails = new List<SuplierTotalAmount>(); //Add columns to the DataTable dataTable.Columns.Add("ID"); dataTable.Columns.Add("Name"); dataTable.Columns.Add("Address"); dataTable.Columns.Add("Total"); //Add rows to the DataTable. foreach (var item in suppliers) { SuplierTotalAmount customer = new SuplierTotalAmount(); customer.name = item.name; customer.remaining = item.remaining; customer.creditorit = item.creditorit; customer.total_amount = item.total_amount; customerDetails.Add(customer); dataTable.Rows.Add(new string[] { customer.total_amount.ToString(), customer.remaining.ToString(), customer.creditorit.ToString(), customer.name }); } //Assign data source. pdfGrid.DataSource = dataTable; pdfGrid.Headers.Add(1); PdfGridRow pdfGridRowHeader = pdfGrid.Headers[0]; pdfGridRowHeader.Cells[3].Value = "الإسم"; pdfGridRowHeader.Cells[2].Value = "الباقي من فواتير الآجل"; pdfGridRowHeader.Cells[1].Value = "الباقي من الرصيد الإفتتاحي"; pdfGridRowHeader.Cells[0].Value = "الإجمالي"; PdfGridStyle pdfGridStyle = new PdfGridStyle(); pdfGridStyle.Font = new PdfTrueTypeFont(fontStream, 12); PdfGridLayoutFormat format1 = new PdfGridLayoutFormat(); format1.Break = PdfLayoutBreakType.FitPage; format1.Layout = PdfLayoutType.Paginate; PdfStringFormat format = new PdfStringFormat(); format.TextDirection = PdfTextDirection.RightToLeft; format.Alignment = PdfTextAlignment.Center; format.LineAlignment = PdfVerticalAlignment.Middle; pdfGrid.Columns[0].Format = format; pdfGrid.Columns[1].Format = format; pdfGrid.Columns[2].Format = format; pdfGrid.Columns[3].Format = format; pdfGrid.Style = pdfGridStyle; //Draw grid to the page of PDF document. pdfGrid.Draw(page, new Syncfusion.Drawing.Point(0, (int)header.Height + 10), format1); MemoryStream stream = new MemoryStream(); //Save the document. doc.Save(stream); //close the document doc.Close(true); await Xamarin.Forms.DependencyService.Get<ISave>().SaveAndView("تقرير ذمم الموردين .pdf", "application/pdf", stream); } private async void AddingClientPageNav() { await Navigation.PushAsync(new AddingSupplierPage()); } private async void ClientsPageNav() { if ( Suppliers.Count() != 0) { await Navigation.PushAsync(new SuppliersPage(Suppliers)); } else { await GetData(); await Navigation.PushAsync(new SuppliersPage(Suppliers)); } } private async void OpeningbalancesPageNav() { if (Suppliers.Count() != 0) { await Navigation.PushAsync(new SuppliersOpeningbalances(Suppliers)); } else { await GetData(); await Navigation.PushAsync(new SuppliersOpeningbalances(Suppliers)); } } private async void ClientRecievableNav() { if ( Suppliers.Count() != 0) { await Navigation.PushAsync(new SupplierRecivable(Suppliers)); } else { await GetData(); await Navigation.PushAsync(new SupplierRecivable(Suppliers)); } } } }<file_sep>using IttezanPos.Models; using Refit; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace IttezanPos.ViewModels { public class SupplierViewModel { [Headers("Content-Type: application/json")] public interface ISupplierService { [Post("/api/addsupplier")] Task<RootObject> AddSupplier(Supplier supplier); [Post("/api/addsupplier")] Task<AddSupplierError> AddSupplierError(Supplier supplier); [Post("/api/updatesupplier")] Task<RootObject> UpdateSupplier(Supplier supplier); [Post("/api/delsupplier")] Task<DelResponse> DeleteSupplier(int supplier_id); [Post("/api/offlineOrder")] Task<Orderoffline> AddOrder([Body] string orders); } } } public class Orderoffline { public bool success { get; set; } public string data { get; set; } public List<int> message { get; set; } } <file_sep>using IttezanPos.Views.SalesPages; using Newtonsoft.Json; using SQLite; using SQLiteNetExtensions.Attributes; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; namespace IttezanPos.Models { public class OrderItem { [PrimaryKey,AutoIncrement] public int id { get; set; } public string total_price { get; set; } public string amount_paid { get; set; } public string discount { get; set; } public string total_price_after_discount { get; set; } public string client_id { get; set; } public int user_id { get; set; } public DateTimeOffset? created_at { get; set; } public DateTimeOffset? updated_at { get; set; } public string payment_type { get; set; } [ForeignKey(typeof(SaleProduct))] public int productId { get; set; } [OneToMany(CascadeOperations = CascadeOperation.All)] public List<SaleProduct> products { get; set; } } public class Purchaseitem { //[PrimaryKey] //public int purchasing_order { get; set; } // public string payment_type { get; set; } public int user_id { get; set; } public string supplier_id { get; set; } public string discount { get; set; } public string total_price { get; set; } // public int total_price_after_discount { get; set; } [OneToMany(CascadeOperations = CascadeOperation.All)] public List<Products> products { get; set; } } public class Products { //[PrimaryKey] //public int purchasing_order { get; set; } // public string payment_type { get; set; } public int id { get; set; } public double quantity { get; set; } public double total_price { get; set; } public double sale_price { get; set; } public double purchase_price { get; set; } public string expiration_date { get; set; } // public int total_price_after_discount { get; set; } } public class sub { public int id { get; set; } public int quantity { get; set; } } public class SaleObject { public bool success { get; set; } public string data { get; set; } public List<OrderItem> message { get; set; } } public class PurchaseObject { public bool success { get; set; } public string data { get; set; } public List<Purchaseitem> message { get; set; } } } <file_sep>using Newtonsoft.Json; using SQLite; using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models.OfflineModel { public class AddSupplierOffline : Supplier { } public class UpdateSupplierOffline { public int supplier_id { get; set; } [PrimaryKey, AutoIncrement] public int id { get; set; } public string name { get; set; } public string enname { get; set; } public string address { get; set; } public string phone { get; set; } public string email { get; set; } public string note { get; set; } } public class DeleteSupplierOffline : Supplier { } } <file_sep>using Plugin.Permissions; using Rg.Plugins.Popup.Extensions; using Rg.Plugins.Popup.Pages; using System; using Plugin.Permissions.Abstractions; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using Plugin.Media.Abstractions; using Plugin.Media; using IttezanPos.Models; using IttezanPos.Resources; namespace IttezanPos.Views.InventoryPages.InventoryPopups { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AddProductImagePopUpPage : PopupPage { private MediaFile ProfilePic; private Color procolor; public AddProductImagePopUpPage() { InitializeComponent(); } private async void ClosePage_Tapped(object sender, EventArgs e) { await Navigation.PopPopupAsync(); } private void RedColor_Tapped(object sender, EventArgs e) { procolor = Color.Red; RedColorlbl.Text = "✔"; Bluelbl.Text = ""; Voiletlbl.Text = ""; IndigoColor.Text = ""; GreenColor.Text = ""; Yellowlbl.Text = ""; Orangelbl.Text = ""; Cyanlbl.Text = ""; Brownlbl.Text = ""; DarkBlue.Text = ""; } private void BlueColor_Tapped(object sender, EventArgs e) { procolor = Color.Blue; Bluelbl.Text = "✔"; RedColorlbl.Text = ""; Voiletlbl.Text = ""; IndigoColor.Text = ""; GreenColor.Text = ""; Yellowlbl.Text = ""; Orangelbl.Text = ""; Cyanlbl.Text = ""; Brownlbl.Text = ""; DarkBlue.Text = ""; } private void VoiletColor_Tapped(object sender, EventArgs e) { procolor = Color.Violet; Voiletlbl.Text = "✔"; RedColorlbl.Text = ""; Bluelbl.Text = ""; IndigoColor.Text = ""; GreenColor.Text = ""; Yellowlbl.Text = ""; Orangelbl.Text = ""; Cyanlbl.Text = ""; Brownlbl.Text = ""; DarkBlue.Text = ""; } private void IndigoColor_Tapped(object sender, EventArgs e) { procolor = Color.Indigo; IndigoColor.Text = "✔"; RedColorlbl.Text = ""; Bluelbl.Text = ""; Voiletlbl.Text = ""; GreenColor.Text = ""; Yellowlbl.Text = ""; Orangelbl.Text = ""; Cyanlbl.Text = ""; Brownlbl.Text = ""; DarkBlue.Text = ""; } private void GreenColor_Tapped(object sender, EventArgs e) { procolor = Color.Green; GreenColor.Text = "✔"; RedColorlbl.Text = ""; Bluelbl.Text = ""; Voiletlbl.Text = ""; IndigoColor.Text = ""; Yellowlbl.Text = ""; Orangelbl.Text = ""; Cyanlbl.Text = ""; Brownlbl.Text = ""; DarkBlue.Text = ""; } private void YellowColor_Tapped(object sender, EventArgs e) { procolor = Color.Yellow; Yellowlbl.Text = "✔"; RedColorlbl.Text = ""; Bluelbl.Text = ""; Voiletlbl.Text = ""; IndigoColor.Text = ""; GreenColor.Text = ""; Orangelbl.Text = ""; Cyanlbl.Text = ""; Brownlbl.Text = ""; DarkBlue.Text = ""; } private void OrangeColor_Tapped(object sender, EventArgs e) { procolor = Color.Orange; Orangelbl.Text = "✔"; RedColorlbl.Text = ""; Bluelbl.Text = ""; Voiletlbl.Text = ""; IndigoColor.Text = ""; GreenColor.Text = ""; Yellowlbl.Text = ""; Cyanlbl.Text = ""; Brownlbl.Text = ""; DarkBlue.Text = ""; } private void CyanColor_Tapped(object sender, EventArgs e) { procolor = Color.Cyan; Cyanlbl.Text = "✔"; RedColorlbl.Text = ""; Bluelbl.Text = ""; Voiletlbl.Text = ""; IndigoColor.Text = ""; GreenColor.Text = ""; Yellowlbl.Text = ""; Orangelbl.Text = ""; Brownlbl.Text = ""; DarkBlue.Text = ""; } private void BrownColor_Tapped(object sender, EventArgs e) { procolor = Color.Brown; Brownlbl.Text = "✔"; RedColorlbl.Text = ""; Bluelbl.Text = ""; Voiletlbl.Text = ""; IndigoColor.Text = ""; GreenColor.Text = ""; Yellowlbl.Text = ""; Orangelbl.Text = ""; Cyanlbl.Text = ""; DarkBlue.Text = ""; } private void DarkBlueColor_Tapped(object sender, EventArgs e) { procolor = Color.DarkBlue; DarkBlue.Text = "✔"; RedColorlbl.Text = ""; Bluelbl.Text = ""; Voiletlbl.Text = ""; IndigoColor.Text = ""; GreenColor.Text = ""; Yellowlbl.Text = ""; Orangelbl.Text = ""; Cyanlbl.Text = ""; Brownlbl.Text = ""; } private async void Choosepic_Tapped(object sender, EventArgs e) { var answer = await DisplayAlert(AppResources.Choose, AppResources.SelectpicMode, AppResources.Gallery, AppResources.Camera); if (answer == true) { try { var storageStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage); if (storageStatus != PermissionStatus.Granted) { if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location)) { await DisplayAlert(AppResources.Alert, AppResources.NeedCamera, AppResources.Ok); } var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Storage }); storageStatus = results[Permission.Storage]; } if (storageStatus == PermissionStatus.Granted) { ProfilePic = await CrossMedia.Current.PickPhotoAsync(); if (ProfilePic == null) return; ProfImgSource.Source = ImageSource.FromStream(() => { return ProfilePic.GetStream(); }); } else { await DisplayAlert(AppResources.Alert, AppResources.PermissionsDenied, AppResources.Ok); //On iOS you may want to send your user to the settings screen. CrossPermissions.Current.OpenAppSettings(); } } catch (Exception ex) { await DisplayAlert(AppResources.Alert, AppResources.PermissionsDenied, AppResources.Ok); return; } } else { try { var cameraStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera); if (cameraStatus != PermissionStatus.Granted) { if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location)) { await DisplayAlert(AppResources.Alert, AppResources.NeedCamera, AppResources.Ok); } var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Camera }); cameraStatus = results[Permission.Camera]; } if (cameraStatus == PermissionStatus.Granted) { ProfilePic = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions { Directory = "Test", SaveToAlbum = true, CompressionQuality = 75, CustomPhotoSize = 50, PhotoSize = PhotoSize.MaxWidthHeight, MaxWidthHeight = 2000, DefaultCamera = CameraDevice.Front }); if (ProfilePic == null) return; ProfImgSource.Source = ImageSource.FromStream(() => { return ProfilePic.GetStream(); }); } else { await DisplayAlert(AppResources.Alert, AppResources.PermissionsDenied, AppResources.Ok); //On iOS you may want to send your user to the settings screen. CrossPermissions.Current.OpenAppSettings(); } } catch (Exception ex) { await DisplayAlert(AppResources.Alert, AppResources.PermissionsDenied, AppResources.Ok); return; } } } private async void Savebtn_Clicked(object sender, EventArgs e) { if (ProfilePic != null) { MessagingCenter.Send(new PopUpPassParameter() { Myvalue = ProfilePic.GetStream() }, "PopUpData"); MessagingCenter.Send(new PopUpPassParameter() { mediaFile = ProfilePic }, "PopUpData"); } else { MessagingCenter.Send(new PopUpPassParameter() { productcolor = procolor }, "PopUpData"); } await Navigation.PopPopupAsync(); } } }<file_sep>using IttezanPos.Helpers; using IttezanPos.Models; using IttezanPos.Models.OfflineModel; using IttezanPos.Resources; using Newtonsoft.Json; using Plugin.Connectivity; using Rg.Plugins.Popup.Extensions; using Rg.Plugins.Popup.Pages; using Rg.Plugins.Popup.Services; using SQLite; using SQLiteNetExtensions.Extensions; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.SalesPages.SalesPopups { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ExtraPopupPage : PopupPage { private List<OrderItem> orderitems; List<string> rooo = new List<string>(); private List<SaleProductoff> sales = new List<SaleProductoff>(); private List<OfflineSalesOrder> OrdersOffline = new List<OfflineSalesOrder>(); public ExtraPopupPage() { InitializeComponent(); FlowDirectionPage(); } private void FlowDirectionPage() { FlowDirection = (Helpers.Settings.LastUserGravity == "Arabic") ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultures(CultureTypes.NeutralCultures).ToList(). First(element => element.EnglishName.Contains(Helpers.Settings.LastUserGravity)); AppResources.Culture = Thread.CurrentThread.CurrentUICulture; GravityClass.Grav(); } private async void ViewHold_Tapped(object sender, EventArgs e) { await Navigation.PushAsync((new HoldListPage())); await PopupNavigation.Instance.PopAllAsync(); } private async void ViewPastReciepts_Tapped(object sender, EventArgs e) { await Navigation.PushAsync((new SalePreviousReciepts())); await PopupNavigation.Instance.PopAllAsync(); } private async void sync_Tapped(object sender, EventArgs e) { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("OrderItem"); if (!info.Any()) { db.CreateTable<OrderItem>(); db.CreateTable<SaleProduct>(); } orderitems = (db.GetAllWithChildren<OrderItem>().ToList()); if (orderitems.Count!=0) { if (CrossConnectivity.Current.IsConnected) { using (var client = new HttpClient()) { // var products = orderitems.ToArray(); var content = new MultipartFormDataContent(); foreach (var item in orderitems) { foreach (var item1 in item.products) { SaleProductoff sale = new SaleProductoff(); sale.id = item1.product_id; // sale.expiration_date = item1.expiration_date; sale.expiration_date = DateTime.Now; sale.purchase_price = item1.purchase_price; sale.quantity = item1.quantity; sale.sale_price = item1.sale_price; sale.total_price = item1.total_price; sales.Add(sale); } OfflineSalesOrder product = new OfflineSalesOrder { discount = double.Parse(item.discount), products = sales, total_price = double.Parse(item.total_price), amount_paid = double.Parse(item.amount_paid), client_id = item.client_id, user_id = "3", payment_type = item.payment_type }; OrdersOffline.Add(product); } //foreach (var item in OrdersOffline) // { // var json = JsonConvert.SerializeObject(item); // rooo.Add(json); // } //var f = rooo.ToArray(); var jsoncategoryArray = JsonConvert.SerializeObject(OrdersOffline); var values = new Dictionary<string, string> { {"orders",jsoncategoryArray } }; var req = new HttpRequestMessage(HttpMethod.Post, "https://ittezanmobilepos.com/api/offlineOrder") { Content = new FormUrlEncodedContent(values) }; var response = await client.SendAsync(req); // content.Add(new StringContent(jsoncategoryArray, Encoding.UTF8, "text/json"), "orders"); // var content = new StringContent(JsonConvert.SerializeObject(values), Encoding.UTF8, "text/json"); // var response = await client.PostAsync("https://ittezanmobilepos.com/api/offlineOrder", content); if (response.IsSuccessStatusCode) { var serverResponse = response.Content.ReadAsStringAsync().Result.ToString(); // ActiveIn.IsRunning = false; var json = JsonConvert.DeserializeObject<SaleObject>(serverResponse); // await Navigation.PushAsync(new SuccessfulReciep(json.message, saleproducts, paymentname)); } else { // ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } } } }}<file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using IttezanPos.DependencyServices; using IttezanPos.Helpers; using IttezanPos.Models; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Grid; using Syncfusion.Pdf.Tables; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.SupplierPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SupplierRecivable : ContentPage { private ObservableCollection<Supplier> suppliers; public SupplierRecivable() { InitializeComponent(); } public SupplierRecivable(ObservableCollection<Supplier> suppliers) { InitializeComponent(); listheaderlistv.FlowDirection = (Helpers.Settings.LastUserGravity == "Arabic") ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; this.suppliers = suppliers; listviewwww.ItemsSource = suppliers; } private void SearchBar_SearchButtonPressed(object sender, EventArgs e) { var keyword = Searchbar.Text; listviewwww.ItemsSource = suppliers.Where(product => product.name.ToLower().Contains(keyword.ToLower())); } void OnTextChanged(object sender, EventArgs e) { SearchBar searchBar = (SearchBar)sender; var keyword = searchBar.Text; listviewwww.ItemsSource = suppliers.Where(product => product.name.ToLower().Contains(keyword.ToLower())); } private async void Button_Clicked(object sender, EventArgs e) { //Create a new PDF document. PdfDocument doc = new PdfDocument(); //Add a page. PdfPage page = doc.Pages.Add(); Stream fontStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("IttezanPos.Assets.arial.ttf"); PdfTemplate header = PdfHelper.AddHeader(doc, "المبالغ المتبقية للموردين", "<NAME>" + " " + DateTime.Now.ToString()); PdfCellStyle headerStyle = new PdfCellStyle(); headerStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center); page.Graphics.DrawPdfTemplate(header, new PointF()); //Create a PdfGrid. PdfGrid pdfGrid = new PdfGrid(); //String format // PdfFont pdfFont = new PdfTrueTypeFont(fontStream1, 12); //Create a DataTable. DataTable dataTable = new DataTable("EmpDetails"); List<SuplierTotalAmount> customerDetails = new List<SuplierTotalAmount>(); //Add columns to the DataTable dataTable.Columns.Add("ID"); dataTable.Columns.Add("Name"); dataTable.Columns.Add("Address"); dataTable.Columns.Add("Total"); //Add rows to the DataTable. foreach (var item in suppliers) { SuplierTotalAmount customer = new SuplierTotalAmount(); customer.name = item.name; customer.remaining = item.remaining; customer.total_amount = item.total_amount; customer.paid_amount = item.paid_amount; customerDetails.Add(customer); dataTable.Rows.Add(new string[] { customer.remaining.ToString(), customer.paid_amount.ToString(), customer.total_amount.ToString(), customer.name }); } //Assign data source. pdfGrid.DataSource = dataTable; pdfGrid.Headers.Add(1); PdfGridRow pdfGridRowHeader = pdfGrid.Headers[0]; pdfGridRowHeader.Cells[3].Value = "الإسم"; pdfGridRowHeader.Cells[2].Value = "إجمالي المبالغ"; pdfGridRowHeader.Cells[1].Value = "المبلغ المدفوع"; pdfGridRowHeader.Cells[0].Value = "الباقي"; PdfGridStyle pdfGridStyle = new PdfGridStyle(); pdfGridStyle.Font = new PdfTrueTypeFont(fontStream, 12); PdfGridLayoutFormat format1 = new PdfGridLayoutFormat(); format1.Break = PdfLayoutBreakType.FitPage; format1.Layout = PdfLayoutType.Paginate; PdfStringFormat format = new PdfStringFormat(); format.TextDirection = PdfTextDirection.RightToLeft; format.Alignment = PdfTextAlignment.Center; format.LineAlignment = PdfVerticalAlignment.Middle; pdfGrid.Columns[0].Format = format; pdfGrid.Columns[1].Format = format; pdfGrid.Columns[2].Format = format; pdfGrid.Columns[3].Format = format; pdfGrid.Style = pdfGridStyle; //Draw grid to the page of PDF document. pdfGrid.Draw(page, new Syncfusion.Drawing.Point(0, (int)header.Height + 10), format1); MemoryStream stream = new MemoryStream(); //Save the document. doc.Save(stream); //close the document doc.Close(true); await Xamarin.Forms.DependencyService.Get<ISave>().SaveAndView("المبالغ المتبقية للموردين .pdf", "application/pdf", stream); } } }<file_sep>using IttezanPos.DependencyServices; using IttezanPos.Helpers; using IttezanPos.Models; using IttezanPos.Models.OfflineModel; using IttezanPos.Resources; using IttezanPos.Services; using Newtonsoft.Json; using Plugin.Connectivity; using Refit; using SQLite; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Grid; using Syncfusion.Pdf.Tables; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.IO; using System.Linq; using System.Net.Http; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using XamEffects; namespace IttezanPos.Views.ClientPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MainClientsPage : ContentPage { private ObservableCollection<Client> clients = new ObservableCollection<Client>(); private List<int> client_ids= new List<int>(); public ObservableCollection<Client> Clients { get { return clients; } set { clients = value; OnPropertyChanged(nameof(clients)); } } public ObservableCollection<AddClientOffline> AddedClients { get; private set; } public ObservableCollection<UpdateClientOffline> UpdatedClients { get; private set; } public ObservableCollection<DeleteClientOffline> DeletedClients { get; private set; } public MainClientsPage() { InitializeComponent(); _ = GetOffline(); _ = GetOfflineUpdate(); _ = GetOfflineDelete(); _ = GetData(); Commandss(); } async Task GetOfflineUpdate() { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("UpdateClientOffline"); if (!info.Any()) db.CreateTable<UpdateClientOffline>(); UpdatedClients = new ObservableCollection<UpdateClientOffline>(db.Table<UpdateClientOffline>().ToList()); if (UpdatedClients.Count != 0) { if (CrossConnectivity.Current.IsConnected) { using (var client = new HttpClient()) { // var products = orderitems.ToArray(); var content = new MultipartFormDataContent(); var jsoncategoryArray = JsonConvert.SerializeObject(UpdatedClients); var values = new Dictionary<string, string> { {"clients",jsoncategoryArray } }; var req = new HttpRequestMessage(HttpMethod.Post, "https://ittezanmobilepos.com/api/off-updateclient") { Content = new FormUrlEncodedContent(values) }; var response = await client.SendAsync(req); if (response.IsSuccessStatusCode) { var serverResponse = response.Content.ReadAsStringAsync().Result.ToString(); ActiveIn.IsVisible = false; var json = JsonConvert.DeserializeObject<RootObject>(serverResponse); UpdatedClients.Clear(); Clients = new ObservableCollection<Client>( json.message.clients); db.DropTable<UpdateClientOffline>(); // await Navigation.PushAsync(new SuccessfulReciep(json.message, saleproducts, paymentname)); } else { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } } } async Task GetOfflineDelete() { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("DeleteClientOffline"); if (!info.Any()) db.CreateTable<DeleteClientOffline>(); DeletedClients = new ObservableCollection<DeleteClientOffline>(db.Table<DeleteClientOffline>().ToList()); if (DeletedClients.Count != 0) { if (CrossConnectivity.Current.IsConnected) { using (var client = new HttpClient()) { // var products = orderitems.ToArray(); var content = new MultipartFormDataContent(); foreach (var item in DeletedClients) { client_ids.Add(item.client_id); } var jsoncategoryArray = JsonConvert.SerializeObject(client_ids); var values = new Dictionary<string, string> { {"client_ids",jsoncategoryArray } }; var req = new HttpRequestMessage(HttpMethod.Post, "https://ittezanmobilepos.com/api/off-delclient") { Content = new FormUrlEncodedContent(values) }; var response = await client.SendAsync(req); if (response.IsSuccessStatusCode) { var serverResponse = response.Content.ReadAsStringAsync().Result.ToString(); ActiveIn.IsVisible = false; // var json = JsonConvert.DeserializeObject<OfflineClientAdded>(serverResponse); DeletedClients.Clear(); db.DropTable<DeleteClientOffline>(); // await Navigation.PushAsync(new SuccessfulReciep(json.message, saleproducts, paymentname)); } else { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } } } async Task GetOffline() { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("AddClientOffline"); if (!info.Any()) db.CreateTable<AddClientOffline>(); AddedClients = new ObservableCollection<AddClientOffline>(db.Table<AddClientOffline>().ToList()); if (AddedClients.Count != 0) { if (CrossConnectivity.Current.IsConnected) { using (var client = new HttpClient()) { // var products = orderitems.ToArray(); var content = new MultipartFormDataContent(); var jsoncategoryArray = JsonConvert.SerializeObject(AddedClients); var values = new Dictionary<string, string> { {"clients",jsoncategoryArray } }; var req = new HttpRequestMessage(HttpMethod.Post, "https://ittezanmobilepos.com/api/off-addclient") { Content = new FormUrlEncodedContent(values) }; var response = await client.SendAsync(req); if (response.IsSuccessStatusCode) { var serverResponse = response.Content.ReadAsStringAsync().Result.ToString(); ActiveIn.IsVisible = false; // var json = JsonConvert.DeserializeObject<OfflineClientAdded>(serverResponse); AddedClients.Clear(); db.DropTable<AddClientOffline>(); // await Navigation.PushAsync(new SuccessfulReciep(json.message, saleproducts, paymentname)); } else { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } } } async Task GetData() { try { ActiveIn.IsVisible = true; if (CrossConnectivity.Current.IsConnected) { var nsAPI = RestService.For<IApiService>("https://ittezanmobilepos.com/"); RootObject data = await nsAPI.GetSettings(); Clients = new ObservableCollection<Client>(data.message.clients); foreach (var item in Clients) { item.client_id = item.id; } var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Client"); if (!info.Any()) { db.CreateTable<Client>(); } else { db.DropTable<Client>(); db.CreateTable<Client>(); } // Clients = new ObservableCollection<Client>(db.Table<Client>().ToList()); // db.CreateTable<Client>(); db.InsertAll(Clients); // listviewwww.ItemsSource = Clients; ActiveIn.IsVisible = false; } else { // ActiveIn.IsRunning = false; var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Client"); if (!info.Any()) db.CreateTable<Client>(); Clients = new ObservableCollection<Client>(db.Table<Client>().ToList()); } ActiveIn.IsVisible = false; // listviewwww.ItemsSource = Clients; // await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } catch (ValidationApiException validationException) { // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } catch (ApiException exception) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } private void Commandss() { Commands.SetTap(AddClientGrid, new Command(() => { AddingClientPageNav(); })); Commands.SetTap(ViewClientGrid, new Command(() => { ClientsPageNav(); })); Commands.SetTap(CustomeropeningbalancesGrid, new Command(() => { OpeningbalancesPageNav(); })); Commands.SetTap(ViewCustomerreceivablesGrid, new Command(() => { ClientRecievableNav(); })); Commands.SetTap(CustomerreceivablesGrid, new Command(() => { CustomerreceivablesGridRe(); })); } private async void CustomerreceivablesGridRe() { //Create a new PDF document. PdfDocument doc = new PdfDocument(); //Add a page. PdfPage page = doc.Pages.Add(); Stream fontStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("IttezanPos.Assets.arial.ttf"); PdfTemplate header = PdfHelper.AddHeader(doc, "تقرير ذمم العملاء", "Ittezan Pos" + " " + DateTime.Now.ToString()); PdfCellStyle headerStyle = new PdfCellStyle(); headerStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center); page.Graphics.DrawPdfTemplate(header, new PointF()); //Create a PdfGrid. PdfGrid pdfGrid = new PdfGrid(); //String format // PdfFont pdfFont = new PdfTrueTypeFont(fontStream1, 12); //Create a DataTable. DataTable dataTable = new DataTable("EmpDetails"); List<Client> customerDetails = new List<Client>(); //Add columns to the DataTable dataTable.Columns.Add("ID"); dataTable.Columns.Add("Name"); dataTable.Columns.Add("Address"); dataTable.Columns.Add("Total"); //Add rows to the DataTable. foreach (var item in Clients) { Client customer = new Client(); customer.name = item.name; customer.remaining = item.remaining; customer.creditorit = item.creditorit; customer.total_amount = item.total_amount; customerDetails.Add(customer); dataTable.Rows.Add(new string[] { customer.total_amount.ToString(), customer.remaining.ToString(), customer.creditorit.ToString(), customer.name }); } //Assign data source. pdfGrid.DataSource = dataTable; pdfGrid.Headers.Add(1); PdfGridRow pdfGridRowHeader = pdfGrid.Headers[0]; pdfGridRowHeader.Cells[3].Value = "الإسم"; pdfGridRowHeader.Cells[2].Value = "الباقي من فواتير الآجل"; pdfGridRowHeader.Cells[1].Value = "الباقي من الرصيد الإفتتاحي"; pdfGridRowHeader.Cells[0].Value = "الإجمالي"; PdfGridStyle pdfGridStyle = new PdfGridStyle(); pdfGridStyle.Font = new PdfTrueTypeFont(fontStream, 12); PdfGridLayoutFormat format1 = new PdfGridLayoutFormat(); format1.Break = PdfLayoutBreakType.FitPage; format1.Layout = PdfLayoutType.Paginate; PdfStringFormat format = new PdfStringFormat(); format.TextDirection = PdfTextDirection.RightToLeft; format.Alignment = PdfTextAlignment.Center; format.LineAlignment = PdfVerticalAlignment.Middle; pdfGrid.Columns[0].Format = format; pdfGrid.Columns[1].Format = format; pdfGrid.Columns[2].Format = format; pdfGrid.Columns[3].Format = format; pdfGrid.Style = pdfGridStyle; //Draw grid to the page of PDF document. pdfGrid.Draw(page, new Syncfusion.Drawing.Point(0, (int)header.Height + 10), format1); MemoryStream stream = new MemoryStream(); //Save the document. doc.Save(stream); //close the document doc.Close(true); await Xamarin.Forms.DependencyService.Get<ISave>().SaveAndView("تقرير ذمم الموردين .pdf", "application/pdf", stream); } private async void AddingClientPageNav() { await Navigation.PushAsync(new AddingClientPage()); } private async void ClientsPageNav() { if ( Clients.Count!=0) { await Navigation.PushAsync(new ClientsPage(Clients)); } else { await GetData(); await Navigation.PushAsync(new ClientsPage(Clients)); } } private async void OpeningbalancesPageNav() { if ( Clients.Count != 0) { await Navigation.PushAsync(new OpeningbalancesPage(Clients)); } else { await GetData(); await Navigation.PushAsync(new OpeningbalancesPage(Clients)); } } private async void ClientRecievableNav() { if ( Clients.Count != 0) { await Navigation.PushAsync(new ClientRecievable(Clients)); } else { await GetData(); await Navigation.PushAsync(new ClientRecievable(Clients)); } } } }<file_sep>using IttezanPos.Models; using IttezanPos.Resources; using IttezanPos.Services; using IttezanPos.Views.PurchasingPages.PurchasePoPups; using IttezanPos.Views.SalesPages; using IttezanPos.Views.SalesPages.SalesPopups; using Newtonsoft.Json; using Plugin.Connectivity; using Refit; using Rg.Plugins.Popup.Extensions; using SQLite; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.PurchasingPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class PurchaseCheckout : ContentPage { private ObservableCollection<Payment> payments = new ObservableCollection<Payment>(); private List<Products> purchasero= new List<Products>(); private string text; private string supplier_id= null; private string paymentid="1"; private List<Product> purchaseProducts; public ObservableCollection<Payment> Payments { get { return payments; } set { payments = value; OnPropertyChanged(nameof(payments)); } } public PurchaseCheckout(List<Product> purchaseProducts, string text) { InitializeComponent(); this.purchaseProducts = purchaseProducts; this.text = text; totallbl.Text = text; if (IttezanPos.Helpers.Settings.LastUserGravity == "Arabic") { PaymentListar.IsVisible = true; PaymentListen.IsVisible = false; } else { PaymentListar.IsVisible = false; PaymentListen.IsVisible = true; } MessagingCenter.Subscribe<ValuePercent>(this, "PopUpData", (value) => { if (value.Value != 0) { Disclbl.Text = value.Value.ToString("0.00"); totallbl.Text = (double.Parse(totallbl.Text) - double.Parse(Disclbl.Text)).ToString(); } else { Disclbl.Text = (value.Percentage * double.Parse(totallbl.Text)).ToString(); totallbl.Text = (double.Parse(totallbl.Text) - double.Parse(Disclbl.Text)).ToString(); } }); MessagingCenter.Subscribe<Client>(this, "PopUpData", (value) => { CustName.Text = value.name; supplier_id = value.id.ToString(); }); } protected override void OnAppearing() { GetData(); base.OnAppearing(); } async Task GetData() { try { // ActiveIn.IsRunning = true; if (CrossConnectivity.Current.IsConnected) { var nsAPI = RestService.For<IApiService>("https://ittezanmobilepos.com/"); RootObject data = await nsAPI.GetSettings(); Payments = new ObservableCollection<Payment>(data.message.payments); var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Payment"); if (!info.Any()) { db.CreateTable<Payment>(); } else { db.DropTable<Payment>(); db.CreateTable<Payment>(); } // Clients = new ObservableCollection<Client>(db.Table<Client>().ToList()); // db.CreateTable<Client>(); db.InsertAll(Payments); PaymentListen.ItemsSource = Payments; PaymentListar.ItemsSource = Payments; // ActiveIn.IsRunning = false; } else { // ActiveIn.IsRunning = false; var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Payment"); db.CreateTable<Payment>(); Payments = new ObservableCollection<Payment>(db.Table<Payment>().ToList()); PaymentListen.ItemsSource = Payments; PaymentListar.ItemsSource = Payments; // await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } catch (ValidationApiException validationException) { // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 // ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } catch (ApiException exception) { // ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { // ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } private async void Discount_Tapped(object sender, EventArgs e) { await Navigation.PushPopupAsync(new CalculatorPage()); } private async void Supplier_Tapped(object sender, EventArgs e) { await Navigation.PushAsync(new SupplierPop()); } private void PaymentList_SelectedIndexChanged(object sender, EventArgs e) { var payment = PaymentListen.SelectedItem as Payment; paymentlbl.Text = payment.PaymentTypeEnname; paymentid = payment.Id.ToString(); } private void PaymentListar_SelectedIndexChanged(object sender, EventArgs e) { var payment = PaymentListar.SelectedItem as Payment; paymentlbl.Text = payment.PaymentType; paymentid = payment.Id.ToString(); } private async void Nextbtn_Clicked(object sender, EventArgs e) { try { ActiveIn.IsRunning = true; if (CrossConnectivity.Current.IsConnected) { using (var client = new HttpClient()) { //ObservableCollection<sub> subs = new ObservableCollection<sub>(); //foreach (var item2 in saleproducts) //{ // subs.Add(new sub // { // id = item2.id, // quantity = item2.quantity // }); //} foreach (var item in purchaseProducts) { Products productss = new Products { expiration_date = item.expiration_date.ToString(), id= item.id, purchase_price = item.purchase_price, quantity = item.quantity, sale_price = item.sale_price, total_price = item.total_price //payment_type = paymentid }; purchasero.Add(productss); } Purchaseitem products = new Purchaseitem { discount = Disclbl.Text, products = purchasero, total_price = totallbl.Text, supplier_id = supplier_id!=null? supplier_id:"0", user_id = 3, //payment_type = paymentid }; var content = new MultipartFormDataContent(); //var jsoncategoryArray = JsonConvert.SerializeObject(products); //var values = new Dictionary<string, string> //{ // {"purchasing_Order",jsoncategoryArray } //}; //var req = new HttpRequestMessage(HttpMethod.Post, // "https://ittezanmobilepos.com/api/make_purchasing_Order") //{ Content = new FormUrlEncodedContent(values) }; //var response = await client.SendAsync(req); var js = JsonConvert.SerializeObject(products); content.Add(new StringContent(js, Encoding.UTF8, "text/json"), "purchasing_Order"); var response = await client.PostAsync("https://ittezanmobilepos.com/api/make_purchasing_Order", content); if (response.IsSuccessStatusCode) { var serverResponse = response.Content.ReadAsStringAsync().Result.ToString(); ActiveIn.IsRunning = false; var json = JsonConvert.DeserializeObject<SaleObject>(serverResponse); App.Current.MainPage = new SuccessfulReciep(products); } else { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } } catch (ValidationApiException validationException) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 } catch (ApiException exception) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } } } }<file_sep>using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models { public class StoreItem { } } <file_sep>using IttezanPos.Models; using IttezanPos.Resources; using IttezanPos.Services; using IttezanPos.Views.SupplierPages; using Plugin.Connectivity; using Refit; using SQLite; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.PurchasingPages.PurchasePoPups { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SupplierPop : ContentPage { private ObservableCollection<Supplier> suppliers = new ObservableCollection<Supplier>(); public ObservableCollection<Supplier> Suppliers { get { return suppliers; } set { suppliers = value; OnPropertyChanged(nameof(suppliers)); } } public SupplierPop() { InitializeComponent(); } protected override void OnAppearing() { GetData(); base.OnAppearing(); } async Task GetData() { try { ActiveIn.IsRunning = true; if (CrossConnectivity.Current.IsConnected) { var nsAPI = RestService.For<IApiService>("https://ittezanmobilepos.com/"); RootObject data = await nsAPI.GetSettings(); Suppliers = new ObservableCollection<Supplier>(data.message.suppliers); if (Device.RuntimePlatform == Device.iOS) { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Supplier"); if (!info.Any()) { db.CreateTable<Supplier>(); } else { db.DropTable<Supplier>(); db.CreateTable<Supplier>(); } db.InsertAll(Suppliers); } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Supplier"); if (!info.Any()) { db.CreateTable<Supplier>(); } else { db.DropTable<Supplier>(); db.CreateTable<Supplier>(); } // Clients = new ObservableCollection<Client>(db.Table<Client>().ToList()); // db.CreateTable<Client>(); db.InsertAll(Suppliers); } listviewwww.ItemsSource = Suppliers; ActiveIn.IsRunning = false; } else { ActiveIn.IsRunning = false; if (Device.RuntimePlatform == Device.iOS) { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Supplier"); if (!info.Any()) db.CreateTable<Supplier>(); Suppliers = new ObservableCollection<Supplier>(db.Table<Supplier>().ToList()); } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Supplier"); Suppliers = new ObservableCollection<Supplier>(db.Table<Supplier>().ToList()); } listviewwww.ItemsSource = Suppliers; } } catch (ValidationApiException validationException) { // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } catch (ApiException exception) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } private void SearchBar_SearchButtonPressed(object sender, EventArgs e) { var keyword = SearchBar.Text; listviewwww.ItemsSource = Suppliers.Where(product => product.name.ToLower().Contains(keyword.ToLower())); } void OnTextChanged(object sender, EventArgs e) { SearchBar searchBar = (SearchBar)sender; var keyword = SearchBar.Text; listviewwww.ItemsSource = Suppliers.Where(product => product.name.ToLower().Contains(keyword.ToLower())); } private async void Listviewwww_ItemTapped(object sender, ItemTappedEventArgs e) { var content = e.Item as Supplier; MessagingCenter.Send(new Supplier() { name = content.name }, "PopUpData"); await Navigation.PopAsync(); } private async void AddNewSupplier_Tapped(object sender, EventArgs e) { await Navigation.PushAsync(new AddingSupplierPage()); } } }<file_sep>using Plugin.Media.Abstractions; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Text; namespace IttezanPos.Models { public class PopUpPassParameter { public Stream Myvalue { get; set; } public MediaFile mediaFile { get; set; } public Color productcolor { get; set; } } } <file_sep>using IttezanPos.Helpers; using IttezanPos.Models; using IttezanPos.Models.OfflineModel; using IttezanPos.Resources; using IttezanPos.Services; using Newtonsoft.Json; using Plugin.Connectivity; using Refit; using Rg.Plugins.Popup.Extensions; using SQLite; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.Xaml; using static IttezanPos.Helpers.CurrencyInfo; using static IttezanPos.ViewModels.BoxViewModel; using Settings = IttezanPos.Helpers.Settings; namespace IttezanPos.Views.ReservoirPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ReservoirPage : ContentPage { List<CurrencyInfo> currencies = new List<CurrencyInfo>(); private int type_Operation; private int disc_purchasing_suppliers; private int disc_expenses; private int add_sales_clients; public Box Box { get; private set; } public List<Box> Boxes { get; private set; } public ReservoirPage() { InitializeComponent(); // _ = GetData(); _ = GetOffline(); _ = GetData(); type_Operation = 1; disc_purchasing_suppliers = 0; disc_expenses=0; add_sales_clients = 0; } async Task GetOffline() { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Box"); if (!info.Any()) db.CreateTable<Box>(); Boxes = (db.Table<Box>().ToList()); Boxes[0].amount = "0"; Boxes[0].balance = "0"; if (Boxes.Count != 0) { if (CrossConnectivity.Current.IsConnected) { using (var client = new HttpClient()) { // var products = orderitems.ToArray(); var content = new MultipartFormDataContent(); var jsoncategoryArray = JsonConvert.SerializeObject(Boxes); var values = new Dictionary<string, string> { {"treasuries",jsoncategoryArray } }; var req = new HttpRequestMessage(HttpMethod.Post, "https://ittezanmobilepos.com/api/Offline-treasury") { Content = new FormUrlEncodedContent(values) }; var response = await client.SendAsync(req); if (response.IsSuccessStatusCode) { var serverResponse = response.Content.ReadAsStringAsync().Result.ToString(); ActiveIn.IsVisible = false; var json = JsonConvert.DeserializeObject<OfflineBox>(serverResponse); Boxes.Clear(); db.DropTable<Box>(); // await Navigation.PushAsync(new SuccessfulReciep(json.message, saleproducts, paymentname)); } else { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } } } async Task GetData() { try { ActiveIn.IsVisible = true; if (CrossConnectivity.Current.IsConnected) { var nsAPI = RestService.For<IApiService>("https://ittezanmobilepos.com/"); RootObject data = await nsAPI.GetSettings(); Box = (data.message.box); Balancelbl.Text = Box.balance; Box.date = DateTime.Now.ToShortDateString(); Box.amount = Box.balance; Box.type_operation = 1; var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Box"); if (!info.Any()) { db.CreateTable<Box>(); } else { db.DropTable<Box>(); db.CreateTable<Box>(); } // Clients = new ObservableCollection<Client>(db.Table<Client>().ToList()); // db.CreateTable<Client>(); db.Insert(Box); // listviewwww.ItemsSource = Suppliers; ActiveIn.IsVisible = false; } else { ActiveIn.IsVisible = true; var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Box"); if (!info.Any()) db.CreateTable<Box>(); Box = (db.Table<Box>().Last()); if (Box!=null) { Balancelbl.Text = Box.balance; } else{ Balancelbl.Text = "0.00"; } ActiveIn.IsVisible = false; // Suppliers = new ObservableCollection<Supplier>(db.Table<Supplier>().ToList()); // listviewwww.ItemsSource = Suppliers; } } catch (ValidationApiException validationException) { // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } catch (ApiException exception) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } private void Addrdbtn_Checked(object sender, EventArgs e) { Deductionbtn.IsVisible = false; Addingbtn.IsVisible = true; type_Operation = 1; } private void Deductrdbtn_Checked(object sender, EventArgs e) { Addingbtn.IsVisible = false; Deductionbtn.IsVisible = true; type_Operation = 0; } private void CustomEntry_TextChanged(object sender, TextChangedEventArgs e) { if(e.NewTextValue!= "" ) { ToWord toWord2 = new ToWord(Convert.ToDecimal(e.NewTextValue), new CurrencyInfo(Currencies.SaudiArabia)); switch (Settings.LastUserGravity) { case "Arabic": NumbertoTextlbl.Text = toWord2.ConvertToArabic(); break; case "English": NumbertoTextlbl.Text = toWord2.ConvertToEnglish(); break; } } else { NumbertoTextlbl.Text = AppResources.ZeroText ; } } private void Salescustswitch_Toggled(object sender, ToggledEventArgs e) { string stateName = e.Value ? "ON" : "OFF"; if (stateName == "ON") { add_sales_clients = 1; Preferences.Set("add_sales_clients", 1); } else { add_sales_clients = 0; Preferences.Set("add_sales_clients", 0); } } private void Purchaseandsuppliersswitch_Toggled(object sender, ToggledEventArgs e) { string stateName = e.Value ? "ON" : "OFF"; if (stateName == "ON") { disc_purchasing_suppliers = 1; Preferences.Set("disc_purchasing_suppliers", 1); } else { disc_purchasing_suppliers = 0; Preferences.Set("disc_purchasing_suppliers", 0); } } private void Expensesswitch_Toggled(object sender, ToggledEventArgs e) { string stateName = e.Value ? "ON" : "OFF"; if (stateName == "ON") { disc_expenses = 1; Preferences.Set("disc_expenses", 1); } else { disc_expenses = 0; Preferences.Set("disc_expenses", 0); } } private async void Addingbtn_Clicked(object sender, EventArgs e) { try { ActiveIn.IsVisible = true; if (CrossConnectivity.Current.IsConnected) { Box box = new Box { add_sales_clients = add_sales_clients, disc_expenses = disc_expenses, disc_purchasing_suppliers = disc_purchasing_suppliers, note = NotesEntry.Text, amount = AmountEntry.Text, type_operation = 1 }; var nsAPI = RestService.For<IBoxService>("https://ittezanmobilepos.com"); try { var data = await nsAPI.Addinterproccess(box); if (data.success == true) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.AddedSucc, AppResources.Ok); Balancelbl.Text = data.message.box.balance; } } catch(Exception ex) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } else { Box box = new Box { add_sales_clients = add_sales_clients, disc_expenses = disc_expenses, disc_purchasing_suppliers = disc_purchasing_suppliers, note = NotesEntry.Text, amount = AmountEntry.Text, date = DateTime.Now.ToShortDateString(), balance = (double.Parse(Balancelbl.Text) + double.Parse(AmountEntry.Text)).ToString(), type_operation =1 }; var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Box"); if (!info.Any()) db.CreateTable<Box>(); db.Insert(box); ActiveIn.IsVisible = false; Balancelbl.Text = box.balance; await DisplayAlert(AppResources.Alert, AppResources.AddedSucc, AppResources.Ok); } } catch (ValidationApiException validationException) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 } catch (ApiException exception) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } } private async void Deductionbtn_Clicked(object sender, EventArgs e) { try { ActiveIn.IsVisible = true; if (CrossConnectivity.Current.IsConnected) { Box box = new Box { add_sales_clients = add_sales_clients, disc_expenses = disc_expenses, disc_purchasing_suppliers = disc_purchasing_suppliers, note = NotesEntry.Text, amount = AmountEntry.Text, type_operation = 0 }; var nsAPI = RestService.For<IBoxService>("https://ittezanmobilepos.com"); try { var data = await nsAPI.Addinterproccess(box); if (data.success == true) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.AddedSucc, AppResources.Ok); Balancelbl.Text = data.message.box.balance; } } catch { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } else { Box box = new Box { add_sales_clients = add_sales_clients, disc_expenses = disc_expenses, disc_purchasing_suppliers = disc_purchasing_suppliers, note = NotesEntry.Text, amount = AmountEntry.Text, date = DateTime.Now.ToShortDateString(), balance = (double.Parse(Balancelbl.Text) - double.Parse(AmountEntry.Text)).ToString(), type_operation = 0 }; var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Box"); if (!info.Any()) db.CreateTable<Box>(); db.Insert(box); ActiveIn.IsVisible = false; Balancelbl.Text = box.balance; await DisplayAlert(AppResources.Alert, AppResources.AddedSucc, AppResources.Ok); } } catch (ValidationApiException validationException) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 } catch (ApiException exception) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } } } }<file_sep>using Plugin.Permissions; using System; using Plugin.Permissions.Abstractions; using Xamarin.Forms; using Xamarin.Forms.Xaml; using ZXing.Net.Mobile.Forms; using System.Threading.Tasks; using Plugin.Connectivity; using IttezanPos.Models; using Refit; using IttezanPos.Services; using System.Collections.ObjectModel; using System.Collections.Generic; using IttezanPos.Helpers; using System.Linq; using Settings = IttezanPos.Helpers.Settings; using SQLite; using System.IO; using IttezanPos.Resources; using IttezanPos.Models.OfflineModel; using System.Net.Http; using Newtonsoft.Json; namespace IttezanPos.Views.InventoryPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ViewProductsPage : ContentPage { private List<int> client_ids = new List<int>(); private List<Product> products = new List<Product>(); public List<Product> Products { get { return products; } set { products = value; OnPropertyChanged(nameof(products)); } } public ObservableCollection<UpdateOfflineProduct> UpdatedClients { get; private set; } public ObservableCollection<DeleteOfflineProduct> DeletedClients { get; private set; } public ObservableCollection<OfflineProduct> AddedClients { get; private set; } public ViewProductsPage() { InitializeComponent(); listheaderlistv.FlowDirection = (Settings.LastUserGravity == "Arabic") ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; lisBydatetheaderlistv.FlowDirection = (Settings.LastUserGravity == "Arabic") ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; } private void Scan_Tapped(object sender, EventArgs e) { Scanner(); } async Task GetOffline() { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("OfflineProduct"); if (!info.Any()) db.CreateTable<OfflineProduct>(); AddedClients = new ObservableCollection<OfflineProduct>(db.Table<OfflineProduct>().ToList()); if (AddedClients.Count != 0) { if (CrossConnectivity.Current.IsConnected) { using (var client = new HttpClient()) { // var products = orderitems.ToArray(); var content = new MultipartFormDataContent(); var jsoncategoryArray = JsonConvert.SerializeObject(AddedClients); var values = new Dictionary<string, string> { {"products",jsoncategoryArray } }; var req = new HttpRequestMessage(HttpMethod.Post, "https://ittezanmobilepos.com/api/off-addproduct") { Content = new FormUrlEncodedContent(values) }; var response = await client.SendAsync(req); if (response.IsSuccessStatusCode) { var serverResponse = response.Content.ReadAsStringAsync().Result.ToString(); ActiveIn.IsVisible = false; // var json = JsonConvert.DeserializeObject<OfflineClientAdded>(serverResponse); AddedClients.Clear(); db.DropTable<OfflineProduct>(); // await Navigation.PushAsync(new SuccessfulReciep(json.message, saleproducts, paymentname)); } else { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } } } async Task GetOfflineUpdate() { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("UpdateOfflineProduct"); if (!info.Any()) db.CreateTable<UpdateOfflineProduct>(); UpdatedClients = new ObservableCollection<UpdateOfflineProduct>(db.Table<UpdateOfflineProduct>().ToList()); if (UpdatedClients.Count != 0) { if (CrossConnectivity.Current.IsConnected) { using (var client = new HttpClient()) { // var products = orderitems.ToArray(); var content = new MultipartFormDataContent(); var jsoncategoryArray = JsonConvert.SerializeObject(UpdatedClients); var values = new Dictionary<string, string> { {"products",jsoncategoryArray } }; var req = new HttpRequestMessage(HttpMethod.Post, "https://ittezanmobilepos.com/api/off-updateproduct") { Content = new FormUrlEncodedContent(values) }; var response = await client.SendAsync(req); if (response.IsSuccessStatusCode) { var serverResponse = response.Content.ReadAsStringAsync().Result.ToString(); ActiveIn.IsVisible = false; var json = JsonConvert.DeserializeObject<RootObject>(serverResponse); UpdatedClients.Clear(); // Clients = new ObservableCollection<Product>(json.message.pr); db.DropTable<UpdateOfflineProduct>(); // await Navigation.PushAsync(new SuccessfulReciep(json.message, saleproducts, paymentname)); // await Navigation.PopModalAsync(); } else { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } } } async Task GetOfflineDelete() { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("DeleteOfflineProduct"); if (!info.Any()) db.CreateTable<DeleteOfflineProduct>(); DeletedClients = new ObservableCollection<DeleteOfflineProduct>(db.Table<DeleteOfflineProduct>().ToList()); if (DeletedClients.Count != 0) { if (CrossConnectivity.Current.IsConnected) { using (var client = new HttpClient()) { // var products = orderitems.ToArray(); var content = new MultipartFormDataContent(); foreach (var item in DeletedClients) { client_ids.Add(item.product_id); } var jsoncategoryArray = JsonConvert.SerializeObject(client_ids); var values = new Dictionary<string, string> { {"product_ids",jsoncategoryArray } }; var req = new HttpRequestMessage(HttpMethod.Post, "https://ittezanmobilepos.com/api/off-delproduct") { Content = new FormUrlEncodedContent(values) }; var response = await client.SendAsync(req); if (response.IsSuccessStatusCode) { var serverResponse = response.Content.ReadAsStringAsync().Result.ToString(); ActiveIn.IsVisible = false; // var json = JsonConvert.DeserializeObject<OfflineClientAdded>(serverResponse); DeletedClients.Clear(); db.DropTable<DeleteOfflineProduct>(); // await Navigation.PushAsync(new SuccessfulReciep(json.message, saleproducts, paymentname)); } else { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } } } } public async void Scanner() { var ScannerPage = new ZXingScannerPage(); _ = Navigation.PushAsync(ScannerPage); try { var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera); if (status != PermissionStatus.Granted) { if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Camera)) { await DisplayAlert(AppResources.Alert, AppResources.NeedCamera,AppResources.Ok); } var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Camera); status = results[Permission.Location]; } if (status == PermissionStatus.Granted) { ScannerPage.OnScanResult += (result) => { Device.BeginInvokeOnMainThread(() => { _ = Navigation.PopAsync(); }); }; } else { await DisplayAlert(AppResources.Alert, AppResources.PermissionsDenied, AppResources.Ok); //On iOS you may want to send your user to the settings screen. CrossPermissions.Current.OpenAppSettings(); } } catch(Exception ex) { await DisplayAlert(AppResources.Alert, AppResources.PermissionsDenied, AppResources.Ok); //On iOS you may want to send your user to the settings screen. CrossPermissions.Current.OpenAppSettings(); } } protected override void OnAppearing() { _ = GetOfflineUpdate(); _ = GetOfflineDelete(); _ = GetData(); base.OnAppearing(); } async Task GetData() { try { ActiveIn.IsRunning = true; if (CrossConnectivity.Current.IsConnected) { var nsAPI = RestService.For<IApiService>("https://ittezanmobilepos.com/"); RootObject data = await nsAPI.GetSettings(); var eachCategories = new ObservableCollection<Category>(data.message.categories); foreach (var item in eachCategories) { // Products = item.category.list_of_products; Products.AddRange(item.category.list_of_products); } var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Product"); db.DeleteAll<Product>(); db.CreateTable<Product>(); foreach (var item in Products) { item.product_id = item.id; db.InsertOrReplace(item); } // Clients = new ObservableCollection<Client>(db.Table<Client>().ToList()); // db.CreateTable<Client>(); ProductsList.ItemsSource = products; ActiveIn.IsRunning = false; } else { ActiveIn.IsRunning = false; if (Device.RuntimePlatform == Device.iOS) { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Product"); Products = (db.Table<Product>().ToList()); ProductsList.ItemsSource = Products; } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Product"); Products =(db.Table<Product>().ToList()); ProductsList.ItemsSource = Products; } } } catch (ValidationApiException validationException) { // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } catch (ApiException exception) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } private void ClassifyByDatebtn_Clicked(object sender, EventArgs e) { ProductsByDateList.ItemsSource = Products.OrderBy(b => b.created_at).ThenBy(b => b.expiration_date).ToList(); ProductsList.IsVisible = false; ProductsByDateList.IsVisible = true; AllListbtn.IsVisible = true; ClassifyByDatebtn.IsVisible = false; } private void SearchBar_SearchButtonPressed(object sender, EventArgs e) { var keyword = SearchBar.Text; ProductsList.ItemsSource= Products.Where(product => product.name.Contains(keyword.ToLower())); } void OnTextChanged(object sender, EventArgs e) { SearchBar searchBar = (SearchBar)sender; var keyword = SearchBar.Text; ProductsList.ItemsSource = Products.Where(product => product.name.Contains(keyword.ToLower())); } private async void ProductsList_ItemTapped(object sender, ItemTappedEventArgs e) { var product = e.Item as Product; await Navigation.PushAsync(new AddingProductPage(product)); } private void AllListbtn_Clicked(object sender, EventArgs e) { ProductsList.IsVisible = true; ProductsByDateList.IsVisible = false; AllListbtn.IsVisible = false; ClassifyByDatebtn.IsVisible = true; } } }<file_sep>using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models.OfflineModel { public class OfflineSalesOrder { public double total_price { get; set; } public double amount_paid { get; set; } public string payment_type { get; set; } public double discount { get; set; } public string user_id { get; set; } public string client_id { get; set; } public List<SaleProductoff> products { get; set; } } public class SaleProductoff { public int id { get; set; } public double quantity { get; set; } public double total_price { get; set; } public double sale_price { get; set; } public double purchase_price { get; set; } public DateTimeOffset? expiration_date { get; set; } } } <file_sep>using Fusillade; using IttezanPos.Models; using Refit; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace IttezanPos.Services { [Headers("Content-Type: application/json")] public interface IApiService { [Get("/api/settinginfo")] Task<RootObject> GetSettings(); } } <file_sep>using IttezanPos.Models; using IttezanPos.Resources; using IttezanPos.Services; using Plugin.Connectivity; using Refit; using SQLite; using SQLiteNetExtensions.Extensions; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using static IttezanPos.ViewModels.InventoryViewModel; namespace IttezanPos.Views.InventoryPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class EditingProductSalaryPage : ContentPage { private ObservableCollection<Category> categories = new ObservableCollection<Category>(); private int up_down; private int purchase_sale; private int value_ratio; private int category_Id; public ObservableCollection<Category> Categories { get { return categories; } set { categories = value; OnPropertyChanged(nameof(categories)); } } public EditingProductSalaryPage() { InitializeComponent(); if (IttezanPos.Helpers.Settings.LastUserGravity == "Arabic") { CategoryListar.IsVisible = true; CategoryListen.IsVisible = false; } else { CategoryListar.IsVisible = false; CategoryListen.IsVisible = true; } up_down = 1; purchase_sale = 1; value_ratio = 1; category_Id = 0; } protected override void OnAppearing() { _ = GetData(); base.OnAppearing(); } async Task GetData() { try { ActiveIn.IsRunning = true; var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); Categories = new ObservableCollection<Category>(db.GetAllWithChildren<Category>().ToList()); CategoryListar.ItemsSource = Categories; CategoryListar.ItemsSource = Categories; ActiveIn.IsRunning = false; } catch (ValidationApiException validationException) { // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } catch (ApiException exception) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } private void increasebtn_Clicked(object sender, EventArgs e) { up_down = 1; } private void decreaebtn_Clicked(object sender, EventArgs e) { up_down = 0; } private void sellingbtn_Clicked(object sender, EventArgs e) { purchase_sale = 1; } private void Purchasingbtn_Clicked(object sender, EventArgs e) { purchase_sale = 0; } private void amountbtn_Clicked(object sender, EventArgs e) { value_ratio = 1; } private void percentbtn_Clicked(object sender, EventArgs e) { value_ratio = 0; } private void CategoryList_SelectedIndexChanged(object sender, EventArgs e) { var category = CategoryListar.SelectedItem as Category; category_Id = category.category.id; } private void CategoryListen_SelectedIndexChanged(object sender, EventArgs e) { var category = CategoryListen.SelectedItem as Category; category_Id = category.category.id; } private async void Button_Clicked(object sender, EventArgs e) { try { ActiveIn.IsRunning = true; Updateprice client = new Updateprice { category_id = category_Id, purchase_sale = purchase_sale, up_down = up_down, value_ratio = value_ratio, amount = double.Parse(amountentry.Text) }; if (CrossConnectivity.Current.IsConnected) { var nsAPI = RestService.For<IUpdateService>("https://<EMAIL>"); try { var data = await nsAPI.UpdatePrice(client); if (data.success == true) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.Productsmodified, AppResources.Ok); await Navigation.PopAsync(); } } catch (Exception ex) { ActiveIn.IsRunning = false; // var data = await nsAPI.AddClientError(client); // await Navigation.PushPopupAsync(new ClientAdded(data)); // Emailentry.Focus(); } } else { var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Updateprice"); if (!info.Any()) db.CreateTable<Updateprice>(); db.Insert(client); ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.Productsmodified, AppResources.Ok); await Navigation.PopAsync(); } } catch (ValidationApiException validationException) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 } catch (ApiException exception) { ActiveIn.IsRunning = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } } } }<file_sep> using IttezanPos.Models; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Tables; using Syncfusion.Drawing; using System.Collections.ObjectModel; using Xamarin.Forms; using Xamarin.Forms.Xaml; using System; using System.Linq; using System.IO; using Settings = IttezanPos.Helpers.Settings; using IttezanPos.DependencyServices; using System.Collections.Generic; using System.Reflection; using Syncfusion.Pdf.Grid; using System.Data; using IttezanPos.Helpers; namespace IttezanPos.Views.ClientPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ClientsPage : ContentPage { private ObservableCollection<Client> clients =new ObservableCollection<Client>(); public ObservableCollection<Client> Clients { get { return clients; } set { clients = value; OnPropertyChanged(nameof(clients)); } } public ClientsPage() { InitializeComponent(); } public ClientsPage(ObservableCollection<Client> clients) { InitializeComponent(); this.Clients = clients; ArabicListView.ItemsSource = Clients; Englishlistview.ItemsSource = Clients; if (IttezanPos.Helpers.Settings.LastUserGravity == "Arabic") { // listheaderlistv.FlowDirection = FlowDirection.RightToLeft; ArabicListView.IsVisible = true; Englishlistview.IsVisible = false; } else { // listheaderlistv.FlowDirection = FlowDirection.LeftToRight; ArabicListView.IsVisible = false; Englishlistview.IsVisible = true; } } private async void Listviewwww_ItemTapped(object sender, ItemTappedEventArgs e) { var content = e.Item as Client; await Navigation.PushAsync(new AddingClientPage(content)); } private void SearchBar_SearchButtonPressed(object sender, EventArgs e) { var keyword = SearchBar.Text; Englishlistview.ItemsSource= clients.Where(product => product.enname.ToLower().Contains(keyword.ToLower())); ArabicListView.ItemsSource = clients.Where(product => product.name.ToLower().Contains(keyword.ToLower())); } void OnTextChanged(object sender, EventArgs e) { SearchBar searchBar = (SearchBar)sender; var keyword = SearchBar.Text; Englishlistview.ItemsSource = clients.Where(product => product.enname.ToLower().Contains(keyword.ToLower())); ArabicListView.ItemsSource = clients.Where(product => product.name.ToLower().Contains(keyword.ToLower())); } private async void Reprtbtn_Clicked(object sender, EventArgs e) { //Create a new PDF document. PdfDocument doc = new PdfDocument(); //Add a page. PdfPage page = doc.Pages.Add(); Stream fontStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("IttezanPos.Assets.arial.ttf"); PdfTemplate header = PdfHelper.AddHeader(doc, "تقرير العملاء", "Ittezan Pos" + " " + DateTime.Now.ToString()); PdfCellStyle headerStyle = new PdfCellStyle(); headerStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center); page.Graphics.DrawPdfTemplate(header, new PointF()); //Create a PdfGrid. PdfGrid pdfGrid = new PdfGrid(); //String format // PdfFont pdfFont = new PdfTrueTypeFont(fontStream1, 12); //Create a DataTable. DataTable dataTable = new DataTable("EmpDetails"); List<Customer> customerDetails = new List<Customer>(); //Add columns to the DataTable dataTable.Columns.Add("ID"); dataTable.Columns.Add("Name"); dataTable.Columns.Add("Address"); //Add rows to the DataTable. foreach (var item in Clients) { Customer customer = new Customer(); customer.ID = item.id; customer.Name = item.name; customer.Address = item.address; customerDetails.Add(customer); dataTable.Rows.Add(new string[] { customer.ID.ToString(), customer.Name, customer.Address }); } //Assign data source. pdfGrid.DataSource = dataTable; pdfGrid.Headers.Add(1); PdfGridRow pdfGridRowHeader = pdfGrid.Headers[0]; pdfGridRowHeader.Cells[0].Value = "رقم العميل"; pdfGridRowHeader.Cells[1].Value = "إسم العميل"; pdfGridRowHeader.Cells[2].Value = "عنوان العميل"; PdfGridStyle pdfGridStyle = new PdfGridStyle(); pdfGridStyle.Font = new PdfTrueTypeFont(fontStream, 12); PdfGridLayoutFormat format1 = new PdfGridLayoutFormat(); format1.Break = PdfLayoutBreakType.FitPage; format1.Layout = PdfLayoutType.Paginate; PdfStringFormat format = new PdfStringFormat(); format.TextDirection = PdfTextDirection.RightToLeft; format.Alignment = PdfTextAlignment.Center; format.LineAlignment = PdfVerticalAlignment.Middle; pdfGrid.Columns[0].Format = format; pdfGrid.Columns[1].Format = format; pdfGrid.Columns[2].Format = format; pdfGrid.Style = pdfGridStyle; //Draw grid to the page of PDF document. pdfGrid.Draw(page, new Syncfusion.Drawing.Point(0, (int)header.Height + 10), format1); MemoryStream stream = new MemoryStream(); //Save the document. doc.Save(stream); //close the document doc.Close(true); await Xamarin.Forms.DependencyService.Get<ISave>().SaveAndView("تقرير العملاء.pdf", "application/pdf", stream); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models { public class Translation { public int id { get; set; } public int category_id { get; set; } public int product_id { get; set; } public string name { get; set; } public string locale { get; set; } } } <file_sep>using System; using System.Globalization; using System.Linq; using System.Threading; using IttezanPos.Helpers; using IttezanPos.Resources; using IttezanPos.Views.ClientPages; using IttezanPos.Views.ExpensesPages; using IttezanPos.Views.InventoryPages; using IttezanPos.Views.PurchasingPages; using IttezanPos.Views.ReportsPages; using IttezanPos.Views.ReservoirPages; using IttezanPos.Views.SalesPages; using IttezanPos.Views.SupplierPages; using Plugin.Connectivity; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.MainPage { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class HomePage : ContentPage { public HomePage() { InitializeComponent(); FlowDirectionPage(); } private void FlowDirectionPage() { FlowDirection = (Settings.LastUserGravity == "Arabic") ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultures(CultureTypes.NeutralCultures).ToList(). First(element => element.EnglishName.Contains(Settings.LastUserGravity)); AppResources.Culture = Thread.CurrentThread.CurrentUICulture; GravityClass.Grav(); } private async void Client_Tapped(object sender, EventArgs e) { await Navigation.PushAsync(new MainClientsPage()); } private async void Supplier_Tapped(object sender, EventArgs e) { await Navigation.PushAsync(new MainSuppliersPage()); } private async void Resrvoir_Tapped(object sender, EventArgs e) { await Navigation.PushAsync(new ReservoirPage()); } private async void Expanse_Tapped(object sender, EventArgs e) { await Navigation.PushAsync(new ExpensePage()); } private async void Inventory_Tapped(object sender, EventArgs e) { await Navigation.PushAsync(new InventoryMainPage()); } private async void Purchase_Tapped(object sender, EventArgs e) { await Navigation.PushAsync(new PurchasePage()); } private async void Sales_Tapped(object sender, EventArgs e) { await Navigation.PushAsync(new SalesMaster()); } private async void Reports_Tapped(object sender, EventArgs e) { await Navigation.PushAsync(new Reportpage()); } } }<file_sep>using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models.OfflineModel { public class OfflineBox { public bool success { get; set; } public string data { get; set; } public List<Offlineforbox> message { get; set; } } public class Offlineforbox { public int type_operation { get; set; } public int amount { get; set; } public string date { get; set; } public string note { get; set; } public string updated_at { get; set; } public string created_at { get; set; } public int id { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace IttezanPos.Views.Intro { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SplashPage : ContentPage { public SplashPage() { InitializeComponent(); } protected override async void OnAppearing() { base.OnAppearing(); await splashImage.FadeTo(1,3000,Easing.Linear); // SetMainPage(); // await splashImage.ScaleTo(150, 1200, Easing.Linear); //After loading MainPage it gets Navigated to our new Page } private double width = 0; private double height = 0; protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); //must be called if (this.width != width || this.height != height) { this.width = width; this.height = height; //reconfigure layout } } } }<file_sep>using Plugin.Permissions.Abstractions; using Plugin.Permissions; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IttezanPos.Helpers; using Xamarin.Forms; using Xamarin.Forms.Xaml; using ZXing.Net.Mobile.Forms; using IttezanPos.Models; using Plugin.Connectivity; using IttezanPos.Services; using Refit; using System.Collections.ObjectModel; using System.IO; using SQLite; using Rg.Plugins.Popup.Extensions; using IttezanPos.Views.SalesPages.SalesPopups; using SQLiteNetExtensions.Extensions; using Settings = IttezanPos.Helpers.Settings; using System.Threading; using System.Globalization; using IttezanPos.Resources; using IttezanPos.Views.InventoryPages; using Plugin.Toast; using System.Text.RegularExpressions; namespace IttezanPos.Views.SalesPages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MainSalesPage : ContentPage { double Alldisc; private ObservableCollection<Category> categories = new ObservableCollection<Category>(); public ObservableCollection<Category> Categories { get { return categories; } set { categories = value; OnPropertyChanged(nameof(categories)); } } private List<Category2> categories1 = new List<Category2>(); public List<Category2> Categories1 { get { return categories1; } set { categories1 = value; OnPropertyChanged(nameof(categories)); } } private List<Product> products = new List<Product>(); public List<Product> Products { get { return products; } set { products = value; OnPropertyChanged(nameof(products)); } } private List<SaleProduct> saleproducts = new List<SaleProduct>(); public List<SaleProduct> SaleProducts { get { return saleproducts; } set { saleproducts = value; OnPropertyChanged(nameof(saleproducts)); } } private ObservableCollection<SaleProduct> salesro = new ObservableCollection<SaleProduct>(); public ObservableCollection<SaleProduct> Salesro { get { return salesro; } set { salesro = value; OnPropertyChanged(nameof(salesro)); } } private List<Client> clients = new List<Client>(); public List<Client> Clients { get { return clients; } set { clients = value; OnPropertyChanged(nameof(clients)); } } private ObservableCollection<Payment> payments = new ObservableCollection<Payment>(); public ObservableCollection<Payment> Payments { get { return payments; } set { payments = value; OnPropertyChanged(nameof(payments)); } } public List<HoldProduct> HoldList { get; private set; } double discount = 0; public MainSalesPage() { InitializeComponent(); if (IttezanPos.Helpers.Settings.LastUserGravity == "Arabic") { ProductsList.IsVisible = false; ProductsListAr.IsVisible = true; CategoryListar.IsVisible = true; CategoryListen.IsVisible = false; } else { ProductsList.IsVisible = true; ProductsListAr.IsVisible = false; CategoryListar.IsVisible = false; CategoryListen.IsVisible = true; } FlowDirectionPage(); MessagingCenter.Subscribe<SaleHold>(this, "SaleHold", (value) => { if (SaleProducts.Count()!=0) { foreach (var item in SaleProducts) { item.quantity = 0; item.total_price = 0; item.discount = 0; } SaleProducts.Clear(); Salesro.Clear(); } totallbl.Text = AppResources.Zero; subtotallbl.Text = AppResources.Zero; Disclbl.Text = AppResources.Zero; cartnolbl.Text = AppResources.Zero; SaleProducts.AddRange(value.product.saleProducts); subtotallbl.Text = value.product.subtotal; totallbl.Text = value.product.total; Disclbl.Text = value.product.discount; cartnolbl.Text = value.product.number; Salesro = new ObservableCollection<SaleProduct>(SaleProducts); SalesList.ItemsSource = Salesro; SalesListen.ItemsSource = Salesro; }); MessagingCenter.Subscribe<ValuePercent>(this, "PopUpData", (value) => { if (value.Value != 0) { Alldisc = value.alldisc; Disclbl.Text = (double.Parse(Disclbl.Text) - value.alldisc).ToString("0.00"); Disclbl.Text = (double.Parse(Disclbl.Text) + value.Value).ToString("0.00"); Alldisc = value.Value; totallbl.Text = (double.Parse(subtotallbl.Text) - double.Parse(Disclbl.Text)).ToString("0.00"); } else { Alldisc = value.alldisc; Disclbl.Text = (double.Parse(Disclbl.Text) - value.alldisc).ToString("0.00"); Disclbl.Text = ((value.Percentage*double.Parse(subtotallbl.Text))+ double.Parse(Disclbl.Text)).ToString("0.00"); Alldisc = value.Percentage * double.Parse(subtotallbl.Text); totallbl.Text = (double.Parse(subtotallbl.Text) - double.Parse(Disclbl.Text)).ToString("0.00"); } }); MessagingCenter.Subscribe<ValueQuantity>(this, "PopUpData1", (value) => { checkquantity(value); }); MessagingCenter.Subscribe<ValuePercentitem>(this, "PopUpDataitem", (value) => { checkdiscount(value); }); } private void checkdiscount(ValuePercentitem value) { if (value.Value!=0) { if (value.product.sale_price > value.Value) { Disclbl.Text = (double.Parse(Disclbl.Text) - value.product.discount).ToString("0.00"); value.product.discount = 0; discount = value.Value; value.product.discount = value.product.discount + discount; Disclbl.Text = (double.Parse(Disclbl.Text) + value.product.discount).ToString("0.00"); totallbl.Text = (double.Parse(subtotallbl.Text) - double.Parse(Disclbl.Text)).ToString("0.00"); value.product.total_price = value.product.sale_price * value.product.quantity; foreach (var item in SaleProducts) { if (item.id == value.product.id) { item.discount = value.product.discount; item.total_price = value.product.total_price- item.discount; } } Salesro = new ObservableCollection<SaleProduct>(SaleProducts); SalesList.ItemsSource = Salesro; SalesListen.ItemsSource = Salesro; } else { CrossToastPopUp.Current.ShowToastError(AppResources.Valuediscerror, Plugin.Toast.Abstractions.ToastLength.Long); //Disclbl.Text = (double.Parse(value.Percentage) * double.Parse(subtotallbl.Text)).ToString(); //totallbl.Text = (double.Parse(subtotallbl.Text) - double.Parse(Disclbl.Text)).ToString(); } } else { // discount = value.Percentage* value.product.sale_price; if (value.product.sale_price > value.Percentage) { Disclbl.Text = (double.Parse(Disclbl.Text) - value.product.discount).ToString("0.00"); value.product.discount = 0; discount = value.Percentage * value.product.total_price; value.product.discount = value.product.discount + discount; Disclbl.Text = (double.Parse(Disclbl.Text) + value.product.discount).ToString("0.00"); totallbl.Text = (double.Parse(subtotallbl.Text) - double.Parse(Disclbl.Text)).ToString("0.00"); value.product.total_price = value.product.sale_price * value.product.quantity; foreach (var item in SaleProducts) { if (item.id == value.product.id) { item.discount = value.product.discount; item.total_price = value.product.total_price - item.discount; } } Salesro = new ObservableCollection<SaleProduct>(SaleProducts); SalesList.ItemsSource = Salesro; SalesListen.ItemsSource = Salesro; } else { CrossToastPopUp.Current.ShowToastError(AppResources.Valuediscerror, Plugin.Toast.Abstractions.ToastLength.Long); //Disclbl.Text = (double.Parse(value.Percentage) * double.Parse(subtotallbl.Text)).ToString(); //totallbl.Text = (double.Parse(subtotallbl.Text) - double.Parse(Disclbl.Text)).ToString(); } } } private void checkquantity(ValueQuantity value) { if (value.Quantity != 0) { if (Convert.ToDouble(value.product.stock) > value.Quantity) { Disclbl.Text = (double.Parse(Disclbl.Text) - value.product.discount).ToString(); cartnolbl.Text = (double.Parse(cartnolbl.Text) - value.product.quantity).ToString(); subtotallbl.Text = (double.Parse(subtotallbl.Text) - value.product.total_price).ToString("0.00"); totallbl.Text = (double.Parse(subtotallbl.Text) - double.Parse(Disclbl.Text)).ToString("0.00"); value.product.quantity = value.Quantity; cartnolbl.Text = (double.Parse(cartnolbl.Text) + value.product.quantity).ToString(); value.product.total_price = value.product.sale_price * value.product.quantity; subtotallbl.Text = (double.Parse(subtotallbl.Text) + value.product.total_price).ToString("0.00"); totallbl.Text = (double.Parse(subtotallbl.Text) - double.Parse(Disclbl.Text)).ToString("0.00"); ; value.product.discount = 0; foreach (var item in SaleProducts.Where(w => w.id == value.product.id)) { item.quantity = value.product.quantity; item.total_price = value.product.total_price; item.discount = value.product.discount; } Salesro = new ObservableCollection<SaleProduct>(SaleProducts); SalesList.ItemsSource = Salesro; SalesListen.ItemsSource = Salesro; } else { CrossToastPopUp.Current.ShowToastError(AppResources.Stockerror, Plugin.Toast.Abstractions.ToastLength.Long); //Disclbl.Text = (double.Parse(value.Percentage) * double.Parse(subtotallbl.Text)).ToString(); //totallbl.Text = (double.Parse(subtotallbl.Text) - double.Parse(Disclbl.Text)).ToString(); } } else { CrossToastPopUp.Current.ShowToastError(AppResources.EnterQuantity, Plugin.Toast.Abstractions.ToastLength.Long); } } private void FlowDirectionPage() { FlowDirection = (Helpers.Settings.LastUserGravity == "Arabic") ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultures(CultureTypes.NeutralCultures).ToList(). First(element => element.EnglishName.Contains(Helpers.Settings.LastUserGravity)); AppResources.Culture = Thread.CurrentThread.CurrentUICulture; GravityClass.Grav(); } protected override bool OnBackButtonPressed() { MessagingCenter.Unsubscribe<SaleHold>(this, "SaleHold"); MessagingCenter.Unsubscribe<ValuePercentitem>(this, "PopUpDataitem"); MessagingCenter.Unsubscribe<ValueQuantity>(this, "PopUpData1"); MessagingCenter.Unsubscribe<ValuePercent>(this, "PopUpData"); if (SaleProducts.Count() != 0) { foreach (var item in SaleProducts) { item.quantity = 0; item.total_price = 0; item.discount = 0; } SaleProducts.Clear(); Salesro.Clear(); totallbl.Text = AppResources.Zero; subtotallbl.Text = AppResources.Zero; Disclbl.Text = AppResources.Zero; cartnolbl.Text = AppResources.Zero; Salesro = new ObservableCollection<SaleProduct>(SaleProducts); SalesList.ItemsSource = Salesro; SalesListen.ItemsSource = Salesro; } CategoryListen.Unfocus(); CategoryListar.Unfocus(); return base.OnBackButtonPressed(); } protected override void OnAppearing() { _ = GetData(); base.OnAppearing(); } async Task GetData() { ActiveIn.IsVisible = true; if (CrossConnectivity.Current.IsConnected) { try { var nsAPI = RestService.For<IApiService>("https://ittezanmobilepos.com/"); RootObject data = await nsAPI.GetSettings(); Categories = new ObservableCollection<Category>(data.message.categories); Clients = data.message.clients; Payments = new ObservableCollection<Payment>(data.message.payments); foreach (var item in Categories) { // item.category2Id = item.category.id; foreach (var item2 in item.category.list_of_products) { item2.product_id = item2.id; } if (item.category.list_of_products.Count!=0) { Products.AddRange(item.category.list_of_products); } Categories1.Add(item.category); } Category2 all = new Category2(); all.name = "الكل"; all.enname = "All"; all.id = 0; all.list_of_products = Products; Categories1.Insert(0,all); Category allL = new Category(); allL.category = all; allL.Id = 0; allL.category2Id = all.id; Categories.Insert(0, allL); var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Product"); var info2 = db.GetTableInfo("Category"); var info5 = db.GetTableInfo("Category2"); var info3 = db.GetTableInfo("Payment"); var info4 = db.GetTableInfo("Client"); if (!info.Any() && !info2.Any() && !info3.Any() && !info5.Any() && !info4.Any()) { db.CreateTable<Product>(); db.CreateTable<Client>(); db.CreateTable<Payment>(); db.CreateTable<Category>(); db.CreateTable<Category2>(); db.InsertAll(Clients); db.InsertAll(Products); db.InsertAll(Payments); db.InsertAll(Categories1); db.InsertAllWithChildren(Categories); } else { db.DropTable<Category>(); db.DropTable<Category2>(); db.DropTable<Product>(); db.DropTable<Client>(); db.DropTable<Payment>(); db.CreateTable<Product>(); db.CreateTable<Category2>(); db.InsertAll(Categories1); db.CreateTable<Client>(); db.CreateTable<Payment>(); db.CreateTable<Category>(); db.InsertAll(Clients); db.InsertAll(Products); db.InsertAll(Payments); db.InsertAllWithChildren(Categories); } } catch (ValidationApiException validationException) { // handle validation here by using validationException.Content, // which is type of ProblemDetails according to RFC 7807 ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } catch (ApiException exception) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); // other exception handling } catch (Exception ex) { ActiveIn.IsVisible = false; await DisplayAlert(AppResources.Alert, AppResources.ConnectionNotAvailable, AppResources.Ok); } } else { try { ActiveIn.IsVisible = false; var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("Product"); if (!info.Any()) db.CreateTable<Product>(); db.CreateTable<Category>(); db.CreateTable<Category2>(); db.CreateTable<Payment>(); Products = (db.Table<Product>().ToList()); Categories = new ObservableCollection<Category>(db.GetAllWithChildren<Category>().ToList()); Payments = new ObservableCollection<Payment>(db.Table<Payment>().ToList()); } catch (Exception e) { } } ActiveIn.IsVisible = false; ProductsList.FlowItemsSource = Products; ProductsListAr.FlowItemsSource = Products; CategoryListar.ItemsSource = Categories; CategoryListen.ItemsSource = Categories; } private void Scan_Tapped(object sender, EventArgs e) { Scanner(); } public async void Scanner() { var ScannerPage = new ZXingScannerPage(); _ = Navigation.PushAsync(ScannerPage); try { var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera); if (status != PermissionStatus.Granted) { if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Camera)) { await DisplayAlert(AppResources.Alert, AppResources.NeedCamera, AppResources.Ok); } var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Camera); status = results[Permission.Location]; } if (status == PermissionStatus.Granted) { ScannerPage.OnScanResult += (result) => { Device.BeginInvokeOnMainThread(() => { _ = Navigation.PopAsync(); // ProductsList.FlowItemsSource = Products.Where(product => product.barcode==result.Text).ToList(); }); }; } else { await DisplayAlert(AppResources.Alert, AppResources.PermissionsDenied, AppResources.Ok); //On iOS you may want to send your user to the settings screen. CrossPermissions.Current.OpenAppSettings(); } } catch (Exception ex) { await DisplayAlert(AppResources.Alert, AppResources.PermissionsDenied, AppResources.Ok); //On iOS you may want to send your user to the settings screen. CrossPermissions.Current.OpenAppSettings(); } } private void searchbarvisible_Tapped(object sender, EventArgs e) { searchbar.IsVisible = true; searchstk.IsVisible = false; pickergrd.IsVisible = false; } private void searchbarinvisible_Tapped(object sender, EventArgs e) { searchbar.IsVisible = false; searchstk.IsVisible = true; pickergrd.IsVisible = true; } private void ProductsList_FlowItemTapped(object sender, ItemTappedEventArgs e) { var saleproduct = ProductsList.FlowLastTappedItem as Product; SaleProduct sale = new SaleProduct { id = saleproduct.id, catname = saleproduct.catname, category_id = saleproduct.category_id, category2Id = saleproduct.category2Id, created_at = saleproduct.created_at, description = saleproduct.description, discount = saleproduct.discount, Enname = saleproduct.Enname, expiration_date = saleproduct.expiration_date, image = saleproduct.image, locale = saleproduct.locale, product_id = saleproduct.product_id, profit_percent = saleproduct.profit_percent, quantity = saleproduct.quantity, sale_price = saleproduct.sale_price, stock = saleproduct.stock, total_price = saleproduct.total_price, updated_at = saleproduct.updated_at, translations = saleproduct.translations, user = saleproduct.user, user_id = saleproduct.user_id, name = saleproduct.name, }; if (sale.stock != 0) { sale.quantity++; sale.total_price = (sale.sale_price * sale.quantity); if (SaleProducts.Count() == 0) { SaleProducts.Add(sale); cartnolbl.Text = (int.Parse(cartnolbl.Text) + 1).ToString(); double subtotal = (double.Parse(subtotallbl.Text) + double.Parse(sale.sale_price.ToString())); Disclbl.Text = (double.Parse(Disclbl.Text) - sale.discount).ToString("0.00"); double total = subtotal - double.Parse(Disclbl.Text); totallbl.Text = total.ToString("0.00"); subtotallbl.Text = subtotal.ToString("0.00"); } else { var obj = SaleProducts.Find(x => x.id == sale.id); if (obj != null) { cartnolbl.Text = (int.Parse(cartnolbl.Text) + 1).ToString(); double subtotal = (double.Parse(subtotallbl.Text) + double.Parse(sale.sale_price.ToString())); Disclbl.Text = (double.Parse(Disclbl.Text) - obj.discount).ToString("0.00"); double total = subtotal - double.Parse(Disclbl.Text); totallbl.Text = total.ToString("0.00"); subtotallbl.Text = subtotal.ToString("0.00"); sale.discount = 0; foreach (var tom in SaleProducts.Where(w => w.id == obj.id)) { tom.discount = sale.discount; tom.quantity = tom.quantity + sale.quantity; tom.total_price = tom.total_price + sale.total_price; } } else { cartnolbl.Text = (int.Parse(cartnolbl.Text) + 1).ToString(); double subtotal = (double.Parse(subtotallbl.Text) + double.Parse(sale.sale_price.ToString())); Disclbl.Text = (double.Parse(Disclbl.Text) - sale.discount).ToString("0.00"); double total = subtotal - double.Parse(Disclbl.Text); totallbl.Text = total.ToString("0.00"); subtotallbl.Text = subtotal.ToString("0.00"); SaleProducts.Add(sale); } } CrossToastPopUp.Current.ShowToastSuccess(sale.name + " " + AppResources.Added, Plugin.Toast.Abstractions.ToastLength.Short); } else { CrossToastPopUp.Current.ShowToastError(AppResources.Stockerror, Plugin.Toast.Abstractions.ToastLength.Long); } Salesro = new ObservableCollection<SaleProduct>(SaleProducts); SalesList.ItemsSource = Salesro; SalesListen.ItemsSource = Salesro; } private void ProductsListAr_FlowItemTapped(object sender, ItemTappedEventArgs e) { var saleproduct = ProductsListAr.FlowLastTappedItem as Product; SaleProduct sale = new SaleProduct { id = saleproduct.id, catname = saleproduct.catname, category_id = saleproduct.category_id, category2Id = saleproduct.category2Id, created_at = saleproduct.created_at, description = saleproduct.description, discount = saleproduct.discount, Enname = saleproduct.Enname, expiration_date = saleproduct.expiration_date, image = saleproduct.image, locale = saleproduct.locale, product_id = saleproduct.product_id, profit_percent = saleproduct.profit_percent, quantity = saleproduct.quantity, sale_price = saleproduct.sale_price, stock = saleproduct.stock, total_price = saleproduct.total_price, updated_at = saleproduct.updated_at, translations = saleproduct.translations, user = saleproduct.user, user_id = saleproduct.user_id, name = saleproduct.name, }; if (sale.stock != 0) { sale.quantity++; sale.total_price = (sale.sale_price * sale.quantity); if (SaleProducts.Count() == 0) { SaleProducts.Add(sale); cartnolbl.Text = (int.Parse(cartnolbl.Text) + 1).ToString(); double subtotal = (double.Parse(subtotallbl.Text) + double.Parse(sale.sale_price.ToString())); Disclbl.Text = (double.Parse(Disclbl.Text) - sale.discount).ToString("0.00"); double total = subtotal - double.Parse(Disclbl.Text); totallbl.Text = total.ToString("0.00"); subtotallbl.Text = subtotal.ToString("0.00"); } else { var obj = SaleProducts.Find(x => x.id == sale.id); if (obj != null) { cartnolbl.Text = (int.Parse(cartnolbl.Text) + 1).ToString(); double subtotal = (double.Parse(subtotallbl.Text) + double.Parse(sale.sale_price.ToString())); Disclbl.Text = (double.Parse(Disclbl.Text) - obj.discount).ToString("0.00"); double total = subtotal - double.Parse(Disclbl.Text); totallbl.Text = total.ToString("0.00"); subtotallbl.Text = subtotal.ToString("0.00"); sale.discount = 0; foreach (var tom in SaleProducts.Where(w => w.id == obj.id)) { tom.discount = sale.discount; tom.quantity = tom.quantity+ sale.quantity; tom.total_price = tom.total_price+ sale.total_price; } } else { cartnolbl.Text = (int.Parse(cartnolbl.Text) + 1).ToString(); double subtotal = (double.Parse(subtotallbl.Text) + double.Parse(sale.sale_price.ToString())); Disclbl.Text = (double.Parse(Disclbl.Text) - sale.discount).ToString("0.00"); double total = subtotal - double.Parse(Disclbl.Text); totallbl.Text = total.ToString("0.00"); subtotallbl.Text = subtotal.ToString("0.00"); SaleProducts.Add(sale); } } CrossToastPopUp.Current.ShowToastSuccess(sale.name + " " + AppResources.Added, Plugin.Toast.Abstractions.ToastLength.Short); } else { CrossToastPopUp.Current.ShowToastError(AppResources.Stockerror, Plugin.Toast.Abstractions.ToastLength.Long); } Salesro = new ObservableCollection<SaleProduct>(SaleProducts); SalesList.ItemsSource = Salesro; SalesListen.ItemsSource = Salesro; } private async void TapGestureRecognizer_Tapped(object sender, EventArgs e) { if (((sender as Grid).BindingContext is Product _selectedprp)) { await Navigation.PushAsync(new AddingProductPage(_selectedprp)); } } private void CategoryList_SelectedIndexChanged(object sender, EventArgs e) { var category = CategoryListar.SelectedItem as Category; if (category.category.name == "الكل") { ProductsList.FlowItemsSource = Products; ProductsListAr.FlowItemsSource = Products; } else { ProductsList.FlowItemsSource = Products.Where(product => product.category_id==category.category.id).ToList(); ProductsListAr.FlowItemsSource = Products.Where(product => product.category_id == category.category.id).ToList(); } } private void CategoryListen_SelectedIndexChanged(object sender, EventArgs e) { var category = CategoryListen.SelectedItem as Category; if (category.category.name == "الكل") { ProductsList.FlowItemsSource = Products; ProductsListAr.FlowItemsSource = Products; } else { ProductsList.FlowItemsSource = Products.Where(product => product.category_id == category.category.id).ToList(); ProductsListAr.FlowItemsSource = Products.Where(product => product.category_id == category.category.id).ToList(); } } private void SearchBar_TextChanged(object sender, TextChangedEventArgs e) { SearchBar searchBar = (SearchBar)sender; var keyword = SearchBar.Text; if(Regex.IsMatch(keyword, "^[a-zA-Z0-9]*$")) { ProductsList.FlowItemsSource = Products.Where(product => product.Enname.Contains(keyword.ToLower())).ToList(); ProductsListAr.FlowItemsSource = Products.Where(product => product.Enname.Contains(keyword.ToLower())).ToList(); } else { ProductsListAr.FlowItemsSource = Products.Where(product => product.name.Contains(keyword.ToLower())).ToList(); ProductsList.FlowItemsSource = Products.Where(product => product.name.Contains(keyword.ToLower())).ToList(); } } private void SearchBar_SearchButtonPressed(object sender, EventArgs e) { var keyword = SearchBar.Text; if (Regex.IsMatch(keyword, "^[a-zA-Z0-9]*$")) { ProductsList.FlowItemsSource = Products.Where(product => product.Enname.Contains(keyword.ToLower())).ToList(); ProductsListAr.FlowItemsSource = Products.Where(product => product.Enname.Contains(keyword.ToLower())).ToList(); } else { ProductsListAr.FlowItemsSource = Products.Where(product => product.name.Contains(keyword.ToLower())).ToList(); ProductsList.FlowItemsSource = Products.Where(product => product.name.Contains(keyword.ToLower())).ToList(); } } private void Master_Tapped(object sender, EventArgs e) { var page = (App.Current.MainPage as NavigationPage).CurrentPage; (page as MasterDetailPage).IsPresented = true; } private async void BAck_Tapped(object sender, EventArgs e) { await Navigation.PopAsync(); } private void Cart_Tapped(object sender, EventArgs e) { if (Settings.LastUserGravity == "Arabic") { SalesList.IsVisible = true; listheaderlistv.FlowDirection = FlowDirection.RightToLeft; SalesListen.IsVisible = false; Productstk.IsVisible = false; backtosales.IsVisible = true; } else { listheaderlistv.FlowDirection = FlowDirection.LeftToRight; SalesList.IsVisible = false; SalesListen.IsVisible = true; Productstk.IsVisible = false; backtosales.IsVisible = true; } } private void Backtostk_Tapped(object sender, EventArgs e) { if (Settings.LastUserGravity == "Arabic") { Productstk.IsVisible = true; SalesList.IsVisible = false; SalesListen.IsVisible = false; backtosales.IsVisible = false; } else { Productstk.IsVisible = true; SalesList.IsVisible = false; SalesListen.IsVisible = false; backtosales.IsVisible = false; } } //private void discEntry_TextChanged(object sender, TextChangedEventArgs e) //{ // if (((sender as Entry).BindingContext is Product _selectedUser)) // { // if (e.NewTextValue != "") // { // subtotallbl.Text = (double.Parse(subtotallbl.Text) - _selectedUser.total_price).ToString(); // totallbl.Text = (double.Parse(subtotallbl.Text) - double.Parse(Disclbl.Text)).ToString(); // _selectedUser.discount = e.NewTextValue; // double discPerc = double.Parse(e.NewTextValue) / 100; // double disc = double.Parse(_selectedUser.total_price.ToString()) * discPerc; // double subtotal2 = _selectedUser.total_price + double.Parse(subtotallbl.Text); // subtotallbl.Text = subtotal2.ToString("0.00"); // double usertotal = _selectedUser.total_price- disc; // _selectedUser.total_price = usertotal; // discountt= Disclbl.Text =(double.Parse(Disclbl.Text)+ disc).ToString("0.00"); // double total2 = subtotal2 - // double.Parse(Disclbl.Text); // totallbl.Text = total2.ToString("0.00"); // // SaleProducts.Insert(_selectedUser.id, obj); // } // else // { // subtotallbl.Text = (double.Parse(subtotallbl.Text) - _selectedUser.total_price).ToString(); // totallbl.Text = (double.Parse(subtotallbl.Text) - double.Parse(Disclbl.Text)).ToString(); // Disclbl.Text = (double.Parse(Disclbl.Text) - double.Parse(discountt)).ToString() ; // _selectedUser.discount = "0"; // double discPerc =0; // double disc = double.Parse(_selectedUser.total_price.ToString()) * discPerc; // double subtotal2 = _selectedUser.total_price + double.Parse(subtotallbl.Text); // subtotallbl.Text = subtotal2.ToString("0.00"); // double usertotal = _selectedUser.sale_price * _selectedUser.quantity; // _selectedUser.total_price = usertotal; // Disclbl.Text = (double.Parse(Disclbl.Text) + disc).ToString("0.00"); // double total2 = subtotal2 - // double.Parse(Disclbl.Text); // totallbl.Text = total2.ToString("0.00"); // } // } // Salesro = new ObservableCollection<Product>(SaleProducts); // SalesList.ItemsSource = Salesro; //} private void CustomEntry_TextChanged(object sender, TextChangedEventArgs e) { //if (((sender as Entry).BindingContext is Product _selectedUser)) //{ // if (e.OldTextValue != null) // { // if (e.OldTextValue == "") // { // cartnolbl.Text = int.Parse(cartnolbl.Text).ToString(); // } // else // { // cartnolbl.Text = (int.Parse(cartnolbl.Text) - int.Parse(e.OldTextValue)).ToString(); // subtotallbl.Text = (double.Parse(subtotallbl.Text) - _selectedUser.total_price).ToString("0.00"); // totallbl.Text = (double.Parse(subtotallbl.Text) - double.Parse(Disclbl.Text)).ToString("0.00"); // } // // totallbl.Text = total.ToString(); // if (e.NewTextValue != "") // { // if (_selectedUser.stock > int.Parse(e.NewTextValue)) // { // if (e.NewTextValue != "1") // { // cartnolbl.Text = (int.Parse(cartnolbl.Text) + _selectedUser.quantity).ToString(); // _selectedUser.quantity = int.Parse(e.NewTextValue); // _selectedUser.total_price = _selectedUser.sale_price * _selectedUser.quantity; // double subtotal2 = _selectedUser.total_price + double.Parse(subtotallbl.Text); // double total2 = subtotal2 - // double.Parse(Disclbl.Text); // totallbl.Text = total2.ToString("0.00"); // subtotallbl.Text = subtotal2.ToString("0.00"); // Salesro = new ObservableCollection<Product>(SaleProducts); // SalesList.ItemsSource = Salesro; // } // else // { // cartnolbl.Text = (int.Parse(cartnolbl.Text) + _selectedUser.quantity).ToString(); // _selectedUser.quantity = int.Parse(e.NewTextValue); // _selectedUser.total_price = _selectedUser.sale_price * _selectedUser.quantity; // double subtotal2 = _selectedUser.total_price + double.Parse(subtotallbl.Text); // double total2 = subtotal2 - // double.Parse(Disclbl.Text); // totallbl.Text = total2.ToString("0.00"); // subtotallbl.Text = subtotal2.ToString("0.00"); // Salesro = new ObservableCollection<Product>(SaleProducts); // SalesList.ItemsSource = Salesro; // } // } // else // { // // e.NewTextValue == e.OldTextValue; // _selectedUser.quantity = int.Parse(e.OldTextValue); // cartnolbl.Text = (int.Parse(cartnolbl.Text) + _selectedUser.quantity).ToString(); // _selectedUser.total_price = _selectedUser.sale_price * _selectedUser.quantity; // double subtotal2 = _selectedUser.total_price + double.Parse(subtotallbl.Text); // double total2 = subtotal2 - // double.Parse(Disclbl.Text); // totallbl.Text = total2.ToString("0.00"); // subtotallbl.Text = subtotal2.ToString("0.00"); // var newt = e.OldTextValue; // // e.NewTextValue == newt; // Salesro = new ObservableCollection<Product>(SaleProducts); // SalesList.ItemsSource = Salesro; // CrossToastPopUp.Current.ShowToastError(AppResources.Stockerror, Plugin.Toast.Abstractions.ToastLength.Long); // } // } // } //} } private async void Payment_Tapped(object sender, EventArgs e) { if (SaleProducts.Count() == 0) { CrossToastPopUp.Current.ShowToastWarning(AppResources.SelectProduct, Plugin.Toast.Abstractions.ToastLength.Long); } else { await Navigation.PushAsync(new CheckOutPage(saleproducts, Disclbl.Text,totallbl.Text,subtotallbl.Text,Payments,Products)); } } private async void Discard_Tapped(object sender, EventArgs e) { if (SaleProducts.Count() == 0) { CrossToastPopUp.Current.ShowToastWarning(AppResources.SelectProduct, Plugin.Toast.Abstractions.ToastLength.Long); } else { var action = await DisplayAlert(AppResources.Alert, AppResources.SureTodiscard, AppResources.Yes, AppResources.No); if (action) { foreach (var item in SaleProducts) { item.quantity = 0; item.total_price = 0; item.discount = 0; } SaleProducts.Clear(); Salesro.Clear(); totallbl.Text = AppResources.Zero; subtotallbl.Text = AppResources.Zero; Disclbl.Text = AppResources.Zero; cartnolbl.Text = AppResources.Zero; Salesro = new ObservableCollection<SaleProduct>(SaleProducts); SalesList.ItemsSource = Salesro; SalesListen.ItemsSource = Salesro; } } } private void delete_Clicked(object sender, EventArgs e) { if (((sender as Button).BindingContext is Product _selectedro)) { var obj = SaleProducts.Find(x => x.id == _selectedro.id); cartnolbl.Text = (int.Parse(cartnolbl.Text) - _selectedro.quantity).ToString(); subtotallbl.Text = (double.Parse(subtotallbl.Text) - _selectedro.total_price).ToString("0.00"); Disclbl.Text = (double.Parse(Disclbl.Text)- _selectedro.discount).ToString("0.00"); totallbl.Text = (double.Parse(subtotallbl.Text) - (double.Parse(Disclbl.Text))).ToString("0.00"); _selectedro.quantity = 0; _selectedro.total_price = 0; _selectedro.discount = 0; saleproducts.Remove(obj); Salesro = new ObservableCollection<SaleProduct>(SaleProducts); SalesList.ItemsSource = Salesro; SalesListen.ItemsSource = Salesro; } } private async void Discount_Tapped(object sender, EventArgs e) { if (SaleProducts.Count() == 0) { CrossToastPopUp.Current.ShowToastWarning(AppResources.SelectProduct, Plugin.Toast.Abstractions.ToastLength.Long); } else { await Navigation.PushPopupAsync(new CalculatorPage(Alldisc)); } } private async void TapGestureRecognizer_Tapped_1(object sender, EventArgs e) { if (((sender as Frame).BindingContext is Product saleproduct)) { SaleProduct sale = new SaleProduct { id = saleproduct.id, catname = saleproduct.catname, category_id = saleproduct.category_id, category2Id = saleproduct.category2Id, created_at = saleproduct.created_at, description = saleproduct.description, discount = saleproduct.discount, Enname = saleproduct.Enname, expiration_date = saleproduct.expiration_date, image = saleproduct.image, locale = saleproduct.locale, product_id = saleproduct.product_id, profit_percent = saleproduct.profit_percent, quantity = saleproduct.quantity, sale_price = saleproduct.sale_price, stock = saleproduct.stock, total_price = saleproduct.total_price, updated_at = saleproduct.updated_at, translations = saleproduct.translations, user = saleproduct.user, user_id = saleproduct.user_id, name = saleproduct.name, }; await Navigation.PushPopupAsync(new Quantitypop(sale)); } } private async void discountitem_Tapped(object sender, EventArgs e) { if (((sender as Frame).BindingContext is Product saleproduct)) { SaleProduct sale = new SaleProduct { id = saleproduct.id, catname = saleproduct.catname, category_id = saleproduct.category_id, category2Id = saleproduct.category2Id, created_at = saleproduct.created_at, description = saleproduct.description, discount = saleproduct.discount, Enname = saleproduct.Enname, expiration_date = saleproduct.expiration_date, image = saleproduct.image, locale = saleproduct.locale, product_id = saleproduct.product_id, profit_percent = saleproduct.profit_percent, quantity = saleproduct.quantity, sale_price = saleproduct.sale_price, stock = saleproduct.stock, total_price = saleproduct.total_price, updated_at = saleproduct.updated_at, translations = saleproduct.translations, user = saleproduct.user, user_id = saleproduct.user_id, name = saleproduct.name, }; await Navigation.PushPopupAsync(new CalculatorPage(sale)); } } private async void Extra_Tapped(object sender, EventArgs e) { await Navigation.PushPopupAsync(new ExtraPopupPage()); } private void Hold_Tapped(object sender, EventArgs e) { if (SaleProducts.Count() == 0) { CrossToastPopUp.Current.ShowToastWarning(AppResources.SelectProduct, Plugin.Toast.Abstractions.ToastLength.Long); } else { HoldProduct Holdsale = new HoldProduct { saleProducts = SaleProducts, created_at = DateTime.Now, total = totallbl.Text, subtotal = subtotallbl.Text, discount = Disclbl.Text, number = cartnolbl.Text }; // HoldList.Add(Holdsale); var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db"); var db = new SQLiteConnection(dbpath); var info = db.GetTableInfo("HoldProduct"); var info1 = db.GetTableInfo("SaleProduct"); if (!info.Any()&& !info1.Any()) { db.CreateTable<HoldProduct>(); db.CreateTable<SaleProduct>(); // db.InsertAll(saleproducts); db.InsertWithChildren(Holdsale); } else if (!info.Any()) { db.CreateTable<HoldProduct>(); db.InsertWithChildren(Holdsale); } else if (!info1.Any()) { db.CreateTable<SaleProduct>(); // db.InsertAll(saleproducts); db.InsertWithChildren(Holdsale); } else { db.InsertWithChildren(Holdsale); } foreach (var item in SaleProducts) { item.quantity = 0; item.total_price = 0; item.discount = 0; } SaleProducts.Clear(); Salesro.Clear(); totallbl.Text = AppResources.Zero; subtotallbl.Text = AppResources.Zero; Disclbl.Text = AppResources.Zero; cartnolbl.Text = AppResources.Zero; Salesro = new ObservableCollection<SaleProduct>(SaleProducts); SalesList.ItemsSource = Salesro; SalesListen.ItemsSource = Salesro; CrossToastPopUp.Current.ShowToastSuccess(AppResources.AddedtoHold, Plugin.Toast.Abstractions.ToastLength.Long); // await Navigation.PushAsync(new HoldListPage(HoldList)); } } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace IttezanPos.Models { public class ZugferdInvoice { } }
720091b73c88dcae14f379f2837626d53625aff7
[ "C#" ]
72
C#
Ahmed17Hamdy/IttezanPos
569e4d990fbf0678c9246f3dcde1cbc7da170bf8
fc31362dd115e4d03efe63b73f9ad0f2950bb0dd
refs/heads/master
<file_sep>import pickle import os import numpy as np import pandas as pd import tensorflow as tf tf.logging.set_verbosity(tf.logging.ERROR) from tqdm import tqdm from scipy.io import wavfile from python_speech_features import mfcc from keras.models import load_model from sklearn.metrics import accuracy_score def build_predictions(audio_dir): y_pred = [] print('Extracting features from audio') for fn in tqdm(os.listdir(audio_dir)): rate, wav = wavfile.read(os.path.join(audio_dir, fn)) y_prob = [] for i in range(0, wav.shape[0]-config.step): sample = wav[i:i+config.step] x = mfcc(sample, rate, numcep=config.nfeat, nfilt=config.nfilt, nfft=1103) x = (x - config.min) / (config.max - config.min) if x.shape[0] == 6: x = np.append(x, np.zeros([3, 13]), 0) if config.mode == 'conv': x = x.reshape(1, x.shape[0], x.shape[1], 1) elif config.mode == 'time': x = np.expand_dims(x, axis=0) y_hat = model.predict(x) y_prob.append(y_hat) y_pred.append(y_prob) return y_pred df = pd.read_csv('instruments.csv') classes = list(np.unique(df.label)) fn2class = dict(zip(df.fname, df.label)) p_path = os.path.join('pickles', 'conv.p') with open(p_path, 'rb') as handle: config = pickle.load(handle) model = load_model(config.model_path) y_pred = build_predictions('clean') print(len(y_pred), len(y_pred[0]), len(y_pred[1]))
0aca38bdf0dd4e7b8ef80143be37b272146f1330
[ "Python" ]
1
Python
frizzid07/audio_classification
2a077153c7619e23fccceb2b69116dd3cfa3aefe
f8935d44ad2498038c4c8ea584dbf22eddd39529
refs/heads/master
<repo_name>tassarion/Manipulacion_Ficheros<file_sep>/Manipulacion_Ficheros_Hernesti/src/com/manu/util/util.java package com.manu.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.StringTokenizer; public class util { /** * Este método se emplea para rellenar de blancos un vector * @param vector * @param pos_actual * @param pos_limite */ public static void ponBytesBlancos(byte [] vector, int pos_actual,int pos_limite){ for(int i = pos_actual; i < pos_limite; i++){ vector[i] = (byte) (32 & 0xff); } } public static void ajustarFichero(String fich_entrada, String fich_salida, int tamanio_ajuste, String fich_properties){ MiProperties arch_prop = new MiProperties(fich_properties); //SE COMPRUEBA SI SE HA INSTANCIADO CORRECTAMENTE EL ARCHIVO PROPERTIES if(!arch_prop.hayError()){ try { MiFichero fichero_entrada = new MiFichero(fich_entrada, MiFichero.LEC_BINARIO); MiFichero fichero_salida = new MiFichero(fich_salida, MiFichero.ESC_BINARIO); byte [] bytes = new byte[1]; byte [] buffer = new byte[tamanio_ajuste + 2]; String caracter_conv; int contador = 0; int cuenta_blancos = 0; while(fichero_entrada.dameBytes(bytes) >= 0){ //MEDIANTE & 0XFF CONVERTIMOS A DECIMAL caracter_conv = arch_prop.dameValor(String.valueOf(bytes[0] & 0xff)); //SE COMPRUEBA SI EL BYTE EXISTE EN EL PROPERTIES if(caracter_conv!=null){ //SE COMPRUEBA SI SE HA LLENADO EL BUFFER ANTES DE INTENTAR ESCRIBIR EL NUEVO CARACTER if(contador==tamanio_ajuste){ //se ha llenado el buffer. Hay que comprobar si se puede grabar en el archivo //SE COMPRUEBA QUE NO SEA UNA LINEA EN BLANCO if(cuenta_blancos == contador){ //es una linea toda de blancos //en este caso no se graba nada en el archivo, solamente se resetea los contadores contador = 0; cuenta_blancos = 0; }else{ buffer[tamanio_ajuste] = (byte) (13 & 0xff); buffer[tamanio_ajuste + 1] = (byte) (10 & 0xff); fichero_salida.escribir_fichero_b(buffer); contador = 0; cuenta_blancos = 0; //System.out.println(new String(buffer, "UTF-8")); } } //SE ANALIZA EL BYTE LEIDO if((caracter_conv.equals("13"))||(caracter_conv.equals("10"))){ //System.out.println("Salto de linea->" + caracter_conv); if(cuenta_blancos != contador){ util.ponBytesBlancos(buffer, contador, tamanio_ajuste); buffer[tamanio_ajuste] = (byte) (13 & 0xff); buffer[tamanio_ajuste + 1] = (byte) (10 & 0xff); fichero_salida.escribir_fichero_b(buffer); } contador = 0; cuenta_blancos = 0; //BUCLE PARA DESECHAR LOS SIGUIENTES 0D Y 0A. ESTO SE HACE HASTA QUE FINALICE EL ARCHIVO O SE ENCUENTRE UN ARCHIVO VALIDO while((fichero_entrada.dameBytes(bytes)>=0)&&((arch_prop.dameValor(String.valueOf(bytes[0] & 0xff))==null)||(arch_prop.dameValor(String.valueOf(bytes[0] & 0xff)).equals("10"))||(arch_prop.dameValor(String.valueOf(bytes[0] & 0xff)).equals("13")))){ //No es necesario hacer nada } caracter_conv = arch_prop.dameValor(String.valueOf(bytes[0] & 0xff)); //SE COMPRUEBA SI EL BYTE LEIDO ES DISTINTO DE 0D Y 0A PARA INFERTARLOS EN EL BUFFER -> ESTO SIGNIFICA QUE NO SE HA ALCANZADO EL FINAL DEL FICHERO if((!String.valueOf(bytes[0] & 0xff).equals("10"))&&(!String.valueOf(bytes[0] & 0xff).equals("13"))){ buffer[contador] = (byte) (Integer.parseInt(caracter_conv) & 0xff); contador = contador + 1; if(String.valueOf(bytes[0] & 0xff).equals("32")){ cuenta_blancos = cuenta_blancos + 1; } }else{ //System.out.println("No entra"); } }else{ //SI NO ES NINGUNO DE LOS CARACTERES ANTERIORES SE METE EN EL BUFFER buffer[contador] = (byte) (Integer.parseInt(caracter_conv) & 0xff); contador = contador + 1; if(String.valueOf(bytes[0] & 0xff).equals("32")){//si es un espacio en blanco se incrementa su contador cuenta_blancos = cuenta_blancos + 1; } } } } //SE HA ALCANZADO EL FINAL DE FICHERO Y HAY BYTES EN EL BUFFER QUE TIENEN QUE SER COPIADOS AL ARCHIVO if((contador > 0)&&(cuenta_blancos != contador)){ buffer[tamanio_ajuste] = (byte) (13 & 0xff); buffer[tamanio_ajuste + 1] = (byte) (10 & 0xff); util.ponBytesBlancos(buffer, contador, tamanio_ajuste); fichero_salida.escribir_fichero_b(buffer); } fichero_entrada.cerrarFichero(); fichero_salida.cerrarFichero(); } catch (FileNotFoundException e) { System.out.print("Error al abrir un fichero->" + e.getMessage()); //e.printStackTrace(); } catch (IOException e) { System.out.print("Error al abrir un fichero->" + e.getMessage()); //e.printStackTrace(); } }else{ System.out.println(arch_prop.dameMensaError()); } } /** * Quita todos los saltos de linea y retorno de carro para que esté en una sola linea * @param ficheroXML */ public static void aplanarXML(String ficheroXML){ try { File tempFile = File.createTempFile("mificherotemporal",null); tempFile.deleteOnExit(); BufferedOutputStream bufferedOutputTemp = new BufferedOutputStream(new FileOutputStream (tempFile)); MiFichero fichero_entrada = new MiFichero(ficheroXML, MiFichero.LEC_BINARIO); byte [] bytes = new byte[1]; String caracter_conv; while(fichero_entrada.dameBytes(bytes) >= 0){ caracter_conv = String.valueOf(bytes[0] & 0xff); if((caracter_conv!=null)&&(!caracter_conv.equals("10"))&&(!caracter_conv.equals("13"))){ bufferedOutputTemp.write(bytes); } } bufferedOutputTemp.close(); fichero_entrada.cerrarFichero(); BufferedInputStream bufferInput = new BufferedInputStream(new FileInputStream(tempFile)); MiFichero fichero_salida = new MiFichero(ficheroXML, MiFichero.ESC_BINARIO); while(bufferInput.read(bytes) >= 0){ fichero_salida.escribir_fichero_b(bytes); } bufferInput.close(); fichero_entrada.cerrarFichero(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Este método * @param ficheroXML */ public static void enColumnarXML(String ficheroXML){ try { File tempFile = File.createTempFile("mificherotemporal",null); tempFile.deleteOnExit(); BufferedOutputStream bufferedOutputTemp = new BufferedOutputStream(new FileOutputStream (tempFile)); MiFichero fichero_entrada = new MiFichero(ficheroXML, MiFichero.LEC_BINARIO); byte [] bytes = new byte[1]; byte [] byteSig = new byte[1]; byte [] salto = new byte[2]; salto[0] = (byte) (13 & 0xff); salto[1] = (byte) (10 & 0xff); Boolean flg_tagApert = false; Boolean prim_linea = true; String caracter_conv; while(fichero_entrada.dameBytes(bytes) >= 0){ caracter_conv = String.valueOf(bytes[0] & 0xff); if((caracter_conv!=null)&&(!caracter_conv.equals("10"))&&(!caracter_conv.equals("13"))){ //APERTURA DE ETIQUETA if(caracter_conv.equals("60")){ //SE LEE EL SIGUIENTE BYTE fichero_entrada.dameBytes(byteSig); if(!String.valueOf(byteSig[0] & 0xff).equals("47")){ //SI EL SEGUNDO BYTE NO ES UN SLASH SE HACE EL SALTO DE LINEA if(!prim_linea){ bufferedOutputTemp.write(salto); }else{ prim_linea = false; } flg_tagApert = true;//SE INDICA QUE SE HA PUESTO UNA ETIQUETA DE APERTURA }else{ if(flg_tagApert){ flg_tagApert = false;//LA SIGUIENTE ETIQUETA DE APERTURA TENDRÁ SALTO }else{ bufferedOutputTemp.write(salto); } } } bufferedOutputTemp.write(bytes); if((String.valueOf(byteSig[0] & 0xff)!=null)&&(caracter_conv.equals("60"))){ bufferedOutputTemp.write(byteSig); } } } bufferedOutputTemp.close(); fichero_entrada.cerrarFichero(); BufferedInputStream bufferInput = new BufferedInputStream(new FileInputStream(tempFile)); BufferedOutputStream bufferedOutput = new BufferedOutputStream(new FileOutputStream(ficheroXML)); while(bufferInput.read(bytes) >= 0){ bufferedOutput.write(bytes); } bufferInput.close(); bufferedOutput.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void repararEtiquetas(String ficheroXML){ StringTokenizer tokens = null; String cadenaToken; String etiqueta; Integer posTag = null; byte [] bytes = new byte[1]; try { File tempFile = File.createTempFile("mificherotemporal",null); //tempFile.deleteOnExit(); BufferedWriter ficheroTemp = new BufferedWriter(new FileWriter (tempFile)); MiFichero fichero_entrada = new MiFichero(ficheroXML, MiFichero.LEC_TEXTO); String linea = null; String linea_resultado = null; Integer contador = 0; while((linea = fichero_entrada.dameLineaTxt())!=null){ linea_resultado = ""; tokens = new StringTokenizer(linea, ">",true); while(tokens.hasMoreTokens()){ cadenaToken = tokens.nextToken().trim()+">"; //BUSCAR LA POSICION DONDE EMPIEZA LA POSIBLE ETIQUETA. //PUEDE HABER SOLO UNA ETIQUETA O UNA ETIQUETA Y TEXTO posTag = cadenaToken.indexOf("<"); if(posTag!=-1){ etiqueta = cadenaToken.substring(posTag);//CONTIENE UNA ETIQUETA if(posTag != 0){//PRIEMRO VIENE EL TEXTO DE LA ETIQUETA //DESPUES DE LA ETIQUETA HAY TEXTO //NO ES UNA ETIQUETA Y LA DEVOLVEMOS QUITANDO EL EXCESO DE ESPACIOS EN BLANCO linea_resultado = linea_resultado + cadenaToken.substring(0, posTag).replaceAll(" +", " ").trim(); } linea_resultado = linea_resultado + verificaTag(etiqueta); } } //HAY QUE ASEGURARSE DE QUE NO SE INTENTA ESCRIBIR UN NULL EN EL FICHERO if(linea_resultado!=null){ contador = contador + 1; ficheroTemp.write(linea_resultado+"\n"); } } ficheroTemp.close(); fichero_entrada.cerrarFichero(); BufferedInputStream bufferInput = new BufferedInputStream(new FileInputStream(tempFile)); BufferedOutputStream bufferedOutput = new BufferedOutputStream(new FileOutputStream(ficheroXML)); while(bufferInput.read(bytes) >= 0){ bufferedOutput.write(bytes); } bufferInput.close(); bufferedOutput.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static String verificaTag(String tag){ String resultado = ""; if(tag.substring(0, 1).equals("<")){ if(tag.indexOf("=")==-1){ //LA ETIQUETA NO TIENE ATRIBUTOS, SOLO HAY QUE ELIMINAR TODOS LOS ESPACIOS resultado = tag.replaceAll(" ",""); }else if((tag.indexOf("?")==-1)&&(!tag.substring(1,9).equals("Document"))){ //LA ETIQUETA TIENE AL MENOS UN ATRIBUTO resultado = "<InstdAmt Ccy="+tag.substring(tag.indexOf("\""), tag.lastIndexOf("\"")) +"\">"; }else{ resultado = tag; } }else{ //NO ES UNA ETIQUETA Y LA DEVOLVEMOS QUITANDO EL EXCESO DE ESPACIOS EN BLANCO resultado = tag.replaceAll(" +", " ");//SI HAY MÁS DE UN ESPACIO SEGUIDO SE ELIMINA } return resultado.trim();//LE QUITAMOS LOS ESPACIOS DE LOS EXTREMOS } public static void copiarFicheTxt(String nombre_entrada, String nombre_salida) throws IOException{ byte [] bytes = new byte[1]; BufferedInputStream bufferInput = new BufferedInputStream(new FileInputStream(nombre_entrada)); MiFichero fichero_salida = new MiFichero(nombre_salida, MiFichero.ESC_BINARIO); while(bufferInput.read(bytes) >= 0){ fichero_salida.escribir_fichero_b(bytes); } bufferInput.close(); fichero_salida.cerrarFichero(); } } <file_sep>/Manipulacion_Ficheros_Hernesti/src/com/manu/util/MiProperties.java package com.manu.util; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; public class MiProperties { private Properties archivoProp; private Boolean error; private String mensa_error; /** * Constructor de la clase. instancia el objeto y lo abre. En caso de que se produzca un error en la apertura * quedará reflejado en el atributo error y se guardará el mensaje en el atributo mensa_error. * @param ruta_nombre * @param error */ public MiProperties(String ruta_nombre){ this.error = false; this.archivoProp = new Properties(); try { this.archivoProp.load(new FileInputStream(ruta_nombre)); } catch (FileNotFoundException e) { this.error = true; mensa_error = "Error archivo Properties->" + e.getMessage(); //e.printStackTrace(); } catch (IOException e) { this.error = true; mensa_error = "Error archivo Properties->" + e.getMessage(); //e.printStackTrace(); } } /** * Devuelve el valor de la clave buscada * @param clave * @return */ public String dameValor(String clave){ return this.archivoProp.getProperty(clave); } /** * Indica si hay o no error * @return */ public Boolean hayError(){ return this.error; } /** * Devuelve el mensaje de error en caso de que se haya producido. * @return */ public String dameMensaError(){ return this.mensa_error; } } <file_sep>/Manipulacion_Ficheros_Hernesti/src/com/manu/util/XMLElementos.java package com.manu.util; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; /** * Esta clase sirve para crear de forma estática un XML y sus componentes, nodo raiz, nodos, texto de nodos y atributos de nodos. * @author <NAME> * */ public class XMLElementos { /** * Crea un documento XML. Para poder añadir un nodo antes debe existir el documento y el nodo raiz. * @return */ public static Document creaDocumento(){ return DocumentHelper.createDocument(); } /** * Crea el nodo raiz del documento. El nodo raiz debe existir y tiene que ser único. A partir de él cuelga el resto de los nodos por lo que ha de crearse antes de poder añadir los nodos. * @param documento * @param raiz * @return */ public static Element creaRaiz(Document documento, String raiz){ return documento.addElement(raiz); } /** * Crea un nodo * @param nombreNodo * @return */ public static Element crearNodo(String nombreNodo){ Document documento = DocumentHelper.createDocument(); return documento.addElement(nombreNodo); } /** * Crea un atributo en un nodo. * @param nodo * @param clave * @param valor */ public static void creaAtributo(Element nodo, String clave, String valor){ nodo.addAttribute(clave, valor); } /** * Crea el texto en un nodo. * @param nodo * @param texto */ public static void creaTexto(Element nodo, String texto){ nodo.addText(texto); } /** * Enlaza dos nodos, uno será el padre y el otro, el que cuelga de él será el hijo. * @param nodoPadre * @param nodoHijo */ public static void aniadeHijoAPadre(Element nodoPadre, Element nodoHijo){ nodoPadre.add(nodoHijo); } }
f83d387a78360abfa38c763a6b3b29d09e1cddd1
[ "Java" ]
3
Java
tassarion/Manipulacion_Ficheros
d247e074e83e7f2774d49d507830630fe20f68f0
061c6cc5cec9aa3c4b044c1d9bafd8b9c147b865
refs/heads/master
<repo_name>VanDalkvist/hexlet-practice<file_sep>/inverted-register/invert-case.test.js const tape = require('tape'); const invertCase = require('./invert-case'); tape('minimal diff', test => { test.equal(invertCase("HeLLo"), "hEllO"); test.equal(invertCase("Hello World!"), "hELLO wORLD!"); test.end(); });<file_sep>/auto-test-runner.js const fs = require('fs'); const path = require('path'); const { exec } = require('child_process'); const debounce = require('debounce'); let [node, command, fileName, reporter, ...rest] = process.argv; console.debug('defaults : ', node, command, fileName, reporter, rest); reporter = reporter || 'tap-dot'; console.info('command : ', node, command, fileName, reporter, rest); if (!fileName) { throw new Error("You must specify a file name or directory."); } const exceptions = ['.idea', 'auto-test-runner', 'package', '.git']; let hash = {}; fs.watch(fileName, {}, (eventType, name) => { console.debug(eventType, name); if (eventType !== 'change') return; if (exceptions.find((e) => name.includes(e))) return; let execute = hash[name]; if (execute) { execute(); return; } hash[name] = debounce(_runTests.bind(null, name), 500); hash[name](); }); function _runTests(name) { let tests = path.join(name, '**', '*.test.js'); let reporterPath = path.join('node_modules', '.bin', reporter); let tapePath = path.join('node_modules', '.bin', 'tape'); let command = `${tapePath} ${tests} | ${reporterPath}`; console.log(`[${name}] running command: ${command}\n`); exec(command, (error, stdout, stderr) => { if (error) { console.error(`failed: ${error}`); } console.info(`stdout [${name}]: ${stdout}`); console.error(`stderr [${name}]: ${stderr}`); }); }<file_sep>/formatted-time/formatted-time.test.js const tape = require('tape'); const formattedTime = require('./formatted-time'); tape('formatted-time', function (test) { test.equals(formattedTime(5), '00:05'); test.equals(formattedTime(15), '00:15'); test.equals(formattedTime(60), '01:00'); test.equals(formattedTime(67), '01:07'); test.equals(formattedTime(175), '02:55'); test.equals(formattedTime(600), '10:00'); test.equals(formattedTime(754), '12:34'); test.end(); });<file_sep>/fizz-buzz/fizz-buzz.js module.exports = function* _fizzBuzz(start, end) { if (end - start < 0) { throw new Error('Invalid range.'); } const arr = Array.from(new Array(end - start + 1).keys()).map(el => el + start); for (let value of arr) { let isThreeDividend = value % 3 === 0; let isFiveDividend = value % 5 === 0; if (isThreeDividend && isFiveDividend) { yield 'FizzBuzz'; } else if (isThreeDividend) { yield 'Fizz'; } else if (isFiveDividend) { yield 'Buzz'; } else { yield value; } } };<file_sep>/without-two-zeros/without-two-zeros.js module.exports = function withoutTwoZeros(zeroCount, oneCount) { if (oneCount === 1) return 0; const count = zeroCount + oneCount; if (zeroCount === 1 || zeroCount === 0) { return _combinations(count, zeroCount); } const combinationCount = _combinations(count, 2); console.error(combinationCount); return combinationCount - (count - 1); }; function _combinations(n, k) { return _factorial(n) / (_factorial(k) * _factorial(n - k)); } function _factorial(n) { if (n === 0) return 1; function _iteration(n, acc) { if (n === 1) return acc; return _iteration(n - 1, n * acc); } return _iteration(n, 1); }<file_sep>/is-power-of-three/is-power-of-three.test.js const tape = require('tape'); const isPowerOfThree = require('./is-power-of-three'); tape('is-power-of-three', function (test) { test.equals(isPowerOfThree(1), true); test.equals(isPowerOfThree(2), false); test.equals(isPowerOfThree(9), true); test.end(); });<file_sep>/sum-square-difference/sum-square-difference.test.js const tape = require('tape'); const { diff } = require('./sum-square-difference'); tape('diff of sums', test => { test.equals(diff(3), (1 + 2 + 3) ** 2 - (1 + 2 ** 2 + 3 ** 2)); test.equals(diff(10), 2640); test.end(); });<file_sep>/is-happy-ticket/is-happy-ticket.js module.exports = function _isHappyTicket(ticket) { const number = ticket.toString(); if (number.length !== 6) { return false; } const first = number.substring(0, 3); const second = number.substring(3, 6); const firstSum = _digitsSum(first); const secondSum = _digitsSum(second); return firstSum === secondSum; }; function _digitsSum(number) { return Array.from(number.toString()).reduce((sum, digit) => sum + parseInt(digit), 0); }<file_sep>/is-happy-number/is-happy-number.test.js const tape = require('tape'); const isHappy = require('./is-happy-number'); tape('sum of square digits', function (test) { test.equals(isHappy(1), true); test.equals(isHappy(7), true); test.equals(isHappy(13), true); test.equals(isHappy(0), false); test.equals(isHappy(2), false); test.equals(isHappy(90), false); test.end(); });<file_sep>/test-tasks/ratings.js // https://github.com/tutu-ru/frontend-javascript-test Задача 2 function drawRating(vote) { if (vote >= 0 && vote <= 20) { return '★☆☆☆☆'; } else if (vote > 20 && vote <= 40) { return '★★☆☆☆'; } else if (vote > 40 && vote <= 60) { return '★★★☆☆'; } else if (vote > 60 && vote <= 80) { return '★★★★☆'; } else if (vote > 80 && vote <= 100) { return '★★★★★'; } } const rules = [ (vote) => vote >= 0 && vote <= 20 && '★☆☆☆☆', (vote) => vote > 20 && vote <= 40 && '★★☆☆☆', (vote) => vote > 40 && vote <= 60 && '★★★☆☆', (vote) => vote > 60 && vote <= 80 && '★★★★☆', (vote) => vote > 80 && vote <= 100 && '★★★★★', ]; function drawRatingWithFind(vote) { const rule = rules.find(rule => rule(vote)); return rule(vote); } function drawRatingWithReduce(vote) { return rules.reduce((prev, rule) => prev || rule(vote), false); } console.log(drawRating(0) ); // ★☆☆☆☆ console.log(drawRating(1) ); // ★☆☆☆☆ console.log(drawRating(50)); // ★★★☆☆ console.log(drawRating(99)); // ★★★★★ console.log(drawRatingWithFind(0) ); // ★☆☆☆☆ console.log(drawRatingWithFind(1) ); // ★☆☆☆☆ console.log(drawRatingWithFind(50)); // ★★★☆☆ console.log(drawRatingWithFind(99)); // ★★★★★ console.log(drawRatingWithReduce(0) ); // ★☆☆☆☆ console.log(drawRatingWithReduce(1) ); // ★☆☆☆☆ console.log(drawRatingWithReduce(50)); // ★★★☆☆ console.log(drawRatingWithReduce(99)); // ★★★★★<file_sep>/fizz-buzz/fizz-buzz.test.js const tape = require('tape'); const fizzBuzz = require('./fizz-buzz'); tape('fizz-buzz', function (test) { let gen = fizzBuzz(11, 20); test.equals(gen.next().value, 11); test.equals(gen.next().value, 'Fizz'); test.equals(gen.next().value, 13); test.equals(gen.next().value, 14); test.equals(gen.next().value, 'FizzBuzz'); test.equals(gen.next().value, 16); test.equals(gen.next().value, 17); test.equals(gen.next().value, 'Fizz'); test.equals(gen.next().value, 19); test.equals(gen.next().value, 'Buzz'); test.end(); });<file_sep>/is-happy-ticket/is-happy-ticket.test.js const tape = require('tape'); const isHappyTicket = require('./is-happy-ticket'); tape('is-happy-ticket', function (test) { test.equals(isHappyTicket(385916), true); test.equals(isHappyTicket(231002), false); test.equals(isHappyTicket(128722), true); test.equals(isHappyTicket('054702'), true); test.throws(() => isHappyTicket('54702')); test.end(); });<file_sep>/angles-difference/diff.js module.exports = function _diff(angle1, angle2) { const diff = Math.abs(angle1 - angle2); const oppositeDiff = 360 - diff; return diff < oppositeDiff ? diff : oppositeDiff; };<file_sep>/angles-difference/diff.test.js var tape = require('tape'); var diff = require('./diff'); tape('minimal diff', function (test) { test.equal(diff(0, 45), 45); test.equal(diff(0, 180), 180); test.equal(diff(0, 190), 170); test.equal(diff(120, 280), 160); test.end(); });<file_sep>/ackermann/ackermann.test.js const tape = require('tape'); const ackermann = require('./ackermann'); tape('ackermann', function (test) { test.equals(ackermann(0, 0), 1); test.equals(ackermann(2, 1), 5); test.equals(ackermann(2, 3), 9); test.end(); });<file_sep>/inverted-register/invert-case.js module.exports = function _invert(string) { return [...string].map(function (char) { return char.toLowerCase() === char ? char.toUpperCase() : char.toLowerCase(); }).join(''); };<file_sep>/reverse/reverse.test.js const tape = require('tape'); const reverse = require('./reverse'); tape('reverse', function (test) { test.equals(reverse('hell'), 'lleh'); test.end(); });<file_sep>/reverse-int/reverse-int.js let reverse = require('../reverse/reverse'); module.exports = function _reverseInt(number) { return Math.sign(number) * parseInt(reverse(Math.abs(number).toString())); };<file_sep>/reverse-int/reverse-int.test.js const tape = require('tape'); const reverseInt = require('./reverse-int'); tape('reverse-int', function (test) { test.equals(reverseInt(321), 123); test.equals(reverseInt(-123), -321); test.end(); });
047c0e05b977b825fd7455e69c989c544981e3f4
[ "JavaScript" ]
19
JavaScript
VanDalkvist/hexlet-practice
bce07bb1029fe68eaed84e75a25161d26423641d
a9730bf31e94e3e4aaa03097ae1b571972ea5b7e
refs/heads/master
<file_sep>import java.sql.Array; import java.sql.Connection; import java.sql.DriverManager; import java.util.ArrayList; public class testResultSet { public static void main(String[]args) throws Exception{ ArrayList<ArrayList<String> > rows = new ArrayList<ArrayList<String> >(); String tablename = "hamada" ; ArrayList<String > columnames = new ArrayList <String>() ; ArrayList <String > columntypes = new ArrayList < String>() ; // ResultSetIM res = new ResultSetIM(rows , columnames , columntypes , s , tablename ) ; StatementIm s = new StatementIm ("hamada",new ConnectionIM ("hamada") ) ; ResultSetIM res = (ResultSetIM) s.executeQuery("select * from Persons"); res.absolute(0); while(res.next()){ System.out.println(res.getInt(0)); System.out.println(res.getString(1)); System.out.println(res.getString(2)); System.out.println(res.getString(3)); System.out.println(res.getString(4)); System.out.println(res.getFloat(5)); // System.out.println(res.getArray(6)); System.out.println("****************************************"); } } } <file_sep> public class Condition { private String name, operator, value; public Condition(String name, String operator, String value) { this.name = name; this.operator = operator; this.value = value; } public String getColName() { return name; } public String getOperator() { return operator; } public String getValue() { return value; } } <file_sep>import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import org.apache.log4j.Logger; public class Schema { private Logger log = Logger.getLogger(Schema.class.getName()); public void schemaCreating(ArrayList<Column> columns, String tablepath, String tablename, String rowname) { try { File myFile = new File(tablepath); myFile.createNewFile(); FileWriter write = new FileWriter(tablepath); write.write("<?xml version=\"1.0\"?>\n"); write.write("<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n"); write.write("<xs:element name=" + "\"" + tablename + "\">\n"); write.write("\t<xs:complexType>\n"); write.write("\t\t<xs:sequence>\n"); write.write("\t\t\t<xs:element name=" + "\"" + rowname + "\">\n"); write.write("\t\t\t\t<xs:complexType>\n"); write.write("\t\t\t\t\t<xs:sequence>\n"); for (int i = 0; i < columns.size(); i++) { write.write("\t\t\t\t\t\t<xs:element name=" + "\"" + columns.get(i).getColName() + "\"" + " type=\"xs:" + columns.get(i).getdataType().toLowerCase() + "\"/>\n"); } write.write("\t\t\t\t\t</xs:sequence>\n"); write.write("\t\t\t\t</xs:complexType>\n"); write.write("\t\t\t</xs:element>\n"); write.write("\t\t</xs:sequence>\n"); write.write("\t</xs:complexType>\n"); write.write("</xs:element>\n"); write.flush(); write.close(); } catch (Exception e) { log.error(e.getMessage()); } } public ArrayList<Column> schemaParsing(String tablepath) { ArrayList<Column> ret = new ArrayList<Column>(); try { File myFile = new File(tablepath); FileReader read = new FileReader(myFile); BufferedReader br = new BufferedReader(read); int counter = 0; while (br.ready()) { String line = br.readLine(); counter++; if (counter < 9) { continue; } if (line.contains("sequence")) { break; } // processing line = line.trim(); String[] nametype = line.split("\\\""); String name = nametype[1]; String type = nametype[3].substring(3); if (type.contains("(")) { Column temp = new Column(name, type.split("\\(")[0], Integer.parseInt(type.split("\\(")[1].replaceAll( "\\)", ""))); ret.add(temp); } else { Column temp = new Column(name, type, 0); ret.add(temp); } } br.close(); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } return ret; } } <file_sep>import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.sql.*; import java.util.ArrayList; import java.util.Calendar; import java.util.Map; import org.apache.log4j.Logger; public class ResultSetIM implements ResultSet { public ArrayList<ArrayList<String>> rows = null; public ArrayList<String> columnNames = null; public ArrayList<String> columnTypes = null; private String tablename; private Logger log = Logger.getLogger(ResultSetIM.class.getName()); boolean closed = false; int pointer = 0; // indicating that it points to a null place private ConnectionIM con; private Statement statement; // the first row index is one not zero public ResultSetIM(ArrayList<ArrayList<String>> rows, ArrayList<String> columnNames, ArrayList<String> columnTypes, Statement statement, String table) { this.rows = rows; this.columnNames = columnNames; this.columnTypes = columnTypes; this.statement = statement; this.tablename = table; } public int getSize() { return this.columnNames.size(); } @Override public boolean absolute(int row) throws SQLException { if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } if (rows.size() == 0) { return false; // need to check } if (row < 0) { row *= -1; if (row > rows.size()) { pointer = 0; } else { pointer = rows.size() - row + 1; } } else if (row > 0) { if (row > rows.size()) { pointer = rows.size() + 1; // indicating after last } else { pointer = row; } } else if (row == 0) { pointer = row; // indicating before first } if (pointer > 0 && pointer <= rows.size()) { return true; } else { return false; } } @Override public void afterLast() throws SQLException { if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } if (rows.size() == 0) { return; } pointer = rows.size() + 1; } @Override public void beforeFirst() throws SQLException { if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } if (rows.size() == 0) { return; } pointer = 0; } @Override public void close() throws SQLException { if (closed) return; closed = true; pointer = 0; columnNames = null; columnTypes = null; rows = null; statement.close(); } @Override public int findColumn(String columnLabel) throws SQLException { if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } int index = -1; for (int i = 0; i < columnNames.size(); i++) { if (columnNames.get(i).equals(columnLabel)) { index = i; return index; } } log.error("Column Not Found"); throw new SQLException("Column Not Found"); } @Override public boolean first() throws SQLException { if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } if (rows.size() == 0) { return false; } else { absolute(1); return true; } } @Override public Array getArray(int columnIndex) throws SQLException { if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } if (columnIndex < 0 || columnIndex >= this.columnNames.size()) { log.error("Column Index Out OF Range"); throw new SQLException("Column Index Out OF Range"); } if (pointer - 1 < 0 || pointer - 1 >= rows.size() || rows.get(pointer - 1).get(columnIndex).isEmpty()) { log.error("ResultSet pointer undefined"); throw new SQLException("ResultSet pointer undefined"); } if (rows.get(pointer - 1).get(columnIndex).equals("null")) return null; String type = columnTypes.get(columnIndex).split(" ")[0]; array arr = new array(rows.get(pointer - 1).get(columnIndex), type); return arr; } @Override public Array getArray(String columnLabel) throws SQLException { return getArray(findColumn(columnLabel)); } /* * (non-Javadoc) * * Retrieves the value of the designated column in the current row of this * ResultSet object as a boolean in the Java programming language. If the * designated column has a datatype of CHAR or VARCHAR and contains a "0" or * has a datatype of BIT, TINYINT, SMALLINT, INTEGER or BIGINT and contains * a 0, a value of false is returned. If the designated column has a * datatype of CHAR or VARCHAR and contains a "1" or has a datatype of BIT, * TINYINT, SMALLINT, INTEGER or BIGINT and contains a 1, a value of true is * returned */ @Override public boolean getBoolean(int columnIndex) throws SQLException { // this method is called on a closed result set if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } // columnIndex not valid if (columnIndex < 0 || columnIndex >= this.columnNames.size()) { log.error("Column Index Out OF Range"); throw new SQLException("Column Index Out OF Range"); } if (columnTypes.get(columnIndex).toLowerCase().equals("char") || columnTypes.get(columnIndex).toLowerCase().equals("varchar") || columnTypes.get(columnIndex).toLowerCase().equals("bit") || columnTypes.get(columnIndex).toLowerCase().equals("tinyint") || columnTypes.get(columnIndex).toLowerCase() .equals("smallint") || columnTypes.get(columnIndex).toLowerCase().equals("integer") || columnTypes.get(columnIndex).toLowerCase().equals("bigint")) { String s = getString(columnIndex); if (s != null && s.equals("0")) { return false; } else if (s != null && s.equals("1")) { return true; } } return false; } @Override public boolean getBoolean(String columnLabel) throws SQLException { // TODO Auto-generated method stub return getBoolean(findColumn(columnLabel)); } /* * * (non-Javadoc) * * @see java.sql.ResultSet#getDate(int) * * Retrieves the value of the designated column in the current row of this * ResultSet object as a java.sql.Date object in the Java programming * language. */ @Override public Date getDate(int columnIndex) throws SQLException { // this method is called on a closed result set if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } // columnIndex not valid if (columnIndex < 0 || columnIndex >= columnNames.size()) { log.error("Column Index Out OF Range"); throw new SQLException("Column Index Out OF Range"); } return null; } @Override public Date getDate(String columnLabel) throws SQLException { // TODO Auto-generated method stub return getDate(findColumn(columnLabel)); } @Override public Date getDate(int columnIndex, Calendar cal) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Date getDate(String columnLabel, Calendar cal) throws SQLException { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) Retrieves the value of the designated column in the current * row of this ResultSet object as a double in the Java programming language */ @Override public double getDouble(int columnIndex) throws SQLException { // this method is called on a closed result set if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } // columnIndex not valid if (columnIndex < 0 || columnIndex >= columnNames.size()) { log.error("Column Index Out OF Range"); throw new SQLException("Column Index Out OF Range"); } String S = getString(columnIndex); if (S != null) { if (S.length() == 0) { return 0; } try { return Double.valueOf(S).doubleValue(); } catch (NumberFormatException E) { log.error("Bad Format For Double" + S + "' in column " + columnIndex + "(" + columnNames.get(columnIndex) + ")."); throw new java.sql.SQLException("Bad Format For Double" + S + "' in column " + columnIndex + "(" + columnNames.get(columnIndex) + ")."); } } return 0; } @Override public double getDouble(String columnLabel) throws SQLException { // TODO Auto-generated method stub return getDouble(findColumn(columnLabel)); } /* * (non-Javadoc) * * @see java.sql.ResultSet#getFetchDirection() * * Retrieves the fetch direction for this ResultSet object. */ @Override public int getFetchDirection() throws SQLException { // TODO Auto-generated method stub return this.FETCH_UNKNOWN; } /* * (non-Javadoc) * * @see java.sql.ResultSet#getFloat(int) * * Retrieves the value of the designated column in the current row of this * ResultSet object as a float in the Java programming language. */ @Override public float getFloat(int columnIndex) throws SQLException { // this method is called on a closed result set if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } // columnIndex not valid if (columnIndex < 0 || columnIndex >= columnNames.size()) { log.error("Column Index Out OF Range"); throw new SQLException("Column Index Out OF Range"); } String S = getString(columnIndex); if (S != null) { if (S.length() == 0) { return 0; } try { return Float.valueOf(S).floatValue(); } catch (NumberFormatException E) { log.error("Bad Format For Float " + S + " in column " + columnIndex + "(" + columnNames.get(columnIndex) + ")."); throw new java.sql.SQLException("Bad Format For Float " + S + " in column " + columnIndex + "(" + columnNames.get(columnIndex) + ")."); } } return 0; } @Override public float getFloat(String columnLabel) throws SQLException { // TODO Auto-generated method stub return getFloat(findColumn(columnLabel)); } /* * (non-Javadoc) * * @see java.sql.ResultSet#getInt(int) * * Retrieves the value of the designated column in the current row of this * ResultSet object as an int in the Java programming language. */ @Override public int getInt(int columnIndex) throws SQLException { // this method is called on a closed result set if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } // columnIndex not valid if (columnIndex < 0 || columnIndex >= columnNames.size()) { log.error("Column Index Out OF Range"); throw new SQLException("Column Index Out OF Range"); } String S = getString(columnIndex); if (S != null) { if (S.length() == 0) { return 0; } try { return Integer.parseInt(S); } catch (NumberFormatException E) { log.error("Bad Integer Format" + S + "' in column" + columnIndex + "(" + columnNames.get(columnIndex) + ")."); throw new java.sql.SQLException("Bad Integer Format" + S + "' in column" + columnIndex + "(" + columnNames.get(columnIndex) + ")."); } } return 0; } @Override public int getInt(String columnLabel) throws SQLException { // TODO Auto-generated method stub return getInt(findColumn(columnLabel)); } /* * (non-Javadoc) * * @see java.sql.ResultSet#getLong(java.lang.String) Retrieves the value of * the designated column in the current row of this ResultSet object as a * long in the Java programming language. */ @Override public long getLong(int columnIndex) throws SQLException { // this method is called on a closed result set if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } // columnIndex not valid if (columnIndex < 0 || columnIndex >= columnNames.size()) { log.error("Column Index Out OF Range"); throw new SQLException("Column Index Out OF Range"); } String s = getString(columnIndex); if (s != null) { if (s.length() == 0) return 0; try { return Long.parseLong(s); } catch (NumberFormatException E) { log.error("Bad Long Format" + s + "' in column" + columnIndex + "(" + columnNames.get(columnIndex) + ")."); throw new java.sql.SQLException("Bad Long Format" + s + "' in column" + columnIndex + "(" + columnNames.get(columnIndex) + ")."); } } return 0; } @Override public long getLong(String columnLabel) throws SQLException { // TODO Auto-generated method stub return getLong(findColumn(columnLabel)); } /* * (non-Javadoc) * * @see java.sql.ResultSet#getMetaData() * * Retrieves the number, types and properties of this ResultSet object's * columns. */ @Override public ResultSetMetaData getMetaData() throws SQLException { // this method is called on a closed result set if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } return new ResultSetMetaDataIM(columnNames, columnTypes, tablename); } /* * (non-Javadoc) * * @see java.sql.ResultSet#getObject(int) Gets the value of the designated * column in the current row of this ResultSet object as an Object in the * Java programming language. * * This method will return the value of the given column as a Java object. * The type of the Java object will be the default Java object type * corresponding to the column's SQL type, following the mapping for * built-in types specified in the JDBC specification. If the value is an * SQL NULL, the driver returns a Java null. */ @Override public Object getObject(int columnIndex) throws SQLException { // this method is called on a closed result set if (closed) { log.error("Accsess Closed ResultSet"); throw new SQLException("Accsess Closed ResultSet"); } // columnIndex not valid if (columnIndex < 0 || columnIndex >= this.columnNames.size()) { log.error("Column Index Out OF Range"); System.out.println(); throw new SQLException("Column Index Out OF Range"); } if (pointer - 1 < 0 ) { log.error("ResultSet pointer undefined"); System.out.println(); throw new SQLException("ResultSet pointer undefined"); } if (rows.get(pointer - 1).get(columnIndex).equals("null")) return "null"; if (columnTypes .get(columnIndex) .toLowerCase() .matches("(integer|varchar[0-9]*)\\ +array\\ *\\[[0-9]+\\]\\ *")) return getArray(columnIndex); switch (columnTypes.get(columnIndex).toLowerCase()) { case "bit": return new Boolean(getBoolean(columnIndex)); case "tinyint": case "smallint": case "integer": case "int": return new Integer(getInt(columnIndex)); case "long": case "bigint": return new Long(getLong(columnIndex)); case "real": case "float": return new Float(getFloat(columnIndex)); case "double": return new Double(getDouble(columnIndex)); case "char": case "varchar": case "longvarchar": return getString(columnIndex); case "date": return getDate(columnIndex); default: { throw new SQLException("Undefined Data Type"); } } } @Override public Object getObject(String columnLabel) throws SQLException { // TODO Auto-generated method stub return getObject(findColumn(columnLabel)); } /* * (non-Javadoc) * * @see java.sql.ResultSet#getStatement() Retrieves the Statement object * that produced this ResultSet object. If the result set was generated some * other way, such as by a DatabaseMetaData method, this method may return * null */ @Override public Statement getStatement() throws SQLException { if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } return statement; } /* * (non-Javadoc) * * @see java.sql.ResultSet#getString(int) Retrieves the value of the * designated column in the current row of this ResultSet object as a String * in the Java programming language. */ @Override public String getString(int columnIndex) throws SQLException { if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } if (rows == null) { log.error("No ResultSet Generated"); throw new SQLException("No ResultSet Generated"); }// this method is called on a closed result set // columnIndex not valid if (columnIndex < 0 || columnIndex >= columnNames.size()) { log.error("Column Index Out OF Range"); throw new SQLException("Column Index Out OF Range"); } if (pointer == -1 || pointer == 0 || pointer == rows.size() + 1) { log.error("Index Out Of bounds"); throw new SQLException("Index Out Of bounds"); } return new String(rows.get(pointer - 1).get(columnIndex)); } @Override public String getString(String columnLabel) throws SQLException { return getString(findColumn(columnLabel)); } @Override public boolean isAfterLast() throws SQLException { if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } if (rows.size() == 0) { return false; } return (pointer == rows.size() + 1); } @Override public boolean isBeforeFirst() throws SQLException { if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } if (rows.size() == 0) { return false; } return (pointer == 0); } @Override public boolean isClosed() throws SQLException { return closed; } @Override public boolean isFirst() throws SQLException { if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } if (rows.size() == 0) { return false; } return (pointer == 1); } @Override public boolean isLast() throws SQLException { if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } if (rows.size() == 0) { return false; } return (pointer == rows.size()); } @Override public boolean last() throws SQLException { if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } if (rows.size() == 0) { return false; } else { pointer = rows.size(); return true; } } @Override public boolean next() throws SQLException { if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } else if (rows.size() == 0) { return false; } else if (pointer == rows.size()) { pointer++; return false; } else if (pointer == rows.size() + 1) { return false; } else { pointer++; return true; } } @Override public boolean previous() throws SQLException { if (closed) { log.error("Accessing Closed ResultSet"); throw new SQLException("Accessing Closed ResultSet"); } else if (rows.size() == 0) { return false; } else if (pointer == 1) { pointer--; return false; } else if (pointer == 0) { return false; } else { pointer--; return true; } } // no need to implement these methods @Override public void moveToCurrentRow() throws SQLException { } @Override public void moveToInsertRow() throws SQLException { // TODO Auto-generated method stub } @Override public void refreshRow() throws SQLException { // TODO Auto-generated method stub } @Override public boolean relative(int rows) throws SQLException { // TODO Auto-generated method stub return false; } @Override public boolean rowDeleted() throws SQLException { // TODO Auto-generated method stub return false; } @Override public boolean rowInserted() throws SQLException { // TODO Auto-generated method stub return false; } @Override public boolean rowUpdated() throws SQLException { // TODO Auto-generated method stub return false; } @Override public void updateArray(int columnIndex, Array x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateArray(String columnLabel, Array x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateAsciiStream(int columnIndex, InputStream x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateAsciiStream(String columnLabel, InputStream x, int length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateAsciiStream(int columnIndex, InputStream x, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateAsciiStream(String columnLabel, InputStream x, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBigDecimal(String columnLabel, BigDecimal x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBinaryStream(int columnIndex, InputStream x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBinaryStream(String columnLabel, InputStream x, int length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBinaryStream(int columnIndex, InputStream x, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBinaryStream(String columnLabel, InputStream x, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBlob(int columnIndex, Blob x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBlob(String columnLabel, Blob x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBlob(String columnLabel, InputStream inputStream, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBoolean(int columnIndex, boolean x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBoolean(String columnLabel, boolean x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateByte(int columnIndex, byte x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateByte(String columnLabel, byte x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBytes(int columnIndex, byte[] x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateBytes(String columnLabel, byte[] x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateCharacterStream(int columnIndex, Reader x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException { // TODO Auto-generated method stub } @Override public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateCharacterStream(String columnLabel, Reader reader, int length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateClob(int columnIndex, Clob x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateClob(String columnLabel, Clob x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateClob(int columnIndex, Reader reader) throws SQLException { // TODO Auto-generated method stub } @Override public void updateClob(String columnLabel, Reader reader) throws SQLException { // TODO Auto-generated method stub } @Override public void updateClob(int columnIndex, Reader reader, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateClob(String columnLabel, Reader reader, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateDate(int columnIndex, Date x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateDate(String columnLabel, Date x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateDouble(int columnIndex, double x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateDouble(String columnLabel, double x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateFloat(int columnIndex, float x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateFloat(String columnLabel, float x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateInt(int columnIndex, int x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateInt(String columnLabel, int x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateLong(int columnIndex, long x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateLong(String columnLabel, long x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNCharacterStream(String columnLabel, Reader reader) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNClob(int columnIndex, NClob nClob) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNClob(String columnLabel, NClob nClob) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNClob(int columnIndex, Reader reader) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNClob(String columnLabel, Reader reader) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNString(int columnIndex, String nString) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNString(String columnLabel, String nString) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNull(int columnIndex) throws SQLException { // TODO Auto-generated method stub } @Override public void updateNull(String columnLabel) throws SQLException { // TODO Auto-generated method stub } @Override public void updateObject(int columnIndex, Object x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateObject(String columnLabel, Object x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateObject(int columnIndex, Object x, int scaleOrLength) throws SQLException { // TODO Auto-generated method stub } @Override public void updateObject(String columnLabel, Object x, int scaleOrLength) throws SQLException { // TODO Auto-generated method stub } @Override public void updateRef(int columnIndex, Ref x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateRef(String columnLabel, Ref x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateRow() throws SQLException { // TODO Auto-generated method stub } @Override public void updateRowId(int columnIndex, RowId x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateRowId(String columnLabel, RowId x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException { // TODO Auto-generated method stub } @Override public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException { // TODO Auto-generated method stub } @Override public void updateShort(int columnIndex, short x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateShort(String columnLabel, short x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateString(int columnIndex, String x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateString(String columnLabel, String x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateTime(int columnIndex, Time x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateTime(String columnLabel, Time x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { // TODO Auto-generated method stub } @Override public void updateTimestamp(String columnLabel, Timestamp x) throws SQLException { // TODO Auto-generated method stub } @Override public boolean wasNull() throws SQLException { // TODO Auto-generated method stub return false; } @Override public void setFetchDirection(int direction) throws SQLException { // TODO Auto-generated method stub } @Override public void setFetchSize(int rows) throws SQLException { // TODO Auto-generated method stub } @Override public void insertRow() throws SQLException { // TODO Auto-generated method stub } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return false; } @Override public <T> T unwrap(Class<T> iface) throws SQLException { return null; } @Override public void cancelRowUpdates() throws SQLException { } @Override public void clearWarnings() throws SQLException { } @Override public void deleteRow() throws SQLException { // TODO Auto-generated method stub } @Override public InputStream getAsciiStream(int columnIndex) throws SQLException { return null; } @Override public InputStream getAsciiStream(String columnLabel) throws SQLException { return null; } @Override public BigDecimal getBigDecimal(int columnIndex) throws SQLException { return null; } @Override public BigDecimal getBigDecimal(String columnLabel) throws SQLException { return null; } @Override public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { return null; } @Override public BigDecimal getBigDecimal(String columnLabel, int scale) throws SQLException { return null; } @Override public InputStream getBinaryStream(int columnIndex) throws SQLException { return null; } @Override public InputStream getBinaryStream(String columnLabel) throws SQLException { return null; } @Override public Blob getBlob(int columnIndex) throws SQLException { return null; } @Override public Blob getBlob(String columnLabel) throws SQLException { return null; } @Override public byte getByte(int columnIndex) throws SQLException { return 0; } @Override public byte getByte(String columnLabel) throws SQLException { return 0; } @Override public byte[] getBytes(int columnIndex) throws SQLException { return null; } @Override public byte[] getBytes(String columnLabel) throws SQLException { return null; } @Override public Reader getCharacterStream(int columnIndex) throws SQLException { return null; } @Override public Reader getCharacterStream(String columnLabel) throws SQLException { return null; } @Override public Clob getClob(int columnIndex) throws SQLException { return null; } @Override public Clob getClob(String columnLabel) throws SQLException { return null; } @Override public int getConcurrency() throws SQLException { return 0; } @Override public String getCursorName() throws SQLException { return null; } @Override public int getFetchSize() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public int getHoldability() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public Reader getNCharacterStream(int columnIndex) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Reader getNCharacterStream(String columnLabel) throws SQLException { // TODO Auto-generated method stub return null; } @Override public NClob getNClob(int columnIndex) throws SQLException { // TODO Auto-generated method stub return null; } @Override public NClob getNClob(String columnLabel) throws SQLException { // TODO Auto-generated method stub return null; } @Override public String getNString(int columnIndex) throws SQLException { // TODO Auto-generated method stub return null; } @Override public String getNString(String columnLabel) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Object getObject(int columnIndex, Map<String, Class<?>> map) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Object getObject(String columnLabel, Map<String, Class<?>> map) throws SQLException { // TODO Auto-generated method stub return null; } @Override public <T> T getObject(int columnIndex, Class<T> type) throws SQLException { // TODO Auto-generated method stub return null; } @Override public <T> T getObject(String columnLabel, Class<T> type) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Ref getRef(int columnIndex) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Ref getRef(String columnLabel) throws SQLException { // TODO Auto-generated method stub return null; } @Override public int getRow() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public RowId getRowId(int columnIndex) throws SQLException { // TODO Auto-generated method stub return null; } @Override public RowId getRowId(String columnLabel) throws SQLException { // TODO Auto-generated method stub return null; } @Override public SQLXML getSQLXML(int columnIndex) throws SQLException { // TODO Auto-generated method stub return null; } @Override public SQLXML getSQLXML(String columnLabel) throws SQLException { // TODO Auto-generated method stub return null; } @Override public short getShort(int columnIndex) throws SQLException { // TODO Auto-generated method stub return 0; } @Override public short getShort(String columnLabel) throws SQLException { // TODO Auto-generated method stub return 0; } @Override public Time getTime(int columnIndex) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Time getTime(String columnLabel) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Time getTime(int columnIndex, Calendar cal) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Time getTime(String columnLabel, Calendar cal) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Timestamp getTimestamp(int columnIndex) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Timestamp getTimestamp(String columnLabel) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Timestamp getTimestamp(String columnLabel, Calendar cal) throws SQLException { // TODO Auto-generated method stub return null; } @Override public int getType() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public URL getURL(int columnIndex) throws SQLException { // TODO Auto-generated method stub return null; } @Override public URL getURL(String columnLabel) throws SQLException { // TODO Auto-generated method stub return null; } @Override public InputStream getUnicodeStream(int columnIndex) throws SQLException { // TODO Auto-generated method stub return null; } @Override public InputStream getUnicodeStream(String columnLabel) throws SQLException { // TODO Auto-generated method stub return null; } @Override public SQLWarning getWarnings() throws SQLException { // TODO Auto-generated method stub return null; } } <file_sep> /* * DeleteVertexMenuItem.java * * Created on March 21, 2007, 2:03 PM; Updated May 29, 2007 * * Copyright March 21, 2007 Grotto Networking * */ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Collection; import java.util.Iterator; import javax.swing.JMenuItem; import edu.uci.ics.jung.visualization.VisualizationViewer; public class DeleteVertexMenuItem<V> extends JMenuItem implements VertexMenuListener<V> { private V vertex; private VisualizationViewer visComp; public DeleteVertexMenuItem() { super("Delete Vertex"); this.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { System.out.println(vertex); visComp.getPickedVertexState().pick(vertex, false); visComp.getGraphLayout().getGraph().removeVertex(vertex); Iterator<GraphElements.MyVertex> it = visComp.getGraphLayout().getGraph().getVertices().iterator(); int[]vertices = new int[visComp.getGraphLayout().getGraph().getVertexCount()]; String[]oldVertices = new String[visComp.getGraphLayout().getGraph().getVertexCount()]; int i = 0; while(it.hasNext()){ vertices[i] = Integer.parseInt(it.next().getName()); oldVertices[i] = ""+vertices[i]; i++; } for(i = 0;i<visComp.getGraphLayout().getGraph().getVertexCount();i++){ for(int j = i+1;j<visComp.getGraphLayout().getGraph().getVertexCount()-1;j++){ if(vertices[j] >vertices[j+1]){ String temp0 = oldVertices[j]; oldVertices[j] = oldVertices[j+1]; oldVertices[j+1] = temp0; int temp = vertices[j]; vertices[j] = vertices[j+1]; vertices[j+1] = temp; } } } for(i = 0;i<visComp.getGraphLayout().getGraph().getVertexCount();i++){ if(vertices[i]!=i){ vertices[i] = i; } } Collection<GraphElements.MyVertex>c = visComp.getGraphLayout().getGraph().getVertices(); i = 0; for(GraphElements.MyVertex ver:c){ for(int j =0;j<vertices.length;j++){ if(ver.getName().equals(oldVertices[j])){ ver.setName(""+vertices[j]); break; } } } visComp.repaint(); } }); } public void setVertexAndView(V v, VisualizationViewer visComp) { this.vertex = v; this.visComp = visComp; this.setText("Delete Vertex " + v.toString()); } } <file_sep> /* * VertexMenuListener.java * * Created on March 21, 2007, 1:50 PM; Updated May 29, 2007 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ import edu.uci.ics.jung.visualization.VisualizationViewer; public interface VertexMenuListener<V> { void setVertexAndView(V v, VisualizationViewer visView); } <file_sep> import edu.uci.ics.jung.algorithms.layout.Layout; import edu.uci.ics.jung.algorithms.layout.StaticLayout; import edu.uci.ics.jung.graph.SparseMultigraph; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.EditingModalGraphMouse; import edu.uci.ics.jung.visualization.control.ModalGraphMouse; import edu.uci.ics.jung.visualization.decorators.ToStringLabeller; import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPopupMenu; public class Main { public static void main(String[] args) { JFrame frame = new JFrame("SIGNAL FLOW GRAPH"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setExtendedState(JFrame.MAXIMIZED_BOTH); frame.getContentPane().add(new SignalFlowGraphFrontEnd(frame)); frame.pack(); frame.setVisible(true); } } <file_sep>import java.sql.Array; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Map; public class array implements Array { private String arrstr; private String arraydatatype; // / need to be initialized from schema with // the type of the array private ArrayList<String> arrele = new ArrayList<String>(); private void parsing(String arr) { arrstr = arrstr.replaceAll("[{]", ""); arrstr = arrstr.replaceAll("[}]", ""); arrstr = arrstr.replaceAll("'", ""); String[] tmpp = arrstr.split(","); for (int i = 0; i < tmpp.length; i++) { this.arrele.add(tmpp[i]); } return; } public array(String arraystr, String arraydatatype) { if (arraystr == null) arraystr = ""; this.arrstr = arraystr; this.arraydatatype = arraydatatype; } @Override public Object getArray() throws SQLException { if (arrstr.equals("null")) return "null"; Object arrayobject; if (arrstr.equals("") || arrstr.length() == 0) return ""; parsing(arrstr); if (arraydatatype.toLowerCase().contains("varchar") || arraydatatype.toLowerCase().contains("char") || arraydatatype.toLowerCase().contains("longvarchar")) { ArrayList ret = new ArrayList(); for (int i = 0; i < arrele.size(); i++) { ret.add(arrele.get(i)); } arrayobject = ret; return arrayobject; } if (arraydatatype.toLowerCase().contains("tinyint") || arraydatatype.toLowerCase().contains("smallint") || arraydatatype.toLowerCase().contains("integer")) { ArrayList ret = new ArrayList(); for (int i = 0; i < arrele.size(); i++) { ret.add(Integer.parseInt(arrele.get(i))); } arrayobject = ret; return arrayobject; } if (arraydatatype.toLowerCase().contains("real") || arraydatatype.toLowerCase().contains("float")) { ArrayList ret = new ArrayList(); for (int i = 0; i < arrele.size(); i++) { ret.add(Float.parseFloat(arrele.get(i))); } arrayobject = ret; return arrayobject; } if (arraydatatype.toLowerCase().contains("double")) { ArrayList ret = new ArrayList(); for (int i = 0; i < arrele.size(); i++) { ret.add(Double.parseDouble(arrele.get(i))); } arrayobject = ret; return arrayobject; } return null; } @Override public void free() throws SQLException { // TODO Auto-generated method stub } @Override public Object getArray(Map<String, Class<?>> map) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Object getArray(long index, int count) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Object getArray(long index, int count, Map<String, Class<?>> map) throws SQLException { // TODO Auto-generated method stub return null; } @Override public int getBaseType() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public String getBaseTypeName() throws SQLException { // TODO Auto-generated method stub return null; } @Override public ResultSet getResultSet() throws SQLException { // TODO Auto-generated method stub return null; } @Override public ResultSet getResultSet(Map<String, Class<?>> map) throws SQLException { // TODO Auto-generated method stub return null; } @Override public ResultSet getResultSet(long index, int count) throws SQLException { // TODO Auto-generated method stub return null; } @Override public ResultSet getResultSet(long index, int count, Map<String, Class<?>> map) throws SQLException { // TODO Auto-generated method stub return null; } } <file_sep> import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.LinkedList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class DB implements Database { private static String DataBase = ""; public int counter = 0; public DB() { try { File f = new File("existDataBase.txt"); if (f.exists()) { BufferedReader bf = new BufferedReader(new FileReader(f)); while (bf.ready()) { DataBase = bf.readLine(); } } } catch (Exception e) { } } private Validator Validate = new Validator(); /* * (non-Javadoc) * * @see Database#createDatabase(java.lang.String) * * create new Database(new Folder) to create tables(xml files) in it later */ @Override public String createDatabase(String databaseName) { counter = 0; try { File f = new File("existDataBase.txt"); if (!f.exists()) { f.createNewFile(); } PrintWriter write = new PrintWriter(new FileOutputStream( "existDataBase.txt")); write.write(databaseName); write.close(); } catch (Exception e) { } File dir = new File(databaseName); if (!dir.exists()) { dir.mkdir(); DataBase = databaseName; return dbms.Con_DB; } else { DataBase = databaseName; return dbms.DB_ALREADY_EXISTS ; } } public void updateFile(Document dom, String TableName) { TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer; try { transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(dom); StreamResult result = new StreamResult(DataBase + '\\' + TableName.toLowerCase() + ".xml"); // StreamResult result = new StreamResult(DataBase + '\\' + // TableName // + ".xml"); transformer.transform(source, result); } catch (TransformerException e) { e.printStackTrace(); } } /* * Build a Dom Tree of an XML File */ public Document buildDom(InputStream is) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } Document dom = null; try { dom = db.parse(is); } catch (SAXException | IOException e) { e.printStackTrace(); } return dom; } private LinkedList<Integer> checkCondition(Condition con, NodeList rows) { LinkedList<Integer> correctRows = new LinkedList<Integer>(); int index = 0; for (int i = 0; i < rows.getLength(); i++) { if (rows.item(i) instanceof Element) { if (rows.item(i).hasChildNodes()) { NodeList columns = rows.item(i).getChildNodes(); for (int j = 0; j < columns.getLength(); j++) { if (columns.item(j) instanceof Element) { Node curr = columns.item(j); if (curr.getNodeName().toLowerCase() .equals(con.getColName().toLowerCase())) { if (conditionMatch(curr.getTextContent(), con.getOperator(), con.getValue())) { correctRows.add(index); } } } } } index++; } } return correctRows; } /* * (non-Javadoc) * * @see Database#update(java.util.ArrayList, java.util.ArrayList, * java.lang.String, Condition) * * Updates table entries with new values and save them to the database */ public String update(ArrayList<String> columnNames, ArrayList<String> values, String TableName, Condition con) { counter = 0; if (DataBase == "") return dbms.DB_NOT_FOUND; InputStream is; try { is = new FileInputStream(DataBase + '\\' + TableName.toLowerCase() + ".xml"); } catch (FileNotFoundException e) { return dbms.TABLE_NOT_FOUND; } if (!Validate.Validate_Parameters(columnNames, DataBase + '\\' + TableName.toLowerCase() + ".xsd")) return dbms.COLUMN_NOT_FOUND; if (!Validate .Validate_DataTypes(columnNames, values, TableName.toLowerCase(), DataBase + '\\' + TableName.toLowerCase() + ".xsd", this, false)) return dbms.COLUMN_TYPE_MISMATCH; if (con != null) { ArrayList<String> temp0 = new ArrayList<String>(); temp0.add(con.getColName()); ArrayList<String> temp1 = new ArrayList<String>(); temp1.add(con.getValue()); if (!Validate.Validate_Parameters(temp0, DataBase + '\\' + TableName.toLowerCase() + ".xsd")) return dbms.COLUMN_NOT_FOUND; if (!Validate.Validate_DataTypes(temp0, temp1, TableName.toLowerCase(), DataBase + '\\' + TableName.toLowerCase() + ".xsd", this, true)) return dbms.COLUMN_TYPE_MISMATCH; } Document dom = buildDom(is); NodeList rows = dom.getDocumentElement().getChildNodes(); if (checkCondition(con, rows).size() == 0) return dbms.NOT_MATCH_CRITERIA; for (int i = 0; i < rows.getLength(); i++) { if (rows.item(i).getNodeName().equals("#text")) continue; boolean flag = false; NodeList rowdata = rows.item(i).getChildNodes(); for (int j = 0; j < rowdata.getLength(); j++) { if (rowdata.item(j).getNodeName().equals("#text")) continue; if (rowdata.item(j).getNodeName().toLowerCase() .equals(con.getColName().toLowerCase()) && conditionMatch(rowdata.item(j).getTextContent(), con.getOperator(), con.getValue())) { // this row match the condition and must be updated flag = true; } } if (flag) { counter++; for (int j = 0; j < columnNames.size(); j++) { for (int q = 0; q < rowdata.getLength(); q++) { if (rowdata.item(q).getNodeName().toLowerCase() .equals(columnNames.get(j).toLowerCase())) { rowdata.item(q).setTextContent( (String) values.get(j)); break; } } } } } updateFile(dom, TableName.toLowerCase()); return dbms.Con_Update; } public boolean conditionMatch(String oper1, String oper, String oper2) { if (oper1.matches("-?\\d+(\\.\\d+)?") && oper2.matches("-?\\d+(\\.\\d+)?")) { int op1 = Integer.parseInt(oper1); int op2 = Integer.parseInt(oper2); if (oper.equals("<")) { return (op1 < op2); } if (oper.equals(">")) { return (op1 > op2); } if (oper.equals("=")) { return (op1 == op2); } } else { return (oper1.equals(oper2)); } return false; } // helping method for select methods private String appendRow(NodeList columns, ArrayList<String> orderingColumns) { StringBuilder temp = new StringBuilder(); for (int k = 0; k < columns.getLength(); k++) { if (columns.item(k).getNodeType() != 3 && columns.item(k) instanceof Element) { temp.append(columns.item(k).getTextContent()); if (k <= columns.getLength() - 1) { temp.append('*'); } } } return temp.toString(); } // helping method for select methods private String appendRowWithExceptions(NodeList columns, ArrayList<String> columnNames, ArrayList<String> orderingColumns) { StringBuilder temp = new StringBuilder(); int index = 0; for (int k = 0; k < columns.getLength(); k++) { if (columns.item(k).getNodeType() != 3 && columns.item(k) instanceof Element && index<columnNames.size() && columns.item(k).getNodeName().toLowerCase() .equals(columnNames.get(index).toLowerCase())) { index++; temp.append(columns.item(k).getTextContent()); if (index <= columnNames.size() - 1) { temp.append('*'); } } } temp.append('*'); return temp.toString(); } /* * (non-Javadoc) * * @see Database#delete(java.lang.String, Condition) Delete any row * statisfying a given condition */ @Override public String delete(String TableName, Condition con) { if (DataBase == "") return dbms.DB_NOT_FOUND; counter = 0; InputStream is; try { is = new FileInputStream(DataBase + '\\' + TableName.toLowerCase() + ".xml"); } catch (FileNotFoundException e) { return dbms.TABLE_NOT_FOUND; } if (con != null) { ArrayList<String> temp0 = new ArrayList<String>(); temp0.add(con.getColName()); ArrayList<String> temp1 = new ArrayList<String>(); temp1.add(con.getValue()); if (!Validate.Validate_Parameters(temp0, DataBase + '\\' + TableName.toLowerCase() + ".xsd")) return dbms.COLUMN_NOT_FOUND; if (!Validate.Validate_DataTypes(temp0, temp1, TableName.toLowerCase(), DataBase + '\\' + TableName.toLowerCase() + ".xsd", this, true)) return dbms.COLUMN_TYPE_MISMATCH; } Document doc = buildDom(is); Element root = doc.getDocumentElement(); NodeList rows = root.getChildNodes(); if (con == null) { while (rows.getLength() != 0) { root.removeChild(rows.item(0)); counter++; } } else { LinkedList<Integer> rowsD = checkCondition(con, rows); counter = rowsD.size(); if (rowsD.size() == 0) return dbms.NOT_MATCH_CRITERIA; for (int i = 0; i < rowsD.size(); i++) { int x = rowsD.get(i) - i; rowsD.set(i, x); } for (int i = 0; i < rows.getLength(); i++) { if (!(rows.item(i) instanceof Element)) root.removeChild(rows.item(i)); } for (int i = 0; i < rowsD.size(); i++) { int index = rowsD.get(i); root.removeChild(rows.item(index)); } } updateFile(doc, TableName.toLowerCase()); return dbms.Con_Delete; } // helping method for select methods private int[] getIndicesArray(ArrayList<String> orderingColumns, ArrayList<String> columnNames) { int[] indices = new int[orderingColumns.size()]; for (int i = 0; i < orderingColumns.size(); i++) { for (int j = 0; j < columnNames.size(); j++) { if (orderingColumns.get(i).toLowerCase() .equals(columnNames.get(j).toLowerCase())) { indices[i] = j; break; } } } return indices; } /* * (non-Javadoc) * * @see Database#selectColumn(java.util.ArrayList, java.lang.String, * Condition, java.util.ArrayList, boolean) * * This method handles the following SQL statements with/without condition : * SELECT * FROM table_name ORDER BY column_name,column_name ASC|DESC; * SELECT * FROM table_name; */ @Override public String selectAll(String TableName, Condition con, ArrayList<String> orderingColumns, boolean DESC) throws Exception { if (DataBase == "") return dbms.DB_NOT_FOUND; InputStream is; try { is = new FileInputStream(DataBase + '\\' + TableName.toLowerCase() + ".xml"); } catch (FileNotFoundException e) { return dbms.TABLE_NOT_FOUND; } if (orderingColumns != null && !Validate.Validate_Parameters(orderingColumns, DataBase + '\\' + TableName.toLowerCase() + ".xsd")) return dbms.COLUMN_NOT_FOUND; if (con != null) { ArrayList<String> temp0 = new ArrayList<String>(); temp0.add(con.getColName()); ArrayList<String> temp1 = new ArrayList<String>(); temp1.add(con.getValue()); if (!Validate.Validate_Parameters(temp0, DataBase + '\\' + TableName.toLowerCase() + ".xsd")) return dbms.COLUMN_NOT_FOUND; if (!Validate.Validate_DataTypes(temp0, temp1, TableName.toLowerCase(), DataBase + '\\' + TableName.toLowerCase() + ".xsd", this, true)) return dbms.COLUMN_TYPE_MISMATCH; } Document document = buildDom(is); // This string will contain all table contents to be returned later StringBuilder requestedItems = new StringBuilder(); Element root = document.getDocumentElement(); NodeList rows = root.getChildNodes(); LinkedList<Integer> correctRows = null; int index = 0; if (con != null) { correctRows = checkCondition(con, rows); } boolean isFound = false; int k = 0; for (int i = 0; i < rows.getLength(); i++) { if (rows.item(i) instanceof Element) { boolean in = false; if (con != null && index < correctRows.size() && correctRows.get(index) == k) { NodeList columns = rows.item(i).getChildNodes(); requestedItems.append(appendRow(columns, orderingColumns)); in = true; isFound = true; index++; } else if (con == null) { NodeList columns = rows.item(i).getChildNodes(); requestedItems.append(appendRow(columns, orderingColumns)); isFound = true; } if (in || con == null) { requestedItems.append('\n'); } k++; } } StringBuilder temp = new StringBuilder(); for (int i = 0; i < requestedItems.length() - 1; i++) temp.append(requestedItems.charAt(i)); requestedItems = temp; if (!isFound) return dbms.NOT_MATCH_CRITERIA; if (orderingColumns == null || orderingColumns.isEmpty()) { return requestedItems.toString(); } Schema schema = new Schema(); ArrayList<Column> tableColumns = schema.schemaParsing( DataBase + '\\' + TableName.toLowerCase() + ".xsd" ); ArrayList<String> columnNames = new ArrayList<String>(); for (int i = 0; i < tableColumns.size(); i++) { columnNames.add(tableColumns.get(i).getColName()); } requestedItems = getRequestedItemsByOrder(requestedItems, getIndicesArray(orderingColumns, columnNames), DESC); return requestedItems.toString(); } // helping method for select methods private StringBuilder getRequestedItemsByOrder( StringBuilder requestedItems, int[] indices, boolean DESC) { String[][] table = parseString(requestedItems.toString(), indices, DESC); StringBuilder newRequestedItems = new StringBuilder(); newRequestedItems = buildString(table); return newRequestedItems; } // helping method for select methods private StringBuilder buildString(String[][] table) { StringBuilder temp = new StringBuilder(); for (int i = 0; i < table.length; i++) { for (int j = 0; j < table[i].length; j++) { temp.append(table[i][j]); if (j <= table[i].length - 1) temp.append('*'); } if (i < table.length - 1) temp.append('\n'); } return temp; } // helping method for select methods private String[][] parseString(String string, int[] indices, boolean DESC) { String[] line = string.split("\\n"); int len = line[0].split("\\*").length; String[][] table = new String[line.length][len]; for (int i = 0; i < table.length; i++) { String[] temp = line[i].split("\\*"); for (int j = 0; j < table[i].length; j++) { table[i][j] = temp[j]; } } sortLexicographically(table, indices, DESC); return table; } /* * This method sorts the selected table from the database accorring to the * given columns through Bubble sort manipulation */ private void sortLexicographically(String[][] table, int[] indices, boolean DESC) { for (int a = 0; a < indices.length; a++) { for (int b = 0; b < table.length - 1; b++) { for (int c = 0; c < table.length - b - 1; c++) { String type = getDataType(table[c][indices[a]]); if (!type.equals("string")) { if (DESC && ((type.equals("integer") && ((a == 0 && Integer .parseInt(table[c][indices[a]]) < Integer .parseInt(table[c + 1][indices[a]])) || (a > 0 && Integer .parseInt(table[c][indices[a]]) < Integer .parseInt(table[c + 1][indices[a]]) && table[c][indices[a - 1]] .compareTo(table[c + 1][indices[a - 1]]) == 0))) || (type .equals("double") && ((a == 0 && Double .parseDouble(table[c][indices[a]]) < Double .parseDouble(table[c + 1][indices[a]])) || (a > 0 && Double .parseDouble(table[c][indices[a]]) < Double .parseDouble(table[c + 1][indices[a]]) && table[c][indices[a - 1]] .compareTo(table[c + 1][indices[a - 1]]) == 0))))) { for (int i = 0; i < table[c].length; i++) { String temp = table[c][i]; table[c][i] = table[c + 1][i]; table[c + 1][i] = temp; } } if (!DESC && ((type.equals("integer") && ((a == 0 && Integer .parseInt(table[c][indices[a]]) > Integer .parseInt(table[c + 1][indices[a]])) || (a > 0 && Integer .parseInt(table[c][indices[a]]) > Integer .parseInt(table[c + 1][indices[a]]) && table[c][indices[a - 1]] .compareTo(table[c + 1][indices[a - 1]]) == 0))) || (type .equals("double") && ((a == 0 && Double .parseDouble(table[c][indices[a]]) > Double .parseDouble(table[c + 1][indices[a]])) || (a > 0 && Double .parseDouble(table[c][indices[a]]) > Double .parseDouble(table[c + 1][indices[a]]) && table[c][indices[a - 1]] .compareTo(table[c + 1][indices[a - 1]]) == 0))))) { for (int i = 0; i < table[c].length; i++) { String temp = table[c][i]; table[c][i] = table[c + 1][i]; table[c + 1][i] = temp; } } } else { if ((a == 0 && DESC && table[c][indices[a]] .compareTo(table[c + 1][indices[a]]) < 0) || (DESC && a > 0 && table[c][indices[a - 1]] .compareTo(table[c + 1][indices[a - 1]]) == 0 && table[c][indices[a]] .compareTo(table[c + 1][indices[a]]) < 0)) { for (int i = 0; i < table[c].length; i++) { String temp = table[c][i]; table[c][i] = table[c + 1][i]; table[c + 1][i] = temp; } } if ((a == 0 && !DESC && table[c][indices[a]] .compareTo(table[c + 1][indices[a]]) > 0) || (!DESC && a > 0 && table[c][indices[a - 1]] .compareTo(table[c + 1][indices[a - 1]]) == 0 && table[c][indices[a]] .compareTo(table[c + 1][indices[a]]) > 0)) { for (int i = 0; i < table[c].length; i++) { String temp = table[c][i]; table[c][i] = table[c + 1][i]; table[c + 1][i] = temp; } } } } } } } /* * Returns true if the given string is Integer false otherwise */ public String getDataType(String string) { if (string.matches("([ ]*)((-?+)(\\+{0,1}+))([ ]*)([0-9]+)([ ]*)")) return "integer"; if (string .matches("([ ]*)((-?+)(\\+{0,1}+))([ ]*)([0-9]+)([ 0-9 ]*)([ ]*)((\\.)([ ]*[0-9]+))?+([ ]*)([ 0-9 ]*)([ ]*)")) { return "double"; } if(string.toLowerCase().matches("\\ *\\{(\\ *'?\\w+'?,?)+\\}")) return "array"; return "string"; } /* * Arranges the user's query according to the arrangement of columns in * schema file */ void arrangeColumnNames(ArrayList<String> columnNames, String TableName) { Schema schema = new Schema(); ArrayList<Column> tableColumns = schema.schemaParsing(DataBase + '\\' + TableName.toLowerCase() + ".xsd"); int[] temp = new int[columnNames.size()]; for (int i = 0; i < columnNames.size(); i++) { for (int j = 0; j < tableColumns.size(); j++) { if (tableColumns.get(j).getColName().toLowerCase() .equals(columnNames.get(i).toLowerCase())) { temp[i] = j; break; } } } for (int c = 0; c < (temp.length - 1); c++) { for (int d = 0; d < temp.length - c - 1; d++) { if (temp[d] > temp[d + 1]) { int swap = temp[d]; temp[d] = temp[d + 1]; temp[d + 1] = swap; String s = columnNames.get(d); columnNames.set(d, columnNames.get(d + 1)); columnNames.set(d + 1, s); } } } } /* * Arranges the user's query according to the arrangement of columns in * schema file for insert into statement */ void arrangeColumnNamesWithValues(ArrayList<String> columnNames, ArrayList<String> values, String TableName) { Schema schema = new Schema(); ArrayList<Column> tableColumns = schema.schemaParsing(DataBase + '\\' + TableName.toLowerCase() + ".xsd"); int[] temp = new int[columnNames.size()]; for (int i = 0; i < columnNames.size(); i++) { for (int j = 0; j < tableColumns.size(); j++) { if (tableColumns.get(j).getColName().toLowerCase() .equals(columnNames.get(i).toLowerCase())) { temp[i] = j; break; } } } for (int c = 0; c < (temp.length - 1); c++) { for (int d = 0; d < temp.length - c - 1; d++) { if (temp[d] > temp[d + 1]) { int swap = temp[d]; temp[d] = temp[d + 1]; temp[d + 1] = swap; String s = columnNames.get(d); columnNames.set(d, columnNames.get(d + 1)); columnNames.set(d + 1, s); s = values.get(d); values.set(d, values.get(d + 1)); values.set(d + 1, s); } } } } /* * (non-Javadoc) * * @see Database#selectColumn(java.util.ArrayList, java.lang.String, * Condition, java.util.ArrayList, boolean) * * This method handles the following SQL statements with/without condition : * SELECT column_name,column_name FROM table_name ORDER BY * column_name,column_name ASC|DESC; SELECT column_name,column_name FROM * table_name; SELECT DISTINCT column_name,column_name FROM table_name; */ @Override public String selectColumn(ArrayList<String> columnNames, String TableName, Condition con, ArrayList<String> orderingColumns, boolean DESC) { if (DataBase == "") return dbms.DB_NOT_FOUND; InputStream is; try { is = new FileInputStream(DataBase + '\\' + TableName.toLowerCase() + ".xml"); } catch (FileNotFoundException e) { return dbms.TABLE_NOT_FOUND; } if (orderingColumns != null && !Validate.Validate_Parameters(orderingColumns, DataBase + '\\' + TableName.toLowerCase() + ".xsd")) return dbms.COLUMN_NOT_FOUND; if (orderingColumns != null && !Validate.Validate_Parameters(orderingColumns, DataBase + '\\' + TableName.toLowerCase() + ".xsd")) return dbms.COLUMN_NOT_FOUND; if (con != null) { ArrayList<String> temp0 = new ArrayList<String>(); temp0.add(con.getColName()); ArrayList<String> temp1 = new ArrayList<String>(); temp1.add(con.getValue()); System.out.println(con.getValue()); if (!Validate.Validate_Parameters(temp0, DataBase + '\\' + TableName.toLowerCase() + ".xsd")) return dbms.COLUMN_NOT_FOUND; if (!Validate.Validate_DataTypes(temp0, temp1, TableName.toLowerCase(), DataBase + '\\' + TableName.toLowerCase() + ".xsd", this, true)) return dbms.COLUMN_TYPE_MISMATCH; } Document document = buildDom(is); // This string will contain all table contents to be returned later StringBuilder requestedItems = new StringBuilder(); Element root = document.getDocumentElement(); NodeList rows = root.getChildNodes(); LinkedList<Integer> correctRows = null; int index = 0; if (con != null) { correctRows = checkCondition(con, rows); } int k = 0; boolean isFound = false; for (int i = 0; i < rows.getLength(); i++) { if (rows.item(i) instanceof Element) { boolean in = false; if (con != null && index < correctRows.size() && correctRows.get(index) == k) { index++; NodeList columns = rows.item(i).getChildNodes(); requestedItems.append(appendRowWithExceptions(columns, columnNames, orderingColumns)); in = true; isFound = true; } else if (con == null) { NodeList columns = rows.item(i).getChildNodes(); requestedItems.append(appendRowWithExceptions(columns, columnNames, orderingColumns)); isFound = true; } if (in || con == null) { requestedItems.append('\n'); } k++; } } if (!isFound) return dbms.NOT_MATCH_CRITERIA; if (orderingColumns == null || orderingColumns.isEmpty()) return requestedItems.toString(); requestedItems = getRequestedItemsByOrder(requestedItems, getIndicesArray(orderingColumns, columnNames), DESC); return requestedItems.toString(); } /* * (non-Javadoc) * * @see Database#selectColumn(java.util.ArrayList, java.lang.String, * Condition, java.util.ArrayList, boolean) * * This method creates an xml file with its schema file stating all table * basic info through method schemaCreating(....) class Schema */ @Override public String createTable(ArrayList<Column> myColumns, String TableName) { if (DataBase == "") return dbms.DB_NOT_FOUND; File myFile = new File(DataBase + '\\' + TableName.toLowerCase() + ".xml"); try { if (!myFile.createNewFile()) return dbms.TABLE_ALREADY_EXISTS; else { XMLOutputFactory factory = XMLOutputFactory.newInstance(); try { // XMLStreamWriter writer = factory // .createXMLStreamWriter(new FileWriter(DataBase // + '\\' + TableName + ".xml")); XMLStreamWriter writer = factory .createXMLStreamWriter(new FileWriter(DataBase + '\\' + TableName.toLowerCase() + ".xml")); writer.writeStartDocument(); writer.writeStartElement(TableName.toLowerCase()); writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } /* Schema creation */ Schema sch = new Schema(); sch.schemaCreating(myColumns, DataBase + '\\' + TableName.toLowerCase() + ".xsd", TableName.toLowerCase(), "Row"); counter = myColumns.size(); return dbms.Con_Table; } /* * (non-Javadoc) * * @see Database#insert(java.util.ArrayList, java.util.ArrayList, * java.lang.String) * * This method inserts a row into a table having given values */ @Override public String insert(ArrayList<String> columnNames, ArrayList<String> values, String TableName) { if (DataBase == "") return dbms.DB_NOT_FOUND; InputStream is; try { is = new FileInputStream(DataBase + '\\' + TableName.toLowerCase() + ".xml"); } catch (FileNotFoundException e) { return dbms.TABLE_NOT_FOUND; } if (columnNames != null) { if (!Validate.Validate_Parameters(columnNames, DataBase + '\\' + TableName.toLowerCase() + ".xsd")) return dbms.COLUMN_NOT_FOUND; if (!Validate.Validate_DataTypes(columnNames, values, TableName.toLowerCase(), DataBase + '\\' + TableName.toLowerCase() + ".xsd", this, false)) return dbms.COLUMN_TYPE_MISMATCH; } Document doc = buildDom(is); Element root = doc.getDocumentElement(); NodeList rows = root.getChildNodes(); Schema sch = new Schema(); ArrayList<Column> schCol = sch.schemaParsing(DataBase + '\\' + TableName.toLowerCase() + ".xsd"); if (columnNames == null || columnNames.size() == 0) { columnNames = new ArrayList<String>(); for (int i = 0; i < schCol.size(); i++) { columnNames.add(schCol.get(i).getColName()); } } else if (columnNames.size() < schCol.size()) { for (int i = 0; i < schCol.size(); i++) { // if (columnNames.contains(schCol.get(i).getColName())) // continue; boolean flag = false; for (int j = 0; j < columnNames.size(); j++) { if (columnNames.get(j).toLowerCase() .equals(schCol.get(i).getColName().toLowerCase())) { flag = true; break; } } if (flag) continue; columnNames.add(schCol.get(i).getColName()); values.add("null"); } } arrangeColumnNamesWithValues(columnNames, values, TableName.toLowerCase()); Element newRow = doc.createElement("Row");// should have a row name for (int i = 0; i < columnNames.size(); i++) { Element n = doc.createElement(columnNames.get(i)); n.setTextContent(values.get(i)); newRow.appendChild(n); } root.appendChild(newRow); updateFile(doc, TableName.toLowerCase()); counter = 1; return dbms.Con_insert; } } <file_sep> /* * MenuPointListener.java * * Created on March 22, 2007, 4:08 PM * * Copyright 2007 Grotto Networking */ import java.awt.geom.Point2D; public interface MenuPointListener { void setPoint(Point2D point); } <file_sep> import java.util.ArrayList; public interface Database { public String createDatabase(String databaseName); /* * if there is no condition then con == null; */ public String selectAll(String TableName, Condition con, ArrayList<String> orderingColumns, boolean DESC)throws Exception; public String selectColumn(ArrayList<String> columnNames, String TableName, Condition con, ArrayList<String> orderingColus, boolean DESC); public String createTable(ArrayList<Column> myColumns, String TableName); public String delete(String TableName, Condition con); public String insert(ArrayList<String> columnNames, ArrayList<String> values, String TableName); /* * if ColumnNames equals null then it is the first case of insertion; */ public String update(ArrayList<String> columnNames, ArrayList<String> values, String TableName, Condition con); }<file_sep>import java.sql.*; import java.util.ArrayList; import org.apache.log4j.Logger; public class ResultSetMetaDataIM implements ResultSetMetaData { private String table_name; private ArrayList<String> columns_types; private ArrayList<String> columns_names; private Logger log = Logger.getLogger(ResultSetMetaDataIM.class.getName()); public ResultSetMetaDataIM(ArrayList<String> columnsNames, ArrayList<String> columnTypes, String TableName) { columns_names = columnsNames; columns_types = columnTypes; table_name = TableName; } /************** the required **************/ @Override public int getColumnCount() throws SQLException { if (columns_names == null) { log.error("There is no column_names"); throw new SQLException("There is no column_names"); } return columns_names.size(); } @Override public String getColumnLabel(int column) throws SQLException { return getColumnName(column); } @Override public String getColumnName(int column) throws SQLException { column--; if (column < -1 || column >= columns_names.size()) { log.error("Index is out of bound"); throw new SQLException("Index is out of bound"); } return columns_names.get(column); } @Override public int getColumnType(int column) throws SQLException { column--; if (column < -1 || column >= columns_names.size()) { log.error("Index is out of bound"); throw new SQLException("Index is out of bound"); } if (columns_types.get(column).equals("int") || columns_types.get(column).equals("integer")) return Types.INTEGER; if (columns_types.get(column).toLowerCase().equals("varchar")) return Types.VARCHAR; if (columns_types.get(column).toLowerCase().equals("float")) return Types.FLOAT; if (columns_types.get(column).toLowerCase().equals("double")) return Types.DOUBLE; if (columns_types.get(column).toLowerCase().contains("array")) return Types.ARRAY; if (columns_types.get(column).toLowerCase().equals("boolean")) return Types.BOOLEAN; if (columns_types.get(column).toLowerCase().equals("char")) return Types.CHAR; if (columns_types.get(column).toLowerCase().equals("null")) return Types.NULL; if (columns_types.get(column).toLowerCase().equals("date")) return Types.DATE; if (columns_types.get(column).toLowerCase().equals("bit")) return Types.BIT; if (columns_types.get(column).toLowerCase().equals("smallint")) return Types.SMALLINT; if (columns_types.get(column).toLowerCase().equals("bigint")) return Types.BIGINT; if (columns_types.get(column).toLowerCase().equals("tinyint")) return Types.TINYINT; if (columns_types.get(column).toLowerCase().equals("real")) return Types.REAL; log.error("Type mismatch"); throw new SQLException("Type mismatch"); } @Override public String getTableName(int column) throws SQLException { if (column < -1 || column >= columns_names.size()) { log.error("Index is out of bound"); throw new SQLException("Index is out of bound"); } return table_name; } @Override public boolean isAutoIncrement(int column) throws SQLException { return true; } @Override public int isNullable(int column) throws SQLException { return ResultSetMetaData.columnNullable; } @Override public boolean isReadOnly(int column) throws SQLException { return false; } @Override public boolean isSearchable(int column) throws SQLException { return true; } @Override public boolean isWritable(int column) throws SQLException { return true; } /******************************************/ @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { // TODO Auto-generated method stub return false; } @Override public <T> T unwrap(Class<T> iface) throws SQLException { // TODO Auto-generated method stub return null; } @Override public String getCatalogName(int column) throws SQLException { // TODO Auto-generated method stub return null; } @Override public String getColumnClassName(int column) throws SQLException { // TODO Auto-generated method stub return null; } @Override public int getColumnDisplaySize(int column) throws SQLException { // TODO Auto-generated method stub return 0; } @Override public int getPrecision(int column) throws SQLException { // TODO Auto-generated method stub return 0; } @Override public int getScale(int column) throws SQLException { // TODO Auto-generated method stub return 0; } @Override public String getSchemaName(int column) throws SQLException { // TODO Auto-generated method stub return null; } @Override public boolean isCaseSensitive(int column) throws SQLException { // TODO Auto-generated method stub return false; } @Override public boolean isCurrency(int column) throws SQLException { // TODO Auto-generated method stub return false; } @Override public boolean isDefinitelyWritable(int column) throws SQLException { // TODO Auto-generated method stub return false; } @Override public boolean isSigned(int column) throws SQLException { // TODO Auto-generated method stub return false; } @Override public String getColumnTypeName(int column) throws SQLException { // TODO Auto-generated method stub return null; } } <file_sep>import java.sql.*; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; import org.apache.log4j.Logger; public class ConnectionIM implements java.sql.Connection { private String DBPath = ""; private StatementIm state; private Logger log = Logger.getLogger(ConnectionIM.class.getName()); public ConnectionIM(String db) { log.info("Connection is initiated"); DBPath = db; try { state = new StatementIm(DBPath, this); } catch (Exception e) { e.printStackTrace(); } } /************** the required **************/ @Override public void close() throws SQLException { if (DBPath.equals("")) return; log.info("Connection is closed."); DBPath = ""; state.close(); } @Override public Statement createStatement() throws SQLException { try { return state; } catch (Exception e) { log.error(e.getMessage()); throw new SQLException(); } } /******************************************/ @Override public boolean isWrapperFor(Class<?> arg0) throws SQLException { // TODO Auto-generated method stub return false; } @Override public <T> T unwrap(Class<T> arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public void abort(Executor arg0) throws SQLException { // TODO Auto-generated method stub } @Override public void clearWarnings() throws SQLException { // TODO Auto-generated method stub } @Override public void commit() throws SQLException { // TODO Auto-generated method stub } @Override public Array createArrayOf(String arg0, Object[] arg1) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Blob createBlob() throws SQLException { // TODO Auto-generated method stub return null; } @Override public Clob createClob() throws SQLException { // TODO Auto-generated method stub return null; } @Override public NClob createNClob() throws SQLException { // TODO Auto-generated method stub return null; } @Override public SQLXML createSQLXML() throws SQLException { // TODO Auto-generated method stub return null; } @Override public Statement createStatement(int arg0, int arg1) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Statement createStatement(int arg0, int arg1, int arg2) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Struct createStruct(String arg0, Object[] arg1) throws SQLException { // TODO Auto-generated method stub return null; } @Override public boolean getAutoCommit() throws SQLException { // TODO Auto-generated method stub return false; } @Override public String getCatalog() throws SQLException { // TODO Auto-generated method stub return null; } @Override public Properties getClientInfo() throws SQLException { // TODO Auto-generated method stub return null; } @Override public String getClientInfo(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public int getHoldability() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public DatabaseMetaData getMetaData() throws SQLException { // TODO Auto-generated method stub return null; } @Override public int getNetworkTimeout() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public String getSchema() throws SQLException { // TODO Auto-generated method stub return null; } @Override public int getTransactionIsolation() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { // TODO Auto-generated method stub return null; } @Override public SQLWarning getWarnings() throws SQLException { // TODO Auto-generated method stub return null; } @Override public boolean isClosed() throws SQLException { // TODO Auto-generated method stub return false; } @Override public boolean isReadOnly() throws SQLException { // TODO Auto-generated method stub return false; } @Override public boolean isValid(int arg0) throws SQLException { // TODO Auto-generated method stub return false; } @Override public String nativeSQL(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public CallableStatement prepareCall(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public CallableStatement prepareCall(String arg0, int arg1, int arg2) throws SQLException { // TODO Auto-generated method stub return null; } @Override public CallableStatement prepareCall(String arg0, int arg1, int arg2, int arg3) throws SQLException { // TODO Auto-generated method stub return null; } @Override public PreparedStatement prepareStatement(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public PreparedStatement prepareStatement(String arg0, int arg1) throws SQLException { // TODO Auto-generated method stub return null; } @Override public PreparedStatement prepareStatement(String arg0, int[] arg1) throws SQLException { // TODO Auto-generated method stub return null; } @Override public PreparedStatement prepareStatement(String arg0, String[] arg1) throws SQLException { // TODO Auto-generated method stub return null; } @Override public PreparedStatement prepareStatement(String arg0, int arg1, int arg2) throws SQLException { // TODO Auto-generated method stub return null; } @Override public PreparedStatement prepareStatement(String arg0, int arg1, int arg2, int arg3) throws SQLException { // TODO Auto-generated method stub return null; } @Override public void releaseSavepoint(Savepoint arg0) throws SQLException { // TODO Auto-generated method stub } @Override public void rollback() throws SQLException { // TODO Auto-generated method stub } @Override public void rollback(Savepoint arg0) throws SQLException { // TODO Auto-generated method stub } @Override public void setAutoCommit(boolean arg0) throws SQLException { // TODO Auto-generated method stub } @Override public void setCatalog(String arg0) throws SQLException { // TODO Auto-generated method stub } @Override public void setClientInfo(Properties arg0) throws SQLClientInfoException { // TODO Auto-generated method stub } @Override public void setClientInfo(String arg0, String arg1) throws SQLClientInfoException { // TODO Auto-generated method stub } @Override public void setHoldability(int arg0) throws SQLException { // TODO Auto-generated method stub } @Override public void setNetworkTimeout(Executor arg0, int arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setReadOnly(boolean arg0) throws SQLException { // TODO Auto-generated method stub } @Override public Savepoint setSavepoint() throws SQLException { // TODO Auto-generated method stub return null; } @Override public Savepoint setSavepoint(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public void setSchema(String arg0) throws SQLException { // TODO Auto-generated method stub } @Override public void setTransactionIsolation(int arg0) throws SQLException { // TODO Auto-generated method stub } @Override public void setTypeMap(Map<String, Class<?>> arg0) throws SQLException { // TODO Auto-generated method stub } } <file_sep>import java.util.ArrayList; import org.apache.log4j.Logger; public class Parser { public DB onFocus = new DB(); public String TableName; private Logger log = Logger.getLogger(ConnectionIM.class.getName()); public String perform(String command) throws Exception { String original = new String(command); command = wellFormatted(command); String[] parts = command.split(" "); Condition con = getCon(parts, original); TableName = getTableName(parts); if (parts[0].toUpperCase().equals("SELECT")) { log.info("Executing Select Statement"); if (onFocus == null) return dbms.TABLE_NOT_FOUND; if (parts[1].equals("*")) { return onFocus.selectAll(TableName, con, orderingColumns(parts), original.toUpperCase() .contains("DESC")); } else if (parts[1].toUpperCase().equals("DISTINCT")) { ArrayList<String> coluNames = new ArrayList<String>(); for (int i = 2; i < parts.length && !parts[i].toUpperCase().equals("FROM"); i++) coluNames.add(parts[i]); return onFocus.selectColumn(coluNames, TableName, con, orderingColumns(parts), original.toUpperCase() .contains("DESC")); } else { ArrayList<String> coluNames = new ArrayList<String>(); for (int i = 1; i < parts.length && !parts[i].toString().equals("FROM"); i++) coluNames.add(parts[i]); return onFocus.selectColumn(coluNames, TableName, con, orderingColumns(parts), original.toUpperCase() .contains("DESC")); } } else if (parts[0].toUpperCase().equals("CREATE")) { if (parts[1].toUpperCase().equals("DATABASE")) { log.info("Executing Create Database Statement"); onFocus = new DB(); return onFocus.createDatabase(parts[2]); } else if (parts[1].toUpperCase().equals("TABLE")) { log.info("Executing Create Table Statement"); parts = command.replaceAll(" ARRAY", "ARRAY") .replaceAll(" Array", "Array") .replaceAll(" array", "array").split(" "); if (onFocus == null) return dbms.DB_NOT_FOUND; return onFocus.createTable(getColumnsData(parts), parts[2]); } } else if (parts[0].toUpperCase().equals("DELETE")) { log.info("Executing Delete Statement"); if (onFocus == null) return dbms.TABLE_NOT_FOUND; return onFocus.delete(TableName, con); } else if (parts[0].toUpperCase().equals("INSERT")) { log.info("Executing Insert Statement"); if (onFocus == null) return dbms.TABLE_NOT_FOUND; ArrayList<String> columns = getBetweenBrackets(original .substring(original.toUpperCase().indexOf("VALUES") + 6)); if (parts[3].equals("(")) return onFocus.insert( getBetweenBrackets(original.substring( original.indexOf("("), original.indexOf(")"))), columns, parts[2]); else return onFocus.insert(null, columns, parts[2]); } else if (parts[0].toUpperCase().equals("UPDATE")) { log.info("Executing update Statement"); if (onFocus == null) return dbms.TABLE_NOT_FOUND; ArrayList<String> ColuNames = new ArrayList<String>(), values = new ArrayList<String>(); getData(ColuNames, values, original); return onFocus.update(ColuNames, values, TableName, con); } return dbms.PARSING_ERROR; } private Condition getCon(String parts[], String d) { if (d.toUpperCase().contains("WHERE")) { d = d.substring(d.toUpperCase().indexOf("WHERE") + 6).trim(); if (d.contains("'")) { d = d.substring(d.indexOf("'")); d.replaceAll("[';]", ""); } else d = null; } for (int i = 3; i < parts.length; i++) if (parts[i].toUpperCase().equals("WHERE")) { return new Condition(parts[i + 1], parts[i + 2], d == null ? parts[i + 3] : d.replaceAll("[';]", "")); } return null; } private String getTableName(String parts[]) { for (int i = 0; i < parts.length; i++) if (parts[i].toLowerCase().equals("FROM".toLowerCase()) || parts[i].toUpperCase().equals("INTO") || parts[i].toUpperCase().equals("UPDATE")) return parts[i + 1]; return null; } public ArrayList<Column> getColumnsData(String parts[]) { ArrayList<Column> myColumns = new ArrayList<Column>(); for (int i = 4; i < parts.length && !parts[i].equals(")"); i += 5) if (parts[i + 1].toLowerCase().equals("int") || parts[i + 1].toLowerCase().equals("integer") || parts[i + 1].toLowerCase().equals("long") || parts[i + 1].toLowerCase().equals("float") || parts[i + 1].toLowerCase().equals("double") || parts[i + 1].toLowerCase().equals("real") || parts[i + 1].toLowerCase().equals("smallint") || parts[i + 1].toLowerCase().equals("bigint") || parts[i + 1].toLowerCase().equals("tinyint")) { myColumns.add(new Column(parts[i], parts[i + 1], 255)); i -= 3; } else { myColumns.add(new Column(parts[i], parts[i + 1], Integer .parseInt(parts[i + 3].trim()))); } return myColumns; } private ArrayList<String> getBetweenBrackets(String original) { original = original.replaceAll("[\\(\\)\\;]", ""); original = original.replaceAll("\\'( )*\\,( )*\\'", ",").trim(); if (original.charAt(0) == '\'') original = original.substring(1, original.length() - 1); String[] parts = original.split(","); ArrayList<String> Values = new ArrayList<String>(); for (int i = 0; i < parts.length; i++) if (parts[i].charAt(0) == '{') { String temp = parts[i++]; for (; i < parts.length; i++) { temp = temp.concat("','" + parts[i]); if (parts[i].charAt(parts[i].length() - 1) == '}') break; } Values.add(temp.trim()); } else { Values.add(parts[i].replaceAll("'", "").trim()); } return Values.size() == 0 ? null : Values; } private void getData(ArrayList<String> names, ArrayList<String> values, String p) { int i = p.length(); if (p.toLowerCase().contains("where")) i = p.toLowerCase().indexOf("where"); String temp = p.substring(p.toLowerCase().indexOf("set") + 3, i).trim(); String[] pe = temp.split("( )*,( )*"); for (int j = 0; j < pe.length; j++) { String[] pe2 = pe[j].split("( )*=( )*"); names.add(pe2[0].trim()); if (pe2[1].charAt(0) == '{') { temp = pe2[1]; for (i = j + 1; i < pe.length; i++) { temp = temp.concat("," + pe[i]); if (pe[i].charAt(pe[i].length() - 1) == '}') break; } j = i; values.add(temp.trim()); } else values.add(pe2[1].trim().substring(1, pe2[1].length() - 1)); } } private String wellFormatted(String command) { command = command.replaceAll(",", " "); command = command.replaceAll("=", " = "); command = command.replaceAll(">", " > "); command = command.replaceAll("<", " < "); command = command.replaceAll("\\)", " \\) "); command = command.replaceAll("\\(", " \\( "); command = command.replaceAll("\\]", " \\) "); command = command.replaceAll("\\[", " \\( "); command = command.replaceAll("[\t;]", ""); return command.replaceAll("^ +| +$|( )+", "$1"); } private ArrayList<String> orderingColumns(String[] parts) { ArrayList<String> res = null; for (int i = 5; i < parts.length; i++) { if (parts[i].toUpperCase().toUpperCase().equals("BY")) { res = new ArrayList<String>(); for (int j = i + 1; j < parts.length && !parts[j].toUpperCase().equals("DESC") && !parts[j].toUpperCase().equals("ASC"); j++) res.add(parts[j]); break; } } return res; } } <file_sep>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.*; import java.util.Properties; import org.apache.log4j.Logger; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String url = "jdbc:DBMS:default"; Connection con; Statement stmt; Logger log = Logger.getLogger(Main.class.getName()); try { Class.forName("DriverIM"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } Properties p = null; try { DriverIM e = new DriverIM(); DriverManager.registerDriver(e); do { String tempo; System.out.print("Enter username: "); tempo = in.readLine(); System.out.print("Enter password: "); p = new Properties(); p.put("username", tempo); p.put("password", in.readLine()); try { con = DriverManager.getConnection(url, p); } catch (SQLException sqlEx) { log.error(sqlEx.getMessage()); continue; } break; } while (true); System.out.println("\n-------------------------------------------"); stmt = con.createStatement(); String query; while (true) { System.out.print("SQL>"); query = in.readLine().trim(); if (query == null) continue; String firstW = query.trim(); if (query.contains(" ")) firstW = query.substring(0, query.indexOf(" ")); if (firstW.toLowerCase().equals("use")) try { con = DriverManager.getConnection("Jdbc:DBMS:" + query.substring(3).trim() .replaceAll(";", " ").trim(), p); stmt = con.createStatement(); } catch (SQLException ee) { log.error(ee.getMessage()); continue; } else if (firstW.toLowerCase().equals("select")) { try { ResultSetIM res = (ResultSetIM) stmt .executeQuery(query); res.absolute(0); int sz = res.rows.size() == 0 ? 0 : res.rows.get(0) .size(); while (res.next()) { for (int i = 0; i < sz; i++) { if (res.columnTypes.get(i).contains("array")) { array a = new array( res.rows.get(res.pointer - 1) .get(i), res.columnTypes .get(i).split(" ")[0]); if (!res.getObject(i).equals("")) { System.out.print(a.getArray() + " | "); } } else { if (!res.getObject(i).equals("")) { System.out.print(res.getObject(i) + " | "); } } } System.out.println(); } } catch (SQLException ee) { log.error(ee.getMessage()); System.out.println(); System.err.println("SQLException: " + ee.getMessage()); continue; } } else if (firstW.toLowerCase().equals("create")) { try { System.out.println(stmt.execute(query)); String[] str = query.split(" "); if (!str[1].toLowerCase().equals("table")) { query = query.trim().substring(query.indexOf(" ")) .trim(); con = DriverManager.getConnection("Jdbc:DBMS:" + query.substring(query.indexOf(" ")) .replaceAll(";", " ").trim(), p); stmt = con.createStatement(); } } catch (SQLException ee) { log.error(ee.getMessage()); System.err.println("SQLException: " + ee.getMessage()); continue; } } else if (query.trim().toLowerCase().equals("end")) { con.close(); stmt.close(); break; } else { try { System.out.println(stmt.executeUpdate(query)); } catch (SQLException ee) { log.error(ee.getMessage()); continue; } } } } catch (SQLException ex) { log.error(ex.getMessage()); System.err.println("SQLException: " + ex.getMessage()); } } }
a718e05ee3c44dddbe9eafc490b01bccd04ba43a
[ "Java" ]
15
Java
ayamoneim/Team-Projects
be27a5104d286c459a572f69e4a0dda39361386f
a5d912e930f6a1980c7387daa7393991757af9b3
refs/heads/master
<repo_name>TylerDev905/RedditService<file_sep>/RedditService/Service1.cs using System; using System.ServiceProcess; using System.Threading; using System.Configuration; using System.IO; namespace RedditService { public partial class RedditService : ServiceBase { public Timer Schedular { get; private set; } public RedditService() { InitializeComponent(); } protected override void OnStart(string[] args) { this.WriteToFile($"Reddit Bot has started!"); this.ScheduleService(); } protected override void OnStop() { this.WriteToFile($"Reddit Bot has stopped!"); this.Schedular.Dispose(); } private void WriteToFile(string text) { string path = @"C:\RedditBotLog.txt"; using (StreamWriter writer = new StreamWriter(path, true)) { writer.WriteLine(string.Format(text, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"))); writer.Close(); } } private void ScheduleService() { try { Schedular = new Timer(new TimerCallback(SchedularCallback)); string mode = ConfigurationManager.AppSettings["Mode"].ToUpper(); DateTime scheduledTime = DateTime.MinValue; if (mode == "DAILY") { scheduledTime = DateTime.Parse(ConfigurationManager.AppSettings["ScheduledTime"]); if (DateTime.Now > scheduledTime) { //If Scheduled Time is passed set Schedule for the next day. scheduledTime = scheduledTime.AddDays(1); } TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now); string schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds); this.WriteToFile("Reddit Bot scheduled to run after: " + schedule + " {0}"); //Get the difference in Minutes between the Scheduled and Current Time. int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds); //Change the Timer's Due Time. Schedular.Change(dueTime, Timeout.Infinite); } } catch(Exception ex) { WriteToFile("Reddit Bot Error on: {0} " + ex.Message + ex.StackTrace); //Stop the Windows Service. using (ServiceController serviceController = new ServiceController("SimpleService")) { serviceController.Stop(); } } } private void SchedularCallback(object state) { this.WriteToFile("Reddit Bot log: {0}"); this.ScheduleService(); } } } <file_sep>/README.md # Reddit service [![Build status](https://ci.appveyor.com/api/projects/status/33hsoo4iig8kq9p3?svg=true)](https://ci.appveyor.com/project/TylerH/redditservice) --------------------------------------- A service that will post to reddit at a scheduled time. This will be used for posting the day to day scrum messages used by the ROME Baseline team. ## How to install? * Open Visual Studios Developer Console * Change directory to the compiled service folder * Type the following ``` InstallUtil.exe "RedditService.exe" ```
ea12d5bf5f323730e3b1847cd2b93009a7acb294
[ "Markdown", "C#" ]
2
C#
TylerDev905/RedditService
48862abb18bb6e5508eb485cccc17ceed888bb01
c46a3e39a9d20a08bee45ca63b13e190077b52c2
refs/heads/master
<repo_name>geebaa/utils<file_sep>/README.md # utils this LRUCache is unconventional way of LRU eviction using priorityqueue and maintaining once own time domain. <file_sep>/lru_cache.cpp #include <bits/stdc++.h> using namespace std; // comparator class for min_heap using priority queue class Compare { public: bool operator() (pair<unsigned long long , int> &v1, pair<unsigned long long , int> &v2) { return v1.first > v2.first; } }; class LRUCache { private: int n; // Max number of elements in cache unordered_map<int,pair<unsigned long long , int> > kv; // map of key to a pair <time,val> // min_heap implementation for LRU priority_queue<pair<unsigned long long , int >,vector < pair<unsigned long long , int > >,Compare> min_heap; unordered_map<int,pair<unsigned long long , int> >::iterator itr; public: // keeps track of time and rollover of time not handled by // this class. Rollover of time requires a rebuild of the existing map "kv" and priority_queue min_heap static unsigned long long curr_time; LRUCache(int capacity) { n=capacity; LRUCache::curr_time=0; } // O(1) get // broadly takes care of 2 conditions // 1) element in cache // 2) element not in cache int get(int key) { itr=kv.find(key); pair<unsigned long long , int> val; if(itr==kv.end()){ return -1; }else{ //update timestamp itr->second.first = LRUCache::curr_time++; val=itr->second; return val.second; } } // O(log(n)) put // boardly takes care of below 3 conditions // 1) key exists , // 2) key does not exist and cache is full // 3) key does not exist and cache has space. void put(int key, int value) { itr=kv.find(key); if(itr != kv.end()){ // if key already exisits just update value and timestamp in the map itr->second.first = LRUCache::curr_time++; itr->second.second = value; }else if(kv.size() == n){ // find a replacement pair<unsigned long long , int> pq_top; pair<unsigned long long , int> map_kv; pq_top = min_heap.top(); map_kv=kv[pq_top.second]; while(pq_top.first < map_kv.first){ // we had a get that is after the put. update the ts in min_pq // pop the element and push with new timestamp min_heap.pop(); pq_top.first=map_kv.first; min_heap.push(pq_top); // check the current pq_top = min_heap.top(); map_kv=kv[pq_top.second]; } // LRU is pq_top, remove the element from min_heap min_heap.pop(); // remove the old element from map kv.erase(pq_top.second); // update the time for new values unsigned long long time; time = LRUCache::curr_time++; // push the new element into min_heap pq_top.first=time; pq_top.second=key; min_heap.push(pq_top); // insert the new element into map pair<unsigned long long , int> ts_val; ts_val.first=time; ts_val.second=value; kv[key]=ts_val; }else{ // insert into min_heap and map pair<unsigned long long , int> ts_val; pair<unsigned long long , int> ts_key; unsigned long long time; time = LRUCache::curr_time++; ts_val.first=time; ts_val.second=value; ts_key.first=time; ts_key.second=key; kv[key]=ts_val; min_heap.push(ts_key); } } };
e80cb5e6f23aa0bcf53b1cb046974b42e370c9e7
[ "Markdown", "C++" ]
2
Markdown
geebaa/utils
4b105123495062eddb0f9ed92387d042c6b69270
d1a9a9a8aa6742c59e04ae88a6d47679c1225669
refs/heads/master
<file_sep>## 前言 ### 1-IT机房简介 在一些安全要求比较高的企业,比如电信、网通、移动等,都有自己的独立服务器,而不是使用阿里云、腾讯云之类的第三方服务器。 这种大企业的服务器可能很多,需要装进IT 机柜里。 一般小点的企业的服务器需要二三十个机柜,而大的则需要上千个机柜。 IT 机房就是用于放置这些机柜的房间。 ### 2-三维IT机房 随着科技的进步和信息化进程的推进,IT机房的重要性越来越高,企业需要对IT机房进行更加妥善的管理和监控,比如实时监控机房的温度和湿度。 现在市面上好点的IT 机柜都可以将其内部数据同步到服务端,这个时候,虚拟现实的三维IT机房便有了用武之地。 三维IT机房可以将机房数据可视化,让企业更好的监控和管理IT 机柜。 ### 3-项目需求 当前这个项目先不整太复杂了,毕竟现在还是入门阶段,以后再逐步深入。 咱们先说几个IT 机房的几个常见功能: 1. 在前端页面对IT 机房进行三维展示。 2. 当鼠标划入IT 机柜的时候,提示当前机柜的详细信息。 3. 一键显示机房中过热的机柜。 ## 三维建模 #### 1-1-建模思路 - 简化模型,能用贴图表现的细节,就用贴图。这样可提高渲染速度。 - 将光效融入贴图中,即模型贴图后便具备光效和体感。这样在three 中就无需打灯,即可提高开发速度,亦可提高渲染效率。 #### 1-2-建模软件 现在市面上可以3d建模的软件有很多,**3DsMax**、**ZRender**、**C4D** 都可以。 3dsMax 相对更复杂一些,不过因为我大学就是学的这个,所以就用3dsMax建模了。 注:3dsMax v2018,无法导出gltf 文件,所以还需要安装一个[gltf 文件导出插件](https://github.com/KhronosGroup/glTF/)。 具体的建模和导出gltf 的过程,我先不做具体讲解,因为一般公司都是有专门的建模师。 等实战案例结束后,我会作为扩展内容,在视频里给大家演示一下建模和导出gltf 的过程。 #### 1-3-模型文件 GLTF 模型文件包含了整个场景的数据,比如几何体、材质、动画、相机等。 GLTF 模型在使用起来,要比传统的obj 模型方便很多。 在导出GLTF模型后,一般会包含以下文件: - gltf 模型文件 - bin文件 - 贴图文件 #### 1-4-规范模型的结构和命名 在建模软件中,同一类型的模型文件可以放入一个数组里,数组可以多层嵌套。 当前的机房模型比较简单,我就没有使用数组,所有的Mesh对象都是平展开的。 为了便于访问和区分模型,需要对模型进行规范命名,如机房中的IT机柜都是按照cabinet-001、cabinet-002、cabinet-003 命名的。 假设IT机柜的名称都是唯一的,那我们便可以基于这个名称从后端获取相应机柜的详细信息。 ## 总结 三维机房对象MachineRoom是最核心部分, MachineRoom 就是图形组件,它有两种职责: - 提供与图形相关的操作,比如场景搭建,模型加载,模型选择,场景渲染等。 - 提供与前端交互的接口,比如鼠标在机柜上的划入、划出和移动事件。 图形组件尽量不要参与前端的业务逻辑,比如参与前端数据解析和存储,参与前端DOM元素的交互操作…… 图形组件与前端页面的分离,会带来以下好处: - 可以明确WebGL工程师与react、vue等主流前端工程师的分工。 由于图形学的水很深,当我们专心于图形学的学习时,短时间内,往往会忽略对react、vue等主流框架的研究。 图形组件与前端页面的分离,可以让我们专精与我们擅长的领域。在项目开发的时候,我们只需要与主流前端工程师做好接口对接就好。 - 降低图形组件与前端业务逻辑的耦合度,降低前端业务需求的频繁修改对图形组件的影响。 有些大厂,涉及的业务逻辑复杂了,频繁改需求、改数据结构、改接口都是很正常的,若图形组件与前端业务逻辑混为一体,那WebGL工程师的工作就会很焦灼。 WebGL工程师与react、vue等主流前端工程师有了明确分工之后,便需要考虑团队协作。 现在在大厂里,一般主流的前端工程师比较好找,而有结实的图形学基础和实战经验的WebGL工程师却很难找。 所以,在一个以三维图形为主导的项目中,一个优秀的WebGL工程师会有很高的话语权,甚至可以让整个前端、后端都围绕他转。 ​ 不过,若WebGL工程师不精通项目工程化、不精通主流前端框架,建议不要主导整个项目的开发,也不要承担下自己不擅长的东西,只要一心一意的做好自己擅长的图形组件,与团队做好交流沟通即可。这样既省心,又省力。 ​ 后面,我们还可以一键显示机房中过热的机柜,这个原理和机柜的高亮是一样的,为其换一个偏红色调的贴图即可,若是我们用这种渲染三维机房的方式渲染室内设计,然后把效果图拿给业主看,那这单子肯定会搞砸了。 这是因为这种三维机房的渲染效果还是太假了。 ​ 因此,我们要不要让一个三维项目渲染得更加逼真,还是要看项目需求的。 比如这个三维机房,更多的是示意性的,若是将其整得太逼真,让它实时光线追踪,那交互起来就可能会卡。 若只是想渲染一张效果图给业主看,那咱们就得全心全意多花点时间,把一帧渲好了就行。 <file_sep>const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); module.exports = { // 开发模式 mode: 'development', // dev // 输入 entry: { // 入口文件 main: './src/main.ts', home: './src/ts/home.ts', demo: './src/ts/demo.ts', }, // 输出 output: { // 输出文件 filename: '[name].js', // filename: '[name]-[hash:6].js', // 命名时,拼接hash值太长,可以指定hash值的长度,这里设为只要前6位hash值 // 输出路径 // path: path.join(__dirname, 'dist') path: path.resolve(__dirname, './dist/js') }, // 开发工具(源代码映射关系) devtool: 'inline-source-map', // resolve: { // // 后缀别名 // extensions: ['.js', '.ts', '.tsx'] // }, // loader模块管理(核心) module: { rules: [ // { // test: /\.css$/, // use: [ // { // loader: 'style-loader', // options: { // injectType: 'singletonStyleTag' // 将所有的style标签合并成⼀个 // } // }, // 'css-loader', // ] // }, { test: /\.tsx?$/, // 解析 ts 或 tsx 文件 loader: 'ts-loader' } ] }, // 插件 plugins: [ // 处理html文件 new HtmlWebpackPlugin({ template: './src/view/box.html', filename: path.resolve(__dirname, './dist/index.html'), }), new HtmlWebpackPlugin({ title: '首页', template: './src/view/home.html', filename: path.resolve(__dirname, './dist/page/home.html'), chunks: ['home'] }), new HtmlWebpackPlugin({ title: '关于', template: './src/view/about.html', filename: path.resolve(__dirname, './dist/page/about.html'), chunks: ['about'] }), // 清除dist文件夹中冗余、重复的文件 new CleanWebpackPlugin(), ], // 开发Web服务器 devServer: { static: './dist', host: 'localhost', open: true, port: '3000', // proxy: [ // { // target: 'http://www.xxx.com/index.php', // secure: false // } // ] }, }<file_sep># React ## 用于构建用户界面的 JavaScript 库 #### [React 官方文档 ](https://react.docschina.org/)、[Create React App 中文文档](https://create-react-app.bootcss.com) > # [快速开始 – React](https://react.docschina.org/docs/getting-started.html) #### ## 安装React ```shell # 创建项目 注:在命令后面加上 --template typescript 参数表示使用ts、tsx进行开发(默认js、jsx) # 用npx创建 npx create-react-app my-App --template typescript # 用npm创建 npm init react-app my-App # 用yarn创建 yarn create react-app my-App # 启动项目 cd my-App npm start # 启动开发服务器, 然后打开 http://localhost:3000/ 查看应用。 # 项目打包 npm run build # 将应用程序捆绑到用于生产的静态文件中。 # 启动测试运行器 npm run test # 项目解构 npm run eject # 注:该命令会:删除此工具并复制构建依赖项、配置文件,并将脚本放入应用程序目录。 注:该操作是不可逆的!! # 在VS Code中安装tsx代码提示、格式化插件: 插件名:Prettir - Code formatter ``` ### 项目目录 ```tex my-App ├── node_modules ├── .gitignore ├── public │ ├── favicon.ico │ ├── index.html │ ├── manifest.json │ └── robots.txt ├── src ├── App.css ├── App.tsx ├── App.test.tsx ├── index.css ├── index.tsx ├── logo.svg ├── react-app-env.d.ts ├── reportWebVitals.ts └── setupTests.ts ├── README.md └── package.json ``` ## 安装Three.js相关依赖 ```shell # 安装Three.js npm install three -S yarn add three -S # 安装Three.js类似注解 npm install @types/three -D ``` #### 设置tconfig.jon ```json { "compilerOptions": { "target": "ES6", "module": "ES6" "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, - "strict": true, //删除这项,以免影响three.js开发 "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx" }, "include": [ "src" ] } ``` <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>HTML5-WebGL</title> <style> body { margin: 0; padding: 0; overflow: hidden; } #canvas { /* width: 100vw; height: 100vh; */ background-color: indigo; /*点击穿透*/ /* pointer-events: none; */ } </style> </head> <body> <canvas id="canvas" width="300" height="150"> 对不起!当您能看到这句话时,表示您当前的浏览器不支持canvas标签(IE9级以上才兼容),建议您升级浏览器后再试! canvas尺寸:默认大小:宽300px, 高150px,最大尽量在4096px以内(当然不同的浏览器也会不一样); canvas尺寸设置:建议直接在canvas标签上设置,或者是在js中的canvas.width/height上设置,不建议在CSS样式中设置,但(在CSS中的优先级最高); Canvas的精彩: Canvas精彩之处在于程序算法和艺术的结合。 它可以用理性的逻辑算法来寻找艺术中美的规律。 若想深入研究Canvas,可以再学习图形架构、图像算法、动画算法、艺术设计等。 相关文档:http://www.webgl3d.cn 相关库:https://threejs.org/ </canvas> <script type="module"> // 获取画布DOM const canvas = document.querySelector('#canvas'); const [width, height] = [window.innerWidth, window.innerHeight]; // 设置画布宽高 canvas.width = width; canvas.height = height; // 获取canvas二维绘图上下文对象 // const ctx = canvas.getContext('2d'); // console.dir(ctx); // 注:canvas.getContext('2d') 和 canvas.getContext('webgl') 不可并存,它们谁在前,谁优先!! // 获取webgl 三维绘图上下文对象 // const gl = canvas.getContext('3d'); // 注:没有3d哦,3d就是webgl!! const gl = canvas.getContext('webgl'); console.dir(gl); // 设置清空绘图区的颜色 // gl.clearColor(red, green, blue, alpha); 注:值为:0-1 gl.clearColor(0, 1, 0, 1); console.log(gl.clear); // gl.COLOR_BUFFER_BIT 颜色缓冲区 console.log(gl.COLOR_BUFFER_BIT); // 使用上面设置的颜色,清空绘图区 gl.clear(gl.COLOR_BUFFER_BIT); setInterval(() => { gl.clearColor(Math.random(), Math.random(), Math.random(), 1); gl.clear(gl.COLOR_BUFFER_BIT); }, 1000); </script> </body><file_sep>/** * 封装多边形对象 * 注:这个Poly类和之前的Poly类是很不一样的, * 因为这里的source数据源是将顶点数据,颜色数据合并到一起了 */ // 防止默认数据在 Poly类实例化时被修改,所以将 const defAttr = () => ({ gl: null, // webgl上下文对象 type: 'POINTS', // 绘图模式 source: [ // 数据源 // x y r, g, b, a // 0.0, 0.2, 1.0, 0.0, 0.0, 1.0, // => rgba(255, 0, 0, 1) 红 // -0.2, -0.1, 0.0, 1.0, 0.0, 1.0, // => rgba(0, 255, 0, 1) 绿 // 0.2, -0.1, 0.0, 0.0, 1.0, 1.0, // => rgba(0, 0, 255, 1) 蓝 ], sourceSize: 0, // 数据源尺寸(顶点数量) elementBytes: 4, // 元素字节数 categorySize: 0, // 类目尺寸 attributes: { // 属性集合 // a_Position: { // 对应的attribute变量名 // size: 3, // 系列尺寸 // index: 0 // 系列元素索引位置 // } }, uniforms: { // 变量集合 // u_Color: { // 对应的uniform变量名 // type: 'uniform1f', // 变量的修改方法 // value: 1 // uniform的变量值 // }, }, maps: { // u_Sampler:{ // image, // format, // wrapS, // wrapT, // magFilter, // minFilter // }, } }); export default class Poly { constructor(attr) { // 如果实例化时传了数据,就以传的数据为准,如果没传就以上面的默认数据为准备 Object.assign(this, defAttr(), attr); this.init(); }; /** * init() 初始化方法 */ init() { if (!this.gl) { return } this.calculateSize(); this.updateAttribute(); this.updateUniform(); this.updateMaps(); }; /** * 基于数据源计算类目尺寸、类目字节数、顶点总数 */ calculateSize() { const { attributes, elementBytes, source } = this; let categorySize = 0; Object.values(attributes).forEach(ele => { const { size, index } = ele; categorySize += size; // 类目尺寸 = 一个类目中所有分量的等数(列) ele.byteIndex = index * elementBytes; }); this.categorySize = categorySize; // 类目尺寸 this.categoryBytes = categorySize * elementBytes; this.sourceSize = source.length / categorySize; }; /** * 更新attribute 相关变量 */ updateAttribute() { const { gl, attributes, categoryBytes, source } = this; // 建立顶点缓冲区对象 const sourceBuffer = gl.createBuffer(); // 绑定缓冲对象( https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindBuffer) gl.bindBuffer(gl.ARRAY_BUFFER, sourceBuffer); // 向缓冲区写入数据 // gl.bufferData(target, size, srcData Optional, usage, srcOffset, length Optional); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(source), gl.STATIC_DRAW) // 循环解构attribute变量 for (let [key, { size, byteIndex }] of Object.entries(attributes)) { const attr = gl.getAttribLocation(gl.program, key); // gl.vertexAttribPointer(index, size, type, normalized, stride, offset); gl.vertexAttribPointer( attr, // attribute 变量,具体而言是指向存储attribute 变量的空间的指针 size, // 系列尺寸,如:顶点、颜色等 gl.FLOAT, // 元素的数据类型,如:int 整型、浮点型等 false, // 是否归一化 categoryBytes,// 类目字节数 byteIndex // 系列索引位置,如:顶点、颜色等的索引位置 ); // 赋能 (开起多点批处理) gl.enableVertexAttribArray(attr); } }; /** * 更新uniform变量 */ updateUniform() { const { gl, uniforms } = this; for (let [key, val] of Object.entries(uniforms)) { const { type, value } = val; const u = gl.getUniformLocation(gl.program, key); if (type.includes('Matrix')) { gl[type](u, false, value); } else { gl[type](u, value); } } }; /** * */ updateMaps() { const { gl, maps } = this Object.entries(maps).forEach(([key, val], ind) => { const { format = gl.RGB, image, wrapS, wrapT, magFilter, minFilter } = val gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1) gl.activeTexture(gl[`TEXTURE${ind}`]) const texture = gl.createTexture() gl.bindTexture(gl.TEXTURE_2D, texture) gl.texImage2D( gl.TEXTURE_2D, 0, format, format, gl.UNSIGNED_BYTE, image ) wrapS && gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS ) wrapT && gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT ) magFilter && gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter ) if (!minFilter || minFilter > 9729) { gl.generateMipmap(gl.TEXTURE_2D) } minFilter && gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter ) const u = gl.getUniformLocation(gl.program, key) gl.uniform1i(u, ind) }) }; // 执行绘图方法 draw(type = this.type) { const { gl, sourceSize } = this; gl.drawArrays(gl[type], 0, sourceSize); /** * 绘制顶点方法 drawArrays() * gl.drawArrays(mode, first, count); 方法用于从向量数组中绘制图元。 * * // https://developer.mozilla.org/zh-CN/docs/Web/API/WebGLRenderingContext/drawArrays * * 参数说明: * mode 【绘图模式】指定绘制图元的方式,可能值如下: * 点: * gl.POINTS: 绘制一系列点。 * * 线: * gl.LINES: 绘制一系列单独线段。每两个点作为端点,线段之间不连接。 * gl.LINE_STRIP: 绘制一个线条。即,绘制一系列线段,上一点连接下一点。 * gl.LINE_LOOP: 绘制一个线圈。即,绘制一系列线段,上一点连接下一点,并且最后一点与第一个点相连。 * * 面: * gl.TRIANGLES: 绘制一系列三角形。每三个点作为顶点 * gl.TRIANGLE_STRIP:绘制一个三角带。 * gl.TRIANGLE_FAN:绘制一个三角扇。 * * first【绘图起点】 指定从哪个点开始绘制。 * count 【绘制数量】指定绘制需要使用到多少个点。 **/ } };<file_sep> /** * GLTF三维模型 类 * 初始化传入 canvas节点、三维模型 */ // Three.js基础对象 import { Scene, WebGLRenderer, Mesh, MeshBasicMaterial, MeshStandardMaterial, PerspectiveCamera, Raycaster, Vector2, Texture, TextureLoader, Color } from 'three'; // GLTF模型加载器 import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; // 轨道控制器 import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; // 实例化GLTF模型加载器 const GLTFL: GLTFLoader = new GLTFLoader(); // 提前实例化射线投射器,以免重复实例化 // 射线投射器可基于鼠标或相机,在世界坐标系内建立一条射线,用于选中模型 const raycaster = new Raycaster(); // 鼠标在裁剪空间中的点位 const mousePointer = new Vector2(); export default class MachineRoom { // 场景 public scene: Scene; // 相机 public camera: PerspectiveCamera; // 相机轨道控制器 public controls: OrbitControls; // webgl渲染器 public renderer: WebGLRenderer; // 三维模型存放路径 public modelPath: string; // 纹理集合(用于存放图像源) public imgMaps: Map<string, Texture> = new Map(); /** * 给机房添加两个属性,三个鼠标事件 */ // 机柜集合 public cabinetArr: Mesh[] = []; // 鼠标当前移入的机柜 public cabinetNow: Mesh | any; // 鼠标移入机柜的事件 // public onMouseOverCabinet = (cabinet: Mesh, index: number) => { }; public onMouseOverCabinet = (cabinet: any, count: number, index: number) => { }; // 鼠标在机柜上移动的事件(根据鼠标在canvas画布上的坐标位) public onMouseMoveCabinet = (x: number, y: number) => { }; // 鼠标移出机柜的事件 public onMouseOutCabinet = () => { }; // 初始化场景 constructor(canvas: HTMLCanvasElement, modelPath: string = '../models/') { this.scene = new Scene(); this.renderer = new WebGLRenderer({ canvas }); this.modelPath = modelPath; this.camera = new PerspectiveCamera( 45, canvas.width / canvas.height, 0.1, 1000 ); this.camera.position.set(0, 10, 15); // x, y, z this.camera.lookAt(0, 0, 0); this.controls = new OrbitControls( this.camera, this.renderer.domElement ); // 提前添加一个高亮贴图,方便鼠标移入机柜时直接更换高亮贴图,不用再新创建贴图 this.newTexture('cabinet-red.jpg'); this.newTexture('cabinet-green.jpg'); this.newTexture('cabinet-blue.jpg'); }; // 建立纹理对象 newTexture(imgName: string) { // 基于图像原名称,获取纹理对象 let newTexture = this.imgMaps.get(imgName); // 如果不存在就建立纹理对象 if (!newTexture) { // 加载纹理对象 newTexture = new TextureLoader().load(this.modelPath + imgName); // 修改纹理对象属性 newTexture.flipY = false; // Y不翻转 newTexture.wrapS = 1000; // 在S方向重复1000 newTexture.wrapT = 1000; // 在T方向重复1000 // 将新建立的纹理对象存入集合 this.imgMaps.set(imgName, newTexture); } return newTexture; }; // 修改材质() setMaterial(obj: Mesh, map: any, color: Color) { // 判断如果有贴图(图像原)的材质时, if (map) { obj.material = new MeshBasicMaterial({ map: this.newTexture(map.name) }); } // 没有贴图(纯色)的材质时 else { obj.material = new MeshBasicMaterial({ color }); } } // 加载GLTF模型 loadGLTF(model: string) { // GLTFL.load( // model, // ({ scene: { children } }) => { // this.scene.add(...children); // } // ) // GLTFL.load(url, onLoad, onProgress, onError) GLTFL.load( // 模型资源网址 this.modelPath + model, // '../models/machineRoom.gltf', // load加载资源时调用 (gltf) => { const { scene, scene: { children } } = gltf; // console.log(children); /** * gltf.scene.children * 注:默认是标准材质,ytpe:"MeshStandardMaterial" 它具有光照效果,但会使贴图颜色变深!! * * 由于这里不需要光照效果,所有用this.setMaterial()方法将标准材质:MeshStandardMaterial,改为基础网络材质:MeshBasicMaterial,因为它不受光照效果的影响 * */ children.forEach((obj: any) => { const { color, map, name } = obj.material as MeshStandardMaterial; // 修改材质,解决颜色变深的问题,恢复到原有图像源的状态 this.setMaterial(obj, map, color); // 将所有机柜存入机柜集合,注:obj.name.includes('cabinet') 是在建模的时候就将所有机柜的命名都以cabinet开头!! if (obj.name.includes('cabinet')) { // 自定义数据 这里可以用API形式请求数据 obj.temperature = parseInt((Math.random() * 40).toString()); // 机柜温度 if (obj.temperature > 36) { obj.material.setValues({ map: this.imgMaps.get('cabinet-red.jpg') }) } // 将所有机柜存入机柜集合 this.cabinetArr.push(obj); } }); // 添加场景 this.scene.add(scene); // gltf.animations; // Array<THREE.AnimationClip> // gltf.scene; // THREE.Group // gltf.scenes; // Array<THREE.Group> // gltf.cameras; // Array<THREE.Camera> // gltf.asset; // Object }, // 在加载过程中调用 (xhr) => { // console.log('已加载:', (xhr.loaded / xhr.total * 100) + '%', xhr); }, // 加载出错时调用 (error) => { console.error('GLTF模型文件加载出错,请在public目录中也添加一份models模型:', error); } ); }; // 选择机柜 selectCabinet(x: number, y: number) { const { imgMaps, cabinetArr, cabinetNow, renderer, camera } = this; const { width, height } = renderer.domElement; // 就是canvas标签DOM // cnavas坐标 转 webgl裁剪坐标 mousePointer.set( (x / width) * 2 - 1, -(y / height) * 2 + 1 ); // 基于鼠标点的裁剪坐标和相机设置射线投射器 raycaster.setFromCamera(mousePointer, camera); // 选择机柜, 在机柜集合中选择模型,返回的是一个数组,取第1个模型 const intersect = raycaster.intersectObjects(cabinetArr)[0]; // 如果有即到模型就获取模型下面的object,没有就为null let cabinetObj: any = intersect ? intersect.object as Mesh : null; // 如果之前已经有机柜被选中,并且不等于当前所选择的机柜,就取消之前选中的机柜的高亮 if (cabinetNow && cabinetNow !== cabinetObj) { const material = cabinetNow.material as MeshBasicMaterial; material.setValues({ map: imgMaps.get('cabinet.jpg'), // map: cabinetObj.temperature > 36 ? imgMaps.get('cabinet-red.jpg') : imgMaps.get('cabinet.jpg'), }); } // 如果当前所选中的机柜对象不为空时 if (cabinetObj) { // 触发鼠标在机柜上移动事件 this.onMouseMoveCabinet(x, y); // 如果当前所选中的机柜对象不等于上一次的机柜对象时 if (cabinetNow !== cabinetObj) { // 更新选中机柜对象 this.cabinetNow = cabinetObj; // 将选中机柜对象设置高亮 const material = cabinetObj.material as MeshBasicMaterial; material.setValues({ map: cabinetObj.temperature > 36 ? imgMaps.get('cabinet-red.jpg') : imgMaps.get('cabinet-blue.jpg'), }); // 触发鼠标移入机柜事件 this.onMouseOverCabinet(cabinetObj, cabinetArr.length, cabinetArr.indexOf(cabinetObj) + 1); } } // 如果上一次所选中的机柜对象存在时 else if (cabinetNow) { // 置空机柜对象 this.cabinetNow = null; // 触发鼠标移出机柜事件 this.onMouseOutCabinet(); } }; // 连续渲染 animateRender() { this.renderer.render(this.scene, this.camera); requestAnimationFrame(() => { this.animateRender(); }) }; }<file_sep>/** * 封装多边形对象 */ // 防止默认数据在 Poly类实例化时被修改,所以将 const defAttr = () => ({ gl: null, // webgl上下文对象 pointsArr: [], // 顶点数据集合,在被赋值的时候会做两件事, 1、更新count 顶点数量,数据运算尽量不放渲染方法里。2、向缓冲区内写入顶点数据 geoData: [], // 模型数据,对象数组,可解析出pointsArr 顶点数据 size: 3, // 顶点分量的数目 positionName: 'a_Position', // 代表顶点位置的attribute 变量名 count: 0, // 顶点数量 types: ['POINTS'], // 绘图方式,可以用多种方式绘图 circleDot: false, // 绘制的是否是圆点 u_IsPOINTS: null, // 绘制的顶点类型是否是gl.POINTS类型 uniforms: {} }); export default class Poly { constructor(attr) { // 如果实例化时传了数据,就以传的数据为准,如果没传就以上面的默认数据为准备 Object.assign(this, defAttr(), attr); this.init(); }; /** * init() 初始化方法,建立缓冲对象,并将其绑定到webgl 上下文对象上,然后向其中写入顶点数据。将缓冲对象交给attribute变量,并开启attribute 变量的批处理功能。 */ init() { const { gl, size, positionName, circleDot } = this; if (gl) { // 创建缓冲对象 // https://developer.mozilla.org/zh-CN/docs/Web/API/WebGLRenderingContext/createBuffer const vertexBuffer = gl.createBuffer(); // 方法可创建并初始化一个用于储存顶点数据或着色数据的WebGLBuffer对象 // 绑定缓冲对象 到 webgl 上下文对象中 gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); this.updateBuffer(); // 获取顶点着色器存储空间 attribute 中gl_Position声明的的a_Position变量; const gl_Position = gl.getAttribLocation(gl.program, positionName); // 修改 顶点着色器存储空间 变量; gl.vertexAttribPointer(gl_Position, size, gl.FLOAT, false, 0, 0); // 赋能-批处理(如果有多个顶点时,需要批处理) gl.enableVertexAttribArray(gl_Position); // 如果绘制的是圆点,就获取一下在片元着色器中用uniform声明的 u_IsPOINTS变量 if (circleDot) { this.u_IsPOINTS = gl.getUniformLocation(gl.program, 'u_IsPOINTS'); } this.updateUniform(); } }; /** * 更新顶点数量 */ updateCount() { this.count = this.pointsArr.length / this.size; }; /** * 更新缓冲区数据,同时更新顶点数量 */ updateBuffer() { const { gl, pointsArr } = this; this.updateCount(); // 向缓冲对象写入(修改)数据 // gl.bufferData(target, size, srcData Optional, usage, srcOffset, length Optional) gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(pointsArr), gl.STATIC_DRAW); }; /** * 基于geoData 解析出pointsArr 数据 * @param {*} params */ updatePointsArr(params) { const { geoData } = this; const pointsArr = []; geoData.forEach(data => { params.forEach(key => { pointsArr.push(data[key]) }); }); this.pointsArr = pointsArr; }; /** * 更新,修改Uniform变量 */ updateUniform() { const { gl, uniforms } = this; for (const [key, val] of Object.entries(uniforms)) { const { type, value } = val; const u = gl.getUniformLocation(gl.program, key); if (type.includes('Matrix')) { gl[type](u, false, value); } else { gl[type](u, value); } } } /** * 添加顶点 * @param {...any} params */ addPointsArr(...params) { this.pointsArr.push(...params); this.updateBuffer(); }; /** * 删除最后一个顶点 */ popPointsArr() { const { pointsArr, size } = this; const len = pointsArr.length; pointsArr.splice(len - size, len); this.updateCount(); }; /** * 根据索引位置设置顶点 * @param {*} ind * @param {...any} params */ setPointsArr(ind, ...params) { const { pointsArr, size } = this; const i = ind * size; params.forEach((param, paramInd) => { pointsArr[i + paramInd] = param; }); }; // 执行绘图方法 draw(types = this.types) { const { gl, count, circleDot, u_IsPOINTS } = this; for (let type of types) { // 如果绘制的是圆点,就将 u_IsPOINTS 变量设为true, 反之则设为false; circleDot && gl.uniform1f(u_IsPOINTS, 'POINTS' === type); gl.drawArrays(gl[type], 0, count); } }; };<file_sep>import { BoxGeometry, Mesh, MeshNormalMaterial, PerspectiveCamera, Scene, WebGLRenderer } from 'three'; // 获取canvas画布 const canvas = <HTMLCanvasElement>document.querySelector('#canvas'); // 获取可视区宽高 const [width, height] = [window.innerWidth, window.innerHeight]; // 设置canvas宽高 canvas.width = width; canvas.height = height; /** * 场景 **/ // 场景创建 const scene = new Scene(); // 创建相机 const camera = new PerspectiveCamera( 75, // 垂直夹角 width / height, // 视口宽高比 0.1, // 近三角面 1000 // 远三角面 ); // 创建渲染器 const render = new WebGLRenderer({ canvas }); /** * 三维立方体 **/ // 创建几何体 const geo = new BoxGeometry(); // 创建材质 const mat = new MeshNormalMaterial(); // const mat = new MeshBasicMaterial( { color: 0x00ff00 } ); // 创建网格 const cube = new Mesh(geo, mat); /** * 把三维立方体 添加到场景中后渲染 **/ scene.add(cube); // 改变相机z轴大小(由于默认为0,是看不到三维效果) camera.position.z = 5; camera.position.x = 0; // 渲染 render.render(scene, camera); /** * 连续渲染动画 **/ (function animate() { // cube.position.x += 0.01; // cube.position.y += 0.01; cube.rotation.x += 0.01; cube.rotation.y += 0.01; // console.log('矩阵', cube.matrix.elements); render.render(scene, camera); requestAnimationFrame(animate); })();<file_sep>/** * 容器对象: * 如果要绘制多线,那就需要有个容器来承载它们,这里用Sky来作为承载多边形的容器。 */ export default class Sky { constructor(gl) { this.gl = gl; // webgl上下文对象 this.children = []; // 子级 }; /** * 添加子对象 * @param {*} obj */ add(obj) { obj.gl = this.gl; this.children.push(obj); }; /** * 更新子对象的顶点数据 * @param {*} attr */ updatePointsArr(attr) { this.children.forEach(item => { item.updatePointsArr(attr); }); }; /** * 遍历子对象绘图 */ draw() { this.children.forEach(item => { // 每个子对象对应一个buffer 对象,所以在子对象绘图item.draw();之前要先初始化。 item.init(); item.draw(); }); } };<file_sep> // https://blog.csdn.net/Javon_huang/article/details/122252177 // import { BrowserRouter, HashRouter, useRoutes } from 'react-router-dom'; // import { Suspense, lazy } from 'react' // const routes = [ // { // path: '/', // auth: false, // component: lazy(() => import('../pages/Login')) // }, // { // path: '/Main', // auth: true, // component: lazy(() => import('../pages/Main')), // children: [ // { // path: '/Main/Home', // auth: true, // component: lazy(() => import('../pages/Main/Home')) // }, // { // path: '/Main/Test/:id', // auth: true, // component: lazy(() => import('../pages/Main/Test')) // }, // { // path: '/Main/*', // auth: false, // component: lazy(() => import('../pages/404')) // } // ] // }, // { // path: '*', // auth: false, // component: lazy(() => import('../pages/404')) // } // ]; // //根据路径获取路由 // const checkAuth = (routers: any, path: String) => { // for (const data of routers) { // if (data.path == path) return data // if (data.children) { // const res: any = checkAuth(data.children, path) // if (res) return res // } // } // return null // } // // 路由处理方式 // const generateRouter = (routers: any) => { // return routers.map((item: any) => { // if (item.children) { // item.children = generateRouter(item.children) // } // item.element = <Suspense fallback={ <div>加载中...</div>}><item.component /></Suspense> // return item; // }) // } // const Router = () => useRoutes(generateRouter(routes)) // const checkRouterAuth = (path: String) => { // let auth = null // auth = checkAuth(routes, path) // return auth // } // export { Router, checkRouterAuth } export default {}; <file_sep>const demo: string = '我是一个字符串'; console.log(demo);<file_sep># WebGL > webgl 是在网页上绘制和渲染三维图形的技术! <file_sep>## 用Webpack + Ts 开发Three # Webpack + TS +Three.js #### [Three.js 官网](https://threejs.org),[Three.js 文档](https://threejs.org/docs/index.html#manual/zh/introduction/Creating-a-scene),[Three.js 实例](https://threejs.org/examples/#webgl_animation_keyframes)、[Three.js 编辑器](https://threejs.org/editor)、[Three.js GitHub)](https://github.com/mrdoob/three.js) > Three.js是基于 WebGL 封装的第三方库,就相当于jQuery和Js! #### 1、创建项目目录、初始化npm ```shell # 在指定的目录中打开命令工具 mkdir myProject // 创建项目目录 cd myProject npm init -y // 初始化npm, -y参数表示:快速生成默认的package.json文件 ``` #### 2、安装webpack、ts、three相关依赖 ```shell # 1、安装webpack npm install webpack-dev-server webpack-cli webpack -D # -D === --save-dev 只在开发时使用 # 2、安装ts npm i ts-loader typescript --save-dev # ts-loader 将ts转为js # 3、安装three.js npm i three -S # -S === --save 在生产环境也用 npm i @types/three -D # three.ts的类型注解 # 4、设置启动命令 # 在package.json中的script选项中添加如下命令: "start": "webpack serve --open" # 完整package.json文件内容: { "name": "demo", "version": "1.0.0", "description": "用webpack+ts开发three", "main": "./dist/index.js", "private": true, "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack serve --open" }, "keywords": [ "webpack", "ts", "three.js" ], "author": "沐枫", "license": "ISC", "devDependencies": { "@types/three": "^0.139.0", "ts-loader": "^9.2.8", "typescript": "^4.6.3", "webpack": "^5.72.0", "webpack-cli": "^4.9.2" }, "dependencies": { "three": "^0.139.2" } } ``` #### 3、创建webpack、ts相关配置文件 - webpack.config.js ```js const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); module.exports = { // 开发模式 mode: 'development', // dev // 输入 entry: { '3d-box': './src/ts/3d-box.ts', }, // 输出 output: { // 输出文件 filename: '[name].js', // filename: '[name]-[hash:6].js', // 命名时,拼接hash值太长,可以指定hash值的长度,这里设为只要前6位hash值 // 输出路径 // path: path.join(__dirname, 'dist') path: path.resolve(__dirname, './dist/js') }, // 开发工具(源代码映射关系) devtool: 'inline-source-map', resolve: { // 后缀别名 extensions: ['.js', '.ts', '.tsx'] }, // loader模块管理(核心) module: { rules: [ // { // test: /\.css$/, // use: [ // { // loader: 'style-loader', // options: { // injectType: 'singletonStyleTag' // 将所有的style标签合并成⼀个 // } // }, // 'css-loader', // ] // }, { test: /\.tsx?$/, // 解析 ts 或 tsx 文件 loader: 'ts-loader' } ] }, // 插件 plugins: [ // 处理html文件 new HtmlWebpackPlugin({ // title: '3d-box', template: './src/html/3d-box.html', filename: path.resolve(__dirname, './dist/3d-box.html'), chunks: ['3d-box'] }), // 清除dist文件夹中冗余、重复的文件 new CleanWebpackPlugin(), ], // 开发Web服务器 devServer: { static: './dist', host: 'localhost', port: '3000', open: true, compress: true, headers: { 'Access-Control-Allow-Origin': '*', }, // proxy: [ // { // target: 'http://www.xxx.com', // secure: true, // changeOrigin: true, // ws: false, // pathRewrite: { // '^/api': '/', // }, // } // ] }, } ``` - tsconfig.json ```json { "compilerOptions": { "sourceMap": true, "target": "ES6", "module": "ES6" } } ``` <file_sep># Three.js #### [Three.js 官网](https://threejs.org),[Three.js 文档](https://threejs.org/docs/index.html#manual/zh/introduction/Creating-a-scene),[Three.js 实例](https://threejs.org/examples/#webgl_animation_keyframes)、[Three.js 编辑器](https://threejs.org/editor)、[Three.js GitHub)](https://github.com/mrdoob/three.js) > Three.js是基于 WebGL 封装的第三方库,就相当于jQuery和Js! ### Threejs渲染结构 ![img](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/abb6db0f056a493ca02e9124db41ba83~tplv-k3u1fbpfcp-zoom-in-crop-mark:1304:0:0:0.awebp) **Renderer(渲染器)**:用于渲染场景,webgl渲染是一帧一帧渲染的,每调用一次renderer.render(scene, camera)方法,就会重新渲染一次场景,一般情况下requestAnimationFrame每秒调用60次,因此场景渲染频率为60帧。 **Scene(场景)** :所有3d对象的容器,相当于现实中的世界。 **Camera(相机)** : 相机是观察者,相当于现实中的眼睛。常用的相机有两种,分别是 **正交投影相机(OrthographicCamera)** 和 **透视投影相机(PerspectiveCamera) ,** 在3d场景下基本都使用透视相机,透视相机有四个参数,分别如下: - fov — 摄像机视锥体垂直视野角度 - aspect — 摄像机视锥体长宽比 - near — 摄像机视锥体近端面 - far — 摄像机视锥体远端面 **Controls(控制器)** :控制器用于调整相机的位置,有了控制器就可以自由地移动视角观察模型了。 **Light(灯光):** 人之所以能看到物体,都是由于光反射到眼睛里的,因此没有灯光场景都是黑暗的。常用的光源种类有四种,分别为:环境光(AmbientLight),平行光(DirectionalLight),点光源(PointLight),聚光灯(SpotLight)。 **Mesh( 网格对象):** 网格对象由**几何体(Geometry)** 和**材质(Material)** 两部分组成,Geometry 负责几何模型,Material 负责外观样式。我们加载的模型可以看成一个**组(Group)** ,一个复杂的模型是由多个网格组合而成的,每个网格对象则相当于汽车的独立零件。 - **Geometry( 几何对象):** 几何体对象负责外形,其内部存储了顶点相关的数据,比如顶点点位、顶点索引、uv坐标等。threejs中内置了许多常用的几何体如:正方体,圆柱体,球体等,我们可通过threejs内置的几何对象构建一个简单的模型,而复杂的模型则需要建模师去建模。 - **Material(材质对象):** 材质对象负责着色,绘制几何体的表面属性,比如漫反射、镜面反射、光泽度、凹凸等。材质对象的许多属性都可以用纹理贴图表示,比如漫反射贴图、凹凸贴图等。 <file_sep>/** * 建立合成对象 */ export class Compose { constructor() { this.parent = null; // 父对象,合成对象可以相互嵌套 this.children = []; // 子对象集合,其集合元素可以是时间轨,也可以是合成对象 }; // 添加子对象方法 add(obj) { obj.parent = this; this.children.push(obj); }; // 基于当前时间更新子对象状态的方法 update(t) { this.children.forEach(ele => { ele.update(t); }); }; }; /** * 架构补间动画 * * 建立时间轨对象 */ export class Track { constructor(target) { this.target = target; // 当前对象(时间轨上的目标对象) this.parent = null; // 当前对象的父级对象 this.start = 0; // 时间轨起始时间 this.timeLen = 5; // 时长(时间轨总时长) this.loop = false; // 是否循环 this.keyMap = new Map();// 所有属性的关键帧集合 /*所有属性的关键帧集合 - 数据结构: [ [ '对象属性1', [ [时间1,属性值], //关键帧 [时间2,属性值], //关键帧 ] ], [ '对象属性2', [ [时间1,属性值], //关键帧 [时间2,属性值], //关键帧 ] ], ]*/ }; /** * 获取两个关键帧之间补间状态的方法 * * @param {*} time 本地时间 * @param {*} fms 某个属性的关键帧集合 * @param {*} last 最后一个关键帧的索引位置 * @returns */ getValBetweenFms(time, fms, last) { // 遍历所有关键帧 for (let i = 0; i < last; i++) { const fm1 = fms[i] const fm2 = fms[i + 1] // 判断当前时间在哪两个关键帧之间 if (time >= fm1[0] && time <= fm2[0]) { // 基于这两个关键帧的时间和状态,求点斜式 const delta = { x: fm2[0] - fm1[0], y: fm2[1] - fm1[1], } // 基于点斜式求本地时间对应的状态 const k = delta.y / delta.x const b = fm1[1] - fm1[0] * k return k * time + b } } }; /** * 基于当前时间更新目标对象的状态, 先计算本地时间,即世界时间相对于时间轨起始时间的的时间。若时间轨循环播放,则本地时间基于时间轨长度取余。 * * @param {*} t */ update(t) { const { target, start, loop, timeLen, keyMap } = this; // 本地时间 let time = t - start; if (loop) { time = time % timeLen; } for (const [key, fms] of keyMap) { const last = fms.length - 1; // 如果本地时间小于第一个关键帧的时间,目标对象的状态等于第一个关键帧的状态 if (time < fms[0][0]) { target[key] = fms[0][1]; //若本地时间大于最后一个关键帧的时间,目标对象的状态等于最后一个关键帧的状态 } else if (time > fms[last][0]) { target[key] = fms[last][1]; //否则,计算本地时间在左右两个关键帧之间对应的补间状态 } else { target[key] = this.getValBetweenFms(time, fms, last); } } }; };
bff13b57aaba106e149ebe49d9db5d3ff69ff730
[ "Markdown", "TypeScript", "JavaScript", "HTML" ]
15
Markdown
MuGuiLin/WebGL
5a1660703c56648b5831fc89478364c24818a4c8
c7d83025393d1a0bb7ba9bf1ea4cb13c33eb4bd6
refs/heads/main
<repo_name>nayyyhaa/minion-speaks<file_sep>/README.md # minion-speaks Want to learn Banana language? Then check out this Minion Translator which I've made. <file_sep>/App.js let inputElement = document.querySelector("#inputTxt"); let btnElement = document.querySelector("#btnElement"); let outputElement = document.querySelector("#outputTxt"); let url="https://api.funtranslations.com/translate/minion.json"; function translateURL(inputValue){ return url + "?" + "text=" + inputValue; } function mininonSpeak(){ let inputValue = inputElement.value; fetch(translateURL(inputValue)) .then(data => data.json()) .then(json => { outputElement.innerHTML=json.contents.translated }) .catch(() => alert("Minion(Server) is busy! Try after sometime")) } btnElement.addEventListener("click",mininonSpeak);
fb282a1a6a477c169f087c3652b0b86f573c629d
[ "Markdown", "JavaScript" ]
2
Markdown
nayyyhaa/minion-speaks
01926245963fcebe2f74bb09f9e214a7600a7dfd
9586be5b1e43266dbf6a103e5eecfee1d4acdb72
refs/heads/master
<file_sep>Позволяет создать БД в postgres или mssql, путем указания параметров окружения DB_TYPE (postgres или mssql),DB_HOST,DB_PORT,DB_USER,DB_PASS,DB_NAME <file_sep>using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text.Json.Serialization; namespace DBProvider.Models { public class ProbeType : IIdentifiable { [Key] public int Id { get; set; } public string Name { get; set; } public int InputMethod { get; set; } public string Description { get; set; } [JsonIgnore] public virtual ICollection<Probe> Probes { get; set; } } }<file_sep>using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text.Json.Serialization; namespace DBProvider.Models { public class Chat : IIdentifiable { [Key] public int Id { get; set; } public string Name { get; set; } public string CreatedAt { get; set; } [JsonIgnore] public virtual ICollection<Membership> Memberships { get; set; } [JsonIgnore] public virtual ICollection<Message> Messages { get; set; } public static Chat GetRandom(DbSet<Profile> profiles) { var rand = new Random(); var nameRand = new RandomNameGeneratorLibrary.PersonNameGenerator(); var memberships = new List<Membership>(); var dd = new Membership(); RandomSeeder.For(20, (_) => { var m = new Membership(); (profiles.ToList().GetRandom() as Profile).Memberships.Add(m); memberships.Add(m); }); var chat = new Chat() { Name = $"Chat{rand.Next() % 100}", CreatedAt = DateTime.Now.ToString(), Memberships = memberships, Messages = Enumerable.Range(0, rand.Next() % 50).Select(i => new Message() { Membership = memberships.GetRandom() as Membership, Text = $"Hey {nameRand.GenerateRandomFirstName()}" }).ToList() }; //memberships.All(el => { el.Chat = chat; return true; }); return chat; //var memberships = Enumerable.Range(0, rand.Next() % 20).Select(i => new Membership() { Profile = }).ToList(); } } }<file_sep>using Microsoft.EntityFrameworkCore; using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text.Json.Serialization; namespace DBProvider.Models { public class Message : IIdentifiable { [Key] public int Id { get; set; } public int MembershipId { get; set; } public string Text { get; set; } public string CreatedAt { get; set; } [JsonIgnore] public virtual Membership Membership { get; set; } public static Message GetRandom(DbSet<Membership> memberships) { var nameRand = new RandomNameGeneratorLibrary.PersonNameGenerator(); var placeRand = new RandomNameGeneratorLibrary.PlaceNameGenerator(); return new Message() { CreatedAt = DateTime.Now.ToString(), Text = $"{nameRand.GenerateRandomFirstName()} {nameRand.GenerateRandomLastName()} at {placeRand.GenerateRandomPlaceName()}", Membership = memberships.ToList().GetRandom() as Membership }; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Text.Json.Serialization; using System.Threading.Tasks; namespace DBProvider.Models { public class User : IIdentifiable { [Key] public int Id { get; set; } public string Name { get; set; } [JsonIgnore] public string PasswordHash { get; set; } [JsonIgnore] public string PasswordSalt { get; set; } public string CreatedAt { get; set; } [JsonIgnore] public virtual Profile Profile { get; set; } public static User GetRandom() { var rand = new Random(); var nameRand = new RandomNameGeneratorLibrary.PersonNameGenerator(); return new User() { Name = $"User{rand.Next() % 100}", PasswordHash = $"<PASSWORD>", PasswordSalt = $"", CreatedAt = DateTime.Now.ToString(), Profile = Profile.GetRandom() }; } } } <file_sep>using System; using System.Linq; using System.Collections.Generic; using System.Text.Json; using DBProvider.Models; namespace DbShell { class Program { static void Main(string[] args) { var db = new DBProvider.MainDBContext(); //db.Users.Add(new User() { Name = "Start" }); //db.Users.Add(new User() { Name = "Start2" }); //db.SaveChanges(); db.Users.AsEnumerable().All((el) => { Console.WriteLine(JsonSerializer.Serialize<User>(el)); return true; }); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Text.Json.Serialization; using System.Threading.Tasks; namespace DBProvider.Models { public class Membership : IIdentifiable { [Key] public int Id { get; set; } public int ProfileId { get; set; } public int ChatId { get; set; } public string Permissions { get; set; } public string LastBeenAt { get; set; } [JsonIgnore] public virtual Profile Profile { get; set; } [JsonIgnore] public virtual Chat Chat { get; set; } [JsonIgnore] public virtual ICollection<Message> Messages { get; set; } } } <file_sep>using DBProvider.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DBProvider { class RandomSeeder { public void Seed(MainDBContext db) { For(10, (_) => db.Users.Add(User.GetRandom())); db.SaveChanges(); For(10, (i) => db.Chats.Add(Chat.GetRandom(db.Profiles))); db.SaveChanges(); For(10, (i) => db.Probes.Add(Probe.GetRandom(db.Profiles))); db.SaveChanges(); } public static Action<int, Action<int>> For = (count, act) => Enumerable.Range(0, count).All((i) => { act(i); return true; }); } } <file_sep>using DBProvider.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Security.Permissions; namespace DBProvider { public class MainDBContext : DbContext { private ConnectionSettings _connectionSettings; public DbSet<User> Users { get; set; } public DbSet<Profile> Profiles { get; set; } public DbSet<Role> Roles { get; set; } public DbSet<Probe> Probes { get; set; } public DbSet<ProbeType> ProbeTypes { get; set; } public DbSet<Chat> Chats { get; set; } public DbSet<Membership> Memberships { get; set; } public DbSet<Message> Messages { get; set; } public MainDBContext() : base() { _connectionSettings = new ConnectionSettings(); Database.EnsureCreated(); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { switch (_connectionSettings.DB_TYPE) { case "mssql": optionsBuilder.UseSqlServer(_connectionSettings.ToString()); break; case "postgres": optionsBuilder.UseNpgsql(_connectionSettings.ToString()); break; default: throw new NotImplementedException("Unsupported db type"); } optionsBuilder.UseLazyLoadingProxies(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Text.Json.Serialization; using System.Threading.Tasks; namespace DBProvider.Models { public class Profile : IIdentifiable { [Key] public int Id { get; set; } public int UserId { get; set; } public int RoleId { get; set; } public string AvatarRaw { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string BirthDay { get; set; } public int Gender { get; set; } public string Description { get; set; } public string AdditionalInfo { get; set; } [JsonIgnore] public virtual Role Role { get; set; } [JsonIgnore] public virtual User User { get; set; } [JsonIgnore] public virtual ICollection<Probe> Probes { get; set; } [JsonIgnore] public virtual ICollection<Membership> Memberships { get; set; } public static Profile GetRandom() { var rand = new Random(); var nameRand = new RandomNameGeneratorLibrary.PersonNameGenerator(); return new Profile() { FirstName = nameRand.GenerateRandomFirstName(), LastName = nameRand.GenerateRandomLastName(), Gender = 2, Role = new Role() { Name=$"Role"} }; } } } <file_sep>using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Text.Json.Serialization; using System.Threading.Tasks; namespace DBProvider.Models { public class Probe : IIdentifiable { [Key] public int Id { get; set; } public int ProfileId { get; set; } public string CreatedAt { get; set; } public int ProbeTypeId { get; set; } public string Value { get; set; } [JsonIgnore] [ForeignKey(nameof(ProfileId))] public virtual Profile Profile { get; set; } [JsonIgnore] public virtual ProbeType ProbeType { get; set; } static public Probe GetRandom(DbSet<Profile> profiles) { return new Probe() { ProbeType = new ProbeType() { Name = "tt", InputMethod = 1 }, Profile = profiles.ToList().GetRandom() as Profile, Value = "val" }; } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DBProvider { class ConnectionSettings { public string DB_TYPE { get; set; } public string DB_HOST { get; set; } public string DB_PORT { get; set; } public string DB_USER { get; set; } public string DB_PASS { get; set; } public string DB_NAME { get; set; } public ConnectionSettings() { DB_TYPE = GetVar(nameof(DB_TYPE), "postgres"); DB_HOST = GetVar(nameof(DB_HOST), "localhost"); DB_USER = GetVar(nameof(DB_USER), "postgres"); DB_PASS = GetVar(nameof(DB_PASS), "<PASSWORD>"); DB_PORT = GetVar(nameof(DB_PORT), DB_TYPE == "mssql" ? "1433" : "5432"); DB_NAME = GetVar(nameof(DB_NAME), "test"); } public override string ToString() { switch (DB_TYPE) { case "mssql": return $"Server={DB_HOST},{DB_PORT};User Id={DB_USER};Password={<PASSWORD>};Database={DB_NAME}"; case "postgres": return $"Host={DB_HOST};Port={DB_PORT};Username={DB_USER};Password={<PASSWORD>};Database={DB_NAME};CommandTimeout=120;"; default: throw new NotImplementedException("Unsopported"); } } private string GetVar(string str, string def) { return (Environment.GetEnvironmentVariable(str) ?? def).ToLower(); } } public static class Extensions { public static object GetRandom(this IList l) { if (l.Count == 0) return null; var rnd = new Random(); return l[rnd.Next() % l.Count]; } } }
30c2a27411b882cf4583813da4777902a98a9e0b
[ "Markdown", "C#" ]
12
Markdown
kostkost2012/db_provider
3d702c5f705102f247238af72cdff2a72f257f1f
acacb6510cb2f081ce8207565eb7218f663bdb5b
refs/heads/master
<file_sep>import React, { Component } from 'react'; import './App.css'; class App extends Component { constructor() { super(); this.state = { lyrics : "" }; } handleClick = () => { fetch('https://api.lyrics.ovh/v1/"Metallica"/"FUEL"') .then(response=> response.json()) .then(data=> this.setState({lyrics: data.lyrics})) } render() { return ( <div className="App"> <button onClick={this.handleClick}> Buscar </button> <h4>State Array: {this.state.lyrics}</h4> </div> ); } } export default App;
ce5f83a1ad9a8e17bf1dc3771ec45daa75e091a0
[ "JavaScript" ]
1
JavaScript
Albertosr18/React
fdd38a33550df95ae0ce88b56632edde24e9e8c9
327290fcc2c63cca1541d0dfc045695ff4615af3
refs/heads/main
<repo_name>JeremyGobert/DEV4<file_sep>/voorbeeld examen/Demo/src/main/java/be/ehb/multec/data/abstractclass/WaitingState.java package be.ehb.multec.data.abstractclass; public class WaitingState extends State{ public WaitingState(StateMachine stateMachine) { super(stateMachine); } @Override public void InWaiting() { System.err.println("Your order is waiting to be prepared"); setState(getStateMachine().WAITING); } public void NextState() { System.err.println("Your order will be prepared"); setState(getStateMachine().PREPARING); getStateMachine().StartMaking(); } } <file_sep>/voorbeeld examen/Demo/src/test/java/be/ehb/multec/data/iterator/RestaurantTest.java package be.ehb.multec.data.iterator; import org.junit.jupiter.api.Test; import java.util.List; class RestaurantTest { @Test void testToString() { Restaurant restaurant = new Restaurant(); System.err.println(restaurant); } @Test void getMenuItems() { Restaurant restaurant = new Restaurant(); List<MenuItem> menu = restaurant.getMenuItems(); for (MenuItem menuItem: menu) { System.err.println(menuItem); } } }<file_sep>/voorbeeld examen/settings.gradle rootProject.name = 'Development III' include 'Groep1' include 'Groep2' include 'Demo' <file_sep>/voorbeeld examen/Demo/src/main/java/be/ehb/multec/data/abstractclass/StateMachine.java package be.ehb.multec.data.abstractclass; public class StateMachine { public final State WAITING; public final State PREPARING; public final State FINISHED; private State state; @Override public String toString() { return "" +state.toString() ; } public StateMachine() { WAITING = new WaitingState(this); PREPARING = new PreparingState(this); FINISHED = new FinishedState(this); state = WAITING; } public void setState(State state) { this.state = state; } public void StartMaking() { state.StartMaking(); } public void InWaiting() { state.InWaiting(); } public void Finished() { state.Finished(); } public void NextState() { state.NextState(); } public String getState() { String stateName = toString(); String result = ""; if(state == WAITING){ result = "WAITING"; }else if(state == PREPARING){ result = "PREPARING"; }else { result = "FINISHED"; } return result; } } <file_sep>/voorbeeld examen/Demo/src/main/java/be/ehb/multec/data/abstractclass/State.java package be.ehb.multec.data.abstractclass; import java.util.Objects; public abstract class State { private StateMachine stateMachine; public State(StateMachine stateMachine) { this.stateMachine = stateMachine; } protected StateMachine getStateMachine() { return stateMachine; } protected void StartMaking() { System.err.println("Imposssible to accept quarter"); } protected void InWaiting() { System.err.println("Imposssible to eject quarter"); } protected void Finished() { System.err.println("No use in turning crank"); } protected void NextState() { System.err.println("fuck"); } protected void setState(State state) { stateMachine.setState(state); } } <file_sep>/voorbeeld examen/Demo/src/main/java/be/ehb/multec/data/abstractclass/PreparingState.java package be.ehb.multec.data.abstractclass; public class PreparingState extends State{ public PreparingState(StateMachine stateMachine) { super(stateMachine); } @Override public void StartMaking() { System.err.println("Your order is being prepared"); setState(getStateMachine().PREPARING); } public void NextState() { System.err.println("Your order is almost finished"); setState(getStateMachine().FINISHED); getStateMachine().Finished(); } }<file_sep>/voorbeeld examen/Demo/src/test/java/be/ehb/multec/data/decorator/BroodTest.java package be.ehb.multec.data.decorator; import org.junit.jupiter.api.Test; public class BroodTest { @Test void createBroodje() { Brood brood = new KipCoery(); System.out.println(brood.getDescription()+ " " + brood.cost()+ "$"); } } <file_sep>/voorbeeld examen/Demo/src/main/java/be/ehb/multec/data/decorator/Prepare.java package be.ehb.multec.data.decorator; public class Prepare extends Brood { public Prepare() { setDescription("Broodje Prepare"); } @Override public double cost() { return 0.05; } } <file_sep>/voorbeeld examen/Demo/src/main/java/be/ehb/multec/data/decorator/Kip.java package be.ehb.multec.data.decorator; public class Kip extends Brood { public Kip() { setDescription("Broodje kip"); } @Override public double cost() { return 45.88; } } <file_sep>/voorbeeld examen/build.gradle plugins { id 'java' } group 'org.example' version '1.0-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } test { useJUnitPlatform() } dependencies { testCompile 'org.junit.jupiter:junit-jupiter:5.4.2' compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.21' }<file_sep>/voorbeeld examen/Demo/src/main/java/be/ehb/multec/data/iterator/MenuIterator.java package be.ehb.multec.data.iterator; import java.util.Iterator; import java.util.List; public class MenuIterator implements Iterator<MenuItem> { private List<MenuItem> Menu; private Iterator<MenuItem> MenuIterator; public MenuIterator(List<MenuItem> Menu) { this.Menu = Menu; MenuIterator = Menu.iterator(); } @Override public boolean hasNext() { if(MenuIterator.hasNext()) return true; else return false; } @Override public MenuItem next() { if(MenuIterator.hasNext()) return MenuIterator.next(); else return null; } } <file_sep>/voorbeeld examen/Demo/src/test/java/be/ehb/multec/data/MainTest.java package be.ehb.multec.data; import be.ehb.multec.data.decorator.Brood; import be.ehb.multec.data.decorator.KipCoery; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class MainTest { @Test void main() { } @Test void getKipCoery() { System.out.println("******Get kipcoery******"); Brood kipCoery = new KipCoery(); System.out.println(kipCoery.getDescription()+ " " + ((KipCoery) kipCoery).cost()+ "$"); System.out.println("************************"); } }
10e1ed2b036ffb2300c2810f07ce25e064e0b02a
[ "Java", "Gradle" ]
12
Java
JeremyGobert/DEV4
7730ade118c829e2a4a260e16b848a222bc757ec
f2f4616f6474b196176d885256e1aa076d04d25b
refs/heads/master
<file_sep>''' A decorator that allows partial matching in function parameter names, like in R Why Use it ---------- Consider a function with long parameter names: f(x, y, population_size=1000, parsimony_coefficient=0.01) Typing calls like f(3, 5, parsimony_coefficient=0.025) can be tiring. If you want to be lazy, and just type f(3, 5, pa=0.025) then this decorator is for you. It allows lazy function call in this fashion. How to Use ---------- Import and add @lazy decorator above your original function definition, like: from lazy import lazy ... @lazy def f(x, y, population_size=1000, parsimony_coefficient=0.01): ... ''' # Author: <NAME> <lei dot fu at connect dot ust dot hk> # Date: 18/06/09 = Sat from functools import wraps import inspect __all__ = ['lazy'] def _partial_matching(p, names): ''' Checks whether a partial name matches any of the complete names Parameters ---------- p : str a partial name names : iterable of str collection of complete names Returns ------- (m, c) : m for match result, c for complete name(s) | Case | m | c | |-------------------------|----|--------------------------| | 1. Unambiguous match | 1 | matched complete name | | 2. No match | 0 | None | | 3. Ambiguous match | -1 | candidate complete names | Doctest ------- # Unambiguous match >>> _partial_matching('pa', {'population_size', 'parsimony_coefficient'}) (1, 'parsimony_coefficient') # No match >>> _partial_matching('pe', {'population_size', 'parsimony_coefficient'}) (0, None) # Ambiguous match >>> names = {'population_size', 'parsimony_coefficient'} >>> m, c = _partial_matching('p', names) >>> m == -1 True >>> set(c) == set({'population_size', 'parsimony_coefficient'}) True ''' c = [x for x in names if x.startswith(p)] m = len(c) if m == 1: c = c[0] elif m == 0: c = None else: m = -1 return (m, c) def lazy(f): ''' A decorator that allows partial matching in function parameter names, like in R Essentially, it performs the conversion: f(*a, **partial) ==> f(*a, **complete) Parameter --------- f : function original function Returns ------- g : function converts f(*a, **partial) ==> f(*a, **complete) Doctest ------- Consider decorating a function f: >>> @lazy ... def f(x, y, population_size=1000, parsimony_coefficient=0.01): ... if population_size != 1000: ... print('customized population size') ... if parsimony_coefficient != 0.01: ... print('customized parsimony coefficient') ... return x + y >>> f(3, 5) 8 >>> f(3, 5, pa=0.025) customized parsimony coefficient 8 >>> f(3, 5, po=2000) customized population size 8 >>> f(3, 5, pe=42) Traceback (most recent call last): ... LookupError: No match for parameter name that starts with 'pe'. Legal parameter name(s): ['x', 'y', 'population_size', 'parsimony_coefficient'] >>> f(3, 5, p=2000) Traceback (most recent call last): ... LookupError: Ambiguous match for parameter name that starts with 'p'. Candidate parameter names: ['population_size', 'parsimony_coefficient'] ''' spec = inspect.getfullargspec(f) # if there is **kwargs in function signature, then lazy call is disabled if spec.varkw is not None: return f @wraps(f) def g(*a, **partial): complete = {} names = spec.args + spec.kwonlyargs for p in partial: m, c = _partial_matching(p, names) if m == 0: raise LookupError("No match for parameter name " "that starts with '%s'.\n" "Legal parameter name(s): %s" % (p, str(names))) elif m == -1: raise LookupError("Ambiguous match for parameter name " "that starts with '%s'.\n" "Candidate parameter names: %s" % (p, str(c))) complete[c] = partial[p] return f(*a, **complete) return g if __name__ == '__main__': import doctest doctest.testmod()<file_sep># manage an all-in-one in-memory database for all historical daily data of China's A-shares # author: <NAME> # date: 18/12/14 = Fri # auto download and update with a very-to-use API to retrieve data import collections import math import numpy as np import os import pandas as pd import shutil import time import tushare import WindPy _TOKEN = '00e38f9331264bad850f7e2df7271f5d390c24e1f42bcb1c36729389' _MAX_IN_PERIOD = 200 _PERIOD = 1 _UNIT = 'm' _ONE_DIR = r'P:\one' # change to local directory to save one.h5 _UPDATE_TIME = 1530 _ONE_FILENAME = 'one.h5' _ONE_PATH = os.path.join(_ONE_DIR, _ONE_FILENAME) _YEARLY_DIR = os.path.join(_ONE_DIR, 'yearly') _TUSHARE_CODE_FIELD = 'ts_code' _TUSHARE_DATE_FIELD = 'trade_date' _TUSHARE_FIELDS = ['open', 'high', 'low', 'close', 'pre_close', 'change', 'pct_chg', 'vol', 'amount', 'adj_factor'] _WIND_FIELDS = ['open', 'high', 'low', 'close', 'pre_close', 'chg', 'pct_chg', 'volume', 'amt', 'adjfactor'] _WIND_FIELDS_STR = ', '.join(_WIND_FIELDS) _ADJUSTABLE_FIELDS = ['open', 'high', 'low', 'close', 'pre_close'] _NONADJUSTABLE_FIELDS = ['chg', 'pct_chg', 'vol', 'amt', 'adj_factor'] _STANDARD_FIELDS = _ADJUSTABLE_FIELDS + _NONADJUSTABLE_FIELDS _COMPLETE_FIELDS = ['date', 'code'] + _STANDARD_FIELDS + ['date_str'] _FIELDS_CONVERSION = {'adjfactor' : 'adj_factor', 'amount' : 'amt', 'change' : 'chg', 'trade_date': 'date_str', 'ts_code' : 'code', 'volume' : 'vol' } _FIELDS_MAP = { 'k': 'code', 'd': 'date', 'o': 'open', 'h': 'high', 'l': 'low', 'c': 'close', 'p': 'pre_close', 'g': 'chg', 'r': 'pct_chg', 'v': 'vol', 'a': 'amt', 'j': 'adj_factor', 's': 'date_str' } _INDEX_LIST = [ '000001.SH', # 上证综指 '000009.SH', # 上证380 '000010.SH', # 上证180 '000016.SH', # 上证50 '000300.SH', # 沪深300 '000852.SH', # 中证1000 '000903.SH', # 中证100 '000905.SH', # 中证500 '000906.SH', # 中证800 '399001.SZ', # 深证成指 '399101.SZ', # 中小板综 '399102.SZ', # 创业板综 '881001.WI'] # 万得全A class TushareUser(): def __init__(self, token=None, max_in_period=None, period=None, unit=None): self.token = token if token else _TOKEN self.api = tushare.pro_api(self.token) self.max_in_period = _MAX_IN_PERIOD self.period = _PERIOD self.unit = _UNIT ########## load functions ######################################## def load(path=_ONE_PATH): if '_one' not in globals(): global _one path = os.path.splitext(path)[0] + '.h5' print('Reading %s ...' % path) print('Please kindly wait a moment for first run ...') _one = pd.read_hdf(path) b, e = get_first_date(_one), get_last_date(_one) print('All-in-one data ready for [%s, %s] ...' % (b, e)) def unload(): if '_one' in globals(): global _one del _one ########## utility functions ######################################## def today(): return pd.to_datetime('today').strftime('%Y%m%d') def yesterday(): return (pd.to_datetime('today') - pd.to_timedelta('1 day')).strftime('%Y%m%d') def this_year(): return str(pd.to_datetime('today').year) def latest_day(): return today() if pd.to_datetime('today').strftime('%H%M') > str(_UPDATE_TIME) else yesterday() def is_leap_year(y): return y % 4 == 0 and y % 25 != 0 or y % 16 == 0 def month_end(d): year = d // 100 month = d % 100 if month == 2: return 29 if is_leap_year(year) else 28 elif month in (1, 3, 5, 7, 8, 10, 12): return 31 else: return 30 def date(d, mode='begin'): if d is None or not (isinstance(d, int) or isinstance(d, str) and d.isdigit()): return None d = int(d) if d <= 0: return None n = int(math.log10(d)) + 1 if n == 4 and 1900 <= d < 2100: d *= 10000 res = str(d + 101), str(d + 1231) elif n == 6 and 190001 <= d < 210001 and 1 <= d % 100 <= 12: res = str(d * 100 + 1), str(d * 100 + month_end(d)) elif n == 8 and 19000101 <= d < 21000101 and 1 <= (d // 100) % 100 <= 12 and 1 <= (d % 100) <= month_end(d // 100): res = str(d), str(d) else: return None if mode in ['b', 'begin']: return res[0] elif mode in ['e', 'end']: return res[1] else: return None def interval(b, e=None, allow_future_days=False): e = e if e else b if allow_future_days: return date(b, mode='begin'), date(e, mode='end') else: return date(b, mode='begin'), min(date(e, mode='end'), latest_day()) if date(e, mode='end') else None def code(k): if k is None: return None elif isinstance(k, int): if k < 0: return str(-k).rjust(6, '0') + '.SH' # for index ending with .SH else: return str(k).rjust(6, '0') + ('.SZ' if k < 400000 else ('.SH' if k < 800000 else '.WI')) elif isinstance(k, str): if k.isdigit(): return code(int(k)) else: return k.upper() elif isinstance(k, (list, tuple)): return [code(x) for x in k] def get_first_date(df): if df is None or df.empty or 'date_str' not in df.columns: return None elif df.date_str.is_monotonic: return df.date_str.iloc[0] else: return df.date_str.min() def get_last_date(df): if df is None or df.empty or 'date_str' not in df.columns: return None elif df.date_str.is_monotonic: return df.date_str.iloc[-1] else: return df.date_str.max() ########## setup functions ######################################## def setup(b=None, e=None): if b is None and e is None: b = input('Enter begin year (press ENTER for 1990): ') b = b if b else 1990 e = input('Enter end year (press ENTER for %s): ' % this_year()) e = e if e else this_year() elif e is None: e = this_year() b = int(b); e = int(e) print('-' * 50) assert 1990 <= b <= e < 2100 print('Setting up all-in-one data for [%s, %s] ...' % (b, e)) unload() make_dir(_ONE_DIR) make_dir(_YEARLY_DIR) yearly_download(b, e) _one = concat() _indexes = get_indexes(b, e) print('Concatenating individual stocks and stock market indexes ...') _one = pd.concat([_one, _indexes], sort=False).sort_values(['date', 'code']) check(_one) save(_one) clean() load() def standardize_fields(df, convert=_FIELDS_CONVERSION): df.columns = [convert[x] if x in convert else x for x in df.columns] def tget(b, e=None, by='date', queue=None, user=None, return_params=False): # set up Tushare user = user if user else TushareUser() # get trade dates in [b, e] b, e = interval(b, e) assert b and e cal = user.api.query('trade_cal', start_date=b, end_date=e) dates = cal[cal.is_open == 1].cal_date # query time control queue = queue if queue else collections.deque() period = pd.to_timedelta(user.period, unit=user.unit) # get all daily data in [b, e] df = pd.DataFrame() for d in dates: print(d) # query time control now = pd.to_datetime('now') span = now - queue[0] if queue else pd.to_timedelta(0) if len(queue) == user.max_in_period and span < period: wait = np.ceil((period - span).total_seconds()) print('Cooling down for %d s ...' % wait) time.sleep(wait) # get daily data daily = user.api.query('daily', trade_date=d) adj = user.api.query('adj_factor', trade_date=d) daily = daily.merge(adj, on=[_TUSHARE_CODE_FIELD, _TUSHARE_DATE_FIELD], how='left') daily['date'] = pd.to_datetime(d) df = df.append(daily, sort=False) # query time control queue.append(pd.to_datetime('now')) if len(queue) > user.max_in_period: queue.popleft() if df.empty: print('Got nothing in [%s, %s] ...' % (b, e)) else: # tushare unnecessarily reports trading volume, amount in unit of 100, 1,000 df['vol'] *= 100 df['amount'] *= 1000 if by == 'date': df.sort_values([_TUSHARE_DATE_FIELD, _TUSHARE_CODE_FIELD], inplace=True) elif by == 'code': df.sort_values([_TUSHARE_CODE_FIELD, _TUSHARE_DATE_FIELD], inplace=True) df.reset_index(drop=True, inplace=True) df = df[['date', _TUSHARE_CODE_FIELD] + _TUSHARE_FIELDS + [_TUSHARE_DATE_FIELD]] standardize_fields(df) return (df, queue, user) if return_params else df def save(data, path=_ONE_PATH, key='one', backup=True): if data.empty: print('Has nothing to write ...') path = os.path.splitext(path)[0] + '.h5' if os.path.exists(path) and backup: bak_path = os.path.splitext(path)[0] + '_bak.h5' print('Backing up existing file to %s ...' % bak_path) shutil.copyfile(path, bak_path) print('Start writing %s ...' % path) data.to_hdf(path, key=key, mode='w', format='table') print('Finish writing %s ...' % path) def download(b, e=None, path=None, queue=None, user=None, return_params=False): b, e = interval(b, e) print('Downloading data in [%s, %s] ...' % (b, e)) df, queue, user = tget(b, e, queue=queue, user=user, return_params=True) path = path if path else b + ('' if b == e else '_' + e) save(df, path, backup=True) return queue, user if return_params else None def yearly_download(b, e=None, directory=_YEARLY_DIR): cwd = os.getcwd() os.chdir(directory) e = e if e else b; b = int(b); e = int(e) if 1900 <= b <= e < 2100: queue = user = None while (b <= e): path = str(b) + '.h5' if not os.path.exists(path) or confirm('%s exists. Overwrite?' % path): queue, user = download(b, b, str(b), queue, user, return_params=True) b += 1 os.chdir(cwd) def concat(): print('Concatenating yearly files in %s ...' % _YEARLY_DIR) files = [] for f in os.listdir(_YEARLY_DIR): root, ext = os.path.splitext(f) if root.isdigit() and 1990 <= int(root) < 2100 and ext == '.h5': files.append(os.path.join(_YEARLY_DIR, f)) files.sort() df = pd.DataFrame() for f in files: print('Concatenating %s ...' % f) df = pd.concat([df, pd.read_hdf(f)], sort=False) df = df.reset_index(drop=True) return df def check(df, return_results=False): if df.empty: return True flag = True dup = nan = None print('Checking for duplicated entries ...') row = df.set_index(['date', 'code']).index.duplicated(keep=False) if row.any(): flag = False dup = df[row] print('Found %d duplication(s). Last duplication at %s.' % (len(dup), get_last_date(dup))) print('Checking for NaN values ...') row = df.isna().any(axis=1) if row.any(): flag = False nan = df[row] print('Found %d NaN value(s). Last NaN value at %s.' % (len(nan), get_last_date(nan))) print('---------- NaN Values Summary --------------------') print(df.isna().sum(axis=0)) print('---------- Last 3 NaN Values ---------------------') print(df[df.isna().any(axis=1)].tail(3)) return (flag, dup, nan) if return_results else flag def make_dir(directory): if not os.path.exists(directory): print('Creating %s ...' % os.path.join(os.getcwd(), directory)) os.makedirs(directory) def confirm(s): while True: ans = input(' '.join([s, '(y/[n])', ''])) if ans.lower() == 'y': return True elif ans.lower() in ['', 'n']: return False def remove(files, silent=False): def delete(files): for f in files: print('Removing %s ...' % f) os.remove(f) if files: if silent: delete(files) else: print('These files can be removed:\n') for f in files: print(f) if confirm('Do you want to remove the above files?'): delete(files) def clean_yearly(): if os.path.exists(_YEARLY_DIR): remove([os.path.join(_YEARLY_DIR, x) for x in os.listdir(_YEARLY_DIR)]) def clean_bak(): def _get_bak(directory): if os.path.exists(directory): return [os.path.join(directory, x) for x in os.listdir(directory) if os.path.splitext(x)[0].endswith('_bak')] else: return [] bak_files = _get_bak(_ONE_DIR) + _get_bak(_YEARLY_DIR) remove(bak_files) def clean(): clean_yearly() clean_bak() ########## wind functions ######################################## def wconnect(): if not WindPy.w.isconnected(): WindPy.w.start() def wget(k, b, e=None, silent=False): wconnect() k = code(k) b, e = interval(b, e) if not silent: print('Getting %s in [%s, %s] ...' % (k, b, e)) wsd = WindPy.w.wsd(k, _WIND_FIELDS_STR, b, e) if wsd.ErrorCode != 0: print('Error in getting %s. ErrorCode =' % k, wsd.ErrorCode) return None df = pd.DataFrame(wsd.Data).T df.columns = [x.lower() for x in wsd.Fields] df['code'] = k df['date'] = pd.to_datetime(wsd.Times) df['date_str'] = [x.strftime('%Y%m%d') for x in list(df.date)] df = df[['date', 'code'] + _WIND_FIELDS + ['date_str']] standardize_fields(df) return df def get_index_list(path=None): if path: return sorted(list(pd.read_csv(path, header=None, usecols=[0], squeeze=True))) else: return _INDEX_LIST def get_indexes(b, e=None, silent=False): index_list = get_index_list() b, e = interval(b, e) print('Getting stock market indexes in [%s, %s] ...' % (b, e)) df = pd.DataFrame() for k in index_list: df = pd.concat([df, wget(k, b, e, silent=silent)], sort=False) # remove rows without close price df = df[df.close.notna()].sort_values(['date', 'code']).reset_index(drop=True) return df ########## update functions ######################################## def update(b=None, e=None, user=None, backup=True): global _one load() user = user if user else TushareUser() b = date(b, 'begin') if b else get_last_date(_one) e = date(e, 'end') if e else latest_day() print('Updating with [%s, %s] ...' % (b, e)) df = tget(b, e) indexes = get_indexes(b, e) df = pd.concat([df, indexes], sort=False) df = df.sort_values(['date', 'code']) _one = _one[_one.date_str < b] _one = pd.concat([_one, df], sort=False).reset_index(drop=True) flag, dup, nan = check(_one, return_results=True) # some historical NaN values before year 2000 if flag or nan.empty or get_last_date(nan) < this_year() or confirm('Found duplications/NaN values. Are you sure to update?'): save(_one, backup=backup) else: print('Update terminated ...') unload() load() ########## ask functions ######################################## def parse(fields): if isinstance(fields, str): fields = fields.lower() if fields in ['full', 'complete']: return _COMPLETE_FIELDS elif fields in ['all', 'standard']: return _STANDARD_FIELDS elif fields in _COMPLETE_FIELDS: return [fields] else: return [_FIELDS_MAP[x] for x in fields if x in _FIELDS_MAP] elif isinstance(fields, list): res = [] for f in fields: res.extend(parse(f)) return sorted(set(res), key=lambda x: _COMPLETE_FIELDS.index(x)) def separate_fields(fields): if isinstance(fields, str): fields = [fields] index = [x for x in fields if x in ['date', 'code', 'date_str']] adjustable = [x for x in fields if x in _ADJUSTABLE_FIELDS] nonadjustable = [x for x in fields if x in _NONADJUSTABLE_FIELDS] return index, adjustable, nonadjustable def query(k, b=None, e=None, by='date'): # k is code or list of codes # b is begin # e is end # essentially, this enables query(None, b, e) if e is None and interval(k, b)[0] is not None: return query(None, k, b) assert k or b load() date_mask = True k = code(k) b, e = interval(b, e) if b is not None: date_mask = (b <= _one.date_str) & (_one.date_str <= e) code_mask = True if isinstance(k, str): code_mask = _one.code == k elif isinstance(k, (list, tuple)): code_mask = _one.code.isin(k) if by == 'code': keys = ['code', 'date'] # by is 'date' by default else: keys = ['date', 'code'] return _one[date_mask & code_mask].set_index(keys, drop=False).sort_index() def ask(fields, k, b=None, e=None, adj='forward', by='date'): fields = parse(fields) if not fields: return None index, adjustable, nonadjustable = separate_fields(fields) df = query(k, b, e, by) if df.empty: return None elif 'none'.startswith(adj) or adj in ['plain', 'vanilla'] or len(adjustable) == 0: res = df[fields] else: if adj in ['b', 'bwd', 'backward']: res = df[adjustable].mul(df.adj_factor, axis=0).join(df[nonadjustable]) # by default, adj is in ['f', 'fwd', 'forward'] else: last_adj_factor = df.groupby(level='code').adj_factor.last() res = df[adjustable].mul(df.adj_factor, axis=0).div(last_adj_factor, axis=0, level=1).join(df[nonadjustable]) if index: res = df[index].join(res) to_drop = [] for i in range(2): if len(res.index.levels[i]) == 1: to_drop.append(i) if to_drop: res = res.reset_index(to_drop, drop=True) return res.T.squeeze() if res.shape[-1] == 1 else res def open(k=None, b=None, e=None, adj='forward'): return ask('open', k, b, e, adj) def high(k=None, b=None, e=None, adj='forward'): return ask('high', k, b, e, adj) def low(k=None, b=None, e=None, adj='forward'): return ask('low', k, b, e, adj) def close(k=None, b=None, e=None, adj='forward'): return ask('close', k, b, e, adj) def ohlc(k=None, b=None, e=None, adj='forward'): return ask(['open', 'high', 'low', 'close'], k, b, e, adj) def pre_close(k=None, b=None, e=None, adj='forward'): return ask('pre_close', k, b, e, adj) def adj_factor(k, b=None, e=None): return ask('adj_factor', k, b, e) def adj(k, b=None, e=None): return ask('adj_factor', k, b, e) def amount(k, b=None, e=None): return ask('amt', k, b, e) def amt(k, b=None, e=None): return ask('amt', k, b, e) def volume(k, b=None, e=None): return ask('vol', k, b, e) def vol(k, b=None, e=None): return ask('vol', k, b, e) def pct_chg(k, b=None, e=None): return ask('pct_chg', k, b, e) def ret(k, b=None, e=None): return ask('pct_chg', k, b, e) def price_vol(k, b=None, e=None, adj='forward'): return ask(['close', 'vol'], k, b, e, adj) def price_amt(k, b=None, e=None, adj='forward'): return ask(['close', 'amt'], k, b, e, adj) def all_codes(b, e=None): return ask('code', b, e) def all_dates(k): return ask('date', k) <file_sep># Capturing Arguments **A decorator that captures parameter names, parameter categories, and values of the arguments passed to a function.** **装饰器:对于给定函数,捕捉调用时传入的实参,输出对应的形参名称、形参类别,以及实参的值。** Suppose you have a function with signature `foo(a, b=500, *c, d=50, e, f=5, **g)`. Let's say you call it with `foo(0, 1, 2, 22, 222, 2222, d=3, e=4, g=6, h=7, i=8, j=9, k=10)`. If you want a clear print-out to show you what values are passed to which parameters, like: ``` ----- Arguments for Positional-or-Keyword Parameters ---------------------- a = 0 b = 1 (default = 500) ----- Arguments for Var-Positional Parameters ----------------------------- c --> (2, 22, 222, 2222) ----- Arguments for Keyword-Only Parameters ------------------------------- d = 3 (default = 50) e = 4 f = 5 (default = 5) ----- Arguments for Var-Keyword Parameters -------------------------------- g --> { g = 6 h = 7 i = 8 j = 9 k = 10 } ``` then you may need this decorator. Get [source code](captor.py). <file_sep>[`one`](one.py) manages an all-in-one in-memory database for all historical daily data of China's A-shares. It automatically downloads and updates with a very-easy-to-use API to retrieve data. --- > *Want to ask the close price of Kweichow Moutai from 2014 to June 2018 ?* Try `one.close(600519, 2014, 201806)`. > *Want to know more about it ?* Try `one.ask(['open', 'high', 'low', close', 'pct_chg', 'vol', 'amt'], 600519)`. Or even easier `one.ask('ohlcrva', 600519)`. > *To setup database ?* Run `one.setup()`. > *To update it ?* Run `one.update()`. - [source](one.py) [Back to Main](https://github.com/aafulei/little-python)<file_sep># Little Python A collection of little Python programs that I wrote for fun. ## Contents - [All-in-One Database for All Daily Data of China's A-shares](#all-in-one-database-for-all-daily-data-of-chinas-a-shares) - [Argument Captor](#argument-captor) - [Augmented `tree`](#augmented-tree) - [Game of Life](#game-of-life) - [Lazy Function Call](#lazy-function-call) ## [All-in-One Database for All Daily Data of China's A-shares](one) [`one`](one/one.py) manages an all-in-one in-memory database for all historical daily data of China's A-shares. It automatically downloads and updates with a very-easy-to-use API to retrieve data. Want to ask the close price of Kweichow Moutai from 2014 to June 2018? Try `one.close(600519, 2014, 201806)`. ## [Argument Captor](captor) [`captor`](captor/captor.py) is a decorator that captures arguments passed to the decorated function. It prints out parameter names, categories, values and default values of the arguments. Useful in debugging. ## [Augmented `tree`](atree) <img src="atree/atree-landscape.png" width="750"/> [`atree`](atree/atree.py) is an augmented tree command that graphically displays the folder structure as a tree, while showing the file sizes, line numbers and percentages. ## [Game of Life](gol) <img src="gol/gol.png" width="500"/> Shows animation of Game of Life with the help of `matplotlib`. ## [Lazy Function Call](lazy) [`lazy`](lazy/lazy.py) is a decorator that allows partial parameter name matching when calling the function, like in R. Assuming signature `f(population=1000, parsimony_coefficient=.01)`, it would be legal to call `f(pa=.025)`. <file_sep>![](atree.png) - [source](atree.py) [Back to Main](https://github.com/aafulei/little-python) <file_sep># Lazy Function Call **A decorator that allows partial matching in function parameter names, like in R.** **装饰器:像R语言一样,允许在调用函数时,对形参名称做部分匹配,不用写全形参的名称。** Consider a function with long parameter names: `f(x, y, population_size=1000, parsimony_coefficient=0.01)` Typing calls like `f(3, 5, parsimony_coefficient=0.025)` can be tiring. If you want to be lazy, and just type `f(3, 5, pa=0.025)` then this decorator is for you. It allows lazy function call in this fashion. For the source code of the decorator, click [here](lazy.py).<file_sep># -*- coding: utf-8 -*- """ A decorator that captures parameter names, parameter categories, and values of the arguments passed to a function. """ # Date: 18/06/21 = Thu # Author: <NAME> <lei dot fu at connect dot ust dot hk> import functools import copy import inspect __all__ = ['capture'] def capture(f): """ A decorator that captures parameter names, parameter categories, and values of the arguments passed to a function. How to Use ---------- Put the @capture above the defitnition of the function to decorate. What Does it Do --------------- Prints out the parameter names, parameter categories, and values of the arguments passed to a function. The arguments fall into 4 categories: 1. arguments for positional-or-keyword parameters 2. arguments for var-positional parameters 3. arguments for keyword-only parameters 4. arguments for var-keyword parameters References ---------- https://docs.python.org/3/glossary.html#term-parameter """ @functools.wraps(f) def g(*args, **kwargs): local = copy.deepcopy(locals()) spec = inspect.getfullargspec(f) print(line('Start Capturing Arguments Passed to Function %s()' % f.__name__, p=':')) # build dict for arguments for positional-or-keyword parameters poskey = {} i = j = 0 for x in spec.args: try: poskey[x] = local['args'][i] i += 1 except IndexError: try: poskey[x] = local['kwargs'][x] del local['kwargs'][x] except KeyError: poskey[x] = spec.defaults[j] j += 1 if len(poskey) > 0: print(line('Arguments for Positional-or-Keyword Parameters')) j = 0 if spec.defaults is None else len(spec.defaults) j -= len(spec.args) for x in poskey: print(x, '=', poskey[x], end='') if j >= 0: print(' (default = ', spec.defaults[j], ')', sep='') else: print('') j += 1 # build tuple for arguments for var-positional parameters varpos = local['args'][i:] if len(varpos) > 0: print(line('Arguments for Var-Positional Parameters')) print(spec.varargs, '-->', varpos) # build dict for arguments for keyword-only parameters keyonly = {} for x in spec.kwonlyargs: try: keyonly[x] = local['kwargs'][x] del local['kwargs'][x] except KeyError: keyonly[x] = spec.kwonlydefaults[x] if len(keyonly) > 0: print(line('Arguments for Keyword-Only Parameters')) for x in keyonly: print(x, '=', keyonly[x], end='') if x in spec.kwonlydefaults: print(' (default = ', spec.kwonlydefaults[x], ')', sep='') else: print('') # build dict for arguments for var-keyword parameters varkey = local['kwargs'] if len(varkey) > 0: print(line('Arguments for Var-Keyword Parameters')) print(spec.varkw, '-->\n{') for x in varkey: print(' ', x, '=', varkey[x]) print('}') print(line('Finish Capturing Arguments Passed to Function %s()' % f.__name__, p=':')) return f(*args, **kwargs) return g @capture def foo(a, b=500, *c, d=50, e, f=5, **g): """ Function to test decorator @capture. | parameter name | type | with default value | | ------------------ | --------------------- | ------------------ | | a | positional-or-keyword | no | | b | positional-or-keyword | yes | | c --> ... (if any) | var-positional | no | | d | keyword-only | yes | | e | keyword-only | no | | f | keyword-only | yes | | g --> ... (if any) | var-keyword | no | """ print('a =', a) print('b =', b) print('c =', c) # c is a tuple print('d =', d) print('e =', e) print('f =', f) print('g =', g) # g is a dict def line(s='', p='-', length=75, lead=5, newline=True): if len(s) > 0: s = ' ' + s + ' ' t = '%s%s%s' % (p * lead, s, p * (length - lead - len(s))) return '\n' + t + '\n' if newline else t # tests if __name__ == '__main__': foo(0, 1, 2, 22, 222, 2222, d=3, e=4, g=6, h=7, i=8, j=9, k=10) foo(a='a', e=2.71828) <file_sep># 18/08/17 = Fri # Show animation of Game of Life import numpy as np import matplotlib.pyplot as plt def iterate(a): a = np.pad(a, pad_width=1, mode='constant') n = (a[0:-2, 0:-2] + a[0:-2, 1:-1] + a[0:-2, 2:] + a[1:-1, 0:-2] + a[1:-1, 2:] + a[2: , 0:-2] + a[2: , 1:-1] + a[2: , 2:]) birth = (n == 3) & (a[1:-1, 1:-1] == 0) survive = ((n == 2) | (n == 3)) & (a[1:-1, 1:-1] == 1) a[...] = 0 a[1:-1, 1:-1][birth | survive] = 1 return a[1:-1, 1:-1] for k in range(100): rng = np.random.RandomState(k) a = rng.randint(0, 2, (10, 10)) fig, ax = plt.subplots() for i in range(100): last = a a = iterate(a) if (last == a).all(): print('At step', i, 'steady state is achieved.') break else: ax.cla() ax.pcolor(a, edgecolor='k', cmap='PuRd_r') ax.set_title('frame %d (seed = %d)' % (i, k)) plt.pause(.1) plt.pause(1) plt.close() <file_sep># 18/11/08-15 = Thu-Thu # augmented tree command that shows sizes, line numbers, and percentages of the files that match predefined patterns. import argparse import colorama import fnmatch import functools import heapq import math import os import platform import sys import unicodedata # to be expanded later TYPE_DICT = {"CODE": [".c", ".cpp", ".h", ".hpp", ".java", ".r", ".py"], "DATA": [".csv"], "MUSIC": [".mp3", ".wav", ".wma"], "PICTURES": [".bmp", ".jpg", ".png"], "TEXT": [".md", ".rst", ".txt"], "VIDEO": [".mp4", ".mpg", ".rm", ".wmv"]} # ========== User-Defined Classes ============================================= class Top_1_And_Which(object): def __init__(self): self.value = None self.which = None def push(self, value, which): if (not self.value) or (value > self.value): self.value = value self.which = which def get(self): return self.value, self.which def get_value(self): return self.get()[0] def get_which(self): return self.get()[1] class Top_K_And_Which(object): """Basically a push-only fixed-size heap for dict""" def __init__(self, size): self.size = size self.heap = [] def push(self, value, which): if len(self.heap) < self.size: heapq.heappush(self.heap, (value, which)) else: heapq.heappushpop(self.heap, (value, which)) def sort(self): self.heap.sort(reverse=True) def get(self): if self.heap: return [list(x) for x in zip(*self.heap)] return [], [] def get_value(self): return self.get()[0] def get_which(self): return self.get()[1] class Tree(object): def __init__(self, args): self.args = args self.case = lambda s: s if self.args.case_sensitive else s.lower() self.file_counter = dict() self.folder_counter = dict() self.get_from = functools.partial(get_lines, verbose=self.args.verbose) if self.args.line else \ functools.partial(get_size, verbose=self.args.verbose) self.max_num_digits = 0 self.num_files = 0 self.num_folders = 0 self.top_files = Top_K_And_Which(self.args.top_k_files) self.top_folders = Top_K_And_Which(self.args.top_k_folders) self.top_size_to_highlight = None self.total_size = 0 self.total_width = 0 # ========== Utility Functions ================================================ def sep(num): return "{0:,}".format(num) def nonnegative(num): return int(num) if int(num) > 0 else 0 def yellow(s): return colorama.Fore.YELLOW + s + colorama.Style.RESET_ALL def plural(word, num, irregular=""): if num > 1: if irregular: return irregular else: return word + "s" else: return word def visual_len(s): """return visual length of string s, which may contain East Asian characters""" n = 0 for c in s: if unicodedata.east_asian_width(c) in {"F", "W"}: n += 1 return len(s) + n def visual_first(s, n): if n <= 0: return "" first = s[:n] slen = len(first) vlen = visual_len(first) if slen == vlen: return first else: e = slen while visual_len(first[:e]) > n: e -= 1 return first[:e] def visual_last(s, n): if n <= 0: return "" last = s[-n:] slen = len(last) vlen = visual_len(last) if slen == vlen: return last else: b = 0 while visual_len(last[b:]) > n: b += 1 return last[b:] def visual_just(s, n, squeeze=True): vlen = visual_len(s) if visual_len(s) <= n: return s + " " * (n - vlen) elif squeeze: return visual_first(s, n - 15) + " ... " + visual_last(s, 10) else: return s def match(s, pattern_list): """return True if string case-sensitively matches any pattern in list""" if isinstance(pattern_list, str): pattern_list = [pattern_list] for p in pattern_list: if fnmatch.fnmatchcase(s, p): return True return False def percent_to_num(per): try: if per.endswith("%"): return eval(per.rstrip("%")) / 100 else: return eval(per) except: return per def size_to_storage(size): """convert file size to str, with proper suffix""" try: suffix = {0: " B", 1: "KB", 2: "MB", 3: "GB", 4: "TB", 5: "PB"} unit = 1000 if platform.system() == "Darwin" else 1024 level = 0 if size == 0 else min(int(math.log(size, unit)), max(suffix)) spec = "{0:,.0f}" if level == 0 else "{0:,.1f}" return spec.format(size / unit ** level) + " " + suffix[level] except: return size def storage_to_size(sto): """convert storage to file size, assuming proper suffix""" try: level = {"PB": 5, "TB": 4, "GB": 3, "MB": 2, "KB": 1, "B": 0, "P": 5, "T": 4, "G": 3, "M": 2, "K": 1, "": 0} unit = 1000 if platform.system() == "Darwin" else 1024 sto = sto.upper() for key in level: if sto.endswith(key): return float(sto.rstrip(key)) * (unit ** level[key]) except: return sto def str_to_head(head, length=78, char="="): left = char * 10 + " " + head + " " return "\n" + left.ljust(length, char) + "\n" # ========== Support Functions ================================================ def parse_only(args): args_dict = vars(args) for a in args_dict: print(a.ljust(20), args_dict[a]) def get_extension(file): # a strange case for .gitignore -- it should have extension "gitignore" base, ext = os.path.splitext(file) if (base and base[0] == ".") and (os.path.splitext(file)[1] == ""): return base else: return ext def get_lines(path, verbose=True): """return lines of a file""" try: return len(open(path, "rb").readlines()) except: if verbose: print("Cannot get number of lines from %s" % path) return 0 def get_size(path, verbose=True): """return file size""" try: return os.path.getsize(path) except: if verbose: print("Cannot get size of %s" % path) return 0 def get_folders_and_files(base, folder_counter=None, file_counter=None, show_only_size=None, show_only_percent=None, total_size=None): try: _, folders, files = next(os.walk(base)) if folder_counter is not None and file_counter is not None: folders = [fo for fo in folders if os.path.join(base, fo) in folder_counter and (folder_counter[os.path.join(base, fo)] > show_only_size if show_only_size else True) and (folder_counter[os.path.join(base, fo)] / total_size >= show_only_percent if total_size and show_only_percent else True)] files = [fi for fi in files if os.path.join(base, fi) in file_counter and (file_counter[os.path.join(base, fi)] > show_only_size if show_only_size else True) and (file_counter[os.path.join(base, fi)] / total_size >= show_only_percent if total_size and show_only_percent else True)] return folders, files except StopIteration: pass return [], [] def get_all_ancestors(base): base = base.rstrip(os.path.sep) + os.path.sep ancestors = [] pos = base.find(os.path.sep) while pos != -1: ancestors.append(base[:pos]) pos = base.find(os.path.sep, pos + 1) return ancestors def get_top_percentile(lst, per): assert 0 <= per < 1, "Error: %f falls out of range [0, 1) as a top percentile!" % per lst.sort(reverse=True) return lst[int(per * len(lst))] # ========== Core Functions =================================================== def parse(): def override_if_defined(specific, general, default=None): return specific if specific else general if general else default example = "For example, " + yellow(sys.argv[0] + " -w *.exe -sz 1MB -ht 5% -d -k 10") + \ """ builds tree upon all the exe files. It shows in tree only the files larger than 1 MB, and highlights those whose sizes are among the top 5% (of all exe files). At each level, folders and files are sorted in descending order by size. The program reports 10 largest files at the end.""" parser = argparse.ArgumentParser(description=str_to_head("Tree Help"), add_help=True, epilog=example) parser.add_argument("root", nargs="?", help="root path of tree (default .)") what_size = parser.add_mutually_exclusive_group() what_size.add_argument("-z", "--size", dest="line", action="store_false", help="use file's size as size (default)") what_size.add_argument("-n", "--line", action="store_true", help="use file's line number as size") parser.add_argument("-w", dest="watch", nargs="*", metavar="", help="watch list (e.g. README.md *.txt 201[78]-??-??.csv)") parser.add_argument("-we", dest="watch_ext", nargs="*", metavar="", help="watch file extensions (e.g. bmp jpg png)") parser.add_argument("-wt", dest="watch_type", nargs="*", metavar="", help="watch types in predefined list (e.g. MUSIC)") parser.add_argument("-i", dest="ignore", nargs="*", metavar="", help="ignore list (e.g. temp* *.tmp ~*)") parser.add_argument("-ie", dest="ignore_ext", nargs="*", metavar="", help="ignore file extensions (e.g. exe zip)") parser.add_argument("-it", dest="ignore_type", nargs="*", metavar="", help="ignore types in predefined list (e.g. VIDEO)") parser.add_argument("-if", dest="ignore_folder", nargs="*", metavar="", help="ignore folders (e.g. .git Temp)") parser.add_argument("-m", dest="max_at_level", type=int, metavar="", help="max folders/files to show in each level") parser.add_argument("-mfo",dest="max_folders_at_level", type=int, metavar="", help="max folders to show in each level") parser.add_argument("-mfi",dest="max_files_at_level", type=int, metavar="", help="max files to show in each level") parser.add_argument("-l", dest="max_level", type=int, metavar="", help="max levels to show") parser.add_argument("-sz", dest="show_only_size", type=storage_to_size, metavar="N", help="show only folders/files whose size > N (e.g. 1MB)") parser.add_argument("-sp", dest="show_only_percent", type=percent_to_num, metavar="P%", help="show only folders/files whose percentage >= P%%") parser.add_argument("-hz", dest="highlight_size", type=storage_to_size, metavar="N", help="highlight folders/files whose size > N (e.g. 100MB)") parser.add_argument("-hp", dest="highlight_percent", type=percent_to_num, metavar="P%", help="highlight folders/files whose percentage >= P%%") parser.add_argument("-ht", dest="highlight_top", type=percent_to_num, metavar="p%", help="highlight files whose sizes are among top p%% (default 10%%)") which_first = parser.add_mutually_exclusive_group() which_first.add_argument("-fof", dest="folder_first", action="store_true", help="show folders first") which_first.add_argument("-fif", dest="folder_first", action="store_false", help="show files first") parser.add_argument("-foo", dest="folder_only", action="store_true", help="show folders only") order = parser.add_mutually_exclusive_group() order.add_argument("-bs", action="store_const", dest="order", const="by-system", help="list by system order (default)") order.add_argument("-bn", action="store_const", dest="order", const="by-name", help="sort by name") order.add_argument("-a", action="store_const", dest="order", const="ascending", help="sort by size in ascending order") order.add_argument("-d", action="store_const", dest="order", const="descending", help="sort by size in descending order") folder_order = parser.add_mutually_exclusive_group() folder_order.add_argument("-fobs", action="store_const", dest="folder_order", const="by-system", help="list folders by system order") folder_order.add_argument("-fobn", action="store_const", dest="folder_order", const="by-name", help="sort folders by name") folder_order.add_argument("-foa", action="store_const", dest="folder_order", const="ascending", help="sort folders by size in ascending order") folder_order.add_argument("-fod", action="store_const", dest="folder_order", const="descending", help="sort folders by size in descending order") file_order = parser.add_mutually_exclusive_group() file_order.add_argument("-fibs", action="store_const", dest="file_order", const="by-system", help="list files by system order") file_order.add_argument("-fibn", action="store_const", dest="file_order", const="by-name", help="sort files by name") file_order.add_argument("-fia", action="store_const", dest="file_order", const="ascending", help="sort files by size in ascending order") file_order.add_argument("-fid", action="store_const", dest="file_order", const="descending", help="sort files by size in descending order") parser.add_argument("-wc", dest="width_control", type=int, metavar="", help="width control") parser.add_argument("-il", dest="indentation_length", type=nonnegative, metavar="", help="indentation length (e.g. 2 for ├──, 4 for ├────)") parser.add_argument("-x", dest="extra", action="count", help="extra indentation length (e.g. -xxx to add 3)") parser.add_argument("-dns", dest="squeeze", action="store_false", help="do not squeeze long names (may break display format)") parser.add_argument("-k", dest="top_k", type=int, metavar="", help="report top K folders/files in size (default K = 5)") parser.add_argument("-kfo", dest="top_k_folders", type=int, metavar="", help="report top K files in size") parser.add_argument("-kfi", dest="top_k_files", type=int, metavar="", help="report top K folders in size") parser.add_argument("-v", dest="verbose", action="store_true", help="verbose (show skips and errors)") parser.add_argument("-po", dest="parse_only", action="store_true", help="show parsed command-line arguments only (for debug)") parser.add_argument("-ro", dest="report_only", action="store_true", help="show report only") parser.add_argument("-to", dest="tree_only", action="store_true", help="show tree only") case_sensitivity = parser.add_mutually_exclusive_group() case_sensitivity.add_argument("-cs", dest="case_sensitive", action="store_true", help="case sensitive in matching (override system)") case_sensitivity.add_argument("-ci", dest="case_sensitive", action="store_false", help="case insensitive in matching (override system)") parser.set_defaults(help=False, root=".", line=False, folder_only=False, folder_first=True, watch=[], watch_ext=[], watch_type=[], ignore=[], ignore_ext=[], ignore_type=[], ignore_folder=[], highlight_percent=0.1, highlight_top=0.1, indentation_length=4, extra=0, width_control=60, squeeze=True, top_k=5, verbose=False, report_only=False) args = parser.parse_args() # override program-wide case sensitivity if not args.case_sensitive: args.case_sensitive = platform.system() == "Linux" def case(s): return s if args.case_sensitive else s.lower() args.root = args.root.rstrip(os.path.sep) + os.path.sep assert os.path.isdir(args.root), "Error: %s is not a valid directory!" % args.root args.folder_order = override_if_defined(args.folder_order, args.order, "by-system") args.file_order = override_if_defined(args.file_order, args.order, "by-system") for t in args.ignore_type: if t.upper() in TYPE_DICT: args.ignore_ext.extend(TYPE_DICT[t]) else: print("Error: %s is not in predefined type list!" % t) print("Current type list:", list(TYPE_DICT.keys())) return for ext in args.ignore_ext: ext = ext.lstrip("*.") args.ignore.append("*." + case(ext)) args.ignore = sorted(list(set(args.ignore))) args.ignore_folder = sorted(list(set([case(x).strip(os.path.sep) for x in args.ignore_folder]))) for t in args.watch_type: if t.upper() in TYPE_DICT: args.watch_ext.extend(TYPE_DICT[t.upper()]) else: print("Error: %s is not in predefined type list!" % t) print("Current type list:", list(TYPE_DICT.keys())) return for ext in args.watch_ext: ext = ext.lstrip("*.") args.watch.append("*." + case(ext)) args.watch = sorted(list(set(args.watch) - set(args.ignore))) # watch_all if (1) watch has * or (2) watch is empty args.watch_all = "*" in args.watch or not bool(args.watch) args.max_folders_at_level = override_if_defined(args.max_folders_at_level, args.max_at_level) args.max_files_at_level = override_if_defined(args.max_files_at_level, args.max_at_level) args.indentation_length += args.extra args.top_k_folders = override_if_defined(args.top_k_folders, args.top_k) args.top_k_files = override_if_defined(args.top_k_files, args.top_k) args.width_control = max(args.width_control, 25) if args.parse_only: parse_only(args) return return args def scan(tree, base="."): def update_folder_count(tree, base_count, base): """update size for ancestors of a file in base folder""" ancestors = get_all_ancestors(base) for a in ancestors: if a in tree.folder_counter: tree.folder_counter[a] += base_count else: tree.folder_counter[a] = base_count def print_scanning(tree, base): print("Found in %d places, now at %s" % (len(tree.folder_counter), visual_just(base, tree.args.width_control)), end="\r") def print_skipping(tree, base, folder): if tree.args.verbose: print("Skipping %s" % visual_just(os.path.join(base, folder), tree.args.width_control)) def get_max_num_digits(tree): if tree.args.line: max_count = Top_1_And_Which() for f in os.listdir("."): path = os.path.join(".", f) if path in tree.folder_counter: max_count.push(tree.folder_counter[path], path) elif path in tree.file_counter: max_count.push(tree.file_counter[path], path) value = max_count.get_value() return int(math.log10(value) * 4 / 3) + 1 if value else 1 # use thousand sep else: return 10 # say 1,023.4 KB def summarize(tree): print(" " * 200, end="\r") tree.total_size = tree.folder_counter["."] if tree.folder_counter else 0 tree.num_folders = len(tree.folder_counter) tree.num_files = len(tree.file_counter) tree.max_num_digits = get_max_num_digits(tree) tree.total_width = tree.args.width_control + tree.max_num_digits * 2 + 21 file_count = list(tree.file_counter.values()) if tree.args.highlight_top: tree.top_size_to_highlight = get_top_percentile(file_count, tree.args.highlight_top) if tree.file_counter else 0 tree.top_files.sort() tree.top_folders.sort() folder_list, file_list = get_folders_and_files(base) level = base.count(os.path.sep) for folder in folder_list: if match(tree.case(folder), tree.args.ignore_folder): print_skipping(tree, base, folder) else: scan(tree, os.path.join(base, folder)) print_scanning(tree, base) base_count = 0 for file in file_list: if match(tree.case(file), tree.args.watch) or (tree.args.watch_all and not match(tree.case(file), tree.args.ignore)): path = os.path.join(base, file) tree.file_counter[path] = size = tree.get_from(path) base_count += size tree.top_files.push(size, path) if base_count != 0: update_folder_count(tree, base_count, base) tree.top_folders.push(base_count, base) if base == ".": summarize(tree) def print_line(tree, level, folder_or_file_name, size, is_folder, is_rest_file=False): args = tree.args s = "" if args.indentation_length: for is_last in level[:-1]: s += (" " if is_last else "│ ") + " " * (args.indentation_length - 1) s += ("└─" if level[-1] else "├─") + "─" * (args.indentation_length - 1) s += folder_or_file_name print(visual_just(s, args.width_control, args.squeeze), end=" ") if not is_folder: print(" " * (12 + tree.max_num_digits), end="") if is_folder: print(colorama.Style.BRIGHT + colorama.Fore.GREEN, end="") percent = 1.0 if tree.total_size == 0 else size / tree.total_size # consider empty files with 0 storage if (args.highlight_size and size > args.highlight_size) or (args.highlight_percent and percent >= args.highlight_percent): print(colorama.Style.BRIGHT + colorama.Fore.RED if is_folder else colorama.Fore.CYAN, end="") if tree.top_size_to_highlight and not (is_folder or is_rest_file) and size >= tree.top_size_to_highlight: print(colorama.Fore.CYAN, end="") # do not highlight rest files (...) if args.line: print("%%%ds" % tree.max_num_digits % sep(size), end=" ") else: # %10s: say 1,023.4 MB print("%10s" % size_to_storage(size), end=" ") # %5.1 %%: say 100.0 % print("%5.1f %%" % (percent * 100) + colorama.Style.RESET_ALL) def show_folders(tree, base, base_level, folder_list, has_files_at_same_level): args = tree.args folder_counter = tree.folder_counter if args.folder_order != "by-system": if args.folder_order == "by-name": folder_list.sort() else: folder_list.sort(key=lambda f: folder_counter[os.path.join(base, f)], reverse=args.folder_order=="descending") last = len(folder_list) - 1 if args.max_folders_at_level is not None: last = min(args.max_folders_at_level, last) for i, folder in enumerate(folder_list): path = os.path.join(base, folder) level = base_level.copy() # ---------- determine whether to print ├ or └ ---------- # print └ only when # a folder (1) has last index and (2) has no files after it # while condition (2) translates to # (a) folder only, or # (b) file first, or # (c) folder first but has no files at same level # note that conditions (b) and (c) combines to # (d) not (folder first and has files at same level) level.append((i == last) and (args.folder_only or not (args.folder_first and has_files_at_same_level))) if i == args.max_folders_at_level: rest = 0 for j in range(i, len(folder_list)): rest += folder_counter[os.path.join(base, folder_list[j])] print_line(tree, level, os.path.sep + "...", rest, True) break else: print_line(tree, level, folder, folder_counter[path], True) if args.max_level is not None and len(level) + 1 > args.max_level: level.append(True) print_line(tree, level, "...", folder_counter[path], True) else: show(tree, path, level) def show_files(tree, base, base_level, file_list, has_folders_at_same_level): args = tree.args file_counter = tree.file_counter if args.file_order != "by-system": if args.file_order == "by-name": file_list.sort() else: file_list.sort(key=lambda f: tree.file_counter[os.path.join(base, f)], reverse=args.file_order=="descending") last = len(file_list) - 1 if args.max_files_at_level is not None: # args.max_files_at_level could be 0, which is not None last = min(args.max_files_at_level, last) for i, file in enumerate(file_list): path = os.path.join(base, file) level = base_level.copy() # ---------- determine whether to print ├ or └ ---------- # print └ only when # a file (1) has last index and (2) has no folder after it # while condition (2) translates to # (a) folder first, or # (b) file first but has no folders at same level level.append((i == last) and (args.folder_first or not has_folders_at_same_level)) if i == args.max_files_at_level: rest = 0 for j in range(i, len(file_list)): rest += file_counter[os.path.join(base, file_list[j])] print_line(tree, level, "...", rest, False, True) break else: print_line(tree, level, file, file_counter[path], False) def show(tree, base=".", base_level=[]): args = tree.args folder_list, file_list = get_folders_and_files(base, tree.folder_counter, tree.file_counter, args.show_only_size, args.show_only_percent, tree.total_size) if args.folder_first: show_folders(tree, base, base_level, folder_list, bool(file_list)) if not args.folder_only: show_files(tree, base, base_level, file_list, bool(folder_list)) else: if not args.folder_only: show_files(tree, base, base_level, file_list, bool(folder_list)) show_folders(tree, base, base_level, folder_list, bool(file_list)) def report(tree): def report_top_k(tree, head, is_folder): args = tree.args top = tree.top_folders if is_folder else tree.top_files value, which = top.get() wlen = args.width_control + tree.max_num_digits + 20 print(str_to_head(head, tree.total_width)) for i in range(len(value)): print(visual_just(which[i], wlen, args.squeeze), end=" ") print(colorama.Fore.CYAN, (sep(value[i]) if args.line else size_to_storage(value[i])).rjust(tree.max_num_digits), colorama.Style.RESET_ALL, sep="") args = tree.args print(str_to_head("Summary", tree.total_width)) if args.line: print("Total %s %s in" % (sep(tree.total_size), plural("line", tree.total_size)), end=" ") else: print("Total storage %s by" % size_to_storage(tree.total_size), end=" ") print("%s %s in %s %s." % (sep(tree.num_files), plural("file", tree.num_files), sep(tree.num_folders), plural("folder", tree.num_folders))) if args.highlight_size: print("\nHighlight files whose %s are more than" % ("line numbers" if args.line else "sizes"), "%s" % (sep(int(args.highlight_size)) if args.line else size_to_storage(args.highlight_size)) + ".") if args.highlight_percent: print("\nHighlight files whose %s percentages are greater than or equal to %.1f%%." % ("line numbers" if args.line else "sizes", args.highlight_percent * 100)) if tree.top_size_to_highlight: print("\nHighlight files whose %s are over top %.1f%% percentile, which is" % ("line numbers" if args.line else "sizes", args.highlight_top * 100), "%s" % (sep(int(tree.top_size_to_highlight)) if args.line else size_to_storage(tree.top_size_to_highlight)) + ".") if args.top_k_folders: head = "Top %d %s (excluding sub-folders)" % (args.top_k_folders, plural("folder", args.top_k_folders)) report_top_k(tree, head, True) if args.top_k_files: head = "Top %d %s" % (args.top_k_files, plural("file", args.top_k_files)) report_top_k(tree, head, False) print(str_to_head("Information", tree.total_width)) print("Working directory", os.getcwd()) print("\nFor help, run " + yellow(sys.argv[0] + " -h") + " or " + yellow(sys.argv[0] + " --help")) def main(): colorama.init() args = parse() if args: tree = Tree(args) os.chdir(tree.args.root) scan(tree) if not args.report_only: show(tree) if not args.tree_only: report(tree) if __name__ == '__main__': main() <file_sep>![](gol.png) - [source](gol.py) [Back to Main](https://github.com/aafulei/little-python)
5c1b845f325441834c0c48889943b30372de7557
[ "Markdown", "Python" ]
11
Python
aafulei/little-python
940ad7c47f3763a2ebec3e6ee7c2ee5564263e28
364dfb864ef1a8f560a91990299696c725dba685
refs/heads/master
<repo_name>zhaifengguang/location_odom<file_sep>/README.md # location_odom ROS Closest Landmark Find the closest landmark in turtlebot world by subscribing the ROS Navigation Odometry message cd ~/catkin_ws/src sudo git clone https://github.com/kennedywai/location_odom.git cd .. catkin_make cd roslaunch turtlebot_gazebo turtlebot_world.launch roslaunch turtlebot_teleop keyboard_teleop.launch rosrun location_odom odom_sub_node (source /opt/ros/indigo/setup.bash) *****Map Building***** roslaunch turtlebot_navigation gmapping_demo.launch (http://answers.ros.org/questivon/205312/no-matching-devices-founded-error-for-gmapping_demolaunch-turtlebot/) roslaunch turtlebot_rviz_launchers view_navigation.launch rosrun map_server map_saver -f /tmp/my_map *****Navigation***** roslaunch turtlebot_gazebo amcl_demo.launch map_file:=/tmp/my_map.yaml roslaunch turtlebot_rviz_launchers view_navigation.launch --screen <file_sep>/src/odom_sub_node.cpp #include "ros/ros.h" #include "nav_msgs/Odometry.h" #include "location_odom/LandmarkDistance.h" #include <math.h> #include <vector> #include <string> //using namespace std; using std::vector; using std::string; using location_odom::LandmarkDistance; class Landmark{ public: Landmark(string name, double x, double y):name(name), x(x), y(y){ } string name; double x; double y; }; class LandmarkMonitor{ public: LandmarkMonitor(): landmarks_(){ InitLandmarks(); } void OdomCallback(const nav_msgs::Odometry::ConstPtr& msg){ double x = msg->pose.pose.position.x; double y = msg->pose.pose.position.y; LandmarkDistance ld = FindClosest(x, y); //ROS_INFO("x= %f, y=%f",x,y); ROS_INFO("name: %s, d: %f", ld.name.c_str(),ld.distance); } private: vector<Landmark> landmarks_; LandmarkDistance FindClosest(double x, double y){ LandmarkDistance result; result.distance = -1;// distance can never be negative for(int i = 0; i< landmarks_.size(); i++){ const Landmark& landmark = landmarks_[i]; double x_distance = landmark.x - x; double y_distance = landmark.y - y; double distance = sqrt((x_distance*x_distance) + (y_distance*y_distance)); if (result.distance < 0 || distance < result.distance){ result.name = landmark.name; result.distance = distance; } } return result; } void InitLandmarks(){ landmarks_.push_back(Landmark("Cube", 0.31, -0.99)); landmarks_.push_back(Landmark("Dumpster", 0.11, -2.42)); landmarks_.push_back(Landmark("Cylinder", -1.14, -2.88)); landmarks_.push_back(Landmark("Barrier", -2.59, -0.83)); landmarks_.push_back(Landmark("Bookshelf", -0.09, 0.53)); } }; /* void OdomCallback(const nav_msgs::Odometry::ConstPtr& msg){ double x = msg->pose.pose.position.x; double y = msg->pose.pose.position.y; //LandmarkDistance ld = FindClosest(x, y); ROS_INFO("x= %f, y=%f",x,y); //ROS_INFO("name: %s, d: %f", ld.name.c_str(),ld.distance); } */ int main(int argc,char** argv){ ros::init(argc, argv, "location_odom"); ros::NodeHandle nh; LandmarkMonitor landmark_monitor; ros::Subscriber sub = nh.subscribe("odom", 10, &LandmarkMonitor::OdomCallback, &landmark_monitor); //ros::Subscriber sub = nh.subscribe("odom", 10, OdomCallback); ros::spin(); return 0; }
62bb7a44e0fb72f51ee3c0e27794997bc7a60329
[ "Markdown", "C++" ]
2
Markdown
zhaifengguang/location_odom
ef40670a297699078a6207cb62de5215793daf55
0e7c0cf1978fd1bf0868d30e2f578c475f01f84a
refs/heads/master
<repo_name>szabadkai/ipython3-versioncontrol<file_sep>/tests/ReadPyTests.py import unittest from app.ReadPy import ReadPy class ToPyTests(unittest.TestCase): def test_object_creation(self): tp = ReadPy() <file_sep>/tests/NotebookTests.py import unittest from app.Notebook import Cell, Notebook class NotebookTests(unittest.TestCase): def test_cell_object(self): self.assertRaises(TypeError, Cell, "") def test_cell_object_init_source(self): cell = Cell({'cell_type': 'code', 'source': ['a', 'b']}) self.assertListEqual(cell.source, ['a', 'b']) def test_cell_object_init_cell_type(self): cell = Cell({'cell_type': 'code', 'source': ['a', 'b']}) self.assertEquals(cell.type, 'code') def test_cell_object_init_missing_celltype(self): self.assertRaises(KeyError, Cell, {'source': ['a', 'b']}) def test_cell_object_init_missing_source(self): self.assertRaises(KeyError, Cell, {'cell_type': 'code'}) def test_cell_object_to_dict_method(self): cell = Cell({'cell_type': 'code', 'source': ['a', 'b']}) self.assertDictEqual(cell.to_dict(), {'cell_type': 'code', 'source': ['a', 'b']}) def test_cell_object_to_generate_output_method(self): cell = Cell({'cell_type': 'code', 'source': ['a', 'b']}) print cell.generate_field_output() self.assertEquals('\n# <codecell>\n\nab\n', cell.generate_field_output()) def test_notebook_object(self): nb = Notebook() self.assertIsInstance(nb, Notebook) def test_notebook_read_ipynb_file(self): nb = Notebook() nb.read_notebook("tests/test.ipynb") self.assertNotEqual(nb.notebook_format, None) def test_notebook_read_ipynb_file_without_cells(self): nb = Notebook() self.assertRaises(ValueError, nb.read_notebook, "tests/test2.ipynb") def test_notebook_read_ipynb_file_cell_loading(self): nb = Notebook() nb.read_notebook("tests/test.ipynb") self.assertGreater(len(nb.cells), 0) def test_notebook_read_py_file_cell_loading(self): nb = Notebook() nb.read_py("tests/test.py") self.assertGreater(len(nb.cells), 0) def test_notebook_read_ipynb_file_cell_type(self): nb = Notebook() nb.read_notebook("tests/test.ipynb") self.assertIsInstance( nb.cells[0], Cell) def test_notebook_read_py_as_notebook_error(self): nb = Notebook() self.assertRaises(ValueError, nb.read_notebook, "tests/test.py") def test_notebook_add_descriptive_data_no_nbformat(self): nb = Notebook() self.assertRaises(IOError, nb.add_descriptive_data, ['', "if '<nmat>' in lines[1]:"]) def test_notebook_read_ipynb_file_nbformat(self): nb = Notebook() nb.add_descriptive_data(open("tests/test.py", 'r').readlines()) self.assertEquals(nb.notebook_format, 4) def test_notebook_to_dict_method(self): nb = Notebook() nb.add_descriptive_data(['', "# <nbformat>4</nbformat>"]) self.assertEquals(nb.to_dict()["nbformat"], 4) def test_if_notebooks_are_the_same_from_different_input_types(self): nb = Notebook() nb.read_notebook("tests/test.ipynb") nb2 = Notebook() nb2.read_py("tests/test.py") self.assertEqual(nb.to_dict(), nb.to_dict()) if __name__ == '__main__': unittest.main()<file_sep>/app/NotebookConverter.py import os import fnmatch from Notebook import Notebook class NotebookConverter(object): def convert_all(self, directory, formater): for root, dirnames, filenames in os.walk(directory): for filename in fnmatch.filter(filenames, '*.ipynb'): filename = os.path.abspath(os.path.join(root, filename)) self.convert(filename, formater) @staticmethod def convert(input_file_path, formater): output_file_path = formater.construct_output_path(input_file_path) if not os.path.exists(output_file_path) or formater.overwrite: nb = Notebook() nb.read(input_file_path) if not formater.dry_run: formater.output(nb, output_file_path) print "Created file: {}".format(output_file_path) <file_sep>/tests/NotebookConverterTests.py import unittest from app.NotebookConverter import NotebookConverter class NotebookToPyTests(unittest.TestCase): def test_object_generation(self): nbconverter = NotebookConverter() self.assertIsInstance(nbconverter, NotebookConverter) if __name__ == '__main__': unittest.main() <file_sep>/app/ReadPy.py from app.Notebook import Cell class ReadPy(object): current_cell = None execution_count = 1 _outputcells = [] def read(self, path_to_file): skip_one_line = False with open(path_to_file, 'r') as lines: self.add_descriptive_data(lines.readlines()) lines.seek(0) for line in lines: if skip_one_line: skip_one_line = False elif self.is_first_line_of_cell(line): self.close_cell() if self.current_cell == 'code': self.execution_count += 1 self.open_cell(line, self.execution_count) skip_one_line = True elif self.current_cell.type in ('markdown', 'code'): self.append_line_to_source(line) self.close_last_cell() return self._outputcells def close_cell(self): if self.current_cell.type in ('markdown', 'code'): if len(self.current_cell.source) > 1: del self.current_cell.source[-1:] self.current_cell.source[-1] = self.current_cell.source[-1].rstrip('\n') self._outputcells.append(self.current_cell) def close_last_cell(self): if self.current_cell.type in ['markdown', 'code']: self.current_cell.source[-1] = self.current_cell.source[-1].rstrip('\n') self._outputcells.append(self.current_cell) def open_cell(self, line, execution_count): if '<markdowncell>' in line: self.current_cell = Cell({'cell_type': 'markdown', 'metadata': {}, 'source':[]}) else: self.current_cell = Cell({'cell_type': 'code', 'execution_count': execution_count, 'metadata': {'collapsed': False}, 'outputs': []}) def append_line_to_source(self, row): if self.current_cell.type == 'markdown': self.current_cell.source.append(row.lstrip("# ")) elif self.current_cell.type == 'code': self.current_cell.source.append(row) @staticmethod def is_first_line_of_cell(line): if line == '# <markdowncell>\n' or line == '# <codecell>\n': return True return False def add_descriptive_data(self, lines): self.metadata = self.create_metadata() self.notebook_format = self.read_nb_format_from_py(lines) self.nbformat_minor = 0 @staticmethod def create_metadata(): kernelspec = {'display_name': 'Python 2', 'language': 'python', 'name': 'python2'} language_info = {'codemirror_mode': {'name': 'ipython', 'version': 2}, 'file_extension': '.py', 'mimetype': 'text/x-python', 'name': 'python', 'nbconvert_exporter': 'python', 'pygments_lexer': 'ipython2', 'version': '2.7.10'} metadata = {'kernelspec': kernelspec, 'language_info': language_info} return metadata @staticmethod def read_nb_format_from_py(lines): if '<nbformat>' in lines[1]: nbformat = lines[1].split('>')[1].split('<')[0] if "." in nbformat: nbformat = float(nbformat) else: nbformat = int(nbformat) return nbformat else: raise IOError("No or not suitable ( line[1]: "+lines[1]+") nbformat in supported lines")<file_sep>/app/Notebook.py import json import os from ReadPy import ReadPy class Notebook(object): notebook_format = None cells = [] metadata = None nbformat_minor = None def read(self, path_to_file): input_headless, ext = os.path.splitext(path_to_file) if ext == ".ipynb": self.read_notebook(path_to_file) elif ext == ".py": self.read_py(path_to_file) def read_notebook(self, path_to_file): with open(path_to_file, 'r') as notebook: notebook_data = json.load(notebook) self.notebook_format = notebook_data["nbformat"] assert "cells" in notebook_data.keys(), "Nbformat is " + str(notebook_data['nbformat']) \ + ", try the old converter script." for cell in notebook_data["cells"]: self.cells.append(Cell(cell)) @staticmethod def read_py(path_to_file): reader = ReadPy() reader.read(path_to_file) def to_dict(self): cells = {'metadata': self.metadata, 'nbformat': self.notebook_format, 'nbformat_minor': self.nbformat_minor, 'cells': []} for cell in self.cells: cells['cells'].append(cell.to_dict()) return cells class Cell(object): def __init__(self, cell): self.type = cell['cell_type'] self.source = cell["source"] def generate_field_output(self): output = '\n# <' + self.type + 'cell' + '>\n\n' for item in self.source: if self.type == "code": output += item else: output += "# " + item return output + "\n" def to_dict(self): return {'cell_type': self.type, 'source': self.source} <file_sep>/app/py_to_notebook_v4.py """ This script converts a .py file to Ipython v4 notebook format. The .py file must be a result of an Ipython -> .py conversion using the notebook_v4_to_py.py script or the automatic post-hook save in Ipyhon 3 based on that script. In this way the version controlled .py files can be converted back to Ipython notebook format. Call this script with argument "-f" to create an .ipynb file from a .py file: python py_to_notebook_v4.py -f filename.py Call the script with argument "--overwrite" to overwrite existing .ipynb files. Call the script with argument "--dry-run" to simulate (print) what would happen. Date: 07. August 2015. ############################################################################# This script is released under the MIT License Copyright (c) 2015 Balabit SA Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from app.NotebookConverter import NotebookConverter from app.Formatter import ToNotebook if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-w', '--overwrite', action='store_true', help='Overwrite existing py files', default=False) parser.add_argument('-f', '--file', help='Specify an Ipython notebook if you only want to convert one. ' '(This will overwrite default.)') parser.add_argument('--dry-run', action='store_true', help='Only prints what would happen', default=False) args = parser.parse_args() py2nb = NotebookConverter() fm = ToNotebook() if args.file is not None: py2nb.convert(args.file, ToNotebook(overwrite=args.overwrite, dry_run=args.dry_run)) else: py2nb.convert_all('.', ToNotebook(overwrite=args.overwrite, dry_run=args.dry_run)) <file_sep>/app/notebook_v4_to_py.py """ The script takes an .ipynb file (or all such files in the directory), and, if it doesn't already have a corresponding .py file, creates it from the .ipynb file. We do this because we don't want to version-control .ipynb files (which can contain images, matrices, data frames, etc), but we do want to save the content of the notebook cells. This is intented to be a replacement of the deprecated ipython notebook --script command for Ipython 2 notebooks that automatically saved notebooks as .py files that can be version controled. Optionally, the first three functions can be used for post-hook autosave in the ipython_notebook_config.py file. Call this script with argument "-f" to create a .py file from notebook: python notebook_v4_to_py.py -f filename.ipynb Call the script with argument "--overwrite" to overwrite existing .py files. Date: 07. August 2015. ############################################################################# This script is released under the MIT License Copyright (c) 2015 Balabit SA Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from app.Formatter import ToPy from app.NotebookConverter import NotebookConverter if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-w', '--overwrite', action='store_true', help='Overwrite existing py files', default=False) parser.add_argument('-f', '--file', help='Specify an Ipython notebook if you only want to convert one. ' '(This will overwrite default.)') args = parser.parse_args() nb2py = NotebookConverter() overwrite=not args.overwrite if args.file is not None: nb2py.convert(args.file, ToPy(args.file, overwrite)) else: nb2py.convert_all('.', ToPy(overwrite)) <file_sep>/tests/FormaterTests.py import unittest import os from app.Formatter import ToNotebook, ToPy class FormaterTests(unittest.TestCase): def test_topy_class_creation(self): topy = ToPy() self.assertIsInstance(topy, ToPy) def test_to_notebook_class_creation(self): tonb = ToNotebook() self.assertIsInstance(tonb, ToNotebook) def test_topy_empty_constructor_creation(self): topy = ToPy() self.assertEquals((topy.dry_run, topy.overwrite), (False, False)) def test_to_notebook_empty_constructor_creation(self): tonb = ToNotebook() self.assertEquals((tonb.dry_run, tonb.overwrite), (False, False)) def test_nb_constructor(self): tonb = ToNotebook(True, True) self.assertEquals((tonb.dry_run, tonb.overwrite), (True, True)) def test_py_constructor(self): topy = ToPy(True, True) self.assertEquals((topy.dry_run, topy.overwrite), (True, True)) def test_topy_construct_path_method(self): topy = ToPy() path = topy.construct_output_path('a.exe') self.assertEquals(path, 'a.py') def test_tonb_construct_path_method(self): topy = ToNotebook() path = topy.construct_output_path('a.exe') self.assertEquals(path, 'a.ipynb') def test_add_header_method(self): with open('header', 'w') as header: topy = ToPy() topy.add_header(header, '4') with open('header', 'r') as header: tmp = header.readlines() os.remove('header') self.assertEquals((tmp[0], tmp[1]), ('# -*- coding: utf-8 -*-\n', '# <nbformat>4</nbformat>\n')) if __name__ == '__main__': unittest.main() <file_sep>/app/Formatter.py import abc import json import os class Formater(): __metaclass__ = abc.ABCMeta @abc.abstractmethod def output(self, notebook, out_path): """Outputs the notebook data in the desired form""" return @staticmethod @abc.abstractmethod def construct_output_path(input_path): return class ToNotebook(Formater): dry_run = None overwrite = None def __init__(self, overwrite=False, dry_run=False): self.overwrite = overwrite self.dry_run = dry_run def output(self, notebook, out_path): output = notebook.to_dict() self.write_py_data_to_notebook(output, out_path) @staticmethod def construct_output_path(input_path): input_headless, ext = os.path.splitext(input_path) return input_headless + ".ipynb" @staticmethod def write_py_data_to_notebook(output, out_file_path): with open(out_file_path, 'w') as outfile: json.dump(output, outfile) class ToPy(Formater): def __init__(self, overwrite=False, dry_run=False,): self.overwrite = overwrite self.dry_run = dry_run def output(self, notebook, out_path): with open(out_path, 'w') as output: self.add_header(output, str(notebook.notebook_format)) for cell in notebook.cells: output.write(cell.generate_field_output()) @staticmethod def construct_output_path(input_path): input_headless, ext = os.path.splitext(input_path) return input_headless + ".py" @staticmethod def add_header(output, notebook_format): assert isinstance(output, file) assert isinstance(notebook_format, str) output.write('# -*- coding: utf-8 -*-\n') output.write('# <nbformat>' + notebook_format + '</nbformat>\n')
bcf345e0b483d2d0215d9eeaa080696649bacfed
[ "Python" ]
10
Python
szabadkai/ipython3-versioncontrol
efc6019b8463b822adb80e0810607069af8f41c0
7e862c0c21d7fd974a3a9caeba6f6e2c373195c5
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> double time_diff(struct timeval x , struct timeval y); int main(int argc, char *argv[]) { /** Declaracon de variables para medir el tiempo **/ struct timeval before , after; int matrixsize, i, j, *numbers; unsigned int histogram[256] = {0}; /** Se da la partida al reloj **/ /** Ficheros de entrada y salida **/ FILE *in = fopen(argv[1], "r"); FILE *out = fopen("salida", "w"); /** Leer el primer numero que determina el tamano de la matriz **/ fscanf(in, "%d", &matrixsize); /** Asigna dinamicamente el tamano necesario para almacenar los enteros **/ numbers = (int *)malloc(matrixsize * matrixsize * sizeof(int)); /** Asigna todos los enteros a un arreglo **/ for (i = 0; i < matrixsize * matrixsize && fscanf(in, "%d", &numbers[i]) == 1; ++i); fclose(in); gettimeofday(&before , NULL); /** Recorre el arreglo y compara cada numero con la histogram para sumar 1 al contador del numero calzado **/ for (i = 0; i < matrixsize * matrixsize; i++) histogram[numbers[i]]++; gettimeofday(&after , NULL); /** Escribe en el archivo out la cantidad de cada numero encontrado **/ for (i = 0; i < 256; i++) { if (i == 255) fprintf(out, "%d", histogram[i]); else fprintf(out, "%d\n", histogram[i]); } /** Parar el reloj **/ printf("Tiempo de ejecucion: %f [ms]\n" , time_diff(before , after) ); fclose(out); return 0; } /** Funcion que retorna una diferencia en milisegundos de dos variables, sacada de internet **/ /** Link: http://www.binarytides.com/get-time-difference-in-microtime-in-c/ **/ double time_diff(struct timeval x , struct timeval y) { double x_ms , y_ms , diff; x_ms = (double)x.tv_sec*(double)1000 + (double)x.tv_usec/(double)1000; y_ms = (double)y.tv_sec*(double)1000 + (double)y.tv_usec/(double)1000; diff = (double)y_ms - (double)x_ms; return diff; }
6218eadc93b97efbe45f01532051c4b4c978d9ce
[ "C" ]
1
C
thwmax/S.O
7da088aea588ee119746b2391d1c0ea39969170e
cc062815604c55bd7eb16f2da6bcd666eafe9749
refs/heads/master
<file_sep>package net.shawnklein.android.remotecontrol; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class RemoteControlFragment extends Fragment { private TextView mSelectedTextView; private TextView mWorkingTextView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { View v = inflater(R.layout.fragment_remote_control, parent, false); mSelectedTextView = (TextView)v.findViewById(R.id.fragment_remote_control_selectedTextView); mWorkingTextView = (TextView)v.findViewById(R.id.fragment_remote_control_workingtextView); View.OnClickListener numberButtonListener = new View.OnClickListener() { public void onClick(View v) { TextView textView = (TextView)v; String working = mWorkingTextView.getText().toString(); String text = textView.getText().toString(); if (working.equals("0")) { mWorkingTextView.setText(text); } else { mWorkingTextView.setText(working + text); } } }; return v; } }
3806cf1f91124f26da64503fc833859e1b9e9767
[ "Java" ]
1
Java
Carpk/RemoteControl
c5335e0b7649e8a62d7fe296d04af1e17dc2c39f
d868f2957fe3697f4df9d65e492de4b5ce26df07
refs/heads/master
<repo_name>madisonscott/15-112<file_sep>/source/circuit.py from Tkinter import * import components class Circuit: def __init__(self, canvas, left, top, right, bottom): self.canvas = canvas (self.left, self.right) = (left, right) (self.top, self.bottom) = (top, bottom) self.margin = 20 self.cellSize = 25 self.rows = ((bottom-top) - (self.margin*2)) / self.cellSize self.cols = ((right-left) - (self.margin*2)) / self.cellSize self.color = "gainsboro" def drawGrid(self): canvas = self.canvas (rows,cols) = (self.rows,self.cols) cellSize = self.cellSize margin = self.margin gridColor = self.color for row in xrange(rows+1): y = margin + row*cellSize left = self.left + margin right = left + cols*cellSize canvas.create_line(left,y,right,y,fill=gridColor) canvas.create_text(left-10,y,text=row) for col in xrange(cols+1): x = left + col*cellSize top = margin bottom = top + rows*cellSize canvas.create_line(x,top,x,bottom,fill=gridColor) for col in xrange(cols+1): x = left + col*cellSize top = margin canvas.create_text(x,top-10,text=col) ################################################################## # FULL CIRCUIT ################################################################## def drawCircuit(canvas): components = canvas.data.components for thing in components: for component in components[thing]: component.draw() <file_sep>/source/simpleCircuit.py import components def demo(canvas): canvas.data.components["source"] = [components.Source(canvas,355,270)] canvas.data.components["source"][0].voltage = 5.0 canvas.data.components["wires"] = [components.Wire(canvas,355,195,355,245), components.Wire(canvas,355,195,405,195), components.Wire(canvas,455,195,480,195), components.Wire(canvas,530,195,555,195), components.Wire(canvas,355,345,555,345), components.Wire(canvas,355,295,355,345), components.Wire(canvas,555,195,555,245), components.Wire(canvas,555,295,555,345)] canvas.data.components["resistors"] = [components.Resistor(canvas,430,195), components.Resistor(canvas,505,195), components.Resistor(canvas,555,270)] for i in xrange(len(canvas.data.components["resistors"])): res = canvas.data.components["resistors"][i] if (i % 2 == 0): res.resistance = 1000 else: res.resistance = 500 canvas.data.components["resistors"][2].orient = 1 canvas.data.components["diodes"] = [] canvas.data.components["ground"] = [components.Ground(canvas,480,370)] <file_sep>/source/controls.py from Tkinter import * import components import solver class Menu: def __init__(self,canvas,left,top,right,bottom): self.canvas = canvas (self.left, self.right) = (left, right) (self.top, self.bottom) = (top, bottom) self.color = "dim gray" self.solveButton = Button(canvas,520,"solve") self.editButton = Button(canvas,520,"edit") canvas.data.mButts = [Button(canvas, 10,"new"), Button(canvas, 95,"source"), Button(canvas,180,"wire"), Button(canvas,265,"resistor"), Button(canvas,350,"diode"), Button(canvas,435,"ground"), self.solveButton, Button(canvas,canvas.data.width-170,"help"), Button(canvas,canvas.data.width-85,"quit")] def drawMenu(self): canvas = self.canvas (left, right) = (self.left, self.right) (top, bottom) = (self.top, self.bottom) fill = self.color canvas.create_rectangle(left,top,right,bottom, fill=fill,width=0) if (canvas.data.editCircuit == False): canvas.data.mButts[6] = self.editButton else: canvas.data.mButts[6] = self.solveButton for button in canvas.data.mButts: button.drawButton() button.drawButtonImage() class Button: def __init__(self,canvas,left,function): self.canvas = canvas self.color = "gainsboro" self.left = left self.right = left + 75 self.top = canvas.data.buttonTop self.bottom = canvas.data.buttonBottom self.function = function def drawButton(self): canvas = self.canvas (left, right) = (self.left, self.left + 75) (top, bottom) = (self.top, self.top + 75) (cx, cy) = ((left+right)/2, (top+bottom)/2) fill = self.color canvas.create_rectangle(left,top,right,bottom, fill=fill,width=0) canvas.create_text(cx,bottom-10, text=self.function.upper(),font="Helvetica 11") def drawButtonImage(self): canvas = self.canvas (left, right) = (self.left, self.left + 75) (top, bottom) = (self.top, self.top + 75) (cx, cy) = ((left+right)/2, (top+bottom)/2) if (self.function == "new"): drawNewButton(canvas,cx,cy-5) elif (self.function == "source"): canvas.data.buttSource = components.Source(canvas,cx,cy-5) canvas.data.buttSource.draw() elif (self.function == "wire"): drawWireButton(canvas,cx,cy-5) elif (self.function == "resistor"): canvas.data.buttResistor = components.Resistor(canvas,cx,cy-5) canvas.data.buttResistor.draw() elif (self.function == "diode"): canvas.data.buttDiode = components.Diode(canvas,cx,cy-5) canvas.data.buttDiode.draw() elif (self.function == "ground"): canvas.data.buttGround = components.Ground(canvas,cx,cy) canvas.data.buttGround.draw() elif (self.function == "solve"): drawSolveButton(canvas,cx,cy-4) elif (self.function == "edit"): drawEditButton(canvas,cx,cy-8) elif (self.function == "help"): drawHelpButton(canvas,cx,cy-4) elif (self.function == "quit"): drawQuitButton(canvas,cx,cy-4) def buttonFunction(self): canvas = self.canvas function = self.function if ((canvas.data.editCircuit == True) and (canvas.data.helpScreen == False)): if (function == "new"): components.initComponents(canvas) elif (function == "source"): canvas.data.drawSource = not canvas.data.drawSource elif (function == "wire"): canvas.data.drawWire = not canvas.data.drawWire elif (function == "resistor"): canvas.data.drawResistor = not canvas.data.drawResistor elif (function == "diode"): canvas.data.drawDiode = not canvas.data.drawDiode elif (function == "ground"): canvas.data.drawGround = not canvas.data.drawGround if (function == "solve") or (function == "edit"): canvas.data.editCircuit = not canvas.data.editCircuit canvas.data.sourceError = False canvas.data.resistorError = False if (canvas.data.editCircuit == False): solver.solve(canvas) elif (function == "help"): canvas.data.helpScreen = not canvas.data.helpScreen elif (function == "quit"): canvas.root.destroy() ################################################################## # BUTTON FUNCTIONALITY ################################################################## def drawNewButton(canvas,cx,cy): left = cx - 13 top = cy - 17 right = cx + 13 bottom = cy + 17 canvas.create_polygon(left,top+9,left+9,top,right,top, right,bottom,left,bottom,width=2) def drawWireButton(canvas,cx,cy): canvas.create_line(cx-20,cy+15,cx+20,cy-15,width=2) def drawSolveButton(canvas,cx,cy): canvas.create_text(cx,cy,text="✓",font="Arial 48 bold") def drawEditButton(canvas,cx,cy): canvas.create_text(cx,cy,text="✎",font="Arial 50 bold") def drawHelpButton(canvas,cx,cy): canvas.create_text(cx,cy,text="?",font="Arial 48 bold") def helpScreen(canvas): cx = (235 + canvas.data.width)/2 cy = (540/2) (left,right) = (cx-250,cx+250) (top,bottom) = (cy-150,cy+150) helpText = """To add wires to your circuit, click WIRE and click on the grid where you'd like it to begin, then drag your mouse and release where you'd like it to end. Click WIRE again when you are finished. To add a voltage source and ground to your circuit, click and drag from either SOURCE or GROUND to where you would like to place these elements. To add circuit elements, click PARTS, then click and drag the parts into your circuit on the grid. click MENU to return to the main menu. Click and drag components to move them around on the grid. Select a component to edit by clicking on it; selected components will be outlined. To rotate the component, press "r". To edit its value, press "e". To delete the component, press "delete". When you are finished drawing your circuit, click SOLVE. Click on any node or component to see the voltage and current at the point. To return to editing your circuit, click EDIT. Press "d" to see a demo circuit. Press "s" for a simple, solvable circuit. Click HELP to exit. """ canvas.create_rectangle(left,top,right,bottom, fill = "gainsboro",width = 0) canvas.create_text(left+15,top+15,anchor=NW, text=helpText,width=((right-15)-(left+15)), font="Helvetica 12 bold") def drawQuitButton(canvas,cx,cy): canvas.create_text(cx,cy,text="X", font="Arial 48 bold") <file_sep>/README.md # 15-112 My project is a circuit solver that allows the user to draw circuits including a voltage source, resistors, and diodes, then find the current through and voltage drop across each component. In order to run the project, navigate to the source directory and run “run.py”. No external libraries are needed to run this project. <file_sep>/source/components.py from Tkinter import * import math import solver class Component(object): def __init__(self,canvas,cx,cy): self.canvas = canvas self.cx = cx self.cy = cy self.update() self.orient = 0 self.width = 2 def update(self): # drawing coordinates cx = self.cx cy = self.cy self.left = self.leftEr = cx-25 self.right = self.rightEr = cx+25 self.top = self.topEr = cy-25 self.bottom = self.bottomEr = cy+25 # circuit coordinates canvas = self.canvas circuit = canvas.circuit (left,top) = (circuit.left,circuit.top) margin = circuit.margin cellSize = circuit.cellSize self.col = (cx-(left + margin)) / cellSize self.row = (cy-(top + margin)) / cellSize self.cols = [self.col-1,self.col,self.col+1] self.rows = [self.row-1,self.row,self.row+1] def drawTemp(self): canvas = self.canvas (holdX,holdY) = closestPoint(canvas.data.holdX,canvas.data.holdY) (self.cx,self.cy) = (holdX,holdY) self.draw() def draw(self): canvas = self.canvas self.update() if (self.orient == 0): self.orient0() elif(self.orient == 1): self.orient1() elif (self.orient == 2): self.orient2() else: self.orient3() def rotate(self): self.orient += 1 if (self.orient == 4): self.orient = 0 def delete(self): canvas = self.canvas canvas.data.components[self.kind()].remove(self) def solve(self): # set positive/negative if (self.orient == 0): self.pos = [0,0,self.col-1] self.neg = [0,0,self.col+1] elif (self.orient == 1): self.pos = [0,0,self.row-1] self.neg = [0,0,self.row+1] elif (self.orient == 2): self.pos = [0,0,self.col+1] self.neg = [0,0,self.col-1] elif (self.orient == 3): self.pos = [0,0,self.row+1] self.neg = [0,0,self.row-1] class Source(Component): def __init__(self,canvas,cx,cy): self.canvas = canvas self.cx = cx self.cy = cy self.voltage = 0 self.update() self.orient = 0 self.width = 2 def kind(self): return "source" def __str__(self): return "%sV source" % self.voltage @classmethod def create(cls,canvas): (relX,relY) = closestPoint(canvas.data.releaseX,canvas.data.releaseY) newSource = Source(canvas,relX,relY) canvas.data.components["source"] = [newSource] # add component value try: canvas.root.update() entry = solver.Dialog(canvas.root,"enter integer voltage") canvas.root.wait_window(entry.top) newSource.voltage = float(entry.result) except: newSource.voltage = 0 # reset draw commands canvas.data.relX = canvas.data.relY = None canvas.data.drawSource = False def update(self): super(Source,self).update() # set positive/negative self.pos = [self.voltage,0,self.row-1] self.neg = [0,0,self.row+1] def draw(self): canvas = self.canvas (cx,cy) = (self.cx,self.cy) width = self.width r = 15 canvas.create_oval(cx-r,cy-r,cx+r,cy+r,width=width) # + canvas.create_line(cx-r*(1.0/3),cy-r*(1.0/6), cx+r*(1.0/3),cy-r*(1.0/6), width=width) canvas.create_line(cx,cy-r*(.5), cx,cy+r*(1.0/6), width=width) # - canvas.create_line(cx-r*(1.0/3),cy+r*(1.0/3), cx+r*(1.0/3),cy+r*(1.0/3), width=width) # don't draw lead wires on SOURCE button if (self != canvas.data.buttSource): canvas.create_line(cx,cy-25,cx,cy-r,width=width) canvas.create_line(cx,cy+r,cx,cy+25,width=width) if (self != canvas.data.tempSource): canvas.create_text(self.right-5,self.top+7, text="%s V" % int(self.voltage), font="Arial 11") def rotate(self): pass def solve(self): self.drop = self.voltage * -1 class Ground(Component): def kind(self): return "ground" def __init__(self,canvas,cx,cy): super(Ground,self).__init__(canvas,cx,cy) self.voltage = 0.0 def __str__(self): return "ground (0.0V)" @classmethod def create(cls,canvas): (relX,relY) = closestPoint(canvas.data.releaseX,canvas.data.releaseY) canvas.data.components["ground"] = [Ground(canvas,relX,relY)] canvas.data.relX = canvas.data.relY = None canvas.data.drawGround = False def draw(self): canvas = self.canvas (cx,cy) = (self.cx,self.cy) (left1,right1) = (cx-20,cx+20) (left2,right2) = (cx-13,cx+13) (left3,right3) = (cx-6,cx+6) (top,mid,bottom) = (cy-7,cy,cy+7) width = self.width canvas.create_line(cx,cy-25,cx,top,width=width) # lead wire canvas.create_line(left1,top,right1,top,width=width) # top canvas.create_line(left2,mid,right2,mid,width=width) # middle canvas.create_line(left3,bottom,right3,bottom,width=width) # bottom def rotate(self): pass def solve(self): self.drop = 0 class Wire(object): def kind(self): return "wires" def __init__(self,canvas,left,top,right,bottom): self.canvas = canvas (self.left,self.right) = (left,right) (self.top,self.bottom) = (top,bottom) self.update() self.width = 2 def update(self): canvas = self.canvas circuit = canvas.circuit margin = circuit.margin cellSize = circuit.cellSize if (self.left == self.right): # drawing coordinates (self.leftEr,self.rightEr) = (self.left-10,self.right+10) (self.topEr,self.bottomEr) = (self.top,self.bottom) # circuit coordinates top = (self.top-(circuit.top + margin)) / cellSize bottom = (self.bottom-(circuit.top + margin)) / cellSize self.row = xrange(top,bottom+1) # inclusive self.col = [(self.left-(circuit.left + margin)) / cellSize] elif (self.top == self.bottom): # drawing coordinates (self.leftEr,self.rightEr) = (self.left,self.right) (self.topEr,self.bottomEr) = (self.top-10,self.bottom+10) # circuit coordinates self.row = [(self.top-(circuit.top + margin)) / cellSize] left = (self.left-(circuit.left + margin)) / cellSize right = (self.right-(circuit.left + margin)) / cellSize self.col = xrange(left,right+1) # inclusive def __str__(self): return "wire" @classmethod def drawTemp(cls,canvas): (clickX,clickY) = closestPoint(canvas.data.clickX,canvas.data.clickY) (holdX,holdY) = closestPoint(canvas.data.holdX,canvas.data.holdY) (x1,y1,x2,y2) = removeDiagonal(clickX,clickY,holdX,holdY) canvas.create_line(x1,y1,x2,y2,width=2) @classmethod def create(cls,canvas): (clickX,clickY) = closestPoint(canvas.data.clickX,canvas.data.clickY) (relX,relY) = closestPoint(canvas.data.releaseX,canvas.data.releaseY) (x1,y1,x2,y2) = removeDiagonal(clickX,clickY,relX,relY) if (x1 != x2) or (y1 != y2): # check for point (x1,x2) = (min(x1,x2),max(x1,x2)) (y1,y2) = (min(y1,y2),max(y1,y2)) canvas.data.components["wires"].append(Wire(canvas,x1,y1,x2,y2)) canvas.data.relX = canvas.data.rel = None def draw(self): canvas = self.canvas self.update() (left,top,right,bottom) = (self.left,self.top,self.right,self.bottom) width = self.width canvas.create_line(left,top,right,bottom,width=width) def rotate(self): pass def delete(self): canvas = self.canvas canvas.data.components["wires".__str__()].remove(self) def solve(self): self.drop = 0 class Resistor(Component): def kind(self): return "resistors" def __type__(self): return "resistors" def __str__(self): return "%sΩ resistor" % self.resistance @classmethod def create(cls,canvas): (relX,relY) = closestPoint(canvas.data.releaseX,canvas.data.releaseY) newResistor = Resistor(canvas,relX,relY) canvas.data.components["resistors"].append(newResistor) # add component value try: canvas.root.update() entry = solver.Dialog(canvas.root,"enter integer resistance") canvas.root.wait_window(entry.top) newResistor.resistance = entry.result except: newResistor.resistance = 0 # reset draw commands canvas.data.relX = canvas.data.relY = None canvas.data.drawResistor = False def orient0(self): # left-pos / right-neg canvas = self.canvas (cx,cy) = (self.cx,self.cy) width = self.width canvas.create_line(cx-25,cy,cx-15,cy,width=width) canvas.create_line(cx-15,cy,cx-10,cy-10,width=width) canvas.create_line(cx-10,cy-10,cx-5,cy+10,width=width) canvas.create_line(cx-5,cy+10,cx,cy-10,width=width) canvas.create_line(cx,cy-10,cx+5,cy+10,width=width) canvas.create_line(cx+5,cy+10,cx+10,cy-10,width=width) canvas.create_line(cx+10,cy-10,cx+15,cy,width=width) canvas.create_line(cx+15,cy,cx+25,cy,width=width) # +/- signs (don't draw on button) if (self != canvas.data.buttResistor): canvas.create_text(self.left+10,self.top+7, text="+",font="Arial 11") canvas.create_text(self.right-10,self.top+7, text="-",font="Arial 13") # reistance value if (self != canvas.data.tempResistor): canvas.create_text(self.cx,self.bottom-7, text="%s Ω" % str(self.resistance), font="Arial 11") def orient1(self): # top-pos / bottom-neg canvas = self.canvas (cx,cy) = (self.cx,self.cy) width = self.width canvas.create_line(cx,cy-25,cx,cy-15,width=width) canvas.create_line(cx,cy-15,cx+10,cy-10,width=width) canvas.create_line(cx+10,cy-10,cx-10,cy-5,width=width) canvas.create_line(cx-10,cy-5,cx+10,cy,width=width) canvas.create_line(cx+10,cy,cx-10,cy+5,width=width) canvas.create_line(cx-10,cy+5,cx+10,cy+10,width=width) canvas.create_line(cx+10,cy+10,cx,cy+15,width=width) canvas.create_line(cx,cy+15,cx,cy+25,width=width) # +/- signs canvas.create_text(self.right-10,self.top+10, text="+",font="Arial 11") canvas.create_text(self.right-10,self.bottom-10, text="-",font="Arial 11") # resistance value canvas.create_text(self.right-10,self.cy,anchor=W, text="%s Ω" % str(self.resistance), font="Arial 11") def orient2(self): # left-neg / right-pos canvas = self.canvas (cx,cy) = (self.cx,self.cy) width = self.width canvas.create_line(cx-25,cy,cx-15,cy,width=width) canvas.create_line(cx-15,cy,cx-10,cy+10,width=width) canvas.create_line(cx-10,cy+10,cx-5,cy-10,width=width) canvas.create_line(cx-5,cy-10,cx,cy+10,width=width) canvas.create_line(cx,cy+10,cx+5,cy-10,width=width) canvas.create_line(cx+5,cy-10,cx+10,cy+10,width=width) canvas.create_line(cx+10,cy+10,cx+15,cy,width=width) canvas.create_line(cx+15,cy,cx+25,cy,width=width) # +/- signs canvas.create_text(self.right-10,self.top+7, text="+",font="Arial 11") canvas.create_text(self.left+10,self.top+7, text="-",font="Arial 11") # resistance value canvas.create_text(self.cx,self.bottom-7, text="%s Ω" % str(self.resistance), font="Arial 11") def orient3(self): # top-neg / bottom-pos canvas = self.canvas (cx,cy) = (self.cx,self.cy) width = self.width canvas.create_line(cx,cy-25,cx,cy-15,width=width) canvas.create_line(cx,cy-15,cx-10,cy-10,width=width) canvas.create_line(cx-10,cy-10,cx+10,cy-5,width=width) canvas.create_line(cx+10,cy-5,cx-10,cy,width=width) canvas.create_line(cx-10,cy,cx+10,cy+5,width=width) canvas.create_line(cx+10,cy+5,cx-10,cy+10,width=width) canvas.create_line(cx-10,cy+10,cx,cy+15,width=width) canvas.create_line(cx,cy+15,cx,cy+25,width=width) # +/- signs canvas.create_text(self.right-10,self.bottom-10, text="+",font="Arial 11") canvas.create_text(self.right-10,self.top+10, text="-",font="Arial 11") # resistance value canvas.create_text(self.right-10,self.cy,anchor=W, text="%s Ω" % str(self.resistance), font="Arial 11") def solve(self): super(Resistor,self).solve() self.drop = self.current * self.resistance class Diode(Component): def kind(self): return "diodes" def __init__(self,canvas,cx,cy): super(Diode,self).__init__(canvas,cx,cy) self.voltage = 0.6 self.drop = self.voltage @classmethod def create(cls,canvas): (relX,relY) = closestPoint(canvas.data.releaseX,canvas.data.releaseY) canvas.data.components["diodes"].append(Diode(canvas,relX,relY)) canvas.data.relX = canvas.data.relY = None canvas.data.drawDiode = False def __str__(self): return "%sV diode" % self.voltage def orient0(self): # left-pos / right-neg canvas = self.canvas (cx,cy) = (self.cx,self.cy) (left,right) = (cy+15,cy-15) (top,bottom) = (cx-13,cx+13) width = self.width canvas.create_polygon(top,left,top,right,bottom,cy,width=width) canvas.create_line(bottom,left,bottom,right,width=width) # lead wires canvas.create_line(cx-25,cy,top,cy,width=width) canvas.create_line(bottom,cy,cx+25,cy,width=width) def orient1(self): # top-pos / bottom-neg canvas = self.canvas (cx,cy) = (self.cx,self.cy) (left,right) = (cx-15,cx+15) (top,bottom) = (cy-13,cy+13) width = self.width canvas.create_polygon(left,top,right,top,cx,bottom,width=width) canvas.create_line(left,bottom,right,bottom,width=width) # lead wires canvas.create_line(cx,cy-25,cx,top,width=width) canvas.create_line(cx,bottom,cx,cy+25,width=width) def orient2(self): # left-neg / right-pos canvas = self.canvas (cx,cy) = (self.cx,self.cy) (left,right) = (cy-15,cy+15) (top,bottom) = (cx+13,cx-13) width = self.width canvas.create_polygon(top,left,top,right,bottom,cy,width=width) canvas.create_line(bottom,left,bottom,right,width=width) # lead wires canvas.create_line(cx-25,cy,bottom,cy,width=width) canvas.create_line(top,cy,cx+25,cy,width=width) def orient3(self): # top-neg / bottom-pos canvas = self.canvas (cx,cy) = (self.cx,self.cy) (left,right) = (cx+15,cx-15) (top,bottom) = (cy+13,cy-13) width = self.width canvas.create_polygon(left,top,right,top,cx,bottom,width=width) canvas.create_line(left,bottom,right,bottom,width=width) # lead wires canvas.create_line(cx,cy-25,cx,top,width=width) canvas.create_line(cx,bottom,cx,cy+25,width=width) ################################################################## # GRID DRAWING METHODS ################################################################## def closestPoint(x,y): # check that the coordinate is on the grid if (x < 255): x = 255 elif (x > 880): x = 880 if (y < 20): y = 20 elif (y > 520): y = 520 # move to closest grid point left = 255 x = x-left col = round(x/25.0) newX = int(left + col*25) row = round((y-20)/25.0) newY = int(20 + row*25) return (newX,newY) def removeDiagonal(x1,y1,x2,y2): # if x distance is closer than y distance, use x for both # else use y for both if (abs(x2 - x1) <= abs(y2 - y1)): newX1 = newX2 = x1 (newY1,newY2) = (y1,y2) else: (newX1,newX2) = (x1,x2) newY1 = newY2 = y1 return (newX1,newY1,newX2,newY2) ################################################################## # INITIALIZERS ################################################################## def initTempComponents(canvas): canvas.data.tempSource = Source(canvas,132,588) canvas.data.tempGround = Ground(canvas,0,588) canvas.data.tempResistor = Resistor(canvas,42,588) canvas.data.tempDiode = Diode(canvas,0,588) def initComponents(canvas): canvas.data.components = {"source":[], "wires":[], "ground":[], "resistors":[], "diodes":[]} def initDrawCommands(canvas): canvas.data.editCircuit = True canvas.data.drawSource = False canvas.data.drawWire = False canvas.data.drawGround = False canvas.data.drawResistor = False canvas.data.drawDiode = False canvas.data.selectedComp = None canvas.data.moveComp = False canvas.data.sourceError = False canvas.data.resistorError = False <file_sep>/source/solver.py from Tkinter import * import components import copy class Sidebar: def __init__(self,canvas,left,top,right,bottom): self.canvas = canvas (self.left, self.right) = (left, right) (self.top, self.bottom) = (top, bottom) self.color = "gainsboro" self.font1 = "Arial 20 bold" self.font2 = "Arial 18" def drawSidebar(self): canvas = self.canvas (left, right) = (self.left, self.right) (top, bottom) = (self.top, self.bottom) fill = self.color canvas.create_rectangle(left,top,right,bottom, fill=fill,width=0) self.drawText() def drawText(self): margin = 15 line = 20 newLine = self.newLine = 25 pad = 15 top = line + newLine + pad self.component(margin,margin) self.voltage(margin,margin+(top)*1) self.current(margin,margin+(top)*2) self.resistance(margin,margin+(top)*3) def component(self,left,top1): canvas = self.canvas top2 = top1 + self.newLine font1 = self.font1 font2 = self.font2 text1 = "selected:" if (canvas.data.selectedComp != None): component = canvas.data.selectedComp text2 = "%s at (%s,%s)" % (str(component),component.col,component.row) else: text2 = "" canvas.create_text(left,top1,anchor=NW,text=text1,font=font1) canvas.create_text(left,top2,anchor=NW,text=text2,font=font2) def voltage(self,left,top1): canvas = self.canvas top2 = top1 + self.newLine font1 = self.font1 font2 = self.font2 text1 = "voltage drop:" if ((canvas.data.selectedComp != None) and (canvas.data.editCircuit == False)): component = canvas.data.selectedComp text2 = "%sV" % component.drop else: text2 = "" canvas.create_text(left,top1,anchor=NW,text=text1,font=font1) canvas.create_text(left,top2,anchor=NW,text=text2,font=font2) def current(self,left,top1): canvas = self.canvas top2 = top1 + self.newLine font1 = self.font1 font2 = self.font2 text1 = "current:" if ((canvas.data.selectedComp != None) and (canvas.data.editCircuit == False)): component = canvas.data.selectedComp text2 = "%sA" % component.current else: text2 = "" canvas.create_text(left,top1,anchor=NW,text=text1,font=font1) canvas.create_text(left,top2,anchor=NW,text=text2,font=font2) def resistance(self,left,top1): canvas = self.canvas top2 = top1 + self.newLine font1 = self.font1 font2 = self.font2 text1 = "circuit resistance:" if ((canvas.data.selectedComp != None) and (canvas.data.editCircuit == False)): component = canvas.data.selectedComp text2 = "%s Ω" % canvas.data.circuitResistance else: text2 = "" canvas.create_text(left,top1,anchor=NW,text=text1,font=font1) canvas.create_text(left,top2,anchor=NW,text=text2,font=font2) # Dialog class adapted from http://effbot.org/tkinterbook/ # tkinter-dialog-windows.htm class Dialog: def __init__(self, parent, function): top = self.top = Toplevel(parent) Label(top, text="%s:" % function).pack() self.e = Entry(top) self.e.pack(padx=5) self.e.focus() self.e.bind("<Return>", lambda event: self.enter(event)) b = Button(top, text="enter", command=self.enter) b.pack(pady=5) def enter(self,event=None): self.result = int(self.e.get()) self.top.destroy() class Node: def __init__(self,canvas): self.canvas = canvas self.wires = [] def __str__(self): wires = [] for wire in self.wires: wires.append(str(wire)) return str(wires) def add(self,wire): self.wires.append(wire) def updateWires(self): canvas = self.canvas for wire in self.wires: wire.node = canvas.data.nodes.index(self) def findComponents(self): canvas = self.canvas components = canvas.data.components wires = self.wires self.components = [] for wire in wires: (row,col) = (wire.row,wire.col) for wireEnd in [(min(row),min(col)),(max(row),max(col))]: for key in components: if (key != "wires" and key != "ground"): for comp in components[key]: if (wireEnd[0] in comp.rows and wireEnd[1] in comp.cols): self.components.append(comp) def updateCompNodes(self): for comp in self.components: for wire in self.wires: (row,col) = (wire.row,wire.col) for end in [(min(row),min(col)),(max(row),max(col))]: if (end[0] == comp.pos[2] or end[1] == comp.pos[2]): comp.pos[1] = self elif (end[0] == comp.neg[2] or end[1] == comp.neg[2]): comp.neg[1] = self def solve(canvas): if (errorCheck(canvas) == True): return loadList(canvas) createNodes(canvas) paraNodes = findParallelNodes(canvas) seriesSolve(canvas) for key in canvas.data.components: for comp in canvas.data.components[key]: comp.solve() for node in canvas.data.nodes: node.findComponents() def errorCheck(canvas): components = canvas.data.components if (len(components["source"]) == 0): canvas.data.sourceError = True return True elif (len(components["resistors"]) == 0): canvas.data.resistorError = True return True return False def sourceError(canvas): cx = (235 + canvas.data.width)/2 cy = (540/2) (left,right) = (cx-150,cx+150) (top,bottom) = (cy-30,cy+30) error = """Please add a source to your circuit. Click EDIT to return to your circuit. """ canvas.create_rectangle(left,top,right,bottom, fill = "gainsboro",width = 0) canvas.create_text(cx,cy+5,width=((right-15)-(left+15)), justify=CENTER,font="Helvetica 12 bold", text=error) def resistorError(canvas): cx = (235 + canvas.data.width)/2 cy = (540/2) (left,right) = (cx-150,cx+150) (top,bottom) = (cy-30,cy+30) error = """Please add at least one resistor to your circuit. Click EDIT to return to your circuit. """ canvas.create_rectangle(left,top,right,bottom, fill = "gainsboro",width = 0) canvas.create_text(cx,cy+5,width=((right-15)-(left+15)), justify=CENTER,font="Helvetica 12 bold", text=error) def loadList(canvas): (rows,cols) = (canvas.circuit.rows+1,canvas.circuit.cols+1) circuitList = [[None] * cols for row in xrange(rows)] components = canvas.data.components for key in components: for comp in components[key]: if (key == "wires"): for row in comp.row: for col in comp.col: circuitList[row][col] = comp else: circuitList[comp.row][comp.col] = comp canvas.data.circuitList = circuitList def sourceWire(canvas): source = canvas.data.components["source"][0] posRow = source.pos[2] col = source.col for wire in canvas.data.components["wires"]: if (posRow in wire.row) and (col in wire.col): canvas.data.sourceWire = wire return [wire,posRow,col] return None def createNodes(canvas): nodeCount = 0 circuitList = canvas.data.circuitList check = sourceWire(canvas) (row,col) = (check[1],check[2]) canvas.data.findNodesCircuit = copy.copy(circuitList) canvas.data.wiresToPlace = set(canvas.data.components["wires"]) canvas.data.nodes = [Node(canvas)] canvas.data.nodes[0].wires.append(check[0]) findNodes(canvas,row,col,check[0]) for node in canvas.data.nodes: node.updateWires() node.findComponents() def findNodes(canvas,row,col,old,nodeCount=0): if ((row < 0) or (row >= canvas.circuit.rows) or (col < 0) or (col >= canvas.circuit.cols)): return new = canvas.data.findNodesCircuit[row][col] canvas.data.findNodesCircuit[row][col] = None if (new == None): return else: if ((isinstance(new, components.Wire) == True) and (new != old) and (new in canvas.data.wiresToPlace)): if (nodeCount == len(canvas.data.nodes)): canvas.data.nodes.append(Node(canvas)) canvas.data.nodes[nodeCount].add(new) canvas.data.wiresToPlace.discard(new) elif (isinstance(new, components.Wire) == False): nodeCount += 1 findNodes(canvas,row-1,col,new,nodeCount) findNodes(canvas,row+1,col,new,nodeCount) findNodes(canvas,row,col-1,new,nodeCount) findNodes(canvas,row,col+1,new,nodeCount) def findParallelNodes(canvas): nodes = canvas.data.nodes paraNodes = [] for node in nodes: if (len(node.components) > 2): paraNodes.append(node) return paraNodes def seriesSolve(canvas): components = canvas.data.components resistance = 0 for resistor in components["resistors"]: resistance += resistor.resistance canvas.data.circuitResistance = resistance diodeVolts = 0 for diode in components["diodes"]: diodeVolts += diode.voltage remainingVolts = components["source"][0].voltage - diodeVolts current = remainingVolts / resistance for key in components: for comp in components[key]: comp.current = current <file_sep>/source/run.py from Tkinter import * import circuit import components import controls import demoCircuit import simpleCircuit import solver def values(canvas,event): for key in canvas.data.components: print key for comp in canvas.data.components[key]: print "#", canvas.data.components[key].index(comp) print " left: %d, right: %d" % (comp.left,comp.right) print " top: %d, bottom: %d" % (comp.top,comp.bottom) if key == "sources": print " %d V" % comp.voltage elif key == "resistors": print " %d Ω" % comp.resistance print print print def demo(canvas,event): init(canvas) demoCircuit.demo(canvas) redrawAll(canvas) def simple(canvas,event): init(canvas) simpleCircuit.demo(canvas) redrawAll(canvas) ################################################################## # MOUSE/KEY CONTROLS ################################################################## def leftClick(canvas,event): x = canvas.data.clickX = event.x y = canvas.data.clickY = event.y if (inMenu(canvas,y) == True): findButton(canvas,x) elif ((inGrid(canvas,x,y) == True) and (canvas.data.helpScreen == False)): findComponent(canvas,x,y) redrawAll(canvas) def leftClickHeld(canvas,event): x = canvas.data.holdX = event.x y = canvas.data.holdY = event.y redrawAll(canvas) print (x,y) if (canvas.data.drawWire == True) and (inGrid(canvas,x,y) == True): components.Wire.drawTemp(canvas) elif (canvas.data.drawSource == True): canvas.data.tempSource.drawTemp() elif (canvas.data.drawGround == True): canvas.data.tempGround.drawTemp() elif (canvas.data.drawResistor == True): canvas.data.tempResistor.drawTemp() elif (canvas.data.drawDiode == True): canvas.data.tempDiode.drawTemp() elif (canvas.data.editCircuit == True and canvas.data.selectedComp != None and inGrid(canvas,x,y) == True and canvas.data.moveComp == True): comp = canvas.data.selectedComp (comp.cx,comp.cy) = components.closestPoint(x,y) comp.update() def leftClickRelease(canvas,event): x = canvas.data.releaseX = event.x y = canvas.data.releaseY = event.y if (canvas.data.drawWire == True) and (inGrid(canvas,x,y) == True): components.Wire.create(canvas) elif (canvas.data.drawSource == True): components.Source.create(canvas) elif (canvas.data.drawGround == True): components.Ground.create(canvas) elif (canvas.data.drawResistor == True): components.Resistor.create(canvas) elif (canvas.data.drawDiode == True): components.Diode.create(canvas) ''' elif (canvas.data.selectedComp != None and canvas.data.moveComp == True): canvas.data.selectedComp.width = 2 canvas.data.selectedComp = None canvas.data.holdX = canvas.data.holdY = None ''' redrawAll(canvas) def rPressed(canvas,event): if ((canvas.data.selectedComp != None) and (canvas.data.editCircuit == True)): canvas.data.selectedComp.rotate() redrawAll(canvas) def ePressed(canvas,event): component = canvas.data.selectedComp if ((component != None) and (canvas.data.editCircuit == True)): canvas.root.update() if (type(component) == components.Source): entry = solver.Dialog(canvas.root,"voltage") canvas.root.wait_window(entry.top) component.voltage = entry.result elif (type(component) == components.Resistor): entry = solver.Dialog(canvas.root,"resistance") canvas.root.wait_window(entry.top) component.resistance = entry.result redrawAll(canvas) def bsPressed(canvas,event): if ((canvas.data.selectedComp != None) and (canvas.data.editCircuit == True)): canvas.data.selectedComp.delete() redrawAll(canvas) canvas.data.selectedComp = None ################################################################## # MOUSE PLACEMENT ################################################################## def inMenu(canvas,y): (top,bottom) = (canvas.data.buttonTop,canvas.data.buttonBottom) if (top < y < bottom): return True return False def findButton(canvas,x): for button in canvas.data.mButts: if (button.left <= x <= button.right): button.buttonFunction() if (button.function != "wire"): canvas.data.drawWire = False if (button.function != "quit"): redrawAll(canvas) def inGrid(canvas,x,y): (left,right) = (canvas.circuit.left,canvas.circuit.right) (top,bottom) = (canvas.circuit.top,canvas.circuit.bottom) if (left < x < right) and (top < y < bottom): return True return False def findComponent(canvas,x,y): for key in canvas.data.components: for component in canvas.data.components[key]: if ((component.leftEr < x < component.rightEr) and (component.topEr < y < component.bottomEr)): if (canvas.data.selectedComp == None): canvas.data.selectedComp = component canvas.data.selectedComp.width = 3 canvas.data.moveComp = True elif (canvas.data.selectedComp == component): canvas.data.selectedComp.width = 2 canvas.data.selectedComp = None canvas.data.moveComp = False else: # if another component is already selected canvas.data.selectedComp.width = 2 canvas.data.selectedComp = component canvas.data.selectedComp.width = 3 return if (canvas.data.selectedComp != None): # if click outside canvas.data.selectedComp.width = 2 canvas.data.selectedComp = None ################################################################## # SOLVER ################################################################## def redrawAll(canvas): canvas.delete(ALL) canvas.sidebar.drawSidebar() canvas.circuit.drawGrid() circuit.drawCircuit(canvas) canvas.menu.drawMenu() if (canvas.data.drawWire == True): canvas.create_rectangle(180,550,180+75,550+75,width=5,fill=None) elif (canvas.data.helpScreen == True): controls.helpScreen(canvas) elif (canvas.data.sourceError == True): solver.sourceError(canvas) elif (canvas.data.resistorError == True): solver.resistorError(canvas) def init(canvas): # widget coordinates canvas.sidebar = solver.Sidebar(canvas,0,0,235,535) canvas.circuit = circuit.Circuit(canvas,235,0,canvas.data.width,540) canvas.data.buttonTop = 550 canvas.data.buttonBottom = canvas.data.buttonTop + 75 canvas.menu = controls.Menu(canvas,0,540,canvas.data.width,canvas.data.height) canvas.data.compMenu = False # init main menu canvas.data.helpScreen = False # circuit drawing components.initDrawCommands(canvas) components.initTempComponents(canvas) components.initComponents(canvas) # click data canvas.data.clickX = None canvas.data.holdX = None canvas.data.releaseX = None redrawAll(canvas) def run(): root = Tk() root.resizable(width=FALSE, height=FALSE) (width,height) = (900,635) canvas = Canvas(root, width=width, height=height) canvas.pack(fill=BOTH, expand=YES) root.canvas = canvas.canvas = canvas root.title("Circuit Solver") class Struct: pass canvas.data = Struct() canvas.root = root canvas.data.width = width canvas.data.height = height init(canvas) root.bind("<Button-1>", lambda event: leftClick(canvas,event)) root.bind("<B1-Motion>", lambda event: leftClickHeld(canvas,event)) root.bind("<ButtonRelease-1>", lambda event: leftClickRelease(canvas,event)) root.bind("<r>", lambda event: rPressed(canvas,event)) root.bind("<e>", lambda event: ePressed(canvas,event)) root.bind("<v>", lambda event: values(canvas,event)) root.bind("<d>", lambda event: demo(canvas,event)) root.bind("<s>", lambda event: simple(canvas,event)) root.bind("<BackSpace>", lambda event: bsPressed(canvas,event)) root.mainloop() run() <file_sep>/source/demoCircuit.py import components def demo(canvas): canvas.data.components["source"] = [components.Source(canvas,355,270)] canvas.data.components["source"][0].voltage = 5.0 canvas.data.components["wires"] = [components.Wire(canvas,355,195,355,245), components.Wire(canvas,355,195,405,195), components.Wire(canvas,455,195,480,195), components.Wire(canvas,530,195,605,195), components.Wire(canvas,655,195,730,195), components.Wire(canvas,730,245,730,270), components.Wire(canvas,730,320,730,345), components.Wire(canvas,355,345,730,345), components.Wire(canvas,355,295,355,345), components.Wire(canvas,555,195,555,245), components.Wire(canvas,555,295,555,345)] canvas.data.components["resistors"] = [components.Resistor(canvas,430,195), components.Resistor(canvas,505,195), components.Resistor(canvas,630,195), components.Resistor(canvas,730,220)] for i in xrange(len(canvas.data.components["resistors"])): res = canvas.data.components["resistors"][i] if (i % 2 == 0): res.resistance = 1000 else: res.resistance = 500 canvas.data.components["resistors"][3].orient = 1 canvas.data.components["diodes"] = [components.Diode(canvas,555,270), components.Diode(canvas,730,295)] canvas.data.components["diodes"][0].orient = 1 canvas.data.components["diodes"][1].orient = 1 canvas.data.components["ground"] = [components.Ground(canvas,480,370)]
f38c41009c9bd3585f71ecf0702604355a0b8c1e
[ "Markdown", "Python" ]
8
Python
madisonscott/15-112
57f5dad78713aa6388eeecd868b2846f548572cd
438d4ab55a194cc9c372093228fe1c79025cbffc
refs/heads/main
<repo_name>ArzateCompany/avocadoStore<file_sep>/src/index.js import "./style/style.css"; console.log('test') const app = document.querySelector("#app"); const formatPrice = (price) => { const newPrice = window.Intl.NumberFormat("en-EN", { style: "currency", currency: "USD", }).format(price); return newPrice; }; const createCardAvocado = (data) => { const cards = []; console.log(data.data); data.data.forEach((avocado) => { const container = document.createElement("div"); container.className = "m-3 pb-3 text-center max-w-1/4 inline-block bg-gray-200 rounded-xl"; const img = document.createElement("img"); img.src = `https://platzi-avo.vercel.app${avocado.image}`; img.className = "m-auto pb-3"; const title = document.createElement("h2"); title.textContent = avocado.name; const price = document.createElement("p"); price.textContent = formatPrice(avocado.price); container.append(img, title, price); cards.push(container); }); app.append(...cards); }; const getData = async (URL) => { try { const response = await fetch(URL); const data = await response.json(); createCardAvocado(data); } catch (err) { console.error(err.message); } }; getData("https://platzi-avo.vercel.app/api/avo"); <file_sep>/README.md # avocadoStore Project created for the practice of the platzi DOM manipulation course.
dfeb9dd7fe4d966c4efeafef06fe1f2514613ca7
[ "JavaScript", "Markdown" ]
2
JavaScript
ArzateCompany/avocadoStore
3a16862117e80a0041f6b6ecc163e381c0a75de3
fe86623b63dbc92fc3a508b72203fe131e395acd
refs/heads/master
<file_sep>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; // components import { AddTodo } from './app/components/add-todo'; import { AppFooter } from './app/components/app-footer'; import { AppHeader } from './app/components/app-header'; import { AppMain } from './app/components/app-main'; import { Link } from './app/components/link'; import { Todo } from './app/components/todo'; import { TodoList } from './app/components/todo-list'; import { TodosFilters } from './app/components/todos-filters'; // containers import { AddTodoContainer } from './app/containers/add-todo'; import { ClearCompletedContainer } from './app/containers/clear-completed'; import { FilterLink } from './app/containers/filter-link'; import { TodoContainer } from './app/containers/todo'; import { TodoApp } from './app/containers/todo-app'; import { TodoListContainer } from './app/containers/todo-list'; import { TodosCounterContainer } from './app/containers/todos-counter'; import { ToggleAllContainer } from './app/containers/toggle-all'; import { Focus } from './app/directives/focus'; @NgModule({ declarations: [ AddTodo, AppFooter, AppHeader, AppMain, Link, Todo, TodoList, TodosFilters, AddTodoContainer, ClearCompletedContainer, FilterLink, TodoContainer, TodoApp, TodoListContainer, TodosCounterContainer, ToggleAllContainer, Focus ], imports: [BrowserModule], bootstrap: [TodoApp] }) export class AppModule {}; <file_sep>import { Component } from '@angular/core'; import { connect } from '../lib'; const mapStateToProps = (state) => { return { hasTodos: state.todos.length > 0 }; }; @Component({ selector: 'todo-app', template: ` <section id="todoapp"> <app-header></app-header> <app-main *ngIf="hasTodos"></app-main> <app-footer *ngIf="hasTodos"></app-footer> </section> ` }) export class TodoApp { ngOnInit() { connect(mapStateToProps)(this); } } <file_sep>const gulp = require('gulp'); const concat = require('gulp-concat'); const preprocess = require('gulp-preprocess'); require('./tasks/webpack'); const DESTINATION_FOLDER = 'dist/'; gulp.task('html', () => { gulp.src('src/index.html') .pipe(preprocess()) .pipe(gulp.dest(DESTINATION_FOLDER)); }); gulp.task('favicon', () => { gulp.src('src/favicon.ico') .pipe(gulp.dest(DESTINATION_FOLDER)); }); gulp.task('css', () => { gulp.src('src/css/*.css') .pipe(concat('app.css')) .pipe(gulp.dest(DESTINATION_FOLDER)); }); gulp.task('build', ['html', 'favicon', 'css', 'webpack:build']); gulp.task('build:dev', ['html', 'favicon', 'css', 'webpack:build:dev']); <file_sep>export const getRemainingTodosCount = (todos) => { return todos.filter(todo => !todo.isDone).length; }; const updateTodo = (todos, id, changes) => { return todos.map((todo) => { if (todo.id !== id) { return todo; } if (typeof changes === 'function') { return Object.assign({}, todo, changes(todo)); } return Object.assign({}, todo, changes); }); }; export const todos = (state = [], action) => { if (action.type === 'CREATE_TODO') { return [...state, { text: action.value, id: Date.now(), isDone: false }]; } if (action.type === 'TOGGLE_TODO') { return updateTodo(state, action.id, (todo) => ({ isDone: !todo.isDone })); } if (action.type === 'CLEAR_COMPLETED_TODOS') { return state.filter((todo) => !todo.isDone); } if (action.type === 'DESTROY_TODO') { return state.filter((todo) => todo.id !== action.id); } if (action.type === 'TOGGLE_ALL_TODOS') { const isDone = getRemainingTodosCount(state) !== 0; return state.map(todo => Object.assign({}, todo, { isDone })); } if (action.type === 'SAVE_TODO') { return updateTodo(state, action.id, { text: action.value }); } return state; }; <file_sep>const uiInitialState = { editingTodoId: null }; export const ui = (uiState = uiInitialState, action) => { if (action.type === 'EDIT_TODO') { return Object.assign(uiState, { editingTodoId: action.id }); } if (action.type === 'SAVE_TODO') { return Object.assign(uiState, { editingTodoId: null }); } if (action.type === 'CANCEL_EDIT_TODO') { return Object.assign(uiState, { editingTodoId: null }); } return uiState; }; <file_sep>// TODO: Move to constants export const FILTERS = { ALL: { text: 'All' }, DONE: { text: 'Completed' }, TODO: { text: 'Active' } }; export const visibilityFilter = (filter = FILTERS.ALL, action) => { if (action.type === 'SET_VISIBILITY_FILTER') { return action.filter; } return filter; }; <file_sep>/* eslint-env node */ // Webpack gulp task // // npm install --save-dev webpack gulp-util // // Available tasks: // - webpack:build // - webpack:build:dev // - webpack-dev-server const gulp = require('gulp'); const gutil = require('gulp-util'); const webpack = require('webpack'); const WebpackDevServer = require('webpack-dev-server'); const WEBPACK_CONFIG = require('../webpack.config.js'); // PRODUCTION const webpackBuildProdTask = callback => { // modify some webpack config options const config = Object.assign({}, WEBPACK_CONFIG, { plugins: [ ...WEBPACK_CONFIG.plugins, new webpack.DefinePlugin({ 'process.env': { // This has effect on the react lib size NODE_ENV: JSON.stringify('production'), }, }), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin(), ], }); // run webpack webpack(config, (err, stats) => { if (err) { throw new gutil.PluginError('webpack:build-prod', err); } gutil.log('[webpack:build-prod]', stats.toString({ colors: true, })); callback(); }); }; // DEVELOPMENT const webpackBuildDevTask = (function task() { // modify some webpack config options const devConfig = Object.assign({}, WEBPACK_CONFIG, { devtool: 'sourcemap', debug: true, }); // create a single instance of the compiler to allow caching const devCompiler = webpack(devConfig); return callback => { // run webpack devCompiler.run((err, stats) => { if (err) { throw new gutil.PluginError('webpack:build-dev', err); } gutil.log('[webpack:build-dev]', stats.toString({ colors: true, })); callback(); }); }; }()); const webpackDevServerTask = () => { // modify some webpack config options const config = Object.assign({}, WEBPACK_CONFIG, { devtool: 'eval', debug: false, plugins: [ ...WEBPACK_CONFIG.plugins, new webpack.HotModuleReplacementPlugin(), ], }); // add special hot-reloading entries to all existed entry points config.entry = Object.keys(config.entry).reduce((acc, entry) => { let entries = config.entry[entry]; if (!Array.isArray(entries)) { entries = [entries]; } return Object.assign({}, acc, { [entry]: [ 'webpack-dev-server/client?http://localhost:8080/', 'webpack/hot/dev-server', ...entries, ], }); }, {}); // Start a webpack-dev-server new WebpackDevServer(webpack(config), { contentBase: 'src/', hot: true, stats: { colors: true, }, }).listen(8080, 'localhost', err => { throw new gutil.PluginError('webpack-dev-server', err); }); }; gulp.task('webpack:build', webpackBuildProdTask); gulp.task('webpack:build:dev', webpackBuildDevTask); gulp.task('webpack-dev-server', webpackDevServerTask); <file_sep>import { Component, Input } from '@angular/core'; import { connect } from '../lib'; import { setVisibilityFilter } from '../actions'; const mapDispatchToProps = (dispatch, props) => { return { onLinkClick: () => dispatch(setVisibilityFilter({ filter: props.filter })) }; }; const mapStateToProps = (state, props) => { return { text: props.filter.text, isActive: state.visibilityFilter === props.filter }; }; @Component({ selector: 'filter-link', template: ` <my-link [text]="text" [isActive]="isActive" (click)="onLinkClick()" ></my-link> `, }) export class FilterLink { @Input() filter; ngOnInit() { connect(mapStateToProps, mapDispatchToProps)(this); } } <file_sep>export const createTodo = ({ value }) => ({ type: 'CREATE_TODO', value }); export const clearCompletedTodos = () => ({ type: 'CLEAR_COMPLETED_TODOS' }); export const setVisibilityFilter = ({ filter }) => ({ type: 'SET_VISIBILITY_FILTER', filter }); export const toggleTodo = ({ id }) => ({ type: 'TOGGLE_TODO', id }); export const destroyTodo = ({ id }) => ({ type: 'DESTROY_TODO', id }); export const editTodo = ({ id }) => ({ type: 'EDIT_TODO', id }); export const saveTodo = ({ id, value }) => ({ type: 'SAVE_TODO', id, value }); export const cancelTodoEdit = ({ id }) => ({ type: 'CANCEL_EDIT_TODO' }); export const toggleAllTodos = () => ({ type: 'TOGGLE_ALL_TODOS' }); <file_sep>import { Component } from '@angular/core'; import { FILTERS } from '../reducers/visibilityFilter'; @Component({ selector: 'todos-filters', template: ` <ul id="filters"> <li><filter-link [filter]="FILTERS.ALL"></filter-link></li> <li><filter-link [filter]="FILTERS.TODO"></filter-link></li> <li><filter-link [filter]="FILTERS.DONE"></filter-link></li> </ul> ` }) export class TodosFilters { public FILTERS = FILTERS; }; <file_sep>import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'add-todo', template: ` <input id="new-todo" placeholder="What needs to be done?" value="" (keyup.enter)="onSubmit($event)" /> ` }) export class AddTodo { @Output() add = new EventEmitter(); onSubmit(event) { event.preventDefault(); this.add.emit({ value: event.target.value }); event.target.value = ''; } } <file_sep>import { Component } from '@angular/core'; @Component({ selector: 'app-header', template: ` <header class="header"> <h1>todos</h1> <add-todo-container></add-todo-container> </header> `, }) export class AppHeader { } <file_sep>import { combineReducers } from 'redux'; import { todos } from './todos'; import { visibilityFilter } from './visibilityFilter'; import { ui } from './ui'; export const rootReducer = combineReducers({ todos, visibilityFilter, ui }); <file_sep>import { Component } from '@angular/core'; import { FILTERS } from '../reducers/visibilityFilter'; import { connect } from '../lib'; const visibleTodos = (todos, filter) => { return todos.filter(todo => { if (filter === FILTERS.ALL) { return true; } if (filter === FILTERS.DONE) { return todo.isDone; } if (filter === FILTERS.TODO) { return !todo.isDone; } }); }; const mapStateToProps = (state) => { return { todos: visibleTodos(state.todos, state.visibilityFilter) }; }; @Component({ selector: 'todo-list-container', template: ` <todo-list [todos]="todos"></todo-list> `, }) export class TodoListContainer { ngOnInit() { connect(mapStateToProps)(this); } } <file_sep>import { createStore } from 'redux'; import { rootReducer } from './reducers/root'; const store = window.devToolsExtension ? window.devToolsExtension()(createStore)(rootReducer) : createStore(rootReducer); export const connect = (mapStateToProps = null, mapDispatchToProps = null) => { return component => { if (!component) { throw new Error('`component` property is mandatory.'); } if (!store) { throw new Error('`store` property is mandatory'); } if (mapDispatchToProps) { Object.assign(component, mapDispatchToProps(store.dispatch, component)); } if (mapStateToProps) { Object.assign(component, mapStateToProps(store.getState(), component)); const unsubscribe = store.subscribe(() => { Object.assign(component, mapStateToProps(store.getState(), component)); }); const componentOnDestroy = component.ngOnDestroy; component.ngOnDestroy = function() { unsubscribe(); return componentOnDestroy.apply(component, arguments); }; } }; }; <file_sep>import { Component, Input } from '@angular/core'; import { connect } from '../lib'; import { toggleAllTodos } from '../actions'; const mapStateToProps = (state) => { const isActive = state.todos.filter(todo => !todo.isDone).length === 0; return { isActive }; }; const mapDispatchToProps = (dispatch) => { return { onToggleAll: () => dispatch(toggleAllTodos()) }; }; @Component({ selector: 'toggle-all', template: ` <input id="toggle-all" type="checkbox" [checked]="isActive" (change)="onToggleAll()" /> ` }) export class ToggleAllContainer { @Input() isActive: boolean = false; ngOnInit() { connect(mapStateToProps, mapDispatchToProps)(this); } } <file_sep>import { Component } from '@angular/core'; @Component({ selector: 'app-footer', template: ` <footer id="footer"> <todos-counter-container></todos-counter-container> <todos-filters></todos-filters> <clear-completed></clear-completed> </footer> `, }) export class AppFooter { } <file_sep>import { Component } from '@angular/core'; import { connect } from '../lib'; import { clearCompletedTodos } from '../actions'; const getCompletedTodosCount = (todos) => { return todos.reduce((total, todo) => { return todo.isDone ? total + 1 : total; }, 0); }; const mapDispatchToProps = (dispatch) => { return { onButtonClicked: () => dispatch(clearCompletedTodos()) }; }; const mapStateToProps = (state) => { return { hasCompleted: getCompletedTodosCount(state.todos) !== 0 }; }; @Component({ selector: 'clear-completed', template: ` <button id="clear-completed" *ngIf="hasCompleted" (click)="onButtonClicked()" >Clear completed</button> ` }) export class ClearCompletedContainer { ngOnInit() { connect(mapStateToProps, mapDispatchToProps)(this); } } <file_sep>#!/bin/sh # Read more about releasing to gh-pages using git-subtree: # http://yeoman.io/learning/deployment.html # http://www.damian.oquanta.info/posts/one-line-deployment-of-your-site-to-gh-pages.html TEMP_BRANCH_NAME="gh-pages-release-temp" git checkout -b $TEMP_BRANCH_NAME $(dirname $0)/exclude-dist-from-gitignore npm run build git add -A git commit -m 'Release to github pages.' git branch -D gh-pages git subtree split --prefix dist -b gh-pages git push -f origin gh-pages:gh-pages git checkout master git branch -D gh-pages git branch -D $TEMP_BRANCH_NAME <file_sep>import { Component, Input } from '@angular/core'; @Component({ selector: 'my-link', template: ` <a href="javascript:void(0);" [ngClass]="{ selected: isActive }">{{text}}</a> ` }) export class Link { @Input() text: string; @Input() isActive: boolean; } <file_sep>import { Component, Input } from '@angular/core'; import { connect } from '../lib'; import { toggleTodo, destroyTodo, editTodo, saveTodo, cancelTodoEdit } from '../actions'; const mapStateToProps = (state, props) => { return { text: props.todo.text, isDone: props.todo.isDone, isEditing: state.ui.editingTodoId === props.todo.id }; }; const mapDispatchToProps = (dispatch, props) => { return { onToggle: () => dispatch(toggleTodo({ id: props.todo.id })), onDestroy: () => dispatch(destroyTodo({ id: props.todo.id })), onEdit: () => dispatch(editTodo({ id: props.todo.id })), onSave: ({ value }) => dispatch(saveTodo({ id: props.todo.id, value })), onCancelEdit: () => dispatch(cancelTodoEdit({ id: props.todo.id })) }; }; @Component({ selector: 'todo-item-container', template: ` <todo-item [text]="text" [isDone]="isDone" [isEditing]="isEditing" (toggle)="onToggle()" (destroy)="onDestroy()" (edit)="onEdit()" (cancelEdit)="onCancelEdit()" (save)="onSave($event)" ></todo-item> `, }) export class TodoContainer { @Input() todo; ngOnInit() { connect(mapStateToProps, mapDispatchToProps)(this); } } <file_sep>import { Component } from '@angular/core'; @Component({ selector: 'app-main', template: ` <section id="main"> <toggle-all></toggle-all> <todo-list-container></todo-list-container> </section> ` }) export class AppMain { } <file_sep>import { Component, Input, Output, EventEmitter } from '@angular/core'; import { Focus } from '../directives/focus'; @Component({ selector: 'todo-item', template: ` <li [ngClass]="{ completed: isDone, editing: isEditing }"> <div class="view"> <input class="toggle" type="checkbox" [checked]="isDone" (change)="onToggle()" /> <label (dblclick)="onEdit()">{{text}}</label> <button class="destroy" (click)="onDestroy()"></button> </div> <input #editable class="edit" value="{{text}}" [focus]="isEditing" (keyup.enter)="onKeyboardSave(editable.value)" (keyup.escape)="onCancelEdit(); editable.value = text;" (blur)="onBlurSave(editable.value)" /> </li> `, }) export class Todo { @Input() text: string; @Input() isDone: boolean; @Input() isEditing: boolean; @Output() toggle = new EventEmitter(); @Output() destroy = new EventEmitter(); @Output() save = new EventEmitter(); @Output() edit = new EventEmitter(); @Output() cancelEdit = new EventEmitter(); private _preventSaveOnBlur = false; // TODO: Remove `null` when typescript interface will be fixed onToggle() { this.toggle.emit(null); } onEdit() { this.edit.emit(null); } onKeyboardSave(value) { this.save.emit({ value }); this._preventSaveOnBlur = true; setTimeout(() => this._preventSaveOnBlur = false, 0); } onBlurSave(value) { if (!this._preventSaveOnBlur) { this.save.emit({ value }); } } onDestroy() { this.destroy.emit(null); } onCancelEdit() { this.cancelEdit.emit(null); } } <file_sep>interface Window { devToolsExtension(): any; } <file_sep>import { Component } from '@angular/core'; import { connect } from '../lib'; import { createTodo } from '../actions'; const mapDispatchToProps = (dispatch) => { return { add: ({ value }) => dispatch(createTodo({ value })) }; }; @Component({ selector: 'add-todo-container', template: ` <add-todo (add)="add($event)"></add-todo> ` }) export class AddTodoContainer { ngOnInit() { connect(null, mapDispatchToProps)(this); } } <file_sep>## angular2-redux-todo TodoMVC app using Angular2 and Redux ### Usage - Clone or fork this repository - Make sure you have [node.js](https://nodejs.org/) installed - run `npm install` to install dependencies - run `npm start` to fire up dev server - open browser to `http://localhost:8080` <file_sep>import { Component } from '@angular/core'; import { getRemainingTodosCount } from '../reducers/todos'; import { connect } from '../lib'; const mapStateToProps = (state) => { return { counter: getRemainingTodosCount(state.todos) }; }; @Component({ selector: 'todos-counter-container', template: ` <span id="todo-count"> <strong>{{counter}}</strong> items left </span> `, }) export class TodosCounterContainer { ngOnInit() { connect(mapStateToProps)(this); } } <file_sep>import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'todo-list', template: ` <ul id="todo-list"> <todo-item-container *ngFor="let todo of todos" [todo]="todo"></todo-item-container> </ul> ` }) export class TodoList { @Input() todos: Object[]; @Output() toggleTodo = new EventEmitter(); @Output() destroyTodo = new EventEmitter(); @Output() editTodo = new EventEmitter(); @Output() saveTodo = new EventEmitter(); onToggleTodo({ id }) { this.toggleTodo.emit({ id }); } onDestroyTodo({ id }) { this.destroyTodo.emit({ id }); } onEditTodo({ id }) { this.editTodo.emit({ id }); } onSaveTodo({ value }, todo) { this.saveTodo.emit({ value, id: todo.id }); } }
6d522ecc79be85e01c3d9721f00b91c22681007e
[ "JavaScript", "TypeScript", "Markdown", "Shell" ]
28
TypeScript
ValeriiVasin/angular2-redux-todo
00401a18674951cf9bc80d73b40061aca3b8f955
fcb8b9093cae7087a1c3f01512ab82bbd4a9c561
refs/heads/master
<repo_name>jonathanpperry/ionic-dragdrop<file_sep>/src/app/home/home.page.ts import { AfterViewInit, ChangeDetectorRef, Component, ElementRef, QueryList, ViewChild, ViewChildren, } from "@angular/core"; import { Gesture, GestureController, IonItem } from "@ionic/angular"; @Component({ selector: "app-home", templateUrl: "home.page.html", styleUrls: ["home.page.scss"], }) export class HomePage implements AfterViewInit { teamBlue = []; teamRed = []; myArray = Array.from(Array(30).keys()); contentScrollActive = true; gestureArray: Gesture[] = []; @ViewChild("dropzoneA") dropA: ElementRef; @ViewChild("dropzoneB") dropB: ElementRef; @ViewChildren(IonItem, { read: ElementRef }) items: QueryList<ElementRef>; constructor( private gestureCtrl: GestureController, private changeDetectorRef: ChangeDetectorRef ) {} // View child elements are only available after viewinit ngAfterViewInit() { this.updateGestures(); } // Remove and add gestures based on ViewChildren Querylist updateGestures() { this.gestureArray.map((gesture) => gesture.destroy()); this.gestureArray = []; const arr = this.items.toArray(); for (let i = 0; i < arr.length; i++) { const oneItem = arr[i]; const drag = this.gestureCtrl.create({ el: oneItem.nativeElement, threshold: 1, gestureName: "drag", onStart: (ev) => { oneItem.nativeElement.style.transition = ""; oneItem.nativeElement.style.opacity = "0.8"; oneItem.nativeElement.style.fontWeight = "bold"; // Disable scrolling the list this.contentScrollActive = false; // Updates view if some updates aren't picked up this.changeDetectorRef.detectChanges(); }, onMove: (ev) => { oneItem.nativeElement.style.transform = `translate(${ev.deltaX}px, ${ev.deltaY}px)`; oneItem.nativeElement.style.zIndex = 11; this.checkDropzoneHover(ev.currentX, ev.currentY); }, onEnd: (ev) => { this.contentScrollActive = true; this.handleDrop(oneItem, ev.currentX, ev.currentY, i); }, }); drag.enable(); this.gestureArray.push(drag); } this.items.changes.subscribe((res) => { // console.log("items changed: ", res); if (this.gestureArray.length != this.items.length) { this.updateGestures(); } }); } // Check if we are dragging above a dropzone checkDropzoneHover(x, y) { const dropA = this.dropA.nativeElement.getBoundingClientRect(); const dropB = this.dropB.nativeElement.getBoundingClientRect(); if (this.isInZone(x, y, dropA)) { this.dropA.nativeElement.style.backgroundColor = "blue"; } else { this.dropA.nativeElement.style.backgroundColor = "white"; } if (this.isInZone(x, y, dropB)) { this.dropB.nativeElement.style.backgroundColor = "red"; } else { this.dropB.nativeElement.style.backgroundColor = "white"; } } // Check if coordinates are within a dropzone rect isInZone(x, y, dropzone) { if (x < dropzone.left || x >= dropzone.right) { return false; } if (y < dropzone.top || y >= dropzone.bottom) { return false; } return true; } // Decide what to do with dropped item handleDrop(item, endX, endY, index) { const dropA = this.dropA.nativeElement.getBoundingClientRect(); const dropB = this.dropB.nativeElement.getBoundingClientRect(); if (this.isInZone(endX, endY, dropA)) { // Dropped in Zone A const removedItem = this.myArray.splice(index, 1); this.teamBlue.push(removedItem[0]); item.nativeElement.remove(); // Sort to show the values in increasing order this.teamBlue.sort(function (a, b) { return a - b; }); } else if (this.isInZone(endX, endY, dropB)) { // Dropped in Zone B const removedItem = this.myArray.splice(index, 1); this.teamRed.push(removedItem[0]); item.nativeElement.remove(); // Sort to show the values in increasing order this.teamRed.sort(function (a, b) { return a - b; }); } else { // Don't drop the item into a zone // Simply bring it back to the initial position item.nativeElement.style.transition = ".2s ease-out"; item.nativeElement.style.zIndex = "inherit"; item.nativeElement.style.transform = `translate(0,0)`; item.nativeElement.style.opacity = "1"; item.nativeElement.style.fontWeight = "normal"; } this.dropA.nativeElement.style.backgroundColor = "white"; this.dropB.nativeElement.style.backgroundColor = "white"; this.changeDetectorRef.detectChanges(); } }
f2b258e40a50d995aed90f803fd30a7497422981
[ "TypeScript" ]
1
TypeScript
jonathanpperry/ionic-dragdrop
0182fdf6c6c801f4b8e6f7ae71dec95447abcf5f
d7ffefebaa78f0488914a3eb64c4b4758d1f257e
refs/heads/master
<repo_name>dla0712tmd/python_question<file_sep>/Bronze5/b2475.py a, b, c, d , e = map(int , input("고유번호를 입력해주세요").split()) f = (a ** 2) + (b ** 2) + (c ** 2) + (d ** 2) + (e ** 2) print(f % 10)<file_sep>/Bronze5/b2558.py a = int(input("첫번 째 수를 입력해주세요")) b = int(input("두번 째 수를 입력해주세요")) print(a + b)<file_sep>/Bronze5/b1001.py a, b = map(int , input("뺼 두 수를 입력해주세요: ").split()) print(a - b)<file_sep>/Bronze5/b1000.py #map과 split을 사용하면 자료형을 숫자로 변환한 후 여러 숫자를 한번에 입력할 수 있음 a, b = map(int , input("더할 두 수를 입력해주세요: ").split()) print(a + b) <file_sep>/Bronze5/b2845.py l , p = map(int, input("1m*2당 사람수와 넓이를 입력: ").split()) a, b, c, d, e = map(int, input("다섯개의 신문기사의 넓이를 입력: ").split()) den = l * p print(a - den , b - den, c - den, d - den, e - den) <file_sep>/Bronze5/b1271.py n , m = map(int, input("가진돈과 나눌 사람수 를 입력: ").split()) print(n // m) print(n % m)
990b0ceef20773b42a1571c33da0ae9c80037823
[ "Python" ]
6
Python
dla0712tmd/python_question
749ffbec8f9c9bcf70a563c20fed638f0a6ca5df
0223d54125140ab0b4ddef934b5752ca97877585
refs/heads/master
<repo_name>jeremy-dowdall/DelishView<file_sep>/README.md DelishView ========== An extension of Android's ListView widget offering support for smooth Drag-and-Drop, Sticky Headers, and a unique 'headers' mode that allows Drag-and-Drop reordering of section headers. Status ====== This widget is largely obsolete and will probably not be continued unless it is converted over to the new RecyclerView. In a large part, this was an expirement in the 'headers' mode, that allowed a user to reorder the sections of a long list without leaving the list. It was interesting, but probably not the best. Still, much was learned and it is placed here to remind us of that. <file_sep>/lib/src/main/java/me/licious/view/ParentBlocker.java package me.licious.view; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewParent; import java.lang.reflect.Field; public class ParentBlocker { private final View view; private SwipeRefreshLayout parentSwipe; private boolean parentSwipeEnabled; private DrawerLayout parentDrawer; private int[] parentDrawerLocks; ParentBlocker(View view) { this.view = view; } void start() { ViewParent parent = view.getParent(); while(parent != null) { if(parent instanceof ViewPager) { try { Field mIsUnableToDrag = parent.getClass().getDeclaredField("mIsUnableToDrag"); mIsUnableToDrag.setAccessible(true); mIsUnableToDrag.setBoolean(parent, true); } catch(Exception e) { Log.wtf(getClass().getSimpleName(), "unable to block ViewPager: " + e.getLocalizedMessage()); } } if(parent instanceof SwipeRefreshLayout) { parentSwipe = (SwipeRefreshLayout) parent; parentSwipeEnabled = parentSwipe.isEnabled(); parentSwipe.setEnabled(false); } if(parent instanceof DrawerLayout) { parentDrawer = (DrawerLayout) parent; parentDrawerLocks = new int[] { parentDrawer.getDrawerLockMode(Gravity.LEFT), parentDrawer.getDrawerLockMode(Gravity.RIGHT) }; if(parentDrawer.isDrawerOpen(Gravity.LEFT)) { parentDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN, Gravity.LEFT); } else { parentDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.LEFT); if(parentDrawer.isDrawerVisible(Gravity.LEFT)) parentDrawer.closeDrawer(Gravity.LEFT); } if(parentDrawer.isDrawerOpen(Gravity.RIGHT)) { parentDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN, Gravity.RIGHT); } else { parentDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT); if(parentDrawer.isDrawerVisible(Gravity.RIGHT)) { parentDrawer.closeDrawer(Gravity.RIGHT); } } } parent = parent.getParent(); } } void stop() { if(parentSwipe != null) { parentSwipe.setEnabled(parentSwipeEnabled); parentSwipe = null; } if(parentDrawer != null) { parentDrawer.setDrawerLockMode(parentDrawerLocks[0], Gravity.LEFT); parentDrawer.setDrawerLockMode(parentDrawerLocks[1], Gravity.RIGHT); parentDrawer = null; parentDrawerLocks = null; } } } <file_sep>/demo/src/main/java/me/licious/delishview/demo/HeadersAdapter.java package me.licious.delishview.demo; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import me.licious.delishview.demo.HeadersFragment.Item; import me.licious.view.DragAdapter; import me.licious.view.HeaderAdapter; public class HeadersAdapter extends BaseAdapter implements DragAdapter, HeaderAdapter { public static final int TYPE_HEADER = 0; public static final int TYPE_ITEM = 1; private final LayoutInflater inflater; private final List<Object> elements; public HeadersAdapter(LayoutInflater inflater, List<Object> elements) { this.inflater = inflater; this.elements = elements; } @Override public int getCount() { return elements.size(); } @Override public Object getItem(int position) { return elements.get(position); } @Override public long getItemId(int position) { return position; } @Override public int getItemViewType(int position) { return (getItem(position) instanceof String) ? TYPE_HEADER : TYPE_ITEM; } @Override public int getViewTypeCount() { return 2; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(getItemViewType(position) == TYPE_HEADER) { View view = (convertView != null) ? convertView : inflater.inflate(R.layout.simple_header, parent, false); ((TextView) view).setText(getItem(position).toString()); return view; } else { View view = (convertView != null) ? convertView : inflater.inflate(R.layout.simple_item, parent, false); ((TextView) view).setText(getItem(position).toString()); return view; } } @Override public View getDragView(int position, ViewGroup parent) { View view = inflater.inflate(R.layout.simple_drag_item, parent, false); ((TextView) view).setText(getItem(position).toString()); return view; } @Override public int getHeaderPosition(int position) { Object element = getItem(position); if(element instanceof String) { return position; } return ((Item) element).header; } @Override public List<Integer> getHeaderPositions() { List<Integer> positions = new ArrayList<>(); for(int i = 0; i < elements.size(); i++) { if(elements.get(i) instanceof String) { positions.add(i); } } return positions; } @Override public View getHeaderView(int position, ViewGroup parent) { View view = inflater.inflate(R.layout.simple_sticky_header, parent, false); TextView textView = (TextView) view.findViewById(R.id.label); textView.setText(getItem(position).toString()); return view; } } <file_sep>/lib/build.gradle apply plugin: 'com.android.library' apply plugin: 'maven' group 'me.licious' version '0.2.0' android { compileSdkVersion 19 buildToolsVersion "20.0.0" defaultConfig { minSdkVersion 14 targetSdkVersion 19 versionCode 1 versionName "1.0" } compileOptions { sourceCompatibility JavaVersion.VERSION_1_6 targetCompatibility JavaVersion.VERSION_1_6 } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } } dependencies { // compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:support-v13:19.+' } uploadArchives { repositories.mavenDeployer { pom.artifactId = 'DelishView' repository(url: "file://${getRootProject().getProjectDir()}/../mvn-repo") } } <file_sep>/demo/src/main/java/me/licious/delishview/demo/DragViewAdapter.java package me.licious.delishview.demo; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; import me.licious.view.DragAdapter; public class DragViewAdapter extends BaseAdapter implements DragAdapter { private final LayoutInflater inflater; private final List<String> elements; public DragViewAdapter(LayoutInflater inflater, List<String> elements) { this.inflater = inflater; this.elements = elements; } @Override public int getCount() { return elements.size(); } @Override public Object getItem(int position) { return elements.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = (convertView != null) ? convertView : inflater.inflate(R.layout.simple_item, parent, false); ((TextView) view).setText("Item " + position); return view; } @Override public View getDragView(int position, ViewGroup parent) { View view = inflater.inflate(R.layout.simple_drag_item, parent, false); ((TextView) view).setText("Item " + position); return view; } } <file_sep>/demo/build.gradle apply plugin: 'com.android.application' android { compileSdkVersion 19 buildToolsVersion "20.0.0" defaultConfig { minSdkVersion 14 targetSdkVersion 19 versionCode 1 versionName "1.0" } compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } signingConfigs { release { storeFile file("${getRootProject().getProjectDir()}/release.keystore") keyAlias "delishview_demo" if(System.console() != null) { storePassword = new String(System.console().readPassword("\n\$ Enter keystore password: ")) keyPassword = new String(System.console().readPassword("\$ Enter key password: ")) } // storePassword = new String(System.getenv("KEYSTORE_PASSWORD")) // keyPassword = new String(System.getenv("KEY_PASSWORD")) } } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' signingConfig signingConfigs.release } } } dependencies { compile project(':lib') compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:support-v13:19.+' } <file_sep>/demo/src/main/java/me/licious/delishview/demo/DragViewFragment.java package me.licious.delishview.demo; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import me.licious.view.DelishView; public class DragViewFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.frag_dragview, container, false); List<String> items = new ArrayList<>(); for(int i = 0; i < 100; i++) { items.add("Item - " + i); } DelishView delishView = (DelishView) view.findViewById(R.id.delish); delishView.setAdapter(new DragViewAdapter(inflater, items)); return view; } } <file_sep>/demo/src/main/java/me/licious/delishview/demo/HeadersFragment.java package me.licious.delishview.demo; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import me.licious.view.DelishView; public class HeadersFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.frag_headers, container, false); List<Object> elements = new ArrayList<>(); for(int i = 0; i < 10; i++) { int headerPosition = elements.size(); elements.add("Header - " + i); for(int j = 0; j < 10; j++) { elements.add(new Item("Item - " + i + " : " + j, headerPosition)); } } DelishView delishView = (DelishView) view.findViewById(R.id.delish); delishView.setAdapter(new HeadersAdapter(inflater, elements)); delishView.addHeaderView(inflater.inflate(R.layout.basic_header, delishView, false)); return view; } public static class Item { public final String label; public final int header; public Item(String label, int header) { this.label = label; this.header = header; } @Override public String toString() { return label; } } } <file_sep>/demo/src/main/java/me/licious/delishview/demo/SwipToRefreshFragment.java package me.licious.delishview.demo; import android.app.Fragment; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import java.util.ArrayList; import java.util.List; import me.licious.view.DelishView; import me.licious.view.DelishView.OnDropAdapter; public class SwipToRefreshFragment extends Fragment { private SwipeRefreshLayout swipe; private DelishView delishView; private List<String> items; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.frag_swipe_to_refresh, container, false); items = new ArrayList<>(); for(int i = 0; i < 100; i++) { items.add("Item - " + i); } swipe = (SwipeRefreshLayout) view.findViewById(R.id.sync_container); swipe.setColorScheme( android.R.color.holo_blue_light, android.R.color.holo_orange_light, android.R.color.holo_green_light, android.R.color.holo_red_light) ; swipe.setOnRefreshListener(new OnRefreshListener() { public void onRefresh() { swipe.postDelayed(new Runnable() { public void run() { swipe.setRefreshing(false); } }, 1000); } }); delishView = (DelishView) view.findViewById(R.id.delish); delishView.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, items)); delishView.setOnDropListener(new OnDropAdapter() { public void onDropItem(int from, int to) { items.add(to, items.remove(from)); delishView.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, items)); } }); delishView.addHeaderView(inflater.inflate(R.layout.basic_header, delishView, false)); return view; } } <file_sep>/lib/src/main/java/me/licious/view/DragAdapter.java package me.licious.view; import android.view.View; import android.view.ViewGroup; public interface DragAdapter { View getDragView(int position, ViewGroup parent); }
d22900d4261f4ff48854cd0fe508fcc8498f3d17
[ "Markdown", "Java", "Gradle" ]
10
Markdown
jeremy-dowdall/DelishView
5186aee5dc79ce78f4e307ee2650cad5c410e284
caebeb0fb4fb6d2b49857585f4f13c88470d3f36
refs/heads/main
<repo_name>ryotasensei/nickel.github.io<file_sep>/app.nickel.eu/configa31d.js window.REACT_APP_ACCOUNT_ENDPOINT='https://api.nickel.eu/customer-banking-api'; window.REACT_APP_ADDRESS_ENDPOINT='https://ws.capadresse.com:8683'; window.REACT_APP_ADDRESS_TIMEOUT='6000'; window.REACT_APP_CUSTOMER_AUTHENTICATION_ENDPOINT='https://api.nickel.eu/customer-authentication-api'; window.REACT_APP_ENV='prod'; window.REACT_APP_GA_ID='UA-42035525-4'; window.REACT_APP_GTM_ID='GTM-577JVB3'; window.REACT_APP_I18N_DEBUG='false'; window.REACT_APP_IS_MAINTENANCE='false'; window.REACT_APP_IS_PREPROD='false'; window.REACT_APP_LOCATION_API='https://api.nickel.eu/location-api'; window.REACT_APP_LOGOUT_DELAY='840000'; window.REACT_APP_MAIL_ENDPOINT='https://ws.capadresse.com:8684'; window.REACT_APP_MAIL_TIMEOUT='6000'; window.REACT_APP_MONISNAP_ENDPOINT='https://api.nickel.eu/monisnap-api'; window.REACT_APP_MONISNAP_SESSION_EXPIRED='900000'; window.REACT_APP_MONISNAP_URL='https://nickel.monisnap.com/fr/nickel/bienvenue/'; window.REACT_APP_MONISNAP_URL_ES='https://nickel.monisnap.com/es/nickel/bienvenido/'; window.REACT_APP_MONITORING_PIXEL_URL='???'; window.REACT_APP_ONE_TRUST_ID='b9acd173-1fbc-4b2e-9f12-f64885ff9c57'; window.REACT_APP_PAYLINE_CSS='https://payment.payline.com/styles/widget-min.css'; window.REACT_APP_PAYLINE_ENDPOINT='https://api.nickel.eu/customer-payline-api'; window.REACT_APP_PAYLINE_SCRIPT='https://payment.payline.com/scripts/widget-min.js'; window.REACT_APP_PERSONAL_SPACE_API_ENDPOINT='https://api.nickel.eu/personal-space-api'; window.REACT_APP_SESSION_EXPIRED='300000'; window.REACT_APP_SHOW_FLAGS='false'; window.REACT_APP_SHOW_YEARLY_STATEMENTS='false'; window.REACT_APP_URL_OLD_VERSION='https://mon.compte-nickel.fr';
b586dc530a550ac4c39534a5d4bbc8e5a82136bd
[ "JavaScript" ]
1
JavaScript
ryotasensei/nickel.github.io
d7fd7948451253809298e45232d41afac95ca14c
f86341d899f48e3be0e5a699a9b8e52b70a240da
refs/heads/main
<repo_name>zapacni/RSAChallenges<file_sep>/sliding/problem.lua --[[ directions: Groups elements of the array in fixed size blocks by passing a "sliding window" over them, stopping when the number of elements in the collection is smaller than the width inputs: arr, the array which the sliding window is passed over width, the number of elements per group step, the distance between the first elements of each group output: an array of arrays of size `width` example: sliding({1, 2, 3, 4}, 2, 1) → {{1, 2}, {2, 3}, {3, 4}} +--------------+ |[1 2]| 3 | 4 | |--------------| | 1 |[2 3]| 4 | |--------------| | 1 | 2 |[3 4]| +--------------+ additional examples: sliding({1, 2, 3, 4, 5}, 2, 2) → {{1, 2}, {3, 4}} sliding({1, 2, 3, 4, 5, 6}, 2, 3) → {{1, 2}, {4, 5}} ]] local mkTests, testCases = table.unpack(require(script.Parent.testgen)) --template local function sliding(arr, width, step) return {} end --test template for _,v in ipairs(mkTests()) do local arr, width, step = table.unpack(v) local out = sliding(arr, width, step) --... end local function eq(s1,s2) local r = #s1 == #s2 for i,t in ipairs(s1) do r = r and #t == #s2[i] for j,v in ipairs(t) do r = r and v == s2[i][j] end end return r end for input, output in pairs(testCases) do local res = sliding(unpack(input)) assert(eq(res,output),("failed for ({%s}, %d, %d), expected {%s} got {%s}"):format( table.concat(input[1], ", "), input[2], input[3], table.concat(output,", "), table.concat(res,", ")) ) end <file_sep>/distances/problem.lua --[[contributed by CntKillMe Input: points (an array of Vector3), #points >= 0, all points are unique. Output: the distance between the closest pair of points, or 0 if there are less than 2 points. Example: if points = { Vector3.new(0, 5, 10), Vector3.new(10, 10, 10), Vector3.new(0, 5, 7) }, then minimum_distance(points) yields 3, because the distance between the first two points is ~11.575837, and the distance between the first and third point is 3, and the distance between the second and third point is ~11.575837. ]] local mkTests,testCases = table.unpack(require(script.Parent.testgen)) -- Only modify this function! -- Bonus challenge ((Optional)) : solve this in O(n log n) time. local function minimum_distance(points) return 0 end --testing template local function formatV3Arr(a) local r = {} for i, v in ipairs(a) do r[i] = "("..tostring(v)..")" end return "{"..table.concat(r,", ").."}" end for _,points in ipairs(mkTests()) do local distance = minimum_distance(points) -- ... end for input, output in pairs(testCases) do local res = minimum_distance(input) assert(math.abs(res - output) < 1e-6, ("for (%s), expected %f, got %f"):format( formatV3Arr(input), output, res )) end <file_sep>/scanning/problem.lua --[[ directions: produce an array containing the intermediate results of applying a binary operator from right → left on an array inputs: arr: a possibly empty array of any combination of values (including the initial value) init: an inital value op: a binary operation to be applied on the intermediate result and the current element output: an array of the intermediate results ex: scanRight({1,3,5,7,9}, 0, function(a,b) return b + a end) yields {25,24,21,16,9,0} since 0 = 0 0 + 9 = 9 9 + 7 = 16 16 + 5 = 21 21 + 3 = 24 25 + 1 = 25 ]] local mkTests,testCases = table.unpack(require(script.Parent.testgen)) --template local function scanRight(arr, init, op) return {} end --testing template for _,case in ipairs(mkTests()) do local arr, init, op = table.unpack(case) local results = scanRight(arr, init, op) --... end local function eq(s1,s2) local r = #s1 == #s2 for i,v in ipairs(s1) do r = r and v == s2[i] end return r end for input, output in pairs(testCases) do local res = scanRight(unpack(input)) assert(eq(res,output),("failed for ({%s}, %d, %q), expected {%s} got {%s}"):format( table.concat(input[1], ", "), input[2], tostring(input[3]), table.concat(output,", "), table.concat(res,", ")) ) end <file_sep>/escaped string/problem.lua --[[ directions: given a string containing at least 2 unescaped quotation marks(") and any number of escaped quotation marks (\"), find the first string of characters between unescaped quotation marks input: a string containing at least 2 unescaped quotes and any number of escaped quotes output: a string of the character between the unescaped quotes example: Bob told me: "jimmy says \"Hello\"" --> yields jimmy says \"Hello\" since while there are quotations around "Hello", they're escaped so they can neither act as starting quotes nor ending quotes, and are instead treated as literal characters ]] local mkTests, testCases = table.unpack(require(script.Parent.testgen)) --template local function getString(str) return "" end --testing template for _,str in ipairs(mkTests()) do local res = getString(str) end for input, output in pairs(testCases) do local res = getString(input) assert(res == output,("failed for %q, expected %s got %s"):format(input,output,res)) end <file_sep>/escaped string/testgen.lua --[[ Autogenerates test cases for escaped string problem output: an array of strings which contain 2 unescaped quotes, and may contain escaped quotes ]] local function insert(s,s2,i) return s:sub(1,i)..s2..s:sub(i+1) end return {function(n) n = n or 100 local ret = {} while #ret < n do local t = {} for j = 1, math.random(30,60) do t[j] = math.random(48,126) end local s = string.char(table.unpack(t)):gsub("\\","") local k1 = math.random(3,math.floor(#s / 2)) local k2 = math.random(k1+5,#s-5) s = insert(s,"\"",k1) s = insert(s,"\"",k2+1) for j = 1, math.random(5) do s = insert(s,[[\"]],math.random(1,#s)) end if not s:match([[\\]]) then ret[#ret+1] = s end end return ret end,{ [ [[^CJ8nCVPos\"dPNALi"Vbpbx=F6YF"zgo94=]] ] = [[Vbpbx=F6YF]]; [ [[y~jTheN"?Y@xUo?SmS"Fc^}>HY@Y8x\"m\"]a]] ] = [[?Y@xUo?SmS]]; [ [[t5\"\"O"[fTA`3u\"P@v0}"7_mQr}Tw{D=\"@sFs]] ] = [[[fTA`3u\"P@v0}]]; [ [[[u5I\"b6=:vyit"O\"YMInw"^m1qCfzkFy[;T>]P]] ] = [[O\"YMInw]]; [ [[~<c_GO8`4"@[qpdJYFC"n@8h\"gER|7]jl;AKkXd]] ] = [[@[qpdJYFC]]; [ [[ON4GLiBBIyh~U"IC|5qz|v76d"IuY2\"_W4RAYH<]] ] = [[IC|5qz|v76d]]; [ [[<ZCeKN]"B7JqPEJdWDR}kJ1}2"T>E<1h:>`=d\"jn]] ] = [[B7JqPEJdWDR}kJ1}2]]; [ [[kQHza?qUkJT@x\"__CZ"N0Mszo\"=8GrS"NS9?FBq]] ] = [[N0Mszo\"=8GrS]]; [ [[]Gl8]j9T>RMv`qP<^"lW_:Nvw[l^\"fScqd"{jShc]] ] = [[lW_:Nvw[l^\"fScqd]]; [ [[KB;z:hZ=pmi\"]VXbw:4"Dbl0_pOQ"w^gyv|Sj1|kxs9]] ] = [[Dbl0_pOQ]]; [ [[bGJ3gk2<kr\"\""4FzZ4``TlON|__G6c"QASK`\"eMOl]] ] = [[4FzZ4``TlON|__G6c]]; [ [[Q_@w"<RWU@x2XL<ry:Z1"h\"Oy\"KGkck3v1JuF{\"qzl>]] ] = [[<RWU@x2XL<ry:Z1]]; [ [[iS{]E?<G>\"~S[t3"WlK9o0"j<}\"\"Z[IbnS8Rxy\"Y=v]] ] = [[WlK9o0]]; [ [[uY5J~6E\"0W[7y;1K1<j\""}\"\"Q|ecSZ8IbtD"Hh9bA1]] ] = [[}\"\"Q|ecSZ8IbtD]]; [ [[XU3;dY|QhO">\"\"Uo`MhgcHAlW5R"bG~\"Py}Yww\"=wr]] ] = [[>\"\"Uo`MhgcHAlW5R]]; [ [[qys">Cm[9Q@3Xz"?@0oM3Aw^XvvFcHve^KIB\"iD@RhD;|O]] ] = [[>Cm[9Q@3Xz]]; [ [[9mAh1D?5]bKz{@}J"VVP|J\"v32<<ByYzh"`>7ut|yqwO;c]] ] = [[VVP|J\"v32<<ByYzh]]; [ [[3@VR6O\"9V_=\";"]oQ<w{PwS\"<|e4F9"uUtBw`f?AZmfzla]] ] = [[]oQ<w{PwS\"<|e4F9]]; [ [[[[zy3Ml_MXlp"R4lwl<NVxf\"k3]4w5pwH?=G`;h"<;XktOA=Q]] ] = [[R4lwl<NVxf\"k3]4w5pwH?=G`;h]]; [ [[g0@lj"69s\"0<yMQGIE"\"q\"yg5\"1UDgG\"6lO^ryvAT];DA@]] ] = [[69s\"0<yMQGIE]]; [ [[[?fx=?RW84@>rBH\""@RILnT5X1Z>xK1UUX;BCXE\""cYTA:8gM]] ] = [[@RILnT5X1Z>xK1UUX;BCXE\"]]; [ [[?aA<G=WvaG`OmQ[AgY"\"Tj8EoAgcLZ"QOkM1MuS~UK3;l1rbI^]] ] = [[\"Tj8EoAgcLZ]]; [ [[Pr<7G\"L70I}thb~\"_tdn"><CG9?F`P:\"7I"E\"yDwBx3A2B0]] ] = [[><CG9?F`P:\"7I]]; [ [[0MndVjuQJ9~ACz?Y0DSf"yDw8Z\"?~v03sD@q?;_hT|FXg0"vgwEw]] ] = [[yDw8Z\"?~v03sD@q?;_hT|FXg0]]; [ [[k_Z[o5u\"JdIvWkUEcS7>~z"V=IkBN"`0q3{;ouYF1i{Qy;>_t5:;]] ] = [[V=IkBN]]; [ [[n22?m06nQY"Q64<\"MS57\"\"vg5=Z_2^>Q@a>nD19V"`\"2]_OsG]] ] = [[Q64<\"MS57\"\"vg5=Z_2^>Q@a>nD19V]]; [ [[yxyeK7nZv\"gZAf~rbL\"c"_j>C1~5G?["axE]f\"5CPwUM1;xzo\"]] ] = [[_j>C1~5G?[]]; [ [[_Yd"[ol22{WGLuF\"H8R\"pfu^m|;<wDf`"OSLHgeDVBe\"f96Rgyi]] ] = [[[ol22{WGLuF\"H8R\"pfu^m|;<wDf`]]; [ [[~f|LoLw^|XOQV"C\"rEHno`x\""n|QB\"Q{IzNxwDCskI>\"`l]U\"]] ] = [[C\"rEHno`x\"]]; [ [[mh2qzN23@wlRTkrHQS`1"y_N]LbYh\"L3IY^^_3|Xpuv{"09\"Z`<aN]] ] = [[y_N]LbYh\"L3IY^^_3|Xpuv{]]; [ [[C:W8jcQk79<rP"9L\"EpL1ec=E]g44?@xY4^I"Baj{mk19Zrhu=FkhC7]] ] = [[9L\"EpL1ec=E]g44?@xY4^I]]; [ [[cH5SnR`?v?aMn~0376s"z9o6ftpWj0"\"LJANDoLRqO9~`u\"hSDy|a[]] ] = [[z9o6ftpWj0]]; [ [[C@Z\"{<jrp8f`E~?Mb~gwP=<ei>"X_J<4az4sn<_@c__IHt"lQA~{8KB]] ] = [[X_J<4az4sn<_@c__IHt]]; [ [[shFud=z:OUbRHr67>Gf7p:~C"E0[N<|xGMGi8aL;=T"\"vSb3KGnFOXi]] ] = [[E0[N<|xGMGi8aL;=T]]; [ [[FVLa?>YcCpn6>:"ac8x\"C"B7oPSihqmzi]_pdYs`}xEhna~8o1sC?k<:]] ] = [[ac8x\"C]]; [ [[{<op|PMSaF[KVmhls39li"fgEvz\"77KUS:uP\"`pJqt>j`W=k9"ogqM5Z]] ] = [[fgEvz\"77KUS:uP\"`pJqt>j`W=k9]]; [ [[FVL"@5ksc<o=8lMcW\"\"MgOSFx6o"h;iym;KZz\"WC\"cVYNL\"q]stY:AVn]] ] = [[@5ksc<o=8lMcW\"\"MgOSFx6o]]; [ [[M7_{vuTMmFyjE^YvLsF[Y"ZdmjA"<2CCyx>~7Eb|\"kpT~A~`H1_Ru[6PnH;E7B]] ] = [[ZdmjA]]; [ [[03v64pY">Z5Pv:@m9EW;e^_xxYtJIxz{tfr5"Ej?\"DB\"aflch}O\"Z\"Vpw?G]] ] = [[>Z5Pv:@m9EW;e^_xxYtJIxz{tfr5]]; [ [[=mBzhRs"sxdAgST"OGy3BCi\"g]^:4gr\"<cdj4T}SYe\":KEhjKSIpHtTusE}BC]] ] = [[sxdAgST]]; [ [[Qt2N~\"rp:f9\"B52XTB~u|"hdVBoLqy7m@s]E<A^"hMLD@NvS|u\"R2:32pKW5Cs]] ] = [[hdVBoLqy7m@s]E<A^]]; [ [[ULovJGDNUAs1]y2P@4_2vOfQ\"m\"1K:"CwAOjx=4dl":zJdM~b0}qmqX9\"^Qv[d]] ] = [[CwAOjx=4dl]]; [ [[@H`qK"V[SvRte7{;0Iy3`A[yqeoK\""nW}2:BUB\"P1sTf;\"^o8\"SyaW{j1I}OT]] ] = [[V[SvRte7{;0Iy3`A[yqeoK\"]]; [ [[9ha"P`w|\"bl\"{^O\"Fo?TE]^28h\"<`MB6j3MQsx^fGQzcXx<PKfl\"m>"gD=:@?]] ] = [[P`w|\"bl\"{^O\"Fo?TE]^28h\"<`MB6j3MQsx^fGQzcXx<PKfl\"m>]]; [ [[RH^b>qj\"5zK=VP9qm3\"1\"]oO`z"lQ;mwo6vnnPvGHC\"x7g~UBUd}hH?^"zj9<6]] ] = [[lQ;mwo6vnnPvGHC\"x7g~UBUd}hH?^]]; [ [[tVcUJbLne\"2uW\"b"q=vHpKj9Kv\"II\"wAJk<i^BPx\"IzD`N<2UfCyHQ"hyw^o[hC=]] ] = [[q=vHpKj9Kv\"II\"wAJk<i^BPx\"IzD`N<2UfCyHQ]]; [ [[YOBU4rwZV`1[oE\"h:D"of_bXYU\"h~"HJK?}~FH8t\"6YRZe@Ko^1w9\"iY{F~V`C\"F]] ] = [[of_bXYU\"h~]]; [ [[a\"bg;\"\"~QO\"K[~VScpgO3vtA"}:\"MZd[1BDR1Yi8i[Y5F5UFu>Y{"~_wzv;313UI]] ] = [[}:\"MZd[1BDR1Yi8i[Y5F5UFu>Y{]]; [ [[IcZjp25tNZ"XuOb}oT\"I`ZOfOj@\"M"\"j|Az[a;nu9nv5=BDAV~R7Wx>NE^r0FgE\"b\"]] ] = [[XuOb}oT\"I`ZOfOj@\"M]]; }}
62fcc85b52b6e264b25f2b408c662e5e06a3e50c
[ "Lua" ]
5
Lua
zapacni/RSAChallenges
0315af1e2acfcc3cddb7ab245404140e2f730b5e
41a5bec0aa6c350fdb73a5a4e274bafadd30489b
refs/heads/master
<repo_name>PradeepShresth/cafe-frontend<file_sep>/src/components/Footer/UpdateFooter.js import React, { useState, useContext } from 'react'; import { AuthContext } from '../Context/auth-context'; import axios from 'axios'; const UpdateFooter = props => { const auth = useContext(AuthContext); const [about, setAbout] = useState(''); const [address, setAddress] = useState(''); const [phone, setPhone] = useState(''); const [email, setEmail] = useState(''); const [facebook, setFacebook] = useState(''); const [twitter, setTwitter] = useState(''); const [instagram, setInstagram] = useState(''); const FooterSubmitHandler = async event => { event.preventDefault(); const data = { about: about, address: address, phone: phone, email: email, facebook: facebook, twitter: twitter, instagram: instagram } try { const response = await axios.patch(process.env.REACT_APP_BACKEND_URL + "/footer/", data, { headers: { 'Authorization': 'Bearer ' + auth.token } }) props.onUpdateFooter(response.data.footer); } catch (err) { console.log(err); } }; const aboutHandler = event => { setAbout(event.target.value); }; const addressHandler = event => { setAddress(event.target.value); }; const phoneHandler = event => { setPhone(event.target.value); }; const emailHandler = event => { setEmail(event.target.value); }; const facebookHandler = event => { setFacebook(event.target.value); }; const twitterHandler = event => { setTwitter(event.target.value); }; const instagramHandler = event => { setInstagram(event.target.value); }; return ( <React.Fragment> <form className="form-control" onSubmit={FooterSubmitHandler}> <textarea onChange={aboutHandler} placeholder="About" defaultValue={props.footer.about} ></textarea> <input type="text" onChange={addressHandler} placeholder="Address" defaultValue={props.footer.address} /> <input type="text" onChange={phoneHandler} placeholder="Phone" defaultValue={props.footer.phone} /> <input type="text" onChange={emailHandler} placeholder="Email" defaultValue={props.footer.email} /> <input type="text" onChange={facebookHandler} placeholder="Facebook" defaultValue={props.footer.facebook} /> <input type="text" onChange={twitterHandler} placeholder="Twitter" defaultValue={props.footer.twitter} /> <input type="text" onChange={instagramHandler} placeholder="Instagram" defaultValue={props.footer.instagram} /> <button className="add-btn" type="submit" onClick={props.cancel}>UPDATE REVIEW</button> <a className="cancel-btn" onClick={props.cancel}>CANCEL</a> </form> </React.Fragment> ); } export default UpdateFooter;<file_sep>/src/containers/Login.js import React, { useState, useContext } from 'react'; import ErrorModal from '../UIElements/ErrorModal/ErrorModal'; import { AuthContext } from '../components/Context/auth-context'; const Login = props => { const auth = useContext(AuthContext); const [name, setName] = useState(''); const [password, setPassword] = useState(''); const [error, setError] = useState(); const loginSubmitHandler = async event => { event.preventDefault(); const data = { name: name, password: <PASSWORD> } try { const response = await fetch(process.env.REACT_APP_BACKEND_URL + '/login', { method: 'POST', headers: { 'Content-type': 'application/json' }, body: JSON.stringify(data) }) setName(''); setPassword(''); const responseData = await response.json(); if (!response.ok) { throw new Error(responseData.message); } auth.login(responseData.userId, responseData.token); } catch (err) { console.log(err); setError(err.message || 'Something went wrong!! Please try again'); } } const nameHandler = event => { setName(event.target.value); } const passwordHandler = event => { setPassword(event.target.value); } const errorHandler = () => { setError(null); } return ( <React.Fragment> <ErrorModal error={error} onClear={errorHandler} modalClosed={errorHandler} /> <section className="section-form"> <div className="row"> <h2>Login</h2> </div> <div className="row"> <form className="contact-form" onSubmit={loginSubmitHandler}> <div className="row"> <div className="col span-1-of-3"> <label>Name</label> </div> <div className="col span-2-of-3"> <input type="text" placeholder="Your name" onChange={nameHandler} value={name} required /> </div> </div> <div className="row"> <div className="col span-1-of-3"> <label>Password</label> </div> <div className="col span-2-of-3"> <input type="text" placeholder="Password" onChange={passwordHandler} value={password} required /> </div> </div> <div className="row"> <div className="col span-1-of-3"></div> <div className="col span-2-of-3"> <input type="submit" value="Login" /> </div> </div> </form> </div> </section> </React.Fragment> ); } export default Login;<file_sep>/src/components/Navigation/NavLink.js import React, { useContext } from 'react'; import { AuthContext } from '../Context/auth-context'; import Aux from '../../hoc/Auxillary'; import './NavLink.css'; const NavLink = props => { const auth = useContext(AuthContext); return ( <Aux> <ul className="main-nav js--main-nav"> <li><a href="#features">Food delivery</a></li> <li><a href="#menu">Menu</a></li> <li><a href="#contact">Contact</a></li> {auth.isLoggedIn && ( <li><a onClick={props.white}>Light Logo</a></li> )} {auth.isLoggedIn && ( <li><a onClick={props.black}>Dark Logo</a></li> )} {auth.isLoggedIn && ( <li><a onClick={auth.logout}>Log out</a></li> )} </ul> <a className="mobile-nav-icon js--nav-icon"><i className="ion-navicon-round"></i></a> </Aux> ); } export default NavLink;<file_sep>/src/components/Menu/MenuItems/UpdateMenu.js import React, { useState, useContext } from 'react'; import { AuthContext } from '../../Context/auth-context'; import axios from 'axios'; const UpdateMenu = props => { const auth = useContext(AuthContext); const [imageFile, setImageFile] = useState(''); const [name, setName] = useState(''); const [description, setDescription] = useState(''); const [price, setPrice] = useState(null); const UpdateMenuSubmitHandler = async event => { event.preventDefault(); const data = new FormData(); data.append("mid", props.m.id); data.append("name", name); data.append("image", imageFile); data.append("description", description); data.append("price", price); try { await axios.patch(process.env.REACT_APP_BACKEND_URL + '/menu/', data, { headers: { 'Authorization': 'Bearer ' + auth.token } }); } catch (err) { console.log(err); } try { const response = await axios.get(process.env.REACT_APP_BACKEND_URL + '/menu/', data); props.onUpdateMenu(response.data.menus); } catch (err) { console.log(err); } }; const nameHandler = event => { setName(event.target.value); }; const imageHandler = event => { setImageFile(event.target.files[0]); }; const descriptionHandler = event => { setDescription(event.target.value); }; const priceHandler = event => { setPrice(event.target.value); }; return ( <React.Fragment> <form className="form-control" onSubmit={UpdateMenuSubmitHandler}> <input type="text" name="name" onChange={nameHandler} placeholder="Name" defaultValue={props.m.name} required /> <input type="file" onChange={imageHandler} /> <textarea name="description" onChange={descriptionHandler} placeholder="Description" defaultValue={props.m.description} required></textarea> <input type="number" name="price" onChange={priceHandler} placeholder="Price" defaultValue={props.m.price} /> <button className="add-btn" type="submit" onClick={props.cancel}>Update BREAKFAST</button> <a className="cancel-btn" onClick={props.cancel}>CANCEL</a> </form> </React.Fragment> ); } export default UpdateMenu;<file_sep>/src/components/Menu/Menu.js import React, { Component } from 'react'; import MenuItems from './MenuItems/MenuItems'; import './Menu.css'; class Menu extends Component { state = { showPoultryAndSeafood: true, showBreakfast: false, showDinner: false, currentValue: 'poultry and seafood', } showPoultryAndSeafoodHandler = () => { this.setState({ showPoultryAndSeafood: true }); this.setState({ showBreakfast: false }); this.setState({ showDinner: false }); this.setState({currentValue: 'poultry and seafood'}); } showBreakfastHandler = () => { this.setState({ showPoultryAndSeafood: false }); this.setState({ showBreakfast: true }); this.setState({ showDinner: false }); this.setState({currentValue: 'breakfast'}); } showDinnerHandler = () => { this.setState({ showPoultryAndSeafood: false }); this.setState({ showBreakfast: false }); this.setState({ showDinner: true }); this.setState({currentValue: 'dinner'}); } render () { return ( <section className="section-menu js--section-menu" id="menu"> <div class="row"> <h2>Our Menu</h2> </div> <div className="menu-buttons"> <a className={this.state.showPoultryAndSeafood === true ? 'menu-button menu-selected' : 'menu-button'} onClick={this.showPoultryAndSeafoodHandler} >PoultryAndSeafood</a> <a className={this.state.showBreakfast === true ? 'menu-button menu-selected' : 'menu-button'} onClick={this.showBreakfastHandler} >Breakfast</a> <a className={this.state.showDinner === true ? 'menu-button menu-selected' : 'menu-button'} onClick={this.showDinnerHandler} >Dinner</a> </div> <MenuItems showPoultryAndSeafood={this.state.showPoultryAndSeafood} showBreakfast={this.state.showBreakfast} showDinner={this.state.showDinner} currentValue={this.state.currentValue} /> </section> ); } }; export default Menu;<file_sep>/src/containers/Cafe.js import React, { Component } from 'react'; import axios from 'axios'; import Modal from '../UIElements/Modal/Modal'; import Aux from '../hoc/Auxillary'; import MainNavigation from '../components/Navigation/MainNavigation'; import NewBanner from '../components/Navigation/NewBanner'; import Features from '../components/Features/Features'; import Gallery from '../components/Gallery/Gallery'; import UpdateGallery from '../components/Gallery/UpdateGallery'; import Menu from '../components/Menu/Menu'; import Reviews from '../components/Reviews/Reviews'; import Map from '../components/Map/Map'; import Footer from '../components/Footer/Footer'; import './queries.css'; class Cafe extends Component { state = { banner: '', banner_adding: false, gallery: [], gallery_adding: false, galleryId: {}, } componentDidMount () { axios.get('http://localhost:8080/api/banner') .then(response => { const banner = response.data.banner.image; this.setState({banner: banner}); }) .catch(error => { console.log(error); }); axios.get('http://localhost:8080/api/gallery') .then(response => { const gallery = response.data.galleries; this.setState({gallery: gallery}); }) .catch(error => { console.log(error); }); } // ------BANNER------------------// addNewBannerHandler = newBanner => { this.setState(state => { state.banner = newBanner; const banner=state.banner; return { banner }; }); }; bannerAddingHandler = () => { this.setState({banner_adding: true}) } bannerCancelHandler = () => { this.setState({banner_adding: false}) } // ------GALLERY------------------// addNewGalleryHandler = newGallery => { this.setState(state => { state.gallery = newGallery; const gallery = state.gallery; return { gallery }; }); }; galleryAddingHandler = gId => { this.setState(state => { state.galleryId = gId; const galleryId = state.galleryId; return { galleryId }; }); this.setState({gallery_adding: true}); console.log(this.state.galleryId); }; galleryCancelHandler = () => { this.setState({gallery_adding: false}) } render () { return ( <Aux> <Modal show={this.state.banner_adding} modalClosed={this.bannerCancelHandler}> <NewBanner cancel={this.bannerCancelHandler} onAddBanner={this.addNewBannerHandler} /> </Modal> <Modal show={this.state.gallery_adding} modalClosed={this.galleryCancelHandler}> <UpdateGallery cancel={this.galleryCancelHandler} onAddGallery={this.addNewGalleryHandler} gid={this.state.galleryId} /> </Modal> <MainNavigation added={this.bannerAddingHandler} banner={this.state.banner} /> <Features /> <Gallery gallerySelectedHandler={this.galleryAddingHandler} galleries={this.state.gallery} /> <Menu /> <Reviews /> <Map /> <Footer /> </Aux> ); } }; export default Cafe;<file_sep>/src/components/Footer/Footer.js import React, { useState, useEffect, useContext } from 'react'; import axios from 'axios'; import Aux from '../../hoc/Auxillary'; import Modal from '../../UIElements/Modal/Modal'; import { AuthContext } from '../Context/auth-context'; import UpdateFooter from './UpdateFooter'; import './Footer.css'; const Footer = props => { const auth = useContext(AuthContext); const [footerUpdating, setFooterUpdating] = useState(false); const [footer, setFooter] = useState({}); useEffect(() => { axios.get(process.env.REACT_APP_BACKEND_URL + '/footer') .then(response => { const footer = response.data.footer; setFooter(footer); }) .catch(error => { console.log(error); }); }, []) const updatingFooterHandler = () => { setFooterUpdating(true); } const cancelUpdatingFooterHandler = () => { setFooterUpdating(false); } const onUpdateFooter = newFooter => { setFooter(newFooter); } return( <Aux> <Modal show={footerUpdating} modalClosed={cancelUpdatingFooterHandler}> <UpdateFooter cancel={cancelUpdatingFooterHandler} footer={footer} onUpdateFooter={onUpdateFooter} /> </Modal> <footer id="contact"> {auth.isLoggedIn && <div className="row" style={{ marginBottom: '20px' }}> <a className="btn btn-review-image" onClick={updatingFooterHandler}>Edit Footer</a> </div> } <div className="row"> <div className="col span-1-of-3 about-footer"> <h3>About</h3> <p>{footer.about}</p> </div> <div className="col span-1-of-3"> <h3>Contact</h3> <p>{footer.address}</p> <p className="info">{footer.phone}</p> <p className="info">{footer.email}</p> </div> <div className="col span-1-of-3"> <h3>Follow Us</h3> <ul className="social-links"> <li><a href={footer.facebook}><i className="ion-social-facebook"></i></a></li> <li><a href={footer.twitter}><i className="ion-social-twitter"></i></a></li> <li><a href={footer.instagram}><i className="ion-social-instagram"></i></a></li> </ul> </div> </div> </footer> </Aux> ) } export default Footer;<file_sep>/src/components/Reviews/Reviews.js import React, { useState, useEffect, useContext } from 'react'; import axios from 'axios'; import { AuthContext } from '../Context/auth-context'; import Aux from '../../hoc/Auxillary'; import Modal from '../../UIElements/Modal/Modal'; import UpdateReviewImage from './UpdateReviewImage'; import UpdateReview from './UpdateReview'; import './Reviews.css'; const Reviews = props => { const auth = useContext(AuthContext); const [reviewImage, setReviewImage] = useState(''); const [reviewImage_updating, setReviewImage_updating] = useState(false); const [reviews, setReviews] = useState([]); const [review_updating, setReview_updating] = useState(false); const [current_review, setCurrent_review] = useState({}); useEffect(() => { axios.get(process.env.REACT_APP_BACKEND_URL + '/review/image') .then(response => { const reviewImage = response.data.reviewImage.image; setReviewImage(reviewImage); }) .catch(error => { console.log(error); }); axios.get(process.env.REACT_APP_BACKEND_URL + '/review/') .then(response => { const reviews = response.data.reviews; setReviews(reviews); }) .catch(error => { console.log(error); }); }, [ ]) const reviewImageUpdatingHandler = () => { setReviewImage_updating(true); } const reviewImageCancelHandler = () => { setReviewImage_updating(false); } const onUpdateReviewImageHandler = newReviewImage => { setReviewImage(newReviewImage); }; const updateReviewHandler = c_review => { setCurrent_review(c_review); setReview_updating(true); } const reviewCancelHandler = () => { setReview_updating(false); } const onUpdateReviewHandler = newReview => { setReviews(newReview); }; return ( <Aux> <Modal show={reviewImage_updating} modalClosed={reviewImageCancelHandler}> <UpdateReviewImage cancel={reviewImageCancelHandler} onUpdateReviewImage={onUpdateReviewImageHandler} /> </Modal> <Modal show={review_updating} modalClosed={reviewCancelHandler}> <UpdateReview cancel={reviewCancelHandler} onUpdateReview={onUpdateReviewHandler} review={current_review} /> </Modal> <section className="section-testimonials" style={{ backgroundImage: `linear-gradient(rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8)), url(${process.env.REACT_APP_ASSET_URL}/${reviewImage })`, }}> <div className="row"> <h2>Our customers can't live without us</h2> {auth.isLoggedIn && <a className="btn btn-review-image" onClick={reviewImageUpdatingHandler}>Edit Image</a> } </div> <div className="row"> {reviews.map(review => { return ( <div key={review._id} className="col span-1-of-3"> <blockquote> {review.comment} <cite> <img src={`${process.env.REACT_APP_ASSET_URL}/${review.image}`} alt="" />{review.name} {auth.isLoggedIn && <a className="btn btn-review-image" onClick={() => updateReviewHandler(review)}>Edit Review</a> } </cite> </blockquote> </div> ); })} </div> </section> </Aux> ); }; export default Reviews;<file_sep>/src/components/Navigation/UpdateBlackLogo.js import React, { useState, useContext } from 'react'; import { AuthContext } from '../Context/auth-context'; import axios from 'axios'; const UpdateBlackLogo = props => { const auth = useContext(AuthContext); const [imageFile, setImageFile] = useState(''); const BLogoSubmitHandler = async event => { event.preventDefault(); const data = new FormData(); data.append("image", imageFile); try { const response = await axios.patch(process.env.REACT_APP_BACKEND_URL + "/blackLogo", data, { headers: { 'Authorization': 'Bearer ' + auth.token } }) props.onUpdateLogo(response.data.logo.image); } catch (err) { console.log(err); } }; const imageHandler = event => { setImageFile(event.target.files[0]); }; return ( <React.Fragment> <form className="form-control" onSubmit={BLogoSubmitHandler}> <input type="file" onChange={imageHandler} required /> <button className="add-btn" type="submit" onClick={props.cancel}>UPDATE LOGO</button> <a className="cancel-btn" onClick={props.cancel}>CANCEL</a> </form> </React.Fragment> ); } export default UpdateBlackLogo;<file_sep>/src/App.js import React, { useEffect } from 'react'; import {BrowserRouter as Router, Route, Redirect, Switch} from 'react-router-dom'; import { useAuth } from './hooks/auth-hook'; import Cafe from './containers/Cafe'; import Login from './containers/Login'; import { AuthContext } from './components/Context/auth-context'; import './App.css'; const App = props => { const { token, login, logout } = useAuth(); useEffect(() => { const script = document.createElement('script'); script.src = "/js/script.js"; script.async = true; document.body.appendChild(script); return () => { document.body.removeChild(script); } }); let routes; if (token) { routes = ( <Switch> <Route path="/" exact> <Cafe /> </Route> <Redirect to="/" /> </Switch> ); } else { routes = ( <Switch> <Route path="/" exact> <Cafe /> </Route> <Route path="/veryverysecretpage"> <Login /> </Route> <Redirect to="/" /> </Switch> ); } return ( <div className="App"> <AuthContext.Provider value={{ isLoggedIn: !!token, token: token, login: login, logout: logout}} > <Router> {routes} </Router> </AuthContext.Provider> </div> ); } export default App; <file_sep>/src/components/Reviews/UpdateReview.js import React, { useState, useContext } from 'react'; import { AuthContext } from '../Context/auth-context'; import axios from 'axios'; const UpdateReview = props => { const auth = useContext(AuthContext); const [name, setName] = useState(''); const [imageFile, setImageFile] = useState(''); const [comment, setComment] = useState(''); const ReviewSubmitHandler = async event => { event.preventDefault(); const data = new FormData(); data.append("rid", props.review._id); data.append("name", name); data.append("image", imageFile); data.append("comment", comment); try { const response = await axios.patch(process.env.REACT_APP_BACKEND_URL + "/review/", data, { headers: { 'Authorization': 'Bearer ' + auth.token } }) props.onUpdateReview(response.data.reviews); } catch (err) { console.log(err); } }; const nameHandler = event => { setName(event.target.value); }; const imageHandler = event => { setImageFile(event.target.files[0]); }; const commentHandler = event => { setComment(event.target.value); }; return ( <React.Fragment> <form className="form-control" onSubmit={ReviewSubmitHandler}> <input type="text" onChange={nameHandler} defaultValue={props.review.name} required /> <input type="file" onChange={imageHandler} /> <textarea onChange={commentHandler} defaultValue={props.review.comment} required></textarea> <button className="add-btn" type="submit" onClick={props.cancel}>UPDATE REVIEW</button> <a className="cancel-btn" onClick={props.cancel}>CANCEL</a> </form> </React.Fragment> ); } export default UpdateReview;<file_sep>/src/components/Gallery/Gallery.js import React, { useContext } from 'react'; import {AuthContext} from '../Context/auth-context'; import Aux from '../../hoc/Auxillary'; import './Gallery.css'; const Gallery = props => { const auth = useContext(AuthContext); return ( <section className="section-meals"> <ul className="meals-showcase clearfix"> {props.galleries.map(gallery => { return ( <Aux key={gallery.id}> { auth.isLoggedIn === true ? ( <li onClick={() => props.gallerySelectedHandler(gallery.id)}> <figure className="meal-photo"> <img src={`${process.env.REACT_APP_ASSET_URL}/${gallery.image}`} alt="" /> </figure> </li> ) : ( <li> <figure className="meal-photo"> <img src={`${process.env.REACT_APP_ASSET_URL}/${gallery.image}`} alt="" /> </figure> </li> )} </Aux> ) })} </ul> </section> ); }; export default Gallery;<file_sep>/src/components/Menu/MenuItems/MenuItems.js import React, { useState, useContext, useEffect } from 'react'; import axios from 'axios'; import { AuthContext } from '../../Context/auth-context'; import Aux from '../../../hoc/Auxillary'; import Modal from '../../../UIElements/Modal/Modal'; import NewMenu from './NewMenu'; import UpdateMenu from './UpdateMenu'; const MenuItems = props => { const auth = useContext(AuthContext); const [menu_adding, setMenuAdding] = useState(false); const [menu_updating, setMenuUpdating] = useState(false); const [current_menu, setCurrentMenu] = useState({}); const [menus, setMenus] = useState([]); useEffect(() => { axios.get(process.env.REACT_APP_BACKEND_URL + '/menu') .then(response => { const menus = response.data.menus; setMenus(menus); }) .catch(error => { console.log(error); }); }, []) const addNewMenuHandler = m => { setMenus(menus.concat(m)); }; const menuAddingHandler= () => { setMenuAdding(true); }; const deleteMenuHandler = async mid => { const data = {mid} let updatedmenus; try { const response = await axios.post(process.env.REACT_APP_BACKEND_URL + '/delete', data, { headers: { 'Authorization': 'Bearer ' + auth.token } }); updatedmenus = response.data.menus; } catch (err) { console.log(err); } setMenus(updatedmenus); } const updateMenuHandler = ( c_menu) => { setCurrentMenu(c_menu); setMenuUpdating(true); } const updateMenuStateHandler = newMenus => { setMenus(newMenus); } const menuUpdateCancelHandler = () => { setMenuUpdating(false); } const menuCancelHandler = () => { setMenuAdding(false); } return ( <Aux> <Modal show={menu_adding} modalClosed={menuCancelHandler}> <NewMenu cancel={menuCancelHandler} onAddMenu={addNewMenuHandler} currentValue={props.currentValue} /> </Modal> <Modal show={menu_updating} modalClosed={menuUpdateCancelHandler}> <UpdateMenu cancel={menuUpdateCancelHandler} onUpdateMenu={updateMenuStateHandler} m={current_menu} /> </Modal> {props.showPoultryAndSeafood && <div className="row menu-content"> {menus.filter(menu => menu.type === "poultry and seafood").map(menu => { return ( <div key={menu.id} className="col menu-1-of-2 meal-col"> <div className="col span-2-of-6 meal-image"> <img src={`${process.env.REACT_APP_ASSET_URL}/${menu.image}`} alt='' /> </div> <div className="col span-4-of-6 meal-info"> <h3> {menu.name} {auth.isLoggedIn && ( <i className="ion-settings" onClick={() => updateMenuHandler(menu)}></i> )} {auth.isLoggedIn && ( <i className="ion-ios-close-outline" onClick={() => deleteMenuHandler(menu.id)}></i> )} </h3> <p>{menu.description}</p> {menu.price && <h4>Rs. {menu.price}</h4> } </div> </div> ); })} {auth.isLoggedIn && ( <div className="col menu-1-of-2 meal-col add-menu" onClick={menuAddingHandler}> <h5>ADD SEAFOOD</h5> </div> )} </div> } {props.showBreakfast && <div className="row menu-content"> {menus.filter(menu => menu.type === "breakfast").map(menu => { return ( <div key={menu.id} className="col menu-1-of-2 meal-col"> <div className="col span-2-of-6 meal-image"> <img src={`${process.env.REACT_APP_ASSET_URL}/${menu.image}`} alt='' /> </div> <div className="col span-4-of-6 meal-info"> <h3> {menu.name} {auth.isLoggedIn && ( <i className="ion-settings" onClick={() => updateMenuHandler(menu.id, menu)}></i> )} {auth.isLoggedIn && ( <i className="ion-ios-close-outline" onClick={() => deleteMenuHandler(menu.id)}></i> )} </h3> <p>{menu.description}</p> {menu.price && <h4>Rs. {menu.price}</h4> } </div> </div> ); })} {auth.isLoggedIn && ( <div className="col menu-1-of-2 meal-col add-menu" onClick={menuAddingHandler}> <h5>ADD BREAKFAST</h5> </div> )} </div> } {props.showDinner && <div className="row menu-content"> {menus.filter(menu => menu.type === "dinner").map(menu => { return ( <div key={menu.id} className="col menu-1-of-2 meal-col"> <div className="col span-2-of-6 meal-image"> <img src={`${process.env.REACT_APP_ASSET_URL}/${menu.image}`} alt='' /> </div> <div className="col span-4-of-6 meal-info"> <h3> {menu.name} {auth.isLoggedIn && ( <i className="ion-settings" onClick={() => updateMenuHandler(menu.id, menu)}></i> )} {auth.isLoggedIn && ( <i className="ion-ios-close-outline" onClick={() => deleteMenuHandler(menu.id)}></i> )} </h3> <p>{menu.description}</p> {menu.price && <h4>Rs. {menu.price}</h4> } </div> </div> ); })} {auth.isLoggedIn && ( <div className="col menu-1-of-2 meal-col add-menu" onClick={menuAddingHandler}> <h5>ADD DINNER</h5> </div> )} </div> } </Aux> ); }; export default MenuItems;
1fdd43595cc487cd688d2dfa3bb3a1ad249f4c60
[ "JavaScript" ]
13
JavaScript
PradeepShresth/cafe-frontend
0a644aa0436c71d07a98f3f146395e514d03d16f
d36c9fd38e6304fdd4a4fba95af9a3e491a99f55
refs/heads/master
<file_sep>package com.githubzhu.linkedlist; import javax.sound.midi.Soundbank; import java.util.Stack; /** * @Author: github_zhu * @Describtion: * @Date:Created in 2020/6/25 17:52 * @ModifiedBy: */ public class LInkedListDemo { public static void main(String[] args) { //测试 HeroNode heroNode1 = new HeroNode(1, "宋江", "及时雨"); HeroNode heroNode2 = new HeroNode(2, "卢俊义", "玉麒麟"); HeroNode heroNode3 = new HeroNode(3, "吴用", "智多星"); HeroNode heroNode4 = new HeroNode(4, "林冲", "豹子头"); ////创建链表 //SingleLinkedList singleLinkedList = new SingleLinkedList(); //singleLinkedList.add(heroNode1); //singleLinkedList.add(heroNode1); //singleLinkedList.add(heroNode2); //singleLinkedList.add(heroNode3); //singleLinkedList.add(heroNode4); //创建链表 SingleLinkedList singleLinkedList = new SingleLinkedList(); singleLinkedList.add2(heroNode1); //singleLinkedList.add2(heroNode1); singleLinkedList.add2(heroNode4); singleLinkedList.add2(heroNode2); singleLinkedList.add2(heroNode3); //显示 singleLinkedList.list(); singleLinkedList.reverseLinkedList(singleLinkedList.getHead()); singleLinkedList.list(); System.out.println("__________________"); singleLinkedList.reversePrint(singleLinkedList.getHead()); } } class SingleLinkedList { private HeroNode head = new HeroNode(0, "", ""); public HeroNode getHead() { return head; } //添加节点到单向链表 //思路,当不考虑标号顺序时 //找到当前节点的最后节点,将这个节点的next 指向新的的节点 public void add(HeroNode heroNode) { //因为节点头不能动,因此需要辅助变量 temp HeroNode temp = head; //遍历链表,找到最后 while (true) { if (temp.next == null) { System.out.print("1--"); break; } //如果没有找到最后,将temp后移 System.out.print("2--"); temp = temp.next; } //当退出while 时 temp 就指向链表的最后 //将这个节点的next 指向新的节点 temp.next = heroNode; } public void add2(HeroNode heroNode) { HeroNode temp = head; boolean flag = false;//英雄存在标志位 while (true) { if (temp.next == null) { break; } else if (temp.next.no > heroNode.no) { break; } else if (temp.next.no == heroNode.no) { flag = true; break; } temp = temp.next; } if (flag) { System.out.printf("英雄 %d 已经存在,不能加入",heroNode.no); } else { heroNode.next = temp.next; temp.next = heroNode; } } //更新链表 public void update(HeroNode newHeroNode) { //判断是否为为空 if (head.next == null) { System.out.println("链表为空"); return; } //找到修改的节点,根据弄 //定义一个辅助变量 HeroNode temp = head.next; boolean flag = false;//该节点是否存在 while (true) { if (temp == null) { break;//已经遍历完链表| } if (temp.no == newHeroNode.no) { flag = true; break; } temp = temp.next; } if (flag) { temp.no = newHeroNode.no; temp.nickname = newHeroNode.nickname; } else { System.out.printf("没有找到%d 英雄,不能更改",newHeroNode.no); } } //删除元素 public void delete(int no) { HeroNode temp = head; boolean flag = false; while (true) { if (temp.next == null) { break; } else if (temp.next.no == no) { flag = true; break; } temp = temp.next; } if (flag) { temp.next = temp.next.next; } else { System.out.printf("%d 英雄不存在",no); } } //反转 public void reverseLinkedList(HeroNode head) { if (head.next == null || head.next.next == null) { return; } //定义一个辅助指针(变量) 帮助我们遍历原来的链表 HeroNode cur = head.next; HeroNode next = null;//指向当前节点的【cur】 的下一个节点 HeroNode reverseHead = new HeroNode(0, "", ""); //遍历原来链表,每遍历一个放在新的链表最前端 while (cur != null) { next = cur.next; cur.next = reverseHead.next;//将新的元素添加到新链表的做最前端 reverseHead.next = cur; cur = next; } //将head。.next 执行reverseHead.next ,实现反转 head.next = reverseHead.next; } //反转打印 public void reversePrint(HeroNode head) { if (head.next == null) { return; } Stack<HeroNode> stack = new Stack<HeroNode>(); HeroNode cur = head.next; while (cur != null) { stack.push(cur); cur = cur.next; } while (stack.size() > 0) { System.out.println(stack.pop()); } } //显示遍历链表 public void list() { //判断是否为空 if (head.next == null) { System.out.println("链表为空"); return; } //因为头节点不能动 因此需要一个辅助变量来遍历 HeroNode temp = head.next; while (true) { //判断是否到链表尾部 if (temp == null) { break; } //输出节点信息 System.out.println(temp); //将输temp 后移, temp = temp.next; } } } class HeroNode { public int no; public String name; public String nickname; public HeroNode next; //构造器 public HeroNode(int no, String name, String nickname) { this.no = no; this.name = name; this.nickname = nickname; } @Override public String toString() { return "HeroNode{" + "no=" + no + ", name='" + name + '\'' + ", nickname='" + nickname + '\'' + '}'; } }
a9db49cf8156b32fb7cf96fb3b849029e1326869
[ "Java" ]
1
Java
github-cccc/data-and-stucture
495124152b609b8c408e3cba3adcc449706213e4
8db1b11ee23875c4adf445db11e8f2c0fcb66381
refs/heads/main
<file_sep>json.extract! @service_zone, :id, :longitude, :latitude, :created_at, :updated_at <file_sep>class Subcategory < ActiveRecord::Base belongs_to :category has_many :articles def to_s name end end <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) Role.where(name:"Administrador").first_or_create Role.where(name: "Usuario").first_or_create User.where(email: "<EMAIL>").first_or_create admin = User.where(email:"<EMAIL>").try(:first) if !admin admin = User.create(email:"<EMAIL>",password:<PASSWORD>,role_id:1) end admin.confirm!<file_sep>require "rails_helper" RSpec.describe ServiceZonesController, type: :routing do describe "routing" do it "routes to #index" do expect(:get => "/service_zones").to route_to("service_zones#index") end it "routes to #new" do expect(:get => "/service_zones/new").to route_to("service_zones#new") end it "routes to #show" do expect(:get => "/service_zones/1").to route_to("service_zones#show", :id => "1") end it "routes to #edit" do expect(:get => "/service_zones/1/edit").to route_to("service_zones#edit", :id => "1") end it "routes to #create" do expect(:post => "/service_zones").to route_to("service_zones#create") end it "routes to #update via PUT" do expect(:put => "/service_zones/1").to route_to("service_zones#update", :id => "1") end it "routes to #update via PATCH" do expect(:patch => "/service_zones/1").to route_to("service_zones#update", :id => "1") end it "routes to #destroy" do expect(:delete => "/service_zones/1").to route_to("service_zones#destroy", :id => "1") end end end <file_sep>class ServiceZonesController < ApplicationController before_action :set_service_zone, only: [:show, :edit, :update, :destroy] respond_to :html, :xml, :json def index @service_zones = ServiceZone.all respond_with(@service_zones) end def show respond_with(@service_zone) end def new @service_zone = ServiceZone.new respond_with(@service_zone) end def edit end def create @service_zone = ServiceZone.new(service_zone_params) @service_zone.save respond_with(@service_zone) end def update @service_zone.update(service_zone_params) respond_with(@service_zone) end def destroy @service_zone.destroy respond_with(@service_zone) end private def set_service_zone @service_zone = ServiceZone.find(params[:id]) end def service_zone_params params.require(:service_zone).permit(:longitude, :latitude) end end <file_sep>json.extract! @image, :id, :name, :path, :article_id, :created_at, :updated_at <file_sep>class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception layout :layout_by_resource def mail existe = User.where(email:params[:busca_correo]).count > 0 respond_to do |format| format.json {render :json => existe} end end def layout_by_resource #decia application 2 es por mientras if devise_controller? "devise" else "application" end end end <file_sep>json.array!(@service_zones) do |service_zone| json.extract! service_zone, :id, :longitude, :latitude json.url service_zone_url(service_zone, format: :json) end <file_sep>class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable belongs_to :role has_many :orders after_create :set_token def to_s email end private def set_token update_column("token", SecureRandom.hex) end end <file_sep>class Order < ActiveRecord::Base belongs_to :user has_many :detail_orders, :dependent => :destroy has_many :articles, :through => :detail_order end <file_sep>require 'rails_helper' RSpec.describe "service_zones/edit", type: :view do before(:each) do @service_zone = assign(:service_zone, ServiceZone.create!( :longitude => "MyString", :latitude => "MyString" )) end it "renders the edit service_zone form" do render assert_select "form[action=?][method=?]", service_zone_path(@service_zone), "post" do assert_select "input#service_zone_longitude[name=?]", "service_zone[longitude]" assert_select "input#service_zone_latitude[name=?]", "service_zone[latitude]" end end end <file_sep>class DetailOrder < ActiveRecord::Base has_many :articles belongs_to :order end <file_sep>json.extract! @detail_order, :id, :article_id, :amount, :order_id, :created_at, :updated_at <file_sep>json.array!(@articles) do |article| json.extract! article, :id, :sku, :description, :price, :amount, :category_id, :subcategory_id json.url article_url(article, format: :json) end <file_sep>class ServiceZone < ActiveRecord::Base end <file_sep>class Image < ActiveRecord::Base belongs_to :article def to_s name end def set_url upload if !!upload random_prefix = Array.new(16){[*"a".."z", *"0".."9"].sample}.join + "_" name = random_prefix + upload.original_filename directory = "public/images" dir = File.join(directory, name) File.open(dir, "wb") { |f| f.write(upload.read) } self.path = name end end end <file_sep>json.array!(@detail_orders) do |detail_order| json.extract! detail_order, :id, :article_id, :amount, :order_id json.url detail_order_url(detail_order, format: :json) end <file_sep>require 'rails_helper' RSpec.describe "detail_orders/new", type: :view do before(:each) do assign(:detail_order, DetailOrder.new( :article_id => 1, :amount => 1, :order_id => 1 )) end it "renders new detail_order form" do render assert_select "form[action=?][method=?]", detail_orders_path, "post" do assert_select "input#detail_order_article_id[name=?]", "detail_order[article_id]" assert_select "input#detail_order_amount[name=?]", "detail_order[amount]" assert_select "input#detail_order_order_id[name=?]", "detail_order[order_id]" end end end <file_sep>class Category < ActiveRecord::Base has_many :subcategories has_many :articles def to_s name end end <file_sep>require 'rails_helper' RSpec.describe "articles/new", type: :view do before(:each) do assign(:article, Article.new( :sku => "MyString", :description => "MyString", :price => "9.99", :amount => 1, :category_id => 1, :subcategory_id => 1 )) end it "renders new article form" do render assert_select "form[action=?][method=?]", articles_path, "post" do assert_select "input#article_sku[name=?]", "article[sku]" assert_select "input#article_description[name=?]", "article[description]" assert_select "input#article_price[name=?]", "article[price]" assert_select "input#article_amount[name=?]", "article[amount]" assert_select "input#article_category_id[name=?]", "article[category_id]" assert_select "input#article_subcategory_id[name=?]", "article[subcategory_id]" end end end <file_sep>require 'rails_helper' RSpec.describe "articles/show", type: :view do before(:each) do @article = assign(:article, Article.create!( :sku => "Sku", :description => "Description", :price => "9.99", :amount => 1, :category_id => 2, :subcategory_id => 3 )) end it "renders attributes in <p>" do render expect(rendered).to match(/Sku/) expect(rendered).to match(/Description/) expect(rendered).to match(/9.99/) expect(rendered).to match(/1/) expect(rendered).to match(/2/) expect(rendered).to match(/3/) end end <file_sep>require 'rails_helper' RSpec.describe "service_zones/new", type: :view do before(:each) do assign(:service_zone, ServiceZone.new( :longitude => "MyString", :latitude => "MyString" )) end it "renders new service_zone form" do render assert_select "form[action=?][method=?]", service_zones_path, "post" do assert_select "input#service_zone_longitude[name=?]", "service_zone[longitude]" assert_select "input#service_zone_latitude[name=?]", "service_zone[latitude]" end end end <file_sep>class Article < ActiveRecord::Base belongs_to :category belongs_to :subcategory belongs_to :detail_order has_many :images def to_s description end end <file_sep>require 'rails_helper' RSpec.describe "detail_orders/show", type: :view do before(:each) do @detail_order = assign(:detail_order, DetailOrder.create!( :article_id => 1, :amount => 2, :order_id => 3 )) end it "renders attributes in <p>" do render expect(rendered).to match(/1/) expect(rendered).to match(/2/) expect(rendered).to match(/3/) end end <file_sep>class HomeController < ApplicationController before_action :authenticate_user! def index respond_to do |format| format.html {render :layout => "application"} end end end <file_sep>require 'rails_helper' RSpec.describe "ServiceZones", type: :request do describe "GET /service_zones" do it "works! (now write some real specs)" do get service_zones_path expect(response).to have_http_status(200) end end end <file_sep>json.extract! @order, :id, :user_id, :address, :longitude, :latitude, :created_at, :updated_at <file_sep>class DetailOrdersController < ApplicationController before_action :set_detail_order, only: [:show, :edit, :update, :destroy] respond_to :html, :xml, :json def index @detail_orders = DetailOrder.all respond_with(@detail_orders) end def show respond_with(@detail_order) end def new @detail_order = DetailOrder.new respond_with(@detail_order) end def edit end def create @detail_order = DetailOrder.new(detail_order_params) @detail_order.save respond_with(@detail_order) end def update @detail_order.update(detail_order_params) respond_with(@detail_order) end def destroy @detail_order.destroy respond_with(@detail_order) end private def set_detail_order @detail_order = DetailOrder.find(params[:id]) end def detail_order_params params.require(:detail_order).permit(:article_id, :amount, :order_id) end end
f585e28809ba072ae49f52b978465ba571b2767f
[ "Ruby" ]
28
Ruby
eugecodes/backend_instachup
4e433d2725a350d8d1f28c54de7876c1a492b7bf
d9e463f36dba9b8b4c761b9252ec1c772ab3deb4
refs/heads/master
<repo_name>soulzcore/basketball<file_sep>/src/main/java/hadoop/CalculateBestPlayerByTeam/JobReducer.java package hadoop.CalculateBestPlayerByTeam; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.MapWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; public class JobReducer extends Reducer<Text, MapWritable, Text, Text>{ HashMap<Text, Integer> hm = new HashMap<Text, Integer>(); @Override protected void reduce(Text key, Iterable<MapWritable> values, Context context) throws IOException, InterruptedException { Iterator<MapWritable> valuesIt = values.iterator(); while(valuesIt.hasNext()){ MapWritable mw = valuesIt.next(); Text name = (Text)mw.get("name"); IntWritable po = (IntWritable) mw.get("points"); //addPlayer(new String(name.getBytes(),StandardCharsets.UTF_8),po.get()); //addPlayer(name,po.get()); addPlayer(name,123); } int totPoints = 0; Text playerName=new Text(""); Set set = hm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); if((Integer)me.getValue()>totPoints){ totPoints = (Integer)me.getValue(); playerName=(Text)me.getKey(); } } context.write(key, playerName); } public void addPlayer(Text name, int points){ if(hm.containsKey(name)){ hm.put(name, hm.get(name)+points); }else{ hm.put(name, points); } } }<file_sep>/src/main/java/hadoop/CalculateBestPlayerByTeam/JobMapper.java package hadoop.CalculateBestPlayerByTeam; import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.MapWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class JobMapper extends Mapper<LongWritable, Text, Text, MapWritable>{ private final static IntWritable one = new IntWritable(1); private Text word = new Text(); @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] records = line.split(","); String points = records[8].replace("\"", "");; MapWritable mp = new MapWritable(); mp.put(new Text("name"),new Text(records[0])); mp.put(new Text("points"),new Text(records[8])); IntWritable p = new IntWritable(Integer.parseInt(points)); StringTokenizer st = new StringTokenizer(line," "); context.write(new Text(records[3]),mp ); /* while(st.hasMoreTokens()){ word.set(st.nextToken()); context.write(word,one); } */ } }
18d58edfd5dd33d9e538dea4fca555e21075cccc
[ "Java" ]
2
Java
soulzcore/basketball
efa11815591357eafd06fe77033741b6b9ce7e55
d5660caaa24d450517950ebb74c0db3880663b9c
refs/heads/master
<file_sep>class Person attr_accessor :name, :total_lives def initialize (name) self.name = name self.total_lives = 3 end def person_name name end def person_lives total_lives end end <file_sep>require_relative ("question") require_relative ("person") require_relative ("random_num") def score_zero (player1, player2) if player1.total_lives == 0 winner = player2.person_name winner_score = player2.person_lives elsif player2.total_lives == 0 winner = player1.person_name winner_score = player1.person_lives end puts "#{winner} wins with a score of #{winner_score}/3" puts "----- GAME OVER -----" puts "Good bye" end def game(player1, player2) i = 1 while (player1.person_lives > 0) && (player2.person_lives > 0) number1 = (Random_num.new).random_number number2 = (Random_num.new).random_number question = Question.new(number1, number2, number1 + number2) question.ask_question answer = gets.chomp.to_i round = i % 2 if answer != question.answer_to_question if round == 1 player1.total_lives -= 1 puts "Player 1: Seriously? No!" else player2.total_lives -= 1 puts "Player 2: Seriously? No!" end else puts (round == 1 ) ? ("Player 1: YES! You are correct") : ("Player 2: YES! You are correct") end if player1.total_lives == 0 || player2.total_lives == 0 score_zero(player1, player2) else puts "P1: #{player1.total_lives}/3 vs P2: #{player2.total_lives}/3" puts "----- NEW TURN -----" end i += 1 end end player1 = Person.new("Player 1") player2 = Person.new("Player 2") game(player1, player2)<file_sep>class Question attr_accessor :number1, :number2, :answer def initialize(num1, num2, ans) self.number1 = num1 self.number2 = num2 self.answer = ans end def ask_question puts "What does #{number1} plus #{number2} equal?" end def answer_to_question answer end end <file_sep>class Random_num attr_accessor :number def initialize self.number = rand(20) end def random_number number end end
27d6eb9dc90d0f36174691cb3b7634250aa0f12f
[ "Ruby" ]
4
Ruby
garychengc/two-o-player
cc2b5d45df787a73104ef1db893260bc21c982c9
dcf874c9411a402780f398e58a789b63c922eb39
refs/heads/master
<file_sep>// // PopUpVC.swift // FactCheck // // Created by <NAME> on 21/04/2017. // Copyright © 2017 Computer Science. All rights reserved. // import UIKit class PopUpVC: UIViewController { var passedScore = 0 @IBOutlet weak var scoreLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.black.withAlphaComponent(0.8) self.showPopUp() scoreLabel.text = "Your score is \(passedScore)%" } func showPopUp() { self.view.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) self.view.alpha = 0.0 UIView.animate(withDuration: 0.25, animations: { self.view.alpha = 1.0 self.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }) } } <file_sep>// // GameVC.swift // FactCheck // // Created by <NAME> on 21/04/2017. // Copyright © 2017 Computer Science. All rights reserved. // import UIKit class GameVC: UIViewController { @IBOutlet weak var webView: UIWebView! @IBOutlet weak var searchButton: UIButton! @IBOutlet weak var questionText: UILabel! @IBOutlet weak var questionNumber: UILabel! @IBOutlet weak var totalQuestions: UILabel! @IBOutlet weak var timeRemaining: UILabel! var score = 0 var time = 5 var questionCount = 1 var questions = [Question]() struct Question { var question: String var answer: Bool init(_ question: String, _ answer: Bool) { self.question = question self.answer = answer } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let requestURL = URL(string: "http://google.ie") let request = URLRequest(url: requestURL!) webView.loadRequest(request) webView.isHidden = true questions = [] setQuestions() questionText.text = questions.first?.question questionNumber.text = "\(questionCount)" totalQuestions.text = "/\(questions.count)" timeRemaining.text = "\(time) seconds" var _ = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) } @IBAction func searchButtonPressed(_ sender: Any) { searchButton.isHidden = true webView.isHidden = false time = 61 updateTimer() } @IBAction func falsePressed(_ sender: Any) { nextQuestion(false, timeOut: false) } @IBAction func truePressed(_ sender: Any) { nextQuestion(true, timeOut: false) } private func nextQuestion(_ truth: Bool, timeOut: Bool) { let currentQuestion = questions.removeFirst() if(!timeOut) { //If the user pressed the search button if(searchButton.isHidden) { //Answer is correct if(currentQuestion.answer == truth) { score += 7 } else { score += 3 } } else { //Answer is correct if(currentQuestion.answer == truth) { score += 10 } } } if(questions.isEmpty) { let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popUpID") as! PopUpVC popOverVC.passedScore = score popOverVC.view.frame = self.view.frame self.view.addSubview(popOverVC.view) } else { time = 6 updateTimer() searchButton.isHidden = false webView.isHidden = true questionText.text = questions.first?.question questionCount += 1 questionNumber.text = "\(questionCount)" } } private func setQuestions() { self.questions = [ Question("US President <NAME> survived two assassination attempts in the same month", true), Question("A blue whale can weigh upwards of 400 tons", false), Question("<NAME> has announced a military partnership with Syria", true), Question("Cherophobia is the fear of fun", true), Question("The next iPhone will feature two headphones ports", false), Question("The planned National Maternity Hospital will cost €300 million", true), Question("\"an bhfuil cead agam dul go dtí an leithreas\" is the latin for \"You're eyes look beautiful in the moonlight\"", true), Question("A Filly is a female horse under the age of 5", true), Question("HBO have produced more tv series than AMC", false), Question("The national colour of Ireland is Blue", true), ] } func updateTimer() { if(time > 0) { time = time - 1 } else { nextQuestion(true, timeOut: true) time = 5 } timeRemaining.text = "\(time)" } }
09fe9f16e1a6ed03335cdb284456ff939755b957
[ "Swift" ]
2
Swift
oisinbyrne/GameWithAPurpose
ebb37d2565bdf84900ca638091ed1c816a427e38
ab8b77ea963280c6bd5a2a47db3835707df43833
refs/heads/master
<file_sep># NJDBakery Demo customer site. The NJD Bakery site is currently being used to further my development and testing skills. The site may be opened up to a real customer base in the future.<file_sep>//create nav elements $(function () { $("[rel='js-header']").after('<div id="reusable-nav" class="reusable-nav hide" rel="js-reusable-nav"></div>'); $("[rel='js-reusable-nav']").append('<div class="nav-bar" rel="js-nav-bar"></div>'); $("[rel='js-nav-bar']").append('<div class="nav-menu" rel="js-nav-menu"></div>'); $("[rel='js-nav-menu']").append('<div class="close-container"><button class="close-nav__icon" onclick="hideNav()"><i class="fas fa-times"></i></button></div>'); $("[rel='js-header']").after('<div id="search-bar__container" onclick="hideSearch()" class="search-bar hide" rel="js-search-bar"></div>'); $("[rel='js-search-bar']").append('<input type="text" name="search-input" placeholder="Search..." class="search-input">'); $("[rel='js-search-bar']").append('<button class="close-search__icon"><i class="fas fa-times"></i></button>'); generateNavLinks(); showNavForLargeViewports(); }); //set nav attributes const navLinks = [{ class: 'index', href: '/src/index/index.html', linkText: 'HOME' }, { class: 'Products', href: '/src/products/products.html', linkText: 'PRODUCTS' }, { class: 'order', href: '/src/order/order.html', linkText: 'ORDER' }, { class: 'MeetNadine', href: '/src/meet-nadine/meet-nadine.html', linkText: 'MEET NADINE' }, { class: 'IngredientInfo', href: '/src/ingredients/ingredients.html', linkText: 'INGREDIENT INFO' }, { class: 'Contact', href: '/src/contact/contact.html', linkText: 'CONTACT' }, ]; //create nav links, and add class to current page's nav link for CSS needs function generateNavLinks() { const navMenuDiv = $("[rel='js-nav-menu']"); navLinks.forEach(li => { const url = window.location.href; const currentArrayURLMatches = url.includes(li.href); navMenuDiv.append(`<a class="nav-menu__link nav-menu__link--${li.class}" href="${li.href}">${li.linkText}</a>`); if (currentArrayURLMatches) { $(`.nav-menu__link--${li.class}`).addClass('nav-menu__link--currentPage disabled'); } }) } //when the x is clicked on the mobile nav, hide the nav function hideNav() { let nav = document.getElementById('reusable-nav'); if ($(nav).hasClass('hide')) { $(nav).removeClass('hide'); } else { $(nav).addClass('hide'); } } //when the x is clicked on the search bar, hide the search bar function hideSearch() { let nav = document.getElementById('search-bar__container'); if ($(nav).hasClass('hide')) { $(nav).removeClass('hide'); } else { $(nav).addClass('hide'); } } function showNavForLargeViewports() { var viewport = document.body.clientWidth; let nav = document.getElementById('reusable-nav'); if (viewport >= 992) { if ($(nav).hasClass('hide')) { $(nav).removeClass('hide'); } } else { $(nav).addClass('hide'); } }; $(window).resize(function () { showNavForLargeViewports(); });<file_sep>$(document).ready(function () { showTopImageForLargeViewports(); hideMainLabelForLargeViewports(); showLeftColumnIngredientsForLargeViewports(); showMainHeadingForLargeViewports(); hideMiddleColumnIngredientsForLargeViewports(); populateInfo(); }); function populateDefaults(currentProduct, products) { products.forEach(product => { if (currentProduct === product.name) { //Will also populate related icon vector in 'icon' <td>'s, once Cicci gets them to me if (product.dairyFree === true) { $(`[rel='js-defaults-table']`).append(`<tr><td class="default-dairyFree__icon table__key"><img class="allergy-icon" src="/assets/allergy_icons/dairy_free.png" alt="dairy free icon"></td> <td class="default-dairyFree__text">DAIRY FREE</td></tr>`); } if (product.eggFree === true) { $(`[rel='js-defaults-table']`).append(`<tr><td class="default-eggFree__icon table__key"><img class="allergy-icon" src="/assets/allergy_icons/egg_free.png" alt="egg free icon"></td> <td class="default-eggFree__text">EGG FREE</td></tr>`); } if (product.glutenFree === true) { $(`[rel='js-defaults-table']`).append(`<tr><td class="default-glutenFree__icon table__key"><img class="allergy-icon" src="/assets/allergy_icons/gluten_free.png" alt="gluten free icon"></td> <td class="default-glutenFree__text">GLUTEN FREE</td></tr>`); } if (product.grainFree === true) { $(`[rel='js-defaults-table']`).append(`<tr><td class="default-grainFree__icon table__key"><img class="allergy-icon" src="/assets/allergy_icons/grain_free.png" alt="grain free icon"></td> <td class="default-grainFree__text">GRAIN FREE</td></tr>`); } if (product.nutFree === true) { $(`[rel='js-defaults-table']`).append(`<tr><td class="default-nutFree__icon table__key"><img class="allergy-icon" src="/assets/allergy_icons/nut_free.png" alt="nut free icon"></td> <td class="default-nutFree__text">NUT FREE</td></tr>`); } if (product.refinedSugarFree === true) { $(`[rel='js-defaults-table']`).append(`<tr><td class="default-refinedSugarFree__icon table__key"><img class="allergy-icon" src="/assets/allergy_icons/refined_sugar_free.png" alt="refined sugar free icon"></td> <td class="default-refinedSugarFree__text">REFINED SUGAR FREE</td></tr>`); } if (product.vegan === true) { $(`[rel='js-defaults-table']`).append(`<tr><td class="default-vegan__icon table__key"><img class="allergy-icon" src="/assets/allergy_icons/vegan.png" alt="vegan icon"></td> <td class="default-vegan__text">VEGAN</td></tr>`); } if (currentProduct === product.name) { return; } } }) } function populateInfo() { let str = document.title; let currentProduct = str.replace(/-/g, ' '); getParentsOnlyProducts(products => { populateDefaults(currentProduct, products); populateOptions(currentProduct, products); populateNutrition(currentProduct, products); }); } function populateNutrition(currentProduct, products) { products.forEach(product => { if (currentProduct === product.name) { //Need to add the type to the API, or pull in its category and remove plurals when necessary $(`[rel='js-nutrition-value__serving']`).html('1' + '"thing"'); $(`[rel='js-nutrition-value__batch-servings']`).html(product.defaultNumberOfServings); $(`[rel='js-nutrition-value__calories']`).html(Math.trunc(product.totalBatchCalories / product.defaultNumberOfServings) + 'g'); $(`[rel='js-nutrition-value__fat']`).html(Math.trunc(product.totalBatchFat / product.defaultNumberOfServings) + 'g'); $(`[rel='js-nutrition-value__carbs']`).html(Math.trunc(product.totalBatchCarbs / product.defaultNumberOfServings) + 'g'); $(`[rel='js-nutrition-value__fiber']`).html(Math.trunc(product.totalBatchFiber / product.defaultNumberOfServings) + 'g'); $(`[rel='js-nutrition-value__sugar']`).html(Math.trunc(product.totalBatchSugar / product.defaultNumberOfServings) + 'g'); $(`[rel='js-nutrition-value__protein']`).html(Math.trunc(product.totalBatchProtein / product.defaultNumberOfServings) + 'g'); } }) } function populateOptions(currentProduct, products) { products.forEach(product => { if (currentProduct === product.name) { //Will also populate related icon vector in 'icon' <td>'s, once Cicci gets them to me if (product.canBeDairyFree === true) { $(`[rel='js-options-table']`).append(`<tr><td class="option-dairyFree__icon table__key"><img class="allergy-icon" src="/assets/allergy_icons/dairy_free.png" alt="dairy free icon"></td> <td class="option-dairyFree__text">DAIRY FREE</td></tr>`); } if (product.canBeEggFree === true) { $(`[rel='js-options-table']`).append(`<tr><td class="option-eggFree__icon table__key"><img class="allergy-icon" src="/assets/allergy_icons/egg_free.png" alt="egg free icon"></td> <td class="option-eggFree__text">EGG FREE</td></tr>`); } if (product.canBeGlutenFree === true) { $(`[rel='js-options-table']`).append(`<tr><td class="option-glutenFree__icon table__key"><img class="allergy-icon" src="/assets/allergy_icons/gluten_free.png" alt="gluten free icon"></td><td class="option-glutenFree__text">GLUTEN FREE</td></tr>`); } if (product.canBeGrainFree === true) { $(`[rel='js-options-table']`).append(`<tr><td class="option-grainFree__icon table__key"><img class="allergy-icon" src="/assets/allergy_icons/grain_free.png" alt="grain free icon"> </td> <td class="option-grainFree__text">GRAIN FREE</td></tr>`); } if (product.canBeNutFree === true) { $(`[rel='js-options-table']`).append(`<tr><td class="option-nutFree__icon table__key"><img class="allergy-icon" src="/assets/allergy_icons/nut_free.png" alt="nut free icon"> </td> <td class="option-nutFree__text">NUT FREE</td></tr>`); } if (product.canBeRefinedSugarFree === true) { $(`[rel='js-options-table']`).append(`<tr><td class="option-refinedSugarFree__icon table__key"><img class="allergy-icon" src="/assets/allergy_icons/refined_sugar_free.png" alt="refined sugar free icon"> </td> <td class="option-refinedSugarFree__text">REFINED SUGAR FREE</td></tr>`); } if (product.canBeVegan === true) { $(`[rel='js-options-table']`).append(`<tr><td class="option-vegan__icon table__key"><img class="allergy-icon" src="/assets/allergy_icons/vegan.png" alt="vegan icon"> </td> <td class="option-vegan__text">VEGAN</td></tr>`); } if (currentProduct === product.name) { return; } } }) } function showTopImageForLargeViewports() { var viewport = document.body.clientWidth; let topImage = document.getElementById('top-image'); if (viewport >= 992) { if ($(topImage).hasClass('hide')) { $(topImage).removeClass('hide'); } } else { $(topImage).addClass('hide'); } }; function showLeftColumnIngredientsForLargeViewports() { var viewport = document.body.clientWidth; let largeIngredients = document.getElementById('lv-ingredients'); if (viewport >= 992) { if ($(largeIngredients).hasClass('hide')) { $(largeIngredients).removeClass('hide'); } } else { $(largeIngredients).addClass('hide'); } }; function showMainHeadingForLargeViewports() { var viewport = document.body.clientWidth; let mainHeading = document.getElementById('lv-heading'); if (viewport >= 992) { if ($(mainHeading).hasClass('hide')) { $(mainHeading).removeClass('hide'); } } else { $(mainHeading).addClass('hide'); } }; function hideMainLabelForLargeViewports() { var viewport = document.body.clientWidth; let mobileLabel = document.getElementById('main-image__label--mobile'); if (viewport <= 992) { if ($(mobileLabel).hasClass('hide')) { $(mobileLabel).removeClass('hide'); } } else { $(mobileLabel).addClass('hide'); } }; function hideMiddleColumnIngredientsForLargeViewports() { var viewport = document.body.clientWidth; let ingredients = document.getElementById('sv-ingredients'); if (viewport <= 992) { if ($(ingredients).hasClass('hide')) { $(ingredients).removeClass('hide'); } } else { $(ingredients).addClass('hide'); } }; $(window).resize(function () { showTopImageForLargeViewports(); hideMainLabelForLargeViewports(); showLeftColumnIngredientsForLargeViewports(); showMainHeadingForLargeViewports(); hideMiddleColumnIngredientsForLargeViewports(); });<file_sep>var allergenDefaults = ['X', 'X', 'X', 'X', 'X', 'X', 'X']; var allergenOptions = ['X', 'X', 'X', 'X', 'X', 'X', 'X']; // var allergenDetails = [{ // allergenOptionAbbreviation: 'DF', // className: 'dairyFree', // isDairyFree: 'X', // canBeDairyFree: 'X', // }, // { // allergenOptionAbbreviation: 'EF', // className: 'eggFree', // isEggFree: 'X', // canBeEggFree: 'X', // }, // { // allergenOptionAbbreviation: 'GF', // className: 'glutenFree', // isGlutenFree: 'X', // canBeGlutenFree: 'X', // }, // { // allergenOptionAbbreviation: 'GRF', // className: 'grainFree', // isGrainFree: 'X', // canBeGrainFree: 'X', // }, // { // allergenOptionAbbreviation: 'NF', // className: 'nutFree', // isNutFree: 'X', // canBeNutFree: 'X', // }, // { // allergenOptionAbbreviation: 'RSF', // className: 'refinedSugarFree', // isRefinedSugarFree: 'X', // canBeRefinedSugarFree: 'X', // }, // { // allergenOptionAbbreviation: 'V', // className: 'vegan', // isVegan: 'X', // canBeVegan: 'X', // } // ] // var allergenDetails = [{ // abbreviation: 'DF', // defaultAllergenType: product.dairyFree, // canBeAllergenType: product.canBeDairyFree, // className: 'dairyFree', // arrayIndex: 0 // }, // { // abbreviation: 'EF', // defaultAllergenType: product.eggFree, // canBeAllergenType: product.canBeEggFree, // className: 'eggFree', // arrayIndex: 1 // }, // { // abbreviation: 'GF', // defaultAllergenType: product.glutenFree, // canBeAllergenType: product.canBeGlutenFree, // className: 'glutenFree', // arrayIndex: 2 // }, // { // abbreviation: 'GRF', // defaultAllergenType: product.grainFree, // canBeAllergenType: product.canBeGrainFree, // className: 'grainFree', // arrayIndex: 3 // }, // { // abbreviation: 'NF', // defaultAllergenType: product.nutFree, // canBeAllergenType: product.canBeNutFree, // className: 'nutFree', // arrayIndex: 4 // }, // { // abbreviation: 'RSF', // defaultAllergenType: product.refinedSugarFree, // canBeAllergenType: product.canBeRefinedSugarFree, // className: 'refinedSugarFree', // arrayIndex: 5 // }, // { // abbreviation: 'V', // defaultAllergenType: product.vegan, // canBeAllergenType: product.canBeVegan, // className: 'vegan', // arrayIndex: 6 // }, // ] $(document).ready(function () { populateTables(); }); // function getDefaults(currentProduct, products, allergenDefaults) { // console.log('in getDefaults function'); // products.forEach(product => { // if (currentProduct === product.name) { // console.log('product.name', product.name); // const isDairyFree = (product.dairyFree); // allergenDefaults[0] = (product.dairyFree); // console.log('isDairyFree', isDairyFree); // const isEggFree = (product.eggFree); // allergenDefaults[1] = (product.eggFree); // console.log('isEggFree', isEggFree); // const isGlutenFree = (product.glutenFree); // allergenDefaults[2] = (product.glutenFree); // console.log('isGlutenFree', isGlutenFree); // const isGrainFree = (product.grainFree); // allergenDefaults[3] = (product.grainFree); // console.log('isGrainFree', isGrainFree); // const isNutFree = (product.nutFree); // allergenDefaults[4] = (product.nutFree); // console.log('isNutFree', isNutFree); // const isRefinedSugarFree = (product.refinedSugarFree); // allergenDefaults[5] = (product.refinedSugarFree); // console.log('isRefinedSugarFree', isRefinedSugarFree); // const isVegan = (product.vegan); // allergenDefaults[6] = (product.vegan); // console.log('isVegan', isVegan); // console.log('allergenDefaults', allergenDefaults); // if (currentProduct === product.name) { // return; // } // } // }) // } // function getOptions(currentProduct, products) { // console.log('in getOptions function'); // products.forEach(product => { // if (currentProduct === product.name) { // console.log('product.name', product.name); // const canBeDairyFree = (product.canBeDairyFree); // allergenOptions[0] = (product.canBeDairyFree); // console.log('canBeDairyFree', canBeDairyFree); // const canBeEggFree = (product.canBeEggFree); // allergenOptions[1] = (product.canBeEggFree); // console.log('canBeEggFree', canBeEggFree); // const canBeGlutenFree = (product.canBeGlutenFree); // allergenOptions[2] = (product.canBeGlutenFree); // console.log('canBeGlutenFree', canBeGlutenFree); // const canBeGrainFree = (product.canBeGrainFree); // allergenOptions[3] = (product.canBeGrainFree); // console.log('canBeGrainFree', canBeGrainFree); // const canBeNutFree = (product.canBeNutFree); // allergenOptions[4] = (product.canBeNutFree); // console.log('canBeNutFree', canBeNutFree); // const canBeRefinedSugarFree = (product.canBeRefinedSugarFree); // allergenOptions[5] = (product.canBeRefinedSugarFree); // console.log('canBeRefinedSugarFree', canBeRefinedSugarFree); // const canBeVegan = (product.canBeVegan); // allergenOptions[6] = (product.canBeVegan); // console.log('canBeVegan', canBeVegan); // console.log('allergenOptions', allergenOptions); // if (currentProduct === product.name) { // return; // } // } // }) // } // function populateInfo() { // let str = document.title; // let currentProduct = str.replace(/-/g, ' '); // console.log('currentProduct', currentProduct); // getParentsOnlyProducts(products => { // getDefaults(currentProduct, products, allergenDefaults); // getOptions(currentProduct, products, allergenOptions); // }); // } // function populateTables() { // allergenDetails.forEach(allergen => { // }) // duplicateAllergenInfo.forEach(allergenObject => { // const currentAbbreviation = allergenObject.allergenOptionAbbreviation; // allergenInfoAdditions.forEach(additionObject => { // if (additionObject.abbreviation === currentAbbreviation) { // const arrayIndex = additionObject.arrayIndex; // duplicateAllergenInfo[arrayIndex].defaultAllergenType = additionObject.defaultAllergenType; // duplicateAllergenInfo[arrayIndex].canBeAllergenType = additionObject.canBeAllergenType; // } // }) // }); // } // function populateOptions () { // } function populateTables(products, allergenInfo) { let str = document.title; let currentProduct = str.replace(/-/g, ' '); console.log('allergenInfo', allergenInfo); let duplicateAllergenInfo; $.each(products, function (key, product) { if (currentProduct === product.name) { duplicateAllergenInfo = JSON.parse(JSON.stringify(allergenInfo)); console.log('duplicateAllergenInfo', duplicateAllergenInfo); const allergenInfoAdditions = [{ abbreviation: 'DF', defaultAllergenType: product.dairyFree, canBeAllergenType: product.canBeDairyFree, arrayIndex: 0 }, { abbreviation: 'EF', defaultAllergenType: product.eggFree, canBeAllergenType: product.canBeEggFree, arrayIndex: 1 }, { abbreviation: 'GF', defaultAllergenType: product.glutenFree, canBeAllergenType: product.canBeGlutenFree, arrayIndex: 2 }, { abbreviation: 'GRF', defaultAllergenType: product.grainFree, canBeAllergenType: product.canBeGrainFree, arrayIndex: 3 }, { abbreviation: 'NF', defaultAllergenType: product.nutFree, canBeAllergenType: product.canBeNutFree, arrayIndex: 4 }, { abbreviation: 'RSF', defaultAllergenType: product.refinedSugarFree, canBeAllergenType: product.canBeRefinedSugarFree, arrayIndex: 5 }, { abbreviation: 'V', defaultAllergenType: product.vegan, canBeAllergenType: product.canBeVegan, arrayIndex: 6 }, ] //Where the abbreviation from the object in allergenInfoAdditions[] matches the abbreviation of the //current object/current iteration of the loop, add the defaultAllergenType key value pair and the //canBeAllergenType key value pair from the matching object that's in the allergenInfoAdditions array to the //current object/iteration of the duplicateAllergenInfo array duplicateAllergenInfo.forEach(allergenObject => { const currentAbbreviation = allergenObject.allergenOptionAbbreviation; allergenInfoAdditions.forEach(additionObject => { if (additionObject.abbreviation === currentAbbreviation) { const arrayIndex = additionObject.arrayIndex; duplicateAllergenInfo[arrayIndex].defaultAllergenType = additionObject.defaultAllergenType; duplicateAllergenInfo[arrayIndex].canBeAllergenType = additionObject.canBeAllergenType; } }) }); console.log('duplicateAllergenInfo', duplicateAllergenInfo); } }) }<file_sep>$(function () { $("[rel='js-body']").append('<div class="footer" rel="js-footer"></div>'); $("[rel='js-footer']").append('<div class="footer-content" rel="js-footer-content"></div>'); $("[rel='js-footer']").after('<div class="footer-copyright" rel="js-footer-copyright"></div>'); $("[rel='js-footer-copyright']").append('<p class="footer-copyright__text" rel="js-footer-copyright__text">&copy; njdbakery 2019</p>'); generateFooterLinks(); }); const footerLinks = [{ class: 'footer-content__link', href: 'index.html', linkText: 'HOME' }, { class: 'footer-content__link', href: 'Products.html', linkText: 'PRODUCTS' }, { class: 'footer-content__link', href: 'Order.html', linkText: 'ORDER' }, { class: 'footer-content__link', href: 'MeetNadine.html', linkText: 'MEET NADINE' }, { class: 'footer-content__link', href: 'IngredientInfo.html', linkText: 'INGREDIENT INFO' }, { class: 'footer-content__link', href: 'Contact.html', linkText: 'CONTACT' }, { class: 'footer-content__link', href: 'Products.html', linkText: 'COOKIES' }, { class: 'footer-content__link', href: 'Products.html', linkText: 'BITES' }, { class: 'footer-content__link', href: 'Products.html', linkText: 'BREADS' }, { class: 'footer-content__link', href: 'Products.html', linkText: 'CAKES & CUPCAKES' }, { class: 'footer-content__link', href: 'Products.html', linkText: 'DESSERT CREATIONS' }, { class: 'footer-content__link', href: 'Products.html', linkText: 'MISCELLANEOUS' }, { class: 'footer-content__link', href: 'Products.html', linkText: 'MUFFINS' }, { class: 'footer-content__link', href: 'Products.html', linkText: 'SNACK BARS' } ]; //populate footer links// function generateFooterLinks() { const footerLinksDiv = $("[rel='js-footer-content']"); footerLinks.forEach(li => { let linkToAdd = $(`<a class="${li.class}" href="${li.href}">${li.linkText}</a>`); footerLinksDiv.append(linkToAdd); }) }<file_sep>//create header elements $(function () { $("[rel='js-header']").append('<div class="logo-div" rel="js-logo-div"></div>'); $("[rel='js-logo-div']").append('<img class="logo-div__logo" src="/assets/njdBakery_Logo_2_Color_web.png" alt="njd_bakery_logo">'); $("[rel='js-header']").append('<div class="header-buttons" rel="js-header-buttons"></div>'); $("[rel='js-header-buttons']").append('<div class="search-container"><button onclick="toggleSearchBar()" class="search-icon"><i class="fas fa-search fa-3x"></i></button></div>'); $("[rel='js-header-buttons']").append('<div id="nav-button" class="nav-icon__container"><button onclick="toggleNav()" class="nav-bar__icon" rel="js-nav-bar__icon"><i class="fa fa-bars fa-3x"></i></button></div>'); }); //show/hide mobile nav on hamburger icon click function toggleNav() { let nav = document.getElementById('reusable-nav'); if ($(nav).hasClass('hide')) { $(nav).removeClass('hide'); } else { $(nav).addClass('hide'); } } function toggleSearchBar() { let nav = document.getElementById('search-bar__container'); if ($(nav).hasClass('hide')) { $(nav).removeClass('hide'); } else { $(nav).addClass('hide'); } }<file_sep>//Populate the Product Select dropdown of the default row with the Parent Products from the API $(document).ready(function () { populateProductDropdownOptions(); }); //find the 'entry' number of the last/newest created order fields row, increment by one make that the number on the next row that will be created //runs when the Add more button is clicked function addRow() { const rowNumber = findNewestRow() + 1; //remove the 'newest' class from the element that currently has it document.getElementsByClassName('newestRow')[0].classList.remove('newestRow'); const rowsContainer = "[rel='js-order-fields__rows']"; const productContainer = `[rel='js-order-form__product-field--container--${rowNumber}']`; const productRow = `[rel='js-order-fields__row--${rowNumber}']`; const removeRowSection = `[rel='js-remove-row__section--${rowNumber}']`; const leftMainBiColumn = `[rel='js-order-form__bi-column__left--${rowNumber}']`; const rightMainBiColumn = `[rel='js-order-form__bi-column__right--${rowNumber}']`; const mainQuadColumn1 = `[rel='js-order-form__quad-column1--${rowNumber}']`; const mainQuadColumn2 = `[rel='js-order-form__quad-column2--${rowNumber}']`; const mainQuadColumn3 = `[rel='js-order-form__quad-column3--${rowNumber}']`; const mainQuadColumn4 = `[rel='js-order-form__quad-column4--${rowNumber}']`; const leftQuantityBiColumn = `[rel='js-quantity__bi-column--left--${rowNumber}']`; const rightQuantityBiColumn = `[rel='js-quantity__bi-column--right--${rowNumber}']`; const quantityContainer = `[rel='js-order-form__quantity-field-container--${rowNumber}']`; const quantitySelect = `[rel='js-order-form__quantity${rowNumber}']`; const dietaryOptions = `[rel='js-order-form__dietary-options-container--${rowNumber}']`; const dietOptsQuad1 = `[rel='js-dietary-options__quad-column1--${rowNumber}']`; const dietOptsQuad2 = `[rel='js-dietary-options__quad-column2--${rowNumber}']`; const dietOptsQuad3 = `[rel='js-dietary-options__quad-column3--${rowNumber}']`; const dietOptsQuad4 = `[rel='js-dietary-options__quad-column4--${rowNumber}']`; const dietOptsDefaults = `[rel='js-dietary-options__defaults--${rowNumber}']`; //create the new elements, adding a class of 'newestRow' to the order-fields__row and a class of 'row<rowNumbervariable> to all' $(rowsContainer).append(`<div id="row${rowNumber}" class="order-fields__row order-fields__row${rowNumber} newestRow entry${rowNumber}" rel="js-order-fields__row--${rowNumber}"></div>`); $(productRow).append(`<div class="order-form__bi-column order-form__bi-column--left order-form__bi-column--left--${rowNumber}" rel="js-order-form__bi-column__left--${rowNumber}"></div>`); $(leftMainBiColumn).append(`<div class="order-form__quad-column order-form__quad-column1 order-form__quad-column1--${rowNumber}" rel="js-order-form__quad-column1--${rowNumber}"></div>`); $(mainQuadColumn1).append(`<div class="order-form__product-field--container order-form__product-field--container--${rowNumber} order-form__input" rel="js-order-form__product-field--container--${rowNumber}"></div>`); $(productContainer).append(`<select type="select" name="product" onchange="populateProductInfo(this);resetQuantity(this);updatePrice(this)" id="product${rowNumber}" class="select order-form__input order-form__product order-form__product${rowNumber} entry${rowNumber}"></select>`); $(mainQuadColumn1).append(`<div class="remove-row__section remove-row__section--${rowNumber}" rel="js-remove-row__section--${rowNumber}"></div>`); $(removeRowSection).append(`<button type="button" id="remove-row__button${rowNumber}" onclick="removeRow(this)"class="remove-row__button remove-row__button${rowNumber} entry${rowNumber} ">-</button>`); $(leftMainBiColumn).append(`<div class="order-form__quad-column order-form__quad-column2 order-form__quad-column2--${rowNumber}" rel="js-order-form__quad-column2--${rowNumber}"></div>`); $(mainQuadColumn2).append(`<div class="quantity__bi-column quantity__bi-column--left" rel="js-quantity__bi-column--left--${rowNumber}"></div>`); $(leftQuantityBiColumn).append(`<p class="order-form__servings--text order-form__servings--text${rowNumber}" rel="js-order-form__servings${rowNumber}"></p>`); $(mainQuadColumn2).append(`<div class="quantity__bi-column quantity__bi-column--right" rel="js-quantity__bi-column--right--${rowNumber}"></div>`); $(rightQuantityBiColumn).append(`<div class="order-form__quantity-field--container" rel="js-order-form__quantity-field-container--${rowNumber}"></div>`); $(quantityContainer).append(`<select type="text" name="quantity" id="quantity${rowNumber}" onchange="findRowNumber(this);updatePrice(this)" class="order-form__input order-form__quantity order-form__quantity${rowNumber} entry${rowNumber}" rel="js-order-form__quantity${rowNumber}"></select>`); $(quantitySelect).append('<option value="1" selected="selected">1 batch</option>'); $(quantitySelect).append('<option value="2">2 batches</option>'); $(quantitySelect).append('<option value="3">3 batches</option>'); $(quantitySelect).append('<option value="4">4 batches</option>'); $(quantitySelect).append('<option value="5">5 batches</option>'); $(productRow).append(`<div class="order-form__bi-column order-form__bi-column--right order-form__bi-column--right--${rowNumber}" rel="js-order-form__bi-column__right--${rowNumber}"></div>`); $(rightMainBiColumn).append(`<div class="order-form__quad-column order-form__quad-column3 order-form__quad-column3--${rowNumber}" rel="js-order-form__quad-column3--${rowNumber}"></div>`); $(mainQuadColumn3).append(`<div class="order-form__dietary-options-container" rel="js-order-form__dietary-options-container--${rowNumber}"></div>`); $(dietaryOptions).append(`<div class="dietary-options__quad-column dietary-options__quad-column1" rel="js-dietary-options__quad-column1--${rowNumber}"></div>`); $(dietOptsQuad1).append(`<input type="checkbox" name="DairyFree" value="DairyFree" class="order-form__checkbox order-form__checkbox--dairyFree${rowNumber}" rel="js-order-form__checkbox--dairyFree${rowNumber}">`); $(dietOptsQuad1).append('<label for="DiaryFree" class="input-label--checkbox input-label__dairy-free">Dairy Free</label><br>'); $(dietOptsQuad1).append(`<input type="checkbox" name="EggFree" value="EggFree" class="order-form__checkbox order-form__checkbox--eggFree${rowNumber}" rel="js-order-form__checkbox--eggFree${rowNumber}">`); $(dietOptsQuad1).append(`<label for="EggFree" class="input-label--checkbox input-label__egg-free">Egg Free</label><br>`); $(dietaryOptions).append(`<div class="dietary-options__quad-column dietary-options__quad-column2" rel="js-dietary-options__quad-column2--${rowNumber}"></div>`); $(dietOptsQuad2).append(`<input type="checkbox" name="GlutenFree" value="GlutenFree" class="order-form__checkbox order-form__checkbox--glutenFree${rowNumber}" rel="js-order-form__checkbox--glutenFree${rowNumber}" checked disabled>`); $(dietOptsQuad2).append(`<label for="GlutenFree" class="input-label--checkbox input-label__gluten-free">Gluten Free</label><br>`); $(dietOptsQuad2).append(`<input type="checkbox" name="GrainFree" value="GrainFree" class="order-form__checkbox order-form__checkbox--grainFree${rowNumber}" rel="js-order-form__checkbox--grainFree${rowNumber}">`); $(dietOptsQuad2).append(`<label for="GrainFree" class="input-label--checkbox input-label__grain-free">Grain Free</label><br>`); $(dietaryOptions).append(`<div class="dietary-options__quad-column dietary-options__quad-column3" rel="js-dietary-options__quad-column3--${rowNumber}"></div>`); $(dietOptsQuad3).append(`<input type="checkbox" name="NutFree" value="NutFree" class="order-form__checkbox order-form__checkbox--nutFree${rowNumber}" rel="js-order-form__checkbox--nutFree${rowNumber}">`); $(dietOptsQuad3).append(`<label for="NutFree" class="input-label--checkbox input-label__Nut-free">Nut Free</label><br>`); $(dietOptsQuad3).append(`<input type="checkbox" name="RefinedSugarFree" value="RefinedSugarFree" class="order-form__checkbox order-form__checkbox--refinedSugarFree${rowNumber}" rel="js-order-form__checkbox--refinedSugarFree${rowNumber}">`); $(dietOptsQuad3).append(`<label for="RefinedSugarFree" class="input-label--checkbox input-label__refined-sugar-free">Sugar Free*</label><br>`); $(dietaryOptions).append(`<div class="dietary-options__quad-column dietary-options__quad-column4" rel="js-dietary-options__quad-column4--${rowNumber}"></div>`); $(dietOptsQuad4).append(`<input type="checkbox" name="Vegan" value="Vegan" class="order-form__checkbox order-form__checkbox--vegan${rowNumber}" rel="js-order-form__checkbox--vegan${rowNumber}">`); $(dietOptsQuad4).append(`<label for="Vegan" class="input-label--checkbox input-label__vegan">Vegan</label><br>`); $(dietaryOptions).append(`<div class="dietary-options__defaults dietary-options__defaults--${rowNumber}" rel="js-dietary-options__defaults--${rowNumber}">`); $(dietOptsDefaults).append(`<p class="dietary-options__defaults-text dietary-options__defaults-text${rowNumber}" rel="js-dietary-options__defaults-text${rowNumber}"></p>`); $(rightMainBiColumn).append(`<div class="order-form__quad-column order-form__quad-column4 order-form__quad-column4--${rowNumber}" rel="js-order-form__quad-column4--${rowNumber}"></div>`); $(mainQuadColumn4).append(`<p class="order-form__price--text order-form__price--text${rowNumber} generated disabled" rel="js-order-form__price${rowNumber}"></p>`); populateProductDropdownOptions(rowNumber); //hide or show Remove Row button and label depending on if there is more than one row showing const numberOfChildren = $('.order-fields__rows > div').length; if (numberOfChildren > 2) { const removeRowButton = document.getElementsByClassName('remove-row__button')[0]; removeRowButton.classList.add('noVisibility'); const removeRowLabel = document.getElementsByClassName('input-label__remove-row')[0]; removeRowButton.classList.remove('noVisibility'); removeRowLabel.classList.remove('noVisibility'); } } //Updates the subtotal at the bottom of the form whenever the price of any row changes //Called by updatePrice() and removeRow() function calculateSubtotal() { const priceArray = document.querySelectorAll('.order-form__price--text'); const prices = []; priceArray.forEach(price => { const rowPrice = price.innerHTML; // const prices = []; prices.push(rowPrice); }); let sum = 0; for (var i = 0; i < prices.length; i++) { const priceString = prices[i].slice(1); sum += +priceString; } $(`[rel='js-order-form__subtotal']`).html('$' + sum); } //Disable check boxes for dietary options that are not available on the current product function disableUnavailableOptions(className, availableOption, currentId) { const currentRowNumber = findRowNumber(currentId); if (!availableOption) { const neededClass = `.order-form__checkbox--${className}${currentRowNumber}`; $(neededClass).attr('disabled', true); } } function findCurrentBatchInfo(products, currentRowNumber, currentProduct) { products.forEach(product => { if (currentProduct === product.name) { const currentProductBatchPrice = (product.batchPrice); const currentQuantityDropdownClass = '.order-form__quantity' + currentRowNumber; const currentBatchSelection = $(`${currentQuantityDropdownClass} option:selected`).val(); const pricePerRow = currentBatchSelection * currentProductBatchPrice; $(`[rel='js-order-form__price${currentRowNumber}']`).html('$' + pricePerRow); $(`[rel='js-order-form__servings${currentRowNumber}']`).html(product.defaultNumberOfServings); } }) } //Finds the row number on the row that was most recently created function findNewestRow() { //find the element with 'newest' class on it and look through its classes for the one that contains 'entry' const classList = document.getElementsByClassName('newestRow')[0].className.split(/\s+/); const neededClass = classList.find(function (nameOfClass) { return nameOfClass.includes('entry'); }) //convert the string to a number and remove the first five characters from the string, set a variable to whatever is left const rowNumber = parseInt(neededClass.substring(5), 10); return rowNumber; } //Find the row number that the clicked element is in function findRowNumber(currentId) { const idOnDiv = $(currentId).closest('.order-fields__row').attr('id'); const currentRowNumber = (idOnDiv.substring(3)); return currentRowNumber; } function findSelectedProduct(currentId) { const currentRowNumber = findRowNumber(currentId); const currentDropdownClass = '.order-form__product' + currentRowNumber; const currentProduct = $(`${currentDropdownClass} option:selected`).text(); return currentProduct; } //Calls functions in a specific order to populate the Product dropdown with a list of parent products from the API function populateProductDropdownOptions(rowNumber) { let dropdown = prepProductDropdown(rowNumber); getParentsOnlyProducts(parentProducts => { setProductDropdown(parentProducts, dropdown) }); } //populates the default allergen info and the available options function populateProductInfo(currentId) { uncheckAllOptions(currentId); getParentsOnlyProducts(products => { updateAllergenInfoArray(products, allergenInfo, currentId, updateDefaultOptionsText); }); } //Prepares the current product dropdown for API population function prepProductDropdown(rowNumber) { if (!rowNumber) { rowNumber = findNewestRow(); } const specificDropdown = `.order-form__product${rowNumber}`; const dropdown = $(specificDropdown); dropdown.empty(); dropdown.append('<option selected="true" disabled>Select...</option>'); dropdown.prop('selectedIndex', 0); return dropdown; } //If a remove row button is clicked, remove all fields in that row and set the previous row to the 'newest' row. If only one row remains, hide the remove option. function removeRow(currentId) { const currentRowNumber = findRowNumber(currentId); const rowNumberMinusOne = parseInt(currentRowNumber) - 1; const rowToAddClassTo = 'order-fields__row' + rowNumberMinusOne; const rowToRemove = 'order-fields__row' + currentRowNumber; //determine if the row that's going to be deleted has the 'newestRow' class on it const classListOfRowToFind = document.getElementsByClassName(rowToRemove)[0].className.split(/\s+/); if ((classListOfRowToFind.includes)('newestRow')) { //if it does, remove that row. Then find the row that was right before it and add the 'newestRow' class to it $(`.${rowToRemove}`).remove(); $(`.${rowToAddClassTo}`).addClass('newestRow'); } else { $(`.${rowToRemove}`).remove(); } //If only one row of fields remains, hide the remove button and label const numberOfChildren = $('.order-fields__rows > div').length; if (numberOfChildren === 2) { const removeRowButton = document.getElementsByClassName('remove-row__button')[0]; removeRowButton.classList.add('noVisibility'); const removeRowLabel = document.getElementsByClassName('input-label__remove-row')[0]; removeRowLabel.classList.add('noVisibility'); } calculateSubtotal(); } //Reset Quantity field to default option when the Product selection changes, then recalculate the price. THe callback function is defined in the onchange in the html function resetQuantity(currentId) { const currentQuantity = 'quantity' + findRowNumber(currentId); $('#' + currentQuantity).val('1'); } //Check/enable the boxes of the default options function setCheckboxAttributes(currentId, className, defaultAllergenType) { const currentRowNumber = findRowNumber(currentId); const neededClass = `.order-form__checkbox--${className}${currentRowNumber}`; $(neededClass).prop('checked', defaultAllergenType); $(neededClass).prop('disabled', defaultAllergenType); } //TODO: add validation to Pickup/Delivery date field function setNeededDateMin(currentID) { const minDate = moment().add(10, 'days').calendar(); document.getElementById('neededDate').min = minDate; // $(`[rel='js-order-fields__needed-date']`).moment({ // minDate: minDate // }); //$(`[rel='js-order-fields__needed-date']`).attr(min, minDate); } //Populates the current product dropdown with parent products that were retrieved from the API function setProductDropdown(products, dropdown) { $.each(products, (key, product) => { dropdown.append($('<option></option>').text(product.name)); }) } //When a new product is chosen in a row that already had products chosen, uncheck any dietary options the user checked in that row function uncheckAllOptions(currentId) { const currentRowNumber = findRowNumber(currentId); allergenInfo.forEach(allergenObject => { const neededClass = `.order-form__checkbox--${allergenObject.className}${currentRowNumber}`; $(neededClass).prop('checked', false); }); } function updateAllergenInfoArray(products, allergenInfo, currentId, updateDefaultOptionsText) { let currentProduct = findSelectedProduct(currentId); let duplicateAllergenInfo; $.each(products, function (key, product) { if (currentProduct === product.name) { duplicateAllergenInfo = JSON.parse(JSON.stringify(allergenInfo)); const allergenInfoAdditions = [{ abbreviation: 'DF', defaultAllergenType: product.dairyFree, canBeAllergenType: product.canBeDairyFree, arrayIndex: 0 }, { abbreviation: 'EF', defaultAllergenType: product.eggFree, canBeAllergenType: product.canBeEggFree, arrayIndex: 1 }, { abbreviation: 'GF', defaultAllergenType: product.glutenFree, canBeAllergenType: product.canBeGlutenFree, arrayIndex: 2 }, { abbreviation: 'GRF', defaultAllergenType: product.grainFree, canBeAllergenType: product.canBeGrainFree, arrayIndex: 3 }, { abbreviation: 'NF', defaultAllergenType: product.nutFree, canBeAllergenType: product.canBeNutFree, arrayIndex: 4 }, { abbreviation: 'RSF', defaultAllergenType: product.refinedSugarFree, canBeAllergenType: product.canBeRefinedSugarFree, arrayIndex: 5 }, { abbreviation: 'V', defaultAllergenType: product.vegan, canBeAllergenType: product.canBeVegan, arrayIndex: 6 }, ] //Where the abbreviation from the object in allergenInfoAdditions[] matches the abbreviation of the //current object/current iteration of the loop, add the defaultAllergenType key value pair and the //canBeAllergenType key value pair from the matching object that's in the allergenInfoAdditions array to the //current object/iteration of the duplicateAllergenInfo array duplicateAllergenInfo.forEach(allergenObject => { const currentAbbreviation = allergenObject.allergenOptionAbbreviation; allergenInfoAdditions.forEach(additionObject => { if (additionObject.abbreviation === currentAbbreviation) { const arrayIndex = additionObject.arrayIndex; duplicateAllergenInfo[arrayIndex].defaultAllergenType = additionObject.defaultAllergenType; duplicateAllergenInfo[arrayIndex].canBeAllergenType = additionObject.canBeAllergenType; } }) }); } }) updateDefaultOptionsText(duplicateAllergenInfo, currentId); duplicateAllergenInfo.forEach(option => { disableUnavailableOptions(option.className, option.canBeAllergenType, currentId); }) duplicateAllergenInfo.forEach(option => { setCheckboxAttributes(currentId, option.className, option.defaultAllergenType); }) } //Update the text under the options so it shows the abbreviations of the what the default options are on that product function updateDefaultOptionsText(duplicateAllergenInfo, currentId) { let defaultOptionsText = 'Default product is: '; const currentRowNumber = findRowNumber(currentId); duplicateAllergenInfo.forEach(option => { if (option.defaultAllergenType) { defaultOptionsText = defaultOptionsText + ' ' + option.allergenOptionAbbreviation; } }) $(`[rel='js-dietary-options__defaults-text${currentRowNumber}']`).html(defaultOptionsText); } //Trigged by onchange on the Product field function updatePrice(currentId, rowNumber) { let currentRowNumber = findRowNumber(currentId); let currentProduct = findSelectedProduct(currentId); getParentsOnlyProducts(products => { findCurrentBatchInfo(products, currentRowNumber, currentProduct); calculateSubtotal(); }); } //Triggered by onchange on the email field function validateEmailAddress() { const emailInput = document.getElementById("email").value; console.log('emailInput', emailInput); console.log('in validateEmailAddress function'); if (emailInput.match(/\S+@\S+\.\S+/)) { document.getElementById("email").className = document.getElementById("email").className.replace(" error", ""); } else { document.getElementById("email").className = document.getElementById("email").className + " error"; alert('Please enter a valid email address.'); } }<file_sep>function getParentsOnlyProducts(callback) { const url = 'http://localhost:56886/api/products?parentsOnly=true'; $.getJSON(url, callback) } <file_sep>const allergenInfo = [{ allergenOptionAbbreviation: 'DF', className: 'dairyFree', }, { allergenOptionAbbreviation: 'EF', className: 'eggFree', }, { allergenOptionAbbreviation: 'GF', className: 'glutenFree', }, { allergenOptionAbbreviation: 'GRF', className: 'grainFree', }, { allergenOptionAbbreviation: 'NF', className: 'nutFree', }, { allergenOptionAbbreviation: 'RSF', className: 'refinedSugarFree', }, { allergenOptionAbbreviation: 'V', className: 'vegan', } ]
35653084e04d4730574d616f626d54a21ab088f1
[ "Markdown", "JavaScript" ]
9
Markdown
doudsnj/NJDBakery
4670005f232cd60f5ff2fc0b99b3ff28b850123c
6cefc69804df4429fd331a1f7debbd53088733b2
refs/heads/master
<file_sep><?php namespace Helmich\TypoScriptParser\Tokenizer; interface TokenizerInterface { /** * @param string $inputString * @return \Helmich\TypoScriptParser\Tokenizer\TokenInterface[] */ public function tokenizeString($inputString); /** * @param string $inputStream * @return \Helmich\TypoScriptParser\Tokenizer\TokenInterface[] */ public function tokenizeStream($inputStream); }<file_sep><?php namespace Helmich\TypoScriptParser\Parser\AST; /** * An object path. * * @package Helmich\TypoScriptParser * @subpackage Parser\AST */ class ObjectPath { /** * The relative object path, as specified in the source code. * @var string */ public $relativeName; /** * The absolute object path, as evaluated from parent nested statements. * @var */ public $absoluteName; /** * Constructs a new object path. * * @param string $absoluteName The absolute object path. * @param string $relativeName The relative object path. */ public function __construct($absoluteName, $relativeName) { $this->absoluteName = $absoluteName; $this->relativeName = $relativeName; } }<file_sep><?php namespace Helmich\TypoScriptParser\Parser; use Helmich\TypoScriptParser\Parser\AST\ConditionalStatement; use Helmich\TypoScriptParser\Parser\AST\DirectoryIncludeStatement; use Helmich\TypoScriptParser\Parser\AST\FileIncludeStatement; use Helmich\TypoScriptParser\Parser\AST\NestedAssignment; use Helmich\TypoScriptParser\Parser\AST\ObjectPath; use Helmich\TypoScriptParser\Parser\AST\Operator\Assignment; use Helmich\TypoScriptParser\Parser\AST\Operator\Copy; use Helmich\TypoScriptParser\Parser\AST\Operator\Delete; use Helmich\TypoScriptParser\Parser\AST\Operator\Modification; use Helmich\TypoScriptParser\Parser\AST\Operator\ModificationCall; use Helmich\TypoScriptParser\Parser\AST\Operator\ObjectCreation; use Helmich\TypoScriptParser\Parser\AST\Operator\Reference; use Helmich\TypoScriptParser\Parser\AST\Scalar; use Helmich\TypoScriptParser\Tokenizer\Token; use Helmich\TypoScriptParser\Tokenizer\TokenInterface; use Helmich\TypoScriptParser\Tokenizer\Tokenizer; use Helmich\TypoScriptParser\Tokenizer\TokenizerInterface; class Parser implements ParserInterface { /** @var \Helmich\TypoScriptParser\Tokenizer\TokenizerInterface */ private $tokenizer; public function __construct(TokenizerInterface $tokenizer) { $this->tokenizer = $tokenizer; } /** * Parses a stream resource. * * This can be any kind of stream supported by PHP (e.g. a filename or a URL). * * @param string $stream The stream resource. * @return \Helmich\TypoScriptParser\Parser\AST\Statement[] The syntax tree. */ public function parseStream($stream) { $content = file_get_contents($stream); return $this->parseString($content); } /** * Parses a TypoScript string. * * @param string $content The string to parse. * @return \Helmich\TypoScriptParser\Parser\AST\Statement[] The syntax tree. */ public function parseString($content) { $tokens = $this->tokenizer->tokenizeString($content); return $this->parseTokens($tokens); } /** * Parses a token stream. * * @param \Helmich\TypoScriptParser\Tokenizer\TokenInterface[] $tokens The token stream to parse. * @return \Helmich\TypoScriptParser\Parser\AST\Statement[] The syntax tree. */ public function parseTokens(array $tokens) { $statements = []; $tokens = $this->filterTokenStream($tokens); $count = count($tokens); for ($i = 0; $i < $count; $i++) { if ($tokens[$i]->getType() === TokenInterface::TYPE_OBJECT_IDENTIFIER) { $objectPath = new ObjectPath($tokens[$i]->getValue(), $tokens[$i]->getValue()); if ($tokens[$i + 1]->getType() === TokenInterface::TYPE_BRACE_OPEN) { $i += 2; $statements[] = $this->parseNestedStatements($objectPath, $tokens, $i, $tokens[$i]->getLine()); } } $this->parseToken($tokens, $i, $statements, NULL); } return $statements; } /** * @param \Helmich\TypoScriptParser\Parser\AST\ObjectPath $parentObject * @param \Helmich\TypoScriptParser\Tokenizer\TokenInterface[] $tokens * @param $i * @param int $startLine * @throws ParseError * @return \Helmich\TypoScriptParser\Parser\AST\NestedAssignment */ private function parseNestedStatements(ObjectPath $parentObject, array $tokens, &$i, $startLine) { $statements = []; $count = count($tokens); for (; $i < $count; $i++) { if ($tokens[$i]->getType() === TokenInterface::TYPE_OBJECT_IDENTIFIER) { $objectPath = new ObjectPath($parentObject->absoluteName . '.' . $tokens[$i]->getValue(), $tokens[$i]->getValue()); if ($tokens[$i + 1]->getType() === TokenInterface::TYPE_BRACE_OPEN) { $i += 2; $statements[] = $this->parseNestedStatements($objectPath, $tokens, $i, $tokens[$i]->getLine()); continue; } } $this->parseToken($tokens, $i, $statements, $parentObject); if ($tokens[$i]->getType() === TokenInterface::TYPE_BRACE_CLOSE) { $statement = new NestedAssignment($parentObject, $statements, $startLine); $i++; return $statement; } } throw new ParseError('Unterminated nested statement!'); } /** * @param \Helmich\TypoScriptParser\Parser\AST\ObjectPath $context * @param \Helmich\TypoScriptParser\Tokenizer\TokenInterface[] $tokens * @param int $i * @param \Helmich\TypoScriptParser\Parser\AST\Statement[] $statements * @throws ParseError * @return \Helmich\TypoScriptParser\Parser\AST\NestedAssignment */ private function parseToken(array $tokens, &$i, array &$statements, ObjectPath $context = NULL) { if ($tokens[$i]->getType() === TokenInterface::TYPE_OBJECT_IDENTIFIER) { $objectPath = $context ? new ObjectPath($context->absoluteName . '.' . $tokens[$i]->getValue(), $tokens[$i]->getValue()) : new ObjectPath($tokens[$i]->getValue(), $tokens[$i]->getValue()); if ($tokens[$i + 1]->getType() === TokenInterface::TYPE_OPERATOR_ASSIGNMENT) { if ($tokens[$i + 2]->getType() === TokenInterface::TYPE_OBJECT_CONSTRUCTOR) { $statements[] = new ObjectCreation($objectPath, new Scalar($tokens[$i + 2]->getValue()), $tokens[$i + 2]->getLine()); $i += 2; } elseif ($tokens[$i + 2]->getType() === TokenInterface::TYPE_RIGHTVALUE) { $statements[] = new Assignment($objectPath, new Scalar($tokens[$i + 2]->getValue()), $tokens[$i + 2]->getLine()); $i += 2; } elseif ($tokens[$i + 2]->getType() === TokenInterface::TYPE_WHITESPACE) { $statements[] = new Assignment($objectPath, new Scalar(''), $tokens[$i]->getLine()); $i += 1; } } else if ($tokens[$i + 1]->getType() === TokenInterface::TYPE_OPERATOR_COPY || $tokens[$i + 1]->getType() === TokenInterface::TYPE_OPERATOR_REFERENCE ) { $targetToken = $tokens[$i + 2]; $this->validateCopyOperatorRightValue($targetToken); if ($targetToken->getValue()[0] === '.') { $absolutePath = $context ? "{$context->absoluteName}{$targetToken->getValue()}" : $targetToken->getValue(); } else { $absolutePath = $targetToken->getValue(); } $target = new ObjectPath($absolutePath, $targetToken->getValue()); if ($tokens[$i + 1]->getType() === TokenInterface::TYPE_OPERATOR_COPY) { $statements[] = new Copy($objectPath, $target, $tokens[$i + 1]->getLine()); } else { $statements[] = new Reference($objectPath, $target, $tokens[$i + 1]->getLine()); } $i += 2; } else if ($tokens[$i + 1]->getType() === TokenInterface::TYPE_OPERATOR_MODIFY) { $this->validateModifyOperatorRightValue($tokens[$i + 2]); preg_match(Tokenizer::TOKEN_OBJECT_MODIFIER, $tokens[$i + 2]->getValue(), $matches); $call = new ModificationCall($matches['name'], $matches['arguments']); $statements[] = new Modification($objectPath, $call, $tokens[$i + 2]->getLine()); $i += 2; } else if ($tokens[$i + 1]->getType() === TokenInterface::TYPE_OPERATOR_DELETE) { if ($tokens[$i + 2]->getType() !== TokenInterface::TYPE_WHITESPACE) { throw new ParseError( 'Unexpected token ' . $tokens[$i + 2]->getType() . ' after delete operator (expected line break).', 1403011201, $tokens[$i]->getLine() ); } $statements[] = new Delete($objectPath, $tokens[$i + 1]->getLine()); $i += 1; } else if ($tokens[$i + 1]->getType() === TokenInterface::TYPE_RIGHTVALUE_MULTILINE) { $statements[] = new Assignment($objectPath, new Scalar($tokens[$i + 1]->getValue()), $tokens[$i + 1]->getLine()); $i += 1; } } else if ($tokens[$i]->getType() === TokenInterface::TYPE_CONDITION) { if ($context !== NULL) { throw new ParseError( 'Found condition statement inside nested assignment.', 1403011203, $tokens[$i]->getLine() ); } $count = count($tokens); $ifStatements = []; $elseStatements = []; $condition = $tokens[$i]->getValue(); $conditionLine = $tokens[$i]->getLine(); $inElseBranch = FALSE; for ($i++; $i < $count; $i++) { if ($tokens[$i]->getType() === TokenInterface::TYPE_CONDITION_END) { $statements[] = new ConditionalStatement($condition, $ifStatements, $elseStatements, $conditionLine); $i++; break; } elseif ($tokens[$i]->getType() === TokenInterface::TYPE_CONDITION_ELSE) { if ($inElseBranch) { throw new ParseError( sprintf('Duplicate else in conditional statement in line %d.', $tokens[$i]->getLine()), 1403011203, $tokens[$i]->getLine() ); } $inElseBranch = TRUE; $i++; } if ($tokens[$i]->getType() === TokenInterface::TYPE_OBJECT_IDENTIFIER) { $objectPath = new ObjectPath($tokens[$i]->getValue(), $tokens[$i]->getValue()); if ($tokens[$i + 1]->getType() === TokenInterface::TYPE_BRACE_OPEN) { $i += 2; if ($inElseBranch) { $elseStatements[] = $this->parseNestedStatements($objectPath, $tokens, $i, $tokens[$i + 1]->getLine()); } else { $ifStatements[] = $this->parseNestedStatements($objectPath, $tokens, $i, $tokens[$i + 1]->getLine()); } } } if ($inElseBranch) { $this->parseToken($tokens, $i, $elseStatements, NULL); } else { $this->parseToken($tokens, $i, $ifStatements, NULL); } } } else if ($tokens[$i]->getType() === TokenInterface::TYPE_INCLUDE) { preg_match(Tokenizer::TOKEN_INCLUDE_STATEMENT, $tokens[$i]->getValue(), $matches); if ($matches['type'] === 'FILE') { $statements[] = new FileIncludeStatement($matches['filename'], $tokens[$i]->getLine()); } else { $statements[] = new DirectoryIncludeStatement( $matches['filename'], isset($matches['extension']) ? $matches['extension'] : NULL, $tokens[$i]->getLine() ); } } else if ($tokens[$i]->getType() === TokenInterface::TYPE_WHITESPACE) { // Pass } else if ($tokens[$i]->getType() === TokenInterface::TYPE_BRACE_CLOSE) { if ($context === NULL) { throw new ParseError( sprintf( 'Unexpected token %s when not in nested assignment in line %d.', $tokens[$i]->getType(), $tokens[$i]->getLine() ), 1403011203, $tokens[$i]->getLine() ); } } else { throw new ParseError( sprintf('Unexpected token %s in line %d.', $tokens[$i]->getType(), $tokens[$i]->getLine()), 1403011202, $tokens[$i]->getLine() ); } } private function validateModifyOperatorRightValue(TokenInterface $token) { if ($token->getType() !== TokenInterface::TYPE_RIGHTVALUE) { throw new ParseError( 'Unexpected token ' . $token->getType() . ' after modify operator.', 1403010294, $token->getLine() ); } if (!preg_match(Tokenizer::TOKEN_OBJECT_MODIFIER, $token->getValue())) { throw new ParseError( 'Right side of modify operator does not look like a modifier: "' . $token->getValue() . '".', 1403010700, $token->getLine() ); } } private function validateCopyOperatorRightValue(TokenInterface $token) { if ($token->getType() !== TokenInterface::TYPE_RIGHTVALUE) { throw new ParseError( 'Unexpected token ' . $token->getType() . ' after copy operator.', 1403010294, $token->getLine() ); } if (!preg_match(Tokenizer::TOKEN_OBJECT_REFERENCE, $token->getValue())) { throw new ParseError( 'Right side of copy operator does not look like an object path: "' . $token->getValue() . '".', 1403010699, $token->getLine() ); } } /** * @param \Helmich\TypoScriptParser\Tokenizer\TokenInterface[] $tokens * @return \Helmich\TypoScriptParser\Tokenizer\TokenInterface[] */ private function filterTokenStream($tokens) { $filteredTokens = []; $ignoredTokens = [ TokenInterface::TYPE_COMMENT_MULTILINE, TokenInterface::TYPE_COMMENT_ONELINE ]; $maxLine = 0; foreach ($tokens as $token) { $maxLine = max($token->getLine(), $maxLine); // Trim unnecessary whitespace, but leave line breaks! These are important! if ($token->getType() === TokenInterface::TYPE_WHITESPACE) { $value = trim($token->getValue(), "\t "); if (strlen($value) > 0) { $filteredTokens[] = new Token( TokenInterface::TYPE_WHITESPACE, $value, $token->getLine() ); } } elseif (!in_array($token->getType(), $ignoredTokens)) { $filteredTokens[] = $token; } } // Add two linebreak tokens; during parsing, we usually do not look more than two // tokens ahead; this hack ensures that there will always be at least two more tokens // present and we do not have to check whether these tokens exists. $filteredTokens[] = new Token(TokenInterface::TYPE_WHITESPACE, "\n", $maxLine + 1); $filteredTokens[] = new Token(TokenInterface::TYPE_WHITESPACE, "\n", $maxLine + 2); return $filteredTokens; } }<file_sep><?php namespace Helmich\TypoScriptParser\Parser\Traverser; use Helmich\TypoScriptParser\Parser\AST\ConditionalStatement; use Helmich\TypoScriptParser\Parser\AST\NestedAssignment; class Traverser { /** * @var \Helmich\TypoScriptParser\Parser\AST\Statement[] */ private $statements; /** @var \Helmich\TypoScriptParser\Parser\Traverser\AggregatingVisitor */ private $visitors; /** * @param \Helmich\TypoScriptParser\Parser\AST\Statement[] $statements */ public function __construct(array $statements) { $this->statements = $statements; $this->visitors = new AggregatingVisitor(); } /** * @param \Helmich\TypoScriptParser\Parser\Traverser\Visitor $visitor */ public function addVisitor(Visitor $visitor) { $this->visitors->addVisitor($visitor); } public function walk() { $this->visitors->enterTree($this->statements); $this->walkRecursive($this->statements); $this->visitors->exitTree($this->statements); } /** * @param \Helmich\TypoScriptParser\Parser\AST\Statement[] $statements * @return \Helmich\TypoScriptParser\Parser\AST\Statement[] */ private function walkRecursive(array $statements) { foreach ($statements as $key => $statement) { $this->visitors->enterNode($statement); if ($statement instanceof NestedAssignment) { $statement->statements = $this->walkRecursive($statement->statements); } else if ($statement instanceof ConditionalStatement) { $statement->ifStatements = $this->walkRecursive($statement->ifStatements); $statement->elseStatements = $this->walkRecursive($statement->elseStatements); } $this->visitors->exitNode($statement); } return $statements; } }<file_sep><?php namespace Helmich\TypoScriptParser\Parser\Traverser; use Helmich\TypoScriptParser\Parser\AST\Statement; class AggregatingVisitor implements Visitor { /** @var \Helmich\TypoScriptParser\Parser\Traverser\Visitor[] */ private $visitors = []; public function addVisitor(Visitor $visitor) { $this->visitors[spl_object_hash($visitor)] = $visitor; } public function enterTree(array $statements) { foreach ($this->visitors as $visitor) { $visitor->enterTree($statements); } } public function enterNode(Statement $statement) { foreach ($this->visitors as $visitor) { $visitor->enterNode($statement); } } public function exitNode(Statement $statement) { foreach ($this->visitors as $visitor) { $visitor->exitNode($statement); } } public function exitTree(array $statements) { foreach ($this->visitors as $visitor) { $visitor->exitTree($statements); } } }<file_sep><?php namespace Helmich\TypoScriptParser\Tokenizer; class Tokenizer implements TokenizerInterface { const TOKEN_WHITESPACE = ',^[ \t\n]+,s'; const TOKEN_COMMENT_ONELINE = ',^(#|/)[^\n]*,'; const TOKEN_COMMENT_MULTILINE_BEGIN = ',^/\*,'; const TOKEN_COMMENT_MULTILINE_END = ',^\*/,'; const TOKEN_CONDITION = ',^(\[(browser|version|system|device|useragent|language|IP|hostname|applicationContext|hour|minute|month|year|dayofweek|dayofmonth|dayofyear|usergroup|loginUser|page\|[a-zA-Z0-9_]+|treeLevel|PIDinRootline|PIDupinRootline|compatVersion|globalVar|globalString|userFunc)\s*=\s(.*?)\](\|\||&&|$))+,'; const TOKEN_CONDITION_ELSE = ',^\[else\],i'; const TOKEN_CONDITION_END = ',^\[(global|end)\],i'; const TOKEN_OBJECT_NAME = ',^(CASE|CLEARGIF|COA(?:_INT)?|COBJ_ARRAY|COLUMNS|CTABLE|EDITPANEL|FILES?|FLUIDTEMPLATE|FORM|HMENU|HRULER|IMAGE|IMG_RESOURCE|IMGTEXT|LOAD_REGISTER|MEDIA|MULTIMEDIA|OTABLE|QTOBJECT|RECORDS|RESTORE_REGISTER|SEARCHRESULT|SVG|SWFOBJECT|TEMPLATE|USER(?:_INT)?|GIFBUILDER|[GT]MENU(?:_LAYERS)?|(?:G|T|JS|IMG)MENUITEM)$,'; const TOKEN_OBJECT_ACCESSOR = ',^([a-zA-Z0-9_\-]+(?:\.[a-zA-Z0-9_\-]+)*)$,'; const TOKEN_OBJECT_REFERENCE = ',^\.?([a-zA-Z0-9_\-]+(?:\.[a-zA-Z0-9_\-]+)*)$,'; const TOKEN_NESTING_START = ',^\{$,'; const TOKEN_NESTING_END = ',^\}$,'; const TOKEN_OBJECT_MODIFIER = ',^ (?<name>[a-zA-Z0-9]+) # Modifier name (?:\s)* \( (?<arguments>[^\)]*) # Argument list \) $,x'; const TOKEN_OPERATOR_LINE = ',^ ([a-zA-Z0-9_\-]+(?:\.[a-zA-Z0-9_\-]+)*) # Left value (object accessor) (\s*) # Whitespace (=|:=|<=|<|>|\{|\() # Operator (\s*) # More whitespace (.*) # Right value (\s*) # Trailing whitespace $,x'; const TOKEN_INCLUDE_STATEMENT = ',^ <INCLUDE_TYPOSCRIPT:\s+ source="(?<type>FILE|DIR):(?<filename>[^"]+)" (?:\s+extension="(?<extension>[^"]+)")? \s*> $,x'; /** * @param string $inputString * @throws \Helmich\TypoScriptParser\Tokenizer\TokenizerException * @return \Helmich\TypoScriptParser\Tokenizer\TokenInterface[] */ public function tokenizeString($inputString) { $inputString = $this->preprocessContent($inputString); $tokens = []; $currentTokenType = NULL; $currentTokenValue = ''; $lines = explode("\n", $inputString); $currentLine = 0; foreach ($lines as $line) { $currentLine++; if ($currentTokenType === TokenInterface::TYPE_COMMENT_MULTILINE) { if (preg_match(self::TOKEN_WHITESPACE, $line, $matches)) { $currentTokenValue .= $matches[0]; $line = substr($line, strlen($matches[0])); } if (preg_match(self::TOKEN_COMMENT_MULTILINE_END, $line, $matches)) { $currentTokenValue .= $matches[0]; $tokens[] = new Token(TokenInterface::TYPE_COMMENT_MULTILINE, $currentTokenValue, $currentLine); $currentTokenValue = NULL; $currentTokenType = NULL; } else { $currentTokenValue .= $line; } continue; } elseif ($currentTokenType === TokenInterface::TYPE_RIGHTVALUE_MULTILINE) { if (preg_match(',^\s*\),', $line, $matches)) { $tokens[] = new Token(TokenInterface::TYPE_RIGHTVALUE_MULTILINE, $currentTokenValue . $matches[0], $currentLine); $currentTokenValue = NULL; $currentTokenType = NULL; } else { $currentTokenValue .= $line . "\n"; } continue; } if (count($tokens) !== 0) { $tokens[] = new Token(TokenInterface::TYPE_WHITESPACE, "\n", $currentLine - 1); } if (preg_match(self::TOKEN_WHITESPACE, $line, $matches)) { $tokens[] = new Token(TokenInterface::TYPE_WHITESPACE, $matches[0], $currentLine); $line = substr($line, strlen($matches[0])); } if (preg_match(self::TOKEN_COMMENT_MULTILINE_BEGIN, $line, $matches)) { $currentTokenValue = $line; $currentTokenType = TokenInterface::TYPE_COMMENT_MULTILINE; continue; } $simpleTokens = [ self::TOKEN_COMMENT_ONELINE => TokenInterface::TYPE_COMMENT_ONELINE, self::TOKEN_NESTING_END => TokenInterface::TYPE_BRACE_CLOSE, self::TOKEN_CONDITION => TokenInterface::TYPE_CONDITION, self::TOKEN_CONDITION_ELSE => TokenInterface::TYPE_CONDITION_ELSE, self::TOKEN_CONDITION_END => TokenInterface::TYPE_CONDITION_END, self::TOKEN_INCLUDE_STATEMENT => TokenInterface::TYPE_INCLUDE, ]; foreach ($simpleTokens as $pattern => $type) { if (preg_match($pattern, $line, $matches)) { $tokens[] = new Token($type, $matches[0], $currentLine); continue 2; } } if (preg_match(self::TOKEN_OPERATOR_LINE, $line, $matches)) { $tokens[] = new Token(TokenInterface::TYPE_OBJECT_IDENTIFIER, $matches[1], $currentLine); if ($matches[2]) { $tokens[] = new Token(TokenInterface::TYPE_WHITESPACE, $matches[2], $currentLine); } switch ($matches[3]) { case '=': case ':=': case '<': case '<=': case '>': try { $tokens[] = new Token($this->getTokenTypeForBinaryOperator($matches[3]), $matches[3], $currentLine); } catch (UnknownOperatorException $exception) { throw new TokenizerException($exception->getMessage(), 1403084548, $exception, $currentLine); } if ($matches[4]) { $tokens[] = new Token(TokenInterface::TYPE_WHITESPACE, $matches[4], $currentLine); } if (preg_match(self::TOKEN_OBJECT_NAME, $matches[5])) { $tokens[] = new Token(TokenInterface::TYPE_OBJECT_CONSTRUCTOR, $matches[5], $currentLine); } else if (strlen($matches[5])) { $tokens[] = new Token(TokenInterface::TYPE_RIGHTVALUE, $matches[5], $currentLine); } if ($matches[6]) { $tokens[] = new Token(TokenInterface::TYPE_WHITESPACE, $matches[6], $currentLine); } break; case '{': $tokens[] = new Token(TokenInterface::TYPE_BRACE_OPEN, $matches[3], $currentLine); break; case '(': $currentTokenValue = "(\n"; $currentTokenType = TokenInterface::TYPE_RIGHTVALUE_MULTILINE; break; default: throw new TokenizerException('Unknown operator: "' . $matches[3] . '"!', 1403084443, NULL, $currentLine); } continue; } if (strlen($line) === 0) { continue; } throw new TokenizerException('Cannot tokenize line "' . $line . '"', 1403084444, NULL, $currentLine); } if ($currentTokenType !== NULL) { throw new TokenizerException('Unterminated ' . $currentTokenType . '!', 1403084445, NULL, $currentLine); } return $tokens; } /** * @param string $inputStream * @return \Helmich\TypoScriptParser\Tokenizer\TokenInterface[] */ public function tokenizeStream($inputStream) { $content = file_get_contents($inputStream); return $this->tokenizeString($content); } /** * @param string $operator * @return string * @throws \Helmich\TypoScriptParser\Tokenizer\UnknownOperatorException */ private function getTokenTypeForBinaryOperator($operator) { switch ($operator) { case '=': return TokenInterface::TYPE_OPERATOR_ASSIGNMENT; case '<': return TokenInterface::TYPE_OPERATOR_COPY; case '<=': return TokenInterface::TYPE_OPERATOR_REFERENCE; case ':=': return TokenInterface::TYPE_OPERATOR_MODIFY; case '>': return TokenInterface::TYPE_OPERATOR_DELETE; } throw new UnknownOperatorException('Unknown binary operator "' . $operator . '"!'); } private function preprocessContent($content) { // Replace CRLF with LF. $content = str_replace("\r\n", "\n", $content); // Remove trailing whitespaces. $lines = explode("\n", $content); $lines = array_map('rtrim', $lines); $content = implode("\n", $lines); return $content; } }<file_sep><?php namespace Helmich\TypoScriptParser\Parser\AST; /** * Include statements that includes many TypoScript files from a directory. * * @package Helmich\TypoScriptParser * @subpackage Parser\AST */ class DirectoryIncludeStatement extends IncludeStatement { /** * The directory to include from. * @var string */ public $directory; /** * An optional file extension filter. May be NULL. * @var string */ public $extension = NULL; /** * Constructs a new directory include statement. * * @param string $directory The directory to include from. * @param string $extension The file extension filter. MAY be NULL. * @param int $sourceLine The original source line. */ public function __construct($directory, $extension, $sourceLine) { parent::__construct($sourceLine); $this->directory = $directory; $this->extension = $extension; } } <file_sep><?php namespace Helmich\TypoScriptParser\Parser\Printer; use Helmich\TypoScriptParser\Parser\AST\ConditionalStatement; use Helmich\TypoScriptParser\Parser\AST\DirectoryIncludeStatement; use Helmich\TypoScriptParser\Parser\AST\FileIncludeStatement; use Helmich\TypoScriptParser\Parser\AST\NestedAssignment; use Helmich\TypoScriptParser\Parser\AST\Operator\Assignment; use Helmich\TypoScriptParser\Parser\AST\Operator\Copy; use Helmich\TypoScriptParser\Parser\AST\Operator\Delete; use Helmich\TypoScriptParser\Parser\AST\Operator\Modification; use Helmich\TypoScriptParser\Parser\AST\Operator\Reference; use Symfony\Component\Console\Output\OutputInterface; class PrettyPrinter implements ASTPrinterInterface { /** * @param \Helmich\TypoScriptParser\Parser\AST\Statement[] $statements * @param \Symfony\Component\Console\Output\OutputInterface $output * @return string */ public function printStatements(array $statements, OutputInterface $output) { $this->printStatementList($statements, $output, 0); } /** * @param \Helmich\TypoScriptParser\Parser\AST\Statement[] $statements * @param \Symfony\Component\Console\Output\OutputInterface $output * @param int $nesting * @return string */ private function printStatementList(array $statements, OutputInterface $output, $nesting = 0) { foreach ($statements as $statement) { if ($statement instanceof NestedAssignment) { $this->printNestedAssignment($output, $nesting, $statement); } else if ($statement instanceof Assignment) { $output->writeln($this->getIndent($nesting) . $statement->object->relativeName . ' = ' . $statement->value->value); } else if ($statement instanceof Copy) { $output->writeln($this->getIndent($nesting) . $statement->object->relativeName . ' < ' . $statement->target->absoluteName); } else if ($statement instanceof Reference) { $output->writeln($this->getIndent($nesting) . $statement->object->relativeName . ' <= ' . $statement->target->absoluteName); } else if ($statement instanceof Delete) { $output->writeln($this->getIndent($nesting) . $statement->object->relativeName . ' >'); } else if ($statement instanceof Modification) { $output->writeln( $this->getIndent( $nesting ) . $statement->object->relativeName . ' := ' . $statement->call->method . '(' . $statement->call->arguments . ')' ); } else if ($statement instanceof ConditionalStatement) { $this->printConditionalStatement($output, $nesting, $statement); } else if ($statement instanceof FileIncludeStatement) { $output->writeln('<INCLUDE_TYPOSCRIPT: source="FILE:' . $statement->filename . '">'); } else if ($statement instanceof DirectoryIncludeStatement) { if ($statement->extension) { $output->writeln( '<INCLUDE_TYPOSCRIPT: source="DIR:' . $statement->directory . '" extension="' . $statement->extension . '">' ); } else { $output->writeln('<INCLUDE_TYPOSCRIPT: source="DIR:' . $statement->directory . '">'); } } } } private function getIndent($nesting) { return str_repeat(' ', $nesting); } /** * @param \Symfony\Component\Console\Output\OutputInterface $output * @param $nesting * @param \Helmich\TypoScriptParser\Parser\AST\NestedAssignment $statement */ private function printNestedAssignment(OutputInterface $output, $nesting, NestedAssignment $statement) { $output->writeln($this->getIndent($nesting) . $statement->object->relativeName . ' {'); $this->printStatementList($statement->statements, $output, $nesting + 1); $output->writeln($this->getIndent($nesting) . '}'); } /** * @param \Symfony\Component\Console\Output\OutputInterface $output * @param int $nesting * @param \Helmich\TypoScriptParser\Parser\AST\ConditionalStatement $statement */ private function printConditionalStatement(OutputInterface $output, $nesting, $statement) { $output->writeln(''); $output->writeln($statement->condition); $this->printStatementList($statement->ifStatements, $output, $nesting); if (count($statement->elseStatements) > 0) { $output->writeln('[else]'); $this->printStatementList($statement->elseStatements, $output, $nesting); } $output->writeln('[global]'); } }<file_sep><?php namespace Helmich\TypoScriptParser\Parser\Traverser; use Helmich\TypoScriptParser\Parser\AST\Statement; interface Visitor { public function enterTree(array $statements); public function enterNode(Statement $statement); public function exitNode(Statement $statement); public function exitTree(array $statements); }<file_sep><?php namespace Helmich\TypoScriptParser\Tokenizer\Printer; interface TokenPrinterInterface { /** * @param \Helmich\TypoScriptParser\Tokenizer\TokenInterface[] $tokens * @return string */ public function printTokenStream(array $tokens); }
122cfd89a6ef985f2157d537ca6c2c9b677f3683
[ "PHP" ]
10
PHP
beathorst/typo3-typoscript-parser
8d738c0966c811d2d568719234f0e94e726bac65
a2f6f494693c0d2df64b9c0dc6f2918cf0c82f37
refs/heads/master
<repo_name>zhupeng1009/springbootdemo<file_sep>/reademe.md idea :https://www.jetbrains.com/idea/download/#section=windows jDK:https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html tomcat:https://tomcat.apache.org/download-80.cgi maven:https://maven.apache.org/download.cgi kafka : https://www.apache.org/dyn/closer.cgi?path=/kafka/2.3.1/kafka_2.12-2.3.1.tgz docker:https://docs.docker.com/v17.09/engine/installation/linux/docker-ce/ubuntu/ (有windows安装文档) docker-compose:https://docs.docker.com/compose/install/ (有windows安装文档)<file_sep>/src/main/java/com/example/demo/common/shiro/ShiroConfig.java package com.example.demo.common.shiro; import at.pollux.thymeleaf.shiro.dialect.ShiroDialect; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashMap; import java.util.Map; /** * shiro 拦截模块 */ @Configuration public class ShiroConfig { @Bean public UserRealm userRealm() { UserRealm userRealm = new UserRealm(); return userRealm; } /** * 认证 * @return */ @Bean public SecurityManager securityManager() { DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); manager.setRealm(userRealm()); return manager; } /** * shiro 过滤器设置 * @return */ @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean() { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager()); //当此用户是一个非认证用户,需要先登陆进行认证 shiroFilterFactoryBean.setLoginUrl("/login"); shiroFilterFactoryBean.setSuccessUrl("/index"); shiroFilterFactoryBean.setUnauthorizedUrl("/403"); //下边表示允许匿名访问的文件夹 , 前面为固定的文件夹的路径(根据自己的醒目而定例如图片等等) //anon 都可以访问 logout 退出 authc 需要鉴权 Map<String, String> filterChainDefinitionMap = new HashMap<>(); filterChainDefinitionMap.put("/css/**", "anon"); filterChainDefinitionMap.put("/js/**", "anon"); filterChainDefinitionMap.put("/fonts/**", "anon"); filterChainDefinitionMap.put("/img/**", "anon"); filterChainDefinitionMap.put("/docs/**", "anon"); filterChainDefinitionMap.put("/druid/**", "anon"); filterChainDefinitionMap.put("/blog", "anon"); //filterChainDefinitionMap.put("/webjars/**", "anon"); //退出系统 filterChainDefinitionMap.put("/logout", "logout"); // 其中/** 表示所有请求 authc 表示需要鉴权 这个必须放最后 上面所有请求过滤后,剩余的请求在继续拦截(是否修改为配置文件会比较好 // 即使修改部分需求后 也可以通过配置文件实现快速启动,而不需要去再次修改代码 ?) filterChainDefinitionMap.put("/**", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } /** * Shiro生命周期处理器 ---可以自定的来调用配置在 Spring IOC 容器中 shiro bean 的生命周期方法. * * @return */ @Bean("lifecycleBeanPostProcessor") public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } /** * 开启shiro注解 ----启用 IOC 容器中使用 shiro 的注解. 但必须在配置了 LifecycleBeanPostProcessor * 之后才可以使用 * * @return */ @Bean public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator(); proxyCreator.setProxyTargetClass(true); return proxyCreator; } @Bean public ShiroDialect shiroDialect() { return new ShiroDialect(); } /** * 开启shiro注解 ---- 注解权限 * * @param securityManager * @return */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor( @Qualifier("securityManager") SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } }
af3c74c75d16d0b101b1d26a6a61e96e9c3b5bde
[ "Markdown", "Java" ]
2
Markdown
zhupeng1009/springbootdemo
344b8dcb502172cd9bed549d2549e9b6b9cecb61
2b32d15a0353e8feca53ec3aca6a881476010668
refs/heads/master
<repo_name>joeymichaelmartinez/Web-Front-end-Design<file_sep>/_site/pokeApiCall.js "use strict"; (() => { window.RandomPokemonSearchController = { init: () => { let randomPokemonButton = $("#random-pokemon-button"); let randomPokemonDescription = $("#random-pokemon-description"); let getRandomPokemonIndex = () => { return Math.floor(Math.random() * 802); }; let randomPokeIndex = getRandomPokemonIndex(); randomPokemonButton.click(() => $.getJSON("http://pokeapi.co/api/v2/pokemon/" + randomPokeIndex, function(data){ randomPokeIndex = getRandomPokemonIndex(); randomPokemonDescription.text( "You got " + data.name + "! " + "Enter the Pokemon's name below, " + "or enter the name of a Pokemon you already know to get more information!" ); }) ); } }; window.PokemonDescriptionSearchController = { init: () => { let pokemonDescriptionButton = $("#pokemon-description-button"); let pokemonDescriptionTerm = $("#pokemon-description-term"); let pokemonDescriptionImage = $("#pokemon-description-image"); let pokemonDescription = $("#pokemon-description"); let pokemonDescriptionErrorMessage = $("#pokemon-description-error-message"); let flavorText; let sprite; let populatePokemonDescription = (pokeId, textToChange, sprite) => { $.getJSON("https://pokeapi.co/api/v2/pokemon-species/" + pokeId, function(data){ let returnedDescription = data.flavor_text_entries; for (let i = 0; i < returnedDescription.length; i++) { // The pokeApi sometimes returns Japanese or Chinese before getting to English, so to ensure // english is always returned, I have to chech the text for English characters. if (returnedDescription[i].flavor_text.match(/^(?=.*[A-Z0-9])[\w.,!"’'\/$ é][\s\S]+$/ig)) { flavorText = returnedDescription[i].flavor_text; break; } } }).done(() => { pokemonDescriptionImage.attr("src", sprite); $(textToChange).text(flavorText); }).fail(() => { pokemonDescriptionErrorMessage.text( "It seems there was an error looking for your pokemon. Please try again." ); }); }; pokemonDescriptionButton.click(() => $.getJSON("http://pokeapi.co/api/v2/pokemon/" + pokemonDescriptionTerm.val().toLowerCase(), function(data){ sprite = data.sprites.front_default; populatePokemonDescription(data.id, pokemonDescription, sprite); }).done(() =>{ pokemonDescriptionErrorMessage.empty(); }).fail(() => { pokemonDescriptionErrorMessage.text( "Incorrect usage. Please enter the name or number of a Pokemon. " + "Be sure the name is spelled correctly or " + "the number you entered is below 802" ); }) ); pokemonDescriptionTerm.bind("input", () => pokemonDescriptionButton.prop("disabled", !pokemonDescriptionTerm.val())); } }; window.PokemonEvolutionSearchController = { init: () => { let pokemonEvolutionButton = $('#pokemon-evolution-button'); let pokemonEvolutionTerm = $('#pokemon-evolution-term'); let pokemonEvolutionResultContainer = $(".pokemon-evolution-result-container"); let pokemonEvolutionErrorMessage = $("#pokemon-evolution-error-message"); let pokemonNames = []; let populatePokemonEvolution = () => { for (let i = 0; i < pokemonNames.length; i++) { $.getJSON("http://pokeapi.co/api/v2/pokemon/" + pokemonNames[i], function(data) { pokemonEvolutionResultContainer.append($(' <div> ', {id: data.id})); $("#" + data.id).append($( '<img>', {class: 'pokemon-evolution-image', src: data.sprites.front_default} )); pokemonEvolutionResultContainer.children().sort(function(a, b){ return a.id - b.id; }).each(function () { var elem = $(this); elem.remove(); $(elem).appendTo(".pokemon-evolution-result-container"); }); }).fail(() => { pokemonEvolutionErrorMessage.text( "It seems there was an error looking for your pokemon. Please try again." ); }); } }; pokemonEvolutionButton.click(() => $.getJSON("http://pokeapi.co/api/v2/evolution-chain/" + pokemonEvolutionTerm.val(), function(data){ pokemonEvolutionResultContainer.empty().append(); pokemonNames = []; // The pokeApi returns the names in the pokemon evolution chain in a strange way, // where some names are nested further than others, so to handle this nesting, I // use the following code. pokemonNames.push(data.chain.species.name); if (data.chain.evolves_to){ for (let i = 0; i < data.chain.evolves_to.length; i++){ pokemonNames.push(data.chain.evolves_to[i].species.name); if (data.chain.evolves_to[i].evolves_to) { for (let j = 0; j < data.chain.evolves_to[i].evolves_to.length; j++) { pokemonNames.push(data.chain.evolves_to[i].evolves_to[j].species.name); } } } } }).done(() => { pokemonEvolutionErrorMessage.empty(); populatePokemonEvolution(); }).fail(() => { pokemonEvolutionErrorMessage.text("Incorrect usage. Please enter a number below 424."); }) ); pokemonEvolutionTerm.bind("input", () => pokemonEvolutionButton.prop("disabled", !pokemonEvolutionTerm.val())); } }; })();
9fe6ecd229dd8c1de3846ee888ff7892a891c3ac
[ "JavaScript" ]
1
JavaScript
joeymichaelmartinez/Web-Front-end-Design
83a4b4fab77e54ae849e394fbcbe285223229360
d2262777f0cd6749b41c34d3c87ab2ae25562272
refs/heads/master
<repo_name>jeck-hang/videoRTP<file_sep>/src/record.js /** * mediaRecord 录屏方式 * @param {*} mediaStream - webrtc 返回的媒体流,用于MediaRecord录制返回blob视频段 * @param {*} cb - MediaRecord 每次录屏返回的视频段传入执行回调 * @param {*} config - {collectTime:每次录得的视频段的时长,ended:录屏结束后的回调} * @returns {*} mediaRecorder, 用于外部停止录屏等操作 * 与 MediaStreamRecord.js 的录屏差异: * startRecording() {... setTimeout(stopRecording, 3000)} * mediaRecorder.onstop() { startRecording()} * 此方式录制出来的视频段是完整的独立的视频段,而本方法录制的视频段是整个视频段切割成的若干部分 */ export function RTCRecord(mediaStream, cb, config = {}) { let stream = null const collectTime = config.collectTime || 1000 let options = { mimeType: 'video/webm;codecs=vp9' } let mediaRecorder = null function getMimeType() { let options = { mimeType: 'video/webm;codecs=vp9' } if (!MediaRecorder.isTypeSupported(options.mimeType)) { console.error(`${options.mimeType} is not Supported`) options = { mimeType: 'video/webm;codecs=vp8' } if (!MediaRecorder.isTypeSupported(options.mimeType)) { console.error(`${options.mimeType} is not Supported`) options = { mimeType: 'video/webm' } if (!MediaRecorder.isTypeSupported(options.mimeType)) { console.error(`${options.mimeType} is not Supported`) options = { mimeType: '' } } } } return options } function startRecording() { try { mediaRecorder = new MediaRecorder(stream, options) } catch (e) { console.error('Exception while creating MediaRecorder:', e) return } mediaRecorder.onstop = (event) => { mediaRecorder = null config.ended && config.ended() } mediaRecorder.ondataavailable = handleDataAvailable mediaRecorder.start(collectTime) // collect 1000ms of data // setTimeout(stopRecording, 3000) } function handleDataAvailable(event) { if (event.data && event.data.size > 0) { // recordedBlobs.push(event.data); // stream && startRecording() cb && cb(event.data) } } // function stopRecording() { // mediaRecorder.stop(); // } stream = mediaStream options = getMimeType() startRecording() mediaStream.onended = function () { mediaStream = stream = null } return mediaRecorder } /** * 在视频开始播放前调用canvas定时录屏 * @param {DOM} video - 要录制的原视频DOM对象 * @param {*} cb - 每次录屏 返回的'image/webp' 图片数据 * @param {*} options - {duration: 录屏间隔时长,ended: 录屏结束的回调方法 } * @returns {Promise} - stop: 停止录屏接口,canvasRecordPromise: 判断是否成功录屏 */ export function CanvasRecord(video, cb, options = {}) { let timer = null const videoHeight = video.videoHeight || video.clientHeight const videoWidth = video.videoWidth || video.clientWidth const record = { ondataavailable() {}, onstop() {}, stop: stopRecord, start() { video.play() }, } // 视频开始播放 video.addEventListener('canplay', startRecord, false) // 视频播放完 video.addEventListener('ended', endRecord, false) let canvas = document.createElement('canvas') canvas.style.display = 'none' canvas.setAttribute('height', videoHeight) canvas.setAttribute('width', videoWidth) function recordFunc() { const context = canvas.getContext('2d') context.drawImage(video, 0, 0, videoHeight, videoWidth) canvas.toBlob((blob) => { record.ondataavailable(blob, context) }, 'image/webp') } function startRecord() { recordFunc() timer = setInterval(() => { recordFunc() }, options.duration || 200) } function endRecord() { stopRecord() record.onstop() console.log('视频录制结束!') } function stopRecord() { timer && clearInterval(timer) video.removeEventListener('canplay', startRecord, false) video.removeEventListener('ended', endRecord, false) canvas = null } return record } /** * This method stops recording MediaStream. * @param {MediaStream} mediaStream - webrtc 返回的媒体流,用于MediaRecord录制返回blob视频段 * @param {DOM} video - webrtc 的呈现视频的video元素,用于Canvas 返回视频画面 * @param {function} callback - Callback function, that is used to pass recorded blob back to the callee. * @param {Object} config - duration:canvas 每隔{duration}捕获视频画面,collectTime:MediaRecord 每次捕获{collectTime}时长的视频段 * @method * @memberof MediaStreamRecorder * @example * webrtcRecorde(stream, config.video, function(data) { * worker.send(data) * }) */ export default function record(mediaStream, video, cb, config = {}) { return typeof MediaRecorder !== 'undefined' ? RTCRecord(mediaStream, cb, config) : CanvasRecord(video, cb, config) } <file_sep>/src/getVideo.js let getVideoByInput = null function getInput() { if (getVideoByInput) return getVideoByInput const input = document.createElement('input') getVideoByInput = input input.setAttribute('type', 'file') input.setAttribute('accept', 'video/*') input.setAttribute('capture', 'user') input.style.display = 'none' document.body.append(input) return input } export default function getVideo() { const input = getInput() return new Promise((resolve) => { input.onchange = (e) => { resolve(e.target.files[0]) } input.click() }) } <file_sep>/rollup.config.js import rollup from './rollup.base.config' export default rollup([ { input: 'src/index.js', file: 'lib/index.js' }, { input: 'src/index.js', file: 'lib/index.min.js', env: 'prod' }, { input: 'src/index.js', file: 'videoRTP.min.js', name: 'videoRTP', format: 'umd', env: 'prod' }, { input: 'src/index.js', file: 'videoRTP.js', name: 'videoRTP', format: 'iife' }, { input: 'src/pressVideo.js', file: 'lib/pressVideo.js' }, { input: 'src/pressVideo.js', file: 'lib/pressVideo.min.js', env: 'prod' }, { input: 'src/record.js', file: 'lib/record.js' }, { input: 'src/record.js', file: 'lib/record.min.js', env: 'prod' }, ]) <file_sep>/src/sender.js // TODO:缓存 + 发送数据机制, 消费数据 data_consume function f(url, useSocket = true, chunkLimit) { self.addEventListener( 'message', function (e) { console.log('push to worker', e.data) if (useSocket) { Consumer.sender.socket(e.data) } else { if (e.data === 0) { Consumer.sender.fetch(0).then(() => { Consumer.sender.destroy = true self.postMessage({ code: 0, data: Consumer.storage.bufs, }) }) } else { Consumer.wirte(e.data) } } }, false ) const Consumer = { storage: { bufs: [], cursor: 0, }, // 读取缓存 read(flag = false) { if (this.storage.bufs.length === 0) return [] if (this.storage.cursor === this.storage.bufs.length) return [] if (flag) { const cursor = this.storage.cursor this.storage.cursor = this.storage.bufs.length return { data: this.storage.bufs.slice(cursor), start: cursor, } } const arr = [] let total = 0 for (let i = this.storage.cursor; i < this.storage.bufs.length; i++) { if (total + this.storage.bufs[i].size > (chunkLimit || 1024 * 1024 * 3)) { const cursor = this.storage.cursor this.storage.cursor = i return { data: arr.length ? arr : [this.storage.bufs[i]], start: arr.length ? i - 1 : cursor, } } arr.push(this.storage.bufs[i]) total += this.storage.bufs[i].size } }, wirte(data) { const bufs = Consumer.storage.bufs bufs.push(data) Consumer.sender.send(data) // 通知发送器,发送数据 }, sender: { wx: null, promise: null, fetchPromise: [], initSocket() { Consumer.sender.ws = new WebSocket(url) return (Consumer.sender.promise = new Promise((resolve) => { Consumer.sender.ws.onopen = () => { resolve(Consumer.sender.ws) } })) }, socket(data) { if (!Consumer.sender.promise) Consumer.sender.promise = Consumer.sender.initSocket() Consumer.sender.promise.then((wx) => { console.log('socket', data) wx.send(data) return wx }) }, fetch(data) { // return fetch(url, { method: "POST", body: data, headers: {} }); // TODO 直接传blob,一次传多张图片 // let file = new File([data], self.id + '.jpg', {type: 'image/jpeg'}) const formData = new FormData() formData.enctype = 'multipart/form-data' const obj = data === 0 ? Consumer.read(true) : data obj.data.forEach((file, index) => { formData.append('files', file, `${obj.start + index}.webp`) }) // formData.append('file', new Blob(['123'], {type: 'text/plain'})) formData.append('start', obj.start) formData.append('end', obj.start + obj.data.length) formData.append('total', data === 0 ? Consumer.storage.cursor : null) const promise = new Promise((resolve) => { const xhr = new XMLHttpRequest() // 开始上传 xhr.open('POST', url, true) xhr.send(formData) xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { resolve(xhr) } } }) Consumer.sender.fetchPromise.push(promise) return data === 0 ? Promise.all(Consumer.sender.fetchPromise) : promise }, destroy: false, block: false, // 工人是否空闲 sendAbles: [true, true, true], isSendAble() { return !Consumer.sender.sendAbles.some((status) => !status) }, // 将缓存里面的数据分批发送出去 send() { // TODO 优化:websocket 走缓存机制,多条websocket可同时进行 // if (useSocket) { // let data = Consumer.read(1); // if (data === -1) return (Consumer.sender.block = true); // Consumer.sender.worker(0, data); // return; // } const datas = Consumer.read() // 缓存中的数据不足,则发送器阻塞掉 if (!datas || datas.length === 0) return (Consumer.sender.block = true) Consumer.sender.fetch(datas).then(() => { Consumer.sender.send() }) }, }, } } // 获取 typeArray 字节数组 function base64ToTypeArray(base64) { // let base64 = canvas.toDataURL(); // 同样通过canvas的toDataURL方法将canvas图片Base64编码 const bstr = atob(base64.split(',')[1]) // atob是将base64编码解码,去掉data:image/png;base64,部分 let n = bstr.length const u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } return u8arr } // 大数据传送,data : 0 | base64, url: 请求地址支持普通请求或者websocket export default function sender({ url, useSocket = true, chunkLimit }) { // 生成线程 const blob = new Blob(['(' + f.toString() + ")('" + url + "'," + useSocket + ',' + chunkLimit + ')']) const script = window.URL.createObjectURL(blob) const worker = new Worker(script) const tool = {} worker.onmessage = (event) => { if (event.data && event.data.code === 0) { // document.getElementsByTagName('video')[0].src = '' worker.terminate() // 终止worker线程 tool.finished && tool.finished(event.data.data) } } tool.send = function (data) { // let binary = data === 0 ? 0 : base64ToTypeArray(data) worker.postMessage(data) } return tool } <file_sep>/src/index.js import webrtc from './webrtc' import webrtcRecorde from './record' import getVideo from './getVideo' import pressVideo from './pressVideo' export function webrtcSurport() { return !!navigator.mediaDevices.getUserMedia } function getDOM(dom) { if (typeof dom === 'string') return (dom = document.querySelector(dom)) return dom } async function degrade(config) { const file = await getVideo() const record = await pressVideo(file, config.chunks, config) return record } /** * 优先唤起webRTC录制视频,若不支持则降级用上传本地视频方式,IE录屏推荐用rtmp-streamer * @param {*} config { chunks: 每次录屏返回的数据包(webp/webm), * ended: 录屏结束回调方法, * duration: 录屏间隔时间, * collectTime: 录制的视频时长, * MINSIZE: 最小视频size,低于此值,则直接返回视频不做处理 * MAXTIME: 视频的最大时长限制} * @return {Promise} 返回初始化成功后的相关配置信息,提供给外部随时stop录屏的接口 * let recorder = await openVideo({ * video: document.getElementById('webrtc'), * duration: 100, * MINSIZE: 1024, * MAXTIME: 15, * chunks(chunk) { * // sender chunks * * }, * ended() { * // record chunks ended * }, * degrade:document.getElementById('p') // 不支持webRTC则降级处理打开本地视频 * }) * * setTimeout(() => { * recorder.stop() * }, 5000) */ export async function openVideo(config) { const isWebrtcSurport = webrtcSurport() if (isWebrtcSurport) { const stream = await webrtc(config.video) const record = webrtcRecorde(stream, config.video, config.chunks, config) return { stop() { const tracks = stream.getTracks() tracks[0].stop() record.stop() }, } } else { if (!config.degrade) return Promise.reject({ isWebrtcSurport: false }) if (config.degrade === true) return degrade(config) if (config.degrade) { let resolveP = null const promise = new Promise((resolve) => (resolveP = resolve)) getDOM(config.degrade).addEventListener('click', function () { degrade(config).then(resolveP) }) return promise } } } <file_sep>/README.md # [video-rtp](https://github.com/zhutao315/videoRTP) [![npm](https://img.shields.io/npm/v/video-rtp.svg)](https://www.npmjs.com/package/video-rtp) A cross-browser implementation to record video on real time > <br>1. Use webRTC/mediaRecord first <br>2. Degrade to use "input[type = file]" when not support webRTC video-rtp can open the camera and record video to a series of blobs. You can upload the recorded blobs in realtime to the server! Or you can get the blobs and combine to a smaller video after specific time-intervals. ## Browser Support According to webRTC/MediaRecord/Canvas's compatibility | Browser | Support | Features | | ------------- |-------------|-------------| | Firefox | mobile / PC | webRTC to webm | | Google Chrome | mobile / PC | webRTC to webm | | Opera | mobile / PC | mobile: canvas to webp, PC: webRTC to webm | | Android | ALL | Chrome: webRTC to webm, Other: canvas to webp | | Microsoft Edge | Suggest: rtmp-streamer | canvas to webp | | Safari 11 | mobile / PC | canvas to webp now | > There is a similar project: **RecordRTC**! [Demo](https://www.webrtc-experiment.com/RecordRTC/) ## How to use it You can [install scripts using NPM](https://www.npmjs.com/package/video-rtp): ```javascript npm install video-rtp ``` ## Record video ```javascript import {webrtcSurport, openVideo} from 'video-rtp' function getSocket(isRTC) { let url = `ws://localhost:3000/${isRTC ? 'webm' : 'webp'}` const ws = new WebSocket(url); return new Promise(resolve => { ws.onopen = () => resolve(ws) }) }, const wsP = getSocket(webrtcSurport()) const record = await openVideo({ video: document.getElementById('webrtc'), duration: 100, MINSIZE: 1024, chunks(chunk) { // sender chunks console.log('sender chunks', chunk) wsP.then(ws => ws.send(chunk)) }, ended() { // record chunks ended, You can save video in this function. console.log('record chunks ended') wsP.then(ws => ws.send(0)) }, degrade:true // 不支持webRTC则降级处理打开本地视频 }) ``` ## How to save recordings? ```javascript import {webrtcSurport, openVideo} from 'video-rtp' import Whammy from 'whammy' let video = null const encoder = new Whammy.Video(15); openVideo({ /* .....*/ chunks(blobs, canvas) { // save webm/webp to blobs encoder.add(canvas) }, ended() { // create video by blobs if (webrtcSurport()) { video = new Blob(blobs, {type: 'video/webm;codecs=vp9'}); }else { video = encoder.compile() } }, degrade:document.getElementById('p') // 不支持webRTC则降级处理打开本地视频 }) ``` ## DEMO Local video compression and upload WEB push and pull stream, mock live broadcast [https://github.com/zhutao315/videoRTP-example](https://github.com/zhutao315/videoRTP-example) ``` npm install && npm start ``` open localhost:3000 # API Documentation | Name | Type | Default | Description | | ---------------| ------------- | ------------- | ---------------------------------------------------------------| | `video` | String/DOM | - | Display video recorded by the camera | | `duration` | Number | 100(ms) | The time interval when Canvas draws frames | | `collectTime` | Number | 1000(ms) | The time length of chunks by mediaRecord record | | `MINSIZE` | Number | 1M | If the video size is lower than this value, the video will be returned without processing | | `MAXTIME` | Number | 15(m) | The Maximum duration of the upload video | | `chunks` | Function | () => { } | The callback Function executed each time when the screen is recorded.<br> The param is a blob and the blob's type is webm/webp | | `ended` | Function | () => { } | The callback Function executed when the record is end | | `degrade` | String/DOM/Boolen | - | The degrage is usefull when the webRTC is not supported | > When the "degrade" is a string, the component will find the DOM by id/class. The dom will bind a click event to open the local video. When the value of "degrade" is true, the openVideo function will open the local video directly. ## How to manually stop recordings? ```javascript record.stop(); ``` ## How to pause recordings? ```javascript record.pause(); ``` ## How to resume recordings? ```javascript record.resume(); ``` ## License If you have any Suggestions, let me know. Thanks! MIT licence
a46e91837f24c7b8fd3e16ce30dcfd90ddd11310
[ "JavaScript", "Markdown" ]
6
JavaScript
jeck-hang/videoRTP
58746db0d443f97065de5276ec4548f134a071db
236a24a8f2b8d37acc1436f9ee64cbbf3b851286
refs/heads/master
<repo_name>swych/client<file_sep>/config/device-client.js var argv = require('minimist')(process.argv.slice(2)); var port = argv['device-port'] || 8080; var WebSocket = require('ws'); var uuid = require('uuid'); var bus = require('./events'); var devices = {}; var deviceClient = { connect:function(deviceAddress,cb){ console.log('Now connecting',deviceAddress); var ws = new WebSocket('ws://'+deviceAddress+':'+port); var id = uuid.v4(); devices[id] = ws; ws.on('open', function open() { console.log('Now listening',deviceAddress); if(cb)cb(); }); ws.on('message', function(payload) { }); ws.on('close', function close() { console.log('disconnected'+id,deviceAddress); delete devices[id]; }); } } bus.on('command:register', function(data){ var ip = data.ips[0]; deviceClient.connect(ip); }); bus.on('command:switch', function(data){ var payload = JSON.stringify(data); Object.keys(devices).forEach(function(key){ var device = devices[key]; device.send(payload); }); }); module.exports = deviceClient;<file_sep>/config/server-client.js var WebSocket = require('ws'); var argv = require('minimist')(process.argv.slice(2)); var host = argv.host || 'api.swych.io'; var port = argv.port || 80; var bus = require('./events'); module.exports = { connect: function(cb){ var ws = new WebSocket('ws://'+host+':'+port); ws.on('open', function open() { if(cb)cb(); console.log('Connected!'); }); ws.on('message', function(payload) { var request = JSON.parse(payload); var action = request.command; console.log('MESSAGE',payload); bus.emit('command:'+action, request.data); }); ws.on('error', function() { console.log('error', arguments); }); } }<file_sep>/listeners/device.js var bus = require('../config/events'); var deviceClient = require('../config/device-client'); var device = { bind: function(){ } } module.exports = device;<file_sep>/listeners/index.js var device = require('./device'); module.exports = { bind:function(){ device.bind(); } }<file_sep>/README.md # client Client codebase - this app sits on a router or home PC <file_sep>/client.js var WebSocket = require('ws'); var argv = require('minimist')(process.argv.slice(2)); var ws = new WebSocket('ws://'+argv.host+':8080'); ws.on('open', function open() { console.log('Connected!'); }); ws.on('message', function(data, flags) { console.log(data,flags); });
b6eac392531f736aee5133eddfb79135d03774c3
[ "JavaScript", "Markdown" ]
6
JavaScript
swych/client
2acada8fade239a3699703908cab574ad17204a6
3baea2327885e73cd425e3defdf5177c4c36204d
refs/heads/master
<repo_name>fadeopolis/slam<file_sep>/Readme.md # SLAM - Screen Layout Automatic Manager Python daemon that listens to Xcb Randr events, and manages screen layouts. It stores layout for each set of connected screens (using EDID to differentiate different screens on same output). It can restore old layouts when you plug the same screens as before. It also updates its layout database when you manually change the layout, using 'xrandr' or a graphical tool. ## Usage The daemon is available as a python library. To launch it, you need to create a python file importing the library, and start this python file as the daemon: import slam slam.start(<options>) ## Todo * Support for properties like backlight * dbus interface : * backlight change * force normalize of manual state * get state info * force backend reload (interface for hotplug events) * Plugin system to make additionnal actions when change of layout : * Background * i3 configure by screens ? * Force reload of state in X when udev hotplug event ? ## Install Requires: * python >= 3.2 * ISL library (usually shipped with gcc) * Boost::Python * xcffib python Xcb binding Use standard distutils (--user will place it in a user local directory): python setup.py install [--user] <file_sep>/examples/slam #!/usr/bin/env python import slam import logging slam.start ( log_file = None, # stderr db_file = "database", # local # Default backend is xcb backend_args = dict ( dpi = 96 ) ) <file_sep>/slam/util.py # Copyright (c) 2013-2015 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ Utilities """ import operator import select import logging, logging.handlers # Logging def setup_root_logging (filename, level): root = logging.getLogger () root.setLevel (level) formatter = logging.Formatter (style = "{", fmt = "{asctime} :: {levelname} :: {name} :: {message}") if filename: output = logging.handlers.RotatingFileHandler (filename, "a", 1000000, 1) else: output = logging.StreamHandler () output.setLevel (level) output.setFormatter (formatter) root.addHandler (output) return root def setup_logger (module_name): return logging.getLogger (module_name) logger = setup_logger (__name__) # Attribute equality helper class class AttributeEquality (object): """ Inherit from this class to automatically support basic equality test """ def __eq__ (self, other): return isinstance (other, self.__class__) and self.__dict__ == other.__dict__ def __ne__ (self, other): return not self.__eq__ (other) # Pair class Pair (tuple): """ Utility type for a pair of values """ def __new__ (cls, a, b = None): """ Takes a pair of values, or an iterable """ if b != None: a = (a, b) return super (Pair, cls).__new__ (cls, a) @classmethod def from_struct (cls, struct, xkey="x", ykey="y"): """ Construct a Pair by querying xkey/ykey (default x/y) fields in a structure """ return cls (getattr (struct, xkey), getattr (struct, ykey)) @classmethod def from_size (cls, struct, formatting="{}"): """ Construct a Pair by taking (optionnaly formatted) width/height fields in the given class """ return cls.from_struct (struct, formatting.format ("width"), formatting.format ("height")) def __getattr__ (self, attr): """ Provide x/y/w/h quick access """ if attr in ["x", "w"]: return self[0] elif attr in ["y", "h"]: return self[1] else: raise AttributeError ("Pair doesn't support '{}' attr (only x/y/w/h)".format (attr)) def copy (self): return Pair (self) def swap (self): return Pair (self.y, self.x) def __add__ (self, other): return Pair (self.x + other.x, self.y + other.y) def __neg__ (self): return Pair (-self.x, -self.y) def __sub__ (self, other): return self + (-other) def __format__ (self, spec): """ Pretty printing, with two str.format flags for integers sizes """ if spec == "s": return "{}x{}".format (self.x, self.y) elif spec == "p": return "{}mm x {}mm".format (self.x, self.y) else: return str (self) # Daemon class Daemon (object): """ Daemon objects that listen to file descriptors and can be activated when new data is available A daemon can ask to be reactivated immediately even if no new data is available. A counter ensure that reactivations does not loop undefinitely. Must be implemented for each subclass : int fileno () : returns file descriptor bool activate () : do stuff, and returns False to stop the event loop """ def activate_manually (self): """ Ask the event loop to activate us again """ self._flag_to_be_activated = True def _to_be_activated (self): # Try-except handles the init case, where the flag doesn't exist try: return self._flag_to_be_activated except AttributeError: return False def _reset_activation_counter (self): self._activation_counter = 0 def _activate (self): # If activation counter doesn't exist, we are not in an event loop and we don't care try: self._activation_counter += 1 if self._activation_counter > 10: raise RuntimeError ("daemon reactivation loop detected") except AttributeError: pass return self.activate () @staticmethod def event_loop (*daemons): """ Event loop """ while True: # Activate deamons until no one has the activation flag raised map (Daemon._reset_activation_counter, daemons) while any (map (Daemon._to_be_activated, daemons)): d = next (filter (Daemon._to_be_activated, daemons)) d._flag_to_be_activated = False if d._activate () == False: return # Raise activation flag on all deamons with new input data new_data, _, _ = select.select (daemons, [], []) for d in new_data: d._flag_to_be_activated = True # Class introspection and pretty print def class_attributes (cls): """ Return all class attributes (usually class constants) """ return {attr: getattr (cls, attr) for attr in dir (cls) if not callable (attr) and not attr.startswith ("__")} def sequence_stringify (iterable, highlight = lambda t: False, stringify = str): """ Print and join all elements of <iterable>, highlighting those matched by <highlight : obj -> bool> """ def formatting (data): return ("[{}]" if highlight (data) else "{}").format (stringify (data)) return " ".join (map (formatting, iterable))
ccaf1f83c7c82dad1ed7ce71dc595e67370c8c8d
[ "Markdown", "Python" ]
3
Markdown
fadeopolis/slam
1647f1a05f7e8c2dde1d8580113e6d1801a3b591
034ac75e7754b5fe9299c292c3eba9190e2394a9
refs/heads/master
<file_sep>package com.mac.thirthir_git; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; public class MainActivity extends Activity { String[] REMIND_TIME; int REMIND_COUNT; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //onCreate內才可以初始化 REMIND_TIME = new String[]{"9:00","12:00"}; REMIND_COUNT = REMIND_TIME.length; if(REMIND_COUNT != 0){ setRemindContent(); //其實不用動態添加,位置太難找(para難設定大小跟相對位置,單位不同),直接判斷是否有提醒跟記錄設定然後載入不同的layout,再找到控件改變text的內容 //只四似乎要多寫三個,因為有兩個部分可以改變設置> 改變設計,設置後變為兩個按鈕,只剩更改,再到下一步改變設置或是取消 } if(REMIND_COUNT != 0) { setInsistanceContent(); //text部分改為 } } private void setRemindContent() { TextView tv_remind_stm = (TextView)findViewById(R.id.tv_remind_stm); tv_remind_stm.setVisibility(View.INVISIBLE); RelativeLayout rl_remind_already = (RelativeLayout)findViewById(R.id.rl_remind_already); rl_remind_already.setVisibility(View.VISIBLE); // ArrayList array = new ArrayList(); TextView tv_upper = (TextView)findViewById(R.id.tv_upper); TextView tv_set01 = (TextView)findViewById(R.id.tv_set01); TextView tv_middle = (TextView)findViewById(R.id.tv_middle); TextView tv_set02 = (TextView)findViewById(R.id.tv_set02); TextView tv_below = (TextView)findViewById(R.id.tv_below); TextView tv_set03 = (TextView)findViewById(R.id.tv_set03); // //將控件放入序列方便設定 // array.add(tv_upper); // array.add(tv_set01); // array.add(tv_middle); // array.add(tv_set02); // array.add(tv_below); // array.add(tv_set03); if(REMIND_COUNT == 1){ //array.get(0) //只能取值 //array[0]; //無法用這方法get //重點是放入的類型通通為object,不含方法“setVisibility()” tv_upper.setVisibility(View.INVISIBLE); tv_set01.setVisibility(View.INVISIBLE); tv_middle.setVisibility(View.VISIBLE); tv_middle.setText("1"); tv_set02.setVisibility(View.VISIBLE); tv_set02.setText(REMIND_TIME[0]); tv_below.setVisibility(View.INVISIBLE); tv_set03.setVisibility(View.INVISIBLE); }else if(REMIND_COUNT == 2){ tv_upper.setVisibility(View.VISIBLE); // tv_upper.setPadding(130,30,0,0);//單位不一致,而且圖跟字會跑掉 tv_set01.setVisibility(View.VISIBLE); tv_set01.setText(REMIND_TIME[0]); // tv_set01.setPadding(160,26,0,0); tv_middle.setVisibility(View.VISIBLE); // tv_middle.setPadding(130,60,0,0); tv_middle.setText("2"); tv_set02.setVisibility(View.VISIBLE); tv_set02.setText(REMIND_TIME[1]); // tv_set02.setPadding(160,56,0,0); tv_below.setVisibility(View.INVISIBLE); tv_set03.setVisibility(View.INVISIBLE); }else if(REMIND_COUNT == 3){ tv_upper.setVisibility(View.VISIBLE); tv_set01.setVisibility(View.VISIBLE); tv_set01.setText(REMIND_TIME[0]); tv_middle.setVisibility(View.VISIBLE); tv_middle.setText("2"); tv_set02.setVisibility(View.VISIBLE); tv_set02.setText(REMIND_TIME[1]); tv_below.setVisibility(View.VISIBLE); tv_below.setText("3"); tv_set03.setVisibility(View.VISIBLE); tv_set03.setText(REMIND_TIME[2]); } //實作原理、設計模型、行動裝置底層運作方式 //design web, and fill keyword list //the end the project //12/23土法煉鋼完成區塊操作 // RelativeLayout rl_remind_content = (RelativeLayout)findViewById(R.id.rl_remind_content); // TextView tv_remind_stm = (TextView)findViewById(R.id.tv_remind_stm); // tv_remind_stm.setText(""); // // TextView tv_remind_setbtn = (TextView)findViewById(R.id.tv_remind_setbtn); // tv_remind_setbtn.setVisibility(View.GONE); // // TextView tv_remind_stopbtn = new TextView(this); // tv_remind_stopbtn.setText(getResources().getString(R.string.stop)); // tv_remind_stopbtn.setBackgroundResource(R.drawable.bluecircle_bg); // tv_remind_stopbtn.setTextSize(25); //// tv_remind_stopbtn.setScaleX(1); //胖瘦效果不對 //// tv_remind_stopbtn.setScaleY(2); // RelativeLayout.LayoutParams para04 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, // ViewGroup.LayoutParams.WRAP_CONTENT); // //RelativeLayout.LayoutParams para04 = new RelativeLayout.LayoutParams(400,400); // para04.topMargin = 400; // para04.leftMargin = 450; // rl_remind_content.addView(tv_remind_stopbtn,para04); // // TextView tv_remind_changebtn = new TextView(this); // tv_remind_changebtn.setText(getResources().getString(R.string.change)); // tv_remind_changebtn.setTextSize(25); // tv_remind_changebtn.setBackgroundResource(R.drawable.bluecircle_bg); // RelativeLayout.LayoutParams para05 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, // ViewGroup.LayoutParams.WRAP_CONTENT); // para05.topMargin = 400; // para05.leftMargin = 700; // rl_remind_content.addView(tv_remind_changebtn,para05); // // LinearLayout subLayout = new LinearLayout(this); // subLayout.setOrientation(LinearLayout.VERTICAL); // RelativeLayout.LayoutParams para = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, // ViewGroup.LayoutParams.WRAP_CONTENT); // para.rightMargin = 10; //para 給數字圖標用 // para.addRule(RelativeLayout.CENTER_VERTICAL, -1); //對父控件的位置置中 // RelativeLayout.LayoutParams para02 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, // ViewGroup.LayoutParams.WRAP_CONTENT); //para02 給數字右邊的時間用 // RelativeLayout.LayoutParams para03 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, // ViewGroup.LayoutParams.WRAP_CONTENT); //para03給新生成的sublayout用 // para03.leftMargin = 400; // para03.topMargin = 60; // // // for(int i=1; i<=REMIND_COUNT; i++){ // LinearLayout listLayout = new LinearLayout(this); // listLayout.setOrientation(LinearLayout.HORIZONTAL); // // TextView tv = new TextView(this); // String i2 = ""+i; // tv.setText(i2); // tv.setTextSize(14); // tv.setBackgroundResource(R.drawable.whitecircle_bg); // listLayout.addView(tv,para); // // TextView tv02 = new TextView(this); // tv02.setText(REMIND_TIME[i-1]); // tv02.setTextSize(20); // listLayout.addView(tv02,para02); // // subLayout.addView(listLayout); // } // // rl_remind_content.addView(subLayout,para03); } private void setInsistanceContent() { } }
48a6bdee11870e551fc632285e207df591e381c9
[ "Java" ]
1
Java
ftstc451810/ThirThir
d607db2b93758681b4a3332b6205a869aa0f5042
f0226d5e28be67646f79d1be683eef05bac406d0
refs/heads/master
<file_sep>import sys debug=True def debug_print(x): if debug==True: print("DEBUG PRINTER") print(x) arg=sys.argv[1] debug_print("arg is "+arg) num_args=len(sys.argv)-1 color_list=[] if num_args>1:#can only handle 1 file at a time for now print("too many input files") sys.exit() def get_colors(input_file): for line in input_file: if "#" in line: #append hex code to color_list hexcode=line[line.index("#"):line.index("#")+7] #debug_print(hexcode) color_list.append(hexcode) def print_colors(collist): pass input_file=open(arg,'r') get_colors(input_file) input_file.close()
c3610cedc155e51eb62ea03468ad49ab9d559025
[ "Python" ]
1
Python
sullyj3/colorprinter
d49d82e5e79e3c90baa0bdee3239303ef2f3b8e9
4e24c70708ee84320ad9700c34999eb224d57802
refs/heads/master
<file_sep>#define GLEW_STATIC #include <GL\glew.h> #include <GLFW\glfw3.h> #include <glm\glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <SOIL/SOIL.h> #include <iostream> #include "shader.h" #include "camera.h" void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); void do_movement(); void mouse_callback(GLFWwindow* window, double xpos, double ypos); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); //camera Camera camera(glm::vec3(0.0f, 0.0f, 3.0f)); bool firstMouse = true; bool keys[1024]; GLfloat deltaTime = 0.0f; // Time between current frame and last frame GLfloat lastFrame = 0.0f; // Time of last frame GLfloat lastX = 400, lastY = 300; int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, false); GLFWwindow* window = glfwCreateWindow(800, 600, "light1", nullptr, nullptr); glfwSetKeyCallback(window,key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cout << "Failed to initialize GLEW" << std::endl; return -1; } int width, height; glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); glEnable(GL_DEPTH_TEST); Shader lightingShader("vertexShaderSource.vs", "fragmentShaderSource.frag"); Shader lightingShader_lamp("vertexShaderSource.vs", "fragmentShaderSource_lamp.frag"); // Set up vertex data (and buffer(s)) and attribute pointers GLfloat vertices[] = { // Positions // Normals // Texture Coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }; glm::vec3 cubePositions[] = { glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; glm::vec3 pointLightPositions[] = { glm::vec3(0.4f, 0.7f, 0.1f), glm::vec3(0.4f, 0.7f, 0.1f), glm::vec3(0.4f, 0.7f, 0.1f), glm::vec3(0.4f, 0.7f, 0.1f) }; GLuint containerVAO,lightVAO; glGenVertexArrays(1, &containerVAO); glGenVertexArrays(1, &lightVAO); GLuint VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindVertexArray(containerVAO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), (GLvoid*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), (GLvoid*)(3 * sizeof(GL_FLOAT))); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GL_FLOAT), (GLvoid*)(6 * sizeof(GL_FLOAT))); glEnableVertexAttribArray(2); glBindVertexArray(0); glBindVertexArray(lightVAO); // We only need to bind to the VBO (to link it with glVertexAttribPointer), no need to fill it; the VBO's data already contains all we need. glBindBuffer(GL_ARRAY_BUFFER, VBO); // Set the vertex attributes (only position data for the lamp)) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glBindVertexArray(0); // Load textures GLuint diffuseMap, specularMap,emissionMap; glGenTextures(1, &diffuseMap); glGenTextures(1, &specularMap); glGenTextures(1, &emissionMap); //int width, height; unsigned char* image; // Diffuse map image = SOIL_load_image("container2.png", &width, &height, 0, SOIL_LOAD_RGB); glBindTexture(GL_TEXTURE_2D, diffuseMap); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); SOIL_free_image_data(image); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); // Specular map image = SOIL_load_image("lighting_maps_specular_color.png", &width, &height, 0, SOIL_LOAD_RGB); glBindTexture(GL_TEXTURE_2D, specularMap); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); SOIL_free_image_data(image); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); // Emission map image = SOIL_load_image("matrix.jpg", &width, &height, 0, SOIL_LOAD_RGB); glBindTexture(GL_TEXTURE_2D, emissionMap); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); SOIL_free_image_data(image); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); // Set texture units lightingShader.Use(); glUniform1i(glGetUniformLocation(lightingShader.Program, "material.diffuse"), 0); glUniform1i(glGetUniformLocation(lightingShader.Program, "material.specular"), 1); glUniform1i(glGetUniformLocation(lightingShader.Program, "material.emission"), 2); //set material //GLint matAmbientLoc = glGetUniformLocation(lightingShader.Program, "material.ambient"); //GLint matDiffuseLoc = glGetUniformLocation(lightingShader.Program, "material.diffuse"); GLint matSpecularLoc = glGetUniformLocation(lightingShader.Program, "material.specular"); GLint matShineLoc = glGetUniformLocation(lightingShader.Program, "material.shininess"); //glUniform3f(matAmbientLoc, 1.0f, 0.5f, 0.31f); //glUniform3f(matDiffuseLoc, 1.0f, 0.5f, 0.31f); glUniform3f(matSpecularLoc, 0.5f, 0.5f, 0.5f); glUniform1f(matShineLoc, 64.0f); while (!glfwWindowShouldClose(window)) { GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; glfwPollEvents(); do_movement(); glClearColor(0.9f, 0.9f, 0.9f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); lightingShader.Use(); glBindVertexArray(containerVAO); //set object color glUniform3f(glGetUniformLocation(lightingShader.Program, "objectColor"), 1.0f, 1.0f, 1.0f); //set light position glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[0].position"), pointLightPositions[0].x, pointLightPositions[0].y, pointLightPositions[0].z); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[1].position"), pointLightPositions[1].x, pointLightPositions[1].y, pointLightPositions[1].z); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[2].position"), pointLightPositions[2].x, pointLightPositions[2].y, pointLightPositions[2].z); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[3].position"), pointLightPositions[3].x, pointLightPositions[3].y, pointLightPositions[3].z); //set view position glUniform3f(glGetUniformLocation(lightingShader.Program, "viewPos"), camera.Position.x, camera.Position.y, camera.Position.z); //set light attenuation glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[0].constant"), 1.0f); glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[0].linear"), 0.07); glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[0].quadratic"), 0.017); glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[1].constant"), 1.0f); glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[1].linear"), 0.07); glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[1].quadratic"), 0.017); glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[2].constant"), 1.0f); glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[2].linear"), 0.07); glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[2].quadratic"), 0.017); glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[3].constant"), 1.0f); glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[3].linear"), 0.07); glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[3].quadratic"), 0.017); glUniform3f(glGetUniformLocation(lightingShader.Program, "dirLight.direction"), -0.2f, -1.0f, -0.3f); //set light ambient/diffuse/speculars glUniform3f(glGetUniformLocation(lightingShader.Program, "dirLight.ambient"), 0.5f,0.5f,0.5f); glUniform3f(glGetUniformLocation(lightingShader.Program, "dirLight.diffuse"), 1.0f, 1.0f, 1.0f); glUniform3f(glGetUniformLocation(lightingShader.Program, "dirLight.specular"), 1.0f, 1.0f, 1.0f); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[0].ambient"), 0.2f, 0.2f, 0.2f); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[0].diffuse"), 0.5f, 0.5f, 0.5f); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[0].specular"), 1.0f, 1.0f, 1.0f); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[1].ambient"), 0.2f, 0.2f, 0.2f); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[1].diffuse"), 0.5f, 0.5f, 0.5f); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[1].specular"), 1.0f, 1.0f, 1.0f); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[2].ambient"), 0.2f, 0.2f, 0.2f); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[2].diffuse"), 0.5f, 0.5f, 0.5f); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[2].specular"), 1.0f, 1.0f, 1.0f); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[3].ambient"), 0.2f, 0.2f, 0.2f); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[3].diffuse"), 0.5f, 0.5f, 0.5f); glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[3].specular"), 1.0f, 1.0f, 1.0f); //set spot light parameter // SpotLight glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight.position"), camera.Position.x, camera.Position.y, camera.Position.z); glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight.direction"), camera.Front.x, camera.Front.y, camera.Front.z); glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight.ambient"), 0.0f, 0.0f, 0.0f); glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight.diffuse"), 0.0f, 1.0f, 0.0f); glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight.specular"), 0.0f, 1.0f, 0.0f); glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight.constant"), 1.0f); glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight.linear"), 0.07); glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight.quadratic"), 0.017); glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight.cutOff"), glm::cos(glm::radians(7.0f))); glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight.outerCutOff"), glm::cos(glm::radians(10.0f))); // Create camera transformations glm::mat4 view; camera.Jump_Movement(deltaTime); view = camera.GetViewMatrix(); glm::mat4 projection = glm::perspective(camera.Zoom, (GLfloat)width / (GLfloat)height, 0.1f, 100.0f); // Get the uniform locations GLint modelLoc = glGetUniformLocation(lightingShader.Program, "model"); GLint viewLoc = glGetUniformLocation(lightingShader.Program, "view"); GLint projLoc = glGetUniformLocation(lightingShader.Program, "projection"); // Pass the matrices to the shader glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); // Bind diffuse map glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, diffuseMap); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, specularMap); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D,emissionMap); // Draw the container (using container's vertex attributes) glBindVertexArray(containerVAO); glm::mat4 model; glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); for (GLuint i = 0; i < 10; i++) { model = glm::mat4(); model = glm::translate(model, cubePositions[i]); GLfloat angle = 20.0f * i; model = glm::rotate(model, angle, glm::vec3(1.0f, 0.3f, 0.5f)); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); } glBindVertexArray(0); lightingShader_lamp.Use(); // Get location objects for the matrices on the lamp shader (these could be different on a different shader) modelLoc = glGetUniformLocation(lightingShader_lamp.Program, "model"); viewLoc = glGetUniformLocation(lightingShader_lamp.Program, "view"); projLoc = glGetUniformLocation(lightingShader_lamp.Program, "projection"); // Set matrices glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); for (GLuint i = 0; i < 4; i++) { model = glm::mat4(); model = glm::translate(model, pointLightPositions[i]); model = glm::scale(model, glm::vec3(0.2f)); // Make it a smaller cube glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); glBindVertexArray(lightVAO); glDrawArrays(GL_TRIANGLES, 0, 36); } glBindVertexArray(0); glfwSwapBuffers(window); } glfwTerminate(); return 0; } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GL_TRUE); } if (action == GLFW_PRESS) keys[key] = true; else if (action == GLFW_RELEASE) keys[key] = false; } void do_movement() { // Camera controls if (keys[GLFW_KEY_W]) camera.ProcessKeyboard(FORWARD, deltaTime); if (keys[GLFW_KEY_S]) camera.ProcessKeyboard(BACKWARD, deltaTime); if (keys[GLFW_KEY_A]) camera.ProcessKeyboard(LEFT, deltaTime); if (keys[GLFW_KEY_D]) camera.ProcessKeyboard(RIGHT, deltaTime); if (keys[GLFW_KEY_Q]) camera.ProcessKeyboard(UP, deltaTime); if (keys[GLFW_KEY_Z]) camera.ProcessKeyboard(DOWN, deltaTime);; if (keys[GLFW_KEY_SPACE]) camera.ProcessKeyboard(JUMP, deltaTime); } void mouse_callback(GLFWwindow* window, double xpos, double ypos) { if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } GLfloat xoffset = xpos - lastX; GLfloat yoffset = lastY - ypos; lastX = xpos; lastY = ypos; GLfloat sensitivity = 0.05f; xoffset *= sensitivity; yoffset *= sensitivity; camera.ProcessMouseMovement(xoffset, yoffset); } void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { camera.ProcessMouseScroll(yoffset); }
01a37961e8b7f22db3d6f29d2fb21bf9f9b5e4ef
[ "C++" ]
1
C++
WangXin93/LearnOpenGL-lightCourse
6910ef3c8e90da562e63474da4e89b7d4579635d
54ae470e43bf31bea8bd2057716e215c24880cd7
refs/heads/main
<repo_name>RascalTwo/TearDrops<file_sep>/bot/setup.py # TOKENS STUFF DISCORD_BOT_TOKEN = "" MONGO_TEARS = "" MONGO_TEARS_PASS = ""
15003aaac534841d756b9340ae66c8166c01e096
[ "Python" ]
1
Python
RascalTwo/TearDrops
16078c06ce32f3e25cc36a2b675000fc85d756e8
07dd083592efd81e759764a119581c688a3dc98e
refs/heads/master
<repo_name>miaozhenkai/OracleDBWalletDemo<file_sep>/src/main/java/com/mzk/oracledbwalletdemo/OracleDbWalletDemoApplication.java package com.mzk.oracledbwalletdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class OracleDbWalletDemoApplication { public static void main(String[] args) { SpringApplication.run(OracleDbWalletDemoApplication.class, args); } } <file_sep>/src/main/java/com/mzk/oracledbwalletdemo/controller/TestController.java package com.mzk.oracledbwalletdemo.controller; import com.mzk.oracledbwalletdemo.mapper.TestTblMapper; import com.mzk.oracledbwalletdemo.pojo.TestTbl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Map; /** * @author miaozhenkai * @version 2021-07-06 15:40 */ @RestController public class TestController { @Autowired TestTblMapper testTblMapper; @Value("${mybatis.mapper-locations}") private String title; @RequestMapping("/test") public Object test (@RequestBody Map<String, Object> param){ System.out.println(title); TestTbl testTbl = TestTbl.builder().name("name1").build(); int i = testTblMapper.insert(testTbl); System.out.println(testTbl); System.out.println(i); return ""; } } <file_sep>/src/main/java/com/mzk/oracledbwalletdemo/mapper/TestTblMapper.java package com.mzk.oracledbwalletdemo.mapper; import com.mzk.oracledbwalletdemo.pojo.TestTbl; import java.math.BigDecimal; import org.apache.ibatis.annotations.Mapper; /** * * @author miaozhenkai * @version 2021-07-06 15:39 */ @Mapper public interface TestTblMapper { int deleteByPrimaryKey(BigDecimal id); int insert(TestTbl record); int insertSelective(TestTbl record); TestTbl selectByPrimaryKey(BigDecimal id); int updateByPrimaryKeySelective(TestTbl record); int updateByPrimaryKey(TestTbl record); }<file_sep>/src/main/java/com/mzk/oracledbwalletdemo/pojo/TestTbl.java package com.mzk.oracledbwalletdemo.pojo; import java.io.Serializable; import java.math.BigDecimal; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * * @author miaozhenkai * @version 2021-07-06 15:39 */ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class TestTbl implements Serializable { private BigDecimal id; private String name; private static final long serialVersionUID = 1L; }
8d0dc2d4eae874863ab820cf23960fc67a808c0b
[ "Java" ]
4
Java
miaozhenkai/OracleDBWalletDemo
41a76d046a1ea8dac6b332ec0b605403a03c2feb
7dea9bb7812eaabd720d1327fac08f4d2b07a60a
refs/heads/master
<file_sep>from flask import Flask, render_template, request import csv app = Flask(__name__) @app.route('/') def home_page(): return render_template('index.html') def write_csv(data): with open('email-database.csv', mode='a', newline='') as database: email = data["email"] csv_writer = csv.writer(database, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) csv_writer.writerow([email]) @app.route('/signup', methods=['POST']) def sign_up(): error = None if request.method == 'POST': html_data = request.form.to_dict() write_csv(html_data) else: return 'Something\'s gone horribly wrong!'
2574d12ba820d1965ea63e5659a898eb4770d5d0
[ "Python" ]
1
Python
gandhirutul/teaser-website
9e8328d3e9a83586f3bc9f17b01fcfb34521d308
b3dd0ff480564fb54ccdc075865b8b13cc5b2e7d
refs/heads/master
<file_sep>import logging logging.basicConfig(level=logging.INFO, format='%(module)s:%(lineno)d [%(threadName)s] [%(levelname)-5.5s] %(message)s', handlers=[logging.FileHandler('logger.log', mode='a'), logging.StreamHandler()]) logger = logging.getLogger('logger') def setLevel(level): global logger if level == 'debug': level = logging.DEBUG elif level == 'info': level = logging.INFO else: level = logging.WARNING logger.setLevel(level) <file_sep>import threading import time import numpy import torch import Logger from ExperienceCollector import ExperienceCollector from ReplayMemory import ReplayMemory from SimulatorFactory import SimulatorFactory logger = Logger.logger def to_one_hot(indices, n_classes): one_hot = torch.zeros(len(indices), n_classes) one_hot[torch.arange(len(indices)), indices.to(torch.long).squeeze()] = 1 return one_hot class DQN(object): def __init__(self, network): self.experienceCollectors = [] self.threadSync = None self.stopSyncThread = False self.network = network def syncNetwork(self): while not self.stopSyncThread: for experienceCollector in self.experienceCollectors: logger.info('Syncing policy network with %s', experienceCollector.name) experienceCollector.lock.acquire() try: experienceCollector.network = self.network.copy() finally: experienceCollector.lock.release() time.sleep(2) logger.info('Stopped thread: Network Sync') def train(self, args): # Parameters gamma = args.gamma device = args.device simulator = SimulatorFactory.getInstance(args.simulator, args) dStates = numpy.prod(simulator.dState()) nActions = simulator.nActions() # Initialise Metrics metrics = { 'test_set': [], 'best_test_performance': -numpy.inf } # initialise a test set logger.info('Loading test set') test = [] for i in range(args.testSize): test.append(simulator.reset()) logger.info('Test set loaded!') test = torch.Tensor(test).to(device) self.experienceCollectors = [ExperienceCollector(i, self.network, args) for i in range(args.threads)] self.threadSync = threading.Thread(target=self.syncNetwork, name='SyncThread') self.threadSync.start() logger.info('Started thread: Network Sync') # Wait while ReplayMemory collects some experiences. while ReplayMemory.memoryEmpty: time.sleep(0.1) policyNetwork = self.network.to(device) targetNetwork = policyNetwork.copy().to(device) # initialise optimiser and loss function optimiser = torch.optim.Adam(policyNetwork.parameters(), lr=args.lr, weight_decay=1e-4) lossFn = torch.nn.MSELoss() itr = 0 while args.itr == 0 or itr < args.itr: itr += 1 if itr % args.frequency == 0: targetNetwork = policyNetwork.copy().to(device) # OPTIMIZE POLICY batch = ReplayMemory.sample(args.batchSize) # slice them to get state and actions batch = torch.Tensor(batch).to(device) state, action, next_state, reward, terminate = torch.split(batch, [dStates, 1, dStates, 1, 1], dim=1) action = to_one_hot(action, nActions).to(device) state = simulator.prettifyState(state).to(device) next_state = simulator.prettifyState(next_state).to(device) # find the target value target = reward + terminate * gamma * targetNetwork(next_state).max(dim=1)[0].unsqueeze(dim=1) # Calculate Q value predicted = (policyNetwork(state) * action).sum(dim=1).unsqueeze(dim=1) # find loss loss = lossFn(predicted, target) # Backprop optimiser.zero_grad() loss.backward() # Clip gradients to avoid exploding gradients torch.nn.utils.clip_grad.clip_grad_value_(policyNetwork.parameters(), 5) optimiser.step() # Terminate episode if contribution of next state is small. # Store Evaluation Metrics metrics['test_set'].append(policyNetwork(test).max(dim=1)[0].mean().item()) # Print statistics logger.info('[Iteration: %s] Test Q-values: %s', itr, metrics['test_set'][-1]) # Checkpoints if metrics['test_set'][-1] > metrics['best_test_performance']: metrics['best_test_performance'] = metrics['test_set'][-1] policyNetwork.save(args.networkPath) if args.checkpoints: policyNetwork.save('checkpoints/Q_network_{}.pth'.format(metrics['test_set'][-1])) def stop(self): for collector in self.experienceCollectors: collector.stop() self.stopSyncThread = True if self.threadSync is not None: self.threadSync.join() <file_sep>import threading import numpy import torch import Logger from ReplayMemory import ReplayMemory from SimulatorFactory import SimulatorFactory logger = Logger.logger class ExperienceCollector(object): def __init__(self, id, network, args): self.network = network self.args = args self.name = 'ExperienceCollector_{}'.format(id) self.stopThread = False self.lock = threading.Lock() self.thread = threading.Thread(target=self.collect, name=self.name) self.thread.start() logger.info('Started thread: %s', self.name) def collect(self): # Parameters eps = self.args.eps gamma = self.args.gamma device = self.args.device simulator = SimulatorFactory.getInstance(self.args.simulator, self.args) buffer = ReplayMemory(self.args.memory) itr = 0 while not self.stopThread: eps = max(0.1, eps ** itr) done = False episodeReward = 0 episodeLength = 0 self.lock.acquire() try: policyNetwork = self.network.to(device) # Reset simulator for new episode logger.debug('Starting new episode') state = simulator.reset() while not done and not self.stopThread: action = simulator.sampleAction() if numpy.random.rand() > eps: action = policyNetwork(torch.Tensor(state).to(device)).argmax().item() # take action and get next state nextState, reward, done, _ = simulator.step(action) # store into experience memory buffer.push(state, action, nextState, reward, int(not done)) state = nextState episodeReward += reward * gamma ** episodeLength episodeLength += 1 if gamma ** episodeLength < 0.1: break logger.debug('Episode Length: %s \tEpisode Reward: %s', episodeLength, episodeReward) finally: self.lock.release() buffer.stop() logger.info('Stopped thread: %s', self.name) def stop(self): self.stopThread = True self.thread.join() <file_sep>matplotlib numpy scipy torch torchtext torchvision tqdm <file_sep>from .CarlaSimulator import * <file_sep>import random import threading import time import numpy import Logger logger = Logger.logger class ReplayMemory(object): memory = [] lock = threading.Lock() memoryEmpty = True def __init__(self, size): self.size = size self.position = 0 self.buffer = [] self.shutdownSync = False self.syncThread = threading.Thread(target=self.sync, name='ReplayMemorySync_{}'.format(id(self))) self.syncThread.start() logger.info('Started thread: Memory Sync') def sync(self): while not self.shutdownSync: ReplayMemory.lock.acquire() logger.debug('Syncing memory.') try: ReplayMemory.memory = ReplayMemory.memory + self.buffer ReplayMemory.memory = ReplayMemory.memory[:self.size] self.buffer = [] logger.debug('Syncing finished.') finally: ReplayMemory.lock.release() if len(ReplayMemory.memory) > 0: ReplayMemory.memoryEmpty = False time.sleep(2) logger.info('Stopped thread: Memory Sync') def push(self, state, action, next_state, reward, terminate): # Combine the experience into 1 big array and store it on next position. Ordering is important ReplayMemory.lock.acquire() try: self.buffer.append(numpy.hstack((state.reshape(-1), action, next_state.reshape(-1), reward, terminate))) finally: ReplayMemory.lock.release() @staticmethod def sample(batch_size): # Change batch size if memory is not big enough batch_size = min(batch_size, len(ReplayMemory.memory)) # Return a sampled batch return random.sample(ReplayMemory.memory, batch_size) def stop(self): self.shutdownSync = True self.syncThread.join() <file_sep>import random import time import numpy import carla from constants import * from simulator.ISimulator import ISimulator # Random spawn location. # These numbers are valid for only a particular junction scenario. def random_location(rand): # Spawn on left side if rand < 0.5: return carla.Transform(carla.Location(x=random.randint(20, 60), y=random.choice([130.5, 127.5]), z=0.2), carla.Rotation(yaw=180)) # Spawn on right side else: return carla.Transform(carla.Location(x=-random.randint(20, 60), y=random.choice([134.5, 137.5]), z=0.2), carla.Rotation(yaw=0)) class CarlaSimulator(ISimulator): def __init__(self, args): super().__init__(args) self.collided = True self.nVehicles = args.nVehicles self.av = None self.gridSensor = None self.collisionSensor = None self.vehicles = [] self.frames = [] # initialise Carla client self.world = carla.Client(args.host, args.port).get_world() self.bplib = self.world.get_blueprint_library() def reset(self): self.destroy() # Spawn Autonomous car. # Spawn position is random in a certain range. Numbers valid for only particular junction. self.av = self.world.spawn_actor(self.bplib.find('vehicle.tesla.model3'), carla.Transform(carla.Location(-6, random.randint(100, 120), 0), carla.Rotation(yaw=90))) # Apply brake as default control self.av.apply_control(carla.VehicleControl(brake=1)) # Spawn Camera camera_properties = self.bplib.find('sensor.camera.semantic_segmentation') camera_properties.set_attribute('fov', '110') camera_properties.set_attribute('image_size_x', str(IMG_WIDTH)) camera_properties.set_attribute('image_size_y', str(IMG_HEIGHT)) camera_properties.set_attribute('sensor_tick', str(1 / FREQUENCY)) self.gridSensor = self.world.spawn_actor(camera_properties, carla.Transform(carla.Location(0, 132, 40), carla.Rotation(roll=90, pitch=-90)), attach_to=self.av) self.gridSensor.listen(lambda image: self.new_frame(image)) # Choose a random number of NPC to spawn vehicles_to_spawn = random.randint(1, self.nVehicles) tries = 0 while vehicles_to_spawn > 0 or tries < vehicles_to_spawn * 10: # Spawn NPC vehicle = self.world.try_spawn_actor(self.bplib.find('vehicle.audi.a2'), random_location(numpy.random.rand())) # if spawning failed, retry if vehicle is None: continue self.vehicles.append(vehicle) vehicles_to_spawn -= 1 tries += 1 # Spawn Collision detector. self.collisionSensor = self.world.spawn_actor(self.bplib.find('sensor.other.collision'), carla.Transform(), attach_to=self.av) self.collisionSensor.listen(lambda x: self.onCollision()) self.collided = False # Wait for the simulator to get ready time.sleep(1 / FREQUENCY) return self.state() def step(self, a): # apply default control to NPCs for vehicle in self.vehicles: vehicle.apply_control(carla.VehicleControl(throttle=0.5)) # apply action to AV self.av.apply_control(carla.VehicleControl(throttle=THROTTLE[a], brake=BRAKE[a], manual_gear_shift=True, gear=1)) # sleep to observe action's effect time.sleep(1 / FREQUENCY) # calculate reward (\Delta s + collision penalty) reward = self.av.get_velocity().y * (-100 if self.collided else 1) - 1 return self.state(), reward, self.collided, None def onCollision(self): self.collided = True def new_frame(self, frame): # Parse the new BGRA frame frame = numpy.asarray(frame.raw_data).reshape(IMG_HEIGHT, IMG_WIDTH, 4) # filter out only R channel frame = frame[:, :, 2] # Mask pixels not containing cars or roads mask = (frame == 7) + (frame == 10) frame = frame * mask frame = frame.astype(numpy.float) # Change pixel label to -1 for Roads frame[frame == 7] = -1 # Change pixel label to 1 for Cars frame[frame == 10] = 1 # Append the new frame at the last self.frames.append(frame) # Duplicate the existing frames if size is less than nFRAMES while len(self.frames) < nFRAMES: self.frames.append(self.frames[-1]) # Trim the list to keep only last nFRAMES. self.frames = self.frames[-nFRAMES:] def state(self): # Convert the frames into array of shape (nFRAMES, IMG_HEIGHT, IMG_WIDTH) return numpy.reshape(self.frames, (nFRAMES, IMG_HEIGHT, IMG_WIDTH)) def nActions(self): return len(THROTTLE) def dState(self): return nFRAMES, IMG_HEIGHT, IMG_WIDTH def sampleAction(self): return numpy.random.randint(self.nActions()) def prettifyState(self, rawState): C, H, W = self.dState() return rawState.reshape(-1, C, H, W) def destroy(self): if self.collisionSensor is not None: self.collisionSensor.destroy() if self.gridSensor is not None: self.gridSensor.destroy() for actor in self.world.get_actors(): if 'vehicle' in actor.type_id or 'sensor' in actor.type_id: actor.destroy() self.av = None self.gridSensor = None self.collisionSensor = None self.vehicles = [] def __del__(self): self.destroy() <file_sep>import torch import torch.nn as nn import Logger # Custom layer to flatten the output in 1-D vector class Flatten(nn.Module): def forward(self, input): return input.view(input.size(0), -1) class QNetwork(nn.Module): def __init__(self, inDims, outDims): super(QNetwork, self).__init__() self.inDims = inDims self.outDims = outDims C, H, W = inDims self.net = nn.Sequential( nn.Conv2d(C, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3)), nn.ReLU(), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(64, 64, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2)), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2), Flatten(), nn.Linear(in_features=512, out_features=512), nn.ReLU(), nn.Linear(in_features=512, out_features=512), nn.ReLU(), nn.Linear(in_features=512, out_features=outDims) ) def forward(self, x): return self.net(x) def save(self, filename): # Switch network to CPU before saving to avoid issues. Logger.logger.debug('Saving network to %s', filename) torch.save(self.cpu().state_dict(), filename) def load(self, filename): # Load state dictionary from saved file Logger.logger.debug('Loading network from %s', filename) self.load_state_dict(torch.load(filename, map_location='cpu')) def copy(self, freeze=True): # Create a copy of self copied = QNetwork(self.inDims, self.outDims) copied.load_state_dict(self.state_dict()) # Freeze its parameters if freeze: for params in copied.parameters(): params.requires_grad = False return copied <file_sep>import argparse import os import Logger from SimulatorFactory import SimulatorFactory from DQN import DQN from QNetwork import QNetwork parser = argparse.ArgumentParser() parser.add_argument('--simulator', dest='simulator', help='Simulator class name', required=True) parser.add_argument('--network', dest='networkPath', help='Path to the save trained network', required=True) parser.add_argument('--vehicles', dest='nVehicles', help='Number of Vehicles', default=10, type=int) parser.add_argument('--host', dest='host', help='Host address of the carla server', default='localhost') parser.add_argument('--port', dest='port', help='Port of the carla server', default=2000, type=int) parser.add_argument('--lr', dest='lr', default=1e-4, help='', type=float) parser.add_argument('--eps', dest='eps', default=0.999, type=float) parser.add_argument('--batch', dest='batchSize', default=32, type=int) parser.add_argument('--itr', dest='itr', default=0, type=int, help='Number of iterations for training [0 for infinite]') parser.add_argument('--threads', dest='threads', default=4, type=int) parser.add_argument('--gamma', dest='gamma', default=0.99, type=float) parser.add_argument('--frequency', dest='frequency', default=50, type=int) parser.add_argument('--memory', dest='memory', default=10000, type=int, help='Buffer size (in number of experiences)') parser.add_argument('--logger', dest='logger', help='Logging sensitivity', default='info') parser.add_argument('--test_size', dest='testSize', help='Size of test set', default=1, type=int) parser.add_argument('--device', dest='device', help='[cpu, cuda]', default='cpu') parser.add_argument('--checkpoints', dest='checkpoints', action='store_true', default=False, help='store checkpoints') args = parser.parse_args() Logger.setLevel(args.logger) logger = Logger.logger logger.info('List of Parameters:\n' 'simulator: %s\n' 'networkPath: %s\n' 'lr: %s\n' 'batchSize: %s\n' 'itr: %s\n' 'eps: %s\n' 'gamma: %s\n' 'memory: %s\n' 'frequency: %s\n' 'testsize: %s\n' 'device: %s\n' 'threads:%s\n' 'checkpoints:%s\n' 'logger: %s\n', args.simulator, args.networkPath, args.lr, args.batchSize, args.itr, args.eps, args.gamma, args.memory, args.frequency, args.testSize, args.device, args.threads, args.checkpoints, args.logger) if __name__ == '__main__': if args.checkpoints and not os.path.exists('checkpoints'): os.makedirs('checkpoints') simulator = SimulatorFactory.getInstance(args.simulator, args) trainer = DQN(QNetwork(simulator.dState(), simulator.nActions())) try: logger.info('Starting training.') trainer.train(args) except KeyboardInterrupt: logger.info('KeyboardInterrupt received. Trying to stop threads.') finally: trainer.stop() simulator.destroy() <file_sep>import argparse import torch import Logger from QNetwork import QNetwork from SimulatorFactory import SimulatorFactory parser = argparse.ArgumentParser() parser.add_argument('--simulator', dest='simulator', help='Simulator class name', required=True) parser.add_argument('--network', dest='networkPath', help='Path to the saved network file', required=True) parser.add_argument('--device', dest='device', help='[cpu, cuda]', default='cpu') parser.add_argument('--logger', dest='logger', help='Logging sensitivity', default='info') args = parser.parse_args() Logger.setLevel(args.logger) logger = Logger.logger logger.info('List of Parameters:\n' 'simulator: %s\n' 'networkPath: %s\n' 'device: %s\n' 'logger: %s\n', args.simulator, args.networkPath, args.device, args.logger) if __name__ == '__main__': simulator = SimulatorFactory.getInstance(args.simulator) network = QNetwork(simulator.dState(), simulator.nActions()) network.load(args.networkPath) network.to(args.device) logger.info('Starting simulation') state = simulator.reset() done = False episodeLength = 0 while not done: episodeLength += 1 action = network(torch.Tensor(state).to(args.device)).argmax().item() state, reward, done, _ = simulator.step(action) logger.info('Reward received: %s', reward) logger.info('Episode complete. Length: %s', episodeLength) <file_sep>import Logger from simulator import * class SimulatorFactory(object): @staticmethod def getInstance(className, args): Logger.logger.info('Instance requested for class %s', className) return globals()[className](args) <file_sep># Navigation-DQN A Deep Q-Network trained to safely guide the autonomous car to cross a 4-way intersection in a complex traffic environment. # Requirements * Python 3 * PyTorch (https://pytorch.org) * Carla (http://carla.org) # Installation ```shell $ python3 -m venv .env $ source .env/bin/activate $ pip install -r requirements.txt ``` # Simulator * Download Carla simulator binary files (https://github.com/carla-simulator/carla/releases). * Extract the .tar file to `<location>` * Start the simulator by ```shell $ ./<location>/CarlaUE4.sh Town03 ``` * To go to simulation site, go towards the left side from the spawned location (using keys WASDQE and mouse pointer) # Training If you have a pretrained file ```shell $ source .env/bin/activate $ python3 trainer.py. --n_vehicles 10 --network <path to file> ``` else ```shell $ source .env/bin/activate $ python3 trainer.py. --n_vehicles 10 ``` # Testing ```shell $ source .env/bin/activate $ python3 tester.py. --n_vehicles 10 --network <path to file> ``` # GPU It is recommended to use GPU for training and inference. # Video Demo https://www.youtube.com/watch?v=drVe_pNmuGc <file_sep>import random import numpy as np import carla import time from constants import * # Random spawn location. # These numbers are valid for only a particular junction scenario. def random_location(rand): # Spawn on left side if rand < 0.5: return carla.Transform(carla.Location(x=random.randint(20, 60), y=random.choice([130.5, 127.5]), z=0.2), carla.Rotation(yaw=180)) # Spawn on right side else: return carla.Transform(carla.Location(x=-random.randint(20, 60), y=random.choice([134.5, 137.5]), z=0.2), carla.Rotation(yaw=0)) class Simulator(object): # Simulator state collided = False frames = [] def __init__(self, args): # initialise Carla client self.world = carla.Client(args.host, args.port).get_world() self.bplib = self.world.get_blueprint_library() self.n_vehicles = args.n_vehicles self.autocar = None self.av_sensor = None self.collision_sensor = None self.vehicles = [] self.actors = [] def reset(self): self.destroy() # Spawn Autonomous car. # Spawn position is random in a certain range. Numbers valid for only particular junction. self.autocar = self.world.spawn_actor(self.bplib.find('vehicle.tesla.model3'), carla.Transform(carla.Location(5, random.randint(100, 120), 0.2), carla.Rotation(yaw=90))) # Apply brake as default control self.autocar.apply_control(carla.VehicleControl(brake=1)) self.actors.append(self.autocar) # Spawn Camera # Choose between rgb and semantic segmentation # camera_properties = self.bplib.find('sensor.camera.rgb') camera_properties = self.bplib.find('sensor.camera.semantic_segmentation') camera_properties.set_attribute('fov', '110') camera_properties.set_attribute('image_size_x', str(IMG_WIDTH)) camera_properties.set_attribute('image_size_y', str(IMG_HEIGHT)) camera_properties.set_attribute('sensor_tick', str(1 / FREQUENCY)) self.av_sensor = self.world.spawn_actor(camera_properties, carla.Transform(carla.Location(0, 132, 40), carla.Rotation(roll=90, pitch=-90)), attach_to=self.autocar ) self.av_sensor.listen(lambda image: Simulator.new_frame(image)) self.actors.append(self.av_sensor) # Choose a random number of NPC to spawn vehicles_to_spawn = random.randint(1, self.n_vehicles) tries = 0 while vehicles_to_spawn > 0 or tries < vehicles_to_spawn * 10: # Spawn NPC vehicle = self.world.try_spawn_actor(self.bplib.find('vehicle.audi.a2'), random_location(np.random.rand())) # if spawning failed, retry if vehicle is None: continue self.vehicles.append(vehicle) self.actors.append(vehicle) vehicles_to_spawn -= 1 tries += 1 # Spawn Collision detector. self.collision_sensor = self.world.spawn_actor(self.bplib.find('sensor.other.collision'), carla.Transform(), attach_to=self.autocar) self.collision_sensor.listen(lambda x: Simulator.on_collision()) self.actors.append(self.collision_sensor) Simulator.collided = False # Wait for the simulator to get ready time.sleep(1 / FREQUENCY) return Simulator.state() def step(self, action): # apply default control to NPCs for vehicle in self.vehicles: vehicle.apply_control(carla.VehicleControl(throttle=0.5)) # Note old AV location to calculate reward old_y = self.autocar.get_location().y # apply action to AV self.autocar.apply_control(carla.VehicleControl(throttle=THROTTLE[action], brake=BRAKE[action])) # sleep to observe action's effect time.sleep(1 / FREQUENCY) # calculate reward (\Delta s + collision penalty) reward = (self.autocar.get_location().y - old_y) + (-100 if Simulator.collided else 0) return {'state': self.state(), 'reward': reward, 'terminate': Simulator.collided} @staticmethod def on_collision(): Simulator.collided = True @staticmethod # For RGB images. # Uncomment this block if you want to use RGB images. You need to set nCHANNELS=3 in constants.py # Comment it if you want to use Semantically Segmented images. # def new_frame(frame): # # append the frame at the end # frame = np.asarray(frame.raw_data).reshape(IMG_HEIGHT, IMG_WIDTH, 4) # frame = frame[:, :, [2, 1, 0]].transpose((2, 0, 1)) # Simulator.frames.append(frame) # while len(Simulator.frames) < nFRAMES: # Simulator.frames.append(Simulator.frames[-1]) # # trim the list to keep only last 3 frames. # Simulator.frames = Simulator.frames[-nFRAMES:] # For Semantically Segmented images. # Uncomment this block if you want to use Semantically Segmented images. You need to set nCHANNELS=1 in constants.py # Comment it if you want to use RGB images. def new_frame(frame): # Parse the new BGRA frame frame = np.asarray(frame.raw_data).reshape(IMG_HEIGHT, IMG_WIDTH, 4) # filter out only R channel frame = frame[:, :, 2] # Mask pixels not containing cars or roads mask = (frame == 7) + (frame == 10) frame = frame * mask frame = frame.astype(np.float) # Change pixel label to -1 for Roads frame[frame == 7] = -1 # Change pixel label to 1 for Cars frame[frame == 10] = 1 # Append the new frame at the last Simulator.frames.append(frame) # Duplicate the existing frames if size is less than nFRAMES while len(Simulator.frames) < nFRAMES: Simulator.frames.append(Simulator.frames[-1]) # Trim the list to keep only last nFRAMES. Simulator.frames = Simulator.frames[-nFRAMES:] @staticmethod def sample_action(): # Sample a random action return np.random.randint(nACTIONS) @staticmethod def state(): # Convert the frames into array of shape (nCHANNELS * nFRAMES, IMG_HEIGHT, IMG_WIDTH) return np.asarray(Simulator.frames).reshape(nCHANNELS * nFRAMES, IMG_HEIGHT, IMG_WIDTH) def destroy(self): # Destroy every spawned actor for actor in self.actors: actor.destroy() self.actors = [] self.vehicles = [] def __del__(self): self.destroy() <file_sep>from abc import abstractmethod class ISimulator(object): def __init__(self, args): self.args = args @abstractmethod def reset(self): raise NotImplementedError @abstractmethod def step(self, a): raise NotImplementedError @abstractmethod def nActions(self): raise NotImplementedError # shape of the environment state [int for vector state; (tuple) for image] @abstractmethod def dState(self): raise NotImplementedError @abstractmethod def sampleAction(self): raise NotImplementedError @abstractmethod def prettifyState(self, rawState): raise NotImplementedError <file_sep># Image parameters IMG_WIDTH = 256 IMG_HEIGHT = 144 nFRAMES = 3 # Car control parameters THROTTLE = [0, 0.5] BRAKE = [0.8, 0] # Environment parameters nACTIONS = 2 FREQUENCY = 2 # in Hz
11937152753d9394717045945bb1683a2cfa902a
[ "Markdown", "Python", "Text" ]
15
Python
dixantmittal/Navigation-DQN
81bb16c82a7d5bdd50cc909b0eff3b0ea2e27374
dac305be3141561e3fd5ea537aa1fa7f5226693d
refs/heads/main
<file_sep>using Blazored.Toast.Services; using Microsoft.AspNetCore.Components; namespace Blazored.Toast.TestExtensions { public class InMemoryToast { public ToastLevel ToastLevel { get; } public RenderFragment Message { get; } public string Heading { get; } public InMemoryToast(ToastLevel toastLevel, RenderFragment message, string heading) { ToastLevel = toastLevel; Message = message; Heading = heading; } } } <file_sep>using Blazored.Toast; using Blazored.Toast.Services; using Bunit; using System.Linq; using Xunit; namespace bUnitExample { public class BlazoredToastTests : TestContext { [Fact] public void DisplaysToast() { // Arrange var toastService = this.AddBlazoredToast(); var cut = RenderComponent<BlazorWebAssembly.Pages.Index>(); // Act cut.Find("#InfoButton").Click(); // Assert Assert.Equal(1, toastService.Toasts.Count); } [Fact] public void DisplaysZeroToasts() { // Arrange Act var toastService = this.AddBlazoredToast(); RenderComponent<BlazorWebAssembly.Pages.Index>(); // Assert Assert.Equal(0, toastService.Toasts.Count); } [Fact] public void DisplaysTwoToasts() { // Arrange var toastService = this.AddBlazoredToast(); var cut = RenderComponent<BlazorWebAssembly.Pages.Index>(); // Act var button = cut.Find("#InfoButton"); button.Click(); button.Click(); // Assert Assert.Equal(2, toastService.Toasts.Count); } [Fact] public void DisplaysToastWithLevel() { // Arrange var toastService = this.AddBlazoredToast(); var cut = RenderComponent<BlazorWebAssembly.Pages.Index>(); // Act cut.Find("#InfoButton").Click(); // Assert Assert.Equal(ToastLevel.Info, toastService.Toasts.Single().ToastLevel); } [Fact] public void DisplaysToastWithHeading() { // Arrange var toastService = this.AddBlazoredToast(); var cut = RenderComponent<BlazorWebAssembly.Pages.Index>(); // Act cut.Find("#SuccessButton").Click(); // Assert Assert.Equal("Congratulations!", toastService.Toasts.Single().Heading); } [Fact] public void DisplaysTwoToastsWithLevel() { // Arrange var toastService = this.AddBlazoredToast(); var cut = RenderComponent<BlazorWebAssembly.Pages.Index>(); // Act cut.Find("#InfoButton").Click(); cut.Find("#SuccessButton").Click(); // Assert Assert.Collection(toastService.Toasts, _ => Assert.Equal(ToastLevel.Info, _.ToastLevel), _ => Assert.Equal(ToastLevel.Success, _.ToastLevel)); } [Fact] public void DisplaysTwoToastsWithHeading() { // Arrange var toastService = this.AddBlazoredToast(); var cut = RenderComponent<BlazorWebAssembly.Pages.Index>(); // Act cut.Find("#InfoButton").Click(); cut.Find("#SuccessButton").Click(); // Assert Assert.Collection(toastService.Toasts, _ => Assert.Equal("Info", _.Heading), _ => Assert.Equal("Congratulations!", _.Heading)); } [Fact] public void DisplaysToasts() { // Arrange var toastService = this.AddBlazoredToast(); var cut = RenderComponent<BlazorWebAssembly.Pages.Index>(); // Act cut.Find("#InfoButton").Click(); cut.Find("#SuccessButton").Click(); // Assert Assert.NotEmpty(toastService.Toasts); } } }
bd6da661c8a37968bf10c943860d6233acee002e
[ "C#" ]
2
C#
titobf/Toast
80037fdc0d0c641beccc353e6517ffb961ed4746
d7f3e8e8cfacd99859796509339550356c4d04d9
refs/heads/master
<repo_name>bdog72/GitHub-Battle<file_sep>/unused.files/components/Home.js import React, { Component } from 'react' import { Link } from 'react-router-dom' import '../styles/home.scss' export default class Home extends Component { render () { return <div className='home-container'> <h1>GITHUB BATTLE: Battle your friends...</h1> <Link className='button' to='/battle'> Battle </Link> </div> } }
a9b8fbfd02a08f8a706ab75a2709945dc1ed917f
[ "JavaScript" ]
1
JavaScript
bdog72/GitHub-Battle
9b1e0f0a18bb9d3426fa132674d750c063087cb8
b825f8e3b2f091b47c2da9edf4490c386045eb85
refs/heads/master
<repo_name>huang-tianwen/latest_trying<file_sep>/src/AppBundle/Entity/Project.php <?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; use AppBundle\Entity\Collaborator; use JMS\Serializer\SerializerBuilder; use JMS\Serializer\Annotation\ExclusionPolicy; use JMS\Serializer\Annotation\Expose; use JMS\Serializer\Annotation as JMS; /** * @ORM\Entity * @ORM\Table(name="project") * @ExclusionPolicy("all") */ class Project { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") * @Expose */ protected $id; /** * @ORM\Column(type="string") */ protected $name; /** * @ORM\Column(type="date") */ protected $start_date; /** * @ORM\Column(type="date") */ protected $completion_date; /** * @ORM\Column(type="integer") */ protected $working_time; /** * @ORM\ManyToOne(targetEntity="Individual", inversedBy="projects") * @ORM\JoinColumn(name="individual_id", referencedColumnName="user_id") */ protected $individual; /** * @ORM\Column(type="json_array") * */ protected $project_outcomes; /** * @ORM\Column(type="array") * @JMS\Type("ArrayCollection<AppBundle\Entity\Collaborator>") */ protected $collaborators; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * * @return Project */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set completionDate * * @param string $completionDate * * @return Project */ public function setCompletionDate($completionDate) { $this->completion_date = $completionDate; return $this; } /** * Get completionDate * * @return string */ public function getCompletionDate() { return $this->completion_date; } /** * Set workingTime * * @param integer $workingTime * * @return Project */ public function setWorkingTime($workingTime) { $this->working_time = $workingTime; return $this; } /** * Get workingTime * * @return integer */ public function getWorkingTime() { return $this->working_time; } /** * Set individual * * @param \AppBundle\Entity\Individual $individual * * @return Project */ public function setIndividual(\AppBundle\Entity\Individual $individual = null) { $this->individual = $individual; return $this; } /** * Constructor */ public function __construct() { $this->collaborators = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get individual * * @return \AppBundle\Entity\Individual */ public function getIndividual() { return $this->individual; } /** * Set projectOutcomes * * @param array $projectOutcomes * * @return Project */ public function setProjectOutcomes($projectOutcomes) { $this->project_outcomes = $projectOutcomes; return $this; } /** * Get projectOutcomes * * @return array */ public function getProjectOutcomes() { return $this->project_outcomes; } public function __toString() { return $this->name; } /** * Set startDate * * @param \DateTime $startDate * * @return Project */ public function setStartDate($startDate) { $this->start_date = $startDate; return $this; } /** * Get startDate * * @return \DateTime */ public function getStartDate() { return $this->start_date; } /** * Add collaborator * * @param \AppBundle\Entity\Collaborator $collaborator * * @return Project */ public function addCollaborator(\AppBundle\Entity\Collaborator $collaborator) { var_dump($collaborator); $this->collaborators->add($collaborator); } /** * Remove collaborator * * @param \AppBundle\Entity\Collaborator $collaborator */ public function removeCollaborator(\AppBundle\Entity\Collaborator $collaborator) { $this->collaborators->removeElement($collaborator); } /** * Get collaborator * * @return \Doctrine\Common\Collections\Collection */ public function getCollaborators() { // var_dump($this->collaborators); return $this->collaborators; } // /** // * Set collaborators // * // * @param array $collaborators // * @return Project // */ // public function setCollaborators($collaborators) // { // // var_dump($collaborators->toArray()); // $this->collaborators = $collaborators ; // // var_dump($this->collaborators[0]); // // // print_r($this->collaborators); // // // return $this->collaborators; // // $serializer = SerializerBuilder::create()->build(); // // // // $this->collaborators = $serializer->serialize($collaborators, 'json'); // // // return $this->collaborators; // } // // /** // * Get collaborators // * @return array // */ // public function getCollaborators() // { // return ($this->collaborators); // // $data = $this->manager->getRepository('AppBundle:Collaborator')->find($data->getId()); // // //here seems to have some bugs // // if(count(json_decode($this->collaborators)) == 0) { // // return null; // // } // // else { // // $serializer = SerializerBuilder::create()->build(); // // // // $object = $serializer->deserialize($this->collaborators, 'ArrayCollection<AppBundle\Entity\Collaborator>', 'json'); // // // $em = $this->getDoctrine()->getManager(); // // // $data = $em->getRepository('AppBundle:Collaborator')->findOneBy($data->getId()); // // $data = new \Doctrine\Common\Collections\ArrayCollection($object); // // var_dump($data); // // return $data; // // } // } } <file_sep>/src/AppBundle/Controller/FormController.php <?php // in AppBundle/Controller/VehicleController.php namespace AppBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Routing\Annotation\Route; use AppBundle\Entity\Individual; use AppBundle\Entity\Project; use AppBundle\Entity\Collaborator; use AppBundle\Form\Type\CollaboratorCustomType; use Doctrine\Common\Collections\ArrayCollection; use AppBundle\Form\Type\CollaboratorType; use FOS\UserBundle\Entity\UserManager; use JMS\Serializer\SerializerBuilder; use JMS\Serializer\Annotation\ExclusionPolicy; use JMS\Serializer\Annotation\Expose; use JMS\Serializer\Annotation as JMS; class FormController extends Controller { /** * @Route("/", name="form") */ public function createFormAction() { $userId = $this->getUser()->getId(); $individual = $this->getDoctrine()->getRepository('AppBundle:Individual')->find($userId); if($individual){ return $this->redirect($this->generateUrl('edit')); } $formData = new Individual(); // Your form data class. Has to be an object, won't work properly with an array. $formData->setId($this->getUser()); $project = new Project(); $formData->addProject($project); $flow = $this->get('form.flow.createForm'); // must match the flow's service id $flow->bind($formData); // form of the current step $form = $flow->createForm(); if ($flow->isValid($form)) { $flow->saveCurrentStepData($form); if ($flow->nextStep()) { // form for the next step $form = $flow->createForm(); } else { // flow finished $em = $this->getDoctrine()->getManager(); $em->persist($formData); $em->flush(); $flow->reset(); // remove step data from the session return $this->redirect($this->generateUrl('edit')); // redirect when done } } return $this->render('createForm.html.twig', array( 'form' => $form->createView(), 'flow' => $flow, 'formData' => $formData, )); } /** * @Route("/edit", name="edit") */ public function editFormAction() { $userId = $this->getUser()->getId(); $individual = $this->getDoctrine()->getRepository('AppBundle:Individual')->find($userId); if(!$individual){ throw $this->createNotFoundException( 'No product found for id '.$userId ); } $flow = $this->get('form.flow.createForm'); // must match the flow's service id $flow->bind($individual); $form = $flow->createForm(); if ($flow->isValid($form)) { $flow->saveCurrentStepData($form); if ($flow->nextStep()) { // form for the next step $form = $flow->createForm(); } else { // flow finished $em = $this->getDoctrine()->getManager(); $em->flush(); $flow->reset(); // remove step data from the session return $this->redirect($this->generateUrl('edit')); // redirect when done } } return $this->render('createForm.html.twig', array( 'form' => $form->createView(), 'flow' => $flow, 'formData' => $individual, )); } } ?> <file_sep>/src/AppBundle/Form/Type/CollaboratorType.php <?php namespace AppBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\CallbackTransformer; use Symfony\Component\Form\Extension\Core\Type\ButtonType; use Doctrine\ORM\EntityRepository; class CollaboratorType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('id', EntityType::class, array( 'class' => 'AppBundle:User', 'choice_label' => 'username', 'query_builder' => function(EntityRepository $er) { return $er->createQueryBuilder('u') ->orderBy('u.username', 'ASC'); } )) ->add('collaborated_before', ChoiceType::class, array( 'choices' => array( 'Yes' => 'Yes', 'No' => 'No', ), 'multiple' => false, 'expanded' => true, )); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'AppBundle\Entity\Collaborator' )); } } ?> <file_sep>/src/AppBundle/Entity/User.php <?php // src/AppBundle/Entity/User.php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Security\Core\User\UserInterface; use FOS\UserBundle\Model\User as BaseUser; use JMS\Serializer\SerializerBuilder; use JMS\Serializer\Annotation\ExclusionPolicy; use JMS\Serializer\Annotation\Expose; use JMS\Serializer\Annotation as JMS; use JMS\Serializer\Annotation\Type; /** * @ORM\Entity * @UniqueEntity(fields="email", message="Email already taken") * @UniqueEntity(fields="username", message="Username already taken") * @ExclusionPolicy("all") */ class User extends BaseUser { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") * @Type("integer") * @Expose */ protected $id; // other properties and methods public function __construct() { parent::__construct(); } } <file_sep>/src/AppBundle/Form/GeneralInformationType.php <?php // src/AppBundle/Form/GeneralInformationType.php namespace AppBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use AppBundle\Entity\Individual; use Symfony\Component\OptionsResolver\OptionsResolver; use Doctrine\ORM\EntityRepository; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use AppBundle\Form\Type\ChoiceOtherRGType; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; use Symfony\Component\Form\CallbackTransformer; class GeneralInformationType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('name') ->add('research_group', ChoiceOtherRGType::class); // $builder->get('research_group')->addModelTransformer(new CallbackTransformer( // function($researchGroupAsString) { // return explode(' ', $researchGroupAsString); // }, // function($researchGroupAsArray) { // return implode(' ', $researchGroupAsArray); // } // )); // $builder->get('research_group')->addModelTransformer(new CallbackTransformer( // function($data) // { // if (in_array($data, $this->choices, true)){ // return array('choice' => 'Other', 'text' => $data); // } // }, // function ($data) // { // if ('Other' === $data['choice']) { // return $data['text']; // } // // return $data['choice']; // } // )); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'AppBundle\Entity\Individual' )); } } ?> <file_sep>/src/AppBundle/Entity/Collaborator.php <?php namespace AppBundle\Entity; use JMS\Serializer\Annotation\Type; use AppBundle\Entity\Individual; class Collaborator{ /** * @Type("AppBundle\Entity\User") */ protected $id; /** * @Type("string") */ protected $collaborated_before; public function getId(){ $this->id; } public function setId($user) { $this->id = $user; // $this->id = $individual->getId()->getId(); } public function getCollaboratedBefore() { $this->collaborated_before; } public function setCollaboratedBefore($collaborated_before) { $this->collaborated_before = $collaborated_before; } } ?> <file_sep>/src/AppBundle/Form/Type/ProjectType.php <?php // src/AppBundle/Form/Type/ProjectType.php namespace AppBundle\Form\Type; use AppBundle\Entity\Project; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\CollectionType; use Symfony\Component\Form\Extension\Core\Type\RangeType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Doctrine\ORM\EntityRepository; use Symfony\Component\Form\Extension\Core\Type\DateType; use AppBundle\Form\Type\RadioOtherProjectType; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; use Symfony\Component\Form\CallbackTransformer; use Symfony\Component\Form\Extension\Core\Type\TextType; use AppBundle\Form\Type\CollaboratorType; use JMS\Serializer\SerializerBuilder; use JMS\Serializer\Annotation\ExclusionPolicy; use JMS\Serializer\Annotation\Expose; use JMS\Serializer\Annotation as JMS; use Doctrine\Common\Collections\ArrayCollection; class ProjectType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('name') // ->add('name', EntityType::class, array( // 'class' => 'AppBundle:Project', // 'choice_label' => 'name', // 'choice_value' => 'name', // 'label' => 'Project title', // 'placeholder' => '--Select--', // 'query_builder' => function (EntityRepository $er) { // return $er->createQueryBuilder('u') // ->orderBy('u.name', 'ASC'); // }, // )) ->add('start_date', DateType::class, array( 'days' => array(1), 'years' => range(2015,2020), 'label' => 'Starting date', )) ->add('completion_date', DateType::class, array( 'label' => 'Completion date', 'years' => range(2015,2020), 'days' => array(1), 'empty_data' => array('year' => '----', 'months' => '----', 'day' => false), )) ->add('working_time', RangeType::class, array( 'label' => 'Over the past six month, how much time on average you spent on this project? Answer percentage of your working time', 'attr' => array( 'min' => 0, 'max' => 100, ) )); $builder->add('project_outcomes', RadioOtherProjectType::class, array( 'label' => 'What are the expected outcomes from this presentation?', )); $builder->add('collaborators', CollectionType::class, array( 'entry_type' => CollaboratorType::class, 'entry_options' => array( 'label' => 'Collaborator', ), 'allow_delete' => true, 'allow_add' => true, 'by_reference' => false, 'label' => false, 'prototype' => true, 'prototype_name' => '__collaborator__', 'attr' => array( 'class' => 'my-selector', ) )); // // $builder->get('collaborators')->addModelTransformer(new CallbackTransformer( // //string to object // function($data) // { // return array($data); // }, // //object to string // function($data) // { // return object($data); // } // )); // $builder->get('collaborators')->addModelTransformer(new CallbackTransformer( // //object to json string // //serialize is to change object to json string // function($data) // { // var_dump($data); // $serializer = SerializerBuilder::create()->build(); // // // $json = $serializer->serialize($data, 'json'); // // var_dump($json); // // $data = $serializer->deserialize($data, 'ArrayCollection<AppBundle\Entity\Collaborator>', 'json'); // // // // return $this->collaborators; // // return ($data); // }, // //json string to object // function ($data) // { // // $serializer = SerializerBuilder::create()->build(); // // // // $object = $serializer->deserialize($data, 'ArrayCollection<AppBundle\Entity\Collaborator>', 'json'); // // // var_dump($object); // // $data = new \Doctrine\Common\Collections\ArrayCollection($object); // return $data; // } // )); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => Project::class, )); } } ?>
e8e2b39cdf7e14e108e91c4dd0979a062f43b80b
[ "PHP" ]
7
PHP
huang-tianwen/latest_trying
97e29b7fc33bd828ecf0b2ad7bb9786f70e2ba22
5ea626b75817c6098e93950041acc13bc77f1152
refs/heads/main
<file_sep>import React, { Component } from 'react'; import { Row, Col, Card, CardHeader, CardBody, Progress, Button } from 'reactstrap'; import { Switch } from '../../vibe'; export default class AnalyticsPage extends Component { constructor(props) { super(props); this.state = { facebook: true, twitter: false }; } render() { return ( <div> <div className="m-b"> <h2>Good morning!</h2> <p className="text-muted"> Here's what's going on with your business today. </p> </div> <Row> <Col md={4} xs={12}> <Card> <CardHeader> Page Views{' '} <Button size="sm" className="pull-right"> View </Button> </CardHeader> <CardBody> <h2 className="m-b-20 inline-block"> <span>13K</span> </h2>{' '} <i className="fa fa-caret-down text-danger" aria-hidden="true" /> <Progress value={77} color="warning" /> </CardBody> </Card> </Col> <Col md={4} xs={12}> <Card> <CardHeader> Product Sold{' '} <Button size="sm" className="pull-right"> View </Button> </CardHeader> <CardBody> <h2 className="m-b-20 inline-block"> <span>1,890</span> </h2>{' '} <i className="fa fa-caret-up text-danger" aria-hidden="true" /> <Progress value={77} color="success" /> </CardBody> </Card> </Col> <Col md={4} xs={12}> <Card> <CardHeader> Server Capacity{' '} <Button size="sm" className="pull-right"> View </Button> </CardHeader> <CardBody> <h2 className="inline-block"> <span>14%</span> </h2> <Progress value={14} color="primary" /> </CardBody> </Card> </Col> </Row> <Row> <Col md={8} sm={12}> <Card> <CardHeader>Traffic</CardHeader> <CardBody> <div className="full-bleed"> </div> </CardBody> </Card> </Col> <Col md={4} sm={12}> <Card> <CardHeader>Product Views</CardHeader> <CardBody> </CardBody> </Card> </Col> </Row> <Row> <Col md={8} sm={12}> <Card> <CardHeader>Conversions</CardHeader> <CardBody> <Row className="m-b-md"> <Col xs={4}> <h5>Added to Cart</h5> <div className="h2">4.30%</div> <small className="text-muted">23 Visitors</small> </Col> <Col xs={4}> <h5>Reached Checkout</h5> <div className="h2">2.93</div> <small className="text-muted">12 Visitors</small> </Col> <Col xs={4}> <h5>Pruchased</h5> <div className="h2">10</div> <small className="text-muted">10 Customers</small> </Col> </Row> </CardBody> </Card> </Col> <Col md={4} xs={12}> <Card> <CardHeader>Integrations</CardHeader> <CardBody> <Switch enabled={this.state.facebook} toggle={() => { this.setState(prevState => ({ facebook: !prevState.facebook })); }} /> <span className="text-facebook pull-right"> <i className="fa fa-facebook" /> Facebook </span> <hr /> <Switch enabled={this.state.twitter} toggle={() => { this.setState(prevState => ({ twitter: !prevState.twitter })); }} /> <span className="text-twitter pull-right"> <i className="fa fa-twitter" /> Twitter </span> </CardBody> </Card> </Col> </Row> </div> ); } } <file_sep>// import logo from './logo.svg'; // import './App.css'; import React from 'react'; import { BrowserRouter, Route, Switch } from 'react-router-dom'; import DashboardLayout from './layouts/DashboardLayout'; import './vibe/scss/styles.scss'; function App() { return ( <BrowserRouter> <Switch> <Route component={DashboardLayout} /> </Switch> </BrowserRouter> ); } export default App;
ea79681f1e1083a8a5b340964d744d29ea468f51
[ "JavaScript" ]
2
JavaScript
kienyb12/Trantien
22a09a4d8fb11bfc2ed34137e22d6fefe42697b7
65e1ec2d7ecd5639dfce04184bb7463e41d5a076
refs/heads/master
<repo_name>fortress-fight/vuepress_template<file_sep>/docs/.vuepress/_configs/sidebar.js module.exports = { /** * 侧边栏 * 如果希望自动生成仅包含当前页面的标题链接的侧边栏,可以设置 sidebar: auto. * 如果希望在某个页面上设置,还可以如下所示: * '/': { sidebar: 'auto' } * 设置为 false 表示禁止 */ sidebar: [ "/", /** * 你可以省略 .md 扩展名,以 / 结尾的路径被推断为 *\/README.md 。 * 该链接的文本是自动推断的(从页面的第一个标题或 YAML front matter 中的显式标题)。 * 如果你希望明确指定链接文本,请使用 \[link,text] 形式的数组。 * "/Introduction/" */ /** * 侧边栏可以分组,形式如下 */ { title: "简介", collapsable: false, children: [ "/Introduction/", "/Introduction/Feature", "/Introduction/Theme", "/Introduction/Markdown" ] }, { title: "官方文档", collapsable: false, children: [ ["https://www.vuepress.cn/", "VuePress"], [ "https://www.vuepress.cn/default-theme-config/", "默认主题配置" ], [ "https://www.vuepress.cn/config/#%E5%9F%BA%E6%9C%AC%E9%85%8D%E7%BD%AE-basic-config", "配置参考" ] ] } ], // 侧边栏自动显示当前激活页面中标题的链接,嵌套在页面本身的链接下 sidebarDepth: 2, /** * 默认情况下,侧边栏只会显示由当前活动页面的标题(headers)组成的链接, * 你可以将 themeConfig.displayAllHeaders 设置为 true 来显示所有页面的标题链接: */ displayAllHeaders: false }; <file_sep>/docs/.vuepress/enhanceApp.js import jquery from "jquery"; import ClipboardJS from "clipboard"; import "./styles/font-awesome.css"; export default ({ Vue, // 当前 VuePress 应用所使用的 Vue 版本 options, // 根 Vue 实例的选项 router, // 应用程序的路由实例 siteData // 网站元数据 }) => { // ...使用应用程序级别的增强功能 window.$ = jquery; console.log(this); router.afterHooks.push(function() { Vue.nextTick(dom_loaded); }); }; function dom_loaded() { // setTimeout(() => {}, 200); $("body").on("mouseenter", "pre", function() { let copy_btn = $(this).find(".copy_btn"); if (!copy_btn.length) { copy_btn = $( "<div class='copy_btn'><i class='fa fa-copy'></div>" ).appendTo(this); new ClipboardJS(copy_btn[0], { target: trigger => { return $(this).find("code")[0]; } }); } }); } <file_sep>/docs/.vuepress/_configs/github.js module.exports = { /** * 假定 GitHub。也可以是一个完整的 GitLab URL。 */ repo: "https://github.com/fortress-fight/vuepress_template", // 自定义项目仓库链接文字 // 默认根据 `themeConfig.repo` 中的 URL 来自动匹配是 "GitHub"/"GitLab"/"Bitbucket" 中的哪个,如果不设置时是 "Source"。 repoLabel: "贡献代码!", // 以下为可选的 "Edit this page" 链接选项 // 如果你的文档和项目位于不同仓库: // docsRepo: "vuejs/vuepress", // 如果你的文档不在仓库的根目录下: docsDir: "docs", // 如果你的文档在某个特定的分支(默认是 'master' 分支): docsBranch: "master", // 默认为 false,设置为 true 来启用 editLinks: true, // 自定义编辑链接的文本。默认是 "Edit this page" editLinkText: "在 GITHUB 上编辑页面内容!" }; <file_sep>/docs/.vuepress/_configs/nav.js module.exports = { // 顶部导航,如果需要禁用导航,需要设置 navbar: false nav: [ /** * 如果需要使用多级导航,示例: * { text: "Languages", items: [ { text: "Chinese", link: "/language/chinese" }, { text: "Japanese", items: [ { text: "Home", link: "/" } ] } ] } */ { text: "Home", link: "/" }, /** * 如果 link 是一个目录,将会默认指向该目录下的 README.md */ { text: "Introduction", link: "/Introduction/" } ] }; <file_sep>/docs/.vuepress/config.js const nav = require("./_configs/nav"); const sidebar = require("./_configs/sidebar"); const github = require("./_configs/github"); const themeConfig = Object.assign( { /** * 默认情况下,当用户滚动页面,查看不同部分时, * 嵌套的标题链接和 URL 中的哈希值会随之更新, * 此行为可以通过以下的主题配置来禁用: */ activeHeaderLinks: true, /** * 表示是否禁用搜索框 * 如果你需要全文搜索,内置搜索只能从标题 h2 和 h3 标题构建索引, * 你可以使用 [Algolia](https://www.vuepress.cn/default-theme-config/#algolia-search) 搜索。 * algolia: { apiKey: '<API_KEY>', indexName: '<INDEX_NAME>' } */ search: true, searchMaxSuggestions: 10, /** * lastUpdated: 选项允许你获取每个文件的最后一次 git 提交的 UNIX 时间戳(ms), * 并且它也会以合适的格式显示在每个页面的底部 * 请注意,它默认是关闭的,如果给定一个 string 类型的值,它将会作为前缀显示(默认值是:Last Updated)。 */ lastUpdated: "更新时间:" }, nav, sidebar, github ); module.exports = { // 指定额外的需要被监听的文件。 extraWatchFiles: [".vuepress/_config/*.*"], // 网站的标题,同时会出现在页面的左上角导航旁边 title: "VuePress Template", /** * 根路径,在文件中引用静态资源的时候使用 `$witchBase('/foo.png')` * <img :src="$withBase('/foo.png')" alt="foo"> * 会自动拼接到 config.js 文件中所有静态资源 URL 中 */ base: "/vuepress_template/", // 网站的描述 description: "Just playing around", /** * 被注入页面 HTML <head> 额外的标签。 * 每个标签可以用 [tagName, { attrName: attrValue }, innerHTML?] 的形式指定。 * 例如,要添加自定义图标:['link', { rel: 'icon', href: '/logo.png' }] */ head: [], /** * 指定此选项来设置默认的自定义主题。使用 "foo" 的值, * VuePress 将尝试在 node_modules/vuepress-theme-foo/Layout.vue 加载主题组件。 */ theme: undefined, configureWebpack: { resolve: { alias: { "@alias": "path/to/some/dir" } } }, markdown: { // 代码是否带有行数的标识 lineNumbers: true, // 目录渲染层级 toc: { includeLevel: [2, 3] }, config: md => { // 使用更多 [markdown-it](https://github.com/markdown-it/markdown-it) 插件! // md.use(require("markdown-it-xxx")); } }, themeConfig }; <file_sep>/docs/README.md --- # YAML # 禁用当前页面的顶部导航 # navbar: false # 当前页面标签,默认为当前页面的 H1 # title: VuePress # 语言 lang: zh-CN # meta meta: - name: description content: Vuepress-template - name: keywords content: Vuepress template # 最大值为2,用于覆盖 config.js 中的 sidebarDepth # sidebarDepth: 2 # 首页没有侧边栏 # 生成仅包含当前页面的标题链接的侧边栏,设置为 false 表示禁止 # sidebar: auto # 根据激活页面的侧边栏顺序自动推断上一个和下一个链接。你也可以使用 YAML front matter 来显式覆盖或禁用它们: # prev: ./some-other-page # next: false # 隐藏指定页面上的编辑链接: # editLink: false # 自定义页面的 Class pageClass: c-index_page # 自定义页面布局 # 下面将会使用 .vuepress/components/SpecialLayout.vue。为当前页面渲染 # layout: SpecialLayout home: true heroImage: /hero.png actionText: 起步 → actionLink: /Introduction/ features: - title: 简明优先 details: 对以 markdown 为中心的项目结构,做最简化的配置,帮助你专注于创作。 - title: Vue 驱动 details: 享用 Vue + webpack 开发环境,在 markdown 中使用 Vue 组件,并通过 Vue 开发自定义主题。 - title: 性能高效 details: VuePress 将每个页面生成为预渲染的静态 HTML,每个页面加载之后,然后作为单页面应用程序(SPA)运行。 footer: MIT Licensed | Copyright © 2018-present Evan You ---
93aacc3b34838b981bb3f85fd0f743a8be6f313c
[ "JavaScript", "Markdown" ]
6
JavaScript
fortress-fight/vuepress_template
ab4caf3435f6401c404eb48f07587ba59feaf5ac
cebe2e6fb41339771252741175bcc21694fce1be
refs/heads/master
<repo_name>nickmancol/SLAPP3<file_sep>/requirements.txt xlrd matplotlib networkx pandas scipy <file_sep>/6 objectSwarmObserverAgents_AESOP_turtleLib_NetworkX/oligopoly/WorldState.py # WorldState.py from Tools import * import commonVar as common class WorldState(object): def __init__(self): # the environment print("World state has been created.") # set market price V1 def setMarketPriceV1(self): # to have a price around 1 common.price = 1.4 - 0.02 * common.totalProductionInA_TimeStep print("Set market price to ", common.price) common.price10 = common.price * 10 # to plot # set market price V2 def setMarketPriceV2(self): common.price = common.totalPlannedConsumptionInValueInA_TimeStep / \ common.totalProductionInA_TimeStep print("Set market price to ", common.price) # set market price V3 def setMarketPriceV3(self): shock0 = random.uniform(-common.maxDemandRelativeRandomShock, common.maxDemandRelativeRandomShock) shock = shock0 print("\n-------------------------------------") if shock >= 0: common.totalDemandInPrevious_TimeStep = \ common.totalPlannedConsumptionInValueInA_TimeStep * \ (1 + shock) common.price = (common.totalPlannedConsumptionInValueInA_TimeStep * (1 + shock)) \ / common.totalProductionInA_TimeStep print("Relative shock (symmetric) ", shock0) print("Set market price to ", common.price) if shock < 0: shock *= -1. # always positive, boing added to the denominator common.totalDemandInPrevious_TimeStep = \ common.totalPlannedConsumptionInValueInA_TimeStep / \ (1 + shock) common.price = (common.totalPlannedConsumptionInValueInA_TimeStep / (1 + shock)) \ / common.totalProductionInA_TimeStep print("Relative shock (symmetric) ", shock0) print("Set market price to ", common.price) print("-------------------------------------\n") # random shock to wages (temporary method to experiment with wages) def randomShockToWages(self): k = 0.10 shock = random.uniform(-k, k) if shock >= 0: common.wage *= (1. + shock) if shock < 0: shock *= -1. common.wage /= (1. + shock) # shock to wages (full employment case) def fullEmploymentEffectOnWages(self): # wages: reset incumbent action if any if common.wageAddendum > 0: common.wage -= common.wageAddendum common.wageAddendum = 0 # employed people peopleList = common.g.nodes() totalPeople = len(peopleList) totalEmployed = 0 for p in peopleList: if p.employed: totalEmployed += 1 # print totalPeople, totalEmployed unemploymentRate = 1. - float(totalEmployed) / \ float(totalPeople) if not common.fullEmploymentStatus and \ unemploymentRate <= common.fullEmploymentThreshold: common.wage *= (1 + common.wageStepInFullEmployment) common.fullEmploymentStatus = True if common.fullEmploymentStatus and \ unemploymentRate > common.fullEmploymentThreshold: common.wage /= (1 + common.wageStepInFullEmployment) common.fullEmploymentStatus = False # incumbents rising wages as na entry barrier def incumbentActionOnWages(self): # current number of entrepreneurs peopleList = common.g.nodes() nEntrepreneurs = 0 for p in peopleList: if p.agType == "entrepreneurs": nEntrepreneurs += 1 nEntrepreneurs = float(nEntrepreneurs) # previous number of entrepreneurs nEntrepreneurs0 = common.str_df.iloc[-1, 0] # indexes Python style # print nEntrepreneurs, nEntrepreneurs0 # wages: reset incumbent action if any if common.wageAddendum > 0: common.wage -= common.wageAddendum common.wageAddendum = 0 # wages: set if nEntrepreneurs / nEntrepreneurs0 - 1 > \ common.maxAcceptableOligopolistRelativeIncrement: common.wageAddendum = common.wage *\ common.temporaryRelativeWageIncrementAsBarrier common.wage += common.wageAddendum <file_sep>/6 objectSwarmObserverAgents_AESOP_turtleLib_NetworkX/oligopoly/commonVar.py # commonVar.py projectVersion = "5bPy3" build = "20170611" debug = False # controlling the existence of an agent with number==0 used by reset # step in modelActions.txt agent1existing = False # the time is set by ObserverSwarm with # common.cycle=1 # in the benginning prune = False pruneThreshold = 0 g = 0 # this variable will contain the address of the graph g_labels = 0 # this variable will contain the address of the labels g_edge_labels = 0 # this variable will contain the address of the labels of the edges btwn = 0 # this variable will contain the betweenness centrality indicators clsn = 0 # this variable will contain the closeness centrality indicators orderedListOfNodes = [] verbose = False clonedN = 0 # sigma of the normal distribution used in randomize the position of the agents/nodes # sigma=0.7 sigma = 1.2 # size of the nodes nsize = 150 # demand funtion paramenters (1) entrepreneurs as consumers (2) employed workers #(3) unemployed workers # with Ci = ai + bi Y + u # u=N(0,consumptionErrorSD) consumptionRandomComponentSD = 0.3 #(1) a1 = 0.4 b1 = 0.55 # Y1=profit(t-1)+wage NB no negative consumption if profit(t-1) < 0 #(2) a2 = 0.3 b2 = 0.65 # Y2=wage #(3) socialWelfareCompensation = 0.3 a3 = 0 b3 = 1 # Y3=socialWelfareCompensation #wages and revenues wage = 1. fullEmploymentThreshold = 0.05 wageStepInFullEmployment = 0.10 fullEmploymentStatus = False wageAddendum = 0 maxAcceptableOligopolistRelativeIncrement = 0.20 temporaryRelativeWageIncrementAsBarrier = 0.15 revenuesOfSalesForEachWorker = 1.005 # work troubles, production correction Psi, relative value productionCorrectionPsi = 0.10 # does it generate a cut of the wages wageCutForWorkTroubles = False # price penalty for work troubles penaltyValue = 0 # was 0.10 # labor productivity laborProductivity = 1 # thresholds (for Version 0) hiringThreshold = 0 firingThreshold = 0 # macro variables totalProductionInA_TimeStep = 0 totalPlannedConsumptionInValueInA_TimeStep = 0 # Poisson mean in makeProoductionPlan, will be modified in paramenters.py # in the function loadParameters nu = 5 # to internally calculate the Poisson mean (nu) in makeProoductionPlan # for time=1 in V3 we use the ratio rho rho = 0.9 # threshold toEntrepreneur thresholdToEntrepreneur = 0.15 # was 0.20 extraCostsDuration = 3 newEntrantExtraCosts = 60 # was 100.0 # was 2.0 randomComponentOfPlannedProduction = 0.10 # max new entrant number in a time step absoluteBarrierToBecomeEntrepreneur = 20 maxDemandRelativeRandomShock = 0.15 # was 0.10 #was 0.20 # threshold toWorker thresholdToWorker = -0.20 nodeNumbersInGraph = False # step to be executed at end (plus an optional second part added # within oActions.py) toBeExecuted = "saveTimeSeries()" <file_sep>/6 objectSwarmObserverAgents_AESOP_turtleLib_NetworkX/debug/commonVar.py # commonVar.py projectVersion = 1.2 # added () in print BY HAND toBeExecuted = "print ('Goodbye from the debug world.')" debug = False # start with False and then try True <file_sep>/6 objectSwarmObserverAgents_AESOP_turtleLib_NetworkX/oligopoly/parameters.py # parameters.py from Tools import * import commonVar as common import networkx as nx import matplotlib as mplt import numpy.random as npr import pandas as pd from IPython import get_ipython import pandas as pd def loadParameters(self): # creating the dataframe of the paramenters try: common.str_df except BaseException: common.par_df = pd.DataFrame(columns=['Parameter names', 'Values']) print("\nCreation of fhe parameter dataframe\n") # print common.par_df # preliminary cntrol if common.graphicStatus == "PythonViaTerminal" and common.IPython: print("Please do not run the 'oligopoly project' in IPython via a terminal.") os.sys.exit(1) print('Warning: if running in "jupyter console" the graphic output is missing."') print("NetworkX version %s running" % nx.__version__) print("matplotlib version %s running" % mplt.__version__) print("pandas version %s running\n" % pd.__version__) nxv = nx.__version__ vOK = checkVersion(nxv, 'NetworkX', 1, 9, 1) if not vOK: print("NetworkX 1.9.1 or greater required") os.sys.exit(1) mpltv = mplt.__version__ vOK = checkVersion(mpltv, 'Matplotlib', 1, 5, 1) if not vOK: print("Matplotlib 1.5.1 or greater required") os.sys.exit(1) pdv = pd.__version__.split('.') vOK = False if int(pdv[0]) > 0: vOK = True if len(pdv) >= 1: if int(pdv[0]) == 0 and int(pdv[1]) > 18: vOK = True if len(pdv) >= 3: if int(pdv[0]) == 0 and int(pdv[1]) == 18 and int(pdv[2]) >= 1: vOK = True if not vOK: print("pandas 0.18.1 or greater required") os.sys.exit(1) # sigma of the normal distribution used in randomize the position of the # agents/nodes print( "sigma of the normal distribution used in randomizing the position of the agents/nodes ", common.sigma) mySeed = eval(input("random number seed (1 to get it from the clock) ")) if mySeed == 1: random.seed() npr.seed() else: random.seed(mySeed) npr.seed(mySeed) self.nAgents = 0 print("No 'bland' agents") #self.worldXSize= input("X size of the world? ") self.worldXSize = 1 # print "X size of the world not relevant" #self.worldYSize= input("Y size of the world? ") self.worldYSize = 1 # print "y size of the world not relevant" # Projct version and thresholds try: projectVersion = str(common.projectVersion) except BaseException: projectVersion = "Unknown" try: build = str(common.build) except BaseException: build = "Unknown" print( "\nProject version " + projectVersion, "build", build, "\nhiringThreshold", common.hiringThreshold, "firingThreshold", common.firingThreshold) dataFrameAppend("project version", projectVersion) # saving pars dataFrameAppend("build", build) # saving pars dataFrameAppend("seed (1 gets it from the clock)", mySeed) # saving pars # wages print("wage base", common.wage) dataFrameAppend("wage base", common.wage) # saving pars # social welfare compensation print("social welfare compensation", common.socialWelfareCompensation) dataFrameAppend("social welfare compensation", common.socialWelfareCompensation) # saving pars # revenue of sales per worker (version 0) # print "revenues of sales for each worker in Version 0", \ # common.revenuesOfSalesForEachWorker # laboor productivity print("labor productivity", common.laborProductivity) dataFrameAppend( "labor productivity", common.laborProductivity) # saving pars # Poisson mean in plannedProduction if common.projectVersion < "3": print( "Mean value of the Poisson distribution used in production planning " + "(not used in V.0; used only at t=1 in V.3);") tmp = input( "suggested nu=5 (enter to confirm or input a number) ") try: common.nu = int(tmp) except BaseException: pass print("Resulting value", common.nu) if common.projectVersion >= "3": print( "nu, mean value of the Poisson distribution used in production\n" + "planning at time=1, is set internally to match the ratio\n" + "between actual and potential initial employed population,") print("set to %3.2f" % common.rho) dataFrameAppend( "expected employment ratio at t=1", common.rho) # saving pars # consumption print() print("consumption behavior with Ci = ai + bi Yi + u\n" + "u = N(0,%5.3f)" % common.consumptionRandomComponentSD) print(("(1) entrepreneurs as consumers with a1 = %4.2f b1 = %4.2f Y1 = profit(t-1)+wage\n" + "(2) employed workers with a2 = %4.2f b2 = %4.2f Y2 = wage\n" + "(3) unemployed workers with a3 = %4.2f b3 = %4.2f Y3 = socialWelfareCompensation") % (common.a1, common.b1, common.a2, common.b2, common.a3, common.b3)) print() dataFrameAppend("consumption behavior: a1", common.a1) # saving pars dataFrameAppend("consumption behavior: b1", common.b1) # saving pars dataFrameAppend("consumption behavior: a2", common.a2) # saving pars dataFrameAppend("consumption behavior: b2", common.b2) # saving pars dataFrameAppend("consumption behavior: a3", common.a3) # saving pars dataFrameAppend("consumption behavior: b3", common.b3) # saving pars print("consumption random component (SD)", common.consumptionRandomComponentSD) dataFrameAppend("consumption random component (SD)", common.consumptionRandomComponentSD) # saving pars print(("Relative threshold to become an entrepreneur %4.2f\n" + "with new entrant extra costs %4.2f and duration of the extra costs %d") % (common.thresholdToEntrepreneur, common.newEntrantExtraCosts, common.extraCostsDuration)) dataFrameAppend("relative threshold to become an entrepreneur", common.thresholdToEntrepreneur) # saving pars dataFrameAppend("new entrant extra costs", common.newEntrantExtraCosts) # saving pars dataFrameAppend("duration (# of cycles) of the extra costs", common.extraCostsDuration) # saving pars print("Random component of planned production, uniformly distributed between %4.2f%s and %4.2f%s" % (-common.randomComponentOfPlannedProduction * 100, "%", common.randomComponentOfPlannedProduction * 100, "%")) dataFrameAppend("min random rel. component of planned production", -common.randomComponentOfPlannedProduction) # saving pars dataFrameAppend("max random rel. component of planned production", common.randomComponentOfPlannedProduction) # saving pars print( "Absolute barrier to become entrepreneur, max number in a time step: ", common.absoluteBarrierToBecomeEntrepreneur) dataFrameAppend("max new entrant number in a time step", common.absoluteBarrierToBecomeEntrepreneur) # saving pars print( "\nRelative threshold to lose the entrepreneur status (becoming a unemployed worker) %4.2f\n" % common.thresholdToWorker) dataFrameAppend("relative threshold from entrepreneur to unempl.", common.thresholdToWorker) # saving pars print( "Total demand relative random shock, uniformly distributed\nbetween " + "-%4.2f%s and +%4.2f%s" % (common.maxDemandRelativeRandomShock * 100, "%", common.maxDemandRelativeRandomShock * 100, "%")) dataFrameAppend("min of uniform demand relative random shock", -common.maxDemandRelativeRandomShock) # saving pars dataFrameAppend("max of uniform demand relative random shock", common.maxDemandRelativeRandomShock) # saving pars print("Node numbers in graph:", common.nodeNumbersInGraph) print("Full employment threshold " + "%4.2f%s and wage step up in full employment %4.2f%s" % (common.fullEmploymentThreshold * 100, "%", common.wageStepInFullEmployment * 100, "%")) dataFrameAppend("full employment threshold", common.fullEmploymentThreshold) # saving pars dataFrameAppend("wage step up in full employment", common.wageStepInFullEmployment) # saving pars print( "Wage relative increment as an entry barrier: " + "%4.2f%s; trigger level (relative increment of oligopolistic firms): %4.2f%s" % (common.temporaryRelativeWageIncrementAsBarrier * 100, "%", common.maxAcceptableOligopolistRelativeIncrement * 100, "%")) dataFrameAppend("wage relative increment as an entry barrier", common.temporaryRelativeWageIncrementAsBarrier) # saving pars dataFrameAppend( "trigger level (relative increment of olig. firms)", common.maxAcceptableOligopolistRelativeIncrement) # saving par print("Production correction (lost production) due to work troubles " + "between %4.2f%s and %4.2f%s, if any." % (common.productionCorrectionPsi * 100 / 2., "%", common.productionCorrectionPsi * 100, "%")) print("The correction acts with the probability indicate in the " + "file schedule.xls for the method 'workTroubles'") print("Is it applied also to the wages of the worker of the firm? ", common.wageCutForWorkTroubles) print("Price penalty for the firms suffering work troubles %4.2f%s" % (common.penaltyValue * 100, "%")) dataFrameAppend("min lost production due to work troubles", common.productionCorrectionPsi / 2.) # saving pars dataFrameAppend("max lost production due to work troubles", common.productionCorrectionPsi) # saving pars dataFrameAppend("probability of work troubles, see below", "-") # saving par if common.wageCutForWorkTroubles: dataFrameAppend("cut also the wages", "yes") # saving pars else: dataFrameAppend("cut also the wages", "no") # saving pars dataFrameAppend("price penalty for the firms if work troubles", common.penaltyValue) # saving par # cycles self.nCycles = eval(input("How many cycles? (0 = exit) ")) dataFrameAppend("# of cycles", self.nCycles) # saving par v = input("verbose? (y/[n]) ") if v == "y" or v == "Y": common.verbose = True # predefined False print("If running in IPython, the messages of the model about che creation" + "\nof each agent are automatically off, to avoid locking the run.") def dataFrameAppend(name, value): par_df2 = pd.DataFrame([[name, value]], columns=['Parameter names', 'Values']) # print par_df2 common.par_df = common.par_df.append(par_df2, ignore_index=True) # print common.par_df #warning: here the row index starts from 0 <file_sep>/6 objectSwarmObserverAgents_AESOP_turtleLib_NetworkX/oligopoly/README.md # Oligopoly <NAME>, <NAME>, and <NAME> The model and its construction are reported in [Oligopoly.pdf](Oligopoly.pdf). We have also the [slides](slides_of_a_presentazione_of_the_model.pdf) of the presentation of the Oligopoly model at [WEHIA 2017](http://www.wehia2017.com). A recent paper [(Business Cycle in a Macromodel with Oligopoly and Agents' Heterogeneity: An Agent-Based Approach, 2017)](https://link.springer.com/epdf/10.1007/s40797-017-0058-y) of M.Mazzoli, M.Morini, and P.Terna, discusses the model and its results. The Oligopoly model uses [SLAPP](https://terna.github.io/SLAPP/) as its agent-based modeling shell. <file_sep>/6 objectSwarmObserverAgents_AESOP_turtleLib_NetworkX/oligopoly/Agent.py # Agent.py from Tools import * from agTools import * from random import * import graphicDisplayGlobalVarAndFunctions as gvf import commonVar as common import numpy.random as npr def mySort(ag): if ag == []: return [] numAg = [] for a in ag: numAg.append((a.number, a)) numAg.sort() agSorted = [] for i in range(len(numAg)): agSorted.append(numAg[i][1]) return agSorted class Agent(SuperAgent): def __init__(self, number, myWorldState, xPos=0, yPos=0, agType=""): # print xPos,yPos # the graph if gvf.getGraph() == 0: gvf.createGraph() common.g.add_node(self) # the environment self.agOperatingSets = [] self.number = number self.agType = agType self.numOfWorkers = 0 # never use it directly to make calculations self.profit = 0 self.plannedProduction = 0 self.consumption = 0 self.employed = False self.extraCostsResidualDuration = 0 if agType == 'workers': common.orderedListOfNodes.append(self) # use to keep the order # in output (ex. adjacency matrix) # colors at http://www.w3schools.com/html/html_colornames.asp gvf.colors[self] = "OrangeRed" self.employed = False self.workTroubles = 0 if agType == 'entrepreneurs': common.orderedListOfNodes.append(self) # use to keep the order # in output (ex. adjacency matrix) # colors at http://www.w3schools.com/html/html_colornames.asp gvf.colors[self] = "LawnGreen" self.employed = True self.plannedProduction = -100 # not used in plots if -100 self.hasTroubles = 0 self.myWorldState = myWorldState self.agType = agType # the agents if common.verbose: print("agent of type", self.agType, "#", self.number, "has been created at", xPos, ",", yPos) gvf.pos[self] = (xPos, yPos) if common.nodeNumbersInGraph: common.g_labels[self] = str(number) # to be used to clone (if any) self.xPos = xPos self.yPos = yPos # talk def talk(self): print(self.agType, self.number) # reset values, redefining the method of agTools.py in $$slapp$$ def setNewCycleValues(self): # the if is to save time, given that the order is arriving to # all the agents (in principle, to reset local variables) if not common.agent1existing: print("At least one of the agents has to have number==1") print("Missing that agent, all the agents are resetting common values") if self.number == 1 or not common.agent1existing: common.totalProductionInA_TimeStep = 0 common.totalPlannedConsumptionInValueInA_TimeStep = 0 common.totalProfit = 0 common.totalPlannedProduction = 0 # troubles related variables if self.agType == "entrepreneurs": self.hasTroubles = 0 if self.agType == "workers": self.workTroubles = 0 # hireIfProfit def hireIfProfit(self): # workers do not hire if self.agType == "workers": return if self.profit <= common.hiringThreshold: return tmpList = [] for ag in self.agentList: if ag != self: if ag.agType == "workers" and not ag.employed: tmpList.append(ag) if len(tmpList) > 0: hired = tmpList[randint(0, len(tmpList) - 1)] hired.employed = True gvf.colors[hired] = "Aqua" gvf.createEdge(self, hired) # self, here, is the hiring firm # count edges (workers) of the firm, after hiring (the values is # recorded, but not used directly) self.numOfWorkers = gvf.nx.degree(common.g, nbunch=self) # nbunch : iterable container, optional (default=all nodes) # A container of nodes. The container will be iterated through once. print("entrepreneur", self.number, "has", self.numOfWorkers, "edge/s after hiring") def hireFireWithProduction(self): # workers do not hire/fire if self.agType == "workers": return # to decide to hire/fire we need to know the number of employees # the value is calcutated on the fly, to be sure of accounting for # modifications coming from outside # (nbunch : iterable container, optional (default=all nodes) # A container of nodes. The container will be iterated through once.) laborForce0 = gvf.nx.degree(common.g, nbunch=self) + \ 1 # +1 to account for the entrepreneur herself # required labor force laborForceRequired = int( self.plannedProduction / common.laborProductivity) #??????????????????? # countUnemployed=0 # for ag in self.agentList: # if not ag.employed: countUnemployed+=1 # print "I'm entrepreneur %d laborForce %d and required %d unemployed are %d" %\ #(self.number, laborForce0, laborForceRequired, countUnemployed) # no action if laborForce0 == laborForceRequired: return # hire if laborForce0 < laborForceRequired: n = laborForceRequired - laborForce0 tmpList = [] for ag in self.agentList: if ag != self: if ag.agType == "workers" and not ag.employed: tmpList.append(ag) if len(tmpList) > 0: k = min(n, len(tmpList)) shuffle(tmpList) for i in range(k): hired = tmpList[i] hired.employed = True gvf.colors[hired] = "Aqua" gvf.createEdge(self, hired) # self, here, is the hiring firm # count edges (workers) of the firm, after hiring (the values is # recorded, but not used directly) self.numOfWorkers = gvf.nx.degree(common.g, nbunch=self) # nbunch : iterable container, optional (default=all nodes) # A container of nodes. The container will be iterated through # once. print( "entrepreneur", self.number, "is applying prod. plan and has", self.numOfWorkers, "edge/s after hiring") # fire if laborForce0 > laborForceRequired: n = laborForce0 - laborForceRequired # the list of the employees of the firm entrepreneurWorkers = gvf.nx.neighbors(common.g, self) # print "entrepreneur", self.number, "could fire", # entrepreneurWorkers # the list returnes by nx is unstable as order entrepreneurWorkers = mySort(entrepreneurWorkers) if len(entrepreneurWorkers) > 0: # has to be, but ... shuffle(entrepreneurWorkers) for i in range(n): fired = entrepreneurWorkers[i] gvf.colors[fired] = "OrangeRed" fired.employed = False # common.g_edge_labels.pop((self,fired)) no labels in edges common.g.remove_edge(self, fired) # count edges (workers) after firing (recorded, but not used # directly) self.numOfWorkers = gvf.nx.degree(common.g, nbunch=self) # nbunch : iterable container, optional (default=all nodes) # A container of nodes. The container will be iterated through # once. print( "entrepreneur", self.number, "is applying prod. plan and has", self.numOfWorkers, "edge/s after firing") # fireIfProfit def fireIfProfit(self): # workers do not fire if self.agType == "workers": return if self.profit >= common.firingThreshold: return # the list of the employees of the firm entrepreneurWorkers = gvf.nx.neighbors(common.g, self) # print "entrepreneur", self.number, "could fire", entrepreneurWorkers # the list returnes by nx is unstable as order entrepreneurWorkers = mySort(entrepreneurWorkers) if len(entrepreneurWorkers) > 0: fired = entrepreneurWorkers[randint( 0, len(entrepreneurWorkers) - 1)] gvf.colors[fired] = "OrangeRed" fired.employed = False # common.g_edge_labels.pop((self,fired)) no label in edges common.g.remove_edge(self, fired) # count edges (workers) after firing (recorded, but not used # directly) self.numOfWorkers = gvf.nx.degree(common.g, nbunch=self) # nbunch : iterable container, optional (default=all nodes) # A container of nodes. The container will be iterated through # once. print("entrepreneur", self.number, "has", self.numOfWorkers, "edge/s after firing") # produce def produce(self): # this is an entrepreneur action if self.agType == "workers": return # to produce we need to know the number of employees # the value is calcutated on the fly, to be sure of accounting for # modifications coming from outside # (nbunch : iterable container, optional (default=all nodes) # A container of nodes. The container will be iterated through once.) laborForce = gvf.nx.degree(common.g, nbunch=self) + \ 1 # +1 to account for the entrepreneur herself print("I'm entrepreneur", self.number, "my laborforce is", laborForce) # productivity is set to 1 in the benginning from common space self.production = common.laborProductivity * \ laborForce # totalProductionInA_TimeStep common.totalProductionInA_TimeStep += self.production # having a copy, that is update after each agent's action common.totalProductionInPrevious_TimeStep = common.totalProductionInA_TimeStep # produce def produceV5(self): # this is an entrepreneur action if self.agType == "workers": return # to produce we need to know the number of employees # the value is calcutated on the fly, to be sure of accounting for # modifications coming from outside # (nbunch : iterable container, optional (default=all nodes) # A container of nodes. The container will be iterated through once.) laborForce = gvf.nx.degree(common.g, nbunch=self) + \ 1 # +1 to account for the entrepreneur herself print("I'm entrepreneur", self.number, "my laborforce is", laborForce) # productivity is set to 1 in the benginning from common space self.production = common.laborProductivity * \ laborForce # print "I'm entrepreneur",self.number,"production before correction is",\ # self.production # correction for work troubles, if any # self.hasTroubles is 0 if no troubles self.production *= (1. - self.hasTroubles) # print "I'm entrepreneur",self.number,"production after correction is",\ # self.production # totalProductionInA_TimeStep common.totalProductionInA_TimeStep += self.production # having a copy, that is update after each agent's action common.totalProductionInPrevious_TimeStep = common.totalProductionInA_TimeStep # makeProductionPlan def makeProductionPlan(self): # this is an entrepreneur action if self.agType == "workers": return if common.projectVersion >= "3" and common.cycle == 1: nEntrepreneurs = 0 for ag in self.agentList: if ag.agType == "entrepreneurs": nEntrepreneurs += 1 # print nEntrepreneurs nWorkersPlus_nEntrepreneurs = len(self.agentList) # print nWorkersPlus_nEntrepreneurs common.nu = ( common.rho * nWorkersPlus_nEntrepreneurs) / nEntrepreneurs # print common.rho, common.nu if (common.projectVersion >= "3" and common.cycle == 1) or \ common.projectVersion < "3": self.plannedProduction = npr.poisson( common.nu, 1)[0] # 1 is the number # of element of the returned matrix (vector) # print self.plannedProduction common.totalPlannedProduction += self.plannedProduction # print "entrepreneur", self.number, "plan", self.plannedProduction,\ # "total", common.totalPlannedProduction # adaptProductionPlan def adaptProductionPlan(self): if common.cycle > 1: nEntrepreneurs = 0 for ag in self.agentList: if ag.agType == "entrepreneurs": nEntrepreneurs += 1 # previous period price #print ("++++++++++++++++++++++", common.ts_df.price.values[-1]) #print ("&&&&&&&&&&&&&&&&&&&&&&",len(common.ts_df.price.values)) if len(common.ts_df.price.values) == 1: previuosPrice = common.ts_df.price.values[-1] # t=2 if len(common.ts_df.price.values) > 1: previuosPrice = common.ts_df.price.values[-2] # t>2 # NB adapt acts from t>1 self.plannedProduction = (common.totalDemandInPrevious_TimeStep / previuosPrice) \ / nEntrepreneurs #self.plannedProduction += gauss(0,self.plannedProduction/10) shock = uniform( -common.randomComponentOfPlannedProduction, common.randomComponentOfPlannedProduction) if shock >= 0: self.plannedProduction *= (1. + shock) if shock < 0: shock *= -1. self.plannedProduction /= (1. + shock) # print self.number, self.plannedProduction common.totalPlannedProduction += self.plannedProduction # print "entrepreneur", self.number, "plan", self.plannedProduction,\ # "total", common.totalPlannedProduction # calculateProfit V0 def evaluateProfitV0(self): # this is an entrepreneur action if self.agType == "workers": return # the number of producing workers is obtained indirectly via # production/laborProductivity # print self.production/common.laborProductivity self.profit = (self.production / common.laborProductivity) * \ (common.revenuesOfSalesForEachWorker - common.wage) + gauss(0, 0.05) # calculateProfit def evaluateProfit(self): # this is an entrepreneur action if self.agType == "workers": return # backward compatibily to version 1 try: XC = common.newEntrantExtraCosts except BaseException: XC = 0 try: k = self.extraCostsResidualDuration except BaseException: k = 0 if k == 0: XC = 0 if k > 0: self.extraCostsResidualDuration -= 1 # the number of pruducing workers is obtained indirectly via # production/laborProductivity # print self.production/common.laborProductivity self.costs = common.wage * \ (self.production / common.laborProductivity) + XC # the entrepreur sells her production, which is cotributing - via # totalActualProductionInA_TimeStep, to price formation self.profit = common.price * self.production - self.costs common.totalProfit += self.profit # calculateProfit def evaluateProfitV5(self): # this is an entrepreneur action if self.agType == "workers": return # backward compatibily to version 1 try: XC = common.newEntrantExtraCosts except BaseException: XC = 0 try: k = self.extraCostsResidualDuration except BaseException: k = 0 if k == 0: XC = 0 if k > 0: self.extraCostsResidualDuration -= 1 # the number of pruducing workers is obtained indirectly via # production/laborProductivity # print self.production/common.laborProductivity # how many workers, not via productvity due to possible troubles # in production laborForce = gvf.nx.degree(common.g, nbunch=self) + \ 1 # +1 to account for the entrepreneur herself # the followin if/else structure is for control reasons because if # not common.wageCutForWorkTroubles we do not take in account # self.workTroubles also if != 0; if = 0 is non relevant in any case if common.wageCutForWorkTroubles: self.costs = (common.wage - self.hasTroubles) \ * (laborForce - 1) \ + common.wage * 1 + \ XC # above, common.wage * 1 is for the entrepreur herself else: self.costs = common.wage * laborForce + \ XC # print "I'm entrepreur", self.number, "costs are",self.costs # penalty Value pv = 0 if self.hasTroubles > 0: pv = common.penaltyValue # the entrepreur sells her production, which is cotributing - via # totalActualProductionInA_TimeStep, to price formation self.profit = common.price * (1. - pv) * self.production - self.costs print("I'm entrepreur", self.number, "my price is ", common.price * (1. - pv)) common.totalProfit += self.profit # compensation def planConsumptionInValue(self): self.consumption = 0 #case (1) # Y1=profit(t-1)+wage NB no negative consumption if profit(t-1) < 0 # this is an entrepreneur action if self.agType == "entrepreneurs": self.consumption = common.a1 + \ common.b1 * (self.profit + common.wage) + \ gauss(0, common.consumptionRandomComponentSD) if self.consumption < 0: self.consumption = 0 # profit, in V2, is at time -1 due to the sequence in schedule2.xls #case (2) # Y2=wage if self.agType == "workers" and self.employed: self.consumption = common.a2 + \ common.b2 * common.wage + \ gauss(0, common.consumptionRandomComponentSD) #case (3) # Y3=socialWelfareCompensation if self.agType == "workers" and not self.employed: self.consumption = common.a3 + \ common.b3 * common.socialWelfareCompensation + \ gauss(0, common.consumptionRandomComponentSD) # update totalPlannedConsumptionInValueInA_TimeStep common.totalPlannedConsumptionInValueInA_TimeStep += self.consumption # print "C sum", common.totalPlannedConsumptionInValueInA_TimeStep # compensation def planConsumptionInValueV5(self): self.consumption = 0 #case (1) # Y1=profit(t-1)+wage NB no negative consumption if profit(t-1) < 0 # this is an entrepreneur action if self.agType == "entrepreneurs": self.consumption = common.a1 + \ common.b1 * (self.profit + common.wage) + \ gauss(0, common.consumptionRandomComponentSD) if self.consumption < 0: self.consumption = 0 # profit, in V2, is at time -1 due to the sequence in schedule2.xls #case (2) # Y2=wage if self.agType == "workers" and self.employed: # the followin if/else structure is for control reasons because if # not common.wageCutForWorkTroubles we do not take in account # self.workTroubles also if != 0; if = 0 is non relevant in any # case if common.wageCutForWorkTroubles: self.consumption = common.a2 + \ common.b2 * common.wage * (1. - self.workTroubles) + \ gauss(0, common.consumptionRandomComponentSD) # print "worker", self.number, "wage x",(1.-self.workTroubles) else: self.consumption = common.a2 + \ common.b2 * common.wage + \ gauss(0, common.consumptionRandomComponentSD) #case (3) # Y3=socialWelfareCompensation if self.agType == "workers" and not self.employed: self.consumption = common.a3 + \ common.b3 * common.socialWelfareCompensation + \ gauss(0, common.consumptionRandomComponentSD) # update totalPlannedConsumptionInValueInA_TimeStep common.totalPlannedConsumptionInValueInA_TimeStep += self.consumption # print "C sum", common.totalPlannedConsumptionInValueInA_TimeStep # to entrepreneur def toEntrepreneur(self): if self.agType != "workers" or not self.employed: return myEntrepreneur = gvf.nx.neighbors(common.g, self)[0] myEntrepreneurProfit = myEntrepreneur.profit if myEntrepreneurProfit >= common.thresholdToEntrepreneur: print("I'm worker %2.0f and myEntrepreneurProfit is %4.2f" % (self.number, myEntrepreneurProfit)) common.g.remove_edge(myEntrepreneur, self) # originally, it was a worker if self.xPos > 0: gvf.pos[self] = (self.xPos - 15, self.yPos) # originally, it was an entrepreneur else: gvf.pos[self] = (self.xPos, self.yPos) # colors at http://www.w3schools.com/html/html_colornames.asp gvf.colors[self] = "LawnGreen" self.agType = "entrepreneurs" self.employed = True self.extraCostsResidualDuration = common.extraCostsDuration # to entrepreneurV3 def toEntrepreneurV3(self): if self.agType != "workers" or not self.employed: return # print float(common.absoluteBarrierToBecomeEntrepreneur)/ \ # len(self.agentList) if random() <= float(common.absoluteBarrierToBecomeEntrepreneur) / \ len(self.agentList): myEntrepreneur = gvf.nx.neighbors(common.g, self)[0] myEntrepreneurProfit = myEntrepreneur.profit myEntrepreneurCosts = myEntrepreneur.costs if myEntrepreneurProfit / myEntrepreneurCosts >= \ common.thresholdToEntrepreneur: print( "Worker %2.0f is now an entrepreneur (previous firm relative profit %4.2f)" % (self.number, myEntrepreneurProfit / myEntrepreneurCosts)) common.g.remove_edge(myEntrepreneur, self) # originally, it was a worker if self.xPos > 0: gvf.pos[self] = (self.xPos - 15, self.yPos) # originally, it was an entrepreneur else: gvf.pos[self] = (self.xPos, self.yPos) # colors at http://www.w3schools.com/html/html_colornames.asp gvf.colors[self] = "LawnGreen" self.agType = "entrepreneurs" self.employed = True self.extraCostsResidualDuration = common.extraCostsDuration # to workers def toWorker(self): if self.agType != "entrepreneurs": return if self.profit <= common.thresholdToWorker: print("I'm entrepreneur %2.0f and my profit is %4.2f" % (self.number, self.profit)) # the list of the employees of the firm, IF ANY entrepreneurWorkers = gvf.nx.neighbors(common.g, self) print("entrepreneur", self.number, "has", len(entrepreneurWorkers), "workers to be fired") if len(entrepreneurWorkers) > 0: for aWorker in entrepreneurWorkers: gvf.colors[aWorker] = "OrangeRed" aWorker.employed = False common.g.remove_edge(self, aWorker) self.numOfWorkers = 0 # originally, it was an entrepreneur if self.xPos < 0: gvf.pos[self] = (self.xPos + 15, self.yPos) # originally, it was a worker else: gvf.pos[self] = (self.xPos, self.yPos) # colors at http://www.w3schools.com/html/html_colornames.asp gvf.colors[self] = "OrangeRed" self.agType = "workers" self.employed = False # to workersV3 def toWorkerV3(self): if self.agType != "entrepreneurs": return # check for newborn firms try: self.costs except BaseException: return if self.profit / self.costs <= common.thresholdToWorker: print("I'm entrepreneur %2.0f and my relative profit is %4.2f" % (self.number, self.profit / self.costs)) # the list of the employees of the firm, IF ANY entrepreneurWorkers = gvf.nx.neighbors(common.g, self) print("entrepreneur", self.number, "has", len(entrepreneurWorkers), "workers to be fired") if len(entrepreneurWorkers) > 0: for aWorker in entrepreneurWorkers: gvf.colors[aWorker] = "OrangeRed" aWorker.employed = False common.g.remove_edge(self, aWorker) self.numOfWorkers = 0 # originally, it was an entrepreneur if self.xPos < 0: gvf.pos[self] = (self.xPos + 15, self.yPos) # originally, it was a worker else: gvf.pos[self] = (self.xPos, self.yPos) # colors at http://www.w3schools.com/html/html_colornames.asp gvf.colors[self] = "OrangeRed" self.agType = "workers" self.employed = False # work troubles def workTroubles(self): # NB this method acts with the probability set in the schedule.txt # file if self.agType != "entrepreneurs": return # production shock due to work troubles psiShock = uniform(common.productionCorrectionPsi / 2, common.productionCorrectionPsi) self.hasTroubles = psiShock print("Entrepreneur", self.number, "is suffering a reduction of " "production of", psiShock * 100, "%, due to work troubles") if common.wageCutForWorkTroubles: # the list of the employees of the firm entrepreneurWorkers = gvf.nx.neighbors(common.g, self) for aWorker in entrepreneurWorkers: # avoiding the entrepreneur herself, as we are refering to her # network of workers aWorker.workTroubles = psiShock # print "Worker ", aWorker.number, "is suffering a reduction of "\ # "wage of", psiShock*100, "%, due to work troubles" # get graph def getGraph(self): return common.g <file_sep>/6 objectSwarmObserverAgents_AESOP_turtleLib_NetworkX/oligopoly/oActions.py from Tools import * from Agent import * import time import csv import graphicDisplayGlobalVarAndFunctions as gvf import commonVar as common import pandas as pd import parameters as par # to eliminate an annoying warning at time 1 in time series plot import warnings warnings.filterwarnings("ignore", module="matplotlib") def do1b(address): # having the map of the agent agL = [] for ag in address.modelSwarm.agentList: agL.append(ag.number) agL.sort() # print "\noActions before drawGraph agents", agL # print "oActions before drawGraph nodes", common.g.nodes() # basic action to visualize the networkX output gvf.openClearNetworkXdisplay() gvf.drawGraph() def do2a(address, cycle): self = address # if necessary # ask each agent, without parameters print("Time = ", cycle, "ask all agents to report position") askEachAgentInCollection( address.modelSwarm.getAgentList(), Agent.reportPosition) def do2b(address, cycle): self = address # if necessary # ask a single agent, without parameters print("Time = ", cycle, "ask first agent to report position") if address.modelSwarm.getAgentList() != []: askAgent(address.modelSwarm.getAgentList()[0], Agent.reportPosition) def otherSubSteps(subStep, address): if subStep == "pause": input("Hit enter key to continue") return True elif subStep == "collectStructuralData": collectStructuralData(address.modelSwarm.agentList, common.cycle) return True elif subStep == "collectTimeSeries": collectTimeSeries(address.modelSwarm.agentList, common.cycle) return True elif subStep == "visualizePlot": visualizePlot() return True elif subStep == "prune": common.prune = True newValue = input(("Prune links with weight < %d\n" + "Enter to confirm " + "or introduce a new level: ") % common.pruneThreshold) if newValue != "": common.pruneThreshold = int(newValue) return True # this subStep performs only partially the "end" item; the execution # will continue in ObserverSwarm.py elif subStep == "end": if not common.IPython or common.graphicStatus == "PythonViaTerminal": # the or is about ipython running in a terminal # += and ; as first character because a first part # of the string toBeExecuted is already defined in # commonVar.py common.toBeExecuted += ";gvf.plt.figure(2);gvf.plt.close()" else: return False # collect Structural Data def collectStructuralData(aL, t): # creating the dataframe try: common.str_df except BaseException: common.str_df = pd.DataFrame(columns=['entrepreneurs', 'workers']) print("\nCreation of fhe structural dataframe\n") # print common.str_df nWorkers = 0 nEntrepreneurs = 0 for ag in aL: if ag.agType == "entrepreneurs": nEntrepreneurs += 1 if ag.agType == "workers": nWorkers += 1 # print nEntrepreneurs, nWorkers str_df2 = pd.DataFrame([[nEntrepreneurs, nWorkers]], columns=['entrepreneurs', 'workers']) # print str_df2 common.str_df = common.str_df.append(str_df2, ignore_index=True) # print common.str_df #warning: here the row index starts from 0 #(correctly in this case, being initial data # in each period) # collect time series def collectTimeSeries(aL, t): # creating the dataframe try: common.ts_df except BaseException: common.ts_df = pd.DataFrame( columns=[ 'unemployed', 'totalProfit', 'totalProduction', 'plannedProduction', 'price', 'wage']) print("\nCreation of fhe time series dataframe\n") # print common.ts_df unemployed = 0 for ag in aL: if not ag.employed: unemployed += 1 ts_df2 = pd.DataFrame([[unemployed, common.totalProfit, common.totalProductionInA_TimeStep, common.totalPlannedProduction, common.price, common.wage]], columns=['unemployed', 'totalProfit', 'totalProduction', 'plannedProduction', 'price', 'wage']) # print ts_df2 # set previous price (t-1) common.p0 = common.price common.ts_df = common.ts_df.append(ts_df2, ignore_index=True) # print common.ts_df #warning: here the row index starts from 0 # graphical function def visualizePlot(): # Matplotlib colors # http://matplotlib.org/api/colors_api.html # html colors # http://www.w3schools.com/html/html_colornames.asp if common.cycle == 1 and \ (not common.IPython or common.graphicStatus == "PythonViaTerminal"): # the or is about ipython running in a terminal gvf.plt.figure(2) mngr2 = gvf.plt.get_current_fig_manager() mngr2.window.wm_geometry("+0+0") mngr2.set_window_title("Time series") params = {'legend.fontsize': 10} gvf.plt.rcParams.update(params) if not common.IPython or common.graphicStatus == "PythonViaTerminal": # the or is about ipython running in a terminal gvf.plt.ion() f2 = gvf.plt.figure(2) gvf.plt.clf() myax = f2.gca() # myax.set_autoscale_on(True) ts_dfOut = common.ts_df # set index to start from 1 ts_dfOut.index += 1 myPlot = ts_dfOut.plot( secondary_y=[ 'price', 'wage'], marker="*", color=[ "OrangeRed", "LawnGreen", "Blue", "Violet", "Gray", "Brown"], ax=myax) myPlot.set_ylabel( 'unemployed, totalProfit, totalProduction, plannedProduction') myPlot.right_ax.set_ylabel('price, wage') myPlot.legend(loc='upper left') myPlot.axes.right_ax.legend(loc='lower right') if common.IPython and not common.graphicStatus == "PythonViaTerminal": # the and not is about ipython running in a terminal f2 = gvf.plt.figure() myax = f2.gca() # myax.set_autoscale_on(True) gvf.plt.title('Time Series') ts_dfOut = common.ts_df # set index to start from 1 ts_dfOut.index += 1 myPlot = ts_dfOut.plot( secondary_y=[ 'price', 'wage'], marker="*", color=[ "OrangeRed", "LawnGreen", "Blue", "Violet", "Gray", "Brown"], ax=myax) myPlot.set_ylabel( 'unemployed, totalProfit, totalProduction, plannedProduction') myPlot.right_ax.set_ylabel('price, wage') myPlot.legend(loc='upper left') myPlot.axes.right_ax.legend(loc='lower right') if not common.IPython or common.graphicStatus == "PythonViaTerminal": # the or is about ipython running in a terminal gvf.plt.figure(1) # gvf.plt.show() # gvf.plt.pause(0.01) #to display the sequence if common.IPython and not common.graphicStatus == "PythonViaTerminal": # the and not is about ipython running in a terminal gvf.plt.show() # saving time series via toBeExecuted in commonVar.py def saveTimeSeries(): # using methodProbs which is a distionary generated by SLAPP par.dataFrameAppend("from schedule.xls: work trouble probability", common.methodProbs["workTroubles"]) tt = time.strftime("%Y%m%d_%H-%M-%S") fileName = tt + "_par.csv" csvfile = open(common.pro + "/" + fileName, "w") common.par_df.to_csv(csvfile, index_label=False, index=False) csvfile.close() fileName = tt + "_ts.csv" csvfile = open(common.pro + "/" + fileName, "w") common.ts_df.to_csv(csvfile, index_label=False, index=False) csvfile.close() fileName = tt + "_str.csv" csvfile = open(common.pro + "/" + fileName, "w") common.str_df.to_csv(csvfile, index_label=False, index=False) csvfile.close() print("Three files with date and hour", tt, "written in oligopoly folder.")
b6bfc702337f2add83bec1971a8a80b93b5cd152
[ "Markdown", "Python", "Text" ]
8
Text
nickmancol/SLAPP3
11c00f5c3eaa2bc5251268b3fde1dd489b6223c3
d5e98a933dd5595bd548ab1d096d34eeb97f9884
refs/heads/master
<file_sep>function tallest_toll(element_class){ var get_class = "."+element_class ; var hf = 0; $(get_class).css("height", "auto"); $(get_class).each(function(){ var height_class = $(this).height(); if (height_class > hf ){ hf = height_class; }; }); $(get_class).css("height", hf); };<file_sep># tallest_tool the tallest tool is a jquery tool for calculating the most bigger height of the elements by a single class name. this tool add the equal height css for the all elements with using a specific css class.
a8a08db56c5a49da824cf5bb18d334e8db136b1b
[ "JavaScript", "Markdown" ]
2
JavaScript
alexandre135/tallest_tool
13efdb3e4ac453f0380b31b66c90b6e1abf45660
2d2a97ec1a4b6f3007a02c1489e8ee4861598546
refs/heads/master
<file_sep># -*- coding: utf-8 -*- # @Time : 2019-04-03 17:32 # @Author : zhangyihan # @File : git.py def new_test(): print(456) return 'zhangyihan' def test(): print(123) return 'zyh'
551c228bdfeb6ce6a637067db2a977e717ca7807
[ "Python" ]
1
Python
hanyce/git
3a5546fc85df99e68e91408b4f6b88489e7efca5
b344cdfde4b95c34d465b4b7048a515b0dd32d18
refs/heads/master
<repo_name>ddoubleH/algorithm<file_sep>/10845.py class queue(): def __init__(self): self.queue = [] self.len = 0 def push(self, N): self.queue.append(N) self.len += 1 def pop(self): try: delete = self.queue[0] del self.queue[0] self.len -= 1 return delete except: return -1 def empty(self): if len(self.queue) == 0: return 1 else: return 0 def size(self): return len(self.queue) def front(self): if queue is None: return -1 else: return self.queue[0] def back(self): if queue is None: return -1 else: return self.queue[-1] if __name__ == '__main__': N = int(input()) Q = queue() while(N > 0): N -= 1 Input = input().split() word = Input[0] if word == 'quit' or word == 'q': break elif word == 'push': Q.push(Input[1]) elif word == 'pop': print(Q.pop()) elif word == 'empty': print(Q.empty()) elif word == 'size': print(Q.size()) elif word == 'front': print(Q.front()) elif word == 'back': print(Q.back()) else: print('Command Not Found')
cb7512a1e9da4ec310a344f59c92d42df09ad014
[ "Python" ]
1
Python
ddoubleH/algorithm
811b563ad0dd2cdfd500aa6d26fc3662ebb7c4d1
5c82aba768320830c9c7da73969fac15fed37690
refs/heads/master
<file_sep># react-cli ![node](https://img.shields.io/node/v/webpack.svg) ![webpack](https://img.shields.io/badge/webpack-%5E4.x.x-brightgreen.svg) ![React](https://img.shields.io/badge/React-%5E16.4.2-yellow.svg) ![React-router](https://img.shields.io/badge/ReactRouter-%5E4.x.x-yellow.svg) ![Redux](https://img.shields.io/badge/ReactRedux-%5E4.0.0-yellow.svg) > 用最新webpack4搭建最好用的react脚手架 # react-cli开箱即用 ``` // 安装 npm install react-cli -g // 初始化 react-cli init ```<file_sep>import React from 'react' import ReactDOM from 'react-dom'; import ExampleHome from './pages/ExampleHome' ReactDOM.render(<ExampleHome/>, document.getElementById('root')) <file_sep># webpack-config webpack配置说明 ## webpack ### 1.1 初始化配置 安装最新的webpack4,webpack4抽离出来了webpack-cli,需要多安装webpack-cli ```js // npm init // npm install webpack webpack-cli --save-dev var path = require('path'); module.exports = { entry: { app: './src/app.client.js' }, output: { path: path.resolve(__dirname, './build'), filename: '[name].[chunkhash].js' }, resolve: {}, plugins: {}, optimization: {}, // webpack4新加入的配置 module: {}, devServer: {} } ``` ### 1.2 解析jsx和es6 解析jsx和es6最好先了解一下babel => babel https://babeljs.io/docs ```js // npm install babel-core babel-loader babel-preset-env babel-preset-react babel-preset-stage-0 babel-plugin-transform-decorators-legacy --save-dev module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: [ // 写在.babelrc文件里面的可以写在presets这里 [ 'env', { "targets": { // 要针对的都是特定范围的浏览器,移动端可以修改成更高版本浏览器 "browsers": ["ie >= 8", 'chrome >= 52'] } } ], 'react', 'stage-0' ], plugins: ["transform-decorators-legacy"] } }, ] } ``` ### 1.3 生成模板文件并引入打包文件 ```js // npm install html-webpack-plugin --save-dev plugins: [ // 自动在'output'打包路径里生成模板文件并引入打包文件 new HtmlWebpackPlugin({ filename: 'index.html', template: 'tmp-index.html', }) ], ``` ### 1.4 打包css、sass/less 从js中提取css,webpack4官方不在推荐使用 extract-text-webpack-plugin了,改换 mini-css-extract-plugin 基本配置如下: ```js // 处理style,css => npm install style-loader css-loader --save-dev // sass/less => sass-loader node-sass less less-loader // 生产环境从js中提取css => mini-css-extract-plugin module:{ rules:[ { test: /\.(sa|sc|le|c)ss$/, exclude: '/node_modules', use: [ // development环境用style-loader把css放入style标签中,非development环境从js中分离css env === 'development' ? 'style-loader' : MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader', 'less-loader' ] }, ] } ``` 生产环境下的压缩css配置优化: 压缩css安装optimize-css-assets-webpack-plugin,放在optimization.minimizer里,但是会覆盖默认压缩js操作,所以还需要安装uglifyjs-webpack-plugin去压缩技术. ```js // webpack.prod.conf.js plugins: [ // MiniCssExtractPlugin => extract css new MiniCssExtractPlugin({ filename: '[name].[hash].css', chunkFilename: '[id].[hash].css' }) ], optimization: { minimizer: [ new UglifyJsPlugin({ // comporess js (optimize) cache: true, parallel: true, sourceMap: true }), new OptimizeCSSAssetsPlugin({}) // compress css(optimize) ], }, module: { ...rules } ``` ### 1.5 处理css3属性前缀 ```js // postcss-loader { test: /\.(sa|sc|le|c)ss$/, exclude: '/node_modules', use: [ 'style-loader', 'css-loader', 'postcss-loader', 'sass-loader', ] } ``` 新建postcss.config.js配置文件 ```js // postcss-import postcss-cssnext module.exports = { plugins: { 'postcss-import': {}, // import css need 'postcss-cssnext': {} // suport css4 } } ``` ### 1.6 url-loader url-loader处理文件,图片等 ```js // url-loader { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: path.posix.join('static', 'img/[name].[hash:7].[ext]') } } ``` ### 1.7 hotReload ```js // webpack.dev.conf.js // webpack-dev-server plugins: [ new webpack.HotModuleReplacementPlugin() ], devServer: { clientLogLevel: 'warning', // browser print info of webpack-dev-server contentBase: path.join(__dirname, '/dist'), inline: true, hot: true, host: 'localhost', port: config.port, publicPath: '/', open: false, } ``` package.json ``` "dev": "cross-env NODE_ENV=development webpack-dev-server --config ./build/webpack.dev.conf.js", ``` <file_sep># webpack-config
970eefe4b8c36714fe372738bfb814b498599f4f
[ "Markdown", "JavaScript" ]
4
Markdown
reactjs-template/webpack
e7ed07fc3ccc5357ce5a931c57571cf8578b633f
7192fbdd35bed6882041d2dc4a051e013c5ea36c
refs/heads/main
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Vex : MonoBehaviour { public bool isFollowing = false; public float speed = 4; private Rigidbody2D enemyRb; private GameObject player; private SpriteRenderer enemySprite; public int eHealth = 3; private Game game; // Start is called before the first frame update void Start() { game = GameObject.Find("Game").GetComponent<Game>(); player = GameObject.Find("dino"); enemyRb = GetComponent<Rigidbody2D>(); enemySprite = GetComponent<SpriteRenderer>(); } // Update is called once per frame void Update() { if (isFollowing) { Vector2 lookDirection = (player.transform.position - transform.position).normalized; enemyRb.AddForce(lookDirection * speed); } if (enemyRb.velocity.x > 0) { enemySprite.flipX = true; } else { enemySprite.flipX = false; } if (eHealth <= 0) { Destroy(gameObject); } } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.name == "dino") { isFollowing = true; } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.CompareTag("dirt")) { UpdateEHealth(1); Destroy(collision.gameObject); enemyRb.isKinematic = true; enemyRb.isKinematic = false; } if (collision.gameObject.name == "dino") { game.UpdateHealth(1); } } public void UpdateEHealth(int eHealthToTake) { eHealth -= eHealthToTake; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class WalkEnemy : MonoBehaviour { public float speed; private Rigidbody2D enemyRb; private GameObject player; private SpriteRenderer enemySprite; public int eHealth; public GameObject rain; public bool noRain = false; public float noRainCounter = 0; public float noRainTime = 0.667f; public bool isFollowing = false; // Start is called before the first frame update void Start() { enemyRb = GetComponent<Rigidbody2D>(); player = GameObject.Find("dino"); enemySprite = GetComponent<SpriteRenderer>(); UpdateEHealth(0); } // Update is called once per frame void Update() { if (isFollowing) { Vector2 lookDirection = (player.transform.position - transform.position).normalized; enemyRb.AddForce(lookDirection * speed, 0); noRainCounter += Time.deltaTime; if (noRainCounter >= noRainTime) { GameObject rainDrop = Instantiate(rain, transform); rainDrop.GetComponent<Rigidbody2D>().velocity = new Vector2(0, -1); noRainCounter = 0; } } if (enemyRb.velocity.x > 0) { enemySprite.flipX = true; } else { enemySprite.flipX = false; } if (eHealth <= 0) { Destroy(gameObject); } } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.name == "dino") { isFollowing = true; } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.CompareTag("dirt")) { UpdateEHealth(1); Destroy(collision.gameObject); enemyRb.isKinematic = true; enemyRb.isKinematic = false; } } public void UpdateEHealth(int eHealthToTake) { eHealth -= eHealthToTake; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine.SceneManagement; using UnityEngine; using TMPro; public class Game : MonoBehaviour { public int health = 5; public TextMeshProUGUI healthText; public GameObject loseScreen; public GameObject player; public GameObject restart; // Start is called before the first frame update void Start() { health = 5; UpdateHealth(0); loseScreen.gameObject.SetActive(false); player = GameObject.Find("dino"); //restart = GameObject.Find("restart"); } // Update is called once per frame void Update() { if (health <= 0) { loseScreen.SetActive(true); restart.SetActive(true); } if (health < 0) { health = 0; } } public void UpdateHealth(int healthToTake) { if (health > 0) { health -= healthToTake; healthText.text = "Health: " + health; } } public void loadLevel() { SceneManager.LoadScene("SampleScene"); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class Player : MonoBehaviour { public float speed; public float bulletSpeed; public Rigidbody2D playerRb; public float jumpForce; public float horizontalInput; public GameObject dirt; public bool hasBeenHit = false; public bool invulnerable = false; public float invulnerableCounter = 0; public float invulnerableTime = 1.5f; private Quaternion zero = new Quaternion(); private Game game; private Animator dinoAnimator; private SpriteRenderer dinoSprite; public float dirtCounter = 0; public float noDirtTime = 0.15f; // Start is called before the first frame update void Start() { game = GameObject.Find("Game").GetComponent<Game>(); dinoAnimator = GetComponent<Animator>(); dinoSprite = GetComponent<SpriteRenderer>(); } // Update is called once per frame void Update() { // Check to see if player is Alive (Health <= 0) Vector2 velocity = playerRb.velocity; velocity.x = Input.GetAxisRaw("Horizontal") * speed; dirtCounter += Time.deltaTime; if (Input.GetKeyDown(KeyCode.Space) && playerRb.velocity.y < 0.05 && playerRb.velocity.y > -0.05) { velocity.y = jumpForce; } if (playerRb.velocity.x != 0) { dinoAnimator.SetBool("isWalking", true); } else { dinoAnimator.SetBool("isWalking", false); } if(playerRb.velocity.x < 0) { dinoSprite.flipX = true; } else if(playerRb.velocity.x > 0) { dinoSprite.flipX = false; } if (hasBeenHit) invulnerable = true; if (invulnerable) { invulnerableCounter += Time.deltaTime; if(invulnerableCounter >= invulnerableTime) { invulnerable = false; hasBeenHit = false; invulnerableCounter = 0; } } if (game.health<=0) { gameObject.SetActive(false); } if (Input.GetKeyDown(KeyCode.Keypad0) && dirtCounter > noDirtTime) { GameObject bullet = Instantiate(dirt, transform); if (dinoSprite.flipX == true) { bullet.transform.SetPositionAndRotation(new Vector3(bullet.transform.position.x - 1, bullet.transform.position.y, bullet.transform.position.z), zero); bullet.GetComponent<Rigidbody2D>().velocity = new Vector2(-1 * bulletSpeed, 0); } else { bullet.transform.SetPositionAndRotation(new Vector3(bullet.transform.position.x + 1, bullet.transform.position.y, bullet.transform.position.z), zero); bullet.GetComponent<Rigidbody2D>().velocity = new Vector2(1 * bulletSpeed, 0); } } if (Input.GetKeyDown(KeyCode.Keypad0) && dirtCounter > noDirtTime) { dirtCounter = 0; } //transform.Translate(Vector2.right * speed * horizontalInput); playerRb.velocity = velocity; } private void OnCollisionStay2D(Collision2D collision) { // If collide with enemy, health -= 1; if (collision.gameObject.CompareTag("EnemyWeak")) { game.UpdateHealth(1); } if(collision.gameObject.CompareTag("Enemy") && !invulnerable) { game.UpdateHealth(1); hasBeenHit = true; } if (collision.gameObject.CompareTag("rain") && !invulnerable) { game.UpdateHealth(1); hasBeenHit = true; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class RainDrop : MonoBehaviour { private Game game; // Start is called before the first frame update void Start() { game = GameObject.Find("Game").GetComponent<Game>(); } // Update is called once per frame void Update() { } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.CompareTag("floor")) { Destroy(gameObject); } if (collision.gameObject.CompareTag("Enemy")) { Destroy(gameObject); } if (collision.gameObject.CompareTag("Player")) { Destroy(gameObject); game.UpdateHealth(1); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Coznix : MonoBehaviour { public bool isFollowing = false; public GameObject Vex; private SpriteRenderer enemySprite; public int eHealth = 30; public float vexSpawnCounter = 0; public float vexSpawnWaitTime = 8f; private Rigidbody2D enemyRb; private GameObject player; // Start is called before the first frame update void Start() { enemyRb = GetComponent<Rigidbody2D>(); enemySprite = GetComponent<SpriteRenderer>(); player = GameObject.Find("dino"); } // Update is called once per frame void Update() { if (isFollowing) { vexSpawnCounter += Time.deltaTime; if (vexSpawnCounter >= vexSpawnWaitTime) { GameObject rainDrop = Instantiate(Vex, transform); vexSpawnCounter = 0; } } if (eHealth <= 0) { Destroy(gameObject); } } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.name == "dino") { isFollowing = true; } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.CompareTag("dirt")) { UpdateEHealth(1); Destroy(collision.gameObject); enemyRb.isKinematic = true; enemyRb.isKinematic = false; } } public void UpdateEHealth(int eHealthToTake) { eHealth -= eHealthToTake; } }
bcb95797ab51b2a6dc6de10414ac7c71feedf560
[ "C#" ]
6
C#
Eliii97/Cloud-Game
07cda27575768c86bd2c7600b156b0de7dd7c866
5dfb0e6bf68ba6f36aa4c5969d33ffdba1e4ae4b
refs/heads/master
<file_sep>/** * Subclass extending from the Shape superclass, used for modelling squares * * @author <NAME>(3035437692) */ class Square extends Shape{//inherits class Shape public void setVertices(double d){ /** * The method overrides setVertices(double d) present in the class Shape and assigns values of the coordinates of the 4 vertices of a square */ xLocal=new double[4];//size 4 for storing the 4 vertices of the square xLocal[0]=d; xLocal[1]=d; xLocal[2]=-d; xLocal[3]=-d; yLocal=new double[4];//size 4 for storing the 4 vertices of the square yLocal[0]=d; yLocal[1]=-d; yLocal[2]=-d; yLocal[3]=d; }//end of setVertices(double) }<file_sep># Shapes Canvas Built a canvas using GUI programming for drawing random shapes ![](images/Screen%20Shot.png) <file_sep>/** * To verify that the subclass RegularPolygon has been implemented correctly and consists of no errors * * @author <NAME>(3035437692) * */ public class RegularPolygonTester{ /** * The method accesses the setters of RegularPolygon class to initialize the respective variables and outputs the * values of the variables obtained from the getters to check whether the instance variables * have been accessed correctly * * @param Polygon1 an object of the class RegularPolygon which models general n-sided polygon * @param Polygon2 an object of the class RegularPolygon which models general n-sided polygon * @param Polygon3 an object of the class RegularPolygon which models general n-sided polygon */ public static void main(String[] args){ RegularPolygon Polygon1 = new RegularPolygon();//use of no argument constructor System.out.println(Polygon1.getNumOfSides());//use of getter System.out.println(Polygon1.getRadius());//use of getter Polygon1.setRadius(-15.0);//we use negative numbers to force the setter to initialize radius properly Polygon1.setNumOfSides(5);//use of setter System.out.println(Polygon1.getNumOfSides());//use of getter System.out.println(Polygon1.getRadius());//use of getter System.out.println(Polygon1.contains(1, 2));//contains() is called to check the location of point RegularPolygon Polygon2 = new RegularPolygon(-1);//use of 1 argument constructor System.out.println(Polygon2.getNumOfSides());//use of getter System.out.println(Polygon2.getRadius());//use of getter Polygon2.setRadius(3.0);//use of setter Polygon2.setNumOfSides(-9);//we use negative numbers to force the setter to initialize the number of sides properly System.out.println(Polygon2.getNumOfSides());//use of getter System.out.println(Polygon2.getRadius());//use of getter System.out.println(Polygon2.contains(3, 4));//contains() is called to check the location of point RegularPolygon Polygon3 = new RegularPolygon(8, -5.5);//use of 2 arguments constructor System.out.println(Polygon3.getNumOfSides());//use of getter System.out.println(Polygon3.getRadius());//use of getter Polygon3.setRadius(15.5);//use of setter Polygon3.setNumOfSides(10);//use of setter System.out.println(Polygon3.getNumOfSides());//use of getter System.out.println(Polygon3.getRadius());//use of getter System.out.println(Polygon3.contains(5, 6));//contains() is called to check the location of point } }<file_sep>/** * Subclass extending from the Shape superclass, used for modelling circles * * @author <NAME>(3035437692) */ class Circle extends Shape{//inherits class Shape public void setVertices(double d){ /** * The method overrides setVertices(double ) present in the class Shape and assigns values of the local coordinates of the upper * left and lower right vertices of an axis-aligned bounding box of a circle */ xLocal=new double[2];//size 2 for storing the upper left and lower right vertices of the axis-aligned bounding box of a circle xLocal[0]=-d; xLocal[1]=d; yLocal=new double[2];//size 2 for storing the upper left and lower right vertices of the axis-aligned bounding box of a circle yLocal[0]=-d; yLocal[1]=d; }//end of setVertices(double) public int[] getX(){ /** * The method overrides getX() present in the class Shape and retrieves the x-coordinates of the upper left and lower * right vertices of an axis-aligned bounding box of the circle in the screen coordinate * system * * @return xLocalint x-coordinates of the vertices of the circle in screen coordinate system */ int xLocalint[]=new int[xLocal.length]; for(int i=0;i<xLocal.length;i++) xLocalint[i]=(int)(xLocal[i]+xc);//rounding to integers return xLocalint; } public int[] getY(){ /** * The method overrides getY() present in the class Shape and retrives the y-coordinates of the upper left and lower * right vertices of an axis-aligned bounding box of the circle in the screen coordinate * system * * @return yLocalint y-coordinates of the vertices of the circle in screen coordinate system */ int yLocalint[]=new int[yLocal.length]; for(int i=0;i<yLocal.length;i++) yLocalint[i]=(int)(yLocal[i]+yc);//rounding to integers return yLocalint; } }
fc0d2bf3d11a2cf7155404f8b1fe6376f9fd0427
[ "Markdown", "Java" ]
4
Java
bratinghosh/Shapes-Canvas
da872eb14f05cc68e29bdf6fc57930503b3b961d
29b91997fa20f7af61712603104f65c07a664a45
refs/heads/master
<repo_name>kierandenshi/redux-flash-message<file_sep>/component.js import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { deleteFlashMessage, hideFlashMessage, timeoutFlashMessage, } from './actions'; import './component.scss'; class FlashMessage extends Component { componentWillReceiveProps(nextProps) { const { messages } = nextProps; Object.keys(messages).forEach(messageId => { if(messages[messageId].timeout) { this.handleSetTimeout(messageId); } }); } handleSetTimeout(id) { this.props.timeoutFlashMessage(id); setTimeout(() => {this.handleDismiss(id);}, 3000); } handleDismiss(id) { this.props.hideFlashMessage(id); setTimeout(() => {this.handleDelete(id);}, 1000); } handleDelete(id) { this.props.deleteFlashMessage(id); } renderMessages() { const { messages } = this.props; return Object.keys(messages).map(messageId => { const { id, className, text, dismissable, visible } = messages[messageId]; return ( <div className={`flash-message__message ${visible ? 'visible' : 'hidden'} ${className ? className : ''}`}> <div className={'flash-message__text'}>{text}</div> {dismissable && ( <div className={'flash-message__dismiss'} onClick={() => {this.handleDismiss(id);}} /> )} </div> ); }); } render() { return ( <div className={'flash-message'}> {this.renderMessages()} </div> ); } } FlashMessage.propTypes = { messages: PropTypes.array, }; export default connect( (state) => ({ messages: state.flashMessage, }), { deleteFlashMessage, hideFlashMessage, timeoutFlashMessage, } )(FlashMessage); <file_sep>/README.md # redux-flash-message<file_sep>/reducer.js import { FLASH_MESSAGE_SHOW, FLASH_MESSAGE_HIDE, FLASH_MESSAGE_DELETE, FLASH_MESSAGE_TIMEOUT, } from './actions.js'; const initialState = {}; export default (state = initialState, { type, value })=>{ switch(type) { case FLASH_MESSAGE_SHOW: const messageId = `fm${Date.now()}`; return { ...state, [messageId]: { id: messageId, visible: true, dismissable: value.dismissable || true, text: value.text || '', timeout: value.timeout || false, className: value.className || null, }, }; case FLASH_MESSAGE_TIMEOUT: return { ...state, [value]: { ...state[value], timeout: false, }, }; case FLASH_MESSAGE_HIDE: return { ...state, [value]: { ...state[value], visible: false, }, }; case FLASH_MESSAGE_DELETE: return Object.keys(state).reduce((memo, id) => { if(id !== value) { memo[id] = state[id]; } return memo; }, {}); default: return state; } };
9b416519c11b04ee302cfa601e3ec7a75993f314
[ "JavaScript", "Markdown" ]
3
JavaScript
kierandenshi/redux-flash-message
49c99134677ffadff62ae71f610a647d291c5b73
139a8083b929a251d3bf9c2264b9ebdd8bbcd935
refs/heads/master
<file_sep>package main import "io/ioutil"
d07c902b3810ed608990bb86ee3355e2b6054266
[ "Go" ]
1
Go
davetapson/go-webserver-with-mssql-access
8c158bcb162590d9b6e9c0a36485c8511c00c287
b706ad2826608da8c7cc0625563c7d38dd0d5991
refs/heads/master
<file_sep>module.exports = function check(str, bracketsConfig) { // const check = (str, bracketsConfig) => { let expected = []; let ret = ''; let br; let brackets = {}; bracketsConfig.map(_ => { brackets[_[0]] = _[1]; }); br = str.split(''); br.map(item => { console.log(item); if (brackets[item]) { if ((brackets[item] == '|' && expected[expected.length-1] == '|') || (brackets[item] == '7' && expected[expected.length-1] == '7') ||(brackets[item] == '8' && expected[expected.length-1] == '8')) { expected.pop(); } else { expected.push(brackets[item]); } } else { if (expected.length == 0) { expected.push('null'); } if (item === expected[expected.length-1]) { expected.pop(); } } }); return expected.length == 0 ? true : false; } //console.log(check(')()',[['(', ')'], ['[', ']'], ['{', '}'], ['|', '|']]));
a3f80ddbec0d94e0fb902d9975449a76407c9f33
[ "JavaScript" ]
1
JavaScript
ReaziS/brackets
fcd3b246afc275bdab0427336dd687d8459fefc4
f51896b483480a0eabdaf3cd99a81cae639ec885
refs/heads/main
<file_sep>import React, { Fragment, useState } from "react"; const InputTodo = () => { const [description, setDescription] = useState(""); const onChange = (e) => setDescription(e.target.value); return ( <Fragment> <h1 className="text-center mt-5">Todo List</h1> <form className="d-flex mt-5"> <input type="text" className="form-control" value={description} onChange={onChange} /> <button className="btn btn-success">Add</button> </form> </Fragment> ); }; export default InputTodo; <file_sep># Todo-List A simple Todo list implemented using the PERN stack (Postgres, Express, React, Node)
b255638d3f6991aecadf1af8a95baa1b6f01919d
[ "JavaScript", "Markdown" ]
2
JavaScript
Jovahkin259/todo-list
df81004d0574d498b47051917d0cd9cfcf76d0a2
e7e2cf006e7d7a19a48f512b403dac452d919855
refs/heads/master
<repo_name>PlaidCloud/google-cloud-functions<file_sep>/slack-alerts/README.md # Slack Alerts via Google Pub/Sub API This cloud function will read all messages from a Pub/Sub topic and generate slack messages for them in a generalized manner (sans IAM policy changes, which have a custom message format). ### tl;dr - One or more [log sinks](https://console.cloud.google.com/logs/router?project=plaidcloud-io) publish log messages to a [Pub/Sub topic](https://console.cloud.google.com/cloudpubsub/topic/detail/alerts?project=plaidcloud-io). - [Logs explorer](https://console.cloud.google.com/logs/query?project=plaidcloud-io&query=%0A) has a [query builder](https://cloud.google.com/logging/docs/view/building-queries) that can be leveraged to write useful log queries. - These [log queries](https://cloud.google.com/logging/docs/view/advanced-queries) can then be copy/pasted into the [logs filter](https://cloud.google.com/logging/docs/export#sink-terms) for each log sink to include only relevant logs. - [`slack-alerts`](https://console.cloud.google.com/functions/details/us-central1/slack-alerts?project=plaidcloud-io) cloud function then subscribes to this Pub/Sub topic, posting each log entry as a Slack message. - See [How to Use](#how-to-use) below for info on setting up and installing this cloud function for use in your GCP setup. ### How Alerts are Gathered The [Logs Explorer](https://cloud.google.com/logging/docs/view/logs-viewer-interface) in GCP provides means of querying all logs generated by our cloud infrastructure, including IAM policy changes and container restarts in GKE. Each entry follows the [`LogEntry`](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry) JSON schema, which provides many details about the event that was logged. `LogEntry` JSON objects can contain a protoPayload field of type [`AuditLog`](https://cloud.google.com/logging/docs/reference/audit/auditlog/rest/Shared.Types/AuditLog), which is especially useful with IAM policy changes and other special sorts of audit logging. To gather relevant log messages for generating alerts, we create something called a 'log sink' to find matching log entries and forward them to a chosen destination, such as a storage bucket or a [Pub/Sub](https://cloud.google.com/pubsub/docs/overview) topic. An overview of log routing can be found [here](https://cloud.google.com/logging/docs/routing/overview). In the case of `slack-alerts`, we are subscribing to a [Pub/Sub](https://cloud.google.com/pubsub/docs/overview) topic that one or more log sinks are publishing to. ### How Alerts are Posted As a cloud function, `slack-alerts` is configured to subscribe to a Pub/Sub topic. For each message in said topic, `slack-alerts` will execute by consuming the log entry and posting a relevant formatted message to a slack channel via webhook. ### How to Use - Fork and clone this repo. - Add an `env.yaml` file under `slack-alerts` directory. - The [structure of this file](https://cloud.google.com/functions/docs/env-var) is flat and entirely key-value, where the keys are the env var names and the values are their values. - `SLACK_WEBHOOK` must be specified for posting to work. Without a valid webhook, this function will fail. - i.e. `SLACK_WEBHOOK: https://hooks.slack.com/services/<KEY>` - Run the command in `deploy.sh` to publish your cloud function, editing it as needed for your application. - For testing locally: - Install `requirements.txt` using `pip install -r requirements.txt` (preferably in a virtualenv). - Add a `test_resources` directory under `slack-alerts`. - Add any number of JSON files to `test_resources` dir that each contain a single sample log entry exported from Logs Explorer. - Run `python main.py`. <file_sep>/README.md # Cloud Fuctions A growing collection of general purpose cloud functions. <file_sep>/slack-alerts/main.py import os import json import base64 import requests from dotmap import DotMap from enum import IntEnum from slack.errors import SlackApiError ROLE_URL = "https://cloud.google.com/iam/docs/understanding-roles#{}" IAM_URL = "https://console.cloud.google.com/iam-admin/iam?project={}" LIST_TEMPLATE = ">• {label}: `{item}`" LIST_URL_TEMPLATE = "• {label}: `<{url}|{item}>`" PAST_TENSE_ACTION = { "ADD": "*_added_*", "REMOVE": "*_removed_*", } class Severity(IntEnum): DEFAULT = 0 # The log entry has no assigned severity level. DEBUG = 100 # Debug or trace information. INFO = 200 # Routine information, such as ongoing status or performance. NOTICE = 300 # Normal but significant events, such as start up, shut down, or a configuration change. WARNING = 400 # Warning events might cause problems. ERROR = 500 # Error events are likely to cause problems. CRITICAL = 600 # Critical events cause more severe problems or outages. ALERT = 700 # A person must take an action immediately. EMERGENCY = 800 # One or more systems are unusable. slack_webhook = os.environ.get('SLACK_WEBHOOK') def _format_message(message_info): message_template = f">*({message_info.severity}) {message_info.method}*\n" for key, value in message_info.items(): message_template += LIST_TEMPLATE.format(label=key, item=value) + '\n' return {"mrkdown": True, "text": message_template} def _format_iam_message(message_info): # TODO: Create templates for each event to be handled # TODO: Pick template based on method message_template = ( f">*(INFO) IAM Policy Update*\n" f">Roles were modified for an external user:\n" f">• user: `{message_info.user}`\n" f">• target_user: `{message_info.target_user}`\n" f">• change: {PAST_TENSE_ACTION[message_info.action]} `<{ROLE_URL.format(message_info.role)}|{message_info.role}>` role.\n" f">• project: `{message_info.project_id}`\n" f">:cloud: <{IAM_URL.format(message_info.project_id)}|View in Cloud Console>\n" ) return {"mrkdown": True, "text": message_template} def parse_base_info(message, fields=None): if not fields: fields = dict() fields["severity"] = message.severity fields["method"] = message.protoPayload.methodName fields[message.resource.type] = message.protoPayload.resourceName.split("/")[-1] fields["project_id"] = message.resource.labels.project_id fields["zone"] = message.resource.labels.zone fields["user"] = message.protoPayload.authenticationInfo.principalEmail return fields def parse_iam_policy_change_info(message, fields): # Audit log messages for IAM policy changes have some unique fields to parse. policy_delta = message.protoPayload.serviceData.policyDelta fields["target_user"] = policy_delta.bindingDeltas[0].member.split(":")[1] fields["action"] = policy_delta.bindingDeltas[0].action fields["role"] = policy_delta.bindingDeltas[0].role.split("/")[1] return fields def parse_event(event): message = DotMap(json.loads(base64.b64decode(event["data"]).decode("utf-8"))) fields = parse_base_info(message) if fields["method"] == "SetIamPolicy": fields = parse_iam_policy_change_info(message, fields) if Severity[fields["severity"]] > Severity.INFO: fields["status"] = f"({str(message.protoPayload.status.code)}) {message.protoPayload.status.message}" return DotMap(fields) def send_slack_alert(event, context): """Post a message to a slack channel. Args: event (dict): The dictionary with data specific to this type of event. The `data` field contains the PubsubMessage message. The `attributes` field will contain custom attributes if there are any. context (google.cloud.functions.Context): The Cloud Functions event metadata. The `event_id` field contains the Pub/Sub message ID. The `timestamp` field contains the publish time. """ formatting_handlers = { "SetIamPolicy": _format_iam_message, "default": _format_message, } try: parsed_event = parse_event(event) handler = formatting_handlers.get(parsed_event.method) if not handler: handler = formatting_handlers["default"] formatted_message = handler(parsed_event) response = requests.post( slack_webhook, json.dumps(formatted_message, sort_keys=True, indent=4, separators=(",", ": ")) ) response.raise_for_status() except requests.exceptions.RequestException as e: print(e) if __name__ == "__main__": import yaml import pathlib with open("env.yaml", 'r') as stream: env = yaml.safe_load(stream) slack_webhook = env['SLACK_WEBHOOK'] resource_dir = pathlib.Path(__file__).parent.absolute().joinpath('test_resources') for resource in resource_dir.glob('**/*.json'): with resource.open("rb") as json_file: # Simulate inbound pubsub message by base64-encoding the JSON string on the 'data' field. send_slack_alert(event={"data": base64.b64encode(json_file.read())}, context={}) <file_sep>/slack-alerts/requirements.txt dotmap==1.3.22 requests==2.24.0 slackclient==2.9.2
919124e3e6c06d25ad03a96dd6607bdf1d716bd6
[ "Markdown", "Python", "Text" ]
4
Markdown
PlaidCloud/google-cloud-functions
abed4fa2fa282ba7a47c3a4ad1db9167f50e94db
42bb0ff98d1ad2ed61b8a03dd6b77d89a02991e7
refs/heads/master
<repo_name>MogaCristina/ArduinoPongGame<file_sep>/pong20.ino #include <U8glib.h> #include "U8glib.h" //pinii lcd-ului U8GLIB_PCD8544 u8g(7, 6, 4, 5, 3); // CLK=7, DIN=6, CE=4, DC=5, RST=3 #define backlight 11 int Jucator1Pin = A1; // Pin potentiomentru jucator stanga int Jucator2Pin = A0; // Pin potentiomentru jucator dreapta int ScorCastigator = 7; // Scorul pentru Winner int VitezaInit = 30; // Viteza initiala pentru inceput de joc u8g_uint_t LatimeTeren, InaltimeTeren, HalfLatimeTeren; u8g_uint_t MarimeMinge = 4; u8g_uint_t Minge0X; u8g_uint_t DirectieMinge0X = 1; u8g_uint_t Minge0Y; u8g_uint_t DirectieMinge0Y= 1;//directia se va incrementa cu 1 u8g_uint_t LBaraJucator = 2;//latimea barii jucatorului este de 2 u8g_uint_t HBaraJucator = 8;//inaltimea este de 8, jocul este cu barele pe verticala u8g_uint_t HalfHBaraJucator = HBaraJucator/2; u8g_uint_t JucatorStangaPoz0Y; // Jucator stanga pozitie pe verticala u8g_uint_t JucatorDreaptaPoz0Y; //Jucator dreapta pozitie pe verticala int ScorJucatorStanga, ScorJucatorDreapta; // Scoruri jucatori stanga si dreapta bool JocTerminat = false; unsigned long MutareMinge; // vom stoca timpul in functie de care se va misca mingea int VitezaActuala = VitezaInit; // Viteza curenta a mingii //Partea de desenare a jocului //cand jocul e terminal afiseaza pe ecran "Joc Terminat" void JocGata(){ u8g.setFont( u8g_font_timB14); u8g.setColorIndex(1); u8g.setFontPosCenter(); char str1[] = "Joc"; char str2[] = "Terminat"; u8g_uint_t s1 = (LatimeTeren - u8g.getStrPixelWidth(str1)) / 2; u8g_uint_t s2 = (LatimeTeren - u8g.getStrPixelWidth(str2)) / 2; u8g.drawStr(s1, 20, str1); u8g.drawStr(s2, 40, str2); int Jucator1Acord=analogRead(Jucator1Pin); int Jucator2Acord=analogRead(Jucator2Pin); if(Jucator1Acord==0) if(Jucator2Acord==0){ delay(2000); JocTerminat=false; ScorJucatorStanga=0; ScorJucatorDreapta=0; } } //afiseaza scorul actual void Scor(){ u8g.setFont(u8g_font_unifont); u8g.setColorIndex(1);//index 1 -> pixel on char strScorJucatorStanga[] = " "; char strScorJucatorDreapta[] = " "; strScorJucatorStanga[0] = '0' + ScorJucatorStanga; strScorJucatorDreapta[0] = '0' + ScorJucatorDreapta; u8g.setFont(u8g_font_04b_03b); //afla latimea intului in pixeli u8g_uint_t latimescor = u8g.getStrPixelWidth(strScorJucatorStanga); u8g_uint_t scoreY = 7;//am dat int-ul pt scorul maxim ca poz Y in functie //am scazut si adunat 7 ca sa aliniez mai bine socrurile/distantele dintre ele u8g.drawStr( HalfLatimeTeren - 7 - latimescor, scoreY, strScorJucatorStanga); u8g.drawStr( HalfLatimeTeren + 7, scoreY, strScorJucatorDreapta); } //desenarea barilor de joc pentru playeri void BaraUnJucator(int L, int H){ u8g.setFont(u8g_font_profont11); u8g.drawBox(L, H, LBaraJucator, HBaraJucator); } void BareJucatori(){ u8g.setFont(u8g_font_profont11); u8g.setColorIndex(1); //citirea valorilor de miscare se face de pe potentiometre int rawDataStg=analogRead(Jucator1Pin);//jucator stanga JucatorStangaPoz0Y = map(rawDataStg, 0, 1023, 0, InaltimeTeren - HBaraJucator); int rawDataDr=analogRead(Jucator2Pin);//jucator dreapta JucatorDreaptaPoz0Y = map(rawDataDr, 0, 1023, 0, InaltimeTeren - HBaraJucator); //desenez bara pentru jucatorul din stanga BaraUnJucator(0, JucatorStangaPoz0Y); //desenez bara pt jucatorul din dreapta BaraUnJucator(LatimeTeren - LBaraJucator, JucatorDreaptaPoz0Y); } //Partea de joc in sine //bara nelovita, lovitura ratata bool PeLangaBara(u8g_uint_t py){ u8g_uint_t MingeBottom = Minge0Y; u8g_uint_t MingeTop= Minge0Y + MarimeMinge - 1; u8g_uint_t BaraBottom = py; u8g_uint_t BaraTop = py + HBaraJucator - 1; return MingeBottom > BaraTop || MingeTop < BaraBottom; } //daca a ratat jucatorul din stanga mingea void JucatorStangaMiss(){ // Mingea se va servi de pe mijlocul barii de joc a jucatorului din dreapta Minge0X = LatimeTeren - MarimeMinge - 1; Minge0Y = JucatorDreaptaPoz0Y + HalfHBaraJucator; //creste scorul jucatorului din dreapta ScorJucatorDreapta++; //se revine la viteza initiala de joc VitezaActuala = VitezaInit; //testez daca e castigator if(ScorJucatorDreapta == ScorCastigator) JocTerminat = true; } //daca a ratat jucatorul din dreapta mingea void JucatorDreaptaMiss(){ // Mingea se va servi de pe mijlocul barii de joc a jucatorului din stanga Minge0X = 1; Minge0Y = JucatorStangaPoz0Y + HalfHBaraJucator; ScorJucatorStanga++; VitezaActuala = VitezaInit; if (ScorJucatorStanga == ScorCastigator) JocTerminat = true; } //in cazul in care nu e miss se testeaza directia pe care se afla mingea si se schimba //astfel,de exemplu, daca a ajuns pe bara din stanga ea va ricosa in dreapta void Ricoseaza0X(){ DirectieMinge0X = -DirectieMinge0X;//schimb directia VitezaActuala--; // Cand viteza se decrementeaza se va mari viteza in joc } //modificarea vitezei mingiei merge astfel: la timpul actual se adauga viteza actuala a mingii, cu cat e mai mica, mingea se va "muta" in teren mai repede //de aceea se scade viteza initiala a mingiei pe parcursul jocului void UpdatePozitieMinge(){ if (millis() > MutareMinge) { Minge0X=Minge0X + DirectieMinge0X;//se incrementeaza cu 1 pozitia mingii //iese din teren in stanga if (Minge0X <= 0) if (PeLangaBara(JucatorStangaPoz0Y)) JucatorStangaMiss(); else Ricoseaza0X(); //iese din teren in dreapta if (Minge0X >= (LatimeTeren - MarimeMinge)) if (PeLangaBara(JucatorDreaptaPoz0Y)) JucatorDreaptaMiss(); else Ricoseaza0X(); Minge0Y=Minge0Y + DirectieMinge0Y; //in cazul in care se "iese din teren", adica a lovit placa de joc se modifica directia if (Minge0Y >= (InaltimeTeren - MarimeMinge) || Minge0Y <= 0) { DirectieMinge0Y= -DirectieMinge0Y; VitezaActuala--; } MutareMinge = millis() + VitezaActuala; } } //initial dau doar marimile terenului de joc adica ale LCD-ului void setup(void) { LatimeTeren = 84; InaltimeTeren = 48; HalfLatimeTeren = LatimeTeren / 2; Serial.begin(9600); } //in loop se testeaza daca s-a atins scorul pentru a fi un winner si daca da se termina jocul si deseneaza pe ecran mesajul de terminare joc //daca nu, se face update la pozitia mingiei,barelor jucatorilor si a scorului void loop(void) { u8g.firstPage(); do { if (JocTerminat) JocGata(); else UpdatePozitieMinge(); //afisez scorul curent Scor(); //desenare minge pe ecran u8g.drawBox(Minge0X, Minge0Y, MarimeMinge, MarimeMinge); //desenare bare jucatori pe ecran BareJucatori(); } while(u8g.nextPage()); }
c2be73e7f72cee8b3e6f98739439d43a20aae5b2
[ "C++" ]
1
C++
MogaCristina/ArduinoPongGame
c018d44849fa2774587b170b75b74bf08d9658a5
fe028e1c67d141b3b0e0fd1425f57183ce8a7aa4
refs/heads/master
<file_sep>import numpy import scipy from scipy import ndimage import matplotlib.pyplot as plt import cv2 import glob from skimage.filters import threshold_otsu from skimage import measure from skimage.measure import regionprops import matplotlib.patches as patches dir_files = glob.glob("*.jpg") for img in dir_files: # read orginal image im = scipy.misc.imread(img) # change type to int32 im = im.astype('int32') # plot orginal image fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(1, 6) # split RGB fron orginal image try: b, g, r = cv2.split(im) except: continue # change to gray scale by this formula gray_im = (3*r+6*g+b)/10 # show gray_im ax1.set_title(img) ax1.imshow(gray_im, cmap="gray") # apply sobel filter in gray_im dx = ndimage.sobel(gray_im, 0) # horizontal derivative dy = ndimage.sobel(gray_im, 1) # vertical derivative mag = numpy.hypot(dx, dy) # magnitude mag *= 255.0 / numpy.max(mag) # normalize (Q&D) scipy.misc.imsave('sobel.jpg', mag) # mag is resualt of sobel filter ax2.set_title("Sobel Filtered") ax2.imshow(mag.astype(int), cmap="gray") # apply otsu threshold #it just a threshold that help to segmentation image into two part #change gray level fron 0,255 into 0,1 mag = mag/255 threshold_value = threshold_otsu(mag) binary_car_image = mag > threshold_value # show gray_im whith threshold ax3.set_title("otsu thresold") ax3.imshow(binary_car_image, cmap="gray") #apply some morphology actions #dilation for binary_car_image #dialation make highlight white lines in binary_car_image kernel = numpy.ones((11,11),numpy.uint8) dilation = cv2.dilate(binary_car_image.astype(float),kernel,iterations = 1) ax4.set_title("dilation") ax4.imshow(dilation, cmap="gray") #closing for binary_car_image #closing improve white segment in binary_car_image kernel = numpy.ones((11,11),numpy.uint8) closing = cv2.morphologyEx(dilation, cv2.MORPH_CLOSE, kernel) ax5.set_title("closing") ax5.imshow(closing, cmap="gray") #erosion for binary_car_image #erosion is a easy way to remove noise but it is'n a good way kernel = numpy.ones((35,35),numpy.uint8) erosion = cv2.erode(closing,kernel,iterations = 1) ax6.set_title("erosion") ax6.imshow(erosion, cmap="gray") plt.show() #detect car plate from erosion image that made in last morphology actions plate = erosion fig, (ax1) = plt.subplots(1) ax1.imshow(plate, cmap="gray") #this for loop detect all rectangle in image which is area is bigger than 50 pixel # regionprops creates a list of properties of all the labelled regions label_image = measure.label(plate) for region in regionprops(label_image): if region.area < 50: #if the region is so small then it's likely not a license plate continue # the bounding box coordinates minRow, minCol, maxRow, maxCol = region.bbox rectBorder = patches.Rectangle((minCol, minRow), maxCol-minCol, maxRow-minRow, edgecolor="red", linewidth=2, fill=False) ax1.add_patch(rectBorder) # let's draw a red rectangle over those regions plt.show() # in this section we want to find best rectangle that is similar to car plate #plate_dimensions is Percentage of the image that Determines a Approximaten of car plate size plate_dimensions = (0.05*label_image.shape[0], 0.3*label_image.shape[0], 0.1*label_image.shape[1], 0.5*label_image.shape[1]) min_height, max_height, min_width, max_width = plate_dimensions plate_objects_cordinates = [] plate_like_objects = [] fig, (ax1) = plt.subplots(1) ax1.imshow(plate, cmap="gray") #minrow, mincol, maxrow, maxcol show the car plate position in the orgianl image at the end of for loop minrow=0 mincol=0 maxrow=0 maxcol=0 label_image = measure.label(plate) for region in regionprops(label_image): if region.area < 100: #if the region is so small then it's likely not a license plate continue # the bounding box coordinates min_row, min_col, max_row, max_col = region.bbox region_height = max_row - min_row region_width = max_col - min_col # ensuring that the region identified satisfies the condition of a typical license plate if region_height >= min_height and region_height <= max_height and region_width >= min_width and region_width <= max_width and region_width > region_height: minrow=min_row mincol=min_col maxrow=maxRow maxcol=max_col plate_like_objects.append(binary_car_image[min_row:max_row, min_col:max_col]) plate_objects_cordinates.append((min_row, min_col, max_row, max_col)) rectBorder = patches.Rectangle((min_col, min_row), max_col-min_col, max_row-min_row, edgecolor="red", linewidth=2, fill=False) ax1.add_patch(rectBorder) # let's draw a red rectangle over those regions plt.show() #this kernel is a matrix of zeros that is same size of orginal image kernel = numpy.zeros((480,640),numpy.uint8) kernel[minrow:maxrow+10,mincol:maxcol+10]=1 #Multiplication of gray_im and kernel show just car plate plate_gray= gray_im*kernel fig, (ax1) = plt.subplots(1) ax1.imshow(plate_gray, cmap="gray") plt.show() <file_sep> # Car plate Detection This project was generated with [Python ](https://www.python.org/) version 3.7.0 I developed this project so simple that its understanding is very simple and has no difficulty. In designing this project I have used the following libraries: 1- numpy 2- scipy 3- matplotlib 4- opencv 5- skimage In my project, I only used soubel mask and few morphological operations. #این پروژه با [پایتون](https://www.python.org) نوشته شده است. ورژن 3.7.0 من این پروژه را خیلی ساده به طوری که هیچ چیز سخت و غیر قابل فهمی نداشته باشد توسعه داده ام. من در این پروژه از کتابخانه های زیر استفاده کرده ام: 1- numpy 2- scipy 3- matplotlib 4- opencv 5- skimage در این پروژه من فقط از ماسک سوبل و چند مورد استفاده از عملیات مورفولوژیک داشته ام.
088d8dd40ffa810325addb0fd541eaca2a5792f0
[ "Markdown", "Python" ]
2
Python
alixdehghani/car-plate-detection
fd54b967dd44a276c3f00057f9d8f3af21c9d9c9
7caeaac9127140adace65c6f6fe6badbfc2aae17
refs/heads/main
<file_sep>from rest_framework.test import APITestCase from .views import get_random from .views import get_access_token from .views import get_refresh_token # Create your tests here. class TestGenericFuncions(APITestCase): def test_get_random(self): rand1= get_random(10) rand2= get_random(10) rand3= get_random(15) self.assertTrue(rand1) self.assertNotEqual(rand1, rand2) self.assertEqual(len(rand1), 10) self.assertEqual(len(rand3), 15) def test_get_access_token(self): payload= { 'id': 1 } token= get_access_token() self.assertTrue(token) class TestAuth(APITestCase): login_url= '/user/login' register_url= '/user/register' refresh_url= 'user/refresh' def test_register(self): payload= { 'username': 'Okoroafor Kelechi Divine', 'password': '<PASSWORD>@#' } response= self.client.post(self.register_url, data= payload) self.assertEqual(response.status_code, 201) def test_login(self): payload = { 'username': 'Okoroafor Kelechi Divine', 'password': '<PASSWORD>@#' } self.client.post(self.register_url, data= payload) response= self.client.post(self.login_url, data= payload) result= response.json() self.assertEqual(response.status_code, 200) self.assertTrue(result['access']) self.assertTrue(result['refresh']) def test_refresh(self): payload = { 'username': 'Okoroafor Kelechi Divine', 'password': '<PASSWORD>@#' } response= self.client.post(self.register_url, data= payload) refresh= response.json()['refresh'] response= self.client.post( self.refresh_url, data= { 'refresh': refresh } ) result= response.json() self.assertEqual(response.status_code, 200) self.assertTrue(result['access']) self.assertTrue(result['refresh']) <file_sep>from django.urls import path from django.urls import include from .views import LoginView from .views import RegisterView from .views import RefreshView urlpatterns= [ path('login', LoginView.as_view()), path('register', RegisterView.as_view()), path('refresh', RefreshView.as_view()), # path('secured-info', Gt) ]<file_sep># chatRoom The term chat room, or chatroom, is primarily used to describe any form of synchronous conferencing, occasionally even asynchronous conferencing. The term can thus mean any technology ranging from real-time online chat and online interaction with strangers to fully immersive graphical social environments <file_sep>from django.contrib import admin from .models import CustomUser from .models import Jwt # Register your models here. admin.site.register((CustomUser, Jwt)) <file_sep>""" Django settings for chatApi project. Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<KEY> # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'user_control.apps.UserControlConfig', ] AUTH_USER_MODEL= 'user_control.CustomUser' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'chatApi.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'chatApi.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ S3_BUCKET_URL= config('S3_BUCKET_URL') STATIC_ROOT= 'staticfiles' AWS_ACCESS_KEY_ID= config('AWS_S3_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY= config('AWS_S3_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME= config('AWS_STORAGE_BUCKET_NAME') AWS_HOST_REGION= config('AWS_HOST_REGION') AWS_S3_CUSTOM_DOMAIN= '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_DEFAULT_ACL= None AWS_LOCATION= 'static' MEDIA_URL= '/media/' STATICFILES_DIRS= [ os.path.join(BASE_DIR, 'chatapi/static'), ] STATIC_URL= 'https://%s%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE= 'storage.backends.s3boto3.S3Boto3Storage' AWS_S3_OBJECT_PARAMETERS= { 'CacheControl': 'max-age= 86400', } DEFAULT_FILE_STORAGE= 'chatapi.storage_backends.MediaStorage' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' <file_sep>from rest_framework import serializers class LoginSerializer(serializers.Serializer): username= serializers.CharField() pasasword= serializers.CharField() class RegisterSerializer(serializers.Serializer): username= serializers.CharField() password= serializers.CharField() class RefreshSerializer(serializers.Serializer): refresh= serializers.CharField()<file_sep>from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager # Create your models here. class CustomUserManager(BaseUserManager): def _create_user(self, username, password, **extra_fields): if not username: raise ValueError("username field is required") user = self.model(username= username, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff= True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser= True.') return self._create_user(username, password, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(unique= True, max_length= 100) created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(auto_now= True) is_staff = models.BooleanField(default= False) is_superuser = models.BooleanField(default= False) is_active = models.BooleanField(default= True) USERNAME_FIELD = 'username' objects = CustomUserManager() def __str__(self): return self.username class Jwt(models.Model): user = models.OneToOneField( CustomUser, related_name= 'login_user', on_delete= models.CASCADE) access= models.TextField() refresh= models.TextField() created_at= models.DateTimeField(auto_now_add= True) update_at= models.DateTimeField(auto_now= True) <file_sep>import jwt from .models import Jwt from .models import CustomUser from datetime import datetime from datetime import timedelta from django.conf import settings import random import string from rest_framework.views import APIViews from .serializers import LoginSerializer from .serializers import RegisterSerializer from .serializers import RefreshSerializer from django.contrib.auth import authenticate from rest_framework.response import Response from .authentication import Authentication from rest_framework.permissions import IsAuthenticated from django.shortcuts import render # Create your views here. def get_random(length): return ''.join(random.choice( string.ascii_uppercase + string.digits, k= length) ) def get_access_token(payload): return jwt.encode( { 'exp': datetime.now() + timedelta(minutes= 5), **payload }, settings.SECRET_KEY, algorithm= 'HS256' ) def get_refresh_token(): return jwt.encode( { 'exp': datetime.now() + timedelta(minutes= 365), 'data': get_random(10) }, settings.SECRET_KEY, algorithm= 'HS256' ) class LoginView(APIViews): serializer_class= LoginSerializer def post(self, request): serializer= self.serializer_class(data= request.data) serializer.is_valid(raise_exception= True) user= authenticate( username= serializer.validated_data['username'], password= serializer.validated_data['password']) if not user: return Response( { 'error': 'Invalid username or password' }, status= '400' ) Jwt.objects.filter(user_id= user.id).delete() access= get_access_token( { 'user_id': user.id } ) refresh= get_refresh_token() Jwt.objects.create( user_id= user.id, access= access.decode(), refresh= refresh.decode() ) return Response( { 'access': access, 'refresh': refresh } ) class RegisterView(APIViews): serializer_class= RegisterSerializer def post(self, request): serializer= self.serializer_class(data= request.data) serializer.is_valid(raise_exception= True) CustomUser.objects._create_user(**serializer.validated_data) return Response( { 'success': 'User Created.' }, status= 201 ) class RefreshView(APIViews): serializer_class = RefreshSerializer def post(self, request): serializer= self.serializer_class(data= request.data) serializer.is_valid(raise_exception= True) try: active_jwt= Jwt.objects.get( refresh= serializer.validated_data['refresh'] ) except Jwt.DoesNotExist: return Response( { 'error': 'refresh token not found' }, status= '400' ) if not Authentication.verify_token(serializer.validated_data['refresh']): return Response( { 'error': 'Token is invalid or has expire' } ) access= get_access_token( { 'user_id': active_jwt.user_id } ) refresh= get_refresh_token() active_jwt.access= access.decode() active_jwt.refresh= refresh.decode() active_jwt.save() return Response( { 'access': access, 'refresh': refresh } ) # # class GetSecuredInfo(APIViews): # permission_classes= [IsAuthenticated] # # def get(self, request): # print(request.user) # return Response( # { # 'data': 'This is a secured info.' # } # )
d2f437f6a659884dd1a13d1bbfead5244df8ae0c
[ "Markdown", "Python" ]
8
Python
KelechiDivine/chatRoom
338a73875bbc0e0c856796995ad562100b2def4b
77f3b1d629dc0cd676ec380f7e6df410f0ce521c
refs/heads/master
<file_sep>let ActivitySuggestion = require('../models/suggestions') const assert = require('assert'); describe('modifying activity', function(){ var activity; beforeEach(function(done){ activity = new ActivitySuggestion({ title: "Museum, <NAME>", body: "I would like to see the black exhibit!", location: "San Francisco", cost: 1.99, rating: 7 }) activity.save().then(function(){ done(); }) }) it('Updates one activity from the database', function(done){ ActivitySuggestion.findOneAndUpdate({rating: 7},{rating: 8}).then(function(){ ActivitySuggestion.findOne({_id: activity._id}).then(function(result){ assert(result.rating === 8) done(); }) }) }) it('Increments activity cost from the database by 1', function(done){ ActivitySuggestion.updateMany({},{$inc: {cost: 1}}).then(function(){ ActivitySuggestion.findOne({rating: 7}).then(function(result){ assert(result.rating === 7) done(); }) }) }) }) <file_sep>let ActivitySuggestion = require('../models/suggestions') const assert = require('assert'); describe('finding activity', function(){ var activity; beforeEach(function(done){ activity = new ActivitySuggestion({ title: "Museum, <NAME>", body: "I would like to see the black exhibit!", location: "San Francisco", rating: 7 }) activity.save().then(function(){ done(); }) }) it('finds one activity from the database', function(done){ ActivitySuggestion.findOne({rating: 7}).then(function(result){ assert(result.rating === 7) done(); }) }) it('finds one activity by ID from the database', function(done){ ActivitySuggestion.findOne({_id: activity._id}).then(function(result){ assert(result._id.toString() === activity._id.toString()); done(); }) }) })<file_sep>let ActivitySuggestion = require('../models/suggestions') const assert = require('assert'); describe('deleting activity', function(){ var activity; beforeEach(function(done){ activity = new ActivitySuggestion({ title: "Museum, <NAME>", body: "I would like to see the black exhibit!", location: "San Francisco", rating: 7 }) activity.save().then(function(){ done(); }) }) it('deletes one activity from the database', function(done){ ActivitySuggestion.findOneAndRemove({rating: 7}).then(function(){ ActivitySuggestion.findOne({rating: 7}).then(function(result){ assert(result === null) done(); }) }) }) })<file_sep># What2Do- --- For those moments when you aren't sure what to do or what to eat; add your favorite activities find something fun to do or consume. ## Wat2Do is the first of a unique SaaS platform for the new age of online dating. Let's see what we're able to create! ___ * To begin, start by cloning this repo, then run NPM init; this should give you your dependencies. <file_sep>const mongoose = require('mongoose'); const Schema = mongoose.Schema; mongoose.set('useFindAndModify', false); // Create Schema and Model const AccomplishedActivitySchema = new Schema({ title: { type: String, // required: [true: 'Title field required'] }, body: { type: String }, category: { type: String }, location: { type: String }, rating: { type: Number }, cost: { type: Number }, accomplished: { type: Boolean, default: true } }) const AccomplishedActivity = mongoose.model('suggestion', AccomplishedActivitySchema); module.exports = AccomplishedActivity;<file_sep>const mongoose = require('mongoose'); mongoose.Promise = global.Promise // Connect to DB before tests run; added before block before(function(done){ var url = 'mongodb://localhost:27017/mongojsdb'; mongoose.connect(url); mongoose.connection.once('open', function(){ console.log("connection has been made; now, make magic..."); done(); }).on('error', function(error){ console.log('connection error', error); }) }) // Drop the collection before each test beforeEach(function(done){ // Drop the collection mongoose.connection.collections.suggestions.drop(function(){ done(); }) })
fb5008c9df65b0a9e2696266f91baa853f7f3e0a
[ "JavaScript", "Markdown" ]
6
JavaScript
Limelight-Management-Group/what2Do-
ef7b0dbf0e9fbee1f4f59354615a2358cd251484
b4f45770386b4677f32f3ea648c0ffdd123530c3
refs/heads/master
<file_sep>/** ****************************************************************************** * @file Project/User/IIC_OLED.c * @author Dragino * @version * @date 8-May-2017 * @brief Main program body ****************************************************************************** * @attention * * 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "hw.h" #include "IIC.h" #include "mpu9250.h" #include "filter.h" #include "flash_eraseprogram.h" #include "bsp.h" #include "math.h" static float gyro_offsetx=0.005199,gyro_offsety=0.035498,gyro_offsetz=0.005152; float tmp1,tmp2,tmp3; float magoffsetx=1.31454428611172,magoffsety=-1.21753632395713,magoffsetz=1.6567777185719; float B[6]={0.980358187761106,-0.0105514731414606,0.00754899338354401,0.950648704823113,-0.0354995317649016,1.07449478456729}; //float accoffsetx=0.096212,accoffsety=-0.028414,accoffsetz=0.030577; static float accoffsetx=-0.030587,accoffsety=-0.032310,accoffsetz=0.046341; float accsensx=1.00851297697413,accsensy=0.991366909333871,accsensz=1.00019364448499; #define filter_high 0.8 #define filter_low 0.2 short accoldx,accoldy,accoldz; short magoldx,magoldy,magoldz; short gyrooldx,gyrooldy,gyrooldz; //A function that initializes the MPU to store accelerometer readings to the fifo so that it can be read from at a later date uint8_t My_MPU_Init(void) { MPU_Write_Byte(MPU9250_ADDR,MPU_PWR_MGMT1_REG,0X80);//Reset power HAL_Delay(100);//Wait for it to finish MPU_Write_Byte(MPU9250_ADDR,MPU_PWR_MGMT1_REG,0X00);//Set the clock to internal 20Mhz //set's scale to +- 8g (default 2) MPU_Set_Rate(DEFAULT_RATE); MPU_Write_Byte(MPU9250_ADDR,MPU_INT_EN_REG,0X00);//TODO: Maybe look at later MPU_Write_Byte(MPU9250_ADDR,MPU_INTBP_CFG_REG,0X82);//Allows IC2 Bypass and sets INT pin as active high MPU_Write_Byte(MPU9250_ADDR,0x6B,0X00);//Wake MPU_Write_Byte(MPU9250_ADDR,MPU_USER_CTRL_REG,0X44);//Enable FIFO in control register and reset it MPU_Write_Byte(MPU9250_ADDR,MPU_PWR_MGMT2_REG,0X07);// Accel w/ power and Gyro no power MPU_Write_Byte(MPU9250_ADDR,MPU_FIFO_EN_REG,0X08);//Enabling fifo for Accel MPU_Set_Accel_Fsr(2);//Set ACCEL scale to +- 16 g (default is 18) LPF2pSetCutoffFreq_1(IMU_SAMPLE_RATE,IMU_FILTER_CUTOFF_FREQ); //30Hz LPF2pSetCutoffFreq_2(IMU_SAMPLE_RATE,IMU_FILTER_CUTOFF_FREQ); LPF2pSetCutoffFreq_3(IMU_SAMPLE_RATE,IMU_FILTER_CUTOFF_FREQ); LPF2pSetCutoffFreq_4(IMU_SAMPLE_RATE,IMU_FILTER_CUTOFF_FREQ); LPF2pSetCutoffFreq_5(IMU_SAMPLE_RATE,IMU_FILTER_CUTOFF_FREQ); LPF2pSetCutoffFreq_6(IMU_SAMPLE_RATE,IMU_FILTER_CUTOFF_FREQ); return 0; } //This method reads the Accelerometer from the FIFO in the MPU and stores it in the inputted arrays uint8_t readFifo(float axArr[],float ayArr[],float azArr[],int size){ uint8_t buffer[6],res; //TODO: Turn this into getFifoSize uint16_t fifoSize = 0; short ax,ay,az; float tmpx,tmpy,tmpz; short fifoFrameSize = 6 ; float ax1,ay1,az1; short iax1,iay1,iaz1; MPU_Read_Len(MPU9250_ADDR,MPU_FIFO_CNTH_REG,2,buffer);//Read the count of the FIFO PRINTF("\n\r Fifo Size: %d",fifoSize); size_t i=0;//Iterator for looping through current fifo data int j = 0; //iterator for filling arrays while(j <= size){ fifoSize = (((uint16_t) (buffer[0]&0x0F)) <<8) + (((uint16_t) buffer[1]));//determine the total size of the fifo for (; i < fifoSize/fifoFrameSize; i++,j++) {//While we have not read through the whole fifo res = MPU_Read_Len(MPU9250_ADDR,MPU_FIFO_RW_REG,fifoFrameSize,buffer); // grab the data from the MPU9250 if (res < 0) { PRINTF("Early Return"); return -1; } ay=(((uint16_t)buffer[0]<<8)|buffer[1]); ax=(((uint16_t)buffer[2]<<8)|buffer[3]); az=(((uint16_t)buffer[4]<<8)|buffer[5]); ax=-ax;//to have axis same as magnetometer? tmpx=LPF2pApply_1((float)(ax)*accel_scale-accoffsetx); tmpy=LPF2pApply_2((float)(ay)*accel_scale-accoffsety); tmpz=LPF2pApply_3((float)(az)*accel_scale-accoffsetz); axArr[j] = tmpx; ayArr[j] = tmpy; azArr[j] = tmpz; PRINTF("Current Values: x y z %f %f %f i: %i\n\r",tmpx,tmpy,tmpz,i); } HAL_Delay(100); } MPU_Write_Byte(MPU9250_ADDR,MPU_USER_CTRL_REG,0X44);//Must reset fifo or program crashes/bad data is given return 0; } //This is the original MPU Init that is from firmware version 1.4 uint8_t MPU_Init(void) { uint8_t res=0; MPU_Write_Byte(MPU9250_ADDR,MPU_PWR_MGMT1_REG,0X80);//复位MPU9250 HAL_Delay(100); //延时100ms MPU_Write_Byte(MPU9250_ADDR,MPU_PWR_MGMT1_REG,0X00);//唤醒MPU9250 MPU_Set_Gyro_Fsr(3); //陀螺仪传感器,±2000dps MPU_Set_Accel_Fsr(2); //加速度传感器,±8g MPU_Set_Rate(10); //设置采样率200Hz MPU_Write_Byte(MPU9250_ADDR,MPU_INT_EN_REG,0X00); //关闭所有中断 //TODO: Look at FIFO Reg here disable fifo to individually read out data //Use proper fifo interface to get things working properly (software pauses can cause hiccups) MPU_Write_Byte(MPU9250_ADDR,MPU_USER_CTRL_REG,0X40);//I2C主模式关闭 MPU_Write_Byte(MPU9250_ADDR,MPU_FIFO_EN_REG,0XF8); //关闭FIFO TODO: Changing FIFO Config default F8 MPU_Write_Byte(MPU9250_ADDR,MPU_INTBP_CFG_REG,0X82);//INT引脚低电平有效,开启bypass模式,可以直接读取磁力计 TODO: (C8 makes res 0 instead of 9) editted Config Reg, default 82 res=MPU_Read_Byte(MPU9250_ADDR,MPU_DEVICE_ID_REG); //读取MPU6500的ID if(res==MPU6500_ID1||res==MPU6500_ID2) //器件ID正确 { PRINTF("MPU6500"); MPU_Write_Byte(MPU9250_ADDR,MPU_PWR_MGMT1_REG,0X01); //设置CLKSEL,PLL X轴为参考 HAL_Delay(50); MPU_Write_Byte(MPU9250_ADDR,MPU_PWR_MGMT2_REG,0X00); //加速度与陀螺仪都工作 MPU_Set_Rate(10); //设置采样率为200Hz }else return 1; res=MPU_Read_Byte(AK8963_ADDR,MAG_WIA); //读取AK8963 ID if(res==AK8963_ID) { PRINTF("AK8963_ID"); MPU_Write_Byte(AK8963_ADDR,MAG_CNTL2,0X01); //复位AK8963 HAL_Delay(50); MPU_Write_Byte(AK8963_ADDR,MAG_CNTL1,0X11); //设置AK8963为单次测量 }else return 1; LPF2pSetCutoffFreq_1(IMU_SAMPLE_RATE,IMU_FILTER_CUTOFF_FREQ); //30Hz LPF2pSetCutoffFreq_2(IMU_SAMPLE_RATE,IMU_FILTER_CUTOFF_FREQ); LPF2pSetCutoffFreq_3(IMU_SAMPLE_RATE,IMU_FILTER_CUTOFF_FREQ); LPF2pSetCutoffFreq_4(IMU_SAMPLE_RATE,IMU_FILTER_CUTOFF_FREQ); LPF2pSetCutoffFreq_5(IMU_SAMPLE_RATE,IMU_FILTER_CUTOFF_FREQ); LPF2pSetCutoffFreq_6(IMU_SAMPLE_RATE,IMU_FILTER_CUTOFF_FREQ); // calibrate(); return 0; } //设置MPU9250陀螺仪传感器满量程范围 //fsr:0,±250dps;1,±500dps;2,±1000dps;3,±2000dps //返回值:0,设置成功 // 其他,设置失败 uint8_t MPU_Set_Gyro_Fsr(uint8_t fsr) { return MPU_Write_Byte(MPU9250_ADDR,MPU_GYRO_CFG_REG,(fsr<<3)|3);//设置陀螺仪满量程范围 } //设置MPU9250加速度传感器满量程范围 //fsr:0,±2g;1,±4g;2,±8g;3,±16g //返回值:0,设置成功 // 其他,设置失败 uint8_t MPU_Set_Accel_Fsr(uint8_t fsr) { return MPU_Write_Byte(MPU9250_ADDR,MPU_ACCEL_CFG_REG,fsr<<3);//设置加速度传感器满量程范围 } //设置MPU9250的数字低通滤波器 //lpf:数字低通滤波频率(Hz) //返回值:0,设置成功 // 其他,设置失败 uint8_t MPU_Set_LPF(uint16_t lpf) { uint8_t data=0; if(lpf>=188)data=1; else if(lpf>=98)data=2; else if(lpf>=42)data=3; else if(lpf>=20)data=4; else if(lpf>=10)data=5; else data=6; return MPU_Write_Byte(MPU9250_ADDR,MPU_CFG_REG,data);//设置数字低通滤波器 } //设置MPU9250的采样率(假定Fs=1KHz) //rate:4~1000(Hz) //返回值:0,设置成功 // 其他,设置失败 uint8_t MPU_Set_Rate(uint16_t rate) { uint8_t data; if(rate>1000)rate=1000; if(rate<4)rate=4; data=1000/rate-1; data=MPU_Write_Byte(MPU9250_ADDR,MPU_SAMPLE_RATE_REG,data); //设置数字低通滤波器 return MPU_Set_LPF(rate/2); //自动设置LPF为采样率的一半 } /* *@功能:补偿陀螺仪漂移 * * */ void calibrate1(void) { uint16_t t; short igx1,igy1,igz1; short iax1,iay1,iaz1; float ax2,ay2,az2; float gx2,gy2,gz2,sumx=0,sumy=0,sumz=0,sumx1=0,sumy1=0,sumz1=0; MPU_Write_Byte(MPU9250_ADDR,MPU_PWR_MGMT1_REG,0X00);//Resets everything and sets clock to fastest speed MPU_Write_Byte(MPU9250_ADDR,MPU_PWR_MGMT2_REG,0X00);//Enable all device on 0x00 only enable accel on 0x07; for (t=0;t<300;t++) { MPU_Get_Gyro(&igx1,&igy1,&igz1,&gx2,&gy2,&gz2); MPU_Get_Accel(&iax1,&iay1,&iaz1,&ax2,&ay2,&az2); sumx=sumx+gx2; sumy=sumy+gy2; sumz=sumz+gz2; sumx1=sumx1+ax2; sumy1=sumy1+ay2; sumz1=sumz1+az2; } gyro_offsetx=sumx/300.0; gyro_offsety=sumy/300.0; gyro_offsetz=sumz/300.0; accoffsetx=sumx1/300.0; accoffsety=sumy1/300.0; accoffsetz=sumz1/300.0-1.0; gyro_offsetx=0; gyro_offsety=0; gyro_offsetz=0; accoffsetx=0; accoffsety=0; accoffsetz=0; } void calibrate2(void) { uint16_t t; short igx1,igy1,igz1; short iax1,iay1,iaz1; float ax2,ay2,az2; float gx2,gy2,gz2,sumx=0,sumy=0,sumz=0,sumx1=0,sumy1=0,sumz1=0; for (t=0;t<300;t++) { MPU_Get_Gyro(&igx1,&igy1,&igz1,&gx2,&gy2,&gz2); MPU_Get_Accel(&iax1,&iay1,&iaz1,&ax2,&ay2,&az2); sumx=sumx+gx2; sumy=sumy+gy2; sumz=sumz+gz2; sumx1=sumx1+ax2; sumy1=sumy1+ay2; sumz1=sumz1+az2; } MPU_Write_Byte(MPU9250_ADDR,0x6B,0X40);//mpu sleep // gyro_offsetx=sumx/300.0; // gyro_offsety=sumy/300.0; // gyro_offsetz=sumz/300.0; accoffsetx=sumx1/300.0; accoffsety=sumy1/300.0; accoffsetz=sumz1/300.0-1.0; long j1=accoffsetx*1000000/1; long j2=accoffsety*1000000/1; long j3=accoffsetz*1000000/1; FLASH_erase(0x801F480);//Page1001 FLASH_program_on_addr(0x801F484,j1); FLASH_program_on_addr(0x801F488,j2); FLASH_program_on_addr(0x801F48C,j3); PRINTF("acc=%f ",accoffsetx); PRINTF("%f ",accoffsety); PRINTF("%f ", accoffsetz); PRINTF("\n\rcalibrating...\n\r"); } void get_calibrated_data(void) { long j1=FLASH_read(0x801F484); long j2=FLASH_read(0x801F488); long j3=FLASH_read(0x801F48C); accoffsetx=j1/1000000.0; accoffsety=j2/1000000.0; accoffsetz=j3/1000000.0; PRINTF("acc=%f ",accoffsetx); PRINTF("%f ",accoffsety); PRINTF("%f\n\r", accoffsetz); } //得到温度值 //返回值:温度值(扩大了100倍) short MPU_Get_Temperature(void) { uint8_t buf[2]; short raw; float temp; MPU_Read_Len(MPU9250_ADDR,MPU_TEMP_OUTH_REG,2,buf); raw=((uint16_t)buf[0]<<8)|buf[1]; temp=21+((double)raw)/333.87; return temp*100;; } ///////////////////////////////// //得到陀螺仪值(原始值),对源数据平均值滤波,并调整陀螺仪方位 //gx,gy,gz:陀螺仪x,y,z轴的原始读数(带符号) //返回值:0,成功 // 其他,错误代码 uint8_t MPU_Get_Gyroscope(short *gy,short *gx,short *gz) { uint8_t buf[6],res; res=MPU_Read_Len(MPU9250_ADDR,MPU_GYRO_XOUTH_REG,6,buf); if(res==0) { *gy=(((uint16_t)buf[0]<<8)|buf[1]); *gx=(((uint16_t)buf[2]<<8)|buf[3]); *gz=(((uint16_t)buf[4]<<8)|buf[5]); // *gx=-*gx; // *gx=(short)(gyrooldx*0.5+*gx*0.5); // *gy=(short)(gyrooldy*0.5+*gy*0.5); // *gz=(short)(gyrooldz*0.5+*gz*0.5); // gyrooldx=*gx; // gyrooldy=*gy; // gyrooldz=*gz; } return res; } /* *@功能:获得陀螺仪数据,单位弧度每秒 * * */ uint8_t MPU_Get_Gyro(short *igx,short *igy,short *igz,float *gx,float *gy,float *gz) { uint8_t res; res=MPU_Get_Gyroscope(igx,igy,igz); if (res==0) { *gx=LPF2pApply_4((float)(*igx)*gryo_scale); *gy=LPF2pApply_5((float)(*igy)*gryo_scale); *gz=LPF2pApply_6((float)(*igz)*gryo_scale); } return res; } //得到加速度值(原始值),低通滤波并调整加速度计方位 //gx,gy,gz:陀螺仪x,y,z轴的原始读数(带符号) //返回值:0,成功 // 其他,错误代码 uint8_t MPU_Get_Accelerometer(short *ay,short *ax,short *az) { uint8_t buf[6],res; res=MPU_Read_Len(MPU9250_ADDR,MPU_ACCEL_XOUTH_REG,6,buf); if(res==0) { *ay=(((uint16_t)buf[0]<<8)|buf[1]); *ax=(((uint16_t)buf[2]<<8)|buf[3]); *az=(((uint16_t)buf[4]<<8)|buf[5]); *ax=-*ax; // *ax=(short)(accoldx*filter_high+*ax*filter_low); // *ay=(short)(accoldy*filter_high+*ay*filter_low); // *az=(short)(accoldz*filter_high+*az*filter_low); // accoldx=*ax; // accoldy=*ay; // accoldz=*az; } return res; } /* *@功能:获得加速度计数据,单位g,并对加速度计进行补偿 * * */ uint8_t MPU_Get_Accel(short *iax,short *iay,short *iaz,float *ax,float *ay,float *az) { uint8_t res; res=MPU_Get_Accelerometer(iax,iay,iaz); if (res==0) { // tmp1=(float)(*iax)*accel_scale-accoffsetx; // tmp2=(float)(*iay)*accel_scale-accoffsety; // tmp3=(float)(*iaz)*accel_scale-accoffsetz; tmp1=LPF2pApply_1((float)(*iax)*accel_scale-accoffsetx); tmp2=LPF2pApply_2((float)(*iay)*accel_scale-accoffsety); tmp3=LPF2pApply_3((float)(*iaz)*accel_scale-accoffsetz); // *ax=tmp1*accsensx; // *ay=tmp2*accsensy; // *az=tmp3*accsensz; *ax=tmp1; *ay=tmp2; *az=tmp3; } return res; } //得到磁力计值(原始值),平均滤波并调整方位 //mx,my,mz:磁力计x,y,z轴的原始读数(带符号) //返回值:0,成功 // 其他,错误代码 uint8_t MPU_Get_Magnetometer(short *mx,short *my,short *mz) { uint8_t buf[6],res; res=MPU_Read_Len(AK8963_ADDR,MAG_XOUT_L,6,buf); if(res==0) { *mx=((uint16_t)buf[1]<<8)|buf[0]; *my=((uint16_t)buf[3]<<8)|buf[2]; *mz=((uint16_t)buf[5]<<8)|buf[4]; *my=-*my; *mz=-*mz; *mx=(short)(magoldx*0.5+*mx*0.5); *my=(short)(magoldy*0.5+*my*0.5); *mz=(short)(magoldz*0.5+*mz*0.5); magoldx=*mx; magoldy=*my; magoldz=*mz; } MPU_Write_Byte(AK8963_ADDR,MAG_CNTL1,0X11); //AK8963每次读完以后都需要重新设置为单次测量模式 return res; } /* *@功能:获得磁力计数据,单位高斯,并对磁力计进行补偿 * * */ uint8_t MPU_Get_Mag(short *imx,short *imy,short *imz,float *mx,float *my,float *mz) { uint8_t res; res=MPU_Get_Magnetometer(imx,imy,imz); if (res==0) { tmp1=(float)(*imx)*mag_scale-magoffsetx; tmp2=(float)(*imy)*mag_scale-magoffsety; tmp3=(float)(*imz)*mag_scale-magoffsetz; *mx=B[0]*tmp1+B[1]*tmp2+B[2]*tmp3; *my=B[1]*tmp1+B[3]*tmp2+B[4]*tmp3; *mz=B[2]*tmp1+B[4]*tmp2+B[5]*tmp3; } return res; } //IIC连续写 //addr:器件地址 //reg:寄存器地址 //len:写入长度 //buf:数据区 //返回值:0,正常 // 其他,错误代码 uint8_t MPU_Write_Len(uint8_t addr,uint8_t reg,uint8_t len,uint8_t *buf) { uint8_t i; IIC_Start(); IIC_SendByte((addr<<1)|0); //发送器件地址+写命令 if(IIC_WaitAck()) //等待应答 { IIC_Stop(); return 1; } IIC_SendByte(reg); //写寄存器地址 IIC_WaitAck(); //等待应答 for(i=0;i<len;i++) { IIC_SendByte(buf[i]); //发送数据 if(IIC_WaitAck()) //等待ACK { IIC_Stop(); return 1; } } IIC_Stop(); return 0; } //IIC连续读 //addr:器件地址 //reg:要读取的寄存器地址 //len:要读取的长度 //buf:读取到的数据存储区 //返回值:0,正常 // 其他,错误代码 uint8_t MPU_Read_Len(uint8_t addr,uint8_t reg,uint8_t len,uint8_t *buf) { IIC_Start(); IIC_SendByte((addr<<1)|0); //发送器件地址+写命令 if(IIC_WaitAck()) //等待应答 { IIC_Stop(); return 1; } IIC_SendByte(reg); //写寄存器地址 IIC_WaitAck(); //等待应答 IIC_Start(); IIC_SendByte((addr<<1)|1); //发送器件地址+读命令 IIC_WaitAck(); //等待应答 while(len) { if(len==1)*buf=IIC_ReadByte(0);//读数据,发送nACK else *buf=IIC_ReadByte(1); //读数据,发送ACK len--; buf++; } IIC_Stop(); //产生一个停止条件 return 0; } //IIC写一个字节 //devaddr:器件IIC地址 //reg:寄存器地址 //data:数据 //返回值:0,正常 // 其他,错误代码 uint8_t MPU_Write_Byte(uint8_t addr,uint8_t reg,uint8_t data) { IIC_Start(); IIC_SendByte((addr<<1)|0); //发送器件地址+写命令 if(IIC_WaitAck()) //等待应答 { IIC_Stop(); return 1; } IIC_SendByte(reg); //写寄存器地址 IIC_WaitAck(); //等待应答 IIC_SendByte(data); //发送数据 if(IIC_WaitAck()) //等待ACK { IIC_Stop(); return 1; } IIC_Stop(); return 0; } //IIC读一个字节 //reg:寄存器地址 //返回值:读到的数据 uint8_t MPU_Read_Byte(uint8_t addr,uint8_t reg) { uint8_t res; IIC_Start(); IIC_SendByte((addr<<1)|0); //发送器件地址+写命令 IIC_WaitAck(); //等待应答 IIC_SendByte(reg); //写寄存器地址 IIC_WaitAck(); //等待应答 IIC_Start(); IIC_SendByte((addr<<1)|1); //发送器件地址+读命令 IIC_WaitAck(); //等待应答 res=IIC_ReadByte(0); //读数据,发送nACK IIC_Stop(); //产生一个停止条件 return res; } /******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/ <file_sep>/****************************************************************************** * @file main.c * @author MCD Application Team * @version V1.1.4 * @date 08-January-2018 * @brief this is the main! ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2017 STMicroelectronics International N.V. * All rights reserved.</center></h2> * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "hw.h" #include "low_power_manager.h" #include "lora.h" #include "bsp.h" #include "timeServer.h" #include "vcom.h" #include "version.h" #include "command.h" #include "at.h" #include "GPS.h" #include "bsp_usart2.h" #include "exti_wakeup.h" #include "IIC.h" #include "mpu9250.h" #include <time.h> /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /*! * CAYENNE_LPP is myDevices Application server. */ //#define CAYENNE_LPP #define LPP_DATATYPE_DIGITAL_INPUT 0x0 #define LPP_DATATYPE_ANOLOG_INPUT 0x02 #define LPP_DATATYPE_HUMIDITY 0x68 #define LPP_DATATYPE_TEMPERATURE 0x67 #define LPP_APP_PORT 99 /*! * Defines the application data transmission duty cycle. 5s, value in [ms]. */ uint32_t APP_TX_DUTYCYCLE=300000; uint32_t Server_TX_DUTYCYCLE=300000; uint32_t Alarm_TX_DUTYCYCLE=60000; uint32_t GPS_ALARM=0; extern uint32_t set_sgm; extern int in1; extern uint32_t s_gm; extern uint8_t Restart; int ALARM = 0; /*! * LoRaWAN Adaptive Data Rate * @note Please note that when ADR is enabled the end-device should be static */ #define LORAWAN_ADR_STATE LORAWAN_ADR_ON /*! * LoRaWAN Default data Rate Data Rate * @note Please note that LORAWAN_DEFAULT_DATA_RATE is used only when ADR is disabled */ #define LORAWAN_DEFAULT_DATA_RATE DR_0 /*! * LoRaWAN application port * @note do not use 224. It is reserved for certification */ #define LORAWAN_APP_PORT 2 /*! * Number of trials for the join request. */ #define JOINREQ_NBTRIALS 200 /*! * LoRaWAN default endNode class port */ #define LORAWAN_DEFAULT_CLASS CLASS_A /*! * LoRaWAN default confirm state */ #define LORAWAN_DEFAULT_CONFIRM_MSG_STATE LORAWAN_UNCONFIRMED_MSG /*! * User application data buffer size */ #define LORAWAN_APP_DATA_BUFF_SIZE 64 /*! * User application data */ static uint8_t AppDataBuff[LORAWAN_APP_DATA_BUFF_SIZE]; uint32_t Alarm_LED = 0,a = 1; int exti_flag=0,basic_flag=0; int exti_de=0; short iax,iay,iaz; float ax,ay,az; static uint32_t ServerSetTDC; static uint32_t AlarmSetTDC; uint8_t TDC_flag=0; uint8_t flag_1=1 ,LP = 0; extern uint8_t Alarm_times; extern uint8_t Alarm_times1; extern uint32_t start; extern uint16_t AD_code3; extern uint32_t Positioning_time; extern float LPF2pApply_1(float sample); extern float LPF2pApply_2(float sample); extern float LPF2pApply_3(float sample); static float accoffsetx=-0.030587,accoffsety=-0.032310,accoffsetz=0.046341; uint32_t Start_times=0,End_times=0; FP32 gps_latitude ,gps_longitude; uint32_t longitude; uint32_t latitude; uint32_t SendData=0; uint16_t batteryLevel_mV; float Roll_basic=0,Pitch_basic=0,Yaw_basic=0; float Roll_sum=0,Pitch_sum=0,Yaw_sum=0; float Roll=0,Pitch=0,Yaw=0; float Roll1=0,Pitch1=0,Yaw1=0; float Roll_new=0,Pitch_new=0,Yaw_new=0; float Roll_old=0,Pitch_old=0,Yaw_old=0; void lora_send_fsm(void); void send_data(void); void send_exti(void); /*! * User application data structure */ static lora_AppData_t AppData={ AppDataBuff, 0 ,0 }; /* Private macro -------------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* call back when LoRa endNode has received a frame*/ static void LORA_RxData( lora_AppData_t *AppData); /* call back when LoRa endNode has just joined*/ static void LORA_HasJoined( void ); /* call back when LoRa endNode has just switch the class*/ static void LORA_ConfirmClass ( DeviceClass_t Class ); /* LoRa endNode send request*/ static void Send( void ); static void lora_send(void); void send_ALARM_data(void); #if defined(LoRa_Sensor_Node) /* start the tx process*/ static void LoraStartTx(TxEventType_t EventType); static TimerEvent_t TxTimer; void AHRSupdate(float gx, float gy, float gz, float ax, float ay, float az, float mx, float my, float mz,float *roll,float *pitch,float *yaw); float invSqrt(float number); /* tx timer callback function*/ static void OnTxTimerEvent( void ); #endif /* Private variables ---------------------------------------------------------*/ /* load Main call backs structure*/ static LoRaMainCallback_t LoRaMainCallbacks ={ HW_GetBatteryLevel, HW_GetTemperatureLevel, HW_GetUniqueId, HW_GetRandomSeed, LORA_RxData, LORA_HasJoined, LORA_ConfirmClass}; /* ! *Initialises the Lora Parameters */ static LoRaParam_t LoRaParamInit= {LORAWAN_ADR_STATE, LORAWAN_DEFAULT_DATA_RATE, LORAWAN_PUBLIC_NETWORK, JOINREQ_NBTRIALS}; #define Kp 40.0f // proportional gain governs rate of convergence toaccelerometer/magnetometer //Kp比例增益 决定了加速度计和磁力计的收敛速度 #define Ki 0.02f // integral gain governs rate of convergenceof gyroscope biases //Ki积分增益 决定了陀螺仪偏差的收敛速度 #define halfT 0.0048f // half the sample period //halfT采样周期的一半 #define dt 0.0096f /***************************************************/ static float q0=1.0f,q1=0.0f,q2=0.0f,q3=0.0f; static float exInt = 0, eyInt = 0, ezInt = 0; static short turns=0; static float newdata=0.0f,olddata=0.0f; static float pitchoffset,rolloffset,yawoffset; static float k10=0.0f,k11=0.0f,k12=0.0f,k13=0.0f; static float k20=0.0f,k21=0.0f,k22=0.0f,k23=0.0f; static float k30=0.0f,k31=0.0f,k32=0.0f,k33=0.0f; static float k40=0.0f,k41=0.0f,k42=0.0f,k43=0.0f; //float invSqrt(float number); //void AHRSupdate(float gx, float gy, float gz, float ax, float ay, float az, float mx, float my, float mz,float *roll,float *pitch,float *yaw); void CountTurns(float *newdata,float *olddata,short *turns); void CalYaw(float *yaw,short *turns); void CalibrateToZero(void); float pitch,roll,yaw; float pitch_sum,roll_sum,yaw_sum; short igx,igy,igz; short imx,imy,imz; float gx,gy,gz; float mx,my,mz; float gx_old,gy_old,gz_old; float ax_old,ay_old,az_old; float mx_old,my_old,mz_old; uint8_t flag_2=1; void RecordAccel(); void BufferAccelData(); void PerformCalculation(float axArr[], float ayArr[],float azArr[],int *index); void ResetAccelBuff(); int BufferAccel_flag = 0; int PerformCalculation_flag = 0; int finishedCalc_flag = 0; int global_time = 0; int res = 0; int temp_time = 0; int Pitch_tot = 0; int buff_size = 101; int TimeSecond = 0; int oneSecTimer = 0; float axArr[500],ayArr[500],azArr[500]; int startTime = -1; int iterator = 0; int FIFO_flag = 0; float axMax,ayMax,azMax; int meanDiv = 1; /* Private functions ---------------------------------------------------------*/ /** * @brief Main program * @param None * @retval None */ int main( void ) { /* STM32 HAL library initialization*/ HAL_Init( ); /* Configure the system clock*/ SystemClock_Config( ); EXTI4_15_IRQHandler_Config(); /* Configure the debug mode*/ DBG_Init( ); usart1_Init(); GPS_init(); GPS_Run(); /* Configure the hardware*/ HW_Init( ); /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ CMD_Init(); powerLED(); IIC_GPIO_MODE_Config(); HAL_Delay(10); uint8_t isMPUInit=0; isMPUInit=My_MPU_Init(); while (isMPUInit) { PRINTF("MPU_Init error\n\r"); HAL_Delay(200); } Restart = 0; /*Disbale Stand-by mode*/ // if(lora_getState() != STATE_WAKE_JOIN) // { LPM_SetOffMode(LPM_APPLI_Id , LPM_Disable ); // } /* Configure the Lora Stack*/ LORA_Init( &LoRaMainCallbacks, &LoRaParamInit); int i = 0; while( 1 )//TODO: Main program loop here {//3200 Iterations is one second //An array with 5 seconds of data would need 3200*5 + 1 slots global_time++; oneSecTimer++; if(oneSecTimer==3200) {//This is unecessary and this timer was used for debugging TimeSecond++; PRINTF("One Second %d \n\r",TimeSecond); oneSecTimer = 0; } /* Handle UART commands */ CMD_Process(); if(in1== 1){//TODO: adding check for button click here PRINTF("Click"); //RecordAccel(); //Flag is set inside this method so that race conditions aren't created FIFO_flag = 1; in1 = 0; HAL_Delay(200); if(in1== 1){ HAL_Delay(10); PRINTF("Double Click"); in1 = 0; } } if(FIFO_flag){ readFifo(axArr,ayArr,azArr); //PerformCalculation_flag = 1; FIFO_flag = 0; } if(PerformCalculation_flag == 1) { PerformCalculation(axArr,ayArr,azArr,&iterator);//The PerformCalculation_flag is reset in this method iterator++; } if(s_gm == 1) { // lora_send_fsm(); lora_send(); if(Restart == 1) { NVIC_SystemReset(); Restart = 0; } } DISABLE_IRQ( ); /* * if an interrupt has occurred after DISABLE_IRQ, it is kept pending * and cortex will not enter low power anyway * don't go in low power mode if we just received a char */ #ifndef LOW_POWER_DISABLE MPU_Write_Byte(MPU9250_ADDR,0x6B,0X40);//MPU sleep LPM_EnterLowPower(); #endif ENABLE_IRQ(); /* USER CODE BEGIN 2 */ /* USER CODE END 2 */ } } static void LORA_HasJoined( void ) { AT_PRINTF("JOINED\n\r"); Read_Config(); LORA_RequestClass( LORAWAN_DEFAULT_CLASS ); #if defined(LoRa_Sensor_Node) /*LSN50 Preprocessor compile swicth:hw_conf.h*/ LoraStartTx( TX_ON_TIMER); lora_state_GPS_Send(); s_gm = 1; start = 0; gps.flag = 1; #endif #if defined(AT_Data_Send) /*LoRa ST Module*/ AT_PRINTF("Please using AT+SEND or AT+SENDB to send you data!\n\r"); #endif } /* A Placeholder function for the real function that will perform an oporation on the data and then output some info to send to the server */ static void PerformCalculation(float axArr[], float ayArr[],float azArr[],int *index) { if(*index >= 499 || axArr[*index] == NULL){//The break condition for this "loop" PRINTF("Max x y z: %f %f %f i: %d\n\r",axMax,ayMax,azMax,iterator); *index = 0; PerformCalculation_flag = 0; axMax = 0; ayMax = 0; azMax = 0; } else{ if(axArr[*index] > axMax){ axMax = axArr[*index]; } if(ayArr[*index] > ayMax){ ayMax = ayArr[*index]; } if(azArr[*index] > azMax){ azMax = azArr[*index]; } } } /* A function made to store 5 seconds worth of acceleration data inside of the inputted arrays After this function runs each of the inputted arrays should be populated with Pitch and Roll data respectivly */ /* A private function to record acceleration data and store it Ideally this is to be used instead of send when gps is not available */ static void RecordAccel()//A function used to take several measurements of accel and average them to get an accurate result and then print that result { float ax1,ay1,az1; short iax1,iay1,iaz1; sensor_t sensor_data; BSP_sensor_Read( &sensor_data ); MPU_Write_Byte(MPU9250_ADDR,MPU_PWR_MGMT1_REG,0X00);//Resets all IO and sets clock to fastest speed MPU_Write_Byte(MPU9250_ADDR,MPU_PWR_MGMT2_REG,0X07);//Enables all sensors on 0x00, on 0x07 Gyro disabled MPU_Get_Accel(&iax1,&iay1,&iaz1,&ax1,&ay1,&az1); float xval = ax1; float yval = ay1; float zval = az1; HAL_Delay(100);//Give fifo time to fill FIFO_flag = 1; PRINTF("x1: %f \n\r",xval); PRINTF("y1: %f \n\r",yval); PRINTF("z1: %f \n\r",zval); } static void Send( void )//TODO: Here is where the high level send function is { sensor_t sensor_data; // if ( LORA_JoinStatus () != LORA_SET) // { /*Not joined, try again later*/ // return; // } BSP_sensor_Read( &sensor_data ); uint32_t i = 0; if(basic_flag==1) { Roll_basic=0; Pitch_basic=0; basic_flag=0; } else if(basic_flag==2) { Roll_basic=Roll; Pitch_basic=Pitch; basic_flag=0; } if(AD_code3 <= 2840) { LP = 1; PRINTF("\n\rAD_code3=%d ", AD_code3); } else { LP = 0; } MPU_Write_Byte(MPU9250_ADDR,0x6B,0X00);//唤醒 MPU_Write_Byte(MPU9250_ADDR,MPU_PWR_MGMT2_REG,0X00); //加速度与陀螺仪都工作 for(int H=0; H<10; H++) { // MPU_Get_Gyro(&igx,&igy,&igz,&gx,&gy,&gz); MPU_Get_Accel(&iax,&iay,&iaz,&ax,&ay,&az); // MPU_Get_Mag(&imx,&imy,&imz,&mx,&my,&mz); AHRSupdate(0,0,0,ax,ay,az,0,0,0,&roll,&pitch,&yaw); olddata=newdata; newdata=yaw; CountTurns(&newdata,&olddata,&turns); CalYaw(&yaw,&turns); pitch+=pitchoffset; roll+=rolloffset; yaw+=yawoffset; } for(int H=0; H<30; H++) { // MPU_Get_Gyro(&igx,&igy,&igz,&gx,&gy,&gz); MPU_Get_Accel(&iax,&iay,&iaz,&ax,&ay,&az); // MPU_Get_Mag(&imx,&imy,&imz,&mx,&my,&mz); AHRSupdate(0,0,0,ax,ay,az,0,0,0,&roll,&pitch,&yaw); olddata=newdata; newdata=yaw; CountTurns(&newdata,&olddata,&turns); CalYaw(&yaw,&turns); pitch+=pitchoffset; roll+=rolloffset; yaw+=yawoffset; Pitch_sum+=pitch; Roll_sum+=roll; } Roll_new=Roll_sum/30.0; Pitch_new=Pitch_sum/30.0; if(flag_1==1) { flag_1=0; Roll_old=Roll_new; Pitch_old=Pitch_new; } if(-0.2<Roll_new-Roll_old&&Roll_new-Roll_old<0.2) { Roll1=(Roll_new+Roll_old)/2.0; Roll1=(Roll_old+Roll1)/2.0; Roll_old=Roll1; } else {Roll1=Roll_new;Roll_old=Roll_new;} if(-0.2<Pitch_new-Pitch_old&&Pitch_new-Pitch_old<0.2) { Pitch1=(Pitch_new+Pitch_old)/2.0; Pitch1=(Pitch_old+Pitch1)/2.0; Pitch_old=Pitch1; } else {Pitch1=Pitch_new;Pitch_old=Pitch_new;} Roll=Roll1; Pitch=Pitch1; Roll1=Roll1-Roll_basic; Pitch1=Pitch1-Pitch_basic; Roll_sum=0; Pitch_sum=0; //if(gps.latitude > 0 && gps.longitude > 0) //{ gps_latitude = gps.latitude; gps_longitude = gps.longitude; gps_state_on(); PRINTF("\n\rRoll=%d ",(int)(Roll1*100)); PRINTF("Pitch=%d\n\r",(int)(Pitch1*100));//TODO store accel info from this var PRINTF("%s: %.4f\n\r",(gps.latNS == 'N')?"South":"North",gps_latitude); PRINTF("%s: %.4f\n\r ",(gps.lgtEW == 'E')?"East":"West",gps_longitude); if(gps.latNS != 'N') { latitude = gps_latitude*10000; latitude = (~latitude)+1 ; } else { latitude = gps_latitude*10000; } if(gps.lgtEW != 'E') { longitude = gps_longitude*10000; longitude = (~longitude)+1 ; } else { longitude = gps_longitude*10000; } gps.latitude = 0; gps.longitude = 0; start = 1; //} AppData.Port = LORAWAN_APP_PORT; if(lora_getGPSState() == STATE_GPS_OFF) { AppData.Buff[i++] = 0x00; AppData.Buff[i++] = 0x00; AppData.Buff[i++] = 0x00; AppData.Buff[i++] = 0x00; AppData.Buff[i++] = 0x00; AppData.Buff[i++] = 0x00; } else if(lora_getGPSState() == STATE_GPS_NO) { AppData.Buff[i++] = 0x0F; AppData.Buff[i++] = 0xFF; AppData.Buff[i++] = 0xFF; AppData.Buff[i++] = 0x0F; AppData.Buff[i++] = 0xFF; AppData.Buff[i++] = 0xFF; } else { AppData.Buff[i++] =(int)latitude>>16& 0xFF; AppData.Buff[i++] =(int)latitude>>8& 0xFF; AppData.Buff[i++] =(int)latitude& 0xFF; AppData.Buff[i++] =(int)longitude>>16& 0xFF; AppData.Buff[i++] =(int)longitude>>8& 0xFF; AppData.Buff[i++] =(int)longitude& 0xFF; } if(set_sgm == 0) { if(ALARM == 1) { AppData.Buff[i++] =(int)(sensor_data.oil)>>8 |0x40; //oil float AppData.Buff[i++] =(int)sensor_data.oil; } else { AppData.Buff[i++] =(int)(sensor_data.oil)>>8; //oil float AppData.Buff[i++] =(int)sensor_data.oil; } AppData.Buff[i++] =(int)(Roll1*100)>>8; //Roll AppData.Buff[i++] =(int)(Roll1*100); AppData.Buff[i++] =(int)(Pitch1*100)>>8; //Pitch AppData.Buff[i++] =(int)(Pitch1*100); } if(set_sgm == 1) { if(ALARM == 1) { AppData.Buff[i++] =(int)(sensor_data.oil)>>8 |0x40; //oil float AppData.Buff[i++] =(int)sensor_data.oil; } else { AppData.Buff[i++] =(int)(sensor_data.oil)>>8; //oil float AppData.Buff[i++] =(int)sensor_data.oil; } } if(start == 1 ) { gps.flag = 1; AppData.BuffSize = i; LORA_send( &AppData, lora_config_reqack_get()); } else { if(lora_getState() != STATE_LORA_ALARM) { lora_state_GPS_Send(); } } } static void LORA_RxData( lora_AppData_t *AppData ) { set_at_receive(AppData->Port, AppData->Buff, AppData->BuffSize); AT_PRINTF("Receive data\n\r"); AT_PRINTF("%d:",AppData->Port); for (int i = 0; i < AppData->BuffSize; i++) { AT_PRINTF("%02x", AppData->Buff[i]); } AT_PRINTF("\n\r"); switch(AppData->Buff[0] & 0xff) { case 1: { if( AppData->BuffSize == 4 ) { ServerSetTDC=( AppData->Buff[1]<<16 | AppData->Buff[2]<<8 | AppData->Buff[3] );//S if(ServerSetTDC<5) { PRINTF("TDC setting must be more than 4S\n\r"); } else { TDC_flag=1; Server_TX_DUTYCYCLE=ServerSetTDC*1000; PRINTF("ServerSetTDC: %02x\n\r",ServerSetTDC); PRINTF("Server_TX_DUTYCYCLE: %02d\n\r",Server_TX_DUTYCYCLE); } BSP_sensor_Init(); LED3_1; HAL_Delay(1000); LED3_0; } break; } case 2: { if( AppData->BuffSize == 2 ) { if(AppData->Buff[1]==0x01) { Alarm_times = 60; Alarm_times1 = 60; GPS_ALARM = 0; ALARM = 0; BSP_sensor_Init(); LED1_1; HAL_Delay(1000); LED1_0; PRINTF("Alarm_times\n\r"); } } break; } case 3: { /*this port switches the class*/ if( AppData->BuffSize == 1 ) { switch ( AppData->Buff[0] ) { case 0: { LORA_RequestClass(CLASS_A); PRINTF("CLASS_A\n\r"); break; } case 1: { LORA_RequestClass(CLASS_B); PRINTF("CLASS_B\n\r"); break; } case 2: { LORA_RequestClass(CLASS_C); PRINTF("CLASS_C\n\r"); break; } default: break; } } break; } case 4: { if( AppData->BuffSize == 2 ) { if(AppData->Buff[1]==0xFF) { NVIC_SystemReset(); } } break; } case 5: { if( AppData->BuffSize == 2 ) { if(AppData->Buff[1]==0x01) { basic_flag=1;//原始值 PRINTF("basic_flag=1\n\r"); } else if(AppData->Buff[1]==0x02) { basic_flag=2;//基准变化值 PRINTF("basic_flag=2\n\r"); } } break; } case 6: { if( AppData->BuffSize == 2 ) { if(AppData->Buff[1]==0x01) { // exti_de=0;GPIO_EXTI_IoInit(); PRINTF("EXTI_IoInit()\n\r"); } else if(AppData->Buff[1]==0x02) { // exti_de=1;GPIO_EXTI_IoDeInit();exti_flag=0; PRINTF("GPIO_EXTI_IoDeInit()\n\r"); } } break; } default: break; } if(TDC_flag==1) { Store_Config(); TimerInit( &TxTimer, OnTxTimerEvent ); TimerSetValue( &TxTimer, APP_TX_DUTYCYCLE); TimerStart( &TxTimer); TDC_flag=0; PRINTF("Store_Config()\n\r"); } } #if defined(LoRa_Sensor_Node) static void OnTxTimerEvent( void ) { if(lora_getState() != STATE_GPS_SEND ) { Send( ); } TimerSetValue( &TxTimer, APP_TX_DUTYCYCLE); /*Wait for next tx slot*/ TimerStart( &TxTimer); } static void LoraStartTx(TxEventType_t EventType) { if (EventType == TX_ON_TIMER) { /* send everytime timer elapses */ TimerInit( &TxTimer, OnTxTimerEvent ); TimerSetValue( &TxTimer, APP_TX_DUTYCYCLE); lora_state_GPS_Send(); gps.flag = 1; gps.latitude = 0; gps.longitude = 0; OnTxTimerEvent(); } } #endif static void LORA_ConfirmClass ( DeviceClass_t Class ) { PRINTF("switch to class %c done\n\r","ABC"[Class] ); /*Optionnal*/ /*informs the server that switch has occurred ASAP*/ AppData.BuffSize = 0; AppData.Port = LORAWAN_APP_PORT; LORA_send( &AppData, LORAWAN_UNCONFIRMED_MSG); } void lora_send(void) { switch(lora_getState()) { case STATE_LED: { gps.flag = 1; start = 0; GPS_POWER_OFF(); BSP_sensor_Init(); LPM_SetOffMode(LPM_APPLI_Id ,LPM_Disable ); if(a == 0) { LED1_1; HAL_Delay(500); LED1_0; HAL_Delay(500); start = 0; a ++; } a ++; if( a == 10 ) { a = 0; } break; } case STATE_GPS_SEND: { if(gps.latitude > 0 && gps.longitude > 0) { SendData = 1; } if(SendData == 1) { if(GPS_ALARM == 0) { send_data(); gps_state_on(); a = 1; GPS_ALARM = 0; SendData = 0; } if(GPS_ALARM == 1) { if(Alarm_LED == 0) { gps_latitude = gps.latitude; gps_longitude = gps.longitude; gps.flag = 1; gps.GSA_mode2 = 0; start = 1; ALARM = 1; Alarm_times1 = 0; Alarm_times = 60; Send( ); GPS_POWER_OFF(); BSP_sensor_Init(); } if( Alarm_LED < 60) { LED3_1; HAL_Delay(500); LED3_0; HAL_Delay(500); Alarm_LED ++; GPS_ALARM = 1; PRINTF("Alarm_LED:%d\n\r",Alarm_LED); } if( Alarm_LED == 60) { Alarm_times = 0; GPS_ALARM = 1; Alarm_LED ++; } if(Alarm_times < 60) { send_ALARM_data(); gps_state_on(); a = 100; GPS_ALARM = 1; SendData = 0; PRINTF("seng data \n\r"); } if(Alarm_times1 == 60) { lora_state_GPS_Send(); start = 0; ALARM = 0; Alarm_LED = 0; GPS_ALARM = 0; PRINTF("led\n\r"); APP_TX_DUTYCYCLE=Server_TX_DUTYCYCLE; TimerInit( &TxTimer, OnTxTimerEvent ); TimerSetValue( &TxTimer, APP_TX_DUTYCYCLE); /*Wait for next tx slot*/ TimerStart( &TxTimer); LPM_SetOffMode(LPM_APPLI_Id ,LPM_Disable ); BSP_sensor_Init(); LED1_1; HAL_Delay(1000); LED1_0; DISABLE_IRQ( ); /* * if an interrupt has occurred after DISABLE_IRQ, it is kept pending * and cortex will not enter low power anyway * don't go in low power mode if we just received a char */ #ifndef LOW_POWER_DISABLE MPU_Write_Byte(MPU9250_ADDR,0x6B,0X40);//MPU sleep LPM_EnterLowPower(); #endif ENABLE_IRQ(); } } } if(LP == 0) { LPM_SetOffMode(LPM_APPLI_Id , LPM_Enable ); BSP_sensor_Init(); POWER_ON(); GPS_INPUT(); LP = 0; LED0_0; Start_times ++; } if(LP == 1) { start = 1; gps_state_no(); APP_TX_DUTYCYCLE = Server_TX_DUTYCYCLE; TimerInit( &TxTimer, OnTxTimerEvent ); TimerSetValue( &TxTimer, APP_TX_DUTYCYCLE); Send( ); TimerSetValue( &TxTimer, APP_TX_DUTYCYCLE); /*Wait for next tx slot*/ TimerStart( &TxTimer); LPM_SetOffMode(LPM_APPLI_Id ,LPM_Disable ); PRINTF("Server_TX_DUTYCYCLE11: %02d\n\r",APP_TX_DUTYCYCLE); PRINTF("LP == 1\n\r"); // gps_state_no(); lora_state_Led(); a = 1; } if(Start_times ==2500) { End_times ++; Start_times =0; LED0_1; HAL_Delay(100); } if(End_times == 30 || End_times == 60 || End_times ==90 || End_times ==120 ) { PRINTF("End_times:%02d \n\r",End_times); PRINTF("Positioning_time:%02d \n\r",Positioning_time); End_times ++; } if(End_times >=Positioning_time) { if(lora_getState() == STATE_GPS_SEND) { gps_state_off(); a = 100; send_data(); PRINTF("GPS NO FIX\n\r"); a = 100; GPS_ALARM = 0; LED3_1; HAL_Delay(500); LED3_0; HAL_Delay(500); } if(GPS_ALARM == 1) { if(Alarm_LED == 0) { gps_state_off(); gps_latitude = gps.latitude; gps_longitude = gps.longitude; gps.flag = 1; gps.GSA_mode2 = 0; start = 1; ALARM = 1; Alarm_times1 = 0; Alarm_times = 60; Send( ); GPS_POWER_OFF(); BSP_sensor_Init(); LPM_SetOffMode(LPM_APPLI_Id ,LPM_Disable ); } if( Alarm_LED < 60) { LED3_1; HAL_Delay(500); LED3_0; HAL_Delay(500); Alarm_LED ++; GPS_ALARM = 1; // Alarm_times = 0; PRINTF("Alarm_LED:%d\n\r",Alarm_LED); } if( Alarm_LED == 60) { Alarm_times = 0; GPS_ALARM = 1; Alarm_LED ++; } if(Alarm_times < 60) { gps_state_off(); send_ALARM_data(); GPS_ALARM = 1; a = 100; LED3_1; HAL_Delay(500); LED3_0; HAL_Delay(500); } if(Alarm_times1 == 60) { lora_state_GPS_Send(); start = 0; ALARM = 0; Alarm_LED = 0; GPS_ALARM = 0; PRINTF("led\n\r"); APP_TX_DUTYCYCLE=Server_TX_DUTYCYCLE; TimerInit( &TxTimer, OnTxTimerEvent ); TimerSetValue( &TxTimer, APP_TX_DUTYCYCLE); /*Wait for next tx slot*/ TimerStart( &TxTimer); LPM_SetOffMode(LPM_APPLI_Id ,LPM_Disable ); BSP_sensor_Init(); LED0_1; HAL_Delay(1000); LED0_0; DISABLE_IRQ( ); /* * if an interrupt has occurred after DISABLE_IRQ, it is kept pending * and cortex will not enter low power anyway * don't go in low power mode if we just received a char */ #ifndef LOW_POWER_DISABLE MPU_Write_Byte(MPU9250_ADDR,0x6B,0X40);//MPU sleep LPM_EnterLowPower(); #endif ENABLE_IRQ(); } } } break; } default: { PRINTF("default\n\r"); lora_state_Led(); start = 0; break; } } } void send_data(void) { start = 1; APP_TX_DUTYCYCLE = Server_TX_DUTYCYCLE; TimerInit( &TxTimer, OnTxTimerEvent ); TimerSetValue( &TxTimer, APP_TX_DUTYCYCLE); Send( ); TimerSetValue( &TxTimer, APP_TX_DUTYCYCLE); /*Wait for next tx slot*/ TimerStart( &TxTimer); LPM_SetOffMode(LPM_APPLI_Id ,LPM_Disable ); PRINTF("Server_TX_DUTYCYCLE: %02d\n\r",APP_TX_DUTYCYCLE); lora_state_Led(); gps.flag = 1; BSP_sensor_Init(); LED0_0; End_times = 0 ; gps.GSA_mode2 = 0; gps_latitude = gps.latitude; gps_longitude = gps.longitude; DISABLE_IRQ( ); /* * if an interrupt has occurred after DISABLE_IRQ, it is kept pending * and cortex will not enter low power anyway * don't go in low power mode if we just received a char */ #ifndef LOW_POWER_DISABLE MPU_Write_Byte(MPU9250_ADDR,0x6B,0X40);//MPU sleep LPM_EnterLowPower(); #endif ENABLE_IRQ(); } void send_ALARM_data(void) { #if defined( REGION_EU868 ) APP_TX_DUTYCYCLE=Alarm_TX_DUTYCYCLE; #else APP_TX_DUTYCYCLE=Alarm_TX_DUTYCYCLE; #endif TimerInit( &TxTimer, OnTxTimerEvent ); TimerSetValue( &TxTimer, APP_TX_DUTYCYCLE); Send( ); TimerSetValue( &TxTimer, APP_TX_DUTYCYCLE); /*Wait for next tx slot*/ TimerStart( &TxTimer); PRINTF("Server_TX_DUTYCYCLE: %02d\n\r",APP_TX_DUTYCYCLE); lora_state_Led(); BSP_sensor_Init(); End_times = 0 ; LED0_0; a = 100; LED3_1; HAL_Delay(1000); LED3_0; // gps_latitude = gps.latitude; // gps_longitude = gps.longitude; DISABLE_IRQ( ); /* * if an interrupt has occurred after DISABLE_IRQ, it is kept pending * and cortex will not enter low power anyway * don't go in low power mode if we just received a char */ #ifndef LOW_POWER_DISABLE MPU_Write_Byte(MPU9250_ADDR,0x6B,0X40);//MPU sleep LPM_EnterLowPower(); #endif ENABLE_IRQ(); } /* *@功能:快速获得开方的倒数 * * */ float invSqrt(float number) { long i; float x,y; const float f=1.5f; x=number*0.5f; y=number; i=*((long*)&y); i=0x5f375a86-(i>>1); y=*((float *)&i); y=y*(f-(x*y*y)); return y; } /** *@功能:融合加速度计和磁力计进行姿态调整 * * */ void AHRSupdate(float gx, float gy, float gz, float ax, float ay, float az, float mx, float my, float mz,float *roll,float *pitch,float *yaw) { if(flag_2==1) { flag_2=0; ax_old=ax; ay_old=ay; az_old=az; gx_old=gx; gy_old=gy; gz_old=gz; mx_old=mx; my_old=my; mz_old=mz; } ax=(ax+ax_old)/2.0; ay=(ay+ay_old)/2.0; az=(az+az_old)/2.0; gx=(gx+gx_old)/2.0; gx=(gx+gx_old)/2.0; gx=(gx+gx_old)/2.0; mx=(mx+mx_old)/2.0; mx=(mx+mx_old)/2.0; mx=(mx+mx_old)/2.0; ax_old=ax; ay_old=ay; az_old=az; gx_old=gx; gy_old=gy; gz_old=gz; mx_old=mx; my_old=my; mz_old=mz; float norm; //用于单位化 float hx, hy, hz, bx, bz; // float vx, vy, vz, wx, wy, wz; float ex, ey, ez; // float tmp0,tmp1,tmp2,tmp3; // auxiliary variables to reduce number of repeated operations 辅助变量减少重复操作次数 float q0q0 = q0*q0; float q0q1 = q0*q1; float q0q2 = q0*q2; float q0q3 = q0*q3; float q1q1 = q1*q1; float q1q2 = q1*q2; float q1q3 = q1*q3; float q2q2 = q2*q2; float q2q3 = q2*q3; float q3q3 = q3*q3; // normalise the measurements 对加速度计和磁力计数据进行规范化 norm = invSqrt(ax*ax + ay*ay + az*az); ax = ax * norm; ay = ay * norm; az = az * norm; norm = invSqrt(mx*mx + my*my + mz*mz); mx = mx * norm; my = my * norm; mz = mz * norm; // compute reference direction of magnetic field 计算磁场的参考方向 //hx,hy,hz是mx,my,mz在参考坐标系的表示 hx = 2*mx*(0.50 - q2q2 - q3q3) + 2*my*(q1q2 - q0q3) + 2*mz*(q1q3 + q0q2); hy = 2*mx*(q1q2 + q0q3) + 2*my*(0.50 - q1q1 - q3q3) + 2*mz*(q2q3 - q0q1); hz = 2*mx*(q1q3 - q0q2) + 2*my*(q2q3 + q0q1) + 2*mz*(0.50 - q1q1 -q2q2); //bx,by,bz是地球磁场在参考坐标系的表示 bx = sqrt((hx*hx) + (hy*hy)); bz = hz; // estimated direction of gravity and magnetic field (v and w) //估计重力和磁场的方向 //vx,vy,vz是重力加速度在物体坐标系的表示 vx = 2*(q1q3 - q0q2); vy = 2*(q0q1 + q2q3); vz = q0q0 - q1q1 - q2q2 + q3q3; //wx,wy,wz是地磁场在物体坐标系的表示 wx = 2*bx*(0.5 - q2q2 - q3q3) + 2*bz*(q1q3 - q0q2); wy = 2*bx*(q1q2 - q0q3) + 2*bz*(q0q1 + q2q3); wz = 2*bx*(q0q2 + q1q3) + 2*bz*(0.5 - q1q1 - q2q2); // error is sum ofcross product between reference direction of fields and directionmeasured by sensors //ex,ey,ez是加速度计与磁力计测量出的方向与实际重力加速度与地磁场方向的误差,误差用叉积来表示,且加速度计与磁力计的权重是一样的 ex = (ay*vz - az*vy) + (my*wz - mz*wy); ey = (az*vx - ax*vz) + (mz*wx - mx*wz); ez = (ax*vy - ay*vx) + (mx*wy - my*wx); // integral error scaled integral gain //积分误差 exInt = exInt + ex*Ki*dt; eyInt = eyInt + ey*Ki*dt; ezInt = ezInt + ez*Ki*dt; // printf("exInt=%0.1f eyInt=%0.1f ezInt=%0.1f ",exInt,eyInt,ezInt); // adjusted gyroscope measurements //PI调节陀螺仪数据 gx = gx + Kp*ex + exInt; gy = gy + Kp*ey + eyInt; gz = gz + Kp*ez + ezInt; //printf("gx=%0.1f gy=%0.1f gz=%0.1f",gx,gy,gz); // integrate quaernion rate aafnd normalaizle //欧拉法解微分方程 // tmp0 = q0 + (-q1*gx - q2*gy - q3*gz)*halfT; // tmp1 = q1 + ( q0*gx + q2*gz - q3*gy)*halfT; // tmp2 = q2 + ( q0*gy - q1*gz + q3*gx)*halfT; // tmp3 = q3 + ( q0*gz + q1*gy - q2*gx)*halfT; // q0=tmp0; // q1=tmp1; // q2=tmp2; // q3=tmp3; //printf("q0=%0.1f q1=%0.1f q2=%0.1f q3=%0.1f",q0,q1,q2,q3); ////RUNGE_KUTTA 法解微分方程 k10=0.5 * (-gx*q1 - gy*q2 - gz*q3); k11=0.5 * ( gx*q0 + gz*q2 - gy*q3); k12=0.5 * ( gy*q0 - gz*q1 + gx*q3); k13=0.5 * ( gz*q0 + gy*q1 - gx*q2); k20=0.5 * (halfT*(q0+halfT*k10) + (halfT-gx)*(q1+halfT*k11) + (halfT-gy)*(q2+halfT*k12) + (halfT-gz)*(q3+halfT*k13)); k21=0.5 * ((halfT+gx)*(q0+halfT*k10) + halfT*(q1+halfT*k11) + (halfT+gz)*(q2+halfT*k12) + (halfT-gy)*(q3+halfT*k13)); k22=0.5 * ((halfT+gy)*(q0+halfT*k10) + (halfT-gz)*(q1+halfT*k11) + halfT*(q2+halfT*k12) + (halfT+gx)*(q3+halfT*k13)); k23=0.5 * ((halfT+gz)*(q0+halfT*k10) + (halfT+gy)*(q1+halfT*k11) + (halfT-gx)*(q2+halfT*k12) + halfT*(q3+halfT*k13)); k30=0.5 * (halfT*(q0+halfT*k20) + (halfT-gx)*(q1+halfT*k21) + (halfT-gy)*(q2+halfT*k22) + (halfT-gz)*(q3+halfT*k23)); k31=0.5 * ((halfT+gx)*(q0+halfT*k20) + halfT*(q1+halfT*k21) + (halfT+gz)*(q2+halfT*k22) + (halfT-gy)*(q3+halfT*k23)); k32=0.5 * ((halfT+gy)*(q0+halfT*k20) + (halfT-gz)*(q1+halfT*k21) + halfT*(q2+halfT*k22) + (halfT+gx)*(q3+halfT*k23)); k33=0.5 * ((halfT+gz)*(q0+halfT*k20) + (halfT+gy)*(q1+halfT*k21) + (halfT-gx)*(q2+halfT*k22) + halfT*(q3+halfT*k23)); k40=0.5 * (dt*(q0+dt*k30) + (dt-gx)*(q1+dt*k31) + (dt-gy)*(q2+dt*k32) + (dt-gz)*(q3+dt*k33)); k41=0.5 * ((dt+gx)*(q0+dt*k30) + dt*(q1+dt*k31) + (dt+gz)*(q2+dt*k32) + (dt-gy)*(q3+dt*k33)); k42=0.5 * ((dt+gy)*(q0+dt*k30) + (dt-gz)*(q1+dt*k31) + dt*(q2+dt*k32) + (dt+gx)*(q3+dt*k33)); k43=0.5 * ((dt+gz)*(q0+dt*k30) + (dt+gy)*(q1+dt*k31) + (dt-gx)*(q2+dt*k32) + dt*(q3+dt*k33)); q0=q0 + dt/6.0 * (k10+2*k20+2*k30+k40); q1=q1 + dt/6.0 * (k11+2*k21+2*k31+k41); q2=q2 + dt/6.0 * (k12+2*k22+2*k32+k42); q3=q3 + dt/6.0 * (k13+2*k23+2*k33+k43); // normalise quaternion norm = invSqrt(q0*q0 + q1*q1 + q2*q2 + q3*q3); q0 = q0 * norm; q1 = q1 * norm; q2 = q2 * norm; q3 = q3 * norm; *pitch = -asin(-2 * q1 * q3 + 2 * q0 * q2)* 57.3; // pitch *roll = atan2(2 * q2 * q3 + 2 * q0 * q1, -2 * q1 * q1 - 2 * q2 * q2 + 1)* 57.3; // roll *yaw = atan2(2*(q1*q2 + q0*q3),q0*q0+q1*q1-q2*q2-q3*q3) * 57.3; //yaw } /* *@功能:计算水平方向转的圈数 * * */ void CountTurns(float *newdata,float *olddata,short *turns) { if (*newdata<-170.0f && *olddata>170.0f) (*turns)++; if (*newdata>170.0f && *olddata<-170.0f) (*turns)--; } /* *@功能:计算偏航角 * * */ void CalYaw(float *yaw,short *turns) { *yaw=360.0**turns+*yaw; } /* *@功能:补偿欧拉角偏移,主要补偿yaw角 * * */ void CalibrateToZero(void) { uint8_t t=0; float sumpitch=0,sumroll=0,sumyaw=0; float pitch,roll,yaw; short igx,igy,igz; short iax,iay,iaz; short imx,imy,imz; float gx,gy,gz; float ax,ay,az; float mx,my,mz; for (t=0;t<150;t++) { MPU_Get_Gyro(&igx,&igy,&igz,&gx,&gy,&gz); MPU_Get_Accel(&iax,&iay,&iaz,&ax,&ay,&az); MPU_Get_Mag(&imx,&imy,&imz,&mx,&my,&mz); AHRSupdate(gx,gy,gz,ax,ay,az,mx,my,mz,&roll,&pitch,&yaw); // delay_us(6430); HAL_Delay(7); if (t>=100) { sumpitch+=pitch; sumroll+=roll; sumyaw+=yaw; } } pitchoffset=-sumpitch/150.0f; rolloffset=-sumroll/150.0f; yawoffset=-sumyaw/150.0f; // PRINTF("offset %0.1f %0.1f\n\r",rolloffset,pitchoffset); pitchoffset=0; rolloffset=0; yawoffset=0; } void USART1_IRQHandler(void) { usart1_IRQHandler(&uart1); } /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
bd3a37a607af028d8a2da193b5668e1ba3b073ad
[ "C" ]
2
C
beasterbro/LoRaWAN-GPS
d45f40a09941bcbbfcf3bdbb8c318656b1348f68
be7921933318be7f93a6a9b3f593bd02a8b5b0f1
refs/heads/master
<repo_name>jaaqo/make-readable<file_sep>/content.js chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { switch (message.type) { case "MAKE_READABLE": makeReadable(); default: break; } }); function makeReadable() { if (document.getElementById("makeReadableWrapper")) { document.body.innerHTML = document.getElementById( "makeReadableContainer" ).innerHTML; } else { const wrapper = document.createElement("div"); wrapper.id = "makeReadableWrapper"; wrapper.style.backgroundColor = "#fff"; wrapper.style.fontFamily = "Open Sans"; const fontLink = document.createElement("link"); fontLink.type = "text/css"; fontLink.rel = "stylesheet"; fontLink.href = "http://fonts.googleapis.com/css?family=Open+Sans"; wrapper.appendChild(fontLink); const container = document.createElement("div"); container.id = "makeReadableContainer"; container.style.paddingTop = "30px"; container.style.paddingBottom = "30px"; container.style.maxWidth = "800px"; container.style.width = "100%"; container.style.margin = "0 auto"; wrapper.appendChild(container); container.innerHTML = document.body.innerHTML; document.body.innerHTML = wrapper.outerHTML; } }
0141f1b0ff40ad8d7ef15b8bc7ff70158bbc2957
[ "JavaScript" ]
1
JavaScript
jaaqo/make-readable
81dd9684d8780ad0a1c596a49cb867e21bd07711
72921d529d407bca4da18e4739dc5f0880cf4542
refs/heads/master
<file_sep>// Psuedoclassical var makeCoolDancer = function(top, left, timeBetweenSteps) { this.$node = $('<span class="cooldancer"></span>'); this.top = top; this.left = left; this.setPosition(top, left); }; makeCoolDancer.prototype = Object.create(MakeDancer.prototype); makeCoolDancer.prototype.constructor = makeCoolDancer; makeCoolDancer.prototype.step = function() { // return; };<file_sep>// Psuedoclassical var makeBoringDancer = function(top, left, timeBetweenSteps) { this.$node = $('<span class="boringdancer"></span>'); this.top = top; this.left = left; this.setPosition(top, left); }; makeBoringDancer.prototype = Object.create(MakeDancer.prototype); makeBoringDancer.prototype.constructor = makeBoringDancer; makeBoringDancer.prototype.step = function() { // return; }; <file_sep>$(document).ready(function() { window.dancers = []; $('.addDancerButton').on('click', function(event) { var dancerMakerFunctionName = $(this).data('dancer-maker-function-name'); var dancerMakerFunction = window[dancerMakerFunctionName]; var dancer = new dancerMakerFunction( $("body").height() * Math.random(), $("body").width() * Math.random(), Math.random() * 1000 ); $('body').append(dancer.$node); }); $('.addboringButton').on('click', function(event) { var dancerMakerFunctionName = $(this).data('dancer-maker-function-name'); var dancerMakerFunction = window[dancerMakerFunctionName]; var dancer = new dancerMakerFunction( $("body").height() * Math.random(), $("body").width() * Math.random(), Math.random() * 1000 ); $('body').append(dancer.$node); }); $('.addcoolButton').on('click', function(event) { var dancerMakerFunctionName = $(this).data('dancer-maker-function-name'); var dancerMakerFunction = window[dancerMakerFunctionName]; var dancer = new dancerMakerFunction( $("body").height() * Math.random(), $("body").width() * Math.random(), Math.random() * 1000 ); $('body').append(dancer.$node); }); $('.lineupButton').on('click', function(event) { console.log('Hello Worlds'); $(".dancer").css({"left": "50px"}); $(".boringdancer").css({"left": "200px"}); $(".cooldancer").css({"left": "400px"}); }); });
090e4c88743b9c3f8171ad99d994acf7c367b739
[ "JavaScript" ]
3
JavaScript
snackersteph/subclass-dance-party
01e665374d8ca801983244f6230a19d70c4db2d4
d37ba39fec8a44745f372d75a823afb71ebfaa10
refs/heads/master
<repo_name>hatoo/libDA<file_sep>/Makefile CC = g++ -std=c++1y -msse4.2 -O3 -Wall CCtest = g++ -std=c++1y -msse4.2 -Wall CCpg = g++ -std=c++1y -msse4.2 -O3 -Wall -pg default : Hand.o Card.o ucb1_tuned.o montecarlo.o simulate.o $(CC) -shared -o libDA.dll Hand.o Card.o ucb1_tuned.o montecarlo.o simulate.o Hand.o : Hand.h Hand.cpp $(CC) -c -o Hand.o Hand.cpp Card.o : Card.cpp Card.h $(CC) -c -o Card.o Card.cpp test : test.cpp Card.o Hand.o simulate.o montecarlo.o ucb1_tuned.o $(CCtest) test.cpp Card.o Hand.o simulate.o montecarlo.o ucb1_tuned.o -lgtest -lgtest_main -lpthread -o test ucb1_tuned.o : ucb1_tuned.h ucb1_tuned.cpp $(CC) -c -o ucb1_tuned.o ucb1_tuned.cpp simulate.o : Card.h Hand.h simulate.cpp simulate.h $(CC) -c -o simulate.o simulate.cpp montecarlo.o : montecarlo.cpp montecarlo.h $(CC) -c -o montecarlo.o montecarlo.cpp prof: profile.cpp montecarlo.cpp montecarlo.h Card.cpp Card.h Hand.h Hand.cpp simulate.cpp simulate.h ucb1_tuned.cpp ucb1_tuned.h $(CCpg) -o prof profile.cpp montecarlo.cpp Card.cpp Hand.cpp simulate.cpp ucb1_tuned.cpp -g -fmudflap -lmudflap clean : rm *.o rm *.exe<file_sep>/test.cpp #include <gtest/gtest.h> #include "Card.h" #include "Hand.h" #include "montecarlo.h" #include "simulate.h" #include <iostream> #include <random> #include <algorithm> #include <set> #include "mlalgo.h" using namespace DA; void dump(Cards cs){ char prefixs[] = "SHDC"; int nums[] = {0,3,4,5,6,7,8,9,10,11,12,13,1,2,99,99,99,99}; std::cout << "[ "; for(int i=0;i<52+4;i++){ if((cs>>i)&1) std::cout << prefixs[i%4] << std::dec << nums[i/4] << " "; } if(cs&JOKER){ std::cout << "JOKER"; } std::cout << " ]" << std::endl; } void dump(const Hand &h){ switch(h.type){ case HandType::PASS: std::cout << "type:Pass "; break; case HandType::GROUP: std::cout << "type:Group "; break; case HandType::STAIR: std::cout << "type:Stair "; break; default: std::cout << "type:broken("<<(int)h.type<<") "; } std::cout << "low: " << (int)h.low << " "; std::cout << "high: " << (int)h.high << " "; std::cout << "joker: " << (int)h.joker << " "; dump(h.cards()); } void dump(const simulator &sim){ std::cout << "ontable: "; dump(sim.ontable); for(int i=0;i<simulator::playernum;i++){ std::cout << "player[" << i << "] has "; dump(sim.hands[i]); } std::cout << "turn: " << sim.turn << std::endl; std::cout << "pass: " << std::hex << (int)sim.passflag << " goalflag: " << (int)sim.goalflag; std::cout << " lock: " << (int)sim.lock << " rev: " << (int)sim.rev << std::endl; } TEST(popcnt,test){ ASSERT_EQ(popcnt(0x111full),7); } TEST(Cards,AllCards){ ASSERT_EQ(popcnt(AllCards),53); } TEST(SingleJoker,cards){ ASSERT_EQ(SingleJoker.cards(),JOKER); } TEST(PassHand,cards){ ASSERT_EQ(PassHand.cards(),0ull); } TEST(Hand,Bin){ Hand h = Hand(HandType::GROUP,2,3,4,5); Hand h2 = Hand::fromBin(h.toBin()); ASSERT_EQ(h,h2); } TEST(Hand_Group,qty){ Hand h = Hand::Group(0x1,1); ASSERT_EQ(h.qty(),1); h = Hand::Group(0xf,4,0x1); ASSERT_EQ(h.qty(),4); } TEST(Hand_Group,cards){ Hand h = Hand::Group(0x1,1); ASSERT_EQ(h.cards(),0x10ull); h = Hand::Group(0xf,1,0x1); ASSERT_EQ(h.cards(),JOKER|0xe0ull); } TEST(Hand_Stair,qty){ Hand h = Hand::Stair(0x1,1,3); ASSERT_EQ(h.qty(),3); } TEST(Hand_Stair,cards){ Hand h = Hand::Stair(0x1,1,3); ASSERT_EQ(h.cards(),0x1110ull); h = Hand::Stair(0x1,1,3,2); ASSERT_EQ(h.cards(),0x1010ull|JOKER); } TEST(getGroup,size){ //ASSERT_EQ(a,1); Hand hs[256]; int ret = getGroup(0x10ull,hs); ASSERT_EQ(ret,1); ASSERT_EQ(hs[0].cards(),0x10ull); ret = getGroup(0x10ull|JOKER,hs); ASSERT_EQ(ret,5); } TEST(getGroup,sim){ Hand hs[256]; int ret = getGroup(0x100ull,Hand::Group(1,1,0),false,false,hs); ASSERT_EQ(ret,1); ret = getGroup(0x100ull,Hand::Group(1,10,0),false,false,hs); ASSERT_EQ(ret,0); } TEST(getStair,size){ Hand hs[512]; int ret = getStair(0x1110ull,hs); ASSERT_EQ(ret,1); ret = getStair(0xfff0ull,hs); ASSERT_EQ(ret,4); ret = getStair(0xff00ull|JOKER,hs); ASSERT_EQ(ret,8); } TEST(getStair,sim){ Hand hs[512]; Hand h = Hand::Stair(1,1,3,Hand::nojokerord); int ret = getStair(0x1111000ull,h,false,false,hs); ASSERT_EQ(ret,1); ret = getStair(0x2222000ull,h,true,false,hs); ASSERT_EQ(ret,0); ret = getStair(0x1111000ull,h,false,true,hs); ASSERT_EQ(ret,0); } TEST(getGroup,random){ Hand hs[512]; std::random_device rd; std::mt19937_64 mt(rd()); for(int i=0;i<1000;i++){ Cards tefuda = mt()&((JOKER<<1)-1)&(~0xfull);//i==0?0x10100d220082100ull:mt()&((JOKER<<1)-1)&(~0xfull); int num = getGroup(tefuda,hs); ASSERT_LT(num,512); Cards t = 0; for(int k=0;k<num;k++){ t|=hs[k].cards(); //std::cout << std::hex << hs[k].cards() << std::endl; //std::cout << std::hex << (int)hs[k].suit << " " << (int)hs[k].low << " " << (int)hs[k].joker << std::endl; EXPECT_EQ(hs[k].cards()&0xfull,0); EXPECT_EQ(popcnt(hs[k].cards()),hs[k].qty()); } //std::cout << std::hex << (tefuda^t) << std::endl; ASSERT_EQ(tefuda,t); } } TEST(getStair,random){ Hand hs[512]; std::random_device rd; std::mt19937_64 mt(rd()); for(int i=0;i<1000;i++){ Cards tefuda = mt()&((JOKER<<1)-1)&(~0xfull); int num = getStair(tefuda,hs); Cards t = 0; for(int k=0;k<num;k++){ t|=hs[k].cards(); //std::cout << std::hex << hs[k].cards() << std::endl; //std::cout << std::hex << (int)hs[k].suit << " " << (int)hs[k].low << " " << (int)hs[k].high // <<" "<< (int)hs[k].joker << std::endl; EXPECT_EQ(hs[k].cards()&0xfull,0); EXPECT_EQ(popcnt(hs[k].cards()),hs[k].qty()); } ASSERT_EQ(tefuda&t,t); } } TEST(validHands,1){ Hand hs[512]; int num = validHands(0xffffffffff0ull,Hand::Group(4,1),true,false,hs); for(int i=0;i<num;i++){ if(!hs[i].ispass()){ if(hs[i].suit!=4){ std::cout << i << std::endl; FAIL(); } } } } TEST(simulator,randominit){ simulator sim; for(int k=0;k<100;k++){ sim.initializeRandom(); for(int i=0;i<sim.playernum;i++){ ASSERT_EQ(sim.hands[i]&0xf,0); ASSERT_EQ(sim.hands[i]&(~((JOKER<<1)-1)),0); } } } TEST(simulator,finitetime){ std::mt19937_64 mt(1234); simulator sim; Hand hs[512]; int counts[5]={0}; for(int i=0;i<10000;i++){ sim.initializeRandom(); int n = 0; uint8_t prevgoal = sim.goalflag; while(popcnt(sim.goalflag)<simulator::playernum){ for(int k=0;k<simulator::playernum;k++){ if(sim.goalflag&(1<<k)){ ASSERT_EQ(sim.hands[k],0); ASSERT_EQ(sim.passflag&(1<<k),1<<k); ASSERT_EQ(sim.isend(k),true); } } counts[sim.turn]++; EXPECT_TRUE((sim.ontable.cards()&Eights)==0); Cards tefuda = sim.CurrentPlayerHand(); ASSERT_EQ(tefuda&0xf,0); ASSERT_EQ(tefuda&(~((JOKER<<1)-1)),0); int num = validHands(tefuda,sim.ontable,sim.lock,sim.rev,hs); if(num>0){ for(int k=0;k<num;k++){ ASSERT_LT(hs[k].suit ,0x10); ASSERT_EQ(hs[k].cards()&0xf,0); EXPECT_EQ(hs[k].cards()&0xfull,0); EXPECT_EQ(hs[k].cards()&tefuda,hs[k].cards()); if((hs[k].cards()&tefuda)!=hs[k].cards()){ FAIL(); } EXPECT_EQ(popcnt(hs[k].cards()),hs[k].qty()); if(!hs[k].ispass()&& !(sim.ontable.cards()==JOKER&&hs[k].cards()==S3)){ if(sim.rev){ EXPECT_LT((int)hs[k].low,(int)sim.ontable.low); }else{ EXPECT_LT((int)sim.ontable.low,(int)hs[k].low); } } if(!hs[k].ispass()&& !(sim.ontable.cards()==JOKER) && hs[k].cards()!=JOKER){ if(sim.lock){ ASSERT_EQ(hs[k].suit,sim.ontable.suit); } } } std::uniform_int_distribution<int> distribution( 0, num-1 ); sim.puthand(hs[distribution(mt)]); }else{ FAIL(); sim.puthand(PassHand); } EXPECT_EQ(prevgoal,prevgoal&sim.goalflag); EXPECT_EQ(sim.passflag&sim.goalflag,sim.goalflag); prevgoal = sim.goalflag; if(++n > 1000){ std::cout << std::hex << " turn:" << sim.turn << " goal:" << (int)sim.goalflag << " pass:" << (int)sim.passflag << " passcount: " << (int)popcnt(sim.passflag) << " tefudacount " << popcnt(sim.hands[0]) << " " << popcnt(sim.hands[1]) << " " << popcnt(sim.hands[2]) << " " << popcnt(sim.hands[3]) << " " << popcnt(sim.hands[4]) << " " << std::endl; FAIL(); break; } } } for(int i=0;i<5;i++){ //std::cout << counts[i] << " " ; } //std::cout << std::endl; } TEST(simulator,humancheck){ /*std::mt19937_64 mt(1234); simulator sim; Hand hs[512]; int counts[5]={0}; for(int i=0;i<1;i++){ sim.initializeRandom(); while(popcnt(sim.goalflag)<simulator::playernum){ counts[sim.turn]++; Cards tefuda = sim.CurrentPlayerHand(); ASSERT_EQ(tefuda&0xf,0); ASSERT_EQ(tefuda&(~((JOKER<<1)-1)),0); int num = validHands(tefuda,sim.ontable,sim.lock,sim.rev,hs); if(num>0){ std::uniform_int_distribution<int> distribution( 0, num-1 ); auto r = distribution(mt); auto h = hs[r]; dump(sim); std::cout << "choose " << std::dec << r << "/" << num-1 << std::endl; dump(h); std::cout << std::endl; sim.puthand(h); }else{ FAIL(); sim.puthand(PassHand); } } } */ } TEST(simulatorInitializer,initialize){ Cards mytefuda = 0xf0ull; Cards rest = 0xffff00ull; int numtefudas[] = {4,4,4,4,4}; simulatorInitializer si(mytefuda,rest,0,PassHand,numtefudas,0,0,false,false); simulator sim; Cards cs[5]; for(int i=0;i<100;i++){ si.initialize(sim); int sum = 0; Cards all = 0ull; for(int i=0;i<5;i++){ EXPECT_EQ(popcnt(sim.hands[i]),4); sum+=popcnt(sim.hands[i]); all |= sim.hands[i]; for(int k=i+1;k<5;k++){ EXPECT_EQ(sim.hands[i]&sim.hands[k],0); } } EXPECT_EQ(sum,20); EXPECT_EQ(all,0xfffff0ull); EXPECT_EQ(sim.CurrentPlayerHand(),mytefuda); EXPECT_EQ(std::equal(cs,cs+5,sim.hands),false); std::copy(sim.hands,sim.hands+5,cs); } } TEST(ucb1_tuned,weaktest){ Bandit::UCB1_tuned ut(100); std::set<int> idxs; for(int i=0;i<1000;i++){ const int idx = ut.next(); ut.putscore(idx,1.0/100*idx); idxs.insert(idx); } EXPECT_EQ(idxs.size(),100); EXPECT_EQ(ut.next(),99); } TEST(montecarlo_uniform,finitetime){ simulator sim; for(int i=0;i<10;i++){ sim.initializeRandom(); Cards rest = 0; int nums[simulator::playernum]; for(int i=1;i<simulator::playernum;i++){ rest |= sim.hands[i]; nums[i] = popcnt(sim.hands[i]); } /*Hand montecarlo_uniform(Cards mytefuda,Cards rest,int mypos,const Hand &ontable ,int *tefudanums,uint8_t passflag,uint8_t goalflag,bool lock,bool rev,int playoutnum);*/ montecarlo_uniform(sim.hands[0],rest,0,sim.ontable,nums,sim.passflag,sim.goalflag,sim.lock,sim.rev,5000); } } TEST(montecarlo_uniform,lock){ simulator sim; for(int i=0;i<10;i++){ sim.initializeRandom(); sim.lock = true; sim.ontable = Hand::Group(1,1); Cards rest = 0; int nums[simulator::playernum]; for(int i=1;i<simulator::playernum;i++){ rest |= sim.hands[i]; nums[i] = popcnt(sim.hands[i]); } /*Hand montecarlo_uniform(Cards mytefuda,Cards rest,int mypos,const Hand &ontable ,int *tefudanums,uint8_t passflag,uint8_t goalflag,bool lock,bool rev,int playoutnum);*/ auto h = montecarlo_uniform(sim.hands[0],rest,0,sim.ontable,nums,sim.passflag,sim.goalflag,sim.lock,sim.rev,5000); if(!h.ispass()){ if(h.suit!=sim.ontable.suit){ std::cout << std::hex << (int)sim.ontable.type << " " << (int)sim.ontable.suit << " " << (int)sim.ontable.low << " " << (int)sim.ontable.high << " " << (int)sim.ontable.joker << std::endl; std::cout << std::hex << (int)h.type << " " << (int)h.suit << " " << (int)h.low << " " << (int)h.high << " " << (int)h.joker << std::endl; FAIL(); } } } } TEST(mlalgo,select){ std::mt19937 engine(123456); double probs[100]; int counts[100]={0}; for(auto &p:probs){ p=1; } for(int i=0;i<100000;i++){ auto ret = ML::select(probs,100,engine); ASSERT_LT(ret,100); ASSERT_GE(ret,0); counts[ret]++; } } /* TEST(exchange,t){ for(int i=0;i<20;i++){ simulator sim; sim.initializeRandom(); auto h = sim.hands[0]; int ranks[] = {0,1,2,3,4}; auto e = exchange_montecarlo_uniform(h,ranks,0,4000); ASSERT_EQ(popcnt(e),2); ASSERT_EQ(h&e,e); } } TEST(exchange,foreign){ for(int n=1;n<=2;n++) for(int i=0;i<20;i++){ simulator sim; sim.initializeRandom(); auto h = sim.hands[0]; auto e = exchange_montecarlo_uniform_foreign(h,n==2?0:1,4000); ASSERT_EQ(popcnt(e),n); ASSERT_EQ(h&e,e); } } */ int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<file_sep>/mlalgo.h #include <random> //machine learn namespace ML{ inline int select(const double *vec,int n,std::mt19937 &engine){ double sum = 0; for(int i=0;i<n;i++){ sum+=vec[i]; } std::uniform_real_distribution<double> distribution( 0.0, sum ) ; double r = distribution(engine); int idx=0; while((r-=vec[idx]) > 0){ ++idx; } return idx; } }<file_sep>/montecarlo.cpp #include "montecarlo.h" #include <algorithm> #include <vector> #include "ucb1_tuned.h" #include <random> #include "Hand.h" #include "Card.h" #include <iostream> #include <cmath> void DA::simulatorInitializer::initialize(simulator &sim){ std::shuffle(yama.begin(),yama.end(),mt); std::fill(sim.hands,sim.hands+simulator::playernum,0ull); auto itr = yama.begin(); for(int i=0;i<simulator::playernum;i++){ const int num = tefudanums[i]; for(int k=0;k<num;k++){ sim.hands[i] |= *itr; itr++; } } sim.hands[mypos] = mytefuda; sim.ontable = ontable; sim.goalflag = goalflag; sim.passflag = passflag; sim.turn = mypos; sim.lock = lock; sim.rev = rev; } void DA::simulatorInitializer::initialize_fromD3(simulator &sim){ initialize(sim); for(int i=0;i<simulator::playernum;i++){ if((sim.hands[i]&D3)==D3){ sim.turn = i; } } } inline int playout_uniform(DA::simulator &sim,int mypos,DA::Hand *buf,std::mt19937 &engine){ while(!sim.isend(mypos)){ DA::Cards t = sim.CurrentPlayerHand(); const int n = validHands(t,sim.ontable,sim.lock,sim.rev,buf); if(n==0){ sim.puthand(DA::PassHand); }else if(n==1){ sim.puthand(buf[0]); }else{ bool f =false; for(int k=0;k<n;k++){ if(buf[k].cards()==t){ sim.puthand(buf[k]); f=true; break; } } if(!f){ std::uniform_int_distribution<int> distribution( 0, n-1 ) ; sim.puthand(buf[distribution(engine)]); } } } return sim.rank(mypos); } DA::Hand DA::montecarlo_uniform(Cards mytefuda,Cards rest,int mypos,const Hand &ontable ,int *tefudanums,uint8_t passflag,uint8_t goalflag,bool lock,bool rev,int playoutnum){ std::mt19937 engine( getrandseed() ) ; Hand myhands[256]; Hand buf[256]; simulatorInitializer siminitter(mytefuda,rest,mypos,ontable,tefudanums,passflag,goalflag,lock,rev); simulator sim; const int handnum = validHands(mytefuda,ontable,lock,rev,myhands); if(handnum==1){//場に何もない時...これで上がる。それ以外...パス return myhands[0]; } Bandit::UCB1_tuned bandit(handnum); for(int i=0;i<playoutnum;i++){ const int idx = bandit.next(); siminitter.initialize(sim); sim.puthand(myhands[idx]); int rank = playout_uniform(sim,mypos,buf,engine); constexpr double reward[] = {1.0,0.88,0.5,0.11,0.0}; bandit.putscore(idx,reward[rank]); } return myhands[bandit.bestmean()]; } int DA::exchanges(Cards tefuda,int num,Cards *out){ std::vector<Cards> ones; for(int i=0;tefuda>>i;i++){ if((tefuda>>i)&1){ ones.push_back(u<<i); } } if(num==1){ std::copy(ones.begin(),ones.end(),out); return ones.size(); }else{ Cards *ptr = out; for(int i=0;i<ones.size();i++){ for(int k=i+1;k<ones.size();k++){ *ptr = ones[i] | ones[k]; ptr++; } } return ptr-out; } } inline void doexchange(DA::Cards &greater,DA::Cards &lesser,DA::Cards ex){ greater^=ex; lesser|=ex; } DA::Cards DA::exchange_montecarlo_uniform(DA::Cards tefuda,const int ranks[],int myrank,int playoutnum){ std::mt19937 engine( getrandseed() ) ; int tefudanums[] = {10,10,10,10,10}; int iranks[5]={0}; Cards cs[256]; const int exnum = exchanges(tefuda,myrank==0?2:1,cs); for(int i=0;i<5;i++){ iranks[ranks[i]] = i; } { int d = iranks[0]; for(int i=0;i<3;i++){ tefudanums[d] = 11; d = (d+1)%5; } } if(myrank==0){ tefudanums[iranks[0]]+=2; tefudanums[iranks[4]]-=2; }else{ tefudanums[iranks[1]]+=1; tefudanums[iranks[3]]-=1; } Bandit::UCB1_tuned bandit(exnum); const int mypos = iranks[myrank]; const int aite = iranks[myrank==0?4:3]; simulatorInitializer siminitter(tefuda,AllCards^tefuda,mypos,PassHand,tefudanums,0,0,false,false); simulator sim; Hand buf[256]; for(int i=0;i<playoutnum;i++){ const int idx = bandit.next(); siminitter.initialize_fromD3(sim); const Cards e = cs[idx]; doexchange(sim.hands[mypos],sim.hands[aite],e); int rank = playout_uniform(sim,mypos,buf,engine); constexpr double reward[] = {1.0,0.88,0.5,0.11,0.0}; bandit.putscore(idx,reward[rank]); } return cs[bandit.bestmean()]; } uint64_t DA::montecarlo_uniform_foreign(uint64_t mytefuda,uint64_t rest,int32_t mypos,uint64_t ontable_bin ,int32_t *tefudanums,uint8_t passflag,uint8_t goalflag,uint8_t lock,uint8_t rev,int32_t playoutnum){ const Hand ontable = Hand::fromBin(ontable_bin); int tn[5]; for(int i=0;i<5;i++){ tn[i] = tefudanums[i]; } const Hand ret = montecarlo_uniform(mytefuda,rest,mypos,ontable,tn,passflag,goalflag,lock,rev,playoutnum); return ret.toBin(); } uint64_t DA::exchange_montecarlo_uniform_foreign(uint64_t tefuda,int32_t myrank,int32_t *ranks,int32_t playoutnum){ int tn[5]={0,1,2,3,4}; for(int i=0;i<5;i++){ tn[i] = ranks[i]; } return DA::exchange_montecarlo_uniform(tefuda,ranks,myrank,playoutnum); } /* using namespace DA; inline double crow_value(const Hand &h,bool rev){ const auto qty = h.qty(); const auto str = h.low-1; const int offset = rev?83:0; //3 4 5 constexpr int seqoffset[] = {19,9,0}; constexpr int groupoffset = 30; if(h.cards()==JOKER){ return crow_param[offset+82]; } switch(h.type){ case HandType::GROUP: return crow_param[offset+groupoffset+(4*str)+(qty-1)]; case HandType::STAIR: return crow_param[offset+seqoffset[std::min(5,qty)-3]+str]; case HandType::PASS: return -10000; } return -10000; } inline double crow_value(Cards tefuda,bool rev){ Hand buf[256]; double sum=0; int n = getStair(tefuda,buf); for(int i=0;i<n;i++){ sum += crow_value(buf[i],rev); } for(int i=0;i<13;i++){ if((tefuda>>(4+4*i))&(0xf)){ sum+=crow_value(Hand::Group((tefuda>>(4+4*i))&(0xf),i+1,0),rev); } } if(tefuda&JOKER){ sum+=crow_value(SingleJoker,rev); } return sum; } Hand crow_policy(Cards tefuda,bool rev,std::mt19937 &engine){ Hand buf[256]; double values[256]; const int n = validHands(tefuda,buf); for(int i=0;i<n;i++){ values[i] = exp(crow_value(tefuda^(buf[i].cards()),rev)); } const int idx = ML::select(values,n,engine); return buf[idx]; } Hand DA::montecarlo_crow(Cards mytefuda,Cards rest,int mypos,const Hand &ontable ,int *tefudanums,uint8_t passflag,uint8_t goalflag,bool lock,bool rev,int playoutnum){ std::mt19937 engine( getrandseed() ) ; Hand myhands[256]; simulatorInitializer siminitter(mytefuda,rest,mypos,ontable,tefudanums,passflag,goalflag,lock,rev); simulator sim; const int handnum = validHands(mytefuda,ontable,lock,rev,myhands); if(handnum==1){//場に何もない時...これで上がる。それ以外...パス return myhands[0]; } Bandit::UCB1_tuned bandit(handnum); for(int i=0;i<playoutnum;i++){ const int idx = bandit.next(); siminitter.initialize(sim); sim.puthand(myhands[idx]); while(!sim.isend(mypos)){ Cards t = sim.CurrentPlayerHand(); sim.puthand(crow_policy(t,sim.rev,engine)); } //int rank = playout_uniform(sim,mypos,engine); constexpr double reward[] = {1.0,0.88,0.5,0.11,0.0}; bandit.putscore(idx,reward[/*rank sim.rank(mypos)]); } return myhands[bandit.bestmean()]; } uint64_t DA::montecarlo_crow_foreign(uint64_t mytefuda,uint64_t rest,int32_t mypos,uint64_t ontable_bin ,int32_t *tefudanums,uint8_t passflag,uint8_t goalflag,uint8_t lock,uint8_t rev,int32_t playoutnum){ const Hand ontable = Hand::fromBin(ontable_bin); int tn[5]; for(int i=0;i<5;i++){ tn[i] = tefudanums[i]; } const Hand ret = montecarlo_crow(mytefuda,rest,mypos,ontable,tn,passflag,goalflag,lock,rev,playoutnum); return ret.toBin(); } */<file_sep>/montecarlo.h #include "Hand.h" #include "Card.h" #include "ucb1_tuned.h" #include "simulate.h" #include <cstdint> #include <random> #include <algorithm> #include <chrono> #include <vector> #include <ctime> #pragma once namespace DA{ inline uint64_t getrandseed(){ return time(NULL);//chronoはmingw64で試してみたところ追加でdllが必要になったので使わない。 } class simulatorInitializer{ std::vector<Cards> yama; std::mt19937 mt; Cards mytefuda; Cards rest; int mypos; Hand ontable; int tefudanums[simulator::playernum]; uint8_t passflag; uint8_t goalflag; int turn; bool lock; bool rev; public: simulatorInitializer(Cards _mytefuda,Cards _rest,int _mypos,const Hand &_ontable ,int *_tefudanums,uint8_t _passflag,uint8_t _goalflag,bool _lock,bool _rev) :mytefuda(_mytefuda),rest(_rest),mypos(_mypos),ontable(_ontable),passflag(_passflag),goalflag(_goalflag),lock(_lock),rev(_rev){ std::copy(_tefudanums,_tefudanums+simulator::playernum,tefudanums); std::mt19937 engine( getrandseed() ) ; mt = engine; rest = rest & (~mytefuda); for(int i=0;(rest>>i)!=0;i++){ if(((rest>>i)&1ull) == 1){ yama.push_back(u<<i); } } tefudanums[mypos] = 0; } void initialize(simulator &sim); void initialize_fromD3(simulator &sim); }; //int playout_uniform(simulator &sim,int mypos); Hand montecarlo_uniform(Cards mytefuda,Cards rest,int mypos,const Hand &ontable ,int *tefudanums,uint8_t passflag,uint8_t goalflag,bool lock,bool rev,int playoutnum); /* Hand montecarlo_crow(Cards mytefuda,Cards rest,int mypos,const Hand &ontable ,int *tefudanums,uint8_t passflag,uint8_t goalflag,bool lock,bool rev,int playoutnum); */ int exchanges(Cards tefuda,int num,Cards *out); Cards exchange_montecarlo_uniform(Cards tefuda,const int ranks[],int myrank,int playoutnum); extern "C" uint64_t montecarlo_uniform_foreign(uint64_t mytefuda,uint64_t rest,int32_t mypos,uint64_t ontable_bin ,int32_t *tefudanums,uint8_t passflag,uint8_t goalflag,uint8_t lock,uint8_t rev,int32_t playoutnum); extern "C" uint64_t exchange_montecarlo_uniform_foreign(uint64_t tefuda,int32_t myrank,int32_t *ranks,int32_t playoutnum); /* extern "C" uint64_t montecarlo_crow_foreign(uint64_t mytefuda,uint64_t rest,int32_t mypos,uint64_t ontable_bin ,int32_t *tefudanums,uint8_t passflag,uint8_t goalflag,uint8_t lock,uint8_t rev,int32_t playoutnum); */ constexpr double crow_param[166] = { // for Normal // 5-Sequence -0.165103445, -1.367353957, -1.084887944, -0.103446973, 0.005614329, // 3-7 -0.177613166, 0.020646977, -0.204253239, 0.018329075, // 8-J // 4-Sequence -1.250221599, -1.305045504, -1.456065252, -0.889654668, -2.987781810, // 3-7 -1.388516263, -1.176554458, -0.794348341, -2.055029278, -1.890634784, // 8-Q // 3-Sequence -3.704179332, -4.281589257, -4.719447787, -4.495022219, // 3-6 -5.089943875, -6.087235981, -2.976696921, -4.422503509, // 7-T -4.221070745, -4.222361704, -4.002477132, // J-K // Solo, Group(2-4pair) -3.902118723, -5.356407798, -4.459366682, -1.673269738, // 3 -3.813512676, -5.646004771, -4.959193566, -0.598674962, // 4 -3.707419103, -5.827590172, -5.076551563, -0.455296345, // 5 -2.914792373, -5.043195734, -4.436616845, -0.790830702, // 6 -2.659857260, -4.498763022, -3.548758188, -0.164144807, // 7 -6.162883027, -7.620724057, -6.552047173, -0.409127296, // 8 -3.377120658, -4.432217918, -3.604395246, -0.447012953, // 9 -2.931679825, -3.827014698, -2.405417588, -0.186615449, // T -2.977701799, -3.088013233, -1.833889336, -0.034788011, // J -3.180260758, -2.933643112, -1.445919210, 0.025592376, // Q -3.039855900, -2.900483696, -1.851938754, 0.005744616, // K -2.396018281, -2.156369375, -1.014889482, 0.035431113, // A -2.386842708, -2.704110364, -2.010499011, -0.169877329, // 2 0.557952043, // JOKER // for Revolution // 5-Sequence 0.015941512, -0.076186286, -1.869357120, -0.280747683, -0.003119470, // 3-7 -0.892415555, 0.001491174, -0.634278907, -1.064733776, // 8-J // 4-Sequence -1.496744051, -0.825525999, -2.733283880, -0.894995405, -1.898804633, // 3-7 -1.538144313, -1.025547067, -0.837688942, -1.185448678, -3.504837011, // 8-Q // 3-Sequence -4.213282878, -3.897294649, -4.012261980, -4.517719657, // 3-6 -5.015807231, -5.507484021, -4.051525440, -4.608462404, // 7-T -4.057425508, -4.326998459, -5.129364509, // J-K // Solo, Group(2-4pair) -2.415693628, -2.782669751, -1.843946193, -0.004313174, // 3 -2.704387616, -2.350158654, -1.209685749, 0.019062053, // 4 -3.187466989, -2.919736669, -1.705203490, -0.060453580, // 5 -3.442788490, -3.467241349, -2.027801109, -0.012216187, // 6 -3.321312748, -3.495115522, -2.244767429, -0.129789376, // 7 -5.744447193, -5.757793499, -5.355164182, -2.659961621, // 8 -3.147674227, -3.078045473, -2.287018461, -0.368540465, // 9 -2.965633813, -4.850912354, -3.522098268, 0.016110389, // T -3.047409384, -4.952092305, -4.031908245, -0.387839210, // J -3.378235820, -5.678286406, -4.574724270, -0.436443491, // Q -3.720091654, -6.173770806, -5.468976055, -0.706931919, // K -4.073372779, -6.424423870, -5.079275011, -0.898643720, // A -4.051587944, -5.937719397, -5.274388701, -2.298538090, // 2 0.848130302, // JOKER }; }<file_sep>/simulate.h #include "Card.h" #include "Hand.h" #include <cstdint> #include <algorithm> #pragma once namespace DA{ struct simulator{ static constexpr int playernum = 5; Cards hands[playernum]; Hand ontable; uint8_t goalflag; uint8_t passflag; int turn; bool lock; bool rev; simulator(const Cards* inithands,const Hand &_ontable,bool _goalflag,bool _passflag ,int _turn,bool _lock,bool _rev):ontable(_ontable),goalflag(_goalflag) ,passflag(_passflag),turn(_turn),lock(_lock),rev(_rev){ std::copy(inithands,inithands+playernum,hands); } simulator():ontable(PassHand),goalflag(0),passflag(0),turn(0),lock(false),rev(false){ std::fill(hands,hands+playernum,0ull); } inline Cards CurrentPlayerHand()const{ return hands[turn]; } void puthand(const Hand&); inline void reset(){ lock = false; ontable = PassHand; passflag = goalflag; } void initializeRandom(); inline bool isend(int pos){ return ((goalflag&(1<<pos))!=0)||popcnt(goalflag)>=(playernum-1); } inline int rank(int pos){//return 0-4 return (goalflag&(1<<pos))!=0?popcnt(goalflag)-1:playernum-1; } }; }<file_sep>/Hand.h #include <cstdint> #include "Card.h" #pragma once namespace DA{ enum class HandType{ PASS=0,GROUP=1,STAIR=2 }; struct Hand{ HandType type; uint8_t suit; uint8_t low; uint8_t high; uint8_t joker; static constexpr uint8_t nojokerord = 0xff; Hand()=default; constexpr Hand(HandType _type,uint8_t _suit,uint8_t _low,uint8_t _high,uint8_t _joker): type(_type),suit(_suit),low(_low),high(_high),joker(_joker){} static constexpr Hand Pass(){ return Hand(HandType::PASS,0,0,0,0); } static constexpr Hand Group(uint8_t suit,uint8_t ord,uint8_t jokersuit=0){ return Hand(HandType::GROUP,suit,ord,ord,jokersuit); } static constexpr Hand Stair(uint8_t suit,uint8_t low,uint8_t high,uint8_t jokerord=nojokerord){ return Hand(HandType::STAIR,suit,low,high,jokerord); } inline bool ispass()const{ return type==HandType::PASS; } inline bool isrev()const{ switch(type){ case HandType::GROUP: return qty()>=4; case HandType::STAIR: return qty()>=5; default: return false; } return false; } inline int qty()const{ switch(type){ case HandType::PASS: return 0; case HandType::GROUP: return popcnt(suit); case HandType::STAIR: return high-low+1; } return 0; } inline Cards cards()const{ switch(type){ case HandType::PASS: return 0; case HandType::GROUP: return (joker?JOKER:0ull)|(((Cards)(suit^joker))<<(low*4));//演算子の優先順位知らず case HandType::STAIR: return ((joker==nojokerord?0:JOKER)|((0x1111111111111111ull>>(4*low)<<(4*low)<<(4*(15-high))>>(4*(15-high)))*suit))^(joker==nojokerord?0:(Cards)suit<<(4*joker)); } return 0; } bool operator==(const Hand&)const; uint64_t toBin()const; static Hand fromBin(uint64_t); }; constexpr Hand PassHand = Hand::Pass(); constexpr Hand SingleJoker = Hand::Group(1,14,1); int getGroup(Cards,Hand*); int getGroup(Cards tefuda,const Hand &group,bool lock,bool rev,Hand *out); int getStair(Cards,Hand*); int getStair(Cards tefuda,const Hand &stair,bool lock,bool rev,Hand *out); int validHands(Cards,Hand*); int validHands(Cards tefuda,const Hand &hand,bool lock,bool rev,Hand *out); }<file_sep>/Card.h #include <cstdint> #include <smmintrin.h> #pragma once namespace DA{ typedef uint64_t Cards; constexpr Cards u = 1; constexpr Cards JOKER = u<<(14*4); constexpr Cards S3 = u<<4; constexpr Cards D3 = u<<6; constexpr Cards Eights = 0xfull << (4*6); constexpr Cards AllCards = ((JOKER<<1)-1)&(~0xfull); constexpr int popcnt8bit_memo[] = {0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8}; inline int popcnt(Cards c){ return _mm_popcnt_u64(c); } constexpr int popcnt(uint8_t b){ return popcnt8bit_memo[b]; } }<file_sep>/ucb1_tuned.cpp #include "ucb1_tuned.h" #include <vector> #include <cmath> #include <algorithm> double Bandit::UCB1_record::v(int n){ if(n==0 || j==0){ return MAX_V; } const double ave = sum/j; const double avesqr = sumsqr/j; const double a = sqrt(2*log(n)/j); const double right = std::min(0.25,avesqr-ave*ave+a); const double left = log(n)/j; return ave+sqrt(left*right); } void Bandit::UCB1_record::put(double s){ ++j; sumsqr+=s*s; sum+=s; } int Bandit::UCB1_tuned::next(){ int idx = 0; double mv = 0; for(int i=0;i<records.size();i++){ double v = records[i].v(n); if(mv<v){ idx = i; mv = v; } } return idx; } int Bandit::UCB1_tuned::putscore(int idx,double score){ ++n; records[idx].put(score); } int Bandit::UCB1_tuned::bestmean(){ int idx = 0; double mv = 0; for(int i=0;i<records.size();i++){ double v = records[i].mean(); if(mv<v){ idx = i; mv = v; } } return idx; }<file_sep>/ucb1_tuned.h #include <vector> #include <cmath> #include <cfloat> #pragma once namespace Bandit{ constexpr double MAX_V = DBL_MAX; class UCB1_record{ int j; double sumsqr; double sum; public: UCB1_record():j(0),sumsqr(0),sum(0){} double v(int n); void put(double s); double mean()const{ return j>0?sum/j:0; } }; class UCB1_tuned{ int n; std::vector<UCB1_record> records; public: UCB1_tuned(int num):n(0),records(num){} int next(); int bestmean(); int putscore(int idx,double score); }; }<file_sep>/simulate.cpp #include "simulate.h" #include "Card.h" #include "Hand.h" #include <cstdint> #include <vector> #include <algorithm> #include <random> #include <iostream> inline bool resethand(DA::Cards ontable,DA::Cards put){ if((put&DA::Eights)!=0){ return true; } if(ontable==DA::JOKER&&put==DA::S3){ return true; } return false; } inline int nextturn(int turn,uint8_t flag){ if(flag==((1<<DA::simulator::playernum)-1)){ std::cout << "debug" << std::endl; return turn; } do{ turn=(turn+1)%DA::simulator::playernum; }while((flag&(1<<turn))!=0); return turn; } void DA::simulator::puthand(const Hand& hand){ constexpr uint8_t fullraise = (1<<playernum)-1; if(hand.ispass()){ passflag |= 1<<turn; if(passflag==fullraise){ reset(); }else{ turn = nextturn(turn,passflag); } }else{ lock = lock||(ontable.suit==hand.suit); if(hand.isrev()){ rev = !rev; } const Cards cs = hand.cards(); const Cards tefuda = CurrentPlayerHand()^cs; const Cards tablecards = ontable.cards(); hands[turn] = tefuda; ontable = hand; if(tefuda==0ull){ goalflag |= 1<<turn; passflag |= goalflag; if(goalflag==fullraise){ return; }else{ if(passflag==fullraise||resethand(tablecards,cs)){ reset(); } turn = nextturn(turn,passflag); } }else{ if(resethand(tablecards,cs)){ reset(); }else{ turn = nextturn(turn,passflag); } } } /* if(hand.ispass()){ passflag |= 1<<turn; if(passflag==fullraise){ reset(); }else{ turn = nextturn(turn,passflag); } }else{ lock = lock||(ontable.suit==hand.suit); if(hand.isrev()){ rev = !rev; } const Cards cs = hand.cards(); const Cards tefuda = CurrentPlayerHand()^cs; const Cards tablecards = ontable.cards(); hands[turn] = tefuda; if(tefuda==0ull){ goalflag |= 1<<turn; } if(goalflag==fullraise)return; if(resethand(tablecards,cs)){ reset(); if(tefuda==0ull){ turn = nextturn(turn,passflag); } }else{ if(passflag==fullraise){ reset(); }else{ ontable = hand; } turn = nextturn(turn,passflag); } } */ } void DA::simulator::initializeRandom(){ std::random_device rd; std::mt19937 mt(159); std::fill(hands,hands+playernum,0ull); constexpr int yamasize = 53; int yama[yamasize]; for(int i=0;i<yamasize;i++){ yama[i] = i; } std::shuffle(yama,yama+yamasize,mt); for(int i=0;i<yamasize;i++){ hands[i%playernum] |= (u<<(yama[i]+4)); } lock = false; rev = false; ontable = PassHand; passflag = 0; goalflag = 0; turn = 0; } <file_sep>/profile.cpp #include "montecarlo.h" #include "simulate.h" #include "Card.h" #include "Hand.h" int main(){ DA::simulator sim; for(int i=0;i<100;i++){ sim.initializeRandom(); DA::Cards rest = 0; int nums[DA::simulator::playernum]; for(int i=1;i<DA::simulator::playernum;i++){ rest |= sim.hands[i]; nums[i] = DA::popcnt(sim.hands[i]); } DA::montecarlo_uniform(sim.hands[0],rest,0,sim.ontable,nums,sim.passflag,sim.goalflag,sim.lock,sim.rev,5000); } }
7039a6faf43253acc79aa51f0adad327737c07a5
[ "Makefile", "C++" ]
12
Makefile
hatoo/libDA
3e729a58014ce92e0ec8db35b6564cc06289d395
73320ece9b71e3c4379d8f384f7615a6c56596d6
refs/heads/master
<file_sep>require 'pry' class Student < User # create initialize method - no arguments # - should have @knowledge array = [] def initialize @knowledge = [] end def learn(string) # has argument (string) # adds string to knowledge array @knowledge << string end def knowledge @knowledge end end
a99846e1728c38641b9caf1744623c701adcde07
[ "Ruby" ]
1
Ruby
WebDevCurriculum/ruby-inheritance-lab-v-000
83a389ae5ab66d9186f8b04415d364db6e35dc00
382729a3c94836ae0bdbd7791390a51c216609e5
refs/heads/master
<file_sep>package reasonablecare; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ StaffShellTest.class,LoginShellTest.class, StudentShellTest.class }) public class AllTests { } <file_sep>package reasonablecare; import asg.cliche.Shell; /** * Shell factory class needed to load shells with the Cliche library * */ public class ShellFactory { static final String APP_NAME = ReasonableCare.APP_NAME; public ShellFactory() { } public Shell createSubshell(Shell parent, String name, Object shell) { return asg.cliche.ShellFactory .createSubshell(name, parent, APP_NAME, shell); } } <file_sep>VAR john_id NUMBER INSERT INTO Doctor(doctorName, password, phoneNumber, specialization) VALUES('<NAME>', 'password', '<PASSWORD>', 'Oncology Surgeon') RETURNING doctorId INTO :john_id; INSERT INTO Doctor(doctorName, password, phoneNumber, specialization) VALUES('<NAME>', 'password', '<PASSWORD>', 'Oncology Surgeon'); INSERT INTO Nurse(nurseName, password) VALUES('<NAME>', '<PASSWORD>'); INSERT INTO Nurse(nurseName, password) VALUES('<NAME>', 'password'); INSERT INTO Staff(staffName, password) VALUES('<NAME>', '<PASSWORD>'); VAR jason_id NUMBER INSERT INTO Student(studentName, password, healthInsuranceProviderName, healthInsurancePolicyNumber, startingDate) VALUES('<NAME>', 'password', '<PASSWORD>', 123456, '15-MAR-2011') RETURNING studentId INTO :jason_id; VAR dale_id NUMBER INSERT INTO Student(studentName, password, startingDate) VALUES('<NAME>', 'password', '<PASSWORD>') RETURNING studentId INTO :dale_id; VAR appt_id NUMBER INSERT INTO Appointment(reasonForVisit, type, appointmentTime, doctorNotes, cost) VALUES('Orthopedics', 'Office Visit', TO_DATE('15.03.2011 09:00:00', 'dd.mm.yyyy hh24:mi:ss'), 'Boken bone: Prescribed pain killer', 30) RETURNING appointmentId INTO :appt_id; INSERT INTO MakesAppointment(studentId, doctorId, appointmentId) VALUES(:jason_id, :john_id, :appt_id); INSERT INTO Appointment(reasonForVisit, type, appointmentTime, doctorNotes, cost) VALUES('Vaccination', 'Vaccination', TO_DATE('21.04.2014 16:00:00', 'dd.mm.yyyy hh24:mi:ss'), '', 100) RETURNING appointmentId INTO :appt_id; INSERT INTO MakesAppointment(studentId, doctorId, appointmentId) VALUES(:jason_id, :john_id, :appt_id); INSERT INTO Appointment(reasonForVisit, type, appointmentTime, doctorNotes, cost) VALUES('Vaccination', 'Vaccination', TO_DATE('16.03.2011 09:00:00', 'dd.mm.yyyy hh24:mi:ss'), '', 30) RETURNING appointmentId INTO :appt_id; INSERT INTO MakesAppointment(studentId, doctorId, appointmentId) VALUES(:dale_id, :john_id, :appt_id); INSERT INTO Appointment(reasonForVisit, type, appointmentTime, doctorNotes, cost) VALUES('Vaccination', 'Vaccination', TO_DATE('16.03.2011 09:30:00', 'dd.mm.yyyy hh24:mi:ss'), '', 30) RETURNING appointmentId INTO :appt_id; INSERT INTO MakesAppointment(studentId, doctorId, appointmentId) VALUES(:dale_id, :john_id, :appt_id); INSERT INTO Appointment(reasonForVisit, type, appointmentTime, doctorNotes, cost) VALUES('Vaccination', 'Vaccination', TO_DATE('16.03.2011 10:00:00', 'dd.mm.yyyy hh24:mi:ss'), '', 30) RETURNING appointmentId INTO :appt_id; INSERT INTO MakesAppointment(studentId, doctorId, appointmentId) VALUES(:dale_id, :john_id, :appt_id); COMMIT; <file_sep>package reasonablecare; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.isEmptyOrNullString; import static org.hamcrest.Matchers.not; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import org.junit.After; import org.junit.Before; import org.junit.Test; import asg.cliche.Shell; public class LoginShellTest extends BaseShellTest { private LoginShell shell; private ShellFactory mockedFactory; private Shell mockedSubshell; @Before public void setUpShell() throws Exception { shell = new LoginShell(getConnection()); // Create a mock subshell for the loginshell to create mockedSubshell = mock(Shell.class); doNothing().when(mockedSubshell).commandLoop(); // Create a mock ShellFactory that doesn't create subshells. mockedFactory = mock(ShellFactory.class); doReturn(mockedSubshell).when(mockedFactory).createSubshell( any(Shell.class), anyString(), any()); shell.setFactory(mockedFactory); } @After public void tearDownShell() throws Exception { mockedFactory = null; mockedSubshell = null; shell = null; } @Test public void testLoginStudent() throws Exception { shell.login(1004, "Triangle"); verify(mockedFactory).createSubshell(any(Shell.class), eq("student"), any(StudentShell.class)); verify(mockedSubshell).commandLoop(); } @Test public void testLoginDoctor() throws Exception { shell.login(2000, "India"); verify(mockedFactory).createSubshell(any(Shell.class), eq("doctor"), any(DoctorShell.class)); verify(mockedSubshell).commandLoop(); } @Test public void testLoginNurse() throws Exception { shell.login(4003, "Green"); verify(mockedFactory).createSubshell(any(Shell.class), eq("nurse"), any(NurseShell.class)); verify(mockedSubshell).commandLoop(); } @Test public void testLoginStaff() throws Exception { shell.login(5020, "Eleven"); verify(mockedFactory).createSubshell(any(Shell.class), eq("staff"), any(StaffShell.class)); verify(mockedSubshell).commandLoop(); } @Test public void testLoginWrongId() throws Exception { // ID range 3000-3999 is invalid for Appointments. Can't login with those. String result = shell.login(3040, "<PASSWORD>"); // No subshell created verify(mockedFactory, never()).createSubshell(any(Shell.class), anyString(), any()); // Non-empty error message returned assertThat(result, not(isEmptyOrNullString())); } @Test public void testLoginStudentWrongPassword() throws Exception { String result = shell.login(1004, "<PASSWORD>"); // No subshell created verify(mockedFactory, never()).createSubshell(any(Shell.class), anyString(), any()); // Non-empty error message returned assertThat(result, not(isEmptyOrNullString())); } @Test public void testLoginDoctorWrongPassword() throws Exception { String result = shell.login(2000, "<PASSWORD>"); // No subshell created verify(mockedFactory, never()).createSubshell(any(Shell.class), anyString(), any()); // Non-empty error message returned assertThat(result, not(isEmptyOrNullString())); } @Test public void testLoginNurseWrongPassword() throws Exception { String result = shell.login(4003, "<PASSWORD>"); // No subshell created verify(mockedFactory, never()).createSubshell(any(Shell.class), anyString(), any()); // Non-empty error message returned assertThat(result, not(isEmptyOrNullString())); } @Test public void testLoginStaffWrongPassword() throws Exception { String result = shell.login(5020, "<PASSWORD>"); // No subshell created verify(mockedFactory, never()).createSubshell(any(Shell.class), anyString(), any()); // Non-empty error message returned assertThat(result, not(isEmptyOrNullString())); } } <file_sep>package reasonablecare; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import asg.cliche.Command; import asg.cliche.Shell; import asg.cliche.ShellDependent; /** * Initial shell to validate the login for different user classes. * * Launches appropriate shell based on provide credentials * */ public class LoginShell implements ShellDependent { public static class LoginFailedException extends Exception { private static final long serialVersionUID = 1L; public LoginFailedException(String msg) { super(msg); } } /** * Connection object used to create Statements. This shell doesn't own the * connection; no need to close. */ Connection connection; private Shell loginShell; ShellFactory factory = new ShellFactory(); public LoginShell(Connection connection) { this.connection = connection; } /** * This method is called in unit tests. */ public void setFactory(ShellFactory f) { this.factory = f; } /** * Called by Cliche so this shell can create sub-shells. */ public void cliSetShell(Shell theShell) { this.loginShell = theShell; } @Command public String login(int id, String password) throws Exception { /* * Parses given userIDs * * Students = 1000-1999 * Doctors = 2000-2999 * Nurses = 4000-4999 * Staff = 5000-5999 */ try { if (1000 <= id && id < 2000) { { loginStudent(id, password); } } else if (2000 <= id && id < 3000) { loginDoctor(id, password); } else if (4000 <= id && id < 5000) { loginNurse(id, password); } else if (5000 <= id && id < 6000) { loginStaff(Integer.toString(id), password); } else { return "Invalid id. Not in any user class range."; } } catch (LoginFailedException e) { return e.getMessage(); } return "Back at login shell."; } /** * Validates a student's credentials and launches the studentShell if valid * * @param id * @param password * @throws Exception */ private void loginStudent(int id, String password) throws Exception { String sql = "select 1 from Student where StudentID=? and password=?"; // Create a statement instance that will be sending // your SQL statements to the DBMS try (PreparedStatement stm = connection.prepareStatement(sql)) { stm.setInt(1, id); stm.setString(2, password); ResultSet rs = stm.executeQuery(); if (!rs.next()) { throw new LoginFailedException("Invalid student ID or password"); } } factory.createSubshell(loginShell, "student", new StudentShell(connection, id)).commandLoop(); } /** * Validates a staff member's credentials and launches the staffShell if valid * * @param id * @param password * @throws Exception */ private String loginStaff(String idStr, String password) throws Exception { int id; try { id = Integer.parseInt(idStr); } catch (NumberFormatException ex) { return "Cannot parse id. Enter a number."; } String sql = "select 1 from Staff where staffID=? and password=?"; // Create a statement instance that will be sending // your SQL statements to the DBMS try (PreparedStatement stm = connection.prepareStatement(sql)) { stm.setInt(1, id); stm.setString(2, password); ResultSet rs = stm.executeQuery(); if (!rs.next()) { throw new LoginFailedException("Invalid staff ID or password"); } } factory.createSubshell(loginShell, "staff", new StaffShell(connection, id)).commandLoop(); return ""; } /** * Validates a doctor's credentials and launches the doctorShell if valid * * @param id * @param password * @throws Exception */ private void loginDoctor(int id, String password) throws Exception { String sql = "select 1 from Doctor where doctorID=? and password=?"; // Create a statement instance that will be sending // your SQL statements to the DBMS try (PreparedStatement stm = connection.prepareStatement(sql)) { stm.setInt(1, id); stm.setString(2, password); ResultSet rs = stm.executeQuery(); if (!rs.next()) { throw new LoginFailedException("Invalid doctor ID or password"); } } factory.createSubshell(loginShell, "doctor", new DoctorShell(connection, id)).commandLoop(); } /** * Validates a nurse's credentials and launches the nurseShell if valid * * @param id * @param password * @throws Exception */ private void loginNurse(int id, String password) throws Exception { String sql = "select 1 from Nurse where NurseID=? and password=?"; // Create a statement instance that will be sending // your SQL statements to the DBMS try (PreparedStatement stm = connection.prepareStatement(sql)) { stm.setInt(1, id); stm.setString(2, password); ResultSet rs = stm.executeQuery(); if (!rs.next()) { throw new LoginFailedException("Invalid nurse ID or password"); } } factory.createSubshell(loginShell, "nurse", new NurseShell(connection, id)).commandLoop(); } } <file_sep>package reasonablecare; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Calendar; import asg.cliche.Command; import asg.cliche.Param; /** * Shell containing methods for the student user class * */ public class StudentShell { /** * Connection object used to create Statements. This shell doesn't own the * connection; no need to close. */ final Connection connection; final CommonStatements commonStatements; static Statement stm = null; final int id; final BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); public StudentShell(Connection connection, int id) throws SQLException { this.connection = connection; this.id = id; //constructor to use shared statements commonStatements = new CommonStatements(connection); } //insurance instances to contact insurance and credit card companies private InsuranceCompanySystem insurance = new InsuranceCompanySystem(); private CreditCardSystem creditCard = new CreditCardSystem(); @Command(description = "List all doctor specializations, and doctors that have " + "those specializations.") public Table getDoctors() throws SQLException { Table doctorTable = commonStatements.getDoctors(); return doctorTable; } @Command(description="Prints the number of vaccination appointments you have made. You must make 3 before the end of the semester.") public String checkVaccinations() throws SQLException { java.util.Calendar calendar = Calendar.getInstance(); java.sql.Timestamp now = new java.sql.Timestamp(calendar.getTime().getTime()); String sql = "select count(*) from appointment natural join makesappointment where type='Vaccination' and studentid=? and APPOINTMENTTIME<?"; try(PreparedStatement stm = connection.prepareStatement(sql)) { stm.setInt(1, id); stm.setTimestamp(2, now); ResultSet rs = stm.executeQuery(); if(!rs.next()) { return "Error retrieving vaccination information."; } if(rs.getInt(1)>=3) return "You have had " + rs.getInt(1) + " vaccinations."; else return "You have had " + rs.getInt(1) + " vaccinations. You must make 3 before the end of the semester."; } } /** * View upcoming appointments for the logged in student * * Displays table with Date/Time, Doctor, Appointment Type, and Reason for appointment * @return * @throws SQLException */ @Command(description="view upcoming appointments") public Object checkFutureAppointments() throws SQLException { //Timestamp representing actual current time java.util.Calendar calendar = Calendar.getInstance(); java.sql.Timestamp now = new java.sql.Timestamp(calendar.getTime().getTime()); String sql = "select appointmentid, appointmenttime, doctorname, type, reasonforvisit from " + "(appointment natural join makesappointment natural join doctor)" + "where appointmenttime > ? and studentid = ?"; try (PreparedStatement stm = connection.prepareStatement(sql, new String[] { "AppointmentTime" })) { stm.setTimestamp(1, now); stm.setInt(2, id); ResultSet rs = stm.executeQuery(); Table upcomingAppointments = new Table("AppointmentID","Time/Date", "Doctor", "Type", "Reason"); while (rs.next()) { upcomingAppointments.add(rs.getInt(1), rs.getTimestamp(2), rs.getString(3), rs.getString(4), rs.getString(5)); } return upcomingAppointments; } } /** * View past appointments for the logged in student * * Displays table with Date/Time, Doctor, Appointment Type, and Reason for appointment * @return * @throws SQLException */ @Command(description="View past appointments") public Object checkPastAppointments() throws SQLException { //Timestamp representing actual current time java.util.Calendar calendar = Calendar.getInstance(); java.sql.Timestamp now = new java.sql.Timestamp(calendar.getTime().getTime()); String sql = "select appointmenttime, doctorname, type, reasonforvisit from " + "(appointment natural join makesappointment natural join doctor)" + "where appointmenttime < ? and studentid = ?"; try (PreparedStatement stm = connection.prepareStatement(sql, new String[] { "AppointmentTime" })) { stm.setTimestamp(1, now); stm.setInt(2, id); ResultSet rs = stm.executeQuery(); Table pastAppointments = new Table("Time/Date", "Doctor", "Type", "Reason"); while (rs.next()){ pastAppointments.add(rs.getTimestamp(1), rs.getString(2), rs.getString(3), rs.getString(4)); } return pastAppointments; } } @Command(description = "Delete one of your appointments given its appointmentID") public String deleteAppointment(@Param(name="appointmentID")String appointmentId) throws SQLException { int apptid; try { apptid = Integer.parseInt(appointmentId); } catch (NumberFormatException e) { return "Error: AppointmentId must be a number. Appointment not deleted."; } String sql = "select appointmentid from makesAppointment where studentid=? and appointmentid=?"; try (PreparedStatement statement = connection.prepareStatement(sql)) { statement.setInt(1, id); statement.setInt(2, apptid); // Get records from the Student table try (ResultSet rs = statement.executeQuery()) { if (!rs.next()) return "Error: That is not one of your appointments"; else return commonStatements.deleteAppointment(appointmentId); } } } /** * Allow student to update his or her information * @throws SQLException * @throws IOException */ @Command(description="Update your information") public void updateStudent() throws IOException, SQLException { commonStatements.updatestudentinformation(id); } /** * Interactive method to allow a student to make appointment by being prompted for * the values needed. Invalid input is mostly handled * * @throws Exception */ @Command(description="Interactive way to make an appointment. Prompts for all information" + "needed.") public Object makeAppointmentInteractive() throws Exception { java.sql.Timestamp apptTime; int apptDoc=0,menuSelection=0, cost=0, ccMonth,ccYear; String apptType="", apptReason="", insuranceProvider, insuranceNumber, ccNumber; boolean apptTypeSelected=false, hasInsurance=false, creditCardAccepted=false; //Check that student has insurance information while (!hasInsurance) { if (!checkHasInsurance(id)) { System.out.println("You do not have insurance. \nEnter an option from the menu below:" +"\n1. Provide Insurance Information" +"\n2. Exit System and Log out\n"); try { menuSelection=Integer.parseInt(br.readLine().trim()); if (menuSelection<1 || menuSelection>2) System.out.println("Invalid Selection\n"); else apptTypeSelected=true; } catch (NumberFormatException e) { System.out.println("Invalid Selection\n"); } if (apptTypeSelected){ switch (menuSelection) { case 1: //take insurance info System.out.println("Enter the name of your insurance provider:"); insuranceProvider = br.readLine().trim(); System.out.println("Enter your insurance policy number:"); insuranceNumber = br.readLine().trim(); String updateIns = "UPDATE STUDENT SET HEALTHINSURANCEPROVIDERNAME=?, " + "HEALTHINSURANCEPOLICYNUMBER= ? " + "WHERE STUDENTID=?"; try (PreparedStatement stm = connection.prepareStatement(updateIns)) { stm.setString(1, insuranceProvider); stm.setString(2, insuranceNumber); stm.setInt(3, id); stm.executeUpdate(); } System.out.println("Insurance Information Accepted"); hasInsurance=true; break; default: System.exit(0); }}// end switch+if } else hasInsurance=true; } String specialization=""; int apptReason1=0; //prompt for appointment type and reason (if not physical/vaccination) do { System.out.println("Select Appointment Type" +"\n1. Vaccination" +"\n2. Physical" +"\n3. Office Visit"); try { menuSelection=Integer.parseInt(br.readLine().trim()); if (menuSelection<1 || menuSelection>3) System.out.println("Invalid Selection\n"); else apptTypeSelected=true; } catch (NumberFormatException e) { System.out.println("Invalid Selection\n"); } if (apptTypeSelected){ switch (menuSelection) { case 1: apptType=apptReason="Vaccination"; specialization="General Physician"; break; case 2: apptType=apptReason="Physical"; specialization="General Physician"; break; default: apptType="Office Visit"; System.out.println("Enter the reason of your visit \n1.Diabetes \n2.FluShots \n3.Mental Health " + "\n4.Orthopedics \n5.Physical Therapy \n6.Women's Health\n7.Urinary, Genital Problems " + "\n8.HIV Testing \n9.Ear, Nose, Throat Problems " + "\n10.Heart related Problems " + "\n11.Cancer Surgery"); apptReason1=Integer.parseInt(br.readLine()); switch(apptReason1) { case 1: apptReason="Diabetes"; specialization="Endocrinologist"; break; case 2: apptReason="FluShots"; specialization="General Physician"; break; case 3: apptReason="Mental Health"; specialization="Psychiatrist"; break; case 4: apptReason="Orthopedics"; specialization="Orthopedic Surgeon"; break; case 5: apptReason="Physical Therapy"; specialization="Physical Therapist"; break; case 6: apptReason="Women's Health"; specialization="Gynaceologist"; break; case 7: apptReason="Urinary, Genital Problems"; specialization="Nephrologist"; break; case 8: apptReason="HIV Testing"; specialization="General Physician"; break; case 9: apptReason="Ear, Nose, Throat Problems"; specialization="ENT specialist"; break; case 10: apptReason="Heart related Problems"; specialization="Cardiologist"; break; case 11: apptReason="Cancer Surgery"; specialization="Oncology Surgeon"; break; } }}// end switch+if } while (!apptTypeSelected);//end while String sql = "SELECT doctorname,doctorid FROM doctor where specialization=?"; try (PreparedStatement stm = connection.prepareStatement(sql)) { stm.setString(1, specialization); ResultSet rs = stm.executeQuery(); while (rs.next()){ System.out.println(rs.getInt("doctorid")+" "+rs.getString("doctorname")); } } int ID=0; int flag=0; do{ System.out.println("Select any valid id of the doctor you want to book appointment"); apptDoc=Integer.parseInt(br.readLine()); String sql1 = "SELECT doctorname,doctorid FROM doctor"; try (PreparedStatement stm = connection.prepareStatement(sql1)) { ResultSet rs = stm.executeQuery(); while (rs.next()) { ID=rs.getInt("doctorid"); if(apptDoc==ID) { flag=1; break; } } }//end try if(flag==0) System.out.println("Please choose a valid doctor id"); }while(flag!=1); apptTime = selectDateTime(apptDoc); //fetch insurance information insuranceProvider = getInsuranceProvider(id); insuranceNumber = getInsuranceNumber(id); //TODO allow student to get a free physical each year //get cost of appointment cost = insurance.getCopay(apptType, apptDoc, insuranceProvider, insuranceNumber); if(apptType.equals("Physical") && commonStatements.verifyFreePhysical(id)){ cost = 0; } System.out.println("The copayment for your appointment will be: "+cost); if(cost == 0){ } else if (insurance.getDeductiblePaid(insuranceProvider, insuranceNumber)) { System.out.println("Your deductible has been paid for the year. You will not be billed."); } else { System.out.println("Your deductible has not been paid for the year."); do{ System.out.println("Enter your credit card number:"); ccNumber = br.readLine().trim(); // handle credit card expiration date System.out.println("Enter your the expiration month:"); ccMonth = Integer.parseInt(br.readLine()); System.out.println("Enter your the expiration year:"); ccYear = Integer.parseInt(br.readLine()); if (creditCard.validateCreditCard(ccNumber,ccMonth,ccYear)) { if (creditCard.getPreapproval(ccNumber)) { creditCardAccepted=true; System.out.println("Your credit card was pre-approved."); } else { System.out.println("Your credit card was not pre-approved. You will need to" + "use a different card."); } } else System.out.println("Invalid Credit Card Number"); } while (!creditCardAccepted); } //Make the appointment return commonStatements.makeAppointment(id, apptDoc, apptType, apptReason, apptTime, cost); } /** * Show the available appointment times for a doctor on a given date. Times associated with * scheduled appointments or times in the past are not displayed. * @param doctorID * @param date * @return appointmentTable with Available Times * @throws Exception */ @Command(description="Displays a list of available times for a doctor on a date") public Object showAvailableTimes( @Param(name="DoctorID") String doctorID, @Param(name="date")String date) throws Exception { Object appointmentTable = commonStatements.showAvailableTimes(doctorID, date); return appointmentTable; } @Command(description="Return whether or not you have a free physical for this calendar year. " + "This will return false if you currently have an upcoming physical appointment.") public String verifyFreePhysical() throws Exception{ if(commonStatements.verifyFreePhysical(id)){ return "You have 1 free physical left for this year."; } else{ return "You do not have a free physical this year."; } } /** * Interactive system of prompts to allow a user to select a doctor from the DB. * * Gives the option to show a list of available doctors * * @return selected DoctorID * @throws Exception */ public int selectDoctor() throws Exception { String doctorID; int menuSelection=0; //loops through prompts; for use handling invalid input without exiting while (true) { System.out.println("Select a doctor: " + "\n1. Enter Doctor ID" + "\n2. View List of Doctors" + "\n3. Exit System and Log Out"); try { menuSelection=Integer.parseInt(br.readLine().trim()); if (menuSelection<1 || menuSelection>3) System.out.println("Invalid Selection\n"); } catch (NumberFormatException e) { System.out.println("Invalid Selection\n"); } switch (menuSelection) { //Allow user to enter a doctorID case 1: System.out.println("Enter Doctor ID: "); doctorID=br.readLine().trim(); if (!commonStatements.validateDoctorID(doctorID)) { System.out.println("Invalid Doctor ID\n"); break; } else return Integer.parseInt(doctorID); //Allow user to view a list of doctors and then enter a doctorID case 2: System.out.println(getDoctors()); System.out.println("Enter DoctorID from List: "); doctorID=br.readLine().trim(); if (!commonStatements.validateDoctorID(doctorID)) { System.out.println("Invalid Doctor ID\n"); break; } else return Integer.parseInt(doctorID); default: System.exit(0); }// end of switch }//end while } @Command(description="Find a specialist to handle your care.") public void findSpecialist() throws IOException, SQLException { try(CommonStatements common = new CommonStatements(connection)) { common.FindSpecialist(); } } /** * Interactive system of prompts to allow a student to select a valid * time and date for an appointment with a given doctor. * * @param doctorID * @return timestamp showing the date and time of the appointment * @throws Exception */ public java.sql.Timestamp selectDateTime(int doctorID) throws Exception { String date=""; java.sql.Date apptDate; @SuppressWarnings("unused") java.sql.Time apptTime; java.util.Calendar calendar = Calendar.getInstance(); java.sql.Timestamp now = new java.sql.Timestamp(calendar.getTime().getTime()); int menuSelection=0; boolean dateSelected=false, runSelectionLoop=true; //loops through prompts; for use handling invalid input without exiting do{ System.out.println("Enter the date for the appointment (YYYY-MM-DD): \n"); date=(br.readLine().trim()); try{ apptDate = java.sql.Date.valueOf(date); dateSelected = true; if(apptDate.before(now)) { System.out.println("Appointment time cannot be in the past"); } } catch (IllegalArgumentException e){ System.out.println("Invalid Date Format: Must be YYYY-MM-DD"); } if (dateSelected) { System.out.println(showAvailableTimes(Integer.toString(doctorID),date)); //Allow user to select a time do { System.out.println("Select an option: " +"\n1. Enter an available time from the list (HH:MM:SS)" +"\n2. Enter a different date" +"\n3. Exit system and log out\n"); try { menuSelection=Integer.parseInt(br.readLine().trim()); if (menuSelection<1 || menuSelection>3) System.out.println("Invalid Selection\n"); else runSelectionLoop=false; } catch (NumberFormatException e) { System.out.println("Invalid Selection\n"); } if (!runSelectionLoop) { switch (menuSelection) { //Allow user to enter a time and validate it case 1: System.out.println("Enter an available time from the list (HH:MM:SS):"); String time = br.readLine().trim(); try{ apptTime = java.sql.Time.valueOf(time); } catch (IllegalArgumentException e){ System.out.println("Invalid Time Format: Must be HH:MM:SS"); } //get available times ArrayList<java.sql.Timestamp> apptTimes = getAvailableTimes(doctorID,date); java.sql.Timestamp apptTimestamp = java.sql.Timestamp.valueOf(date+" "+time); if (apptTimes.contains(apptTimestamp)) { if (apptTimestamp.after(now)) return apptTimestamp; else { System.out.println("Appointment time cannot be in the past"); runSelectionLoop=true; } } else { System.out.println("Time not available for appointments"); runSelectionLoop=true; } break; //Go back through the previous menus case 2: runSelectionLoop=false; dateSelected=false; break; default: System.exit(0); } }//end if }while (runSelectionLoop);//end while selection }//end if date }while (!dateSelected); return null; //if error } /** * Method to return the avaialable appointment times for a given doctor * on a given date as an ArrayList * * @param doctorID * @param date * @return ArrayList<java.sql.Timestamp> of available times for a doctor * @throws Exception */ public ArrayList<java.sql.Timestamp> getAvailableTimes(int doctorID, String date) throws Exception { java.sql.Date apptDate = java.sql.Date.valueOf(date); //set a string equal to the day of week for the date String dayName = String.format("%tA", apptDate); //import result set into an ArrayList ArrayList<java.sql.Timestamp> scheduledAppointments = new ArrayList<java.sql.Timestamp>(); ArrayList<java.sql.Timestamp> availableAppointments = new ArrayList<java.sql.Timestamp>(); //return appointments for a specific doctor on a specific date String sql="select a.appointmenttime from (appointment a natural join makesappointment ma) " + "where ma.doctorID= ? and to_char(a.appointmenttime, 'YYYY-MM-DD') = ?"; try (PreparedStatement stm = connection.prepareStatement(sql, new String[] { "AppointmentTime" })) { stm.setInt(1, doctorID); stm.setString(2, date); ResultSet rs = stm.executeQuery(); while (rs.next()) { scheduledAppointments.add(rs.getTimestamp(1)); } //Timestamp representing actual current time java.util.Calendar calendar = Calendar.getInstance(); java.sql.Timestamp now = new java.sql.Timestamp(calendar.getTime().getTime()); //Build AppointmentTable java.sql.Timestamp currentTime; if (dayName.equals("Sunday")); //system is closed on Sundays. else if (dayName.equals("Saturday")) //open 10-2 { for (int hour=10; hour<14; hour++) { for (int minute=0; minute<31; minute+=30) { currentTime = java.sql.Timestamp.valueOf(date+" "+hour+":"+minute+":00"); if (!scheduledAppointments.contains(currentTime) && now.before(currentTime)) availableAppointments.add(currentTime); } } } else //weekday - open 8-5 { for (int hour=8; hour<17; hour++) { for (int minute=0; minute<31; minute+=30) { currentTime = java.sql.Timestamp.valueOf(date+" "+hour+":"+minute+":00"); if (!scheduledAppointments.contains(currentTime)) availableAppointments.add(currentTime); } } } } return availableAppointments; } /** * Check if a student has insurance * @param studentID * @return true or false that the student has insurance */ public boolean checkHasInsurance(int studentID) { String sql = "select healthinsuranceprovidername,healthinsurancepolicynumber " + "from student where studentID=?"; try (PreparedStatement stm = connection.prepareStatement(sql)) { stm.setInt(1,studentID); ResultSet rs = stm.executeQuery(); rs.next(); if (rs.getString(1)==null || rs.getString(2)==null) return false; else return true; } catch (SQLException e) { // TODO Auto-generated catch block return false; } } /** * Check return insuranceProvider of student * @param studentID * @return */ public String getInsuranceProvider(int studentID) { String sql = "select healthinsuranceprovidername from student where studentID=?"; try (PreparedStatement stm = connection.prepareStatement(sql)) { stm.setInt(1,studentID); ResultSet rs = stm.executeQuery(); rs.next(); return rs.getString(1); } catch (SQLException e) { // TODO Auto-generated catch block return null; } } /** * Get Insurance Policy Number from Student * @param studentID * @return */ public String getInsuranceNumber(int studentID) { String sql = "select healthinsurancepolicynumber from student where studentID=?"; try (PreparedStatement stm = connection.prepareStatement(sql)) { stm.setInt(1,studentID); ResultSet rs = stm.executeQuery(); rs.next(); return rs.getString(1); } catch (SQLException e) { // TODO Auto-generated catch block return null; } } static void close(PreparedStatement statement) { if(statement != null) { try { statement.close(); } catch(Throwable whatever) {} } } } <file_sep>ReasonableCare ============== The Reasonable Care management system for CSC 540 Team Members: gshah, mpsenn, glsetlif, mdnevill Reasonable Care provides a means for students, doctors, and nurses to schedule doctor and receive medical care. It provides an interface for students to schedule appointments, search for doctors, and update their personal information. Doctors may view their upcoming and past appointments, and nurses may help provide on-the-phone consultations for students, as well as schedule appointments if necessary. #Installation #Usage ##Managing User Accounts ###Register a new student with basic information Staff users may register new students with basic information. This essentially creates a new student account, and they student may then update their own information or staff can do this for them. ReasonableCare/staff> create-student <name> <password> <starting date> ###Take health insurance information and update student information Staff may update a student's information, or a student may do this himself. Upon issuing the update command, users are prompted for which criteria they wish to update, i.e. health insurance information. ####Staff ReasonableCare/staff> update-student <student ID> Enter the attribute to be updated: 1.Name 2.HealthInsurance Provider Name 3.HealthInsurance Provider Number 4.Password 5.Starting semester ####Student ReasonableCare/student> update-student Enter the attribute to be updated: 1.Name 2.HealthInsurance Provider Name 3.HealthInsurance Provider Number 4.Password 5.Starting semester ###Maintain and update doctor information Staff have the ability to create new doctor accounts and update doctor information, including name, phone number, and area of specialization. ####Create a new doctor account ReasonableCare/staff> create-doctor <name> <password> <phone number> <specialization> ####Update existing doctor account ReasonableCare/staff> update-doctor <doctor ID> Enter the attribute to be updated: 1.Name 2.Password 3.Specialization 4.Phone Number ###Check student records for holds A student must receive three vaccinations by the end of their first semester, otherwise their account with the health center is in a hold. It is possible to check which students have not received their mandatory vaccinations in the Staff Shell with the check vaccinations command, which will print a list of all students who are in violation. ReasonableCare/staff> check-vaccinations +------------+--------------+-----------------------+------------------------+ | Student ID | Student Name | Starting Semester | Number of Vaccinations | +------------+--------------+-----------------------+------------------------+ | 1005 | MDaniel | 2012-08-01 00:00:00.0 | 0 | | 1052 | Jim | 2013-01-04 00:00:00.0 | 0 | | 1082 | Gati | 2013-03-12 00:00:00.0 | 0 | ... Students may also check their own vaccinatino records through the Student Shell ReasonableCare/student> check-vaccinations You have had 0 vaccinations. ##Making an Appointment with a Doctor Students can make appointments through the Student shell. Upon issuing the make appointment command, students are prompted for the relevant information for the appointment, including appointment type. ReasonableCare/sudent> make-appointment-interactive Select Appointment Type 1. Vaccination 2. Physical 3. Office Visit ###Scheduling an office visit To schedule an office visit, select the appopriate prompt response. You will then be shown doctors who specialize in that field and a list of availble times for a date that you choose. After successfully choosing a doctor and appointment time, enter relevant payment information if you have not met your deductible. Enter the reason of your visit 1.Diabetes 2.FluShots 3.Mental Health 4.Orthopedics 5.Physical Therapy 6.Women's Health 7.Urinary, Genital Problems 8.HIV Testing 9.Ear, Nose, Throat Problems 10.Heart related Problems 3 2004 Dr. Rob 2108 Dr. Harry Select the id of the doctor you want to book appointment with 2004 Enter the date for the appointment (YYYY-MM-DD): 2014-04-12 +-------------------------------------------+ | Available Appointment Times on 2014-04-12 | +-------------------------------------------+ | 2014-04-12 13:30:00.0 | +-------------------------------------------+ Select an option: 1. Enter an available time from the list (HH:MM:SS) 2. Enter a different date 3. Exit system and log out 1 Enter an available time from the list (HH:MM:SS): 13:30:00 The copayment for your appointment will be: 20 Your deductible has not been paid for the year. Enter your credit card number: 12345 Enter your the expiration month: 8 Enter your the expiration year: 2014 Your credit card was pre-approved. Created new Appointment with id = 3220 ###Checking past appointments Students can view their past appointments in the Student Shell ReasonableCare/student> check-past-appointments +-----------------------+-----------+--------------+--------------+ | Time/Date | Doctor | Type | Reason | +-----------------------+-----------+--------------+--------------+ | 2014-04-09 16:30:00.0 | Dr. Harry | Office Visit | Stomach Ache | +-----------------------+-----------+--------------+--------------+ ###Showing and canceling future appointments A student can view his or her future appointments using the Student Shell. ReasonableCare/student> check-future-appointments +---------------+-----------------------+---------+--------------+---------------+ | AppointmentID | Time/Date | Doctor | Type | Reason | +---------------+-----------------------+---------+--------------+---------------+ | 3241 | 2014-04-14 16:30:00.0 | Dr. Rob | Office Visit | Mental Health | +---------------+-----------------------+---------+--------------+---------------+ Students can also cancel their own appointments using the appointment ID's. ReasonableCare/student> delete-appointment 3220 Deleted appointment between Dr. Rob and <NAME> ##Doctors' Schedules Doctors are able to view inforamtion about their appointments from the Doctor Shell. ReasonableCare/doctor> check-future-appointments +---------+------------------+-----------------------+--------------+---------------+-------+ | Appt ID | Student | Date and Time | Appt Type | Appt Reason | Notes | +---------+------------------+-----------------------+--------------+---------------+-------+ | 3220 | <NAME> | 2014-04-12 13:30:00.0 | Office Visit | Mental Health | null | +---------+------------------+-----------------------+--------------+---------------+-------+ ##Consultations
96d22fae6f3f7bb018ddca7cdd51f3f0a0134923
[ "Markdown", "Java", "SQL" ]
7
Java
gatishah/ReasonableCare
e2b7ed47b6b34eb13250156b08e8bd7e9f6fd80c
4115d5b55ec49a8e988af809ec2d3d9103897a6f
refs/heads/master
<repo_name>HermanHeringa/Peter-Pannekoek<file_sep>/Central Unit/cu0.1.py import socket import threading import time UDP_IP = "192.168.11.193" UDP_HOSTPORT = 1337 address_list = [] HOSTADDR = (UDP_IP, UDP_HOSTPORT) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(HOSTADDR) sock.settimeout(0) def get_millis(): return round(time.time() * 1000) def send_msg(msg, address): print(f"[SENT]{msg},{address}") sock.sendto(msg.encode(), address) def handle_bot(data, address): timeout_counter = 0 start_time = get_millis() while True: #Every 5 seconds an alive message is sent to the bot to check if it's still there if get_millis() - start_time > 5000: print(timeout_counter) send_msg("a", address) start_time = get_millis() timeout_counter += 1 try: data= sock.recv(1024) except: data = -1 if data == b"a": timeout_counter = 0 print("Alive") def start(): print(f"[RUNNING] Server is running on {HOSTADDR}") while True: try: data,addr = sock.recvfrom(1024) except: data = -1 addr = -1 if data != -1: if data == b"w": if addr in address_list: pass else: address_list.append(addr) thread = threading.Thread(target=handle_bot, args=(data, addr)) thread.start() print(f"[TOTAL CONNECTIONS] {threading.activeCount() - 1}") print(address_list) print("[STARTING] Server is starting up...") start() <file_sep>/Central Unit/bot.py from controller import Robot, Motor, Compass import math import socket TIME_STEP = 16 MAX_SPEED = 1 UDP_IP = "192.168.11.193" UDP_PORT = 4210 UDP_HOSTPORT = 1337 ADDR = (UDP_IP,UDP_PORT) HOSTADDR = (UDP_IP, UDP_HOSTPORT) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(ADDR) sock.settimeout(0) # create the Robot instance. robot = Robot() compass = Compass("compass") compass.enable(250) def get_bearing_in_degrees(): north = compass.getValues() rad = math.atan2(north[0], north[2]) bearing = (rad - 1.5708) / math.pi * 180.0 if (bearing < 0.0): bearing = bearing + 360.0 return bearing def run_motor(left, right): leftMotor = robot.getDevice('LeftMotor') rightMotor = robot.getDevice('RightMotor') # get a handler to the motors and set target position to infinity (speed control) leftMotor.setPosition(float('inf')) rightMotor.setPosition(float('inf')) #set up the motor speeds at 10% of the MAX_SPEED. leftMotor.setVelocity(left * MAX_SPEED) rightMotor.setVelocity(right * MAX_SPEED) def forward(): run_motor(0.5,0.5) def backward(): run_motor(-0.5,-0.5) def left(): run_motor(-0.5,0.5) def right(): run_motor(0.5,-0.5) def stop(): run_motor(0.0,0.0) while robot.step(TIME_STEP) != -1: heading = get_bearing_in_degrees() print(heading) try: data,addr = sock.recvfrom(1024) except: data = -1 addr = -1 if data != -1: print(data) print(addr) if data == b"f": forward() elif data == b"b": backward() elif data == b"l": left() elif data == b"r": right() elif data == b"s": stop() elif data == b"h": sock.sendto(str(heading).encode(), HOSTADDR) pass data = -1 pass <file_sep>/Central Unit/1.0/server1.0.py import socket import re import threading import base64 from hashlib import sha1 HEADER = 1024 PORT = 1337 HOST = "192.168.11.193" #socket.gethostbyname(socket.gethostname()) ADDR = (HOST, PORT) FORMAT = 'utf-8' RECEIVED_MESSAGE = "ACK" DISCONNECT_MESSAGE = "CLOSE" GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" websocket_answer = ( 'HTTP/1.1 101 Switching Protocols', 'Upgrade: Websocket', 'Connection: upgrade', 'Sec-WebSocket-Accept: {key}\r\n\r\n', ) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR) def close_connection(client): client.close() def send_msg(client, msg): client.send(msg.encode(FORMAT)) print(msg) def do_handshake(client): msg = client.recv(HEADER).decode(FORMAT) print(f"[HANDSHAKE] {msg}") key = (re.search('Sec-WebSocket-Key:\s+(.*?)[\n\r]+', msg) .groups()[0] .strip()) response_key = base64.b64encode(sha1((key + GUID).encode(FORMAT)).digest()) response = '\r\n'.join(websocket_answer).format(key=response_key.decode(FORMAT)) print(response) send_msg(client, response) send_msg(client, "test") def handle_client(client, address): print(f"[NEW CONNECTION] Client connected on: {address}") do_handshake(client) connected = True while connected: send_msg(client, "aaaa") msg = client.recv(HEADER) if msg != -1: print(type(msg)) print(f"[{address}] {msg}") client.send(msg) #send_msg(client, RECEIVED_MESSAGE) print(f"[CLOSING] Closing connection with client on {address}") #send_msg(client, DISCONNECT_MESSAGE) client.close() def start(): server.listen() print(f"[RUNNING] Server is running on {HOST}:{PORT}") while True: client, address = server.accept() thread = threading.Thread(target=handle_client, args=(client, address)) thread.start() print(f"[TOTAL CONNECTIONS] {threading.activeCount() - 1}") print("[STARTING] Server is starting up") start()<file_sep>/Sim/controllers/RobotController2/RobotController2.py from controller import Robot, Motor, Compass, GPS import math import socket TIME_STEP = 16 MAX_SPEED = 1 UDP_IP = "192.168.11.193" UDP_PORT = 4211 UDP_HOSTPORT = 1337 ADDR = (UDP_IP,UDP_PORT) HOSTADDR = (UDP_IP, UDP_HOSTPORT) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(ADDR) sock.settimeout(0) # create the Robot instance. robot = Robot() compass = Compass("compass") gps = GPS("gps") compass.enable(1) gps.enable(1) def send_msg(message): print(f"{message} r2") sock.sendto(str(message).encode(), HOSTADDR) def get_bearing_in_degrees(): north = compass.getValues() rad = math.atan2(north[0], north[2]) bearing = (rad - 1.5708) / math.pi * 180.0 if (bearing < 0.0): bearing = bearing + 360.0 return bearing def get_pos(): xyz = gps.getValues() #Get XYZ Values from GPS Module xyz.pop(1) #Remove Y value because it is not needed xyz = [ round(elem, 2) for elem in xyz] return xyz #Return X and Z values def run_motor(left, right): leftMotor = robot.getDevice('LeftMotor') rightMotor = robot.getDevice('RightMotor') # get a handler to the motors and set target position to infinity (speed control) leftMotor.setPosition(float('inf')) rightMotor.setPosition(float('inf')) #set up the motor speeds at 10% of the MAX_SPEED. leftMotor.setVelocity(left * MAX_SPEED) rightMotor.setVelocity(right * MAX_SPEED) #Functions defining movement and speed def forward(): run_motor(0.1,0.1) def backward(): run_motor(-0.1,-0.1) def left(): run_motor(-0.1,0.1) def right(): run_motor(0.1,-0.1) def stop(): run_motor(0.0,0.0) #Function to turn into right direction def turn(degrees): pass def start(): send_msg("w") while robot.step(TIME_STEP) != -1: try: data,addr = sock.recvfrom(1024) except: data = -1 addr = -1 if data != -1: print(data) print(addr) if data == b"a": print("aaa") send_msg("a") elif data == b"f": send_msg(-1) forward() elif data == b"b": send_msg(-1) backward() elif data == b"l": send_msg(-1) left() elif data == b"r": send_msg(-1) right() elif data == b"s": send_msg(-1) stop() elif data == b"h": heading = get_bearing_in_degrees() send_msg(heading) elif data == b"p": pos = get_pos() send_msg(pos) data = -1 #Setup heading = get_bearing_in_degrees() pos = get_pos() start() <file_sep>/robotConnectionCode/robotConnectionCode.ino #include <ESP8266WiFi.h> #include <WiFiUdp.h> #define HOST_SSID "testtest" #define HOST_PASS "<PASSWORD>" #define MY_SSID "ESP-14" #define MY_PASS "<PASSWORD>" #define UDP_PORT 4210 #define HOST_IP "192.168.137.1" WiFiUDP UDP; char packet[255]; char reply[] = "Packet received!"; void setup() { // Connect to host wifi network Serial.begin(9600); WiFi.begin(HOST_SSID, HOST_PASS); Serial.print("Connecting"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.print("Connected, IP address: "); Serial.println(WiFi.localIP()); // Setup network for beacons to track boolean fakeNetwork = WiFi.softAP(MY_SSID, MY_PASS); if (fakeNetwork) { Serial.println("Network created."); } else { Serial.println("Network creation failed"); } // Setup UDP UDP.begin(UDP_PORT); Serial.print("Listening on UDP port "); Serial.println(UDP_PORT); } void loop() { int packetSize = UDP.parsePacket(); if (packetSize) { Serial.print("Received packet! Size: "); Serial.println(packetSize); int len = UDP.read(packet, 255); if (len > 0) { packet[len] = '\0'; } Serial.print("Packet received: "); Serial.println(packet); } // driving code here } <file_sep>/Central Unit/cu.py import socket UDP_IP = "192.168.11.193" UDP_PORT = 4210 UDP_PORT2 = 4211 UDP_HOSTPORT = 1337 ADDR = (UDP_IP, UDP_PORT) ADDR2 = (UDP_IP,UDP_PORT2) HOSTADDR = (UDP_IP, UDP_HOSTPORT) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(HOSTADDR) def control(msg, address): sock.sendto(msg, address) try: data,addr = sock.recvfrom(1024) except: data = -1 addr = -1 print(data) print(addr) data = -1 addr = -1 while True: message = input("command: ").encode() control(message, ADDR) message = input("command2: ").encode() control(message, ADDR2)<file_sep>/Sim/controllers/test/testGyro.py from controller import Robot, Motor, Compass import math TIME_STEP = 16 MAX_SPEED = 1 # create the Robot instance. robot = Robot() compass = Compass("compass") compass.enable(250) # get a handler to the motors and set target position to infinity (speed control) leftMotor = robot.getDevice('LeftMotor') rightMotor = robot.getDevice('RightMotor') leftMotor.setPosition(float('inf')) rightMotor.setPosition(float('inf')) # set up the motor speeds at 10% of the MAX_SPEED. leftMotor.setVelocity(0.05 * MAX_SPEED) rightMotor.setVelocity(0.01 * MAX_SPEED) def get_bearing_in_degrees(): north = compass.getValues() rad = math.atan2(north[0], north[2]) bearing = (rad - 1.5708) / math.pi * 180.0 if (bearing < 0.0): bearing = bearing + 360.0 return bearing while robot.step(TIME_STEP) != -1: print(get_bearing_in_degrees()) pass<file_sep>/beaconCode/beaconCode.ino #include <ESP8266WiFi.h> #include <WiFiUdp.h> #define HOST_SSID "testtest" #define HOST_PASS "<PASSWORD>" #define DRONE_ID "ESP-" #define UDP_PORT 4210 WiFiUDP UDP; char packet[255]; char reply[255]; char buff[5]; void setup() { // put your setup code here, to run once: Serial.begin(9600); delay(500); WiFi.begin(HOST_SSID, HOST_PASS); Serial.print("\nConnecting"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.print("Connected, IP address: "); Serial.println(WiFi.localIP()); UDP.begin(UDP_PORT); Serial.print("Listening on UDP port "); Serial.println(UDP_PORT); } void loop() { int n = WiFi.scanNetworks(); for (int i = 0; i < n; i++) { if (strstr(WiFi.SSID(i).c_str(), DRONE_ID)) { strcpy(reply, WiFi.SSID(i).c_str()); strcat(reply, " ("); strcat(reply, itoa(WiFi.RSSI(i), buff, 10)); strcat(reply, "dBm)"); UDP.beginPacket(UDP.remoteIP(), UDP.remotePort()); UDP.write(reply); UDP.endPacket(); } } } <file_sep>/Central Unit/TestShizzle/ESPWebsockets/ESPWebsockets.ino /* Esp8266 Websockets Client This sketch: 1. Connects to a WiFi network 2. Connects to a Websockets server 3. Sends the websockets server a message ("Hello Server") 4. Prints all incoming messages while the connection is open Hardware: For this sketch you only need an ESP8266 board. Created 15/02/2019 By <NAME> https://github.com/gilmaimon/ArduinoWebsockets */ #include <ArduinoWebsockets.h> #include <ESP8266WiFi.h> const char* ssid = "SSIDHERE"; //Enter SSID const char* password = "<PASSWORD>"; //Enter Password const char* websockets_server_host = "192.168.11.193"; //Enter server adress const uint16_t websockets_server_port = 1337; // Enter server port using namespace websockets; WebsocketsClient client; void onMessageCallback(WebsocketsMessage message) { Serial.print("Got Message: "); Serial.println(message.data()); } void onEventsCallback(WebsocketsEvent event, String data) { if (event == WebsocketsEvent::ConnectionOpened) { Serial.println("Connnection Opened"); } else if (event == WebsocketsEvent::ConnectionClosed) { Serial.println("Connnection Closed"); } else if (event == WebsocketsEvent::GotPing) { Serial.println("Got a Ping!"); } else if (event == WebsocketsEvent::GotPong) { Serial.println("Got a Pong!"); } } void setup() { Serial.begin(115200); Serial.println(); // run callback when messages are received client.onMessage(onMessageCallback); // run callback when events are occuring client.onEvent(onEventsCallback); // Connect to wifi WiFi.begin(ssid, password); // Wait some time to connect to wifi for (int i = 0; i < 10 && WiFi.status() != WL_CONNECTED; i++) { Serial.print("."); delay(1000); } // Check if connected to wifi if (WiFi.status() != WL_CONNECTED) { Serial.println("No Wifi!"); return; } Serial.println("Connected to Wifi, Connecting to server."); // try to connect to Websockets server bool connected = client.connect(websockets_server_host, websockets_server_port, "/"); if (connected) { Serial.println("Connected!"); client.send("Hello Server"); } else { Serial.println("Not Connected!"); } } void loop() { // let the websockets client check for incoming messages client.poll(); client.send("TEST"); delay(500); client.send("01234567890123456789"); } <file_sep>/Sim/controllers/test/test.py from controller import Robot, Motor, Compass import math TIME_STEP = 16 MAX_SPEED = 1 # create the Robot instance. robot = Robot() # get a handler to the motors and set target position to infinity (speed control) leftMotor = robot.getDevice('LeftMotor') rightMotor = robot.getDevice('RightMotor') leftMotor.setPosition(float('inf')) rightMotor.setPosition(float('inf')) # set up the motor speeds at 10% of the MAX_SPEED. leftMotor.setVelocity(0.05 * MAX_SPEED) rightMotor.setVelocity(0.01 * MAX_SPEED) while robot.step(TIME_STEP) != -1: pass<file_sep>/robotCode/robot/robot.ino #include <Wire.h> #include <ESP8266WiFi.h> #include <WiFiUdp.h> #include <Adafruit_Sensor.h> #include <Adafruit_HMC5883_U.h> #define HOST_SSID "testtest" #define HOST_PASS "<PASSWORD>" #define MY_SSID "ESP0-4" #define MY_PASS "<PASSWORD>" #define UDP_PORT 4210 //magnetometer Adafruit_HMC5883_Unified mag = Adafruit_HMC5883_Unified(12345); //motor 1 int motorOneReverse = 0; //D3 int motorOneForward = 12; //D6 int motorOneSpeed = 13; //D7 //motor 2 int motorTwoReverse = 14; //D5 int motorTwoForward = 12; //D6 int motorTwoSpeed = 13; //D7 WiFiUDP UDP; char packet[255]; char reply[] = "Packet received!"; void setup() { pinMode(motorOneReverse, OUTPUT); pinMode(motorOneForward , OUTPUT); pinMode(motorOneSpeed , OUTPUT); pinMode(motorTwoReverse, OUTPUT); pinMode(motorTwoForward , OUTPUT); pinMode(motorTwoSpeed , OUTPUT); // Connect to host wifi network Serial.begin(9600); WiFi.begin(HOST_SSID, HOST_PASS); Serial.print("Connecting"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.print("Connected, IP address: "); Serial.println(WiFi.localIP()); // Setup network for beacons to track boolean fakeNetwork = WiFi.softAP(MY_SSID, MY_PASS); if (fakeNetwork) { Serial.println("Network created."); } else { Serial.println("Network creation failed"); } // Setup UDP UDP.begin(UDP_PORT); Serial.print("Listening on UDP port "); Serial.println(UDP_PORT); // Setup magnetometer if (!mag.begin()) { /* There was a problem detecting the HMC5883 ... check your connections */ Serial.println("Ooops, no HMC5883 detected ... Check your wiring!"); while (1); } } void loop() { int packetSize = UDP.parsePacket(); if (packetSize) { Serial.print("Received packet! Size: "); Serial.println(packetSize); int len = UDP.read(packet, 255); if (len > 0) { packet[len] = '\0'; } Serial.print("Packet received: "); Serial.println(packet); /*String stringPacket(packet); set_speed(255); if (stringPacket == "f") { move_forward(); Serial.println("forward"); } else if (stringPacket == "b") { move_back(); Serial.println("back"); } else if (stringPacket == "r") { move_right(); Serial.println("right"); } else if (stringPacket == "l") { Serial.println("left"); move_left(); } else if (stringPacket == "s") { Serial.println("stop"); motor_off(); }*/ packetHandler(packet); } } //Packets zijn een relatieve direction (1 tot 3 cijfers), gevolgd door een plat streepje (-), gevolgd door een snelheid (1 tot 3 cijfers), met daarna een terminating zero. void packetHandler (char input[255]) { int temp; int i; char direction[4]; for (i = 0; input[i] != '-'; i++) { direction[i] = input[i]; temp = i + 1; } direction[temp] = '\0'; Serial.print("Direction: "); Serial.println(direction); char speed[4]; for (i = 0; input[i + temp + 1] != '\0'; i++) { speed[i] = input[i + temp + 1]; } speed[i] = '\0'; Serial.print("Speed: "); Serial.println(speed); temp = 0; int iDirection = atoi(direction); int iSpeed = atoi(speed); if (iDirection != 0) { turn(iDirection); } set_speed(iSpeed); move_forward(); } void turn(int direction) { int startAngle = getAngle(); int currentAngle = startAngle; set_speed(255); while (currentAngle != ((startAngle + direction) % 360)) { Serial.print("current angle: "); Serial.println(currentAngle); Serial.print("target angle: "); Serial.println((startAngle + direction) % 360); if (currentAngle > ((currentAngle + direction) % 360)) { move_left(); } else { move_right(); } currentAngle = getAngle(); } motor_off(); } int getAngle() { sensors_event_t event; mag.getEvent(&event); float heading = atan2(event.magnetic.y, event.magnetic.x); if (heading < 0) { heading += 2 * PI; } if (heading > 2 * PI) { heading -= 2 * PI; } float headingDegrees = heading * 180 / M_PI; return round(headingDegrees); } void set_speed(int Speed) { analogWrite(motorOneSpeed, Speed); analogWrite(motorTwoSpeed, Speed); } void move_forward() { digitalWrite(motorOneReverse, LOW); digitalWrite(motorOneForward , HIGH); digitalWrite(motorTwoReverse, LOW); digitalWrite(motorTwoForward , HIGH); } void move_back() { digitalWrite(motorOneReverse, HIGH); digitalWrite(motorOneForward , LOW); digitalWrite(motorTwoReverse, HIGH); digitalWrite(motorTwoForward , LOW); } void motor_off() { digitalWrite(motorOneReverse, LOW); digitalWrite(motorOneForward , LOW); digitalWrite(motorTwoReverse, LOW); digitalWrite(motorTwoForward , LOW); } void move_right() { digitalWrite(motorOneReverse, LOW); digitalWrite(motorOneForward , HIGH); digitalWrite(motorTwoReverse, HIGH); digitalWrite(motorTwoForward , LOW); } void move_left() { digitalWrite(motorOneReverse, HIGH); digitalWrite(motorOneForward , LOW); digitalWrite(motorTwoReverse, LOW); digitalWrite(motorTwoForward , HIGH); } <file_sep>/AS Cam/cr.py import cv2 import numpy as np cam = cv2.VideoCapture(1) img = cam.read() #img = cv2.imread("aa.png") hsv = cv2.cvtColor(img[1], cv2.COLOR_BGR2HSV) #purple #lower_range = np.array([40, 70, 70]) #upper_range = np.array([180,255,255]) #grey #lower_range = np.array([110,50,50]) #upper_range = np.array([130,255,255]) #orange #lower_range = np.array([10,100,20]) #upper_range = np.array([25,255,255]) #yellow #lower_range = np.array([20,100,100]) #upper_range = np.array([30,255,255]) mask = cv2.inRange(hsv, lower_range, upper_range) cv2.imshow("Image", img[1]) cv2.imshow("Mask", mask) cv2.waitKey(0) cv2.destroyAllWindows()<file_sep>/Central Unit/1.0/client1.0.py import socket HEADER = 64 PORT = 1337 SERVER = "192.168.11.193" ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "CLOSE" websocket_answer = ( 'HTTP/1.1 101 Switching Protocols', 'Upgrade: Websocket', 'Connection: upgrade', 'Sec-WebSocket-Accept: {key}\r\n\r\n', ) handshake_msg = ( 'GET / HTTP/1.1\n' 'Host: 192.168.11.193\n' 'Sec-WebSocket-Key: <KEY>' 'Upgrade: websocket\n' 'Connection: Upgrade\n' 'Sec-WebSocket-Version: 13\n' 'User-Agent: TinyWebsockets Client\n' 'Origin: https://github.com/gilmaimon/TinyWebsockets\n' ) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(ADDR) def send(msg): message = msg.encode(FORMAT) client.send(message) print(handshake_msg) send(handshake_msg) print(client.recv(2048).decode(FORMAT)) send("ROBIN IS DIK") print(client.recv(2048).decode(FORMAT)) send("THOM HEEFT EEN GROOTHOOFD") print(client.recv(2048).decode(FORMAT)) send("JAAPIE IS EEN HACKER") print(client.recv(2048).decode(FORMAT)) send("MICKEY MOUSE") print(client.recv(2048).decode(FORMAT)) client.close()
a21b45dae8b81542999b93994f56a0451e3f89d3
[ "Python", "C++" ]
13
Python
HermanHeringa/Peter-Pannekoek
a3ec23b18e71499ebb6a906b68ca4c9a9486e376
39e01d0eaa92c71e6da356ea72e721c3f218182f
refs/heads/master
<file_sep><!DOCTYPE HTML> <html> <head> <title>Starting WoT </title> </head> <body> <header class="top"> <h1><a href="Encyclopedia-Home.html"><img class="large"src="Images/WoT%20logo.png" alt="Missing picture \o/" width=300px></a></h1> </header> <ul class="navl"> <li class="dropdown"> <a class="anav" href="Encyclopedia-Home.html">Home</a> </li> <li class="dropdown"> <a class="anav" href="javascript:void(0)" class="dropbtn">Tanks</a> <div class="dropdown-content"> <a href="Encyclopedie-Tanks.html">Tanks</a> <a href="Encyclopedie-Light_tanks.html">Light Tanks</a> <a href="Encyclopedie-Medium_tanks.html">Medium Tanks</a> <a href="Encyclopedie-Heavy_tanks.html">Heavy Tanks</a> <a href="Encyclopedie-Tank_destroyers.html">Tank Destroyers</a> <a href="Encyclopedie-Self-propelled_gun.html">Self-propelled Gun</a> <a href="Encyclopedie-Premium_tanks.html">Premium Tank</a> </div> </li> <li class="dropdown"> <a class="anav" href="javascript:void(0)" class="dropbtn">Economy</a> <div class="dropdown-content"> <a href="Encyclopedie-Credits.html">Credits</a> <a href="Encyclopedie-Gold.html">Gold</a> <a href="Encyclopedia-Experience.html">Experience</a> <a href="Encyclopedie-garage.html">Garage</a> <a href="Encyclopedie-Ammunition.html">Ammunition</a> <a href="Encyclopedie-Missions.html">Missions</a> <a href="Encyclopedie-Research.html">Research</a> <a href="Encyclopedie-Premium_tanks.html">Premium Tanks</a> </div> </li> <li class="dropdown"> <a class="anav" href="javascript:void(0)" class="dropbtn">Tactics</a> <div class="dropdown-content"> <a href="Encyclopedie-Tactics.html">Tactics</a> <a href="Encyclopedie-Matchs.html">Matchs</a> <a href="Encyclopedie-Mini%20map.html">Mini Map</a> <a href="Encyclopedie-Spotting.html">Spotting</a> <a href="Encyclopedie-Armor.html">Armor</a> <a href="Encyclopedie-Camouflage.html">Camouflage</a> <a href="Encyclopedie-Tiers.html">Tiers</a> <a href="Encyclopedie-Tanks.html">Tanks</a> <a href="Encyclopedie-Light_tanks.html">Light Tanks</a> <a href="Encyclopedie-Medium_tanks.html">Medium Tanks</a> <a href="Encyclopedie-Heavy_tanks.html">Heavy Tanks</a> <a href="Encyclopedie-Tank_destroyers.html">Tank Destroyers</a> <a href="Encyclopedie-Self-propelled_gun.html">Self-propelled Gun</a> <a href="Encyclopedie-Premium_tanks.html">Premium Tank</a> </div> </li> </ul> <header class="second"> <h2>Ammunition</h2> <p>The main way to kill tanks</p> </header> <hr> <article> <section> <h3>Standared and Premium Ammo</h3> <P>In World of tanks there is Standared Ammo, payed for with <a href="Encyclopedie-Credits.html">credits</a>, and Premium ammo payed for with large amount of <a href="Encyclopedie-Credits.html">credits</a>, or <a href="Encyclopedie-Gold.html">gold</a>.</P> <P>There is a 5 common types of ammo used in World of tanks</P> <ul id="normal"><li>Armor Piercing (AP)</li> <li>Armor Piercing Composite Rigid (APCR)</li> <li>High Explosive (HE)</li> <li>High Explosive Anti-Tank (HEAT)</li> <li>High Explosive Squash Head (HESH)</li> </ul> </section> <section> <h3>Armor Piercing: </h3> <img src="Images/Shells_AP.png" alt="Missing picture \o/" width=100px> <p>Armor Piercing is the most common round used. <br>AP rounds are the best round vs. sloped <a href="Encyclopedie-Armor.html">armor</a>, as they have a normilization of 5% and will auto bounce at angles over 75°. As AP rounds travel, they will lose penetration over distance. <br> </p> </section> <section> <h3>Armor Piercing Compiste Rigid</h3> <img src="Images/Shells_APCR.png" alt="Missing picture \o/" width=100px> <p>APCR in lower tiers is more often Premium ammo, in the higher tiers it seen often as standared. <br>APCR is better Vs. flater armor but will fair okay Vs. sloped <a href="Encyclopedie-Armor.html">armor</a> with normilization of 3% and will auto bounce at angles over 70°. As the APCR rounds travel, they will lose a large amount of penetration over a distance.</p> </section> <section> <h3>High Explosive</h3> <img src="Images/Shells_HE.png" alt="Missing picture \o/" width=100px> <p>HE rounds specilize in dealing large amounts of damage, but has low penetration.<br>He rounds don't care what armor, as they will always explode on contact. They also don't lose any penetration over distance, but travel slow.</p> </section> <section> <h3>High Explosive Anti-tank</h3> <img src="Images/Shells_HEAT.png" alt="Missing picture \o/" width=100px> <p>HEAT rounds have the highest penetration out of all the rounds, but are almost always premium ammo (with a few exeptions).<br>HEAT rounds are best to use Vs flat armor and tanks at long ranges, as they don't lose any penetration over time, but have slow travel time. They have no normilization and will auto bounce at angles over 85°.</p> </section> <section> <h3>High Explosive Squash Head</h3> <img src="Images/Shells_HESH.png" alt="Missing picture \o/" width=100px> <P>HESH rounds are only available with British tanks and are only really used with the FV183. They act like HE but have better penetration.</P> </section> <hr> <section> <h4>Best time to use each type of Ammo</h4> <style> Table, th, td { border: 1px solid black; } </style> <Table> <tr> <th>Round</th> <th>Sloped armor</th> <th>Spaced armor</th> <th>Flat armor</th> <th>Range</th> <th>Speed of target</th> </tr> <tr> <th>AP</th> <th><mark>Good</mark></th> <th><mark>Good</mark></th> <th><mark>Excellent</mark></th> <th>Ok</th> <th>Ok</th> </tr> <tr> <th>APCR</th> <th>Ok</th> <th><mark>Good</mark></th> <th><mark>Excellent</mark></th> <th>Poor</th> <th><mark>Excellent</mark></th> </tr> <tr> <th>HE</th> <th>Poor</th> <th>Bad</th> <th>Ok</th> <th><mark>Excellent</mark></th> <th>Bad</th> </tr> <tr> <th>HEAT</th> <th>Ok</th> <th>Bad</th> <th><mark>Excellent</mark></th> <th><mark>Excellent</mark></th> <th>Bad</th> </tr> <tr> <th>HESH</th> <th>Ok</th> <th>Bad</th> <th>Ok</th> <th><mark>Excellent</mark></th> <th>Bad</th> </tr> </Table> </section> </article> <p><a href="Encyclopedia-Home.html">Return Home</a></p> <hr> <footer> <p>Created by <NAME>, copyright 2017</p> </footer> </body> </html><file_sep>var myGamePiece; //lawn mower var house; //house var mowerSize = 30; //Size of the mower var ranStump; //places a random stump //changes the size of the mower from 1-100 function sliderChange() { //gets the value from the slider and puts it into the text box document.getElementById("slText").value = document.getElementById("slider").value; mowerSize = document.getElementById("slider").value; myGameArea.stop(); //needed to start the game for reset of size startGame(); //needed to start the game for reset of size } function ranPlace() { var rwidth = 50; //var rHeight = 50; } //starts the game function startGame() { var ranWidth = Math.floor((Math.random() * 750)); //random number for width var ranHeight = Math.floor((Math.random() * 700)); //random number for height var stumpSize = Math.floor((Math.random() * 40) + 10) //maybe i need to use a button to get the value into the thing also myGamePiece = new component(mowerSize, mowerSize, "blue", 0, 800); //size, color, and start location of lawnmower house = new component(100, 100, "grey", 450, 250); //size, color and start location of house ranStump = new component(stumpSize, stumpSize, "black", ranPlace(), ranHeight); //places a stump in a random location even in the house xD myGameArea.start(); } //creates the game area var myGameArea = { canvas : document.createElement("canvas"), start : function() { this.canvas.width = 800; //size of the width for the canvas this.canvas.height = 800; //size of the height for the canvas this.context = this.canvas.getContext("2d"); document.body.insertBefore(this.canvas, document.body.childNodes[0]); this.frameNo = 0; this.interval = setInterval(updateGameArea, 20); //the infomation the canvas needs to allow movment with the keys window.addEventListener('keydown', function (e) { e.preventDefault(); myGameArea.keys = (myGameArea.keys || []); myGameArea.keys[e.keyCode] = (e.type == "keydown"); }) window.addEventListener('keyup', function (e) { myGameArea.keys[e.keyCode] = (e.type == "keydown"); }) }, stop : function() { clearInterval(this.interval); }, clear : function() { this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); } } //component function component(width, height, color, x, y, type) { this.type = type; this.width = width; this.height = height; this.speed = 0; this.angle = 0; this.moveAngle = 0; this.x = x; this.y = y; //updates the component this.update = function() { ctx = myGameArea.context; ctx.save(); ctx.translate(this.x, this.y); ctx.rotate(this.angle); ctx.fillStyle = color; ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height); ctx.restore(); } this.newPos = function() { this.angle += this.moveAngle * Math.PI / 180; this.x += this.speed * Math.sin(this.angle); this.y -= this.speed * Math.cos(this.angle); this.hitBottom(); //for hitting the bottom of the canvas this.hitTop(); //for hitting the top of the canvas this.hitLeft(); //for hitting the left of the canvas this.hitRight(); //for hitting the right of the canvas this.paintRect(); //call the function to paint the background } //Checks to see if the mower has crashed into any other objects this.crashWith = function(otherobj) { var myleft = this.x - (this.width / 2); //mower width - 1/2 mower width to get right area var myright = this.x + (this.width / 2); //mower width + 1/2 mower width to get right area var mytop = this.y - (this.height / 2); //mower height - 1/2 mower height to get right area var mybottom = this.y + (this.height / 2); //mower height + 1/2 mower height to get right area var otherleft = otherobj.x - (otherobj.width /2); //otherobj width + 1/2 otherobj width to get right area var otherright = otherobj.x + (otherobj.width / 2); //otherobj width + 1/2 otherobj width to get right area var othertop = otherobj.y - (otherobj.height / 2); //otherobj height + 1/2 otherobj height to get right area var otherbottom = otherobj.y + (otherobj.height / 2); //otherobj height + 1/2 otherobj height to get right area var crash = true; if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) { crash = false; } return crash; } //paints under the component this.paintRect = function() { var sub = 25; //used to subtract the location to be panted sub = mowerSize / 2; //makes sub = half the size of the mower var ctx = myGameArea.context; //gets the context for the back ground ctx.fillStyle = "green"; //makes the back ground become green ctx.rect(this.x - sub, this.y - sub, this.width, this.height); //puts new background color under the lower mower ctx.fill(); //fills it in } //makes the object hit the bottom of the canvas this.hitBottom = function() { var bottom = myGameArea.canvas.height - (this.height / 2) + 5; //canvas hight - 1/2 mower height to hit bottom if (this.y > bottom) { this.y = bottom; } } //makes the object hit the top this.hitTop = function() { var top = myGameArea.canvas.clientTop + (this.height / 2) - 5; //canvas hight + 1/2 mower height to hit top if (this.y < top) { this.y = top; } } //makes the object hit the left of the canvas this.hitLeft = function() { var left = myGameArea.canvas.clientLeft + (this.width / 2) - 5; //left of canvas + 1/2 mower width if (this.x < left) { this.x = left; } } //makes the object hit the right of the canvas this.hitRight = function() { var right = myGameArea.canvas.width - (this.width / 2) + 5; //right of canvas - 1/2 mower width if (this.x > right) { this.x = right; } } } function updateGameArea() { //checks to see if the mower has indeed crashed into the house or stump if (myGamePiece.crashWith(house) || myGamePiece.crashWith(ranStump)) { gameScore(); //if there is a crash it calls the gamescore function } else { myGameArea.clear(); myGameArea.frameNo += 1; myGamePiece.moveAngle = 0; myGamePiece.speed = 0; //the speed and angle to move the piece depending on the key pressed if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.moveAngle = -3; } if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.moveAngle = 3; } if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speed= 3; } if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speed= -3; } myGamePiece.newPos(); myGamePiece.update(); house.update(); ranStump.update(); } } //restarts the game but keeps the piece moving after you crash function restart() { myGameArea.stop(); //stops the game startGame(); //restarts the game } function gameScore() { myGameArea.stop(); var imgData = ctx.getImageData(0, 0, myGameArea.canvas.width, myGameArea.canvas.height) var i; //counting variable var score = 640000; //the scout amount for (i = 0; i < imgData.data.length; i+=4) //loops through as long as 'i' is less than the canvas area { red = imgData.data[i]; //looks for red value green = imgData.data[i+1]; //looks for the green value blue = imgData.data[i+2]; //looks for the blue value alph = imgData.data[i+3]; //looks for the transparance if(green == 128) //looks to see if the green = 128 { score = score - 1; //subtracts 1 to the score if it does } } alert('Game over!\nYou missed: '+ score + ' blades of grass!\n' + 'You mowed for ' + myGameArea.frameNo / 50 + ' seconds!'); //gives and alert with the score upon hitting end game button }
165b3364db31107d73805f2878963cedc5febd88
[ "JavaScript", "HTML" ]
2
HTML
PetersonLuke/WWW-class
52f47918def1ca3b40f058dea007fe8ce7403196
bd55ffc5f147ec3f08b82ccd6bc51bddb058e15f
refs/heads/master
<repo_name>MultiFe22/aula-eracing-alunos<file_sep>/aula.py print("Hello world") x = 1 y = 2 print(x+y) print("Testing version system") print("Now we are in a branch") print("Second branch commit")
be9e7fb9a444b56f30a218e89ab452b4651528b4
[ "Python" ]
1
Python
MultiFe22/aula-eracing-alunos
0b4420f613ef17339396a39fbc183d8010155aae
9bc07d079552f40806c6274f1937cc64e229edcf
refs/heads/master
<repo_name>runopti/parity_experiment<file_sep>/results/test/experiment1-2016-07-03-23:36:15/getData.py import numpy as np np.random.seed(0) def createTargetData(digit_list): """ generate len(digit_list) vector, whose i th element is the corresponding parity upto the ith element of the input.""" sum_ = 0 parity_list = [] # check the first digit sum_ = digit_list[0] if sum_ % 2 == 0: parity_list.append(0) else: parity_list.append(1) # main for loop for i in range(len(digit_list)): if i == 0: continue else: sum_ += digit_list[i] if sum_ % 2 == 0: parity_list.append(0) else: parity_list.append(1) return parity_list def createInputData(n): """ generate a list of digits 0/1""" digit_list = [] for i in range(n): digit_list.append(np.random.randint(2)) return digit_list #data = createInputData(10) #parity = createTargetData(data) #print(data) #print(parity) <file_sep>/src/plot_table.py import numpy as np import tensorflow as tf import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import pickle import sys import argparse parser = argparse.ArgumentParser(description='Define parameters for plot_table.py.') parser.add_argument('--num_plot', type=int) num_plot = int(sys.argv[2]) parser.add_argument('--save', type=str) #parser.add_argument('--max_epoch', type=int) parser.add_argument('--yaxis', nargs=int(sys.argv[2]), type=str) #parser.add_argument('--xaxis', nargs=int(sys.argv[2]), type=str) args = parser.parse_args() #max_epoch = args.max_epoch plot_list = [] for i in range(num_plot): with open(args.yaxis[i],'rb') as f: plot_list.append(pickle.load(f)) for i in range(num_plot): plt.figure(figsize=(8, 8)) plot_out = plt.plot(range(len(plot_list[i])), plot_list[i] ,'ro',alpha=0.3) #plt.show() image_file = args.save + '/' + args.yaxis[i].split('.')[0] # taking the name before 'dot' pickle plt.savefig(image_file + ".png") #plt.figure(figsize=(8, 8)) #plot_out = plt.plot(range(max_epoch),acc_list,'bo', alpha=0.3) #plt.show() #image_file = args.save + '/acc_list' #plt.savefig(image_file + ".png") <file_sep>/src/rnn_lstm.py import tensorflow as tf import reader import getData import numpy as np import math import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt # for storing info import platform import sys import datetime import os info = {} info['script_name'] = sys.argv[0].split('/')[-1] info['python_version'] = platform.python_version() info['sys_uname'] = platform.uname() start_time = datetime.datetime.now() start_utime = os.times()[0] info['start_time'] = start_time.isoformat() import argparse parser = argparse.ArgumentParser(description='Define parameters for Parity Experiment.') parser.add_argument('--max_epoch', type=int) parser.add_argument('--hidden_size', type=int) parser.add_argument('--batch_size', type=int) parser.add_argument('--output_size', type=int) parser.add_argument('--seq_len', type=int) parser.add_argument('--data_size', type=int) parser.add_argument('--rseed', type=int) parser.add_argument('--lr_test', type=bool, default=False) parser.add_argument('--loss_diff_eps', type=float) parser.add_argument('--grad_clip', type=bool) parser.add_argument('--max_grad_norm', type=float) parser.add_argument('--train_method', type=str) args = parser.parse_args() for i in args.__dict__.keys(): if i[0] != "_": info['option_' + i] = str(getattr(args, i)) max_epoch = args.max_epoch # 300 hidden_size = args.hidden_size # 2 # 4 batch_size = args.batch_size #1 output_size = args.output_size #2 seq_len = args.seq_len #12 #3 #6 n = args.data_size # 1000 print(max_epoch) np.random.seed(args.rseed) tf.set_random_seed(args.rseed) def calc_accuracy(n, state): total_sum = 0 for i in range(n): state = initial_state.eval() x = getData.createInputData(seq_len) x = np.asarray(x).reshape(1, seq_len) y = getData.createTargetData(x[0])[-1] y_target = np.zeros((1,2)) if y == 0: y_target[0][0] = 1 else: y_target[0][1] = 1 feed_dict={initial_state: state, data:x} output_ = session.run(output, feed_dict=feed_dict) #print(np.argmax(y_target)) #print(np.argmax(output_)) if np.argmax(y_target) == np.argmax(output_): total_sum += 1 return (1.0 * total_sum / n) #print("accuracy: %f" % (1.0 * total_sum / n)) input_data = getData.createInputData(n) target_data = getData.createTargetData(input_data) val_input_data = getData.createInputData(n) val_target_data = getData.createTargetData(val_input_data) with tf.Graph().as_default(): ############## Graph construction ################ data = tf.placeholder(tf.float32, shape=[batch_size, seq_len]) if args.train_method == "single": target = tf.placeholder(tf.float32, shape=[batch_size, output_size]) else: target = tf.placeholder(tf.float32, shape=[seq_len, batch_size, output_size]) target_list = [tf.squeeze(tf.slice(target, [i,0,0], [1, batch_size, output_size])) for i in range(seq_len)] learning_rate = tf.placeholder(tf.float32, shape=[]) #rnn_cell = tf.nn.rnn_cell.BasicRNNCell(hidden_size) rnn_cell = tf.nn.rnn_cell.BasicLSTMCell(2*hidden_size) # initialize the state initial_state = state = tf.zeros([batch_size, 2*hidden_size]) if args.train_method != "single": loss = tf.constant(0.0) for i in range(seq_len): if i > 0: tf.get_variable_scope().reuse_variables() cell_output, state = rnn_cell(tf.reshape(data[:,i], [1,1]), state) # should change [1,1] if I want to change batch_size? # I need to use tf.get_variable to activate reuse_variables() weights = tf.get_variable("weights", dtype=tf.float32, initializer=tf.truncated_normal([hidden_size, output_size], stddev=1.0/math.sqrt(float(hidden_size)))) biases = tf.get_variable("biases", dtype=tf.float32,initializer=tf.truncated_normal([output_size], stddev=1.0/math.sqrt(float(hidden_size)))) output = tf.nn.softmax(tf.matmul(cell_output, weights) + biases) # the size of output should be just [batch_size, 1] right? if args.train_method == "single": pass else: # target has to be shape=[seq_len * [1,2]] loss_per_digit = -tf.reduce_sum(target_list[i]*tf.log(output)) # this should be just 1 by 1 - 1 by 1 loss += loss_per_digit if args.train_method == "single": #output = tf.Print(output, [output], message="this is output: ") # print(state) loss = -tf.reduce_sum(target*tf.log(output)) # this should be just 1 by 1 - 1 by 1 tf.scalar_summary("loss", loss) #train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss) if args.grad_clip: tvars = tf.trainable_variables() grads, _ = tf.clip_by_global_norm(tf.gradients(loss, tvars), args.max_grad_norm) #optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op = optimizer.apply_gradients(zip(grads, tvars)) else: train_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss) # 0.001 else: if args.grad_clip: tvars = tf.trainable_variables() grads, _ = tf.clip_by_global_norm(tf.gradients(loss, tvars), args.max_grad_norm) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op = optimizer.apply_gradients(zip(grads, tvars)) else: train_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss) tf.add_to_collection('train_op', train_op) tf.add_to_collection('output', output) tf.add_to_collection('initial_state', initial_state) tf.add_to_collection('data', data) tf.add_to_collection('target', target) tf.add_to_collection('state', state) final_state = state summary_op = tf.merge_all_summaries() init_op = tf.initialize_all_variables() ############### Graph construction end ########## total_loss_list = [] acc_list = [] loss_diff_list = [] saver = tf.train.Saver() with tf.Session() as session: summary_writer = tf.train.SummaryWriter("tensorflow_log", graph=session.graph) session.run(init_op) numpy_state = initial_state.eval() # for epoch in range(max_epoch): epoch = 0 old_val_loss = 1; new_val_loss = 2*old_val_loss while abs(new_val_loss - old_val_loss) > args.loss_diff_eps: epoch += 1 if epoch == max_epoch: print("max epoch reached. break the loop:") break total_loss = 0 step_count = 0 for step, (x,y) in enumerate(reader.parity_iterator(input_data,target_data,batch_size, seq_len)): step_count += 1 if args.train_method == "single": y = getData.createTargetData(x[0])[-1] y_target = np.zeros((1,2)) if y == 0: y_target[0][0] = 1 else: y_target[0][1] = 1 else: # y_target needs to be shape=[num_seq * [batch_size, output_size] y_target = np.zeros((seq_len, 1, 2)) for i in range(seq_len): if y[0][i] == 0: y_target[i][0][0] = 1 else: y_target[i][0][1] = 1 lr_value = 0.001 if args.lr_test == True and epoch == 180: lr_value = lr_value / 10 feed_dict={initial_state: numpy_state, data: x, target: y_target, learning_rate: lr_value} numpy_state, current_loss, _, output_ = session.run([final_state, loss, train_op, output], feed_dict=feed_dict) total_loss += current_loss #print(current_loss) #print("target: %d output: %d" % (np.argmax(y_target), np.argmax(output_[0]))) #print(output_[0]) #print(current_loss) #if step % 100 == 0: #print("loss") #current_loss = session.run(loss, feed_dict) # summary_str = session.run(summary_op, feed_dict) # summary_writer.add_summary(summary_str, step) #print(current_loss) print(1.0 * total_loss / step_count) total_loss_list.append(1.0 * total_loss / step_count) acc = calc_accuracy(100, numpy_state) acc_list.append(acc) # validation (for termination criteria) val_total_loss = 0 num_total_steps = 0 for step_val, (val_x,val_y) in enumerate(reader.parity_iterator(val_input_data,val_target_data,batch_size, seq_len)): if args.train_method == "single": # using only the last target (at the end of the time_step) val_y = getData.createTargetData(x[0])[-1] val_y_target = np.zeros((1,2)) if val_y == 0: val_y_target[0][0] = 1 else: val_y_target[0][1] = 1 else: val_y_target = np.zeros((seq_len, 1, 2)) for i in range(seq_len): if val_y[0][i] == 0: val_y_target[i][0][0] = 1 else: val_y_target[i][0][1] = 1 val_loss = session.run([loss], feed_dict={initial_state: numpy_state, data: val_x, target: val_y_target, learning_rate: 0.0}) val_total_loss += val_loss[0] num_total_steps += 1 old_val_loss = new_val_loss new_val_loss = 1.0 * val_total_loss / num_total_steps print("printing diff") print(new_val_loss - old_val_loss) loss_diff_list.append(new_val_loss - old_val_loss) saver.save(session, 'my_model', global_step=0) import pickle with open('total_loss_list.pickle', 'wb') as f: pickle.dump(total_loss_list, f) with open('acc_list.pickle', 'wb') as f: pickle.dump(acc_list, f) with open('loss_diff_list.pickle', 'wb') as f: pickle.dump(loss_diff_list, f) end_time = datetime.datetime.now() end_utime = os.times()[0] info['end_time'] = end_time.isoformat() info['elapsed_time'] = str((end_time - start_time)) info['elapsed_utime'] = str((end_utime - start_utime)) with open('info.txt', 'w') as outfile: for key in info.keys(): outfile.write("#%s=%s\n" % (key, str(info[key]))) <file_sep>/README.md # Investigation of RNN's leanability of parity function On-going project <file_sep>/test/rnn_test.py import tensorflow as tf import reader import getData import numpy as np import math np.random.seed(0) tf.set_random_seed(0) max_epoch = 10 hidden_size = 4 batch_size = 1 output_size = 1 seq_len = 6 n = 1000 input_data = getData.createInputData(n) target_data = getData.createTargetData(input_data) ############## Graph construction ################ data = tf.placeholder(tf.float32, [batch_size, seq_len]) target = tf.placeholder(tf.float32, [batch_size]) lstm = tf.nn.rnn_cell.BasicRNNCell(hidden_size) # initialize the state initial_state = state = tf.zeros([batch_size, hidden_size]) for i in range(seq_len): if i > 0: tf.get_variable_scope().reuse_variables() with tf.name_scope("in") as scope: weights = tf.Variable(tf.truncated_normal([hidden_size, batch_size], stddev=1.0/math.sqrt(float(hidden_size)), name="weights")) biases = tf.Variable(tf.truncated_normal([hidden_size], stddev=1.0/math.sqrt(float(hidden_size)), name="biases")) mapped = weights * data[:,i] mapped = tf.reshape(mapped, [1, hidden_size]) # 1 x hidden_size mapped = mapped + biases #mapped = tf.Print(mapped, [mapped], message="this is mapped: ") cell_output, state = lstm(mapped, state) with tf.name_scope("out") as scope: weights = tf.Variable(tf.truncated_normal([hidden_size, output_size], stddev=1.0/math.sqrt(float(hidden_size)), name="weights")) biases = tf.Variable(tf.truncated_normal([output_size], stddev=1.0/math.sqrt(float(hidden_size)), name="biases")) output = tf.matmul(cell_output, weights) + biases # the size of output should be just [batch_size, 1] right? loss = tf.reduce_mean(tf.square(output - target)) # this should be just 1 by 1 - 1 by 1 train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss) final_state = state init_op = tf.initialize_all_variables() ############### Graph construction end ########## with tf.Session() as session: session.run(init_op) numpy_state = initial_state.eval() for epoch in range(max_epoch): total_loss = 0 for step, (x,y) in enumerate(reader.parity_iterator(input_data,target_data,batch_size, seq_len)): #print([y[0][-1]]) #exit() #print(x[0]) y = getData.createTargetData(x[0]) #print(float(y)) #exit() feed_dict={initial_state: numpy_state, data: x, target: [float(y[-1])]} numpy_state, current_loss, _, output_ = session.run([final_state, loss, train_op, output], feed_dict=feed_dict) total_loss += current_loss print("target: %f output: %f" % (y[-1], output_[0])) #print(current_loss) print(total_loss) <file_sep>/results/test/test.py import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import tensorflow as tf test = [i for i in range(100)] import pickle with open("test.pickle", "wb") as file: pickle.dump(test, file) <file_sep>/results/2016-07-03/sample_comp1/experiment3-2016-07-04-04:12:54/runall.sh #!/bin/sh ## Experiment1 filename="experiment1-`date \"+%F-%T"`" # will output something like 2016-03-13-17:35:11 mkdir $filename script_dir_path=$(dirname $(readlink -f $0)) cd $filename python3 ${script_dir_path}/../../src/rnn_test_classif_graph.py --max_epoch 600 --hidden_size 3 --batch_size 1 --output_size 2 --seq_len 5 --data_size 1000 --rseed 0 # passing the right path to train_mnist.lua using ${script_dir_path} which is the current directory where # this runall.sh is located. mkdir img image_name="plot-`date \"+%F-%T"`.png" # th ${script_dir_path}/../../src/plot_table.lua -i norm_gradParam.bin -name ${image_name} --save 'img' -xlabel "number of update" -ylabel "norm of gradient" # plot the norm_gradParam.bin and name it as plot-the-date-time-it-was-created.png. Saved in img folder. #sed -e "1c\test_acc" ${script_dir_path}/$filename/logs/test.log > ${script_dir_path}/$filename/logs/test.csv #sed -e "1c\train_acc" ${script_dir_path}/$filename/logs/train.log > ${script_dir_path}/$filename/logs/train.csv #image_name="epochPlot-`date \"+%F-%T"`.png" #th ${script_dir_path}/../../src/plot_table.lua -epochPlot -xlabel "epoch" -ylabel "accuracy" -input1 ${script_dir_path}/$filename/logs/train.csv -input2 ${script_dir_path}/$filename/logs/test.csv -name ${image_name} --save 'img' python3 ${script_dir_path}/../../src/plot_table.py --num_plot 2 --save img --max_epoch 600 --yaxis acc_list.pickle total_loss_list.pickle --xaxis 600 600 cp ${script_dir_path}/$(basename $0) ${script_dir_path}/$(basename $0)_ mv ${script_dir_path}/$(basename $0)_ ${script_dir_path}/$filename/$(basename $0) cd ../ ## Experiment 2 filename="experiment2-`date \"+%F-%T"`" # will output something like 2016-03-13-17:35:11 mkdir $filename script_dir_path=$(dirname $(readlink -f $0)) cd $filename python3 ${script_dir_path}/../../src/rnn_test_classif_graph.py --max_epoch 600 --hidden_size 3 --batch_size 1 --output_size 2 --seq_len 5 --data_size 2000 --rseed 0 # passing the right path to train_mnist.lua using ${script_dir_path} which is the current directory where # this runall.sh is located. mkdir img image_name="plot-`date \"+%F-%T"`.png" python3 ${script_dir_path}/../../src/plot_table.py --num_plot 2 --save img --max_epoch 600 --yaxis acc_list.pickle total_loss_list.pickle --xaxis 600 600 cp ${script_dir_path}/$(basename $0) ${script_dir_path}/$(basename $0)_ mv ${script_dir_path}/$(basename $0)_ ${script_dir_path}/$filename/$(basename $0) cd ../ ## Experiment 3 filename="experiment3-`date \"+%F-%T"`" # will output something like 2016-03-13-17:35:11 mkdir $filename script_dir_path=$(dirname $(readlink -f $0)) cd $filename python3 ${script_dir_path}/../../src/rnn_test_classif_graph.py --max_epoch 600 --hidden_size 3 --batch_size 1 --output_size 2 --seq_len 5 --data_size 4000 --rseed 0 # passing the right path to train_mnist.lua using ${script_dir_path} which is the current directory where # this runall.sh is located. mkdir img image_name="plot-`date \"+%F-%T"`.png" python3 ${script_dir_path}/../../src/plot_table.py --num_plot 2 --save img --max_epoch 600 --yaxis acc_list.pickle total_loss_list.pickle --xaxis 600 600 cp ${script_dir_path}/$(basename $0) ${script_dir_path}/$(basename $0)_ mv ${script_dir_path}/$(basename $0)_ ${script_dir_path}/$filename/$(basename $0) cd ../ ## Experiment 4 filename="experiment4-`date \"+%F-%T"`" # will output something like 2016-03-13-17:35:11 mkdir $filename script_dir_path=$(dirname $(readlink -f $0)) cd $filename python3 ${script_dir_path}/../../src/rnn_test_classif_graph.py --max_epoch 600 --hidden_size 4 --batch_size 1 --output_size 2 --seq_len 5 --data_size 8000 --rseed 0 # passing the right path to train_mnist.lua using ${script_dir_path} which is the current directory where # this runall.sh is located. mkdir img image_name="plot-`date \"+%F-%T"`.png" python3 ${script_dir_path}/../../src/plot_table.py --num_plot 2 --save img --max_epoch 600 --yaxis acc_list.pickle total_loss_list.pickle --xaxis 600 600 cp ${script_dir_path}/$(basename $0) ${script_dir_path}/$(basename $0)_ mv ${script_dir_path}/$(basename $0)_ ${script_dir_path}/$filename/$(basename $0) cd ../ <file_sep>/qiita/foo.py fafafaq fafao q 1 print(); print(i) print(); print(i) print(); print(i) i print(); print(i) i i k print(); print(i) /rain gc_step = tf(rain.GradientDescentOptimizer().minimize()fiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii print(); print(i) print(); print(i) print(); print(i) /rain gc_step = tf(rain.GradientDescentOptimizer().minimize()fiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii print(); print(i) fefefe ijijij fefefef () <file_sep>/old_files/main_single.py from models import rnn_single import tensorflow as tf import numpy as np import getData import reader np.random.seed(0) tf.set_random_seed(0) n = 1000 batch_size = 1 input_data = getData.createInputData(n) target = getData.createTargetData(input_data) #input_data = np.asarray(input_data).reshape(batch_size,n) #print(input_data.shape) #target = np.asarray(target).reshape(batch_size,n) #print(target) #print(target[0][1].shape) #mlp = model.MLP(10, 10, 3, 3, 1) #weights = mlp.test() batch_size = 1 seq_len = 5 target_size = 1 hidden_size = 2 def see_output(data_size): test_input = getData.createInputData(data_size) test_target = getData.createTargetData(test_input) print("printing test_input") print(test_input) print("printing test_target") print(test_target[-1]) print("printing model output") print(sess.run(m.output_op, feed_dict={m.input: np.array(test_input).reshape(1,data_size), m.target: [np.array(test_target[-1])]})) m = rnn_single.RNNmodel(seq_len, target_size, hidden_size, batch_size, "mse") num_epoch = 40 #init_op = tf.initialize_all_variables() init_op = m.get_init_op summary_op = m.get_summary_op #exit() with tf.Session() as sess: summary_writer = tf.train.SummaryWriter('logdata-single', graph=sess.graph) sess.run(init_op) #print(sess.run(weights)) for i in range(num_epoch): for step, (x,y) in enumerate(reader.parity_iterator(input_data, target, batch_size, seq_len)): #print(y[0][-1]) sess.run(m.train_op, feed_dict={m.input: x, m.target: [y[0][-1]]}) if step % 20 == 0: print("printing loss") print(sess.run(m.loss, feed_dict={m.input: x, m.target: [y[0][-1]]})) summary_str=sess.run(summary_op, feed_dict={m.input: x, m.target: [y[0][-1]]}) summary_writer.add_summary(summary_str, i) see_output(seq_len) <file_sep>/src/main.py import argparse import sys parser = argparse.ArgumentParser(description='Check num of graphs to plot for Parity Experiment.') parser.add_argument('--num_plot', type=int) #print(sys.argv[2]) #if sys.args[0] == 1: # print("ok") #parser = argparse.ArgumentParser(description='Define parameters for Parity Experiment.') parser.add_argument('--max_epoch', type=int) parser.add_argument('--hidden_size', type=int) parser.add_argument('--batch_size', type=int) parser.add_argument('--output_size', type=int) parser.add_argument('--seq_len', type=int) parser.add_argument('--data_size', type=int) parser.add_argument('--rseed', type=int) parser.add_argument('--yaxis', nargs=int(sys.argv[2]), type=str) parser.add_argument('--xaxis', nargs=int(sys.argv[2]), type=str) num_plot = int(sys.argv[2]) print(int(sys.argv[2])) args = parser.parse_args() print(args.yaxis) print(args.yaxis[0].split(".")[1]) max_epoch = args.max_epoch # 300 hidden_size = args.hidden_size # 2 # 4 batch_size = args.batch_size #1 output_size = args.output_size #2 seq_len = args.seq_len #12 #3 #6 n = args.data_size # 1000 print(type(max_epoch)) #np.random.seed(args.rseed) #tf.set_random_seed(args.seed) import numpy as np import matplotlib.pyplot as plt NSAMPLE = 1000 x_data = np.float32(np.random.uniform(-10.5, 10.5, (1, NSAMPLE))).T r_data = np.float32(np.random.normal(size=(NSAMPLE,1))) y_data = np.float32(np.sin(0.75*x_data)*7.0+x_data*0.5+r_data*1.0) image_name = "sig_function" plt.figure(figsize=(8, 8)) plot_out = plt.plot(x_data,y_data,'ro',alpha=0.3) #plt.savefig(image_name + '.png') import platform import sys import datetime import os info = {} info['script_name'] = sys.argv[0].split('/')[-1] info['python_version'] = platform.python_version() info['sys_uname'] = platform.uname() start_time = datetime.datetime.now() start_utime = os.times()[0] info['start_time'] = start_time.isoformat() for i in args.__dict__.keys(): if i[0] != "_": info['option_' + i] = str(getattr(args, i)) end_time = datetime.datetime.now() end_utime = os.times()[0] info['end_time'] = end_time.isoformat() info['elapsed_time'] = str((end_time - start_time)) info['elapsed_utime'] = str((end_utime - start_utime)) with open('info.txt', 'w') as outfile: for key in info.keys(): outfile.write("#%s=%s\n" % (key, str(info[key]))) <file_sep>/models/mlp.py import tensorflow as tf import numpy as np import math class MLP: def __init__(self, input_size, target_size, hidden_size1, hidden_size2, batch_size): self.hidden_size1 = hidden_size1 self.hidden_size2 = hidden_size2 self.input_size = input_size self.target_size = target_size print(self.hidden_size1) self.input = tf.placeholder(tf.float32, shape=(batch_size, input_size)) self.target = tf.placeholder(tf.int32, shape=(batch_size)) # feed the data to the model and get the output self.output = output = self._inference(self.input) # get loss value #loss = self._loss(output, target) # get train_op #self._train_op = self._training(loss) def _inference(self, input): with tf.name_scope("hidden1") as scope: weights = tf.Variable(tf.truncated_normal((self.input_size, self.hidden_size1), stddev=1.0/math.sqrt(float(self.input_size)), name="weights")) biases = tf.Variable(tf.zeros([self.hidden_size1]), name="biases") hidden1 = tf.nn.relu(tf.matmul(input, weights) + biases) with tf.name_scope("hidden2") as scope: weights = tf.Variable(tf.truncated_normal((self.hidden_size1, self.hidden_size2), stddev=1.0/math.sqrt(float(self.hidden_size1)), name="weights")) biases = tf.Variable(tf.zeros([self.hidden_size2]), name="biases") hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases) with tf.name_scope("soft_max") as scope: weights = tf.Variable(tf.truncated_normal((self.hidden_size2, self.target_size), stddev=1.0/math.sqrt(float(self.target_size)), name="weights")) biases = tf.Variable(tf.zeros([self.target_size]), name="biases") output = tf.matmul(hidden2, weights) + biases return output def test(self): with tf.name_scope("test") as scope: weights = tf.Variable(tf.truncated_normal((2,4))) return weights @property def train_op(self): return self._train_op @property def output_op(self): return self.output @property def input_data(self): return self.input @property def target(self): return self.target <file_sep>/test/rnn_test_classif.py import tensorflow as tf import reader import getData import numpy as np import math np.random.seed(0) tf.set_random_seed(0) max_epoch = 100 hidden_size = 2 # 4 batch_size = 1 output_size = 2 seq_len = 3 #6 n = 1000 def calc_accuracy(n, state): total_sum = 0 for i in range(n): state = initial_state.eval() x = getData.createInputData(seq_len) x = np.asarray(x).reshape(1, seq_len) y = getData.createTargetData(x[0])[-1] y_target = np.zeros((1,2)) if y == 0: y_target[0][0] = 1 else: y_target[0][1] = 1 feed_dict={initial_state: state, data:x, target: y_target} output_ = session.run(output, feed_dict=feed_dict) #print(np.argmax(y_target)) #print(np.argmax(output_)) if np.argmax(y_target) == np.argmax(output_): total_sum += 1 print("accuracy: %f" % (1.0 * total_sum / n)) input_data = getData.createInputData(n) target_data = getData.createTargetData(input_data) ############## Graph construction ################ data = tf.placeholder(tf.float32, [batch_size, seq_len]) target = tf.placeholder(tf.float32, [batch_size, output_size]) lstm = tf.nn.rnn_cell.BasicRNNCell(hidden_size) # initialize the state initial_state = state = tf.zeros([batch_size, hidden_size]) for i in range(seq_len): if i > 0: tf.get_variable_scope().reuse_variables() with tf.name_scope("in") as scope: weights = tf.Variable(tf.truncated_normal([hidden_size, batch_size], stddev=1.0/math.sqrt(float(hidden_size)), name="weights")) biases = tf.Variable(tf.truncated_normal([hidden_size], stddev=1.0/math.sqrt(float(hidden_size)), name="biases")) mapped = weights * data[:,i] mapped = tf.reshape(mapped, [1, hidden_size]) # 1 x hidden_size mapped = mapped + biases #mapped = tf.Print(mapped, [mapped], message="this is mapped: ") cell_output, state = lstm(mapped, state) with tf.name_scope("out") as scope: weights = tf.Variable(tf.truncated_normal([hidden_size, output_size], stddev=1.0/math.sqrt(float(hidden_size)), name="weights")) biases = tf.Variable(tf.truncated_normal([output_size], stddev=1.0/math.sqrt(float(hidden_size)), name="biases")) output = tf.nn.softmax(tf.matmul(cell_output, weights) + biases) # the size of output should be just [batch_size, 1] right? #output = tf.reshape(output, [1,2]) loss = -tf.reduce_sum(target*tf.log(output)) # this should be just 1 by 1 - 1 by 1 #train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss) train_op = tf.train.AdamOptimizer(0.001).minimize(loss) final_state = state init_op = tf.initialize_all_variables() ############### Graph construction end ########## with tf.Session() as session: session.run(init_op) numpy_state = initial_state.eval() for epoch in range(max_epoch): total_loss = 0 for step, (x,y) in enumerate(reader.parity_iterator(input_data,target_data,batch_size, seq_len)): #print([y[0][-1]]) #exit() #print(x[0]) y = getData.createTargetData(x[0])[-1] y_target = np.zeros((1,2)) #print(y_target) #print(y) if y == 0: y_target[0][0] = 1 else: y_target[0][1] = 1 #print(y_target) #exit() #numpy_state = initial_state.eval() feed_dict={initial_state: numpy_state, data: x, target: y_target} numpy_state, current_loss, _, output_ = session.run([final_state, loss, train_op, output], feed_dict=feed_dict) total_loss += current_loss #print(current_loss) #print("target: %d output: %d" % (np.argmax(y_target), np.argmax(output_[0]))) #print(output_[0]) #print(current_loss) print(total_loss) calc_accuracy(100, numpy_state) <file_sep>/old_files/test.py import model import tensorflow as tf import numpy as np input_data = np.linspace(-1,1,10) input_data = input_data.reshape(1,10) print(input_data.shape) target = np.arange(10) target = target.reshape(1,10) print(target) print(target[0][1].shape) mlp = model.MLP(10, 10, 3, 3, 1) weights = mlp.test() init_op = tf.initialize_all_variables() with tf.Session() as sess: sess.run(init_op) #print(sess.run(weights)) print(sess.run(mlp.output_op, feed_dict={mlp.input_data: input_data, mlp.target: [target[0][1]]})) <file_sep>/src/getData.py import numpy as np import math np.random.seed(0) ## I changed [0,1] to [-1,1] on 7/22 def createTargetData(digit_list): """ generate len(digit_list) vector, whose i th element is the corresponding parity upto the ith element of the input.""" sum_ = 0 parity_list = [] # check the first digit sum_ = digit_list[0] if sum_ % 2 == 0: parity_list.append(0) else: parity_list.append(1) # main for loop for i in range(len(digit_list)): if i == 0: continue else: sum_ += digit_list[i] if sum_ % 2 == 0: parity_list.append(0) else: parity_list.append(1) return parity_list def createInputData(n): """ generate a list of digits 0/1""" digit_list = [] for i in range(n): digit_list.append(np.random.randint(2)) return digit_list def createRandomData(n, n_test, seq_len): """ uniformly sample a data point from the 2^n space. """ data_input_list = [] data_test_list = [] store_int_list = [] for _ in range(n): random_int = np.random.randint(math.pow(2,seq_len)) # sample a number from [1, 2^seq_len] store_int_list.append(random_int) binary_digits = np.array(list(bin(random_int)[2:].zfill(seq_len))).astype(float) #binary_digits[binary_digits==0] = -1.0 data_input_list.append(binary_digits) # convert this into binary digit for _ in range(n_test): random_int = store_int_list[0] # just to pass the first test in while while random_int in store_int_list: random_int = np.random.randint(math.pow(2,seq_len)) binary_digits = np.array(list(bin(random_int)[2:].zfill(seq_len))).astype(float) #binary_digits[binary_digits==0] = -1.0 data_test_list.append(binary_digits) return data_input_list, data_test_list #data = createInputData(10) #parity = createTargetData(data) #print(data) #print(parity) <file_sep>/test/minimal.py import tensorflow as tf from tensorflow.python.ops import rnn_cell init_scale = 0.1 num_steps = 7 num_units = 7 input_data = [1, 2, 3, 4, 5, 6, 7] target = [2, 3, 4, 5, 6, 7, 7] batch_size = 1 with tf.Graph().as_default(), tf.Session() as session: input1 = tf.placeholder(tf.float32, [batch_size, 1]) inputs = [input1 for _ in range(num_steps)] lstm = tf.nn.rnn_cell.BasicLSTMCell(num_units) initial_state = state = tf.zeros([batch_size, 2*num_unites]) loss = tf.constant(0.0) # unroll for i in range(num_steps): if i > 0: tf.get_variable_scope().reuse_variables() cell_output, state = lstm(inputs[i], state) loss += tf.reduce_sum(abs(cell_output - target)) final_state = state optimizer = tf.train.AdamOptimizer(0.1) train = optimizer.minimize(loss) max_grad_norm = 5 trainable_variables = tf.trainable_variables() numpy_state = initial_state.eval() session.run(tf.initialize_all_variables()) for epoch in range(10): for k in range(7): <file_sep>/test/minimal_working.py import tensorflow as tf from tensorflow.python.ops import rnn_cell init_scale = 0.1 num_steps = 7 num_units = 7 input_data = [1, 2, 3, 4, 5, 6, 7] target = [2, 3, 4, 5, 6, 7, 7] batch_size = 1 with tf.Graph().as_default(), tf.Session() as session: # Placeholder for the inputs and target of the net # inputs = tf.placeholder(tf.int32, [batch_size, num_steps]) input1 = tf.placeholder(tf.float32, [batch_size, 1]) inputs = [input1 for _ in range(num_steps)] outputs = tf.placeholder(tf.float32, [batch_size, num_steps]) #gru = rnn_cell.GRUCell(num_units) gru = rnn_cell.BasicLSTMCell(num_units) initial_state = state = tf.zeros([batch_size, 2*num_units]) loss = tf.constant(0.0) # setup model: unroll for time_step in range(num_steps): if time_step > 0: tf.get_variable_scope().reuse_variables() step_ = inputs[time_step] #step_ = tf.Print(step_, [step_], message="this is step_:") #state = tf.Print(state, [state], message="this is state:") output, state = gru(step_, state) output = tf.Print(output, [output], message="this is output:") loss += tf.reduce_sum(abs(output - target)) # all norms work equally well? NO! final_state = state # setup ... uh machinery? again? # initializer = tf.random_uniform_initializer(-init_scale,init_scale) # for step in range(num_steps): # # x=input_batch[:,step] # x=input_batch[step] # state = session.run([state,outputs], {state: state}) # final_state = state optimizer = tf.train.AdamOptimizer(0.1) # CONVERGEs sooo much better train = optimizer.minimize(loss) # let the optimizer train max_grad_norm=5 trainable_variables = tf.trainable_variables() grads=tf.gradients(loss, trainable_variables) optimizer = tf.train.GradientDescentOptimizer(0.01) train_op = optimizer.apply_gradients(zip(grads, trainable_variables)) numpy_state = initial_state.eval() session.run(tf.initialize_all_variables()) for epoch in range(10): # now for i in range(7): # feed fake 2D matrix of 1 byte at a time ;) feed_dict = {initial_state: numpy_state, input1: [[input_data[i]]]} # no numpy_state, current_loss,_,_ = session.run([final_state, loss,train,train_op], feed_dict=feed_dict) print(current_loss) # hopefully going down, always stuck at 189, why!? <file_sep>/results/2016-07-16/Sigmoid-2016-07-16-17:52:10/run_check.sh #!/bin/sh ## Experiment 1 filename="Sigmoid-`date \"+%F-%T"`" # will output something like 2016-03-13-17:35:11 mkdir $filename script_dir_path=$(dirname $(readlink -f $0)) cd $filename python3 ${script_dir_path}/../../src/rnn_simple_sigm_data.py --max_epoch 500 --hidden_size 50 --batch_size 1 --output_size 1 --seq_len 13 --data_size 4000 --rseed 0 --loss_diff_eps 1e-6 --grad_clip True --max_grad_norm 1 --train_method "total" --lr_test True --cell_type "lstm" --learning_rate 0.001 # passing the right path to train_mnist.lua using ${script_dir_path} which is the current directory where # this runall.sh is located. mkdir img image_name="plot-`date \"+%F-%T"`.png" python3 ${script_dir_path}/../../src/plot_table.py --num_plot 3 --save img --yaxis acc_list.pickle total_loss_list.pickle loss_diff_list.pickle cp ${script_dir_path}/$(basename $0) ${script_dir_path}/$(basename $0)_ mv ${script_dir_path}/$(basename $0)_ ${script_dir_path}/$filename/$(basename $0) cd ../ <file_sep>/results/2016-07-12/visualize_hidden_states.py import tensorflow as tf import numpy as np import math import matplotlib.pyplot as plt import getData from easydict import EasyDict as edict args = edict({'hidden_size':3, 'batch_size':1, 'output_size': 2, 'seq_len': 5, 'train_method': "single", 'max_grad_norm':5.0, 'grad_clip': True}) hidden_size = args.hidden_size # 2 # 4 batch_size = args.batch_size #1 output_size = args.output_size #2 seq_len = args.seq_len #12 #3 #6 g1 = tf.Graph() with g1.as_default(): ############## Graph construction ################ data = tf.placeholder(tf.float32, shape=[batch_size, seq_len]) if args.train_method == "single": target = tf.placeholder(tf.float32, shape=[batch_size, output_size]) else: target = tf.placeholder(tf.float32, shape=[seq_len, batch_size, output_size]) target_list = [tf.squeeze(tf.slice(target, [i,0,0], [1, batch_size, output_size])) for i in range(seq_len)] learning_rate = tf.placeholder(tf.float32, shape=[]) rnn_cell = tf.nn.rnn_cell.BasicRNNCell(hidden_size) # initialize the state initial_state = state = tf.zeros([batch_size, hidden_size]) for i in range(seq_len): if i > 0: tf.get_variable_scope().reuse_variables() cell_output, state = rnn_cell(tf.reshape(data[:,i], [1,1]), state) # should change [1,1] if I want to change batch_size? state_name = 'state_' + str(i) tf.add_to_collection(state_name, state) # I need to use tf.get_variable to activate reuse_variables() weights = tf.get_variable("weights", dtype=tf.float32, initializer=tf.truncated_normal([hidden_size, output_size], stddev=1.0/math.sqrt(float(hidden_size)))) biases = tf.get_variable("biases", dtype=tf.float32,initializer=tf.truncated_normal([output_size], stddev=1.0/math.sqrt(float(hidden_size)))) output = tf.nn.softmax(tf.matmul(cell_output, weights) + biases) # the size of output should be just [batch_size, 1] right? if args.train_method == "single": pass else: # target has to be shape=[seq_len * [1,2]] loss_per_digit = -tf.reduce_sum(target_list[i]*tf.log(output)) # this should be just 1 by 1 - 1 by 1 if args.grad_clip: tvars = tf.trainable_variables() grads, _ = tf.clip_by_global_norm(tf.gradients(loss_per_digit, tvars), args.max_grad_norm) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op = optimizer.apply_gradients(zip(grads, tvars)) else: train_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss) if args.train_method == "single": #output = tf.Print(output, [output], message="this is output: ") #print(state) loss = -tf.reduce_sum(target*tf.log(output)) # this should be just 1 by 1 - 1 by 1 tf.scalar_summary("loss", loss) #train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss) if args.grad_clip: tvars = tf.trainable_variables() grads, _ = tf.clip_by_global_norm(tf.gradients(loss, tvars), args.max_grad_norm) #optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op = optimizer.apply_gradients(zip(grads, tvars)) else: train_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss) # 0.001 else: loss = tf.identity(loss_per_digit) tf.add_to_collection('train_op', train_op) tf.add_to_collection('output', output) tf.add_to_collection('initial_state', initial_state) tf.add_to_collection('data', data) tf.add_to_collection('target', target) tf.add_to_collection('state', state) final_state = state summary_op = tf.merge_all_summaries() init_op = tf.initialize_all_variables() ############### Graph construction end ########## # let's visualize the hidden state with g1.as_default(): saver_vis = tf.train.Saver(tf.all_variables()) with tf.Session() as sess: saver_vis.restore(sess, './test-2016-07-12-18:07:14/my_model-0') state = tf.get_collection('state')[0] output = tf.get_collection('output')[0] x = getData.createInputData(seq_len) x = np.float32(np.asarray(x).reshape(1, seq_len)) y = getData.createTargetData(x[0])[-1] y_target = np.zeros((1,2)) if y == 0: y_target[0][0] = 1 else: y_target[0][1] = 1 feed_dict={data:x} state_restore_np = np.zeros([seq_len, hidden_size]) for i in range(seq_len): state_name = 'state_' + str(i) output_, state_restore_np[i] = sess.run([output, tf.get_collection(state_name)[0]], feed_dict=feed_dict) x_data = np.array(range(5)) y_data2 = np.array([0, 1,0,0,1]) * 0.1 y_data = state_restore_np[:, 0] plt.figure(figsize=(8,8)) plot_out = plt.plot(x_data,y_data,'r--', x_data, y_data2, x_data, state_restore_np[:, 1], 'r--',x_data, state_restore_np[:, 2], 'y--', lw=2,alpha=1.0) plt.show() <file_sep>/test/reader.py import tensorflow as tf import numpy as np def parity_iterator(raw_data, raw_target, batch_size, num_steps): """Iterate on the raw PTB data. This generates batch_size pointers into the raw PTB data, and allows minibatch iteration along these pointers. Args: raw_data: one of the raw data outputs from ptb_raw_data. batch_size: int, the batch size. num_steps: int, the number of unrolls. Yields: Pairs of the batched data, each a matrix of shape [batch_size, num_steps]. The second element of the tuple is the same data time-shifted to the right by one. Raises: ValueError: if batch_size or num_steps are too high. """ raw_data = np.array(raw_data, dtype=np.float32) raw_target = np.array(raw_target, dtype=np.float32) data_len = len(raw_data) batch_len = data_len // batch_size data = np.zeros([batch_size, batch_len], dtype=np.float32) target = np.zeros([batch_size, batch_len], dtype=np.float32) if batch_size > 1: for i in range(batch_size): data[i] = raw_data[batch_len * i:batch_len * (i + 1)] target[i] = raw_target[batch_len * i:batch_len * (i + 1)] else: data[0,:] = raw_data target[0,:] = raw_target epoch_size = (batch_len - 1) // num_steps #print(len(raw_data)) #print(batch_len) if epoch_size == 0: raise ValueError("epoch_size == 0, decrease batch_size or num_steps") #if batch_size > 1: for i in range(epoch_size): x = data[:, i*num_steps:(i+1)*num_steps] y = target[:, i*num_steps:(i+1)*num_steps] yield (x, y) #else: # for i in range(epoch_size): # x = data[i*num_steps:(i+1)*num_steps] # y = target[i*num_steps:(i+1)*num_steps] #yield (x, y) <file_sep>/models/rnn_long.py import tensorflow as tf from tensorflow.models.rnn import rnn, rnn_cell import math class RNNmodel: def __init__(self, seq_len, target_size, hidden_size, batch_size): self.hidden_size = hidden_size self.seq_len = seq_len self.target_size = target_size self.batch_size = batch_size #self.lstm_size = lstm_size -> this is a hidden size I guess? print(self.hidden_size) self.input = tf.placeholder(tf.float32, shape=(batch_size, seq_len)) self.target = tf.placeholder(tf.float32, shape=(batch_size, seq_len)) self.state = tf.zeros([self.batch_size, 2*self.hidden_size]) self.output, self.hidden_state = self._inference(self.input, self.state) self.loss = loss = self._loss(self.output, self.target) self.train = self._training(loss) self.init_op = tf.initialize_all_variables() self.summary_op = tf.merge_all_summaries() def _inference(self, input, hidden_state): with tf.name_scope("hidden_in") as scope: weights = tf.Variable(tf.truncated_normal([self.seq_len, self.hidden_size], stddev=1.0/math.sqrt(float(self.seq_len)), name="weights")) biases = tf.Variable(tf.zeros([self.hidden_size], name="biases")) hidden_in = tf.matmul(input, weights) + biases with tf.name_scope("LSTM") as scope: lstm = rnn_cell.BasicLSTMCell(self.hidden_size) cell_output, hidden_state = lstm(hidden_in, hidden_state) with tf.name_scope("hidden_out") as scope: weights = tf.Variable(tf.truncated_normal([self.hidden_size, self.target_size], stddev=1.0/math.sqrt(float(self.target_size)), name="weights")) biases = tf.Variable(tf.zeros([self.target_size], name="biases")) output = tf.matmul(cell_output, weights) + biases return output, hidden_state def _loss(self, output, target): with tf.name_scope("mse-loss") as scope: loss = tf.reduce_mean(tf.square(output - target)) tf.scalar_summary("mse-loss", loss) return loss def _training(self, loss): with tf.name_scope("training") as scope: train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss) return train_step @property def output_op(self): return self.output @property def state_op(self): return self.hidden_state @property def loss_op(self): return self.loss @property def train_op(self): return self.train @property def get_summary_op(self): return self.summary_op @property def get_init_op(self): return self.init_op
b167d213ad6872957bfdf09e7761b733aed6d56c
[ "Markdown", "Python", "Shell" ]
20
Python
runopti/parity_experiment
7d30fb59c6078bb227009bd0978b6a6ad1c3e94a
e566c2bbcaf957677824e20224982f7eabcac2d3
refs/heads/master
<repo_name>thisismykingdomcome/migu<file_sep>/src/api/mainContent.js //方法一 import {http} from "../utils/my-http" export const mainContent1 = () => http("post",'api/lovev/miguMovie/data/seeFilmData.jsp'); export const watchContent = () => http("get",'api/lovev/miguMovie/data/seeFilmData.jsp',{nodeId:70022795,pagesize:3,pageidx:1}) export const movieList = () => http("get",'api/lovev/miguMovie/data/seeFilmData.jsp',{nodeId:70035127,pagesize:3,pageidx:1}) export const smallVideo = () => http("get",'api/lovev/miguMovie/data/seeFilmData.jsp',{nodeId:70027030,pagesize:3,pageidx:1}) export const filmReview = () => http("get",'api/lovev/miguMovie/data/seeFilmData.jsp',{nodeId:70022797,pagesize:3,pageidx:1}) // mainContent1().then((res) => { // console.log(res) // }) <file_sep>/src/api/discover.js import {http} from "@utils/http"; //接口的管理 //获取发现主页面数据 export const discoverData = ()=>http("post","api/lovev/miguMovie/data/find_index.jsp"); //获取资讯新闻详情 export const discoverMovieDetails = (id)=>http("get","api/lovev/miguMovie/data/newsDetail_data.jsp",{cid:id}) <file_sep>/src/store/store-zdw/mutations.js export default{ mutationsMainOne(state,params){ var a = sessionStorage.getItem("loopPic") if(a){ return; }else{ sessionStorage.setItem("loopPic",JSON.stringify(params[0])); sessionStorage.setItem("sellTicket",JSON.stringify(params[1])); sessionStorage.setItem("wonderfulActivity",JSON.stringify(params[2])); Array.prototype.push.apply(state.loopPic,params[0]) Array.prototype.push.apply(state.sellTicket,params[1]) Array.prototype.push.apply(state.wonderfulActivity,params[2]) } }, mutationsMovie(state,params){ var b = sessionStorage.getItem("watchOne") if(b){ return; }else{ sessionStorage.setItem("watchOne",JSON.stringify(params[0])) sessionStorage.setItem("watchTwo",JSON.stringify(params[1])); sessionStorage.setItem("watchThree",JSON.stringify(params[2])); // Array.prototype.push.apply(state.loopPic,params[0]) // Array.prototype.push.apply(state.watchTwo,params[1]) // Array.prototype.push.apply(state.watchThree,params[2]) } }, mutationsMovieList(state,params){ var c = sessionStorage.getItem("movieListOne") if(c){ return; }else{ sessionStorage.setItem("movieListOne",JSON.stringify(params[0])) sessionStorage.setItem("movieListTwo",JSON.stringify(params[1])); sessionStorage.setItem("movieListThree",JSON.stringify(params[2])); // Array.prototype.push.apply(state.loopPic,params[0]) // Array.prototype.push.apply(state.watchTwo,params[1]) // Array.prototype.push.apply(state.watchThree,params[2]) } }, mutationsVideo(state,params){ var d = sessionStorage.getItem("VideoOne") if(d){ return; }else{ sessionStorage.setItem("VideoOne",JSON.stringify(params[0])) // Array.prototype.push.apply(state.loopPic,params[0]) // Array.prototype.push.apply(state.watchTwo,params[1]) // Array.prototype.push.apply(state.watchThree,params[2]) } }, mutationsFilm(state,params){ var d = sessionStorage.getItem("FilmOne") if(d){ return; }else{ sessionStorage.setItem("FilmOne",JSON.stringify(params[0])) // Array.prototype.push.apply(state.loopPic,params[0]) // Array.prototype.push.apply(state.watchTwo,params[1]) // Array.prototype.push.apply(state.watchThree,params[2]) } }, }<file_sep>/src/router/shopping/index.js export default { path:'/shopping', name:'shopping', component:()=>import("@components/shopping/shopping"), meta :{ TabBarFlag:true }, props:true }<file_sep>/src/router/BuyTicket/index.js export default{ path:"/BuyTicket", name:"BuyTicket", component: () => import("@views/BuyTicket/BuyTicket"), meta:{ TabBarFlag:true, SectionFlag:true }, children:[ { path:"movie", name:"movie", component: () => import("@views/BuyTicket/BuyTicket"), meta: { TabBarFlag: true, SectionFlag: true }, children:[ { path: "movieNow", name: "movieNow", component: () => import("@components/BuyTicket/movie/movieNow"), meta: { TabBarFlag: true, SectionFlag: true }, }, { path: "movieComing", name: "movieComing", component: () => import("@components/BuyTicket/movie/movieComing"), meta: { TabBarFlag: true, SectionFlag: true }, } ] }, { path:"cinema", name:"cinema", component: () => import("@components/BuyTicket/cinema/cinema"), meta: { TabBarFlag: true, SectionFlag: false }, }, { path: "/", redirect: "/BuyTicket/movie/movieNow" }, ] }<file_sep>/src/store/BuyTicket/actions.js //使用接口 import { movieNowData, movieComingData, cinemaData } from "@api/BuyTicket"; export default { //正在上映 async actionsMovieNow({commit}, params) { let data = await movieNowData(params); commit("mutationsMovieNow", data.movies); }, //即将上映 async actionsMovieComing({commit}, params) { let data = await movieComingData(params); commit("mutationsMovieComing", data.movies); }, //影院 async actionsCinema({commit},params){ let data = await cinemaData(params); console.log(data); commit("mutationsCinema",data.cinemaes); } }<file_sep>/src/router/homePage/index.js export default { path:'/FP', name:"FP", component:() => import("@views/firstpage/firstPage.vue"), meta:{ flag:0, TabBarFlag:true }, props:true, children:[ { path:"watchMovie", name:"watchMovie", component:() => import("@components/watchMovie/watchMovie.vue"), meta:{ flag:false } }, { path:"mainContent", name:"mainContent", component:() => import("@components/main/mainContent.vue"), meta:{ flag:false } } ] }<file_sep>/src/router/search/index.js export default { path:'/search', name:"search", component:()=>import("@components/search/search"), props:true, meta:{ } }<file_sep>/src/store/discover/actions.js import { discoverData, discoverMovieDetails } from "@api/discover" export default{ async discoverData({commit}){ let data = await discoverData(); commit("mutationsDiscoverData",data) }, async NewDetails({commit},params){ let data = await discoverMovieDetails(params); commit("informationData",data) } }<file_sep>/src/store/store-zdw/actions.js import {mainContent1, watchContent,movieList,smallVideo,filmReview} from "../../api/mainContent" export default{ async actionsMainOne({commit}){ let data = await mainContent1(); var arr = []; for(var i =0,len=data.length;i < len;i++){ if(data[i].showCount == 11 || data[i].showCount == 13 || data[i].showCount == 8){ arr.push(data[i].list) } } // console.log(arr) commit('mutationsMainOne',arr) }, async actionsMovie({commit}){ let data = await watchContent(); // console.log(data[0].list); // console.log(data[1].list); // console.log(data[2].list); var arr = [data[0].list,data[1].list,data[2].list]; commit('mutationsMovie',arr) }, async actionsList({commit}){ let data = await movieList(); var arr = [data[0].list,data[1].list,data[2].list]; console.log(arr) commit('mutationsMovieList',arr) }, async actionsVideo({commit}){ let data = await smallVideo(); var arr = [data[1].list]; commit('mutationsVideo',arr) }, async actionsFilm({commit}){ let data = await filmReview(); // console.log(data) var arr = [data[0].list]; // console.log(arr) commit('mutationsFilm',arr) } }<file_sep>/src/router/movieList/movieList.js export default{ path:"/movieList", name:"movieList", component:() => import("@components/movieList/movieList.vue"), meta:{ flag:2, TabBarFlag:true } }<file_sep>/src/main.js import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import VueLazyload from "vue-lazyload" import axios from "axios" import BScroll from '@common/BScroll/BScroll' import VueTouch from "vue-touch";//引入点击事件组件 Vue.use(VueLazyload) Vue.prototype.$axios = axios; // axios.defaults.baseURL ="/api";//方法二:这里不写,下面的响应头设置就无效. // axios.defaults.headers.post['Content-Type'] = 'application/json';//方法二 Vue.use(VueTouch, {name: 'v-touch'})//使用点击事件组件 Vue.config.productionTip = false Vue.component("BScroll",BScroll); new Vue({ router, store, render: h => h(App) }).$mount('#app') <file_sep>/src/utils/http.js import axios from 'axios' const server = axios.create({ baseURL:process.env.BASE_API, // withCredentials:true }) server.interceptors.request.use((config)=>{ config.data = JSON.stringify(config.data) //返回数据格式 config.headers = {//设置请求头部 'Content--Type':'application/x-www-form-urlencoded;charset=UTF-8' } return config; },(e)=>{ return Promise.reject(e); }) server.interceptors.response.use((res)=>{ if(res.statusText == "OK"){ return res.data; } },(e)=>{ return Promise.reject(e); }) export const http = (method,url,data={})=>{ if(method == "get"){ return server.get(url,{ params:data }) }else if(method == "post"){ return server.post(url,data); }else{ return; } }<file_sep>/src/router/filmReview/filmReview.js export default{ path:"/filmReview", component:() => import("@components/filmReview/filmReview.vue"), meta:{ flag:4, TabBarFlag:true } }<file_sep>/src/router/index.js import Vue from 'vue' import Router from "vue-router"; import discover from "./discover" import discoverShopping from './shopping' import search from './search' import informations from './informations' import newDetail from './information_newDetail' import BuyTicket from "./BuyTicket" import cinemaSearch from "./cinemaSearch" import homePage from "./homePage/index" import watchMovie from './watchMovie/watchMovie' import movieList from './movieList/movieList' import smallVideo from './smallVideo/smallVideo' import filmReview from './filmReview/filmReview' Vue.use(Router) export default new Router({ mode: 'hash', routes: [ { path:"/", redirect:"/FP" }, discover, discoverShopping, search, informations, newDetail, cinemaSearch, BuyTicket, homePage, watchMovie, movieList, smallVideo, filmReview ] }) <file_sep>/src/store/discover/state.js export default { discover_banner:JSON.parse(window.sessionStorage.getItem("discover_banner")) || [], discover_menu:JSON.parse(window.sessionStorage.getItem("discover_menu")) || [], discover_information:JSON.parse(window.sessionStorage.getItem("discover_information")) || [], discover_shop: JSON.parse(window.sessionStorage.getItem("discover_shop")) || [] , informationsData:JSON.parse(window.sessionStorage.getItem("discover_informationsData")) || {}, }<file_sep>/src/router/discover/index.js export default { path:'/discover', name:'discover', component:()=>import("@views/discover/Discover"), meta :{ TabBarFlag:true } }<file_sep>/src/router/smallVideo/smallVideo.js export default{ path:"/smallVideo", component:() => import("@components/smallVideo/smallVideo.vue"), meta:{ flag:3, TabBarFlag:true } }<file_sep>/src/store/BuyTicket/mutations.js export default { mutationsMovieNow(state,params){ state.movieNowList = params; }, mutationsMovieComing(state,params){ state.movieComingList = params; }, mutationsCinema(state,params){ state.cinemaList = params; } }<file_sep>/src/router/information_newDetail/index.js export default { path:"/newDetail/:movieId", name:"details", component:()=>import("@components/informations/newDetail/newDetail"), props:true, meta:{ } }
3349205c8eda93e0540b81fde79a700062799e85
[ "JavaScript" ]
20
JavaScript
thisismykingdomcome/migu
76df466102ebb659fdd8aa11018c4a0e9ae7e473
e143458458d070c00f788a472a0cee51f1dd945f
refs/heads/master
<repo_name>litangyu/VrEarthMoon<file_sep>/VrEarthMoon/app/src/main/java/com/example/wanghui26/vrearthmoon/Space.java package com.example.wanghui26.vrearthmoon; import android.opengl.GLES20; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; /** * Created by wanghui26 on 2017/1/18. */ public class Space { String mVertexShader; String mFragShader; private int mProgram; private int muMVPMatrixHandle; private int maPositionHandle; private int muPointSizeHandle; private int vCount; private float yAngle; private float scale; FloatBuffer mVertexBuffer; static final float UNIT_SIZE = 10f; public Space(float scale, float yAngle, int vCount, MainActivity mainActivity) { this.scale = scale; this.yAngle = yAngle; this.vCount = vCount; initVertexData(); initShader(mainActivity); } private void initVertexData() { float vertices[] = new float[vCount * 3]; for(int i = 0; i < vCount; i++) { double angleTempJD = Math.PI * 2 * Math.random(); // 方位角 double angleTempWD = Math.PI * (Math.random() - 0.5f); // 仰角,-90~90 vertices[3 * i] = (float) (UNIT_SIZE * Math.cos(angleTempWD) * Math.sin(angleTempJD)); vertices[3 * i + 1] = (float) (UNIT_SIZE * Math.sin(angleTempWD)); vertices[3 * i + 2] = (float)(UNIT_SIZE * Math.cos(angleTempWD) * Math.cos(angleTempJD)); } ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4); vbb.order(ByteOrder.nativeOrder()); mVertexBuffer = vbb.asFloatBuffer(); mVertexBuffer.put(vertices); mVertexBuffer.position(0); } private void initShader(MainActivity mainActivity) { mVertexShader = ShaderUtil.loadFromAssetsFile("vertexSpace.sh", mainActivity.getResources()); mFragShader = ShaderUtil.loadFromAssetsFile("fragSpace.sh", mainActivity.getResources()); mProgram = ShaderUtil.createProgram(mVertexShader, mFragShader); muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix"); maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition"); muPointSizeHandle = GLES20.glGetAttribLocation(mProgram, "uPointSize"); } public void drawSelf() { GLES20.glUseProgram(mProgram); GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, MatrixState.getFinalMatrix(), 0); GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false, 3 * 4, mVertexBuffer); GLES20.glUniform1f(muPointSizeHandle, scale); GLES20.glEnableVertexAttribArray(maPositionHandle); GLES20.glDrawArrays(GLES20.GL_POINTS, 0, vCount); } } <file_sep>/VrEarthMoon/app/src/main/assets/fragEarth.sh precision mediump float; varying vec2 vTextureCoor; varying vec4 vDiffuse; varying vec4 vAmbient; varying vec4 vSpecular; uniform sampler2D sTextureDay; uniform sampler2D sTextureNight; void main() { vec4 finalColorDay; vec4 finalColorNight; finalColorDay = texture2D(sTextureDay, vTextureCoor); finalColorDay = finalColorDay * vAmbient + finalColorDay * vDiffuse + finalColorDay * vSpecular; finalColorNight = texture2D(sTextureNight, vTextureCoor); finalColorNight = finalColorNight * vec4(0.5, 0.5, 0.5, 1.0); if(vDiffuse.x > 0.21) { gl_FragColor = finalColorDay; } else if(vDiffuse.x < 0.05) { gl_FragColor = finalColorNight; } else { float t = (vDiffuse.x - 0.05) / 0.16; gl_FragColor = t * finalColorDay + (1.0 - t) * finalColorNight; } } <file_sep>/VrEarthMoon/app/src/main/java/com/example/wanghui26/vrearthmoon/Constant.java package com.example.wanghui26.vrearthmoon; /** * Created by wanghui26 on 2016/12/20. */ public class Constant { public static int CURR_DRAW_MODE = 0; public static final int GL_POINTS = 0; public static final int GL_LINES = 1; public static final int GL_LINES_STRIP = 2; public static final int GL_LINES_LOOP = 3; public static final float UNIT_SIZE = 1.0f; public static float ratio; public static boolean threadFlag = true; } <file_sep>/VrEarthMoon/app/src/main/assets/fragMoon.sh precision mediump float; varying vec4 vDiffuse; varying vec4 vAmbient; varying vec4 vSpecular; varying vec2 vTextureCoor; uniform sampler2D sTexture;//纹理内容数据 void main() { vec4 finalColor = texture2D(sTexture, vTextureCoor); gl_FragColor = finalColor * vAmbient + finalColor * vSpecular + finalColor * vDiffuse; //gl_FragColor = finalColor; } <file_sep>/VrEarthMoon/app/src/main/assets/vertexEarth.sh uniform mat4 uMVPMatrix; uniform mat4 uMMatrix; uniform vec3 uCamera; uniform vec3 uLightLocationSun; attribute vec3 aPosition; attribute vec2 aTexCoor; attribute vec3 aNormal; varying vec4 vDiffuse; varying vec4 vAmbient; varying vec4 vSpecular; varying vec2 vTextureCoor; void pointLight( in vec3 normal, inout vec4 ambient, inout vec4 diffuse, inout vec4 specular, in vec3 lightLocation, in vec4 lightAmbient, in vec4 lightDiffuse, in vec4 lightSpecular ) { ambient = lightAmbient; vec3 normalTarget = aPosition + normal; vec3 newNormal = (uMMatrix * vec4(normalTarget, 1)).xyz - (uMMatrix * vec4(aPosition, 1)).xyz; newNormal = normalize(newNormal); vec3 eye = normalize(uCamera - (uMMatrix * vec4(aPosition, 1)).xyz); vec3 vp = normalize(lightLocation - (uMMatrix * vec4(aPosition, 1.0)).xyz); vp = normalize(vp); vec3 halfVector = normalize(vp + eye); float shininess = 50.0f; float nDotViewPositon = max(0.0, dot(newNormal, vp)); diffuse = lightDiffuse * nDotViewPositon; float nDotViewHalfVector = dot(newNormal, halfVector); float powerFactor = max(0.0, pow(nDotViewHalfVector, shininess)); specular = lightSpecular * powerFactor; } void main() { vec4 diffuseTmp = vec4(0.0, 0.0, 0.0, 0.0); vec4 ambientTmp = vec4(0.0, 0.0, 0.0, 0.0); vec4 specularTmp = vec4(0.0, 0.0, 0.0, 0.0); pointLight(normalize(aNormal), ambientTmp, diffuseTmp, specularTmp, uLightLocationSun, vec4(0.05, 0.05, 0.05, 1.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.3, 0.3, 0.3, 1.0)); //pointLight(normalize(aNormal), ambientTmp, diffuseTmp, specularTmp, uLightLocationSun, vec4(1.0, 1.0, 0.5, 1.0), vec4(1.0, 1.0, 0.5, 1.0), vec4(1.0, 1.0, 0.5, 1.0)); vAmbient = ambientTmp; vSpecular = specularTmp; vDiffuse = diffuseTmp; vTextureCoor = aTexCoor; gl_Position = uMVPMatrix * vec4(aPosition, 1); }<file_sep>/README.md # VrEarthMoon Draw Earth-Moon with Android Daydream SDK Develop a native app with OpenGL ES, then porting it to Daydream SDK. <file_sep>/VrEarthMoon/app/src/main/assets/vertexSpace.sh uniform mat4 uMVPMatrix; uniform float uPointSize; attribute vec3 aPosition; void main() { gl_Position = uMVPMatrix * vec4(aPosition, 1); gl_PointSize = uPointSize; }
a639f6d0e949219b426bab7d6a15541580637c28
[ "Markdown", "Java", "Shell" ]
7
Java
litangyu/VrEarthMoon
c975bc7e8a2407f910fdcd05b9baa90d72687bd9
8f52929c04eb1e594052001253c8241b83fb9c51
refs/heads/master
<repo_name>lcserny/hibernate<file_sep>/src/main/java/com/teamtreehouse/hibernate/JdbcMain.java package com.teamtreehouse.hibernate; import java.sql.*; /** * Created by leonardo on 10.04.2016. */ public class JdbcMain { public static void main(String[] args) throws ClassNotFoundException { Class.forName("org.sqlite.JDBC"); try (Connection connection = DriverManager.getConnection("jdbc:sqlite:contactmgr.db")) { Statement statement = connection.createStatement(); statement.executeUpdate("DROP TABLE IF EXISTS contacts"); statement.executeUpdate("CREATE TABLE contacts (id INTEGER PRIMARY KEY, firstname STRING, lastname STRING, email STRING, phone INT(10))"); Contact leo = new Contact("Leonardo", "Cserny", "<EMAIL>", 351315); save(leo, statement); Contact sabina = new Contact("Sabina", "Hodorog", "<EMAIL>", 8814351); save(sabina, statement); // statement.executeUpdate("INSERT INTO contacts (firstname, lastname, email, phone) VALUES ('Leonardo', 'Cserny', '<EMAIL>', 351315)"); // statement.executeUpdate("INSERT INTO contacts (firstname, lastname, email, phone) VALUES ('Sabina', 'Hodorog', '<EMAIL>', 8814351)"); ResultSet resultSet = statement.executeQuery("SELECT * FROM contacts"); while (resultSet.next()) { int id = resultSet.getInt("id"); String firstName = resultSet.getString("firstname"); String lastName = resultSet.getString("lastname"); System.out.printf("%s, %s with id: %d%n", firstName, lastName, id); } } catch (SQLException ex) { System.err.printf("There was a database error: %s%n", ex.getMessage()); } } public static void save(Contact contact, Statement statement) throws SQLException { // compose query String sql = "insert into contacts (firstname, lastname, email, phone) values ('%s', '%s', '%s', %d)"; sql = String.format(sql, contact.getFirstName(), contact.getLastName(), contact.getEmail(), contact.getPhone()); // execute query statement.executeUpdate(sql); } }
322407e1f58368a3274131d0a95a319ef4e8d9ec
[ "Java" ]
1
Java
lcserny/hibernate
583486ad7351f57584edf20e9ac2a2bd9e235cef
3e03b1e2e28dd1aaaaeb54453496fa8b478d9161
refs/heads/master
<file_sep>package de.tuda.sdm.dmdb.access.exercise; import de.tuda.sdm.dmdb.storage.AbstractPage; import de.tuda.sdm.dmdb.storage.AbstractRecord; import de.tuda.sdm.dmdb.storage.PageManager; import de.tuda.sdm.dmdb.storage.Record; import de.tuda.sdm.dmdb.storage.exercise.RowPage; import de.tuda.sdm.dmdb.storage.types.AbstractSQLValue; import de.tuda.sdm.dmdb.access.RowIdentifier; import de.tuda.sdm.dmdb.access.HeapTableBase; public class HeapTable extends HeapTableBase { /** * * Constructs table from record prototype * @param prototypeRecord */ public HeapTable(AbstractRecord prototypeRecord) { super(prototypeRecord); } @Override public RowIdentifier insert(AbstractRecord record) { if (!this.lastPage.recordFitsIntoPage(record)) { this.lastPage = PageManager.createDefaultPage(this.prototype.getFixedLength()); this.addPage(lastPage); } this.lastPage.insert(record); return new RowIdentifier(this.lastPage.getPageNumber(), this.lastPage.getNumRecords()-1); } @Override public AbstractRecord lookup(int pageNumber, int slotNumber) { AbstractPage ap = this.getPage(pageNumber); AbstractRecord res = this.prototype.clone(); try { ap.read(slotNumber, res); } catch (Exception e) { System.out.println(e.getMessage()); } return res; } } <file_sep>package de.tuda.sdm.dmdb.storage.types.exercise; import java.util.Arrays; import de.tuda.sdm.dmdb.storage.types.SQLIntegerBase; /** * SQL integer value * * @author cbinnig * */ public class SQLInteger extends SQLIntegerBase { /** * Constructor with default value */ public SQLInteger() { super(); } /** * Constructor with value * * @param value * Integer value */ public SQLInteger(int value) { super(value); } @Override public byte[] serialize() { byte[] result = new byte[4]; result[3] = (byte) this.value; result[2] = (byte) (this.value >> 8); result[1] = (byte) (this.value >> 16); result[0] = (byte) (this.value >> 24); // System.out.println(Arrays.toString(result)); return result; } @Override public void deserialize(byte[] data) { int x = (Byte.toUnsignedInt(data[0])) << 24; x = x | (Byte.toUnsignedInt(data[1])) << 16; x = x | (Byte.toUnsignedInt(data[2])) << 8; x = x | (Byte.toUnsignedInt(data[3])); // System.out.println(x); this.value = x; } @Override public SQLInteger clone() { return new SQLInteger(this.value); } }
6719af4dfaba80423c084f25273dcb8cd53c7dc5
[ "Java" ]
2
Java
qwyster/SDM_Ex1
f3b2c68b3d8cc4ffbec5c85dcede1f5f1153610b
59d146c8ac75699dea2f834134188419bb786ec1
refs/heads/master
<repo_name>baivanco/Magic-The-Gathering<file_sep>/public/js/cards.js //Get User Name From LocalStorage window.addEventListener("load", () => { const name = localStorage.getItem("NAME"); document.getElementById("user-name").innerHTML = name; }); //Loading Screen const spinner = document.getElementById("spinner"); function showSpinner() { spinner.className = "show"; } function hideSpinner() { spinner.className = "hide"; } //Search and Filter - Searchbar const searchField = document.getElementById("search-n-t"); let displayCards = []; searchField.addEventListener("keyup", (e) => { const searchString = e.target.value.toLowerCase(); const filteredCards = displayCards.filter((card) => { return card.name.toLowerCase().includes(searchString); }); displayTheCards(filteredCards); }); // Filter by types function showSelectedType() { const selectedType = document.getElementById("types").value; const filteredCardType = displayCards.filter((card) => { return card.types.includes(selectedType); }); if (filteredCardType.length == 0) { cardsList.innerHTML = `<h2 style="color:white">" No cards found for chosen type "</h2>`; } else { displayTheCards(filteredCardType); } } // Filter by color function showSelectedColor() { const selectedColors = document.getElementById("colors").value; const filteredCardColors = displayCards.filter((card) => { return card.colors.includes(selectedColors); }); displayTheCards(filteredCardColors); } //Sort By Name sortByNameAsc = () => { const filterNames = displayCards.sort((a, b) => a.name.toString().toLowerCase() > b.name.toString().toLowerCase() ? 1 : -1 ); displayTheCards(filterNames); }; sortByNameDesc = () => { const filterNames = displayCards.sort((a, b) => a.name.toString().toLowerCase() < b.name.toString().toLowerCase() ? 1 : -1 ); displayTheCards(filterNames); }; //Fetch API const cardsList = document.getElementById("cardsList"); const loadCards = async () => { try { const res = await fetch( "https://api.magicthegathering.io/v1/cards?random=true&pageSize=100&language=English" ); mgtCards = await res.json(); displayCards = mgtCards.cards; displayTheCards(mgtCards.cards); } catch (err) { if (err) { cardsList.innerHTML = `<h1 style="color:white">"SERVER ERROR PLEASE TRY AGAIN LATER"</h1>`; } console.error(err); } hideSpinner(); }; //Rendering the cards const displayTheCards = (cards) => { const htmlString = cards .map((card) => { return ` <li class="card"> <h2>${card.name}</h2> <img src=${card.imageUrl} width=200px onerror="this.src='../images/card-back-not-found.jpg'" ></img> <p> Types: ${card.types}</p> <p> Set Name: ${card.setName}</p> <p> Colors: <span style="color:${card.colors};">${card.colors}</span></p> </li> `; }) .join(""); cardsList.innerHTML = htmlString; }; showSpinner(); loadCards(); <file_sep>/README.md # Magic The Gathering List, search and filter MGT cards from API \ No frameworks and libraries used just plain JS ## Short Intro Two paged application for preview and searching MGT cards.\ Home page with user name input and simple validation.\ Second page with API fetch, listed cards and search/filter options. ## User Guide Just download the .zip - extract and run index.html\ "Magic-The-Gathering-master\public\index.html"\ ## Preview image ![preview image](https://user-images.githubusercontent.com/45272390/95723280-426bcc80-0c75-11eb-96e5-273f924ca406.jpg) <file_sep>/public/js/index.js //Submit Name to LocalStorage function handleSubmit() { const name = document.getElementById("name").value; localStorage.setItem("NAME", name); return; } //Input FORM Validation function validateForm() { var name = document.getElementById("name").value; //Minimum 3 characters Validation if (name.length < 3) { document.getElementById("min-char").style.display = "block"; return false; } else { document.getElementById("min-char").style.display = "none"; } //First character Uppercase Validation if (name[0] == name[0].toLowerCase()) { document.getElementById("first-upper").style.display = "block"; return false; } else { document.getElementById("first-upper").style.display = "none"; } return; }
24491edc7c8515d89cac792e490c331bba016da4
[ "JavaScript", "Markdown" ]
3
JavaScript
baivanco/Magic-The-Gathering
cf515d63b7726c5aa3210fc1a9217751d808ac02
e2fa80fd6fa865549e625ed6d97d83df643be5f7
refs/heads/master
<repo_name>william084531/PyQt-image-annotation-tool<file_sep>/annotation/annotation_object/My_rectitem.py from PyQt5.QtWidgets import QGraphicsRectItem, QGraphicsItem from PyQt5.QtGui import QPen, QCursor, QColor, QBrush from PyQt5.QtCore import Qt, QRectF, QPointF from .My_gripItem import My_gripItem class My_rectitem(QGraphicsRectItem): def __init__(self, lastpos): super(My_rectitem, self).__init__() self.setFlag(QGraphicsItem.ItemIsMovable, True) self.setFlag(QGraphicsItem.ItemIsSelectable, True) self.setAcceptHoverEvents(True) pen = QPen(Qt.green) pen.setWidth(2) pen.setCosmetic(True) self.setPen(pen) self.setCursor(QCursor(Qt.PointingHandCursor)) self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) self.lastpos = lastpos self.pos = [] self.rect_point = [] self.m_items = [] def move_rect(self, point): self.pos = point point_use = [[self.lastpos.x(), self.pos.x()], [self.lastpos.y(), self.pos.y()]] self.setRect(QRectF(QPointF(min(point_use[0]), min(point_use[1])), QPointF(max(point_use[0]), max(point_use[1])))) def movePoint(self, i, p): if 0 <= i < len(self.rect_point): self.rect_point[i] = self.mapFromScene(p) rect_use = [[self.rect_point[0].x(), self.rect_point[1].x()], [self.rect_point[0].y(), self.rect_point[1].y()]] if i == 0: self.setRect(QRectF(QPointF(min(rect_use[0]), min(rect_use[1])), QPointF(max(rect_use[0]), max(rect_use[1])))) else: self.setRect(QRectF(QPointF(min(rect_use[0]), min(rect_use[1])), QPointF(max(rect_use[0]), max(rect_use[1])))) print("move_item", rect_use) def move_item(self, index, pos): if 0 <= index < len(self.m_items): item = self.m_items[index] item.setEnabled(False) item.setPos(pos) item.setEnabled(True) def addPoint(self, p): self.rect_point = p self.setRect(QRectF(p[0], p[1])) for i in range(len(p)): item = My_gripItem(self, i, 1) self.scene().addItem(item) self.m_items.append(item) item.setPos(self.rect_point[i]) def itemChange(self, change, value): if change == QGraphicsItem.ItemPositionHasChanged: for i, point in enumerate(self.rect_point): self.move_item(i, self.mapToScene(point)) return super(My_rectitem, self).itemChange(change, value) def hoverEnterEvent(self, event): self.setBrush(QColor(0, 100, 100, 100)) super(My_rectitem, self).hoverEnterEvent(event) def hoverLeaveEvent(self, event): self.setBrush(QBrush(Qt.NoBrush)) super(My_rectitem, self).hoverLeaveEvent(event)<file_sep>/annotation/annotation_object/My_lineitem.py from PyQt5.QtWidgets import QGraphicsLineItem, QGraphicsItem, QStyleOptionGraphicsItem from PyQt5.QtGui import QPen, QPainter from PyQt5.QtCore import Qt class My_lineitem(QGraphicsLineItem): def __init__(self, lastpos): super(My_lineitem, self).__init__() self.setFlag(QGraphicsItem.ItemIsMovable, True) self.setFlag(QGraphicsItem.ItemIsSelectable, True) pen = QPen(Qt.green) pen.setWidth(2) pen.setCosmetic(True) self.setPen(pen) self.lastpos = lastpos self.pos = None def move_line(self, point): self.pos = point self.setLine(self.pos.x(), self.pos.y(), self.lastpos.x(), self.lastpos.y()) <file_sep>/annotation/main.py from PyQt5.QtWidgets import QApplication import sys # from annotation.image_window_test import window from annotation_object.image_window import window if __name__ == "__main__": app = QApplication(sys.argv) window = window() window.show() sys.exit(app.exec()) # class window(QMainWindow): # def __init__(self, parent=None): # super(window, self).__init__(parent) # self.title = "PyQt5 Graphic View Test cat" # self.top = 100 # self.left = 100 # self.width = 1000 # self.height = 800 # self.view = MyGraphicsView() # self.setCentralWidget(self.view) # self.view.setMouseTracking(True) # self.InitWindow() # # def InitWindow(self): # self.importbutton = QPushButton("file import ", self) # self.importbutton.setGeometry(self.width - 150, 20, 100, 50) # self.importbutton.clicked.connect(self.view.import_image) # self.importjsonbutton = QPushButton("json import ", self) # self.importjsonbutton.setGeometry(self.width - 150, 90, 100, 50) # self.importjsonbutton.clicked.connect(self.view.import_json) # self.Rotateleftbutton = QPushButton("Rotate-L ", self) # self.Rotateleftbutton.setGeometry(self.width-150, 160, 100, 50) # self.Rotateleftbutton.clicked.connect(self.view.rotate_left) # self.Rotaterightbutton = QPushButton("Rotate-R ", self) # self.Rotaterightbutton.setGeometry(self.width-150, 230, 100, 50) # self.Rotaterightbutton.clicked.connect(self.view.rotate_right) # self.Zoominbutton = QPushButton("Zoom_in", self) # self.Zoominbutton.setGeometry(self.width-150, 300, 100, 50) # self.Zoominbutton.clicked.connect(self.view.zoom_in) # self.Zoomoutbutton = QPushButton("Zoom_out", self) # self.Zoomoutbutton.setGeometry(self.width-150, 370, 100, 50) # self.Zoomoutbutton.clicked.connect(self.view.zoom_out) # self.Originalbutton = QPushButton("Original_view", self) # self.Originalbutton.setGeometry(self.width - 150, 440, 100, 50) # self.Originalbutton.clicked.connect(self.view.original_view) # self.enablepolygonsbutton = QPushButton("create_polygens", self) # self.enablepolygonsbutton.setGeometry(self.width-270, 20, 100, 50) # self.enablepolygonsbutton.clicked.connect(self.view.scene.enable_polygons) # self.enablerectsbutton = QPushButton("create_rect", self) # self.enablerectsbutton.setGeometry(self.width - 270, 90, 100, 50) # self.enablerectsbutton.clicked.connect(self.view.scene.enable_rect) # self.undobutton = QPushButton("undo", self) # self.undobutton.setGeometry(self.width - 270, 160, 100, 50) # self.undobutton.clicked.connect(self.view.scene.undo) # self.delet_item = QPushButton("delet_item", self) # self.delet_item.setGeometry(self.width - 270, 230, 100, 50) # self.delet_item.clicked.connect(self.view.scene.delete) # self.delet_all = QPushButton("delet_all_item", self) # self.delet_all.setGeometry(self.width - 270, 300, 100, 50) # self.delet_all.clicked.connect(self.view.scene.delete_all) # self.savebutton = QPushButton("save", self) # self.savebutton.setGeometry(self.width - 270, 370, 100, 50) # self.savebutton.clicked.connect(self.view.save_image) # self.savejsonbutton = QPushButton("save json", self) # self.savejsonbutton.setGeometry(self.width - 270, 440, 100, 50) # self.savejsonbutton.clicked.connect(self.view.save_json) # # # TODO: delet function # # self.removebutton = QPushButton("removeitem", self) # # self.removebutton.setGeometry(self.width - 150, 650, 100, 50) # # self.removebutton.clicked.connect(self.removeitem) # # self.setWindowIcon(QtGui.QIcon("C:/Users/willi/Desktop/classification/data_annotated/0001.jpg")) # self.setWindowTitle(self.title) # self.setGeometry(self.top, self.left, self.width, self.height) # if self.Rect_flag == 1: # self.view.setDragMode(QGraphicsView.RubberBandDrag) # class MyGraphicsScene(QGraphicsScene): # def __init__(self, parent=None): # super(MyGraphicsScene, self).__init__(parent) # self._parent = parent # self.Polygon_flag = 0 # self.Rect_flag = 0 # self.rubberband_select_flag = 0 # self.lastpos = [] # self.polygon = [] # self.rect = [] # self.line_item_list = [] # self.Grip_item_list = [] # self.view = MyGraphicsView() # # # def enable_polygons(self): # self.Polygon_flag = 1 # self.Rect_flag = 0 # # def enable_rect(self): # self.Rect_flag = 1 # self.Polygon_flag = 0 # # def undo(self): # # # TODO: if future need redo this function should change because it kill the last element # # # kill point # if len(self.polygon) >= 1: # self.removeItem(self.itemAt(self.polygon[-1].x(), self.polygon[-1].y(), self.view.transform())) # self.removeItem(self.itemAt(self.polygon[-1].x(), self.polygon[-1].y(), self.view.transform())) # del self.polygon[-1] # if len(self.polygon) == 1: # self.lastpos = [] # else: # print("can't undo") # # def delete(self): # if self.selectedItems() != [] and self.rubberband_select_flag !=1: # selecteditem = self.selectedItems() # for idx in range(len(selecteditem)): # selecteditem = selecteditem + selecteditem[idx].m_items # # selecteditem = selecteditem+selecteditem[0].m_items # for i in selecteditem: # self.removeItem(i) # # elif self.selectedItems() != [] and self.rubberband_select_flag ==1: # # self.rubberband_select_flag = 0 # # selecteditem = self.selectedItems() # # for i in selecteditem: # # self.removeItem(i) # else: # print("can't delete") # # def delete_all(self): # if self.selectedItems() != [] and self.rubberband_select_flag ==1: # self.rubberband_select_flag = 0 # selecteditem = self.selectedItems() # for i in selecteditem: # self.removeItem(i) # else: # print("can't delete all") # # def load_polygon_item(self, point): # for i in point: # self.polygon_item = PolygonAnnotation() # self.addItem(self.polygon_item) # self.polygon_item.addPoint(i) # # self.polygon_item.addPoint(i) # # def load_rect_item(self, point): # for i in point: # self.rect_item = rect(i[0]) # self.addItem(self.rect_item) # self.rect_item.addPoint(i) # # self.rect_item.addPoint(i) # # def mousePressEvent(self, event): # if event.button() == Qt.RightButton: # self.rubberband_select_flag = 1 # #window.view.setDragMode(QGraphicsView.RubberBandDrag) # self._parent.setDragMode(QGraphicsView.RubberBandDrag) # # if event.button() == Qt.LeftButton: # self.rubberband_select_flag = 0 # self._parent.setDragMode(QGraphicsView.ScrollHandDrag) # pos = event.scenePos() # if self.Polygon_flag == 1: # self._parent.setDragMode(QGraphicsView.NoDrag) # # self.polygon_item cannot put in intiital # self.polygon_item = PolygonAnnotation() # # to get all point coordinate # self.polygon.append(pos) # # catch the last element as x, y coordinate # x = self.polygon[-1].x() # y = self.polygon[-1].y() # if self.lastpos == []: # self.lastpos = [self.polygon[-1].x(), self.polygon[-1].y()] # else: # self.lastpos[0] = self.polygon[-2].x() # self.lastpos[1] = self.polygon[-2].y() # # add circle point in scene # if self._parent.import_flag == 1: # point = GripItem(self.polygon_item, len(self.polygon)) # self.addItem(point) # self.Grip_item_list.append(point) # point.setPos(self.polygon[-1]) # print(self.lastpos) # self.line_Item = line(self.polygon[-1]) # self.addItem(self.line_Item) # self.line_item_list.append(self.line_Item) # # elif self.Rect_flag == 1 and self.rect == [] and self._parent.import_flag == 1: # self._parent.setDragMode(QGraphicsView.NoDrag) # # to get all point coordinate # self.rect.append(pos) # self.square = rect(self.rect[0]) # self.addItem(self.square) # # elif self.Rect_flag == 1 and self.rect != [] and self._parent.import_flag == 1: # self.Rect_flag = 0 # pos = event.scenePos() # self.rect.append(pos) # self.square.addPoint(self.rect) # # TODO: save special info for this rect item use setData # # self.square.setData(3, "test_rect") # self.rect = [] # super(MyGraphicsScene, self).mousePressEvent(event) # # def mouseReleaseEvent(self, event): # QGraphicsScene.mouseReleaseEvent(self, event) # self._parent.setDragMode(QGraphicsView.NoDrag) # # # def mouseMoveEvent(self, event): # # call basic function # QGraphicsScene.mouseMoveEvent(self, event) # if self.Polygon_flag == 1 and self._parent.import_flag == 1 and self.lastpos != []: # self.line_Item.move_line(event.scenePos()) # if self.Rect_flag == 1 and self.rect != []: # self.square.move_rect(event.scenePos()) # print(self.rect) # # # def mouseDoubleClickEvent(self, event): # if event.button() == Qt.LeftButton: # if self.Polygon_flag == 1: # self.Polygon_flag = 0 # for i in range(len(self.Grip_item_list)): # self.removeItem(self.Grip_item_list[i]) # self.removeItem(self.line_item_list[i]) # self.addItem(self.polygon_item) # self.polygon_item.addPoint(self.polygon) # # TODO: save special info for this polygon item use setData # # self.polygon_item.setData(5, "test_polygon") # self.polygon = [] # self.lastpos = [] # super(MyGraphicsScene, self).mouseDoubleClickEvent(event) # class MyGraphicsView(QGraphicsView): # def __init__(self): # QGraphicsView.__init__(self) # self.setMouseTracking(True) # self._dlg_file = QFileDialog() # self.scene = MyGraphicsScene(self) # self.setScene(self.scene) # # for zoom in zoom out # self.unit_in = 2 # self.unit_out = 1 / 2 # self.imageName_ = None # self.jsonName_ = None # self.pixmap = None # self.save_jsonName = '' # self.jsonName_ = '' # self.import_flag = 0 # self.transform_initial = self.transform() # self.zoom_flag = 0 # # def import_image(self): # # clear all item in view # self.scene.clear() # self.scene.lastpos = [] # self.scene.polygon = [] # self.scene.Polygon_flag = 0 # self.scene.Rect_flag = 0 # # import image # options = self._dlg_file.Options() # self.imageName_, _ = self._dlg_file.getOpenFileName(self, "Read Image", "", # "Image Files (*.png *.jpg *.jpeg *.gif *.tiff *.tif);;All Files (*)", # options=options) # self.pixmap = QPixmap(self.imageName_) # photo = QGraphicsPixmapItem(self.pixmap) # # change graphic view free # self.viewport().installEventFilter(self) # self.setGeometry(0, 0, self.pixmap.width()+10, self.pixmap.height()+10) # self.setTransform(self.transform_initial) # self.scene.addItem(photo) # self.import_flag = 1 # # # # def import_json(self): # self.scene.clear() # self.scene.lastpos = [] # self.scene.polygon = [] # self.scene.Polygon_flag = 0 # self.scene.Rect_flag = 0 # options = self._dlg_file.Options() # self.jsonName_, _ = self._dlg_file.getOpenFileName(self, "Read Json", "", # "Json Files (*.json);;All Files (*)", # options=options) # if self.jsonName_ !='': # self.import_flag = 1 # with open(self.jsonName_, 'r') as reader: # jf = json.loads(reader.read()) # # # to turn string back to byte # image_json = jf["image"].encode(encoding="utf-8") # ba = QByteArray.fromBase64(image_json) # img = QImage.fromData(ba, 'PNG') # self.pixmap = QPixmap.fromImage(img) # photo = QGraphicsPixmapItem(self.pixmap) # self.viewport().installEventFilter(self) # self.setGeometry(0, 0, self.pixmap.width() + 10, self.pixmap.height() + 10) # self.scene.addItem(photo) # if jf["polygon"] != []: # all_poly_item = [] # for i in jf["polygon"]: # single_poly_item = [] # for j in i: # single_poly_item.append(QPointF(j[0], j[1])) # all_poly_item.append(single_poly_item) # # TODO: make mainwindow not only show a item, not to get this error "wrapped C/C++ object of type XXXX has been deleted" # print("test") # self.scene.load_polygon_item(all_poly_item) # else: # print("no polygon") # if jf["rect"] != []: # all_rect_item = [] # for i in jf["rect"]: # single_rect_item = [] # for j in i: # single_rect_item.append(QPointF(j[0], j[1])) # all_rect_item.append(single_rect_item) # self.scene.load_rect_item(all_rect_item) # else: # print("no rect") # else: # print("no json import") # # def rotate_left(self): # if self.import_flag == 1: # self.rotate(-10) # # to get current transformation matrix for the view # elif self.import_flag != 1: # print("no image import") # # def rotate_right(self): # if self.import_flag == 1: # self.rotate(10) # # to get current transformation matrix for the view # elif self.import_flag != 1: # print("no image import") # def zoom_in(self): # if self.import_flag == 1 and self.zoom_flag < 4: # self.zoom_flag +=1 # self.scale(self.unit_in, self.unit_in) # elif self.import_flag != 1: # print("no image import") # elif self.zoom_flag == 4: # print("can't zoom in") # # to get current transformation matrix for the view # # def zoom_out(self): # if self.import_flag == 1 and self.zoom_flag > -4: # self.zoom_flag -= 1 # self.scale(self.unit_out, self.unit_out) # # to get current transformation matrix for the view # elif self.import_flag != 1: # print("no image import") # elif self.zoom_flag == -4: # print("can't zoom out") # # def original_view(self): # if self.import_flag == 1: # self.zoom_flag = 0 # self.setTransform(self.transform_initial) # # to get current transformation matrix for the view # elif self.import_flag != 1: # print("no image import") # # def save_image(self): # options = self._dlg_file.Options() # if self.pixmap is not None: # # Get region of scene to capture from somewhere. # area = QRectF(0, 0, self.pixmap.width() + 10, self.pixmap.height() + 10) # # # Create a QImage to render to and fix up a QPainter for it. # image = QImage(QRectF.toRect(area).size(), QImage.Format_ARGB32_Premultiplied) # painter = QPainter(image) # # # Render the region of interest to the QImage. # self.scene.render(painter, QRectF(image.rect()), area) # painter.end() # save_imageName, _ = self._dlg_file.getSaveFileName(self, "Save Image", "", # "Image Files (*.png *.jpg *.jpeg *.gif *.tiff *.tif);;All Files (*)", # options=options) # # Save the image to a file. # image.save(save_imageName) # else: # print("can't save image") # def save_json(self): # options = self._dlg_file.Options() # if self.pixmap is not None: # area = QRectF(0, 0, self.pixmap.width() + 10, self.pixmap.height() + 10) # self.select_all_scene = QtGui.QPainterPath() # self.select_all_scene.addRect(area) # self.scene().setSelectionArea(self.select_all_scene, Qt.IntersectsItemShape, self.transform()) # selecteditem = self.scene().selectedItems() # # selecteditem: different object has different type, use, selecteditem[?].type(), can get different object, polygon type == 5, rect type == 3, gripitem type == 2 # polygon_point = [] # rect_point = [] # for i in selecteditem: # if i.type() == 5: # # get polgon item point # each_point_polygon = [] # for j in i.m_points: # each_point_polygon.append([j.x(), j.y()]) # polygon_point.append(each_point_polygon) # elif i.type() == 3: # each_point_rect = [] # each_use = [[i.rect_point[0].x(), i.rect_point[1].x()], [i.rect_point[0].y(), i.rect_point[1].y()]] # for j in i.rect_point: # if j is i.rect_point[0]: # each_point_rect.append([min(each_use[0]), min(each_use[1])]) # else: # each_point_rect.append([max(each_use[0]), max(each_use[1])]) # rect_point.append(each_point_rect) # # save image # PIC = self.pixmap.toImage() # ba = QByteArray() # buffer = QBuffer(ba) # buffer.open(QIODevice.WriteOnly) # PIC.save(buffer, 'PNG') # base64_data = ba.toBase64().data() # image_data = str(base64_data, encoding='utf-8') # # # save to json # annotation_object = { # 'polygon': polygon_point, # 'rect': rect_point, # 'image': image_data} # # self.save_jsonName, _ = self._dlg_file.getSaveFileName(self, "Save Json", "", # "Json Files (*.json);;All Files (*)", options=options) # if self.save_jsonName != '': # with open(self.save_jsonName, 'w') as json_file: # json.dump(annotation_object, json_file) # print("test") # else: # print("no choose save path") # else: # print("can't save json") # def save_json(self): # TODO : make polygon resize # class PolygonAnnotation(QGraphicsPolygonItem): # def __init__(self, parent=None): # super(PolygonAnnotation, self).__init__(parent) # self.m_points = [] # self.setZValue(10) # pen = QPen(Qt.green) # pen.setWidth(2) # pen.setCosmetic(True) # self.setPen(pen) # self.setAcceptHoverEvents(True) # self.setFlag(QGraphicsItem.ItemIsSelectable, True) # self.setFlag(QGraphicsItem.ItemIsMovable, True) # self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) # self.setCursor(QtGui.QCursor(Qt.PointingHandCursor)) # self.view = MyGraphicsView() # self.m_items = [] # self.poly_item = [] # # def number_of_points(self): # return len(self.m_items) # # # def addPoint(self, p): # if self.m_points == []: # self.m_points = p # self.setPolygon(QtGui.QPolygonF(self.m_points)) # for i in range(len(self.m_points)): # item = GripItem(self, i, 1) # self.scene().addItem(item) # self.m_items.append(item) # item.setPos(self.m_points[i]) # # def movePoint(self, i, p): # if 0 <= i < len(self.m_points): # self.m_points[i] = self.mapFromScene(p) # self.setPolygon(QtGui.QPolygonF(self.m_points)) # # print("sss", self.m_points) # # def move_item(self, index, pos): # if 0 <= index < len(self.m_items): # item = self.m_items[index] # item.setEnabled(False) # item.setPos(pos) # item.setEnabled(True) # # def itemChange(self, change, value): # if change == QGraphicsItem.ItemPositionHasChanged: # for i, point in enumerate(self.m_points): # self.move_item(i, self.mapToScene(point)) # return super(PolygonAnnotation, self).itemChange(change, value) # # def hoverEnterEvent(self, event): # self.setBrush(QtGui.QColor(0, 100, 100, 100)) # super(PolygonAnnotation, self).hoverEnterEvent(event) # # def hoverLeaveEvent(self, event): # self.setBrush(QtGui.QBrush(Qt.NoBrush)) # super(PolygonAnnotation, self).hoverLeaveEvent(event) # class line(QGraphicsLineItem): # def __init__(self, lastpos): # super(line, self).__init__() # self.setFlag(QGraphicsItem.ItemIsMovable, True) # self.setFlag(QGraphicsItem.ItemIsSelectable, True) # pen = QPen(Qt.green) # pen.setWidth(2) # pen.setCosmetic(True) # self.setPen(pen) # self.lastpos = lastpos # # def move_line(self, point): # self.pos = point # self.setLine(self.pos.x(), self.pos.y(), self.lastpos.x(), self.lastpos.y()) # # class GripItem(QGraphicsPathItem): # def __init__(self, annotation_item, index, type=0): # super(GripItem, self).__init__() # self.m_annotation_item = annotation_item # self.m_index = index # self.circle = QtGui.QPainterPath() # self.circle.addEllipse(QRectF(-4, -4, 8, 8)) # self.square = QtGui.QPainterPath() # self.square.addRect(QRectF(-4, -4, 8, 8)) # self.setPath(self.circle) # self.setBrush(Qt.green) # self.setFlag(QGraphicsItem.ItemIsSelectable, True) # if type == 1: # self.setFlag(QGraphicsItem.ItemIsMovable, True) # self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) # self.setFlag(QGraphicsItem.ItemIgnoresTransformations) # self.setAcceptHoverEvents(True) # self.setZValue(11) # self.setCursor(QtGui.QCursor(Qt.PointingHandCursor)) # # def hoverEnterEvent(self, event): # self.setPath(self.square) # self.setBrush(Qt.red) # super(GripItem, self).hoverEnterEvent(event) # # def hoverLeaveEvent(self, event): # self.setPath(self.circle) # self.setBrush(Qt.green) # super(GripItem, self).hoverLeaveEvent(event) # # def itemChange(self, change, value): # if change == QGraphicsItem.ItemPositionChange and self.isEnabled(): # self.m_annotation_item.movePoint(self.m_index, value) # return super(GripItem, self).itemChange(change, value) # class rect(QGraphicsRectItem): # def __init__(self, lastpos): # super(rect, self).__init__() # self.setFlag(QGraphicsItem.ItemIsMovable, True) # self.setFlag(QGraphicsItem.ItemIsSelectable, True) # self.setAcceptHoverEvents(True) # pen = QPen(Qt.green) # pen.setWidth(2) # pen.setCosmetic(True) # self.setPen(pen) # self.setCursor(QtGui.QCursor(Qt.PointingHandCursor)) # self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) # self.lastpos = lastpos # self.pos = [] # self.rect_point = [] # self.m_items = [] # self.view = MyGraphicsView() # def move_rect(self, point): # self.pos = point # point_use = [[self.lastpos.x(), self.pos.x()], [self.lastpos.y(), self.pos.y()]] # self.setRect(QRectF(QPointF(min(point_use[0]), min(point_use[1])), QPointF(max(point_use[0]), max(point_use[1])))) # # def movePoint(self, i, p): # if 0 <= i < len(self.rect_point): # self.rect_point[i] = self.mapFromScene(p) # rect_use = [[self.rect_point[0].x(), self.rect_point[1].x()], [self.rect_point[0].y(), self.rect_point[1].y()]] # if i == 0: # self.setRect(QRectF(QPointF(min(rect_use[0]), min(rect_use[1])), QPointF(max(rect_use[0]), max(rect_use[1])))) # else: # self.setRect(QRectF(QPointF(min(rect_use[0]), min(rect_use[1])), QPointF(max(rect_use[0]), max(rect_use[1])))) # # def move_item(self, index, pos): # if 0 <= index < len(self.m_items): # item = self.m_items[index] # item.setEnabled(False) # item.setPos(pos) # item.setEnabled(True) # # def addPoint(self, p): # self.rect_point = p # self.setRect(QRectF(p[0], p[1])) # for i in range(len(p)): # item = GripItem(self, i, 1) # self.scene().addItem(item) # self.m_items.append(item) # item.setPos(self.rect_point[i]) # # def itemChange(self, change, value): # if change == QGraphicsItem.ItemPositionHasChanged: # for i, point in enumerate(self.rect_point): # self.move_item(i, self.mapToScene(point)) # return super(rect, self).itemChange(change, value) # # def hoverEnterEvent(self, event): # self.setBrush(QtGui.QColor(0, 100, 100, 100)) # super(rect, self).hoverEnterEvent(event) # # def hoverLeaveEvent(self, event): # self.setBrush(QtGui.QBrush(Qt.NoBrush)) # super(rect, self).hoverLeaveEvent(event)<file_sep>/annotation/annotation_object/My_polygonitem.py from PyQt5.QtWidgets import QGraphicsPolygonItem, QGraphicsItem from PyQt5.QtGui import QPen, QCursor, QPolygonF, QColor, QBrush, QPainter from PyQt5.QtCore import Qt from .My_gripItem import My_gripItem class My_polygonitem(QGraphicsPolygonItem): def __init__(self, parent=None): super(My_polygonitem, self).__init__(parent) self.m_points = [] self.setZValue(10) pen = QPen(Qt.green) pen.setWidth(2) pen.setCosmetic(True) self.setPen(pen) self.setAcceptHoverEvents(True) self.setFlag(QGraphicsItem.ItemIsSelectable, True) self.setFlag(QGraphicsItem.ItemIsMovable, True) self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) self.setCursor(QCursor(Qt.PointingHandCursor)) self.m_items = [] self.poly_item = [] def number_of_points(self): return len(self.m_items) def addPoint(self, p): if self.m_points == []: self.m_points = p self.setPolygon(QPolygonF(self.m_points)) for i in range(len(self.m_points)): item = My_gripItem(self, i, 1) self.scene().addItem(item) self.m_items.append(item) item.setPos(self.m_points[i]) def movePoint(self, i, p): if 0 <= i < len(self.m_points): self.m_points[i] = self.mapFromScene(p) self.setPolygon(QPolygonF(self.m_points)) print("move_item", self.m_points) def move_item(self, index, pos): if 0 <= index < len(self.m_items): item = self.m_items[index] item.setEnabled(False) item.setPos(pos) item.setEnabled(True) def itemChange(self, change, value): if change == QGraphicsItem.ItemPositionHasChanged: for i, point in enumerate(self.m_points): self.move_item(i, self.mapToScene(point)) return super(My_polygonitem, self).itemChange(change, value) def hoverEnterEvent(self, event): self.setBrush(QColor(0, 100, 100, 100)) super(My_polygonitem, self).hoverEnterEvent(event) def hoverLeaveEvent(self, event): self.setBrush(QBrush(Qt.NoBrush)) super(My_polygonitem, self).hoverLeaveEvent(event) <file_sep>/annotation/annotation_object/My_gripItem.py from PyQt5.QtWidgets import QGraphicsPathItem, QGraphicsItem from PyQt5.QtGui import QPainterPath, QCursor from PyQt5.QtCore import Qt, QRectF class My_gripItem(QGraphicsPathItem): def __init__(self, annotation_item, index, type=0): super(My_gripItem, self).__init__() self.m_annotation_item = annotation_item self.m_index = index self.circle = QPainterPath() self.circle.addEllipse(QRectF(-4, -4, 8, 8)) self.square = QPainterPath() self.square.addRect(QRectF(-4, -4, 8, 8)) self.setPath(self.circle) self.setBrush(Qt.green) self.setFlag(QGraphicsItem.ItemIsSelectable, True) if type == 1: self.setFlag(QGraphicsItem.ItemIsMovable, True) self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) self.setFlag(QGraphicsItem.ItemIgnoresTransformations) self.setAcceptHoverEvents(True) self.setZValue(11) self.setCursor(QCursor(Qt.PointingHandCursor)) def hoverEnterEvent(self, event): self.setPath(self.square) self.setBrush(Qt.red) super(My_gripItem, self).hoverEnterEvent(event) def hoverLeaveEvent(self, event): self.setPath(self.circle) self.setBrush(Qt.green) super(My_gripItem, self).hoverLeaveEvent(event) def itemChange(self, change, value): if change == QGraphicsItem.ItemPositionChange and self.isEnabled(): self.m_annotation_item.movePoint(self.m_index, value) return super(My_gripItem, self).itemChange(change, value)<file_sep>/annotation/annotation_object/image_scene.py from PyQt5.QtWidgets import QGraphicsScene, QGraphicsView from .My_polygonitem import My_polygonitem from .My_rectitem import My_rectitem from .My_gripItem import My_gripItem from .My_lineitem import My_lineitem from PyQt5.QtCore import Qt from PyQt5.QtGui import QPainterPath class image_scene(QGraphicsScene): def __init__(self, parent=None): super(image_scene, self).__init__(parent) self._parent = parent self.Polygon_flag = 0 self.Rect_flag = 0 self.lastpos = [] self.polygon = [] self.rect = [] self.line_item_list = [] self.Grip_item_list = [] def enable_polygons(self): self.Polygon_flag = 1 self.Rect_flag = 0 def enable_rect(self): self.Rect_flag = 1 self.Polygon_flag = 0 def undo(self): # # TODO: if future need redo this function should change because it kill the last element # # kill point if len(self.polygon) >= 1: self.removeItem(self.itemAt(self.polygon[-1].x(), self.polygon[-1].y(), self._parent.transform())) self.removeItem(self.itemAt(self.polygon[-1].x(), self.polygon[-1].y(), self._parent.transform())) del self.polygon[-1] if len(self.polygon) == 1: self.lastpos = [] else: print("can't undo") def delete(self): if self.selectedItems() != []: selecteditem = self.selectedItems() for idx in range(len(selecteditem)): if "muen_gripItem" in selecteditem[idx].__repr__(): pass else: selecteditem = selecteditem + selecteditem[idx].m_items for i in selecteditem: self.removeItem(i) else: print("can't delete") def load_polygon_item(self, point): for i in point: self.polygon_item = My_polygonitem() self.addItem(self.polygon_item) self.polygon_item.addPoint(i) # self.polygon_item.addPoint(i) def load_rect_item(self, point): for i in point: self.rect_item = My_rectitem(i[0]) self.addItem(self.rect_item) self.rect_item.addPoint(i) # self.rect_item.addPoint(i) def keyPressEvent(self, event): if event.key() == Qt.Key_Control: self._parent.canZoom = False def keyReleaseEvent(self, event): QGraphicsScene.keyReleaseEvent(self, event) if event.key() == Qt.Key_Control: self._parent.canZoom = True def mousePressEvent(self, event): if event.button() == Qt.RightButton: self._parent.setDragMode(QGraphicsView.RubberBandDrag) if event.button() == Qt.LeftButton: self._parent.setDragMode(QGraphicsView.ScrollHandDrag) pos = event.scenePos() if self.Polygon_flag == 1: self._parent.setDragMode(QGraphicsView.NoDrag) # self.polygon_item cannot put in intiital self.polygon_item = My_polygonitem() # to get all point coordinate self.polygon.append(pos) # catch the last element as x, y coordinate if self.lastpos == []: self.lastpos = [self.polygon[-1].x(), self.polygon[-1].y()] else: self.lastpos[0] = self.polygon[-2].x() self.lastpos[1] = self.polygon[-2].y() # add circle point in scene # if self._parent.import_flag == 1: point = My_gripItem(self.polygon_item, len(self.polygon)) self.addItem(point) self.Grip_item_list.append(point) point.setPos(self.polygon[-1]) self.line_Item = My_lineitem(self.polygon[-1]) self.addItem(self.line_Item) self.line_item_list.append(self.line_Item) # elif self.Rect_flag == 1 and self.rect == [] and self._parent.import_flag == 1: elif self.Rect_flag == 1 and self.rect == []: self._parent.setDragMode(QGraphicsView.NoDrag) # to get all point coordinate self.rect.append(pos) self.square = My_rectitem(self.rect[0]) self.addItem(self.square) # elif self.Rect_flag == 1 and self.rect != [] and self._parent.import_flag == 1: elif self.Rect_flag == 1 and self.rect != []: self.Rect_flag = 0 pos = event.scenePos() self.rect.append(pos) self.square.addPoint(self.rect) print("original", self.rect) # TODO: save special info for this rect item use setData # self.square.setData(3, "test_rect") self.rect = [] super(image_scene, self).mousePressEvent(event) def mouseReleaseEvent(self, event): QGraphicsScene.mouseReleaseEvent(self, event) if event.button() == Qt.LeftButton: self._parent.setDragMode(QGraphicsView.NoDrag) self._parent.setCursor(Qt.ArrowCursor) elif event.button() == Qt.RightButton: if self._parent.canZoom: viewBBox = self._parent.zoomStack[-1] if len(self._parent.zoomStack) else self._parent.sceneRect() selectionBBox = self.selectionArea().boundingRect().intersected(viewBBox) self.setSelectionArea(QPainterPath()) # Clear current selection area. if selectionBBox.isValid() and (selectionBBox != viewBBox): self._parent.zoomStack.append(selectionBBox) self._parent.updateViewer() self._parent.setDragMode(QGraphicsView.NoDrag) def mouseMoveEvent(self, event): # call basic function QGraphicsScene.mouseMoveEvent(self, event) # if self.Polygon_flag == 1 and self._parent.import_flag == 1 and self.lastpos != []: if self.Polygon_flag == 1 and self.lastpos != []: self.line_Item.move_line(event.scenePos()) if self.Rect_flag == 1 and self.rect != []: self.square.move_rect(event.scenePos()) def mouseDoubleClickEvent(self, event): if event.button() == Qt.LeftButton: if self.Polygon_flag == 1: self.Polygon_flag = 0 for i in range(len(self.Grip_item_list)): self.removeItem(self.Grip_item_list[i]) self.removeItem(self.line_item_list[i]) self.addItem(self.polygon_item) self.polygon_item.addPoint(self.polygon) print("original",self.polygon) # TODO: save special info for this polygon item use setData # self.polygon_item.setData(5, "test_polygon") # TODO: SAVE POINT IN DB self.polygon = [] self.lastpos = [] elif event.button() == Qt.RightButton: if self._parent.canZoom: self._parent.zoomStack = [] # Clear zoom stack. self._parent.updateViewer() super(image_scene, self).mouseDoubleClickEvent(event)<file_sep>/annotation/annotation_object/image_my_viewer.py from PyQt5.QtWidgets import QGraphicsView, QGraphicsPixmapItem from annotation_object.image_scene import image_scene from PyQt5.QtWidgets import QFileDialog from PyQt5.QtGui import QPixmap, QImage, QPainter, QPainterPath, QPaintDevice from PyQt5.QtCore import QByteArray, QBuffer, QIODevice, QPointF, QRectF, Qt import json class MyGraphicsView(QGraphicsView): def __init__(self): QGraphicsView.__init__(self) self.setMouseTracking(True) self._dlg_file = QFileDialog() self.scene = image_scene(self) self.setScene(self.scene) # for zoom in zoom out self.unit_in = 2 self.unit_out = 1 / 2 self.imageName_ = None self.jsonName_ = None self.pixmap = None self.save_jsonName = '' self.jsonName_ = '' self.import_flag = 0 self.transform_initial = self.transform() self.zoom_flag = 0 self.setRenderHint(QPainter.Antialiasing) def import_image(self): # clear all item in view self.scene.clear() self.scene.lastpos = [] self.scene.polygon = [] self.scene.Polygon_flag = 0 self.scene.Rect_flag = 0 # import image options = self._dlg_file.Options() self.imageName_, _ = self._dlg_file.getOpenFileName(self, "Read Image", "", "Image Files (*.png *.jpg *.jpeg *.gif *.tiff *.tif);;All Files (*)", options=options) self.pixmap = QPixmap(self.imageName_) photo = QGraphicsPixmapItem(self.pixmap) # change graphic view free self.viewport().installEventFilter(self) self.setGeometry(0, 0, self.pixmap.width()+10, self.pixmap.height()+10) self.setTransform(self.transform_initial) self.scene.addItem(photo) self.import_flag = 1 def import_json(self): self.scene.clear() self.scene.lastpos = [] self.scene.polygon = [] self.scene.Polygon_flag = 0 self.scene.Rect_flag = 0 options = self._dlg_file.Options() self.jsonName_, _ = self._dlg_file.getOpenFileName(self, "Read Json", "", "Json Files (*.json);;All Files (*)", options=options) if self.jsonName_ !='': self.import_flag = 1 with open(self.jsonName_, 'r') as reader: jf = json.loads(reader.read()) # to turn string back to byte image_json = jf["image"].encode(encoding="utf-8") ba = QByteArray.fromBase64(image_json) img = QImage.fromData(ba, 'PNG') self.pixmap = QPixmap.fromImage(img) photo = QGraphicsPixmapItem(self.pixmap) self.viewport().installEventFilter(self) self.setGeometry(0, 0, self.pixmap.width() + 10, self.pixmap.height() + 10) self.scene.addItem(photo) if jf["polygon"] != []: all_poly_item = [] for i in jf["polygon"]: single_poly_item = [] for j in i: single_poly_item.append(QPointF(j[0], j[1])) all_poly_item.append(single_poly_item) # TODO: make mainwindow not only show a item, not to get this error "wrapped C/C++ object of type XXXX has been deleted" print("test") self.scene.load_polygon_item(all_poly_item) else: print("no polygon") if jf["rect"] != []: all_rect_item = [] for i in jf["rect"]: single_rect_item = [] for j in i: single_rect_item.append(QPointF(j[0], j[1])) all_rect_item.append(single_rect_item) self.scene.load_rect_item(all_rect_item) else: print("no rect") else: print("no json import") def rotate_left(self): if self.import_flag == 1: self.rotate(-10) # to get current transformation matrix for the view elif self.import_flag != 1: print("no image import") def rotate_right(self): if self.import_flag == 1: self.rotate(10) # to get current transformation matrix for the view elif self.import_flag != 1: print("no image import") def zoom_in(self): if self.import_flag == 1 and self.zoom_flag < 4: self.zoom_flag +=1 self.scale(self.unit_in, self.unit_in) elif self.import_flag != 1: print("no image import") elif self.zoom_flag == 4: print("can't zoom in") # to get current transformation matrix for the view def zoom_out(self): if self.import_flag == 1 and self.zoom_flag > -4: self.zoom_flag -= 1 self.scale(self.unit_out, self.unit_out) # to get current transformation matrix for the view elif self.import_flag != 1: print("no image import") elif self.zoom_flag == -4: print("can't zoom out") def original_view(self): if self.import_flag == 1: self.zoom_flag = 0 self.setTransform(self.transform_initial) # to get current transformation matrix for the view elif self.import_flag != 1: print("no image import") def save_image(self): options = self._dlg_file.Options() if self.pixmap is not None: # Get region of scene to capture from somewhere. area = QRectF(0, 0, self.pixmap.width() + 10, self.pixmap.height() + 10) # Create a QImage to render to and fix up a QPainter for it. image = QImage(QRectF.toRect(area).size(), QImage.Format_ARGB32_Premultiplied) painter = QPainter(image) # Render the region of interest to the QImage. self.scene.render(painter, QRectF(image.rect()), area) painter.end() save_imageName, _ = self._dlg_file.getSaveFileName(self, "Save Image", "", "Image Files (*.png *.jpg *.jpeg *.gif *.tiff *.tif);;All Files (*)", options=options) # Save the image to a file. image.save(save_imageName) else: print("can't save image") def save_json(self): options = self._dlg_file.Options() if self.pixmap is not None: area = QRectF(0, 0, self.pixmap.width() + 10, self.pixmap.height() + 10) self.select_all_scene = QPainterPath() self.select_all_scene.addRect(area) self.scene.setSelectionArea(self.select_all_scene, Qt.IntersectsItemShape, self.transform()) allitem = self.scene.items() selecteditem = self.scene.selectedItems() # selecteditem: different object has different type, use, selecteditem[?].type(), can get different object, polygon type == 5, rect type == 3, gripitem type == 2 polygon_point = [] rect_point = [] for i in selecteditem: if i.type() == 5: # get polgon item point each_point_polygon = [] for j in i.m_points: each_point_polygon.append([j.x(), j.y()]) polygon_point.append(each_point_polygon) elif i.type() == 3: each_point_rect = [] each_use = [[i.rect_point[0].x(), i.rect_point[1].x()], [i.rect_point[0].y(), i.rect_point[1].y()]] for j in i.rect_point: if j is i.rect_point[0]: each_point_rect.append([min(each_use[0]), min(each_use[1])]) else: each_point_rect.append([max(each_use[0]), max(each_use[1])]) rect_point.append(each_point_rect) # save image PIC = self.pixmap.toImage() ba = QByteArray() buffer = QBuffer(ba) buffer.open(QIODevice.WriteOnly) PIC.save(buffer, 'PNG') base64_data = ba.toBase64().data() image_data = str(base64_data, encoding='utf-8') # save to json annotation_object = { 'polygon': polygon_point, 'rect': rect_point, 'image': image_data} self.save_jsonName, _ = self._dlg_file.getSaveFileName(self, "Save Json", "", "Json Files (*.json);;All Files (*)", options=options) if self.save_jsonName != '': with open(self.save_jsonName, 'w') as json_file: json.dump(annotation_object, json_file) print("test") else: print("no choose save path") else: print("can't save json") <file_sep>/README.md # PyQt-image-annotation-tool use pyqt5 to create annotation tool 這是用python3.7 ptqt5 設計的標記工具,有興趣者可拿去嘗試,由於是初學時製作的工具,有諸多需要改進,有任何指教再跟我聯絡吧~ <file_sep>/annotation/annotation_object/image_window.py from PyQt5.QtWidgets import QMainWindow, QPushButton, QLabel from PyQt5.QtGui import QIcon from annotation_object.image_my_viewer import MyGraphicsView class window(QMainWindow): def __init__(self, parent=None): super(window, self).__init__(parent) self.title = "PyQt5 Graphic View Test cat" self.top = 100 self.left = 100 self.width = 1000 self.height = 800 self.view = MyGraphicsView() self.setCentralWidget(self.view) self.view.setMouseTracking(True) self.annotation_label = QLabel(self) self.InitWindow() def InitWindow(self): self.importbutton = QPushButton("file import ", self) self.importbutton.setGeometry(self.width - 150, 20, 100, 50) self.importbutton.clicked.connect(self.view.import_image) self.importjsonbutton = QPushButton("json import ", self) self.importjsonbutton.setGeometry(self.width - 150, 90, 100, 50) self.importjsonbutton.clicked.connect(self.view.import_json) self.Rotateleftbutton = QPushButton("Rotate-L ", self) self.Rotateleftbutton.setGeometry(self.width-150, 160, 100, 50) self.Rotateleftbutton.clicked.connect(self.view.rotate_left) self.Rotaterightbutton = QPushButton("Rotate-R ", self) self.Rotaterightbutton.setGeometry(self.width-150, 230, 100, 50) self.Rotaterightbutton.clicked.connect(self.view.rotate_right) self.Zoominbutton = QPushButton("Zoom_in", self) self.Zoominbutton.setGeometry(self.width-150, 300, 100, 50) self.Zoominbutton.clicked.connect(self.view.zoom_in) self.Zoomoutbutton = QPushButton("Zoom_out", self) self.Zoomoutbutton.setGeometry(self.width-150, 370, 100, 50) self.Zoomoutbutton.clicked.connect(self.view.zoom_out) self.Originalbutton = QPushButton("Original_view", self) self.Originalbutton.setGeometry(self.width - 150, 440, 100, 50) self.Originalbutton.clicked.connect(self.view.original_view) self.enablepolygonsbutton = QPushButton("create_polygens", self) self.enablepolygonsbutton.setGeometry(self.width-270, 20, 100, 50) self.enablepolygonsbutton.clicked.connect(self.view.scene.enable_polygons) self.enablerectsbutton = QPushButton("create_rect", self) self.enablerectsbutton.setGeometry(self.width - 270, 90, 100, 50) self.enablerectsbutton.clicked.connect(self.view.scene.enable_rect) self.undobutton = QPushButton("undo", self) self.undobutton.setGeometry(self.width - 270, 160, 100, 50) self.undobutton.clicked.connect(self.view.scene.undo) self.delet_item = QPushButton("delet_item", self) self.delet_item.setGeometry(self.width - 270, 230, 100, 50) self.delet_item.clicked.connect(self.view.scene.delete) # self.delet_all = QPushButton("delet_all_item", self) # self.delet_all.setGeometry(self.width - 270, 300, 100, 50) # self.delet_all.clicked.connect(self.view.scene.delete_all) self.savebutton = QPushButton("save", self) self.savebutton.setGeometry(self.width - 270, 370, 100, 50) self.savebutton.clicked.connect(self.view.save_image) self.savejsonbutton = QPushButton("save json", self) self.savejsonbutton.setGeometry(self.width - 270, 440, 100, 50) self.savejsonbutton.clicked.connect(self.view.save_json) # TODO: add QlIST # TODO: delet function # self.removebutton = QPushButton("removeitem", self) # self.removebutton.setGeometry(self.width - 150, 650, 100, 50) # self.removebutton.clicked.connect(self.removeitem) self.setWindowIcon(QIcon("C:/Users/willi/Desktop/classification/data_annotated/0001.jpg")) self.setWindowTitle(self.title) self.setGeometry(self.top, self.left, self.width, self.height)
d6a5ffee13176291b482e19a54470051a3f9a894
[ "Markdown", "Python" ]
9
Python
william084531/PyQt-image-annotation-tool
2017ae9ce99c5f29b19a53fd53cb1a5dd3394bd7
850afd3652228b4ec1b3da7f0b1a20646a22eac2
refs/heads/master
<repo_name>brightxiaomin/CodePrep<file_sep>/Microsoft OA 2022/SmallestStringRemovingOneChar.cs using System; using System.Collections.Generic; using System.Text; namespace MicrosoftOA { class SmallestStringRemovingOneChar { // Function to return the // smallest String by removing on character static string smallest(string s) { int l = s.Length; String ans = ""; // iterate the String for (int i = 0; i < l - 1; i++) { // first point where s[i]>s[i+1] if (s[i] > s[i + 1]) { // append the String without // i-th character in it for (int j = 0; j < l; j++) { if (i != j) { ans += s[j]; } } return ans; } } // leave the last character ans = s.Substring(0, l - 1); return ans; } } } <file_sep>/CodePractice/CodePractice/LeetCode/LRUCacheLinkedListHashMap.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { //O(1) operations for GET, PUT public class LRUCacheLinkedListHashMap { private readonly Dictionary<int, DLinkedNode> cache = new Dictionary<int, DLinkedNode>(); private int size; private readonly int capacity; private readonly DLinkedNode head, tail; public LRUCacheLinkedListHashMap(int capacity) { this.size = 0; this.capacity = capacity; //Dummy Node, always there head = new DLinkedNode(); tail = new DLinkedNode(); head.Next = tail; tail.Prev = head; } private void AddNode(DLinkedNode node) { /** * Always add the new node right after head. */ node.Prev = head; node.Next = head.Next; head.Next.Prev = node; head.Next = node; } private void RemoveNode(DLinkedNode node) { /** * Remove an existing node from the linked list. */ DLinkedNode Prev = node.Prev; DLinkedNode Next = node.Next; Prev.Next = Next; Next.Prev = Prev; } private void MoveToHead(DLinkedNode node) { /** * Move certain node in between to the head. */ RemoveNode(node); AddNode(node); } private DLinkedNode PopTail() { /** * Pop the current tail. */ DLinkedNode res = tail.Prev; RemoveNode(res); return res; } public int Get(int key) { if (!cache.ContainsKey(key)) return -1; DLinkedNode node = cache[key]; // move the accessed node to the head; MoveToHead(node); return node.Value; } public void Put(int key, int value) { if (!cache.ContainsKey(key)) { DLinkedNode newNode = new DLinkedNode { Key = key, Value = value }; cache.Add(key, newNode); AddNode(newNode); ++size; if (size > capacity) { // pop the tail DLinkedNode tail = PopTail(); cache.Remove(tail.Key); --size; } } else { // update the value. DLinkedNode node = cache[key]; node.Value = value; MoveToHead(node); } } class DLinkedNode { public int Key { get; set; } public int Value { get; set; } public DLinkedNode Prev { get; set; } public DLinkedNode Next { get; set; } } } } <file_sep>/Amazon QA 2022/NumberOfPageWays.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class NumberOfPageWays { // Count the number of pages public long NumberOfWays(string s) { long ans = 0; int len = s.Length; long totOnes = 0; for (int i = 0; i < len; i++) totOnes += s[i] - '0';//only s[i]=='1' plus 1 long totZeros = len - totOnes; long currZeros = s[0] == '0' ? 1 : 0; long currOnes = s[0] == '1' ? 1 : 0; for (int i = 1; i < len; i++) { if (s[i] == '0') { ans += (currOnes * (totOnes - currOnes)); currZeros++; } else { ans += (currZeros * (totZeros - currZeros)); currOnes++; } } return ans; } } } <file_sep>/CodePractice/CodePractice/Amazon Coding Problems/WordLadderII.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { public class WordLadderII { private int minLevel = int.MaxValue; public IList<IList<string>> FindLadders(string beginWord, string endWord, IList<string> wordList) { int level = 0; IList<IList<string>> res = new List<IList<string>>(); HashSet<string> remainSet = new HashSet<string>(wordList); HashSet<string> route = new HashSet<string>() { beginWord }; BackTrack(beginWord, endWord, remainSet, route, res, level); return res; } //backtrack, when to return, more than min level or hit endword. //word list is the word left for word void BackTrack(string beginWord, string endWord, HashSet<string> remainSet, HashSet<string> route, IList<IList<string>> res, int le) { if (le > minLevel) return; //found endword here if (beginWord == endWord) { if (le < minLevel) { minLevel = le; res.Clear(); res.Add(route.ToList()); return; } else if (le == minLevel) { res.Add(route.ToList()); return; } } int len = beginWord.Length; for (int j = 0; j < len; j++) //O(L * 26) { //or this way using stringbuilder StringBuilder sb = new StringBuilder(beginWord); for (char ch = 'a'; ch <= 'z'; ch++) { if (ch == beginWord[j]) continue; sb[j] = ch; string temp = sb.ToString(); if (remainSet.Remove(temp)) //in set and removed { route.Add(temp); BackTrack(temp, endWord, remainSet, route, res, le + 1); route.Remove(temp); remainSet.Add(temp); } } } } public IList<IList<string>> FindLadders2(string start, string end, IList<string> wordList) { HashSet<string> dict = new HashSet<string>(wordList); IList<IList<string>> res = new List<IList<string>>(); Dictionary<string, List<string>> nodeNeighbors = new Dictionary<string, List<string>>();// Neighbors for every node Dictionary<string, int> distance = new Dictionary<string, int>();// Distance of every node from the start node List<string> solution = new List<string>(); dict.Add(start); Bfs(start, end, dict, nodeNeighbors, distance); Dfs(start, end, dict, nodeNeighbors, distance, solution, res); return res; } // BFS: Trace every node's distance from the start node (level by level). private void Bfs(string start, string end, HashSet<string> dict, Dictionary<string, List<string>> nodeNeighbors, Dictionary<string, int> distance) { foreach (string str in dict) nodeNeighbors.Add(str, new List<string>()); Queue<string> queue = new Queue<string>(); queue.Enqueue(start); distance.Add(start, 0); while (queue.Count > 0) { int count = queue.Count; bool foundEnd = false; for (int i = 0; i < count; i++) { string cur = queue.Dequeue(); int curDistance = distance[cur]; List<string> neighbors = getNeighbors(cur, dict); foreach (string neighbor in neighbors) { nodeNeighbors[cur].Add(neighbor); if (!distance.ContainsKey(neighbor)) {// Check if visited distance.Add(neighbor, curDistance + 1); if (end.Equals(neighbor))// Found the shortest path foundEnd = true; else queue.Enqueue(neighbor); } } } if (foundEnd) break; } } // Find all next level nodes. private List<string> getNeighbors(string node, HashSet<string> dict) { List<string> res = new List<string>(); char[] chs = node.ToCharArray(); for (int i = 0; i < chs.Length; i++) { for (char ch = 'a'; ch <= 'z'; ch++) { if (chs[i] == ch) continue; char old_ch = chs[i]; chs[i] = ch; string temp = new string(chs); if (dict.Contains(temp)) { res.Add(temp); } chs[i] = old_ch; } } return res; } // DFS: output all paths with the shortest distance. private void Dfs(string cur, string end, HashSet<string> dict, Dictionary<string, List<string>> nodeNeighbors, Dictionary<string, int> distance, List<string> solution, IList<IList<string>> res) { solution.Add(cur); if (end.Equals(cur)) { res.Add(new List<string>(solution)); } else { foreach (string next in nodeNeighbors[cur]) if (distance[next] == distance[cur] + 1) { Dfs(next, end, dict, nodeNeighbors, distance, solution, res); } } solution.RemoveAt(solution.Count - 1); } //A sample solution for C sharp // two end BFS // very smilar logic as this java implementations // https://leetcode.com/problems/word-ladder-ii/discuss/40477/Super-fast-Java-solution-(two-end-BFS) public class SolutionTwoBFS { // create a dictionary for parent and children relations for one step switching // use a bidirectional bfs to create the dictionary, and its parents/children relationships. This will keep going until one word is found within the end set. // use a DFS backtracking method to create the possible lists for the shortest transformations public IList<IList<string>> FindLadders(string beginWord, string endWord, IList<string> wordList) { HashSet<string> set = new HashSet<string>(wordList); IList<IList<string>> list = new List<IList<string>>(); if (!set.Contains(endWord)) { return list; } Dictionary<string, List<string>> dct = getChildren(beginWord, endWord, set); IList<string> path = new List<string>(); path.Add(beginWord); findLadder(beginWord, endWord, dct, path, list); return list; } public Dictionary<string, List<string>> getChildren(string beginWord, string endWord, HashSet<string> wordBank) { Dictionary<string, List<string>> dct = new Dictionary<string, List<string>>(); HashSet<string> beginSet = new HashSet<string>(); HashSet<string> endSet = new HashSet<string>(); beginSet.Add(beginWord); endSet.Add(endWord); HashSet<string> visited = new HashSet<string>(); bool isBackward = false; bool isFound = false; // loop can rewrite to recursion. //visited is shared, while (beginSet.Count > 0 && !isFound) { if (beginSet.Count > endSet.Count) { isBackward = !isBackward; HashSet<string> temp = beginSet; beginSet = endSet; endSet = temp; } HashSet<string> set = new HashSet<string>(); foreach (string cur in beginSet) { visited.Add(cur); foreach (string next in getNext(cur, wordBank)) { if (visited.Contains(next) || beginSet.Contains(next)) { continue; } if (endSet.Contains(next)) { isFound = true; } set.Add(next); string parent = isBackward ? next : cur; string child = isBackward ? cur : next; if (!dct.ContainsKey(parent)) { dct.Add(parent, new List<string>()); } dct[parent].Add(child); } } beginSet = set; } return dct; } public void findLadder(string beginWord, string endWord, Dictionary<string, List<string>> dct, IList<string> path, IList<IList<string>> res) { if (beginWord == endWord) { res.Add(new List<string>(path)); } if (!dct.ContainsKey(beginWord)) { return; } IList<string> list = dct[beginWord]; foreach (string s in list) { path.Add(s); findLadder(s, endWord, dct, path, res); path.RemoveAt(path.Count - 1); } } public IList<string> getNext(string word, HashSet<string> wordBank) { IList<string> list = new List<string>(); char[] cArr = word.ToCharArray(); for (int i = 0; i < cArr.Length; i++) { char old = cArr[i]; for (char c = 'a'; c <= 'z'; c++) { if (c == old) { continue; } cArr[i] = c; string s = new string(cArr); if (wordBank.Contains(s)) { list.Add(s); } } cArr[i] = old; } return list; } } } } <file_sep>/CodePractice/CodePractice/LeetCode/RandomizedSet.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { // this is key part //delete part is to swap element with last one // then remove last one public class RandomizedSet { private readonly Dictionary<int, int> store; // key is value, value is index private readonly List<int> set; private readonly Random random; /** Initialize your data structure here. */ public RandomizedSet() { store = new Dictionary<int, int>(); set = new List<int>(); random = new Random(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public bool Insert(int val) { if (store.ContainsKey(val)) //search O(1) return false; int size = set.Count; // index for the to be inserted item store.Add(val, size); // dict add, o1 set.Add(val); // list, add O1 return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ public bool Remove(int val) { if (!store.ContainsKey(val)) //search O(1) return false; int index = store[val]; // get index from val in O(1), thats why need dict int lastIndex = set.Count - 1; //Key part //swap, put last element to the index int lastElement = set[lastIndex]; set[index] = lastElement; //update index for the last element value because it is swaped, now the list is valid, all spot has values //we know all element in list is always in the dict because no duplicate store[lastElement] = index; //now we dont care about last element since it is stored at index position set.RemoveAt(lastIndex); //remove current val store.Remove(val); return true; } /** Get a random element from the set. */ public int GetRandom() { int index = random.Next(set.Count); return set[index]; } } } <file_sep>/CodePractice/CodePractice/LeetCode/VisitPattern.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { struct Pair { public int time; public string web; public Pair(int time, string web) { this.time = time; this.web = web; } } class Solution2 { public List<string> MostVisitedPattern(string[] username, int[] timestamp, string[] website) { Dictionary<string, List<Pair>> map = new Dictionary<string, List<Pair>>(); int n = username.Length; // collect the website info for every user, key: username, value: (timestamp, website) for (int i = 0; i < n; i++) { if (!map.ContainsKey(username[i])) map.Add(username[i], new List<Pair> ()); map[username[i]].Add(new Pair(timestamp[i], website[i])); } // count map to record every 3 combination occuring time for the different user. Dictionary<string, int> count = new Dictionary<string, int>(); string res = ""; foreach (string key in map.Keys) { HashSet<string> set = new HashSet<string>(); // this set is to avoid visit the same 3-seq in one user List<Pair> list = map[key]; list.Sort((a, b) => (a.time - b.time)); // sort by time // brutal force O(N ^ 3) for (int i = 0; i < list.Count; i++) { for (int j = i + 1; j < list.Count; j++) { for (int k = j + 1; k < list.Count; k++) { string str = list[i].web + " " + list[j].web + " " + list[k].web; if (!set.Contains(str)) { if (!count.ContainsKey(str)) count.Add(str, 0); count[str] = count[str] + 1; set.Add(str); } if (res.Equals("") || count[res] < count[str] || (count[res] == count[str] && res.CompareTo(str) > 0)) { // make sure the right lexi order res = str; } } } } } // grab the right answer string[] r = res.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); List<string> result = new List<string>(); foreach (string str in r) { result.Add(str); } return result; } public string LongestDupSubstring(string S) { int n = S.Length; int[] nums = new int[n]; for (int i = 0; i < n; ++i) nums[i] = S[i] - 'a'; // base value for the rolling hash function int a = 26; // modulus value for the rolling hash function to avoid overflow long modulus = (long)Math.Pow(2, 32); int left = 1, right = n; while (left <= right) { int L = left + (right - left) / 2; if (Search(L, a, modulus, n, nums) != -1) left = L + 1; else right = L - 1; } int index = Search(left - 1, a, modulus, n, nums); return S.Substring(index, left - 1); } public int Search(int L, int a, long modulus, int n, int[] nums) { // compute the hash of string S[0:L], the first one in the rolling hash long h = 0; for (int i = 0; i < L; ++i) h = (h * a + nums[i]) % modulus; // already seen hashes of strings of length L HashSet<long> seen = new HashSet<long>(); seen.Add(h); // const value to be used often : a**L % modulus long aL = 1; for (int i = 1; i <= L; ++i) aL = (aL * a) % modulus; for (int start = 1; start < n - L + 1; ++start) { // compute rolling hash in O(1) time //h = (h * a - nums[start - 1] * aL % modulus + modulus) % modulus; //h = (h + nums[start + L - 1]) % modulus; // compute rolling hash in O(1) time h = (h * a - nums[start - 1] * aL + nums[start + L - 1]) % modulus; if (seen.Contains(h)) return start; seen.Add(h); } return -1; } } } <file_sep>/CodePractice/CodePractice/Amazon OA/KClosestPoints.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { public class KClosestPoints { public int[][] KClosest(int[][] points, int K) { if (points == null || points.Length == 0) return points; if (K > points.Length) K = points.Length; int[][] res = new int[K][]; //build max heap of size K, insert one by one, then recalculate up for(int i = 0; i < K; i++) { res[i] = points[i]; RecalculateUp(res, i); } //loop through rest of points for (int j = K; j < points.Length; j++) { if (Dist(points[j]) < Dist(res[0])) { // we only care about the heap of K, rest elements we dont care res[0] = points[j]; Heapify(res, 0, K); } } return res; } public void Heapify(int[][] res, int index, int size) { while (true) { int max = index; int left = 2 * index + 1; int right = 2 * index + 2; if (left < size && Dist(res[max]) < Dist(res[left])) max = left; if (right < size && Dist(res[max]) < Dist(res[right])) max = right; if (max == index) return; // NO swap Swap(res, max, index); index = max; } } public void RecalculateUp(int[][] res, int index) { // has parent node and parent value < child value // there is a bug here, index = 0, -1/2 =0, will go down. // doesnt affect result, just one more calculation. // change from (index - 1) / 2 >=0 to index > 0 while (index > 0 && Dist(res[(index - 1) / 2]) < Dist(res[index])) { Swap(res, index, (index - 1) / 2); index = (index - 1) / 2; } } public int Dist(int[] point) { return point[0] * point[0] + point[1] * point[1]; } public void Swap(int[][] points, int a, int b) { int[] temp = points[a]; points[a] = points[b]; points[b] = temp; } } } <file_sep>/AmazonOA/CriticalConnection2.java class Solution { List<PairInt> list; Map<Integer, Boolean> visited; List<PairInt> criticalConnections(int numOfServers, int numOfConnections, List<PairInt> connections) { Map<Integer, HashSet<Integer>> adj = new HashMap<>(); for(PairInt connection : connections){ int u = connection.first; int v = connection.second; if(adj.get(u) == null){ adj.put(u,new HashSet<Integer>()); } adj.get(u).add(v); if(adj.get(v) == null){ adj.put(v,new HashSet<Integer>()); } adj.get(v).add(u); } list = new ArrayList<>(); for(int i =0;i<numOfConnections;i++){ visited = new HashMap<>(); PairInt p = connections.get(i); int x = p.first; int y = p.second; adj.get(x).remove(y); adj.get(y).remove(x); DFS(adj,1); if(visited.size()!=numOfServers){ if(p.first > p.second) list.add(new PairInt(p.second,p.first)); else list.add(p); } adj.get(x).add(y); adj.get(y).add(x); } return list; } public void DFS(Map<Integer, HashSet<Integer>> adj, int u){ visited.put(u, true); if(adj.get(u).size()!=0){ for(int v : adj.get(u)){ if(visited.getOrDefault(v, false)== false){ DFS(adj,v); } } } } }<file_sep>/CodePractice/CodePractice/Amazon OA/ProductSuggetion.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { public class ProductSuggetion { public List<List<string>> GetSuggestedProducts(string[] products, string searchWord) { Trie root = new Trie(); foreach (string p in products) { // build Trie. Trie t = root; foreach (char c in p) { // insert current product into Trie. if (t.Sub[c - 'a'] == null) t.Sub[c - 'a'] = new Trie(); t = t.Sub[c - 'a']; t.Suggestion.Add(p); // put products with same prefix into suggestion list. t.Suggestion.Sort(); // sort products in the suggestions if (t.Suggestion.Count > 3) // maintain 3 lexicographically minimum strings. { int lastIndex = t.Suggestion.Count - 1; t.Suggestion.RemoveAt(lastIndex); } } } List<List<string>> ans = new List<List<string>>(); foreach (char c in searchWord) { // search product. if (root != null) // if current Trie is NOT null. root = root.Sub[c - 'a']; ans.Add(root == null ? new List<string>() : root.Suggestion); // add it if there exist products with current prefix. } return ans; } //Brutal Force, what surprised me is public IList<IList<string>> SuggestedProducts(string[] products, string searchWord) { Array.Sort(products, StringComparer.Ordinal); IList<IList<string>> result = new List<IList<string>>(); string keyword = ""; for (int i = 0; i < searchWord.Length; i++) { keyword += searchWord[i]; IList<string> current = new List<string>(); int count = 0; foreach (string product in products) { if (product.StartsWith(keyword, StringComparison.Ordinal)) { current.Add(product); count++; } if (count == 3) { break; } } result.Add(current); } return result; } } class Trie { public Trie[] Sub = new Trie[26]; public List<string> Suggestion = new List<string>(); } } /* * Analysis: Complexity depends on the process of building Trie and the length of searchWord. For each Trie Node, sorting suggestion List involving comparing String, hence cost time O(m), but space cost only O(1) due to suggestion List save only String referrence. Therefore, Time: O(m * m * n + L), space: O(m * n + L), where m = average length of products, n = products.length, L = searchWord.length(). * */ <file_sep>/Microsoft OA 2022/MinStepsToMakePileEqual.cs using System; using System.Collections.Generic; using System.Text; namespace MicrosoftOA { class MinStepsToMakePileEqual { // working solution to me, O(nlogn) public static int MinSteps(int[] piles) { Array.Sort(piles); int sum = 0; int n = piles.Length; for (int i = 1; i < n; i++) { if (piles[n - i - 1] != piles[n - i]) { sum += i; } } return sum; } } } <file_sep>/Microsoft OA 2022/MinOperationsEqualSum.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MicrosoftOA { // Equal Sum Arrays With Minimum Number of Operations // I suggest going through the heap solution below to get a good feel of this problem. // In this solution, we use the same approach, but we count numbers [1...6] in each array and then calculate how many of each number we need to change. // In a way, we go from O(n log n) to O(n) by using counting sort. class MinOperationsEqualSum { public int MinOperations(int[] n1, int[] n2) { if (n2.Length * 6 < n1.Length || n1.Length * 6 < n2.Length) return -1; int sum1 = n1.Sum(), sum2 = n2.Sum(); if (sum1 < sum2) return MinOperations(n1, n2, sum1, sum2); return MinOperations(n2, n1, sum2, sum1); } public int MinOperations(int[] n1, int[] n2, int sum1, int sum2) { int[] cnt = new int[6]; int diff = sum2 - sum1, res = 0; foreach (var n in n1) ++cnt[6 - n]; foreach (var n in n2) ++cnt[n - 1]; for (int i = 5; i > 0 && diff > 0; --i) { int take = Math.Min(cnt[i], diff / i + (diff % i != 0 ? 1 : 0)); diff -= take * i; res += take; } return res; } } } <file_sep>/Amazon QA 2022/WifiRange.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class WifiRange { // wifi router problem // use diff array public void increment(int i, int j, int val) { int[] diff = new int[10]; diff[i] += val; if (j + 1 < diff.Length) { diff[j + 1] -= val; } } public int[] result() { int[] diff = new int[10]; int[] res = new int[diff.Length]; // 根据差分数组构造结果数组 res[0] = diff[0]; for (int i = 1; i < diff.Length; i++) { res[i] = res[i - 1] + diff[i]; } return res; } } } <file_sep>/Amazon QA 2022/FlipStringMonotone.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class FlipStringMonotone { // flip string public int MinFlipsMonoIncr(string s) { int N = s.Length; int[] P = new int[N + 1]; for (int i = 0; i < N; ++i) P[i + 1] = P[i] + (s[i] == '1' ? 1 : 0); int ans = int.MaxValue; for (int j = 0; j <= N; ++j) { ans = Math.Min(ans, P[j] + N - j - (P[N] - P[j])); } return ans; } } } <file_sep>/CodePractice/CodePractice/LeetCode/Palindrome.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { public class Palindrome { // can delete at most 1 character, decide whether we can make a palindrome // Valid Palindrome II public bool ValidPalindrome(string s) { int i = 0, j = s.Length - 1; while (i < j) { if (s[i] != s[j]) { if (s[i + 1] == s[j]) { int a = i + 1, b = j; while (a < b) { if (s[a] != s[b]) break; a++; b--; } if (a >= b) return true; } if (s[i] == s[j - 1]) { int a = i, b = j - 1; while (a < b) { if (s[a] != s[b]) break; a++; b--; } if (a >= b) return true; } return false; } i++; j--; } return true; } public bool IsValidPalindrome(string s) { int i = 0, j = s.Length - 1; while(i < j) { if(s[i] != s[j]) { return IsPalindrome(s, i + 1, j) || IsPalindrome(s, i, j - 1); } i++; j--; } return true; } //helper method to simplify the above code private bool IsPalindrome(string s, int i, int j) { while (i < j) { if (s[i] != s[j]) return false; i++; j--; } return true; } // 5. Longest Palindromic Substring // going to use DP, states dp[i,j] mean whether substring(i, j) is palindrome or not // idea is sub(i,j) = sub(i + 1, j - 1) && s[i] == s[j], be careful about j - i < 3, which means, j = i, i + 1, i +2, j is i, none in between, one in between, we dont need to check anything // starting from n - 1 position all the way up to 0, // each position, we count i up to n -1, so we only the fill in the top right half of the matrix public string LongestPalindrome(string s) { //string res = string.Empty; int n = s.Length, max = 0, start = 0; bool[,] dp = new bool[n, n]; //starting dp, bottom up approach, starting from smallest problem (from end point len - 1), to biggest problem(starting point 0) for(int i = n - 1; i >= 0; i--) { for(int j = i; j < n; j++) { if (s[j] == s[i] && (j - i < 3 || dp[i + 1, j - 1])) dp[i, j] = true; // when we found a palindrome, update max if(dp[i,j] && j - i + 1 > max) { max = j - i + 1; start = i; } } } return s.Substring(start, max); } //optimize space a little to O(n) public string LongestPalindrome2(string s) { int n = s.Length, max = 0, start = 0; bool[] pre = new bool[n]; bool[] cur = new bool[n]; //two arrays to save for (int i = n - 1; i >= 0; i--) { bool lastLeft = pre[i]; for (int j = i; j < n; j++) { if (s[j] == s[i] && (j - i < 3 || lastLeft)) cur[j] = true; else cur[j] = false; // important, previous 2-d array, it is okay, // when we found a palindrome, update max if (cur[j] && j - i + 1 > max) { max = j - i + 1; start = i; } lastLeft = pre[j]; pre[j] = cur[j]; } } return s.Substring(start, max); } //one row public string LongestPalindrome3(string s) { int n = s.Length, max = 0, start = 0; bool[] cur = new bool[n]; //one array to save for (int i = n - 1; i >= 0; i--) { bool lastLeft = cur[i]; for (int j = i; j < n; j++) { bool lastCurrent = cur[j]; if (s[j] == s[i] && (j - i < 3 || lastLeft)) cur[j] = true; else cur[j] = false; // important, previous 2-d array, it is okay, // when we found a palindrome, update max if (cur[j] && j - i + 1 > max) { max = j - i + 1; start = i; } lastLeft = lastCurrent; lastCurrent = cur[j]; } } return s.Substring(start, max); } //516. Longest Palindromic Subsequence // DP to solve this // sort of like the longest common subsequence problem // use a 2-d array to store the max at i,j, here dp[i,j] means the longest (int) palindromic subsequence between substring (i,j) //dp[i,i] = 1; dp[i,j] = dp[i + 1, j -1] + 2 if (s[i] == s[j]) //dp[i,j] = Max(dp[i + 1, j], dp[i, j -1])if (s[i] != s[j]) // if we want to retrieve, we must have another 2-d array to store the selection like LCS problem // or we can do compare at each i, j to find out the selection. public int LongestPalindromeSubseq(string s) { int n = s.Length; int[,] dp = new int[n, n]; //fill in dp for(int i = n - 1; i >= 0; i--) { dp[i, i] = 1; for(int j = i + 1; j < n; j++) { if (s[i] == s[j]) dp[i, j] = dp[i + 1, j - 1] + 2; else { dp[i, j] = Math.Max(dp[i + 1, j], dp[i, j - 1]); } } } return dp[0, n - 1]; } public int LongestPalindromeSubseq2(string s) { int n = s.Length; int[] cur = new int[n]; int[] pre = new int[n]; //fill in dp, after update current[i], need to also update pre[i] to cur[i] last for (int i = n - 1; i >= 0; i--) { cur[i] = 1; int lastLeft = pre[i]; for (int j = i + 1; j < n; j++) { if (s[i] == s[j]) cur[j] = lastLeft + 2; else { cur[j] = Math.Max(pre[j], cur[j - 1]); } lastLeft = pre[j]; pre[j] = cur[j]; } pre[i] = cur[i]; } return cur[n - 1]; } //optimize some space public int LongestPalindromeSubseq3(string s) { int n = s.Length; int[] dp = new int[n]; //fill in dp, use it before its updated for (int i = n - 1; i >= 0; i--) { int lastLeft = dp[i]; dp[i] = 1; for (int j = i + 1; j < n; j++) { int lastCurrent = dp[j]; if (s[i] == s[j]) dp[j] = lastLeft + 2; else { dp[j] = Math.Max(lastCurrent, dp[j - 1]); } lastLeft = lastCurrent; lastCurrent = dp[j]; } } return dp[n - 1]; } //866. Prime Palindrome public int PrimePalindrome(int N) { //BF produce TLE int i = N; while(i < 200000000 ) { if (IsPrimeNumber(i) && IsPalindromeNumber(i)) return i; i++; } return -1; } bool IsPrimeNumber(int num) { if (num == 0 || num == 1) return false; int R = (int)Math.Sqrt(num); for(int i = 2; i <= R; i++) { if (num % i == 0) return false; } return true; } bool IsPalindromeNumber(int num) { int div = 1, temp = num; while(temp / 10 != 0) { div *= 10; temp /= 10; } while(num != 0) { int left = num / div; int right = num % 10; if (left != right) return false; //chop two numbers num = (num % div) / 10; div /= 100; } return true; } //construct palindromic number in order //we skip even length palindrome numbers //according to number theory, /* * O(10000) to check all numbers 1 - 100000. isPrime function is O(sqrt(x)) in worst case. But only sqrt(N) worst cases for 1 <= x <= N In general it's O(logx) */ public int PrimePalindrome2(int N) { if (8 <= N && N <= 11) return 11; for (int x = 1; x < 100000; x++) { string s = x.ToString(); char[] charArray = s.ToCharArray(); Array.Reverse(charArray); string r = new string(charArray); int y = int.Parse(s + r.Substring(1)); if (y >= N && IsPrime(y)) return y; } return -1; } // This is a good way to check prime numbers!!! public bool IsPrime(int x) { if (x < 2 || x % 2 == 0) return x == 2; // if it is even number, we return false, for even number, only 2 is prime number // sqrt(x) times at most, check all odd number up to sqrt(x),for even number, we dont need to check even number for i, because if it can be divided by an even number, then itself must be a even number. // all numbers pass first line, are odd number, it won't be divided by even number, there is no meaning to check even numbers here, the x % i will always be false for even number i. for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false; return true; } // Way to construct palindrome numbers in order public int PrimePalindrome3(int N) { for (int L = 1; L <= 5; ++L) { //Check for odd-length palindromes for (int root = (int)Math.Pow(10, L - 1); root < (int)Math.Pow(10, L); ++root) { StringBuilder sb = new StringBuilder(root.ToString()); for (int k = L - 2; k >= 0; --k) sb.Append(sb[k]); int x = int.Parse(sb.ToString()); if (x >= N && IsPrime2(x)) return x; //If we didn't check for even-length palindromes: //return N <= 11 ? Math.Min(x, 11) : x; } //Check for even-length palindromes, we know even length is not needed, skip the rest for (int root = (int)Math.Pow(10, L - 1); root < (int)Math.Pow(10, L); ++root) { StringBuilder sb = new StringBuilder(root.ToString()); for (int k = L - 1; k >= 0; --k) sb.Append(sb[k]); int x = int.Parse(sb.ToString()); if (x >= N && IsPrime2(x)) return x; } } throw null; } public bool IsPrime2(int N) { if (N < 2) return false; int R = (int)Math.Sqrt(N); for (int d = 2; d <= R; ++d) if (N % d == 0) return false; return true; } } } <file_sep>/Amazon QA 2022/MinSwapToMakePalindrome.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class MinSwapToMakePalindrome { // min swap to make palindrome public static int MinSwapsPal(string str) { int countOne = 0; int countZero = 0; foreach (char c in str) { if (c == '0') { countZero++; } else { countOne++; } } if (countOne % 2 == 1 && countZero % 2 == 1) { return -1; } int mismatchedIndexes = 0; for (int i = 0; i < (str.Length / 2); i++) { if (str[i] != str[str.Length - 1 - i]) { mismatchedIndexes++; } } int countSwaps = mismatchedIndexes / 2; if (mismatchedIndexes % 2 == 1) { countSwaps++; } return countSwaps; } } } <file_sep>/CodePractice/CodePractice/LeetCode/JumpGame.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { class JumpGame { public bool CanJumpM(int[] nums) { return Jump(nums, nums.Length - 1); } public bool Jump(int[] nums, int i) { if (i == 0) return true; for (int j = i - 1; j >= 0; j--) { if (i - j <= nums[j] && Jump(nums, j)) return true; } return false; } //greedy public bool CanJump2(int[] nums) { int lastPos = nums.Length - 1; for (int i = nums.Length - 1; i >= 0; i--) { if (i + nums[i] >= lastPos) { lastPos = i; } } return lastPos == 0; } //min steps to reach last index //first DP, O(N*N) //TLE public int Jump(int[] nums) { int len = nums.Length; int[] min = Enumerable.Repeat(-1, len).ToArray(); min[len - 1] = 0; for (int i = len - 2; i >= 0; i--) { if (nums[i] == 0) continue; //cannot reach last within one step if (i + nums[i] < len - 1) { int tempMin = int.MaxValue; //find min from i + 1 to i + nums[i] //consider num[i] = 0 for (int j = 1; j <= nums[i]; j++) { if (min[i + j] == -1) continue; if (min[i + j] < tempMin) tempMin = min[i + j]; } min[i] = tempMin == int.MaxValue ? -1: tempMin + 1; // tempMin still max means the values cannt reach last } else min[i] = 1; } return min[0]; } //Greedy //worest is O(n2), one step a time //two loops //currentLeftMost, current left most which can reach last level // was constrained by the greedy solution for Original jump game, going backward. public int JumpGreedy(int[] nums) { int step = 0, len = nums.Length, currentLeftMost = len - 1; while (currentLeftMost > 0) { step++; int temp = currentLeftMost; for (int i = temp - 1; i >= 0; i--) { if (i + nums[i] >= currentLeftMost) temp = i; } currentLeftMost = temp; } return step; } //jump forward public int JumpGreedy2(int[] nums) { int jumps = 0, curEnd = 0, curFarthest = 0; for (int i = 0; i < nums.Length - 1; i++) { curFarthest = Math.Max(curFarthest, i + nums[i]); if (i == curEnd) { jumps++; curEnd = curFarthest; if (curEnd >= nums.Length - 1) { break; } } } return jumps; } } } <file_sep>/CodePractice/CodePractice/Amazon Coding Problems/Anagram.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { public class Anagram { //this more like two pointers. public IList<int> FindAnagramsUsingDictionary(string s, string p) { //sliding window approach, two pointers, one counter List<int> result = new List<int>(); //Dictionary to store the frequency of each characters //more generic way Dictionary<char, int> freq = new Dictionary<char, int>(); for (int i = 0; i < p.Length; i++) { if (freq.ContainsKey(p[i])) freq[p[i]] = freq[p[i]] + 1; else freq.Add(p[i], 1); } //two pointers, one counter int left = 0, right = 0, counter = freq.Count; while (right < s.Length) { if (freq.ContainsKey(s[right])) { freq[s[right]] = freq[s[right]] - 1; //minus one //check if one character in the dictionary is all covered if (freq[s[right]] == 0) counter--; } right++; //next need to move left pointer // this whil loop is to move left all the way to skip // characters not in p, and extra characters from p in s while (counter == 0) { if (freq.ContainsKey(s[left])) { // move pass one character, right side needs to cover this character // so plus one freq[s[left]] = freq[s[left]] + 1; //this check is necessary as the value could be still zero // > 0 means reset to zero, if (freq[s[left]] > 0) counter++; } // all chacters covered plus same length thats a hit if (right - left == p.Length) result.Add(left); //always move left left++; } } return result; } //this is real sliding window, first run is build window with p.Length, then slide // right pointer moves one, left pointer moves one step public IList<int> FindAnagramsUsingArray(string s, string p) { List<int> result = new List<int>(); //we assume the string only contains lower case letters int[] freq = new int[26]; //populate the array for (int i = 0; i < p.Length; i++) freq[p[i] - 'a']++; //two pointers, one counter int left = 0, right = 0, counter = p.Length; while(right < s.Length) { //if freq array has it before //means we need to cover it if(freq[s[right] - 'a'] > 0) counter--; freq[s[right] - 'a']--; //always minus 1 right++; if (counter == 0) result.Add(left); //move left pointer if right -left == p.len if(right - left == p.Length) { if (freq[s[left] - 'a'] >= 0) // going to skip a, count plus one counter++; freq[s[left] - 'a']++; //always plus one left++; } } return result; } } } <file_sep>/CodePractice/CodePractice/Flexera/Billboards.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { class Billboards { static void Print() { string input = Console.ReadLine(); int result = GetRejectNumber(input); Console.WriteLine(result.ToString()); } static int GetRejectNumber(string input) { int result = 0; if (string.IsNullOrWhiteSpace(input)) return result; string[] requests = input.Split(','); //array to store the occupied info for each billboard bool[] occupied = new bool[100]; for(int i = 0; i < requests.Length; i++) { int num = int.Parse(requests[i]); if (num > 100 || occupied[num - 1]) result++; else occupied[num - 1] = true; } return result; } } } <file_sep>/CodePractice/CodePractice/Program.cs using CodePractice.LeetCode; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { class Program { static void Main() { #region old test // TOP N toy problem // string[] toys = { "elmo", "elsa", "legos", "drone", "tablet", "Warcraft" }; // string[] quotes = //{ "Elmo is the hottest of the season! Elmo will be on every kid's wishlist!", //"The new Elmo dolls are super high quality", //"Expect the Elsa dolls to be very popular this year, Elsa!", //"Elsa and Elmo are the toys I'll be buying for my kids, Elsa is good", //"For parents of older kids, look into buying them a drone", //"Warcraft is slowly rising in popularity ahead of the holiday season "}; // var res = new TopNToysClean().TopToys(6, 3, toys, 6, quotes); //Critical Routers //int numRouters = 7; //int numLinks = 7; //int[][] links = new int[][] { new int[] { 0, 1 }, // new int[]{ 0, 2 }, new int[]{ 1, 3 }, new int[]{ 2, 3 }, new int[]{ 2, 5 }, new int[]{ 5, 6 }, new int[]{ 3, 4 } }; //var res = new CriticialRouters().GetCriticalNodes(links, numLinks, numRouters); //EightQueen eightQueen = new EightQueen(); //eightQueen.CalculateQueen(0); //LCS //string a = "ABCBDAB", b = "BDCABA"; //var test = new LongestCommonSequence(); //int res = test.GetLCSLengthUsingOneRow(a, b); //Console.WriteLine("length: " + res); //test.PrintDecisionMatrix(); //int count = test.PrintLCSRevers(a); //Console.WriteLine("count is " + count); //test.PrintLCS(a, 6, 5); //var test = new Knapsack(); ////test.CalculateMaxUsingMemo(0, 0); //int res = test.GetMaxDP(); //[5,9,3,2,1,0,2,3,3,1,0,0] // Mine: -2147483647 //expected: 3 //int[] test = { 5, 9, 3, 2, 1, 0, 2, 3, 3, 1, 0, 0 }; //var res = new JumpGame().JumpGreedy(test); //var res = new SlidingWindowSubstrings().LengthOfLongestSubstring("abcabcbb"); //string m = "<KEY>"; //string s = "eeccccbebaeeabebccceea"; //string s = "abca"; //string s = "<KEY>"; //string s = "abc"; //Console.WriteLine(m == s); //var res = new Palindrome().ValidPalindrome(s); //Console.WriteLine(res); //var res = new SlidingWindowSubstrings().LengthOfLongestSubstring("abcdefgcx"); //Console.WriteLine(res); //List<string> test = new List<string> { "hot", "dot", "dog", "lot", "log", "cog" }; //var res = new WordLadderII().FindLadders2("hit", "cog", test); //["i"],[" "],["a"],["#"],["i"],[" "],["a"],["#"]] //string[] input = { "i love you", "island", "iroman", "i love leetcode" }; //int[] num = { 5, 3, 2, 2 }; //var aut = new AutocompleteSystem(input, num); //var r = aut.Input('i'); //var b = aut.Input(' '); //var c = aut.Input('a'); //var d = aut.Input('#'); //var tt = aut.Input('i'); //var bb = aut.Input(' '); //var cc = aut.Input('a'); //var dd = aut.Input('#'); //var rf = aut.Input('i'); //var bbd = aut.Input(' '); //var cdc = aut.Input('a'); //var ddd = aut.Input #endregion string s = "rabbbit", t = "rabbit"; int ans = NumDistinct(s, t); Console.ReadLine(); } public string SimplifyPath(string path) { string[] dirs = path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); Stack<string> st = new Stack<string>(); foreach(string dir in dirs) { if (dir == ".") continue; else if(dir == "..") { if (st.Count > 0) st.Pop(); } else { st.Push(dir); } } //StringBuilder sb = new StringBuilder(); //while(st.Count > 0) //{ // sb.Insert(0, st.Pop()); // sb.Insert(0, '/'); //} //return sb.Length == 0 ? "/" : sb.ToString(); List<string> result = new List<string>(); while (st.Count > 0) { result.Insert(0, st.Pop()); } return "/" + string.Join("/", result); } public static int NumDistinct(string s, string t) { int m = s.Length, n = t.Length; // dp[i][j] means distinct subsequence for s[0...i-1] and t[0...j-1] int[][] dp = new int[m + 1][]; for (int i = 0; i <= m; i++) dp[i] = new int[n + 1]; for (int i = 0; i <= m; i++) dp[i][0] = 1; // empty string is a sub of any string for (int i = 0; i < m; i++) for (int j = 0; i < n; j++) { if (s[i] == t[j]) dp[i + 1][j + 1] = dp[i][j] + dp[i][j + 1]; // match on both or skip source else dp[i + 1][j + 1] = dp[i][j + 1]; } return dp[m][n]; } //compare diag public void SearchMatrix(int[,] matrix, int target) { int rows = matrix.GetLength(0), cols = matrix.GetLength(1); int lr, lc, rr = rows - 1, rc = cols - 1; if( rows > cols) { lr = rows - cols; lc = 0; } else { lr = 0; lc = cols - rows; } int left = 0, right = Math.Min(rows, cols) - 1; //boundary define while(left < right) { int mid = (left + right) / 2; if (target > matrix[lr + mid, lc + mid]) { left = mid + 1; } else right = mid; } } public string MostCommonWord(string paragraph, string[] banned) { string[] p = paragraph.ToLower().Split(new char[] { ' ', ',', ';', '!', '?', '.', '\''}); Dictionary<string, int> map = new Dictionary<string, int>(); HashSet<string> set = new HashSet<string>(banned); int max = int.MinValue; string ans = string.Empty; foreach (string w in p) { if (!set.Contains(w)) { if (!map.ContainsKey(w)) map.Add(w, 1); else map[w] = map[w] + 1; if (map[w] > max) { max = map[w]; ans = w; } } } return ans; } public void Practice() { string s = "test"; string t = "test"; //256 array int[] map = new int[256]; foreach (char c in t) map[c - 'a']++; int left = 0, right = 0, counter = t.Length; while (right < s.Length) { //decrement the char map[s[right] - 'a']--; //means we have it before if (map[s[right] - 'a'] > 0) ; counter--; // repeating char, val > 1;count++ right++; while (counter == 0) { map[s[left] - 'a']++; if (map[s[right] - 'a'] > 0) counter++; left++; // do something, == length or get min } // get max here } Stack<int> stack = new Stack<int>(); stack.Push(3); stack.Pop(); stack.Peek(); //return res; //test company pc git connection } } } <file_sep>/CodePractice/CodePractice/LeetCode/IntToEnglish.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { public class IntToEnglish { // The leetcod problem is even simpler, no cents. public string NumberToWords(int num) { string strText = string.Empty; string strCurrFormat = string.Empty; int intLowDigit = 0; string strCents = string.Empty; int intDigit1 = 0; int intDigit2 = 0; int intDigit3 = 0; string strSubText = string.Empty; int arrGroupIdx = 0; string[] arrOnes = new string[20]; string[] arrTens = new string[10]; string[] arrGroup = new string[4]; arrOnes[0] = "Zero"; arrOnes[1] = "One"; arrOnes[2] = "Two"; arrOnes[3] = "Three"; arrOnes[4] = "Four"; arrOnes[5] = "Five"; arrOnes[6] = "Six"; arrOnes[7] = "Seven"; arrOnes[8] = "Eight"; arrOnes[9] = "Nine"; arrOnes[10] = "Ten"; arrOnes[11] = "Eleven"; arrOnes[12] = "Twelve"; arrOnes[13] = "Thirteen"; arrOnes[14] = "Fourteen"; arrOnes[15] = "Fifteen"; arrOnes[16] = "Sixteen"; arrOnes[17] = "Seventeen"; arrOnes[18] = "Eighteen"; arrOnes[19] = "Nineteen"; arrTens[0] = "Zero"; arrTens[1] = "Ten"; arrTens[2] = "Twenty"; arrTens[3] = "Thirty"; arrTens[4] = "Forty"; arrTens[5] = "Fifty"; arrTens[6] = "Sixty"; arrTens[7] = "Seventy"; arrTens[8] = "Eighty"; arrTens[9] = "Ninety"; arrGroup[0] = "Zero"; arrGroup[1] = "Thousand"; arrGroup[2] = "Million"; arrGroup[3] = "Billion"; if (num > 0) { strCurrFormat = num.ToString("#,###.00"); intLowDigit = strCurrFormat.IndexOf(".", 0); while (intLowDigit > 0) { intDigit3 = int.Parse(strCurrFormat.Substring(intLowDigit - 1, 1)); if (intLowDigit > 1) intDigit2 = int.Parse(strCurrFormat.Substring(intLowDigit - 2, 1)); else intDigit2 = 0; if (intLowDigit > 2) intDigit1 = int.Parse(strCurrFormat.Substring(intLowDigit - 3, 1)); else intDigit1 = 0; strSubText = string.Empty; if (intDigit1 > 0) strSubText = arrOnes[intDigit1] + " HUNDRED "; if (intDigit2 > 0) { if (intDigit2 == 1) strSubText = strSubText + arrOnes[intDigit3 + 10] + " "; else { strSubText = strSubText + arrTens[intDigit2]; if (intDigit3 > 0) strSubText = strSubText + "-" + arrOnes[intDigit3]; strSubText = strSubText + " "; } } else { if (intDigit3 > 0) strSubText = string.Format("{0}{1}{2}", strSubText, arrOnes[intDigit3], " "); } if (strSubText != "" && arrGroupIdx != 0) strSubText = strSubText + arrGroup[arrGroupIdx] + " "; strText = strSubText + strText; intLowDigit = intLowDigit - 4; arrGroupIdx = arrGroupIdx + 1; } } return strText; } //tricky part to get space right public string NumberToWords2(int num) { string res = string.Empty; int arrGroupIdx = 0; string[] arrOnes = new string[20]; string[] arrTens = new string[10]; string[] arrGroup = new string[4]; arrOnes[0] = "Zero"; arrOnes[1] = "One"; arrOnes[2] = "Two"; arrOnes[3] = "Three"; arrOnes[4] = "Four"; arrOnes[5] = "Five"; arrOnes[6] = "Six"; arrOnes[7] = "Seven"; arrOnes[8] = "Eight"; arrOnes[9] = "Nine"; arrOnes[10] = "Ten"; arrOnes[11] = "Eleven"; arrOnes[12] = "Twelve"; arrOnes[13] = "Thirteen"; arrOnes[14] = "Fourteen"; arrOnes[15] = "Fifteen"; arrOnes[16] = "Sixteen"; arrOnes[17] = "Seventeen"; arrOnes[18] = "Eighteen"; arrOnes[19] = "Nineteen"; arrTens[0] = "Zero"; arrTens[1] = "Ten"; arrTens[2] = "Twenty"; arrTens[3] = "Thirty"; arrTens[4] = "Forty"; arrTens[5] = "Fifty"; arrTens[6] = "Sixty"; arrTens[7] = "Seventy"; arrTens[8] = "Eighty"; arrTens[9] = "Ninety"; arrGroup[0] = "Zero"; arrGroup[1] = "Thousand"; arrGroup[2] = "Million"; arrGroup[3] = "Billion"; //process three characters one time while(num >= 0) { string sub = string.Empty; int lastThree = num % 1000; int digit3 = lastThree % 10; int digit2 = lastThree / 10 % 10; int digit1 = lastThree / 100; if(digit1 > 0) sub += arrOnes[digit1] + " Hundred "; if(digit2 > 0) { if (digit2 == 1) sub += arrOnes[digit2 + digit3] + " "; else { sub += arrTens[digit2]; if(digit3 > 0) sub += " " + arrOnes[digit3]; sub += " "; } } else if (digit3 > 0) { sub += arrOnes[digit3] + " "; } //add unit if (arrGroupIdx > 0) sub += arrGroup[arrGroupIdx] + " "; res += sub; //move to next three num /= 1000; arrGroupIdx++; } return res; } //SurePayroll Way of converting currency to Text #region * string manipulation methods public static string Left(String strParam, int iLen) { if (iLen > 0) return strParam.Substring(0, iLen); else return strParam; } public static string Right(String strParam, int iLen) { if (iLen > 0) return strParam.Substring(strParam.Length - iLen, iLen); else return strParam; } public static string Mid(string param, int startIndex, int length) { string result = param.Substring(startIndex, length); return result; } #endregion public static string ConvertCurrencyToText_TSB(double dblAmount, int intLength) { string strText = string.Empty; string strCurrFormat = string.Empty; int intLowDigit = 0; string strCents = string.Empty; int intDigit1 = 0; int intDigit2 = 0; int intDigit3 = 0; string strSubText = string.Empty; int arrGroupIdx = 0; string[] arrOnes = new string[20]; string[] arrTens = new string[10]; string[] arrGroup = new string[4]; arrOnes[0] = "ZERO"; arrOnes[1] = "ONE"; arrOnes[2] = "TWO"; arrOnes[3] = "THREE"; arrOnes[4] = "FOUR"; arrOnes[5] = "FIVE"; arrOnes[6] = "SIX"; arrOnes[7] = "SEVEN"; arrOnes[8] = "EIGHT"; arrOnes[9] = "NINE"; arrOnes[10] = "TEN"; arrOnes[11] = "ELEVEN"; arrOnes[12] = "TWELVE"; arrOnes[13] = "THIRTEEN"; arrOnes[14] = "FOURTEEN"; arrOnes[15] = "FIFTEEN"; arrOnes[16] = "SIXTEEN"; arrOnes[17] = "SEVENTEEN"; arrOnes[18] = "EIGHTEEN"; arrOnes[19] = "NINETEEN"; arrTens[0] = "ZERO"; arrTens[1] = "TEN"; arrTens[2] = "TWENTY"; arrTens[3] = "THIRTY"; arrTens[4] = "FORTY"; arrTens[5] = "FIFTY"; arrTens[6] = "SIXTY"; arrTens[7] = "SEVENTY"; arrTens[8] = "EIGHTY"; arrTens[9] = "NINETY"; arrGroup[0] = "ZERO"; arrGroup[1] = "THOUSAND"; arrGroup[2] = "MILLION"; arrGroup[3] = "BILLION"; if (dblAmount > 0) { strCurrFormat = dblAmount.ToString("#,###.00"); intLowDigit = strCurrFormat.IndexOf(".", 0); strCents = Mid(strCurrFormat, intLowDigit + 1, 2); while (intLowDigit > 0) { intDigit3 = int.Parse(Mid(strCurrFormat, intLowDigit - 1, 1)); if (intLowDigit > 1) intDigit2 = int.Parse(Mid(strCurrFormat, intLowDigit - 2, 1)); else intDigit2 = 0; if (intLowDigit > 2) intDigit1 = int.Parse(Mid(strCurrFormat, intLowDigit - 3, 1)); else intDigit1 = 0; strSubText = string.Empty; if (intDigit1 > 0) strSubText = arrOnes[intDigit1] + " HUNDRED "; if (intDigit2 > 0) { if (intDigit2 == 1) strSubText = strSubText + arrOnes[intDigit3 + 10] + " "; else { strSubText = strSubText + arrTens[intDigit2]; if (intDigit3 > 0) strSubText = strSubText + "-" + arrOnes[intDigit3]; strSubText = strSubText + " "; } } else { if (intDigit3 > 0) strSubText = string.Format("{0}{1}{2}", strSubText, arrOnes[intDigit3], " "); } if (strSubText != "" && arrGroupIdx != 0) strSubText = strSubText + arrGroup[arrGroupIdx] + " "; strText = strSubText + strText; intLowDigit = intLowDigit - 4; arrGroupIdx = arrGroupIdx + 1; } strText = strText + "& " + strCents + "/100"; if (Left(strText, 1) == "&") strText = "NO " + strText; if (intLength > 0) { if (strText.Length > intLength) { strText = strText + "*****"; } else { for (int iCtr = 1; iCtr <= (intLength - strText.Length); iCtr++) strText = strText + "*"; } } } return strText; } } } <file_sep>/Amazon QA 2022/Questions.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class Questions { // Optimal Utilization public List<int[]> GetPairs(List<int[]> a, List<int[]> b, int target) { a.Sort((i, j) => i[1] - j[1]); b.Sort((i, j) => i[1] - j[1]); List<int[]> result = new List<int[]>(); int max = int.MinValue; int m = a.Count; int n = b.Count; int i = 0; int j = n - 1; while (i < m && j >= 0) { int sum = a[i][1] + b[j][1]; if (sum > target) { --j; } else { if (max <= sum) { if (max < sum) { // we got even closer pair max = sum; result.Clear(); } result.Add(new int[] { a[i][0], b[j][0] }); int index = j - 1; while (index >= 0 && b[index][1] == b[index + 1][1]) { result.Add(new int[] { a[i][0], b[index][0] }); index--; } } ++i; } } return result; } // valid string, similar as valid parenthesis public bool IsValid(String s) { Stack<char> stack = new Stack<char>(); foreach (char c in s) { if (stack.Count == 0 || c != stack.Peek()) { stack.Push(c); } else if (c == stack.Peek()) { stack.Pop(); } } return stack.Count == 0; } // Given an array of only 1 and -1, find a subarray of maximum length such that the product of all the elements in the subarray is 1 // iterate the array, store position of all -1,if count is even number,return whole array, else compare head to last -1, and tail to first 1 // decreasing review list, decreasing sublist // monotonic decrease public static int DecreasingSubarray(int[] array) { Stack<int> stack = new Stack<int>(); int count = 0; for (int i = 0; i < array.Length; i++) { if (stack.Count > 0 && stack.Peek() <= array[i]) { stack.Clear(); } stack.Push(array[i]); count += stack.Count; } return count; } } class Solution { private static int[,] directions = new int[,] { { -1, -1 }, { -1, 0 }, { -1, 1 }, { 0, -1 }, { 0, 1 }, { 1, -1 }, { 1, 0 }, { 1, 1 } }; public int ShortestPathBinaryMatrix(int[][] grid) { // Firstly, we need to check that the start and target cells are open. if (grid[0][0] != 0 || grid[grid.Length - 1][grid[0].Length - 1] != 0) { return -1; } // Set up the BFS. Queue<int[]> queue = new Queue<int[]>(); queue.Enqueue(new int[] { 0, 0, 1 }); // Put distance on the queue bool[,] visited = new bool [grid.Length, grid[0].Length]; // Used as visited set. visited[0,0] = true; // Carry out the BFS while (queue.Count > 0) { int[] cell = queue.Dequeue(); int row = cell[0]; int col = cell[1]; int distance = cell[2]; // Check if this is the target cell. if (row == grid.Length - 1 && col == grid[0].Length - 1) { return distance; } foreach (int[] neighbour in GetNeighbours(row, col, grid)) { int neighbourRow = neighbour[0]; int neighbourCol = neighbour[1]; if (visited[neighbourRow, neighbourCol]) { continue; } visited[neighbourRow, neighbourCol] = true; queue.Enqueue(new int[] { neighbourRow, neighbourCol, distance + 1 }); } } // The target was unreachable. return -1; } private List<int[]> GetNeighbours(int row, int col, int[][] grid) { List<int[]> neighbours = new List<int[]>(); for (int i = 0; i < directions.GetLength(0); i++) { int newRow = row + directions[i,0]; int newCol = col + directions[i, 1]; if (newRow < 0 || newCol < 0 || newRow >= grid.Length || newCol >= grid[0].Length || grid[newRow][newCol] != 0) { continue; } neighbours.Add(new int[] { newRow, newCol }); } return neighbours; } } } <file_sep>/CodePractice/CodePractice/Amazon Coding Problems/TwoSumAll.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { public class TwoSumAll { //O(N) public int UniquePairs(int[] nums, int target) { int count = 0; HashSet<int> used = new HashSet<int>(); HashSet<int> set = new HashSet<int>(); //because no index is need here, can use foreach // if need to return index, use for loop foreach(int num in nums) { if(set.Contains(target - num) && !used.Contains(num)) { count++; used.Add(num); used.Add(target - num); } else if(!set.Contains(num)) { set.Add(num); } } return count; } //find two numbers or indexes from two arrays, closet to target and sum<= target //O(nlogn) + O(mlogm) + O(M + N) //if m == n, then O(nlogn); public int[] TwoSumClosest(int[] arr1, int[] arr2, int target) { Array.Sort(arr1); Array.Sort(arr2); int[] result = new int[2]; int minDiff = int.MaxValue; int lo = 0, hi = arr2.Length - 1; while(lo < arr1.Length && hi >= 0) { int diff = target - (arr1[lo] + arr2[hi]); if (diff > 0) { if (diff < minDiff) { minDiff = diff; result[0] = arr1[lo]; // if we want index, assign to lo result[1] = arr2[hi]; } lo++; } else if (diff < 0) { hi--; } else { result[0] = arr1[lo]; result[1] = arr2[hi]; break; } } return result; } //brutal force public List<int> solution(int target, List<int> foregroundSizes, List<int> backgroundSizes) { // O(n^2) List<int> res = new List<int> { 0, 0 }; int max = 0; for (int i = 0; i < foregroundSizes.Count; i++) { for (int j = 0; j < backgroundSizes.Count; j++) { int cur = foregroundSizes[i] + backgroundSizes[j]; if (cur <= target && cur > max) { max = cur; res[0] = i; res[0] = j; } } } return max == 0 ? new List<int>() : res; } //find two nums for two sum closest that sum <= target //kind of two pointers, O(n) runtime for the loop, O(nlogn) for the sort // so runtime is O(nlogn), space is O(1) public int[] TwoSumClosest(int[] nums, int target) { Array.Sort(nums); int[] result = new int[2]; int minDiff = int.MaxValue; for (int lo = 0, hi = nums.Length - 1; lo < hi;) { int diff = target - (nums[lo] + nums[hi]); if (diff > 0) { //update diff and result if (diff < minDiff) { minDiff = diff; result[0] = nums[lo]; // if we want index, assign to lo result[1] = nums[hi]; } lo++; } else if (diff < 0) { hi--; } else { result[0] = nums[lo]; result[1] = nums[hi]; break; } } return result; } //two sum cloest, return diff (absolute) public int TwoSumClosetDiff(int[] nums, int target) { if (nums == null || nums.Length == 0) { return 0; } Array.Sort(nums); int low = 0, high = nums.Length - 1; int diff = int.MaxValue; while (low < high) { int sum = nums[low] + nums[high]; if (sum > target) { high--; } else { low++; } diff = Math.Min(diff, Math.Abs(sum - target)); } return diff; } //find indexes for two sum equal target public int[] TwoSum(int[] nums, int target) { Dictionary<int, int> dict = new Dictionary<int, int>(); for (int i = 0; i < nums.Length; i++) { int x = nums[i]; if (dict.ContainsKey(target - x)) { return new int[2] { i, dict[target - x] }; } if (!dict.ContainsKey(x)) dict.Add(x, i); } throw new Exception("no two sum solution"); } } } <file_sep>/CodePractice/CodePractice/LeetCode/LFU.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { public class LFUCache { private readonly int capacity; private int curSize; private int minFrequency; private readonly Dictionary<int, DLLNode> cache; private readonly Dictionary<int, DoubleLinkedList> frequencyMap; /*.*/ /* * @param capacity: total capacity of LFU Cache * @param curSize: current size of LFU cache * @param minFrequency: frequency of the last linked list (the minimum frequency of entire LFU cache) * @param cache: a hash map that has key to Node mapping, which used for storing all nodes by their keys * @param frequencyMap: a hash map that has key to linked list mapping, which used for storing all * double linked list by their frequencies * */ public LFUCache(int capacity) { this.capacity = capacity; this.curSize = 0; this.minFrequency = 0; this.cache = new Dictionary<int, DLLNode>(); this.frequencyMap = new Dictionary<int, DoubleLinkedList>(); } /** get node value by key, and then update node frequency as well as relocate that node **/ public int Get(int key) { if (!cache.ContainsKey(key)) return -1; DLLNode curNode = cache[key]; UpdateNode(curNode); return curNode.Value; } /** * add new node into LFU cache, as well as double linked list * condition 1: if LFU cache has input key, update node value and node position in list * condition 2: if LFU cache does NOT have input key * - sub condition 1: if LFU cache does NOT have enough space, remove the Least Recent Used node * in minimum frequency list, then add new node * - sub condition 2: if LFU cache has enough space, add new node directly * **/ public void Put(int key, int value) { // corner case: check cache capacity initialization if (capacity == 0) { return; } if (cache.ContainsKey(key)) { DLLNode curNode = cache[key]; curNode.Value = value; UpdateNode(curNode); } else { curSize++; if (curSize > capacity) { // get minimum frequency list DoubleLinkedList minFreqList = frequencyMap[minFrequency]; DLLNode deleteNode = minFreqList.RemoveTail(); cache.Remove(deleteNode.Key); curSize--; } // reset min frequency to 1 because of adding new node minFrequency = 1; DLLNode newNode = new DLLNode(key, value); // get the list with frequency 1, and then add new node into the list, as well as into LFU cache DoubleLinkedList curList = frequencyMap.ContainsKey(1) ? frequencyMap[1] : new DoubleLinkedList(); curList.AddNode(newNode); // do not add duplicate if (frequencyMap.ContainsKey(1)) frequencyMap[1] = curList; else frequencyMap.Add(1, curList); cache.Add(key, newNode); } } public void UpdateNode(DLLNode curNode) { int curFreq = curNode.Frequency; DoubleLinkedList curList = frequencyMap[curFreq]; curList.RemoveNode(curNode); // if current list the the last list which has lowest frequency and current node is the only node in that list // we need to remove the entire list and then increase min frequency value by 1 if (curFreq == minFrequency && curList.listSize == 0) { minFrequency++; } curNode.Frequency++; // add current node to another list has current frequency + 1, // if we do not have the list with this frequency, initialize it DoubleLinkedList newList = frequencyMap.ContainsKey(curNode.Frequency) ? frequencyMap[curNode.Frequency] : new DoubleLinkedList(); newList.AddNode(curNode); // do not add duplicate if (frequencyMap.ContainsKey(curNode.Frequency)) frequencyMap[curNode.Frequency] = newList; else frequencyMap.Add(curNode.Frequency, newList); } /* * @param key: node key * @param val: node value * @param frequency: frequency count of current node * (all nodes connected in same double linked list has same frequency) * @param prev: previous pointer of current node * @param next: next pointer of current node * */ public class DLLNode { public int Key { get; set; } public int Value { get; set; } public int Frequency { get; set; } public DLLNode Prev { get; set; } public DLLNode Next { get; set; } public DLLNode(int key, int val) { Key = key; Value = val; Frequency = 1; } } /* * @param listSize: current size of double linked list * @param head: head node of double linked list * @param tail: tail node of double linked list * */ public class DoubleLinkedList { public int listSize; readonly DLLNode head; readonly DLLNode tail; public DoubleLinkedList() { this.listSize = 0; this.head = new DLLNode(0, 0); this.tail = new DLLNode(0, 0); head.Next = tail; tail.Prev = head; } /** add new node into head of list and increase list size by 1 **/ public void AddNode(DLLNode curNode) { DLLNode nextNode = head.Next; curNode.Next = nextNode; curNode.Prev = head; head.Next = curNode; nextNode.Prev = curNode; listSize++; } /** remove input node and decrease list size by 1**/ public void RemoveNode(DLLNode curNode) { DLLNode prevNode = curNode.Prev; DLLNode nextNode = curNode.Next; prevNode.Next = nextNode; nextNode.Prev = prevNode; listSize--; } /** remove tail node **/ public DLLNode RemoveTail() { // DO NOT FORGET to check list size if (listSize > 0) { DLLNode tailNode = tail.Prev; RemoveNode(tailNode); return tailNode; } return null; } } } } <file_sep>/CodePractice/CodePractice/Amazon Coding Problems/WordLadder.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { public class WordLadder { public int LadderLength(string beginWord, string endWord, IList<string> wordList) { //got some hint, can use BFS //from begin word, one letter change, a list of words, like one step, one level // on that list, change one letter, another list, like another level // when when hit the target, we return the number of steps. // it is very similar like the remove obstacle problem if (!wordList.Contains(endWord)) return 0; int res = 1; int len = wordList.Count; Queue<string> queue = new Queue<string>(); bool[] visited = new bool[len]; queue.Enqueue(beginWord); //loop through all words, N * N * L //if we use 26 lower case transformation, reduce to N * 26 * L // but the 26 letter transformation needs to check whether the new word is in word list or not, contains/remove all is O(N) operation //logic if wordList constains new word, we remove it from the list and then add to next level list, . This way we dont need the vistied array. // also do not add current word again to next level (queue, hashset, etc). // the solutions have already removed in the list/set before adding to next level, so when we loop next level, it wont be in the word list/set while (queue.Count > 0) { int size = queue.Count; for (int i = 0; i < size; i++) { string word = queue.Dequeue(); //as long as we get the target, we return the value, res result level if (word == endWord) return res; //for (int j = 0; j < len; j++) //{ // if (!visited[j] && DifferByOneLetter(word, wordList[j])) // { // visited[j] = true; // queue.Enqueue(wordList[j]); // } //} } res++; } return 0; } //O(L) operations, L is word length public bool DifferByOneLetter(string s1, string s2) { int count = 0; for (int i = 0; i < s1.Length; i++) { if (s1[i] == s2[i]) continue; count++; if (count > 1) return false; } return true; } public bool DifferByOneLetterClean(string s1, string s2) { int count = 0; for (int i = 0; i < s1.Length; i++) if (s1[i] != s2[i]) count++; return count <= 1; } //use a-z transformation. public int LadderLength2(string beginWord, string endWord, IList<string> wordList) { // assumption is that beginWord is not in wordList // so we dont need to remove from set // because logic is in set, first remove, then add to queue. int level = 1; int len = beginWord.Length; //change list to a set, so contain, remove is O(1) //also remove duplicates HashSet<string> set = new HashSet<string>(wordList); //need a queue Queue<string> queue = new Queue<string>(); //start the queue queue.Enqueue(beginWord); //BFS while(queue.Count > 0) { //level iteration, have to know which level it is //need a size int size = queue.Count; for(int i = 0; i < size; i++) { string s = queue.Dequeue(); //check now if (s == endWord) return level; //now is the trick //for each letter in a string, transform it, //to char array, then replace it for(int j = 0; j < len; j++) //O(L * 26) { //char[] c = s.ToCharArray(); //for (char ch = 'a'; ch <= 'z'; ch++) //{ // //if (ch == s[j]) continue; // skip itself, its unnecessary as we remove temp because add to queue, next level, it wont be added to queue // c[j] = ch; // string temp = new string(c); // if (set.Remove(temp)) //in set and removed // { // queue.Enqueue(temp); // } //} //or this way using stringbuilder StringBuilder sb = new StringBuilder(s); for (char ch = 'a'; ch <= 'z'; ch++) { sb[j] = ch; if (set.Remove(sb.ToString())) //in set and removed { queue.Enqueue(sb.ToString()); } } } } //go to top loop, another level level++; } return 0; } } } <file_sep>/CodePractice/CodePractice/LeetCode/SerializeBinaryTree.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { public class SerializeBinaryTree { public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int x) { val = x; } } // Encodes a tree to a single string. public string serialize(TreeNode root) { StringBuilder sb = new StringBuilder(); //BFS Queue<TreeNode> queue = new Queue<TreeNode>(); queue.Enqueue(root); while (queue.Count > 0) { TreeNode node = queue.Dequeue(); if(node == null) { sb.Append("#,"); continue; } //else //{ sb.Append(string.Format("{0}{1}", node.val, ",")); queue.Enqueue(node.left); queue.Enqueue(node.right); //} } return sb.ToString(); } // Decodes your encoded data to tree. public TreeNode deserialize(string data) { int len = data.Length - 1; data.Remove(len); string[] val = data.Split(new char[] { ',' }); if (val[0] == "#") return null; //bool[] visited = new bool[val.Length]; TreeNode root = new TreeNode(int.Parse(val[0])); //TreeNode current = root; //visited[0] = true; //for(int i = 0; i < val.Length; i++) //{ // if (visited[i]) continue; // int left = 2 * i + 1; // int right = 2 * i + 2; // if (left < val.Length && val[left] != "#") // current.left = new TreeNode(int.Parse(val[left])); //} // again use BFS, cause you used to serialize int i = 1; Queue<TreeNode> queue = new Queue<TreeNode>(); queue.Enqueue(root); while(queue.Count > 0 && i < data.Length) { TreeNode current = queue.Dequeue(); if(val[i] != "#") { TreeNode left = new TreeNode(int.Parse(val[i])); current.left = left; queue.Enqueue(left); } i++; if (val[i] != "#") { TreeNode right = new TreeNode(int.Parse(val[i])); current.right = right; queue.Enqueue(right); } i++; } return root; } public string serialize2(TreeNode root) { StringBuilder sb = new StringBuilder(); //BFS Queue<TreeNode> queue = new Queue<TreeNode>(); queue.Enqueue(root); while (queue.Count > 0) { TreeNode node = queue.Dequeue(); if (node == null) { sb.Append("#,"); continue; } sb.Append(string.Format("{0}{1}", node.val, ",")); queue.Enqueue(node.left); queue.Enqueue(node.right); } string res = sb.ToString(); return res.Remove(res.Length - 1); } // Decodes your encoded data to tree. public TreeNode deserialize2(string data) { string[] val = data.Split(new char[] { ',' }); if (val[0] == "#") return null; TreeNode root = new TreeNode(int.Parse(val[0])); int i = 1; Queue<TreeNode> queue = new Queue<TreeNode>(); queue.Enqueue(root); while (queue.Count > 0 && i < data.Length) { TreeNode current = queue.Dequeue(); if (val[i] != "#") { TreeNode left = new TreeNode(int.Parse(val[i])); current.left = left; queue.Enqueue(left); } i++; if (val[i] != "#") { TreeNode right = new TreeNode(int.Parse(val[i])); current.right = right; queue.Enqueue(right); } i++; } //for loop is also fine, but still queue is neeeded //for (int i = 1; i < val.Length; i++) //{ // TreeNode parent = queue.Dequeue(); // if (!val[i].Equals("#")) // { // TreeNode left = new TreeNode(int.Parse(val[i])); // parent.left = left; // queue.Enqueue(left); // } // if (!val[++i].Equals("n#")) // { // TreeNode right = new TreeNode(int.Parse(val[i])); // parent.right = right; // queue.Enqueue(right); // } //} return root; } public string serialize3(TreeNode root) { return serial(new StringBuilder(), root).ToString(); } // Generate preorder string private StringBuilder serial(StringBuilder str, TreeNode root) { if (root == null) return str.Append("#,"); str.Append(root.val).Append(","); serial(str, root.left); serial(str, root.right); return str; } public TreeNode deserialize3(String data) { return deserial(new LinkedList<string>(data.Split(new char[] { ',' }))); } // Use queue to simplify position move private TreeNode deserial(LinkedList<string> q) { string val = q.First(); q.RemoveFirst(); if (val == "#") return null; TreeNode root = new TreeNode(int.Parse(val)); root.left = deserial(q); root.right = deserial(q); return root; } } } <file_sep>/Amazon QA 2022/GroupDigit.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class GroupDigit { // Grouping Digits // similar as sort color problem // min swap to group public static int MinMoves(int[] input) { int n = input.Length; if (n <= 1) return 0; int[] oneOrZeroAtLeft = new int[2]; for (int k = 0; k < 2; k++) { int first = 0; for (int i = 0; i < n; i++) { if (input[i] == k) { oneOrZeroAtLeft[k] += Math.Abs(i - first); // because we can only swap adjacent, so instead of adding 1,its i-first first++; } } } return Math.Min(oneOrZeroAtLeft[0], oneOrZeroAtLeft[1]); } } } <file_sep>/Amazon QA 2022/OptimalUtilization.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class OptimalUtilization { // Optimal Utilization public List<int[]> GetPairs(List<int[]> a, List<int[]> b, int target) { a.Sort((i, j) => i[1] - j[1]); b.Sort((i, j) => i[1] - j[1]); List<int[]> result = new List<int[]>(); int max = int.MinValue; int m = a.Count; int n = b.Count; int i = 0; int j = n - 1; while (i < m && j >= 0) { int sum = a[i][1] + b[j][1]; if (sum > target) { --j; } else { if (max <= sum) { if (max < sum) { // we got even closer pair max = sum; result.Clear(); } result.Add(new int[] { a[i][0], b[j][0] }); int index = j - 1; while (index >= 0 && b[index][1] == b[index + 1][1]) { result.Add(new int[] { a[i][0], b[index][0] }); index--; } } ++i; } } return result; } } } <file_sep>/README.md # CodePrep This solution is creatd to prepare for Online Assessment<file_sep>/Amazon QA 2022/ConsecutiveElementsByMinus1.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class ConsecutiveElementsByMinus1 { // Function to count Subarrays with // Consecutive elements differing by 1 public static int SubarrayCount(int[] arr, int n) { // Variable to store count of subarrays // whose consecutive elements differ by 1 int result = 0; // Take two pointers for maintaining a // window of consecutive elements int fast = 0, slow = 0; // Traverse the array for (int i = 1; i < n; i++) { // If elements differ by 1 // increment only the fast pointer if (arr[i] - arr[i - 1] == 1) { fast++; } else { // Calculate length of subarray int len = fast - slow + 1; // Calculate total subarrays except // Subarrays with single element result += len * (len - 1) / 2; // Update fast and slow fast = i; slow = i; } } // For last iteration. That is if array is // traversed and fast > slow if (fast != slow) { int len = fast - slow + 1; result += len * (len - 1) / 2; } return result; } } } <file_sep>/Amazon QA 2022/MaxSumAfterPartitioning.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class MaxSumAfterPartitioning { // Partition Array for Maximum Sum // Think dynamic programming: dp[i] will be the answer for array A[0], ..., A[i]. // For j = 1 .. k that keeps everything in bounds, dp[i] is the maximum of dp[i-j] + max(A[i], ..., A[i-j+1]) * j . public int MaxSumAfterPartitioning2(int[] A, int K) { int N = A.Length; int[] dp = new int[N]; for (int i = 0; i < N; ++i) { int curMax = 0; for (int j = 1; j <= K && i - j + 1 >= 0; ++j) { curMax = Math.Max(curMax, A[i - j + 1]); dp[i] = Math.Max(dp[i], (i >= j ? dp[i - j] : 0) + curMax * j); } } return dp[N - 1]; } } } <file_sep>/Amazon QA 2022/DecodeString.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class DecodeString { //decode string public static string DecodeStringWay(string s, int rows) { // assume s.length is divided by n int cols = s.Length / rows; char[,] mat = new char[rows, cols]; int pos = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { mat[i, j] = s[pos++]; } } //All diagonal elements have same j-i difference //string result = ""; StringBuilder sb = new StringBuilder(); for (int diag = 0; diag < cols; diag++) { //j-i=diag. So j=diag+i for (int i = 0; i < rows; i++) { if (diag + i >= cols) break; if (mat[i, i + diag] == '_') sb.Append(" "); else sb.Append(mat[i, i + diag]); } } return sb.ToString(); } } } <file_sep>/Amazon QA 2022/ShortestsPathBinaryMatrix.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { // Shortest path in binary matrix class ShortestsPathBinaryMatrix { private static int[,] directions = new int[,] { { -1, -1 }, { -1, 0 }, { -1, 1 }, { 0, -1 }, { 0, 1 }, { 1, -1 }, { 1, 0 }, { 1, 1 } }; public int ShortestPathBinaryMatrix(int[][] grid) { // Firstly, we need to check that the start and target cells are open. if (grid[0][0] != 0 || grid[grid.Length - 1][grid[0].Length - 1] != 0) { return -1; } // Set up the BFS. Queue<int[]> queue = new Queue<int[]>(); queue.Enqueue(new int[] { 0, 0, 1 }); // Put distance on the queue bool[,] visited = new bool[grid.Length, grid[0].Length]; // Used as visited set. visited[0, 0] = true; // Carry out the BFS while (queue.Count > 0) { int[] cell = queue.Dequeue(); int row = cell[0]; int col = cell[1]; int distance = cell[2]; // Check if this is the target cell. if (row == grid.Length - 1 && col == grid[0].Length - 1) { return distance; } foreach (int[] neighbour in GetNeighbours(row, col, grid)) { int neighbourRow = neighbour[0]; int neighbourCol = neighbour[1]; if (visited[neighbourRow, neighbourCol]) { continue; } visited[neighbourRow, neighbourCol] = true; queue.Enqueue(new int[] { neighbourRow, neighbourCol, distance + 1 }); } } // The target was unreachable. return -1; } private List<int[]> GetNeighbours(int row, int col, int[][] grid) { List<int[]> neighbours = new List<int[]>(); for (int i = 0; i < directions.GetLength(0); i++) { int newRow = row + directions[i, 0]; int newCol = col + directions[i, 1]; if (newRow < 0 || newCol < 0 || newRow >= grid.Length || newCol >= grid[0].Length || grid[newRow][newCol] != 0) { continue; } neighbours.Add(new int[] { newRow, newCol }); } return neighbours; } } } <file_sep>/Amazon QA 2022/MinRoofToCoverCars.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class MinRoofToCoverCars { // min roof public static int MinRoof(int[] pos, int k) { Array.Sort(pos); int min = int.MaxValue; if (pos.Length == 0 || pos.Length < k) return 0; for (int i = 0; i + k - 1 < pos.Length; i++) { min = Math.Min(min, pos[i + k - 1] - pos[i] + 1); } return min; } } } <file_sep>/Microsoft OA 2022/MinDeletionsToMakeFrequencyUnique.cs using System; using System.Collections.Generic; using System.Text; namespace MicrosoftOA { class MinDeletionsToMakeFrequencyUnique { public int MinDeletions(string s) { int[] ct = new int[26]; foreach (char c in s) ct[c - 'a']++; Array.Sort(ct); int del = 0; int maxFreqAllowed = s.Length; for (int i = 25; i >= 0 && ct[i] > 0; i--) { // delete characters to make the frequence equal the max allowed freq if (ct[i] > maxFreqAllowed) { del += ct[i] - maxFreqAllowed; ct[i] = maxFreqAllowed; } // update next max allowed freq to one smaller than current freq maxFreqAllowed = Math.Max(0, ct[i] - 1); } return del; } } } <file_sep>/CodePractice/CodePractice/Paypal.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { public class Paypal { public static List<int> reassignShelves(List<int> shelves) { //1,12,4,12 var ans = new List<int>(); var avail = new List<int>(shelves); avail.Sort(); //1,4,12,12 var dict = new Dictionary<int, int>(); for (var i = 0; i < avail.Count; i++) { if (!dict.ContainsKey(avail[i])) { dict.Add(avail[i], i + 1); } } for (var i = 0; i < shelves.Count; i++) { ans.Add(dict[shelves[i]]); } return ans; } public static string IsSimilarOrder(string s1, string s2) { if (s1.Length != s2.Length) return "NO"; // can use array to do counting as well //var count1 = new Dictionary<char, int>(); //var count2 = new Dictionary<char, int>(); var count1 = new int[26]; var count2 = new int[26]; foreach(char c in s1) { count1[c-'a']++; } foreach(char c in s2) { count2[c - 'a']++; } for(int i = 0; i < 26; i++) { if (count1[i] > 0 && count2[i] > 0) { int delta = Math.Abs(count1[i] - count2[i]); if (delta > 3) return "NO"; } } return "YES"; } public static List<string> userLog(string[] logs, int max) { var result = new List<string>(); // time or (time, isSign) boolean // Dictionary<string, int> map = new Dictionary<string, int>(); Dictionary<string, (int, bool)> map2 = new Dictionary<string, (int, bool)>(); foreach(string log in logs) { string[] items = log.Split(' '); string userId = items[0]; int currentTime = int.Parse(items[1]); //string sign = items[2]; bool isSignIn = items[2] == "sign-in"; if(!map2.ContainsKey(userId)) { map2.Add(userId, (currentTime, isSignIn)); } else { var val = map2[userId]; if(val.Item2 && !isSignIn) { int diff = currentTime - val.Item1; map2[userId] = (diff, isSignIn); } } } foreach(var kvp in map2) { if(kvp.Value.Item1 <= max && !kvp.Value.Item2) { result.Add(kvp.Key); } } result.Sort(); return result; } } } <file_sep>/Microsoft OA 2022/LargestNumberSoBothExist.cs using System; using System.Collections.Generic; using System.Text; namespace MicrosoftOA { class LargestNumberSoBothExist { // Largest value of K such that both K and -K exist in Array in given index range [L, R] public static int FindMax(int N, int[] arr, int L, int R) { // Using a set to store the elements HashSet<int> s = new HashSet<int>(); // ArrayList to store the possible answers List<int> possible = new List<int>(); // Store the answer int ans = 0; // Traverse the array for (int i = 0; i < N; i++) { // If set has it's negation, // check if it is max if (s.Contains(arr[i] * -1)) possible.Add(Math.Abs(arr[i])); else s.Add(arr[i]); } // Find the maximum possible answer for (int i = 0; i < possible.Count; i++) { if (possible[i] >= L && possible[i] <= R) { ans = Math.Max(ans, possible[i]); } } return ans; } // Function to find the Largest Alphabetic char public static String largestchar(String str) { // Array for keeping track of both uppercase // and lowercase english alphabets bool[] uppercase = new bool[26]; bool[] lowercase = new bool[26]; char[] arr = str.ToCharArray(); foreach (char c in arr) { if (char.IsLower(c)) lowercase[c - 'a'] = true; if (char.IsUpper(c)) uppercase[c - 'A'] = true; } // Iterate from right side of array // to get the largest index character for (int i = 25; i >= 0; i--) { // Check for the character if both its // uppercase and lowercase exist or not if (uppercase[i] && lowercase[i]) return (char)(i + 'A') + ""; } // Return -1 if no such character whose // uppercase and lowercase present in // string str return "-1"; } } } <file_sep>/Amazon QA 2022/MaxNumberOfEngineer.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class MaxNumberOfEngineer { // max number of engineers int MaxTeams(int teamSize, int maxDiff, int[] skills) { if (teamSize == 1) return skills.Length; Array.Sort(skills); int teams = 0; int leastSkilled = 0; for (int i = 1; i < skills.Length; ++i) { while (skills[i] - skills[leastSkilled] > maxDiff) ++leastSkilled; if (i - leastSkilled + 1 == teamSize) { ++teams; leastSkilled = i + 1; } } return teams; } } } <file_sep>/Microsoft OA 2022/JumpGameIII.cs using System; using System.Collections.Generic; using System.Text; namespace MicrosoftOA { class JumpGameIII { // jump game public bool CanReach(int[] arr, int start) { int n = arr.Length; Queue<int> q = new Queue<int>(); q.Enqueue(start); while (q.Count > 0) { int node = q.Dequeue(); // check if reach zero if (arr[node] == 0) { return true; } if (arr[node] < 0) { continue; } // check available next steps if (node + arr[node] < n) { q.Enqueue(node + arr[node]); } if (node - arr[node] >= 0) { q.Enqueue(node - arr[node]); } // mark as visited arr[node] = -arr[node]; } return false; } } } <file_sep>/CodePractice/CodePractice/GeekBang/EightQueen.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { public class EightQueen { private readonly int[] result = new int[8]; private int total = 0; public void CalculateQueen(int row) { //accept, return to output if(row == 8) { total++; //printQueen method PrintQueens(); return; } for(int column = 0; column < 8; column++) // first candidate is row and column =0, then next, is row, column+ 1 so on. { if(IsOk(row, column)) // if not okay, then reject and return { result[row] = column; CalculateQueen(row + 1); // back tracking point. } } } private bool IsOk(int row, int column) { int leftUp = column - 1, rightUp = column + 1; //iterate previous rows for(int i = row - 1; i>=0; i--) { //Constraint rules logic implemented here // if there is any queen on the same column up, not ok if (result[i] == column) return false; //diagonal, first is row-1, col -1, goes up one level, row -2, col-2 if (leftUp >= 0 && result[i] == leftUp) return false; if (rightUp < 8 && result[i] == rightUp) return false; leftUp--; rightUp++; } return true; } private void PrintQueens() { for(int row = 0; row < 8; row++) { for(int column = 0; column < 8; column++) { if (result[row] == column) Console.Write("Q "); else Console.Write("* "); } Console.WriteLine(); } Console.WriteLine(total); } } } <file_sep>/CodePractice/CodePractice/LeetCode/InMemoryFileSystem.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { public class FileSystem { private Folder root; public FileSystem() { root = new Folder(); } public IList<string> Ls(string path) { if (path == "/") return ReadFolder(root); char[] delimiter = { '/' }; string[] list = path.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); Folder current = root; for(int i = 0; i < list.Length - 1; i++) { current = current.subFolders[list[i]]; } string lastName = list[list.Length - 1]; if (current.files.ContainsKey(lastName)) { return new List<string> { lastName }; } current = current.subFolders[lastName]; return ReadFolder(current); } public void Mkdir(string path) { char[] delimiter = { '/' }; string[] list = path.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); Folder current = root; for (int i = 0; i < list.Length; i++) { string name = list[i]; if (!current.subFolders.ContainsKey(name)) current.subFolders.Add(name, new Folder()); current = current.subFolders[name]; } } public void AddContentToFile(string filePath, string content) { char[] delimiter = { '/' }; string[] list = filePath.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); Folder current = root; for (int i = 0; i < list.Length - 1; i++) current = current.subFolders[list[i]]; string fileName = list[list.Length - 1]; if (!current.files.ContainsKey(fileName)) current.files.Add(fileName, content); else { current.files[fileName] = current.files[fileName] + content; } } public string ReadContentFromFile(string filePath) { char[] delimiter = { '/' }; string[] list = filePath.Split(delimiter, StringSplitOptions.RemoveEmptyEntries); Folder current = root; for (int i = 0; i < list.Length - 1; i++) current = current.subFolders[list[i]]; string fileName = list[list.Length - 1]; return current.files[fileName]; } public List<string> ReadFolder(Folder node) { var folders = node.subFolders.Keys; var files = node.files.Keys; var res = folders.Concat(files).ToList(); res.Sort(); return res; } } public class Folder { //public string name; //public List<Folder> subFolders; public Dictionary<string, Folder> subFolders = new Dictionary<string, Folder>(); public Dictionary<string, string> files = new Dictionary<string, string>(); // store filename maps to fileContent //public List<File> files; // constructor is not needed } public class File { public string name; public string content; public File(string name, string content) { this.name = name; this.content = content; } } } <file_sep>/CodePractice/CodePractice/Amazon OA/CriticialRouters.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { public class CriticialRouters { // this method is similar to https://www.geeksforgeeks.org/articulation-points-or-cut-vertices-in-a-graph/ // https://www.geeksforgeeks.org/tarjan-algorithm-find-strongly-connected-components/ //good video about finding bridges private int time = 0; public List<int> GetCriticalNodes(int[][] links, int numLinks, int numRouters) { time = 0; Dictionary<int, HashSet<int>> map = new Dictionary<int, HashSet<int>>(); for (int i = 0; i < numRouters; i++) { map.Add(i, new HashSet<int>()); } // each node, store its neighbor nodes in the hashset // in the dictionary foreach (int[] link in links) { map[link[0]].Add(link[1]); map[link[1]].Add(link[0]); } //index i represent node i HashSet<int> set = new HashSet<int>(); int[] low = new int[numRouters]; int[] dis = Enumerable.Repeat<int>(-1, numRouters).ToArray(); //also server the purpose of visited[] array purpose. if not -1, mean visited. int[] parent = Enumerable.Repeat<int>(-1, numRouters).ToArray(); for (int i = 0; i < numRouters; i++) { if (dis[i] == -1) DFS(map, low, dis, parent, i, set); } return set.ToList(); } private void DFS(Dictionary<int, HashSet<int>> map, int[] low, int[] dis, int[] parent, int cur, HashSet<int> res) { int children = 0; dis[cur] = low[cur] = ++time; foreach (int ne in map[cur]) { if (dis[ne] == -1) { children++; parent[ne] = cur; DFS(map, low, dis, parent, ne, res); low[cur] = Math.Min(low[cur], low[ne]); //#1. current is root of DFS tree and has two or more chilren. // #2. If u is not root and low value of one of its child is more than discovery value of u. if ((parent[cur] == -1 && children > 1) || (parent[cur] != -1 && low[ne] >= dis[cur])) // = is right res.Add(cur); } else if (ne != parent[cur]) low[cur] = Math.Min(low[cur], dis[ne]); } } } } <file_sep>/CodePractice/CodePractice/Amazon OA/TopNToysClean.cs using System.Collections.Generic; using System.Linq; namespace CodePractice { public class TopNToysClean { public List<string> TopToys(int numToys, int topToys, string[] toys, int numQuotes, string[] quotes) { List<string> output = new List<string>(); if (numToys == 0 || topToys == 0 || numQuotes == 0 || toys == null || quotes == null) return output; char[] delimiterChars = { ' ', ',', '.', ':', '!', '?', '\t' }; Dictionary<string, int[]> freq = new Dictionary<string, int[]>(); foreach (string toy in toys) { freq.Add(toy.ToLower(), new int[] { 0, 0 }); } foreach (string quote in quotes) { HashSet<string> used = new HashSet<string>(); string[] words = quote.ToLower().Split(delimiterChars, System.StringSplitOptions.RemoveEmptyEntries); foreach (string word in words) { if (!freq.ContainsKey(word)) continue; int[] nums = freq[word]; nums[0]++; if (!used.Contains(word)) { nums[1]++; used.Add(word); } } } //C# doesn't have built in priority queue, has to implement a min-heap below string[] toysInQuote = freq.Where(kv => kv.Value[0] > 0).Select(kv => kv.Key).ToArray(); if (topToys > toysInQuote.Length) topToys = toysInQuote.Length; // array to store min heap of size topToys string[] heap = new string[topToys]; //build min heap, insert one by one, then recalculate up for (int i = 0; i < topToys; i++) { heap[i] = toysInQuote[i]; ReCalculateUp(heap, i, freq); } //loop through rest of toys in quote for (int i = topToys; i < toysInQuote.Length; i++) { if (Compare(toysInQuote[i], heap[0], freq) > 0) { heap[0] = toysInQuote[i]; ReCalculateDown(heap, 0, topToys, freq); } } // now heap is array contain top toys for (int i = topToys - 1; i >= 0; i--) // dont need to do for 0, but we need to add last heap[0] to output, so still i >= 0 { output.Add(heap[0]); heap[0] = heap[i]; // since heap[0] is gone, so there are two duplicate values in the array, thats why it was working before. // we dont need to include heap[i], last element in the array. size should decrease by one before we re heapify, index always 1 less than size, so good to use // then for i = 1 and 0, no swap in the sink method. ReCalculateDown(heap, 0, i, freq); } output.Reverse(); return output; } public void ReCalculateDown(string[] arr, int index, int size, Dictionary<string, int[]> freq) { while (true) { int min = index; int left = 2 * index + 1; int right = 2 * index + 2; if (left < size && Compare(arr[min], arr[left], freq) > 0) min = left; if (right < size && Compare(arr[min], arr[right], freq) > 0) min = right; if (min == index) return; // NO swap Swap(arr, min, index); index = min; } } public void ReCalculateUp(string[] arr, int index, Dictionary<string, int[]> freq) { // has parent node and parent value > child value while (index > 0 && Compare(arr[(index - 1) / 2], arr[index], freq) > 0) { Swap(arr, index, (index - 1) / 2); index = (index - 1) / 2; } } public int Compare(string k1, string k2, Dictionary<string, int[]> freq) { if (freq[k1][0] != freq[k2][0]) return freq[k1][0] - freq[k2][0]; if (freq[k1][1] != freq[k2][1]) return freq[k1][1] - freq[k2][1]; return k2.CompareTo(k1); } public void Swap(string[] arr, int a, int b) { string temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } } } <file_sep>/CodePractice/CodePractice/LeetCode/WordBreak.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { class WordBreak2 { public static IList<string> WordBreak(string s, IList<string> wordDict) { return DFS(s, wordDict, new Dictionary<string, LinkedList<string>>()); } /// <summary> /// DFS function returns an array including all substrings derived from s. /// I need to get comfortable to use Double Linked List class LinkedList class /// Also I need to push myself to put together a memoization plan when I try to apply DFS search. /// Focus on more using string class API like StartsWith, same as Java class. /// LinkedList is a good choice to manage the collection in-between given function argument and final result. /// </summary> /// <param name="s"></param> /// <param name="wordDict"></param> /// <param name="map"></param> /// <returns></returns> private static IList<string> DFS(string s, IList<string> wordDict, Dictionary<string, LinkedList<string>> map) { // Look up cache if (map.ContainsKey(s)) { return map[s].ToList(); } var list = new LinkedList<string>(); // base case if (s.Length == 0) { list.AddLast(""); return list.ToList(); } // go over each word in dictionary foreach (string word in wordDict) { if (s.StartsWith(word)) { var sublist = DFS(s.Substring(word.Length), wordDict, map); foreach (string sub in sublist) { list.AddLast(word + (string.IsNullOrEmpty(sub) ? "" : " ") + sub); } } } // memoization map.Add(s, list); return list.ToList(); } // dont understand why use linked list, a little faster than list solution public List<string> WordBreak4(string s, IList<string> wordDict) { // no meaning for this one int n = s.Length; HashSet<string> set = new HashSet<string>(wordDict); // Check if there is at least one possible sentence bool[] dp1 = new bool[n + 1]; dp1[0] = true; for (int i = 1; i <= n; i++) { for (int j = 0; j < i; j++) { if (dp1[j] && set.Contains(s.Substring(j, i - j))) { dp1[i] = true; break; } } } // We are done if there isn't a valid sentence at all if (!dp1[n]) { return new List<string>(); } //interstingly that the above code snnipt solves the TLE problem LinkedList<string>[] dp = new LinkedList<string>[n + 1]; LinkedList<string> initial = new LinkedList<string>(); initial.AddLast(""); dp[0] = initial; for (int i = 1; i <= s.Length; i++) { LinkedList<string> list = new LinkedList<string>(); for (int j = 0; j < i; j++) { if (dp[j].Count > 0 && set.Contains(s.Substring(j, i - j))) { foreach (string l in dp[j]) { list.AddLast(l + (string.IsNullOrEmpty(l) ? "" : " ") + s.Substring(j, i-j)); } } } dp[i] = list; } return dp[n].ToList(); } //use list, TLE public List<string> WordBreak3(string s, IList<string> wordDict) { int n = s.Length; HashSet<string> set = new HashSet<string>(wordDict); List<string>[] dp = new List<string>[n + 1]; List<string> initial = new List<string>(); initial.Add(""); dp[0] = initial; for (int i = 1; i <= s.Length; i++) { List<string> list = new List<string>(); for (int j = 0; j < i; j++) { if (dp[j].Count > 0 && set.Contains(s.Substring(j, i - j))) { foreach (string l in dp[j]) { list.Add(l + (string.IsNullOrEmpty(l) ? "" : " ") + s.Substring(j, i - j)); } } } dp[i] = list; } return dp[n]; } } public class TT { private Dictionary<string, List<string>> cache = new Dictionary<string, List<string>>(); public List<string> WordBreak(string s, IList<string> wordDict) { return WordBreak(s, new HashSet<string>(wordDict)); } private bool containsSuffix(HashSet<string> dict, string str) { for (int i = 0; i < str.Length; i++) { if (dict.Contains(str.Substring(i))) return true; } return false; } public List<string> WordBreak(string s, HashSet<string> dict) { if (cache.ContainsKey(s)) return cache[s]; List<string> result = new List<string>(); if (dict.Contains(s)) result.Add(s); for (int i = 1; i < s.Length; i++) { string left = s.Substring(0, i), right = s.Substring(i); if (dict.Contains(left) && containsSuffix(dict, right)) { foreach (string ss in WordBreak(right, dict)) { result.Add(left + " " + ss); } } } cache.Add(s, result); return result; } } } <file_sep>/CodePractice/CodePractice/LeetCode/LRUCache.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { //Array based //least used // plus hashtable to store key value public class LRUCache { private readonly int capacity; private int count; private readonly int[] store; private readonly Dictionary<int, int> cache; public LRUCache(int capacity) { this.capacity = capacity; count = 0; store = new int[capacity]; cache = new Dictionary<int, int>(); } public int Get(int key) { if (!cache.ContainsKey(key))return -1; //int is accessed, so it has to be moved to last position of array int i = 0; while (i < count) { if (store[i] == key) break; i++; } while (i < count - 1) { // move element from i + 1 to count - 1 to i > count -2 store[i] = store[i + 1]; i++; } store[count - 1] = key; return cache[key]; } // most recently used, put to last position of array // least recently used, put to first position of array public void Put(int key, int value) { if(cache.ContainsKey(key)) { int i = 0; while(i < count) { if (store[i] == key) break; i++; } while(i < count - 1 ) { // move element from i + 1 to count - 1 to i > count -2 store[i] = store[i + 1]; i++; } store[count - 1] = key; //update value cache[key] = value; } else { // if capactiy is not full, just insert if(count < capacity) //put at last position store[count++] = key; else { // first delete most least used element, which is at position zero // also rememer to delete this least used key/value from cache cache.Remove(store[0]); //move all position one level up for (int i = 0; i < count - 1; i++) store[i] = store[i + 1]; // now we have position at count - 1 store[count - 1] = key; } cache.Add(key, value); } } } } <file_sep>/Microsoft OA 2022/MinSwapToMakeStringPalindrome.cs using System; using System.Collections.Generic; using System.Text; namespace MicrosoftOA { // Time O(N2), Space O(1) // https://www.geeksforgeeks.org/count-minimum-swap-to-make-string-palindrome/ class MinSwapToMakeStringPalindrome { // Function to Count minimum swap static int countSwap(String str) { // Length of string int n = str.Length; // it will convert string to // char array char[] s = str.ToCharArray(); // Counter to count minimum // swap int count = 0; // A loop which run in half // string from starting for (int i = 0; i < n / 2; i++) { // Left pointer int left = i; // Right pointer int right = n - left - 1; // A loop which run from // right pointer to left // pointer while (left < right) { // if both char same // then break the loop // if not same then we // have to move right // pointer to one step // left if (s[left] == s[right]) { break; } else { right--; } } // it denotes both pointer at // same position and we don't // have sufficient char to make // palindrome string if (left == right) { return -1; } else { for (int j = right; j < n - left - 1; j++) { char t = s[j]; s[j] = s[j + 1]; s[j + 1] = t; count++; } } } return count; } // min swap to make 0/1 palindrome public static int MinSwapsPal(string str) { int countOne = 0; int countZero = 0; foreach (char c in str) { if (c == '0') { countZero++; } else { countOne++; } } if (countOne % 2 == 1 && countZero % 2 == 1) { return -1; } int mismatchedIndexes = 0; for (int i = 0; i < (str.Length / 2); i++) { if (str[i] != str[str.Length - 1 - i]) { mismatchedIndexes++; } } int countSwaps = mismatchedIndexes / 2; if (mismatchedIndexes % 2 == 1) { countSwaps++; } return countSwaps; } } } <file_sep>/CodePractice/CodePractice/LeetCode/MedianFinderHeap.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { //It passed the test Yes public class MedianFinderHeap { private MaxHeap left; private MinHeap right; /** initialize your data structure here. */ public MedianFinderHeap() { left = new MaxHeap(1000); right = new MinHeap(1000); } public void AddNum(int num) { if (left.IsEmpty() || num <= left.Peek()) left.Add(num); else right.Add(num); //keep balance if (left.Count() - right.Count() > 1) right.Add(left.Pop()); if (right.Count() - left.Count() > 1) left.Add(right.Pop()); } public double FindMedian() { if (left.Count() == right.Count()) { return (double)(left.Peek() + right.Peek()) / 2; } else if (left.Count() > right.Count()) { return left.Peek(); } else { return right.Peek(); } } } public class MinHeap { private int used; private int[] store; public MinHeap(int cap) { used = 0; store = new int[cap]; } public bool IsEmpty() { return used == 0; } public int Count() { return used; } public int Peek() { if (used == 0) throw new IndexOutOfRangeException(); return store[0]; } public int Pop() { if (used == 0) throw new IndexOutOfRangeException(); var result = store[0]; store[0] = store[used - 1]; used--; Sink(); return result; } public void Add(int val) { if (used == store.Length) Resize(); store[used] = val; used++; BubbleUp(); } private void BubbleUp() { int index = used - 1; while (index > 0 && store[index] < store[(index - 1) / 2]) { Swap(store, index, (index - 1) / 2); index = (index - 1) / 2; } } private void Sink() { int index = 0; while (true) { int min = index; int left = 2 * index + 1; int right = 2 * index + 2; if (left < used && store[min] > store[left]) min = left; if (right < used && store[min] > store[right]) min = right; if (min == index) return; // NO swap Swap(store, min, index); index = min; } } void Swap(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } void Resize() { int[] temp = new int[2 * store.Length]; store.CopyTo(temp, 0); store = temp; } } public class MaxHeap { private int used; private int[] store; public MaxHeap(int cap) { used = 0; store = new int[cap]; } public bool IsEmpty() { return used == 0; } public int Count() { return used; } public int Peek() { if (used == 0) throw new IndexOutOfRangeException(); return store[0]; } public int Pop() { if (used == 0) throw new IndexOutOfRangeException(); var result = store[0]; store[0] = store[used - 1]; used--; Sink(); return result; } public void Add(int val) { if (used == store.Length) Resize(); store[used] = val; used++; BubbleUp(); } private void BubbleUp() { int index = used - 1; while (index > 0 && store[index] > store[(index - 1) / 2]) { Swap(store, index, (index - 1) / 2); index = (index - 1) / 2; } } private void Sink() { int index = 0; while (true) { int max = index; int left = 2 * index + 1; int right = 2 * index + 2; if (left < used && store[max] < store[left]) max = left; if (right < used && store[max] < store[right]) max = right; if (max == index) return; // NO swap Swap(store, max, index); index = max; } } void Swap(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } void Resize() { int[] temp = new int[2 * store.Length]; store.CopyTo(temp, 0); store = temp; } } // public class MedianFinder2 { private int counter = 0; private SortedSet<int[]> setLow = new SortedSet<int[]>(Comparer<int[]>.Create((a, b) => a[0] == b[0] ? a[1] - b[1] : a[0] - b[0])); private SortedSet<int[]> setHigh = new SortedSet<int[]>(Comparer<int[]>.Create((a, b) => a[0] == b[0] ? a[1] - b[1] : a[0] - b[0])); public void AddNum(int num) { int[] newNum = new int[2] { num, counter++ }; if (setLow.Count == setHigh.Count) { if (setLow.Count == 0 || newNum[0] <= setLow.Max[0]) setLow.Add(newNum); else { setHigh.Add(newNum); setLow.Add(setHigh.Min); setHigh.Remove(setHigh.Min); } } else if (newNum[0] <= setLow.Max[0]) { setLow.Add(newNum); setHigh.Add(setLow.Max); setLow.Remove(setLow.Max); } else setHigh.Add(newNum); } // return the median of current data stream public double FindMedian() { if (setLow.Count == 0) return 0; if (setLow.Count == setHigh.Count) return (setLow.Max[0] + setHigh.Min[0]) / 2d; else return setLow.Max[0]; } } } <file_sep>/CodePractice/CodePractice/LeetCode/MorrisTreeTraversal.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { class MorrisTreeTraversal { class Node { public int data; public Node left_node, right_node; Node(int item) { data = item; left_node = null; right_node = null; } } class Tree { readonly Node root; void MorrisInOrder(Node root) { Node curr, prev; if (root == null) return; curr = root; while (curr != null) { if (curr.left_node == null) { Console.WriteLine(curr.data + " "); curr = curr.right_node; } else { /* Find the previous (prev) of curr */ prev = curr.left_node; while (prev.right_node != null && prev.right_node != curr) prev = prev.right_node; /* Make curr as right child of its prev */ if (prev.right_node == null) { prev.right_node = curr; curr = curr.left_node; } /* fix the right child of prev*/ else { prev.right_node = null; Console.WriteLine(curr.data + " "); // Visit here, come back to current node, left subtree has be traversed already, now come back curr = curr.right_node; } } } } //public List<Integer> preorderTraversal(TreeNode root) //{ // LinkedList<Integer> output = new LinkedList<>(); // TreeNode node = root; // while (node != null) // { // if (node.left == null) // { // output.add(node.val); // Visit // node = node.right; // } // else // { // TreeNode predecessor = node.left; // while ((predecessor.right != null) && (predecessor.right != node)) // { // predecessor = predecessor.right; // } // if (predecessor.right == null) // { // output.add(node.val); // Visit before even processing the left // predecessor.right = node; // node = node.left; // } // else // { // predecessor.right = null; // come back to current // node = node.right; // } // } // } //} } } } <file_sep>/CodePractice/CodePractice/Amazon OA/RottingOrange.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { public class RottingOrange { public int OrangesRotting(int[][] grid) { //edge case if (grid == null || grid.Length == 0) return 0; //define direction array to code cleaness int[][] dir = new int[4][] { new int[] { 1, 0 }, new int[] { -1, 0 }, new int[] { 0, 1 }, new int[] { 0, -1 } }; int rows = grid.Length; int cols = grid[0].Length; Queue<int[]> queue = new Queue<int[]>(); int count_fresh = 0; int time = 0; // two for loop for(int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (grid[i][j] == 2) queue.Enqueue(new int[] { i, j }); // add index of rotten orange to queue else if (grid[i][j] == 1) count_fresh++; } } //if no fresh orange if (count_fresh == 0) return 0; //BFS while (queue.Count > 0) { time++; int size = queue.Count; // take out all elements in the queue, represent the rotten organge at time x // can not use queue.count, it is changed every time for(int i = 0; i < size; i++) { int[] point = queue.Dequeue(); foreach(int[] dr in dir) { int r = point[0] + dr[0]; int c = point[1] + dr[1]; if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] != 1) continue; grid[r][c] = 2; queue.Enqueue(new int[] { r, c }); count_fresh--; } } } return count_fresh == 0 ? time - 1 : -1; } //only '1' and '0' public int ServerProblem(int rows, int cols, int[][] grid) { //edge case if (grid == null || grid.Length == 0) return 0; //define direction array for code cleaness int[][] dir = new int[4][] { new int[] { 1, 0 }, new int[] { -1, 0 }, new int[] { 0, 1 }, new int[] { 0, -1 } }; Queue<int[]> queue = new Queue<int[]>(); int count_old = 0; int days = 0; // count the out of date servers and also add updated servers to the queue for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (grid[i][j] == 1) queue.Enqueue(new int[] { i, j }); // add index of updated server to queue else if (grid[i][j] == 0) count_old++; } } //BFS while (queue.Count > 0 && count_old > 0) { days++; int size = queue.Count; // take out all elements in the queue, represent the rotten organge at time x // can not use queue.count, it is changed every time for (int i = 0; i < size; i++) { int[] point = queue.Dequeue(); foreach (int[] dr in dir) { int r = point[0] + dr[0]; int c = point[1] + dr[1]; if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == 1) continue; grid[r][c] = 1; // mark as updated queue.Enqueue(new int[] { r, c }); count_old--; } } } return count_old == 0 ? days : -1; } } } <file_sep>/Amazon QA 2022/MaxSubArrayLengthProductOne.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class MaxSubArrayLengthProductOne { // Given an array of only 1 and -1, find a subarray of maximum length such that the product of all the elements in the subarray is 1 // iterate the array, store position of all -1,if count is even number,return whole array, else compare head to last -1, and tail to first 1 static int max(int[] a) { int c = 0; int fnegindex = -1;//for the first negative index int lnegindex = -1;//for the last negative index for (int i = 0; i < a.Length; i++) { if (a[i] == -1) { if (fnegindex == -1) { fnegindex = i; } lnegindex = i; c++; } } if (c % 2 == 0) return a.Length; else { return Math.Max(a.Length - fnegindex - 1, lnegindex); } } } } <file_sep>/Microsoft OA 2022/Program.cs using System; using System.Collections.Generic; namespace MicrosoftOA { class Program { static void Main(string[] args) { int test = Convert(423, 40); Console.WriteLine(test); Console.WriteLine("Hello World!"); } static int Convert(int N, int k) { int remaining = k; int div = 100, res = 0; while(div != 0) { int temp = N / div; int digit = remaining > 0 ? 9 - temp <= remaining ? 9 : temp + remaining : temp; remaining -= 9 - temp; res += digit * div; N %= div; div /= 10; } return res; } public int CountServers(int[][] grid) { if (grid == null || grid.Length == 0 || grid[0].Length == 0) return 0; int numRows = grid.Length; int numCols = grid[0].Length; int[] rowCount = new int[numRows]; int[] colCount = new int[numCols]; for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { if (grid[row][col] == 1) { rowCount[row]++; colCount[col]++; } } } int result = 0; for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { if (grid[row][col] == 1 && (rowCount[row] > 1 || colCount[col] > 1)) { result++; } } } return result; } public int MaxNonOverlapping(int[] nums, int target) { Dictionary<int, int> map = new Dictionary<int, int>(); map.Add(0, 0); int res = 0; int sum = 0; for (int i = 0; i < nums.Length; ++i) { sum += nums[i]; if (map.ContainsKey(sum - target)) { res = Math.Max(res, map[sum - target] + 1); } if (!map.ContainsKey(sum)) map.Add(sum, res); else map[sum] = res; } return res; } public int maxNonOverlapping(int[] nums, int target) { Dictionary<int, int> map = new Dictionary<int, int>(); int prefixSum = 0, availableIdx = -1, res = 0; map.Add(0, -1); for (int i = 0; i < nums.Length; i++) { prefixSum += nums[i]; int remain = prefixSum - target; if (map.ContainsKey(remain) && map[remain] >= availableIdx) { res++; availableIdx = i; } if (!map.ContainsKey(prefixSum)) map.Add(prefixSum, res); else map[prefixSum] = res; } return res; } } } <file_sep>/Amazon QA 2022/BalancedString.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class BalancedString { // ways to split, balanced string, not fully working, but at least something. public static int SplitWays(string s) { int count = 0; Dictionary<char, int> leftBrackets = new Dictionary<char, int>(); Dictionary<char, int> rightBrackets = CountBrackets(s); leftBrackets[s[0]] = 1; rightBrackets[s[0]]--; for (int i = 1; i < s.Length - 1; i++) { leftBrackets[s[i]] = leftBrackets.GetValueOrDefault(s[i], 0) + 1; rightBrackets[s[i]]--; if (IsBalanced(leftBrackets) && IsBalanced(rightBrackets)) { count++; } } return count; } private static bool IsBalanced(Dictionary<char, int> brackets) { int rdOpen = brackets.GetValueOrDefault('(', 0); int rdClose = brackets.GetValueOrDefault(')', 0); int sqOpen = brackets.GetValueOrDefault('[', 0); int sqClose = brackets.GetValueOrDefault(']', 0); int questionMark = brackets.GetValueOrDefault('?', 0); int rdDiff = Math.Abs(rdOpen - rdClose); int sqDiff = Math.Abs(sqOpen - sqClose); int diff = rdDiff + sqDiff; if (diff == 0 && questionMark % 2 == 0) { return true; } questionMark -= diff; if (questionMark < 0) { return false; } return questionMark % 2 == 0; } private static Dictionary<char, int> CountBrackets(string s) { Dictionary<char, int> charFreq = new Dictionary<char, int>(); foreach (char c in s) { charFreq[c] = charFreq.GetValueOrDefault(c, 0) + 1; } return charFreq; } } } <file_sep>/CodePractice/CodePractice/Amazon OA/ProductSuggestionPrefer.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { class ProductSuggestionPrefer { class Trie { public Trie[] Children = new Trie[26]; public List<string> Suggestion = new List<string>(); } public IList<IList<string>> SuggestedProducts(string[] products, string searchWord) { // Array.Sort(products); //O(n * logn * m); Trie root = new Trie(); BuildTrie(root, products); List<IList<string>> result = new List<IList<string>>(); foreach (char c in searchWord) { if(root != null) root = root.Children[c - 'a']; if (root != null) { // not sorting the produdct array, but sort each suggestion array, and then take first three. root.Suggestion.Sort(); // comment this line if already sorted the product array result.Add(root.Suggestion.GetRange(0, Math.Min(3, root.Suggestion.Count))); } else { result.Add(new List<string>()); } } return result; } private void BuildTrie(Trie root, string[] products) { foreach (string word in products) // n * m { Trie current = root; foreach (char c in word) { if (current.Children[c - 'a'] == null) { current.Children[c - 'a'] = new Trie(); } current = current.Children[c - 'a']; current.Suggestion.Add(word); // put products with same prefix into suggestion list. } } } } } <file_sep>/Amazon QA 2022/KthLargest.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { // k largest in a data stream public class KthLargest { private int k; private SimpleHeap heap = new SimpleHeap(); public KthLargest(int k, int[] nums) { this.k = k; foreach (int num in nums) { heap.Add(num); if (heap.GetSize() > k) heap.Pop(); } } public int Add(int val) { heap.Add(val); if (heap.GetSize() > k) heap.Pop(); return heap.Peek(); } } public class SimpleHeap { private static readonly int DEFAULT_CAPACITY = 11; private int used; private int[] store; public SimpleHeap() : this(DEFAULT_CAPACITY) { } public SimpleHeap(int cap) { used = 0; store = new int[cap]; } public bool IsEmpty() { return used == 0; } public int GetSize() { return used; } public int Peek() { if (used == 0) throw new IndexOutOfRangeException(); return store[0]; } public int Pop() { if (used == 0) throw new IndexOutOfRangeException(); var result = store[0]; store[0] = store[used - 1]; used--; Sink(); return result; } public void Add(int val) { if (used == store.Length) Resize(); store[used] = val; used++; BubbleUp(); } private void BubbleUp() { int index = used - 1; while (index > 0 && store[index] < store[(index - 1) / 2]) { Swap(store, index, (index - 1) / 2); index = (index - 1) / 2; } } private void Sink() { int index = 0; while (true) { int min = index; int left = 2 * index + 1; int right = 2 * index + 2; if (left < used && store[min] > store[left]) min = left; if (right < used && store[min] > store[right]) min = right; if (min == index) return; // NO swap Swap(store, min, index); index = min; } } public void Swap(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } void Resize() { int[] temp = new int[2 * store.Length]; store.CopyTo(temp, 0); store = temp; } } } <file_sep>/Microsoft OA 2022/MaxSubstringLengthWithout3Consecutive.cs using System; using System.Collections.Generic; using System.Text; namespace MicrosoftOA { class MaxSubstringLengthWithout3Consecutive { // Function to return the length of the // longest substring such that no three // consecutive characters are same static int maxLenSubStr(String s) { // If the length of the given string // is less than 3 if (s.Length < 3) return s.Length; // Initialize temporary and final ans // to 2 as this is the minimum length // of substring when length of the given // string is greater than 2 int temp = 2; int ans = 2; // Traverse the string from the // third character to the last for (int i = 2; i < s.Length; i++) { // If no three consecutive characters // are same then increment temporary count if (s[i] != s[i - 1] || s[i] != s[i - 2]) temp++; // Else update the final ans and // reset the temporary count else { ans = Math.Max(temp, ans); temp = 2; } } ans = Math.Max(temp, ans); return ans; } } } <file_sep>/Amazon QA 2022/DecreaseReviewList.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class DecreaseReviewList { // decreasing review list, decreasing sublist // monotonic decrease public int DecreasingSubarray(int[] array) { Stack<int> stack = new Stack<int>(); int count = 0; for (int i = 0; i < array.Length; i++) { if (stack.Count > 0 && stack.Peek() <= array[i]) { stack.Clear(); } stack.Push(array[i]); count += stack.Count; } return count; } } } <file_sep>/CodePractice/CodePractice/LeetCode/WordSearch.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { class WordSearch { //I have some idea about it, using DFS, I know how to solve with one start node //but this one have all possible starting node, so the actually search, is to try every possible // starting node, I am trying to optimize at very beginning, no need. just get the answer first. //DFS mix with backtrack (normal DFS, terminating is reaching boundary, while backtrack, it is not found a solution, not valid step) public bool Exist(char[][] board, string word) { //start from all nodes for(int i = 0; i < board.Length; i++) { for(int j =0; j < board[0].Length; j++) { // anytime it is found, method return. if (DFS(board, word, i, j, 0)) return true; } } return false; } // there is a bug, cannot reuse letter inside one try private bool DFS(char[][] board, string word, int row, int col, int pos) { // found if (pos == word.Length) return true; // out of grid if (row < 0 || row >= board.Length || col < 0 || col >= board[0].Length) return false; char temp = board[row][col]; if (temp != word[pos]) return false; // make sure same node is not reused board[row][col] = '*'; // run four directions, if first true, second not exectued. bool exist= DFS(board, word, row + 1, col, pos + 1) || DFS(board, word, row - 1, col, pos + 1) || DFS(board, word, row, col + 1, pos + 1) || DFS(board, word, row, col - 1, pos + 1); //this the point of backtrack, you go back, and another route, this node can be reused now board[row][col] = temp; return exist; } //word search II, kind of brutal force public IList<string> FindWords(char[][] board, string[] words) { List<string> ret = new List<string>(); foreach (string word in words) { if (Exist(board, word)) ret.Add(word); } return ret; } } public class Solution { public IList<int> TopKFrequent(int[] nums, int k) { List<int> output = new List<int>(); Dictionary<int, int> fre = new Dictionary<int, int>(); foreach (int s in nums) { if (!fre.ContainsKey(s)) { fre.Add(s, 1); continue; } fre[s] = fre[s] + 1; } nums = fre.Keys.ToArray(); // remove duplicates in dict int[] heap = new int[k]; //insert the k words in heap for (int i = 0; i < k; i++) { heap[i] = nums[i]; ReCalculateUp(heap, i, fre); } for (int i = k; i < nums.Length; i++) { if (Compare(nums[i], heap[0], fre) > 0) { heap[0] = nums[i]; ReCalculateDown(heap, 0, k, fre); } } for (int i = k - 1; i >= 0; i--) { output.Add(heap[0]); heap[0] = heap[i]; ReCalculateDown(heap, 0, i, fre); } output.Reverse(); return output; } public void ReCalculateDown(int[] arr, int index, int size, Dictionary<int, int> freq) { while (true) { int min = index; int left = 2 * index + 1; int right = 2 * index + 2; if (left < size && Compare(arr[min], arr[left], freq) > 0) min = left; if (right < size && Compare(arr[min], arr[right], freq) > 0) min = right; if (min == index) return; // NO swap Swap(arr, min, index); index = min; } } public void ReCalculateUp(int[] arr, int index, Dictionary<int, int> freq) { // has parent node and parent value > child value while (index > 0 && Compare(arr[(index - 1) / 2], arr[index], freq) > 0) { Swap(arr, index, (index - 1) / 2); index = (index - 1) / 2; } } public int Compare(int k1, int k2, Dictionary<int, int> freq) { if (freq[k1] != freq[k2]) return freq[k1] - freq[k2]; return k2.CompareTo(k1); } public void Swap(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } } } <file_sep>/CodePractice/CodePractice/LeetCode/MedianFinder.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { public class MedianFinder { /** initialize your data structure here. */ public MedianFinder() { } //because no duplicate allow in the sorted set. private SortedSet<int> setLow = new SortedSet<int>(); private SortedSet<int> setHigh = new SortedSet<int>(); public void AddNum(int num) { bool twoTreesSameSize = setLow.Count == setHigh.Count; //keep setLow size >= setHigh if (twoTreesSameSize) { if (setLow.Count == 0 || num <= setLow.Max) { setLow.Add(num); } else { setHigh.Add(num); // move the minimum number from setHigh to setLow. setLow.Add(setHigh.Min); setHigh.Remove(setHigh.Min); } } else if (num <= setLow.Max) { setLow.Add(num); // move the maximum number from setLow to setHigh setHigh.Add(setLow.Max); setLow.Remove(setLow.Max); } else { setHigh.Add(num); } } public double FindMedian() { if (setLow.Count == 0) { return 0; } if (setLow.Count == setHigh.Count) { return (setLow.Max + setHigh.Min) / 2d; } else { return setLow.Max; } } } } <file_sep>/CodePractice/CodePractice/GeekBang/knapsack.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { class Knapsack { // backtrack way, all input has been defined as class members private int maxW = int.MinValue; // the result for max weight private int maxValue = int.MinValue; // result for max value private readonly int[] weight = { 2, 4, 7, 9, 15 }; private readonly int[] value = { 3, 4, 8, 9, 6 }; // value for item private readonly int num = 5; // item numbers private readonly int capacity = 12; // capacity public void CalculateMax(int i, int cw) // starting point, call f(0,0) { //cw = current weight if (cw == capacity || i == num) { // cw == w means bag is full, i == n mean all items have been processed if (cw > maxW) maxW = cw; return; } CalculateMax(i + 1, cw); // not pick item i if (cw + weight[i] <= capacity) { CalculateMax(i + 1, cw + weight[i]); // select item i } } // max value version // backtracking, cannot use memo public void CalculateMaxValue(int i, int cw, int cv) { //cw = current weight //cv = current value if (cw == capacity || i == num) // constraint is capacity and num { // cw == w means bag is full, i == n mean all items have been processed if (cv > maxValue) maxValue = cv; return; } CalculateMaxValue(i + 1, cw, cv); // not pick item i if (cw + weight[i] <= capacity) { CalculateMaxValue(i + 1, cw + weight[i], cv + value[i]); // select item i } } //improve way of backtracking with memoization public void CalculateMaxUsingMemo(int i, int cw) { //array to store previous calculated results // using bool typed to store whether it has been reached or not bool[,] memo = new bool[num, capacity + 1]; // same logic applies if (cw == capacity || i == num) { if (cw > maxW) maxW = cw; return; } //current stack is f(i,cw), so if it is reached, we just return // this way the first time f(i,cw) is reached will be calculated all the way down if (memo[i, cw]) return; //to this step, means not reached, updated memo memo[i, cw] = true; // fist time for f(i, cw) stil need to continue calculation CalculateMaxUsingMemo(i + 1, cw); // not pick item i if (cw + weight[i] <= capacity) { CalculateMaxUsingMemo(i + 1, cw + weight[i]); // select item i } } public int GetMax() { return maxW; } //DP Approach using sentinel //using sentinel, row has more than one, // real index for weight array is i - 1 public int GetMaxDP() { //store states at each stage bool[][] states = new bool[num + 1][]; for(int i = 0; i < num + 1; i++) { states[i] = new bool[capacity + 1]; } //0,0 position is sentinel, assign to true states[0][0] = true; //state transition from one stage to next stage // real stage is 1 - n for n items for(int i = 1; i <=num; i++) { for(int j = 0; j <=capacity; j++) { //only if i-1, j has been reached // can i decide whether to put item i on top of j or not //i - 1 reached j, now what, two directions. //not put item i if (states[i - 1][j]) states[i][j] = states[i - 1][j]; // in one for loop //if (states[i - 1][j] && j <= w - weight[i - 1]) states[i][j + weight[i - 1]] = true; } //second loop to put item i // recond to minus 1 for the weight index for(int j = 0; j <= capacity - weight[i - 1]; j++) { if (states[i - 1][j]) states[i][j + weight[i - 1]] = true; } } //for (int j = capacity; j >= 0; j--) // // we need find largest index which is true (reached) in the last stage // if (states[num][j]) return j; // index i is weight // return 0; //to print in reverse order int k; for (k = capacity; k >= 0; k--) // we need find largest index which is true (reached) in the last stage if (states[num][k]) break; int max = k; for (int i = num; i > 0; i--) { //i,j comes from i-1, j-weight[i-1] if (k - weight[i - 1] >= 0 && states[i - 1][k - weight[i - 1]]) { Console.Write(weight[i-1]); Console.Write("->"); //update j k -= weight[i - 1]; } //else comes from i-1, j //j is same } Console.WriteLine(); return max; } //optimize to save some space, one d array public int GetMaxDP2() { bool[] states = new bool[capacity + 1]; //default value all false states[0] = true; // can be optimized using sentinel if (weight[0] <= capacity) { states[weight[0]] = true; // first item processed here } for (int i = 1; i < num; ++i) { // remember to process in reverse order,otherwise, wrong result, because if we process from small to big // we may change last current state at certain index, which may be used by later processing // if mean we need a value of last state at a index later, but we assign it to a different value before we actually use it // from big to small avoid this problem, we only assign values after biggest j, but the state we need is all state[j] before biggest j. // while small to big has issue, we need state[j] from 0 to j, when we process from 0 to j, we may change the state from 0 to j // they need to be kept untouched before this round of processing. for (int j = capacity - weight[i]; j >= 0; --j) {//pick item i if (states[j] == true) states[j + weight[i]] = true; } } for (int i = capacity; i >= 0; --i) { // output if (states[i] == true) return i; // index is weight } return 0; } //calcualte max value using DP //using sentinel, row has more than one, // real index for weight array and value array is i - 1 public int GetMaxValueDP() { //store states at each stage // change from bool to int, to not only store vistied or not (value > 0), but also store max value at certain weight //first row is sentinel row int [][] states = new int [num + 1][]; states[0] = Enumerable.Repeat(0, capacity + 1).ToArray(); //sentinel row has to been all visited, but value is 0, as no items in it for (int i = 1; i < num + 1; i++) { states[i] = Enumerable.Repeat(-1, capacity + 1).ToArray(); } //state transition from one stage to next stage // real stage is 1 - n for n items for (int i = 1; i <= num; i++) { for (int j = 0; j <= capacity; j++) { //not put item i if (states[i - 1][j] >= 0) states[i][j] = states[i - 1][j]; } //second loop to put item i // recond to minus 1 for the weight index // need store max value at spot of states for (int j = 0; j <= capacity - weight[i - 1]; j++) { if (states[i - 1][j] >= 0) { states[i][j + weight[i - 1]] = Math.Max(states[i][j + weight[i - 1]], states[i - 1][j] + value[i-1]); } } } int maxValue = -1; for (int i = capacity; i >= 0; i--) // noraml order or reverse order are both fine, we just need get max at last row if (states[num][i] > maxValue) maxValue = states[num][i]; return maxValue; } public int GetMaxValueDP2() { int[] states = Enumerable.Repeat(-1, capacity + 1).ToArray(); //default value all false states[0] = 0; if (weight[0] <= capacity) { states[weight[0]] = value[0]; // first item processed here } for (int i = 1; i < num; ++i) // 2 to num items, index 1 to num -1 { for (int j = capacity - weight[i]; j >= 0; --j) { //pick item i // previous max at this position if (states[j] >= 0) states[j + weight[i]] = Math.Max(states[j + weight[i]], states[j] + value[i - 1]); } } int maxValue = -1; for (int i = capacity; i >= 0; --i) // normal order or reverse order are both fine, we just need max index range (0, capacity) { // output if (states[i] > maxValue) maxValue = states[i]; } return maxValue; } } } <file_sep>/CodePractice/CodePractice/ObjectHeap.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { class ObjectHeap { private static readonly int DEFAULT_CAPACITY = 11; private int used; private Cell[] store; public ObjectHeap() : this(DEFAULT_CAPACITY) { } public ObjectHeap(int cap) { used = 0; store = new Cell[cap]; } public bool IsEmpty() { return used == 0; } public int GetSize() { return used; } public Cell Peek() { if (used == 0) throw new IndexOutOfRangeException(); return store[0]; } public Cell Pop() { if (used == 0) throw new IndexOutOfRangeException(); var result = store[0]; store[0] = store[used - 1]; used--; Sink(); return result; } public void Add(Cell val) { if (used == store.Length) Resize(); store[used] = val; used++; BubbleUp(); } private void BubbleUp() { int index = used - 1; while (index > 0 && Compare(store[index], store[(index - 1) / 2])) { Swap(store, index, (index - 1) / 2); index = (index - 1) / 2; } } private void Sink() { int index = 0; while (true) { int cur = index; int left = 2 * index + 1; int right = 2 * index + 2; if (left < used && Compare(store[left], store[cur])) cur = left; if (right < used && Compare(store[right], store[cur])) cur = right; if (cur == index) return; // NO swap Swap(store, cur, index); index = cur; } } public bool Compare(Cell a, Cell b) { // what ever compare we want, here we want a max hepa. return a.val > b.val; // if min heap, reversed // return a.val < b.val } public void Swap(Cell[] arr, int a, int b) { Cell temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } void Resize() { Cell[] temp = new Cell[2 * store.Length]; store.CopyTo(temp, 0); store = temp; } } public struct Cell { public int row; public int col; public int val; public Cell(int row, int col, int val) { this.row = row; this.col = col; this.val = val; } } public class Solution2 { public int MaximumMinimumPath(int[][] A) { int n = A.Length; int m = A[0].Length; bool[][] visited = new bool[n][]; for (int i = 0; i < n; i++) visited[i] = new bool[m]; // in the BFS approach, for each step, we are interested in getting the maximum min that we have seen so far, thus we reverse the ordering in the pq ObjectHeap heap = new ObjectHeap(1000); heap.Add(new Cell(0, 0, A[0][0])); visited[0][0] = true; int[] dirR = { 0, 0, 1, -1 }; int[] dirC = { 1, -1, 0, 0 }; // BFS while (!heap.IsEmpty()) { Cell cell = heap.Pop(); int row = cell.row; int col = cell.col; if (row == n - 1 && col == m - 1) { return cell.val; } for (int i = 0; i < 4; i++) { int nextRow = row + dirR[i]; int nextCol = col + dirC[i]; if (nextRow < 0 || nextRow >= n || nextCol < 0 || nextCol >= m || visited[nextRow][nextCol]) continue; // we are keeping track of the min element that we have seen until now heap.Add(new Cell(nextRow, nextCol, Math.Min(cell.val, A[nextRow][nextCol]))); visited[nextRow][nextCol] = true; } } return -1; } } } <file_sep>/Amazon QA 2022/Program.cs using System; using System.Collections.Generic; namespace AmazonOA { class Program { static void Main(string[] args) { int result = DistinctLetterString("ABC"); var tt = new Solution(); int[][] test = new int[][] { new int[] { 0, 1 }, new int[] { 1, 0 } }; int ss = tt.ShortestPathBinaryMatrix(test); Console.WriteLine("Hello World!"); } // Grouping Digits // similar as sort color problem public static int MinMoves(int[] input) { int n = input.Length; if (n <= 1) return 0; int[] oneOrZeroAtLeft = new int[2]; for (int k = 0; k < 2; k++) { int first = 0; for (int i = 0; i < n; i++) { if (input[i] == k) { oneOrZeroAtLeft[k] += Math.Abs(i - first); // because we can only swap adjacent, so instead of adding 1,its i-first first++; } } } return Math.Min(oneOrZeroAtLeft[0], oneOrZeroAtLeft[1]); } // max number of engineers int MaxTeams(int teamSize, int maxDiff, int[] skills) { if (teamSize == 1) return skills.Length; Array.Sort(skills); int teams = 0; int leastSkilled = 0; for (int i = 1; i < skills.Length; ++i) { while (skills[i] - skills[leastSkilled] > maxDiff) ++leastSkilled; if (i - leastSkilled + 1 == teamSize) { ++teams; leastSkilled = i + 1; } } return teams; } // flip string public int MinFlipsMonoIncr(string s) { int N = s.Length; int[] P = new int[N + 1]; for (int i = 0; i < N; ++i) P[i + 1] = P[i] + (s[i] == '1' ? 1 : 0); int ans = int.MaxValue; for (int j = 0; j <= N; ++j) { ans = Math.Min(ans, P[j] + N - j - (P[N] - P[j])); } return ans; } // sum of subarray range public long SubArrayRanges(int[] A) { long res = 0; for (int i = 0; i < A.Length; i++) { int max = A[i], min = A[i]; for (int j = i; j < A.Length; j++) { max = Math.Max(max, A[j]); min = Math.Min(min, A[j]); res += max - min; } } return res; } public long SubArrayRanges2(int[] A) { int n = A.Length, j, k; long res = 0; Stack<int> s = new Stack<int>(); for (int i = 0; i <= n; i++) { while (s.Count > 0 && A[s.Peek()] > (i == n ? int.MinValue : A[i])) { j = s.Pop(); k = s.Count == 0 ? -1 : s.Peek(); res -= (long)A[j] * (i - j) * (j - k); } s.Push(i); } s.Clear(); for (int i = 0; i <= n; i++) { while (s.Count > 0 && A[s.Peek()] < (i == n ? int.MaxValue : A[i])) { j = s.Pop(); k = s.Count ==0 ? -1 : s.Peek(); res += (long)A[j] * (i - j) * (j - k); } s.Push(i); } return res; } // LC828 password strength, if unique use this one public int UniqueLetterString(string S) { int res = 0; if (S == null || S.Length == 0) return res; int[] showLastPosition = new int[128]; int[] contribution = new int[128]; int cur = 0; for (int i = 0; i < S.Length; i++) { char x = S[i]; cur -= contribution[x]; // remove previous contribution contribution[x] = (i + 1 - showLastPosition[x]); cur += contribution[x]; // add current contribution showLastPosition[x] = i + 1; res += cur; } return res; } // pass word strength, if distinct, this way public static int DistinctLetterString(string s) { int res = 0; if (s == null || s.Length == 0) return res; int[] lastIndexArray = new int[26]; for (int i = 0; i < 26; i++) lastIndexArray[i] = -1; //int[] contribution = new int[128]; int cur = 0; for (int i = 0; i < s.Length; i++) { char x = s[i]; int lastIndex = lastIndexArray[x - 'A']; cur = cur + i + 1 - (lastIndex + 1); res += cur; //update last index lastIndexArray[x - 'A'] = i; } return res; } // idea is to process letter by letter public int UniqueLetterStringII(String s) { int[] lastPosition = new int[26]; int[] contribution = new int[26]; int res = 0; // Basically, at each it, we count the contribution of all the characters to all the substrings ending till that point. for (int i = 0; i < s.Length; i++) { int curChar = s[i] - 'A'; // Now, we need to update the contribution of curChar. // The total number of substrings ending at i are i+1. So if it was a unique character, it'd contribute to all of those // and it's contribution would have been i+1. // But if it's repeating, it means it has already contributed previously. So remove it's previous contribution. // We can do that as we have it's last position. // So these are the contributions for strings which start after this character's last occurrence and end at i. // A simple example will demonstrate that the number of these strings are i+1 - lastPosition[curChar] // For characters not appeared till now, lastPosition[curChar] would be 0. int totalNumOfSubstringsEndingHere = i + 1; contribution[curChar] = totalNumOfSubstringsEndingHere - lastPosition[curChar]; // Note that, the contribution of all the other characters will remain same. // count the cur answer by summing all the contributions. This loop can be avoided by the idea in original post, but I find // it easy to understand with this and it only iterates over 26 values. int cur = 0; for (int j = 0; j < 26; j++) { cur += contribution[j]; } // add the current value to final answer. res += cur; // update the last position of this char. This helps in future to count it's contribution if it appears again. lastPosition[curChar] = i + 1; } return res; } // ways to split, balanced string, not fully working, but at least something. private static int SplitWays(string s) { int count = 0; Dictionary<char, int> leftBrackets = new Dictionary<char, int>(); Dictionary<char, int> rightBrackets = CountBrackets(s); leftBrackets[s[0]] = 1; rightBrackets[s[0]]--; for (int i = 1; i < s.Length - 1; i++) { leftBrackets[s[i]] = leftBrackets.GetValueOrDefault(s[i], 0) + 1; rightBrackets[s[i]]--; if (IsBalanced(leftBrackets) && IsBalanced(rightBrackets)) { count++; } } return count; } private static bool IsBalanced(Dictionary<char, int> brackets) { int rdOpen = brackets.GetValueOrDefault('(', 0); int rdClose = brackets.GetValueOrDefault(')', 0); int sqOpen = brackets.GetValueOrDefault('[', 0); int sqClose = brackets.GetValueOrDefault(']', 0); int questionMark = brackets.GetValueOrDefault('?', 0); int rdDiff = Math.Abs(rdOpen - rdClose); int sqDiff = Math.Abs(sqOpen - sqClose); int diff = rdDiff + sqDiff; if (diff == 0 && questionMark % 2 == 0) { return true; } questionMark -= diff; if (questionMark < 0) { return false; } return questionMark % 2 == 0; } private static Dictionary<char, int> CountBrackets(string s) { Dictionary<char, int> charFreq = new Dictionary<char, int>(); foreach (char c in s) { charFreq[c] = charFreq.GetValueOrDefault(c, 0) + 1; } return charFreq; } } } <file_sep>/CodePractice/CodePractice/Amazon OA/MinStepsTreasureIslands.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { public class MinStepsTreasureIslands { public int TreasureIsland(char[][] island) { if (island == null || island.Length == 0) return 0; int steps = 0; Queue<int[]> queue = new Queue<int[]>(); queue.Enqueue(new int[] { 0, 0 }); //bool[][] visited = new bool[island.Length][]; //for (int i = 0; i < island.Length; i++) // visited[0] = new bool[island[0].Length]; //visited[0][0] = true; //mark starting point as visited island[0][0] = 'D'; int[][] dirs = new int[][] { new int[] { 1, 0 }, new int[] { -1, 0 }, new int[] { 0, 1 }, new int[] { 0, -1 } }; // bfs while (queue.Count > 0) { int size = queue.Count; for (int i = 0; i < size; i++) { int[] point = queue.Dequeue(); int r = point[0]; int c = point[1]; if (island[r][c] == 'X') return steps; foreach (int[] dir in dirs) { int newR = point[0] + dir[0]; int newC = point[1] + dir[1]; if (newR >= 0 && newR < island.Length && newC >= 0 && newC < island[0].Length && island[newR][newC] != 'D' ) { queue.Enqueue(new int[] { newR, newC }); //mark visited by changing to 'D' island[newR][newC] = 'D'; } } } steps++; } return -1; } } } <file_sep>/CodePractice/CodePractice/LeetCode/TreeTraversalStack.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { class TreeTraversalStack { //public List<Integer> preorderTraversal(TreeNode root) //{ // LinkedList<TreeNode> stack = new LinkedList<>(); // LinkedList<Integer> output = new LinkedList<>(); // if (root == null) // { // return output; // } // stack.add(root); // while (!stack.isEmpty()) // { // //out put before process, inside the stack // // before process any left or right // TreeNode node = stack.pollLast(); // output.add(node.val); // if (node.right != null) // { // stack.add(node.right); // } // if (node.left != null) // { // stack.add(node.left); // } // } // return output; //} //Adopt this one for stack imp for in order, // first go all the way left, output, then one step to the left //public List<Integer> inorderTraversal(TreeNode root) //{ // List<Integer> res = new ArrayList<>(); // Stack<TreeNode> stack = new Stack<>(); // TreeNode curr = root; // while (curr != null || !stack.isEmpty()) // { // while (curr != null) // { // stack.push(curr); // curr = curr.left; // } // // left has been processed then we out put // curr = stack.pop(); // res.add(curr.val); // curr = curr.right; // } // return res; //} //use linked list //this is actually a right PREORDER (parent node -> right child ->left child ) and then reverse it. public List<int> PostorderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); LinkedList<int> output = new LinkedList<int>(); if (root == null) { return output.ToList(); } stack.Push(root); while (stack.Count > 0) { TreeNode node = stack.Pop(); output.AddFirst(node.val); if (node.left != null) { stack.Push(node.left); } if (node.right != null) { stack.Push(node.right); } } return output.ToList(); } //use list public List<int> PostorderTraversal2(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); List<int> output = new List<int>(); if (root == null) { return output; } stack.Push(root); while (stack.Count > 0) { TreeNode node = stack.Pop(); output.Add(node.val); if (node.left != null) { stack.Push(node.left); } if (node.right != null) { stack.Push(node.right); } } output.Reverse(); return output; } // https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/45582/A-real-Postorder-Traversal-.without-reverse-or-insert-4ms //real post order using double pushing public List<int> PostorderTraversal3(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); List<int> output = new List<int>(); if (root == null) { return output; } stack.Push(root); stack.Push(root); TreeNode cur; while (stack.Count > 0) { cur = stack.Peek(); stack.Pop(); if (stack.Count > 0 && stack.Peek() == cur) { if (cur.right != null) { stack.Push(cur.right); stack.Push(cur.right); } if (cur.left != null) { stack.Push(cur.left); stack.Push(cur.left); } } else output.Add(cur.val); } return output; } public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int x) { val = x; } } } } <file_sep>/CodePractice/CodePractice/SimpleHeap.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { public class SimpleHeap { private static readonly int DEFAULT_CAPACITY = 11; private int used; private int[] store; public SimpleHeap() : this(DEFAULT_CAPACITY) { } public SimpleHeap(int cap) { used = 0; store = new int[cap]; } public bool IsEmpty() { return used == 0; } public int GetSize() { return used; } public int Peek() { if (used == 0) throw new IndexOutOfRangeException(); return store[0]; } public int Pop() { if (used == 0) throw new IndexOutOfRangeException(); var result = store[0]; store[0] = store[used - 1]; used--; Sink(); return result; } public void Add(int val) { if (used == store.Length) Resize(); store[used] = val; used++; BubbleUp(); } private void BubbleUp() { int index = used - 1; while (index > 0 && store[index] < store[(index - 1) / 2]) { Swap(store, index, (index - 1) / 2); index = (index - 1) / 2; } } private void Sink() { int index = 0; while (true) { int min = index; int left = 2 * index + 1; int right = 2 * index + 2; if (left < used && store[min] > store[left]) min = left; if (right < used && store[min] > store[right]) min = right; if (min == index) return; // NO swap Swap(store, min, index); index = min; } } public void Swap(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } void Resize() { int[] temp = new int[2 * store.Length]; store.CopyTo(temp, 0); store = temp; } } public class MedianFinder { private Heap left; private Heap right; /** initialize your data structure here. */ public MedianFinder() { left = new Heap(1000, false); //max for left right = new Heap(1000, true); //true for right } public void AddNum(int num) { if (left.IsEmpty() || num <= left.Peek()) left.Add(num); else right.Add(num); //keep balance if (left.Count() - right.Count() > 1) right.Add(left.Pop()); if (right.Count() - left.Count() > 1) left.Add(right.Pop()); } public double FindMedian() { if (left.Count() == right.Count()) { return (double)(left.Peek() + right.Peek()) / 2; } else if (left.Count() > right.Count()) { return left.Peek(); } else { return right.Peek(); } } } public class Heap { private int used; private int[] store; private bool isMin; public Heap(int cap, bool min) { used = 0; store = new int[cap]; isMin = min; } public bool IsEmpty() { return used == 0; } public int Count() { return used; } public int Peek() { if (used == 0) throw new IndexOutOfRangeException(); return store[0]; } public int Pop() { if (used == 0) throw new IndexOutOfRangeException(); var result = store[0]; store[0] = store[used - 1]; used--; Sink(); return result; } public void Add(int val) { if (used == store.Length) Resize(); store[used] = val; used++; BubbleUp(); } private void BubbleUp() { int index = used - 1; while (index > 0 && Compare(store[index], store[(index - 1) / 2])) { Swap(store, index, (index - 1) / 2); index = (index - 1) / 2; } } private void Sink() { int index = 0; while (true) { int cur = index; int left = 2 * index + 1; int right = 2 * index + 2; if (left < used && Compare(store[left], store[cur])) cur = left; if (right < used && Compare(store[right], store[cur])) cur = right; if (cur == index) return; // NO swap Swap(store, cur, index); index = cur; } } void Swap(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } void Resize() { int[] temp = new int[2 * store.Length]; store.CopyTo(temp, 0); store = temp; } bool Compare(int a, int b) { return isMin ? a < b : a > b; } } } <file_sep>/Amazon QA 2022/ValidString.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class ValidString { // valid string, similar as valid parenthesis public bool IsValid(String s) { Stack<char> stack = new Stack<char>(); foreach (char c in s) { if (stack.Count == 0 || c != stack.Peek()) { stack.Push(c); } else if (c == stack.Peek()) { stack.Pop(); } } return stack.Count == 0; } } } <file_sep>/CodePractice/CodePractice/Amazon OA/CriticalConnectionsAllCasePassed.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { class Solution { List<List<int>> list; Dictionary<int, bool> visited; public List<List<int>> GetCriticalConnections(int numOfServers, int numOfConnections, List<List<int>> connections) { Dictionary<int, HashSet<int>> adj = new Dictionary<int, HashSet<int>>(); foreach (List<int> connection in connections) { int u = connection[0]; int v = connection[1]; if (!adj.ContainsKey(u)) adj.Add(u, new HashSet<int>()); adj[u].Add(v); if (!adj.ContainsKey(v)) adj.Add(v, new HashSet<int>()); adj[v].Add(u); } list = new List<List<int>>(); for (int i = 0; i < numOfConnections; i++) { visited = new Dictionary<int, bool>(); List<int> p = connections[i]; int x = p[0]; int y = p[1]; adj[x].Remove(y); adj[y].Remove(x); DFS(adj, 1); if (visited.Count != numOfServers) { if (p[0] > p[1]) list.Add(new List<int> { p[1], p[0] }); else list.Add(p); } adj[x].Add(y); adj[y].Add(x); } return list; } public void DFS(Dictionary<int, HashSet<int>> adj, int u) { visited.Add(u, true); if (adj[u].Count != 0) { foreach (int v in adj[u]) { if (!visited.ContainsKey(v) || !visited[v]) { DFS(adj, v); } } } } } } <file_sep>/Microsoft OA 2022/CountGoodNodes.cs using System; using System.Collections.Generic; using System.Text; namespace MicrosoftOA { class CountGoodNodes { public int GoodNodes(TreeNode root) { traverse(root, root.val); return count; } int count = 0; // 二叉树遍历函数,pathMax 参数记录从根节点到当前节点路径中的最大值 void traverse(TreeNode root, int pathMax) { if (root == null) { return; } if (pathMax <= root.val) { // 找到一个「好节点」 count++; } // 更新路径上的最大值 pathMax = Math.Max(pathMax, root.val); traverse(root.left, pathMax); traverse(root.right, pathMax); } } public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null) { this.val = val; this.left = left; this.right = right; } } } <file_sep>/CodePractice/CodePractice/Flexera/RockPaperScissor.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { public class RockPaperScissor { //beat rules, value beats key //rock beats scissors //scissors beats paper //paper beats rock static readonly Dictionary<char, char> beatRules = new Dictionary<char, char> { {'S', 'R' }, {'P', 'S' }, {'R', 'P' } }; static void Print() { string input = Console.ReadLine(); int result = GetWinRounds(input); Console.WriteLine(result.ToString()); } public static int GetWinRounds(string input) { int result = 0; //process first two rounds, for (int i = 0; i < 2 && i < input.Length; i++) { if (Win('R', input[i]) > 0) result++; } //process rest of characters for (int i = 2; i < input.Length; i++) { char myNext = MyNextMove(input[i - 2], input[i - 1]); if (Win(myNext, input[i]) > 0) result++; } return result; } //apply psychology, based on opponent two previous move //decide my next move private static char MyNextMove(char prepre, char pre) { List<char> threeMoves = new List<char> { 'R', 'S', 'P' }; if (prepre == pre) return beatRules[pre]; threeMoves.Remove(prepre); threeMoves.Remove(pre); char next = threeMoves.First(); return beatRules[next]; } private static int Win(char c1, char c2) { //c1 beats c2 if (c1 == beatRules[c2]) return 1; //c2 beats c1 if (c2 == beatRules[c1]) return -1; //tie return 0; } } } <file_sep>/CodePractice/CodePractice/LongestCommonSequence.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { public class LongestCommonSequence { /* CLRS book present and prove the theorem * C[i,j] = C[i-1, j -1] + 1; if Xi = Yj * C[i,j] = Max(C[i-1, j], C[i, j -1]); if Xi <> Yj * C[i,j] = 0; if i ==0 or j == 0 */ //create the decision array to reconstuct the sequence private char[,] decision; //reproduce the algorithm on the book // here just return length // the book needs to return the table len and decision //time: O(M*N) //space: O(M*N) public int GetLCSLength(string s1, string s2) { int m = s1.Length, n = s2.Length; //construct the two tables //Len array to store the solution at i,j //Decision array to store which spot it was picked in the previous subproblem, this way, we can reconstruct the sequence. //use two-d array for simplicity, jagged array is faster, but has to do for loop (array of array) // len size is (m+1) * (n+1), sentinel approach to simplify code int[,] len = new int[m + 1, n + 1]; decision = new char[m, n]; //we do row-major order, fill in first row, then second row //fill first column for len array, starting at 1, because below one take care of 0,0 for (int i = 1; i <= m; i++) len[i, 0] = 0; //fill first row for (int i = 0; i <= n; i++) len[0, i] = 0; //start from 1,1 which is first character for each string for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (s1[i - 1] == s2[j - 1]) { // two things //calculate vale for len[i,j] len[i, j] = len[i - 1, j - 1] + 1; //record the decision at i,j decision[i - 1, j - 1] = 'D'; // D for diagnol } else { //from up // note, > or >= are both okay, the longest length is unique, just one number, // but the path to reach longest are not necesarily only one, could be multiple if (len[i - 1, j] >= len[i, j - 1]) { //take up len[i, j] = len[i - 1, j]; //record decision[i - 1, j - 1] = 'U'; // U for up } else { //take up, if same, we take Left len[i, j] = len[i, j - 1]; //record decision[i - 1, j - 1] = 'L'; // U for up } } } } return len[m, n]; } // optimize 1 // use two rows and temp variable // can not reconstruct the sequence, can only get the number now public int GetLCSLengthUsingTwoRows(string s1, string s2) { // we want do row-major order, process row by row in the 2-d Grid //so need keep cloumns smaller than rows int rows = s1.Length, columns = s2.Length; if (rows < columns) return GetLCSLengthUsingTwoRows(s2, s1); // if columns is greater, swap //two array to store previous and current state int[] previous = Enumerable.Repeat(0, columns + 1).ToArray(); int[] current = new int[columns + 1]; // +1 is for sentinel current[0] = 0; //process the strings, two loops // first loop all rows (all character in s1) // second loop all columns, index 0 is sentinel, so starting at index 1, (all characters in s2) for (int i = 1; i <= rows; i++) { int temp = previous[0]; // it will always be 0 for (int j = 1; j <= columns; j++) { //because we go from 1 to cloumns, go forward, not backward, // only need to store the value of previous[j] before we update it to current[j] //after current j if (s1[i - 1] == s2[j - 1]) { // from up and left current[j] = temp + 1; } else { //from up if (previous[j] >= current[j - 1]) // compare up with left { //take up record current[j] = previous[j]; } else { //take left current[j] = current[j - 1]; } } temp = previous[j]; previous[j] = current[j]; } } return current[columns]; } public int GetLCSLengthUsingOneRow(string s1, string s2) { // we want do row-major order, process row by row in the 2-d Grid //so need keep cloumns smaller than rows int rows = s1.Length, columns = s2.Length; if (rows < columns) return GetLCSLengthUsingOneRow(s2, s1); // if columns is greater, swap //onley one array to store previous and current state int[] current = Enumerable.Repeat(0, columns + 1).ToArray(); //process the strings, two loops // first loop all rows (all character in s1) // second loop all columns, index 0 is sentinel, so starting at index 1, (all characters in s2) int lastLeft, lastCurrent; for (int i = 1; i <= rows; i++) { lastLeft = current[0]; // it will always be 0 //int lastCurrent; for (int j = 1; j <= columns; j++) { //because we go from 1 to cloumns, go forward, not backward, //record current[j] into temp before update current[j] lastCurrent = current[j]; if (s1[i - 1] == s2[j - 1]) { // from up and left, use last left current[j] = lastLeft + 1; } else { ////from up //if (lastCurrent >= current[j - 1]) // compare up with left, last current //{ // //take up record, use last current, nothing to do // //current[j] = lastCurrent; // this line no meaning, since current[j] did not change after line 164, remove it //} //else //{ // //take left // current[j] = current[j - 1]; //} //simply the above to if (lastCurrent < current[j - 1]) //compare up with left, take left current[j] = current[j - 1]; } //after process, we actually move to j + 1, lastCurrent becomes lastLeft lastLeft = lastCurrent; } } return current[columns]; } //Print LCS reverse order //loop through decision, public int PrintLCSReverse(string s1) { int m = decision.GetLength(0), n = decision.GetLength(1); int count = 0; //this loop is wrong //for(int i = m - 1; i >= 0 && j>=0;) //{ // for(int j = n -1; i >= 0 && j >=0; ) // { // count++; // Console.Write(decision[i, j]); // if(decision[i,j] == 'D') // { // //if means s1[i] == s2[j] // // print the current one // //Console.Write(s1[i]); // //both i and j needs to be updated // i = i - 1; j = j - 1; // } // else if(decision[i, j] == 'U') // { // //updte row // i = i - 1; // } // else // { // // no if needed, as it must be 'L' // j = j - 1; // } // } //} int i = m - 1, j = n - 1; while (i >= 0 && j >= 0) { count++; //Console.Write(decision[i, j]); if (decision[i, j] == 'D') { //if means s1[i] == s2[j] // print the current one Console.Write(s1[i]); //both i and j needs to be updated i--; j--; } else if (decision[i, j] == 'U') { //updte row i--; } else { // no if needed, as it must be 'L' j--; } } Console.WriteLine(); return count; } //print in normal order, //need to user recursion public void PrintLCS(string s1, int i, int j) { if (i < 0 || j < 0) // terminating condition for the recursion, stack return; if (decision[i, j] == 'D') { //go to up left PrintLCS(s1, i - 1, j - 1); // be cautious, --i or i++ in the parameter, it not only pass the new value and change the value for variable i. Console.Write(s1[i]); } else if (decision[i, j] == 'U') { //go up PrintLCS(s1, i - 1, j); } else { //go left PrintLCS(s1, i, j - 1); } } //print decision matrix for debugging public void PrintDecisionMatrix() { int m = decision.GetLength(0), n = decision.GetLength(1); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { Console.Write(decision[i, j]); Console.Write(" "); } Console.WriteLine(); } } } } <file_sep>/Microsoft OA 2022/UniqueIntSumToZero.cs using System; using System.Collections.Generic; using System.Text; namespace MicrosoftOA { class UniqueIntSumToZero { public int[] SumZero(int n) { List<int> res = new List<int>(); for (int i = 1; i <= n / 2; i++) { res.Add(i); res.Add(-i); } if (n % 2 != 0) res.Add(0); return res.ToArray(); } } } <file_sep>/CodePractice/CodePractice/Amazon OA/TopNToys.cs using System.Collections.Generic; using System.Linq; namespace CodePractice { public class TopNToys { public List<string> TopToys(int numToys, int topToys, string[] toys, int numQuotes, string[] quotes) { char[] delimiterChars = { ' ', ',', '.', ':', '!', '?', '\t' }; Dictionary<string, int[]> freq = new Dictionary<string, int[]>(); // we can also use two dictionary to solve this foreach (string toy in toys) { freq.Add(toy.ToLower(), new int[] { 0, 0 }); // to lower may not needed, we can toggle } foreach (string quote in quotes) { HashSet<string> used = new HashSet<string>(); string[] words = quote.ToLower().Split(delimiterChars, System.StringSplitOptions.RemoveEmptyEntries); foreach (string word in words) { if (!freq.ContainsKey(word)) { continue; } int[] nums = freq[word]; nums[0]++; if (!used.Contains(word)) { nums[1]++; used.Add(word); } } } //rest is to find top k in N //C# doesnt have built in priority queue, has to implement a min-heap here //linq string[] toysInQ = freq.Where(kv => kv.Value[0] > 0).Select(kv => kv.Key).ToArray(); if (topToys > numToys) topToys = toysInQ.Length; // build a heap string[] heap = new string[topToys]; //build min heap of size K, insert one by one, then recalculate up for (int i = 0; i < topToys; i++) { heap[i] = toysInQ[i]; ReCalculateUp(heap, i, freq); } //loop through rest of points for (int j = topToys; j < toysInQ.Length; j++) { if (Compare(toysInQ[j], heap[0], freq) > 0) { // we only care about the heap of K, rest elements we dont care heap[0] = toysInQ[j]; ReCalculateDown(heap, 0, topToys, freq); } } // now heap is array contain top N toys // need to pop one by one List<string> output = new List<string>(); for (int i = topToys - 1; i >= 0; i--) { output.Add(heap[0]); heap[0] = heap[i]; ReCalculateDown(heap, 0, i + 1, freq); } //if return is array string[] res = new string[topToys]; for (int i = topToys - 1; i >= 0; i--) { res[i] = heap[0]; heap[0] = heap[i]; ReCalculateDown(heap, 0, i + 1, freq); } //none linq way, has to use list //List<string> tq = new List<string>(); //foreach (KeyValuePair<string, int[]> item in freq) //{ // if (item.Value[0] > 0) // tq.Add(item.Key); //} // if topToys > total number of toys, update to the size of dictionary which has freq > 0 //if (topToys > numToys) //{ // topToys = freq.Count(kv => kv.Value[0] > 0); // // a for loop // int count = 0; // foreach(KeyValuePair<string, int[]> item in freq) // { // if (item.Value[0] > 0) // ++count; // } //} // build min-heap to get top frequent N toys // PriorityQueue<string> pq = new PriorityQueue<>((t1, t2)-> { // if (freq.get(t1)[0] != freq.get(t2)[0]) // { // return freq.get(t1)[0] - freq.get(t2)[0]; // } // if (freq.get(t1)[1] != freq.get(t2)[1]) // { // return freq.get(t1)[1] - freq.get(t2)[1]; // } // return t2.compareTo(t1); // }); // if (topToys > numToys) { // for (string toy : freq.keySet()) { // if (freq.get(toy)[0] > 0) { // pq.add(toy); // } //} // } else { // for (string toy : toys) { // pq.add(toy); // if (pq.size() > topToys) { // pq.poll(); // } // } // } //while (!pq.isEmpty()) { // output.add(pq.poll()); //} //Collections.reverse(output); return output; } public void ReCalculateDown(string[] arr, int index, int size, Dictionary<string, int[]> fre) { while (true) { int min = index; int left = 2 * index + 1; int right = 2 * index + 2; if (left < size && Compare(arr[min], arr[left], fre) > 0) min = left; if (right < size && Compare(arr[min], arr[right], fre) > 0) min = right; if (min == index) return; // NO swap Swap(arr, min, index); index = min; } } public void ReCalculateUp(string[] arr, int index, Dictionary<string, int[]> fre) { // has parent node and parent value > child value while ((index - 1) / 2 >= 0 && Compare(arr[(index - 1)/2], arr[index], fre) > 0) { Swap(arr, index, (index - 1) / 2); index = (index - 1) / 2; } } public int Compare(string k1, string k2, Dictionary<string, int[]> fre) { if (fre[k1][0] != fre[k1][0]) return fre[k1][0] - fre[k2][0]; if (fre[k1][1] != fre[k2][1]) return fre[k1][1] - fre[k2][1]; return k2.CompareTo(k1); } public void Swap(string[] arr, int a, int b) { string temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } } } <file_sep>/Microsoft OA 2022/MaxLengthConcateString.cs using System; using System.Collections.Generic; using System.Text; namespace MicrosoftOA { class MaxLengthConcateString { private int result = 0; public int MaxLength(IList<string> arr) { if (arr == null || arr.Count == 0) { return 0; } dfs(arr, "", 0); return result; } private void dfs(IList<string> arr, string path, int idx) { bool isUniqueChar = IsUniqueChars(path); if (isUniqueChar) { result = Math.Max(path.Length, result); } if (idx == arr.Count || !isUniqueChar) { return; } for (int i = idx; i < arr.Count; i++) { if (!IsUniqueChars(arr[i])) continue; dfs(arr, path + arr[i], i + 1); } } private bool IsUniqueChars(string s) { HashSet<char> set = new HashSet<char>(); foreach (char c in s) { if (set.Contains(c)) { return false; } set.Add(c); } return true; } bool isUniqueChars(string s) { bool[] set = new bool[26]; foreach (char c in s) { if (set[c - 'a']) return false; set[c - 'a'] = true; } return true; } } } <file_sep>/Microsoft OA 2022/MinMeetingRooms.cs using System; using System.Collections.Generic; using System.Text; namespace MicrosoftOA { class MinMeetingRooms { public int MinMeetingRoomCount(int[][] intervals) { int used = 0; int len = intervals.Length; //two arrays int[] start = new int[len]; int[] end = new int[len]; for (int i = 0; i < len; i++) { start[i] = intervals[i][0]; end[i] = intervals[i][1]; } //sort two array, in time order] Array.Sort(start); Array.Sort(end); int str = 0, etr = 0; //process two pointers while (str < len) { //has vacant room if (start[str] >= end[etr]) { used--; //decrement anyway, because I am going to increment // move etr to new room etr++; } used++; str++; } return used; } int minMeetingRooms(int[][] meetings) { int n = meetings.Length; int[] begin = new int[n]; int[] end = new int[n]; for (int k = 0; k < n; k++) { begin[k] = meetings[k][0]; end[k] = meetings[k][1]; } Array.Sort(begin); Array.Sort(end); // 扫描过程中的计数器 int count = 0; // 双指针技巧 int res = 0, i = 0, j = 0; while (i < n && j < n) { if (begin[i] < end[j]) { // 扫描到一个红点 count++; i++; } else { // 扫描到一个绿点 count--; j++; } // 记录扫描过程中的最大值 res = Math.Max(res, count); } return res; } } } <file_sep>/Amazon QA 2022/PasswordStrength.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { class PasswordStrength { // LC828 password strength, if unique use this one public int UniqueLetterString(string S) { int res = 0; if (S == null || S.Length == 0) return res; int[] showLastPosition = new int[128]; int[] contribution = new int[128]; int cur = 0; for (int i = 0; i < S.Length; i++) { char x = S[i]; cur -= contribution[x]; // remove previous contribution contribution[x] = (i + 1 - showLastPosition[x]); cur += contribution[x]; // add current contribution showLastPosition[x] = i + 1; res += cur; } return res; } // pass word strength, if distinct, this way public static int DistinctLetterString(string s) { int res = 0; if (s == null || s.Length == 0) return res; int[] lastIndexArray = new int[26]; for (int i = 0; i < 26; i++) lastIndexArray[i] = -1; //int[] contribution = new int[128]; int cur = 0; for (int i = 0; i < s.Length; i++) { char x = s[i]; int lastIndex = lastIndexArray[x - 'A']; cur = cur + i + 1 - (lastIndex + 1); res += cur; //update last index lastIndexArray[x - 'A'] = i; } return res; } // idea is to process letter by letter public int UniqueLetterStringII(string s) { int[] lastPosition = new int[26]; int[] contribution = new int[26]; int res = 0; // Basically, at each it, we count the contribution of all the characters to all the substrings ending till that point. for (int i = 0; i < s.Length; i++) { int curChar = s[i] - 'A'; // Now, we need to update the contribution of curChar. // The total number of substrings ending at i are i+1. So if it was a unique character, it'd contribute to all of those // and it's contribution would have been i+1. // But if it's repeating, it means it has already contributed previously. So remove it's previous contribution. // We can do that as we have it's last position. // So these are the contributions for strings which start after this character's last occurrence and end at i. // A simple example will demonstrate that the number of these strings are i+1 - lastPosition[curChar] // For characters not appeared till now, lastPosition[curChar] would be 0. int totalNumOfSubstringsEndingHere = i + 1; contribution[curChar] = totalNumOfSubstringsEndingHere - lastPosition[curChar]; // Note that, the contribution of all the other characters will remain same. // count the cur answer by summing all the contributions. This loop can be avoided by the idea in original post, but I find // it easy to understand with this and it only iterates over 26 values. int cur = 0; for (int j = 0; j < 26; j++) { cur += contribution[j]; } // add the current value to final answer. res += cur; // update the last position of this char. This helps in future to count it's contribution if it appears again. lastPosition[curChar] = i + 1; } return res; } } } <file_sep>/CodePractice/CodePractice/LeetCode/SlidingWindowSubstrings.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { public class SlidingWindowSubstrings { /* Can solove * 76. Minimum Window Substring * 3. Longest Substring Without Repeating Characters * 159. longest-substring-with-at-most-two-distinct-characters * 340. Longest Substring with At Most K Distinct Characters * 30. Substring with Concatenation of All Words * 438. Find All Anagrams in a String * 567. Permutation in String * 424. Longest Repeating Character Replacement */ //Template for sliding window public List<int> SlidingTemplate(string s, string t) { //init a collection or int value to save the result according the question. List<int> result = new List<int>(); if (t.Length > s.Length) return result; //create a hashmap to save the Characters of the target substring. //(K, V) = (Character, Frequence of the Characters) Dictionary<char, int> map = new Dictionary<char, int>(); foreach (char c in t.ToCharArray()) { if (map.ContainsKey(c)) map[c] = map[c] + 1; else map.Add(c, 1); } //maintain a counter to check whether match the target string. int counter = map.Count;//must be the map size, NOT the string size because the char may be duplicate. //Two Pointers: begin - left pointer of the window; end - right pointer of the window int begin = 0, end = 0; //the length of the substring which match the target string. //int len = int.MaxValue; //loop at the begining of the source string while (end < s.Length) { char c = s[end];//get a character if (map.ContainsKey(c)) { map[c] = map[c] - 1;// plus or minus one if (map[c] == 0) counter--;//modify the counter according the requirement(different condition). } end++; //increase begin pointer to make it invalid/valid again while (counter == 0 /* counter condition. different question may have different condition */) { char tempc = s[begin];//***be careful here: choose the char at begin pointer, NOT the end pointer if (map.ContainsKey(tempc)) { map[tempc] = map[tempc] + 1;//plus or minus one if (map[tempc] > 0) counter++;//modify the counter according the requirement(different condition). } /* save / update(min/max) the result if find a target*/ // result collections or result int value begin++; } //Max len type of problem sometimes get updated here } return result; } //Template two //int findSubstring(string s) //{ // int[] map = new int[128]; // int counter; // check whether the substring is valid // int begin = 0, end = 0; //two pointers, one point to tail and one head // int d; //the length of substring // for () { /* initialize the hash map here */ } // while (end < s.size()) // { // if (map[s[end++]]-- ?) { /* modify counter here */ } // if (map[s[end] > 0]) // map[end] = map[end] - 1; // end++; // while (/* counter condition */) // { // /* update d here if finding minimum*/ // //increase begin to make it invalid/valid again // if (map[s[begin++]]++ ?) { /*modify counter here*/ } // if (map[s[begin] > 0]) // map[begin] = map[begin] + 1; // begin++; // } // /* update d here if finding maximum*/ // } // return d; //} public IList<int> FindAnagrams(string s, string p) { //sliding window approach, two pointers, one counter List<int> result = new List<int>(); //Dictionary to store the frequency of each characters //more generic way Dictionary<char, int> freq = new Dictionary<char, int>(); for (int i = 0; i < p.Length; i++) { if (freq.ContainsKey(p[i])) freq[p[i]] = freq[p[i]] + 1; else freq.Add(p[i], 1); } //two pointers, one counter int left = 0, right = 0, counter = freq.Count; while (right < s.Length) { if (freq.ContainsKey(s[right])) { freq[s[right]] = freq[s[right]] - 1; //minus one //check if one character in the dictionary is all covered if (freq[s[right]] == 0) counter--; } right++; //next need to move left pointer while (counter == 0) { if (freq.ContainsKey(s[left])) { // move pass one character, right side needs to cover this character // so plus one //reset to characters in p freq[s[left]] = freq[s[left]] + 1; //this check is necessary as the value could be still zero // > 0 means reset to zero, if (freq[s[left]] > 0) counter++; } // all chacters covered plus same length thats a hit if (right - left == p.Length) result.Add(left); //always move left left++; } } return result; } public IList<int> FindAnagramsTwo(string s, string p) { List<int> result = new List<int>(); //we assume the string only contains lower case letters int[] freq = new int[26]; //populate the array for (int i = 0; i < p.Length; i++) freq[p[i] - 'a']++; //two pointers, one counter int left = 0, right = 0, counter = p.Length; while (right < s.Length) { //if freq array has it before //means we need to cover it if (freq[s[right] - 'a'] > 0) counter--; freq[s[right] - 'a']--; //always minus 1 right++; if (counter == 0) result.Add(left); //move left pointer if right -left == p.len if (right - left == p.Length) { if (freq[s[left] - 'a'] >= 0) // going to skip a, count plus one counter++; freq[s[left] - 'a']++; //always plus one left++; } } return result; } // 3. Longest Substring Without Repeating Characters //sliding approach public int LengthOfLongestSubstring(string s) { int left = 0, right = 0, count = 0; int[] map = new int[256]; // assume all ascii charaters int len = 0; while(right < s.Length) { char c = s[right]; if (map[c] == 1) count++; //repeating char map[c] = map[c] + 1; right++; //since the moment count = 1, it will be catch, so map[c] always equal 2 then, so check == 1 is fine. // a more readable way maybe //first increment // then check if > 1, make it symmetric as left processing. //map[c] = map[c] + 1; //if (map[c] > 1) count++; //right++; while (count > 0) //when condition is invalid, we move left to make it valid { char temp = s[left]; if (map[temp] > 1) count--; // the repeating char, count is not for all char, it is only counting repeating characters. map[temp] = map[temp] - 1; left++; } len = Math.Max(len, right - left); //when we update result, the invariant is satisfied, (no repeating character) within the sliding window. Usually the invariant is just the constraint //invariant is [left, right) contains a substring without repeating characters, which means every one here is a candidate. } return len; } public int LengthOfLongestSubstringTwoDistinct(string s) { int left = 0, right = 0, count = 0; int[] map = new int[256]; // assume all ascii charaters int len = 0; while (right < s.Length) { char c = s[right]; if (map[c] == 0) count++; //new character, different here, every character counts map[c] = map[c] + 1; right++; while (count > 2) //when condition is invalid, we move left to make it valid { char temp = s[left]; map[temp] = map[temp] - 1; if (map[temp] == 0) count--; // this character does not exist between (left, right) after left is processed left++; } len = Math.Max(len, right - left); } return len; } //extend to at most K characters public int LengthOfLongestSubstringKDistinct(string s, int k) { int left = 0, right = 0, count = 0; int[] map = new int[256]; // assume all ascii charaters int len = 0; while (right < s.Length) { char c = s[right]; if (map[c] == 0) count++; //new character, different here, every character counts map[c] = map[c] + 1; right++; while (count > k) //when condition is invalid, we move left to make it valid { char temp = s[left]; map[temp] = map[temp] - 1; if (map[temp] == 0) count--; // this character does not exist between (left, right) after left is processed left++; } len = Math.Max(len, right - left); } return len; } public string MinWindow(string s, string p) { if (p.Length > s.Length) return string.Empty; Dictionary<char, int> freq = new Dictionary<char, int>(); for (int i = 0; i < p.Length; i++) { if (freq.ContainsKey(p[i])) freq[p[i]] = freq[p[i]] + 1; else freq.Add(p[i], 1); } //two pointers, one counter int left = 0, right = 0, counter = freq.Count; // no duplicate character here. int head = 0, minLen = int.MaxValue; while (right < s.Length) { if (freq.ContainsKey(s[right])) { freq[s[right]] = freq[s[right]] - 1; if (freq[s[right]] == 0) counter--; } right++; //next need to move left pointer while (counter == 0) { if (freq.ContainsKey(s[left])) { freq[s[left]] = freq[s[left]] + 1; //this check is necessary as the value could be still zero // > 0 means reset to zero, if (freq[s[left]] > 0) counter++; } // all chacters covered plus same length thats a hit if (right - left < minLen) { head = left; minLen = right - left; } left++; } } return minLen == int.MaxValue ? string.Empty : s.Substring(head, minLen); } } } <file_sep>/CodePractice/CodePractice/Amazon OA/CriticalConnectionClass.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { public class CriticalConnectionClass { // Basically, it uses dfs to travel through the graph to find if current vertex u, can travel back to u or previous vertex //low[u] records the lowest vertex u can reach //disc[u] records the time when u was discovered public IList<IList<int>> CriticalConnections(int n, IList<IList<int>> connections) { int[] low = new int[n]; // use adjacency list instead of matrix will save some memory, adjmatrix will cause MLE List<int>[] graph = new List<int>[n]; List<IList<int>> res = new List<IList<int>>(); int[] disc = Enumerable.Repeat<int>(-1, n).ToArray(); // use disc to track if visited (disc[i] == -1) for (int i = 0; i < n; i++) { graph[i] = new List<int>(); } // build graph for (int i = 0; i < connections.Count; i++) { int from = connections[i][0], to = connections[i][1]; graph[from].Add(to); graph[to].Add(from); } for (int i = 0; i < n; i++) { if (disc[i] == -1) { DFS(i, low, disc, graph, res, i); } } return res; } int time = 0; // time when discover each vertex private void DFS(int u, int[] low, int[] disc, List<int>[] graph, List<IList<int>> res, int pre) { disc[u] = low[u] = ++time; // discover u for (int j = 0; j < graph[u].Count; j++) { int v = graph[u][j]; if (v == pre) { continue; // if parent vertex, ignore } if (disc[v] == -1) { // if not discovered DFS(v, low, disc, graph, res, u); low[u] = Math.Min(low[u], low[v]); if (low[v] > disc[u]) { // u - v is critical, there is no path for v to reach back to u or previous vertices of u res.Add(new List<int> { u, v }); } } else { // if v discovered and is not parent of u, update low[u], cannot use low[v] because u is not subtree of v low[u] = Math.Min(low[u], disc[v]); } } } } } <file_sep>/CodePractice/CodePractice/LeetCode/AutoComplete.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice.LeetCode { public class AutocompleteSystem { private string sent; private TrieNode root; public AutocompleteSystem(string[] sentences, int[] times) { //build the trie root = new TrieNode(); for (int i = 0; i < sentences.Length; i++) { TrieNode current = root; string se = sentences[i]; foreach (char c in se) { if (c == ' ') { if (current.Nodes[26] == null) current.Nodes[26] = new TrieNode(); current = current.Nodes[26]; continue; } if (current.Nodes[c - 'a'] == null) current.Nodes[c - 'a'] = new TrieNode(); current = current.Nodes[c - 'a']; } current.Count += times[i]; current.word = se; } } public IList<string> Input(char d) { List<string> res = new List<string>(); //end of sentence if (d == '#') { //insert sent to trie TrieNode current = root; foreach (char c in sent) { if (c == ' ') { if (current.Nodes[26] == null) current.Nodes[26] = new TrieNode(); current = current.Nodes[26]; continue; } if (current.Nodes[c - 'a'] == null) current.Nodes[c - 'a'] = new TrieNode(); current = current.Nodes[c - 'a']; } current.word = sent; current.Count++; sent = ""; } else { List<TrieNode> temp = new List<TrieNode>(); sent += d; //search the whole tree TrieNode current = root; foreach (char c in sent) { current = c == ' ' ? current.Nodes[26] : current.Nodes[c - 'a']; if (current == null) break; //; } if (current.Count > 0) temp.Add(current); //last node in sent if (current != null) { foreach (var item in current.Nodes) { DFS(item, temp); } temp.Sort((a, b) => a.Count == b.Count ? a.word.CompareTo(b.word) : b.Count - a.Count); int len = Math.Min(3, temp.Count); for (int i = 0; i < len; i++) res.Add(temp[i].word); } } return res; } private void DFS(TrieNode root, List<TrieNode> ans) { if (root == null) return; foreach (var item in root.Nodes) { DFS(item, ans); } if (root.Count > 0) ans.Add(root); } } public class TrieNode { public TrieNode[] Nodes; public int Count; public string word; public TrieNode() { Count = 0; Nodes = new TrieNode[27]; } } /** * Your AutocompleteSystem object will be instantiated and called as such: * AutocompleteSystem obj = new AutocompleteSystem(sentences, times); * IList<string> param_1 = obj.Input(c); */ // This is another approach, each trie node has the list of words (sentence) that go through public class AutocompleteSystem2 { private readonly TrieNode2 root; private readonly Dictionary<string, int> map; private TrieNode2 curNode; private StringBuilder curSb; public AutocompleteSystem2(string[] sentences, int[] times) { root = new TrieNode2(); curNode = root; curSb = new StringBuilder(); map = new Dictionary<string, int>(); for (int i = 0; i < sentences.Length; i++) { string curSent = sentences[i]; int curTimes = times[i]; var node = root; map.Add(curSent, curTimes); foreach (char ch in curSent) { int charIndex = ch == ' ' ? 26 : ch - 'a'; if (node.children[charIndex] == null) { node.children[charIndex] = new TrieNode2(); } node = node.children[charIndex]; OrderFrequentSentences(node, curSent); } } } public IList<string> Input(char c) { if (c == '#') { string sent = curSb.ToString(); AddSentence(sent); curNode = root; curSb = new StringBuilder(); return new List<string>(); } else { curSb.Append(c); int charIndex = c == ' ' ? 26 : c - 'a'; if (curNode == null || curNode.children[charIndex] == null) { curNode = null; return new List<string>(); } curNode = curNode.children[charIndex]; return curNode.mostFrequentSents; } } private void AddSentence(string sent) { map[sent] = map.ContainsKey(sent) ? map[sent] + 1 : 1; var node = root; foreach (char ch in sent) { int charIndex = ch == ' ' ? 26 : ch - 'a'; if (node.children[charIndex] == null) { node.children[charIndex] = new TrieNode2(); } node = node.children[charIndex]; OrderFrequentSentences(node, sent); } } private void OrderFrequentSentences(TrieNode2 node, string sent) { if (!node.mostFrequentSents.Contains(sent)) { node.mostFrequentSents.Add(sent); } node.mostFrequentSents.Sort((a, b) => map[a] == map[b] ? string.Compare(a, b, StringComparison.Ordinal) : map[b] - map[a]); if (node.mostFrequentSents.Count > 3) { node.mostFrequentSents.RemoveAt(3); } } private class TrieNode2 { public readonly List<string> mostFrequentSents; public readonly TrieNode2[] children; public TrieNode2() { mostFrequentSents = new List<string>(); children = new TrieNode2[27]; } } } /** * Your AutocompleteSystem object will be instantiated and called as such: * AutocompleteSystem obj = new AutocompleteSystem(sentences, times); * IList<string> param_1 = obj.Input(c); */ } <file_sep>/CodePractice/CodePractice/SnniptPractice.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodePractice { public class PHeap // dynamic heap { public int used; public int capacity; public int[] store; public PHeap(int cap) { used = 0; capacity = cap; store = new int[capacity]; } public int Pop() { if (used == 0) throw new Exception("no element"); int res = store[0]; store[0] = store[used - 1]; Sink(); return res; } public int Peek() { if (used == 0) throw new Exception("no element"); return store[0]; } public void Add(int val) { if (used == capacity) Resize(); store[used] = val; used++; BubbleUp(); } public void BubbleUp() { int index = used - 1; while (index > 0 && Compare(store[index], store[(index - 1) / 2])) { Swap(index, (index - 1) / 2); index = (index - 1) / 2; } } public void Sink() { int index = 0; while (true) { int current = index; int left = 2 * current + 1; int right = 2 * current + 2; if (left < used && Compare(store[current], store[left])) current = left; if (right < used && Compare(store[current], store[right])) current = right; //order is right, return if (current == index) return; Swap(index, current); index = current; } } public bool Compare(int child, int parent) { // min heap, child smaller, need to swap return store[child] < store[parent]; // max heap, reversed } public void Swap(int a, int b) { int temp = store[a]; store[a] = store[b]; store[b] = temp; } public void Resize() { int[] temp = new int[2 * capacity]; store.CopyTo(temp, 0); store = temp; } } } <file_sep>/Amazon QA 2022/MaxDeviation.cs using System; using System.Collections.Generic; using System.Text; namespace AmazonOA { public class MaxDev { int MaxSubArraySum(List<int> arr, int k) { if (arr.Count < k) return 0; int n = arr.Count; int[] maxSum = new int[n]; // use kadane's maxSum[0] = arr[0]; for (int i = 1; i < arr.Count; i++) { maxSum[i] = Math.Max(arr[i], maxSum[i - 1] + arr[i]); } int sum = 0; for (int i = 0; i < k; i++) { sum += arr[i]; } int ans = sum; for (int i = k; i < arr.Count; i++) { sum = sum + arr[i] - arr[i - k]; ans = Math.Max(ans, sum); ans = Math.Max(ans, sum + maxSum[i - k]); } return ans; } int MaxDeviation(string str) { int ans = 0; for (char c1 = 'a'; c1 <= 'z'; c1++) { for (char c2 = 'a'; c2 <= 'z'; c2++) { if (c1 == c2) continue; List<int> arr = new List<int>(); // we consider c1 as character with maxFreq and c2 with minFreq foreach (char c in str) { if (c == c1) { // We shall include all consecutive c1's in our array so we add their frequency if (arr.Count > 0 && arr[arr.Count - 1] != -1) { arr[arr.Count - 1] += 1; } else { arr.Add(1); } } else if (c == c2) { // we take distinct c2 arr.Add(-1); } } ans = Math.Max(ans, MaxSubArraySum(arr, 2)); } } return ans; } } }
63b798f3c06f7a30bcf1bfa4f1bc47edeaf6c873
[ "Java", "C#", "Markdown" ]
78
C#
brightxiaomin/CodePrep
aee4f0d6a93f4f93051df0962151bd3745332570
a756a503adce6257a8c5e842fd558a55d008d5c0
refs/heads/master
<file_sep>package szkg.repositories; import org.apache.log4j.Logger; import szkg.algorithms.sort.ListType; import szkg.algorithms.sort.SorterType; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; /** * Created by Gencay on 21.06.2015. */ public class SqliteRepository implements IRepository { private Logger logger = Logger.getLogger(SqliteRepository.class); private Connection connection; private void openConnection() throws Exception { Class.forName("org.sqlite.JDBC"); connection = DriverManager.getConnection("jdbc:sqlite:GarbageCollection.sqlite"); } private void closeConnection() throws Exception { connection.close(); } private void createSortingTable() throws Exception { openConnection(); String createTableSql = "CREATE TABLE IF NOT EXISTS \"main\".\"SortingExecutions\" " + "(\"Id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , " + "\"Collector\" VARCHAR NOT NULL , " + "\"CoreCount\" INTEGER NOT NULL , " + "\"ListSize\" INTEGER NOT NULL , " + "\"Algorithm\" INTEGER NOT NULL , " + "\"ListType\" INTEGER NOT NULL , " + "\"PauseTime\" DOUBLE NOT NULL , " + "\"ExecutionTime\" DOUBLE NOT NULL , " + "\"JdkVersion\" VARCHAR NOT NULL , " + "\"CreateDate\" DATETIME NOT NULL DEFAULT CURRENT_DATE)"; PreparedStatement createTableStatement = connection.prepareStatement(createTableSql); createTableStatement.execute(); createTableStatement.close(); closeConnection(); } @Override public void open() throws Exception { createSortingTable(); } @Override public void addSortingExecution(int coreCount, String collector, int listSize, SorterType algorithm, ListType listType, double pauseTime, double executionTime, String jdkVersion) throws Exception { openConnection(); String addExecutionSql = "INSERT INTO SortingExecutions " + "(Collector, ListSize, Algorithm, ListType, PauseTime, ExecutionTime, CoreCount, JdkVersion)" + " VALUES (?,?,?,?,?,?,?,?)"; PreparedStatement addExecutionStatement = connection.prepareStatement(addExecutionSql); addExecutionStatement.setString(1, collector); addExecutionStatement.setInt(2, listSize); addExecutionStatement.setInt(3, algorithm.getValue()); addExecutionStatement.setInt(4, listType.getValue()); addExecutionStatement.setDouble(5, pauseTime); addExecutionStatement.setDouble(6, executionTime); addExecutionStatement.setInt(7, coreCount); addExecutionStatement.setString(8, jdkVersion); addExecutionStatement.execute(); addExecutionStatement.close(); closeConnection(); } } <file_sep>package szkg.algorithms.sort; import java.util.ArrayList; import java.util.LinkedList; //taken from http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort#Java public class InsertionSort implements ISorter { public ArrayList<Integer> sort(ArrayList<Integer> input) { for(int i = 1; i < input.size(); i++){ int value = input.get(i); int j = i - 1; while(j >= 0 && input.get(j) > value){ input.set(j + 1, input.get(j)); j = j - 1; } input.set(j + 1, value); } return input; } public LinkedList<Integer> sort(LinkedList<Integer> input) { for(int i = 1; i < input.size(); i++){ int value = input.get(i); int j = i - 1; while(j >= 0 && input.get(j) > value){ input.set(j + 1, input.get(j)); j = j - 1; } input.set(j + 1, value); } return input; } } <file_sep>package szkg.algorithms.sort; import java.util.ArrayList; import java.util.LinkedList; import java.util.Iterator; //taken from http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort public class MergeSort implements ISorter{ public ArrayList<Integer> sort(ArrayList<Integer> input) { if(input.size() <= 1) return input; int middle = input.size() / 2; ArrayList<Integer> left = new ArrayList<Integer>(input.subList(0, middle)); ArrayList<Integer> right = new ArrayList<Integer>(input.subList(middle, input.size())); right = sort(right); left = sort(left); ArrayList<Integer> result = merge(left, right); return result; } public ArrayList<Integer> merge(ArrayList<Integer> left, ArrayList<Integer> right){ ArrayList<Integer> result = new ArrayList<Integer>(); Iterator<Integer> it1 = left.iterator(); Iterator<Integer> it2 = right.iterator(); Integer x = it1.next(); Integer y = it2.next(); while (true){ //change the direction of this comparison to change the direction of the sort if(x <= y){ result.add(x); if(it1.hasNext()){ x = it1.next(); }else{ result.add(y); while(it2.hasNext()){ result.add(it2.next()); } break; } }else{ result.add(y); if(it2.hasNext()){ y = it2.next(); }else{ result.add(x); while (it1.hasNext()){ result.add(it1.next()); } break; } } } return result; } public LinkedList<Integer> sort(LinkedList<Integer> input) { if(input.size() <= 1) return input; int middle = input.size() / 2; LinkedList<Integer> left = new LinkedList<Integer>(input.subList(0, middle)); LinkedList<Integer> right = new LinkedList<Integer>(input.subList(middle, input.size())); right = sort(right); left = sort(left); LinkedList<Integer> result = merge(left, right); return result; } public LinkedList<Integer> merge(LinkedList<Integer> left, LinkedList<Integer> right){ LinkedList<Integer> result = new LinkedList<Integer>(); Iterator<Integer> it1 = left.iterator(); Iterator<Integer> it2 = right.iterator(); Integer x = it1.next(); Integer y = it2.next(); while (true){ //change the direction of this comparison to change the direction of the sort if(x <= y){ result.add(x); if(it1.hasNext()){ x = it1.next(); }else{ result.add(y); while(it2.hasNext()){ result.add(it2.next()); } break; } }else{ result.add(y); if(it2.hasNext()){ y = it2.next(); }else{ result.add(x); while (it1.hasNext()){ result.add(it1.next()); } break; } } } return result; } }<file_sep>log4j.rootLogger=ALL, ConsoleLogger, FileLogger log4j.appender.FileLogger=org.apache.log4j.FileAppender log4j.appender.FileLogger.File=log.txt log4j.appender.FileLogger.ImmediateFlush=true log4j.appender.FileLogger.Threshold=all log4j.appender.FileLogger.Append=true log4j.appender.FileLogger.layout=org.apache.log4j.PatternLayout log4j.appender.FileLogger.layout.conversionPattern=%d\t%p\t%m%n log4j.appender.ConsoleLogger=org.apache.log4j.ConsoleAppender log4j.appender.ConsoleLogger.layout=org.apache.log4j.PatternLayout log4j.appender.ConsoleLogger.layout.ConversionPattern=%d\t%p\t%m%n log4j.appender.ConsoleLogger.Threshold=all<file_sep>package szkg.repositories; import szkg.algorithms.sort.ListType; import szkg.algorithms.sort.SorterType; /** * Created by Gencay on 21.06.2015. */ public interface IRepository { public void open() throws Exception; public void addSortingExecution(int coreCount, String collector, int listSize, SorterType algorithm, ListType listType, double pauseTime, double executionTime, String jdkVersion) throws Exception; } <file_sep>package szkg.algorithms.sort; import java.util.ArrayList; import java.util.LinkedList; public interface ISorter { public ArrayList<Integer> sort(ArrayList<Integer> input); public LinkedList<Integer> sort(LinkedList<Integer> input); }
e2b930c49b8ea1542ae4209ed8c7a58640abfc40
[ "Java", "INI" ]
6
Java
szkg/garbagecollection
fb591273e1d0afa588fd93c3160bcc1ebb04d6f3
09f6fbc19b20a2c5fab4b6615fa3d6390ef2068d
refs/heads/master
<repo_name>kubaresicki/Obiektowe<file_sep>/ConsoleApp1/PodstepnyBankier.cs using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp1 { public class PodstepnyBankier: Bankier { public PodstepnyBankier(string imie) : base(imie) { } public override float Licz(float jeden, float dwa) { int wynik = (int)(jeden + dwa); return (float)(wynik*0.8); } } } <file_sep>/Delegatory/Program.cs using System; namespace Delegatory { class Program { public delegate int Delegator(int a, int b); public delegate string Delegator1(string s); public static int Mnozenie(int a, int b) { return a * b; } public static int Test(int a, int b, Delegator del) { return del(a, b); } public static int Maks(int a, int b) { if (a > b) return a; else return b; } static void Main(string[] args) { //Utwórz funkcję lambda (int) => (int) która zwraca ile razy wykona się następująca pętla: jeżeli a jest parzyste - podziel przez 2, jeżeli nieparzyste - pomnóż przez 3 i dodaj 1. Func<int, int> lambda = (a) => { int counter = 0; while (a != 1) { if (a % 2 == 0) a = a / 2; else a = 3 * a + 1; counter++; } return counter; }; //Utwórz funkcję lambda (string, bool) => (string), która ucina pierwszą literę albo ostatnią w zależności od wartości parametru logicznego. Func<string, bool> lamb = (string a) => { bool prawda; if (prawda) a.Substring(0); else a.Substring(a.Length); return a; }; Delegator1[] del1 = new Delegator1[5]; del1[0] = (s) => { return s + s + s; }; del1[1] = (s) => { string wynik = ""; wynik = s.Substring(0, 3); return wynik; }; for(int i = 0; i < 2; i++) { Console.WriteLine(del1[i]("miś")); } Delegator del; del = Mnozenie; /* Console.Write(del(5, 3)); Console.WriteLine(Test(3, 5, del)); */ } } } <file_sep>/Geometria/punkt.cs using System; using System.Collections.Generic; using System.Text; namespace Geometria { public class Punkt { public int WspX, WspY; public static Punkt operator+(Punkt a, Punkt b) { Punkt wynik = new Punkt(a.WspX + b.WspX, a.WspY + b.WspY); return wynik; } public static Punkt operator-(Punkt a, Punkt b) { Punkt wynik = new Punkt(a.WspX - b.WspX, a.WspY - b.WspY); return wynik; } /* public static Punkt operator *(Punkt a, Punkt b) { Punkt wynik = new Punkt((a.WspX + b.WspX)* (a.WspY + b.WspY)); return wynik; }*/ public Punkt(int WspX, int WspY) { this.WspX = WspX; this.WspY = WspY; } public override string ToString() { return string.Format("({0}, {1})", WspX, WspY); } } } <file_sep>/ConsoleApp1/Bankier.cs using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp1 { public abstract class Bankier { protected string imie; public Bankier(string imie) { this.imie = imie; } public abstract float Licz(float jeden, float dwa); } } <file_sep>/Geometria/Wektor.cs using System; using System.Collections.Generic; using System.Text; namespace Geometria { public class Wektor { public int[] tab; public Wektor(int[] tab) { this.tab = tab; } public static Wektor operator +(Wektor a, Wektor b) { if (a.tab.Length == b.tab.Length) { int[] tab = new int[a.tab.Length]; int[] tab1 = new int[b.tab.Length]; for (int i = 0; i < tab.Length; i++) { tab[i] = a.tab[i] + b.tab[i]; }; return new Wektor(tab); } else return null; } public static int operator *(Wektor a, Wektor b) { if (a.tab.Length == b.tab.Length) { int[] tab = new int[a.tab.Length]; int[] tab1 = new int[b.tab.Length]; int wynik = 0; for (int i = 0; i < a.tab.Length; i++) { tab[i] = a.tab[i] * b.tab[i]; wynik += tab[i]; }; return wynik; } else return 0; } public override string ToString() { string w = "["; for (int i=0; i<tab.Length; i++) { if((i + 1) != tab.Length) w += tab[i] + ","; if ((i + 1) == tab.Length) { w += "}"; } } return w; } } } <file_sep>/Geometria/Kwadrat.cs using System; using System.Collections.Generic; using System.Text; namespace Geometria { public class Kwadrat: Figura { public Kwadrat(int Dlugosc) : base(Dlugosc) { Console.WriteLine("Kwadrat"); } public override void Rysuj() { for (int i = 0; i < Dlugosc; i++) { for(int j = 1; j < Dlugosc; j++) { Console.Write("*"); } Console.WriteLine(); } } public int Pole() { return Dlugosc * Dlugosc; } } } <file_sep>/Geometria/Linia.cs using System; using System.Collections.Generic; using System.Text; namespace Geometria { public class Linia : Figura { public Linia(int Dlugosc) : base(Dlugosc) { Console.WriteLine("utowrzone linie"); } public override void Rysuj() { for(int i = 1; i < Dlugosc; i++) { Console.Write("-"); } } } } <file_sep>/ConsoleApp1/Program.cs using System; using Geometria; namespace ConsoleApp1 { class Program { static void Main(string[] args) { //ZADANIE 1_________+++++++++++ //Figura[] f = new Figura[5]; //f[0] = new Linia(7); //f[1] = new Kwadrat(13); //f[2] = new Figura(56); //f[3] = new Linia(26); //f[4] = new Kwadrat(36); //foreach(Figura x in f) //{ // x.Rysuj(); // Console.WriteLine(); //} //ZADANIE 2________++++++++++++++ /* Console.WriteLine("kwadrat czy linia"); string name = Console.ReadLine(); Console.WriteLine("jaka wielkosc"); int y = Int32.Parse(Console.ReadLine()); if (name == "linia") { Linia linia = new Linia(y); linia.Rysuj(); } if (name == "kwadrat") { Kwadrat kwadrat = new Kwadrat(y); kwadrat.Rysuj(); }*/ //ZADANIE 3__++++++++++++++++ /* Random r = new Random(); int liczba = r.Next(); Figura figura; if (liczba % 2 == 0) figura = new Linia(23); else figura = new Kwadrat(23); //string typ = figura.getType().ToString(); string a = "sdfsg"; Console.WriteLine(a.GetType().ToString()); */ /* Rysownik.Test(new Kwadrat(4)); Punkt p = new Punkt(53, 87); Punkt q = new Punkt(-3, -81); Console.WriteLine(p + q); Console.WriteLine(p - q); Console.ReadLine(); PodstepnyBankier podstepny = new PodstepnyBankier("Jan"); Console.WriteLine("podstępny"+podstepny.Licz(1, 2)); UczciwyBankier bankier = new UczciwyBankier("Aleksander"); Console.WriteLine("uczciwy"+bankier.Licz(1, 2)); */ int[] tab = new int[] { 1, 2, 3, 4, 5, 6 }; Wektor w = new Wektor(tab); int[] tab1 = new int[] { 0, 1, 2, 3, 4, 5 }; Wektor w1 = new Wektor(tab1); Console.WriteLine(w + w1); Console.WriteLine(w * w1); } } } <file_sep>/Geometria/figura.cs using System; using System.Text; using System.Collections.Generic; namespace Geometria { public abstract class Figura { protected int Dlugosc; public Figura(int Dlugosc) { this.Dlugosc = Dlugosc; } public abstract void Rysuj(); public override string ToString() { return "dlugosc: " + Dlugosc; } } } <file_sep>/ConsoleApp1/UczciwyBankier.cs using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp1 { public class UczciwyBankier : Bankier { public UczciwyBankier(string imie): base(imie) { } public override float Licz(float jeden, float dwa) { return jeden + dwa; } } } <file_sep>/Geometria/Rysownik.cs using System; using System.Collections.Generic; using System.Text; namespace Geometria { public class Rysownik { public static void Test(Figura f) { f.Rysuj(); string typ = f.GetType().ToString(); if (typ == "Geometria.Kwadrat") { Kwadrat k = (Kwadrat)f; Console.WriteLine(k.Pole()); } } } }
c0549a91e1a3e3fa9aabc66d1f3753fb78b81ba1
[ "C#" ]
11
C#
kubaresicki/Obiektowe
25f185724b40b1fe1ed3656e56708af111af2f6c
5cdaa8159081f3eaa758f95266b3364a3736466d
refs/heads/master
<repo_name>bryandmc/pricer<file_sep>/price.go package main import ( "strconv" ) type Price struct { Current USD `json:"current,omitempty"` Lowest USD `json:"lowest,omitempty"` Highest USD `json:"highest,omitempty"` TaxRate float64 `json:"tax_rate,omitempty"` Tax USD `json:"tax,omitempty"` Additional USD `json:"additional,omitempty"` } type Currency interface { Normalize() Currency // normalize to proper notation New(float64) Currency // create a new instance Get() float64 // get the float representation Add(...float64) Currency // add it to any number of other values * Sub(...float64) Currency // subtract it from any number of other values Mult(...float64) Currency // multiply it and any number of other values Div(...float64) Currency // divide it and any number of other values Show() string } func CreateUSD(price float64) USD { u := USD{} return u.New(price).(USD) } // USD is a type of currency (duh) type USD struct { typename string dollars int cents int } func (us USD) Div(nums ...float64) Currency { startVal := us.Get() for _, n := range nums { startVal = startVal / n } us = us.New(startVal).(USD) return us } func (us USD) Mult(nums ...float64) Currency { startVal := us.Get() for _, n := range nums { startVal = startVal * n } us = us.New(startVal).(USD) return us } func (us USD) Add(nums ...float64) Currency { startVal := us.Get() for _, n := range nums { startVal = startVal + n } us = us.New(startVal).(USD) return us } func (us USD) Sub(nums ...float64) Currency { startVal := us.Get() for _, n := range nums { startVal = startVal - n } us = us.New(startVal).(USD) return us } // New is a constructor type function. Returns a pointer to a newly created variable func (us USD) New(in float64) Currency { us.dollars = 0 us.cents = int(in * 100) //remove decimal by multiplying by 100 us = us.Normalize().(USD) return us //then normalize it } // Normalize must be called on the currency so that there are less than 100 cents at all times // for USD, while other rules would apply for other currencies. func (us USD) Normalize() Currency { if us.cents > 99 { rem := us.cents % 100 div := us.cents / 100 us.dollars = us.dollars + div us.cents = rem } return us } // Get returns a float64 representation of the number func (us USD) Get() float64 { actual := float64(us.cents) / 100 return float64(float64(us.dollars) + actual) } // Show returns the properly formatted string representation of the number func (us USD) Show() string { return strconv.FormatFloat(us.Get(), 'f', 2, 64) } <file_sep>/models.go package main import ( "reflect" "os" "github.com/labstack/echo" mgo "gopkg.in/mgo.v2" ) // The goal of this entire file is to abstract the database portion of the app // Product is a representation of each product. type Product struct { Name string `json:"name,omitempty"` UPC string `json:"upc,omitempty"` Image *os.File `json:"-,omitempty"` //always omit this Filename string `json:"filename,omitempty"` Categories []Category `json:"categories,omitempty"` Price Price `json:"price,omitempty"` } // Category represents a products category type Category struct { Name string `json:"name,omitempty"` SubCategories []*Category `json:"sub_categories,omitempty"` //useful for traversing category tree SuperCategory []*Category `json:"super_category,omitempty"` //ditto ^^^^^ } // ConnectDB connects to mongoDB and returns a session. func ConnectDB() *mgo.Session { session, err := mgo.Dial("localhost") if err != nil { panic(err) } session.SetMode(mgo.Monotonic, true) return session } // MongoContext is a wrapper for the echo.Context to add more functionality onto it. type MongoContext struct { echo.Context Conn *mgo.Session DB *mgo.Database } func MongoMiddleWare() echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { s := ConnectDB() mg := MongoContext{c, s, s.DB("New")} return next(mg) // pass mg along } } } type Model interface { Save() Serialize() } // Save is the example wrapper for the more generic SaveGeneric. Unfortunately, // they seem to be required with the way Go is setup.Best case scenario, we will // be able to only write these small wrapper functions // Note: does allow for type specific checks though func (p Product) Save(db *mgo.Database, ctx *echo.Context) { SaveGeneric(db, ctx, p) } // SaveGeneric will take a struct and save it to the database func SaveGeneric(db *mgo.Database, ctx *echo.Context, doc interface{}) { t := Pluralize(GetType(doc)) (*ctx).Logger().Info(t, VerifyType(doc, new(Product))) // very basic logical implementation if VerifyType(doc, new(Product)) { db.C(t).Insert(doc) } } // GetType is modified from https://stackoverflow.com/a/35791105 // it returns the string name of the type given. Used for the // mongodb abstraction. func GetType(v interface{}) string { t := reflect.TypeOf(v) if t.Kind() == reflect.Ptr { return t.Elem().Name() } return t.Name() } // Pluralize simple adds an 's' to whatever string is entered. // A trivial implementation to pluralize strings. func Pluralize(s string) string { return s + "s" } // VerifyType takes in the two types and verifies them. // Meant to verify structs types are equal to a (usually) generically // instantiated version of the same struct. ex. *new(Person{}) // Note: doesn't matter which is which. func VerifyType(i interface{}, j interface{}) bool { first := GetType(i) second := GetType(j) // are they equal ? Find out. if first != second { return false } return true } <file_sep>/views.go package main import ( "encoding/json" "fmt" "net/http" "github.com/gorilla/websocket" "github.com/labstack/echo" ) var ( upgrader = websocket.Upgrader{} ) func test(c echo.Context) error { v := make(map[string]interface{}) ConnectDB() v["table2"] = [][]string{ {"1", "Bryan", "unemployed"}, {"2", "Dave", "unemployed"}, {"3", "<NAME>", "employed"}, } l := c.Logger() db := c.(MongoContext).DB fmt.Println(c.(MongoContext).Conn.Ping()) if err := c.(MongoContext).Conn.DB("New").C("comments").Insert(&v); err != nil { fmt.Println(err.Error()) } else { coll := c.(MongoContext).Conn.DB("New").C("Comments") fmt.Println(coll.Bulk()) } p := Product{} ctx := c.(MongoContext) p.Save(ctx.Conn.DB("New"), &c) newout := make([]interface{}, 10, 100) out := db.C("comments").Find(v).All(&newout) collection, _ := db.CollectionNames() l.Info(collection[0], out) c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8) c.Response().WriteHeader(http.StatusOK) return json.NewEncoder(c.Response()).Encode(newout) } func UpgradeWS(c echo.Context) error { ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil) if err != nil { return err } defer ws.Close() for { // Write p := Product{} err := ws.WriteJSON(p) if err != nil { c.Logger().Error(err) } // Read d, msg, err := ws.ReadMessage() if err != nil { c.Logger().Error(err) fmt.Println(d) } fmt.Printf("%s\n", msg) } } <file_sep>/routes.go package main import ( "github.com/labstack/echo" ) func LoadRoutes(e *echo.Echo) { e.GET("/test/", test) e.GET("/ws/", UpgradeWS) } <file_sep>/server.go package main import ( "fmt" "github.com/labstack/echo" "github.com/labstack/echo/middleware" ) type JSON struct { Key string `json:"key,omitempty"` Value interface{} `json:"value,omitempty"` } func main() { u := CreateUSD(19.99) p := Price{u, u.Sub(10).(USD), u.Add(10).(USD), 0.01, CreateUSD(1.98), CreateUSD(0)} fmt.Println(p) e := echo.New() e.Use(middleware.CORS(), middleware.AddTrailingSlash(), MongoMiddleWare()) e.Debug = true LoadRoutes(e) e.Logger.Info(e.Start(":8000")) } <file_sep>/pricer/src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import axios from 'axios'; import registerServiceWorker from './registerServiceWorker'; import injectTapEventPlugin from 'react-tap-event-plugin'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import FlatButton from 'material-ui/FlatButton'; import TextField from 'material-ui/TextField'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'material-ui/Table'; import Divider from 'material-ui/Divider'; import Paper from 'material-ui/Paper'; import {Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle} from 'material-ui/Toolbar'; import IconMenu from 'material-ui/IconMenu'; import IconButton from 'material-ui/IconButton'; import FontIcon from 'material-ui/FontIcon'; import NavigationExpandMoreIcon from 'material-ui/svg-icons/navigation/expand-more'; import MenuItem from 'material-ui/MenuItem'; import DropDownMenu from 'material-ui/DropDownMenu'; import RaisedButton from 'material-ui/RaisedButton'; // Needed for onTouchTap // http://stackoverflow.com/a/34015469/988941 injectTapEventPlugin(); class ProductList extends React.Component { constructor(props) { super(props); this.state = {table:""} } componentDidMount(){ axios.get("http://localhost:8000/test/").then( (res) => { console.log(res) if (res.status == 200) { var val = res.data["key"] //this.setState({ value: val}) var rows = this.getValue(res.data["table"]) console.log(rows) this.setState({table: rows }) } }) } getValue(objects){ console.log(objects) return ( <TableBody> {objects.map(function(ro) { return ( <TableRow key={ro[0]} data={ro}> <TableRowColumn>{ro[0]}</TableRowColumn> <TableRowColumn>{ro[1]}</TableRowColumn> <TableRowColumn>{ro[2]}</TableRowColumn> </TableRow> ); })} </TableBody> ); } render() { return ( <MuiThemeProvider> <Table> <TableHeader> <TableRow> <TableHeaderColumn>ID</TableHeaderColumn> <TableHeaderColumn>Name</TableHeaderColumn> <TableHeaderColumn>Status</TableHeaderColumn> </TableRow> </TableHeader> {this.state.table} </Table> </MuiThemeProvider> ) } } class NameForm extends React.Component { constructor(props) { super(props); this.state = { value: '' }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.onClick = this.onClick.bind(this) this.style = { marginLeft: 20, }; } handleChange(event) { this.setState({ value: event.target.value }); } handleSubmit(event) { alert('A name was submitted: ' + this.state.value); event.preventDefault(); } onClick(event) { alert(this.state.value) } componentDidMount(){ axios.get("http://localhost:8000/test/").then( (res) => { console.log(res) if (res.status == 200) { var val = res.data["key"] this.setState({value: val}) } }) } render() { return( <MuiThemeProvider> <Paper zDepth={2}> < form onSubmit = { this.handleSubmit } > <TextField hintText="First name" style={this.style} underlineShow={false} floatingLabelText="Name:" type = "text" value = { this.state.value } onChange = { this.handleChange } /> <Divider /> <TextField hintText="Middle name" style={this.style} underlineShow={false} /> <Divider /> <TextField hintText="Last name" style={this.style} underlineShow={false} /> <Divider /> <TextField hintText="Email address" style={this.style} underlineShow={false} /> <Divider /> <FlatButton type="submit" value="Submit" label="Submit" fullWidth={true} /> </form> </Paper> </MuiThemeProvider> ); } } function get(url) { fetch(url).then(res => { if (res.ok) return res.json(); else throw new Error(res) }) } function post(url, request) { fetch(url, request).then(res => { if (res.ok) return res.json(); else throw new Error(res) }) } class Navvy extends React.Component{ constructor(props) { super(props); this.state = { value: 1, }; } handleChange = (event, index, value) => this.setState({value}); handleSubmit(event) { } componentDidMount(){ } render() { return( <MuiThemeProvider> <Toolbar> <ToolbarGroup firstChild={true}> <DropDownMenu value={this.state.value} onChange={this.handleChange}> <MenuItem value={1} primaryText="All Products" /> <MenuItem value={2} primaryText="Search" /> </DropDownMenu> </ToolbarGroup> <ToolbarGroup> <ToolbarTitle text="Products" /> <FontIcon className="muidocs-icon-custom-sort" /> <ToolbarSeparator /> <RaisedButton label="Create Broadcast" primary={true} /> <IconMenu iconButtonElement={ <IconButton touch={true}> <NavigationExpandMoreIcon /> </IconButton> }> <MenuItem primaryText="Download" /> <MenuItem primaryText="More Info" /> </IconMenu> </ToolbarGroup> </Toolbar> </MuiThemeProvider> ); } } ReactDOM.render(React.createElement(Navvy), document.getElementById('navvy')); ReactDOM.render(React.createElement(ProductList), document.getElementById('product_list')) registerServiceWorker();<file_sep>/README.md # pricer A simple price tracking/updating engine this is currently not an active project. Only the Price/Currency structures/interface were used for another project.
25e5d5c1e25f4635c6950cafbd580bdc9e055970
[ "JavaScript", "Go", "Markdown" ]
7
Go
bryandmc/pricer
38f71b23b486ff8f6ccf947bb27d44afaefd5de7
b2af1fa0f33b8340342065484a9436ac2fa0dfb9
refs/heads/master
<file_sep># leadr A time limited secret microblog for groups with the possibility of revealing all posts at a later date # demo The website is currently live [here](https://leadr.freeciv.life) #background This is an experiment around a slow paced long running game and whether it would be possible to set up a 'secret twitter' The idea is that nobody can see your 'tweets' - we call them jots until the end of the game. This means you can document plans, attacks, intrigue etc. #review It worked well - sadly only a few players jotted regularly, but reading the jots is entertaining. #future I have a vague dream of this being developed into something to be used on stag or hen dos or other fairly long term events featuring the same people. <file_sep>from flask import render_template, url_for, redirect, flash, request from flask_login import login_user, logout_user, login_required, current_user from itsdangerous import TimestampSigner, BadTimeSignature, Signer, BadSignature, SignatureExpired from passlib.hash import pbkdf2_sha256 as hasher from . import app from .forms import Login_Form, New_Jot_Form, New_Password_Form, Forgot_Password_Form from . import secrets from .models import User, Jot timedsigner = TimestampSigner(secrets.SECRET_KEY) untimedsigner = Signer(secrets.SECRET_KEY) @app.route('/') def index(): if current_user.is_authenticated: return redirect(url_for('new_jot')) else: return redirect(url_for('login_view')) @app.route('/myjots') @login_required def all_jots(): user = User.get(id=current_user.id) jots = Jot.select().where(Jot.user==user).order_by(Jot.datetime.desc()) return render_template('all_jots.html', jots=jots) @app.route('/jotted') @login_required def jotted(): jot = request.args.get('jot') return render_template('jotted.html',jot=Jot.get(id=jot)) @app.route('/jot', methods = ['GET', 'POST']) @login_required def new_jot(): form = New_Jot_Form(id=current_user.id) if form.validate_on_submit(): user = User.get(id=int(form.id.data)) text = form.text.data jot = Jot.create(text=text, user=user) return redirect(url_for('jotted',jot=jot.id)) return render_template("new_jot.html",form=form) @app.route('/logout', methods=['GET']) def logout_view(): logout_user() return redirect(url_for('login_view')) @app.route('/login',methods=['GET','POST']) def login_view(): form = Login_Form() #if they have filled in the form, deal with the login if form.validate_on_submit(): username = form.username.data.lower()#no need for it to be case sensitive password = form.password.data try:#does the user exist? Redirect to login if they don't user = User.get(username=username) except User.DoesNotExist: flash("User {} does not exist, bro!".format(username)) return redirect(url_for('login_view')) #before trying to authenticate, see if the user is confirmed if user.confirmed == False: flash("User {} is not confirmed - see the link in the email...".format(username)) return redirect(url_for('login_view')) #if they are confirmed, try and authenticate, redirect to login if fails if user.authenticate(password): #it all works, yay! log them in! login_user(user) return redirect(url_for('new_jot')) else: flash("That password isn't right, sis!") return redirect(url_for('login_view')) #if it's not filled in, or not valid, let them do it again, including errors if needed return render_template("login.html",form=form) @app.route('/single/<user>/<code>') def single_use(user, code): try: timedsigner.unsign(request.url, max_age=3600) user_to_login = User.get(username=user) login_user(user_to_login) return redirect(url_for('new_password')) except BadTimeSignature: flash("That link was not valid") return redirect(url_for('index')) except SignatureExpired: flash("That link is more than an hour old") return redirect(url_for('index')) @app.route('/register/<username>/<code>') def register(username,code): try: untimedsigner.unsign(request.url) except BadSignature: flash("That link was not valid") return redirect(url_for('index')) #special URL is okay, let's log whoever out if current_user.is_authenticated: flash("Logging out {} as this is a link for registering someone".format(current_user.username)) logout_user() #but does the user exist? try: user = User.get(username=username) except User.DoesNotExist: flash("That user doesn't exist. This is strange in a link that should only be generated for valid users!") return redirect(url_for('index')) #okay so the user exists, but what if they're already registered? if user.confirmed: flash("That user is already registered, go ahead and log in.") return redirect(url_for('index')) #so they aren't already registered, let's register them, log them in, and send them to the change password page user.confirmed = True user.save()#now registered - is there a weakpoint here where if they don't change password straight away, the hash is left as null? login_user(user) flash("You are now registered for leadr. Please set a password so you can come back!") return redirect(url_for('new_password')) @app.route('/password', methods=['GET', 'POST']) @login_required def new_password(): form = New_Password_Form(id=current_user.id) if form.validate_on_submit(): user = User.get(id=int(form.id.data)) password = form.new_password.data user.password_hash = <PASSWORD>(password) user.save() flash("Password Changed") return redirect(url_for('new_jot')) return render_template("new_password.html",form=form) @app.route('/forgot', methods=['GET', 'POST']) def forgot_password(): form = Forgot_Password_Form() if form.validate_on_submit(): flash("If the address {} is _with us, then we have sent a login link to it. It is valid for one hour. Use it to change your password.".format(form.email.data)) try: user = User.get(email=form.email.data) link_stem = url_for('single_use',user=user.username, code="", _external=True) signed_link = timedsigner.sign(link_stem).decode() message = "Hi {},\n\nYou requested a login in order to change your password. Please use this link:\n{}\nThanks!\nlove from leadr x".format(user.username,signed_link) user.send_email("Forgotten leadr password?",message) except User.DoesNotExist: pass # fail gracefully for security reasons - people now can't tell if an email address is registered on the site return redirect(url_for('login_view')) return render_template('forgot.html',form=form) <file_sep>from flask import Flask app = Flask(__name__) import views @app.route('/yo/') def what(): return "YO" if __name__ == '__main__': app.run(host="0.0.0.0",port=5678,debug=True) <file_sep>from .models import User while True: uname = input("Username?") passwd = input("<PASSWORD>") print("match={}".format(User.get(username=uname).authenticate(passwd))) <file_sep>from peewee import Model, CharField, DateTimeField, TextField, ForeignKeyField, IntegerField, BooleanField, PostgresqlDatabase from passlib.hash import pbkdf2_sha256 as hasher from datetime import datetime from email.message import EmailMessage import smtplib from . import secrets db = PostgresqlDatabase(secrets.POSTGRES_DB, user=secrets.POSTGRES_USER, password=secrets.POST<PASSWORD>, host='127.0.0.1') class User(Model): class Meta: database = db db_table = "user_account" pass username = CharField(unique=True) civname = CharField() email = CharField(verbose_name="Email Address") confirmed = BooleanField(default=False) hexcode = CharField(max_length=6) password_hash = CharField(max_length=87, null=True) avatar = CharField(max_length=255, null=True) #flask-login stuff @property def is_authenticated(self): return True @property def is_active(self): return True @property def is_anonymous(self): return False def get_id(self): return str(self.id) def authenticate(self, password): return hasher.verify(password,self.password_hash) def send_email(self,subject,text): """Sends email with subject *subject* and body *text* to the user's email address.""" message = EmailMessage() message['From'] = secrets.FROM_ADDR message['To'] = self.email message['Subject'] = subject message.set_content(text) server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.login(secrets.FROM_ADDR, secrets.EMAIL_PASSWORD) server.send_message(message) class Jot(Model): class Meta: database = db user = ForeignKeyField(User, related_name='jots') datetime = DateTimeField(default=datetime.now) text = CharField(max_length=140) def date_formatted(self): return self.datetime.strftime("%d %b %y") def time_formatted(self): return self.datetime.strftime("%H:%M") class Turn(Model): class Meta: database = db timestamp = DateTimeField(default=datetime.now) number = IntegerField() year = CharField(max_length=6) <file_sep>from flask_wtf import FlaskForm from wtforms.fields import StringField, PasswordField, TextAreaField, HiddenField from wtforms.validators import Length, Email class Login_Form(FlaskForm): username = StringField() password = PasswordField() class New_Jot_Form(FlaskForm): text = TextAreaField('Jot',validators=[Length(1,140)]) id = HiddenField("id") class New_Password_Form(FlaskForm): new_password = PasswordField('New Password', validators=[Length(min=8)]) id = HiddenField('id') class Forgot_Password_Form(FlaskForm): email = StringField(validators=[Email(message="That doesn't look like a valid email address.")]) <file_sep>{% from 'macros.html' import display_jot %} {% extends 'base.html' %} {% block content %} Your newest jot: {{display_jot(jot)}} Thanks!<br> Why not <a href="{{url_for('new_jot')}}">jot again</a>? {% endblock %} <file_sep>from application.models import User import itsdangerous import application.secrets as secrets print("""what is the URL stem? 1 => wilsonseverywhere.ddns.net:8000 2 => leadr.freeciv.life Something else => use that""") a = input() if a == "1": URL_STEM = "http://wilsonseverywhere.ddns.net:8000" elif a == "2": URL_STEM = "https://leadr.freeciv.life" else: URL_STEM = a signer = itsdangerous.Signer(secrets.SECRET_KEY) username=input('username?') civname=input('civname?') email=input('email?') hexcode=input('hexcode?') u = User.create(username=username, civname=civname, email=email, confirmed=False, hexcode=hexcode) link_stem = "{}/register/{}/".format(URL_STEM,username) signed_link = signer.sign(link_stem.encode('utf-8')) u.send_email("TEST","Testing the registration stuff. Bit of a bind. URL: {} ".format(signed_link.decode())) <file_sep>from flask import Flask, url_for from flask_login import LoginManager, current_user from .models import User,Jot app = Flask(__name__) from . import views from . import secrets app.config['SECRET_KEY'] = secrets.SECRET_KEY login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login_view' @login_manager.user_loader def load_user(user_id_unicode): try: return User.get(id=int(user_id_unicode)) except User.DoesNotExist: return None @app.context_processor def stats(): total = Jot.select().count() if current_user.get_id(): user = User.get(id=current_user.id) user_total = Jot.select().where(Jot.user==user).count() else: user_total=None return dict( jot_count=total, user_jot_count=user_total)
3ec445000f93566f623384981026b21825858556
[ "Markdown", "Python", "HTML" ]
9
Markdown
wilsonrocks/leadr
05d468208f36d710de63b8692c90324c08d1d8f7
94e9750a5464fd5453d972bde2ad6febabda3226
refs/heads/master
<repo_name>andri000me/aplikasi-kp<file_sep>/application/views/admin_kelolapengguna_edit.php <div class="container mt-2"> <div class="d-flex flex-column p-3 bg-white text-black border rounded"> <div class="container mt-3 border-btm"> <div class="d-flex justify-content-beetwen row"> <div class="col-sm-12 col-md-6 col-lg-6"> <div><h3>Edit Pengguna</h3></div> </div> <div class="col-sm-12 col-md-6 col-lg-6" style="text-align: right;"> <?php if ($this->session->userdata('nama') == "admin") { ?> <a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <a href="<?= base_url('admin_kelolapengguna?labId='); ?>">Kelola Pengguna</a> > <b>Edit Pengguna</b> <?php }else{ ?> <a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <a href="<?= base_url('admin_kelolalab/lab_info'); ?>">Kelola Laboratorium</a> > <b>Edit Pengguna</b> <?php } ?> </div> </div> </div> <?php if ($this->session->userdata('nama') != "admin") { ?> <form action="<?php echo base_url('admin_kelolapengguna/modUser?labId='.$as->lab_id)?>" method="post"> <div class="mt-2 mb-2"> <button class="btn btn-primary btn-sm mr-2" type="submit">Simpan</button> <a href="<?php echo base_url('admin_kelolapengguna?labId=').$as->lab_id ?>"> <span class="btn btn-danger btn-sm">Batal</span> </a> </div> <div class="collapsible rounded"> <small><b>Nama</b></small> <input type="text" name="nama" class="form-control form-control-sm" required value="<?= $as->name ?>"><br> <small class="hide-form"> <select class="form-control form-control-sm" name="status" readonly> <option selected hidden><?php echo $as->level ?></option> <option>Koordinator Laboratorium</option> <option>Asisten Laboratorium</option> </select> </small> <small class="hide-form"> <input type="text" name="lab" class="form-control form-control-sm form-block" required value="<?= $as->lab_id ?>" readonly> </small> </div> <div class="content-edit"> <div class="mb-2 p-3"> <div class="d-flex flex-column"> <div class="p-2"><small><b>E-Mail</b><br></small> <input type="text" name="email" class="form-control form-control-sm form-block" required value="<?= $as->email ?>"> </div> <div class="p-2"><small><b>Kontak</b><br></small> <input type="text" name="kontak" class="form-control form-control-sm" required value="<?= $as->cp ?>"> </div> <div class="p-2"><small><b>Nama Pengguna</b><br></small> <input type="text" name="username" class="form-control form-control-sm" required value="<?= $as->username ?>"> <div class="hide-form"> <input type="text" name="u_id" class="form-control form-control-sm" required value="<?= $as->u_id ?>"> </div> </div> <div class="p-2"><small><b>Kata Sandi</b><br></small> <input type="text" name="password" class="form-control form-control-sm" required value="<?= $as->password ?>"> </div> </div> </div> </div> </form> <?php }else{ ?> <form action="<?php echo base_url('admin_kelolapengguna/modUser?labId=')?>" method="post"> <div class="mt-2 mb-2"> <button class="btn btn-primary btn-sm mr-2" type="submit">Simpan</button> <a href="<?php echo base_url('admin_kelolapengguna?labId=')?>"> <span class="btn btn-danger btn-sm">Batal</span> </a> </div> <div class="collapsible rounded"> <input type="text" name="nama" class="form-control form-control-sm" required value="<?= $as->name ?>"><br> <small> <select class="form-control form-control-sm" name="status"> <option selected hidden><?php echo $as->level ?></option> <option>Koordinator Laboratorium</option> <option>Asisten Laboratorium</option> </select> </small><br> <small> <select class="form-control form-control-sm" name="lab"> <option selected value="<?php echo $as->lab_id; ?>"><?php echo $as->lab_name ?></option> <?php foreach ($optLab as $listLab) : ?> <option value="<?php echo $listLab->lab_id; ?>"><?php echo $listLab->lab_name; ?></option> <!--PASS VALUE LAB ID KE MODEL??--> <?php endforeach; ?> </select> </small> </div> <div class="content-edit"> <div class="mb-2 p-3"> <div class="d-flex flex-column"> <div class="p-2"><small><b>E-Mail</b><br></small> <input type="text" name="email" class="form-control form-control-sm form-block" required value="<?= $as->email ?>"> </div> <div class="p-2"><small><b>Kontak</b><br></small> <input type="text" name="kontak" class="form-control form-control-sm" required value="<?= $as->cp ?>"> </div> <div class="p-2"><small><b>Username</b><br></small> <input type="text" name="username" class="form-control form-control-sm" required value="<?= $as->username ?>"> <div class="hide-form"> <input type="text" name="u_id" class="form-control form-control-sm" required value="<?= $as->u_id ?>"> </div> </div> <div class="p-2"><small><b>Password</b><br></small> <input type="text" name="password" class="form-control form-control-sm" required value="<?= $as->password ?>"> </div> </div> </div> </div> </form> <?php } ?> </div> </div> </body> </html><file_sep>/application/models/androidDb.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Db_labkom extends CI_Model{ function __construct(){ } function daftar_perangkat($type){ $query = $this->db->query("select from wares where w_kind = '$type'"); return $query; } }<file_sep>/application/views/labInfo.php <?php if (isset($_GET['warn'])) { if ($_GET['warn']=="success") { echo '<script type="text/javascript">window.onload=alert("Data Ditambahkan!");</script>'; }elseif ($_GET['warn']=="delsuccess") { echo '<script type="text/javascript">window.onload=alert("Data Dihapus!");</script>'; }elseif ($_GET['warn']=="updsuccess") { echo '<script type="text/javascript">window.onload=alert("Data Diubah!");</script>'; }elseif ($_GET['warn']=="aslabfull") { echo '<script type="text/javascript">window.onload=alert("Gagal! Laboratorium sudah memiliki 2 asisten!");</script>'; } } $userLevel = $this->session->userdata("level"); ?> <?php if ($userLevel == "admin") { ?> <!--BACA ROLE USER INI DULUUUU--> <div class="container mt-2 d-flex flex-column p-3 bg-white text-black border rounded"> <div class="container mt-3 border-btm"> <div class="d-flex justify-content-beetwen row"> <div class="col-sm-12 col-md-6 col-lg-6"> <div><h3>Kelola <?php echo $namaLaboratorium->lab_name; ?></h3></div> </div> <div class="col-sm-12 col-md-6 col-lg-6" style="text-align: right;"> <?php if ($this->session->userdata('nama') == "admin") { ?> <a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <a href="<?= base_url('admin_kelolalab'); ?>">Kelola Laboratorium</a> > <b>Info Laboratorium</b> <?php }else{ ?> <a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <b>Kelola Laboratorium</b> <?php } ?> </div> </div> </div> <div class="d-flex justify-content-end mt-2 mb-2"> <div style="text-align: right;" class="col-sm-12 col-md-6 col-lg-6"> <input type="text" name="" class="inputbox-3 p-1 form form-control" id="input" onkeyup="searchTable()" placeholder=" Cari..."> </div> </div> <div class="container mt-2 row ml-2"> <div class="col-sm-12 col-md-4 col-lg-4 bg-light" style="max-height: 370px;"> <div class="mt-2"> <span style="font-size: 14pt;"><b>Informasi Laboratorium</b></span> <hr> <span><b>Kapasitas :</b> <?php echo $namaLaboratorium->capacity; ?>-PC</span><br> <span> <b>Siap Pakai:</b> <?php $kapasitasLab = $namaLaboratorium->capacity; $pcBermasalah = $countTrouble; $perangkatBermasalah = $countPC->sumPC; $siapPakai = $kapasitasLab-$pcBermasalah; echo $siapPakai; ?>-PC </span><br> <span> <b>Jumlah Masalah:</b> <?php if ($perangkatBermasalah == 0) { echo "---"; }else{ echo $perangkatBermasalah; ?> perangkat <?php } ?> </span> <hr> <span> <b>Koordinator:</b> <?php if ($koordinatorLab == ' ') { echo "----"; }else{ echo $koordinatorLab; } ?> </span> <hr> <span class="d-flex"> <b>Asisten Laboratorium</b> <?php if ($this->session->userdata("nama")=="admin") { ?> <?php }else{ ?> <a href="<?php echo base_url('admin_kelolapengguna');?>?labId=<?= $lab->lab_id; ?>"> <button type="submit" class="btn btn-primary btn-sm ml-1 mr-1"> <i class="fa fa-info"></i> </button> </a> <?php } ?> </span> <ul class="list-unstyled"> <?php foreach ($aslabList as $key) : ?> <li><?php echo $key->name; ?></li> <?php endforeach; ?> </ul> <hr> </div> </div> <div class="col-sm-12 col-md-8 col-lg-8 p-3"> <h3>Daftar Kerusakan Perangkat</h3> <div class="table table-responsive" style="width: 100%;"> <table class="table table-sm table-bordered table-striped mt-2" id="sortTable" style="width: 100%;"> <tr align="center"> <th style="width: 30%;">Nama Perangkat</th> <th style="width: 26%;">Deskripsi Kerusakan</th> <th style="width: 24%;">PC-</th> <?php if ($userLevel == "admin") { }else{ ?> <th style="width: 20%;">Aksi</th> <?php } ?> </tr> <?php $i=0; foreach ($troubleList as $val) : $i++; ?> <tr> <!--<td align="center" style="width: 5%;"><?php echo $i; ?></td>--> <td><?= $val->wares_name; ?></td> <td><?= $val->description; ?></td> <td align="center">PC-<?= $val->pc; ?></td> <?php if ($userLevel == "admin") { }else{ ?> <td class="d-flex justify-content-center" style="border: none;"> <div> <a class="btn btn-primary btn-sm mr-2" href="<?= base_url('admin_kelolalab/lab_info');?>?name=<?= $val->wares_name; ?>&desc=<?= $val->description; ?>&pc=<?= $val->pc; ?>&id=<?= $val->lab_id; ?>&thingID=<?= $val->things_id; ?>" role="button"> <i class="fa fa-edit" style="font-size: 10pt;"></i> <!--<button type="submit" class="btn btn-primary border btn-sm m-1"> <i class="fa fa-edit"></i> </button>--> </a> </div> <div> <!--form delete--> <form action="<?php echo base_url('admin_kelolalab/hapus_kerusakan')?>" method="post"> <div class="hide-form"> <input readonly type="text" class="btn btn-tersier" name="tId" value="<?= $val->things_id;?>"> <input readonly type="text" class="btn btn-tersier" name="labId" value="<?= $val->lab_id;?>"> </div> <button type="submit" class="btn btn-danger border btn-sm del_alert"> <i class="fa fa-trash"></i> </button> </form> </div> </td> <?php } ?> </tr> <?php endforeach; ?> </table> </div> </div> </div> </div> <?php }elseif ($userLevel == "Koordinator Laboratorium") { ?><!--BACA ROLE USER INI DULUUUU--> <div class="container mt-2 d-flex flex-column p-3 bg-white text-black border rounded"> <div class="container mt-3 border-btm"> <div class="d-flex justify-content-beetwen row"> <div class="col-sm-12 col-md-6 col-lg-6"> <div><h3>Kelola <?php echo $namaLaboratorium->lab_name; ?></h3></div> </div> <div class="col-sm-12 col-md-6 col-lg-6" style="text-align: right;"> <?php if ($this->session->userdata('nama') == "admin") { ?> <a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <a href="<?= base_url('admin_kelolalab'); ?>">Kelola Laboratorium</a> > <b>Info Laboratorium</b> <?php }else{ ?> <a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <b>Kelola Laboratorium</b> <?php } ?> </div> </div> </div> <div class="ml-4 mt-2"> <div class="d-flex justify-content-beetwen row"> <!-- Button trigger modal --> <button class="btn btn-primary btn-sm" onclick="modal()" data-toggle="modal" data-target="#modalTambahPengguna"><b>+</b>Tambah Asisten</button> <button class="btn btn-primary btn-sm ml-2" onclick="modal()" data-toggle="modal" data-target="#modalKerusakan"><b>+</b>Tambah Kerusakan</button> </div> </div> <div class="container mt-2 row ml-2"> <div class="col-sm-12 col-md-4 col-lg-4 bg-light" style="max-height: 370px;"> <div class="mt-2"> <span style="font-size: 14pt;"><b>Informasi Laboratorium</b></span> <hr> <span><b>Kapasitas :</b> <?php echo $namaLaboratorium->capacity; ?>-PC</span><br> <span> <b>Siap Pakai:</b> <?php $kapasitasLab = $namaLaboratorium->capacity; $pcBermasalah = $countTrouble; $perangkatBermasalah = $countPC->sumPC; $siapPakai = $kapasitasLab-$pcBermasalah; echo $siapPakai; ?>-PC </span><br> <span> <b>Bermasalah:</b> <?php if ($perangkatBermasalah == 0) { echo "---"; }else{ echo $perangkatBermasalah; ?> perangkat <?php } ?> </span> <hr> <span> <b>Koordinator:</b><br> <?php if ($koordinatorLab == ' ') { echo "----"; }else{ echo $koordinatorLab; } ?> </span> <hr> <span class="d-flex"> <b>Asisten Laboratorium</b> <?php if ($this->session->userdata("nama")=="admin") { ?> <?php }else{ ?> <a href="<?php echo base_url('admin_kelolapengguna');?>?labId=<?= $lab->lab_id; ?>"> <button type="submit" class="btn btn-primary btn-sm ml-1 mr-1"> <i class="fa fa-edit"></i> </button> </a> <?php } ?> </span> <ul class="list-unstyled"> <?php foreach ($aslabList as $key) : ?> <li><?php echo $key->name; ?></li> <?php endforeach; ?> </ul> <hr> </div> </div><br> <div class="col-sm-12 col-md-8 col-lg-8 mt-3"> <h3>Daftar Kerusakan Perangkat</h3> <div> <input type="text" name="" class="inputbox-3 p-1" id="input" onkeyup="searchTable()" placeholder=" Cari..."> </div> <div class="table table-responsive" style="width: 100%;"> <table class="table table-sm table-bordered table-striped mt-2" id="sortTable" style="width: 100%;"> <tr align="center"> <th style="width: 30%;">Nama Perangkat</th> <th style="width: 26%;">Deskripsi Kerusakan</th> <th style="width: 24%;">PC-</th> <?php if ($userLevel == "admin") { }else{ ?> <th style="width: 20%;">Aksi</th> <?php } ?> </tr> <?php $i=0; foreach ($troubleList as $val) : $i++; ?> <tr> <!--<td align="center" style="width: 5%;"><?php echo $i; ?></td>--> <td><?= $val->wares_name; ?></td> <td><?= $val->description; ?></td> <td align="center">PC-<?= $val->pc; ?></td> <?php if ($userLevel == "admin") { }else{ ?> <td class="d-flex justify-content-center" style="border: none;"> <div> <a class="btn btn-primary btn-sm mr-2" href="<?= base_url('admin_kelolalab/lab_info');?>?name=<?= $val->wares_name; ?>&desc=<?= $val->description; ?>&pc=<?= $val->pc; ?>&id=<?= $val->lab_id; ?>&thingID=<?= $val->things_id; ?>" role="button"> <i class="fa fa-edit" style="font-size: 10pt;"></i> <!--<button type="submit" class="btn btn-primary border btn-sm m-1"> <i class="fa fa-edit"></i> </button>--> </a> </div> <div> <!--form delete--> <form action="<?php echo base_url('admin_kelolalab/hapus_kerusakan')?>" method="post"> <div class="hide-form"> <input readonly type="text" class="btn btn-tersier" name="tId" value="<?= $val->things_id;?>"> <input readonly type="text" class="btn btn-tersier" name="labId" value="<?= $val->lab_id;?>"> </div> <button type="submit" class="btn btn-danger border btn-sm del_alert"> <i class="fa fa-trash"></i> </button> </form> </div> </td> <?php } ?> </tr> <?php endforeach; ?> </table> </div> </div> </div> </div> <?php } ?> <!-- AddAslab Modal --> <form action="<?= base_url('admin_kelolapengguna/addUserbyKoordi') ?>" method="post"> <div class="modal" id="modalTambahPengguna"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Tambah Asisten Lab.</h4> </div> <!-- Modal body --> <div class="modal-body"> <table style="width: 100%;"> <tr> <td> <small>Nama</small><br> <input type="text" name="nama" placeholder="" class="form-control form-control-sm" required> </td> </tr> <tr hidden> <td> <small>Status</small><br> <input type="text" name="status" value="Asisten Laboratorium" class="form-control form-control-sm" readonly> </td> </tr> <tr> <td> <small>Posisi</small><br> <small>lab_id</small> <input type="text" class="form-control form-control-sm" name="lab" value="<?php echo $lab->lab_id; ?>" readonly> <small>lab_name</small> <input type="text" class="form-control form-control-sm" name="labName" value="<?php echo $lab->lab_name; ?>" readonly> <small>totalAslab (max. 2)</small> <input type="text" class="form-control form-control-sm" name="maxAslab" value="<?php echo $maxAslab->maxAslab; ?>" readonly> </td> </tr> <tr> <td> <small>Email</small><br> <input type="email" name="email" class="form-control form-control-sm" required> </td> </tr> <tr> <td> <small>Kontak</small><br> <input type="text" name="kontak" placeholder="" class="form-control form-control-sm" required> </td> </tr> <tr> <td> <small>Username</small><br> <input type="text" name="username" placeholder="" class="form-control form-control-sm" required> </td> </tr> <tr> <td> <small>Password</small><br> <input type="text" name="password" placeholder="" class="form-control form-control-sm" required> </td> </tr> <tr><td></td></tr> </table> </div> <!-- Modal footer --> <div class="modal-footer"> <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal" onclick="hideModalTambahPengguna()">Batal</button> <button type="submit" class="btn btn-success btn-sm">Simpan</button> </div> </div> </div> </div> </form> <!-- Wares problem Modal --> <?php echo form_open_multipart('admin_kelolalab/addTrouble'); ?> <div class="modal" id="modalKerusakan"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Tambah Kerusakan</h4> </div> <!-- Modal body --> <div class="modal-body"> <table style="width: 100%;"> <tr> <td> <small>Nama Perangkat</small> <input type="text" name="nama" placeholder="" class="form-control form-control-sm" required> </td> </tr> <tr> <td> <small>Deskripsi</small> <textarea name="deskripsi" class="form-control form-control-sm" rows="3" required></textarea> </td> </tr> <tr> <td> <small>PC</small> <input type="number" max="<?php echo $lab->capacity ?>" min="0" name="pc" placeholder="" class="form-control form-control-sm" required> </td> </tr> <tr class="hide-form"> <td> <input type="text" name="labId" placeholder="" class="form-control form-control-sm" value="<?php echo $lab->lab_id; ?>" readonly> </td> </tr> </table> </div> <!-- Modal footer --> <div class="modal-footer"> <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal" onclick="hideModalKerusakan()">Batal</button> <button type="submit" class="btn btn-success btn-sm">Simpan</button> </div> </div> </div> </div> <?php echo form_close(); ?> <!-- Edit wares problem Modal --> <?php if (isset($_GET['name']) && isset($_GET['desc']) && isset($_GET['pc']) && isset($_GET['id']) && isset($_GET['thingID'])) { echo form_open_multipart('admin_kelolalab/editTrouble'); ?> <div class="modal fade" id="modalEdit"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Edit Daftar Kerusakan</h4> </div> <!-- Modal body --> <div class="modal-body"> <table style="width: 100%;"> <tr> <td> <small>Nama Perangkat</small> <input type="text" name="nama" value="<?=$_GET['name'];?>" class="form-control form-control-sm" required> </td> </tr> <tr> <td> <small>Deskripsi</small> <textarea type="text" name="deskripsi" class="form-control form-control-sm" rows="3" required><?=$_GET['desc'];?></textarea> </td> </tr> <tr> <td> <small>PC</small> <input type="number" max="<?php echo $lab->capacity ?>" min="0" name="pc" value="<?=$_GET['pc'];?>" placeholder="" class="form-control form-control-sm" required> </td> </tr> <tr class="hide-form"> <td> <input type="text" name="labId" placeholder="" class="form-control form-control-sm" value="<?= $_GET['id']; ?>" readonly> <input type="text" name="tId" placeholder="" class="form-control form-control-sm" value="<?= $_GET['thingID']; ?>" readonly> </td> </tr> </table> </div> <!-- Modal footer --> <div class="modal-footer"> <button type="button" class="btn btn-danger btn-sm"> <a href="<?php echo base_url('admin_kelolalab/lab_info?id='.$lab->lab_id) ?>" style="text-decoration: none; color: white;"> Batal </a> </button> <button type="submit" class="btn btn-success btn-sm">Simpan</button> </div> </div> </div> </div> <?php echo form_close(); } ?> <script language="JavaScript" type="text/javascript"> //USER DELETE ALERT $(document).ready(function(){ $("button.del_alert").click(function(e){ if(!confirm('Anda akan menghapus data')){ e.preventDefault(); return false; }return true; }); }); function hideModalKerusakan(){ document.getElementById('modalKerusakan').style.display='none'; $('button').click(function(){ $('input[type="email"]').val(' '); $('input[type="text"]').val(' '); $('input[type="number"]').val(' '); }); } function hideModalTambahPengguna(){ document.getElementById('modalKerusakan').style.display='none'; $('button').click(function(){ $('input[type="email"]').val(' '); $('input[type="text"]').val(' '); $('input[type="number"]').val(' '); }); } function searchTable() { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("input"); filter = input.value.toUpperCase(); table = document.getElementById("sortTable"); tr = table.getElementsByTagName("tr"); for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } (function ($){ $(window).on('load',function(){ $('#modalEdit').modal('show'); }); })( jQuery ); </script> </body> </html><file_sep>/application/models/Db_labkom.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Db_labkom extends CI_Model{ function __construct(){ $this->wares_ts = 'wares_ts'; } public function get_auth($uname,$pass){ $query = $this->db->query("select * from active_user where username = '$uname' or password = '$pass'"); return $query->result_array(); //return $this->db->get('user')->result_array(); } //KELOLA PENGGUNA public function newUserbyAdmin($nama,$aslab,$status,$email,$kontak,$username,$password){ $cekMaxPosition = $this->db->query("SELECT COUNT(A.lab_id) as jmlAslab FROM user_detail AS A INNER JOIN user AS B ON A.u_id = B.u_id INNER JOIN laboratory AS C ON A.lab_id = C.lab_id WHERE B.level = '$status' AND C.lab_id = '$aslab' AND B.u_status = '1'"); $value = $cekMaxPosition->row()->jmlAslab; if ($status == "Koordinator Laboratorium") { if ($value < 1) { $query_newUser = $this->db->query("insert into user set username = '$username', password = <PASSWORD>', level = '$status'"); if ($query_newUser) { $query_newUserdetail = $this->db->query("insert into user_detail set lab_id = '$aslab', name='$nama', email = '$email', cp = '$kontak'"); if ($query_newUserdetail) { redirect(base_url('admin_kelolapengguna?warn=success&labId=&get_valueKoordi='.$value)); }else{ redirect(base_url('admin_kelolapengguna?warn=failed&labId=')); } } }else{ redirect(base_url('admin_kelolapengguna?warn=maxKoordi&labId=')); } }elseif ($status == "Asisten Laboratorium") { if ($value < 2) { $query_newUser = $this->db->query("insert into user set username = '$username', password = <PASSWORD>', level = '$status'"); if ($query_newUser) { $query_newUserdetail = $this->db->query("insert into user_detail set lab_id = '$aslab', name='$nama', email = '$email', cp = '$kontak'"); if ($query_newUserdetail) { redirect(base_url('admin_kelolapengguna?warn=success&labId=&get_valueAslab='.$value)); }else{ redirect(base_url('admin_kelolapengguna?warn=failed&labId=')); } } }else{ redirect(base_url('admin_kelolapengguna?warn=maxAslab&labId=')); } }else{ } } public function newUserbyKoordi($nama,$aslab,$status,$email,$kontak,$username,$password,$maxAslab,$labId){ if ($maxAslab < 2 ) { $query_newUser = $this->db->query("insert into user set username = '$username', password = <PASSWORD>', level = '$status'"); if ($query_newUser) { $query_newUserdetail = $this->db->query("insert into user_detail set lab_id = '$aslab', name='$nama', email = '$email', cp = '$kontak'"); if ($query_newUserdetail) { redirect(base_url('admin_kelolalab/lab_info?warn=success&id=').$labId.'&lab='.$aslab); }else{ redirect(base_url('admin_kelolalab/lab_info?warn=failed&id=').$labId.'&lab='.$aslab); } } }else{ redirect(base_url('admin_kelolalab/lab_info?warn=aslabfull&id=').$labId.'&lab='.$aslab); } } public function maxAslab($labId){ $query_maxAslab = $this->db->query("SELECT COUNT(lab_id) AS maxAslab FROM user_detail AS A INNER JOIN user AS B ON A.u_id = B.u_id WHERE lab_id = '$labId' AND B.`level` = 'Asisten Laboratorium' AND B.u_status = '1'"); return $query_maxAslab; } public function maxAslabInAdmin(){ $query_maxAslab = $this->db->query("SELECT COUNT(lab_id) AS maxAslabInAdmin FROM user_detail AS A INNER JOIN user AS B ON A.u_id = B.u_id WHERE B.`level` = 'Asisten Laboratorium' AND B.u_status = '1'"); return $query_maxAslab; } public function editUser($nama,$aslab,$status,$email,$kontak,$username,$u_id,$password, $labId){ $query_modUser = $this->db->query("update user set username = '$username', password='<PASSWORD>', level = '$status' where u_id = '$u_id'"); if ($query_modUser) { $query_modUserdetail = $this->db->query("update user_detail set lab_id = '$aslab', name='$nama', email = '$email', cp = '$kontak' where u_id = '$u_id'"); if ($query_modUser && $query_modUserdetail) { redirect(base_url('admin_kelolapengguna?warn=updsuccess&labId='.$labId.'&id='.$username.'&lab='.$aslab)); }else{ redirect(base_url('admin_kelolapengguna?warn=updfailed&labId='.$labId.'&id='.$username.'&lab='.$aslab)); } } } public function deleteUser($u_id, $labId){ if (!empty($labId)) { $remove_user = $this->db->query("DELETE A,B from user as A inner join user_detail as B on A.u_id = B.u_id where A.u_id = '$u_id'"); if ($remove_user) { redirect(base_url('admin_kelolapengguna?warn=del_success&labId='.$labId)); } }else{ $remove_user = $this->db->query("DELETE A,B from user as A inner join user_detail as B on A.u_id = B.u_id where A.u_id = '$u_id'"); if ($remove_user) { redirect(base_url('admin_kelolapengguna?warn=del_success&labId=')); } } } public function updateUserStatusActive($id, $stat, $labId, $level){ $get_maxAslab = $this->db->query("SELECT COUNT(lab_id) AS maxAslabInAdmin FROM user_detail AS A INNER JOIN user AS B ON A.u_id = B.u_id WHERE B.`level` = '$level' AND B.u_status = '1' AND A.lab_id = '$labId'"); $value = $get_maxAslab->row()->maxAslabInAdmin; if ($level == "Asisten Laboratorium") { if ($value < 2) { $update = $this->db->query("update user set u_status = '$stat' where u_id = '$id'"); redirect(base_url('admin_kelolapengguna?labId=0&user='.$id.'&warn=active')); }else{ redirect(base_url('admin_kelolapengguna?labId=0&user='.$id.'&warn=updStatFailed')); } }elseif ($level == "Koordinator Laboratorium"){ if ($value < 1) { $update = $this->db->query("update user set u_status = '$stat' where u_id = '$id'"); redirect(base_url('admin_kelolapengguna?labId=0&user='.$id.'&warn=active')); }else{ redirect(base_url('admin_kelolapengguna?labId=0&user='.$id.'&warn=updStatKoordiFailed')); } } } public function updateUserStatusFailed($id, $stat, $labId, $level){ $update = $this->db->query("update user set u_status = '$stat' where u_id = '$id'"); } public function updateLabStatus($id, $stat){ $update = $this->db->query("update laboratory set lab_status = '$stat' where lab_id = '$id'"); } public function showUser($labId){ if (!empty($labId)) { $query = $this->db->query("SELECT B.name, A.lab_name, A.lab_id, B.email, B.cp, C.username, C.password, C.level, B.u_id, C.u_status FROM `laboratory` AS A INNER JOIN `user_detail` AS B ON A.lab_id = B.lab_id INNER JOIN `user` AS C ON B.u_id = C.u_id WHERE A.lab_id = '$labId' AND C.level = 'Asisten Laboratorium' AND C.u_status = '1' ORDER BY B.name asc "); return $query; }else{ return $this->db->get('show_user'); } //$query_showUser = $this->db->query("select * FROM show_user"); } public function selectUser($getUser){ $query = $this->db->query("select u_id from user where username = '$getUser'"); return $query; } public function filterUser($filter){ if ($filter == "KoordinatorLaboratorium") { $query_showUser = $this->db->query("select * FROM show_user where level = 'Koordinator Laboratorium'"); }else{ $query_showUser = $this->db->query("select * FROM show_user where level = 'Asisten Laboratorium' order by u_status desc"); } return $query_showUser; } public function filterUserLab($filter){ $query_showUser = $this->db->query("select * FROM show_user where lab_id = '$filter'"); return $query_showUser; } public function addLab($labName, $capacity){ $query = $this->db->query("insert into laboratory set lab_name = '$labName', capacity = '$capacity'"); if ($query) { redirect(base_url('admin_kelolalab?warn=success')); }else{ redirect(base_url('admin_kelolalab?warn=failed')); } } public function editLab($labName, $capacity, $labId){ $query = $this->db->query("update laboratory set lab_name = '$labName', capacity = '$capacity' where lab_id = '$labId'"); if ($query) { redirect(base_url('admin_kelolalab?warn=updsuccess')); }else{ redirect(base_url('admin_kelolalab?warn=updfailed')); } } public function takeLabID($name){ $query = $this->db->query("select A.lab_id as labId from laboratory as A inner join user_detail as B on A.lab_id = B.lab_id inner join user AS C on B.u_id = C.u_id where C.username = '$name'"); return $query->num_rows()->labId; } public function showLab($name){ if (!empty($name)) { $query = $this->db->query("select * from laboratory as A inner join user_detail as B on A.lab_id = B.lab_id inner join user AS C on B.u_id = C.u_id where C.username = '$name'"); return $query; }else{ return $this->db->get('laboratory'); } } public function optionLab(){ return $this->db->get('laboratory'); } /*public function countAslab($labId){ $query = $this->db->query(" SELECT COUNT(A.lab_id) AS maxAslab FROM user_detail AS A INNER JOIN user AS B ON A.u_id = B.u_id WHERE A.lab_id = '$labId' AND B.level = 'Asisten Laboratorium' "); return $query; }*/ public function Laboratorium($lab){ $query = $this->db->query("select * from laboratory where lab_id = '$lab'"); return $query; } public function showALab($lab){ //koordi if (!empty($lab)) { $query_showLab = $this->db->query("select * from laboratory as A inner join user_detail as B on A.lab_id = B.lab_id inner join user AS C on B.u_id = C.u_id where A.lab_id = '$lab' AND C.level = 'Koordinator Laboratorium'"); return $query_showLab; }else{ $query = $this->db->query("select * from laboratory as A inner join user_detail as B on A.lab_id = B.lab_id inner join user as C on B.u_id = C.u_id where C.level = 'Koordinator Laboratorium'"); return $query; } } public function koordiLabInfo($lab){ $query = $this->db->query("select B.name as koordinator from laboratory as A inner join user_detail as B on A.lab_id = B.lab_id inner join user AS C on B.u_id = C.u_id where A.lab_id = '$lab' AND C.level = 'Koordinator Laboratorium' AND C.u_status = '1'"); if ($query->num_rows()>0) { return $query->row()->koordinator; }else{ return ' '; } } public function active_aslab($lab){ $query = $this->db->query("SELECT * from user_detail as A INNER JOIN user AS B ON A.u_id = B.u_id WHERE A.lab_id = '$lab' AND B.level = 'Asisten Laboratorium' AND B.u_status = '1' limit 2"); return $query; } public function showAslab($lab){ //aslab $query = $this->db->query("SELECT * from user_detail as A INNER JOIN user AS B ON A.u_id = B.u_id WHERE A.lab_id = '$lab' AND B.level = 'Asisten Laboratorium'"); return $query; } public function take_Aslab($labId){ $query = $this->db->query("SELECT B.name, A.lab_name, B.email, B.cp, C.username, C.password, C.level, B.u_id FROM `laboratory` AS A INNER JOIN `user_detail` AS B ON A.lab_id = B.lab_id INNER JOIN `user` AS C ON B.u_id = C.u_id WHERE A.lab_id = '1' AND C.level = 'Asisten Laboratorium' ORDER BY B.name asc "); return $query; } public function take_id($get_id, $labId){ if (!empty($labId)) { $query = $this->db->query("select * from show_user where u_id = '$get_id' and lab_id = '$labId'"); return $query; }else{ $query = $this->db->query("select * from show_user where u_id = '$get_id'"); return $query; } } public function showLab_Things($lab){ //MUNGKIN NDA JADI PAKE $query = $this->db->query("select * from laboratory_things where lab_id = '$lab'"); return $query; } public function admin_kelolalabEditPage($lab){ $query = $this->db->query("select * from laboratory where lab_id = '$lab'"); return $query; } public function addTrouble($nameTrouble, $desc, $pc, $labId){ $query = $this->db->query("insert into laboratory_things set lab_id = '$labId', wares_name = '$nameTrouble', description = '$desc', pc = '$pc'"); //BACA INSERT pc = 'PC-$pc' if ($query) { redirect(base_url('admin_kelolalab/lab_Info?warn=success&id=').$labId); }else{ redirect(base_url('admin_kelolalab/lab_Info?warn=failed&id=').$labId); } } public function editTrouble($nameTrouble, $desc, $pc, $labId, $id){ $query = $this->db->query("update laboratory_things set lab_id = '$labId', wares_name = '$nameTrouble', description = '$desc', pc = '$pc' where lab_id = '$labId' and things_id = '$id'"); //BACA INSERT pc = 'PC-$pc' if ($query) { redirect(base_url('admin_kelolalab/lab_Info?warn=updsuccess&id=').$labId.'&tID='.$id); }else{ redirect(base_url('admin_kelolalab/lab_Info?warn=updfailed&id=').$labId.'&tID='.$id); } } public function removeTrouble($id, $labId){ $query = $this->db->query("delete from laboratory_things where things_id = '$id'"); if ($query) { redirect(base_url('admin_kelolalab/lab_Info?warn=delsuccess'.'&id='.$labId)); }else{ redirect(base_url('admin_kelolalab/lab_Info?warn=delfailed'.'&id='.$labId)); } } public function countTrouble($labId){ $query = $this->db->query("SELECT * FROM laboratory_things WHERE lab_id = '$labId' group by pc"); return $query->num_rows(); //TAKE sumTrouble to COUNTtROUBLE VARIABLE } public function countPC($labId){ $query = $this->db->query("SELECT COUNT(pc) AS sumPC FROM laboratory_things WHERE lab_id = '$labId'"); return $query; } //KELOLA PERANGKAT public function newHw($nama, $jp, $icon){ $query = $this->db->query("insert into wares set w_name = '$nama', w_kind = '$jp', w_icon = '$icon'"); if ($query) { redirect(base_url('kelolaperangkat/hardware?warn=success')); } else{ redirect(base_url('kelolaperangkat/hardware?warn=failed')); } } public function showHw(){ $query = $this->db->query("select * from wares where w_kind = 'Hardware' order by w_name asc"); return $query; } public function deleteHw($id,$url){ $query1 = $this->db->query("DELETE A, B from wares as A inner join wares_ts as B on A.w_id = B.w_id where A.w_id = '$id'"); $query2 = $this->db->query("DELETE from wares where w_id = '$id'"); if ($query1 && $query2) { unlink($url); redirect(base_url('kelolaperangkat/hardware?warn=delsuccess')); } } public function updateHw($id,$nama,$jp,$icon,$url){ if ($icon == '') { $query = $this->db->query("update wares set w_name = '$nama', w_kind = '$jp' where w_id = '$id'"); if ($query) { redirect(base_url('kelolaperangkat/hardware?warn=updsuccess')); } }else{ $query = $this->db->query("update wares set w_name = '$nama', w_kind = '$jp', w_icon = '$icon' where w_id = '$id'"); if ($query) { unlink($url); redirect(base_url('kelolaperangkat/hardware?warn=updsuccess')); } } } public function take_Hwid($get_id){ $query = $this->db->query("select * from wares where w_id = '$get_id'"); return $query; } //TROUBLESHOOTING PERANGKAT public function take_ware_ts($get_id, $get_user){ //PASSING USERDATA DISINI if ($get_user == 'admin' || $get_user == '1') { $query = $this->db->query("select * from wares as A inner join wares_ts as B on A.w_id = B.w_id inner join user as C on B.upd_by = C.u_id inner join user_detail as D on C.u_id = D.u_id where A.w_id = '$get_id' order by B.status asc"); }else{ $query = $this->db->query("select * from wares as A inner join wares_ts as B on A.w_id = B.w_id inner join user as C on B.upd_by = C.u_id inner join user_detail as D on C.u_id = D.u_id where A.w_id = '$get_id' and B.status = '1'"); } return $query; } public function take_a_ware($get_id){ $query = $this->db->query("select * from wares where w_id = '$get_id'"); return $query; } public function updateStat2($stat,$get_tsId){ $update = $this->db->query("update wares_ts set status = '$stat' where ts_id = '$get_tsId'"); //$base_url = base_url('kelolaperangkat/ts_data?id='.$get_wId.'&user='.$get_user); } //TROUBLESHOOTING HARDWARE public function new_ts_data($masalah,$id_perangkat,$id_user,$deskripsi,$solusi,$linkVid,$date){ $query_ts = $this->db->query("insert into wares_ts set w_id = '$id_perangkat', title = '$masalah', detail = '$deskripsi', solving = '$solusi', video = '$linkVid', upd_by = '$id_user', upd_date = '$date'"); $base_url = base_url("kelolaperangkat/ts_data?warn=success&id=".$id_perangkat."&user=".$id_user); if ($query_ts) { redirect($base_url); }else{ redirect(base_url('kelolaperangkat/ts_data?warn=failed&id='.$id_perangkat."&user=".$id_user)); } } //insertdata array public function insert_ts_hw($data = array()){ if (!empty($data)) { $insert = $this->db->insert($this->wares_ts, $data); return $insert?$this->db->insert_id():false; } return false; } public function take_dataTs($get_id){ $query = $this->db->query("select * from wares as A inner join wares_ts as B on A.w_id = B.w_id inner join user as C on B.upd_by = C.u_id inner join user_detail as D on C.u_id = D.u_id where B.ts_id = '$get_id'"); return $query; } public function update_ts_data($masalah,$id_ts,$id_user,$id_perangkat,$deskripsi,$solusi,$linkVid,$date){ //$youTube = "https://www.youtube.com/embed/"; //$key = $youTube.$linkVid; $update_ts = $this->db->query("update wares_ts set title = '$masalah', detail = '$deskripsi', solving = '$solusi', video = '$linkVid', upd_by = '$id_user', upd_date = '$date' where ts_id = '$id_ts'"); $base_url = base_url("kelolaperangkat/ts_data?warn=updsuccess&id=".$id_perangkat."&user=".$id_user); if ($update_ts) { redirect($base_url); }else{ redirect(base_url('kelolaperangkat/ts_data?warn=failed')); } } public function remove_ts_data($ts_id, $id_ware, $get_user){ $query = $this->db->query("delete from wares_ts where ts_id = '$ts_id'"); if ($query) { redirect(base_url('kelolaperangkat/ts_data?warn=delsuccess&id=').$id_ware."&user=".$get_user); } } //SOFTWARE public function showSw(){ $query = $this->db->query("select * from wares where w_kind = 'Software' order by w_name asc"); return $query; } public function newSw($nama, $jp, $icon){ $query = $this->db->query("insert into wares set w_name = '$nama', w_kind = '$jp', w_icon = '$icon'"); if ($query) { redirect(base_url('kelolaperangkat/software?warn=success')); } else{ redirect(base_url('kelolaperangkat/software?warn=failed')); } } public function deleteSw($id,$url){ $query1 = $this->db->query("DELETE A, B from wares as A inner join wares_ts as B on A.w_id = B.w_id where A.w_id = '$id'"); $query2 = $this->db->query("DELETE from wares where w_id = '$id'"); if ($query1 && $query2) { unlink($url); redirect(base_url('kelolaperangkat/software?warn=delsuccess')); } } public function updateSw($id,$nama,$jp,$icon,$url){ if ($icon == '') { $query = $this->db->query("update wares set w_name = '$nama', w_kind = '$jp' where w_id = '$id'"); if ($query) { redirect(base_url('kelolaperangkat/software?warn=updsuccess')); } }else{ $query = $this->db->query("update wares set w_name = '$nama', w_kind = '$jp', w_icon = '$icon' where w_id = '$id'"); if ($query) { unlink($url); redirect(base_url('kelolaperangkat/software?warn=updsuccess')); } } } public function take_Swid($get_id){ $query = $this->db->query("select * from wares where w_id = '$get_id'"); return $query; } //MODEL FOR ANDROID public function daftar_perangkat($type){ $query = $this->db->query("select * from wares where w_kind = '$type' order by w_name asc"); return $query; } public function daftar_solusi($wId){ $query = $this->db->query("select * from wares_ts where w_id = '$wId' and status = '1'"); return $query; } public function tableWare($wId){ $query = $this->db->query("select w_name, w_kind, w_icon from wares where w_id = '$wId'"); return $query; } public function solusi($tsId){ $query = $this->db->query("select * from wares_ts where ts_id = '$tsId'"); return $query; } public function cariSolusi($kata){ $query = $this->db->query("select title, ts_id from wares_ts where title like '%$kata%' order by title asc"); return $query; //redirect(base_url('Android_controller?msg='.$kata)); } public function countHasilSolusi($kata){ $query = $this->db->query("select count(title) as countResult from wares_ts where title like '%$kata%' order by title asc"); if ($query->num_rows() > 0) { return $query->row()->countResult; }else{ return 0; } } } ?><file_sep>/application/views/android_view/android_solusi.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Solusi</title> <!-- Bootstrap CSS CDN --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Our Custom CSS --> <link rel="stylesheet" type="text/css" href="<?= base_url(); ?>assets/css/style.css"> <!-- Scrollbar Custom CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css"> <!-- Font Awesome JS --> <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js" integrity="<KEY>" crossorigin="anonymous"></script> <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="<KEY>" crossorigin="anonymous"></script> </head> <body class="bg-light"> <div class="wrapper"> <!-- Sidebar --> <nav id="sidebar"> <div id="dismiss"> <i class="fas fa-arrow-left"></i> </div> <div class="sidebar-header"> <a href="<?php echo base_url(); ?>Android_controller" class="navbar-brand"><img src="<?php echo base_url();?>images/dlsubig.png" class="dlsu"> <span style="color: white;">Troubleshooting<br><small>Perangkat Komputer</small></span> </a> </div> <ul class="list-unstyled components"> <li> <a href="<?php echo base_url('Android_controller'); ?>">Beranda</a> </li> <li> <a href="<?php echo base_url('Android_controller/list_perangkat?w=Hardware'); ?>">Perangkat Keras</a> </li> <li> <a href="<?php echo base_url('Android_controller/list_perangkat?w=Software'); ?>">Perangkat Lunak</a> </li> <hr> <li> <a href="<?php echo base_url('Android_controller/login'); ?>">Login</a> </li> </ul> <!--<ul class="list-unstyled CTAs"> <li> <a href="https://bootstrapious.com/tutorial/files/sidebar.zip" class="download">Download source</a> </li> <li> <a href="https://bootstrapious.com/p/bootstrap-sidebar" class="article">Back to article</a> </li> </ul>--> </nav> <!-- Konten --> <div id="content"> <div class="border bg-light shadow rounded d-flex justify-content-begin billStickTop"> <div class="col-1" style="z-index: 299;"> <button type="button" id="sidebarCollapse" class="btn btn-default"> <i class="fas fa-bars" style="color: #7C7C7D;"></i> </button> </div> <div class="col-11" style="color: #7C7C7D; overflow: hidden;"> <button class="btn btn-default" disabled> <b style="text-transform: uppercase;"><?php echo $this->bbcode->parse($solusi->title); ?></b> </button> </div> </div> <div class="bg-white mt-3 p-3 shadow"> <h4><b>Penjelasan</b></h4><hr> <?php echo $this->bbcode->parse($solusi->detail); ?> </div> <div class="bg-white mt-2 p-3 shadow" style="overflow: hidden;"> <h4><b>Langkah Penyelesaian</b></h4><hr> <?php echo $this->bbcode->parse($solusi->solving); ?> <!--Modal preview gambar--> <div id="modalImgPreview" class="modalImg"> <span class="closeImgPrev">&times;</span> <img class="ImgContent" id="img01"> </div> <?php if (!empty($solusi->video)) { ?> <div class="p-2"><small><b>Video</b><br></small> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src="<?php echo $solusi->video ?>" allowfullscreen></iframe> </div> <hr> <!--UKURAN VIDEO COBA LIA ULANG--> </div> <?php } ?> </div> </div> </div> <div class="overlay"></div> <!-- jQuery CDN - Slim version (=without AJAX) --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- Popper.JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- Bootstrap JS --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- jQuery Custom Scroller CDN --> <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#sidebar").mCustomScrollbar({ theme: "minimal" }); $('#dismiss, .overlay').on('click', function () { $('#sidebar').removeClass('active'); $('.overlay').removeClass('active'); }); $('#sidebarCollapse').on('click', function () { $('#sidebar').addClass('active'); $('.overlay').addClass('active'); $('.collapse.in').toggleClass('in'); $('a[aria-expanded=true]').attr('aria-expanded', 'false'); }); }); //IMAGE PREVIEW // Get the modal var modal = document.getElementById("modalImgPreview"); // Get the <span> element that closes the modal var span = document.getElementsByClassName("closeImgPrev")[0]; // Get the image and insert it inside the modal - use its "alt" text as a caption var img = document.getElementById("imgPreview"); var modalImg = document.getElementById("img01"); //var captionText = document.getElementById("caption"); if (img != null) { img.onclick = function(){ span.style.display = "block"; modal.style.display = "block"; modalImg.src = this.src; //captionText.innerHTML = this.alt; }; } // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; }; </script> </body> </html><file_sep>/application/views/kelola_ts_edit.php <?php $currentUser = $this->session->userdata('level'); ?> <div class="container mt-2"> <div class="d-flex flex-column p-3 bg-white text-black border rounded"> <div class="container mt-3 border-btm"> <div class="d-flex justify-content-beetwen row"> <div class="col-sm-12 col-md-5 col-lg-5"> <div><h3>Edit Daftar Masalah <small>(<?= $data_ts->w_name; ?>)</small></h3></div> </div> <div class="col-sm-12 col-md-7 col-lg-7" style="text-align: right;"> <?php if ($a_ware->w_kind == "Hardware") { //pisah nav link softawre hardware if ($currentUser == "admin" || $currentUser == "Koordinator Laboratorium") { ?> <a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <a href="<?= base_url('kelolaperangkat'); ?>">Kelola Perangkat</a> > <a href="<?= base_url('kelolaperangkat/hardware'); ?>">Kelola Perangkat Keras</a> > <a href="<?= base_url('kelolaperangkat/ts_data');?>?id=<?= $data_ts->w_id; ?>&user=<?= $this->session->userdata('nama'); ?>">Daftar Masalah</a> > <b> Edit Daftar Masalah</b> <?php }else{ ?> <a href="<?= base_url('kelolaperangkat'); ?>">Kelola Perangkat</a> > <a href="<?= base_url('kelolaperangkat/hardware'); ?>">Kelola Perangkat Keras</a> > <a href="<?= base_url('kelolaperangkat/ts_data');?>?id=<?= $data_ts->w_id; ?>&user=<?= $this->session->userdata('nama'); ?>">Daftar Masalah</a> > <a href="<?= base_url('kelolaperangkat/ts_data');?>?id=<?= $data_ts->w_id; ?>&user=<?= $this->session->userdata('nama'); ?>">Daftar Masalah</a> > <b> Edit Daftar Masalah</b> <?php } }elseif ($a_ware->w_kind == "Software") { if ($currentUser == "admin" || $currentUser == "Koordinator Laboratorium") { ?> <a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <a href="<?= base_url('kelolaperangkat'); ?>">Kelola Perangkat</a> > <a href="<?= base_url('kelolaperangkat/software'); ?>">Kelola Perangkat Lunak</a> > <a href="<?= base_url('kelolaperangkat/ts_data');?>?id=<?= $data_ts->w_id; ?>&user=<?= $this->session->userdata('nama'); ?>">Daftar Masalah</a> > <b> Edit Daftar Masalah</b> <?php }else{ ?> <a href="<?= base_url('kelolaperangkat'); ?>">Kelola Perangkat</a> > <a href="<?= base_url('kelolaperangkat/software'); ?>">Kelola Perangkat Lunak</a> > <a href="<?= base_url('kelolaperangkat/ts_data');?>?id=<?= $data_ts->w_id; ?>&user=<?= $this->session->userdata('nama'); ?>">Daftar Masalah</a> > <b> Edit Daftar Masalah</b> <?php } }else{ echo "no navigation"; } ?> </div> </div> </div> <form action="<?php echo base_url('kelolaperangkat/upd_ts_data')?>" method="post" id="formUploadImg" enctype="multipart/form-data"> <div class="mt-2 mb-2"> <button class="btn btn-primary btn-sm mr-2" type="submit">Simpan</button> <!--<input type="button" class="btn btn-danger btn-sm" onclick="kembali()" value="Batal">--> <a href="<?= base_url('kelolaperangkat/ts_data');?>?id=<?= $data_ts->w_id; ?>&user=<?= $data_ts->username; ?>"><input type="button" class="btn btn-danger btn-sm" value="Batal"></a> </div> <div class="collapsible rounded"> <input type="text" name="masalah" class="form-control form-control-sm" required value="<?= $data_ts->title; ?>"><br> <textarea class="form-control form-control-sm" rows="3" name="deskripsi"><?= $data_ts->detail; ?></textarea> </div> <div class="content-edit"> <div class="mb-2 p-3"> <div class="d-flex flex-column"> <div class="p-2"><small><b>Solusi</b><br></small> <textarea name="solusi" class="form-control form-control-sm" rows="5" id="txtsolusi" required><?= $data_ts->solving; ?></textarea> <small>Upload Gambar</small><input type="file" name="gbr" class="btn btn-sm" id="fimg"> </div> <?php if (!empty($data_ts->video)){ ?> <div class="p-2"><small><b>Video</b><br></small> <input type="text" name="link_vid" class="form-control form-control-sm mb-2" value="<?= $data_ts->video ?>"> <div class="embed-responsive embed-responsive-4by3" style="height: 400px;"> <iframe class="embed-responsive-item" src="<?php echo $data_ts->video ?>" allowfullscreen></iframe> </div> </div> <?php }else{ ?> <div class="p-2"><small><b>Video</b><br></small> <input type="text" name="link_vid" class="form-control form-control-sm mb-2" value="<?= $data_ts->video ?>"> </div> <?php } ?> <div class="p-2" hidden="hidden"><small><b>ID Troubleshooting</b><br></small> <input readonly type="text" name="id_troubleshooting" value="<?= $data_ts->ts_id; ?>"> </div> <div class="p-2" hidden="hidden"><small><b>User</b><br></small> <input readonly type="text" name="id_user" value="<?= $this->session->userdata('nama'); ?>"> </div> <div class="p-2" hidden="hidden"><small><b>Id Perangkat</b><br></small> <input readonly type="text" name="id_perangkat" value="<?= $data_ts->w_id; ?>"> </div> </div> </div> </div> </form> </div> </div> <script type="text/javascript"> function kembali(){ window.history.back(); } $("document").ready(function(){ $("#fimg").change(function(){ //console.log("proses upload"); var form = $('#formUploadImg')[0]; var data = new FormData(form); $.ajax({ type: "POST", encytype: 'multipart/form-data', processData: false, contentType: false, cache: false, data: data, timeout: 5000, url: "<?=base_url('kelolaperangkat/imgUpload')?>" }) .done(function(res){ var url = "<?=base_url('assets/troubleshooting_images/')?>"; var txtsolusi = $("textarea#txtsolusi").val(); $("textarea#txtsolusi").val(txtsolusi + "[img]" + url + res + "[/img]"); console.log(res); }); }); }); </script> </body> </html><file_sep>/troubleshooting .sql -- phpMyAdmin SQL Dump -- version 4.4.14 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: 09 Jan 2020 pada 05.45 -- Versi Server: 5.6.26 -- PHP Version: 5.6.12 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `troubleshooting` -- -- -------------------------------------------------------- -- -- Stand-in structure for view `active_user` -- CREATE TABLE IF NOT EXISTS `active_user` ( `u_id` int(11) ,`username` varchar(25) ,`password` varchar(20) ,`level` varchar(25) ,`u_status` tinyint(1) ); -- -------------------------------------------------------- -- -- Struktur dari tabel `laboratory` -- CREATE TABLE IF NOT EXISTS `laboratory` ( `lab_id` int(8) NOT NULL, `lab_name` varchar(40) DEFAULT NULL, `lab_status` tinyint(1) DEFAULT '1', `capacity` int(11) DEFAULT NULL ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `laboratory` -- INSERT INTO `laboratory` (`lab_id`, `lab_name`, `lab_status`, `capacity`) VALUES (1, 'Laboratoraium Multimedia', 1, 28), (2, 'Laboratorium Basis Data', 0, 40), (3, 'Laboratorium Pemrograman', 1, 34); -- -------------------------------------------------------- -- -- Struktur dari tabel `laboratory_things` -- CREATE TABLE IF NOT EXISTS `laboratory_things` ( `things_id` int(11) NOT NULL, `lab_id` int(8) DEFAULT '0', `wares_name` varchar(50) DEFAULT '0', `description` text, `pc` int(4) DEFAULT '0' ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `laboratory_things` -- INSERT INTO `laboratory_things` (`things_id`, `lab_id`, `wares_name`, `description`, `pc`) VALUES (1, 1, 'Netbeans', 'hanya ada', 22); -- -------------------------------------------------------- -- -- Stand-in structure for view `show_user` -- CREATE TABLE IF NOT EXISTS `show_user` ( `name` char(70) ,`lab_name` varchar(40) ,`lab_id` int(8) ,`email` varchar(50) ,`cp` varchar(14) ,`username` varchar(25) ,`password` varchar(20) ,`level` varchar(25) ,`u_id` int(11) ,`u_status` tinyint(1) ); -- -------------------------------------------------------- -- -- Struktur dari tabel `user` -- CREATE TABLE IF NOT EXISTS `user` ( `u_id` int(11) NOT NULL, `username` varchar(25) NOT NULL, `password` varchar(20) NOT NULL, `level` varchar(25) NOT NULL, `u_status` tinyint(1) NOT NULL DEFAULT '1' ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `user` -- INSERT INTO `user` (`u_id`, `username`, `password`, `level`, `u_status`) VALUES (1, 'admin', 'admin', 'admin', 1), (4, '16013013', '16013013', 'Asisten Laboratorium', 1), (5, 'jsanger', 'jsanger', 'Koordinator Laboratorium', 1); -- -------------------------------------------------------- -- -- Struktur dari tabel `user_detail` -- CREATE TABLE IF NOT EXISTS `user_detail` ( `u_id` int(11) NOT NULL, `lab_id` int(8) DEFAULT NULL, `name` char(70) DEFAULT NULL, `email` varchar(50) DEFAULT NULL, `cp` varchar(14) DEFAULT NULL ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `user_detail` -- INSERT INTO `user_detail` (`u_id`, `lab_id`, `name`, `email`, `cp`) VALUES (1, NULL, 'admin', NULL, NULL), (4, 1, '<NAME>', '<EMAIL>', '09090912233'), (5, 1, '<NAME>', '<EMAIL>', '081355689038'); -- -------------------------------------------------------- -- -- Struktur dari tabel `wares` -- CREATE TABLE IF NOT EXISTS `wares` ( `w_id` int(8) NOT NULL, `w_name` varchar(50) NOT NULL DEFAULT '', `w_kind` varchar(25) NOT NULL DEFAULT '', `w_icon` varchar(100) DEFAULT NULL ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `wares` -- INSERT INTO `wares` (`w_id`, `w_name`, `w_kind`, `w_icon`) VALUES (1, 'RAM', 'Hardware', 'icons8-memory-slot-96.png'), (2, 'Dreamweaver', 'Software', 'icons8-adobe-dreamweaver-144.png'), (3, 'MATLAB', 'Software', 'Matlab_Logo_(1).png'), (4, 'Microsoft Power Point', 'Software', 'icons8-microsoft-powerpoint-144.png'), (5, 'Microsoft Visio', 'Software', 'icons8-microsoft-visio-144.png'), (6, 'Microsoft Word 2019', 'Software', 'icons8-microsoft-word-144.png'), (7, 'Netbeans', 'Software', '800px-Apache_NetBeans_Logo_svg.png'), (8, 'Photoshop', 'Software', 'icons8-adobe-photoshop-144.png'), (9, 'Animate', 'Software', 'Animate-512.png'); -- -------------------------------------------------------- -- -- Struktur dari tabel `wares_ts` -- CREATE TABLE IF NOT EXISTS `wares_ts` ( `ts_id` int(8) NOT NULL, `w_id` int(8) NOT NULL DEFAULT '0', `title` varchar(100) NOT NULL DEFAULT '', `detail` text NOT NULL, `solving` text, `video` varchar(100) DEFAULT '0', `upd_by` int(11) DEFAULT NULL, `status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1 = approved | 0 = unapprove', `upd_date` date NOT NULL DEFAULT '0000-00-00' ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `wares_ts` -- INSERT INTO `wares_ts` (`ts_id`, `w_id`, `title`, `detail`, `solving`, `video`, `upd_by`, `status`, `upd_date`) VALUES (1, 1, 'tambah perangkat tes', 'tes tambah perangkat', 'tes solusi', '', 1, 1, '2019-12-05'), (4, 1, 'Bunyi [b]Beep[/b] pendek sebanyak 1 kali saat komputer dihidupkan', 'Bunyi beep pendek sebanyak 1 kali menandakan bahwa terjadi permasalahan pada DRAM komputer yaitu gagalnya refresh pada DRAM komputer. Oleh karena itu disarankan untuk mengecek apabila terjadi kerusakan pada RAM ataupun mengganti RAM dengan komponen yang baru. Berikut adalah video cara melepas RAM dari komputer.', '[b]Langkah 1:[/b][br]\r\nBuka case pada komputer dengan melepaskan sekrupnya.[br]\r\n[b]Langkah 2:[/b][br]\r\nCabut RAM dengan cara melepaskan kunci soket, lalu tarik RAM secara perlahan dari soket.[br]\r\n[b]Langkah 3:[/b][br]\r\nPeriksalah RAM tersebut apabila terdapat kerusakan seperti beberapa bagian yang mengalami kecacatan.\r\n', 'https://www.youtube.com/embed/zZhWAl9PFcw', 1, 1, '2019-12-19'); -- -------------------------------------------------------- -- -- Struktur untuk view `active_user` -- DROP TABLE IF EXISTS `active_user`; CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `active_user` AS select `user`.`u_id` AS `u_id`,`user`.`username` AS `username`,`user`.`password` AS `password`,`user`.`level` AS `level`,`user`.`u_status` AS `u_status` from `user` where (`user`.`u_status` = '1'); -- -------------------------------------------------------- -- -- Struktur untuk view `show_user` -- DROP TABLE IF EXISTS `show_user`; CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `show_user` AS select `b`.`name` AS `name`,`a`.`lab_name` AS `lab_name`,`a`.`lab_id` AS `lab_id`,`b`.`email` AS `email`,`b`.`cp` AS `cp`,`c`.`username` AS `username`,`c`.`password` AS `<PASSWORD>`,`c`.`level` AS `level`,`c`.`u_id` AS `u_id`,`c`.`u_status` AS `u_status` from ((`laboratory` `a` join `user_detail` `b` on((`a`.`lab_id` = `b`.`lab_id`))) join `user` `c` on((`b`.`u_id` = `c`.`u_id`))) order by `c`.`level` desc; -- -- Indexes for dumped tables -- -- -- Indexes for table `laboratory` -- ALTER TABLE `laboratory` ADD PRIMARY KEY (`lab_id`); -- -- Indexes for table `laboratory_things` -- ALTER TABLE `laboratory_things` ADD PRIMARY KEY (`things_id`), ADD KEY `lab_id` (`lab_id`), ADD KEY `lab_id_2` (`lab_id`); -- -- Indexes for table `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`u_id`); -- -- Indexes for table `user_detail` -- ALTER TABLE `user_detail` ADD PRIMARY KEY (`u_id`), ADD KEY `lab_id` (`lab_id`), ADD KEY `u_id` (`u_id`); -- -- Indexes for table `wares` -- ALTER TABLE `wares` ADD PRIMARY KEY (`w_id`); -- -- Indexes for table `wares_ts` -- ALTER TABLE `wares_ts` ADD PRIMARY KEY (`ts_id`), ADD KEY `upd_by` (`upd_by`), ADD KEY `w_id` (`w_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `laboratory` -- ALTER TABLE `laboratory` MODIFY `lab_id` int(8) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `laboratory_things` -- ALTER TABLE `laboratory_things` MODIFY `things_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `user` -- ALTER TABLE `user` MODIFY `u_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `user_detail` -- ALTER TABLE `user_detail` MODIFY `u_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `wares` -- ALTER TABLE `wares` MODIFY `w_id` int(8) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=10; -- -- AUTO_INCREMENT for table `wares_ts` -- ALTER TABLE `wares_ts` MODIFY `ts_id` int(8) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7; -- -- Ketidakleluasaan untuk tabel pelimpahan (Dumped Tables) -- -- -- Ketidakleluasaan untuk tabel `laboratory_things` -- ALTER TABLE `laboratory_things` ADD CONSTRAINT `laboratory_things_ibfk_1` FOREIGN KEY (`lab_id`) REFERENCES `laboratory` (`lab_id`); -- -- Ketidakleluasaan untuk tabel `user` -- ALTER TABLE `user` ADD CONSTRAINT `user_ibfk_1` FOREIGN KEY (`u_id`) REFERENCES `user_detail` (`u_id`); -- -- Ketidakleluasaan untuk tabel `user_detail` -- ALTER TABLE `user_detail` ADD CONSTRAINT `user_detail_ibfk_1` FOREIGN KEY (`lab_id`) REFERENCES `laboratory` (`lab_id`), ADD CONSTRAINT `user_detail_ibfk_2` FOREIGN KEY (`u_id`) REFERENCES `user` (`u_id`); -- -- Ketidakleluasaan untuk tabel `wares_ts` -- ALTER TABLE `wares_ts` ADD CONSTRAINT `wares_ts_ibfk_1` FOREIGN KEY (`upd_by`) REFERENCES `user_detail` (`u_id`), ADD CONSTRAINT `wares_ts_ibfk_2` FOREIGN KEY (`w_id`) REFERENCES `wares` (`w_id`); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/application/views/admin_kelolalab.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Troubleshooting Perangkat Komputer | Kelola Laboratorium</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="<?= base_url(); ?>assets/css/style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" type="text/javascript"></script> <script src="<?= base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> <script src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script> </head> <body> <?php if (isset($_GET['warn'])) { if ($_GET['warn']=="success") { echo '<script type="text/javascript">window.onload=alert("Data Laboratorium Ditambahkan!");</script>'; }elseif ($_GET['warn']=="delsuccess") { echo '<script type="text/javascript">window.onload=alert("Data Laboratorium Dihapus!");</script>'; }elseif ($_GET['warn']=="updsuccess") { echo '<script type="text/javascript">window.onload=alert("Data Laboratorium Diubah!");</script>'; } } $userLevel = $this->session->userdata("level"); ?> <nav class="navbar navbar-expand-md navbar-light bg-light sticky-top shadow mb-4"> <div class="container"> <a href="<?php echo base_url(); ?>adminberanda" class="navbar-brand"><img src="<?php echo base_url();?>images/dlsubig.png" class="dlsu"> <span>Troubleshooting<br><small>Perangkat Komputer</small></span> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"><hr></li> <li class="nav-item shadow p-2"> <a href="#" class="nav-link disabled" style="color: green;"> <b><i class="fa fa-user-circle"></i><?php echo $this->session->userdata("nama"); ?></b> </a> </li> <li class="nav-item shadow p-2"> <a href=" <?= base_url('adminberanda'); ?> " class="nav-link"><i class="fa fa-home"></i> Beranda</a> </li> <li class="nav-item shadow p-2"> <?php if ($userLevel == "admin"){ ?> <a href="<?php echo base_url('login/logout'); ?>" class="nav-link"><i class="fa fa-sign-out-alt"></i>Keluar</a> <?php }else{ ?> <a href="<?php echo base_url('login/logout_aslab'); ?>" class="nav-link"><i class="fa fa-sign-out-alt"></i>Keluar</a> <?php } ?> </li> </ul> </div> </div> </nav> <div class="container mt-2"> <div class="d-flex flex-column p-3 bg-white text-black border rounded"> <div class="container mt-3 border-btm"> <div class="d-flex justify-content-beetwen row"> <div class="col-sm-12 col-md-6 col-lg-6"> <div><h3>Kelola Laboratorium</h3></div> </div> <div class="col-sm-12 col-md-6 col-lg-6" style="text-align: right;"> <?php if ($this->session->userdata('nama') == "admin") { ?> <a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <b>Kelola Laboratorium</b> <?php }else{ } ?> </div> </div> </div> <div class="mt-2 mb-2"> <div class="d-flex justify-content-beetwen row"> <div class="col-7"> <!-- Button trigger modal --> <button class="btn btn-primary btn-sm" onclick="modal()" data-toggle="modal" data-target="#myModal"><b>+</b>Tambah Lab.</button> </div> <!-- <div class="col-5" style="text-align: right;"> <div> <input type="text" name="" class="inputbox-3 p-1" id="input" onkeyup="searchTable()" placeholder=" Cari..."> </div> </div>--> </div> </div> <div class="table table-responsive"> <table class="table table-sm table-bordered table-striped mt-2" id="sortTable"> <tr> <thead align="center"> <th>No.</th> <th>Laboratorium</th> <th>Kapasitas Lab.</th> <th>Status Laboratorium</th> <th>Aksi</th> </thead> </tr> <?php $i=1; foreach ($lab as $val) : $status = ($val->lab_status == 1)?site_url('admin_kelolalab/inactive/?lab_id='.$val->lab_id):site_url('admin_kelolalab/active/?lab_id='.$val->lab_id); ?> <tr> <td align="center"><?php echo $i++; ?></td> <td><?php echo $val->lab_name; ?></td> <td align="center"><?php echo $val->capacity; ?>-PC</td> <td align="center"> <a href="<?php echo $status; ?>" style="text-decoration: none;"> <span class="badge p-2 <?= ($val->lab_status == 1)?'badge-success':'badge-danger'; ?>" style="width: 68px; max-width: 68px;"> <?php echo ($val->lab_status == 1)?'Aktif':'Nonaktif'; ?> </span> </a><br> </td> <td class="d-flex justify-content-center" style="border: none;"> <div> <a href="<?= base_url('admin_kelolalab/edit_page');?>?idLab=<?= $val->lab_id; ?>"> <button type="submit" class="btn btn-primary btn-sm border m-1"> <i class="fa fa-edit"></i> </button> </a> </div> <div> <a href="<?= base_url('admin_kelolalab/lab_info?id=').$val->lab_id; ?>"> <button type="submit" class="btn btn-info btn-sm border m-1" style="width: 33px;"> <i class="fa fa-info"></i> </button> </a> </div> <div class="hide-form"> <!--NI FORM DELETE ADA HIDE--> <!--form delete--> <form action="<?php echo base_url('')?>" method="post"> <div class="hide-form"> <input type="text" class="btn btn-tersier" name="w_id" value="<?= $val->lab_id; ?>"> </div> <button type="submit" class="btn btn-danger border btn-sm m-1 del_alert"> <i class="fa fa-trash"></i> </button> </form> </div> </td> </tr> <?php endforeach; ?> </table> </div> </div> </div> <!-- Modal --> <?php echo form_open_multipart('admin_kelolalab/addLab'); ?> <div class="modal" id="myModal"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Tambah Laboratorium</h4> </div> <!-- Modal body --> <div class="modal-body"> <table style="width: 100%;"> <tr> <td> <small>Nama</small><br> <input type="text" name="nama" placeholder="" class="form-control form-control-sm" required> </td> </tr> <tr> <td> <small>Kapasitas</small><br> <input type="number" min="1" max="40" name="kapasitas" placeholder="" class="form-control form-control-sm" required> </td> </tr> </table> </div> <!-- Modal footer --> <div class="modal-footer"> <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal" onclick="hidemodal()">Batal</button> <button type="submit" class="btn btn-success btn-sm">Simpan</button> </div> </div> </div> </div> <?php echo form_close(); ?> <script language="JavaScript" type="text/javascript"> //USER DELETE ALERT $(document).ready(function(){ $("button.del_alert").click(function(e){ if(!confirm('Anda akan menghapus data')){ e.preventDefault(); return false; }return true; }); }); function hidemodal(){ document.getElementById('myModal').style.display='none'; $('button').click(function(){ $('input[type="email"]').val(' '); $('input[type="text"]').val(' '); $('input[type="number"]').val(' '); }); } function searchTable() { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("input"); filter = input.value.toUpperCase(); table = document.getElementById("sortTable"); tr = table.getElementsByTagName("tr"); for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } </script> </body> </html><file_sep>/application/views/kelolasoftware_edit.php <?php if (isset($_GET['warn'])) { if ($_GET['warn']=="success") { echo '<script type="text/javascript">window.onload=alert("Data Perangkat Ditambahkan!");</script>'; }elseif ($_GET['warn']=="delsuccess") { echo '<script type="text/javascript">window.onload=alert("Data Perangkat Dihapus!");</script>'; }elseif ($_GET['warn']=="updsuccess") { echo '<script type="text/javascript">window.onload=alert("Data Perangkat Diubah!");</script>'; } } ?> <div class="container mt-2"> <div class="d-flex flex-column p-3 bg-white text-black border rounded"> <div class="container mt-3 border-btm"> <div class="d-flex justify-content-beetwen row"> <div class="col-sm-12 col-md-6 col-lg-6"> <div><h3>Edit Perangkat Lunak</h3></div> </div> <div class="col-sm-12 col-md-6 col-lg-6" style="text-align: right;"> <?php if ($this->session->userdata('nama') == "admin") { ?> <a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <a href="<?= base_url('kelolaperangkat'); ?>">Kelola Perangkat</a> > <a href="<?= base_url('kelolaperangkat/software'); ?>">Kelola Perangkat Lunak</a> > <b>Edit Perangkat Lunak</b> <?php }else{ ?> <a href="<?= base_url('kelolaperangkat'); ?>">Kelola Perangkat</a> > <a href="<?= base_url('kelolaperangkat/software'); ?>">Kelola Perangkat Lunak</a> > <b>Edit Perangkat Lunak</b> <?php } ?> </div> </div> </div> <?php echo form_open_multipart('Kelolaperangkat/modSw'); ?> <div class="mt-2 mb-2"> <button class="btn btn-primary btn-sm mr-2" type="submit">Simpan</button> <a href="<?php echo base_url('Kelolaperangkat/software')?>"> <span class="btn btn-danger btn-sm">Batal</span> </a> </div> <div class="table mt-4"> <table class="table table-sm table-borderless mt-2"> <tr> <th class="w-10">Nama</th> <td><input type="text" name="editnama" value="<?= $as->w_name ?>" required class="inputbox-2"></td> <div class="hide-form"> <input type="text" name="editperangkat" class="inputbox-2" required value="Software" readonly> <input type="text" name="idperangkat" class="inputbox-2" required value="<?php echo $as->w_id; ?>" readonly> <input type="text" name="icon" class="inputbox-2" required value="<?php echo $as->w_icon; ?>" readonly> </div> </tr> <tr> <th>Icon</th> <td> <input type="file" name="icon" class="btn btn-sm"><img src="<?php echo base_url('/assets/icon/').$as->w_icon;?>" style="max-width: 32px;"> </td> </tr> </table> </div> <?php echo form_close(); ?> </div> </div> <script language="JavaScript" type="text/javascript"> //USER DELETE ALERT $(document).ready(function(){ $("button.del_alert").click(function(e){ if(!confirm('Anda akan menghapus data')){ e.preventDefault(); return false; }return true; }); }); </script> </body> </html><file_sep>/application/views/admin_kelolalab_edit.php <div class="container mt-2"> <div class="d-flex flex-column p-3 bg-white text-black border rounded"> <div class="container mt-3 border-btm"> <div class="d-flex justify-content-beetwen row"> <div class="col-sm-12 col-md-6 col-lg-6"> <div><h3>Edit Informasi Laboratorium</h3></div> </div> <div class="col-sm-12 col-md-6 col-lg-6" style="text-align: right;"> <?php if ($this->session->userdata('nama') == "admin") { ?> <a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <a href="<?= base_url('admin_kelolalab'); ?>">Kelola Laboratorium</a> > <b>Edit Informasi Laboratorium</b> <?php }else{ ?> <?php } ?> </div> </div> </div> <form action="<?php echo base_url('admin_kelolalab/editLab?labId='.$lab_detail->lab_id)?>" method="post"> <div class="mt-2 mb-2"> <button class="btn btn-primary btn-sm mr-2" type="submit">Simpan</button> <a href="<?php echo base_url('admin_kelolalab') ?>"> <span class="btn btn-danger btn-sm">Batal</span> </a> </div> <div> <small>Nama Laboratorium</small> <input type="text" name="nama" placeholder="" class="form-control form-control-sm mb-2" value="<?php echo $lab_detail->lab_name; ?>" required> <small>Kapasitas</small> <input type="number" min="1" max="40" name="kapasitas" class="form-control form-control-sm mb-2" value="<?php echo $lab_detail->capacity; ?>" required> </div> </form> </div> </div> </body> </html><file_sep>/application/views/admin_kelolapengguna.php <?php if (isset($_GET['warn'])) { if ($_GET['warn']=="success") { echo '<script type="text/javascript">window.onload=alert("Pengguna Ditambahkan!");</script>'; }elseif ($_GET['warn']=="del_success") { echo '<script type="text/javascript">window.onload=alert("Pengguna Dihapus!");</script>'; }elseif ($_GET['warn']=="updsuccess") { echo '<script type="text/javascript">window.onload=alert("Data Pengguna Diubah!");</script>'; }elseif ($_GET['warn']=="updStatFailed") { echo '<script type="text/javascript">window.onload=alert("Aktivasi asisten gagal! Laboratorium memiliki 2 asisten aktif!");</script>'; }elseif ($_GET['warn']=="updStatKoordiFailed") { echo '<script type="text/javascript">window.onload=alert("Aktivasi koordinator gagal! Laboratorium memiliki 1 Koordinator aktif!");</script>'; }elseif ($_GET['warn']=="maxKoordi") { echo '<script type="text/javascript">window.onload=alert("Gagal! Laboratorium memiliki Koordinator aktif!");</script>'; }elseif ($_GET['warn']=="maxAslab") { echo '<script type="text/javascript">window.onload=alert("Gagal! Laboratorium memiliki 2 Asisten aktif!");</script>'; } } ?> <div class="container mt-2 mb-4"> <div class="d-flex flex-column p-3 bg-white text-black border rounded"> <div class="container mt-3 border-btm"> <div class="d-flex justify-content-beetwen row"> <div class="col-sm-12 col-md-6 col-lg-6"> <?php $user = $this->session->userdata("nama"); if ($user == "admin") { ?> <h3>Daftar Pengguna</h3> <?php }else{ ?> <h3>Asisten <?php echo $lab->lab_name; ?></h3> <?php } ?> </div> <div class="col-sm-12 col-md-6 col-lg-6" style="text-align: right;"> <?php if ($this->session->userdata("nama") == "admin") { ?> <div> <a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <b>Kelola Pengguna</b> </div> <?php }else { ?> <div> <a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <a href="<?= base_url('admin_kelolalab/lab_info?id='.$lab->lab_id); ?>">Kelola Laboratorium</a> > <b>Kelola Pengguna</b> </div> <?php } ?> </div> </div> </div> <div class="mt-2 mb-2"> <div class="d-flex justify-content-beetwen row"> <?php if ($this->session->userdata("nama")=="admin") { ?> <div class="col-md-6 col-lg-6 col-sm-12"> <button class="btn btn-primary btn-sm" type="submit" onclick="showmodal()" data-toggle="modal" data-target="#myModal"><b>+</b>Tambah Pengguna</button> </div> <div class="col-md-6 col-lg-6 col-sm-12 d-flex justify-content-end" style="text-align: right;"> <div class="p-1"> <pre style="font-family: calibri;">Filter: </pre> </div> <div> <select onchange="src(this.value)" class="form-control form-control-sm"> <?php if ($filter == "KoordinatorLaboratorium" || $filter == "AsistenLaboratorium") { ?> <option selected hidden><?php echo $filter; ?></option> <?php }elseif(!empty($labName)) { ?> <option selected hidden><?php echo $labName; ?></option> <?php }else{?> <option selected hidden>Tampilkan Semua</option> <?php } ?> <option value="<?= base_url('admin_kelolapengguna?labId=');?>">Tampilkan Semua</option> <option value="<?= base_url('admin_kelolapengguna/filter_user?filter=KoordinatorLaboratorium&labId=&labName=');?>">Koordinator Laboratorium</option> <option value="<?= base_url('admin_kelolapengguna/filter_user?filter=AsistenLaboratorium&labId=&labName=');?>">Asisten Laboratorium</option> <?php foreach ($optLab as $listLab) : ?> <option value="<?= base_url('admin_kelolapengguna/filter_userLab?filter='.$listLab->lab_id.'&labId='.'&labName='.$listLab->lab_name);?>"><?php echo $listLab->lab_name; ?></option> <!--PASS VALUE LAB ID KE MODEL??--> <?php endforeach; ?> </select> </div> </div> <?php }else{ } ?> </div> </div> <?php foreach ($admin_kelolapengguna as $val) : $status = ($val->u_status == 1)?site_url('admin_kelolapengguna/unapprove/?u_id='.$val->u_id.'&labId='.$val->lab_id.'&level='.$val->level):site_url('admin_kelolapengguna/approved/?u_id='.$val->u_id.'&labId='.$val->lab_id.'&level='.$val->level); ?> <button class="collapsible rounded"> <?php echo $val->name; ?><br> <small><?php echo $val->level; ?></small> </button> <div class="content"> <div class="d-flex justify-content-between mb-2 p-3"> <div class="d-flex flex-column"> <div class="p-2 bd-highlight"><small><b>Nama</b><br></small> <?php echo $val->name ?> </div> <div class="p-2 bd-highlight"><small><b>Posisi</b><br></small> <?php echo $val->lab_name ?> </div> <div class="p-2 bd-highlight"><small><b>E-Mail</b><br></small> <?php echo $val->email ?> </div> <div class="p-2 bd-highlight"><small><b>Kontak</b><br></small> <?php echo $val->cp ?> </div> <div class="p-2 bd-highlight"><small><b>Username</b><br></small> <?php echo $val->username ?> </div> <div class="p-2 bd-highlight"><small><b>Password</b><br></small> <?php echo $val->password ?></div> </div> <div class="mt-2"> <?php if ($user != "admin") { ?> <?php }else { ?> <a href="<?php echo $status; ?>" style="text-decoration: none; z-index: 1;"> <span class="btn btn-sm mb-1 <?= ($val->u_status == 1)?'btn-success':'btn-danger'; ?>" style="width: 68px; max-width: 68px;"> <?php echo ($val->u_status == 1)?'Aktif':'Nonaktif'; ?> </span> </a><br> <?php } ?> <a href="<?php echo base_url('admin_kelolapengguna/edit_page');?>?id=<?= $val->u_id; ?>&labId=<?= $val->lab_id; ?>"> <button type="submit" class="btn btn-sw btn-sm mb-1" style="width: 67.4px;"> <i class="fa fa-edit"></i>Edit </button> </a> <!--form delete pengguna--> <?php if ($user != "admin") { ?> <!--<form action="<?php echo base_url('admin_kelolapengguna/delUser?labId='.$val->lab_id)?>" method="post">--> <?php }else{ ?> <form action="<?php echo base_url('admin_kelolapengguna/delUser?labId=')?>" method="post"> <div class="hide-form"> <input type="text" class="btn btn-tersier" name="u_id" value="<?php echo $val->u_id; ?>"> </div> <button type="submit" class="btn btn-danger btn-sm del_alert"> <i class="fa fa-trash"></i> Hapus</button> </form> <?php } ?> </div> </div> </div> <?php endforeach; ?> </div> </div> <!-- Modal Tambah Pengguna --> <form action="<?= base_url('admin_kelolapengguna/addUserbyAdmin') ?>" method="post"> <div class="modal" id="myModal"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Tambah Pengguna</h4> </div> <!-- Modal body --> <div class="modal-body"> <table style="width: 100%;"> <tr> <td> <small>Nama</small><br> <input type="text" name="nama" placeholder="" class="form-control form-control-sm" required> </td> </tr> <tr> <td> <small>Status</small><br> <select class="form-control form-control-sm" name="status"> <option selected hidden></option> <option>Koordinator Laboratorium</option> <option>Asisten Laboratorium</option> </select> </td> </tr> <tr> <td> <small>Posisi</small><br> <select class="form-control form-control-sm" name="lab"> <option selected hidden></option> <?php foreach ($optLab as $listLab) : ?> <option value="<?php echo $listLab->lab_id; ?>"><?php echo $listLab->lab_name; ?></option> <!--PASS VALUE LAB ID KE MODEL??--> <?php endforeach; ?> </select> </td> </tr> <tr> <td> <small>Email</small><br> <input type="email" name="email" class="form-control form-control-sm" required> </td> </tr> <tr> <td> <small>Kontak</small><br> <input type="text" name="kontak" placeholder="" class="form-control form-control-sm" required> </td> </tr> <tr> <td> <small>Nama Pengguna</small><br> <input type="text" name="username" placeholder="" class="form-control form-control-sm" required> </td> </tr> <tr> <td> <small><NAME>andi</small><br> <input type="text" name="password" placeholder="" class="form-control form-control-sm" required> </td> </tr> <tr><td></td></tr> </table> </div> <!-- Modal footer --> <div class="modal-footer"> <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal" onclick="hidemodal()">Batal</button> <button type="submit" class="btn btn-success btn-sm">Simpan</button> </div> </div> </div> </div> </form> <script type="text/javascript"> function src(src){ window.location = src; } function showmodal(){ } function hidemodal(){ document.getElementById('myModal').style.display='none'; $('button').click(function(){ $('input[type="email"]').val(' '); $('input[type="text"]').val(' '); }); } function cltxt(){ document.getElementById('myModal').style.display='none'; $('button').click(function(){ $('input[type="text"]').val(' '); }); } //expand|collapse data var coll = document.getElementsByClassName("collapsible"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.maxHeight){ content.style.maxHeight = null; } else { content.style.maxHeight = content.scrollHeight + "px"; } }); } //USER DELETE ALERT $(document).ready(function(){ $("button.del_alert").click(function(e){ if(!confirm('Anda akan menghapus data')){ e.preventDefault(); return false; }return true; }); }); </script> </body> </html><file_sep>/application/controllers/Android_controller.php <?php /** * */ class Android_controller extends CI_Controller { function __construct() { parent::__construct(); $this->load->library('Bbcode'); } public function index(){ $this->load->view('android_view/android_beranda'); } public function login(){ $this->load->view('android_view/android_login'); } public function list_perangkat(){ $ware_type = $_GET['w']; $data['daftar_perangkat'] = $this->Db_labkom->daftar_perangkat($ware_type)->result(); $data['jenisPerangkat'] = $this->Db_labkom->daftar_perangkat($ware_type)->row(); $this->load->view('android_view/android_daftarPerangkat', $data); } public function list_solusi(){ $ware_id = $_GET['wId']; $data['daftar_solusi'] = $this->Db_labkom->daftar_solusi($ware_id)->result(); $data['namaPerangkat'] = $this->Db_labkom->tableWare($ware_id)->row(); $this->load->view('android_view/android_daftarSolusi', $data); } public function solusi(){ $ts_id = $_GET['tsId']; $data['solusi'] = $this->Db_labkom->solusi($ts_id)->row(); $this->load->view('android_view/android_solusi', $data); } public function cari(){ $val = $this->input->post('cariSolusi'); if (!is_null($val)) { $data['searchResult'] = $this->Db_labkom->cariSolusi($val)->result(); $data['countResult'] = $this->Db_labkom->countHasilSolusi($val); $this->load->view('android_view/android_hasilCari', $data); }else{ redirect(base_url('android_controller')); } } } ?><file_sep>/application/controllers/AdminBeranda.php <?php /** * */ class AdminBeranda extends CI_Controller { function __construct() { parent::__construct(); if($this->session->userdata('level') != "admin" && $this->session->userdata('level') != "Koordinator Laboratorium"){ redirect(base_url("login?warn=loginFailed")); } } public function index(){ $name = $this->session->userdata("nama"); $data['lab'] = $this->Db_labkom->showLab($name)->row(); //$data['idLab'] = $this->Db_labkom->takeLabID($name); $this->load->view('header/header'); $this->load->view('adminberanda', $data); } } ?><file_sep>/application/views/kelolahardware.php <?php if (isset($_GET['warn'])) { if ($_GET['warn']=="success") { echo '<script type="text/javascript">window.onload=alert("Data perangkat ditambahkan!");</script>'; }elseif ($_GET['warn']=="delsuccess") { echo '<script type="text/javascript">window.onload=alert("Data Dihapus!");</script>'; }elseif ($_GET['warn']=="updsuccess") { echo '<script type="text/javascript">window.onload=alert("Data Diubah!");</script>'; } } $userLevel = $this->session->userdata('level'); ?> <div class="container mt-2"> <div class="d-flex flex-column p-3 bg-white text-black border rounded"> <div class="container mt-3 border-btm"> <div class="d-flex justify-content-beetwen row"> <div class="col-sm-12 col-md-6 col-lg-6"> <div><h3>Daftar Perangkat Keras</h3></div> </div> <div class="col-sm-12 col-md-6 col-lg-6" style="text-align: right;"> <?php if ($this->session->userdata('level') == "admin" || $this->session->userdata('level') == "Koordinator Laboratorium") { ?> <a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <a href="<?= base_url('kelolaperangkat'); ?>">Kelola Perangkat</a> > <b>Kelola Perangkat Keras</b> <?php }else{ ?> <a href="<?= base_url('kelolaperangkat'); ?>">Kelola Perangkat</a> > <b>Kelola Perangkat Keras</b> <?php } ?> </div> </div> </div> <div class="mt-2 mb-2"> <div class="d-flex justify-content-beetwen row"> <div class="col-7"> <?php if ($userLevel == "admin" || $userLevel == "Koordinator Laboratorium") { ?> <!-- Button trigger modal --> <button class="btn btn-primary btn-sm" onclick="modal()" data-toggle="modal" data-target="#myModal"><b>+</b>Tambah Perangkat Keras</button> <?php }else{ } ?> </div> <div class="col-5" style="text-align: right;"> <div> <input type="text" name="" class="inputbox-3 p-1" id="input" onkeyup="searchTable()" placeholder=" Cari..."> </div> </div> </div> </div> <div class="table"> <table class="table table-sm table-borderless table-striped mt-2" id="sortTable"> <tr> <thead style="text-align: center;"> <th>Nama Perangkat</th> <th style="width: 10%;">Aksi</th> </thead> </tr> <?php foreach ($listHw as $val) : ?> <tr> <td> <img src="<?= base_url('/assets/icon/');?><?=$val->w_icon?>" class="mr-3" style="max-width: 32px;"><?= $val->w_name ?> </td> <td class="d-flex justify-content-center"> <?php if ($this->session->userdata("level") == "admin" || $this->session->userdata("level") == "Koordinator Laboratorium") { ?> <div> <a href="<?= base_url('kelolaperangkat/page_editHw');?>?id=<?= $val->w_id; ?>"> <button type="submit" class="btn btn-primary border btn-sm m-1"> <i class="fa fa-edit"></i> </button> </a> </div> <?php }else{ } ?> <div> <a href="<?php echo base_url('kelolaperangkat/ts_data');?>?id=<?= $val->w_id; ?>&user=<?= $this->session->userdata("nama"); ?>"> <button type="submit" class="btn btn-info btn-sm border m-1" title="Lihat Informasi" style="width: 33px;"> <i class="fa fa-info"></i> </button> </a> </div> <?php if ($this->session->userdata("level") == "admin" || $this->session->userdata("level") == "Koordinator Laboratorium") { ?> <div> <!--form delete--> <form action="<?php echo base_url('Kelolaperangkat/delHw')?>" method="post"> <div class="hide-form"> <input readonly type="text" class="btn btn-tersier" name="w_id" value="<?= $val->w_id;?>"> <input readonly type="text" class="btn btn-tersier" name="w_icon" value="<?= $val->w_icon;?>"> </div> <button type="submit" class="btn btn-danger border btn-sm m-1 del_alert"> <i class="fa fa-trash"></i> </button> </form> </div> <?php }else{ } ?> </td> </tr> <?php endforeach; ?> </table> </div> </div> </div> <!-- AddThings Modal --> <?php echo form_open_multipart('Kelolaperangkat/addHw'); ?> <div class="modal" id="myModal"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Tambah Perangkat Keras</h4> </div> <!-- Modal body --> <div class="modal-body"> <table style="width: 100%;"> <tr><td> <small>Nama</small><br> <input type="text" name="nama" placeholder="" class="form-control form-control-sm" required></td></tr> <tr class="hide-form"><td> <small>Jenis Perangkat</small><br> <input type="text" name="jenis_perangkat" class="form-control form-control-sm" required value="Hardware" readonly> </td></tr> <tr><td> <small>Icon</small><br> <input type="file" name="icon" class="btn btn-sm"> </td></tr> </table> </div> <!-- Modal footer --> <div class="modal-footer"> <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal" onclick="cltxt()">Batal</button> <button type="submit" class="btn btn-success btn-sm">Simpan</button> </div> </div> </div> </div> <?php echo form_close(); ?> <script language="JavaScript" type="text/javascript"> //USER DELETE ALERT $(document).ready(function(){ $("button.del_alert").click(function(e){ if(!confirm('Anda akan menghapus data')){ e.preventDefault(); return false; }return true; }); }); function cltxt(){ document.getElementById('myModal').style.display='none'; $('button').click(function(){ $('input[type="text"]').val(' '); }); } function searchTable() { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("input"); filter = input.value.toUpperCase(); table = document.getElementById("sortTable"); tr = table.getElementsByTagName("tr"); for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } </script> </body> </html><file_sep>/application/controllers/Login.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Login extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->model('Db_labkom'); } public function index(){ $this->load->helper('url'); $this->load->view('login'); } function aksi_login(){ $username = $this->input->post('uname'); $password = $this->input->post('pass'); $getUser = $this->Db_labkom->get_auth($username,$password); $matched_id = $value['u_id']; $matched_uname = $value['username']; $matched_pass = $value['password']; $matched_level = $value['level']; foreach ($getUser as $value) { $matched_id = $value['u_id']; $matched_uname = $value['username']; $matched_pass = $value['password']; $matched_level = $value['level']; if ($username == $matched_uname && $password == $matched_pass) { if ($username == "admin" && $password == "<PASSWORD>") { $data_session = array( 'nama' => $username, 'status' => "login", 'level' => $matched_level); $this->session->set_userdata($data_session); }else{ $data_session = array( 'nama' => $username, 'status' => "login", 'level' => $matched_level); $this->session->set_userdata($data_session); } if ($matched_level == "admin") { redirect(base_url('adminberanda')); }elseif ($matched_level == "Asisten Laboratorium") { redirect(base_url('kelolaperangkat')); }elseif($matched_level == "Koordinator Laboratorium"){ redirect(base_url('adminberanda')); }else{ if ($matched_level == "Asisten Laboratorium" || $matched_level == "Koordinator Laboratorium") { redirect(base_url('Android_controller/login?warn=loginFailed')); }else{ redirect(base_url('login?warn=loginFailed')); } } }else{ if ($matched_level == "Asisten Laboratorium" || $matched_level == "Koordinator Laboratorium") { redirect(base_url('Android_controller/login?warn=loginFailed')); }else{ redirect(base_url('login?warn=loginFailed')); } } } if ($matched_level == "Asisten Laboratorium" || $matched_level == "Koordinator Laboratorium") { redirect(base_url('Android_controller/login?warn=loginFailed')); }else{ redirect(base_url('login?warn=loginFailed')); } } public function logout(){ $this->session->sess_destroy(); redirect(base_url('login')); } public function logout_aslab(){ $this->session->sess_destroy(); redirect(base_url('Android_controller/login')); } } ?><file_sep>/application/views/header/header.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0"> <title>Troubleshooting Perangkat Komputer</title> <link rel="stylesheet" type="text/css" href="<?= base_url(); ?>assets/css/style.css"> <script src="<?php echo base_url('assets/js/jquery-3.4.1.min.js'); ?>"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" type="text/javascript"></script> <script src="<?= base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> <script src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script> </head> <body> <nav class="navbar navbar-expand-md navbar-light bg-light sticky-top shadow mb-4"> <div class="container"> <a href="<?php echo base_url(); ?>adminberanda" class="navbar-brand"> <img src="<?php echo base_url();?>images/dlsu.png" class="dlsu"> <span style="font-family: Roboto;">Troubleshooting<br> <small style="font-family: Roboto;">Perangkat Komputer</small> </span> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"><hr></li> <li class="nav-item shadow p-2"> <a href="#" class="nav-link disabled" style="color: green;"> <i class="fa fa-user-circle"></i><b> <?php echo $this->session->userdata("nama"); ?></b> </a> </li> <li class="nav-item shadow p-2"> <?php $userLevel = $this->session->userdata("level"); if ($userLevel == "admin" || $userLevel == "Koordinator Laboratorium") { ?> <a href=" <?= base_url('adminberanda'); ?> " class="nav-link"><i class="fa fa-home"></i>Beranda</a> <?php }else{ ?> <a href=" <?= base_url('kelolaperangkat'); ?> " class="nav-link"><i class="fa fa-home"></i>Beranda</a> <?php } ?> </li> <li class="nav-item shadow p-2"> <?php if ($userLevel == "admin"){ ?> <a href="<?php echo base_url('login/logout'); ?>" class="nav-link"><i class="fa fa-sign-out-alt"></i>Keluar</a> <?php }else{ ?> <a href="<?php echo base_url('login/logout_aslab'); ?>" class="nav-link"><i class="fa fa-sign-out-alt"></i>Keluar</a> <?php } ?> </li> </ul> </div> </div> </nav><file_sep>/application/views/kelola_ts.php <?php if (isset($_GET['warn'])) { if ($_GET['warn']=="success") { echo '<script type="text/javascript">window.onload=alert("Data Ditambahkan! Mohon menunggu validasi");</script>'; }elseif ($_GET['warn']=="delsuccess") { echo '<script type="text/javascript">window.onload=alert("Data Dihapus!");</script>'; }elseif ($_GET['warn']=="updsuccess") { echo '<script type="text/javascript">window.onload=alert("Data Diubah!");</script>'; } } $currentUser = $this->session->userdata('level'); ?> <div class="container mt-2 mb-4"> <div class="d-flex flex-column p-3 bg-white text-black border rounded"> <div class="container mt-3 border-btm"> <div class="d-flex justify-content-beetwen row"> <div class="col-sm-12 col-md-6 col-lg-6"> <div><h3>Daftar Masalah <small>(<?= $a_ware->w_name; ?>)</small></h3></div> </div> <div class="col-sm-12 col-md-6 col-lg-6" style="text-align: right;"> <?php if ($a_ware->w_kind == "Hardware") { //pisah nav link softawre hardware if ($currentUser == "admin" || $currentUser == "Koordinator Laboratorium") { ?> <a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <a href="<?= base_url('kelolaperangkat'); ?>">Kelola Perangkat</a> > <a href="<?= base_url('kelolaperangkat/hardware'); ?>">Kelola Perangkat Keras</a> > <b>Daftar Masalah</b> <?php }else{ ?> <a href="<?= base_url('kelolaperangkat'); ?>">Kelola Perangkat</a> > <a href="<?= base_url('kelolaperangkat/hardware'); ?>">Kelola Perangkat Keras</a> > <b>Daftar Masalah</b> <?php } }elseif ($a_ware->w_kind == "Software") { if ($currentUser == "admin" || $currentUser == "Koordinator Laboratorium") { ?> <a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <a href="<?= base_url('kelolaperangkat'); ?>">Kelola Perangkat</a> > <a href="<?= base_url('kelolaperangkat/software'); ?>">Kelola Perangkat Lunak</a> > <b>Daftar Masalah</b> <?php }else{ ?> <a href="<?= base_url('kelolaperangkat'); ?>">Kelola Perangkat</a> > <a href="<?= base_url('kelolaperangkat/software'); ?>">Kelola Perangkat Lunak</a> > <b>Daftar Masalah</b> <?php } }else{ echo "no navigation"; } ?> </div> </div> </div> <div class="mt-2 mb-2"> <div class="d-flex justify-content-beetwen row"> <div class="col-7"> <button class="btn btn-primary btn-sm" onclick="modal()" data-toggle="modal" data-target="#myModal"><b>+</b>Tambah Data</button> </div> <div class="col-5" style="text-align: right;"> <div> <input type="text" name="" class="inputbox-3 p-1" id="input" onkeyup="searchTable()" placeholder=" Cari..."> </div> </div> </div> </div> <table id="sortTable" style="overflow: hidden; width: 100%"> <tr><td> <?php foreach ($all_ware as $val) { $d = $val->upd_date; $tanggal = date("d-m-Y", strtotime($d)); $status = ($val->status == 1)?site_url('kelolaperangkat/unapprove/?ts_id='.$val->ts_id.'&w_id='.$val->w_id.'&user='.$currentUser):site_url('kelolaperangkat/approved/?ts_id='.$val->ts_id.'&w_id='.$val->w_id.'&user='.$currentUser); //CEK PASS W_ID DAN USER ?> <?php if ($currentUser != "admin") { ?> <?php }else { ?> <hr> <div class="mb-1"> <small><b>Status:</b></small> <a href="<?php echo $status; ?>" style="text-decoration: none; z-index: 1;" title="Tekan untuk mengubah status"> <span style="color: white;" class="badge <?= ($val->status == 1)?'badge-success':'badge-secondary'; ?>"> <?php echo ($val->status == 1)?'<b>Diteruskan</b>':'<b>Menunggu</b>'; ?> </span> </a> </div> <?php } ?> <button class="collapsible rounded mb-1"> <small style="font-size: 12pt;"> <?php echo $this->bbcode->parse($val->title); ?><hr> <?php echo $this->bbcode->parse($val->detail); ?> </small> </button> <div class="content" style="width: 100%;"> <?php if ($currentUser == "admin" || $currentUser == "Koordinator Laboratorium"): ?> <table class="mt-2"> <tr> <td> <div class="d-flex row ml-1 p-2"> <a href="<?= base_url('kelolaperangkat/edit_ts_data');?>?id=<?= $val->ts_id;?>&wId=<?= $a_ware->w_id; ?>"> <!--LIHAT ID DISINI--> <button type="submit" class="btn btn-sw btn-sm mr-2" style="width: 67.4px;"> <i class="fa fa-edit"></i>Edit </button> </a> <!--form delete--> <form action="<?php echo base_url('kelolaperangkat/delete_ts_data'); ?>?user=<?= $this->session->userdata("nama"); ?>" method="post"> <button type="submit" class="btn btn-danger btn-sm del_alert"> <i class="fa fa-trash"></i> Hapus</button> <div class="hide-form"> <input type="text" class="btn btn-tersier" name="id_ts" value="<?php echo $val->ts_id; ?>"> <input type="text" name="id_perangkat" value="<?php echo $val->w_id ?>"> </div> </form> </div> </td> </tr> </table> <?php endif ?> <div class="d-flex flex-column p-2"> <div> <b>Solusi</b><br> <?php echo $this->bbcode->parse($val->solving); ?> <hr> <!--Modal preview gambar--> <div id="modalImgPreview" class="modalImg"> <span class="closeImgPrev">&times;</span> <img class="ImgContent" id="img01"> </div> </div> </div> <?php if (!empty($val->video)) { ?> <div class="p-2"><small><b>Video</b><br></small> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src="<?php echo $val->video ?>" allowfullscreen></iframe> </div> <hr> <!--UKURAN VIDEO COBA LIA ULANG--> </div> <?php } ?> <div class="p-2"><small><b>Dibuat oleh:</b><br></small> <?php echo $val->name;?> (<?php echo $tanggal; ?>) </div> </div> <?php } ?> </td></tr> </table> </div> </div> <!-- AddThings Modal --> <form method="post" id="formUploadImg" action="<?php echo base_url('kelolaperangkat/add_ts_data'); ?>" enctype="multipart/form-data"> <div class="modal" id="myModal"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Tambah Data</h4> </div> <!-- Modal body --> <div class="modal-body"> <table style="width: 100%;"> <tr> <td> <small>Masalah</small><br> <input type="text" name="masalah" class="form-control form-control-sm" required> </td> </tr> <tr> <td hidden> <small>ID Perangkat</small><br> <small>w_id</small> <input type="text" name="id_perangkat" class="form-control form-control-sm" required value="<?= $a_ware->w_id; ?>" readonly> <small>u_id</small> <input type="text" name="id_user" class="form-control form-control-sm" required value="<?php echo $user_id->u_id; ?>" readonly> </td> </tr> <tr><td> <small>Deskripsi</small><br> <textarea name="deskripsi" class="form-control form-control-sm" rows="3" required></textarea></td> </tr> <tr><td> <small>Solusi</small><br> <textarea name="solusi" class="form-control form-control-sm" rows="5" id="txtsolusi"></textarea></td> </tr> <tr><td> <small>Upload Gambar</small><input type="file" name="gbr" class="btn btn-sm" id="fimg"></td> </tr> <tr><td> <small>Link Video</small><br> <input type="text" name="link_vid" class="form-control form-control-sm"></td> </tr> <!--<tr class="hide-form"><td> <small>Upload Video</small><br> <input type="file" name="video" placeholder="" class="btn btn-sm" required></td> </tr>--> </table> </div> <!-- Modal footer --> <div class="modal-footer"> <button type="button" class="btn btn-danger btn-sm" data-dismiss="modal" onclick="cltxt()">Batal</button> <input type="submit" name="simpan" class="btn btn-success btn-sm" value="Simpan"> <!--<button type="submit" class="btn btn-success btn-sm">Simpan</button>--> </div> </div> </div> </div> <script language="JavaScript" type="text/javascript"> //IMAGE PREVIEW // Get the modal var modal = document.getElementById("modalImgPreview"); // Get the <span> element that closes the modal var span = document.getElementsByClassName("closeImgPrev")[0]; // Get the image and insert it inside the modal - use its "alt" text as a caption var img = document.getElementById("imgPreview"); var modalImg = document.getElementById("img01"); //var captionText = document.getElementById("caption"); if (img != null) { img.onclick = function(){ span.style.display = "block"; modal.style.display = "block"; modalImg.src = this.src; //captionText.innerHTML = this.alt; }; } // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; }; //USER DELETE CONFIRM $(document).ready(function(){ $("button.del_alert").click(function(e){ if(!confirm('Anda akan menghapus data')){ e.preventDefault(); return false; }return true; }); }); function cltxt(){ document.getElementById('myModal').style.display='none'; $('button').click(function(){ $('input[type="text"]').val(' '); $('textarea').val(' '); }); } function searchTable() { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("input"); filter = input.value.toUpperCase(); table = document.getElementById("sortTable"); tr = table.getElementsByTagName("button"); for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("small")[0]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } //expand|collapse data var coll = document.getElementsByClassName("collapsible"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.maxHeight){ content.style.maxHeight = null; } else { content.style.maxHeight = content.scrollHeight + "px"; } }); } $("document").ready(function(){ $("#fimg").change(function(){ //console.log("proses upload"); var form = $('#formUploadImg')[0]; var data = new FormData(form); $.ajax({ type: "POST", encytype: 'multipart/form-data', processData: false, contentType: false, cache: false, data: data, timeout: 5000, url: "<?=base_url('kelolaperangkat/imgUpload')?>" }) .done(function(res){ var url = "<?=base_url('assets/troubleshooting_images/')?>"; var txtsolusi = $("textarea#txtsolusi").val(); $("textarea#txtsolusi").val(txtsolusi + "[img]" + url + res + "[/img]"); console.log(res); }); }); }); </script> </body> </html><file_sep>/application/views/kelolaperangkat.php <div class="container" style="overflow: hidden;"> <div class="container border-btm"> <div class="d-flex justify-content-end row"> <div class="col-sm-12 col-md-6 col-lg-6"> <h3 class="ml-2">Kelola Perangkat</h3> </div> <div class="col-sm-12 col-md-6 col-lg-6" style="text-align: right;"> <?php $session = $this->session->userdata('level'); if ($session == "admin" || $session == "Koordinator Laboratorium") { ?> <div><a href="<?= base_url('adminberanda'); ?>">Beranda</a> > <b>Kelola Perangkat</b></div> <?php }else{ } ?> </div> </div> </div> <div class="container-menu mt-4"> <div class="row padding justify-content-center"> <div class="col-sm-12 col-md-6 col-lg-6"> <div class="card margin-btm"> <a href="<?php echo base_url('Kelolaperangkat/hardware') ?>" class="btn btn-success"><i class="fa fa-desktop"></i><br><hr>Perangkat Keras</a> </div> </div> <div class="col-sm-12 col-md-6 col-lg-6"> <div class="card margin-btm"> <a href="<?php echo base_url('Kelolaperangkat/software') ?>" class="btn-sw"><i class="far fa-window-restore"></i><br><hr>Perangkat Lunak</a> </div> </div> </div> </div> </div> </body> </html><file_sep>/application/controllers/admin_kelolalab.php <?php /** * */ class Admin_kelolalab extends CI_Controller { function __construct() { parent::__construct(); if($this->session->userdata('status') != "login"){ redirect(base_url("login?warn=loginFailed")); } } public function index(){ $data['lab'] = $this->Db_labkom->optionLab()->result(); $this->load->view('admin_kelolalab', $data); } public function lab_info(){ $lab = $_GET['id']; $data['lab'] = $this->Db_labkom->showALab($lab)->row(); $data['namaLaboratorium'] = $this->Db_labkom->Laboratorium($lab)->row(); $data['aslabList'] = $this->Db_labkom->active_aslab($lab)->result(); //DONE $data['troubleList'] = $this->Db_labkom->showLab_Things($lab)->result(); //PANGGIL DAFTAR MASALAH $data['countTrouble'] = $this->Db_labkom->countTrouble($lab); //LIHAT CATATAN DI MODEL $data['koordinatorLab'] = $this->Db_labkom->koordiLabInfo($lab); $data['countPC'] = $this->Db_labkom->countPC($lab)->row(); $data['maxAslab'] = $this->Db_labkom->maxAslab($lab)->row(); $this->load->view('header/header'); $this->load->view('labInfo', $data); } public function addLab(){ $labName = $this->input->post('nama'); $capacity = $this->input->post('kapasitas'); $this->Db_labkom->addLab($labName, $capacity); } public function editLab(){ $labId = $_GET['labId']; $labName = $this->input->post('nama'); $capacity = $this->input->post('kapasitas'); $this->Db_labkom->editLab($labName, $capacity, $labId); } public function active(){ $get_lab = $_GET['lab_id']; if ($get_lab) { $stat = 1; $update = $this->Db_labkom->updateLabStatus($get_lab, $stat); } redirect(base_url('admin_kelolalab')); } public function inactive(){ $get_lab = $_GET['lab_id']; if ($get_lab) { $stat = 0; $update = $this->Db_labkom->updateLabStatus($get_lab, $stat); } redirect(base_url('admin_kelolalab')); } public function addTrouble(){ $nameTrouble = $this->input->post('nama'); $desc = $this->input->post('deskripsi'); $pc = $this->input->post('pc'); $labId = $this->input->post('labId'); $this->Db_labkom->addTrouble($nameTrouble, $desc, $pc, $labId); } public function editTrouble(){ $nameTrouble = $this->input->post('nama'); $desc = $this->input->post('deskripsi'); $pc = $this->input->post('pc'); $labId = $this->input->post('labId'); $id = $this->input->post('tId'); $this->Db_labkom->editTrouble($nameTrouble, $desc, $pc, $labId, $id); } public function hapus_kerusakan(){ $labId = $this->input->post('labId'); $id = $this->input->post('tId'); $this->Db_labkom->removeTrouble($id, $labId); } public function edit_page(){ $labId = $_GET['idLab']; $data['lab_detail'] = $this->Db_labkom->admin_kelolalabEditPage($labId)->row(); $this->load->view('header/header'); $this->load->view('admin_kelolalab_edit', $data); } } ?><file_sep>/application/controllers/admin_kelolapengguna.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * */ class Admin_kelolapengguna extends CI_Controller { function __construct() { parent::__construct(); if($this->session->userdata('level') != "admin" && $this->session->userdata('level') != "Koordinator Laboratorium"){ redirect(base_url("login?warn=loginFailed")); } } public function index(){ $get_labId = $_GET['labId']; $data['lab'] = $this->Db_labkom->showALab($get_labId)->row(); $data['optLab'] = $this->Db_labkom->optionLab()->result(); $data['admin_kelolapengguna'] = $this->Db_labkom->showUser($get_labId)->result(); $data['maxAslabInAdmin'] = $this->Db_labkom->maxAslabInAdmin()->row(); //CEKLAGI $this->load->view('header/header'); $this->load->view('admin_kelolapengguna', $data); } public function addUserbyAdmin(){ $nama = $this->input->post('nama'); $aslab = $this->input->post('lab'); $status = $this->input->post('status'); $email = $this->input->post('email'); //$level = $this->input->post('level'); $kontak = $this->input->post('kontak'); $username = $this->input->post('username'); $password = $this->input->post('password'); $this->Db_labkom->newUserbyAdmin($nama,$aslab,$status,$email,$kontak,$username,$password); } public function addUserbyKoordi(){ $nama = $this->input->post('nama'); $aslab = $this->input->post('lab'); $status = $this->input->post('status'); $email = $this->input->post('email'); //$level = $this->input->post('level'); $kontak = $this->input->post('kontak'); $username = $this->input->post('username'); $password = $this->input->post('password'); $maxAslab = $this->input->post('maxAslab'); $labId = $this->input->post('lab'); $this->Db_labkom->newUserbyKoordi($nama,$aslab,$status,$email,$kontak,$username,$password,$maxAslab,$labId); } public function delUser(){ //$labId = $this->input->post('labId'); $labId = $_GET['labId']; $u_id = $this->input->post('u_id'); $this->Db_labkom->deleteUser($u_id,$labId); } public function edit_page(){ $labId = $_GET['labId']; $get_id = $_GET['id']; $id['optLab'] = $this->Db_labkom->optionLab()->result(); $id['as'] = $this->Db_labkom->take_id($get_id, $labId)->row(); $this->load->view('header/header'); $this->load->view('admin_kelolapengguna_edit', $id); } public function modUser(){ $labId = $_GET['labId']; $nama = $this->input->post('nama'); $aslab = $this->input->post('lab'); $status = $this->input->post('status'); $email = $this->input->post('email'); //$level = $this->input->post('level'); $kontak = $this->input->post('kontak'); $username = $this->input->post('username'); $u_id = $this->input->post('u_id'); $password = $this->input->post('<PASSWORD>'); $this->Db_labkom->editUser($nama,$aslab,$status,$email,$kontak,$username,$u_id,$password, $labId); } public function approved(){ $get_user = $_GET['u_id']; $labId = $_GET['labId']; $u_level = $_GET['level']; if ($get_user) { $stat = 1; $update = $this->Db_labkom->updateUserStatusActive($get_user, $stat, $labId, $u_level); //redirect(base_url('admin_kelolapengguna?labId=0&user='.$get_user.'-active')); } } public function unapprove(){ $get_user = $_GET['u_id']; $labId = $_GET['labId']; $u_level = $_GET['level']; if ($get_user) { $stat = 0; $update = $this->Db_labkom->updateUserStatusFailed($get_user, $stat, $labId, $u_level); redirect(base_url('admin_kelolapengguna?labId=0&user='.$get_user.'-nonactive')); } } public function filter_user(){ $labId = $_GET['labId']; $data['optLab'] = $this->Db_labkom->optionLab()->result(); $filter = $_GET['filter']; $data['filter'] = $_GET['filter']; $data['admin_kelolapengguna'] = $this->Db_labkom->filterUser($filter)->result(); $data['maxAslabInAdmin'] = $this->Db_labkom->maxAslabInAdmin()->row(); //CEKLAGI //$data['countAslab'] = $this->Db_labkom->countAslab($labId)->row(); $this->load->view('header/header'); $this->load->view('admin_kelolapengguna', $data); } public function filter_userLab(){ $labId = $_GET['labId']; $labName = $_GET['labName']; $data['labName'] = $_GET['labName']; $data['optLab'] = $this->Db_labkom->optionLab()->result(); $filter = $_GET['filter']; $data['filter'] = $_GET['filter']; $data['admin_kelolapengguna'] = $this->Db_labkom->filterUserLab($filter)->result(); $data['maxAslabInAdmin'] = $this->Db_labkom->maxAslabInAdmin()->row(); //CEKLAGI //$data['countAslab'] = $this->Db_labkom->countAslab($labId)->row(); $this->load->view('header/header'); $this->load->view('admin_kelolapengguna', $data); } } ?><file_sep>/application/views/adminberanda.php <?php $currentUser = $this->session->userdata("nama");?> <div class="container-menu mt-4"> <?php if ($currentUser == "admin") { ?> <div class="row padding"> <div class="col-sm-12 col-md-6 col-lg-4"> <div class="card margin-btm"> <a href="<?= base_url('kelolaperangkat')?>" class="btn btn-outline-success btn-block"><i class="fa fa-desktop"></i><br><hr>Kelola Perangkat</a> </div> </div> <div class="col-sm-12 col-md-6 col-lg-4"> <div class="card margin-btm"> <a href="<?php echo base_url('admin_kelolalab') ?>" class="btn btn-outline-info btn-block"><i class="fa fa-clipboard-list"></i><br><hr>Kelola Laboratorium</a> </div> </div> <div class="col-sm-12 col-md-6 col-lg-4"> <div class="card margin-btm"> <a href="<?php echo base_url();?>admin_kelolapengguna?labId=0" class="btn btn-outline-primary btn-block"><i class="fa fa-user"></i><br><hr>Kelola Pengguna</a> </div> </div> </div> <?php }else{ ?> <div class="row padding"> <div class="col-sm-12 col-md-6 col-lg-6"> <div class="card margin-btm"> <a href="<?= base_url('kelolaperangkat')?>" class="btn btn-outline-success btn-block"><i class="fa fa-desktop"></i><br><hr>Kelola Perangkat</a> </div> </div> <div class="col-sm-12 col-md-6 col-lg-6"> <div class="card margin-btm"> <a href="<?php echo base_url('admin_kelolalab/lab_info?id='.$lab->lab_id) ?>" class="btn btn-outline-info btn-block"><i class="fa fa-clipboard-list"></i><br><hr>Kelola Laboratorium</a> </div> </div> </div> <?php } ?> </div> </body> </html><file_sep>/assets/js/jscript.js function showmodal(){ alert } function hidemodal(){ document.getElementById('myModal').style.display='none'; $('button').click(function(){ $('input[type="email"]').val(' '); $('input[type="text"]').val(' '); }); } function cltxt(){ document.getElementById('myModal').style.display='none'; $('button').click(function(){ $('input[type="text"]').val(' '); }); } //expand|collapse user data var coll = document.getElementsByClassName("collapsible"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.maxHeight){ content.style.maxHeight = null; } else { content.style.maxHeight = content.scrollHeight + "px"; } }); } //USER DELETE ALERT $(document).ready(function(){ $("button.del_alert").click(function(e){ if(!confirm('Anda akan menghapus data')){ e.preventDefault(); return false; }return true; }); });<file_sep>/application/controllers/kelolaperangkat.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * */ class Kelolaperangkat extends CI_Controller { function __construct() { parent::__construct(); if ($this->session->userdata('status') != "login") { redirect(base_url("login?warn=loginFailed")); } $this->load->helper('form'); $this->load->library('form_validation'); $this->load->helper("file"); $this->load->model('Db_labkom'); } public function index(){ $this->load->view('header/header'); $this->load->view('kelolaperangkat'); } //HARDWARE public function hardware(){ $data['listHw'] = $this->Db_labkom->showHw()->result(); $this->load->view('header/header'); $this->load->view('kelolahardware', $data); } public function addHw(){ $nama = $this->input->post('nama'); $jp = $this->input->post('jenis_perangkat'); $icon = $_FILES['icon']; if ($icon='') { }else{ $config['upload_path'] = './assets/icon'; $config['allowed_types'] = 'jpg|png|jpeg'; $this->load->library('upload',$config); if (!$this->upload->do_upload('icon')) { echo "Upload Gagal!"; die(); }else{ $icon = $this->upload->data('file_name'); } } $this->Db_labkom->newHw($nama,$jp,$icon); } public function delHw(){ $id = $this->input->post('w_id'); $icon = $this->input->post('w_icon'); $url = "assets/icon/".$icon; $this->Db_labkom->deleteHw($id,$url); } public function modHw(){ $id = $this->input->post('idperangkat'); $nama = $this->input->post('editnama'); $jp = $this->input->post('editperangkat'); $gambar = $this->input->post('icon'); $url = "assets/icon/".$gambar; $icon = $_FILES['icon']; if ($icon='') { }else{ $config['upload_path'] = './assets/icon'; $config['allowed_types'] = 'jpg|png|jpeg;'; $this->load->library('upload',$config); if (!$this->upload->do_upload('icon')) { $this->Db_labkom->updateHw($id,$nama,$jp); die(); }else{ $icon = $this->upload->data('file_name'); $this->Db_labkom->updateHw($id,$nama,$jp,$icon,$url); } } } public function page_editHw(){ $get_id = $_GET['id']; $id['as'] = $this->Db_labkom->take_Hwid($get_id)->row(); $this->load->view('header/header'); $this->load->view('kelolahardware_edit', $id); } //SOFTWARE public function software(){ $data['listSw'] = $this->Db_labkom->showSw()->result(); $this->load->view('header/header'); $this->load->view('kelolasoftware', $data); } public function addSw(){ $nama = $this->input->post('nama'); $jp = $this->input->post('jenis_perangkat'); $icon = $_FILES['icon']; if ($icon='') { }else{ $config['upload_path'] = './assets/icon'; $config['allowed_types'] = 'jpg|png|jpeg;'; $this->load->library('upload',$config); if (!$this->upload->do_upload('icon')) { echo "Upload Gagal!"; die(); }else{ $icon = $this->upload->data('file_name'); } } $this->Db_labkom->newSw($nama,$jp,$icon); } public function delSw(){ $id = $this->input->post('w_id'); $icon = $this->input->post('w_icon'); $url = "assets/icon/".$icon; $this->Db_labkom->deleteSw($id,$url); } public function modSw(){ $id = $this->input->post('idperangkat'); $nama = $this->input->post('editnama'); $jp = $this->input->post('editperangkat'); $gambar = $this->input->post('icon'); $url = "assets/icon/".$gambar; $icon = $_FILES['icon']; if ($icon='') { }else{ $config['upload_path'] = './assets/icon'; $config['allowed_types'] = 'jpg|png|jpeg;'; $this->load->library('upload',$config); if (!$this->upload->do_upload('icon')) { $this->Db_labkom->updateSw($id,$nama,$jp); die(); }else{ $icon = $this->upload->data('file_name'); $this->Db_labkom->updateSw($id,$nama,$jp,$icon,$url); } } } public function page_editSw(){ $get_id = $_GET['id']; $id['as'] = $this->Db_labkom->take_Swid($get_id)->row(); $this->load->view('header/header'); $this->load->view('kelolasoftware_edit', $id); } //TROUBLESHOOTING PERANGKAT public function ts_data(){ $this->load->library('Bbcode'); $id_perangkat = $this->input->post('id_perangkat'); $get_id = $_GET['id']; $get_user = $_GET['user']; date_default_timezone_set("Singapore"); $date = date("Y-m-d"); $id['all_ware'] = $this->Db_labkom->take_ware_ts($get_id, $get_user)->result(); //take all record in the table $id['a_ware'] = $this->Db_labkom->take_a_ware($get_id)->row(); // take a record $id['user_id'] = $this->Db_labkom->selectUser($get_user)->row(); $this->load->view('header/header'); $this->load->view('kelola_ts', $id); } public function imgUpload(){ $icon = $_FILES['gbr']; if ($icon='') { $icon = 'blank.jpg'; }else{ $config['upload_path'] = './assets/troubleshooting_images/'; $config['allowed_types'] = 'jpg|png|jpeg;'; $this->load->library('upload',$config); if ($this->upload->do_upload('gbr')) { $icon = $this->upload->data('file_name'); }else{ $icon = "sukses.jpg"; } } echo $icon; } public function approved(){ $get_tsId = $_GET['ts_id']; $get_wId = $_GET['w_id']; $get_user = $_GET['user']; if ($get_tsId) { $stat = 1; $update = $this->Db_labkom->updateStat2($stat, $get_tsId); } redirect(base_url('kelolaperangkat/ts_data?id='.$get_wId.'&user='.$get_user)); } public function unapprove(){ $get_tsId = $_GET['ts_id']; $get_wId = $_GET['w_id']; $get_user = $_GET['user']; if ($get_tsId) { $stat = 0; $update = $this->Db_labkom->updateStat2($stat, $get_tsId); } redirect(base_url('kelolaperangkat/ts_data?id='.$get_wId.'&user='.$get_user)); } public function edit_ts_data(){ $get_id = $_GET['id']; $w_id = $_GET['wId']; $id['data_ts'] = $this->Db_labkom->take_dataTs($get_id)->row(); $id['a_ware'] = $this->Db_labkom->take_a_ware($w_id)->row(); // take a record $this->load->view('header/header'); $this->load->view('kelola_ts_edit', $id); } public function add_ts_data(){ $masalah = $this->input->post('masalah'); $id_perangkat = $this->input->post('id_perangkat'); $id_user = $this->input->post('id_user'); $deskripsi = $this->input->post('deskripsi'); $solusi = $this->input->post('solusi'); $linkVid = $this->input->post('link_vid'); date_default_timezone_set("Singapore"); $date = date("Y-m-d"); if (!empty($linkVid)) { $youTube = "https://www.youtube.com/embed/"; $key = $youTube.$linkVid; $this->Db_labkom->new_ts_data($masalah,$id_perangkat,$id_user,$deskripsi,$solusi,$key,$date); }else{ $this->Db_labkom->new_ts_data($masalah,$id_perangkat,$id_user,$deskripsi,$solusi,$linkVid,$date); } } public function upd_ts_data(){ $masalah = $this->input->post('masalah'); $id_ts = $this->input->post('id_troubleshooting'); $id_user = $this->input->post('id_user'); $id_perangkat = $this->input->post('id_perangkat'); $deskripsi = $this->input->post('deskripsi'); $solusi = $this->input->post('solusi'); $linkVid = $this->input->post('link_vid'); date_default_timezone_set("Singapore"); $date = date("Y-m-d"); $this->Db_labkom->update_ts_data($masalah,$id_ts,$id_user,$id_perangkat,$deskripsi,$solusi,$linkVid,$date); } public function delete_ts_data(){ $get_user = $_GET['user']; $id_ware = $this->input->post('id_perangkat'); $ts_id = $this->input->post('id_ts'); $this->Db_labkom->remove_ts_data($ts_id, $id_ware, $get_user); } } ?>
a9c18cecd494ee06e74e789381ec9f484f0bb2aa
[ "JavaScript", "SQL", "PHP" ]
23
PHP
andri000me/aplikasi-kp
93eb24a6c8837ff861b1c38c6ae7fb75d66b2e89
331bd07e730648c4a1936f7b548d06c4c0c9dc7b
refs/heads/master
<file_sep>class Friend < ActiveRecord::Base belongs_to :friend_one, :class_name => 'User' belongs_to :friend_two, :class_name => 'User' belongs_to :user has_many :activities def friend_id(f1_id, f2_id, dk_id) @val1 = Integer(f1_id) @val2 = Integer(f2_id) @val3 = Integer(dk_id) if @val1 == @val3 id = @val2 elsif @val2 == @val3 id = @val1 else id = 3 end return id end end <file_sep>class Invite < ActiveRecord::Base belongs_to :user belongs_to :challenge has_many :completes def as_json(options = {}) { id: self.id, accepted: self.accepted, challenge: self.challenge, user: self.user } end def self.all_actions_for_user(user_id) # all.includes(challenge: {tasks: :actions, tasks: task_dates}).includes(user: :actions).where('invites.user_id' => 3) where(user_id: user_id, accepted: true) .includes(challenge: {tasks: :actions, tasks: :task_dates}) .includes(:user) .includes(:completes) end def otherUsers?(invite_id) # Find the users invite to find the challenge_id. @invite = Invite.find(invite_id) #Use the challenge_id from the users invite to find out if there are other invites with the same challenge id. if Invite.where(challenge_id: @invite.challenge_id).count > 1 status = true else status = false end status end def validateID?(invite_id, task_date_id) if Complete.where(id: invite_id, task_date_id: task_date_id).count > 0 status = true else status = false end status end def completionResult?(invite_id, task_date_id) if Complete.where(id: invite_id, task_date_id: task_date_id).count > 0 if Complete.where(id: invite_id, task_date_id: task_date_id).first!.distance != nil && Complete.where(id: invite_id, task_date_id: task_date_id).first!.time == nil status = Complete.where(id: invite_id, task_date_id: task_date_id).first!.distance end if Complete.where(id: invite_id, task_date_id: task_date_id).first!.time != nil && Complete.where(id: invite_id, task_date_id: task_date_id).first!.distance == nil status = Complete.where(id: invite_id, task_date_id: task_date_id).first!.time end else status = 0 end status end end <file_sep>class AddNewFeaturesToActionModules < ActiveRecord::Migration def change add_column :completes, :distance, :integer change_column :completes, :time, :integer end end <file_sep>class LandingController < ApplicationController #skip_before_action :verify_authenticity_token skip_before_action :verify_authenticity_token before_action :set_signup, only: [:edit, :update, :destroy] def hello end def index end def show @pre = Presignup.find(params[:id]) end def new @pre = Presignup.new end def create @pre = Presignup.new(set_params) if @pre.save redirect_to '/', notice: 'Du er nu blevet skrevet op, vi glæder os til at se dig!' else render :new end end def add_signup @pre = Presignup.new(email: @email) if @pre.save redirect_to '/', notice: 'Du er nu blevet skrevet op, vi glæder os til at se dig!' else render :new end end private def set_params params.require(:presignup).permit( :email) end def set_signup @pre = Presignup.find(params[:id]) end def deleteSession session.delete(:user_id) redirect_to root_path end end <file_sep>class Api::FollowersController < ApplicationController before_action :doorkeeper_authorize!, except: [] #Todo sæt tilbage til at have oauth #before_action :set_user, only: [:show, :edit, :update, :destroy] skip_before_action :verify_authenticity_token def index followers = Follower.all render json:followers end def create param = params.permit(:follower_one_id, :follower_two_id, :status) follower = Follower.create(param) if follower Activity.add_activity(doorkeeper_token.resource_owner_id, 'started_following', follower.id) render status: :created, json: follower else render :status => 400 end end def destroy @follower = Follower.find_by(follower_one_id: doorkeeper_token.resource_owner_id, follower_two_id: params[:id]) Activity.add_activity(doorkeeper_token.resource_owner_id, 'stopped_following', @follower.follower_two_id) @follower.destroy render json: :deleted end def update follower = Follower.find_by(follower_one_id: params[:id], follower_two_id: doorkeeper_token.resource_owner_id) p = params.permit(:status) respond_to do |format| if follower.update(p) #invite.save format.json { render :status => :updated, :json => follower } else format.json { render :status => 400 } end end end # 'friendOne.profileimage.url(:thumb)' def followers @followers = Follower.where(follower_two_id: params[:id]) render json: @followers.map {|follower| { id: follower.follower_one_id, username: User.find(follower.follower_one_id).username, firstname: User.find(follower.follower_one_id).first_name, lastname: User.find(follower.follower_one_id).last_name, profile_image: User.find(follower.follower_one_id).profileimage.url(:thumb) }} end def follows @followers = Follower.where(follower_one_id: params[:id]) render json: @followers.map {|follower| { id: follower.follower_two_id, username: User.find(follower.follower_two_id).username, firstname: User.find(follower.follower_two_id).first_name, lastname: User.find(follower.follower_two_id).last_name, profile_image: User.find(follower.follower_two_id).profileimage.url(:thumb) }} end def followRequest followRequest = Follower .select('followers.id','friendOne.username as follower_1', 'friendTwo.username as follower_2', 'followers.status') .joins("left join users as friendOne on followers.follower_one_id = friendOne.id") .joins("left join users as friendTwo on followers.follower_two_id = friendTwo.id") .where(status: 0) .where(friend_two_id: doorkeeper_token.resource_owner_id) render json: followRequest end def followers_1 followers = Follower .select('followers.id','friendOne.username as follower_1', 'friendTwo.username as follower_2', 'followers.status') .joins("left join users as friendOne on followers.follower_one_id = friendOne.id") .joins("left join users as friendTwo on followers.follower_two_id = friendTwo.id") .where(status: 1) .where("follower_one_id =" + doorkeeper_token.resource_owner_id + " OR follower_two_id = " + doorkeeper_token.resource_owner_id) render json: followers end end <file_sep>class AddAuthLogicToUser < ActiveRecord::Migration def change add_column :users, :crypted_password, :string add_column :users, :password_salt, :string add_column :users, :persistence_token, :string add_column :users, :auth_token, :string add_column :users, :cleartext_password, :string add_column :users, :is_super_admin, :boolean, default: false add_column :users, :is_admin, :boolean, default: false end end <file_sep>class AddCorrectReferencesToAwesomeTables < ActiveRecord::Migration def change add_reference :action_dates, :task, index: true, foreign_key: true add_reference :actionmodules, :action, index: true, foreign_key: true end end <file_sep>class Follower < ActiveRecord::Base belongs_to :follower_one, :class_name => 'User' belongs_to :follower_one, :class_name => 'User' belongs_to :user has_many :activities end <file_sep>class Api::ActivitiesController < ApplicationController before_action :doorkeeper_authorize!, except: [] #Todo sæt tilbage til at have oauth #before_action :set_user, only: [:show, :edit, :update, :destroy] skip_before_action :verify_authenticity_token def get_activities @activities = User.find(doorkeeper_token.resource_owner_id).activities.where(feed_type: 0).order('created_at DESC') render json: @activities.map {|activity| { username: User.find(activity.user_id).username, profile_image: User.find(activity.user_id).profileimage.url(:thumb), user_id: activity.user_id, activity_type: activity.activity_type, activity_id: activity.activity_id, task_name: activity.task_name_for_activity(activity.activity_type, activity.activity_id), challenge_name: activity.challenge_title_for_activity(activity.activity_id) } } end end <file_sep>class Api::InvitesController < ApplicationController before_action :doorkeeper_authorize!, except: [:create] skip_before_action :verify_authenticity_token before_action :set_invite, only: [:show, :edit, :destroy] def index invites = Invite.all render json:invites end def show end def create invite = Invite.create(create_invite_params) if invite render :status => :created, :json => invite else render :status => 400, json: [] end end def update p = params.permit(:accepted, :id) invite = Invite.find(p[:id]) puts(p[:accepted]) if p[:accepted] == 'true' Activity.add_activity(doorkeeper_token.resource_owner_id, 'accepted_challenge', invite.id) elsif p[:accepted] == 'false' Activity.add_activity(doorkeeper_token.resource_owner_id, 'declined_challenge', invite.id) end respond_to do |format| if invite.update(p) format.json { render :status => :updated, :json => invite } else format.json { render :status => 400 } end end end def destroy invite.destroy respond_to do |format| msg = { :status => "ok", :message => "success", :html => "<b>...</b>" } format.json { render :json => msg } end end def showInviteWithChallengeName # # Getting all the invites the user haven't answered. # invites_for_user = Invite.where(user_id: doorkeeper_token.resource_owner_id).where(accepted: nil).order('created_at DESC') render json: invites_for_user.map {|invite| { id: invite.id, title: invite.challenge.title, invited: invite.user.username, invited_id: invite.user.id, invited_by: User.find(invite.challenge.user_id).username, invited_by_profileimage: User.find(invite.challenge.user_id).profileimage.url(:thumb), invited_by_id: invite.challenge.user_id, accepted: invite.accepted } } end def showAcceptedChallenges # # Show all the accepted challenges for a user. # invites = Invite .select('invites.id', 'challenges.title', 'users.username as invited', 'users.id as invited_id', 'invited_by.username as invited_by', 'invited_by.id as invited_by_id', 'invites.accepted') .joins("inner join challenges on challenges.id = invites.challenge_id inner join users on invites.user_id = users.id left join users as invited_by on challenges.user_id = invited_by.id") .where(user_id: doorkeeper_token.resource_owner_id).where("accepted IS ?", true).order('invites.created_at DESC') render json: invites end private def set_invite invite = Invite.find(params[:id]) render json: invite end def invite_params params.require(:invite).permit(:accepted) end def create_invite_params params.require(:invite).permit(:user_id, :challenge_id, :accepted) end end <file_sep>class ChangeCompleteTabke < ActiveRecord::Migration def change remove_column :completes, :action_dates_id add_reference :completes, :task_date, index: true, foreign_key: true end end <file_sep>class Task < ActiveRecord::Base belongs_to :challenge has_many :actions has_many :task_dates accepts_nested_attributes_for :actions accepts_nested_attributes_for :task_dates def as_json(options = {}) { id: self.id, title: self.title, actions: self.actions, task_dates: self.task_dates } end end <file_sep>class DataHandling < ActiveRecord::Base has_many :users accepts_nested_attributes_for :users end <file_sep>class PresignupsController < ApplicationController skip_before_action :verify_authenticity_token def create @presignup = Presignup.new(params[:presignup]) if @presignup.save redirect_to root_path else render action: :new end end def new @presignup = Presignup.new end end <file_sep>class RemoveChallengesFromUser < ActiveRecord::Migration def change remove_column :users, :challenges_id end end <file_sep>class Api::UsersController < ApplicationController before_action :doorkeeper_authorize!, except: [:create, :user_challenges, :new] before_action :set_user, only: [:show, :edit, :update, :destroy] skip_before_action :verify_authenticity_token def index users = User.find(doorkeeper_token.resource_owner_id) render json:users end def show @user = User.find(params[:id]) render json: User end def new @user = User.new end def create param = params.require(:user).permit(:first_name, :last_name, :username, :gender, :password, :created_at, :updated_at, :active, :phone, :email, :birthday, :weight) user = User.create(param) if user render status: :created, json: user else render :status => 400 end end def update respond_to do |format| if user.update(user_params) render :status => :updated, :json => user else render :status => 400 end end end def destroy user.destroy respond_to do |format| msg = { :status => "ok", :message => "success", :html => "<b>...</b>" } format.json { render :json => msg } end end def user_challenges user = User.find(params[:id]) render json: { id: user.id, first_name: user.first_name, last_name: user.last_name, challenges: user.challenges } end def user_score #TODO count all @actions = Action.includes(:task).where(tasks: {challenge_id: self.id}).count end def search_users @key = "%#{params[:key]}%" @columns = %w{first_name last_name username} @users = User.where( @columns .map {|c| "#{c} like :search" } .join(' OR '), search: @key ).limit(50) render json: @users.map {|user| { id: user.id, username: user.username, firstname: user.first_name, lastname: user.last_name, profileimage: user.profileimage.url(:thumb), friend_status: user.friend_status?(doorkeeper_token.resource_owner_id, user.id), follower_status: user.follower_status?(doorkeeper_token.resource_owner_id, user.id), follows: user.who_i_follow(user.id), follows_user: user.who_follow_me(user.id), total_friends: user.total_friends(user.id), pending_friend_status: user.pending_friend_status?(doorkeeper_token.resource_owner_id, user.id) } } end def user_stats @user = User.where(id: params[:id]) render json: @user.map {|user| { friend_status: user.friend_status?(doorkeeper_token.resource_owner_id, user.id), follower_status: user.follower_status?(doorkeeper_token.resource_owner_id, user.id), follows: user.who_i_follow(user.id), follows_user: user.who_follow_me(user.id), total_friends: user.total_friends(user.id), pending_friend_status: user.pending_friend_status?(doorkeeper_token.resource_owner_id, user.id), points: user.get_total_points(user.id) } } end def news @user = User.find(params[:id]) @news = @user.challenges.tasks.actions render json: @news end def profile_image_medium_url @user = User.find(params[:id]) @url = @user.profileimage.url(:medium) render json: @url end def cover_image_medium_url @user = User.find(params[:id]) @url = @user.coverimage.url(:medium) render json: @url end def upload_profile_image @p = params.permit(:image_data, :id) if User.exists?(id: @p[:id]) @user = User.find(@p[:id]) image_data = @p[:image_data] respond_to do |format| if @user.update_attributes(profileimage: image_data) Activity.add_activity(doorkeeper_token.resource_owner_id, 'uploaded_new_profile_image', @user.id) format.json { render :status => :ok, json: :updated } else format.json { render :status => 400 } end end end end def upload_cover_image @p = params.permit(:image_data, :id) if User.exists?(id: @p[:id]) @user = User.find(@p[:id]) image_data = @p[:image_data] respond_to do |format| if @user.update_attributes(coverimage: image_data) Activity.add_activity(doorkeeper_token.resource_owner_id, 'uploaded_new_cover_image', @user.id) format.json { render :status => :ok, json: :updated } else format.json { render :status => 400 } end end end end def remove_profile_image @user = User.find(params[:id]) @user.profileimage = nil if @user.save render :status => :created, :json => @user else render :status => 400, json: [] end end def remove_cover_image @user = User.find(params[:id]) @user.coverimage = nil if @user.save render :status => :created, :json => @user else render :status => 400, json: [] end end def otherUsersForActions @p = params.permit(:invite_id, :task_date_id) @invite = Invite.find(params[:invite_id]) @invites = Invite.where(challenge_id: @invite.challenge_id).where("id NOT IN (?)", @invite.id) render json: @invites.map {|invite| { user_id: User.find(invite.user_id).id, username: User.find(invite.user_id).username, profileimage: User.find(invite.user_id).profileimage.url(:medium), completed: invite.validateID?(invite.id, @p[:task_date_id]), completed_result: invite.completionResult?(invite.id, @p[:task_date_id]) } } end private def set_user user = User.find(params[:id]) render json: user end def user_params params.require(:user).permit(:first_name, :last_name, :username, :gender, :profileimage, :coverimage, :weight) end end <file_sep>class Presignup < ActiveRecord::Base validates_uniqueness_of :email validates :email, presence: true end <file_sep>class RenameType < ActiveRecord::Migration def change rename_column :activities, :type, :feed_type end end <file_sep>class AddTasksToChallenge < ActiveRecord::Migration def change # add_reference :challenges, :tasks, index: true, foreign_key: true end end <file_sep>class Actionmodule < ActiveRecord::Base belongs_to :action def as_json(options = {}) { id: self.id, moduletype: self.moduletype, time: self.time, distance: self.distance } end end <file_sep>class RenameActionDatesToTaskDates < ActiveRecord::Migration def change rename_table :action_dates, :task_dates end end <file_sep>class Complete < ActiveRecord::Base has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/ belongs_to :task_date belongs_to :invite def as_json(options = {}) { id: self.id, invite_id: self.invite_id, task_date: self.task_date, image: self.image, moduletype: self.moduletype, time: self.time, distance: self.distance } end end <file_sep>class SessionsController < ApplicationController skip_before_action :verify_authenticity_token def new end def create @user = User.find_by(email: params[:sessions_path][:email]) if @user && @user.valid_password?(params[:sessions_path][:password]) session[:user_id] = @user.id #flash[:success] = "Velkommen tilbage!" redirect_to "/backend" else flash[:warning] = "Du har indtastet den forkerte email eller password." redirect_to "/sessions/new" end end def destroy session.delete(:user_id) redirect_to root_path end end <file_sep>class TaskDatesController < ApplicationController end <file_sep>class Api::TasksController < ApplicationController end <file_sep>class RemoveTaskDatesFromDb < ActiveRecord::Migration def change drop_table :task_dates end end <file_sep>class Api::FriendsController < ApplicationController before_action :doorkeeper_authorize!, except: [] #Todo sæt tilbage til at have oauth #before_action :set_user, only: [:show, :edit, :update, :destroy] skip_before_action :verify_authenticity_token def index friends = Friend.all render json:friends end def destroy @friend = Friend.find_by(friend_one_id: doorkeeper_token.resource_owner_id, friend_two_id: params[:id]) Activity.add_activity(doorkeeper_token.resource_owner_id, 'removed_friend_request', @friend.friend_two_id) @friend.destroy render json: :deleted end def create param = params.permit(:friend_one_id, :friend_two_id, :status) friend = Friend.create(param) Activity.add_activity(doorkeeper_token.resource_owner_id, 'friend_request', friend.id) if friend render status: :created, json: friend else render :status => 400 end end def update friend = Friend.find_by(friend_one_id: params[:id], friend_two_id: doorkeeper_token.resource_owner_id) p = params.permit(:status) respond_to do |format| if friend.update(p) #invite.save Activity.add_activity(doorkeeper_token.resource_owner_id, 'accepted_friend_request', friend.id) format.json { render :status => :updated, :json => friend } else format.json { render :status => 400 } end end end def decline_friendship @friend = Friend.find_by(friend_one_id: params[:id], friend_two_id: doorkeeper_token.resource_owner_id) Activity.add_activity(doorkeeper_token.resource_owner_id, 'declined_friend', @friend.friend_one_id) @friend.destroy render json: :deleted end def friends @friends = Follower.select('friendTwo.username as username', 'friendTwo.first_name as firstname', 'friendTwo.last_name as lastname', 'friendTwo.id as user_id' ) .joins("left join users as friendOne on friends.friend_one_id = friendOne.id") .joins("left join users as friendTwo on friends.friend_two_id = friendTwo.id") .where("friend_one_id =" + params[:id] + " OR friend_two_id = " + params[:id]) render json: @friends end def friendRequests friendRequest = Friend .select('friends.id','friendOne.username as friend_1', 'friendTwo.username as friend_2', 'friends.status') .joins("left join users as friendOne on friends.friend_one_id = friendOne.id") .joins("left join users as friendTwo on friends.friend_two_id = friendTwo.id") .where(status: 0) .where(friend_two_id: doorkeeper_token.resource_owner_id) render json: friendRequest end def friends1 friends = Friend .select('friends.id','friendOne.username as friend_1', 'friendTwo.username as friend_2', 'friends.status') .joins("left join users as friendOne on friends.friend_one_id = friendOne.id") .joins("left join users as friendTwo on friends.friend_two_id = friendTwo.id") .where(status: 1) .where("friend_one_id =" + doorkeeper_token.resource_owner_id + " OR friend_two_id = " + doorkeeper_token.resource_owner_id) render json: friends end def show_friends @p = params.permit(:id) @friends = Friend.where(status: 1).where('friend_one_id = :val1 OR friend_two_id = :val2', val1: @p[:id], val2: @p[:id]) dk_id = @p[:id] if @friends.count > 0 render json: @friends.map {|friend| { id: friend.friend_id(friend.friend_one_id, friend.friend_two_id, dk_id), username: User.find(friend.friend_id(friend.friend_one_id, friend.friend_two_id, dk_id)).username, firstname: User.find(friend.friend_id(friend.friend_one_id, friend.friend_two_id, dk_id)).first_name, lastname: User.find(friend.friend_id(friend.friend_one_id, friend.friend_two_id, dk_id)).last_name, profile_image: User.find(friend.friend_id(friend.friend_one_id, friend.friend_two_id, dk_id)).profileimage.url(:thumb) } } else render json: [] end end end <file_sep>class CreateActivities < ActiveRecord::Migration def change create_table :activities do |t| t.integer :user_id #Who generated the activity t.string :activity_type #Is it a comment, completed or other activity t.integer :activity_id #What is the id of the activity t.timestamps null: false end end end <file_sep>class Api::LocationsController < ApplicationController before_action :doorkeeper_authorize!, except: [] skip_before_action :verify_authenticity_token def create @p = params.permit(:latitude, :longitude, :altitude, :course, :completes_id) @location = Location.create(@p) if @location render :status => :created, :json => @location else render :status => 400, json: [] end end def create_all_locations @locations = params[:locations] if @locations.count != 0 params[:locations].each do |l| if Complete.where(id: l[:completes_id]).count > 0 Location.create(latitude: l[:latitude], longitude: l[:longitude], altitude: l[:altitude], course: l[:course], completes_id: l[:completes_id]) end end render :status => created, json: @locations else render :status => 500, json: [] end end def destroy_all_locations if Complete.find(params[:id]).present? @locations = Location.where(completes_id: params[:id]) if @locations.destroy_all render :status => 200, json: @locations else render :status => 400, json: [] end else render :status => 500, json: [] end end end <file_sep>class Renametype < ActiveRecord::Migration def change rename_column :actionmodules, :type, :moduletype end end <file_sep># Be sure to restart your server when you modify this file. #The old key was: _challyme_api_session Rails.application.config.session_store :cookie_store, key: 'CM_User' <file_sep>class UserPoint < ActiveRecord::Base belongs_to :user def self.give_point(user_id, point_type) add_point = UserPoint.create({user_id: user_id, point_type: point_type}) add_point end end <file_sep>class BackendController < ApplicationController skip_before_action :verify_authenticity_token def index end def show end def new end def create end def destroy session.delete(:user_id) redirect_to root_path end def deleteSession session.delete(:user_id) redirect_to root_path end def numberOfUsers @users = User.count end end <file_sep>class Api::AuthController < ApplicationController layout "login" def login #@user = User.new @user = AuthHelper::Session.new end def validate @user = AuthHelper::Session.new(params[:auth_helper_session]) if @user.save redirect_to root_path else render :login end end def logout current_user_session.destroy redirect_to 'api/login' end end <file_sep>class RenameActionModuleColumns < ActiveRecord::Migration def change rename_column :actionmodules, :text, :type rename_column :actionmodules, :countertype, :time end end <file_sep>class AddActionDatesToComplete < ActiveRecord::Migration def change add_reference :completes, :action_dates, index: true, foreign_key: true end end <file_sep>class TaskDate < ActiveRecord::Base belongs_to :task has_many :completes def as_json(options = {}) { id: self.id, date: self.date } end end <file_sep>class AddActionDatesToAction < ActiveRecord::Migration def change add_reference :action_dates, :actions, index: true, foreign_key: true end end <file_sep>class RemoveCounterTime < ActiveRecord::Migration def change remove_column :actionmodules, :countertime end end <file_sep>class CreateLocations < ActiveRecord::Migration def change create_table :locations do |t| t.string :latitude t.string :longitude t.integer :altitude t.integer :course t.integer :completes_id t.timestamps null: false end add_index(:locations, :completes_id) end end <file_sep>class Api::CompletesController < ApplicationController before_action :doorkeeper_authorize!, except: [ :destroy, :home_feed] #Todo sæt tilbage til at have oauth before_action :set_complete, only: [:destroy] skip_before_action :verify_authenticity_token def index completes = Complete.all render json:completes end def destroy complete.destroy respond_to do |format| msg = { :status => "ok", :message => "success", :html => "<b>...</b>" } format.json { render :json => msg } end end def showAllActionForUser # # Show all actions sorted by date, and if they are completed or not. #.where('task_dates.date >= ?', Date.today).where('invite.user_id = ?', 3) .where('invite.accepted = ?', true) #invite = Invite.all_actions_for_user(3) #render json: { # invites: invite #} invites = Invite.where(user_id: doorkeeper_token.resource_owner_id, accepted: true) tasks = invites.reduce([]) do |acc, invite| tasks = invite.challenge.tasks tasks.each do |task| logger.info "In task" task_dates = task.task_dates.where('date >= ?', Date.today) task_actions = task.actions task_dates.each do |task_date| task_actions.each do |action| acc.push({ taskname: task.title, task_id: task.id, action_id: action.id, actionname: action.name, taskdate_id: task_date.id, taskdate: task_date.date, moduletype: action.actionmodule.try(:moduletype), moduletime: action.actionmodule.try(:time), moduledistance: action.actionmodule.try(:distance), user_id: invite.user_id, complete_status: action.complete_status(invite.id, task_date.id), challengetitle: invite.challenge.title, invite_id: invite.id, otherUsers: invite.otherUsers?(invite.id) }) end end end acc end render json: tasks end def showAllActionsForInvite invites = Invite.where(user_id: doorkeeper_token.resource_owner_id).where(id: params[:id]) tasks = invites.reduce([]) do |acc, invite| tasks = invite.challenge.tasks tasks.each do |task| logger.info "In task" task_dates = task.task_dates.where('date >= ?', Date.today) task_actions = task.actions task_dates.each do |task_date| task_actions.each do |action| acc.push({ taskname: task.title, task_id: task.id, action_id: action.id, actionname: action.name, taskdate_id: task_date.id, taskdate: task_date.date, moduletype: action.actionmodule.try(:moduletype), moduletime: action.actionmodule.try(:time), user_id: invite.user_id, complete_status: action.complete_status(invite.id, task_date.id), challengetitle: invite.challenge.title, invite_id: invite.id, otherUsers: invite.otherUsers?(invite.id) }) end end end acc end render json: tasks end def create # # Complete a challenge. Checks if the id's exist in the tables. # @p = params.permit(:invite_id, :task_date_id, :image, :description, :moduletype, :time, :distance) if Complete.where(invite_id: @p[:invite_id]).count > 0 && Complete.where(task_date_id: @p[:task_date_id]).count > 0 render json: { status: 400, message: "error" }.to_json else if Invite.where(id: @p[:invite_id]).count > 0 && TaskDate.where(id: @p[:task_date_id]).count > 0 complete = Complete.create(@p) if complete Activity.add_activity(doorkeeper_token.resource_owner_id, 'completed_task', complete.id) UserPoint.give_point(doorkeeper_token.resource_owner_id, 0) render status: :created, json: complete else render :status => 400, json: $ERROR_INFO end else render json: { status: 400, message: "error" }.to_json end end end def challengeprocess # # Show process over how many actions there have been completed. # @invites = Invite.where(user_id: doorkeeper_token.resource_owner_id, accepted: true) p @invites render json: @invites.map {|invite| { actions_completed: invite.completes.count, total_actions: invite.challenge.totals, challenge_id: invite.challenge.id, challenge_title: invite.challenge.title, creator: User.find(invite.challenge.user_id).username, creator_image: User.find(invite.challenge.user_id).profileimage.url(:thumb), creator_id: invite.challenge.user_id } } end def upload_complete_image @p = params.permit(:image_data, :id, :task_date_id, :invite_id) if Complete.exists?(id: @p[:id]) @complete = Complete.find(@p[:id]) image_data = @p[:image_data] respond_to do |format| if @complete.update_attributes(image: image_data) format.json { render :status => :ok, json: :updated } else format.json { render :status => 400 } end end end end def home_feed @p = params.permit(:user_id, :challenge_status) @completes = Complete.select('completes.created_at as complete_date', 'completes.description', 'completes.image', 'tasks.title AS task_title', 'actions.name', 'users.username as username', 'users.first_name as firstname', 'users.last_name as lastname', 'challenges.title AS challenge_title').joins('LEFT JOIN invites ON completes.invite_id = invites.id LEFT JOIN challenges ON invites.challenge_id = challenges.id LEFT JOIN users ON invites.user_id = users.id LEFT JOIN task_dates ON completes.task_date_id = task_dates.id LEFT JOIN tasks on task_dates.task_id = tasks.id LEFT JOIN actions on tasks.id = actions.task_id').where('invites.user_id = :val1 AND challenges.status = :val2', val1: @p[:user_id], val2: @p[:challenge_status]) render json: @completes end private def set_complete complete = Complete.find(params[:id]) render json: complete end end <file_sep>class Api::UserPointsController < ApplicationController before_action :doorkeeper_authorize!, except: [] skip_before_action :verify_authenticity_token before_action :set_user_points, only: [:show, :edit, :destroy] def create @p = params.permit(:points_type, :user_id) @point = UserPoint.create(@p) if @point render :status => :created, :json => @point else render :status => 400, json: [] end end def total_points @p = params.permit(:user_id) @points = UserPoint.where(user_id: @p[:user_id]).count if @points render json: @points else render :status => 400, json: 0 end end private def set_user_points user_point = UserPoint.find(params[:id]) render json: user_point end end <file_sep>class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable has_attached_file :profileimage, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :profileimage, content_type: /\Aimage\/.*\z/ has_attached_file :coverimage, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :coverimage, content_type: /\Aimage\/.*\z/ devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :invites has_many :challenges has_many :friends has_many :followers has_many :activities has_many :user_points has_and_belongs_to_many :activities accepts_nested_attributes_for :challenges accepts_nested_attributes_for :invites accepts_nested_attributes_for :friends accepts_nested_attributes_for :followers def friend_status?(myId, userId) if Friend.where(friend_one_id: myId, friend_two_id: userId, status: 1).count > 0 status = true elsif Friend.where(friend_two_id: myId, friend_one_id: userId, status: 1).count > 0 status = true else status = false end status end def follower_status?(myId, userId) if Follower.where(follower_one_id: myId, follower_two_id: userId).count > 0 status = true else status = false end status end def who_follow_me(myId) total_followers = Follower.where(follower_two_id: myId).count total_followers end def total_friends(myId) friend1 = Friend.where(friend_one_id: myId, status: 1).count friend2 = Friend.where(friend_two_id: myId, status: 1).count friend1 + friend2 end def who_i_follow(myId) total_followers = Follower.where(follower_one_id: myId).count total_followers end def pending_friend_status?(myId, userId) if Friend.where(friend_one_id: myId, friend_two_id: userId, status: 0).count > 0 status = true elsif Friend.where(friend_two_id: myId, friend_one_id: userId, status: 0).count > 0 status = true else status = false end status end def username?(id) user = User.find(id) user.username end def firstname?(id) user = User.find(id) user.first_name end def lastname?(id) user = User.find(id) user.last_name end def user_id?(id) user = User.find(id) user.id end def get_total_points(user_id) @points = 0 if UserPoint.where(user_id: user_id).count > 0 @points = UserPoint.where(user_id: user_id).count else @points end end end <file_sep>class ChangeFuckedReferences < ActiveRecord::Migration def change remove_column :action_dates, :tasks_id remove_column :actionmodules, :actions_id end end <file_sep>class Challenge < ActiveRecord::Base has_many :invites has_many :users, through: :invites belongs_to :user #lav alias creator has_many :tasks has_many :activities accepts_nested_attributes_for :tasks def totals total = 0; self.tasks.each do |t| count = t.task_dates.count * t.actions.count total = total + count end total end def as_json(options = {}) { id: self.id, title: self.title, prize: self.prize, status: self.status, tasks: self.tasks } end end <file_sep>module AuthHelper # Sessions # # Keeps track of session info and provides methods of loggin in, logging out etc # @see https://github.com/binarylogic/Authlogic class Session < Authlogic::Session::Base authenticate_with User end # Logs out a user def self.logout AuthHelper::Session.find.destroy end # Logins user via a user object # # @params User user def self.login(user) session = AuthHelper::Session.new(user) return session.save end end <file_sep>Rails.application.routes.draw do get 'landing/hello' devise_for :users use_doorkeeper # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end root "landing#new" resources :home do post "add_signup" => "home#add_signup" end resources :landing do post "add_signup" => "landing#add_signup" delete "deleteSession" => "landing#deleteSession" end resources :sessions, only: [:new, :create] delete '/logout', to: 'sessions#destroy', as: :logout resources :application resources :backend resources :data_handling delete 'backend/deleteSession/' => 'backend#deleteSession' delete 'application/deleteSession/' => 'application#deleteSession' #resources :landing_page namespace :api do get 'userchallenges/:id' => 'users#user_challenges', as: :users get 'showInviteWithChallengeName' => 'invites#showInviteWithChallengeName', as: :invites get 'showAcceptedChallenges/:id' => 'invites#showAcceptedChallenges' get 'friendRequests' => 'friends#friendRequests' get 'friends/:id' => 'friends#friends' delete 'enterpriceapp/getridofroomphoto/:id' => 'friends#getridofroomphoto' get 'followRequest' => 'followers#followRequest' get 'followers/:id' => 'followers#followers' get 'follows/:id' => 'followers#follows' post 'challenges/create_with_receivers' => 'challenges#create_with_receivers' get 'showAllActionForUser' => 'completes#showAllActionForUser' get 'showAllActionsForInvite/:id' => 'completes#showAllActionsForInvite' get 'challengeprocess' => 'completes#challengeprocess' get 'search_users/:key' => 'users#search_users' get 'user_stats/:id' => 'users#user_stats' get 'otherUsersForActions/:invite_id/:task_date_id' => 'users#otherUsersForActions' get 'news/:id' => 'users#news' get 'get_activities' => 'activities#get_activities' post 'upload_complete_image/:id' => 'completes#upload_complete_image' post 'upload_profile_image/:id' => 'users#upload_profile_image' post 'upload_cover_image/:id' => 'users#upload_cover_image' get 'remove_profile_image/:id' => 'users#remove_profile_image' get 'remove_cover_image/:id' => 'users#remove_cover_image' get 'profile_image_medium_url/:id' => 'users#profile_image_medium_url' get 'cover_image_medium_url/:id' => 'users#cover_image_medium_url' get 'show_friends/:id' => 'friends#show_friends' get 'home_feed' => 'completes#home_feed' get 'total_points' => 'user_points#total_points' delete 'destroy_all_locations/:id' => 'locations#destroy_all_locations' post 'create_all_locations' => 'locations#create_all_locations' resources :locations resources :user_points resources :invites resources :completes resources :friends resources :followers #resources :home resources :users do resources :challenges do resources :tasks do resources :actions do resources :task_dates end end end end resources :invites end end <file_sep>require 'test_helper' module Api class ChallengesControllerTest < ActionController::TestCase setup do @challenge = challenges(:one) @user = users(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:challenges) end test "should get new" do get :new assert_response :success end test "should create challenge" do assert_difference('Challenge.count') do post :create, challenge: {} end assert_redirected_to challenge_path(assigns(:challenge)) end test "should create challenge with receivers" do resp = nil assert_difference('Challenge.count') do challenge_data = { title: "Something", tasks_attributes: [ { title: "Task 1" }, { title: "Task 2", } ] } resp = post 'create_with_receivers', format: :json, challenge: challenge_data, receiver_ids: [@user.id] end assert_response :created data = JSON.parse(@response.body) assert_equal "Something", data["title"] assert_equal "Task 1", data["tasks"][0]["title"] assert_equal "Task 2", data["tasks"][1]["title"] invites = Invite.where(challenge_id: data["id"]) assert_not_empty invites assert_equal invites[0].user_id, @user.id end test "should show challenge" do get :show, id: @challenge assert_response :success end test "should get edit" do get :edit, id: @challenge assert_response :success end test "should update challenge" do patch :update, id: @challenge, challenge: {} assert_redirected_to challenge_path(assigns(:challenge)) end test "should destroy challenge" do assert_difference('Challenge.count', -1) do delete :destroy, id: @challenge end assert_redirected_to challenges_path end end end<file_sep>class RemoveActionDatesFromActions < ActiveRecord::Migration def change remove_column :actions, :action_dates_id end end <file_sep>class RenameActionsIdInActionDate < ActiveRecord::Migration def change rename_column :action_dates, :actions_id, :action_id end end <file_sep>class RemoveActionFromComplete < ActiveRecord::Migration def change remove_column :completes, :action_id end end <file_sep>class AddUserAsResourceOwner < ActiveRecord::Migration def change add_foreign_key :table_name, :users, column: :resource_owner_id end end <file_sep>class Api::ChallengesController < ApplicationController #before_action :doorkeeper_authorize! skip_before_action :verify_authenticity_token before_action :set_challenge, only: [:show, :edit, :update, :destroy] def index challenges = Challenge.all render json: challenges end def show end def create # Todo - Create challenge challenge = Challenge.create(challenge_params) if challenge render :status => :created, :json => challenge else render :status => 400 end end def update respond_to do |format| if challenge.update(challenge_params) render :status => :updated, :json => challenge else render :status => 400 end end end def destroy challenge.destroy respond_to do |format| msg = {:status => "ok", :message => "success", :html => "<b>...</b>"} format.json { render :json => msg } end end # Forventet json: # { # challenge: { # title: "Månedens program", # prize: "En tur i biografen" # tasks: [ # { # title: "sdflkjelr" # dates: [ "2016-01-01", "2016-02-01" ] # actions: [ # { # title: "sdiljfoier" # type: "sldkfjlier" # } # ] # } # ] # }, # receiver_ids: [ 12093809123, 123102983, 123098123 ] # } # def create_with_receivers challenge_params = params.require(:challenge).permit(:title, :prize, :status, :user_id, tasks: [ :id, :title, actions: [ :id, :name, actionmodule: [ :id, :moduletype, :time, :distance ] ], task_dates: [ :id, :date] ]) tasks = challenge_params.delete(:tasks).map do |task| task[:actions_attributes] = task.delete(:actions).map do |action| if action[:actionmodule].present? action[:actionmodule_attributes] = action.delete(:actionmodule) end action end task[:task_dates_attributes] = task.delete(:task_dates) task end challenge_params[:tasks_attributes] = tasks challenge_params.permit! receiver_ids = params.require(:receiver_ids) challenge = Challenge.create(challenge_params) unless challenge render status: :bad_request return end receiver_ids.each do |user_id| if challenge.user_id == user_id Invite.create(challenge_id: challenge.id, user_id: user_id, accepted: true) else Invite.create(challenge_id: challenge.id, user_id: user_id) end end render status: :created, json: challenge end private def set_challenge challenge = Challenge.find(params[:id]) render json: challenge end def challenge_params params.require(:challenge).permit(:title, :prize) end end <file_sep>class DataHandlingController < ApplicationController skip_before_action :verify_authenticity_token before_action :set_user, only: [:edit, :update, :destroy, :show] def index @users = User.all end def new @user = User.new end def show @user = User.find(params[:id]) end def destroy @user = User.find(params[:id]) @user.destroy redirect_to '/data_handling' #, error: "Brugeren blev slettet" end def update @user = User.find(params[:id]) if @user.update(user_params) redirect_to '/data_handling'#, notice: "Brugeren blev opdateret" else render :edit end end def edit @user = User.find(params[:id]) if @user.birthday.nil? @user.birthday = DateTime.now end end def create param = params.require(:user).permit(:first_name, :last_name, :username, :gender, :password, :created_at, :updated_at, :active, :phone, :email, :birthday, :weight) @user = User.create(param) if @user.save redirect_to '/data_handling' #, notice: "Brugeren blev oprettet" else render :new end end # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def user_params params.require(:user).permit(:email, :username, :first_name, :last_name, :isAdmin) end end <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) User.destroy_all Challenge.destroy_all Task.destroy_all TaskDate.destroy_all user = User.create!(first_name: "<NAME>", last_name: "Christensen", birthday: "29/01/1993", username: "fyren", phone: "22770695", email: "<EMAIL>", password: "<PASSWORD>", gender: "male", active: true) challenge = Challenge.create!(title: "Månedens program", prize: "En tur i biografen", user: user) task2 = Task.create!(title: "Tirsdag", challenge: challenge) action2 = Action.create!(name: "Aften", task: task2) TaskDate.create!(date: "2016-01-01", task: task2) Actionmodule.create!(text: "Løb 5 km", action:action2)<file_sep>class CreateFollowers < ActiveRecord::Migration def change create_table :followers do |t| t.integer :follower_one_id t.integer :follower_two_id t.integer :status t.timestamps null: false end add_index(:followers, :follower_one_id) add_index(:followers, :follower_two_id) end end <file_sep>class LandingPageController < ApplicationController skip_before_action :verify_authenticity_token before_action :set_signup, only: [:edit, :update, :destroy] def index end def show end def new end def create end def add_signup end private def set_params end def set_signup end end <file_sep>class Api::ActionmodulesController < ApplicationController end <file_sep>class Action < ActiveRecord::Base belongs_to :task has_one :actionmodule accepts_nested_attributes_for :actionmodule def as_json(options = {}) { id: self.id, name: self.name, actionmodule: self.actionmodule } end def action_module_type(action_id) type = '' if Action.find(action_id).present? @action = Action.find(action_id) if @action.actionmodule.present? type = @action.actionmodule.moduletype puts type.inspect end end type end def action_module_time(action_id) type = 0 if Action.find(action_id).present? @action = Action.find(action_id) if @action.actionmodule.present? type = @action.actionmodule.time end end type end def task_name_for_action(task_id) task_name = '' if Task.find_by_id(task_id).present? task_name = Task.find(task_id).title end task_name end def invite_id(user_id, challenge_id) c_id = 0 if Invite.find_by_user_id(user_id).present? && Invite.find_by_challenge_id(challenge_id).present? @invite = Invite.find_by(user_id: user_id, challenge_id: challenge_id) c_id = @invite.id end c_id end def invite_user_id(challenge_id) u_id = 0 if Challenge.find(challenge_id).present? @challenge = Challenge.find(challenge_id) if Invite.find_by_challenge_id(@challenge.id).present? @invite = Invite.find_by_challenge_id(@challenge.id) u_id = @invite.user_id end end u_id end def complete_status(invite_id, task_date_id) if Complete.find_by_invite_id(invite_id).present? && Complete.find_by_task_date_id(task_date_id).present? status = true else if TaskDate.find(task_date_id).date >= Date.today status = nil else status = false end end puts status.inspect puts invite_id.inspect puts task_date_id.inspect status end end <file_sep>class CreateActionmodules < ActiveRecord::Migration def change create_table :actionmodules do |t| t.integer :countertype #if 0 then up, if 1 then down t.integer :countertime t.string :text t.timestamps null: false end end end <file_sep>class AddDescriptionToCompletedTask < ActiveRecord::Migration def change add_column :completes, :description, :text, limit: 2200 end end <file_sep>class Activity < ActiveRecord::Base belongs_to :user belongs_to :task belongs_to :complete belongs_to :challenge belongs_to :friend belongs_to :follower belongs_to :action has_and_belongs_to_many :relevant_users, class_name: 'User' def task_name_for_activity(a_type, a_id) action_name = '' if Complete.exists?(a_id) && a_type == 'completed_task' @complete = Complete.find(a_id) @task_date = @complete.task_date @task = @task_date.task @actions = @task.actions @actions.find_each do |action| if action.task_id == @task_date.task_id action_name = action.name end end action_name else action_name end end def challenge_title_for_activity(a_id) challenge_title = '' if Invite.exists?(a_id) @invite = Invite.find(a_id) @challenge = Challenge.find(@invite.challenge_id) challenge_title = @challenge.title else challenge_title = '' end challenge_title end def self.add_activity(u_id, a_type, a_id) activity = Activity.create({user_id: u_id, activity_type: a_type, activity_id: a_id}) case activity.activity_type when 'started_following' @follower = Follower.find(activity.activity_id) activity.relevant_users << User.find(@follower.follower_two_id) when 'stopped_following' activity.relevant_users << User.find(activity.activity_id) when 'friend_request' @friend = Friend.find(activity.activity_id) activity.relevant_users << User.find(@friend.friend_two) when 'removed_friend_request' activity.relevant_users << User.find(activity.activity_id) when 'accepted_friend_request' @friend = Friend.find(activity.activity_id) activity.relevant_users << User.find(@friend.friend_one) when 'declined_friend' activity.relevant_users << User.find(activity.activity_id) when 'accepted_challenge' @invite_for_user = Invite.find(activity.activity_id) @challenge = Challenge.find(@invite_for_user.challenge_id) activity.relevant_users << User.find(@challenge.user_id) when 'declined_challenge' @invite_for_user = Invite.find(activity.activity_id) @challenge = Challenge.find(@invite_for_user.challenge_id) activity.relevant_users << User.find(@challenge.user_id) when 'uploaded_new_profile_image' @friends = Friend.where(status: 1).where('friend_one_id = :val1 OR friend_two_id = :val2', val1: u_id, val2: u_id) @friends.each do |friend| activity.relevant_users << User.find(friend.friend_id(friend.friend_one_id, friend.friend_two_id, u_id)) end when 'uploaded_new_cover_image' @friends = Friend.where(status: 1).where('friend_one_id = :val1 OR friend_two_id = :val2', val1: u_id, val2: u_id) @friends.each do |friend| activity.relevant_users << User.find(friend.friend_id(friend.friend_one_id, friend.friend_two_id, u_id)) end when 'completed_task' @complete = Complete.find(activity.activity_id) @invite_for_user = Invite.find(@complete.invite_id) @invites = Invite.where(challenge_id: @invite_for_user.challenge_id) @invites.each do |invite| if invite.user_id != activity.user_id activity.relevant_users << User.find(invite.user_id) end end else raise Exception.new('Ikkefsfrsf') end end end <file_sep>class CreateCompletes < ActiveRecord::Migration def change create_table :completes do |t| t.string :video t.string :image t.references :action t.references :invite t.timestamps null: false end end end
cb1bbf75a6bf22f45f6377cd20f868928ec2454c
[ "Ruby" ]
63
Ruby
AndersBChristensen/Challyme_api
88c0b2da60b8d74ef5a08c5206a1dfe6e17e4507
5664ee5f2bfc5113aad65904ea83ae6f602eb04d
refs/heads/master
<repo_name>KTJL/Sanjuan<file_sep>/Sanjuan/main.c #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include "linuxlist.h" #define NONE "\033[m" #define RED "\033[0;32;31m" #define LIGHT_RED "\033[1;31m" #define GREEN "\033[0;32;32m" #define LIGHT_GREEN "\033[1;32m" #define BLUE "\033[0;32;34m" #define LIGHT_BLUE "\033[1;34m" #define DARY_GRAY "\033[1;30m" #define CYAN "\033[0;36m" #define LIGHT_CYAN "\033[1;36m" #define PURPLE "\033[0;35m" #define LIGHT_PURPLE "\033[1;35m" #define BROWN "\033[0;33m" #define YELLOW "\033[1;33m" LIST_HEAD(player_list_head_1); LIST_HEAD(player_list_head_2); LIST_HEAD(player_list_head_3); LIST_HEAD(player_list_head_4); LIST_HEAD(build_list_head_1); LIST_HEAD(build_list_head_2); LIST_HEAD(build_list_head_3); LIST_HEAD(build_list_head_4); int32_t game = 1; int32_t playernum = 0; int32_t roundnum = 1; int main(void) { int32_t w = welcome(); while(w == 1){ printf("----------\n"); w = welcome(); } //遊戲開啟 int32_t tradecards[5] = {0}; int8_t trademk = 0; int32_t level = 1; if(w == 2) { printf("遊戲開始!( Ctrl+C 可隨時結束遊戲:) )\n\n"); printf(RED"請選擇遊戲難度:\n1) 普通版(無時間限制)\n2) 燒腦版(操作限時30秒)\n(請輸入數字進行選擇):"NONE); while(scanf("%d", &level) != 1 || level < 1 || level > 2){ char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!(請輸入數字進行選擇):"); } srand(time(0)); playernum = rand()%4; if(playernum == 0) playernum = 4; printf(YELLOW"\n\n你的號碼為: %d號\n\n"NONE, playernum); start(&player_list_head_1, &player_list_head_2, &player_list_head_3, &player_list_head_4, &build_list_head_1, &build_list_head_2, &build_list_head_3, &build_list_head_4);//開始 for(int32_t i = 0;i<5;i++){//洗價物牌 tradecards[i] = rand()%5; while(((trademk >> tradecards[i]) & 1) == 1){ tradecards[i] = rand()%5; } trademk = trademk|(1 << tradecards[i]); //printf("tradetest: %d\n", tradecards[i]); } sleep(3); } else if(w == 3) return 0;//結束 /*test for(int32_t i = 0;i<4;i++) { gameround(roundnum, playernum, tradecards[roundnum%5], &player_list_head_1, &player_list_head_2, &player_list_head_3, &player_list_head_4, &build_list_head_1, &build_list_head_2, &build_list_head_3, &build_list_head_4); roundnum++; } */ while(game) { game = gameround(roundnum, playernum, tradecards[roundnum%5], &player_list_head_1, &player_list_head_2, &player_list_head_3, &player_list_head_4, &build_list_head_1, &build_list_head_2, &build_list_head_3, &build_list_head_4, level); if(game == 1) roundnum++; } printf(RED"\n\n\n遊戲結束!結算分數!\n"NONE); int32_t score[4] = {0}; int32_t commod[4] = {0}; struct list_head *listptr = NULL; score[0] = score_count(&build_list_head_1, playernum == 1); commod[0] = commodcount(&build_list_head_1); printf("1 號玩家得分: %d分/ %d個貨物\n---\n", score[0], commod[0]); score[1] = score_count(&build_list_head_2, playernum == 2); commod[0] = commodcount(&build_list_head_2); printf("2 號玩家得分: %d分/ %d個貨物\n---\n", score[1], commod[1]); score[2] = score_count(&build_list_head_3, playernum == 3); commod[0] = commodcount(&build_list_head_3); printf("3 號玩家得分: %d分/ %d個貨物\n---\n", score[2], commod[2]); score[3] = score_count(&build_list_head_4, playernum == 4); commod[0] = commodcount(&build_list_head_4); printf("4 號玩家得分: %d分/ %d個貨物\n---\n", score[3], commod[3]); int32_t winner[4] = {1,2,3,4}; for(int32_t i = 0;i<4;i++){ for(int32_t j = i;j<4;j++){ if(score[i] < score[j]){ int32_t tmp = winner[i]; winner[i] = winner[j]; winner[j] = tmp; } else if(score[i] == score[j]){ if(commod[i]<commod[j]){ int32_t tmp = winner[i]; winner[i] = winner[j]; winner[j] = tmp; } } } } printf(YELLOW"!!!!最終結果!!!!\n"NONE); for(int32_t i = 0;i<4;i++){ printf("第 %d 名: %d 號玩家", i+1, winner[i]); for(int32_t j = i+1;j<4;j++){ if(score[i] == score[j] && commod[i] == commod[j]){ printf("、%d 號玩家", winner[j]); i++; } else{ printf("\n"); break; } } } delAllplayercard(&player_list_head_1); delAllplayercard(&build_list_head_1); delAllplayercard(&player_list_head_2); delAllplayercard(&build_list_head_2); delAllplayercard(&player_list_head_3); delAllplayercard(&build_list_head_3); delAllplayercard(&player_list_head_4); delAllplayercard(&build_list_head_4); return 0; }<file_sep>/Sanjuan/Card.h #pragma once #include <stdio.h> #include <stdint.h> enum role_card { Builder, Producer, Trader, Councilor, Prospector, }; typedef struct Building { int32_t id; char name[128]; int32_t fee; int32_t score; int32_t num; char tip[5096]; }__attribute__((packed)) _sbuild; typedef struct _cost_card { int32_t value[5]; }cost_card; cost_card valuecards[5] = {{1,2,2,3,3}, {1,1,2,2,3}, {1,2,2,2,3}, {1,1,1,2,2}, {1,1,2,2,2}}; _sbuild building[29] = { {1,"染料廠", 1, 1, 10, "可生產一份貨物"}, {2,"蔗糖廠", 2, 1, 8, "可生產一份貨物"}, {3,"菸草廠", 3, 2, 8, "可生產一份貨物"}, {4,"咖啡廠", 4, 2, 8, "可生產一份貨物"}, {5,"白銀廠", 5, 3, 8, "可生產一份貨物"}, {6,"塔樓", 3, 2, 3, "各回合玩家計算手牌前,已打出此張卡牌的玩家手牌上限可增加至12張"}, {7,"禮拜堂", 3, 2, 3, "各回合玩家計算手牌前,已打出此張卡牌的玩家可挑選其中1張手牌正面朝下置於此張卡牌底下"}, {8,"鐵匠鋪", 1, 1, 3, "建築師階段時,已打出此張卡牌的玩家在建造生產建築物時可少支付1張手牌"}, {9,"救濟院", 2, 1, 3, "建築師階段時,已打出此張卡牌的玩家在行動完成後,若玩家手牌張數不多於1張時,可從卡牌堆抽取1張卡牌加入手牌"}, {10,"黑市", 2, 1, 3, "建築師階段時,已打出此張卡牌的玩家最多可用2個貨品(即置於自家生產建築下方的卡牌)取代支付費用(手牌),1個貨品只能替代1張手牌"}, {11,"起重機", 2, 1, 3, "建築師階段時,已打出此張卡牌的玩家可支付興建新建築物與原先擁有舊建築物的費用差額,將新建築物蓋在舊建築物的上方。被覆蓋的卡牌不計分亦無效能,被覆蓋的生產建築其上方貨品則須棄置,被覆蓋的禮拜堂其上方卡牌仍可保留計分"}, {12,"木工場", 3, 2, 3, "建築師階段時,已打出此張卡牌的玩家在建造特殊建築物時可從卡牌堆上方抽取1張卡牌"}, {13,"採石場", 4, 2, 3, "建築師階段時,已打出此張卡牌的玩家在建造特殊建築物時可少支付1張手牌"}, {14,"水井", 2, 1, 3, "生產者階段時,已打出此張卡牌的玩家若生產2個以上貨品,可從卡牌堆上方抽取1張卡牌加入手牌"}, {15,"溝渠", 3, 2, 3, "生產者階段時,已打出此張卡牌的玩家可多生產1個貨品"}, {16,"攤販", 2, 1, 3, "商人階段時,已打出此張卡牌的玩家若賣出2個以上貨品,可從卡牌堆上方抽取1張卡牌加入手牌"}, {17,"市場", 4, 2, 3, "商人階段時,已打出此張卡牌的玩家在行動完成後,可從卡牌堆上方抽取1張卡牌加入手牌"}, {18,"交易所", 2, 1, 3, "商人階段時,已打出此張卡牌的玩家可多賣出1個貨品"}, {19,"檔案館", 1, 1, 3, "市長階段時,已打出此張卡牌的玩家在挑選卡牌時,可將卡牌堆上方抽取的卡牌全數加入手牌後再進行挑選,並將挑選外的其餘卡牌丟棄"}, {20,"辦公處", 3, 2, 3, "市長階段時,已打出此張卡牌的玩家從卡牌堆上抽取卡牌後,挑選其中2張加入手牌"}, {21,"金礦坑", 1, 1, 3, "淘金者階段時,已打出此張卡牌的玩家可在行動完成後,從卡牌堆上方翻開4張卡牌,若4張卡牌的費用皆不相同,可挑選其中1張加入手牌。但只要任2張出現相同費用,則須全數棄置"}, {22,"圖書館", 5, 3, 3, "\n已打出此張卡牌的玩家在下列各階段行使特殊行動時,可提升其特殊行動能力\n\n建築師階段時,已打出此張卡牌的玩家建造建築物時可少支付2張手牌\n\n生產者階段時,已打出此張卡牌的玩家最多可生產3個貨品(即從卡牌堆上方抽取3張卡牌置於自家生產建築下方)\n\n商人階段時,已打出此張卡牌的玩家最多可賣出3個貨品(即最多可丟棄3張置於自家生產建築下方的卡牌,並從卡牌堆上方抽取對應貨品價格數量張數的卡牌加入手牌)\n\n市長階段時,已打出此張卡牌的玩家可從卡牌堆上方抽取8張卡牌,挑選其中1張加入手牌\n\n淘金者階段時,已打出此張卡牌的玩家可從卡牌堆上方抽取2張卡牌加入手牌"}, {23,"雕鑄像紀念碑", 3, 3, 3, "無特殊效能"}, {24,"勝利柱紀念碑", 4, 4, 3, "無特殊效能"}, {25,"英雄像紀念碑", 5, 5, 3, "無特殊效能"}, {26,"同業會館", 6, 0, 2, "遊戲結束時,已打出此張卡牌的玩家每擁有1棟生產建築物可額外獲得2分"}, {27,"市政廳", 6, 0, 2, "遊戲結束時,已打出此張卡牌的玩家每擁有1棟特殊建築物(包括此張卡牌)可額外獲得1分"}, {28,"凱旋門", 6, 0, 2, "遊戲結束時,已打出此張卡牌的玩家若擁有1種紀念碑卡可額外獲得4分,擁有2種紀念碑卡可額外獲得6分,擁有3種紀念碑卡可額外獲得8分"}, {29,"宮殿", 6, 0, 2, "遊戲結束時,已打出此張卡牌的玩家可額外獲得該玩家總分的四分之一分數(採無條件捨去)"} }; <file_sep>/Sanjuan/makefile all:Play.o gcc -pthread -lm main.c Play.o -o main Play: gcc -c -pthread -lm Play.c -o Play.o <file_sep>/Sanjuan/Play.c #include "Play.h" #define Player if(player == 1) #define Robot if(player != 1) #define NONE "\033[m" #define RED "\033[0;32;31m" #define LIGHT_RED "\033[1;31m" #define GREEN "\033[0;32;32m" #define LIGHT_GREEN "\033[1;32m" #define BLUE "\033[0;32;34m" #define LIGHT_BLUE "\033[1;34m" #define DARY_GRAY "\033[1;30m" #define CYAN "\033[0;36m" #define LIGHT_CYAN "\033[1;36m" #define PURPLE "\033[0;35m" #define LIGHT_PURPLE "\033[1;35m" #define BROWN "\033[0;33m" #define YELLOW "\033[1;33m" int32_t alrm = 1; int32_t welcome() { printf("歡迎遊玩聖胡安桌遊\n"); printf("1)遊戲規則\n2)開始遊戲\n3)退出遊戲\n(請輸入數字進行選擇):"); int8_t option = 0; scanf("%hhd", &option); switch(option) { case 1: system("xdg-open rules.pdf"); case 2: return 2; break; case 3: return 3; break; default: printf("無效輸入!\n"); char c; while (( c = getchar()) != EOF && c != '\n'){} return 1; break; } } void start(struct list_head *player_list_head_1, struct list_head *player_list_head_2, struct list_head *player_list_head_3, struct list_head *player_list_head_4, struct list_head *build_list_head_1, struct list_head *build_list_head_2, struct list_head *build_list_head_3, struct list_head *build_list_head_4) { //發染料廠卡 for(int32_t i = 0;i<4;i++) { _splayer_card *newcard = add_newcard(&building[0]); if(i == 0) list_add(&(newcard->list), build_list_head_1); else if(i == 1) list_add(&(newcard->list), build_list_head_2); else if(i == 2) list_add(&(newcard->list), build_list_head_3); else if(i == 3) list_add(&(newcard->list), build_list_head_4); (&building[0])->num --; //printf("%d\n", (&building[0])->num); } //各抽4張 srand(time(0)); for(int32_t i = 0;i<4;i++) {//printf("%d\n", i); for(int32_t j = 0;j<4;j++) { _sbuild *drawcard = draw_card(); _splayer_card *newcard = add_newcard(drawcard); if(i == 0) list_add(&(newcard->list), player_list_head_1); else if(i == 1) list_add(&(newcard->list), player_list_head_2); else if(i == 2) list_add(&(newcard->list), player_list_head_3); else if(i == 3) list_add(&(newcard->list), player_list_head_4); drawcard->num --; } } return; } _splayer_card *add_newcard(_sbuild *building)//加卡 { _splayer_card *newcard = malloc(sizeof(_splayer_card)); newcard->id = building->id; strncpy(newcard->name, building->name, strlen(building->name)); newcard->fee = building->fee; newcard->score = building->score; strncpy(newcard->tip, building->tip, strlen(building->tip)); if((building->id > 0 && building->id < 6) || building->id == 7) { newcard->commodity = 0; } else { newcard->commodity = -1; } return newcard; } _sbuild *draw_card()//抽卡 { int32_t draw = 1; int32_t lucky_num = 0; _sbuild *drawcard; while(draw == 1) { lucky_num = rand()%29; //printf("%d ", lucky_num); if((&building[lucky_num])->num == 0) continue; else if((&building[lucky_num])->num > 0) draw = 0; } drawcard = &building[lucky_num]; //printf("抽卡測:%s\n", drawcard->name); return drawcard; } int32_t gameround(int32_t roundnum, const int32_t playernum, const int32_t tradecardnum, struct list_head *player_list_head_1, struct list_head *player_list_head_2, struct list_head *player_list_head_3, struct list_head *player_list_head_4, struct list_head *build_list_head_1, struct list_head *build_list_head_2, struct list_head *build_list_head_3, struct list_head *build_list_head_4, const int32_t level) { printf("-----------------\nRound %d\n\n", roundnum); int32_t mayor = roundnum%4; if(mayor == 0) { mayor = 4; printf("總督: %d號\n", mayor); mayor = 0; } else printf("總督: %d號\n", mayor); //檢查牌數、禮拜堂 if(roundnum >= 2) { for(int32_t i = 0;i<4;i++){ printf("檢查玩家手牌數量...\n"); switch(i){ case 0: Chapel(player_list_head_4, build_list_head_4, playernum%4 == i%4); Tower(player_list_head_4, build_list_head_4, playernum%4 == i%4); break; case 1: Chapel(player_list_head_1, build_list_head_1, playernum%4 == i%4); Tower(player_list_head_1, build_list_head_1, playernum%4 == i%4); break; case 2: Chapel(player_list_head_2, build_list_head_2, playernum%4 == i%4); Tower(player_list_head_2, build_list_head_2, playernum%4 == i%4); break; case 3: Chapel(player_list_head_3, build_list_head_3, playernum%4 == i%4); Tower(player_list_head_3, build_list_head_3, playernum%4 == i%4); break; default: break; } sleep(2); } } //選角、執行 uint32_t player_role[4] = {0}; uint32_t chose_role = 0; uint32_t *choseptr = &chose_role; for(int32_t i = roundnum;i<roundnum+4;i++) { //選角(4號->i%4 = 0) if(end_game(build_list_head_1, build_list_head_2, build_list_head_3, build_list_head_4) == 0) return 0;//end? print_table(player_list_head_1, player_list_head_2, player_list_head_3, player_list_head_4, build_list_head_1, build_list_head_2, build_list_head_3, build_list_head_4, playernum);//印牌桌 printf(">>>>>\n"); if(playernum%4 == i%4){//印玩家手牌 printf(BLUE"你的手牌:\n"NONE); switch(playernum){ case 1: print_handcard(player_list_head_1, 1); break; case 2: print_handcard(player_list_head_2, 1); break; case 3: print_handcard(player_list_head_3, 1); break; case 4: print_handcard(player_list_head_4, 1); break; default: printf("ERR!\n"); break; } } player_role[i%4] = choose_role(choseptr, playernum%4 == i%4); chose_role = chose_role | (1 << player_role[i%4]); if(player_role[i%4]-1 == Builder) { for(int32_t j = i%4;j < (i%4) + 4;j++) { if(end_game(build_list_head_1, build_list_head_2, build_list_head_3, build_list_head_4) == 0) return 0;//end? if(j%4 == 0)printf("---\n 4 號玩家\n"); else printf("---\n %d 號玩家\n", j%4); if(playernum%4 != j%4) sleep(5); if(level == 2 && playernum%4 == j%4){ pthread_t thread_timer, thread_func; lv2 tmp; alrm = 1; if(j%4 == 0 && list_empty(player_list_head_4) == 0){ tmp.sp = j == i%4; tmp.player = playernum%4 == j%4; tmp.player_list_head = player_list_head_4; tmp.build_list_head = build_list_head_4;} else if(j%4 == 1 && list_empty(player_list_head_1) == 0){ tmp.sp = j == i%4; tmp.player = playernum%4 == j%4; tmp.player_list_head = player_list_head_1; tmp.build_list_head = build_list_head_1;} else if(j%4 == 2 && list_empty(player_list_head_2) == 0){ tmp.sp = j == i%4; tmp.player = playernum%4 == j%4; tmp.player_list_head = player_list_head_2; tmp.build_list_head = build_list_head_2;} else if(j%4 == 3 && list_empty(player_list_head_3) == 0){ tmp.sp = j == i%4; tmp.player = playernum%4 == j%4; tmp.player_list_head = player_list_head_3; tmp.build_list_head = build_list_head_3;} pthread_create(&thread_timer, NULL, timer, NULL); pthread_create(&thread_func,NULL, Builder_func2, (void *)&tmp); while(alrm){sleep(1);} pthread_cancel(thread_func); pthread_cancel(thread_timer); } if(level == 1 || (level == 2 && playernum%4 != j%4)){ if(j%4 == 0 && list_empty(player_list_head_4) == 0) Builder_func(j == i%4, playernum%4 == j%4, player_list_head_4, build_list_head_4); else if(j%4 == 1 && list_empty(player_list_head_1) == 0) Builder_func(j == i%4, playernum%4 == j%4, player_list_head_1, build_list_head_1); else if(j%4 == 2 && list_empty(player_list_head_2) == 0) Builder_func(j == i%4, playernum%4 == j%4, player_list_head_2, build_list_head_2); else if(j%4 == 3 && list_empty(player_list_head_3) == 0) Builder_func(j == i%4, playernum%4 == j%4, player_list_head_3, build_list_head_3); } } } else if(player_role[i%4]-1 == Producer) { for(int32_t j = i%4;j < (i%4) + 4;j++) { if(j%4 == 0)printf("---\n 4 號玩家\n"); else printf("---\n %d 號玩家\n", j%4); if(playernum%4 != j%4) sleep(5); int32_t facnum = 0; if(j %4 == 0){ struct list_head *listptr = NULL; list_for_each(listptr, build_list_head_4)//是否有工廠 { _splayer_card *cptr = list_entry(listptr, _splayer_card, list); if(cptr->id <= 5 && cptr->commodity == 0) facnum ++; } if(facnum != 0){ if(level == 2 && playernum%4 == j%4){ pthread_t thread_timer, thread_func; alrm = 1; lv2 tmp; tmp.sp = j == i%4; tmp.player = playernum%4 == j%4; tmp.player_list_head = player_list_head_4; tmp.build_list_head = build_list_head_4; tmp.facnum = facnum; pthread_create(&thread_timer, NULL, timer, NULL); pthread_create(&thread_func,NULL, Producer_func2, (void *)&tmp); while(alrm){sleep(1);} pthread_cancel(thread_func); pthread_cancel(thread_timer); } else Producer_func(j == i%4, playernum%4 == j%4, player_list_head_4, build_list_head_4, facnum); } } else if(j %4 == 1){ struct list_head *listptr = NULL; list_for_each(listptr, build_list_head_1)//是否有工廠 { _splayer_card *cptr = list_entry(listptr, _splayer_card, list); if(cptr->id <= 5 && cptr->commodity == 0) facnum ++; } if(facnum != 0){ if(level == 2 && playernum%4 == j%4){ pthread_t thread_timer, thread_func; alrm = 1; lv2 tmp; tmp.sp = j == i%4; tmp.player = playernum%4 == j%4; tmp.player_list_head = player_list_head_1; tmp.build_list_head = build_list_head_1; tmp.facnum = facnum; pthread_create(&thread_timer, NULL, timer, NULL); pthread_create(&thread_func,NULL, Producer_func2, (void *)&tmp); while(alrm){sleep(1);} pthread_cancel(thread_func); pthread_cancel(thread_timer); } else Producer_func(j == i%4, playernum%4 == j%4, player_list_head_1, build_list_head_1, facnum); } } else if(j %4 == 2){ struct list_head *listptr = NULL; list_for_each(listptr, build_list_head_2)//是否有工廠 { _splayer_card *cptr = list_entry(listptr, _splayer_card, list); if(cptr->id <= 5 && cptr->commodity == 0) facnum ++; } if(facnum != 0){ if(level == 2 && playernum%4 == j%4){ pthread_t thread_timer, thread_func; alrm = 1; lv2 tmp; tmp.sp = j == i%4; tmp.player = playernum%4 == j%4; tmp.player_list_head = player_list_head_2; tmp.build_list_head = build_list_head_2; tmp.facnum = facnum; pthread_create(&thread_timer, NULL, timer, NULL); pthread_create(&thread_func,NULL, Producer_func2, (void *)&tmp); while(alrm){sleep(1);} pthread_cancel(thread_func); pthread_cancel(thread_timer); } else Producer_func(j == i%4, playernum%4 == j%4, player_list_head_2, build_list_head_2, facnum); } } else if(j %4 == 3){ struct list_head *listptr = NULL; list_for_each(listptr, build_list_head_3)//是否有工廠 { _splayer_card *cptr = list_entry(listptr, _splayer_card, list); if(cptr->id <= 5 && cptr->commodity == 0) facnum ++; } if(facnum != 0){ if(level == 2 && playernum%4 == j%4){ pthread_t thread_timer, thread_func; alrm = 1; lv2 tmp; tmp.sp = j == i%4; tmp.player = playernum%4 == j%4; tmp.player_list_head = player_list_head_3; tmp.build_list_head = build_list_head_3; tmp.facnum = facnum; pthread_create(&thread_timer, NULL, timer, NULL); pthread_create(&thread_func,NULL, Producer_func2, (void *)&tmp); while(alrm){sleep(1);} pthread_cancel(thread_func); pthread_cancel(thread_timer); } else Producer_func(j == i%4, playernum%4 == j%4, player_list_head_3, build_list_head_3, facnum); } } } } else if(player_role[i%4]-1 == Trader) { printf(RED"價格表: "); for(int32_t k = 0;k<5;k++){ printf("%d ", valuecards[tradecardnum].value[k]); } printf("\n"NONE); for(int32_t j = i%4;j < (i%4) + 4;j++) { if(j%4 == 0)printf("---\n 4 號玩家\n"); else printf("---\n %d 號玩家\n", j%4); if(playernum%4 != j%4) sleep(5); int32_t commodnum = 0; if(j %4 == 0){ struct list_head *listptr = NULL; list_for_each(listptr, build_list_head_4)//是否有貨物 { _splayer_card *cptr = list_entry(listptr, _splayer_card, list); if(cptr->commodity == 1) commodnum ++; } if(commodnum != 0){ if(level == 2 && playernum%4 == j%4){ pthread_t thread_timer, thread_func; alrm = 1; lv2 tmp; tmp.sp = j == i%4; tmp.player = playernum%4 == j%4; tmp.player_list_head = player_list_head_4; tmp.build_list_head = build_list_head_4; tmp.commodnum = commodnum; tmp.tradercardnum = tradecardnum; pthread_create(&thread_timer, NULL, timer, NULL); pthread_create(&thread_func,NULL, Trader_func2, (void *)&tmp); while(alrm){sleep(1);} pthread_cancel(thread_func); pthread_cancel(thread_timer); } else Trader_func(j == i%4, playernum%4 == j%4, tradecardnum, player_list_head_4, build_list_head_4, commodnum); } } else if(j %4 == 1){ struct list_head *listptr = NULL; list_for_each(listptr, build_list_head_1)//是否有貨物 { _splayer_card *cptr = list_entry(listptr, _splayer_card, list); if(cptr->commodity == 1) commodnum ++; } if(commodnum != 0){ if(level == 2 && playernum%4 == j%4){ pthread_t thread_timer, thread_func; alrm = 1; lv2 tmp; tmp.sp = j == i%4; tmp.player = playernum%4 == j%4; tmp.player_list_head = player_list_head_1; tmp.build_list_head = build_list_head_1; tmp.commodnum = commodnum; tmp.tradercardnum = tradecardnum; pthread_create(&thread_timer, NULL, timer, NULL); pthread_create(&thread_func,NULL, Trader_func2, (void *)&tmp); while(alrm){sleep(1);} pthread_cancel(thread_func); pthread_cancel(thread_timer); } else Trader_func(j == i%4, playernum%4 == j%4, tradecardnum, player_list_head_1, build_list_head_1, commodnum); } } else if(j %4 == 2){ struct list_head *listptr = NULL; list_for_each(listptr, build_list_head_2)//是否有貨物 { _splayer_card *cptr = list_entry(listptr, _splayer_card, list); if(cptr->commodity == 1) commodnum ++; } if(commodnum != 0){ if(level == 2 && playernum%4 == j%4){ pthread_t thread_timer, thread_func; alrm = 1; lv2 tmp; tmp.sp = j == i%4; tmp.player = playernum%4 == j%4; tmp.player_list_head = player_list_head_2; tmp.build_list_head = build_list_head_2; tmp.commodnum = commodnum; tmp.tradercardnum = tradecardnum; pthread_create(&thread_timer, NULL, timer, NULL); pthread_create(&thread_func,NULL, Trader_func2, (void *)&tmp); while(alrm){sleep(1);} pthread_cancel(thread_func); pthread_cancel(thread_timer); } else Trader_func(j == i%4, playernum%4 == j%4, tradecardnum, player_list_head_2, build_list_head_2, commodnum); } } else if(j %4 == 3){ struct list_head *listptr = NULL; list_for_each(listptr, build_list_head_3)//是否有貨物 { _splayer_card *cptr = list_entry(listptr, _splayer_card, list); if(cptr->commodity == 1) commodnum ++; } if(commodnum != 0){ if(level == 2 && playernum%4 == j%4){ pthread_t thread_timer, thread_func; alrm = 1; lv2 tmp; tmp.sp = j == i%4; tmp.player = playernum%4 == j%4; tmp.player_list_head = player_list_head_3; tmp.build_list_head = build_list_head_3; tmp.commodnum = commodnum; tmp.tradercardnum = tradecardnum; pthread_create(&thread_timer, NULL, timer, NULL); pthread_create(&thread_func,NULL, Trader_func2, (void *)&tmp); while(alrm){sleep(1);} pthread_cancel(thread_func); pthread_cancel(thread_timer); } else Trader_func(j == i%4, playernum%4 == j%4, tradecardnum, player_list_head_3, build_list_head_3, commodnum); } } } } else if(player_role[i%4]-1 == Councilor) { for(int32_t j = i%4;j < (i%4) + 4;j++) { if(j%4 == 0)printf("---\n 4 號玩家\n"); else printf("---\n %d 號玩家\n", j%4); if(playernum%4 != j%4) sleep(5); if(level == 2 && playernum%4 == j%4){ pthread_t thread_timer, thread_func; lv2 tmp; alrm = 1; if(j%4 == 0 && list_empty(player_list_head_4) == 0){ tmp.sp = j == i%4; tmp.player = playernum%4 == j%4; tmp.player_list_head = player_list_head_4; tmp.build_list_head = build_list_head_4;} else if(j%4 == 1 && list_empty(player_list_head_1) == 0){ tmp.sp = j == i%4; tmp.player = playernum%4 == j%4; tmp.player_list_head = player_list_head_1; tmp.build_list_head = build_list_head_1;} else if(j%4 == 2 && list_empty(player_list_head_2) == 0){ tmp.sp = j == i%4; tmp.player = playernum%4 == j%4; tmp.player_list_head = player_list_head_2; tmp.build_list_head = build_list_head_2;} else if(j%4 == 3 && list_empty(player_list_head_3) == 0){ tmp.sp = j == i%4; tmp.player = playernum%4 == j%4; tmp.player_list_head = player_list_head_3; tmp.build_list_head = build_list_head_3;} pthread_create(&thread_timer, NULL, timer, NULL); pthread_create(&thread_func,NULL, Councilor_func2, (void *)&tmp); while(alrm){sleep(1);} pthread_cancel(thread_func); pthread_cancel(thread_timer); } if(level == 1 || (level == 2 && playernum%4 != j%4)){ if(j%4 == 0) Councilor_func(j == i%4, playernum%4 == j%4, player_list_head_4, build_list_head_4); else if(j%4 == 1) Councilor_func(j == i%4, playernum%4 == j%4, player_list_head_1, build_list_head_1); else if(j%4 == 2) Councilor_func(j == i%4, playernum%4 == j%4, player_list_head_2, build_list_head_2); else if(j%4 == 3) Councilor_func(j == i%4, playernum%4 == j%4, player_list_head_3, build_list_head_3);} } } else if(player_role[i%4]-1 == Prospector) { if(playernum%4 != i%4) sleep(5); if(level == 2 && playernum%4 == i%4){ pthread_t thread_timer, thread_func; lv2 tmp; alrm = 1; if(i%4 == 0 && list_empty(player_list_head_4) == 0){ tmp.player = playernum%4 == i%4; tmp.player_list_head = player_list_head_4; tmp.build_list_head = build_list_head_4;} else if(i%4 == 1 && list_empty(player_list_head_1) == 0){ tmp.player = playernum%4 == i%4; tmp.player_list_head = player_list_head_1; tmp.build_list_head = build_list_head_1;} else if(i%4 == 2 && list_empty(player_list_head_2) == 0){ tmp.player = playernum%4 == i%4; tmp.player_list_head = player_list_head_2; tmp.build_list_head = build_list_head_2;} else if(i%4 == 3 && list_empty(player_list_head_3) == 0){ tmp.player = playernum%4 == i%4; tmp.player_list_head = player_list_head_3; tmp.build_list_head = build_list_head_3;} pthread_create(&thread_timer, NULL, timer, NULL); pthread_create(&thread_func,NULL, Prospector_func2, (void *)&tmp); while(alrm){sleep(1);} pthread_cancel(thread_func); pthread_cancel(thread_timer); } if(level == 1 || (level == 2 && playernum%4 != i%4)){ if(i%4 == 0) Prospector_func( playernum%4 == i%4, player_list_head_4, build_list_head_4); else if(i%4 == 1) Prospector_func( playernum%4 == i%4, player_list_head_1, build_list_head_1); else if(i%4 == 2) Prospector_func( playernum%4 == i%4, player_list_head_2, build_list_head_2); else if(i%4 == 3) Prospector_func( playernum%4 == i%4, player_list_head_3, build_list_head_3); } } } if(end_game(build_list_head_1, build_list_head_2, build_list_head_3, build_list_head_4) == 0) return 0;//end? return 1; } void Chapel(struct list_head *player_list_head, struct list_head *build_list_head, const int32_t player){ int32_t chapel = 0; _splayer_card *cptr = NULL; struct list_head *listptr = NULL; list_for_each(listptr, build_list_head){ cptr = list_entry(listptr, _splayer_card, list); if(cptr->id == 7){ chapel = 1; break; } } if(chapel == 1 && print_handcard(player_list_head, 0) > 0){ int8_t option = 0; Player{ printf("\n你有禮拜堂!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[6].tip); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有禮拜堂!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[6].tip); } } Robot{ option = rand()%2 + 1; } if(option == 1){ lost_card(player_list_head, NULL, player); cptr->vicpoint ++; printf("使用了禮拜堂!\n"); } } return; } void Tower(struct list_head *player_list_head, struct list_head *build_list_head, const int32_t player){ int32_t tower = 0; struct list_head *listptr = NULL; list_for_each(listptr, build_list_head){ _splayer_card *cptr = list_entry(listptr, _splayer_card, list); if(cptr->id == 6){ tower = 1; break; } } if(tower == 1){ int32_t count = print_handcard(player_list_head, 0) - 12; if(count > 0){ printf("手牌超過12張!請丟棄多餘手牌!\n"); for(int32_t i = 0;i < count;i++){ lost_card(player_list_head, NULL, player); } } } else if(tower == 0){ int32_t count = print_handcard(player_list_head, 0) - 7; if(count > 0){ printf("手牌超過7張!請丟棄多餘手牌!\n"); for(int32_t i = 0;i < count;i++){ lost_card(player_list_head, NULL, player); } } } return; } uint32_t choose_role(uint32_t *choseptr, uint32_t player)//選角 { uint32_t role = 0; if(player == 1) { printf("\n請選擇職業:\n"); if(((*choseptr >> (Builder+1)) & 1) == 0) printf("1) 建築師\n"); if(((*choseptr >> (Producer+1)) & 1) == 0) printf("2) 生產者\n"); if(((*choseptr >> (Trader+1)) & 1) == 0) printf("3) 商人\n"); if(((*choseptr >> (Councilor+1)) & 1) == 0) printf("4) 市長\n"); if(((*choseptr >> (Prospector+1)) & 1) == 0) printf("5) 淘金者\n"); printf("(請輸入數字進行選擇):");//----------輸入無效 while(scanf("%d", &role) != 1 || ((*choseptr >> role)&1) == 1 || role > 5 || role < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("選擇無效!請選擇職業:\n"); if(((*choseptr >> (Builder+1)) & 1) == 0) printf("1) 建築師\n"); if(((*choseptr >> (Producer+1)) & 1) == 0) printf("2) 生產者\n"); if(((*choseptr >> (Trader+1)) & 1) == 0) printf("3) 商人\n"); if(((*choseptr >> (Councilor+1)) & 1) == 0) printf("4) 市長\n"); if(((*choseptr >> (Prospector+1)) & 1) == 0) printf("5) 淘金者\n"); printf("(請輸入數字進行選擇):"); } } else { while(role == 0 || ((*choseptr >> role) & 1) == 1 ) { role = rand()%5 + 1; } } printf(RED"職業: "); switch(role){ case 1: printf("建築師\n"NONE); break; case 2: printf("生產者\n"NONE); break; case 3: printf("商人\n"NONE); break; case 4: printf("市長\n"NONE); break; case 5: printf("淘金者\n"NONE); break; default: break; } return role; } _splayer_card *choose_card(struct list_head *player_list_head, const int32_t player)//選卡 { int32_t cardnum = 0; int32_t count = print_handcard(player_list_head, player); Player{ printf("\n(輸入卡片編號進行選擇):"); while(scanf("%d", &cardnum) != 1 || cardnum <= 0|| cardnum > count) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("輸入無效!(輸入卡片編號進行選擇):"); } } Robot{ cardnum = rand()%count + 1; } struct list_head *listptr = NULL; count = 1; list_for_each(listptr, player_list_head) { if(count == cardnum) { _splayer_card *choosecard = list_entry(listptr, _splayer_card, list); return choosecard; } count ++; } return NULL; } void lost_card(struct list_head *player_list_head, struct list_head *choosecard, const int32_t player) { printf("選擇欲丟出的手牌--\n"); _splayer_card *lostcard = choose_card(player_list_head, player); while(lostcard == NULL || &(lostcard->list) == choosecard) { printf("選擇無效!選擇欲丟出的手牌--\n"); lostcard = choose_card(player_list_head, player); } list_del(&(lostcard->list)); free(lostcard); return; } void lost_commod(struct list_head *build_list_head, const int32_t player) { _splayer_card *lostcommod = choose_card(build_list_head, player); while(lostcommod == NULL || lostcommod->commodity != 1) { lostcommod = choose_card(build_list_head, player); } lostcommod->commodity = 0; return; } //建築師 void Builder_func(const int32_t sp, const int32_t player, struct list_head *player_list_head, struct list_head *build_list_head) { Player{ printf("你的手牌:\n"); print_handcard(player_list_head, 1); } int32_t sp_building = 0;//是否有特殊建築 struct list_head *listptr = NULL; list_for_each(listptr, build_list_head) { _splayer_card *bptr = list_entry(listptr, _splayer_card, list); if((bptr->id >= 8 && bptr->id <= 13) || bptr->id == 22) { sp_building = sp_building | (1 << bptr->id); } } int8_t sp_option = 0; int8_t option = 0; printf("\n是否執行一般行動-建造1棟建築,根據建築卡上的所示費用,支付對應手牌張數?\n1)是 2)否\n(請輸入數字進行選擇):"); Player{ while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("選擇無效!是否執行一般行動-建造1棟建築,根據建築卡上的所示費用,支付對應手牌張數?\n1)是 2)否\n(請輸入數字進行選擇):"); } } Robot{ option = rand()%2 + 1; printf("%d\n", option); } if(sp == 1 && option == 1)//選擇特權 { printf("\n是否執行特權行動-根據建築卡上的所示費用,支付對應手牌張數時,可減少支付1張手牌,但建築最後支付的費用不能少於0?\n1)是 2)否\n(請輸入數字進行選擇):"); Player{ while(scanf("%hhd", &sp_option) != 1 || sp_option > 2 || sp_option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("選擇無效!是否執行特權行動-根據建築卡上的所示費用,支付對應手牌張數時,可減少支付1張手牌,但建築最後支付的費用不能少於0?\n1)是 2)否\n(請輸入數字進行選擇):"); } } Robot{ sp_option = rand()%2 + 1; printf("%d\n", sp_option); } } int32_t action = 2; while(option == 1 && action == 2) { _splayer_card *choosecard = choose_card(player_list_head, player); if(choosecard == NULL) { printf("選擇失敗!\n"); break; } if((sp_building >> (choosecard->id) & 1 )== 1){//是否已有該特殊建築 printf("\n已有一棟該特殊建築!\n1)重新選擇\n2)放棄執行\n(請輸入數字進行選擇):"); Player{ while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("選擇無效!已有一棟該特殊建築!\n1)重新選擇\n2)放棄執行\n(請輸入數字進行選擇):"); } } Robot{ option = 2; printf("%d\n", option); } if(option == 1) continue; else if(option == 2) break; } int32_t cardfee = choosecard->fee; int32_t *feeptr = &cardfee; //特殊功能 if(sp_option == 1)//特權 cardfee --; if(((sp_building >> 8) & 1 )== 1 && cardfee > 0 && choosecard -> id <= 5) Smithy(feeptr, player);//鐵匠 if(((sp_building >> 13) & 1 )== 1 && cardfee > 0 && choosecard->id > 5) Quarry(feeptr, player);//採石場 if(((sp_building >> 22) & 1 )== 1 && cardfee > 0 && sp == 1)//圖書館 build_Library(feeptr, player); int32_t vicpoint = 0; if(((sp_building >> 11) & 1 )== 1 && (list_empty(build_list_head) == 0)) vicpoint = Crane(cardfee, feeptr, build_list_head, player);//起重機 int32_t commod = 0;//是否有貨物 listptr = NULL; list_for_each(listptr, build_list_head) { _splayer_card *cptr = list_entry(listptr, _splayer_card, list); if(cptr->commodity == 1) { commod ++; } } if(((sp_building >> 10) & 1 )== 1 && commod != 0 ) Black_market(build_list_head, feeptr, commod, player);//黑市 if(((sp_building >> 12) & 1 )== 1 && choosecard->id > 5) Carpenter(player_list_head, player);//木工場 action = normal_build(cardfee, choosecard, player_list_head, build_list_head, player, vicpoint);//建造行動 if(action == 1) { int32_t count = print_handcard(player_list_head, 0);//手牌不超過1張 if(((sp_building >> 9) & 1 )== 1 && count <= 1) Poor_house(player_list_head, player);//救濟院 } } return; } void *Builder_func2(void *arg) { const int32_t sp = ((lv2 *)arg)->sp; const int32_t player = ((lv2 *)arg)->player; struct list_head *player_list_head = ((lv2 *)arg)->player_list_head; struct list_head *build_list_head = ((lv2 *)arg)->build_list_head; Builder_func(sp, player, player_list_head, build_list_head); alrm = 0; return 0; } int32_t normal_build(int32_t cardfee, _splayer_card *choosecard, struct list_head *player_list_head, struct list_head *build_list_head, const int32_t player, int32_t vicpoint) { //printf("347\n"); int32_t count = 0; struct list_head *lisptr = NULL; list_for_each(lisptr, player_list_head) count++; if(count <= cardfee)//判斷手牌是否足夠 { int8_t option = 0; printf("\n沒有足夠手牌!\n1)重新選擇\n2)放棄執行\n(請輸入數字進行選擇):"); Player{ while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("選擇無效!沒有足夠手牌!\n1)重新選擇\n2)放棄執行\n(請輸入數字進行選擇):"); } } Robot{ option = 2; printf("%d\n", option); } if(option == 1) return 2; else return 0; } for(int32_t i =0;i<cardfee;i++)//丟卡 lost_card(player_list_head, &(choosecard->list), player); _splayer_card *newbuild = add_newcard(&building[choosecard->id - 1]); list_add(&(newbuild->list), build_list_head); if(vicpoint > 0) newbuild->vicpoint = vicpoint; list_del(&(choosecard->list)); free(choosecard); //printf("401\n"); return 1; } void Smithy(int32_t *feeptr, const int32_t player) { int8_t option = 0; Player{ printf("\n你有鐵匠鋪!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[7].tip); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有鐵匠鋪!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[7].tip); } } Robot{ option = rand()%2 + 1; } if(option == 1){ *feeptr -= 1; printf("使用了鐵匠鋪!\n");} return; } void Poor_house(struct list_head *player_list_head, const int32_t player) { int8_t option = 0; Player{ printf("\n你有救濟院!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[8].tip); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有救濟院!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[8].tip); } } Robot{ option = rand()%2 + 1; } if(option == 1) { _sbuild *drawcard = draw_card(); _splayer_card *newcard = add_newcard(drawcard); list_add(&(newcard->list), player_list_head); printf("使用了救濟院!\n"); drawcard->num --; } return; } void Black_market(struct list_head *build_list_head, int32_t *feeptr, int32_t commodnum, const int32_t player) { int8_t option = 0; Player{ printf("\n你有黑市!是否執行特殊行動-%s\n使用 0)0張 1)1張 2)2張\n(請輸入數字進行選擇):", building[9].tip); while(scanf("%hhd", &option) != 1 || option > commodnum) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有黑市!是否執行特殊行動-%s\n使用 0)0張 1)1張 2)2張\n(請輸入數字進行選擇):", building[9].tip); } } Robot{ option = rand()%3; while(option > commodnum) { option = 0; } } for(int32_t i = 0;i<option;i++) { lost_commod(build_list_head, player); } *feeptr -= option; if(option > 0){ printf("使用了黑市!\n"); } return; } int32_t Crane(int32_t cardfee, int32_t *feeptr, struct list_head *build_list_head, const int32_t player) { int8_t option = 0; int32_t ret = 0; Player{ printf("\n你有起重機!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[10].tip); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有起重機!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[10].tip); } } Robot{ option = rand()%2 + 1; } if(option == 1) { _splayer_card *lostbuild = choose_card(build_list_head, player); if(lostbuild == NULL) { printf("\n使用失敗!\n"); return 0; } if(lostbuild->id == 7 || lostbuild->vicpoint > 0) { ret = lostbuild->vicpoint; } *feeptr = lostbuild->fee - cardfee; if(*feeptr < 0) *feeptr = 0; list_del(&(lostbuild->list)); free(lostbuild); printf("使用了起重機!\n"); } return ret; } void Carpenter(struct list_head *player_list_head, const int32_t player) { int8_t option = 0; Player{ printf("\n你有木工場!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[11].tip); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有木工場!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[11].tip); } } Robot{ option = rand()%2 + 1; } if(option == 1) { _sbuild *drawcard = draw_card(); _splayer_card *newcard = add_newcard(drawcard); list_add(&(newcard->list), player_list_head); drawcard->num --; printf("使用了木工場!\n"); } return; } void Quarry(int32_t *feeptr, const int32_t player) { int8_t option = 0; Player{ printf("\n你有採石場!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[12].tip); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有採石場!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[12].tip); } } Robot{ option = rand()%2 + 1; } if(option == 1){ *feeptr -= 1; printf("使用了採石場!\n"); } return; } void build_Library(int32_t *feeptr, const int32_t player) { int8_t option = 0; Player{ printf("\n你有圖書館!是否執行特殊行動-建造建築物時可少支付2張手牌\n1)是 2)否\n(請輸入數字進行選擇):"); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有圖書館!是否執行特殊行動-建造建築物時可少支付2張手牌\n1)是 2)否\n(請輸入數字進行選擇):"); } } Robot{ option = rand()%2 + 1; } if(option == 1) { printf("使用了圖書館!\n"); *feeptr -= 2; } return; } //生產者 void Producer_func(const int32_t sp, const int32_t player, struct list_head *player_list_head, struct list_head *build_list_head, int32_t facnum){ Player{ printf("你的手牌:\n"); print_handcard(player_list_head, 1); } int32_t sp_building = 0;//是否有特殊建築 struct list_head *listptr = NULL; list_for_each(listptr, build_list_head) { _splayer_card *bptr = list_entry(listptr, _splayer_card, list); if((bptr->id >= 14 && bptr->id <= 15) || bptr->id == 22) { sp_building = sp_building | (1 << bptr->id); } } int8_t sp_option = 0; int8_t option = 0; printf("\n是否執行一般行動-生產1個貨品(即從卡牌堆上方抽取1張卡牌,正面朝下直接置於自家生產建築物下方,玩家不能偷看內容)?\n1)是 2)否\n(請輸入數字進行選擇):"); Player{ while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("選擇無效!是否執行一般行動-生產1個貨品(即從卡牌堆上方抽取1張卡牌,正面朝下直接置於自家生產建築物下方,玩家不能偷看內容)?\n1)是 2)否\n(請輸入數字進行選擇):"); } } Robot{ option = rand()%2 + 1; printf("%d\n", option); } if(sp == 1 && option == 1 && facnum > 1)//選擇特權 { printf("\n是否執行特權行動-可生產2個貨品?\n1)是 2)否\n(請輸入數字進行選擇):"); Player{ while(scanf("%hhd", &sp_option) != 1 || sp_option > 2 || sp_option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("選擇無效!可生產2個貨品?\n1)是 2)否\n(請輸入數字進行選擇):"); } } Robot{ sp_option = rand()%2 + 1; printf("%d\n", sp_option); } } int32_t action = 0; while(option == 1 && action == 0) { int32_t commodnum = 1; int32_t *comptr = &commodnum; //特殊功能 if(sp_option == 1 && facnum > commodnum)//特權 commodnum ++; if(((sp_building >> 15) & 1 )== 1 && facnum > commodnum) Aqueduct(comptr, player);//溝渠 if(((sp_building >> 22) & 1 )== 1 && facnum > commodnum && commodnum < 3 && sp == 1)//圖書館 produce_Library(comptr, facnum, player); for(int32_t i = 0;i < commodnum;i++){//產貨 _splayer_card *choosecard = choose_card(build_list_head, player); if(choosecard == NULL) { printf("選擇失敗!\n"); break; } if(choosecard->id > 5 || choosecard-> commodity != 0){//無法產貨 printf("\n該建築無法生產貨物!\n1)重新選擇\n2)放棄執行(會保留已生產貨物)\n(請輸入數字進行選擇):"); Player{ while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("選擇無效!該建築無法生產貨物!\n1)重新選擇\n2)放棄執行(會保留已生產貨物)\n(請輸入數字進行選擇):"); } } Robot{ option = rand()%2 + 1; printf("%d\n", option); } if(option == 1) { i--; continue; } else if(option == 2) break; } else action += normal_produce(choosecard, build_list_head, player);//生產行動 } if(((sp_building >> 14) & 1 )== 1 && action >= 2 ) Well(player_list_head, player);//水井 } return; } void * Producer_func2(void *arg){ const int32_t sp = ((lv2 *)arg)->sp; const int32_t player = ((lv2 *)arg)->player; struct list_head *player_list_head = ((lv2 *)arg)->player_list_head; struct list_head *build_list_head = ((lv2 *)arg)->build_list_head; int32_t facnum = ((lv2 *)arg)->facnum; Producer_func(sp, player, player_list_head, build_list_head, facnum); alrm = 0; return 0; } int32_t normal_produce(_splayer_card *choosecard, struct list_head *build_list_head, const int32_t player){ choosecard->commodity = 1; _sbuild *commod = draw_card(); commod->num --; return 1; } void Well(struct list_head *player_list_head, const int32_t player){ int8_t option = 0; Player{ printf("\n你有水井!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[13].tip); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有水井!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[13].tip); } } Robot{ option = rand()%2 + 1; } if(option == 1) { _sbuild *drawcard = draw_card(); _splayer_card *newcard = add_newcard(drawcard); list_add(&(newcard->list), player_list_head); drawcard->num --; printf("使用了水井!\n"); } return; } void Aqueduct(int32_t *comptr, int32_t player){ int8_t option = 0; Player{ printf("\n你有溝渠!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[14].tip); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有溝渠!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[14].tip); } } Robot{ option = rand()%2 + 1; } if(option == 1){ *comptr += 1; printf("使用了溝渠!\n"); } return; } void produce_Library(int32_t *comptr, int32_t facnum, const int32_t player){ int8_t option = 0; Player{ printf("\n你有圖書館!是否執行特殊行動-至多生產3個貨物\n生產 1)1個 2)2個 3)3個 4)否\n(請輸入數字進行選擇):"); while(scanf("%hhd", &option) != 1 || option > 4 || option < 1 || (option != 4 &&(option > facnum || option <= *comptr)) ) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有圖書館!是否執行特殊行動-至多生產3個貨物s\n生產 1)1個 2)2個 3)3個 4)否\n(請輸入數字進行選擇):"); } } Robot{ option = rand()%4 + 1; while(option != 4 && (option > facnum || option <= *comptr)) option = rand()%4 + 1; } if(option <= 3 ) { printf("使用了圖書館!\n"); *comptr = option; } return; } //商人 void Trader_func(const int32_t sp, const int32_t player, const int32_t tradecardnum, struct list_head *player_list_head, struct list_head *build_list_head, int32_t commodnum){ Player{ printf("你的手牌:\n"); print_handcard(player_list_head, 1); } int32_t sp_building = 0;//是否有特殊建築 struct list_head *listptr = NULL; list_for_each(listptr, build_list_head) { _splayer_card *bptr = list_entry(listptr, _splayer_card, list); if((bptr->id >= 16 && bptr->id <= 18) || bptr->id == 22) { sp_building = sp_building | (1 << bptr->id); } } int8_t sp_option = 0; int8_t option = 0; printf("\n是否執行一般行動-賣出1個貨品(即丟棄1張置於自家生產建築下方的卡牌,並從卡牌堆上方抽取對應貨品價格數量張數的卡牌加入手牌)\n1)是 2)否\n(請輸入數字進行選擇):"); Player{ while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("選擇無效!是否執行一般行動-賣出1個貨品(即丟棄1張置於自家生產建築下方的卡牌,並從卡牌堆上方抽取對應貨品價格數量張數的卡牌加入手牌)\n1)是 2)否\n(請輸入數字進行選擇):"); } } Robot{ option = rand()%2 + 1; printf("%d\n", option); } if(sp == 1 && option == 1 && commodnum > 1)//選擇特權 { printf("\n是否執行特權行動-可賣出2個貨品(即丟棄2張置於自家生產建築下方的卡牌,並從卡牌堆上方抽取對應貨品價格數量張數的卡牌加入手牌)?\n1)是 2)否\n(請輸入數字進行選擇):"); Player{ while(scanf("%hhd", &sp_option) != 1 || sp_option > 2 || sp_option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("選擇無效!可賣出2個貨品(即丟棄2張置於自家生產建築下方的卡牌,並從卡牌堆上方抽取對應貨品價格數量張數的卡牌加入手牌)?\n1)是 2)否\n(請輸入數字進行選擇):"); } } Robot{ sp_option = rand()%2 + 1; printf("%d\n", sp_option); } } int32_t action = 0; while(option == 1 && action == 0) { int32_t soldnum = 1; int32_t *soldptr = &soldnum; //特殊功能 if(sp_option == 1 && commodnum > soldnum)//特權 soldnum ++; if(((sp_building >> 18) & 1 )== 1 && commodnum > soldnum) Trading_post(soldptr, player);//交易所 if(((sp_building >> 22) & 1 )== 1 && commodnum > soldnum && soldnum < 3 && sp == 1)//圖書館 trade_Library(soldptr, commodnum, player); for(int32_t i = 0;i < soldnum;i++){//賣貨 _splayer_card *choosecard = choose_card(build_list_head, player); if(choosecard == NULL) { printf("選擇失敗!\n"); break; } if(choosecard-> commodity != 1){//無法賣貨 printf("\n該建築無法販賣貨物!\n1)重新選擇\n2)放棄執行(已販賣貨物無法回復)\n(請輸入數字進行選擇):"); Player{ while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("選擇無效!該建築無法販賣貨物!\n1)重新選擇\n2)放棄執行(已販賣貨物無法回復)\n(請輸入數字進行選擇):"); } } Robot{ option = rand()%2 + 1; printf("%d\n", option); } if(option == 1) { i--; continue; } else if(option == 2) break; } else action += normal_trade(choosecard, player_list_head, player, tradecardnum);//販賣行動 } if(((sp_building >> 17) & 1 )== 1 && action != 0 ) Market_hall(player_list_head, player);//市場 if(((sp_building >> 16) & 1 )== 1 && action >= 2 ) Market_stand(player_list_head, player);//攤販 } return; } void *Trader_func2(void *arg){ const int32_t sp = ((lv2 *)arg)->sp; const int32_t player = ((lv2 *)arg)->player; const int32_t tradercardnum = ((lv2 *)arg)->tradercardnum; struct list_head *player_list_head = ((lv2 *)arg)->player_list_head; struct list_head *build_list_head = ((lv2 *)arg)->build_list_head; int32_t commodnum = ((lv2 *)arg)->commodnum; Trader_func(sp, player, tradercardnum, player_list_head, build_list_head, commodnum); alrm = 0; return 0; } int32_t normal_trade(_splayer_card *choosecard, struct list_head *player_list_head,const int32_t player, const int32_t tradecardnum){ choosecard->commodity = 0; int32_t money = valuecards[tradecardnum].value[choosecard->id - 1]; for(int32_t i = 0;i<money;i++){//拿錢 _sbuild *drawcard = draw_card(); _splayer_card *newcard = add_newcard(drawcard); list_add(&(newcard->list), player_list_head); drawcard->num --; } return 1; } void Market_stand(struct list_head *player_list_head, const int32_t player){ int8_t option = 0; Player{ printf("\n你有攤販!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[15].tip); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有攤販!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[15].tip); } } Robot{ option = rand()%2 + 1; } if(option == 1) { _sbuild *drawcard = draw_card(); _splayer_card *newcard = add_newcard(drawcard); list_add(&(newcard->list), player_list_head); drawcard->num --; printf("使用了攤販!\n"); } return; } void Market_hall(struct list_head *player_list_head, const int32_t player){ int8_t option = 0; Player{ printf("\n你有市場!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[16].tip); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有市場!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[16].tip); } } Robot{ option = rand()%2 + 1; } if(option == 1) { _sbuild *drawcard = draw_card(); _splayer_card *newcard = add_newcard(drawcard); list_add(&(newcard->list), player_list_head); drawcard->num --; printf("使用了市場!\n"); } return; } void Trading_post(int32_t *soldptr, const int32_t player){ int8_t option = 0; Player{ printf("\n你有交易所!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[17].tip); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有交易所!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[17].tip); } } Robot{ option = rand()%2 + 1; } if(option == 1){ *soldptr += 1; printf("使用了交易所!\n"); } return; } void trade_Library(int32_t *soldptr, int32_t commodnum, const int32_t player){ int8_t option = 0; Player{ printf("\n你有圖書館!是否執行特殊行動-至多賣出3個貨物\n生產 1)1個 2)2個 3)3個 4)否\n(請輸入數字進行選擇):"); while(scanf("%hhd", &option) != 1 || option > 4 || option < 1 || (option != 4 &&(option > commodnum || option <= *soldptr)) ) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有圖書館!是否執行特殊行動-至多生產賣出貨物s\n生產 1)1個 2)2個 3)3個 4)否\n(請輸入數字進行選擇):"); } } Robot{ option = rand()%4 + 1; while(option != 4 && (option > commodnum || option <= *soldptr)) option = rand()%4 + 1; } if(option <= 3 ) { printf("使用了圖書館!\n"); *soldptr = option; } return; } //市長 void Councilor_func(const int32_t sp, const int32_t player, struct list_head *player_list_head, struct list_head *build_list_head){ Player{ printf("你的手牌:\n"); print_handcard(player_list_head, 1); } int32_t sp_building = 0;//是否有特殊建築 struct list_head *listptr = NULL; list_for_each(listptr, build_list_head) { _splayer_card *bptr = list_entry(listptr, _splayer_card, list); if((bptr->id == 19 || bptr->id == 20) || bptr->id == 22) { sp_building = sp_building | (1 << bptr->id); } } int8_t sp_option = 0; int8_t option = 0; printf("\n是否執行一般行動-從卡牌堆上方抽取2張卡牌,挑選其中1張加入手牌,其餘的卡牌則正面朝下丟置棄牌區?\n1)是 2)否\n(請輸入數字進行選擇):"); Player{ while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("選擇無效!是否執行一般行動-從卡牌堆上方抽取2張卡牌,挑選其中1張加入手牌,其餘的卡牌則正面朝下丟置棄牌區?\n1)是 2)否\n(請輸入數字進行選擇):"); } } Robot{ option = rand()%2 + 1; printf("%d\n", option); } if(sp == 1 && option == 1)//選擇特權 { printf("\n是否執行特權行動-從卡牌堆上方抽取5張卡牌,挑選其中1張加入手牌,其餘的卡牌則正面朝下丟置棄牌區?\n1)是 2)否\n(請輸入數字進行選擇):"); Player{ while(scanf("%hhd", &sp_option) != 1 || sp_option > 2 || sp_option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("選擇無效!是否執行特權行動-從卡牌堆上方抽取5張卡牌,挑選其中1張加入手牌,其餘的卡牌則正面朝下丟置棄牌區?\n1)是 2)否\n(請輸入數字進行選擇):"); } } Robot{ sp_option = rand()%2 + 1; printf("%d\n", sp_option); } } int32_t action = 2; while(option == 1 && action == 2) { int32_t chosenum = 1; int32_t *choseptr = &chosenum; int32_t drawnum = 2; int32_t *drawptr = &drawnum; //特殊功能 if(sp_option == 1)//特權 drawnum = 5; if(((sp_building >> 22) & 1 )== 1 && sp == 1)//圖書館 council_Library(drawptr, player); if(((sp_building >> 20) & 1 )== 1) Prefecture(choseptr, player);//辦公室 int32_t ar = 0; if(((sp_building >> 19) & 1 )== 1) ar = Archive(player);//檔案館 action = normal_council(chosenum, drawnum, player_list_head, player, ar);//市長行動 } return; } void *Councilor_func2(void *arg){ const int32_t sp = ((lv2 *)arg)->sp; const int32_t player = ((lv2 *)arg)->player; struct list_head *player_list_head = ((lv2 *)arg)->player_list_head; struct list_head *build_list_head = ((lv2 *)arg)->build_list_head; Councilor_func(sp, player, player_list_head, build_list_head); alrm = 0; return 0; } int32_t normal_council(const int32_t chosenum, const int32_t drawnum, struct list_head *player_list_head, const int32_t player, const int32_t ar){ if(ar == 1){ int32_t handnum = print_handcard(player_list_head,0); int32_t cards[drawnum+handnum];//手牌加抽牌數 存id int32_t count = 0; struct list_head *listptr = NULL; list_for_each(listptr, player_list_head){//加手牌 _splayer_card *cptr = list_entry(listptr, _splayer_card, list); cards[count] = cptr->id; count++; } for(int32_t i = handnum;i<drawnum+handnum;i++){//抽牌 _sbuild *drawbuild = draw_card(); cards[i] = drawbuild->id; drawbuild->num --; } delAllplayercard(player_list_head);//重選 int32_t mark = 0; for(int32_t i = 0;i<chosenum+handnum;i++){//選擇 int32_t chose = 0; printf("\n選擇想要收入的手牌---\n"); Player{ printf(BLUE"編號 /名字\t/建設費用/得分\t/技能\n"); for(int32_t j = 1;j<=drawnum+handnum;j++){ printf("%d\t/%s\t/\t %d/\t%d\t/%s\n", j, building[cards[j-1] - 1].name, building[cards[j-1] - 1].fee, building[cards[j-1] - 1].score, building[cards[j-1] - 1].tip); } printf("(得分0為視情況得分)\n"); printf("\n(輸入卡片編號進行選擇):"NONE); while(scanf("%d", &chose) != 1 || chose <= 0|| chose > drawnum+handnum || ((mark >> chose) & 1 )== 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("輸入無效!(輸入卡片編號進行選擇):"); } } Robot{ chose = rand()%(drawnum+handnum) + 1; while(((mark >> chose) & 1 )== 1) chose = rand()%drawnum + 1; } _splayer_card *newcard = add_newcard(&building[cards[chose-1] - 1]); list_add(&(newcard->list), player_list_head); mark = mark|(1 << chose); } } else{ int32_t drawcard[drawnum]; for(int32_t i = 0;i < drawnum;i++){ _sbuild *drawbuild = draw_card(); drawcard[i] = drawbuild->id; drawbuild->num --; } int32_t mark = 0; for(int32_t i = 0;i<chosenum;i++){ int32_t chose = 0; printf("\n選擇想要收入的手牌---\n"); Player{ printf(BLUE"編號 /名字\t/建設費用/得分\t/技能\n"); for(int32_t j = 1;j <= drawnum;j++){ printf("%d\t/%s\t/\t %d/\t%d\t/%s\n", j, building[drawcard[j-1] - 1].name, building[drawcard[j-1] - 1].fee, building[drawcard[j-1]- 1].score, building[drawcard[j-1] - 1].tip); } printf("(得分0為視情況得分)\n"); printf("\n(輸入卡片編號進行選擇):"NONE); while(scanf("%d", &chose) != 1 || chose <= 0|| chose > drawnum || ((mark >> chose) & 1 )== 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("輸入無效!(輸入卡片編號進行選擇):"); } } Robot{ chose = rand()%drawnum + 1; while(((mark >> chose) & 1 )== 1) chose = rand()%drawnum + 1; } _splayer_card *newcard = add_newcard(&building[drawcard[chose-1] - 1]); list_add(&(newcard->list), player_list_head); mark = mark|(1 << chose); } } return 1; } int32_t Archive(const int32_t player){ int8_t option = 0; Player{ printf("\n你有檔案館!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[18].tip); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有檔案館!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[18].tip); } } Robot{ option = rand()%2 + 1; } if(option == 1){ printf("使用了檔案館!\n"); return 1; } return 0; } void Prefecture(int32_t *choseptr, const int32_t player){ int8_t option = 0; Player{ printf("\n你有辦公處!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[19].tip); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有辦公處!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[19].tip); } } Robot{ option = rand()%2 + 1; } if(option == 1){ printf("使用了辦公處!\n"); *choseptr = 2; } return; } void council_Library(int32_t *drawptr, const int32_t player){ int8_t option = 0; Player{ printf("\n你有圖書館!是否執行特殊行動-從卡牌堆上方抽取8張卡牌,挑選其中1張加入手牌?\n1)是 2)否\n(請輸入數字進行選擇):"); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1 ) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有圖書館!是否執行特殊行動-從卡牌堆上方抽取8張卡牌,挑選其中1張加入手牌?\n1)是 2)否\n(請輸入數字進行選擇):"); } } Robot{ option = rand()%2 + 1; } if(option == 1) { printf("使用了圖書館!\n"); *drawptr = 8; } return; } //淘金者 void Prospector_func(const int32_t player, struct list_head *player_list_head, struct list_head *build_list_head){ Player{ printf("你的手牌:\n"); print_handcard(player_list_head, 1); } int32_t sp_building = 0;//是否有特殊建築 struct list_head *listptr = NULL; list_for_each(listptr, build_list_head) { _splayer_card *bptr = list_entry(listptr, _splayer_card, list); if(bptr->id == 21 || bptr->id == 22) { sp_building = sp_building | (1 << bptr->id); } } int8_t option = 0; printf("\n是否執行特權行動-從卡牌堆上方抽取1張卡牌加入手牌?\n1)是 2)否\n(請輸入數字進行選擇):"); Player{ while(scanf("%hhd", &option) != 1 || option > 2 || option < 1){ char c; while (( c = getchar()) != EOF && c != '\n'){} printf("選擇無效!是否執行特權行動-從卡牌堆上方抽取1張卡牌加入手牌?\n1)是 2)否\n(請輸入數字進行選擇):"); } } Robot{ option = rand()%2 + 1; printf("%d\n", option); } int32_t action = 2; while(option == 1 && action == 2) { int32_t drawnum = 1; int32_t *drawptr = &drawnum; if(((sp_building >> 22) & 1 )== 1)//圖書館 prospect_Library(drawptr, player_list_head, player); action = normal_prospect(drawnum, player_list_head);//淘金行動 if(action == 1 && ((sp_building >> 21) & 1 )== 1 ) Gold_mine(player_list_head, player);//起重機 } return; } void *Prospector_func2(void *arg){ const int32_t player = ((lv2 *)arg)->player; struct list_head *player_list_head = ((lv2 *)arg)->player_list_head; struct list_head *build_list_head = ((lv2 *)arg)->build_list_head; Prospector_func(player, player_list_head, build_list_head); alrm = 0; return 0; } int32_t normal_prospect(int32_t drawnum, struct list_head *player_list_head){ for(int32_t i = 0;i<drawnum;i++){ _sbuild *drawcard = draw_card(); _splayer_card *newcard = add_newcard(drawcard); list_add(&(newcard->list), player_list_head); drawcard->num --; } return 1; } void Gold_mine(struct list_head *player_list_head, const int32_t player){ int8_t option = 0; Player{ printf("\n你有金礦坑!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[20].tip); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有金礦坑!是否執行特殊行動-%s\n1)是 2)否\n(請輸入數字進行選擇):", building[20].tip); } } Robot{ option = rand()%2 + 1; } if(option == 1){ _splayer_card drawcard[4]; for(int32_t i = 0;i < 4;i++){ _sbuild *drawbuild = draw_card(); drawcard[i].id = drawbuild->id; drawcard[i].fee = drawbuild->fee; drawbuild->num --; printf("使用了金礦坑!\n"); } int32_t same = 0;//是否有相同費用 for(int32_t i = 0;i<4;i++){ for(int32_t j = i+1;j<4;j++){ if(drawcard[i].fee == drawcard[j].fee){ same = 1; break; } } if(same == 1) break; } if(same == 0){ int32_t chose = 0; printf("\n選擇想要收入的手牌---\n編號 /名字\t/建設費用/得分\t/技能\n"); for(int32_t i = 1;i<=4;i++){ printf("%d\t/%s\t/\t %d/\t%d\t/%s\n", i, building[drawcard[i-1].id - 1].name, building[drawcard[i-1].id - 1].fee, building[drawcard[i-1].id - 1].score, building[drawcard[i-1].id - 1].tip); } Player printf("(得分0為視情況得分)\n"); printf("\n(輸入卡片編號進行選擇):"); Player{ while(scanf("%d", &chose) != 1 || chose <= 0|| chose > 4) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("輸入無效!(輸入卡片編號進行選擇):"); } } Robot{ chose = rand()%4 + 1; printf("%d\n", chose); } _splayer_card *newcard = add_newcard(&building[drawcard[chose-1].id - 1]); list_add(&(newcard->list), player_list_head); } } return; } void prospect_Library(int32_t *drawptr, struct list_head *player_list_head, const int32_t player){ int8_t option = 0; Player{ printf("\n你有圖書館!是否執行特殊行動-抽取2張卡牌加入手牌?\n1)是 2)否\n(請輸入數字進行選擇):"); while(scanf("%hhd", &option) != 1 || option > 2 || option < 1 ) { char c; while (( c = getchar()) != EOF && c != '\n'){} printf("無效選擇!你有圖書館!是否執行特殊行動-抽取2張卡牌加入手牌?\n1)是 2)否\n(請輸入數字進行選擇):"); } } Robot{ option = rand()%2 + 1; } if(option == 1) { printf("使用了圖書館!\n"); *drawptr = 2; } return; } void print_table(struct list_head *player_list_head_1, struct list_head *player_list_head_2, struct list_head *player_list_head_3, struct list_head *player_list_head_4, struct list_head *build_list_head_1, struct list_head *build_list_head_2, struct list_head *build_list_head_3, struct list_head *build_list_head_4, const int32_t playernum) { printf(GREEN"----------牌桌----------\n"); for(int32_t i = 0;i<4;i++){ printf("%d", i+1); if(playernum == i%4+1) printf("(YOU): "); else printf(": "); int32_t count = 0; switch(i){ case 0: count = print_handcard(player_list_head_1, 0); printf("%d 張手牌\n\n", count); print_build(build_list_head_1); break; case 1: count = print_handcard(player_list_head_2, 0); printf("%d 張手牌\n\n", count); print_build(build_list_head_2); break; case 2: count = print_handcard(player_list_head_3, 0); printf("%d 張手牌\n\n", count); print_build(build_list_head_3); break; case 3: count = print_handcard(player_list_head_4, 0); printf("%d 張手牌\n\n", count); print_build(build_list_head_4); break; default: break; } } printf("(0:0個貨物(卡片)/1:1個貨物(卡片)/-1:無法生產貨物)\n"); printf("------------------------\n"NONE); sleep(3); return; } int32_t print_handcard(struct list_head *player_list_head, const int32_t player) { Player{ printf(BLUE"\n編號 /名字\t/建設費用/得分\t/貨物\t/技能\n"); } int32_t count = 1; struct list_head *lisptr = NULL; list_for_each(lisptr, player_list_head) { _splayer_card *card = list_entry(lisptr, _splayer_card, list); Player{ printf("%d\t/%s\t/\t %d/\t %d/\t %d/%s\n", count, card->name, card->fee, card->score, card->commodity, card->tip); } count++; } Player printf("(得分0為視情況得分)\n"NONE); return count-1; } int32_t print_build(struct list_head *build_list_head) { int32_t count = 1; struct list_head *lisptr = NULL; list_for_each(lisptr, build_list_head) { _splayer_card *card = list_entry(lisptr, _splayer_card, list); printf("\t%d)%s:\t%d\n", count, card->name, card->commodity); count++; } printf("\n"); return count; } //算分 int32_t score_count(struct list_head *build_list_head, const int32_t player){ int32_t score = 0; int32_t *sctmp = &score; int32_t sp_building = 0;//是否有特殊建築 struct list_head *listptr = NULL; list_for_each(listptr, build_list_head) { _splayer_card *bptr = list_entry(listptr, _splayer_card, list); if(bptr->id >= 26 || bptr->id <= 29) { sp_building = sp_building | (1 << bptr->id); } } if(((sp_building >> 26)&1) == 1) Guild_hall(sctmp, build_list_head, player); if(((sp_building >> 27)&1) == 1) City_hall(sctmp, build_list_head, player); if(((sp_building >> 28)&1) == 1) Triumhal_arch(sctmp, build_list_head, player); listptr = NULL; list_for_each(listptr, build_list_head){ _splayer_card *bptr = list_entry(listptr, _splayer_card, list); score += bptr->score; score += bptr->vicpoint; } if(((sp_building >> 29)&1) == 1){ printf("已使用宮殿技能...\n"); score += (score/4); } return score; } void Guild_hall(int32_t *sctmp, struct list_head *build_list_head, const int32_t player){ printf("已使用同業會館技能...\n"); struct list_head *listptr = NULL; list_for_each(listptr, build_list_head){ _splayer_card *bptr = list_entry(listptr, _splayer_card, list); if(bptr->id <= 5) *sctmp += 2; } return; } void City_hall(int32_t *sctmp, struct list_head *build_list_head, const int32_t player){ printf("已使用市政廳技能...\n"); struct list_head *listptr = NULL; list_for_each(listptr, build_list_head){ _splayer_card *bptr = list_entry(listptr, _splayer_card, list); if(bptr->id > 5) *sctmp += 1; } return; } void Triumhal_arch(int32_t *sctmp, struct list_head *build_list_head, const int32_t player){ printf("已使用凱旋門技能...\n"); int32_t count = 0; struct list_head *listptr = NULL; list_for_each(listptr, build_list_head){ _splayer_card *bptr = list_entry(listptr, _splayer_card, list); if(bptr->id >= 23 && bptr->id <= 25) count++; } if(count == 1) *sctmp += 4; else if(count == 2) *sctmp += 6; else if(count == 3) *sctmp += 8; return; } int32_t commodcount(struct list_head *build_list_head){ int32_t count = 0; struct list_head *listptr = NULL; list_for_each(listptr, build_list_head){ _splayer_card *bptr = list_entry(listptr, _splayer_card, list); if(bptr->commodity == 1) count++; } return count; } void delAllplayercard(struct list_head *player_list_head){ while(!list_empty(player_list_head)){ _splayer_card *cptr = list_entry(player_list_head->next, _splayer_card, list); free(cptr); list_del(player_list_head->next); } //printf("deltest: %d\n", list_empty(player_list_head)); return; } int32_t end_game(struct list_head *build_list_head_1, struct list_head *build_list_head_2, struct list_head *build_list_head_3, struct list_head *build_list_head_4) { int32_t game = 1; for(int32_t i = 0;i<4;i++) { int32_t count = 0; struct list_head *listptr = NULL; if(i == 0) { list_for_each(listptr, build_list_head_1); count++; } else if(i == 1) { list_for_each(listptr, build_list_head_2); count++; } else if(i == 2) { list_for_each(listptr, build_list_head_3); count++; } else if(i == 3) { list_for_each(listptr, build_list_head_4); count++; } if(count >= 12) { game = 0; break; } } return game; } void *timer(){ signal(SIGALRM,handler); alarm(30); if(alrm == 0) alarm(0); return 0; } void handler(int signo){ printf(RED"\n時間到!終止操作!\n"NONE); alrm = 0; }<file_sep>/Sanjuan/Play.h #pragma once #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <pthread.h> #include "linuxlist.h" #include "Card.h" typedef struct Player_card { int32_t id; char name[128]; int32_t fee; int32_t score; char tip[5096]; int32_t commodity; int32_t vicpoint; struct list_head list; }__attribute__((packed)) _splayer_card; typedef struct lv2{ int32_t sp; int32_t player; struct list_head *player_list_head; struct list_head *build_list_head; int32_t facnum; int32_t commodnum; int32_t tradercardnum; }lv2; int32_t welcome(); void start(struct list_head *player_list_head_1, struct list_head *player_list_head_2, struct list_head *player_list_head_3, struct list_head *player_list_head_4, struct list_head *build_list_head_1, struct list_head *build_list_head_2, struct list_head *build_list_head_3, struct list_head *build_list_head_4); _splayer_card *add_newcard(_sbuild *building); _sbuild *draw_card(); int32_t gameround(int32_t roundnum, const int32_t playernum, const int32_t tradecardnum, struct list_head *player_list_head_1, struct list_head *player_list_head_2, struct list_head *player_list_head_3, struct list_head *player_list_head_4, struct list_head *build_list_head_1, struct list_head *build_list_head_2, struct list_head *build_list_head_3, struct list_head *build_list_head_4, const int32_t level); void Chapel(struct list_head *player_list_head, struct list_head *build_list_head, const int32_t player);//禮拜堂 void Tower(struct list_head *player_list_head, struct list_head *build_list_head, const int32_t player);//塔樓 void print_table(struct list_head *player_list_head_1, struct list_head *player_list_head_2, struct list_head *player_list_head_3, struct list_head *player_list_head_4,struct list_head *build_list_head_1, struct list_head *build_list_head_2, struct list_head *build_list_head_3, struct list_head *build_list_head_4, const int32_t player);//畫面 int32_t print_handcard(struct list_head *player_list_head, const int32_t player);//印手牌、計算卡數 int32_t print_build(struct list_head *build_list_head); uint32_t choose_role(uint32_t *choseptr, uint32_t player); _splayer_card *choose_card(struct list_head *player_list_head, const int32_t player); void lost_card(struct list_head *player_list_head, struct list_head *choosecard, const int32_t player);//丟牌 void lost_commod(struct list_head *build_list_head, const int32_t player);//丟貨 //建築師 void Builder_func(const int32_t sp, const int32_t player, struct list_head *player_list_head, struct list_head *build_list_head); void *Builder_func2(void *arg); int32_t normal_build(int32_t cardfee, _splayer_card *choosecard, struct list_head *player_list_head, struct list_head *build_list_head, const int32_t player, int32_t vicpoint); void Smithy(int32_t *feeptr, const int32_t player); void Poor_house(struct list_head *player_list_head, const int32_t player); void Black_market(struct list_head *build_list_head, int32_t *feeptr, int32_t commodnum, const int32_t player); int32_t Crane(int32_t cardfee, int32_t *feeptr, struct list_head *build_list_head, const int32_t player); void Carpenter(struct list_head *player_list_head, const int32_t player); void Quarry(int32_t *feeptr, const int32_t player); void build_Library(int32_t *feeptr, const int32_t player); //生產者 void Producer_func(const int32_t sp, const int32_t player, struct list_head *player_list_head, struct list_head *build_list_head, int32_t facnum); void * Producer_func2(void *arg); int32_t normal_produce(_splayer_card *choosecard, struct list_head *build_list_head,const int32_t player); void Well(struct list_head *player_list_head, const int32_t player); void Aqueduct(int32_t *comptr, const int32_t player); void produce_Library(int32_t *comptr, int32_t facnum, const int32_t player); //商人 void Trader_func(const int32_t sp, const int32_t player, const int32_t tradecardnum, struct list_head *player_list_head, struct list_head *build_list_head, int32_t commodnum); void *Trader_func2(void *arg); int32_t normal_trade(_splayer_card *choosecard, struct list_head *player_list_head,const int32_t player, const int32_t tradecardnum); void Market_stand(struct list_head *player_list_head, const int32_t player); void Market_hall(struct list_head *player_list_head, const int32_t player); void Trading_post(int32_t *soldptr, const int32_t player); void trade_Library(int32_t *soldptr, int32_t commodnum, const int32_t player); //市長 void Councilor_func(const int32_t sp, const int32_t player, struct list_head *player_list_head, struct list_head *build_list_head); void *Councilor_func2(void *arg); int32_t normal_council(const int32_t chosenum, const int32_t drawnum, struct list_head *player_list_head, const int32_t player, const int32_t ar); int32_t Archive(const int32_t player); void Prefecture(int32_t *choseptr, const int32_t player); void council_Library(int32_t *drawptr, const int32_t player); //淘金者 void Prospector_func(const int32_t player, struct list_head *player_list_head, struct list_head *build_list_head); void *Prospector_func2(void *arg); int32_t normal_prospect(int32_t drawnum, struct list_head *player_list_head); void Gold_mine(struct list_head *player_list_head, const int32_t player); void prospect_Library(int32_t *drawptr, struct list_head *player_list_head, const int32_t player); int32_t end_game(struct list_head *player_list_head_1, struct list_head *player_list_head_2, struct list_head *player_list_head_3, struct list_head *player_list_head_4); //算分 int32_t score_count(struct list_head *build_list_head, const int32_t player); int32_t commodcount(struct list_head *build_list_head); void Guild_hall(int32_t *sctmp, struct list_head *build_list_head, const int32_t player); void City_hall(int32_t *sctmp, struct list_head *build_list_head, const int32_t player); void Triumhal_arch(int32_t *sctmp, struct list_head *build_list_head, const int32_t player); //結束程式 void delAllplayercard(struct list_head *player_list_head); //beta void *timer(); void handler();
54b81e3ae33d438a1e00eb9daaabb3c5f39db8d8
[ "C", "Makefile" ]
5
C
KTJL/Sanjuan
960ff4cb6e0e5546835e9bb37e5cc02a27d81c99
a7b26c15b0d1ab8785b65e82cef4c7195edbcd24
refs/heads/master
<file_sep># ca-scripts This repo is based on the gist https://gist.github.com/Soarez/9688998 ## Generate a Certificate Authority First you have to generate a custom CA: ```bash ./generate-ca.sh ``` and set the informations below as you wish: ``` // ... Country Name (2 letter code) [AU]:HU State or Province Name (full name) [Some-State]:Bács-Kiskun Locality Name (eg, city) []:Kecskemét Organization Name (eg, company) [Internet Widgits Pty Ltd]:Something Ltd. Organizational Unit Name (eg, section) []:IT Common Name (e.g. server FQDN or YOUR name) []: // <- empty Email Address []: // <- empty ``` You can see that the `Common Name` and `Email Address` fields are **EMPTY**. After this you have to import the `ca.crt` file into your browser. ## Generate a signed certificate You have to generate the CA only once. After that you can generate any amount of certificates which are signed by the `ca.cert` CA. Generate your first certificate: ```bash ./generate.sh ``` In this example we will generate a certificate for the host `localhost` so see the informations provided below: ``` Please give the domain name: localhost // <- first question, set the domain name what you want // the script will create a directory with this name and // the generated files will be in this folder Country Name (2 letter code) [AU]:HU State or Province Name (full name) [Some-State]:Bács-Kiskun Locality Name (eg, city) []:Kecskemét Organization Name (eg, company) [Internet Widgits Pty Ltd]:Something Ltd. Organizational Unit Name (eg, section) []:IT Common Name (e.g. server FQDN or YOUR name) []:localhost // <- here we set the main domain name // only one domain name can be added here Email Address []: // <- empty Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: // <- empty An optional company name []: // <- empty Please give the domain names, separated by space: (example: *.test.net test.net) localhost 127.0.0.1 ::1 // <- here we set the domains and IP addresses // you can give multiple domains and IP addresses // (separated by a space character) // what will be valid with this certificate Sign the key... // ... Sign the certificate? [y/n]:y // <- yes, we want to sign the certificate 1 out of 1 certificate requests certified, commit? [y/n]y // <- yes, commit it Write out database with 1 new entries Data Base Updated ``` After this you can find the certificate files in the directory what you provided in section `Please give the domain name:`. <file_sep>#!/bin/bash echo "Please give the domain name: " read domain dir=${domain} mkdir ${dir} # Generate an RSA key openssl genrsa -out "${dir}/${domain}.key" 4096 # Generate Certificate Signing Request openssl req -new -key "${dir}/${domain}.key" -out "${dir}/${domain}.csr" echo "Please give the domain names, separated by space: " echo "(example: *.test.net test.net)" read domains cat > "${dir}/${domain}.extensions.cnf" <<EOL basicConstraints=CA:FALSE subjectAltName=@my_subject_alt_names subjectKeyIdentifier = hash [ my_subject_alt_names ] EOL # source: https://gist.github.com/syzdek/6086792 RE_IPV4="((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])" RE_IPV6="([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|" # TEST: 1:2:3:4:5:6:7:8 RE_IPV6="${RE_IPV6}([0-9a-fA-F]{1,4}:){1,7}:|" # TEST: 1:: 1:2:3:4:5:6:7:: RE_IPV6="${RE_IPV6}([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|" # TEST: fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b fc00:e968:6179::de52:7100 fc00:e968:6179::de52:7100 RE_IPV6="${RE_IPV6}([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|" # TEST: fc00:db20:35b:7399::5 fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:8 fc00:db20:35b:7399::5 RE_IPV6="${RE_IPV6}([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|" # TEST: fc00:e968:6179::de52:7100:7:8 fc00:e968:6179::de52:7100:7:8 fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b RE_IPV6="${RE_IPV6}([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|" # TEST: fdf8:f53e:61e4::18:6:7:8 fdf8:f53e:61e4::18:6:7:8 fdf8:f53e:61e4::18 RE_IPV6="${RE_IPV6}([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|" # TEST: fc00:db20:35b:7399::5:5:6:7:8 fc00:db20:35b:7399::5:5:6:7:8 fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b RE_IPV6="${RE_IPV6}[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|" # TEST: fdf8:f53e:61e4::18:4:5:6:7:8 fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:5:6:7:8 fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b RE_IPV6="${RE_IPV6}:((:[0-9a-fA-F]{1,4}){1,7}|:)|" # TEST: fc00:db20:35b:7399::5:4:5:6:7:8 fc00:db20:35b:7399::5:4:5:6:7:8 ::8 :: RE_IPV6="${RE_IPV6}fe08:(:[0-9a-fA-F]{1,4}){2,2}%[0-9a-zA-Z]{1,}|" # TEST: fc00:e968:6179::de52:7100:8%eth0 fc00:e968:6179::de52:7100:8%1 (link-local IPv6 addresses with zone index) RE_IPV6="${RE_IPV6}::(ffff(:0{1,4}){0,1}:){0,1}${RE_IPV4}|" # TEST: fc00:db20:35b:7399::5.255.255.255 fdf8:f53e:61e4::18:255.255.255.255 fc00:db20:35b:7399::5:2192.168.3.11 (IPv4-mapped IPv6 addresses and IPv4-translated addresses) RE_IPV6="${RE_IPV6}([0-9a-fA-F]{1,4}:){1,4}:${RE_IPV4}" # TEST: 2001:db8:3:4::192.0.2.33 fc00:db20:35b:7399::5.0.2.33 (IPv4-Embedded IPv6 Address) ipCounter=1 dnsCounter=1 for d in $domains; do if [[ $d =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] || [[ $d =~ $RE_IPV6 ]]; then echo "IP.${ipCounter} = ${d}" >> "${dir}/${domain}.extensions.cnf" ipCounter=$((ipCounter+1)) else echo "DNS.${dnsCounter} = ${d}" >> "${dir}/${domain}.extensions.cnf" dnsCounter=$((dnsCounter+1)) fi done echo "Sign the key..." # Sign the key openssl ca -config ca.conf -out "${dir}/${domain}.crt" -extfile "${dir}/${domain}.extensions.cnf" -in "${dir}/${domain}.csr" # Delete config files rm -f "${dir}/${domain}.extensions.cnf" rm -f "${dir}/${domain}.csr" <file_sep>#!/bin/bash # based on https://gist.github.com/Soarez/9688998 mkdir -p newcerts touch index.txt if [ ! -f "./serial" ]; then echo '01' > serial fi if [ -f "./ca.crt" ] && [ -f "./ca.key" ]; then echo "The CA key and cert files are already generated" exit 1 fi # Generate a key openssl genrsa -out ca.key 4096 # Generate a self signed certificate for the CA openssl req -new -x509 -key ca.key -out ca.crt
4b80574dd93d766c46ddd214f44dd85a5ba5889c
[ "Markdown", "Shell" ]
3
Markdown
TamasHugyak/ca-scripts
f9b8c65c26cb64178887cb98d479fe14254db11b
ebd20697b518a150eca77c7dd18da592d29ef06a
refs/heads/master
<file_sep>#include <iostream> #include <string> using namespace std; //size/clear/resize void Teststring1() { string s("hello!!!"); cout << s.size() << endl; cout << s.length() << endl; cout << s.capacity() << endl; cout << s << endl; //将s中的字符串清空,只将size清0,不改变底层空间的大小 s.clear(); cout << s.size() << endl; cout << s.capacity() << endl; //将s中的有效字符个数增加到10个,多出位置用'a'进行填充 //"aaaaaaaa" s.resize(10, 'a'); cout << s.size() << endl; cout << s.capacity() << endl; //将s中的有效字符增加到15个,多出位置用缺省值'\0'进行填充 //"aaaaaaaa\0\0\0\0\0" //此时s中的有效字符已经增加到15个 s.resize(15); cout << s.size() << endl; cout << s.capacity() << endl; cout << s << endl; } void Teststring2() { string s; //测试reserve是否会改变string中的有效元素 s.reserve(100); cout << s.size() << endl; cout << s.capacity() << endl; //测试reserve参数小于string的底层空间大小时,是否会将空间缩小 s.reserve(50); cout << s.size() << endl; cout << s.capacity() << endl; } void TestPushBack() { string s; size_t sz = s.capacity(); cout << "making s grow:\n"; for (int i = 0; i < 100; ++i) { s.push_back('c'); if (sz != s.capacity()) { sz = s.capacity(); cout << "capacity changed: " << sz << '\n'; } } } void TestPushBackReserve() { string s; s.reserve(100); size_t sz = s.capacity(); cout << "making s grow:\n"; for (int i = 0; i < 100; ++i) { s.push_back('c'); if (sz != s.capacity()) { sz = s.capacity(); cout << "capacity changed: " << sz << '\n'; } } } void Teststring3() { string s("hello world!"); //3种遍历方式 //1.for + operator[] for (size_t i = 0; i < s.size(); ++i) { cout << s[i] << " "; } cout << endl; //2.迭代器 string::iterator it = s.begin(); while (it != s.end()) { cout << *it << " "; ++it; } cout << endl; string::reverse_iterator rit = s.rbegin(); while (rit != s.rend()) { cout << *rit << " "; ++rit; } cout << endl; //3.范围for //for(auto& ch : s) //{ // cout << ch << endl; //} } void Teststring4() { string str; str.push_back(' '); str.append("hello"); str += 'b'; str += "it"; cout << str << endl; cout << str.c_str() << endl; //获取file的后缀 string file("string.cpp"); size_t pos = file.rfind('.'); string suffix(file.substr(pos, file.size() - pos)); cout << suffix << endl; //npos是string里面的一个静态成员变量 //static const size_t npos = -1; //取出url中的域名 string url("https://www.baidu.com/?tn=78040160_26_pg&ch=8"); cout << url << endl; size_t start = url.find("://"); if (start == string::npos) { cout << "invalid url" << endl; return; } start += 3; size_t finish = url.find('/', start); string address = url.substr(start, finish - start); cout << address << endl; //删除url的协议前缀 pos = url.find("://"); url.erase(0, pos + 3); cout << url << endl; } int main() { //Teststring1(); //Teststring2(); //TestPushBack(); //TestPushBackReserve(); //Teststring3(); Teststring4(); return 0; } <file_sep>#define _CRT_SECURE_NO_WARNINGS 1 #include "Slist.h" SListNode* BuySListNode(SLTDataType x) { SListNode *newnode = (SListNode *)malloc(sizeof(SListNode)); newnode->_data = x; newnode->_next = NULL; return newnode; } void SListPrint(SListNode *plist) { while (plist != NULL) { printf("%d->", plist->_data); plist = plist->_next; } printf("NULL\n"); } void SListPushBack(SListNode **pplist, SLTDataType x) { SListNode *newnode = BuySListNode(x); if (*pplist == NULL) { *pplist = newnode; } else { SListNode *cur = *pplist; while (cur->_next != NULL) { cur = cur->_next; } cur->_next = newnode; } } void SListPopBack(SListNode **pplist) { SListNode *tail = *pplist; SListNode *prev = NULL; while (tail->_next != NULL) { prev = tail; tail = tail->_next; } free(tail); tail = NULL; prev->_next = NULL; } void SListPushFront(SListNode **pplist, SLTDataType x) { SListNode *list = *pplist; SListNode *newnode = BuySListNode(x); if (list == NULL) { *pplist = newnode; } else { newnode->_next = list; *pplist = newnode; } } void SListPopFront(SListNode **pplist) { SListNode *node = *pplist; if (node == NULL || node->_next == NULL) { *pplist = NULL; } else { SListNode *next = node->_next; free(node); node = NULL; *pplist = next; } } SListNode* SListFind(SListNode *plist, SLTDataType x) { while (plist != NULL) { if (plist->_data == x) { return plist; } else { plist = plist->_next; } } return NULL; } void SListInsertAfter(SListNode *pos, SLTDataType x) { assert(pos); SListNode *node = BuySListNode(x); SListNode *next = pos->_next; pos->_next = node; node->_next = next; } void SListEraseAfter(SListNode *pos) { assert(pos); SListNode *next = pos->_next; if (next != NULL) { SListNode *next_next = next->_next; pos->_next = next_next; free(next); next = NULL; } } <file_sep>#define _CRT_SECURE_NO_WARNINGS 1 #include "List.h" ListNode* CreateNode() { ListNode* pHead = (ListNode*)malloc(sizeof(ListNode)); pHead->next = pHead; pHead->prev = pHead; return pHead; } ListNode* BuyListNode(LTDataType x) { ListNode* newnode = (ListNode*)malloc(sizeof(ListNode)); newnode->prev = NULL; newnode->next = NULL; newnode->val = x; return newnode; } void ListPrint(ListNode *pHead) { assert(pHead); ListNode *cur = pHead->next; while (cur != pHead) { printf("%d->", cur->val); cur = cur->next; } printf("\n"); } void ListPushBack(ListNode *pHead, LTDataType x) { assert(pHead); //ListInsert(pHead, x); ListNode *newnode = BuyListNode(x); ListNode *tail = pHead->prev; tail->next = newnode; newnode->prev = tail; newnode->next = pHead; pHead->prev = newnode; } void ListPushFront(ListNode *pHead, LTDataType x) { assert(pHead); //ListInsert(pHead->next, x); ListNode *newnode = BuyListNode(x); ListNode *first = pHead->next; pHead->next = newnode; newnode->prev = pHead; newnode->next = first; first->prev = newnode; } void ListPopBack(ListNode *pHead) { assert(pHead); //ListErase(pHead); ListNode *tail = pHead->prev; tail->prev->next = pHead; pHead->prev = tail->prev; free(tail); } void ListPopFront(ListNode *pHead) { assert(pHead); //ListErase(pHead->next->next); ListNode *first = pHead->next; pHead->next = first->next; first->next->prev = pHead; free(first); } ListNode* ListFind(ListNode *pHead, LTDataType x) { assert(pHead); ListNode *cur = pHead->next; while (cur != pHead) { if (cur->val == x) { return cur; } cur = cur->next; } return NULL; } //在pos位置前面插入数据 void ListInsert(ListNode *pos, LTDataType x) { assert(pos); ListNode *newnode = BuyListNode(x); ListNode *Prev = pos->prev; Prev->next = newnode; newnode->prev = Prev; newnode->next = pos; pos->prev = newnode; } //在pos位置前面删除数据 void ListErase(ListNode *pos) { assert(pos); ListNode *Prev = pos->prev; Prev->prev->next = pos; pos->prev = Prev->prev; free(Prev); }<file_sep>#include <stdio.h> #include <unistd.h> #include <fcntl.h> int main() { int fp = open("./tmp.txt", O_RDWR | O_CREAT | O_APPEND, 0664); if (fp < 0) { perror("open"); return 0; } int ret = write(fp, "hello world", 11); if(ret < 0) { perror("write"); return 0; } lseek(fp, 0, SEEK_SET); char buf[1024] = {0}; ret = read(fp, buf, sizeof(buf) - 1); if(ret < 0) { printf("read"); return 0; } else if(ret == 0) { printf("read size :[%d]\n", ret); } printf("%s\n",buf); close(fp); return 0; } <file_sep>#include <stdio.h> #include <unistd.h> #include <fcntl.h> int main() { int fd = open("./tmp.txt", O_RDWR | O_CREAT, 0664); if(fd < 0) { perror("open"); return 0; } //重定向 //把本应输出到屏幕的内容输出到文件中 dup2(fd, 1); printf("good job!\n"); while(1) { sleep(1); } return 0; } <file_sep>all:cfile cread filecount filecount:filecount.c gcc $^ -o $@ -g cread:cread.c gcc $^ -o $@ -g cfile:cfile.c gcc $^ -o $@ -g <file_sep>#include <stdio.h> #include <unistd.h> int main() { //int ret = execl("/usr/bin/ls", "ls", "-l", NULL); //printf("ret :%d\n", ret); //int ret = execlp("ls", "ls", "-l", NULL); //int ret = execlp("./mygetenv", "mygetenv", "-a", "-b", "-c", NULL); //printf("ret :%d\n", ret); char *envp[3]; envp[0] = "PATH = /hahaha"; envp[1] = "MYGETENV = mygetenv"; envp[2] = NULL; //execle("./mygetenv", "mygetenv", "-a", "-b", "-c", NULL, envp); char *argv[3]; argv[0] = "mygetenv"; argv[1] = "-a"; argv[2] = NULL; //execv("./mygetenv", argv); //execvp("./mygetenv", argv); execve("./mygetenv", argv, envp); printf("hello\n"); return 0; } <file_sep>#define _CRT_SECURE_NO_WARNINGS 1 #include "SeqList.h" void SeqListInit(SeqList *ps) { assert(ps); ps->_a = NULL; ps->_size = ps->_capatity = 0; } void SeqListCheckCapacity(SeqList *ps) { assert(ps); int newcapacity = ps->_capatity == 0 ? 4 : ps->_capatity * 2; ps->_a = realloc(ps->_a, newcapacity*sizeof(SLDataType)); ps->_capatity = newcapacity; } void SeqListDestory(SeqList* ps) { assert(ps); free(ps->_a); ps->_a = NULL; ps->_capatity = ps->_size = 0; } void SeqListPrint(SeqList *ps) { assert(ps); for (size_t i = 0; i < ps->_size; ++i) { printf("%d ", ps->_a[i]); } printf("\n"); } void SeqListPushBack(SeqList *ps, SLDataType x) { assert(ps); SeqListCheckCapacity(ps); ps->_a[ps->_size++] = x; } void SeqListPopBack(SeqList *ps) { assert(ps && ps->_size > 0); ps->_size--; } void SeqListPushFront(SeqList *ps, SLDataType x) { assert(ps); SeqListCheckCapacity(ps); int pos = ps->_size - 1; for (; pos >= 0; pos--) { ps->_a[pos + 1] = ps->_a[pos]; } ps->_a[0] = x; ps->_size++; } void SeqListPopFront(SeqList *ps) { assert(ps); /*for (size_t i = 1; i < ps->_size; i++) { ps->_a[i - 1] = ps->_a[i]; }*/ for (size_t i = 0; i < ps->_size - 1; i++) { ps->_a[i] = ps->_a[i + 1]; } ps->_size--; } int SeqListFind(SeqList* ps, SLDataType x) { assert(ps); for (size_t i = 0; i < ps->_size; i++) { if (ps->_a[i] == x) { return i; } } return -1; } void SeqListInsert(SeqList* ps, size_t pos, SLDataType x) { assert(ps); SeqListCheckCapacity(ps); size_t end = ps->_size + 1; for (; end > pos; end--) { ps->_a[end] = ps->_a[end - 1]; } ps->_a[pos] = x; ps->_size++; } void SeqListErase(SeqList* ps, size_t pos) { assert(ps); size_t i = pos; for (; i < ps->_size; ++i) { ps->_a[i] = ps->_a[i + 1]; } ps->_size--; } void SeqListBubbleSort(SeqList* ps) { assert(ps); //¿ØÖÆÌËÊý for (size_t end = ps->_size - 1; end > 0; --end) { int exchange = 1; for (size_t i = 0; i < end; ++i) { if (ps->_a[i] > ps->_a[i + 1]) { SLDataType tmp = ps->_a[i]; ps->_a[i] = ps->_a[i + 1]; ps->_a[i + 1] = tmp; exchange = 0; } } if (exchange == 1) { break; } } } int SeqListBinaryFind(SeqList* ps, SLDataType x) { assert(ps); size_t begin = 0, end = ps->_size - 1; while (begin <= end) { int mid = (begin + end) / 2; if (x == ps->_a[mid]) { return mid; } else if (x > ps->_a[mid]) { begin = mid + 1; } else { end = mid - 1; } } return -1; } <file_sep>#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <assert.h> typedef int QDataType; typedef struct QueueNode { QDataType val; struct QueueNode *next; }QueueNode; typedef struct Queue { QueueNode *front; QueueNode *back; }Queue; // 初始化队列 void QueueInit(Queue* pq); // 销毁队列 void QueueDestroy(Queue* pq); // 队尾入队列 void QueuePush(Queue* pq, QDataType data); // 队头出队列 void QueuePop(Queue* pq); // 获取队列头部元素 QDataType QueueFront(Queue* pq); // 获取队列队尾元素 QDataType QueueBack(Queue* pq); // 获取队列中有效元素个数 int QueueSize(Queue* pq); // 检测队列是否为空,如果为空返回非零结果,如果非空返回0 int QueueEmpty(Queue* pq); <file_sep>#pragma once #include <stdio.h> #include <assert.h> #include <stdlib.h> typedef int STDataType; typedef struct Stack { STDataType *a; size_t top; //栈顶 size_t capacity; }Stack; void StackInit(Stack *pst); void StackDestory(Stack *pst); void StackPush(Stack *pst, STDataType x); void StackPop(Stack *pst); // 获取栈顶元素 STDataType StackTop(Stack* pst); //返回1表示空,返回0表示非空 int StackEmpty(Stack *pst); // 获取栈中有效元素个数 size_t StackSize(Stack *pst); <file_sep>#include <stdio.h> #include <unistd.h> int main() { int fd[2]; int ret = pipe(fd); if(ret < 0) { perror("pipe"); return 0; } //fd[0] : 读端-->文件描述符 //fd[1] : 写端-->文件描述符 write(fd[1], "be happy", 8); char buf[1024] = {0}; read(fd[0], buf, sizeof(buf) - 1); printf("buf [%s]\n", buf); while(1) { sleep(1); } return 0; } <file_sep>all:writeshm readshm writeshm:writeshm.c gcc $^ -o $@ readshm:readshm.c gcc $^ -o $@ <file_sep>#include <stdio.h> int main() { printf("my first commit\n"); return 0; } <file_sep>#include <stdio.h> #include <unistd.h> int main() { while(1) { printf("hello world"); usleep(10000); } sleep(5); return 0; } <file_sep>#pragma once #include <stdio.h> #include <assert.h> #include <stdlib.h> typedef int LTDataType; typedef struct ListNode { struct ListNode *prev; struct ListNode *next; LTDataType val; }ListNode; ListNode* CreateNode(); ListNode* BuyListNode(LTDataType x); void ListPrint(ListNode *pHead); void ListPushBack(ListNode *pHead, LTDataType x); void ListPushFront(ListNode *pHead, LTDataType x); void ListPopBack(ListNode *pHead); void ListPopFront(ListNode *pHead); ListNode* ListFind(ListNode *pHead, LTDataType x); void ListInsert(ListNode *pos, LTDataType x); void ListErase(ListNode *pos);<file_sep>//#include <iostream> //using namespace std; //class Date //{ //public: // //获取某年某月的天数 // int GetMonthDay(int year, int month) // { // static int month_days[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // int day = month_days[month]; // if (month == 2 && // ((year % 4 == 0 && year % 100 != 100) || year % 400 == 0)) { // day += 1; // } // return day; // } // //打印日期 // void Print()const // { // cout << _year << "-" << _month << "-" << _day << endl; // } // //全缺省参数的构造函数 // Date(int year = 1900, int month = 1, int day = 1) // { // if (month > 0 && month < 13 // && day > 0 && day <= GetMonthDay(year, month) // && year >= 0) // { // _year = year; // _month = month;; // _day = day; // } // else // { // cout << "日期非法" << endl; // } // } // //拷贝构造函数 // Date(const Date& d) // { // _year = d._year; // _month = d._month; // _day = d._day; // } // //赋值运算符重载 // Date& operator=(const Date& d) // { // if (this != &d) // { // _year = d._year; // _month = d._month; // _day = d._day; // } // return *this; // } // //日期+天数,原日期不变 // //Date& operator+(int day) // //{ // // //拷贝构造一个和原日期相等的类,不能直接对原日期进行操作,否则会改变原日期 // // Date ret(*this); // // ret._day += day; // // while (ret._day > GetMonthDay(ret._year, ret._month)) // // { // // ret._day -= GetMonthDay(ret._year, ret._month); // // ++ret._month; // // if (ret._month == 13) // // { // // ret._year++; // // ret._month = 1; // // } // // } // // return ret; // //} // // Date operator+(int day) // { // //对+=的复用 // Date ret(*this); // ret += day; // return ret; // } // //日期+=天数,原日期改变 // Date& operator+=(int day) // { // if (day < 0) // { // *this -= -day; // return *this; // } // _day += day; // while (_day > GetMonthDay(_year, _month)) // { // _day -= GetMonthDay(_year, _month); // _month++; // if (_month == 13) // { // _year++; // _month = 1; // } // } // return *this; // } // //析构函数,Date类直接用编译器生成的默认析构函数 // // //日期-天数 // Date operator-(int day) // { // Date ret(*this); // ret -= day; // return ret; // } // // //日期-=天数 // Date& operator-=(int day) // { // if (day < 0) // { // *this -= -day; // return *this; // } // _day -= day; // while (_day <= 0) // { // --_month; // if (_month == 0) // { // _year--; // _month = 12; // } // _day += GetMonthDay(_year, _month); // } // return *this; // } // // 前置++ // Date& operator++() // { // *this += 1; // return *this; // } // // 后置++ // Date operator++(int) // { // Date tmp(*this); // *this += 1; // return tmp; // } // // 后置-- // Date operator--(int) // { // Date tmp(*this); // *this -= 1; // return tmp; // } // // 前置-- // Date& operator--() // { // *this -= 1; // return *this; // } // // >运算符重载 // bool operator>(const Date& d) // { // if ((_year > d._year) // || (_year == d._year&&_month > d._month) // || (_year == d._year&&_month == d._month&&_day > d._day)) // { // return true; // } // else // { // return false; // } // } // // ==运算符重载 // bool operator==(const Date& d) // { // return _year == d._year&&_month == d._month&&_day == d._day; // } // // >=运算符重载 // // 实际中这里不加inline也可以,因为直接在类中实现的函数,默认就是inline // inline bool operator >= (const Date& d) // { // return *this > d || *this == d; // } // // <运算符重载 // bool operator < (const Date& d) // { // return !(*this>d); // } // // <=运算符重载 // bool operator <= (const Date& d) // { // return !(*this >= d); // } // // !=运算符重载 // bool operator != (const Date& d) // { // return !(*this == d); // } // // // 日期-日期 返回天数 // //如果*this<flag,返回值为负 // int operator-(const Date& d) // { // int flag = -1; // Date min = *this; // Date max = d; // if (*this > d) // { // flag = 1; // min = d; // max = *this; // } // int n = 0; // while (min != max) // { // ++n; // ++min; // } // return n*flag; // } //private: // int _year; // int _month; // int _day; //}; //int main() //{ // Date d1(2020, 3, 19); // // Date d2(2020, 3, 23); // bool ret = d2 > d1; // cout << ret << endl; // // return 0; //} #include <iostream> using namespace std; class Date { public: friend ostream& operator<<(ostream& _cout, const Date d); friend istream& operator>>(istream& _cout, Date& d); Date(int year=1990, int month=1, int day=1) { _year = year; _month = month; _day = day; } private: int _year; int _month; int _day; }; ostream& operator<<(ostream& _cout, const Date d) { _cout << d._year << "-" << d._month << "-" << d._day << endl; return _cout; } istream& operator>>(istream& _cin, Date& d) { _cin >> d._year >> d._month >> d._day; return _cin; } int main() { Date d1(2020, 3, 26); Date d2(2020, 3, 27); cin >> d1 >> d2; cout << d1 << d2; return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS 1 #include "List.h" void ListTest1() { ListNode *pHead = CreateNode(); ListPushBack(pHead, 1); ListPushBack(pHead, 2); ListPushBack(pHead, 3); ListPushBack(pHead, 4); ListPushBack(pHead, 5); ListPrint(pHead); ListPushFront(pHead, 1); ListPushFront(pHead, 2); ListPushFront(pHead, 3); ListPushFront(pHead, 4); ListPushFront(pHead, 5); ListPrint(pHead); ListPopBack(pHead); ListPopBack(pHead); ListPopBack(pHead); ListPopBack(pHead); ListPrint(pHead); /*ListPopFront(pHead); ListPopFront(pHead); ListPopFront(pHead); ListPopFront(pHead); ListPrint(pHead);*/ ListNode *pos = ListFind(pHead, 3); ListInsert(pos, 6); ListInsert(pos, 6); ListInsert(pos, 6); ListPrint(pHead); ListErase(pos); ListErase(pos); ListErase(pos); ListPrint(pHead); } int main() { ListTest1(); return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS 1 #include "SList.h" void SListTest1() { SListNode *list = NULL; SListPushBack(&list, 1); SListPushBack(&list, 2); SListPushBack(&list, 3); SListPushBack(&list, 4); SListPushBack(&list, 5); SListPrint(list); SListPopFront(&list); SListPrint(list); SListPopFront(&list); SListPrint(list); SListPopFront(&list); SListPrint(list); SListPopFront(&list); SListPrint(list); SListPopFront(&list); SListPrint(list); SListPushFront(&list, 1); SListPushFront(&list, 2); SListPushFront(&list, 3); SListPushFront(&list, 4); SListPushFront(&list, 5); SListPrint(list); SListPopBack(&list); SListPrint(list); SListPopBack(&list); SListPrint(list); SListPopBack(&list); SListPrint(list); SListPopBack(&list); SListPrint(list); SListPopBack(&list); SListPrint(list); } void SListTest2() { SListNode *list = NULL; SListPushBack(&list, 1); SListPushBack(&list, 2); SListPushBack(&list, 3); SListPushBack(&list, 4); SListPushBack(&list, 5); SListPrint(list); SListNode *node = SListFind(list, 3); if (node != NULL) { node->_data = 30; } SListPrint(list); SListNode *pos = SListFind(list, 30); SListInsertAfter(pos, 7); SListPrint(list); SListEraseAfter(pos); SListPrint(list); SListEraseAfter(pos); SListPrint(list); } int main() { SListTest2(); return 0; }<file_sep>#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> int main() { int fd[2]; int ret = pipe(fd); if(ret < 0) { perror("pipe"); return 0; } //获取当前文件描述符的属性,通过返回值返回回来 int flags = fcntl(fd[0], F_GETFL, 0); flags |= O_NONBLOCK; fcntl(fd[0], F_SETFL, flags); //创建子进程 ret = fork(); if(ret < 0) { perror("fork"); return 0; } else if(ret == 0) { //child 读 //sleep(3); //close(fd[0]); close(fd[1]); char buf[1024] = {0}; int readsize = read(fd[0], buf, sizeof(buf) - 1); if(readsize < 0) { perror("read"); printf("readsize :[%d]\n", readsize); exit(0); } printf("i am child and i read buf [%s]\n", buf); printf("size :[%d]\n", readsize); //1.管道当中没有数据了,read就会阻塞 //2.管道当中的数据是被拿走了 //readsize = read(fd[0], buf, sizeof(buf) - 1); while(1) { sleep(1); } } //father 写 //sleep(30); //close(fd[0]); //int count = 0; //while(1) //{ // int ret = write(fd[1], "6", 1); // if(ret < 0) // { // perror("write:"); // break; // } // count++; // printf("write size [%d]\n", count); //} close(fd[1]); while(1) { sleep(1); printf("i am father\n"); } return 0; } <file_sep>#include <stdio.h> int main() { FILE *fp =fopen("tmp.txt", "w+"); if(!fp) { perror("fp"); return 0; } const char *lp = "happy everyday"; int ret = fwrite(lp, 1, 14, fp); if(ret == 14) { printf("write size:[%d]\n", ret); } fseek(fp, 0, SEEK_SET); char arr[1024] = {0}; ret = fread(arr, 1, sizeof(arr) - 1, fp); if(ret == 14) { printf("read size[%d]\n", ret); } fclose(fp); return 0; } <file_sep>#pragma once #include <stdio.h> #include <assert.h> #include <stdlib.h> typedef int SLDataType; typedef struct SeqList { SLDataType *_a; size_t _size; size_t _capatity; }SeqList; // 顺序表初始化 void SeqListInit(SeqList* ps); // 顺序表销毁 void SeqListDestory(SeqList* ps); // 顺序表打印 void SeqListPrint(SeqList* ps); // 检查空间,如果满了,进行增容 void CheckCapacity(SeqList* ps); // 顺序表尾插 void SeqListPushBack(SeqList* ps, SLDataType x); // 顺序表尾删 void SeqListPopBack(SeqList* ps); // 顺序表头插 void SeqListPushFront(SeqList* ps, SLDataType x); // 顺序表头删 void SeqListPopFront(SeqList* ps); // 顺序表查找 int SeqListFind(SeqList* ps, SLDataType x); // 顺序表在pos位置插入x void SeqListInsert(SeqList* ps, size_t pos, SLDataType x); // 顺序表删除pos位置的值 void SeqListErase(SeqList* ps, size_t pos); void SeqListBubbleSort(SeqList* ps); int SeqListBinaryFind(SeqList* ps, SLDataType x); <file_sep>#include <stdio.h> int main(int argc, char*argv[]) { int i = 0; for(; i < argc; i++) { printf("argv[%d]:%s\n", i, argv[i]); } extern char** environ; for(i = 0; environ[i]; i++) { printf("environ[%d]:%s\n", i, environ[i]); } return 0; } <file_sep>#define _CRT_SECURE_NO_WARNINGS 1 #include <iostream> #include <assert.h> using namespace std; namespace func { class string { public: typedef char* iterator; iterator begin() { return _str; } iterator end() { return _str + _size; } string(const char *str = "") :_size(strlen(str)) { _capacity = _size; _str = new char[_capacity + 1]; strcpy(_str, str); } ~string() { delete[] _str; _str = nullptr; _size = _capacity = 0; } string(const string& s) { //开空间时给\0留一个位置 _str = new char[s._size + 1]; strcpy(_str, s._str); _size = s._size; _capacity = _size; } string& operator=(string& s) { //注意自赋值情况,s1 = s1;不处理会把同一块空间释放两次 if (this != &s) { delete[] _str; _str = new char[s._size + 1]; strcpy(_str, s._str); _size = s._size; _capacity = _size; } return *this; } size_t size() const { return _size; } size_t capacity() const { return _capacity; } char& operator[](size_t pos) { assert(pos < _size); return _str[pos]; } const char& operator[](size_t pos) const { assert(pos < _size); return _str[pos]; } void reserve(size_t newcapacity) { //新容量大时要增容 if (newcapacity > _capacity) { char *newstr = new char[newcapacity + 1]; strcpy(newstr, _str); //释放旧空间,把新空间给旧空间 delete[] _str; _str = newstr; _capacity = newcapacity; } } void resize(size_t newcapcity, char ch = '\0') { //比原空间小,减小容量 if (newcapcity < _capacity) { _size = newcapcity; _str[_size] = '\0'; } else { //容量不够进行扩容 if (newcapcity > _capacity) { reserve(newcapcity); } for (size_t i = _size; i < newcapcity; i++) { _str[i] = ch; } _size = newcapcity; //一定要把最后一个位置置为'\0' _str[_size] = '\0'; } } //尾插一个字符 void push_back(char ch) { if (_size == _capacity) { reserve(_capacity * 2); } _str[_size] = ch; ++_size; _str[_size] = '\0'; } //拼接一个字符串 void append(const char *str) { size_t len = strlen(str); if (_size + len >= _capacity) { reserve(_size + len); } strcpy(_str + _size, str); _size += len; } string& operator+=(char ch) { push_back(ch); return *this; } string& operator+=(const char *str) { append(str); return *this; } private: char *_str; size_t _capacity; size_t _size; }; ostream& operator<<(ostream& out, const string& s) { for (size_t i = 0; i < s.size(); ++i) { out << s[i]; } return out; } } int main() { func::string s1("hello"); func::string s2; s2 = s1; cout << s1 << endl; cout << s2 << endl; s1.push_back('x'); s1.push_back('y'); s1.append("world"); s2 += " "; s2 += " "; s2 += "world"; cout << s1 << endl; cout << s2 << endl; for (size_t i = 0; i < s1.size(); ++i) { cout << s1[i] << " "; } cout << endl; for (auto& ch : s2) { ch += 1; cout << ch << " "; } cout << endl; func::string::iterator it1 = s2.begin(); while (it1 != s2.end()) { *it1 -= 1; cout << *it1 << " "; ++it1; } cout << endl; return 0; }<file_sep>#define _CRT_SECURE_NO_WARNINGS 1 #include "stack.h" #include "Queue.h" void StackInit(Stack *pst) { assert(pst); pst->a = NULL; pst->top = pst->capacity = 0; } void StackDestory(Stack *pst) { assert(pst); free(pst->a); pst->a = NULL; pst->top = pst->capacity = 0; } void StackPush(Stack *pst, STDataType x) { assert(pst); if (pst->top == pst->capacity) { size_t newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2; pst->a = (STDataType*)realloc(pst->a, sizeof(STDataType)*newcapacity); pst->capacity = newcapacity; } pst->a[pst->top] = x; pst->top++; } void StackPop(Stack *pst) { assert(pst && pst->top > 0); pst->top--; } STDataType StackTop(Stack* pst) { assert(pst); return pst->a[pst->top - 1]; } int StackEmpty(Stack *pst) { assert(pst); return pst->top == 0 ? 1 : 0; } size_t StackSize(Stack *pst) { assert(pst); return pst->top; } //ΆΣΑΠ void QueueInit(Queue* pq) { assert(pq); pq->back = pq->front = NULL; } void QueueDestroy(Queue* pq) { assert(pq); QueueNode *cur = pq->front; while (cur != NULL) { QueueNode *next = cur->next; free(cur); cur = next; } pq->back = pq->front = NULL; } void QueuePush(Queue* pq, QDataType x) { assert(pq); QueueNode *newnode = (QueueNode *)malloc(sizeof(QueueNode)); newnode->next = NULL; newnode->val = x; if (pq->front == NULL) { pq->back = pq->front = newnode; } else { pq->back->next = newnode; pq->back = newnode; } } void QueuePop(Queue* pq) { assert(pq); QueueNode *next = pq->front->next; free(pq->front); pq->front = next; if (pq->front == NULL) { pq->back = NULL; } } QDataType QueueFront(Queue* pq) { assert(pq); return pq->front->val; } QDataType QueueBack(Queue* pq) { assert(pq); return pq->back->val; } int QueueSize(Queue* pq) { assert(pq); QueueNode *cur = pq->front; int count = 0; while (cur != NULL) { count++; cur = cur->next; } return count; } int QueueEmpty(Queue* pq) { assert(pq); return pq->back == NULL ? 1 : 0; } <file_sep>#pragma once #include <stdio.h> #include <stdlib.h> #include <assert.h> typedef int SLTDataType; typedef struct SListNode { SLTDataType _data; struct SListNode *_next; }SListNode; SListNode* BuySListNode(SLTDataType x); void SListPushFront(SListNode **pplist, SLTDataType x); void SListPopFront(SListNode **pplist); void SListPushBack(SListNode **pplist, SLTDataType x); void SListPopBack(SListNode **pplist); SListNode* SListFind(SListNode *plist, SLTDataType x); // 在pos的后面进行插入 void SListInsertAfter(SListNode *pos, SLTDataType x); // 在pos的前面进行插入 void SListEraseAfter(SListNode *pos); void SListPrint(SListNode *plist); <file_sep>#include <stdio.h> #include <sys/shm.h> #include <unistd.h> #define shm_key 0x12345678 int main() { int shmid = shmget(shm_key, 1024, IPC_CREAT | 0664); if(shmid < 0) { perror("shmget"); return 0; } struct shmid_ds buf; shmctl(shmid, IPC_STAT, &buf); printf("shmsize [%ld]\n", buf.shm_segsz); void *lp = shmat(shmid, NULL, 0); if(!lp) { perror("shmat"); return 0; } while(1) { printf("readshm read [%s]\n", (char *)lp); sleep(1); } shmdt(lp); shmctl(shmid, IPC_RMID, NULL); return 0; } <file_sep>#include <stdio.h> #include <string.h> #include <unistd.h> #include <ctype.h> #include <sys/wait.h> #include <stdlib.h> char g_Command[1024]; int GetCommand() { memset(g_Command, '\0', sizeof(g_Command)); printf("[minishell@localhost ~]"); fflush(stdout); //一定要预留\0的位置 if(fgets(g_Command, sizeof(g_Command) - 1, stdin) == NULL) { printf("fgets error\n"); return -1; } printf("g_Command: %s\n", g_Command); return 0; } //argv[] // argv[0] : 可执行程序的名称,没有路径 // argv[1] : 可执行程序的参数 // ... // argv[x] : NULL int ExecCommand(char *argv[]) { if(argv[0] == NULL) { printf("ExecCommand error\n"); return -1; } pid_t pid = fork(); if(pid < 0) { perror("fork"); return -1; } else if(pid == 0) { //child 进程程序替换 //将已经切割命令好的命令程序(可执行程序以及可执行程序的参数),进行程序替换 execvp(argv[0], argv); //将没有替换成功的子进程杀掉 exit(0); } else { //father 进程等待 waitpid(pid, NULL, 0); } return 0; } int DealCommand(char *command) { if(!command && command == '\0') { printf("command error\n"); return -1; } //ls -al 区分哪一部分是命令,哪一部分是命令行参数 // ls -al -s- d int argc = 0; char *argv[1024] = {0}; //argv[0] = 可执行程序的名称,在这里是保存命令的 //argv[1] = 保存命令行参数 //... argv[i] = NULL; while(*command) { while(!isspace(*command) && *command != '\0') { argv[argc] = command; argc++; //去找下一个空格 while(!isspace(*command) && *command != '\0') { command++; } command = '\0'; } command++; } argv[argc] = NULL; int i = 0; //for(; i < argc; i++) //{ // printf("%d:%s\n", argc, argv[i]); //} ExecCommand(argv); return 0; } int main() { while(1) { if(GetCommand() == -1) { continue; } //处理字符串 DealCommand(g_Command); } return 0; } <file_sep>#define _CRT_SECURE_NO_WARNINGS 1 #include "SeqList.h" void SeqListTest1() { SeqList s; SeqListInit(&s); SeqListPushBack(&s, 1); SeqListPushBack(&s, 2); SeqListPushBack(&s, 3); SeqListPushBack(&s, 4); SeqListPushBack(&s, 5); SeqListPrint(&s); SeqListPopBack(&s); SeqListPrint(&s); SeqListPushFront(&s, 0); SeqListPrint(&s); SeqListPopFront(&s); SeqListPrint(&s); int ret = SeqListFind(&s, 8); printf("%d\n", ret); } void SeqListTest2() { SeqList s; SeqListInit(&s); SeqListPushBack(&s, 0); SeqListPushBack(&s, 1); SeqListPushBack(&s, 2); SeqListPushBack(&s, 3); SeqListPushBack(&s, 4); SeqListPushBack(&s, 5); SeqListPrint(&s); SeqListInsert(&s, 3, 30); SeqListPrint(&s); SeqListInsert(&s, 0, -1); SeqListPrint(&s); SeqListErase(&s, 0); SeqListPrint(&s); SeqListErase(&s, 3); SeqListPrint(&s); } void SeqListTest3() { SeqList s; SeqListInit(&s); SeqListPushBack(&s, 20); SeqListPushBack(&s, 54); SeqListPushBack(&s, 29); SeqListPushBack(&s, 13); SeqListPushBack(&s, 4); SeqListPushBack(&s, 15); SeqListPrint(&s); SeqListBubbleSort(&s); SeqListPrint(&s); int ret1 = SeqListBinaryFind(&s, 4); int ret2 = SeqListBinaryFind(&s, 13); int ret3 = SeqListBinaryFind(&s, 15); int ret4 = SeqListBinaryFind(&s, 20); int ret5 = SeqListBinaryFind(&s, 29); int ret6 = SeqListBinaryFind(&s, 54); int ret7 = SeqListBinaryFind(&s, 9); printf("%d %d %d %d %d %d %d\n", ret1, ret2, ret3, ret4, ret5, ret6, ret7); } int main() { SeqListTest3(); return 0; }<file_sep>#include <stdio.h> int main() { FILE *fp = fopen("tmp.txt", "r+"); if(!fp) { perror("fp"); } char arr[1024] = {0}; int ret = fread(arr, 1, sizeof(arr) - 1, fp); if(ret == 14) { printf("read size[%d]\n", ret); } return 0; } <file_sep>#include <stdio.h> #include <unistd.h> #include <fcntl.h> int main() { //关闭标准输入 close(0); int fp = open("./tmp.txt", O_RDWR | O_CREAT, 0664); if(fp < 0) { perror("open"); return 0; } printf("fp :[%d]\n", fp); while(1) { sleep(1); } return 0; } <file_sep>creatfifo:creatfifo.c gcc $^ -o $@ -g pipe:pipe.c gcc $^ -o $@
990005f2c7dde2929e5b4b08a045af184f73ba8e
[ "C", "Makefile", "C++" ]
31
C++
chen-t7/Newproj
ab80cb21143769c4b9ce1a7a7b4268e0eabb5bd8
0c252977dcc1272dd9bb40f1384343cf02dbd3ff