问:
colormap for 3d bar plot in matplotlib applied to every bar
Does anyone know how to implement easily colormaps to 3d bar plots in matplotlib?

Consider this example, how do I change each bar according to a colormap? For example, short bars should be mainly blue, while taller bars graduate their colors from blue towards the red...

答:
So maybe not exactly what you're looking for (perhaps a good starting point for you), but using

Getting individual colors from a color map in matplotlib

can give varying solid colors for the bars:

```<code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.cm as cm           # import colormap stuff!
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x, y = np.random.rand(2, 100) * 4
hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]])

# Construct arrays for the anchor positions of the 16 bars.
# Note: np.meshgrid gives arrays in (ny, nx) so we use 'F' to flatten xpos,
# ypos in column-major order. For numpy >= 1.7, we could instead call meshgrid
# with indexing='ij'.
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25)
xpos = xpos.flatten('F')
ypos = ypos.flatten('F')
zpos = np.zeros_like(xpos)

# Construct arrays with the dimensions for the 16 bars.
dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = hist.flatten()

cmap = cm.get_cmap('jet') # Get desired colormap
max_height = np.max(dz)   # get range of colorbars
min_height = np.min(dz)

# scale each z to [0,1], and get their rgb values
rgba = [cmap((k-min_height)/max_height) for k in dz]

ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=rgba, zsort='average')

plt.show()
</code>```

Personally, I find that ugly as sin!  But it probably won't look too bad with a sequential colormap - https://matplotlib.org/examples/color/colormaps_reference.html

Body:
So maybe not exactly what you're looking for (perhaps a good starting point for you), but using

Getting individual colors from a color map in matplotlib

can give varying solid colors for the bars:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.cm as cm           # import colormap stuff!
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x, y = np.random.rand(2, 100) * 4
hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]])

# Construct arrays for the anchor positions of the 16 bars.
# Note: np.meshgrid gives arrays in (ny, nx) so we use 'F' to flatten xpos,
# ypos in column-major order. For numpy >= 1.7, we could instead call meshgrid
# with indexing='ij'.
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25)
xpos = xpos.flatten('F')
ypos = ypos.flatten('F')
zpos = np.zeros_like(xpos)

# Construct arrays with the dimensions for the 16 bars.
dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = hist.flatten()

cmap = cm.get_cmap('jet') # Get desired colormap
max_height = np.max(dz)   # get range of colorbars
min_height = np.min(dz)

# scale each z to [0,1], and get their rgb values
rgba = [cmap((k-min_height)/max_height) for k in dz]

ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=rgba, zsort='average')

plt.show()

Personally, I find that ugly as sin!  But it probably won't look too bad with a sequential colormap - https://matplotlib.org/examples/color/colormaps_reference.html


来源: stackexchange

问:
Softlayer Endurance File Storage mounting in Ubuntu machines
I have two ubuntu machines and an Endurance file storage in dal 10 datacenter of Softlayer.

In the machine, I had installed
 apt-get -y install nfs-common

In the Softlayer control center File Storage ->  -> Authorized Hosts, added the machine using "Devices"

Then I tried to execute the command and got following error.

mount -t nfs -o hard,intr fsf-dal1001d-fz.adn.networklayer.com:/IBM02SEV571879_232/data01 /batch
mount.nfs: access denied by server while mounting fsf-dal1001d-fz.adn.networklayer.com:/IBM02SEV571879_232/data01

I tried with subnet authorising and IP way of authorising. Unfortunately same results

Could you please help me?

答: I had tried with another storage server and the issue resolved. It seems like there were some issues with a specified File Storage server in Softlayer.</p>

ContentLicense: CC BY-SA 3.0


问:
Need to have button change text when clicked, then change back when outside click
I have a "Quit" button that changes text based on a variable. When clicked, the variable increases by one, and the application quits when the var is 2.

```<code>public static int QuitVar = 0;

        private void quitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QuitVar = QuitVar + 1;

            if (QuitVar == 0)
            {
                quitToolStripMenuItem.Text = "Quit";
            }

            if (QuitVar == 1)
            {
                quitToolStripMenuItem.Text = "Really?";
            }

            if (QuitVar == 2)
            {
                QuitVar = 0;
                Application.Exit();
            }
</code>```

I would like QuitVar to change back to 0 when the user clicks outside the button, so the button text is "quit". Is there a way to do this in C#?

答:
There are too many places a user could click that aren't the Quit button.  What might be easier is to detect when the mouse leaves the Quit button with the MouseLeave event.

By going to the Control properties (I used a Button here), and Events (the lighting symbol), then double-clicking inside the MouseLeave event, it will generate a template event handler method for you:

Inside that event handler, set your text and QuitVar appropriately:

```<code>private void quitToolStripMenuItem_MouseLeave(object sender, EventArgs e)
{
    QuitVar = 0;
    quitToolStripMenuItem.Text = "Quit";
}
</code>```

Body:
I have a "Quit" button that changes text based on a variable. When clicked, the variable increases by one, and the application quits when the var is 2.

public static int QuitVar = 0;

        private void quitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QuitVar = QuitVar + 1;

            if (QuitVar == 0)
            {
                quitToolStripMenuItem.Text = "Quit";
            }

            if (QuitVar == 1)
            {
                quitToolStripMenuItem.Text = "Really?";
            }

            if (QuitVar == 2)
            {
                QuitVar = 0;
                Application.Exit();
            }

I would like QuitVar to change back to 0 when the user clicks outside the button, so the button text is "quit". Is there a way to do this in C#?

Body:
There are too many places a user could click that aren't the Quit button.  What might be easier is to detect when the mouse leaves the Quit button with the MouseLeave event.

By going to the Control properties (I used a Button here), and Events (the lighting symbol), then double-clicking inside the MouseLeave event, it will generate a template event handler method for you:

Inside that event handler, set your text and QuitVar appropriately:

private void quitToolStripMenuItem_MouseLeave(object sender, EventArgs e)
{
    QuitVar = 0;
    quitToolStripMenuItem.Text = "Quit";
}


问:
Admob's NativeExpressAdView not showing in Custom view Android

I want NativeExpressAdView on Exit dialog. Exit dialog is custom dialog created in app. code for custom dialog are below.

```<code>public void onBackPressed() {
    System.out.println("IN ON BACK PRESSED:");
    final Dialog dialog = new Dialog(SplashActivity.this);
    dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
    dialog.setContentView(R.layout.exit_dialog);

    LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View main = inflater.inflate(R.layout.exit_dialog, null);
    dialog.setContentView(main);
    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();

    LinearLayout linear = (LinearLayout)main.findViewById(R.id.layoutAdd);

    NativeExpressAdView mNativeExpressAdView = new NativeExpressAdView(this);
    mNativeExpressAdView.setAdSize(new AdSize(AdSize.FULL_WIDTH, AdSize.AUTO_HEIGHT));
    mNativeExpressAdView.setAdUnitId("ca-app-pub-8410399846074282/9976822052");
    AdRequest.Builder adRequestBuilder = new AdRequest.Builder();

    linear.addView(mNativeExpressAdView);
    mNativeExpressAdView.loadAd(adRequestBuilder.build());

    dialog.setTitle("Title...");

    // set the custom dialog components - text, image and button
    TextView text = (TextView) dialog.findViewById(R.id.dialog_text);
    text.setText("Are you sure you wants to exit ?? " + R.string.app_name);

    Button dialogButton = (Button) dialog.findViewById(R.id.btnCancel);
    // if button is clicked, close the custom dialog
    dialogButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dialog.dismiss();
        }
    });

    Button btnRateus = (Button) dialog.findViewById(R.id.btnRateus);
    // if button is clicked, close the custom dialog
    btnRateus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
            Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
            // To count with Play market backstack, After pressing back button,
            // to taken back to our application, we need to add following flags to intent.
            goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
                    Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
                    Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
            try {
                startActivity(goToMarket);
            } catch (ActivityNotFoundException e) {
                startActivity(new Intent(Intent.ACTION_VIEW,
                        Uri.parse("http://play.google.com/store/apps/details?id=" + getApplicationContext().getPackageName())));
            }
        }
    });

    Button btnConfirm = (Button) dialog.findViewById(R.id.btnConfirm);
    // if button is clicked, close the custom dialog
    btnConfirm.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });
    dialog.show();
}
</code>```

Its not working directly so i was try to inflate NativeExpressAdview in Linearlayout but it not displayed in linearlayout too. Please help me on that ... Thank you in Advance !!

答:
This is due to the AUTO_HEIGHT attribute as mentionned in the official native ad express documentation here :

At this time, the AUTO_HEIGHT constant and FLUID ad size should not be used with Native Ads Express.

Body:
I want NativeExpressAdView on Exit dialog. Exit dialog is custom dialog created in app. code for custom dialog are below.

public void onBackPressed() {
    System.out.println("IN ON BACK PRESSED:");
    final Dialog dialog = new Dialog(SplashActivity.this);
    dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
    dialog.setContentView(R.layout.exit_dialog);

    LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View main = inflater.inflate(R.layout.exit_dialog, null);
    dialog.setContentView(main);
    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();

    LinearLayout linear = (LinearLayout)main.findViewById(R.id.layoutAdd);

    NativeExpressAdView mNativeExpressAdView = new NativeExpressAdView(this);
    mNativeExpressAdView.setAdSize(new AdSize(AdSize.FULL_WIDTH, AdSize.AUTO_HEIGHT));
    mNativeExpressAdView.setAdUnitId("ca-app-pub-8410399846074282/9976822052");
    AdRequest.Builder adRequestBuilder = new AdRequest.Builder();

    linear.addView(mNativeExpressAdView);
    mNativeExpressAdView.loadAd(adRequestBuilder.build());

    dialog.setTitle("Title...");

    // set the custom dialog components - text, image and button
    TextView text = (TextView) dialog.findViewById(R.id.dialog_text);
    text.setText("Are you sure you wants to exit ?? " + R.string.app_name);

    Button dialogButton = (Button) dialog.findViewById(R.id.btnCancel);
    // if button is clicked, close the custom dialog
    dialogButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dialog.dismiss();
        }
    });

    Button btnRateus = (Button) dialog.findViewById(R.id.btnRateus);
    // if button is clicked, close the custom dialog
    btnRateus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName());
            Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
            // To count with Play market backstack, After pressing back button,
            // to taken back to our application, we need to add following flags to intent.
            goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
                    Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
                    Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
            try {
                startActivity(goToMarket);
            } catch (ActivityNotFoundException e) {
                startActivity(new Intent(Intent.ACTION_VIEW,
                        Uri.parse("http://play.google.com/store/apps/details?id=" + getApplicationContext().getPackageName())));
            }
        }
    });

    Button btnConfirm = (Button) dialog.findViewById(R.id.btnConfirm);
    // if button is clicked, close the custom dialog
    btnConfirm.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });
    dialog.show();
}

Its not working directly so i was try to inflate NativeExpressAdview in Linearlayout but it not displayed in linearlayout too. Please help me on that ... Thank you in Advance !!


问:
how to remove key constraint of column in mysql?

how to remove key from column in Mysql?(primary,foreign,unique all)

here i given primary key to the column id

```<code>ALTER TABLE table ADD PRIMARY KEY(id);
</code>```

now i like to remove it, and make none key column id
is there is any way.i used,

```<code> ALTER TABLE `table` MODIFY `id` INT
</code>```

