问:
How to force Chrome/Firefox/Opera to do crossdomain requests from localhost?
Hy,

So I've got this problem: I'm trying to develop an HTML file on my localhost, and all the browsers I have installed are preventing me to send cross-domain requests.

What I'm trying to do is to convert a script I wrote in Python (with Mechanize, pyquery and lxml) to Javascript, the reasons don't really matter (I thought in Javascript it would be easier to simulate something).

Cross-domain requests from local files used to work, and are still working on the latest Safari (stable), but I can't install Safari on this machine (it's a Linux box).

EDIT

I discovered the escalated privileges of Firefox, e.g.:

```<code>netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
// among others
</code>```

Problem is, I'm also trying to access the content loaded in an iFrame ... as I said, I'm trying to simulate a browser session, like I would with a library like Mechanize, but from Javascript. My script still works in Safari.

So how to force Chrome / Firefox / Opera to bypass all security restrictions from locally stored files?

I'm interested in a browser command-line option, I would even consider a patch to the browser (I'm the user, not trying to distribute this to anyone else).

Thanks,

答:
Why don't you start a simple http server instead to solve your problem?

```<code>import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

HandlerClass = SimpleHTTPRequestHandler
ServerClass  = BaseHTTPServer.HTTPServer
Protocol     = "HTTP/1.0"

if sys.argv[1:]:
    port = int(sys.argv[1])
else:
    port = 8000
server_address = ('127.0.0.1', port)

HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)

sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
</code>```

This python code will start a simple http server listening on port 8000 or the first argument and handles all files in the folder from this script.

Body:
Hy,

So I've got this problem: I'm trying to develop an HTML file on my localhost, and all the browsers I have installed are preventing me to send cross-domain requests.

What I'm trying to do is to convert a script I wrote in Python (with Mechanize, pyquery and lxml) to Javascript, the reasons don't really matter (I thought in Javascript it would be easier to simulate something).

Cross-domain requests from local files used to work, and are still working on the latest Safari (stable), but I can't install Safari on this machine (it's a Linux box).

EDIT

I discovered the escalated privileges of Firefox, e.g.:

netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
// among others

Problem is, I'm also trying to access the content loaded in an iFrame ... as I said, I'm trying to simulate a browser session, like I would with a library like Mechanize, but from Javascript. My script still works in Safari.

So how to force Chrome / Firefox / Opera to bypass all security restrictions from locally stored files?

I'm interested in a browser command-line option, I would even consider a patch to the browser (I'm the user, not trying to distribute this to anyone else).

Thanks,

Body:
Why don't you start a simple http server instead to solve your problem?

import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

HandlerClass = SimpleHTTPRequestHandler
ServerClass  = BaseHTTPServer.HTTPServer
Protocol     = "HTTP/1.0"

if sys.argv[1:]:
    port = int(sys.argv[1])
else:
    port = 8000
server_address = ('127.0.0.1', port)

HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)

sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()

This python code will start a simple http server listening on port 8000 or the first argument and handles all files in the folder from this script.


来源: stackexchange

问:
Track bounced/undeliverable emails sent by AWS Cognito
I'm looking for a way to figure out if the emails AWS Cognito sends out (e.g. verification emails, password reset emails, etc.) are bouncing.

In fact, any way to confirm if emails have even been sent would be nice to have.

In theory it uses SES, but the SES dashboard shows no activity at all even though emails are definitely getting sent.

Is this functionality available at all?

答: The emails are sent by Cognito on behalf of developers so there is no way to track them at this point. We have heard this functionality request in the past and we have an item on our roadmap to expose the bounce stream to developers. I will add a +1 on your behalf to the feature.</p>

ContentLicense: CC BY-SA 3.0


问:
Manually remove multiple “Open a Terminal” icons from the Eclipse toolbar
The problem is I have multiple "Open a Terminal" icons in my toolbar this is the same problem as reported in Multiple "Open a Terminal" icons keep appearing in Eclipse toolbar however the answers do not appear to work for me.

I was wonder perhaps it is possible to manually edit a file to remove the extra or all "Open a Terminal" icons.

Other suggestions for removing the icons are welcome as well.

答:
After a bit of digging + grepping I worked out that I could edit the file:

```<code>workspace/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi
</code>```

And remove the element that contained "Open a Terminal".

When I started eclipse the icons had finally disappeared.

Body:
After a bit of digging + grepping I worked out that I could edit the file:

workspace/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi

And remove the element that contained "Open a Terminal".

When I started eclipse the icons had finally disappeared.


问:
jQuery - How do I find an element with partial ID under a specific element
I have multiple records, each with the same fields, they all have the same name/id, plus the RecordID.  When I press cmdUpdate_xxx I detect which record div, assigning it to 'fldTarget'.  I know want to check each field (20, so don't want to do this manually) for validity.  I've tried

```<code>$('#RecordsWrapper')
    .on("click" , "[id*=cmdUpdate]", "input", function(e){
      fldTarget = $(this);
      fldAccountID = fldTarget.parent().find("#txtAccountID").prop("id");`
    })
</code>```

...but fldAccountID comes back as undefined.  How can I locate a sub element with an ID that contains 'txtAccountID' under 'Record001' div?

```<code><div id='RecordsWrapper'>
<div id='Record001'>
  <input type='text' id='txtAccount_001'>
  <input type='text' id='txtEntry_001'>
  <input type='text' id='txtValue_001'>
  <input type='submit' id='cmdUpdate_001'>
</div>
<div id='Record002'>
  <input type='text' id='txtAccount_002'>
  <input type='text' id='txtEntry_002'>
  <input type='text' id='txtValue_002'>
  <input type='submit' id='cmdUpdate_002'>
</div>
</div>
</code>```

答:
Since you already have the div for the current record stored in fldTarget can you parse the record ID from that div's own ID?

For example.

```<code>var recordID = fldTarget.prop('id').replace('Record', '');
var txtAccountID = 'txtAccount_' + recordID;
</code>```

Or you could add a data-* attribute for each "record" div to hold contain the ID num like this:

```<code><div id='Record001' data-id="001">
    <input type='text' id='txtAccount_001'>
    <input type='text' id='txtEntry_001'>
    <input type='text' id='txtValue_001'>
    <input type='submit' id='cmdUpdate_001'>
</div>
<div id='Record002' data-id="002">
    <input type='text' id='txtAccount_002'>
    <input type='text' id='txtEntry_002'>
    <input type='text' id='txtValue_002'>
    <input type='submit' id='cmdUpdate_002'>
</div>
</code>```

And get the value from that attribute like this:

```<code>var recordID = fldTarget.data('id');
var txtAccountID = 'txtAccount_' + recordID;
</code>```

Body:
I have multiple records, each with the same fields, they all have the same name/id, plus the RecordID.  When I press cmdUpdate_xxx I detect which record div, assigning it to 'fldTarget'.  I know want to check each field (20, so don't want to do this manually) for validity.  I've tried

$('#RecordsWrapper')
    .on("click" , "[id*=cmdUpdate]", "input", function(e){
      fldTarget = $(this);
      fldAccountID = fldTarget.parent().find("#txtAccountID").prop("id");`
    })

...but fldAccountID comes back as undefined.  How can I locate a sub element with an ID that contains 'txtAccountID' under 'Record001' div?

  <input type='text' id='txtAccount_001'>
  <input type='text' id='txtEntry_001'>
  <input type='text' id='txtValue_001'>
  <input type='submit' id='cmdUpdate_001'>

  <input type='text' id='txtAccount_002'>
  <input type='text' id='txtEntry_002'>
  <input type='text' id='txtValue_002'>
  <input type='submit' id='cmdUpdate_002'>

Body:
Since you already have the div for the current record stored in fldTarget can you parse the record ID from that div's own ID?

For example.

var recordID = fldTarget.prop('id').replace('Record', '');
var txtAccountID = 'txtAccount_' + recordID;

Or you could add a data-* attribute for each "record" div to hold contain the ID num like this:

<div id='Record001' data-id="001">
    <input type='text' id='txtAccount_001'>
    <input type='text' id='txtEntry_001'>
    <input type='text' id='txtValue_001'>
    <input type='submit' id='cmdUpdate_001'>
</div>
<div id='Record002' data-id="002">
    <input type='text' id='txtAccount_002'>
    <input type='text' id='txtEntry_002'>
    <input type='text' id='txtValue_002'>
    <input type='submit' id='cmdUpdate_002'>
</div>

And get the value from that attribute like this:

var recordID = fldTarget.data('id');
var txtAccountID = 'txtAccount_' + recordID;


问:
Find the lowest value of php foreach loops
I am trying to extract the lower (but not 0) of two figures produced by the following code. This code loops twice giving two figures. I only want the lower of the two. I can see that I should be using min(array) but I can't really see where to start.</p>

```<code>foreach ($objResult->ProductGroups as $objProductGroup)
{
    if ($objProductGroup->hasProductQuote)
    {
        foreach ($objProductGroup->ProductQuotes as $objProductQuote)
        {
            if (!$objProductQuote->hasErrors)
            {
                printf("<div>£%01.2f</div>", $objProductQuote->Figures->RegularPayment);
                break;
            }
        }
    }
}
</code>```

答:
Instead of printing the quotes as you get to them, append them to an array. Then you can use min afterward to print the lower of the two.

```<code>$quotes = [];
foreach ($objResult->ProductGroups as $objProductGroup)
{
    if ($objProductGroup->hasProductQuote)
    {
        foreach ($objProductGroup->ProductQuotes as $objProductQuote)
        {
            if (!$objProductQuote->hasErrors)
            {
                $quotes[] = $objProductQuote->Figures->RegularPayment;
                break;
            }
        }
    }
}
printf("<div>£%01.2f</div>", min($quotes));
</code>```

Body:
I am trying to extract the lower (but not 0) of two figures produced by the following code. This code loops twice giving two figures. I only want the lower of the two. I can see that I should be using min(array) but I can't really see where to start.

