text:
Q: Erro NullReferenceException em join Criei um join em LINQ pra criar uma List:
(from p in listaProcedimento
    join pd in oListaprocedimentodetalhe on p.codigo equals pd.codigoProcedimento into pd1
    from pd2 in pd1.DefaultIfEmpty()
    select new ProcedimentoDetalhe()
    {
        codigoDetalhe = pd2.codigoDetalhe == null ? "000" : "012",
        codigoProcedimento = p.codigo,
        descricao = p.descricao,
        idadeMax = p.idadeMax,
        idadeMin = p.idadeMin
    }).OrderBy(p => p.descricao)
      .ToList();

Recebo o erro dizendo que pd2 was null, sendo que eu já tentei corrigir isso na linha: pd2.codigoDetalhe == null ? "000" : "012".
Porque não está funcionando?

A: Estou achando esse código estranho, mas não está fazendo o que imagina. Não está analisando se o p2 é null está analisando se um campo dele (pd2.codigoDetalhe) é nulo, o que é tarde demais porque o próprio p2 é nulo e já dá erro e não pode analisar seu campo que não existe já que seria um campo de algo nulo. O correto seria:
codigoDetalhe = pd2 == null ? "000" : "012",

Ainda assim não sei se esta é a solução final, mas resolve a questão que está na pergunta.
Você pode garantir que o campo nunca é nulo? Se não puder tem que verificar ele também, assim:
codigoDetalhe = pd2 == null || pd2.codigoDetalhe == null ? "000" : "012",

Coloquei no GitHub para referência futura.

A: Porque o que está nulo é o pd2, não a propriedade pd2.codigoDetalhe.
Tente assim:
codigoDetalhe = pd2 == null ? "000" : "012",

A: Mude sua linha para compara pd2  e codigoDetalhe se são iguais a null
codigoDetalhe = pd2 == null && pd2.codigoDetalhe == null ? "000" : "012",
Uma coisa curiosa é você trocar o valor de codigoDetalhe por outro valor.
Se você esta tralhando com listas faria algo mais performático assim.
(from p in listaProcedimento
    select new ProcedimentoDetalhe()
    {
        codigoDetalhe = (oListaprocedimentodetalhe.any(pd => p.codigo == pd.codigoProcedimento && pd.codigoDetalhe != null) ? "012" : "000" ,
        codigoProcedimento = p.codigo,
        descricao = p.descricao,
        idadeMax = p.idadeMax,
        idadeMin = p.idadeMin
    }).OrderBy(p => p.descricao)
      .ToList();

Dentro do seu select faria a verificarão do seu campo .
(oListaprocedimentodetalhe.any(pd => p.codigo == pd.codigoProcedimento && pd.codigoDetalhe ! null)


text:
Q: Compare Columns in 2 Workbooks With multiple entries per cell? I have 2 workbooks. And I am comparing column entries to verify that all of the entries in one column are represented in the second workbook's column.
I am using the following formula:
=IF(OR(TEXT(B2,0)=RIGHT('C:\Users\XXXXXXXXX\Documents\Call Manager Exports\[Doc1.xls]Doc2'!$D$2:$D$1000,10)),"YES","NO")

However, I have run into an issue where the workbook I am comparing against, has multiple entries in the same cell. This is of course skewing the data I just cannot figure out how to get the formula to check all of the entries in a cell.
It would be fine if even a single entry of the multiples reported a "NO".
To get an idea.
Both workbooks have phone numbers.
Workbook A has a column with phone numbers and some of the cells have multiple phone numbers in them.
Workbook B has a list of phone numbers and is checking to see that each of it's phone numbers is represented in Workbook A.  IF it is found Workbook A then it reports "yes" if not "no".

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make a bash script classify files in folders by a specific number I found a script, here on StackOverflow, which I modified a little.
The script classifies all files from a folder in subfolders, each subfolder having only 8 files. But I have files with such names 0541_2pcs.jpg. 2pcs means two pieces (copies).
so I would like the script to take this into count when dividing files to each folder. e.g. a folder may have 6 files and this 0541_2pcs.jpg which literally means 2 files and so on, depending on the number indicated in the file's name.
This is the script:
cd photos;
dir="${1-.}"
x="${1-8}"

let n=0
let sub=0
while IFS= read -r file ; do
    if [ $(bc <<< "$n % $x") -eq 0 ] ; then
            let sub+=1
            mkdir -p "Page-$sub"
            n=0
    fi

    mv "$file" "Page-$sub"
    let n+=1
done < <(find "$dir" -maxdepth 1 -type f)

Can anyone help me?

A: You can add a test for whether a file name contains the string "2pcs" via code like [ ${file/2pcs/x} != $file ].  In the script shown below, if that test succeeds then n is incremented a second time.  Note, if the eighth file tested for inclusion in a directory is a multi-piece file, you will end up with one too many files in that directory.  That could be handled by additional testing the script doesn't do. Note, there's no good reason for your script to call bc to do a modulus, and setting both of dir and x from the first parameter doesn't work; my script uses two parameters.
#!/bin/bash

# To test pagescript, create dirs four and five in a tmp dir.
# In four, say
#    for i in {01..30}; do touch $i.jpg; done
#    for i in 03 04 05 11 16 17 18; do mv $i.jpg ${i}_2pcs.jpg; done
# Then in the tmp dir, say
#     rm -rf Page-*; cp four/* five/; ../pagescript five; ls -R

#cd photos;   # Leave commented out when testing script as above
dir="${1-.}"  # Optional first param is source directory
x=${2-8}      # Optional 2nd param is files-per-result-dir

let n=x
let sub=0
for file in $(find "$dir" -maxdepth 1 -type f)
do  # Uncomment next line to see values as script runs
    #echo file is $file, n is $n, sub is $sub, dir is $dir, x is $x
    if [ $n -ge $x ]; then
        let sub+=1
        mkdir -p Page-$sub
        n=0
    fi
    mv "$file" Page-$sub
    [ ${file/2pcs/x} != $file ] && let n+=1
    let n+=1
done


text:
Q: How to check if wifi is connected in uiautomator? in my uiautomator test, i want to do something like
if( wifi is connected) {
    doSth();
} else {
    doSthElse();
}

Can I check that?

A: Since version 21 (?) UiAutomator has access to Instrumentation and thus to Context.
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
Context context = instrumentation.getContext();
WifiManager wManager = context.getSystemService(Context.WIFI_SERVICE); //this works for other services as well

Now you can use all WifiManager methods such as:
wManager.isWifiEnabled()
wManager.setWifiEnabled(boolean)  //turn wifi on and off

A: method-1
Goto Wifi page- check "Conncted" string below your ssid.
method-2
check out put of adb shell netcfg and grep for valid ipaddress for wifi interface,mostly- wlan0.
method-3 (but works on rooted phones)
check out put of adb shell wpa_cli ifname=wlan0 status, It gives wifi connected or not information.
All above methods you can code with uiautomator.


text:
Q: No output will be generated because there is no Main module I wrote a simple module called Test:
module Test (main) where

main =
  putStrLn "Hello"

However, when i try to compile it via the following command line:
ghc Test.hs -o my-program

I get the following error:
[1 of 1] Compiling Test             ( Test.hs, Test.o )

<no location info>: error:
    output was redirected with -o, but no output will be generated because there is no Main module.

A: ghc will assume that the main is located in a module called Main (like the compiler says).
ghc however has an option -main-is where you can specify the name of the module where the main function is located. So you can compile with:
ghc -main-is Test Test.hs -o my-program

A: I had the same problem, but in my case I had caused it by adding a module name to the test source file, test/Spec.hs:
module Tests where

main :: IO ()
main = hspec $ do ...

The solution was simply removing the first line:
main :: IO ()
main = hspec $ do ...

This is also the default when you create a project with stack - e.g., stack new myproject.


text:
Q: Facebook notification style (3), etc. in the window title Facebook puts a little (1) in the page title whenever you have a comment, etc. I find this really handy when I have a bunch of tabs open, and it would be great on Stack Overflow too. So, could we get the development team to add this in?
To clarify, when a notification or comment is received and shown as a number in a red/blue circle next to the Stack Exchange logo in the top bar, I think it would be a good idea to mirror that number in the page title, similar to the way Facebook does.

A: This kind of notification exists, but is being used for a different purpose. On the front page for each site (except SO due to large volume), the title will notify you when a question has been updated.


text:
Q: Shared state in a XCTestCase class? Can I have shared states in a XCTestCase class?
class Tests: XCTestCase {
    var person: Person!

    override func setUp() {
        person = Person()
    }
    override func tearDown() {
        person = nil
    }
    func testExample() {
        print("✅ testExample")
        print(person)
        XCTAssertTrue(true)
    }

    func testExample2() {
        print("✅ testExample2")
        print(person)
        XCTAssertTrue(true)
    }
}

For example in the above code I know that person object is different in the different test methods, but is it possible to have same memory location for person object in both the test methods?

A: There are many popular misconceptions or confusions about how tests work, so I'll just take this opportunity to set the record straight. The memory is managed in a really weird way:
Every time a test method runs, a brand-new instance of the test case class is created, and that instance stays in existence until all the test methods of every test case class have finished.
Thus, you don't need to create the Person object for the person instance variable before every test method (setUp), because you'll get a whole new Tests instance and thus a whole new Person object, before every test method, if you just say
    var person: Person! = Person()

But you do need your tearDown to nilify the person instance variable after each test method, because otherwise you'll end up with lots of Person objects. That might not matter for a tiny Person but it's a good habit to get into because you can use a boatload of memory without realizing it otherwise.


text:
Q: $\theta_1(\theta_1 + 1)x^\theta_1 = \theta_2(\theta_2 + 1)x^{\theta_2} \Rightarrow \theta_1 = \theta_2$ Let's fix number $x \in (0, 1)$. I want to prove for $\theta_1, \theta_2 > 0$ that:
$$\theta_1(\theta_1 + 1)x^\theta_1 = \theta_2(\theta_2 + 1)x^{\theta_2} \Rightarrow \theta_1 = \theta_2$$
I wanted to assume that $\theta_1 \neq \theta_2$. Then without loosing of generality we can assume that $\theta_1>\theta_2$. Then we can say that $\exists_{\epsilon>0}:\theta_1 =\theta_2 + \epsilon$ and rewrite expression as:
$$(\theta_2 + \epsilon)(\theta_2 +  \epsilon + 1 )x^\epsilon = \theta_2(\theta_2 + 1)$$
$$(1 + \frac{\epsilon}{\theta_2})(1 + \frac{\epsilon}{\theta_2 + 1})x^\epsilon = 1$$
But I couldn't find any contradiction. Could you please give me a hint how can I prove it?

A: Define $$f(x;\theta) = \theta(\theta+1)x^\theta, \quad 0 \le x \le 1, \quad \theta > 0.$$  Then if your question is whether $$\bigl(f(x;\theta_1) = f(x;\theta_2) \quad \forall x \in [0,1]\bigr) \implies \theta_1 = \theta_2, \tag{1}$$ then the answer is yes.  If however, your question is whether for a single given $x \in [0,1]$, if $f(x;\theta_1) = f(x;\theta_2)$, then $\theta_1 = \theta_2$, the answer is no; e.g., $$f(\sqrt{3/10}; 2) = f(\sqrt{3/10}; 4) = \frac{9}{5}.$$
How do we prove the assertion $(1)$?  We reason by contradiction.  Suppose $\theta_1 \ne \theta_2$ and for all $x \in [0,1]$, $f(x;\theta_1) = f(x;\theta_2)$.  Then this implies
$$\frac{f(x;\theta_1)}{f(x;\theta_2)} = \frac{\theta_1(\theta_1 + 1)}{\theta_2(\theta_2 + 1)} x^{\theta_1 - \theta_2} = 1$$ for all $x \in [0,1]$.  Equivalently, this implies
$$x^m = c$$ for some nonzero constants $m = \theta_1 - \theta_2$ and $c > 0$.  But this has the unique solution $x = c^{1/m}$, which of course cannot equal all values in $[0,1]$.  Therefore, no such $\theta_1, \theta_2$ exist.


text:
Q: Get evenly spaced X, Y cords from a given size and required amount I'm working in Actionscript 3, but this is pretty general.
I'd like to make a simple function that I can call, e.g. GiveCords(Width, Height, Num) that will take a width and height, map that out and using the Num variable place the given amount evenly across the space.
Say I give it a value of 500, 500, 1. I'd expect it to return an X, Y position of 250, 250.
But I'd like it to return an array of given points with X, Y.
So If I gave it 10 points, it would find the best position for them all to be of even distance apart from each other.
I'm guessing there is a simple formula for working this out, but I've searched a plenty and found nothing.
Cheers

A: If I understood correctly this should do the job:
var object:Object = {width: 500, height:500, num:10};
var points:Array = getCoordinates(object);

function getCoordinates(object:Object):Array {

   var array:Array = new Array();
   var widthMultiplier:Number = object.width / (object.num + 1);
   var heightMultiplier:Number = object.height / (object.num + 1);

   for (a = 1; a <= object.num; a++) {
      var coordinates:Point = new Point();
      coordinates.x = widthMultiplier * a;
      coordinates.y = heightMultipler * a;
      array.push(coordinates);
   }

return array;
}

It takes the number of items and the total space, divides the total space by the number of items + 1 (to account for the space at the end of the last element) increment the objects each time.
Edit: In response to comments here is a version where you can state the number of rows you want your objects to spread across. If the number of rows does not divide the number of objects and return an integer then the function will return null. If you do not give it a rows paramater it assumes you want it across one row. Enjoy.
var object:Object = {width:500,height:500,num:10};
var points:Array = getCoordinates(object,2);

function getCoordinates(object:Object, rows:int = 1):Array
{
    if ((object.num / rows) % 1)
    {
        return null;
    }
    else
    {
        var columns:int = object.num / rows;

        var array:Array = new Array();
        var widthMultiplier:Number = object.width / (columns + 1);
        var heightMultiplier:Number = object.height / (rows + 1);

        for (var a = 1; a <= rows; a++)
        {
            for (var b = 1; b <= columns; b++)
            {
                var coordinates:Point = new Point();
                coordinates.x = widthMultiplier * b;
                coordinates.y = heightMultiplier * a;
                array.push(coordinates);
            }
        }

        return array;
    }
}


text:
Q: Download File by starting a Chrome Process I want to download a file by just starting a new Process of Chrome. I've found the parameter "--download", so the solution should be "CHROMEPATH --download URI". ( http://peter.sh/experiments/chromium-command-line-switches/#download )
I wrote the code to start the process in C#, and yes, I know there are other options to do this like webclient, but I don't want to implement the download per se in my code.
string FILEURI = "example.org/file.png";
System.Diagnostics.Process prozess = new System.Diagnostics.Process();
prozess.StartInfo.FileName = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
prozess.StartInfo.Arguments = "--download " + FILEURI;
prozess.Start();

This works without any problem, but just opening the link "file://FILEURI". So I can't download it without any user interaction.

A: Chrome always downloads to the download folder.  You could try to just get the latest download file, like this:
new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),"Downloads"))
    .GetFiles()
    .OrderByDescending(f => f.CreationTime)
    .First()

