text:
Q: If Value is Equal to Anchor's Text then Change it's CSS Fiddle 1 = http://liveweave.com/gG4EHH
Fiddle 2 = http://jsbin.com/zequyilo/1/edit
I have a set of anchors that I click to change a selected elements CSS (In this case the font-family attribute)
What I'm trying to do is type the font in a textbox and if the font is one of the fonts in the anchor list to change it's css according to the text.
I'd like to use a method of something like this where if the input value is equal to the anchor's text to change it's css, but not exactly sure on how to go about it.
$('.grab-font-family').on('keyup change', function() {
  $('.grab-typography a').css('backgroundColor', '#444');
  if ( $('.grab-typography a').text() === $(this).val() ) {
     $(this).css('backgroundColor', '#1c1c1c');
  }
});

I tried this method using the title attribute, but when I tried arial black, or andale mono the anchor that has that title. it's background was not changed.
$('.grab-font-family').on('keyup change', function() {
  $('.grab-typography a').css('backgroundColor', '#444');
  $(".grab-typography a[title=" + $(this).val() + "]").css('backgroundColor', '#1c1c1c');
});

So I tried using the contains selector. If I type a in the textbox this methos will change all the anchor's background colors that begin with an a.
$('.grab-font-family').on('keyup change', function() {
  $('.grab-typography a').css('backgroundColor', '#444');
  $(".grab-typography a:contains(" + $(this).val() + ")").css('backgroundColor', '#1c1c1c');
});

A: filter() is the most controllable way. Your first approach is only pulling the text() of first element in the collection. This is the same for all getters when there are more than one element in the collection.
filter() will loop over all elements and let you run more involved conditions
Make sure to quote fonts that have spaces in them or they will be misinterpreted by browser
$('.grab-font-family').on('keyup change', function() {
  var font=this.value;
  $('.grab-typography a').filter(function(){
     return this.title === font;/* return ones that match font */
  }).css('font-family', '"'+font+'"'});
})


text:
Q: Type definition for functions in Typescript In a recent coding situation, I found out that (A)onPress?(): void is a valid alternative for (B) onPress?: () => void. I do prefer B over A, because it looks like it's more common in the TypeScript community and because of the consistency of defining your prop name, ? if necessary for optional props, separated by a : and then your type.
My question is: is there any documentation why A is also correct, or in which way it's different from B? Or is it just the same? Or is one of both more preferred?
Thanks in advance!
type Props = {
   onPress?(): void
}

type OtherProps = {
   onPress?: () => void
}

const instanceOfProps: Props = {
    onPress: () => {}
}

const instanceOfOtherProps: OtherProps = {
    onPress: () => {}
}

A: A is just syntax sugar for B in this case. I believe it's based on ES6 object initializers, which support using onPress() {...} for a function value. However since you're creating a type, TypeScript is only concerned with types and not implementations, so {...} is replaced with : type.
Personally I prefer A, as it's shorter, more consistent with ES6, and looks more like a property type in TypeScript.

redpajama_set_name: RedPajamaStackExchange


text:
Q: sqlContext.sql returnts table with count 0 , pyspark I'm running a spark application, using EMR through pyspark interactive shell.
I'm trying to connect to a hive table named: content_publisher_events_log which I know that is isn't empty (through my hue console using exactly the same query), though when I try to read it throuhg pyspark I get count=0 as following:
from pyspark.sql import HiveContext
Query=""" select dt
from default.content_publisher_events_log
where  dt  between  '20170415'  and '20170419'
"""
hive_context = HiveContext(sc)
user_data = hive_context.sql(Query)
user_data.count()
0 #that's the result

Also, from the console i can see that this table exists:
    >>> sqlContext.sql("show tables").show()
+--------+--------------------+-----------+
|database|           tableName|isTemporary|
+--------+--------------------+-----------+
| default|content_publisher...|      false|
| default|  feed_installer_log|      false|
| default|keyword_based_ads...|      false|
| default|search_providers_log|      false|
+--------+--------------------+-----------+

>>> user_data.printSchema()
root
 |-- dt: string (nullable = true)

Also checked on the spark history server - seems like the job that ran the count worked without any errors, any idea on what could go wrong?
Thank's in advance!

A: The dt column isnt in datetime format . Either properly change the column itself to have datetime format or change the query itself to cast string as timestamp
Query=""" select dt
from default.content_publisher_events_log
where  dt  between
unix_timestamp('20170415','yyyyMMdd')  and
unix_timestamp('20170419','yyyyMMdd')
"""

A: It seems like our data team moved per each partition the parquet file into a subfolder, they fixed it and starting from April 25th it works perfectly.
As far as i know if anyone is facing this isseue, try something like this one:
sqlContext.sql("SET hive.mapred.supports.subdirectories=true")
sqlContext.sql("SET mapreduce.input.fileinputformat.input.dir.recursive=true")

or this one:
sc._jsc.hadoopConfiguration().set("mapreduce.input.fileinputformat.input.dir.recursive","true")


text:
Q: Script to Create a Monthly folder and move files to it every month I have been given a business requirement to move some files every month into a file folder format similar to the below. I have used powershell before to move files to a folder that already exists and I have read some things about powershell creating and naming folders but is there a way to do it monthly without changing the folder name it creates every month?
Client 1
Reports 2018
01Jan
02Feb
03Mar
etc.
Client 2
Reports 2018
01Jan
02Feb
03Mar
etc.

So ideally, it would be a script that would create a folder for the month it is run and then move all files in a directory that were created/modified that month into their monthly folder.
Is this possible?
some code I have tried:
Get-ChildItem \\test\d$\Reports*.xlsx -Recurse | foreach {
$x = $_.LastWriteTime.ToShortDateString()
$new_folder_name = Get-Date $x -Format yyyy.MM
$des_path = "c:\test\test2\$new_folder_name"

if (test-path $des_path){
    move-item $_.fullname $des_path
    } else {
    new-item -ItemType directory -Path $des_path
    move-item $_.fullname $des_path
    }
}
::
cd "\\test\d$\Reports\client1"
$fso = new-object -ComObject scripting.filesystemobject
$fso.CreateFolder("\03Mar")
cd "\\test\d$\Reports\client2"
$fso = new-object -ComObject scripting.filesystemobject
$fso.CreateFolder("\03Mar")

repeat for 20 clients but as you could tell this gets hard to keep up with every month since you have to go update the 03 to 04 and mar to april and further on.
EDIT:
As requested the structure is as follows:
Client 1 - folder
Saved Reports - folder
2017 - folder
01Jan - folder
  report 1
02Feb - folder
2018 - folder
01Jan - folder
02Feb - folder

Repeating for 20+ clients
Also EDIT:
# Get the files which should be moved, without folders
$files = Get-ChildItem '\\test\d$\Reports\client\saved reports' -Recurse | where {!$_.PsIsContainer}

# List Files which will be moved
$files

# Target Filder where files should be moved to. The script will automatically create a folder for the year and month.
$targetPath = '\\test\d$\Reports\client\2018 client reports'

foreach ($file in $files)
{
# Get year and Month of the file
# I used LastWriteTime since this are synced files and the creation day will be the date when it was synced
$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString("00")
$monthname = (Get-Culture).DateTimeFormat.GetAbbreviatedMonthName($month)

# Out FileName, year and month
$file.Name
$year
$month
$monthname

# Set Directory Path
$Directory = $targetPath + "\" + $month + $monthname

# Create directory if it doesn't exsist
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}

# Move File to new location
$file | Move-Item -Destination $Directory
}

The above seems to be working, but I have to have this entire block of code for every client and will have to change the year each time, any way to generalize this or not?
Last Edit:
Also -- is there a way to do $month -1 so the folder says the last month name not the current month name?
Thanks,

A: You will need to use the following Cmdlets:
New-Item -Path $path -Name "$((Get-Date).Month)_$((Get-Date).Year)" -ItemType Directory

Get-ChildItem $directoryWTheFiles -File -Recurse | where {$_.CreationTime.Month -eq ((Get-Date).Month) -or $_.LastWriteTime.Month -eq ((Get-Date).Month)} | Move-Item -Destination $dest

I haven't tested it, but this should get you to a 70% completion on that script.

A: Here is what I have so far... it is just an expansion on Roque Sosa's answer
$folderName = "$(Get-Date -format MM)$(Get-Date -format MMM)"
New-Item -Path $path -Name $folderName -ItemType Directory
$destination = "$path/$folderName/"
Get-ChildItem $directoryWTheFiles -File -Recurse |
    Where-Object {$_.LastWriteTime.Month -eq ((Get-Date).Month) -and $_.LastWriteTime.Year -eq ((Get-Date).Year)} |
        Move-Item -Destination $destination

This at least gets the folder name formatted correctly as you have shown above. Then it also moves the files that match the month and year of the lastwritetime attribute.
Once you give me the structure of the client folders you are searching I can update more specific to your situation.

A: I managed to find an answer to this, thank you for your help.
I have updated my post with the code.
Thanks again


text:
Q: Nginx force redirect or rewrite mp3 url path I have this mp3 url:
http://example.com/downloads/low_quality/songs/song_name.mp3
and i want force rewrite to this url without allow downloading first url:
http://example.com/downloads/high_quality/songs/song_name.mp3
Indeed i need replace low_quality with high_quality path. I trying use alias and rewrite, but not working. it start downloading first url low_quality.
location /downloads/low_quality/ {
    alias /downloads/high_quality/;
}

or
location ~* ^/downloads/low_quality/(.*)$ {
    rewrite ^/downloads/low_quality/(.*)$ http://example.com/downloads/high_quality/$1 permanent;
    break;
}
// but low quality download started!

low_quality file always is exists but i don't want downloading when requested. i want redirect(rewrite) to second url high_quality.

A: according to https://www.nginx.com/blog/creating-nginx-rewrite-rules/
this is true rewrite:
rewrite ^/downloads/low_quality/songs/(\w+)\.?.*$ /downloads/high_quality/songs/$1.mp3 last;

high quality requested and downloaded.


text:
Q: Left align labels in itemize I want my itemize environment to output something like
Email:     my@email.com

Address:   Street name
           City
           Country

Phone:     My phone number

I have tried using \usepackage{enumitem} and \setitemize{leftmargin=*, align=left} but the output is just
Email: my@email.com

Address: Street name
  City
  Country

Phone: My phone number

I could probably accomplish what I want with a table, but shouldn't it be possible to do the same with itemize?

A: You can simply modify some parameters of a description environment:
\documentclass{article}
\usepackage{enumitem}

\begin{document}

\begin{description}[labelwidth=4em,leftmargin =\dimexpr\labelwidth+\labelsep\relax, font=\sffamily\mdseries]
\item[Email:] my@email.com

\item[Address:] Street name\\
                    City\\
                    Country