foreach ($objResult->ProductGroups as $objProductGroup)
{
    if ($objProductGroup->hasProductQuote)
    {
        foreach ($objProductGroup->ProductQuotes as $objProductQuote)
        {
            if (!$objProductQuote->hasErrors)
            {
                printf("
£%01.2f
", $objProductQuote->Figures->RegularPayment);
                break;
            }
        }
    }
}

Body:
Instead of printing the quotes as you get to them, append them to an array. Then you can use min afterward to print the lower of the two.

$quotes = [];
foreach ($objResult->ProductGroups as $objProductGroup)
{
    if ($objProductGroup->hasProductQuote)
    {
        foreach ($objProductGroup->ProductQuotes as $objProductQuote)
        {
            if (!$objProductQuote->hasErrors)
            {
                $quotes[] = $objProductQuote->Figures->RegularPayment;
                break;
            }
        }
    }
}
printf("<div>&pound;%01.2f</div>", min($quotes));


问:
HTML - CSS: Styling <object>?
If my div container has this:

```<code><div id="container"><img src...
</code>```

I can style the image by this:

```<code>CSS
#container img{ ... }
</code>```

For object tag

```<code><div id="container"><object ...
</code>```

How do I address it? I tried this:

```<code>CSS
#container object{ width: 100px; }
</code>```

But it does not work.

Assume the I cant define "id" or "class" for the object tag

I am using tinymce to embed to youtube video. And the code will be rendered like this:

```<code><div id="container">
...

    <div id="content">
      <p>
      <object width="435" height="350" type="application/x-shockwave-flash" data="http://www.youtube.com/v/l9caxMr9RgY">
      <param value="http://www.youtube.com/v/XXXXXX" name="src"></object>
      </p>
    </div>
</div>
</code>```

答:
An object tag can be styled using CSS.  Ref link text

The reason width didn't work in your example is that its a HTML attribute only and not accessible with CSS (see list in link above).

I would recommend that you put the object into a wrapper div (give the object a width of 100%) and control the width of the wrapper div with css.

ContentLicense: CC BY-SA 2.5

Title: HTML - CSS: Styling <object>?

Body:
If my div container has this:

<img src...

I can style the image by this:

CSS
#container img{ ... }

For object tag

<object ...

How do I address it? I tried this:

CSS
#container object{ width: 100px; }

But it does not work.

Assume the I cant define "id" or "class" for the object tag

I am using tinymce to embed to youtube video. And the code will be rendered like this:

...

      <object width="435" height="350" type="application/x-shockwave-flash" data="http://www.youtube.com/v/l9caxMr9RgY">
      <param value="http://www.youtube.com/v/XXXXXX" name="src"></object>

ContentLicense: CC BY-SA 4.0


问:
PowerPC version of Go
I just got access to a powerful Minski IBM machine (Linux) and intend on running some go scripts on it. I have gone through a lot of the versions of golang and tried installing and using them on the machine but none of them seem to work. Is there some special version of GO that I need that is specially designed to work on this powerful computer.

I have now tried installing about 4 or 5 different versions but still keep getting:

```<code>The program 'go' is currently not installed. To run 'go' please ask your administrator to install the package 'golang-go'
</code>```

I was told that there is no need for an administrator to do a system wide install and to just install golang on my machine.

I have been using this step-by-step to install GO on this machine:
https://www.digitalocean.com/community/tutorials/how-to-install-go-1-6-on-ubuntu-14-04

I do not have root access on this machine, just FYI

EDIT:
Problem solved

Had to use:

```<code>curl -O storage.googleapis.com/golang/go1.8.3.linux-ppc64le.tar.gz
</code>```

答:
Go Downloads

PowerPC architecture: ppc64le (64-bit PowerPC little-endian). For example, for Go 1.8.3,

go1.8.3.linux-ppc64le.tar.gz: https://storage.googleapis.com/golang/go1.8.3.linux-ppc64le.tar.gz

Title: PowerPC version of Go

Body:
I just got access to a powerful Minski IBM machine (Linux) and intend on running some go scripts on it. I have gone through a lot of the versions of golang and tried installing and using them on the machine but none of them seem to work. Is there some special version of GO that I need that is specially designed to work on this powerful computer.

I have now tried installing about 4 or 5 different versions but still keep getting:

The program 'go' is currently not installed. To run 'go' please ask your administrator to install the package 'golang-go'

I was told that there is no need for an administrator to do a system wide install and to just install golang on my machine.

I have been using this step-by-step to install GO on this machine:
https://www.digitalocean.com/community/tutorials/how-to-install-go-1-6-on-ubuntu-14-04

I do not have root access on this machine, just FYI

EDIT:
Problem solved

Had to use:

curl -O storage.googleapis.com/golang/go1.8.3.linux-ppc64le.tar.gz


问:
Is it possible to debug application wireless or without connecting USB cable in XCODE?
how to connect device in xcode without cable. it is tedious to connect the cable and my USB is lil bit loose, so it disconnects from PC.</p>

答:
This is now officially supported as a built-in feature in Xcode 9.

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?


问:
How to make a Calculator using extends Fragment
I'm trying to make a tabbed app to the store I work. It's to count the money and see if it's right.

In the first tab is the aplication, and in the second one, I wanna put a calculator (like the Android's one). Then, I'm using a Tabbed Activity so my Java classes have extends Fragment.

I'm trying to watch some YouTube videos, but every one uses extends AppCompatActivity, so I made the same code, but I think this one doesn't work like Fragments. My app isn't working when I try to run it.

What can I do to make this work? What can I change?

I already put the methods in "onClick" on Layout's Button.

```<code>package com.example.ayrton.fecharcaixa;
import android.app.Dialog;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class TabCalc extends Fragment{

    TextView screen;
    String display = "";
    String currentOperator = "";

    public TabCalc(){

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab_calculadora, container, false);
        screen = (TextView) view.findViewById(R.id.txtScreen);
        screen.setText("");
        return view;
    }
    public void updateScreen(){
        screen.setText(display);
    }

    public void onClickNumber (View v){
        Button b = (Button) v;
        display += b.getText();
        updateScreen();
    }

    public void onClickOperator(View v){
        Button b = (Button)v;
        display += b.getText();
        currentOperator = b.getText().toString();
        updateScreen();
    }

    public void clear(){
        display = "";
        currentOperator = "";
        updateScreen();
    }

    public void onClickPonto(View v){
        Button b = (Button)v;
        display += b.getText();
        updateScreen();
    }

    public void onClickClear(View v){
        clear();
        updateScreen();
    }

    public void onClickEqual(View v){
    }
}
</code>```

The error is:

```<code>FATAL EXCEPTION: main
    Process: com.example.ayrton.fecharcaixa, PID: 12074
    java.lang.IllegalStateException: Could not find method onClickNumber(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'bt7'
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
        at android.view.View.performClick(View.java:5612)
        at android.view.View$PerformClick.run(View.java:22285)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6123)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
</code>```

答:
You have to define your onClickNumber(View) in the Tabbed Activity where the fragment is included.

The other solution is to define the onclicklistener of the button in the fragment class code:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab_calculadora, container, false);
        screen = (TextView) view.findViewById(R.id.txtScreen);
        screen.setText("");

        Button yourButton = (Button)view.findViewById(R.id.yourButtonId);
        yourButton.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                  onClickNumber(v);
             }
        });
        return view;
}
</code>```

Body:
I'm trying to make a tabbed app to the store I work. It's to count the money and see if it's right.

In the first tab is the aplication, and in the second one, I wanna put a calculator (like the Android's one). Then, I'm using a Tabbed Activity so my Java classes have extends Fragment.

I'm trying to watch some YouTube videos, but every one uses extends AppCompatActivity, so I made the same code, but I think this one doesn't work like Fragments. My app isn't working when I try to run it.

What can I do to make this work? What can I change?

I already put the methods in "onClick" on Layout's Button.

package com.example.ayrton.fecharcaixa;
import android.app.Dialog;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class TabCalc extends Fragment{

    TextView screen;
    String display = "";
    String currentOperator = "";

    public TabCalc(){

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab_calculadora, container, false);
        screen = (TextView) view.findViewById(R.id.txtScreen);
        screen.setText("");
        return view;
    }
    public void updateScreen(){
        screen.setText(display);
    }

    public void onClickNumber (View v){
        Button b = (Button) v;
        display += b.getText();
        updateScreen();
    }

    public void onClickOperator(View v){
        Button b = (Button)v;
        display += b.getText();
        currentOperator = b.getText().toString();
        updateScreen();
    }

    public void clear(){
        display = "";
        currentOperator = "";
        updateScreen();
    }

    public void onClickPonto(View v){
        Button b = (Button)v;
        display += b.getText();
        updateScreen();
    }

    public void onClickClear(View v){
        clear();
        updateScreen();
    }

    public void onClickEqual(View v){
    }
}

The error is:

FATAL EXCEPTION: main
    Process: com.example.ayrton.fecharcaixa, PID: 12074
    java.lang.IllegalStateException: Could not find method onClickNumber(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'bt7'
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
        at android.view.View.performClick(View.java:5612)
        at android.view.View$PerformClick.run(View.java:22285)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6123)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

Body:
You have to define your onClickNumber(View) in the Tabbed Activity where the fragment is included.

The other solution is to define the onclicklistener of the button in the fragment class code:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab_calculadora, container, false);
        screen = (TextView) view.findViewById(R.id.txtScreen);
        screen.setText("");

        Button yourButton = (Button)view.findViewById(R.id.yourButtonId);
        yourButton.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                  onClickNumber(v);
             }
        });
        return view;
}


问:
convert to show percentage of the sum of 2 or more combined columns
I have looked at the similar questions and was unable to find anything that answered my question.

I have a column that is the calculation of other columns of which sum I would like to divide by a set number and show results in percentage from. I have tried the below query and am able to show in decimal. Basically find out what percentage of UPH an associate is doing...This way I can tell if they are slacking in their department or exceling. I am using 150 as my base rate

```<code>SELECT
ID
  , DeptCode AS 'DC'
  , OpCode AS 'OC'
  ,Units = sum(Units)
  ,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0))
  ,Percentage = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0)) / 150

FROM dbo.TimeLog
 WITH (NOLOCK)

WHERE DeptCode = 'FB'
  and OpCode   = 'PU'
  and Units IS NOT NULL
GROUP BY
    ID
  , DeptCode
  , OpCode