but it actually gives UNIQUE key

Body:
how to remove key from column in Mysql?(primary,foreign,unique all)

here i given primary key to the column id

ALTER TABLE table ADD PRIMARY KEY(id);

now i like to remove it, and make none key column id
is there is any way.i used,

 ALTER TABLE `table` MODIFY `id` INT

but it actually gives UNIQUE key

Body:
Hi you can run the below command :

Alter TABLE tableName MODIFY COLUMN  id INT, DROP PRIMARY KEY;

mysql> desc TestTable;

+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(10)     | NO   | PRI | NULL    |       |
| name  | varchar(30) | NO   |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.05 sec)

mysql> ALTER TABLE TestTable MODIFY COLUMN id INT(10),DROP PRIMARY KEY;
Query OK, 0 rows affected (0.62 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc TestTable;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(10)     | YES  |     | NULL    |       |
| name  | varchar(30) | NO   |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)


问:
how can I show loading spinner when changing router in vue 2
I have been trying to show a spinner on each router change in vue 2. I added a flag in created method to show the initial loading and after sometime I stopped the loading spinner. This doesn't work at all.

Is there any other solution to achieve this?

Thanks in advance.

答: You can also use navigation guards to set a beforeEach method that will run before entering each new route: https://router.vuejs.org/en/advanced/navigation-guards.html</p>


问:
How to get an HTML file using Python?
I am not very familiar with Python. I am trying to extract the artist names (for a start :)) from the following page: http://www.infolanka.com/miyuru_gee/art/art.html.

How do I retrieve the page? My two main concerns are; what functions to use and how to filter out useless links from the page?

答:
Use urllib2 to get the page.

Use BeautifulSoup to parse the HTML (the page) and get what you want!

ContentLicense: CC BY-SA 2.5

Title: How to get an HTML file using Python?


问:
How to create a table from a json api using HTML tables
We are using an api to retrieve data from MySQL database and turning it into a json file type. What would be the best way to get that data into an HTML table.

This is the api: https://nauticmc.com/dev/top.php?type=kills&start=0&end=9

Depending on what you change the type to it will change ascending order of the data I.E Kills will display the heights amount of kills first.

