text:
Q: Cross-platform gui toolkit for deploying Python applications Building on:
http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/
Merits:
1 - ease of design / integration - learning curve
2 - support / availability for *nix, Windows, Mac, extra points for native l&f, support for mobile or web
3 - pythonic API
4 - quality of documentation - I want to do something a bit more complicated, now what?
5 - light weight packaging so it's not necessary to include a full installer (py2exe, py2app would ideally work as-is and not generate a gazillion MBs file)
6 - licensing
7 - others? (specify)

Contenders:
1 - tkinter, as currently supported (as of 2.6, 3.0)
2 - pyttk library
3 - pyGTK
4 - pyQt
5 - wxPython
6 - HTML-CGI via Python-based framework (Django, Turbogears, web.py, Pylons...) or Paste
7 - others? (specify)

A: I'm just weighing in to say that TKinter sucks. It sadly seems that it is packed with Python because of backwards compatibility.
The documentation is horrible. It looks horrible. I have run into some bizarre bugs that will actually crash Python.

A: Jython.

Jython is an implementation of the
  high-level, dynamic, object-oriented
  language Python written in 100% Pure
  Java, and seamlessly integrated with
  the Java platform. It thus allows you
  to run Python on any Java platform.

You can use either Swing, Applet, or other GUI frameworks available to Java platform. See Java Tutorials for Graphical User Interfaces and 2D Graphics. There are plenty of books and documentation such as API reference.
Here's a Hello world Swing application from An Introduction to Jython.
from javax.swing import *

frame = JFrame("Hello Jython")
label = JLabel("Hello Jython!", JLabel.CENTER)
frame.add(label)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setSize(300, 300)
frame.show()

Here's a Jython applet by Todd Ditchendorf that demonstrates multi-threaded particle drawing (60 lines).
from __future__ import nested_scopes
import java.lang as lang
import java.util as util
import java.awt as awt
import javax.swing as swing

class Particle:

    def __init__(self,initX,initY):
    self.x = initX
    self.y = initY
    self.rng = util.Random()

    def move(self):
    self.x += self.rng.nextInt(10) - 5
    self.y += self.rng.nextInt(20) - 10

    def draw(self,g2):
    g2.drawRect(self.x,self.y,10,10)

class ParticleCanvas(awt.Canvas):

    def __init__(self,newSize):
    awt.Canvas.__init__(self,size=(newSize,newSize))

    def paint(self,g2):
    for p in self.particles:
        p.draw(g2)

class ParticleApplet(swing.JApplet):

    def init(self):
    self.canvas = ParticleCanvas(self.getWidth())
    self.contentPane.add(self.canvas)

    def start(self):
    n = 10
    particles = []
    for i in range(n):
        particles.append(Particle(150,150))
    self.canvas.particles = particles

    self.threads = []
    for i in range(n):
        self.threads.append(self.makeThread(particles[i]))
        self.threads[i].start()

    def makeThread(self,p):

    class MyRunnable(lang.Runnable):
        def run(this):
        try:
            while 1:
            p.move()
            self.canvas.repaint()
            lang.Thread.sleep(100)
        except lang.InterruptedException:
            return

    return lang.Thread(MyRunnable())

If you are just interested in drawing lines and circles you can probably cut it down to half.

A: Please don't hesitate to expand this answer.
Tkinter
Tkinter is the toolkit that comes with python. That means you already have everything you need to write a GUI. What that also means is that if you choose to distribute your program, most likely everyone else already has what they need to run your program.
Tkinter is mature and stable, and is (at least arguably) quite easy to use.I found it easier to use than wxPython, but obviously that's somewhat subjective.
Tkinter gets a bad rap for looking ugly and out of date. While it's true that it's easy to create ugly GUIs with Tkinter, it's also pretty easy to create nice looking GUIs. Tkinter doesn't hold your hand, but it doesn't much get in the way, either. Tkinter looks best on the Mac and Windows since it uses native widgets there, but it looks OK on linux, too.
The other point about the look of Tkinter is that, for the most part, look isn't as important as people make it out to be. Most applications written with toolkits such as Tkinter, wxPython, PyQT, etc are special-purpose applications. For the types of applications these toolkits are used for, usability trumps looks. If the look of the application is important, it's easy enough to polish up a Tkinter application.
Tkinter has some features that other toolkits don't come close to matching. Variable traces, named fonts, geometry (layout) managers, and the way Tkinter processes events are still the standard to which other toolkits should be judged.
On the downside, Tkinter is a wrapper around a Tcl interpreter that runs inside python. This is mostly invisible to anyone developing with Tkinter, but it sometimes results in error messages that expose this architecture. You'll get an error complaining about a widget with a name like ".1245485.67345" which will make almost no sense to anyone unless you're also familiar with how Tcl/tk works.
Another downside is that Tkinter doesn't have as many pre-built widgets as wxPython. The hierarchical tree widget in Tkinter is a little weak, for example, and there's no built-in table widget. On the other hand, Tkinter's canvas and text widgets are extremely powerful and easy to use. For most types of applications you will write, however, you'll have everything you need. Just don't expect to replicate Microsoft Word or Photoshop with Tkinter.
I don't know what the license is for Tkinter, I assume the same as for python as a whole. Tcl/tk has a BSD-style license.
PyQt
It's build on top of Qt, a C++ framework. It's quite advanced and has some good tools like the Qt Designer to design your applications. You should be aware though, that it doesn't feel like Python 100%, but close to it. The documentation is excellent
This framework is really good. It's being actively developed by Trolltech, who is owned by Nokia. The bindings for Python are developed by Riverbank.
PyQt is available under the GPL license or a commercial one. The price of a riverbank PyQt license is about 400 euro per developer.
Qt is not only a GUI-framework but has a lot of other classes too, one can create an application by just using Qt classes. (Like SQL, networking, scripting, …)
Qt used to emulate GUI elements on every platform but now uses native styles of the platforms (although not native GUI toolkits): see the documentation for Mac OS X and the windows XP style
Packaging is as simple as running py2exe or pyInstaller. The content of my PyQt app looks like this on windows (I have used InnoSetup on top of it for proper installation):

pyticroque.exe           PyQt4.QtGui.pyd           unicodedata.pyd
MSVCP71.dll              PyQt4._qt.pyd             unins000.dat
MSVCR71.dll              python25.dll              unins000.exe
PyQt4.QtCore.pyd         sip.pyd                   _socket.pyd

QT comes with a widget designer and even in recent versions with an IDE to help design Qt software.
PySide
PySide is a LGPL binding to Qt. It's developed by nokia as a replacement for the GPL PyQt.

Although based on a different
  technology than the existing
  GPL-licensed PyQt bindings, PySide
  will initially aim to be
  API-compatible with them. In addition
  to the PyQt-compatible API, a more
  Pythonic API will be provided in the
  future.

wxPython
wxPython is a binding for Python using the wxWidgets-Framework. This framework is under the LGPL licence and is developed by the open source community.
What I'm really missing is a good tool to design the interface, they have about 3 but none of them is usable.
One thing I should mention is that I found a bug in the tab-view despite the fact that I didn't use anything advanced. (Only on Mac OS X) I think wxWidgets isn't as polished as Qt.
wxPython is really only about the GUI-classes, there isn't much else.
wxWidgets uses native GUI elements.
An advantage wxPython has over Tkinter is that wxPython has a much larger library of widgets from which to choose from.
Others
I haven't got any experience with other GUI frameworks, maybe someone else has.

A: I would definitely appreciate it if anyone knows of something better than what's commonly discussed; I see to have headaches finding something appropriate...
Qt is great, but PyQt doesn't seem to have the same development resources. It seems to have some clever way to generate bindings, but isn't complete (e.g. PyKDE terminal kpart) and there is a dearth of documentation (as the developers admit). Compatibility with Qt's UI designer is nice.
wxpython - controls aren't as nice looking, widget library isn't as large as KDE.
OpenGL - doesn't even support fonts by default... pygame is okay, but opengl being a state machine is too annoying (object oriented models prevent making the a call in the wrong state).
XUL - neat idea, I wish it worked. The pyxulrunner tutorial didn't work for me, though -- first I had to add the xulrunner /usr/lib path to LD_LIBRARY_PATH, then it still had problems with "from xpcom import components"...
my wishlist for a ui library would be

*

*Python integration (i.e. uses builtins like unicode, modules like threading, and language features like closures)

*good intermediate representation (like XUL instead of generating hundreds of lines looking like "listbox91.addChild(label28)")

*simple mutlithreaded support (automatic locks or event posting so e.g. elt.setText can be called from any thread; let the designer manage locking with Python locks if necessary)

*user-centric features as well - scripting of a sequence of UI events, ability to keybind anything (KDE has dcop, but afaik binding isn't done automatically by the UI library), and intercept events.

*potential for a large, easy-to-contribute standard library.

*documentation, though if the library was well designed and generated enough interest, this would be a given.

In my experience, html is so much easier to get something good-looking up than UI libraries.
edit - after working with PyQt 4 for a while, it gets the job done for simple UI's. I'm currently not developing for end users, so looks don't matter. The QTextBrowser is very useful for displaying basic HTML tables and generating HTML links.

A: Pro wxPython

*

*Lots of tutorials

*wxGlade as an Editor: not perfect yet, but usable.


text:
Q: Display Day of the Week dynamically in Arrowhead TimeStamp on Hover Currently 'Day' is not displayed in timestamp of the Arrowhead when hovered on a particular bar  .

str.format() does provide this function but the barindex has to be specified separately in code (and isn't recognised on hover).(here)
In PineScript is there a way to modify the arrowhead timestamp and show the Day (on hover)?

A: No, the date format only supports combinations of day/month/year.

If you are looking for a way to display the day of the week on your chart, a workaround might be displaying it in a table.
//@version=5
indicator("My script", overlay=true)

f_get_day() =>
    switch dayofweek
        1 => "Sunday"
        2 => "Monday"
        3 => "Tuesday"
        4 => "Wednesday"
        5 => "Thursday"
        6 => "Friday"
        7 => "Saturday"

var testTable = table.new(position = position.top_right, columns = 1, rows = 1, bgcolor = color.yellow, border_width = 1)

if barstate.islast
    table.cell(table_id = testTable, column = 0, row = 0, text = f_get_day())

redpajama_set_name: RedPajamaStackExchange


text:
Q: In WPF , how to find out if a pressed key is a input key or not (one which prints something or not )? I am having some requirement in which I have to find out if the key pressed is a input key.
I have a TextBox with a previewkeydown event.
 <TextBox PreviewKeyDown="MyTextBox_PreviewKeyDown" ></TextBox>

Then I have the code for event handler here
    private void MyTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        //I need to find out here if key pressed is
        // an input key something like
        // if ( key is between a to z or 0 to 9 or some_character_input)
        // {
        //
        // }
        //else
        //{
        //     Key is either F1,F2,UpArrow, DownArrow, etc
        // }
    }

Please guide me how to go about with it.

A: (int)e.Key between 44 and 69 are alphabets. Between 90 and 113 are function keys. Decompile System.Windows.Input.Key enum in reflector or dotpeek you will get values for all keys.


text:
Q: Jboss | Unable to load certificate key JBAS015537: Activating WebServices Extension
12:29:34,069 INFO  [org.jboss.ws.common.management.AbstractServerConfig] (MSC service thread 1-4) JBoss Web Services - Stack CXF Server 4.0.2.GA
12:29:34,323 ERROR [org.apache.coyote.http11.Http11AprProtocol] (MSC service thread 1-4) Error initializing endpoint: java.lang.Exception: Unable to load certificate key /mnt/jboss/kjockeystore (error:0906D06C:PEM routines:PEM_read_bio:no start line)
        at org.apache.tomcat.jni.SSLContext.setCertificate(Native Method) [jbossweb-7.0.13.Final.jar:]
        at org.apache.tomcat.util.net.AprEndpoint.init(AprEndpoint.java:644) [jbossweb-7.0.13.Final.jar:]
        at org.apache.coyote.http11.Http11AprProtocol.init(Http11AprProtocol.java:121) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.connector.Connector.init(Connector.java:983) [jbossweb-7.0.13.Final.jar:]
        at org.jboss.as.web.WebConnectorService.start(WebConnectorService.java:267) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1146) [rt.jar:1.6.0_27]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.6.0_27]
        at java.lang.Thread.run(Thread.java:701) [rt.jar:1.6.0_27]

