SQL corner: remove duplicated number

Last time I have problem with duplicated number. Our callback interfaces write to us many error_number. So first i have to find where is and how many this number are.

SELECT l.site_number, l.ADR_STREET_NO, REGEXP_REPLACE (l.ADR_STREET_NO, '([^ ]+)( \1)+', '\1')
FROM mibp_owner.locations l
WHERE REGEXP_LIKE (ADR_STREET_NO, '\d \d'); l
UPDATE mibp_owner.locations l
SET l.ADR_STREET_NO = REGEXP_REPLACE (l.ADR_STREET_NO, '([^ ]+)( \1)+', '\1')
WHERE REGEXP_LIKE (ADR_STREET_NO, '\d \d');

Function to remove double number:

CREATE OR REPLACE FUNCTION MIBP_OWNER.rem_dubble (n in VARCHAR2)
   RETURN VARCHAR2
IS
  ind integer;
  t1 varchar2(100);
  t2 varchar2(100);
BEGIN
  if is_no_dubbled(n)='N' then
    return n;
  end if;

  for i in 1..10 loop
    ind:=instr(n,' ',1,i);
    if ind=0 then
      exit;
    end if;
    t1:=trim(substr(n,1,ind));
    t2:=trim(substr(n,ind));
    if t1=t2 then
      return rem_dubble(t1);
    end if;
  end loop;
  return n;

END;
/
CREATE OR REPLACE FUNCTION MIBP_OWNER.is_no_dubbled (n in VARCHAR2)
   RETURN VARCHAR2
IS
  ind integer;
  t1 varchar2(100);
  t2 varchar2(100);
BEGIN
  if instr(n,' ')=0 then return 'N'; end if;
  for i in 1..10 loop
    ind:=instr(n,' ',1,i);
    if ind=0 then
      exit;
    end if;
    t1:=trim(substr(n,1,ind));
    t2:=trim(substr(n,ind));
    if t1=t2 then
      return 'Y';
    end if;
  end loop;
  return 'N';

END;
/

Show errors;

SQL Fiddle

  1. http://sqlfiddle.com/#!4/75b32/1/1
  2. http://rextester.com/l/oracle_online_compiler
  3. http://dbfiddle.uk/
  4. https://livesql.oracle.com/apex/livesql/file/index.html

Hits: 8

Alternative way monitoring Zabbix via PHP API

Purpose create this project

Display: alarms, warnings from Zabbix on PHP page. In this case I had to show some information about my services on independent web page.

Set enviroment for Zabbix PHP API

What you need to start:

  1. Zabbix API 2+ – doc: https://www.zabbix.com/documentation/, download: https://www.zabbix.com/download
  2. Apache 2.4+
  3. PHP 7+
  4. Bootstap 3+
  5. I have defined some alarms in Zabbix and I want to observe it in “application”. Just use https://github.com/confirm/PhpZabbixApi and https://www.zabbix.com/documentation/2.2/manual/api
  6. Fronted i use Bootstrap http://getbootstrap.com/javascript/#buttons and some additional lib’s https://datatables.net/extensions/index it is good effective way to make it simple an easy.
  7. Git (Btubucket, Github)

Work set

Zabbix PHP API

PhpZabbixApi is an open-source PHP class library to communicate with the Zabbix™ JSON-RPC API. Because PhpZabbixApi is generated directly from the origin Zabbix™ 2.0 PHP front-end source code / files, each real Zabbix™ JSON-RPC API method is implemented (hard-coded) directly as an own PHP method. This means PhpZabbixApi is IDE-friendly, because you’ve a PHP method for each API method, and there are no PHP magic functions or alike.

Bootstrap

Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web.

Source code on Bitbucket

<?php
/**
 * ZabbixAPI_class.php Copyright 2017 by Karol Preiskorn
 *
 * @version 18.03.2017 21:35:17 Karol Preiskorn Init
 * @version 19.03.2017 16:37:59 KPreiskorn ZabbixAPI_class.php Export to BB
 *
 */
require_once 'PhpZabbixApi-2.4.5/build/ZabbixApi.class.php';
include 'header.php';

use ZabbixApi\ZabbixApi;

/**
 *
 * @todo add LDAP via uptime
 *
 * @var string $uri
 *
 */

$uri = "http://zabixx";
$username = "user";
$password = "pass";

// set passwords and uri
include "passwords.php";

