text:
Q: Multi-form Issue I have 3 Forms that I want to be active at once. The first Form is the main window that is used to launch the other two. The problem I'm facing is with data transfer. It works when I use .ShowDialog(); to launch and transfer data. But I don't want the form to lock access to just that window. when I use form .Show(); It will transfer the data as default "0". Is there anyway around this? Is there a better way to achieve the same results, such as a utility window? What my end goal is to have separate active windows that will store there variables in the first form.
public partial class CH_Info : Form
{
    private Ch_Creation MyChcreation;

    public CH_Info()
    {
        InitializeComponent();
        MyChcreation = new Ch_Creation();
    }
    private void UpdateBtn_Click(object sender, EventArgs e)
    {
        //this grabs the text from the CH_Creation's STR,DEX,CON,INT,WIS,CHA Total Label
        StrResLbl.Text = MyChcreation.StrTotalLbl.Text;
        DexResLbl.Text = MyChcreation.DexTotalLbl.Text;
        ConResLbl.Text = MyChcreation.ConTotalLbl.Text;
        WisResLbl.Text = MyChcreation.WisTotalLbl.Text;
        IntResLbl.Text = MyChcreation.IntTotalLbl.Text;
        ChaResLbl.Text = MyChcreation.ChaTotalLbl.Text;
    }

This is using  CH_Info MyChInfo = new CH_Info(); MyChInfo.Visible = true;  and this is using .ShowDialog(); (The only way It works is if the Dialog box is closed)
The goal is to have the two other forms act as utility windows that I can exit out of and re-open while keeping there data until the program closes. Right now I only have form3 returning data to Form2. But I think if I find away to store the variables in the first Form I'll be able to achieve what I want. Which is to return the data back to the other Form when I re-open them. But to clarify, my current problem is keeping all 3 forms active without using .ShowDialog(); And like I said before, I can transfer data fine aslong as I do not use .Show();
Thanks for the help guys.

A: If there is only one form of type Ch_Creation opened at all times then it is simple a matter of searching the Application.OpenForms collection for your open form of type Ch_Creation and use the instance stored for you by the Winforms engine in that collection
public CH_Info()
{
    InitializeComponent();
    MyChcreation = Application.OpenForms.OfType<Ch_Creation>().FirstOrDefault();
}
private void UpdateBtn_Click(object sender, EventArgs e)
{
    if(MyChcreation != null)
    {
        StrResLbl.Text = MyChcreation.StrTotalLbl.Text;
        DexResLbl.Text = MyChcreation.DexTotalLbl.Text;
        ConResLbl.Text = MyChcreation.ConTotalLbl.Text;
        WisResLbl.Text = MyChcreation.WisTotalLbl.Text;
        IntResLbl.Text = MyChcreation.IntTotalLbl.Text;
        ChaResLbl.Text = MyChcreation.ChaTotalLbl.Text;
    }
    else
    {
        StrResLbl.Text = "";
        DexResLbl.Text = "";
        ConResLbl.Text = "";
        WisResLbl.Text = "";
        IntResLbl.Text = "";
        ChaResLbl.Text = "";
    }
}

As a measure of precaution always check is a reference variable (like MyChcreation) is null before trying to use its members...


text:
Q: Facebook share count not working - new API? A few days ago facebook stopped displaying share count information in graph. how is it currently downloaded to display on a page in php?
always after entering this link, there was also information about the number of shares and currently there is no: https://graph.facebook.com/https://demotywatory.pl/4922745/Dziecko-nie-wie-ze-to-rzezba-po-prostu-chce-pomoc
  I want to display this information on my website. how to do it? please help

A: This info is now provided under the engagement field of the URL object node.
https://developers.facebook.com/docs/graph-api/reference/v3.2/url
/?id={url}&fields=engagement

https://developers.facebook.com/tools/explorer?method=GET&path=%3Fid%3Dhttps%3A%2F%2Fdemotywatory.pl%2F4922745%2FDziecko-nie-wie-ze-to-rzezba-po-prostu-chce-pomoc%26fields%3Dengagement&version=v3.2

A: Its working like below with facebook's app_id & app_secret.
https://graph.facebook.com/?id={URL}&fields=engagement&access_token={your-app_id}|{your-app_secret}

output :

{
  "engagement": {
    "reaction_count": 5,
    "comment_count": 3,
    "share_count": 60,
    "comment_plugin_count": 0
  },
  "id": "https://www.testing.com"
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java PriorityQueue custom Comparator In my PriorityQueue I have 2 types of customers, VIP and regular. I want to serve VIP first, then regular.
If CustomerID < 100 it is considered to be VIP.
If a customer is VIP he goes at the end of VIP part of the queue
If a customer is regular he goes at the end of the entire queue.
In other words, I want to sort by boolean VIP value, while preserving the order in which customers came in.
Here's my Order class
public class Order implements Comparable<Order> {
    private final int customerID;
    private final int amount;
    private final boolean vip_status;

    public Order(int customerID, int amount) {
        this.customerID = customerID;
        this.amount = amount;
        this.vip_status = customerID < 100 ? true : false;

    }

    @Override
    public int compareTo(Order o) {
        if (vip_status && !o.vip_status) {
            return -1;
        }
        if (!vip_status && o.vip_status)
            return 1;
        return 0;
    }

    public int getCustomerID() {
        return customerID;
    }

    public int getAmount() {
        return amount;
    }

    public boolean isVip_status() {
        return vip_status;
    }
}

Here's my attempt to fill the queue:
import java.util.PriorityQueue;

public class MyPriorityQueue {
    public static void main(String[] args) {
        PriorityQueue<Order> queue = new PriorityQueue<>();
        Order o1 = new Order(1, 50);
        Order o2 = new Order(5, 30);
        Order o3 = new Order(4, 10);
        Order o4 = new Order(150, 5);
        Order o5 = new Order(2, 5);
        Order o6 = new Order(200, 5);

        queue.add(o1);
        queue.add(o2);
        queue.add(o3);
        queue.add(o4);
        queue.add(o5);
        queue.add(o6);

        while(!queue.isEmpty()){
            Order s = queue.poll();
            System.out.printf("VIP Status: %s CustomerID: %s Amount: %s%n",
                        s.isVip_status(), s.getCustomerID(), s.getAmount());
        }
    }
}

RESULT that I'm getting (which is wrong):
VIP Status: true CustomerID: 1 Amount: 50
VIP Status: true CustomerID: 5 Amount: 30
VIP Status: true CustomerID: 2 Amount: 5
VIP Status: true CustomerID: 4 Amount: 10
VIP Status: false CustomerID: 150 Amount: 5
VIP Status: false CustomerID: 200 Amount: 5

This is what I expected to see (CustomerID 2 and 4 should be in the same order they came in):
VIP Status: true CustomerID: 1 Amount: 50
VIP Status: true CustomerID: 5 Amount: 30
VIP Status: true CustomerID: 4 Amount: 10
VIP Status: true CustomerID: 2 Amount: 5
VIP Status: false CustomerID: 150 Amount: 5
VIP Status: false CustomerID: 200 Amount: 5

UPDATE: I don't want sort by any other column except VIP. I don't want add "date" because it feels like a hack, rather than understanding how Java works.

A: It appears that the PriorityQueue class that java comes with out of the box feels free to reorder items if they compare as equal to each other.
(This is not "how java works", it is just a little perversion on behalf of a certain class that comes with the Java Runtime.)
So, here is something that will probably work:

*

*Introduce a new OrderPlacement class, containing a) an Order and b) an int priority.

*In your PriorityQueue add OrderPlacement objects instead of Order objects.

*When you create a new OrderPlacement object, issue a new priority for it, by incrementing a counter.
Then, your OrderPlacement object can have a compareTo() method that looks like this:
@Override
public int compareTo( OrderPlacement o )
{
    int d = -Boolean.compare( order.vip_status, o.order.vip_status );
    if( d != 0 )
        return d;
    return Integer.compare( priority, o.priority );
}

A: If you must do it using priority queue, below code will solve your problem. Do note that I am using a static counter to maintain correct order of elements with same VIP status as equal elements are maintained in random order inside priority queue. This is because priority queue uses a min / max heap data structure and it only cares about placing min / max element at top of heap and does not bother about ordering of same elements.
import java.util.PriorityQueue;

public class Order implements Comparable<Order> {
  private final int customerID;
  private final int amount;
  private final int vip_status;
  private final int score;
  private static int counter = 0;

  public Order(int customerID, int amount) {
    this.customerID = customerID;
    this.amount = amount;
    this.vip_status = customerID < 100 ? 0 : 1;
    this.score = counter++;
  }

  @Override
  public String toString() {
    return customerID + " : " + amount + " : " + vip_status;
  }

  @Override
  public int compareTo(Order o) {
    int status = ((Integer) this.vip_status).compareTo(o.vip_status);
    status = status == 0 ? ((Integer) this.score).compareTo(o.score) : status;
    return status;
  }

  public static void main(String[] args) {
    Order o1 = new Order(1000, 100);
    Order o2 = new Order(500, 100);
    Order o3 = new Order(99, 100);
    Order o4 = new Order(10, 100);
    Order o5 = new Order(200, 100);
    Order o6 = new Order(1, 100);

    PriorityQueue<Order> orderQueue = new PriorityQueue<>();
    orderQueue.offer(o1);
    orderQueue.offer(o2);
    orderQueue.offer(o3);
    orderQueue.offer(o4);
    orderQueue.offer(o5);
    orderQueue.offer(o6);

    System.out.println(orderQueue.poll());
    System.out.println(orderQueue.poll());
    System.out.println(orderQueue.poll());
    System.out.println(orderQueue.poll());
    System.out.println(orderQueue.poll());
    System.out.println(orderQueue.poll());
  }
}