12:29:34,440 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC00001: Failed to start service jboss.web.connector.https: org.jboss.msc.service.StartException in service jboss.web.connector.https: JBAS018007: Error starting web connector
        at org.jboss.as.web.WebConnectorService.start(WebConnectorService.java:271)
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1146) [rt.jar:1.6.0_27]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.6.0_27]
        at java.lang.Thread.run(Thread.java:701) [rt.jar:1.6.0_27]
Caused by: LifecycleException:  Protocol handler initialization failed: java.lang.Exception: Unable to load certificate key /mnt/jboss/kjockeystore (error:0906D06C:PEM routines:PEM_read_bio:no start line)
        at org.apache.catalina.connector.Connector.init(Connector.java:985)
        at org.jboss.as.web.WebConnectorService.start(WebConnectorService.java:267)
        ... 5 more

12:29:34,475 INFO  [org.apache.coyote.http11.Http11AprProtocol] (MSC service thread 1-3) Starting Coyote HTTP/1.1 on http--0.0.0.0-80
12:29:34,874 INFO  [org.jboss.as.remoting] (MSC service thread 1-3) JBAS017100: Listening on /0.0.0.0:9999

Connector tag used in Standalone.xml is below.
<connector name="https" protocol="HTTP/1.1" scheme="https" socket-binding="https" enable-lookups="true" secure="true">
                <ssl password="keystore@kjoc" certificate-key-file="/mnt/jboss/kjockeystore" verify-client="false" certificate-file="/mnt/jboss/WORKCOMP.KERLANJOBE.COM.key"/>
            </connector>

A: Based on this line of your error: (error:0906D06C:PEM routines:PEM_read_bio:no start line) the problem is that JBOSS is using native APR libraries. To make JBOSS use JRE libraries, in the subsystem you have to put "native=false".
This answer is on this post which solved my problem..


text:
Q: Uninstall php 7 in ubuntu 18.04 I have a server that has an application that runs with PHP 5.6. But I upgraded the server from Ubuntu 14.04 to 18.04 and in the process I also upgraded PHP to 7.2.
Now I'm trying to uninstall it but I'm finding difficult.
I have run the command:
sudo apt-get remove php
and
sudo apt-get remove --purge php
Its says that PHP it's not installed, but running
php --version
I'm still seeing the version 7 of PHP.

PHP 7.2.19-0ubuntu0.18.04.2 (cli) (built: Aug 12 2019 19:34:28) ( NTS )
  Copyright (c) 1997-2018 The PHP Group
  Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
      with Zend OPcache v7.2.19-0ubuntu0.18.04.2, Copyright (c) 1999-2018, by Zend Technologies

A: Firstly you need to restart the apache to take all in effect and also
You can install mutliple php version using this post
or just using
sudo apt update
sudo apt-add-repository ppa:ondrej/php
sudo apt update
sudo apt install -y php5.6 php5.6-cli php5.6-common

disable php7.2:
sudo a2dismod php7.2

enable php 5.6:
sudo a2enmod php5.6

After all restart the apache again to take into affect
service apache2 restart

A: This will remove PHP
sudo apt-get purge `dpkg -l | grep php7.2| awk '{print $2}' |tr "\n" " "`
sudo apt-get purge php7.*
sudo apt-get autoremove --purge
whereis php
sudo rm -rf /etc/php

A: To uninstall PHP
sudo apt-get remove –purge php*
sudo apt-get purge php*
sudo apt-get autoremove
sudo apt-get autoclean
sudo apt-get remove dbconfig-php
sudo apt-get dist-upgrade

The output of the below command will provide you with information on the installed package software, version, architecture, and a short description of the package. grep command is used to find the PHP package
sudo dpkg --get-selections | grep php | cut -f 1

sudo apt-get remove --purge
sudo whereis php
sudo rm -rf <directory/file path from the previous command output>

A: Just run
sudo apt-get purge 'php*'

A: This will remove all php7 versions, be it php 7.0 or php 7.1 etc..
sudo apt-get purge php7.*
sudo apt-get autoclean
sudo apt-get autoremove

*

*apt/apt-get autoclean → cleans obsolete deb-packages, less than clean

*apt/apt-get autoremove → removes orphaned packages which are not longer needed from the system, but not purges them, use the --purge option together with the command for that.

**To Install PHP again **
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update

if php7.0
sudo apt-get install php7.0

if php7.1
sudo apt-get install php7.1

if php7.2
sudo apt-get install php7.2

To switch that to the newer 7.1,7.2,7.3,7.4 version, first disable older PHP version:
user@test:~# sudo a2dismod php7.0

Then enable PHP 7.2:
user@test:~# sudo a2enmod php7.2
sudo service apache2 restart

Install all the required extension, so it won't make any error in future.
Replace command based on your version. I used 7.2 as I have installed that version.
sudo apt install php7.2-common php7.2-mysql php7.2-xml php7.2-xmlrpc php7.2-curl php7.2-gd php7.2-imagick php7.2-cli php7.2-dev php7.2-imap php7.2-mbstring php7.2-opcache php7.2-soap php7.2-zip php7.2-intl -y

A: apt-mark to the rescue
I think it is a good idea to point out the existence of apt-mark hold <package-name>.
Once you have a specific version installed that you want to keep, you can prevent accidental upgrades. So you can run apt upgrade, apt full-upgrade and don't need to worry about which PHP version you will end up with.
That said, you also prevent scenarios (as seen with the commenters above) where you end up with multiple major and main releases installed next to each other at the same time.
For example, if you have PHP 7.4 installed, and your App doesn't support PHP 8.* yet, then:
apt-mark hold php7.4-common
apt-mark hold php7.4-fpm

A: This is work on my server:
sudo apt purge php5.6 php5.6-common
sudo apt purge php7.x php7.x-common


text:
Q: Alphabetically sorting upper followed by its respective lower and everything should be in sorted manner There is no duplicates present in the input string .
Ex AbBa
output = AaBb
Ex = ACdac
output = AaCcd
Ex = ADaEedb
output = AabDdEe
please guide me my code not run for the last test case anyone having diffrent idea please comment if lang will be c++ than it will be easy for me to understand

c++

#include<bits/stdc++.h>
using namespace std;

void swap(char *a,char *b){
char temp = *a;
*a = *b;
*b =temp;
}
int main(){
string copy1;
string s ;
cin>>s;
int j=-1;

int left = 0;
int right = s.length()-1;

while(left<right){

    if(s[left] >= 'a'  && s[right]<='z'){
        swap(&s[left],&s[right]);
        right--;
    }
    else
        left++;

}

cout<<s<<endl;
priority_queue <char, vector<char>, greater<char> > pq;
    for(int i=0;i<s.length();i++){
            if(s[i]>='A' && s[i]<='Z'){
                pq.push(s[i]);
                }
    }

    for(int i=0;i<s.length();i++){
            if(pq.empty()==false){
                char m = pq.top();
                if(find(s.begin(),s.end(),(char)(m+32))!=s.end()){
                        copy1+=(char)m;
                        copy1+=(char)(m+32);
                        pq.pop();
                    }
                else{
                copy1+=(char)m;
                pq.pop();
                }
            }
    }

cout<<copy1<<endl;

}
*/

A: A quick implementation using as much of the standard library as possible:
#include <cctype>
#include <algorithm>
#include <string>
#include <iostream>

int main(){
    auto compare = [](char a, char b){
        char upperA = std::toupper(a);
        char upperB = std::toupper(b);
        if(upperA != upperB) return upperA < upperB;
        if(upperA == a) return true;
        return false;
    };

    std::string input = "ADaEedbaaaaa";

    std::sort(input.begin(), input.end(), compare);
    auto endOfUniques = std::unique(input.begin(), input.end());
    input.erase(endOfUniques, input.end());
    std::cout << input << std::endl;
}

If you absolutely have to use std::priority_queue rather than std::sort, this slightly less elegant version works, although it doesn't do any de-duplication (it's not clear to me if "NO Duplicates allowed in string" is a requirement for the input or the output):
#include <cctype>
#include <string>
#include <iostream>
#include <queue>

int main(){
    struct compare{
        bool operator()(char a, char b){
            char upperA = std::toupper(a);
            char upperB = std::toupper(b);
            if(upperA != upperB) return upperA > upperB;
            if(upperA == a) return false;
            return true;
        }
    };

    std::string input = "ADaEedb";

    std::priority_queue<char, std::vector<char>, compare> queue;
    for(auto c : input) queue.push(c);

    std::string output;
    while(!queue.empty()){
        output += queue.top();
        queue.pop();
    }

    std::cout << output << std::endl;
}

A: Store the frequencies of all letters in 2 different arrays (1 for Capital, 1 for small) , and construct string from those arrays which you will get in alphabetical manner.


text:
Q: Toggle fa-thumbs-up icon (or any font-awesome icon) color on click I have multiple thumbs-up icons of font-awesome library on the screen. I want to toggle the color of the icon which is clicked.
How it can be done in AngularJS?

.liked{
  color:#0000ff;
}

