问:
Creating an object that can hold id and value
Right now this method is creating a button that can hold both the id and value, it is done so through the merge attribute value. How can I make it so that it is not a button, instead just an object, a I can pass a command like: RowID(32, "objectid"); </p>

```<code>public static string RowPair(string btnValue, string btnID)
{
    string buttonHtml;
    var btnBuilder = new TagBuilder("button");
    btnBuilder.MergeAttribute("value", btnValue);
    btnBuilder.MergeAttribute("id", btnID);
    buttonHtml = btnBuilder.ToString(TagRenderMode.Normal);
    return buttonHtml;
}
</code>```

答:
You can just create a KeyValuePair object. It stores a key and a value, obviously. Use it like this:

```<code>var btnBuilder = new KeyValuePair<string, string>(btnID, btnValue);
</code>```

Hope it helps!

Body:
Right now this method is creating a button that can hold both the id and value, it is done so through the merge attribute value. How can I make it so that it is not a button, instead just an object, a I can pass a command like: RowID(32, "objectid");

public static string RowPair(string btnValue, string btnID)
{
    string buttonHtml;
    var btnBuilder = new TagBuilder("button");
    btnBuilder.MergeAttribute("value", btnValue);
    btnBuilder.MergeAttribute("id", btnID);
    buttonHtml = btnBuilder.ToString(TagRenderMode.Normal);
    return buttonHtml;
}

Body:
You can just create a KeyValuePair object. It stores a key and a value, obviously. Use it like this:

var btnBuilder = new KeyValuePair<string, string>(btnID, btnValue);

Hope it helps!


来源: stackexchange

问:
Informix equivalent to mysql's SHOW CREATE TABLE
Is there any equivalent to MySQL's SHOW CREATE TABLE <tablename>   in informix? I would like to run it in the SQL Manager on the Server Studio and would also like to obtain information about a tables columns and their types. Is this possible? I've found the systables, syscolumns and information schema, but wasn't lucky with the results I got with the output of select * from... .

答:
You can also obtain the basic column names and types from within DB-Access or ISQL with

```<code>INFO COLUMNS FOR <table>
</code>```

I don't know whether this works in SQL Manager or not, but it costs nothing to try.

ContentLicense: CC BY-SA 3.0

Body:
You can also obtain the basic column names and types from within DB-Access or ISQL with

INFO COLUMNS FOR <table>

I don't know whether this works in SQL Manager or not, but it costs nothing to try.

ContentLicense: CC BY-SA 2.5


问:
PropertyGrid - how to add ability to reset property of collection type in design-time
I'm developing a control. Control has a property of Collection type:

```<code>[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
TimeRuleCollection TimeRules { get { return timeRules; } }
</code>```

Is it possible to allow user to reset the property in design-time via property grid?

The reset method:

```<code>    void ResetWorkTimeRules() {
        TimeRules.Clear();
    }
</code>```

has no any effect. "Reset" action is disabled.

Is it possible to reset read-only properties this way?

答:
It's possible, but the property must be public and you have to provide a (even fake) public property setter:

```<code>[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public TimeRuleCollection TimeRules
{
    get { return timeRules; }
    set { throw new NotSupportedException(); }
}
</code>```

The next requirement is to have method void {PropertyName}Reset() (it could be with any accessibility, usually is private):

```<code>private void ResetTimeRules()
{
    timeRules.Clear();
}
</code>```

Optionally you can control when the Reset command is enabled by implementing a method bool ShouldSerialize{PropertyName}():

```<code>private bool ShouldSerializeTimeRules()
{
    return timeRules.Count > 0;
}
</code>```

Body:
I'm developing a control. Control has a property of Collection type:

[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
TimeRuleCollection TimeRules { get { return timeRules; } }

Is it possible to allow user to reset the property in design-time via property grid?

The reset method:

    void ResetWorkTimeRules() {
        TimeRules.Clear();
    }

has no any effect. "Reset" action is disabled.

Is it possible to reset read-only properties this way?

Body:
It's possible, but the property must be public and you have to provide a (even fake) public property setter:

[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public TimeRuleCollection TimeRules
{
    get { return timeRules; }
    set { throw new NotSupportedException(); }
}

The next requirement is to have method void {PropertyName}Reset() (it could be with any accessibility, usually is private):

private void ResetTimeRules()
{
    timeRules.Clear();
}

Optionally you can control when the Reset command is enabled by implementing a method bool ShouldSerialize{PropertyName}():

private bool ShouldSerializeTimeRules()
{
    return timeRules.Count > 0;
}


问:
How can i divide two expressions in Microsoft SQL Server
How can i divide two expressions in Microsoft SQL Server which give Numbers as a Result? I tried with a /, but this didn't work

```<code>SELECT COUNT(*) FROM A
SELECT COUNT(*) FROM B WHERE c = 1
</code>```

I tried with  / but this didnt work

```<code>SELECT COUNT(*)
FROM A/SELECT COUNT(*) FROM B WHERE c = 1
</code>```

答:
It might depend on RDBMS, this works in sql server.

```<code>SELECT ACounts/ CAST(BCounts AS Decimal(29,20))
FROM (SELECT COUNT(*) AS ACounts FROM A) AS suba
, (SELECT COUNT(*) AS BCounts FROM B WHERE c = 1) AS subb
</code>```

Note that I cast the BCounts to a decimal of arbitrary size otherwise it will round off to the nearest whole number. Ignore that part if that is what you wanted.

This also works

```<code>SELECT (SELECT COUNT(*) AS ACounts FROM A)/ CAST((SELECT COUNT(*) AS BCounts FROM B WHERE c = 1) AS Decimal(29,20))
</code>```

Body:
How can i divide two expressions in Microsoft SQL Server which give Numbers as a Result? I tried with a /, but this didn't work

SELECT COUNT(*) FROM A
SELECT COUNT(*) FROM B WHERE c = 1

I tried with  / but this didnt work

SELECT COUNT(*)
FROM A/SELECT COUNT(*) FROM B WHERE c = 1

Body:
It might depend on RDBMS, this works in sql server.

SELECT ACounts/ CAST(BCounts AS Decimal(29,20))
FROM (SELECT COUNT(*) AS ACounts FROM A) AS suba
, (SELECT COUNT(*) AS BCounts FROM B WHERE c = 1) AS subb

Note that I cast the BCounts to a decimal of arbitrary size otherwise it will round off to the nearest whole number. Ignore that part if that is what you wanted.

This also works

SELECT (SELECT COUNT(*) AS ACounts FROM A)/ CAST((SELECT COUNT(*) AS BCounts FROM B WHERE c = 1) AS Decimal(29,20))


问:
Android. I have two tabs and only one responds to touch
I have an APP and one activity contains two tabs in a TabHost control, it worked fine, but now only the second tab works. I see the content in both tabs but I can only scroll and select an item on the second one. If I try to scroll the first tab this one does not move but I see the scrollbar moving and actually the second tab is moving, so if I return to the second tab now is in a different position. If I try to select and ítem on the first tab nothing happens. Here's the layout and the code:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_tab_mesas"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".TabMesasActivity">

<TabHost
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:id="@+id/tab_host">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <ScrollView
                android:id="@+id/scrl_tab1"
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" >
                <RelativeLayout
                    android:id="@+id/tab1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                </RelativeLayout>
            </ScrollView>

            <ScrollView
                android:id="@+id/scrl_tab2"
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" >
                <RelativeLayout
                    android:id="@+id/tab2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
                </RelativeLayout>
            </ScrollView>
        </FrameLayout>
    </LinearLayout>
</TabHost>
</code>```

```<code>package xxxxxx;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.TabHost;

import java.util.List;

public class TabMesasActivity extends AppCompatActivity {
    TabHost tabHost;
    List<String> lstMesasSala;
    List<String> lstMesasTerraza;
    clsBBDD bd = new clsBBDD();
    RelativeLayout layoutSala;
    RelativeLayout layoutTerraza;
    TabHost.TabSpec spec;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tab_mesas);
    tabHost = (TabHost)findViewById(R.id.tab_host);
    //Botones Mesas
    layoutSala = (RelativeLayout) findViewById(R.id.tab1);
    layoutTerraza = (RelativeLayout) findViewById(R.id.tab2);
    tabHost.setup();

    //Tab 1
    spec = tabHost.newTabSpec("SALON");
    spec.setContent(R.id.tab1);
    spec.setIndicator("SALON");
    tabHost.addTab(spec);

    //Tab 2
    spec = tabHost.newTabSpec("TERRAZA");
    spec.setContent(R.id.tab2);
    spec.setIndicator("TERRAZA");
    tabHost.addTab(spec);

    if (savedInstanceState != null)
        tabHost.setCurrentTab(savedInstanceState.getInt("tabId"));

    lstMesasSala = bd.SelectMesasSalaDB();
    lstMesasTerraza = bd.SelectMesasTerrazaDB();

    clsSoporte.AñadirBotones(lstMesasSala, layoutSala, getWindow(), TabMesasActivity.this, TicketActivity.class);
    clsSoporte.AñadirBotones(lstMesasTerraza, layoutTerraza, getWindow(), TabMesasActivity.this, TicketActivity.class);
}

public void onSaveInstanceState(Bundle savedState) {
    super.onSaveInstanceState(savedState);
    //Guardar tab id
    int intTabId = tabHost.getCurrentTab();
    savedState.putInt("tabId", intTabId);

}

public void onBackPressed(){
    Intent i = new Intent(TabMesasActivity.this, MainActivity.class);
    startActivity(i);
    finish();
}
}
</code>```

Any idea why is this happening? Thanks.

答:
Finally i got the answer putting the ScrollView outside the FrameLayout.</p>

```<code><ScrollView
    android:id="@+id/scrl_tab1"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
                <RelativeLayout
                    android:id="@+id/tab1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
                </RelativeLayout>
                <RelativeLayout
                    android:id="@+id/tab2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
                </RelativeLayout>
            </FrameLayout>
        </ScrollView>