$(document).ready(function () {
    var json = [{"uuid":"ba6df9ff-84fa-464b-a231-d36782a7fdba","username":"zFrost87","kills":"19","deaths":"6","broken":"34","placed":"34","fish":"15","onlinetime":"9493","mobskilled":"6","crops":"1"},{"uuid":"b07762f3-38a4-45b7-9f21-6147704aee4b","username":"frechette456","kills":"3","deaths":"11","broken":"33","placed":"61","fish":"0","onlinetime":"1251","mobskilled":"1","crops":"7"},{"uuid":"83af0a86-7c09-4c32-8fa5-65db3c50b4cf","username":"MineManFrost","kills":"1","deaths":"2","broken":"16","placed":"1","fish":"0","onlinetime":"238","mobskilled":"0","crops":"0"},{"uuid":"71cb5612-d586-4390-ad78-05d295d6d2bd","username":"Nikolassparrow","kills":"0","deaths":"2","broken":"1","placed":"2","fish":"0","onlinetime":"30","mobskilled":"0","crops":"0"},{"uuid":"c34f51b5-8f2a-4e08-8b83-99d5faf21ea9","username":"SetupS1CK","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"81","mobskilled":"0","crops":"0"},{"uuid":"80212863-9466-4a4b-852e-5812e77d075b","username":"PickCottonNig","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"835","mobskilled":"0","crops":"0"},{"uuid":"a64de20f-91e7-4bb0-80db-4f7f1614d693","username":"OstenGaming","kills":"0","deaths":"0","broken":"1","placed":"0","fish":"0","onlinetime":"213","mobskilled":"0","crops":"0"},{"uuid":"25c60209-9fd4-42b8-a2b7-d78e01c0b3ae","username":"OpTc","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"9","mobskilled":"0","crops":"0"},{"uuid":"3a1dc4c7-e9ec-425e-ad50-54ae37c5f1a7","username":"AutoDolphin","kills":"0","deaths":"11","broken":"20","placed":"1","fish":"0","onlinetime":"444","mobskilled":"0","crops":"0"}];
    var tr;
    for (var i = 0; i < json.length; i++) {
        tr = $('
');
        tr.append("" + json[i].username + "	");
        tr.append("" + json[i].kills + "	");
        tr.append("" + json[i].deaths + "	");
        tr.append("" + json[i].broken + "	");
        tr.append("" + json[i].placed + "	");
        tr.append("" + json[i].fish + "	");
        tr.append("" + json[i].onlinetime + "	");
        tr.append("" + json[i].mobskilled + "	");
        tr.append("" + json[i].crops + "	");
        $('table').append(tr);
    }
});```

I am using Local JSON for now because Ajax does not allow access cross domain but I would parse it into a var to get it.

I also want people to be able to see what data is on top by corresponding arrows in each column I tried to use datatables.js but that did not work so well

This is just the table without any js or json

https://strixdesigns.com/Stats1/ < I want the arrows to work like this

答:
Another way to do this is to store the desired order in an array and add a nested loop to your logic. The advantage here is that you can change the order to whatever you'd like (username last, third, etc.) and your markup will not have to change to accommodate the reordering of fields.

$(document).ready(function () {
    var json = [{"uuid":"ba6df9ff-84fa-464b-a231-d36782a7fdba","username":"zFrost87","kills":"19","deaths":"6","broken":"34","placed":"34","fish":"15","onlinetime":"9493","mobskilled":"6","crops":"1"},{"uuid":"b07762f3-38a4-45b7-9f21-6147704aee4b","username":"frechette456","kills":"3","deaths":"11","broken":"33","placed":"61","fish":"0","onlinetime":"1251","mobskilled":"1","crops":"7"},{"uuid":"83af0a86-7c09-4c32-8fa5-65db3c50b4cf","username":"MineManFrost","kills":"1","deaths":"2","broken":"16","placed":"1","fish":"0","onlinetime":"238","mobskilled":"0","crops":"0"},{"uuid":"71cb5612-d586-4390-ad78-05d295d6d2bd","username":"Nikolassparrow","kills":"0","deaths":"2","broken":"1","placed":"2","fish":"0","onlinetime":"30","mobskilled":"0","crops":"0"},{"uuid":"c34f51b5-8f2a-4e08-8b83-99d5faf21ea9","username":"SetupS1CK","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"81","mobskilled":"0","crops":"0"},{"uuid":"80212863-9466-4a4b-852e-5812e77d075b","username":"PickCottonNig","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"835","mobskilled":"0","crops":"0"},{"uuid":"a64de20f-91e7-4bb0-80db-4f7f1614d693","username":"OstenGaming","kills":"0","deaths":"0","broken":"1","placed":"0","fish":"0","onlinetime":"213","mobskilled":"0","crops":"0"},{"uuid":"25c60209-9fd4-42b8-a2b7-d78e01c0b3ae","username":"OpTc","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"9","mobskilled":"0","crops":"0"},{"uuid":"3a1dc4c7-e9ec-425e-ad50-54ae37c5f1a7","username":"AutoDolphin","kills":"0","deaths":"11","broken":"20","placed":"1","fish":"0","onlinetime":"444","mobskilled":"0","crops":"0"}];
    var tr, th;
    var order = ['username', 'kills', 'deaths', 'broken', 'placed', 'fish', 'onlinetime', 'mobskilled', 'crops'];

    for (var i = 0; i < json.length; i++) {
      tr = $('
');
      th = $('
');

      if (i === 0) { // create table headers
        for (var j = 0; j < order.length; j++) {
          th.append("" + order[j] + "	");
          $('table').append(th)
        }
      }

      for (var j = 0; j < order.length; j++) {
        tr.append("" + json[i][order[j]] + "	");
        $('table').append(tr);
      }
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  font-family:Arial, Helvetica, sans-serif;
  color:#666;
  font-size:12px;
  text-shadow: 1px 1px 0px #fff;
  background:#eaebec;
  margin:20px;
  border:#ccc 1px solid;
  border-radius:3px;
  box-shadow: 0 1px 2px #d1d1d1;
  display: block;
  max-width: 100%;
  overflow: auto;
}

table th {
  padding:21px 25px 22px 25px;
  border-top:1px solid #fafafa;
  border-bottom:1px solid #e0e0e0;
  background: #ededed;
  background: -webkit-gradient(linear, left top, left bottom, from(#ededed), to(#ebebeb));
  background: -moz-linear-gradient(top,  #ededed,  #ebebeb);
}
table th:first-child {
  text-align: left;
  padding-left:20px;
}
table tr:first-child th:first-child {
  border-top-left-radius:3px;
}
table tr:first-child th:last-child {
  border-top-right-radius:3px;
}
table tr {
  text-align: center;
  padding-left:20px;
}
table td:first-child {
  text-align: left;
  padding-left:20px;
  border-left: 0;
}
table td {
  padding:18px;
  border-top: 1px solid #ffffff;
  border-bottom:1px solid #e0e0e0;
  border-left: 1px solid #e0e0e0;

  background: #fafafa;
  background: -webkit-gradient(linear, left top, left bottom, from(#fbfbfb), to(#fafafa));
  background: -moz-linear-gradient(top,  #fbfbfb,  #fafafa);
}
table tr.even td {
  background: #f6f6f6;
  background: -webkit-gradient(linear, left top, left bottom, from(#f8f8f8), to(#f6f6f6));
  background: -moz-linear-gradient(top,  #f8f8f8,  #f6f6f6);
}
table tr:last-child td {
  border-bottom:0;
}
table tr:last-child td:first-child {
  border-bottom-left-radius:3px;
}
table tr:last-child td:last-child {
  border-bottom-right-radius:3px;
}
table tr:hover td {
  background: #f2f2f2;
  background: -webkit-gradient(linear, left top, left bottom, from(#f2f2f2), to(#f0f0f0));
  background: -moz-linear-gradient(top,  #f2f2f2,  #f0f0f0);
}</code>```

```

Body:
We are using an api to retrieve data from MySQL database and turning it into a json file type. What would be the best way to get that data into an HTML table.

This is the api: https://nauticmc.com/dev/top.php?type=kills&start=0&end=9

Depending on what you change the type to it will change ascending order of the data I.E Kills will display the heights amount of kills first.

$(document).ready(function () {
    var json = [{"uuid":"ba6df9ff-84fa-464b-a231-d36782a7fdba","username":"zFrost87","kills":"19","deaths":"6","broken":"34","placed":"34","fish":"15","onlinetime":"9493","mobskilled":"6","crops":"1"},{"uuid":"b07762f3-38a4-45b7-9f21-6147704aee4b","username":"frechette456","kills":"3","deaths":"11","broken":"33","placed":"61","fish":"0","onlinetime":"1251","mobskilled":"1","crops":"7"},{"uuid":"83af0a86-7c09-4c32-8fa5-65db3c50b4cf","username":"MineManFrost","kills":"1","deaths":"2","broken":"16","placed":"1","fish":"0","onlinetime":"238","mobskilled":"0","crops":"0"},{"uuid":"71cb5612-d586-4390-ad78-05d295d6d2bd","username":"Nikolassparrow","kills":"0","deaths":"2","broken":"1","placed":"2","fish":"0","onlinetime":"30","mobskilled":"0","crops":"0"},{"uuid":"c34f51b5-8f2a-4e08-8b83-99d5faf21ea9","username":"SetupS1CK","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"81","mobskilled":"0","crops":"0"},{"uuid":"80212863-9466-4a4b-852e-5812e77d075b","username":"PickCottonNig","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"835","mobskilled":"0","crops":"0"},{"uuid":"a64de20f-91e7-4bb0-80db-4f7f1614d693","username":"OstenGaming","kills":"0","deaths":"0","broken":"1","placed":"0","fish":"0","onlinetime":"213","mobskilled":"0","crops":"0"},{"uuid":"25c60209-9fd4-42b8-a2b7-d78e01c0b3ae","username":"OpTc","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"9","mobskilled":"0","crops":"0"},{"uuid":"3a1dc4c7-e9ec-425e-ad50-54ae37c5f1a7","username":"AutoDolphin","kills":"0","deaths":"11","broken":"20","placed":"1","fish":"0","onlinetime":"444","mobskilled":"0","crops":"0"}];
    var tr;
    for (var i = 0; i < json.length; i++) {
        tr = $('
');
        tr.append("" + json[i].username + "	");
        tr.append("" + json[i].kills + "	");
        tr.append("" + json[i].deaths + "	");
        tr.append("" + json[i].broken + "	");
        tr.append("" + json[i].placed + "	");
        tr.append("" + json[i].fish + "	");
        tr.append("" + json[i].onlinetime + "	");
        tr.append("" + json[i].mobskilled + "	");
        tr.append("" + json[i].crops + "	");
        $('table').append(tr);
    }
});

I am using Local JSON for now because Ajax does not allow access cross domain but I would parse it into a var to get it.

I also want people to be able to see what data is on top by corresponding arrows in each column I tried to use datatables.js but that did not work so well

This is just the table without any js or json

https://strixdesigns.com/Stats1/ < I want the arrows to work like this

Body:
Another way to do this is to store the desired order in an array and add a nested loop to your logic. The advantage here is that you can change the order to whatever you'd like (username last, third, etc.) and your markup will not have to change to accommodate the reordering of fields.

$(document).ready(function () {
    var json = [{"uuid":"ba6df9ff-84fa-464b-a231-d36782a7fdba","username":"zFrost87","kills":"19","deaths":"6","broken":"34","placed":"34","fish":"15","onlinetime":"9493","mobskilled":"6","crops":"1"},{"uuid":"b07762f3-38a4-45b7-9f21-6147704aee4b","username":"frechette456","kills":"3","deaths":"11","broken":"33","placed":"61","fish":"0","onlinetime":"1251","mobskilled":"1","crops":"7"},{"uuid":"83af0a86-7c09-4c32-8fa5-65db3c50b4cf","username":"MineManFrost","kills":"1","deaths":"2","broken":"16","placed":"1","fish":"0","onlinetime":"238","mobskilled":"0","crops":"0"},{"uuid":"71cb5612-d586-4390-ad78-05d295d6d2bd","username":"Nikolassparrow","kills":"0","deaths":"2","broken":"1","placed":"2","fish":"0","onlinetime":"30","mobskilled":"0","crops":"0"},{"uuid":"c34f51b5-8f2a-4e08-8b83-99d5faf21ea9","username":"SetupS1CK","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"81","mobskilled":"0","crops":"0"},{"uuid":"80212863-9466-4a4b-852e-5812e77d075b","username":"PickCottonNig","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"835","mobskilled":"0","crops":"0"},{"uuid":"a64de20f-91e7-4bb0-80db-4f7f1614d693","username":"OstenGaming","kills":"0","deaths":"0","broken":"1","placed":"0","fish":"0","onlinetime":"213","mobskilled":"0","crops":"0"},{"uuid":"25c60209-9fd4-42b8-a2b7-d78e01c0b3ae","username":"OpTc","kills":"0","deaths":"0","broken":"0","placed":"0","fish":"0","onlinetime":"9","mobskilled":"0","crops":"0"},{"uuid":"3a1dc4c7-e9ec-425e-ad50-54ae37c5f1a7","username":"AutoDolphin","kills":"0","deaths":"11","broken":"20","placed":"1","fish":"0","onlinetime":"444","mobskilled":"0","crops":"0"}];
    var tr, th;
    var order = ['username', 'kills', 'deaths', 'broken', 'placed', 'fish', 'onlinetime', 'mobskilled', 'crops'];

    for (var i = 0; i < json.length; i++) {
      tr = $('<tr/>');
      th = $('<tr/>');

      if (i === 0) { // create table headers
        for (var j = 0; j < order.length; j++) {
          th.append("<th>" + order[j] + "</th>");
          $('table').append(th)
        }
      }

      for (var j = 0; j < order.length; j++) {
        tr.append("<td>" + json[i][order[j]] + "</td>");
        $('table').append(tr);
      }
    }
});

table {
  font-family:Arial, Helvetica, sans-serif;
  color:#666;
  font-size:12px;
  text-shadow: 1px 1px 0px #fff;
  background:#eaebec;
  margin:20px;
  border:#ccc 1px solid;
  border-radius:3px;
  box-shadow: 0 1px 2px #d1d1d1;
  display: block;
  max-width: 100%;
  overflow: auto;
}

table th {
  padding:21px 25px 22px 25px;
  border-top:1px solid #fafafa;
  border-bottom:1px solid #e0e0e0;
  background: #ededed;
  background: -webkit-gradient(linear, left top, left bottom, from(#ededed), to(#ebebeb));
  background: -moz-linear-gradient(top,  #ededed,  #ebebeb);
}
table th:first-child {
  text-align: left;
  padding-left:20px;
}
table tr:first-child th:first-child {
  border-top-left-radius:3px;
}
table tr:first-child th:last-child {
  border-top-right-radius:3px;
}
table tr {
  text-align: center;
  padding-left:20px;
}
table td:first-child {
  text-align: left;
  padding-left:20px;
  border-left: 0;
}
table td {
  padding:18px;
  border-top: 1px solid #ffffff;
  border-bottom:1px solid #e0e0e0;
  border-left: 1px solid #e0e0e0;

  background: #fafafa;
  background: -webkit-gradient(linear, left top, left bottom, from(#fbfbfb), to(#fafafa));
  background: -moz-linear-gradient(top,  #fbfbfb,  #fafafa);
}
table tr.even td {
  background: #f6f6f6;
  background: -webkit-gradient(linear, left top, left bottom, from(#f8f8f8), to(#f6f6f6));
  background: -moz-linear-gradient(top,  #f8f8f8,  #f6f6f6);
}
table tr:last-child td {
  border-bottom:0;
}
table tr:last-child td:first-child {
  border-bottom-left-radius:3px;
}
table tr:last-child td:last-child {
  border-bottom-right-radius:3px;
}
table tr:hover td {
  background: #f2f2f2;
  background: -webkit-gradient(linear, left top, left bottom, from(#f2f2f2), to(#f0f0f0));
  background: -moz-linear-gradient(top,  #f2f2f2,  #f0f0f0);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table></table>


问:
Cant increase the size of whole chart in bokeh and make the chart in horizontal axis
Hi I have data in the below Dataframe :

I want to plot in a basic bar chart using Bokeh library but I can't increase the plot area so i am not getting a better looking graph due to variables > 50.

Any help/direction appreciated.

Also i want to plot in horizontal way.
Thank you !!

答:
For bokeh.charts usage, you can update chart defaults:

```<code>from bokeh.charts import defaults

defaults.width = 450
defaults.height = 350
</code>```

However, please note: bokeh.charts is effectively unmaintained at this point. I would actively discourage its use. The officially endorsed and recommended "High Level" API for use on top of Bokeh will be HoloViews (http://holoviews.org/) going forward. It is already much more capable than the the old bokeh.charts API and more importantly, very actively maintained. I would recommend to anyone to switch to it.

Body:
For bokeh.charts usage, you can update chart defaults:

from bokeh.charts import defaults

defaults.width = 450
defaults.height = 350

However, please note: bokeh.charts is effectively unmaintained at this point. I would actively discourage its use. The officially endorsed and recommended "High Level" API for use on top of Bokeh will be HoloViews (http://holoviews.org/) going forward. It is already much more capable than the the old bokeh.charts API and more importantly, very actively maintained. I would recommend to anyone to switch to it.


问:
MS Word 2010 Could not open macro storage
I am creating Word Document Using Word Template

Following is code

```<code>  Word.Document wordDoc = new Word.Document();
 wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
</code>```

i am getting error Could not open macro storage. I apply DCOM security permission and all Read/Write permission.

My Server is Windows 2008 Professorial & IIS 7

答: I've seen this error happen when a document is loaded from a template but the template is NOT in a 'trusted' location. Happens with or without macros in the specified template.</p>

Body:
I am creating Word Document Using Word Template

Following is code

  Word.Document wordDoc = new Word.Document();
 wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

i am getting error Could not open macro storage. I apply DCOM security permission and all Read/Write permission.

My Server is Windows 2008 Professorial & IIS 7


答:
You could try creating a custom ToolstripMenuItem, and override the WndProc Method.

The override can capture the windows messages, and notify when the click is not on the item.  The following code is adapted from code to close a form if the user clicks outside it, but it should suit your purposes.

```<code>/// <summary>
    /// Function to capture if the user clicks outside of the control, in which case need to close this form.
    /// </summary>
    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);

        // if click outside dialog -> Close Dlg
        if (m.Msg == 0x86) //0x86 = NativeConstants.WM_NCACTIVATE
        {
            if (this.Visible)
            {
                if (!this.RectangleToScreen(this.DisplayRectangle).Contains(Cursor.Position))
                    QuitVar = 0;
            }
        }
    }
</code>```

Title: Need to have button change text when clicked, then change back when outside click

Body:
You could try creating a custom ToolstripMenuItem, and override the WndProc Method.

The override can capture the windows messages, and notify when the click is not on the item.  The following code is adapted from code to close a form if the user clicks outside it, but it should suit your purposes.

/// <summary>
    /// Function to capture if the user clicks outside of the control, in which case need to close this form.
    /// </summary>
    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);

        // if click outside dialog -> Close Dlg
        if (m.Msg == 0x86) //0x86 = NativeConstants.WM_NCACTIVATE
        {
            if (this.Visible)
            {
                if (!this.RectangleToScreen(this.DisplayRectangle).Contains(Cursor.Position))
                    QuitVar = 0;
            }
        }
    }


问:
PHP upload requests not concurrent
I'm using the Blueimp jQuery File Uploader to handle multiple file uploads.

It works fine with one exception: It doesn't upload files concurrently but waits for one request to finish to start the other. It seems to be on the side of Apache/PHP because the requests are initiated at the same time and waiting for each other to finish.

Here's my waterfall:

My uploadImage function only has sleep(1); die(); for this test.

Shouldn't it make 5 requests simultaneously for a total of 1 second instead of 5 seconds sequentially? I wouldn't know how to do this even if i wanted to. Is this php setting or Apache?

答:
My gut feeling is you probably use sessions in your upload script, and they all fight to get the session lock. Well, actually they don't fight, they just wait for the lock to be release before doing anything.

There's a detailed description of the issue here:
http://konrness.com/php5/how-to-prevent-blocking-php-requests/

See if you can avoid sessions, or close them as soon as possible (aka, get what you need from the session, close it, and then sleep(1).

Title: PHP upload requests not concurrent


问:
Rails 3: Social Stream Gem. Where is the code?
I've installed social_stream according to the README ( https://github.com/ging/social_stream ) and it works fine, however, I'd like to have the code in my app/ directory and the code isn't there.

The same question arises for Devise and other gems. When I install it, I'd like to have access to the controllers, models, views, etc but it seems nothing is in the app/.

What do I have to do in order to put the code there and being able to change it as I'd like? Or, access it in other folder.

Thank you

答: I don't know these plugins specifically, but Rails plugins in general get put in vendor/plugins.


问:
When I use an PaintComponent to my JFrame, I have to resize my window to get it to show up unless I use pack. How can I remedy this?
I am creating a Blackjack game, and I'm trying to get cards to show up on top of the table image when the hit button is hit. However, they keep showing up to the side of the table image, and only either show up a. when I use the pack() method in the ActionListener, or if I don't use pack(), when I resize the window.

My Code:

```<code>import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;

public class BlackjackTable3 extends JFrame {

  JButton stayButton = new JButton("STAY");
  JButton hitButton = new JButton("HIT");
  JPanel mainPanel = new JPanel();

  public BlackjackTable3() {
    this.setTitle("Blackjack Test Table");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel tablePanel = new JPanel();
    ImageIcon pic = new ImageIcon("blackjackTableCanvas.jpg");
    mainPanel.add(new JLabel(pic), BorderLayout.NORTH);

    this.add(mainPanel);
    this.setSize(1600,1600);
    this.setVisible(true);

    JPanel buttonPanel = new JPanel();
    ActionListener pressChoice = new DecisionListener();
    hitButton.addActionListener(pressChoice);
    stayButton.addActionListener(pressChoice);

    buttonPanel.setSize(300,150);
    buttonPanel.add(hitButton,BorderLayout.WEST);
   buttonPanel.add(stayButton,BorderLayout.EAST);
    buttonPanel.setVisible(true);
    this.add(buttonPanel, BorderLayout.SOUTH);

  }

  class DecisionListener implements ActionListener{

    public void actionPerformed(ActionEvent a){
      //code for hit/stay to go here

      if(a.getSource() == hitButton){
        System.out.println("YOU CHOSE HIT!");
        CardRender2 c = new CardRender2(new Card());

        mainPanel.add(c, BorderLayout.CENTER);
        pack();
      }
      else if(a.getSource() == stayButton){
        System.out.println("YOU CHOSE STAY!");
      }

    }
  }

  public static void main(String[] args){
    BlackjackTable3 b = new BlackjackTable3();

  }

}
</code>```

My CardRender2 code:

```<code>public class CardRender2 extends JComponent{
public CardRender2(Card card) {
  this.val = card.value.face;
    this.suit = card.suit.toString();
    String filename = this.fetchCardFileLabel();
    try {
        image = ImageIO.read(new File("card deck\\" + filename + ".png"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    JLabel j = new JLabel();
    j.add(this);

}

@Override
protected void paintComponent(Graphics g) {
  Graphics2D g2 = (Graphics2D) g;
    super.paintComponent(g2);
    g2.drawImage(image, 0, 0, null);

}
...}
</code>```

I tried using repaint(), and I can't use paint bc I get a compiler error. How can I fix this issue?

答:
how can I place these cards OVER, ON TOP OF, the table image?

You need a hierarchy of components something like:

JFrame

background component with image

card component with image

One way is to use labels to contain your images:

```<code>JLabel card = new JLabel(...);
JLabel background = new JLabel(...);
background.setLayout( new FlowLayout() );
background.add( card );
frame.add(background, BorderLayout.CENTER);
</code>```

This will only work if the background image is bigger than your card component.

Body:
I am creating a Blackjack game, and I'm trying to get cards to show up on top of the table image when the hit button is hit. However, they keep showing up to the side of the table image, and only either show up a. when I use the pack() method in the ActionListener, or if I don't use pack(), when I resize the window.

My Code:

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;

public class BlackjackTable3 extends JFrame {

  JButton stayButton = new JButton("STAY");
  JButton hitButton = new JButton("HIT");
  JPanel mainPanel = new JPanel();

  public BlackjackTable3() {
    this.setTitle("Blackjack Test Table");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel tablePanel = new JPanel();
    ImageIcon pic = new ImageIcon("blackjackTableCanvas.jpg");
    mainPanel.add(new JLabel(pic), BorderLayout.NORTH);

    this.add(mainPanel);
    this.setSize(1600,1600);
    this.setVisible(true);

    JPanel buttonPanel = new JPanel();
    ActionListener pressChoice = new DecisionListener();
    hitButton.addActionListener(pressChoice);
    stayButton.addActionListener(pressChoice);

    buttonPanel.setSize(300,150);
    buttonPanel.add(hitButton,BorderLayout.WEST);
   buttonPanel.add(stayButton,BorderLayout.EAST);
    buttonPanel.setVisible(true);
    this.add(buttonPanel, BorderLayout.SOUTH);

  }

  class DecisionListener implements ActionListener{

    public void actionPerformed(ActionEvent a){
      //code for hit/stay to go here

      if(a.getSource() == hitButton){
        System.out.println("YOU CHOSE HIT!");
        CardRender2 c = new CardRender2(new Card());

        mainPanel.add(c, BorderLayout.CENTER);
        pack();
      }
      else if(a.getSource() == stayButton){
        System.out.println("YOU CHOSE STAY!");
      }

    }
  }

  public static void main(String[] args){
    BlackjackTable3 b = new BlackjackTable3();

  }

}

My CardRender2 code:

public class CardRender2 extends JComponent{
public CardRender2(Card card) {
  this.val = card.value.face;
    this.suit = card.suit.toString();
    String filename = this.fetchCardFileLabel();
    try {
        image = ImageIO.read(new File("card deck\\" + filename + ".png"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    JLabel j = new JLabel();
    j.add(this);

}

@Override
protected void paintComponent(Graphics g) {
  Graphics2D g2 = (Graphics2D) g;
    super.paintComponent(g2);
    g2.drawImage(image, 0, 0, null);

}
...}

I tried using repaint(), and I can't use paint bc I get a compiler error. How can I fix this issue?

Body:
how can I place these cards OVER, ON TOP OF, the table image?

You need a hierarchy of components something like:

JFrame

background component with image

card component with image

One way is to use labels to contain your images:

JLabel card = new JLabel(...);
JLabel background = new JLabel(...);
background.setLayout( new FlowLayout() );
background.add( card );
frame.add(background, BorderLayout.CENTER);

This will only work if the background image is bigger than your card component.


问:
Sum all documents for a field within an array
I just want to know about count in mongodb through php. In this case, I have document looks like this:

```<code>{
"_id": 1,
"item" : [
{ "name": "foo",
"price": 1000
},
{ "name": "bar",
"price": 500
}
]
}

{
"_id": 2,
"item" : [
{ "name": "foo",
"price": 1000
}
]
}
</code>```

When I was using the following code like this:

```<code>$connection = new MongoClient();
$db = $connection->shop;
$collection = $db->sales;
$pipe = array(array('$unwind'=>'$item'),
array('$group'=>array('_id'=>array('_id'=>'1','result'=>array('$sum'=>'$item.price')))));
$total = $collection->aggregateCursor($pipe);
foreach ($total as $dc){
$total_price = $dc['result'];
}
echo "<b>Result of all this customer : </b>".$total_price."<br>";
</code>```

The result of that code is looks like the result of all document such as:

```<code>Result of all this customer : 2500
</code>```

In other side as I wish, the result has counted for each id not for count all of document that I had. What's wrong with that code ?

I hope, the result of this case:

```<code>Result of all this customer : 1500
</code>```

Please someone help me...

The following answer that I found, maybe it will be helping someone who had same trouble.

```<code>$connection = new MongoClient();
    $db = $connection->shop;
    $collection = $db->sales;
    $pipe = array(array('$unwind'=>'$item'),array('$match'=>array('_id'=>'1')), array('$group'=>array('_id'=>array('_id'=>'1','result'=>array('$sum'=>'$item.price')))));
    $total = $collection->aggregateCursor($pipe);
    foreach ($total as $dc){
    $total_price = $dc['result'];
    }
    echo "<b>Result of all this customer : </b>".$total_price."<br>";
</code>```

Added $match for sorting an id, and that query will check only embedded document with targeted id.

答:
Here is the aggregation. If you remove match stage, it will give a sum for every user.</p>

```<code>> db.product.aggregate(
...    [
...       {
...          $match: {'_id':{ '$eq': 1}}
...       },
...       {
...           $unwind: '$item'
...       },
...       {
...         $group : {
...            _id : '$_id',
...            totalPrice: { $sum: '$item.price' },
...         }
...       }
...    ]
... )
{ "_id" : 1, "totalPrice" : 1500 }
</code>```

Body:
I just want to know about count in mongodb through php. In this case, I have document looks like this:

{
"_id": 1,
"item" : [
{ "name": "foo",
"price": 1000
},
{ "name": "bar",
"price": 500
}
]
}

{
"_id": 2,
"item" : [
{ "name": "foo",
"price": 1000
}
]
}

When I was using the following code like this:

$connection = new MongoClient();
$db = $connection->shop;
$collection = $db->sales;
$pipe = array(array('$unwind'=>'$item'),
array('$group'=>array('_id'=>array('_id'=>'1','result'=>array('$sum'=>'$item.price')))));
$total = $collection->aggregateCursor($pipe);
foreach ($total as $dc){
$total_price = $dc['result'];
}
echo "Result of all this customer : ".$total_price."
";

The result of that code is looks like the result of all document such as:

Result of all this customer : 2500

In other side as I wish, the result has counted for each id not for count all of document that I had. What's wrong with that code ?

I hope, the result of this case:

Result of all this customer : 1500

Please someone help me...

The following answer that I found, maybe it will be helping someone who had same trouble.

$connection = new MongoClient();
    $db = $connection->shop;
    $collection = $db->sales;
    $pipe = array(array('$unwind'=>'$item'),array('$match'=>array('_id'=>'1')), array('$group'=>array('_id'=>array('_id'=>'1','result'=>array('$sum'=>'$item.price')))));
    $total = $collection->aggregateCursor($pipe);
    foreach ($total as $dc){
    $total_price = $dc['result'];
    }
    echo "Result of all this customer : ".$total_price."
";

Added $match for sorting an id, and that query will check only embedded document with targeted id.

Body:
Here is the aggregation. If you remove match stage, it will give a sum for every user.

> db.product.aggregate(
...    [
...       {
...          $match: {'_id':{ '$eq': 1}}
...       },
...       {
...           $unwind: '$item'
...       },
...       {
...         $group : {
...            _id : '$_id',
...            totalPrice: { $sum: '$item.price' },
...         }
...       }
...    ]
... )
{ "_id" : 1, "totalPrice" : 1500 }


问:
d3 center tick and x-axis label when single value
I have the following d3 code:

```<code>                var json = [
                {
                    date: "05/17",
                    numTags: 23
                }
            ];

            d3.select('summary-graph').selectAll('*').remove();

            var svg = d3.select("summary-graph"),
                margin = {
                    top: 20,
                    right: 30,
                    bottom: 30,
                    left: 40
                },
                width = svg.attr("width") - margin.left - margin.right,
                height = svg.attr("height") - margin.top - margin.bottom;

            var parseTime = d3.timeParse("%m/%y");

            var svg = d3.select("summary-graph").append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g")
                .attr("transform",
                    "translate(" + margin.left + "," + margin.top + ")");

            // Get the data
            var data = json;

            // format the data
            data.forEach(function (d) {
                console.log(d);
                d.date = parseTime(d.date);
                d.numTags = +d.numTags;
            });

            // set the ranges
            var xScale = d3.scaleTime()
                            .range([0, width])
                            .domain(d3.extent(data, function (d) {
                                return d.date;
                            }))
                            .nice();

            var yScale = d3.scaleLinear()
                            .range([height, 0])
                            .domain([0, d3.max(data, function (d) {
                                return Math.max(d.numTags);
                            })])
                            .nice();

            // define the 1st line
            var tagLine = d3.line()
                .x(function (d) {
                    return xScale(d.date);
                })
                .y(function (d) {
                    return yScale(d.numTags);
                });

            // Axes
            var xAxis = d3.axisBottom()
                          .scale(xScale)
                          .ticks(json.length)
                          .tickSizeOuter(0)
                          .tickFormat(d3.timeFormat('%B %Y'));

            var yAxis = d3.axisLeft().scale(yScale);

            svg.append("path")
                .data([data])
                .attr("class", "line")
                .style("stroke", "blue")
                .attr("d", tagLine);

            var points = svg.selectAll(".point")
                    .data(data)
                    .enter().append("svg:circle")
                     .attr("stroke", "green")
                     .attr("fill", function(d, i) { return "blue" })
                     .attr("cx", function(d, i) { return xScale(d.date) })
                     .attr("cy", function(d, i) { return yScale(d.numTags) })
                     .attr("r", function(d, i) { return 10 });

            // Add the X Axis
            svg.append("g")
                .attr("transform", "translate(0," + height + ")")
                .call(xAxis)
                .style("font-size","14px");;

            // Add the Y Axis
            svg.append("g")
                .call(yAxis);
</code>```

Which produces the following visualization:

I'm trying to figure out how to center the tick mark and show the x-axis label when there is only 1 data point like this. At 2 data points, I don't love how it still sets the tick marks at the extreme ends of the x-axis. For 3 data points and above, it looks nice (thanks to .nice() it seems).

Any help?

Based on Gerado's response, I was able to get close. The last sticking point is that the left side of the X-axis now has the month (March) despite no data for that day.

Fixed:
changed .ticks(json.length) to .ticks(d3.timeMonth.every(1))

答:
Since you are using only a single data point, your date scale has a domain in which the lower and upper values are the same:

```<code>[
    Mon May 01 2017 00: 00: 00 GMT + 1000,
    Mon May 01 2017 00: 00: 00 GMT + 1000
]
</code>```

For putting that circle in the middle of the x axis you have to set different values for the scale's domain.

There are several ways for doing that. My proposed solution here involves verifying if the domain's values are the same...

```<code>if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
</code>```

... and, if they are, changing them. In this case, I'm subtracting one day from the lower limit and adding one day to the upper limit:

```<code>if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
    var dateLess = d3.timeDay.offset(xScale.domain()[0], -1);
    var dateMore = d3.timeDay.offset(xScale.domain()[0], 1);
    xScale.domain([dateLess, dateMore])
}
</code>```

Check the result:

var json = [{
  date: "05/17",
  numTags: 23
}];

var margin = {
    top: 20,
    right: 30,
    bottom: 30,
    left: 40
  },
  width = 400,
  height = 200;

var parseTime = d3.timeParse("%m/%y");

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");

// Get the data
var data = json;

// format the data
data.forEach(function(d) {
  d.date = parseTime(d.date);
  d.numTags = +d.numTags;
});

// set the ranges
var xScale = d3.scaleTime()
  .range([0, width])
  .domain(d3.extent(data, function(d) {
    return d.date;
  }))
  .nice();

if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
  var dateLess = d3.timeDay.offset(xScale.domain()[0], -1);
  var dateMore = d3.timeDay.offset(xScale.domain()[0], 1);
  xScale.domain([dateLess, dateMore])
}

var yScale = d3.scaleLinear()
  .range([height, 0])
  .domain([0, d3.max(data, function(d) {
    return Math.max(d.numTags);
  })])
  .nice();

// define the 1st line
var tagLine = d3.line()
  .x(function(d) {
    return xScale(d.date);
  })
  .y(function(d) {
    return yScale(d.numTags);
  });

// Axes
var xAxis = d3.axisBottom()
  .scale(xScale)
  .ticks(json.length)
  .tickSizeOuter(0)
  .tickFormat(d3.timeFormat('%B %Y'));

var yAxis = d3.axisLeft().scale(yScale);

svg.append("path")
  .data([data])
  .attr("class", "line")
  .style("stroke", "blue")
  .attr("d", tagLine);

var points = svg.selectAll(".point")
  .data(data)
  .enter().append("svg:circle")
  .attr("stroke", "green")
  .attr("fill", function(d, i) {
    return "blue"
  })
  .attr("cx", function(d, i) {
    return xScale(d.date)
  })
  .attr("cy", function(d, i) {
    return yScale(d.numTags)
  })
  .attr("r", function(d, i) {
    return 10
  });

// Add the X Axis
svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)
  .style("font-size", "14px");;

// Add the Y Axis
svg.append("g")
  .call(yAxis);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.js"></script></code>```

EDIT: As you asked in your edit, when you have two data values my solution will create additional ticks on the limits, which is the expected behaviour:

var json = [{
  date: "05/17",
  numTags: 23
}, {
  date: "05/17",
  numTags: 17
}];

var margin = {
    top: 20,
    right: 30,
    bottom: 30,
    left: 40
  },
  width = 400,
  height = 200;

var parseTime = d3.timeParse("%m/%y");

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");

// Get the data
var data = json;

// format the data
data.forEach(function(d) {
  d.date = parseTime(d.date);
  d.numTags = +d.numTags;
});

// set the ranges
var xScale = d3.scaleTime()
  .range([0, width])
  .domain(d3.extent(data, function(d) {
    return d.date;
  }))
  .nice();

if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
  var dateLess = d3.timeDay.offset(xScale.domain()[0], -1);
  var dateMore = d3.timeDay.offset(xScale.domain()[0], 1);
  xScale.domain([dateLess, dateMore])
}

var yScale = d3.scaleLinear()
  .range([height, 0])
  .domain([0, d3.max(data, function(d) {
    return Math.max(d.numTags);
  })])
  .nice();

// define the 1st line
var tagLine = d3.line()
  .x(function(d) {
    return xScale(d.date);
  })
  .y(function(d) {
    return yScale(d.numTags);
  });

// Axes
var xAxis = d3.axisBottom()
  .scale(xScale)
  .ticks(json.length)
  .tickSizeOuter(0)
  .tickFormat(d3.timeFormat('%B %Y'));

var yAxis = d3.axisLeft().scale(yScale);

svg.append("path")
  .data([data])
  .attr("class", "line")
  .style("stroke", "blue")
  .attr("d", tagLine);

var points = svg.selectAll(".point")
  .data(data)
  .enter().append("svg:circle")
  .attr("stroke", "green")
  .attr("fill", function(d, i) {
    return "blue"
  })
  .attr("cx", function(d, i) {
    return xScale(d.date)
  })
  .attr("cy", function(d, i) {
    return yScale(d.numTags)
  })
  .attr("r", function(d, i) {
    return 10
  });

// Add the X Axis
svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)
  .style("font-size", "14px");;

// Add the Y Axis
svg.append("g")
  .call(yAxis);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.js"></script></code>```

There are several ways for removing those ticks. One of them is using tickValues:

```<code>.tickValues(data.map(function(d){ return d.date}))
</code>```

Here is the demo:

var json = [{
  date: "05/17",
  numTags: 23
}, {
  date: "05/17",
  numTags: 17
}];

var margin = {
    top: 20,
    right: 30,
    bottom: 30,
    left: 40
  },
  width = 400,
  height = 200;

var parseTime = d3.timeParse("%m/%y");

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");

// Get the data
var data = json;

// format the data
data.forEach(function(d) {
  d.date = parseTime(d.date);
  d.numTags = +d.numTags;
});

// set the ranges
var xScale = d3.scaleTime()
  .range([0, width])
  .domain(d3.extent(data, function(d) {
    return d.date;
  }))
  .nice();

if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
  var dateLess = d3.timeDay.offset(xScale.domain()[0], -1);
  var dateMore = d3.timeDay.offset(xScale.domain()[0], 1);
  xScale.domain([dateLess, dateMore])
}