This has risks (as outlined by DavidG) as well as the fact the user might download another file, etc.  So this is not necessarily the best way.


text:
Q: Is there something wrong with the index number of array in merge sort? So I am trying to implement merge sort in C++, and this version uses O(n) of space complexity.
This algorithm is written using pseudo-code found in the book "Foundation of Algorithms".
I think there are some errors when using the index in the function merge2.
The variables that end with _tmp are used to manipulate the array U, and variables without _tmp are used to manipulate the array S.
#include <iostream>

int n = 8;
int S[8] = { 0, };

void mergeSort2(int low, int high);
void merge2(int low, int mid, int high);

void mergeSort2(int low, int high) {
    int mid;
    if (low < high) {
        mid = (low + high) / 2;
        mergeSort2(low, mid);
        mergeSort2(mid + 1, high);
        merge2(low, mid, high);
    }
}

void merge2(int low, int mid, int high) {
    int i, j, k;
    int i_tmp, j_tmp, k_tmp;
    int high_tmp = high - low;
    int low_tmp = 0;
    int mid_tmp = high / 2;
    i_tmp = low_tmp; j_tmp = mid_tmp + 1; k_tmp = low_tmp;
    i = low; j = mid + 1; k = low;
    int* U = new int[high_tmp + 1];
    while (i <= mid && j <= high) {
        if (S[i] < S[j]) {
            U[k_tmp] = S[i];
            i++;
            i_tmp++;
        }
        else {
            U[k_tmp] = S[j];
            j++;
            j_tmp++;
        }
        k++;
        k_tmp++;
    }
    if (i_tmp > mid_tmp) {
        //move S[j] through S[high] to U[k] through U[high-1]
        for (int r = j, s = k_tmp; r < high, s < high_tmp; r++, s++) {
            U[s] = S[r];
        }
    }
        else {
        //move S[i] through S[mid] to U[k] through U[high-1]
        for (int r = i, s = k_tmp; r < mid, s < high_tmp; r++, s++) {
            U[s] = S[r];
        }
    }
    //move U[low] through U[high] to S[low] through S[high-1]
    for (int r = low_tmp, s = low; r < high_tmp, s < high; r++, s++) {
        S[s] = U[r];
    }
    delete U;
}

int main() {
    std::cout << "Enter the elements of the array S (size : " << n << ") : ";
    for (int i = 0; i < n; i++) {
        std::cin >> S[i];
    }
    mergeSort2(0, n);
    std::cout << std::endl;
    std::cout << "Result of array S sorted in an ascending order : ";
    for (int i = 0; i < n; i++) {
        std::cout << S[i] << "  ";
    }
    std::cout << std::endl << std::endl;
    return 0;
}

A: As pointed out in the comments, the problem is with your for loops' test conditions using the comma operator. As described in cppreference:

In a comma expression E1, E2, the expression E1 is evaluated, its
  result is discarded ... before evaluation of the expression E2 begins ...