\item[Phone:] My phone number
\end{description}

\end{document}

A: Another solution :
\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[french]{babel}
\usepackage{enumitem}
\begin{document}
\begin{enumerate}[align=parleft, labelsep=2cm,]
\item[test1:] premier item;
\item[Coucou:] deuxième item;\\
  line 2
\item[test\_auto:] troisième item.
\end{enumerate}
\end{document}

A: You may want to use tabbing:
\documentclass{article}

\begin{document}

\begin{tabbing}
Address: \=\kill
Email:   \> my@email.com \\[1ex]
Address: \> Street name \\
         \> City \\
         \> Country \\[1ex]
Phone:   \> My phone number
\end{tabbing}

\end{document}

If you have to compile a directory, use \\* instead of \\ so no page break can happen inside an entry.
It wouldn't also be difficult providing an interface such as
\personaldata{
  email   = my@email.com,
  address = Street name \\ City \\ Country,
  phone   = +55 555 555 5555,
}

A: Design own list! From "The LaTeX Companion":
\documentclass{article}
    \usepackage{calc}
    \usepackage{hyperref}

\newcommand{\entrylabel}[1]{%
     \makebox[\labelwidth][l]{\parbox[t]{\labelwidth}{\raggedleft#1}}%
                             }% end of definition

\newenvironment{entry}[1]%
    {\begin{list}{}{%
        \renewcommand{\makelabel}{\entrylabel}%
        \settowidth{\labelwidth}{#1:~}%
        \setlength{\leftmargin}{\labelwidth + \labelsep}
        \setlength{\listparindent}{2ex}%
        \setlength{\parsep}{0.2\baselineskip}
        \setlength{\itemsep}{0.2\baselineskip}
    }}%
    {\end{list}}

\begin{document}
    \begin{entry}{Address:}
\item[e-mail:]      \href{mailto:my@email.com}{my@email.com}
\item[Address:]     Street name\\
                    City\\
                    Country
\item[Phone:]       My phone number
    \end{entry}
\end{document}

Of course, similar result you can obtain with enumitem. In this case you need define adequate labelwidth.

A: for this use can just use \item[•]
\documentclass{article}
\usepackage{enumitem}

\begin{document}

\begin{enumerate}[leftmargin=*]
\item[Email:]       my@email.com

\item[Address:]     Street name\\
                    City\\
                    Country

\item[Phone:]       My phone number
\end{enumerate}

\end{document}


text:
Q: Does this sequence converge to $0$? In a similar vain as my previous question, I was wondering whether the following converges to $0:$
$$
a_n = \left\{
  \begin{array}{l l}
    1 & \quad n=2^k\,\text{for some}\,k\in\mathbb{N}_0\\
    0 & \quad \text{otherwise}
  \end{array} \right.$$
First terms are:
$$1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0\cdots$$
In other words, the $1$'s get more and more separated. Again, as in the other question, intuitively it would seem that "at infinity", the string of $0$'s is infinite, but since intuition can often be erroneous in cases like these, I am not convinced. Can someone enlighten me here?
Follow-up:
Can I conclude from the commments and answers that a sequence of integers that converges to $0$ must be $0$ for $n$ sufficiently large?

A: For $\epsilon=\frac12$, there is no $N\in \mathbb N$ with the property that for all indices $n>N$ we have $|a_n|<\epsilon$.
Even though they are somewhat rare, terms $a_n$ with $a_n=1>\epsilon$ occur again and again. (To be explicit, we can consider $n=2^N$, which is $>N$ and gives us $a_n=1$).
There is something behind this: The sequence indeed converges to zero in a less strict sense so to speak, see Cesáro mean.

A: The other answers are good, this is more of a side-topic or another place to look.
There is a notion of something called the "Cesàro mean." Given a convergent sequence, the Cesàro mean is just the limit. But the Cesàro mean also gives a value for some non-convergent sequences.
For example, $-1,1,-1,1,\dots$ has Cesàro mean zero, but does not have a limit.
Your series has Cesàro mean zero, too.

A: No.  A sequence converges to zero if and only if we can eventually make all the terms which are large enough as close to zero as we want.  In symbols, $a_n \to a$ if for all $\epsilon > 0$, there exists a constant $M$ so that $n > M$ implies $|a_n - a| < \epsilon$.
This cannot happen with your example, since every entry that is a power of two will be $1$.


text:
Q: non blocking info dialog in Tkinter I need a simple info box to display some status output, that I would alternatively dump to the console using print. The easiest possibility that I found is the following:
import Tkinter as tk
root = tk.Tk()
root.withdraw()

from tkMessageBox import showinfo
showinfo('some caption', 'some info')

The only problem with this implementation is that my program (not written in Tkinter) will not continue running, until the 'ok' button of the showinfo messagebox is pressed. That is, the showinfo dialog will block.
Therefore my question: Is there a simple way to make showinfo non-blocking? Are there alternative messagebox implementations in Tkinter that are non-blocking? I can think of the typical use-cage of showing a help page - the window should open and the main program keeps on running normally.
EDIT1: here's a simple help window that I came up with, but unfortunately it doesn't show up, unless I launch a different tkMessageBox or a similar object:
class TextInfo(object):

    def __init__(self, parent, window_title = 'window', textfield = 'a text field', label = None):

        self.top = tk.Toplevel(parent)
        self.parent = parent
        self.window_title = window_title
        self.textfield = textfield

        # set window title
        if window_title:
            self.top.title(window_title)

        # add label if given
        if label:
            tk.Label(self.top, text=window_title).grid(row=0)

        # create the text field
        self.textField = tk.Text(self.top, width=80, height=20, wrap=tk.NONE)
        if textfield:
            self.textField.insert(1.0, textfield)
        self.textField.grid(row=1)

        # create the ok button
        b = tk.Button(self.top, text="OK", command=self.ok)
        b.grid(row=2)

    def ok(self):
        self.top.destroy()

And this is how I call the window:
root = tk.Tk()
root.withdraw()
TextInfo(self.root, window_title, textfield, label)
# don't call root.mainloop() here, because this will lead to blocking.

Is there some kind of property or event that I need to set for the window to show up? If I call root.mainloop() the window will show up, but then my GUI is blocked again.

A: Don't use the tkMessageBox as it doesn't allow much configuration. Just create your own custom dialog that looks like one. This page talks a lot about creating custom Tkinter dialogs.


text:
Q: Using TControlBar, how do I limit the movement of the bands to a single row? I have use for the TControlBar component in my current project but I'm having issues with the control drawing extra rows when I'm moving the bands around,
basically what I want is the ControlBar to always only have 1 Row which is of fixed Height, and where the bands can't escape it while being dragged.
How can I achieve this ?

A: You can do a workaround for this:
procedure TForm1.ControlBar1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var R:TRect;
    Pt:TPoint;

begin
  Pt:=ControlBar1.ClientToScreen(Point(0,Y));
  R.Left:=Pt.X;
  R.Top:=Pt.Y;
  R.Right:=Pt.X+ControlBar1.Width;
  R.Bottom:=Pt.Y;
  ClipCursor(@R);
end;

procedure TForm1.ControlBar1MouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  ClipCursor(nil) ;
end;

With that you can restrict the mouse movement to allow only vertical positioning of the Bands.

A: I solved this months ago by basically deriving my own component from the TPanel class and implementing a drag solution of child panels to mimic the behavior I wanted.
This is the most basic principle I used to implement the desired effect :
var oldPos : TPoint;

procedure TMainForm.ControlMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer);

begin

   if Button = mbLeft then
     if (Sender is TWinControl) then
     begin
      inReposition:=True;
      SetCapture(TWinControl(Sender).Handle);
      GetCursorPos(oldPos);
      TWinControl(Sender).BringToFront;
     end else
        ((Sender as TLabel).Parent as TQPanelSub).OnMouseDown((Sender as TLabel).Parent as TQPanelSub,Button,Shift,X,Y)

end;

procedure TMainForm.ControlMouseMove(Sender: TObject; Shift: TShiftState; X: Integer; Y: Integer);
var
  newPos: TPoint;
  temp : integer;

begin

  if (Sender is TWinControl) then begin

    if inReposition then
    begin

      with TWinControl(Sender) do
      begin
        GetCursorPos(newPos);
        Screen.Cursor := crSize;
        (* Constrain to the container *)
        Top := 0;
        temp := Left - oldPos.X + newPos.X;
        if (temp >= 0) and (temp <= (Parent.Width - Width))
        then Left := temp;
        oldPos := newPos;
      end;

    end;

  end else
    ((Sender as TLabel).Parent as TQPanelSub).OnMouseMove((Sender as TLabel).Parent as TQPanelSub,Shift,X,Y);

end;

procedure TMainForm.ControlMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer);
begin

   if inReposition then
  begin
    Screen.Cursor := crDefault;
    ReleaseCapture;
    inReposition := False;
  end;

end;

This is just the basis that I wanted from the TControlBar which infact is a horribly written component.


text:
Q: How to get my angular controller to reload data I have an angular app with three views. When it loads it runs some code to populate the $scope variables. When I change views and then go back to the controller I want the initial code to run again but it doesn't. It seems it is cached and the $scope variables are not updated based on what happened.
How can I force the controller to run the initialisation code every time the view is loaded?
My routes:
app.config(function ($routeProvider) {
  $routeProvider
    .when('/', {
        controller: 'HomeController',
        templateUrl: 'home.html'
    })
    .when('/teach', {
      controller: 'TeachController',
      templateUrl: 'teach.html'
    })
    .otherwise({
        redirectTo: '/'
    });
});

The code I want to run every time the '/' route is clicked:
getSubPools.success(function(data) {
  $scope.userPools = data;
});

Controller in full:
app.controller('HomeController', ['$scope', '$filter', 'stream', 'removeDroplet', 'qrecords', 'helps', 'get_user', 'updateRecords', 'getSubPools', function($scope, $filter, stream, removeDroplet, qrecords, helps, get_user, updateRecords, getSubPools) {

  get_user.success(function(data) { //get current user
    $scope.user = data;
  });

  getSubPools.success(function(data) {
    $scope.userPools = data;
  });

  stream.success(function(data) {
    $scope.stream = data;
    if ($scope.stream.length === 0) { //determine if user has stream
      $scope.noStream = true;
    } else {
      $scope.noStream = false;
    }
    $scope.getNumberReady(); //determine if any droplets are ready
    if ($scope.numberReady === 0){
      $scope.noneReady = true;
    } else {
      $scope.noneReady = false;
      $scope.stream = $filter('orderBy')($scope.stream, 'next_ready'); //orders droplets by next ready
    }
  });

    $scope.showEditStream = true;
    $scope.showStream = false;
    $scope.rightAnswer = false;
    $scope.wrongAnswer = true;
    $scope.noneReady = false;
    $scope.subbedDroplets = [];
    $scope.focusInput = false;

}]);

A: You can use the $routeChangeStart and $routeChangeSuccess events to reload the data into the controller:
https://docs.angularjs.org/api/ngRoute/service/$route
Edit:
As mohan said as this will work for every route change, you can make a service to catch these events and for each route broadcast a special event.
And in the relevant controller/service listen to this event and reload data

A: If you want to force reload, then add an click function like follows,
Note: This will work only if you use $stateProvider
Home

and in controller ,
$scope.goToHome = function(){
    $state.transitionTo('home', {}, {reload:true});
}

A: The issue here was that on clicking the link to '/' not all of the initialisation code was rerunning. Rather than making calls to the database to get fresh data, angular was just returning old data. The way I fixed this was to rewrite my factories. The factories that were failing were written:
app.factory('stream', ['$http', function($http) {
  return $http.get('/stream/')
  .success(function(data) {
    return data;
  })
  .error(function(err) {
    return err;
  });
}]);

The factory that worked every time was written:
app.factory('stream', ['$http', function($http) {
  return {
    fetch: function () {
      return $http.get('/stream/');
    }
  }
}]);

Now it runs every time. I am not sure why though.


text:
Q: Deserializing protobuf from C++ and reserializing in C# gives different output I have a file with a protobuf message in it in byte format, when I read the file and deserialize the protobuf it works fine (I can read the objects fields and they are correct), however, when I reserialize it and save it back to a file, some bytes are different from the original (causing compatibility issues).
More specifically, after a string and before a bool theres the bytes '18 00' added.
I tried playing around with the DataFormat options from protobuf-net to get the exact same result as the original, but to no avail.
Does anyone know of any options in protobuf-net in regards to saving a string or a bool which could explain the extra 2 bytes?
Also, a ulong is being saved differently in bytes aswell.
I don't have control over the original file, I only know it's compiled/serialized with c++
My goal is to recreate the exact same file (bytewise) by serializing in c#, so it is identical to the file serialized by c++.

A: This comes down to how properties are handled. By default,
protogen -i:my.proto -o:my.cs

generates simple properties, of the form:
private bool _some_value = default(bool);
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"some_value",
    DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(default(bool))]
public bool some_value
{
  get { return _some_value; }
  set { _some_value = value; }
}

This is fine for most scenarios, but doesn't quite support every "was a value actually specified?" scenario.
However, you can do instead:
protogen -i:my.proto -o:my.cs -p:detectMissing

which generates the much more thorough:
private bool? _some_value;
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"some_value",
    DataFormat = global::ProtoBuf.DataFormat.Default)]
