text:
Q: Qt GUI app unexpectedly ending Hi I am working on Linux and I am trying to create a GUI app to go with my executable I have made.
For some reason it unexpectedly ends. There is no error message, it just says in the Qt console window it unexpectedly ended with exit code 0.
Can someone please have a look at it for me. I am working on Linux.
I will also paste the code here.
void MainWindow::on_pushButton_clicked()
{
    QString stringURL = ui->lineEdit->text();

    ui->labelError->clear();
    if(stringURL.isEmpty() || stringURL.isNull()) {
        ui->labelError->setText("You have not entered a URL.");
        stringURL.clear();
        return;
    }

    std::string cppString = stringURL.toStdString();
    const char* cString = cppString.c_str();

    char* output;

    //These arrays will hold the file id of each end of two pipes
    int fidOut[2];
    int fidIn[2];

    //Create two uni-directional pipes
    int p1 = pipe(fidOut);                //populates the array fidOut with read/write fid
    int p2 = pipe(fidIn);                 //populates the array fidIn  with read/write fid
    if ((p1 == -1) || (p2 == -1)) {
        printf("Error\n");
        return;
    }

    //To make this more readable - I'm going to copy each fileid
    //into a semantically more meaningful name
    int parentRead  = fidIn[0];
    int parentWrite = fidOut[1];
    int childRead   = fidOut[0];
    int childWrite  = fidIn[1];

    //////////////////////////
    //Fork into two processes/
    //////////////////////////
    pid_t processId = fork();

    //Which process am I?
    if (processId == 0) {
        /////////////////////////////////////////////////
        //CHILD PROCESS - inherits file id's from parent/
        /////////////////////////////////////////////////
        ::close(parentRead);      //Don't need these
        ::close(parentWrite);     //

        //Map stdin and stdout to pipes
        dup2(childRead,  STDIN_FILENO);
        dup2(childWrite, STDOUT_FILENO);

        //Exec - turn child into sort (and inherit file id's)
        execlp("htmlstrip", "htmlstrip", "-n", NULL);

    } else {
        /////////////////
        //PARENT PROCESS/
        /////////////////
        ::close(childRead);       //Don't need this
        ::close(childWrite);      //

        //Write data to child process
        //char strMessage[] = cString;
        write(parentWrite, cString, strlen(cString));
        ::close(parentWrite);     //this will send an EOF and prompt sort to run

        //Read data back from child
        char charIn;
        while ( read(parentRead, &charIn, 1) > 0 ) {
            output = output + (charIn);
            printf("%s", output);
        }
        ::close(parentRead);      //This will prompt the child process to quit
    }

    return;
}

EDIT:: DEBUGGING RESULTS
I ran the debugger and this is the error I received:
The inferior stopped because it received a signal from the Operating System.

Signal name : SIGSEGV
Signal meaning : Segmentation fault

A: You haven't initialized the "output" variable. On the last lines of your code, you do this:
while ( read(parentRead, &charIn, 1) > 0 ) {
    output = output + (charIn);
    printf("%s", output);
}

Which will do nasty things, since you are adding a byte read from your child process, to the output variable, which is a pointer that contains garbage, and then printing the contents of the "output" variable's address as a string. You probably want "output" to be a std::string, that way your code could make sense:
std::string output;
/* ... */
while ( read(parentRead, &charIn, 1) > 0 ) {
    output += (charIn);
}
std::cout << output;

Once you have read all the data your child process has generated, you can write it to stdout.
EDIT: since you want to set the contents of "output" to a QPlainTextEdit, you can use QPlainTextEdit::setPlainText:
while ( read(parentRead, &charIn, 1) > 0 ) {
    output += (charIn);
}
plainTextEdit.setPlainText(output.c_str());


text:
Q: On Pokemon Let's Go! Can you connect 1 Pokemon Go account to 2 different Let's Go! Games? I want to know if I can connect a single Pokemon Go account to 2 different Let's Go! games so I can only Use one of my emails for Pokemon Go.

A: Yes
But both games should not be close to the phone at the same time as that causes bugs. It's best to always unpair your game once you're finished to avoid device detection/pairing bugs*.
Note: The same applies to if there are multiple Switches/Go Plus/Go!tcha paired to a single phone or if multiple phones are paired to a single Switch/Go Plus/Go!tcha.
*It's likely because of the way Bluetooth works; status-bydesign.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Keras: ValueError: Graph disconnected: cannot obtain value I am getting a graph disconnected error when running the following function:
def create_vgg_model(input_shape):
    network_input = k.layers.Input(shape=input_shape)
    vgg_model = VGG16(weights='imagenet', input_tensor=network_input, include_top=False)

    inp = k.layers.Input(shape=input_shape, name="input_0")
    out = inp
    for i, layer in enumerate(vgg_model.layers[1:]):
        out = layer(out)
        if i == 5:
            out_bkp = out

    out = k.layers.GlobalAveragePooling2D()(out)
    out = k.layers.Dropout(0.1)(out)
    out = k.layers.Dense(64, activation='relu')(out)
    out = k.layers.Dense(1, activation='linear')(out)
    model = k.Model(inputs=inp, outputs=out)
    model.compile(optimizer=Adam(learning_rate=1e-4), loss=k.losses.BinaryCrossentropy(from_logits=True),
                  metrics=["accuracy"])
    model2 = k.Model(inputs=inp, outputs=out_bkp)
    model3 = k.Model(inputs=model.input, outputs=model.layers[6].output)
    model.summary()
    return model

When running the function, model and model2 are created, but model3 returns the error:
ValueError: Graph disconnected: cannot obtain value for tensor KerasTensor(type_spec=TensorSpec(shape=(None, 1444, 1448, 3), dtype=tf.float32, name='input_1'), name='input_1', description="created by layer 'input_1'") at layer "block1_conv1". The following previous layers were accessed without issue: []

In my opinon model2 and model3 should be exactly the same: The parameter are as followed:
inp:
*<KerasTensor: shape=(None, 1444, 1448, 3) dtype=float32 (created by layer 'input_0')>*

out_bkp:
*<KerasTensor: shape=(None, 361, 362, 128) dtype=float32 (created by layer 'block2_pool')>*

model.input:
*<KerasTensor: shape=(None, 1444, 1448, 3) dtype=float32 (created by layer 'input_0')>*

model.layers[6].output
*<KerasTensor: shape=(None, 361, 362, 128) dtype=float32 (created by layer 'block2_pool')>*

However, for some reason the error returns a renamed input layer ('input_1'). Anyone has an idea why?


text:
Q: How to "cast" a two-argument function into a one-argument function? In matlab, one can write:
S = @(x,y) x^2+y^2-1
G = @(x) S(x,1);

If I have a function expecting a one-argument function, I can do the above.  How can I do this in c/c++?
I have a library function (from the CGAL library) that expects as an argument a function that itself has only one argument.  Ideally, I have a class (SphericalHarmonics) and I would like to have a member function which takes the one argument.  So I have:
FT SphericalHarmonics::distFunction(Point_3 p)

(note that FT is a type similar to double) but of course when I try
SphericalHarmonics *sh = new SphericalHarmonics(1);
Surface_3 surface(sh->distFunction, Sphere(ORIGIN,2.));

this is also treated as an argument, my distFunction function is a two-argument function, and an error is thrown.
Note that this can be solved with global variables, i.e.
SphericalHarmonics *sh;
FT dist_function(Point_3 p) {
    return sh->distFunction(p);
}

main() {
    sh = new SphericalHarmonics(1);
    Surface_3 surface(dist_function);
}

However, this is really non-ideal.  I'd like a way to do this without global variables, as it would be far better to be able to have a class function that easily integrates with the CGAL library.
Thanks in advance!
[UPDATED]
@Andy-Prowl: I have tried your std::bind and lambda solutions, but still seem to be running into errors with regards to the number of arguments.
When, in main, I use the code:
SphericalHarmonics *sh = new SphericalHarmonics(cInit, numL, symm);
auto fxn = std::bind(&SphericalHarmonics::distFunction, sh, std::placeholders::_1);
Surface_3 surface(fxn, Sphere_3(ORIGIN,2.));

I get the errors:
~/lib/basisfunctions/SphericalHarmonics2/mesh_an_implicit_function.cpp:62:48:
error: no matching function for call to
'CGAL::Implicit_surface_3<CGAL::Robust_circumcenter_traits_3<CGAL::Epick>,
double (*)
(CGAL::Point_3<CGAL::Epick>)>::Implicit_surface_3(std::_Bind<std::_Mem_fn
<double (SphericalHarmonics::*)(CGAL::Point_3<CGAL::Epick>)>
(SphericalHarmonics*, std::_Placeholder<1>)>&, Sphere_3)'

and
~/CGAL-4.1/include/CGAL/Implicit_surface_3.h:50:5: note:   no known conversion
for argument 1 from 'std::_Bind<std::_Mem_fn<double (SphericalHarmonics::*)
(CGAL::Point_3<CGAL::Epick>)>(SphericalHarmonics*, std::_Placeholder<1>)>' to
'CGAL::Implicit_surface_3<CGAL::Robust_circumcenter_traits_3<CGAL::Epick>,
double (*)(CGAL::Point_3<CGAL::Epick>)>::Function
{aka double (*)(CGAL::Point_3<CGAL::Epick>)}'

and
~/CGAL-4.1/include/CGAL/Implicit_surface_3.h:34:9: note:
candidate expects 1 argument, 2 provided

[UPDATED]
It is now clear to me that I need a function which can be converted to a function pointer (i.e. surface required a function pointer argument).  This rules out the std::bind option.  Moreover, it appears that a lambda cannot be converted to a function pointer if it captures variables (capture-less vs. capturing lambdas).  So I think Andy-Prowl's answer below is in general the correct answer to this question, although I'll need to find a different work-around.

A: Use std::bind or boost::bind :
#include <functional>

SphericalHarmonics *sh = new SphericalHarmonics(1);
surface(std::bind(&SphericalHarmonics::distFunction, sh, _1));

A: OPTION 1:
In case your member function does not to implicitly work on an instance of your class (and therefore does not need to receive a this pointer), you can make it static:
class SphericalHarmonics
{
    ...
    static double distFunction(Point p);
    ...
};

double SphericalHarmonics::distFunction(Point p)
{
    ...
}

Now, your function will effectively have a single argument:
surface(SphericalHarmonics::distFunction);

OPTION 2:
Otherwise, you may use std::bind() to curry the member function distFunction and fix its first, implicit argument (if you are not working with a C++11 compiler, you can use the equivalent boost::bind() from the Boost.Bind library):
#include <functional>