So, in the loop:
for (int r = j, s = k_tmp; r < high, s < high_tmp; r++, s++) {
   //...

the r < high expression is never used and the loop will only end when the s < high_tmp expression evaluates to false.
If you want the loop to end when either expression is false, you need to combine the two tests with && (logical AND operator):
for (int r = j, s = k_tmp; r < high && s < high_tmp; r++, s++) {
   //...


text:
Q: Converting Excel VBA 32bit code to 64bit A friend of mine made this Excel VBA code for me a while ago. It's 32bit, but now I need it converted for 64bit.
Can anyone please help me to do so?
Private Declare Function FindWindow Lib "user32" _
                     Alias "FindWindowA" ( _
                             ByVal lpClassName As String, _
                             ByVal lpWindowName As String) As Long

Private Declare Function GetWindowLong Lib "user32.dll" _
                     Alias "GetWindowLongA" ( _
                             ByVal hWnd As Long, _
                             ByVal nIndex As Long) As Long

Private Declare Function SetWindowsHookEx Lib "user32" _
                     Alias "SetWindowsHookExA" ( _
                             ByVal idHook As Long, _
                             ByVal lpfn As Long, _
                             ByVal hmod As Long, _
                             ByVal dwThreadId As Long) As Long

Private Declare Function CallNextHookEx Lib "user32" ( _
                             ByVal hHook As Long, _
                             ByVal nCode As Long, _
                             ByVal wParam As Long, _
                             lParam As Any) As Long

Private Declare Function UnhookWindowsHookEx Lib "user32" ( _
                             ByVal hHook As Long) As Long

Private Declare Function PostMessage Lib "user32.dll" _
                     Alias "PostMessageA" ( _
                             ByVal hWnd As Long, _
                             ByVal wMsg As Long, _
                             ByVal wParam As Long, _
                             ByVal lParam As Long) As Long

Private Declare Function WindowFromPoint Lib "user32" ( _
                             ByVal xPoint As Long, _
                             ByVal yPoint As Long) As Long

Private Declare Function GetCursorPos Lib "user32.dll" ( _
                             ByRef lpPoint As POINTAPI) As Long

A: You need to use "PtrSafe" when declaring function :
Private Declare PtrSafe  Function

Also in 64bit Excel, use LongLong instead of Long

A: and LongPtr for callback functions
but for ptrSafe compiler itself will warn you if this is missing


text:
Q: Guacamole get password from external api I'm trying to setup a guacamole instance to manage my servers accounts. It's working well when I'm using my MySQL database to manage connection user ID and user password.
But I would like to get my password from my keepass like container through REST API, the idea is to store my password in one and secure location !
I have several ideas to do it, but to be honnest this is not very "beautiful"

*

*Hack the JDBC extension to replace my password when guacamole try to access it. So I store in my password field something like "MY_KEEPASS:password_id" and I will do a request to my API, get the value and replace MY_KEEPASS:password_id by the password

*Use the token extension to execute my api call when password will find the token ${PASS}. But I'm not sure this is possible without hack the token extension...

Do someone have a better idea to do that ?
Thanks

A: You can create an authentication extension for Guacamole, this is a regular way to provide more authentication mechanism to the Guacamole. The extension is essentially a .jar that can be registered to the Guacamole as an authenticator.
In your case, it would be probably sufficient to extend some of the JDBC authentication plugins and add your specific auth method.
You can find some documentation about this on the Guacamole site: http://guacamole.apache.org/doc/gug/custom-auth.html. There are also examples in the examples directory of the guacamole-client.


text:
Q: Repeat content title how i can fix? <?php if (function_exists('get_highest_score_category')): ?>
    <?php get_highest_score_category(81); ?>
<?php endif; ?>

index.php code:
<?php query_posts('showposts=5&orderby=date&cat=81'); ?>
<?php while (have_posts()) : the_post(); ?>
<?php if (function_exists('z_taxonomy_image_url')) echo z_taxonomy_image_url(); ?>

1.

<img src="<?php bloginfo('template_url'); ?>/images/metin2kucuk.png" />

<?php if (function_exists('get_highest_score_category')): ?>
<?php get_highest_score_category(81); ?>
<?php endif; ?>

<img src="<?php bloginfo('template_url'); ?>/images/<?php echo get_post_meta($post->ID, "metin_selectt", true); ?>.png" />

<?php echo get_post_meta($post->ID, "metin_select", true); ?>

<?php endwhile; ?>

Example my problem:

A: I have tried to make sense of the code, this is what I have been able to come up with:
<?php
    query_posts('showposts=5&orderby=date&cat=81');
    while (have_posts()) : the_post();
        if (function_exists('z_taxonomy_image_url')) echo z_taxonomy_image_url();
?>

1.

            <img src="<?php bloginfo('template_url'); ?>/images/metin2kucuk.png" />

            <?php
                if (function_exists('get_highest_score_category')):
                    get_highest_score_category(81);
                endif;
            ?>

            <img src="<?php bloginfo('template_url'); ?>/images/<?php echo get_post_meta($post->ID, "metin_selectt", true); ?>.png" />

            <?php
                echo get_post_meta($post->ID, "metin_select", true);
            ?>

<?php
    endwhile;
?>

All I see is a loop to blame. I would guess that something with have_posts() and the_post() is not working well, causing it repeat the post.


text:
Q: Is ClassName.variable always a static member variable? I had never seen syntax like below, where a variable is directly initialized by appending to the class name (except in case of static members)
class Fruit {
  constructor(color) {
    this.color = color;
  }
}
Fruit.count = 0;

Where does this count variable go in the memory? I can't access it with class instance. So, is it a static member implicitly. How will it look in Classical Prototypal Inheritance? Thanks in advance.

A: Any property directly assigned to a class, like with Fruit.count = 0;, is considered to be a validly assigning static variable/member. One actually uses the constructor as namespace.
Examples ...

class Fruit {
  constructor(color) {
    this.color = color;
  }
}
Fruit.count = 0;

console.log('considered to be "static" ... Fruit.count :', Fruit.count);

const fruitType = new Fruit('yellow');

console.log('fruitType.constructor.count :', fruitType.constructor.count);

class Fruit {
  constructor(color) {
    this.color = color;
  }
  static count = 42;
}

console.log('literally "static" ... Fruit.count :', Fruit.count);

const fruitType = new Fruit('red');

console.log('fruitType.constructor.count :', fruitType.constructor.count);

function Fruit(color) {
  this.color = color;
}
Fruit.count = 9;

console.log('old school "static" ... Fruit.count :', Fruit.count);

const fruitType = new Fruit('pink');

console.log('fruitType.constructor.count :', fruitType.constructor.count);

How will it look in Classical Prototypal Inheritance?

Static and Prototypal do not have anything in common. Thus there will not be any valid answer to this last Q.
But in case the OP was referring with "Classical Prototypal Inheritance" to ES3 syntax then it has been answered by the third example code.

A: class Fruit {
  constructor(color) {
    this.color = color;
  }
  static s = 1
}

Fruit.count = 0
const f = new Fruit('red')

count and s are a properties of Fruit object. console.dir(Fruit) results in -
class Fruit
  count: 0
  s: 1
  arguments: (...)
  caller: (...)
  length: 1
  name: "Fruit"
  prototype: {constructor: ƒ}
  __proto__: ƒ ()
  [[FunctionLocation]]: VM924:2
  [[Scopes]]: Scopes[2]

In the above output, Fruit.prototype.constructor and Fruit are same i.e. Fruit.prototype.constructor === Fruit is true.
console.dir(f) results in -
Fruit
  color: "red"
  __proto__:
    constructor: class Fruit
    __proto__: Object

When a new object is constructed from this class, Fruit.prototype becomes f.__proto__. So Fruit.prototype === f.__proto__ is true.
So you can access the static properties by f.__proto__.constructor.count. Since properties on __proto__ are inherited to the instance directly, you can access them by f.constructor.count.


text:
Q: Why does REPEATABLE READ not see new rows? I thought that REPEATABLE READ should not pick up on changed data but should pick up on new data.
However I have the following script:
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;

create table testLocking(a int);

BEGIN TRANSACTION
    insert into testLocking values (1);
    select * from testLocking;
    WAITFOR DELAY '000:00:30';
    select * from testLocking;
COMMIT TRANSACTION;

BEGIN TRANSACTION
    insert into testLocking values (2);
    UPDATE testLocking SET A=4 WHERE a=1;
    select * from testLocking;
    WAITFOR DELAY '000:00:40';
COMMIT TRANSACTION;

drop table testLocking;

I get the results:
1

1

4
2

I was expecting:
1

1
**2**

2
4

Can anyone see what I have done wrong?
UPDATED
I want to be able to see the effects of transaction isolation levels by running queries concurrently.

A: Repeatable Read means that changes made by other transactions are not reflected in your queries.  You code makes it's change in the same transaction.
UPDATED
A single script is not able to show the effects of two transactions interacting with a database.  The best way to do this in SSMS is to separate the code into two windows.  Open them side by side using Window -> New Vertical Tab Group.
By highlighting lines one at a time you can run the transactions concurrently and you will see the effects of the queries in each window.


text:
Q: Google CSE - jump to specific keyword i'm currently working with the google cse and i wonder wether it's possible to jump to a specific searchword. for example if i goole on my page the word publications, and there is a section of publications on a page, is it possible to jump directly to this section by using the implemented google search?
at the moment every search i do, leads me to the beginning of the page where the keyword is placed.
greetings martin

A: This is possible, yes, but you would have to do some coding.  If you think about how the Google search works, it just generates a list of links.  It has no control over what happens once you reach the other page.  So, anything that you wanted to happen on the destination page, you would have to code yourself.  If you really want to do this, you could set it up something like this:
First, you will want to use a V1 CSE, since it offers the ability to set a callback function on search complete, which the new, simplified V2 does not.  See V1 documentation here: https://developers.google.com/custom-search/docs/js/cselement-devguide
Here's the sample code from that page, modified to add a callback function:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Custom Search Element API Example</title>

Loading...

Then you can create that callback function like so:
function searchCompleteFn(control, searcher) {
    //your code
}

In your code, you would want to get all the a.gs-title elements within the cse div and modify their href attributes to add the user's query.  That way your destination page can see what the user searched for and take appropriate action (scroll to the appropriate section, highlight the keywords, whatever you want).  For example, if the existing href is http://www.yoursite.com/somepath/somepage.html, you could change it to http://www.yoursite.com/somepath/somepage.html#query=[user_query].
[user_query] is given by control.getInputQuery()
Finally, on your destination pages you would have javascript check for a query parameter in location.hash, and act appropriately.
I'm guessing this is way more work than you're interested in doing, but perhaps it will be helpful to someone.


text:
Q: Memory issue with ViewPager I'm currently developing an app that uses a ViewPager, the problem is that the way I'm doing it makes it extremely slow to start and takes up tonnes of memory.
I'm implementing the pageradapter like so:
        public MyPagerAdapter(Context context) {
        views = new ArrayList<RelativeLayout>();
        views.add(new SliderLayout(context, "slide 8"));
        views.add(new SliderLayout(context, "slide 1"));
        views.add(new SliderLayout(context, "slide 2"));
        views.add(new SliderLayout(context, "slide 3"));
        views.add(new SliderLayout(context, "slide 4"));
        views.add(new SliderLayout(context, "slide 5"));
        views.add(new SliderLayout(context, "slide 6"));
        views.add(new SliderLayout(context, "slide 7"));
        views.add(new SliderLayout(context, "slide 8"));
        views.add(new SliderLayout(context, "Slide 1"));
    }

All the layoutobjects contain a FrameLayout with a textView and a panel that contains a webview with local html. All the layouts have unique content, that is loaded and inflated when the SliderLayout class is instantiated.
I also attempted to add views on the fly in the instantiateItem method, but that just makes the scrolling more dodgy and will give an OutOfMemory fatal exception if I scroll too fast.
So my question is, what is the best way to implement a ViewPager that contains several unique views (but based on the same layout), so it doesn't consume so much memory and starts quicker?

A: You must attach your views to pager in instantiateItem() (like you do it in regular adapter's getView() method). In this case ViewPager takes care about memory management. Take a look into demo project in CompatibilityPackage. Actually you can have thousands of pages without any lags.
@Override
public Object instantiateItem(View collection, int position) {
    View v = layoutInflater.inflate(...);
    ...
    ((ViewPager) collection).addView(v,0);
    return tv;
}

@Override
public void destroyItem(View collection, int position, Object view) {
    ((ViewPager) collection).removeView((TextView) view);
}

A: hm, my idea is to catch the event "onPageChanged()" in the ViewPager and set the
webview after the page has changed - or, to preload as example a page so you have
the "scroll effect": you do the following:
as example, you have a count of 10 pages. if your viewpager is at page 0, then you instanciate and load the pages 0,1,2. if your viewpager is at screen 4, then you remove the webviews
at positions 0,1 and 7,8,9...
in this way you dont need all instances of webviews (webkit consumes a lot of memory)
and have some more memory.


text:
Q: index openxml structured documents with Elasticsearch We have a set of structured documents. The structure is extremely inspired by openxml data model. Briefly speaking, documents are made up of an ordered set of paragraphs, each paragraph itself has id and an ordered set of runs and each run has a textual content and some metadata.
For instance, the following sample document contains two ["Lorem ipsum" , "dolor sit amet"] paragraphs.
{
    id: 1
    paragraphs : [
        {
            title: "De finibus"
            runs: [
                {text: "Lorem i", metadata: {} },
                {text: "psu", metadata: {bold: true} },
                {text: "m", metadata: {} },
            ]
        },
        {
            id: 2
            runs: [
                {text: "dolor sit amet", metadata: {} },
            ]
        },
    ]
}

We want to index the documents by Elasticsearch, of course, in a way such that it be able to answer the following queries:

*

*Query: dolor sit
Expected answer: in the document with title="De finibus", in the paragraph with id=2, from the 1th character of the 1s run to the 9th character of the 1rd run

*Query: ipsum
Expected answer: in the document with title="De finibus", in the paragraph with id=1, from the 7th character of the 1s run to the 1st character of the 3rd run

*Query: ipsum dolor
Expected answer: in the document with title="De finibus", from the 7th character of the 1s run of the paragraph with id=1 to the 5th character of the 1rd run of the paragraph with id=2
I familiar with nested field in elastic. It may satisfy the first query. But how should we map our documents to connect the consecutive runs and  paragraphs together and make elastic to answer two latter queries?


text:
Q: gnuplot+latex+postscript eps enhanced terminal: key text misaligned i am compiling some eps graphs with gnuplot using the following terminal line:
set terminal postscript enhanced eps color dashed rounded dl 4 "Times-Roman" 24

An example:
p 'file1' u 5:6 w p t 't=0.5 ms',\
  'file2' u 5:6 w p t '    1 ms',\
  'file3' u 5:6 w p t '    2 ms'

I added extra spaces in the key to have a nice alignment for the labels in the key. This alignment works fine if i open the resulting eps with ghostviewer, but if i compile it within a latex file
$ latex
 ... pdfTeX, Version 3.14159265-2.6-1.40.15 (TeX Live 2015/dev/Debian) ...

then the text in the key is misaligned. It happens especially if i am using special typesetting like subscripts or superscripts:
p 'file1' u 5:6 w p t 't_{something}=0.5 ms'

then the text will be totally jeopardized, like overlapping text or weird alignments, but only after compiling within latex.
Have you ever seen this before?
Many thanks
edit: add a minimal example
gnuplot script:
set terminal postscript enhanced eps color dashed rounded dl 4 "Times-Roman" 24
set key spacing 1.1 samplen 1.2 top left
set output 'out.eps'
p 3*x w p lc 1 t 't=0.5 ms',\
  2*x w p lc 2 t '    1 ms'

everything fine if I run:
$gv out.eps

i compile the following latex file:
\documentclass[final,5p,times,onecolumn]{elsarticle}

\usepackage{float}
\usepackage{graphicx}
\usepackage{subfig}
\usepackage{fixltx2e}
\usepackage{epstopdf}

\journal{Combustion and Flame}

\begin{document}

\begin{figure*}[]
    \centering\includegraphics[width=\textwidth]{out}
 \caption{caption.}
\end{figure*}

\end{document}

using the following script ($name=latex file name):
latex $name.tex
latex $name.tex
dvips $name.dvi
ps2pdf $name.ps

using acroread, evince or xpdf, the 't=0.5 ms' label overlaps the corresponding key symbol, while visualizing out.eps on gv shows everything fine, with key text aligned to the right.
FURTHER EDIT:
replacing elsarticle with book solves the problem!
LAST EDIT:
compiling with pdflatex instead of latex solves the problem


text:
Q: Assignin object to self inside class method I want to do a check inside model whether object already exists in DB or not, and if its exists to read all properties from DB and assign to same object.
models.py
class Obj1(models.Model)
    name
    prop1
    prop2
    prop3

    def obj_check(self, name, prop1):
        objects = Obj1.object.filter(name=name, prop1=prop1)
        len = len(objects)
        if len == 0:
            # Object does not exists in DB
            self.name = name
            self.prop1 = prop1
            self.save()
            return 0
        elif len == 1:
            # Object does exists in DB
            self = objects[0]  # <<< Is it possible to do like this?
            return 1
        else:
            # Something wrong, too many objects in DB
            return len

main.py
...

obj = Obj1()
check = obj.obj_check(name, var)
if check == 0:
    print("Such object does NOT exists")
    print("New object created")
elif check == 1:
    print("Such object already exists")
    obj.prop3 = "New Value"
else:
    print("Something wrong, too many objects in DB")

Is this possible/right to do like this?
self = objects[0]
I know I can use try: .. except Obj1.DoesNotExist: costruction, but wanted to create Object first and make less queries to DB.
Thanks!

A: No, reassigning self doesn't really do anything. It just reassigns the local variable, it does not modify the object.
You would want to implement this kind of method as a method on the model manager instead. The default manager for an object is the .objects property, but you can also implement your own manager.
Obj1Manager(models.Manager):
    def obj_check(self, name, prop1):
        qs = self.get_query()
        objects = qs.filter(name=name, prop1=prop1)
        n = len(objects)
        if n == 0:
            # Object does not exists in DB, create it
            obj = self.create(name=name, prop1=prop1)
            return obj, 1
        else:
            obj = objects.first()
            return obj, 0

class Obj1(models.Model):
    objects = Obj1Manager()
    # ...

# ....
obj, created = Obj1.objects.obj_check(name='foo', prop1='bar')

However, it's worth noting that this already exists as a default manager method: get_or_create.
obj, created = Obj1.objects.get_or_create(name='foo', prop1='bar')


text:
Q: Bluetooth status on statusbar I have  my own application home screen as default home screen for  my android device. I have a status bar in my application and I am managing the Bluetooth connection status with an Imageview(onclick) in that status bar.
If I click on the Imageview in my statusbar I am turning the bluetooth on/off. I am changing the background of imageview according to the status of bluetooth.
If bluetooth is ON -  Blueimage
If bluetooth is OFF - greyImage
So my question is - If I enable/disable the bluetooth in bluetoth settings page and press the back button and navigate to my home screen then Imageview(background image) in my status bar should get changed automatically.
I tried a lot updating the image of  imageview  on back button press(by overriding onbackpressed method) but no result.
Is there any similar API with which we can read/store the status of bluetooth in a variable as soon as we enable/disable the bluetooth in bluetooth settings page and according to that the status bar imageview backround will get changed automatically?
Any help is greatly appreciated, Thanks

A: you can put the code that checked for the Bluetooth status in the onRestart() method
like this:
public class yourClass {

 public void onCreate(Bundle savedInstanceState) {

 // your code
 }

 public void onRestart() {

 // put the checked code for the Bluetooth status here
 }

A: You need to add broadcast receivers in your code to receive once bluetooth is switched on or off in your activity class. for your reference :
public void onCreate() {

    IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
    IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    this.registerReceiver(mReceiver, filter1);
    this.registerReceiver(mReceiver, filter2);
    this.registerReceiver(mReceiver, filter3);

}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        ... //Device found
        }
        else if (BluetoothAdapter.ACTION_ACL_CONNECTED.equals(action)) {
        ... //Device is now connected
        }
        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
         ... //Done searching
        }
        else if (BluetoothAdapter.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
        ... //Device is about to disconnect
        }
        else if (BluetoothAdapter.ACTION_ACL_DISCONNECTED.equals(action)) {
        ... //Device has disconnected
        }

once you receives the status do your functionality .. done !!


text:
Q: Why doesn't Telegram's desktop file show its name label in the Dash? I've created a .desktop file for Telegram but it doesn't show the label like all others. I did the same with Android Studio and it worked perfectly. Here's what I typed within telegram.desktop :
[Desktop Entry]
Version=1.0
Name=Telegram
Comment=Telegram
Exec=/usr/local/Telegram/Telegram
Icon=/usr/local/Telegram/telegram.png
Terminal=false
Type=Application
Categories=Messaging;

A: just run telegram it will automatically create a telegramdesktop.desktop file as follows
[Desktop Entry]
Encoding=UTF-8
Version=1.0
Name=Telegram Desktop
Comment=Official desktop version of Telegram messaging app
#path file
Exec=/home/username/download/telegram/Telegram -- %u
Icon=telegram
Terminal=false
StartupWMClass=Telegram
Type=Application
Categories=Network;
MimeType=x-scheme-handler/tg;
X-Desktop-File-Install-Version=0.22


text:
Q: Aws Blockchain Template Error on stack creation I'm trying to create stack to deploy fabric blockchain network on EC2, but I've always the same error

The following resource(s) failed to create: [FabricEC2CommonStack]. .
  Rollback requested by user. CREATE_FAILED AWS::CloudFormation::Stack
  FabricEC2CommonStack Embedded stack
  arn:aws:cloudformation:us-east-1:>:stack/FabricStack-FabricEC2CommonStack-NNFUD6RJCZB1/<>
  was not successfully created: The following resource(s) failed to
  create: [EC2InstanceForDev].

I thought it was a problem with my EC2 Instance profile, but it seems correct. It has the policies to use ECR+S3. Thanks


text:
Q: Possible to target HTML tag that is before text within a parent element? I want to target the  tag in sample 1, but not sample 2:
Sample 1:
foo() describes the function

Sample 2:
Other text comes first, bar() is not at the beginning

the code:first-child selector does not regard the text-node "Other text comes first" as a child element.
Any ideas, on whether I can handle this in pure CSS (I know how to do it with JS or by altering the HTML code, but that's not what is needed)

A: Unfortunately, no.
Not with pure CSS. There is no "first node of parent element without any text before it" selector.
Even with a combination of child combinator and the various sibling selectors (adjacent and / or general), this is not possible.
In fact, a javascript solution to this would be non-trivial to author, even if using jQuery.

A: In the context given, I also don't think this is possible.
If you are able to manage everything within a single element (in this case, a singular
 element), you can use the CSS :first-of-type selector, which matches every element that is the first child, of a particular type, of its parent:
<!DOCTYPE html>

  foo() describes the function

  Other text comes first, bar() is not at the beginning

  foo() describes the function

  Other text comes first, bar() is not at the beginning

In this case, only the first code element would be targeted with the CSS. You can see that in action here. More info on CSS :first-of-type selector.
Hope this helps :)


text:
Q: Using Synergy Pro 1.8.8, but clicks are not working on Client Windows 10 as the server and MacOS 10.13 as Client.
The client (macOS) is getting connected to the server. I can even see the mouse cursor. But the client is not accepting the clicks (Left or Right). The keyboard input works fine. I really don't understand the problem. Tried restarting both the host and the client and still, the problem persists.


text:
Q: Exception handler works for doGet(), but not for doPost() I have a servlet api where I used to throw my own exceptions from servlets level
When I throw exception from doGet method everything works fine and exception handler catches and processed my exception. the problem ocures when I throw exception from doPost method. in this case unfortunatelly I never see error page
web.xml
<error-page>
    <exception-type>java.lang.Throwable</exception-type >
    <location>/ErrorHandler</location>
</error-page>

exception handler
@WebServlet("/ErrorHandler")
public class ErrorHandler extends HttpServlet {

    private final Logger logger;

    public ErrorHandler() {
        logger = Logger.getLogger(ErrorHandler.class);
    }

    @Override
    public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
        Throwable throwable = (Throwable) httpServletRequest.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
        logger.error("occurred exception: ", throwable);
        httpServletRequest.getRequestDispatcher("/error.jsp").forward(httpServletRequest, httpServletResponse);
    }
}

Servlet
@Override
public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
    throw new UserException("error message");
}