public bool some_value
{
  get { return _some_value?? default(bool); }
  set { _some_value = value; }
}
[global::System.Xml.Serialization.XmlIgnore]
[global::System.ComponentModel.Browsable(false)]
public bool some_valueSpecified
{
  get { return this._some_value != null; }
  set { if (value == (this._some_value== null))
      this._some_value = value ? this.some_value : (bool?)null; }
}
private bool ShouldSerializesome_value() { return some_valueSpecified; }
private void Resetsome_value() { some_valueSpecified = false; }

This has full support for tracking explicit assignment, including support for most UI-binding and serialization frameworks (not just protobuf-net).
The 2-byte difference is simply the difference between "false, not serialized due to implicit default value" and "false, known to be explicitly specified as false, and thus serialized".
So the fix is: include the -p:detectMissing when using protogen.


text:
Q: Running JUnit test suite using Maven I have written a JUnit test suite for running multiple test cases.
Now I want to run my test suite class (AllTest.java) at once so that all tests are triggered, carried and managed by one class. I know maven-failsafe-plugin is available, but is there any other easier way to invoke a JUnit test suite from Maven?
I dont want to use another plugin for this.
This is my current maven-failsafe-plugin configuration:
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-failsafe-plugin</artifactId>
  <version>2.9</version>
  <configuration>
    <includes>
      <include>**/AllTests.java</include>
    </includes>
  </configuration>
  <executions>
    <execution>
      <id>integration-test</id>
      <goals>
        <goal>integration-test</goal>
      </goals>
    </execution>
    <execution>
      <id>verify</id>
      <goals>
        <goal>verify</goal>
      </goals>
    </execution>
  </executions>
</plugin>

A: You can run test suite using following maven command:
 mvn test -Dtest=x.y.z.MyTestSuite

Note : x.y.z is the package name.

A: You can run it with -Dit.test=[package].AllTest (-Dtest with surefire), or configure the included tests in the pom:
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.1</version>
    <configuration>
      <includes>
        <include>AllTest.java</include>
      </includes>
    </configuration>
  </plugin>


text:
Q: appending zeroes to an integer variable in perl I have an integer value in perl, let's say $runid = 1, I need to create a new directory named R_00001 using mkdir R_$runid from the perl script. I am not able to append zeroes. "printf" does the trick for me when I print it but I am not able to figure out how to get this done. Please suggest some way.

A: sprintf("R_%05d", $runid)

A: You can use the concatenate operator in a nested anonymous function:
#! /usr/bin/perl

my $runid = 1 ;
mkdir (('R_0000' . $runid)) ;


text:
Q: How does an "auto voltage setting" laptop charger work? I recently came across a very interesting device for me, a laptop adapter that claims it adjusts its output voltage automatically:
https://www.trust.com/en/product/20194-plug-go-universal-90w-laptop-charger-black
The question is obvious: how can it possibly detect the voltage that the target laptop needs? I am planning to buy it but I have concerns over its safety.

A: There is no auto detection or other magic. The tip that fits your laptop also selects what voltage the power supply shall output, perhaps with by connecting a certain value resistance between two pins for selecting a certain voltage.

A: It could start with a low voltage, measure the current drawn by the laptop, and, if that current is very low, raise the output voltage  a little


text:
Q: Keyboard navigation in WPF Grids Suppose you have a StackPanel, which contains a ScrollViewer which contains another StackPanel with an ItemsControl with a bound ItemsSource. This ItemsSource is bound to a collection of Grids created at runtime. Each Grid contains a label and a textbox/combobox/a few checkboxes that all have a unique TabIndex value within the StackPanel.
Here is the xaml:
<ScrollViewer Name="scrollViewer" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
  <StackPanel Name="stackPanel" MinWidth="500" Width="Auto">
    <ItemsControl Name="itemsControl"                          ItemsSource="{Binding ElementName=SomeWindow, Path=GridsCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
  </StackPanel>
</ScrollViewer>

I want to simply tab from one control to the next, but only within the controls in the grids in the grids collection. So far I've tried different KeyboardNavigation.TabNavigation settings but without any luck. What is the best way to do this?

A: Set TabNavigation to KeyboardNavigationMode.Cycle for each container you want to behave like that, so the focus won't escape it as long as you use Tab and Shift+Tab:
KeyboardNavigation.SetTabNavigation(grid1, KeyboardNavigationMode.Cycle);

If you want to change Ctrl+Tab behaviour, use KeyboardNavigation.SetControlTabNavigation.

A: You can apply an implicit style that disables tabbing for every Control, then you re-enable it for just what you want to be tab-able:
<ScrollViewer Name="scrollViewer" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
  <ScrollViewer.Resources>
      <Style TargetType="Control">
          <Setter Property="IsTabStop" Value="False" />
      </Style>
  </ScrollViewer.Resources>
  <StackPanel Name="stackPanel" MinWidth="500" Width="Auto">
    <ItemsControl Name="itemsControl"
                  ItemsSource="{Binding ElementName=SomeWindow, Path=GridsCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
  </StackPanel>
</ScrollViewer>

Don't forget to set IsTabStop on your dynamically generated Grids to True


text:
Q: How can I stop an auto-generated Linq to SQL class from loading ALL data? UPDATE: from what I'm hearing, I was imagining the problem I describe below. So, this is pretty much a non-question. Future readers, move on... nothing to see here.

