text:
Q: How to avoid using user profile to perform s3 operations without EC2 instances According to many advices, we should not configure IAM USER but using IAM Role instead to avoid someone managed to grab the user confidential in .aws folder.
Lets say I don't have any EC2 instances. Can I still able to perform S3 operation via AWS CLI? Says aws s3 ls

MacBook-Air:~ user$ aws s3 ls
  Unable to locate credentials. You can configure credentials by running "aws configure".

A: You are correct that, when running applications on Amazon EC2 instances or as AWS Lambda functions, an IAM role should be assigned that will provide credentials via the EC2 metadata service.
If you are not running on EC2/Lambda, then the normal practice is to use IAM User credentials that have been created specifically for your application, with least possible privilege assigned.
You should never store the IAM User credentials in an application -- there have been many cases of people accidentally saving such files into GitHub, and bad actors grab the credentials and have access to your account.
You could store the credentials in a configuration file (eg via aws configure) and keep that file outside your codebase. However, there are still risks associated with storing the credentials in a file.
A safer option is to provide the credentials via environment variables, since they can be defined through a login profile and will never be included in the application code.

A: I don't think you can use service roles on your personal machine.
You can however use multi-factor authentication for AWS CLI

A: You can use credentials on any machine not just EC2.
Follow the steps as described by the documentation for your OS.
http://docs.aws.amazon.com/cli/latest/userguide/installing.html


text:
Q: Как сделать отбор по колонке ДАТА и текущей дате и -5 дней? У меня есть таблица
ФИО МЕЙЛ ДАТА
Яковлев yakovlev@ma.ru 2.06
Рубцов rubcov@ma.ru 25.10
Кравцов kravcov@ma.ru 23.10

Как мне написать запрос к DataFrame что бы он убрал из таблицы людей у кого сегодняшняя дата и -5 в последующем, совпадает с колонкой ДАТА? К примеру у человека ДР 02.06 , так вот за 5 дней и до  03.06 он из таблички должен исчезать?

A: Если преобразовать столбец ДАТА к типу datetime64, добавив текущий год, то задача сводится к сравнению дат:
from datetime import datetime as DT, timedelta

filename = r"D:\download\abc.xlsx"
dob_col = "День\nрождения"

# читаем ДР как строки, а не как вещественные числа
df = pd.read_excel(filename, header=1, dtype={dob_col: str})

days = 5
today = DT.today().date()
dt_from = today - timedelta(days=days)

res = (df
       .assign(dt=pd.to_datetime(df[dob_col] + ".{}".format(today.year), dayfirst=True))
       .query("not (@dt_from <= dt <= @today)")
       .drop(columns="dt"))

результат:
In [119]: res
Out[119]:
   No               ФИ           Направление работы                            ФИО   e-mail  IP       Мобильный День\nрождения  \
0   1   Иванов\nЛеонид                 Директор ДСМ         Иванов Леонид Павлович  a@mt.ru  19  +79160000\n000           16.1
1   2  Иванов\nВиталий            business teamlead       Иванов Виталий\nИванович  p@mt.ru  11  +79160000\n000           2.08
2   3   Иванов\nИльдар  Управление продуктом (сеть)         Иванов Ильдар Иванович  t@mt.ru  10  +79160000\n000          26.06
4   5  Иванов\nАлексей   Управление продуктом (Гео)  Иванов Алексей\nАлександрович  v@mt.ru  16  +79160000\n000          25.05
5   6      Иванов Иван    Управление продуктом (RA)           Иванов Иван Иванович  k@mt.ru  14  +79160000\n000           7.04
6   7    Иванов\nАнтон    Управление продуктом (RA)      Иванов Антон\nГеннадьевич  z@mt.ru  19  +79160000\n000           5.08

  Login\nAD Комна\nта  Табельный\nномер
0         t         3           6888888
1         v         3            488888
2         i         3           2388888
4        aa         3           6888888
5         g    уволен           6888888
6        dd         4           6888888

redpajama_set_name: RedPajamaStackExchange


text:
Q: Binary Java 7 for Mac Is there any binary release of Java 7 (using the Mac/BSD-port project) anywhere?  Some blogs (e.g. Building Java 7 on Mac OS X) have a detailed instructions to build the jdk from source, but I was hoping that someone have a binary of it available for download.
The problem with the instructions is that it's quite annoying to get all the version numbers correct, and slight variations might lead to wasted hours of work.

A: Binary builds of Java 7 for Mac OS X are provided by this Google Code project:
http://code.google.com/p/openjdk-osx-build/

A: This just got released by Oracle: http://jdk7.java.net/macportpreview/

A: I have compiled the OpenJDK 7 and made the binaries available at my lame hosting service: http://www.notnoop.com/open-jdk-7 .
Future readers should feel free to contact me regarding any incompatibilities, portability problems, and such.

A: There is a PPC Mac Binary of Java 7.  That's the only build that I'm aware of being publicized.

A: Dig into comments of this blog post, it's a licensing issue, you might end up building one for yourself, wait for Intel builds from SoyLatte, or official build from Apple.

A: There is a "Java for Mac OS X 10.7 Preview" package available in the Java section of http://connect.apple.com.
It was released 08 Jun 2011.
I have not tried it yet.

A: You may find OpenJDK7 binaries for Mac OS X 10.7.3+ in openjdk-unofficial-builds github project.
Disclaimer: I've built them myself


text:
Q: $\phi(A) =(I_n-A)(I_n+A)^{-1}$ is antisymmetric? Let $U=\{A\in SO_n(\mathbb R)/ \;\det(I_n+A)\neq0\}$. Let $\phi :U\to M_n(\mathbb R)$ the application defined by : $$\phi(A)=(I_n-A)(I_n+A)^{-1}$$
How can I show that $\phi(A)$ is antisymmetric !?
Any help is highlty appreciated!

A: Since $A$ is orthogonal, $AA^T = I$.
Set $\phi = (I-A)(I+A)^{-1}$,
so
$$
\begin{split}
  \phi^T &= ((I+A)^{-1})^T (I-A)^T \\
  &= (I+A^T)^{-1} (I-A^T) \\
  &= (I+A^{-1})^{-1} (I-A^{-1}) \\
  &= (A^{-1}(A+I))^{-1} (A^{-1}(A-I)) \\
  &= (A+I)^{-1}AA^{-1}(A-I).
\end{split}
$$
Here, all the factors commute with each other because they just involve $A$ and $I$.
From this, you can finish the steps to show that $\phi^T = -\phi$.
So $\phi$ is antisymmetric.

A: You are writing down an inverse Cayley transform which is   its own inverse: an involution. You may check all inverses below are nonsingular. Your matrices A are orthogonal (rotation) matrices by definition. The Cayley transform maps antisymmetric to orthogonal matrices, and hence orthogonal to antisymmetric ones. You might be interested in this question.
Since the left and right factor of what you write commute because both terms in each do, you can write
$$
\phi= \frac{I-A}{I+A},  ~~~~~~~~~~~~~A A^T=I, \leadsto \\
A=  \frac{I-\phi}{\phi +I}, ~~~~~~~~~~~~~    \frac{I-\phi}{I+\phi} \frac{I-\phi^T}{I+\phi^T}=I \leadsto \\
 \frac{I-\phi}{I+\phi}=  \frac{I+\phi^T}{I-\phi^T}  ~.
$$
Cayley-transforming both sides again, you conclude that $\phi^T= -\phi$. This is why you had to show the transform is an involution.
Reassure yourself no denominator vanishes. Try a simple example, e.g.
$$
A= \tfrac{1}{2}\begin{bmatrix}\sqrt 3 & -1\\1& \sqrt 3  \end{bmatrix}, ~~~~~~~I-A= \tfrac{1}{2}\begin{bmatrix}2-\sqrt 3 & 1\\-1&2- \sqrt 3  \end{bmatrix},\\
(I+A)^{-1}= \frac{1}{4+2\sqrt3}\begin{bmatrix}2+\sqrt 3 & 1\\-1&2+ \sqrt 3  \end{bmatrix}\\ \implies \phi= \frac{1}{2+\sqrt 3}\begin{bmatrix}0 & 1\\-1&0   \end{bmatrix}
$$


text:
Q: How to get distance between two coordinates with Mapbox I am learning how to use the Mapbox API for my node app and I want to perform calculations on the backend like getting the distance between two coordinates.
How can I achieve this?, the Mapbox documentation doesn't make this clear...
Set-up the SDK
const mapboxSdk = require("mapbox")
let mapbox = new mapboxSdk(process.env.MAPBOX_TOKEN)

// EXAMPLE OF WHAT I WANT TO DO
coordA = {lat : 33.968123, long: -118.419454}

coordB = {{lat : 33.997223, long: -117.929145}}

const distance = await mapbox.getDistance(coordA, coordB)

console.log(distance)

A: I believe Mapbox recommends using the Turf.js library for this type of thing: Turf.js Distance Function. However, the distance between two lat/long coords is a simple geometry problem that doesn't need any external APIs/libraries, and can be calculated from your coordinates using the Haversine Formula. Check this SO question for implementations of the Haversine formula as a javascript function.


text:
Q: Counting characters in a file stream I'm trying to make a function how_many(), which counts the number of characters of a certain type, say "\n" or ",", in a file stream. Here is my (failed) attempt:
int how_many(char mychar, anifstream myfile){
    int result;
    while(!myfile.eof())
    {
       if(myfile.get()==mychar){result=result+1;}
    }
    myfile.close(); // Closes the filestream "my file"
    return result;
}

First question: is "\n" a character or a string? (If so, then I should make the first input a string instead of a character)
Second question: can you explain the resulting error message? (or alternatively, directly point out the misuse of syntax in my code):
 warning: result of comparison against a string literal is unspecified
  (use strncmp instead) [-Wstring-compare]
 note: candidate function not viable: no known conversion from 'const char [2]' to
  'char' for 1st argument

A: "\n" is a string literal that has type const char[2] and contains two characters: '\n' and '\0'.
'\n' - is an escape character literal that has type char.
Take into account that variable result in your function was not initialized.

A: '\n' is a char, whereas "\n" is a string literal (of type const char[2] last one for null )
For counting prefer algorithm
#include <algorithm>
#include <iterator>
//..

std::size_t result = std::count( std::istream_iterator<char>(myfile),
                                 std::istream_iterator<char>(),
                                  mychar
                                ) ;

A: You may want to make a histogram, while you are reading the file:
std::vector<char> character_counts(256); // Assuming ASCII characters

// ...

char c;
while (cin >> c) // The proper way to read in a character and check for eof
{
  character_counts[c]++; // Increment the number of occurances of the character.
}

In the case you posted, you could find the number of '\n' by:
cout << "Number of \'\\n\' is: " << character_counts['\n'] << endl;


text:
Q: R - Plotting mesh with lattice wireframe I'm trying to plot a mesh over some points in 3D to make some kind of landscape. But, actually I have some problems with the lattice wireframe function. The function doesn't show all the vertices. I'm anyway not sure, if the wireframe function is the best way to do this? Basically I'm looking for a function that maps the ListPlot3D function of Mathematica.
library(lattice)

