text:
Q: Linkbutton to open Windows Explorer from Gridview I have a link in a Gridview that I want opened in Windows Explorer (or explorer.exe).
<asp:GridView  ID="GridView1"runat="server" >
   <Columns>
       <asp:TemplateField>
           <ItemTemplate>
               <asp:LinkButton ID="DeploymentLocation" runat="server" CommandName="OpenLink"
                   Text='<%# Eval("DeploymentLocation") %>' CommandArgument='<%# Eval("DeploymentLocation") %>'  />
           </ItemTemplate>
        </asp:TemplateField>
   </Columns>

and in codebehind I have this:
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
          Process.Start("explorer.exe", "/n," + e.CommandArgument.ToString());
    }

Obviously this doesn't work as Process.Start only works if I have full permissions, etc, etc.  I heard that I can use Javascript to do this, but haven't succeeded so far.
Basically, what I want is the exact link that is displayed in the grid to be opened when clicked.  Any help would be much appreciated!
Thanks!

A: As you have found out starting processes on the client computer from a web site is not possible. You could redirect though to this web page:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    Response.Redirect(e.CommandArgument.ToString());
}

Another option is to use an ActiveX control but this will work only on Internet Explorer.

A: (1) Please don't use javascript to start a local executable file (especially explorer.exe which is an important system file) because sometimes the firewall/anti-virus software will consider your action dangerous/baleful.
(2) Anyway executing a client user's programme via your website/web application is always not so friendly. I guess you want to execute "explorer.exe" to open a window to browse the local directory? If so, you can simulate a windows explorer window in your web page.

A: I managed to resolved it easily:
<ItemTemplate>
   <asp:HyperLink Text='<%# Eval("DeploymentLocation") %>'  id="DeploymentLocation" runat="server" Target="_blank" NavigateUrl='<%# "file:///" + Eval("DeploymentLocation").ToString() %>' ></asp:HyperLink>
</ItemTemplate>


text:
Q: How to make Ruby on Rails RESTful routes pretty and human friendly? With Ruby on Rails, REST is a great concept in terms of simplifying things for the developer and making resources easy for machines to access, but it also produces phenomenally ugly URLs for humans.
For example, using the popular RESTful Authentication plugin to handle user login and authentication, it creates two controllers for authentication and authorization, users and sessions.  This is because user represents the long term resources associated with a user, such as the login and password, while a session represents the login info associated with a login session such as the cookie resources.  Thus, the login url for a site would be site.com/sessions/new.
By default, it also creates a route to help this:
map.login '/login', :controller => 'sessions', :action => 'new'
However, this is really only a kludge, because on submit in order for the routes to work right, the form it creates uses <% form_tag session_path do -%>.  This causes the post of the form to go to SessionsController#create, but if the form submission fails (such as due to bad credentials) the user's browser is left at site.com/session, which looks really awkward.  Worse yet, if the user manually were to enter that url, it is unavailable unless I define an index method.  If I change the form_tag to read <% form_tag login_path do -%> then this results in POSTS to SessionsController#new, which completely messes up the REST.
How can I have consistent and reasonable looking URLs with REST?  Overall, I really am tempted by the convenience of using REST, but it seems pretty wrong that this should produce (negative) changes visible to the user.

A: I think on the whole REST provides consistent, intuitive and user-friendly URLs, particularly when it comes to retrieving resources (GET) which is usually what a user wants to do (the pages they most often bookmark).  Usually, you are dealing with URLs like
/posts/34
/articles/456/edit
/companies

You've hit on an isolated (although unavoidable, and therefore very annoying) exception, to which I have never seen a really satisfying solution, other than using AJAX.  The problem is that RESTful routes shine in applications that have carefully thought out domains, where the resources on the backend make sense even to the user (like the examples above) whereas session management is inherently obscure to the user.
If you're that unhappy with the /sessions URL, why not alias /login/submit to /sessions/create?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Start-Process passing a hashtable in the ArgumentList Consider the following situation:
Content MyScript.ps1:
Param (
    [String]$CountryCode,
    [String]$FilesPath,
    [String]$KeepassDatabase,
    [String]$KeepassKeyFile,
    [String]$EventLog = 'HCScripts',
    [String]$EventSource,
    [HashTable]$CitrixFarm = @{'Server1' = '6.5'}
)

$CountryCode
$FilesPath
$KeepassDatabase
$KeepassKeyFile
$EventLog
$EventSource
$CitrixFarm

Content of the Caller.ps1:
Param (
    $FilesPath = ".\MyScript.ps1",
    $EvenntLog = 'Test',
    $CountryCode = 'BNL',
    $KeepasDatabase,
    $KeepasKeyFile
)

$Arguments = @()
$Arguments += "-EventSource ""$AppName"""
$Arguments += "-EventLog ""$EventLog"""
$Arguments += "-FilesPath ""$((Get-Item $FilesPath).FullName)"""
$Arguments += "-CountryCode ""$CountryCode"""
$Arguments += "-KeepassDatabase ""$((Get-Item $KeepasDatabase).FullName)"""
$Arguments += "-KeepassKeyFile ""$((Get-Item $KeepasKeyFile).FullName)"""
$Arguments += "-CitrixFarm $CitrixFarm"

$StartParams = @{
    Credential   = $Credentials
    ArgumentList = "-File ""$ScriptPath"" -verb runas" + $Arguments
    WindowStyle  = 'Hidden'
}
Start-Process powershell @StartParams

We can't seem to find a way to pass in the [HashTable] for the argument $CitrixFarm. How is it possible to add that argument. or pass it on to the script called by Start-Process with elevated permissions and in a new PowerShell session?
When omitting the parameter $CitrixFarm all is working fine. So the problem really is with passing the HashTable.

A: You should pass the hashtable in PowerShell object notation, just as you would if running the script from a PowerShell window.
How you construct the string is up to you.
You could

*

*use a string template

*use a quick-and-dirty call "@$((ConvertTo-Json $CitrixFarm -Compress) -replace ':','=')"

*use a function to convert the hashtable object.

Below is effectively what you are trying to achieve.
$Arguments = @()
...
$Arguments += "-CitrixFarm @{'Server1' = '6.5'}"

$StartParams = @{
    Credential   = $Credentials
    ArgumentList = "-File ""$ScriptPath"" -verb runas" + $Arguments
    WindowStyle  = 'Hidden'
}
Start-Process powershell @StartParams

Source: A Better ToString() Method for Hash Tables


text:
Q: jQuery AJAX Syntax for getting response I'm working on a simple AJAX request that calls a URL when a button is clicked. I've got the basics working successfully so that the GET request is made to the URL when the button is clicked and I've confirmed the GET request was made by checking the logs at the other server. Here's the simple request script:

< script >
  $("#callContact1").click(function() {

    $.ajax({

      url: "https://www.server.com?type=makecall",
      data: {},
      method: "GET",
      success: function(data) {

      }

    });

  }); <
/script>

I'm now trying to show the response from the GET request in a hidden div in my html:

  Callback Response

I've modified the script as follows:

< script >
  $("#callContact1").click(function() {

      $.ajax({

        url: "https://www.server.com?type=makecall",
        data: {},
        method: "GET",
        success: function(data) {
          $('#ajaxResponse').html(data);
          $("#ajaxResponse").show();

        }
      });

      fail(function(xhr) {
          var httpStatus = (xhr.status);
          var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus;
          console.log('ajaxError: ' + ajaxError);
          //make alert visible
          $('#ajaxResponse').html(ajaxError);
          $("#ajaxResponse").show();
        }

      }); <
    /script>

but I'm running into syntax errors which I can't seem to overcome. Basically I want to insert the response from the GET request which will include a simple text response for a successful request or an error if one was encountered.

A: fail method is not defined in your code. You can use deferred done/fail methods to attach success and fail callbacks:

A: Use .then() or jQuery deferred.done() if you use .fail(), which can be chained to .then(). Also closing </script> should on same line.


text:
Q: Converting MySql DateTime type into something more friendly I have a Java web app that reads a MySql db and returns DateTime fields.  What is the best way to convert the DateTime fields returned in the resultset into something more readable?
Currently the DateTime fields print as:
2008-12-14 16:30:00
but I would like something more user friendly like:
14 Dec 2008 at 16:30
I am populating an ArrayList with these dateTimes from a pojo.  I would like to format them before adding to the arrayList, so then I can just print the contents of the arrayList in the JSP.

A: Another option is to use the JSTL. The formatting library makes it easy to display a date in any format and it is i18n aware. The advantage is that you can leave the date as a Date object and manipulate it as such but only convert it when you need to display. The format tag will look like this:
<fmt:formatDate value="${myDate}" dateStyle="MEDIUM"/>

Like I said above, one big advantage is that it is i18n aware so you can display the date in a localized format.
The full syntax is:
 <fmt:formatDate value="expression"
     timeZone="expression"
     type="field" dateStyle="style"
     timeStyle="style"
     pattern="expression"
     var="name" scope="scope"/>

A: Mysql date_format()
mysql> select date_format(now(),'%d %b %Y at %H:%i') as formated_date;
+----------------------+
| formated_date        |
+----------------------+
| 20 Dec 2008 at 10:56 |
+----------------------+

A: I would prefer to use a simpleDateFormat in the Java code so my code is not bound to any database function (weak reason, I know).
    Date date = ...
    DateFormat df = new SimpleDateFormat("dd MMM yyyy 'at' HH:mm");  // Locale?
    String text = df.format(date);

Be warned that SimpleDateFormat is not thread safe. From the documentation:

Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

A: What kind of abstraction layer do you have over the database? It looks like a simple case of subclassing whatever you're using as the field class, and adding a method for your format.

A: I'd recommend the tag formatting option, because you have the real data (dates/times) and you format at page level where format is relevant (and you know.. by example, locale to apply).
If you anyway want to format it and put the strings into a List use java.text.SimpleDateFormat as Carlos Heuberger says.


text:
Q: JPA Hibernate merge performs insert instead of update I have a simple test, where I am trying to update the object, but merge seems to be performing an insert instead of update.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/app-context.xml","classpath:spring/testdb-context.xml"})
public class UserJPATest {
@Test
public void testUpdate() throws Exception {
    System.out.println("update");

    User entity = ObjectManager.USER_DAO.findById(3L);
    entity.setUsername("harryUpdate");

    ObjectManager.USER_DAO.update(entity);

    User selEntity = ObjectManager.USER_DAO.findById(3L);
    Assert.assertEquals(entity.getUsername(),selEntity.getUsername());
}

}
This is my update method
@Override
@Transactional(propagation= Propagation.REQUIRES_NEW)
public T update(T entity) throws Exception {
    try {
        T merged = entityManager.merge(entity);
        return merged;
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception(e);
    }
}

Update to code
@Override
@Transactional(propagation= Propagation.REQUIRES_NEW)
public T update(T entity) throws Exception {
    try {
        T merged = null;
        BaseEntity baseEntity = null;
        if(entity instanceof BaseEntity){
            baseEntity = (BaseEntity)entity;
            merged = entityManager.find(entityClass, baseEntity.getId());
        }
        merged = entityManager.merge(entity);
        entityManager.flush();
        return merged;
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception(e);
    }
}

Now I get the following error Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly

A: I had a version column which was not set when seed data was inserted into database. Hence all the problems with update and delete

A: Merge will update the row ONLY IF it founds the id in the database, so if you create a new object and forgot to set its ID to the same ID of the desired row, it will try to insert a new one. In case your database table doesn't have any unique field, probably this insert will be successful as there will be no sql error.
I was able to update the desired row once I set the new object with the ID of that row.


text:
Q: Mac OS Django-admin startproject mysite receives syntax error I'm trying to follow the tutorial on https://docs.djangoproject.com/en/3.1/intro/tutorial01/ and have made it to the step where you are supposed to run django-admin startproject mysite in the command line.
I have tried running the followings:
django-admin startproject mysite

django-admin.py startproject mysite

django-admin startproject.py mysite

$ django-admin startproject mysite

and
$ django-admin.py startproject mysite

and all of them receive
SyntaxError: invalid syntax

either with a ^ under the "t" in "startproject" or under the $ when I've tried that.
I've searched through about ten different posts trying to figure out how to proceed, and none of the answers provided have worked for me. They all continue to receive
SyntaxError: invalid syntax

I would really appreciate any insight into why this is happening and how to fix it.

A: What did you get as a response when you typed python -m django --version in terminal?
Given that you have django installed properly, django-admin startproject *name of project* is the correct syntax. (the first line you listed is correct).
Perhaps try to re-install django and try again. You can access the docs for installing here


text:
Q: Maven is not running any test I am writing the unit test for the first time. In order to create the test file in IntelliJ, I created a *Test.java by using shortcut [https://www.jetbrains.com/help/idea/create-tests.html]. Now when I am trying to run mvn test it is not running any tests.
pom.xml
      <dependency>
          <groupId>org.junit.jupiter</groupId>
          <artifactId>junit-jupiter</artifactId>
          <version>5.6.2</version>
          <scope>test</scope>
      </dependency>

*

*Few answers from SO I found was to check the name. I checked and the name of the file is <classNametoTest>Test.java and I can also see the JUnit symbol on the file.

*I have another folder named test (in root directory). In order to verify, I tried to rename the folder and did mvn clean package -> mvn test. Not tests run.

*Test folder is there in src as well [https://stackoverflow.com/questions/6178583/maven-does-not-find-junit-tests-to-run]

A: can you check if you have @Test is imported from org.junit.jupiter.api.Test


text:
Q: GOPATH variable not persisting I'm setting the $GOPATH using export GOPATH=$HOME/go as per GoLang's instructions and everything works fine. When I echo out the path it shows what I set it to.
However, if I close my terminal and re-open it the $GOPATH is no longer what I set it to.
I guess my question is how can I make the new $GOPATH persist?

A: Open you terminal (you can use any text editor, like: gedit, vi or vim).
   gedit ~/.bashrc

go to the end of file and edit with the following lines:
   export GOPATH=$HOME/go
   export PATH=$PATH:$GOPATH/bin

Assuming that /usr/lib/go is your GOROOT
to know your GOROOT you can do:
   go env

or
   which go

A: Just so you know this should be answered in general form on SuperUser or something other than here. Regardless here's the steps to make it so this is always set in your session;
cd ~
vi .bashrc
//page down, end whatever to get to bottom of file if it's not new
press i to insert, add export GOPATH=$HOME/go
press escape
:w
:q

A: To make Felix's answer more simpler you could run the below commands while not breaking your head with vim
echo "export GOPATH=$HOME/go" >> ~/.bash_profile
echo "export PATH=$GOPATH/bin:$PATH" >> ~/.bash_profile
source ~/.bash_profile


text:
Q: Using DateTime With input from a textbox.text I have this code that when executed gives me 74 Days, which is correct, but the date for oldDate has to come from a TextBox.  Does anyone know how to do this as the DateTime only takes three integers.
private void myButton_Click(object sender, RoutedEventArgs e)
{
     string  myDate = myTextBox.Text;

     DateTime oldDate = new DateTime(2013, 6, 5);

     DateTime newDate = DateTime.Now;

     // Difference in days, hours, and minutes.
     TimeSpan ts = oldDate - newDate;
     // Difference in days.
     int differenceInDays = ts.Days;

     differenceInDays = ts.Days;

     myTextBlock.Text = differenceInDays.ToString();
}

A: You can parse the date from the user:
string  myDate = myTextBox.Text;

DateTime oldDate;
if (!DateTime.TryParse(myDate, out oldDate))
{
   // User entered invalid date - handle this
}

// oldDate is set now

That being said, depending on the UI framework, a more appropriate control (ie: the DateTimePicker from the extended WPF toolkit, etc) may be easier to use.

A: From your code you have to obtain oldDate from myTextBox, which you have stored in myDate string variable. You can convert it to datetime
oldDate=Convert.ToDateTime(myDate);

But since it might cause exception use following
`DateTime myyDateTime;if(DateTime.TryParse(myDate, out myDateTime){//use your date difference code here}


text:
Q: valence desire 2 learn profile image upload error 404 I'm trying to upload an image profile using the api but I'm getting a Unknown: NOT_FOUND 404 error. the call I am using is POST /d2l/api/lp/1.3/profile/(profileId)/image, I am passing the content type, length and filename (profileImage). I'm passing the image as a dataStream. I've reduced the size of the image as well. Any ideas?
                public static void UploadFilesToRemoteUrl(string file, string logpath, NameValueCollection nvc, ID2LUserContext userContext, string accion)
    {
        var uri = userContext.CreateAuthenticatedUri(accion, "POST");
        string boundary = "bde472ff1f1a46539e54e655857c27c1";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.ContentType = "multipart/form-data; boundary=" +
        boundary;
        request.Headers.Add("Accept-Encoding", "gzip, deflate, compress");
        request.Method = "POST";
        request.KeepAlive = true;

        request.Proxy.Credentials = new NetworkCredential(Constantes.UsuarioProxy, Constantes.PasswordProxy, Constantes.DominioProxy);

        Stream memStream = new System.IO.MemoryStream();

        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
        boundary + "\r\n");

        string formdataTemplate = "\r\n--" + boundary +
        "\r\nContent-Disposition: form-data; name=\"profileImage\"; filename=\"profileImage.png\" \r\nContent-Type: image/png\r\n";

        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formdataTemplate);
        memStream.Write(formitembytes, 0, formitembytes.Length);

        // Read image File *************************************************************
        FileStream fileStream = new FileStream(file, FileMode.Open,FileAccess.Read);
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            memStream.Write(buffer, 0, bytesRead);
        }
        fileStream.Close();
        //*****************************************************************************
        //*********** End Read image file *********************************************

        memStream.Write(boundarybytes, 0, boundarybytes.Length);

        request.ContentLength = memStream.Length;
        Stream requestStream = request.GetRequestStream();
        memStream.Position = 0;
        byte[] tempBuffer = new byte[memStream.Length];
        memStream.Read(tempBuffer, 0, tempBuffer.Length);
        memStream.Close();
        requestStream.Write(tempBuffer, 0, tempBuffer.Length);
        requestStream.Close();

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
        string responseValence = reader.ReadToEnd();

    }

A: It seems most likely that the 404 is coming either from

*

*The API route you're providing (and the back-end service cannot match your API route to a handler method): this could be because of an incorrect profileId value, or a mis-typed route, or an incorrect API version number in the route, and so forth.

*That for some reason the back-end service is accepting your profile image data but then unable to assign it to the user's profile.
Here's a capture of some request/response details of what an uploaded profile image packet looks like. When uploading a profile image to "my profile", I use an HTTP header that gets built from these values:
{'Content-Length': '75143',
 'User-Agent': 'python-requests/2.2.1 CPython/3.3.3 Darwin/12.5.0',
 'Content-Type': 'multipart/form-data; boundary=bde472ff1f1a46539e54e655857c27c1',
 'Accept': '*/*',
 'Accept-Encoding': 'gzip, deflate, compress'}

Note that this is a multipart/form-data content body, with a boundary marker around a single body part. The body content for the request looks like this:
--bde472ff1f1a46539e54e655857c27c1
Content-Disposition: form-data; name="profileImage"; filename="profile_img-225x225.png"

[actual PNG bytes here]
--bde472ff1f1a46539e54e655857c27c1--

The name property in the Content-Disposition header must be profileImage, and the filename property should be named after the local filename you're using to provide the content (so, as far as the back-end service is concerned, it's value is not particularly relevant).
Finally, there are particular role permissions at play that permit a user to edit someone else's profile image, so you should ensure that your calling user context for the API call has permission to edit someone else's image.

A: Fixed. This code works correctly:
        public static void UploadFilesToRemoteUrl(byte[] profileImage, ID2LUserContext userContext, string accion)
    {
        //Reference:
        //action = "/d2l/api/lp/1.3/profile/" + profileIdentifier + "/image";

        //profileImage = the profileImage of user read from disk:
        /*
        FileStream fileStream = new FileStream(pictureLocalPath, FileMode.Open, FileAccess.Read);
        Byte[] img = new Byte[fileStream.Length];
        fileStream.Read(img, 0, Convert.ToInt32(img.Length));
        fileStream.Close();
        */

        var uri = userContext.CreateAuthenticatedUri(accion, "POST");
        string boundary = "bde472ff1f1a46539e54e655857c27c1";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.ContentType = "multipart/form-data; boundary=" +
        boundary;
        request.Headers.Add("Accept-Encoding", "gzip, deflate, compress");
        request.Method = "POST";
        request.KeepAlive = true;

        request.Proxy.Credentials = new NetworkCredential(Constantes.UsuarioProxy, Constantes.PasswordProxy, Constantes.DominioProxy);

        Stream memStream = new System.IO.MemoryStream();

        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
        boundary + "\r\n");

        string formdataTemplate = "\r\n--" + boundary +
        "\r\nContent-Disposition: form-data; name=\"profileImage\"; filename=\"profileImage.jpg\"\r\nContent-Type: image/jpeg;\r\n\r\n";

        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formdataTemplate);
        memStream.Write(formitembytes, 0, formitembytes.Length);

        //escribo el array de byte de la imagen
        memStream.Write(profileImage, 0, profileImage.Length);

        byte[] boundaryClose = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--");
        memStream.Write(boundaryClose, 0, boundarybytes.Length);

        StreamReader readerReq = new StreamReader(memStream);
        string stringReq = readerReq.ReadToEnd();

        request.ContentLength = memStream.Length;
        Stream requestStream = request.GetRequestStream();
        memStream.Position = 0;
        byte[] tempBuffer = new byte[memStream.Length];
        memStream.Read(tempBuffer, 0, tempBuffer.Length);
        memStream.Close();
        requestStream.Write(tempBuffer, 0, tempBuffer.Length);
        requestStream.Close();

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        if (response.StatusCode == HttpStatusCode.OK)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string responseValence = reader.ReadToEnd();
            response.Close();
        }
    }


text:
Q: Query to count two fields I am looking to do 2 counts on the data of a table with a grouping on a field.
Here is an example of data :

 sends_id | status | result
----------+--------+----------
 119      | er     | 7dccs11x
 119      | er     |
 120      | po     | 5bde48u1
 120      | pu     |
 121      | po     | a1d9tbg8

I try to do this :

*

*Count the number of lines with sends_id identical -> n_total

*Count the number of lines including status = "po" and result = non-empty value

What should give me this:

 sends_id | n_total | n_ok
--------------------+------
 119      | 2       | 0
 120      | 2       | 1
 121      | 1       | 1

I wrote this :

WITH a AS (
    SELECT
        sends_id,
        COUNT(sends_id) AS n_total,
        CASE WHEN status = 'po' THEN 1 ELSE 0 END AS po
    FROM resource
    GROUP BY sends_id, status
)
SELECT sends_id, sum(po) AS n_ok, n_total
FROM a
GROUP BY sends_id, n_total;

 sends_id | n_total | n_ok
--------------------+------
 119      | 2       | 0
 120      | 1       | 1
 121      | 1       | 1

What does not go is that the lines with 121 on 2 different statuses.
I do not see how to take into account this ...
An ideas?

A: What you want is called conditional aggregation.
select
  sends_id,
  count(*) as total,
  count(*) filter (where status = 'po') as po
from resource
group by sends_id
order by sends_id;


text:
Q: How to bind exit to a key? When I am using screen, every time I use kill, it prompts a confirmation and ask me whether to really kill (which I really do after pressing so many keys). To get around this I type exit instead. But can I bind a key to it?
bind key exit does not work...

A: What you can do is to bind a key to send "exit^M" to your shell session instead of producing kill command to the screen itself. Of course, this only works in case you have nothing else going on in the shell. For those occasions you might have to modify this example a bit, e.g. to send CTRLC followed by exit.
Add bind ^K stuff "exit^M" to your ~/.screenrc and re-evaluate it by CTRL+a : source ~/.screenrc.
After that you will be able to kill shell sessions having an empty commmand line waiting with CTRLaCTRLK (note the capital K there, you probably don't want to completely override the kill command of screen itself).


text:
Q: Help with proof that the expected value of $x_i$ is $\bar{X}$ I'm having a little trouble with the proof that the expected value of $x_i$ is $ \bar{X} $.
What I have is
$E[x_i]=\sum_{j=1}^{N}X_j Pr(x_i=X_j) $
Then,
$Pr(x_i=X_j) = 1/N $
This is the bit I can't understand, how does that probability evaluate to that value.
I know the denominator is how many ways you can choose n out N. I think that the numerator should be how many ways you can choose (n-1) out of (N-1). But I seem to have an extra n.
Any advice ?

A: Every $X_j$ is equally likely to be selected (this isn't true for every population, but it is a common situation [for example, a die, where 1, 2, 3, 4, 5, 6 are all equally likely to be thrown]). So since there are $N$ possible values, the probability of each is ${1 \over N}.$
So you have \begin{align}\mathrm E[x_i]&=\sum_{j=1}^N X_j\,\mathrm P[x_i=X_j]\\ &={1 \over N} \sum_{j=1}^N X_j\\ &={1 \over N} (N \bar{X})\\&= \bar{X}\;.\end{align}

A: If, as some of the comments have suggested, that $x_i$ is a single (discrete) random variable, and the $X_j$ are all the potential values that $x_i$ can take, then basically the definition of expectation of $x_i$ is $\mathbb{E}(x_i) := \sum_{j=1}^n X_j \mathbb{P}(x_i = X_j)$. However, in no way does this imply anything about the values that $\mathbb{P}(x_i = X_j)$ can take (other than that they are non-negative and must sum to unity over $j$)!! The probabilities $\mathbb{P}(x_i = X_j)$ define the distribution of the discrete random variable $x_i$, and since the expectation of $x_i$ is just a quantity associated with its distribution, then $\mathbb{E}(x_i)$ changes as the probabilities $\mathbb{P}(x_i = X_j)$ change.
Perhaps you're missing something from your question - maybe you've been given a question where you know that $\mathbb{E}(x_i)$ is fixed to be equal to a given value, and you're also given the values $X_j$, then it may be that you're asked to solve for all possible values of $\mathbb{P}(x_i = X_j)$?
Several comments:
1) Your use of capitals to represents values and lower-case to represent random variables is very confusing - mathematicians use the opposite convention.
2) Your use of the index $i$ is very confusing - it is not used anywhere (usefully) in your question. Come to think of it, your question mentions some combinatorial statement - perhaps you have written your question badly, in which case I urge you to rephrase your question. If this question was prompted by some other question that you're trying to solve, I would ask that original question.
================================================
EDIT in response to comment:
Ah, if you're trying to prove that the sample mean is unbiased estimator of the population mean, then let's start with only two random variables $x_1$ and $x_2$ (using your notation). We need to prove that the expectation operator is linear i.e. $\mathbb{E}(x_1 + x_2) = \mathbb{E}(x_1) + \mathbb{E}(x_2)$ (note that if this is the case, then it's trivial to extend this to the case of there being $n$ random variables - use induction). So to prove linearity (and letting the $X_1$ and $X_2$ are the possibles values that $x_1$ and $x_2$ can take, respectively):
$\begin{align}
\mathbb{E}(x_1 + x_2) &= \sum_{X_1, X_2} (X_1+X_2) \mathbb{P}(x_1 = X_1, x_2 = X_2) \\
                      &= \sum_{X_1} \sum_{X_2} \left[X_1 \mathbb{P}(x_1 = X_1, x_2 = X_2) + X_2 \mathbb{P}(x_1 = X_1, x_2 = X_2)\right] \\
&= \sum_{X_1} \sum_{X_2} X_1 \mathbb{P}(x_1 = X_1, x_2 = X_2) + \sum_{X_2} \sum_{X_1} X_2 \mathbb{P}(x_1 = X_1, x_2 = X_2) \\
&= \sum_{X_1} \left[ X_1 \sum_{X_2}  \mathbb{P}(x_1 = X_1, x_2 = X_2)\right] + \sum_{X_2} \left[ X_2\sum_{X_1}  \mathbb{P}(x_1 = X_1, x_2 = X_2)\right] \\
&= \sum_{X_1}X_1\mathbb{P}(x_1 = X_1) + \sum_{X_2}X_2\mathbb{P}(x_2 = X_2)\\
&= \mathbb{E}(x_1) + \mathbb{E}(x_2) \,\,\,\,\,\text{QED}
\end{align}$
From this, it should be easy to see that $\mathbb{E}(\bar{x})$ is equal to the population mean.


text:
Q: AngularJs view not updating when parent property is changed from child controller I'm trying to play around with extending controllers so the same code can be used in multiple places but extended with additional functionality where required. eg. when some functionality is available to some users but not others.
So I'm starting with a little experimentation with a very basic example. I have a simple controller and a more advanced controller that I extend with the simple controller. It all works so far, except when a function in the simple controller changes a property, the view doesn't update, although the property does update.
 var app = angular.module("myApp",  []);
app.controller("myCtrl", ['$scope', '$http', '$anchorScroll',
function($scope, $http, $anchorScroll)  {
    var vm=this;
    vm.base_property='this is the base';
    vm.baseFunction = function()
    {
        console.log('base function pressed');
        vm.base_property='base function pressed';
        console.log(vm.base_property);
    }
    }]);

    app.controller("myCtrl2", ['$scope', '$http', '$anchorScroll', '$controller',
function($scope, $http, $anchorScroll, $controller)  {
    var vm=this;
    angular.extend(vm, $controller("myCtrl", {
$scope: $scope
}));
        vm.extended_property='this is extended';
        vm.extendedFunction =function()
        {
            vm.extended_property = 'extended pressed';
        }
    }]);

base Property: {{cal.base_property}}

<button ng-click="cal.baseFunction()" >Base Function</button>

extended Property: {{cal.extended_property}}

<button ng-click="cal.extendedFunction()" >Extended Function</button>

So clicking the extended function button , the text in the view for cal.extended_property updates, but clicking the base function button, the console output indicates the function is run and that the base_property has been updated but the value in the view doesn't change
I tried added $scope.$apply() but that just throws an error Error: [$rootScope:inprog] http://errors.angularjs.org/1.6.4/$rootScope/inprog?p0=%24apply (not ideal anyway as the real script is a lot more complex and I didn't want to have to be running that every time the base controller changes a property)
If there's a better way to achieve what I'm trying to do that isn't too complicated, I'm open to that too. Essentially I have a controller and I want to, in some circumstances, add additional properties and methods to that controller and ideally have it function seemlessly as if it were all the 1 controller


text:
Q: Can't download file in IE7 but there isn't any issue in Firefox, Chrome, etc..? I have an script that receives an encrypted url and from that generates a download, the most critic par of the script is this:
$MimeType = new MimeType();
$mimetype = $MimeType->getType($filename);
$basename = basename($filename);
header("Content-type: $mimetype");
header("Content-Disposition: attachment; filename=\"$basename\"");
header('Content-Length: '. filesize($filename));
if ( @readfile($filename)===false ) {
  header("HTTP/1.0 500 Internal Server Error");
  loadErrorPage('500');
}

Downloads works as charm in any Browser except IE, I have seen problems related to 'no-cache' headers but I don't send anything like that, they talk about utf-8 characters, but there is not any utf-8 characters(and the $filename has not any utf-8 characteres neither).

A: I solved it by sending the headers
header('Pragma: public');
header('Cache-Control: max-age=0');

I didn't knew that session_start() send headers by it's own.
I found the answer in the comments section of: Error: Internet Explorer Cannot Download FileName from WebServer

A: This site has a problem similar to yours in IE6. To summarize:

session_start() by default sends a cache control header including "no-store".
  Internet Explorer takes this a bit too literally, but doesn't have appropriate
  error handling for the case, and as a result explodes cryptically when you
  attempt to save the output page to disk.
Before session_start(), add "session_cache_limiter('none');", or look up that
  function and tweak the limiter as appropriate (probably 'private' is closer to
  the mark).

I realize the code snippet you posted does not include a call to session_start();, but I figured I'd share this possible solution in case you do have a call to it and just didn't show us.

A: Use this
In IE7 Browser go to internet option--> security--->custom level --->downloads
then enabled autometic prompting for file download.
this will solve the problem.
hope this will help


text:
Q: ExtJS4: Value read in Store does not get populated in datafield As part of my EXTJS 4 learning process, I am trying to establish a simple process of database connection - loading a value in a data Store - taking the value and placing it in a dataField.
The data is loaded fine from the php script and placed into the Store via a json call. (as confirmed through FireBug)
However, the dataField, does not seem to be able to load the value.
Here is what I have so far:
//Model definition
Ext.define('FingerModel', {
        extend: 'Ext.data.Model',
        fields: [
                    {name: 'name', type: 'string'}
              ]
    });

//Store Definition
        var est_data = new Ext.data.Store({
            model: 'FingerModel',
            proxy: {
                type: 'ajax',
                url: 'finger.php',
                extraParams: {opt: 'getName'},
                reader: {
                    type: 'json',
                    root: 'results',
                    totalProperty: 'total'
                }
            },
            autoLoad: true,
            // turn off remote sorting
            remoteSort: false
        });

//Form definition
var fingerForm = Ext.create('Ext.form.Panel', {
            width: 500,
            title: 'Finger',
            waitMsgTarget: true,
            items: [{
                xtype: 'fieldset',
                title: 'Finger Form',
                items: [{
                        xtype:'textfield',
                        fieldLabel: 'Location Name',
                        name: 'name'
                    }]
            }]
    });

        fingerForm.getForm().loadRecord(FingerModel);

Anybody see anything obvious that I'm doing wrong?
Thanks in advance.
M.

A: Ext.form.field.Text does not have a 'store' property. How would it know which row of the store to use?
You should use Form.loadRecord() to load the model into the form, and it will set form fields with the same name as the model field names.


text:
Q: Ember - Page not getting displayed I am trying my first ember application. It has two pages. One is the Welcome page and the other page lists student details. so I have created two routes namely index and studentdb. The problem is my second page is not getting displayed. I have used Mirage as I am following ember guides. The code is as below:
templates/index.hbs

 Welcome

{{#link-to "studentdb"}}List{{/link-to}}

{{outlet}}

templates/studentdb.hbs

 Welcome to Student Database

 Following are the details

{{#each model as |student|}}

Name: {{student.Name}}

College: {{student.College}}

Department: {{student.Department}}

{{/each}}

{{outlet}}

routes/studentdb.js
import Ember from 'ember';

export default Ember.Route.extend({

    model() {
        return this.store.findAll('student');
    }
});

models/student.js (model)
import DS from 'ember-data';

export default DS.Model.extend({
  Name: DS.attr(),
  College: DS.attr(),
  Department: DS.attr()
});

mirage/config.js
export default function() {

  this.get('/student', function() {
    return {
      data: [{
        type: 'student',
        id: 1,
        attributes: {
          Name: 'Archana',
          College: 'MNM Jain',
          Department: 'CSE'

        }
      }, {
        type: 'student',
        id: 2,
        attributes: {
          Name: 'Monica',
          College: 'Sathyabama',
          Department: 'IT'
        }
      }, {
        type: 'student',
        id: 3,
        attributes: {
          Name: 'Manoj',
          College: 'Kumarsaamy',
          Department: 'MECH'
        }
      }]
    }
  });

}

router.js
import Ember from 'ember';
import config from './config/environment';

const Router = Ember.Router.extend({
  location: config.locationType
});

Router.map(function() {
  this.route('studentdb');
});

export default Router;

Kindly someone help. Thanks in advance.
This the error I get after re-installing ember as given in the below instructions
https://github.com/ember-cli/ember-cli/releases

npm WARN deprecated lodash-node@2.4.1: This package is no longer
  maintained. See its readme for upgrade details. npm ERR! registry
  error parsing json npm ERR! registry error parsing json npm ERR!
  registry error parsing json npm ERR! Windows_NT 6.1.7601 npm ERR! argv
  "C:\Program Files\nodejs\\node.exe" "C:\Program
  Files\nodejs\node_modules\npm\bin\npm-cli.js" "install" "-g"
  "ember-cli@2.2.0-beta.3"npm ERR! npm ERR! If you need help, you may
  report this error at: npm ERR!     http://github.com/npm/npm/issues
npm ERR! Please include the following file with any support request:
  npm ERR!     C:\Users\learner\npm-debug.lo

Kindly help please.

A: you need to define your route this.get('/students', it uses ember-inflector internally to pluralize your urls this is according to jsonapi.org

A: I'm new to ember as well and had the same problem. The issue below from github helped me realize that the guides I was following were newer than the version of ember-cli I had installed on my system:
https://github.com/samselikoff/ember-cli-mirage/issues/422
So, I chose to update ember to version 2.2.0-beta.3 using these instructions:
https://github.com/ember-cli/ember-cli/releases
After that, I also had to re-install ember-cli-mirage, but then it worked!


text:
Q: Injecting dynamic list content into an alert template email I have tried, and successfully failed, to determine a way to inject the emailed item's value from a universal custom column into the default alert emails generated by SharePoint, in both the subject and body. I'm hoping someone in the community here can assist.
Initially, we attempted to add content directly to the XML alert template file.
We also attempted working through the information in:

*

*Customizing Alert Notifications and Alert Templates in Windows SharePoint Services 3.0

*How To: Customizing alert emails using IAlertNotifyHandler
I've also been through this post which doesn't seem to dive deep enough, as well as this answer and this answer, neither of which answered the situation I'm looking to solve here.
We've found a number of other blog posts and sites that seem to just copy and paste from the examples in the above two. All of the discussions we've worked through either talk about changing the formatting of an email template, or show you how to build a completely custom email and send that instead of the normal system-generated email. I've been through the questions here and it's the same story...
My goal is to not reinvent the wheel. I want in some sense of the idea, to let SharePoint build its email, then catch it, inject content, then send it on its way.
So, two parts to the question:

*

*Can someone explain the sequence from the timer job starting to emails hitting the mail server?

*Does anyone have a known method for either

*

*intercepting an email, injecting content, then releasing it, or

*invoking the default alert handler within a custom alert handler, so that we don't have to rewrite all of the default email templates in C#?

A: I do something real similar to what you are looking for here: How can I create custom Alerts for external email addresses?
However, the correct location for the custom field would be in the xml template. Although this answer may work better for you than the ones listed above: Hide or Remove Workflow Columns on Alert Emails


text:
Q: Opening High Res Images on Lumia 1020 Any one know if there is a way of opening the high res original photo stored on a 1020 in an app?
 are stored in pairs, the post-processed lower res one and original high res one which seems to be hidden from the phone api.
You can get to it when connected to a pc.
cheers

A: Apparently there is no way to access the original (41MP) image from code on the device.
I've heard lots of people complaining about this, so maybe this will change in the future. But for now it's not accessible.

A: Here is the reason.
http://social.msdn.microsoft.com/Forums/en-US/69ca308b-ff37-4f27-a6b0-b7559bbdfa33/programmatically-access-high-resolution-images-on-lumia-1020-1520?forum=wpdevelop
Looks like Nokia and MS have decided to keep it blocked to 3rd party apps for stability reasons. However i have heard 'Open in Nokia Camera' option makes native Nokia Camera to access 38MP pics.
Makes sense as this app clicks (writes) it, so it will have surely read permissions.


text:
Q: PHP program that requires user to accept a string as a parameter and return the same string randomly capitalized characters PHP program that requires user to accept a string as a parameter and return the same string randomly capitalized characters. Example: the input is "php script" may display "PHP SCRIPT", "pHp ScriPT", "PHP script" or "php SCRIPT".
I don't really know what i'm doing actually.

Random Capitalized Character

<form action="Q5.php" method="post"><input type="text" name="input" value="<?php if (isset($_POST['input'])) echo $_POST['input']; ?>" />
<input type="submit" />
</form>

<?php

$name = "input";

$lowercaseTitle = strtolower($name);
$uppercaseTitle = strtoupper($name);
$ucTitleString = ucwords($lowercaseTitle && $uppercaseTitle);
echo "$ucTitleString";
?>

I would like to ask how to create this? already done this and that but results still no no.

A: Here a custom function to randomly capitalized characters:
    function randomCapitalize($input)
    {
        $output = '';

        foreach (str_split($input) as $c) {
            if (rand(0, 1) == 1) {
                $output .= strtoupper($c);
            } else {
                $output .= strtolower($c);
            }
        }

        return $output;
    }

And you just need to echo with your string in parameter:
 echo randomCapitalize("php script");


text:
Q: How to write a shell script to check the service file is running or not if not then restart the service? I have written one shell script to check the status of a service file, if I run that script I'm getting an error.
#! /bin/sh
SERVICE = myApp

while(true)
do
   if ! ps -ef | grep -i $SERVICE > /dev/null
       then nohup /full_path/runMyApp &
   fi
   sleep 10
done

here I'm getting error as follows:

try grep [OPTION]... pattern[FILE]... nohup:failed to run command 'full_path/runMyApp':no such file or directory

A: Your grep command fails, and myApp isn't found in the path you give.
Problems/fixes in your script:

*

*Don't put a space between #! and /bin/sh.

*You must not have spaces around the = sign when you assign a variable (this causes your grep to fail).

*The variable should be quoted in the grep command, in case the name has a space.

*Make sure there is a / before and after the path to myApp. It looks like you might have missed the trailing / above.

*When grepping for a process (not the best way to check if a process is running), make sure you exclude the grep process itself, otherwise you'll always see some process running and think your service is up.

*The parenthesis in while isn't needed, as this isn't C. In sh, it means you run the command true in a subshell.

*grep has a parameter -q which makes it output nothing. This is better than redirecting to /dev/null.

Putting it all together:
#!/bin/sh
SERVICE="myApp"

while true
do
   if ! ps -ef | grep -v grep | grep -qi "$SERVICE"
       then nohup "/full_path/$SERVICE" &
   fi
   sleep 10
done


text:
Q: Which version of the Dinkumware STL Lib ships with Visual Studio 2012? In earlier versions of Visual Studio, there was a predefinied macro "_CPPLIB_VER" which reported the version of the Dinkumware STL Library shipped with this version of VS. As of 2012, I am unable to find or use this macro - it is undefinied and I am unable to find any information on this matter online.
Is the Dinkumware STL Lib no longer used in VS2012? Was the macro renamed?
Windows 7 x64
Microsoft Visual Studio 2012 Professional

A: Usually the definition of _CPPLIB_VER can be found in a header file named yvals.h somewhere under your VS installation folder. For Visual Studio 2010 it's in VC\include.
Be careful because _CPPLIB_VER is no longer an official predefined macro since Visual Studio 2008.
The "Change History" section of Predefined Macros (Visual Studio 2008) on MSDN says:

Added Visual Studio 2008 values for _ATL_VER, _MSC_VER, _MFC_VER; removed _CPPLIB_VER; updated __COUNTER__, _DEBUG, _DLL, _MT, __FUNCDNAME__, __FUNCSIG__, __FUNCTION__, __FILE__. Cleaned up topic.

And the macro was one of the "Microsoft-Specific Predefined Macros" for VS 2005. See Predefined Macros (Visual Studio 2005):

_CPPLIB_VER
Defined if you include any of the C++ Standard Library headers; reports which version of the Dinkumware header files are present.


text:
Q: Why do I get different base64 encodings for the same string using Powershell/.NET and Javascript? On a webpage, I am using Javascript to convert a string to Base64:
<script type="text/javascript">
    function base64_encode (data) {
    var b64 = ""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
    ac = 0,
    enc = """",
    tmp_arr = [];
    if (!data) { return data; }
    do {
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);
        bits = o1 << 16 | o2 << 8 | o3;
        h1 = bits >> 18 & 0x3f;
        h2 = bits >> 12 & 0x3f;
        h3 = bits >> 6 & 0x3f;
        h4 = bits & 0x3f;
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);
    enc = tmp_arr.join('');
    var r = data.length % 3;
    return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
}
</script>

That is the code from here: http://phpjs.org/functions/base64_encode/
When I use that code the above code to base64-encode the string cat, it responds with Y2F0.
When I encode the same word in Powershell/.NET, I get this:
PS C:\> [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes("cat"))
YwBhAHQA

Why are they different, and how can I make the Javascript function match the .NET output?

A: base64 encodes binary data. The binary representation of 'cat' is different in JS (most likely UTF-8 encoded) and .NET (Unicode 16 bit encoded), so the base64 encoding is bound to differ.
Try to convert the string to UTF-8 (byte[]) in .NET, then encode.

A: In order to convert a string to base64, the characters must first be encoded into bytes.
Unicode encodes characters using two bytes for each character, while the JavaScript encoder you have pasted assumes that data is already encoded into bytes (or, at a minimum, ASCII).
Try using UTF8.GetBytes instead of Unicode.GetBytes in your Powershell script.  UTF-8 will use one byte for characters when possible, and use multiple bytes when necessary.


text:
Q: How to use an integer id to identify a class in a class hierarchy automatically? For example, I have a base class A and its sub-classes B, C and so on. B and C can also has its sub-classes. The structure is a tree with root A. And each class in the tree is assigned a different integer to identify itself. There is no restriction on the integer id's values and orders. Just make sure they are different for different classes.
My question is how to do it smartly (or automatically) by using like template techniques since manual assignment is error-prone. Any way to get the id is fine, like
class A
{
public:
    static const id = ...;
};

or
template<class A>
struct Id
{
    enum { value = ... };
};

A: Easiest way is just a function
int nextId() {
    static int rval = 1;
    return rval++;
}

class A { public: static const id = nextId();  };
class B { public: static const id = nextId();  };
class C { public: static const id = nextId();  };

That will work so long as you do not need to use the IDs in dynamic initialization at the start of the program.
Edit: if that is not sufficient, the next step up is to do the same thing with static variables in a template.  This works across compilation units, but is still dynamic initialization time.
template <typename DummyT = void>
struct CommonCounter
{
    public:
        static int nextId() {
            static int rval = 1;
            return rval ++;
        }
};

template <typename T>
struct IdFor
{
    static int value()
    {
        static int rval = CommonCounter<>::nextId();
        return rval;
    }
};

class A { public: static const id = IdFor<A>::get(); };

A: You could do something like this. This should give the same order on the same compiler. You could also modify how you key things to get a known order and detect problems at initialisation time. Simple implementation, not tested.
#include <typeinfo>

class A {
public:
    virtual ~A();
    static void register_type(std::type_info const& t);
    int id() const;
};

template<class T>
struct DoInitA
{
    DoInitA() { A::register_type(typeid(T)); }
};

class B : public A
{
    static DoInitA<B> s_a_init;
public:
    ~B() { }
};

//
// Implementation file.
//

#include <vector>
#include <functional>

namespace {
    struct TypeinfoLess {
        typedef std::reference_wrapper<const std::type_info> value_type;

        bool operator()(value_type const& lhs, value_type const& rhs) const {
            return lhs.get().before(rhs.get());
        }
    };
}

typedef std::vector<std::reference_wrapper<const std::type_info>> TypeVector;

static TypeVector s_types;
static bool s_init_complete = false;

A::~A() { }

void A::register_type(std::type_info const& t)
{
    static int s_counter = 0;
    if (s_init_complete)
        throw std::runtime_error("Late initialisation");

    s_types.push_back(std::reference_wrapper<const std::type_info>(t));
}

int A::id() const
{
    if (!s_init_complete) {
        sort(s_types.begin(), s_types.end(), TypeinfoLess());
        s_init_complete = true;
    }

    for (size_t i = 0; i < s_types.size(); ++i)
        if (s_types[i].get() == typeid(*this)) return i;

    throw std::runtime_error("Uninitialised type");
}


text:
Q: Comparison of unspecified generic properties Consider the following code:
public interface IIdentifiable<T>
{
    T Id { get; set; }
}

public interface IViewModel
{
}

public class MyViewModel1 : IViewModel, IIdentifiable<int>
{
    public string MyProperty { get; set; }

    public int Id { get; set; }
}

public class MyViewModel2 : IViewModel, IIdentifiable<string>
{
    public string MyProperty { get; set; }

    public string Id { get; set; }
}

I also have class that operates with ViewModels:
public class Loader<T> where T: IViewModel
{
    public void LoadData()
    {
        /*some important stuff here*/

        if (typeof(IIdentifiable<??>).IsAssignableFrom(typeof(T)))
        {                     // ^- here's the first problem
            data = data.Where(d => _dataSource.All(ds => ((IIdentifiable<??>) ds).Id != ((IIdentifiable<??>) d).Id)).ToList();
        }                                                             // ^---- and there the second ----^

        /*some important stuff here too*/
    }
}

Now, as you can see, viewmodels that I have might implement the IIdentifiable<> interface. I want to check that, and if it's true,
I want to make sure my data list does not contains any entry that are already present in my _dataSourse list.
So I have 2 questions:

*

*I don't know what IIdentifiable<> has in its generic parentheses, it might be int, string or even GUID.
I tried typeof(IIdentifiable<>).IsAssignableFrom(typeof(T)) which is the correct syntax, yet it always returns false.
Is there a way to check whether T is IIdentifiable<> without knowing the exact generic type?

*If there is an answer for the first question, I would also like to know how can I compare the Id fields without knowing their type.
I found this answer quite useful, yet it doesn't cover my
specific case.
I know that I probably can solve that problem if I make my Loader<T> class a generic for two types Loader<T,K>, where K would be the
type in IIdentifiable<>, yet I would like to know if there are other solutions.

P.S. In addition to my first question: I'm also curious why one can write something like this typeof(IIdentifiable<>).IsAssignableFrom(typeof(T)) if it returns false when the generic type of IIdentifiable<> is not specified?

Edit: I guess, in hindsight, I understand why I can't write the code this bluntly - because there's might be the collection ICollection<IViewModel> where the entries implement different types of IIdentifiable<> (or don't implement it at all), and the check like that would fail awkwardly. Yet maybe there is a way to do something like that with some restrictions, but without creating second generic parameter to my Loader?

A: Try add two methods to your Loader<T>:
public bool CanCast<TId>()
{
    var identifiableT = typeof(IIdentifiable<>).MakeGenericType(typeof(TId));
    return identifiableT.IsAssignableFrom(typeof(T));
}

public IEnumerable<IIdentifiable<TId>> Filter<TId>(IEnumerable<T> data)
{
    return data.Where(d => _dataSource.All(
      ds => !((IIdentifiable<TId>) ds).Id.Equals(((IIdentifiable<TId>) d).Id)));
}

Then in LoadData
if (CanCast<int>())
    data = Filter<int>(data);
else if (CanCast<Guid>())
    data = Filter<Guid>(data);
// and so om

A: Well, I would suggest you to always use a string for identification. You can convert int and guid to a string. And if you want to ensure proper type is used then you can prefix the string with type information.
However, I do think that the performance of you algorithm would be very poor as you wouls essentially loop 2 containers so it would be O(n * m).
Thus it would be best to either do appropriate SQL query if both sources are from the database or use a dictionary if you do it in code. Alternatively if data is properly sorted, you could find duplicates more efficiently.
By the way generics are quite limited in C#. Sometime using ˋFunc<>ˋ could help but even then you have to provide extra information to the algorithm.

A: We should address your question in two steps (because there really are two problems to solve here).
First, make following change to your interface IIdentifiable<T>
public interface IIdentifiable<T>
    where T : IEquatable<T>
{
    T Id { get; set; }
}

This will ensure that you can compare Id properties correctly.
Secondly, in your LoadData() method, change the if statement to
    if (T is IIdentifiable<T>)
    {                     // ^- here's the first problem
        data = data.Where(d => _dataSource.All(ds => ((IIdentifiable<T) ds).Id != ((IIdentifiable<T) d).Id)).ToList();
    }


text:
Q: Parse json inside another json string in swift4 I am trying to parse the json. But the problem is I have json inside to it another json String. Like :
{
    "count": 284,
    "next": "http://X:X:X:X:8080/api/sensor/last5feed?page=2&search=XXXXX",
    "previous": null,
    "results": [
        {
            "id": 571,
            "feed": "{'app_id': 'XXXXX', 'dev_id': 'XXXX', 'hardware_serial': 'XXXXX', 'port': 6, 'counter': 4290, 'payload_raw': 'AQEBIwXsF4IAAAA=', 'payload_fields': {'aamsg_type': 'weather', 'abstatus': 0, 'batteryV': 3.5, 'battery_low': 'no', 'humiP': 60.2, 'tempC': 15.2}, 'metadata': {'time': '2020-01-23T15:09:32.350967362Z', 'frequency': 868.1, 'modulation': 'LORA', 'data_rate': 'SF7BW125', 'airtime': 61696000, 'coding_rate': '4/5', 'gateways': [{'gtw_id': 'XXXXX', 'timestamp': 3227230963, 'time': '2020-01-23T15:09:32.326146Z', 'channel': 0, 'rssi': -98, 'snr': 4.8, 'rf_chain': 1, 'latitude': 57.124737, 'longitude': -2.1646452, 'altitude': 90, 'location_source': 'registry'}]}}",
            "created_at": "2020-01-23T15:09:32.630326Z",
            "sensor": 1
        },
        {
            "id": 569,
            "feed": "{'app_id': 'XXXXXX', 'dev_id': 'XXXX', 'hardware_serial': 'XXXX', 'port': 6, 'counter': 4289, 'payload_raw': 'XXXXX', 'payload_fields': {'aamsg_type': 'weather', 'abstatus': 0, 'batteryV': 3.5, 'battery_low': 'no', 'humiP': 57.6, 'tempC': 16.9}, 'metadata': {'time': '2020-01-23T14:09:32.132070865Z', 'frequency': 867.3, 'modulation': 'LORA', 'data_rate': 'SF7BW125', 'airtime': 61696000, 'coding_rate': '4/5', 'gateways': [{'gtw_id': 'XXXXXX', 'timestamp': 3921981659, 'time': '2020-01-23T14:09:32.104672Z', 'channel': 4, 'rssi': -107, 'snr': 8.2, 'rf_chain': 0, 'latitude': 57.124737, 'longitude': -2.1646452, 'altitude': 90, 'location_source': 'registry'}]}}",
            "created_at": "2020-01-23T14:09:32.448929Z",
            "sensor": 1
        }
}

I am getting the values till feed. But I am not able to parse further, My code is :
if(status_code == 200){
  if let json = response.data {
    do{
      let data = try JSON(data: json)
      let result = data["results"].arrayObject! as NSArray
      let ct = result.count
       if(ct != 0 ) {
       self.noDataFound.isHidden = true
       for i in 0...ct-1 {
          let data = result[i] as? NSDictionary
          let feed = data?.value(forKey: "feed") as? NSString
          let data3 = try JSON(data: feed as! Data) .
          print(data3)
        }
    }
} catch {} }}

I need to get the hardware_serial from feed. Can any body please help me what i am doing wrong here!! Thanks!!!

A: *

*The string for key feed is not valid JSON. You have to replace the single quotes with double quotes.

*Create a Data object from the string (casting the type doesn't work).

*Create a JSON object from the data.

*Get the values you need.

Side note:
Don't use NS... collection types and NSString in Swift.

A: Use Codable to parse the above JSON response.
Models:
struct Root: Codable {
    let count: Int
    let next: String
    let previous: String?
    let results: [Result]
}

struct Result: Codable {
    let id: Int
    let feed, createdAt: String
    let sensor: Int
}

Parse the JSON data like so,
do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let response = try decoder.decode(Root.self, from: data)
    print(response)
} catch {
    print(error)
}

A: First, peel off the piece you want:
struct ResultWrapper: Decodable {
    let results: [Result]
}

And then build a custom decoder to extract feed, which is malformed. Single-quotes are not legal JSON. As a hack, the following code just substitutes all single-quotes with double-quotes, but this won't work if there are any embedded quoted-single-quotes.
struct Result: Decodable {
    enum CodingKeys: String, CodingKey { case feed }
    let feed: Feed
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        // inner JSON is mal-formed. Have to fix it.
        let feedString = try container.decode(String.self, forKey: .feed)
            .replacingOccurrences(of: "'", with: "\"")

        feed = try JSONDecoder().decode(Feed.self, from: Data(feedString.utf8))
    }
}

Finally, decoding Feed is mechanical, but requires custom CodingKeys. I recommend quicktype for that:
// https://app.quicktype.io?share=7O6iNJ3ugXb4mr84TIoG
struct Feed: Codable {
    var appID, devID, hardwareSerial: String
    var port, counter: Int
    var payloadRaw: String
    var payloadFields: PayloadFields
    var metadata: Metadata

    enum CodingKeys: String, CodingKey {
        case appID = "app_id"
        case devID = "dev_id"
        case hardwareSerial = "hardware_serial"
        case port, counter
        case payloadRaw = "payload_raw"
        case payloadFields = "payload_fields"
        case metadata
    }
}

// MARK: - Metadata
struct Metadata: Codable {
    var time: String
    var frequency: Double
    var modulation, dataRate: String
    var airtime: Int
    var codingRate: String
    var gateways: [Gateway]

    enum CodingKeys: String, CodingKey {
        case time, frequency, modulation
        case dataRate = "data_rate"
        case airtime
        case codingRate = "coding_rate"
        case gateways
    }
}

// MARK: - Gateway
struct Gateway: Codable {
    var gtwID: String
    var timestamp: Int
    var time: String
    var channel, rssi: Int
    var snr: Double
    var rfChain: Int
    var latitude, longitude: Double
    var altitude: Int
    var locationSource: String

    enum CodingKeys: String, CodingKey {
        case gtwID = "gtw_id"
        case timestamp, time, channel, rssi, snr
        case rfChain = "rf_chain"
        case latitude, longitude, altitude
        case locationSource = "location_source"
    }
}

// MARK: - PayloadFields
struct PayloadFields: Codable {
    var aamsgType: String
    var abstatus: Int
    var batteryV: Double
    var batteryLow: String
    var humiP, tempC: Double

    enum CodingKeys: String, CodingKey {
        case aamsgType = "aamsg_type"
        case abstatus, batteryV
        case batteryLow = "battery_low"
        case humiP, tempC
    }
}


text:
Q: using pandas dataframe to create matplotlib bar chart This is an example of how my pandasDF dataframe look like. This is a movie dataset. The count represent how each movie title represent 1.
| yearOfRelease |count|
| 1989          | 1   |
| 1990          | 1   |
| 1991          | 1   |
| 1992          | 1   |
| 1993          | 1   |

Previously my dataframe is a spark dataframe but i convert it to a pandas dataframe
pandasDF = movies_DF.toPandas()
pandasDF.head()

This is the plot i have right now.

I am trying to achieve a plot that look like this.

This is my code:
x = list(pandasDF[pandasDF['yearOfRelease'] >= '1990']['yearOfRelease'])
import matplotlib.pyplot as plt
plt.figure()
pd.value_counts(x).plot.bar(title="number of movies by year of release ")

plt.xlabel("yearOfRelease")
plt.ylabel("numOfMovies")
plt.show()

A: You have to sort your values by index (yearOfRelease):
import matplotlib.pyplot as plt

sr = pandasDF.loc[pandasDF['yearOfRelease'] >= '1990', 'yearOfRelease'].astype(int)
ax = (sr.value_counts().sort_index()
        .plot.bar(title='number of movies by year of release',
                  xlabel='yearOfRelease', ylabel='numOfMovies',
                  rot=-90))
ax.xaxis.set_major_locator(ticker.MultipleLocator(2))
ax.yaxis.set_major_locator(ticker.MultipleLocator(500))
plt.tight_layout()
plt.show()

Output:


text:
Q: Finding a basis for a set of vectors-reasoning behind reduced row echelon form I had a question about finding the basis for a set of vectors. so one way to do it, is just to write it in a matrix form, and convert it to reduced row-echelon form correct? And the pivot columns in reduced row echelon form, and the corresponding columns in the original matrix gives us the basis for that set of vector.
I don't quite see how this works. Why should this be true? Can someone please help me?

A: Linear independence has a few equivalent formulations. The one that most resembles the matrix version is this one:

A list $(v_1, \ldots, v_n)$ is linearly dependent if and only if there exists some $v_i$ such that
  $$v_i \in \operatorname{span}(v_1, \ldots, v_{i-1}).$$

In other words, at some point when adding the vectors in the list, you've added one that doesn't expand the span at all. To prove this, consider the least $i$ such that $(v_1, \ldots, v_i)$ is linearly dependent (there must be one, since the whole list is linearly dependent, and the well-ordering property of $\Bbb{N}$). Then, for $a_1, \ldots, a_i$, we have
$$a_1 v_1 + \ldots + a_i v_i = 0 \tag{1}$$
for some scalars $a_1, \ldots, a_i$, not all of which are equal to $0$.
If $a_i = 0$, then $(1)$ reduces to
$$a_1 v_1 + \ldots + a_{i-1} v_i = 0$$
where $a_1, \ldots, a_{i-1}$ are not all $0$. This implies $(v_1, \ldots, v_{i-1})$ is linearly dependent, against the definition of $i$. Therefore, by contradiction, $a_i \neq 0$. Hence, $(1)$ becomes
$$v_i = -\frac{a_1}{a_i} v_1 - \ldots - \frac{a_{i-1}}{a_i}v_i \in \operatorname{span}(v_1, \ldots, v_{i-1}),$$
as required.
Conversely, if $v_i \in \operatorname{span}(v_1, \ldots, v_{i-1})$, then
$$v_i = a_1 v_1 + \ldots + a_{i-1}v_{i-1}$$
for some $a_1, \ldots, a_{i-1}$, and hence
$$a_1 v_1 + \ldots + a_{i-1}v_{i-1} + (-1)v_i + 0v_{i+1} + \ldots + 0v_n = 0$$
is a non-trivial null linear combination of $(v_1, \ldots, v_n)$, making the list linearly dependent.

How does this help us? Think about the procedure for figuring out if a column vector $w$ belongs to the span of a list of column vectors $(v_1, \ldots, v_n)$. The first thing to do is set up an equation to solve:
$$w = a_1 v_1 + \ldots + a_n v_n.$$
This turns into a system of linear equations in the variables $a_1, \ldots, a_n$, which we can turn into an augmented matrix
$$\left[\begin{array}{ccc|c}&&&\\v_1&\dots&v_n&w\\&&&\end{array}\right]. \tag{2}$$
We then reduce this down to a row-echelon form, and examine the $0$ rows. If every $0$ row extends to the augmented column, then $w$ belongs to the span. If one of the zero rows has a non-zero entry in the augmented column, then $w$ does not belong to the span.
However, think about this: there's no real difference between an augmented column and a regular column! Reducing the matrix from $(2)$ to row-echelon form requires exactly the same procedure as reducing
$$\left[\begin{array}{cccc}&&&\\v_1&\dots&v_n&w\\&&&\end{array}\right].$$
If you get a pivot in the final column (corresponding to $w$), then this is equivalent to having one of your zero rows from the row-echelon form of $(2)$ having a non-zero entry in the augmented column. So, a pivot in the final column implies that it does not belong to the span of the previous vectors.
Finally, we should note that this doesn't just hold for the vector in the final column. Think about how we actually go about, routinely, computing a row-echelon form of a matrix. We first try to secure a pivot in the top of the leftmost column (provided the column is not just $0$), and then proceed to try to eliminate every entry below this pivot. We then proceed to the next column, leaving the first row alone. We then repeat this process to get a pivot as leftmost as possible in the second row, and continue working our way to the right.
In essence, we try to shore up columns from left to right. The process of shoring up the leftmost column is precisely the full process for turning just that column vector into row-echelon form. The process for shoring up the two leftmost columns is precisely the full process for turning the submatrix containing just those two columns into row-echelon form.
Let's briefly illustrate this:
\begin{align*}
\begin{bmatrix}1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9\end{bmatrix}
&\sim \begin{bmatrix}1 & 2 & 3 \\ 0 & -3 & -6 \\ 7 & 8 & 9\end{bmatrix} \\
&\sim \begin{bmatrix}\color{red}{1} & 2 & 3 \\ \color{red}{0} & -3 & -6 \\ \color{red}{0} & -6 & -12\end{bmatrix} \\
&\sim \begin{bmatrix}1 & 2 & 3 \\ 0 & 1 & 2 \\ 0 & -6 & -12\end{bmatrix} \\
&\sim \begin{bmatrix}\color{red}1 & \color{red}2 & 3 \\ \color{red}0 & \color{red}1 & 2 \\ \color{red}0 & \color{red}0 & 0\end{bmatrix}.
\end{align*}
The highlights show the submatrices turning into row-echelon form. The first highlight shows the row-echelon form of the submatrix
$$\begin{bmatrix}1 \\ 4 \\ 7\end{bmatrix}.$$
The second highlight shows the row-echelon form of the submatrix
$$\begin{bmatrix} 1 & 2 \\ 4 & 5 \\ 7 & 8\end{bmatrix}.$$
This is always true when reducing a matrix: you always reduce more and more columns, until the whole thing is in row-echelon form.
So, what this means is, when you row reduce a matrix
$$\begin{bmatrix}&&\\v_1&\dots&v_n\\&&\end{bmatrix},$$
you are simultaneously checking if $v_2 \in \operatorname{span}(v_1)$ and if $v_3 \in \operatorname{span}(v_1, v_2)$, and if $v_4 \in \operatorname{span}(v_1, v_2, v_3)$, etc. There will be a pivot in the $i$th column if and only if $v_i \notin \operatorname{span}(v_1, \ldots, v_{i-1})$. That is, there will be a pivot in the $i$th column if and only if $v_i$ adds something to the span that no previous vectors contribute. Discarding all vectors without pivots will therefore not damage the span, and what you're left with is a list of vectors for which do not belong to the span of the previous vectors, and hence are linearly independent.


text:
Q: Add elements in multidimensional ArrayList in Java I want to store some values (actually a message) using list in Java. I want to store something like:
{user1, message, user2, time}
{user1, message, user4, time}
{user3, message, user1, time}

I have declared an arraylist like this:
public List<List<String>> message = new ArrayList<List<String>>();

How can I add values in this list and how can I get a specific row (let's say the second row) of this list?
I've tried:
    message.get(0).add(msg, target,time);

but I get an error:

"The method add(String) in the type List is not applicable for
  the arguments (String, String, Integer)"

A: You could do something like:
List<Object[]> list = new ArrayList<Object[]>();
Object[] ob = new Object[4];
ob[0] = "user1";
ob[1] = "messge1";
ob[2] = "user2";
ob[3] = "time1";

list.add(ob);

ob = new Object[4];
ob[0] = "user2";
ob[1] = "messge2";
ob[2] = "user4";
ob[3] = "time2";
list.add(ob);

// Output the values
for(Object[] o : list){
    System.out.print(o[0] + "\t");
    System.out.print(o[1] + "\t");
    System.out.print(o[2] + "\t");
    System.out.print(o[3] + "\n");
}

and the output will be:
user1 messge1 user2 time1

user2 messge2 user4 time2

A: by
message.get(0);

you are retriving the first list in list of list referred by message
List has add(T object) method so you can't pass all 3 Objects in one call, one way to do is
message.get(0).add(msg);
message.get(0).add(target);
message.get(0).add(time);


text:
Q: Spinners with file inputs I have 7 inputs of files and I want to add spinners to each input. How can I achieve this? I can`t use standart lightning:fileUpload but only lightning:input type="file"

A: The lightning:input aura component is more DIY than lightning:fileUpload as you need to provide your own event handlers and Apex code to handle the file upload (per the documentation on the component). If you want to display a spinner that's easy enough to accomplish by using an onchange handler on your component to show and hide a spinner based on the file being uploaded.

        Uploading...

    <lightning:input type="file" onchange="{! c.handleFileUpload }" />

/* Controller */

handleFileUpload : function(cmp, event, helper) {
    // find the spinner and show it
    let spinner = cmp.find('spinner');
    $A.util.toggleClass('slds-hide');

    // handle the file upload, in callback hide the spinner again
}

You may need some additional styling to get the spinner to look its best, but the foundations should be here.


text:
Q: H1 tag inside breadcrumb okay for accessibility? In my web app I have a header bar that is both the app's breadcrumbs as well as the heading for the current page.
So in the header you will see:

App Name > Section Name > Current Page

Where "current page" is the H1 tag for the page.
Does this make sense from an accessibility (ARIA rules) standpoint?
Here is what my code looks like:

    App Name
    Section Name

Current Page Name

The reason for this is so I have the one H1 tag per page, and then the content can have H2 and lower.
OR should I leave the current page as just a span tag, and allow multiple H1 tags within the content?

A: A heading inside a section belongs to this section. The nav element creates such a section. This means that "Current Page Name" is the heading for the navigation, not for the page. But that would be wrong, of course (a navigation's heading, if it has one, could be something like "Navigation").
Whether or not this creates an actual accessibility problem is impossible to tell (users might use tools that make use of the outline, possibly even custom ones). But even if doesn't affect accessibility currently, you shouldn't go against the spec (unless you have good reason to do so).
(By the way, for accessibility, you should either provide textual delimiters for the breadcrumb items, or use markup like ol.)
It's possible to implement what you want to achieve in a spec-conforming way, if you don't use nav, e.g.:

    App Name → Section Name →

Current Page Name

But the conventional way would be not to integrate the page heading in the breadcrumbs: either by duplicating the label for the current page (having it in the heading and in the breadcrumbs), or by omitting the breadcrumb item for the current page.

A: I would avoid putting a
 in the navigation as I think some screen readers may interpret it as being the heading for the navigation rather than the page as a whole. I would also recommend that you structure your breadcrumb as an ordered list (or at the very least an unordered list) as the W3C describes a breadcrumb trail as "a list of links to the parent pages of the current page in hierarchical order" and an ordered list would semantically demonstrate this hierarchy to screenreaders. The W3C also has a tutorial that seems to confirm this view.
User agents do not yet support the HTML 5 document outline: (See There is No Document Outline), Therefore you are better off putting your H1 in your header and using H2 headings and lower in your main content. Here's an example:

Current page name

App Name

Section Name

Current Page Name

Article heading

Article sub-heading


text:
Q: Incremental countdown to change z-index value of sibling elements I have checked everywhere looking for a solution to this, and have not been able to figure it out. The solution eludes me.
For complicated reasons, I can't simply change the margin/padding swap in CSS, so I'm trying to add style="z-index:5;" in the first div, and then style="z-index:4;" in the second div, etc. so that the last element on the page has the lowest z-index, and each element going toward the top adds one, so it always remains on top if there is any overlap, which is the case with some links that currently sit below the subsequent sibling element.
Stripped down sample code below: I know my counter is working, but the value of the incrementer (z) is not passing to the .css method in the for loop. Any suggestions?

some content
  //add style="z-index:5:

some content
  //add style="z-index:4:

some content
  //add style="z-index:3:

some content
  //add style="z-index:2:

some content
  //add style="z-index:1:

A: You are working with a jQuery collection (var subsection).  You need to go over each item in that collection separately.
Something like:
subsection.each(function(i){
  $(this).css('z-index', subsection.length-i);
});

A: You should use z -= 1 in a for loop. Sometimes things get screwy otherwise. See here
And iterate with each.
subsection.each
  (
    function(i) {
         $(this).css('z-index',subsections-i);
    }
  )
;


text:
Q: Tasks in task scheduler not running from cmd I am using command line to create tasks, run them as well as delete. I am able to create tasks in the scheduler with no issue but when i run it via command line it immediately gets stuck as "queued". But when i go to task scheduler GUI and click "run" the tasks run properly. What could i be doing wrong? I am using windows 10. After running it on cmd it outputs "SUCCESS: Attempted to run the scheduled task "_a"." But still nothing happens unless i go the GUI of task scheduler and run it from there.
Here is a code i tried to schedule notepad:
    schtasks /create /ru yanic /sc daily /tn "note" /tr C:\windows\system32\notepad.exe
    SCHTASKS /RUN /TN "note


text:
Q: Hilbert space automorphisms realized as induced by transformations of some base-spaces Following question may be soft. Fix abstract hilbert space H and consider any automorphism A in banach-spaces sence (i.e. no conditions on metric). Call A is realizable if exist measure space $(X,\mu)$ and isomorphism from H onto (or into, depending on the preferred definition) $L_2(X,\mu)$ such that direct image of A realized by some homeomorphism (or other type of transformations) of X i.e. in "new coordinates" A induced by automorphism of X. Set of all realizable automorphisms is conjugate-invariant. My main question: Is it group? i.e. can i construct measure space $(X,\mu)$ from $(X_1,\mu_1)$ and $(X_2,\mu_2)$ with operators A,B induced by transformations of $X_1,X_2$  respectively, such that AB realizible on $(X,\mu)$? Sorry for bad english.
Added: simple argument that it haven't group structure on usual multiplicity structure gived by Costabel. But questions related to common construction described bellow are stayes.
Yemon Choi, your point of view is proper. In fact we working on some discrete category of functional spaces (L_2) on certain-type measure-spaces (probability spaces, topological groups and so on). Morphisms in such category called by "transformations", and in my first message they are obtained by transformations on themselves measure-spaces. We can consider our category with new object - abstract hilbert space H with morphisms from H to each other object - just bounded and left-invertible linear maps (or isometries, as you want). Inverse arrows just bounded maps. Obtained morphisms from H to itself called realizable. For instance, consider such category where transformations is multiplication on square-integrable function and all maps from H is isometries, so spectral theorem gives that self-adjoint operators in precisely are realizible in such category. I really upset by the fact, that obtained sets of realizable operators do not have any natural algebraic structure. So that on it moment question may be closed, but any comments are welcome. May be certain category of measure-spaces (lie groups with haar measure) will gives something interesting? May be this sets need to be considering in total?

A: Here is a simple example showing that it is not a group. In the example, only isometries appear, so it doesn't really matter how the definitions are made precise.

Note first that the only multiples of the identity that are realizable are zero and the identity itself (Proof: Whatever your definition of "transformation of $X$" is, it will map characteristic functions of sets of finite measure to functions that take the values $0$ and $1$ only).
Now take $H=\mathbb{R}^2$ and let $A$ be defined by the matrix
$0\ \ \  1\choose 1\ \ \ 0$. This is realizable, by transposition of indices in $H\equiv \ell^2(\{0,1\})$. Let $U$ be the automorphism of $H$ defined by the matrix
$1\ \ \ \ 0\choose \ \ 0\ \ -1$. Then $B=UAU^{-1}$ is also realizable. But $B=-A$ and $AB=-1$, which is not realizable.


text:
Q: C# Array Index Error Simple array I'm adding to, however I keep getting this Index Out Of Bounds error. Looked around, can't quite figure out where I'm going wrong, I'm assuming it's something to do with where I've used the pos variable. Posted anything I think might be relevant. Thanks in advance.
const int MAX = 5;
    Account[] db = new Account[MAX];

    // global variable for position in array
    int pos;

    private void Form1_Load(object sender, EventArgs e)
    {
        // initialise the array with instantiated objects
        for (int i = 0; i < MAX; i++)
            db[i] = new Account();
    }

private void OpenAcc_Click(object sender, EventArgs e)
    {
        //hide menu
        hide_menu();

        //make new form elements visible
        tbNameEnt.Visible = true;
        tbBalaEnt.Visible = true;
        SubDet.Visible = true;

        //set pos to the first empty element of array
        pos = Array.FindIndex(db, i => i == null);
    }

private void SubDet_Click(object sender, EventArgs e)
    {
        string textBox1;
        double textBox2;
        int a = 0011228;
        int b = pos + 1;
        int accNo;

        //get and parse input details
        textBox1 = tbNameEnt.Text;
        textBox2 = double.Parse(tbBalaEnt.Text);

        //allocate account number
        accNo = int.Parse(a.ToString() + b.ToString());

        //set details for new object in array
        db[pos].SetAccount(textBox1, accNo, textBox2); //ERROR HERE

        //print account created confirmation message
        ConfMess();

        //OK button then takes us back to menu
    }

A: Array.FindIndex would return position according to the predicate, if none of the item matched than it will return -1, For your case, you are assigning each element of the array in
for (int i = 0; i < MAX; i++)
       db[i] = new Account();

This will ensure that no item is null, hence -1 is returned from the Array.FindIndex, later when you use that position pos for accessing array element you get exception.
This line:
pos = Array.FindIndex(db, i => i == null);

Would set pos to -1 later when you do:
db[pos].SetAccount(textBox1, accNo, textBox2);

You will get exception.

A: you initialize your array with instantiated Account objects.
There's no guarantee the FindIndex() call would return a valid position (i.e pos would be assigned -1)
Following that, you might refer to db[-1], which would raise an exception.


text:
Q: How to order a looped list of calculated accuracies from highest to lowest? # Splitting into training and testing sizes

X_train, X_test, Y_train, Y_test = train_test_split(df['content'], label_df, test_size=0.2, random_state=1)

X_train looks like this:
566     deadly highly infectious avian flu forcing u f...
1546    join u today pm et citizencnn panel cost war f...
1676    troy kotsurs historymaking win full performanc...
2983    monday attack fox news crew reporting near ukr...
3203    louisiana state police hired outside consultan...
                              ...
905     mcdonalds bringing back spicy chicken mcnugget...
5192                      china name world hacking empire
3980    eu urgently discussing new sanction russia ukr...
235     hear offer ukrainian president zelensky made r...
5157    russia take measure decouple metallurgical pro...
Name: content, Length: 5141, dtype: object

Y_train - like this. The "label" are 0 and 1 meaning Fake News or Real News:
566     0
1546    0
1676    0
2983    0
3203    0
       ..
905     0
5192    1
3980    1
235     0
5157    1
Name: label, Length: 5141, dtype: int64

I have this loop to calculate predictions and their accuracies for a list of classifiers and I want to print the order by the accuracy results (from highest to lowest):
 # Show classification algorithm and accuracy

for name, classifier in models:
    print('\033[1m')
    print(name)
    classifier.fit(tfidf_X_train,Y_train)

    # Make predictions
    Y_pred = classifier.predict(tfidf_X_test)

    # Compute the scores
    score = metrics.accuracy_score(Y_test, Y_pred)
    print(f'\033[1mAccuracy\033[0m: {round(score*100,2)}%\n')

    #print(confusion_matrix(Y_test, Y_pred))

    #print(metrics.classification_report(Y_test, Y_pred))

This is what I get and want to be listed from Higher to Lower:
Multinomial Naïve Bayes Classifier
Accuracy: 89.35%

Passive Aggressive Classifier
Accuracy: 89.35%

Linear Support Vector Classification
Accuracy: 90.05%

Logistic Regression Classifier
Accuracy: 88.88%

Stochastic Gradient Descent Classifier
Accuracy: 89.74%

Random Forest Classifier
Accuracy: 89.81%

Decision Tree Classifier
Accuracy: 82.5%

K-Nearest Neighbours Classifier
Accuracy: 80.56%


text:
Q: Is there any library for this error or something else?  $_helper = $this->helper('catalog/output');

i received this error on browser when I run the code.
Using $this when not in object context in C:\xampp\htdocs\magento\test.php
What should i do for this .

A: you should have this:
require_once('app/Mage.php');
        $app = Mage::app();
        Mage::helper('catalog/output');

Basically the $this->helper is calling the function that is contained inside the current template's block class. The Mage::helper is calling the function in the "God" class.
The $this->helper normally calls a function in the class Mage_Core_Block_Abstract which checks the layout for a helper and then simply calls the normal Mage::helper if it cannot find one.

A: I think you are creating a stand alone script.
so you can try below things to work
require_once("$Magento_Root_DIR/app/Mage.php"); // include Mage.php file
$app = Mage::app(); //init Mage::app()
$_helper = Mage::helper('catalog/output'); //calling helper class


text:
Q: Random 2x2 tables with fixed margin totals in Julia Is there a way to generate a random 2x2 table with fixed margin totals (as with using r2dtable in R)?

A: If you need to sample only from 2x2 tables and assume that all admissible matrices are equally probable then you can use something like:
function rand2x2(r1::Integer, r2::Integer, c1::Integer, c2::Integer)
    if min(r1, r2, c1, c2) < 0 || r1+r2 != c1+c2
        error("invalid parameters")
    end
    a11 = rand(max(0, c1-r2):min(r1, c1))
    [a11 r1-a11; c1-a11 r2-c1+a11]
end

where r1 and r2 are row margins and c1 and c2 are column margins.

A: Without looking at the R implementation, perhaps the following:
function r2dtable(r::Tuple{Int,Int},c::Tuple{Int,Int})
    sum(r)==sum(c) || error("Rows and columns must sum to same number")
    min(r...,c...)>=0 || error("Input should be non-negative margins")
    rswap = indmin(r)==2
    cswap = indmin(c)==2
    r2 = minmax(r...)
    c2 = minmax(c...)
    rowismin = indmin((r2,c2))==1
    swapmat = [0 1 ; 1 0]
    cycle = rand(0:(rowismin ? r2[1] : c2[1]))
    base = rowismin ?
      [r2[1]-cycle 0+cycle ; c2[2]-r2[1]+cycle c2[1]-cycle] :
      [c2[1]-cycle r2[2]-c2[1]+cycle  ; 0+cycle r2[1]-cycle]
    return (swapmat^xor(rswap,!rowismin))*base*(swapmat^xor(cswap,rowismin))
end

is what you mean. You can use it for example, as follows:
julia> srand(2);

julia> r2dtable((2,2),(2,2))
2×2 Array{Int64,2}:
 1  1
 1  1

julia> r2dtable((2,2),(2,2))
2×2 Array{Int64,2}:
 0  2
 2  0

julia> r2dtable((2,2),(2,2))
2×2 Array{Int64,2}:
 2  0
 0  2

(this may contain bugs, so be sure to check it and perhaps fix them ;))


text:
Q: cx_Oracle equivalent of datetime64[ns] Given the following kind of data in a column of a Pandas data frame (Pandas data type is datetime64[ns]:
Contract_EffDt
1974-02-01

I want to import this (along with some string and int columns) into Oracle like this:
import cx_Oracle as cx
.
.
.
cur.setinputsizes(25,25,255,255,25,25,25,255,255,25,25,cx.DATE,int)
cur=con.cursor()
cur.bindarraysize = 1000
cur.executemany('''insert into Table(Contract_ID,Plan_ID,Org_Type,Plan_Type,Offers_Part_D,SNP_Plan,\
EGHP,Org_Name,Org_Mkt_Name,Plan_Name,Parent_Org,Contract_EffDt,YYYYMM) values (:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13)''', rows)
con.commit()
cur.close()
con.close()

How can I get cx_Oracle to recognize my datetime column for what it is and insert it accordingly? As you can see, I've tried cx.DATE but this doesn't work.
Thanks in advance!
Update with more information:
import cx_Oracle as cx
import pandas as pd
pwd=pwd
namec='table'
con = cx.Connection("table/"+pwd+"@server")
dfc=pd.read_csv(r'\\...\CPSC_Contract_Info_2016_03.csv',
                encoding='latin-1')
#taken from https://www.cms.gov/Research-Statistics-Data-and-Systems/Statistics-Trends-and-Reports/MCRAdvPartDEnrolData/Downloads/2016/March/CPSC-Enrollment-2016-03.zip
#^contract info file^
rows=dfc.values.tolist()
dfc['Contract_EffDt'] = pd.to_datetime(dfc['Contract_EffDt'])
dfc['Contract_EffDt'] = pd.to_datetime(dfc['Contract_EffDt'],format='%YYYY-%mm-%dd')
dfc['Plan_ID']=dfc['Plan_ID'].astype(str)
dfc.dtypes

Contract_ID               object
Plan_ID                   object
Org_Type                  object
Plan_Type                 object
Offers_Part_D             object
SNP_Plan                  object
EGHP                      object
Org_Name                  object
Org_Mkt_Name              object
Plan_Name                 object
Parent_Org                object
Contract_EffDt    datetime64[ns]
YYYYMM                     int64
dtype: object

cur.setinputsizes(25,25,255,255,25,25,25,255,255,25,25,cx.DATETIME,int)
cur=con.cursor()
cur.bindarraysize = 1000
cur.executemany('''insert into table(Contract_ID,Plan_ID,Org_Type,Plan_Type,Offers_Part_D,SNP_Plan,\
EGHP,Org_Name,Org_Mkt_Name,Plan_Name,Parent_Org,Contract_EffDt,YYYYMM) values (:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,to_date(:12,'yyyy-mm-dd'),:13)''', rows)
con.commit()
cur.close()
con.close()

Output:
TypeError                                 Traceback (most recent call last)
<ipython-input-152-6696ee05e0f2> in <module>()
      4 cur=con.cursor()
      5 cur.bindarraysize = 1000
----> 6 cur.executemany('''insert into table(Contract_ID,Plan_ID,Org_Type,Plan_Type,Offers_Part_D,SNP_Plan,EGHP,Org_Name,Org_Mkt_Name,Plan_Name,Parent_Org,Contract_EffDt,YYYYMM) values (:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,to_date(:12,'yyyy-mm-dd'),:13)''', rows)
      7 con.commit()
      8 cur.close()

TypeError: expecting numeric data


text:
Q: How to fix "Unmappable character for encoding windows-1252 error" displayed by Gradle build? When building my project in Android Studio by executing the Gradle release task, I get the following error:
error: unmappable character for encoding windows-1252
 * usage: app:behavior_saveFlags=ÔÇ?hideable|skipCollapsedÔÇ?
                                                            ^

It doesn't break the build or doesn't seem to cause any bugs so far from what I know of, however I would like to find out what's causing this issue.
The error seems to be triggered by some of the generated comment blocks in R.java:
/**
 * Behavior properties will be saved and restored by evaluating each flag.
 * usage: app:behavior_saveFlags="hideable|skipCollapsed"
 *
Must be one or more (separated by '|') of the following constant values.

My configuration:

*

*Android Studio 3.4

*Gradle Tools 3.4.0

*Gradle 5.4.1

A: You probably have a config for encoding in the android compileOptions in your build.gradle
Look for encoding = 'Cp1252' and remove it.
android
{
    compileOptions {
        encoding = 'Cp1252'
    }
}

A: Most likely it's attrs.xml, which reads encoding="utf-8".
Change all files of the project to UTF-8 encoding; some file might be Windows-1252 encoded.


text:
Q: Spring - Security - Trouble with authorizeRequests chain I can't understand, how to correctly make chain of the authorizeRequests chain.
If I write
 http
                .addFilterBefore(characterEncodingFilter(), CsrfFilter.class)
                .addFilterAfter(cacheControllerFilter(), CsrfFilter.class)
                .authorizeRequests()
                .antMatchers("/**").permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN").anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/admin/login.html")
                .defaultSuccessUrl("/admin/")
                .permitAll()
                .and()
                .logout()
                .permitAll();

in this case all is permitAll, including /admin/** .
If I have
http
                .addFilterBefore(characterEncodingFilter(), CsrfFilter.class)
                .addFilterAfter(cacheControllerFilter(), CsrfFilter.class)
                .authorizeRequests()
                .antMatchers("/**").permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN").anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/admin/login.html")
                .defaultSuccessUrl("/admin/")
                .permitAll()
                .and()
                .logout()
                .permitAll();

in this case everything, including /admin/** requires authentication of the user.

A: Found solution
http://docs.spring.io/spring-security/site/docs/3.2.5.RELEASE/reference/htmlsingle/#authorize-requests
In my case solution is
http
                .addFilterBefore(characterEncodingFilter(), CsrfFilter.class)
                .addFilterAfter(cacheControllerFilter(), CsrfFilter.class)
                .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().permitAll()
                .and()
                .formLogin()
                .loginPage("/admin/login.html")
                .defaultSuccessUrl("/admin/")
                .permitAll()
                .and()
                .logout()
                .permitAll();


text:
Q: Similar trick to git bisect WITHIN a commit With git bisect we can zoom in on when a problem might have been introduced between commits.
I was wondering if there is also a way to have git go through (combinations) of files within a single commit, so you can figure out which file / part is causing the trouble?

A: The recommended way to split a commit is with git rebase -i $commit_you_want_to_split^. Chop up your commit with the edit rebase action then a reset HEAD^ and a bunch of git adds to insert your new smaller commits into the index. Admittedly this isn't automatic, but you might be able to script it with a lot of sed or awk or python. See the the SO links above for more details.
Once your commit is chopped up, your git bisect will now be much more precise.
Has anyone automated this process?