</code>```

Here is my result...

```<code>ID      DC  OC  Units   UPH Percentage
11259   FB  PU  553     114 0.760000
2375935 FB  PU  263     70  0.466666
</code>```

I would like to see column 'Percentage' like the below

```<code>ID      DC  OC  Units   UPH Percentage
11259   FB  PU  553     114 76%
2375935 FB  PU  263     70  47%
</code>```

Any help would be appreciated and I apologize in advance if this is elementary for a lot you, I am relatively new to SQL

答:
You can use format(decimal, 'p') as below:</p>

```<code>      ,Percentage = Format(cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0)) / 100 , 'p')
</code>```

Body:
I have looked at the similar questions and was unable to find anything that answered my question.

I have a column that is the calculation of other columns of which sum I would like to divide by a set number and show results in percentage from. I have tried the below query and am able to show in decimal. Basically find out what percentage of UPH an associate is doing...This way I can tell if they are slacking in their department or exceling. I am using 150 as my base rate

SELECT
ID
  , DeptCode AS 'DC'
  , OpCode AS 'OC'
  ,Units = sum(Units)
  ,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0))
  ,Percentage = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0)) / 150

FROM dbo.TimeLog
 WITH (NOLOCK)

WHERE DeptCode = 'FB'
  and OpCode   = 'PU'
  and Units IS NOT NULL
GROUP BY
    ID
  , DeptCode
  , OpCode

Here is my result...

ID      DC  OC  Units   UPH Percentage
11259   FB  PU  553     114 0.760000
2375935 FB  PU  263     70  0.466666

I would like to see column 'Percentage' like the below

ID      DC  OC  Units   UPH Percentage
11259   FB  PU  553     114 76%
2375935 FB  PU  263     70  47%

Any help would be appreciated and I apologize in advance if this is elementary for a lot you, I am relatively new to SQL

Body:
You can use format(decimal, 'p') as below:

      ,Percentage = Format(cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60  as decimal(10,0)) / 100 , 'p')


问:
How do I center my logo in the navigation bar?
How do I center my logo in my Navigation bar? I kind of already have it centered, but the issue that I'm running into is when I place an image in the content area, the image covers up part of the logo. I do want the logo kind of dropped a little from the navigation links. I don't want a giant space between the logo and the content image. Is there a way I can achieve this? The image attached is the design I'm trying to accomplish. Thanks in advance!

body {
    font-family:Georgia;
    font-size:12pt;
    }

    * {
 margin:0;
  padding:0;
     }

    #header {
    background-color:#000000;
    height:100px;
    margin:auto;
    }

    #header ul {
    margin:0 auto;
    width:35%;
    padding:12px;
    list-style: none;
    }

    #header li {
    float: left;
    }

    #header a {
    padding:0 14px;
    text-align:center;
    display:block;
 text-decoration:none;
 color:#FFFFFF;
 font-size:18pt;
 }

    #header ul li a.logo {
    background: url("Logo.png");
    background-repeat:no-repeat;
    height:140px;
    display:block;
    width:140px;
    padding: 0;

    .clearfix {
    *zoom: 1;
    }

    .clearfix:after {
     content: "";
     clear: both;
     display: table;
     }

    #MainContent {
 }

    #MainContent img {
 margin-top:-10px;
 position:absolute;
 left:0;
 width:100%;
    }

    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
 <div id="header" class="clearfix">

     <ul class="Nav">
   <li>Home</li>
   <li>Menu</li>
   <li></li>
   <li>Gallery</li>
   <li>About</li>

            </ul>

            </div>
 <div id="MainContent">
   <img src="Photos/drinks.jpeg">
 </div>
</body>

    </code>```

答:
You can add a z-index to your .logo class. This will render it above the image.

e.g.

```<code>.logo {
  z-index: 100;
}
</code>```

https://developer.mozilla.org/de/docs/Web/CSS/z-index

Body:
How do I center my logo in my Navigation bar? I kind of already have it centered, but the issue that I'm running into is when I place an image in the content area, the image covers up part of the logo. I do want the logo kind of dropped a little from the navigation links. I don't want a giant space between the logo and the content image. Is there a way I can achieve this? The image attached is the design I'm trying to accomplish. Thanks in advance!

body {
    font-family:Georgia;
    font-size:12pt;
    }

    * {
 margin:0;
  padding:0;
     }

    #header {
    background-color:#000000;
    height:100px;
    margin:auto;
    }

    #header ul {
    margin:0 auto;
    width:35%;
    padding:12px;
    list-style: none;
    }

    #header li {
    float: left;
    }

    #header a {
    padding:0 14px;
    text-align:center;
    display:block;
 text-decoration:none;
 color:#FFFFFF;
 font-size:18pt;
 }

    #header ul li a.logo {
    background: url("Logo.png");
    background-repeat:no-repeat;
    height:140px;
    display:block;
    width:140px;
    padding: 0;

    .clearfix {
    *zoom: 1;
    }

    .clearfix:after {
     content: "";
     clear: both;
     display: table;
     }

    #MainContent {
 }

    #MainContent img {
 margin-top:-10px;
 position:absolute;
 left:0;
 width:100%;
    }

    }

Home

Menu

Gallery

About

Body:
You can add a z-index to your .logo class. This will render it above the image.

e.g.

.logo {
  z-index: 100;
}

https://developer.mozilla.org/de/docs/Web/CSS/z-index


问:
Bootstrap - is it possible to resize an image based on the column size?
I am creating a picture gallery using Bootstrap. At full screen, it looks good

At minimum size, it looks good

But while re-sizing, it does this

I would like the first image (the trees) to be as wide as the second image (the lake), and I've tried adjusting width/max-width, but the problem is the image doesn't scale back down when the second image is ready to be in-line with the first image.

Is it possible to have an image be a certain width when it's col-sm-#, and a different width when it sets to col-md-#?

答:
Consider setting both as background image covers on the divs. This will allow you to resize the divs while retaining the proper aspect ratios of the images.</p>

```<code>.yourdiv1{
  background: url(images/yourimage.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

.yourdiv2{
  background: url(images/yourotherimage.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
</code>```

Body:
Consider setting both as background image covers on the divs. This will allow you to resize the divs while retaining the proper aspect ratios of the images.