/**
 * poor print_r function
 *
 * @param unknown $val
 *
 */
function print_r2($val)
{
    echo '<pre>';
    print_r($val);
    echo '</pre>';
}

/**
 * Better print_r function
 */
function obsafe_print_r($var, $return = false, $html = true, $level = 0)
{
    $spaces = "";
    $space = $html ? " " : " ";
    $newline = $html ? "<br />" : "\n";
    for ($i = 1; $i <= 6; $i ++) {
        $spaces .= $space;
    }
    $tabs = $spaces;
    for ($i = 1; $i <= $level; $i ++) {
        $tabs .= $spaces;
    }
    if (is_array($var)) {
        $title = "Array";
    } elseif (is_object($var)) {
        $title = get_class($var) . " Object";
    }
    $output = "<b>" . $title . "</b>" . $newline . $newline;
    foreach ($var as $key => $value) {
        if (is_array($value) || is_object($value)) {
            $level ++;
            $value = obsafe_print_r($value, true, $html, $level);
            $level --;
        }
        $output .= $tabs . "[" . $key . "] => [" . $value . "]" . $newline;
    }
    if ($return)
        return $output;
    else
        echo "<pre>" . $output . "</pre>";
}

/**
 *
 * Generate bootstrap table with headers and coun of elements
 *
 * @param string $title
 * @param unknown $count
 * @param unknown $id
 */
function print_table_header($title, $count, $headers, $id)
{
    print('<div class="panel panel-default">' . "\n");
    print('<div class="panel-heading">' . $title . ' <a href="#"> <span class="badge">' . $count . '</span></a></div>' . "\n");
    print("<table id='" . $id . "' class='table table-striped table-bordered'>" . "\n");

    print("<thead><tr>" . "\n");
    foreach ($headers as $header) {
        print("<th>" . $header . "</th>" . "\n");
    }
    print("</tr>\n</thead>\n<tbody>" . "\n");
}

