Q: Nokia Asha SDK: Glitch in List component when used with TextField on the same Form I'm a bit stuck with strange behaviour of List component in Asha SDK. What I'm doing is using TextField and List on the same form. Just a TextField and a List on BoxLayout, with no relationship. The problem is - focusing on TextField seems to trigger creation of another List component which is exact copy of original one, but displays just one item. You can see it in

*

*large green border marks 2 horizontal row delimiters - first one belongs to original List, second one seems to belong to that new fake List

*small green border marks little vertical scroll bar which works for new fake List. Original List uses big scroll bar, you can see it on the right.

*'Item 9' on provided image belongs to fake List, 'Item 8' - to original one.

And this image shows how List is rendered when TextField is non-focused. Everything there seems to be correct:

Could you please advise is there any way to solve this glitch? Is it possible to tweak it somehow with LookAndFeel? I really don't need that fake List.
By the way, on Nokia SDK 2 (S40) there is no such glitch, everything works as expected.
P.S. What I'm trying to implement is Autocomplete TextField. I'm using this article for that. If there is any other way to do so for Asha SDK, please share.


Q: StringByAppendingPathComponent() and WriteToFile() I'm trying to learn Swift 3 with translating a code from Swift 2. In swift 2, I see the code like this:
return fullPath.stringByAppendingPathComponent(name)

But, when I try in Swift 3, I've got similiar code, but like this:
return fullPath.strings(byAppendingPaths: [name])

The issue is, return type in the 1st code is String (and that's the output I need from the lesson I learn), but return type in 2nd code should be [String].
The other issue is, in Swift 2 the code should be:
imgData?.WriteToFile(fullPath, atomicaly:Bool)

But in Swift 3, I only can input code like this:
imgData.Write(to: URL , option: WritingOption) throws

But in some examples, there's .Write(toFile: , atomically:) but I can't find it in Xcode.
Am I translating incorrectly or using both Swift 2 and Swift 3 incorrectly?

A: Regarding the first part of your question, as dan stated in the comments you should be using fullPath.appendingPathComponent(name) instead.
Regarding your second question:
The main difference between writeToFile and write(to: is the fact that the first is for Strings and the seconds is for NSData.
Somewhat related:
According to the NSData Class Reference
In iOS 2.0+ you have:
write(to:atomically:)

and
write(toFile:atomically:)

Given:

Since at present only file:// URLs are supported, there is no
  difference between this method and writeToFile:atomically:, except for
  the type of the first argument.

None of this has changed in Swift 3 according to the Swift Changelog.


Q: Bluetooth LE active scanning causes connection problems on other machine I am having a problem where BLE active scanning on one machine causes connection problems on another machine.  I was wounder if anyone could explain why, and offer any suggestions on how to fix.
I have broken down a rough version of my what my code does into simple scripts.
on machine 1:
sudo stdbuf -oL hcidump -X |tee hci.log &
sudo hcitool lewlclr
sudo hcitool lewladd 68:C9:0B:xx:xx:01
sudo hcitool lewladd 68:C9:0B:xx:xx:02
sudo hcitool lewladd 68:C9:0B:xx:xx:03
sudo hcitool lewladd 68:C9:0B:xx:xx:04
sudo hcitool lewladd 68:C9:0B:xx:xx:05
sudo hcitool lewladd 68:C9:0B:xx:xx:06
while true; do sudo hcitool lecc --whitelist; if [ $? == 1 ] ; then sleep 20;  else sleep 1; sudo hcitool ledc 64 ; fi; done

The above will run with no problems
However after running the following on a different machine I get connection issues.
sudo hcitool lescan --duplicates

from the hci logs a normal connecition looks like:
< HCI Command: LE Create Connection (0x08|0x000d) plen 25
    bdaddr 00:00:00:00:00:00 type 0
    interval 4 window 4 initiator_filter 1
    own_bdaddr_type 0 min_interval 15 max_interval 15
    latency 0 supervision_to 3200 min_ce 1 max_ce 1
> HCI Event: Command Status (0x0f) plen 4
    LE Create Connection (0x08|0x000d) status 0x00 ncmd 1
> HCI Event: LE Meta Event (0x3e) plen 19
    LE Connection Complete
      status 0x00 handle 64, role master
      bdaddr 68:C9:0B:xx:xx:xx (Public)
< HCI Command: Disconnect (0x01|0x0006) plen 3
    handle 64 reason 0x13
    Reason: Remote User Terminated Connection
> HCI Event: Command Status (0x0f) plen 4
    Disconnect (0x01|0x0006) status 0x00 ncmd 1
> HCI Event: Disconn Complete (0x05) plen 4
    status 0x00 handle 64 reason 0x16
    Reason: Connection Terminated by Local Host

and a bad connection is as follows:
< HCI Command: LE Create Connection (0x08|0x000d) plen 25
    bdaddr 00:00:00:00:00:00 type 0
    interval 4 window 4 initiator_filter 1
    own_bdaddr_type 0 min_interval 15 max_interval 15
    latency 0 supervision_to 3200 min_ce 1 max_ce 1
> HCI Event: Command Status (0x0f) plen 4
    LE Create Connection (0x08|0x000d) status 0x00 ncmd 1
> HCI Event: LE Meta Event (0x3e) plen 19
    LE Connection Complete
      status 0x00 handle 64, role master
      bdaddr 68:C9:0B:xx:xx:xx (Public)
> HCI Event: Disconn Complete (0x05) plen 4
    status 0x00 handle 64 reason 0x3e
    Reason: Connection Failed to be Established
< HCI Command: Disconnect (0x01|0x0006) plen 3
    handle 64 reason 0x13
    Reason: Remote User Terminated Connection
> HCI Event: Command Status (0x0f) plen 4
    Disconnect (0x01|0x0006) status 0x12 ncmd 1
    Error: Invalid HCI Command Parameters

Note: the last two entries (Invalid HCI Command Parameters) are because of the crudeness of the script, and only occur because of the failed connection.
Of note, it looks like the connection is made, then it says in couldn't (Connection Failed to be Established). This seems a bit confusing to me.
I have tried this on different machines. (desktop PC and RPi3)

A: Peripheral is advertising.  That means it periodically sends an avertisement (ADV_IND) packet on some advertisement channel.  In response to this packet, a central may either (Core_v4.2, 6.B.4.4.2.3):

*

*do nothing,

*send a scan request (SCAN_REQ) packet (Figure 4.3), peripheral should respond with a scan response (SCAN_RSP),

*send a connection request (CONN_REQ) packet (Figure 4.5).

Here, you have two centrals trying to reach the same peripheral at the same time.  One is doing active scanning (#2 above), the other is initiating (#3 above).  Unfortunately, both must send their packet at the exact same time, receiver gets jammed, and both scan request and connection request packets get lost.
There is no acknowledgement for connection requests. Initiator must to assume the advertiser received and accepted the connection request, create the connection speculatively, and possibly time out afterwards.  That's why the fast termination feature pointed by bare_metal exists.  In case the peripheral does not take the connection request, central should not wait forever.
LE Connection Complete event in your dumps just tell a Connection Request packet got sent, it does not tell it actually got received, processed or accepted by target.

A: on the confusion of connection created vs connection established please see the vol 6, Part B,section 4.5 from low energy specification (core 4.2). so it seems in the second instance the remote device didn't send any
data channel packet after CONNECT_REQ PDU. and in the second case if a disconnect is tried on a link which is not established , the controller will complain about invalid handle ( as there is no valid connection exist). To debug further you could enable Timing in hcidump which will confirm the failed to establish event is received by the host after Supervision Timeout.
"The Link Layer enters the Connection State when an initiator sends a
CONNECT_REQ PDU to an advertiser or an advertiser receives a
CONNECT_REQ PDU from an initiator.
After entering the Connection State, the connection is considered to be
created. The connection is not considered to be established at this point. A connection is only considered to be established once a data channel packet
has been received from the peer device. The only difference between A connection that is created and a connection that is established is the Link Layer connection supervision timeout value that is used"
"If the Link Layer connection supervision timer reaches 6 * connInterval before the connection is established (see Section 4.5), the connection shall be considered lost. This enables fast termination of connections that fail to establish"


Q: Add Dynamic table rows to table layout in android together with textwatcher I try to Add new Table rows into TableLayout in my android app. I successfully added new table rows with multiple edittexts,  by following an android tutorial. Now what I try to do is, I need to get user values for those edittexts using TextWatcher. I searched a lot of tutorials and tried a lot, but i was failed.
This is how my app looks like before I add a button to this.

What I need is to Open Second row by clicking a button If user wants, and if user enters values to edittext fields they need to use and , final Result should display accordingly.
This is my previous code, I posted with a question and solved it in here .
Using Android TextWatcher with multiple user input values and Update thses values
If someone could help me, I highly appreciate your help. Thanks in advance.
Now this is my new XML code
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/Button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:text="Add Line" />

    <ScrollView
        android:id="@+id/scrollView2"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/Button1"
        android:layout_marginTop="97dp">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TableLayout
                android:id="@+id/TableLayout1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:divider="?android:attr/dividerHorizontal"
                android:showDividers="middle">

                <TableRow
                    android:id="@+id/TableRow1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">

                    <EditText
                        android:id="@+id/editText1"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:ems="4"
                        android:padding="2dp" />

                    <EditText
                        android:id="@+id/editText2"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:ems="4"
                        android:padding="2dp" />

                    <EditText
                        android:id="@+id/editText3"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:ems="4"
                        android:padding="2dp" />

                    <TextView
                        android:id="@+id/TextViewsub1"
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:gravity="center"
                        android:hint="$ 0.00"
                        android:textSize="18dip" />

                </TableRow>

                <TableRow
                    android:id="@+id/TableRow2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">

                    <EditText
                        android:id="@+id/editText4"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:ems="4"
                        android:padding="2dp" />

                    <EditText
                        android:id="@+id/editText5"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:ems="4"
                        android:padding="2dp" />

                    <EditText
                        android:id="@+id/editText6"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:ems="4"
                        android:padding="2dp" />

                    <TextView
                        android:id="@+id/TextViewsub2"
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:gravity="center"
                        android:hint="$ 0.00"
                        android:textSize="18dip" />

                </TableRow>
            </TableLayout>
        </RelativeLayout>
    </ScrollView>

    <TextView
        android:id="@+id/textView12"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/scrollView2"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginEnd="87dp"
        android:layout_marginRight="87dp"
        android:hint="Rs: 0.00" />

    <TextView
        android:id="@+id/textView13"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/textView12"
        android:layout_marginEnd="86dp"
        android:layout_marginRight="86dp"
        android:layout_toLeftOf="@+id/textView12"
        android:layout_toStartOf="@+id/textView12"
        android:text="Total Value" />

</RelativeLayout>

This is now How my Java File looks like
 public class NewClass extends AppCompatActivity implements View.OnClickListener {

        Button btnAdd;
        int counter = 0;

        EditText edit1, edit2, edit3;
        TextView textViewSub1, textViewResult;

        @Override
        protected void onCreate(Bundle savedInstanceState) {

            /*First row variables*/
            edit1 = (EditText) findViewById(R.id.editText1);
            edit2 = (EditText) findViewById(R.id.editText2);
            edit3 = (EditText) findViewById(R.id.editText3);
            textViewSub1 = (TextView) findViewById(R.id.TextViewsub1);

            textViewResult = (TextView) findViewById(R.id.textView12);

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_new_class);

            //add line button
            btnAdd = (Button) findViewById(R.id.Button1);
            btnAdd.setOnClickListener(this);

            edit1.addTextChangedListener(new LashCustomTextWatcher1());
            edit2.addTextChangedListener(new LashCustomTextWatcher1());
            edit3.addTextChangedListener(new LashCustomTextWatcher1());

        }

        public class LashCustomTextWatcher1 implements TextWatcher {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                textViewResult.setText(lashCalculate());
            }
        }

        public void onClick(View view) {
            TableLayout tl = (TableLayout) findViewById(R.id.TableLayout1);
            TableRow tr = new TableRow(this);

            //TextView tv = new TextView(this);
            //tv.setText("text ");

            edit1 = new EditText(this);
            //edit1.setText("Hello " + counter++);

            edit2 = new EditText(this);
            //edit2.setText("Item no " + counter++);

            edit3 = new EditText(this);
            //edit3.setText("Qty no " + counter++);

            textViewSub1 = new TextView(this);

            tr.addView(edit1);
            tr.addView(edit2);
            tr.addView(edit3);
            tr.addView(textViewSub1);
            //tr.addView(cb);
            tl.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
        }

        public String lashCalculate() {

            //declaring variables
            double row1_value = 0;

            DecimalFormat df = new DecimalFormat("0.00");

            //calculate first row
            if (!edit1.getText().toString().equals("") && !edit2.getText().toString().equals("")) {
                double num1 = Double.parseDouble((edit1.getText().toString()));
                double num2 = Double.parseDouble((edit2.getText().toString()));

                row1_value = num1 * num2;

                double num3 = 0;
                if (!edit3.getText().toString().equals("")) {
                    num3 = Double.parseDouble((edit3.getText().toString()));
                    row1_value = (((100 - num3) * num2) * num1) / 100;
                }

                textViewSub1.setText(df.format(row1_value));
            }

            return df.format(row1_value);
    }

    }

A: 1) First of all in parent layout xml put linearlayot as below:
 <LinearLayout
                android:id="@+id/parent_layout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"></LinearLayout>