.yourdiv1{
  background: url(images/yourimage.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

.yourdiv2{
  background: url(images/yourotherimage.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}


问:
MongoDB: Unique Key in Embedded Document
Is it possible to set a unique key for a key in an embedded document?

I have a Users collection with the following sample documents:

```<code> {
       Name: "Bob",
       Items: [
           {
               Name: "Milk"
           },
           {
               Name: "Bread"
           }
       ]
    },
    {
       Name: "Jim"
    },
</code>```

Is there a way to create an index on the property Items.Name?

I got the following error when I tried to create an index:

```<code>> db.Users.ensureIndex({"Items.Name": 1}, {unique:true});
E11000 duplicate key error index: GroceryGuruApp.Users.$Items.Name_1  dup key: {
 : null }
</code>```

Any suggestions? Thank you!

答:
An alternative would be to model the items as a hash with the item name as the key.

```<code>Items: { "Milk": 1, "Bread": 1 }
</code>```

I'm not sure about whether you're trying to use the index for performance or purely for the constraint. The right way to approach depends on your use cases, and determining whether the atomic operations are enough to keep your data consistent.

Body:
Is it possible to set a unique key for a key in an embedded document?

I have a Users collection with the following sample documents:

 {
       Name: "Bob",
       Items: [
           {
               Name: "Milk"
           },
           {
               Name: "Bread"
           }
       ]
    },
    {
       Name: "Jim"
    },

Is there a way to create an index on the property Items.Name?

I got the following error when I tried to create an index:

> db.Users.ensureIndex({"Items.Name": 1}, {unique:true});
E11000 duplicate key error index: GroceryGuruApp.Users.$Items.Name_1  dup key: {
 : null }

Any suggestions? Thank you!

Body:
An alternative would be to model the items as a hash with the item name as the key.

Items: { "Milk": 1, "Bread": 1 }

I'm not sure about whether you're trying to use the index for performance or purely for the constraint. The right way to approach depends on your use cases, and determining whether the atomic operations are enough to keep your data consistent.


问:
Which Package or assembly had ISession?
I used this series to work on CQRS/ES with ASP.NET:

https://www.exceptionnotfound.net/real-world-cqrs-es-with-asp-net-and-redis-part-2-the-write-model/

My problem is somewhere in the code it uses ISession,that I don't know what assembly/package has it. Bases on document I need to install CQRSLite but when I try to install it I get an error.

```<code>private readonly ISession _session;
</code>```

This is the error I am getting:

```<code>Could not install package 'CqrsLite 0.12.9'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
</code>```

I am using Visual studio 2015 and .net 4.5.

答:
There's probably a smarter way, but I right-click on the class name in the editor and select "Go to definition."

It disassembles the class and at the top shows the name of the assembly and where it's referenced. If it's a Nuget package that's going to give you the name of the package.

```<code>#region Assembly EPPlus, Version=4.1.0.0, Culture=neutral, PublicKeyToken=ea159fdaa78159a1
// C:\.. etc... etc...\packages\EPPlus.4.1.0\lib\net40\EPPlus.dll
//                     ^^^^^^^^^^^^^^^^^^^^
#endregion
</code>```

Title: Which Package or assembly had ISession?

Body:
I used this series to work on CQRS/ES with ASP.NET:

https://www.exceptionnotfound.net/real-world-cqrs-es-with-asp-net-and-redis-part-2-the-write-model/

My problem is somewhere in the code it uses ISession,that I don't know what assembly/package has it. Bases on document I need to install CQRSLite but when I try to install it I get an error.

private readonly ISession _session;

This is the error I am getting:

Could not install package 'CqrsLite 0.12.9'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

I am using Visual studio 2015 and .net 4.5.

Body:
There's probably a smarter way, but I right-click on the class name in the editor and select "Go to definition."

It disassembles the class and at the top shows the name of the assembly and where it's referenced. If it's a Nuget package that's going to give you the name of the package.

#region Assembly EPPlus, Version=4.1.0.0, Culture=neutral, PublicKeyToken=ea159fdaa78159a1
// C:\.. etc... etc...\packages\EPPlus.4.1.0\lib\net40\EPPlus.dll
//                     ^^^^^^^^^^^^^^^^^^^^
#endregion


问:
Extra space inserted on new pages when creating PDFs with iTextSharp
I'm using iTextSharp 5.0.5 to create dynamic PDFs (asp.net c#), and I'm having problems with an extra space being inserted when creating a new page. The first page looks fine but on any additional pages the extra space appears at the top.

I've made a mini example that inserts a new page with a logo and a title for each article in a list. If I only insert the logo or only the title it works fine, but if I try to insert both there's an extra space coming from somewhere. Anyone got any ideas of what I'm doing wrong?

```<code>public static void CreatePDF(List<Item> Articles)
{
    Document document = new Document(PageSize.A4, 35, 35, 35, 35);
    MemoryStream memoryStream = new MemoryStream();
    PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);

    document.Open();

    for (int i = 0; i < Articles.Count; i++)
    {
        if (i > 0)
        {
            document.NewPage();
        }

        Image logo = Image.GetInstance(@"C:\logo.gif");
        document.Add(logo);

        Paragraph title = new Paragraph("test title", new Font(Font.FontFamily.HELVETICA, 20, Font.NORMAL, CMYKColor.BLACK));
        document.Add(title);
    }

    document.Close();

    SendPDFResponse(memoryStream, "myfile.pdf");
}
</code>```

Thanks,

Annelie

答:
There's no extra space on the pages that follow page 1. The problem is that there's less space on page 1.
No, this is not a joke. The problem is caused by the "leading" (that is: the space between two lines). The initial value for the leading is 0. When you add content to a document, this value changes to a value different from 0.

What is the leading you're using throughout the document? You should set this as the initial leading with the method setInitialLeading() in PdfWriter.

Body:
I'm using iTextSharp 5.0.5 to create dynamic PDFs (asp.net c#), and I'm having problems with an extra space being inserted when creating a new page. The first page looks fine but on any additional pages the extra space appears at the top.

I've made a mini example that inserts a new page with a logo and a title for each article in a list. If I only insert the logo or only the title it works fine, but if I try to insert both there's an extra space coming from somewhere. Anyone got any ideas of what I'm doing wrong?

public static void CreatePDF(List<Item> Articles)
{
    Document document = new Document(PageSize.A4, 35, 35, 35, 35);
    MemoryStream memoryStream = new MemoryStream();
    PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);

    document.Open();

    for (int i = 0; i < Articles.Count; i++)
    {
        if (i > 0)
        {
            document.NewPage();
        }

        Image logo = Image.GetInstance(@"C:\logo.gif");
        document.Add(logo);

        Paragraph title = new Paragraph("test title", new Font(Font.FontFamily.HELVETICA, 20, Font.NORMAL, CMYKColor.BLACK));
        document.Add(title);
    }

    document.Close();

    SendPDFResponse(memoryStream, "myfile.pdf");
}

Thanks,

Annelie


问:
AJAX and PHP has problems
I'm pretty new to coding so sorry if this is a dumb question.  I'm wondering if I'm doing something wrong or if there's possibly a better way to troubleshoot my problem.  I'm using AJAX to submit information to a php handler and then basically replace the data on my page with updated info so that the page doesn't have to refresh everytime.

This is my AJAX code.

```<code><script>
     $(document).ready(function(){
         $("#start<?php echo $rowCount; ?>").click(function(){
                        $("#displayJobs").load("assemblyStartHandlerCopy.php", {
                            jobID: <?php echo $jobID; ?>,
                            roomID: <?php echo $roomID; ?>,
                            finishColor: '<?php echo $finishColor; ?>',
                            startTime: '<?php echo $assemblyS; ?>'
                        });
                        $("#displayJobsNotStarted").load("assemblyNotStartedCount.php");
                    });
                });
</script>
</code>```

And my PHP code is

```<code><?php include "../../../includes/db.php"; ?>
<?php
    $startBtnColor = "";
    $completeBtnColor = "";
    $onQlistStatus = "On Q-List";
?>

<!--IF START BUTTON UPDATE DATA-->
<?php
date_default_timezone_set("America/Denver");
if(isset($_POST['jobID'])) {
    $jobID = $_POST['jobID'];
    $roomID = $_POST['roomID'];
    $finishColor = $_POST['finishColor'];
    $startTime = $_POST['startTime'];
    $start = date("Y-m-d H:i:s");

    if($startTime == NULL || $startTime == 0) {
        $startTime = $start;
    }
    elseif($startTime != NULL || $startTime == 0) {
        $startTime = 0;
    };

$querySetStart = "UPDATE rooms SET assemblyS = '$startTime' WHERE jobID = $jobID AND finishColor = '$finishColor'";
$resultSetStart = mysqli_query($connect, $querySetStart);

if(!$resultSetStart) {
    echo "Start Button Failed " . mysqli_error($connect);
};
?>

<!--GET AND DISPLAY JOBS-->
    <table>
            <tr>
                <th class="rowStart">Start</th>
                <th class="rowJobName">Job Name</th>
                <th class="rowWoodType">Wood Type</th>
                <th class="rowFinishColor">Finish Color</th>
                <th class="rowComplete">Complete</th>
            </tr>
<?php
    $query = "SELECT
        jobs.jobID,
        jobs.jobName,
        rooms.roomID,
        rooms.roomName,
        rooms.assemblyS,
        rooms.assemblyF,
        rooms.assemblyNeeded,
        rooms.woodType,
        rooms.finishType,
        rooms.finishColor
        FROM jobs
        LEFT JOIN rooms
        ON jobs.jobID = rooms.jobID
        WHERE rooms.assemblyNeeded = 1 AND jobs.status = '$onQlistStatus' AND rooms.assemblyF IS NULL
        OR rooms.assemblyNeeded = 1 AND jobs.status = '$onQlistStatus' AND rooms.assemblyF = 0
        GROUP BY jobs.jobName, rooms.finishColor
        ORDER BY deliveryDate, jobName, finishColor LIMIT 100";

    $result = mysqli_query($connect, $query);

    $x = 1;
    $rowCount = 1;

    if ($result) {
    while($row = mysqli_fetch_assoc($result)) {
        $jobID = $row['jobID'];
        $jobName = $row['jobName'];
        $woodType = $row['woodType'];
        $finishColor = $row['finishColor'];
        $roomID = $row['roomID'];
        $assemblyS = $row['assemblyS'];
        $assemblyF = $row['assemblyF'];
//SET BUTTON BACKGROUND COLOR
        if ($assemblyS != NULL) {
            $startBtnColor = "green";
        };
        if ($assemblyS == NULL || $assemblyS == 0) {
            $startBtnColor = "white";
        };
//ALTERNATE ROW COLOR
        $x++;
        if ($x%2 == 0) {
            $class1 = "backgroundColor1";
        }
        else {
            $class1 = "backgroundColor2";
        };
//DISPLAY ROW INFORMATION
        $start = "<td class='rowStart'><button id='start$rowCount' style='background-color: $startBtnColor'>Start</button></td>";
        ?>
            <script>
                $(document).ready(function(){
                    $("#start<?php echo $rowCount; ?>").click(function(){
                        $("#displayJobs").load("assemblyStartHandlerCopy.php", {
                            jobID: <?php echo $jobID; ?>,
                            roomID: <?php echo $roomID; ?>,
                            finishColor: '<?php echo $finishColor; ?>',
                            startTime: '<?php echo $assemblyS; ?>'
                        });
                        $("#displayJobsNotStarted").load("assemblyNotStartedCount.php");
                    });
                });
            </script>
        <?php
        $jobName = "<td class='$class1 rowJobName'>$jobName</td>";
        $woodType = "<td class='$class1 rowWoodType'>$woodType</td>";
        $finishColorRow = "<td class='$class1 rowFinishColor'>$finishColor</td>";

        $complete = "<td class='rowComplete'><button id='complete$rowCount' style='background-color: $completeBtnColor'>Complete</button></td>";
            ?>
            <script>
                $(document).ready(function() {
                    $("#complete<?php echo $rowCount; ?>").click(function() {
                        $("#displayJobs").load("assemblyCompleteHandlerCopy.php", {
                            jobID: <?php echo $jobID; ?>,
                            roomID: <?php echo $roomID; ?>,
                            finishColor: '<?php echo $finishColor; ?>',
                            completeTime: '<?php echo $assemblyS; ?>'
                        }, function(responseTxt, statusTxt, xhr) {
                            if(statusTxt == "success") {
                            //DO NOTHING
                            };
                            if(statusTxt == "error") {
                                alert("Error: " + xhr.status + ": " + xhr.statusText);
                            };
                        });

                    $("#displayJobsNotStarted").load("assemblyNotStartedCount.php");
                    $("#recentlyCompleted").load("assemblyRecentlyCompletedHandler.php", {
                        complete: 1
                    }, function(responseTxt, statusTxt, xhr) {
                            if(statusTxt == "success") {
                            //DO NOTHING
                            };
                            if(statusTxt == "error") {
                                alert("Error: " + xhr.status + ": " + xhr.statusText);
                            };
                        });
                    });
                });
            </script>
            <?php
        echo "<tr>" . $start . $jobName . $woodType . $finishColorRow . $complete . "</tr>";
        $rowCount++;
    };
    };
?>
            </table>
<?php
}
?>
</code>```

I know it's pretty messy.  Basically all the information is being pulled into a table and echoing the rows out through a while loop.  Then if I select a button associated with a "job" or "row" it 1st marks a start time, 2nd changes the color, and 3rd gives me a new count.
Is there a better way to do this or a way to make sure my code won't fire unless it's a success.

The weird thing to me is that my code is duplicated in the PHP handler.  If I refresh the page everything is displayed correctly every time with no problems.

答:
Well there are a lot of things that you can improve in this code.

First, you should not write values from PHP to JavaScript directly, you should store them in variables and have separate file for JavaScript and use those variables instead.

Second, you should escape values before writing them to database to avoid possible SQL injections, using addslashes method.

What you are doing right now is writing all the code in one single file that's making code hard to understand. Organize your code and divide it in manageable chunks using methods/functions and have separate files where required.

Title: AJAX and PHP has problems

Body:
I'm pretty new to coding so sorry if this is a dumb question.  I'm wondering if I'm doing something wrong or if there's possibly a better way to troubleshoot my problem.  I'm using AJAX to submit information to a php handler and then basically replace the data on my page with updated info so that the page doesn't have to refresh everytime.

This is my AJAX code.

And my PHP code is

<?php include "../../../includes/db.php"; ?>
<?php
    $startBtnColor = "";
    $completeBtnColor = "";
    $onQlistStatus = "On Q-List";
?>

<?php
date_default_timezone_set("America/Denver");
if(isset($_POST['jobID'])) {
    $jobID = $_POST['jobID'];
    $roomID = $_POST['roomID'];
    $finishColor = $_POST['finishColor'];
    $startTime = $_POST['startTime'];
    $start = date("Y-m-d H:i:s");

    if($startTime == NULL || $startTime == 0) {
        $startTime = $start;
    }
    elseif($startTime != NULL || $startTime == 0) {
        $startTime = 0;
    };

$querySetStart = "UPDATE rooms SET assemblyS = '$startTime' WHERE jobID = $jobID AND finishColor = '$finishColor'";
$resultSetStart = mysqli_query($connect, $querySetStart);

if(!$resultSetStart) {
    echo "Start Button Failed " . mysqli_error($connect);
};
?>

                Start
                Job Name
                Wood Type
                Finish Color
                Complete

<?php
    $query = "SELECT
        jobs.jobID,
        jobs.jobName,
        rooms.roomID,
        rooms.roomName,
        rooms.assemblyS,
        rooms.assemblyF,
        rooms.assemblyNeeded,
        rooms.woodType,
        rooms.finishType,
        rooms.finishColor
        FROM jobs
        LEFT JOIN rooms
        ON jobs.jobID = rooms.jobID
        WHERE rooms.assemblyNeeded = 1 AND jobs.status = '$onQlistStatus' AND rooms.assemblyF IS NULL
        OR rooms.assemblyNeeded = 1 AND jobs.status = '$onQlistStatus' AND rooms.assemblyF = 0
        GROUP BY jobs.jobName, rooms.finishColor
        ORDER BY deliveryDate, jobName, finishColor LIMIT 100";

    $result = mysqli_query($connect, $query);

    $x = 1;
    $rowCount = 1;

    if ($result) {
    while($row = mysqli_fetch_assoc($result)) {
        $jobID = $row['jobID'];
        $jobName = $row['jobName'];
        $woodType = $row['woodType'];
        $finishColor = $row['finishColor'];
        $roomID = $row['roomID'];
        $assemblyS = $row['assemblyS'];
        $assemblyF = $row['assemblyF'];
//SET BUTTON BACKGROUND COLOR
        if ($assemblyS != NULL) {
            $startBtnColor = "green";
        };
        if ($assemblyS == NULL || $assemblyS == 0) {
            $startBtnColor = "white";
        };
//ALTERNATE ROW COLOR
        $x++;
        if ($x%2 == 0) {
            $class1 = "backgroundColor1";
        }
        else {
            $class1 = "backgroundColor2";
        };
//DISPLAY ROW INFORMATION
        $start = "<button id='start$rowCount' style='background-color: $startBtnColor'>Start</button>	";
        ?>

        <?php
        $jobName = "$jobName	";
        $woodType = "$woodType	";
        $finishColorRow = "$finishColor	";

        $complete = "<button id='complete$rowCount' style='background-color: $completeBtnColor'>Complete</button>	";
            ?>

            <?php
        echo "
" . $start . $jobName . $woodType . $finishColorRow . $complete . "
";
        $rowCount++;
    };
    };
?>

<?php
}
?>

I know it's pretty messy.  Basically all the information is being pulled into a table and echoing the rows out through a while loop.  Then if I select a button associated with a "job" or "row" it 1st marks a start time, 2nd changes the color, and 3rd gives me a new count.
Is there a better way to do this or a way to make sure my code won't fire unless it's a success.

The weird thing to me is that my code is duplicated in the PHP handler.  If I refresh the page everything is displayed correctly every time with no problems.


问:
SQL Server 2012 ACE.OLEDB.12.0 from CSV
I'm trying to use next code to import data from CSV file:

```<code> select * FROM OPENROWSET(
    'Microsoft.ACE.OLEDB.12.0',
    'Text;Database=C:\Users\Evgeny\Desktop;HDR=Yes;FORMAT=Delimited(;)',
    'SELECT * FROM [test.csv]'
);
</code>```

And my data have next structure, where 1st string has column names:

```<code>"Name1";"Name2";"Name3"
"Value1";"Value2";"Value3"
</code>```

But after the query is executed, the result is only one column, like this:

```<code>Name1
Value1
</code>```

What can be a problem?
How can I solve it not usung other drivers, becouse on my job place I can't do that.

答:
Try using OPENROWSET with BULK

```<code>SELECT * FROM OPENROWSET(
BULK 'FILE.csv',
SINGLE_CLOB) AS DATA;
</code>```

Or use Microsoft Text Driver:

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/5869d247-f0a0-4224-80b3-ff2e414be402/how-to-read-csv-file-in-sql-server-2005-using-openrowset-function?forum=sqldataaccess

You can also follow my answer at Import error using Openrowset it may helps you

Title: SQL Server 2012 ACE.OLEDB.12.0 from CSV

Body:
I'm trying to use next code to import data from CSV file:

 select * FROM OPENROWSET(
    'Microsoft.ACE.OLEDB.12.0',
    'Text;Database=C:\Users\Evgeny\Desktop;HDR=Yes;FORMAT=Delimited(;)',
    'SELECT * FROM [test.csv]'
);

And my data have next structure, where 1st string has column names:

"Name1";"Name2";"Name3"
"Value1";"Value2";"Value3"

But after the query is executed, the result is only one column, like this:

Name1
Value1

What can be a problem?
How can I solve it not usung other drivers, becouse on my job place I can't do that.

Body:
Try using OPENROWSET with BULK

SELECT * FROM OPENROWSET(
BULK 'FILE.csv',
SINGLE_CLOB) AS DATA;

Or use Microsoft Text Driver:

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/5869d247-f0a0-4224-80b3-ff2e414be402/how-to-read-csv-file-in-sql-server-2005-using-openrowset-function?forum=sqldataaccess

You can also follow my answer at Import error using Openrowset it may helps you


问:
WSO2 Identity Server User Registration validation using OTP
I need to implement user verification using email containing OTP(Randomly generated 4 digit number) for newly registered user accounts in WSO2 Identity Server but I could not find such functionality. Is there any feature in the repository that might help me?</p>

答: You can follows the https://docs.wso2.com/display/ISCONNECTORS/Configuring+EmailOTP+Authenticator it describes the steps that you need to follow</p>


问:
why doesn't my interpolated html display properly in vue.js?
The data in my app.js file is not being interpolated and displayed on the screen. I tried the older v-repeat. Could it be some missing items in the installation? Any help would be appreciated.

Here is my html

```<code><!-- show the events -->
<div class="col-sm-6">
  <div class="list-group">
      <a href="#" class="list-group-item" v-for="event in events">
        <!-- <h1>{{text}}</h1> -->
        <h4 class="list-group-item-heading">
          <i class="glyphicon glyphicon-bullhorn"></i>
          {{ event.name }}
        </h4>

        <h5>
          <i class="glyphicon glyphicon-calendar" v-if="event.date"></i>
          {{ event.date }}
        </h5>

        <p class="list-group-item-text" v-if="event.description">{{ event.description }}</p>

        <button class="btn btn-xs btn-danger" v-on="click: deleteEvent($index)">Delete</button>
      </a>
  </div>
</div>
</code>```

And here is my js file

```<code>new Vue({

data: {
    text: 'hello world',
  event: { name: '', description: '', date: '' },
  events: []
},

// Anything within the ready function will run when the application loads
ready: function() {
  // When the application loads, we want to call the method that initializes
  // some data
  this.fetchEvents();
},

// Methods we want to use in our application are registered here
methods: {

  // We dedicate a method to retrieving and setting some data
  fetchEvents: function() {
    var events = [
      {
        id: 1,
        name: 'TIFF',
        description: 'Toronto International Film Festival',
        date: '2015-09-10'
      },
      {
        id: 2,
        name: 'The Martian Premiere',
        description: 'The Martian comes to theatres.',
        date: '2015-10-02'
      },
      {
        id: 3,
        name: 'SXSW',
        description: 'Music, film and interactive festival in Austin, TX.',
        date: '2016-03-11'
      }
    ];
    // $set is a convenience method provided by Vue that is similar to pushing
    // data onto an array
    this.$set('events', events);
  },

  // Adds an event to the existing events array
  addEvent: function() {
    if(this.event.name) {
      this.events.push(this.event);
      this.event = { name: '', description: '', date: '' };
    }
  }
}
});
</code>```

Thanks for any help.

答:
So, there are a few issues here. I've cleaned them up for you to look over.

Added the el: "#app" property to tell Vue where to mount your Vue.

Changed your ready to mounted (you could also use created).

Changed this.$set('events',events) to this.events = events.

Added the unreferenced deleteEvent method.

Fixed the click handler syntax for v-on:click.

So the code ends up looking like this.

```<code>new Vue({
  el: "#app",
  data: {
    text: 'hello world',
    event: { name: '', description: '', date: '' },
    events: []
  },
  mounted: function() {
      this.fetchEvents();
  },
  // Methods we want to use in our application are registered here
  methods: {

    // We dedicate a method to retrieving and setting some data
    fetchEvents: function() {
      var events = [...];
      this.events = events;
    },

    // Adds an event to the existing events array
    addEvent: function() {
      if(this.event.name) {
        this.events.push(this.event);
        this.event = { name: '', description: '', date: '' };
      }
    },
    deleteEvent(){
      alert('delete this one')
    }
  }
});
</code>```

Template

```<code><div id="app">
  <!-- show the events -->
  <div class="col-sm-6">
    <div class="list-group">
      <a href="#" class="list-group-item" v-for="event in events">
        <!-- <h1>{{text}}</h1> -->
        <h4 class="list-group-item-heading">
          <i class="glyphicon glyphicon-bullhorn"></i>
          {{ event.name }}
        </h4>

        <h5>
          <i class="glyphicon glyphicon-calendar" v-if="event.date"></i>
          {{ event.date }}
        </h5>

        <p class="list-group-item-text" v-if="event.description">{{ event.description }}</p>

        <button class="btn btn-xs btn-danger" v-on:click=" deleteEvent(event)">Delete</button>
      </a>
    </div>
  </div>
</div>
</code>```

Working example.

Body:
The data in my app.js file is not being interpolated and displayed on the screen. I tried the older v-repeat. Could it be some missing items in the installation? Any help would be appreciated.

Here is my html

          {{ event.name }}

          {{ event.date }}

{{ event.description }}

        <button class="btn btn-xs btn-danger" v-on="click: deleteEvent($index)">Delete</button>

And here is my js file

new Vue({

data: {
    text: 'hello world',
  event: { name: '', description: '', date: '' },
  events: []
},

// Anything within the ready function will run when the application loads
ready: function() {
  // When the application loads, we want to call the method that initializes
  // some data
  this.fetchEvents();
},

// Methods we want to use in our application are registered here
methods: {

  // We dedicate a method to retrieving and setting some data
  fetchEvents: function() {
    var events = [
      {
        id: 1,
        name: 'TIFF',
        description: 'Toronto International Film Festival',
        date: '2015-09-10'
      },
      {
        id: 2,
        name: 'The Martian Premiere',
        description: 'The Martian comes to theatres.',
        date: '2015-10-02'
      },
      {
        id: 3,
        name: 'SXSW',
        description: 'Music, film and interactive festival in Austin, TX.',
        date: '2016-03-11'
      }
    ];
    // $set is a convenience method provided by Vue that is similar to pushing
    // data onto an array
    this.$set('events', events);
  },

  // Adds an event to the existing events array
  addEvent: function() {
    if(this.event.name) {
      this.events.push(this.event);
      this.event = { name: '', description: '', date: '' };
    }
  }
}
});

Thanks for any help.

Body:
So, there are a few issues here. I've cleaned them up for you to look over.

Added the el: "#app" property to tell Vue where to mount your Vue.

Changed your ready to mounted (you could also use created).

Changed this.$set('events',events) to this.events = events.

Added the unreferenced deleteEvent method.

Fixed the click handler syntax for v-on:click.

So the code ends up looking like this.

new Vue({
  el: "#app",
  data: {
    text: 'hello world',
    event: { name: '', description: '', date: '' },
    events: []
  },
  mounted: function() {
      this.fetchEvents();
  },
  // Methods we want to use in our application are registered here
  methods: {

    // We dedicate a method to retrieving and setting some data
    fetchEvents: function() {
      var events = [...];
      this.events = events;
    },

    // Adds an event to the existing events array
    addEvent: function() {
      if(this.event.name) {
        this.events.push(this.event);
        this.event = { name: '', description: '', date: '' };
      }
    },
    deleteEvent(){
      alert('delete this one')
    }
  }
});

Template

<div id="app">
  <!-- show the events -->
  <div class="col-sm-6">
    <div class="list-group">
      <a href="#" class="list-group-item" v-for="event in events">
        <!-- <h1>{{text}}</h1> -->
        <h4 class="list-group-item-heading">
          <i class="glyphicon glyphicon-bullhorn"></i>
          {{ event.name }}
        </h4>

        <h5>
          <i class="glyphicon glyphicon-calendar" v-if="event.date"></i>
          {{ event.date }}
        </h5>

        <p class="list-group-item-text" v-if="event.description">{{ event.description }}</p>

        <button class="btn btn-xs btn-danger" v-on:click=" deleteEvent(event)">Delete</button>
      </a>
    </div>
  </div>
</div>

Working example.


问:
Timeout when importing an excel file into database
I'm trying to import excel files to my MySQL database on Laravel 5.4 with the PHPExcel-based Maatwebsite/laravel-excel library.

The files I need to import are pretty big: at least 50k rows with 100 columns, and I need to create a database entry for each row.

I thought I may have some problems with the import process, so I started out with using chunks, however even at 1 chunks I get the following error message:

Maximum execution time of 180 seconds exceeded.

I tried to increase the max_execution_time variable and memory limit, but I still can't seem to go through with the import.

This is the code I'm using:

```<code>Excel::filter('chunk')->load($request->file('source_file')->getRealPath())->chunk(1,function ($results) {
    foreach($results as $row) {
        TaskMeta::create([
         'task_id' => $row['task_id'],
         'col2' => $row['column2'],
         ... etc, rest of the 100 columns ommited for clarity
        ]);
    }
});
</code>```

I'm testing this locally in my Homestead environment by the way. I need a solution that would work on a production server as well.

答:
If you want to disable the timeout just for this script use:

```<code>set_time_limit(0)
</code>```

...and monitor your processes to make sure it's not hanging. Maybe even put it into a Command and use $this->info() to output the row number for every iteration so you know where it's at in the file.

This way you override any .ini config that may be holding you back :)

http://php.net/manual/en/function.set-time-limit.php

Body:
I'm trying to import excel files to my MySQL database on Laravel 5.4 with the PHPExcel-based Maatwebsite/laravel-excel library.

The files I need to import are pretty big: at least 50k rows with 100 columns, and I need to create a database entry for each row.

I thought I may have some problems with the import process, so I started out with using chunks, however even at 1 chunks I get the following error message:

Maximum execution time of 180 seconds exceeded.

I tried to increase the max_execution_time variable and memory limit, but I still can't seem to go through with the import.

This is the code I'm using:

Excel::filter('chunk')->load($request->file('source_file')->getRealPath())->chunk(1,function ($results) {
    foreach($results as $row) {
        TaskMeta::create([
         'task_id' => $row['task_id'],
         'col2' => $row['column2'],
         ... etc, rest of the 100 columns ommited for clarity
        ]);
    }
});

I'm testing this locally in my Homestead environment by the way. I need a solution that would work on a production server as well.

Body:
If you want to disable the timeout just for this script use:

set_time_limit(0)

...and monitor your processes to make sure it's not hanging. Maybe even put it into a Command and use $this->info() to output the row number for every iteration so you know where it's at in the file.

This way you override any .ini config that may be holding you back :)