</code>```

Body:
I have an APP and one activity contains two tabs in a TabHost control, it worked fine, but now only the second tab works. I see the content in both tabs but I can only scroll and select an item on the second one. If I try to scroll the first tab this one does not move but I see the scrollbar moving and actually the second tab is moving, so if I return to the second tab now is in a different position. If I try to select and ítem on the first tab nothing happens. Here's the layout and the code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_tab_mesas"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".TabMesasActivity">

<TabHost
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:id="@+id/tab_host">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <ScrollView
                android:id="@+id/scrl_tab1"
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" >
                <RelativeLayout
                    android:id="@+id/tab1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                </RelativeLayout>
            </ScrollView>

            <ScrollView
                android:id="@+id/scrl_tab2"
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" >
                <RelativeLayout
                    android:id="@+id/tab2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
                </RelativeLayout>
            </ScrollView>
        </FrameLayout>
    </LinearLayout>
</TabHost>

package xxxxxx;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.TabHost;

import java.util.List;

public class TabMesasActivity extends AppCompatActivity {
    TabHost tabHost;
    List<String> lstMesasSala;
    List<String> lstMesasTerraza;
    clsBBDD bd = new clsBBDD();
    RelativeLayout layoutSala;
    RelativeLayout layoutTerraza;
    TabHost.TabSpec spec;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tab_mesas);
    tabHost = (TabHost)findViewById(R.id.tab_host);
    //Botones Mesas
    layoutSala = (RelativeLayout) findViewById(R.id.tab1);
    layoutTerraza = (RelativeLayout) findViewById(R.id.tab2);
    tabHost.setup();

    //Tab 1
    spec = tabHost.newTabSpec("SALON");
    spec.setContent(R.id.tab1);
    spec.setIndicator("SALON");
    tabHost.addTab(spec);

    //Tab 2
    spec = tabHost.newTabSpec("TERRAZA");
    spec.setContent(R.id.tab2);
    spec.setIndicator("TERRAZA");
    tabHost.addTab(spec);

    if (savedInstanceState != null)
        tabHost.setCurrentTab(savedInstanceState.getInt("tabId"));

    lstMesasSala = bd.SelectMesasSalaDB();
    lstMesasTerraza = bd.SelectMesasTerrazaDB();

    clsSoporte.AñadirBotones(lstMesasSala, layoutSala, getWindow(), TabMesasActivity.this, TicketActivity.class);
    clsSoporte.AñadirBotones(lstMesasTerraza, layoutTerraza, getWindow(), TabMesasActivity.this, TicketActivity.class);
}

public void onSaveInstanceState(Bundle savedState) {
    super.onSaveInstanceState(savedState);
    //Guardar tab id
    int intTabId = tabHost.getCurrentTab();
    savedState.putInt("tabId", intTabId);

}

public void onBackPressed(){
    Intent i = new Intent(TabMesasActivity.this, MainActivity.class);
    startActivity(i);
    finish();
}
}

Any idea why is this happening? Thanks.

Body:
Finally i got the answer putting the ScrollView outside the FrameLayout.

<ScrollView
    android:id="@+id/scrl_tab1"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
                <RelativeLayout
                    android:id="@+id/tab1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
                </RelativeLayout>
                <RelativeLayout
                    android:id="@+id/tab2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
                </RelativeLayout>
            </FrameLayout>
        </ScrollView>


问:
How to make my scanner ignore lines ending in <dir> using java?
I have a scanner which is reading in a file, but I do not know how to make the scanner ignore lines ending in < dir > </p>

答:
To skip lines that match a given pattern you can use, Scanner#skip(String pattern) method.

In your case, you want to skip input lines ending in .
So you can call above method with following pattern "<dir>$".


问:
Python - How to efficiently iterate through the subsets of a dictionary?
I have a dictionary with 500 DateFrames in it. Each data frame has columns 'date' , 'num_patients'. I apply the model to all the data frames in the dictionary, but Python kernel crash due to large data in the dictionary.

```<code>prediction_all = {}
for key, value in dict.items():
    model = Prophet(holidays = holidays).fit(value)
    future = model.make_future_dataframe(periods = 365)
    forecast = model.predict(future)
    prediction_all[key] = forecast.tail()
</code>```

So, then I've subsetted the dictionary and applied the model to each subset.

```<code>dict1 = {k: dict[k] for k in sorted(dict.keys())[:50]}
prediction_dict1 = {}
for key, value in dict1.items():
    model = Prophet(holidays = holidays).fit(value)
    future = model.make_future_dataframe(periods = 365)
    forecast = model.predict(future)
    prediction_dict1[key] = forecast.tail()

dict2 = {k: dict[k] for k in sorted(dict.keys())[50:100]}
prediction_dict2 = {}
for key, value in dict2.items():
    model = Prophet(holidays = holidays).fit(value)
    future = model.make_future_dataframe(periods = 365)
    forecast = model.predict(future)
    prediction_dict2[key] = forecast.tail()
</code>```

But I will need to run the code above for 10 times since I have 500 DataFrames (10 subsets). Is there a more efficient way to do this?

答:
One immediate improvement is to drop the sorted() and slicing step and replace it with heapq.nsmallest() which will do many fewer comparisons.  Also, the .keys() is not necessary since dicts automatically iterate over their keys by default.

Replace:

```<code> dict1 = {k: dict[k] for k in sorted(dict.keys())[:50]}
 dict2 = {k: dict[k] for k in sorted(dict.keys())[50:100]}
</code>```

With:

```<code> lowest_keys = heapq.nsmallest(100, dict)
 dict1 = {k : dict[k] for k in lowest_keys[:50]}
 dict2 = {k : dict[k] for k in lowest_keys[50:100]}
