text:
Q: ajax reload in angular js I have dropdown which generates items from json.
`generalService.getUrlData('get_data')
        .then(function(data){
            $scope.names = data.data;
            for (var i=0; i < $scope.names.length; i++) {
                var compn = $scope.names[i].NAME;
                $scope.compname.push(compn);
            }
    });`

my question is when i entered a new data to db using typeahed combo box the newly entered data is not populating in the dropdown. It is populating after the page is reloaded. How to reload the ajax call when submit button is clicked, so that the newly entered item appears in dropdown without reloading the page.I hope you understood my question.

A: you need to invoke new http request if you want to load new data from server to client.
if your data just entered from consumer, you can avoid new request by simulating serverside update

A: Call the getUrlData once the save new data API call is success.
Eg:
function getAllUrlData () {
  generalService.getUrlData('get_data')
    .then(function(data){
        $scope.names = data.data;
        for (var i=0; i < $scope.names.length; i++) {
            var compn = $scope.names[i].NAME;
            $scope.compname.push(compn);
        }
  });
}

function save newData (new_data) {
   generalService.veNewasUrlData('get_data')
    .then(function(data){
       getAllUrlData()   // fecth all data again when save data is success
    });
}

OR
Don't call the getAllUrlData function again. Just push the new data to $scope.compname when you are saving the new data.
$scope.compname.push(newData) // this will automatically come once reload. So no issues with temporary push

A: When you entered a new data to db using typeahed combo box. You need to trigger again dropdown getdata api. or use $route.reload() after new data to db by typeahed combo box but, It will call all on-fly functions requests.


text:
Q: Inheritance and interfaces I want to express the extends behavior many languages possess.
In my Go Code I have a few structs that look like so:
type Base struct {
        // Some fields
}

type BaseExtender struct {
        Base
        // Unique fields
}

type AnotherBaseExtender struct {
        Base
        // Unique fields
}

Now, I want to write a function that takes any Base since I only need it's "similar fields".
func UseTheBase(b Base) {
        testVal := b.thingICareAbout
}

However, this doesn't work. I've done some digging into interface and thought I could do something like:
type Base interface {
        // Some fields
}

Except it appears that Go automatically infers interfaces by method implementation. Is there a way to mimic this behavior so I can pass any Base into my function, and not have to implement some nop method on the Base struct and all of it's extenders?
Thanks!

A: Base implies you want inheritance in Go, Go deliberately eschews inheritance, don't try to recreate it. You can embed types but think of this as embedding behaviour, not just data (as you might be tempted to in an inheriting language).
You're on the right lines with your solution but need public methods and yes interfaces are defined in terms of methods. Just define the interface where you call it as:
type Doer interface {
DoSomething()
}

...
func doit(d Doer) {
   d.DoSomething()
}

doit doesn't care what its argument is as long as it has a DoSomething method. Obviously this is a trivial example and there's no point in it, but if you need to override something in all extenders, ask yourself why Base exists, if it is just to add some fields, that's probably not enough reason for a separate type, just add the fields where you need them.
Try to avoid the vast taxonomies of types that you might construct in other languages.

A: To add on, a common pattern I use is:
type Base interface {
    SomeFunction() int
}

type SimpleBaseImpl struct {
    // Unique fields
}

func (s SimpleBaseImpl) SomeFunction() int {
    return 0
}

type SomethingMoreComplicated struct {
    SimpleBaseImpl
    // Unique fields
}

Then you could treat SomethingMoreComplicated as "type" Base – but again, its important to note the golang preference for composition (shown here) over inheritance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change change / to - in yii2 url for specific action I'm rewriting wordpress site to yii2.
and I have to keep previous posts urls for some reasons!
They are somethings like that
https://example.com/blog-thenameofpost

So I created a Blog controller and I have this link in this way
https://example.com/blog/view?id=thenameofpost

I don't know how can I write a urlManager rule for doing that.
I just add this rules
    '<controller:\w+>/<id:\d+>' => '<controller>/view',
    '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
    '<controller:\w+>/<action:\w+>' => '<controller>/<action>',

and now  this link
https://example.com/blog/view?id=thenameofpost
 opens with something like it:
https://example.com/blog/thenameofpost
Are there any rules to open link with some thing like it https://example.com/blog/thenameofpost ?

A: If you want to create a rule for https://example.com/blog-thenameofpost you could add the following rule.
'blog-<id>' => 'blog/view',

The left part is what you will actually see in your address bar. You can use < > to indicate a parameter. So this rule will match anything that starts with blog- and then consider the part after that as the id param. The right part is where this request should be routed to. So this request will end up in the BlogController and call actionView($id), where $id will be set to the <id> part; thenameofpost in the case of the example URL.
The rule for https://example.com/blog/thenameofpost would be
'blog/<id>' => 'blog/view'

Additional info:
In the param part (left side) you can add additional info for matching the param. So <id:\d+> will only match digits, because of de \d+ part. For more info read the docs: http://www.yiiframework.com/doc-2.0/yii-web-urlmanager.html#$rules-detail


text:
Q: Uncaught TypeError: (sales_total + sales_vat).toFixed is not a function" Every time I input a quantity it will always give me an error:  (sales_total + sales_vat).toFixed is not a function. Can you please check my code? Here's my full code: https://jsfiddle.net/yv6zks1g/1/
Thanks!
$('#sales_qty').keyup(function(){
    var qty = parseFloat($('#sales_qty').val()) || 0;
    var sub_total = parseFloat($('#sales_sub_total').val()) || 0;
    var vat = 0.12;

    var sales_total = $('#sales_total').val((qty * sub_total).toFixed(2)).val();

    var sales_vat = $('#sales_vat').val((sales_total * vat).toFixed(2));

    $('#sales_amount_due').val((sales_total + sales_vat).toFixed(2));
});

A: The issue is because sales_total is a string, as returned from val(), and sales_vat is a jQuery object. Presumably the latter is missing the call to val(), but would then have the same issue as the preceding variable.
To fix this, add the val() call on #sales_vat to set the variable to the string, then convert them to Number types before making the #sales_amount_due calculation. Try this:

$('#sales_qty').keyup(function() {
  var qty = parseFloat($('#sales_qty').val()) || 0;
  var sub_total = parseFloat($('#sales_sub_total').val()) || 0;
  var vat = 0.12;

  var sales_total = $('#sales_total').val((qty * sub_total).toFixed(2)).val();
  var sales_vat = $('#sales_vat').val((sales_total * vat).toFixed(2)).val();

  $('#sales_amount_due').val((+sales_total + +sales_vat).toFixed(2));
});

Qty: <input type="text" id="sales_qty" />

Sub total: <input type="text" id="sales_sub_total" value="50" />

Total: <input type="text" id="sales_total" />

VAT: <input type="text" id="sales_vat" />

Due: <input type="text" id="sales_amount_due" value="1.2" />

Better still would be to perform the calculations and store them in variables instead of the DOM elements. That way you're not wasting time by calculating a value as a number, storing it as a string, retrieving it as a string then converting it back to a number again. Try this:

$('#sales_qty').keyup(function() {
  var qty = parseFloat($('#sales_qty').val()) || 0;
  var sub_total = parseFloat($('#sales_sub_total').val()) || 0;
  var vat = 0.12;

  var sales_total = qty * sub_total;
  var sales_vat = sales_total * vat;
  var sales_due = sales_total + sales_vat;

  $('#sales_total').val(sales_total.toFixed(2))
  $('#sales_vat').val(sales_vat.toFixed(2));
  $('#sales_amount_due').val(sales_due.toFixed(2));
});

Qty: <input type="text" id="sales_qty" />

Sub total: <input type="text" id="sales_sub_total" value="50" />

Total: <input type="text" id="sales_total" />

VAT: <input type="text" id="sales_vat" />

Due: <input type="text" id="sales_amount_due" value="1.2" />


text:
Q: Shaka Player: ignore empty AdaptationSet I'm trying to play DASH stream in Shaka Player.
Sometimes the stream doesn't have an audio source and its manifest file contains an empty AdaptationSet entry.
In this case Shaka Player returns the manifest parsing error:
| DASH_EMPTY_ADAPTATION_SET | 4003 | number |  The DASH Manifest contained an AdaptationSet with no Representations. |
Is it possible to ignore this error somehow and play the video without audio source?
Example of manifest file:
<?xml version="1.0" encoding="utf-8"?>
<MPD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="urn:mpeg:dash:schema:mpd:2011"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xsi:schemaLocation="urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd"
    profiles="urn:mpeg:dash:profile:isoff-live:2011"
    type="dynamic"
    minimumUpdatePeriod="PT4S"
    suggestedPresentationDelay="PT4S"
    availabilityStartTime="2019-06-24T13:38:04Z"
    publishTime="2019-06-24T13:38:34Z"
    timeShiftBufferDepth="PT14.9S"
    minBufferTime="PT9.9S">
    <ProgramInformation>
        <Title>Media Presentation</Title>
    </ProgramInformation>
    <Period id="0" start="PT0.0S">
        <AdaptationSet id="0" contentType="video" segmentAlignment="true" bitstreamSwitching="true">
            <Representation id="0" mimeType="video/mp4" codecs="avc1.640028" bandwidth="2000000" width="1920" height="1080" frameRate="20/1">
                <SegmentTemplate timescale="10240" initialization="init-stream$RepresentationID$.m4s" media="chunk-stream$RepresentationID$-$Number%05d$.m4s" startNumber="5">
                    <SegmentTimeline>
                        <S t="201697" d="51190" r="2" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="1" contentType="audio" segmentAlignment="true" bitstreamSwitching="true">
        </AdaptationSet>
    </Period>
</MPD>


text:
Q: Login to instagram using python I am trying to login to instagram.Here is my code
from bs4 import BeautifulSoup
from requests import *
payload = {
    'action': 'login',
    'username': 'name',
    'password': 'pass'
}

with session() as c:
    c.post('https://www.instagram.com/login.php', data=payload)
    response = c.get('https://www.instagram.com/accounts/edit/')
    print(response.headers)
    print(response.text)

unfortunately it doesn't seem to log me in. I get:
lt-ie8 lt-ie7 not-logged-in client-root

Any solutions would be much appreciated. Thanks.

A: you can get idea to implement this from here
Logging to Instagram using Python requests
my code for login to instagram
import pdb
from selenium import webdriver

driver = webdriver.PhantomJS()
driver.get('https://www.instagram.com/accounts/login/')
dom = driver.find_element_by_xpath('//*')

pdb.set_trace()
username = dom.find_element_by_name('username')
password = dom.find_element_by_name('password')
login_button = dom.find_element_by_xpath('//*[@class="_qv64e _gexxb _4tgw8 _njrw0"]')

username.clear()
password.clear()
username.send_keys('your username')
password.send_keys('your password')

login_button.click()
driver.get('https://www.instagram.com/accounts/login')

