问:
Canvas toDataURL() returns blank image in Firefox even with .onload and callbacks
I have a problem with toDataURL() function in FireFox

Imagine I have such base64 image:

```<code>var url = " data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMTkgMTE5Ij48Zz48Y2lyY2xlIGN4PSI1NyIgY3k9IjYyIiByPSI1NyIgc3R5bGU9ImZpbGw6IHJnYigxNjAsIDE2MSwgMTYzKTsgb3BhY2l0eTogMC42OyIvPjxjaXJjbGUgY3g9IjU3IiBjeT0iNTciIHI9IjU3IiBzdHlsZT0iZmlsbDogcmdiKDEyMywgMjEwLCAyNDApOyIvPjxjaXJjbGUgY3g9IjU3IiBjeT0iNTciIHI9IjQ1IiBzdHlsZT0iZmlsbDogcmdiKDI1NSwgMjU1LCAyNTUpOyIvPjx0ZXh0IGR4PSI1NyIgZHk9IjY1IiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBzdHlsZT0iZm9udC1zaXplOjI1cHg7IGZpbGw6ICMyYjJmMmU7IGZvbnQtZmFtaWx5OiAnRElOUHJvIFJlZ3VsYXInLCBzYW5zLXNlcmlmOyBmb250LXdlaWdodDogYm9sZCI+MTUlPC90ZXh0PjwvZz48L3N2Zz4=";
</code>```

And then I want to resize it and send new uri back:

```<code>function getImageUri(url, callback) {
  image = new Image();

  image.onload = function() {
    var image = this;
    var canvas = document.createElement('canvas'),
        context = canvas.getContext('2d'),
        dataURL;

    context.drawImage(image, 0, 0, 60, 60);
    callback(canvas.toDataURL());
  }

  image.src = url;

}
</code>```

At the end I just call it to get new uri

```<code>getImageUri(url, function (uri) {
    console.log(uri);
    document.getElementById('circle').innerHTML = "<img src=" + uri + ">";
});
</code>```

Here is the codepen of this example. It works in Chrome, but not in FireFox.

I've searched a lot for similar questions here and most of time the reason was use of image without waiting for its loading, but I have this .onload thing, right?

And also I've tried to make same actions as in this question, but FF is still showing just transparent image. Please help!

答:
There’s a bug open in Firefox about this: drawImage() fails silently when drawing an SVG image without @width or @height.

You can fix it by adding (go figure) width and height to the SVG:

```<code><svg
    xmlns="http://www.w3.org/2000/svg"
    width="119" height="119" viewBox="0 0 119 119">
    …
</code>```

Updated Codepen

Body:
I have a problem with toDataURL() function in FireFox

Imagine I have such base64 image:

var url = " data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMTkgMTE5Ij48Zz48Y2lyY2xlIGN4PSI1NyIgY3k9IjYyIiByPSI1NyIgc3R5bGU9ImZpbGw6IHJnYigxNjAsIDE2MSwgMTYzKTsgb3BhY2l0eTogMC42OyIvPjxjaXJjbGUgY3g9IjU3IiBjeT0iNTciIHI9IjU3IiBzdHlsZT0iZmlsbDogcmdiKDEyMywgMjEwLCAyNDApOyIvPjxjaXJjbGUgY3g9IjU3IiBjeT0iNTciIHI9IjQ1IiBzdHlsZT0iZmlsbDogcmdiKDI1NSwgMjU1LCAyNTUpOyIvPjx0ZXh0IGR4PSI1NyIgZHk9IjY1IiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBzdHlsZT0iZm9udC1zaXplOjI1cHg7IGZpbGw6ICMyYjJmMmU7IGZvbnQtZmFtaWx5OiAnRElOUHJvIFJlZ3VsYXInLCBzYW5zLXNlcmlmOyBmb250LXdlaWdodDogYm9sZCI+MTUlPC90ZXh0PjwvZz48L3N2Zz4=";

And then I want to resize it and send new uri back:

function getImageUri(url, callback) {
  image = new Image();

  image.onload = function() {
    var image = this;
    var canvas = document.createElement('canvas'),
        context = canvas.getContext('2d'),
        dataURL;

    context.drawImage(image, 0, 0, 60, 60);
    callback(canvas.toDataURL());
  }

  image.src = url;

}

At the end I just call it to get new uri

getImageUri(url, function (uri) {
    console.log(uri);
    document.getElementById('circle').innerHTML = "";
});

Here is the codepen of this example. It works in Chrome, but not in FireFox.

I've searched a lot for similar questions here and most of time the reason was use of image without waiting for its loading, but I have this .onload thing, right?

And also I've tried to make same actions as in this question, but FF is still showing just transparent image. Please help!

Body:
There’s a bug open in Firefox about this: drawImage() fails silently when drawing an SVG image without @width or @height.

You can fix it by adding (go figure) width and height to the SVG:

<svg
    xmlns="http://www.w3.org/2000/svg"
    width="119" height="119" viewBox="0 0 119 119">
    …

Updated Codepen


来源: stackexchange

问:
A strange problem with WPF Window.Icon
I'm going to set Window.Icon property by using ResourceDictionary like below:

```<code><Style TargetType="{x:Type Window}">
    <Setter Property="Icon" Value="/WpfApplication1;component/Resources/Icon.ico" />
</Style>
</code>```

Above Style wasn't change Icon of Window. However when i set Icon of Window directly, It is done correctly!

```<code><Window Icon="/WpfApplication1;component/Resources/Icon.ico">
    //Content
</Window>
</code>```

Note: Build Action of Icon.ico was set to Resource and ResourceDictionary also loaded.

答:
The problem is that your style is not applied at all. You'll have to define your style in app.xaml, assign a key to it and set your windows style explicitly.

EDIT:

Goblin suggested another valuable solution, excerpt from his comment:

he could set the TargetType="{local:MainWindow}" where local is the namespace for WPFApplication1. The problem is that 'empty key'-application works only for the specified type - not descendants.

ContentLicense: CC BY-SA 2.5

Title: A strange problem with WPF Window.Icon

Body:
I'm going to set Window.Icon property by using ResourceDictionary like below:

Above Style wasn't change Icon of Window. However when i set Icon of Window directly, It is done correctly!

<Window Icon="/WpfApplication1;component/Resources/Icon.ico">
    //Content
</Window>

Note: Build Action of Icon.ico was set to Resource and ResourceDictionary also loaded.


问:
Android - Prevent white screen at startup
As we all know, many Android apps display a white screen very briefly before their first Activity comes into focus. This problem is observed in the following cases:

Android apps that extend the global Application class and
perform major initializations therein. The Application
object is always created before the first Activity (a fact that can
be observed in the debugger), so this makes sense. This is the cause of the delay in my case.

Android apps that display the default preview window before the splash screen.

Setting android:windowDisablePreview = "true" obviously does not work here. Nor can I set the parent theme of the splash screen to Theme.Holo.NoActionBar as described here, because [unfortunately] my splash screen makes use of an ActionBar.

Meanwhile, apps that do not extend the Application class do not show the white screen at startup.

The thing is, ideally the initializations performed in the Application object need to occur before the first Activity is shown. So my question is, how can I perform these initializations on app startup without using an Application object? Possibly using a Thread or Service, I suppose?

This is an interesting problem to think about. I can't bypass it the usual way (by setting the NoActionBar theme), as tragically my Splash screen actually has an ActionBar due to some unrelated reasons.

Note:

I have already referred to the following questions:

How To fix white screen on app Start
up?

Android splash screen is white in the
beginning?

White screen before
splashscreen

White background when Android app start up

Why there is a white screen appears for 1sec when starting to run the apps in Android?

References:

Patterns – Launch screens.

Branded launch screen: the new splash for Android.

Splash Screens the Right Way.

答:
Just write the item in values/styles.xml:

```<code><item name="android:windowBackground">@android:color/black</item>
</code>```

For example, in the AppTheme:

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="windowNoTitle">true</item>
    <item name="windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>

    <item name="android:windowBackground">@android:color/black</item>

    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Just write the item in values/styles.xml:

<item name="android:windowBackground">@android:color/black</item>

For example, in the AppTheme:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="windowNoTitle">true</item>
    <item name="windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>

    <item name="android:windowBackground">@android:color/black</item>

    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>


问:
Use trigger to determine to implement insert or not
I am a beginner of SQL and Oracle database, and I need a little help about trigger. Here is the question:

I need to create a trigger that before insert a row into table Room, it will check this new row's hotel_id to see if it exists in another table Hotel. If the new hotel_id exists, then do the insert; if not, cancel this insert.

My code:

```<code>CREATE OR REPLACE TRIGGER TRIGGER1
BEFORE INSERT ON ROOM
FOR EACH ROW
BEGIN
  if (:new.hotel_id in (select hotel_id from hotel)) then
    --execute the insert;
    else
      --cancel the insert;
  end if;
END;
</code>```

I'm not sure that SQL has syntax that can be used to continue or cancel an operation. If there is, please teach me or attach the link related to it.

答:
As GurV said, foreign keys are more appropriate way for doing this

Though, here is trigger way:

```<code>CREATE OR REPLACE TRIGGER TRIGGER1
BEFORE INSERT ON ROOM
FOR EACH ROW
declare myvar INT;
BEGIN
    SELECT 1 INTO myvar FROM Hotel WHERE hotel_id = :NEW.hotel_id FETCH NEXT 1 ROW ONLY;
    exception
    when no_data_found then
       RAISE_APPLICATION_ERROR (-20000, 'some_error_message');
END;
</code>```

Body:
I am a beginner of SQL and Oracle database, and I need a little help about trigger. Here is the question:

I need to create a trigger that before insert a row into table Room, it will check this new row's hotel_id to see if it exists in another table Hotel. If the new hotel_id exists, then do the insert; if not, cancel this insert.

My code:

CREATE OR REPLACE TRIGGER TRIGGER1
BEFORE INSERT ON ROOM
FOR EACH ROW
BEGIN
  if (:new.hotel_id in (select hotel_id from hotel)) then
    --execute the insert;
    else
      --cancel the insert;
  end if;
END;

I'm not sure that SQL has syntax that can be used to continue or cancel an operation. If there is, please teach me or attach the link related to it.

Body:
As GurV said, foreign keys are more appropriate way for doing this

Though, here is trigger way:

CREATE OR REPLACE TRIGGER TRIGGER1
BEFORE INSERT ON ROOM
FOR EACH ROW
declare myvar INT;
BEGIN
    SELECT 1 INTO myvar FROM Hotel WHERE hotel_id = :NEW.hotel_id FETCH NEXT 1 ROW ONLY;
    exception
    when no_data_found then
       RAISE_APPLICATION_ERROR (-20000, 'some_error_message');
END;


问:
Wait on all promises in a simulate call
I am using Jest and Enzyme to test React components.

My React component (under test) has a remote select component. When the user types some text, data is fetched from API and the options are displayed.

```<code>test('should fetch data', () => {
  // mock the API call
  const store = require('../../src/store').default;
  store.fetchData = jest.fn(() => Promise.resolve([{
    id: 1,
    name: 'someText
  }]));

  // test
  const wrapper = shallow(<Form />);
  const remote = wrapper.find('RemoteSelect').first();
  remote.simulate('fetch', 'someText');
  expect(store.fetchData).toBeCalled();

  // more test
  remote.simulate('change', 1);
  const remoteRequeried = wrapper.find('RemoteSelect').first();
  expect(remoteRequeried.prop('label')).toBe('someText');
});
</code>```

The first test fetches data from the store when user types some text. The second test selects an option. The second test fails.

It is a difficult to explain this is an SO question. The options are set in the "then" part of the Promise. "Then" function is not getting executed before the second simulate. So, the options are not set when the second simulate is fired.

If I move the second test within a setTimeout(), the second test passes.

Is there anyway for Jest to ensure the "then" of the promise gets executed before performing more tests?

答:
You could do something like this:</p>

```<code>test('should fetch data', () => {
  // mock the API call
  const store = require('../../src/store').default;
  let promise;
  store.fetchData = jest.fn(() => {
    promise = Promise.resolve([{
      id: 1,
      name: 'someText',
    }]);
    return promise;
  );

  // test
  const wrapper = shallow(<Form />);
  const remote = wrapper.find('RemoteSelect').first();
  remote.simulate('fetch', 'someText');
  expect(store.fetchData).toBeCalled();

  return promise.then((result) => {
    // more test
    remote.simulate('change', 1);
    const remoteRequeried = wrapper.find('RemoteSelect').first();
    expect(remoteRequeried.prop('label')).toBe('someText');
  });
});
</code>```

Title: Wait on all promises in a simulate call

Body:
I am using Jest and Enzyme to test React components.

My React component (under test) has a remote select component. When the user types some text, data is fetched from API and the options are displayed.

test('should fetch data', () => {
  // mock the API call
  const store = require('../../src/store').default;
  store.fetchData = jest.fn(() => Promise.resolve([{
    id: 1,
    name: 'someText
  }]));

  // test
  const wrapper = shallow(<Form />);
  const remote = wrapper.find('RemoteSelect').first();
  remote.simulate('fetch', 'someText');
  expect(store.fetchData).toBeCalled();

  // more test
  remote.simulate('change', 1);
  const remoteRequeried = wrapper.find('RemoteSelect').first();
  expect(remoteRequeried.prop('label')).toBe('someText');
});

The first test fetches data from the store when user types some text. The second test selects an option. The second test fails.

It is a difficult to explain this is an SO question. The options are set in the "then" part of the Promise. "Then" function is not getting executed before the second simulate. So, the options are not set when the second simulate is fired.

If I move the second test within a setTimeout(), the second test passes.

Is there anyway for Jest to ensure the "then" of the promise gets executed before performing more tests?

Body:
You could do something like this:

test('should fetch data', () => {
  // mock the API call
  const store = require('../../src/store').default;
  let promise;
  store.fetchData = jest.fn(() => {
    promise = Promise.resolve([{
      id: 1,
      name: 'someText',
    }]);
    return promise;
  );

  // test
  const wrapper = shallow(<Form />);
  const remote = wrapper.find('RemoteSelect').first();
  remote.simulate('fetch', 'someText');
  expect(store.fetchData).toBeCalled();

  return promise.then((result) => {
    // more test
    remote.simulate('change', 1);
    const remoteRequeried = wrapper.find('RemoteSelect').first();
    expect(remoteRequeried.prop('label')).toBe('someText');
  });
});


问:
Menu Items are not showing on Action Bar
I have made a completely new project. I have added items to the menu layout file. Those items do not show up on the action bar's right side. I remember that an icon with three dots shows up which opens up the menu.

Here is my Activity

```<code>public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getActionBar();
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLUE));
        actionBar.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}
</code>```

And here is my main.xml

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_option1"/>
    <item
        android:id="@+id/action_settings34"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_option2"/>
    <item
        android:id="@+id/action_settings3"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_option3"/>

</menu>
</code>```

答:
Add

```<code>Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
</code>```

in the onCreate method.

Body:
I have made a completely new project. I have added items to the menu layout file. Those items do not show up on the action bar's right side. I remember that an icon with three dots shows up which opens up the menu.

Here is my Activity

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getActionBar();
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLUE));
        actionBar.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

And here is my main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_option1"/>
    <item
        android:id="@+id/action_settings34"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_option2"/>
    <item
        android:id="@+id/action_settings3"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_option3"/>

</menu>

Body:
Add

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

in the onCreate method.


问:
Clojure insta/parser 1.4.5, problems with ]
I have the following grammar:

```<code>LIST = LBRACE LISTBODY RBRACE
LISTBODY = ATOM | ATOM COMMA LISTBODY
ATOM = NUMBER | WORD
NUMBER = INTEGER
INTEGER = #'[-|+]{0,1}[ ]*(\\d)+'
WORD = #'[a-z]([a-zA-z0-9_])*'
LBRACE = '['
RBRACE = ']'
COMMA = ','
</code>```

Trying to parse [a,b] fails. If I replace RBRACE=']' with RBRACE='}' I can then parse [a,b}

Is there something special about the ] that I am missing?

答:
What you have as LBRACE and RBRACE are fine.

I wonder that what is happening is not what you may think is happening i.e. multiple rules are working against each other. You can often tell by the error that is in the form [:index n], where n is how far the parsing got.

INTEGER is a regex that has [ and ] in it, with a space between. Could you take them and the space and the * away and see how you go? I know they should be escaped in regex, but still I would try experiments along those lines.

Body:
I have the following grammar:

LIST = LBRACE LISTBODY RBRACE
LISTBODY = ATOM | ATOM COMMA LISTBODY
ATOM = NUMBER | WORD
NUMBER = INTEGER
INTEGER = #'[-|+]{0,1}[ ]*(\\d)+'
WORD = #'[a-z]([a-zA-z0-9_])*'
LBRACE = '['
RBRACE = ']'
COMMA = ','

Trying to parse [a,b] fails. If I replace RBRACE=']' with RBRACE='}' I can then parse [a,b}

Is there something special about the ] that I am missing?


问:
How to draw groups of bar plots, grouped by year?
I want to graph data that looks like this:

```<code>## Source: local data frame [6 x 3]
## Groups: year [?]
##
##    year            helpnot count
##   <int>             <fctr> <int>
## 1  1975       Govt Do More   371
## 2  1975    Agree With Both   433
## 3  1975 Govt Does Too Much   245
## 4  2012       Govt Do More   199
## 5  2012    Agree With Both   530
## 6  2012 Govt Does Too Much   242
</code>```

And I want the x axis to be helpnot, and I want the why to be the actual number of count. I want the X axis split into two groups. How do I do this? I have this which is close... but year is split on top of each bar and in groups by year. How do I fix this?

This is what I have:

```<code>ggplot(data = helpnotComparison, aes(x=helpnot, y=count, fill = year)) +
   geom_bar(stat='identity')
</code>```

That produces me this:

UPDATE

This comes close:

```<code>ggplot(data = helpnotComparison, aes(x=helpnot, y=count, group=year, fill=year)) +
+   geom_bar(position='dodge', stat="identity")
</code>```

produces me this:

But how do I get the year labels at the bottom? and why is the scale on the right showing 4 years when I only have 2?

答:
Start with

```<code>data$year <- as.factor(data$year)
</code>```

The reason you have 4 year is because it is interpreted as continuous.

Is this what you are looking for?

```<code>data <- data.frame(Year = c(rep("1975",3), rep("2010",3)),
                   helpnot = c("GDB","AWB", "GDT", "GDB", "AWB", "GDT"),
                               count = c(370, 430, 250, 200, 530, 250))
data

ggplot(data, aes(x  = helpnot, y = count, fill = Year)) +
  geom_bar(stat = "identity", position = "dodge") + theme_minimal() +
  annotate("text", c(0.75,1.25,1.75,2.25,2.75,3.25), y = -15,
           label = rep(c("1975","2010"),3), size = 2) +
guides(fill=FALSE)
</code>```

Body:
I want to graph data that looks like this:

## Source: local data frame [6 x 3]
## Groups: year [?]
##
##    year            helpnot count
##   <int>             <fctr> <int>
## 1  1975       Govt Do More   371
## 2  1975    Agree With Both   433
## 3  1975 Govt Does Too Much   245
## 4  2012       Govt Do More   199
## 5  2012    Agree With Both   530
## 6  2012 Govt Does Too Much   242

And I want the x axis to be helpnot, and I want the why to be the actual number of count. I want the X axis split into two groups. How do I do this? I have this which is close... but year is split on top of each bar and in groups by year. How do I fix this?

This is what I have:

ggplot(data = helpnotComparison, aes(x=helpnot, y=count, fill = year)) +
   geom_bar(stat='identity')

That produces me this:

UPDATE

This comes close:

ggplot(data = helpnotComparison, aes(x=helpnot, y=count, group=year, fill=year)) +
+   geom_bar(position='dodge', stat="identity")

produces me this:

But how do I get the year labels at the bottom? and why is the scale on the right showing 4 years when I only have 2?

Body:
Start with

data$year <- as.factor(data$year)

The reason you have 4 year is because it is interpreted as continuous.

Is this what you are looking for?

data <- data.frame(Year = c(rep("1975",3), rep("2010",3)),
                   helpnot = c("GDB","AWB", "GDT", "GDB", "AWB", "GDT"),
                               count = c(370, 430, 250, 200, 530, 250))
data

ggplot(data, aes(x  = helpnot, y = count, fill = Year)) +
  geom_bar(stat = "identity", position = "dodge") + theme_minimal() +
  annotate("text", c(0.75,1.25,1.75,2.25,2.75,3.25), y = -15,
           label = rep(c("1975","2010"),3), size = 2) +
guides(fill=FALSE)


问:
HTML connection to MySQL
I want to create a login script on HTML page. I read that I need to use an intermediate script so that I can let my HTML use the database. So, I`ve written a PHP page that checks the username/password regarding the database.

I also read that I should use AJAX to connect to the database.

I would like to know how to write the AJAX code to return the value of the login either true or false.

答:
Although it's not necessary to use AJAX for this, you can use something like below.

Considering you have an element that has a username and password like below:

```<code><div id="login">
  <label for="txtUsername">Username:</label>
  <input type="text" id="txtUsername" />
  <label for="txtPassword">Password:</label>
  <input type="password" id="txtPassword" />
  <button id="btnLogin">Log In</buton>
</div>
<div id="logout" style="display: none;">
   <a href="logout.php">Log Out</a>
</div>
</code>```

Then, having jQuery already referenced call your PHP page ("login.php" in the example):

```<code><script type="text/javascript">
$(function() {
  $("#btnLogin").click(function() {
    $.ajax({
      url: "login.php",
      data: {username: $("#txtUsername").val(), password: $("#txtPassword").val()},
      success: function(data){
        $("#login").toggle();
        $("#logout").toggle();
      }
    });
  });
});
</script>
</code>```

Title: HTML connection to MySQL

Body:
Although it's not necessary to use AJAX for this, you can use something like below.

Considering you have an element that has a username and password like below:

<div id="login">
  <label for="txtUsername">Username:</label>
  <input type="text" id="txtUsername" />
  <label for="txtPassword">Password:</label>
  <input type="password" id="txtPassword" />
  <button id="btnLogin">Log In</buton>
</div>
<div id="logout" style="display: none;">
   <a href="logout.php">Log Out</a>
</div>

Then, having jQuery already referenced call your PHP page ("login.php" in the example):

<script type="text/javascript">
$(function() {
  $("#btnLogin").click(function() {
    $.ajax({
      url: "login.php",
      data: {username: $("#txtUsername").val(), password: $("#txtPassword").val()},
      success: function(data){
        $("#login").toggle();
        $("#logout").toggle();
      }
    });
  });
});
</script>


问:
jQuery oddity in Wordpress
I'm getting started with Wordpress and trying to use jQuery as my JavaScript library of choice. I've got it loading with wp_enqueue_script but for some reason when the page actually loads the $ function it does so with it behaving like it does in Prototype (single dollar sign is "get by Id" and $$ is the CSS selector system).

I'm very confused as to why because I cannot find anywhere in the response from the server where the instruction to load Prototype is coming from; there is no

Title: jQuery oddity in Wordpress

Body:
Some things I might try in order to debug this:

Save Page As -> Web page, complete. Search the resulting directory for "Prototype".

Then start tinkering with your saved copy of the page. You could insert <script> tags at various points in the head of the document, trying to figure out at what point $ is set, or at what point its behavior changes.

Or, in Firefox, use this.watch("$", function () { alert(Error().stack); }) to see where it is set.


问:
Enable Button Clickable after writing certain text in textview android
I am trying to build a Sign in method in which one person has to write its Email Address of the particular domain
e.g rob@playground.football.in

Now my intention my codes should check the domain i.e playground.football.in then if it matches then only the button which is for signing in(which is disable/unclickable before writing the particular domain) should be enabled now.

I have done half of the work.for getting the domain shown below

```<code>email = (EditText) findViewById(R.id.email); verify = (Button) findViewById(R.id.button); verify.setEnabled(false); String getEmail = email.getText().toString();
String x = getEmail.substring(getEmail.lastIndexOf('@') + 1);
if (x.equals(domain)) {
verify.setEnabled(true);
}
</code>```

答:
Add TextChangedListener to your email EditText using email.addTextChangedListener() and put your checking inside onTextChanged().

Here is the working code. Update your code as below:

```<code>    ..................
    .........................
    EditText email = (EditText) findViewById(R.id.email);
    Button verify = (Button) findViewById(R.id.button);
    verify.setEnabled(false);

    email.addTextChangedListener(new 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) {

            String getEmail = email.getText().toString();
            String x = getEmail.substring(getEmail.lastIndexOf('@') + 1);

            if (x.equals(domain)) {
                verify.setEnabled(true);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }

    });
    ..............
    .....................
</code>```

Hope this will help~

Body:
I am trying to build a Sign in method in which one person has to write its Email Address of the particular domain
e.g rob@playground.football.in

Now my intention my codes should check the domain i.e playground.football.in then if it matches then only the button which is for signing in(which is disable/unclickable before writing the particular domain) should be enabled now.

I have done half of the work.for getting the domain shown below

email = (EditText) findViewById(R.id.email); verify = (Button) findViewById(R.id.button); verify.setEnabled(false); String getEmail = email.getText().toString();
String x = getEmail.substring(getEmail.lastIndexOf('@') + 1);
if (x.equals(domain)) {
verify.setEnabled(true);
}

Body:
Add TextChangedListener to your email EditText using email.addTextChangedListener() and put your checking inside onTextChanged().

Here is the working code. Update your code as below:

    ..................
    .........................
    EditText email = (EditText) findViewById(R.id.email);
    Button verify = (Button) findViewById(R.id.button);
    verify.setEnabled(false);

    email.addTextChangedListener(new 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) {

            String getEmail = email.getText().toString();
            String x = getEmail.substring(getEmail.lastIndexOf('@') + 1);

            if (x.equals(domain)) {
                verify.setEnabled(true);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }

    });
    ..............
    .....................