SphericalHarmonics *sh = new SphericalHarmonics(1);
auto fxn = std::bind(&SphericalHarmonics::distFunction, sh, _1);
surface(fxn);

OPTION 3:
Alternatively, in C++11, a lambda could do the job:
SphericalHarmonics *sh = new SphericalHarmonics(1);
auto fxn = [=] (double d) { return sh->distFunction(d); }

A: In the specific case of dealing with CGAL's templated Surface_3 class. You're probably using something like this (from their example) to define Surface_3 type:
typedef CGAL::Surface_mesh_default_triangulation_3 Tr;
// c2t3
typedef CGAL::Complex_2_in_triangulation_3<Tr> C2t3;
typedef Tr::Geom_traits GT;
typedef GT::Sphere_3 Sphere_3;
typedef GT::Point_3 Point_3;
typedef GT::FT FT;
typedef FT (*Function)(Point_3);
typedef CGAL::Implicit_surface_3<GT, Function> Surface_3;

This is misleading because it makes it seem like CGAL's isosurface classes can only deal with function pointers (as opposed to std::function etc.). But the problem is only that we've just defined it that way. Simply define Surface_3 to use std::function<FT (Point_3)> as its template argument and the std::bind and lambdas from Andy Prowl's answer will work just fine:
...
typedef std::function<FT (Point_3)> Function;
typedef CGAL::Implicit_surface_3<GT, Function> Surface_3;


text:
Q: database design for multiple and all pepople Assume I writing an email applicaiton.
Now I want to send some messages to specified person, some messages to multiple person, some messages to specified group and some to all members.
I am wondering in the best practice I have to treat every mail like a one instance mail, I mean I if I am sending mail to all I have to assign one record for every person or I can define a type field and from the code I must handle with codes.

A: Mail Master table

MailID (PK)
Mail content

Emp Master table

EmpID (PK)
EmpName

Mail-Employee Mapping table

Mail-Employee_ID (auto increament id PK)
MailID (FK)
EmployeeID (FK)

Group_Master table

GroupID (auto increament PK)
GroupName

Group_Employee_Mapping table

Group_Employee_ID (auto increament)
GroupID (FK)
EmployeeID (FK)
(GroupID+Employee are unique so Composite PK)

I think tables and their roles are self explanatory.
Some rule for Group Master:-
Group_Employee_Mapping is predefined in system :you have already mapped all employee and its group in this table.One employee can belong to many group .
If Group='All' don't store "All" employee in Group_Employee_Mapping Table.As this is unnecessary
If user select "All" select all employee from Employee Table ,send them mail and store each employee and mailid in "Mail-Employee Mapping" table
If user select any specific group then select those employee from Group_Employee_Mapping table,send them mail and store them in Mail-Employee Mapping


text:
Q: Continuing a Divisor I need some help, to find the strategy for solving the following problem:
Given an analytic surface $S^0$, its compacitfication $S$ and a horizontal Divisor $D^0$ on $S^0$, I have to continue $D^0$ to a Divisor $D$ on $S$.
The problem is, that to continue $D^0$ as a smooth Curve in $S$ by its Limes can only be half of the answer. $D$ should have some vertical components lying over the points of $S\setminus S^0$. But I don't no, how to find them.
Being more precise about the situation:
I have an atlas $(U_\alpha)_{\alpha \in I}$ for $S^0$ and holomorphic functions $g_{\alpha\beta} : S^0 \to \mathbb C\setminus\{ 0\}$, which fulfill the properties:
$g_{\alpha\beta} \cdot g_{\beta\alpha} = 1$ and
$g_{\alpha\beta} \cdot g_{\beta\gamma} \cdot g_{\gamma\alpha} = 1$.
Therefore these functions define a line-bundle on $S^0$, having the $g_{\alpha\beta}$ as transition-functions vor the charts $U_\alpha$ and $U_\beta$.
I also have maps $s_\alpha : U_\alpha \to \mathbb C$, which fulfill: $s_\beta = g_{\alpha\beta} \cdot s_\beta$. Hence I get a Divisor $D^0$ on $S^0$ by taking
$D^0:= \sum_C ord_C ( {s_{\alpha}}_{|U_\alpha\cap C} ) \cdot C $ where $C$ is running over all irreducible Curves in $S^0$.
For continuing $D^0$, I thought about looking at the limites of the functions $s_\alpha$ in the points of $S\setminus S^0$. But my transitionfunctions $g_{\alpha\beta}$ do have poles in this points. Therefore the order of $s_\alpha$ is different to the one of $s_\beta$.
So how do I compute the vertical components then?
Thanks for any help.
Greyfox


text:
Q: Not able to use the attribute facecolor while using matplotlib while using boxplot import numpy as np
import pandas as pd
import os
import sys
import csv
import matplotlib.pyplot as plt

fifa = pd.read_csv(r"H:\matplotlib with pandas\fifa_data.csv")
barcelona = fifa.loc[fifa.Club == 'FC Barcelona']['Overall']
plt.figure(figsize=(5, 8))
madrid = fifa.loc[fifa.Club == 'Real Madrid']['Overall']
revs = fifa.loc[fifa.Club == 'New England Revolution']['Overall']
labels = ['FC Barcelona', 'Real Madrid', 'NE Revolution']
boxes = plt.boxplot([barcelona, madrid, revs], labels=labels)

for box in boxes['boxes']:
    box.set(color='#4243f5', linewidth=2)
    # fill color in boxes.
    box.set(facecolor='#abcdef')

plt.ylabel("FIFA Overall Ratings")
plt.title("Comparison of barcelona and real madrid team stats.")
plt.show()

The attribute of edge color is working but the latter one of facecolor is giving an error:
AttributeError: 'Line2D' object has no property 'facecolor'

Before facecolor output is:

A: You are missing one crucial thing.
When you want to change the color of the box, you must specify:
boxes = ax.boxplot(x, patch_artist=True)

I have checked the following code and it works:
import matplotlib.pyplot as plt
%matplotlib inline

x = [[1, 2, 3], [4, 5, 6]]

fig = plt.figure()
ax = fig.add_subplot(111)
boxes = ax.boxplot(x, patch_artist=True)

for box in boxes["boxes"]:
    box.set(facecolor = "green")


text:
Q: DEM reconditioning? I'm using ArcGIS Desktop 10.5 Arc Hydro Toolbox & encountered a problem while trying to delineate watersheds respectively drainage lines.

The red lines indicate my obtained drainage lines, which does not match my actual drainage (blue). So I wanted to start all over again & tried several times to burn the streams into my DEM (DEM reconditioning), but it does not work, instead I get this error warning:

I'm working locally on C drive, have all my files in a gdb & also project all the files to the same coordinate system.
How do I approach that?
I updated my model, but encountered a new problem:

Basically what I did:
Data basis included DEM, stream shape & sink polygon

*

*Create Drainage Line Structures

*DEM Reconditioning

*Create Sink Structures

*Fill Sinks

*Create Sinks Structures

*Flow Direction with Sinks

*Adjust Flow Direction in Sinks

*Adjust Flow Direction in Streams

*Flow Accumulation

*Stream Definition

*Stream Segmentation

*Combine Stream Link and Sink Link

*Drainage Line Processing

*Catchment Grid Delineation

*Catchment Polygon Processing

*Adjoint Catchment Processing

What does this error code imply, what did I do wrong respectively forget to specify?

A: If I am understanding you correctly, the blue lines on your map (your 'actual' lines) are lines that represent physical, ground-truthed drainage on landscape. The red lines represent drainage lines that ArcHydro has delineated using the output from a flow accumulation raster. Is this the case?
If so, the biggest problem I see initially is that your 'actual' drainage lines that you want to burn in don't touch the edge of the watershed. Notice, in fact, that in the red lines, two separate watersheds have been delineated: one in the north, and one in the south. Since you are working in a relatively flat area, a stream burn is probably going to be necessary, particularly since your drainage lines look anthropogenic and therefore don't follow the land's natural contours (which might have naturally been two watersheds). However, you can't burn in streams unless water can exit the watershed through them. The end of your drainage must intersect the edge of the watershed.
I think the solution to this is to change the watershed boundary. I would read this post in detail and follow all the steps to delineate your watershed and its streams properly. Specific to your case, decide on at least one pour point (step 5 in the post). A pour point is the theoretically lowest point in the watershed, where all surface water will theoretically flow, and exit (not in reality though - remember that this is just a simplification). Your 'actual' lines must lead to this pour point if you want your stream burn to be successful.
If you are using ArcHydro, you can also refer to this documentation which outlines the entire procedure, for both watershed and stream delineation.


text:
Q: C# Animations (Sliders, etc.) I have yet to get into C# Animations and i'm still learning some of the basics in beginners C# and I'd love to learn animations!
So what I need is the move my panel1 from X: -4 ; Y:-50   to X:-4 ; Y:27
I don't want it to go too fast or too slow.
I need examples of ways to plot this animations the drop in and out when selected
(Down button: button1) ; (Up button: button2) So I'll need a setup to fit in those areas!
    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        //this is the panel i need to move from X:-4 Y:27 to X:-4 Y:-50
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //panel1 down
    }

    private void button2_Click(object sender, EventArgs e)
    {
        //panel1 up
    }
}

}


text:
Q: Reading values from binary file stored in char array with reinterpret_cast (C++) I am trying to read in a binary file in a known format. I want to find the most efficient way to extract values from it. My ideas are:
Method 1: Read each value into a new char array then get it into the correct data type. For the first 4 byte positive int, I bitshift the values accordingly and assign to an integer as below.
Method 2: Keep the whole file in a char array, then create pointers to different parts of it. In the code below I am trying to point to these first 4 bytes and use reinterpret_cast to interpret them as an integer when I dereference the variable 'bui'.
But the ouput from this code is:
11000000001100000000110000000011
3224374275
00000011000011000011000011000000
51130560

My questions are

*

*why does the endianness get swapped using my method 2 and how do I point to it correctly?

*which method is more efficient? I need all of the file, and the file contains other data types too so I will need to write different methods to interpret them if using method 1. I was assuming I could just define different type pointers if using method 2 without doing extra work!

Thanks
#include <iostream>
#include <bitset>