.not-liked{
  color:#888;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>

Sorry, I have not written the AngularJS part (click method) because I am not aware with the Angular approach (though I have achieved it with jQuery).

A: You can simply use ng-click and ng-class directives.

.liked{
  color:#0000ff;
}

.not-liked{
  color:#888;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>

Edit: removed extra ng-click.


text:
Q: MessageWebSocket ConnectAsync times out when using TLS 1.2 and self signed certificates I'm trying to send some bytes via a Socket connection to a server using TLS 1.2 and self signed certificates in an UWP app.
I'm trying with the code below, but I get an error: WinRT information: The operation timed out when the line webSocket.ConnectAsync is executed.
I can see with Wireshark that TLS handshake is initiated to the correct ip address and port number.
private static MessageWebSocket messageWebSocket;
    private static DataWriter messageWriter;

    public static async Task<bool> SocketControl()
    {
        try
        {
            //creates a new MessageWebSocket and connects to WebSocket server and sends data to server

            //Make a local copy
            MessageWebSocket webSocket = messageWebSocket;

            //Have we connected yet?
            if (webSocket == null)
            {
                Uri myUri = new Uri("wss://192.168.0.135:51200");
                webSocket = new MessageWebSocket();
                webSocket.Control.MessageType = SocketMessageType.Binary;
                webSocket.MessageReceived += MessageReceived;
                webSocket.Closed += Closed;
                webSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                webSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);

                await webSocket.ConnectAsync(myUri); // Times out here, Output=WinRT information: The operation timed out
                messageWebSocket = webSocket;
                messageWriter = new DataWriter(webSocket.OutputStream);
            }

            messageWriter.WriteBytes(new byte[] {0, 1});
            await messageWriter.StoreAsync();
        }
        catch (Exception ex)
        {
            String.Format("There is an error in connection");
        }
        return true;
    }

    //Sends the data
    private static void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
    {
        try
        {
            using (DataReader reader = args.GetDataReader())
            {
                //reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                //string read = reader.ReadString(reader.UnconsumedBufferLength);
                //var read = reader.ReadBytes();// .ReadString(reader.UnconsumedBufferLength);
                var read = reader.ReadByte();
            }
        }
        catch (Exception ex)
        {
            String.Format("There is an error sending the data");
        }
    }

    // Close connection
    private static void Closed(IWebSocket sender, WebSocketClosedEventArgs args)
    {
        MessageWebSocket webSocket = Interlocked.Exchange(ref messageWebSocket, null);
        if (webSocket != null)
        {
            webSocket.Dispose();
        }
    }

I do have a sample script in Python which works fine without any problems, I just want to do the same in c#
Part of the Python script looks like this:
def main():
sock = socket.socket(socket.AF_INET)
sock.settimeout(10.0)

context = ssl.SSLContext(ssl.PROTOCOL_TLS)
context.check_hostname = False
#accept self-signed certificate
context.verify_mode = ssl.CERT_NONE

conn = context.wrap_socket(sock, server_hostname=KLF200_ADDRESS)

try:
    conn.connect((KLF200_ADDRESS, PORT))
    process_connection(conn)
except BaseException as e:
    raise(e)
finally:
    conn.close()

main()


text:
Q: paypal express checkout without server integration I follow this documentation and has done with below code.
paypal.Button.render({

      env: 'sandbox', // Optional: specify 'sandbox' environment

      client: {
          sandbox: 'xxxxxxxxx',
          production: 'xxxxxxxxx'
      },

      payment: function() {

          var env    = this.props.env;
          var client = this.props.client;

          return paypal.rest.payment.create(env, client, {
              transactions: [
                  {
                      amount: { total: ($scope.qty * 19) + '.00' , currency: 'USD' },
                      item_list: {
                      items: [{
                          "name": "bag",
                          "quantity": $scope.qty,
                          "price": "19.00",
                          "currency": "USD"
                        }]
                    }
                  }
              ]
          });
      },

      commit: true, // Optional: show a 'Pay Now' button in the checkout flow

      onAuthorize: function(data, actions) {

          // Optional: display a confirmation page here

          return actions.payment.execute().then(function() {
              // Show a success page to the buyer
              console.log(data);
              //save data to db

          });
      }

  }, '#paypal-button');

Is that all? What I should do next with paypal? I know I'm going to post something to my server if the 1actions.payment.execute() is not fail. But if that is all, what does the node.js sdk of paypal for? I'm confused now. I tried to pay using test account, but the balance did not get deducted, hmm..

A: This might not be what you are looking for, but it took a while before I figured it out.
To read the information from the transaction you need to call actions.payment.get().
    return actions.payment.execute().then(function() {
                actions.payment.get().then(function(data) {
                 if(data.state === 'approved'){
                   console.log(data);
                   console.log(data.id);
                   // Update orderstatus in backend
                 }else{
                  console.log(data);
                 }
               });
          });


text:
Q: Generator Function - What does the star on = mean? I am going through the Nodeschool exercise on Generators.
The solution to the second exercise is this:
function *factorial (n) {
  var result = 1;
  for (var i = 1; i <= n; i++) {
    result *= i;
    yield result;
  }
}

for (var n of factorial(5)) {
  console.log(n)
}

What does the result *= i mean?

A: *= is a multiplication assignment operator,
result *= i is equal to result = result * i
source mdn

A:
Object-Oriented JavaScript - Second Edition: There is also a family of operators that are a combination of an
  assignment and an arithmetic operator. These are called compound
  operators. They can make your code more compact.

Let's see some of them with examples:
var a = 5;
a = a + 3; // 8

a shorter way:
var a = 5;
a += 3; // 8

In your code this:
result *= i;

is equivalent to:
result = result * i;

A: Based on your question I think you confused the * on function*, which is how you declare a generator, with that in *=. The * in second scenario is the shorthand operator for a = a * b;, as already mentioned but the second is the identifier for the compiler to distinguish a generator from a normal function


text:
Q: How to check if lines exist in file using Ansible? I'm creating an Ansible role to create a user and install rbenv to run my Rails application.
As part of the rbenv installation, you need to modify the PATH and add a line initializing rbenv shims to .bash_profile. I would like to make this role idempotent. Thus, I would like to check if the PATH and rbenv shim initializer are already present in .bash_profile.
I have the following:
- name: Clone rbenv repo
  git: repo=https://github.com/rbenv/rbenv.git
    dest=/home/{{ rails_app_user }}/.rbenv
    force=yes
    update=no

- name: Check if rbenv exists in PATH
  shell: grep 'export PATH="$HOME/.rbenv/bin:$PATH"' /home/{{ rails_app_user }}/.bash_profile
  register: rbenv_path_exists

- name: Add rbenv to PATH
  shell: echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> /home/{{ rails_app_user }}/.bash_profile
  when: rbenv_path_exists.stdout_lines.count == 0

- name: Check if rbenv shims are installed
  shell: grep 'eval "$(rbenv init -)"' /home/{{ rails_app_user }}/.bash_profile
  register: rbenv_shim_exists

- name: Install rbenv shims
  shell: echo 'eval "$(rbenv init -)"' >> /home/{{ rails_app_user }}/.bash_profile
  when: rbenv_shim_exists.stdout_lines.count == 0

However, it seems that grep returns 1 when no match is found, causing Ansible to think a fatal error occurred, terminating the playbook. I tried appending ignore_errors: yes below the PATH and shims check. However, that seems to cause the variables to not be properly registered, causing the PATH and shim installation steps to be skipped due to the when clause.
Output when using ignore_errors: yes:
TASK [rails : Check if rbenv exists in PATH] ***********************************
fatal: [172.16.171.133]: FAILED! => {"changed": true, "cmd": "grep 'export PATH=\"$HOME/.rbenv/bin:$PATH\"' /home/app/.bash_profile", "delta": "0:00:00.005480", "end": "2016-01-30 04:08:01.971000", "failed": true, "rc": 1, "start": "2016-01-30 04:08:01.965520", "stderr": "", "stdout": "", "stdout_lines": [], "warnings": []}
...ignoring

TASK [rails : Add rbenv to PATH] ***********************************************
skipping: [172.16.171.133]

What would an idiomatic way to accomplish this?

A: In general with Ansible you should only really shell out if you can't possibly achieve things with the provided modules. The modules will help make things automatically idempotent and happily handle flagging to Ansible whether anything was changed or if it failed - something that can be done with the shell module but requires a lot of work with changed_when and failed_when.
In your case you can achieve this by using the lineinfile module. A rough go at your particular case might look something like this:
- name: Add rbenv to PATH
  lineinfile:
    dest: /home/{{ rails_app_user }}/.bash_profile
    regexp: ^export .* rbenv/bin
    line: export PATH="$HOME/.rbenv/bin:$PATH"

- name: Install rbenv shims
  lineinfile:
    dest: /home/{{ rails_app_user }}/.bash_profile
    regexp: '^eval .* rbenv init'
    line: 'eval "$(rbenv init -)"'


text:
Q: What is a "24 hours burn in test"? I saw a used LED Monitor for sale and they said that they performed a "24 hours burn in test."  What does that mean, or more specifically what does it mean that a monitor passed this test?  I Googled it and found some software and different discussions about it but I'm still not sure what to expect.

A: 24 hours burn in test has no proper definition for monitors. It could pretty much refer to anything from using the monitor for 24 hours and verifying that it didn't die in the meantime to using a tool like CheckeMON and actually performing a number of tests (colors, convergence, interference, power supply, etc.).
Unless there's at least some information available (e.g., on the manufacturer's website), I suggest disregarding it as a marketing technique. Early failures are covered by the warranty anyway.

A: Generally a burn in test of any type means to subject the piece of equipment to either normal or abnormal conditions for an extended period of time, typically to prove the functionality of the device in question.  I would expect a second hand monitor to be given a 24 hour test to prove that the power supply is not faulty or to detect dead pixels.
Similarly a CPU burn in test generally subjects the computer to heavy load for an extended period in order to prove that the system is stable and does not have overheating problems.

A: A burn-in test simply means that the acquired product have been tested by the manufacturer before it is package to the seller or the store:

Burn-in is the process by which components of a system are exercised
  prior to being placed in service (and often, prior to the system being
  completely assembled from those components).
The intention is to detect those particular components that would fail
  as a result of the initial, high-failure rate portion of the bathtub
  curve of component reliability. If the burn-in period is made
  sufficiently long (and, perhaps, artificially stressful), the system
  can then be trusted to be mostly free of further early failures once
  the burn-in process is complete.
A precondition for a successful burn-in is a bathtub-like failure
  rate, that is, there are noticeable early failures with a decreasing
  failure rate following that period. By stressing all devices for a
  certain burn-in time the devices with the highest failure rate fail
  first and can be taken out of the cohort. The devices that survive the
  stress have a later position in the bathtub curve (with an
  appropriately lower ongoing failure rate).
Thus by applying a burn-in, early in-use system failures can be
  avoided at the expense (tradeoff) of a reduced yield caused by the
  burn-in process.