2) Than Make a layout that is want to add in every click.
3) You can now add your view in parent like below :
LinearLayout parent_layout = (LinearLayout)findViewById(R.id.parent_layout);
                    for(i=0;i<3;i++)
                    {
                      parentlayout.addView(myViewReview(data.get(i)));
                    }

public View myViewReview() {

        View v; // Creating an instance for View Object
        LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.row_facility_review, null);
        TextView row_reviewer_name = (TextView) v.findViewById(R.id.row_reviewer_name);
        TextView row_review_text = (TextView) v.findViewById(R.id.row_review_text);
        return v;
    }


Q: Ruby on Rails - Why is Materialize.updateTextFields not a function? I have a Ruby on Rails project that uses the material-saas gem. I recently noticed that text field animations have stopped working. More specifically, when a text field is active, the label does not move up on the page and whatever the user types in the input field writes over the label text and looks awful. Here (https://github.com/Dogfalo/materialize/issues/682) is an example of the style issue I'm encountering. In addition to the label text not moving correctly, the form also has a file field that is not working. When a user selects a file to upload, the file name does not appear in the form, which is the intended behavior.
I recently ran rake assets:clobber and rake assets:precompile and I wonder if that has something to do with this issue.
I did some research and in the Material CSS docs they say:

You can also call the function Materialize.updateTextFields(); to
  reinitialize all the Materialize labels on the page if you are
  dynamically adding inputs.

I attempted this fix, but I get Uncaught TypeError: Materialize.updateTextFields is not a function in my console when I load the page.
Here is my form view:
<%= render 'shared/header' %>

New Photo of the Day

<%= form_for @photo, multiple: true do |f| %>

    <%= f.label :title %>
    <%= f.text_field :title %>

    <%= f.label :caption %>
    <%= f.text_area :caption, class: "materialize-textarea" %>

  <%= f.label :date %>
  <%= f.date_field :date, class: "datepicker"%>

      File
      <%= f.file_field :image %>

      <input class="file-path validate" type="text">

    <%= f.submit "Upload", class: "btn-large waves-effect waves-light"  %>

<% end %>

Here is my assets/application.js
//= require jquery
//= require materialize-sprockets
//= require jquery_ujs
//= require react
//= require react_ujs
//= require components
//= require_tree .

Here is my assets/custom.js
$(document).ready(function() {
  Materialize.updateTextFields();
});

This is all really strange because I know the form style animations were working. I did not change the code for my form. The only thing I can think of is the clobber / precompile command, which I needed to run to get some ui improvements up onto production.
Thanks for taking the time to look this one over and I appreciate the assistance!

A: You are using jQuery 1.x.
Try using jQuery 2.x or 3.x.
Source: https://github.com/Dogfalo/materialize/issues/4593
E: The way to do this in your setup would be to change the line //= require jquery to //= require jquery2.

A: Looks like a few issues to me:
Rails is magic, and it does something called "turbolinks." Basically, pages are dynamically replaced instead of actually changing pages. It makes your site faster, but doesn't always issue the same Javascript events.
You'll also need JQuery 2 (I've updated my answer after advice from Dmitry).
Change the first few lines of your application JS to:
//= require jquery2
//= require turbolinks
//= require materialize-sprockets

Secondly, I found a second bug that exists in the materialize library. Basically, it wouldn't define updateTextFields() until turbo links loaded a page. To fix this, I've submitted a PR, but in the meantime, I would money-patch this by copy/pasting the method from the source to your code (inside $(document).ready). Use something like this to let your code get updated once they fix the bug (pretty much a polyfill).
Materialize.updateTextFields = Materialize.updateTextFields || // code from forms.js


Q: How to use a php code both for ajax and http requests? I have some classes and methods which are containing some php codes. Now I want to use those PHPcodes both for ajax and http requests. How?
Should I write all my PHP codes twice? onetime for ajax requests and one time for http request?
Here is my currect structure:
/********************************************** Search.php ****/

... // some html codes

<?php

if(!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) &&
   strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest")
{
  $type = true; // true means ajax request
} else {
  $type = false; // false means http request
}

  $obj = new classname;
  $results = obj->func($type);
  echo $results;

?>

... // some html codes

/********************************************** Classname.php ****/

class classname {

  public function func($type){
    $arr = ('key1'=>'some', 'kay2'=>'data');

    if ($type){
      echo json_encode($arr);
    } else {
      return $arr;
    }

  }

}

Now I want to know, this is standard? Actually I want to use it also for a request which came from a mobile app (something like an API). I think the above code has two problem:

*

*there will be a lot of IF-statement just for detecting type of requests (in the every methods)

*there is just one file (class.php) for both ajax and http requests. And when I send a ajax request by for example mobile, it will process some codes which doesn't need to them at all

Well, is there any point that I need to know?

A: This is more about the design of your software then simplifying it. Often you would have a structure with classes that you use and separate PHP files for types of responses.
For example:
You could have the documents: classes.php, index.php and ajax.php.
The classes would contain generic classes that can both be shown as JSON or as HTML.
PS:Simplified could mean:
/********************************************** Search.php ****/

... // some html codes

<?php

  $obj = new classname;
  $results = obj->func($_SERVER["HTTP_X_REQUESTED_WITH"]);
  echo $results;

?>

... // some html codes

/********************************************** Classname.php ****/

class classname {

  public function func($type){
    $arr = ('key1'=>'some', 'kay2'=>'data');

    if(!empty($type["HTTP_X_REQUESTED_WITH"]) &&
   strtolower($type["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest"){
      echo json_encode($arr);
    } else {
      return $arr;
    }

  }

}

A: You can write a single code, and you should use only partials to load AJAX data. The main reason we are using AJAX is to minimize data transfer. You should not load a full page HTML in an AJAX call, although it is perfectly valid.
I would suggest from my experience is, have a single file:
<?php
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        /* special ajax here */
        die(json_encode($data));
    } else { ?>

Regular Flow of Content

<?php } ?>

A: I would first do all the business logic, calling on your classes, without any dependency on whether you are in an ajax call or not. When all is ready for output, make the switch:
Search.php:
<?php
    // first do your business logic without view dependency.
    $obj = new classname;
    $results = obj->func(); // no type is passed.

    if(!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) &&
       strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest")
    {
        // ajax request
        echo json_encode($results);
        exit();
    }
    // http request
?>
... // some html codes