int main(void){
    unsigned char b[4];
    //ifs.read((char*)b,sizeof(b));
    //let's pretend the following 4 bytes are read in representing the number 3224374275:
    b[0] = 0b11000000;
    b[1] = 0b00110000;
    b[2] = 0b00001100;
    b[3] = 0b00000011;

    //method 1:
    unsigned int a = 0; //4 byte capacity
    a = b[0] << 24 | b[1] << 16 | b[2] << 8 | b[3];
    std::bitset<32> xm1(a);
    std::cout << xm1 << std::endl;
    std::cout << a << std::endl;

    //method 2;
    unsigned int* bui = reinterpret_cast<unsigned int*>(b);
    std::bitset<32> xm2(*bui);
    std::cout << xm2 << std::endl;
    std::cout << *bui << std::endl;
}


text:
Q: Delphi ClientDataSet Calculated field not updating for specific value Can anyone please help me to figure out why a calculated field in ClientDataset is not updating with 0.1875. In fact it is not accepting 0.25, 0.50, 0.75, 1.0...etc. Field can be updated if value is 0.26, 0.51...0.1876..etc. I am using following code in Delphi XE3:
procedure TForm1.Button1Click(Sender: TObject);
begin
  ClientDataSet1.Close;
  DBEdit1.DataSource:= DataSource1;
  DBEdit1.DataField := 'PieceRate';
  ClientDataSet1.Open;
end;

procedure TForm1.ClientDataSet1CalcFields(DataSet: TDataSet);
begin
  ClientDataSet1.FieldByName('PieceRate').AsFloat :=StrToFloat(Edit1.Text);
end;

procedure TForm1.ClientDataSet1PieceRateGetText(Sender: TField;
 var Text: string; DisplayText: Boolean);
begin
  if Sender.IsNull then
   Text:='Why it is blank?'
  else
   Text:= Sender.Value;
end;

A: As you haven't provided an MCVE, I created my own, and its code and DFM extract
are below.  Its operation should be self-evident - it sets the Value calculated
field to the selected value in the ListBox.  The point of the ListBox's OnClick
handler calling ClientDataSet.First is to cause the dataset to scroll and so
invoke its OnCalcFields event.
The project does NOT exhibit the problem you allege (though it's unclear what
exactly you mean by the value not being "accepted").  Whichever item in the ListBox
is clicked, the corresponding currency value is displayed in the DBEdit preceded
by the system's curency symbol, the only minor exception being that 0.1875
is displayed as "£0.19" because by default the value is rounded to two decimal places.  My program operates identically in D7 and D10 Seattle, btw.
So, whatever is causing your problem is something in your project that you've not
included in your q, which shows if nothing else the value of an MCVE.
In a comment you said:

When I press Calc button, I am just assigning Edit1.text value to calculated field.

Well, that's not what your Button1Click handler does, according to the code in your q.  If you are assigning a value to the calculated field anywhere else than in the OnCalcFields event you should be checking that your dataset is in the appropriate State (TDataSetState) before you do so.  Are you?
Code:
type
  TForm1 = class(TForm)
    ClientDataSet1: TClientDataSet;
    DataSource1: TDataSource;
    DBEdit1: TDBEdit;
    ClientDataSet1ID: TIntegerField;
    ClientDataSet1Value: TCurrencyField;
    ListBox1: TListBox;
    procedure ClientDataSet1CalcFields(DataSet: TDataSet);
    procedure FormCreate(Sender: TObject);
    procedure ListBox1Click(Sender: TObject);
  public
  end;

[...]

procedure TForm1.ClientDataSet1CalcFields(DataSet: TDataSet);
begin
  ClientDataSet1.FieldByName('Value').AsString := ListBox1.Items[ListBox1.ItemIndex];
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ListBox1.ItemIndex := 0;
  ClientDataSet1.CreateDataSet;
  ClientDataSet1.InsertRecord([1]);
end;

procedure TForm1.ListBox1Click(Sender: TObject);
begin
  ClientDataSet1.First;
end;

DFM extract
object DBEdit1: TDBEdit
  DataField = 'Value'
  DataSource = DataSource1
end
object ListBox1: TListBox
  Items.Strings = (
    '0'
    '0.1875'
    '0.25'
    '0.50'
    '0.75'
    '1.0')
  OnClick = ListBox1Click
end
object ClientDataSet1: TClientDataSet
  Aggregates = <>
  Params = <>
  OnCalcFields = ClientDataSet1CalcFields
  object ClientDataSet1ID: TIntegerField
    FieldName = 'ID'
  end
  object ClientDataSet1Value: TCurrencyField
    FieldKind = fkCalculated
    FieldName = 'Value'
    Calculated = True
  end
end
object DataSource1: TDataSource
  DataSet = ClientDataSet1
end


text:
Q: Como faço para fazer subtração e apresentar o resultado na consulta MYSQL Tenho 3 Tabelas
Veiculos
idVeiculo | Placa | Prefixo

oleomotor
idMotor | idVeiculo | datatroca | kmtroca | horimetroca | proximatroca |idMecanico

Tenho ja essa consulta abaixo que mostra o resultado das ultimas trocas de cada veiculo sem repetir o veiculo. como faço para incluir nessa consulta a tabela hodomentro que vai pegar o ultimo horimetro de cada veiculo e subtrair com o proximatroca e dar o resultado de quantas horas falta.
SELECT DISTINCT b.prefixo as idVeiculo, max(datatroca) as datatroca, max(kmtroca) as kmtroca, max(horimetroca) as horimetroca, max(proximatroca) as proximatroca, idMecanico FROM oleomotor a
                  JOIN veiculos b on (a.idVeiculo=b.idVeiculo)
                  GROUP BY a.idVeiculo order by datatroca DESC;

Hodometro
idVeiculo | km | horimetro

A:
Você pode utilizar a Função TIMEDIFF() que tem como finalidade
  retorna a diferença entre dois valores de tempo (expressos como um
  valor de tempo).

Adicione: timediff(proximatroca, max(horimetro)) as Horas Restantes
Ficaria assim:
SELECT DISTINCT b.prefixo as idVeiculo,
                max(datatroca) as datatroca,
                max(kmtroca) as kmtroca,
                max(horimetroca) as horimetroca,
                max(proximatroca) as proximatroca,
                idMecanico,
                timediff(proximatroca, max(horimetro)) as 'Horas Restantes'
FROM oleomotor a
JOIN veiculos b on (a.idVeiculo=b.idVeiculo)
JOIN hodometro h on (a.idVeiculo= h.idVeiculo)
GROUP BY a.idVeiculo
ORDER BY datatroca DESC;


text:
Q: What is the best way to use this in prototype method It is comfortable to create self = this variable. In all methods we always can use self, and don't worry about method context - some times this in method not we expected.
But in prototype method we can't use this hint;
Look at the example (jQuery needed onle to show the question)
var myClass = function () {
    this.propery = 'someData';

    var self = this;

    this.method = function () {
        console.log(self.propery);
    }
}

myClass.prototype.method2 = function () {
    // want to use self here
    console.log(this);
}

var my = new myClass();

var eventBus = $({});
eventBus.bind('onMyEvent', my.method);
eventBus.bind('onMyEvent', my.method2);

eventBus.trigger('onMyEvent');

What is the best way to declare the class with possibility to use self in prototype methods?

A: You don't need self, just need to set the value of this by binding the object to the function:
var MyClass = function () {
  this.property = 'someData';
  this.method = function () {
    console.log(this.property);
  };
};

MyClass.prototype.method2 = function () {
  console.log(this);
};

var my = new MyClass();

var eventBus = $({});
eventBus.bind('onMyEvent', my.method.bind(my)); // bind
eventBus.bind('onMyEvent', my.method2.bind(my)); // bind

eventBus.trigger('onMyEvent');


text:
Q: Finding a needed dll after a JBoss (hot) redeploy? My web application uses a native dll for part of its functionality (the location of which is provided in PATH). Everything works until I make a change to the WAR and JBoss hot deploys this WAR. At this point, the dll is no longer found and I need to manually restart the server.
What is the best way to load the dll back into the app after a hot deploy?

A: It might not be so easy.  Normally a DLL is tied to a specific classloader.  When you redeploy, that means that the original classloader used for your application is destroyed.  Unfortunately the Java Virtual Machine does not allow a second classloader to reload a DLL again.
You must have something static, that will never be unloaded by the Virtual Machine.  Maybe having a second application that loads the DLL would be a solution, as redeploying the first application wouldn't then affect the DLL.  I guess it could also be possible to create a Jar file that loads the DLL and add it to the classpath of JBoss itself, instead of adding it to your application.  Normally such servers have a "shared" directory where such jar files can be added that will be shared by all applications.
The following bug from SUN sheds some light in this issue, which is way more general than just loading servlets:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4225434


text:
Q: Running a command on SLURM that takes command-line arguments I'm completely new to using HPCs and SLURM, so I'd really appreciate some guidance here.
I need to iteratively run a command that looks like this
kallisto quant -i '/home/myName/genomes/hSapien.idx' \
               -o "output-SRR3225412"                 \
                         "SRR3225412_1.fastq.gz"       \
                         "SRR3225412_2.fastq.gz"

where the SRR3225412 part will be different in each interation
The problem is, as I found out, I can't just append this to the end of an sbatch command
sbatch --nodes=1          \
       --ntasks-per-node=1 \
       --cpus-per-task=1    \
         kallisto quant -i '/home/myName/genomes/hSapien.idx' \
                        -o "output-SRR3225412"                 \
                                  "SRR3225412_1.fastq.gz"       \
                                  "SRR3225412_2.fastq.gz"

This command doesn't work. I get the error
sbatch: error: This does not look like a batch script.  The first
sbatch: error: line must start with #! followed by the path to an interpreter.
sbatch: error: For instance: #!/bin/sh

I wanted to ask, how do I run the sbatch command, specifying its run parameters, and also adding the command-line arguments for the kallisto program I'm trying to use? In the end I'd like to have something like
#!/bin/bash

for sample in ...
do
    sbatch --nodes=1          \
           --ntasks-per-node=1 \
           --cpus-per-task=1    \
             kallistoCommandOnSample --arg1 a1 \
                                     --arg2 a2 arg3 a3
done

A: The error sbatch: error: This does not look like a batch script. is because sbatch expect a submission script. It is a batch script, typically a Bash script, in which comments starting with #SBATCH are interpreted by Slurm as options.
So the typical way of submitting a job is to create a file, let's name it submit.sh:
#! /bin/bash
#SBATCH --nodes=1
#SBATCH --ntasks-per-node=1
#SBATCH --cpus-per-task=1

kallisto quant -i '/home/myName/genomes/hSapien.idx' \
               -o "output-SRR3225412"                 \
                         "SRR3225412_1.fastq.gz"       \
                         "SRR3225412_2.fastq.gz"

