问:
Why does PlaceAutocompleteFragment crashes with NoSuchMethodError?
I am trying to find place from Google map in my android
my code is

```<code>PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
            getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            // TODO: Get info about the selected place.
            Log.i(TAG, "Place: " + place.getName());

            String placeDetailsStr = place.getName() + "\n"
                    + place.getId() + "\n"
                    + place.getLatLng().toString() + "\n"
                    + place.getAddress() + "\n"
                    + place.getAttributions();
        }

        @Override
        public void onError(Status status) {
            // TODO: Handle the error.
            Log.i(TAG, "An error occurred: " + status);
        }
    });
</code>```

but when I try to enter something it crashes with error

```<code>FATAL EXCEPTION: main                                                    Process: com.example.asset.lab13_bonus, PID: 1192
                                                                         java.lang.NoSuchMethodError: No virtual method zzbo(Landroid/content/Context;)V in class Lcom/google/android/gms/common/GoogleApiAvailability; or its super classes (declaration of 'com.google.android.gms.common.GoogleApiAvailability' appears in /data/app/com.example.asset.lab13_bonus-bAk1S6P8t8HToIo1FR8JeA==/split_lib_dependencies_apk.apk:classes12.dex)
                                                                             at com.google.android.gms.location.places.ui.zza$zza.build(Unknown Source:79)
                                                                             at com.google.android.gms.location.places.ui.PlaceAutocomplete$IntentBuilder.build(Unknown Source:0)
                                                                             at com.google.android.gms.location.places.ui.PlaceAutocompleteFragment.zzboi(Unknown Source:42)
                                                                             at com.google.android.gms.location.places.ui.PlaceAutocompleteFragment.zza(Unknown Source:0)
                                                                             at com.google.android.gms.location.places.ui.PlaceAutocompleteFragment$1.onClick(Unknown Source:2)
                                                                             at android.view.View.performClick(View.java:6256)
                                                                             at android.view.View$PerformClick.run(View.java:24697)
                                                                             at android.os.Handler.handleCallback(Handler.java:789)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                             at android.os.Looper.loop(Looper.java:164)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

Gradle dependencies :

```<code>compile 'com.google.android.gms:play-services-maps:11.0.4'
compile 'com.google.android.gms:play-services-places:9.4.0'
compile "com.google.android.gms:play-services-base:9.4.0"
</code>```

what does this mean ?
Can someone help me?
May be it does not work because of device?

答: Try to make sure all your dependencies are the same version to avoid conflicts, whether it be 9.4.0 or 11.0.4.  Older versions could work fine but you might be missing out on some features the newer ones provide.</p>

Body:
I am trying to find place from Google map in my android
my code is

PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
            getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            // TODO: Get info about the selected place.
            Log.i(TAG, "Place: " + place.getName());

            String placeDetailsStr = place.getName() + "\n"
                    + place.getId() + "\n"
                    + place.getLatLng().toString() + "\n"
                    + place.getAddress() + "\n"
                    + place.getAttributions();
        }

        @Override
        public void onError(Status status) {
            // TODO: Handle the error.
            Log.i(TAG, "An error occurred: " + status);
        }
    });

but when I try to enter something it crashes with error

FATAL EXCEPTION: main                                                    Process: com.example.asset.lab13_bonus, PID: 1192
                                                                         java.lang.NoSuchMethodError: No virtual method zzbo(Landroid/content/Context;)V in class Lcom/google/android/gms/common/GoogleApiAvailability; or its super classes (declaration of 'com.google.android.gms.common.GoogleApiAvailability' appears in /data/app/com.example.asset.lab13_bonus-bAk1S6P8t8HToIo1FR8JeA==/split_lib_dependencies_apk.apk:classes12.dex)
                                                                             at com.google.android.gms.location.places.ui.zza$zza.build(Unknown Source:79)
                                                                             at com.google.android.gms.location.places.ui.PlaceAutocomplete$IntentBuilder.build(Unknown Source:0)
                                                                             at com.google.android.gms.location.places.ui.PlaceAutocompleteFragment.zzboi(Unknown Source:42)
                                                                             at com.google.android.gms.location.places.ui.PlaceAutocompleteFragment.zza(Unknown Source:0)
                                                                             at com.google.android.gms.location.places.ui.PlaceAutocompleteFragment$1.onClick(Unknown Source:2)
                                                                             at android.view.View.performClick(View.java:6256)
                                                                             at android.view.View$PerformClick.run(View.java:24697)
                                                                             at android.os.Handler.handleCallback(Handler.java:789)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                             at android.os.Looper.loop(Looper.java:164)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Gradle dependencies :

compile 'com.google.android.gms:play-services-maps:11.0.4'
compile 'com.google.android.gms:play-services-places:9.4.0'
compile "com.google.android.gms:play-services-base:9.4.0"

what does this mean ?
Can someone help me?
May be it does not work because of device?


来源: stackexchange

问:
How to achieve sequence of timeouts with RX?
The scenario is as follows: a device communicating over is considered connected if it makes a callback to the server within a short period of time.
I want to create a class that encapsulates the functionality of keeping track of this status. On call to the device, the timeout should be reset. On callback, the connection is confirmed, and the status should be set to true, if the callback times out, it should be set to false. But the next call should be able to reset the timeout again indifferent to the current status.

I was thinking to achieve this with RX using swith and timeout. But I don't know why it stops working.

```<code>public class ConnectionStatus
{
private Subject<bool> pending = new Subject<bool>();
private Subject<bool> connected = new Subject<bool>();

public bool IsConnected { get; private set; }

public ConnectionStatus(CancellationToken token, short timeoutSeconds = 15)
{
    pending.Select(outer => connected.Timeout(TimeSpan.FromSeconds(timeoutSeconds)))
        .Switch()
        .Subscribe(_ => IsConnected = true, e => IsConnected = false, token);
}

public void ConfirmConnected()
{
    connected.OnNext(true);
}

public void SetPending()
{
    pending.OnNext(true);
}
}
</code>```

This is the "test case":

```<code>var c = new ConnectionStatus(default(CancellationToken));

c.SetPending();
await Task.Delay(TimeSpan.FromSeconds(5));
c.ConfirmConnected();
c.IsConnected.Dump(); // TRUE, OK

c.SetPending();
await Task.Delay(TimeSpan.FromSeconds(5));
c.ConfirmConnected();
c.IsConnected.Dump(); // TRUE, OK

c.SetPending();
await Task.Delay(TimeSpan.FromSeconds(20));
c.IsConnected.Dump(); // FALSE, OK
c.ConfirmConnected();
c.IsConnected.Dump(); // FALSE, OK

c.SetPending();
await Task.Delay(TimeSpan.FromSeconds(10));
c.ConfirmConnected();
c.IsConnected.Dump(); // FALSE, NOT OK!
</code>```

I assume that the timeout of the inner observable is also stopping the outer observable. As the outer => lambda is not called anymore. What is the correct way?

Thank you

答:
Here's an alternative way to produce the stream of IsConnected values without using .TimeOut:

```<code>public class ConnectionStatus
{
    private Subject<Unit> pending = new Subject<Unit>();
    private Subject<Unit> connected = new Subject<Unit>();

    public bool IsConnected { get; private set; }

    public ConnectionStatus(CancellationToken token, short timeoutSeconds = 15)
    {
        pending
            .Select(outer =>
                Observable.Amb(
                    connected.Select(_ => true),
                    Observable.Timer(TimeSpan.FromSeconds(timeoutSeconds)).Select(_ => false)))
            .Switch()
            .Subscribe(isConnected => IsConnected = isConnected, token);
    }

    public void ConfirmConnected()
    {
        connected.OnNext(Unit.Default);
    }

    public void SetPending()
    {
        pending.OnNext(Unit.Default);
    }
}
</code>```

The Observable.Amb operator simply takes a value from whichever observable produces a value first - it's preferable to coding with exceptions.

ContentLicense: CC BY-SA 3.0

Body:
The scenario is as follows: a device communicating over is considered connected if it makes a callback to the server within a short period of time.
I want to create a class that encapsulates the functionality of keeping track of this status. On call to the device, the timeout should be reset. On callback, the connection is confirmed, and the status should be set to true, if the callback times out, it should be set to false. But the next call should be able to reset the timeout again indifferent to the current status.

I was thinking to achieve this with RX using swith and timeout. But I don't know why it stops working.

public class ConnectionStatus
{
private Subject<bool> pending = new Subject<bool>();
private Subject<bool> connected = new Subject<bool>();

public bool IsConnected { get; private set; }

public ConnectionStatus(CancellationToken token, short timeoutSeconds = 15)
{
    pending.Select(outer => connected.Timeout(TimeSpan.FromSeconds(timeoutSeconds)))
        .Switch()
        .Subscribe(_ => IsConnected = true, e => IsConnected = false, token);
}

public void ConfirmConnected()
{
    connected.OnNext(true);
}

public void SetPending()
{
    pending.OnNext(true);
}
}

This is the "test case":

var c = new ConnectionStatus(default(CancellationToken));

c.SetPending();
await Task.Delay(TimeSpan.FromSeconds(5));
c.ConfirmConnected();
c.IsConnected.Dump(); // TRUE, OK

c.SetPending();
await Task.Delay(TimeSpan.FromSeconds(5));
c.ConfirmConnected();
c.IsConnected.Dump(); // TRUE, OK

c.SetPending();
await Task.Delay(TimeSpan.FromSeconds(20));
c.IsConnected.Dump(); // FALSE, OK
c.ConfirmConnected();
c.IsConnected.Dump(); // FALSE, OK

c.SetPending();
await Task.Delay(TimeSpan.FromSeconds(10));
c.ConfirmConnected();
c.IsConnected.Dump(); // FALSE, NOT OK!

I assume that the timeout of the inner observable is also stopping the outer observable. As the outer => lambda is not called anymore. What is the correct way?

Thank you

Body:
Here's an alternative way to produce the stream of IsConnected values without using .TimeOut:

public class ConnectionStatus
{
    private Subject<Unit> pending = new Subject<Unit>();
    private Subject<Unit> connected = new Subject<Unit>();

    public bool IsConnected { get; private set; }

    public ConnectionStatus(CancellationToken token, short timeoutSeconds = 15)
    {
        pending
            .Select(outer =>
                Observable.Amb(
                    connected.Select(_ => true),
                    Observable.Timer(TimeSpan.FromSeconds(timeoutSeconds)).Select(_ => false)))
            .Switch()
            .Subscribe(isConnected => IsConnected = isConnected, token);
    }

    public void ConfirmConnected()
    {
        connected.OnNext(Unit.Default);
    }

    public void SetPending()
    {
        pending.OnNext(Unit.Default);
    }
}

The Observable.Amb operator simply takes a value from whichever observable produces a value first - it's preferable to coding with exceptions.


问:
Failure to execute cql script using cqlsh with nested SOURCE on DSE 5.1.2
I have a script I used to execute queries and DDL in DSE 4.8.10.

The script include nested use of the SOURCE command.
E.g.

1.sql

```<code>USE test;
SOURCE '2.sql'
exit;
</code>```

2.sql

```<code>SELECT count(1) FROM user;
SOURCE '3.sql';
</code>```

3.sql

```<code>SELECT count(1) FROM user;
</code>```

When executing this script with DSE 4.8.10 it runs correctly and output

```<code>cqlsh –f  1.sql
count
--------
 0

