text:
/**
 * Created by Fine on 2016/12/4.
 */

var crossTable = {
    table: function (args) {
        var data = args.data,
            chartConfig = args.chartConfig,
            tall = args.tall,
            pageDataNum = 20,
            drill = args.drill,
            random = Math.random().toString(36).substring(2),
            container = args.container;
        var html = "

",
            colContent = "
";
        for (var i = 0; i < chartConfig.groups.length; i++) {
            var groupId = chartConfig.groups[i].id;
            var colspan = 1;
            var colList = [];
            for (var t = 0; t < chartConfig.keys.length; t++) {
                colContent += "

	";
            }
            for (var y = chartConfig.keys.length; y < data[i].length; y++) {
                if ((data[i][y + 1]) && (data[i][y].data == data[i][y + 1].data)) {
                    if (i > 0) {
                        var noEqual = false;
                        for (var s = i - 1; s > -1; s--) {
                            if (data[s][y].data != data[s][y + 1].data) {
                                noEqual = true;
                                break;
                            }
                        }
                        if (noEqual) {
                            colList.push({
                                data: data[i][y].data,
                                colSpan: colspan,
                                property: data[i][y].property
                            });
                            colspan = 1;
                        }
                        else {
                            colspan++;
                        }
                    }
                    else if (i == 0) {
                        colspan++;
                    }
                }
                else {
                    data[i][y] != data[i][y - 1] ? colList.push({
                        data: data[i][y].data,
                        colSpan: colspan,
                        property: data[i][y].property
                    }) : null;
                    colspan = 1;
                }
            }
            for (var c = 0; c < colList.length; c++) {
                var d = ""
                if (drill && drill.config[groupId] && (drill.config[groupId].down || drill.config[groupId].up)) {
                    d += "class='table_drill_cell'";
                    if (drill.config[groupId].down) {
                        d += " drill-down='" + groupId + "' ";
                    }
                    if (drill.config[groupId].up) {
                        d += " drill-up='" + groupId + "' ";
                    }
                }
                var value = "
" + colList[c].data + "
";
                colContent += colList[c].colSpan > 1 ? "" + value + "	" :
                    "" + value + "	";
            }
            colContent += "

";
        }
        for (var k = 0; k < data[chartConfig.groups.length].length; k++) {
            colContent += "
" + data[chartConfig.groups.length][k].data + "
	";
        }
        html += colContent + "

";
        var headerLines = chartConfig.groups.length + 1;
        var dataPage = this.paginationProcessData(data, headerLines, pageDataNum);
        var colNum = data[0].length;
        var rowNum = colNum ? data.length - headerLines : 0;
        var trDom = this.render(dataPage[0], chartConfig, drill);
        html = html + trDom + "

";
        var optionDom = "<select><option value='20'>20</option><option value='50'>50</option><option value='100'>100</option><option value='150'>150</option></select>";
        var p_class = "p_" + random;
        var PaginationDom = "

Show" + optionDom + "entries

";
        var operate = "
info: " + rowNum + " x " + colNum + "" +
            "
";
        $(container).html(operate);
        $(container).append("
" + html + "
");
        $(container).append(PaginationDom);
        var pageObj = {
            data: dataPage,
            chartConfig: chartConfig,
            drill: drill
        };
        data.length ? this.renderPagination(dataPage.length, 1, pageObj, $('.' + p_class + ' .page>ul')[0]) : null;
        this.clickPageNum(dataPage, chartConfig, drill, p_class);
        this.clickNextPrev(dataPage.length, pageObj, p_class);
        this.selectDataNum(data, chartConfig.groups.length + 1, chartConfig, drill, p_class);
        this.export(random, data);
        this.clickDrill("table_" + random, drill, args.render);
    },
    clickDrill: function (t_class, drill, render) {
        $('.' + t_class + ' .table_drill_cell[drill-down]').click(function(){
            var down = $(this).attr('drill-down');
            var value = $(this).html();
            drill.drillDown(down, value, render);
        });
        $.contextMenu({
            selector: '.' + t_class + ' .table_drill_cell',
            build: function ($trigger, e) {
                var down = $trigger.attr('drill-down');
                var up = $trigger.attr('drill-up');
                var value = $trigger.html();
                var items = {};
                if (up) {
                    items.up = {name: cboardTranslate("COMMON.ROLL_UP"), icon: "fa-arrow-up"}
                }
                if (down) {
                    items.down = {name: cboardTranslate("COMMON.DRILL_DOWN"), icon: "fa-arrow-down"}
                }
                return {
                    callback: function (key, options) {
                        if ('up' == key) {
                            drill.drillUp(up, render);
                        } else if ('down' == key) {
                            drill.drillDown(down, value, render);
                        }
                    },
                    items: items
                };
            }
        });

    },
    paginationProcessData: function (rawData, headerLines, pageSize) {
        var dataLength = rawData.length - headerLines;
        var lastPageLines = dataLength % pageSize;
        var fullSizePages = parseInt(dataLength / pageSize);
        var totalPages;
        lastPageLines == 0 ? totalPages = fullSizePages : totalPages = fullSizePages + 1;
        var pageData = [];
        for (var currentPage = 1; currentPage < totalPages + 1; currentPage++) {
            var startRow = (currentPage - 1) * pageSize + headerLines;
            var partData = rawData.slice(startRow, startRow + pageSize);
            pageData.push(partData);
        }
        return pageData;
    },
    render: function (data, chartConfig, drill) {
        var html = '';
        if (data === undefined) {
            return html;
        }
        for (var r = 0; r < chartConfig.keys.length; r++) {
            for (var n = 1; n < data.length; n++) {
                var node = data[n][r].data;
                if (r > 0) {
                    var parent = data[n][r - 1].data;
                    var next;
                    n > 0 ? next = data[n - 1][r - 1].data : null;
                    (node == data[n - 1][r].data && parent == next) ? data[n][r] = {
                        data: data[n][r].data,
                        rowSpan: 'row_null',
                        property: data[n][r].property
                    } : data[n][r] = {
                        data: data[n][r].data,
                        rowSpan: 'row',
                        property: data[n][r].property
                    };
                }
                else if (r == 0) {
                    var preNode = n > 0 ? data[n - 1][r].data : null;
                    (node == preNode) ? data[n][r] = {
                        data: data[n][r].data,
                        rowSpan: 'row_null',
                        property: data[n][r].property
                    } : data[n][r] = {
                        data: data[n][r].data,
                        rowSpan: 'row',
                        property: data[n][r].property
                    };
                }
            }
        }
        for (var n = 0; n < data.length; n++) {
            var rowContent = "
";
            var isFirstLine = (n == 0) ? true : false;
            for (var m = 0; m < chartConfig.keys.length; m++) {
                var currentCell = data[n][m];
                var rowParentCell = data[n][m - 1];
                var cur_data = currentCell.data ? currentCell.data : "";
                var keyId = chartConfig.keys[m].id;
                var align = chartConfig.keys[m].align;
                if (drill && drill.config[keyId] && (drill.config[keyId].down || drill.config[keyId].up)) {
                    var d = "";
                    if (drill.config[keyId].down) {
                        d += " drill-down='" + keyId + "' ";
                    }
                    if (drill.config[keyId].up) {
                        d += " drill-up='" + keyId + "' ";
                    }
                    cur_data = "
" + cur_data + "
";
                }
                if (m > 0) {
                    if (currentCell.rowSpan == 'row_null' && rowParentCell.rowSpan == 'row_null' && !isFirstLine) {
                        rowContent += "

	";
                    } else {
                        rowContent += "
" + cur_data + "
	";
                    }
                } else {
                    if (currentCell.rowSpan == 'row_null' && !isFirstLine) {
                        rowContent += "

	";
                    } else {
                        rowContent += "
" + cur_data + "
	";
                    }
                }
            }
            for (var y = chartConfig.keys.length; y < data[n].length; y++) {
                var align = chartConfig.values[0].cols[(y-chartConfig.keys.length)%chartConfig.values[0].cols.length].align;
                rowContent += "
" + data[n][y].data + "
	";
            }
            html = html + rowContent + "
";
        }
        return html;
    },
    selectDataNum: function (data, num, chartConfig, drill, random) {
        var _this = this;
        $('.' + random).on('change', '.optionNum select', function (e) {
            var pageDataNum = e.target.value;
            var dataPage = _this.paginationProcessData(data, num, pageDataNum);

            var dom = $(e.target.offsetParent).find('.page>ul')[0];
            var tbody = $(e.target.offsetParent).find('tbody')[0];
            tbody.innerHTML = (_this.render(dataPage[0], chartConfig, drill));
            _this.renderPagination(dataPage.length, 1, null, dom);
            $('.' + random).off('click');
            _this.clickPageNum(dataPage, chartConfig, random);
            var pageObj = {
                data: dataPage,
                chartConfig: chartConfig,
                drill: drill
            };
            _this.clickNextPrev(dataPage.length, pageObj, random);
        });
    },
    clickPageNum: function (data, chartConfig, drill, random) {
        var _this = this;
        $('.' + random).on('click', 'a.pageLink', function (e) {
            var pageNum = e.target.innerText - 1;
            var pageObj = {
                data: data,
                chartConfig: chartConfig,
                drill: drill
            };

            var dom = $(e.target.offsetParent).find('.page>ul')[0];
            var tbody = $(e.target.offsetParent).find('tbody')[0];
            tbody.innerHTML = _this.render(data[pageNum], chartConfig, drill);
            _this.renderPagination(data.length, parseInt(e.target.innerText), pageObj, dom);
        });
    },
    renderPagination: function (pageCount, pageNumber, pageObj, target) {
        var liStr = '
Preview
';
        if (pageCount < 10) {
            for (var a = 0; a < pageCount; a++) {
                liStr += '
' + (a + 1) + '
';
            }
        }
        else {
            if (pageNumber < 6) {
                for (var a = 0; a < pageNumber + 2; a++) {
                    liStr += '
' + (a + 1) + '
';
                }
                liStr += '
...
';
                for (var i = pageCount - 2; i < pageCount; i++) {
                    liStr += '
' + (i + 1) + '
';
                }
            } else if (pageNumber <= (pageCount - 5)) {
                for (var c = 0; c < 2; c++) {
                    liStr += '
' + (c + 1) + '
';
                }
                liStr += '
...
';
                for (var j = pageNumber - 2; j < pageNumber + 3; j++) {
                    liStr += '
' + j + '
';
                }
                liStr += '
...
';
                for (var i = pageCount - 2; i < pageCount; i++) {
                    liStr += '
' + (i + 1) + '
';
                }
            } else {
                for (var c = 0; c < 2; c++) {
                    liStr += '
' + (c + 1) + '
';
                }
                liStr += '
...
';
                for (var i = pageNumber - 2; i < pageCount + 1; i++) {
                    liStr += '
' + i + '
';
                }
            }
        }
        liStr += '
Next
';
        if (target) {
            target.innerHTML = liStr;
            if (pageNumber == 1) {
                target.childNodes[0].setAttribute('class', 'hide');
            } else if (pageNumber == pageCount) {
                target.childNodes[target.childNodes.length - 1].setAttribute('class', 'hide');
            }
            this.buttonColor(pageNumber, target);
        }
        // else {
        //     $('.page>ul').html(liStr);
        //     if (pageNumber == 1) {
        //         $('.page a.previewLink').addClass('hide');
        //     } else if (pageNumber == pageCount) {
        //         $('.page a.nextLink').addClass('hide');
        //     }
        //     this.buttonColor(pageNumber);
        //     this.clickNextPrev(pageCount, pageObj);
        // }
    },
    buttonColor: function (pageNum, target) {
        if (target) {
            var buttons = target.childNodes;
            for (var i = 0; i < buttons.length; i++) {
                buttons[i].childNodes[0].innerText == pageNum ? $(buttons[i].childNodes[0]).addClass('current') : null;
            }
        }
    },
    clickNextPrev: function (pageCount, pageObj, random) {
        var _this = this;
        $('.' + random).on('click', '.page a.previewLink', function (e) {
            var kids = e.target.parentNode.parentNode.childNodes;
            var dom = e.target.parentNode.parentNode.parentNode.childNodes[0];
            var tbody = $(e.target.offsetParent).find('tbody')[0];

            for (var i = 0; i < kids.length; i++) {
                if (kids[i].childNodes[0].className.indexOf('current') > -1) {
                    var pageNum = parseInt(kids[i].childNodes[0].text) - 1;
                }
            }
            tbody.innerHTML = _this.render(pageObj.data[pageNum - 1], pageObj.chartConfig, pageObj.drill);
            _this.renderPagination(pageCount, pageNum, pageObj, dom);
            //_this.clickPageNum(pageObj.data, pageObj.chartConfig);
        });
        $('.' + random).on('click', '.page a.nextLink', function (e) {
            var kids = e.target.parentNode.parentNode.childNodes;
            var dom = e.target.parentNode.parentNode.parentNode.childNodes[0];
            var tbody = $(e.target.offsetParent).find('tbody')[0];

            for (var i = 0; i < kids.length; i++) {
                if (kids[i].childNodes[0].className.indexOf('current') > -1) {
                    var pageNum = parseInt(kids[i].childNodes[0].text) + 1;
                }
            }
            tbody.innerHTML = _this.render(pageObj.data[pageNum - 1], pageObj.chartConfig, pageObj.drill);
            _this.renderPagination(pageCount, pageNum, pageObj, dom);
            //_this.clickPageNum(pageObj.data, pageObj.chartConfig);
        });
    },
    export: function (random, data) {
        $(".toolbar" + random + " .exportBnt").on('click', function () {
            var xhr = new XMLHttpRequest();
            var formData = new FormData();
            formData.append('data', JSON.stringify({data: data, type: 'table'}));
            xhr.open('POST', 'dashboard/tableToxls.do');
            xhr.responseType = 'arraybuffer';
            xhr.onload = function (e) {
                var blob = new Blob([this.response], {type: "application/vnd.ms-excel"});
                var objectUrl = URL.createObjectURL(blob);
                var aForExcel = $("下载excel").attr("href", objectUrl);
                aForExcel.attr("download", "table.xls");
                $("body").append(aForExcel);
                $(".forExcel").click();
                aForExcel.remove();
            };
            xhr.send(formData);
        });

    }
};


text:
(function(){'use strict';

    var TwitterStrategy  = require('passport-twitter').Strategy;

    module.exports = function(passport, config) {

        passport.serializeUser(function(user, done) {
            done(null, user);
        });
        passport.deserializeUser(function(obj, done) {
            done(null, obj);
        });

        passport.use(new TwitterStrategy({
                consumerKey : config.auth.twitterAuth.consumerKey,
                consumerSecret : config.auth.twitterAuth.consumerSecret,
                callbackURL: config.auth.twitterAuth.callbackURL
            }, function(token, tokenSecret, profile, done) {
                // To keep the example simple, the user's Twitter profile is returned to
                // represent the logged-in user. In a typical application, you would want
                // to associate the Twitter account with a user record in your database,
                // and return that user instead.
                profile.twitter_token = token;
                profile.twitter_token_secret = tokenSecret;
                //console.log(JSON.stringify(profile, null, 4));
                done(null,profile);
            }
        ));
};
})();

redpajama_set_name: RedPajamaGithub


text:
<?php require_once('Connections/MySQL.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
    if (PHP_VERSION < 6) {
          $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
    }
    $theValue = function_exists("mysqli_real_escape_string") ? mysqli_real_escape_string(dbconnect(), $theValue) : mysqli_escape_string(dbconnect(), $theValue);
    switch ($theType) {
          case "text":
            $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
            break;
          case "long":
          case "int":
            $theValue = ($theValue != "") ? intval($theValue) : "NULL";
            break;
          case "double":
            $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
            break;
          case "date":
            $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
            break;
          case "defined":
            $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
            break;
    }
    return $theValue;
  }
}
?>