A: Add to your ErrorHandler
@Override
public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
    Throwable throwable = (Throwable) httpServletRequest.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
    logger.error("occurred exception: ", throwable);
    httpServletRequest.getRequestDispatcher("/error.jsp").forward(httpServletRequest, httpServletResponse);
}

To avoid code duplication consider creating third method
private void processError(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    Throwable throwable = (Throwable) httpServletRequest.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
    logger.error("occurred exception: ", throwable);
    httpServletRequest.getRequestDispatcher("/error.jsp").forward(httpServletRequest, httpServletResponse);
}

and invoke it from both doGet() and doPost()
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    processError(req, resp);
}

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    processError(req, resp);
}


text:
Q: ¿Cómo registrar un effect para agregar una nueva entidad en Angular Ngrx/Effects/Entity? Estoy usando @Ngrx/entity para almacenar mi data en mi store en Angular 8. El problema que tengo es en el efecto (effects), puesto que cuando llamo a mi primera acción CREAR_TIPO, todo funciona OK, ya que traigo la información de mi formulario. Esta primera acción me devuelve el payload que le enviaré a mi servicio (el objeto nuevo a crear). Sin embargo, cuando se ejecuta no me devuelve el objeto creado, dándome NULL, es decir crea el objeto en la base de datos, pero no lo regitra correctamente en mi store.
Llevo horas en esto, si pudieran ayudarme, este es mi código:
Este son mis acciones:
export class CreateTipo implements Action {
    readonly type = TiposActionsTypes.CREATE_TIPO;
    constructor(public payload: Tipo) {}
}

export class CreateTipoFail implements Action {
    readonly type = TiposActionsTypes.CREATE_TIPO_FAIL;
    constructor(public payload: any) {}
}

export class CreateTipoSuccess implements Action {
    readonly type = TiposActionsTypes.CREATE_TIPO_SUCCESS;
    constructor(public payload: Tipo) {}
}

Estos son mis reducers:
case TiposActionsTypes.CREATE_TIPO_SUCCESS: {
            // console.log('action=');
            // console.log(JSON.stringify(action));
            // console.log('action.payload=');
            // console.log(JSON.stringify(action.payload));
            // console.log(JSON.stringify(action['paylaod']));
            return adapter.addOne(action.payload, state);
        }

Y, este es mi effect:
 @Effect()
    createTipo$ = this.actions$.pipe(
        ofType(tiposActions.TiposActionsTypes.CREATE_TIPO),
        map((action: tiposActions.CreateTipo) => {
            console.log('action.payload', action.payload);
            return action.payload;
        }),
        switchMap(tipo => {
                return this.tiposServices
                    .createTipo(tipo).pipe(
                        map(data => {
                            console.log('del efecto', data);
                            return new tiposActions.CreateTipoSuccess(data);
                        }),
                        catchError(err => of(new tiposActions.CreateTipoFail(err)))
                    );
            }
        )
    );

Muchas gracias de antemano por su tiempo.

A: Para registrar una nueva entidad se requiere que el servicio devuelva la entidad creada, la cual será pasada al reducer el cual ejecutará la acción de incluir una nueva entidad al store.


text:
Q: how to install android studio 2.0 offline complete how i can install android studio complete offline.
because my internet is slow.
thanks in advance.
I need to install android studio in many pc. So, i wish if there is any way to install android studio lattest version offline by downloading all the offline file just once time.


text:
Q: How to find product by manufacturer? I am using Laravel 8 and using Raw Query. I have added query to fetch count of product by manufacturers but facing below error.
SQLSTATE[42000]: Syntax error or access violation: 1055 'ngtonlin_superadmin.m.manufacturerid'
isn't in GROUP BY (SQL: select `m`.`manufacturerid` as `id`, `m`.`name`, `m`.`logowidth`,
`m`.`logoheight`, count(p.id) as total from `products` as `p` inner join `manufacturer` as `m` on
`m`.`manufacturerid` = `p`.`manufacturer_id` group by `p`.`manufacturer_id` order by `total` desc limit 5)

and my query is
DB::table('products as p')
        ->select('m.manufacturerid as id','m.name','m.logowidth','m.logoheight', DB::raw('count(p.id) as total'))
        ->join('manufacturer as m','m.manufacturerid','=','p.manufacturer_id')
        ->groupBy('p.manufacturer_id')
        ->orderBy('total', 'DESC')
        ->limit(5)
        ->get();