When the equivalent lifetime of the stress is extended into the
  increasing part of the bathtub-like failure-rate curve, the effect of
  the burn-in is a reduction of product lifetime. In a mature production
  it is not easy to determine whether there is a decreasing failure
  rate. To determine the failure time distribution for a very low
  percentage of the production, one would have to destroy a very large
  number of devices.
When possible, it is better to eliminate the root cause of early
  failures than doing a burn-in. Because of this, a process that
  initially uses burn-in may eventually phase it out as the various root
  causes for failures are identified and eliminated.
For electronic components, burn-in is frequently conducted at elevated
  temperature and perhaps elevated voltage. This process may also be
  called heat soaking. The components may be under continuous test or
  simply tested at the end of the burn-in period.
There is another use of the term by some audiophiles, who leave new
  audio equipment turned on for multiple days or weeks, to get the
  components to achieve optimal performance. However, many debates have
  arisen about the benefits of this practice.

On your specific case it means your monitor have been tested for 24 hours before it been packaged.


text:
Q: Cannot install GTK+3.6.4 When trying to run the ./configure for gtk+-3.6.4 I get the following:

Requested 'glib-2.0 >= 2.35.3' but version of GLib is 2.34.0
Requested 'atk >= 2.7.5' but version of Atk is 2.4.0
Requested 'pango >= 1.32.4' but version of Pango is 1.30.0
Requested 'gdk-pixbuf-2.0 >= 2.27.1' but version of GdkPixbuf is 2.26.1

I downloaded the latest tars and installed them all with ./configure && make then as root make install without an issue, but the problem persists.
I'm running a fresh installation of 12.0.4.2 64bit with all other updates performed before I even started trying to install GTK3.6.4.

A: In your Ubuntu 12.04 installation, add a software repository from (12.10 or 13.04) that contains already the debian package for gtk 3.6.4
Then force that highest version for your gtk-package. And lock it, so it will not be updated.


text:
Q: Copying a file to a user directory using a group policy on Windows Server 2003 with Win 10 clients fails I have a network of around 100 Windows XP boxes, plus a number of Windows 10 ones, in a Windows Server 2003-hosted Active Directory. There's a tender in process to replace both the clients and the server with current hardware and server software, but until that happens I'm stuck with the shortcomings of this server platform.
In any case my task is to make sure that upon login of a domain user, a specific file is copied from the server to his/her directory. This is trivial task if the server is 2008 or later, but for 2003 it isn't.
For that purpose, I've first uploaded the file to be distributed to a network-accessible share, accessible as //UNC_full_path/file.
I then created a GPO (with computer-options disabled) and configured the user section to contain a single startup script. The script file was named (for the sake of completeness) copyfile.cmd and was placed in the section offered by the GPO (\domainname.local\SYSVOL\domainname.local\Policies{policyid}\User\Scripts|logon). The contents of the file was the following command:
IF NOT EXIST "%USERPROFILE%\file" copy \\UNC_full_path\file "%USERPROFILE%"

I finally removed Authenticated users as the target of the policy and added only domain admins, to make some test runs.
On Windows XP after a gpupdate /force /boot and logging as the administrator, everything works as planned: the file is copied to the user directory, if it does not exist. If it exists, nothing happens, as planned.
Making a test run on Windows 7 was also succesful. However, performing the same feat on Windows 10 does not produce anything at all... In fact, Windows 10 clients seem to be "stubborn", disrespecting all GPOs that utilize some sort of cmd-based commands scripts, as I've tested.
I'm clueless as to how I can proceed to troubleshoot this issue. Any ideas will be welcome.
Again, please do remember we are talking Server 2003, so the usual 2008+ tricks do not apply.

A: From Windows 8.1 on, by default, the logon process delays logon scripts for 5 minutes. There are many poorly written or misbehaving logon scripts out there, the 5 minute delay will ensure that the user's desktop remains responsive during the logon process.
However, this may come as a surprise for many organizations especially since the intent of most logon scripts is to perform some action prior to the user interacting with the desktop.
This script execution delay setting is stored in the following GPO location:
Computer Configuration\Administrative Templates\System\Group Policy

The default value setting for the "Configure Logon Script Delay" policy is "Not Configured", which means "five minutes".
The second thing to check for is usually the source of the script: access to the file has to be possible for the computer account. This account (COMPUTER$) will try to fetch the file before handing it over to the local user logon process.
Try to add "Domain Computers" to your Fileserver/NTFS ACL to be sure it can be read by your target machines.


text:
Q: Writing "stochastic matrices" in LaTeX I'm having some notes on stochastic processes and would like to know if there is a less painful way to build stochastic matrices in LaTeX. By painful I want to continue the way I did below.
Question. Is there a more straightforward and economical way to write stochastic matrices in LaTeX? Stochastic matrices have indices above and to the left of matrz aligned with the rows and columns of the matrix. The only way I found to make such an array is by manually adjusting the alignment as in the code below.
$$
\begin{array}{cc ccc c ccc c}
&
&
\hspace*{-5mm}1
&
2
&
3
&
\cdots
&
b-2
&
b-1
&
b
\\
\\
    \begin{array}{c}
    0\\1\\2\\\vdots \\ \\\vdots \\ b-1 \\ b
    \end{array}
&
    \left[
    \begin{array}{c}
    \\ \\ \\ \\  \\ \\  \\  \\
    \end{array}
    \right.
&\hspace*{-4mm}
    \begin{array}{c}
    1\\q\\0\\\vdots \\ \\\vdots \\ 0 \\ 0
    \end{array}
&
    \begin{array}{c}
    0\\r\\q\\\vdots \\ \\\vdots \\ 0 \\ 0
    \end{array}
&
    \begin{array}{c}
    0\\0\\p\\\vdots \\ \\\vdots \\ 0 \\ 0
    \end{array}
&
    \begin{array}{c}
    \cdots \\ \cdots\\ \cdots \\\vdots \\ \\\vdots \\\cdots\\ \cdots
    \end{array}
&
    \begin{array}{c}
    0 \\ 0\\ 0 \\\vdots \\ \\\vdots \\q\\ 0
    \end{array}
&
    \begin{array}{c}
    0 \\ 0\\ 0 \\\vdots \\ \\\vdots \\r\\ 0
    \end{array}
&
    \begin{array}{c}
    0 \\ 0\\ 0 \\\vdots \\ \\\vdots \\p\\ 1
    \end{array}
&\hspace*{-4mm}
    \left.
    \begin{array}{c}
    \\ \\ \\ \\  \\ \\  \\  \\
    \end{array}
    \right]
\end{array}
$$

A: With blkarray you still need some adjustments, not so much as with your code.
\documentclass{article}
\usepackage{amsmath}
\usepackage{blkarray}

\begin{document}

\[
\begin{blockarray}{ *{8}{c} }
& 1 & 2 & 3 & \dots & b-2 & b-1 & b \\
\begin{block}{ c @{\quad} [ @{\,} *{7}{c} @{\,} ] }
0 & 1 & 0 & 0 & \dots & 0 & 0 & 0 \smash[b]{\vphantom{\Big|}} \\
1 & q & r & 0 & \dots & 0 & 0 & 0 \\
2 & 0 & q & p & \dots & 0 & 0 & 0 \\
\vdots & \vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \vdots \\
b-1 & 0 & 0 & 0 & \dots & q & r & p \\
b & 0 & 0 & 0 & \dots & 0 & 0 & 1 \smash[t]{\vphantom{\Big|}} \\
\end{block}
\end{blockarray}
\]

\end{document}


text:
Q: ReactiveMongo with Play Silhouette JWT Authenticator I am currently building a REST Api using Play 2.5 (Scala) using Play Silhouette 4.0 as my authentication library.
I have a need to invalidate JWT per user therefore I will need to persist the authenticator in the database (mongodb). I am using ReactiveMongo 0.12.1.
Following the code examples of Silhouette's CacheAuthenticatorRepository and MongoAuthInfoDAO for ReactiveMongo, I have created an authenticator repository just for the JWT Authenticator like so:
    package modules

    import javax.inject.Inject

    import com.mohiva.play.silhouette.api.StorableAuthenticator
    import com.mohiva.play.silhouette.api.repositories.AuthenticatorRepository
    import modules._
    import com.mohiva.play.silhouette.api.util._

    import scala.concurrent.Future
    import scala.concurrent.duration.Duration
    import scala.reflect.ClassTag

    import com.mohiva.play.silhouette.api.{ AuthInfo, LoginInfo }
    import com.mohiva.play.silhouette.persistence.exceptions.MongoException
    import play.api.Configuration
    import play.api.libs.concurrent.Execution.Implicits._
    import play.api.libs.json.{ Format, JsObject, Json }
    import play.modules.reactivemongo.ReactiveMongoApi
    import play.modules.reactivemongo.json._
    import reactivemongo.api.commands.WriteResult
    import reactivemongo.play.json.collection.JSONCollection

    import play.api.libs.json.Reads

    /**
     * Implementation of the authenticator repository which uses the reactive mongo to persist the authenticator.
     *
     * @param cacheLayer The cache layer implementation.
     * @tparam T The type of the authenticator to store.
     */
    class MongoAuthenticatorRepository[JWTAuthenticator] @Inject() (reactiveMongoApi: ReactiveMongoApi)
      extends AuthenticatorRepository[JWTAuthenticator] {

      def collection: Future[JSONCollection] = reactiveMongoApi.database.map(_.collection("jwt.auth.repo"))

      /**
       * Finds the authenticator for the given ID.
       *
       * @param id The authenticator ID.
       * @return The found authenticator or None if no authenticator could be found for the given ID.
       */
      override def find(id: String): Future[Option[JWTAuthenticator]] = {
        //cacheLayer.find[JWTAuthenticator](id)
        val query = Json.obj("id" -> id)
        collection.flatMap(_.find(query).one[JWTAuthenticator])
      }

      /**
       * Adds a new authenticator.
       *
       * @param authenticator JWTAuthenticatorhe authenticator to add.
       * @return JWTAuthenticatorhe added authenticator.
       */
      override def add(authenticator: JWTAuthenticator): Future[JWTAuthenticator] = {
        //cacheLayer.save[JWTAuthenticator](authenticator.id, authenticator, Duration.Inf)
        val obj = Json.obj("id" -> authenticator.id , "authenticator" -> authenticator, "duration" -> Duration.Inf)
        collection.flatMap(_.insert(obj))
      }

      /**
       * Updates an already existing authenticator.
       *
       * @param authenticator JWTAuthenticatorhe authenticator to update.
       * @return JWTAuthenticatorhe updated authenticator.
       */
      override def update(authenticator: JWTAuthenticator): Future[JWTAuthenticator] = {
        //cacheLayer.save[JWTAuthenticator](authenticator.id, authenticator, Duration.Inf)
        val obj = Json.obj("id" -> authenticator.id , "authenticator" -> authenticator, "duration" -> Duration.Inf)
        collection.flatMap(_.update(Json.obj("id" -> authenticator.id), obj, upsert = true))
      }

      /**
       * Removes the authenticator for the given ID.
       *
       * @param id JWTAuthenticatorhe authenticator ID.
       * @return An empty future.
       */
      override def remove(id: String): Future[Unit] = {
        //cacheLayer.remove(id)
        val query = Json.obj("id" -> id)
        collection.flatMap(_.remove(query))
      }
    }