I have an ASP.NET MVC project, much like the NerdDinner tutorial example. (I'm using MVC 2, but followed the NerdDinner tutorial in order to create it).
As per the instructions in part 3 of the tutorial, I've created a Linq-to-SQL model of my database by creating a "Linq to SQL Classes" (.dbml) surface, and dropping my database tables onto it. The designer has automatically added relationships between the generated classes based on my database tables.
Let's say that my classes are as per the NerdDinner example, so I have Dinner and RSVP tables, where each Dinner record is associated with many RSVP records - hence in the generated classes, the Dinner object has a RSVPs property which is a list of RSVP objects.
My problem is this: it appears (and I'd be gladly proved wrong on this) that as soon as I
access a Dinner object, it's loading all of the corresponding RSVP objects, even if I don't use the RSVPs member.
First question: is this really the default behavior for the generated classes?
In my particular situation, the object graph contains many more tables (which have an order of magnitude more records), and so this is disastrous behaviour - I'd be loading tons of data when all I want to do is show the details of a single parent record.
Second question: are there any properties exposed through the designer UI that would let me modify this behavior? (I can't find any).
Third question: I've seen a description of how to control the loading of related records in a DataContext by using a DataShape object associated with the DataContext. Is that what I'm meant to do, and if so are there any tutorials like the NerdDinner one that would show not only how to do it, but also suggest a 'pattern' for normal use?

A: When you have a 1:M relationship, the L2S code generator will generate an entity class for the single entity and include an entity set of child objects within the entity. When you retrieve the single (parent) entity, L2S will not retrieve the child objects until you attempt to access the collection of child objects in some way. This is called Lazy Loading. There is no way, that I am aware of, to prevent L2S from retrieving the child objects, other than never attempting to access the collection of child objects. But note, if you never access the child collection, L2S WILL NOT retrieve the child rows. So, since your application is retrieving the child rows, you must be accessing the collection in some way.
You can also perform what is called 'eager loading' by having L2S automatically retrieve the child objects before you attempt to access the collection. However, it doesn't sound like this is what you want to do.

A: http://www.davidhayden.com/blog/dave/archive/2007/08/05/LINQToSQLLazyLoadingPropertiesSpecifyingPreFetchWhenNeededPerformance.aspx
http://www.davidhayden.com/blog/dave/archive/2009/02/12/LINQToSQLTutorialsLazyLoadingPropertiesPerformance.aspx


text:
Q: how to make a delay for few seconds on text to speech in javascript Is it posible to make a delay between two phrases using javascript? Others says that "!" can make a delay, but i was looking for other way. I tried <silence msec="5000" /> but TTS reads it also. The message have to delay for 5-10 seconds every loop from the database. So how i can make a delay for few seconds?
//data = database on spreadsheet
var msg = new SpeechSynthesisUtterance();
        var voices = window.speechSynthesis.getVoices();
        msg.voice = voices[10]; // Note: some voices don't support altering params
        msg.voiceURI = 'native';
        msg.volume = 1; // 0 to 1
        msg.rate = 0.8; // 0.1 to 10
        msg.pitch = 0; //0 to 2
        msg.lang = 'en-US';

    var text = "";
    for(var i = 1; i < data.length; i++){
      text = text + " " + data[i][0] + " " + data[i][1] + '! <silence msec="5000" />';
    }
    msg.text = text;
    msg.onend = function(e) {
      console.log('Finished in ' + event.elapsedTime + ' seconds.');
    };
    speechSynthesis.speak(msg);


text:
Q: EnableViewStateMAC set to false, but received "Validation of viewstate MAC failed" error I was notified by a client that a website I am maintaining threw this error a few times in quick succession:
Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

What is curious is that on every page this has been set in the directive:
 <%@ page language="VB" autoeventwireup="false" enableviewstatemac="false"

Putting to one side the question of why someone turned off ViewState MAC validation, I'm flummoxed as to how I would get a MAC validation error when it has been explicitly turned off. And, after a few errors, the page just started working again.
This ASP.Net website has just been upgraded from 2.0 to 4.5, for what it is worth.

A: This may occur if you are using cross page posting to different page. This was the feature introduced with .net3.5 SP1. You can find the details about this here.
Hope this helps.

A: MS released an update in December that forced it on: http://support.microsoft.com/kb/2905247


text:
Q: Let $X = \{0\} \cup \{1, 1/2, 1/3, ... , 1/n, ... \}$ and let $Y$ be a countable discrete space. Show that $X$ & $Y$ don't have the same homotopy type
Let $X = \{0\} \cup \{1, 1/2, 1/3, ... , 1/n, ... \}$ and let $Y$ be a countable discrete space. Show that $X$ and $Y$ do not have the same homotopy type.

I think that the author wants me to show a contradiction if I suppose that the spaces have the same homotopy type. So suppose that they have. Then for maps $f:X \to Y$ and $g: Y \to X$ there exists homotopies $H: g \circ f \simeq id_X$ and $H':f \circ g \simeq id_Y$. That is two maps $$H:X \times I \to X \text{ and } H':Y \times I \to Y$$ that satisfies $$H(x,0)=g(f(x)), H(x,1)=id_X \text { and } H'(x,0)=f(g(x)), H'(x,1)=id_Y$$
However it's not immediately obvious how to get a contradiction just from how $X$ and $Y$ are defined. I only have that $X$ is an infinite space and that $Y$ is a countable discrete space.
What is the "crux" here? Does it have something to do with the fact that we have chosen $X$ to be the set of points from the sequence $1/n$ which converges to $0$?

A: Consider the homotopy $H' \colon Y \times I \to Y$. Fix an arbitrary $y_{0} \in Y,$ and consider the map
$$H'_{y_{0}} \colon I  \to Y,$$ defined by
$$H'_{y_{0}}(t) = H'(y_{0}, t)$$ for all $t \in I.$ The continuity of $H'_{y_{0}}$ follows from the continuity of $H'$ (do you see why?).
Note that $H'_{y_{0}}$ is a path connecting $H'_{y_{0}}(0)$ and $H'_{y_{0}}(1)$ in the space $Y$. However, since $Y$ is a discrete space, the path-components of $Y$ are singletons (sets containing only one point). This means that $H'_{y_{0}}(0)$ and $H'_{y_{0}}(1)$ must be the same point!
Unravelling the definition of $H'_{y_{0}}$ and using the fact that $H'$ is a homotopy between $f \circ g$ and $\text{id}_{Y}$, we have
$$f(g(y_{0})) = H'(y_{0}, 0) = H'_{y_{0}}(0) = H'_{y_{0}}(1) = H'(y_{0}, 1) = \text{id}_{Y}(y_{0}) = y_{0}.$$
Since $y_{0} \in Y$ was arbitrary, this proves that $(f \circ g)(y) = f(g(y)) = y$ for all $y \in Y.$ So, we have $f \circ g = \text{id}_{Y}.$
Now, we can use the same argument for $H \colon X \times I \to X.$ Even though $X$ is not discrete, you can still show that the path-components of $X$ are singletons. So, the above proof still goes through, and we can conclude that
$g \circ f = \text{id}_{Y}.$
So, we conclude that $f, g$ are homeomorphisms. Can you find a contradiction here?


text:
Q: onmouseover show div adjusting x and y I have several small images in my page and onmouseover I show a div next to the image. So far so good. However when the image is on the bottom of the page I'd like to diplay the div not under the image but above. Basically what I'm trying to do is to verify where the image is and if is near the bottom I show the div above the image instead. The same thing if the image is to close to the right margin to show the div on the left.
Do anyone know any simple way of achieving this?
Cheers

A: Without seeing any of your code, it's a bit hard to suggest the "right" way to do it, but I'd try the following method (using JQuery syntax):
First, calculate your 'threshold' - whatever is the lowest point you want the div to appear underneath. Probably the easiest way to do this is with $(document).height() and subtract X pixels.
Then, on hover, calculate where the image is on the page. You can do this with .offset();.
If the top of the image is higher than the threshold, show the div below, otherwise show the div above.
Note: Depending on how your page is set up you could calculate the positions of each one on load and then apply a class to the ones below the threshold, and use that to position the corresponding div correctly.


text:
Q: jQuery - how to implement live() on combobox? i have combobox (in fact, several of them), with elements that are added dynamicly.
using jQuery, i don't know how to implement function that will return id of item i selected in combo...
i know that it have to be something using .live(), something like
$(".foo").live("change", function() {
do something;
});

... but i don't know how to implement it here.
tnx in adv!

A: Use the :selected selector on child elements of the select element (a.k.a. options)
$(".foo").live("change").function(){
    var val = $(".foo").find(":selected").val();
    // pass val to some other method for work
});

http://api.jquery.com/selected-selector/

A: Are you looking for something like this?
$(".foo").live("change", function() {
  $(this).val(); // value of the changed item
});

A: $(".foo").live("change", function() {
   alert($(this).attr("id")); // Id of the element
});

A: You can use $(this).val() to find the value of the element that fired the event.
It seems others have beat me to it. Mine is the same as @John and @Daniel.
Here is a jsfiddle to test it out jsfiddle.
One thing to note is that the live does not support the change method in all browsers (such as IE 6 through 8).
One way around this is to use the delegate method, which I have demonstrated here
It would look something like:
$(parentElement).delegate(selector, 'change', function() {
    //do something interesting here
    //$(this).val() still works.
});


text:
Q: Android : Call Recording error if existing recorder app engage in recording         recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        fileName = FileHelper.getFilename(phoneNumber);
        recorder.setOutputFile(fileName);
        recorder.start();

It works perfectly in my device .But when i have another recording application  it is unable to record the audio says "Another application is trying  to record".

A: It's not possible. It's a singleton method.


text:
Q: MVVM Light TextView two-way binding in Xamarin (Android) Has anyone successfully implemented a two-way binding on a TextView with MVVM Light? Two-way works perfectly fine with EditView, but the moment I try two-way binding with TextView - only one way binding works. Does anyone have any insight as to why, please?
View Model:
private string _someField;
public string SomeField
{
    get { return _someField; }
    set { Set(ref _someField, value); }
}

View:
private EditText _editableText;
public EditText EditableText;
{
  get { return _editableTex ?? (_editableTex = FindViewById<EditText>(Resource.Id.editText1)); }
}

private TextView _simpleText
public TextView SimpleText
{
  get { return _simpleText ?? (_simpleText = FindViewById<TextView>(Resource.Id.textDateDisplay)); }
}

protected override void OnCreate(Bundle savedInstanceState)
{
    bindings.Add(this.SetBinding(() => vm.SomeField, () => EditableText.Text, BindingMode.TwoWay));
    bindings.Add(this.SetBinding(() => vm.SomeField, () => SimpleText.Text, BindingMode.TwoWay));
}

No errors are thrown. But when I change (in code) of the View the text of the EditableText (EditableText.Text="asdf";) the corresponding set { Set(ref _someField, value); } triggers in the VewModel. It also triggers, naturally, if I just type in the EditText widget.
However, when I change (in code) the text property of the SimpleText (SimpleText.Text="2145";) it does not trigger the corresponding set.
Does anyone know why?
Thank you very much for help,
mike

A: You can't set a two-way binding with TextViews, because they doesn't allow input by user.
When you are using MVVM pattern you should never update the view. You should update the bound model property. So you should replace SimpleText.Text = "2145"; with vm.SomeField = "2145";.


text:
Q: Where can I get the JSONRequestError code? Following the JSONRequest proposal, I've found code for the JSONRequest object. However, this object depends on JSONRequestError, and the code for that is nowhere to be found.
Anyone know where I can find the code?
Thanks in advance!

A: For such a highly spoke of and nicely documented library, finding the download link is ridiculous but here goes:

*

*JSONRequest.javascript

*JSONRequestError.javascript
(The second  as the guy said in a hard to understand kind of way - all coders seem to half explain things!)

A: I used the request JSONRequestError site:devpro.it in Google, it is a useful tip... ^_^
Found JSONRequestError.js which explain the API, and ... hmm, no source code!
Just poked around the magical number 153, got lucky: JSONRequestError.js :-D


text:
Q: Integrate a USB connected scale to a web app with java or some other framework? I am trying to integrate any kind of a postage scale with my web app so that I can get the current weight from my application. Most computer connected scales seem to use USB but I am not finding anything promising for web integration.
Any advice is appreciated, thank you!

A: You could use something like this:
https://github.com/JaggedJax/CIO_Scale
You probably want a Java Applet though as there is no way for JS to access the USB devices on your host machine.


text:
Q: check in blade if exists variable in @include I´m developping a system with laravel 7.4 and i need check if one variable that i´m sending from my controller exists in my blade. If exists, include it:
I have this code in my controller:
public function index()
    {
        //Store Image
        $newsItem = User::find(Auth::user()->id);

        if($newsItem->hasMedia('userPhoto')){
            $profilePhoto = $newsItem->getMedia('userPhoto')[0]->file_name;
            $idPhoto = $newsItem->getMedia('userPhoto')[0]->id;

            return view('home')->with('idPhoto', $idPhoto)
                               ->with('profilePhoto', $profilePhoto);

        }else if($newsItem->hasMedia('logoSystem')){
            $logoSystem = $newsItem->getMedia('logoSystem')[0]->file_name;
            $idPhotoLogo = $newsItem->getMedia('logoSystem')[0]->id;

            return view('home')->with('idPhotoLogo', $idPhotoLogo)
                               ->with('logoSystem', $logoSystem);
        }else{
            return view('home');
        }

        if($newsItem->getMedia('userPhoto') && $newsItem->getMedia('logoSystem')){
            return view('home')->with('idPhoto', $idPhoto)
                                ->with('profilePhoto', $profilePhoto)
                                ->with('idPhotoLogo', $idPhotoLogo)
                                ->with('logoSystem', $logoSystem);
        }

    }

this return profile image or system image but it´s possible that this images don´t exists and i need check before, because i have error in my system and i can´t show my view.
Whit this code in my view after, i created a image with this route:
{{-- asset('storage/'.$idPhoto."/".$profilePhoto) --}}

But previously i need send this variable ton my view head and after to my sidebar.
i´m traying to do this:
home.blade.php
@include('layouts.head', (isset([$idPhoto])) ? ["idPhoto" => $idPhoto, "idPhotoLogo" => $idPhotoLogo]  : '')

head.blade.php
@include('layouts.sidebar', ["idPhoto", $idPhoto, "idPhotoLogo" => $idPhotoLogo])

and in my sidebar created my image:
<img src="{{-- asset('storage/'.$idPhoto."/".$profilePhoto) --}}" alt="Logo" class="brand-image">

UPDATED
now i have this error:
in my head.blade.php i have this:
@if(isset([$idPhoto])
              @include('layouts.sidebar', ["idPhoto", $idPhoto, "idPhotoLogo" => $idPhotoLogo])
            @else
              @include('layouts.sidebar')
            @endif

in my home.blade.php i have this
@if(isset([$idPhoto])
    @include('layouts.head',["idPhoto" => $idPhoto, "idPhotoLogo" => $idPhotoLogo])
@else
    @include('layouts.head')
@endif

this return:
syntax error, unexpected token ":", expecting "(" (View: C:\wamp64\www\clinicaCampoy\resources\views\home.blade.php)

i need to do, that if table media is empty, load image for deafult, but if table media have logo or image system, load this images

A: you can use  if condition
@if(isset($idPhoto))
    @include('layouts.head',["idPhoto" => $idPhoto, "idPhotoLogo" => $idPhotoLogo])

@endif


text:
Q: Intersecting vector data with raster data in PostGIS? I have Open Street Map [OSM] data imported so that I can access the geometry of buildings.
I have also loaded SRTM digital height data from NASA from a GeoTIFF raster. I have projected the raster into EPSG:3857 (the same as OSM) from the original EPSG:4326.
For the SRTM tiles that I am interested in, I have warped them into 1 meter resolution with cubic spline interpolation via ST_Resample and produced smaller tiles from that with ST_Tile(as a single INSERT .. SELECT which is very handy).
Now I run into a problem:
The ST_Intersection() of the resampled tile and the building polygon simply produces a square bounding box, which is not what I want.  I want to get at the exact x,y points on the raster for the intersection because I'm using this data for generating 3d voxel scenes (1 pixel = one voxel) and I want to produce a 2d map of the rendered area to pixel-point precision as well.
What I am currently doing:
I use ST_Clip() to clip the raster by the geometry of the buildings, which puts NODATA data into the returned clipped raster everywhere except where the building is actually situated.  This is like using an template to "burn" the image of the building into the raster, leaving the points inside the building completely intact while everything else is burned away.
I dump the resulting clipped raster with ST_PixelAsPoints() or ST_PixelAsCentroids() which gives me x,y positions on the raster where the building is located.
Is this the right approach?
I have heard of something called a 'pointcloud' but PostGIS doesn't seem to have this available.  Converting the raster into polygons doesn't work, because the x,y data from the raster is lost.


text:
Q: How to display C# source code from external file? For my project I'd like to display C# source code that I get from an external file. All I want to do is to parse that file and if possible display the code with syntax highlighting.
If also possible I'd like to divide the code I read into the various methods.
Where should I start?

A: I'd recommend AvalonEdit. It's easy to setup and use. Example
xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit"

<avalonEdit:TextEditor Name="textEditor"
                       Loaded="textEditor_Loaded"
                       FontFamily="Consolas"
                       FontSize="10pt"/>

private void textEditor_Loaded(object sender, RoutedEventArgs e)
{
    textEditor.Load(@"C:\MainWindow.xaml.cs");
    textEditor.SyntaxHighlighting =
        HighlightingManager.Instance.GetDefinition("C#");
}

Example Output

A: An alternative way is to launch an external tool or app like viewer. For example, in Windows you can use VIM app to open a cs file in read-only and no modification mode:
"C:\Program Files\Vim\vim72\gvim.exe" -R -M C:\test\MyClass.cs

Here are some codes to launch the tool:
public static int StartViewer(string file)
    {
        string parameters = string.Format("-R -M {0}", file);
        ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
        psi.FileName = "C:\Program Files\Vim\vim72\gvim.exe";
        psi.Arguments = parameters;

        Process p = Process.Start(psi);
        p.WaitForExit();

        return p.ExitCode;
    }

I think VIM has CS syntax colorizer, or you can find some better one. It is free and has great search feature. However, VIM may not be good for none-VIM users. This is just an example. You can use other tools if you like to leverage other app strength.

A: Another take on syntax highlighting.


text:
Q: AttributeError: 'numpy.ndarray' object has no attribute 'dim' 1:
issues with pytorch nn. made an auto encoder out of linear layers for a tensorflow conversion project (to use pysyft at a future point)
2:
have made sure that the forward method does return a value, does work in other situations.
3:
the full error:
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "B:\tools and software\PyCharm 2020.1\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "B:\tools and software\PyCharm 2020.1\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "B:/projects/openProjects/githubprojects/BotnetTrafficAnalysisFederaedLearning/anomaly-detection/pytorch_conversion.py", line 157, in <module>
    torch.from_numpy(x_test).float(), tr=1)
  File "B:/projects/openProjects/githubprojects/BotnetTrafficAnalysisFederaedLearning/anomaly-detection/pytorch_conversion.py", line 88, in test
    x_test_predictions = net(x_test.detach().numpy())
  File "B:\tools and software\Anaconda\envs\pysyft-pytorch\lib\site-packages\torch\nn\modules\module.py", line 532, in __call__
    result = self.forward(*input, **kwargs)
  File "B:/projects/openProjects/githubprojects/BotnetTrafficAnalysisFederaedLearning/anomaly-detection/pytorch_conversion.py", line 121, in forward
    x = torch.tanh(self.fc1(x))
  File "B:\tools and software\Anaconda\envs\pysyft-pytorch\lib\site-packages\torch\nn\modules\module.py", line 532, in __call__
    result = self.forward(*input, **kwargs)
  File "B:\tools and software\Anaconda\envs\pysyft-pytorch\lib\site-packages\torch\nn\modules\linear.py", line 87, in forward
    return F.linear(input, self.weight, self.bias)
  File "B:\tools and software\Anaconda\envs\pysyft-pytorch\lib\site-packages\torch\nn\functional.py", line 1368, in linear
    if input.dim() == 2 and bias is not None:
AttributeError: 'numpy.ndarray' object has no attribute 'dim'

the method:
def test(net, x_test, tr):
    correct = 0
    total = 0
    x_test_predictions = net(x_test.detach().numpy())
    print("Calculating MSE on test set...")
    mse_test = np.mean(np.power(x_test - x_test_predictions, 2), axis=1)
    over_tr = mse_test > tr
    false_positives = sum(over_tr)
    test_size = mse_test.shape[0]
    print(f"{false_positives} false positives on dataset without attacks with size {test_size}")

    with torch.no_grad():
        for i in tqdm(range(len(x_test))):
            real_class = torch.argmax(x_test[i])
            net_out = net(x_test[i])
            predicted_class = torch.argmax(net_out)
            if predicted_class == real_class:
                correct += 1
            total += 1
    print("Accuracy: ", round(correct / total, 3))
enter code here

The NN:
class Net(nn.Module):
    def __init__(self, input_dim=10):
        super().__init__()
        self.fc1 = nn.Linear(input_dim, int(0.75 * input_dim))
        self.fc2 = nn.Linear(int(0.75 * input_dim), int(0.5 * input_dim))
        self.fc3 = nn.Linear(int(0.5 * input_dim), int(0.33 * input_dim))
        self.fc4 = nn.Linear(int(0.33 * input_dim), int(0.25 * input_dim))
        self.fc5 = nn.Linear(int(0.25 * input_dim), int(0.33 * input_dim))
        self.fc6 = nn.Linear(int(0.33 * input_dim), int(0.5 * input_dim))
        self.fc7 = nn.Linear(int(0.5 * input_dim), int(0.75 * input_dim))
        self.fc8 = nn.Linear(int(0.75 * input_dim), input_dim)

    def forward(self, x):
        x = torch.tanh(self.fc1(x))
        x = torch.tanh(self.fc2(x))
        x = torch.tanh(self.fc3(x))
        x = torch.tanh(self.fc4(x))
        x = torch.tanh(self.fc5(x))
        x = torch.tanh(self.fc6(x))
        x = torch.tanh(self.fc7(x))
        x = self.fc8(x)
        return torch.softmax(x, dim=1)


text:
Q: Collapsing cardinal to its cofinality I'm struggling with this exercise from Jech; Suppose we have a forcing notion $P$  = the set of all functions from a bounded subset of $\kappa$ into $\{0,1\}$ with $\kappa$ singular (ordered by inclusion). I want to show that $P$ collapes $\kappa$ to cf$(\kappa)$.
I don't really see how to approach this problem. Suppose we have a generic $G$ and let $f = \bigcup G$.  We are essentially adding a subset of $\kappa$ in the extension since $f$ is a function from $\kappa\to\{0,1\}$. I don't really see how adding a single subset would collapse anything. The standard Levy collapse approach is rather different. Any hints?

A: Let's look at a concrete example: $\kappa=\omega_\omega$. We'll break the generic filter $G$ into $\omega$-many "chunks," each coding an ordinal $<(\omega_\omega)^V$; every ordinal $<(\omega_\omega)^V$ will have infinitely many opportunities to be so coded, hence by genericity will be one of the $\omega$-many ordinals coded into $G$, and this means that $(\omega_\omega)^V$ will be countable in $V[G]$.
First, let $S=f^{-1}(\{1\})$. (Note that $S, f$, and $G$ are all "absolutely definable" from each other.) We divide $S$ as follows:

*

*$C_0=S\cap \omega$.

*$C_1=S\cap (\omega_1^V\setminus\omega)$.

*$C_2=S\cap (\omega_2^V\setminus\omega_1^V)$.
...
If you prefer, you can think of $C_i$ as $f\upharpoonright (\omega_i^V\setminus\omega_{i-1}^V)$ with the convention that $C_0=f\upharpoonright\omega$.
Now I'm going to have each $C_i$ "code" an ordinal $<\omega_i^V$. For each $i$, fix (in $V$) an injection $h_i$ from $\omega_i^V$ to $(2^{[\omega_{i-1},\omega_i)})^V$ (with the convention that $\omega_{-1}=0$), and let $\beta_i=h_i^{-1}(C_i)$ if $C_i\in ran(h_i)$ and $\beta_i=0$ otherwise.
Can you argue that - in $V[G]$ - the map $i\mapsto\beta_i$ is a surjection from $\omega$ to $(\omega_\omega)^V$? Note that each $\alpha<(\omega_\omega)^V$ is in the domain of unboundedly many (indeed, cofinitely many) $h_i$s ...


text:
Q: How get stringValue from FeedItem[] item I'm downloading some data from google adWords
My code looks like this :

    public static FeedItem[] GetFeedItems(string _cid)
    {
        var user = CurrentOAuthUser.ConfigureUserForOAuthInstance(_cid).GetCurrentUser();
        FeedItemService feedItemService = (FeedItemService)user.GetService(
            AdWordsService.v201502.FeedItemService);
        FeedItemPage page = feedItemService.query(string.Format("Select FeedItemId, " +
            "AttributeValues, Scheduling where PlaceholderType = 1"));
        return page.entries;
    }

my result looks like this:
Now i need to get the information that in blue , the string value of this object.
I tried this with foreach but had no success.
Do anyone have any idea how gen I get this value ?

A: Try this
foreach(var attribute in resultList)
 foreach(var val in attribute.attributeValues)
  foreach(string x in val.stringvalues)
   Console.Write(x)


text:
Q: Translating php laravel sql code to postgres I am working on rewriting a web app written in php and laravel to a JavaScript stack. At present I am working on reworking the db schema which seems to be mysql to postgres.
I am slightly confused with some of the syntax for the following create table command
    public function up()
    {
        Schema::create('sessions', function (Blueprint $table) {
            $table->string('id')->unique();
            $table->unsignedInteger('user_id')->nullable();
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();
            $table->text('payload');
            $table->integer('last_activity');
        });
    }

From my understanding the postgres equivalent for the above would be
create table sessions (
    id text unique not null,
    user_id int references users,
    ip_address text,
    user_agent text,
    payload text,
    last_activity integer

);

However I am not sure that I have translated $table->string('ip_address', 45)->nullable(); correctly as I am not sure what exactly string('ip_address', 45) is doing.
Is my transformation to potgres correct or what do I need to change in order to have something equivalent in the postgres create command?

A: You can, for one, leverage artisan command's migration as the developer intended. It has been explained in How to convert Laravel Migrations to Raw SQL Scripts that you can use:
php artisan migrate --pretend

However, it has one caveat, you need to have a working database server to actually make it work. It will create migrations table (if it doesn't exist) in the target database but it will not create any of the table in the migrations. It will also adhere migrations table so you might need to use new database or truncate migrations table before running pretend.
Alternatively, you can go digging into Laravel's SQL "Grammar" code and figure things out from there. Sadly, someone is yet to make an easy to read reference table for it.
In your case it translates roughly this way:

Laravel
Postgre

$table->string('id')->unique();
id varchar

$table->unsignedInteger('user_id')->nullable();
user_id integer null

$table->string('ip_address', 45)->nullable();
ip_address varchar(45) null

$table->text('user_agent')->nullable();
user_agent varchar null

$table->text('payload');
payload text

$table->integer('last_activity');
last_activity integer

Or rather, written in PostgreSQL:
create table sessions (
    id varchar,
    user_id integer null,
    ip_address varchar(45) null,
    user_agent varchar null,
    payload text,
    last_activity integer
);

Note:

*

*There was no directive in the migration to add any foreign keys.

*PostgreSQL does not support unsigned integer, see Why Unsigned Integer is Not Available in PostgreSQL.


text:
Q: create clean url with htaccess I need to generate clean url for my website, and after a week of searching i was able to arrive at this.
RewriteEngine On
RewriteBase /
# remove .php extention from web pages
RewriteRule ^(.+)\.php$ /$1 [R,L]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ /$1.php [NC,END]

the rewrite rule is working perfectly
e.g "mysite.com/user.php" result in "mysite.com/user"
"mysite.com/user/profile.php" result in "mysite.com/user/profile"
Now, the issue I'm having is this;
when i add query rule like the following
# remove .php extention from web pages and query
RewriteRule ^(.+)\.php$ /$1 [R,L]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/(.*?)/?$ /$1.php?user=$2 [NC,END]

the query works for link like this; mysite.com/user/stephen
but when i try to visit mysite.com/user again it send me to the 404 page
now these are my aims:

1) If someone visit mysite.com/page.php or  mysite.com/page it should
  display mysite.com/page
2) I should be able to query the stephen data
  from user.php with this link mysite.com/user/stephen without having
  previous issue i'm trying to solve

thanks in advance, Stephen.


text:
Q: how to change ionic 3 tab max-width? I m trying to change tab max-width for 1 tab only, I did it with CSS class, but doesn't work, is there any other way to do it.
.resized_tab .tab-nav{
        max-width: 20px!important;
  }
<ion-tabs  class="tabs tabs-dark" selectedIndex="1"   >

    <ion-tab [root]="tab2Root"  tabTitle=" {{ 'home' | translate }}"
      tabIcon="nnsm3-nnsm3"  >
  </ion-tab>

    <ion-tab    tabTitle=""  class="resized_tab" tabIcon="nnsm3-menu"
     (ionSelect)="presentNotifications($event)">
   </ion-tab>
</ion-tabs>


text:
Q: wp_query help with retrieveing posts via tag s it possible to retrieve post entry for a custom post type by tag, I have been trying with the following code, however it just locks me into a infinte loop.
<aside class="supporting_images">
    <?php /*<?php if($post->ID == 241) : echo apply_filters('the_content', '[slideshow=3]'); endif;  ?>
    <?php the_post_thumbnail(); ?>*/?>

    <?php if($post->ID == 241) : ?>
        <?php
            $query = new WP_Query();
            $query->query('tag=branding');
        ?>
        <?php while ($query->have_posts()) : ?>
            hello
        <?php endwhile; ?>
    <?php endif;?>

A: First try changing your loop to:
<?php while ($query->have_posts()) : the_post(); ?>
    <?php the_title(); ?>
<?php endwhile; ?>

The have_posts() function just returns true if there is another post but does not increment the loop counter, so the loop will never end.


text:
Q: How to enforce Azure AD SSO between iOS native app and Safari browser? We are using https://github.com/AzureAD/azure-activedirectory-library-for-objc to enable Azure AD login for our native iOS app.
We have a webpage (javascript) which also uses ADAL.js to enable Azure AD login (same AD) for SSO.
Now, suppose a user is already logged in to the iOS app and then the user clicks on a the webpage link from within the iOS app, then the webpage opens in Safari but the user is asked to enter his credentials again instead of using the iOS app session.
How can SSO be enforced between native iOS app and webpage in browser?
If iOS app is able to pass the id_token to the webpage as a url parameter, how can we validate and use the same session from the webpage (javascript)?
Any help is greatly appreciated.
Thanks.


text:
Q: Checking Spring Security Role in FreeMarker Template I have been struggling with integrating Spring Security and FreeMarker template in Spring MVC application. I used a very simple login form to submit the username and password to /j_spring_security_check. I am able to login and retrieve user's roles  in Java layer. But when I tried to check Role in FreeMarker, I have no luck.
I added the following on top of the FTL file:
<#assign security=JspTaglibs["http://www.springframework.org/security/tags"] />

and used the following to check Role:

<@security.authorize ifAnyGranted="ROLE_ADMIN">
Your is Administrator
</@security.authorize>

I am getting the following error:
Jan 15, 2015 10:15:22 PM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet freemarker threw exception
FreeMarker template error:
The following has evaluated to null or missing:
==> security  [in template "WEB-INF/jsp/modules/user/welcome.ftl" at line 2, column 3]

Tip: If the failing expression is known to be legally null/missing, either specify a default value with myOptionalVar!myDefault, or use <#if myOptionalVar??>when-present<#else>when-missing</#if>. (These only cover the last step of the expression; to cover the whole expression, use parenthessis: (myOptionVar.foo)!myDefault, (myOptionVar.foo)??

The failing instruction (FTL stack trace):
----------
==> @security.authorize ifAnyGranted="ROL...  [in template "WEB-INF/jsp/modules/user/welcome.ftl" at line 2, column 1]
----------

Java stack trace (for programmers):
----------
freemarker.core.InvalidReferenceException: [... Exception message was already printed; see it above ...]
    at freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:98)
    at freemarker.core.UnexpectedTypeException.newDesciptionBuilder(UnexpectedTypeException.java:41)
    at freemarker.core.UnexpectedTypeException.<init>(UnexpectedTypeException.java:24)
    at freemarker.core.Dot._eval(Dot.java:81)
    at freemarker.core.Expression.eval(Expression.java:111)
    at freemarker.core.UnifiedCall.accept(UnifiedCall.java:106)
    at freemarker.core.Environment.visit(Environment.java:265)
    at freemarker.core.MixedContent.accept(MixedContent.java:93)
    at freemarker.core.Environment.visit(Environment.java:265)
    at freemarker.core.Environment.process(Environment.java:243)
    at freemarker.template.Template.process(Template.java:277)
    at freemarker.ext.servlet.FreemarkerServlet.process(FreemarkerServlet.java:452)
    at freemarker.ext.servlet.FreemarkerServlet.doGet(FreemarkerServlet.java:391)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
    at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:551)
    at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:488)
    at freemarker.ext.jsp.FreeMarkerPageContext.include(FreeMarkerPageContext.java:406)
    at org.apache.tiles.request.jsp.JspRequest.doInclude(JspRequest.java:123)
    at org.apache.tiles.request.AbstractViewRequest.dispatch(AbstractViewRequest.java:47)
    at org.apache.tiles.request.render.DispatchRenderer.render(DispatchRenderer.java:47)
    at org.apache.tiles.request.render.ChainedDelegateRenderer.render(ChainedDelegateRenderer.java:68)
    at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:259)
    at org.apache.tiles.template.InsertAttributeModel.renderAttribute(InsertAttributeModel.java:188)
    at org.apache.tiles.template.InsertAttributeModel.execute(InsertAttributeModel.java:132)
    at org.apache.tiles.jsp.taglib.InsertAttributeTag.doTag(InsertAttributeTag.java:299)
    at freemarker.ext.jsp.SimpleTagDirectiveModel.execute(SimpleTagDirectiveModel.java:75)
    at freemarker.core.Environment.visit(Environment.java:341)
    at freemarker.core.UnifiedCall.accept(UnifiedCall.java:136)
    at freemarker.core.Environment.visit(Environment.java:265)
    at freemarker.core.MixedContent.accept(MixedContent.java:93)
    at freemarker.core.Environment.visit(Environment.java:265)
    at freemarker.core.Environment.process(Environment.java:243)
    at freemarker.template.Template.process(Template.java:277)
    at freemarker.ext.servlet.FreemarkerServlet.process(FreemarkerServlet.java:452)
    at freemarker.ext.servlet.FreemarkerServlet.doGet(FreemarkerServlet.java:391)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
    at org.apache.tiles.request.servlet.ServletRequest.forward(ServletRequest.java:265)
    at org.apache.tiles.request.servlet.ServletRequest.doForward(ServletRequest.java:228)
    at org.apache.tiles.request.AbstractClientRequest.dispatch(AbstractClientRequest.java:57)
    at org.apache.tiles.request.render.DispatchRenderer.render(DispatchRenderer.java:47)
    at org.apache.tiles.request.render.ChainedDelegateRenderer.render(ChainedDelegateRenderer.java:68)
    at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:259)
    at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:397)
    at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:238)
    at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:221)
    at org.apache.tiles.renderer.DefinitionRenderer.render(DefinitionRenderer.java:59)
    at org.springframework.web.servlet.view.tiles3.TilesView.renderMergedOutputModel(TilesView.java:137)
    at com.smartwcm.web.tiles.ExtTilesView.renderMergedOutputModel(ExtTilesView.java:41)
    at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:264)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:662)