(1 rows)

count
--------
 0

(1 rows)
</code>```

Running the same script in DSE 5.1.2.

```<code>cqlsh –f  1.sql
 count
-------
     0

(1 rows)

Warnings :
Aggregation query used without partition key

2.sql:3:DSEShell instance has no attribute 'execution_profiles'
</code>```

The actual issue is that the script in 3.sql is not executed.

I failed to find any useful information on the error
"DSEShell instance has no attribute 'execution_profiles'"

I failed to figure out what are execution_profiles although they are mentioned int the python docs here

Note: I am using python 2.7.7

Update
I did some additional investigations

With DSE-5.1.2 I switch the off to authenticator: AllowAllAuthenticator
authorizer: AllowAllAuthorizer, but I am still experiencing the issue

With  DSE-5.1.1 it also happens

With DSE-5.0.9 it works

I failed to reproduce this in Apache Cassandra 3.11.0

Update 2: following support ticket we posted for Datastaxs we got a patch for this issue, I guess we should be expecting this to be fixed in the near feature.

答:
As from DSE 5.1.4 this issue was resolved as part of DSP-14494.

See the 5.1.4 release notes

DSP-14494:Always define execution_profiles in cqlsh.py.

I tested this with 5.1.4 and the issue was resolved.

ContentLicense: CC BY-SA 4.0

Body:
I have a script I used to execute queries and DDL in DSE 4.8.10.

The script include nested use of the SOURCE command.
E.g.

1.sql

USE test;
SOURCE '2.sql'
exit;

2.sql

SELECT count(1) FROM user;
SOURCE '3.sql';

3.sql

SELECT count(1) FROM user;

When executing this script with DSE 4.8.10 it runs correctly and output

cqlsh –f  1.sql
count
--------
 0

(1 rows)

count
--------
 0

(1 rows)

Running the same script in DSE 5.1.2.

cqlsh –f  1.sql
 count
-------
     0

(1 rows)

Warnings :
Aggregation query used without partition key

2.sql:3:DSEShell instance has no attribute 'execution_profiles'

The actual issue is that the script in 3.sql is not executed.

I failed to find any useful information on the error
"DSEShell instance has no attribute 'execution_profiles'"

I failed to figure out what are execution_profiles although they are mentioned int the python docs here

Note: I am using python 2.7.7

Update
I did some additional investigations

With DSE-5.1.2 I switch the off to authenticator: AllowAllAuthenticator
authorizer: AllowAllAuthorizer, but I am still experiencing the issue

With  DSE-5.1.1 it also happens

With DSE-5.0.9 it works

I failed to reproduce this in Apache Cassandra 3.11.0

Update 2: following support ticket we posted for Datastaxs we got a patch for this issue, I guess we should be expecting this to be fixed in the near feature.


问:
I want to Use Spring JPARepository in Generic way, so that same line of code i have to not write for all enitties
I am new to Spring and want to use JpaRepository in a Generic way, so that i can use the same interface for all.
Please suggest some examples.
Thanks :)

Like i have 2 entities Employee.java & Student.java

```<code>@Repository
public interface EmployeeRepo<T, ID extends Serializable> extends JpaRepository<Employee, ID> {

}
</code>```

答:
There is no way to do this in Spring Data. The inner mechanics of Spring Data need the type parameters from the interface definition and if there is no interface definition with specific type parameters only the bound of the type parameters (Object in case of doubt) is available which is not usable.

Also, you shouldn't have a Repository per Entity but per Aggregate. See this answer for details: Are you supposed to have one repository per table in JPA?

Body:
I am new to Spring and want to use JpaRepository in a Generic way, so that i can use the same interface for all.
Please suggest some examples.
Thanks :)

Like i have 2 entities Employee.java & Student.java

@Repository
public interface EmployeeRepo<T, ID extends Serializable> extends JpaRepository<Employee, ID> {

}


问:
How to stack two images and center in the middle
I want the images to be centered  and I need two of the images to be stacked up on each other in the center. I have logo on the left and nav bar on the right

.projImg {
  margin: 0;
}

.projImg img {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="mainProj">
    <main>
        <figure class="projImg">
            <img src="https://i.imgur.com/UiAiZYm.jpg" alt="projectImage1">
        </figure>

        <figure class="projImg">
            <img src="https://i.imgur.com/4F4Agjz.jpg" alt="projectImage2">
        </figure>

        <figure class="projImg">
            <img src="https://i.imgur.com/GncQ8QI.jpg" alt="projectImage3">
        </figure>

        <figure class="projImg">
            <img src="https://i.imgur.com/MGkSJza.jpg" alt="projectImage4">
        </figure>
    </main>
  </div></code>```

答:
Use following code...

.projImg {
  text-align:center;
  width: 50%;
  float:left;
  margin:0;
}