`
Sample Output:
99 : 100 : 0
10 : 100 : 0
1 : 100 : 0
1000 : 100 : 1
500 : 100 : 1
200 : 100 : 1

Note: you need to be aware that score may eventually reach Integer.MAX_VALUE


text:
Q: rhandsontable using a dropdown to "hide" columns I have a data frame that I am passing to a rhandsontable. Let's say it has 10 columns. I have a drop-down that has 3 choices:

*

*Show columns 1 through 5

*Show columns 1, 5 and 10

*Show columns 6 through 10

Be default, when the rhandsontable loads, it will show all 10 columns. When the use selects one of the three options in the drop-down, I want to hide certain columns using the hot_col(col = col_name, width = 0.5)
For example, if the user selects option 1 - Show columns 1 through 5, hiding columns 6 through 10 would look something like:
rhandsontable(df) %>%
hot_col(col = column_6, width = 0.5) %>%
hot_col(col = column_7, width = 0.5) %>%
hot_col(col = column_8, width = 0.5) %>%
hot_col(col = column_9, width = 0.5) %>%
hot_col(col = column_10, width = 0.5)

I attempted filtering the data set with something like:
df <- if (input$dropdown == "Show columns 1 through 5") {df %>% select(1:5)}
else if (input$dropdown == "Show columns 1, 5 and 10") {df %>% select(1, 5, 10)}
else if (input$dropdown == "Show columns 6 through 10") {df %>% select(6:10)}
else {df %>% select(1:10)}

which works for only showing specific columns, but I have hot_col rules specific to different columns which bombs because if I have a rule saying that column_6 is of date type, it won't find column_6 if "Show columns 1 through 5" is chosen.
Sorry I don't have a working example, but hope this makes sense. Thanks!

A: You can determine from the selectInput which columns should be hidden and then use this information in the renderRHandsontable call to dynamically hide columns:
library(shiny)
library(rhandsontable)
ui <- fluidPage(
  fluidRow(
    column(width = 6,
           selectInput( inputId = "columns",
                        label = "select columns",
                        choices = c("all", "first half", "second half")
           )

    ),
    rHandsontableOutput("table")
  )
)

server <- function(input, output, session) {

  output$table <- renderRHandsontable({
    output <- rhandsontable(mtcars[, 1:4])

    # determine the columns to show
    if (input$columns == "all") columns_to_hide <- NULL
    if (input$columns == "first half") columns_to_hide <- 3:4
    if (input$columns == "second half") columns_to_hide <- 1:2

    used_colnames <- colnames(mtcars[, 1:4])

    if (!is.null(columns_to_hide)) {
      for (col_name in used_colnames[columns_to_hide]) {
        output <- output %>% hot_col(col = col_name, width = 0.5)
      }
    }

    output
  })
}
shinyApp(ui, server)


text:
Q: Как корректно отобразить объект на странице Проблема такая, ко мне на страницу заходят пользователь(новая страница - новый пользователь), все они заносятся в объект объектов с полями name и id, если мы откроем 1 страницу пользователь запишется корректно, если откроем вторую, то на второй странице будет все хорошо(допустим andrey, john), а на первой будет andrey, andrey, john. и так каждая последующая страница имеет дубликаты, как можно выводить без них?
Вот код:
const addUserToModalWindow = () => {
    const contentWindow = document.querySelector(".usersList");
    socket.on('users', (users) => {
        for (let user of Object.values(users)) {
            contentWindow.innerHTML += `<div>• ${user.name}</div>`;
        }
    });
};

Вот как выглядит на сайте и хранится на сервере объект:

A: Сейчас текст постоянно дописывается в конец
contentWindow.innerHTML +=

Чтобы не дублировать вывод достаточно либо очищать элемент перед циклом вывода:
contentWindow.innerHTML = '';
for (let user of Object.values(users)) {

либо добавить событие добавления пользователя в котором получать только нового добавленного пользователя.


text:
Q: Visual Studio 2013 Web Deploy Package and Physical IIS Path at runtime When I import a Web Deploy Package into IIS 7 it installs to a physical path under the default IIS directory (c:\inetpub\www) on Windows Server 2008 R2.
I am using Visual Studio 2013 Community Edition to create the Web Deploy Package and following the instructions here.  At the end of that link it says you can specify the physical IIS path but I want the user installing it to be able to choose the physical IIS path at runtime not have it set the same for all installations.
Is it possible to do this with a Web Deploy Package?  I want to avoid creating an installer with Wix.


text:
Q: If I use SSLSocket in Android and hard code the passcode to the truststore in the source code is that insecure? I am using java's SSLSocket to securely connect an android application to a server. The certificate is located in a truststore. But the passcode to the truststore seems to be required for the connection and so it is currently hardcoded into the device. I don't know much about PKI but that doesn't seem secure. I am bundling the truststore with the application in the raw resources folder. Is there a better approach to securely allow an application to connect to a server using TLS? I am very much new to TLS/SSL so I would appreciate any help or recommendations.
Here is the client side of the code.
        store = KeyStore.getInstance("BKS");
        InputStream in = appcontext.getResources().openRawResource(R.raw.truststore);
        store.load(in, "PASSWORD".toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        tmf.init(store);
        sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, tmf.getTrustManagers(), new SecureRandom());

        SSLSocketFactory sslsocketfactory = sslcontext.getSocketFactory();

        // connect to socket
        SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(
                "192.168.1.16", 9999);

A: I haven't tried on Android, but here is how it works in plain Java.
You're using your keystore as a truststore here, so (hopefully) it doesn't contain any private key or secret material. In this case, the purpose of the password is to verify the integrity of the store.
From the Keystore.load(InputStream, char[]) documentation:

A password may be given to unlock the keystore (e.g. the keystore
  resides on a hardware token device), or to check the integrity of the
  keystore data. If a password is not given for integrity checking, then
  integrity checking is not performed.

Either you use null as the password (in which case you'll always be able to load the certificates) or you use a non-null char array with the actual password (in which case an incorrect password will fail with something like "java.io.IOException: Keystore was tampered with, or password was incorrect").
Using a password here is meant to increase the security (to prevent the truststore to be tampered with). This being said, if you're bundling both this truststore and this application together, it's likely that an attacker able to replace the truststore would also gain access to the password (by decompiling) anyway. (I'm not too familiar with Android app distribution, but if apps are signed, it's possible that tampering with raw resources such as your truststore would invalidate the signature too, so that might be a more realistic way of having this protection. Otherwise, I guess you can ask the user to input the truststore's password every time, but that seems unrealistic.)

It's not really part of your question, but to secure the SSL/TLS connection, you also need to verify that the certificate sent by the server is valid for the host name you were trying to reach, after SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("192.168.1.16", 9999);.
This was discussed recently in this question in Java. (Unfortunately, you won't be able to use the new Java 7 API to do this automatically for you on Android, so you'll have to check the certificate a bit more manually. You might also be interested in this recent question.)

EDIT (following your comment):

I'm concerned about someone recompiling the application, retrieving
  the passcode and the truststore and using it to connect to my server.
  If it is possible then it kind of defeats the purpose of the TLS in
  the first place.

It's not clear from this comment you understand the purpose of the truststore (see this question, for example).
The purpose of the truststore in your client app isn't to authenticate your app to the server, it is to make sure your client can verify the identity of the server it connects to, so that it can't be tricked into connecting to a MITM attacker. It's not about how your server trusts your app/client/user, but it's about how your app trusts your server.
Authenticating the app user to the server would be the purpose of a keystore. This is fine for authenticating the user (but it would make more sense if each user had a different certificate). Making sure connections can only come from your app is another, much more difficult problem (a lost cause, if you don't have complete control of the client hardware at all times). Using a common client certificate in your app could buy you a bit of time, but anyone who has got hold of the client code could certainly reverse engineer it eventually. I wouldn't spend too much time on it. You might be interested in these questions:

*

*How can I securely authenticate the client application sending me data?

*Authenticating client without hardcoding key?

*Client code tampering detection

A: Problem:
Anything you include in your source code is readable by anyone who has obtained the apk file. Therefore, if you include your passcode and truststore in your source code (or your resource files), it can be read by anyone with the apk.
In fact, it is impossible to guarantee that the app connecting to your server is your own app. Imagine a modified Dalvik VM, which waits until your app has run SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("192.168.1.16", 9999);, and then passes sslsocket to another app.
Solution:

*

*Move your trusted code to the server. For example, if you have a method in your app called addNewProductDirectlyToDatabaseOnServer, replace it with a method called addNewProductToServer, and have it call a REST API for your server, that adds a new user, without letting evil apps directly control your databases.

*Authenticate individual users using passwords. This isn't strictly necessary, but it helps make sure that the right people are accessing your server, and if a badguy ever gets someone's password (or if someone becomes a badguy), you can revoke their access to the server by disabling their password/login.

If you're interested in learning more about how attackers could pull your source code out of your apk file, I would recommend looking at these tools:

*

*https://code.google.com/p/android-apktool/ - apktool

*https://code.google.com/p/dex2jar/ and http://java.decompiler.free.fr/?q=jdgui


text:
Q: Is the universe expanding on a preferred axis, or asymmetrically? I remember back in 2011 i found this paper on the research a team of Chinese physicist completed about the universe may having a prefered axis when expanding.
On ARXIV
I haven't seen any other papers released on the same topic and i'm wondering if any new evidence or papers have been released since then. Or if anyone has some information on it that would be great.

A: This paper on the Arxiv claims to have measured an anisotropy at the $2\sigma$ level. I'm not familiar enough with the subject to pass judgement, though I get the impression that the general view is interesting but unproven at the moment. If nothing else the paper gives a convenient literature review.
Various anisotropies have been suggested, such as a north-south anisotropy in the fine structure constant and the axis of evil alignment of low multipoles in the CMB data. However the various proposed anisotropies don't line up with each other, which strengthens the skeptics case.


text:
Q: Input button script conflicting with other buttons - How to make unique? I have many buttons in one form.  I made one script for a few particular buttons and now my other buttons are not working correctly.
Is it possible to make my button script unique for only the designated butons avoiding conflict with other buttons? It appears "input[type='button']" applies to all buttons in the form when I only want it to apply to a few in the script.
Here is the script I wish to modify to only work for a few particular buttons:
$(document).ready(function(){
   $(function() {
      var $buttons = $("input[type='button']");
      $buttons.click(function() {

      $(this).parent().siblings('.bx, #bxGender .gender').css({'background':'#2F2F2F','color':'#fff'});
    $buttons.not(this).removeClass('button-toggle-on');
    $(this).toggleClass('button-toggle-on').attr('style','');

    var varval = '';
    if ($(this).hasClass('button-toggle-on')) {
        varval = $(this).hasClass('gnF') ? 'Female' : 'Male';
        $(this).siblings('input[type="button"]').css('background-position','0 -180px');
    }
    else {
          $(this).siblings('input[type="button"]').attr('style','');
       $(this).parent().siblings('.bx').attr('style','');
    }
    $("#gender").val(varval);
 });});
 });

 <input type="button" class="gnM" >
 <input type="button" class="gnF">
 <input class="req-string gender" id="gender" name="gender">

A: Check this link http://api.jquery.com/category/selectors/
You can use dom element's id, class, name & many others to select elements using jquery.
So, to narrow down your selection to the buttons you wish better use same class attribute
Ex:
HTML:
<input type='button' class='mine' value='hai' />
<input type='button' class='not-mine' value='hai' />
<input type='button' class='not-mine' value='hai' />
<input type='button' class='mine' value='hai' />

and then using jquery
$('.mine').click() or $('.mine').addClass or any valid jquery function you wish to use
jQuery returns the proper this attribute even if there are many dom elements match your selector attribute [here there are 2 buttons with same class].
A complete example:
http://jsfiddle.net/AEkbh/2/

A: Like this? Here's an example of using classes to only affect certain elements.
$(document).ready(function(){
    $(function() {
        $(".special-button").click(function() {

            $(this).parent().siblings('.bx, #bxGender.gender').css({'background':'#2F2F2F','color':'#fff'});
            $(this).siblings('.special-button').removeClass('button-toggle-on');
            $(this).toggleClass('button-toggle-on').attr('style','');

            var varval = '';
            if ($(this).hasClass('button-toggle-on')) {
                varval = $(this).hasClass('gnF') ? 'Female' : 'Male';
                $(this).siblings('.special-button').css('background-position','0 -180px');
            }
            else {
                $(this).siblings('.special-button').attr('style','');
                $(this).parent().siblings('.bx').attr('style','');
            }
            $("#gender").val(varval);
        });
    });
});

 <input type="button" class="gnM special-button" >
 <input type="button" class="gnF special-button">
 <input class="req-string gender" id="gender" name="gender">

A: Or if you still want to contain all your button handlers in one method but target specific ones:
$( document ).ready( function(){
  $( "input[type='button']" ).click( function( e ){
    var $this = $( this );
    switch( true ){
      case $this.hasClassName( "special-button" ):
        //do some stuff
      break;
      case $this.attr("name") === "gender":
        //do something else
      break;
      default:
        //catch all other cases
     }
   });
 });

So many ways to skin a javascript cat


text:
Q: Is the sort-order of table-valued-parameters guaranteed to remain the same? I need to know if i need to add a sort-column to my custom table-type which i could then use to sort or if i can trust that the order of parameters remains the same even without such a column.
This is my type:
CREATE TYPE [dbo].[VwdCodeList] AS TABLE(
    [VwdCode] [varchar](50) NOT NULL
)

and this is one of the sql where is use it:
/// <summary>
///     Inserts all new WatchListCodes for a given watchlist
/// </summary>
public const string InsertWatchListCodes = @"
INSERT INTO [dbo].[WatchListCodes]
   ([WatchListID]
   ,[VwdCode]
   ,[Sort])
 SELECT @WatchListID, VwdCode, ROW_NUMBER()OVER(ORDER BY (SELECT 1))
 FROM @VwdCodeList;";

as you can see i'm using ROW_NUMBER to get the sort-column value.
Do i need to add also a sort-column to the table-type or is it guaranteed(documented) that it remains the same? It seems to work.
This is the ADO.NET code where  i use it:
SqlParameter vwdCodeListParameter = insertWatchListCodeCommand.Parameters.Add("@VwdCodeList", SqlDbType.Structured);
vwdCodeListParameter.TypeName = "[dbo].[VwdCodeList]";
vwdCodeListParameter.Value = WatchListSql.GetVwdCodeRecords(newVwdCodes, true);
int inserted = insertWatchListCodeCommand.ExecuteNonQuery();

GetVwdCodeRecords returns IEnumerable<SqlDataRecord> for an IEnumerable<string>.

Thanks all. If a future reader is interested to know how i've guaranteed the sort-order. I've modifed the table-type as suggested by adding another column:
CREATE TYPE [dbo].[VwdCodeList] AS TABLE(
    [VwdCode] [varchar](50) NOT NULL,
    [Sort] [smallint] NOT NULL
)

The insert-sql is even simpler because the sort-column is passed in and not calculated:
public const string InsertWatchListCodes = @"
INSERT INTO [dbo].[WatchListCodes]
   ([WatchListID]
   ,[VwdCode]
   ,[Sort])
 SELECT @WatchListID, cl.VwdCode, cl.Sort
 FROM @VwdCodeList cl;";

For the sake of completeness, here is the method that returns the IEnumerable<SqlDataRecord> used as value for the table-valued-parameter(omitted error-handling):
public static IEnumerable<SqlDataRecord> GetVwdCodeRecords(IEnumerable<string> vwdCodes, bool trimCode = true)
{
    short currentSort = 0;
    foreach (string vwdCode in vwdCodes)
    {
        var record = new SqlDataRecord(
            new SqlMetaData("VwdCode", SqlDbType.VarChar, 50),
            new SqlMetaData("Sort", SqlDbType.SmallInt));
        record.SetString(0, trimCode ? vwdCode.Trim() : vwdCode);
        record.SetInt16(1, ++currentSort);

        yield return record;
    }
}

A: In general: There is no implicit sort order on any result set.
The only way to achieve a guaranteed sort order is an ORDER BY on the outer-most query.
I'm sure you knew this already...
There is one specialty with ROW_NUMBER() OVER(ORDER BY ...) Read "General Remarks". But this is dangerous.

*

*The sort-order is only sure, if you are using a unique sort criterium in ORDER BY. You are using SELECT 1, which will not guarantee any sort order. This might work hundreds of tests and suddenly breaks...

*Any later action can destroy this sort-order. Just imagin you have a working function and - some months later - you use this function in a complex query.

I use this for example to create XML with a sure order, because within XML there is an implicit order given by position...

A: Yes, you need to add a column. SQL is a set-based language and sets are inherently unordered (admittedly, there are more than a few cases where SQL is kind of leaky about this).
If you want to use ORDER BY and you want to guarantee the results, you need to ensure that it's based on enough expressions based on the data within the table such that it uniquely defines the ordering. Here, you're ordering by a constant (and the warnings you receive if you just try ORDER BY 1 here should be enough clue that its not going to work well) so there are no guarantees on what ordering is actually applied.

A: Same order is not guaranteed unless you do an explicit order by..
Below are some tests..
 create type numbes as table
 (
 num int primary key
 )

 DECLARE @nums AS numbes;

 insert into @nums
 select row_number() over(order by(select 1))
 from
 master.sys.objects

 select Top 100* from @nums

and execution plan shows..

So below piece of code..
ROW_NUMBER()OVER(ORDER BY (SELECT 1))
 FROM @VwdCodeList;";

may not get you same order every time,unless you mention explicit order by


text:
Q: What is the fastest way to convert the following byte array -> collection of class objects I have a byte array which can contain millions of bytes and is represented by the following structure: The array breaks down into n segments of 16 bytes each. The first 8 bytes of each segment represent a value of type long (8 bytes), followed by 2 values each of type short (2* 4 bytes).
I look for the absolute fastest way to convert the byte array segments into a collection of class objects of the following type:
public class Foo
{
    public long Value1 { get; set; }
    public float Value2 { get; set; }
    public float Value3 { get; set; }

    public Foo(long value1, float value2, float value3)
    {
        Value1 = value1;
        Value2 = value2;
        Value3 = value3;
    }
}

What I have tried done so far was using the BitConverter.ToInt64(...),... but the conversion takes way too long given I have to deal with arrays of sizes in the millions of bytes and several hundred of such arrays.
var collection = new List<Foo>();
        var byteArraySize = byteArray.Count();
        for (var counter = 0; counter < byteArraySize; counter += PacketLength) //Packetlength here is 16
        {
            collection.Add(new Foo(
                               BitConverter.ToInt64(byteArray, counter),
                               BitConverter.ToSingle(byteArray, counter + 8),
                               BitConverter.ToSingle(byteArray, counter + 12)));
        }

Can someone please show me how to apply bit-shift logic to speed up this procedure. Unsafe code, using pointer logic, would also work.
Thanks a lot.

A: The following codes needs 4.668 seconds to process 1 GiB of data on my machine, out of which 0.028 seconds are spent on converting the data and 4.641 seconds on creating Foo objects. Your original code needs 6.227 seconds.
unsafe Foo[] Load(byte[] buffer, int offset, int length)
{
    fixed (byte* ptr = buffer)
    {
        Data* data = (Data*)(ptr + offset);
        Foo[] result = new Foo[length / sizeof(Data)];
        for (int i = 0; i < result.Length; i++)
        {
            result[i] = new Foo(data);
            data++;
        }
        return result;
    }
}

with
struct Data
{
    public long Value1;
    public float Value2;
    public float Value3;
}

and
class Foo
{
    public long Value1 { get; set; }
    public float Value2 { get; set; }
    public float Value3 { get; set; }

    public unsafe Foo(Data* data)
    {
        Value1 = data->Value1;
        Value2 = data->Value2;
        Value3 = data->Value3;
    }
}


text:
Q: Recognizing years without preposition with Duckling I'm trying to get the year from this sentence :
"events 2015"
Only grabs 2015 as a number.
But if I put the sentence in https://duckling.wit.ai/ grabs 2015 correctly as year, even if I just put 2015.
What can I do to have this behav in my side?
Regards

A: Try to add locale in your request.
It works with "en_us" or "en_gb"


text:
Q: Jasmine - why does it give me an error on a simple getElementsByTagName(...) Html:

{{person.nome +" - "+ person.citta}}

Piece of my script.js with AngularJS (1.3.1):
mymod.controller("maincontroller", function($scope){

    $scope.people = [
        { name: "name1", city: "city1" },
        { name: "name2", city: "city2" },
        { name: "name3", city: "city3" }
    ];

    $scope.oldIndex = 0;
    $scope.oldPerson = 0;
$scope.selPersonToChange = function(){

    $scope.personToChange.person = this.person;
    $scope.personToChange.index = this.$index;

    lis = document.getElementById("listONE").getElementsByTagName("li");//here it report an error
    for(i=0; i<lis.length; i++){ lis[i].className = ""; }
    lis[this.$index].className = "selected";
    return true;
}

Jasmine tdd:
Jasmine tdd.js:

describe("myApp", function(){

    beforeEach(module("mymod"));

    describe("maincontroller", function(){

        var scope;
        var ctrl;
        var els;
        beforeEach(inject(function($rootScope, $controller, $compile){
            scope = $rootScope.$new();
            ctrl = $controller("maincontroller", {$scope:scope});
            els = $compile('

{{person.nome +" - "+ person.citta}}

')(scope);
            scope.$digest();
            console.log(els.html());

        }));

        it("Is ul #listONE null or undefined?", function(){
            expect(scope.selPersonToChange()).toEqual(true);
        });

    });

});

The real problem is "document.getElementById('listONE')", because it return to me that "listONE" doesn't exist.

A: There is no way for your controller to find that element because in your test you're not telling AngularJS to "load" any view. You're just instantiating the controller which doesn't load your html.
If you're using ngRoute module in your app, you could try to inject and use in your test the $location service in order to force a path to be loaded, which involves using the controller and loading the assigned template. Let's say that you have /some/path path that uses your controller and your html. You could do a $location.path('/some/path') and a $rootScope.$apply() before your assertions.
If you're not using ngRoute, I guess that you could try to $compile a template defined in your tests that includes some
...
 code in it.


text:
Q: Supremum family of measurable functions is not measurable Let $(f_i)_{i\in I}$ be an uncountable family of measurable functions $f_i:X \to \mathbb{R}$. Show that functions defined by,
$$ h(x)=\inf\{ f_i(x) : i \in I \} \:\:\: \text{for each }x \in X$$
and
$$ g(x)=\sup\{ f_i(x) : i \in I \} \:\:\: \text{for each }x \in X$$
are not measurable in generality.
The idea
let's take a non-measurable set E, then
$\mathbb{1}_{ \{e\} }$ where $e \in E$, indicator functions are measurable. However
$$ g(x)= \mathbb{1}_ {E} $$ is not measurable but I do not know why.
For $h(x)$ we just take $-\mathbb{1}_{ \{e\} }$.
Is there any possibility that someone will clarify the problem?


text:
Q: Listen to a dynamic number of dojo widgets (dijits) I need to dynamically generate a web page UI using Javascript and dojo. I need to listen to the generated widgets in order to react on user input, but I cannot determine which one was changed...
var combobox = new dijit.form.ComboBox(
{
    id: id,
    store: dataStore,
    onChange: dojo.hitch(this, this._comboChanged)
});

In the call to _comboChanged I get the new value, but I also need to know which combo was pressed. There can be any numbers of combos and currently I store them in an array after creation.

A: You can pass the combo box itself to the comboChanged method:
var combobox = new dijit.form.ComboBox(
{
  id: id,
  store: dataStore
});
combobox.onChange = dojo.hitch(this, this._comboChanged, combobox);


text:
Q: Clojure - the fastest way to extract the last N bits in an integer? I need a function that extracts last N bits in an integer (N < 32 so the result is always positive). I cannot seem to work it out myself.
My first approach was to left shift (32 - n) bits then shift right (32 - n) bits, however Clojure converts the first result to BigInt thus I'm unable to get rid off the first 32-n bits.
Could anybody help please? Thanks!

A: I think what you want is something using bitwise and, for instance:
(defn low-bits [x n]
    "Get the lowest n bits of x"
    (bit-and x (unchecked-dec (bit-shift-left 1 n))))

Taking n 8, (bit-shift-left 1 8) gives us 256, then (dec 256) gives us 255, a number which has the lowest 8 bits set and the higher bits 0. Then the bitwise and will give us a number where the lowest 8 bits are whatever they were in x, and the higher bits are all 0 (which is what you want I think?).
Disclaimer: This is probablty the 4th Clojure function I've written, so I'm just learning too...


text:
Q: Large data and high dimensionality As I assume, we more often have datasets with (A) very many cases (objects) and not so many variables (properties) (= large data) than the other way around: (B) just a few cases and many more variables (= high dimensionality).
There are other conceivable cases: (C) few cases, few variables, (D) very many cases, equally many variables.
I assume, that for these different cases, different statistical methods will be applied. Is this true, and how can these be characterized?
Further, I wonder, how often each of these cases does occur in practice (proportionally, estimated) - and from which disciplines they typically stem.

A: This question may be too broad to answer. What model to use depends on the hardware software and the requirement from business. In addition, as mentioned in the comments, different fields may have different definitions on how big the data is.

*

*In medical study, it is very costly to get few data points. If we have thousands patient's data with different treatment, that would be considered is big enough.

*In bioinformatics, we usually have many "features" (say from DNA) but few "instances".

*In computer science, say pattern recognition on images. It is very common to have billion of instances (pictures) and millions of features (pixels in an image) for one instance.


text:
Q: Show that $\frac{a+b}{2} \geq \sqrt{ab} \geq \frac{2ab}{a+b}$ Question:

Show that the harmonic mean is less than or equal to the arithmetic mean, and also less than or equal to the geometric mean, with equality if and only if $a=b$ ; ie., show that $$\frac{a+b}{2} \geq \sqrt{ab} \geq \frac{2ab}{a+b}$$

My attempt,
I've shown the first equality which is $$\frac{a+b}{2}-\frac{2ab}{a+b}=(a-b)^2\geq0$$
My first question, should I write $\frac{(a-b)^2}{2(a+b)}\geq0$ or just leave as $(a-b)^2\geq0$?
For the second,
$$\sqrt{ab}-\frac{2ab}{a+b}=\frac{\sqrt{ab}(a+b)-2ab}{a+b}$$
$$=\frac{a^{\frac{3}{2}} \sqrt{b}+\sqrt{a} b^{\frac{3}{2}}-2ab}{a+b}$$
$$=\frac{\sqrt{ab}(a+b-2\sqrt{ab})}{a+b}$$
I stuck at here. Can anyone explain to me how to solve this question Thanks in advance.
**I found other similar questions being asked in this site. But my question includes harmonic  which is not a duplicate.

A: From AM-GM,
$$\frac {a+b}2\ge\sqrt{ab}\tag{1}$$
Cross-multiplying,
$$\frac 1{\sqrt{ab}}\ge \frac 2{a+b}\\
\frac{\sqrt{ab}}{ab}\ge \frac 2{a+b}$$
$$\sqrt{ab}\ge \frac {2ab}{a+b}\tag{2}$$
Combining $(1),(2)$ gives
$$\color{red}{\frac {a+b}2\ge \sqrt{ab}\ge \frac {2ab}{a+b}}$$

A: You are almost there with the second part:
$$
\frac{\sqrt{ab}(a+b-2\sqrt{ab})}{a+b} \ge 0
$$
because
$$
a+b\ge2\sqrt{ab} \quad\Leftrightarrow\quad {a+b\over2}\ge\sqrt{ab}
$$
(this has been already proved in the first part). Just like with the AM-GM case, we have equality only when $a=b$.


text:
Q: How to make setuptools fail if it can't find some of the files declared in MANIFEST.in? Had some files declared in MANIFEST.in, half of them were missing from the project directory. When I ran python3 setup.py install it has copied files that were present and gave no warning or error about the missing ones.
How to make it fail when some of the include_package_data files are missing?

A: Well, the only think I found is to parse output from python setup.py dist_info:
python setup.py dist_info 2>&1 >/dev/null |
    grep '^warning: no files found matching'

Can be used as a condition:
if python setup.py dist_info 2>&1 >/dev/null | grep '^warning: no files found matching'; then
    echo "Error: missing files" >&2
    exit 1
fi


text:
Q: Bake-in logging statements of a Catch block I'm working with a .Core 3.1 app that will have the conventional try/catch blocks --- all of them formed similar to:
Logger.LogWarning(ex, "Failed to load product {ProductId}",

There's going to be lots of these blocks -- logging the catch will be pretty much the same for all of them: A string message that will be unique per block plus the exception message.
So if every catch block is calling the logger, why is the explicit call required? What is the extension point to 'bake-in' the call to the logger and pass a log message to be established by convention.
So consider this code block:
protected override async Task OnParametersSetAsync()
{
    var _logMessage = "OPSA calls GetProductByIdAsync with: " + ProductId;
    try
    {
        _loadFailed = false;
        _details = await GetProductByIdAsync(ProductId);
    }
    catch (Exception ex)
    {
        _loadFailed = true;
        //app should implicitly call:
        // Logger.LogWarning(ex, _logMessage);
        //
       // Shouldn't I expect to find a special something somewhere
       // to override the default behavior and inject that logger call?
    }
}


text:
Q: Bulma table rows not spanning full width I have a is-fullwidth Bulma table in my angular7 app which works fine. But now I need to add a angular component inside each row, and td tags lies inside that component. But when I do that, table rows not spans to its full width.

      Column 1
      Column 2

      <app-table-row [details]="row">
      </app-table-row>

table-row.component.html

 {{ details.name }}

      <input [value]="details.name" class="input" type="text">

{{ details.address }}

This outputs the following

if I remove the angular component and add tds normally, it spans correctly. Like this.

Why is it not work when angular component added? And how should I fix it?

A: The reason this is happening is probably because the td elements are not direct children of the tr, but children of the app-table-row component.
Not sure that it would make sense in your case, but you can change the selector property in the app-table-row component to select the tr itself, like so:
@Component({
    selector: 'tr[app-table-row]',
    ...
})
export class AppTableRowComponent  {}

And use it like this:

      Column 1
      Column 2

This way the app-table-row is not a separate node in the DOM.


text:
Q: How to authenticate in ruby via REST api I am trying to authenticate with ruby to firebase as Service Account.
So what I did so far, is using Google auth lib as I always did (in other google services):
require 'googleauth'
scopes =  ["https://www.googleapis.com/auth/firebase.database"]
tt = Google::Auth.get_application_default(scopes).fetch_access_token

I get the tt["access_token"] and then I do something like
curl -X POST -d '{"user_id" : "jack", "text" : "Ahoy!"}' 'https://project-xxxxxxxxxxxxxxxxxxx.firebaseio.com/message_list.json?access_token=ya29.CjHzAsjcGEQsSppI9AKCV9g4Uen7qlREI3N_nCGDsWkLh6ZSCg5JmNYzIU8NuV6PAq7h'
Like they say in https://firebase.google.com/docs/reference/rest/database/user-auth#section-get
and I get:
Permission denied (that is because in our DB Rules we said auth != null.
So I went ahead and called ?auth=ya29.CjHzAsjcGEQsSppI9AKCV9g4Uen7qlREI3N_nCGDsWkLh6ZSCg5JmNYzIU8NuV6PAq7h
And I got:
"{\n  \"error\" : \"Could not parse auth token.\"\n}\n"

How am I supposed to authenticate to Firebase WITHOUT nodejs... just a simple REST???
Please assist!
Thanks!

A: Here's a fully baked example, assuming you have an access token as described above:
require 'cgi'
require 'json'
require 'net/https'
require 'uri'

ACCESS_TOKEN = 'XXX'
DATABASE_NAME = 'YYY'

path = '/example'
auth_variable = {uid: 'ruby-admin'}
payload = {my: 'data'}

uri = URI("https://#{DATABASE_NAME}.firebaseio.com#{path}.json?auth_variable_override=#{CGI::escape auth_variable.to_json}")
req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')

req.body = payload.to_json
req['Authorization'] = "Bearer #{ACCESS_TOKEN}"

http = Net::HTTP.new(uri.hostname, uri.port)
http.use_ssl = true

res = http.request(req)

puts res.body

You can edit auth_variable to change the auth variable available in security rules, and payload is obviously your data you want to post.


text:
Q: ModelMetaData: How to get "Parent"-Metadata? In my view I call Html.EditFor() which triggers a custom editor-template for this datatype. Additionally I pass some Metadata with it (and that's the part I don't like):
<% ModelMetadata metaTitle = ModelMetadataProviders.Current.GetMetadataForProperty(null, Model.GetType(), "Title"); %>
<%: Html.EditorFor(x => Model.Title, new { metaData = metaTitle })%>

The passed type (property Title) is of type 'Translation'. Within the custom editor-template I have to read the passed metadata from the viewData in order to use it:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Translation>" %>
// {...}
if (ViewData["metaData"] != null)
    metaData = (ModelMetadata)ViewData["metaData"];

Is there some way I could access the metadata directly within the custom editor-template? Unfortunately, if I call the following within the editor-template, I won't get the same metadata-object (where for example the information if the Title-Property is required or not is missing):
ModelMetadata metaData = ModelMetadataProviders.Current.GetMetadataForType(null, Model.GetType());

I would like to avoid to pass the metadata-object on each call...
Thx for any tipps!
sl3dg3

A: I think you're trying to get the metadata for the actual property for the EditorTemplate.
You can do this like this (inside the EditorTemplate):
var metadata = ModelMetadata.FromStringExpression("", ViewData);

"" means for MVC the current property.

A: You could try the following to access the parent metadata:
<%
    var parentType = this.ViewData.ModelMetadata.ContainerType;
    var metadata = ModelMetadataProviders.Current.GetMetadataForType(null, parentType);
%>

A: Admittedly a little late to the party, however there is a simpler way to get the model metadata for the current model - it exists as a property of ViewData:
var metadata = ViewData.ModelMetadata;


text:
Q: pug file compiled to html does not livereload In my project folder, I have pug files that are located in src/pug/*.pug, one of those files is index.pug. When compiled to html, the compiled files are located in build/templates/*.html. In the serve task, in browsersync.init(), I changed the baseDir from ./ to build/templates/ because the compiled index.html is located there. The problem is, browsersync livereload does not work; I have to refresh the browser just to see the changes I make in index.pug.
Gulpfile.js
const gulp = require('gulp'),
        sass = require('gulp-sass'),
        pug = require('gulp-pug'),
        uglify = require('gulp-uglify'),
        plumber = require('gulp-plumber'),
        imagemin = require('gulp-imagemin'),
        concat = require('gulp-concat'),
        autoprefixer = require('gulp-autoprefixer'),
        browserSync = require('browser-sync');

gulp.task('templates', () => {
    return gulp.src('src/pug/*.pug')
        .pipe(plumber())
        .pipe(pug({pretty: true}))
        .pipe(gulp.dest('build/templates/'))
        .pipe(browserSync.stream({stream: true}));
});

gulp.task('styles', () => {
  return gulp.src('src/sass/**/*.sass')
    .pipe(plumber())
    .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
    .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
    .pipe(gulp.dest('build/css/all/'))
    .pipe(concat('style.css'))
    .pipe(gulp.dest('build/css/'))
    .pipe(browserSync.stream({stream: true}));
});

gulp.task('scripts', () => {
    return gulp.src('src/js/*.js')
        .pipe(plumber())
        .pipe(concat('script.js'))
        .pipe(gulp.dest('build/js/'))
        .pipe(browserSync.stream({stream: true}));
});

gulp.task('imagemin', () => {
    gulp.src('assets/img/src/**/*')
        .pipe(imagemin())
        .pipe(gulp.dest('assets/img/dist/'));
});

gulp.task('serve', ['templates', 'styles', 'scripts'], () => {
    browserSync.init({
        server: {
            baseDir: 'build/templates/'
        },
        notify: false
    });

    gulp.watch('src/pug/*.pug', ['templates']);
    gulp.watch('src/sass/**/*.sass', ['styles']);
    gulp.watch('src/js/*.js', ['scripts']);
    gulp.watch('build/templates/index.html').on('change', browserSync.reload);
});

gulp.task('default', ['imagemin', 'serve']);

Can someone help me fix this?

A: Not sure why that doesn't work, but I have compared your build file to the official docs, and I came across this approach from the docs: Instead of watching the HTML files, it watches the source (pug files in your case) and calls browserSync.reload after that source compilation task has completed. In your case, the pug line would be replaced by something like this:
gulp.watch('src/pug/*.pug', ['templates-watch']);

And you would create a new task, called templates-watch, that would be defined as follows:
gulp.task('templates-watch', ['templates'], function (done) {
    browserSync.reload();
    done();
});


text:
Q: Initializing a multi-dimensional array in C++ 20 using an expression list Is it correct such an initialization of a multi-dimensional array in C++ 20 using an expression list?
int a[][3]( 1, 2, 3, { 4, 5, 6 } );

At least the C++ compiler of MS VS 2019 does not compile such a declaration
This declaration
int a[][3]( 1, 2, 3, 4, 5, 6 );

is not also compiled while this declaration
int a[][3]( { 1, 2, 3 }, { 4, 5, 6 } );

is compiled successfuly.
In the corresponding quote from the C++ 20 Standard (9.4 Initializers) relative to array initialization there is nothing said about whether brace elision is allowed or not when an expression list is used.

(17.5) — Otherwise, if the destination type is an array, the object is
initialized as follows. Let x1, . . . , xk be the elements of the
expression-list. If the destination type is an array of unknown bound,
it is defined as having k elements. Let n denote the array size after
this potential adjustment. If k is greater than n, the program is
ill-formed. Otherwise, the ith array element is copy-initialized with
xi for each 1 ≤ i ≤ k, and value-initialized for each k < i ≤ n. For
each 1 ≤ i < j ≤ n, every value computation and side effect associated
with the initialization of the ith element of the array is sequenced
before those associated with the initialization of the jth element.

A: Rereading the provided quote especially its this part

the ith array element is copy-initialized with xi for each 1 ≤ i ≤ k

It seems that such an initialization like this
int a[][3]( 1, 2, 3, { 4, 5, 6 } );

is indeed incorrect because the element of the array a is in turn an array of the type int[3] and to initialize it in this case you need to use a braced-init-list. After that within the braced-init-list the brace elision will be accepted. That is you may not initialize an array with an expression.
Here is an example that confirms that and is compiled by the C++ compiler of MS VS 2019
int e[][2][3]( { 1, 2, 3,  { 4, 5, 6 } }, { 6, 5, 4, 3, 2, 1 } );

Within the braced-init-lists the brace elision may be used.

A: Taken from c++ 20 draft
7.6.1
expression-list:
  initializer-list

9.4
initializer-clause :
   assignment-expression
   braced-init-list

initializer-list:
   initializer-clause ...opt
   initializer-list , initializer-clause ...opt

a[][2]({1, 2, 3}, {4, 5, 6}) is ok
a[][2](1, 2, 3, {4, 5, 6}) is not ok because 1, 2, 3, {4, 5, 6} is not an expression-list
That mean the () syntax for array is pointless, anyway the inner part need to be a {} except for:
int e[](1);
because 1 is an assignment-expression


text:
Q: Stats- Finding percentages between two scores I dont know how to start the problem. can someone help me start it? step by step?

*

*A teacher wants to know what percentage of her 5th grade students is reading one grade level above, and one grade level below the norm. The mean grade level equivalent on a reading test for a 5th grade class is 5.5 and the standard deviation is 1.5. What percentage of students are reading at a grade level between 4.5 (one level below) and 6.5 (one level above)?

*In a further study, the same teacher wants to know what percentage of her students are reading between 8 and 10 books per month because the administration feels that amount is above average at this age. The mean number of books read in her class is 7 per month with a standard deviation of 2.

A: Hint: Assuming normal distribution for both exercises.
Here is an explanation for the first exercise:
$\mu =5.5$ and $\sigma=1.5$, hence
$z(4.5)=(4.5-5.5)/1.5=-2/3$ and $z(6.5)=(6.5-5.5)/1.5=2/3$.
$P[z(4.5) \leq z \leq z(6.5)]=\Phi(2/3)-\Phi(-2/3),$
in which $\Phi(z)$ is the cumulative normal distribution.
Can you complete the second task?


text:
Q: PHP Email Sanitization Filter I'm trying to figure out why my sanitize filter don't work. When entering an email with incorrect characters, it displays the email with incorrect characters. I would have thought it will strip out incorrect characters and only display the correct email address. Below is my code. What am I doing wrong?
<?php

if(filter_has_var(INPUT_POST, 'data')){

$email = $_POST['data'];

//Now remove illegal characters
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
echo $email;

}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="data">
<button type="submit">Submit</button>
</form>

A: To me it seems to be working. I would however not want to store a different email than the exact input. If the incoming email adress is incorrect I would return an error message asking the user for a real email adress:
if(filter_has_var(INPUT_POST, 'data')){
  $email = trim($_POST['data']);
  $sanitized = filter_var($email, FILTER_SANITIZE_EMAIL);
  if($email === $sanitized && filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "This is a valid email: " . $email;
  } else {
    echo "This is an invalid email: " . $email;
  }
}

A: I don't know if this is exactly what's you're looking for but just give it a try.
<?php
function filter_mail($string) {
   return preg_replace('/[^A-Za-z0-9.@\-]/', '', $string); // We remove special chars and accept only Alphs&Nums&.&@
}
$mail="jp)(*&@gmail)**&.com";
echo filter_mail($mail); //This will output the desired email
echo "<br>";
echo $mail; //This is how it was !
?>

A: this may help, after sanitizing we need to check if it is a valid mail
<?php
  if(filter_has_var(INPUT_POST, 'data')){
    $regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';

    $email = $_POST['data'];
    $email = filter_var($email, FILTER_SANITIZE_EMAIL);

    if (preg_match($regex, $email)) {
      echo $email;
    } else {
      echo "invalid email";
    }
  }
?>

A: It seems like only certain types of characters can get sanitized. For instance here are examples of wrong emails that will get sanitized:
(comment)localpart@example.com - After sanitization: commentlocalpart@example.com
"much.more unusual"@example.com - After sanitization: much.moreunusual@example.com
But these for instance will not get sanitized:
sarah{[@gmail}{[.com - After sanitization: sarah{[@gmail}{[.com
jp*&@gmail**&.com - After sanitization: jp*&@gmail**&.com


text:
Q: How to add other users to a calendar I'm trying to add a user programatically to some Google calendars via Google Apps Script. Basically, it's for when a new teacher starts, I want to add them to the 5 calendars we have, without having to do it manually (note, these are personal accounts).
I want something like the subscribeToCalendar method but to add a user that isn't the active one, i.e. me. The script already collects their email address and I have the calendar IDs. I've looked in the Google Calendar documentation and can't find any way to do this.
I have also found this in the Google Calendar API documentation which talks about updating the role to for example, "reader", which is want I want, but I have no idea how this is implemented with Google Apps Script, as the examples on the page are Java, etc.
https://developers.google.com/google-apps/calendar/v3/reference/acl/update#examples
I found this question which I think is in the right direction but seems awfully complex for just adding a user to the calendar:
Create a POST body using Google Apps Script
Can anyone help?
Thanks in advance.
Baz

A: You're heading in the right direction, you need to use the Advanced Calendar Service (That must be enabled before use. In the Script Editor select Resources > Advanced Google services... and then enable it in the Google Developers Console.)
Once enabled you can share the calendar using the ACL: insert, here's an example:
function myFunction() {

  var calendarIds = ['CAL_ID_1','CAL_ID_2','CAL_ID_3','CAL_ID_4','CAL_ID_5'];
  var userEmail = 'USER_EMAIL';
  var resource = {
      'scope': {
        'type': 'user',
        'value': userEmail
      },
      'role': 'reader'
    };

  for (var i = 0; i < calendarIds.length; i++) {
    Calendar.Acl.insert(resource, calendarIds[i]);
  }
}


text:
Q: Jpa project where is annotation @NamedQueries I have a maven project and I want to work with JPA.
My pom.xml is
<dependencies>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.197</version>
        </dependency>
    </dependencies>

I have the following class
package edu.javacd.reviewservice;

import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

    @Entity
    @Table(name = "REVIEW")
    @NamedQueries({ @NamedQuery(name = "Review.findAll", query = "SELECT r FROM Review r"),
    @NamedQuery(name = "Review.findById", query = "SELECT r FROM Review r WHERE r.id = :id"),
    @NamedQuery(name = "Review.findByMovieId", query = "SELECT r FROM Review r WHERE r.movieId = :id") })
    public class Review implements Serializable {
    }

How  do I have to configure the pom.xml for using the annotation @NamedQueries

A: Edit : The annotation is in this package : javax.persistence.NamedQueries
Normally your pom.xml is already configure to you use the @NamesQueries annotation.
Edit : And you are missing the EclipseLink implementation dependency :
Check this old post : How to setup Eclipselink with JPA?
Your 3 dependencies (which are external libraries) stand respectively for :

*

*Edit : JPA annotations

*Transaction Management for JPA

*JDBC Driver for H2 database

This annotation allows you list all the queries you will use in your program and their sql statements. Instead of typing directly sql statements in your code, you will have something like this:
Query query = em.createNamedQuery("Review.findAll");
List results = query.getResultList();

A: You will find the @NamedQueries annotation and the others you mention(@Entity, @Table, @NamedQuery) in the java persistence api. Add its coordinates (or those of a different library that uses it, such as Hibernate, WildFly, etc.) as a dependency in your pom.xml to use them:
<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>javax.persistence-api</artifactId>
    <version>2.2</version>
</dependency>


text:
Q: Arduino near Identical Functions with very different outputs I have 3 different functions that send text messages using my Arduino and SIM900.
The first function has two arguments and sends the character array given to it to the target phone number
void sendText(char msg[], char num[]) {
  Serial.print("[Text] Sending text to ");
  Serial.println(num);
  simController.print("AT+CMGF=1\r");
  delay(100);
  simController.print("AT + CMGS = \"");
  simController.print(num);
  simController.println("\"");
  delay(100);
  Serial.print("[Text] ");
  Serial.println(msg);
  simController.println(msg);
  delay(100);
  simController.println((char)26);
  delay(100);
  simController.println();
  delay(5000);
}

The last two functions are near identical except they have different number of arguments and have completely different outcomes
void sendText(char msg[], char num[], int startChar) {
  char *newMsg = (char *)malloc(strlen(msg)+1);
  memset(&newMsg[0], 0, sizeof(newMsg));
  Serial.print("[Text] Sending text to ");
  Serial.println(num);
  simController.print("AT+CMGF=1\r");
  delay(100);
  simController.print("AT + CMGS = \"");
  simController.print(num);
  simController.println("\"");
  delay(100);
  for (int x=0;x<strlen(msg);x++) newMsg[x] = msg[x+startChar];
  Serial.print("[Text] ");
  Serial.println(newMsg);
  simController.println(newMsg);
  delay(100);
  simController.println((char)26);
  delay(100);
  simController.println();
  delay(5000);
}

void sendText(char msg[], char num[], int startChar, int endChar) {
  char *newMsg = (char *)malloc(strlen(msg)+1);
  memset(&newMsg[0], 0, sizeof(newMsg));
  Serial.print("[Text] Sending text to ");
  Serial.println(num);
  simController.print("AT+CMGF=1\r");
  delay(100);
  simController.print("AT + CMGS = \"");
  simController.print(num);
  simController.println("\"");
  delay(100);
  for (int x=0;x<strlen(msg);x++) newMsg[x] = msg[x+startChar];
  Serial.print("[Text] ");
  Serial.println(newMsg);
  simController.println(newMsg);
  delay(100);
  simController.println((char)26);
  delay(100);
  simController.println();
  delay(5000);
}

The code I use when calling these function looks like this
sendText("Hello","+447597865XXX");
sendText("Hello","+447597865XXX", 1);
sendText("Hello","+447597865XXX", 1, 3);

The output looks like this
[Text] Sending text to +447597865XXX
[Text] Hello
[Text] Sending text to +447597865XXX
[Text] ello
[Text] Sending text to +447597865XXX
[Text] ell��U�����=ڨl��fr}Ѧ�o�e�6�������f��+��V���_{���

Why is this happening? Remember there is no difference between the body of void sendText(char msg[], char num[], int startChar, int endChar) and void sendText(char msg[], char num[], int startChar)

A: Your memset is wrong, specifically sizeof(newMsg) where newMsg is a pointer. So sizeof(newMsg) is most likely 2 or 4 depending on your platform. The first one might work by luck, having already 0 in uninitialized memory.
Use the size passed to malloc also for memset (or only write the string terminator '\0' after you copied your data with the for loop.
And also check if malloc succeeded, i.e. it's return value is not NULL.
Edit: To refactor your second function, you can remove the call to memset and change
for (int x=0;x<strlen(msg);x++) newMsg[x] = msg[x+startChar];

to
int x;
for (x=0;x<strlen(msg);x++) newMsg[x] = msg[x+startChar];
newMsg[x] = '\0'; // Or just 0, it is equivalent


text:
Q: Problems with defining font defaults in `XeLaTeX` I want to define a default font(Arial), a sans-serif font(also Arial), a monospace font(Roboto Mono), and a roman font(Times New Roman). Defining the latter three is okay, but introducing the main font seems to ruin the monospace font. Reordering also fails. Here are two MWEs(reordering the commands in between the two comment percent signs don't work either):
\documentclass[12pt]{article}
\usepackage{fontspec}
%
\setsansfont{Arial}
\setromanfont{Times New Roman}
\setmonofont{Roboto Mono}
\setmainfont{Arial}
%

\begin{document}
    \noindent
    c\\
    {\sffamily c}\\
    {\rmfamily c}\\
    {\ttfamily c}\\
\end{document}

I was looking at other sources, which seemed to imply that this should work(but it fails too):
\documentclass[12pt]{article}
\usepackage{fontspec}
%
\setsansfont{Arial}
\setromanfont{Times New Roman}
\setmonofont{Roboto Mono}
\renewcommand{\familydefault}{\sfdefault}
%

\begin{document}
    \noindent
    c\\
    {\sffamily c}\\
    {\rmfamily c}\\
    {\ttfamily c}\\
\end{document}

PS: I would like to also change the small caps font to Helvetica, as Arial doesn't have one. Any way to do that too?


text:
Q: Whats wrong with this phrase? Is the phrase
Tips on how tell the difference.
Grammatically correct?
Should it be
Tips on how to tell the difference.

A: The correct one is
"Tips on how to tell the difference."
"to" is a preposition and is needed to show the relationship between the subject "tips" and the object "tell the difference."


text:
Q: Design spinner programmatically (android) I need create spinner programmatically. I add spinner to linearLayout, its work but I don't know how chache designe it.
Example, I have this:

How remove it?(highlighted in red)
And how remove spinner text to center?

My xml
LinearLayout spinnerL add this my spinner
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/spinnerL"
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="20dp"
        />

</RelativeLayout>

and main class
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Array of choices
        View linearLayout =  findViewById(R.id.spinnerL);

        ArrayList<String> list = new ArrayList<String>();
        list.add("one");
        list.add("two");

        Spinner spinner = new Spinner(this);
        //Make sure you have valid layout parameters.

        spinner.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

        ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
                android.R.layout.simple_spinner_dropdown_item, list);
        spinner.setAdapter(spinnerArrayAdapter);

        ((LinearLayout) linearLayout).addView(spinner );
    }

A: *

*To remove small triangle, simplest method is to set background drawable, for example:
spinner.setBackgroundResource(android.R.drawable.btn_default);

*To align text center, you need to create layout for spinner, see examples


text:
Q: check bunches of data I have got a lot of different data which needs to be compared on a site. I explain it deeply

I have to go to a website paste a1 on box1 paste b1 on box2 and paste c1 on box3 of a site the site has recaptcha (I'm not asking if I'm able to bypass or not I know I will have to solve it myself so in that case my script, application or whatever would have to wait there for me to solve the captcha as shown here then this will lead to a new page with a  particular piece of text in which case the macro app or whatever should post in d1 something like INVALID then it needs to restart but this time take column 2 i.e. a2 b2 c2 d2 I have been reading that best way to achieve this would be  doing it in VBA and I have tried to follow tutorials and so on but I don't seem to quite understand it well.
what I have tried is:
Sub ListaNominal()

    Dim IE As Object
    Dim doc As HTMLDocument

    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    IE.navigate "xxxxxxxxxxxxxxx/"

    Do While IE.Busy Or IE.readyState <> 4
    Application.Wait DateAdd("s", 1, Now)
    Loop

    Set doc = IE.document
    IE.document.getElementById("claveElector").Value = GTLPAL73052511H600
    doc.getElementById("numeroEmision").Value = 2
    doc.getElementById("ocr").Value = 1121035022017#
    MsgBox "Click to go on", , "Example"

    Set element = doc.getElementsByClassName("col-xs-6 col-sm-8 table-responsive")("VALIDA")

    ThisWorkbook.Sheets("Hoja1").Range("d1").Value = element

End Sub

but doesn't seem to work even with a hardcoded value. A friend of mine told me that maybe VBA would be so difficult that I should try CSV file along with Autofill Chrome app, but I don't seem to understand how to do this any help would be appreciated


text:
Q: How do I display the deleted content from an existing form to a completely separate url, Where it displays the deleted items in django How do I display the deleted content from an existing form to a completely separate URL, Where it displays the deleted items in django. I've been trying to figure out how to create a separate table where it displays all the items that I've deleted
I can't figure out what I should put in my function key
from django.shortcuts import render, redirect
from employee.forms import EmployeeForm
from employee.models import Employee
# Create your views here.
def emp(request):
    if request.method == "POST":

        form = EmployeeForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                return redirect('/show')
            except:
                pass
    else:
        form = EmployeeForm()
    return render(request,'index.html',{'form':form})
def show(request):
    employees = Employee.objects.all()
    return render(request,"show.html",{'employees':employees})
def edit(request, id):
    employee = Employee.objects.get(id=id)
    return render(request,'edit.html', {'employee':employee})
def update(request, id):
    employee = Employee.objects.get(id=id)
    form = EmployeeForm(request.POST, instance = employee)
    if form.is_valid():
        form.save()
        return redirect("/show")  enter code here
    return render(request, 'edit.html', {'employee': employee})
def destroy(request, id):
    employee = Employee.objects.get(id=id)
    employee.delete()
    return redirect("/show")

A: So if you want to display all of your deleted employees, then you cannot do employee.delete(), since this removes the record from the underlying database.
Instead think of a flag (i.e. a boolean value) that you attach to your Employee model - for example "deleted" with a default value False. Once you go into your destroy function you just do
employee.deleted =True
employee.save()

and in your show function you do the following:
Employee.objects.filter(deleted=False)

On your separate URL where you want to display all the deleted employees you do
Employee.objects.filter(deleted=True)

You can also work with custom model managers there.


text:
Q: I get a NameError: uninitialized constant CoffeeScript::ExecJS on a Rails 4 app deployment I have a Rails 4 app deployed on my Digital Ocean LAM-Rails VPS. I have been developing it for quite a while and all has been going well but now when I want to run a migration or clean assets I get this error:
NameError: uninitialized constant CoffeeScript::ExecJS
/usr/local/rvm/gems/ruby-2.1.1/gems/coffee-script-2.3.0/lib/coffee_script.rb:5:in `<module:CoffeeScript>'
/usr/local/rvm/gems/ruby-2.1.1/gems/coffee-script-2.3.0/lib/coffee_script.rb:4:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.1.1/gems/coffee-script-2.3.0/lib/coffee-script.rb:1:in `require'
/usr/local/rvm/gems/ruby-2.1.1/gems/coffee-script-2.3.0/lib/coffee-script.rb:1:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.1.1/gems/coffee-rails-4.0.1/lib/coffee-rails.rb:1:in `require'
/usr/local/rvm/gems/ruby-2.1.1/gems/coffee-rails-4.0.1/lib/coffee-rails.rb:1:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.1.1@global/gems/bundler-1.6.2/lib/bundler/runtime.rb:76:in `require'
/usr/local/rvm/gems/ruby-2.1.1@global/gems/bundler-1.6.2/lib/bundler/runtime.rb:76:in `block (2 levels) in require'
/usr/local/rvm/gems/ruby-2.1.1@global/gems/bundler-1.6.2/lib/bundler/runtime.rb:72:in `each'
/usr/local/rvm/gems/ruby-2.1.1@global/gems/bundler-1.6.2/lib/bundler/runtime.rb:72:in `block in require'
/usr/local/rvm/gems/ruby-2.1.1@global/gems/bundler-1.6.2/lib/bundler/runtime.rb:61:in `each'
/usr/local/rvm/gems/ruby-2.1.1@global/gems/bundler-1.6.2/lib/bundler/runtime.rb:61:in `require'
/usr/local/rvm/gems/ruby-2.1.1@global/gems/bundler-1.6.2/lib/bundler.rb:132:in `require'
/var/www/html/kosarka/config/application.rb:7:in `<top (required)>'
/var/www/html/kosarka/Rakefile:4:in `require'
/var/www/html/kosarka/Rakefile:4:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.1.1/bin/ruby_executable_hooks:15:in `eval'
/usr/local/rvm/gems/ruby-2.1.1/bin/ruby_executable_hooks:15:in `<main>'
(See full trace by running task with --trace)

My Gem file looks the following:
source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.0'
# Use sqlite3 as the database for Active Record
group :development do
    gem 'sqlite3'
end
group :production do
    gem 'mysql2'
    gem 'therubyracer',  platforms: :ruby
    gem 'execjs'
end

#To validate delivery date is in the futurebund
gem 'date_validator'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer',  platforms: :ruby
# Use Paperclip for image upload
gem 'paperclip'
# Use jquery as the JavaScript library
gem 'jquery-rails'

gem 'jquery-turbolinks'

gem 'jquery-ui-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0',          group: :doc

# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring',        group: :development

# For development on Windows machines
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw]

# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'

# Use unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
gem 'capistrano-rails', group: :development

# Use debugger
# gem 'debugger', group: [:development, :test]

I develop this app both on a Win7 machine and a Mac and I have no problem running it in the dev environments.
I use Phusion Passenger on the server and usually just pulled the repo content with a .sh script and ran the rake migrate asset clean and precompile commands.
Any help would be much appreaciated.

A: Replace this section:
group :production do
    gem 'mysql2'
    gem 'therubyracer',  platforms: :ruby
    gem 'execjs'
end

to
gem 'mysql2'
gem 'therubyracer',  platforms: :ruby
gem 'execjs'

P.S. I think your application will be works fine without execjs gem too. Try to check it for any case.

A: It is going to be a rather clouded answer. I have seen this question coming up from many on stackOverflow but the tips (rm -rf .bundle and cache etc.) did not help me.
So I just reverted back to an old Gem file and Gem.lock and it happened to solve the problem.
Then I went to Bitbucket and had a look on the commit and figured out actually it was all the version changes in the Gem.lock (probably an accidental bundle update instead of bundle install) that might caused the problem.
Eventhough in my Gemfile there was only a date_validator change, my Gem.lock was full of new versions of the following:
bcrypt
capistrano
coffee-script-source
execjs
multi_json
jbuilder
spring

I still could not get to the depth of the problem but at least figured how to avoid it.


text:
Q: Почта приходит в СПАМ Вопрос почему почта приходит в СПАМ:

*

*
Это зависит от обработчика

*
От самого почтовика

*
Или еще от чего-то
Объясните почему так происходит!
A: Во первых убедитесь что ваша почта действительно не спам.
Во вторых поищите ваш ip и домен  в базах dnsbl.
В третьих, посмотрите заголовки которые вы посылаете, убедитесь, что обратная запись dns для ip с которого вы посылаете совпадает с доменом в поле from (желательно), что MX запись для вашего домена существует,  прочитайте про spf и dkim.


text:
Q: Making an Array call an object in and index I am getting error that myArray hides an instances variable. Please explain briefly what the error means and how to fix it. Thanks for you help. I am new at programming with objective-c
- (IBAction)buttonPushed:(id)sender
{
    NSArray *snarkyCommentArray = [[NSArray alloc] initWithObjects: @"Butter",@"Cheese",@"Gravy",@"Your fat",@"smells like roses",nil];

    self.snarkOffLabel.text = [snarkyCommentArray objectAtIndex:(1)];

}
@end

A: While the code doesn't align with your question, I can still explain the error message.
If your class defines an instance variable, and you then create a local variable with the same name, the compiler warns you that the local variable will be used and not the instance variable. The local variable is "hiding" the instance variable.
It's best to ensure that you never give local variables the same name as instance variables to avoid any confusion. A common practice is to give all of your instance variables an underscore prefix such as _myArray. This way, whenever you are reading code, it's very obvious which variables are instance variables and which are not.
Another way to avoid the issue is to reference instance variables through the self pointer.
Let's say my class has a instance variable named foo and I have a local variable named foo.
foo = 5; // local variable
self->foo = 10; // instance variable

A: I can say, your ivar and local variable have same name. So you need to change the name of either one. Or use arrow operator to access your ivar.

A: Consider the following:
@interface myClass : NSObject{
NSString *name;
}

- (void)print:(NSString*)name;
- (void)printName;
@end

@implementation myClass

- (void)print:(NSString*)name{
    // This line will print the local variable 'name', not the instance variable 'name'
    // This line will cause a warning to the effect "Local variable hides instance variable"

    NSLog(@"%@", name);
}

- (void)print{
    // This line will print the instance variable 'name'.
    NSLog(@"%@", name);

    NSString *name = @"Steve";

    // This line will print the local variable 'name'.
    // This line will cause a warning to the effect "Local variable hides instance variable"
    NSLog(@"%@", name);
}
@end

It's important to understand the difference between instance variables and local variables. An instance variable is a variable defined in your class's '@interface' section. Example:
@interface myClass : NSObject {
// Instance variables
NSString *name;
float progressAmount;
NSUInteger *age;
}
@end

An instance variable can be accessed by any method of the class.  A local variable is a variable that has local scope and can only be accessed in the method or block in which it is declared. Example:
- (int)square:(int)num{
    int result = num * num;
    return result;
}

In the preceding example both num and result are local variables. The square: method is their entire universe. They can't be accessed from outside of square: nor do they exist once square: returns. They are said to have local scope.
So what happens when an instance variable and a local variable are given the same name? It all comes down to scope. Local variables trump instance variables when it comes to scope, so when faced with the decision of which variable to use, the compiler will use the local variable. This is why the compiler produces a warning and not an error. What is happening is perfectly acceptable, but it's still a good idea to warn the programmer.

A: Did u try check where is mistake with NSLog?  Do u know about if snarkyCommentArray keeps your strings?  Check it like
Nslog(@"snarkyCommentArray %@",snarkyCommentArray);

if it keeps all, then care about your label,  you can use it without self like
snarkOffLabel.text = [snarkyCommentArray objectAtIndex:(1)];

if it still doesn't work, then allocate your array like NSMutableArray,
NSMutableArray *snarkyCommentArray = [[NSMutableArray alloc] initWithObjects: @"Butter",@"Cheese",@"Gravy",@"Your fat",@"smells like roses",nil];

Hope it helps.


text:
Q: Set breadcrumb path for woocommerce product, with multiple category I have a product in multiple categories. The latest woocommerce shows the shortest way as breadcrumb on the product page, but that doesnt make sense for me. I would like to use the primary category of the product as breadrumb trail.
I know that yoast has a function to do that, but it would be better to do it with some custom functions.php code.

A: Ok, this will work as a solution, so here it is:
As i found out, woocommerce doesnt show the shortest way as breadcrumb. It shows the newest category which the product is in. As newest I mean that the product category that was created latest.
So I created a "new primary category", assigned the products to that with importing, and deleted the "original primary category". Then I renamed the "new primary category" to "original primary category".
Now the newest path is displaying as breadcurmb on product page.
Before tweaking with category names, make sure you have a backup in case. And you have to refresh your menu links too, because in some case it will point to the deleted category.


text:
Q: Is using mysql_num_rows a lot slows page loading? I built a classified. In the main/index.php page, I have many categories like cars, electronics, furniture..etc which you click on and give you the list of available cars or cell phones you can buy in your town.
I am thinking to add/show the number of ads each category contains like:
cars(74) electronics(32) and so on..
using of course mysql_num_rows
My question is> is this going to make loading the index.php page slower? if yes how slow? milliseconds, seconds, a lot?
Thanks :)
UPDATE >> CODE:
$query="select * FROM db_post WHERE cat='cars'";
$result= mysql_query($query);
$carnum=mysql_num_rows($result));

 CARS <?php echo "("."$carnum".")"; ?>
 	 <?php echo  ?>

All I want is the number. Is there a difference between mysql_num_rows and SELECT COUNT(*) in terms of speed?

A: Would be best to cache the values if possible.  On a low usage website you won't see much of a difference, but add a lot of users, you would want to cache the values until they are changed.

A: Using mysql_num_rows() alone isn't inherently slow. If you're using it because (say) you're selecting every product and displaying the number of matched rows, though, that will be slow! If all you need is a count, make the database do the counting with a query like:
SELECT COUNT(*) FROM ... WHERE ...

If you need a bunch of counts, use something like:
SELECT ..., COUNT(*) FROM ... WHERE ... GROUP BY ...

In general, try to decrease the total number of rows returned by the SQL server for the whole page by avoiding unnecessary queries, returning unused rows, or loading data when a summary is sufficient. As a general rule, fewer returned rows is better!

A: I would do something like
 select category_name, count( category_id ) from table group by category_id
Ideally you would want to cache these results and run query the every minute or so if you have alot of data (many thousands of rows on a basic server) and alot of traffic (many thousands of hits a day). If you are only having hundreds of hits a day, I wouldnt worry as your solution would probably be fine.

A: It is not matter of speed of "poage load".
It is matter of the very basics of database usage.
The main rule is:
Always select only data you need.
If you need only count of rows - select count of rows, not rows to count them after.
Got the idea?
Make database to do as much calculations as possible.


text:
Q: lxde quits unexpectedly I use lxde on Gentoo.
Versions of software:
lxappearance 0.5.2
lxde-common 0.5.5
lxde-icon-theme 0.5.0
lxinput 0.3.2
lxmenu-data 0.1.2
lxpanel 0.5.12
lxrandr 0.1.2
lxsession 0.4.6.1
lxsession-edit 0.2.0
lxshortcut 0.1.2
menu-cache 0.4.1

Time to time lxde exits from session to the session manager (I use slim-1.3.5). After it items reboot and halt disappear from the Logout menu and ck-list-sessions shows two sessions: one active and one not active.
System log near the problem: http://vpaste.net/zOZFl
The question is where can I try to look for the reason of this problem? Where does lxde store logs?

A: Check /var/log/Xorg.0.log.old for errors. It may be the X server that is restarting. Failing that, try starting X from the console using startx. You'll need to stop /etc/init.d/xdm first. If it still boots you out, you'll probably see some useful output. As a side note, I found slim to be a little unreliable but it's been a while since I tried it. I use lightdm now instead.


text:
Q: Issue in executing mongo commands through shell script Based on the answer by Matt for the question asked here:
I tried the below script
use sample

db.testCollection.insert({"result":1})

However when I run as suggested, get an error as below and the record gets inserted in a collection of the default db and not in the 'sample' db as expected.
[tmp]# mongo < output.js
connecting to: mongodb://127.0.0.1:27017
2018-03-21T14:54:52.713+0530 E QUERY    [thread1] SyntaxError: unterminated string literal @(shellhelp2):1:21
WriteResult({ "nInserted" : 1 })
bye

Kindly request for help.

A: Your script and command are correct.
On Unix, you will get this error if your script has Dos/Windows end of lines (CRLF) instead of Unix end of lines (LF).
To convert your end of lines :
dos2unix output.js

or: How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

A: You need to specify the db name as shown below.
mongo your-db-name < output.js


text:
Q: Property with name "id" not deserialized in mongodb C# I am trying to fetch a record from the mongo db in c#
Data in the mongodb collection:
{
  id:0
  parameter:"Unscheduled Demand"
  remarks:"Formula Based"
  value:89
}

Issue: id property is not getting deserialized from the data in C#.
C# class structure:
public class children
{
    [BsonId]
    [BsonRepresentation(BsonType.Int32)]
    public int id { get; set; }

    public string parameter { get; set; }

    public string remarks { get; set; }

    public double value { get; set; }
}

This is the error that occurs:

Element 'id' does not match any field or property of class children

A: According to the documentation here https://mongodb.github.io/mongo-csharp-driver/1.11/serialization/ the [BsonId] attribute defines which field should be mapped for Mongo's _id element. If you want to use a field called "id" you should remove this tag
public class children
{
    [BsonRepresentation(BsonType.Int32)]
    public int id { get; set; }

    public string parameter { get; set; }

    public string remarks { get; set; }

    public double value { get; set; }
}

My guess is that without removing the attribute you will still be able to insert into Mongo, and see there is an _id set

A: We need to make manually identify the identity property as per the official mongodb documentation for C#
https://mongodb.github.io/mongo-csharp-driver/1.11/serialization/
Changes Made
Previous Class Structure
public class children
{
    [BsonId]
    [BsonRepresentation(BsonType.Int32)]
    public int id { get; set; }

    public string parameter { get; set; }

    public string remarks { get; set; }

    public double value { get; set; }
}

Current Class Structure
public class children
{
    [BsonRepresentation(BsonType.Int32)]
    public int id { get; set; }

    public string parameter { get; set; }

    public string remarks { get; set; }

    public double value { get; set; }
}

Additional Changes in
Startup.cs
BsonClassMap.RegisterClassMap<children>(cm =>
            {
                cm.MapProperty(c => c.id);
                cm.MapProperty(c => c.parameter);
                cm.MapProperty(c => c.remarks);
                cm.MapProperty(c => c.value);
            });

MAKING THE ABOVE CHANGES RESOLVED MY ISSUE


text:
Q: Blank screen in vue.js if not using created() life cycle hook or spread operator (...) The following example gives me a blank screen (jsfiddle here). Even the parts which have nothing to do with the loop are not being rendered.
HTML:

  <button @click="objectFromApi">
    run objectFromApi function
  </button>

      {{ obj.message }}

JavaScript:
new Vue({
  el: "#app",
  data: {
    myObject: []
  },
  methods: {
    objectFromApi: function(){
        this.myObject.push(
        {
          "count": 5,
          "results": [
            {
              "id": 1,
              "message": "object 1"
            },
            {
              "id": 2,
              "message": "object 2"
            }
          ]
        }
      )
    }
  },
  //created() {
  //  this.objectFromApi()
  //}
})

Nevertheless it does work if:
1.) Either using objectFromApi function directly in the created life cycle hook (what I don't want!)
created() {
  this.objectFromApi()
}

2.) Or (without the use of created life cycle hook) if I go directly into the nested results array and spread the objects out like this (what I also don't want!)
this.myObject.push(
  ...{
    "count": 5,
    "next": "http://127.0.0.1:8000/api/someurl/?page=2",
    "previous": null,
    "results": [
      {
        "id": 1,
        "message": "object 1"
      },
      {
        "id": 2,
        "message": "object 2"
      }
    ]
  }.results
)

When using option 2.) of course the v-for loop has to look different:
v-for="obj in myObject" instead of v-for="obj in myObject[0].results"
What is wrong with my initial example?

A: When the component is first rendering the array myObject will be empty.
During rendering it attempts this:

The value of myObject[0] will be undefined. Attempting to access the results property of undefined will result in an error. This error will cause rendering to fail. Nothing will be shown, even the parts that didn't fail.
There are various ways to fix this problem. You could prepopulate the data with suitable empty properties:
data: {
  myObject: [
    {
      results: []
    }
  ]
}

Alternatively, as you've noted, you could change the loop to use v-for="obj in myObject", changing objectFromApi accordingly to only store the results array in myObject. Even if you don't want that exact change some similar change is probably a good idea because the [0] part strongly suggests you've got a problem with your data model. The key thing here is that it avoids trying to access nested objects that don't exist. The use of the spread operator in your second example is largely irrelevant.
Or you could skip the loop in the template:
<template v-if="myObject[0]">

    ...

</template>


text:
Q: How to prevent the peek method from moving the read cursor ahead? I'm writing a method to split a text file. It has two options,

*

*Split a file blindly (split the file according to the bytes given)

*Split a file by preserving lines (if the last line in the splitted file is not whole, then it's moved to the next split)

The code for preserving lines is as follows:
file.rewind # `file` is a File object with proper modes passed
lines = file.each_line

until file.eof?
  tfile.truncate(0) # `tfile` is a temporary File object which will be given to the block passed

  while tfile.size + lines.peek.size <= size
    tfile << lines.next
    tfile.flush
  end

  file_count += 1
  yield(tfile, file_count)
end

Now the problem is that if there only remains one line in the last split, then the iteration won't run, because peek moves the cursor to the end of file in the second last iteration and therefore condition for the last iteration of the unless produces a true value and the loop exits.
How to solve this issue of the cursor moving to eof?
I'm thinking of moving the cursor back one line before every next. If there is a better option, then suggest it.

A: Enumerator#peek does not move the internal position of the Enumerator forward. But if the position is already at the end, StopIteration is raised. The thing is you don't need to peek at all.
That would be the proper way to solve the issue (the code is untested, but it should work):
file.rewind
tfile.truncate(0)

total_files =
  file.each_line.with_object(file_count: 0) do |line, acc|
    if tfile.size + line.size <= size
      tfile << line
      tfile.flush
    else
      acc[:file_count] += 1
      yield(tfile, acc[:file_count])

      tfile.truncate(0)
      tfile << line
      tfile.flush
    end
  end[:file_count]
yield(tfile, total_count)


text:
Q: Eclipse crashing frequently Eclipse is crashing within 5 minutes of opening it. Eclipse version I am using is 4.4-luna.
Below is the error log:
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00002b1568210c24, pid=6792, tid=0x00002b15822de940
#
# JRE version: Java(TM) SE Runtime Environment (8.0_92-b14) (build 1.8.0_92-b14)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.92-b14 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# V  [libjvm.so+0x815c24]  PhaseIdealLoop::build_loop_late_post(Node*)+0x144
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#

A: This looks like it might be the JVM bug discussed in Eclipse bugzilla report 465693.
A workaround was added in Eclipse 4.5.1
The bug also suggests trying adding one of the following to the -vmargs in your eclipse.ini:
-XX:-UseLoopPredicate

or
-XX:CompileCommand=exclude,org/eclipse/jdt/internal/compiler/parser/TypeConverter.decodeType

A: Add below line in your eclipse.ini file and relaunch.
-Dorg.eclipse.swt.browser.DefaultType=mozilla


text:
Q: Could Flutter's ReorderableListView drag item out of line? I'm using Flutter's ReorderableListView to display some images picked from photo library.
After I picked some images, I want drag one image onto a trash bin icon to delete it from selection. Assume the trash bin icon is at the bottom of screen. Since we can't drag item out of Listview's area,
How could I do it? Or if there is any other plugin could do this job?


text:
Q: How does the angularjs.forEach() work? I have the object :
var obj = {
     a : 5,
     b : 6,
     c : 7
}

I want to set zero to every object properties using angular.forEach():
angular.forEach(obj, function(value, key) {
    value = 0;
});

I displayed their values using console.log() and I found out that none of them are zero.
but when I do
obj.a = 0;
obj.b = 0;
obj.c = 0;

Their values are zero.
Can anyone explain about this?

A: You are just assigning the value parameter a value of 0.
Access each property on the object with the key parameter:
angular.forEach(obj, function(value, key) {
    obj[key] = 0;
});


text:
Q: Can't resolve Google pagespeed "Enable compression" point using Yii2 Site in question is http://burghleys.com/
Having trouble trying to improve the Google pagespeed score and says I need to enable compression with a 70% improvement on the JS file for example but I can't make the same improvement at all!
https://developers.google.com/speed/pagespeed/insights/?url=http%3A%2F%2Fburghleys.com%2F
I have GZIP enabled and use the apache mod_deflate to do so, tested as per http://checkgzipcompression.com/?url=http%3A%2F%2Fburghleys.com%2F
I use yii2 https://github.com/rmrevin/yii2-minify-view plugin to compress my files which generally works really well.
I use the HTML5 boiler plate htaccess file.
I tried manually compressing the JS file but can only reach 25%. CSS is even less yet states i can save 80%.
Any thoughts?
ps. I'm working on the other issues too, wanna get that 99 score.

A: You do have GZIP enabled for some items but if you follow the link to your js you will see that this resource is not being zipped up.
http://checkgzipcompression.com/?url=http%3A%2F%2Fburghleys.com%2Fminify%2Fb329b2d2ce53b5c6be05decfe5e5d723527a666e.js
Add the following line to your .htaccess
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/xml application/xhtml+xml application/rss+xml application/javascript appliction/x-javascript