    <?=$results?>

... // some html codes

Classname.php:
<?php
class classname {
  public function func(){
    $arr = ('key1'=>'some', 'kay2'=>'data');
    return $arr;
  }
}
?>


Q: GLFW triangle will not change color I've been following a short youtube tutorial on how to make basic graphics with glfw.  I cannot get my triangle to change color help me.
main code:
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <fstream>

#include <GL/glew.h>
#include <GLFW/glfw3.h>

std::string LoadFileToString(const char* filepath)
{
    std::string fileData;
    std::ifstream stream(filepath, std::ios::in);

    if (stream.is_open())
    {
        std::string line = "";

        while (getline(stream, line))
        {
            fileData += "\n" + line;
        }

        stream.close();
    }

    return fileData;
}

GLuint LoadShaders(const char* vertShaderPath, const char* fragShaderPath)
{
    GLuint vertShader = glCreateShader(GL_VERTEX_SHADER);
    GLuint fragShader = glCreateShader(GL_FRAGMENT_SHADER);

    std::string vertShaderSource = LoadFileToString(vertShaderPath);
    std::string fragShaderSource = LoadFileToString(vertShaderPath);

    const char* rawVertShaderSource = vertShaderSource.c_str();
    const char* rawFragShaderSource = fragShaderSource.c_str();

    glShaderSource(vertShader, 1, &rawVertShaderSource, NULL);
    glShaderSource(fragShader, 1, &rawFragShaderSource, NULL);

    glCompileShader(vertShader);
    glCompileShader(fragShader);

    GLuint program = glCreateProgram();
    glAttachShader(program, vertShader);
    glAttachShader(program, fragShader);
    glLinkProgram(program);

    return program;
}

int main()
{
    if (glfwInit() == false)
    {
        //did not succeed
        fprintf(stderr, "GLFW failed to initialise.");
        return -1;
    }

    //4 AA
    glfwWindowHint(GLFW_SAMPLES, 4);
    //tells glfw to set opengl to 3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* window;
    window = glfwCreateWindow(640, 480, "DJ KELLER KEEMSTAR", NULL, NULL);

    if (!window)
    {
        fprintf(stderr, "Window failed to create");
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);
    glewExperimental = true;

    if (glewInit() != GLEW_OK)
    {
        fprintf(stderr, "Glew failed to initialise");
        glfwTerminate();
        return -1;
    }

    //generate VAO
    GLuint vaoID;
    glGenVertexArrays(1, &vaoID);
    glBindVertexArray(vaoID);

    static const GLfloat verts[] =
    {
        //X, Y, Z
        -1.0f, -1.0f, 0.0f,
        1.0f, -1.0f, 0.0f,
        0.0f, 1.0f, 0.0f
    };

    GLuint program = LoadShaders("shader.vertshader", "shader.fragshader");

    //generate VBO
    GLuint vboID;
    glGenBuffers(1, &vboID);
    glBindBuffer(GL_ARRAY_BUFFER, vboID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);

    glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
    do
    {
        glClear(GL_COLOR_BUFFER_BIT);
        glEnableVertexAttribArray(0);

        glBindBuffer(GL_ARRAY_BUFFER, vboID);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

        glUseProgram(program);
        glDrawArrays(GL_TRIANGLES, 0, 3);

        glDisableVertexAttribArray(0);

        glfwSwapBuffers(window);
        glfwPollEvents();

    } while (glfwWindowShouldClose(window) == false);

    return 0;
}

fragshader:
#version 330 core
out vec3 color;

void main()
{
    color = vec3(1,0,0);
}

vertshader:
#version 330 core
layout(location = 0) in vec3 in_pos;

void main()
{
    gl_Position.xyz = in_pos;
    gl_Position.w = 1;
}

The triangle is supposed to be red:

A: std::string vertShaderSource = LoadFileToString(vertShaderPath);
std::string fragShaderSource = LoadFileToString(vertShaderPath);
                                                ^^^^^^^^^^^^^^ wat

Don't try to use a vertex shader as a fragment shader.
Recommend querying the compilation and link status/logs while assembling the shader:
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <cstdarg>

struct Program
{
    static GLuint Load( const char* shader, ... )
    {
        GLuint prog = glCreateProgram();
        va_list args;
        va_start( args, shader );
        while( shader )
        {
            const GLenum type = va_arg( args, GLenum );
            AttachShader( prog, type, shader );
            shader = va_arg( args, const char* );
        }
        va_end( args );
        glLinkProgram( prog );
        CheckStatus( prog );
        return prog;
    }

private:
    static void CheckStatus( GLuint obj )
    {
        GLint status = GL_FALSE;
        if( glIsShader(obj) ) glGetShaderiv( obj, GL_COMPILE_STATUS, &status );
        if( glIsProgram(obj) ) glGetProgramiv( obj, GL_LINK_STATUS, &status );
        if( status == GL_TRUE ) return;
        GLchar log[ 1 << 15 ] = { 0 };
        if( glIsShader(obj) ) glGetShaderInfoLog( obj, sizeof(log), NULL, log );
        if( glIsProgram(obj) ) glGetProgramInfoLog( obj, sizeof(log), NULL, log );
        std::cerr << log << std::endl;
        exit( EXIT_FAILURE );
    }

    static void AttachShader( GLuint program, GLenum type, const char* src )
    {
        GLuint shader = glCreateShader( type );
        glShaderSource( shader, 1, &src, NULL );
        glCompileShader( shader );
        CheckStatus( shader );
        glAttachShader( program, shader );
        glDeleteShader( shader );
    }
};

#define GLSL(version, shader) "#version " #version "\n" #shader

const char* vert = GLSL
(
    330 core,
    layout( location = 0 ) in vec3 in_pos;
    void main()
    {
        gl_Position.xyz = in_pos;
        gl_Position.w = 1;
    }
);

const char* frag = GLSL
(
    330 core,
    out vec3 color;
    void main()
    {
        color = vec3(1,0,0);
    }
);

int main()
{
    if (glfwInit() == false)
    {
        //did not succeed
        fprintf(stderr, "GLFW failed to initialise.");
        return -1;
    }

    //4 AA
    glfwWindowHint(GLFW_SAMPLES, 4);
    //tells glfw to set opengl to 3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* window = glfwCreateWindow(640, 480, "DJ KELLER KEEMSTAR", NULL, NULL);
    if (!window)
    {
        fprintf(stderr, "Window failed to create");
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);

    glewExperimental = true;
    if (glewInit() != GLEW_OK)
    {
        fprintf(stderr, "Glew failed to initialise");
        glfwTerminate();
        return -1;
    }

    //generate VAO
    GLuint vaoID;
    glGenVertexArrays(1, &vaoID);
    glBindVertexArray(vaoID);

    static const GLfloat verts[] =
    {
        //X, Y, Z
        -1.0f, -1.0f, 0.0f,
        1.0f, -1.0f, 0.0f,
        0.0f, 1.0f, 0.0f
    };

    GLuint program = Program::Load
        (
        vert, GL_VERTEX_SHADER,
        frag, GL_FRAGMENT_SHADER,
        NULL
        );

    //generate VBO
    GLuint vboID;
    glGenBuffers(1, &vboID);
    glBindBuffer(GL_ARRAY_BUFFER, vboID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);

    glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
    do
    {
        glClear(GL_COLOR_BUFFER_BIT);
        glEnableVertexAttribArray(0);

        glBindBuffer(GL_ARRAY_BUFFER, vboID);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

        glUseProgram(program);
        glDrawArrays(GL_TRIANGLES, 0, 3);

        glDisableVertexAttribArray(0);

        glfwSwapBuffers(window);
        glfwPollEvents();

    } while (glfwWindowShouldClose(window) == false);

    return 0;
}

That way if you try something like:
GLuint program = Program::Load
    (
    vert, GL_VERTEX_SHADER,
    vert, GL_VERTEX_SHADER,
    NULL
    );

...it will bail out early and give you a better indication of what went wrong:
Vertex shader(s) failed to link.
Vertex link error: INVALID_OPERATION.
ERROR: 0:2: error(#248) Function already has a body: main
ERROR: error(#273) 1 compilation errors.  No code generated


Q: Minimalist Sphere Impostor -- computing sphere radius in zdepth I'm trying to code up a fast and minimalist sphere impostor-- the sphere doesn't need to be shaded or do anything but correct gl_FragDepth.
I have some code that's very close to working... cutting out everything but the key code:
vertex shader:
out_XYZ=float4(sphereCenter.xyz,1.)*sceneComboMatrix;
switch(gl_VertexID)
{
case 0:
    out_XYZ.xy+=vec2(radius,-radius);
    out_UV=float2(1.,-1.);
    break;
case 1:
    out_XYZ.xy+=vec2(-radius,-radius);
    out_UV=float2(-1.,-1.);
    break;
case 2:
    out_XYZ.xy+=vec2(radius,radius);
    out_UV=float2(1.,1.);
    break;
case 3:
    out_XYZ.xy+=vec2(-radius,radius);
    out_UV=float2(-1.,1.);
    break;
}

fragment shader:
float aLen2=dot(in_UV,in_UV);
float aL=inversesqrt(aLen2);
if (aL<1.) discard;
out_Color=float4(1.,0.,0.,1.);
float magicNumber=.0031f;
gl_FragDepth=gl_FragCoord.z-(sin(1.-(1./aL))*(3.14/2.)*magicNumber);

This produces the following:

Not TOO bad... it works as a proof of concept.  The issue is, my variable magicNumber above, which I simply fiddled around with, should be replaced with the radius of the sphere in zdepth.
How can I compute the size of the sphere's radius in terms of zdepth?
(A note: I don't need this to be hyperaccurate-- it's being used for some particles that can clip slightly wrong... but it does need to be more accurate than my screenshot above)
(EDIT----------)
Using resources from Nicol Bolas, I wrote some code to attempt to get the difference in zdepth between the sphere's maximally close point ot the camera and the sphere's center.  However, the result pushes the sphere VERY FAR toward the camera.  Why doesn't this code give me the length of the sphere's radius in z-space (i.e. the difference in Z between the sphere's center and another point closer to the camera?)
vec4 aSPos=vec4(spherePos.xyz,1.)*sceneComboMatrix;
float aD1=aSPos.z/aSPos.w;
aSPos=vec4(spherePos.xyz+(normalTowardCamera.xyz*sphereRadius),1.)*sceneComboMatrix;
float aD2=aSPos.z/aSPos.w;
radiusLengthInZ=((gl_DepthRange.diff*(aD1-aD2))+gl_DepthRange.near+gl_DepthRange.far)/2.0;


Q: Firefox profile is throwing a Selenium WebDriverException since I updated to Firefox 63 I have been using the following Selenium code to open a fresh Firefox profile.
    FirefoxProfile profile = new FirefoxProfile(new File("profile file path"));
    FirefoxOptions firefoxOptions = new FirefoxOptions();
    firefoxOptions.setProfile(profile);
    driver = new FirefoxDriver(firefoxOptions);
    driver.get("application Url");

It was working fine until I updated to Firefox 63 and now I am getting the following error.
1540496896005   Marionette  DEBUG   Accepted connection 0 from 127.0.0.1:53310
1540496896006   Marionette  TRACE   0 -> [0,1,"newSession",{"acceptInsecureCerts":true,"browserName":"firefox","capabilities":{"desiredCapabilities":{"acceptInsecureCerts":true,"browserName":"firefox"}}}]
1540496896006   Marionette  TRACE   0 <- [1,1,{"error":"unknown command","message":"newSession","stacktrace":"WebDriverError@chrome://marionette/content/error.js:178: ... et@chrome://marionette/content/server.js:245:8\n_onJSONObjectReady/<@chrome://marionette/content/transport.js:490:9\n"},null]
Oct 25, 2018 2:48:16 PM org.openqa.selenium.remote.ErrorCodes toStatus
INFO: HTTP Status: '404' -> incorrect JSON status mapping for 'unknown error' (500 expected)
Exception in thread "main" org.openqa.selenium.WebDriverException: newSession
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:05:20.749Z'
System info: host: 'NRIJCTDU8047923', ip: '10.241.10.83', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0'
Driver info: driver.version: FirefoxDriver
remote stacktrace: stack backtrace:
   0:           0x4bb74f - <no info>
   1:           0x4bbea9 - <no info>
   2:           0x43ce8d - <no info>
   3:           0x44ce14 - <no info>
   4:           0x44944a - <no info>
   5:           0x4203e1 - <no info>
   6:           0x407dc7 - <no info>
   7:           0x6d95b9 - <no info>
   8:           0x4173a7 - <no info>
   9:           0x6d38b3 - <no info>
  10:         0x770b59cd - BaseThreadInitThunk
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:83)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:57)
at java.lang.reflect.Constructor.newInstance(Constructor.java:437)
at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$new$0(W3CHandshakeResponse.java:57)
at org.openqa.selenium.remote.W3CHandshakeResponse$$Lambda$200.0000000013211B00.apply(Unknown Source)
at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$getResponseFunction$2(W3CHandshakeResponse.java:104)
at org.openqa.selenium.remote.W3CHandshakeResponse$$Lambda$202.0000000011F857C0.apply(Unknown Source)
at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:122)
at org.openqa.selenium.remote.ProtocolHandshake$$Lambda$203.0000000012223A00.apply(Unknown Source)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:204)
at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:969)
at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:137)
at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:540)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:527)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:513)
at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:163)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:245)
at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:475)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:125)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:73)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:212)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:130)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:125)
at selenium.utilities.SeleniumUtilities.OpenApplicationWelcomePage(SeleniumUtilities.java:35)
at selenium.mogems.MoGemsMainPondek.main(MoGemsMainPondek.java:14)