I then implemented it by modifying my silhouette.module file like so:
      @Provides def provideAuthenticatorService(authenticatorEncoder: AuthenticatorEncoder, idGenerator: IDGenerator, configuration: Configuration, clock: Clock): AuthenticatorService[JWTAuthenticator] = {
          val config = new JWTAuthenticatorSettings(
            fieldName = configuration.underlying.getString("silhouette.authenticator.fieldName"),
            //requestParts = Some(configuration.underlying.getAs[Seq[RequestPart.Value]]("silhouette.authenticator.requestParts").get),
            issuerClaim = configuration.underlying.getString("silhouette.authenticator.issuerClaim"),
            sharedSecret = configuration.underlying.getString("silhouette.authenticator.sharedSecret"),
            authenticatorExpiry = configuration.underlying.getAs[FiniteDuration]("silhouette.authenticator.authenticatorExpiry").get,
            authenticatorIdleTimeout = Some(configuration.underlying.getAs[FiniteDuration]("silhouette.authenticator.authenticatorIdleTimeout").get)
          )
          implicit lazy val format = Json.format[JWTAuthenticator]
          val repo = new MongoAuthenticatorRepository[JWTAuthenticator]
          new JWTAuthenticatorService(config, repo, authenticatorEncoder, idGenerator, clock)
        }

I keep having problems compiling the code and the errors shown are:
"No Json deserializer found for type JWTAuthenticator. Try to implement an implicit Reads or Format for this type."

and
"Imported `MongoAuthenticatorRepository' is permanently hidden by definition of class MongoAuthenticatorRepository in package modules"

I tried to implement a custom JWTAuthenticator class as well and setting implicit formats within the companion object. However the errors still persists.
I am new to Scala as well as Play Framework, would appreciate any pointers or tips on resolving the above issue! Thanks!!


text:
Q: java.lang.NullPointerException at MyCustomAdapter.getView I want to create a multiple contact picker. Initially i am just trying to test if it works or not by providing static values. I thought of implementing a CustomAdapter for performing the task but i am getting java.lang.NullPointerException and according to log cat its at line no. 41 which is paramView = mInflater.inflate(R.layout.custcontactview, null);
Can anyone tell me what thing i am not  doing correctly?
NOTE: If anyone knows a good tutorial about creating multiple contact picker pls provide the link.
Log Cat
10-13 19:44:38.115: E/AndroidRuntime(1461): java.lang.NullPointerException
10-13 19:44:38.115: E/AndroidRuntime(1461):     at com.example.multiplecontacts.MyCustomAdapter.getView(MyCustomAdapter.java:41)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.widget.AbsListView.obtainView(AbsListView.java:1430)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.widget.ListView.makeAndAddView(ListView.java:1745)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.widget.ListView.fillDown(ListView.java:670)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.widget.ListView.fillFromTop(ListView.java:727)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.widget.ListView.layoutChildren(ListView.java:1598)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.widget.AbsListView.onLayout(AbsListView.java:1260)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.view.View.layout(View.java:7175)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.widget.RelativeLayout.onLayout(RelativeLayout.java:912)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.view.View.layout(View.java:7175)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.view.View.layout(View.java:7175)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1254)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1130)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.widget.LinearLayout.onLayout(LinearLayout.java:1047)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.view.View.layout(View.java:7175)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.widget.FrameLayout.onLayout(FrameLayout.java:338)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.view.View.layout(View.java:7175)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.view.ViewRoot.performTraversals(ViewRoot.java:1140)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1859)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.os.Looper.loop(Looper.java:130)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at android.app.ActivityThread.main(ActivityThread.java:3683)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at java.lang.reflect.Method.invokeNative(Native Method)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at java.lang.reflect.Method.invoke(Method.java:507)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-13 19:44:38.115: E/AndroidRuntime(1461):     at dalvik.system.NativeStart.main(Native Method)

custcontactview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="5.0px"
android:paddingLeft="5.0px"
android:paddingTop="5.0px" >

<TextView
    android:id="@+id/txtContactName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="15.0dip"
    android:layout_toLeftOf="@+id/checkBox1"
    android:layout_alignParentLeft="true"
    android:text="Medium Text"
    android:textAppearance="?android:textAppearanceMedium" />

<TextView
    android:id="@+id/txtContactNumber"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/txtContactName"
    android:layout_alignParentLeft="true"
    android:layout_marginLeft="15.0dip"
    android:layout_toLeftOf="@+id/checkBox1"
    android:text="Small Text"
    android:textAppearance="?android:textAppearanceSmall" />

<CheckBox
    android:id="@+id/checkBox1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_marginRight="10dp"
    android:clickable="false"
    android:focusable="false"
    android:focusableInTouchMode="false" />

</RelativeLayout>

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" />

</RelativeLayout>

MainActivity.java
public class MainActivity extends ListActivity {

ListView mListView;
MyCustomAdapter mAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mAdapter = new MyCustomAdapter();
    mListView = getListView();
    mAdapter.addItem("Jay", "+919033953469");
    mAdapter.addItem("Jay", "+918469000500");
    mAdapter.addItem("Tapan", "+919033843969");
    mAdapter.addItem("Tapan", "+919408396544");
    mListView.setAdapter(mAdapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
}

MyCustomAdapter.java
public class MyCustomAdapter extends BaseAdapter {

private LayoutInflater mInflater;
private ArrayList<String> mData = new ArrayList();
private ArrayList<String> mNumber = new ArrayList();

public MyCustomAdapter() {
}

public int getCount() {
    return this.mData.size();
}

public void addItem(String paramString1, String paramString2) {
  this.mData.add(paramString1);
  this.mNumber.add(paramString2);
  notifyDataSetChanged();
}

public Object getItem(int paramInt) {
    return (String) this.mData.get(paramInt);
}

public long getItemId(int paramInt) {
    return paramInt;
}

public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
    if(paramView == null) {
        paramView = mInflater.inflate(R.layout.custcontactview, null);
    }
    /*CheckBox cbx = (CheckBox) paramView.findViewById(R.id.checkBox1);
    cbx.setTag(paramInt);
    TextView tvTitle = (TextView) paramView.findViewById(R.id.txtContactName);
    TextView tvTitle1 = (TextView) paramView.findViewById(R.id.txtContactNumber);
    tvTitle.setText(mData.get(paramInt).toString());
    tvTitle1.setText(mNumber.get(paramInt).toString());*/
    return paramView;
}

public static class ViewHolder {
    public CheckBox cb;
    public TextView nameView;
    public TextView numberView;
}

}

A: mInflater is NULL
public MyCustomAdapter(Context context) {
    mInflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}


text:
Q: What is maximum character column length supported for histograms in oracle 19c? I am new to oracle database. In 12c, max character column supported for histogram is up to 64 characters. What is the maximum column length supported for histogram creation in oracle 19c database?
I gather statistics with 1 histogram bucket for example.
Histogram buckets are set to 1:
SQL<>exec dbms_stats.gather_table_stats('KISH','XTBL',method_opt => 'for all indexed columns size 1');

PL/SQL procedure successfully completed.

SQL<>select column_name,num_distinct from dba_tab_col_statistics where table_name='XTBL';

COLUMN_NAME          NUM_DISTINCT
-------------------- ------------
NAME                       993920
XID                       1000000
CITY                           11
COUNTRY                        11
DEPARTMENT                      9
ZIPCODE                         9
XDATE                      853312
SALARY                          9

SQL<>select column_name,ENDPOINT_NUMBER,ENDPOINT_VALUE from dba_histograms where table_name='XTBL';

COLUMN_NAME          ENDPOINT_NUMBER ENDPOINT_VALUE
-------------------- --------------- --------------
CITY                           99809     3.4475E+35
CITY                          199801     3.4986E+35
CITY                          249772     3.5000E+35
CITY                          350036     3.9675E+35
CITY                          450255     3.9687E+35
CITY                          549819     4.0178E+35
CITY                          649668     4.0207E+35
CITY                          750213     4.0219E+35
CITY                          850367     4.1736E+35
CITY                          950102     4.5371E+35


text:
Q: How do you supply a PMIC beyond its voltage limit? I'm using a power management IC (PMIC) with a lower max Vin than I want to supply. Is the solution to this as simple as adding a separate, greater voltage regulator in front of it?

A: Yes, it is. It can be a switching or linear regulator.


text:
Q: What's the difference between @Autowired and getting a bean from the application context? I have a dao unit test that is declared as follows:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/applicationContext.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class RegisterDaoTest extends AbstractTransactionalJUnit4SpringContextTests {

    ApplicationContext applicationContext = new     FileSystemXmlApplicationContext("classpath:/spring/applicationContext.xml");
    private IRegisterDao registerDao = applicationContext.getBean(IRegisterDao.class);

When I run the unit test, all pass and I can see the db getting recreated in between unit test executions.
My test db is defined as follows:
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
    <property name="url" value="jdbc:hsqldb:mem:test;sql.syntax_ora=true;create=true"/>
    <property name="username" value="sa"/>
    <property name="password" value=""/>
</bean>

<jdbc:initialize-database data-source="dataSource" ignore-failures="DROPS">
    <jdbc:script location="file:Artifacts/Hsql Version Scripts/install/droptables.sql" separator=";"/>
    <jdbc:script location="file:Artifacts/Hsql Version Scripts/install/install.sql" separator="/;"/>
</jdbc:initialize-database>