http://php.net/manual/en/function.set-time-limit.php


问:
How do you use srgbClr in openpyxl ColorChoices
How can I use colors that are not represented by the colornames like RGB.
Sorry, I don't understand the documents but there are no examples. Here is my code:</p>

```<code>series4Total = chart1.series[3]
fill4Total =  PatternFillProperties(prst="pct5")
fill4Total.foreground = ColorChoice(srgbClr='30,144,255') # dodgerBlue: R:30 G: 144 B: 255
fill4Total.background = ColorChoice(srgbClr='30,144,255')
series4Total.graphicalProperties.pattFill = fill4Total
</code>```

答:
srgbClr needs a HEX value
So try this:</p>

```<code>ColorChoice(srgbClr='1E90FF') # for dodgerBlue: R:30 G: 144 B: 255
</code>```

Body:
How can I use colors that are not represented by the colornames like RGB.
Sorry, I don't understand the documents but there are no examples. Here is my code:

series4Total = chart1.series[3]
fill4Total =  PatternFillProperties(prst="pct5")
fill4Total.foreground = ColorChoice(srgbClr='30,144,255') # dodgerBlue: R:30 G: 144 B: 255
fill4Total.background = ColorChoice(srgbClr='30,144,255')
series4Total.graphicalProperties.pattFill = fill4Total