and then submit it with
sbatch submit.sh

If you have multiple similar jobs to submit, it is beneficial for several reasons to use a job array. The loop you want to create can be replaced with a single submission script looking like
#! /bin/bash
#SBATCH --nodes=1
#SBATCH --ntasks-per-node=1
#SBATCH --cpus-per-task=1
#SBATCH --array=1-10 # Replace here with the number of iterations in the loop

SAMPLES=(...) # here put what you would loop over
CURRSAMPLE=${SAMPLE[$SLURM_ARRAY_TASK_ID]}
kallisto quant -i '/home/myName/genomes/hSapien.idx' \
               -o "output-${CURRSAMPLE}"              \
                         "${CURRSAMPLE}_1.fastq.gz"    \
                         "${CURRSAMPLE}_2.fastq.gz"

As pointed out by @Carles Fenoy, if you do not want to use a submission script, you can use the --wrap parameter of sbatch:
sbatch --nodes=1          \
       --ntasks-per-node=1 \
       --cpus-per-task=1    \
       --wrap "kallisto quant -i '/home/myName/genomes/hSapien.idx' \
                              -o 'output-SRR3225412'                 \
                                        'SRR3225412_1.fastq.gz'       \
                                        'SRR3225412_2.fastq.gz'"


text:
Q: How to locate a package installed by yum? I use yum list php-imap list the php-imap:
# yum list php-imap
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.zju.edu.cn
 * epel: ftp.cuhk.edu.hk
 * extras: mirrors.zju.edu.cn
 * updates: mirrors.zju.edu.cn
 * webtatic: sp.repo.webtatic.com
Installed Packages
php-imap.x86_64                        5.4.16-7.el7                        @epel

But how can I find the location of it?
I know I can use find / -name php-imap for searching, but it is every long time, even the command do not have reactivity.

In my CentOS 7, the /var/tmp/ is an empty directory. and list the /var/cache/yum/x86_64/7/ are:
base epel extras mysql56-community mysql-connectors-community mysql-tools-community timedhosts timedhosts.txt updates webtatic.

there is no php-imap.

A: If you want to know where the rpm file is, depending on your yum config your system may or may not keep it.  Check /etc/yum.conf (not sure this is the right location on ALL systems but on my Centos box this is the right place) for the line "cachedir=" and this will tell you where the cache of rpms is located.  For example:
grep cachedir /etc/yum.conf

My system says /var/cache/yum/$basearch/$releasevar
In the same file, if keepcache=0 is included, your system will not save the rpms.  Change this to keepcache=1 to keep them around.  Depending on your storage space you might need to clean this up now and then.
If you want to know where the actual software is on your system, do this:
rpm -qa | grep php-imap

Then take the package name from the result (looks like it might be php-imap.x86_64) and do this
rpm -q --filesbypkg <package full name here>

A: Given that your question is about the packages installed using yum, then You have to check the options info and list "sub-flags". According to Yum man:
       info           Display details about a package or group of packages
       list   Is used to list various information about available packages;

        LIST OPTIONS
       The following are the ways which you can invoke yum in list mode.  Note that all list commands include information on the version of the package.

       OUTPUT

              The format of the output of yum list is:

              name.arch [epoch:]version-release  repo or @installed-from-repo

              Note that if the repo cannot be determined, "installed" is printed instead.

       yum list [all | glob_exp1] [glob_exp2] [...]
              List all available and installed packages.

       yum list available [glob_exp1] [...]
              List all packages in the yum repositories available to be installed.

       yum list updates [glob_exp1] [...]
              List all packages with updates available in the yum repositories.

       yum list installed [glob_exp1] [...]
              List the packages specified by args.  If an argument does not match the name of an available package, it is assumed to be a shell-style glob and any matches are printed.

       yum list extras [glob_exp1] [...]
              List the packages installed on the system that are not available in any yum repository listed in the config file.

       yum list distro-extras [glob_exp1] [...]
              List the packages installed on the system that are not available, by name, in any yum repository listed in the config file.

       yum list obsoletes [glob_exp1] [...]
              List the packages installed on the system that are obsoleted by packages in any yum repository listed in the config file.

       yum list recent
              List packages recently added into the repositories. This is often not helpful, but what you may really want to use is "yum list-updateinfo new" from the security yum plugin.

In Addition, the path to the installed packages depends on your system settings:
In Centos7
/var/tmp/yum-root-xxxxx/

or
/var/tmp/yum-username-xxxxx/

or
/var/cache/yum/x86_64/7/program_name/packages/

In RHEL, the files are stored in
/var/cache/yum/x86_64/6Server/rhel-6-server-rpms/packages/


text:
Q: How to use regex to find a string that is combination of numbers and letters in java? Given a string that looks like this "ABC789 Nusc 2888". How do I find strings like "ABC789" which is a combination of capitalized letters followed by a three digit number? Here is what I have tried
"[A-Z]*[0-9]{3}"

This helps me find "ABC789" but it also matches with " 288". What should I do to only match with "ABC789" not " 288"?

A: If you want at least one letter then you can change * to +.
"[A-Z]+[0-9]{3}"

If you want exactly three letters, then you can repeat the {3} syntax.
"[A-Z]{3}[0-9]{3}"

If you have a range, you can use {1,9}.
"[A-Z]{1,9}[0-9]{3}"

A: You can do something like:
When re-using it:
Pattern p = Pattern.compile("[A-Z]{3}\d{3}");
Matcher m = p.matcher("ABC789 Nusc 2888");
if(m.matches()){
   printf("It matches");
}

When using once:
if(Pattern.matches("[A-Z]{3}\d{3}", "Not important XYZ123 2888"))
   printf("It matches");
}

Class Pattern


text:
Q: Why prefer Non-SRGB format for vulkan swapchain? in the Vulkan cube example, the method to pick the surface format is:
vk::SurfaceFormatKHR Demo::pick_surface_format(const std::vector<vk::SurfaceFormatKHR> &surface_formats) {
// Prefer non-SRGB formats...
for (const auto &surface_format : surface_formats) {
    const vk::Format format = surface_format.format;

    if (format == vk::Format::eR8G8B8A8Unorm || format == vk::Format::eB8G8R8A8Unorm ||
        format == vk::Format::eA2B10G10R10UnormPack32 || format == vk::Format::eA2R10G10B10UnormPack32 ||
        format == vk::Format::eR16G16B16A16Sfloat) {
        return surface_format;
    }
}

printf("Can't find our preferred formats... Falling back to first exposed format. Rendering may be incorrect.\n");

assert(surface_formats.size() >= 1);
return surface_formats[0];

}
why would we prefer the non-SRGB formats, isn't most screens expecting the SRGB format?

A: The answer to your question is: You generally do not prefer non-sRGB formats for the swapchain images.
Your doubts are totally justified: The code in question arguably does not show a best practice approach. Consider Figure 1, which shows the fundamental conversion stages involved when capturing images, storing them in a a low dynamic range (LDR) format, and displaying it through a computer monitor.

Figure 1: Clearly, physical radiance is in linear space (leftmost stage).  When we capture an image, we often want to store it in an LDR format to save some space ("LDR image" stage). Whatever radiance is output by a monitor must be again in linear space, otherwise we would have distorted the color values (rightmost stage). Since most (all?) monitors only support LDR framebuffer formats, they apply gamma correction to the framebuffer color values, before they emit the corresponding radiance (monitor stage).
So, yes, the proper approach would be to send an sRGB format to your monitor.
In fact, checking gpuinfo.org and sorting the list by COLOR_ATTACHMENT support, one can observe that sRGB formats are the most commonly supported formats. Here are the top four formats support-wise:

*

*B8G8R8A8_SRGB: 99.88%

*A8B8G8R8_SRGB_PACK32: 99.72%

*R8G8B8A8_SRGB: 99.48%

*B8G8R8A8_UNORM: 99.44%

So, I would say, default to an sRGB format!
P.S.: In case you are wondering why it makes sense to use an LDR image format, have a look at Figure 2 for an explanation!

Figure 2: The top row shows evenly spaced bars w.r.t. physical light intensity. This means, the amount of emitted photons increases by the same amount between each neighboring bar. The bottom row shows evenly spaced bars w.r.t. perceived light intensity---the increase of physical light intensity corresponds to the gamma curve shown in Figure 1. In other words, we only have to add a few photons in darker regions for a big change in perceived light intensity. For brighter regions, we have to add a lot of photons for the same relative difference in perceived light intensity. Therefore, it makes sense to store images so that relatively more bits are allocated for the darker colors, and fewer bits for the brighter colors in order to use the available bits optimally w.r.t. the human visual system.


text:
Q: How to get the AppData folder in C# under Windows 10 I have always gotten the AppData folder using
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

However, on my Windows 10 test machine this returns "C:\Users\User\AppData\Roaming" not "C:\Users\<user>\AppData\Roaming" as on all other versions of Windows.
What do I need to call for Windows 10?


text:
Q: XMPP+iOS Delivered,SENT known SEEN Receipt not known I have gone through the XEP 0184 and have done following implementation.

*