A: I think you need to use
->groupBy('m.manufacturerid', 'm.name','m.logowidth','m.logoheight')

Not
->groupBy('p.manufacturer_id')

Because, I think p.manufacturer_id = m.manufacturerid, and you use m.manufacturerid in the select part.

A: Try this:
DB::table('products as p')->join('manufacturer as m','m.manufacturerid','p.manufacturer_id')->selectRaw('m.manufacturerid as id')->selectRaw('m.name')->selectRaw('m.logowidth')->selectRaw('m.logoheight')->selectRaw('count(p.id) as total')->groupBy('p.manufacturer_id')->orderBy('total', 'DESC')->limit(5)->get();


text:
Q: deny any writing to given app and its children So I have a Python app (which spawns other processes) which I want to deny any writing. It seems like a job for SELinux. Could you describe the steps needed to accomplish this, or perhaps direct me to some good reading resource, since from what I've found there aren't too many.

A: Under every OS, it's quite hard to do this, at the moment. Chrome developers have made some progess in this area, but it's still hard. They came with a solution about 22k lines of code (LOC) for Win* systems and 11k LOC for Linux.
In recent news, FreeBSD 9.0 was announced with Capsicum, a framework designed for this purpose, but it can work only on *BSD systems.
On Linux, you can avoid SELinux or AppArmor using seccomp. See this LWN article for more details and sample usage. But it's really hard: it's an all or nothing feature for system calls like read or write.
There is currently a new approach on-going in the LKML, using Berkeley Packet Filter, see this post of Will Drewry.


text:
Q: ListBox SelectedItem not working I'm trying to load a list of objects as grids with several data and I've selected ListBox for it as you can see here:
<ListBox ItemsSource="{Binding People, Mode=TwoWay}" SelectedItem="{Binding Person, Mode=TwoWay}" >
  <ListBox.ItemContainerStyle>
     <Style TargetType="ListBoxItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
     </Style>
  </ListBox.ItemContainerStyle>
  <ListBox.ItemTemplate>
     <DataTemplate>
         <Grid>
             <Grid.ColumnDefinitions>
                  <ColumnDefinition Width="200"></ColumnDefinition>
                  <ColumnDefinition Width="50"></ColumnDefinition>
                  <ColumnDefinition Width="30"></ColumnDefinition>
                  <ColumnDefinition Width="50"></ColumnDefinition>
                  <ColumnDefinition Width="20"></ColumnDefinition>
             </Grid.ColumnDefinitions>
             <TextBlock VerticalAlignment="Center" Text="{Binding name}" Grid.Column="0" TextAlignment="Right"></TextBlock>
             <TextBox Grid.Column="1" Margin="5,0,0,0" Height="Auto" VerticalAlignment="Center" HorizontalAlignment="Stretch" Text="{Binding age}"></TextBox>
             <TextBlock Grid.Column="2" Text="yo" VerticalAlignment="Center" Margin="5,0,0,0"></TextBlock>
             <TextBox Grid.Column="3" Margin="5,0,0,0" Height="Auto" VerticalAlignment="Center" HorizontalAlignment="Stretch" Text="{Binding baremo}"></TextBox>
             <TextBlock Grid.Column="4" Text="€" VerticalAlignment="Center" Margin="5,0,0,0"></TextBlock>
         </Grid>
    </DataTemplate>
 </ListBox.ItemTemplate>

When I load data into People ObservableCollection everything goes right and it is shown perfectly.
The first time I select a Person, it works and it sets the property value in the VM.
The problem comes the second time I select a different "Person". The property doesn't change and... every time I select a different one, it takes a little longer (after 10 ó 20 it is MUCH LONGER).
Here is my ViewModel code:
#region People
        public const string PeoplePropertyName = "People";

        private ObservableCollection<Player> _People;

        public ObservableCollection<Player> People
        {
            get
            {
                return _People;
            }

            set
            {
                _People = value;
                RaisePropertyChanged(People);
            }
        }
        #endregion

        #region Person
        public const string PersonPropertyName = "Person";

        private Player _Person;

        public Player Person
        {
            get
            {
                return _Person;
            }

            set
            {
                _Person = value;
                RaisePropertyChanged(PersonPropertyName);
            }
        }
        #endregion

And I'm loading the People list like this:
void LoadPeople(GetPlayersEventArgs e)
{
     if (this.People == null) this.People = new ObservableCollection<Player>();

        foreach (Player Person in e.Result)
        {
            Player newPerson = new Player();
            ...
            this.People.Add(newPerson);
        }

        this.SetUnBusy();
}

Am I missing anything?? Thanks in advance.
After @Ryan question I've seen everytime I try to select another value, I get a lot of:

A first chance exception of type 'System.InvalidCastException'
  occurred in Solution

A: From what you've shared the implementation of the Person property is good. There are a few things I would recommend.
As vinod8812 suggests, change the binding mode to OneWay, or remove it as OneWay is the default:
<ListBox ItemsSource="{Binding People}" SelectedItem="{Binding Person, Mode=TwoWay}" >

Change the sequence of populating the ObservableCollection<Player> in your ViewModel:
public class ViewModel
{
    private readonly ObservableCollection<Player>();

    public ViewModel()
    {
        _People = new ObservableCollection<Player>();
    }

    public ObservableCollection<Player> People
    {
        get
        {
            return _People;
        }
    }
    /* rest of class */
}

Finally, clear out the _People collection before populating it. Otherwise you may just be adding duplicates:
void LoadPeople(GetPlayersEventArgs e)
{
    _People.Clear();

    foreach (Player Person in e.Result)
    {
        Player newPerson = new Player();
        ...
        this.People.Add(newPerson);
    }

    this.SetUnBusy();
}

Is there anything that you know is bound to the INotifyPropertyChanged.PropertyChanged event on your ViewModel? It is not clear from the code you have shared exactly what could be causing the app to slow down.

A: I'd recommend turning on the feature that will break when a CLR exception is thrown. If you're using Visual Studio 2010 or 2012, go to Debug -> Exceptions (or Ctrl-E,D by default) and under "Common Language Runtime Exceptions" make sure "Thrown" is checked on. Then re-run your solution and see if anything breaks.
Then you'll see the problem in your Person object ;)


text:
Q: How to stop admob adview? My problem is how to code adview admob comlete stop when exit on application. I have try this but i start getin error. It say adView cannot be resolved ?
My code:
      @Override
      public void onDestroy() {

           if (mp != null) {
               mp.release();
               mp = null;
              }
         super.onDestroy();
         adView.destroy();

      }

}


text:
Q: How Do I Override X-Forwarded-Proto and X-Forwarded-Port So Rels Are Properly Calculated? I'm running SDR 2.6.4 in AWS and have a situation where the rels are not being properly calculated.
I have an API Gateway proxying calls to an Application Load Balancer which forwards calls to SDR.  The AGW terminates the TLS connection, talking to the ALB over plain HTTP and non-standard port.
The URLs looks something like this:
https://apigateway:443/foo -> http://loadbalancer:9876/foo.
The rels that get calculated are a hybrid of the two: http://apigateway:9876/bar.
The cause is that the ALB fills in the X-Forwarded-Proto and X-Forwarded-Port with the values it was called with, not what the AGW was called with, and the UriComponentsBuilder uses those values to calculate the rels.
My initial thought was to create a HandlerInterceptor and force those values but quickly discovered that HttpServletRequest does not allow for mutation of HTTP headers.
Watching things in the debugger leads me to believe that once Tomcat hands off the HTTP request object, it is fully formed and Spring can't do anything to modify it.
Does anybody have any ideas on how I could add/modify the forward headers to point at the AGW and not the ALB?
Thanks,
Ron

A: As you state, you cannot modify the HttpServletRequest however you can wrap it.
https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequestWrapper.html
Via a Servlet filter then rather than via a Spring interceptor you should be able to do something like:
Wrapper:
public class MyRequestWrapper extends HttpServletRequestWrapper{

    public MyRequestWrapper(HttpServletRequest request){
        super(request);
    }

    @Override
    public String getHeaders(String name){
        if(name.equals("X-Forwarded-Proto"){
            return "xyz";
        }
        else{
            return ((HttpServletRequest)getRequest()).getHeaders(name);
        }
    }
}

Filter:
public class MyFilter implements Filter{

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        chain.doFilter(new MyRequestWrapper((HttpServletRequest)request), response);
    }
}


text:
Q: Laravel problems when sending email When I'm trying to send an email using the swiftmailer in laravel I get the folowing error: "Missing argument 2 for UsersController::{closure}()".
My code is below:
Mail::send('emails.default', array('key' => Config::get('settings.WELCOMEMAIL')), function($message, $mail, $subject = 'Welcome!')
{
    $message->to($mail)->subject($subject);
});

It's really weird though. The $mail variable contains a valid email address and I'm not using the UsersController at all in this script.
Thanks in advance

A: You must pass only the $message to the closure. Any additional variable must be passed down with the use keyword:
Mail::send('emails.default', array('key' => Config::get('settings.WELCOMEMAIL')), function($message) use($mail, $subject)
{
    $subject = empty($subject) ? 'Welcome!' : $subject;
    $message->to($mail)->subject($subject);
});


text:
Q: Apache server-status when running as proxy server We are running apache as a proxy server and have tomcat behind apache. We are using server_status module but when we try to access server_status as in https://host.com/server-status it redirects to tomcat and we get 404 error.
I am quite new to this, tried going through apache docs but unable to figure out the solution. Fyi.We have ssl enabled
Current ssl.conf settings:
  ProxyRequests     Off
  ProxyPreserveHost On

  <Proxy http://localhost:8081/*>
      Order deny,allow
      Allow from all
  </Proxy>

  ProxyPass         /  http://localhost:8081/
  ProxyPassReverse  /  http://localhost:8081/
  ProxyPassReverse   /  http://myhost:8081/

    <Location /server-status>
            SetHandler server-status
            Order deny,allow
            Deny from all
            Allow from 10.90
    </Location>

After suggested changes
 ProxyRequests     Off
 ProxyPreserveHost On

<Proxy http://localhost:8081/*>
    Order deny,allow
    Allow from all
</Proxy>

ProxyPass         /server-status !
ProxyPass         /  http://localhost:8081/
ProxyPassReverse  /  http://localhost:8081/
ProxyPassReverse   /  http://myhost:8081/

Edit 2:
Change was required to httpd.conf and I added the  ProxyPass  /server-status ! under the directive for proxy module configuration and it works.

A: You can use ! in the ProxyPass directive for proxy exceptions. Something like
ProxyPass /server-status !

ought to do it.
See apache docs for ProxyPass directive for more: http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypass , especially

The ! directive is useful in situations where you don't want to
  reverse-proxy a subdirectory, e.g.

A: I had a lot of sites and some of them had 'Redirect permanent' in it.
For some reason it doesn't work (at least for me).
I use the /server-status for monitoring so I only had to connect to it from another server inside the local LAN. So I created an extra Vhost with the local IP as the ServerName like this:
<VirtualHost *:80>
   ServerName   <<local_server_ip>>
   ServerAlias  <<local_server_ip>>
   ServerAdmin  foo@example.com

        DocumentRoot "/var/www/html"

    Options Indexes FollowSymLinks
</VirtualHost>

I'm not an expert but it worked for me.