.projImg img {
  display: inline-block;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="mainProj">
    <main>
        <figure class="projImg">
            <img src="https://i.imgur.com/UiAiZYm.jpg" alt="projectImage1">
        </figure>

        <figure class="projImg">
            <img src="https://i.imgur.com/4F4Agjz.jpg" alt="projectImage2">
        </figure>

        <figure class="projImg">
            <img src="https://i.imgur.com/GncQ8QI.jpg" alt="projectImage3">
        </figure>

        <figure class="projImg">
            <img src="https://i.imgur.com/MGkSJza.jpg" alt="projectImage4">
        </figure>
    </main>
  </div></code>```

Body:
Use following code...

.projImg {
  text-align:center;
  width: 50%;
  float:left;
  margin:0;
}

.projImg img {
  display: inline-block;
  width: 100%;
}

  <div class="mainProj">
    <main>
        <figure class="projImg">
            <img src="https://i.imgur.com/UiAiZYm.jpg" alt="projectImage1">
        </figure>

        <figure class="projImg">
            <img src="https://i.imgur.com/4F4Agjz.jpg" alt="projectImage2">
        </figure>

        <figure class="projImg">
            <img src="https://i.imgur.com/GncQ8QI.jpg" alt="projectImage3">
        </figure>

        <figure class="projImg">
            <img src="https://i.imgur.com/MGkSJza.jpg" alt="projectImage4">
        </figure>
    </main>
  </div>


问:
Understanding * (zero or more) operator using re.search()
I am new to python and was going through "Google for Education" python course

Now, the line below confuses me:

* -- 0 or more occurrences of the pattern to its left

(all the examples are in python3)

e.g. 1

```<code>In [1]: re.search(r"pi*", "piiig!!").group()
Out[1]: 'piii'
</code>```

This is fine since, "pi" has 1 occurrance so it is retured

e.g. 2

```<code>In [2]: re.search(r"i*", "piiig!!").group()
Out[2]: ''
</code>```

Why does it not return "i" in fact - from my understanding, it should be returning "iii". But the result is an empty string.

Also, What exactly does "0 or more" mean? I searched on google but everywhere it is mentioned * -- 0 or more. But if there is 0 occurrence of an expression, does that not become true even if it's not there? What is the point of searching then?

I am so confused with this. Can you please help me with explaining this or point me in the right direction.

i hope the right explanation would also resolve my this issue:

```<code>In [3]: re.search(r"i?", "piiig!!").group()
Out[3]: ''
</code>```

I have tried the examples in Spyder 3.2.4

答:
The special charecter * means 0 or more occurrence of the preceding character. For eg. a* matches with 0 or more occurrence of a which could be '', 'a', 'aa' etc. This happens because '' has 0 occurrence of a.
To get iii you should have used + instead of * and thus would have got the first non zero  sequence of 'i' which is iii

```<code>re.search("i+", "piiig!!").group()
</code>```

Body:
I am new to python and was going through "Google for Education" python course

Now, the line below confuses me:

* -- 0 or more occurrences of the pattern to its left

(all the examples are in python3)

e.g. 1

In [1]: re.search(r"pi*", "piiig!!").group()
Out[1]: 'piii'

This is fine since, "pi" has 1 occurrance so it is retured

e.g. 2

In [2]: re.search(r"i*", "piiig!!").group()
Out[2]: ''

Why does it not return "i" in fact - from my understanding, it should be returning "iii". But the result is an empty string.

Also, What exactly does "0 or more" mean? I searched on google but everywhere it is mentioned * -- 0 or more. But if there is 0 occurrence of an expression, does that not become true even if it's not there? What is the point of searching then?

I am so confused with this. Can you please help me with explaining this or point me in the right direction.

i hope the right explanation would also resolve my this issue:

In [3]: re.search(r"i?", "piiig!!").group()
Out[3]: ''

I have tried the examples in Spyder 3.2.4

Body:
The special charecter * means 0 or more occurrence of the preceding character. For eg. a* matches with 0 or more occurrence of a which could be '', 'a', 'aa' etc. This happens because '' has 0 occurrence of a.
To get iii you should have used + instead of * and thus would have got the first non zero  sequence of 'i' which is iii

re.search("i+", "piiig!!").group()


问:
Wordpress - CPT and ACF Plugins
I'm about starting developing my own theme by using CPT and ACF Plugins. I read some articles and reviews about CPT as well as ACF and most of the developers they love them because they are very easy to use and helpful. However some of them they gave very bad feedback in terms of security, stability and slowing down the performance of the website; even they said these plugins for non-technical developers which developing for cheap clients.

What do you think about this? because I like CPT and ACF very much once I tried doing things with them. However I don't want to put my self in a risk by using these plugins.

Also do you suggest another professional way to create Custom Post Type and Custom Fields? or do you prefer CPT and ACF anyway for even the advanced developer?

Thanks.

答:
First of all

It is depending on your requirements. If you have to create only one or two post type. I don't think it is really a need to use those plugins. Because both are heavy plugins.So better to use custom code to create post type. and custom field.

Regarding the plugins, It is true that CPT is more heavy then ACF. I have used ACF from the beginning. Before that CPT was my favourite. I came to know about the above complexity as i have much more experience with those plugins.

Title: Wordpress - CPT and ACF Plugins


问:
view (VIEW ONLINE) file instead of download from gridview using Eval in asp.net
I want to make a button (VIEW ONLINE) so that people can view PDF online in new tab when they click on it and those who want to download they can easily download. i have developed download but failed to make VIEW ONLINE .</p>

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string[] filePaths = Directory.GetFiles(Server.MapPath("~/App_Data/urg_list/"));
        List<ListItem> files = new List<ListItem>();
        foreach (string filePath in filePaths)
        {
            files.Add(new ListItem(Path.GetFileName(filePath), filePath));
        }
        GridView1.DataSource = files;
        GridView1.DataBind();
    }
}
protected void DownloadFile(object sender, EventArgs e)
{
    string filePath = (sender as LinkButton).CommandArgument;
    Response.ContentType = ContentType;
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
    Response.WriteFile(filePath);
    Response.End();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{

}
</code>```

答:
For that you have to set the content disposition as inline instead of attachment.
Try the below, this may work.

```<code>Response.AddHeader("content-disposition", "inline;filename=" + filename + ".pdf");
</code>```

or

```<code>Response.AppendHeader("Content-Disposition", "inline; filename=" + Path.GetFileName(filePath));
</code>```

Body:
I want to make a button (VIEW ONLINE) so that people can view PDF online in new tab when they click on it and those who want to download they can easily download. i have developed download but failed to make VIEW ONLINE .

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string[] filePaths = Directory.GetFiles(Server.MapPath("~/App_Data/urg_list/"));
        List<ListItem> files = new List<ListItem>();
        foreach (string filePath in filePaths)
        {
            files.Add(new ListItem(Path.GetFileName(filePath), filePath));
        }
        GridView1.DataSource = files;
        GridView1.DataBind();
    }
}
protected void DownloadFile(object sender, EventArgs e)
{
    string filePath = (sender as LinkButton).CommandArgument;
    Response.ContentType = ContentType;
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
    Response.WriteFile(filePath);
    Response.End();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{

}

Body:
For that you have to set the content disposition as inline instead of attachment.
Try the below, this may work.

Response.AddHeader("content-disposition", "inline;filename=" + filename + ".pdf");

or

Response.AppendHeader("Content-Disposition", "inline; filename=" + Path.GetFileName(filePath));


问:
Hive join tables on string field match
Hi I am trying to Left outer join on table onto another, the matching colums are type String.

Will Hive join on matching string columns or do they need to be converted to a different datatype?

My join ON Clause looks like
Select table1.para1, table2.para2
From table a
left outer Join Table b
On (table1.a=table2.b). A and B are strings, will this work?

答:
Join on string will work. Just keep in mind that string matching will be case-sensitive.

Consider using functions like UPPER or LOWER.

For example,

```<code>select * from temp join new_temp on LOWER(temp.dept) = LOWER(new_temp.dept);
</code>```

Title: Hive join tables on string field match

Body:
Join on string will work. Just keep in mind that string matching will be case-sensitive.

Consider using functions like UPPER or LOWER.

For example,

select * from temp join new_temp on LOWER(temp.dept) = LOWER(new_temp.dept);


问:
CLI free memory for composer
Is there a shell command to find out how much memory composer can use at the cli SAPI? Not the CGI one which can be found by performing a phpinfo();

I would like to know the memory limit my hoster has.

答:
On the command line:

```<code>php -i | grep memory_limit
</code>```

Read about memory limit errors here.

Title: CLI free memory for composer

Body:
On the command line:

php -i | grep memory_limit

Read about memory limit errors here.


问:
Attaching tr inside a table reusable component
i have a table component

Table Component

```<code>       <table>
         <thead>
            <tr>
              <th>{this.props.th1}</th>
              <th>{this.props.th2}</th>
              <th>{this.props.th3}</th>
            </tr>
          </thead>
      </table>
</code>```

Inside the App.js i am calling the Table Component ,

```<code>               <Table th1="one"  th2="two" th3="three">
                  <tbody>
                      <tr>
                        <td>sample 1</td>
                        <td>sample 2</td>
                        <td>sample 3</td>
                      </tr>
                   </tbody>
                </Table>
</code>```

But i am not able to see the tbody inside the Table, how can i do this one.

Many thanks in advance

答:
You forgot this.props.children . Indeed, you are injecting
as a child of
:

```<code>  <table>
     <thead>
        <tr>
          <th>{this.props.th1}</th>
          <th>{this.props.th2}</th>
          <th>{this.props.th3}</th>
        </tr>
      </thead>
      {this.props.children}
  </table>
</code>```

Body:
i have a table component

Table Component

              {this.props.th1}
              {this.props.th2}
              {this.props.th3}

Inside the App.js i am calling the Table Component ,

                        sample 1
                        sample 2
                        sample 3

But i am not able to see the tbody inside the Table, how can i do this one.

Many thanks in advance

Body:
You forgot this.props.children . Indeed, you are injecting <tbody />as a child of <Table />:

  <table>
     <thead>
        <tr>
          <th>{this.props.th1}</th>
          <th>{this.props.th2}</th>
          <th>{this.props.th3}</th>
        </tr>
      </thead>
      {this.props.children}
  </table>


问:
I'm currently working on a project using the angular 2 . I am getting Access-Control-Allow-Origin issue
when i am hitting third party services from my java script code I am getting below error in the browser :

Failed to load http://api.mysite.com: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://client.mysite.com' is therefore not allowed access.

Please suggest me how to fix this issue.

答: First of all , check your service API has CORS enabled/not. If not enable and check.</p>


问:
Find all elements that start with 'button-'
I am using Selenium to try and get all ID elements that that start with "button-". What I have tried so far was to use regex to match the "button-" but I get an error stating that TypeError: Object of type 'SRE_Pattern' is not JSON serializable. My code so far is:

```<code>all_btns = self.driver.find_elements_by_id(re.compile('^button-?'))
</code>```

But as mentioned that raises an error. What is the appropriate way of getting all elements when you don't know the full ID, class, css selector etc.?

答:
Clément's answers works just fine, but there is also a way to do this with css selectors:

```<code>*[id^='button'].
</code>```

* matches all tags, just like in xpath and ^= means 'starts with'

Body:
I am using Selenium to try and get all ID elements that that start with "button-". What I have tried so far was to use regex to match the "button-" but I get an error stating that TypeError: Object of type 'SRE_Pattern' is not JSON serializable. My code so far is:

all_btns = self.driver.find_elements_by_id(re.compile('^button-?'))

But as mentioned that raises an error. What is the appropriate way of getting all elements when you don't know the full ID, class, css selector etc.?

Body:
Clément's answers works just fine, but there is also a way to do this with css selectors:

*[id^='button'].

* matches all tags, just like in xpath and ^= means 'starts with'


问:
filter results in an array of objects just like operator(%oil%) using lodash
I want to filter array of objects based on the input change by the user and create a new array of matched array of objects using LODASH (https://lodash.com/).

```<code>let listing = [{title: "Courier/Logistics", id: 1, totalWorkers: 1058, openPositions: 0, omani: 99.72},
{title: "Information Technology", id: 1, totalWorkers: 2, openPositions: 1, omani: 50},
{title: "Oil & Gas", id: 1, totalWorkers: 98, openPositions: 6, omani: 91.84}];
</code>```

I have tried lodash _.filter but this filters exact words and exact case and then return that single searched value.

```<code>const filtered = _.filter(listing, function(o) {
        return o.title === "oi";
      });
      console.log(filtered);
</code>```

I want to get results just like we do in mysql as:

```<code>WHERE title like %oi%
</code>```

and it gives matched values which contained that input.

Thanks

答:
In your filter function, use the includes function
ie</p>

```<code>return o.title.includes("oi");
</code>```

Body:
I want to filter array of objects based on the input change by the user and create a new array of matched array of objects using LODASH (https://lodash.com/).

let listing = [{title: "Courier/Logistics", id: 1, totalWorkers: 1058, openPositions: 0, omani: 99.72},
{title: "Information Technology", id: 1, totalWorkers: 2, openPositions: 1, omani: 50},
{title: "Oil & Gas", id: 1, totalWorkers: 98, openPositions: 6, omani: 91.84}];

I have tried lodash _.filter but this filters exact words and exact case and then return that single searched value.

const filtered = _.filter(listing, function(o) {
        return o.title === "oi";
      });
      console.log(filtered);

I want to get results just like we do in mysql as:

WHERE title like %oi%

and it gives matched values which contained that input.

Thanks

Body:
In your filter function, use the includes function
ie

return o.title.includes("oi");


问:
How to get value of input field in typescript file Angular 4
```<code> <div id="lists">
            <table id='mytable' cellspacing='0' cellpadding='0'>
                <tr  class="row" [ngClass]="{'selected': i === selectedIndex}"  *ngFor= 'let item of list; let i = index' [attr.data-index]='i'  [ngStyle]="{'background-color': i%2 == '0' ? 'gray' : ''}">
                    <td class='default-field'>
                        <p class='para' *ngIf="selectedIndex!=i  ">{{i+1}}. {{item}}</p>
                    </td>
                    <td class="edit-field" *ngIf="selectedIndex==i   " >
                        <input type="text" class="myCl" [value]="val" >
                    </td>
                    <td class='btns'>

                    <input type='button' value='edit' class='edit-btn'  (click)='hidePara(item,i)' *ngIf="selectedIndex!=i">

                    <input type='button' value='save' class='save-btn' *ngIf="selectedIndex==i" (click)='hidePara1(item,i)'>
                    <input type='button' value='DELETE' class='delete-btn' (click)='deleterow(i)'>
                    </td>
                </tr>
            </table>

        </div>
</code>```

Above is my html code, i want to retrieve the value of input field when user click on save button, the hidePara1(item,i) function will execute, i want to get value of input field in hidepara1, how this can be possible.

```<code> hidePara1(item,ii)
 {
  this.selectedIndex=-1;
  this.showHideP = !this.showHideP;  //for hiding paragraph
  this.tbox = !this.tbox;  //showing text box
  this.edt=!this.edt;  //hide edt button
  this.sbtn = !this.sbtn;  //display save button

 }
</code>```

答:
First of all you need to import FormsModule in app.modules.ts in order to use ngModel

```<code>import { FormsModule } from '@angular/forms';
</code>```

Then you can use [(ngModel)] to get the value in .ts file

HTML :

```<code><input type="text" [(ngModel)]="inputText">
</code>```

TS :

```<code>inputText :string = "I am sample text";
</code>```

Your code becomes :

```<code> <div id="lists">
            <table id='mytable' cellspacing='0' cellpadding='0'>
                <tr  class="row" [ngClass]="{'selected': i === selectedIndex}"  *ngFor= 'let item of list; let i = index' [attr.data-index]='i'  [ngStyle]="{'background-color': i%2 == '0' ? 'gray' : ''}">
                    <td class='default-field'>
                        <p class='para' *ngIf="selectedIndex!=i  ">{{i+1}}. {{item}}</p>
                    </td>
                    <td class="edit-field" *ngIf="selectedIndex==i   " >
                        <input type="text" class="myCl" [value]="val" [(ngModel)]="item.inputText">
                    </td>
                    <td class='btns'>

                    <input type='button' value='edit' class='edit-btn'  (click)='hidePara(item,i)' *ngIf="selectedIndex!=i">

                    <input type='button' value='save' class='save-btn' *ngIf="selectedIndex==i" (click)='hidePara1(item,i)'>
                    <input type='button' value='DELETE' class='delete-btn' (click)='deleterow(i)'>
                    </td>
                </tr>
            </table>

        </div>
</code>```

Body:
{{i+1}}. {{item}}

                        <input type="text" class="myCl" [value]="val" >

                    <input type='button' value='edit' class='edit-btn'  (click)='hidePara(item,i)' *ngIf="selectedIndex!=i">

                    <input type='button' value='save' class='save-btn' *ngIf="selectedIndex==i" (click)='hidePara1(item,i)'>
                    <input type='button' value='DELETE' class='delete-btn' (click)='deleterow(i)'>

Above is my html code, i want to retrieve the value of input field when user click on save button, the hidePara1(item,i) function will execute, i want to get value of input field in hidepara1, how this can be possible.

 hidePara1(item,ii)
 {
  this.selectedIndex=-1;
  this.showHideP = !this.showHideP;  //for hiding paragraph
  this.tbox = !this.tbox;  //showing text box
  this.edt=!this.edt;  //hide edt button
  this.sbtn = !this.sbtn;  //display save button

 }

Body:
First of all you need to import FormsModule in app.modules.ts in order to use ngModel

import { FormsModule } from '@angular/forms';

Then you can use [(ngModel)] to get the value in .ts file

HTML :

<input type="text" [(ngModel)]="inputText">

TS :

inputText :string = "I am sample text";

Your code becomes :

 <div id="lists">
            <table id='mytable' cellspacing='0' cellpadding='0'>
                <tr  class="row" [ngClass]="{'selected': i === selectedIndex}"  *ngFor= 'let item of list; let i = index' [attr.data-index]='i'  [ngStyle]="{'background-color': i%2 == '0' ? 'gray' : ''}">
                    <td class='default-field'>
                        <p class='para' *ngIf="selectedIndex!=i  ">{{i+1}}. {{item}}</p>
                    </td>
                    <td class="edit-field" *ngIf="selectedIndex==i   " >
                        <input type="text" class="myCl" [value]="val" [(ngModel)]="item.inputText">
                    </td>
                    <td class='btns'>

                    <input type='button' value='edit' class='edit-btn'  (click)='hidePara(item,i)' *ngIf="selectedIndex!=i">

                    <input type='button' value='save' class='save-btn' *ngIf="selectedIndex==i" (click)='hidePara1(item,i)'>
                    <input type='button' value='DELETE' class='delete-btn' (click)='deleterow(i)'>
                    </td>
                </tr>
            </table>

        </div>


答:
For CPT it's very truth.

You can do it with simple code, no plugins needed.

For ui use generator before add to theme functions, like this site:
https://generatewp.com/post-type/

For custom fields ACF is useful to UI elements, so just if it's a special value use ACF. Then just add metabox to cpt.

Title: Wordpress - CPT and ACF Plugins

Body:
I'm about starting developing my own theme by using CPT and ACF Plugins. I read some articles and reviews about CPT as well as ACF and most of the developers they love them because they are very easy to use and helpful. However some of them they gave very bad feedback in terms of security, stability and slowing down the performance of the website; even they said these plugins for non-technical developers which developing for cheap clients.

What do you think about this? because I like CPT and ACF very much once I tried doing things with them. However I don't want to put my self in a risk by using these plugins.

Also do you suggest another professional way to create Custom Post Type and Custom Fields? or do you prefer CPT and ACF anyway for even the advanced developer?

Thanks.


问:
Filter in sliced ng-repeat
I try make table with pagination and filter using angular. I found nice pagination example (of course I didn't "ctrl+c, ctrl+v), but I have one problem. I use ng-repeat with slice but if I would make | filter this doesn't work properly, because filtered items didn't change pages. For example  if item is on second page and I filter and is only one stiil stay on second page against go to first. Look on code and please help me make working filter

http://embed.plnkr.co/eheFSh/

答:
At this case you should apply filter at first and only then pagination, i.e. slice:

```<code>name: <input type='text' ng-model='searchName'/>
id: <input type='text' ng-model='searchId'/>

<tr ng-repeat="row in (data | filter : {name:searchName, id: searchId }).slice(((currentPage-1)*itemsPerPage), ((currentPage)*itemsPerPage))">
     <td>{{row.name}}</td>
     <td>{{row.id}}</td>
</tr>
</code>```

Title: Filter in sliced ng-repeat

Body:
At this case you should apply filter at first and only then pagination, i.e. slice:

name: <input type='text' ng-model='searchName'/>
id: <input type='text' ng-model='searchId'/>

<tr ng-repeat="row in (data | filter : {name:searchName, id: searchId }).slice(((currentPage-1)*itemsPerPage), ((currentPage)*itemsPerPage))">
     <td>{{row.name}}</td>
     <td>{{row.id}}</td>
</tr>


问:
how to run mutliple thread groups with different database users in JMeter
I've set of sql-files they need to execute in parallel and I've achieved it by ThreadGroups.

I've created 2 thread groups. Each TG will start each sql-file, But, they are running with same database-user.

I need to run the TG1 with user1 and TG2 with user2. Can we achieve it throw single jmx ?

答:
You can use 2 (or more) JDBC Connection Configuration which will be similar except the user and password

When you write your JDBC Request give the relevant Variable Name from the Configuration.

Variable Name

  Name of the JMeter variable that the connection pool is bound to. This must agree with the 'Variable Name' field of a JDBC Connection Configuration.


问:
Undefined properties in Angular expression binding
I have a binding {{getCategoryName(post.categories[0])['name']}} where I need to process the value post.categories[0] returned in the *ngFor loop with a method getCategoryByName() in my component before finally binding it to the template.The method returns an  Object.

I keep getting the error Cannot read property 'name' of undefined . I have tried getting the property using the ['name'] key instead of .name but still get the error.

Any thoughts for a workaround?

```<code>  <ion-item text-wrap class="news-item" *ngFor="let post of posts" (click)="viewStory(post)">
          <div >
          <p>{{getCategoryName(post.categories[0])['name']}}</p>
          <h2>{{post.title.rendered}}</h2>
          <p>By Fitz · {{post.date | fromNow}}</p>
        </div>
    </ion-item>
</code>```

The method

```<code>  getCategoryName(categoryId) {
    return this.categories[this.categories.findIndex((el)=>{ return el.id == categoryId})];
  }
</code>```

Example ember of the Array from which the Object is returned by method above

```<code>[
  {
    "id": 33,
    "count": 1,
    "description": "",
    "link": "http://XXXXXXXXXXXXX.co/category/apps/",
    "name": "Apps",
    "slug": "apps",
    "taxonomy": "category",
    "parent": 0,
    "meta": [],
    "_links": {
      "self": [
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/categories/33"
        }
      ],
      "collection": [
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/categories"
        }
      ],
      "about": [
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/taxonomies/category"
        }
      ],
      "wp:post_type": [
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/posts?categories=33"
        },
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/jobs?categories=33"
        }
      ],
      "curies": [
        {
          "name": "wp",
          "href": "https://api.w.org/{rel}",
          "templated": true
        }
      ]
    }
  },

]
</code>```

答:
You could simply do like this

{{getCategoryName(post.categories[0])?.name}}```

? is the safe navigation operator. It checks whether the variable is null or undefined so that our template won't try to select a property of something falsy.

More info: https://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths

Body:
I have a binding {{getCategoryName(post.categories[0])['name']}} where I need to process the value post.categories[0] returned in the *ngFor loop with a method getCategoryByName() in my component before finally binding it to the template.The method returns an  Object.

I keep getting the error Cannot read property 'name' of undefined . I have tried getting the property using the ['name'] key instead of .name but still get the error.

Any thoughts for a workaround?

  <ion-item text-wrap class="news-item" *ngFor="let post of posts" (click)="viewStory(post)">

{{getCategoryName(post.categories[0])['name']}}

{{post.title.rendered}}

By Fitz · {{post.date | fromNow}}

    </ion-item>

The method

  getCategoryName(categoryId) {
    return this.categories[this.categories.findIndex((el)=>{ return el.id == categoryId})];
  }

Example ember of the Array from which the Object is returned by method above

[
  {
    "id": 33,
    "count": 1,
    "description": "",
    "link": "http://XXXXXXXXXXXXX.co/category/apps/",
    "name": "Apps",
    "slug": "apps",
    "taxonomy": "category",
    "parent": 0,
    "meta": [],
    "_links": {
      "self": [
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/categories/33"
        }
      ],
      "collection": [
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/categories"
        }
      ],
      "about": [
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/taxonomies/category"
        }
      ],
      "wp:post_type": [
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/posts?categories=33"
        },
        {
          "href": "http://XXXXXXXXXXXXX.co/wp-json/wp/v2/jobs?categories=33"
        }
      ],
      "curies": [
        {
          "name": "wp",
          "href": "https://api.w.org/{rel}",
          "templated": true
        }
      ]
    }
  },

]

Body:
You could simply do like this

{{getCategoryName(post.categories[0])?.name}}

? is the safe navigation operator. It checks whether the variable is null or undefined so that our template won't try to select a property of something falsy.

More info: https://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths


问:
Is it better to use the column name or column index on .Net DataSets?
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

```<code>int price = (int)dr["Price"];
</code>```

While column index is just faster (I think):

```<code>int price = (int)dr[3];
</code>```

Would using column names break if you decide to obfuscate the database?

答: I generally prefer readability and understanding over speed.  Go with the name.  You could (should) use string constants that can be updated in one place if you decide to change database column names.</p>

OwnerDisplayName: tpower

ContentLicense: CC BY-SA 2.5

Body:
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

int price = (int)dr["Price"];

While column index is just faster (I think):

int price = (int)dr[3];

Would using column names break if you decide to obfuscate the database?

LastEditorDisplayName: tpower

OwnerDisplayName: tvanfosson


问:
chardet apparently wrong on Big5
I'm decoding a large (about a gigabyte) flat file database, which mixes character encodings willy nilly.  The python module chardet is doing a good job, so far, of identifying the encodings, but if hit a stumbling block...

```<code>In [428]: badish[-3]
Out[428]: '\t\t\t"Kuzey r\xfczgari" (2007) {(#1.2)}  [Kaz\xc4\xb1m]\n'

In [429]: chardet.detect(badish[-3])
Out[429]: {'confidence': 0.98999999999999999, 'encoding': 'Big5'}

In [430]: unicode(badish[-3], 'Big5')
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)

~/src/imdb/<ipython console> in <module>()

UnicodeDecodeError: 'big5' codec can't decode bytes in position 11-12: illegal multibyte sequence
</code>```

chardet reports a very high confidence in it's choice of encodings, but it doesn't decode...  Are there any other sensible approaches?

答:
A point that can't be stressed too strongly: You should not expect any reasonable encoding guess from a piece of text that is so short and has such a high percentage of plain old ASCII characters in it.

About big5: chardet casts a very wide net when checking CJK encodings. There are lots of unused slots in big5, and chardet doesn't exclude them. That string is not valid big5, as you have found out. It is in fact valid (but meaningless) big5_hkscs (which used a lot of the holes in big5).

There are an enormous number of single-byte encodings that fit the string.

At this stage it's necessary to seek out-of-band help. Googling "Kuzey etc" drags up a Turkish TV series "Kuzey rüzgari" so we now have the language.

That means that if it was entered by a person familar with Turkish, it could be in cp1254, or iso_8859_3 (or _9), or mac_turkish. All of those produce gibberish for the [Kaz??m] word near the end. According to the imdb website, that's the name of a character, and it's the same gibberish as obtained by decoding with cp1254 and iso-8859-9 (KazÄ±m). Decoding with your suggested iso-8859-2 gives KazÄąm which doesn't look very plausible either.

Can you generalise this? I don't think so :-)

I would strongly suggest that in such a case that you decode it using latin1 (so that no bytes are mangled) and flag the record as having unknown encoding. You should use a minimum length cutoff as well.

Update For what it's worth, the_two_bytes_in_the_character_name.decode('utf8') produces U+0131 LATIN SMALL LETTER DOTLESS I which is used in Turkish and Azerbaijani. Further googling indicates that Kazım is a common-enough Turkish given name.

Title: chardet apparently wrong on Big5

Body:
I'm decoding a large (about a gigabyte) flat file database, which mixes character encodings willy nilly.  The python module chardet is doing a good job, so far, of identifying the encodings, but if hit a stumbling block...

In [428]: badish[-3]
Out[428]: '\t\t\t"Kuzey r\xfczgari" (2007) {(#1.2)}  [Kaz\xc4\xb1m]\n'

In [429]: chardet.detect(badish[-3])
Out[429]: {'confidence': 0.98999999999999999, 'encoding': 'Big5'}

In [430]: unicode(badish[-3], 'Big5')
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)

~/src/imdb/<ipython console> in <module>()

UnicodeDecodeError: 'big5' codec can't decode bytes in position 11-12: illegal multibyte sequence

chardet reports a very high confidence in it's choice of encodings, but it doesn't decode...  Are there any other sensible approaches?


答:
value is the property of this component by using Input field.use [(ngmodel)]

<input type="text" class="myCl" [(ngmodel)]="value[i]" >

get value from input field and store the value of array by ng model method then click the save button pass array valy and parameter to save

<input type='button' value='save' class='save-btn' *ngIf="selectedIndex==i" (click)='hidePara1(value,item,i)'>

Title: How to get value of input field in typescript file Angular 4


答:
Because '' is the first matched result of r'i*' and 'iii' is the second matched result.

In [1]: import re

In [2]: re.findall(r'i*', 'piiig!!')
Out[2]: ['', 'iii', '', '', '', '']
```

This website will also explain the way how regular expression work.
https://regex101.com/r/XVPXMv/1

Title: Understanding * (zero or more) operator using re.search()

Body:
I am new to python and was going through "Google for Education" python course

Now, the line below confuses me:

* -- 0 or more occurrences of the pattern to its left

(all the examples are in python3)

e.g. 1

In [1]: re.search(r"pi*", "piiig!!").group()
Out[1]: 'piii'

This is fine since, "pi" has 1 occurrance so it is retured

e.g. 2

In [2]: re.search(r"i*", "piiig!!").group()
Out[2]: ''

Why does it not return "i" in fact - from my understanding, it should be returning "iii". But the result is an empty string.

Also, What exactly does "0 or more" mean? I searched on google but everywhere it is mentioned * -- 0 or more. But if there is 0 occurrence of an expression, does that not become true even if it's not there? What is the point of searching then?

I am so confused with this. Can you please help me with explaining this or point me in the right direction.

i hope the right explanation would also resolve my this issue:

In [3]: re.search(r"i?", "piiig!!").group()
Out[3]: ''

I have tried the examples in Spyder 3.2.4

Body:
Because '' is the first matched result of r'i*' and 'iii' is the second matched result.

In [1]: import re

In [2]: re.findall(r'i*', 'piiig!!')
Out[2]: ['', 'iii', '', '', '', '']

This website will also explain the way how regular expression work.
https://regex101.com/r/XVPXMv/1


答:
tbody is passed to the Table component as children props and hence you need to change your Table component to render the children as well.

Why is tbody passed as children prop to Table?

In JSX expressions that contain both an opening tag and a closing tag,
  the content between those tags is passed as a special prop:
  props.children.

You will have to do

```<code><table>
     <thead>
        <tr>
          <th>{this.props.th1}</th>
          <th>{this.props.th2}</th>
          <th>{this.props.th3}</th>
        </tr>
      </thead>
      {this.props.children}
  </table>
</code>```

Title: Attaching tr inside a table reusable component

Body:
tbody is passed to the Table component as children props and hence you need to change your Table component to render the children as well.

Why is tbody passed as children prop to Table?

In JSX expressions that contain both an opening tag and a closing tag,
  the content between those tags is passed as a special prop:
  props.children.

You will have to do

<table>
     <thead>
        <tr>
          <th>{this.props.th1}</th>
          <th>{this.props.th2}</th>
          <th>{this.props.th3}</th>
        </tr>
      </thead>
      {this.props.children}
  </table>


问:
Resize functionality does not work properly
I need to hide my main navigation menu if the browser is less than 768px.
Function triggers on resize. But the navigation menu hides at 784px instead.
    Here's the code: </p>

```<code>jQuery(window).resize(function(){
    var windowSize = jQuery( window ).width();
    if(jQuery("#main-navigation").css('display') == 'none' && windowSize > 768) {
        jQuery("nav#main-navigation").css("display", "block");
    }
    if(windowSize < 768) {
        jQuery("nav#main-navigation").css("display", "none");
    }

});
</code>```

答: It's because you have scrollbar. $(window).widht() returns you widht without scrollbar. If you want to have width with scroll width, you can use window.innerWidth

Body:
I need to hide my main navigation menu if the browser is less than 768px.
Function triggers on resize. But the navigation menu hides at 784px instead.
    Here's the code:

jQuery(window).resize(function(){
    var windowSize = jQuery( window ).width();
    if(jQuery("#main-navigation").css('display') == 'none' && windowSize > 768) {
        jQuery("nav#main-navigation").css("display", "block");
    }
    if(windowSize < 768) {
        jQuery("nav#main-navigation").css("display", "none");
    }

});


问:
Haskell: Using List Comprehension and reducing x by 1 each list to make x amount of lists
I'm new to using Haskell I've been spending hours trying to build a simple function where entering a function will turn out like this:

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

No amount of research can really help me figure out how I should iterate my functions 'x' so that I have multiple lists building based on the number I choose, I'm close but that's where I'm stumped, my current code is essentially set up where I can do this if I were to enter makeList 3:

```<code>makeList 3 = [ [ x | x <- xs ] | xs <- [[1..x-2],[1..x-1],[1..x]] ]
</code>```

prints out:

```<code>[[1],[1,2],[1,2,3]]
</code>```

Body:
I'm new to using Haskell I've been spending hours trying to build a simple function where entering a function will turn out like this:

makeList 5 == [[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5]]
makeList 2 == [[1],[1,2]]

No amount of research can really help me figure out how I should iterate my functions 'x' so that I have multiple lists building based on the number I choose, I'm close but that's where I'm stumped, my current code is essentially set up where I can do this if I were to enter makeList 3:

makeList 3 = [ [ x | x <- xs ] | xs <- [[1..x-2],[1..x-1],[1..x]] ]

prints out:

[[1],[1,2],[1,2,3]]

Body:
Prelude> makeList n = [ [1..x] | x <- [1..n] ]
Prelude> makeList 5
[[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5]]


问:
is it possible to change the bottom border of entry in Xamarin.Forms (Portable)
I want to change the border colour of Editor and Entry in the simplest way, I don't want to create any custom renderer.

Is it possible using Style.xml?

Thank You.

答: Create xml files with different stroke color in android project, from XAML send background color value through trigger and you find those values in OnElementPropertyChanged in your android renderer then switch the xml how you want.</p>


问:
which api's are available to find movie shows information?
I want to find shows of movie,show booking,price of shows, I am searching for api for that can any one tell me which api's are there for that.</p>

答: Have you had a look at the UIWebView?</p>

Body: Have you had a look at the UIWebView?


问:
oracle ref() ora-00904 invalid column name
apparently there are many ora-00904 errors out there, but I can't find similar case with mine.

my case is related to ref() function in oracle: https://docs.oracle.com/cloud/latest/db112/SQLRF/functions145.htm#SQLRF00694

according to the example in the link above, you can query like below without problem:

```<code>select ref(x) from some_table x
</code>```

but what I get is error ora-00904 invalid column name and it highlighted the x in ref(x)

I can't remove the ref() function from my query as it is added automatically by oracle forms.

Anyone have similar experience? is there some settings to set?

BTW, I am using an ancient oracle form 6i on top of oracle 8i

答: The ref() function is used in conjunction with user defined types; hence the table alias used by the function needs to refer to a table of a user defined type.</p>

Body:
apparently there are many ora-00904 errors out there, but I can't find similar case with mine.

my case is related to ref() function in oracle: https://docs.oracle.com/cloud/latest/db112/SQLRF/functions145.htm#SQLRF00694

according to the example in the link above, you can query like below without problem:

select ref(x) from some_table x

but what I get is error ora-00904 invalid column name and it highlighted the x in ref(x)

I can't remove the ref() function from my query as it is added automatically by oracle forms.

Anyone have similar experience? is there some settings to set?

BTW, I am using an ancient oracle form 6i on top of oracle 8i


问:
Is it safe to use Glide Caching instead of Internal Storage
I have a scenario where i have to keep few images in offline mode. Now i am confused here that should i rely on Glide's cache or I have to put those images in Internal Storage?

Hopefully Glide will work, but need to know if there exists any limitation if i go with Glide. Here word cache is causing confusion.

答:
Here is the information about underlying memory usage by Glide.

Glide uses DiskLruCacheWrapper as the default DiskCache. DiskLruCacheWrapper is a fixed size disk cache with LRU eviction. The default disk cache size is 250 MB and is placed in a specific directory in the Application’s cache folder.

Further underlying complexities of Glide are here. Hope confusion about the max memory Glide uses is cleared here and if customization is needed, that can also be achieved by following the link mentioned.


问:
Powershell break a long array into a array of array with length of N and repeat first element in sub arrays
This answer here: Powershell break a long array into a array of array with length of N in one line?

almost perfectly answers my requirements. What I would like to do is group my elements so that the first group has one extra element in it and all others have the first element repeated in each group.

Like this:

```<code>$bigList = ("Name","One","Two","Three","Four","Five","six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen")

$counter = [pscustomobject] @{ Value = 0 }
$groupSize = 5

$groups = $bigList | Group-Object -Property { [math]::Floor($counter.Value++ / $groupSize) }
</code>```

With my groups ending up looking like this ...

```<code>Name, One, Two, Three, Four, Five
Name, Six, Seven, Eight, Nine, Ten
Name, Eleven, Twelve, Thirteen
</code>```

答:
How's this:

```<code>$bigList = ("Name","One","Two","Three","Four","Five","six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen")

$counter = [pscustomobject] @{ Value = 0 }
$groupSize = 5

$bigList[1..$biglist.count] |
    Group-Object -Property { [math]::Floor($counter.Value++ / $groupSize) } |
    foreach-object {
        $_.Group.Insert(0,$biglist[0])
        write-output $_
    }
</code>```

Output:

```<code>Count Name                      Group
----- ----                      -----
    5 0                         {Name, One, Two, Three...}
    5 1                         {Name, six, Seven, Eight...}
    3 2                         {Name, Eleven, Twelve, Thirteen}
</code>```

This works by stripping out the first element ("Name") and sending the rest of the array through the group-object cmdlet. The resulting objects are modified in the foreach-object scriptblock by inserting the value from the first element of the big list into the group property. The modified object is re-written to the pipeline.

Assuming you want these in an list of arrays, you'd need to modify the code slightly:

```<code>$arrayList = $bigList[1..$biglist.count] |
    Group-Object -Property { [math]::Floor($counter.Value++ / $groupSize) } |
    ForEach-Object {
        $_.Group.Insert(0,$biglist[0])
        ,$_.group
    }

$arraylist |
    % {
        write-host ( $_ -join "," )
    }
</code>```

Here, we deliberately output only the group property of the groupinfo object that comes from group-object. In addition, we use the , operator to force powershell to output an individual array. If this is not done, we end up with a single array that is just like $biglist, but with extra instances of 'Name' every 5 elements. The final chunk of code outputs the contents of each element of $arrayList, concatenating with commas to demonstrate that we do indeed have an array of arrays:

```<code>Name,One,Two,Three,Four,Five
Name,six,Seven,Eight,Nine,Ten
Name,Eleven,Twelve,Thirteen
</code>```

Body:
This answer here: Powershell break a long array into a array of array with length of N in one line?

almost perfectly answers my requirements. What I would like to do is group my elements so that the first group has one extra element in it and all others have the first element repeated in each group.

Like this:

$bigList = ("Name","One","Two","Three","Four","Five","six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen")

$counter = [pscustomobject] @{ Value = 0 }
$groupSize = 5

$groups = $bigList | Group-Object -Property { [math]::Floor($counter.Value++ / $groupSize) }

With my groups ending up looking like this ...

Name, One, Two, Three, Four, Five
Name, Six, Seven, Eight, Nine, Ten
Name, Eleven, Twelve, Thirteen

Body:
How's this:

$bigList = ("Name","One","Two","Three","Four","Five","six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen")

$counter = [pscustomobject] @{ Value = 0 }
$groupSize = 5

$bigList[1..$biglist.count] |
    Group-Object -Property { [math]::Floor($counter.Value++ / $groupSize) } |
    foreach-object {
        $_.Group.Insert(0,$biglist[0])
        write-output $_
    }

Output:

Count Name                      Group
----- ----                      -----
    5 0                         {Name, One, Two, Three...}
    5 1                         {Name, six, Seven, Eight...}
    3 2                         {Name, Eleven, Twelve, Thirteen}

This works by stripping out the first element ("Name") and sending the rest of the array through the group-object cmdlet. The resulting objects are modified in the foreach-object scriptblock by inserting the value from the first element of the big list into the group property. The modified object is re-written to the pipeline.

Assuming you want these in an list of arrays, you'd need to modify the code slightly:

$arrayList = $bigList[1..$biglist.count] |
    Group-Object -Property { [math]::Floor($counter.Value++ / $groupSize) } |
    ForEach-Object {
        $_.Group.Insert(0,$biglist[0])
        ,$_.group
    }

$arraylist |
    % {
        write-host ( $_ -join "," )
    }

Here, we deliberately output only the group property of the groupinfo object that comes from group-object. In addition, we use the , operator to force powershell to output an individual array. If this is not done, we end up with a single array that is just like $biglist, but with extra instances of 'Name' every 5 elements. The final chunk of code outputs the contents of each element of $arrayList, concatenating with commas to demonstrate that we do indeed have an array of arrays:

Name,One,Two,Three,Four,Five
Name,six,Seven,Eight,Nine,Ten
Name,Eleven,Twelve,Thirteen


问:
Issue in copying rows based on certain conditions in Vba
```<code>Set ws4 = Workbooks("A.xlsx").Worksheets(1)
Lastrowto = ws4.Cells(Rows.Count, "B").End(xlUp).Row

For y = Lastrowto To 1 Step -1
    If ws4.Cells(y, "B").Value = "Not found" Then
        ws4.Rows(y).EntireRow.Copy
    End If
Next y
</code>```

The above piece of vba code copies only 1 (the first one) row but I want to copy all those rows for which the given condition is met, kindly suggest me the correct version of code.

答:
Where do you want to copy it to? if you specify a destination to your copy, then your code could work.

e.g. if you have a destination sheet defined as wsDest, you can replace

```<code>ws4.Rows(y).EntireRow.Copy
</code>```

by

```<code>ws4.Rows(y).EntireRow.Copy wsDest.cells(rows.count,1).end(xlup).offset(1)
</code>```

assuming you always have a value in column 1.

Another option is to do an autofilter on column B, with the value not found, and use the specialcells property to copy to another spot. Recording a macro will help you quite a bit, but code will be something like:

```<code>with ws4.cells(1,1).currentregion
    .autofilter field:=2,criteria1:="Not found"
    .specialcells(xlcelltypevisible).copy
end with
</code>```

Body:
Set ws4 = Workbooks("A.xlsx").Worksheets(1)
Lastrowto = ws4.Cells(Rows.Count, "B").End(xlUp).Row

For y = Lastrowto To 1 Step -1
    If ws4.Cells(y, "B").Value = "Not found" Then
        ws4.Rows(y).EntireRow.Copy
    End If
Next y

The above piece of vba code copies only 1 (the first one) row but I want to copy all those rows for which the given condition is met, kindly suggest me the correct version of code.

Body:
Where do you want to copy it to? if you specify a destination to your copy, then your code could work.

e.g. if you have a destination sheet defined as wsDest, you can replace

ws4.Rows(y).EntireRow.Copy

by

ws4.Rows(y).EntireRow.Copy wsDest.cells(rows.count,1).end(xlup).offset(1)

assuming you always have a value in column 1.

Another option is to do an autofilter on column B, with the value not found, and use the specialcells property to copy to another spot. Recording a macro will help you quite a bit, but code will be something like:

with ws4.cells(1,1).currentregion
    .autofilter field:=2,criteria1:="Not found"
    .specialcells(xlcelltypevisible).copy
end with


问:
Maintain 16:9 aspect ratio according to width and height
So I have this video that I want to be, not quite fullscreen, but close. I want it to maintain its 16:9 aspect ratio but I want there to always be padding or space between the video and the edge of the screen. So what I have right now, https://jsfiddle.net/99yen3v3/, is:

```<code>width: 80vw;
height: 45vw;
</code>```

for the div. It works fine when I shrink the web browser horizontally, the video div maintains its 16:9 aspect ratio. The only problem is, whenever I shrink the web browser vertically, the video slowly goes off the screen. I want that same padding to be there when I shrink the web browser vertically, if that makes any sense.

If you have any questions, or are confused, just ask. I would appreciate any help, thanks.

EDIT1: And I have checked out this post already, the only difference is they use a 1:1 ratio in that example, whereas mine is more difficult, being 16:9.

EDIT2: No my question is not a duplicate of this one. I clearly stated that I want the div to be contained also by the height of the browser window, not just width.

答:
What you want is the CSS object-fit property, with contain for the value.

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

Since you're using <video> this is actually the default.  Simply set the video size to 100% width/height, and padding on the parent.

Body:
So I have this video that I want to be, not quite fullscreen, but close. I want it to maintain its 16:9 aspect ratio but I want there to always be padding or space between the video and the edge of the screen. So what I have right now, https://jsfiddle.net/99yen3v3/, is:

width: 80vw;
height: 45vw;

for the div. It works fine when I shrink the web browser horizontally, the video div maintains its 16:9 aspect ratio. The only problem is, whenever I shrink the web browser vertically, the video slowly goes off the screen. I want that same padding to be there when I shrink the web browser vertically, if that makes any sense.

If you have any questions, or are confused, just ask. I would appreciate any help, thanks.

EDIT1: And I have checked out this post already, the only difference is they use a 1:1 ratio in that example, whereas mine is more difficult, being 16:9.

EDIT2: No my question is not a duplicate of this one. I clearly stated that I want the div to be contained also by the height of the browser window, not just width.


问:
Is it possible to generate Typescript interfaces from files with a webpack loader?
I am attempting to create a webpack loader that converts a file containing a description of API data structures into a set of TypeScript interfaces.

In my concrete case, the file is JSON, but this should be ultimately irrelevant — the file is only a shared source of data describing the interaction between web application backend(s) and frontend(s). In my MCVE below, you can see that the JSON file contains an empty object to underscore how the type and contents of the file do not matter to the problem.

My current attempt reports two errors (I assume the second is caused by the first):

[at-loader]: Child process failed to process the request:  Error: Could not find file: '/private/tmp/ts-loader/example.api'.
```

<pre class="lang-none prettyprint-override"><code>ERROR in ./example.api
Module build failed: Error: Final loader didn't return a Buffer or String
</code>```

How can I generate TypeScript code using a webpack loader?

package.json

```<code>{
  "name": "so-example",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "build": "webpack"
  },
  "dependencies": {
    "awesome-typescript-loader": "^3.2.3",
    "typescript": "^2.6.1",
    "webpack": "^3.8.1"
  }
}
</code>```

webpack.config.js

```<code>const path = require('path');

module.exports = {
  entry: './index.ts',
  output: {
    filename: 'output.js',
  },
  resolveLoader: {
    alias: {
      'my-own-loader': path.resolve(__dirname, "my-own-loader.js"),
    },
  },
  module: {
    rules: [
      {
        test: /\.api$/,
        exclude: /node_modules/,
        use: ["awesome-typescript-loader", "my-own-loader"],
      },
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        loader: "awesome-typescript-loader",
      },
    ]
  },
};
</code>```

my-own-loader.js

```<code>module.exports = function(source) {
  return `
interface DummyContent {
    name: string;
    age?: number;
}
`;
};
</code>```

index.ts

```<code>import * as foo from './example';

console.log(foo);
</code>```

example.api

```<code>{}
</code>```

I recognize that there are other code generation techniques. For example, I could convert my JSON files to TypeScript with some build tool and check them in. I'm looking for a more dynamic solution.

my-own-loader.js does not export json but string.

That's correct, much like loading an image file doesn't always export binary data but sometimes outputs a JavaScript data structure representing metadata about the image.

Why you need to define the typescript interfaces from json file? Would the interfaces be used for typescript compilation?

Yes. I want to import a file that describes my API data structures and automatically generate corresponding TypeScript interfaces. Having a shared file allows the frontend(s) and backend(s) to always agree on what data will be present.

答:
If your API follows the swagger spec, you can use the npm package swagger-ts-generator to generate TypeScript files from it:

Swagger TypeScript code generator

Node module to generate TypeScript code for Angular (2 and above)
  based on Webapi meta data in Swagger v2 format.

Basically, you give it the swagger URL and it generates TypeScript. The examples are for Gulp, but they should port over to WebPack fairly well:

```<code>var swagger = {
    url: 'http://petstore.swagger.io/v2/swagger.json',
    //url: 'http://127.0.0.1/ZIB.WebApi.v2/swagger/docs/v1',
    swaggerFile: folders.swaggerFolder + files.swaggerJson,
    swaggerFolder: folders.swaggerFolder,
    swaggerTSGeneratorOptions: {
        modelFolder: folders.srcWebapiFolder,
        enumTSFile: folders.srcWebapiFolder + 'enums.ts',
        enumLanguageFiles: [
            folders.srcLanguagesFolder + 'nl.json',
            folders.srcLanguagesFolder + 'en.json',
        ],
        modelModuleName: 'webapi.models',
        enumModuleName: 'webapi.enums',
        enumRef: './enums',
        namespacePrefixesToRemove: [
        ],
        typeNameSuffixesToRemove: [
        ]
    }
}
</code>```

Body:
I am attempting to create a webpack loader that converts a file containing a description of API data structures into a set of TypeScript interfaces.

In my concrete case, the file is JSON, but this should be ultimately irrelevant — the file is only a shared source of data describing the interaction between web application backend(s) and frontend(s). In my MCVE below, you can see that the JSON file contains an empty object to underscore how the type and contents of the file do not matter to the problem.

My current attempt reports two errors (I assume the second is caused by the first):

[at-loader]: Child process failed to process the request:  Error: Could not find file: '/private/tmp/ts-loader/example.api'.

ERROR in ./example.api
Module build failed: Error: Final loader didn't return a Buffer or String

How can I generate TypeScript code using a webpack loader?

package.json

{
  "name": "so-example",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "build": "webpack"
  },
  "dependencies": {
    "awesome-typescript-loader": "^3.2.3",
    "typescript": "^2.6.1",
    "webpack": "^3.8.1"
  }
}

webpack.config.js

const path = require('path');

module.exports = {
  entry: './index.ts',
  output: {
    filename: 'output.js',
  },
  resolveLoader: {
    alias: {
      'my-own-loader': path.resolve(__dirname, "my-own-loader.js"),
    },
  },
  module: {
    rules: [
      {
        test: /\.api$/,
        exclude: /node_modules/,
        use: ["awesome-typescript-loader", "my-own-loader"],
      },
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        loader: "awesome-typescript-loader",
      },
    ]
  },
};

my-own-loader.js

module.exports = function(source) {
  return `
interface DummyContent {
    name: string;
    age?: number;
}
`;
};

index.ts

import * as foo from './example';

console.log(foo);

example.api

{}

I recognize that there are other code generation techniques. For example, I could convert my JSON files to TypeScript with some build tool and check them in. I'm looking for a more dynamic solution.

my-own-loader.js does not export json but string.

That's correct, much like loading an image file doesn't always export binary data but sometimes outputs a JavaScript data structure representing metadata about the image.

Why you need to define the typescript interfaces from json file? Would the interfaces be used for typescript compilation?

Yes. I want to import a file that describes my API data structures and automatically generate corresponding TypeScript interfaces. Having a shared file allows the frontend(s) and backend(s) to always agree on what data will be present.

Body:
If your API follows the swagger spec, you can use the npm package swagger-ts-generator to generate TypeScript files from it:

Swagger TypeScript code generator

Node module to generate TypeScript code for Angular (2 and above)
  based on Webapi meta data in Swagger v2 format.

Basically, you give it the swagger URL and it generates TypeScript. The examples are for Gulp, but they should port over to WebPack fairly well:

var swagger = {
    url: 'http://petstore.swagger.io/v2/swagger.json',
    //url: 'http://127.0.0.1/ZIB.WebApi.v2/swagger/docs/v1',
    swaggerFile: folders.swaggerFolder + files.swaggerJson,
    swaggerFolder: folders.swaggerFolder,
    swaggerTSGeneratorOptions: {
        modelFolder: folders.srcWebapiFolder,
        enumTSFile: folders.srcWebapiFolder + 'enums.ts',
        enumLanguageFiles: [
            folders.srcLanguagesFolder + 'nl.json',
            folders.srcLanguagesFolder + 'en.json',
        ],
        modelModuleName: 'webapi.models',
        enumModuleName: 'webapi.enums',
        enumRef: './enums',
        namespacePrefixesToRemove: [
        ],
        typeNameSuffixesToRemove: [
        ]
    }
}


问:
Best way to disable Android game install banner from C2 game url
How to disable @Android google web app install banner ?

On android 6 phones chrome started to display install banner, now our C2 games are installed to phone when user should be playing games on our website.

We prefer to allow usage on website only. What setting should we change on page to prevent the installation. We have https site.

答:
```<code>window.addEventListener('beforeinstallprompt', function(e) {
  console.log('beforeinstallprompt Event fired');
  e.preventDefault();
  return false;
});
</code>```


问:
Hive Join on String returns no matching
I am trying to run a simple join on string values but getting no matching rows. However all the values are the same in both the tables

```<code>select l2.word,d.polarity from l2 join  dictionary d on (l2.word=d.word);

L2 table :
realtimesession_id      bigint                  None
word                    string                  None

Dictionary table :
realtimesession_id      bigint                  None
word                    string                  None
</code>```

I tried setting set hive.auto.convert.join=true;
but still no records matching. Please someone help.

答:
Join on string will work. Just keep in mind that string matching will be case-sensitive.

Consider using functions like UPPER or LOWER.

For example,

```<code>select * from temp join new_temp on LOWER(temp.dept) = LOWER(new_temp.dept);
</code>```

(Tested solution)

Title: Hive Join on String returns no matching

Body:
I am trying to run a simple join on string values but getting no matching rows. However all the values are the same in both the tables

select l2.word,d.polarity from l2 join  dictionary d on (l2.word=d.word);

L2 table :
realtimesession_id      bigint                  None
word                    string                  None

Dictionary table :
realtimesession_id      bigint                  None
word                    string                  None

I tried setting set hive.auto.convert.join=true;
but still no records matching. Please someone help.

Body:
Join on string will work. Just keep in mind that string matching will be case-sensitive.

Consider using functions like UPPER or LOWER.

For example,

select * from temp join new_temp on LOWER(temp.dept) = LOWER(new_temp.dept);

(Tested solution)


问:
SQL query to combine data from 2 tables with pivot
I have 2 tables:

```<code>CREATE TABLE [ObIndex](
    [idx] [int] IDENTITY(1,1) NOT NULL,
    [dtg] [smalldatetime] NOT NULL,
    [site] [varchar](6) NOT NULL,
    [name] [varchar](32) NOT NULL,
    [lat] [float] NOT NULL,
    [lon] [float] NOT NULL,
    [el] [int] NOT NULL,
 CONSTRAINT [PK_SurfaceObIndex] PRIMARY KEY CLUSTERED
(
    [icao] ASC,
    [dtg] ASC
)
</code>```

and

```<code>CREATE TABLE [ObData](
    [idx] [int] NOT NULL,
    [label] [varchar](32) NOT NULL,
    [value] [varchar](128) NOT NULL,
 CONSTRAINT [PK_SurfaceObData] PRIMARY KEY CLUSTERED
(
    [idx] ASC,
    [label] ASC
)
</code>```

where for each record in ObIndex there will exist one or more records in ObData, each containing a single parameter from the observation (note that stations may have different instruments):

```<code>ObIndex (metadata)
    1,"2017-11-15 12:00:00","C104","AWS 104",-77.100,-167.100,33
    2,"2017-11-15 12:00:00","C105","AWS 105",-77.200,-167.200,55
    etc.

ObData (instrument data)
    1,"Temperature", -10
    1,"DewPoint", -20
    1,"WindDirection", 123
    1,"WindSpeed", 45
    1,"Humidity",66
    2,"Temperature", -10
    2,"DewPoint", -20
    2,"WindDirection", 123
    2,"WindSpeed", 45
    2,"Pressure",998
    etc.
</code>```

There is also a third table of current station locations that is not relevant to this question.

I want to use a single query, if possible, to extract all the values from the ObData table for each ObIndex record, and convert the 'label' values to column names.  This query works for a single observation (or record in ObIndex):

```<code>select
Min(Case label When 'Temperature' Then value End) Temperature,
Min(Case label When 'DewPoint' Then value End) DewPoint
Min(Case label When 'WindSpeed' Then value End) WindSpeed,
Min(Case label When 'WindDirection' Then value End) WindDirection,
From SurfaceObData Where SurfaceObData.idx = 138586
</code>```

Can anyone help me complete the query to return data from all observations?
The results would ideally look like:

```<code>idx,site,dtg,WindDirection,WindSpeed,Temperature,Humidity,Dewpoint,Pressure
1,"C104",2017-11-15 12:00:00,123,45,-10,66,-20,
2,"C106",2017-11-15 12:00:00,123,45,-10,,-20,998
</code>```

(Not sure how to put it in table format... First post.)

Thanks in advance!

答:
Thanks to the assist from Squirrel I found the solution:</p>

```<code>select i.idx,i.site,i.dtg,
    Min(Case d.label When 'WindDirection' Then d.value End) WindDirection,
    Min(Case d.label When 'WindSpeed' Then d.value End) WindSpeedKnots,
    Min(Case d.label When 'Temperature' Then d.value End) Temperature,
    Min(Case d.label When 'Humidity' Then d.value End) Humidity,
    Min(Case d.label When 'DewPoint' Then d.value End) DewPoint,
    Min(Case d.label When 'Pressure' Then d.value End) Pressure
    from SurfaceObData  as d, SurfaceObIndex as i
    where d.idx = i.idx
    group by i.idx,i.site,i.dtg
</code>```

Body:
I have 2 tables:

CREATE TABLE [ObIndex](
    [idx] [int] IDENTITY(1,1) NOT NULL,
    [dtg] [smalldatetime] NOT NULL,
    [site] [varchar](6) NOT NULL,
    [name] [varchar](32) NOT NULL,
    [lat] [float] NOT NULL,
    [lon] [float] NOT NULL,
    [el] [int] NOT NULL,
 CONSTRAINT [PK_SurfaceObIndex] PRIMARY KEY CLUSTERED
(
    [icao] ASC,
    [dtg] ASC
)

and

CREATE TABLE [ObData](
    [idx] [int] NOT NULL,
    [label] [varchar](32) NOT NULL,
    [value] [varchar](128) NOT NULL,
 CONSTRAINT [PK_SurfaceObData] PRIMARY KEY CLUSTERED
(
    [idx] ASC,
    [label] ASC
)

where for each record in ObIndex there will exist one or more records in ObData, each containing a single parameter from the observation (note that stations may have different instruments):

ObIndex (metadata)
    1,"2017-11-15 12:00:00","C104","AWS 104",-77.100,-167.100,33
    2,"2017-11-15 12:00:00","C105","AWS 105",-77.200,-167.200,55
    etc.

ObData (instrument data)
    1,"Temperature", -10
    1,"DewPoint", -20
    1,"WindDirection", 123
    1,"WindSpeed", 45
    1,"Humidity",66
    2,"Temperature", -10
    2,"DewPoint", -20
    2,"WindDirection", 123
    2,"WindSpeed", 45
    2,"Pressure",998
    etc.

There is also a third table of current station locations that is not relevant to this question.

I want to use a single query, if possible, to extract all the values from the ObData table for each ObIndex record, and convert the 'label' values to column names.  This query works for a single observation (or record in ObIndex):

select
Min(Case label When 'Temperature' Then value End) Temperature,
Min(Case label When 'DewPoint' Then value End) DewPoint
Min(Case label When 'WindSpeed' Then value End) WindSpeed,
Min(Case label When 'WindDirection' Then value End) WindDirection,
From SurfaceObData Where SurfaceObData.idx = 138586

Can anyone help me complete the query to return data from all observations?
The results would ideally look like:

idx,site,dtg,WindDirection,WindSpeed,Temperature,Humidity,Dewpoint,Pressure
1,"C104",2017-11-15 12:00:00,123,45,-10,66,-20,
2,"C106",2017-11-15 12:00:00,123,45,-10,,-20,998

(Not sure how to put it in table format... First post.)

Thanks in advance!

Body:
Thanks to the assist from Squirrel I found the solution:

select i.idx,i.site,i.dtg,
    Min(Case d.label When 'WindDirection' Then d.value End) WindDirection,
    Min(Case d.label When 'WindSpeed' Then d.value End) WindSpeedKnots,
    Min(Case d.label When 'Temperature' Then d.value End) Temperature,
    Min(Case d.label When 'Humidity' Then d.value End) Humidity,
    Min(Case d.label When 'DewPoint' Then d.value End) DewPoint,
    Min(Case d.label When 'Pressure' Then d.value End) Pressure
    from SurfaceObData  as d, SurfaceObIndex as i
    where d.idx = i.idx
    group by i.idx,i.site,i.dtg