if 'logged-in' in driver.page_source:
    print 'Logged in'

A: You would need an API key in order to make calls to the Instagram API, also I don't think you can directly log in someone like that.

A: I would recomend you to use Selenium and a PhantomJS webdriver.


text:
Q: Ease of writing custom rules in (Java) static code analysis tools At present I am working for a group where source code (Java) for multiple projects have to be analysed by static code analysic tools
But I would like to write custom rules that I can add to the existing set of rules provided by the tool (the rules would involve mostly regular expressions matching for text/string within the source code).
Especially keeping the perspective that I should be able to easily write/add my own custom rules that can be used alongwith the existing list of rules of the tool.
Can anyone please suggest which tool (or combination of tools) among the below given list should I use ?

*

*PMD

*Checkstyle

*Findbugs

Edited : Thanks Ira for the direction. I am looking for static code analysis tools to be used along with Sonar. I hope now the question is clear.

A: Here are some tutorials on setting up custom rules on PMD, I use PMD integrated with Maven myself in addition to sonar.
http://www.techtraits.com/Programming/2011/10/31/writting-pretty-code-with-pmd/
http://www.techtraits.com/Programming/2011/11/05/custom-pmd-rules-using-xpath/
http://blog.code-cop.org/2010/05/custom-pmd-rules.html

A: I have used all of these tools for many years, and I would recommend them all!
Checkstyle, Findbugs, and PMD all integrate very well with sonar, all three allow the creation of custom checks, and all three allow those custom checks to be used in sonar.
PMD probably makes it easiest to create new checks, but it is also slightly limited compared to the others. Findbugs needs .class files, but since the whole thing usually integrates into some form of automated build process, that's no problem. Checkstyle is the tool that I use most heavily, because it is both light-weight and powerful.
Each of the tools has some checks that the others don't have. Especially Findbugs has some quite sophisticated checks that suprised me in a positive way several times. By combining the advantages of all three tools in sonar, you can build a powerful static code analysis system that really helps your development team.

A: I use FindBugs and PMD integrated with Sonar.
I discourage the usage of CheckStyke since introduce a formatting style which is not pleasing to all developers .
FundBugs is very complete and hepled me to find a lot of bugs. I suggest to integrate FindBugs with a continuous integration tool such as hudson (http://www.eclipse.org/hudson/).
Hudson supports FindBugs, CheckStyle and PMD both.


text:
Q: Is a url query parameter valid if it has no value? Is a url like http://example.com/foo?bar valid?
I'm looking for a link to something official that says one way or the other.  A simple yes/no answer or anecdotal evidence won't cut it.

A: Yes, it is valid.
If one simply want to check if the parameter exists or not, this is one way to do so.

A: URI Spec
The only relevant part of the URI spec is to know everything between the first ? and the first # fits the spec's definition of a query. It can include any characters such as [:/.?]. This means that a query string such as ?bar, or ?ten+green+apples is valid.
Find the RFC 3986 here
HTML Spec
isindex is not meaningfully HTML5.
It's provided deprecated for use as the first element in a form only, and submits without a name.

If the entry's name is "isindex", its type is "text", and this is the first entry in the form data set, then append the value to result and skip the rest of the substeps for this entry, moving on to the next entry, if any, or the next step in the overall algorithm otherwise.
The isindex flag is for legacy use only. Forms in conforming HTML documents will not generate payloads that need to be decoded with this flag set.

The last time isindex was supported was HTML3. It's use in HTML5 is to provide easier backwards compatibility.
Support in libraries
Support in libraries for this format of URI varies however some libraries do provide legacy support to ease use of isindex.
Perl URI.pm (special support)
Some libraries like Perl's URI provide methods of parsing these kind of structures
$uri->query_keywords
$uri->query_keywords( $keywords, ... )
$uri->query_keywords( \@keywords )
Sets and returns query components that use the keywords separated by "+" format.

Node.js url (no special support)
As another far more frequent example, node.js takes the normal route and eases parsing as either

*

*A string

*or, an object of keys and values (using parseQueryString)

Most other URI-parsing APIs following something similar to this.

*

*PHP parse_url, follows as similar implementation but only returns the string for the query. Parsing into an object of k=>v requires parse_string()

A: It is valid: see Wikipedia, RFC 1738 (3.3. HTTP), RFC 3986 (3.  Syntax Components).

A: isindex deprecated magic name from HTML5
This deprecated feature allows a form submission to generate such an URL, providing further evidence that it is valid for HTML. E.g.:
<form action="#isindex" class="border" id="isindex" method="get">
  <input type="text" name="isindex" value="bar"/>
  <button type="submit">Submit</button>
</form>

generates an URL of type:
?bar

Standard: https://www.w3.org/TR/html5/forms.html#naming-form-controls:-the-name-attribute
isindex is however deprecated as mentioned at: https://stackoverflow.com/a/41689431/895245

A: *

*Valid to the URI RFC

*Likely acceptable to your server-side framework/code

The URI RFC doesn't mandate a format for the query string.  Although it is recognized that the query string will often carry name-value pairs, it is not required to (e.g. it will often contain another URI).

3.4.  Query
The query component contains non-hierarchical data that, along with
data in the path component (Section 3.3), serves to identify a
resource within the scope of the URI's scheme and naming authority
(if any).  ...
... However, as query components
are often used to carry identifying information in the form of
"key=value" pairs and one frequently used value is a reference to
another URI, ...

HTML establishes that a form submitted via HTTP GET should encode the form values as name-value pairs in the form "?key1=value1&key2=value2..." (properly encoded).  Parsing of the query string is up to the server-side code (e.g. Java servlet engine).
You don't identify what server-side framework you use, if any, but it is possible that your server-side framework may assume the query string will always be in name-value pairs and it may choke on a query string that is not in that format (e.g. ?bar).  If its your own custom code parsing the query string, you simply have to ensure you handle that query string format.  If its a framework, you'll need to consult your documentation or simply test it to see how it is handled.

A: They're perfectly valid. You could consider them to be the equivalent of the big muscled guy standing silently behind the mob messenger. The guy doesn't have a name and doesn't speak, but his mere presence conveys information.

A: "The "http" scheme is used to locate network resources via the HTTP protocol. This section defines the scheme-specific syntax and semantics for http URLs." http://www.w3.org/Protocols/rfc2616/rfc2616.html
http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]]

So yes, anything is valid after a question mark. Your server may interpret differently, but anecdotally, you can see some languages treat that as a boolean value which is true if listed.