</code>```

The big for-loop in your code looks to only need .values() instead of .items() since key doesn't seem to be used.

Body:
I have a dictionary with 500 DateFrames in it. Each data frame has columns 'date' , 'num_patients'. I apply the model to all the data frames in the dictionary, but Python kernel crash due to large data in the dictionary.

prediction_all = {}
for key, value in dict.items():
    model = Prophet(holidays = holidays).fit(value)
    future = model.make_future_dataframe(periods = 365)
    forecast = model.predict(future)
    prediction_all[key] = forecast.tail()

So, then I've subsetted the dictionary and applied the model to each subset.

dict1 = {k: dict[k] for k in sorted(dict.keys())[:50]}
prediction_dict1 = {}
for key, value in dict1.items():
    model = Prophet(holidays = holidays).fit(value)
    future = model.make_future_dataframe(periods = 365)
    forecast = model.predict(future)
    prediction_dict1[key] = forecast.tail()

dict2 = {k: dict[k] for k in sorted(dict.keys())[50:100]}
prediction_dict2 = {}
for key, value in dict2.items():
    model = Prophet(holidays = holidays).fit(value)
    future = model.make_future_dataframe(periods = 365)
    forecast = model.predict(future)
    prediction_dict2[key] = forecast.tail()

But I will need to run the code above for 10 times since I have 500 DataFrames (10 subsets). Is there a more efficient way to do this?

Body:
One immediate improvement is to drop the sorted() and slicing step and replace it with heapq.nsmallest() which will do many fewer comparisons.  Also, the .keys() is not necessary since dicts automatically iterate over their keys by default.

Replace:

 dict1 = {k: dict[k] for k in sorted(dict.keys())[:50]}
 dict2 = {k: dict[k] for k in sorted(dict.keys())[50:100]}

With:

 lowest_keys = heapq.nsmallest(100, dict)
 dict1 = {k : dict[k] for k in lowest_keys[:50]}
 dict2 = {k : dict[k] for k in lowest_keys[50:100]}

The big for-loop in your code looks to only need .values() instead of .items() since key doesn't seem to be used.


问:
Is there a way to add zone_weights() in Sphinx?
I successfully managed to use field_weights in Sphinx to get the relevance I needed. However my fields are actually inclusive of several html tags (e.g. <Author> and <Description>). I need those in one field because of some other config work I am doing. So the field_weights won't in fact work for me. What I need is a way to weight the ZONES I set up in sphinx. However zone_weights is not working for me.

答:
Well no, there are no explicit zone weights.

Can perhaps use the individual boost modifier to boost words, that are also within the zone...

```<code>ZONE:(h3) banada^1.234
</code>```

Body:
Well no, there are no explicit zone weights.

Can perhaps use the individual boost modifier to boost words, that are also within the zone...

ZONE:(h3) banada^1.234


问:
How does RxJava actually work internally in regards to threading?
I have experience working with RxJava, to make reactive applications. However, I'm wondering how it (and other libraries, like Spring Reactor), actually work on the inside. I can't seem to find any interesting information regarding that online, only the typical simple tutorials. How does it deal with threading, etc? Do all "actors" run on the same thread? Or is it a thread per "declaration"?</p>

答: One key point about RxJava is it allows both the API owner and the consumer to decide on an execution model (and change it without breaking any interfaces). If you want to expose an observable which runs on the calling subscriber thread, inside an ExecutorService, on an Actor, e.t.c, that's up to you. Likewise you can subscribe to an observable using whatever threading model suits- be it blocking on the calling thread or on some kind of thread pool. Bottom line is the library itself takes no opinion on threading model; you need to decide what's best for the workload you're exposing.


问:
"Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" while importing data from Excel sheet to SQL Server using C#
I want to import an Excel sheet into SQL Server using C#
My Office version is Microsoft Office 2013
Windows version : Windows 10
I tried to download this tool
2007 Office System Driver: Data Connectivity Components
and change CPU to x86 but nothing changed
This is my code

```<code>private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            button1.Enabled = true;
            textBox1.Enabled = true;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            of1.Filter = "xls|*.xlsx";
            if ((of1.ShowDialog()) == System.Windows.Forms.DialogResult.OK)
            {
                imagepath = of1.FileName; //image path
                textBox1.Text = imagepath.ToString();
            }
        }

        private void loadbtn_Click(object sender, EventArgs e)
        {
            string ssqltable = comboBox1.GetItemText(comboBox1.SelectedItem);
            string myexceldataquery = "select * from ["+ ssqltable + "$]";
            try
            {
                string sexcelconnectionstring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Work\Bioxcell\UCB.xlsx;Extended Properties=Excel12.0Xml;HDR=YES;";
                string ssqlconnectionstring = "Data Source=.;Initial Catalog=Bioxcell;Integrated Security=True";
                OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
                OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
                oledbconn.Open();
                OleDbDataReader dr = oledbcmd.ExecuteReader();
                SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
                bulkcopy.DestinationTableName = ssqltable;
                while (dr.Read())
                {
                    bulkcopy.WriteToServer(dr);
                }

                oledbconn.Close();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
</code>```

Error message : Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

答:
Your code looks fine.  Install this:
https://www.microsoft.com/en-us/download/details.aspx?id=23734

That should fix your problem!!

Body:
I want to import an Excel sheet into SQL Server using C#
My Office version is Microsoft Office 2013
Windows version : Windows 10
I tried to download this tool
2007 Office System Driver: Data Connectivity Components
and change CPU to x86 but nothing changed
This is my code

private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            button1.Enabled = true;
            textBox1.Enabled = true;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            of1.Filter = "xls|*.xlsx";
            if ((of1.ShowDialog()) == System.Windows.Forms.DialogResult.OK)
            {
                imagepath = of1.FileName; //image path
                textBox1.Text = imagepath.ToString();
            }
        }

        private void loadbtn_Click(object sender, EventArgs e)
        {
            string ssqltable = comboBox1.GetItemText(comboBox1.SelectedItem);
            string myexceldataquery = "select * from ["+ ssqltable + "$]";
            try
            {
                string sexcelconnectionstring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Work\Bioxcell\UCB.xlsx;Extended Properties=Excel12.0Xml;HDR=YES;";
                string ssqlconnectionstring = "Data Source=.;Initial Catalog=Bioxcell;Integrated Security=True";
                OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
                OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
                oledbconn.Open();
                OleDbDataReader dr = oledbcmd.ExecuteReader();
                SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
                bulkcopy.DestinationTableName = ssqltable;
                while (dr.Read())
                {
                    bulkcopy.WriteToServer(dr);
                }

                oledbconn.Close();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }

Error message : Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine


问:
Java - 2d Array not filling when transferring info from file
In my program I am trying to read a file that contains Strings, booleans and doubles. I'm trying to have it skip a line if it determines that it isn't a double when filling an array. This is done by first checking if there is data on the line. Then it determines if the first character is a number or not. However, when I print the supposedly filled array with Arrays.deepToString it shows this:

```<code>[[2.33, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], ...
</code>```

I was wondering if anyone could tell me why it isn't filling properly. Here is the sample code:

```<code>public static double[][] readFile(String fileName) throws IOException
{
    double data[][] = new double[30][6];
    int indexRow = 0, indexCol = 0;

    File file = new File(fileName);
    Scanner input = new Scanner(file);

    while(input.hasNext())
    {
        String temp = input.nextLine();

        if(temp.trim().length() > 0)
        {
            if(Character.isDigit(temp.charAt(0)))
            {
                data[indexRow][indexCol] = input.nextDouble();

                if(indexCol < 6) indexCol++;
                if(indexRow < 30 && indexCol % 6 == 0)
                {
                    indexRow++;
                    indexCol = 0;
                }
            }
            else{}
        }
        else
            break;
    }
    System.out.println(Arrays.deepToString(data));

    return data;
}
</code>```

Here is a sample of the file (it should just fill the array with the doubles):

```<code>Washington Capitals
3.02
2.33
85.2
30.6
28.4
True
Dallas Stars
3.23
2.78
82.3
32.0
28.9
True
St. Louis Blues
2.67
2.40
85.1
30.2
29.7
True
</code>```

Thanks in advance.

EDIT
Here is the current array:

```<code>[[3.02, 2.33, 85.2, 30.6, 28.4], [3.23, 2.78, 82.3, 32.0, 28.9], [2.67, 2.4, 85.1, 30.2, 29.7], [2.94, 2.43, 84.4, 33.2, 29.7], [2.83, 2.44, 79.5, 28.8, 29.5], [2.85, 2.52, 80.3, 30.5, 30.8], [2.62, 2.29, 87.2, 30.3, 27.5], [2.72, 2.34, 81.4, 32.0, 27.5], [2.84, 2.62, 78.2, 28.5, 30.4], [2.77, 2.57, 84.5, 29.4, 30.4], [2.89, 2.52, 80.5, 30.4, 27.4], [2.73, 2.41, 84.0, 29.3, 28.9], [2.73, 2.6, 81.2, 30.6, 27.3], [2.57, 2.56, 80.5, 31.0, 30.7], [2.88, 2.78, 82.2, 32.0, 30.4], [2.55, 2.67, 81.5, 29.7, 29.7], [2.6, 2.49, 77.9, 29.0, 28.6], [2.39, 2.7, 84.3, 29.9, 27.6], [2.8, 2.94, 75.8, 28.4, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0]]
</code>```

Here is the full file:

```<code>Carolina Hurricanes
2.39
2.70
84.3
29.9
27.6
False
Ottawa Senators
2.80
2.94
75.8
28.4
32.8
False
New Jersey Devils
2.22
2.46
83.0
24.4
28.6
False
Colorado Avalanche
2.59
2.93
80.2
28.6
32.3
False
Montréal Canadiens
2.63
2.84
81.9
30.5
29.4
False
Buffalo Sabres
2.43
2.62
82.6
29.5
30.6
False
Winnipeg Jets
2.59
2.88
78.4
29.6
29.5
False
Arizona Coyotes
2.54
2.98
77.3
27.6
31.0
False
Calgary Flames
2.79
3.13
75.5
29.2
29.0
False
Columbus Blue Jackets
2.60
3.02
81.0
29.1
31.1
False
Vancouver Canucks
2.27
2.91
81.1
28.2
32.5
False
Edmonton Oilers
2.43
2.95
81.1
29.1
31.1
False
Toronto Maple Leafs
2.34
2.93
81.6
30.7
30.5
False
</code>```

答:
this code worked perfectly for me with your sample input

```<code>public static double[][] readFile(String fileName) throws IOException {
    double data[][] = new double[30][6];
    int indexRow = 0, indexCol = 0;

    File file = new File(fileName);
    try (Scanner input = new Scanner(file)) {
        while (input.hasNext()) {
            String temp = input.nextLine();

            if (temp.trim().length() == 0) {
                continue;
            } else {
                if (Character.isDigit(temp.charAt(0))) {
                    data[indexRow][indexCol] = Double.parseDouble(temp);

                    if (indexCol < 6)
                        indexCol++;
                    if (indexRow < 30 && indexCol % 6 == 0) {
                        indexRow++;
                        indexCol = 0;
                    }
                } else {
                    //do something
                }
            }
        }
    }
    System.out.println(Arrays.deepToString(data));

    return data;
}
</code>```

this is how I tested it

```<code>public static void main(String[] args) throws IOException {
    double[][] result = readFile("array.txt");

    for (int i = 0; i < result.length; i++) {
        boolean isFirst = true;
        for (int k = 0; k < result[i].length; k++) {
            if (isFirst)
                isFirst = false;
            else
                System.out.print(", ");
            System.out.printf("%5s", result[i][k]);
        }
        System.out.println();
    }
}
</code>```

and here's the output

```<code>[[3.02, 2.33, 85.2, 30.6, 28.4, 3.23], [2.78, 82.3, 32.0, 28.9, 2.67, 2.4], [85.1, 30.2, 29.7, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
 3.02,  2.33,  85.2,  30.6,  28.4,  3.23
 2.78,  82.3,  32.0,  28.9,  2.67,   2.4
 85.1,  30.2,  29.7,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
</code>```

my function readFile implemented with a BufferedReader

```<code>public static double[][] readFile(String fileName) throws IOException {
    double data[][] = new double[30][6];
    int indexRow = 0, indexCol = 0;

    File file = new File(fileName);
    try (BufferedReader input = new BufferedReader(new FileReader(file))) {
        String temp = input.readLine();
        while (temp != null) {
            if (temp.trim().length() > 0) {
                if (Character.isDigit(temp.charAt(0))) {
                    data[indexRow][indexCol] = Double.parseDouble(temp);

                    if (indexCol < 6)
                        indexCol++;
                    if (indexRow < 30 && indexCol % 6 == 0) {
                        indexRow++;
                        indexCol = 0;
                    }
                } else {
                    //do something
                }
            }

            temp = input.readLine();
        }
    }
    System.out.println(Arrays.deepToString(data));

    return data;
}
</code>```

Body:
In my program I am trying to read a file that contains Strings, booleans and doubles. I'm trying to have it skip a line if it determines that it isn't a double when filling an array. This is done by first checking if there is data on the line. Then it determines if the first character is a number or not. However, when I print the supposedly filled array with Arrays.deepToString it shows this:

[[2.33, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], ...

I was wondering if anyone could tell me why it isn't filling properly. Here is the sample code:

public static double[][] readFile(String fileName) throws IOException
{
    double data[][] = new double[30][6];
    int indexRow = 0, indexCol = 0;

    File file = new File(fileName);
    Scanner input = new Scanner(file);

    while(input.hasNext())
    {
        String temp = input.nextLine();

        if(temp.trim().length() > 0)
        {
            if(Character.isDigit(temp.charAt(0)))
            {
                data[indexRow][indexCol] = input.nextDouble();

                if(indexCol < 6) indexCol++;
                if(indexRow < 30 && indexCol % 6 == 0)
                {
                    indexRow++;
                    indexCol = 0;
                }
            }
            else{}
        }
        else
            break;
    }
    System.out.println(Arrays.deepToString(data));

    return data;
}

Here is a sample of the file (it should just fill the array with the doubles):

Washington Capitals
3.02
2.33
85.2
30.6
28.4
True
Dallas Stars
3.23
2.78
82.3
32.0
28.9
True
St. Louis Blues
2.67
2.40
85.1
30.2
29.7
True

Thanks in advance.

EDIT
Here is the current array:

[[3.02, 2.33, 85.2, 30.6, 28.4], [3.23, 2.78, 82.3, 32.0, 28.9], [2.67, 2.4, 85.1, 30.2, 29.7], [2.94, 2.43, 84.4, 33.2, 29.7], [2.83, 2.44, 79.5, 28.8, 29.5], [2.85, 2.52, 80.3, 30.5, 30.8], [2.62, 2.29, 87.2, 30.3, 27.5], [2.72, 2.34, 81.4, 32.0, 27.5], [2.84, 2.62, 78.2, 28.5, 30.4], [2.77, 2.57, 84.5, 29.4, 30.4], [2.89, 2.52, 80.5, 30.4, 27.4], [2.73, 2.41, 84.0, 29.3, 28.9], [2.73, 2.6, 81.2, 30.6, 27.3], [2.57, 2.56, 80.5, 31.0, 30.7], [2.88, 2.78, 82.2, 32.0, 30.4], [2.55, 2.67, 81.5, 29.7, 29.7], [2.6, 2.49, 77.9, 29.0, 28.6], [2.39, 2.7, 84.3, 29.9, 27.6], [2.8, 2.94, 75.8, 28.4, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0]]

Here is the full file:

Carolina Hurricanes
2.39
2.70
84.3
29.9
27.6
False
Ottawa Senators
2.80
2.94
75.8
28.4
32.8
False
New Jersey Devils
2.22
2.46
83.0
24.4
28.6
False
Colorado Avalanche
2.59
2.93
80.2
28.6
32.3
False
Montréal Canadiens
2.63
2.84
81.9
30.5
29.4
False
Buffalo Sabres
2.43
2.62
82.6
29.5
30.6
False
Winnipeg Jets
2.59
2.88
78.4
29.6
29.5
False
Arizona Coyotes
2.54
2.98
77.3
27.6
31.0
False
Calgary Flames
2.79
3.13
75.5
29.2
29.0
False
Columbus Blue Jackets
2.60
3.02
81.0
29.1
31.1
False
Vancouver Canucks
2.27
2.91
81.1
28.2
32.5
False
Edmonton Oilers
2.43
2.95
81.1
29.1
31.1
False
Toronto Maple Leafs
2.34
2.93
81.6
30.7
30.5
False

Body:
this code worked perfectly for me with your sample input

public static double[][] readFile(String fileName) throws IOException {
    double data[][] = new double[30][6];
    int indexRow = 0, indexCol = 0;

    File file = new File(fileName);
    try (Scanner input = new Scanner(file)) {
        while (input.hasNext()) {
            String temp = input.nextLine();

            if (temp.trim().length() == 0) {
                continue;
            } else {
                if (Character.isDigit(temp.charAt(0))) {
                    data[indexRow][indexCol] = Double.parseDouble(temp);

                    if (indexCol < 6)
                        indexCol++;
                    if (indexRow < 30 && indexCol % 6 == 0) {
                        indexRow++;
                        indexCol = 0;
                    }
                } else {
                    //do something
                }
            }
        }
    }
    System.out.println(Arrays.deepToString(data));

    return data;
}

this is how I tested it

public static void main(String[] args) throws IOException {
    double[][] result = readFile("array.txt");

    for (int i = 0; i < result.length; i++) {
        boolean isFirst = true;
        for (int k = 0; k < result[i].length; k++) {
            if (isFirst)
                isFirst = false;
            else
                System.out.print(", ");
            System.out.printf("%5s", result[i][k]);
        }
        System.out.println();
    }
}

and here's the output

[[3.02, 2.33, 85.2, 30.6, 28.4, 3.23], [2.78, 82.3, 32.0, 28.9, 2.67, 2.4], [85.1, 30.2, 29.7, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
 3.02,  2.33,  85.2,  30.6,  28.4,  3.23
 2.78,  82.3,  32.0,  28.9,  2.67,   2.4
 85.1,  30.2,  29.7,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0
  0.0,   0.0,   0.0,   0.0,   0.0,   0.0

my function readFile implemented with a BufferedReader

public static double[][] readFile(String fileName) throws IOException {
    double data[][] = new double[30][6];
    int indexRow = 0, indexCol = 0;

    File file = new File(fileName);
    try (BufferedReader input = new BufferedReader(new FileReader(file))) {
        String temp = input.readLine();
        while (temp != null) {
            if (temp.trim().length() > 0) {
                if (Character.isDigit(temp.charAt(0))) {
                    data[indexRow][indexCol] = Double.parseDouble(temp);

                    if (indexCol < 6)
                        indexCol++;
                    if (indexRow < 30 && indexCol % 6 == 0) {
                        indexRow++;
                        indexCol = 0;
                    }
                } else {
                    //do something
                }
            }

            temp = input.readLine();
        }
    }
    System.out.println(Arrays.deepToString(data));

    return data;
}


问:
Uncaught ReferenceError: Chart is not defined
I've installed chart.js using npm by : npm install chart.js --save-dev, in "resources/assets/js/bootstrap.js"

I refer to it by:
require('chart.js');

Then in my console npm run dev and finally it's successfully compiled in "public/js/app.js", however when I try to use it in my view as follow

```<code><script src="/js/app.js"></script><script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
......... </script>
</code>```

the browser returns

Uncaught ReferenceError: Chart is not defined.

How come it's declared in app.js and can't refer to it ?

Thanks in advance.

答:
If you're using es6 you might need to change the way you require it.

from the docs:
http://www.chartjs.org/docs/

```<code>// Using CommonJS
var Chart = require('chart.js')
var myChart = new Chart({...})

// ES6
import Chart from 'chart.js'
let myChart = new Chart({...})

// Using requirejs
require(['path/to/Chartjs'], function(Chart){
var myChart = new Chart({...})
})
</code>```

Body:
I've installed chart.js using npm by : npm install chart.js --save-dev, in "resources/assets/js/bootstrap.js"

I refer to it by:
require('chart.js');

Then in my console npm run dev and finally it's successfully compiled in "public/js/app.js", however when I try to use it in my view as follow

the browser returns

Uncaught ReferenceError: Chart is not defined.

How come it's declared in app.js and can't refer to it ?

Thanks in advance.

Body:
If you're using es6 you might need to change the way you require it.

from the docs:
http://www.chartjs.org/docs/

// Using CommonJS
var Chart = require('chart.js')
var myChart = new Chart({...})

// ES6
import Chart from 'chart.js'
let myChart = new Chart({...})

// Using requirejs
require(['path/to/Chartjs'], function(Chart){
var myChart = new Chart({...})
})


问:
Slick element not fully showing after click event
I am using the slick slider library. On page load, my slider wrapper is set to display: none. When I click my trigger click button, it then shows the slider, but the first slide doesn't show. Then when the second slide shows, the height isn't correct.

I have read through articles that share my issue, such as this one:

https://github.com/kenwheeler/slick/issues/158

Here is the library:

https://github.com/kenwheeler/slick

I have tried initializing the slider and then adding visibility: visible to it, but that does not seem to work.

Does anyone see or know what I have to add to get the first slide to fully show after being triggered?

Here is a fiddle which shows the issue I am having.

$('#trigger').on('click', function() {
 $('#pg-preview-wrap').show();
});
$('#calendar-select').on('init', function() {
  $('#calendar-select').css("visibility", "visible");
  $('.slick-initialized').css("visibility", "visible");
});
$('#calendar-select').slick({
  dots: true,
  infinite: true,
  autoplay: true,
  autoplaySpeed: 7000,
  speed: 800,
  slidesToShow: 1,
  adaptiveHeight: true
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#pg-preview-wrap {
  display: none;
}

#calendar-select {
  width: 50%;
  margin: 0 auto 70px auto;
  background: #CCC;
  visibility: hidden;
  height: auto;
}

.no-fouc {
  display: none;
}

.slick-initialized {
  visibility: visible;
}

.slick-slide img.checkmark-img {
  display: none;
  width: 40%;
  height: auto;
  z-index: 1;
  cursor: pointer;
}

.slick-slide img.pg-preview-img {
  display: block;
}

.calendar-option img {
  margin: 20px auto;
  cursor: pointer;
  width: 50%;
  height: auto;
  display: block;
}

.calendar-option-push {
  width: 0;
  height: 20px;
  border: none;
  margin: 20px auto;
}

.calendar-option cite {
  text-align: center;
  font-size: 1.25rem;
  margin: auto;
  color: #303030;
  font-family: 'Lato', sans-serif;
  display: block;
}

.slick-prev,
.slick-next {
  background-repeat: no-repeat;
  background-size: 120px 120px;
  height: 120px;
  width: 120px;
}

.slick-prev {
  left: -130px;
  background-image: url("images/arrow-back.png");
}

.slick-prev:hover,
.slick-prev:active,
.slick-prev:focus {
  background-image: url("images/arrow-back.png");
}

.slick-prev:hover,
.slick-prev:active,
.slick-prev:focus,
.slick-next:hover,
.slick-next:active,
.slick-next:focus {
  background-repeat: no-repeat;
  background-size: 120px 120px;
}

.slick-next {
  right: -130px;
  background-image: url("images/arrow-forward.png");
}

.slick-next:hover,
.slick-next:active,
.slick-next:focus {
  background-image: url("images/arrow-forward.png");
}

.slick-prev:before,
.slick-next:before {
  font-size: 0px;
}

.slick-dots {
  margin: 15px 0 20px 0;
}

.white-back {
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  background: #FFF;
}</code>```

<link href="https://cdn.jsdelivr.net/jquery.slick/1.5.0/slick-theme.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/jquery.slick/1.5.0/slick.css" rel="stylesheet"/>

<button id="trigger">Trigger</button>

          A

        <input type="checkbox" class="option-check" id='flag-option'>

          B

        <input type="checkbox" class="option-check" id='nickel-option'>

          C

        <input type="checkbox" class="option-check" id='gold-option'>

```

答:
Probably not a straight forward solution to your problem, you could destroy and reinitialize the slider after it's visible.

var options = {
  dots: true,
  infinite: true,
  autoplay: true,
  autoplaySpeed: 7000,
  speed: 800,
  slidesToShow: 1,
  adaptiveHeight: true
}
$('#trigger').on('click', function() {
 $('#pg-preview-wrap').show();
  $('#calendar-select').slick('unslick');
  $('#calendar-select').slick(options);
});
$('#calendar-select').on('init', function() {
  //$('#calendar-select').css("visibility", "visible");
  //$('.slick-initialized').css("visibility", "visible");
});
$('#calendar-select').slick(options);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#pg-preview-wrap {
  display: none;
}

#calendar-select {
  width: 50%;
  margin: 0 auto 70px auto;
  background: #CCC;
  height: auto;
}

.no-fouc {
  display: none;
}

.slick-initialized {
  visibility: visible;
}

.slick-slide img.checkmark-img {
  display: none;
  width: 40%;
  height: auto;
  z-index: 1;
  cursor: pointer;
}

.slick-slide img.pg-preview-img {
  display: block;
}

.calendar-option img {
  margin: 20px auto;
  cursor: pointer;
  width: 50%;
  height: auto;
  display: block;
}

.calendar-option-push {
  width: 0;
  height: 20px;
  border: none;
  margin: 20px auto;
}

.calendar-option cite {
  text-align: center;
  font-size: 1.25rem;
  margin: auto;
  color: #303030;
  font-family: 'Lato', sans-serif;
  display: block;
}

.slick-prev,
.slick-next {
  background-repeat: no-repeat;
  background-size: 120px 120px;
  height: 120px;
  width: 120px;
}

.slick-prev {
  left: -130px;
  background-image: url("images/arrow-back.png");
}

.slick-prev:hover,
.slick-prev:active,
.slick-prev:focus {
  background-image: url("images/arrow-back.png");
}

.slick-prev:hover,
.slick-prev:active,
.slick-prev:focus,
.slick-next:hover,
.slick-next:active,
.slick-next:focus {
  background-repeat: no-repeat;
  background-size: 120px 120px;
}

.slick-next {
  right: -130px;
  background-image: url("images/arrow-forward.png");
}

.slick-next:hover,
.slick-next:active,
.slick-next:focus {
  background-image: url("images/arrow-forward.png");
}

.slick-prev:before,
.slick-next:before {
  font-size: 0px;
}

.slick-dots {
  margin: 15px 0 20px 0;
}

.white-back {
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  background: #FFF;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Slick JS</title>

 <link rel="stylesheet" href="https://cdn.jsdelivr.net/jquery.slick/1.5.0/slick.css">
 <link rel="stylesheet" href="https://cdn.jsdelivr.net/jquery.slick/1.5.0/slick-theme.css">

<button id="trigger">Trigger</button>

          A

        <input type="checkbox" class="option-check" id='flag-option'>

          B

        <input type="checkbox" class="option-check" id='nickel-option'>

          C

        <input type="checkbox" class="option-check" id='gold-option'>

```

I couldn't find any reInit method, otherwise that could have been used. Here is fiddle of the above code.

Body:
I am using the slick slider library. On page load, my slider wrapper is set to display: none. When I click my trigger click button, it then shows the slider, but the first slide doesn't show. Then when the second slide shows, the height isn't correct.

I have read through articles that share my issue, such as this one:

https://github.com/kenwheeler/slick/issues/158

Here is the library:

https://github.com/kenwheeler/slick

I have tried initializing the slider and then adding visibility: visible to it, but that does not seem to work.

Does anyone see or know what I have to add to get the first slide to fully show after being triggered?

Here is a fiddle which shows the issue I am having.

$('#trigger').on('click', function() {
 $('#pg-preview-wrap').show();
});
$('#calendar-select').on('init', function() {
  $('#calendar-select').css("visibility", "visible");
  $('.slick-initialized').css("visibility", "visible");
});
$('#calendar-select').slick({
  dots: true,
  infinite: true,
  autoplay: true,
  autoplaySpeed: 7000,
  speed: 800,
  slidesToShow: 1,
  adaptiveHeight: true
});

#pg-preview-wrap {
  display: none;
}

#calendar-select {
  width: 50%;
  margin: 0 auto 70px auto;
  background: #CCC;
  visibility: hidden;
  height: auto;
}

.no-fouc {
  display: none;
}

.slick-initialized {
  visibility: visible;
}

.slick-slide img.checkmark-img {
  display: none;
  width: 40%;
  height: auto;
  z-index: 1;
  cursor: pointer;
}

.slick-slide img.pg-preview-img {
  display: block;
}

.calendar-option img {
  margin: 20px auto;
  cursor: pointer;
  width: 50%;
  height: auto;
  display: block;
}

.calendar-option-push {
  width: 0;
  height: 20px;
  border: none;
  margin: 20px auto;
}

.calendar-option cite {
  text-align: center;
  font-size: 1.25rem;
  margin: auto;
  color: #303030;
  font-family: 'Lato', sans-serif;
  display: block;
}

.slick-prev,
.slick-next {
  background-repeat: no-repeat;
  background-size: 120px 120px;
  height: 120px;
  width: 120px;
}

.slick-prev {
  left: -130px;
  background-image: url("images/arrow-back.png");
}

.slick-prev:hover,
.slick-prev:active,
.slick-prev:focus {
  background-image: url("images/arrow-back.png");
}

.slick-prev:hover,
.slick-prev:active,
.slick-prev:focus,
.slick-next:hover,
.slick-next:active,
.slick-next:focus {
  background-repeat: no-repeat;
  background-size: 120px 120px;
}

.slick-next {
  right: -130px;
  background-image: url("images/arrow-forward.png");
}

.slick-next:hover,
.slick-next:active,
.slick-next:focus {
  background-image: url("images/arrow-forward.png");
}

.slick-prev:before,
.slick-next:before {
  font-size: 0px;
}

.slick-dots {
  margin: 15px 0 20px 0;
}

.white-back {
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  background: #FFF;
}

<link href="https://cdn.jsdelivr.net/jquery.slick/1.5.0/slick-theme.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/jquery.slick/1.5.0/slick.css" rel="stylesheet"/>

<button id="trigger">Trigger</button>

          A

        <input type="checkbox" class="option-check" id='flag-option'>

          B

        <input type="checkbox" class="option-check" id='nickel-option'>

          C

        <input type="checkbox" class="option-check" id='gold-option'>

Body:
Probably not a straight forward solution to your problem, you could destroy and reinitialize the slider after it's visible.

var options = {
  dots: true,
  infinite: true,
  autoplay: true,
  autoplaySpeed: 7000,
  speed: 800,
  slidesToShow: 1,
  adaptiveHeight: true
}
$('#trigger').on('click', function() {
 $('#pg-preview-wrap').show();
  $('#calendar-select').slick('unslick');
  $('#calendar-select').slick(options);
});
$('#calendar-select').on('init', function() {
  //$('#calendar-select').css("visibility", "visible");
  //$('.slick-initialized').css("visibility", "visible");
});
$('#calendar-select').slick(options);

#pg-preview-wrap {
  display: none;
}

#calendar-select {
  width: 50%;
  margin: 0 auto 70px auto;
  background: #CCC;
  height: auto;
}

.no-fouc {
  display: none;
}

.slick-initialized {
  visibility: visible;
}

.slick-slide img.checkmark-img {
  display: none;
  width: 40%;
  height: auto;
  z-index: 1;
  cursor: pointer;
}

.slick-slide img.pg-preview-img {
  display: block;
}

.calendar-option img {
  margin: 20px auto;
  cursor: pointer;
  width: 50%;
  height: auto;
  display: block;
}

.calendar-option-push {
  width: 0;
  height: 20px;
  border: none;
  margin: 20px auto;
}

.calendar-option cite {
  text-align: center;
  font-size: 1.25rem;
  margin: auto;
  color: #303030;
  font-family: 'Lato', sans-serif;
  display: block;
}

.slick-prev,
.slick-next {
  background-repeat: no-repeat;
  background-size: 120px 120px;
  height: 120px;
  width: 120px;
}

.slick-prev {
  left: -130px;
  background-image: url("images/arrow-back.png");
}

.slick-prev:hover,
.slick-prev:active,
.slick-prev:focus {
  background-image: url("images/arrow-back.png");
}

.slick-prev:hover,
.slick-prev:active,
.slick-prev:focus,
.slick-next:hover,
.slick-next:active,
.slick-next:focus {
  background-repeat: no-repeat;
  background-size: 120px 120px;
}

.slick-next {
  right: -130px;
  background-image: url("images/arrow-forward.png");
}

.slick-next:hover,
.slick-next:active,
.slick-next:focus {
  background-image: url("images/arrow-forward.png");
}

.slick-prev:before,
.slick-next:before {
  font-size: 0px;
}

.slick-dots {
  margin: 15px 0 20px 0;
}

.white-back {
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  background: #FFF;
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Slick JS</title>
</head>
 <link rel="stylesheet" href="https://cdn.jsdelivr.net/jquery.slick/1.5.0/slick.css">
 <link rel="stylesheet" href="https://cdn.jsdelivr.net/jquery.slick/1.5.0/slick-theme.css">
<body>
<button id="trigger">Trigger</button>
<div id="pg-preview-wrap">
  <div id="calendar-select">
    <div class="calendar-option">
      <div class="product-wrap">
        <label for="flag-option" class="package-check-toggle">
          <img src='http://s3.amazonaws.com/static.graphemica.com/glyphs/i500s/000/009/448/original/25AE-500x500.png?1275323708' alt='American Flag' class='pg-preview-img'>
          <p class="calendar-option-push"></p>
          <cite>A</cite>
        </label>
        <input type="checkbox" class="option-check" id='flag-option'>
      </div>
    </div>
    <div class="calendar-option">
      <div class="product-wrap">
        <label for="nickel-option" class="package-check-toggle">
          <img src='http://s3.amazonaws.com/static.graphemica.com/glyphs/i500s/000/009/448/original/25AE-500x500.png?1275323708' alt='Brushed Nickel & Black' class='pg-preview-img'>
          <p class="calendar-option-push"></p>
          <cite>B</cite>
        </label>
        <input type="checkbox" class="option-check" id='nickel-option'>
      </div>
    </div>
    <div class="calendar-option">
      <div class="product-wrap">
        <label for="gold-option" class="package-check-toggle">
          <img src='http://s3.amazonaws.com/static.graphemica.com/glyphs/i500s/000/009/448/original/25AE-500x500.png?1275323708' alt='Gold & Black' class='pg-preview-img'>
          <p class="calendar-option-push"></p>
          <cite>C</cite>
        </label>
        <input type="checkbox" class="option-check" id='gold-option'>
      </div>
    </div>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.slick/1.5.0/slick.min.js"></script>

</body>
</html>

I couldn't find any reInit method, otherwise that could have been used. Here is fiddle of the above code.


问:
How to format date in angular2?
My code:

```<code>   this.nextDay = new Date();
   var datePipe = new DatePipe('en-US')
   this.presentDate = datePipe.transform(this.nextDay, 'YYYY-MM-DD H:mm:ss');
</code>```

But with the above code, I am getting this.presentDate = yyyy-3-DD 23:04:99

I want date as 2017-3-23 23:09:06 ,but here I don't know why I got yyyy?.

答:
You need to use a single y and lowercase dd

```<code>this.nextDay = new Date();
var datePipe = new DatePipe('en-US')
this.presentDate = datePipe.transform(this.nextDay, 'y-MM-dd H:mm:ss');
</code>```

Reference: https://webdev.dartlang.org/angular/api/angular2.common/DatePipe-class

Title: How to format date in angular2?

Body:
My code:

   this.nextDay = new Date();
   var datePipe = new DatePipe('en-US')
   this.presentDate = datePipe.transform(this.nextDay, 'YYYY-MM-DD H:mm:ss');

But with the above code, I am getting this.presentDate = yyyy-3-DD 23:04:99

I want date as 2017-3-23 23:09:06 ,but here I don't know why I got yyyy?.

Body:
You need to use a single y and lowercase dd

this.nextDay = new Date();
var datePipe = new DatePipe('en-US')
this.presentDate = datePipe.transform(this.nextDay, 'y-MM-dd H:mm:ss');

Reference: https://webdev.dartlang.org/angular/api/angular2.common/DatePipe-class


问:
How to count the number of zeros at the start of a string
I have a string:

```<code>"0011HelloWor00ld001"
</code>```

How do I count the number of zeros in the starting of the string?
For example, the above string should return 2.

I tried .match(/^[0]+/).size but it doesn't work.

答:
.match(/^0+/) will return a MatchData object, and thus you get 1 as the result (it denotes the number of elements in the match array).

You need to get the size of the match itself. Use  one of the following:

```<code>"0011HelloWor00ld001".match(/^0+/)[0].size
"0011HelloWor00ld001"[/^0+/].size
"0011HelloWor00ld001".match(/^0+/).to_s.size
</code>```

Body:
I have a string:

"0011HelloWor00ld001"

How do I count the number of zeros in the starting of the string?
For example, the above string should return 2.

I tried .match(/^[0]+/).size but it doesn't work.

Body:
.match(/^0+/) will return a MatchData object, and thus you get 1 as the result (it denotes the number of elements in the match array).

You need to get the size of the match itself. Use  one of the following:

"0011HelloWor00ld001".match(/^0+/)[0].size
"0011HelloWor00ld001"[/^0+/].size
"0011HelloWor00ld001".match(/^0+/).to_s.size


问:
How to filter out duplicate rows based on some columns in spark dataframe?
Suppose, I have a Dataframe like below:

Here, you can see that transaction number 1,2 and 3 have same value for columns A,B,C but different value for column D and E. Column E has date entries.

For same A,B and C combination (A=1,B=1,C=1), we have 3 rows. I want to take only one row based on the recent transaction date of column E means the rows which have the most recent date. But for the most recent date, there are 2 transactions. But i want to take just one of them if two or more rows found for the same combination of A,B,C and most recent date in column E.
So my expected output for this combination will be row number 3 or 4(any one will do).

For same A,B and C combination (A=2,B=2,C=2), we have 2 rows. But based on column E, the most recent date is the date of row number 5. So we will just take this row for this combination of A,B and C.
So my expected output for this combination will be row number 5

So the final output will be (3 and 5) or (4 and 5).

Now how should i approach:

I read this:

Both reduceByKey and groupByKey can be used for the same purposes but
  reduceByKey works much better on a large dataset. That’s because Spark
  knows it can combine output with a common key on each partition before
  shuffling the data.

I tried with groupBy on Column A,B,C and max on column E. But it can't give me the head of the rows if multiple rows present for the same date.

What is the most optimized approach to solve this? Thanks in advance.

EDIT: I need get back my filtered transactions. How to do it also?

答:
I have used spark window functions to get my solution:

```<code> val window = Window
      .partitionBy(dataframe("A"), dataframe("B"),dataframe("C"))
      .orderBy(dataframe("E") desc)

 val dfWithRowNumber = dataframe.withColumn("row_number", row_number() over window)
 val filteredDf = dfWithRowNumber.filter(dfWithRowNumber("row_number") === 1)
</code>```

Body:
I have used spark window functions to get my solution:

 val window = Window
      .partitionBy(dataframe("A"), dataframe("B"),dataframe("C"))
      .orderBy(dataframe("E") desc)

 val dfWithRowNumber = dataframe.withColumn("row_number", row_number() over window)
 val filteredDf = dfWithRowNumber.filter(dfWithRowNumber("row_number") === 1)


问:
Excluding child values
I have a property within my Entity which links to another Entity:

```<code> /**
 * @Groups({"bookReviews"})
 * @ORM\ManyToOne(targetEntity="Book\MainBundle\Entity\Book", inversedBy="reviews")
 * @ORM\JoinColumn(name="bookID", referencedColumnName="id")
 */
private $bookID;
</code>```

Within my controller when this is called:

```<code>    public function getReviewsAction()
{
    $serializer = $this->get('serializer');
    $em = $this->getDoctrine()->getManager();
    $reviews = $em->getRepository('BookMainBundle:Review')->findAll();
    $data = $serializer->serialize($reviews, 'json', SerializationContext::create()->setGroups(array('Default')));
    return $this->handleView($this->view($reviews));
}
</code>```

This retrieves a JSON with the following result:

```<code>{
 "id": 17,
 "book_i_d": {
 "id": 10,
 "author": "J.K Rowling",
 "title": "Harry Potter: Philosopher's Stone",
 "posted": "2017-01-03T04:19:18+0000",
 "summary": "Harry Potter and the Philosopher's Stone is the first novel in the Harry Potter series and J. K. Rowling's debut novel, first published in 1997 by Bloomsbury. It was published in the United States as Harry Potter and the Sorcerer's Stone by Scholastic Corporation in 1998. The plot follows Harry Potter, a young wizard who discovers his magical heritage as he makes close friends and a few enemies in his first year at the Hogwarts School of Witchcraft and Wizardry. With the help of his friends, Harry faces an attempted comeback by the dark wizard Lord Voldemort, who killed Harry's parents, but failed to kill Harry when he was just a year old.",
 "image": "cde5910f46d0e6bed33ffa18aa24ec5c.jpeg"
},
"posted": "2017-01-03T04:19:19+0000",
"review": "The author started Harry's journey with this book. It's the beginning and it's bloody brilliant!"
}
</code>```

However, as you notice.. irrelevant information of the book is retrieved. At this point, the only detail I want to retrieve of the book is the book's ID.

What can I do about this?

答:
I see two solutions here.

Create a virtual property for serializer and assign to a custom method in your entity that returns id only, remove $bookID from serializer context at all.

@Serializer\VirtualProperty()

@Serializer\SerializedName("book_id")

@Serializer\Groups({"bookReviewes"})

The other option is to correctly assign serializer annotations in the linked entity. User different context for all the fields.

Just make sure you're serializing the entities with the right context. Because now you're doing it with "Default" group but in the annotation it's set to "bookReviews".

Title: Excluding child values

Body:
I have a property within my Entity which links to another Entity:

 /**
 * @Groups({"bookReviews"})
 * @ORM\ManyToOne(targetEntity="Book\MainBundle\Entity\Book", inversedBy="reviews")
 * @ORM\JoinColumn(name="bookID", referencedColumnName="id")
 */
private $bookID;

Within my controller when this is called:

    public function getReviewsAction()
{
    $serializer = $this->get('serializer');
    $em = $this->getDoctrine()->getManager();
    $reviews = $em->getRepository('BookMainBundle:Review')->findAll();
    $data = $serializer->serialize($reviews, 'json', SerializationContext::create()->setGroups(array('Default')));
    return $this->handleView($this->view($reviews));
}

This retrieves a JSON with the following result:

{
 "id": 17,
 "book_i_d": {
 "id": 10,
 "author": "J.K Rowling",
 "title": "Harry Potter: Philosopher's Stone",
 "posted": "2017-01-03T04:19:18+0000",
 "summary": "Harry Potter and the Philosopher's Stone is the first novel in the Harry Potter series and J. K. Rowling's debut novel, first published in 1997 by Bloomsbury. It was published in the United States as Harry Potter and the Sorcerer's Stone by Scholastic Corporation in 1998. The plot follows Harry Potter, a young wizard who discovers his magical heritage as he makes close friends and a few enemies in his first year at the Hogwarts School of Witchcraft and Wizardry. With the help of his friends, Harry faces an attempted comeback by the dark wizard Lord Voldemort, who killed Harry's parents, but failed to kill Harry when he was just a year old.",
 "image": "cde5910f46d0e6bed33ffa18aa24ec5c.jpeg"
},
"posted": "2017-01-03T04:19:19+0000",
"review": "The author started Harry's journey with this book. It's the beginning and it's bloody brilliant!"
}

However, as you notice.. irrelevant information of the book is retrieved. At this point, the only detail I want to retrieve of the book is the book's ID.

What can I do about this?


问:
Dynamically resize iframe
Situation:
I'm working on a responsive design that involves the typical HTML/CSS combo. Everything is working nicely except in one case where there is an iframe inside of a div. The iframe should adjust automatically to the size of the parent div. A purely css solution has not presented itself so I'm going with a JQuery approach. It works nicely except in one scenario, when resizing from a smaller width to a larger width screen.

HTML:

```<code><div class="container">
    <iframe class="iframe-class" src="http://www.cnn.com/"></iframe>
</div>
</code>```

CSS:

```<code>.container {
    width: 100%;
    height: 250px;
}
.iframe-class {
    width: 100%;
    height: 100%;
    border: 1px solid red;
    overflow: auto;
}
</code>```

Javascript:

```<code>$(function () {
    setIFrameSize();
    $(window).resize(function () {
        setIFrameSize();
    });
});

function setIFrameSize() {
    var ogWidth = 700;
    var ogHeight = 600;
    var ogRatio = ogWidth / ogHeight;

    var windowWidth = $(window).width();
    if (windowWidth < 480) {
        var parentDivWidth = $(".iframe-class").parent().width();
        var newHeight = (parentDivWidth / ogRatio);
        $(".iframe-class").addClass("iframe-class-resize");
        $(".iframe-class-resize").css("width", parentDivWidth);
        $(".iframe-class-resize").css("height", newHeight);
    } else {
        // $(".iframe-class-resize").removeAttr("width");
        // $(".iframe-class-resize").removeAttr("height");
        $(".iframe-class").removeClass("iframe-class-resize");
    }
}
</code>```

http://jsfiddle.net/TBJ83/

Problem:
As the window is resized smaller, it continually checks the window width and once it hits < 480 px, the code adds a class called iframe-class-resize and sets the width and height to that class. As the window is resized larger, it removes the class once the size hits 480 px. The problem is that setting the width and height attributes adds them directly to the element and not the class itself. Therefore, removing the class does not remove the new width and heights. I tried to force removing the attributes using removeAttr() (commented out above) but that didn't work.

Anyone see where the code above went wrong? Or any suggestions on how to accomplish having a responsive iframe more effectively? The main things that are required are that the iframe has to be inside the

 and the div may not necessarily have a width or height defined. Ideally, the parent div should have the width and height explicitly defined but the way this site is currently setup, that won't always be possible.

Additional:
In case the above wasn't clear enough, try the following to reproduce the issue:

Open up a browser on a desktop machine. I'm using Chrome on a Windows machine. Don't maximize the browser.

Open up the jsfiddle above (http://jsfiddle.net/TBJ83/). You'll notice that the iframe content spans the entire width of the Preview panel.

Manually resize the width down until the entire window is < 480px. At this point, the iframe content will be pretty tiny.

Manually resize the width back up until the entire window is >> 480px. The goal is to have that iframe content to regain the entire width of the Preview panel. Instead, the content is retaining the resized width and height since the .css() function applies css changes directly to elements rather than to the classes.

Thanks in advance!

答:
This can be done using pure CSS as below:

```<code>iframe {
  height: 300px;
  width: 300px;
  resize: both;
  overflow: auto;
}
</code>```

Set the height and width to the minimum size you want, it only seems to grow, not shrink.

Title: Dynamically resize iframe

Body:
Situation:
I'm working on a responsive design that involves the typical HTML/CSS combo. Everything is working nicely except in one case where there is an iframe inside of a div. The iframe should adjust automatically to the size of the parent div. A purely css solution has not presented itself so I'm going with a JQuery approach. It works nicely except in one scenario, when resizing from a smaller width to a larger width screen.

HTML:

CSS:

.container {
    width: 100%;
    height: 250px;
}
.iframe-class {
    width: 100%;
    height: 100%;
    border: 1px solid red;
    overflow: auto;
}

Javascript:

$(function () {
    setIFrameSize();
    $(window).resize(function () {
        setIFrameSize();
    });
});

function setIFrameSize() {
    var ogWidth = 700;
    var ogHeight = 600;
    var ogRatio = ogWidth / ogHeight;

    var windowWidth = $(window).width();
    if (windowWidth < 480) {
        var parentDivWidth = $(".iframe-class").parent().width();
        var newHeight = (parentDivWidth / ogRatio);
        $(".iframe-class").addClass("iframe-class-resize");
        $(".iframe-class-resize").css("width", parentDivWidth);
        $(".iframe-class-resize").css("height", newHeight);
    } else {
        // $(".iframe-class-resize").removeAttr("width");
        // $(".iframe-class-resize").removeAttr("height");
        $(".iframe-class").removeClass("iframe-class-resize");
    }
}

http://jsfiddle.net/TBJ83/

Problem:
As the window is resized smaller, it continually checks the window width and once it hits < 480 px, the code adds a class called iframe-class-resize and sets the width and height to that class. As the window is resized larger, it removes the class once the size hits 480 px. The problem is that setting the width and height attributes adds them directly to the element and not the class itself. Therefore, removing the class does not remove the new width and heights. I tried to force removing the attributes using removeAttr() (commented out above) but that didn't work.

Anyone see where the code above went wrong? Or any suggestions on how to accomplish having a responsive iframe more effectively? The main things that are required are that the iframe has to be inside the

 and the div may not necessarily have a width or height defined. Ideally, the parent div should have the width and height explicitly defined but the way this site is currently setup, that won't always be possible.

Additional:
In case the above wasn't clear enough, try the following to reproduce the issue:

Open up a browser on a desktop machine. I'm using Chrome on a Windows machine. Don't maximize the browser.

Open up the jsfiddle above (http://jsfiddle.net/TBJ83/). You'll notice that the iframe content spans the entire width of the Preview panel.

Manually resize the width down until the entire window is < 480px. At this point, the iframe content will be pretty tiny.

Manually resize the width back up until the entire window is >> 480px. The goal is to have that iframe content to regain the entire width of the Preview panel. Instead, the content is retaining the resized width and height since the .css() function applies css changes directly to elements rather than to the classes.

Thanks in advance!

Body:
This can be done using pure CSS as below:

iframe {
  height: 300px;
  width: 300px;
  resize: both;
  overflow: auto;
}

Set the height and width to the minimum size you want, it only seems to grow, not shrink.


问:
How to inverse a conditional in JavaScript
I have a function that changes the case of some text and returns it, based on the value of capitalisation. I would like to pass another parameter called inverse, which if true, basically performs the opposite; so if capitalisation is lowercase, it will make the text lower case instead of uppercase.

It's important that the value of capitalisation does not change, because it's used by other parts of the application.

I'm looking for a really succinct way to do this with minimal code.

```<code>       capitalisation = "lowercase";

       function switchCase(text, inverse) {
            if (capitalisation === "lowercase") {
                text = text.toLowerCase();
            } else {
                text = text.toUpperCase();
            }
            return text;
        }
</code>```

答:
You could take advantage of the fact that JS treats functions as first class citizens and store in a dictionary the functions to apply to the string. Then just retrieve the correct function depending on the value of capitalisation and inverse.

var capitalisation = "lowercase";

function switchCase(text, inverse) {
  var strProto = String.prototype,
    inverseType = function(capitalisation) {
      return capitalisation === "lowercase" ? "uppercase" : "lowercase";
    },
    fncDict = {
      "uppercase": strProto.toUpperCase,
      "lowercase": strProto.toLowerCase
    };

  return inverse ? fncDict[inverseType(capitalisation)].apply(text) : fncDict[capitalisation].apply(text);
}

console.log(switchCase("ASDF", false));
console.log(switchCase("ASDF", true));```

Body:
I have a function that changes the case of some text and returns it, based on the value of capitalisation. I would like to pass another parameter called inverse, which if true, basically performs the opposite; so if capitalisation is lowercase, it will make the text lower case instead of uppercase.

It's important that the value of capitalisation does not change, because it's used by other parts of the application.

I'm looking for a really succinct way to do this with minimal code.

       capitalisation = "lowercase";

       function switchCase(text, inverse) {
            if (capitalisation === "lowercase") {
                text = text.toLowerCase();
            } else {
                text = text.toUpperCase();
            }
            return text;
        }


问:
php - unlink throws error: Resource temporarily unavailable
Here is the piece of code:

```<code>public function uploadPhoto(){
    $filename = '../storage/temp/image.jpg';
    file_put_contents($filename,file_get_contents('http://example.com/image.jpg'));
    $photoService->uploadPhoto($filename);
    echo("If file exists: ".file_exists($filename));
    unlink($filename);
}
</code>```

I am trying to do the following things:

Get a photo from a URL and save it in a temp folder in my server. This works fine. The image file is created and echoes If file exists: 1 when echo("If file exists: ".file_exists('../storage/temp/image.jpg'));.

Pass that file to another function that hanldes uploading the file to Amazon s3 bucket. The file gets stored in my s3 bucket.

Delete the photo stored in the temp folder. This doesn't work! I get an error saying:

unlink(../storage/temp/image.jpg): Resource temporarily unavailable

If I use rename($filename,'../storage/temp/renimage.jpg'); instead of unlink($filename); i get an error:

rename(../storage/temp/image.jpg,../storage/temp/renimage.jpg): The process cannot access the file because it is being used by another process. (code: 32)

If I remove the function call $photoService->uploadPhoto($filename);, everything works perfectly fine.

If the file is being used by another process, how do I unlink it after the process has been completed and the file is no longer being used by any process? I do not want to use timers.

Please help! Thanks in advance.

答:
The unlink method return bool value, so you can build a cycle, with some wait() and retries limit to wait for your processes to complete.

Additionally put "@" on the unlink, to hide the access error.

Throw another error/exception if retries count reached.

Body:
Here is the piece of code:

public function uploadPhoto(){
    $filename = '../storage/temp/image.jpg';
    file_put_contents($filename,file_get_contents('http://example.com/image.jpg'));
    $photoService->uploadPhoto($filename);
    echo("If file exists: ".file_exists($filename));
    unlink($filename);
}

I am trying to do the following things:

Get a photo from a URL and save it in a temp folder in my server. This works fine. The image file is created and echoes If file exists: 1 when echo("If file exists: ".file_exists('../storage/temp/image.jpg'));.

Pass that file to another function that hanldes uploading the file to Amazon s3 bucket. The file gets stored in my s3 bucket.

Delete the photo stored in the temp folder. This doesn't work! I get an error saying:

unlink(../storage/temp/image.jpg): Resource temporarily unavailable

If I use rename($filename,'../storage/temp/renimage.jpg'); instead of unlink($filename); i get an error:

rename(../storage/temp/image.jpg,../storage/temp/renimage.jpg): The process cannot access the file because it is being used by another process. (code: 32)

If I remove the function call $photoService->uploadPhoto($filename);, everything works perfectly fine.

If the file is being used by another process, how do I unlink it after the process has been completed and the file is no longer being used by any process? I do not want to use timers.

Please help! Thanks in advance.


问:
How can I implement an anti-spamming technique on my IRC bot?
I run my bot in a public channel with hundreds of users. Yesterday a person came in and just abused it.

I would like to let anyone use the bot, but if they spam commands consecutively  and if they aren't a bot "owner" like me when I debug then I would like to add them to an ignored list which expires in an hour or so.

One way I'm thinking would be to save all commands by all users, in a dictionary such as:

```<code>({
  'meder@freenode': [{command:'.weather 20851', timestamp: 209323023 }],
  'jack@efnet': [{command:'.seen john' }]
})
</code>```

I would setup a cron job to flush this out every 24 hours, but I would basically determine if a person has made X number of commands in a duration of say, 15 seconds and add them to an ignore list.

Actually, as I'm writing this answer I thought of a better idea.. maybe instead of storing each users commands, just store the the bot's commands in a list and keep on pushing until it reaches a limit of say, 15.

```<code>lastCommands = [], limit = 5;

function handleCommand( timeObj, action ) {
    if ( lastCommands.length < limit ) {
        action();
    } else {
        // enumerate through lastCommands and compare the timestamps of all 5 commands
        // if the user is the same for all 5 commands, and...
        // if the timestamps are all within the vicinity of 20 seconds
        // add the user to the ignoreList
    }
}

watch_for('command', function() {
   handleCommand({timestamp: 2093293032, user: user}, function(){ message.say('hello there!') })
});
</code>```

I would appreciate any advice on the matter.

答:
Redis

I would use the insanely fast advanced key-value store redis to write something like this, because:

It is insanely fast.

There is no need for cronjob because you can set expire on keys.

It has atomic operations to increment key

You could use redis-cli for prototyping.

I myself really like node_redis as redis client. It is a really fast redis client, which can easily be installed using npm.

Algorithme

I think my algorithme would look something like this:

For each user create a unique key which counts the commands consecutively executed. Also set expire to the time when you don't flag a user as spammer anymore. Let's assume the spammer has nickname x and the expire 15.

Inside redis-cli

incr x

expire x 15

When you do a get x after 15 seconds then the key does not exist anymore.

If value of key is bigger then threshold then flag user as spammer.

get x

Body:
I run my bot in a public channel with hundreds of users. Yesterday a person came in and just abused it.

I would like to let anyone use the bot, but if they spam commands consecutively  and if they aren't a bot "owner" like me when I debug then I would like to add them to an ignored list which expires in an hour or so.

One way I'm thinking would be to save all commands by all users, in a dictionary such as:

({
  'meder@freenode': [{command:'.weather 20851', timestamp: 209323023 }],
  'jack@efnet': [{command:'.seen john' }]
})

I would setup a cron job to flush this out every 24 hours, but I would basically determine if a person has made X number of commands in a duration of say, 15 seconds and add them to an ignore list.

Actually, as I'm writing this answer I thought of a better idea.. maybe instead of storing each users commands, just store the the bot's commands in a list and keep on pushing until it reaches a limit of say, 15.

lastCommands = [], limit = 5;

function handleCommand( timeObj, action ) {
    if ( lastCommands.length < limit ) {
        action();
    } else {
        // enumerate through lastCommands and compare the timestamps of all 5 commands
        // if the user is the same for all 5 commands, and...
        // if the timestamps are all within the vicinity of 20 seconds
        // add the user to the ignoreList
    }
}

watch_for('command', function() {
   handleCommand({timestamp: 2093293032, user: user}, function(){ message.say('hello there!') })
});

I would appreciate any advice on the matter.


问:
Codeigniter set_checkbox() keeping checked state
I have this code in my view:

```<code><input type="checkbox" name="test[]" value="1" <?php echo set_checkbox("test[]", "1") ?> >test1

<input type="checkbox" name="test[]" value="2" <?php echo set_checkbox("test[]", "2") ?> >test2
</code>```

These checkboxes are not required, but some other fields on the form are. I want to keep the state of these checkboxes when I post the form. The values from the checkboxes are in the POST if they are checked, but the checked state is not kept when the form loads again after the post (if some of them is checked before the post, I want it to be checked after the post). I also tried set_checkbox(“test”, “1”), but it didn’t work. The values on the other text fields is kept using the set_value() function and is working fine.

答:
When you're using an array like "test[]" in form, you don't need to include the square brackets ([]) in your set_checkbox call.

The set_checkbox should always be like this:

```<code>set_checkbox('test', 'value');
</code>```

Where 'value' is the second parameter of the form checkbox.

Body:
I have this code in my view:

<input type="checkbox" name="test[]" value="1" <?php echo set_checkbox("test[]", "1") ?> >test1

<input type="checkbox" name="test[]" value="2" <?php echo set_checkbox("test[]", "2") ?> >test2

These checkboxes are not required, but some other fields on the form are. I want to keep the state of these checkboxes when I post the form. The values from the checkboxes are in the POST if they are checked, but the checked state is not kept when the form loads again after the post (if some of them is checked before the post, I want it to be checked after the post). I also tried set_checkbox(“test”, “1”), but it didn’t work. The values on the other text fields is kept using the set_value() function and is working fine.

Body:
When you're using an array like "test[]" in form, you don't need to include the square brackets ([]) in your set_checkbox call.

The set_checkbox should always be like this:

set_checkbox('test', 'value');

Where 'value' is the second parameter of the form checkbox.


问:
What is the function of the & character in overloading std::cout?
I understand that the & character has various uses in c++, but I'm having trouble understanding what its function is in the code sample below (taken from here) (not its use in the left argument, but its use in std ostream&.

```<code>std::ostream& operator<< (std::ostream &out, const Point &point)
{
    // Since operator<< is a friend of the Point class, we can access Point's members directly.
    out << "Point(" << point.m_x << ", " << point.m_y << ", " << point.m_z << ")";

    return out;
}
</code>```

I think I understand the use of & when it represents a pass by reference inside a function parameter, but I can't see what it would do outside a function.

As far as I can see (which isn't very far at all), std::ostream is an class, which, when instantiated, can, via the operator <<, can be fed strings etc. to output to console. Then &out in the code above is a reference to an instance of std::ostream, (which will be std::cout?), which inside the function is fed point.m_x etc. and then returned so that multiple << operations can be performed.

I'm guessing the first instance of the & character is somehow communicating that the << operator defined in std::ostream is to be modified in some way, in order to allow it to function with members of the example Point class, but I want to have a better understanding than that.

答:
I think I understand the use of & when it represents a pass by reference inside a function parameter, but I can't see what it would do outside a function.

It means that the function returns an std::ostream by reference.

Body:
I understand that the & character has various uses in c++, but I'm having trouble understanding what its function is in the code sample below (taken from here) (not its use in the left argument, but its use in std ostream&.

std::ostream& operator<< (std::ostream &out, const Point &point)
{
    // Since operator<< is a friend of the Point class, we can access Point's members directly.
    out << "Point(" << point.m_x << ", " << point.m_y << ", " << point.m_z << ")";

    return out;
}

I think I understand the use of & when it represents a pass by reference inside a function parameter, but I can't see what it would do outside a function.

As far as I can see (which isn't very far at all), std::ostream is an class, which, when instantiated, can, via the operator <<, can be fed strings etc. to output to console. Then &out in the code above is a reference to an instance of std::ostream, (which will be std::cout?), which inside the function is fed point.m_x etc. and then returned so that multiple << operations can be performed.

I'm guessing the first instance of the & character is somehow communicating that the << operator defined in std::ostream is to be modified in some way, in order to allow it to function with members of the example Point class, but I want to have a better understanding than that.