I have tried creating a new profile and also tried the following code.
        ProfilesIni profile = new ProfilesIni();
    FirefoxProfile myprofile = profile.getProfile("Selenium2");
    FirefoxOptions firefoxOptions = new FirefoxOptions();
    firefoxOptions.setProfile(myprofile);
    driver = new FirefoxDriver(firefoxOptions);

A: I just needed to update to the latest geckoDriver.

A: It might be useful to someone else, since I didn't immediately have success from just updating to the latest gecko driver (I was running an older version of selenium stand alone server, 3.6).
I am using facebook/php-webdriver.
After updating to Firefox 63, the combination of Selenium standalone server v3.8.1 and geckodriver 0.23 stopped the error occurring.

A: I am Case I Update my Gecko Driver its Working Fine Now.Always Try New Gecko Driver .
https://www.seleniumhq.org/download/.


Q: NoClassDefFoundError for aurora.jar I am trying to execute next:
C:\dev\sources\boSchedules\loadJavaLibs>java -cp aurora.jar; ojdbc6.jar
oracle.aurora.server.tools.loadjava.LoadJavaMain -thin -user login/pass@myserv:mysid
 %BOS_SRC%/credit/card/api/ScheduleCardApi

And I get next:
Exception in thread "main" java.lang.NoClassDefFoundError: ojdbc6/jar
Caused by: java.lang.ClassNotFoundException: ojdbc6.jar
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: ojdbc6.jar.  Program will exit.

Why am I getting this error?

A: Take a look at the Java Application Launcher man page.
java -cp aurora.jar; ojdbc6.jar
oracle.aurora.server.tools.loadjava.LoadJavaMain -thin -user sched/sched@teach:prod
 %BOS_SRC%/credit/card/api/ScheduleCardApi

You have a space between your classpath entries aurora.jar; ojdbc6.jar. The launcher thinks the first jar is the only classpath entry and the ojdbc6.jar is your class containing the main(String[] args) method. It also considers everything after that as arguments to pass to the main(String[] args) method. Remove that space.

A: Remove the space between the aurora.jar; and the ojdbc6.jar

A: Spaces delimit the parameters each other. The JVM interprets the command as if you run "ojdbc6.jar" class: "jar" as a classname and "ojdbc6" as a package.
To concat the names of libraries you want to place into classpath for a specific class run please use semicolon with no spaces as "lib1;lib2"
P.S.: Could you please ask your colleagues if you may paste some of our credentials to the SO? :)


Q: Can phone use host network when debugging on device via Eclipse/ADB? I have a Android phone connected with host computer with USB cable. ADB runs well and I can debug application on phone. The only problem is that the App requires special network setup which I can reach on host but not mobile. Is there a way to let the device send all network operations through ADB and Host network?

A: What you're looking for is known as reverse tethering. See https://android.stackexchange.com/questions/2298/how-to-set-up-reverse-tethering-over-usb for a solution.

A: Have you tried sharing your internet connection on your laptop, and connect your phone through it?. Make sure you disable data connection on your phone to assure you are connected through WiFi


Q: Reactive redirection using go_router and flutter_bloc What would be the best way to somehow implement a reactive redirection using bloc states? Currently I'm doing redirection like this:
router.dart
final router = GoRouter(
  routes: [
    GoRoute(
      name: OnBoardingPage.name,
      path: '/',
      builder: (context, state) => OnBoardingPage(),
      redirect: (context, state) async {

        final homeLocation = '/login';
        if (isMobilePlatform) {
          final onBoardingCubit = context.read<OnBoardingCubit>();
          await onBoardingCubit.init();
          if (onBoardingCubit.state is DoNotShowOnBoarding) return homeLocation;

          return null;
        }

        return homeLocation;
      },
    ),
    GoRoute(
      name: 'login',
      path: '/login',
      builder: (context, state) => HomePage(),
    ),
  ],
);

onboardingpage.dart
class OnBoardingPage extends StatelessWidget {
  static String name = 'oboarding';
  const OnBoardingPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocListener<OnBoardingCubit, OnBoardingState>(
      listener: (context, state) {
        if (state is DoNotShowOnBoarding) {
          GoRouter.of(context).refresh();
        }
      },
      child: IntroductionScreen(
        rawPages: introductionPages(context),
        onDone: () => context.read<OnBoardingCubit>()..onBoardingIsCompleted(),
        next: Icon(Icons.arrow_forward),
        done: Text('done'.tr()),
        curve: Curves.easeInQuad,
        controlsMargin: const EdgeInsets.all(16),
        dotsDecorator: DotsDecorator(
          size: const Size.square(10.0),
          activeSize: const Size(20.0, 10.0),
          activeColor: Theme.of(context).colorScheme.primary,
          spacing: const EdgeInsets.symmetric(horizontal: 3.0),
          activeShape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(25.0),
          ),
        ),
      ),
    );
  }
}

However I do not like the fact hat I have to call GoRouter.of(context).refresh() in the bloc listener to trigger the redirection again. Is there a more professional way to work with flutter_bloc ?


Q: How to receive response from an HTTPS site (PYTHON) I would like to know how do I connect and receive a response from a website that uses HTTPS I believe I have to use ssl but I do not know how?
import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("www.netflix.com", 443))
client.send("GET / HTTP/1.1\r\nHost: www.netflix.com\r\n\r\n")
print client.recv(1024)


Q: convert mysql dump file to access db I have mysql dump file and I need to convert it to ms access, I have no access to phpmyadmin  so I can't use the programs that connect to the mysql db, so  I need for a software to convert mysql dump file to ms access db.
just i have this dump file in hand
thanks if you can help


Q: Is it possible to share a branch to anyone else in the team without committing it in GIT ? Consider that i am working on a branch and made some changes and need some help from my friend and want to send the branch to him without committing it.
is it possible?
Considering that i am working on the main development branch