*If XMPP is connected and packet then is send then i set the status for each message as SENT (✔) if I don't get following callback.
-(void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error

*If i get the received status from XEP 0184 implemented in Objective C, I set the status as Delivered (✔✔)

RECV: < message xmlns="jabber:client" from="+122232322@wer.com/2323"
  to="+3343232322@wer.com/2223" lang="" >< received
  xmlns="urn:xmpp:receipts" id="avv-33343"/ >< /message >

*But my question is how to show the SEEN status for each message as readh XMPP 0079 that is Advanced Messaging protocol is doing this. But I could not find in Objective C.

Can anyone please help? If my direction is correct and I am missing something could you let me know?
A code snippet guidance would be much appreciated.
Here is my implementation.
Using the stack documentation help I have added the following lines to get the delivery receipts.
XMPPMessageDeliveryReceipts* xmppMessageDeliveryReceipts = [[XMPPMessageDeliveryReceipts alloc] initWithDispatchQueue:dispatch_get_main_queue()];
xmppMessageDeliveryReceipts.autoSendMessageDeliveryReceipts = YES;
xmppMessageDeliveryReceipts.autoSendMessageDeliveryRequests = YES;
[xmppMessageDeliveryReceipts activate:self.xmppStream];

Now due to this I get the following response for the send and RECV xml.

SEND: 111111111 for avv-33343 Id message.
   RECV: < message xmlns="jabber:client" from="+122232322@wer.com/2323"
  to="+3343232322@wer.com/2223" lang="" >< received
  xmlns="urn:xmpp:receipts" id="avv-33343"/ >< /message >

But this is just giving me info that the message is delivered but how to send the SEEN receipts like above to intimate the sender that the other end user have acknowledged + SEEN the message.
Something like this ... RECV: < seen xmlns="urn:xmpp:receipts" id="222-4444"/ >

A: For seen status use same functionality as send a normal message with same id which message received and you want to mark seen on Sender device,
When on sender device receive a static message @"to@fromSeen" with same message id for sent/delivered message, When receiver get exist msg id already in db  then your purpose resolve .
Code for send seen status
NSString *bodymessageString = [NSString stringWithFormat:@"to@fromSeen"];
        NSString *str_loginUser = [NSString stringWithFormat:@"%@@%@", [[NSUserDefaults standardUserDefaults]valueForKey:@"mobile"],kXMPPServer ];
        NSString *str_OtherUser = [NSString stringWithFormat:@"%@@%@",str_OtherUserRegName,kXMPPServer];

        NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
        [body setStringValue:bodymessageString];

        NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
        [message addAttributeWithName:@"type" stringValue:@"chat"];
        [message addAttributeWithName:@"from" stringValue:str_loginUser];
        //                    [[[delegate xmppStream] myJID] bare]
        [message addAttributeWithName:@"to" stringValue:str_OtherUser];

        //          NSString *messageID= [XMPPStream generateUUID];
        [message addAttributeWithName:@"id" stringValue:str_msgID];

        //            NSXMLElement *request = [NSXMLElement elementWithName:@"request" xmlns:@"urn:xmpp:receipts"];
        //            [message addChild:request];
        [message addChild:body];

        [[delegate xmppStream] sendElement:message];

        [ChatData GetUpdateToDatabase:str_msgID :@"Seen"];

Code for check message status in appdelegate file
if ([message isChatMessageWithBody])
{
if ([msg isEqualToString:@"to@fromSeen"])
{
   BOOL is_Exist;
   is_Exist = [ChatData  GetAllReadyAvailable :message.elementID];
   if (is_Exist == YES)
   {
     NSString *str_status = [ChatData getstatusChatBy:message.elementID];
     if (![str_status isEqualToString:@"Seen"])
     {
        [ChatData GetUpdateToDatabase:message.elementID :@"Seen"];
     }
   }
 }
 else
 {
   BOOL is_Exist;
  is_Exist = [ChatData  GetAllReadyAvailable :message.elementID];
            if (is_Exist == NO)
            {
              // Store message in DB
            }
  }
}
else if ([message hasReceiptResponse])
{
}
else if([message isErrorMessage])
{}


text:
Q: How to set date limit in JTCalender? I want to set date limit in JTCalender. As of now it shows dates more than of past year & more than a year ahead of current year. I want to set limit that it should show only dates of past 6 months & future 6 months. I am using swift language. Please suggest how to resolve this issue ?
EDIT: I am using below code in my app also.
func calendarDidLoadNextPage(_ calendar: JTCalendarManager!) {

    let formatter = DateFormatter()
    formatter.dateFormat = "MMMM yyyy"
    print("load next date \(calendar.date())")
    label_month.text = formatter.string(from: calendar.date()).uppercased()
    filterDate(cal_date: calendar.date())
  }

  func calendarDidLoadPreviousPage(_ calendar: JTCalendarManager!) {
    let formatter = DateFormatter()
    formatter.dateFormat = "MMMM yyyy"
    print("loading previous date is \(self.dateFormatter().string(from: calendar.date()))")
    label_month.text = formatter.string(from: calendar.date()).uppercased()
    filterDate(cal_date: calendar.date())
  }

A: You can create Max and Min Date as per your requirement and use JTCalendar's delegate method to limit the date of calendar.
In your Interface
 NSDate *_todayDate;
 NSDate *_minDate;
 NSDate *_maxDate;
 @property (strong, nonatomic) JTCalendarManager *calendarManager;

In implementation section, you can do below code.
_calendarManager = [JTCalendarManager new];
_calendarManager.delegate = self;

_todayDate = [NSDate date];

_minDate = [_calendarManager.dateHelper addToDate:_todayDate months:-6];

_maxDate = [_calendarManager.dateHelper addToDate:_todayDate months:6];

And A delegate method is there to limit the date for the calendar
// Used to limit the date for the calendar, optional
- (BOOL)calendar:(JTCalendarManager *)calendar canDisplayPageWithDate:(NSDate *)date
{
    return [_calendarManager.dateHelper date:date isEqualOrAfter:_minDate andEqualOrBefore:_maxDate];
}

The problem is your condition in your delegate method.
func calendar(_ calendar: JTCalendarManager!, canDisplayPageWith date: Date!) -> Bool {

    return (calendarManager?.dateHelper.date(minDate, isEqualOrAfter: maxDate))!
  }

You are passing minDate to check isEqualorAfter to your maxDate. which will n ever be true.


text:
Q: Eclipse Regex Search for beginning and end of line not working This is a small question, but it has been nagging me for a while.  When I do a Find or Find/Replace in Eclipse and I use ^ or $ and check the Regular Expressions box, I always get a message:
String Not Found
I don't understand why.  I know about the CTRL+SPACE content assist feature and even when I select ^ from the list, it does not work.
I was looking at this question, Regex to match start of line and end of line for quick find and replace, but it is not working for me.  Other regex searches like ^. or ;$ work fine.
I see that ^ and $ are anchor characters, and do not match a string per se, but these characters seem to work in other editors.
EDIT:
For example, I want to convert a list of data into an SQL in clause.
From:
1
2
3
Hi
I need to quote these!

To:
'1',
'2',
'3',
'Hi',
'I need to quote these!',

A: ^ and $ are zero-width anchors as you said, therefore they will not match anything by themselves.  You need to use something with the anchors in order to match anything in your file.

A: I was able to do it with this regex replace:
Find: ^(\s*)(.*)$
Replace: $1'$2',
So what I do is use:

*

*^ to find the beginning of the line.

*(\s*) to find and capture any white space.

*(.*) to find and capture anything.

*$ to find the end of line.

Then replace with

*

*$1 First capture

*' quote

*$2 Second capture

*', quote comma

I wish ^ and $ worked by themselves, but this is cool b/c I can do it in one operation.


text:
Q: Session not updating until refresh I'm trying to use an AJAX call to update a session variable, then redirect and get that variable on the next page. My problem is that once the page has redirected, the session is not updated until I refresh.
I think this might be to do with the fact that the session is the first thing that gets loaded, but I can't find a way around it. Here is my relevant code:
Input page
$.post('save.php', {data:$input})
    .done(function() {
        window.location.replace('result.php');
    }
);

save.php
session_start();

// make sure previous value has been deleted
unset($_SESSION['word']);

$_SESSION['word'] = $_POST['word'];

result.php
session_start();

$data = $_SESSION['word'];

print_r($data);

Thanks!

A: I think @skywalker has a very good point, but if you want to do it with ajax like now:
In your php file where you save the session change it to
session_start();

// make sure previous value has been deleted // <--- not needed
unset($_SESSION['word']);

$_SESSION['word'] = $_POST['word'];

session_write_close();  //<---------- Add this to close the session so that reading from the session will contain the new value.

To explain: the session is stored in files on the server. When you edit the session, the files are locked for writing but not for reading. When the server did not write all the changes yet to the session files and the next php script tries to read the session, you will get the 'old' values. To force the server to write all changes to the session, close the session for writing before reading with the next script.


text:
Q: Automating taking screenshots of a website I have been given the horrible task of doing this.

*

*Launch the website

*Take a screenshot

*Fill in the form details, click on Next

*Take a screenshot

*...

*...

*...

Rinse. Repeat.
Now, with various combinations, this comes up to 300 screenshots.
And I have to do this for 4 different browsers. Chrome, Firefox, IE 6 and IE 7.
I cannot use tools which will capture the screenshot and store them, such as, SnagIT. I need to take a screenshot, copy it to a Word Document and take the second screenshot and take it to a Word Document.
I thought, I will write a tiny utility which will help me do this. Here is the requirement spec that I put up for it -

*

*An executable which once launched seats itself in the System Tray.

*While it is active, all instances of Key Press (Print Scrn), it should write the contents to a Word Document as defined (either a default path or a user defined one).

*Save the document periodically.

Now, my question is - if I am going to develop this using C# (Winforms application), how do I go about doing this.
I can do a fair bit of C# programming and I am willing to learn. But I am not able to locate the references for how to do a background process so that it runs in the background. And while it runs, it has to capture the Print Scrn command.
Can you folks point me to the right material where I can learn this? Theoretical references should suffice. But if there are practical references, then nothing like it.
Thanks!

A: WatiN has screenshot methods and will work for firefox. Selenium is probably better suited however as it supports more browsers.
However I would recommend that if you can, leverage something like browsershots.org to get the screen shots.

A: As recently answered in this question, you could try AutoIt. It's not browser-based, but there's no reason why it has to be, and all the heavy-lifting has already been done for you.

A: Slightly different from what are you are looking for but worth a shot.
For automation of website testing, have a look at WatiN or Selenium. As for capturing the screenshot, have a look at this - http://www.vikramlakhotia.com/Capturing_the_image_of_the_screen_using_C.aspx . For saving the image to a Word document you can use Office Automation. Now link all this together and you have got your tool. :)
Best of luck. Let me know how it works out.

A: So you can do this with both Cucumber and Capybara, but the Cucumber way is much easier. First, under your project file, create two folders: (1) failed_png and (2) success_png. Then, in your env.rb file, paste the following code:
After do |scenario|
  take_screenshot(@browser, scenario)
end

def take_screenshot(browser, scenario)
  if scenario.failed?
    scenario_name = scenario.name.gsub /[^\w\-]/, ' '
    time = Time.now.strftime("%Y-%m-%d %H%M")
    screenshot_path = './failed_png/' + time + ' - ' + scenario_name + '.png'
  else
    scenario_name = scenario.name.gsub /[^\w\-]/, ' '
    time = Time.now.strftime("%Y-%m-%d %H%M")
    screenshot_path = './success_png/' + time + ' - ' + scenario_name + '.png'
  end
  browser.save_screenshot(screenshot_path)
end

This takes a screen shot after each scenario and places it either in the SUCCESS folder or FAILED folder accordingly with the time stamp on it.
For a complete env.rb file and more documentation, see my blog at whitneytaylorimura.wordpress.com


text:
Q: How to enable code assist for Solr in php using ZendStudio I have just installed the Solr extension for php and I'm trying to set ZendStudio to recognize the lib so I can get code assist for it.
I read here that I should put a stub file for the library in the path, but I couldn't find such a file, and before I code it myself... here I am. Thanks!

A: *

*Download last solr here http://pecl.php.net/package/solr

*Unpack it

*You need file like /solr-x.x.x/docs/documentation.php

*Include this file to your project


text:
Q: Override validation in rails model Hi I have a spree model that has the following validations:
with_options presence: true do
  validates :firstname, :lastname, :address1, :city, :country
  validates :zipcode, if: :require_zipcode?
  validates :phone, if: :require_phone?
end

I would like to remove the city and/or country from presence validation. In my address_decorator i wrote this
Spree::Address.class_eval do

  with_options presence: true do
    validates :firstname, :lastname, :address1
    validates :zipcode, if: :require_zipcode?
    validates :phone, if: :require_phone?
  end
......

But this didnt remove city or country. Both are still demanded in order to create new record.
What am i missing? Please help.

A: When you add "with_options" you are not removing the previous validations, you are just adding more.
So, there is to remove the validations for :city and :country
Not checked myself, but I´ve seen something similar to:
.class_eval do
  _validators.reject{ |key, _| key == :field }

  _validate_callbacks.reject do |callback|
    callback.raw_filter.attributes == [:field]
  end

where :field is :city and :country


text:
Q: jQuery remove appended div element(s) in order I'm creating a registration form where the user may need to enter up to 10 directors details. I want to display only one set of director questions to begin with, and if needs be the user can click '+ director' to add further details.
this appends a div to the .director_wrapper (which works fine). However, I also want to include a remove button in case they append too many director classes to the parent element.
My code so far removes one div when the '-director' button is clicked but I can't figure out why it only removes one, and doesn't continue to remove the others when clicked.

    var director    =  $('.director');
    var dirClone    =  $('.director').html();
    var wrapper     =  $('.director_wrapper');
    var count       =  1;
    var maxField    =  10;
    var removeBtn   =  $('.remove_dir');

    $('.add_dir').on('click', function(e){
        e.preventDefault;
        if(count < maxField){
            $(wrapper).append(dirClone);
            count ++;
            $(removeBtn).removeClass('disabled');
        };

    });

    $(removeBtn).click('click', function(e){
        e.preventDefault;
        $('.director_wrapper div.director:last').remove();
        count--;
        console.log(count);
    });

Director Details

            <button type="button" class="btn add_dir">+ director</button>
            <button type="button" class="btn remove_dir disabled">- director</button>

        Director

            <input type="email" class="form-control custom-address" id="exampleInputEmail3" placeholder="Line 1">

            <input type="email" class="form-control custom-address" id="exampleInputEmail3" placeholder="Line 2">

            <input type="password" class="form-control custom-address" id="exampleInputPassword3" placeholder="Line 3">

            <input type="password" class="form-control custom-address" id="exampleInputPassword3" placeholder="City">

            <input type="password" class="form-control custom-address" id="exampleInputPassword3" placeholder="Country">

            <input type="password" class="form-control custom-address" id="exampleInputPassword3" placeholder="Postcode or equivalent">

            <input type="password" class="form-control custom-address" id="exampleInputPassword3" placeholder="Phone Number">

            <input type="password" class="form-control custom-address" id="exampleInputPassword3" placeholder="Email">

A: The problem is your second line: $('.director').html();.  .html() only gets the inner HTML of the element.  There's a DOM property called outerHTML that you can use instead to get the right HTML

    var director    =  $('.director');
    var dirClone    =  $('.director').prop('outerHTML');
    var wrapper     =  $('.director_wrapper');
    var count       =  1;
    var maxField    =  10;
    var removeBtn   =  $('.remove_dir');

    $('.add_dir').on('click', function(e){
        e.preventDefault;
        if(count < maxField){
            $(wrapper).append(dirClone);
            count ++;
            $(removeBtn).removeClass('disabled');
        };

    });

    $(removeBtn).click('click', function(e){
        e.preventDefault;
        $('.director_wrapper div.director:last').remove();
        count--;
        console.log(count);
    });

Director Details

            <button type="button" class="btn add_dir">+ director</button>
            <button type="button" class="btn remove_dir disabled">- director</button>

        Director

            <input type="email" class="form-control custom-address" id="exampleInputEmail3" placeholder="Line 1">

            <input type="email" class="form-control custom-address" id="exampleInputEmail3" placeholder="Line 2">

            <input type="password" class="form-control custom-address" id="exampleInputPassword3" placeholder="Line 3">

            <input type="password" class="form-control custom-address" id="exampleInputPassword3" placeholder="City">

            <input type="password" class="form-control custom-address" id="exampleInputPassword3" placeholder="Country">

            <input type="password" class="form-control custom-address" id="exampleInputPassword3" placeholder="Postcode or equivalent">

            <input type="password" class="form-control custom-address" id="exampleInputPassword3" placeholder="Phone Number">

            <input type="password" class="form-control custom-address" id="exampleInputPassword3" placeholder="Email">


text:
Q: add elements to top RealmRecyclerViewAdapter I developing news feed like twitter, facebook and etc.
I have a server that gives me portions of articles for 10 pieces.
When I scroll down, new articles are loaded, added to the database and displayed in RealmRecyclerView.
I added SwipeRefreshLayout to update the data (in the case when new quotes came in).
I have a problem with adding new items to the top when i use SwipeRefreshLayout.
My idea was to sort new articles on id. In that case, when I scroll down the items with the smaller ones the id will be at the bottom, and when I use SwipeRefreshLayout new articles with higher id are download and adding in top list.
MyFragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_view_all_quotes, container, false);
    swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
    swipeRefreshLayout.setOnRefreshListener(this);
    Realm.init(getActivity());
    realm = Realm.getDefaultInstance();
    recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);
    adapter = new QuoteAdapter(realm.where(QuoteObject.class).findAllSortedAsync("id", Sort.DESCENDING), getActivity());
    recyclerView.setAdapter(adapter);
    return view;
}

  @Override