Can anyone suggest any idea why I am not able to check the Role in view (FreeMarker) file?

A: It is complaining about not finding @security.authorize tag. I see you are using tiles. If welcome.ftl is an include file you may have to include Spring security tag library on top of each include files. I had similar issue and that is how I got it working.
<#assign security=JspTaglibs["http://www.springframework.org/security/tags"] />


text:
Q: Need GUI to run qemu on Ubuntu server Need GUI to run qemu on Ubuntu server: I need to run QEMU for ARM on a Ubuntu srever. THis QEmu is not supporting a text mode, so I need to install GUI software on Ubuntu server 13.04. Please suggest any that I can do a sudo apt-get install and get started quickly.

A: Are you connecting to the server over ssh? You could just use X forwarding to your local machine.
See the very good first answer here.
Then you can just start the software and interact with the GUI on a computer that already has the desktop environment installed.

A: You can do the following
sudo apt-get install ubuntu-desktop

For more info, look to this link


text:
Q: Absolutely positioned scrolling view with header I'm trying to create an absolutely positioned widget for a web-app that looks something like this:
+-----------+ <-- top: 10px
| Header    |
| Desc ln 1 |
| Desc ln 2 |
+-----------+ <-- moves down as more lines added to the description
| Scrolling |
| content   |
|           |
|           |
+-----------+ <-- bottom: 10px