text:
Q: Help Solve $\int \sqrt{x^{2}+x-2}\,dx$ I have this integral $\int \sqrt{x^{2}+x-2}\,dx=\int |x-1|\sqrt{\frac{x+2}{x-1}}\,dx$.
My textbook advices to use the substitution $t^{2}=\frac{x+2}{x-1}$.
Observation: This integral should be solvable without using integral of modules as it is placed before moduled function integrals chapter.
I did the substitution and i obtaind $-18\int \frac{{t^{2}}}{|(t^{2}-1)^{3}|}\,dt$ . At this point i thought that since the substitution has to be an invertible function, i may consider a restrinction to cancel the absolute value.
I checked on wolfram alpha both integrals but it gives different results. Wolfram solution:
$$\int \sqrt{(x^2 + x - 2)}\,dx = \frac14 (2 x + 1) \sqrt{(x^2 + x - 2)} - \frac98 \log\left(2 \sqrt{(x^2 + x - 2)} + 2 x + 1\right) + c$$
Any help?
The purpose of the exercise is to trasform the irrational function into a rational one and use the Hermite's equation to solve it

A: Using (after having completed the square)$$\frac{2}{3} \left(x+\frac{1}{2}\right)=\cosh(t)\implies x=\frac{3 }{2}\cosh (t)-\frac 12\implies dx=\frac{3 }{2}\sinh (t)$$
$$I=\int \sqrt{x^2+x-2}\,dx=\frac 94 \int \sinh (t) \sqrt{\sinh ^2(t)}\,dt$$ Using the double angle formula
$$\int \sinh^2 (t)\,dt=\frac{1}{4} \sinh (2 t)-\frac{1}{2}t+C$$

A: First, reduce to a simpler square root
\begin{align*}
\int \sqrt{x^2+x-2} dx &= \int \sqrt{\left(x+\frac{1}{2}\right)^2-\frac{9}{4}} \,dx = \\
&= \frac{3}{2}\int \sqrt{\frac{4}{9}\left(x+\frac{1}{2}\right)^2-1} \,dx = \\
&= \frac{3}{2}\int \sqrt{\left(\frac{2}{3}x+\frac{1}{3}\right)^2-1} \,dx = \\
&= \frac{9}{4}\int \sqrt{t^2-1} \,dt
\end{align*}
Then use this know result
\begin{align*}
I = \int \sqrt{t^2-1} \,dt &= t\sqrt{t^2-1} -\int t\frac{2t}{2\sqrt{t^2-1}} \,dt = \\
&= t\sqrt{t^2-1} -\int \frac{t^2-1+1}{\sqrt{t^2-1}} \,dt = \\
&= t\sqrt{t^2-1} -\int \sqrt{t^2-1} \,dt -\int \frac{1}{\sqrt{t^2-1}} \,dt= \\
&= t\sqrt{t^2-1} -\int \sqrt{t^2-1} \,dt -\operatorname{arccosh} t = \\
&= t\sqrt{t^2-1} -I -\operatorname{arccosh} t
\end{align*}
from which
\begin{align*}
I = \int \sqrt{t^2-1} \,dt &= \frac{1}{2}t\sqrt{t^2-1} -\frac{1}{2}\operatorname{arccosh} t +C = \\
&= \frac{1}{2}t\sqrt{t^2-1} -\frac{1}{2}\log\left(t+\sqrt{t^2-1}\right) +C
\end{align*}
Then come back to the original integral
\begin{align*}
& \int \sqrt{x^2+x-2} dx = \frac{9}{4}\int \sqrt{t^2-1} \,dt = \\
& \qquad = \frac{9}{8}t\sqrt{t^2-1} -\frac{9}{8}\log\left(t+\sqrt{t^2-1}\right) +C = \\
& \qquad = \frac{9}{8}\left(\frac{2}{3}x+\frac{1}{3}\right)\sqrt{\left(\frac{2}{3}x+\frac{1}{3}\right)^2-1} -\frac{9}{8}\log\left(\left(\frac{2}{3}x+\frac{1}{3}\right)+\sqrt{\left(\frac{2}{3}x+\frac{1}{3}\right)^2-1}\right) +C = \\
& \qquad = \frac{1}{4}(2x+1)\sqrt{x^2+x-2} -\frac{9}{8}\log\left(2x+1+2\sqrt{x^2+x-2}\right) +C \\
\end{align*}

A: Under the substitution $t=\sqrt{\frac{x+2}{x-1}}$, the two subdomains $x<-2$ and $x>1$ corresponds to $0<t<1$ and $t>1$, respectively. Thus, integrate the two cases separately
\begin{align}
\int\limits_{x<-2} \sqrt{x^{2}+x-2}\ dx=&-\int\limits_{0<t<1}\frac{18t^2}{(1-t^2)^3}dt=-\frac{9t(1+t^2)}{4(1-t^2)^2}+\frac94\tanh^{-1}t\\
\int\limits_{x>1} \sqrt{x^{2}+x-2}\ dx=&-\int\limits_{t>1}\frac{18t^2}{(t^2-1)^3}dt= \frac{9t(1+t^2)}{4(1-t^2)^2}-\frac94\coth^{-1}t
\end{align}

A: Another standard approach, set $t = x + \sqrt{x^2 +x -2}$, then
\begin{align*}
& (t -x)^2 = x^2 +x -2 \\
& t^2 -2tx = x -2 \\
& x = \frac{t^2 +2}{1 +2t} \\
& dx = 2\frac{t^2 +t -2}{(1 +2t)^2}dt \\
\end{align*}
moreover, express the square root in terms of $t$
\begin{align*}
\sqrt{x^2 +x -2} &= t - x = \\
& = t - \frac{t^2 +2}{1 +2t} = \\
& = \frac{t^2 +t -2}{1 +2t} \\
\end{align*}
Then
\begin{align*}
\int \sqrt{x^2 +x -2} \, dx &= \int \frac{t^2 +t -2}{1 +2t} \cdot 2\frac{t^2 +t -2}{(1 +2t)^2}dt = \\
&= 2\int \frac{(t^2 +t -2)^2}{(1 +2t)^3} dt = \\
&= \int \left(\frac{1}{4}t +\frac{1}{8} +\frac{81}{16}\cdot\frac{2}{(1 +2t)^3} -\frac{9}{8}\cdot\frac{2}{1 +2t} \right)dt = \\
&= \frac{1}{8}t^2 +\frac{1}{8}t -\frac{81}{32}\cdot\frac{1}{(1 +2t)^2} -\frac{9}{8}\log{(1 +2t)}  +C \\
\end{align*}
and this can be simplified, with some efforts, to
$$
\frac{1}{4}(2x+1)\sqrt{x^2+x-2} -\frac{9}{8}\log\left(2x+1+2\sqrt{x^2+x-2}\right) +C
$$

A: Well, we are trying to solve:
$$\mathcal{I}\left(x\right):=\int\sqrt{x^2+x-2}\space\text{d}x\tag1$$
First, complete the square:
$$\mathcal{I}\left(x\right)=\int\sqrt{\left(x+\frac{1}{2}\right)^2-\frac{9}{4}}\space\text{d}x\tag2$$
Substitute $\text{u}=x+\frac{1}{2}$:
$$\mathcal{I}\left(x\right)=\int\sqrt{\text{u}^2-\frac{9}{4}}\space\text{du}\tag3$$
Now, substitute $\text{u}=\frac{3\sec\left(\text{s}\right)}{2}$:
$$\mathcal{I}\left(x\right)=\frac{9}{4}\int\tan^2\left(\text{s}\right)\sec\left(\text{s}\right)\space\text{ds}\tag4$$
Now, write $\tan^2\left(\text{s}\right)=\sec^2\left(\text{s}\right)-1$:
$$\mathcal{I}\left(x\right)=\frac{9}{4}\cdot\left(\int\sec^3\left(\text{s}\right)\space\text{ds}-\int\sec\left(\text{s}\right)\space\text{ds}\right)\tag5$$
Now, you can use:

*

*The reduction formula:
$$\int\sec^\text{n}\left(\text{s}\right)\space\text{ds}=\frac{\sin\left(\text{s}\right)\sec^{\text{n}-1}\left(\text{s}\right)}{\text{n}-1}+\frac{\text{n}-2}{\text{n}-1}\int\sec^{\text{n}-2}\left(\text{s}\right)\space\text{ds}\tag6$$

*And:
$$\int\sec\left(\text{s}\right)\space\text{ds}=\ln\left|\tan\left(\text{s}\right)+\sec\left(\text{s}\right)\right|+\text{C}\tag7$$
So, you will get:
\begin{equation}
\begin{split}
\mathcal{I}\left(x\right)&=\frac{9}{4}\cdot\left(\int\sec^3\left(\text{s}\right)\space\text{ds}-\int\sec\left(\text{s}\right)\space\text{ds}\right)\\
\\
&=\frac{9}{4}\cdot\left(\frac{\sin\left(\text{s}\right)\sec^{3-1}\left(\text{s}\right)}{3-1}+\frac{3-2}{3-1}\int\sec^{3-2}\left(\text{s}\right)\space\text{ds}-\int\sec\left(\text{s}\right)\space\text{ds}\right)\\
\\
&=\frac{9}{4}\cdot\left(\frac{\sin\left(\text{s}\right)\sec^2\left(\text{s}\right)}{2}+\frac{1}{2}\int\sec\left(\text{s}\right)\space\text{ds}-\int\sec\left(\text{s}\right)\space\text{ds}\right)\\
\\
&=\frac{9}{4}\cdot\left(\frac{\sin\left(\text{s}\right)\sec^2\left(\text{s}\right)}{2}-\frac{1}{2}\int\sec\left(\text{s}\right)\space\text{ds}\right)\\
\\
&=\frac{9}{4}\cdot\left(\frac{\sin\left(\text{s}\right)\sec^2\left(\text{s}\right)}{2}-\frac{1}{2}\cdot\ln\left|\tan\left(\text{s}\right)+\sec\left(\text{s}\right)\right|+\text{C}\right)\\
\\
&=\frac{9}{8}\cdot\left(\sin\left(\text{s}\right)\sec^2\left(\text{s}\right)-\ln\left|\tan\left(\text{s}\right)+\sec\left(\text{s}\right)\right|+\text{C}\right)\\
\\
&=\frac{9\left(\sin\left(\text{s}\right)\sec^2\left(\text{s}\right)-\ln\left|\tan\left(\text{s}\right)+\sec\left(\text{s}\right)\right|\right)}{8}+\text{C}
\end{split}\tag8
\end{equation}

A: $$
\begin{aligned}
I &= \int{\sqrt{x^2 + x - 2}dx} = \int{\underbrace{\sqrt{x^2 + x - 2}}_{u}\underbrace{dx}_{dv}} = |\text{ integrating by parts }| = \\
&= x\sqrt{x^2+x-2}-\int{xd\sqrt{x^2+ x-2}} = \\
&= x\sqrt{x^2+x-2}-\int{x\frac{2x+1}{2\sqrt{x^2+x-2}}dx} = \\
&= x\sqrt{x^2+x-2}-\int{\frac{2\left(x^2+x-2\right)-\left(x-4\right)}{2\sqrt{x^2+x-2}}dx} = \\
&= x\sqrt{x^2+x-2}-\underbrace{\int{\sqrt{x^2+x-2}dx}}_{I} + \int{\frac{x-4}{2\sqrt{x^2+ x-2}}dx} \Leftrightarrow \\
2I &= x\sqrt{x^2+x-2} + \frac{1}{2}\underbrace{\int{\frac{2x+1}{2\sqrt{x^2+ x - 2}}dx}}_{\int{d\sqrt{x^2+ x-2}}=\sqrt{x^2+x-2}}-\frac{9}{4}\int{\frac{dx}{\sqrt{x^2+x-2}}} = \\
&= \left(x+\frac{1}{2}\right)\sqrt{x^2+x-2}-\frac{9}{4}\int{\frac{dx}{\sqrt{\left(x+\frac{1}{2}\right)^2-\frac{9}{4}}}} = \left|\text{ note that }dx = d\left(x+\frac{1}{2}\right)\right|=\\
&= \left(x+\frac{1}{2}\right)\sqrt{x^2+x-2}-\frac{9}{4}\int{\frac{d\left(x+\frac{1}{2}\right)}{\sqrt{\left(x+\frac{1}{2}\right)^2-\left(\frac{3}{2}\right)^2}}} = \left|\int{\frac{du}{\sqrt{u^2-a^2}}} = \ln\left|u+\sqrt{u^2-a^2}\right|\right|=\\
&= \left(x+\frac{1}{2}\right)\sqrt{x^2+x-2}-\frac{9}{4}\ln\left|\left(x+\frac{1}{2}\right)+\sqrt{\left(x+\frac{1}{2}\right)^2-\left(\frac{3}{2}\right)^2}\right| + C \Leftrightarrow \\
I &=\frac{1}{2}\left(x+\frac{1}{2}\right)\sqrt{x^2+x-2}-\frac{9}{8}\ln\left|\left(x+\frac{1}{2}\right)+\sqrt{x^2+x-2}\right| + C
\end{aligned}
$$