A: As all other answers described, it's perfectly valid for checking, specially for boolean kind stuff
Here is a simple function to get the query string by name:
function getParameterByName(name, url) {
    if (!url) {
        url = window.location.href;
    }
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

and now you want to check if the query string you are looking for exists or not, you may do a simple thing like:
var exampleQueryString = (getParameterByName('exampleQueryString') != null);

the exampleQueryString will be false if the function can't find the query string, otherwise will be true.

A: The correct resource to look for this is RFC6570. Please refer to section 3.2.9 where in examples empty parameter is presented as below.
 Example Template     Expansion
   {&x,y,empty}       &x=1024&y=768&empty=


text:
Q: Selection Sorting program showing abnormal results I wrote a selection sort program in C++. I have checked and rechecked the code, but the logic is perfectly fine. But the code is not sorting the array properly:
    // Selection Sort

#include <iostream>

using namespace std;

inline void swap( int& x, int& y) {
    int temp = x;
    x = y;
    y = temp;
}

int main() {
    const int n = 10;
    int list[n];

    string line(14, '-');
    cout << '\n' << line << "\nSelection Sort\n" << line << '\n';
    cout << "Enter " << n << " elements:\n";

    for( int i = 0; i < n; ++i ) {
        cin >> list[i];
    }

    for( int i = 0; i < n-1; ++i ) {
        int small = i;
        for( int j = 1; j < n; ++j ) {
            if( list[j] < list[small] ) {
                small = j;
            }
        }
        if( list[small] < list[i] ) {
            swap( list[i], list[small]);
        }
    }

    cout << "Sorted Array:\n";
    for( int i = 0; i < n; ++i ) {
        cout << list[i] << ' ';
    }

    return 0;
}

Where am I going wrong? The algorithm of Selection sort is given here: Selection Sort- wikipedia
Sample input with 10 numbers:

7 8 9 10 11 12 13 14 15 16

Output:

7 9 10 11 12 13 14 15 8 16

A: The inner loop is surely wrong here:
for( int j = 1; j < n; ++j ) {

should be
for( int j = i+1; j < n; ++j ) {

Also, the condition at the end of the loop
if( list[small] < list[i] ) {
    swap( list[i], list[small]);
}

is excessive. It is satisfied by definition after the inner loop exits.
See: Sorting algorithms - selection sort for the pseudocode and a nicely animated demo on different kinds of data.

A: In the inner loop of the sorting loop, you have written: for( int j = 1; ...)
Now, every time, the inner loop is not going from 1 to n-1, but instead is going from i+1 to n-1
So change the loop to for( int j = i+1; ...)
Also, you may change the swapping condition to small != i, but this is optional.

A: I've inspected your code and you have a logic error for the selection sort to succeed. In the inner loop, the initialization of the inner loop is always j = 1. This should change to:
for( int j = i+1; j < n; ++j ) {
        if( list[j] < list[small] ) {
            small = j;
        }
}

and also change the condition value of your outer loop to i < n to ensure the loop goes from start to end.

A: The inner loop should be
  for(j=i+1;j<n;j++)
  {
    if( list[j] < list[small] ) {
        small = j;
    }
  }

And if they small is not equal to I variable then swap
  if(small != i)
  {
   swap();
  }


text:
Q: Convertir string moneda a double sin saber el formato Estoy tratando de pasar un string con valores aleatorios con diferentes formatos de moneda:
1,222.50
1.222,50
1222.5
1222,500
1222

A un double para poder insertarlo en la base de datos. Hasta ahora tengo el siguiente código:
String a1, a2;
a1 = "1.100,50";
a2 = "1,100.50";
NumberFormat nf = NumberFormat.getInstance();
double number = nf.parse(a1).doubleValue();
double number2 = nf.parse(a2).doubleValue();
System.out.println(number);
System.out.println(number2);

Pero este es el resultado que obtengo:
1100.5
1.1

No me está funcionando con el formato inglés. Traté con la función Double.parseDouble(a1) pero tiene problemas con el formato español. Hay alguna manera de pasarlo a Double independientemente del formato que tenga?

A: Como bien se menciona solo puede existir un separador de decimales, por lo que debes de identificar cuál es y reemplazarlo con punto para que se haga correctamente la conversión a Double.
Nunca me he topado con el problema que representas, pero me dió la curiosidad y desarrollé el siguiente método rápidamente. Verás que siempre te devuelve el separador de decimales con el punto y elimina los separadores de miles.
public static String ajustaMoneda(String valor1)
{

    int lastPosComas = -1;
    int lastPosPuntos = -1;

    lastPosComas = valor1.lastIndexOf(",");
    lastPosPuntos = valor1.lastIndexOf(".");

    if (lastPosComas > lastPosPuntos)
    {
        valor1 = valor1.replace(".", "");
        valor1 = valor1.replace(",", ".");

    }
    else
    {
        valor1 = valor1.replace(",", "");
    }

    Double valorDouble = new Double(valor1);
    System.out.println(valorDouble);

    return valor1;
}

Con los ejemplos que pusiste el resultado sería:
Valor de 1,222.50: 1222.5
Valor de 1.222,50: 1222.5
Valor de 1222.5: 1222.5
Valor de 1222,500: 1222.5
Valor de 1222: 1222.0
Espero que se adapte a tus necesidades.
Saludos!


text:
Q: Powershell Get-Process : Couldn't connect to remote machine Been struggling with this for a couple days now.
I'm getting the following error:
PS C:\> get-process -ComputerName Win2012r2
get-process : Couldn't connect to remote machine.
At line:1 char:1
+ get-process -ComputerName 10.10.1.54
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-Process], InvalidOperationException
    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetProcessCommand

I have confirmed that the Remote Registry service is running on the server (I also tried restarting it).
Additionally, I've created a custom firewall rule to allow RCP connections on ports 5985 && 5986 per
https://stackoverflow.com/questions/22357063/get-process-to-remote-computer-doesnt-work-but-invoke-command-does
I've also double checked the usernames per Powershell Get-Process cannot connect to remote computer
Note
invoke-command -ComputerName Win2012r2 -ScriptBlock {Get-Process} works fine, but I really need to get the get-process -computername process to work directly since it's failing inside another script that is used by others

A: I had a similar error when I started to teach myself PS2 on Win7 client testing LocalHost. I resolved it by starting the Remote Registry service.

A: I finally gave up and wrote a new script that uses the following rather than calling Get-Process directly:
invoke-command -ComputerName Win2012r2 -ScriptBlock {param($procName) Get-Process -Name $processName} -ArgumentList $ProcName

A: -ComputerName in Get-Process uses RPC, not WinRM. WinRM is what uses 5985 and 5986, not RPC.
RPC ports are dynamic by default.
Check the "Get-Help" of Get-Process.
-ComputerName
This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter of Get-Process even if your computer is not configured to run remote commands.
Invoke-Command DOES use WinRM.
So when you changed your code to use Invoke-Command, your script started working.

A: Try using this instead:
get-wmiobject -class win32_process -computername pcname -filter "Name = 'procname'"

A: The only thing I can think of is that either the account you're running this under doesn't have admin rights on the target (Win2012r2), or that the firewall is blocking it.  Try disabling the firewall completely to test the latter.

A: Have you verified that your DNS resolution is working? Might try nslookup to verify that you are resolving to the correct IP.
Check out this post. This looks like an answer to your problem. Try turning off the firewall on both systems and use get-process. If it then works you will know that you need to open the ports that are mentioned in this post.
https://stackoverflow.com/questions/22357063/get-process-to-remote-computer-doesnt-work-but-invoke-command-does


text:
Q: reference dict element from another one? Is it possible in python one dict element to reference another ?
F.e. :
h = { 'a' : 1, 'b' : 2 }
h['c'] = \h[a]

print h['c']
1

h['a'] = 12
print h['c']
12

I see :
In [382]:  h = { 1: {6:7}, 3:4 }

In [383]: h
Out[383]: {1: {6: 7}, 3: 4}

In [384]: h[5]=h[1]

In [385]: h
Out[385]: {1: {6: 7}, 3: 4, 5: {6: 7}}

In [386]: h[1][6] = 13

In [387]: h
Out[387]: {1: {6: 13}, 3: 4, 5: {6: 13}}

trying to build tree, bottom-up.

A: Yes, you can certainly point elements in a dictionary to another element.  When you assign h['c'] to h['a'], they now share the same memory location:
h = { 'a' : 1, 'b' : 2 }
h['c'] = h['a']
h['c'] is h['a']
True

However, many types in Python are something called immutable.  They cannot be changed once they are created.  int is one of those types, (as are str, tuple, and others).  So once you change h['a'], h['c'] is no longer pointing to it, since it is now a different object.
h['a'] = 12
h['c'] is h['a']
False

However, if h['a'] is a mutable type (this includes list, dict, and others), when you point h['c'] to h['a'], and mutate h['a'], that change will be reflected in h['c'] as well, as h['c'] is pointing to the same object that h['a'] is.
Here is a very simple example using a list:
dct = {'x': [1,2,3]}
dct['y'] = dct['x']
dct['y'] is dct['x']
True

dct['x'][0] = 5
dct['y'] is dct['x']
True

dct
{'x': [5, 2, 3], 'y': [5, 2, 3]}


text:
Q: Bootstrap navigation - from bottom to top / affix Please take a look on a following link:
bootstrap nav example
I want to achieve the same result in terms of navigation. So when we start browsing the web, menu in on the bottom, after scrolling down it goes top and stay there. I've read in doc's of Bootstrap that it might be connected with affix. But - its not clear to me how to achieve that. I've use such code:

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

                </button>

                      Start Bootstrap

                        About

                        Download

                        Contact

But it doesn't seems to work.. Is there any other idea how to approach it ?

A: Looking at the source of the theme you linked, all they are doing is putting the initial content above the normal navbar.

This keeps the navbar on the bottom initially, then after you click the initial button or scroll down, the header stays at the top of the page for the rest of the site.

A: Try this:
You are almost correct ! Its displaying but not in correct formats ! You have to change the style of the toggle button and set the width 100% for nav bar

                <button style="background-color:lightgray" type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

                </button>

                      Start Bootstrap

                        About

                        Download

                        Contact


text:
Q: Order clause with 'like' clause in Zend DB Query:
select * from table_name ORDER BY name like 'C%' DESC;
This query work fine in MySql, but i am unable build the query using Zend DB.
I am getting error while executing.
PHP DB code:

    $result = $this->getDefaultAdapter()
                           ->select()
                           ->from($this->_name,array('*'))
                           ->order("name like 'C%' DESC")
                           ->query()
                           ->fetchAll();

Error:

Column not found: 1054 Unknown column 'name like 'C%'' in 'order clause'

Thanks in advance

A: Zend_Db_Select tries to delimit strings as column names, but it skips doing that if you pass an object of type Zend_Db_Expr instead of a string:
->order(new Zend_Db_Expr("name like 'C%' DESC"))->

There's also an undocumented shortcut: the column-delimiting function assumes that any string containing parentheses is very likely to be an expression instead of just a column name.  So the following would work too:
->order( "(name like 'C%' DESC)" )->

A: I'm not familiar with zend but Try to rewrite your sql query in Zend like this
select *, (`name` like 'C%') as theFiled from  table_name by theFiled desc;

Though i'm not so sure I guess that the Zend Code must be something like this,
 $result = $this->getDefaultAdapter() ->select()
->from($this->_name,array('*', "theFiled" => "name like 'C%'") ->order("theFiled DESC")
->query() ->fetchAll();


text:
Q: Clang++ 6.0 Memory Sanitizer not reporting uninitialised local variable in a function whose return value dictates a conditional branch The following code(in src.cpp) was used to experiment with Clang's Memory Sanitizer (MSan)
#include <iostream>
#include <vector>

int add(int x, int y) {
    int sum;
    sum = x + y;
    return sum;
}
int main() {
    if(add(10, 20) > 0) {
        std::cout << "Greater";
    }
    std::cout << std::endl;
    return 0;
}

We can clearly see that sum is unitialized and would cause an undenfined behaviour. As per MSan Github Wiki

MemorySanitizer is bit-exact: it can track uninitialized bits in a
  bitfield. It will tolerate copying of uninitialized memory, and also
  simple logic and arithmetic operations with it. In general,
  MemorySanitizer silently tracks the spread of uninitialized data in
  memory, and reports a warning when a code branch is taken (or not
  taken) depending on an uninitialized value.

This clearly seems to conform to this use case since the if branch will be taken based on the intial value of sum. However, no error/warning is displayed while running this code compiled with
clang++  -fsanitize=memory -fsanitize-memory-track-origins -O0 -std=c++14 src.cpp -o src
Clang 6.0 is used on Linux x86_64.

A: sum is not uninitialized, because the next instruction is the assignment of the sum variable.
This code is the same as:
int sum = x + y;
And thats why it is initialized.


text:
Q: Insert Python string to datetime Oracle column I have a python list with 10 string fields.
One of the strings is a date and I want to write the list to an Oracle table.
I try to use executemany.
if I write all fields as strings it is OK but when I try to convert one of the fields to a date and change the table column type to DATE I get errors.
For example:
I try to change from my list (data) the field to datetime
data[0][2] = datetime.strptime(data[1][2], "%Y-%m-%d %H:%M:%S.%f")

and then I try to executemany and I got the error:

TypeError: expecting date or datetime

Maybe someone can share example or idea to solve this issue?
sample data:
data sample
and after that i try to executemany like that:
sql="insert into py_table (RECORD_DATE,TYPECOL,GMTRD) values (:1,:2,:3)"
cursor.executemany(sql, listdf)
connection_dev.commit()


text:
Q: c# How Save text file line to line I am success save file but I need 1st save after when click 2nd save then going 2nd line.
but it's show all same line.
Can you help me how I am doing 2nd line?
    private void button1_Click(object sender, EventArgs e)
    {
        string fileName = "E:\\sumon.txt";
        string textToAdd = textBox1.Text;

       using (StreamWriter writer = new StreamWriter(fileName, false))
        {
            writer.Write(textToAdd);

       }

    }

A: Use a StreamWriter, not a StreamReader. Try the following:
using(StreamWriter sr = new StreamWriter("yourfilename.txt"))
{
    sr.WriteLine(textBox1.Text);
}

The using keyword here allows the compiler to automatically dispose of the writer when it falls out of scope, which includes closing the stream and releasing the underlying operating system resources.

A: You can also simply use
System.IO.File.WriteAllText("yourfilename.txt", textBox1.Text);


text:
Q: When can optimizations done by the compiler destroy my C++ code? When can optimizations done by the compiler cause my C++ code to exhibit wrong behaviour which would not be present had those optimizations not been performed? For example, not using volatile in certain circumstances can cause the program to behave incorrectly (e.g. not re-reading the value of a variable from memory and instead only reads it once and stores it in register). But are there other pitfalls which one should know about before turning on the most aggressive optimization flag and afterwards wondering why the program doesn't work anymore?

A: Besides the case you mentioned, timing can change in multi-threaded code such that what appears to be working no longer does.  Placement of local variables can vary such that harmful behaviour like a memory buffer overrun occurs in debug but not release, optimized or non-optimized, or vice versa. But all of these are bugs that were there already, just exposed by compiler option changes.
This is assuming the compiler has no bugs in its optimizer.

A: I've only run into it with floating point math.  Sometimes the optimizations for speed can change the answer a little.  Of course with floating point math, the definition of "right" is not always easy to come up with so you have to run some tests and see if the optimizations are doing what you're expecting.  The optimizations don't necessarily make the result wrong, just different.
Other than that, I've never seen any optimizations break correct code.  Compiler writers are pretty smart and know what they're doing.

A: Bugs caused by compiler optimizations that are not rooted in bugs in your code are not predictable and hard to determine (I managed to find one once when examining the assembly code a compiler had created when optimizing a certain area in my code once). The common case is that if an optimization makes your program unstable, it just reveals a flaw in your program.

A: Compiler optimizations should not affect the observable behavior of your program, so in theory, you don't need to worry.  In practice, if your program strays in to undefined behavior, anything could already happen, so if your program breaks when you enable optimizations, you've merely exposed existing bugs - it wasn't optimization that broke it.
One common optimization point is the return value optimisation (RVO) and named return value optimization (NRVO) which basically means objects returned by value from functions get constructed directly in the object which is receiving them, rather than making a copy.  This adjusts the order and number of constructor, copy constructor and destructor calls - but usually with those functions correctly written, there's still no observable difference in the behavior.

A: Just don't work from the assumption that the optimizer ever destroys your code.  It's just not what it was made to do.  If you do observe problems then automatically consider unintentional UB.
Yes, threading can play havoc with the kind of assumptions you are used to.  You get no help from either the language or the compiler, although that's changing.  What you do about that is not piss around with volatile, you use a good threading library.  And you use one of its synchronization primitives wherever two or more threads can both touch variables.  Trying to take short-cuts or optimizing this yourself is a one-way ticket into threading hell.

A: Failing to include the volatile keyword when declaring access to a volatile memory location or IO device is a bug in your code; even if the bug is only evident when your code gets optimized.
Your compiler will document any "unsafe" optimizations where it documents the command-line switches and pragmas that turn them on and off. Unsafe optimizations usually related to assumptions about floating point math (rounding, edge cases like NAN) or aliasing as others have already mentioned.
Constant folding can create aliasing making bugs in your code appear. So, for example, if you have code like:
static char *caBuffer = "                                         ";

...

strcpy(caBuffer,...)

Your code is basically an error where you scribble over a constant (literal). Without constant folding, the error won't really effect anything. But much like the volatile bug you mentioned, when your compiler folds constants to save space, you might scribble over another literal like the spaces in:
printf("%s%s%s",cpName,"   ",cpDescription);

because the compiler might point the literal argument to the printf call at the last 4 characters of the literal used to initialize caBuffer.

A: As long as your code does not rely on specific manifestations of undefined/unspecified behavior, and as long as the functionality of your code is defined in terms of observable behavior of C++ program, a C++ compiler optimizations cannot possibly destroy the functionality of your code with only one exception:

*

*When a temporary object is created with the only purpose of being immediately copied and destroyed, the compiler is allowed to eliminate the creation of such temporary object even if the constructor/destructor of the object has side-effects affecting the observable behavior of the program.
In the newer versions of C++ standard that permission is extended to cover named object in so called Named Return Value Optimization (NRVO).
That's the only way the optimizations can destroy the functionality of conforming C++ code. If your code suffers from optimizations in any other way, it is either a bug in your code or a bug in the compiler.
One can argue though, that relying on this behavior is actually nothing else than relying on a specific manifestation of unspecified behavior. This is a valid argument, which can be used to support the assertion that under the above conditions optimizations can never break the functionality of the program.
Your original example with volatile is not a valid example. You are basically accusing the compiler of breaking guarantees that never existed in the first place. If your question should be interpreted in that specific way (i.e. what random fake non-existent imaginary guarantees can optimizer possibly break), then the number of possible answers is virtually infinite. The question simply wouldn't make much sense.

A: I just recently saw that (in C++0x) the compiler is allowed to assume that certain classes of loops will always terminate (to allow optimizations). I can't find the reference right now but I'll try to link it if I can track it down. This can cause observable program changes.

A: Strict aliasing is an issue you might run into with gcc. From what I understand, with certain versions of gcc (gcc 4.4) it gets automatically enabled with optimizations. This site http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html does a very good job at explaining strict aliasing rules.

A: At a meta level, if your code uses relies on behavior that is based on undefined aspects of the C++ standard, a standards conforming compiler is free to destroy your C++ code (as you put it). If you don't have a standards conforming compiler, then it can also do non-standard things, like destroy your code anyway.
Most compilers publish what subset of the C++ standard they conform to, so you can always write your code to that particular standard and mostly assume you are safe. However, you can't really guard against bugs in the compiler without having encountered them in the first place, so you still aren't really guaranteed anything.

A: I do not have the exact details (maybe someone else can chime in), but I have heard tell of a bug caused by loop unrolling/optimization if the loop counter variable is of char/uint8_t type(in a gcc context i.e.).


text:
Q: Import/Export DataFusion pipelines Does anyone know if it is possible to programmatically import/export DataFlow pipelines (deployed or in draft status)?
The idea is to write a script to drop and create a DataFusion instance, in order to avoid billing when it's not used.
Via gloud commandline it's possible to provision a DataFusion cluster and to destroy it, but it would be interesting to automatically export and import all my pipelines too.
The official documentation, unfortunately, didn't help me...
Thanks!

A: You could use the REST API to do this. However you would probably need some script that automatically does this given the instance url. You should be able to get pipeline config from application list API (reference here). In your case you first need to get list of pipelines (reference here) then iterate through all pipelines and get details of individual pipeline which will have a property called configuration which will have the config pipeline json. You still have to create a new JSON with name, description, artifact information along with config property with configuration json you received from backend.
A sample would look like this,

*

*In your cluster you are about to destroy, GET API to get list of apps with artifactName=cdap-data-pipeline,cdap-data-streams as query parameter

/namespaces/default/apps?artifactName=cdap-data-pipeline,cdap-data-streams?artifactName=cdap-data-pipeline,cdap-data-streams

*Parse response and iterate through individual apps and GET app details

namespaces/default/apps/<app-name>

For each app get configuration property in the response and form your final JSON to something like,

{
  "name": "Pipeline_1",
  "description": "Pipeline to do taskX",
  "artifact": {
    "name": "cdap-data-pipeline",
    "version": "6.1.0-SNAPSHOT",
    "scope": "USER"
  },
  "config": JSON.parse(<configuration-from-app-detailed-api>)
}

*Then in a new cluster you are about to create just deploy the pipeline using the json you got in the previous step.

One thing to note is, if you have setup schedules or triggers for pipelines in old cluster, those won't be created in the new cluster. Rest of the pipeline should just work if you are just deploying and running the pipeline.
Hope this helps.
[UPDATE] 11/20
Just realized there is docs on accessing REST API for datafusion here However it doesn't take entirely about HOW to make the REST api call. Here is an example on how to do it,
curl -H "Authorization: Bearer $(gcloud auth print-access-token)" -w"\n" -X GET <instance-url>/namespaces/default/apps?artifactName=cdap-data-pipeline,cdap-data-streams?artifactName=cdap-data-pipeline,cdap-data-streams

Here we use gcloud to get access-token to that specific instance. A pre-requisite for this would be to signin with gcloud SDK. This should successfully return the list of apps in your specific instance once the authentication is successful.


text:
Q: How to simulate KEY_BUSY hot key error code 14 in Aerospike How can I test/produce an Aerospike exception code 14?
I have a simple one node environment with Aerospike in it and a java application on K8s.
There are 3 pods of the application, all are consuming messages from Kafka topic with 3 partitions, all in the same consumer group.
With Kafka producer driver, we inject at once 200 messages, with no Kafka message key (so that kafka will round robin on the 3 topic partitions).
All messages relate to the same Aerospike key so the 3 application pods suppose to update the same record in parallel, resulting with Aerospike hotkey exception (KEY_BUSY, error code 14).
But that's not happening and all 200 messages are processed successfully.
The configuration parameter "transaction-pending-limit" is set to 1 in aerospike.conf.
Many thanks.

A: Try adding one more node in the Aerospike cluster. With a one node Aerospike cluster, you are not replicating to another node. So the transaction is completing before you can encounter "key busy". Adding another node to the Aerospike cluster with replication factor 2 will cause the current transaction to wait in the queue for the replication ack and then, I believe, you will be able to simulate key busy error with transaciton-pending-limit set to 1. Let us know if that works for you.


text:
Q: How expensive is maintaining a TCP socket in java I have currently implemented a heartbeat mechanism for my project and I am using TCP as my underlying connectivity. I was wondering how expensive is maintaining a tcp connection. Each slave sends a heartbeat every 5 seconds to the master(yes i know its way to often but i have a good reason to do so). So I was wondering should I constantly create a new connection or should I keep the connection open. Because if I keep the open connection then in that case I can just handle the exception. But since I need to know every 5 seconds wether or not a slave is down should I be re establishing the connection or just keep it open. Thanks in advance.

A: It's more expensive to re-open the connection regularly; there is a three-way handshake on open. Once the socket is open, that cost can be amortized (but only if you leave it open).

A: As previously stated reopening the connection is more expensive, unless there are other factors involved like mobility. Not only do you have a three-way handshake, but you also have a four-way handshake terminating the connection. In addition to this, your TCP server application likely open up new threads for each new connection, which also needs to be allocated, deallocated etc.
Most likely your connection will also pass through firewalls which are often NATed, which in turn opens up ports and states. This is why I personally rarely use UDP, because UDP may have problems passing through firewalls and ISP filters.
Finally the maintenance of the TCP connection itself from a protocol point of view is minimal. TCP do have the option of keep-alive, but these are rarely sent as often as every 5 seconds. There is a small overhead of context switching within your OS process, but that would happen regardless of you opening and closing the connection.
Keep it open.

A: If you are doing a heartbeat, why not use UDP, TCP requires confirmation of receipt, UDP does not, then you can have a listener and just receive any packets that are broadcast to it and process. meaning one port open on the main system no matter how many children are sending to it.
TCP you would require one connection per child.


text:
Q: NotSerializableException: org.springframework.binding.mapping.impl.DefaultMappingResults I'm getting
Caused by: org.springframework.webflow.execution.repository.snapshot.SnapshotCreationException: Could not serialize flow execution; make sure all objects stored in flow or flash scope are serializable
    at org.springframework.webflow.execution.repository.snapshot.SerializedFlowExecutionSnapshot.<init>(SerializedFlowExecutionSnapshot.java:75)
    at org.springframework.webflow.execution.repository.snapshot.SerializedFlowExecutionSnapshotFactory.createSnapshot(SerializedFlowExecutionSnapshotFactory.java:70)
    at org.springframework.webflow.execution.repository.snapshot.AbstractSnapshottingFlowExecutionRepository.snapshot(AbstractSnapshottingFlowExecutionRepository.java:75)
    at org.springframework.webflow.execution.repository.impl.DefaultFlowExecutionRepository.putFlowExecution(DefaultFlowExecutionRepository.java:126)
    at org.springframework.webflow.executor.FlowExecutorImpl.resumeExecution(FlowExecutorImpl.java:171)
    at org.springframework.webflow.mvc.servlet.FlowHandlerAdapter.handle(FlowHandlerAdapter.java:228)
    at org.springframework.faces.webflow.JsfFlowHandlerAdapter.handle(JsfFlowHandlerAdapter.java:57)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
    ... 46 more
Caused by: java.io.NotSerializableException: org.springframework.binding.mapping.impl.DefaultMappingResults
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)

so that NotSerializableException completely eats root cause making it impossible to figure out what's happend. The not serializable DefaultMappingResults come from
"lastError" -> "org.springframework.webflow.engine.FlowInputMappingException: Errors occurred during input mapping in state 'openAgreement' of flow 'menu'; errors = [[SourceAccessError@226a8851 mapping = flowScope.securityCards.selectedRow.agreementId -> agreementId, code = 'evaluationException', error = true, errorCause = org.springframework.binding.expression.EvaluationException: An ELException occurred getting the value for expression 'flowScope.securityCards.selectedRow.agreementId' on context [class org.springframework.webflow.engine.impl.RequestControlContextImpl], originalValue = [null], mappedValue = [null]]]"

Not sure if it's related but the problem poped up after updating JSF from 2.1 to 2.2 but most likely there were no root error under 2.1
The problem somehwat resambles this one but not sure.
the openAgreement state:
<subflow-state id="openAgreement" subflow="menu">
    <on-entry>
        <evaluate expression="agreementService.init()" result="flowScope.agreementReadCriteria" />
    </on-entry>

    <input name="agreementReadCriteria" value="flowScope.agreementReadCriteria"/>

    <input name="agreementId" value="flowScope.securityCards.selectedRow.agreementId"/>
    <input name="currentBankId" value="flowScope.currentBankId"/>
    <input name="goToAgreement" value="true"/>

    <transition on="closeAgreement" to="securityCardsViewBasic">

    </transition>
</subflow-state>


text:
Q: How to setup Apache so some websites across multiple sub-domains are always using https  I realise there are lots of different variations on this question on serverfault but I haven't had any luck with combining answers to match our situation.
We have a CentOS 6.2 web server running Apache 2.2 hosting dozens of websites with the same parent domain - i.e. cat.example.com, bat.example.com, rat.example.com
We'd like to add https to some (but not all) of these sub-domains. The sub-domains that are https would run https permanently. For example http://bat.example.com would redirect to https://bat.example.com
We have purchased a Comodo Multi-Domain SSL Certificate License for the SSL, which allows us to create certificates for multiple domains. The web server only has a single public facing IP.
How do we setup Apache to do this? If the Virtual Host entry in httpd.conf for bat.example.com is:
<VirtualHost *:80>
  ServerName bat.example.com
  DocumentRoot /var/www/sites/bat
  ErrorLog logs/bat-error_log
  CustomLog  logs/bat-access_log common
</VirtualHost>

What changes should be made to enable SSL on bat.example.com and make sure http://bat.example.com is still valid, but redirects to https://bat.example.com?

A: You will first need to set up an SSL VirtualHost, so something like:
<VirtualHost *:443>
  ServerName bat.example.com
  DocumentRoot /var/www/sites/bat
  ErrorLog logs/bat-error_log
  CustomLog  logs/bat-access_log common

  SSLEngine on
  SSLCertificateFile /path/to/cert
  SSLCertificateKeyFile /path/to/key
</VirtualHost>

In your non-SSL virtual host, you will need some Rewrite directives to force requests to the corresponding SSL virtual host.  So, additional directives to what you have, along the lines of:
   RewriteEngine on
   RewriteRule   ^/(.*)         https://bat.example.com/$1 [R,L]

So, all requests to the plain HTTP virtual host will be rewritten to the SSL virtual host.


text:
Q: Count of Value from the Given Date time + 1Hour I have a Dataset like:
Date - Time Dimension1  Dimension2  Count
10-1-2020 00:18:15  A   B   2
10-1-2020 01:18:00  A   B   3
10-1-2020 01:45:00  A   B   2
10-1-2020 01:48:00  A   B   1
10-1-2020 03:02:00  B   A   5

The DateTime column that we see in the Dataset has 2 dimensions and the final display is the count of values with respect to the Date Time + 1Hour.
Record 1 : Given Date : 01/10/2020 12:18:15 AM  Date + 1Hour : 01/10/2020 01:18:15 AM

So between these 2 dates I need to find out the count of matching records. For this date range there are 2 records which are within 1 hour so the count is 2.
Code :
SELECT
D5,
CAL_DATE,
Transaction_DATETIME,
D1,
D2,
D3,
D4,
COUNT(D4) AS CNT
FROM TAB1
WHERE
timestamp(Transaction_DATETIME, 'MM-D-YYYY HH:mm:ss TT') >= timestamp(Transaction_DATETIME, 'MM-D-YYYY HH:mm:ss TT')
AND timestamp(Transaction_DATETIME, 'MM-D-YYYY HH:mm:ss TT') <= Timestamp(Transaction_DATETIME + Time#('01:00:00','HH:mm:ss'),'MM-D-YYYY HH:mm:ss TT')
GROUP By
D5,
DATE,
Transaction_DATETIME,
D1,
D2,
D3,
D4;

Requesting your help on this.
Thanks.

A: SQL supports window functions for this purpose.  In many databases, the syntax is something like this:
select t.*,
       count(*) over (partition by dim1, dim2
                      order by datetime
                      range between current row and interval '1 hour' following
                     ) as cnt
from t;

Not all databases support window functions with range on intervals.  In those, a subquery is needed:
select t.*,
       (select count(*)
        from t t2
        where t2.dim1 = t.dim1 and t2.dim2 = t.dim2 and
              t2.datetime >= t.datetime and
              t2.datetime < t.datetime + interval '1 hour'
       ) as cnt
from t;

Once again, note that date/time functions notoriously vary among databases.  The above is standard SQL but may need to be tweaked for your database.


text:
Q: HP Laptop not charging when working, doesn't start without battery - Windows 10 I have a HP laptop and yesterday I accidentally hit the laptop on the table. It was fine but when I charged it, it didn't charge at all. When it had 60% remains, the charging indicator showed white- fully charged. I close the lip to make it sleep and the indicator changed to red- charging. When I opened it, it turned back to white.

I checked the tutorials online, I uninstall battery AC options in device manager and restarted it twice and it didn't work. Also, when I shut down the computer, I toke off the battery but with the AC charger charging, I could not boot the computer.

I tried to posit the charger inside the DC power jack in an angle and length and sustained in a few seconds then it's charging! I pushed it into the deepest and it's still charging even it's working. But here is the problem, when I close the lid, and reopen it, it doesn't charge anymore. I have to do it again and it's taking me a long time to do once. Here are my questions,

*

*Why it's happening?

*How can I solve this?

*Do I need to replace anything?

Thank you so much for help!


text:
Q: Split several strings in a foreach I have these records:
Value  Part   Qty
A      PartA  QtyA
B      PartB  QtyB
C      PartC  QtyC

I'm concatenating each column in different strings:
stringValue = A~B~C
stringPart = PartA~PartB~PartC
stringQty = QtyA~QtyB~QtyC

I want to split each string to get the original row value according to the position but I'm not sure how to do it any insight would be appreciate it.
Thanks

A: String[] yourfirstrow = stringValue.Split(new string[] { "~" }, StringSplitOptions.None);

//yourfirstrow[0] first cell value
//yourfirstrow[1] second cell value
//yourfirstrow[2] third cell value

A: Create some data storage
class Model
{
    string Value {get; set;}
    string Part {get; set;}
    string Quantity {get; set;}

}

Parse and format
private List<Model> _list = new List<Model>();

void MakeList()
{
    string[] values = "A~B~C".Split("~".ToCharArray(), StringSplitOptions.None);
    string[] parts = "PartA~PartB~PartC"("~".ToCharArray(), StringSplitOptions.None);
    string[] qtys = "QtyA~QtyB~QtyC"("~".ToCharArray(), StringSplitOptions.None);

    for (int i = 0; i < values.Length; i++)
    {
        var item = new Model(){ Value = values[i], Part = parts[i], Quantity = qtys[i]};
        _list.Add(item);
    }

}

string[] GenerateCommaSeparatedRecords()
{
    return _list.Select(x => string.Format("{0},{1},{2}", x.Value, x.Part, x.Quantity)).ToArray();
}

You can generate any output you wish


text:
Q: String not serializable exception coming for interned strings from Wicket Model (on JRockit/Weblogic) The following seems to be a bug with JRockit or Weblogic, but maybe
someone on this list has seen it before and has a better
workaround/solution.
We have been developing a Wicket application for a government agency
that is going to be used by 15k users. The application will be
deployed on a Weblogic cluster running on JRockit and Red Hat.
We have been experiencing strange "Model object not serializable"
exceptions coming from Model and traced it back to interned (by the
compiler) String objects becoming not serializable after hitting the
server with a few hundred parallel users. Once the exception occurs
for a given String reference it keeps coming consistently for that
reference.
The current workaround is a custom Model class that has an overrided
setObject method which checks the object if it's instanceof
Serializable and if the check fails it sets new String(object) on the
Model. This eliminates the exceptions but would like a better solution
to the problem.
Has anyone seen anything like this?

A: I encountered the same problem using jrockit R28.0.1-21-133393-1.6.0_20-20100512-2126-linux-x86_64. After some stress to my application wicket model complains about strings not being serializable. I'm unable to replicate the situation using -Xdebug flag enabled to see what's actually passed to Model.setObject() method. It looks like my only hope is to switch back to sun jvm.


text:
Q: Tensorflow batch processing with sparse matrices - can batch numbers be arbitrary? I am doing image recognition batch processing with sparse matrices in tensorflow. The only way I can find to pass a batch of sparse images into a session through a feed_dict is to make my sparse 3d images (x, y, colour) into sparse 4d images (batchNo, x, y, colour) and pass in indices, values, and shape.
This works fine but I have to continually create 4d images with the appropriate imageNumbers within the batch. What I am wondering is if I can create them all when I initially read in the data with arbitrary image numbers (e.g. 0-1000) then keep submitting 50 (say) picked as a batch from the shuffled data. The imageNumber would be unique for each image but not sequential or ordered. This would remove a big bottle neck from my code.
def getBatchOfImagesAndLabels(data, batchSize, singlePass = False):
    # Get a shuffled array of images and labels.
    # Array length will be batchSize or smaller
    #if we get to the end of the data on a singlePass
    # an image is a dictionary of indices, values, and shape.
    batch = data.next_batch(batchSize, singlePass)
    images = batch.images
    labels = batch.labels

    # Convert array of 3d sparse images into a 4d sparse matrix
    indices = []
    values = []
    shape = [len(labels)] + images[0]['shape']
    imageNumber=0
    for image in images:
        for ind in image['indices']:
            indices.append([imageNumber] + ind)
        values.extend(image['values'])
        imageNumber += 1
    batchOfImages = {"indices": indices, "values": values, "shape": shape}
    return batchOfImages, labels

The for loop is very slow. Can I create the 4d sparse matrix when reading the data in and select slices from it which I believe would be quicker? The slices would have random, but unique, imageNumbers for each image in the batch.
Alternatively can some python guru suggest a clever way to make my for loop more efficient?


text:
Q: Recycleview child covered by keyboard I have an activity that has RecycleView.
Child of this RecycleView contain radio buttons in radioGroup, where when last radio buttons selected it show the EditText.
this is the layout:
<LinearLayout>
<Toolbar/>

<RelativeLayout
width:match_parent
height:match_parent>
    <RecycleView
    width:match_parent
    height:match_parent
    above:footer/>
    <LinearLayout
      id:footer
      width:match_parent
      height:wrap_content>
       <Button/>
    </LinearLayout>
</RelativeLayout>

</LinearLayout>

The problem happen when I scroll down to last child. It covered by keyboard.
This is the layout of each cell:
<LinearLayout>
  <RadioGroup/>
  <EditText/>
</LinearLayout>

I have try to use "AdjustResize", that should resize the ui when keyboard appears. But the last child still covered.
Has anyone have other solution?

A: try android:windowSoftInputMode="adjustPan"

A: I got the solution from this post Look the honeal's answer.
So basicly you can't set activity to fullscreen (in your theme) while use "AdjustResize"


text:
Q: Where is the "Exit Classic Experience" link in the Oslo layout? While using the Seattle Site layout, in lists or libraries, I find that at the very bottom of the left navigation, there is a link that says "Exit Classic Experience". I can't seem to find this link when using the Oslo layout since there is not a left navigation.
Does anyone know where this option is?

A: The "Exit classic experience" option displays in the left navigation. As you mentioned, the oslo is different with the seattle and the oslo does not have the left navigation.
To view this option, you need to use seattle or customize the master page to display the left navigation.
Another workaround with the oslo, you need to close the browser and re-open the list/library. It will switch back to the default experience.

A: A blog I read had a trick to hide it that consisted of some javascript and css. I converted it to how to go back to modern from classic. Simply go to Console in your browser (normally F12), then write GoToModern(); in "console" (web console in Firefox). Thats all there is to it.


text:
Q: Convert date format 1542575966120 18/11/2018 I have a DB that shows when the user made the last login but then it shows 1542575966120. I wanted it to show so 18/11/2018 19:00
I tried using this in php
$intDate = "20". $ infologado ["lastlogin"];

$newDate = date ("d-m-Y", strtotime ($ intDate));

but I could not.
sorry for English

A: So as @Taha Paksu had mentioned, these numbers are a timestamp (seconds since 1 January 1970). Try this code:
$intDate = 1542575966120;
$newDate = date('d/m/Y H:i', $intDate/1000);

It is in miliseconds, date function accepts seconds, thus the division by 1000. Also no need to put it into strtotime, because this function is meant to convert string dates to... said numeric timestamps.
In your case, you can put $intDate = $infologado['lastlogin']; instead of first line to get the result dynamically from the database.

A: First of all, you need to learn what a timestamp is. The timestamp is a number which shows the seconds passed (or milliseconds, some include the milliseconds too) since epoch (01/01/1970). A general definition can be found here:

The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z). Literally speaking the epoch is Unix time 0 (midnight 1/1/1970), but 'epoch' is often used as a synonym for 'Unix time'. Many Unix systems store epoch dates as a signed 32-bit integer, which might cause problems on January 19, 2038 (known as the Year 2038 problem or Y2038).
The converter on this page converts timestamps in seconds, milliseconds and microseconds to readable dates.

Taken from: https://www.epochconverter.com/ a tool which you can convert your dates to/from timestamps or vice versa.
Then to answer your question, the system saved the dates as a timestamp to the database to (probably) bypass the formatting errors on each different system that uses it.
Nevermind, TL;DR:
The number shows Sunday, 18 November 2018 21:19:26.120 when you give it to the timestamp converter I mentioned above. With PHP, you can use:
$unixTimestamp = 1542575966120;
$dt = DateTime::createFromFormat("U.u", $unixTimestamp / 1000);
var_dump($dt);

to convert to PHP DateTime class, then you can use it in your application.


text:
Q: Looping over elements to change font in math mode I have the following code:
\documentclass{article}

\newcommand*{\ident}[1]{\texttt{\small #1}}

\makeatletter
\newcommand\ci[1]{%
    \def\citmp{}%
    \@for\reserved:=#1\do{%
        \protected@edef\citmp{\citmp\ifx\citmp\empty\else,\fi\ident{\reserved}}%
    }%
    \{\citmp\}%
}
\makeatother

\begin{document}

$\ci{a,b,c}$ % (1)

$\ci{a, b, c}$ % (2)

$\{\ident{a}, \ident{b}, \ident{c} \}$ % (3)

\end{document}

(The code for \ci is taken from an answer on this site; I can't find the URL right now, though.)
This contains two problems:

*

*Lines (1) and (2) report those warnings, whereas line (3), which should (from what I understand, at least), be identical to line (1), does not: (Solved by jfbu, thanks!)
LaTeX Font Warning: Command \relax \GenericWarning {(Font)              }{LaTeX
 Font Warning: Command \relax \GenericWarning {(Font)              }{LaTeX Font
 Warning: Command \relax \fontsize {9}{11}\selectfont \abovedisplayskip 8.5\p@
plus3\p@ minus4\p@ \abovedisplayshortskip \z@ plus2\p@ \belowdisplayshortskip 4
\p@ plus2\p@ minus2\p@ \def \leftmargin \leftmargini \parsep 4\p@ plus2\p@ minu
s\p@ \topsep 8\p@ plus2\p@ minus4\p@ \itemsep 4\p@ plus2\p@ minus\p@ {\leftmarg
in \leftmargini \topsep 4\p@ plus2\p@ minus2\p@ \parsep 2\p@ plus\p@ minus\p@         itemsep \parsep }\belowdisplayskip \abovedisplayskip invalid in math mode}\font
size {9}{11}\selectfont \abovedisplayskip 8.5\p@ plus3\p@ minus4\p@ \abovedispl
ayshortskip \z@ plus2\p@ \belowdisplayshortskip 4\p@ plus2\p@ minus2\p@ \def \l
eftmargin \leftmargini \parsep 4\p@ plus2\p@ minus\p@ \topsep 8\p@ plus2\p@ min
us4\p@ \itemsep 4\p@ plus2\p@ minus\p@ {\leftmargin \leftmargini \topsep 4\p@ p
lus2\p@ minus2\p@ \parsep 2\p@ plus\p@ minus\p@ \itemsep \parsep }\belowdisplay
skip \abovedisplayskip invalid in math mode}\fontsize {9}{11}\selectfont \above
displayskip 8.5\p@ plus3\p@ minus4\p@ \abovedisplayshortskip \z@ plus2\p@ \belo
wdisplayshortskip 4\p@ plus2\p@ minus2\p@ \def \leftmargin \leftmargini \parsep
 4\p@ plus2\p@ minus\p@ \topsep 8\p@ plus2\p@ minus4\p@ \itemsep 4\p@ plus2\p@
minus\p@ {\leftmargin \leftmargini \topsep 4\p@ plus2\p@ minus2\p@ \parsep 2\p@
 plus\p@ minus\p@ \itemsep \parsep }\belowdisplayskip \abovedisplayskip invalid
 in math mode on input line 17.

LaTeX Font Warning: Command \relax \GenericWarning {(Font)              }{LaTeX
 Font Warning: Command \relax \fontsize {9}{11}\selectfont \abovedisplayskip 8.
5\p@ plus3\p@ minus4\p@ \abovedisplayshortskip \z@ plus2\p@ \belowdisplayshorts
kip 4\p@ plus2\p@ minus2\p@ \def \leftmargin \leftmargini \parsep 4\p@ plus2\p@
 minus\p@ \topsep 8\p@ plus2\p@ minus4\p@ \itemsep 4\p@ plus2\p@ minus\p@ {\lef
tmargin \leftmargini \topsep 4\p@ plus2\p@ minus2\p@ \parsep 2\p@ plus\p@ minus
\p@ \itemsep \parsep }\belowdisplayskip \abovedisplayskip invalid in math mode}
\fontsize {9}{11}\selectfont \abovedisplayskip 8.5\p@ plus3\p@ minus4\p@ \above
displayshortskip \z@ plus2\p@ \belowdisplayshortskip 4\p@ plus2\p@ minus2\p@ \d
ef \leftmargin \leftmargini \parsep 4\p@ plus2\p@ minus\p@ \topsep 8\p@ plus2\p
@ minus4\p@ \itemsep 4\p@ plus2\p@ minus\p@ {\leftmargin \leftmargini \topsep 4
\p@ plus2\p@ minus2\p@ \parsep 2\p@ plus\p@ minus\p@ \itemsep \parsep }\belowdi
splayskip \abovedisplayskip invalid in math mode on input line 17.

LaTeX Font Warning: Command \relax \fontsize {9}{11}\selectfont \abovedisplaysk
ip 8.5\p@ plus3\p@ minus4\p@ \abovedisplayshortskip \z@ plus2\p@ \belowdisplays
hortskip 4\p@ plus2\p@ minus2\p@ \def \leftmargin \leftmargini \parsep 4\p@ plu
s2\p@ minus\p@ \topsep 8\p@ plus2\p@ minus4\p@ \itemsep 4\p@ plus2\p@ minus\p@
{\leftmargin \leftmargini \topsep 4\p@ plus2\p@ minus2\p@ \parsep 2\p@ plus\p@
minus\p@ \itemsep \parsep }\belowdisplayskip \abovedisplayskip invalid in math
mode on input line 17.

The same warnings are repeated for the other line.

*Line (2) is formatted differently (see below) than lines (1) and (3), since the spaces between the commas and the elements are copied to the output instead of ignored. This is not that bad since I can always use the version in line (1), but I wonder if there is a way to simply ignore the spaces.

A: Issue 1. originates in the fact that your \ident macro is not protected against expansion (and \small from inside \ident is executed at a time when \texttt has not effectively made an exit from math mode, hence the first of the error). Using
\DeclareRobustCommand*{\ident}etc...

rather than
\newcommand*{\ident}

will instruct \protected@edef to not expand (too much) \ident.
The second issue 2. can be handled by the use of \ignorespaces prior to where an unwanted space could occur, here a space right after a comma which ends up inside \reserved: so \ignorespaces #1 in the definition of \ident or rather as you mentioned in a comment \ignorespaces\reserved in \ci.


text:
Q: Is it possible to inject javascript into a twitter feed to customize it's colors, font, etc.? Is it possible to create a safari extension to inject javascript that will alter twitter feed color, font, etc., once it's loaded on screen, or has twitter somehow disabled this?

A: Twitter cannot "somehow disable" that; if you inject Javascript/CSS into a page via an extension you can do whatever you want.

A: Yep. You can use Greasemonkey (for Firefox) or Tampermonkey (for Google Chrome) to create userscripts which are Javascript scripts that are executed on the pages that you specify.

*

*Here's a similar userscript I wrote for facebook: customizefb

*Here's one I wrote for StackOverflow: Who downvoted me?!

*And here are a bunch other people have already written for twitter.

You can always run custom Javascript directly from the browser console too if you don't want to install the userscript plugin.


text:
Q: Does the Stern-Gerlach experiment really suggest superposition? The Stern-Gerlach experiment is often cited as evidence of quantum superposition and there are some very simple explanations like this one https://www.youtube.com/watch?v=hkmoZ8e5Qn0  in which spin on one axis is compared to colour and spin on a perpendicular axis is compared to hardness.
The Stern Gerlach experiment relies on the inherent angular momentum of a silver atom giving it the properties of a tiny bar magnet.  When a beam of particles are fired through a large external magnet field, half of them are deflected up and half are deflected down, with respect to the orientation of the external field. This does not surprise me at all. I am reminded of a high school experiment in which iron filings sprinkled onto a piece of paper which is placed over a bar magnet to demonstrate the lines of force. I imagine something similar happening when a beam of atoms are fired through the Stern Gerlach apparatus; the particles align themselves with an external (UP/DOWN) magnetic field as they pass through it. $50$% go up and $50$% go down. When only the UP aligned particles exiting the apparatus are directed through a second apparatus, at right angles to the first apparatus (LEFT/RIGHT), $50$% go left and $50$% go right (that is up or down with respect to the alignment of the second apparatus).  This is no surprise to me at all because I imagine them simply realigning themselves to the magnetic field.
When ALL of the particles exiting the second apparatus (which are now aligned either left or right) are directed through a third apparatus, with the same orientation as the first (UP/DOWN), they ALL come out aligned UP. Admittedly this seems odd, but perhaps they have retained enough of their UP alignment to be forced back into an UP state.
In short, it looks like the the orientation of the external magnet field changes the orientation of the particles.  Why is this evidence of superposition? Does it not simply suggest that spin is changeable?

A: The last step is incorrect. The sequence is

*

*Atoms are split into $|\uparrow \rangle$ and $|\downarrow \rangle$, but only the $|\uparrow \rangle$-atoms are kept (=atoms possessing a spin which points in the $|\uparrow \rangle$ direction).

*Atoms are split into $|\leftarrow \rangle$  and $|\rightarrow \rangle$, but only the $|\leftarrow \rangle$ atoms are kept. Thus, one would expect that the spin of the atoms points $|\uparrow\rangle$ and $|\leftarrow \rangle$.

*If these atoms are again brought into a B-field which separates the atoms into $|\uparrow \rangle$ and $|\downarrow \rangle$, one would expect that we obtain only $|\uparrow \rangle$ atoms, because we kept only those atoms in step 1. However, we find that the atoms are again split into $|\uparrow \rangle$ and $|\downarrow \rangle$. Thus, we conclude that the second measurement scrambles the $|\uparrow \downarrow \rangle$ spin direction.

I wouldn't say that the Stern-Gerlach experiment is widely used to show the superposition principle. The superposition principle is not surprising in physics, because it is standard for linear systems. Instead, the Stern-Gerlach experiment shows that the two spin measurements (along $z$ and $y$) do not commutate: This means that the order of the measurement matters. Although this is not a big deal in every day life (e.g. it matters if you first open the window and then put out your head, or visa versa), this was a big deal in physics.
Minor detail: The magnetic field must be inhomogeneous. Else the atoms would not experience a force, because $F = \nabla E = \nabla (-\mu\cdot B_z) = -\mu \cdot \nabla B_z = 0$, if $B_z=const.$
Edit: I didn't watch the video before. Now that I watched part of the video I realise that your question is not about the original Stern-Gerlach experiment (sidemark: Please try to post a self containing question). The missing twist in your question is that step 2 is performed (the atoms are split into two components), but these components are not measured. Instead, the two components are recombined -- note the "mirrors" outside the "Hardness Box" (=spin measurement in $y$-direction) in the following image (taken from the linked video)

After recombining the two path we obtain the same result as if the "Hardness Box" were removed, because no measurement was taken. So, yes, in this context the experiment shows the superposition principle of pure states, because the result only makes sense if we argue that the atom has taken both path simultaneously. Only if this is the case no measurement was performed. However, I feel that this point is clearer in the quantum eraser experiment, which uses linear polarisers and the standard Young double slit setup, or other "which way" experiments.


text:
Q: How Do I copy the files and the Folder Tree to Remote Machine? I have two machines Server A and Server B, and I want to copy all the files and folder tree from Server A to Server B using PowerShell.
I have tried the command given below, but it copies only the files in the folder and does not create the folder tree:
Copy-Item E:\TestSource\* //TestDestination/ -recurse -force

A: If you have a source and a destination folder, you could use the following command:
robocopy $source $dest /e

If you need any more information about the command, you could use robocopy /?, or visit Robocopy documentation at Windows Server Technet, Robocopy.

A: Get-ChildItem \\server_a\c$ -Recurse | % {
   $dest = Join-Path -Path \\server_b\c$ -ChildPath (Split-Path $_.FullName -NoQualifier)

   if (!(Test-Path $dest))
   {
      mkdir $dest
   }

   Copy-Item $_.FullName -Destination $dest -Force
}

Using Split-Path with the -NoQualifier parameter will return the source path without the drive information. Join that with your destination path prefix and use the result to create the destination directory (if it does not exist) and perform the copy.

A: I would assume you have rights for the 2 servers
Get-ChildItem "\SERVER_A\C$" -Recurse | Copy-Item -Destination" \SERVER_B\C$"

A: Don't use PowerShell's Copy-Item cmdlet. Find a third-party mirroring/synchronization tool. We use RoboCopy.


text:
Q: Call directive controller methods from outside I write a directive that provide a tab functionality, I use latest version of AngularJS (v1).
In my directive I have a controller that expose an api to a children directives, the scope is isolated in all directives:
Parent Directive
scope: {},
controller: function($scope) {
   $scope.values = [];

   this.addValue = function(value) {
        $scope.values.push(value);
   }
}

Child Directive on link function
scope: {},
transclude: true,
template: '

',
replace: true,
link: function(scope, element, attr, parentCtrl)
{
    parentCtrl.addValues('test')
}

In child directive I have a custom html with own controller:
TestCtrl
function TestCtrl($scope){
    var vm = this;
    ... other logic
}

Implementation
<parent>
   <child>

          <button ng-click="addValues('new_test')"></button>

   </child>
</parent>

I need to call "addValues" method (inside directive controller) on click on my button.
How to organise the code to make this?

A:

var module = angular.module('app', []);

module.controller('root', function ($scope) {
    $scope.test = function () {
        console.log('i am clicked');
    }
});

module.component('child', {
    template: '<button type="button" data-ng-click="$ctrl.click()">Click me</button>',
    controller: myController,
    bindings: {
        onClick: '&'
    }
});

function myController() {
    var ctrl = this;
    ctrl.click = function () {
        this.onClick();
    }
}

        <child data-on-click="test()"></child>

It is just an example
Here you can read more.
Hope this helps.
MAy be it will be usefull to read about angular's best practice here


text:
Q: Invertibility Proof Suppose $A$ is a square matrix that satisfies $A^2=A$. Show that $(I-A)^2=I-A$ and $2A-I$ is invertible and its own inverse.
$(I-A)^2$
$=I^2-2A+A^2$
=$I-2A+A^2$
=$I-2A+A$
$=I-A$
Not sure how to show invertibility for 2A-I, I know you need to show $AA^{-1}=I$ to show invertibility but not sure how to get there.

A: $$
(2A-I)(2A-I)=4A^{2}-4A+I=4(A^{2}-A)+I
$$
Since $A^{2}=A$ we have that
$$
(2A-I)(2A-I)=I,
$$
and therefore $(2A-I)$ is invertible, because it is its own inverse.


text:
Q: Why htaccess isn't working with pretty links Here's my current code:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ /go/redirect.php?slug=$1 [L]

This file is located at http://example.com/go/.htaccess
It is working correctly when people visit this link:
http://example.com/go/test

But not when it has a trailing slash like this:
http://example.com/go/test/

When the trailing slash exists, they are being redirected here for some reason:
http://example.com/test

How can I make this work with and without trailing slashes at the end of the URL?

A: Try with below,
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ /go/redirect.php?slug=$1 [L]


text:
Q: I get Object Reference not set to an instance of an object while invoking SetExpressCheckout method I have been facing this issue from a long time and I really need help with this. I am trying to invoke Paypal SetExpressCheckout method. But I get the error in the very first line. I have checked all the mandatory fields and I am sure that I am not passing any null values in mandatory field. I have a Paypal developer account whose API credentials I am using.
[ // Configuration map containing signature credentials and other required configuration.
            // For a full list of configuration parameters refer in wiki page
            // [https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters]
        // Create the PayPalAPIInterfaceServiceService service object to make the API call
        PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap);

        SetExpressCheckoutRequestType setExpressCheckoutReq = new SetExpressCheckoutRequestType();
        SetExpressCheckoutRequestDetailsType details = new SetExpressCheckoutRequestDetailsType();

        // (Optional) Email address of the buyer as entered during checkout.
        // PayPal uses this value to pre-fill the PayPal membership sign-up portion on the PayPal pages.
        // Character length and limitations: 127 single-byte alphanumeric characters
        details.BuyerEmail = buyerEmail;
        details.ReturnURL = returnUrl;
        details.CancelURL = cancelUrl;

        // Fix for release
        // NOTE: Setting this field overrides the setting you specified in your Merchant Account Profile
        // Indicates whether or not you require the buyer's shipping address on
        // file with PayPal be a confirmed address. For digital goods,
        // this field is required, and you must set it to 0. It is one of the following values:
        //  0 – You do not require the buyer's shipping address be a confirmed address.
        //  1 – You require the buyer's shipping address be a confirmed address.
        //  Note:
        //  Setting this field overrides the setting you specified in your Merchant Account Profile.
        //  Character length and limitations: 1 single-byte numeric character

        details.ReqConfirmShipping = ReqConfirmShipping;

        // (Optional) Determines whether or not the PayPal pages should
        //display the shipping address set by you in this SetExpressCheckout request,
        // not the shipping address on file with PayPal for this buyer. Displaying
        // the PayPal street address on file does not allow the buyer to edit that address.
        // It is one of the following values:
        //  0 – The PayPal pages should not display the shipping address.
        //  1 – The PayPal pages should display the shipping address.
        // Character length and limitations: 1 single-byte numeric character
        details.AddressOverride = addressoverride;
        details.NoShipping = noShipping;

        decimal itemTotal = 0.0M;
        decimal orderTotal = 0.0M;

        // Cost of item. This field is required when you pass a value for ItemCategory.
        //Split by |
        string amountItems = itemAmounts;

        // Item quantity. This field is required when you pass a value for ItemCategory.
        // For digital goods (ItemCategory=Digital), this field is required.
        // Character length and limitations: Any positive integer
        //Split by |
        string qtyItems = itemQuantities;

        // Item name. This field is required when you pass a value for ItemCategory.
        //Split by |
        string names = itemNames;

        List<PaymentDetailsItemType> lineItems = new List<PaymentDetailsItemType>();
        if (itemNames.Contains('|'))
        {
            string[] INames = itemNames.Split('|');
            string[] IQtys = itemQuantities.Split('|');
            string[] IAmts = itemAmounts.Split('|');

            for (int i = 0; i < INames.Length; i++)
            {
                PaymentDetailsItemType item = new PaymentDetailsItemType();
                BasicAmountType amt = new BasicAmountType();

                // PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables.
                amt.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currencyCode);
                amt.value = IAmts[i];
                item.Quantity = Convert.ToInt32(Convert.ToDecimal(IQtys[i]));
                item.Name = INames[i];
                item.Amount = amt;

                // Indicates whether an item is digital or physical. For digital goods, this field is required and must be set to Digital. It is one of the following values:
                // 1. Digital
                // 2. Physical
                // By default its Physical for us
                item.ItemCategory = ItemCategoryType.PHYSICAL;
                itemTotal += Convert.ToDecimal(IQtys[i]) * Convert.ToDecimal(IAmts[i]);
                lineItems.Add(item);
            }
        }
        else
        {
            PaymentDetailsItemType item = new PaymentDetailsItemType();
            BasicAmountType amt = new BasicAmountType();

            // PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables.
            amt.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currencyCode);
            amt.value = itemAmounts;
            item.Quantity = Convert.ToInt32(Convert.ToDecimal(itemQuantities));
            item.Name = itemNames;
            item.Amount = amt;

            // Indicates whether an item is digital or physical. For digital goods, this field is required and must be set to Digital. It is one of the following values:
            // 1. Digital
            // 2. Physical
            // By default its Physical for us
            item.ItemCategory = ItemCategoryType.PHYSICAL;
            itemTotal += Convert.ToDecimal(itemQuantities) * Convert.ToDecimal(itemAmounts);
            lineItems.Add(item);
        }

        // (Optional) Item sales tax.
        // Note: You must set the currencyID attribute to one of
        // the 3-character currency codes for any of the supported PayPal currencies.
        // Character length and limitations: Value is a positive number which cannot exceed $10,000 USD in any currency.
        // It includes no currency symbol. It must have 2 decimal places, the decimal separator must be a period (.),
        // and the optional thousands separator must be a comma (,).
        //if (salesTax != string.Empty)
        //{
        //    item.Tax = new BasicAmountType((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]), parameters["salesTax"]);
        //}

        orderTotal += itemTotal;

        List<PaymentDetailsType> payDetails = new List<PaymentDetailsType>();
        PaymentDetailsType paydtl = new PaymentDetailsType();

        // How you want to obtain payment. When implementing parallel payments,
        // this field is required and must be set to Order.
        // When implementing digital goods, this field is required and must be set to Sale.
        // If the transaction does not include a one-time purchase, this field is ignored.
        // It is one of the following values:
        // Sale – This is a final sale for which you are requesting payment (default).
        // Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture.
        // Order – This payment is an order authorization subject to settlement with PayPal Authorization and Capture.
        // BY DEFAULT THIS IS SALE
        paydtl.PaymentAction = (PaymentActionCodeType)Enum.Parse(typeof(PaymentActionCodeType), paymentType);

        // (Optional) Total shipping costs for this order.
        // Note:
        // You must set the currencyID attribute to one of the 3-character currency codes
        // for any of the supported PayPal currencies.
        // Character length and limitations:
        // Value is a positive number which cannot exceed $10,000 USD in any currency.
        // It includes no currency symbol.
        // It must have 2 decimal places, the decimal separator must be a period (.),
        // and the optional thousands separator must be a comma (,)
        if (shipTotal != string.Empty)
        {
            BasicAmountType shippingTotal = new BasicAmountType();
            shippingTotal.value = shipTotal.Trim();
            shippingTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currencyCode);
            orderTotal += Convert.ToDecimal(shipTotal.Trim());
            paydtl.ShippingTotal = shippingTotal;
        }

        // (Optional) Total shipping insurance costs for this order.
        // The value must be a non-negative currency amount or null if you offer insurance options.
        // Note:
        // You must set the currencyID attribute to one of the 3-character currency
        // codes for any of the supported PayPal currencies.
        // Character length and limitations:
        // Value is a positive number which cannot exceed $10,000 USD in any currency.
        // It includes no currency symbol. It must have 2 decimal places,
        // the decimal separator must be a period (.),
        // and the optional thousands separator must be a comma (,).
        // InsuranceTotal is available since version 53.0.

        //if (parameters["insuranceTotal"] != string.Empty)
        //{
        //    paydtl.InsuranceTotal = new BasicAmountType((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]), parameters["insuranceTotal"]);
        //    paydtl.InsuranceOptionOffered = "true";
        //    orderTotal += Convert.ToDecimal(parameters["insuranceTotal"]);
        //}

        // (Optional) Total handling costs for this order.
        // Note:
        // You must set the currencyID attribute to one of the 3-character currency codes
        // for any of the supported PayPal currencies.
        // Character length and limitations: Value is a positive number which
        // cannot exceed $10,000 USD in any currency.
        // It includes no currency symbol. It must have 2 decimal places,
        // the decimal separator must be a period (.), and the optional
        // thousands separator must be a comma (,).

        //if (parameters["handlingTotal"] != string.Empty)
        //{
        //    paydtl.HandlingTotal = new BasicAmountType((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"]), parameters["handlingTotal"]);
        //    orderTotal += Convert.ToDecimal(parameters["handlingTotal"]);
        //}

        // (Optional) Sum of tax for all items in this order.
        // Note:
        // You must set the currencyID attribute to one of the 3-character currency codes
        // for any of the supported PayPal currencies.
        // Character length and limitations: Value is a positive number which
        // cannot exceed $10,000 USD in any currency. It includes no currency symbol.
        // It must have 2 decimal places, the decimal separator must be a period (.),
        // and the optional thousands separator must be a comma (,).
        if (salesTax != string.Empty)
        {
            paydtl.TaxTotal = new BasicAmountType((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currencyCode), salesTax);
            orderTotal += Convert.ToDecimal(salesTax);
        }

        // (Optional) Description of items the buyer is purchasing.
        // Note:
        // The value you specify is available only if the transaction includes a purchase.
        // This field is ignored if you set up a billing agreement for a recurring payment
        // that is not immediately charged.
        // Character length and limitations: 127 single-byte alphanumeric characters
        //if (parameters["orderDescription"] != string.Empty)
        //{
        //    paydtl.OrderDescription = parameters["orderDescription"];
        //}

        BasicAmountType itemsTotal = new BasicAmountType();
        itemsTotal.value = Convert.ToString(itemTotal);

        // PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables.
        itemsTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currencyCode);

        paydtl.OrderTotal = new BasicAmountType((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currencyCode), Convert.ToString(orderTotal));
        paydtl.PaymentDetailsItem = lineItems;

        paydtl.ItemTotal = itemsTotal;

        #region shipping address

        AddressType shippingAddress = new AddressType();
        shippingAddress.Street1 = shipStreet;
        shippingAddress.CityName = shipCity;
        shippingAddress.StateOrProvince = shipState;
        shippingAddress.Country = CountryCodeType.US;
        shippingAddress.PostalCode = shipPostalcode;
        shippingAddress.Name = shipName;
        paydtl.ShipToAddress = shippingAddress;
        #endregion

        details.PaymentDetails.Add(paydtl);

        setExpressCheckoutReq.SetExpressCheckoutRequestDetails = details;
        SetExpressCheckoutReq expressCheckoutReq = new SetExpressCheckoutReq();
        expressCheckoutReq.SetExpressCheckoutRequest = setExpressCheckoutReq;

        SetExpressCheckoutResponseType response = null;
        try
        {

            response = service.SetExpressCheckout(expressCheckoutReq);
        }
        catch (System.Exception ex)
        {
            //contextHttp.Response.Write(ex.Message);
            return null;
        }

        Dictionary<string, string> responseValues = new Dictionary<string, string>();
        responseValues.Add("Acknowledgement", response.Ack.ToString().Trim().ToUpper());
        if (response.Ack.ToString().Trim().ToUpper() == "SUCCESS")
        {
            responseValues.Add("Token", response.Token.ToString().Trim());
            responseValues.Add("TimeStamp", response.Timestamp.ToString().Trim());
        }
        return responseValues;

    }][1]