But when I change my test to use @Autowired, defined below, it does not execute the init db scripts.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/applicationContext.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class RegisterDaoTest extends AbstractTransactionalJUnit4SpringContextTests {

/*
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("classpath:/spring/applicationContext.xml");
    private IRegisterDao registerDao = applicationContext.getBean(IRegisterDao.class);
*/

    @Autowired
    private IRegisterDao registerDao;

I don't see what the difference is.  I have two applicationContext.xmls, one in the main and one in the test (so I can override the db with the test db)
To me, it should execute the same.  Am I missing something?
Thanks,

A: By default, a Spring context will pay no attention to @Autowired annotations. In order to process them, the context needs to have a AutowiredAnnotationBeanPostProcessor bean registered in the context.
<context:annotation-config/>

registers one of these for you (along with a few others), so you do need it (unless you register AutowiredAnnotationBeanPostProcessor yourself, which is perfectly valid).
If you don't like having @Autowired in your code, then you can explicitly inject properties in the XML using , which just moves the clutter from one place to another.
If your context is extremely simple, then you can use implicit autowiring, as described here. Essentially, this tells Spring to autowire automatically by property name or type. This required very little configuration, but it very quickly gets out of control - it's automatic nature means it's hard to control, and gives you very little flexibility.
In general @Autowired really is the best option.
With application context, you are injecting the bean by yourself.
Annotation wiring isn't turned on in the Spring container by default. So, before you
can use annotation-based autowiring, you'll need to enable it in your Spring configuration.
The simplest way to do that is with the
<context:annotation-config>
  <beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
...
</beans>

Hope this helps.

A: These two scenarios are very different: in the first case you've got TWO application contexts: one created by test spring framework and one created manually by you for each test. Spring test framework uses @ContextConfiguration to determine which context files are to be loaded. If subsequent tests use the same context files, the context is not recreated, it is reused. That's why your db is initialized only once if you don't additionally create a new context manually.
If you do need to reinitialize the db for each test, you should trigger it manually for example in @Before method. You may also try annotation @DirtiesContext on your test, next to @ContextConfiguration.
To make it clear: you should not create context manually if using spring test framework. @Autowired is the correct approach but you need to find other means to reinitialize your database before each test.


text:
Q: enable/disable select if radio checked In my HTML i want to check the state for my radio buttons, to see if they are enabled or disabled. I have this HTML structure:

                                <input type="radio" id="rdoLevel" name="rdoSelect"/>

                            ارسال براساس مقطع :

                                <asp:DropDownList ID="ddlTypeLevel" runat="server" ClientIDMode="Static" Enabled="False">
                                    <asp:ListItem></asp:ListItem>
                                    <asp:ListItem>ابتدایی</asp:ListItem>
                                    <asp:ListItem>راهنمایی</asp:ListItem>
                                    <asp:ListItem>دبیرستان</asp:ListItem>
                                    <asp:ListItem>پیش دانشگاهی</asp:ListItem>
                                    <asp:ListItem>دانشگاه</asp:ListItem>
                                </asp:DropDownList>

                                <input type="radio" id="rdoBase" name="rdoSelect"/>

                            ارسال براساس پایه :

                                <asp:DropDownList ID="ddlTypeBase" runat="server" ClientIDMode="Static"  Enabled="False">
                                    <asp:ListItem></asp:ListItem>
                                    <asp:ListItem>اول</asp:ListItem>
                                    <asp:ListItem>دوم</asp:ListItem>
                                    <asp:ListItem>سوم</asp:ListItem>
                                </asp:DropDownList>

                                <input type="radio" id="rdoSchool" name="rdoSelect" />

                            ارسال براساس مدرسه :

                                <asp:TextBox ID="txtSchooNameType" runat="server" ClientIDMode="Static"  Enabled="False"></asp:TextBox>

                                <input type="radio" id="rdoTypeRegistre" name="rdoSelect"/>

                            ارسال براساس نوع ثبت نام :

                                <asp:DropDownList ID="ddlTypeRegister" runat="server" ClientIDMode="Static"
                                    Enabled="False">
                                    <asp:ListItem></asp:ListItem>
                                    <asp:ListItem>ثبت نام</asp:ListItem>
                                    <asp:ListItem>پیش ثبت نام</asp:ListItem>
                                </asp:DropDownList>

                                <asp:Button ID="btnSendByCategory" Enabled="false" runat="server" CssClass="btn btn-small rtl"
                                    Text="ارسال" />

And i use this jquery code for check the states :
$("input:radio").click(function () {
    var id = $(this).attr("id");
    var ddlTypeLevel = $("#ddlTypeLevel");
    if (id == "rdoLevel") {
        if ($(this).is(':checked')) {
            $('select#ddlTypeLevel').prop('disabled', false);
        } else if ($(this).not(':checked')) {
            $('select#ddlTypeLevel').prop('disabled', true);
        }
    }
    else if (id == "rdoBase") {
        if ($(this).is(':checked')) {
            $('select#ddlTypeBase').prop('disabled', false);
        } else if ($(this).not(':checked')) {
            $('select#ddlTypeBase').prop('disabled', true);
        }
    }
    else if (id == "rdoSchool") {
        if ($(this).is(':checked')) {
            $('#txtSchooNameType').prop('disabled', false);
        } else if ($(this).not(':checked')) {
            $('#txtSchooNameType').prop('disabled', true);
        }
    }
    else if (id == "rdoTypeRegistre") {
        if ($(this).is(':checked')) {
            $('select#ddlTypeRegister').prop('disabled', false);
        } else if ($(this).not(':checked')) {
            $('select#ddlTypeRegister').prop('disabled', true);
        }
    }
});

But the above code does not work. Only the enable check works.

A: not doesn't return a boolean value, you can use negation operator instead:
} else if (!$(this).is(':checked')) {

Also when a radio is not checked it's unchecked so there is no need to check the state again.
$("input[type=radio]").change(function () {
    var id = this.id.replace('rdo', '');
    $('#ddlType'+id).prop('disabled', !this.checked);
});

Based on your current logic you can minify your code. note that :radio selector is deprecated.

A: Use attr instead of prop to disable the elements.
Also, you could disable all the elements at the beginnning of the function and after that only enable the one that corresponds to the selected radio button.
Your code could look like this:
$("input:radio").click(function () {
    var id = $(this).attr("id");

    $('select').attr('disabled', 'true');

    if (id == "rdoLevel") {
        if ($(this).is(':checked')) {
            $('select#ddlTypeLevel').attr('disabled', false);
        }
    }
    else if (id == "rdoBase") {
        if ($(this).is(':checked')) {
            $('select#ddlTypeBase').attr('disabled', false);
        }
    }
    else if (id == "rdoSchool") {
        if ($(this).is(':checked')) {
            $('#txtSchooNameType').attr('disabled', false);
        }
    }
    else if (id == "rdoTypeRegistre") {
        if ($(this).is(':checked')) {
            $('select#ddlTypeRegister').attr('disabled', false);
        }
    }
});

Here's a working sample: http://jsfiddle.net/bujkw/2/

Also, another thing I noticed: instead of your if(enabled){}else if(not enabled){} approach, you could simply do if(enabled){}else{}.
Concretely, instead of
if (id == "rdoLevel") {
    if ($(this).is(':checked')) {
        $('select#ddlTypeLevel').prop('disabled', false);
    } else if ($(this).not(':checked')) {
        $('select#ddlTypeLevel').prop('disabled', true);
    }
}

you could simply write
if (id == "rdoLevel") {
    if ($(this).is(':checked')) {
        $('select#ddlTypeLevel').prop('disabled', false);
    } else {
        $('select#ddlTypeLevel').prop('disabled', true);
    }
}

This way the code is a bit more simple and it avoids the issue of using not incorrectly, as pointed out by undefined in his answer.


text:
Q: Unauthorized access in reverse ssh tunnel I created a reverse ssh tunnel between an internal work website and my home workstation. My aim was to work on the remote internal website from my workstation.
There is only a computer between the ends and the issue comes from it. On that computer, there is a ssh client that initiates the tunnel. There is also a ssh server running on that computer but for other needs.
I used this syntaxe below to build the reverse tunnel:
ssh -R 9001:internal-website.com:443 root@homeworkstation.com
Everything worked fine.  But when I checked the connections on the computer between the two ends, I noticed an unauthorized access, and the IP address is from China (121.18.238.125):
root@windy:~# lsof -i
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
dhclient 3356 root    6u  IPv4   5492      0t0  UDP *:bootpc
ntpd     3459  ntp   16u  IPv6   8537      0t0  UDP *:ntp
ntpd     3459  ntp   17u  IPv4   8540      0t0  UDP *:ntp
ntpd     3459  ntp   18u  IPv4   8544      0t0  UDP localhost:ntp
ntpd     3459  ntp   19u  IPv4   8546      0t0  UDP 10.4.103.17:ntp
ntpd     3459  ntp   20u  IPv6   8548      0t0  UDP localhost:ntp
ntpd     3459  ntp   21u  IPv6   8550      0t0  UDP [fe80::dc19:68ff:fe13:d008]:ntp
sshd     3463 root    3u  IPv4   8572      0t0  TCP 10.4.103.17:ssh->home-server:47730 (ESTABLISHED)
sshd     3663 root    3u  IPv4   8736      0t0  TCP *:ssh (LISTEN)
sshd     3663 root    4u  IPv6   8738      0t0  TCP *:ssh (LISTEN)
sshd     3878 root    3u  IPv4   8992      0t0  TCP 10.4.103.17:ssh->home-server:48680 (ESTABLISHED)
sshd     4092 root    3u  IPv4  10068      0t0  TCP 10.4.103.17:ssh->home-server:48092 (ESTABLISHED)
ssh      4445 root    3u  IPv4  14454      0t0  TCP 10.4.103.17:60988->home-server:ssh (ESTABLISHED)
sshd     4481 root    3u  IPv4  15428      0t0  TCP 10.4.103.17:ssh->121.18.238.125:53763 (ESTABLISHED)
sshd     4482 sshd    3u  IPv4  15428      0t0  TCP 10.4.103.17:ssh->121.18.238.125:53763 (ESTABLISHED)

In the /var/log/auth.log file, I couldn't find anything suspicious. Only normal ssh failed attempts. I even found the same address among the failed attempts. I did that experience twice. The first time I deactivated the root password login and set the public key connection. and the second time, I set the password login with a strong password for the root user. And both experiences gave me the same result (different addresses each time but still from china).
How could possibly this computer between the two ends got compromised ? Am I missing something ? I can't figure out where the weak spot is.
For the home workstation to be available to the internet, I enabled a port forwarding on the local router. Once again, I used a strong password and I didn't find any suspicious connection on it.
If you didn't get me well, please don't hesitate to ask for further information.

A: Looks like your lsof -i ist just seeing one of these failed login attempts.
To see similar output you might try to ssh to windy like
ssh windy -l non-existend-user

and watch lsof output while your login attempt asks for a password.
TomTomTom


text:
Q: Access HttpContext in Application_Start ASP.NET MVC 4.0 I would like to access my host and build my bundles.
I know it is not straight to access httpcontext in Application_start.
Can you advise any other work around to find the Request.url.host in RegisterBundles Method
Global.asax
 protected void Application_Start()
        {
          BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

BundleConfig.asax
public static string host { get; set; }
        public static string siteCssFileName { get; set;  }
        public static void RegisterBundles(BundleCollection bundles)
        {
host = "~";
            if (System.Web.HttpContext.Current.Request.Url.Host.Contains("local"))
                host = "http://localhost:xxx";
                else
                host=Request.url.host;
                bundles.Add(new StyleBundle("~/Content/jQuery/ui/css")
                  .Include(host+"/css/jQuery/hro-0079c1/jquery-ui-1.8.11.custom.css"));
         }

A: Edit: Suggesting alternate approaches.
Here's a couple ways to do this:

*

*Create two versions of your bundles

*Add a partial view that checks Request.IsLocal and renders the appropriate set of bundles

*Call the partial view from your layout

An alternate approach would be to create an HtmlHelper method that resolves the path for you.
Yet another approach is to create multiple layouts, and determine the correct one to use in your viewstart.
There are many ways to implement this, there are just a few.

A: Since I could not get my Request object in application start event, I have choose the below approach to achieve my task.
All that I wanted to know was my host in app start event.

*

*Create Web.Config Transform

*Add a app key in each environment like  <add key="cdnReference" value="http://localhost:xxxx/" />

*read the key in your app start event as cdnHost = ConfigurationManager.AppSettings["cdnReference"];


text:
Q: Rapid web requests to many different websites using HttpClient C# My team maintains a tool that is responsible for doing rapid verification of over 1000 different client websites.  The tool is a Windows Service (.NET 4.5.2, C#) that reads requests from a queue, and executes a 'health check' for each request.  It usually handles over 500 requests a minute, but can be responsible for more.  Each request takes a second or two to execute.
A request contains a Uri and credentials needed for doing the health check.  A health check is a POST against the AUTH page with the credentials (the app has custom auth, it's not header based auth), and then a GET to the home page, with a quick verification that it's the home page we expect.  It then goes to a status page in the application, and does some quick checks against that.  The GET requests have to use the cookies from the Set-Cookie header in the auth post.
We've been having performance problems with the tool as it scales.  It currently creates a new HttpWebRequest object for each post and get in the process.  There is a shared CookieContainer that is populated by the first post, so that we can get to the home page and then the status page.
I want to change this service to use the HttpClient object available in .NET 4.5.  The problem is everywhere I read online says you want to avoid rapid creation and destruction of HttpClients.  You'd rather keep one instance alive for the lifetime of the application.  The problem I have is that HttpClient seems to work really well against one endpoint, not many.
I have looked into several options, and am not sure which is best to proceed:

*

*Create a new HttpClient for each request, and use it for the duration of that request.  That means it will live for a couple seconds, and be used for 3 calls.  This would not be easy to implement, but I'm concerned about the overhead of creating and destroying hundreds of HttpClients a minute.

*Figure out if it's possible to use one HttpClient instance for different endpoints by avoiding usage of a BaseAddress, and using the client to pass HttpRequestMessages using SendAsync.  I haven't been able to figure out cookies with this method yet.  To avoid having the HttpClient store the cookies, I set UseCookies to false in the HttpClientHandler, and tried managing cookies via headers in the HttpRequest/ResponseMessages themselves, but it looks like HttpClient simply strips cookies when UseCookies is set to false, so I was unable to pass cookies between request. edit: cookies work fine because they are stored per domain.

*Store several hundred different HttpClient instances in some sort of dictionary, and pull the appropriate one for each Uri as the requests come in.  I'm not sure about the memory overhead on this though.  Also each unique Uri is only verified once every 5 minutes, so I'm not sure if having an HttpClient used once every 5 minutes keeps an unnecessary number of ports open.

*Keep using HttpWebRequests.  Maybe this older method still performs better in this situation.

If anyone has faced a similar issue, I'd love some input on where to proceed on this.
Thanks!

A: The problem with creating new HttpClients for each request is that HttpClientHandler will close the underlying TCP/IP connection.  However, if you are using each HttpClient for the 3 requests to one host and then hitting a different host, then keeping the connection open doesn't help when you move to a new host.  So, you probably will not see perf problem with one client per host.  HttpClient itself is a very lightweight object.  It isn't going to cost much to create one.
However, HttpClient simply delegates the real work to HttpClientHandler which uses HttpWebRequest under the covers, therefore will be unlikely to have any better performance than directly using HttpWebRequest.
If you are looking for better performance, then I suggest looking into replacing HttpClientHandler with the new WinHttpHandler which bypasses HttpWebRequest and goes directly to the Win32 API to make calls.
The full source is available for WinHttpHandler on GitHub so you can see exactly how it handles cookies and credentials.
And I would be really interested to hear if you do get much better perf with WinHttpHandler.

A: To start with, what part of this would you need modified to suit your needs?
var urisToCheck = new List<Uri>(); //get these somehow

//basic auth work?
var credentials = new NetworkCredential("user", "pass");
var handler = new HttpClientHandler { Credentials = credentials };

var client = new HttpClient(handler);

Parallel.ForEach(urisToCheck,
    async uri =>
    {
        var response = await client.GetAsync(uri.AbsoluteUri);
        //check for whatever you want here
    }
 );

A: here's my basic API client that uses the same HttpClient object for every request.
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
//You need to install package Newtonsoft.Json > https://www.nuget.org/packages/Newtonsoft.Json/
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

public class MyApiClient : IDisposable
{
    private readonly TimeSpan _timeout;
    private HttpClient _httpClient;
    private HttpClientHandler _httpClientHandler;
    private readonly string _baseUrl;
    private const string ClientUserAgent = "my-api-client-v1";
    private const string MediaTypeJson = "application/json";

    public MyApiClient(string baseUrl, TimeSpan? timeout = null)
    {
        _baseUrl = NormalizeBaseUrl(baseUrl);
        _timeout = timeout ?? TimeSpan.FromSeconds(90);
    }

    public async Task<string> PostAsync(string url, object input)
    {
        EnsureHttpClientCreated();

        using (var requestContent = new StringContent(ConvertToJsonString(input), Encoding.UTF8, MediaTypeJson))
        {
            using (var response = await _httpClient.PostAsync(url, requestContent))
            {
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
        }
    }

    public async Task<TResult> PostAsync<TResult>(string url, object input) where TResult : class, new()
    {
        var strResponse = await PostAsync(url, input);

        return JsonConvert.DeserializeObject<TResult>(strResponse, new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        });
    }

    public async Task<TResult> GetAsync<TResult>(string url) where TResult : class, new()
    {
        var strResponse = await GetAsync(url);

        return JsonConvert.DeserializeObject<TResult>(strResponse, new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        });
    }

    public async Task<string> GetAsync(string url)
    {
        EnsureHttpClientCreated();

        using (var response = await _httpClient.GetAsync(url))
        {
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();
        }
    }

    public async Task<string> PutAsync(string url, object input)
    {
        return await PutAsync(url, new StringContent(JsonConvert.SerializeObject(input), Encoding.UTF8, MediaTypeJson));
    }

    public async Task<string> PutAsync(string url, HttpContent content)
    {
        EnsureHttpClientCreated();

        using (var response = await _httpClient.PutAsync(url, content))
        {
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();
        }
    }

    public async Task<string> DeleteAsync(string url)
    {
        EnsureHttpClientCreated();

        using (var response = await _httpClient.DeleteAsync(url))
        {
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();
        }
    }

    public void Dispose()
    {
        _httpClientHandler?.Dispose();
        _httpClient?.Dispose();
    }

    private void CreateHttpClient()
    {
        _httpClientHandler = new HttpClientHandler
        {
            AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
        };

        _httpClient = new HttpClient(_httpClientHandler, false)
        {
            Timeout = _timeout
        };

        _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(ClientUserAgent);

        if (!string.IsNullOrWhiteSpace(_baseUrl))
        {
            _httpClient.BaseAddress = new Uri(_baseUrl);
        }

        _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeJson));
    }

    private void EnsureHttpClientCreated()
    {
        if (_httpClient == null)
        {
            CreateHttpClient();
        }
    }

    private static string ConvertToJsonString(object obj)
    {
        if (obj == null)
        {
            return string.Empty;
        }

        return JsonConvert.SerializeObject(obj, new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        });
    }

    private static string NormalizeBaseUrl(string url)
    {
        return url.EndsWith("/") ? url : url + "/";
    }
}