text:
Q: DNN file manager is showing 'no permission' error when uploading files I have created a new DotNetNuke user and gave him a new User Role.
I have linked this role to his username and gave the role permissions to upload to a certain folder on the server in the File Manager module.
For some reason, it is giving a 'No Permission' error when he/she tries to upload a file. The DNN version is 9.1.0

A: First of all, I recomend you to upgrade DNN to last stable version (9.3.2). And check that the folder (and subfolders) containing DNN have the required permissions.
Now, it's the moment to check inside DNN: sometimes folders lose their permissions; go to file manager, click on root folder and make sure it has the proper permissions, then propagate them to subfolders.
Let us know if you get tid of errors.


text:
Q: Selecting data week wise with (week = current timestamp - 7days) and so on in db2 I am selecting data grouped on the basis of week.
My data contains tickets raised week wise but the week should be current timestamp - 7 days.
So I need to calculate the week not from the start but from the end and then move backwards till the start date i.e. 01-09-2018
Following is the Example of how I need the weeks calculated :
PreviousWeek :      Current Timestamp - 7 days
PreviousWeek - 1:   PreviousWeek -  7 days
PreviousWeek - 2 : (PreviousWeek - 1) - 7 days
and so on.
Complete required data required is :
  Week   TicketCount
  11         100
  16         100
  21         100
  26         97
  31         100
   1         77
   6         72

I am stuck at this for couple of days any clue to achieve this would be very helpful.
Sample data:
  PROBLEMSINCE          STATUS        INITIATOR_DEPARTMENT
  2018-12-20 19:36:34   CLOSED          MWP-PMT-NR
  2018-12-21 12:35:57   CLOSED          MWP-PMT-NR
  2018-12-19 19:00:00   CLOSED          MWP-PMT-NR
 2018-12-19 22:00:00    CLOSED          MWP-PMT-NR
 2018-12-20 21:00:00    CLOSED          MWP-PMT-NR
 2018-12-20 22:00:00    CLOSED         MWP-PMT-NR
 2018-12-13 16:41:18    CLOSE           MWP-PMT-NR
 2017-12-21 10:30:24    CLOSED          MWP-PMT-NR
 2017-12-29 21:22:37    CLOSED          MWP-PMT-NR
 2017-12-29 21:43:42    CLOSED          MWP-PMT-NR
 2018-01-01 13:58:14    CLOSED          MWP-PMT-NR

A: What's the 01-09-2018 date? It's better to use ISO format. Is this Sep 1-st (2018-09-01) or Jan 9-th (2018-01-09)?
Your sample data absolutely don't match the result you provided.
Run the following statement as is.
with t(week_num, ts_start, ts_end) as (
values (1, current timestamp - 7 days, current timestamp)
  union all
select week_num+1, ts_start - 7 days, ts_end - 7 days
from t
where ts_start > date('2018-09-01')
)
select *
from t
order by week_num

Is this expected week numeration?
If not, then update your question with exact expected week numeration, and matched sample data and result.

A: Depending on your definition of previous week, you can use one of the following SQLs.
SQL 1:

select week1 , count(*)
from
( select  int ( ( days (current date) - days(PROBLEMSINCE) ) / 7 ) as week1
 from tickets_table
 where PROBLEMSINCE >= '2018-09-01 00:00:00' ) a
group by week1
order by 2 desc

SQL 2:

select week1 , count(*)
from
( select  timestampdiff ( 32 , char ( current timestamp - PROBLEMSINCE ) ) as week1
 from tickets_table
 where PROBLEMSINCE >= '2018-09-01 00:00:00' ) a
group by week1
order by 2 desc


text:
Q: How can you post a status to Facebook without requiring API login? I'd like to set up a web tool with the ability to share a message on Twitter and Facebook, but I'm not sure how to make a post to Facebook directly. I'd like an interface something like Twitter's standard tweet button, or even just a link directly into Facebook with the status message field pre-populated, but I don't want to require anyone to authorize the app with Facebook if I can help it. Is there a way to do this?

A: As of July 12th message parameter is ignored: http://developers.facebook.com/docs/reference/dialogs/feed/
So there is no way to pre-fill the message text


text:
Q: How to open new activity with different name on app bar in navigation drawer When click on gallery of navigation drawer a new activity whose name is gallery on app bar has to be open with same hamburger icon and all the stuff that are on main app bar.

A: Check this link: http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
I hope this help you...


text:
Q: get_item in Lambda to read one item from dynamodb table having issues I have a simple table with agentId (PK) and agentRole(SK). I am trying read one item from that table. Using boto3 client
I am getting syntax error on print statement.
   import json
   import boto3

   client = boto3.client('dynamodb')

   def lambda_handler(event, context):
       response = client.get_item(
            TableName='USBCallCenterTable',
            Key={
                'agentId': {
                    'N': str(1)
                 },
                'agentRole':{
                     'S': 'Manager'
                 }
             }

       )
      print(response)

"errorMessage": "name 'response' is not defined",
"errorType": "NameError",
"requestId": "",

A: Print is not an argument of get_item. Try to put the print outside get_item. I think it should solve the problem.


text:
Q: Image won't move in Lua LÖVE game I am writting a game in Lua LÖVE framework, for the LudumDare26. I can't seem to figure out why my "player" won't move when I press WASD.
function love.draw()

    playerX = 10
    playerY = 10

    if love.keyboard.isDown ("w") then
        playerY = playerY - 1
    elseif love.keyboard.isDown ("s") then
        playerY = playerY + 1
    elseif love.keyboard.isDown ("a") then
        playerX = playerX - 1
    elseif love.keyboard.isDown ("d") then
        playerX = playerX + 1
    end

    local x = love.mouse.getX()
    local y = love.mouse.getY()

    love.graphics.setColor(0, 200, 255, 100)
    love.graphics.rectangle("fill", 0, 0, 800, 300)

    love.graphics.setColor(255, 255, 255, 255)
    love.graphics.rectangle("fill", xCloud, 128, 128, 50)

    love.graphics.setColor(50, 160, 80, 255)
    love.graphics.rectangle("fill", 0, 300, 800, 300)

    love.graphics.setColor(255, 0, 0, 255)
    love.graphics.draw(corsair, x - 16, y - 16, 0, 1, 1, 0, 0)

    love.graphics.draw(player, playerX, playerY)

    love.graphics.line(playerX, playerY, x, y)
end

A: Take these lines out of love.draw() method:
playerX = 10
playerY = 10


text:
Q: Angular 6 receive input from another component for Karma unit test So I'm trying to write Karma tests for a variety of components, and many of them receive input from a parent component. To try to illustrate how tests work, I've created a sample group of 5 different files as a tutorial of sorts: "random.test.component.child.html", "random.test.component.child.ts", "random.test.component.html", "random.test.component.ts", and "random.test.file.spec.ts".
I want to receive input from one component and set the value to the variable of the other ([variable]="value"). I've already tried accessing the variable that should be set directly via the HTML file's input to no avail.
Here are the relevant parts of the files:
random.test.component.child.html (variableThatStoresTheDataThatTheChildReceives shows up as blank unless manually set)

Also, here's a thing that should load properly: {{variableThatStoresTheDataThatTheChildReceives}}

random.test.component.child.ts
@Input() variableThatStoresTheDataThatTheChildReceives: any;

random.test.component.html

<random-test-child [variableThatStoresTheDataThatTheChildReceives]="dataFromTheParentToTheChild"></random-test-child>

random.test.component.ts
public dataFromTheParentToTheChild:any = "This is a test.";

random.test.file.spec.ts (inside a describe statement)
it('Testing if receiving input from one component to another works properly', () => {

        childFixture.whenStable().then(() => {
            childFixture.detectChanges();
expect(childComponent.variableThatStoresTheDataThatTheChildReceives).toEqual("This is a test.");
        });
});

I'd expect to have the input received from the HTML component result in childComponent.variableThatStoresTheDataThatTheChildReceives equaling "This is a test.", but instead I get "undefined". I know you can set the input manually like so:
childComponent.variableThatWillHaveTheInputHardCodedKindOf = 'Manual Text';

but I'm trying to run the test using the data that gets passed to the component when it's not being tested.
Is there a way to do this?

A: You should use By.directive to get hold of your child component. Setup your test case like this:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { RandomTestComponent } from './random-test.component';
import { RandomTestChildComponent } from '../random-test-child/random-test-child.component';
import { By } from '@angular/platform-browser';

describe('RandomTestComponent', () => {
  let component: RandomTestComponent;
  let fixture: ComponentFixture<RandomTestComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ RandomTestComponent, RandomTestChildComponent ],
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(RandomTestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('Testing if receiving input from one component to another works properly', () => {

    const childComp: RandomTestChildComponent = fixture.debugElement.query(By.directive(RandomTestChildComponent)).componentInstance;
    expect(childComp).toBeTruthy();
    expect(childComp.variableThatStoresTheDataThatTheChildReceives).toEqual('This is a test.');
  });

});


text:
Q: How to use relationship ajax with laravel? In Laravel, for relationship with ajax in the file blade.php is as follow, for example:
{{ foreach($schhols as $school) }}
    {{ $school->user->name }}
    {{ $school->user->address}}
    {{ $school->user->country}}
{{ endforeach }}

