text:
package org.commonjava.indy.bind.jaxrs;

import org.commonjava.cdi.util.weft.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static org.commonjava.indy.util.RequestContextHelper.X_FORWARDED_FOR;

@ApplicationScoped
public class ThreadContextFilter
        implements Filter
{
    @Inject
    private MDCManager mdcManager;

    private final Logger logger = LoggerFactory.getLogger( getClass() );

    @Override
    public void init( final FilterConfig filterConfig )
            throws ServletException
    {
    }

    @Override
    public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain )
            throws IOException, ServletException
    {
        try
        {
            ThreadContext.clearContext();
            ThreadContext.getContext( true );

            if ( request instanceof HttpServletRequest )
            {
                HttpServletRequest hsr = (HttpServletRequest) request;

                String clientAddr = request.getRemoteAddr();
                final String xForwardFor = hsr.getHeader( X_FORWARDED_FOR );
                if ( xForwardFor != null )
                {
                    clientAddr = xForwardFor; // OSE proxy use HTTP header 'x-forwarded-for' to represent user IP
                }

                mdcManager.putUserIP( clientAddr );
                mdcManager.putExtraHeaders( hsr );
                mdcManager.putRequestIDs( hsr );
            }

            chain.doFilter( request, response );
        }
        finally
        {
            ThreadContext.clearContext();
            mdcManager.clear();
        }
    }

    @Override
    public void destroy()
    {
    }

}

redpajama_set_name: RedPajamaGithub