public void onRefresh() {
    int position = realm.where(QuoteObject.class).findAll().size();
    DownloadDataFromServer.DownloadQuotes downloadQuotes =
            new DownloadDataFromServer.DownloadQuotes();
    try {
        DownloadDataFromServer.DownloadQuotes.FlagQuotes = true;
        downloadQuotes.execute(position+1).get();
    }catch (Exception e){
        Log.e(TAG, "Error", e);
    }finally {
        swipeRefreshLayout.setRefreshing(false);
    }
}

RealmRecyclerViewAdapter
class QuoteAdapter extends RealmRecyclerViewAdapter<QuoteObject, QuoteAdapter.AllQuotesViewHolder> {

 QuoteAdapter(OrderedRealmCollection<QuoteObject> quotes, Context context) {
    super(quotes, true);
    this.context = context;
    if (quotes.size() == 0) downloadData(0);
}

.
.
.
 @Override
public void onBindViewHolder(final QuoteAdapter.AllQuotesViewHolder viewHolder, int position) {
    if (position == getData().size() - 1) downloadData(position);
....
}

But it does not work, the new data is loaded but does not add to top
Since I'm doing this for the first time, maybe I did not choose the right approach.
If you did this, tell how to create a news feed correctly.

A: If you don't have a updated field by which you can do
findAllSortedAsync("updated", Sort.DESCENDING)

Then you might want to consider adding a RANK field, and sort based on that.
For example,
// when downloading new items by "SwipeToRefresh" from top
        // inside Realm transaction
                RealmResults<FeedItem> feedItems = dao.findAll(realm);
                for(int i = feedItems.size() - 1; i >= 0; i--) {
                    FeedItem feedItem = feedItems.get(i);
                    feedItem.setRank(feedItem.getRank() + response.size());
                }
                long rank = 1;
                FeedItem defaultInstance = new FeedItem();
                for(FeedItemDTO dto : response) {
                    FeedItem realmObject = mapper.toRealmObject(realm, dto, defaultInstance);
                    realmObject.setRank(rank++);
                    dao.insertOrUpdate(realm, realmObject);
                }

And
// when download new items by scrolling to bottom
        // inside Realm transaction
                long count = dao.count(realm);
                long rank = count + 1;
                FeedItem defaultInstance = new FeedItem();
                for(FeedItemDTO dto : response) {
                    FeedItem realmObject = mapper.toRealmObject(realm, dto, defaultInstance);
                    realmObject.setRank(rank++);
                    dao.insertOrUpdate(realm, realmObject);
                }

public FeedItem toRealmObject(Realm realm, FeedItemDTO dto, FeedItemInterface defaultInstance) {
    if(defaultInstance == null) {
        defaultInstance = new FeedItem();
    }
    defaultInstance.setId(dto.getId());
    RealmList<FeedCategory> categoryIds = new RealmList<FeedCategory>();
    if(dto.getCategoryIds() != null) {
        for(Long categoryId : dto.getCategoryIds()) {
            FeedCategory feedCategory = feedCategoryRepository.findOne(realm, categoryId);
            if(feedCategory != null) {
                categoryIds.add(feedCategory);
            }
        }
    }
    defaultInstance.setCategoryIds(categoryIds);
    defaultInstance.setCreatedTime(new Date(dto.getCreatedTime()));
    defaultInstance.setUpdatedTime(new Date(dto.getUpdatedTime()));
    defaultInstance.setTitle(dto.getTitle());
    defaultInstance.setShortDescription(dto.getShortDescription());
    defaultInstance.setNumberOfLikes(dto.getNumberOfLikes());
    defaultInstance.setIsLiked(dto.getIsLiked());
    defaultInstance.setIsFavorited(dto.getIsFavorited());
    defaultInstance.setIsImportant(dto.getIsImportant());
    defaultInstance.setImageUrl(dto.getImageUrl());
    defaultInstance.setTypeCode(dto.getTypeCode());
    defaultInstance.setResultTypeCode(dto.getResultTypeCode());
    return defaultInstance;
}


text:
Q: DB2 Stored Procedure returning Multiple rows of a Cursor in C Program I want to write a Stored Procedure in DB2 which will have a curosor for a table and then it will send the whole cursor rows to a C program?
Can anyone help me?

A: CREATE PROCEDURE GETNAMESET ( IN CNUM INTEGER )
RESULT SET 1
LANGUAGE SQL
BEGIN
--Take the inputted customer number, CNUM and
--return the record(s) for that customer from the
--customer table via SQL result set(s)
  DECLARE C1 CURSOR FOR
    SELECT * FROM CUSTTABLE WHERE CUSTNUM = CNUM;
  OPEN C1;
  SET RESULT SETS CURSOR C1;
END;


text:
Q: How can I get more info on Facebook login I am trying to do a Facebook login which is working but I would like to get some more info about the user, like first and last name, and could also be the profile picture.
This is what I am doing:
.factory('Auth', function($http, $location, $rootScope, $alert, $window) {

    var token = $window.localStorage.token;
    if (token) {
      var payload = JSON.parse($window.atob(token.split('.')[1]));
      $rootScope.currentUser = payload.user;
    }

    // Asynchronously initialize Facebook SDK
    $window.fbAsyncInit = function() {
      FB.init({
        appId : '1234567890',
        responseType : 'token',
        status : true,
        cookie : true,
        xfbml : true,
        version : 'v2.4'
      });
    };

    // Asynchronously load Facebook SDK
    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {
        return;
      }
      js = d.createElement(s);
      js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    return {
      facebookLogin: function() {
        FB.login(function(response) {
          FB.api('/me', function(profile) {
            var data = {
              signedRequest: response.authResponse.signedRequest,
              profile: profile
            };

            $http.post('/auth/facebook', data).success(function(token) {
              var payload = JSON.parse($window.atob(token.split('.')[1]));
              $window.localStorage.token = token;
              $rootScope.currentUser = payload.user;
              console.log('profile', payload);
              $location.path('/');
            });
          });
        }, { scope: 'email, public_profile' });
      }
    };
});

When I call the function
FB.login(function(response) {...}

what I get is this
{
  "authResponse": {
    "accessToken": "EAAI3lCeCXL",
    "userID": "1062220283817044",
    "expiresIn": 6886,
    "signedRequest": "oVzEDRHPz4e3ammGG"
  },
  "status": "connected"
}

and then when the post call its been performed
        $http.post('/auth/facebook', data).success(function(token) {
          var payload = JSON.parse($window.atob(token.split('.')[1]));
          $window.localStorage.token = token;
          $rootScope.currentUser = payload.user;
          console.log(angular.toJson($rootScope.currentUser, 'pretty'));
          $location.path('/');

        });

I get this
{
  "user": {
    "__v": 0,
    "name": "Marcelo Retana",
    "_id": "574b5b48d6742c401106c3f9",
    "facebook": {
      "id": "1062220283817044"
    }
  },
  "iat": 1464556360470,
  "exp": 1465161160470
}

Here is the Node part just in case:
app.post('/auth/facebook', function(req, res, next) {
  var profile = req.body.profile;
  var signedRequest = req.body.signedRequest;
  var encodedSignature = signedRequest.split('.')[0];
  var payload = signedRequest.split('.')[1];

  var appSecret = '1234567890';

  var expectedSignature = crypto.createHmac('sha256', appSecret).update(payload).digest('base64');
  expectedSignature = expectedSignature.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');

  User.findOne({ facebook: profile.id }, function(err, existingUser) {
    if (existingUser) {
      var token = createJwtToken(existingUser);
      return res.send(token);
    }
    var user = new User({
      name: profile.name,
      facebook: {
        id: profile.id,
        email: profile.email
      }
    });
    user.save(function(err) {
      if (err) return next(err);
      var token = createJwtToken(user);
      res.send(token);
    });
  });
});

So, any suggestions ?

A: You just need to ask for the fields you want to get:
FB.api('/me', {fields: 'name,first_name,last_name,picture,email'}, function(profile) {
    ...
});

It is called "Declarative Fields" and came with Graph API v2.4: https://developers.facebook.com/docs/apps/changelog#v2_4


text:
Q: Java Multi-Thread Pausing
My Goal

I am brand new to multi-threading in java and I am attempting to create pong.  I will only include a bit of code here that is relevant to the question.

Problem

I want to be able to pause the game by pressing the space bar, and then resume it again by pressing the space bar later.  The following code works to pause the game, however it cannot resume.  All future key presses are not recognized.  It seems as if the main thread is being paused.

Code

Main Class
public class MainManager {

    private Ticker ticker;
    private Thread tickerThread;

    private boolean active;

    public MainManager() {
        ticker = new Ticker(this,10);
        tickerThread = new Thread(ticker);

        tickerThread.start();
    }

    public synchronized void tick() {
        // Does necesary things for each game tick
    }

    public void toggleState() {
        if (this.active) {
            ticker.pause();
        } else {
            this.setActive(true);
            notify();
        }
    }

    public void setActive(boolean b) {
        this.active = b;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
                    @Override
                   public void run() {
                        MainManager manager = new MainManager();
                   }
        });
    }
}