Basically it has a header and scrolling content under it.  I want the scrolling content area to get smaller as more lines are added to the description.  I also need the top of the header and the bottom of the scrolling content to be pegged to the top and bottom of the viewport.
Here's my Plunker attempt: http://plnkr.co/edit/LdYl7e7GYhdGiF3NQ0Bv
As you can see, I haven't been able to figure out how to connect the middle line to the height of the header.
I know I could figure out a way to do it with JavaScript but I'd prefer to be able to do it in pure HTML/CSS.

A:
 you could try to use inherited height and display specifities that has <table>.
Your demo forked :http://plnkr.co/edit/45f0SCrdrNzHJFZLsa8w?p=preview
Add content either  in #header or <div> in #content or both and see what comes to scroll.
if #header becomes taller than window , the all thing will expand and window will scroll.
Only <div> in #content can scroll inside .
oups, FF had trouble , something kind of messy for it . http://plnkr.co/edit/xBJuqnxBuFwfTV2BAAWl?p=preview


text:
Q: Euler Numbers and Bernoulli Numbers Euler numbers, $E_{n}$, $n∈ℕ,$ are integers defined by the Maclaurin series $\frac{1}{\cosh x}=∑_{n=0}^{∞}\frac{E_{n}}{n!}x^n.$
Euler polynomials, $E_{n}(x), n∈ℕ,$ are defined by the generating function identity $\frac{2e^{xt}}{e^{t}+1}=∑_{n=0}^{∞}\frac{E_{n}(x)}{n!}x^n$ so that we have $E_{n}=2^nE_{n}(\frac{1}{2})$.
There are some very complicated explicit formulas for $E_{n}$ in https://en.wikipedia.org/wiki/Euler_numbers.
There is also a a kind of duality between Bernoulli numbers and Euler numbers.
Bernoulli polynomials and numbers can be defined respectively by the umbral calculus identities $B_{n}(x)=(B+x)^n↓$ for all  $n∈ℕ$ and $B_0=1$, $(B+1)^n=B^n↓, n≥2$.
Long time ago, after complications and mistakes, I derived the identity
$$E_{n}=∑_{k=0}^n\binom{n}{k}(2^{k+1}-2^{2k+2})\frac{B_{k+1}}{k+1}$$
for all $n∈ℕ$. I think this identity I found is correct. I am also wondering the formula for $B_{n}$ in terms of Euler numbers. Are there some faster ways to derive these identities?
My second question is the following: Are the umbral calculus identities
$E_{n}(x)=(E+(2x-1))^n↓$ for all  n∈ℕ and $(E-1)^n↓=(2^{n+1}-2^{2n+2})\frac{B_{n+1}}{n+1}$ for $n≥1$, correct?
My third question is about the connections between Euler numbers and L-functions, specifically Rieaman Zeta Function. Can Euler numbers be connected with some special values of such functions? I have not much experience in analytic number theory.