A: Of course you can send patches to anyone (git diff >file).  However, branches contain commits (really, they're just a name for one commit and its ancestors come along for the ride), so it's meaningless to talk about sharing a branch without having committed anything.


Q: How to determine if a user purchased an App I was wondering how can I determine though code, if a user did buy our App through the Windows Store.
Because we have a payed App, and I found it for download on eg. FileDir as an .xap file. Fully working.
We are not working with in-app purchases or trial version, you have to pay for it.

A: If you are not the original developer (logged in with the same account) XAP installation through SD Card or download will still require you buy the application. If you have already bought it in the past it will not ask again as it will verify that with the Windows Phone Store.
Is that your question?
If you are asking how to check from one app if another one has been bought the best option is to check the list of installed apps:
InstallationManager.FindPackagesForCurrentPublisher method
To check if license is still active you can check in the code:
bool hasBeenBought = Windows.ApplicationModel.Store.CurrentApp.LicenseInformation.IsActive;


Q: Syntax errors in if/else statement I am very new to c# and while working on a basic program I am receiving this error(Error Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement) and cannot figure out why it is appearing.
if (pizzaDiameter >= 12 && pizzaDiameter < 16)// begin nested if statement
{
    Console.WriteLine("A" + pizzaDiameter + "will yield 8 slices.");
}
else if (pizzaDiameter >= 16 && pizzaDiameter < 24)//Second pizza diameter range
{
    Console.WriteLine("A" + pizzaDiameter + "will yield 12 slices.");
}
else if (pizzaDiameter >= 24 && pizzaDiameter < 30)
{
    Console.WriteLine("A" + pizzaDiameter + "will yield 16 slices.");
}
else (pizzaDiameter >= 24 && pizzaDiameter <= 30)
{
    Console.WriteLine("A" + pizzaDiameter + "will yield 24 slices.");
}
else // pizza diameter was not a whole number
{
    Console.WriteLine("Pizza diameter must be between 12-36 inclusive.");// Error appears here.
}
else //pizza diameter must be between 12-36
{
    Console.WriteLine("Pizza diameter must be a whole number.");
}

A: There's something wrong with your control structure, i.e. you've got only one if(), but three times else.
Also, try to think about the problem and you'll notice that you can simplify the whole structure significantly (and also skip many checks):
if (pizzaDiameter < 12) // All diameters below 12 will use this branch.
    Console.WriteLine("Your pizza seems to be too small.");
else if (pizzaDiameter < 16) // You don't have to ensure it's bigger than 12, since those smaller already picked the branch above.
    Console.WriteLine("A diameter of " + pizzaDiameter + " will yield 8 slices");
else if (pizzaDiameter < 24) // Again you won't have to care for less than 16.
    Console.WriteLine("A diameter of " + pizzaDiameter + " will yield 12 slices");
// ...
else
    Console.WriteLine("Your pizza seems to be too big.");


Q: What does LockBits/UnlockBits do in c#? I have a method in c# that the only thing it does its LockBits, and then UnlockBits, and the images(input/output, transformed to byte arrays) are different. The one from output has less 100 and something bytes than the one from the input. This happens only with .jpg files. And checking the files in HxD I came to the understanding that it´s removing a part of the header, the exif signature to be exact. But I don't know how and why.
Does someone know what this is doing?
Here's the code:
public Image Validate (image){
  BitmapData original = null;
  Bitmap originalBMP = null;
  try{
     originalBMP = image as Bitmap;
     original = originalBMP.LockBits(new Rectangle(0, 0,
        originalBMP.Width, originalBMP.Height),
        ImageLockMode.ReadWrite,
        originalBMP.PixelFormat);
     originalBMP.UnlockBits(original);
  }catch{}

  return image;
}

A: Calling Bitmap.LockBits() followed by Bitmap.UnlockBits() does nothing.
The behavior you observe is because of loading a JPEG image, and then saving it again. JPEG uses a lossy algorithm. So what happens:

*

*You load the JPEG from disk

*The JPEG data gets decoded into individual pixels with color information, i.e. a bitmap

*You save the bitmap again in the JPEG format, resulting in a different file than #1

You also potentially lose metadata that was present in the JPEG file in doing so. So yes, the file is different and probably smaller, because every time you do this, you lose some pixel data or metadata.
Lockbits/Unlockbits are used to allow the program to manipulate the image data in memory. Nothing more, nothing less. See also the documentation for those methods.

A: Use the LockBits method to lock an existing bitmap in system memory so that it can be changed programmatically. You can change the color of an image with the SetPixel method, although the LockBits method offers better performance for large-scale changes.
A Rectangle structure that specifies the portion of the Bitmap to lock.
Example:
    private void LockUnlockBitsExample(PaintEventArgs e)
    {
    // Create a new bitmap.
    Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg");

    // Lock the bitmap's bits.
    Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
    System.Drawing.Imaging.BitmapData bmpData =
        bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
        bmp.PixelFormat);

    // Get the address of the first line.
    IntPtr ptr = bmpData.Scan0;

    // Declare an array to hold the bytes of the bitmap.
    int bytes  = Math.Abs(bmpData.Stride) * bmp.Height;
    byte[] rgbValues = new byte[bytes];

    // Copy the RGB values into the array.
    System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

    // Set every third value to 255. A 24bpp bitmap will look red.
    for (int counter = 2; counter < rgbValues.Length; counter += 3)
        rgbValues[counter] = 255;

    // Copy the RGB values back to the bitmap
    System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);

    // Unlock the bits.
    bmp.UnlockBits(bmpData);

    // Draw the modified image.
    e.Graphics.DrawImage(bmp, 0, 150);

}


Q: While generating Controller, "View Model "requires a primary key" error I have 3 tables, 1 has master data of students, 1 is a lookup table that links address and third is a table of family members names.
I wanted to create a page to input student details, their address and family members. So I created a View model class.
When I generate the Controller for that view model class, The Entity type "ViewModelClassName" requires a primary key error pops up.
I am new to web development. I am in a situation where there is no one to ask anything. Please help. Thanks.
public StudentMaster StudentMaster { get; set; }
public StudentAddresses StudentAddresses { get; set; }
public StudentFamilyMembers StudentFamilyMembers { get; set; }

A: ASP.NET Scaffolding is expecting Entity Framework based Data Model classes in order to help you creating views/controllers . But you are using View Model ,view model doesn't been persist in a database and also it doesn't have any primary key field, hence it cannot be scaffolded. And also when using scaffold wizard you always need to choose data context . But a view model has no relationship with your data context.
You should use your actual data model instead of a viewmodel to perform scaffolding , then modify the codes to use view model to transfer data between views and controllers
Inside your controller action that you could map the view model back to your data model that will be persisted using EF. You could use AutoMapper to map between your view models and data models.


Q: How to create file association with two program and making one default if both present? I have to create file association for an extension with two programmes and if both programmes A and B are present then choose program A to open the file. If only B is present then choose program B to open the file. If you can give the wix code or else you can provide me with registry details.

A: Create a wrapper (just a simple batch script) that calls the appropriate program. Set the file type association to use the wrapper.

A: I would suggest you to use registry entry.
Call a CustomAction in WIX to check for the registry entry. The check can be as simple as if...else
IF (Regitry_A != null && Registry_B != null)
{
//Choose program A
}
ELSE IF (Regitry_A != null)
{
//Choose Program A
}
ELSE
{
//Choose Program B
}


Q: Playframework - internationalization and routes I need two language versions of my web site which will be located in domainname/lang1/somecontroller and domainname/lang2/somecontroller urls. What architecture of routes file allow me to avoid of duplicating controllers declaration for every language?

A: *   /{language}/MyController         Application.MyController

should allow you to access both languages, and you then have access to the language passed in, in the controller, if you wish.


Q: I recently installed tensorflow on python 3.7.5 on my system without any problem but I couldn't import it. Below is the error that it gives me import tensorflow
Traceback (most recent call last):
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow\__init__.py", line 98, in <module>
    from tensorflow_core import *
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\__init__.py", line 40, in <module>
    from tensorflow.python.tools import module_util as _module_util
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow\__init__.py", line 50, in __getattr__
    module = self._load()
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow\__init__.py", line 44, in _load
    module = _importlib.import_module(self.__name__)
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\PETER\Anaconda3\envs\flaskenv\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.

Failed to load the native TensorFlow runtime.


Q: Property.ValueChangeListener - Cannot be resolved to a variable (Vaadin) I'm trying the tutorial available on vaadin's website and when I was setting the item selection on a table's row the tutorial suggests that I should add the following line to my table class.
addListener((Property.ValueChangeListener), app);

Being app a reference to my controller. However eclipse points an error to Property.ValueChangeListener "Property.ValueChangeListener cannot be resolved to a variable".
What exactly am I doing wrong here ?
PS: My believe my imports are correct since eclipse's auto-complete was working just fine to identify .ValueChangeListener
PersonList Class:
package com.example.simpleaddressbook2;

import com.vaadin.data.Property;
import com.vaadin.ui.Table;

public class PersonList extends Table {

    public PersonList(Simpleaddressbook2Application app){

        setSizeFull();
        setContainerDataSource(app.getDataSource());
        setVisibleColumns(PersonContainer.NATURAL_COL_ORDER);
        setColumnHeaders(PersonContainer.COL_HEADERS_ENGLISH);
        setSelectable(true);
        setImmediate(true);
        addListener((Property.ValueChangeListener), app);
        setNullSelectionAllowed(false);
    }

}

A: Found what was wrong, the correct code is :
addListener((Property.ValueChangeListener) app);

and not
addListener((Property.ValueChangeListener), app);

Damn comma !


Q: Creating a method to remove ArrayList elements from index x to index y As the title says, if I'm creating a method to remove a section of an ArrayList, how would I go about this.
If I have ArrayList<Character> se = {'a','b','c','d','e','f','g'}
and want to return only "abg"
I would call this method as such:
remove(2,5);

How could I create this method to remove not only the arg indexes but also everything in between?

A: list.subList(2, 6).clear()

does the job in one step.

A: Create a loop counting backward from 5 to 2 and remove the elements.
for(int i = 5; i >= 2; i--) ...

A:   void method(int startindex , int endindex)
   {
    for(int i = 0 ; i < endindex - startindex ; i++)//in your example startindex = 2 end.. = 6
     {
       list.remove(startindex);
     }
   }

modify your code accordingly.Hope this may solve your problem.

A: Create a loop at same position, removing elements a certain number of times.
For example, if you wanted to call
list.remove(a,b)

Your code would be:
for (int i = 0; i <= b - a; i++) {
    list.remove(a);
}


Q: bash get the number of files and pass it to for loop I am trying to get the number of files with a certain pattern in a directory and then do a for loop starting from zero to that number.
number=`ls -d *pattern_* | wc -l`%3d
for i in {001.."$number"};do
  # do something with $i
done

the problem is that my numbers are three digits, so that is why i added %3d to the end of my number variable, but it is not working.
so if I have 20 files, the number variable in the for loop should get a leading zero 020.