try {
    // connect to Zabbix API
    $api = new ZabbixApi($uri, $username, $password);

    // get all graphs
    $alerts = $api->alertGet();
    // print_r2 ( $graphs [0] );

    arsort($alerts);

    $headers = array(
        "Alert Id",
        "Event Id",
        "Date time",
        "Sent to",
        "Subject",
        "Message"
    );

    print_table_header('Alerts', count($alerts), $headers, 'alarms');

    // print all alerts
    foreach ($alerts as $alert) {
        if ($alert->sendto != "karol.preiskorn@t-mobile.pl") {
            if (strpos($alert->subject, "PROBLEM:") !== false) {
                $alerttype = "class='warning'";
            } else {
                $alerttype = "class='normal'";
            }
            if (preg_match("/Original event ID: ([0-9]{4,12})/", $alert->message, $regs)) {
                $eventid_org = "[link: <a href='#" . $regs[1] . "'>" . $regs[1] . "</a>]";
            } else {
                $eventid_org = "Not found Original event ID";
            }
            printf("<tr id='%s' %s><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" . "\n", $alert->eventid, $alerttype, $alert->alertid, $alert->eventid, date("Y-m-d h:i", $alert->clock), $alert->sendto, $alert->subject, $alert->message . " " . $eventid_org);
        }
    }
    print("</tbody>\n</table>\n</div>\n");

    // get all graphs
    $graphs = $api->graphGet();
    $header_graph = array(
        "Graph Id",
        "Description"
    );
    print_table_header('Graph', count($graphs), $header_graph, 'graph');

    // print all graph IDs
    foreach ($graphs as $graph) {
        printf("<tr><td>%8d</td><td>%s</td></tr>\n", $graph->graphid, $graph->name);
    }
    print("</tbody>\n</table>\n</div>\n");

    print('<div class="panel-footer">

        <p>© T-Mobile Polska Company | OSS development powered by Karol Preiskorn | internal use</p>

      </div>');
    print("</div></body></html>"); // end of container

    // print "<h1>Alerts... agian in raw</h2>";
                                       // obsafe_print_r ( $alerts, FALSE, TRUE );
} catch (Exception $e) {
    // Exception in ZabbixApi catched
    echo $e->getMessage();
}
?>
<?php
/**
 *
 * HTML 5
 *
 */
?>
<!DOCTYPE html>
<html>
<head>
<title>Zabbix</title>

<link rel="stylesheet" type="text/css"
	href="https://cdn.datatables.net/v/bs-3.3.7/jq-2.2.4/dt-1.10.13/af-2.1.3/b-1.2.4/b-colvis-1.2.4/fh-3.1.2/kt-2.2.0/r-2.1.1/rr-1.2.0/sc-1.4.2/se-1.2.0/datatables.min.css" />
<script type="text/javascript"
	src="https://cdn.datatables.net/v/bs-3.3.7/jq-2.2.4/dt-1.10.13/af-2.1.3/b-1.2.4/b-colvis-1.2.4/fh-3.1.2/kt-2.2.0/r-2.1.1/rr-1.2.0/sc-1.4.2/se-1.2.0/datatables.min.js"></script>

<script>
$(document).ready(function() {
    $('#alarms').DataTable( {
        deferRender:    true,
        scrollY:        400,
        scrollCollapse: false,
        scroller:       false
    } );
} );


$(document).ready(function() {
	$('#graph').DataTable({
        deferRender:    true,
        scrollY:        400,
        scrollCollapse: false,
        scroller:       false
    } );
} );
</script>

</head>

<body>
	<div class="container">
		<div class="jumbotron">
			<h1>Zabbix Alarm monitoring</h1>
			<p>Aplikacja monitoruje alarmy z Zabbix.</p>

			<a class="btn btn-primary btn-lg"
				href="http://wrex/zabbix/zabbix.php?action=dashboard.view"
				role="button">Zabbix Dashboard</a> <a class="btn btn-lg"
				href="#alarms" role="button">Alarms</a> <a class="btn btn-lg"
				href="#graph" role="button">Graph</a> <a class="btn btn-lg"
				href="simple-json.php" role="button">Simple JSON</a>


			<button class="btn btn-primary" type="button" data-toggle="collapse"
				data-target="#collapseExample" aria-expanded="false"
				aria-controls="collapseExample">About</button>


			<div class="collapse" id="collapseExample">
				<div class="well">Aplikacja monitoruje alarmy z OSS Zabbix na
					serwerze wrex. Dost�p do API poprzez klas� PHP -> ZabbixApi. Opis
					API
					https://www.zabbix.com/documentation/2.2/manual/api/reference/history/get
				</div>
			</div>

		</div>
<?php

/**
 * Zabbix monitoring in PHP
 *
 * @author Karol Preiskorn
 *
 * @version 2017-04-16 KP init
 * @version 17.03.2017 14:47:16 Karol Preiskorn dodanie informacji na temat Alert�w
 * @version 17.03.2017 18:07:38 Karol Preiskorn - dodanie synchronizacji
 * @version 9 gru 2017 12:47:16 KPreiskorn simple-json.php add composer and manage password
 *
 *
 *
 * phpinfo ();
 *
 */
$uri = "http://zabixx";
$username = "user";
$password = "pass";

// set passwords and uri
include "passwords.php";
/**
 *
 * @param unknown $in
 * @param number $indent
 * @param string $from_array
 * @return string
 */
function json_readable_encode($in, $indent = 0, $from_array = true) {
	$_myself = __FUNCTION__;
	$_escape = function ($str) {
		return preg_replace ( "!([\b\t\n\r\f\"\\'])!", "\\\\\\1", $str );
	};

	$out = '';

	foreach ( $in as $key => $value ) {
		$out .= str_repeat ( "\t", $indent + 1 );
		$out .= "\"" . $_escape ( ( string ) $key ) . "\": ";

		if (is_object ( $value ) || is_array ( $value )) {
			$out .= "\n";
			$out .= $_myself ( $value, $indent + 1 );
		} elseif (is_bool ( $value )) {
			$out .= $value ? 'true' : 'false';
		} elseif (is_null ( $value )) {
			$out .= 'null';
		} elseif (is_string ( $value )) {
			$out .= "\"" . $_escape ( $value ) . "\"";
		} else {
			$out .= $value;
		}

		$out .= ",\n";
	}

	if (! empty ( $out )) {
		$out = substr ( $out, 0, - 2 );
	}

	$out = str_repeat ( "\t", $indent ) . "{\n" . $out;
	$out .= "\n" . str_repeat ( "\t", $indent ) . "}";

	return $out;
}

/**
 *
 * @param unknown $array
 */
function expand_arr($array) {
	foreach ( $array as $key => $value ) {
		if (is_array ( $value )) {
			echo "<i>" . $key . "</i>:<br>";
			expand_arr ( $value );
			echo "<br>\n";
		} else {
			echo "<i>" . $key . "</i>: " . $value . "<br>\n";
		}
	}
}
/**
 *
 * @param unknown $uri
 * @param unknown $data
 * @return mixed
 */
function json_request($uri, $data) {
	$json_data = json_encode ( $data );
	$c = curl_init ();
	curl_setopt ( $c, CURLOPT_URL, $uri );
	curl_setopt ( $c, CURLOPT_CUSTOMREQUEST, "POST" );
	curl_setopt ( $c, CURLOPT_RETURNTRANSFER, true );
	curl_setopt ( $c, CURLOPT_POST, $json_data );
	curl_setopt ( $c, CURLOPT_POSTFIELDS, $json_data );
	curl_setopt ( $c, CURLOPT_HTTPHEADER, array (
			'Content-Type: application/json',
			'Content-Length: ' . strlen ( $json_data )
	) );
	curl_setopt ( $c, CURLOPT_SSL_VERIFYPEER, false );
	$result = curl_exec ( $c );

	echo "<b>JSON Request:</b><br>\n";
	echo $json_data . "<br><br>\n";

	echo "<b>JSON Answer:</b><br>\n";
	echo $result . "<br><br>\n";

	/*
	 * echo "<b>CURL Debug Info:</b><br>\n";
	 * $debug = curl_getinfo ( $c );
	 * echo expand_arr ( $debug ) . "<br><hr>\n";
	 */

	return json_decode ( $result, true );
}
/**
 *
 * @param unknown $uri
 * @param unknown $username
 * @param unknown $password
 * @return unknown
 */
function zabbix_auth($uri, $username, $password) {
	$data = array (
			'jsonrpc' => "2.0",
			'method' => "user.login",
			'params' => array (
					'user' => $username,
					'password' => $password
			),
			'id' => "1"
	);
	$response = json_request ( $uri, $data );
	return $response ['result'];
}

/**
 *
 * @param unknown $uri
 * @param unknown $authtoken
 * @return unknown
 */
function zabbix_get_hostgroups($uri, $authtoken) {
	$data = array (
			'jsonrpc' => "2.0",
			'method' => "hostgroup.get",
			'params' => array (
					'output' => "extend",
					'sortfield' => "name"
			),
			'id' => "2",
			'auth' => $authtoken
	);
	$response = json_request ( $uri, $data );
	return $response ['result'];
}
/**
 *
 * @param unknown $uri
 * @param unknown $authtoken
 */
function zabbix_get_alert($uri, $authtoken) {
	$data = array (
			"jsonrpc" => "2.0",
			"method" => "alert.get",
			"params" => array (
					"output" => "extend",
					"actionids" => "3"
			),
			"auth" => $authtoken,
			"id" => 1
	);
	$response = json_request ( $uri, $data );
	return $response ['result'];
}

/**
 *
 * @var Ambiguous $authtoken
 */
print "<h1>Auth</h1>";
$authtoken = zabbix_auth ( $uri, $username, $password );

print "<h1>HostGrups</h1>";
expand_arr ( zabbix_get_hostgroups ( $uri, $authtoken ) );
print "<h2>json_readable_encode</h2>";
json_readable_encode ( zabbix_get_hostgroups ( $uri, $authtoken ) );
print "<h1>Alerts</h1>";
expand_arr ( zabbix_get_alert ( $uri, $authtoken ) );
?>

Hits: 685

How to make webservices Java, Tomcat, Metro and Eclipse

Abstract

It is about impelemtation webserwices on Tomcat in Java (Metro, Ant)

Creating the Service Provider Environment

Prerequisites

These series of articles require the following software to be installed on your system:

  1. JDK,
  2. Apache Ant 1.6.5 or later, Apache Ant is a Java library and command-line tool whose mission is to drive processes described in build files as targets and extension points dependent upon each other. The main known usage of Ant is the build of Java applications. Ant supplies a number of built-in tasks allowing to compile, assemble, test and run Java applications. Ant can also be used effectively to build non Java applications, for instance C or C++ applications. More generally, Ant can be used to pilot any type of process which can be described in terms of targets and tasks… for example deploy webserwices…
    1. http://ant.apache.org/manual/index.html
    2. http://ant.apache.org/bindownload.cgi
  3. web container: either Glassfish v3.x or Apache Tomcat 7.0+
    1. http://localhost:8080 – console
  1. programming webserwices engine
    1. Metro Standalone Budle 2.x (in case of using Apache Tomcat as a web container)
      1. https://metro.java.net/2.3.1/ Metro
      2. https://metro.java.net/getting-started/building-a-simple-metro-application.html
    2. http://trickyinfo.blogspot.com/2012/08/web-services-development-using-eclipse.html – other way to build webserwices in Eclipse
    3. http://www.eclipse.org/webtools/community/education/web/t320/Implementing_a_Simple_Web_Service.pdf
    4. http://www.ibm.com/developerworks/webservices/tutorials/ws-eclipse-javase1/ws-eclipse-javase1.html
    5. https://www.eclipse.org/webtools/ws/ – Eclipse WS tool
      1. Eclipse Web Services Explorer tool http://www.eclipse.org/webtools/initial-contribution/IBM/evalGuides/WebServicesToolsEval.html
    6. https://netbeans.org/kb/docs/websvc/jax-ws.html

How to prepare webserwis from WSDL

http://www.eclipse.org/webtools/community/education/web/t320/Generating_a_client_from_WSDL.pdf

Set Tomcat

Assuming Java (JDK + JRE) is installed in your system, do the following steps:

  1. Install Tomcat7
  2. Copy ‘tools.jar’ from ‘C:\Program Files (x86)\Java\jdk1.6.0_27\lib’ and paste it under ‘C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib’.
  3. Setup paths in your Environment Variables as shown below:

C:>echo %path%

C:\Program Files (x86)\Java\jdk1.6.0_27\bin;%CATALINA_HOME%\bin;

C:>echo %classpath%

C:\Program Files (x86)\Java\jdk1.6.0_27\lib\tools.jar;
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar;

C:>echo %CATALINA_HOME%

C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0;

C:>echo %JAVA_HOME%

C:\Program Files (x86)\Java\jdk1.6.0_27;

Now you can test whether Tomcat is setup correctly, by typing the following commands in your command prompt:

C:/>javap javax.servlet.ServletException
C:/>javap javax.servlet.http.HttpServletRequest

It should show a bunch of classes

Now start Tomcat service by double clicking on ‘Tomcat7.exe‘ under ‘C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\bin’.

Errors

INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path:

60down voteaccepted

It means exactly what it says: “The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path”

The library referred to is bundled into an OS specific dll (tcnative-1.dll) loaded via JNI. It allows tomcat to use OS functionalities not provided in the Java Runtime (such as sendfile, epoll, OpenSSL, system status, etc.). Tomcat will run just fine without it, but for some use cases, it will be faster with the native libraries.

If you really want it, download the tcnative-1.dll (or libtcnative.so for Linux) and put it in the bin folder, and add a system property to the launch configuration of the tomcat server in eclipse.

 -Djava.library.path=c:\dev\tomcat\bin

Set Metro

Again, the top-level directory of the Tomcat installation is passed as an argument to the ant command. To shutdown Tomcat, change directories, invoke ant, and restart Tomcat by executing these commands:

catalina.sh stop
ant -Dtomcat.home=<TOMCAT_INSTALL_DIR> -f <METRO_INSTALL_DIR>/metro-on-tomcat.xml install
catalina.sh start

Other Tutorials

  • http://www.ibm.com/developerworks/learn/web/index.html
  • http://stackoverflow.com/questions/14579661/how-to-set-catalina-home-variable-in-windows-7#17044342

Hits: 0

Automat komórkowy w C | Cellular automaton (CA) in C

Cellular automata and Moore neighborhood

Cellular automaton (CA) is by definition a periodic grid of cells, where in each cell sits a finite automaton, and a set of (identical) rules for every such automaton describing to which state it switches on a next moment of discrete time ti+1, depending of its own state and states of all its neighbors on a current moment of time ti. For now, we will be interested in 2d, rectangular CA, and a neighborhood which includes 8 neighbors of the cell. This is what is called the Moore neighborhood, because it was invented by Edward Moore.

Rules Brain

http://zvold.blogspot.com/2010/01/conways-life-and-brians-brain-cellular.html

  • Each cell has three possible states: passive, active, and semi-active.
  • If a cell is active, it goes to semi-active state on the next step
  • If a cell is semi-active, it becomes passive on the next step
  • If a cell is passive, it becomes active if and only if it has exactly 2 active neighbors

Materials

Source

/**
* Brian's Brain
*
* Rules:
* -------
* Each cell has three possible states: passive, active, and semi-active.
* If a cell is active, it goes to semi-active state on the next step
* If a cell is semi-active, it becomes passive on the next step
* If a cell is passive, it becomes active if and only if it has exactly 2 active neighbors
*
**/
#include 
#include 

#include 
#include 

 

Hits: 34

Przykład zadania egazminacyjnego z programowania PHP

Zadanie

  1. Stwórz dwuwymiarową tablicę numeryczną (z użyciem PHP). Napisz funkcję, za pomocą której wyświetlisz tablicę w HTML. Wyświetl tablicę.
  2. Napisz funkcję obliczającą i wyświetlającą sumę wszystkich elementów tej tablicy. Zastosuj ją.
  3. Napisz funkcję znajdującą wartości max i min w tablicy. Napisy funkcję zamieniającą po przekątnej z prawej do lewej wszystkie wartości na max, a z lewej do prawej – na min. Wyświetl wynik.
  4. Zamień losową komórkę tablicy na napis i wyznacz jego długość (za pomocą wyszukiwania napisu). Wyświetl tablicę za pomocą funkcji.
  5. Stwórz formularz odbierający wprowadzone dane podczas rejestracji (login, hasło, powtórzenie hasła, mail, imię, nazwisko, dane ankietowe, lista typu select)

Projekt PHP

  • Stwórz tablicę (z użyciem html). Napisz funkcję, za pomocą której wyświetlisz tablicę. Wyświetl tablicę.
  • Napisz funkcję obliczającą i wyświetlającą sumę wszystkich elementów tej tablicy. Zastosuj ją.
  • Napisz funkcję znajdującą wartości max i min w tablicy.
  • Napisz funkcję zamieniającą po przekątnej z prawej do lewej wszystkie wartości na max, a z lewej do prawej – na min. Wyświetl wynik.
  • Zamień losową komórkę tablicy na napis i wyznacz jego długość (za pomocą wyszukiwania napisu). Wyświetl tablicę za pomocą funkcji.
  1. Stwórz formularz odbierający wprowadzone dane podczas rejestracji
  2. login
  3. hasło
  4. powtórzenie hasła,
  5. mail,
  6. imię,
  7. nazwisko,
  8. dane ankietowe,
  9. lista typu select.

Source from GitHub

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Projekt PHP</title>
    </head>
    <body>
        <h1>Projekt PHP</h1>
        <ol>
            <li>Stwórz tablicę (z użyciem html). Napisz funkcję, za pomocą której wyświetlisz tablicę. Wy-świetl tablicę.</li>
            <li>Napisz funkcję obliczającą i wyświetlającą sumę wszystkich elementów tej tablicy. Zastosuj ją.</li>
            <li>Napisz funkcję znajdującą wartości max i min w tablicy. Napisy funkcję zamieniającą po przekątnej z prawej do lewej wszystkie wartości na max, a z lewej do prawej – na min. Wyświetl wynik.</li>
            <li>Zamień losową komórkę tablicy na napis i wyznacz jego długość (za pomocą wyszukiwania napisu). Wyświetl tablicę za pomocą funkcji.</li>
            <li>Stwórz formularz odbierający wprowadzone dane podczas rejestracji (login, hasło, powtórze-nie hasła, mail, imię, nazwisko, dane ankietowe, lista typu select).</li>
        </ol>
        <?php
        error_reporting(E_ALL);

        function print_pre($p_string) {
            print "<pre>" . print_r($p_string, true) . "</pre>";
        }

        function tablica_wyswietlanie($la_array, $p_nazwa) {
            print "<h3>" . $p_nazwa . "</h3>";
            print "<table>";
            foreach ($la_array as $key_x => $value_x) {
                echo '<tr>';
                foreach ($value_x as $key_y => $value_y) {
                    echo '<td>' . $la_array[$key_x][$key_y] . '</td>';
                }
                echo '</tr>';
            }
            print '</table>';
        }

        function tablica_min_max($la_array, $p_operacja) {
            $max = 0;
            $max_x = 0;
            $max_y = 0;

            $min = 5;
            $min_x = 0;
            $min_y = 0;

            foreach ($la_array as $key_x => $value_x) {
                foreach ($value_x as $key_y => $value_y) {

                    if ($la_array[$key_x][$key_y] >= $max) {
                        $max = $la_array[$key_x][$key_y];
                        $max_x = $key_x;
                        $max_y = $key_y;
                    }

                    if ($la_array[$key_x][$key_y] < $min) {
                        $min = $la_array[$key_x][$key_y];
                        $min_x = $key_x;
                        $min_y = $key_y;
                    }
                }
            }
            if ($p_operacja == 'max') {
                print "<p>max [" . $max_x . ',' . $max_y . "] = " . $max . "</p>";
                return $max;
            } else {
                print "<p>min [" . $min_x . ',' . $min_y . "] = " . $min . "</p>";
                return $min;
            }
        }

        function tablica_suma($la_array) {
            $sum = 0;

            foreach ($la_array as $key_x => $value_x) {
                foreach ($value_x as $key_y => $value_y) {

                    $sum = $sum + $la_array[$key_x][$key_y];
                }
            }
            print "<p>Suma elementów tablicy = " . $sum . "</p>";
        }

        function tablica_przekatna_prawa($la_array, $p_min, $p_max) {
            foreach ($la_array as $key_x => $value_x) {
                foreach ($value_x as $key_y => $value_y) {
                    if ($key_x <= $key_y)
                        $la_array [$key_x][$key_y] = $p_min;
                    if ($key_x > $key_y)
                        $la_array [$key_x][$key_y] = $p_max;
                   
                }
            }
            return $la_array;
        }

        $model = Array(
            array(1, 5, 6),
            array(2, 3, 1),
            array(4, 4, 8),
            array(8, 9, 3));

        print "Ilość pól w tablicy = " . count($model) . "<br>";


        print "<h2>Zadanie 1</h2>";
        tablica_wyswietlanie($model, 'Tablica model');

        print "<h2>Zadanie 2</h2>";
        tablica_suma($model);

        print "<h2>Zadanie 3a</h2>";
        $t_min = tablica_min_max($model, 'min');
        $t_max = tablica_min_max($model, 'max');

        print "<h2>Zadanie 3b</h2>";
        $t_prawa = tablica_przekatna_prawa($model, $t_min, $t_max);
        tablica_wyswietlanie($t_prawa, 'Wypełnienie prawe');
       
        print "<h2>Zadanie 4</h2>";
       
        $l_x = rand(0, 2);
        $l_y = rand(0, 3);
       
        $model[$l_x][$l_y] = 'Jakiś napis...';
       
        tablica_wyswietlanie($model, 'Losowy napis');

        print "<p>Długość napisu model [$l_x][$l_y] = " . strlen($model[$l_x][$l_y])."</p>";
       
        ?>
    </body>
</html>

Hits: 386

Show hide jQuery and DIV

I had to problem. A lot information to show on one web page and I have to read it all on one page. The best solution I came up with was to make a hiding to text blocks. So i try write short jQuery program according discussion at http://stackoverflow.com/questions/6967081/show-hide-multiple-divs-with-jquery i rewrite one of these solution it to my purposes.

HTML

<div class="buttons">
<a id="showall">Show All</a><br />
<a id="hideall">Hide All</a><br />
<a class="showSingle" target="1">show Div1</a> <a class="hideSingle" target="1">hide Div1</a><br />
<a class="showSingle" target="2">show Div2</a> <a class="hideSingle" target="2">hide Div2</a><br />
<a class="showSingle" target="3">show Div3</a> <a class="hideSingle" target="3">hide Div3</a><br />
<a class="showSingle" target="4">show Div4</a> <a class="hideSingle" target="4">hide Div4</a><br />
</div>
<div id="div1" class="targetDiv">1. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
<div id="div2" class="targetDiv">2. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
<div id="div3" class="targetDiv">3. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</div>
<div id="div4" class="targetDiv">4. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>

jQuery

jQuery(function () {
jQuery('#showall').click(function () {
jQuery('.targetDiv').show();
});
jQuery('#hideall').click(function () {
jQuery('.targetDiv').hide();
});
jQuery('.showSingle').click(function () {
// jQuery('.targetDiv').hide();
jQuery('#div' + jQuery(this).attr('target')).show();
});
jQuery('.hideSingle').click(function () {
jQuery('#div' + jQuery(this).attr('target')).hide();
});
});

All http://jsfiddle.net/kpreiskorn/m5xmwvhw/11/

Hits: 4

Proudly powered by WordPress | Theme: Baskerville 2 by Anders Noren.

Up ↑