Ticker Class
public class Ticker implements Runnable {

    private MainManager manager;
    private int tick;

    public Ticker(MainManager manager,int tick) {
        this.manager = manager;
        this.tick = tick;
    }

    @Override
    public void run() {
        manager.setActive(true);
        while (true) {
            try {
                Thread.sleep(this.tick);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            manager.tick();
        }
    }

    public void setTickSpeed(int speed) {
        this.tick = speed;
    }

    public synchronized void pause() {
        synchronized(manager) {
            try {
                System.out.println("Waiting for Manager");
                manager.setActive(false);
                manager.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

KeyListener Class
NOTE: This class is added to a JFrame that is constructed inside of the MainManager constructor.  If this JFrame class is important for my question I will post the code, just let me know
public class KeyboardListener implements KeyListener {

    private MainManager manager;

    public KeyboardListener(MainManager manager) {
        this.manager = manager;
    }

    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println("KeyPressed);
        //This line only prints on the first spacebar.
        //After the game is paused, it never prints again.  Despite me spamming spacebar
        if (e.getKeyCode() == KeyEvent.VK_SPACE) {
            manager.toggleState();
        }
    }
}

How do I get the tickerThread to pause and resume with the press of a key?  Any other criticisms are welcome.

A: You never left the Swing Event Dispatch Thread.
Your ticker is merrily ticking away in the other thread, which is working fine. However, if we follow the path of your toggle call, it never reaches the other thread.
Your space key is pressed->Swing EDT witchcraft->keyPressed->manager.toggleState()->ticker.pause() Now we synchronize with Manager, which isn't hard. We're still on the main thread! Then we wait.
Your space key is pressed->Swing EDT is paused. The only part of your ticker that's running in another thread is the run method.
You want to run everything relating to your game logic off the EDT. Run both the MainManager and the Ticker in a different thread from your JFrame and event handlers and synchronize or use a locked boolean value to send data from the IO thread to the logic thread.


text:
Q: Finite ratios between pairs of infinities I know that there are infinities of different magnitudes for countable things (e.g. via Cantor's diagonal argument), and that the ratios of the sizes of two such infinities may itself be infinite. However, how do ratios of infinities work for uncountable things? And can the ratio of two infinities of uncountable things be finite?
Consider an infinitely large two-dimensional plane, consisting of a point $p$ and two unit vectors $v_1$ and $v_2$ rooted at $p$. Divide the infinite plane into two regions: $A$, the region of space spanned by the "wedge" centered at $p$, the "short way around" between $v_1$ and $v_2$, and $B$, the remainder of the plane (the "long way around"). The areas $|A|$ and $|B|$ are infinite, however it would seem that $|A| \over |B|$ is finite, since if a circle of any nonzero radius centered at $p$ is intersected with $A$ and $B$, the ratio of the areas of the two intersected regions would always be be the constant value $\theta \over {2\pi - \theta}$, where $\theta = cos^{-1}{{|v_1 . v_2|} \over {|v_1||v_2|}}$.
(Actually maybe I am mistaken, and points on a plane are countable, by extension of Cantor's argument to two dimensions...)


text:
Q: Can I Toggle content of Element based on pixel height of element? Using Bootstrap 2.3.2 I've previously used a toggle button to show and hide text using the Collapse plugin but from what I see it only allows me to reveal and hide the entire contents of an element.
What I need is to already have 170px of the element's content visible and then when the button is clicked, it reveals the rest of the text in the element - but I need to do this without adding any additional elements, it needs to be based on height.
Is this possible with Bootstrap? Or if not, jQuery?

A: This can be done using CSS for the element styling and then applying classes via Javascript:
The HTML:
<div class="toggle">
your huge text here...
</div>

CSS:
.toggle{
    height:170px;
}
.open{
    height:auto;
}

and JS (using jQuery):
$('.toggle').on('click', function () {
    $(this).toggleClass('open');
});

What the script basically does is detect when you click on the .toggle and, if it is clicked, then it toggles the class .open which sets the propertie height to auto, leading the element with the text to be as huge as it can grow.
Here is a working example: http://jsfiddle.net/8SXNZ/1/


text:
Q: Which is better to swap numbers? Using temporary variable or without it? Does it even matter? I have been asked a question to swap two numbers without using temporary variable. It was a easy to answer the question with the following answer.
swapping  with temp variable
int a =10;
int b =20;
int temp = a;
a = b;
b = temp;

swapping without temp variable
int a =10;
int b =20;
a = a+b;
b = a-b;
a = a-b;

It works, But which is better in terms of performance? When it is only one time operation performance doesn't matter i think. But if i need to reverse a huge array of numbers using this swapping method or during a selection sort where swapping needed etc..,  creating local variable is better or doing it with arithmetic operation?

A: I will say definitely with a temp variable i.e. your first option. If you refer to your second example you have done total three operation. For each operation your java virtual machine generate equivalent assembly operation. But in your first option with a temp variable you are just swapping the values. Hence very minimal assembly operation only to read from address and write into address.

A: Quite apart from the fact that the second one can overflow*, there are three possible answers for this:

*

*You can measure it.

*Only think about this level of optimisation if you've measured it and this is really proven to be a problem. (In this instance it is highly unlikely that you'll be able to measure any appreciable difference.)

*When in doubt, it's usually a good idea to choose the simpler / more canonical solution. A lot of optimisations are based on the premise that you write "normal" code, and will look for patterns developers usually employ. Naive optimisation efforts can sometimes result in inferior performance with Java Hotspot.

So unless you want to dive into the wonderful and tricky (but fun) world of microbenchmarking, just go with the temp variable.
*Though because of the way Java handles overflows, you'll still get the correct result. But as an aside, if you use xor instead of arithmetic operations, there is no danger of overflow.
P.s.: If you are reversing a huge array, the running time will be overwhelmingly dominated by memory access to the array.


text:
Q: How to allow routing into Kubernetes IP addresses only accessable via iptables rules? I have set up a working Kubernetes cluster using Rancher which defines two networks:

*

*10.42.0.0/16 for pod ip addresses

*10.43.0.0./16 for service endpoints

I want to use my existing Caddy reverse proxy to access those service endpoints, so I defined a route (10.10.10.172 is one of my kubernetes nodes):
sudo route add -net 10.43.0.0 netmask 255.255.0.0 gw 10.10.10.172

My routing table on the Caddy web server:
arturh@web:~$ sudo route
[sudo] password for arturh:
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         DD-WRT.local    0.0.0.0         UG    0      0        0 eth0
10.10.10.0      0.0.0.0         255.255.255.0   U     0      0        0 eth0
10.43.0.0       rancherkube1.lo 255.255.0.0     UG    0      0        0 eth0
172.17.0.0      0.0.0.0         255.255.0.0     U     0      0        0 docker0

Using this setup I can access and use 10.43.0.1:443 without any issues (it is the main kubernetes api endpoint):
arturh@web:~$ nmap 10.43.0.1 -p 443 | grep 443
443/tcp open  https
arturh@web:~$ curl -k https://10.43.0.1
Unauthorized

But accessing any other IP address in the 10.43.0.0/16 network fails and I cannot figure out why:
arturh@web:~$ kubectl get svc | grep prometheus-server
prometheus-prometheus-server               10.43.115.122   <none>         80/TCP              1d
arturh@web:~$ curl 10.43.115.122
curl: (7) Failed to connect to 10.43.115.122 port 80: No route to host
arturh@web:~$ traceroute 10.43.115.122
traceroute to 10.43.115.122 (10.43.115.122), 30 hops max, 60 byte packets
 1  rancherkube1.local (10.10.10.172)  0.348 ms  0.341 ms  0.332 ms
 2  rancherkube1.local (10.10.10.172)  3060.710 ms !H  3060.722 ms !H  3060.716 ms !H

I can access everything from the kubernetes node itself:
[rancher@rancherkube1 ~]$ wget -qO- 10.43.115.122
<!DOCTYPE html>
<html lang="en">...

which works because of iptable NAT rules:
[rancher@rancherkube1 ~]$ sudo iptables -t nat -L -n  | grep 10.43
KUBE-SVC-NGLRF5PTGH2R7LSO  tcp  --  0.0.0.0/0            10.43.115.122        /* default/prometheus-prometheus-server:http cluster IP */ tcp dpt:80
KUBE-SVC-NPX46M4PTMTKRN6Y  tcp  --  0.0.0.0/0            10.43.0.1            /* default/kubernetes:https cluster IP */ tcp dpt:443

I'm confused because the entries for 10.43.0.1 which works looks identical the the others which do not... I figure I need to add an iptables rule to allow access to the 10.43.0.0/16 subnet, but I'm not familiar with iptables.
I'm quite new to the whole kubernetes business, is this the correct way to go about accessing your service endpoints? If so can someone please help me with the correct iptables command?

A: you can access things from a host that's running a kubernetes workload because it has the iptables rules and possible route table rules to route traffic.
If you want to access the kubernetes services from outside your cluster then you want to use a ingress controller with a ingress service.
https://kubernetes.io/docs/concepts/services-networking/ingress/

A: I am looking for an easier way to make K8S accessible to external hosts without using loadBalance and NodePort.
I also deployed K8S using Rancher, one of the nodes is 192.168.1.4 . By default, only k8S nodes can access the virtual IP 10.42.0.0/16 and 10.43.0.0/16 .
Thanks @arturh for the example, I added a route rule on a non-K8S host and it worked:
[root@CentOS ~]# curl 10.43.1.15:27017

^C
[root@CentOS ~]# ip route add 10.43.0.0/16 via 192.168.1.4
[root@CentOS ~]# curl 10.43.1.15:27017
It looks like you are trying to access MongoDB over HTTP on the native driver port.

Possible mistakes:

*

*sysctl net.ipv4.ip_forward of the host is disabled.

*Non-k8s hosts and K8S nodes are on different subnets, so they cannot communicate with each other directly.


text:
Q: How to obtain the derived class type from base when calling a method Ive searched the internet and didnt immediately see a solution, should be simple but I just cant figure it out.
I need to obtain the derived class Type within a method that only passes in the base class:
class Base
{
}

class Derived1 : Base
{
}

class Derived2 : Base
{
}

void SomeMethod(Base obj)
{
    Type baseType = obj.GetType();
    Type derivedType = obj.????
}

void Main()
{
    Base d1 = new Derived1();
    Base d2 = new Derived2();

    SomeMethod(d1);
    SomeMethod(d2);
}

A: .GetType() returns actual type of current object. It doesn't return base type. So if you do SomeMethod(new Derived1()), obj.GetType() will return Derived1 (seems like that is what you want).

A: Probably, you want something like this:
 using System.Reflection;
 ...

 void SomeMethod(Base obj) {
   // Declared type, "Base" - since "Base obj" is declared in the method
   Type baseType = MethodInfo.GetCurrentMethod().GetParameters()[0].ParameterType;
   // Actual type, "Derived1", "Derived2" - actually passed as parameter
   Type derivedType = obj.GetType();
   ...
 }


text:
Q: video file downloads with no file type? javascript Is there any way to force it to download as what it is, an MP4?
Clearly the file type is not set on the server but I am wondering if there is a clean way to tell JavaScript it is an MP4. So far I have tried just about everything under the sun. Any way of doing it no matter how difficult would be great.
                var link = document.createElement('a');
                link.href =url;
                link.type='video/mp4';
                link.download = 'videodfdf.mp4';
                link.dispatchEvent(new MouseEvent('click'));

The thing is, I am creating a YouTube Downloader. So far everything is working but I am trying to avoid having to stream every YouTube video from my server directly. This is the difference between me paying £5 a month to host my site and something like £30


text:
Q: Scoverage: Ambiguous measurement from branch coverage I have noticed that all the tests with no control-flow (such as if, else, switch, etc) shows 100% branch coverage due to no branch present in the code block. For example
def foo = {
println("Hello World!")
}

Shows 100% branch coverage and 0 % statement coverage. This is due to 0/0 branch covered. From my eyes, I see one branch in above test case, so shouldn't there be one branch even if there is no control flow?

A: I guess its semantics. The code can only follow one path - so it can never "branch". Or do you consider the whole thing to be one branch.
If you have a train track which is a straight line, how many branches does it have ?
Does this have 2 branches, or 3 ?
def foo = {
  if (b)
   println("1")
  else
   println("2)
}

At the very least I think we could update scoverage so that your example is 100% branch coverage, but should it say 0 branches or 1...


text:
Q: Android app closing on start. giving error 'Cause: execute-only (no-read) memory access error; likely due to data in .text' MY app closing in startup and throwing error.
Cause: execute-only (no-read) memory access error; likely due to data in .text.

This is described in Android 10 behaviour changes
https://developer.android.com/about/versions/10/behavior-changes-all#xom-binaries
But i'm not able proceed with this solution. how can use mProtect() method.
my project is not ndk. my libraries, that are using native code
the bellow link also seen but i'm not able to do how can i solve
After migrating from SDK 28 to SDK 29 in Android my app crashed and facing : signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), error in Android studio 3.4.1
https://source.android.com/devices/tech/debug/execute-only-memory
this issue came when i'm used my android sdk is 30. but when i use sdk to 28 issue not coming


text:
Q: Respring application for jailbroken iPod Touch So I have a third generation iPod Touch, with ios 4.2.1 and it's jailbroken. I'm using SSH to transfer files between it and my computer, but my problem is that when ever I add a file to it, and I want to take a look at it, I need to restart or respring my iPod before I can see it. So I've thought of a very tiny app placed at the homescreen, that resprings the iPod. My problems is that I don't know anything about coding for apple. Is there a 'one line solution' for this?

A: If you want an app that just kills springboard, then in
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

just add this:
system("killall SpringBoard");

A: I don't know exactly what you mean by transferring files.  Are you referring to transferring apps?
If so, you can make newly installed (via SSH copy) apps appear on the home screen by SSHing in to your phone and doing this
>ssh mobile@ipod
>uicache

or
>ssh root@ipod
>su mobile -c uicache

depending on whether you have your iPod setup to allow logins as root or mobile.  Obviously, in my above example, you must have the IP address of your iPod mapped to the hostname "iPod", or else use IP addresses.
Another option that you may or may not be aware of is the SBSettings app itself.  If you install that from Cydia, it has a really nice toggle to simply respring.  That's not much more work than having a "tiny app" to respring (one extra touch, I guess).
If you are writing an Objective-C iOS app, and you want to do this programmatically (which wasn't 100% clear in the question), then check out this answer.  And see here for information on using notify_post


text:
Q: Android Get Screen Size not Working? I am Drawing a Rectangle on a Canvas by Doing the Following:
canvas.drawRect(0, 0, Screen.getCenterX(), Screen.getCenterY(), paint);

Screen is Set Up the following way:
public static int width;
public static int height;

public static void setupScale(Context context) {
    WindowManager wm = (WindowManager) context
            .getSystemService(Context.WINDOW_SERVICE);
    DisplayMetrics displaymetrics = new DisplayMetrics();
    wm.getDefaultDisplay().getMetrics(displaymetrics);
    height = displaymetrics.heightPixels;
    width = displaymetrics.widthPixels;
    Log.e("TEST", "TEST");
}

public static int getCenterX() {
    return width / 2;
}

public static int getCenterY() {
    return height / 2;
}

It also seems that the Log: "TEST" does not get called sometimes.
The Screen.setup() function is called in my MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.game_layout);

    // SETUP ONCE:
    context = this;
    Screen.setupScale(context);

The Screen should display a rectangle that fills a quarter of the Screen. However, this is the Result:

As you can see, the Rectangle appears in the top left corner. The worst part s that sometimes the Rectangle shows the way it should so it feels random. When I log Screen.width, it returns 16 for Some reason.
Here is my Relevant Manifest Info:
minSdkVersion 13
targetSdkVersion 21

What could be the issue here? Please Help. It seems that sometime that Log is showing and the Resolution is set. But other times it does not work. What is the issue here. It feels very random.
Thank you very much.

A: Working from the answer here, why don't you try to call the getWindowManager() inside the setupScale() function instead of passing it along as a parameter.
public static void setupScale() {
    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    height = displaymetrics.heightPixels;
    width = displaymetrics.widthPixels;
    Log.e("TEST", "TEST");
}