text:
\documentclass[Screen16to9,17pt]{foils}
\usepackage{zencurity-slides}

\externaldocument{communication-and-network-security-exercises}
\selectlanguage{english}

\begin{document}

\mytitlepage
{4. Encrypting the Network}
{Communication and Network Security \the\year}

\slide{Goals for today}

\hlkimage{6cm}{thomas-galler-hZ3uF1-z2Qc-unsplash.jpg}

Todays goals:
\begin{list2}
\item Introduce Encryption
\item Present the common algorithms, protocols, and tools used
\end{list2}

Photo by Thomas Galler on Unsplash

\slide{Plan for today}

{~}
\hlkrightpic{8cm}{0cm}{Encrypt_all_the_things.png}

\begin{list1}
\item Subjects
\begin{list2}
\item Basic cryptography - Encryption Decryption - Hashing
\item Short introduction to algorithms RSA, AES
\item Diffie Helman exchange and Transport Layer Security (TLS)
\end{list2}
\item Exercises
\begin{list2}
\item \link{https://www.ssllabs.com/} and sslscan checking servers
\item sslstrip \link{https://moxie.org/software/sslstrip/}
\item mitmproxy \link{https://mitmproxy.org/}
\item sslsplit \link{https://www.roe.ch/SSLsplit}
\end{list2}
\end{list1}

\slide{Time schedule}

\begin{list2}
\item 17:00 - 18:15\\
Introduction and basics
\item 30min break\\

\item 18:45 - 19:30\\

\item 15min break\\

\item 19:45 -20:30 45min\\
\end{list2}

\slide{Reading Summary}

\begin{quote}
It is not clear that the link layer is the right one for security. In a coffeeshop, the security association is terminated by the store: is there any reason you should trust the shopkeeper? Perhaps link-layer security makes some sense in a home, where you control both the access point and the wireless machines. However, we prefer end-to-end security at the network layer or in the
applications.
\end{quote} Source: Cheswick-chap2.pdf Firewalls and Internet Security: Repelling the Wily Hacker , Second Edition, William R. Cheswick, Steven M. Bellovin, and Aviel D. Rubin

\begin{list2}
\item Read: PPA chapters 7,8,9
\item PPA chapter 7: Network Layer Protocols
\item PPA chapter 8: Transport Layer Protocols
\item PPA chapter 9: Common Upper-Layer Protocols
\item Skim: table of contents of RFC5246 The TLS Protocol Version 1.2
\item wikipedia page \link{https://en.wikipedia.org/wiki/Transport_Layer_Security}
\end{list2}

\slide{Reading Summary, continued}

\begin{alltt}\footnotesize
user@Projects:~$ ping -s 1472 -M do 91.102.91.18
PING 91.102.91.18 (91.102.91.18) 1472(1500) bytes of data.
1480 bytes from 91.102.91.18: icmp_seq=1 ttl=244 time=7.43 ms
1480 bytes from 91.102.91.18: icmp_seq=2 ttl=244 time=7.20 ms
...
user@Projects:~$ ping -s 1474 -M do 91.102.91.18
PING 91.102.91.18 (91.102.91.18) 1474(1502) bytes of data.
ping: local error: Message too long, mtu=1500
ping: local error: Message too long, mtu=1500
^C
--- 91.102.91.18 ping statistics ---
2 packets transmitted, 0 received, +2 errors, 100% packet loss, time 1025ms
\end{alltt}

\begin{list1}
\item PPA chapter 7: Network Layer Protocols
\begin{list2}
\item What is normal network traffic?
\item Great reference chapter for basic protocols
\item Plus basic IPv6
\item Re PATH MTU etc. Linux MTU 1500 check \verb+ping -s 1472 -M do+
\end{list2}
\end{list1}

\slide{Reading Summary, continued}

\hlkimage{10cm}{tcp_state_diagram.png}

\begin{list1}
\item PPA chapter 8: Transport Layer Protocols
\begin{list2}
\item Again the TCP 3-way handshake is described Note: can be done in 4 packets
\item Closed TCP returns Reset (RST) packet, closed UDP returns ICMP port unreachable
\end{list2}
\end{list1}

\slide{Reading Summary, continued}

\hlkimage{10cm}{dns-1.pdf}

\begin{list1}
\item PPA chapter 9: Common Upper-Layer Protocols
\begin{list2}
\item Dynamic Host Configuration Protocol (DHCP) port 67/udp and 68/udp, and options
\item Domain Name System (DNS) common query types A, NS, CNAME, MX, TXT, AAAA, AXFR, IXFR
\end{list2}
\end{list1}

\slide{Confidentiality Integrity Availability}

\hlkimage{8cm}{cia-triad-uk.pdf}

\begin{list1}
\item We want to protect something
\item Confidentiality - data holdes hemmelige
\item Integrity - data ændres ikke uautoriseret
\item Availability - data og systemet er tilgængelige når de skal bruges
\end{list1}

\slide{What is data?}

{~}
\hlkrightpic{10cm}{0cm}{Linus3-04041999.jpg}

\begin{list1}
\item Personal data you dont want to loose:
\begin{list2}
\item Wedding pictures
\item Pictures of your children
\item Sextapes
\item Personal finances
\end{list2}
\end{list1}

Source: picture of my son less than 24 hours old - precious!

\slide{Why think of security?}

\hlkimage{8cm}{1984-not-instruction-manual.jpg}

\begin{quote}
	Privacy is necessary for an open society in the electronic age. Privacy is not secrecy. A private matter is something one doesn't want the whole world to know, but a secret matter is something one doesn't want anybody to know. Privacy is the power to selectively reveal oneself to the world.
\end{quote}
Source: A Cypherpunk's Manifesto by Eric Hughes, 1993

\slide{Solidaritetskryptering}

Hvorfor skal vi kryptere?

\begin{alltt}
       Køn
                       Seksualitet
 Tro religion       hatecrimes

 Politisk overbevisning, eller blot aktiv

 Whistleblowers             soldater      diplomater
\end{alltt}

\centerline{Du bestemmer ikke hvem der diskrimineres eller trues i andre lande}

\vskip2cm

Når vi krypterer hjælper vi andre! {\bf Solidaritetskryptering}

\slide{Person in the middle attacks}

\begin{list1}
\item ARP spoofing, ICMP redirects, the classics
\item Used to be called Man in The Middle MiTM
\begin{list2}
\item ICMP redirect
\item ARP spoofing
\item Wireless listening and spoofing higher levels like  airpwn-ng \link{https://github.com/ICSec/airpwn-ng}
\end{list2}
\item Usually aimed at unencrypted protocols
\item Today we only talk about getting the data, not how to perform higher level attacks
\end{list1}

\slide{Basic cryptography}

{~}
\hlkrightpic{9cm}{-1cm}{mitm-2019.png}

\begin{list2}
\item Confidentiality - data holdes hemmelige
\item Integrity - data ændres ikke uautoriseret
\item A common attack category is children intercepting messages
\item or MiTM Mini in the Middle in this case
\end{list2}
\slide{Cryptography}

\begin{list1}
\item Cryptography or cryptology is the practice and study of techniques for secure communication
\item Modern cryptography is heavily based on mathematical theory and computer science practice; cryptographic algorithms are designed around computational hardness assumptions, making such algorithms hard to break in practice by any adversary
\item Symmetric-key cryptography refers to encryption methods in which both the sender and receiver share the same key, to ensure confidentiality, example algorithm AES
\item Public-key cryptography (like RSA) uses two related keys, a key pair of a public key and a private key. This allows for easier key exchanges, and can provide confidentiality, and methods for signatures and other services
\end{list1}

Source: \link{https://en.wikipedia.org/wiki/Cryptography}

\slide{Kryptografi er svært}

%Stoler vi på de andre autentificeringsmetoder?}
\hlkimage{20cm}{crypto-class.png}

Åbent kursus på Stanford\\
\link{http://crypto-class.org/}

\slide{Kryptering: Cryptography Engineering}

\hlkimage{6cm}{book-ce-150w.jpg}

\emph{Cryptography Engineering} by
Niels Ferguson, Bruce Schneier, and Tadayoshi Kohno\\
\link{https://www.schneier.com/book-ce.html}

\slide{Serious Cryptography}

\hlkimage{5cm}{serious_crypto_cover-front-final.png}

\emph{Serious Cryptography
A Practical Introduction to Modern Encryption}
by Jean-Philippe Aumasson
November 2017, 312 pp.
ISBN-13:
978-1-59327-826-7
\link{https://nostarch.com/seriouscrypto}

\slide{Encryption Decryption}

\slide{Kryptografi}

\hlkimage{12cm}{images/crypto-rot13.pdf}

\begin{list1}
\item Kryptografi er læren om, hvordan man kan kryptere data
\item Kryptografi benytter algoritmer som sammen med nøgler giver en
  ciffertekst
\item  - der kun kan læses ved hjælp af den tilhørende nøgle
\end{list1}

\slide{Kryptografiske principper}

\begin{list1}
\item Algoritmerne er kendte
\item Nøglerne er hemmelige
\item Nøgler har en vis levetid - de skal skiftes ofte
\item Et successfuldt angreb på en krypto-algoritme er enhver genvej
  som kræver mindre arbejde end en gennemgang af alle nøglerne
\item Nye algoritmer, programmer, protokoller m.v. skal gennemgås nøje!
\item Se evt. Snake Oil Warning Signs:
Encryption Software to Avoid\\
\link{http://www.interhack.net/people/cmcurtin/snake-oil-faq.html}
\end{list1}

\slide{DES, Triple DES og AES}

\hlkimage{15cm}{images/AES_head.png}

\begin{list1}
\item DES kryptering - gammel og pensioneret!
\item Der blev i 2001 vedtaget en ny standard algoritme Advanced Encryption
  Standard (AES) som afløser Data Encryption Standard (DES)
\item Algoritmen hedder Rijndael og er udviklet
af Joan Daemen og Vincent Rijmen.
%\item \emph{Rijndael is available for free. You can use it for
%whatever purposes  you want, irrespective of whether
%it is accepted as AES or not.}
\item Se også \link{https://en.wikipedia.org/wiki/Advanced_Encryption_Standard}
\item Findes animationer (med fejl) \link{https://www.youtube.com/watch?v=mlzxpkdXP58}
\end{list1}

\slide{AES Advanced Encryption Standard}

\hlkimage{10cm}{aes-overview.png}

\begin{list2}
\item The official Rijndael web site displays this image to promote understanding of the Rijndael round transformation [8].
\item Key sizes 128,192,256 bit typical
\item Some extensions in cryptosystems exist: XTS-AES-256 really is 2 instances of AES-128 and 384 is two instances of AES-192 and 512 is two instances of AES-256
\item \link{https://en.wikipedia.org/wiki/RSA_(cryptosystem)}
\end{list2}

\slide{RSA}

\begin{quote}
RSA (Rivest–Shamir–Adleman) is one of the first public-key cryptosystems and is widely used for secure data transmission. ...
In RSA, this asymmetry is based on the practical difficulty of the factorization of the product of two large prime numbers, the "factoring problem". The acronym RSA is made of the initial letters of the surnames of Ron Rivest, Adi Shamir, and Leonard Adleman, who first publicly described the algorithm in 1978.
\end{quote}

\begin{list2}
\item Key sizes	1,024 to 4,096 bit typical
\item  Quote from: \link{https://en.wikipedia.org/wiki/RSA_(cryptosystem)}
\end{list2}

\slide{RSA operation}

\begin{quote}\small
The RSA algorithm involves four steps: key generation, key distribution, encryption and decryption.

A basic principle behind RSA is the observation that it is practical to find three very large positive integers e, d and n such that with modular exponentiation for all integers $m$ (with $0 ≤ m < n$):

${\displaystyle (m^{e})^{d}\equiv m{\pmod {n}}} {\displaystyle (m^{e})^{d}\equiv m{\pmod {n}}}$

and that knowing e and n, or even m, it can be extremely difficult to find d. The triple bar (≡) here denotes modular congruence.

In addition, for some operations it is convenient that the order of the two exponentiations can be changed and that this relation also implies:

${\displaystyle (m^{d})^{e}\equiv m{\pmod {n}}} {\displaystyle (m^{d})^{e}\equiv m{\pmod {n}}}$

RSA involves a public key and a private key. The public key can be known by everyone, and it is used for encrypting messages. The intention is that messages encrypted with the public key can only be decrypted in a reasonable amount of time by using the private key. The public key is represented by the integers n and e; and, the private key, by the integer d (although n is also used during the decryption process. Thus, it might be considered to be a part of the private key, too). m represents the message (previously prepared with a certain technique explained below).
\end{quote}

Source: \link{https://en.wikipedia.org/wiki/RSA_(cryptosystem)}

\slide{Public key kryptografi - 1}

\hlkimage{12cm}{images/crypto-public-key.pdf}

\begin{list1}
\item privat-nøgle kryptografi (eksempelvis AES) benyttes den samme
  nøgle til kryptering og dekryptering
\item offentlig-nøgle kryptografi (eksempelvis RSA) benytter to
  separate nøgler til kryptering og dekryptering
\end{list1}

\slide{Public key kryptografi - 2}

\hlkimage{12cm}{images/crypto-public-key-2.pdf}

\begin{list1}
\item offentlig-nøgle kryptografi (eksempelvis RSA) bruger den private
  nøgle til at dekryptere
\item man kan ligeledes bruge offentlig-nøgle kryptografi til at
  signere dokumenter\\ - som så verificeres med den offentlige nøgle
\item NB: Kryptering alene sikrer ikke anonymitet
\end{list1}

\slide{Elliptic Curve }

\begin{quote}
Elliptic-curve cryptography (ECC) is an approach to public-key cryptography based on the algebraic structure of elliptic curves over finite fields. ECC requires smaller keys compared to non-EC cryptography (based on plain Galois fields) to provide equivalent security.[1]
\end{quote}

\begin{list2}
\item Today we use \link{https://en.wikipedia.org/wiki/Elliptic-curve_cryptography}
\end{list2}

\slide{Hashing - MD5 message digest funktion}

\hlkimage{16cm}{images/message-digest-1.pdf}

\begin{list1}
\item HASH algoritmer giver en næsten unik værdi baseret på input

\item værdien ændres radikalt selv ved små ændringer i input
\item MD5 er blandt andet beskrevet i RFC-1321: The MD5 Message-Digest
  Algorithm
\item Algoritmen MD5 er baseret på MD4, begge udviklet af Ronald
  L. Rivest
\item Både MD5 og SHA-1 er idag gamle og skal generelt ikke bruges mere
\item Idag benyttes eksempelvis \link{https://en.wikipedia.org/wiki/PBKDF2}
\end{list1}

\slide{Base64}

\begin{quote}
In computer science, Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding. Each Base64 digit represents exactly 6 bits of data. Three 8-bit bytes (i.e., a total of 24 bits) can therefore be represented by four 6-bit Base64 digits.
\end{quote}

\begin{list2}
	\item Encoding data is not secure, can be decoded
	\item \link{https://en.wikipedia.org/wiki/Base64}
\end{list2}

\slide{Old skool NT hashes}

\begin{list1}
  \item NT LAN manager hash værdier er noget man typisk kunne samle op i
  netværk
\item det er en hash værdi af et password som man ikke burde kunne
  bruge til noget - hash algoritmer er envejs
\item opbygningen gør at man kan forsøge brute-force på 7 tegn ad
  gangen!
\item en moderne pc med l0phtcrack kan nemt knække de fleste password
  på få dage!
\item og sikkert 25-30\% indenfor den første dag - hvis der ingen
  politik er omkring kodeord!
\item ved at generere store tabeller, eksempelvis 100GB kan man dække
  mange hashværdier af passwords med almindelige bogstaver, tal og
  tegn - og derved knække passwordshashes på sekunder. Søg efter
  rainbowcrack med google
\end{list1}

\slide{l0phtcrack LC4}
\hlkimage{7cm}{images/lc4_splash.png}

\begin{alltt}
\small
Consider that at one of the largest technology companies, where policy
required that passwords exceed 8 characters, mix cases, and include
numbers or symbols...

L0phtCrack obtained 18\% of the passwords in 10 minutes
90\% of the passwords were recovered within 48 hours on a Pentium II/300
The Administrator and most Domain Admin passwords were cracked
\link{http://www.atstake.com/research/lc/}
\end{alltt}

\slide{Cracking passwords}

\begin{list2}
\item Hashcat is the world's fastest CPU-based password recovery tool.
\item oclHashcat-plus is a GPGPU-based multi-hash cracker using a brute-force attack (implemented as mask attack), combinator attack, dictionary attack, hybrid attack, mask attack, and rule-based attack.
\item oclHashcat-lite is a GPGPU cracker that is optimized for cracking performance. Therefore, it is limited to only doing single-hash cracking using Markov attack, Brute-Force attack and Mask attack.
\item John the Ripper password cracker old skool men stadig nyttig
\end{list2}

Source:\\
\link{http://hashcat.net/wiki/}\\
\link{http://www.openwall.com/john/}

\slide{Encryption key length - who are attacking you}

\hlkimage{9cm}{encryption-crack.png}

Source: \link{http://www.mycrypto.net/encryption/encryption_crack.html}

{\small
More up to date:  In 1998, the EFF built Deep Crack for less than \$250,000\\
\link{https://en.wikipedia.org/wiki/EFF_DES_cracker}\\
FPGA Based UNIX Crypt Hardware Password Cracker - ~100 EUR in 2006\\
\link{http://www.sump.org/projects/password/}}

\slide{Pass the hash}

Lots of tools in pentesting pass the hash, reuse existing credentials and tokens
\emph{Still Passing the Hash 15 Years Later}\\
\link{http://passing-the-hash.blogspot.dk/2013/04/pth-toolkit-for-kali-interim-status.html}

\begin{quote}
If a domain is built using only modern Windows OSs and COTS products (which know how to operate within these new constraints), and configured correctly with no shortcuts taken, then these protections represent a big step forward.
\end{quote}

Source:\\
{\small\link{http://www.harmj0y.net/blog/penetesting/pass-the-hash-is-dead-long-live-pass-the-hash/}
\link{https://samsclass.info/lulz/pth-8.1.htm}}

\slide{Mimikatz}

\begin{quote}
mimikatz is a tool I've made to learn C and make somes experiments with Windows security.

It's now well known to extract plaintexts passwords, hash, PIN code and kerberos tickets from memory. mimikatz can also perform pass-the-hash, pass-the-ticket or build Golden tickets.
\end{quote}

\begin{list2}
\item Understatement of the year, candidate
\item Proof of concept code, that is abused a lot by everyone, malware to pentesters
\item \url{https://github.com/gentilkiwi/mimikatz}
\end{list2}

\centerline{Your anti-virus application SHOULD catch mimikatz}

\slide{Encryption on the web}

\slide{Diffie Helman exchange}

{~}
\hlkrightpic{7cm}{-15mm}{800px-Diffie-Hellman_Key_Exchange.png}

\begin{quote}
Diffie–Hellman key exchange (DH)[nb 1] is a method of securely exchanging cryptographic keys over a public channel and was one of the first public-key protocols as originally conceptualized by Ralph Merkle and named after Whitfield Diffie and Martin Hellman.[1][2] DH is one of the earliest practical examples of public key exchange implemented within the field of cryptography.
... The scheme was first published by Whitfield Diffie and Martin Hellman in 1976
\end{quote}

\begin{list2}
\item Quote from: {\small \link{https://en.wikipedia.org/wiki/Diffie-Hellman_key_exchange}}
\item Today we use \link{https://en.wikipedia.org/wiki/Elliptic-curve_cryptography}
\end{list2}

\slide{Transport Layer Security (TLS)}

\hlkimage{5cm}{crypto-class.png}

\begin{list1}
\item Oprindeligt udviklet af Netscape Communications Inc.
\item Secure Sockets Layer SSL er idag blevet adopteret af IETF og kaldes
derfor også for Transport Layer Security TLS
TLS er baseret på SSL Version 3.0
\item RFC-2246 The TLS Protocol Version 1.0 fra Januar 1999
\item RFC-3207 SMTP STARTTLS
\item Det er svært!
\item Stanford Dan Boneh udgiver en masse omkring crypto\\ \link{https://crypto.stanford.edu/~dabo/cryptobook/}
\end{list1}

\slide{SSL/TLS udgaver af protokoller}
\hlkimage{12cm}{imap-ssl.png}

\begin{list1}
\item Mange protokoller findes i udgaver hvor der benyttes SSL
\item HTTPS vs HTTP
\item IMAPS, POP3S, osv.
\item Bemærk: nogle protokoller benytter to porte IMAP 143/tcp vs IMAPS 993/tcp
\item Andre benytter den samme port men en kommando som starter:
\item SMTP STARTTLS RFC-3207
\end{list1}

\slide{Secure protocols}

\begin{list1}
\item Securing e-mail
\begin{list2}
\item Pretty Good Privacy - Phil Zimmermann
\item OpenPGP = e-mail security
\end{list2}
\item Network sessions use SSL/TLS
\begin{list2}
\item Secure Sockets Layer SSL / Transport Layer Services TLS
\item Encrypting data sent and received
\item SSL/TLS already used for many protocols as a wrapper: POP3S, IMAPS, SSH, SMTP+TLS m.fl.
\end{list2}
\item Encrypting traffic at the network layer - Virtual Private Networks VPN
\begin{list2}
\item {\color{green}IPsec IP Security Framework, se også L2TP}
\item {\color{red} PPTP Point to Point Tunneling Protocol - dårlig og usikker, brug den ikke mere!}
\item OpenVPN uses SSL/TLS across TCP or UDP
\end{list2}
\end{list1}

\slide{Email er usikkert}

\hlkimage{14cm}{email-uden-kryptering.png}

\centerline{Email uden kryptering - er som et postkort}

\slide{Email med OpenPGP kryptering - afsendelse}

\hlkimage{14cm}{email-med-kryptering.png}

\centerline{En sikker krypteret email er ikke sværere at sende}

\slide{Krypteret OpenPGP Email under transporten}

\hlkimage{10cm}{modtaget-email-med-kryptering.png}

\centerline{En sikker krypteret email er beskyttet undervejs}

\slide{Fokus \the\year: TLS og VPN indstillinger}

\hlkimage{16cm}{bettercrypto-nginx.png}

\begin{list2}
\item De fleste har https nu, men er det konfigureret optimalt
\item Vi bruger også VPN til at forbinde sites, kontorer
\item Anbefaler at alle indstillingerne gennemgås!
\end{list2}

\slide{Nmap efter SSL og TLS}

\hlkimage{7cm}{nmap-sslv2.png}

\begin{list1}
\item Nu vi har lært Kali og Nmap at kende
\begin{list2}
\item Find nemt alle ssl version 2 og 3\\
\verb+nmap --script ssl-enum-ciphers+
\item Brug ssllabs https://www.ssllabs.com/
\end{list2}
\end{list1}

\slide{sslscan}

\begin{alltt}\small
root@kali:~# sslscan --ssl2 web.kramse.dk
Version: 1.10.5-static
OpenSSL 1.0.2e-dev xx XXX xxxx

Testing SSL server web.kramse.dk on port 443
...
  SSL Certificate:
Signature Algorithm: sha256WithRSAEncryption
RSA Key Strength:    2048

Subject:  *.kramse.dk
Altnames: DNS:*.kramse.dk, DNS:kramse.dk
Issuer:   AlphaSSL CA - SHA256 - G2
\end{alltt}

Source:
Originally sslscan from http://www.titania.co.uk
 but use the version on Kali

SSLscan can check your own sites, while Qualys SSLLabs only can test from hostname

\slide{Example Weak DH paper}

\hlkimage{13cm}{weakdh-logjam.png}

Source: \link{https://weakdh.org/} and \\
\link{https://weakdh.org/imperfect-forward-secrecy-ccs15.pdf}

Every year in different SSL/TLS implementations there have been problems.

\slide{Why?, because things like Superfish February 2015}

\hlkimage{12cm}{robert-graham-superfish-cert.png}

Lenovo laptops included Adware, which did SSL/TLS Man in the Middle on connections.
They had a root certificate installed on the Windows operating system, WTF!

{\footnotesize Sources:\\
\link{https://en.wikipedia.org/wiki/Superfish}\\
\link{http://blog.erratasec.com/2015/02/extracting-superfish-certificate.html}\\
\link{http://www.version2.dk/blog/kibana4-superfish-og-emergingthreats-81610}\\
}{\tiny\link{https://www.eff.org/deeplinks/2015/02/further-evidence-lenovo-breaking-https-security-its-laptops}
}

\slide{FREAK March 2015}

\begin{quote}\small
"A group of cryptographers at INRIA, Microsoft Research and IMDEA have discovered some serious vulnerabilities in OpenSSL (e.g., Android) clients and Apple TLS/SSL clients (e.g., Safari) that allow a 'man in the middle attacker' to downgrade connections from 'strong' RSA to 'export-grade' RSA. These attacks are real and exploitable against a shocking number of websites -- including government websites. Patch soon and be careful."
\end{quote}

Source: Matthew Green, cryptographer and research professor at Johns Hopkins Univ\\
{\footnotesize\link{http://blog.cryptographyengineering.com/2015/03/attack-of-week-freak-or-factoring-nsa.html}\\
\link{https://www.smacktls.com/} \link{https://freakattack.com/}
}

OpenSSL, LibreSSL, Apple SSL flaw exit exit exit!, Android SSL, certs certs!!!111, SSLv3, Heartbleed, MS TLS

\vskip 1cm
PS From now on its TLS! Not SSL anymore, any SSLv2, SSLv3 is old and vulnerable

\slide{Heartbleed CVE-2014-0160}

\hlkimage{18cm}{heartbleed-com.png}

\centerline{Nok det mest kendte SSL/TLS exploit}

Source: \link{http://heartbleed.com/}

\slide{Heartbleed hacking}

\begin{alltt}\footnotesize
  06b0: 2D 63 61 63 68 65 0D 0A 43 61 63 68 65 2D 43 6F  -cache..Cache-Co
  06c0: 6E 74 72 6F 6C 3A 20 6E 6F 2D 63 61 63 68 65 0D  ntrol: no-cache.
  06d0: 0A 0D 0A 61 63 74 69 6F 6E 3D 67 63 5F 69 6E 73  ...action=gc_ins
  06e0: 65 72 74 5F 6F 72 64 65 72 26 62 69 6C 6C 6E 6F  ert_order&billno
  06f0: 3D 50 5A 4B 31 31 30 31 26 70 61 79 6D 65 6E 74  =PZK1101&payment
  0700: 5F 69 64 3D 31 26 63 61 72 64 5F 6E 75 6D 62 65  _id=1&card_numbe
  0710: XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX   r=4060xxxx413xxx
  0720: 39 36 26 63 61 72 64 5F 65 78 70 5F 6D 6F 6E 74  96&card_exp_mont
  0730: 68 3D 30 32 26 63 61 72 64 5F 65 78 70 5F 79 65  h=02&card_exp_ye
  0740: 61 72 3D 31 37 26 63 61 72 64 5F 63 76 6E 3D 31  ar=17&card_cvn=1
  0750: 30 39 F8 6C 1B E5 72 CA 61 4D 06 4E B3 54 BC DA  09.l..r.aM.N.T..
\end{alltt}

\begin{list2}
\item Obtained using Heartbleed proof of concepts - Gave full credit card details
\item "can XXX be exploited" - yes, clearly! PoCs ARE needed\\
without PoCs even Akamai wouldn't have repaired completely!
\item The internet was ALMOST fooled into thinking getting private keys from Heartbleed was not possible - scary indeed.
\end{list2}

\slide{Key points after heartbleed}

\hlkimage{16cm}{ssl-tls-breaks-timeline.png}
Source: picture source\\ {\footnotesize\link{https://www.duosecurity.com/blog/heartbleed-defense-in-depth-part-2}}
\begin{list2}
\item Writing SSL software and other secure crypto software is hard
\item Configuring SSL is hard\\
check you own site \link{https://www.ssllabs.com/ssltest/}
\item SSL is hard, finding bugs "all the time"
\link{http://armoredbarista.blogspot.dk/2013/01/a-brief-chronology-of-ssltls-attacks.html}
\end{list2}

\slide{Decrypting TLS Browser Traffic With Wireshark }

\hlkimage{16cm}{wireshark-decrypt-ssl.png}

\begin{list2}
\item  Firefox and Chrome both support logging the symmetric session key used to encrypt TLS traffic to a file
\item Wireshark can read this file - and decrypt sessions - Nifty trick
\item Another option is to use Burp
\end{list2}

Source: great blog article about the features used\\
{\tiny\link{https://jimshaver.net/2015/02/11/decrypting-tls-browser-traffic-with-wireshark-the-easy-way/}}

\slide{HTTPS Everywhere}

\hlkimage{5cm}{HTTPS_Everywhere_new_logo.jpg}
\begin{quote}
HTTPS Everywhere is a Firefox extension produced as a collaboration between The Tor Project and the Electronic Frontier Foundation. It encrypts your communications with a number of major websites.
\end{quote}

\centerline{\link{http://www.eff.org/https-everywhere}}

\slide{Basic cryptography}

{~}
\hlkimage{6cm}{mitm-2019.png}

\begin{list2}
\item A common attack category is children intercepting messages
\item or MiTM Mini in the Middle in this case
\end{list2}

\slide{sslstrip - transparently hijack HTTP}

\begin{quote}
This tool provides a demonstration of the HTTPS stripping attacks that I presented at Black Hat DC 2009. It will transparently hijack HTTP traffic on a network, watch for HTTPS links and redirects, then map those links into either look-alike HTTP links or homograph-similar HTTPS links. It also supports modes for supplying a favicon which looks like a lock icon, selective logging, and session denial. For more information on the attack, see the video from the presentation below.
\end{quote}

\link{https://moxie.org/software/sslstrip/}

\begin{list2}
\item \emph{First, arpspoof convinces a host that our MAC address is the router's MAC address, and the target begins to send us all its network traffic.}
\item \emph{supplying a favicon which looks like a lock icon}
\end{list2}

\slide{mitmproxy -  interactive HTTPS proxy}

\hlkimage{8cm}{mitmproxy-web.png}

\link{https://mitmproxy.org/}

\begin{list2}
\item Command line, Web interface, Python API
\item Intercept HTTP and HTTPS requests and responses and modify them on the fly
\item Reverse proxy mode to forward traffic to a specified server
\item Make scripted changes to HTTP traffic using Python
\item SSL/TLS certificates for interception are generated on the fly
\end{list2}

\slide{sslsplit  - transparent SSL/TLS interception}

\begin{quote}\small
Overview\\
SSLsplit is designed to transparently terminate connections that are redirected to it using a network address translation engine. SSLsplit then terminates SSL/TLS and initiates a new SSL/TLS connection to the original destination address, while logging all data transmitted. Besides NAT based operation, SSLsplit also supports static destinations and using the server name indicated by SNI as upstream destination. SSLsplit is purely a transparent proxy and cannot act as a HTTP or SOCKS proxy configured in a browser.
\end{quote}

\link{https://www.roe.ch/SSLsplit}

\begin{list2}
\item SSLsplit implements a number of defences against mechanisms which would normally prevent MitM attacks or make them more difficult
\item {\small SSLsplit can deny OCSP requests in a generic way. For HTTP and HTTPS connections, SSLsplit mangles headers to prevent server-instructed public key pinning (HPKP), avoid strict transport security restrictions (HSTS), avoid Certificate Transparency enforcement (Expect-CT) and prevent switching to QUIC/SPDY, HTTP/2 or WebSockets (Upgrade, Alternate Protocols)}
\end{list2}

\centerline{We will not really run SSLsplit, but its interesting}

\exercise{ex:SSLScanner}
\exercise{ex:burp-basic}
\exercise{ex:burp-tls}
\exercise{ex:sslstrip}
\exercise{ex:mitmproxy}
\exercise{ex:sslsplit}

\slide{Other crypto related stuff}

\slide{PRNG}

\hlkimage{21cm}{debian-prng.png}

{\small\link{https://en.wikipedia.org/wiki/Random_number_generator_attack\#Debian_OpenSSL}}

\centerline{The random number generator is VITAL for crypto security}

Check out modern CPUs and Linux response to this\\
 \link{https://en.wikipedia.org/wiki/RdRand}

\slide{Fokus \the\year: DNS og email}

\hlkrightpic{10cm}{-2cm}{brian-patrick-tagalog-680954-unsplash.jpg}
{~}

\begin{list2}
\item Vi er afhængige af email, modtagelse og afsendelse
\item Når vi modtager skal det helst gå hurtigt
\item Når vi sender skal vi ikke ende i spam mappen
\item Phishing, hvem kan sende \emph{fra vores domæne}
\end{list2}

\slide{Various key attack types, clients and employees}

\begin{list2}
\item Phishing - sending fake emails, to collect credentials
\item Spear phishing - targetted attacks
\item Person in the middle - sniffing and changing data in transit
\item Drive-by attacks - web pages infected with malware, often ad servers
\item Malware transferred via USB or email
\item Credential Stuffing, Password related, like re-use of password, see slide about being pwned
\end{list2}

\vskip 1cm
\centerline{\Large\bf If we all wait a bit, and not click links immediately}

\vskip 1cm
Hackers try to create "urgency", click this or loose money

\slide{DNS er mere end navneopslag}

\begin{list1}
  \item består af resource records med en type:
    \begin{list2}
\item adresser A-records
\item IPv6 adresser AAAA-records
\item autoritative navneservere NS-records
\item post, mail-exchanger MX-records
\item flere andre: md ,  mf ,  cname ,  soa ,
                  mb , mg ,  mr ,  null ,  wks ,  ptr ,
                  hinfo ,  minfo ,  mx ....
\end{list2}
\end{list1}
\begin{alltt}
        IN      MX      10      mail.zencurity.dk.
        IN      MX      20      mail2.zencurity.dk.
\end{alltt}

\slide{SMTP Simple Mail Transfer Protocol}

\begin{alltt}\tiny
hlk@bigfoot:hlk$ telnet mail.kramse.dk 25
Connected to sunny.
220 sunny.kramse.dk ESMTP Postfix
HELO bigfoot
250 sunny.kramse.dk
MAIL FROM: Henrik
250 Ok
RCPT TO: hlk@kramse.dk
250 Ok
DATA
354 End data with <CR><LF>.<CR><LF>
hejsa
.
250 Ok: queued as 749193BD2
QUIT
221 Bye
\end{alltt}

\begin{list2}
\item RFC-821 SMTP Simple Mail Transfer Protocol fra 1982
\item \link{http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol}
\end{list2}

\slide{DNS attacks, Your registrar}

\hlkimage{10cm}{krebs-lenovo-google-dns-hack.png}
\begin{list1}
%\item DNS is the Domain Name System, \link{https://en.wikipedia.org/wiki/Dns}
\item DNS insecurity has huge impact on your security!
\item Most are denial of service, by may create Mitm or confidentiality concerns
\item Select DNS providers with care
\end{list1}

Sources:\\
{\tiny
\link{https://krebsonsecurity.com/2015/02/webnic-registrar-blamed-for-hijack-of-lenovo-google-domains/}\\
\link{http://www.version2.dk/artikel/google-og-lenovo-defaced-som-foelge-af-overset-sikkerhedsproblemstilling-91295}}

\slide{DNSSEC get started now}

\hlkimage{12cm}{cz-nic-dnssec-tlsa-validator.png}

\begin{quote}
"TLSA records store hashes of remote server TLS/SSL certificates. The authenticity of a TLS/SSL certificate for a domain name is verified by DANE protocol (RFC 6698). DNSSEC and TLSA validation results are displayer by using several icons."
\end{quote}

\slide{DNSSEC and DANE}

\begin{quote}
"Objective:

Specify mechanisms and techniques that allow Internet applications to
establish cryptographically secured communications by using information
distributed through DNSSEC for discovering and authenticating public
keys which are associated with a service located at a domain name."
\end{quote}

\begin{list1}
\item DNS-based Authentication of Named Entities (dane)
\end{list1}

\slide{Email security \the\year - Goals}

\begin{list2}
\item SPF Sender Policy Framework\\ {\footnotesize\link{https://en.wikipedia.org/wiki/Sender_Policy_Framework}}
\item DKIM DomainKeys Identified Mail\\
{\footnotesize\link{https://en.wikipedia.org/wiki/DomainKeys_Identified_Mail}}
\item DMARC Domain-based Message Authentication, Reporting and Conformance\\
{\footnotesize\link{https://en.wikipedia.org/wiki/DMARC}}
\item DANE DNS-based Authentication of Named Entities\\ {\footnotesize\link{https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities}}
\item Brug allesammen, check efter ændringer!
\end{list2}

\slide{SMTP TLS}

\begin{quote}
The STARTTLS command for IMAP and POP3 is defined in RFC 2595, for SMTP in RFC 3207, for XMPP in RFC 6120 and for NNTP in RFC 4642. For IRC, the IRCv3 Working Group
 has defined the STARTTLS extension. FTP uses the command "AUTH TLS" defined in RFC 4217 and LDAP defines a protocol extension OID in RFC 2830. HTTP uses upgrade he
ader.
\end{quote}

\begin{list1}
\item SMTP was extended with support for Transport Layer Security TLS
\item Also called {\bf Opportunistic TLS}, where the quote is also from:\\ \link{https://en.wikipedia.org/wiki/Opportunistic_TLS}
\end{list1}

\slide{DNS over TLS vs DNS over HTTPS - DNS encryption}

\begin{list1}
\item Protocols exist that encrypt DNS data, like dnscrypt which is not RFC\\ standard \link{https://dnscrypt.info/} \link{https://en.wikipedia.org/wiki/DNSCrypt}
\item Today we have competing standards:
\item
\emph{Specification for DNS over Transport Layer Security (TLS)} (DoT), RFC 7858 MAY 2016\\
\link{https://en.wikipedia.org/wiki/DNS_over_TLS}

\item \emph{DNS Queries over HTTPS (DoH)} RFC 8484

\item How to cofigure DoT \link{https://dnsprivacy.org/wiki/display/DP/DNS+Privacy+Clients}
\end{list1}

\slide{Fokus \the\year: Laptop sikkerhed}

\hlkimage{13cm}{kelly-sikkema-212376-unsplash.jpg}

\begin{list2}
\item Relevant for alle
\item Hvordan sikrer vi at vi ikke mister værdierne, hardware og data typisk
\end{list2}

\slide{Secure Laptops}

\hlkimage{7cm}{librem-15-v3-turns99.png}

\begin{list2}
\item Laptops (og mobile enheder)
\item Hvad kendetegner en laptop?
\item Hardware naturligvis, en Macbook koster officielt mere end en brugt mellemklassebil
\item - og husk brugen af laptops
\item Er laptops sikre, og hvad betyder det?
\end{list2}

\slide{Are your data secure - data at rest}

\hlkimage{12cm}{images/data-integrity-1.pdf}

\begin{list1}
\item Stolen laptop, tablet, phone - can anybody read your data?
\item Do you trust "remote wipe"
\item How do you in fact wipe data securely off devices, and SSDs?
\item Encrypt disk and storage devices before using them in the first place!
\end{list1}

\slide{Circumvent security - single user mode boot}
\begin{list1}
\item Unix systems often allows boot into singleuser mode\\
press command-s when booting Mac OS X
\item Laptops can often be booted using PXE network or CD boot
\item Mac computers can become a Firewire disk\\
hold t when booting - firewire target mode
\item Unrestricted access to un-encrypted data
\item Moving hard drive to another computer is also easy
\end{list1}
\pause
\centerline{Physical access is often - {\bf game over}}

\slide{Encrypting hard disk}

\hlkimage{9cm}{images/apple-filevault.png}

\begin{list1}
\item Becoming available in the most popular client operating systems
\begin{list2}
\item Microsoft Windows Bitlocker
\item Apple Mac OS X - FileVault
\item FreeBSD GEOM og GBDE - encryption framework
\item Linux LUKS distributions like Ubuntu ask to encrypt home dir during installation
\item Some vendors have BIOS passwords, or disk passwords
\end{list2}
\end{list1}

\slide{Attacks on disk encryption}

\begin{list2}
\item Firewire, DMA \& Windows, Winlockpwn via FireWire\\
Hit by a Bus: Physical Access Attacks with Firewire Ruxcon 2006
\item Removing memory from live system - data is not immediately lost, and can be read under some circumstances\\
Lest We Remember: Cold Boot Attacks on Encryption Keys\\
\link{http://citp.princeton.edu/memory/}
\item This is very CSI or Hollywoord like - but a real threat
\item VileFault decrypts encrypted Mac OS X disk image files\\ \link{https://code.google.com/p/vilefault/}
\item  FileVault Drive Encryption (FVDE) (or FileVault2) encrypted volumes\\
\link{https://code.google.com/p/libfvde/}
\end{list2}

\centerline{So perhaps use both hard drive encryption AND turn off computer after use?}

\slide{... and deleting data}

{~}
\hlkrightpic{8cm}{0cm}{dban-screenshot.png}

\begin{list1}
\item Getting rid of data from old devices is a pain
\item Some tools will not overwrite data, leaving it vulnerable to recovery
\item Even secure erase programs might not work on SSD\\
 - due to reallocation of blocks
\item I have used Darik's Boot and Nuke ("DBAN")\\
\link{http://www.dban.org/}
\end{list1}

\slide{2018 attack}

\hlkimage{12cm}{ssd-attack-2018.png}
\emph{self-encrypting deception: weakness in the encryption of solid state drives (SSDs)}\\
\link{https://www.ru.nl/publish/pages/909282/draft-paper.pdf}

\slide{Github Public passwords?}

\hlkimage{13cm}{github-credentials.png}

 Sources:\\
{\footnotesize\link{https://twitter.com/brianaker/status/294228373377515522}\\
\link{http://www.webmonkey.com/2013/01/users-scramble-as-github-search-exposes-passwords-security-details/}\\
\link{http://www.leakedin.com/}\\
\link{http://www.offensive-security.com/community-projects/google-hacking-database/}
}

\vskip 5mm
\centerline{Use different passwords for different sites, yes - every site!}

\slide{kryptering, OpenPGP}

\begin{list1}
  \item kryptering er den eneste måde at sikre:
    \begin{list2}
      \item fortrolighed
      \item autenticitet
    \end{list2}
\item kryptering består af:
  \begin{list2}
    \item Algoritmer - eksempelvis RSA
    \item \emph{protokoller} - måden de bruges på
\item programmer - eksempelvis PGP
\end{list2}
\item fejl eller sårbarheder i en af komponenterne kan formindske
  sikkerheden
\item PGP = mail sikkerhed, se eksempelvis Enigmail plugin til Mozilla Thunderbird

\end{list1}

\slide{PGP/GPG verifikation af integriteten}

\begin{list1}
\item Pretty Good Privacy PGP
\item Gnu Privacy Guard GPG
\item Begge understøtter OpenPGP - fra IETF RFC-2440
\item Når man har hentet og verificeret en nøgle kan man fremover nemt
checke integriteten af software pakker
\end{list1}

\begin{alltt}
\small
hlk@bigfoot:postfix$ gpg --verify  postfix-2.1.5.tar.gz.sig
gpg: Signature made Wed Sep 15 17:36:03 2004 CEST using RSA key ID D5327CB9
gpg: Good signature from "wietse venema <wietse@porcupine.org>"
gpg:                 aka "wietse venema <wietse@wzv.win.tue.nl>"
\end{alltt}
%$

\slide{Secure Shell - SSH og SCP}

%\begin{center}
%\colorbox{white}{\includegraphics[width=12cm]{images/tshirt-9b.jpg}}
%\end{center}

\hlkimage{13cm}{images/openssh-banner.png}

\begin{list1}
\item Hvad er Secure Shell SSH?
\item Oprindeligt udviklet af Tatu Ylönen i Finland,\\
se \link{http://www.ssh.com}
\item SSH afløser en række protokoller som er usikre:
  \begin{list2}
  \item Telnet til terminal adgang
  \item r* programmerne, rsh, rcp, rlogin, ...
  \item FTP med brugerid/password
  \end{list2}
\end{list1}

\slide{SSH - de nye kommandoer er}
\begin{list1}
\item kommandoerne er:
\begin{list2}
  \item ssh - Secure Shell
  \item scp - Secure Copy
  \item sftp - secure FTP
  \end{list2}
\item Husk: SSH er både navnet på protokollerne - version 1 og 2 samt
  programmet \verb+ssh+ til at logge ind på andre systemer
\item SSH tillader også port-forward, tunnel til usikre protokoller,
  eksempelvis X protokollen til UNIX grafiske vinduer
\item {\bfseries NB: Man bør idag bruge SSH protokol version 2!}
\end{list1}

\slide{SSH nøgler}

I praksis benytter man nøgler fremfor kodeord
\begin{list1}
\item I kan lave jeres egne SSH nøgler med programmerne i Putty
\item Hvilken del skal jeg have for at kunne give jer adgang til en
  server?
\item Hvordan får jeg smartest denne nøgle?
\end{list1}

\slide{Installation af SSH nøgle}
\begin{list1}
\item Vi bruger login med password på kurset, men for
  fuldstændighedens skyld beskrives her hvordan nøgle installeres:

\begin{list2}
\item først skal der genereres et nøglepar {\bfseries id\_dsa og id\_dsa.pub}
\item Den offentlige del, filen id\_dsa.pub, kopieres til serveren
\item Der logges ind på serveren
\item Der udføres følgende kommandoer:
\end{list2}
\end{list1}
\begin{alltt}
$ cd  \emph{skift til dit hjemmekatalog}
$ mkdir .ssh  \emph{lav et katalog til ssh-nøgler}
$ cat id\_dsa.pub >> .ssh/authorized\_keys  \emph{kopierer nøglen}
$ chmod -R go-rwx .ssh  \emph{skift rettigheder på nøglen}
\end{alltt}

\slide{OpenSSH konfiguration}

\begin{list1}
\item Sådan anbefaler jeg at konfigurere OpenSSH SSHD
\item Det gøres i filen \verb+sshd_config+ typisk \verb+/etc/ssh/sshd_config+
\end{list1}

\begin{alltt}\small
Port 22780    // eller anden tilfældig port
Protocol 2

PermitRootLogin no
PubkeyAuthentication yes
# To disable tunneled clear text passwords, change to no here!
PasswordAuthentication no

UseDNS no
#X11Forwarding no
#X11DisplayOffset 10
#X11UseLocalhost yes
\end{alltt}

Det er en smagssag om man vil tillade \emph{X11 forwarding}

\slidenext

\end{document}


text:
<?php

namespace Google\AdsApi\Dfp\v201705;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class NativeStyleErrorReason
{
    const UNRECOGNIZED_PLACEHOLDER = 'UNRECOGNIZED_PLACEHOLDER';
    const NATIVE_CREATIVE_TEMPLATE_REQUIRED = 'NATIVE_CREATIVE_TEMPLATE_REQUIRED';
    const ACTIVE_CREATIVE_TEMPLATE_REQUIRED = 'ACTIVE_CREATIVE_TEMPLATE_REQUIRED';
    const UNIQUE_SNIPPET_REQUIRED = 'UNIQUE_SNIPPET_REQUIRED';
    const INVALID_CUSTOM_TARGETING_MATCH_TYPE = 'INVALID_CUSTOM_TARGETING_MATCH_TYPE';
    const INVALID_TARGETING_TYPE = 'INVALID_TARGETING_TYPE';
    const INVALID_INVENTORY_TARTGETING_TYPE = 'INVALID_INVENTORY_TARTGETING_TYPE';
    const UNRECOGNIZED_MACRO = 'UNRECOGNIZED_MACRO';
    const UNKNOWN = 'UNKNOWN';

}

redpajama_set_name: RedPajamaGithub


text:
author: generalchoa
comments: true
date: 2012-10-24 16:54:39+00:00
layout: post
slug: 10-days-rest-low-back-injury
title: 10 Days Rest - Low Back Injury
wordpress_id: 1088
categories:
- Miscellaneous
tags:
- injury
- rest week
---

Managed to induce my first ever exercise-related injury this past Monday.  I hadn't exercises consistently prior to that gym day.  Finding new gyms combined with road trips and visiting friends pushed me away from my regular routine.  Anyway, while doing box jumps, I managed to injure my lower back.  I can only describe the sensation as feeling like something getting dislodged in my lower back.  I immediately felt pressure in my low back and moving around and even just walking around would sometimes cause spasms.  I could barely bend over.  And the intermittent spasms would sometimes cause me to buckle and almost fall down.

Went to the doctor yesterday and initial diagnosis is indicating that there are no herniated conditions yet, so that was a relief.  Although, they still have to look at the X-rays that were taken to find out for sure.  I'm currently not allowed to do any running, heavy lifting or any impact related activities (jumping) for 10 days.  Two Alleves twice a day for the 10 days and I report again to see if the problem is still persisting.

I'll have to say that I my low back does feel slightly better compared to yesterday.  I have a bit more mobility and getting up out of a seated position is much easier than yesterday.  Yesterday, I literally had to push my upper body up because my low back just would not stay tight and get my body upright.

With regards to exercise, I think I'm going to dial back my lifts in anticipation of recovering from this injury.  I will also be making sure I spend at least 10-20 minutes solely for warming up.  I think I could have avoided this injury had I sufficiently warmed myself up.  Jumping right into plyometrics without any stretching of the low back is just a bad idea.


text:
class BaseError(Exception):
    """SmartFile Auth base Exception. """
    pass

class AuthError(BaseError):
    """ Exception for authentication errors. """
    def __init__(self, exc, *args, **kwargs):
        self.exc = exc
        self.detail = str(exc)
        super(AuthError, self).__init__(*args, **kwargs)

        def __str__(self):
            return self.detail

class NoAuthError(BaseError):
    """ Exception for network connection errors. """
    def __init__(self, exc, *args, **kwargs):
        self.exc = exc
        self.detail = str(exc)
        super(NoAuthError, self).__init__(*args, **kwargs)

        def __str__(self):
            return self.detail

class NetConnectionError(BaseError):
    """ Exception for network connection errors. """
    def __init__(self, exc, *args, **kwargs):
        self.exc = exc
        self.detail = str(exc)
        super(NetConnectionError, self).__init__(*args, **kwargs)

        def __str__(self):
            return self.detail


text:
#Requires -Version 3.0
function Get-MrLeapYear2 {

<#
.SYNOPSIS
   Get-MrLeapYear is used to determine whether or not a specific year is a leap year.
.DESCRIPTION
   Get-MrLeapYear is a function that is used to determine whether or not the specified
   year(s) are leap years. Contrary to popular belief, leap year does not occur every
   four years: http://en.wikipedia.org/wiki/Leap_year
.PARAMETER Year
   The year(s) specified in integer form that you would like to determine whether or
   not they are a leap year.
.EXAMPLE
   Get-MrLeapYear
.EXAMPLE
   Get-MrLeapYear -Year 2010, 2011, 2012, 2013, 2014, 2015
.EXAMPLE
   1890..1910 | Get-MrLeapYear
.INPUTS
   Integer
.OUTPUTS
   String
.NOTES
   Author:  Mike F Robbins
   Website: http://mikefrobbins.com
   Twitter: @mikefrobbins
#>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [ValidateRange(1582,9999)]
        [int[]]$Year = (Get-Date).Year
    )

    PROCESS {
        foreach ($y in $Year) {
            try {
                if (Get-Date -Date 2/29/$y) {
                    Write-Output "$y is a leap year"
                }
            }
            catch {
                Write-Output "$y is not a leap year"
            }
        }
    }
}


text:
@implementation RGWindow

- (void)close
{
	[self makeFirstResponder:nil];
	[super close];
}

@end


text:
Paris is now considered to be feature complete as of version 1.5.0. Whilst it will continue to be maintained with bug fixes there will be no further new features added.

**Please do not submit feature requests or pull requests adding new features as they will be closed without ceremony.**

---

When making a pull request please include the following aspects:

- Update the changelog in the README.markdown file to include details of the pull request
- If the documentation in the README or Sphinx docs needs to be amended please do so in the pull request
- Include unit tests for any changes - if it is a bug include at least one regression test


text:
"use strict"

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const path = require("path")
const globParent = require("glob-parent")
const assert = require("./assert")

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

const BACK_SLASH = /\\/g
const DRIVE_LETER_ONLY = /^[a-zA-Z]+:$/
const DRIVE_LETER = /^[a-zA-Z]+:/

/**
 * Get the parent path of the given glob as an array of path elements.
 *
 * @param {string} glob - The glob to get.
 * @returns {string[]} The path elements.
 * @private
 */
function globParentToArray(glob) {
    return path.resolve(globParent(glob))
        .replace(BACK_SLASH, "/")
        .split("/")
        .filter(Boolean)
}

/**
 * Get the index of the last element which is same between the given 2 elements.
 *
 * @param {string[]} xs - An array to compare.
 * @param {string[]} ys - Another array to compare.
 * @returns {number} The index of the last element is same.
 * @private
 */
function findLastCommonIndex(xs, ys) {
    for (let i = Math.min(xs.length, ys.length) - 1; i >= 0; --i) {
        if (xs[i] === ys[i]) {
            return i
        }
    }
    return -1
}

/**
 * Check whether the given path is an drive letter.
 *
 * @param {string} targetPath - The path to be checked.
 * @returns {boolean} `true` if the path is an drive letter.
 * @private
 */
function isDriveLeterOnly(targetPath) {
    return DRIVE_LETER_ONLY.test(targetPath)
}

/**
 * Check whether the given path starts with an drive letter.
 *
 * @param {string} targetPath - The path to be checked.
 * @returns {boolean} `true` if the path starts with an drive letter.
 * @private
 */
function hasDriveLeter(targetPath) {
    return DRIVE_LETER.test(targetPath)
}

//------------------------------------------------------------------------------
// Exports
//------------------------------------------------------------------------------

/**
 * Calculates the common ancestor's path of given globs.
 *
 * @param {string[]} globs - A list of globs to calculate.
 * @returns {string|null} the common ancestor's path.
 * @private
 */
module.exports = function commonPart(globs) {
    assert(globs.length > 0)
    assert.string(globs[0], "globs[0]")

    const commonParts = globParentToArray(globs[0])
    for (let i = 1, end = globs.length; i < end; ++i) {
        assert.string(globs[i], `globs[${i}]`)

        const parts = globParentToArray(globs[i])
        const index = findLastCommonIndex(commonParts, parts)
        if (index === -1) {
            return null
        }

        // remove all after the index.
        commonParts.splice(1 + index)
    }

    const common = commonParts.join("/")
    if (isDriveLeterOnly(common)) {
        return null
    }
    if (hasDriveLeter(common)) {
        return `${common}/`
    }
    return `/${common}/`
}


text:
// Package reconciler implements interfaces that attempt to reconcile the
// desired state of the with the actual state of the world by triggering
// actions.
package reconciler

import (
	"fmt"
	"strings"
	"time"

	"github.com/golang/glog"
	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/client-go/tools/record"
	"k8s.io/kubernetes/pkg/controller/volume/attachdetach/cache"
	"k8s.io/kubernetes/pkg/controller/volume/attachdetach/statusupdater"
	kevents "k8s.io/kubernetes/pkg/kubelet/events"
	"k8s.io/kubernetes/pkg/util/goroutinemap/exponentialbackoff"
	"k8s.io/kubernetes/pkg/volume"
	"k8s.io/kubernetes/pkg/volume/util/operationexecutor"
)

// Reconciler runs a periodic loop to reconcile the desired state of the world with
// the actual state of the world by triggering attach detach operations.
// Note: This is distinct from the Reconciler implemented by the kubelet volume
// manager. This reconciles state for the attach/detach controller. That
// reconciles state for the kubelet volume manager.
type Reconciler interface {
	// Starts running the reconciliation loop which executes periodically, checks
	// if volumes that should be attached are attached and volumes that should
	// be detached are detached. If not, it will trigger attach/detach
	// operations to rectify.
	Run(stopCh <-chan struct{})
}

// NewReconciler returns a new instance of Reconciler that waits loopPeriod
// between successive executions.
// loopPeriod is the amount of time the reconciler loop waits between
// successive executions.
// maxWaitForUnmountDuration is the max amount of time the reconciler will wait
// for the volume to be safely unmounted, after this it will detach the volume
// anyway (to handle crashed/unavailable nodes). If during this time the volume
// becomes used by a new pod, the detach request will be aborted and the timer
// cleared.
func NewReconciler(
	loopPeriod time.Duration,
	maxWaitForUnmountDuration time.Duration,
	syncDuration time.Duration,
	disableReconciliationSync bool,
	desiredStateOfWorld cache.DesiredStateOfWorld,
	actualStateOfWorld cache.ActualStateOfWorld,
	attacherDetacher operationexecutor.OperationExecutor,
	nodeStatusUpdater statusupdater.NodeStatusUpdater,
	recorder record.EventRecorder) Reconciler {
	return &reconciler{
		loopPeriod:                loopPeriod,
		maxWaitForUnmountDuration: maxWaitForUnmountDuration,
		syncDuration:              syncDuration,
		disableReconciliationSync: disableReconciliationSync,
		desiredStateOfWorld:       desiredStateOfWorld,
		actualStateOfWorld:        actualStateOfWorld,
		attacherDetacher:          attacherDetacher,
		nodeStatusUpdater:         nodeStatusUpdater,
		timeOfLastSync:            time.Now(),
		recorder:                  recorder,
	}
}

type reconciler struct {
	loopPeriod                time.Duration
	maxWaitForUnmountDuration time.Duration
	syncDuration              time.Duration
	desiredStateOfWorld       cache.DesiredStateOfWorld
	actualStateOfWorld        cache.ActualStateOfWorld
	attacherDetacher          operationexecutor.OperationExecutor
	nodeStatusUpdater         statusupdater.NodeStatusUpdater
	timeOfLastSync            time.Time
	disableReconciliationSync bool
	recorder                  record.EventRecorder
}

func (rc *reconciler) Run(stopCh <-chan struct{}) {
	wait.Until(rc.reconciliationLoopFunc(), rc.loopPeriod, stopCh)
}

// reconciliationLoopFunc this can be disabled via cli option disableReconciliation.
// It periodically checks whether the attached volumes from actual state
// are still attached to the node and update the status if they are not.
func (rc *reconciler) reconciliationLoopFunc() func() {
	return func() {

		rc.reconcile()

		if rc.disableReconciliationSync {
			glog.V(5).Info("Skipping reconciling attached volumes still attached since it is disabled via the command line.")
		} else if rc.syncDuration < time.Second {
			glog.V(5).Info("Skipping reconciling attached volumes still attached since it is set to less than one second via the command line.")
		} else if time.Since(rc.timeOfLastSync) > rc.syncDuration {
			glog.V(5).Info("Starting reconciling attached volumes still attached")
			rc.sync()
		}
	}
}

func (rc *reconciler) sync() {
	defer rc.updateSyncTime()
	rc.syncStates()
}

func (rc *reconciler) updateSyncTime() {
	rc.timeOfLastSync = time.Now()
}

func (rc *reconciler) syncStates() {
	volumesPerNode := rc.actualStateOfWorld.GetAttachedVolumesPerNode()
	rc.attacherDetacher.VerifyVolumesAreAttached(volumesPerNode, rc.actualStateOfWorld)
}

// isMultiAttachForbidden checks if attaching this volume to multiple nodes is definitely not allowed/possible.
// In its current form, this function can only reliably say for which volumes it's definitely forbidden. If it returns
// false, it is not guaranteed that multi-attach is actually supported by the volume type and we must rely on the
// attacher to fail fast in such cases.
// Please see https://github.com/kubernetes/kubernetes/issues/40669 and https://github.com/kubernetes/kubernetes/pull/40148#discussion_r98055047
func (rc *reconciler) isMultiAttachForbidden(volumeSpec *volume.Spec) bool {
	if volumeSpec.Volume != nil {
		// Check for volume types which are known to fail slow or cause trouble when trying to multi-attach
		if volumeSpec.Volume.AzureDisk != nil ||
			volumeSpec.Volume.Cinder != nil {
			return true
		}
	}

	// Only if this volume is a persistent volume, we have reliable information on whether it's allowed or not to
	// multi-attach. We trust in the individual volume implementations to not allow unsupported access modes
	if volumeSpec.PersistentVolume != nil {
		// Check for persistent volume types which do not fail when trying to multi-attach
		if len(volumeSpec.PersistentVolume.Spec.AccessModes) == 0 {
			// No access mode specified so we don't know for sure. Let the attacher fail if needed
			return false
		}

		// check if this volume is allowed to be attached to multiple PODs/nodes, if yes, return false
		for _, accessMode := range volumeSpec.PersistentVolume.Spec.AccessModes {
			if accessMode == v1.ReadWriteMany || accessMode == v1.ReadOnlyMany {
				return false
			}
		}
		return true
	}

	// we don't know if it's supported or not and let the attacher fail later in cases it's not supported
	return false
}

func (rc *reconciler) reconcile() {
	// Detaches are triggered before attaches so that volumes referenced by
	// pods that are rescheduled to a different node are detached first.

	// Ensure volumes that should be detached are detached.
	for _, attachedVolume := range rc.actualStateOfWorld.GetAttachedVolumes() {
		if !rc.desiredStateOfWorld.VolumeExists(
			attachedVolume.VolumeName, attachedVolume.NodeName) {

			// Don't even try to start an operation if there is already one running
			// This check must be done before we do any other checks, as otherwise the other checks
			// may pass while at the same time the volume leaves the pending state, resulting in
			// double detach attempts
			if rc.attacherDetacher.IsOperationPending(attachedVolume.VolumeName, "") {
				glog.V(10).Infof("Operation for volume %q is already running. Can't start detach for %q", attachedVolume.VolumeName, attachedVolume.NodeName)
				continue
			}

			// Set the detach request time
			elapsedTime, err := rc.actualStateOfWorld.SetDetachRequestTime(attachedVolume.VolumeName, attachedVolume.NodeName)
			if err != nil {
				glog.Errorf("Cannot trigger detach because it fails to set detach request time with error %v", err)
				continue
			}
			// Check whether timeout has reached the maximum waiting time
			timeout := elapsedTime > rc.maxWaitForUnmountDuration
			// Check whether volume is still mounted. Skip detach if it is still mounted unless timeout
			if attachedVolume.MountedByNode && !timeout {
				glog.V(12).Infof(attachedVolume.GenerateMsgDetailed("Cannot detach volume because it is still mounted", ""))
				continue
			}

			// Before triggering volume detach, mark volume as detached and update the node status
			// If it fails to update node status, skip detach volume
			err = rc.actualStateOfWorld.RemoveVolumeFromReportAsAttached(attachedVolume.VolumeName, attachedVolume.NodeName)
			if err != nil {
				glog.V(5).Infof("RemoveVolumeFromReportAsAttached failed while removing volume %q from node %q with: %v",
					attachedVolume.VolumeName,
					attachedVolume.NodeName,
					err)
			}

			// Update Node Status to indicate volume is no longer safe to mount.
			err = rc.nodeStatusUpdater.UpdateNodeStatuses()
			if err != nil {
				// Skip detaching this volume if unable to update node status
				glog.Errorf(attachedVolume.GenerateErrorDetailed("UpdateNodeStatuses failed while attempting to report volume as attached", err).Error())
				continue
			}

			// Trigger detach volume which requires verifing safe to detach step
			// If timeout is true, skip verifySafeToDetach check
			glog.V(5).Infof(attachedVolume.GenerateMsgDetailed("Starting attacherDetacher.DetachVolume", ""))
			verifySafeToDetach := !timeout
			err = rc.attacherDetacher.DetachVolume(attachedVolume.AttachedVolume, verifySafeToDetach, rc.actualStateOfWorld)
			if err == nil {
				if !timeout {
					glog.Infof(attachedVolume.GenerateMsgDetailed("attacherDetacher.DetachVolume started", ""))
				} else {
					glog.Warningf(attachedVolume.GenerateMsgDetailed("attacherDetacher.DetachVolume started", fmt.Sprintf("This volume is not safe to detach, but maxWaitForUnmountDuration %v expired, force detaching", rc.maxWaitForUnmountDuration)))
				}
			}
			if err != nil && !exponentialbackoff.IsExponentialBackoff(err) {
				// Ignore exponentialbackoff.IsExponentialBackoff errors, they are expected.
				// Log all other errors.
				glog.Errorf(attachedVolume.GenerateErrorDetailed("attacherDetacher.DetachVolume failed to start", err).Error())
			}
		}
	}

	rc.attachDesiredVolumes()

	// Update Node Status
	err := rc.nodeStatusUpdater.UpdateNodeStatuses()
	if err != nil {
		glog.Warningf("UpdateNodeStatuses failed with: %v", err)
	}
}

func (rc *reconciler) attachDesiredVolumes() {
	// Ensure volumes that should be attached are attached.
	for _, volumeToAttach := range rc.desiredStateOfWorld.GetVolumesToAttach() {
		if rc.actualStateOfWorld.VolumeNodeExists(volumeToAttach.VolumeName, volumeToAttach.NodeName) {
			// Volume/Node exists, touch it to reset detachRequestedTime
			glog.V(5).Infof(volumeToAttach.GenerateMsgDetailed("Volume attached--touching", ""))
			rc.actualStateOfWorld.ResetDetachRequestTime(volumeToAttach.VolumeName, volumeToAttach.NodeName)
			continue
		}
		// Don't even try to start an operation if there is already one running
		if rc.attacherDetacher.IsOperationPending(volumeToAttach.VolumeName, "") {
			glog.V(10).Infof("Operation for volume %q is already running. Can't start attach for %q", volumeToAttach.VolumeName, volumeToAttach.NodeName)
			continue
		}

		if rc.isMultiAttachForbidden(volumeToAttach.VolumeSpec) {
			nodes := rc.actualStateOfWorld.GetNodesForVolume(volumeToAttach.VolumeName)
			if len(nodes) > 0 {
				if !volumeToAttach.MultiAttachErrorReported {
					rc.reportMultiAttachError(volumeToAttach, nodes)
					rc.desiredStateOfWorld.SetMultiAttachError(volumeToAttach.VolumeName, volumeToAttach.NodeName)
				}
				continue
			}
		}

		// Volume/Node doesn't exist, spawn a goroutine to attach it
		glog.V(5).Infof(volumeToAttach.GenerateMsgDetailed("Starting attacherDetacher.AttachVolume", ""))
		err := rc.attacherDetacher.AttachVolume(volumeToAttach.VolumeToAttach, rc.actualStateOfWorld)
		if err == nil {
			glog.Infof(volumeToAttach.GenerateMsgDetailed("attacherDetacher.AttachVolume started", ""))
		}
		if err != nil && !exponentialbackoff.IsExponentialBackoff(err) {
			// Ignore exponentialbackoff.IsExponentialBackoff errors, they are expected.
			// Log all other errors.
			glog.Errorf(volumeToAttach.GenerateErrorDetailed("attacherDetacher.AttachVolume failed to start", err).Error())
		}
	}
}

// reportMultiAttachError sends events and logs situation that a volume that
// should be attached to a node is already attached to different node(s).
func (rc *reconciler) reportMultiAttachError(volumeToAttach cache.VolumeToAttach, nodes []types.NodeName) {
	// Filter out the current node from list of nodes where the volume is
	// attached.
	// Some methods need []string, some other needs []NodeName, collect both.
	// In theory, these arrays should have always only one element - the
	// controller does not allow more than one attachment. But use array just
	// in case...
	otherNodes := []types.NodeName{}
	otherNodesStr := []string{}
	for _, node := range nodes {
		if node != volumeToAttach.NodeName {
			otherNodes = append(otherNodes, node)
			otherNodesStr = append(otherNodesStr, string(node))
		}
	}

	// Get list of pods that use the volume on the other nodes.
	pods := rc.desiredStateOfWorld.GetVolumePodsOnNodes(otherNodes, volumeToAttach.VolumeName)

	if len(pods) == 0 {
		// We did not find any pods that requests the volume. The pod must have been deleted already.
		simpleMsg, _ := volumeToAttach.GenerateMsg("Multi-Attach error", "Volume is already exclusively attached to one node and can't be attached to another")
		for _, pod := range volumeToAttach.ScheduledPods {
			rc.recorder.Eventf(pod, v1.EventTypeWarning, kevents.FailedAttachVolume, simpleMsg)
		}
		// Log detailed message to system admin
		nodeList := strings.Join(otherNodesStr, ", ")
		detailedMsg := volumeToAttach.GenerateMsgDetailed("Multi-Attach error", fmt.Sprintf("Volume is already exclusively attached to node %s and can't be attached to another", nodeList))
		glog.Warningf(detailedMsg)
		return
	}

	// There are pods that require the volume and run on another node. Typically
	// it's user error, e.g. a ReplicaSet uses a PVC and has >1 replicas. Let
	// the user know what pods are blocking the volume.
	for _, scheduledPod := range volumeToAttach.ScheduledPods {
		// Each scheduledPod must get a custom message. They can run in
		// different namespaces and user of a namespace should not see names of
		// pods in other namespaces.
		localPodNames := []string{} // Names of pods in scheduledPods's namespace
		otherPods := 0              // Count of pods in other namespaces
		for _, pod := range pods {
			if pod.Namespace == scheduledPod.Namespace {
				localPodNames = append(localPodNames, pod.Name)
			} else {
				otherPods++
			}
		}

		var msg string
		if len(localPodNames) > 0 {
			msg = fmt.Sprintf("Volume is already used by pod(s) %s", strings.Join(localPodNames, ", "))
			if otherPods > 0 {
				msg = fmt.Sprintf("%s and %d pod(s) in different namespaces", msg, otherPods)
			}
		} else {
			// No local pods, there are pods only in different namespaces.
			msg = fmt.Sprintf("Volume is already used by %d pod(s) in different namespaces", otherPods)
		}
		simpleMsg, _ := volumeToAttach.GenerateMsg("Multi-Attach error", msg)
		rc.recorder.Eventf(scheduledPod, v1.EventTypeWarning, kevents.FailedAttachVolume, simpleMsg)
	}

	// Log all pods for system admin
	podNames := []string{}
	for _, pod := range pods {
		podNames = append(podNames, pod.Namespace+"/"+pod.Name)
	}
	detailedMsg := volumeToAttach.GenerateMsgDetailed("Multi-Attach error", fmt.Sprintf("Volume is already used by pods %s on node %s", strings.Join(podNames, ", "), strings.Join(otherNodesStr, ", ")))
	glog.Warningf(detailedMsg)
}


text:
<?php

namespace backend\models;

use Yii;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "town".
 *
 * @property integer $id
 * @property integer $province_id
 * @property integer $city_id
 * @property string $name
 * @property integer $status
 * @property string $seo_title
 * @property string $seo_keyword
 * @property string $seo_desc
 * @property string $created_at
 * @property string $updated_at
 */
class Town extends ActiveRecord
{
    const STATUS_ENABLE      = 1;
    const STATUS_DISABLE     = 2;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'town';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['province_id', 'city_id', 'status', 'created_at', 'updated_at'], 'integer'],
            [['name', 'province_id', 'city_id', 'seo_title', 'seo_keyword', 'seo_desc'], 'required'],
            [['seo_desc'], 'string'],
            [['name', 'seo_title', 'seo_keyword'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'province_id' => 'Province',
            'city_id' => 'City',
            'name' => 'Name',
            'status' => 'Status',
            'seo_title' => 'Seo Title',
            'seo_keyword' => 'Seo Keyword',
            'seo_desc' => 'Seo Desc',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    // status array
    public static function getStatusArray(){
        return [
            self::STATUS_ENABLE    => 'Enable',
            self::STATUS_DISABLE   => 'Disable'
        ];
    }

    // get town list by city id
    public static function getTownList($cityId)
    {
        $data =  self::find()->select(['id', 'name'])
                        ->where(['status' => 1, 'city_id' => $cityId])
                        ->orderBy(['name' => 'DESC'])
                        ->asArray()
                        ->all();
        $array[0] = 'Please Select the Town';
        foreach($data as $val){
            $array[$val['id']] = $val['name'];
        }

        return $array;
    }
}


text:
var phonegap = require('../lib'),
    path = require('path');

phonegap.create({
    path: path.join(__dirname, 'basic-app'),
    version: '3.3.0'
})
.on('progress', function(state) {
    console.log('progress:', state);
})
.on('error', function(e) {
    console.error('error:', e);
})
.on('complete', function(data) {
    console.log('complete:', data);
});


text:
require 'spec_helper'

describe Pond, "configuration" do
  it "should eagerly instantiate objects if the option is given" do
    int = 0
    pond = Pond.new(:eager => true){int += 1}
    pond.available.should == (1..10).to_a
  end

  it "should have its collection type gettable and settable" do
    pond = Pond.new { Object.new }
    pond.collection.should == :queue
    pond.collection = :stack
    pond.collection.should == :stack

    pond = Pond.new(:collection => :stack) { Object.new }
    pond.collection.should == :stack
    pond.collection = :queue
    pond.collection.should == :queue

    procs = [
      proc{pond.collection = nil},
      proc{Pond.new(:collection => nil) { Object.new }},
      proc{pond.collection = :blah},
      proc{Pond.new(:collection => :blah) { Object.new }}
    ]

    procs.each { |p| p.should raise_error RuntimeError, /Bad value for Pond collection:/ }
  end

  it "should have its timeout gettable and settable" do
    pond = Pond.new { Object.new }
    pond.timeout.should == 1
    pond.timeout = 4
    pond.timeout.should == 4

    pond = Pond.new(:timeout => 3.7) { Object.new }
    pond.timeout.should == 3.7
    pond.timeout = 1.9
    pond.timeout.should == 1.9

    procs = [
      proc{pond.timeout = nil},
      proc{Pond.new(:timeout => nil) { Object.new }},
      proc{pond.timeout = :blah},
      proc{Pond.new(:timeout => :blah) { Object.new }}
    ]

    procs.each { |p| p.should raise_error RuntimeError, /Bad value for Pond timeout:/ }
  end

  it "should have its maximum_size gettable and settable" do
    pond = Pond.new { Object.new }
    pond.maximum_size.should == 10
    pond.maximum_size = 7
    pond.maximum_size.should == 7
    pond.maximum_size = 0
    pond.maximum_size.should == 0
    pond.maximum_size = 2
    pond.maximum_size.should == 2

    procs = [
      proc{pond.maximum_size = nil},
      proc{Pond.new(:maximum_size => nil) { Object.new }},
      proc{pond.maximum_size = :blah},
      proc{Pond.new(:maximum_size => :blah) { Object.new }},
      proc{pond.maximum_size = 4.0},
      proc{Pond.new(:maximum_size => 4.0) { Object.new }},
    ]

    procs.each { |p| p.should raise_error RuntimeError, /Bad value for Pond maximum_size:/ }
  end

  it "when the maximum_size is decreased should free available objects" do
    int  = 0
    pond = Pond.new(:eager => true) { int += 1 }

    pond.available.should == (1..10).to_a
    pond.maximum_size = 8
    pond.available.should == (3..10).to_a
    pond.maximum_size = 10
    pond.available.should == (3..10).to_a
    pond.maximum_size = 9
    pond.available.should == (3..10).to_a
  end

  it "when the maximum_size is decreased should free available objects and checked-out objects upon return" do
    int = 0
    pond = Pond.new(:eager => true, :maximum_size => 2) { int += 1 }
    pond.available.should == [1, 2]

    q1, q2 = Queue.new, Queue.new
    t = Thread.new do
      pond.checkout do |i|
        i.should == 1
        q1.push nil
        q2.pop
      end
    end

    q1.pop

    pond.maximum_size = 0
    pond.maximum_size.should == 0

    pond.size.should == 1
    pond.available.should == []
    pond.allocated.should == {nil => {t => 1}}

    q2.push nil
    t.join

    pond.size.should == 0
    pond.available.should == []
    pond.allocated.should == {nil => {}}
  end
end


text:
package lxc

import (
	"fmt"
	"github.com/awkisopen/docker/engine"
	"github.com/awkisopen/docker/networkdriver"
	"github.com/awkisopen/docker/networkdriver/ipallocator"
	"github.com/awkisopen/docker/networkdriver/portallocator"
	"github.com/awkisopen/docker/networkdriver/portmapper"
	"github.com/awkisopen/docker/pkg/iptables"
	"github.com/awkisopen/docker/pkg/netlink"
	"github.com/awkisopen/docker/utils"
	"io/ioutil"
	"log"
	"net"
	"strings"
	"syscall"
	"unsafe"
)

const (
	DefaultNetworkBridge = "docker0"
	siocBRADDBR          = 0x89a0
)

// Network interface represents the networking stack of a container
type networkInterface struct {
	IP           net.IP
	PortMappings []net.Addr // there are mappings to the host interfaces
}

var (
	addrs = []string{
		// Here we don't follow the convention of using the 1st IP of the range for the gateway.
		// This is to use the same gateway IPs as the /24 ranges, which predate the /16 ranges.
		// In theory this shouldn't matter - in practice there's bound to be a few scripts relying
		// on the internal addressing or other stupid things like that.
		// The shouldn't, but hey, let's not break them unless we really have to.
		"172.17.42.1/16", // Don't use 172.16.0.0/16, it conflicts with EC2 DNS 172.16.0.23
		"10.0.42.1/16",   // Don't even try using the entire /8, that's too intrusive
		"10.1.42.1/16",
		"10.42.42.1/16",
		"172.16.42.1/24",
		"172.16.43.1/24",
		"172.16.44.1/24",
		"10.0.42.1/24",
		"10.0.43.1/24",
		"192.168.42.1/24",
		"192.168.43.1/24",
		"192.168.44.1/24",
	}

	bridgeIface   string
	bridgeNetwork *net.IPNet

	defaultBindingIP  = net.ParseIP("0.0.0.0")
	currentInterfaces = make(map[string]*networkInterface)
)

func init() {
	if err := engine.Register("init_networkdriver", InitDriver); err != nil {
		panic(err)
	}
}

func InitDriver(job *engine.Job) engine.Status {
	var (
		network        *net.IPNet
		enableIPTables = job.GetenvBool("EnableIptables")
		icc            = job.GetenvBool("InterContainerCommunication")
		ipForward      = job.GetenvBool("EnableIpForward")
		bridgeIP       = job.Getenv("BridgeIP")
	)

	if defaultIP := job.Getenv("DefaultBindingIP"); defaultIP != "" {
		defaultBindingIP = net.ParseIP(defaultIP)
	}

	bridgeIface = job.Getenv("BridgeIface")
	if bridgeIface == "" {
		bridgeIface = DefaultNetworkBridge
	}

	addr, err := networkdriver.GetIfaceAddr(bridgeIface)
	if err != nil {
		// If the iface is not found, try to create it
		job.Logf("creating new bridge for %s", bridgeIface)
		if err := createBridge(bridgeIP); err != nil {
			job.Error(err)
			return engine.StatusErr
		}

		job.Logf("getting iface addr")
		addr, err = networkdriver.GetIfaceAddr(bridgeIface)
		if err != nil {
			job.Error(err)
			return engine.StatusErr
		}
		network = addr.(*net.IPNet)
	} else {
		network = addr.(*net.IPNet)
	}

	// Configure iptables for link support
	if enableIPTables {
		if err := setupIPTables(addr, icc); err != nil {
			job.Error(err)
			return engine.StatusErr
		}
	}

	if ipForward {
		// Enable IPv4 forwarding
		if err := ioutil.WriteFile("/proc/sys/net/ipv4/ip_forward", []byte{'1', '\n'}, 0644); err != nil {
			job.Logf("WARNING: unable to enable IPv4 forwarding: %s\n", err)
		}
	}

	// We can always try removing the iptables
	if err := iptables.RemoveExistingChain("DOCKER"); err != nil {
		job.Error(err)
		return engine.StatusErr
	}

	if enableIPTables {
		chain, err := iptables.NewChain("DOCKER", bridgeIface)
		if err != nil {
			job.Error(err)
			return engine.StatusErr
		}
		portmapper.SetIptablesChain(chain)
	}

	bridgeNetwork = network

	// https://github.com/awkisopen/docker/issues/2768
	job.Eng.Hack_SetGlobalVar("httpapi.bridgeIP", bridgeNetwork.IP)

	for name, f := range map[string]engine.Handler{
		"allocate_interface": Allocate,
		"release_interface":  Release,
		"allocate_port":      AllocatePort,
		"link":               LinkContainers,
	} {
		if err := job.Eng.Register(name, f); err != nil {
			job.Error(err)
			return engine.StatusErr
		}
	}
	return engine.StatusOK
}

func setupIPTables(addr net.Addr, icc bool) error {
	// Enable NAT
	natArgs := []string{"POSTROUTING", "-t", "nat", "-s", addr.String(), "!", "-d", addr.String(), "-j", "MASQUERADE"}

	if !iptables.Exists(natArgs...) {
		if output, err := iptables.Raw(append([]string{"-I"}, natArgs...)...); err != nil {
			return fmt.Errorf("Unable to enable network bridge NAT: %s", err)
		} else if len(output) != 0 {
			return fmt.Errorf("Error iptables postrouting: %s", output)
		}
	}

	var (
		args       = []string{"FORWARD", "-i", bridgeIface, "-o", bridgeIface, "-j"}
		acceptArgs = append(args, "ACCEPT")
		dropArgs   = append(args, "DROP")
	)

	if !icc {
		iptables.Raw(append([]string{"-D"}, acceptArgs...)...)

		if !iptables.Exists(dropArgs...) {
			utils.Debugf("Disable inter-container communication")
			if output, err := iptables.Raw(append([]string{"-I"}, dropArgs...)...); err != nil {
				return fmt.Errorf("Unable to prevent intercontainer communication: %s", err)
			} else if len(output) != 0 {
				return fmt.Errorf("Error disabling intercontainer communication: %s", output)
			}
		}
	} else {
		iptables.Raw(append([]string{"-D"}, dropArgs...)...)

		if !iptables.Exists(acceptArgs...) {
			utils.Debugf("Enable inter-container communication")
			if output, err := iptables.Raw(append([]string{"-I"}, acceptArgs...)...); err != nil {
				return fmt.Errorf("Unable to allow intercontainer communication: %s", err)
			} else if len(output) != 0 {
				return fmt.Errorf("Error enabling intercontainer communication: %s", output)
			}
		}
	}

	// Accept all non-intercontainer outgoing packets
	outgoingArgs := []string{"FORWARD", "-i", bridgeIface, "!", "-o", bridgeIface, "-j", "ACCEPT"}
	if !iptables.Exists(outgoingArgs...) {
		if output, err := iptables.Raw(append([]string{"-I"}, outgoingArgs...)...); err != nil {
			return fmt.Errorf("Unable to allow outgoing packets: %s", err)
		} else if len(output) != 0 {
			return fmt.Errorf("Error iptables allow outgoing: %s", output)
		}
	}

	// Accept incoming packets for existing connections
	existingArgs := []string{"FORWARD", "-o", bridgeIface, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"}

	if !iptables.Exists(existingArgs...) {
		if output, err := iptables.Raw(append([]string{"-I"}, existingArgs...)...); err != nil {
			return fmt.Errorf("Unable to allow incoming packets: %s", err)
		} else if len(output) != 0 {
			return fmt.Errorf("Error iptables allow incoming: %s", output)
		}
	}
	return nil
}

// CreateBridgeIface creates a network bridge interface on the host system with the name `ifaceName`,
// and attempts to configure it with an address which doesn't conflict with any other interface on the host.
// If it can't find an address which doesn't conflict, it will return an error.
func createBridge(bridgeIP string) error {
	nameservers := []string{}
	resolvConf, _ := utils.GetResolvConf()
	// we don't check for an error here, because we don't really care
	// if we can't read /etc/resolv.conf. So instead we skip the append
	// if resolvConf is nil. It either doesn't exist, or we can't read it
	// for some reason.
	if resolvConf != nil {
		nameservers = append(nameservers, utils.GetNameserversAsCIDR(resolvConf)...)
	}

	var ifaceAddr string
	if len(bridgeIP) != 0 {
		_, _, err := net.ParseCIDR(bridgeIP)
		if err != nil {
			return err
		}
		ifaceAddr = bridgeIP
	} else {
		for _, addr := range addrs {
			_, dockerNetwork, err := net.ParseCIDR(addr)
			if err != nil {
				return err
			}
			if err := networkdriver.CheckNameserverOverlaps(nameservers, dockerNetwork); err == nil {
				if err := networkdriver.CheckRouteOverlaps(dockerNetwork); err == nil {
					ifaceAddr = addr
					break
				} else {
					utils.Debugf("%s %s", addr, err)
				}
			}
		}
	}

	if ifaceAddr == "" {
		return fmt.Errorf("Could not find a free IP address range for interface '%s'. Please configure its address manually and run 'docker -b %s'", bridgeIface, bridgeIface)
	}
	utils.Debugf("Creating bridge %s with network %s", bridgeIface, ifaceAddr)

	if err := createBridgeIface(bridgeIface); err != nil {
		return err
	}

	iface, err := net.InterfaceByName(bridgeIface)
	if err != nil {
		return err
	}

	ipAddr, ipNet, err := net.ParseCIDR(ifaceAddr)
	if err != nil {
		return err
	}

	if netlink.NetworkLinkAddIp(iface, ipAddr, ipNet); err != nil {
		return fmt.Errorf("Unable to add private network: %s", err)
	}
	if err := netlink.NetworkLinkUp(iface); err != nil {
		return fmt.Errorf("Unable to start network bridge: %s", err)
	}
	return nil
}

// Create the actual bridge device.  This is more backward-compatible than
// netlink.NetworkLinkAdd and works on RHEL 6.
func createBridgeIface(name string) error {
	s, err := syscall.Socket(syscall.AF_INET6, syscall.SOCK_STREAM, syscall.IPPROTO_IP)
	if err != nil {
		utils.Debugf("Bridge socket creation failed IPv6 probably not enabled: %v", err)
		s, err = syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_IP)
		if err != nil {
			return fmt.Errorf("Error creating bridge creation socket: %s", err)
		}
	}
	defer syscall.Close(s)

	nameBytePtr, err := syscall.BytePtrFromString(name)
	if err != nil {
		return fmt.Errorf("Error converting bridge name %s to byte array: %s", name, err)
	}

	if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(s), siocBRADDBR, uintptr(unsafe.Pointer(nameBytePtr))); err != 0 {
		return fmt.Errorf("Error creating bridge: %s", err)
	}
	return nil
}

// Allocate a network interface
func Allocate(job *engine.Job) engine.Status {
	var (
		ip          *net.IP
		err         error
		id          = job.Args[0]
		requestedIP = net.ParseIP(job.Getenv("RequestedIP"))
	)

	if requestedIP != nil {
		ip, err = ipallocator.RequestIP(bridgeNetwork, &requestedIP)
	} else {
		ip, err = ipallocator.RequestIP(bridgeNetwork, nil)
	}
	if err != nil {
		job.Error(err)
		return engine.StatusErr
	}

	out := engine.Env{}
	out.Set("IP", ip.String())
	out.Set("Mask", bridgeNetwork.Mask.String())
	out.Set("Gateway", bridgeNetwork.IP.String())
	out.Set("Bridge", bridgeIface)

	size, _ := bridgeNetwork.Mask.Size()
	out.SetInt("IPPrefixLen", size)

	currentInterfaces[id] = &networkInterface{
		IP: *ip,
	}

	out.WriteTo(job.Stdout)

	return engine.StatusOK
}

// release an interface for a select ip
func Release(job *engine.Job) engine.Status {
	var (
		id                 = job.Args[0]
		containerInterface = currentInterfaces[id]
		ip                 net.IP
		port               int
		proto              string
	)

	if containerInterface == nil {
		return job.Errorf("No network information to release for %s", id)
	}

	for _, nat := range containerInterface.PortMappings {
		if err := portmapper.Unmap(nat); err != nil {
			log.Printf("Unable to unmap port %s: %s", nat, err)
		}

		// this is host mappings
		switch a := nat.(type) {
		case *net.TCPAddr:
			proto = "tcp"
			ip = a.IP
			port = a.Port
		case *net.UDPAddr:
			proto = "udp"
			ip = a.IP
			port = a.Port
		}

		if err := portallocator.ReleasePort(ip, proto, port); err != nil {
			log.Printf("Unable to release port %s", nat)
		}
	}

	if err := ipallocator.ReleaseIP(bridgeNetwork, &containerInterface.IP); err != nil {
		log.Printf("Unable to release ip %s\n", err)
	}
	return engine.StatusOK
}

// Allocate an external port and map it to the interface
func AllocatePort(job *engine.Job) engine.Status {
	var (
		err error

		ip            = defaultBindingIP
		id            = job.Args[0]
		hostIP        = job.Getenv("HostIP")
		hostPort      = job.GetenvInt("HostPort")
		containerPort = job.GetenvInt("ContainerPort")
		proto         = job.Getenv("Proto")
		network       = currentInterfaces[id]
	)

	if hostIP != "" {
		ip = net.ParseIP(hostIP)
	}

	// host ip, proto, and host port
	hostPort, err = portallocator.RequestPort(ip, proto, hostPort)
	if err != nil {
		job.Error(err)
		return engine.StatusErr
	}

	var (
		container net.Addr
		host      net.Addr
	)

	if proto == "tcp" {
		host = &net.TCPAddr{IP: ip, Port: hostPort}
		container = &net.TCPAddr{IP: network.IP, Port: containerPort}
	} else {
		host = &net.UDPAddr{IP: ip, Port: hostPort}
		container = &net.UDPAddr{IP: network.IP, Port: containerPort}
	}

	if err := portmapper.Map(container, ip, hostPort); err != nil {
		portallocator.ReleasePort(ip, proto, hostPort)

		job.Error(err)
		return engine.StatusErr
	}
	network.PortMappings = append(network.PortMappings, host)

	out := engine.Env{}
	out.Set("HostIP", ip.String())
	out.SetInt("HostPort", hostPort)

	if _, err := out.WriteTo(job.Stdout); err != nil {
		job.Error(err)
		return engine.StatusErr
	}
	return engine.StatusOK
}

func LinkContainers(job *engine.Job) engine.Status {
	var (
		action       = job.Args[0]
		childIP      = job.Getenv("ChildIP")
		parentIP     = job.Getenv("ParentIP")
		ignoreErrors = job.GetenvBool("IgnoreErrors")
		ports        = job.GetenvList("Ports")
	)
	split := func(p string) (string, string) {
		parts := strings.Split(p, "/")
		return parts[0], parts[1]
	}

	for _, p := range ports {
		port, proto := split(p)
		if output, err := iptables.Raw(action, "FORWARD",
			"-i", bridgeIface, "-o", bridgeIface,
			"-p", proto,
			"-s", parentIP,
			"--dport", port,
			"-d", childIP,
			"-j", "ACCEPT"); !ignoreErrors && err != nil {
			job.Error(err)
			return engine.StatusErr
		} else if len(output) != 0 {
			job.Errorf("Error toggle iptables forward: %s", output)
			return engine.StatusErr
		}

		if output, err := iptables.Raw(action, "FORWARD",
			"-i", bridgeIface, "-o", bridgeIface,
			"-p", proto,
			"-s", childIP,
			"--sport", port,
			"-d", parentIP,
			"-j", "ACCEPT"); !ignoreErrors && err != nil {
			job.Error(err)
			return engine.StatusErr
		} else if len(output) != 0 {
			job.Errorf("Error toggle iptables forward: %s", output)
			return engine.StatusErr
		}
	}
	return engine.StatusOK
}


text:
<?php
require_once('../Connections/db.php');
include('../include/_restrito.php');
include('../classes/function.php');

// INFO PAGE
$pagetitle ="Páginas";
$pagebtn ="Página";
$tabelabd ="paginas";
$controller = "../controller/paginasController.php";

// INFO IMAGE RESIZE
$largura ="1000";
$altura ="800";

// RECEIVE DATA
mysql_select_db($database_db, $db);
$query_r = "SELECT * FROM $tabelabd WHERE idusuario='".$row_user["idusuario"]."' ORDER BY id DESC";
$r = mysql_query($query_r, $db) or die(mysql_error());
$row_r = mysql_fetch_assoc($r);
$totalRows_r = mysql_num_rows($r);

// RECEIVE DATA GALLERYV
mysql_select_db($database_db, $db);
$query_galeria = "SELECT * FROM galerias WHERE idusuario='".$row_user["idusuario"]."' AND ativo = 'S' ORDER BY titulo ASC";
$galeria = mysql_query($query_galeria, $db) or die(mysql_error());
$row_galeria = mysql_fetch_assoc($galeria);
$totalRows_galeria = mysql_num_rows($galeria);

// RECEIVE FOR UPDATE
$upregister = "-1"; if (isset($_GET['edit'])) { $upregister = $_GET['edit'];}
$editdecode = base64_decode($upregister);
mysql_select_db($database_db, $db);
$query_up = sprintf("SELECT * FROM $tabelabd WHERE id = %s", GetSQLValueString($editdecode, "int"));
$up = mysql_query($query_up, $db) or die(mysql_error());
$row_up = mysql_fetch_assoc($up);
$totalRows_up = mysql_num_rows($up);
?>

<?php include("../include/_head.php"); ?>

                <?php if (@$_GET['s'] > 0) { ?>

                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                     Efetuado com sucesso!

                <?php } ?>

Administrar <?php echo $pagetitle; ?>

                        <?php if (@$_GET['upload'] != "") { ?>

                        <form id="upload" method="post" action="../view/paginasFotosUpload.php?upload=<?php echo $_GET['upload']; ?>&iduser=<?php echo $_GET['iduser']; ?>&tipo=<?php echo $tabelabd; ?>&w=<?php echo $largura; ?>&h=<?php echo $altura; ?>" enctype="multipart/form-data">

                            Arraste para cá as fotos

                             Procurar fotos
                            <input type="file" name="upl" multiple />

                        </form>

 Fotos cadastradas

 Voltar

                        <?php } else { ?>

						<?php if (@$_GET['edit'] != "") { ?>

                                <form role="form" action="<?php echo $controller; ?>" method="post" data-toggle="validator" class="form-group" name="editForm" id="editForm">

                                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

 Edite este registro

                                             Quer esta galeria aparecendo no site?
                                            <select class="form-control" name="ativo">
                                                <option value="S" <?php if (!(strcmp("S", htmlentities($row_up['ativo'], ENT_COMPAT, 'utf-8')))) {echo "SELECTED";} ?>> Sim</option>
                                                <option value="N" <?php if (!(strcmp("N", htmlentities($row_up['ativo'], ENT_COMPAT, 'utf-8')))) {echo "SELECTED";} ?>>Não</option>
                                            </select>

                                             Selecione o tipo de conteúdo
                                            <select class="form-control" name="tipo">
                                                <option value="<?php echo htmlentities($row_up['tipo'], ENT_COMPAT, 'utf-8'); ?>" <?php echo htmlentities($row_up['tipo'], ENT_COMPAT, 'utf-8'); ?>><?php echo htmlentities($row_up['tipo'], ENT_COMPAT, 'utf-8'); ?></option>
                                                <option value="categoria01" <?php if (!(strcmp("categoria01", htmlentities($row_up['tipo'], ENT_COMPAT, 'utf-8')))) {echo "SELECTED";} ?>>Categoria 01</option>
                                            </select>

                                            <input placeholder="Titulo" name="titulo" type="text" class="form-control" value="<?php echo htmlentities($row_up['titulo'], ENT_COMPAT, 'utf-8'); ?>" required/>

                                            <textarea placeholder="Campo de texto livre 1" name="texto01" type="text" class="form-control"/><?php echo htmlentities($row_up['texto01'], ENT_COMPAT, 'utf-8'); ?></textarea>

                                            <textarea placeholder="Campo de texto livre 2" name="texto02" type="text" class="form-control"/><?php echo htmlentities($row_up['texto02'], ENT_COMPAT, 'utf-8'); ?></textarea>

                                            <textarea  placeholder="Campo de texto livre 3" name="texto03" type="text" class="form-control"/><?php echo htmlentities($row_up['texto03'], ENT_COMPAT, 'utf-8'); ?></textarea>

                                            <textarea placeholder="Campo de texto livre 4" name="texto04" type="text" class="form-control"/><?php echo htmlentities($row_up['texto04'], ENT_COMPAT, 'utf-8'); ?></textarea>

                                                 Galeria de Fotos
                                                <select class="form-control" name="idgaleria">
                                                    <option value="">Sem Nenhuma</option>
                                                    <?php do { ?>
                                                    <option value="<?php echo $row_galeria['id']; ?>" <?php if (!(strcmp($row_galeria['id'], htmlentities($row_up['idgaleria'], ENT_COMPAT, 'utf-8')))) {echo "SELECTED";} ?>><?php echo $row_galeria['titulo']; ?></option>
                                                    <?php } while ($row_galeria = mysql_fetch_assoc($galeria)); ?>
                                                </select>

                                                 Imagem anexada
                                                <?php if (@$row_up['imagem'] != "") { ?>

<img width="400" src="../img/paginas/<?php echo $row_up['imagem']; ?>">

<a href="paginas.php?upload=<?php echo $_GET['edit']; ?>&iduser=<?php echo base64_encode($row_user["idusuario"]); ?>">
 Altere esta imagem

                                                <?php } else { ?>

<a href="paginas.php?upload=<?php echo $_GET['edit']; ?>&iduser=<?php echo base64_encode($row_user["idusuario"]); ?>">
 Enviar uma imagem

                                                <?php } ?>

                                            <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                                            <input type="submit" class="btn btn-primary"  value="Atualizar" />
                                            <input type="hidden" name="data_cadastro" value="<?php echo htmlentities($row_up['data_cadastro'], ENT_COMPAT, 'utf-8'); ?>" />
                                            <input type="hidden" class="btn btn-primary" name="id"  value="<?php echo $row_up['id']; ?>" />
                                            <input type="hidden" name="MM_update" value="editForm" />

                                </form>

                        <?php } else { ?>

                        <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#formModal">
                             Adicionar nova <?php echo $pagebtn; ?>
                        </button>

                                <form role="form" action="<?php echo $controller; ?>" method="post" data-toggle="validator" name="addForm" class="form-group" id="addForm">

    	                        		<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

 Insira um novo registro

                                                <select class="form-control col-md-12" name="tipo" require>
                                                    <option value="" selected>Selecione uma Categoria</option>
                                                    <option value="categoria01">Categoria 01</option>
                                                </select>

                                            <input placeholder="Titulo" name="titulo" type="text" class="form-control" value="" required/>

                                            <textarea placeholder="Campo de texto livre 1" name="texto01" type="text" class="form-control"/></textarea>

                                            <textarea placeholder="Campo de texto livre 2" name="texto02" type="text" class="form-control"/></textarea>

                                            <textarea placeholder="Campo de texto livre 3" name="texto03" type="text" class="form-control"/></textarea>

                                            <textarea placeholder="Campo de texto livre 4" name="texto04" type="text" class="form-control"/></textarea>

                                                 Galeria de Imagem
                                                <select class="form-control" name="idgaleria">
                                                    <option value="" selected>Selecione alguma galeria se desejar</option>
                                                    <?php do { ?>
                                                    <option value="<?php echo $row_galeria['id']; ?>"><?php echo $row_galeria['titulo']; ?></option>
                                                    <?php } while ($row_galeria = mysql_fetch_assoc($galeria)); ?>
                                                </select>

                                            <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                                            <input type="submit" class="btn btn-primary"  value="Inserir" />
                                            <input type="hidden" name="ativo" value="N" />
                                            <input type="hidden" name="idusuario" value="<?php echo $row_user["idusuario"] ?>" />
                                            <input type="hidden" name="data_cadastro" value="<?php echo date("Y-m-d"); ?>" />
                                            <input type="hidden" name="MM_insert" value="addForm" />

                                </form>

                                    <?php if (@$row_r['id'] > 0) { ?>

                                                ID
                                                ATIVO
                                                TIPO
                                                NOME
                                                AÇÕES

                                            <?php do { ?>
                                            <tr class="odd gradeX <?php if (@$_GET['idpost'] == $row_r['id']) { ?> div-atencao <?php } ?>">
                                                <?php echo $row_r['id']; ?>

                                                    <input type="hidden" value="<?php echo $row_r['id']; ?>" />
                                                    <input type="checkbox" <?php if($row_r['ativo']=="S") { echo "checked"; } ?> id="<?php echo $row_r['id']; ?>" /><label for="<?php echo $row_r['id']; ?>">

                                                <?php echo limitar($row_r['tipo'],50); ?>
                                                <?php echo limitar($row_r['titulo'],50); ?>

                                                      <button class="btn btn-default btn-block dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                                                         Ações

                                                      </button>

<a href="?edit=<?php echo base64_encode($row_r['id']); ?>"> Editar

<a onClick="return confirm('Deseja realmente excluir?')" href="<?php echo $controller; ?>?del=<?php echo base64_encode($row_r['id']); ?>"> Deletar

                                            <?php } while ($row_r = mysql_fetch_assoc($r)); ?>

                                    <?php } else { ?>

 Nenhum registro foi encontrado

                                    <?php } ?>

            <?php } ?>
            <?php } ?>

<?php include("../include/_footer.php"); ?>


text:
.. raw:: html

    </div>
    <div class=col-md-9 content>

opcsim.AerosolDistribution
==========================

.. currentmodule:: opcsim

.. autoclass:: AerosolDistribution

   .. automethod:: __init__

   .. rubric:: Methods

   .. autosummary::

      ~AerosolDistribution.__init__
      ~AerosolDistribution.add_mode
      ~AerosolDistribution.cdf
      ~AerosolDistribution.pdf