I am also attching screenshots of the error I am getting. I am using 1.3.5 version of PaypalCoreSDK. Any help would be really appreciated.
Exception:
PayPal.APIService.MakeRequestUsing(IAPICallPreHandler apiCallHandler)
at PayPal.BasePayPalService.Call(IAPICallPreHandler apiCallHandler)
at PayPal.PayPalAPIInterfaceService.PayPalAPIInterfaceServiceService.SetExpressCheckout(SetExpressCheckoutReq setExpressCheckoutReq, String apiUserName)
at PayPal.PayPalAPIInterfaceService.PayPalAPIInterfaceServiceService.SetExpressCheckout(SetExpressCheckoutReq setExpressCheckoutReq)      upvote
at gs_PayPalECAPI.PayPalProcess.SetExpressCheckout_Ecommerce(Dictionary`2 configurationMap, String returnUrl, String cancelUrl, String currencyCode, String paymentType, String ReqConfirmShipping, String addressoverride, String noShipping, String buyerEmail, String itemAmounts, String itemQuantities, String itemNames, String salesTax, String shipTotal, String shipStreet, String shipState, String shipCity, String shipPostalcode, String shipName)

A: Finally got a solution and code working. There was nothing that was being passed as null, but yes there were things missing that I didn't know have to be done.
Firstly while implementing this one should be using .Net Framework 4.5 or above.
Secondly following things must be set before invoking the SetExpressCheckout method:
System.Net.ServicePointManager.Expect100Continue = true;
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
System.Net.ServicePointManager.DefaultConnectionLimit = 9999;