var yScale = d3.scaleLinear()
  .range([height, 0])
  .domain([0, d3.max(data, function(d) {
    return Math.max(d.numTags);
  })])
  .nice();

// define the 1st line
var tagLine = d3.line()
  .x(function(d) {
    return xScale(d.date);
  })
  .y(function(d) {
    return yScale(d.numTags);
  });

// Axes
var xAxis = d3.axisBottom()
  .scale(xScale)
  .ticks(json.length)
  .tickSizeOuter(0)
  .tickValues(data.map(function(d){ return d.date}))
  .tickFormat(d3.timeFormat('%B %Y'));

var yAxis = d3.axisLeft().scale(yScale);

svg.append("path")
  .data([data])
  .attr("class", "line")
  .style("stroke", "blue")
  .attr("d", tagLine);

var points = svg.selectAll(".point")
  .data(data)
  .enter().append("svg:circle")
  .attr("stroke", "green")
  .attr("fill", function(d, i) {
    return "blue"
  })
  .attr("cx", function(d, i) {
    return xScale(d.date)
  })
  .attr("cy", function(d, i) {
    return yScale(d.numTags)
  })
  .attr("r", function(d, i) {
    return 10
  });

// Add the X Axis
svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)
  .style("font-size", "14px");;

// Add the Y Axis
svg.append("g")
  .call(yAxis);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.js"></script></code>```