But in ajax with laravel how do it?
function load() {
    $.get('/read', function (data){
        $('#data').html("");
        $.each(data, function (key, val) {
            $('#data').append("
"+
                ""+val.id+"	"+
                ""+val.name+"	"+
                ""+val.address+"	"+
                ""+val.country+"	"+
                ""+
                    "<button class='btn btn-warning' id='edit' data-id="+val.id+">Edit</button>"+
                    "<button class='btn btn-danger' id='delete' data-id="+val.id+">Delete</button>"
                +"	"+
            +"
")
        });
    });
}

Will this happen?
""+val.user.name+"	"+
""+val.user.address+"	"+
""+val.user.country+"	"+

A: in your controller
public function read(Request $request){
  $schhols = Schhol::get();

  // if ajax request return response in json

  if($request->ajax()){
     return response()->json($schhols);
  }else{

   // else return data to view

     return view('schhol_view',compact('schhols'))
   }
}

if your sending ajax request from frontend :


text:
Q: Javafx table loads the correct number of rows, but loads duplicate data. Am I missing something? My code should load a customer tableview in javafx via loadCusotmerTable() from MYSQL database with JDBC through the CustomerDOA.findAll() method. The findAll() method returns an ObservableList that should display the customers.
The Table output is currently displaying the correct number of rows for each customer in the Observable list, but it only displays the data from the last entry in the ObservableList. Is there something missing in my code to load the ObservableList<Customer> Customers correctly?
loadCustomerTable
package Controller;

import Model.Customer;
import Model.DAO.CustomerDAO;
import Model.DAO.UserDAO;
import Model.DBConnection;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.ResourceBundle;
import java.util.Set;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

public class CustomerViewController implements Initializable {

    @FXML private TextField TextFieldCustomerID;
    @FXML private TextField TextFieldCustomerName;

    @FXML private Button ButtonGoBack;
    @FXML private Button ButtonAddModify;
    @FXML private Button ButtonRemove;
    @FXML private Button ButtonCancel;

    @FXML private MenuButton MenuButtonAddress;

    @FXML private MenuButton MenuButtonActive;
    @FXML private MenuItem MenuActiveItemActive;
    @FXML private MenuItem MenuActiveItemInactive;

    @FXML private TableView<Customer> TableViewCustomer;
    @FXML private TableColumn<Customer, String> TableCustomerColumnCustomerID;
    @FXML private TableColumn<Customer, String> TableCustomerColumnCustomerName;
    @FXML private TableColumn<Customer, String> TableCustomerColumnAddress;
    @FXML private TableColumn<Customer, String> TableCustomerColumnActive;

    private int addressId = 1;
    private int Active = 1;
    private int userId = 1;

    private boolean isCustomerSelected = true;
    private ObservableList<Customer> Customers = FXCollections.observableArrayList();

    // .......

    public void loadCustomerTable(){

        CustomerDAO customerDAO = new CustomerDAO(DBConnection.getConnection());
        ObservableList<Customer> Customers = customerDAO.findAll();

        TableCustomerColumnCustomerID.setCellValueFactory(new PropertyValueFactory<>("customerId"));
        TableCustomerColumnCustomerName.setCellValueFactory(new PropertyValueFactory<>("customerName"));
        TableCustomerColumnAddress.setCellValueFactory(new PropertyValueFactory<>("addressId"));
        TableCustomerColumnActive.setCellValueFactory(new PropertyValueFactory<>("active"));

        TableViewCustomer.setItems(Customers);
    }

CustomerDAO.findAll()
 public ObservableList<Customer> findAll() {
        ObservableList<Customer> Customers = FXCollections.observableArrayList();
        Customer customer = new Customer();

        try(PreparedStatement statement = this.connection.prepareStatement(GET_ALL)){

            ResultSet resultSet = statement.executeQuery();
            int i =0;
            while(resultSet.next()){

                customer.setCustomerId(resultSet.getInt("customerId"));
                customer.setCustomerName(resultSet.getString("customerName"));
                customer.setAddressId(resultSet.getInt("addressId"));
                customer.setActive(resultSet.getInt("active"));
                customer.setCreateDate(resultSet.getTimestamp("createDate"));
                customer.setLastUpdate(resultSet.getTimestamp("lastUpdate"));
                customer.setCreatedBy(resultSet.getString("createdBy"));
                customer.setLastUpdateBy(resultSet.getString("lastUpdateBy"));

                Customers.add(customer);
                System.out.println(Customers.get(i).getCustomerName());
                i++;
            }

        }catch(SQLException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        return Customers;
    }

Customer Class
import Utils.DataTransferObject;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import javafx.beans.property.IntegerProperty;

public class Customer implements DataTransferObject {
    private int customerId;
    private String customerName; //varchar 45
    private int addressId;
    private int active; // tiny int 1
    private LocalDateTime createDate;
    private LocalDateTime  lastUpdate;
    private String createdBy;
    private String lastUpdateBy;

    @Override
    public long getId() {
        return customerId;
    }

    public int getCustomerId() {
        return customerId;
    }

    public void setCustomerId(int customerId) {
        this.customerId = customerId;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public int getAddressId() {
        return addressId;
    }

    public void setAddressId(int addressId) {
        this.addressId = addressId;
    }

    public int getActive() {
        return active;
    }

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

    public LocalDateTime getCreateDate() {
        return createDate;
    }

    public void setCreateDate(LocalDateTime createDate) {
        this.createDate = createDate;
    }

    public void setCreateDate(Timestamp createDate) {

        this.createDate = createDate.toLocalDateTime();

    }

    public LocalDateTime getLastUpdate() {
        return lastUpdate;
    }

    public void setLastUpdate(LocalDateTime lastUpdate) {
        this.lastUpdate = lastUpdate;
    }

    public void setLastUpdate(Timestamp lastUpdate) {
        this.lastUpdate = lastUpdate.toLocalDateTime();
    }

    public String getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    public String getLastUpdateBy() {
        return lastUpdateBy;
    }

    public void setLastUpdateBy(String lastUpdateBy) {
        this.lastUpdateBy = lastUpdateBy;
    }

}

A: Your CustomerDAO.findAll() method repeatedly adds the same Customer instance to the table (changing the data in that single object every time). Consequently, the table contains multiple references to the same object.
The memory picture looks like:

Since there's only one Customer object, there's only one customerId, one customerName, etc, and each element of the list refers to the same value.
Instead, create a new Customer every time, and add it to the list. Then the memory picture looks like:

public ObservableList<Customer> findAll() {
    ObservableList<Customer> customers = FXCollections.observableArrayList();

    try(PreparedStatement statement = this.connection.prepareStatement(GET_ALL)){

        ResultSet resultSet = statement.executeQuery();
        int i =0;
        while(resultSet.next()){

            // This line moved inside the loop, to create a new
            // object on each iteration:
            Customer customer = new Customer();

            customer.setCustomerId(resultSet.getInt("customerId"));
            customer.setCustomerName(resultSet.getString("customerName"));
            customer.setAddressId(resultSet.getInt("addressId"));
            customer.setActive(resultSet.getInt("active"));
            customer.setCreateDate(resultSet.getTimestamp("createDate"));
            customer.setLastUpdate(resultSet.getTimestamp("lastUpdate"));
            customer.setCreatedBy(resultSet.getString("createdBy"));
            customer.setLastUpdateBy(resultSet.getString("lastUpdateBy"));

            customers.add(customer);
            System.out.println(customers.get(i).getCustomerName());
            i++;
        }

    }catch(SQLException e){
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    return customers;
}


text:
Q: UniqueElement Counter Java I just started a Java Data Structures summer class.  One of the problems assigned is instead of counting all the elements in the array, I am to find each unique element.
numUnique(new double[] { 11, 11, 11, 11, 22, 33, 44, 44, 44, 44, 44, 55, 55, 66, 77, 88, 88 })==8

numUnique(new double[] { 11, 22, 33, 44, 55, 66, 77, 88})==8

In the first example above 11 is listed 4 times, 22 once, 33 once, 44 5 times, 66 once, 77 once, and 88 twice.  there are 17 elements in the array but there are only 8 different numbers.  the two examples give the same output of 8 and thats what number I'm supposed to find.

A: There's a nice easy way to do this in Java 8 without any intermediate collections:
List<Double> unique = Arrays.stream(array).distinct()
    .collect(Collectors.toList());

or replace the collector with count() if you just want the number of unique elements.

A: Two straightforward ways to do this are adding the array to a set (which will remove duplicates by definition), or adding each number to a hashmap using the number as key.
Using a set:
double[] input = new double[] {11, 11, 11, 11, 22, 33, 44, 44, 44, 44, 44, 55, 55, 66, 77, 88, 88};
Set<Double> set = new HashSet<Double>(Arrays.asList(input));
System.out.println("There were " + set.size() + " unique numbers in the set.");

Using a map:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i=0; i < double.length; ++i) {
    map.put(i, null);
}
System.out.println("There were " + map.keySet.size() + " unique numbers in the set.");

A: One of the easiest way for tracking unique items in Java is to use the HashMap implementation.
The API you will need are: containsKey() and put(). Have read at the API documentation below.
https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Example implementation:
import java.util.HashMap;
import java.util.Map;

public class test {
    public static void main(String[] args) {
        double[] value1 = new double[] { 11, 11, 11, 11, 22, 33, 44, 44, 44, 44, 44, 55, 55, 66, 77, 88, 88 };
        Map<Double, Integer> numberTracker = new HashMap<>();

        for(Double value : value1) {
            if (!numberTracker.containsKey(value)) {
                numberTracker.put(value, /*dummy value=*/1);
            }
        }

        for (Map.Entry<Double,Integer> entry : numberTracker.entrySet()) {
            System.out.println(entry.getKey());
        }
    }
}

Note: As you have got a double array therefore the output is going to be something in double data type. That is, it will be something like;
[ 33.0, 66.0, 77.0, 11.0... ]
You can solve the double type problem by either changing your array to be on Integer type or find a way to convert your double value into integer.
As this is supposed to be an assignment question, I'll leave the last bit to you.


text:
Q: How to disable suspend on Ubuntu 20.04 (systemd) via CLI I have a laptop that has been installed with ubuntu 20.04 that is being used as a server. Thus I want it to never suspend.
By default it automatically suspends when the lid is closed.
As I can only access it via ssh (and there is no X installed anyway) I need to disable it via the CLI.
Multiple sites suggest using
sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target
This does indeed stop the laptop from suspending while the lid is closed, but results in systemd-logind consuming 100% cpu and continuously logging the following: (multiple times per second)
 systemd-logind[514]: Suspending...
 systemd-logind[514]: Unit suspend.target is masked, refusing operation.
 systemd-logind[514]: Failed to execute suspend operation: Permission denied

Can anyone tell me how to properly disable suspending?

A: After some more searching, I found the correct answer:
In /etc/systemd/logind.conf add the following lines at the bottom:
HandleSuspendKey=ignore
HandleHibernateKey=ignore
HandleLidSwitch=ignore
HandleLidSwitchExternalPower=ignore
HandleLidSwitchDocked=ignore

and run
systemctl restart systemd-logind
to activate the new settings.


text:
Q: How to get text filed value in ajax? I have a table with dynamic data from database, each row consist of a text filed and 2 link (accept or reject). then if user clicks on any of these link, the row will disappear and the rest of the rows are only visible in table.
I get ID of each row with ajax by clicking on each link, however I also need to get the text-field value.
how can I get it?
I need to have in ajax cause after getting value I need to insert in database with php+sql.
this is my ajax part for link:
 $('a.accept').click(function(d) {
    d.preventDefault();
    var parent = $(this).parent();
    $.ajax({
      type: 'get',
      url: 'Test.php',
      data: 'ajax=1&accept=' + parent.attr('id').replace('record-',''),
      beforeSend: function() {
        parent.animate({'backgroundColor':'#fb6c6c'},300);
      },
      success: function() {
        parent.slideUp(300,function() {
          parent.remove();
        });
      }
    });
  });

});

how can I include text filed value in it?
please comment me which I'm really in need to solve it,
Thanks

A: You can add manually your text to the GET request.
(snippet)
data: 'ajax=1&accept=' + parent.attr('id').replace('record-','') + '&text=VALUE',

Substitute text with the name you want to be received in PHP. Substitute VALUE with the text entered on the page that you want to grab - and don't forget to encode the value.

A: You will need the name of id of the textfield first. Then you could do something like this:
var textboxvalue = $('name or id of textfield').val();

Then you will need to append this value to your data string:
data: 'ajax=1&textvalue='+textboxvalue+'accept=' + parent.attr('id').replace('record-',''),

Then you can use $_GET['textvalue']; to get the value of textbox.

A: Use following and you're good to go. Also you had extra '});' at the end line of JS fragment. I had it removed. But make sure you give id to text fields in following pattern : text-fld-RECORD_ID where RECORD_ID is the ID of the record.

$('a.accept').click(function(d) {
    d.preventDefault();
    var parent = $(this).parent();
    var id = parent.attr('id').replace('record-','');
    //make sure that text field has ID in pattern 'text-fld-RECORD_ID'
    var text_fld = $('#text-fld-'+id).val();
    $.ajax({
      type: 'post', // I suggest using post; get will be harmful in such occasions
      url: 'Test.php',
      data: {ajax:1,accept:id,text:text_fld},
      beforeSend: function() {
        parent.animate({'backgroundColor':'#fb6c6c'},300);
      },
      success: function() {
        parent.slideUp(300,function() {
          parent.remove();
        });
      }
    });
});