A: You really shouldn't rely on the output of ls in this way, since you can have filenames with embedded spaces, newlines and so on.
Thankfully there's a way to do this in a more reliable manner:
((i == 0))
for fspec in *pattern_* ; do
    ((i = i + 1))
    doSomethingWith "$(printf "%03d" $i)"
done

This loop will run the exact number of times related to the file count regardless of the weirdness of said files. It will also use the correctly formatted (three-digit) argument as requested.


Q: reactjs-components@5.0.3 requires a peer of cnvs@1.1.14 but none was installed I would like too install redux package. When i am using "npm install redux" i have warrning like this.
─ UNMET PEER DEPENDENCY cnvs@1.1.18 extraneous
├── gulp-sass@4.1.0  extraneous
├── gulp-sourcemaps@2.6.5  extraneous
├── gulp-watch-sass@1.4.1  extraneous
├── node-sass@4.14.1
├── react-gemini-scrollbar@2.3.4  extraneous
├── react-redux@7.2.1
├── react-transition-group@4.4.1  extraneous
├── reactjs@1.0.0  extraneous
├── reactjs-components@5.0.3  extraneous
├── redux@4.0.5  extraneous
├── sass@1.26.10  extraneous
└── usestate@1.1.3  extraneous
reactjs-components@5.0.3 requires a peer of cnvs@1.1.14 but none was installed.
How too fix it?

A: there are some solutions

*

*npm install cnvs@1.1.14

*npm audit fix (this one requires you to have a package.json file [get that by npm init])
tell me if one works
OR
list the problems that you face

A: Now when i am using npm install redux everythink looks fine but, this is my package.json and i dont have 'redux' in dependencies. When i wanna use  import { createStore } from 'redux';
my Webstorm dont see redux package.
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-redux": "^7.2.1",
"react-scripts": "0.9.5"
},
"devDependencies": {
"gulp": "^4.0.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"description": "This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).",
"main": "index.js",
"author": "",
"license": "ISC"
}


Q: PhpStorm highlighting Laravel blade incorrectly on Mac? Was ok on old PC tl;dr -  My PhpStorm 10 is highlighting my blade code incorrectly: (see screenshot)
Screenshot sample of incorrect highlighting:

Please help me fix this?
I recently switched away from PC (PhpStorm 9) to Mac (PhpStorm 10.0.2).
I git cloned to the new mac (a Laravel 5.1 project), setup homestead, ok.
But PhpStorm highlights this code as if I've missed an ending semicolon. (see screenshot above - the below is the code that gets highlighted strangely).
        @yield('content')

           <!--also the following-->

        @if (Session::has('flash_message'))
            <div>{{ Session::get('flash_message') }}</div>
        @endif

This was not an issue on my old PC setup.  AFAIK Laravel's @yield and @if @endif don't need a semicolon, based on this.
I've run this code for 4 months from my old PC without issues, and it runs normally on my Mac's Laravel Homestead installation.
I've tried these:
1. exported and imported all settings from my old PC's phpstorm to
        the Mac - it imported my text colors but still highlights wrong on Mac.
2. downloaded the Laravel plugin and restarted phpstorm - no change
3. confirmed the blade plugin is activated in phpstorm
4. tested the same file on my old PC - no issues there in phpstorm 9.
What could be causing this highlighting? What have I missed?

A: Tinkered around and a solution:
Go to Phpstorm

Preferences  (on Mac, 'Settings' on PC) >
  Editor > Colors & Fonts > PHP >
  PHP Code  > Background

On my Mac the background color was set incorrectly to white (inherited).
I then unchecked "Use Inherited Attributes" and set it to black. Problem fixed.
I don't know why this was set to white as on my PC it is set to black.
I had done a phpstorm full settings export from pc, and imported to mac, using the generated settings.jar file so I can't say why this did not import properly. Don't know if something changed between versions 9.0 and 10.0 or whether it got skipped somehow during import.


Q: Retrieving viewport height of screen in mobile browsers with jquery I'm attempting to get the viewport height in mobile browsers WITHOUT the height of the browser bar but all of the solutions I've attempted have come up short.
What others have suggested is using the below, however it does not work for me. I still get a blank white bar at the bottom of the window when scrolling
var screenHeight = window.innerHeight;
$('.mobile-nav-wrapper').height(screenHeight)

A: Solution 1:
I don't have an answer using jQuery. But using a plain/vanilla JavaScript wouldn't cause any issue :).
Following script allows you to detect the Viewport size (height and width) reliably.
https://github.com/tysonmatanich/viewportSize
Sample usage:
<script type="text/javascript">
    var width = viewportSize.getWidth();
    var height = viewportSize.getHeight();
</script>