Body:
srgbClr needs a HEX value
So try this:

ColorChoice(srgbClr='1E90FF') # for dodgerBlue: R:30 G: 144 B: 255


问:
Is there a jQuery Click method?
I'm trying to click on a link using jquery. There only appears to be a click event that replicates "onclick" (i.e user input). Is it possible to use jquery to actually click a link?</p>

答:
```<code>$("table:first").find("tr:first").find("td:first").find("a:first")[0].click();
</code>```

This will work in Internet Explorer if thats your only target, otherwise you're stucked with the document.location solution.

OwnerDisplayName: Jeff Banks

Title: Is there a jQuery Click method?

Body:
$("table:first").find("tr:first").find("td:first").find("a:first")[0].click();

This will work in Internet Explorer if thats your only target, otherwise you're stucked with the document.location solution.

OwnerDisplayName: bang


问:
SVG support on smart-phone browsers
I am investigating SVG, so I was wondering if anyone knows how good SVG support is for browsers on smart-phones. I know Opera Mini/iPhone support a lot of SVG Tiny, but I cannot figure out the support for other browsers (Blackberry, Pre, Android, Nokia smart-phones). I know phones using IE as rendering engine will have no support at all.

I have tried to find latest data, but cannot find anything later than 2007. I would appreciate if anyone can link to a post that discusses SVG support on mobile browsers.

答:
Currently some people including me work on it independently.

You may find working solution in these articles:

  Android. ImageView with SVG Support.

  Android ImageView and Drawable with SVG support

Title: SVG support on smart-phone browsers


答:
I am not sure if direct all-Pandas conversion is possible, but you can do it step by step. First, collect all records pertaining to the same member, and convert each group to JSON:

```<code>u = df.groupby('member')\
    .apply(lambda x:x[['date','size']].to_json(orient='records'))
</code>```

Then, combine the results into a JSON array:

```<code>result = '[' + ','.join(u) + ']'
#'''[
#    [{"date":"2017-02-02","size":220}],
#    [{"date":"2016-08-25","size":25560},{"date":"2016-09-08","size":1051753},
#     {"date":"2017-01-25","size":1312},{"date":"2017-05-13","size":1174405}],
#    [{"date":"2017-01-25","size":74971},{"date":"2017-05-28","size":4016046}]
#]'''
</code>```

Title: Python pandas to_json format of indexes

Body:
I have a pandas dataframe like this

        date       size       member
0   2016-08-25     25560      Jason
1   2016-09-08   1051753      Jason
2   2017-01-25      1312      Jason
3   2017-01-25     74971      Peter
4   2017-02-02       220      George
....
100 2017-05-13   1174405       Jason
101 2017-05-28   4016046       Peter

And I can use to_json() to produce a json array

with open('members.json', 'w') as f:
    f.write(data.to_json(orient='records', lines=False))

[
{"date":"2016-08-25","size":25560,"member":"Jason"},
{"date":"2016-09-08","size":1051753,"member":"Jason"},
{"date":"2017-01-25","size":1312,"member":"Jason"},
{"date":"2017-01-25","size":74971,"member":"Peter"},
{"date":"2017-02-02","size":220,"member":"George"},
...
{"date":"2017-05-13","size":1174405,"member":"Jason"},
{"date":"2017-05-28","size":4016046,"member":"Peter"}
]

However, how could I end up with something like this:

[ // Jason
 [
  {"date":"2016-08-25","size":25560},
  {"date":"2016-09-08","size":1051753},
  {"date":"2017-01-25","size":1312},
   ...
  {"data":"2017-05-13", "size":1174405}
 ],

 [ // Peter
  {"date":"2017-01-25","size":74971},
  {"date":"2017-05-28","size":4016046}
 ],

 [ // George
  {"date":"2017-02-02","size":220}
 ],
   ...
]

Any help, is very much appreciated. Thanks.

Body:
I am not sure if direct all-Pandas conversion is possible, but you can do it step by step. First, collect all records pertaining to the same member, and convert each group to JSON:

u = df.groupby('member')\
    .apply(lambda x:x[['date','size']].to_json(orient='records'))

Then, combine the results into a JSON array:

result = '[' + ','.join(u) + ']'
#'''[
#    [{"date":"2017-02-02","size":220}],
#    [{"date":"2016-08-25","size":25560},{"date":"2016-09-08","size":1051753},
#     {"date":"2017-01-25","size":1312},{"date":"2017-05-13","size":1174405}],
#    [{"date":"2017-01-25","size":74971},{"date":"2017-05-28","size":4016046}]
#]'''


问:
Using Date as an index in IndexedDb and sorting with it
I'm currently using a guid as a keypath in my object store.

I'd like to add an index - created - that I can then use to get the newest entry.  I have added the index:

This is how I was originally attempting to get the newest entry (via getNewest) but it was not working as expected:

```<code>const latestMediaRequest = store.getAll();
latestMediaRequest.onsuccess = function (event) {
      const allData = event.target.result;
      const targetEntry = allData[allData.length - 1];  // nope
}
</code>```

This is how I'm currently adding entries (working):

```<code> const request = database.transaction(storeName, "readwrite")
                .objectStore(storeName)
                .add(dbEntry); // contains "created" timestamp
</code>```

And this is how I'm getting by guid (working):

```<code> const request = database.transaction(storeName, "readwrite")
                .objectStore(storeName)
                .get(mediaId);
</code>```

I have created the index here:

```<code>          request.onupgradeneeded = function (event) {
                const db = event.target.result;
                if (db.objectStoreNames.contains(storeName)) {
                    db.deleteObjectStore(storeName);
                }
                const objectStore = db.createObjectStore(storeName, { keyPath: keyPath });
                objectStore.createIndex("created", "created", { unique: false });
            };
</code>```

How can the getNewest snippet be modified to support fetching by order of a date index?  I'll be using this to recursively delete the oldest items - so I can't just store a single "lastAdded" entry.

答:
This did the trick: </p>

```<code>// "created"
const latestMediaRequest = store.index(dateIndex).openCursor();
latestMediaRequest.onsuccess = function (event) {
    const targetEntry = event.target.result.value;
}
</code>```

Body:
I'm currently using a guid as a keypath in my object store.

I'd like to add an index - created - that I can then use to get the newest entry.  I have added the index:

This is how I was originally attempting to get the newest entry (via getNewest) but it was not working as expected:

const latestMediaRequest = store.getAll();
latestMediaRequest.onsuccess = function (event) {
      const allData = event.target.result;
      const targetEntry = allData[allData.length - 1];  // nope
}

This is how I'm currently adding entries (working):

 const request = database.transaction(storeName, "readwrite")
                .objectStore(storeName)
                .add(dbEntry); // contains "created" timestamp

And this is how I'm getting by guid (working):

 const request = database.transaction(storeName, "readwrite")
                .objectStore(storeName)
                .get(mediaId);

I have created the index here:

          request.onupgradeneeded = function (event) {
                const db = event.target.result;
                if (db.objectStoreNames.contains(storeName)) {
                    db.deleteObjectStore(storeName);
                }
                const objectStore = db.createObjectStore(storeName, { keyPath: keyPath });
                objectStore.createIndex("created", "created", { unique: false });
            };

How can the getNewest snippet be modified to support fetching by order of a date index?  I'll be using this to recursively delete the oldest items - so I can't just store a single "lastAdded" entry.

Body:
This did the trick:

// "created"
const latestMediaRequest = store.index(dateIndex).openCursor();
latestMediaRequest.onsuccess = function (event) {
    const targetEntry = event.target.result.value;
}


问:
How can I create a hyperlink in the middle of cell text?
In google spreadsheets, it is possible to add a hyperlink to a cell as:

```<code> =hyperlink("www.google.com", "search the web")
</code>```

This will show the text search the web which will hyperlink to google.  However, I am wondering:

How can this rule be inserting into the middle of a cell?  In other words, I'd like a single cell to look like:

click here for answer

答:
EDIT (2020-Aug-06):
Google Sheets now supports this; see Aibol Kussain's answer.

Original answer:

As far as I can tell, Google Sheets [still] simply does not support what you are asking for. (I've looked around for it, too.)

See, e.g., https://docs.google.com/document/preview?hgd=1&id=1x_qjPL5rmSuQWW57KcwB9lg3eiykKpd8dMEaQUZbWU8, particularly where it says:

Please note: Like the other types of data and cell formatting, links in spreadsheets must be assigned to an entire cell, you cannot have just part of the text inside a cell be hyperlinked.

Also:

https://webapps.stackexchange.com/questions/24931/a-way-to-add-text-before-your-hyperlink-in-google-spreadsheets

https://webapps.stackexchange.com/questions/83073/is-it-possible-to-have-plain-text-and-a-link-in-the-same-cell

Body:
In google spreadsheets, it is possible to add a hyperlink to a cell as:

 =hyperlink("www.google.com", "search the web")

This will show the text search the web which will hyperlink to google.  However, I am wondering:

How can this rule be inserting into the middle of a cell?  In other words, I'd like a single cell to look like:

click here for answer


问:
Setting a relative path to sqlite database with Delphi and Firedac
In replacement of my previous question which was confusing and poorly formulated, here is the "real" question.

I would like to known how to set, with Firedac, at runtime, a relative path to a sqlite database located in a subfolder of my application folder.

As Jerry Dodge stated :

Any application should never rely on writable data in the same directory anyway. Also, even if you did, you should make sure all your paths are relative to the application at least.

At the moment, the application I have in mind is portable and I would like the database file to be stored in a sub-folder of the main exe folder.

On the Form.Create event of my main form, is used first

```<code>path := ExtractFilePath(Application.ExeName);
</code>```

And in then for FDConnection :

```<code>with FDConnection1 do begin
  Close;
  with Params do begin
    Clear;
    Add('DriverID=SQLite');
    Add('Database='+path+'Data\sqlite.db');
  end;
  Open;
end;
</code>```

I keep on getting an error saying "unable to open database file".

I don't want to set the path to the database file in the FiredDac Connection Editor because then it would be absolute and bound to my machine, right ?

How could I set this path to the database file so that it would work in any configuration, wherever the user puts the application folder ?

Thank you all in advance

Math

答:
As I found my own solution, I decided to post it here for future users who might encounter the same problem (that is to say a Delphi beginner level and the need to link a database file relative to their project exe file).

FIRST STEP was to add a data module to the project. This was done by going to File -> New -> Other -> Delphi Files -> Data Module

SECOND STEP Once the data module added to the project, as my main Application Form makes a call to the database on creation, I had to make sure the Data Module was created first. To achive that, I went to Project -> Options -> Forms and dragged the datamodule in first position of the list of auto created Forms

THIRD STEP was to drop a FDConnection on the datamodule and set all parameters EXCEPT database file.

FOURTH STEP was to add an OnCreate event to the datamodule, to specify the path to the database relative to the application exe and connect. It was done like this :

```<code>procedure TDataModule1.DataModuleCreate(Sender: TObject);
begin
  path := ExtractFilePath(ParamStr(0));

  FDConnection.Params.Add('Database='+path+'Database\sqlite.db');
  FDConnection.Connected := True;
end;
</code>```

FIFTH AND FINAL STEP was to add the datamodule to the uses clause of all other units that needed a connection to the database.

I realize that this solution is far from perfect and that, as very experienced users already stated, storing the database in the same folder (or a sub-folder) as the main application Exe is not a good solution.

Also, I decided to connect to the database on DataModule creation, but another solution could be to connect on demand before triggering the queries and then disconnect. That's up to you and your needs

Thanks to all for your help, tips and advises

Math

PS : please notice I did not check my answer as accepted as the best answer, would not be fair right :-)

Body:
In replacement of my previous question which was confusing and poorly formulated, here is the "real" question.

I would like to known how to set, with Firedac, at runtime, a relative path to a sqlite database located in a subfolder of my application folder.

As Jerry Dodge stated :

Any application should never rely on writable data in the same directory anyway. Also, even if you did, you should make sure all your paths are relative to the application at least.

At the moment, the application I have in mind is portable and I would like the database file to be stored in a sub-folder of the main exe folder.

On the Form.Create event of my main form, is used first

path := ExtractFilePath(Application.ExeName);

And in then for FDConnection :

with FDConnection1 do begin
  Close;
  with Params do begin
    Clear;
    Add('DriverID=SQLite');
    Add('Database='+path+'Data\sqlite.db');
  end;
  Open;
end;

I keep on getting an error saying "unable to open database file".

I don't want to set the path to the database file in the FiredDac Connection Editor because then it would be absolute and bound to my machine, right ?

How could I set this path to the database file so that it would work in any configuration, wherever the user puts the application folder ?

Thank you all in advance

Math

Body:
As I found my own solution, I decided to post it here for future users who might encounter the same problem (that is to say a Delphi beginner level and the need to link a database file relative to their project exe file).

FIRST STEP was to add a data module to the project. This was done by going to File -> New -> Other -> Delphi Files -> Data Module

SECOND STEP Once the data module added to the project, as my main Application Form makes a call to the database on creation, I had to make sure the Data Module was created first. To achive that, I went to Project -> Options -> Forms and dragged the datamodule in first position of the list of auto created Forms

THIRD STEP was to drop a FDConnection on the datamodule and set all parameters EXCEPT database file.

FOURTH STEP was to add an OnCreate event to the datamodule, to specify the path to the database relative to the application exe and connect. It was done like this :

procedure TDataModule1.DataModuleCreate(Sender: TObject);
begin
  path := ExtractFilePath(ParamStr(0));

  FDConnection.Params.Add('Database='+path+'Database\sqlite.db');
  FDConnection.Connected := True;
end;

FIFTH AND FINAL STEP was to add the datamodule to the uses clause of all other units that needed a connection to the database.

I realize that this solution is far from perfect and that, as very experienced users already stated, storing the database in the same folder (or a sub-folder) as the main application Exe is not a good solution.

Also, I decided to connect to the database on DataModule creation, but another solution could be to connect on demand before triggering the queries and then disconnect. That's up to you and your needs

Thanks to all for your help, tips and advises

Math

PS : please notice I did not check my answer as accepted as the best answer, would not be fair right :-)


问:
Stopping background javascript activity on location-triggered bluetooth-central iOS wakes
I'm using the Cordova Gimbal plugin to monitor bluetooth beacons in the background. iOS wakes up the app while in the background to send it bluetooth beacon sighting events; the Gimbal SDK processes these and calls a objc handler function in the plugin. I've removed any code that fires events on the window object in an attempt to prevent any javascript from running while in the 10-second execution window.