A: I would have defined Euler numbers using the coefficients of the power series of $1/\cos x$, not $1/\cosh x$:
$$
\frac{1}{\cos x} = \sum_{n \geq 0} \frac{\mathcal E_n}{n!}x^n,
$$
where I write $\mathcal E_n$ to avoid clashing with your notation $E_n$. We have $\mathcal E_n= 0$ for odd $n \geq 0$  since $\cos x$ is an even function, just as $E_n = 0$ for odd $n \geq 0$.
Since $\cos x = (e^{ix} + e^{-ix})/2$ and $\cosh x = (e^x + e^{-x})/2$, $\cosh(ix) = \cos x$, so $i^nE_n = \mathcal E_n$ for all $n$. This is boring for odd $n$, since both sides are $0$. For even $n \geq 0$, $(-1)^{n/2}E_n = \mathcal E_n$.
You ask about a connection between Euler numbers and $L$-functions.  The even-indexed Bernoulli numbers are related to the Riemann zeta-function at positive even numbers $2k$:
$$
\zeta(2k) = \frac{(-1)^{k-1}B_{2k}}{2(2k)!}(2\pi)^{2k}.
$$
Since $\zeta(2k) > 0$, $(-1)^{k-1}B_{2k} > 0$, so
$$
\zeta(2k) = \frac{|B_{2k}|}{2(2k)!}(2\pi)^{2k}.
$$
In a similar way even-indexed Euler numbers are related to the $L$-function of the nontrivial character mod $4$ at positive odd numbers: for $k \geq 0$,
$$
L(2k+1,\chi_4) = \frac{\mathcal E_{2k}}{2(2k)!}\left(\frac{\pi}{2}\right)^{2k+1} =
 \frac{(-1)^kE_{2k}}{2(2k)!}\left(\frac{\pi}{2}\right)^{2k+1}.
$$
For example, taking $k = 0$ we get
$L(1,\chi_4) = (E_0/2)(\pi/2) = \pi/4$, which is the famous Leibniz series evaluation.
Since $L(2k+1,\chi_4) > 0$, $(-1)^kE_{2k} > 0$, so
$$
L(2k+1,\chi_4) =
\frac{|E_{2k}|}{2(2k)!}\left(\frac{\pi}{2}\right)^{2k+1}.
$$
That's the analogue of the formula for $\zeta(2k)$ in terms of $|B_{2k}|$.
There are also formulas for the analytic continuations of $\zeta(s)$ and $L(s,\chi_4)$ at negative integers: for $n \geq 2$,
$$
\zeta(1-n) = -\frac{B_n}{n}
$$
(this is not correct at $n = 1$: $\zeta(0) = -1/2$ while $-B_1/1 = -(-1/2) = 1/2$) and for $n \geq 1$,
$$
L(1-n,\chi_4) = (-1)^{(n-1)/2}\frac{\mathcal E_{n-1}}{2} = \frac{E_{n-1}}{2}.
$$
(In this last formula, all terms are $0$ when $n$ is even, just like $\zeta(1-n)$ and $B_n$ are $0$ when $n$ is odd.)


text:
Q: Pre-text (cover, dedicatory, table of contents, list of figures) printed one-sided, rest two-sided My thesis commitee demands that the pre-text elements, including table of contents, list of figures, list of algorithms goes only on the odd pages, with the body of the thesis go two-sided, with new chapters initiating on odd pages. I do almost all, except by the lists. How can I get the toc, lof, loa, lot to go only in odd pages?

A: This seems to work, at least with the book class:
\documentclass{book}
\usepackage{afterpage,emptypage}

\usepackage{kantlipsum} % mock text

\begin{document}
\frontmatter
\afterpage{\afterpage{\cleardoublepage}}
\tableofcontents

\cleardoublepage
\afterpage{\afterpage{\cleardoublepage}}
\listoffigures

\cleardoublepage
\afterpage{\afterpage{\cleardoublepage}}
\listoftables

\mainmatter
\afterpage{}

\def\mock{
  \chapter{A}
  \section{B}
  \kant[1]
  \begin{figure}\caption{F}\end{figure}
  \kant[2]
  \begin{table}\caption{T}\end{table}
  \kant[3]
  \section{B}
  \kant[1]
  \begin{figure}\caption{F}\end{figure}
  \kant[2]
  \begin{table}\caption{T}\end{table}
  \kant[3]
  \section{B}
  \kant[1]
  \begin{figure}\caption{F}\end{figure}
  \kant[2]
  \begin{table}\caption{T}\end{table}
  \kant[3]
}
\def\fivemock{\mock\mock\mock\mock\mock}
\fivemock\fivemock

\end{document}


text:
Q: Here Maps Calculate Matrix API returns "The request is missing the app_id and app_code parameters." error I'm trying to get distances for an origin-destination matrix using the following call using an API Key:
https://matrix.route.api.here.com/routing/7.2/calculatematrix.json?apiKey=[API Key Here]&start0=35.04672,-85.30947&start1=39.766998.49461&destination0=39.10344,-94.58311&destination1=39.76691,-86.14996&destination2=29.42458,-98.49461&mode=fastest;car;traffic:disabled