text:
using Community.CsharpSqlite.SQLiteClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GAPPSF.Locus
{
    public class Export
    {
        public static void ExportToFile(string filename, List<Core.Data.Geocache> gcList)
        {
            try
            {
                DateTime nextUpdate = DateTime.Now.AddSeconds(1);
                using (Utils.ProgressBlock fixscr = new Utils.ProgressBlock("ExportingLocus", "CreatingFile", 1, 0, true))
                {
                    System.Collections.Hashtable logTypes = new System.Collections.Hashtable();
                    logTypes.Add(2, "Found it");
                    logTypes.Add(3, "Didn't find it");
                    logTypes.Add(4, "Write note");
                    logTypes.Add(5, "Archive");
                    logTypes.Add(7, "Needs Archived");
                    logTypes.Add(9, "Will Attend");
                    logTypes.Add(10, "Attended");
                    logTypes.Add(11, "Webcam Photo Taken");
                    logTypes.Add(12, "Unarchive");
                    logTypes.Add(22, "Temporarily Disable Listing");
                    logTypes.Add(23, "Enable Listing");
                    logTypes.Add(24, "Publish Listing");
                    logTypes.Add(25, "Retract Listing");
                    logTypes.Add(45, "Needs Maintenance");
                    logTypes.Add(46, "Owner Maintenance");
                    logTypes.Add(47, "Update Coordinates");
                    logTypes.Add(68, "Post Reviewer Note");
                    logTypes.Add(74, "Announcement");

                    if (System.IO.File.Exists(filename))
                    {
                        System.IO.File.Delete(filename);
                    }

                    Utils.ResourceHelper.SaveToFile("/Locus/sqlite.db3", filename, true);

                    SqliteConnection dbconFiles = null;
                    string basePath = null;
                    int imgFolderIndex = 0;
                    int imgInFolderCount = 0;
                    if (Core.Settings.Default.LocusExportOfflineImages)
                    {
                        basePath = System.IO.Path.GetDirectoryName(filename);
                        basePath = System.IO.Path.Combine(basePath, ".GrabbedImages");
                        if (!System.IO.Directory.Exists(basePath))
                        {
                            System.IO.Directory.CreateDirectory(basePath);
                        }
                        if (Core.Settings.Default.LocusMaxImagesInFolder > 0)
                        {
                            string imgSubFolder = System.IO.Path.Combine(basePath, string.Format("batch{0}", imgFolderIndex));
                            while (System.IO.Directory.Exists(imgSubFolder))
                            {
                                imgFolderIndex++;
                                imgSubFolder = System.IO.Path.Combine(basePath, string.Format("batch{0}", imgFolderIndex));
                            }
                        }
                        dbconFiles = new SqliteConnection(string.Format("data source=file:{0}", System.IO.Path.Combine(basePath, "files.db3")));
                        dbconFiles.Open();
                        using (SqliteCommand cmd = new SqliteCommand("", dbconFiles))
                        {
                            cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='fdone'";
                            object o = cmd.ExecuteScalar();
                            if (o == null || o.GetType() == typeof(DBNull))
                            {
                                cmd.CommandText = "CREATE TABLE fdone (dlink text)";
                                cmd.ExecuteNonQuery();
                                cmd.CommandText = "CREATE INDEX ifdone on fdone (dlink)";
                                cmd.ExecuteNonQuery();
                            }

                            cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='files'";
                            o = cmd.ExecuteScalar();
                            if (o == null || o.GetType() == typeof(DBNull))
                            {
                                cmd.CommandText = "CREATE TABLE files (Link text collate nocase, Fname text collate nocase, Found integer)";
                                cmd.ExecuteNonQuery();
                                cmd.CommandText = "CREATE INDEX ilink on files (Link)";
                                cmd.ExecuteNonQuery();
                                cmd.CommandText = "CREATE INDEX ifname on files (Fname)";
                                cmd.ExecuteNonQuery();
                            }

                            cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='purge'";
                            o = cmd.ExecuteScalar();
                            if (o == null || o.GetType() == typeof(DBNull))
                            {
                                cmd.CommandText = "CREATE TABLE purge (pfile text)";
                                cmd.ExecuteNonQuery();
                            }
                        }
                    }

                    using (SqliteConnection dbcon = new SqliteConnection(string.Format("data source=file:{0}", filename)))
                    {
                        dbcon.Open();

                        DbParameter par;
                        using (Utils.ProgressBlock progress = new Utils.ProgressBlock("ExportingLocus", "SavingGeocaches", gcList.Count, 0, true))
                        {
                            using (SqliteCommand cmd = new SqliteCommand("", dbcon))
                            using (SqliteCommand cmd2 = new SqliteCommand("", dbcon))
                            using (SqliteCommand cmd3 = new SqliteCommand("", dbcon))
                            using (SqliteCommand cmd4 = new SqliteCommand("", dbcon))
                            using (SqliteCommand cmd5 = new SqliteCommand("", dbcon))
                            using (SqliteCommand cmd6 = new SqliteCommand("", dbcon))
                            using (SqliteCommand cmd7 = new SqliteCommand("", dbcon))
                            using (SqliteCommand cmd8 = new SqliteCommand("", dbcon))
                            {
                                cmd.CommandText = "drop index CachesSmart";
                                cmd.ExecuteNonQuery();

                                cmd.CommandText = "insert into Caches (Code, Name, PlacedBy, Archived, CacheId, CacheType, Container, Country, Difficulty, Found, HasCorrected, HasUserNote, Latitude, LongHtm, Longitude, OwnerName, PlacedDate, ShortHtm, State, Terrain, UserFlag, IsOwner, LatOriginal, LonOriginal, Status, GcNote, IsPremium, FavPoints) values (@Code, @Name, @PlacedBy, @Archived, @CacheId, @CacheType, @Container, @Country, @Difficulty, @Found, @HasCorrected, @HasUserNote, @Latitude, @LongHtm, @Longitude, @OwnerName, @PlacedDate, @ShortHtm, @State, @Terrain, @UserFlag, @IsOwner, @LatOriginal, @LonOriginal, @Status, @GcNote, @IsPremium, @FavPoints)";
                                cmd2.CommandText = "insert into CacheMemo (Code, LongDescription, ShortDescription, Url, Hints, UserNote) values (@Code, @LongDescription, @ShortDescription, @Url, @Hints, @UserNote)";
                                cmd3.CommandText = "insert into Attributes (aCode, aId, aInc) values (@aCode, @aId, @aInc)";
                                cmd4.CommandText = "insert into LogMemo (lParent, lLogId, lText) values (@lParent, @lLogId, @lText)";
                                cmd5.CommandText = "insert into Logs (lParent, lLogId, lType, lBy, lDate, lLat, lLon, lEncoded, lownerid, lHasHtml, lIsowner, lTime) values (@lParent, @lLogId, @lType, @lBy, @lDate, @lLat, @lLon, @lEncoded, @lownerid, @lHasHtml, @lIsowner, @lTime)";
                                cmd6.CommandText = "insert into WayMemo (cParent, cCode, cComment, cUrl) values (@cParent, @cCode, @cComment, @cUrl)";
                                cmd7.CommandText = "insert into Waypoints (cParent, cCode, cPrefix, cName, cType, cLat, cLon, cByuser, cDate, cFlag, sB1) values (@cParent, @cCode, @cPrefix, @cName, @cType, @cLat, @cLon, @cByuser, @cDate, @cFlag, @sB1)";
                                cmd8.CommandText = "insert into Corrected (kCode, kBeforeLat, kBeforeLon, kAfterLat, kAfterLon) values (@kCode, @kBeforeLat, @kBeforeLon, @kAfterLat, @kAfterLon)";

                                par = cmd8.CreateParameter();
                                par.ParameterName = "@kCode";
                                par.DbType = DbType.String;
                                cmd8.Parameters.Add(par);
                                par = cmd8.CreateParameter();
                                par.ParameterName = "@kBeforeLat";
                                par.DbType = DbType.String;
                                cmd8.Parameters.Add(par);
                                par = cmd8.CreateParameter();
                                par.ParameterName = "@kBeforeLon";
                                par.DbType = DbType.String;
                                cmd8.Parameters.Add(par);
                                par = cmd8.CreateParameter();
                                par.ParameterName = "@kAfterLat";
                                par.DbType = DbType.String;
                                cmd8.Parameters.Add(par);
                                par = cmd8.CreateParameter();
                                par.ParameterName = "@kAfterLon";
                                par.DbType = DbType.String;
                                cmd8.Parameters.Add(par);

                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cParent";
                                par.DbType = DbType.String;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cCode";
                                par.DbType = DbType.String;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cPrefix";
                                par.DbType = DbType.String;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cName";
                                par.DbType = DbType.String;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cType";
                                par.DbType = DbType.String;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cLat";
                                par.DbType = DbType.String;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cLon";
                                par.DbType = DbType.String;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cByuser";
                                par.DbType = DbType.Boolean;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cDate";
                                par.DbType = DbType.String;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@cFlag";
                                par.DbType = DbType.Boolean;
                                cmd7.Parameters.Add(par);
                                par = cmd7.CreateParameter();
                                par.ParameterName = "@sB1";
                                par.DbType = DbType.Boolean;
                                cmd7.Parameters.Add(par);

                                par = cmd6.CreateParameter();
                                par.ParameterName = "@cParent";
                                par.DbType = DbType.String;
                                cmd6.Parameters.Add(par);
                                par = cmd6.CreateParameter();
                                par.ParameterName = "@cCode";
                                par.DbType = DbType.String;
                                cmd6.Parameters.Add(par);
                                par = cmd6.CreateParameter();
                                par.ParameterName = "@cComment";
                                par.DbType = DbType.String;
                                cmd6.Parameters.Add(par);
                                par = cmd6.CreateParameter();
                                par.ParameterName = "@cUrl";
                                par.DbType = DbType.String;
                                cmd6.Parameters.Add(par);

                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lParent";
                                par.DbType = DbType.String;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lLogId";
                                par.DbType = DbType.Int32;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lType";
                                par.DbType = DbType.String;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lBy";
                                par.DbType = DbType.String;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lDate";
                                par.DbType = DbType.String;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lLat";
                                par.DbType = DbType.String;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lLon";
                                par.DbType = DbType.String;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lEncoded";
                                par.DbType = DbType.Boolean;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lownerid";
                                par.DbType = DbType.Int32;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lHasHtml";
                                par.DbType = DbType.Boolean;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lIsowner";
                                par.DbType = DbType.Boolean;
                                cmd5.Parameters.Add(par);
                                par = cmd5.CreateParameter();
                                par.ParameterName = "@lTime";
                                par.DbType = DbType.String;
                                cmd5.Parameters.Add(par);

                                par = cmd4.CreateParameter();
                                par.ParameterName = "@lParent";
                                par.DbType = DbType.String;
                                cmd4.Parameters.Add(par);
                                par = cmd4.CreateParameter();
                                par.ParameterName = "@lLogId";
                                par.DbType = DbType.Int32;
                                cmd4.Parameters.Add(par);
                                par = cmd4.CreateParameter();
                                par.ParameterName = "@lText";
                                par.DbType = DbType.String;
                                cmd4.Parameters.Add(par);

                                par = cmd3.CreateParameter();
                                par.ParameterName = "@aCode";
                                par.DbType = DbType.String;
                                cmd3.Parameters.Add(par);
                                par = cmd3.CreateParameter();
                                par.ParameterName = "@aId";
                                par.DbType = DbType.Int32;
                                cmd3.Parameters.Add(par);
                                par = cmd3.CreateParameter();
                                par.ParameterName = "@aInc";
                                par.DbType = DbType.Int32;
                                cmd3.Parameters.Add(par);

                                par = cmd2.CreateParameter();
                                par.ParameterName = "@Code";
                                par.DbType = DbType.String;
                                cmd2.Parameters.Add(par);
                                par = cmd2.CreateParameter();
                                par.ParameterName = "@LongDescription";
                                par.DbType = DbType.String;
                                cmd2.Parameters.Add(par);
                                par = cmd2.CreateParameter();
                                par.ParameterName = "@ShortDescription";
                                par.DbType = DbType.String;
                                cmd2.Parameters.Add(par);
                                par = cmd2.CreateParameter();
                                par.ParameterName = "@Url";
                                par.DbType = DbType.String;
                                cmd2.Parameters.Add(par);
                                par = cmd2.CreateParameter();
                                par.ParameterName = "@Hints";
                                par.DbType = DbType.String;
                                cmd2.Parameters.Add(par);
                                par = cmd2.CreateParameter();
                                par.ParameterName = "@UserNote";
                                par.DbType = DbType.String;
                                cmd2.Parameters.Add(par);

                                par = cmd.CreateParameter();
                                par.ParameterName = "@Code";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Name";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@PlacedBy";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Archived";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@CacheId";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@CacheType";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Container";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Country";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Difficulty";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Found";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@HasCorrected";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@HasUserNote";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Latitude";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@LongHtm";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Longitude";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@OwnerName";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@PlacedDate";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@ShortHtm";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@State";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Terrain";
                                par.DbType = DbType.Double;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@UserFlag";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@IsOwner";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@LatOriginal";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@LonOriginal";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@Status";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@GcNote";
                                par.DbType = DbType.String;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@IsPremium";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);
                                par = cmd.CreateParameter();
                                par.ParameterName = "@FavPoints";
                                par.DbType = DbType.Int32;
                                cmd.Parameters.Add(par);

                                cmd.Prepare();
                                cmd2.Prepare();
                                cmd3.Prepare();
                                cmd4.Prepare();
                                cmd5.Prepare();
                                cmd6.Prepare();
                                cmd7.Prepare();
                                cmd8.Prepare();

                                //using (DbTransaction trans = dbcon.BeginTransaction())
                                //{
                                int index = 0;
                                foreach (Core.Data.Geocache gc in gcList)
                                {
                                    string notes = "";
                                    if (!string.IsNullOrEmpty(gc.Notes))
                                    {
                                        notes = System.Web.HttpUtility.HtmlDecode(gc.Notes);
                                    }
                                    if (!string.IsNullOrEmpty(gc.PersonalNote))
                                    {
                                        notes = string.Concat(notes, gc.PersonalNote);
                                    }

                                    cmd2.Parameters["@Code"].Value = gc.Code;
                                    cmd2.Parameters["@LongDescription"].Value = gc.LongDescription ?? "";
                                    cmd2.Parameters["@ShortDescription"].Value = gc.ShortDescription ?? "";
                                    cmd2.Parameters["@Url"].Value = gc.Url ?? "";
                                    cmd2.Parameters["@Hints"].Value = gc.EncodedHints ?? "";
                                    cmd2.Parameters["@UserNote"].Value = notes;

                                    cmd.Parameters["@Code"].Value = gc.Code;
                                    cmd.Parameters["@Name"].Value = gc.Name ?? "";
                                    cmd.Parameters["@PlacedBy"].Value = gc.PlacedBy ?? "";
                                    cmd.Parameters["@Archived"].Value = gc.Archived ? 1 : 0;
                                    cmd.Parameters["@CacheId"].Value = Utils.Conversion.GetCacheIDFromCacheCode(gc.Code).ToString();
                                    cmd.Parameters["@CacheType"].Value = getCacheType(gc.GeocacheType);
                                    cmd.Parameters["@Container"].Value = getContainer(gc.Container);
                                    cmd.Parameters["@Country"].Value = gc.Country ?? "";
                                    cmd.Parameters["@Difficulty"].Value = gc.Difficulty;
                                    cmd.Parameters["@Found"].Value = gc.Found ? 1 : 0;
                                    cmd.Parameters["@HasCorrected"].Value = gc.ContainsCustomLatLon ? 1 : 0;
                                    cmd.Parameters["@HasUserNote"].Value = gc.ContainsNote ? 1 : 0;
                                    cmd.Parameters["@LatOriginal"].Value = gc.Lat.ToString().Replace(',', '.');
                                    cmd.Parameters["@LonOriginal"].Value = gc.Lon.ToString().Replace(',', '.');
                                    if (gc.ContainsCustomLatLon)
                                    {
                                        cmd.Parameters["@Latitude"].Value = gc.CustomLat.ToString().Replace(',', '.');
                                        cmd.Parameters["@Longitude"].Value = gc.CustomLon.ToString().Replace(',', '.');
                                    }
                                    else
                                    {
                                        cmd.Parameters["@Latitude"].Value = gc.Lat.ToString().Replace(',', '.');
                                        cmd.Parameters["@Longitude"].Value = gc.Lon.ToString().Replace(',', '.');
                                    }
                                    cmd.Parameters["@LongHtm"].Value = gc.LongDescriptionInHtml ? 1 : 0;
                                    cmd.Parameters["@OwnerName"].Value = gc.Owner ?? "";
                                    cmd.Parameters["@PlacedDate"].Value = gc.PublishedTime.ToString("yyyy-MM-dd");
                                    cmd.Parameters["@ShortHtm"].Value = gc.ShortDescriptionInHtml ? 1 : 0;
                                    cmd.Parameters["@State"].Value = gc.State ?? "";
                                    cmd.Parameters["@Terrain"].Value = gc.Terrain;
                                    cmd.Parameters["@UserFlag"].Value = gc.Flagged ? 1 : 0;
                                    cmd.Parameters["@IsOwner"].Value = gc.IsOwn ? 1 : 0;
                                    cmd.Parameters["@Status"].Value = gc.Available ? "A" : gc.Archived ? "X" : "T";
                                    cmd.Parameters["@GcNote"].Value = notes;
                                    cmd.Parameters["@IsPremium"].Value = gc.MemberOnly ? 1 : 0;
                                    cmd.Parameters["@FavPoints"].Value = gc.Favorites;

                                    cmd.ExecuteNonQuery();
                                    cmd2.ExecuteNonQuery();

                                    if (gc.ContainsCustomLatLon)
                                    {
                                        cmd8.Parameters["@kCode"].Value = gc.Code;
                                        cmd8.Parameters["@kBeforeLat"].Value = gc.Lat.ToString().Replace(',', '.');
                                        cmd8.Parameters["@kBeforeLon"].Value = gc.Lon.ToString().Replace(',', '.');
                                        cmd8.Parameters["@kAfterLat"].Value = gc.CustomLat.ToString().Replace(',', '.');
                                        cmd8.Parameters["@kAfterLon"].Value = gc.CustomLon.ToString().Replace(',', '.');

                                        cmd8.ExecuteNonQuery();
                                    }

                                    List<int> attr = gc.AttributeIds;
                                    foreach (int att in attr)
                                    {
                                        cmd3.Parameters["@aCode"].Value = gc.Code;
                                        cmd3.Parameters["@aId"].Value = Math.Abs(att);
                                        cmd3.Parameters["@aInc"].Value = att < 0 ? 0 : 1;

                                        cmd3.ExecuteNonQuery();
                                    }

                                    List<Core.Data.Log> logs = Utils.DataAccess.GetLogs(gc.Database, gc.Code).Take(Core.Settings.Default.LocusMaxLogs).ToList();
                                    foreach (Core.Data.Log l in logs)
                                    {
                                        try
                                        {
                                            int logid = 0;
                                            if (!int.TryParse(l.ID, out logid))
                                            {
                                                logid = Utils.Conversion.GetCacheIDFromCacheCode(l.ID);
                                            }
                                            cmd4.Parameters["@lLogId"].Value = logid;
                                            cmd4.Parameters["@lText"].Value = l.Text ?? "";
                                            cmd4.Parameters["@lParent"].Value = gc.Code;
                                            cmd4.ExecuteNonQuery();

                                            cmd5.Parameters["@lLogId"].Value = logid;
                                            cmd5.Parameters["@lParent"].Value = gc.Code;
                                            object o = logTypes[l.LogType.ID];
                                            if (o == null)
                                            {
                                                cmd5.Parameters["@lType"].Value = 4;
                                            }
                                            else
                                            {
                                                cmd5.Parameters["@lType"].Value = (string)o;
                                            }
                                            cmd5.Parameters["@lBy"].Value = l.Finder ?? "";
                                            cmd5.Parameters["@lDate"].Value = l.Date.ToString("yyyy-MM-dd HH:mm:ss");
                                            cmd5.Parameters["@lLat"].Value = DBNull.Value;
                                            cmd5.Parameters["@lLon"].Value = DBNull.Value;
                                            cmd5.Parameters["@lEncoded"].Value = l.Encoded;
                                            try
                                            {
                                                cmd5.Parameters["@lownerid"].Value = int.Parse(l.FinderId);
                                            }
                                            catch
                                            {
                                            }
                                            cmd5.Parameters["@lHasHtml"].Value = false;
                                            cmd5.Parameters["@lIsowner"].Value = gc.IsOwn;
                                            cmd5.Parameters["@lTime"].Value = "";

                                            cmd5.ExecuteNonQuery();

                                        }
                                        catch(Exception e)
                                        {
                                            Core.ApplicationData.Instance.Logger.AddLog(new Export(), e);
                                        }
                                    }

                                    List<Core.Data.Waypoint> wps = Utils.DataAccess.GetWaypointsFromGeocache(gc.Database, gc.Code);
                                    foreach (Core.Data.Waypoint w in wps)
                                    {
                                        try
                                        {
                                            cmd6.Parameters["@cParent"].Value = gc.Code;
                                            cmd6.Parameters["@cCode"].Value = w.Code;
                                            cmd6.Parameters["@cComment"].Value = w.Comment;
                                            cmd6.Parameters["@cUrl"].Value = w.Url;

                                            cmd7.Parameters["@cParent"].Value = gc.Code;
                                            cmd7.Parameters["@cCode"].Value = w.Code;
                                            cmd7.Parameters["@cPrefix"].Value = w.Code.Substring(0, 2);
                                            cmd7.Parameters["@cName"].Value = w.Name ?? "";
                                            cmd7.Parameters["@cType"].Value = getWPType(w.WPType);
                                            cmd7.Parameters["@cLat"].Value = w.Lat == null ? "0.0" : w.Lat.ToString().Replace(',', '.');
                                            cmd7.Parameters["@cLon"].Value = w.Lon == null ? "0.0" : w.Lon.ToString().Replace(',', '.');
                                            cmd7.Parameters["@cByuser"].Value = false;
                                            cmd7.Parameters["@cDate"].Value = w.Time.ToString("yyyy-MM-dd");
                                            cmd7.Parameters["@cFlag"].Value = false;
                                            cmd7.Parameters["@sB1"].Value = false;

                                            cmd7.ExecuteNonQuery();
                                            cmd6.ExecuteNonQuery();
                                        }
                                        catch(Exception e)
                                        {
                                            Core.ApplicationData.Instance.Logger.AddLog(new Export(), e);
                                        }
                                    }

                                    if (dbconFiles != null && (gc.LongDescriptionInHtml || gc.ShortDescriptionInHtml))
                                    {
                                        try
                                        {
                                            List<string> imgs = Utils.DataAccess.GetImagesOfGeocache(gc.Database, gc.Code);
                                            Dictionary<string, string> oimgs = ImageGrabber.OfflineImagesManager.Instance.GetImages(gc);
                                            foreach (string im in imgs)
                                            {
                                                if (oimgs.ContainsKey(im))
                                                {
                                                    string p = oimgs[im];
                                                    using (SqliteCommand filescmd = new SqliteCommand("", dbconFiles))
                                                    {
                                                        filescmd.CommandText = string.Format("SELECT Fname FROM files WHERE Link='{0}'", im.Replace("'", "''"));
                                                        object o = filescmd.ExecuteScalar();
                                                        if (o == null || o.GetType() == typeof(DBNull))
                                                        {
                                                            filescmd.CommandText = string.Format("insert into files (Link, Fname, Found) values ('{0}', '{1}', 1)", im.Replace("'", "''"), System.IO.Path.GetFileName(p).Replace("'", "''"));
                                                            filescmd.ExecuteNonQuery();
                                                        }
                                                    }
                                                    if (Core.Settings.Default.LocusMaxImagesInFolder > 0)
                                                    {
                                                        imgInFolderCount++;
                                                        if (imgInFolderCount > Core.Settings.Default.LocusMaxImagesInFolder)
                                                        {
                                                            imgFolderIndex++;
                                                            imgInFolderCount = 1;
                                                        }
                                                        string imgSubFolder = System.IO.Path.Combine(basePath, string.Format("batch{0}", imgFolderIndex));
                                                        if (imgInFolderCount == 1)
                                                        {
                                                            if (!System.IO.Directory.Exists(imgSubFolder))
                                                            {
                                                                System.IO.Directory.CreateDirectory(imgSubFolder);
                                                            }
                                                        }
                                                        string dst = System.IO.Path.Combine(imgSubFolder, System.IO.Path.GetFileName(p));
                                                        if (!System.IO.File.Exists(dst))
                                                        {
                                                            System.IO.File.Copy(p, dst, true);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        string dst = System.IO.Path.Combine(basePath, System.IO.Path.GetFileName(p));
                                                        if (!System.IO.File.Exists(dst))
                                                        {
                                                            System.IO.File.Copy(p, dst, true);
                                                        }
                                                    }

                                                }
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            Core.ApplicationData.Instance.Logger.AddLog(new Export(), e);
                                        }
                                    }

                                    index++;
                                    if (DateTime.Now>=nextUpdate)
                                    {
                                        if (!progress.Update("SavingGeocaches", gcList.Count, index))
                                        {
                                            break;
                                        }
                                        nextUpdate = DateTime.Now.AddSeconds(1);
                                    }
                                }
                                //trans.Commit();
                            }
                        }
                    }
                }
            }
            catch(Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(new Export(), e);
            }
        }

        private static string getWPType(Core.Data.WaypointType type)
        {
            switch (type.ID)
            {
                case 217: return "Parking Area";
                case 220: return "Final location";
                case 218: return "Question to Answer";
                case 452: return "Reference Point";
                case 219: return "Stages of a Multicache";
                case 221: return "Trailhead";
                default: return "Stages of a Multicache";
            }
        }

        private static string getContainer(Core.Data.GeocacheContainer container)
        {
            switch (container.ID)
            {
                case 1: return "Not chosen";
                case 2: return "Micro";
                case 3: return "Regular";
                case 4: return "Large";
                case 5: return "Virtual";
                case 6: return "Other";
                case 8: return "Small";
                case 9: return "A";
                default: return "Other";
            }
        }

        private static string getCacheType(Core.Data.GeocacheType type)
        {
            switch (type.ID)
            {
                case 2: return "T";
                case 3: return "M";
                case 4: return "V";
                case 5: return "B";
                case 6: return "E";
                case 8: return "U";
                case 9: return "A";
                case 11: return "W";
                case 12: return "L";
                case 13: return "C";
                case 137: return "R";
                case 453: return "Z";
                case 1304: return "X";
                case 1858: return "I";
                case 3653: return "F";
                case 3773: return "H";
                case 3774: return "D";
                default: return "O";
            }
        }
    }
}


text:
package com.alibaba.dubbo.rpc.cluster.configurator;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.dubbo.rpc.cluster.Configurator;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * AbstractOverrideConfigurator
 *
 * @author william.liangf
 */
public abstract class AbstractConfigurator implements Configurator {

    private final URL configuratorUrl;

    public AbstractConfigurator(URL url) {
        if (url == null) {
            throw new IllegalArgumentException("configurator url == null");
        }
        this.configuratorUrl = url;
    }

    public static void main(String[] args) {
        System.out.println(URL.encode("timeout=100"));
    }

    public URL getUrl() {
        return configuratorUrl;
    }

    public URL configure(URL url) {
        if (configuratorUrl == null || configuratorUrl.getHost() == null
                || url == null || url.getHost() == null) {
            return url;
        }
        if (configuratorUrl.getPort() != 0) {// override输入提供端地址,意图是控制提供者机器。可能在提供端生效 也可能在消费端生效
            if (url.getPort() == configuratorUrl.getPort()) {
                return configureIfMatch(url.getHost(), url);
            }
        } else {// 没有端口,override输入消费端地址 或者 0.0.0.0
            // 1.如果是消费端地址,则意图是控制消费者机器,必定在消费端生效,提供端忽略;
            // 2.如果是0.0.0.0可能是控制提供端,也可能是控制提供端
            if (url.getParameter(Constants.SIDE_KEY, Constants.PROVIDER).equals(Constants.CONSUMER)) {
                return configureIfMatch(NetUtils.getLocalHost(), url);// NetUtils.getLocalHost是消费端注册到zk的消费者地址
            } else if (url.getParameter(Constants.SIDE_KEY, Constants.CONSUMER).equals(Constants.PROVIDER)) {
                return configureIfMatch(Constants.ANYHOST_VALUE, url);//控制所有提供端,地址必定是0.0.0.0,否则就要配端口从而执行上面的if分支了
            }
        }
        return url;
    }

    private URL configureIfMatch(String host, URL url) {
        if (Constants.ANYHOST_VALUE.equals(configuratorUrl.getHost()) || host.equals(configuratorUrl.getHost())) {
            String configApplication = configuratorUrl.getParameter(Constants.APPLICATION_KEY,
                    configuratorUrl.getUsername());
            String currentApplication = url.getParameter(Constants.APPLICATION_KEY, url.getUsername());
            if (configApplication == null || Constants.ANY_VALUE.equals(configApplication)
                    || configApplication.equals(currentApplication)) {
                Set<String> condtionKeys = new HashSet<String>();
                condtionKeys.add(Constants.CATEGORY_KEY);
                condtionKeys.add(Constants.CHECK_KEY);
                condtionKeys.add(Constants.DYNAMIC_KEY);
                condtionKeys.add(Constants.ENABLED_KEY);
                for (Map.Entry<String, String> entry : configuratorUrl.getParameters().entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    if (key.startsWith("~") || Constants.APPLICATION_KEY.equals(key) || Constants.SIDE_KEY.equals(key)) {
                        condtionKeys.add(key);
                        if (value != null && !Constants.ANY_VALUE.equals(value)
                                && !value.equals(url.getParameter(key.startsWith("~") ? key.substring(1) : key))) {
                            return url;
                        }
                    }
                }
                return doConfigure(url, configuratorUrl.removeParameters(condtionKeys));
            }
        }
        return url;
    }

    /**
     * 根据priority、host依次排序
     * priority值越大,优先级越高;
     * priority相同,特定host优先级高于anyhost 0.0.0.0
     *
     * @param o
     * @return
     */
    public int compareTo(Configurator o) {
        if (o == null) {
            return -1;
        }

        int ipCompare = getUrl().getHost().compareTo(o.getUrl().getHost());
        if (ipCompare == 0) {//ip相同,根据priority排序
            int i = getUrl().getParameter(Constants.PRIORITY_KEY, 0),
                    j = o.getUrl().getParameter(Constants.PRIORITY_KEY, 0);
            if (i < j) {
                return -1;
            } else if (i > j) {
                return 1;
            } else {
                return 0;
            }
        } else {
            return ipCompare;
        }

    }

    protected abstract URL doConfigure(URL currentUrl, URL configUrl);

}


text:
#include "nau/enums.h"
#include "nau/math/data.h"
#include "nau/math/number.h"
#include "nau/math/matrix.h"
#include "nau/math/vec4.h"
#include "nau/math/vec2.h"
#include "nau/render/iAPISupport.h"

#include <assert.h>
#include <map>
#include <memory>
#include <string>
#include <vector>

using namespace nau::math;
using namespace nau::render;

namespace nau {

	class AttribSet;

	class Attribute {

	public:
		friend class AttribSet;

		typedef enum {
			NONE,
			NORMALIZED,
			COLOR
		} Semantics;

		Attribute();
		Attribute(unsigned int id, std::string name, Enums::DataType type,
			bool readOnlyFlag = false, Data *defaultV = NULL,
			Data *min=NULL, Data *max = NULL,
			IAPISupport::APIFeatureSupport requires = IAPISupport::OK, Semantics sem=NONE);

		Attribute(unsigned int id, std::string name, std::string objType, bool readOnlyFlag = false, bool mustExist = true, std::string default = "");

		~Attribute();

		Attribute(const Attribute & source);

		//Attribute & operator=(const Attribute &rhs);

		static bool isValidUserAttrType(std::string s);
		static std::vector<std::string> &getValidUserAttrTypes();

		std::string &getName();
		Enums::DataType getType();
		int getId();
		bool getRangeDefined();
		bool getReadOnlyFlag();
		Semantics getSemantics();

		std::shared_ptr<Data> &getMax();
		std::shared_ptr<Data> &getMin();
		std::shared_ptr<Data> &getDefault();

		const std::string & getDefaultString();
		bool getMustExist();
		const std::string & getObjType();

		bool getListDefined();
		int getOptionValue(std::string &s);
		std::string &getOptionString(int v);
		const std::vector<std::string> &getOptionStringList();
		void getOptionListSupported(std::vector<int>* result);
		void getOptionStringListSupported(std::vector<std::string> *result);

		void setDefault(Data &);

		void setRequirement(IAPISupport::APIFeatureSupport req);
		IAPISupport::APIFeatureSupport getRequirement();

		void listAdd(std::string name, int id, IAPISupport::APIFeatureSupport requires = IAPISupport::OK);

		// for enum types only. Checks if it is a valid option.
		bool isValid(std::string value);
		bool isValid(int v);

	protected:
		static std::vector<std::string> m_DummyVS;

		int m_Id;
		std::string m_Name;
		std::string m_ObjType;
		std::string m_DefaultS;
		bool m_MustExist;
		Enums::DataType m_Type;
		bool m_ReadOnlyFlag;
		std::shared_ptr<Data> m_Default;
		bool m_ListDefined;
		bool m_RangeDefined;
		std::shared_ptr<Data> m_Min;
		std::shared_ptr<Data> m_Max;

		Semantics m_Semantics;
		IAPISupport::APIFeatureSupport m_Requires;
		std::vector<int> m_ListValues;
		std::vector<IAPISupport::APIFeatureSupport> m_ListRequire;
		std::vector<std::string> m_ListString;
		std::string m_DummyS;
	};

	// -------------------------------------------------------------------------------------------
	//    Attribute Set
	// -------------------------------------------------------------------------------------------

	class AttribSet {

	public:

		static const int USER_ATTRIBS = 1000;
		AttribSet();
		~AttribSet() ;

		unsigned int getNextFreeID();

		void deleteUserAttributes();

		void add(Attribute &a);

		std::map<std::string, std::unique_ptr<Attribute>> &getAttributes();

		int getDataTypeCount(Enums::DataType dt);
		std::unique_ptr<Attribute> &get(std::string name);
		std::unique_ptr<Attribute> &get(int id, Enums::DataType dt);
		// returns the ID of the attribute
		// -1 if attribute does not exist
		int getID(std::string name);
		const std::string &getName(int id, Enums::DataType dt);
		void getPropTypeAndId(const std::string &s, nau::Enums::DataType *dt, int *id);

		const std::vector<std::string> &getListString(int id);
		const std::vector<int> &getListValues(int id);
		std::string getListStringOp(std::string s, int prop);
		std::string getListStringOp(int id, int prop);
		int getListValueOp(std::string s, std::string prop);
		int getListValueOp(int id, std::string prop);
		void listAdd(std::string attrName, std::string elemS, int elem_Id, IAPISupport::APIFeatureSupport requires = IAPISupport::OK);
		bool isValid(std::string attr, std::string value);
		void setDefault(std::string attr, Data &value);
		//std::unique_ptr<Data> &getDefault(int id, Enums::DataType type);

		//template <typename T>
		//void initAttribInstanceArray(Enums::DataType, std::map<int, T> &m);

		void initAttribInstanceIntArray(std::map<int, int> &m);
		void initAttribInstanceInt2Array(std::map<int, ivec2> &m);
		void initAttribInstanceEnumArray(std::map<int, int> &m);
		void initAttribInstanceUIntArray(std::map<int, unsigned int> &m);
		void initAttribInstanceUInt2Array(std::map<int, uivec2> &m);
		void initAttribInstanceUInt3Array(std::map<int, uivec3> &m);
		void initAttribInstanceFloatArray(std::map<int, float> &m);
		void initAttribInstanceVec4Array(std::map<int, vec4> &m);
		void initAttribInstanceVec2Array(std::map<int, vec2> &m);
		void initAttribInstanceVec3Array(std::map<int, vec3> &m);
		void initAttribInstanceMat4Array(std::map<int, mat4> &m);
		void initAttribInstanceMat3Array(std::map<int, mat3> &m);
		void initAttribInstanceBvec4Array(std::map<int, bvec4> &m);
		void initAttribInstanceBoolArray(std::map<int, bool> &m);

	protected:
		std::map<std::string, std::unique_ptr<Attribute>> m_Attributes;
		std::unique_ptr<Attribute> m_Dummy;
		std::string m_DummyS;
		std::vector<std::string> m_DummyVS;
		std::vector<int> m_DummyVI;
		int m_NextFreeID;
		std::map<int, int> mDataTypeCounter;
	};

};

#endif


text:
package iso20022

// Choice of format for the trade date.
type TradeDate3Choice struct {

	// Trade date expressed as an ISO 20022 code.
	Date *ISODate `xml:"Dt"`

	// Date expressed as a code.
	DateCode *DateType1Code `xml:"DtCd"`
}

func (t *TradeDate3Choice) SetDate(value string) {
	t.Date = (*ISODate)(&value)
}

func (t *TradeDate3Choice) SetDateCode(value string) {
	t.DateCode = (*DateType1Code)(&value)
}


text:
layout: post
unique_id: wrong_class
title: Wrong Class
categories: []
locations:
---

TODAY:
* woke up and found a fellow interviewer lost power
  * took on interview at last minute for her
* dumplings for lunch
* made my missing mustaches materialize
* went to my bikram class (haven't gone in a month)
  * apparently they switched the schedue, so I ended up in a "Yoga Sculpt" class
  * my glasses were off and I didn't notice until the instructor asked if we all had our weights
  * good workout anyway :P
* grocery shopping at Ranch 99
  * spent 10 minutes looking for sacha sauce and gave up :(
* baked salmon + veggies + rice + leftover Korean-fried cauliflower for dinner
* did a full db migration to new "schema"
  * added a backend verification test
  * added client-side validation
* fixed a bunch of minor bugs
* screw fell out of my chair
  * toothpick trick to fix!

LEARNINGS:
* _.compact to remove falsy values from an Array
* Keyboard.dismiss to remove focus from a TextInput element


text:
Edge

### Version Introduced
4.5

### Version Reverted
4.5

### Source Analyzer Status
Not planned

### Change Description
In the .NET Framework 4.5, non-pooled SQL connections which are not explicitly exposed (via Dispose, Close, or using) will leak memory

- [ ] Quirked
- [ ] Build-time break

### Recommended Action
This issue is fixed in a .NET Framework 4.5 servicing update. Please update the .NET Framework 4.5, or upgrade to .NET Framework 4.5.1 or later, to fix this issue. Alternatively, this issue may be avoided by using the SqlConnection in a 'using' pattern (which is a best practice) or by explicitly calling Dispose or Close when the connection is no longer needed.

### Affected APIs
* `M:System.Data.SqlClient.SqlConnection.#ctor(System.String)`
* `M:System.Data.SqlClient.SqlConnection.#ctor(System.String,System.Data.SqlClient.SqlCredential)`

### Category
Data

[More information](https://support.microsoft.com/kb/2748720)

<!-- breaking change id: 97 -->


text:
.. CrowData documentation master file, created by
   sphinx-quickstart on Tue May 20 13:43:31 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Crowdsourcing the liberation of data trapped in documents!
==========================================================

``CrowData`` is a tool to collaborate on the verification or release of data that otherwise would be hard or impossible to get via automatic tools.

But the outcome of Crowdata is more than only to extract data. With Crowdata you can work with your community on a data set. They can navigate the data, help to extract it via a game and make comments on information that may be interesting to look at by journalists.

When to use Crowdata?
=====================

.. image:: _static/vozdata.png

* `VozData <http://vozdata.lanacion.com.ar>`_ is a website from `La Nacion <http://www.lanacion.com.ar>`_ in Argentina to convert scanned PDF documents from senate spendings into an usable dataset. `Collaborating to free data from PDFs <http://blogs.lanacion.com.ar/projects/data/vozdata/>`_.

Contents
--------

.. toctree::
   :maxdepth: 2

   technical
   install
   schema
   how to use it

Similar projects
================

Crowdata was inspired by the project from `ProPublica <http://www.propublica.org>`_ called `Free the Files <https://projects.propublica.org/free-the-files/>`_ and The Guardian MP's Expenses and Sarah Palin's Emails.
It was born from a need that La Nacion had to transform scanned image PDFs into a comprehensible and structured dataset, and ask for their community's help to catalog those expenses that call their attention.

Here are some of the projects that do the same for some specific cases.

* `Free the Files <http://www.propublica.org/series/free-the-files>`_
* `Yanukovych Leaks <http://www.yanukovychleaks.org/detail/23570/>`_
* `How to crowdsource MPs' expenses <http://www.theguardian.com/news/datablog/2009/jun/18/mps-expenses-houseofcommons>`_

Credits
=======

'Crowdata' is an open source project that was born when Manuel Aristaran was an Open News fellow at La Nacion in 2013. It was finally released as free software when Gabriela Rodriguez  continued it for VozData in 2014. Thanks to Cristian Bertelegni and La Nacion for contributing to the code.

Now it relies on contributions from people and organizations. Please, use it, comment on it and make improvements by pull requests in `GitHub <http://github.com/crowdata/crowdata>`_.

Contributions
=============

* Fork the repo
* Clone your fork
* Make a branch of your changes
* Make a pull request through GitHub, and clearly describe your changes

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
\echo --start_ignore
set gp_enable_column_oriented_table=on;
\echo --end_ignore
SELECT COUNT(*) FROM dml_co_check_s;
SELECT COUNT(*) FROM (SELECT dml_co_check_s.a, dml_co_check_s.b, 'text', dml_co_check_s.d FROM dml_co_check_r, dml_co_check_s WHERE dml_co_check_r.a = dml_co_check_s.b)foo;
INSERT INTO dml_co_check_s SELECT dml_co_check_s.a, dml_co_check_s.b, 'text', dml_co_check_s.d FROM dml_co_check_r, dml_co_check_s WHERE dml_co_check_r.a = dml_co_check_s.b ;
SELECT COUNT(*) FROM dml_co_check_s;


text:
                        {{ site.title }}

                        Rail Developer - Quick Learner


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Gui;

/**
 *
 * @author tobias
 */
public class SalBinaria extends javax.swing.JFrame {

    /**
     * Creates new form SalBinaria
     */
    public SalBinaria() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel6 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jComboBox1 = new javax.swing.JComboBox<>();
        jLabel2 = new javax.swing.JLabel();
        jComboBox2 = new javax.swing.JComboBox<>();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton2 = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();

        jLabel6.setText("jLabel6");

        getContentPane().setLayout(null);

        jLabel1.setFont(new java.awt.Font("Ubuntu Light", 1, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(254, 254, 254));
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenesq/image3398.png"))); // NOI18N
        jLabel1.setText("Sales Binarias");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(12, 12, 178, 49);
        getContentPane().add(jSeparator1);
        jSeparator1.setBounds(0, 67, 517, 6);

        getContentPane().add(jComboBox1);
        jComboBox1.setBounds(12, 101, 109, 27);

        jLabel2.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(254, 254, 254));
        jLabel2.setText("Hidracidos");
        getContentPane().add(jLabel2);
        jLabel2.setBounds(155, 73, 90, 18);

        getContentPane().add(jComboBox2);
        jComboBox2.setBounds(155, 101, 115, 27);

        jLabel3.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(254, 254, 254));
        jLabel3.setText("+");
        getContentPane().add(jLabel3);
        jLabel3.setBounds(133, 105, 10, 18);

        jLabel4.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(254, 254, 254));
        jLabel4.setText("=");
        getContentPane().add(jLabel4);
        jLabel4.setBounds(288, 105, 9, 18);
        getContentPane().add(jLabel5);
        jLabel5.setBounds(0, 0, 0, 0);
        getContentPane().add(jTextField1);
        jTextField1.setBounds(310, 90, 100, 40);

        jLabel7.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
        jLabel7.setForeground(new java.awt.Color(254, 254, 254));
        jLabel7.setText("hidroxido");
        getContentPane().add(jLabel7);
        jLabel7.setBounds(12, 73, 80, 18);

        jButton1.setText("crear");
        getContentPane().add(jButton1);
        jButton1.setBounds(10, 150, 510, 70);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(12, 228, 505, 90);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenesq/flecharec.png"))); // NOI18N
        jButton2.setText("Menu");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2);
        jButton2.setBounds(379, 16, 132, 42);

        jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenesq/fondo-con-ilustraciones-de-molculas_23-2147491176.jpg"))); // NOI18N
        jLabel8.setText("jLabel8");
        getContentPane().add(jLabel8);
        jLabel8.setBounds(0, 0, 530, 350);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
 VentanaPricipal aux = new VentanaPricipal();
    aux.setVisible(true);
    this.setVisible(false);
    }//GEN-LAST:event_jButton2ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox<String> jComboBox1;
    private javax.swing.JComboBox<String> jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}


text:
"""
File for configuring multiple workers

TODO: FIX ALL THE SQL INJECTIONS. EVERYONE OF THESE THINGS IS FULL OF THEM
"""
import bitHopper.Database.Commands
import bitHopper.Database
import random
workers = None

def __patch():
    global workers
    if workers == None:
        workers = load_from_db()

def load_from_db():
    """
    Load workers from database
    """
    columns = [ 'Server TEXT',
                'Username TEXT',
                'Password TEXT']

    bitHopper.Database.Commands.Create_Table('Workers', columns)
    results = bitHopper.Database.execute('SELECT Server, Username, Password FROM Workers')

    workers = {}

    for server, username, password in results:
        if server not in workers:
            workers[server]  = set()
        workers[server].add((username, password))

    return workers

def len_workers():
    __patch()
    return sum(map(len, workers.values()))

def get_worker_from(pool):
    """
    Returns a list of workers in the given pool
    In the form of [(Username, Password), ... ]
    """
    __patch()
    if pool not in workers:
        return []
    return workers[pool]

def get_single_worker(pool):
    """
    Returns username, password or None, None
    """
    possible = get_worker_from(pool)
    if len(possible) == 0:
        return None, None

    return random.choice(list(possible))

def add(server, username, password):
    """
    Adds a worker into the database and the local cache
    """
    __patch()
    if server not in workers:
        workers[server] = set()
    if (username, password) not in workers[server]:
        workers[server].add((username, password))
        bitHopper.Database.execute("INSERT INTO Workers VALUES ('%s','%s','%s')" % (server, username, password))

def remove(server, username, password):
    """
    Removes a worker from the local cache and the database
    """
    __patch()
    if server not in workers:
        return
    if (username, password) not in workers[server]:
        return
    workers[server].remove((username, password))
    if workers[server] == set([]):
        del workers[server]
    bitHopper.Database.execute("DELETE FROM Workers WHERE Server = '%s' AND Username = '%s' AND Password = '%s'" % (server, username, password))


text:
{% extends "_base.html" %}

{% block title %}Map Reduce for Collection: {{ collection_name }}{% endblock %}

{% block head %}
<link rel="stylesheet" type="text/css" href="/static/s/pygments.css"/>

{% endblock %}

{% block content %}

{{ self.title() }}

Example Record

    {{ example_record|safe }}

Configure Map / Reduce

  <form>
    Map Function
      <textarea>
function() {
   emit(this.foo, 1);
}
      </textarea>

    Reduce Function
      <textarea>
function(key, values) {
    var total = 0;
    for (var i in values) {
        total += values[i];
    }
    return total;
}
      </textarea>

      Auto-clear results
      <input type="checkbox" checked="checked"/>

    <input id="execute" type="submit" class="button" value="Execute"/>
  </form>

Mapping and reducing... this might take a little while.

Please be patient.

{% endblock %}

{% block extra_nav %}

Speed Bar

Count View

Collection View

{% endblock %}

{% block js %}

{% endblock %}


text:
import urllib
import urllib2
import json

class NameServer(object):

    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.address = "http://{}:{}".format(host, port)

    def get_new_connections(self, name):
        req = urllib2.urlopen(self.address + "/connections/new/" + name)
        resp = req.read()
        return json.loads(resp)

    def get_alive(self):
        req = urllib2.urlopen(self.address + "/alive")
        resp = req.read()
        resp_dict = json.loads(resp)
        return resp_dict

    def get_id(self, name):
        req = urllib2.urlopen(self.address + "/id/" + name)
        resp = req.read()
        resp_dict = json.loads(resp)
        robot_id = resp_dict["id"]

        if robot_id is None:
            raise LookupError(
                "Robot name, {}, does not exist in the database".format(name)
            )

        return robot_id

    def get_names(self):
        req = urllib2.urlopen(self.address + "/all")
        resp = req.read()
        bot_names = json.loads(resp)

        return bot_names

    def create_swarm(self, names):
        try:
            post_form = {
                "names": names
            }

            post_str = urllib.urlencode(post_form)
            req = urllib2.Request(self.address + "/swarm/create", post_str)
            resp = urllib2.urlopen(req)
            ret_dict = json.loads(resp.read())

            if not ret_dict["error"] == 0:
                raise Exception(ret_dict["message"])

            return ret_dict["host"], ret_dict["ports"]
        except urllib2.URLError:
            raise Exception("Unable to connect to name server")

    def free_swarm(self, name_port_dicts):
        try:
            post_form = {"swarm": name_port_dicts}
            post_str = urllib.urlencode(post_form)
            req = urllib2.Request(self.address + "/swarm/free", post_str)
            resp = urllib2.urlopen(req)
            ret_dict = json.loads(resp.read())

            if not ret_dict["error"] == 0:
                raise Exception(ret_dict["message"])

            return 0
        except urllib2.URLError:
            return 1


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/C:/Users/apurvak/Downloads/Parse-Starter-Project-1.10.3/ParseStarterProject/build/intermediates/exploded-aar/com.android.support/appcompat-v7/22.2.0/res/values-w500dp/values-w500dp.xml -->
    <eat-comment/>
    <integer name="abc_max_action_buttons">4</integer>
</resources>


text:
package com.amazonaws.services.codepipeline.model.transform;

import static com.amazonaws.util.StringUtils.UTF8;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.codepipeline.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * ExecutionDetailsMarshaller
 */
public class ExecutionDetailsJsonMarshaller {

    /**
     * Marshall the given parameter object, and output to a JSONWriter
     */
    public void marshall(ExecutionDetails executionDetails,
            JSONWriter jsonWriter) {
        if (executionDetails == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        try {
            jsonWriter.object();

            if (executionDetails.getSummary() != null) {
                jsonWriter.key("summary").value(executionDetails.getSummary());
            }

            if (executionDetails.getExternalExecutionId() != null) {
                jsonWriter.key("externalExecutionId").value(
                        executionDetails.getExternalExecutionId());
            }

            if (executionDetails.getPercentComplete() != null) {
                jsonWriter.key("percentComplete").value(
                        executionDetails.getPercentComplete());
            }

            jsonWriter.endObject();
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }
    }

    private static ExecutionDetailsJsonMarshaller instance;

    public static ExecutionDetailsJsonMarshaller getInstance() {
        if (instance == null)
            instance = new ExecutionDetailsJsonMarshaller();
        return instance;
    }

}


text:
  Beaufort-en-Vallée est
      une ville située dans le département de Maine-et-Loire en Pays de la Loire. Elle totalisait 5 754 habitants en 2008.

À Beaufort-en-Vallée, la valeur moyenne à la vente d'un appartement se situe à 1 068 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 476 € du m². À la location la valorisation moyenne se situe à 7,54 € du m² mensuel.

À coté de Beaufort-en-Vallée sont situées les villes de
Le Thoureil localisée à 8 km, 410 habitants,
Saint-Rémy-la-Varenne à 8 km, 998 habitants,
Mazé à 4 km, 4 485 habitants,
La Ménitré située à 5 km, 2 053 habitants,
Gée à 2 km, 328 habitants,
Brion à 4 km, 1 059 habitants,
 entre autres. De plus, Beaufort-en-Vallée est située à seulement 25 km de Angers.

La commune propose de multiples  équipements sportifs, elle propose entre autres un terrain de tennis, quatre terrains de sport, une salle de combat et un équipement de roller/skate.

À Beaufort-en-Vallée le salaire moyen par mois par individu se situe à approximativement 1 808 €  net. C'est au dessous de la moyenne nationale.

Le nombre de logements, à Beaufort-en-Vallée, se décomposait en 2011 en 367 appartements et 2 359 maisons soit
 un marché plutôt équilibré.

La localité est équipée s'agissant de des études de un collège.
Concernant ceux d'entre nous ayant moins de 6 ans, la localité est équipée de une maternelle et trois écoles primaires.
Beaufort-en-Vallée est équipée des  équipements permettant une vie àgréable.
Lors d'un projet de faire une acquisition à Beaufort-en-Vallée, il est intéressant d' regarder la notoriété des équipements éducatifs


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Scheduler extends CI_Controller {

	function __construct() {
		parent::__construct();
		$this->load->helper('url');
		$this->load->helper('security');
		$this->load->library('session');
		$this->load->model('Search_model', 'search_model', true);
		$this->load->model('Profile_model', 'profile_model', true);
		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('
', '
');
	}

	public function index() {
		if (empty($this->session->userdata['email'])) {
			redirect(site_url() . 'login/');
		}
		$data['userdata'] = $this->session->userdata;
		$data['bodyClass'] = "scheduler";
		// Retrieve profile data
		$data['profile'] = $this->db->get_where('users', array('id' => $data['userdata']['id']))->row_array();
		$user_id = $data['profile']['id'];

    if ($data['userdata']['user_type'] == "stylist") {
			$data['profile']['current_stylist'] = $this->profile_model->getCurrentStylist($data['profile']);
			$data['profile']['appointments'] = $this->profile_model->getStylistAppointments($user_id);
			$data['profile']['clients'] = $this->profile_model->getStylistClients($user_id);
      $data['view'] = "scheduler/schedule";
      $this->load->view("template", $data);
    } else {
      redirect(site_url() . 'login');
    }
	}

	public function appointment() {
		$data['userdata'] = $this->session->userdata;
		$data['bodyClass'] = "appointment-details";
		$appointment_id = $this->uri->segment(3);
		$user_id = $data['userdata']['id'];
		$query = $this->profile_model->getAppointmentDetails($appointment_id);
		if ($query) {
			$data['appointment'] = $query;
		} else {
			$data['appointment'] = false;
		}
		if ($data['userdata']['user_type'] == "stylist") {
			$data['view'] = "scheduler/appointment-details";
			$this->load->view("template", $data);
		} else {
			redirect(site_url() . 'login');
		}
	}

	public function getStylistBookingServices(){
		$user_type = xss_clean($this->input->post('user_type'));
		$profile_id = xss_clean($this->input->post('lookupID'));
		if($user_type == "stylist"){
			$fetched_services = $this->profile_model->getStylistBookingServices($profile_id);
		}else{
			$fetched_services = false;
		}
		$success_msg = "Success, stylist booking services data retrieved.";
		$error_msg = "Unable to fetch stylist booking services data";
		$response = generateApiResponse($fetched_services, $success_msg, $error_msg);
		$this->output->set_status_header($response['status_header']);
		echo encodedResponse($response);
	}

	public function updateAppointmentStatus() {
		$appointment = xss_clean($this->input->post("appointment"));
		$appointment_update = $this->profile_model->updateAppointmentStatus($appointment);
		$success_msg = "Success, appointment status updated.";
		$error_msg = "Unable to update appointment status";
		$response = generateApiResponse($appointment_update, $success_msg, $error_msg);
		$this->output->set_status_header($response['status_header']);
		echo encodedResponse($response);
	}

	public function bookNextAppointment() {
		$appointment = xss_clean($this->input->post("appointment"));
		$appointment_insert = $this->profile_model->bookNextAppointment($appointment);
		$success_msg = "Success, next appointment booked";
		$error_msg = "Unable to make next appointment booking";
		$response = generateApiResponse($appointment_insert, $success_msg, $error_msg);
		$this->output->set_status_header($response['status_header']);
		echo encodedResponse($response);
	}

}


text:
/*
 * ----------------------------------------
 *      Nutrient Usage Tracking System
 * ----------------------------------------
 *          Produced by Dan Grew
 *                 2017
 * ----------------------------------------
 */
package uk.dangrew.nuts.meal;

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.MapChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import uk.dangrew.kode.observable.FunctionListChangeListenerImpl;
import uk.dangrew.nuts.food.Food;
import uk.dangrew.nuts.food.FoodItem;
import uk.dangrew.nuts.food.FoodPortion;

/**
 * {@link StockUsage} provides a map of {@link FoodItem}s to the percentage of stock the use, associated with
 * set of {@link FoodPortion}s.
 */
public class StockUsage {

   private final ObservableMap< FoodItem, Double > stockPortionUsed;
   private final ObservableMap< FoodItem, Double > totalWeightUsed;

   private final Map< FoodItem, Double > stockPortionUsedConstruction;
   private final Map< FoodItem, Double > totalWeightUsedConstruction;

   private final MapChangeListener< FoodItem, Double > subStockChangeListener;
   private final Set< Meal > subStockRegistrations;
   private final ChangeListener< Object > propertyListener;
   private final Set< ObservableValue< ? > > propertyRegistrations;

   private ObservableList< FoodPortion > portions;

   /**
    * Constructs a new {@link StockUsage}.
    */
   public StockUsage() {
      this.stockPortionUsed = FXCollections.observableHashMap();
      this.totalWeightUsed = FXCollections.observableHashMap();
      this.stockPortionUsedConstruction = new LinkedHashMap<>();
      this.totalWeightUsedConstruction = new LinkedHashMap<>();

      this.subStockChangeListener = c -> recalculateStock();
      this.subStockRegistrations = new HashSet<>();
      this.propertyListener = ( s, o, n ) -> recalculateStock();
      this.propertyRegistrations = new HashSet<>();
   }//End Constructor

   /**
    * Associates with the given {@link FoodPortion}s.
    * @param portions the {@link ObservableList}.
    */
   public void associate( ObservableList< FoodPortion > portions ) {
      if ( this.portions != null ) {
         throw new IllegalStateException( "Already associated." );
      }

      this.portions = portions;
      this.recalculateStock();
      this.portions.addListener( new FunctionListChangeListenerImpl<>(
               p -> this.recalculateStock(), p -> this.recalculateStock()
      ) );
   }//End Method

   /**
    * Access to the stock structure, no modification allowed.
    * @return the {@link ObservableMap}.
    */
   public ObservableMap< FoodItem, Double > stockPortionUsed() {
      return stockPortionUsed;
   }//End Method

   /**
    * Access to the total weight of stock used, no modification allowed.
    * @return the {@link ObservableMap}.
    */
   public ObservableMap< FoodItem, Double > totalWeightUsed() {
      return totalWeightUsed;
   }//End Method

   /**
    * Method to do a blanket recalculation.
    */
   private void recalculateStock(){
      this.stockPortionUsedConstruction.clear();
      this.totalWeightUsedConstruction.clear();
      this.subStockRegistrations.forEach( m -> m.stockUsage().stockPortionUsed().removeListener( subStockChangeListener ) );
      this.propertyRegistrations.forEach( p -> p.removeListener( propertyListener ) );
      this.portions.forEach( this::updateFoodItemPortion );
      this.updateMapFromCalculations( totalWeightUsed, totalWeightUsedConstruction );
      this.updateMapFromCalculations( stockPortionUsed, stockPortionUsedConstruction );
   }//End Method

   /**
    * Method to update the given data {@link Map} from the construction {@link Map}. This is resolve multiple unnecessary
    * notifications of changes to the {@link ObservableMap}.
    * @param dataMap the {@link Map} providing the notifications.
    * @param calculationMap the {@link Map} providing the information to populate to the data map.
    */
   private void updateMapFromCalculations( Map< FoodItem, Double > dataMap, Map< FoodItem, Double > calculationMap ){
      Set< FoodItem > previousKeys = new LinkedHashSet<>( dataMap.keySet() );
      for ( FoodItem item : previousKeys ) {
         if ( !calculationMap.containsKey( item ) || calculationMap.get( item ) == 0.0 ) {
            dataMap.remove( item );
         }
      }

      dataMap.putAll( calculationMap );
   }//End Method

   /**
    * Method to update the stock for the given {@link FoodPortion}.
    * @param portion the {@link FoodPortion}.
    */
   private void updateFoodItemPortion( FoodPortion portion ) {
      portion.food().addListener( propertyListener );
      propertyRegistrations.add( portion.food() );
      portion.portion().addListener( propertyListener );
      propertyRegistrations.add( portion.portion() );

      Food food = portion.food().get();
      if ( food == null ){
         return;
      } else if ( food instanceof FoodItem ) {
         FoodItem item = ( FoodItem )food;
         updateFoodItemPortion( item, portion.portion().get() );
      } else if ( food instanceof Meal ) {
         Meal meal = ( Meal )food;
         updateMealPortion( meal, portion.portion().get() );
      }
   }//End Method

   /**
    * Method to update the stock for the given {@link FoodItem} and how much of it is consumed.
    * @param item the {@link FoodItem} being used.
    * @param portion the amount of the logged weight used.
    */
   private void updateFoodItemPortion( FoodItem item, double portion ) {
      item.stockProperties().loggedWeight().addListener( propertyListener );
      propertyRegistrations.add( item.stockProperties().loggedWeight() );
      item.stockProperties().soldInWeight().addListener( propertyListener );
      propertyRegistrations.add( item.stockProperties().soldInWeight() );

      double totalPortionUsed = item.stockProperties().loggedWeight().get() * portion;
      double totalWeightUsedValue = totalPortionUsed / 100;
      double stockUsage = totalPortionUsed / item.stockProperties().soldInWeight().get();

      putValue( stockPortionUsedConstruction, item, stockUsage );
      putValue( totalWeightUsedConstruction, item, totalWeightUsedValue );
   }//End Method

   /**
    * Method to put the {@link FoodItem} addition into the {@link Map}.
    * @param map the {@link Map} to update.
    * @param item the {@link FoodItem} to add.
    * @param addition the amount to add for the {@link FoodItem}.
    */
   private void putValue( Map< FoodItem, Double > map, FoodItem item, Double addition ) {
      Double value = map.get( item );
      if ( value == null ) {
         value = 0.0;
      }
      map.put( item, value + addition );
   }//End Method

   /**
    * Method to update the stock for the given {@link Meal} and how much of it is consumed.
    * @param item the {@link Meal} being used.
    * @param portion the amount of the logged weight used.
    */
   private void updateMealPortion( Meal meal, double portion ) {
      meal.stockUsage().stockPortionUsed().addListener( subStockChangeListener );
      subStockRegistrations.add( meal );

      meal.stockUsage().stockPortionUsed().forEach( ( item, usage ) -> {
         double additionalUsage = usage * ( portion / 100.0 );
         double additionalWeight = ( additionalUsage / 100.0 ) * item.stockProperties().soldInWeight().get();
         putValue( stockPortionUsedConstruction, item, additionalUsage );
         putValue( totalWeightUsedConstruction, item, additionalWeight );
      } );
   }//End Method

}//End Class


text:
package retrofit;

import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Element;

@Default(value = DefaultType.FIELD)
final class MyObject {
  @Element private String message;
  @Element private int count;

  public MyObject() {
  }

  public MyObject(String message, int count) {
    this.message = message;
    this.count = count;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public String getMessage() {
    return message;
  }

  public void setCount(int count) {
    this.count = count;
  }

  public int getCount() {
    return count;
  }

  @Override public int hashCode() {
    int result = 1;
    result = result * 31 + count;
    result = result * 31 + (message == null ? 0 : message.hashCode());
    return result;
  }

  @Override public boolean equals(Object obj) {
    if (obj == this) return true;
    if (!(obj instanceof MyObject)) return false;
    MyObject other = (MyObject) obj;
    return count == other.count
        && (message == null ? other.message == null : message.equals(other.message));
  }
}


text:
struct OmniboxPopupSelection {
  // Directions for stepping through selections. These may apply for going
  // up/down by lines or cycling left/right through states within a line.
  enum Direction { kForward, kBackward };

  // When changing selections, these are the possible stepping behaviors.
  enum Step {
    // Step by an entire line regardless of line state. Usually used for the
    // Up and Down arrow keys.
    kWholeLine,

    // Step by a state if another one is available on the current line;
    // otherwise step by line. Usually used for the Tab and Shift+Tab keys.
    kStateOrLine,

    // Step across all lines to the first or last line. Usually used for the
    // PgUp and PgDn keys.
    kAllLines
  };

  // See `Selection::state` below for details. The numeric values are to aid
  // comparison only. They are not persisted anywhere and can be freely changed.
  enum LineState {
    // This means the Header above this row is highlighted, and the
    // header collapse/expand button is focused.
    FOCUSED_BUTTON_HEADER = 0,

    // NORMAL means the row is focused, and Enter key navigates to the match.
    NORMAL = 1,

    // KEYWORD_MODE state is used when in Keyword mode.  If the keyword search
    // button is enabled, keyword mode is entered when the keyword button is
    // focused.
    KEYWORD_MODE = 2,

    // FOCUSED_BUTTON_TAB_SWITCH state means the Switch Tab button is focused.
    // Pressing enter will switch to the tab match.
    FOCUSED_BUTTON_TAB_SWITCH = 3,

    // FOCUSED_BUTTON_ACTION state means an Action button (such as a Pedal)
    // is in focus.
    FOCUSED_BUTTON_ACTION = 4,

    // FOCUSED_BUTTON_REMOVE_SUGGESTION state means the Remove Suggestion (X)
    // button is focused. Pressing enter will attempt to remove this suggestion.
    FOCUSED_BUTTON_REMOVE_SUGGESTION = 5,

    // Whenever new line state is added, accessibility label for current
    // selection should be revisited
    // (OmniboxEditModel::GetAccessibilityLabelForCurrentSelection).
    LINE_STATE_MAX_VALUE
  };

  // The sentinel value for Selection::line which means no line is selected.
  static const size_t kNoMatch;

  // The selected line.  This is kNoMatch when nothing is selected,
  // which should only be true when the popup is closed.
  size_t line;

  // If the selected line has both a normal match and a keyword match, this
  // determines whether the normal match (if NORMAL) or the keyword match
  // (if KEYWORD) is selected. Likewise, if the selected line has a normal
  // match and a secondary button match, this determines whether the button
  // match (if FOCUSED_BUTTON_*) is selected.
  LineState state;

  explicit OmniboxPopupSelection(size_t line, LineState state = NORMAL)
      : line(line), state(state) {}

  bool operator==(const OmniboxPopupSelection&) const;
  bool operator!=(const OmniboxPopupSelection&) const;
  bool operator<(const OmniboxPopupSelection&) const;

  // Returns true if going to this selection from given `from` selection
  // results in activation of keyword state when it wasn't active before.
  bool IsChangeToKeyword(OmniboxPopupSelection from) const;

  // Returns true if this selection represents a button being focused.
  bool IsButtonFocused() const;

  // Returns true if the control represented by this selection's `state` is
  // present on the match for `line` in given `result`.
  bool IsControlPresentOnMatch(const AutocompleteResult& result,
                               PrefService* pref_service) const;

  // Returns the next selection after this one in given `result`.
  OmniboxPopupSelection GetNextSelection(const AutocompleteResult& result,
                                         PrefService* pref_service,
                                         Direction direction,
                                         Step step) const;

 private:
  // This is a utility function to support `GetNextSelection`.
  static std::vector<OmniboxPopupSelection> GetAllAvailableSelectionsSorted(
      const AutocompleteResult& result,
      PrefService* pref_service,
      Direction direction,
      Step step);
};

#endif  // COMPONENTS_OMNIBOX_BROWSER_OMNIBOX_POPUP_SELECTION_H_