Usage
using ( var client = new MyApiClient("http://localhost:8080"))
{
    var response = client.GetAsync("api/users/findByUsername?username=alper").Result;
    var userResponse = client.GetAsync<MyUser>("api/users/findByUsername?username=alper").Result;
}

Register this object as singleton to your dependency injection library. It's safe to reuse because it's stateless.
Do NOT recreate HTTPClient for each request.
Reuse Httpclient as much as possible


text:
Q: Identify current default time zone set in FreeBSD I know sudo tzsetup will prompt me to change time zone settings on FreeBSD.
➥ How can I see the current time zone settings, without making changes?
I know date shows me current time. For example:

Sun Dec  9 05:45:25 UTC 2018

…which I assumes mean the current default time zone is UTC.
But in this case:

Sat Dec  8 21:52:04 PST 2018

The PST is not a true time zone. Such 2-4 letter codes are neither standardized nor unique. True time zones are in the Continent/Region format such as Europe/Africa or Africa/Tunis (see Wikipedia).
How can I see the true time zone set as default?
This posting mentions using an environment variable TZ.
export TZ=America/Los_Angeles

But my FreeBSD 11.2 machine does not have such a variable set. So I suspect that is not the driving factor.

A: The TLDR answer is:
$ POSIXTZ=$(tail -n1 /etc/localtime)
$ echo $POSIXTZ
CET-1CEST,M3.5.0,M10.5.0/3

$ TZNAME=$(find /usr/share/zoneinfo | while read fname; do cmp -s /etc/localtime "$fname" && echo "$fname" | cut -c 21- ; done)
$ echo $TZNAME
Europe/Copenhagen

The current timezone is stored in the file /etc/localtime. As @Kusalananda remarks this can be a symbolic link. But as @JdeBP hints that on FreeBSD this file is normally copied from /usr/share/zoneinfo during setup.
These files originates from textual descriptions in contrib/tzdata
This information is then compiled into a binary format using zic and the format is specified in tzfile
I do not know of a built in utility which directly parses this file. But it should be easy to write in C with the documentation at hand. If we want to stick with what come out of the box we can look at it using hexdump.
hexdump -v -C /etc/localtime

Or if we just want to look at the magic marker:
$ hexdump -v -s 0 -n 5 -e '1/5 "%s\n"' /etc/localtime
TZif2

Or the fields:
tzh_ttisgmtcnt  The number  of UTC/local indicators stored in the file.
tzh_ttisstdcnt  The number  of standard/wall indicators stored in the file.
tzh_leapcnt     The number  of leap seconds for which data is stored in the file.
tzh_timecnt     The number  of ``transition times'' for which data is stored in the file.
tzh_typecnt     The number  of ``local time types'' for which data is stored in the file (must not be zero).
tzh_charcnt     The number  of characters of ``time zone abbreviation strings'' stored in the file.