Body:
I have the following d3 code:

                var json = [
                {
                    date: "05/17",
                    numTags: 23
                }
            ];

            d3.select('summary-graph').selectAll('*').remove();

            var svg = d3.select("summary-graph"),
                margin = {
                    top: 20,
                    right: 30,
                    bottom: 30,
                    left: 40
                },
                width = svg.attr("width") - margin.left - margin.right,
                height = svg.attr("height") - margin.top - margin.bottom;

            var parseTime = d3.timeParse("%m/%y");

            var svg = d3.select("summary-graph").append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g")
                .attr("transform",
                    "translate(" + margin.left + "," + margin.top + ")");

            // Get the data
            var data = json;

            // format the data
            data.forEach(function (d) {
                console.log(d);
                d.date = parseTime(d.date);
                d.numTags = +d.numTags;
            });

            // set the ranges
            var xScale = d3.scaleTime()
                            .range([0, width])
                            .domain(d3.extent(data, function (d) {
                                return d.date;
                            }))
                            .nice();

            var yScale = d3.scaleLinear()
                            .range([height, 0])
                            .domain([0, d3.max(data, function (d) {
                                return Math.max(d.numTags);
                            })])
                            .nice();

            // define the 1st line
            var tagLine = d3.line()
                .x(function (d) {
                    return xScale(d.date);
                })
                .y(function (d) {
                    return yScale(d.numTags);
                });

            // Axes
            var xAxis = d3.axisBottom()
                          .scale(xScale)
                          .ticks(json.length)
                          .tickSizeOuter(0)
                          .tickFormat(d3.timeFormat('%B %Y'));

            var yAxis = d3.axisLeft().scale(yScale);

            svg.append("path")
                .data([data])
                .attr("class", "line")
                .style("stroke", "blue")
                .attr("d", tagLine);

            var points = svg.selectAll(".point")
                    .data(data)
                    .enter().append("svg:circle")
                     .attr("stroke", "green")
                     .attr("fill", function(d, i) { return "blue" })
                     .attr("cx", function(d, i) { return xScale(d.date) })
                     .attr("cy", function(d, i) { return yScale(d.numTags) })
                     .attr("r", function(d, i) { return 10 });

            // Add the X Axis
            svg.append("g")
                .attr("transform", "translate(0," + height + ")")
                .call(xAxis)
                .style("font-size","14px");;

            // Add the Y Axis
            svg.append("g")
                .call(yAxis);