<?php
// *** Validate request to login to this site.
if (!isset($_SESSION)) {
  session_start();
}

$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
  $_SESSION['PrevUrl'] = $_GET['accesscheck'];
}

if (isset($_POST['dni'])) {
  $loginUsername=$_POST['dni'];
  $MM_fldUserAuthorization = "";
  //$MM_redirectLoginSuccess = "Carga1.php";

  //mysql_select_db($database_MySQL, $MySQL);

  $LoginRS__query=sprintf("SELECT idAlumno, DNI FROM alumnos WHERE DNI=%s",
        GetSQLValueString($loginUsername, "int"));

  $LoginRS = mysqli_query(dbconnect(),$LoginRS__query) or die(mysql_error());
  $row_Recordset1 = mysqli_fetch_assoc($LoginRS);
  $loginFoundUser = mysqli_num_rows($LoginRS);
  if ($loginFoundUser) {

  	if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();}
      //declare two session variables and assign them
      // $_SESSION['MM_Username'] = $row_Recordset1['idAlumno'];
      // $_SESSION['MM_UserGroup'] = $loginStrGroup;
      $caca = $row_Recordset1['idAlumno'];
      $MM_redirectLoginSuccess = "AltaFechaFirma.php?id=$caca";
      $MM_redirectLoginFailed = "Failure.php";
      $MM_redirecttoReferrer = false;

      if (isset($_SESSION['PrevUrl']) && false) {
        $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];
      }
      header("Location: " . $MM_redirectLoginSuccess );
  }
  else {
    header("Location: ". $MM_redirectLoginFailed );
  }
}
?>

 IFTS18 - Seleccione alumno para ingresar fechas de firma

      <form name="form1" method="POST" action="<?php echo $loginFormAction; ?>">

              Ingrese DNI :
              <input name="dni" type="text" required="required" id="dni">

              <input type="submit" name="Enviar" id="enviar" value="Enviar">

      </form>