But it is returning this error in the response details: "The request is missing the app_id and app_code parameters. They must both be passed as query parameters. If you do not have app_id and app_code, please obtain them through your customer representative or at http://developer.here.com/myapps."
But the documentation here says I can use either ApiKey or App_code and App_id. https://developer.here.com/documentation/routing/dev_guide/topics/resource-calculate-matrix.html
Why doesn't it work with the apiKey?

A: The base url you are using is incorrect, please replace it with https://matrix.route.ls.hereapi.com/routing/7.2/calculatematrix.json to use it with API key.
https://matrix.route.api.here.com/routing/7.2/calculatematrix.json will work with APPid and APPcode.
For more help on the same, please refer to the example at https://developer.here.com/documentation/examples/rest/routing/one-to-many-matrix-routing


text:
Q: LINQ where clause throwing error with 2nd where UPDATE
Even doing a search on the contacts firstName or LastName causes issues:
var contacts =
            (
                from c in context.ContactSet
                join m in context.py3_membershipSet on c.ContactId equals m.py3_Member.Id
                where m.statuscode.Value == 1
                && ((c.FirstName != null && c.FirstName == searchTerm) || (c.LastName!=null && c.LastName == searchTerm) || (c.FullName != null && c.FullName == searchTerm))
                orderby c.LastName
                select new
                {
                    ContactId = c.ContactId,
                    FirstName = c.FirstName,
                    LastName = c.LastName,
                    BranchCode = c.py3_BranchArea,
                    Branch = (c.FormattedValues != null && c.FormattedValues.Contains("py3_brancharea") ? c.FormattedValues["py3_brancharea"] : "N/a"),
                    JobTitle = c.JobTitle,
                    Organisation = (c.ParentCustomerId != null ? c.ParentCustomerId.Name : "N/a"),
                    joinedAsCode = c.py3_SOLACEMemberJoinedAs,
                    JoinedAs = (c.FormattedValues != null && c.FormattedValues.Contains("py3_solacememberjoinedas") ? c.FormattedValues["py3_solacememberjoinedas"] : "N/a"),
                    Expertise = (c.py3_SOLACEMemberAreasofExpertise != null && c.py3_SOLACEMemberAreasofExpertise.Trim() != String.Empty ? c.py3_SOLACEMemberAreasofExpertise : "N/a"),
                    Title = c.Salutation
                }
            );

Which screams back:
'py3_membership' entity doesn't contain attribute with Name = 'firstname'.

Ive got the following code that het some info from an Online CRM:
        var context = new XrmServiceContext();
    var contacts1 =
        (
            from c in context.ContactSet
            join m in context.py3_membershipSet on c.ContactId equals m.py3_Member.Id
            where m.statuscode.Value == 1

            orderby c.LastName
            select new
            {
                ContactId = c.ContactId,
                FirstName = c.FirstName,
                LastName = c.LastName,
                BranchCode = c.py3_BranchArea,
                Branch = (c.FormattedValues != null && c.FormattedValues.Contains("py3_brancharea") ? c.FormattedValues["py3_brancharea"] : "N/a"),
                JobTitle = c.JobTitle,
                Organisation = (c.ParentCustomerId != null ? c.ParentCustomerId.Name : "N/a"),
                joinedAsCode = c.py3_SOLACEMemberJoinedAs,
                JoinedAs = (c.FormattedValues != null && c.FormattedValues.Contains("py3_solacememberjoinedas") ? c.FormattedValues["py3_solacememberjoinedas"] : "N/a"),
                Expertise = (c.py3_SOLACEMemberAreasofExpertise != null && c.py3_SOLACEMemberAreasofExpertise.Trim() != String.Empty ? c.py3_SOLACEMemberAreasofExpertise : "N/a")
            }
        );

I then bind this to a datalist as an array, which all works fine.
However I want to be able to limit the results to a value selected from a dropdownlist, and expected the following to work:
        var context = new XrmServiceContext();
    var contacts1 =
        (
            from c in context.ContactSet
            join m in context.py3_membershipSet on c.ContactId equals m.py3_Member.Id
            where m.statuscode.Value == 1 &&
                c.FormattedValues["py3_brancharea"] == ddlBranchTags.SelectedItem.Value

            orderby c.LastName
            select new
            {
                ContactId = c.ContactId,
                FirstName = c.FirstName,
                LastName = c.LastName,
                BranchCode = c.py3_BranchArea,
                Branch = (c.FormattedValues != null && c.FormattedValues.Contains("py3_brancharea") ? c.FormattedValues["py3_brancharea"] : "N/a"),
                JobTitle = c.JobTitle,
                Organisation = (c.ParentCustomerId != null ? c.ParentCustomerId.Name : "N/a"),
                joinedAsCode = c.py3_SOLACEMemberJoinedAs,
                JoinedAs = (c.FormattedValues != null && c.FormattedValues.Contains("py3_solacememberjoinedas") ? c.FormattedValues["py3_solacememberjoinedas"] : "N/a"),
                Expertise = (c.py3_SOLACEMemberAreasofExpertise != null && c.py3_SOLACEMemberAreasofExpertise.Trim() != String.Empty ? c.py3_SOLACEMemberAreasofExpertise : "N/a")
            }
        );

However, this throws the following error:
Invalid 'where' condition. An entity member is invoking an invalid property or method.

Its the same even if I hard code the branchtag criteria rather than going of the DDL value.
Ive also tried doing a select on the contacts1 set eg:
var results = contacts1.select(c=> c.BranchTag == ddlBranchTags.SelectedItem.Value

But that throws the same error.
If I remove the branchTag where clause it works as expected.
I think its fair to assume that Ive gone wayward with this, so any useful / constructive pointers (for a LINQ newb) would be really appreciated. Thanks.

A: LINQ-to-CRM is actually fairly limited in terms of the expression forms it can support. If you consider what it's doing behind the scenes – taking your entire LINQ expression and translating it into a CRM QueryExpression – this makes more sense.
Basically, it's not valid to expect to be able to embed arbitrary C# into your query (even if it compiles), as it's not possible to translate all code into a CRM query. The query provider could hypothetically be smart enough to determine what it can submit as a query to CRM, and what code it then has to execute client-side to get your final desired results, but that's generally a pretty hard problem – one which the LINQ provider does not attempt to solve.
In Where clauses specifically, the LINQ provider scans the expressions for basic forms of <attribute name accessor> <simple comparison> <value>. It understands early-bound codegen attribute accessors (entity.Attribute_name), indexer access (entity["attribute_name"]), and entity.GetAttributeValue<T>("attribute_name") access. Those are the only things you can use on the left side of a comparision in a Where clause (or in an OrderBy clause). In your second query, you're accessing FormattedValues, which the query provider doesn't understand/support.
An additional limitation is that a single Where clause can only address one "target" entity. So the case where you have filters on both "m" and "c" in a single predicate is not supported. I'm less clear on the reasons for this limitation, but that's how it is. You can still accomplish the equivalent filter by splitting the two conditions (joined by an && in your current query) into two separate Where clauses.
It's natural to want to write LINQ-to-CRM queries as though you are using LINQ-to-Objects, but doing so will generally be frustrating. LINQ-to-CRM is somewhat limited, but many of those limitations are inherited from the underlying CRM SDK query systems it's built upon. It's still a decent API for writing CRM queries, as long as you keep the limitations in mind.
If you're writing a query that is going to require you to execute some arbitrary code to filter/order/map your results, the general technique that should be used is to separate your query into two parts: the query that should be submitted to CRM, and your aribitrary code transformation. You write the most data-efficient query you can for getting your CRM data, force evaluation of the query using something like ToList or ToArray (as LINQ is otherwise lazily-evaluated), and then you proceed with your code on the results of that evaluation.

A: This looks to be a limitation of the CRM LINQ Provider.

where: The left side of the clause must be an attribute name and the right side of the clause must be a value. You cannot set the left side to a constant. Both the sides of the clause cannot be constants. Supports the String functions Contains, StartsWith, EndsWith, and Equals.

(Emphasis mine)
It probably has to do with indexing into the FormattedValues property of your Contact Set. You can try using a let clause and see if that helps.
EDIT: Here's an example of how to use let. I'm not sure if this will actually help - I can't test it at the moment.
from c in context.ContactSet
let formattedValue = c.FormattedValues["py3_brancharea"]
join m in context.py3_membershipSet on c.ContactId equals m.py3_Member.Id
where m.statuscode.Value == 1 &&
    formattedValue == ddlBranchTags.SelectedItem.Value

Notice how I let formattedValue be the value from c.FormattedValue["py3_brancharea"] and then use that in the where clause. It might get you past the limitation.

A: I believe you can get around this issue by using method syntax for where instead of query syntax.
var context = new XrmServiceContext();
var contacts1 =
(
    from c in context.ContactSet.Where(c => c.FormattedValues["py3_brancharea"] == ddlBranchTags.SelectedItem.Value)
    join m in context.py3_membershipSet.Where(m => m.statuscode.Value == 1)
    on c.ContactId equals m.py3_Member.Id
    // ...
);

More insight on using method syntax. If you prefer a solution that lets you use query syntax, you can use LINQKit as explained here.  As an aside, the LINQKit answer mentions that join gets performed on the client side, so you might want to change it to a where clause.

A: Based on @Peter Majeed's answer, I solved my problem by using the double where clause:
var contacts =
            (
                from c in context.ContactSet
                join m in context.py3_membershipSet on c.ContactId equals m.py3_Member.Id
                where m.statuscode.Value == 1
                where ((c.FirstName != null && c.FirstName == searchTerm) || (c.LastName!=null && c.LastName == searchTerm) || (c.FullName != null && c.FullName == searchTerm))
                orderby c.LastName
                select new
                {
                    ContactId = c.ContactId,
                    FirstName = c.FirstName,
                    LastName = c.LastName,
                    BranchCode = c.py3_BranchArea,
                    Branch = (c.FormattedValues != null && c.FormattedValues.Contains("py3_brancharea") ? c.FormattedValues["py3_brancharea"] : "N/a"),
                    JobTitle = c.JobTitle,
                    Organisation = (c.ParentCustomerId != null ? c.ParentCustomerId.Name : "N/a"),
                    joinedAsCode = c.py3_SOLACEMemberJoinedAs,
                    JoinedAs = (c.FormattedValues != null && c.FormattedValues.Contains("py3_solacememberjoinedas") ? c.FormattedValues["py3_solacememberjoinedas"] : "N/a"),
                    Expertise = (c.py3_SOLACEMemberAreasofExpertise != null && c.py3_SOLACEMemberAreasofExpertise.Trim() != String.Empty ? c.py3_SOLACEMemberAreasofExpertise : "N/a"),
                    Title = c.Salutation
                }
            );

Essentially the answer is to split each logical 'chunk' of the query with its own where clause. It would appear this allows LINQ to make one query based on the first 'where' clause and then do a secondary filter on that via the second 'where' clause.