Which produces the following visualization:

I'm trying to figure out how to center the tick mark and show the x-axis label when there is only 1 data point like this. At 2 data points, I don't love how it still sets the tick marks at the extreme ends of the x-axis. For 3 data points and above, it looks nice (thanks to .nice() it seems).

Any help?

Based on Gerado's response, I was able to get close. The last sticking point is that the left side of the X-axis now has the month (March) despite no data for that day.

Fixed:
changed .ticks(json.length) to .ticks(d3.timeMonth.every(1))

Body:
Since you are using only a single data point, your date scale has a domain in which the lower and upper values are the same:

[
    Mon May 01 2017 00: 00: 00 GMT + 1000,
    Mon May 01 2017 00: 00: 00 GMT + 1000
]

For putting that circle in the middle of the x axis you have to set different values for the scale's domain.

There are several ways for doing that. My proposed solution here involves verifying if the domain's values are the same...

if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {

... and, if they are, changing them. In this case, I'm subtracting one day from the lower limit and adding one day to the upper limit:

if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
    var dateLess = d3.timeDay.offset(xScale.domain()[0], -1);
    var dateMore = d3.timeDay.offset(xScale.domain()[0], 1);
    xScale.domain([dateLess, dateMore])
}

Check the result:

var json = [{
  date: "05/17",
  numTags: 23
}];

var margin = {
    top: 20,
    right: 30,
    bottom: 30,
    left: 40
  },
  width = 400,
  height = 200;

var parseTime = d3.timeParse("%m/%y");

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");

// Get the data
var data = json;

// format the data
data.forEach(function(d) {
  d.date = parseTime(d.date);
  d.numTags = +d.numTags;
});

// set the ranges
var xScale = d3.scaleTime()
  .range([0, width])
  .domain(d3.extent(data, function(d) {
    return d.date;
  }))
  .nice();

if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
  var dateLess = d3.timeDay.offset(xScale.domain()[0], -1);
  var dateMore = d3.timeDay.offset(xScale.domain()[0], 1);
  xScale.domain([dateLess, dateMore])
}

var yScale = d3.scaleLinear()
  .range([height, 0])
  .domain([0, d3.max(data, function(d) {
    return Math.max(d.numTags);
  })])
  .nice();

// define the 1st line
var tagLine = d3.line()
  .x(function(d) {
    return xScale(d.date);
  })
  .y(function(d) {
    return yScale(d.numTags);
  });

// Axes
var xAxis = d3.axisBottom()
  .scale(xScale)
  .ticks(json.length)
  .tickSizeOuter(0)
  .tickFormat(d3.timeFormat('%B %Y'));

var yAxis = d3.axisLeft().scale(yScale);

svg.append("path")
  .data([data])
  .attr("class", "line")
  .style("stroke", "blue")
  .attr("d", tagLine);

var points = svg.selectAll(".point")
  .data(data)
  .enter().append("svg:circle")
  .attr("stroke", "green")
  .attr("fill", function(d, i) {
    return "blue"
  })
  .attr("cx", function(d, i) {
    return xScale(d.date)
  })
  .attr("cy", function(d, i) {
    return yScale(d.numTags)
  })
  .attr("r", function(d, i) {
    return 10
  });

// Add the X Axis
svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)
  .style("font-size", "14px");;

// Add the Y Axis
svg.append("g")
  .call(yAxis);

<script src="https://d3js.org/d3.v4.js"></script>

EDIT: As you asked in your edit, when you have two data values my solution will create additional ticks on the limits, which is the expected behaviour:

var json = [{
  date: "05/17",
  numTags: 23
}, {
  date: "05/17",
  numTags: 17
}];

var margin = {
    top: 20,
    right: 30,
    bottom: 30,
    left: 40
  },
  width = 400,
  height = 200;

var parseTime = d3.timeParse("%m/%y");

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");

// Get the data
var data = json;

// format the data
data.forEach(function(d) {
  d.date = parseTime(d.date);
  d.numTags = +d.numTags;
});

// set the ranges
var xScale = d3.scaleTime()
  .range([0, width])
  .domain(d3.extent(data, function(d) {
    return d.date;
  }))
  .nice();

if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
  var dateLess = d3.timeDay.offset(xScale.domain()[0], -1);
  var dateMore = d3.timeDay.offset(xScale.domain()[0], 1);
  xScale.domain([dateLess, dateMore])
}

var yScale = d3.scaleLinear()
  .range([height, 0])
  .domain([0, d3.max(data, function(d) {
    return Math.max(d.numTags);
  })])
  .nice();

// define the 1st line
var tagLine = d3.line()
  .x(function(d) {
    return xScale(d.date);
  })
  .y(function(d) {
    return yScale(d.numTags);
  });

// Axes
var xAxis = d3.axisBottom()
  .scale(xScale)
  .ticks(json.length)
  .tickSizeOuter(0)
  .tickFormat(d3.timeFormat('%B %Y'));

var yAxis = d3.axisLeft().scale(yScale);

svg.append("path")
  .data([data])
  .attr("class", "line")
  .style("stroke", "blue")
  .attr("d", tagLine);

var points = svg.selectAll(".point")
  .data(data)
  .enter().append("svg:circle")
  .attr("stroke", "green")
  .attr("fill", function(d, i) {
    return "blue"
  })
  .attr("cx", function(d, i) {
    return xScale(d.date)
  })
  .attr("cy", function(d, i) {
    return yScale(d.numTags)
  })
  .attr("r", function(d, i) {
    return 10
  });

// Add the X Axis
svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)
  .style("font-size", "14px");;

// Add the Y Axis
svg.append("g")
  .call(yAxis);

<script src="https://d3js.org/d3.v4.js"></script>

There are several ways for removing those ticks. One of them is using tickValues:

.tickValues(data.map(function(d){ return d.date}))

Here is the demo:

var json = [{
  date: "05/17",
  numTags: 23
}, {
  date: "05/17",
  numTags: 17
}];

var margin = {
    top: 20,
    right: 30,
    bottom: 30,
    left: 40
  },
  width = 400,
  height = 200;

var parseTime = d3.timeParse("%m/%y");

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");

// Get the data
var data = json;

// format the data
data.forEach(function(d) {
  d.date = parseTime(d.date);
  d.numTags = +d.numTags;
});

// set the ranges
var xScale = d3.scaleTime()
  .range([0, width])
  .domain(d3.extent(data, function(d) {
    return d.date;
  }))
  .nice();

if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
  var dateLess = d3.timeDay.offset(xScale.domain()[0], -1);
  var dateMore = d3.timeDay.offset(xScale.domain()[0], 1);
  xScale.domain([dateLess, dateMore])
}

var yScale = d3.scaleLinear()
  .range([height, 0])
  .domain([0, d3.max(data, function(d) {
    return Math.max(d.numTags);
  })])
  .nice();

// define the 1st line
var tagLine = d3.line()
  .x(function(d) {
    return xScale(d.date);
  })
  .y(function(d) {
    return yScale(d.numTags);
  });

// Axes
var xAxis = d3.axisBottom()
  .scale(xScale)
  .ticks(json.length)
  .tickSizeOuter(0)
  .tickValues(data.map(function(d){ return d.date}))
  .tickFormat(d3.timeFormat('%B %Y'));

var yAxis = d3.axisLeft().scale(yScale);

svg.append("path")
  .data([data])
  .attr("class", "line")
  .style("stroke", "blue")
  .attr("d", tagLine);

var points = svg.selectAll(".point")
  .data(data)
  .enter().append("svg:circle")
  .attr("stroke", "green")
  .attr("fill", function(d, i) {
    return "blue"
  })
  .attr("cx", function(d, i) {
    return xScale(d.date)
  })
  .attr("cy", function(d, i) {
    return yScale(d.numTags)
  })
  .attr("r", function(d, i) {
    return 10
  });

// Add the X Axis
svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)
  .style("font-size", "14px");;

// Add the Y Axis
svg.append("g")
  .call(yAxis);

<script src="https://d3js.org/d3.v4.js"></script>


问:
Request a page with cron to update cache
I use http caching on Heroku:

```<code>def homepage
  response.headers['Cache-Control'] = 'public, max-age=86340'
  ...
end
</code>```

I also have added Heroku's free cron addon:

```<code>desc "This task is called by the Heroku cron add-on"
task :cron => :environment do
 if Time.now.hour == 0 # run at midnight
   # I want to request a page here
 end
end
</code>```

Could you tell me what should I put inside this file in order to request a page?

A similar question has been asked at How to force fragment cache on rails from cron schedule?
They don't provide an example in the answer.

答:
```<code>require 'uri'
require 'net/http'

desc "This task is called by the Heroku cron add-on"
task :cron => :environment do
 if Time.now.hour == 0 # run at midnight
   uri = URI.parse('http://my-app.heroku.com/page')
   Net::HTTP.get(uri)
 end
end
</code>```

That should do it.

Body:
I use http caching on Heroku:

def homepage
  response.headers['Cache-Control'] = 'public, max-age=86340'
  ...
end

I also have added Heroku's free cron addon:

desc "This task is called by the Heroku cron add-on"
task :cron => :environment do
 if Time.now.hour == 0 # run at midnight
   # I want to request a page here
 end
end

Could you tell me what should I put inside this file in order to request a page?

A similar question has been asked at How to force fragment cache on rails from cron schedule?
They don't provide an example in the answer.

Body:
require 'uri'
require 'net/http'

desc "This task is called by the Heroku cron add-on"
task :cron => :environment do
 if Time.now.hour == 0 # run at midnight
   uri = URI.parse('http://my-app.heroku.com/page')
   Net::HTTP.get(uri)
 end
end

That should do it.


问:
PHP instance find total
I need help with this code.

```<code>$aBlockVideos = (array) Advancedvideo_Service_Video::instance()->query("","v.total_comment DESC",1,5);
</code>```

How do I make it so it shows the total number of comments for this week?

答:
For the code that shows, the variable $aBlockVideos returns in an array () the results of the query, therefore, to know the total value of results, just use:

$TotalRows = count ($ aBlockVideos);

However, it is not recommended as it may slow down the execution of the script. I suggest you analyze your class and see if there is an appropriate option, for example:

$Result = mysqli_query ($ con, $ sql);
$NumRows = mysqli_num_rows ($ result);

Or, leave the processing to the database itself, in large data, you will get very fast execution time, example of your query:

SELECT COUNT (*) AS qtd FROM table WHERE ...

The return is the qtd field.

This way your execution time will be more agile.

Tip, review your class and see how to implement this suggestion.

Title: PHP instance find total

Body:
I need help with this code.