col1 <- c(1.02,1.00,1.02,1.01,1.00,1.00,1.00,1.01,1.00,0.99,1.01,0.98,0.99)
col2 <- c(1.00,0.99,1.00,1.01,0.98,0.99,1.00,1.01,1.02,0.99,1.00,1.01,1.00)
col3 <- c(0.98,0.99,0.99,0.99,1.00,1.00,1.00,1.00,1.00,1.01,1.01,1.01,1.02)

data <- data.frame(phen=col1,param1=col2,param2=col3)

wireframe(phen ~ param1 * param2,
          data=data,
          xlab="param1",
          ylab="param2",
          zlab="phen",shade = T,
          aspect = c(1, 0.2),
          scales=list(arrows=FALSE))

My plot then misses following data points:
p1 <- c(1.02,1.00,0.98)
p2 <- c(1.00,0.98,1.00)
p3 <- c(1.00,1.02,1.00)
p4 <- c(0.99,1.00,1.02)

These are points from the data frame that get not plotted by the wireframe function. It is not clear to me, why they are not included.
wireframe plot with missing points: The red dots are marking data that is actually existing in the data frame, BUT not in the plot
I'm totally running out of ideas what's going on here?
Thanks for any advice on that!
EDIT: added plot


text:
Q: Working with API's in a Angular project I am newbie on API's so this question might be silly.
I am trying to structure login / register on the Angular project and I have API for this. But I checked a lot of login / register structure. They uses one enpoint. Its called '/login' for example. But I have three endpoints:
/authenticate,
/authorize,
/token

authenticate params: username, password, client_id, redirect_uri, scope
authorize params: client_id, client_secret, redirect_uri
/token params: code
I got it login structure by this service:
var loginUser = function (User, callback) {
  var fullApiPath = serviceROOT + 'authentication';
  $http({
    method: 'POST',
    url: fullApiPath,
    data: User
  }).
  success(function (data, status, headers, config) {
    callback(data, status, headers, config);
    console.log('ok');
    $location.url('/profile');
  }).
  error(function (data, status, headers, config) {
    console.log('Fatal request on = ' + fullApiPath);
    callback(data, status, headers, config);
  });
};

Yes, it works but I do not know how to proceed after that or its a good solution.
How can I proceed? Any demo or example for like this structure?
If you can help I would be very happy. Thanks.


text:
Q: Any manifold admitting a genus $0$ Heegaard splitting is homeomorphic to the $3$-sphere I was trying to prove this statement, and multiple sources say that it is clear from the 'Alexander's trick'. However, in the proof that I thought of, I only used the fact that a homeomorphism $f:S^{n-1} \to S^{n-1}$ can be extended to a homeomorphism of $D^n$. Now Wikipedia mentions that some authors indeed call this the Alexander's trick, but I just wanted to make sure that my proof is correct.
What I did was to consider both my manifold $M$ and $S^3$ as $D^3 \cup_{s}D^3$, take any homeomorphism $f:S^2 \to S^2$ of the splitting surface and extend it to homeomorphisms of $D^3$ on 'both sides'. These local homeomorphisms patch up to give a homeomorphism from $S^3$ to $M$.


text:
Q: Using the pygame function pygame.pixelcopy.surface_to_array() I've been sitting on this for a while now but the documentation is really confusing and has no examples.
I'm trying to store the rgb values of every pixel in a surface. I've tried the following code:
original_pixels = numpy.zeros((wn_width, wn_height, 3))
pygame.pixelcopy.surface_to_array(original_pixels, wn, 'P')

but it throws the error ValueError: Unsupport array item type.
From the documentation:

surface_to_array(array, surface, kind='P', opaque=255, clear=0) ->
None The surface_to_array function copies pixels from a Surface object
to a 2D or 3D array. Depending on argument kind and the target array
dimension, a copy may be raw pixel value, RGB, a color component
slice, or colorkey alpha transparency value. Recognized kind values
are the single character codes 'P', 'R', 'G', 'B', 'A', and 'C'. Kind
codes are case insensitive, so 'p' is equivalent to 'P'. The first two
dimensions of the target must be the surface size (w, h).
The default 'P' kind code does a direct raw integer pixel (mapped)
value copy to a 2D array and a 'RGB' pixel component (unmapped) copy
to a 3D array having shape (w, h, 3). For an 8 bit colormap surface
this means the table index is copied to a 2D array, not the table
value itself. A 2D array's item size must be at least as large as the
surface's pixel byte size. The item size of a 3D array must be at
least one byte.
For the 'R', 'G', 'B', and 'A' copy kinds a single color component of
the unmapped surface pixels are copied to the target 2D array. For
kind 'A' and surfaces with source alpha (the surface was created with
the SRCALPHA flag), has a colorkey (set with Surface.set_colorkey()),
or has a blanket alpha (set with Surface.set_alpha()) then the alpha
values are those expected for a SDL surface. If a surface has no
explicit alpha value, then the target array is filled with the value
of the optional opaque surface_to_array argument (default 255: not
transparent).
Copy kind 'C' is a special case for alpha copy of a source surface
with colorkey. Unlike the 'A' color component copy, the clear argument
value is used for colorkey matches, opaque otherwise. By default, a
match has alpha 0 (totally transparent), while everything else is
alpha 255 (totally opaque). It is a more general implementation of
pygame.surfarray.array_colorkey()Copy the colorkey values into a 2d
array.
Specific to surface_to_array, a ValueError is raised for target arrays
with incorrect shape or item size. A TypeError is raised for an
incorrect kind code. Surface specific problems, such as locking, raise
a pygame.error.

By the way if you can just recommend a different approach to achieve the same goal it's all good.

A: Your code is almost correct, but by default numpy.zeros creates an array of floats. However, for use with pygame.pixelcopy.surface_to_array the datatype must be uint8:
original_pixels = numpy.zeros((wn_width, wn_height, 3), dtype=numpy.uint8)
pygame.pixelcopy.surface_to_array(original_pixels, wn, 'P')


text:
Q: Is the Wave Function a Unitary Operator? A unitary operator can be represented as an exponential $$e^{iA}$$
and as we represent the wave function in general as $$e^{i k x}.$$ Does that mean that the wavefunction is unitary as the exponent is also a hermitian Operator?
Is this also the reason why we can switch the order of integration as the wavefunction is unitary?

A: A wave function is an abstract mathematical function which could completely describe about the system under consideration. We define a wave function such that we could derive whatever information from it, provided that will not affect the state of the system. The wave function is not any operator. It's simply a function of position and time.
Any dynamical properties we use in classical physics, we term them as operators in quantum mechanics, like the momentum operator, energy operator etc. These operators acts on the wave function to give the value of the property of the system at that instant. When you operate the wave function by the momentum operator, you will get the momentum eigen value.

A:
and as we represent the wave function in general as $e^{ikx}$