text:
module Opal
  class SourceMapServer
    # Carelessly taken from Sprockets::Caching (Sprockets v2)
    class Cache
      def initialize
        @cache = {}
      end

      attr_reader :cache

      def cache_get(key)
        # `Cache#get(key)` for Memcache
        if cache.respond_to?(:get)
          cache.get(key)

        # `Cache#[key]` so `Hash` can be used
        elsif cache.respond_to?(:[])
          cache[key]

        # `Cache#read(key)` for `ActiveSupport::Cache` support
        elsif cache.respond_to?(:read)
          cache.read(key)

        else
          nil
        end
      end

      def cache_set(key, value)
        # `Cache#set(key, value)` for Memcache
        if cache.respond_to?(:set)
          cache.set(key, value)

        # `Cache#[key]=value` so `Hash` can be used
        elsif cache.respond_to?(:[]=)
          cache[key] = value

        # `Cache#write(key, value)` for `ActiveSupport::Cache` support
        elsif cache.respond_to?(:write)
          cache.write(key, value)
        end

        value
      end
    end

    def self.get_map_cache(sprockets, logical_path)
      logical_path = logical_path.gsub(/\.js#{REGEXP_END}/, '')
      cache_key = cache_key_for_path(logical_path+'.map')
      cache(sprockets).cache_get(cache_key)
    end

    def self.set_map_cache(sprockets, logical_path, map_contents)
      logical_path = logical_path.gsub(/\.js#{REGEXP_END}/, '')
      cache_key = cache_key_for_path(logical_path+'.map')
      cache(sprockets).cache_set(cache_key, map_contents)
    end

    def self.cache(sprockets)
      @cache ||= sprockets.cache ? sprockets : Cache.new
    end

    def self.cache_key_for_path(logical_path)
      base_name = logical_path.gsub(/\.js#{REGEXP_END}/, '')
      File.join('opal', 'source_maps', base_name)
    end

    def initialize sprockets, prefix = '/'
      @sprockets = sprockets
      @prefix = prefix
    end

    attr_reader :sprockets, :prefix

    def inspect
      "#<#{self.class}:#{object_id}>"
    end

    def call(env)
      prefix_regex = %r{^(?:#{prefix}/|/)}
      path_info = env['PATH_INFO'].to_s.sub(prefix_regex, '')

      case path_info
      when %r{^(.*)\.self\.map$}
        path = $1
        asset  = sprockets[path]
        return not_found(path) if asset.nil?

        # "logical_name" of a BundledAsset keeps the .js extension
        source = SourceMapServer.get_map_cache(sprockets, asset.logical_path)
        return not_found(asset) if source.nil?

        map = JSON.parse(source)
        map['sources'] = map['sources'].map {|s| "#{prefix}/#{s}"}
        source = map.to_json

        return [200, {"Content-Type" => "text/json"}, [source.to_s]]
      when %r{^(.*)\.rb$}
        begin
          asset = sprockets.resolve(path_info.sub(/\.rb#{REGEXP_END}/,''))
        rescue Sprockets::FileNotFound
          return not_found(path_info)
        end
        return [200, {"Content-Type" => "text/ruby"}, [Pathname(asset).read]]
      else
        not_found(path_info)
      end
    end

    def not_found(*messages)
      not_found = [404, {}, [{not_found: messages}.inspect]]
    end
  end
end


text:
function Resolve-ProjectName {
    param(
        [parameter(ValueFromPipelineByPropertyName = $true)]
        [string[]]$ProjectName
    )

    if($ProjectName) {
        $projects = Get-Project $ProjectName
    }
    else {
        # All projects by default
        $projects = Get-Project
    }

    $projects
}

function Get-MSBuildProject {
    param(
        [parameter(ValueFromPipelineByPropertyName = $true)]
        [string[]]$ProjectName
    )
    Process {
        (Resolve-ProjectName $ProjectName) | % {
            $path = $_.FullName
            @([Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($path))[0]
        }
    }
}

function Install-CleanReferencesTarget()
{
    $buildProject = Get-MSBuildProject

    if ($buildProject.Xml.Targets | Where-Object { "CleanReferenceCopyLocalPaths" -contains $_.Name })
    {
        Write-Host "Target CleanReferenceCopyLocalPaths already exists." -foregroundcolor Black -backgroundcolor Yellow

        return
    }

    $usingTask = $buildProject.Xml.AddUsingTask("CosturaCleanup", "`$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll", "")
	$usingTask.TaskFactory = "CodeTaskFactory"
    $parameterGroup = $usingTask.AddParameterGroup()
    $configParam = $parameterGroup.AddParameter("Config", "false", "true", "Microsoft.Build.Framework.ITaskItem")
    $filesParam = $parameterGroup.AddParameter("Files", "false", "true", "Microsoft.Build.Framework.ITaskItem[]")
	$taskBody = $usingTask.AddUsingTaskBody("true", "<Reference xmlns=`"http://schemas.microsoft.com/developer/msbuild/2003`" Include=`"System.Xml`"/>
      <Reference xmlns=`"http://schemas.microsoft.com/developer/msbuild/2003`" Include=`"System.Xml.Linq`"/>
      <Using xmlns=`"http://schemas.microsoft.com/developer/msbuild/2003`" Namespace=`"System`"/>
      <Using xmlns=`"http://schemas.microsoft.com/developer/msbuild/2003`" Namespace=`"System.IO`"/>
      <Using xmlns=`"http://schemas.microsoft.com/developer/msbuild/2003`" Namespace=`"System.Xml.Linq`"/>
      <Code xmlns=`"http://schemas.microsoft.com/developer/msbuild/2003`" Type=`"Fragment`" Language=`"cs`">
<![CDATA[
var config = XElement.Load(Config.ItemSpec).Elements(`"Costura`").FirstOrDefault();

if (config == null) return true;

var excludedAssemblies = new List<string>();
var attribute = config.Attribute(`"ExcludeAssemblies`");
if (attribute != null)
    foreach (var item in attribute.Value.Split('|').Select(x => x.Trim()).Where(x => x != string.Empty))
        excludedAssemblies.Add(item);
var element = config.Element(`"ExcludeAssemblies`");
if (element != null)
    foreach (var item in element.Value.Split(new[] { `"\r\n`", `"\n`" }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).Where(x => x != string.Empty))
        excludedAssemblies.Add(item);

var filesToCleanup = Files.Select(f => f.ItemSpec).Where(f => !excludedAssemblies.Contains(Path.GetFileNameWithoutExtension(f), StringComparer.InvariantCultureIgnoreCase));

foreach (var item in filesToCleanup)
  File.Delete(item);
]]>
      </Code>")

    $target = $buildProject.Xml.AddTarget("CleanReferenceCopyLocalPaths")
    $target.AfterTargets = "AfterBuild;NonWinFodyTarget"
    $deleteTask = $target.AddTask("CosturaCleanup")
    $deleteTask.SetParameter("Config", "FodyWeavers.xml")
    $deleteTask.SetParameter("Files", "@(ReferenceCopyLocalPaths->`'`$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)`')")

    $buildProject.Save()

    Write-Host "Added target CleanReferenceCopyLocalPaths."
}

function Uninstall-CleanReferencesTarget()
{
    $buildProject = Get-MSBuildProject

    $target = $buildProject.Xml.Targets | Where-Object { "CleanReferenceCopyLocalPaths" -contains $_.Name }
    $usingTask = $buildProject.Xml.UsingTasks | Where-Object { "CosturaCleanup" -contains $_.TaskName }

    if (!$target)
    {
        Write-Host "Target CleanReferenceCopyLocalPaths did not exist." -foregroundcolor Black -backgroundcolor Yellow

        return
    }

    $buildProject.Xml.RemoveChild($usingTask)
    $buildProject.Xml.RemoveChild($target)

    $buildProject.Save()

    Write-Host "Removed target CleanReferenceCopyLocalPaths."
}


text:
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).

You are given a target value to search. If found in the array return true, otherwise return false.

### Example 1:

```
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
```

### Example 2:

```
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
```

### Follow up:

- This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
- Would this affect the run-time complexity? How and why?

#Array #Binary Search

#Similar questions [#33](../p033m/README.md) [#81](../p081m/README.md) [#153](../p153m/README.md)


text:
package de.htwg.zeta.persistence.fixtures

import java.util.UUID

import de.htwg.zeta.common.models.entity.AccessAuthorisation

object AccessAuthorisationFixtures {

  val entity1 = AccessAuthorisation(
    id = UUID.randomUUID,
    authorizedEntityAccess = Map(
      "col1" -> Set(UUID.randomUUID, UUID.randomUUID, UUID.randomUUID),
      "col2" -> Set(UUID.randomUUID, UUID.randomUUID),
      "col3" -> Set.empty
    ),
    authorizedFileAccess = Map.empty
  )

  val entity2 = AccessAuthorisation(
    id = UUID.randomUUID,
    authorizedEntityAccess = Map(
      "col4" -> Set(UUID.randomUUID),
      "col5" -> Set(UUID.randomUUID, UUID.randomUUID, UUID.randomUUID),
      "col6" -> Set.empty
    ),
    authorizedFileAccess = Map(
      UUID.randomUUID -> Set("file1.txt", "file2.txt", "file3.txt"),
      UUID.randomUUID -> Set("file4.txt"),
      UUID.randomUUID -> Set("file5.txt", "file6.txt")
    )
  )

  val entity2Updated: AccessAuthorisation = entity2.grantEntityAccess("col7", UUID.randomUUID)

  val entity3 = AccessAuthorisation(
    id = UUID.randomUUID,
    authorizedEntityAccess = Map.empty,
    authorizedFileAccess = Map(
      UUID.randomUUID -> Set("file7.txt", "file8.txt")
    )
  )

}


text:
define({
  "enableUndoRedo": "Abilita Annulla/Ripeti",
  "toolbarVisible": "Barra degli strumenti visibile",
  "toolbarOptions": "Opzioni barra degli strumenti",
  "mergeVisible": "Unisci",
  "cutVisible": "Taglia",
  "reshapeVisible": "Rimodella",
  "back": "Indietro",
  "label": "Layer",
  "edit": "Modificabile",
  "update": "Disabilita aggiornamento geometria",
  "fields": "Campi",
  "actions": "Azioni",
  "editpageName": "Nome",
  "editpageAlias": "Alias",
  "editpageVisible": "Visibile",
  "editpageEditable": "Modificabile",
  "noLayers": "Non sono disponibili feature layer modificabili",
  "configureFields": "Configura campi layer",
  "useFilterEdit": "Utilizza filtro modello di feature",
  "display": "Visualizza",
  "autoApplyEditWhenGeometryIsMoved": "Applica automaticamente la modifica quando la geometria viene spostata",
  "snappingTolerance": "Imposta la tolleranza snap in pixel",
  "popupTolerance": "Imposta la tolleranza del popup di modifica dell'attributo in pixel",
  "stickyMoveTolerance": "Imposta la tolleranza spostamento permanente in pixel",
  "usingSaveButton": "Le modifiche apportate agli attributi non vengono applicate finché non si clicca il pulsante Salva",
  "generalSettings": "Impostazioni generali",
  "editableLayersSetting": "Impostazioni layer modificabili",
  "honorTheWebMapSetting": "Rispettare le impostazioni nella mappa Web",
  "honorTheWebMapSettingTip1": "Le impostazioni includono:",
  "honorTheWebMapSettingTip2": "I layer modificabili",
  "honorTheWebMapSettingTip3": "I campi che si desidera visualizzare e modificare",
  "honorTheWebMapSettingTip4": "Alias, ordine e formato di un campo",
  "customSettings": "Impostazioni personalizzate"
});


text:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD//EN"
  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <mapping class="pl.garciapl.banknow.model.Transaction"/>
    <mapping class="pl.garciapl.banknow.model.Account"/>
  </session-factory>
</hibernate-configuration>


text:
var config = require("../helpers/config");
var Tools = require("../helpers/tools");

var defineSetting = function(o, name, def) {
    Object.defineProperty(o, name, {
        get: function() {
            return config("captcha." + o.id + "." + name, config("captcha." + name, def));
        },
        configurable: true
    });
};

var captchas = {};

var Captcha = function(id, title, options) {
    Object.defineProperty(this, "id", {
        value: id,
        configurable: true
    });
    Object.defineProperty(this, "title", {
        value: title,
        configurable: true
    });
};

/*public*/ Captcha.prototype.defineSetting = function(name, def) {
    return defineSetting(this, name, def);
};

/*public*/ Captcha.prototype.solve = function(window, container) {
    return Promise.resolve("");
};

Captcha.captcha = function(id) {
    return captchas[id];
};

Captcha.addCaptcha = function(captcha) {
    if (!Captcha.prototype.isPrototypeOf(captcha))
        return;
    captchas[captcha.id] = captcha;
};

Captcha.captchaIds = function() {
    return Tools.toArray(captchas).sort(function(p1, p2) {
        return (p1.name < p2.name) ? -1 : 1;
    }).map(function(captcha) {
        return captcha.id;
    });
};

module.exports = Captcha;


text:
package cn.iflyapi.blog.entity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UserFileExample {
    protected String orderByClause;

    protected boolean distinct;

    protected List<Criteria> oredCriteria;

    public UserFileExample() {
        oredCriteria = new ArrayList<Criteria>();
    }

    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    public String getOrderByClause() {
        return orderByClause;
    }

    public void setDistinct(boolean distinct) {
        this.distinct = distinct;
    }

    public boolean isDistinct() {
        return distinct;
    }

    public List<Criteria> getOredCriteria() {
        return oredCriteria;
    }

    public void or(Criteria criteria) {
        oredCriteria.add(criteria);
    }

    public Criteria or() {
        Criteria criteria = createCriteriaInternal();
        oredCriteria.add(criteria);
        return criteria;
    }

    public Criteria createCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (oredCriteria.size() == 0) {
            oredCriteria.add(criteria);
        }
        return criteria;
    }

    protected Criteria createCriteriaInternal() {
        Criteria criteria = new Criteria();
        return criteria;
    }

    public void clear() {
        oredCriteria.clear();
        orderByClause = null;
        distinct = false;
    }

    protected abstract static class GeneratedCriteria {
        protected List<Criterion> criteria;

        protected GeneratedCriteria() {
            super();
            criteria = new ArrayList<Criterion>();
        }

        public boolean isValid() {
            return criteria.size() > 0;
        }

        public List<Criterion> getAllCriteria() {
            return criteria;
        }

        public List<Criterion> getCriteria() {
            return criteria;
        }

        protected void addCriterion(String condition) {
            if (condition == null) {
                throw new RuntimeException("Value for condition cannot be null");
            }
            criteria.add(new Criterion(condition));
        }

        protected void addCriterion(String condition, Object value, String property) {
            if (value == null) {
                throw new RuntimeException("Value for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value));
        }

        protected void addCriterion(String condition, Object value1, Object value2, String property) {
            if (value1 == null || value2 == null) {
                throw new RuntimeException("Between values for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value1, value2));
        }

        public Criteria andFileIdIsNull() {
            addCriterion("file_id is null");
            return (Criteria) this;
        }

        public Criteria andFileIdIsNotNull() {
            addCriterion("file_id is not null");
            return (Criteria) this;
        }

        public Criteria andFileIdEqualTo(Long value) {
            addCriterion("file_id =", value, "fileId");
            return (Criteria) this;
        }

        public Criteria andFileIdNotEqualTo(Long value) {
            addCriterion("file_id <>", value, "fileId");
            return (Criteria) this;
        }

        public Criteria andFileIdGreaterThan(Long value) {
            addCriterion("file_id >", value, "fileId");
            return (Criteria) this;
        }

        public Criteria andFileIdGreaterThanOrEqualTo(Long value) {
            addCriterion("file_id >=", value, "fileId");
            return (Criteria) this;
        }

        public Criteria andFileIdLessThan(Long value) {
            addCriterion("file_id <", value, "fileId");
            return (Criteria) this;
        }

        public Criteria andFileIdLessThanOrEqualTo(Long value) {
            addCriterion("file_id <=", value, "fileId");
            return (Criteria) this;
        }

        public Criteria andFileIdIn(List<Long> values) {
            addCriterion("file_id in", values, "fileId");
            return (Criteria) this;
        }

        public Criteria andFileIdNotIn(List<Long> values) {
            addCriterion("file_id not in", values, "fileId");
            return (Criteria) this;
        }

        public Criteria andFileIdBetween(Long value1, Long value2) {
            addCriterion("file_id between", value1, value2, "fileId");
            return (Criteria) this;
        }

        public Criteria andFileIdNotBetween(Long value1, Long value2) {
            addCriterion("file_id not between", value1, value2, "fileId");
            return (Criteria) this;
        }

        public Criteria andUserIdIsNull() {
            addCriterion("user_id is null");
            return (Criteria) this;
        }

        public Criteria andUserIdIsNotNull() {
            addCriterion("user_id is not null");
            return (Criteria) this;
        }

        public Criteria andUserIdEqualTo(Long value) {
            addCriterion("user_id =", value, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdNotEqualTo(Long value) {
            addCriterion("user_id <>", value, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdGreaterThan(Long value) {
            addCriterion("user_id >", value, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdGreaterThanOrEqualTo(Long value) {
            addCriterion("user_id >=", value, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdLessThan(Long value) {
            addCriterion("user_id <", value, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdLessThanOrEqualTo(Long value) {
            addCriterion("user_id <=", value, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdIn(List<Long> values) {
            addCriterion("user_id in", values, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdNotIn(List<Long> values) {
            addCriterion("user_id not in", values, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdBetween(Long value1, Long value2) {
            addCriterion("user_id between", value1, value2, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdNotBetween(Long value1, Long value2) {
            addCriterion("user_id not between", value1, value2, "userId");
            return (Criteria) this;
        }

        public Criteria andFileNameIsNull() {
            addCriterion("file_name is null");
            return (Criteria) this;
        }

        public Criteria andFileNameIsNotNull() {
            addCriterion("file_name is not null");
            return (Criteria) this;
        }

        public Criteria andFileNameEqualTo(String value) {
            addCriterion("file_name =", value, "fileName");
            return (Criteria) this;
        }

        public Criteria andFileNameNotEqualTo(String value) {
            addCriterion("file_name <>", value, "fileName");
            return (Criteria) this;
        }

        public Criteria andFileNameGreaterThan(String value) {
            addCriterion("file_name >", value, "fileName");
            return (Criteria) this;
        }

        public Criteria andFileNameGreaterThanOrEqualTo(String value) {
            addCriterion("file_name >=", value, "fileName");
            return (Criteria) this;
        }

        public Criteria andFileNameLessThan(String value) {
            addCriterion("file_name <", value, "fileName");
            return (Criteria) this;
        }

        public Criteria andFileNameLessThanOrEqualTo(String value) {
            addCriterion("file_name <=", value, "fileName");
            return (Criteria) this;
        }

        public Criteria andFileNameLike(String value) {
            addCriterion("file_name like", value, "fileName");
            return (Criteria) this;
        }

        public Criteria andFileNameNotLike(String value) {
            addCriterion("file_name not like", value, "fileName");
            return (Criteria) this;
        }

        public Criteria andFileNameIn(List<String> values) {
            addCriterion("file_name in", values, "fileName");
            return (Criteria) this;
        }

        public Criteria andFileNameNotIn(List<String> values) {
            addCriterion("file_name not in", values, "fileName");
            return (Criteria) this;
        }

        public Criteria andFileNameBetween(String value1, String value2) {
            addCriterion("file_name between", value1, value2, "fileName");
            return (Criteria) this;
        }

        public Criteria andFileNameNotBetween(String value1, String value2) {
            addCriterion("file_name not between", value1, value2, "fileName");
            return (Criteria) this;
        }

        public Criteria andFileSizeIsNull() {
            addCriterion("file_size is null");
            return (Criteria) this;
        }

        public Criteria andFileSizeIsNotNull() {
            addCriterion("file_size is not null");
            return (Criteria) this;
        }

        public Criteria andFileSizeEqualTo(Long value) {
            addCriterion("file_size =", value, "fileSize");
            return (Criteria) this;
        }

        public Criteria andFileSizeNotEqualTo(Long value) {
            addCriterion("file_size <>", value, "fileSize");
            return (Criteria) this;
        }

        public Criteria andFileSizeGreaterThan(Long value) {
            addCriterion("file_size >", value, "fileSize");
            return (Criteria) this;
        }

        public Criteria andFileSizeGreaterThanOrEqualTo(Long value) {
            addCriterion("file_size >=", value, "fileSize");
            return (Criteria) this;
        }

        public Criteria andFileSizeLessThan(Long value) {
            addCriterion("file_size <", value, "fileSize");
            return (Criteria) this;
        }

        public Criteria andFileSizeLessThanOrEqualTo(Long value) {
            addCriterion("file_size <=", value, "fileSize");
            return (Criteria) this;
        }

        public Criteria andFileSizeIn(List<Long> values) {
            addCriterion("file_size in", values, "fileSize");
            return (Criteria) this;
        }

        public Criteria andFileSizeNotIn(List<Long> values) {
            addCriterion("file_size not in", values, "fileSize");
            return (Criteria) this;
        }

        public Criteria andFileSizeBetween(Long value1, Long value2) {
            addCriterion("file_size between", value1, value2, "fileSize");
            return (Criteria) this;
        }

        public Criteria andFileSizeNotBetween(Long value1, Long value2) {
            addCriterion("file_size not between", value1, value2, "fileSize");
            return (Criteria) this;
        }

        public Criteria andFileTypeIsNull() {
            addCriterion("file_type is null");
            return (Criteria) this;
        }

        public Criteria andFileTypeIsNotNull() {
            addCriterion("file_type is not null");
            return (Criteria) this;
        }

        public Criteria andFileTypeEqualTo(String value) {
            addCriterion("file_type =", value, "fileType");
            return (Criteria) this;
        }

        public Criteria andFileTypeNotEqualTo(String value) {
            addCriterion("file_type <>", value, "fileType");
            return (Criteria) this;
        }

        public Criteria andFileTypeGreaterThan(String value) {
            addCriterion("file_type >", value, "fileType");
            return (Criteria) this;
        }

        public Criteria andFileTypeGreaterThanOrEqualTo(String value) {
            addCriterion("file_type >=", value, "fileType");
            return (Criteria) this;
        }

        public Criteria andFileTypeLessThan(String value) {
            addCriterion("file_type <", value, "fileType");
            return (Criteria) this;
        }

        public Criteria andFileTypeLessThanOrEqualTo(String value) {
            addCriterion("file_type <=", value, "fileType");
            return (Criteria) this;
        }

        public Criteria andFileTypeLike(String value) {
            addCriterion("file_type like", value, "fileType");
            return (Criteria) this;
        }

        public Criteria andFileTypeNotLike(String value) {
            addCriterion("file_type not like", value, "fileType");
            return (Criteria) this;
        }

        public Criteria andFileTypeIn(List<String> values) {
            addCriterion("file_type in", values, "fileType");
            return (Criteria) this;
        }

        public Criteria andFileTypeNotIn(List<String> values) {
            addCriterion("file_type not in", values, "fileType");
            return (Criteria) this;
        }

        public Criteria andFileTypeBetween(String value1, String value2) {
            addCriterion("file_type between", value1, value2, "fileType");
            return (Criteria) this;
        }

        public Criteria andFileTypeNotBetween(String value1, String value2) {
            addCriterion("file_type not between", value1, value2, "fileType");
            return (Criteria) this;
        }

        public Criteria andCreateTimeIsNull() {
            addCriterion("create_time is null");
            return (Criteria) this;
        }

        public Criteria andCreateTimeIsNotNull() {
            addCriterion("create_time is not null");
            return (Criteria) this;
        }

        public Criteria andCreateTimeEqualTo(Date value) {
            addCriterion("create_time =", value, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeNotEqualTo(Date value) {
            addCriterion("create_time <>", value, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeGreaterThan(Date value) {
            addCriterion("create_time >", value, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {
            addCriterion("create_time >=", value, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeLessThan(Date value) {
            addCriterion("create_time <", value, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeLessThanOrEqualTo(Date value) {
            addCriterion("create_time <=", value, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeIn(List<Date> values) {
            addCriterion("create_time in", values, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeNotIn(List<Date> values) {
            addCriterion("create_time not in", values, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeBetween(Date value1, Date value2) {
            addCriterion("create_time between", value1, value2, "createTime");
            return (Criteria) this;
        }

        public Criteria andCreateTimeNotBetween(Date value1, Date value2) {
            addCriterion("create_time not between", value1, value2, "createTime");
            return (Criteria) this;
        }

        public Criteria andIsDeleteIsNull() {
            addCriterion("is_delete is null");
            return (Criteria) this;
        }

        public Criteria andIsDeleteIsNotNull() {
            addCriterion("is_delete is not null");
            return (Criteria) this;
        }

        public Criteria andIsDeleteEqualTo(Boolean value) {
            addCriterion("is_delete =", value, "isDelete");
            return (Criteria) this;
        }

        public Criteria andIsDeleteNotEqualTo(Boolean value) {
            addCriterion("is_delete <>", value, "isDelete");
            return (Criteria) this;
        }

        public Criteria andIsDeleteGreaterThan(Boolean value) {
            addCriterion("is_delete >", value, "isDelete");
            return (Criteria) this;
        }

        public Criteria andIsDeleteGreaterThanOrEqualTo(Boolean value) {
            addCriterion("is_delete >=", value, "isDelete");
            return (Criteria) this;
        }

        public Criteria andIsDeleteLessThan(Boolean value) {
            addCriterion("is_delete <", value, "isDelete");
            return (Criteria) this;
        }

        public Criteria andIsDeleteLessThanOrEqualTo(Boolean value) {
            addCriterion("is_delete <=", value, "isDelete");
            return (Criteria) this;
        }

        public Criteria andIsDeleteIn(List<Boolean> values) {
            addCriterion("is_delete in", values, "isDelete");
            return (Criteria) this;
        }

        public Criteria andIsDeleteNotIn(List<Boolean> values) {
            addCriterion("is_delete not in", values, "isDelete");
            return (Criteria) this;
        }

        public Criteria andIsDeleteBetween(Boolean value1, Boolean value2) {
            addCriterion("is_delete between", value1, value2, "isDelete");
            return (Criteria) this;
        }

        public Criteria andIsDeleteNotBetween(Boolean value1, Boolean value2) {
            addCriterion("is_delete not between", value1, value2, "isDelete");
            return (Criteria) this;
        }
    }

    public static class Criteria extends GeneratedCriteria {

        protected Criteria() {
            super();
        }
    }

    public static class Criterion {
        private String condition;

        private Object value;

        private Object secondValue;

        private boolean noValue;

        private boolean singleValue;

        private boolean betweenValue;

        private boolean listValue;

        private String typeHandler;

        public String getCondition() {
            return condition;
        }

        public Object getValue() {
            return value;
        }

        public Object getSecondValue() {
            return secondValue;
        }

        public boolean isNoValue() {
            return noValue;
        }

        public boolean isSingleValue() {
            return singleValue;
        }

        public boolean isBetweenValue() {
            return betweenValue;
        }

        public boolean isListValue() {
            return listValue;
        }

        public String getTypeHandler() {
            return typeHandler;
        }

        protected Criterion(String condition) {
            super();
            this.condition = condition;
            this.typeHandler = null;
            this.noValue = true;
        }

        protected Criterion(String condition, Object value, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.typeHandler = typeHandler;
            if (value instanceof List<?>) {
                this.listValue = true;
            } else {
                this.singleValue = true;
            }
        }

        protected Criterion(String condition, Object value) {
            this(condition, value, null);
        }

        protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.secondValue = secondValue;
            this.typeHandler = typeHandler;
            this.betweenValue = true;
        }

        protected Criterion(String condition, Object value, Object secondValue) {
            this(condition, value, secondValue, null);
        }
    }
}


text:
package view.task;

import java.util.Calendar;
import java.util.Date;

import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.util.Log;
import android.widget.TimePicker;

public class TimePickerFragment extends DialogFragment implements
		android.app.TimePickerDialog.OnTimeSetListener {

	private Date time;
	private KulOnTimeChangeListener listener;

	static TimePickerFragment newInstance(Date time) {
		Bundle args = new Bundle();
		args.putSerializable("time", time);
		TimePickerFragment tp = new TimePickerFragment();
		tp.setArguments(args);
		return tp;
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		try {
			listener = (KulOnTimeChangeListener) getActivity();
		} catch (ClassCastException e) {
			Log.i("TODO", "Bad KulOnDataDialogListener");
		}

		Bundle args = getArguments();
		this.time = (Date) args.getSerializable("time");
		final Calendar c = Calendar.getInstance();
		c.setTime(time);

		return new TimePickerDialog(getActivity(), this,
				c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true);
	}

	@Override
	public void onTimeSet(TimePicker view, int hour, int min) {
		Calendar c = Calendar.getInstance();
		final int year = c.get(Calendar.YEAR);
		final int mon = c.get(Calendar.MONTH);
		final int day = c.get(Calendar.DAY_OF_MONTH);
		c.setTime(time);
		c.set(year, mon, day, hour, min);

		time = c.getTime();
		listener.onTimeChange(time);
	}

	interface KulOnTimeChangeListener {
		void onTimeChange(Date time);
	}
}


text:
package hr.fer.zemris.vhdllab.platform.context;

import org.apache.log4j.Logger;

public enum Environment {
    DEVELOPMENT, PRODUCTION;

    /**
     * Logger for this class
     */
    private static final Logger LOG = Logger.getLogger(Environment.class);

    private static Environment currentEnvironment;

    public static Environment getCurrentEnvironment() {
        if (currentEnvironment == null) {
            setCurrentEnvironment(DEVELOPMENT);
        }
        return currentEnvironment;
    }

    public static void setCurrentEnvironment(Environment env) {
        currentEnvironment = env;
        LOG.debug("Environment set to " + currentEnvironment);
    }

    public static boolean isDevelopment() {
        return getCurrentEnvironment().equals(DEVELOPMENT);
    }

}


text:
package v2

import (
	"errors"
	"io"
	"sync"
	"time"

	xdsapi "github.com/envoyproxy/go-control-plane/envoy/api/v2"
	core "github.com/envoyproxy/go-control-plane/envoy/api/v2/core"
	ads "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v2"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/peer"
	"google.golang.org/grpc/status"

	"istio.io/istio/pkg/config/schemas"
	istiolog "istio.io/pkg/log"

	"istio.io/istio/pilot/pkg/features"
	"istio.io/istio/pilot/pkg/model"
	"istio.io/istio/pilot/pkg/networking/util"
)

var (
	adsLog = istiolog.RegisterScope("ads", "ads debugging", 0)

	// adsClients reflect active gRPC channels, for both ADS and EDS.
	adsClients      = map[string]*XdsConnection{}
	adsClientsMutex sync.RWMutex

	// Map of sidecar IDs to XdsConnections, first key is sidecarID, second key is connID
	// This is a map due to an edge case during envoy restart whereby the 'old' envoy
	// reconnects after the 'new/restarted' envoy
	adsSidecarIDConnectionsMap = map[string]map[string]*XdsConnection{}

	// SendTimeout is the max time to wait for a ADS send to complete. This helps detect
	// clients in a bad state (not reading). In future it may include checking for ACK
	SendTimeout = 5 * time.Second
)

// DiscoveryStream is a common interface for EDS and ADS. It also has a
// shorter name.
type DiscoveryStream interface {
	Send(*xdsapi.DiscoveryResponse) error
	Recv() (*xdsapi.DiscoveryRequest, error)
	grpc.ServerStream
}

// XdsConnection is a listener connection type.
type XdsConnection struct {
	// Mutex to protect changes to this XDS connection
	mu sync.RWMutex

	// PeerAddr is the address of the client envoy, from network layer
	PeerAddr string

	// Time of connection, for debugging
	Connect time.Time

	// ConID is the connection identifier, used as a key in the connection table.
	// Currently based on the node name and a counter.
	ConID string

	node *model.Proxy

	// Sending on this channel results in a push. We may also make it a channel of objects so
	// same info can be sent to all clients, without recomputing.
	pushChannel chan *XdsEvent

	LDSListeners []*xdsapi.Listener                    `json:"-"`
	RouteConfigs map[string]*xdsapi.RouteConfiguration `json:"-"`
	CDSClusters  []*xdsapi.Cluster

	// Last nonce sent and ack'd (timestamps) used for debugging
	ClusterNonceSent, ClusterNonceAcked   string
	ListenerNonceSent, ListenerNonceAcked string
	RouteNonceSent, RouteNonceAcked       string
	RouteVersionInfoSent                  string
	EndpointNonceSent, EndpointNonceAcked string
	EndpointPercent                       int

	// current list of clusters monitored by the client
	Clusters []string

	// Both ADS and EDS streams implement this interface
	stream DiscoveryStream

	// Routes is the list of watched Routes.
	Routes []string

	// LDSWatch is set if the remote server is watching Listeners
	LDSWatch bool
	// CDSWatch is set if the remote server is watching Clusters
	CDSWatch bool

	// added will be true if at least one discovery request was received, and the connection
	// is added to the map of active.
	added bool
}

// XdsEvent represents a config or registry event that results in a push.
type XdsEvent struct {
	// If not empty, it is used to indicate the event is caused by a change in the clusters.
	// Only EDS for the listed clusters will be sent.
	edsUpdatedServices map[string]struct{}

	namespacesUpdated map[string]struct{}

	configTypesUpdated map[string]struct{}

	// Push context to use for the push.
	push *model.PushContext

	// start represents the time a push was started.
	start time.Time

	// function to call once a push is finished. This must be called or future changes may be blocked.
	done func()

	noncePrefix string
}

func newXdsConnection(peerAddr string, stream DiscoveryStream) *XdsConnection {
	return &XdsConnection{
		pushChannel:  make(chan *XdsEvent),
		PeerAddr:     peerAddr,
		Clusters:     []string{},
		Connect:      time.Now(),
		stream:       stream,
		LDSListeners: []*xdsapi.Listener{},
		RouteConfigs: map[string]*xdsapi.RouteConfiguration{},
	}
}

func receiveThread(con *XdsConnection, reqChannel chan *xdsapi.DiscoveryRequest, errP *error) {
	defer close(reqChannel) // indicates close of the remote side.
	for {
		req, err := con.stream.Recv()
		if err != nil {
			if status.Code(err) == codes.Canceled || err == io.EOF {
				con.mu.RLock()
				adsLog.Infof("ADS: %q %s terminated %v", con.PeerAddr, con.ConID, err)
				con.mu.RUnlock()
				return
			}
			*errP = err
			adsLog.Errorf("ADS: %q %s terminated with error: %v", con.PeerAddr, con.ConID, err)
			totalXDSInternalErrors.Increment()
			return
		}
		select {
		case reqChannel <- req:
		case <-con.stream.Context().Done():
			adsLog.Errorf("ADS: %q %s terminated with stream closed", con.PeerAddr, con.ConID)
			return
		}
	}
}

// StreamAggregatedResources implements the ADS interface.
func (s *DiscoveryServer) StreamAggregatedResources(stream ads.AggregatedDiscoveryService_StreamAggregatedResourcesServer) error {
	peerInfo, ok := peer.FromContext(stream.Context())
	peerAddr := "0.0.0.0"
	if ok {
		peerAddr = peerInfo.Addr.String()
	}

	t0 := time.Now()

	// first call - lazy loading, in tests. This should not happen if readiness
	// check works, since it assumes ClearCache is called (and as such PushContext
	// is initialized)
	// InitContext returns immediately if the context was already initialized.
	err := s.globalPushContext().InitContext(s.Env, nil, nil)
	if err != nil {
		// Error accessing the data - log and close, maybe a different pilot replica
		// has more luck
		adsLog.Warnf("Error reading config %v", err)
		return err
	}
	con := newXdsConnection(peerAddr, stream)

	// Do not call: defer close(con.pushChannel) !
	// the push channel will be garbage collected when the connection is no longer used.
	// Closing the channel can cause subtle race conditions with push. According to the spec:
	// "It's only necessary to close a channel when it is important to tell the receiving goroutines that all data
	// have been sent."

	// Reading from a stream is a blocking operation. Each connection needs to read
	// discovery requests and wait for push commands on config change, so we add a
	// go routine. If go grpc adds gochannel support for streams this will not be needed.
	// This also detects close.
	var receiveError error
	reqChannel := make(chan *xdsapi.DiscoveryRequest, 1)
	go receiveThread(con, reqChannel, &receiveError)

	for {
		// Block until either a request is received or a push is triggered.
		select {
		case discReq, ok := <-reqChannel:
			if !ok {
				// Remote side closed connection.
				return receiveError
			}
			// This should be only set for the first request. Guard with ID check regardless.
			if discReq.Node != nil && discReq.Node.Id != "" {
				err = s.initConnectionNode(discReq.Node, con)
				if err != nil {
					return err
				}
			}

			switch discReq.TypeUrl {
			case ClusterType:
				if con.CDSWatch {
					// Already received a cluster watch request, this is an ACK
					if discReq.ErrorDetail != nil {
						errCode := codes.Code(discReq.ErrorDetail.Code)
						adsLog.Warnf("ADS:CDS: ACK ERROR %v %s %s:%s", peerAddr, con.ConID, errCode.String(), discReq.ErrorDetail.GetMessage())
						incrementXDSRejects(cdsReject, con.node.ID, errCode.String())
					} else if discReq.ResponseNonce != "" {
						con.ClusterNonceAcked = discReq.ResponseNonce
					}
					adsLog.Debugf("ADS:CDS: ACK %s %s %s %s", peerAddr, con.ConID, discReq.VersionInfo, discReq.ResponseNonce)
					continue
				}
				// CDS REQ is the first request an envoy makes. This shows up
				// immediately after connect. It is followed by EDS REQ as
				// soon as the CDS push is returned.
				adsLog.Infof("ADS:CDS: REQ %v %s %v version:%s", peerAddr, con.ConID, time.Since(t0), discReq.VersionInfo)
				con.CDSWatch = true
				err := s.pushCds(con, s.globalPushContext(), versionInfo())
				if err != nil {
					return err
				}

			case ListenerType:
				if con.LDSWatch {
					// Already received a cluster watch request, this is an ACK
					if discReq.ErrorDetail != nil {
						errCode := codes.Code(discReq.ErrorDetail.Code)
						adsLog.Warnf("ADS:LDS: ACK ERROR %v %s %s:%s", peerAddr, con.ConID, errCode.String(), discReq.ErrorDetail.GetMessage())
						incrementXDSRejects(ldsReject, con.node.ID, errCode.String())
					} else if discReq.ResponseNonce != "" {
						con.ListenerNonceAcked = discReq.ResponseNonce
					}
					adsLog.Debugf("ADS:LDS: ACK %s %s %s %s", peerAddr, con.ConID, discReq.VersionInfo, discReq.ResponseNonce)
					continue
				}
				// too verbose - sent immediately after EDS response is received
				adsLog.Debugf("ADS:LDS: REQ %s %v", con.ConID, peerAddr)
				con.LDSWatch = true
				err := s.pushLds(con, s.globalPushContext(), versionInfo())
				if err != nil {
					return err
				}

			case RouteType:
				if discReq.ErrorDetail != nil {
					errCode := codes.Code(discReq.ErrorDetail.Code)
					adsLog.Warnf("ADS:RDS: ACK ERROR %v %s %s:%s", peerAddr, con.ConID, errCode.String(), discReq.ErrorDetail.GetMessage())
					incrementXDSRejects(rdsReject, con.node.ID, errCode.String())
					continue
				}
				routes := discReq.GetResourceNames()
				if discReq.ResponseNonce != "" {
					con.mu.RLock()
					routeNonceSent := con.RouteNonceSent
					routeVersionInfoSent := con.RouteVersionInfoSent
					con.mu.RUnlock()
					if routeNonceSent != "" && routeNonceSent != discReq.ResponseNonce {
						adsLog.Debugf("ADS:RDS: Expired nonce received %s %s, sent %s, received %s",
							peerAddr, con.ConID, routeNonceSent, discReq.ResponseNonce)
						rdsExpiredNonce.Increment()
						continue
					}
					if discReq.VersionInfo == routeVersionInfoSent {
						if listEqualUnordered(con.Routes, routes) {
							adsLog.Debugf("ADS:RDS: ACK %s %s %s %s", peerAddr, con.ConID, discReq.VersionInfo, discReq.ResponseNonce)
							con.mu.Lock()
							con.RouteNonceAcked = discReq.ResponseNonce
							con.mu.Unlock()
							continue
						}
					} else if discReq.ErrorDetail != nil {
						// If versions mismatch then we should either have an error detail or no routes if a protocol error has occurred
						if discReq.ErrorDetail != nil {
							errCode := codes.Code(discReq.ErrorDetail.Code)
							adsLog.Warnf("ADS:RDS: ACK ERROR %v %s %s:%s", peerAddr, con.ConID, errCode.String(), discReq.ErrorDetail.GetMessage())
							incrementXDSRejects(rdsReject, con.node.ID, errCode.String())
						}
						continue
					} else if len(routes) == 0 {
						// XDS protocol indicates an empty request means to send all route information
						// In practice we can just skip this request, as this seems to happen when
						// we don't have any routes to send.
						continue
					}
				}

				con.Routes = routes
				adsLog.Debugf("ADS:RDS: REQ %s %s routes:%d", peerAddr, con.ConID, len(con.Routes))
				err := s.pushRoute(con, s.globalPushContext(), versionInfo())
				if err != nil {
					return err
				}

			case EndpointType:
				if discReq.ErrorDetail != nil {
					errCode := codes.Code(discReq.ErrorDetail.Code)
					adsLog.Warnf("ADS:EDS: ACK ERROR %v %s %s:%s", peerAddr, con.ConID, errCode.String(), discReq.ErrorDetail.GetMessage())
					incrementXDSRejects(edsReject, con.node.ID, errCode.String())
					continue
				}
				clusters := discReq.GetResourceNames()
				if clusters == nil && discReq.ResponseNonce != "" {
					// There is no requirement that ACK includes clusters. The test doesn't.
					con.mu.Lock()
					con.EndpointNonceAcked = discReq.ResponseNonce
					con.mu.Unlock()
					continue
				}
				// clusters and con.Clusters are all empty, this is not an ack and will do nothing.
				if len(clusters) == 0 && len(con.Clusters) == 0 {
					continue
				}

				// Already got a list of endpoints to watch and it is the same as the request, this is an ack
				if listEqualUnordered(con.Clusters, clusters) {
					adsLog.Debugf("ADS:EDS: ACK %s %s %s %s", peerAddr, con.ConID, discReq.VersionInfo, discReq.ResponseNonce)
					if discReq.ResponseNonce != "" {
						con.mu.Lock()
						edsClusterMutex.RLock()
						con.EndpointNonceAcked = discReq.ResponseNonce
						if len(edsClusters) != 0 {
							con.EndpointPercent = int((float64(len(clusters)) / float64(len(edsClusters))) * float64(100))
						}
						edsClusterMutex.RUnlock()
						con.mu.Unlock()
					}
					continue
				}

				for _, cn := range con.Clusters {
					s.removeEdsCon(cn, con.ConID)
				}

				for _, cn := range clusters {
					s.getOrAddEdsCluster(cn, con.ConID, con)
				}

				con.Clusters = clusters
				adsLog.Debugf("ADS:EDS: REQ %s %s clusters:%d", peerAddr, con.ConID, len(con.Clusters))
				err := s.pushEds(s.globalPushContext(), con, versionInfo(), nil)
				if err != nil {
					return err
				}

			default:
				adsLog.Warnf("ADS: Unknown watched resources %s", discReq.String())
			}

			con.mu.Lock()
			if !con.added {
				con.added = true
				con.mu.Unlock()
				s.addCon(con.ConID, con)
				defer s.removeCon(con.ConID, con)
			} else {
				con.mu.Unlock()
			}
		case pushEv := <-con.pushChannel:
			// It is called when config changes.
			// This is not optimized yet - we should detect what changed based on event and only
			// push resources that need to be pushed.

			// TODO: possible race condition: if a config change happens while the envoy
			// was getting the initial config, between LDS and RDS, the push will miss the
			// monitored 'routes'. Same for CDS/EDS interval.
			// It is very tricky to handle due to the protocol - but the periodic push recovers
			// from it.

			err := s.pushConnection(con, pushEv)
			pushEv.done()
			if err != nil {
				return nil
			}
		}
	}
}

// listEqualUnordered checks that two lists contain all the same elements
func listEqualUnordered(a []string, b []string) bool {
	if len(a) != len(b) {
		return false
	}
	clusterSet := make(map[string]struct{}, len(a))
	for _, c := range a {
		clusterSet[c] = struct{}{}
	}
	for _, c := range b {
		_, f := clusterSet[c]
		if !f {
			return false
		}
	}
	return true
}

// update the node associated with the connection, after receiving a a packet from envoy.
func (s *DiscoveryServer) initConnectionNode(node *core.Node, con *XdsConnection) error {
	con.mu.RLock() // may not be needed - once per connection, but locking for consistency.
	if con.node != nil {
		con.mu.RUnlock()
		return nil // only need to init the node on first request in the stream
	}
	con.mu.RUnlock()

	if node == nil || node.Id == "" {
		return errors.New("missing node id")
	}
	meta, err := model.ParseMetadata(node.Metadata)
	if err != nil {
		return err
	}
	nt, err := model.ParseServiceNodeWithMetadata(node.Id, meta)
	if err != nil {
		return err
	}
	// Update the config namespace associated with this proxy
	nt.ConfigNamespace = model.GetProxyConfigNamespace(nt)

	if err := nt.SetServiceInstances(s.Env); err != nil {
		return err
	}

	// Get the locality from the proxy's service instances.
	// We expect all instances to have the same IP and therefore the same locality. So its enough to look at the first instance
	if len(nt.ServiceInstances) > 0 {
		nt.Locality = util.ConvertLocality(nt.ServiceInstances[0].GetLocality())
	}

	// If there is no locality in the registry then use the one sent as part of the discovery request.
	// This is not preferable as only the connected Pilot is aware of this proxies location, but it
	// can still help provide some client-side Envoy context when load balancing based on location.
	if util.IsLocalityEmpty(nt.Locality) {
		nt.Locality = node.Locality
	}

	if err := nt.SetWorkloadLabels(s.Env); err != nil {
		return err
	}

	// Set the sidecarScope and merged gateways associated with this proxy
	nt.SetSidecarScope(s.globalPushContext())
	nt.SetGatewaysForProxy(s.globalPushContext())

	con.mu.Lock()
	con.node = nt
	if con.ConID == "" {
		// first request
		con.ConID = connectionID(node.Id)
	}
	con.mu.Unlock()

	return nil
}

// DeltaAggregatedResources is not implemented.
func (s *DiscoveryServer) DeltaAggregatedResources(stream ads.AggregatedDiscoveryService_DeltaAggregatedResourcesServer) error {
	return status.Errorf(codes.Unimplemented, "not implemented")
}

// Compute and send the new configuration for a connection. This is blocking and may be slow
// for large configs. The method will hold a lock on con.pushMutex.
func (s *DiscoveryServer) pushConnection(con *XdsConnection, pushEv *XdsEvent) error {
	// TODO: update the service deps based on NetworkScope

	if pushEv.edsUpdatedServices != nil {
		if !ProxyNeedsPush(con.node, pushEv) {
			adsLog.Debugf("Skipping EDS push to %v, no updates required", con.ConID)
			return nil
		}
		// Push only EDS. This is indexed already - push immediately
		// (may need a throttle)
		if len(con.Clusters) > 0 {
			if err := s.pushEds(pushEv.push, con, versionInfo(), pushEv.edsUpdatedServices); err != nil {
				return err
			}
		}
		return nil
	}

	// TODO: remove this ?
	if err := con.node.SetWorkloadLabels(s.Env); err != nil {
		return err
	}

	if err := con.node.SetServiceInstances(pushEv.push.Env); err != nil {
		return err
	}
	if util.IsLocalityEmpty(con.node.Locality) {
		// Get the locality from the proxy's service instances.
		// We expect all instances to have the same locality. So its enough to look at the first instance
		if len(con.node.ServiceInstances) > 0 {
			con.node.Locality = util.ConvertLocality(con.node.ServiceInstances[0].GetLocality())
		}
	}

	// Precompute the sidecar scope and merged gateways associated with this proxy.
	// Saves compute cycles in networking code. Though this might be redundant sometimes, we still
	// have to compute this because as part of a config change, a new Sidecar could become
	// applicable to this proxy
	con.node.SetSidecarScope(pushEv.push)
	con.node.SetGatewaysForProxy(pushEv.push)

	// This depends on SidecarScope updates, so it should be called after SetSidecarScope.
	if !ProxyNeedsPush(con.node, pushEv) {
		adsLog.Debugf("Skipping push to %v, no updates required", con.ConID)
		return nil
	}

	adsLog.Infof("Pushing %v", con.ConID)

	// check version, suppress if changed.
	currentVersion := versionInfo()

	if con.CDSWatch {
		err := s.pushCds(con, pushEv.push, currentVersion)
		if err != nil {
			return err
		}
	}

	if len(con.Clusters) > 0 {
		err := s.pushEds(pushEv.push, con, currentVersion, nil)
		if err != nil {
			return err
		}
	}
	if con.LDSWatch {
		err := s.pushLds(con, pushEv.push, currentVersion)
		if err != nil {
			return err
		}
	}
	if len(con.Routes) > 0 {
		err := s.pushRoute(con, pushEv.push, currentVersion)
		if err != nil {
			return err
		}
	}
	proxiesConvergeDelay.Record(time.Since(pushEv.start).Seconds())
	return nil
}

func adsClientCount() int {
	var n int
	adsClientsMutex.RLock()
	n = len(adsClients)
	adsClientsMutex.RUnlock()
	return n
}

func (s *DiscoveryServer) ProxyUpdate(clusterID, ip string) {
	var connection *XdsConnection

	adsClientsMutex.RLock()
	for _, v := range adsClients {
		if v.node.ClusterID == clusterID && v.node.IPAddresses[0] == ip {
			connection = v
			break
		}

	}
	adsClientsMutex.RUnlock()

	// It is possible that the envoy has not connected to this pilot, maybe connected to another pilot
	if connection == nil {
		return
	}
	if adsLog.DebugEnabled() {
		currentlyPending := s.pushQueue.Pending()
		if currentlyPending != 0 {
			adsLog.Debugf("Starting new push while %v were still pending", currentlyPending)
		}
	}

	s.pushQueue.Enqueue(connection, &model.PushRequest{
		Full:  true,
		Push:  s.globalPushContext(),
		Start: time.Now(),
	})
}

// AdsPushAll will send updates to all nodes, for a full config or incremental EDS.
func AdsPushAll(s *DiscoveryServer) {
	s.AdsPushAll(versionInfo(), &model.PushRequest{Full: true, Push: s.globalPushContext()})
}

// AdsPushAll implements old style invalidation, generated when any rule or endpoint changes.
// Primary code path is from v1 discoveryService.clearCache(), which is added as a handler
// to the model ConfigStorageCache and Controller.
func (s *DiscoveryServer) AdsPushAll(version string, req *model.PushRequest) {
	if !req.Full {
		s.edsIncremental(version, req.Push, req)
		return
	}

	adsLog.Infof("XDS: Pushing:%s Services:%d ConnectedEndpoints:%d",
		version, len(req.Push.Services(nil)), adsClientCount())
	monServices.Record(float64(len(req.Push.Services(nil))))

	t0 := time.Now()

	// First update all cluster load assignments. This is computed for each cluster once per config change
	// instead of once per endpoint.
	edsClusterMutex.Lock()
	// Create a temp map to avoid locking the add/remove
	cMap := make(map[string]*EdsCluster, len(edsClusters))
	for k, v := range edsClusters {
		cMap[k] = v
	}
	edsClusterMutex.Unlock()

	// UpdateCluster updates the cluster with a mutex, this code is safe ( but computing
	// the update may be duplicated if multiple goroutines compute at the same time).
	// In general this code is called from the 'event' callback that is throttled.
	for clusterName, edsCluster := range cMap {
		if err := s.updateCluster(req.Push, clusterName, edsCluster); err != nil {
			adsLog.Errorf("updateCluster failed with clusterName %s", clusterName)
			totalXDSInternalErrors.Increment()
		}
	}
	adsLog.Infof("Cluster init time %v %s", time.Since(t0), version)
	req.EdsUpdates = nil
	s.startPush(req)
}

// Send a signal to all connections, with a push event.
func (s *DiscoveryServer) startPush(req *model.PushRequest) {

	// Push config changes, iterating over connected envoys. This cover ADS and EDS(0.7), both share
	// the same connection table
	adsClientsMutex.RLock()
	// Create a temp map to avoid locking the add/remove
	pending := []*XdsConnection{}
	for _, v := range adsClients {
		pending = append(pending, v)
	}
	adsClientsMutex.RUnlock()

	if adsLog.DebugEnabled() {
		currentlyPending := s.pushQueue.Pending()
		if currentlyPending != 0 {
			adsLog.Infof("Starting new push while %v were still pending", currentlyPending)
		}
	}
	req.Start = time.Now()
	for _, p := range pending {
		s.pushQueue.Enqueue(p, req)
	}
}

func ProxyNeedsPush(proxy *model.Proxy, pushEv *XdsEvent) bool {
	if !features.ScopePushes.Get() {
		// If push scoping is not enabled, we push for all proxies
		return true
	}

	targetNamespaces := pushEv.namespacesUpdated
	configs := pushEv.configTypesUpdated

	// appliesToProxy starts as false, we will set it to true if we encounter any configs that require a push
	appliesToProxy := false
	// If no config specified, this request applies to all proxies
	if len(configs) == 0 {
		appliesToProxy = true
	}
	for config := range configs {
		if config == schemas.Gateway.Type && proxy.Type == model.SidecarProxy {
			// Gateways do not impact sidecars, so no need to push
		} else {
			// This config may impact the proxy, so we do need to push
			appliesToProxy = true
		}
	}

	if !appliesToProxy {
		return false
	}

	// If no only namespaces specified, this request applies to all proxies
	if len(targetNamespaces) == 0 {
		return true
	}

	// Otherwise, only apply if the egress listener will import the config present in the update
	for ns := range targetNamespaces {
		if proxy.SidecarScope.DependsOnNamespace(ns) {
			return true
		}
	}
	return false
}

func (s *DiscoveryServer) addCon(conID string, con *XdsConnection) {
	adsClientsMutex.Lock()
	defer adsClientsMutex.Unlock()
	adsClients[conID] = con
	xdsClients.Record(float64(len(adsClients)))
	if con.node != nil {
		node := con.node

		if _, ok := adsSidecarIDConnectionsMap[node.ID]; !ok {
			adsSidecarIDConnectionsMap[node.ID] = map[string]*XdsConnection{conID: con}
		} else {
			adsSidecarIDConnectionsMap[node.ID][conID] = con
		}
	}
}

func (s *DiscoveryServer) removeCon(conID string, con *XdsConnection) {
	adsClientsMutex.Lock()
	defer adsClientsMutex.Unlock()

	for _, c := range con.Clusters {
		s.removeEdsCon(c, conID)
	}

	if _, exist := adsClients[conID]; !exist {
		adsLog.Errorf("ADS: Removing connection for non-existing node:%v.", conID)
		totalXDSInternalErrors.Increment()
	} else {
		delete(adsClients, conID)
	}

	xdsClients.Record(float64(len(adsClients)))
	if con.node != nil {
		node := con.node

		delete(adsSidecarIDConnectionsMap[node.ID], conID)
		if len(adsSidecarIDConnectionsMap[node.ID]) == 0 {
			delete(adsSidecarIDConnectionsMap, node.ID)
		}
	}
}

// Send with timeout
func (conn *XdsConnection) send(res *xdsapi.DiscoveryResponse) error {
	done := make(chan error, 1)
	// hardcoded for now - not sure if we need a setting
	t := time.NewTimer(SendTimeout)
	go func() {
		err := conn.stream.Send(res)
		done <- err
		conn.mu.Lock()
		if res.Nonce != "" {
			switch res.TypeUrl {
			case ClusterType:
				conn.ClusterNonceSent = res.Nonce
			case ListenerType:
				conn.ListenerNonceSent = res.Nonce
			case RouteType:
				conn.RouteNonceSent = res.Nonce
			case EndpointType:
				conn.EndpointNonceSent = res.Nonce
			}
		}
		if res.TypeUrl == RouteType {
			conn.RouteVersionInfoSent = res.VersionInfo
		}
		conn.mu.Unlock()
	}()
	select {
	case <-t.C:
		// TODO: wait for ACK
		adsLog.Infof("Timeout writing %s", conn.ConID)
		xdsResponseWriteTimeouts.Increment()
		return errors.New("timeout sending")
	case err := <-done:
		t.Stop()
		return err
	}
}


text:
package org.aksw.sparqlify.qa.metrics.consistency;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.aksw.sparqlify.core.algorithms.ViewQuad;
import org.aksw.sparqlify.core.domain.input.ViewDefinition;
import org.aksw.sparqlify.qa.dataset.SparqlifyDataset;
import org.aksw.sparqlify.qa.exceptions.NotImplementedException;
import org.aksw.sparqlify.qa.metrics.DatasetMetric;
import org.aksw.sparqlify.qa.metrics.MetricImpl;
import org.aksw.sparqlify.qa.pinpointing.Pinpointer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;

/**
 * This metric should find resources that are
 * - defined as a property but also appear on subject or object positions in
 *   other triples (except cases like ex:prop rdf:type rdfs:Property, ex:prop
 *   rds:subPropetyOf)
 * - defined as a class but also appear on predicate position in other triples
 *
 * To find such properties for every triple predicate it is checked if it also
 * appears in subject position in connection with a not explicitly allowed
 * property. Such allowed properties can be found in the
 * propertyOnSubjPosWhitelist class attribute. Another whitelist check is
 * performed if the considered property appears on object position of other
 * triples (see propertiesOnObjPosWhitelist).
 * So this explicit whitelist approach does not cover properties that would
 * also be allowed and could be found through inference.
 *
 * For all classes it is checked if any of them appears in predicate position:
 * If so an error is reported.
 *
 * @author Patrick Westphal <patrick.westphal@informatik.uni-leipzig.de>
 *
 */
@Component
public class WellPlacedClassesAndProperties extends MetricImpl implements
		DatasetMetric {

	@Autowired
	private Pinpointer pinpointer;

	private final List<String> propertyOnSubjPosWhitelist = new ArrayList<String>(
			Arrays.asList( RDF.type.getURI(), RDFS.subPropertyOf.getURI(),
					OWL.equivalentProperty.getURI(), OWL.inverseOf.getURI(),
					RDFS.domain.getURI(), RDFS.range.getURI(),
					RDFS.label.getURI(), RDFS.comment.getURI()));

	private final List<String> propertyOnObjPosWhitelist = new ArrayList<String>(
			Arrays.asList(RDFS.subPropertyOf.getURI(),
					OWL.equivalentProperty.getURI(), OWL.inverseOf.getURI(),
					OWL.onProperty.getURI()));

	@Override
	public void assessDataset(SparqlifyDataset dataset)
			throws NotImplementedException, SQLException {

		/* ====================================================================
		 * checks for wrong-placed properties
		 */
		List<String> propertyClsUris = new ArrayList<String>(Arrays.asList(
				RDF.Property.getURI(), OWL.AnnotationProperty.getURI(),
				OWL.DatatypeProperty.getURI(), OWL.DeprecatedProperty.getURI(),
				OWL.FunctionalProperty.getURI(),
				OWL.InverseFunctionalProperty.getURI(),
				OWL.ObjectProperty.getURI(), OWL.OntologyProperty.getURI(),
				OWL.SymmetricProperty.getURI(), OWL.TransitiveProperty.getURI()
			));

		Set<Node> properties = new HashSet<Node>();

		String genPropQueryStr = "SELECT distinct ?p { ?s ?p ?o }";
		Query genPropQuery = QueryFactory.create(genPropQueryStr);
		QueryExecution genPropQe;
		if (dataset.isSparqlService() && dataset.getSparqlServiceUri()!=null) {
			genPropQe = QueryExecutionFactory.createServiceRequest(dataset.getSparqlServiceUri(), genPropQuery);
		} else {
			genPropQe = QueryExecutionFactory.create(genPropQuery, dataset);
		}
		ResultSet genPropRes = genPropQe.execSelect();

		while (genPropRes.hasNext()) {
			QuerySolution sol = genPropRes.next();
			Node prop = sol.get("p").asNode();
			properties.add(prop);
		}
		genPropQe.close();

		for(String propUri : propertyClsUris) {
			String propQueryStr =
				"SELECT ?p {" +
					"{ ?p a <" + propUri + "> } UNION " +
					"{ ?p a ?cls. ?cls <" + RDFS.subClassOf.getURI() + ">+ <" + propUri + "> }" +
				"}";
			Query propQuery = QueryFactory.create(propQueryStr);

			QueryExecution propQe;
			if (dataset.isSparqlService() && dataset.getSparqlServiceUri()!=null) {
				propQe = QueryExecutionFactory.createServiceRequest(dataset.getSparqlServiceUri(), propQuery);
			} else {
				propQe = QueryExecutionFactory.create(propQuery, dataset);
			}

			ResultSet propRes = propQe.execSelect();

			while(propRes.hasNext()) {
				QuerySolution sol = propRes.next();
				Node pred = sol.get("p").asNode();
				properties.add(pred);
			}
			propQe.close();
		}

		for (Node prop : properties) {

			// property is on subject position...
			String propSubjQueryStr = "SELECT * { <" + prop.getURI() + "> ?p ?o }";
			Query propSubjQuery = QueryFactory.create(propSubjQueryStr);

			QueryExecution propSubjQe;
			if (dataset.isSparqlService() && dataset.getSparqlServiceUri()!=null) {
				propSubjQe = QueryExecutionFactory.createServiceRequest(
						dataset.getSparqlServiceUri(), propSubjQuery);
			} else {
				propSubjQe = QueryExecutionFactory.create(propSubjQuery, dataset);
			}

			ResultSet propSubjRes = propSubjQe.execSelect();

			while(propSubjRes.hasNext()) {
				QuerySolution sol = propSubjRes.nextSolution();
				Node pred = sol.get("p").asNode();
				Node obj = sol.get("o").asNode();

				if (!propertyOnSubjPosWhitelist.contains(pred.getURI())) {
					// ...and used in connection with a predicate that is not
					// whitelisted explicitly

					Triple triple = new Triple(prop, pred, obj);
					Set<ViewQuad<ViewDefinition>> viewQuads =
							pinpointer.getViewCandidates(triple);

					writeTripleMeasureToSink(0, triple, viewQuads);
				}

			}

			// property is on object position...
			String propObjQueryStr = "SELECT * { ?s ?p <" + prop.getURI() + "> }";
			Query propObjQuery = QueryFactory.create(propObjQueryStr);

			QueryExecution propObjQe;
			if (dataset.isSparqlService() && dataset.getSparqlServiceUri()!=null) {
				propObjQe = QueryExecutionFactory.createServiceRequest(
						dataset.getSparqlServiceUri(), propObjQuery);
			} else {
				propObjQe = QueryExecutionFactory.create(propObjQuery, dataset);
			}

			ResultSet propObjRes = propObjQe.execSelect();

			while(propObjRes.hasNext())
			{
				QuerySolution sol = propObjRes.nextSolution();
				Node subj = sol.get("s").asNode();
				Node pred = sol.get("p").asNode();

				if (!propertyOnObjPosWhitelist.contains(pred.getURI())) {
					// ...and used in connection with a predicate that is not
					// whitelisted explicitly

					Triple triple = new Triple(subj, pred, prop);
					Set<ViewQuad<ViewDefinition>> viewQuads =
							pinpointer.getViewCandidates(triple);

					writeTripleMeasureToSink(0, triple, viewQuads);
				}

			}
		}

		/*
		 * In a second step a more throughout query would be required, e.g.
		 * using the query below. But this query was not used due to
		 * performance problems
		 */
//		String propQueryStr =
//				"SELECT distinct ?p {" +
//					"{ ?s ?p ?o } UNION " +
					// is (subclass of) rdf:Property
//					"{ ?p a <" + RDF.Property.getURI() + "> } UNION " +
//					"{ ?p a ?cls. ?cls <" + RDFS.subClassOf.getURI() + ">+ <" + RDF.Property.getURI() + "> } UNION " +
					// is (subclass of) owl:AnnotationProperty
//					"{ ?p a <" + OWL.AnnotationProperty.getURI() + "> } UNION " +
//					"{ ?p a ?cls. ?cls <" + RDFS.subClassOf.getURI() + ">+ <" + OWL.AnnotationProperty.getURI() + "> } UNION " +
					// is (subclass of) owl:DatatypeProperty
//					"{ ?p a <" + OWL.DatatypeProperty.getURI() + "> } UNION " +
//					"{ ?p a ?cls. ?cls <" + RDFS.subClassOf.getURI() + ">+ <" + OWL.DatatypeProperty.getURI() + "> } UNION " +
					// is (subclass of) owl:DeprecatedProperty
//					"{ ?p a <" + OWL.DeprecatedProperty.getURI() + "> } UNION " +
//					"{ ?p a ?cls. ?cls <" + RDFS.subClassOf.getURI() + ">+ <" + OWL.DeprecatedProperty.getURI() + "> } UNION " +
					// is (subclass of) owl:FunctionalProperty
//					"{ ?p a <" + OWL.FunctionalProperty.getURI() + "> } UNION " +
//					"{ ?p a ?cls. ?cls <" + RDFS.subClassOf.getURI() + ">+ <" + OWL.FunctionalProperty.getURI() + "> } UNION " +
					// is (subclass of) owl:InverseFunctionalProperty
//					"{ ?p a <" + OWL.InverseFunctionalProperty.getURI() + "> } UNION " +
//					"{ ?p a ?cls. ?cls <" + RDFS.subClassOf.getURI() + ">+ <" + OWL.InverseFunctionalProperty.getURI() + "> } UNION " +
					// is (subclass of) owl:ObjectProperty
//					"{ ?p a <" + OWL.ObjectProperty.getURI() + "> } UNION " +
//					"{ ?p a ?cls. ?cls <" + RDFS.subClassOf.getURI() + ">+ <" + OWL.ObjectProperty.getURI() + "> } UNION " +
					// is (subclass of) owl:OntologyProperty
//					"{ ?p a <" + OWL.OntologyProperty.getURI() + "> } UNION " +
//					"{ ?p a ?cls. ?cls <" + RDFS.subClassOf.getURI() + ">+ <" + OWL.OntologyProperty.getURI() + "> } UNION " +
					// is (subclass of) owl:SymmetricProperty
//					"{ ?p a <" + OWL.SymmetricProperty.getURI() + "> } UNION " +
//					"{ ?p a ?cls. ?cls <" + RDFS.subClassOf.getURI() + ">+ <" + OWL.SymmetricProperty.getURI() + "> } UNION " +
					// is (subclass of) owl:TransitiveProperty
//					"{ ?p a <" + OWL.TransitiveProperty.getURI() + "> } UNION " +
//					"{ ?p a ?cls. ?cls <" + RDFS.subClassOf.getURI() + ">+ <" + OWL.TransitiveProperty.getURI() + "> } " +
//				"}";

		/* ====================================================================
		 * checks for wrong-placed classes
		 */

		// get classes
		List<String> clsUris = new ArrayList<String>(Arrays.asList(
				RDFS.Class.getURI(), OWL.Class.getURI()
			));

		Set<Node> classes = new HashSet<Node>();

		String genClsQueryStr = "SELECT distinct ?cls { ?s a ?cls }";
		Query genClsQuery = QueryFactory.create(genClsQueryStr);
		QueryExecution genClsQe;
		if (dataset.isSparqlService() && dataset.getSparqlServiceUri()!=null) {
			genClsQe = QueryExecutionFactory.createServiceRequest(dataset.getSparqlServiceUri(), genClsQuery);
		} else {
			genClsQe = QueryExecutionFactory.create(genClsQuery, dataset);
		}
		ResultSet genClsRes = genClsQe.execSelect();
		while (genClsRes.hasNext()) {
			QuerySolution sol = genClsRes.next();
			Node cls = sol.get("cls").asNode();
			classes.add(cls);
		}
		genClsQe.close();

		for(String clsUri : clsUris) {
			String clsQueryStr =
				"SELECT ?cls {" +
					"{ ?cls a <" + clsUri + "> } UNION " +
					"{ ?cls a ?sth. ?sth <" + RDFS.subClassOf.getURI() + ">+ <" + clsUri + "> }" +
				"}";
			Query clsQuery = QueryFactory.create(clsQueryStr);

			QueryExecution clsQe;
			if (dataset.isSparqlService() && dataset.getSparqlServiceUri()!=null) {
				clsQe = QueryExecutionFactory.createServiceRequest(dataset.getSparqlServiceUri(), clsQuery);
			} else {
				clsQe = QueryExecutionFactory.create(clsQuery, dataset);
			}

			ResultSet clsRes = clsQe.execSelect();

			while(clsRes.hasNext()) {
				QuerySolution sol = clsRes.next();
				Node cls = sol.get("cls").asNode();
				classes.add(cls);
			}
			clsQe.close();
		}

		for (Node cls : classes) {

			if (cls.isBlank()) continue;
			String clsPredQueryStr = "SELECT * { ?s <" + cls.getURI() + "> ?o }";

			Query clsPredQuery = QueryFactory.create(clsPredQueryStr);

			QueryExecution clsPredQe;
			if (dataset.isSparqlService() && dataset.getSparqlServiceUri()!=null) {
				clsPredQe = QueryExecutionFactory.createServiceRequest(
						dataset.getSparqlServiceUri(), clsPredQuery);
			} else {
				clsPredQe = QueryExecutionFactory.create(clsPredQuery, dataset);
			}

			ResultSet clsPredRes = clsPredQe.execSelect();

			while (clsPredRes.hasNext()) {
				QuerySolution sol = clsPredRes.nextSolution();
				Node subj = sol.get("s").asNode();
				Node obj = sol.get("o").asNode();
				Triple triple = new Triple(subj, cls, obj);

				Set<ViewQuad<ViewDefinition>> viewQuads =
						pinpointer.getViewCandidates(triple);

				writeTripleMeasureToSink(0, triple, viewQuads);
			}
		}

	}

}


text:
drop view if exists v1;
drop table if exists t1;

create table t1 (a int);
insert into t1 select rownum from db_class limit 20;

create view v1 as select * from t1 order by 1 limit 0, (2+2)/2 ;
select * from v1;

alter view v1 add query select * from t1 order by 1 limit 0+1*(1-1)/1, (2+2*3)/(2-1);
select * from v1 limit 3+3;
show create view v1;

alter view v1 as select * from t1 order by t1.a limit 0, (2+2)/2 ;
select * from v1;

alter view v1 add query select * from t1 order by t1.a limit 0+1*(1-1)/1, (2+2*3)/(2-1);
select * from v1;
show create view v1;

drop view if exists v1;
drop table if exists t1;
--+ holdcas off;