$aBlockVideos = (array) Advancedvideo_Service_Video::instance()->query("","v.total_comment DESC",1,5);

How do I make it so it shows the total number of comments for this week?


问:
Vim getting indentation wrong for Python code (with the python-mode Plugin)
As shown in the following screen-cast, I demonstrate the strange behaviors of Vim when it comes to adding comments to Python code. Between Demo 1 and Demo 2, I was only starting the line of comments at different indentation level (inside a class definition).

Demo 1

Demo 2

The problem:

As demonstrated towards the end of screen-cast, only typing : in insert mode will get the indentation right.

An ideal solution would achieve:

That when starting a line of comment, please leave the indentation level correctly;

答:
Solution in my case

I commented out the following line, and everything went on fine. No further weird corrections was made to the comments.

set smartindent

Other info of my Vim:

For the sake of indentation, here goes the settings:

```<code>filetype plugin on
filetype indent on
set autoindent
</code>```

Also, it has been verified that python-mode is not at fault. With the python-mode or without, set smartindent keeps getting me the problem.

Tentative conclusion:

set smartindent is not working well, probably, with my folding method specified as follows. Such setting is placed in C:/vim/vimfiles/ftplugin/python.vim

```<code>setlocal formatoptions=crnqj
</code>```

Here goes the correspondence of the characters used, yet none of which seems to be a trouble.

c: Auto-wrap comments using textwidth, inserting the current comment leader automatically.

r: Automatically insert the current comment leader after hitting <Enter> in Insert mode.

n: When formatting text, recognize numbered lists.  This actually uses
the 'formatlistpat' option, thus any kind of list can be used.  The
indent of the text after the number is used for the next line.  The
default is to find a number, optionally followed by '.', ':', ')',
']' or '}'.  Note that 'autoindent' must be set too.  Doesn't work
well together with "2".
Example:

```<code>1. the first item
   wraps
2. the second item
</code>```

q: Allow formatting of comments with "gq".
Note that formatting will not change blank lines or lines containing
only the comment leader.  A new paragraph starts after such a line,
or when the comment leader changes.

j: Where it makes sense, remove a comment leader when joining lines.

Reference to a better framed + answered solution

Direct answer: Vim automatically removes indentation on Python comments

Other cited ref:

How to configure vim to not put comments at the beginning of lines while editing python files

http://vim.wikia.com/wiki/Restoring_indent_after_typing_hash

In short, what I observed when editing a Python script is not unique to the "Python filetype" alone. It has to do with the symbol #, aka "hash".

Body:
Solution in my case

I commented out the following line, and everything went on fine. No further weird corrections was made to the comments.

set smartindent

Other info of my Vim:

For the sake of indentation, here goes the settings:

filetype plugin on
filetype indent on
set autoindent

Also, it has been verified that python-mode is not at fault. With the python-mode or without, set smartindent keeps getting me the problem.

Tentative conclusion:

set smartindent is not working well, probably, with my folding method specified as follows. Such setting is placed in C:/vim/vimfiles/ftplugin/python.vim

setlocal formatoptions=crnqj

Here goes the correspondence of the characters used, yet none of which seems to be a trouble.

c: Auto-wrap comments using textwidth, inserting the current comment leader automatically.

r: Automatically insert the current comment leader after hitting <Enter> in Insert mode.

n: When formatting text, recognize numbered lists.  This actually uses
the 'formatlistpat' option, thus any kind of list can be used.  The
indent of the text after the number is used for the next line.  The
default is to find a number, optionally followed by '.', ':', ')',
']' or '}'.  Note that 'autoindent' must be set too.  Doesn't work
well together with "2".
Example:

1. the first item
   wraps
2. the second item

q: Allow formatting of comments with "gq".
Note that formatting will not change blank lines or lines containing
only the comment leader.  A new paragraph starts after such a line,
or when the comment leader changes.

j: Where it makes sense, remove a comment leader when joining lines.

Reference to a better framed + answered solution

Direct answer: Vim automatically removes indentation on Python comments

Other cited ref:

How to configure vim to not put comments at the beginning of lines while editing python files

http://vim.wikia.com/wiki/Restoring_indent_after_typing_hash

In short, what I observed when editing a Python script is not unique to the "Python filetype" alone. It has to do with the symbol #, aka "hash".


问:
How to flip the exponent of a double (e.g. 1e300->1e-300)?
I am interested in  writing a fast C program that flips the exponent of a double. For instance, this program should convert 1e300 to 1e-300.  I guess the best way would be some bit operations, but I lack enough knowledge to fulfill that. Any good idea?  </p>

答:
Assuming you mean to negate the decimal exponent, the power of ten exponent in scientific notation:

```<code>#include <math.h>

double negate_decimal_exponent(const double value)
{
    if (value != 0.0) {
        const double p = pow(10.0, -floor(log10(fabs(value))));
        return (value * p) * p;
    } else
        return value;
}
</code>```

Above, floor(log10(fabs(value))) is the base 10 logarithm of the absolute value of value, rounded down. Essentially, it is the power of ten exponent in value using the scientific notation. If we negate it, and raise ten to that power, we have the inverse of that power of ten.

We can't calculate the square of p, because it might underflow for very large values of value in magnitude, or overflow for very small values of value in magnitude. Instead, we multiply value by p, so that the product is near unity in magnitude (that is, decimal exponent is zero); then multiply that with p, to essentially negate the decimal exponent.

Because the base-ten logarithm of zero is undefined, so we need to deal with that separately. (I initially missed this corner case; thanks to chux for pointing it out.)

Here is an example program to demonstrate:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <math.h>

double negate_decimal_exponent(const double value)
{
    if (value != 0.0) {
        const double p = pow(10.0, -floor(log10(fabs(value))));
        return (value * p) * p;
    } else
        return value;
}

#define TEST(val) printf("negate_decimal_exponent(%.16g) = %.16g\n", val, negate_decimal_exponent(val))