This isn't true.  In general, we represent the wave function as
$$\psi(\mathbf{x}) = \langle\mathbf{x}|\psi\rangle$$
Only in the case that $|\psi\rangle = |\mathbf{p}\rangle$ (a momentum eigenstate) do we have
$$\psi(\mathbf{x}) = \langle\mathbf{x}|\mathbf{p}\rangle = e^{\frac{i}{\hbar}\mathbf{p\cdot x}} = e^{i\mathbf{k \cdot x}}$$
Now, it's true that $e^{i\mathbf{k}' \cdot \hat{\mathbf{x}}}$ is an operator (note the hat over x) - an operator that is a function of the position operator.  A function of an operator is a function of the eigenvalue when operating on an eigenstate so
$$e^{i\mathbf{k}' \cdot \hat{\mathbf{x}}} |\mathbf{x}\rangle = e^{i\mathbf{k' \cdot x}}|\mathbf{x}\rangle$$
thus
$$\langle\mathbf{x}|e^{i\mathbf{k}' \cdot \hat{\mathbf{x}}} |\psi\rangle = e^{i\mathbf{k' \cdot x}}\psi(\mathbf{x})$$
So, this operator, when operating on wavefunction, returns the wavefunction multiplied by a position dependent phase.  What does this do?
Transform to $\mathbf{k}$ space and find that
$$\frac{1}{(2\pi)^{3/2}}\int d^3k\: e^{i\mathbf{k' \cdot x}}\psi(\mathbf{x})e^{-i\mathbf{k}\cdot \mathbf{x}} = \phi(\mathbf{k} - \mathbf{k}')$$
where $\phi(\mathbf{k})$ is the Fourier transform of $\psi(\mathbf{x})$.  In short, the operator $e^{i\mathbf{k}' \cdot \hat{\mathbf{x}}}$ shifts the momentum components of the state by $\mathbf{p}' = \hbar \mathbf{k'}$.
But, and again, $e^{i\mathbf{k}' \cdot \hat{\mathbf{x}}}$ is an operator, not a wavefunction.


text:
Q: Invoke an application installed on your computer from a web page I am currently developing a web application. The application needs to open other applications installed on the computer. The end user will use Windows and Internet Explorer, the application does not have to support other web browsers.
Some people told me that I should use "URL scheme" with javascript, but can not find any example.
I found a possible solution but uses activex, How to launch an EXE from Web page (asp.net)

A: It's not so easy. You need to develop your own plugin for each web browser. Here is some helpfull links NPAPI, PPAPI, and IE BHO.
Another approach is to use ClickOnce application as launcher.

A: this is another possible solution.
Check if URL scheme is supported in javascript
HTML:
URI

Javascript (using jQuery here):
var windowHasFocus;

$(window).focus(function() {
  windowHasFocus = true;
}).blur(function() {
  windowHasFocus = false;
});

function goToUri(uri) {
  document.location = uri;
  setTimeout(function(){
    if(windowHasFocus) {
      if(confirm('You do not seem to have Qobuz installed, do you want to go download it now?')){
        document.location = 'http://www.qobuz.com';
      }
    }
  }, 100);
}

$('a').on('click', function(){
  goToUri($(this).data('uri'));
});


text:
Q: How can I access the values inside a json response rails? So I have installed the gem Httparty on my rails app. I test if its working on my console first so this is what I'm doing:
I get the response first from the url:
rate = HTTParty.get("https://free.currencyconverterapi.com/api/v6/convert?q=USD_PHP").parsed_response

I get this value:
{"query"=>{"count"=>1}, "results"=>{"USD_PHP"=>{"id"=>"USD_PHP", "val"=>54.333011, "to"=>"PHP", "fr"=>"USD"}}}

By this I can access each value doing this:
price = rate["results"]["USD_PHP"]["val"]
54.333011

So basically if you type in 'price' on the console you will get the value of 54.333011.
Meanwhile when I do the steps above with this one:
hero = HTTParty.get("https://api.opendota.com/api/heroes").parsed_response
 [
    {
        "id": 1,
        "name": "npc_dota_hero_antimage",
        "localized_name": "Anti-Mage",
        "primary_attr": "agi",
        "attack_type": "Melee",
        "roles": [
            "Carry",
            "Escape",
            "Nuker"
        ],
        "legs": 2
    },
    {
        "id": 2,
        "name": "npc_dota_hero_axe",
        "localized_name": "Axe",
        "primary_attr": "str",
        "attack_type": "Melee",
        "roles": [
            "Initiator",
            "Durable",
            "Disabler",
            "Jungler"
        ],
        "legs": 2
    },
    {
        "id": 3,
        "name": "npc_dota_hero_bane",
        "localized_name": "Bane",
        "primary_attr": "int",
        "attack_type": "Ranged",
        "roles": [
            "Support",
            "Disabler",
            "Nuker",
            "Durable"
        ],

I get these bunch of data but I can't access each of the value inside when I try my steps above
id = hero["id"]

Traceback (most recent call last):
          2: from (irb):37
          1: from (irb):37:in '[]' TypeError (no implicit conversion of String into Integer)

I get this error.

A: response is in Array of (JSON)hashes
so, you can try this
id = hero[0]["id"]


text:
Q: How to compare two LinearGradients? SwiftUI I have multiple gradients as themes for my app. I want to have a bool that becomes true when the gradient (stored in a variable) is a specific one. However, I keep getting an error:

"Binary operator '==' cannot be applied to two 'LinearGradient'
  operands"

Please HELP!
This is my code:
let pinkGradient = LinearGradient(gradient: Gradient(colors:[Color(red: 123/255, green: 30/255, blue: 122/255), Color(red: 248/255, green: 74/255, blue: 167/255)]), startPoint: .bottomLeading, endPoint: .topTrailing)
let blueGradient = LinearGradient(gradient: Gradient(colors:[Color(red: 0/255, green: 52/255, blue: 89/255), Color(red: 0/255, green: 168/255, blue: 232/255)]), startPoint: .bottomLeading, endPoint: .topTrailing)
let yellowGradient = LinearGradient(gradient: Gradient(colors:[Color(red: 240/255, green: 30/255, blue: 50/255), Color(red: 255/255, green: 189/255, blue: 0/255)]), startPoint: .bottomLeading, endPoint: .topTrailing)

if userData.selectedTheme == pinkGradient { //This is where the error occurs
     self.isPinkThemeSelected = true
} else if userData.selectedTheme == blueGradient { //This is where the error occurs
     self.isBlueThemeSelected = true
} else {
     self.isYellowThemeSelected = true
}

A: You cannot do this directly. Most SwiftUI views are "write-only." Once you've created them, you can't ask how they were created. (Path is a notable exception to this rule.)
Instead, I would recommend isolating your state from the gradient view itself. For example, you can create a Theme struct such as:
struct Theme: Identifiable {
    let id = UUID() // This ensures that even two themes with the same name are unique
    let name: String // This is just for your convenience
    let gradient: LinearGradient
}

extension Theme: Equatable {
    static func == (lhs: Theme, rhs: Theme) -> Bool { lhs.id == rhs.id }
}

let pinkTheme = Theme(name: "pink",
                      gradient: LinearGradient(gradient: Gradient(colors:[
                        Color(red: 123/255, green: 30/255, blue: 122/255),
                        Color(red: 248/255, green: 74/255, blue: 167/255)]),
                                               startPoint: .bottomLeading, endPoint: .topTrailing))

let blueTheme = Theme(name: "blue",
                      gradient: LinearGradient(gradient: Gradient(colors:[
                        Color(red: 0/255, green: 52/255, blue: 89/255),
                        Color(red: 0/255, green: 168/255, blue: 232/255)]),
                                               startPoint: .bottomLeading, endPoint: .topTrailing))

Now you can track selectedThem == pinkTheme.
If you have a fixed number of themes, you could also implement this more simply as an enum:
enum Theme: Equatable {
    case pink
    case blue
    case yellow

    var gradient: LinearGradient {
        switch self {
        case .pink: return LinearGradient(gradient: Gradient(colors:[
            Color(red: 123/255, green: 30/255, blue: 122/255),
            Color(red: 248/255, green: 74/255, blue: 167/255)]),
                                          startPoint: .bottomLeading, endPoint: .topTrailing)
        case .blue: ...
        case .yellow: ...
        }
    }
}


text:
Q: Libgdx how to use shader in 3D I reached a point in my wip game, where I want to make it more eye-appealing. Currently I add some Ambientlight and a Directionla-light to an Environment and render my scene with it. But now I want to add a custom Shader to it. So I have been looking for some tutorials and for some reason in almost every tutorial they have used another "version" of using Shader in their game:

*

*Giving the ModelBatch a String or FileHandle vertex/fragment-shader

*Creating a ShaderProgram with vertex and fragment Shader.

*Creating a new DefaultShader with this vertex and fragment Shader.

*Creating a class, which implements Shader and use this ShaderClass.

I think there are more possibilitis, because there is also ShaderProviderand other classes as well.
I am a bit confused cause of all this posibilities. so I am looking for someone who can point me in the right direction.
To make it easier for you i tell you what i have and what I need:
I have:

*

*A ModelBatch which should draw everything.

*An Array<ModelInstance> instances, to which i wanna apply the Shader.

*A Texture and its NormalMap, both stored as Textures.

*The position, the direction and the color of my light, given as Vector3 and its strength given as float.

*The color of the ambient light and its strength, given as Vector3 and float.

*The light "Falloff" given as Vector3.

I need:

*

*To bind the Texture and its Normal Map to the Shader.

*Give the light pos, direction, color and strength to the Shader.

*Give the ambientlight color and strength to the Shader.

*Give the Falloff Vector to the Shader.

*Use this Shader for all "instances" in the Array, which are all drawn with my ModelBatch.

Another thing I would like to be able to do is, using different Textures for different models.
I have all my ModleInstances with a textured Material. And I have the normal map for all those different Textures. Now i want to be able to bind the right Texture and Normal Map to the Shader, depending on the Texture in the Material of the Modelinstance.
A more "advanced" thing, I would like to if it is possible, is using different Shaders for different ModelTypes in my game (Stonewall uses a Shader without "Specularity" and "Reflection", while Metalwalls use Specularity for example).
What would be the best way to do this things in Libgdx?
How can i bind the different variables i have? (With ShaderProgram i can use setUniformi for example).
Thanks a lot. If you need more information or if it is hard to understand let me know and i will try to create a better question.
Edit: I think the best way in my case creating a new Shader class, which implements Shader. But i would like to hear about all the other possibilities, their pros and their cons, regarding design, performance and possible restrictions.

A: An overall explanation of rendering pipeline of the 3d api can be found here. This tutorial guides you in creating a new Shader from scratch. And this tutorial show how to use custom attributes to pass data to the shader. This wiki page also explains how to use Material Attributes and which Attributes the DefaultShader supports.
In LibGDX there's a difference between a Shader and ShaderProgram. A ShaderProgram is only the GPU implementation (both the vertex and fragment shader program), which is basically only the compiled GLSL files. You can, for example, set uniforms on ShaderProgram and use it to render a mesh. But the ShaderProgram itself does not "know" how it should render a model.
The Shader interface is intended to bridge the gap between the ShaderProgram and the Renderable (the latter being the smallest renderable part of a model). Thus a Shader most commonly encapsulates a ShaderProgram and makes sure it sets the correct uniforms etc. (Note that strictly speaking a Shader doesn't have to encapsulate a ShaderProgram. E.g. before GLES1 support was removed, there also was a GLES1 shader which managed the fixed rendering pipe instead of encapsulating a ShaderProgram)
The BaseShader class is an abstract helper class which implements the Shader interface, encapsulated a ShaderProgram and adds some helper methods to easily set uniforms. If you extend this class, you can easily register and set uniform, e.g. like this:
public class MyShader extends BaseShader {
    public final int u_falloff = register("u_falloff");
    ...
    @Override
    public void render (final Renderable renderable) {
        set(u_falloff, 15f);
        ...
        super.render(renderable);
    }
}

This will set the unifom called "u_falloff" to the specified value 15f (it will call setUniformX). If the ShaderProgram (glsl files) don't implement an uniform called "u_falloff", it will simply ignore the call. You could also check this using: if (has(u_falloff)) { /* calculate falloff and set it */ }. The BaseShader also adds the possibility to use a Validator and Setter for each uniform.
The DefaultShader extends the BaseShader and adds a default implementation for most of the Material Attributes. Have a look at the source if you want to see the naming of each uniform. In practice, if you use the same uniform naming as the DefaultShader does, it is possible to only specify the glsl files and let the DefaultShader take care of setting the uniforms. Of course it is possible to extend the DefaultShader to add additional uniforms.
When you call ModelBatch#render(...), the ModelBatch will query the ShaderProvider for a Shader to use. This is because every possible combination of vertex attributes and material attributes might require a different Shader. For example if you have two ModelInstances (or to be more precise two Renderables), one with a TextureAttribute.Diffuse and one without texture but with a ColorAttribute.Diffuse. Then most commonly, the ShaderProvider needs to create two different Shaders. Note that they can be of the same class (e.g. DefaultShader), but that the underlying GLSL files might be different.
The DefaultShader takes care of this using preprocessor macros (an ubershader). Depending on the vertex attributes and material attributes, it will #define multiple flags, causing the glsl program to be compiled specifically for that combination of vertex and material attributes. Have a look at the glsl files if you want to see how this is done.
So, in practice you will likely need you own ShaderProvider and your own Shader (either by implementing it from scratch, extending BaseShader or extending DefaultShader). You can extends DefaultShaderProvider for this and fall back to the DefaultShader if needed, e.g.:
public class MyShaderProvider extends DefaultShaderProvider {
    ... // implement constructor
    @Override
    protected Shader createShader (final Renderable renderable) {
        if (renderable.material.has(MyCustomAttribute.Type))
            return new MyShader(renderable);
        else
            return super.createShader(renderable);
    }
}

tl;dr If you want to use your own or a modified version of the ubershader, using the same uniforms as the default shader does, then simply provide the glsl files. If you want to use the same uniforms but add an additional uniform or two, then it might be easy to extend DefaultShader. Otherwise (or if you're learning shaders) I would advise to create the shader from scratch as described in This tutorial.


text:
Q: mysql replace ids with names from other table in query Hi I have a table like
matches

match_id, home_team_id, away_team_id, home_team_player_1_id, home_team_player_2_id, ....

and I have tables
teams

team_id, team_name

players

player_id, player_name

Now I am trying to get the query the matches table with the actual names instead of ids.
query_result

match_id, home_team_name, away_team_name, home_team_player_1_name, ...

Is there a neat way to 'replace' ids with the lookup values from the tables?
The only way to do this that I can come up with is to join the teams table for each team and then the player name table for each player. Is there a better way to do this than writing 50 joins?
I dont want to alter the actual match table, just get the names in the query.

A: You need to join the tables 2 times each with a different alias something as
select
m.match_id,
t1.team_name as home_team_name,
t2.team_name as away_team_name,
p1.player_name as home_team_player_1_name
p2.player_name as home_team_player_2_name
from matches m
left join teams t1 on t1.team_id = m.home_team_id
left join teams t2 on t2.team_id = m.away_team_id
left join players p1 on p1.player_id = m.home_team_player_1_id
left join players p2 on p2.player_id = m.home_team_player_2_id


text:
Q: Troubleshooting a DNS issue I created a virtual configuration in VirtualBox for practice but can't get it to work. I have an Ubuntu 14.04 Server as a server and Xubuntu 16.04 as a client. Server has one network interface as a bridge (192.168.1.192) and another in a local network (192.168.56.101), client only one interface in a local network(192.168.56.200). I am trying to set up bind in a DNS forwarder configuration, but the client won't connect to the server.
Server configuration:
-iptables
*filter
:INPUT DROP [1824:109808]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [776:81374]
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -p icmp -j ACCEPT
-A FORWARD -p udp -m multiport --ports 53 -j ACCEPT
-A FORWARD -p tcp -m multiport --ports 53,80,8080,443,110,25,21 -j ACCEPT
COMMIT
# Completed on Mon Feb  6 19:29:11 2017
# Generated by iptables-save v1.4.21 on Mon Feb  6 19:29:11 2017
*nat
:PREROUTING ACCEPT [1983:119530]
:INPUT ACCEPT [2:144]
:OUTPUT ACCEPT [19:1244]
:POSTROUTING ACCEPT [19:1244]
-A POSTROUTING -s 192.168.56.0/24 -j MASQUERADE
COMMIT

/etc/bind/named.conf
// This is the primary configuration file for the BIND DNS server named.
//
// Please read /usr/share/doc/bind9/README.Debian.gz for information on the
// structure of BIND configuration files in Debian, *BEFORE* you customize
// this configuration file.
//
// If you are just adding zones, please do that in /etc/bind/named.conf.local

include "/etc/bind/named.conf.options";
include "/etc/bind/named.conf.local";
include "/etc/bind/named.conf.default-zones";
# Use with the following in named.conf, adjusting the allow list as needed:
 key "rndc-key" {
    algorithm hmac-md5;
    secret "PuLMSMi7CDsY1tG9qGSQBQ==";
 };
#
 controls {
    inet 127.0.0.1 port 953
        allow { 127.0.0.1; } keys { "rndc-key"; };
 };
# End of named.conf

/etc/bind/rndc.conf
#Start of rndc.conf
key "rndc-key" {
    algorithm hmac-md5;
    secret "PuLMSMi7CDsY1tG9qGSQBQ==";
};

options {
    default-key "rndc-key";
    default-server 127.0.0.1;
    default-port 953;
};
# End of rndc.conf

/etc/bind/named.conf.options
acl goodclients {
        192.168.56.0/24;
        localhost;
        localnets;
};

options {
    directory "/var/cache/bind";

    recursion yes;
    allow-query { goodclients; };
    // If there is a firewall between you and nameservers you want
    // to talk to, you may need to fix the firewall to allow multiple
    // ports to talk.  See http://www.kb.cert.org/vuls/id/800113

    // If your ISP provided one or more IP addresses for stable
    // nameservers, you probably want to use them as forwarders.
    // Uncomment the following block, and insert the addresses replacing
    // the all-0's placeholder.

    forwarders {
    8.8.8.8;
    8.8.4.4;
    };
    forward only;
    listen-on port 53 { 192.168.56.101; };

    //========================================================================
    // If BIND logs error messages about the root key being expired,
    // you will need to update your keys.  See https://www.isc.org/bind-keys
    //========================================================================
    dnssec-enable yes;
    dnssec-validation yes;

    auth-nxdomain no;    # conform to RFC1035
    listen-on-v6 { any; };
};

/etc/resolv.conf
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver 8.8.8.8

The bind seems to work fine
sudo service bind9 restart
 * Stopping domain name service... bind9                                                                                WARNING: key file (/etc/bind/rndc.key) exists, but using default configuration file (/etc/bind/rndc.conf)
waiting for pid 1046 to die
                                                                                [ OK ]
 * Starting domain name service... bind9                                                                          [ OK ]

But named does not, in fact named isn't found at all
sudo service named status
named: unrecognized service

Client config
/etc/resolv.conf
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN

I have tried adding 192.168.56.101 (server's interface on the inside network) to resolv.conf, nothing happened.
/etc/network/interfaces
# interfaces(5) file used by ifup(8) and ifdown(8)
auto lo
iface lo inet loopback
auto enp0s3
iface enp0s3 inet static
    address 192.168.56.200
    netmask 255.255.255.0
    broadcast 192.168.56.255
    network 192.168.56.0
    gateway 192.168.56.101

/etc/hosts
127.0.0.1   localhost
127.0.1.1   xubuntu-VirtualBox

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Investigation
ping 8.8.8.8

PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=40 time=148 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=40 time=105 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=40 time=78.9 ms
64 bytes from 8.8.8.8: icmp_seq=4 ttl=40 time=79.2 ms
^C
--- 8.8.8.8 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3004ms
rtt min/avg/max/mdev = 78.928/102.951/148.389/28.314 ms

Ping to the outside world works
telnet 8.8.8.8 53
Trying 8.8.8.8...
Connected to 8.8.8.8.
Escape character is '^]'.
Connection closed by foreign host.

As well as telnet.
ping 192.168.56.101
PING 192.168.56.101 (192.168.56.101) 56(84) bytes of data.
64 bytes from 192.168.56.101: icmp_seq=1 ttl=64 time=0.735 ms
64 bytes from 192.168.56.101: icmp_seq=2 ttl=64 time=0.492 ms
64 bytes from 192.168.56.101: icmp_seq=3 ttl=64 time=0.483 ms
64 bytes from 192.168.56.101: icmp_seq=4 ttl=64 time=0.610 ms
64 bytes from 192.168.56.101: icmp_seq=5 ttl=64 time=0.357 ms
^C
--- 192.168.56.101 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 3997ms
rtt min/avg/max/mdev = 0.357/0.535/0.735/0.129 ms

Ping to the inside server interface suceeds.
telnet 192.168.56.101 53
Trying 192.168.56.101...
telnet: Unable to connect to remote host: Connection timed out

However the telnet doesn't
netstat -anp | grep '53'
(No info could be read for "-p": geteuid()=1000 but you should be root.)
tcp        0      0 192.168.56.101:53       0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:953           0.0.0.0:*               LISTEN      -
tcp6       0      0 :::53                   :::*                    LISTEN      -
udp        0      0 192.168.56.101:53       0.0.0.0:*                           -
udp6       0      0 ::1:53908               ::1:48239               ESTABLISHED -
udp6       0      0 :::53                   :::*                                -
udp6       0      0 ::1:48239               ::1:53908               ESTABLISHED -

But the server is listening on this port.
I enabled forwarding in the firewall, set up forwarding in named.conf, disabled ufw on both ends. What else can go awry?
UPDATE: Edited the firewall rules to:
# Generated by iptables-save v1.4.21 on Tue Feb  7 21:04:56 2017
*nat
:PREROUTING ACCEPT [1:60]
:INPUT ACCEPT [1:60]
:OUTPUT ACCEPT [6:435]
:POSTROUTING ACCEPT [6:435]
-A POSTROUTING -s 192.168.56.0/24 -j MASQUERADE
COMMIT
# Completed on Tue Feb  7 21:04:56 2017
# Generated by iptables-save v1.4.21 on Tue Feb  7 21:04:56 2017
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [123:14050]
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m multiport --ports 53 -j ACCEPT
-A INPUT -p udp -m multiport --ports 53 -j ACCEPT
-A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -p icmp -j ACCEPT
-A FORWARD -p tcp -m multiport --ports 80,8080,443,110,25,21 -j ACCEPT
COMMIT
# Completed on Tue Feb  7 21:04:56 2017

Telnet connects now, however DNS still doesn't.
dig google.com

; <<>> DiG 9.10.3-P4-Ubuntu <<>> google.com
;; global options: +cmd
;; connection timed out; no servers could be reached

Elaboration: firewall and bind are hosted on the same server.

A: The problem with the configuration was twofold:
First, the forwarding server's iptables should be configured to direct incoming DNS requests to the INPUT chain, because otherwise they could not be accepted and processed by bind.
-A INPUT -p tcp -m multiport --ports 53 -j ACCEPT
-A INPUT -p udp -m multiport --ports 53 -j ACCEPT

Secondly, the client's configuration was lacking a dns-nameserver entry in the /etc/network/interfaces file, where it should be if the interface is configured as static.
iface enp0s3 inet static
    address 192.168.56.200
    netmask 255.255.255.0
    broadcast 192.168.56.255
    network 192.168.56.0
    gateway 192.168.56.101
    dns-nameservers 192.168.56.101

If the network interface is configured as a dynamic one, one should edit /etc/dhcp/dhclient.conf and add the following line to it.
prepend domain-name-servers x.x.x.x, y.y.y.y;

Where x.x.x.x and y.y.y.y are the addresses of DNS servers.


text:
Q: Google Sheets variable does not work, hardcode string does I am trying to call a http rest url using Google Sheets custom function.
This works
function getProductDetailsbyEAN(EANCode) {
  EANCode = '8901719255137'
  if (EANCode == undefined) {
    Logger.log("EANCode undefined") ;
    return "undefined EANCode"
  }

  //EANCode = "'" + EANCode + "'"
  Logger.log(EANCode)
  var formData = {
    'gtins': [EANCode],
  };
  Logger.log(formData.toString())

  var options = {
    'method' : 'post',
    'headers' : { 'Authorization':'Bearer mysecuritycode', 'content-type': 'application/json' },
    'payload' : JSON.stringify(formData)
  };
  var URL = "http://myurl"
  var response = UrlFetchApp.fetch(URL, options);
  response = response.toString() ;
  if (response.indexOf("returned code 404") != -1) {
    Logger.log("ResponseError");
    Logger.log(response) ;
    return "ResponseError" ;
  }
  var jsonResponse = JSON.parse(response) ;
  var jsonResponseItems = jsonResponse['items']
  var jsonResponseZerothItem = jsonResponseItems[0] ;
  Logger.log(jsonResponseZerothItem) ;
  return jsonResponseZerothItem ;
  SpreadsheetApp.flush();
}

But if I try to get this working via the parameter it does not, returns 404
This does not work
function getProductDetailsbyEAN(EANCode) {
  //EANCode = '8901719255137'
  if (EANCode == undefined) {
    Logger.log("EANCode undefined") ;
    return "undefined EANCode"
  }

  EANCode = "'" + EANCode + "'"
  Logger.log(EANCode)
  var formData = {
    'gtins': [EANCode],
  };
  Logger.log(formData.toString())

  var options = {
    'method' : 'post',
    'headers' : { 'Authorization':'Bearer myscuritycode', 'content-type': 'application/json' },
    'payload' : JSON.stringify(formData)
  };
  var URL = "http://myurl"
  var response = UrlFetchApp.fetch(URL, options);
  response = response.toString() ;
  if (response.indexOf("returned code 404") != -1) {
    Logger.log("ResponseError");
    Logger.log(response) ;
    return "ResponseError" ;
  }
  var jsonResponse = JSON.parse(response) ;
  var jsonResponseItems = jsonResponse['items']
  var jsonResponseZerothItem = jsonResponseItems[0] ;
  Logger.log(jsonResponseZerothItem) ;
  return jsonResponseZerothItem ;
  SpreadsheetApp.flush();
}

I am missing something really basic on parameter passing. Please advice.

A: I think that in your case, it seems that EANCode is required to be used as the string. So how about this modification?
Please modify the below script in your question as follows.
From:
EANCode = "'" + EANCode + "'"

To:
EANCode = EANCode.toString();

Note:

*

*8901719255137 is less than 9007199254740991 which is Number.MAX_SAFE_INTEGER. So I thought that you can use EANCode.toString().

*From your question, I cannot confirm the method for calling getProductDetailsbyEAN(EANCode). So if above modification was not the direct solution, can you provide the script for calling getProductDetailsbyEAN(EANCode)?

Reference:

*

*toString()
If I misunderstood your question and this was not the result you want, I apologize.


text:
Q: How can I use Tkinter in a virtual environment? I want to use Tkinter in a virtual environment, but I have a problem: Tkinter is not included with the virtual environment.
On this site, I found a solution: adding the environment variable to the \scripts\activate.bat file. I did so, but it wasn't the solution for me.
I get the following while executing an example file:
(learning) c:\Users\jordy\python\learning>python simpleapp_tk.py
Traceback (most recent call last):
  File "simpleapp_tk.py", line 4, in <module>
    import Tkinter
ModuleNotFoundError: No module named 'Tkinter'

(learning) c:\Users\jordy\python\learning\sources>

What is the solution here? How can I make Tkinter working?

A: In python3, use import tkinter instead pf import Tkinter


text:
Q: PyQt4.QtCore.pyqtSignal object has no attribute 'connect' I'm having issues with a custom signal in a class I made.
Relevant code:
self.parse_triggered = QtCore.pyqtSignal()

def parseFile(self):
    self.emit(self.parse_triggered)

Both of those belong to the class: RefreshWidget.
In its parent class I have:
self.refreshWidget.parse_triggered.connect(self.tabWidget.giveTabsData())

When I try to run the program, I get the error:
AttributeError: 'PyQt4.QtCore.pyqtSignal' object has no attribute 'connect'

Help?
Thanks in advance.

A: You also get that error message if you fail to call super() or QObject.__init__() in your custom class.
A checklist for defining custom signals in a class in Qt in Python:

*

*your class derives from QObject (directly or indirectly)

*your class __init__ calls super() (or calls QObject.__init__() directly.)

*your signal is defined as a class variable, not an instance variable

*the signature (formal arguments) of your signal matches the signature of any slot that you will connect to the signal e.g. () or (int) or (str) or ((int,), (str,))

A: To use the signal/slot system you need to have a QObject inherited class.
Here is a simple example:

    from PySide import QtCore
    class LivingBeing(QtCore.QObject):
      bornSignal = QtCore.Signal() # initialise our signal

      def __init__(self,name):
        QtCore.QObject.__init__(self) # initialisation required for object inheritance
        self.bornSignal.connect(self.helloWorld) # connect the born signal to the helloworld function
        self.name = name #
        self.alive = False

      def summonFromClay(self):
        self.alive = True
        self.bornSignal.emit() # emit the signal

      def helloWorld(self):
         print "Hello World !, my name is %s, this place is so great !" % self.name

    # now try the little piece of code
    if __name__ == '__main__':
      firstHuman = LivingBeing('Adam')
      firstHuman.summonFromClay()

A: I had the same problem.
I forgot that if a class uses Signals, then it must inherit from QObject. I was doing some re-factoring and did not pay attention to this.

A: I had the same exact problem as you.
Try moving
self.parse_triggered = QtCore.pyqtSignal()

out of your constructor but inside your class declaration. So instead of it looking like this:
class Worker(QtCore.QThread):
    def __init__(self, parent = None):
        super(Worker, self).__init__(parent)

        self.parse_triggered = QtCore.pyqtSignal()

It should look like this:
class Worker(QtCore.QThread):
    parse_triggered = QtCore.pyqtSignal()

    def __init__(self, parent = None):
        super(Worker, self).__init__(parent)

This might not be at all what you are looking for, but it worked for me. I switched back to old-style signals anyways because I haven't found a way in new-style signals to have an undefined number or type of parameters.

A: I have recently started working with PySide (Nokia's own version of PyQt), and saw the exact same behaviour (and solution) with custom new-style signals. My biggest concern with the solution was that using a class variable to hold the signal would mess things up when I have multiple instances of that class (QThreads in my case).
From what I could see, QtCore.QObject.__init__(self) finds the Signal variable in the class and creates a copy of that Signal for the instance. I have no idea what QObject.__init__() does, but the resulting Signal does proper connect(), disconnect() and emit() methods (and also a __getitem__() method), whereas the class Signal or standalone Signal variables created outside of a QObject-derived class do not have these methods and can't be used properly.

A: Why do you connect directly to the signal, while you can do
self.connect(widget, SIGNAL('parse_triggered()'), listener.listening_method)?
where self is, for example, the form itself, and may be the same as listener


text:
Q: Error in Visual-Studio "No module named 'IPython'" When I run the script:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from IPython.core.debugger import set_trace

But the following error is displayed.

I installed Ipython in the terminal. The version I have is 7.22

Is it related to the interpreters?, These are my options available to select interpreters

How can I fix it?

A: I see you have IPython installed in your base environment, are you sure you selected this as your interpreter in your code editor? In VSCode, you can change this by clicking on 'Python {version}' at the bottom left of your window.


text:
Q: Triangulation of 3-sphere and Hopf Fibration I am currently reading the paper A Minimal Triangulation of the Hopf Map and its Application. In the paper, the authors are trying to describe a triangulation of the 3-sphere into a (abstract) simplicial complex. It is supposed to have 12 vertices, given by gluing the top parts (before the arrow $\eta$) of Figure 1b and 2b, if I understand it correctly. However, I can't find (or visualize) the vertex $D_2$. I saw $D_2$ appears in the formula $W = D_2 * \partial W$ in Figure 2b, but I'm not sure what does the symbol $*$ really means. Is it some sort of product? I would suppose that this"product" gives an edge from $D_1$ to $D_2$. Also, since $\eta$ is the usual Hopf fibration, I should expect the fiber of each vertex $A,B,C,D$ of the tetrahedron in Figure 2b to be $S^1$, so the vertex $D_2$ must connect to the vertex $D_0$ with an edge, but I can't see how (as $D_0$ only appears on the 3-ball $V$). I think this has something to do with the thing St.$_{\partial V}$ appearing in Figure 2b, but (again) I am not sure what that means.
Thanks for the help.


text:
Q: update android sdk permission error I have downloaded the android SDK 8 for linux and following the tutorial typed:
#tools/android update sdk
bash: tools/android: Permission denied

So I tried:
#sudo tools/android update sdk
sudo: unable to execute tools/android: Permission denied

A: Permission denied is because you are trying to execute something from a noexec mounted partition. Either mount with exec rights or use sh ./script. In your case:
cd tools
sh ./android sdk

To remount with exec rights:
sudo mount -o remount,exec /dev/yourpartition

A: it is generaly caused by the files of java, you need to change the rights of the java files in the /usr/bin/
to do that you can execute:
sudo chmod +x /usr/bin/java
sudo chmod +x /usr/bin/javac
sudo chmod +x /usr/bin/javaws

sory for my bad english


text:
Q: JavaScript - Regex split string to array allowing for apostrophes I have some Express middleware which handles a string - a sentence entered by a user through a text field - and does some analysis on it.  For this I need both the words and the punctuation broken into an array.
An example string is:
"It's familiar. Not much has really changed, which is surprising, but
it's nice to come back to where I was as a kid."

As part of the process I replace new lines with
 and split the string into an array
res.locals.storyArray =
res.locals.story.storyText.replace(/(?:\r\n|\r|\n)/g, '
' ).split(" ");

this works to a certain degree but when a sentence contains an apostrophe e.g. "It's familiar. things get thrown out of sync and I get an array like (note that there is detail I'm not showing here regarding how the word gets mapped to its grammar type) :
[ [ '"', 'quote' ],
['It', 'Personal pronoun' ], <--these items are the issue
[ '\'', 'quote' ],   < --------these items are the issue
[ 's', 'Personal pronoun'],  <------these items are the issue
[ 'familiar', 'Adjective' ],
[ '.', 'Sent-final punct' ],
[ 'Not', 'Adverb' ],
[ 'much', 'Adjective' ],
[ 'has', 'Verb, present' ],
[ 'really', 'Adverb' ],
[ 'changed', 'verb, past part' ],
[ ',', 'Comma' ],
[ 'which', 'Wh-determiner' ],
[ 'is', 'Verb, present' ]]

I'm actually surprised that the commas and full stops seem to be split correctly seeing I am only splitting on white space but I'm trying to get my array to be:
[ [ '"', 'quote' ],
[ 'It's, 'Personal pronoun' ],
[ 'familiar', 'Adjective' ],
[ '.', 'Sent-final punct' ],
.....
]

A: You could use String.raw to make sure the string remains correctly in-tact with included punctuation.
The only issue I had was in keeping the "." punctuation marks. For that I added a new replace function before splitting .replace(/\./g, " .") - this was done for all commas as well.
let strArray = myStr.replace(/\./g, " .")
  .replace(/\,/g, " ,")
  .replace(/\"/g, String.raw` " `)
  .split(/\s/g)
  .filter(_=>_);

let myStr = String.raw `"It's familiar. Not much has really changed, which is surprising, but
it's nice to come back to where I was as a kid."`;
let strArray = myStr.replace(/\./g, " .")
  .replace(/\,/g, " ,")
  .replace(/\"/g, String.raw` " `)
  .split(/\s/g)
  .filter(_=>_);

let HTML = myStr.replace(/(?:\r\n|\r|\n)/g, "
");
console.log(myStr);
console.log(strArray);

EDIT: Added replace for comma separation as well.
I'm not sure what you expect to be done about the
 - it seems silly to insert them while trying to turn your string into an array. In the code I've separated the process. You now have a string that spits out with
 tags and another variable that contains the array.
If you have any supplemental information, if this doesn't solve your issue, I'd be happy to help


text:
Q: Catch 22 ModuleNotFoundError: ImportError: If I fix one I get the other I have a Python project that I am trying to package for PyPI but when I get it working with setup.py it stops working as a standalone script.
The directory structure is like:
project_dir
    setup.py
    module_name_dir
        __init__.py
        main.py
        other.py

init.py exports selected methods from main.py. main.py imports various things from other.py
When I write the imports in main.py like
from other import *

Then $ python main.py runs fine but $ python setup.py sdist gives "ModuleNotFoundError: No module named 'other'"
On the other hand when I write the imports like
from .other import *

then $ python setup.py sdist runs fine but $ python main.py gives "ImportError: attempted relative import with no known parent package
"
setup.py script is very straightforward, close to the minimal example:
from setuptools import setup

description=""" ... """
long_description=""" ... """

setup(
    name="",
    version="",
    packages=[module_name],
    url="",
    license='MIT',
    author="",
    author_email="",
    description=description,
    long_description=long_description,
    long_description_content_type='text/markdown',
    keywords='',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'Topic :: System :: Networking',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3'
    ],
)

I assume this apparent catch 22 situation is because I have dome something wrong and not the way it is actually supposed to be. Can anyone help me fix it?

A: In fact you try to use different module names for the same file.
This will not work.
You want create a package:
The module name of the file module_name_dir/main.py is module_name_dir.main
If you want to call the script stand alone you could for example type:
python -m module_name_dir.main
But you cannot (should not) call it with
python module_name_dir/main.py
You should neither cd to module_name_dir and call it with python main.py
Concerning entry points:
This is completely optional, but I thought it might be good to know:
What you could do however is following:
Add an entry to your setup.py.
For example:
    entry_points={
        'console_scripts': [
            'mycmd = module_name_dir.main:main',
            ]
        },

This assumes that module_name_dir/main.py contains a function named main
If you use virtualenvs (which is recommened for developping python packages) you can for testing purposes type
pip install -e .
Then you can type mycmd to start your script

A: You will have to update your setup.py file:
from setuptools import *

description=""" ... """
long_description=""" ... """

setup(
    name="",
    version="",
    packages=[module_name],
    url="",
    license='MIT',
    author="",
    author_email="",
    description=description,
    long_description=long_description,
    long_description_content_type='text/markdown',
    packages = find_packages(),
    keywords='',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'Topic :: System :: Networking',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3'
    ],
)

The find_packages() function will add all external modules along with the main .py file, and if it a CLI, then as @KlausF said, you'll have to include an entry point


text:
Q: Why cannot I print whats in the array token[ ] in this java program The whole idea of the program is to read a file line by line and save each word into an array token[]. I am trying to print the elements in array token[] on to the console using for loop. But it says variable token has not been initialized.
import java.io.*;

public class ReadFile{
    public static void main(String args[]){
        String[] token;
        int i;

            try{
                // Open and read the file
                FileInputStream fstream = new FileInputStream("a.txt");
                BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
                String strLine;
                //Read file line by line and storing data in the form of tokens
                while((strLine = br.readLine()) != null){
                    token = strLine.split(" ");
                }
                in.close();//Close the input stream
            }
            catch (Exception e){//Catch exception if any
                System.err.println("Error: " + e.getMessage());
            }

                   // Why can't I do this printing part?
            for(i=0;i<=token.length;i++){
                System.out.println(token[i]);
            }``
        }// close main()
}// close Class

A: When you're inside a method, such as main, variable declarations are not initialized, you must provide them with an initial value yourself.
eg:
String[] array = new String[0];
or even
String[] array = null;

A: The following Code:
    public class ReadFile{
    public static void main(String args[]){
    String[] token;
    int i;
    try{
        // Open and read the file
        FileInputStream fstream = new FileInputStream("a.txt");
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        //Read file line by line and storing data in the form of tokens
        while((strLine = br.readLine()) != null){
            token = strLine.split(" ");
        }
        in.close();//Close the input stream
    }
    catch (Exception e){//Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }

should be changed to  this one:
    public class ReadFile{
    public static void main(String args[]){
    String[] token = null;//initialize token with null
    int i;
try{
        // Open and read the file
        FileInputStream fstream = new FileInputStream("a.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(fStream));//Don't use DataInputStream as this class is good for reading primitives, length-prefixed strings e.t.c
        StringBuilder sBuilder = new StringBuilder();
        String strLine;
        //Read file line by line and storing data in the form of tokens
        while((strLine = br.readLine()) != null){
            //token = strLine.split(" ");
            sBuilder.append(strLine);
        }
        token = (sBuilder.toString()).split(" ");//Write this line here.
        in.close();//Close the input stream
    }
    catch (Exception e){//Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }

Also change the for loop construct:
for(i=0;i<=token.length;i++){//This will give ArrayOutOfBoundException
        System.out.println(token[i]);
    }

To
if (token != null)
for(i=0; i<token.length; i++){// condition should be checked for i < token.length
        System.out.println(token[i]);
    }

NOTE: As suggested by  @Peter Lawrey DataInputStream should be used especially for reading primitives.

A: This is a matter of scope.
In the scope of main(). token is defined but not initialized.  If you want to use token at this scope level, you have to initialize it.
In the scope of the try...catch block, token is initialized.  Curiously, its value will only matter for the last line, as split() creates a new String[] every time through, and you're reassigning it to token.

A: check this code, you will understand where the problem is.
import java.io.*;
import java.util.*;
public class ReadFile{
public static void main(String args[]){
ArrayList<String[]> tokenlist = new ArrayList<>();
int i;

try{
    // Open and read the file
    FileInputStream fstream = new FileInputStream("health.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
    String strLine;
    //Read file line by line and storing data in the form of tokens
    while((strLine = br.readLine()) != null){
         String[] token = strLine.split(" ");
        tokenlist.add(token);
    }
    //in.close();//Close the input stream
}
catch (Exception e){//Catch exception if any
    System.err.println("Error: " + e.getMessage());
}

       // Why can't I do this printing part?
for(int count=0; count<tokenlist.size();count++){
    String[] token = tokenlist.get(count);
    for(i=0;i<token.length;i++){
        System.out.println(token[i]);
    }
 }

 }// close main()
 }


text:
Q: running pskill.exe "access denied" Im attempting to kill a process remotely by using pskill.
From the command line, pskill works great, but when trying the same command in C# Im getting an access denied error.
    var startInfo = new ProcessStartInfo {
                                            FileName = "pskill.exe",
                                            Arguments = "-t \\" + _currentMachine +
                                                        " -u BobSmith -p Pass123 " + _currentService +
                                                        " /acceptEULA"
                                         };

    try {
        using (Process exeProcess = Process.Start(startInfo)) {
            exeProcess.WaitForExit();
        }
    } catch {
        Console.WriteLine("Cannot forcibly kill process.");
    }

I have even tried creating a .bat file which runs fine manually but I get the same error when trying to call the .bat from C#.
Im on an XP machine attempting to access a win 2003 server.

A: For the next guy...
pskill.exe needed to be run in Win2000 compatibility mode.

A: I would double check your credentials.  It is either that or your process is 'locked'.

A: In C# characters in strings are escaped by default. The string you assign to Arguments contains two escape characters. I suspect that they are turned into a single back slash. Add an @ in front of the string definition to resolve this.
  Arguments = @"-t \\" + _currentMachine +

In any case I would suggest adding code to write the whole command line out to a text file and check that it is as you need it. If the text file has a bat extension can you run it successfully?


text:
Q: Java with Drupal-6/PHP I really dislike PHP, but am pretty comfortable in Java. I have a stable Drupal installation that has been deployed to an Apache/Linux server. I don't know if the server currently supports Java. (What does it take to do that? I have programming in desktop apps for Java but never online before.)
For developing new modules for my site, is there any way that I can write Java and somehow have it work with the PHP?

A: To use Java on a (web) server, you'll probably need:

*

*an installed Java VM,

*a servlet container or a full application server if you'll use some advanced techs like EJBs.

Theoretically you could run a web application without an installed servlet container, but that needs an embedded servlet container or some hacking, though. Most servlet containers or app servers can be used as frontend web servers, but if you decide to move them one step backwards behind the Apache httpd, then with the mod_jk connector plugin, you'll be able to load balance or proxy requests from the Apache web server to your servlet container (note, not just Tomcat: Glassfish and JBoss can be used as well) and hide the Java container from direct web access and provide an additional layer of security and load handling.
If somehow you'd like to run PHP and Java together, that is possible with some mild hacking: use Quercus (which is a Java implementation of the PHP language) on a suitable server (I'd prefer Glassfish v3), pack your app as a war file and you'll be able to run most PHP applications on a Java app server (and no, this doesn't mean any kind of sluggishness).
And, of course, if you push back the original Drupal application from the frontend Apache to a backend Java servlet container, then you'll be able to run Java and PHP apps side by side and the only job left for Apache is to load balance. If you are interested, check the Quercus and Drupal howto.
One more thing I forgot: if you'd like to create new Drupal plugins/modules in Java, that would only work with Quercus or if the Java and PHP apps are connected via web services or a cross-language framework like Protobuf or Thrift (so the view part could be Drupal plugin written in PHP, and business logic in Java running on a remote server). Note that I'm not an experienced Drupal plugin developer.

A: You're much better off simply biting the bullet and developing any custom modules in PHP. Even if you have to learn a good bit of PHP, it will be much much cleaner, more maintainable, and probably even quicker.

A: I feel your pain but seriously learn PHP and write modules in PHP for Drupal.
You wil be surprised how well the Drupal API is written and documented.
Java can be used if you have another system running and need the two to communicate. Java can be the middle man to compare user tables, update them, etc.
This CAN also be done in PHP but Java is probably more efficient (don't quote me)
In my situation I run PHP on MySQL and another system is on .NET/SQL Server so I intend to use java to export data and manage a middle table between the two so neither PHP or .NET has to run large queries on their respective databases.
There is a chance ill stick to PHP though to keep the languages at a minimin...still thinking about it.


text:
Q: Possible to change backend_type of multiselect from varchar to text? We have a very large multiselect with over 1200 options.  If more than a certain number are selected (around 70, give or take the id numbers length), no more additional attribute options can be selected.  The quick answer to this would be to change the backend_type for multiselect to text from varchar.  Is this possible?

A: First you have to disable cache:
public_html/bin/magento cache:disable

Then open your mysql database on the servers console (via ssh/bash):
mysql

Then open the mysql database:
show databases;
use my_magento_database;

Find the attribute_id:
select * from eav_attribute where attribute_code='my_code'\G

Where my_code is the system name for your field, which you can see in the admin attribute configuration page for that attribute or looking at a form field and seeing what its name is.
Next update it:
update eav_attribute set backend_type='text',is_user_defined=0 where attribute_id=138;

Where 138 would be replaced by your attribute_id.  We set is_user_defined=0 because for some reason that stops magento from overwriting your value.
Now you have some cleanup to do:
select * from catalog_product_entity_varchar where attribute_id=138;

You can choose to either delete or migrate this data.  If you want to preserve your data you basically have to select from the varchar table and insert into the text table the only differences between the two tables is the field type of value (one is varchar, one is text who knew).  I deleted mine though because we didn't have any data we cared about yet:
delete from catalog_product_entity_varchar where attribute_id=138;

And you're done, load a product page, save, then verify it worked:
select * from catalog_product_entity_text where attribute_id=138;

If that is empty or only contains the values you copied over then something wasn't changed right and double check your work.
You can now renable caching:
public_html/bin/magento cache:enable


text:
Q: Why won't a 1.5V (or 1.2V) battery give an electric shock? Why won't a standard 1.5V (or 1.2V) battery give an electric shock when touching both ends (positive and negative) in the same time? Even if the battery is capable to provide a short-circuit current of 1-2 amps. It is only because of the human body resistance?

A: The current a voltage source (like a battery in this case) delivers is up to the load.  The current rating is only the maximum the source can deliver.  It can't somehow force this onto the load.  For example, if you connect a 1.5 kΩ resistor accross the 1.5 V battery, only 1 mA will flow.  This will be true whether the battery or power supply was rated for 1 A, 10 A, or 100 mA, since all those are more than the 1 mA the load will draw.
What causes harm to your body and what you feel is current, not voltage.  The published levels of how much current is safe vary quite a bit out there depending on what part of the body and what point the author is trying to make.  You want to be extra careful running current accross the heart and thru the brain.  Between two fingers of the same hand is relavtively safe in that it will be uncomfortable before you get hurt.  You can safely put your fingers accross a 1.5 V battery because the skin resistance prevents any significant current from flowing.  As shown above, it would take 1.5 kΩ just to get 1 mA.  Normal skin resistance is in the 10s of kΩ at least.  You can try dipping your fingers in salt water and then touching both ends of the 1.5 V battery and see if you feel anything.  Again, make sure this is the fingers of the same hand.  That way just in case you get any significant current it will stay local to the hand and not get to the heart or brain.  You can definitely feel a 9 V battery on the tounge, but I don't know if even wet fingers is enough to feel a 1.5 V battery.  If you try it, let us know.

A: You skin resistance will ensure that you get nowhere near 1-2 A. However your skin resistance is from your skin; if you have an open cut it will be much less and you can be harmed much more easily.
Try putting a 9 V battery to your tongue if you wish to feel electricity safely. E&0


text:
Q: What is the rank of a positive definite quadratic form? The text I am studying from seems to suggest that the rank of a quadratic form q on a vector space V is equal to n=dim(V), and I'm confused as to why this is the case.

A: The rank of a quadratic form is certainly not always the dimension of the space, otherwise the notion would be empty. But for a positive definite form, then yes, it is the dimension of the space, because it is non-degenerate (being anisotropic).


text:
Q: When to use "run" vs when to use "ran" My friend is writing some documentation and asked me an English question I don't know the answer to. In this case which would it be?

CCleaner has been run.

or

CCleaner has been ran.

A: Run is an irregular verb with the following forms:

Infinitive / imperative / present - run (third-person singular runs)
Past - ran
Continuous forms with be / gerund / present participle - running
Perfect forms with have / passive forms with be / past participle - run

So you never should say have (been) ran or has (been) ran, it's always have (been) run or has (been) run.
That being said you will hear native speakers get it wrong all the time, especially when the speaker wants to emphasize has run.

A: It is being used with a perfect tense (has been, which usually means present perfect progressive, but not always - see below), so it requires the past participle (for completed action) or present participle (for continuous/still commencing action).
Additionally, your sentence is phrased in the passive voice (because CCleaner is not the agent in the sentence, it was run by something else). In the passive voice an auxiliary (usually) BE verb is used, which is used to give the tense (which would have been given by the main verb in the active voice), and this also requires the past participle of the main verb. Your sentence is using the present perfect tense in the passive voice. If it were not in the passive voice, it would require the progressive, present participle form if been is kept.
In the case of the verb run, the past participle is run and the present participle is running.


text:
Q: I am having some sort of jquery conflict or issue If you take a look at this page http://50.87.6.244/~storeupp/index.php/basketball/lebron-james-dwyane-wade-dual-signed-basketball.html you will notice that everything works great except for the little red arrow that is in the footer. This arrow is suppose to expand an additional footer area. This worked fine until I added the infortis cloudzoon scripts which are:
http://50.87.6.244/~storeupp/js/infortis/jquery/jquery-1.7.1.min.js
http://50.87.6.244/~storeupp/js/infortis/jquery/jquery-noconflict.js
http://50.87.6.244/~storeupp/js/infortis/jquery/plugins/cloud-zoom.1.0.2.min.js

The cloudzoon is what makes the product image larger when hovered over. I also see in the source files that there is a second cloudzoom script and a different version of jquery being called first. I am not sure what the exact issue is here and how to fix it.
Any help would be greatly appreciated.

A: You references jQuery library twice: the first occurence references the 1.6.2 version : <script type="text/javascript" src="http://50.87.6.244/~storeupp/js/etheme/dresscode/jquery-1.6.2.min.js"></script> and then, after a few js files dependent on jQuery you add adding another one script element for 1.7.1 version:  <script type="text/javascript" src="http://50.87.6.244/~storeupp/js/infortis/jquery/jquery-1.7.1.min.js"></script>
Try to replace the 1.6.2 script element with 1.7.1


text:
Q: Continuity of power series proof
I dont understand this proof of continuity, the part under the red line.
1. Why is |y-x| < T-|x| .. where did they get the y from? Also how does this imply |y|

A: The intention is to prove continuity at $x$, that is
$$ \forall\epsilon>0,\exists \delta>0,\forall y\colon |y-x|<\delta\to |f(y)-f(x)|<\epsilon.$$
So you might expect a proof to run as follows:

Let $\epsilon>0$ be given. Then let $\delta = (\ldots)$.
  We want to show that with this choice $|f(y)-f(x)|<\epsilon$ for all $y$ with $|y-x|<\delta$.
  So let $y$ be an real number with $|y-x|<\delta$. Then ...

That's where the $y$ comes from. And as we can demand that $\delta\le T-|x|$ (and whatever additional conditions come to our mind upon further investigation), we can safely assume that $|y-x|<T-|x|$.
And so on. This is just the way that more or less every epsilon-delta proof runs.


text:
Q: wxPython: Copying text from RichTextCtrl I've been trying to figure out how to copy rich text from a RichTextCtrl to the clipboard. I'm able to copy the text just fine, but not the rich text information. For example, if I copy some bold text from my RichTextCtrl and then paste it in to another program, it is just plain text.
Any ideas?
Thanks,
Peter

A: Take a look at the PyRTFParser project.
From the project website:

...the Cut, Copy, and Paste methods in the
  RichTextCtrl support only plain text, not formatted
  text
Cut / Copy / Paste of RTF-formatted text through the
  clipboard between Word on Windows and Word and
  TextEdit on OS X has been implemented in the
  PyRTFParserDemo.py file.


text:
Q: Inserting values to sqlite table results in error: [SQLITE_CONSTRAINT] Abort due to constraint violation (UNIQUE constraint failed: salesman.code) I have created a fully-functional java app with mysql db. I have to change the mysql db to sqlite db to make the app more portable (no installation required). I'm in the process of converting all my mysql tables and values to sqlite.
I was to create the database and tables and now, I'm populating my salesman table from a .csv file selected by the user through FileChooser. After the user selects .csv file that would populate the salesman table, NetBeans would result to this error:
java.sql.SQLException: [SQLITE_CONSTRAINT]  Abort due to constraint violation (UNIQUE constraint failed: salesman.code)
at org.sqlite.core.DB.newSQLException(DB.java:890)
at org.sqlite.core.DB.newSQLException(DB.java:901)
at org.sqlite.core.DB.execute(DB.java:810)
at org.sqlite.core.DB.executeUpdate(DB.java:847)
at org.sqlite.jdbc3.JDBC3PreparedStatement.executeUpdate(JDBC3PreparedStatement.java:86)

After researching for similar problems, it would mean that the values I'm putting in the salesman table are not aligned with the parameters / constraint set with the salesman table. But when I created the table, I did not put any UNIQUE constraint. I made the table using Browser for SQLite and this is the code for creating database and tables:
 try {
        Class.forName("org.sqlite.JDBC");
        conn = DriverManager.getConnection("jdbc:sqlite:sandapp.db");
        String createSalesmanQuery = "CREATE TABLE IF NOT EXISTS salesman (\n" +
                "    code INTEGER PRIMARY KEY\n" +
                "                 NOT NULL,\n" +
                "    name TEXT    NOT NULL\n" +
                ")\n" +
                "WITHOUT ROWID;";

        ps = conn.prepareStatement(createSalesmanQuery);
        ps.executeUpdate();

        String emptySalesmanQuery = "DELETE FROM salesman;"; //empties if there are contents
        ps = conn.prepareStatement(emptySalesmanQuery);
        ps.executeUpdate();
    } catch ( Exception e ) {
        System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        System.exit(0);
    }

The constraint WITHOUT ROWID is there because the attribute code are coming from another database, so there shouldn't be a table id that auto-increments. I already checked the .csv file where all the values for column codes are and there are no repeating values. This file was also used for mysql db and it uploaded successfully.  Anyone have any ideas?
EDIT: Here is my method that gets the salesman details from a .csv file
public static String getSalesmanFromFile(String filePath){
    ArrayList<Salesman> salesmanList= new ArrayList<Salesman>();
    String status = null;
    try {
        BufferedReader br = new BufferedReader(new FileReader(filePath));
        String line = null;
        String[] strSalesman = null;
        try {
            Class.forName("org.sqlite.JDBC");
            Connection connection =  DBConnection.getConnection();
            PreparedStatement ps = null;

            while ((line=br.readLine()) != null){
                strSalesman = line.split(",");
                salesmanList.add(new Salesman(Integer.parseInt(strSalesman[0]), strSalesman[1]));

                String insertSalesmanQuery = "INSERT INTO salesman VALUES(?, ?);";
                ps = connection.prepareStatement(insertSalesmanQuery);

                for(int i = 0; i<salesmanList.size(); i++){
                    ps.setInt(1, salesmanList.get(i).getCode());
                    ps.setString(2, salesmanList.get(i).getName());
                    ps.executeUpdate();
                }
                status = "Successfully uploaded";
            }
            ps.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
           ex.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
        status = "Error"; //- Please review file selected. Make sure that format is followed.";
        System.out.println(status);
    }
    return status;

Here are sample Salesman details from .csv file:
5099    JONATHAN REYES
5010    EDWIN DAVID

These two values return the error stated above in the Output  log in NetBeans.


text:
Q: Linux vs. Windows copy performance I am attempting to copy files from an old NAS to a new one (I say "new", but the new one is about 8 years old, and the old one is about 12 years old). Since both have RAIDed disks, physically removing them isn't an option. The old NAS is running some sort of embedded Busybox Linux supplied by EMC. The newer one has just been rebuilt, and is running a recent version of Debian. Total amount to be copied is around 8TB. In addition, the only external connections on the old NAS other than network are USB 2.0 connectors, and I'm not even sure they are supported by the operating system, so copying to an external disk and then moving to the new NAS likewise isn't an option.
At any rate, using rsync or rcp gets me a copy speed of about 20MB/sec. With scp I get under 10MB/sec. I also tried piping the output of tar from one host to another using ssh, and performance was abysmal. However, when I mount both shares on a Windows box and copy the files from one share to another, I am able to achieve around 60MB/sec. All speeds are being determined using iotop and/or iostat; I'm not basing this on Windows speed.
Why is the Linux to Linux copy so slow, and is there anything I can do to increase the speed to what I get with Windows?
ETA: here is the output from ip a (interface 3 is disconnected):
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: enp3s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 10:6f:3f:17:0f:cb brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.227/24 brd 192.168.1.255 scope global dynamic enp3s0
       valid_lft 57093sec preferred_lft 57093sec
3: enp4s0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN group default qlen 1000
    link/ether 10:6f:3f:17:0f:ca brd ff:ff:ff:ff:ff:ff

ETA2: Output from ethtool looks fine to me:
# ethtool enp3s0
Settings for enp3s0:
        Supported ports: [ TP ]
        Supported link modes:   10baseT/Half 10baseT/Full
                                100baseT/Half 100baseT/Full
                                1000baseT/Full
        Supported pause frame use: No
        Supports auto-negotiation: Yes
        Supported FEC modes: Not reported
        Advertised link modes:  10baseT/Half 10baseT/Full
                                100baseT/Half 100baseT/Full
                                1000baseT/Full
        Advertised pause frame use: No
        Advertised auto-negotiation: Yes
        Advertised FEC modes: Not reported
        Speed: 1000Mb/s
        Duplex: Full
        Port: Twisted Pair
        PHYAD: 1
        Transceiver: internal
        Auto-negotiation: on
        MDI-X: off (auto)
        Supports Wake-on: pumbg
        Wake-on: g
        Current message level: 0x00000007 (7)
                               drv probe link
        Link detected: yes

A: Instead of scp, have you tried mounting the SMB share of the new NAS onto the old one, then rsync copy the data to the mount point?

A: on a 1gbps wired network, theoretical max speed is = 1000 mbps / 8 bits per byte = 125 MB/sec.  Real world the the largest copy speed I've ever had is ~112 MB/sec per the windows popup and this is copying from a linux server (running samba-server) to a windows 7/10 pc.
You have 8 TB => 8,000,000 MB / 112 MB/s = 71,428 seconds = greater than 19 hours for a sustained transfer with zero problems.
When i do scp I generally see 80-90 MB/sec versus 112, thanks to the overhead of SSH.

Why is the Linux to Linux copy so slow, and is there anything I can do to increase the speed to what I get with Windows?

My reported 112 MB/sec copy speed is downloading from linux to windows (reading) and also uploading from windows to linux (writing).  My linux servers (at work) have 512GB of RAM, and with disk caching that will mostly prevent waiting for disk to provide the data especially when writing to a system the data is delivered over the network and stored in RAM before being written to disk.  Typical real read speeds from hard disk are generally 80 MB/sec or greater so they usually don't have much impact especially if it's multiple in a RAID but if it's a single hard disk then that could be your bottleneck simply reading the data off it.

I am attempting to copy files from an old NAS to another  one

I have experience with synology nas, on the same network and location where I see 112 MB/sec copies as explained; sometimes my NAS's will do near 100 MB/sec, may times they are doing only 50 MB/sec over a couple minutes moving a single ~10GB file.  NAS's can have various settings within them reducing network transfer speed to maintain bandwidth expecting multiple user connections to be reading/writing from it.
Your copy between 2 NAS's for 8TB of data is not a single file, so there will be some incurred overhead dealing with those millions of separate files there's no way around that unless you locally tar up chunks of data into 100+gb tar files and transfer those then do the work untarring them on the destination nas.

Why is the Linux to Linux copy

your really not doing linux to linux, you are doing nas to nas and it is whatever linux operating system is on each nas and how it's configured to do networking as well as performance it can read/write to the types of storage (disks) that are in it.
Per my description of my 112 MB/sec on a 1gbps wired network, I can see that same transfer speed between linux to linux servers (not NAS); if doing scp then that SSH overhead is what causes the reduction to ~80MB/sec.  When you start copying thousands of small (less than 10MB) files then you can incur a lot of overhead and speed loss resulting from the operating system reading that data from its file system on whatever storage, and then again on the other system writing it all to it's storage.  A good NAS with enough RAM can buffer the data in RAM coming over the network at which point it will be the sustained write speed it can do to it's disks, which i think those advertised numbers are often exaggerated and almost always dependent on having the max number of disks installed into the NAS, as RAID-0, so they can advertise the highest possible read/write numbers.
as a sanity check transfer a single ~2GB file, and also a single ~30gb file, and see what those max transfer speeds are, and if they are sustained on your network.

A: Both rsync and scp encrypt the data that is sent across the wire.  On old hardware, I have found that this can limit the speed to about 20MB/s as you observe.
Try using an unencrypted copy, such as:

*

*running an rsync server on one end and using the rsync:// protocol

*using netcat (or nc) on both sides something like (untested, likely wrong syntax):

*

*source: tar cf - ... | nc host port

*destination: nc -l port | tar xf -


text:
Q: text processing rows to columns for a block I have a file containing lists on Solaris:
List A
hi
hello
hw r u

List B
Hi
Yes

List C
Hello

I need to transpose the lists as shown below:
List A    List B    List C
hi        Hi        Hello
hello     Yes
hw r u

How can I do this on Solaris?

A: You could use awk to split each block into separate files, then paste them together (below is assuming always there is empty lines between each lists).
awk '/^$/ {N++;next}{print >"file"N}' infile.txt
paste file*

Also you can move the paste command into awk.
awk '/^$/ {N++;next}{print >"file"N} END{system("paste file*")}' inile.txt

The output is:
List A    List B    List C
hi        Hi        Hello
hello     Yes
hw r u

to having beauty indentation in result when varying lines length like below:
Input file:
list A
hi
hello
hw r u

List B
Hi this is list B
Yes

List C
Hello, this is list C

you can do paste file* |column -s $'\t' -tn and will have result:
list A  List B             List C
hi      Hi this is list B  Hello, this is list C
hello   Yes
hw r u

A: Besides of my previous answer, there is also csplit command to split the file in that same way and then use paste command to get desired output.
csplit -zs -f outputfile inputfile '/^List/' '{*}'
paste outfile*

*

*'/^List/' is a pattern to match and break the file there into the next new file

*'{*}' repeat the pattern as many times as possible

*-z is used to remove empty output files; and -s is used to do not print counts of output file sizes

*-f is used to define custom prefix outputfile## where ## is by default 2 digits, you can define it with -n N (N is number of digits in suffix after defined prefix)

A: GNU awk approach:
awk 'BEGIN{ max=0 }
     /^List/{ if(k && k>max) { max=k; idx=c } ++c; k=0 }
     NF{ a[c][++k]=$0 }
     END{
         for(i=1;i<=max;i++)
             for(j=1;j<=c;j++) printf "%s%s",a[j][i],(j==c)?ORS:"\t"
     }' file | column -ts$'\t'

The output:
List A  List B  List C
hi      Hi      Hello
hello   Yes
hw r u

A: Command
for i in "List A" "List B" "List C"; do sed -n "/$i/,/^$/p" h.txt >"$i.txt"; done

paste List\ *

output
List A  List B  List C
hi  Hi  Hello
hello   Yes
hw r u


text:
Q: Can you use #defined values in if statements (In C programs)? I am new at C programming. I thought when you type something like #define Const 5000 that the compiler just replaces every instance of Const with 5000 at compile time. Is that wrong?
I try doing this in my code and I get a syntax error. Why can't i do this?
#define STEPS_PER_REV 12345

... in some function
if(CurrentPosition >= STEPS_PER_REV)
{
    // do some stuff here
}

The compiler complains about the if statement with a syntax error that gives me no details.

A: Your code fragment is correct. #define is literally a string subsitution (with a bit more intelligence).
You can check what the preprocessor is doing in gcc by using the -E option, which will output the code after the pre-processor has run.

A: the people in the comments are right. You almost definitely have a semicolon at the end of your #define. This means that your assignment becomes:
CURRENT_POSITION = 12345;;

(assuming that you HAD a semicolon at the end of the line...)
but your if becomes:
if(CurrentPosition >= 12345;)

which is of course invalid.
remember, #defines are NOT C code. They don't need semicolons.

A: You are correct in that the C preprocessor will just replace STEPS_PER_REV with 12345. So your if statement looks fine, based on the code you provided.
To get to the bottom of this, could you please post your code and the actual contents of the error message.

A: You are right when you say that the compiler replaces every instance with the content of the macro. Check the type of CurrentPosition, probably the error is there.

A: Yes, but that should be a const, not a macro. You probably getting the wrong type in your comparison.

A: #define in c are macros, they are used by c preprocessor to replace them when they're found. For example in your source code the
 **#define MAX_VALUE 500**

*if( reservations < **MAX_VALUE** )*
{
    ......
}

will be become into

*if( reservations < **500**)*
{
        ......
}

after preprocessing step. So that they could be used in boolean statetments in if sentences.


text:
Q: Gulp-Uglify - Unable to minify Javascript Angular 1.6.8 Hi I am trying to minify my app.js file using gulp uglify, I used pump to get error details and it gives me an error on Line 2
GulpUglifyError: unable to minify JavaScript
Caused by: SyntaxError: Unexpected token: name (app)
File: /Users/Alexander/OneDrive/Alexander/scripts/app.js
Line: 2

Where as Line 2 in my app.js is let app = angular.module("app", ["ngRoute"]);
here is my complete app.js file
let app = angular.module("app", ["ngRoute"]);

app.config(function ($routeProvider) {
   $routeProvider

       .when("/",{
           templateUrl : "templates/home.html"
       })

       .when("/resume",{
           templateUrl: "templates/resume.html"
       })

       .when("/contact",{
           templateUrl: "templates/contact.html"
       });

});

app.controller("MainController",["$scope", function ($scope) {

    $scope.name = "Alexander Personal Website";

}]);

here is my gulpfile.js
var gulp = require('gulp');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var pump = require('pump');
gulp.task('compress', function (cb) {
    pump([
            gulp.src('scripts/*.js'),
            uglify(),
            gulp.dest('app')
        ],
        cb
    );
});

I have seen the Question where it says uglify doesn't work with es6 but the line where I am getting the error is also same for es5.
I hope enough detail is there. Thank you for looking into this issue.

A:
What is var and let?

The scope of a variable defined with var is function scope or declared outside any function, global.
The scope of a variable defined with let is block scope.
In ES6, introduce let. Generally all browsers support ES6 syntax, but the plugins which have already built on earlier version, it throws an error. Probably the main reason is behind your error.
Since our code may going to uglify by gulp-uglify module and there is not support of ES6. If our simple code run with let in browser, then it will not throw an error.

So question what should do?

To use ES6 features will have to transpile our ES6 code to ES5 so that it could run seamlessly on our current browsers. There are several tools out there that could do this task, and for this tutorial, we'll be using Babel.
We'll also bundle all of our source javascript files into one single file using a module bundling tool called Webpack. Support for Babel through Webpack is available in the form of plugins, and we'll use them to automate the transpilation task. This means once we configure these plugins, we just have to write ES6 code and Webpack will take care of the rest.


text:
Q: make carousel centered in page?

Space 1

Infinite Boredom

Space 2

Infinite Boredom

Space 3

Infinite Boredom

I have a bootstrap carousel that is working fine. However, when I make my window fullscreen, it does not span the entire width of the page. What styling would I use in order to do this?

A: Make sure you are following the correct nesting conventions. There may be an issue with your ".container" or ".container-fluid".
For more, reference: http://getbootstrap.com/css/#grid