However, javascript executes anyway on these background events: my app uses Angular, and expensive $digest cycles continue in the background. $interval (wrapper for setInterval()) works too. It seems that while the app is running in the 10-second window, it just keeps on running the javascript engine as if it were in the foreground. This is significantly affecting battery usage for the app. How can I get the cordova event loop to just stop executing when it's done handling the beacon sighting?

versions: cordova 6.5.0 cordova-ios 4.3.1

答: I discovered that the javascript engine doesn't run opportunistically like this if we switch to using WKWebView. So, adding this plugin (and fixing the fallout from the switch) fixed the issue.</p>


问:
How to use logical indexing on multiple criteria
I have a table that has a column containing values between 1 and 20. I want to filter the table such that I can show only certain discrete values, i.e. 3, 10, 12, and 19. The problem is writing this is cumbersome, especially since I want to write other criteria for filtering too.:

```<code>i = tb.subn==3 | tb.subn==10 | tb.subn==12 | tb.subn==19
</code>```

If I use i = tb.subn==[3 10 12 19] then I get a :x4 boolean matrix. How can I get that into just one column?

If it were &, I suppose I could use prod(tb.subn==[3 10 12 19],2) but I can't figure out or.

Thanks.

答:
```<code>i = all(tb.subn==[3 10 12 19], 2);
</code>```

Note that this works only for very late matlab, while you solution will work better for all versions.

Body:
I have a table that has a column containing values between 1 and 20. I want to filter the table such that I can show only certain discrete values, i.e. 3, 10, 12, and 19. The problem is writing this is cumbersome, especially since I want to write other criteria for filtering too.:

i = tb.subn==3 | tb.subn==10 | tb.subn==12 | tb.subn==19

If I use i = tb.subn==[3 10 12 19] then I get a :x4 boolean matrix. How can I get that into just one column?

If it were &, I suppose I could use prod(tb.subn==[3 10 12 19],2) but I can't figure out or.

Thanks.

Body:
i = all(tb.subn==[3 10 12 19], 2);

Note that this works only for very late matlab, while you solution will work better for all versions.


问:
How to Add Advanced Custom Fields to a Product Variation
Add Advanced Custom Fields to WooCommerce Product Variation

Hello, we are having issues trying to add a unique ACF per each variable product.

Our product: "Product A - Variable Product." This product has 4 different variations, and we would like to add unique ACF depending on that product variation.

Within our custom fields tab I created a new custom field, field group, and label, I then selected; "Show this field group if post is equal to product_variation Product A - Variable Product." Doing so did NOT add the custom field to our products admin page. Previously we have used; "post type is equal to product" which works great, but can not be used in the variable product situation.

More background:
Currently, we are using ACF to aid in our WooCommerce Email customizer, and it is working great. The email is printing out ACF data in accordance to the product that is purchased (see code below).

```<code><?php
$product_idMe = $item->get_product_id();
$fields = get_field_objects($product_idMe);
if( $fields )
{
    foreach( $fields as $field_name => $field )
    {
            echo $field['label'];
            echo $field['value'];
    }
}
?>
</code>```

Goal: To add unique ACF to variable products, and print out the data into an email (like we are doing already doing, but now with the variable products unique ACF).

Please let me know if you need any clarification, a client of ours is trying to launch their website with this feature working.
-Thanks, Michael P.

答:
There seems not to be a solution with ACF.

But have a look at this discussion. It points you to a workaround: https://support.advancedcustomfields.com/forums/topic/custom-fields-on-woocommerce-product-variations/

Body:
Add Advanced Custom Fields to WooCommerce Product Variation

Hello, we are having issues trying to add a unique ACF per each variable product.

Our product: "Product A - Variable Product." This product has 4 different variations, and we would like to add unique ACF depending on that product variation.

Within our custom fields tab I created a new custom field, field group, and label, I then selected; "Show this field group if post is equal to product_variation Product A - Variable Product." Doing so did NOT add the custom field to our products admin page. Previously we have used; "post type is equal to product" which works great, but can not be used in the variable product situation.

More background:
Currently, we are using ACF to aid in our WooCommerce Email customizer, and it is working great. The email is printing out ACF data in accordance to the product that is purchased (see code below).

<?php
$product_idMe = $item->get_product_id();
$fields = get_field_objects($product_idMe);
if( $fields )
{
    foreach( $fields as $field_name => $field )
    {
            echo $field['label'];
            echo $field['value'];
    }
}
?>

Goal: To add unique ACF to variable products, and print out the data into an email (like we are doing already doing, but now with the variable products unique ACF).

Please let me know if you need any clarification, a client of ours is trying to launch their website with this feature working.
-Thanks, Michael P.


问:
R Data Cleaning Challenge - What is the best way to find and replace string matches across multiple columns of data?
I have a marketing dataset where each customer has 3 parameters:

utm_source

utm_medium

utm_campaign

The data set looks like this:

```<code>Id  utm_source  utm_medium  utm_campaign
11  internet    google+ppc  unknown
23  internet    organic home
31  internet    organic home
35  internet    google+ppc  unknown
37  internet    google+ppc  unknown
</code>```

The data has a parent-child, grand-child relationship like this:

utm_source (parent) -> utm_medium (child) -> utm_capaign (grand-child)

The problem I have is that some of these parent-child relationship have changed.

Thus, I need to clean the old data to match the new utm structure.

For example,

OLD:

```<code>Id  utm_source  utm_medium  utm_campaign
11  internet    google+ppc  unknown
</code>```

NEW:

```<code>Id  utm_source  utm_medium  utm_campaign
11  internet    paid    google
</code>```

Does anyone have an idea of how to solve this difficult data-cleaning problem in R?

答:
```<code>data$utm_medium <- gsub("google+ppc", "paid", data$utm_medium)
data$utm_campaign <- gsub("unknown", "google", data$utm_campaign)
</code>```

Body:
I have a marketing dataset where each customer has 3 parameters:

utm_source

utm_medium

utm_campaign

The data set looks like this:

Id  utm_source  utm_medium  utm_campaign
11  internet    google+ppc  unknown
23  internet    organic home
31  internet    organic home
35  internet    google+ppc  unknown
37  internet    google+ppc  unknown

The data has a parent-child, grand-child relationship like this:

utm_source (parent) -> utm_medium (child) -> utm_capaign (grand-child)

The problem I have is that some of these parent-child relationship have changed.

Thus, I need to clean the old data to match the new utm structure.

For example,

OLD:

Id  utm_source  utm_medium  utm_campaign
11  internet    google+ppc  unknown

NEW:

Id  utm_source  utm_medium  utm_campaign
11  internet    paid    google

Does anyone have an idea of how to solve this difficult data-cleaning problem in R?


问:
Can anybody explain this statement - "The point of all lambdas is deferred execution"
I was going through an example in "Java SE 8 for the Really Impatient: Programming with Lambdas".

Let us look at a simple example. Suppose you log an event:

```<code>logger.info("x: " + x + ", y: " + y);
</code>```

What happens if the log level is set to suppress INFO messages? The message string is computed and passed to the info method, which then decides to throw it away. Wouldn’t it be nicer if the string concatenation only happened when necessary?

Running code only when necessary is a use case for lambdas. The standard idiom is to wrap the code in a no-arg lambda:

```<code>() -> "x: " + x + ", y: " + y
</code>```

The following method provides lazy logging:

```<code>public static void info(Logger logger, Supplier<String> message) {
if (logger.isLoggable(Level.INFO))
  logger.info(message.get());
}
</code>```

We use the isLoggable method of the Logger class to decide whether INFO messages should be logged. If so, we invoke the lambda by calling its abstract method, which happens to be called get.

So what I don't understand is - we could have used the logger.isLoggable(Level.INFO) in the Example 1 (the code which does not use lambdas) and the message string will be computed only if we the logger.isLoggable(Level.INFO) is satisfied.

```<code>logger.info("x: " + x + ", y: " + y);
</code>```

What was the use of using lambdas in this case?

答:
we could have used the logger.isLoggable(Level.INFO) in the Example 1 and the message string will be computed only if we the logger.isLoggable(Level.INFO) is satisfied.

That is true, yes, but only if you actually check the isLoggable for every log call:

```<code>if (logger.isLoggable(Level.INFO))
   logger.info("x: " + x + ", y: " + y);

if (logger.isLoggable(Level.INFO))
   logger.info("another log entry");
</code>```

So you are basically requiring users to explicitly check the log level for every log call. There is also no way to actually enforce users to check it all the time, so you would need to also check the log level inside the method. And as you can probably imagine, this becomes very verbose if you end up having to add an if for every single log call.

On the other hand, if you are using a lambda, you can move that condition inside the info method, so you do not have to check the log level explicitly.

Body:
I was going through an example in "Java SE 8 for the Really Impatient: Programming with Lambdas".

Let us look at a simple example. Suppose you log an event:

logger.info("x: " + x + ", y: " + y);

What happens if the log level is set to suppress INFO messages? The message string is computed and passed to the info method, which then decides to throw it away. Wouldn’t it be nicer if the string concatenation only happened when necessary?

Running code only when necessary is a use case for lambdas. The standard idiom is to wrap the code in a no-arg lambda:

() -> "x: " + x + ", y: " + y

The following method provides lazy logging:

public static void info(Logger logger, Supplier<String> message) {
if (logger.isLoggable(Level.INFO))
  logger.info(message.get());
}

We use the isLoggable method of the Logger class to decide whether INFO messages should be logged. If so, we invoke the lambda by calling its abstract method, which happens to be called get.

So what I don't understand is - we could have used the logger.isLoggable(Level.INFO) in the Example 1 (the code which does not use lambdas) and the message string will be computed only if we the logger.isLoggable(Level.INFO) is satisfied.

logger.info("x: " + x + ", y: " + y);

What was the use of using lambdas in this case?

Body:
we could have used the logger.isLoggable(Level.INFO) in the Example 1 and the message string will be computed only if we the logger.isLoggable(Level.INFO) is satisfied.

That is true, yes, but only if you actually check the isLoggable for every log call:

if (logger.isLoggable(Level.INFO))
   logger.info("x: " + x + ", y: " + y);

if (logger.isLoggable(Level.INFO))
   logger.info("another log entry");

So you are basically requiring users to explicitly check the log level for every log call. There is also no way to actually enforce users to check it all the time, so you would need to also check the log level inside the method. And as you can probably imagine, this becomes very verbose if you end up having to add an if for every single log call.

On the other hand, if you are using a lambda, you can move that condition inside the info method, so you do not have to check the log level explicitly.