int main(void)
{
    TEST(1.0e300);
    TEST(1.1e300);
    TEST(-1.0e300);
    TEST(-0.8e150);
    TEST(0.35e-25);
    TEST(9.83e-200);
    TEST(23.4728395e-220);
    TEST(0.0);
    TEST(-0.0);

    return EXIT_SUCCESS;
}
</code>```

which, when compiled (remember to link with the math library, -lm) and run, outputs (on my machine; should output the same on all machines using IEEE-754 Binary64 for doubles):

```<code>negate_decimal_exponent(1e+300) = 1e-300
negate_decimal_exponent(1.1e+300) = 1.1e-300
negate_decimal_exponent(-1e+300) = -1e-300
negate_decimal_exponent(-8e+149) = -8e-149
negate_decimal_exponent(3.5e-26) = 3.5e+26
negate_decimal_exponent(9.83e-200) = 9.83e+200
negate_decimal_exponent(2.34728395e-219) = 2.34728395e+219
negate_decimal_exponent(0) = 0
negate_decimal_exponent(-0) = -0
</code>```

Are there faster methods to do this?

Sure. Construct a look-up table of powers of ten, and use a binary search to find the largest value that is smaller than value in magnitude. Have a second look-up table have the two multipliers that when multiplied with value, negates the decimal power of ten. Two factors are needed, because a single one does not have the necessary range and precision. (However, the two values are symmetric with respect to the base-ten logarithm.) For a look-up table with thousand exponents (covers IEEE-754 doubles, but one should check at compile time that it does cover DBL_MAX), that would be ten comparisons and two multiplications (using floating-point values), so it'd be quite fast.

A portable program could calculate the tables necessary at run-time, too.

Body:
Assuming you mean to negate the decimal exponent, the power of ten exponent in scientific notation:

#include <math.h>

double negate_decimal_exponent(const double value)
{
    if (value != 0.0) {
        const double p = pow(10.0, -floor(log10(fabs(value))));
        return (value * p) * p;
    } else
        return value;
}

Above, floor(log10(fabs(value))) is the base 10 logarithm of the absolute value of value, rounded down. Essentially, it is the power of ten exponent in value using the scientific notation. If we negate it, and raise ten to that power, we have the inverse of that power of ten.

We can't calculate the square of p, because it might underflow for very large values of value in magnitude, or overflow for very small values of value in magnitude. Instead, we multiply value by p, so that the product is near unity in magnitude (that is, decimal exponent is zero); then multiply that with p, to essentially negate the decimal exponent.

Because the base-ten logarithm of zero is undefined, so we need to deal with that separately. (I initially missed this corner case; thanks to chux for pointing it out.)

Here is an example program to demonstrate:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

double negate_decimal_exponent(const double value)
{
    if (value != 0.0) {
        const double p = pow(10.0, -floor(log10(fabs(value))));
        return (value * p) * p;
    } else
        return value;
}

#define TEST(val) printf("negate_decimal_exponent(%.16g) = %.16g\n", val, negate_decimal_exponent(val))

int main(void)
{
    TEST(1.0e300);
    TEST(1.1e300);
    TEST(-1.0e300);
    TEST(-0.8e150);
    TEST(0.35e-25);
    TEST(9.83e-200);
    TEST(23.4728395e-220);
    TEST(0.0);
    TEST(-0.0);

    return EXIT_SUCCESS;
}

which, when compiled (remember to link with the math library, -lm) and run, outputs (on my machine; should output the same on all machines using IEEE-754 Binary64 for doubles):

negate_decimal_exponent(1e+300) = 1e-300
negate_decimal_exponent(1.1e+300) = 1.1e-300
negate_decimal_exponent(-1e+300) = -1e-300
negate_decimal_exponent(-8e+149) = -8e-149
negate_decimal_exponent(3.5e-26) = 3.5e+26
negate_decimal_exponent(9.83e-200) = 9.83e+200
negate_decimal_exponent(2.34728395e-219) = 2.34728395e+219
negate_decimal_exponent(0) = 0
negate_decimal_exponent(-0) = -0

Are there faster methods to do this?

Sure. Construct a look-up table of powers of ten, and use a binary search to find the largest value that is smaller than value in magnitude. Have a second look-up table have the two multipliers that when multiplied with value, negates the decimal power of ten. Two factors are needed, because a single one does not have the necessary range and precision. (However, the two values are symmetric with respect to the base-ten logarithm.) For a look-up table with thousand exponents (covers IEEE-754 doubles, but one should check at compile time that it does cover DBL_MAX), that would be ten comparisons and two multiplications (using floating-point values), so it'd be quite fast.

A portable program could calculate the tables necessary at run-time, too.


问:
Uninitialized list size C#
I have the following snippet of code:

```<code>public static IEnumerable<IEnumerable<TIn>> splitToEvenly<TIn>(this IList<TIn> source, int splits)
{
    List<TIn[]> returnValue = new List<TIn[]>(splits);
</code>```

But when run I get a returnValue.Count of 0:

Why does this happen and how can I fix it?

*PS Just to follow the regulations:

It is expected that returnValue has a size of 15 because it has been assigned said value;

答:
According to the documentation, the constructor List(int) will:

Initializes a new instance of the List class that is empty and has the specified initial capacity.

The list may have a capacity of 15, but it is empty (Count = 0).

Alternatively you could use the List(IEnumerable) constructor to initialise your list with the source list like so:

```<code> List<TIn[]> returnValue = new List<TIn[]>(source);
</code>```

And then it would have Count = 23 (same as the source)

Title: Uninitialized list size C#

Body:
I have the following snippet of code:

public static IEnumerable<IEnumerable<TIn>> splitToEvenly<TIn>(this IList<TIn> source, int splits)
{
    List<TIn[]> returnValue = new List<TIn[]>(splits);

But when run I get a returnValue.Count of 0:

Why does this happen and how can I fix it?

*PS Just to follow the regulations:

It is expected that returnValue has a size of 15 because it has been assigned said value;

Body:
According to the documentation, the constructor List(int) will:

Initializes a new instance of the List class that is empty and has the specified initial capacity.

The list may have a capacity of 15, but it is empty (Count = 0).

Alternatively you could use the List(IEnumerable) constructor to initialise your list with the source list like so:

 List<TIn[]> returnValue = new List<TIn[]>(source);

And then it would have Count = 23 (same as the source)


问:
Why is TOAD faster than my java code?
I want to execute a select query and be able to get the count of the results, without using "COUNT(*)", like TOAD does. The concept is to give the option to the user to input any 'select query' he wants and to count the number of the results for him.

```<code>try {
   selectStatement = globalConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
   ResultSet selectResultSet = selectStatement.executeQuery(selectStatementString);
   selectResultSet.last();
   int countOfResults = selectResultSet.getRow();
   writeInLabel(kllStatusLabel, "Count Finished: Found " + countOfResults + " Inserts");
} catch (SQLException ex) {
   writeInLabel(kllStatusLabel, "Error executing select query.");
}
</code>```

This code delays much in line: "selectResultSet.last();".
TOAD does it with much less delay. (Right-Click -> Record Count).
Even when I scroll the results table all the way down in TOAD it does it faster.

How does TOAD get the record count?

OK I got it, I will use count(*) and have a second ResultSet to show my results.

```<code>ResultSet selectResultSet = selectStatement.executeQuery("select count(*) from (" + selectStatementString + ")");
int countOfResults = 0;
if (selectResultSet.next()){
   countOfResults = selectResultSet.getInt(1);
}
</code>```

答: Better keep the COUNT() close to the database providing a separate stored procedure exclusively containing the select with the count, and access that stored procedure from your code whenever you need it.

Title: Why is TOAD faster than my java code?

Body:
I want to execute a select query and be able to get the count of the results, without using "COUNT(*)", like TOAD does. The concept is to give the option to the user to input any 'select query' he wants and to count the number of the results for him.

try {
   selectStatement = globalConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
   ResultSet selectResultSet = selectStatement.executeQuery(selectStatementString);
   selectResultSet.last();
   int countOfResults = selectResultSet.getRow();
   writeInLabel(kllStatusLabel, "Count Finished: Found " + countOfResults + " Inserts");
} catch (SQLException ex) {
   writeInLabel(kllStatusLabel, "Error executing select query.");
}

This code delays much in line: "selectResultSet.last();".
TOAD does it with much less delay. (Right-Click -> Record Count).
Even when I scroll the results table all the way down in TOAD it does it faster.

How does TOAD get the record count?

OK I got it, I will use count(*) and have a second ResultSet to show my results.

ResultSet selectResultSet = selectStatement.executeQuery("select count(*) from (" + selectStatementString + ")");
int countOfResults = 0;
if (selectResultSet.next()){
   countOfResults = selectResultSet.getInt(1);
}


问:
Set input value by VueJS and mixing the content of value
I try this:

```<code><input type="text"
    name="username"
    v-model="user.name"
    :value="'The user name is: '+user.name">
</code>```

Is possible somehow to show in the input filed is "The user name is: John Doe" ?

Or I need definitely use a computed value in this case?

答:
The options seem to be to either bind directly to the value, instead of a v-model, or to created a computed property and v-model to that:

https://codepen.io/aprouja1/pen/jwxagE

```<code>new Vue({
  el:'#app',
  data(){
    return{
      user:{
        name:'Bob'
      }
    }
  },
  computed:{
    nameString(){
      return `The user name is: ${this.user.name}`
    }
  }
})
</code>```

Body:
I try this:

<input type="text"
    name="username"
    v-model="user.name"
    :value="'The user name is: '+user.name">

Is possible somehow to show in the input filed is "The user name is: John Doe" ?

Or I need definitely use a computed value in this case?

Body:
The options seem to be to either bind directly to the value, instead of a v-model, or to created a computed property and v-model to that:

https://codepen.io/aprouja1/pen/jwxagE

new Vue({
  el:'#app',
  data(){
    return{
      user:{
        name:'Bob'
      }
    }
  },
  computed:{
    nameString(){
      return `The user name is: ${this.user.name}`
    }
  }
})


问:
unmarshal json array into go struct (array is in the middle of the JSON string
I am new to Go. I am working with a weather API. I have commented out the sections that cause the error. I have seen several other links that have a similar problem, however none of them seem to have the array in the middle of the JSON string. I'm sure there is a way to define the struct with a slice. I can't seem to get get the syntax to allow it. Here is where I'm stuck:</p>

```<code>package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

// WeatherData struct to collect data from the API call
type WeatherData struct {
    Wind Wind
    Sys  Sys
    // Weather Weather
    Name string `json:"name"`
}

////////////// ERROR when unmarshalling this struct /////////
// Weather provides basic weather info
// type Weather struct {
//  ID      int    `json:"id"`
//  Descrip string `json:"description"`
//  Icon    string `json:"icon"`
// }
/////////////////////////////////////////////////////////////

// Sys includes sunrise, sunset, country, etc.
type Sys struct {
    Country string `json:"country"`
}

// Wind struct to get specific wind characteristics
type Wind struct {
    Speed  float64 `json:"speed"`
    Degree float64 `json:"deg"`
    Gust   float64 `json:"gust"`
}

func main() {
    res, getErr := http.Get("http://api.openweathermap.org/data/2.5/weather?zip=REMOVED,us&appid=REMOVEDBUTWILLPOSTJSONData")
    if getErr != nil {
        log.Fatalln("http.Get error: ", getErr)
    }
    defer res.Body.Close()
    body, readErr := ioutil.ReadAll(res.Body)
    if readErr != nil {
        log.Fatalln("Read Error: ", readErr)
    }
//////////// UNABLE TO UNMARSHAL the array that passes through here ////
    var data WeatherData
    if err := json.Unmarshal(body, &data); err != nil {
        panic(err)
    }

    fmt.Println("Wind gusts: ", data.Wind.Gust)
    fmt.Println("Wind speed: ", data.Wind.Speed)
    fmt.Println("Wind degrees: ", data.Wind.Degree)

    fmt.Println("Country is: ", data.Sys.Country)
    fmt.Println("City is: ", data.Name)

///////////////// CAN'T ACCESS Description...or anything in Weather
// fmt.Println("Country is: ", data.Weather.Descrip) // cannot access due to this portion being inside an array

}

/////////////////THIS IS THE JSON DATA THAT IS AVAILABLE ///////////
{
  "coord": {
    "lon": -97.31,
    "lat": 32.94
  },
  "weather": [  // CAN'T ACCESS THIS CORRECTLY
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 306.46,
    "pressure": 1014,
    "humidity": 55,
    "temp_min": 306.15,
    "temp_max": 307.15
  },
  "visibility": 16093,
  "wind": {
    "speed": 5.1,
    "deg": 150,
    "gust": 7.2
  },
  "clouds": {
    "all": 1
  },
  "dt": 1499120100,
  "sys": {
    "type": 1,
    "id": 2597,
    "message": 0.0225,
    "country": "US",
    "sunrise": 1499081152,
    "sunset": 1499132486
  },
  "id": 0,
  "name": "Fort Worth",
  "cod": 200
}
</code>```

答:
You have to define slice of Weather struct in WeatherData.

Uncomment Weather struct and update WeatherData struct to following.

```<code>// WeatherData struct to collect data from the API call
type WeatherData struct {
    Wind    Wind      `json:"wind"`
    Sys     Sys       `json:"sys"`
    Weather []Weather `json:"weather"`
    Name    string    `json:"name"`
}
</code>```

Please have a look on example code: https://play.golang.org/p/4KFqRuxcx2

Body:
I am new to Go. I am working with a weather API. I have commented out the sections that cause the error. I have seen several other links that have a similar problem, however none of them seem to have the array in the middle of the JSON string. I'm sure there is a way to define the struct with a slice. I can't seem to get get the syntax to allow it. Here is where I'm stuck:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

// WeatherData struct to collect data from the API call
type WeatherData struct {
    Wind Wind
    Sys  Sys
    // Weather Weather
    Name string `json:"name"`
}

////////////// ERROR when unmarshalling this struct /////////
// Weather provides basic weather info
// type Weather struct {
//  ID      int    `json:"id"`
//  Descrip string `json:"description"`
//  Icon    string `json:"icon"`
// }
/////////////////////////////////////////////////////////////

// Sys includes sunrise, sunset, country, etc.
type Sys struct {
    Country string `json:"country"`
}

// Wind struct to get specific wind characteristics
type Wind struct {
    Speed  float64 `json:"speed"`
    Degree float64 `json:"deg"`
    Gust   float64 `json:"gust"`
}

func main() {
    res, getErr := http.Get("http://api.openweathermap.org/data/2.5/weather?zip=REMOVED,us&appid=REMOVEDBUTWILLPOSTJSONData")
    if getErr != nil {
        log.Fatalln("http.Get error: ", getErr)
    }
    defer res.Body.Close()
    body, readErr := ioutil.ReadAll(res.Body)
    if readErr != nil {
        log.Fatalln("Read Error: ", readErr)
    }
//////////// UNABLE TO UNMARSHAL the array that passes through here ////
    var data WeatherData
    if err := json.Unmarshal(body, &data); err != nil {
        panic(err)
    }

    fmt.Println("Wind gusts: ", data.Wind.Gust)
    fmt.Println("Wind speed: ", data.Wind.Speed)
    fmt.Println("Wind degrees: ", data.Wind.Degree)

    fmt.Println("Country is: ", data.Sys.Country)
    fmt.Println("City is: ", data.Name)

///////////////// CAN'T ACCESS Description...or anything in Weather
// fmt.Println("Country is: ", data.Weather.Descrip) // cannot access due to this portion being inside an array

}

/////////////////THIS IS THE JSON DATA THAT IS AVAILABLE ///////////
{
  "coord": {
    "lon": -97.31,
    "lat": 32.94
  },
  "weather": [  // CAN'T ACCESS THIS CORRECTLY
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 306.46,
    "pressure": 1014,
    "humidity": 55,
    "temp_min": 306.15,
    "temp_max": 307.15
  },
  "visibility": 16093,
  "wind": {
    "speed": 5.1,
    "deg": 150,
    "gust": 7.2
  },
  "clouds": {
    "all": 1
  },
  "dt": 1499120100,
  "sys": {
    "type": 1,
    "id": 2597,
    "message": 0.0225,
    "country": "US",
    "sunrise": 1499081152,
    "sunset": 1499132486
  },
  "id": 0,
  "name": "Fort Worth",
  "cod": 200
}

Body:
You have to define slice of Weather struct in WeatherData.

Uncomment Weather struct and update WeatherData struct to following.

// WeatherData struct to collect data from the API call
type WeatherData struct {
    Wind    Wind      `json:"wind"`
    Sys     Sys       `json:"sys"`
    Weather []Weather `json:"weather"`
    Name    string    `json:"name"`
}

Please have a look on example code: https://play.golang.org/p/4KFqRuxcx2