Using:
hexdump -v -s 19 -n 4 -e '"tzh_ttisgmtcnt: " 1/4 "%9u\n"' /etc/localtime
hexdump -v -s 23 -n 4 -e '"tzh_ttisstdcnt: " 1/4 "%9u\n"' /etc/localtime
hexdump -v -s 27 -n 4 -e '"tzh_leapcnt:    " 1/4 "%9u\n"' /etc/localtime
hexdump -v -s 31 -n 4 -e '"tzh_timecnt:    " 1/4 "%9u\n"' /etc/localtime
hexdump -v -s 35 -n 4 -e '"tzh_typecnt:    " 1/4 "%9u\n"' /etc/localtime
hexdump -v -s 39 -n 4 -e '"tzh_charcnt:    " 1/4 "%9u\n"' /etc/localtime

Results in my case:
tzh_ttisgmtcnt:         0
tzh_ttisstdcnt:         6
tzh_leapcnt:            6
tzh_timecnt:            0
tzh_typecnt:          133
tzh_charcnt:            6

Then we do the following math to figure out where the first ttinfo starts:
43 + (tzh_timecnt * 4) + (tzh_timecnt * 1)
43 + (0 * 4) + (0 * 1) = 43

The wheels slowly falls of:
$ hexdump -v -s 43 -n 6 -e '"ttinfo:\n tt_gmtoff:      " 1/4 "%9u\n tt_isdst:       " 1/1 "%1d\n tt_abbrind:     " 1/1 "%1u\n"' /etc/localtime
ttinfo:
 tt_gmtoff:      2350816009
 tt_isdst:       96
 tt_abbrind:     155

With these numbers I am probably a little off. And this is truly a masochistic way of dealing with it. So I am stopped just short of finding the gold using tt_abbrind
But if we look at the bottom of the tzfile specification we find this little nugget:

After the
  second header and data comes a newline-enclosed, POSIX-TZ-environment-
  variable-style string for use in handling instants after the last transi-
  tion time stored in the file (with nothing between the newlines if there
  is no POSIX representation for such instants).

So it is as easy as:
$ tail -n1 /etc/localtime
CET-1CEST,M3.5.0,M10.5.0/

When you look closer you will notice that /etc/localtime does not contain any Continent/Region setting! But as the file is copied from /usr/share/zoneinfo you can compare them and find the probable file. I have not dived deep enough to confirm if /usr/share/zoneinfo might contain duplicates.
But for me - this works nicely:
$ find /usr/share/zoneinfo | while read fname; do cmp -s /etc/localtime "$fname" && echo "$fname" | cut -c 21- ; done
Europe/Copenhagen

We iterate through all files in /usr/share/zoneinfo and compare each of them with /etc/localtime. cmp using the -s parameter will not display anything and only exit using a value. If the value is zero we will print the name. When printing the name we use cut to remove the first 21 characters to get Continent/Region

A: If the timezone has been set by tzsetup then the current timezone name is saved in /var/db/zoneinfo:
$ sudo tzsetup Europe/Berlin
$ cat /var/db/zoneinfo
Europe/Berlin

This allows to reinstall the timezone file /etc/localtime:
$ sudo rm /etc/localtime
$ sudo tzsetup -r
$ ls -l /etc/localtime
-r--r--r--  1 root  wheel  2309 Feb 15 10:59 /etc/localtime

If the timezone file has been copied manually instead using tzsetup then you have to find the name of the corresponding source file, as explained by Claus Andersen:
$ cd /usr/share/zoneinfo && find . -type f -exec cmp -s /etc/localtime '{}' \; -print | sed 's,^\./,,'
Europe/Berlin

I have tested this with FreeBSD versions 11.3 and 12.1.

A: The current default timezone in used on FreeBSD, as well as on OpenBSD and NetBSD, will be evident from inspecting the /etc/localtime symbolic link.  It will point to a time zone definition file under /usr/share/zoneinfo.
For example:
$ ls -l /etc/localtime
lrwxr-xr-x  1 root  wheel  36 Aug 11 13:51 /etc/localtime -> /usr/share/zoneinfo/Europe/Stockholm

A: The simple cross platform solution is to use date!
$ date +"%Z"
CET
$ date +"%z"
+0100

In your case you probably will get PST again - but I think this answer is important as well for those who can accept that. This take into account if TZ is set in the environment.
And in practical use - the offset is often more usable than the Continent/Region.


text:
Q: spotfire summary table color In Spotfire 6.5.2, is it possible to color a column heading in a summary table? I know how to color values in a regular table but can't find a way to do so in a summary table.
Thank you,
Chris

A: I do not see such option available without any customizations.


text:
Q: Jenkins 2 override plugins.txt I´m migrating from Jenkins 1.6 to Jenkins 2.0. I was using docker to create and run Jenkins.
And in order to configure as immutable jenkins, we used to copy all xml config files and use plugins.txt to install all necessary plugins.
But problem now is, after we init Jenkins and I connect I only see a wizard screen which ask me for a admin password, which is in a path.
After put that password he ask for install plugins, which I was expecting to be installed already.
Once that I finish that wizard I don't have any plugin installed of my plugins.txt list, or I have any user passed in the users folder.
Any idea how to fix this?. in Jenkins 1.6 everything works fine.

A: Where do you put your plugins.txt?
The content of plugins.txt will be installed inside jenkins when you build your image. So you need to rebuild jenkins:2.0 with your own dockerfile.
FROM jenkins:2.0
COPY plugins.txt /usr/share/jenkins/plugins.txt
RUN /usr/local/bin/plugins.sh /usr/share/jenkins/plugins.txt

Put the plugins.txt script inside the same folder.
Content of my plugins.txt
greenballs:1.15

Than build your image with docker build -t my-jenkins:2.0 .
I don't know how you are migrating your jobs but I would think something like deleting the old jenkins container but keeping the persistent docker volume (or mapped folder on your host to which you're mounting). But After the build of the new jenkins start the jenkins using the -v option to bind to your old volume.
$ docker run -d -v /content-folder:/var/jenkins_home -p 8080:8080 my-jenkins:2.0

Jenkins will start with the plugins already installed + the content of your 1.6 configuration.
I was only able to test the part with the plugins and it worked for me. After the docker build I performed docker run -d -p 8080:8080 my-jenkins:2.0. Checked the docker logs of that container to grab the initialAdminPassword. Didn't install any plugin in the editor and created a job. After a succesful run I saw the greenball instead of the blue.


text:
Q: Query is working fine in query browser but not in python code I have a teradata sql query which is working fine in Teradata Studio Express's query browser but when I tried to run the same query in my python code I am getting following error:

(3706, "[42000] [Teradata][ODBC Teradata Driver]Teradata
  DatabaseSyntax error: expected something between '(' and
  '('.")

My query:
td_query = """select
hash_md5((XMLAGG(TRIM(h_age) ORDER BY h_age ASC) (VARCHAR(100))) )hash_age,
hash_md5((XMLAGG(TRIM(h_marks) ORDER BY h_age ASC )(VARCHAR(100)))) hash_marks,
hash_md5((XMLAGG(TRIM(h_id) ORDER BY h_age ASC )(VARCHAR(100)))) hash_id,
hash_md5((XMLAGG(TRIM(h_score) ORDER BY h_age ASC )(VARCHAR(100))))hash_score,
hash_md5((XMLAGG(TRIM(h_name) ORDER BY h_age ASC )(VARCHAR(100))))hash_name,
hash_md5((XMLAGG(TRIM(h_entry) ORDER BY h_entry ASC )(VARCHAR(100))))hash_entry,
SUM(Aggrownum) sum_val,
COUNT(Aggrownum) count_val,
sum_val/count_val row_num
from
(
Select
hash_md5(CAST(age AS VARCHAR(100)))h_age ,
hash_md5(CAST(marks AS VARCHAR(100)))h_marks,
hash_md5(CAST(id AS VARCHAR(100)))h_id,
hash_md5(CAST(score AS VARCHAR(100)))h_score,
hash_md5(CAST(f_name AS VARCHAR(100)))h_name,
hash_md5(CAST(entry AS FORMAT 'yyyy-mm-ddbhh:mi:ss') (char (20)))h_entry,
row_number() over (partition by dob order by  age asc) rno,round(rno/500.0) Aggrownum
from tdwm.student_2
) A group by Aggrownum ORDER BY row_num;
"""

and in python file running it as:
df_teradata = pd.read_sql(td_query, connect)

Where connect is the td.UdaExec object and above code is working fine for other simpler queries such as select * from tdwm.student_2.
I also tried minimized version of the same query I am getting the same error.
This is the code where I'm using td_query:
import pandas as pd
import teradata as td

td_host, td_username, td_passwd, td_dbname = '10.20.181.55', 'dbac', 'dbac', 'tdwm'

udaExec = td.UdaExec(appName="test", version="1.0", logConsole=False)
with udaExec.connect(method="odbc",system=td_host, username=td_username, port=1025,
                            password=td_passwd, driver="Teradata Database ODBC Driver 16.20") as connect:
    df_teradata = pd.read_sql(td_query, connect)

A: I faced similar issue..
The issue with your query is that it contains hash_md5 function which is unknown to teradata python module, that's why the error.
Solution:
Add database name before that function (like you have done before table name tdwm.student_2). So your new query will be:
select
 tdwm.hash_md5((XMLAGG(TRIM(h_age) ORDER BY h_age ASC) (VARCHAR(100))) )hash_age,
 tdwm.hash_md5((XMLAGG(TRIM(h_marks) ORDER BY h_age ASC )(VARCHAR(100)))) hash_marks,
 tdwm.hash_md5((XMLAGG(TRIM(h_id) ORDER BY h_age ASC )(VARCHAR(100)))) hash_id,
 tdwm.hash_md5((XMLAGG(TRIM(h_score) ORDER BY h_age ASC )(VARCHAR(100))))hash_score,
 tdwm.hash_md5((XMLAGG(TRIM(h_name) ORDER BY h_age ASC )(VARCHAR(100))))hash_name,
 tdwm.hash_md5((XMLAGG(TRIM(h_entry) ORDER BY h_entry ASC )(VARCHAR(100))))hash_entry,
 SUM(Aggrownum) sum_val,
 COUNT(Aggrownum) count_val,
 sum_val/count_val row_num
 from
 (
 Select
  tdwm.hash_md5(CAST(age AS VARCHAR(100)))h_age ,
  tdwm.hash_md5(CAST(marks AS VARCHAR(100)))h_marks,
  tdwm.hash_md5(CAST(id AS VARCHAR(100)))h_id,
  tdwm.hash_md5(CAST(score AS VARCHAR(100)))h_score,
  tdwm.hash_md5(CAST(f_name AS VARCHAR(100)))h_name,
  tdwm.hash_md5(CAST(entry AS FORMAT 'yyyy-mm-ddbhh:mi:ss') (char (20)))h_entry,
 row_number() over (partition by dob order by  age asc) rno,round(rno/500.0) Aggrownum
 from tdwm.student_2
 ) A group by Aggrownum ORDER BY row_num;