Hope this will help~


问:
CSS: How to make a background-image appear within a div without setting a fixed height
I have made the following layout:

html,
body {
  height: 100%;
}

.header {
  height: 120px;
  width: 100%;
  background-image: url(http://lorempixel.com/500/120/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet" />
<div class="row">
  <div class="columns small-12 header"></div>
</div></code>```

It works because I have used a height-property with a fixed pixel-value.

If one removes that the image disappears:

html,
body {
  height: 100%;
}

.header {
  width: 100%;
  background-image: url(http://lorempixel.com/500/120/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet" />
<div class="row">
  <div class="columns small-12 header"></div>
</div></code>```

One of the problems with using that fixed height is that responsiveness can't be accomplished.

How can I make the background appear without having to use a fixed height?
Or should I fall back to using img-tag instead?

There the height is determined by the image-sizes itself.

答:
You can use viewport height to make div responsive, in below example 40vh is 40% of viewport height.

html,
body {
  height: 100%;
}

.header {
  height: 40vh;
  width: 100%;
  background-image: url(http://lorempixel.com/500/120/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet" />
<div class="row">
  <div class="columns small-12 header"></div>
</div></code>```

Body:
I have made the following layout:

html,
body {
  height: 100%;
}

.header {
  height: 120px;
  width: 100%;
  background-image: url(http://lorempixel.com/500/120/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet" />

It works because I have used a height-property with a fixed pixel-value.

If one removes that the image disappears:

html,
body {
  height: 100%;
}

.header {
  width: 100%;
  background-image: url(http://lorempixel.com/500/120/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet" />

One of the problems with using that fixed height is that responsiveness can't be accomplished.

How can I make the background appear without having to use a fixed height?
Or should I fall back to using img-tag instead?

There the height is determined by the image-sizes itself.

Body:
You can use viewport height to make div responsive, in below example 40vh is 40% of viewport height.

html,
body {
  height: 100%;
}

.header {
  height: 40vh;
  width: 100%;
  background-image: url(http://lorempixel.com/500/120/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css" rel="stylesheet" />
<div class="row">
  <div class="columns small-12 header"></div>
</div>


问:
DataGridComboBoxColumn Values Different For each Row
I am trying to populate a datagridview combobox column with comboboxcells in    winforms where each row has a different collection derived from the nested list within the dictionary, the dictionary works fine when i iterate over it and get its objects and their string values, however every different combination i have exhausted to populate the combobox cells on form load has failed. Is it possible? I have found other posts where they use cellclick events etc. I prefer to populate on form initialization.</p>

```<code>//this works
public void create datatable()
{
    DataGridViewComboBoxColumn Data_CmBx_Col_ObjectType = new  DataGridViewComboBoxColumn();
    Data_CmBx_Col_FamilyType.Name = _ADD_OBJECT_TYPE;
    Data_CmBx_Col_FamilyType.HeaderText = _ADD_OBJECT_TYPE;
    dataGridView.Columns.Insert(6, Data_CmBx_Col_ObjectType);

    //pop combobox, the dictionary works
    int i = 0;
    foreach (KeyValuePair<object, List<objectType>> objectAndType in combined_Dictionary)
    {
        i++;
        if (rowIndex <= combined_Dictionary.Count)
        {
            CreateCustomComboBoxDataSouce(i, objectAndType.Value);
        }
    }

    //Bind dataGridView to a datatable
    dataGridView_Family.DataSource = data;
}//end method

//method is called and fails with index out of range error collection
private void CreateCustomComboBoxDataSouce(int row, List<objectAndType> type) //row index ,and two parameters
{
    DataGridViewComboBoxCell comboCell = dataGridView_objectAndType[6, row] as DataGridViewComboBoxCell;
    comboCell.DataSource = new BindingSource(type, null);
}//end method
</code>```

答:
The index is zero based, so it must be strictly less than its count

```<code>if (rowIndex < combined_Dictionary.Count) // not <= but without =
</code>```

Body:
I am trying to populate a datagridview combobox column with comboboxcells in    winforms where each row has a different collection derived from the nested list within the dictionary, the dictionary works fine when i iterate over it and get its objects and their string values, however every different combination i have exhausted to populate the combobox cells on form load has failed. Is it possible? I have found other posts where they use cellclick events etc. I prefer to populate on form initialization.

//this works
public void create datatable()
{
    DataGridViewComboBoxColumn Data_CmBx_Col_ObjectType = new  DataGridViewComboBoxColumn();
    Data_CmBx_Col_FamilyType.Name = _ADD_OBJECT_TYPE;
    Data_CmBx_Col_FamilyType.HeaderText = _ADD_OBJECT_TYPE;
    dataGridView.Columns.Insert(6, Data_CmBx_Col_ObjectType);

    //pop combobox, the dictionary works
    int i = 0;
    foreach (KeyValuePair<object, List<objectType>> objectAndType in combined_Dictionary)
    {
        i++;
        if (rowIndex <= combined_Dictionary.Count)
        {
            CreateCustomComboBoxDataSouce(i, objectAndType.Value);
        }
    }

    //Bind dataGridView to a datatable
    dataGridView_Family.DataSource = data;
}//end method

//method is called and fails with index out of range error collection
private void CreateCustomComboBoxDataSouce(int row, List<objectAndType> type) //row index ,and two parameters
{
    DataGridViewComboBoxCell comboCell = dataGridView_objectAndType[6, row] as DataGridViewComboBoxCell;
    comboCell.DataSource = new BindingSource(type, null);
}//end method

Body:
The index is zero based, so it must be strictly less than its count

if (rowIndex < combined_Dictionary.Count) // not <= but without =


问:
Underscore.js - Check if Object Array contains value
I have the following Object and I want to check if Type.ID contains value 6508 :

```<code> {
   "item": {
      "Feature": [
         {
            "ID": 85408,
            "Status": {
                "ID": 65,
             },
             "Type": {
                 "ID": 6508,
                  "Volume": null
              },
              "Manufacturer": null
          },
          {
             "ID": 85409,
             "Status": {
                 "ID": 65,
              },
              "Type": {
                  "ID": 6509,
                   "Volume": null
              },
              "Manufacturer": null
          }
       ],
       "Errors": {
           "Result": 0,
           "Message": ""
        },
       "RecordCount": 2
      }
 }
</code>```

I can muster the following:

```<code>for (i = 0; i < data.item.Feature.length; i++) {
     if (data.item.Feature[i].Type.ID == 6508)
        return true;
}
return false;
</code>```

How can I use underscore.js to do the same? The following doesn't work?

```<code>_.contains(data.item.Feature.Type.ID, 6508)
</code>```

答:
Using @FakeRainBrigand JS code I've manged to achieve the same using underscore by doing the following:</p>

```<code>_.some(data.item.Feature, function(f) {
       return f.Type.ID == 6508;
 })
</code>```

Body:
I have the following Object and I want to check if Type.ID contains value 6508 :

 {
   "item": {
      "Feature": [
         {
            "ID": 85408,
            "Status": {
                "ID": 65,
             },
             "Type": {
                 "ID": 6508,
                  "Volume": null
              },
              "Manufacturer": null
          },
          {
             "ID": 85409,
             "Status": {
                 "ID": 65,
              },
              "Type": {
                  "ID": 6509,
                   "Volume": null
              },
              "Manufacturer": null
          }
       ],
       "Errors": {
           "Result": 0,
           "Message": ""
        },
       "RecordCount": 2
      }
 }

I can muster the following:

for (i = 0; i < data.item.Feature.length; i++) {
     if (data.item.Feature[i].Type.ID == 6508)
        return true;
}
return false;

How can I use underscore.js to do the same? The following doesn't work?

_.contains(data.item.Feature.Type.ID, 6508)

Body:
Using @FakeRainBrigand JS code I've manged to achieve the same using underscore by doing the following:

_.some(data.item.Feature, function(f) {
       return f.Type.ID == 6508;
 })


问:
NHibernate: Why would you use <composite-element> over <one-to-many> to map a collection
When using NHibernate, under what circumstances would you choose to map a collection using a composite-element to give a collection of value objects, rather than creating a full-blown entity and mapping it using one-to-many?

You might have a value-type class 'PostalAddress' to represent an address. If you had a person entity and each person could have many addresses you could map this relationship like this (Option 1):

```<code><bag name="Addresses" table="PersonAddress">
    <key column="PersonID"/>
    <composite-element class="PostalAddress">
        <property name="StreetAddress"/>
        <property name="Town"/>
        <property name="City"/>
        <property name="Postcode"/>
    </composite-element>
</bag>
</code>```

Or you could create an entity 'PersonAddress' which has a 'PostalAddress' typed property on it and map the addresses with a one-to-many association (Option 2):

```<code><bag name="Addresses">
    <key column="PersonID"/>
    <one-to-many class="PersonAddress"/>
</bag>

<class name="PersonAddress">

    <id name="Id">
        <generator class="native"/>
    </id>

    <component name="Address" class="PostalAddress">
        <property name="StreetAddress"/>
        <property name="Town"/>
        <property name="City"/>
        <property name="Postcode"/>
    </component>

</class>
</code>```

Are there any reasons not to do option 1? Does the fact that the PersonAddress table has an ID column suggest that it should be an entity itself, hence use option 2?

答:
<composite-element> is for when you have a collection of values whereas <one-to-many> is a collection of entities. The defining characteristic of an entity is a unique identifier. So if the items in your collection have a PK, use <one-to-many>. Otherwise use <composite-element>.

Another way to think about it is how you determine equality. Do you determine equality by comparing an ID or by verifying that all properties are identical? e.g. In your application, do two objects represent the same address if (address1.Id == address2.Id) or if (address1.Street == address2.Street && address1.City == address2.City && etc.)? There is no universal right answer as it depends on application context. In many cases, money is a value object. Whether you have this $20 or that $20, it doesn't matter. Only the amount is relevant. If you were writing a tracking application for a mint, they probably need to know which $20 bill you're dealing with and you would track the serial number on the $20 bill. In this case, money is an entity. It all depends on application and context...

Body:
When using NHibernate, under what circumstances would you choose to map a collection using a composite-element to give a collection of value objects, rather than creating a full-blown entity and mapping it using one-to-many?

You might have a value-type class 'PostalAddress' to represent an address. If you had a person entity and each person could have many addresses you could map this relationship like this (Option 1):

<bag name="Addresses" table="PersonAddress">
    <key column="PersonID"/>
    <composite-element class="PostalAddress">
        <property name="StreetAddress"/>
        <property name="Town"/>
        <property name="City"/>
        <property name="Postcode"/>
    </composite-element>
</bag>

Or you could create an entity 'PersonAddress' which has a 'PostalAddress' typed property on it and map the addresses with a one-to-many association (Option 2):

<bag name="Addresses">
    <key column="PersonID"/>
    <one-to-many class="PersonAddress"/>
</bag>

<class name="PersonAddress">

    <id name="Id">
        <generator class="native"/>
    </id>

    <component name="Address" class="PostalAddress">
        <property name="StreetAddress"/>
        <property name="Town"/>
        <property name="City"/>
        <property name="Postcode"/>
    </component>

</class>

Are there any reasons not to do option 1? Does the fact that the PersonAddress table has an ID column suggest that it should be an entity itself, hence use option 2?


问:
Compare the column values and update another column in Oracle
I have a scenario where we have first two entries for each test. Meaning for each test we have two entries, now I want to compare the test ranks and update the LoginID column in my table.

Sample data:

```<code>RANK | TestID | LoginID
-----+--------+---------
234     14       null
235     14       null
330     15       null
331     15       null
223     18       null
222     18       null
500     20       null
501     20       null
</code>```

In the above table, I have two entries for each testId, now I need to compare the RANK column of the corresponding TESTID rows, and update the LoginId column with 1 and 2.

Finally I am looking for output like follows:

```<code>RANK | TestID | LoginID
-----+--------+---------
234     14       1
235     14       2
330     15       1
331     15       2
223     18       2
222     18       1
500     20       1
501     20       2
</code>```

Can anyone suggest which is better way to achieve this? I tried with min() and max(), with Case (When /then) concept, but the query is not returning the expected results.

答:
You can use MERGE with window function row_number:

```<code>merge into your_table t
using (
    select t.*,
        row_number() over (partition by testId order by rank) as rn
    from your_table t
) s on (
    t.rank = s.rank
    and t.testId = s.testId
    )
when matched then update set t.loginId = s.rn;
</code>```

Body:
I have a scenario where we have first two entries for each test. Meaning for each test we have two entries, now I want to compare the test ranks and update the LoginID column in my table.

Sample data:

RANK | TestID | LoginID
-----+--------+---------
234     14       null
235     14       null
330     15       null
331     15       null
223     18       null
222     18       null
500     20       null
501     20       null

In the above table, I have two entries for each testId, now I need to compare the RANK column of the corresponding TESTID rows, and update the LoginId column with 1 and 2.

Finally I am looking for output like follows:

RANK | TestID | LoginID
-----+--------+---------
234     14       1
235     14       2
330     15       1
331     15       2
223     18       2
222     18       1
500     20       1
501     20       2

Can anyone suggest which is better way to achieve this? I tried with min() and max(), with Case (When /then) concept, but the query is not returning the expected results.

Body:
You can use MERGE with window function row_number:

merge into your_table t
using (
    select t.*,
        row_number() over (partition by testId order by rank) as rn
    from your_table t
) s on (
    t.rank = s.rank
    and t.testId = s.testId
    )
when matched then update set t.loginId = s.rn;


问:
Could work an app then reboot iPhone?
I have an iOS Objective-C application, and this implements a store restoration function.
But if I reboot my iPhone while my app is running... they continue working before reboot?

I'm trying reboot my iPhone and apps in the background continue running in the background, but when I bring some to foreground, they show the launch screen like I would open them for the first time.
How to make sure that the application state is called before rebooting?

答: iOS has asystem call which is called applicationWillTerminate and this method doesn't get called when you reboot your device. When a reboot occurs, all apps, which work in the background, save their state and start again with this state when the reboot finishes.

Title: Could work an app then reboot iPhone?


问:
Extract and format Values from nested json data
I am trying to extract some data from the json data frame below, using Python 2.7.9.

I am trying to get to the counts in a single row that are listed inside the "steps" list using the code below:

```<code>data2 = (json.loads(data));

for data_key,data_value in data2['data'].items():
for date_key,date_value in data_value.items():
    for steps_value in date_value:
        if 'steps' == date_key:    #looping on dictionary object
            print data_key,steps_value['count'],steps_value['event'],steps_value['custom_event']
</code>```

On digging further, I managed to make some progress and get to the values. I am not a Python expert, so wondering if this could be done in a more elegant manner.Still looking to get to the output as below.

Ideal Output format:

Date1 Step1 Count1 Step2 Count2

Date2 Step2 Count1 Step2 Count2

Sample Data frame:

```<code>"frame":
{"dates": ["2016-09-12", "2016-09-19", "2016-09-26"]},
"data": {
    "2016-09-12":
        {"steps": [
            {"count": 325788, "step_conv_ratio": 1, "goal": "App Open", "overall_conv_ratio": 1, "avg_time": null, "event": "App Open"},
            {"count": 20524, "step_conv_ratio": 0.627875673029858, "goal": "Game Played",
            "avg_time": 572, "event": "Game Played"}],
        "analysis": {"completion": 20524, "starting_amount": 32688, "steps": 2, "worst": 1}},
    "2016-09-19":
        {"steps": [
            {"count": 32186, "step_conv_ratio": 1, "goal": "App Open", "overall_conv_ratio": 1, "avg_time": null, "event": "App Open"},
            {"count": 20809, "step_conv_ratio": 0.6405528535369082, "goal": "Game Played",
            "avg_time": 698, "event": "Game Played"}],
        "analysis": {"completion": 20809, "starting_amount": 32486, "steps": 2, "worst": 1}},
    "2016-09-26":
        {"steps": [
            {"count": 456, "step_conv_ratio": 1, "goal": "App Open", "overall_conv_ratio": 1, "avg_time": null, "event": "App Open"},
            {"count": 587, "step_conv_ratio": 0.7873688132646091, "goal": "Game Played",
            "avg_time": 571, "event": "Game Played"}],
        "analysis": {"completion": 12679, "starting_amount": 16103, "steps": 2, "worst": 1}}
    }}
</code>```

Any help / suggestions would be appreciated.

Thanks

答:
If every date only has two steps you could do something like:</p>

```<code>stuff = json.loads(data)
dates = stuff["frame"]["dates"] # list of dates as strings
for date in dates:
    steps = stuff["data"][date]["steps"] # list of dicts
    print("{0}: step 1: {1}, step 2: {2}".format(date, steps[0]["count"], steps[1]["count"]))
</code>```

Body:
I am trying to extract some data from the json data frame below, using Python 2.7.9.

I am trying to get to the counts in a single row that are listed inside the "steps" list using the code below:

data2 = (json.loads(data));

for data_key,data_value in data2['data'].items():
for date_key,date_value in data_value.items():
    for steps_value in date_value:
        if 'steps' == date_key:    #looping on dictionary object
            print data_key,steps_value['count'],steps_value['event'],steps_value['custom_event']

On digging further, I managed to make some progress and get to the values. I am not a Python expert, so wondering if this could be done in a more elegant manner.Still looking to get to the output as below.

Ideal Output format:

Date1 Step1 Count1 Step2 Count2

Date2 Step2 Count1 Step2 Count2

Sample Data frame:

"frame":
{"dates": ["2016-09-12", "2016-09-19", "2016-09-26"]},
"data": {
    "2016-09-12":
        {"steps": [
            {"count": 325788, "step_conv_ratio": 1, "goal": "App Open", "overall_conv_ratio": 1, "avg_time": null, "event": "App Open"},
            {"count": 20524, "step_conv_ratio": 0.627875673029858, "goal": "Game Played",
            "avg_time": 572, "event": "Game Played"}],
        "analysis": {"completion": 20524, "starting_amount": 32688, "steps": 2, "worst": 1}},
    "2016-09-19":
        {"steps": [
            {"count": 32186, "step_conv_ratio": 1, "goal": "App Open", "overall_conv_ratio": 1, "avg_time": null, "event": "App Open"},
            {"count": 20809, "step_conv_ratio": 0.6405528535369082, "goal": "Game Played",
            "avg_time": 698, "event": "Game Played"}],
        "analysis": {"completion": 20809, "starting_amount": 32486, "steps": 2, "worst": 1}},
    "2016-09-26":
        {"steps": [
            {"count": 456, "step_conv_ratio": 1, "goal": "App Open", "overall_conv_ratio": 1, "avg_time": null, "event": "App Open"},
            {"count": 587, "step_conv_ratio": 0.7873688132646091, "goal": "Game Played",
            "avg_time": 571, "event": "Game Played"}],
        "analysis": {"completion": 12679, "starting_amount": 16103, "steps": 2, "worst": 1}}
    }}

Any help / suggestions would be appreciated.

Thanks

Body:
If every date only has two steps you could do something like:

stuff = json.loads(data)
dates = stuff["frame"]["dates"] # list of dates as strings
for date in dates:
    steps = stuff["data"][date]["steps"] # list of dicts
    print("{0}: step 1: {1}, step 2: {2}".format(date, steps[0]["count"], steps[1]["count"]))


问:
Get Array of Input fields values and append itinto the associated textarea
I have some input field dynamically generated inside form. I am trying to read the value of hidden input and append to to the end of text area

```<code>   .<input type="hidden" id="formtype_loans_0_comment" name="formtype[loans][0][comment]" disabled="disabled" value="VAlue 1 value 123" />
    <textarea id="formtype_loans_0_description" name="formtype[loans][0][description]">Text Area 1 or 1 </textarea>

    <input type="hidden" id="formtype_loans_1_comment" name="formtype[loans][1][comment]" disabled="disabled" value="VAlue value 123" />
    <textarea id="formtype_loans_1_description" name="formtype[loans][1][description]">test desc</textarea>
</code>```

and Here is the js  code, but it's not working,

```<code>var values = [];

$("input[name='formtype[loans][][description]']").each(function() {
    values.push($(this).val());
});
alert(values);
</code>```

答:
```<code>var values = [],
    inputs = $('input[type="hidden"]'),
    textareas = $('textarea');

if (inputs.length === textareas.length) {
    $.each(inputs, function(i, input) {
        var val = ($(input).val()) ? $(input).val(): undefined;
        if (val) {
            $(textareas).eq(i).empty().val(val);
        }
    });
}

alert(values);
</code>```

The working code above assumes a couple of things:

There will always be one textarea per hidden input.

The associated textarea will always be the next sibling after the hidden input.

Even if that is not the case, there are still various ways to resolve this challenge. But I'll break down the different parts of the code:

First, instantiate your variables. Most importantly, cache your selected HTML elements into vars: touching the DOM is expensive and negatively impacts performance (e.g. querying the DOM each time in a loop).

Next, we put a conditional test to ensure there is one textarea for each input. No need to waste time iterating through a loop looking for elements that aren't there.

Finally, iterate through each of the selected inputs confirming each of them have a value. Again, no need manipulating textarea if there is no value to insert. If there is a value in the input, insert it into the textarea that occupies the same position as the input in each of your arrays of elements.

Body:
I have some input field dynamically generated inside form. I am trying to read the value of hidden input and append to to the end of text area

   .<input type="hidden" id="formtype_loans_0_comment" name="formtype[loans][0][comment]" disabled="disabled" value="VAlue 1 value 123" />
    <textarea id="formtype_loans_0_description" name="formtype[loans][0][description]">Text Area 1 or 1 </textarea>

    <input type="hidden" id="formtype_loans_1_comment" name="formtype[loans][1][comment]" disabled="disabled" value="VAlue value 123" />
    <textarea id="formtype_loans_1_description" name="formtype[loans][1][description]">test desc</textarea>

and Here is the js  code, but it's not working,

var values = [];

$("input[name='formtype[loans][][description]']").each(function() {
    values.push($(this).val());
});
alert(values);

Body:
var values = [],
    inputs = $('input[type="hidden"]'),
    textareas = $('textarea');

if (inputs.length === textareas.length) {
    $.each(inputs, function(i, input) {
        var val = ($(input).val()) ? $(input).val(): undefined;
        if (val) {
            $(textareas).eq(i).empty().val(val);
        }
    });
}

alert(values);

The working code above assumes a couple of things:

There will always be one textarea per hidden input.

The associated textarea will always be the next sibling after the hidden input.

Even if that is not the case, there are still various ways to resolve this challenge. But I'll break down the different parts of the code:

First, instantiate your variables. Most importantly, cache your selected HTML elements into vars: touching the DOM is expensive and negatively impacts performance (e.g. querying the DOM each time in a loop).

Next, we put a conditional test to ensure there is one textarea for each input. No need to waste time iterating through a loop looking for elements that aren't there.

Finally, iterate through each of the selected inputs confirming each of them have a value. Again, no need manipulating textarea if there is no value to insert. If there is a value in the input, insert it into the textarea that occupies the same position as the input in each of your arrays of elements.


问:
How to avoid a "java.util.NoSuchElementException" crashing my program
TL;DR-- how to get a java.util.NoSuchElementException to return a null instead of error and crash the program.

I was writing a program that is supposed to read a series of ints from a text file. In the program the amount of ints will vary each time I run it. I have written a piece of code that will read ints and I want to know how to make the java.util.NoSuchElementException not crash my program and instead return a null.

 The code I have writen is as follows

```<code>    public static void main(String[] args)  throws IOException{
    Scanner Input = new Scanner(new File("newestcode.txt"));
    Integer[] digits = new Integer[100];
    int h = 0;
    while(true){
        digits[h] = Input.nextInt();
        h++;
        System.out.println(digits[h]);
    }
}
</code>```

in case you are curious, the program I am to be writing is a sort of decryption engine for a bad encryption engine I wrote the other day

答:
```<code>try {
    digits[h] = Input.nextInt();
    h++;
    System.out.println(digits[h]);
}catch (NoSuchElementException e){
    break;
}
</code>```

Body:
TL;DR-- how to get a java.util.NoSuchElementException to return a null instead of error and crash the program.

I was writing a program that is supposed to read a series of ints from a text file. In the program the amount of ints will vary each time I run it. I have written a piece of code that will read ints and I want to know how to make the java.util.NoSuchElementException not crash my program and instead return a null.

 The code I have writen is as follows

    public static void main(String[] args)  throws IOException{
    Scanner Input = new Scanner(new File("newestcode.txt"));
    Integer[] digits = new Integer[100];
    int h = 0;
    while(true){
        digits[h] = Input.nextInt();
        h++;
        System.out.println(digits[h]);
    }
}

in case you are curious, the program I am to be writing is a sort of decryption engine for a bad encryption engine I wrote the other day


问:
javascript how to stop loop four less than elems.length?
This should be easy, but I'm apparently ridiculous with syntax if I have

```<code>var elems = document.getElementsByTagName("details");

function openAll() {
  for (var i = 0; i < elems.length; i++){
    elems[i].setAttribute("open", "true");
  }
</code>```

but I want to stop 4 tags before the end. How do I write that? The below does not work or a variety of other variations.

```<code>var elems = document.getElementsByTagName("details");

function openAll() {
  for (var i = 0; i < elems.length -4; i++){
    elems[i].setAttribute("open", "true");
  }
</code>```

答:
This may help you. please see this snippet

var elems = document.getElementsByTagName("p");

function openAll() {
  for (var i = 0; i < elems.length-4; i++){
    elems[i].setAttribute("class", "open");
  }

  }
  openAll();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.open{
  display:bolck
}

.close{
display:none;
}</code>```

hello

hello

hello

hello

hello

hello

hello

hello
```

Body:
This should be easy, but I'm apparently ridiculous with syntax if I have

var elems = document.getElementsByTagName("details");

function openAll() {
  for (var i = 0; i < elems.length; i++){
    elems[i].setAttribute("open", "true");
  }

but I want to stop 4 tags before the end. How do I write that? The below does not work or a variety of other variations.

var elems = document.getElementsByTagName("details");

function openAll() {
  for (var i = 0; i < elems.length -4; i++){
    elems[i].setAttribute("open", "true");
  }

Body:
This may help you. please see this snippet

var elems = document.getElementsByTagName("p");

function openAll() {
  for (var i = 0; i < elems.length-4; i++){
    elems[i].setAttribute("class", "open");
  }

  }
  openAll();

.open{
  display:bolck
}

.close{
display:none;
}

<p class="close">hello</p>
<p class="close">hello</p>
<p class="close">hello</p>
<p class="close">hello</p>
<p class="close">hello</p>
<p class="close">hello</p>
<p class="close">hello</p>
<p class="close">hello</p>


问:
Mario CS50 in Python
so I tried coding the mario assignment from CS50 in python instead of C to challenge myself and I managed to get it to work! I don't quite understand how the loops are working, especially the math because I just played around to get the result I wanted.

The requirements of the assignment were as follows

Create a half pyramid using hashes

Make sure it's right aligned

It should correspond to the height given by the User

The first line should start with 2"#"s

Any clarification on my loops would be greatly appreciated :)

```<code>print('Height: ', end='');
h = int(input());

while(h<0 or h > 24):
  print("That is an invalid input")
  print('Height: ', end='');
  h = int(input());

for i in range(h):
    print(" "*(h-i)+"#"*(i+1));
</code>```

答:
range(start, stop[, step])

Python range() function returns a list of integers from some lower bound (zero, by default) up to (but not including) some upper bound, possibly in increments (steps) of some other number (one, by default).
Hence,

```<code>range(3) returns a sequence: 0, 1, 2
range(1,3) returns a sequence: 1, 2
range(1,7,2) returns a sequence: 1, 3, 5
</code>```

Title: Mario CS50 in Python

Body:
so I tried coding the mario assignment from CS50 in python instead of C to challenge myself and I managed to get it to work! I don't quite understand how the loops are working, especially the math because I just played around to get the result I wanted.

The requirements of the assignment were as follows

Create a half pyramid using hashes

Make sure it's right aligned

It should correspond to the height given by the User

The first line should start with 2"#"s

Any clarification on my loops would be greatly appreciated :)

print('Height: ', end='');
h = int(input());

while(h<0 or h > 24):
  print("That is an invalid input")
  print('Height: ', end='');
  h = int(input());

for i in range(h):
    print(" "*(h-i)+"#"*(i+1));

Body:
range(start, stop[, step])

Python range() function returns a list of integers from some lower bound (zero, by default) up to (but not including) some upper bound, possibly in increments (steps) of some other number (one, by default).
Hence,

range(3) returns a sequence: 0, 1, 2
range(1,3) returns a sequence: 1, 2
range(1,7,2) returns a sequence: 1, 3, 5


问:
Table-Valued Parameter versus multiple Insert rows performance question for inserting into SQL Server 2008
If all I'm doing is inserting multiple rows of data into a single table in SQL Server 2008, which is faster?

A Table-Valued Parameter or a single insert statement with multiple values?

Where in this simple scenario would you prefer one over the other?

答:
Since both operations will insert data into a table the question becomes; "Is the overhead of using a stored procedure to make table inserts to much for my system to handle?"

Does your system allow direct inserts into tables from the app now?  If yes then just go with the direct insert.

I prefer to use stored procs as it allows me to add auditing, error logic, etc which just makes me feel better than dumping data directly into a table.


问:
XSLT Template Match for Dynamic Node
My input xml

```<code>   <ns1:TrackingResponse xmlns:ns1="http://sample/response">
    <TC10000004SF>
      <client_request>
        <id>402919</id>
        <client_order_id>66967604933444</client_order_id>
        <awb_number>TC10000004SF</awb_number>
      </client_request>
   </TC10000004SF>
   <TC10000005SF>
     <client_request>
        <id>402919</id>
        <client_order_id>66967604933444</client_order_id>
        <awb_number>TC10000005SF</awb_number>
     </client_request>
   </TC10000005SF>
</code>```

I want output xml to be like

```<code><TrackingResponse>
 <AWBNumber>
    <client_request>
        <id>402919</id>
        <client_order_id>66967604933444</client_order_id>
        <awb_number>TC10000004SF</awb_number>
    </client_request>
 </AWBNumber>
 <AWBNumber>
    <client_request>
        <id>402919</id>
        <client_order_id>66967604933444</client_order_id>
        <awb_number>TC10000005SF</awb_number>
    </client_request>
 </AWBNumber>
</TrackingResponse>
</code>```

We have used now the below xsl

```<code><?xml version="1.0"?>
  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"version="1.0">
<xsl:output method="xml" encoding="UTF-8" indent="yes"/>
<xsl:template match="*[starts-with(local-name(),'TC')]">
    <AWBNumber>
        <xsl:apply-templates select="node()"/>
    </AWBNumber>
</xsl:template>
<xsl:template match="*">
    <xsl:element name="{local-name(.)}">
        <xsl:apply-templates select="@* | node()"/>
    </xsl:element>
</xsl:template>
<xsl:template match="@*">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
</code>```

Since we are hardcoding SF we want to use some other method which takes the value from  node and then do the template match and renaming of node. I guess xslt 2.0 or 3.0 would be required for this requirement. Please help me regarding the same.

答:
Couldn't you do simply:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/*/*">
    <AWBNumber>
        <xsl:apply-templates/>
    </AWBNumber>
</xsl:template>

<xsl:template match="*">
    <xsl:element name="{local-name()}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>
</code>```

Title: XSLT Template Match for Dynamic Node

Body:
My input xml

   <ns1:TrackingResponse xmlns:ns1="http://sample/response">
    <TC10000004SF>
      <client_request>
        <id>402919</id>
        <client_order_id>66967604933444</client_order_id>
        <awb_number>TC10000004SF</awb_number>
      </client_request>
   </TC10000004SF>
   <TC10000005SF>
     <client_request>
        <id>402919</id>
        <client_order_id>66967604933444</client_order_id>
        <awb_number>TC10000005SF</awb_number>
     </client_request>
   </TC10000005SF>

I want output xml to be like

<TrackingResponse>
 <AWBNumber>
    <client_request>
        <id>402919</id>
        <client_order_id>66967604933444</client_order_id>
        <awb_number>TC10000004SF</awb_number>
    </client_request>
 </AWBNumber>
 <AWBNumber>
    <client_request>
        <id>402919</id>
        <client_order_id>66967604933444</client_order_id>
        <awb_number>TC10000005SF</awb_number>
    </client_request>
 </AWBNumber>
</TrackingResponse>

We have used now the below xsl

<?xml version="1.0"?>
  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"version="1.0">
<xsl:output method="xml" encoding="UTF-8" indent="yes"/>
<xsl:template match="*[starts-with(local-name(),'TC')]">
    <AWBNumber>
        <xsl:apply-templates select="node()"/>
    </AWBNumber>
</xsl:template>
<xsl:template match="*">
    <xsl:element name="{local-name(.)}">
        <xsl:apply-templates select="@* | node()"/>
    </xsl:element>
</xsl:template>
<xsl:template match="@*">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

Since we are hardcoding SF we want to use some other method which takes the value from  node and then do the template match and renaming of node. I guess xslt 2.0 or 3.0 would be required for this requirement. Please help me regarding the same.

Body:
Couldn't you do simply:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/*/*">
    <AWBNumber>
        <xsl:apply-templates/>
    </AWBNumber>
</xsl:template>

<xsl:template match="*">
    <xsl:element name="{local-name()}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>


问:
How do I check if an array have same value or not?
```<code>const style1=['50%','3.5vw','3.5vw','2.5vw','2.5vw']
const style2=['0%','22.5%','95%','2.5vw','2.5vw']

function addbuttonAnimation() {
    let applied = ( document.activeElement.id === 'add-order') ? [].concat(style2) : [].concat(style1)
    let x = document.querySelector('#add-order')

    function goStyle(...applied) {
        x.style.borderRadius = applied[0]
        x.style.width =applied[1]
        x.style.height =applied[2]
        x.style.bottom =applied[3]
        x.style.right =applied[4]
    }

    goStyle(...applied)
}

document.querySelector('#add-order').addEventListener("mouseup", addbuttonAnimation, false);
document.querySelector('main-wrap').addEventListener("mouseup", addbuttonAnimation, false);
</code>```

How do I know that my "applied" array value has changed (have same value or not from previous invoke)? So whenever addbuttonAnimation() invoked, it does not have to re-assign any value once again if the "applied" array have the same value from previous invoke.

答:
The indexOf() method searches the array for the specified item and returns its position.

The search will start at the specified position, or at the beginning if no start position is specified, and end the search at the end of the array.

Returns -1 if the item is not found.

If the item is present more than once, the indexOf method returns the position of the first occurrence.

Note: The first item has position 0, the second item has position 1, and so on.

Tip: If you want to search from end to start, use the lastIndexOf() method

```<code>var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");
</code>```

The result of a will be: 2

ContentLicense: CC BY-SA 4.0

Body:
const style1=['50%','3.5vw','3.5vw','2.5vw','2.5vw']
const style2=['0%','22.5%','95%','2.5vw','2.5vw']

function addbuttonAnimation() {
    let applied = ( document.activeElement.id === 'add-order') ? [].concat(style2) : [].concat(style1)
    let x = document.querySelector('#add-order')

    function goStyle(...applied) {
        x.style.borderRadius = applied[0]
        x.style.width =applied[1]
        x.style.height =applied[2]
        x.style.bottom =applied[3]
        x.style.right =applied[4]
    }

    goStyle(...applied)
}

document.querySelector('#add-order').addEventListener("mouseup", addbuttonAnimation, false);
document.querySelector('main-wrap').addEventListener("mouseup", addbuttonAnimation, false);

How do I know that my "applied" array value has changed (have same value or not from previous invoke)? So whenever addbuttonAnimation() invoked, it does not have to re-assign any value once again if the "applied" array have the same value from previous invoke.

Body:
The indexOf() method searches the array for the specified item and returns its position.

The search will start at the specified position, or at the beginning if no start position is specified, and end the search at the end of the array.

Returns -1 if the item is not found.

If the item is present more than once, the indexOf method returns the position of the first occurrence.

Note: The first item has position 0, the second item has position 1, and so on.

Tip: If you want to search from end to start, use the lastIndexOf() method

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");

The result of a will be: 2


问:
Adding fields to js objects, in functional way
I have an array of objects with a set of fields in node.js. Lets say

```<code>let arr = [ {a:1,b:2}, {a:3,b:6}]
</code>```

I would like to extend all objects and assign to a new variable. My naïve approach is like the following way

```<code>let arr2 = arr.map(x => x.c = x.a + x.b )
</code>```

However, the arrow function returns the x.a+x.b value, instead of the x object, so this won't work as I hope. It also alters the arr in place which is very nonfunctional and confusing.

I'm relatively new to js so maybe I'm thinking wrong from the beginning. What is the idiomatic js expression for this kind of object extension?

答:
You can write all properties from one object to another with Object.assign:

```<code>const arr2 = arr.map(x => Object.assign({c: x.a + x.b}, x));
</code>```

And maybe at some point in the future with object spread (not yet standardized):

```<code>const arr2 = arr.map(x => ({...x, c: x.a + x.b}));
</code>```

Body:
I have an array of objects with a set of fields in node.js. Lets say

let arr = [ {a:1,b:2}, {a:3,b:6}]

I would like to extend all objects and assign to a new variable. My naïve approach is like the following way

let arr2 = arr.map(x => x.c = x.a + x.b )

However, the arrow function returns the x.a+x.b value, instead of the x object, so this won't work as I hope. It also alters the arr in place which is very nonfunctional and confusing.

I'm relatively new to js so maybe I'm thinking wrong from the beginning. What is the idiomatic js expression for this kind of object extension?

Body:
You can write all properties from one object to another with Object.assign:

const arr2 = arr.map(x => Object.assign({c: x.a + x.b}, x));

And maybe at some point in the future with object spread (not yet standardized):

const arr2 = arr.map(x => ({...x, c: x.a + x.b}));


答:
First of all, if you're not sure about amount of ints in your file, don't try to store them into fixed-size array. Use ArrayList instead.

Also don't use endless loop while(true) but consider using Input.hasNext() to check if there still is something to read from file.

And one more. You're trying to print value after increment. This means that you're adding element on 0 position but trying to read it from 1 position. Make increment on the end of the loop.

```<code>Scanner Input = new Scanner(new File("newestcode.txt"));
List<Integer> digits = new ArrayList<>();
int h = 0;
while(Input.hasNetxt()){
    digits.add(h, Input.nextInt());
    System.out.println(digits.get(h));
    h++;
}
</code>```

Title: How to avoid a "java.util.NoSuchElementException" crashing my program

Body:
First of all, if you're not sure about amount of ints in your file, don't try to store them into fixed-size array. Use ArrayList instead.

Also don't use endless loop while(true) but consider using Input.hasNext() to check if there still is something to read from file.

And one more. You're trying to print value after increment. This means that you're adding element on 0 position but trying to read it from 1 position. Make increment on the end of the loop.

Scanner Input = new Scanner(new File("newestcode.txt"));
List<Integer> digits = new ArrayList<>();
int h = 0;
while(Input.hasNetxt()){
    digits.add(h, Input.nextInt());
    System.out.println(digits.get(h));
    h++;
}


问:
HierarchyID in Entity Framework not working
We are using WCF Data Service based on an Entity Framework model for our application.

In this we need to add the table with a column of type HierarchyId. When I add that table to the EDMX file, the HierarchId column is not appearing in the class file.

What should I do to make use of HierarchyID? I read that Entity Framework is not supporting HierarchyID, so how can I achieve this?

答:
You can always convert a HierarchyId to its string representation - something like /1/3/4/1 - and send that string across the WCF data service.

Update: if you add this computed, persisted column to your SQL Server table, that new column should definitely show up in your EF model and you should be able to use this to send it back over WCF and WCF Data Services:

```<code>ALTER TABLE dbo.YourTable
ADD HierarchyString AS (your hierarchyID field).ToString() PERSISTED
</code>```

Update #2: read the docs! You can parse back a string like /1/3/4/1 into a HierarchyId type - either use the HierarchyId::Parse(string) or the usual CAST(string as HierarchyId) methods to do so.

Body:
You can always convert a HierarchyId to its string representation - something like /1/3/4/1 - and send that string across the WCF data service.

Update: if you add this computed, persisted column to your SQL Server table, that new column should definitely show up in your EF model and you should be able to use this to send it back over WCF and WCF Data Services:

ALTER TABLE dbo.YourTable
ADD HierarchyString AS (your hierarchyID field).ToString() PERSISTED

Update #2: read the docs! You can parse back a string like /1/3/4/1 into a HierarchyId type - either use the HierarchyId::Parse(string) or the usual CAST(string as HierarchyId) methods to do so.


答:
You can use underscore.js#intersection to avoid extra pain of writing

```<code>  let prevApplied = [];

 function addbuttonAnimation() {

   let applied = (document.activeElement.id === 'add-order') ? [].concat(style2) : [].concat(style1)
   var boolStyleDiff = _.intersection(prevApplied, applied);

   if (!boolStyleDiff) {

     return false; //to avoid call to goStyle()
   }

   prevApplied = applied; //saved previously applied
   let x = document.querySelector('#add-order')

   function goStyle(...applied) {
     //code
   }

   goStyle(...applied)
 }
</code>```

Title: How do I check if an array have same value or not?

Body:
You can use underscore.js#intersection to avoid extra pain of writing

  let prevApplied = [];

 function addbuttonAnimation() {

   let applied = (document.activeElement.id === 'add-order') ? [].concat(style2) : [].concat(style1)
   var boolStyleDiff = _.intersection(prevApplied, applied);

   if (!boolStyleDiff) {

     return false; //to avoid call to goStyle()
   }

   prevApplied = applied; //saved previously applied
   let x = document.querySelector('#add-order')

   function goStyle(...applied) {
     //code
   }

   goStyle(...applied)
 }


问:
How to get file contents by inode in Bash?
How can I retrieve file contents in Bash by knowing only the inode of the file?</p>

答:
If you have access to find with find (GNU findutils) and not the POSIX find, you can use its  -inum option for it,

```<code>-inum n
       File  has  inode  number  n.   It  is normally easier to use the
       -samefile test instead
</code>```

Just use it along with the -exec option and open the file using cat,

```<code>find . -inum 1346087 -exec cat {} \;
</code>```

Assume inode value for my file sample.txt is as

```<code>ls -id sample.txt
1346087 sample.txt
</code>```

Body:
If you have access to find with find (GNU findutils) and not the POSIX find, you can use its  -inum option for it,

-inum n
       File  has  inode  number  n.   It  is normally easier to use the
       -samefile test instead

Just use it along with the -exec option and open the file using cat,

find . -inum 1346087 -exec cat {} \;

Assume inode value for my file sample.txt is as

ls -id sample.txt
1346087 sample.txt


答:
As per this unixexchange answer:

You cannot access files by inodes, because that would break access control via permissions. For example, if you don't have the permission to traverse a directory, then you can't access any of the files in that directory no matter what the permissions on the file are. If you could access a file by inode, that would bypass directory permissions.

There is some ways to get the path or name of a file through an inode number though, for example using find. Once you get one path to the file, you can use any of the regular tools.

find has an inum argument to look up files by inodes. Here is an example:

find -inum 1704744 -exec cat {} \;
```

This will print the content of the file with inode 1704744, assuming it is located in the current directory or one of its children.

Note: ls also has a -i option to get the inode associated with files.

Title: How to get file contents by inode in Bash?

Body: How can I retrieve file contents in Bash by knowing only the inode of the file?

Body:
As per this unixexchange answer:

You cannot access files by inodes, because that would break access control via permissions. For example, if you don't have the permission to traverse a directory, then you can't access any of the files in that directory no matter what the permissions on the file are. If you could access a file by inode, that would bypass directory permissions.

There is some ways to get the path or name of a file through an inode number though, for example using find. Once you get one path to the file, you can use any of the regular tools.

find has an inum argument to look up files by inodes. Here is an example:

find -inum 1704744 -exec cat {} \;

This will print the content of the file with inode 1704744, assuming it is located in the current directory or one of its children.

Note: ls also has a -i option to get the inode associated with files.


问:
How to stop or disable Google App Engine production server?
I have uploaded google app java project to production google app engine (from this tutorial), but I can't found any information how to stop or disable the production app engine.

From google developer console, I can shutdown the instance via menu Compute -> Instances, but if I open or access the app's url in the browser, the app instance will start running again.

So how to completely stop or disable Google App Engine production server?

答:
Late to the game here, the tutorial currently suggests deleting the project, but I wanted to keep the project ID so the suggested option isn't the ideal solution for me.

After spending a good 15 min around the site I've found 2 ways to stop the application. Hope this will be of some help to others until the UI changes again.

Method 1: Disable Application

Go into App Engine, Settings, click on Disable application.

Method 2: Stop Instance

Go into App Engine, Versions, and then click on STOP.


问:
Combine 2 lists in python such that elements at the corresponding index are together
I have two lists like:

```<code>listone = [1, 2, 3]
listtwo = [4, 5, 6]
</code>```

I would like to combine them to get:

```<code>l = [1, 4, 2, 5, 3, 6]
</code>```

How can I do this without using loops?

答:
this is a variant using zip and a nested list comprehension:

```<code>listone = [1, 2, 3]
listtwo = [4, 5, 6]

l = list(a for ab in zip(listone, listtwo) for a in ab)
print(l)  # [1, 4, 2, 5, 3, 6]
</code>```

Body:
I have two lists like:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

I would like to combine them to get:

l = [1, 4, 2, 5, 3, 6]

How can I do this without using loops?

Body:
this is a variant using zip and a nested list comprehension:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

l = list(a for ab in zip(listone, listtwo) for a in ab)
print(l)  # [1, 4, 2, 5, 3, 6]


答:
you can use this

```<code>let arr2 = arr.map(x => {
      x.c = x.a + x.b;
      return x;
});
</code>```

Please also refer working snippet

let arr = [ {a:1,b:2}, {a:3,b:6}];
let arr2 = arr.map(x => {
  return Object.assign({c : x.a + x.b},x);
});

console.log(arr);
console.log(arr2);
console.log(arr);```

Title: Adding fields to js objects, in functional way

Body:
you can use this

let arr2 = arr.map(x => {
      x.c = x.a + x.b;
      return x;
});

Please also refer working snippet

let arr = [ {a:1,b:2}, {a:3,b:6}];
let arr2 = arr.map(x => {
  return Object.assign({c : x.a + x.b},x);
});

console.log(arr);
console.log(arr2);
console.log(arr);


问:
Why is this semaphore code failing?
```<code>#include <semaphore.h>

sem_t mutex;

int main (int argc, char * argv[])
{

sem_init (&mutex,0,1);

}
</code>```

<p>I'm getting: </p>

```<code>/tmp/ccAMFxDX.o: In function `main':
programaservidor.c:(.text+0x86): undefined reference to `sem_init'
collect2: ld returned 1 exit status
</code>```

答:
The relevant POSIX reference is:

http://www.opengroup.org/onlinepubs/9699919799/utilities/c99.html#tag_20_11_13

Title: Why is this semaphore code failing?

Body:
#include <semaphore.h>

sem_t mutex;

int main (int argc, char * argv[])
{

sem_init (&mutex,0,1);

}

I'm getting:

/tmp/ccAMFxDX.o: In function `main':
programaservidor.c:(.text+0x86): undefined reference to `sem_init'
collect2: ld returned 1 exit status


问:
html form post is not sending variable data
After clicking "delete" (submit): I can tell that it processes the form because I get the error "You forgot to select a vendor to delete.".

The form itself is generated using PHP. When I check the HTML output, I see that the values are there. But when it gets to POST, nothing carries over. I'm testing and using a local host, so other than the existing action link, I'm not sure what else I can modify.

I have the exact same code in another delete form and it works fine. I literally copied the other form to create this one and just changed the SQL/Variable names.

PHP Code:

```<code>#delete vendor
require('includes/mysqli_connect.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $errors = array(); //array to collect errors

    //check to ensure fields are filled out
    if (!empty($_POST['vendor'])) {
        $vendor = trim($_POST['vendor']);
    }
    else {
        $errors[] = "<p>You forgot to select a vendor to delete</p>";
    }

    if (empty($errors)) {
        //insert information into appt table
        $query = "UPDATE vendors_t SET active = 0 WHERE vendorID = $vendor;";
        $result = mysqli_query($dbc, $query);
        if($result){
            echo '<div class="alert alert-success" role="alert">';
            echo '<h2>Thank you!</h2>';
            echo '<p> Your request to delete vendorID ' . $customerID . 'has been completed </p></div>';
        } else {
            echo "Error updating record: " . mysqli_error($dbc);
        }
    } else{
        echo '<div class="alert alert-danger" role="alert"><br>';
        echo '<h2>Errors Detected</h2>';
        echo '<p>The following errors occured:<br/>';
        foreach ($errors as $msg) {
            echo "$msg<br/>\n";
        }
        echo '</p><p>Please try again. </p></div>';
    }

}
</code>```

HTML Code

```<code><div class="container standout" >
    <div class="col-lg-12">
        <h2>Delete a vendor</h2>
        <p> Please select a vendor to delete.</p>
    </div>
    <div class="row">
        <form action="index.php?pagelet=deletevendor" method="post">
            <div class="form-group col-md-4">
                <label for="vendor">Vendors</label>
                <select name="vendor" class="form-control">
                    <option name="vendor" selected disabled>Choose here</option>
                    <?php
                        $query = "SELECT vendorID, contactFname, contactLname, businessName FROM vendors_T WHERE active = 1;";
                        $result = mysqli_query($dbc, $query);

                        while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                            echo '<option name="vendor" value="'.$row['vendorID'].'">'
                                    .$row['vendorID'].' '.$row['businessName']
                                    .' '.$row['contactFname'].' '.$row['contactLname']
                                .'</option>';
                        }?>
                </select>
                <br>
                <br>
                <input class="btn btn-primary" id="submit" type="submit" value="Delete">
            </div>
        </div>
    </form>
</div>
</code>```

答: Your option names should be the value of the vendor ID (I presume) and certainly not "vendor".</p>

Body:
After clicking "delete" (submit): I can tell that it processes the form because I get the error "You forgot to select a vendor to delete.".

The form itself is generated using PHP. When I check the HTML output, I see that the values are there. But when it gets to POST, nothing carries over. I'm testing and using a local host, so other than the existing action link, I'm not sure what else I can modify.

I have the exact same code in another delete form and it works fine. I literally copied the other form to create this one and just changed the SQL/Variable names.

PHP Code:

#delete vendor
require('includes/mysqli_connect.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $errors = array(); //array to collect errors

    //check to ensure fields are filled out
    if (!empty($_POST['vendor'])) {
        $vendor = trim($_POST['vendor']);
    }
    else {
        $errors[] = "
You forgot to select a vendor to delete
";
    }

    if (empty($errors)) {
        //insert information into appt table
        $query = "UPDATE vendors_t SET active = 0 WHERE vendorID = $vendor;";
        $result = mysqli_query($dbc, $query);
        if($result){
            echo '
';
            echo '
Thank you!
';
            echo '
 Your request to delete vendorID ' . $customerID . 'has been completed

';
        } else {
            echo "Error updating record: " . mysqli_error($dbc);
        }
    } else{
        echo '

';
        echo '
Errors Detected
';
        echo '
The following errors occured:
';
        foreach ($errors as $msg) {
            echo "$msg
\n";
        }
        echo '

Please try again.

';
    }

}

HTML Code

Delete a vendor

 Please select a vendor to delete.

        <form action="index.php?pagelet=deletevendor" method="post">

                Vendors
                <select name="vendor" class="form-control">
                    <option name="vendor" selected disabled>Choose here</option>
                    <?php
                        $query = "SELECT vendorID, contactFname, contactLname, businessName FROM vendors_T WHERE active = 1;";
                        $result = mysqli_query($dbc, $query);

                        while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                            echo '<option name="vendor" value="'.$row['vendorID'].'">'
                                    .$row['vendorID'].' '.$row['businessName']
                                    .' '.$row['contactFname'].' '.$row['contactLname']
                                .'</option>';
                        }?>
                </select>

                <input class="btn btn-primary" id="submit" type="submit" value="Delete">

    </form>


问:
action item in menu set text color
I have a menu that is inflated on to a toolbar in 3 different Activities. One of the Activities has a Overflow menu with one Action behind the Overflow. I can change the background color of the Action. I can not change the text color of the text associated with the Action. Please do not down vote I have looked at and tried all 136 similar posted questions.
Here is the styles code and menu code below.

```<code><resources>
<!-- Base application theme. -->
<!-- parent="Theme.AppCompat.NoActionBar"> -->
<!-- Line of CODE ABOVE gives WHITE color to items in ToolBar -->
<!-- Line of CODE BELOW gives BLACk color to items in ToolBar -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="android:itemBackground">@color/color_Red</item>
    <item name="actionMenuTextColor">@style/MyActionBarTitleText</item>
</style>

<style name="MyActionBarTitleText" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:textColor">@color/color_Yellow</item>
</style>
</code>```

Menu Code

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  tools:context=".MainActivity">

<item
    android:id="@+id/action_ReSetPW"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never"
    android:visible="true"/>
</code>```

As a side note I also could not change the Title Text Color based on some parameter. I would like to know how to set or change the text color?
After some trial and ERROR I am posting a styles code with comments for a solution solution code below

```<code><resources>
<!-- Base application theme. -->
<!-- parent="Theme.AppCompat.NoActionBar"> -->
<!-- Line of CODE ABOVE gives WHITE color to items in ToolBar -->
<!-- Line of CODE BELOW gives BLACk color to items in ToolBar -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="android:itemBackground">@color/color_Red</item>
    <!--The line of CODE above styles the action background color  -->

</style>

<style name="Toolbar.TitleText" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
    <item name="android:textSize">21sp</item>
    <item name="android:textStyle">italic</item>
</style>

<!--ADD THIS TO THE XML that defines the widget ToolBar android:theme="@style/ToolbarTheme" -->
<!--the line of CODE above tells the ToolBar where to find the style to use -->
<!--Code below will make the Overflow three dots Yellow and the text of the Action Yellow -->
<style name="ToolbarTheme" parent="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:textColorPrimary">@color/color_Yellow</item>
</style>
</code>```

It seems part of the solution is to call the style from the toolbar.xml

答:
```<code>app:itemTextColor="@color/your_color"

<android.support.design.widget.NavigationView
    android:id="@+id/navigation_view_search"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header"
    app:menu="@menu/drawer_menu"
    app:itemTextColor="@color/colorWhite"
    app:itemIconTint="@android:color/white"
    android:background="@drawable/nav_drawer_background" />
</code>```

Title: action item in menu set text color

Body:
I have a menu that is inflated on to a toolbar in 3 different Activities. One of the Activities has a Overflow menu with one Action behind the Overflow. I can change the background color of the Action. I can not change the text color of the text associated with the Action. Please do not down vote I have looked at and tried all 136 similar posted questions.
Here is the styles code and menu code below.

<resources>

Menu Code

<menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  tools:context=".MainActivity">

<item
    android:id="@+id/action_ReSetPW"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never"
    android:visible="true"/>

As a side note I also could not change the Title Text Color based on some parameter. I would like to know how to set or change the text color?
After some trial and ERROR I am posting a styles code with comments for a solution solution code below

<resources>

It seems part of the solution is to call the style from the toolbar.xml


问:
how to terminate mapreduce job after checking for a condition?
I already found this solution. But, As answer says it's unsafe to do so, is there any safer way to do this using new MapReduce library (org.apache.hadoop.mapreduce)</p>

答:
As I was willing to terminate the MapReduce job that runs in a loop; So, I solved this problem by using counters as follows,

```<code>public static enum SOLUTION_FLAG{
    SOLUTION_FOUND;
}
</code>```

I took help from this site,

How to use the counters in Hadoop?

From the value of a flag, I decided to if I can skip the task and when a job ends, at the end of each loop I checked for a value of this flag.

Let me know if I'm doing it correctly.

Body:
As I was willing to terminate the MapReduce job that runs in a loop; So, I solved this problem by using counters as follows,

public static enum SOLUTION_FLAG{
    SOLUTION_FOUND;
}

I took help from this site,

How to use the counters in Hadoop?

From the value of a flag, I decided to if I can skip the task and when a job ends, at the end of each loop I checked for a value of this flag.

Let me know if I'm doing it correctly.