I have used it in couple of projects, were i have to re-initialize some widgets based on current Viewport width/height rather than using window width/height (Window width/height calculation isn't consistent in all browsers - some include scroll bar size 16px as a part of window width and some doesn't).
Sample Test page:
http://tysonmatanich.github.io/viewportSize/
Solution 2: (Just for reference - Not an answer to OP's question, though it is related so I thought that it can remain)
Well modernizr has a very good addition Modernizr.Mq. Through which you can cross check which break point range you are in...
if(Modernizr.mq("(min-width:320px)")){
//Do job 1
}
else if (Modernizr.mq("(min-width:768px)")){
//Do job 2
}

or
based on height
Modernizr.mq("(min-height: 800px)")
http://tysonmatanich.github.io/viewportSize/

A: I believe what you are looking for is scrollHeight

The scrollHeight property returns the entire height of an element in
  pixels, including padding, but not the border, scrollbar or margin.

You can try this:
document.body.scrollHeight


Q: Select box options to write to new row in database - MySQL and PHP I have a form which currently has the following fields:
Name, Size, Template

There are two select boxes in this form for the fields 'Size' and 'Template'. I want the form to insert a new row if a user selects more than one option on the select box.
I have managed to do this for 'Template' but I can not figure out how to use the foreach construct twice so that it also inserts a new row when multiple options are selected from the Size field.
Here is my code which works for inserting a new row for multiple 'Template' selected options:
$template = $_POST['Template'];
$size = $_POST['Size'];

foreach( $template as $temp ) {

  switch( $temp ) {
 case '1':
   $template;
 break;
 case '2':
   $template;
 break;
 case '3':
   $template;
 break;
  case '4':
   $template;
 break;
 };

 $query = "INSERT INTO tbl (Name,Size,Template) VALUES('$name', '$size', '$temp')";
 }

Is there a way to use this foreach statement twice but to run the same query.
For example, I was thinking to do
foreach( $size as $newsize) {
switch( $newsize ) {

//cases go here

};
}

A: The for loop would be more appropriate for what you've been trying to achieve:
for($i=0; $i<count($size); $i++)
{
    for($j=0; $j<count($template); $j++)
    {
        $currentSize = $template[$i];
        $currentTemplate = $template[$j];
        $query = "INSERT INTO tbl (Name, Size, Template) VALUES('$name', '$currentSize', '$currentTemplate')";
    }
}

Warning: I only wrote the query in the same way you did to demonstrate the rest of the code. The query is actually vulnerable to SQL Injection attacks and you should definitely avoid it. Instead write the query like this:
$query = "INSERT INTO tbl (Name, Size, Template) VALUES(?,?,?)";
The question marks are place holders. You will need to prepare this statement and then bind $name, $currentTemplate and $currentSize to them before executing. Check this for more information on prepared statements. Since you need to execute the same query multiple times with different data you have one more reason to use prepared statements. I highly recommend you check Example#3 of the documentation in the link above


Q: Is there a python REPL for Google App Engine? The Clojure/Compojure people have a drop in repl for Google App Engine, do Python people have anything similar? I use the repl quite a bit in "vanilla" python development, and it would be really useful if I could use it in Google App Engine Python as well.
I have seen the following http://shell.appspot.com/ demo, and I was basically hoping there might be a drop-in replacement for any Python App Engine project that gave me a repl; even if the repl only worked against the dev server. Anyone know of such a thing?
here is the source code to this demo, just for completeness.

A: If you're okay with a REPL that works on the dev server, take a look at the bin/python script that Tipfy creates for you. It just loads the Python REPL with your project and the GAE SDK code. I've pasted my version of it here - YMMV, but you can use it as a starting point.


Q: Dropdown Contents below Modal I'm having challenges with a dropdown list in my project. When I have it on a regular page it works just fine. When I have it in a modal the contents are behind the modal and can't be accessed.
I did some research and see I'm having problems with my z-index. However, I still can't get it to work. I've given the modal a z-index of 3000 and given the dropdown the absolute maximum z-index of 2147483647 and the dropdown still renders behind the modal.
Here is the relevant CSS:
/*trying to get query dropdown on top*/
.dropdown-on-top{
  /*position: absolute;*/
  z-index: 2147483647;
}

.modal-below-dropdown{
  /*position: relative;*/
  z-index: 3000;
}
/*end of tring to get query dropdown on top:*/

I'm using model-below-dropdown to set the z-index for the modal. I'm using dropdown-on-top to have the dropdown stay above the modal.
FYI - I've commented out the position items for both because when I had them enabled the modal wouldn't display at all. But, from what I've read I need both of them to make this work.
Here is the HTML for the modal:

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Create Query

    <form class="form-horizontal">

        Query Name

          <input type="text" class="form-control" placeholder="Query Name">

        Media

              <input type="checkbox" value="">
              Print

              <input type="checkbox" value="">
              Digital

        Type

              <input type="radio" name="optionsRadios" value="">
              Add

              <input type="radio" name="optionsRadios" value="">
              Drop

    </form>

        Demographic

        Values
        Operator

  <select id="combobox" class="dropdown-on-top">
    <option value="Select one...">Select one...</option>
    <option value="Product Registration > Magazine > On File">"Product Registration > Magazine > On File"</option>
    <option value="Product Registration > Magazine > BPA Par 3B Source">"Product Registration > Magazine > BPA Par 3B Source"</option>
    <option value="Product Registration > Magazine > Promo Key">"Product Registration > Magazine > Promo Key"</option>
    <option value="Product Registration > Magazine > Record Status">"Product Registration > Magazine > Record Status"</option>
    <option value="Product Registration > Magazine > Subtype">"Product Registration > Magazine > Subtype"</option>
    <option value="Product Registration > Magazine > Verification Date">"Product Registration > Magazine > Verification Date"</option>
    <option value="Product Registration > Magazine > Activated Date">"Product Registration > Magazine > Activated Date"</option>
  </select><span

            <select class="form-control">
              <option>Equals</option>
              <option>Not Equal To</option>
              <option>Contains</option>
              <option>Does Not Contain</option>
              <option>Is Empty</option>
              <option>Is Not Empty</option>
            </select>

            <select class="form-control">
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
              <option>5</option>
            </select>

            <select class="form-control">
              <option> </option>
              <option>And</option>
              <option>Or</option>
            </select>

            <select class="form-control">
              <option> </option>
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
              <option>5</option>
            </select>

            <select class="form-control">
              <option>Equals</option>
              <option>Not Equal To</option>
              <option>Contains</option>
              <option>Does Not Contain</option>
              <option>Is Empty</option>
              <option>Is Not Empty</option>
            </select>

            <select class="form-control">
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
              <option>5</option>
            </select>

            <select class="form-control">
              <option> </option>
              <option>And</option>
              <option>Or</option>
            </select>

            <select class="form-control">
              <option> </option>
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
              <option>5</option>
            </select>

            <select class="form-control">
              <option>Equals</option>
              <option>Not Equal To</option>
              <option>Contains</option>
              <option>Does Not Contain</option>
              <option>Is Empty</option>
              <option>Is Not Empty</option>
            </select>

            <select class="form-control">
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
              <option>5</option>
            </select>

            <select class="form-control">
              <option> </option>
              <option>And</option>
              <option>Or</option>
            </select>

      Save Query
      Cancel

All help is greatly appreciated.

A: The Jquery plugin hide the original select <select id="combobox"> and apply other HTML tags. So, write CSS for the hidden ones won't change a thing.
You should use ui-autocomplete.ui-menu as the css selector to style the dropdown.
Try:
.ui-autocomplete.ui-menu {
  z-index: 3001;
}


Q: Specify Binding of DependencyProperty in UserControl itself Following up on my previous question (Change brushes based on ViewModel property)
In my UserControl I have have a DependencyObject. I want to bind that object to a property of my ViewModel. In this case a CarViewModel, property name is Status and returns an enum value.
public partial class CarView : UserControl
{
    public CarStatus Status
    {
        get { return (CarStatus)GetValue(CarStatusProperty); }
        set { SetValue(CarStatusProperty, value); }
    }

    public static readonly DependencyProperty CarStatusProperty =
        DependencyProperty.Register("Status", typeof(CarStatus), typeof(CarView), new PropertyMetadata(OnStatusChanged));

    private static void OnStatusChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
    {
        var control = (CarView)obj;
        control.LoadThemeResources((CarStatus)e.NewValue == CarStatus.Sold);
    }

    public void LoadThemeResources(bool isSold)
    {
        // change some brushes
    }
}

<UserControl x:Class="MySolution.Views.CarView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:views="clr-MySolution.Views"
             mc:Ignorable="d"
             views:CarView.Status="{Binding Status}">
    <UserControl.Resources>
    </UserControl.Resources>
    <Grid>
        <TextBlock Text="{Binding Brand}"FontSize="22" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    </Grid>
<UserControl

Where do I need to specify this binding? In the root of the UserControl it gives an error:

The attachable property 'Status' was not found in type 'CarView'

In my MainWindow I bind the CarView using a ContentControl:
<ContentControl
    Content="{Binding CurrentCar}">
    <ContentControl.Resources>
        <DataTemplate DataType="{x:Type viewmodel:CarViewModel}">
            <views:CarView />
        </DataTemplate>
    </ContentControl.Resources>
</ContentControl>

My ViewModel:
[ImplementPropertyChanged]
public class CarViewModel
{
    public Car Car { get; private set; }

    public CarStatus Status
    {
        get
        {
            if (_sold) return CarStatus.Sold;
            return CarStatus.NotSold;
        }
    }
}

A: your binding isn't well written. instead of writing views:CarView.Status="{Binding Status}" you should write only Status="{Binding Status}"

A: It seems that your Control is binding to itself.
Status is looked for in CarView.
You should have a line of code in your control CodeBehind like  :
this.DataContext = new ViewModelObjectWithStatusPropertyToBindFrom();

Regards


Q: Java and UML: Relationship between a LinkedList class and an Iterator Interface I have a few questions on UML relationships in Java.
The following classes and interfaces refer to classes and interfaces (either created or existing) in Java.
Setup:
Suppose I have a GenericLinkedList<T> implements Iterable<I> class (with private Node<T> head). This class also has a static inner class Node<D>.
The GenericLinkedList<T> implements the abstract method iterator() (from Iterable<I>) that returns an Iterator<T>.
The class that implements Iterator<T>, GLLIterator<T>, takes an GenericLinkedList<T> object as a parameter (in its constructor), but just stores the head of this list in a private cur variable.

*

*Would the relationship between GLLIterator<T> and GenericLinkedList<T> be Composition (with the black diamond pointing to the list), even though the latter does not contain the former? I thought it would because the "iterators" are meaningless without the the "lists". Or would it just be a dependency, since the iterator just "uses" the list to get head?

*Would the relationship between Node<D> and GLLIterator<T> be Aggregation or Composition? I thought it would be Aggregation because we can have multiple iterators at the same node. But, on the other hand, when the cur node dies, the iterator is meaningless.

*Would I draw a dependency between the list class and the iterator interface or the class that implements the interface?

Edit: I was trying to reason through (1) as follows:
So, the linked list has nodes and the iterator has a node.
If Java had destructors, would I need to call the destructor of an iterator if I destroy the linked list?
If I destroy the linked list, the destructors of the nodes should get called.
But the iterator exists apart from the list, it (1) just points to a node in the list and (2) can be used as an iterator for another list.
I ask because I was wondering the UML relationship between the iterator classes and the linked list class: Composition (owns) or Aggregation (has-a).
Thank you.

A:
If Java had destructors, would I need to call the destructor of an iterator if I destroy the linked list?

To delete an iterator because it corresponds to a deleted node (whatever the list is deleted or not, so all its nodes are deleted or not) is for me the worst possible choice, that means the iterator becomes silently unusable, a very practical way to introduce undefined behaviors at the execution.
In case a node knows its iterators a good way is to mark them invalid when the node is  deleted, and in that case to try access the corresponding element of the list or go to the previous/next element produces an exception.
For me the list by itself do not need to know the iterators, and an iterator does not need to know the list by itself, so for question 1 no relation at all between GenericLinkedList<T> and GLLIterator<T>.
For the question 2 no aggregation nor composition, because the iterator just references a node, the iterator has a node is false, an iterator is not composed of nodes nor owns them. In the reverse direction even a node knows the iterators pointing to it that node is not composed of iterator nor owns them, but also just reference them.
If a node knows the iterators you have an association from node to iterator with the multiplicity *, else no relation at all.
In iterator you have a simple association to node, the multiplicity can be 0..1 (0 means the iterator was invalidated) or 1 depending on the implementation.
For the question 3 an interface having no implementation it cannot use something else, contrarily to the implementing class(es).


Q: JQUERY AJAX - change class of $(this) in case of success I have a div. Inside that div I have multiple elements. Some elements have the class 'myClass'. I also have a button. When clicked, a foreach loop runs for each element that has the class myClass within the div. An ajaxCall is send for each element. The text color of those elements are black by default. In case of success of the ajax call. I would like to remove the class classBlackFont and add the one classGreenFont. I tried the following code which is unfortunately not switching the classes eventhough the ajax call succeeded.
$("#someDiv .myClass").each(function() {

    var ajaxData = "myAjaxData";
    $.ajax({
        type: "POST",
        url: "somefile.php",
        data: ajaxData,
        success: function(data) {

            $(this).removeClass('classBlackFont').addClass('classGreenFont');
        }
    });

});

A: this is not automatically a reference to the right object in the ajax callback. You can change that by closing over a variable that does have the right value:
$("#someDiv .myClass").each(function() {
    var $this = $(this);
    var ajaxData = "myAjaxData";
    $.ajax({
        type: "POST",
        url: "somefile.php",
        data: ajaxData,
        success: function(data) {
            $this.removeClass('classBlackFont').addClass('classGreenFont');
        }
    });

});

or by using the context option of $.ajax():
$("#someDiv .myClass").each(function() {
    var ajaxData = "myAjaxData";
    $.ajax({
        type: "POST",
        url: "somefile.php",
        data: ajaxData,
        context: this,
        success: function(data) {
            $(this).removeClass('classBlackFont').addClass('classGreenFont');
        }
    });

});

A: context : this
like something
/**
* Default ajax
*/
$.ajaxSetup({
        type: 'post',
        dataType: 'json',
        context: this
});


Q: What tool can I use to view the changes in an in-memory H2 database? I switched to using an in-memory H2 database for development. It works great, but I'm not able to see my changes as I make them.
This is their suggested list of tools: http://h2database.com/html/links.html#tools
I tried DB Visualizer and SQL Developer, but I can't find the tables my software creates. Are there any gotcha's that I should be aware of when working with H2, or any suggestions on a nice tool for Linux.

A: to be independent of the operating system used(Win,Linux(Ubuntu,..),Mac),Execute this command  :
java -cp h2*.jar org.h2.tools.Console

It will open the browser : http://localhost:8082

A: I've generally just used their web interface, found at http://localhost:8082 by default.
Their quickstart guide covers making it available on Windows in great detail, but I recommend simply checking http://localhost:8082 as a first step to see if it's already up and running.


Q: Error when checking model target: expected predictions to have shape (None, 1000) but got array with shape (64, 2) Notebook so far: Notebook
I am trying to reshape the standard Keras VGG16 model to use for the classic cats vs dogs competition (Kaggle Cats vs Dogs)
I had to recreate the pop() and add() functions of the Sequential() Keras model to remove the last Dense(1000) layer and replace it with Dense(2) layer.
However, when I try to use the fit_generator() function, I get the following error:
ValueError: Error when checking model target: expected predictions to have shape (None, 1000) but got array with shape (64, 2)

It sounds like my model is still expecting to output 1000 categories rather than 2. Why is this?
Model summary below:
Layer (type) Output Shape Param # Connected to
input_27 (InputLayer) (None, 224, 224, 3) 0

block1_conv1 (Convolution2D) (None, 224, 224, 64) 1792 input_27[0][0]

block1_conv2 (Convolution2D) (None, 224, 224, 64) 36928 block1_conv1[0][0]

block1_pool (MaxPooling2D) (None, 112, 112, 64) 0 block1_conv2[0][0]

block2_conv1 (Convolution2D) (None, 112, 112, 128) 73856 block1_pool[0][0]

block2_conv2 (Convolution2D) (None, 112, 112, 128) 147584 block2_conv1[0][0]

block2_pool (MaxPooling2D) (None, 56, 56, 128) 0 block2_conv2[0][0]

block3_conv1 (Convolution2D) (None, 56, 56, 256) 295168 block2_pool[0][0]

block3_conv2 (Convolution2D) (None, 56, 56, 256) 590080 block3_conv1[0][0]

block3_conv3 (Convolution2D) (None, 56, 56, 256) 590080 block3_conv2[0][0]

block3_pool (MaxPooling2D) (None, 28, 28, 256) 0 block3_conv3[0][0]

block4_conv1 (Convolution2D) (None, 28, 28, 512) 1180160 block3_pool[0][0]

block4_conv2 (Convolution2D) (None, 28, 28, 512) 2359808 block4_conv1[0][0]

block4_conv3 (Convolution2D) (None, 28, 28, 512) 2359808 block4_conv2[0][0]

block4_pool (MaxPooling2D) (None, 14, 14, 512) 0 block4_conv3[0][0]

block5_conv1 (Convolution2D) (None, 14, 14, 512) 2359808 block4_pool[0][0]

block5_conv2 (Convolution2D) (None, 14, 14, 512) 2359808 block5_conv1[0][0]

block5_conv3 (Convolution2D) (None, 14, 14, 512) 2359808 block5_conv2[0][0]

block5_pool (MaxPooling2D) (None, 7, 7, 512) 0 block5_conv3[0][0]

flatten (Flatten) (None, 25088) 0 block5_pool[0][0]

fc1 (Dense) (None, 4096) 102764544 flatten[0][0]

fc2 (Dense) (None, 4096) 16781312 fc1[0][0]

predictions (Dense) (None, 2) 8194 fc2[0][0]
Total params: 134,268,738
Trainable params: 8,194
Non-trainable params: 134,260,544

The .add() function sets the model.built variable to False, so I am wondering if it's anything to do with that. And if it is, how do I "build" the model? Any help is greatly appreciated.


Q: Database design, wish list and its items I am creating a new database to manage wish lists.
Solution A:
Two tables,

*

*wish_list and

*wish_list_item

Solution B:
One table,

*

*wish_list_with_item
This would have a wish list item per column, so it will be many columns on this table.
Which is better?

A: Solution A is better.  Anytime you try to store collections in columns rather than rows, you're going to run into problems.

A: solution A is normalized and solution B is not.  In most situations solution A will be better and more flexible.  The major time this is not true is if you are making a summary table of some complex join on large tables for use as a source of quick queries for common questions.  Unless you are building a datamart, this is unlikely to be the case.  Go with solution A.

A: I would definitly go with the first solution :

*

*at least, it means you can have as many items you want -- and it'll probably be easier to deal with, on the application side (think about "deleting an item", or "adding an item", for instance)

*the second solution absolutly doesn't feel right

A: The second solution would be better only if you are forced to do a denormalization for the sake of easier caching or if your application grows immensely and you need database sharding. In all other cases I prefer a cleaner design of the database.

A: Multi - table is complicated, so, single table is practical, simple and thus worth considering. Assuming wish list is a feature of a web site, where some users come, create user account, and then list their wishes it might not be completely obvious, but if you think of it, the question needs to be asked, why would you want to have a header table defining wish list(s) instead of having just the second table, listing wishes. In my mind the need for such an approach indicates that each user will ( likely ) want to have more than one wish list. One for close friends and relatives and one for space ship adventure planned for year 2050 :) Otherwise all the wishes could probably be neatly listed in the wish detail ( second ) table, without the first, for one huge wish list ( let's call it default wish list ), without distinction between wishes, be that something you would like for a present, or plan to accomplish while preparing for space ship adventures ( may all your wishes come true! :) ).
Going back to design of tables, here is considerations. If you do not plan to

*

*use wish list for wish list fulfillment

*add any specifics, details for each of the "whishes" separately

than storing list in something like a long string field allows single table.
If you need 2, than adding second table is justified, but still can be avoided by turning "long string" field into XML column with attributes, where you can pair wished item and some additional comments and / or information.
If you need 1, than two table solution is required, so that a relationship can be established between items on the wish list and anything related to this specific item, be that a gift from close friend or relative, which fulfills the wish, or something like catalog of things stored in yet another table.
If you do use multi - table approach than you will need to be careful so that table listing individual wish items didn't have entries without matching header entry defining the list itself. Usually databases use foreign key to enforce such a relationship. So, the "item" table will need to have a field with a key from the parent table.
Summarizing, it is very likely you will have 2 or 3 tables.
Table 1 - listing user accounts
In the simplest case this table will have a field "my wish list" with long string and / or XML column.
Table 2 - enumerating user wish lists with a key noting related user account.
Table 3 - enumerating wish items, with key from either user account ( if user can have only one wish list ) or Table 2 if each user can have multiple distinct wish lists.
Finally, in theory, users can have shared wish lists. For example, Kate and Simon plan to marry in year 2025. They wish to have a wedding ceremony in a cabin on Vashon Island ( the line is long and last time I checked the place is booked 4 years in advance ). In which case a possibility of 4th table comes along. This table will pare together "users" and "wish lists", to enable joined ownership of wish list.
Hope this helps.
-- cheers!


Q: MVC Razor WebGrid Nullable Complex Types I have an entity called Lookup who has a complex Type Description with two string English and French. There has arise a time where no value will be store into the lookup. Now other entities have lookups as properties so we could have foo.Lookup.Description.English for example.
I'm trying to use a Web Grid to display the information being selected.
Originally my controller looked like
    public ViewResult Index()
    {
        var foos = db.Foos;

        return View(foo.ToList());
    }

and my view looked like
@model IEnumerable<Foo>

@{
    ViewBag.Title = "Index";
}

Stay Manager

@{
    var grid = new WebGrid(Model, defaultSort: "sortMe", rowsPerPage: 3);
    grid.GetHtml(htmlAttributes: new { id = "DataTable" });
}

@grid.GetHtml(columns: grid.Columns(
        grid.Column("Lookup.Description.English", "Column Header")
))

My issue is that Lookup can at times be null and ill will get an error saying the the Column Lookup.Description.English does not exist.
I found a solution but not a very elegant one and was hoping that there was a better a way. My solution was to change my controller action to
    public ViewResult Index()
    {
        var foos = db.Foos;

        foreach (Foo currentFoo in Foos.Where(s => s.Lookup == null))
        {
            Foo.Lookup = new Lookup();
            Foo.Lookup.Description.English = "";
            Foo.Lookup.Description.French = "";
        }

        return View(foos.ToList());
    }

Any suggestions on how to get the Web Grid to work better with null-able complex types?

A: Not at all that familair with webgrid, but would the following be a solution for you?
I made the following simple model:
public class Foo
{
    public string Name { get; set; }
    public Lookup Lookup { get; set; }
}

public class Lookup
{
    public string Name { get; set; }
    public Description Description { get; set; }
}

public class Description
{
    public string English { get; set; }
    public string French { get; set; }
}

controller action (i don't have a db, so I mocked some data):
public ViewResult Index()
{
    //var foos = db.Foos;

    var foos = new List<Foo>();

    foos.Add(new Foo { Name = "Foo1" });
    foos.Add(new Foo
    {
        Name = "Foo2",
        Lookup = new Lookup
        {
            Name = "Lookup2",
            Description = new Description
            {
                English = "englishFoo2",
                French = "frenchFoo2"
            }
        }
    });
    foos.Add(new Foo
    {
        Name = "Foo3",
        Lookup = new Lookup
        {
            Name = "Lookup3",
            Description = new Description
            {
                //English = "englishFoo3",
                French = "frenchFoo3"
            }
        }
    });
    foos.Add(new Foo { Name = "Foo4" });
    foos.Add(new Foo
    {
        Name = "Foo5",
        Lookup = new Lookup
        {
            Description = new Description
            {
                English = "englishFoo5",
                French = "frenchFoo5"
            }
        }
    });
    foos.Add(new Foo {
        Name = "Foo6",
        Lookup = new Lookup
        {
            Name = "Lookup6"
        }
    });

    return View(foos);
}

So, I now have Foos with or without Lookups (with or without Description).
The view is as follows:
@model IEnumerable<Foo>

@{
    var grid = new WebGrid(Model, defaultSort: "sortMe", rowsPerPage: 10);
    grid.GetHtml(htmlAttributes: new { id = "DataTable" });
}
@grid.GetHtml(
columns: grid.Columns(
    grid.Column(
        columnName: "Name",
        header: "Foo"
    ),
    grid.Column(
        columnName: "Lookup.Name",
        header: "Lookup",
        format: @@if (item.Lookup != null)
                       { @item.Lookup.Name }

    ),
    grid.Column(
        columnName: "Lookup.Description.English",
        header: "Description.English",
        format: @@if (item.Lookup != null && item.Lookup.Description != null)
                       { @item.Lookup.Description.English }

    ),
    grid.Column(
        columnName: "Lookup.Description.French",
        header: "Description.French",
        format: @@if (item.Lookup != null && item.Lookup.Description != null)
                       { @item.Lookup.Description.French }

    )
)
)

which works just fine for me (Asp.Net MVC 3), it procudes the following html:
[snip]

    Foo4

    Foo5

    englishFoo5
    frenchFoo5

    Foo6
    Lookup6

[/snip]