问:
"where" + "or_where, "or_where" leaving out conditions
How would I make it so I have the conditions of:

```<code>$this->db->where('msgto.msgto_display', 'y');
$this->db->where('msgto.msgto_unread', 'y');
</code>```

But then have:

```<code>$this->db->where('msgto.msgto_recipient', $userid);
$this->db->or_where('msgto.msgto_recipient', 4);
</code>```

At the moment its fine apart from when it reads the "or_where" it leaves out above "conditions" so the results to recipient 4 dont have the ('msgto.msgto_display', 'y') and ('msgto.msgto_unread', 'y')flagged.

Thanks for your help :)

答: I'm not sure CodeIgniter's query builder is powerful enough to handle that case, based on its documentation. You may need to do your query on recipient first, and then manually filter the results.</p>

ContentLicense: CC BY-SA 2.5

Body:
How would I make it so I have the conditions of:

$this->db->where('msgto.msgto_display', 'y');
$this->db->where('msgto.msgto_unread', 'y');

But then have:

$this->db->where('msgto.msgto_recipient', $userid);
$this->db->or_where('msgto.msgto_recipient', 4);

At the moment its fine apart from when it reads the "or_where" it leaves out above "conditions" so the results to recipient 4 dont have the ('msgto.msgto_display', 'y') and ('msgto.msgto_unread', 'y')flagged.

Thanks for your help :)


来源: stackexchange

问:
Images not showing over SSL on apache2 with python script
I know this question has been asked several times, but I am all out of ideas and have been reading everywhere about this.

I am running Ubuntu 17.04 and Apache 2.4.25 to host a web server.  I have generated my own SSL certificate.  Since doing this, I am unable to view any images over SSL.  Currently, I can confirm the path is working, the file is in tact and URL is correct, as I can access this typing the http URL into my browser.

If I go to the web inspector whilst loading my site, if I click on any image it gives me a 404 error.

How do I get these images to load over SSL.

My apache2 config is:

```<code><VirtualHost *:80>

    ServerName localhost
    ServerAdmin info@****.com
    DocumentRoot /var/www/****.com/pay
    Redirect /secure https://****.com/

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

<VirtualHost *:443>
    SSLEngine On
    SSLCertificateFile /etc/ssl/certs/****.com.crt
    SSLCertificateKeyFile /etc/ssl/private/****.com.key
    SSLCACertificateFile /etc/ssl/certs/ca-certificates.crt

    SetEnv SECRET_KEY ****
    SetEnv PUBLISHABLE_****
    ServerAdmin info@****.com
    ServerName www.****.com
    DocumentRoot /var/www/****.com/pay/static

    WSGIDaemonProcess webtool threads=5 python-path=/var/www/****.com/pay
    WSGIScriptAlias / /var/www/****.com/pay/webtool.wsgi
    EnableMMAP off
    EnableSendfile off
    <Directory /var/www/****.com/pay>
    Options +ExecCGI
    WSGIProcessGroup webtool
    WSGIApplicationGroup %{GLOBAL}
    WSGIScriptReloading On
    AllowOverride All
    Require all granted
    </Directory>
</VirtualHost>
</code>```

and I have a python script running to do my routes:

```<code>    import os
    import stripe
    import cgi
    print "Context-type: text/html"

    from flask import Flask, render_template, request, redirect, send_from_directory
    from flask import request
    from flask import json

    stripe_keys = {
        'secret_key': os.environ['SECRET_KEY'],
        'publishable_key': os.environ['PUBLISHABLE_KEY']
    }

    stripe.api_key = stripe_keys['secret_key']

    app = Flask(__name__, static_url_path='')

    @app.route('/')
    def index():
        return render_template('index.html', key=stripe_keys['publishable_key'])

    @app.route("/hello")
    def hello():
        return "Hello World!"

    if __name__ == "__main__":
        app.run(host="127.0.0.1", port="5050")

    @app.route("/charge", methods=['POST'])
    def charge():
         # Amount in cents
        amount = 500

        customer = stripe.Customer.create(
        email=request.form['stripeEmail'],
        source=request.form['stripeToken']
        )

        charge = stripe.Charge.create(
            customer=customer.id,
            receipt_email=request.form['stripeEmail'],
            amount=amount,
            currency='usd',
            description='Donation'
        )

        return render_template('charge.html', amount=amount)
</code>```

I cannot work out if I need to set a route in my python script to allow images to be fetched, or I am missing something else.

I am calling the image in my index.html file with:

with the 'img' folder being in the same location as index.html.  Please help.

答:
Your image requests are being sent to WSGI, if you want Apache to handle them, you'll have to "undo" the  WSGIScriptAlias of /.

I'm not a WSGI user, but it seems like you could block this from
running conditionally by putting this in your vhost:

```<code>RewriteEngine ON
RewriteRule ^/img/ - [L]
</code>```

Even though this is a no-op, it should block this part of WSGi from running.

ContentLicense: CC BY-SA 3.0

Body:
I know this question has been asked several times, but I am all out of ideas and have been reading everywhere about this.

I am running Ubuntu 17.04 and Apache 2.4.25 to host a web server.  I have generated my own SSL certificate.  Since doing this, I am unable to view any images over SSL.  Currently, I can confirm the path is working, the file is in tact and URL is correct, as I can access this typing the http URL into my browser.

If I go to the web inspector whilst loading my site, if I click on any image it gives me a 404 error.

How do I get these images to load over SSL.

My apache2 config is:

<VirtualHost *:80>

    ServerName localhost
    ServerAdmin info@****.com
    DocumentRoot /var/www/****.com/pay
    Redirect /secure https://****.com/

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

<VirtualHost *:443>
    SSLEngine On
    SSLCertificateFile /etc/ssl/certs/****.com.crt
    SSLCertificateKeyFile /etc/ssl/private/****.com.key
    SSLCACertificateFile /etc/ssl/certs/ca-certificates.crt

    SetEnv SECRET_KEY ****
    SetEnv PUBLISHABLE_****
    ServerAdmin info@****.com
    ServerName www.****.com
    DocumentRoot /var/www/****.com/pay/static

    WSGIDaemonProcess webtool threads=5 python-path=/var/www/****.com/pay
    WSGIScriptAlias / /var/www/****.com/pay/webtool.wsgi
    EnableMMAP off
    EnableSendfile off
    <Directory /var/www/****.com/pay>
    Options +ExecCGI
    WSGIProcessGroup webtool
    WSGIApplicationGroup %{GLOBAL}
    WSGIScriptReloading On
    AllowOverride All
    Require all granted
    </Directory>
</VirtualHost>

and I have a python script running to do my routes:

    import os
    import stripe
    import cgi
    print "Context-type: text/html"

    from flask import Flask, render_template, request, redirect, send_from_directory
    from flask import request
    from flask import json

    stripe_keys = {
        'secret_key': os.environ['SECRET_KEY'],
        'publishable_key': os.environ['PUBLISHABLE_KEY']
    }

    stripe.api_key = stripe_keys['secret_key']

    app = Flask(__name__, static_url_path='')

    @app.route('/')
    def index():
        return render_template('index.html', key=stripe_keys['publishable_key'])

    @app.route("/hello")
    def hello():
        return "Hello World!"

    if __name__ == "__main__":
        app.run(host="127.0.0.1", port="5050")

    @app.route("/charge", methods=['POST'])
    def charge():
         # Amount in cents
        amount = 500

        customer = stripe.Customer.create(
        email=request.form['stripeEmail'],
        source=request.form['stripeToken']
        )

        charge = stripe.Charge.create(
            customer=customer.id,
            receipt_email=request.form['stripeEmail'],
            amount=amount,
            currency='usd',
            description='Donation'
        )

        return render_template('charge.html', amount=amount)

I cannot work out if I need to set a route in my python script to allow images to be fetched, or I am missing something else.

I am calling the image in my index.html file with:

with the 'img' folder being in the same location as index.html.  Please help.

Body:
Your image requests are being sent to WSGI, if you want Apache to handle them, you'll have to "undo" the  WSGIScriptAlias of /.

I'm not a WSGI user, but it seems like you could block this from
running conditionally by putting this in your vhost:

RewriteEngine ON
RewriteRule ^/img/ - [L]

Even though this is a no-op, it should block this part of WSGi from running.


问:
Missing javaCompileTask for variant
Trying to build something with Android Studio 3.0 that worked fine in a previous version. Now I am seeing:

Error:Execution failed for task ':mobile-app:transformClassesWithRetrolambdaForDevDebug'.

Missing javaCompileTask for variant: dev/debug/0 from output dir: /Users/myname/mycompany-android-app/MyProject/mobile-app/build/intermediates/transforms/retrolambda/dev/debug/0

I had a prior compile issue I got around by the adding the following to my module level build.gradle inside of defaultConfig:

javaCompileOptions {
            annotationProcessorOptions {
                includeCompileClasspath false
            }
        }

I can't find much of anything on "javaCompileTask". Maybe that relates to something else?

答:
I tried to use retrolambda version 3.6.1 with Android Gradle plugin 3.0.0-alpha5 and it does works.
This is an issue with Android Gradle plugin 3.0.0-alpha* version.

Reference:

Does not currently work with the Retrolambda plugin. However, you should instead use the plugin's built-in support for Java 8 language features.

Documented in the Known Issues section at https://developer.android.com/studio/preview/features/new-android-plugin.html

Title: Missing javaCompileTask for variant


问:
OnItemClickListener vs OnclickListener in listview android
This is gonna be long due to code. So I have a question about OnItemclickListener vs OnclickListener,and here I have two codes one for each and both worked, so is there any preference to use one of the two or can I use anyone???
Here is code with OnItemClickListener

```<code>public class MainActivity extends AppCompatActivity {
    private ArrayList<String> numbers=new ArrayList<String>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); //a listview with id "list"

        ListView numberLV = (ListView) findViewById(R.id.list);
        numbers.add("one");
        numbers.add("two");
        numbers.add("three");
        numbers.add("four");
        // and so on
        listAdapter itemadapter=new listAdapter(this,numbers);
        numberLV.setAdapter(itemadapter);
        numberLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String num=numbers.get(position);
                String display="You have clicked "+num;
                Toast.makeText(MainActivity.this,display,Toast.LENGTH_SHORT).show();
            }
        });
    }
}
class listAdapter extends ArrayAdapter<String> {
    public listAdapter(@NonNull Context context, ArrayList<String> numbers){
        super(context,0,numbers);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View listItemView = convertView;
        if(listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_num, parent, false);
        }
        TextView tvnum=(TextView) listItemView.findViewById(R.id.numbersTV);
        String num=getItem(position);
        tvnum.setText(num);
        return listItemView;
    }
}
</code>```

and here's one with OnClickListener

```<code>public class MainActivity extends AppCompatActivity {
    private ArrayList<String> numbers=new ArrayList<String>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); //a listview with id "list"

        ListView numberLV = (ListView) findViewById(R.id.list);
        numbers.add("one");
        numbers.add("two");
        numbers.add("three");
        numbers.add("four");
        // and so on
        listAdapter itemadapter=new listAdapter(this,numbers);
        numberLV.setAdapter(itemadapter);
    }
}
class listAdapter extends ArrayAdapter<String> {
    public listAdapter(@NonNull Context context, ArrayList<String> numbers){
        super(context,0,numbers);
    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View listItemView = convertView;
        if(listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_num, parent, false);
        }
        TextView tvnum=(TextView) listItemView.findViewById(R.id.numbersTV);
        String num=getItem(position);
        tvnum.setText(num);
        listItemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String display="You have clicked "+getItem(position);
                Toast.makeText(getContext(),display,Toast.LENGTH_SHORT).show();
            }
        });
        return listItemView;
    }
}
</code>```

Both codes worked normally for me, but the confusion was whether the second one was right or wrong??

答:
I think setOnItemClickListener() is the best than onClickListener() because,

It give you a single row click in activity or fragment where ListView defined.

It is easier when you want to perform operation on onItemClickListener() such as open another activity or fragment.

We can get selected row List object using view.getTag() method in on item click method.

When you have call data from web api like soap or restful on listview item click then it is easy way to implement it.

Body:
This is gonna be long due to code. So I have a question about OnItemclickListener vs OnclickListener,and here I have two codes one for each and both worked, so is there any preference to use one of the two or can I use anyone???
Here is code with OnItemClickListener

public class MainActivity extends AppCompatActivity {
    private ArrayList<String> numbers=new ArrayList<String>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); //a listview with id "list"

        ListView numberLV = (ListView) findViewById(R.id.list);
        numbers.add("one");
        numbers.add("two");
        numbers.add("three");
        numbers.add("four");
        // and so on
        listAdapter itemadapter=new listAdapter(this,numbers);
        numberLV.setAdapter(itemadapter);
        numberLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String num=numbers.get(position);
                String display="You have clicked "+num;
                Toast.makeText(MainActivity.this,display,Toast.LENGTH_SHORT).show();
            }
        });
    }
}
class listAdapter extends ArrayAdapter<String> {
    public listAdapter(@NonNull Context context, ArrayList<String> numbers){
        super(context,0,numbers);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View listItemView = convertView;
        if(listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_num, parent, false);
        }
        TextView tvnum=(TextView) listItemView.findViewById(R.id.numbersTV);
        String num=getItem(position);
        tvnum.setText(num);
        return listItemView;
    }
}

and here's one with OnClickListener

public class MainActivity extends AppCompatActivity {
    private ArrayList<String> numbers=new ArrayList<String>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); //a listview with id "list"

        ListView numberLV = (ListView) findViewById(R.id.list);
        numbers.add("one");
        numbers.add("two");
        numbers.add("three");
        numbers.add("four");
        // and so on
        listAdapter itemadapter=new listAdapter(this,numbers);
        numberLV.setAdapter(itemadapter);
    }
}
class listAdapter extends ArrayAdapter<String> {
    public listAdapter(@NonNull Context context, ArrayList<String> numbers){
        super(context,0,numbers);
    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View listItemView = convertView;
        if(listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_num, parent, false);
        }
        TextView tvnum=(TextView) listItemView.findViewById(R.id.numbersTV);
        String num=getItem(position);
        tvnum.setText(num);
        listItemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String display="You have clicked "+getItem(position);
                Toast.makeText(getContext(),display,Toast.LENGTH_SHORT).show();
            }
        });
        return listItemView;
    }
}

Both codes worked normally for me, but the confusion was whether the second one was right or wrong??


问:
java.lang.NullPointerException: Cannot invoke method when running Groovy in Java
I am using Groovy and Java for the first time and keep getting exception while running my simple main project.

Exception:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke method sell() on null object

class App Java:

```<code>public void start() throws CompilationFailedException, IOException {

    File trades = uploadGroovyScript();

    Binding binding = new Binding();
    GroovyShell shell = new GroovyShell(binding);
    shell.evaluate(trades);
    TradeDsl tradeDsl = new TradeDsl();
    Closure c = (Closure) binding.getVariable("trades1");
    c.setDelegate(tradeDsl);
    c.call();
}
</code>```

file Groovy:

```<code> trades1 = {
            buy 100,200 from "MSFT"
            buy 1000,200 from "APPL"
            buy 500,200 from "VMW"
            sell 50,200 from "MSFT"
            buy 1200,200 from "MSFT"
            sell 200,200 from "VMW"
            buy 1200,200 from "APPL"
          }
</code>```

class TradeDsl:

```<code>public void buy(int quantity1 , int quantity2) {
    System.out.println("Buying " + quantity1 + " or " + quantity2);
}

public void sell(int quantity1) {
    System.out.println("Selling " + quantity1);
}

public void from(String epic) {
    System.out.println("from " + epic);
}
</code>```

答: found the problem, the TradeDsl buy, sell, from need to return TradeDsl</p>

Body:
I am using Groovy and Java for the first time and keep getting exception while running my simple main project.

Exception:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke method sell() on null object

class App Java:

public void start() throws CompilationFailedException, IOException {

    File trades = uploadGroovyScript();

    Binding binding = new Binding();
    GroovyShell shell = new GroovyShell(binding);
    shell.evaluate(trades);
    TradeDsl tradeDsl = new TradeDsl();
    Closure c = (Closure) binding.getVariable("trades1");
    c.setDelegate(tradeDsl);
    c.call();
}

file Groovy:

 trades1 = {
            buy 100,200 from "MSFT"
            buy 1000,200 from "APPL"
            buy 500,200 from "VMW"
            sell 50,200 from "MSFT"
            buy 1200,200 from "MSFT"
            sell 200,200 from "VMW"
            buy 1200,200 from "APPL"
          }

class TradeDsl:

public void buy(int quantity1 , int quantity2) {
    System.out.println("Buying " + quantity1 + " or " + quantity2);
}

public void sell(int quantity1) {
    System.out.println("Selling " + quantity1);
}

public void from(String epic) {
    System.out.println("from " + epic);
}


问:
Git svn work flow, making branchs in git-svn
```<code>git version 1.7.3.3
</code>```

I had a project that was using git.

Our company changed its policy and wanted everyone to switch to svn.

So I imported my project in subversion using the standard layout (trunk, branchs, and tags).

So my current workflow is the following:

Make some changes, put them in the staging area, then commit them to git. However, I get a little confused when it comes to svn. First I rebase to get the latest changes from subversion. Then I do a dcommit.

i.e.

Stage the change files

```<code>git stage app_driver.c
</code>```

Commit them to git

```<code>git commit -m"Added some changes"
</code>```

Get the latest changes from svn

```<code>git svn rebase
</code>```

commit the my latest changes to svn

```<code>git svn dcommit
</code>```

push the changes to my git repository

```<code>git push upstream my_project
</code>```

However, the real confusion comes when I make a new branch in git, and how I can commit to that branch in subversion.

```<code>git checkout -b add_new_feature
</code>```

Then how do I make the new branch in svn and commit it?

Many thanks for any suggestions,

答:
What I do normally is create a branch in subversion using svn copy.

For example, suppose my trunk is in
https://svnserver/svn/MyProject/trunk and I want to create a branch in https://svnserver/svn/MyProject/branches/my-branch, I would do:

```<code>svn copy https://svnserver/svn/MyProject/trunk https://svnserver/svn/MyProject/branches/my-branch
</code>```

Ok, this would get rid of creating the svn branch, but to fetch this branch with git I would go  to my directory and do a git svn fetch. This would fetch things from svn but would not modify your current branches.

If you started your project with git svn init --stdlayout  your branch will appear when you do a git branch -r. You can then checkout it with something like this:

```<code>git checkout -b my_local_branch_name my_remote_branch_name
</code>```

Note: do not use the same name for your local branch and for your remote branch or git will complain (although it works.)

Then you can work as normal.

Body:
git version 1.7.3.3

I had a project that was using git.

Our company changed its policy and wanted everyone to switch to svn.

So I imported my project in subversion using the standard layout (trunk, branchs, and tags).

So my current workflow is the following:

Make some changes, put them in the staging area, then commit them to git. However, I get a little confused when it comes to svn. First I rebase to get the latest changes from subversion. Then I do a dcommit.

i.e.

Stage the change files

git stage app_driver.c

Commit them to git

git commit -m"Added some changes"

Get the latest changes from svn

git svn rebase

commit the my latest changes to svn

git svn dcommit

push the changes to my git repository

git push upstream my_project

However, the real confusion comes when I make a new branch in git, and how I can commit to that branch in subversion.

git checkout -b add_new_feature

Then how do I make the new branch in svn and commit it?

Many thanks for any suggestions,

Body:
What I do normally is create a branch in subversion using svn copy.

For example, suppose my trunk is in
https://svnserver/svn/MyProject/trunk and I want to create a branch in https://svnserver/svn/MyProject/branches/my-branch, I would do:

svn copy https://svnserver/svn/MyProject/trunk https://svnserver/svn/MyProject/branches/my-branch

Ok, this would get rid of creating the svn branch, but to fetch this branch with git I would go  to my directory and do a git svn fetch. This would fetch things from svn but would not modify your current branches.

If you started your project with git svn init --stdlayout  your branch will appear when you do a git branch -r. You can then checkout it with something like this:

git checkout -b my_local_branch_name my_remote_branch_name

Note: do not use the same name for your local branch and for your remote branch or git will complain (although it works.)

Then you can work as normal.


问:
SQL server report builder show text box only if a field is blank
I have several text boxes that display information that the field cannot display.

Now when there is data in the field, I don't want the textboxes to display their extra information.  Is there a visibility expression that makes it so the textboxes are only displayed if the field is blank or 0.00?

Edit:
The text box ("TxtCycleTime13") expressions are: "=IIf((Fields!PartNum.Value Like "16THW-PIF"), "24.0", "0.00")" right now  -  This makes the text boxes display 24.0 whenever a part number starts with 16THW-PIF

The text box ("TxtCycleTime13") visibility expression are: "=Iif(ReportItems!TxtCycleTime13.Value = "0.00", True, False)" right now. - This makes the text box show ONLY if it has 24.0 (or in other words, if only the part number is 16THW-PIF)

Thanks!

答:
True in the expression specifies Hidden, so if the expression returns true the text box will not show. To invert this you would simply swap the True and False:

```<code>=Iif(ReportItems!TxtCycleTime13.Value = "0.00", False, True)
</code>```

This will only show the textbox if the value is 0.
If you want to check  a field instead of the existing textbox, just reference it instead;

```<code>=Iif(Fields!CycleTime.Value = "0.00", False, True)
</code>```

Body:
True in the expression specifies Hidden, so if the expression returns true the text box will not show. To invert this you would simply swap the True and False:

=Iif(ReportItems!TxtCycleTime13.Value = "0.00", False, True)

This will only show the textbox if the value is 0.
If you want to check  a field instead of the existing textbox, just reference it instead;

=Iif(Fields!CycleTime.Value = "0.00", False, True)


问:
DNN ModuleID not being passed from the code behind to the ascx
Backstory: I use a DNN (DotNetNuke) content management system to host VB.NET/Angular1 modules.

I'm currently having an issue where a value in the code-behind is not accessible in the View.ascx of my module. This is causing a fatal runtime error.

The code behind where the value is being passed to a publicly defined variable

The View.ascx where the variable is being used

```<code>Erreur: icod est présentement indisponible.
DotNetNuke.Services.Exceptions.ModuleLoadException: C:\inetpub\wwwroot\FRANCO-NORD-www1\DesktopModules\icod\View.ascx(2): error BC30451: 'modID' n'est pas déclaré. Il peut être inaccessible en raison de son niveau de protection. ---> System.Web.HttpCompileException: C:\inetpub\wwwroot\FRANCO-NORD-www1\DesktopModules\icod\View.ascx(2): error BC30451: 'modID' n'est pas déclaré. Il peut être inaccessible en raison de son niveau de protection.
à System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath)
à System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
à System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
à System.Web.UI.TemplateControl.LoadControl(VirtualPath virtualPath)
à DotNetNuke.UI.ControlUtilities.LoadControl[T](TemplateControl containerControl, String ControlSrc)
à DotNetNuke.UI.Modules.WebFormsModuleControlFactory.CreateModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration)
à DotNetNuke.UI.Modules.ModuleControlFactory.LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration)
à DotNetNuke.UI.Modules.ModuleHost.LoadModuleControl() --- Fin de la trace de la pile d'exception interne --
</code>```

I noticed that they reference View.ascx(2) as if there are two physical versions of the file in the project or on the server, but this is not the case.

Any ideas on what may be going on here? Please let me know should the post require additional information.

答:
My best guess, based on the updated screenshot, is that your full class name is incorrect in your View.ascx.  It is expecting a codebehind class "Christoc.Modules.icod.View", but no namespace is defined in your partial class which means it will default to your default project namespace (which I am assuming is different).

I would try two things.

1) Ensure the namespace is defined in your View.ascx.cs

```<code>Namespace Christoc.Modules.icod
    Partial Class View
        ...
    End Class
End Namespace
</code>```

2) Make sure you are building your module's assembly into the correct /bin folder of your DNN installation.

Body:
Backstory: I use a DNN (DotNetNuke) content management system to host VB.NET/Angular1 modules.

I'm currently having an issue where a value in the code-behind is not accessible in the View.ascx of my module. This is causing a fatal runtime error.

The code behind where the value is being passed to a publicly defined variable

The View.ascx where the variable is being used

Erreur: icod est présentement indisponible.
DotNetNuke.Services.Exceptions.ModuleLoadException: C:\inetpub\wwwroot\FRANCO-NORD-www1\DesktopModules\icod\View.ascx(2): error BC30451: 'modID' n'est pas déclaré. Il peut être inaccessible en raison de son niveau de protection. ---> System.Web.HttpCompileException: C:\inetpub\wwwroot\FRANCO-NORD-www1\DesktopModules\icod\View.ascx(2): error BC30451: 'modID' n'est pas déclaré. Il peut être inaccessible en raison de son niveau de protection.
à System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath)
à System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
à System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
à System.Web.UI.TemplateControl.LoadControl(VirtualPath virtualPath)
à DotNetNuke.UI.ControlUtilities.LoadControl[T](TemplateControl containerControl, String ControlSrc)
à DotNetNuke.UI.Modules.WebFormsModuleControlFactory.CreateModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration)
à DotNetNuke.UI.Modules.ModuleControlFactory.LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration)
à DotNetNuke.UI.Modules.ModuleHost.LoadModuleControl() --- Fin de la trace de la pile d'exception interne --

I noticed that they reference View.ascx(2) as if there are two physical versions of the file in the project or on the server, but this is not the case.

Any ideas on what may be going on here? Please let me know should the post require additional information.

Body:
My best guess, based on the updated screenshot, is that your full class name is incorrect in your View.ascx.  It is expecting a codebehind class "Christoc.Modules.icod.View", but no namespace is defined in your partial class which means it will default to your default project namespace (which I am assuming is different).

I would try two things.

1) Ensure the namespace is defined in your View.ascx.cs

Namespace Christoc.Modules.icod
    Partial Class View
        ...
    End Class
End Namespace

2) Make sure you are building your module's assembly into the correct /bin folder of your DNN installation.


问:
How to set up play framework ApplicationLoader and Macwire to work with custom routes?
I set up the application loader this way:

```<code>class MyProjectApplicationLoader extends ApplicationLoader {
  def load(context: Context): Application = new ApplicationComponents(context).application
}

class ApplicationComponents(context: Context) extends BuiltInComponentsFromContext(context)
  with QAControllerModule
  with play.filters.HttpFiltersComponents {

  // set up logger
  LoggerConfigurator(context.environment.classLoader).foreach {
    _.configure(context.environment, context.initialConfiguration, Map.empty)
  }

  lazy val router: Router = {
    // add the prefix string in local scope for the Routes constructor
    val prefix: String = "/"
    wire[Routes]
  }
}
</code>```

but my routes is custom, so it looks like:

the routes file:

```<code>-> /myApi/v1 v1.Routes
-> /MyHealthcheck HealthCheck.Routes
</code>```

and my v1.Routes file:

```<code>GET    /getData    controllers.MyController.getData
</code>```

so now when I compile the project I get this error:

Error: Cannot find a value of type: [v1.Routes]
      wire[Routes]

so im not sure how to fix this, does someone know how can I make the loader to work with this structure of routes?

答:
You also need to wire the v1.Routes. See how it is done manually here:

https://www.playframework.com/documentation/2.6.x/ScalaCompileTimeDependencyInjection#Providing-a-router

This should work as you expect:

```<code>lazy val v1Routes = wire[v1.Routes]
lazy val wiredRouter = wire[Routes]

lazy val router = wiredRouter.withPrefix("/my-prefix")
</code>```

ps.: didn't test it in a real project.

Body:
I set up the application loader this way:

class MyProjectApplicationLoader extends ApplicationLoader {
  def load(context: Context): Application = new ApplicationComponents(context).application
}

class ApplicationComponents(context: Context) extends BuiltInComponentsFromContext(context)
  with QAControllerModule
  with play.filters.HttpFiltersComponents {

  // set up logger
  LoggerConfigurator(context.environment.classLoader).foreach {
    _.configure(context.environment, context.initialConfiguration, Map.empty)
  }

  lazy val router: Router = {
    // add the prefix string in local scope for the Routes constructor
    val prefix: String = "/"
    wire[Routes]
  }
}

but my routes is custom, so it looks like:

the routes file:

-> /myApi/v1 v1.Routes
-> /MyHealthcheck HealthCheck.Routes

and my v1.Routes file:

GET    /getData    controllers.MyController.getData

so now when I compile the project I get this error:

Error: Cannot find a value of type: [v1.Routes]
      wire[Routes]

so im not sure how to fix this, does someone know how can I make the loader to work with this structure of routes?

Body:
You also need to wire the v1.Routes. See how it is done manually here:

https://www.playframework.com/documentation/2.6.x/ScalaCompileTimeDependencyInjection#Providing-a-router

This should work as you expect:

lazy val v1Routes = wire[v1.Routes]
lazy val wiredRouter = wire[Routes]

lazy val router = wiredRouter.withPrefix("/my-prefix")

ps.: didn't test it in a real project.


问:
Question about "FOR EACH ROW" in SQL Triggers
If I'm using a trigger to update one row, and it's only reading from the NEW row, is FOR EACH ROW even needed in the trigger?</p>

答: If you are never going to update more than 1 row with an update statement, then the for each row declaration in your trigger is optional.</p>


问:
Spring Business Object Modeling
We're building a service that can handle posts which are proxied from a web app or a dialer application. Users can confirm or cancel appointments via email, SMS, phone calls, or app.

The complicating factor is that with app and email you get a discrete "Confirm" or "Cancel" action, whereas with phone calls you get a digit pressed and with SMS you get a keyword, like "CONFIRM" or "C". (Further complicating is that to different accounts, keywords or digits will resolve to different actions.)

Here's my question. We receive a post and serialize it into a UserInteraction POJO that contains all relevant info and which is persisted to the database. Unfortunately, this POJO doesn't contain the abstraction of the discrete action the user is taking as far as the business logic is concerned.

Should I add to the POJO something like:

```<code>@Transient
private ResponseType responseType;
</code>```

or should this additional attribute pass through all the methods in its lifecycle as a separate argument?

Method signatures would be like this if I was to keep the ResponseType separate:

```<code>public GenericResponse handleConfirmation(UserInteraction userInteraction, AppointmentInfo apptInfo, ResponseType responseType)
</code>```

答:
IMO base your decision on whether the 'responseType' is part of the 'UserInteraction' abstraction, ie. could it be considered an attribute of a 'User Interaction'

Based on your description, I would think yes -- resolve the actual response (ie. CONFIRM, C, etc) to the corresponding discrete enumeration/type, set on the POJO attribute and then persist in the db.

Title: Spring Business Object Modeling

Body:
We're building a service that can handle posts which are proxied from a web app or a dialer application. Users can confirm or cancel appointments via email, SMS, phone calls, or app.

The complicating factor is that with app and email you get a discrete "Confirm" or "Cancel" action, whereas with phone calls you get a digit pressed and with SMS you get a keyword, like "CONFIRM" or "C". (Further complicating is that to different accounts, keywords or digits will resolve to different actions.)

Here's my question. We receive a post and serialize it into a UserInteraction POJO that contains all relevant info and which is persisted to the database. Unfortunately, this POJO doesn't contain the abstraction of the discrete action the user is taking as far as the business logic is concerned.

Should I add to the POJO something like:

@Transient
private ResponseType responseType;

or should this additional attribute pass through all the methods in its lifecycle as a separate argument?

Method signatures would be like this if I was to keep the ResponseType separate:

public GenericResponse handleConfirmation(UserInteraction userInteraction, AppointmentInfo apptInfo, ResponseType responseType)


问:
Getting text from XPath but want elements?
I am new to XPath so please bear with me. Basic question.

I want to select text, including the elements as well.  Example input below:

```<code><node1>
    <node2>
        <node3>A1</node3>
        <node3>A2</node3>
        <node3>A3</node3>
        <node3>A4</node3>
    </node2>
</node1>
</code>```

I wish to copy the content of node 2 including the tags, which is:

```<code><node2>
    <node3>A1</node3>
    <node3>A2</node3>
    <node3>A3</node3>
    <node3>A4</node3>
</node2>
</code>```

However, if I use the XPath /node1/node2/, I only get values A1 A2 A3 A4 (not the node2 and node3 tags).

答:
However if I use xpath as /node1/node2 - I only get values A1 A2 A3 A4 (not the node2 and node3 tags).

Incorrect.  The XPath, /node1/node2 selects node2 element children of node1, not text nodes or strings.  If you are seeing just A1 A2 A3 A4 for this XPath, then you are evaluating the XPath in a context that automatically converts to string values.

You do not need a new XPath; you need to evaluate the results of the XPath that you already have differently.  For example, if you're using

```<code><xsl:value-of select="/node1/node2"/>
</code>```

you should instead be iterating over the nodeset or applying templates to all elements in the nodeset,

```<code><xsl:apply-templates select="/node1/node2"/>
</code>```

or in XSLT 2.0, returning a sequence,

```<code><xsl:sequence select="/node1/node2"/>
</code>```

etc, depending upon exactly what you need to do with the selected elements.

Body:
I am new to XPath so please bear with me. Basic question.

I want to select text, including the elements as well.  Example input below:

<node1>
    <node2>
        <node3>A1</node3>
        <node3>A2</node3>
        <node3>A3</node3>
        <node3>A4</node3>
    </node2>
</node1>

I wish to copy the content of node 2 including the tags, which is:

<node2>
    <node3>A1</node3>
    <node3>A2</node3>
    <node3>A3</node3>
    <node3>A4</node3>
</node2>

However, if I use the XPath /node1/node2/, I only get values A1 A2 A3 A4 (not the node2 and node3 tags).

Body:
However if I use xpath as /node1/node2 - I only get values A1 A2 A3 A4 (not the node2 and node3 tags).

Incorrect.  The XPath, /node1/node2 selects node2 element children of node1, not text nodes or strings.  If you are seeing just A1 A2 A3 A4 for this XPath, then you are evaluating the XPath in a context that automatically converts to string values.

You do not need a new XPath; you need to evaluate the results of the XPath that you already have differently.  For example, if you're using

<xsl:value-of select="/node1/node2"/>

you should instead be iterating over the nodeset or applying templates to all elements in the nodeset,

<xsl:apply-templates select="/node1/node2"/>

or in XSLT 2.0, returning a sequence,

<xsl:sequence select="/node1/node2"/>

etc, depending upon exactly what you need to do with the selected elements.


问:
Comparing Files in 2 directories
I have this code that tell me if the 2 files have the same content. However, I want to expand this to not just one file but to directory Files. In other words, compare files in one folder to files in another to see if they have same or different contents and if so print it out.

In doing this is it just a matter of modifying the directory paths? My code is below. I think I remember reading somewhere that I may need import another library. Any help would be appreciated.

Problem now I am having is printing out the file name from the area that are the same and that are not the same I tried .getName it is not working my result come back (true) (instead of the names of the files that meet the condition

Code below

```<code>import java.io.File;

public class F2FCompare {

 public static void main(String[] args)
    {
     File folderA = new File("C:/Users/hoflerj/Desktop/FolderA");
     File[] listOfFilesInA = folderA.listFiles();

     File folderB = new File("/C:/Users/hoflerj/Desktop/FolderB");
     File[] listOfFilesInB = folderB.listFiles();

     for (File fileA : listOfFilesInA){
         if (fileA.isFile())
         {
             for (File fileB : listOfFilesInB) {
                  if(fileB.isFile())
                    {
                      if ( fileA.equals(fileB))
                      {
                          System.out.println( "FolderA same as FolderB" + listOfFilesInA.equals(listOfFilesInB) );
                          //File[] files = folder.listFiles();
                      }

                     // txtfile.getName()
                      else
                      {
                          //System.out.println(! fileA.getName().equals(fileB) + "    Folder A diff B" );
                          System.out.println( "Folder same as FolderB  " + !fileA.getName().equals(fileB) );
                      }

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

答:
Try changing:

```<code>if(line1 == null || line2 == null)
</code>```

for:

```<code>if((line1 == null && line2 != null) || (line2 == null && line1 != null))
</code>```

Title: Comparing Files in 2 directories

Body:
I have this code that tell me if the 2 files have the same content. However, I want to expand this to not just one file but to directory Files. In other words, compare files in one folder to files in another to see if they have same or different contents and if so print it out.

In doing this is it just a matter of modifying the directory paths? My code is below. I think I remember reading somewhere that I may need import another library. Any help would be appreciated.

Problem now I am having is printing out the file name from the area that are the same and that are not the same I tried .getName it is not working my result come back (true) (instead of the names of the files that meet the condition

Code below

import java.io.File;

public class F2FCompare {

 public static void main(String[] args)
    {
     File folderA = new File("C:/Users/hoflerj/Desktop/FolderA");
     File[] listOfFilesInA = folderA.listFiles();

     File folderB = new File("/C:/Users/hoflerj/Desktop/FolderB");
     File[] listOfFilesInB = folderB.listFiles();

     for (File fileA : listOfFilesInA){
         if (fileA.isFile())
         {
             for (File fileB : listOfFilesInB) {
                  if(fileB.isFile())
                    {
                      if ( fileA.equals(fileB))
                      {
                          System.out.println( "FolderA same as FolderB" + listOfFilesInA.equals(listOfFilesInB) );
                          //File[] files = folder.listFiles();
                      }

                     // txtfile.getName()
                      else
                      {
                          //System.out.println(! fileA.getName().equals(fileB) + "    Folder A diff B" );
                          System.out.println( "Folder same as FolderB  " + !fileA.getName().equals(fileB) );
                      }

                    }
                }
            }
        }
    }
}

Body:
Try changing:

if(line1 == null || line2 == null)

for:

if((line1 == null && line2 != null) || (line2 == null && line1 != null))


问:
Formatting CSV with PHP
I'm taking form data and writing it to a csv file on the server. I keep running into the same type of issues and I don't know what I am doing wrong. Either the column headers repeat with each entry, or each additional submission writes on the same row. Also, how would I take the $_POST data and populate the csv? I have to declare it twice to get this to work to this point. Here is what I have that somewhat works.</p>

```<code><?php
   //this is just for the post data, but I'm having to declare the key/values again below. I'm sure this is wrong.
   $email = $_POST['email'];
   //rest of the form inputs go here same as $email
   //some server side validation builds an 'error' array

   if(!isset($error) {
        $del = ", ";
        //this is where I have to repeat the post data key/values
        $data[1] = $_POST['email'];
        $data[2] = $_POST['FirstName'];
        $data[3] = $_POST['LastName'];
        $data[4] = $_POST['Address'];
        $data[5] = $_POST['City'];
        $data[6] = $_POST['Country'];
        $data[7] = $_POST['State'];
        $data[8] = $_POST['Phone1'];
        $data[9] = $_POST['password'];

        $file = fopen("Registration.csv", "a");
        //$data is the column headers that won't behave
        $data = "Email, First Name, Last Name, Address, City, Country, State, Phone, Password
        ".implode($del, $data);
        fwrite($file, $data);
        fclose($file);
   }
?>
</code>```

答:
Okay, try the following:

This code checks if the file is empty, and if it is, writes the headers.

```<code>$headers = "Email, First Name, Last Name, Address, City, Country, State, Phone, Password";
if (0 == filesize( $file_path )) {
     fwrite($file, $headers);
}
</code>```

<?php
   $email = $_POST['email'];

   if(!isset($error) {
        $del = ", ";
        //this is where I have to repeat the post data key/values
        $data = array(
          $_POST['email'], //You can replace this with $email
          $_POST['FirstName'], //You can also replace this with the rest of the variables. It should make it cleaner and faster.
          $_POST['LastName'],
          $_POST['Address'],
          $_POST['City'],
          $_POST['Country'],
          $_POST['State'],
          $_POST['Phone1'],
          $_POST['password'],
        );

        $file = fopen("Registration.csv", "a");

        $headers = "Email, First Name, Last Name, Address, City, Country, State, Phone, Password";

        if (0 == filesize( "Registration.csv" )) {
          fwrite($file, $headers . "\n");
        }

        fputcsv($file, $data);
        fclose($file);
   }
?>```

Title: Formatting CSV with PHP

Body:
I'm taking form data and writing it to a csv file on the server. I keep running into the same type of issues and I don't know what I am doing wrong. Either the column headers repeat with each entry, or each additional submission writes on the same row. Also, how would I take the $_POST data and populate the csv? I have to declare it twice to get this to work to this point. Here is what I have that somewhat works.

<?php
   //this is just for the post data, but I'm having to declare the key/values again below. I'm sure this is wrong.
   $email = $_POST['email'];
   //rest of the form inputs go here same as $email
   //some server side validation builds an 'error' array

   if(!isset($error) {
        $del = ", ";
        //this is where I have to repeat the post data key/values
        $data[1] = $_POST['email'];
        $data[2] = $_POST['FirstName'];
        $data[3] = $_POST['LastName'];
        $data[4] = $_POST['Address'];
        $data[5] = $_POST['City'];
        $data[6] = $_POST['Country'];
        $data[7] = $_POST['State'];
        $data[8] = $_POST['Phone1'];
        $data[9] = $_POST['password'];

        $file = fopen("Registration.csv", "a");
        //$data is the column headers that won't behave
        $data = "Email, First Name, Last Name, Address, City, Country, State, Phone, Password
        ".implode($del, $data);
        fwrite($file, $data);
        fclose($file);
   }
?>

Body:
Okay, try the following:

This code checks if the file is empty, and if it is, writes the headers.

$headers = "Email, First Name, Last Name, Address, City, Country, State, Phone, Password";
if (0 == filesize( $file_path )) {
     fwrite($file, $headers);
}

<?php
   $email = $_POST['email'];

   if(!isset($error) {
        $del = ", ";
        //this is where I have to repeat the post data key/values
        $data = array(
          $_POST['email'], //You can replace this with $email
          $_POST['FirstName'], //You can also replace this with the rest of the variables. It should make it cleaner and faster.
          $_POST['LastName'],
          $_POST['Address'],
          $_POST['City'],
          $_POST['Country'],
          $_POST['State'],
          $_POST['Phone1'],
          $_POST['password'],
        );

        $file = fopen("Registration.csv", "a");

        $headers = "Email, First Name, Last Name, Address, City, Country, State, Phone, Password";

        if (0 == filesize( "Registration.csv" )) {
          fwrite($file, $headers . "\n");
        }

        fputcsv($file, $data);
        fclose($file);
   }
?>


问:
how to fix ChakraCore NuGet package error?
When initializing a new React Native Windows WPF project, this error happens:

NuGet Package restore failed for project Native: Unable to find version '1.4.1-preview-00010-42060' of package 'Microsoft.ChakraCore'.
https://www.myget.org/F/chakracore-preview/api/v3/index.json: Package 'Microsoft.ChakraCore.1.4.1-preview-00010-42060' is not found on source 'https://www.myget.org/F/chakracore-preview/api/v3/index.json'.
https://api.nuget.org/v3/index.json: Package 'Microsoft.ChakraCore.1.4.1-preview-00010-42060' is not found on source 'https://api.nuget.org/v3/index.json'.

If I create a standalone project and add the same NuGet package reference, I get the same error -- even on Xamarin Studio Mac.

答:
Looks like the preview Microsoft.ChakraCore NuGet package was removed from the MyGet feed.

The main NuGet.org site only has stable releases for the Microsoft.ChakraCore NuGet package.

So you are left with editing any references to the package and using a published version. Microsoft.ChakraCore version 1.4.4 should work.

There is also an open issue about this on the React native GitHub site.


问:
Understanding macros in C
Why is the output from the following code the value 5?</p>

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

#define A -B
#define B -C
#define C 5

int main()
{
  printf("The value of A is %d\n", A);
  return 0;
}
</code>```

答:
No need to compile this code, just use gcc -E on it (preprocessor) and see what happens:

```<code><lots of output expanding stdio.h> ...

int main()
{
  printf("The value of A is %d\n", - -5);
  return 0;
}
</code>```

Obviously the result is 5 (which could have been guessed by looking at the nested macros, but a small preprocessor test doesn't hurt).

(Other answers noted that some compilers may handle the preprocessing of the minus signs which would result in a compiler error. gcc handles that nicely.)

Title: Understanding macros in C

Body:
Why is the output from the following code the value 5?

#include<stdio.h>

#define A -B
#define B -C
#define C 5

int main()
{
  printf("The value of A is %d\n", A);
  return 0;
}

Body:
No need to compile this code, just use gcc -E on it (preprocessor) and see what happens:

<lots of output expanding stdio.h> ...

int main()
{
  printf("The value of A is %d\n", - -5);
  return 0;
}

Obviously the result is 5 (which could have been guessed by looking at the nested macros, but a small preprocessor test doesn't hurt).

(Other answers noted that some compilers may handle the preprocessing of the minus signs which would result in a compiler error. gcc handles that nicely.)


问:
Extract lines between headings repeated through file
I am trying to modify a txt file with ~43k lines. After the command *Nset is given in the file, I need to extract and save all of the lines following that command, stopping when it gets to the next *command in the file. There is a different number of lines and characters after each of the commands. For instance, here's a sample part of the file:

```<code>*Nset

1, 2, 3, 4, 5, 6, 7,

12, 13, 14, 15, 16,

17, 52, 75, 86, 92,

90, 91, 92 93, 94, 95....

*NEXT COMMAND

 blah blah blah

*Nset

 numbers

*Nset

 numbers

*Command

 irrelevant text
</code>```

The code I currently have works when the numbers I need are not in between two *Nset's. When one *Nset follows another's numbers, it skips that command and the proceeding lines all together and I can't figure out why. When the next command is not *Nset, it finds the next one and pulls out the data perfectly fine.

```<code>import re

# read in the input deck
deck_name = 'master.txt'
deck = open(deck_name,'r')

#initialize variables
nset_data = []
matched_nset_lines = []
nset_count = 0

for line in deck:
     # loop to extract all nset names and node numbers
     important_line = re.search(r'\*Nset,.*',line)
     if important_line :
         line_value = important_line.group() #name for nset
         matched_nset_lines.insert(nset_count,line_value) #name for nset
         temp = []

        # read lines from the found match up until the next *command
         for line_x in deck :
             if not re.match(r'\*',line_x):
                 temp.append(line_x)
             else :
                 break

         nset_data.append(temp)

     nset_count = nset_count + 1
</code>```

I'm using Python 3.5. Thanks for any help.

答:
If you just want to extract the lines between *Nsets the following approach should work:

```<code>In [5]: with open("master.txt") as f:
   ...:     data = []
   ...:     gather = False
   ...:     for line in f:
   ...:         line = line.strip()
   ...:         if line.startswith("*Nset"):
   ...:             gather = True
   ...:         elif line.startswith("*"):
   ...:             gather = False
   ...:         elif line and gather:
   ...:             data.append(line)
   ...:

In [6]: data
Out[6]:
['1, 2, 3, 4, 5, 6, 7,',
 '12, 13, 14, 15, 16,',
 '17, 52, 75, 86, 92,',
 '90, 91, 92 93, 94, 95....',
 'numbers',
 'numbers']
</code>```

And, if you want the additional information, it is simple enough to extend the above:

```<code>In [7]: with open("master.txt") as f:
   ...:     nset_lines = []
   ...:     nset_count = 0
   ...:     data = []
   ...:     gather = False
   ...:     for i, line in enumerate(f):
   ...:         line = line.strip()
   ...:         if line.startswith("*Nset"):
   ...:             gather = True
   ...:             nset_lines.append(i)
   ...:             nset_count += 1
   ...:         elif line.startswith("*"):
   ...:             gather = False
   ...:         elif line and gather:
   ...:             data.append(line)
   ...:

In [8]: nset_lines
Out[8]: [0, 14, 18]

In [9]: nset_count
Out[9]: 3

In [10]: data
Out[10]:
['1, 2, 3, 4, 5, 6, 7,',
 '12, 13, 14, 15, 16,',
 '17, 52, 75, 86, 92,',
 '90, 91, 92 93, 94, 95....',
 'numbers',
 'numbers']
</code>```

Body:
I am trying to modify a txt file with ~43k lines. After the command *Nset is given in the file, I need to extract and save all of the lines following that command, stopping when it gets to the next *command in the file. There is a different number of lines and characters after each of the commands. For instance, here's a sample part of the file:

*Nset

1, 2, 3, 4, 5, 6, 7,

12, 13, 14, 15, 16,

17, 52, 75, 86, 92,

90, 91, 92 93, 94, 95....

*NEXT COMMAND

 blah blah blah

*Nset

 numbers

*Nset

 numbers

*Command

 irrelevant text

The code I currently have works when the numbers I need are not in between two *Nset's. When one *Nset follows another's numbers, it skips that command and the proceeding lines all together and I can't figure out why. When the next command is not *Nset, it finds the next one and pulls out the data perfectly fine.

import re

# read in the input deck
deck_name = 'master.txt'
deck = open(deck_name,'r')

#initialize variables
nset_data = []
matched_nset_lines = []
nset_count = 0

for line in deck:
     # loop to extract all nset names and node numbers
     important_line = re.search(r'\*Nset,.*',line)
     if important_line :
         line_value = important_line.group() #name for nset
         matched_nset_lines.insert(nset_count,line_value) #name for nset
         temp = []

        # read lines from the found match up until the next *command
         for line_x in deck :
             if not re.match(r'\*',line_x):
                 temp.append(line_x)
             else :
                 break

         nset_data.append(temp)

     nset_count = nset_count + 1

I'm using Python 3.5. Thanks for any help.

Body:
If you just want to extract the lines between *Nsets the following approach should work:

In [5]: with open("master.txt") as f:
   ...:     data = []
   ...:     gather = False
   ...:     for line in f:
   ...:         line = line.strip()
   ...:         if line.startswith("*Nset"):
   ...:             gather = True
   ...:         elif line.startswith("*"):
   ...:             gather = False
   ...:         elif line and gather:
   ...:             data.append(line)
   ...:

In [6]: data
Out[6]:
['1, 2, 3, 4, 5, 6, 7,',
 '12, 13, 14, 15, 16,',
 '17, 52, 75, 86, 92,',
 '90, 91, 92 93, 94, 95....',
 'numbers',
 'numbers']

And, if you want the additional information, it is simple enough to extend the above:

In [7]: with open("master.txt") as f:
   ...:     nset_lines = []
   ...:     nset_count = 0
   ...:     data = []
   ...:     gather = False
   ...:     for i, line in enumerate(f):
   ...:         line = line.strip()
   ...:         if line.startswith("*Nset"):
   ...:             gather = True
   ...:             nset_lines.append(i)
   ...:             nset_count += 1
   ...:         elif line.startswith("*"):
   ...:             gather = False
   ...:         elif line and gather:
   ...:             data.append(line)
   ...:

In [8]: nset_lines
Out[8]: [0, 14, 18]

In [9]: nset_count
Out[9]: 3

In [10]: data
Out[10]:
['1, 2, 3, 4, 5, 6, 7,',
 '12, 13, 14, 15, 16,',
 '17, 52, 75, 86, 92,',
 '90, 91, 92 93, 94, 95....',
 'numbers',
 'numbers']


问:
How to display text on multiple lines?
I am using RadPhp to build a PHP application. I want to display several independent lines of text in an Edit control (using $this->edit->text property ) but it seems to be impossible. If I use \n it just displays it instead of braking this line in two.

PS: can anybody add 'RadPHP' as tag for this question?

答:
I have no experience on RadPHP, but instead of \n character, try using
 to break your lines into two.

Title: How to display text on multiple lines?

Body: I have no experience on RadPHP, but instead of \n character, try using <br/> to break your lines into two.


问:
Trouble connecting to PostgreSQL in python with psycopg2
I am having problems connecting to my database through postgreSQL3 version 9.5. However, after running the code below:

```<code>import psycopg2 as p

con = p.connect("dbname ='dvdrental' user = 'myusername' host ='localhost' password ='somepassword'")
cur = con.cursor()
cur.execute("select * from title")
rows = cur.fetchall()
</code>```

I get this error message:

```<code>psycopg2.OperationalError: could not connect to server: Connection refused
(0x0000274D/10061)
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
</code>```

For background information, I accidentally downloaded the newest version of PostgreSQL, and it connected to the part 5432. I need it to connect to PostgreSQL port 5433. I do not know how to do that. How can I solve this DB problem? Is this a PostgreSQL problem or a python problem?

答:
Check the listen adresses of postgres, using netstat (from the shell):

```<code>plasser@pisbak$ netstat -nl |grep 5432
tcp        0      0 0.0.0.0:5432            0.0.0.0:*               LISTEN
tcp6       0      0 :::5432                 :::*                    LISTEN
unix  2      [ ACC ]     STREAM     LISTENING     9002     /tmp/.s.PGSQL.5432
plasser@pisbak$
</code>```

If nothing shows up, Postgres is not listening on port 5432.

Body:
I am having problems connecting to my database through postgreSQL3 version 9.5. However, after running the code below:

import psycopg2 as p

con = p.connect("dbname ='dvdrental' user = 'myusername' host ='localhost' password ='somepassword'")
cur = con.cursor()
cur.execute("select * from title")
rows = cur.fetchall()

I get this error message:

psycopg2.OperationalError: could not connect to server: Connection refused
(0x0000274D/10061)
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?

For background information, I accidentally downloaded the newest version of PostgreSQL, and it connected to the part 5432. I need it to connect to PostgreSQL port 5433. I do not know how to do that. How can I solve this DB problem? Is this a PostgreSQL problem or a python problem?

Body:
Check the listen adresses of postgres, using netstat (from the shell):

plasser@pisbak$ netstat -nl |grep 5432
tcp        0      0 0.0.0.0:5432            0.0.0.0:*               LISTEN
tcp6       0      0 :::5432                 :::*                    LISTEN
unix  2      [ ACC ]     STREAM     LISTENING     9002     /tmp/.s.PGSQL.5432
plasser@pisbak$

If nothing shows up, Postgres is not listening on port 5432.


问:
Looping slice value in HTML file
I have created slice of struct and an array of slice.

```<code>type blogs struct {
    id             int
    title          string
    featured_image string
    created_at     string
}
</code>```

and created variable inside "xyz" function :

```<code>blog := blogs{}
blogData := []blogs{}
</code>```

with value as :

```<code>    rows, err := db.Query("SELECT id, title, featured_image, created_at from blogs order by created_at desc limit 0,6")
    if err != nil {
        ctx.Application().Logger().Fatalf("MySQL Error fetching row %s\n", err)
    }
    for rows.Next() {
        rcan := rows.Scan(&id, &title, &featured_image, &created_at)

        blog.id = id
        blog.title = title
        blog.featured_image = featured_image
        blog.created_at = created_at

        blogData = append(blogData, blog)
    }
</code>```

and now, I have passed "blogData" value to "html" template and iterating below gives error :

```<code>  <ul>
  {{ range $value := .blogData }}
    <li>{{ $value.title }}</li>
  {{ end }}
  </ul>
</code>```

Error :

```<code>template: master.html:18:5: executing "master.html" at <yield>: error calling yield: template: home.html:5:17: executing "home.html" at <$value.title>: title is an unexported field of struct type main.blogs
</code>```

How can I print "title" and other value from blogData Variable in my template.

if I print $value , it returns all value in below format

```<code>{5 This is Title img/blog.jpg 2017-07-05T10:11:30+05:30 }
</code>```

But I want to print, title , featured_image and other date separately.

Any help would be appreciated. I am using "github.com/get-ion/ion" framework

Thanks

答:
To access your struct field on template, it must be exported fields. Update your struct to-

```<code>type blogs struct {
    ID             int
    Title          string
    Featured_image string
    Created_at     string
}
</code>```

Read more about Exported/Unexported Identifiers In Go.

Title: Looping slice value in HTML file

Body:
I have created slice of struct and an array of slice.

type blogs struct {
    id             int
    title          string
    featured_image string
    created_at     string
}

and created variable inside "xyz" function :

blog := blogs{}
blogData := []blogs{}

with value as :

    rows, err := db.Query("SELECT id, title, featured_image, created_at from blogs order by created_at desc limit 0,6")
    if err != nil {
        ctx.Application().Logger().Fatalf("MySQL Error fetching row %s\n", err)
    }
    for rows.Next() {
        rcan := rows.Scan(&id, &title, &featured_image, &created_at)

        blog.id = id
        blog.title = title
        blog.featured_image = featured_image
        blog.created_at = created_at

        blogData = append(blogData, blog)
    }

and now, I have passed "blogData" value to "html" template and iterating below gives error :

  {{ range $value := .blogData }}

{{ $value.title }}

  {{ end }}

Error :

template: master.html:18:5: executing "master.html" at <yield>: error calling yield: template: home.html:5:17: executing "home.html" at <$value.title>: title is an unexported field of struct type main.blogs

How can I print "title" and other value from blogData Variable in my template.

if I print $value , it returns all value in below format

{5 This is Title img/blog.jpg 2017-07-05T10:11:30+05:30 }

But I want to print, title , featured_image and other date separately.

Any help would be appreciated. I am using "github.com/get-ion/ion" framework

Thanks

Body:
To access your struct field on template, it must be exported fields. Update your struct to-

type blogs struct {
    ID             int
    Title          string
    Featured_image string
    Created_at     string
}

Read more about Exported/Unexported Identifiers In Go.


问:
Applying the <!DOCTYPE html> in xquery file
I'm trying to add dateTimePicker of jquery to my UI through xquery code.
without  dateTimePicker functionality is not working correctly.

I'm using below method to apply !DOCTYPE, but browser is unable to render it as html, it is returning as text, please suggest.

```<code>let $document := <html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8"></meta>
    <title>Demo - jquery-simple-datetimepicker</title>

    <!--Requirement jQuery-->
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <!--Load Script and Stylesheet -->
    <script type="text/javascript" src="jquery.simple-dtpicker.js"></script>
    <script type="text/javascript" src="date.js"></script>
    <link type="text/css" href="jquery.simple-dtpicker.css" rel="stylesheet" />
    <!---->

</head>
<body onload ="function()">

    <h3>Append to Input-field</h3>
    <input type="text" name="date" value=""></input>

</body>
</html>

return document {

      text{ '<!DOCTYPE html>' },
      xdmp:quote($document)

    }
</code>```

答:
XQuery does not have a means of producing a DOCTYPE declaration the same way that XSLT does with xsl:output, but you can just add it to the result sequence. And as Dave Cassel suggested, you can also use xdmp:set-response-content-type() to ensure that the response content-type is text/html:

```<code>return (
  xdmp:set-response-content-type("text/html"),
  "<!DOCTYPE html>",
  document{ $document}
)
</code>```

Body:
I'm trying to add dateTimePicker of jquery to my UI through xquery code.
without  dateTimePicker functionality is not working correctly.

I'm using below method to apply !DOCTYPE, but browser is unable to render it as html, it is returning as text, please suggest.

let $document :=

    <meta charset="UTF-8"></meta>
    <title>Demo - jquery-simple-datetimepicker</title>

    <link type="text/css" href="jquery.simple-dtpicker.css" rel="stylesheet" />

Append to Input-field

    <input type="text" name="date" value=""></input>

return document {

      text{ '<!DOCTYPE html>' },
      xdmp:quote($document)

    }

Body:
XQuery does not have a means of producing a DOCTYPE declaration the same way that XSLT does with xsl:output, but you can just add it to the result sequence. And as Dave Cassel suggested, you can also use xdmp:set-response-content-type() to ensure that the response content-type is text/html:

return (
  xdmp:set-response-content-type("text/html"),
  "<!DOCTYPE html>",
  document{ $document}
)


问:
how do get number separately
I have number from 1 to 100 in column A1 to A100.

I am trying to achieve two results from data.

I want separately 1,2,3,4,5,6,7,8,9 and another one 10,20,30,40,50,60,70,80,90,100

Please help me

答: This question is a bit vague.  If you are looking to count by 10s, try adding a 10 in cell B1 and then adding the formula =B1+10 in cell B2. You can drag that formula down to count by 10s.

Title: how do get number separately


问:
How to check whether a string contains a substring in Ruby
I have a string variable with content:

```<code>varMessage =
            "hi/thsid/sdfhsjdf/dfjsd/sdjfsdn\n"

            "/my/name/is/balaji.so\n"
            "call::myFunction(int const&)\n"
            "void::secondFunction(char const&)\n"
             .
             .
             .
            "this/is/last/line/liobrary.so"
</code>```

In the string I have to find a sub-string:

```<code>"hi/thsid/sdfhsjdf/dfjsd/sdjfsdn\n"

"/my/name/is/balaji.so\n"
"call::myFunction(int const&)\n"
</code>```

How can I find it? I need to determine whether the sub-string is present or not.

答:
You can use the String Element Reference method which is []

Inside the [] can either be a literal substring, an index, or a regex:

```<code>> s='abcdefg'
=> "abcdefg"
> s['a']
=> "a"
> s['z']
=> nil
</code>```

Since nil is functionally the same as false and any substring returned from [] is true you can use the logic as if you use the method .include?:

```<code>0> if s[sub_s]
1>    puts "\"#{s}\" has \"#{sub_s}\""
1> else
1*    puts "\"#{s}\" does not have \"#{sub_s}\""
1> end
"abcdefg" has "abc"

0> if s[sub_s]
1>    puts "\"#{s}\" has \"#{sub_s}\""
1> else
1*    puts "\"#{s}\" does not have \"#{sub_s}\""
1> end
"abcdefg" does not have "xyz"
</code>```

Just make sure you don't confuse an index with a sub string:

```<code>> '123456790'[8]    # integer is eighth element, or '0'
=> "0"              # would test as 'true' in Ruby
> '123456790'['8']
=> nil              # correct
</code>```

You can also use a regex:

```<code>> s[/A/i]
=> "a"
> s[/A/]
=> nil
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a string variable with content:

varMessage =
            "hi/thsid/sdfhsjdf/dfjsd/sdjfsdn\n"

            "/my/name/is/balaji.so\n"
            "call::myFunction(int const&)\n"
            "void::secondFunction(char const&)\n"
             .
             .
             .
            "this/is/last/line/liobrary.so"

In the string I have to find a sub-string:

"hi/thsid/sdfhsjdf/dfjsd/sdjfsdn\n"

"/my/name/is/balaji.so\n"
"call::myFunction(int const&)\n"

How can I find it? I need to determine whether the sub-string is present or not.

Body:
You can use the String Element Reference method which is []

Inside the [] can either be a literal substring, an index, or a regex:

> s='abcdefg'
=> "abcdefg"
> s['a']
=> "a"
> s['z']
=> nil

Since nil is functionally the same as false and any substring returned from [] is true you can use the logic as if you use the method .include?:

0> if s[sub_s]
1>    puts "\"#{s}\" has \"#{sub_s}\""
1> else
1*    puts "\"#{s}\" does not have \"#{sub_s}\""
1> end
"abcdefg" has "abc"

0> if s[sub_s]
1>    puts "\"#{s}\" has \"#{sub_s}\""
1> else
1*    puts "\"#{s}\" does not have \"#{sub_s}\""
1> end
"abcdefg" does not have "xyz"

Just make sure you don't confuse an index with a sub string:

> '123456790'[8]    # integer is eighth element, or '0'
=> "0"              # would test as 'true' in Ruby
> '123456790'['8']
=> nil              # correct

You can also use a regex:

> s[/A/i]
=> "a"
> s[/A/]
=> nil


答:
New solution with dt.hour and dt.minute:

```<code>df['label'] = df['event_time'].dt.hour * 4 + df['event_time'].dt.minute // 15 + 1
print (df)
           event_time  label
0 2017-01-17 00:12:50      1
1 2016-12-05 01:00:21      5
2 2016-12-04 01:14:36      5
3 2016-12-04 01:04:03      5
4 2016-12-04 02:28:23     10
5 2016-12-04 02:46:49     12
6 2016-12-04 01:58:04      8
</code>```

Timings:

```<code>rng = pd.date_range('2017-04-03', periods=100000, freq='27T')
df = pd.DataFrame({'timestamp': rng})

df['label'] = df['timestamp'].dt.hour * 4 + df['timestamp'].dt.minute // 15 + 1
df['period'] = df.timestamp.apply(lambda ts: 1 + ts.hour * 4 + ts.minute // 15)
print (df)

In [172]: %timeit df['timestamp'].dt.hour * 4 + df['timestamp'].dt.minute // 15 + 1
10 loops, best of 3: 20.2 ms per loop

In [173]: %timeit df.timestamp.apply(lambda ts: 1 + ts.hour * 4 + ts.minute // 15)
1 loop, best of 3: 301 ms per loop
</code>```

Old solution (working, but a bit complicated):

You can first convert datetimes to to_timedelta by strftime and then convert to seconds by total_seconds.

Then use cut or numpy.searchsorted:

```<code>df['tot'] = pd.to_timedelta(df['event_time'].dt.strftime('%H:%M:%S'))
              .dt.total_seconds()
              .astype(int)

#necessary add one group
bins = np.concatenate([np.arange(24 * 4) * 900, np.array([100000])])
labels = np.arange(1, 24 * 4 + 1)
df['label'] = pd.cut(df['tot'], bins=bins, labels=labels)
</code>```

```<code>df = df.assign(label1=np.searchsorted(bins, df['tot']))
print (df)
           event_time    tot label  label1
0 2017-01-17 00:12:50    770     1       1
1 2016-12-05 01:00:21   3621     5       5
2 2016-12-04 01:14:36   4476     5       5
3 2016-12-04 01:04:03   3843     5       5
4 2016-12-04 02:28:23   8903    10      10
5 2016-12-04 02:46:49  10009    12      12
6 2016-12-04 01:58:04   7084     8       8
</code>```

Similar solutions, only works with Series tot:

```<code>tot = pd.to_timedelta(df['event_time'].dt.strftime('%H:%M:%S'))
       .dt.total_seconds()
       .astype(int)

bins = np.concatenate([np.arange(24 * 4) * 900, np.array([100000])])
labels = np.arange(1, 24 * 4 + 1)
df['label'] = pd.cut(tot, bins=bins, labels=labels)

df = df.assign(label1=np.searchsorted(bins, tot))
print (df)
           event_time label  label1
0 2017-01-17 00:12:50     1       1
1 2016-12-05 01:00:21     5       5
2 2016-12-04 01:14:36     5       5
3 2016-12-04 01:04:03     5       5
4 2016-12-04 02:28:23    10      10
5 2016-12-04 02:46:49    12      12
6 2016-12-04 01:58:04     8       8
</code>```

Title: Pandas: divide data to 15min period

Body:
I have dataframe and date looks like

event_time
2017-01-17 00:12:50
2016-12-05 01:00:21
2016-12-04 01:14:36
2016-12-04 01:04:03
2016-12-04 02:28:23
2016-12-04 02:46:49
2016-12-04 01:58:04

I need to get column period, where 15 min starts from 00:00:00 and day, month and year don't important.
time in 00:00:00 - 00:15:00 - period 1
00:15:01 - 00:50:00 - period 2, etc.
If I use df = df.groupby(pd.TimeGrouper(freq='15Min')) it works wrong, because it use also day. But I need to use only time.

Desire output

event_time            period
2017-01-17 00:12:50   1
2016-12-05 01:00:21   4
2016-12-04 01:14:36   4
2016-12-04 01:04:03   4
2016-12-04 02:28:23   10
2016-12-04 02:46:49   12
2016-12-04 01:58:04   8

How can I do that?

Body:
New solution with dt.hour and dt.minute:

df['label'] = df['event_time'].dt.hour * 4 + df['event_time'].dt.minute // 15 + 1
print (df)
           event_time  label
0 2017-01-17 00:12:50      1
1 2016-12-05 01:00:21      5
2 2016-12-04 01:14:36      5
3 2016-12-04 01:04:03      5
4 2016-12-04 02:28:23     10
5 2016-12-04 02:46:49     12
6 2016-12-04 01:58:04      8

Timings:

rng = pd.date_range('2017-04-03', periods=100000, freq='27T')
df = pd.DataFrame({'timestamp': rng})

df['label'] = df['timestamp'].dt.hour * 4 + df['timestamp'].dt.minute // 15 + 1
df['period'] = df.timestamp.apply(lambda ts: 1 + ts.hour * 4 + ts.minute // 15)
print (df)

In [172]: %timeit df['timestamp'].dt.hour * 4 + df['timestamp'].dt.minute // 15 + 1
10 loops, best of 3: 20.2 ms per loop

In [173]: %timeit df.timestamp.apply(lambda ts: 1 + ts.hour * 4 + ts.minute // 15)
1 loop, best of 3: 301 ms per loop

Old solution (working, but a bit complicated):

You can first convert datetimes to to_timedelta by strftime and then convert to seconds by total_seconds.

Then use cut or numpy.searchsorted:

df['tot'] = pd.to_timedelta(df['event_time'].dt.strftime('%H:%M:%S'))
              .dt.total_seconds()
              .astype(int)

#necessary add one group
bins = np.concatenate([np.arange(24 * 4) * 900, np.array([100000])])
labels = np.arange(1, 24 * 4 + 1)
df['label'] = pd.cut(df['tot'], bins=bins, labels=labels)

df = df.assign(label1=np.searchsorted(bins, df['tot']))
print (df)
           event_time    tot label  label1
0 2017-01-17 00:12:50    770     1       1
1 2016-12-05 01:00:21   3621     5       5
2 2016-12-04 01:14:36   4476     5       5
3 2016-12-04 01:04:03   3843     5       5
4 2016-12-04 02:28:23   8903    10      10
5 2016-12-04 02:46:49  10009    12      12
6 2016-12-04 01:58:04   7084     8       8

Similar solutions, only works with Series tot:

tot = pd.to_timedelta(df['event_time'].dt.strftime('%H:%M:%S'))
       .dt.total_seconds()
       .astype(int)

bins = np.concatenate([np.arange(24 * 4) * 900, np.array([100000])])
labels = np.arange(1, 24 * 4 + 1)
df['label'] = pd.cut(tot, bins=bins, labels=labels)

df = df.assign(label1=np.searchsorted(bins, tot))
print (df)
           event_time label  label1
0 2017-01-17 00:12:50     1       1
1 2016-12-05 01:00:21     5       5
2 2016-12-04 01:14:36     5       5
3 2016-12-04 01:04:03     5       5
4 2016-12-04 02:28:23    10      10
5 2016-12-04 02:46:49    12      12
6 2016-12-04 01:58:04     8       8


问:
Conditional cell formatting on SSRS pivot table
I created a pivot table in SQL that has report names along the left side, and hours (00:00, 00:01, etc.) along the top. The values in the table are the number of times each report has been used during that hour over the past three months. I've imported the table into SSRS, and I'm trying to create a heat map of sorts. I want to color the cells darker or lighter across the row based on the number in each cell compared to the value of cells across the row (cell that has the highest value will be the darkest colored).
I've tried following this guide to color the cells, but here the entire row is one field, while I have separate fields for each column. Is there a way to achieve this?

EDIT: Added picture of table design, and preview where coloring is done incorrectly

答:
I understand your problem better now...The function uses the min and max values of a column to determine the range from lightest to darkest, then it probably looks at what fraction of the range your actual value is. In your case where you have each column's data coming from a different cell it'll be a pain unless your columns are fixed and even then it's more trouble than it needs to be.

I would suggest the following.

DON'T PIVOT your data in SQL, we can do that really easily in SSRS, your dataset will be simpler too something like

```<code>ReportName   Hour   UsageCount
ReportA       0     8
ReportA       1     4
ReportC       22    18
</code>```

and so on...

Create a new report and add a matrix with reportName as the row group and hour as the column group. The data values will be UsageCount.

That's it for the report design, then just set the cells back ground based on your function but this time you can pass in Max(Fields!UsageCount.Value) etc as per the sample.

I've rushed this a bit so it if not clear, let me know and I'll post a clearer solution.

Body:
I understand your problem better now...The function uses the min and max values of a column to determine the range from lightest to darkest, then it probably looks at what fraction of the range your actual value is. In your case where you have each column's data coming from a different cell it'll be a pain unless your columns are fixed and even then it's more trouble than it needs to be.

I would suggest the following.

DON'T PIVOT your data in SQL, we can do that really easily in SSRS, your dataset will be simpler too something like

ReportName   Hour   UsageCount
ReportA       0     8
ReportA       1     4
ReportC       22    18

and so on...

Create a new report and add a matrix with reportName as the row group and hour as the column group. The data values will be UsageCount.

That's it for the report design, then just set the cells back ground based on your function but this time you can pass in Max(Fields!UsageCount.Value) etc as per the sample.

I've rushed this a bit so it if not clear, let me know and I'll post a clearer solution.


问:
Java generics - ArrayList initialization
It is known that arraylist init. should be like this

```<code>ArrayList<A> a = new ArrayList<A>();
ArrayList<Integer> a = new ArrayList<Number>(); // compile-time error
</code>```

so, why does java allow these ?

```<code>1. ArrayList<? extends Object> a1 = new ArrayList<Object>();
2. ArrayList<?> a2 = new ArrayList<Integer>();
</code>```

then, if they are correct why doesn't allow these ?

```<code>1. a1.add(3);
2. a2.add(3);
</code>```

the compiler message is : The method add(int, capture#1-of ? extends Object) in the type ArrayList is not applicable for the arguments (int)

more general

```<code>  1. a1.add(null e);
  2. a2.add(? e);
</code>```

I read about this but it is good to hear from you. thanks

the other amusing point is :

```<code> ArrayList<ArrayList<?>> a = new ArrayList<ArrayList<?>>(); // correct
 ArrayList<?> a = new ArrayList<?>(); // wrong. I know it's reason but I have some
question in my mind that mentioned above
</code>```

答:
The key lies in the differences between references and instances and what the reference can promise and what the instance can really do.

```<code>ArrayList<A> a = new ArrayList<A>();
</code>```

Here a is a reference to an instance of a specific type - exactly an array list of As.  More explicitly, a is a reference to an array list that will accept As and will produce As.  new ArrayList() is an instance of an array list of As, that is, an array list that will accept As and will produce As.

```<code>ArrayList<Integer> a = new ArrayList<Number>();
</code>```

Here, a is a reference to exactly an array list of Integers, i.e. exactly an array list that can accept Integers and will produce Integers.  It cannot point to an array list of Numbers.  That array list of Numbers can not meet all the promises of ArrayList<Integer> a (i.e. an array list of Numbers may produce objects that are not Integers, even though its empty right then).

```<code>ArrayList<Number> a = new ArrayList<Integer>();
</code>```

Here, declaration of a says that a will refer to exactly an array list of Numbers, that is, exactly an array list that will accept Numbers and will produce Numbers.  It cannot point to an array list of Integers, because the type declaration of a says that a can accept any Number, but that array list of Integers cannot accept just any Number, it can only accept Integers.

```<code>ArrayList<? extends Object> a= new ArrayList<Object>();
</code>```

Here a is a (generic) reference to a family of types rather than a reference to a specific type. It can point to any list that is member of that family.  However, the trade-off for this nice flexible reference is that they cannot promise all of the functionality that it could if it were a type-specific reference (e.g. non-generic).  In this case, a is a reference to an array list that will produce Objects. But, unlike a type-specific list reference, this a reference cannot accept any Object.  (i.e. not every member of the family of types that a can point to can accept any Object, e.g. an array list of Integers can only accept Integers.)

```<code>ArrayList<? super Integer> a = new ArrayList<Number>();
</code>```

Again, a is a reference to a family of types (rather than a single specific type).  Since the wildcard uses super, this list reference can accept Integers, but it cannot produce Integers. Said another way, we know that any and every member of the family of types that a can point to can accept an Integer.  However, not every member of that family can produce Integers.

PECS - Producer extends, Consumer super - This mnemonic helps you remember that using  extends means the generic type can produce the specific type (but cannot accept it). Using super means the generic type can consume (accept) the specific type (but cannot produce it).

```<code>ArrayList<ArrayList<?>> a
</code>```

An array list that holds references to any list that is a member of a family of array lists types.

```<code>= new ArrayList<ArrayList<?>>(); // correct
</code>```

An instance of an array list that holds references to any list that is a member of a family of array lists types.

```<code>ArrayList<?> a
</code>```

An reference to any array list (a member of the family of array list types).

```<code>= new ArrayList<?>()
</code>```

ArrayList<?> refers to any type from a family of array list types, but you can only instantiate a specific type.

See also How can I add to List<? extends Number> data structures?

Body:
It is known that arraylist init. should be like this

ArrayList a = new ArrayList();
ArrayList<Integer> a = new ArrayList<Number>(); // compile-time error

so, why does java allow these ?

1. ArrayList<? extends Object> a1 = new ArrayList<Object>();
2. ArrayList<?> a2 = new ArrayList<Integer>();

then, if they are correct why doesn't allow these ?

1. a1.add(3);
2. a2.add(3);

the compiler message is : The method add(int, capture#1-of ? extends Object) in the type ArrayList is not applicable for the arguments (int)

more general

  1. a1.add(null e);
  2. a2.add(? e);

I read about this but it is good to hear from you. thanks

the other amusing point is :

 ArrayList<ArrayList<?>> a = new ArrayList<ArrayList<?>>(); // correct
 ArrayList<?> a = new ArrayList<?>(); // wrong. I know it's reason but I have some
question in my mind that mentioned above

Body:
The key lies in the differences between references and instances and what the reference can promise and what the instance can really do.

ArrayList<A> a = new ArrayList<A>();

Here a is a reference to an instance of a specific type - exactly an array list of As.  More explicitly, a is a reference to an array list that will accept As and will produce As.  new ArrayList<A>() is an instance of an array list of As, that is, an array list that will accept As and will produce As.

ArrayList<Integer> a = new ArrayList<Number>();

Here, a is a reference to exactly an array list of Integers, i.e. exactly an array list that can accept Integers and will produce Integers.  It cannot point to an array list of Numbers.  That array list of Numbers can not meet all the promises of ArrayList<Integer> a (i.e. an array list of Numbers may produce objects that are not Integers, even though its empty right then).

ArrayList<Number> a = new ArrayList<Integer>();

Here, declaration of a says that a will refer to exactly an array list of Numbers, that is, exactly an array list that will accept Numbers and will produce Numbers.  It cannot point to an array list of Integers, because the type declaration of a says that a can accept any Number, but that array list of Integers cannot accept just any Number, it can only accept Integers.

ArrayList<? extends Object> a= new ArrayList<Object>();

Here a is a (generic) reference to a family of types rather than a reference to a specific type. It can point to any list that is member of that family.  However, the trade-off for this nice flexible reference is that they cannot promise all of the functionality that it could if it were a type-specific reference (e.g. non-generic).  In this case, a is a reference to an array list that will produce Objects. But, unlike a type-specific list reference, this a reference cannot accept any Object.  (i.e. not every member of the family of types that a can point to can accept any Object, e.g. an array list of Integers can only accept Integers.)

ArrayList<? super Integer> a = new ArrayList<Number>();

Again, a is a reference to a family of types (rather than a single specific type).  Since the wildcard uses super, this list reference can accept Integers, but it cannot produce Integers. Said another way, we know that any and every member of the family of types that a can point to can accept an Integer.  However, not every member of that family can produce Integers.

PECS - Producer extends, Consumer super - This mnemonic helps you remember that using  extends means the generic type can produce the specific type (but cannot accept it). Using super means the generic type can consume (accept) the specific type (but cannot produce it).

ArrayList<ArrayList<?>> a

An array list that holds references to any list that is a member of a family of array lists types.

= new ArrayList<ArrayList<?>>(); // correct

An instance of an array list that holds references to any list that is a member of a family of array lists types.

ArrayList<?> a

An reference to any array list (a member of the family of array list types).

= new ArrayList<?>()

ArrayList<?> refers to any type from a family of array list types, but you can only instantiate a specific type.

See also How can I add to List<? extends Number> data structures?


问:
How to access a protected method of superclass in a subclass?
I have parent-child classes in two different packages. I am overriding a method of protected type. I want to access super class protected method in subclass.

Consider below code:

```<code>package package1;

public class Super
{
    protected void demoMethod()
    {
        System.out.println("In super method");
    }
}

package package2;

import package1.Super;

public class Sub extends Super
{
    @Override
    protected void demoMethod()
    {
        System.out.println("In sub method");
    }

    public static void main(String[] args)
    {
        //code for accessing superclass demoMethod to print "In super method"
    }
}
</code>```

In the main method of sub class, I want to access super class demoMethod which prints "In super method". I know demoMethod won't be visible from sub class using super class object reference to call demoMethod.

Is it possible or not? If yes, how?

Consider me new to Java and provide answers replacing comment in main method.

答: In the child class use super.demoMethod() or just remove it altogether from the child class

Body:
I have parent-child classes in two different packages. I am overriding a method of protected type. I want to access super class protected method in subclass.

Consider below code:

package package1;

public class Super
{
    protected void demoMethod()
    {
        System.out.println("In super method");
    }
}

package package2;

import package1.Super;

public class Sub extends Super
{
    @Override
    protected void demoMethod()
    {
        System.out.println("In sub method");
    }

    public static void main(String[] args)
    {
        //code for accessing superclass demoMethod to print "In super method"
    }
}

In the main method of sub class, I want to access super class demoMethod which prints "In super method". I know demoMethod won't be visible from sub class using super class object reference to call demoMethod.

Is it possible or not? If yes, how?

Consider me new to Java and provide answers replacing comment in main method.


问:
Qooxdoo: Include tree into a form
I'm trying to include the tree widget into a form with the qooxdoo form controller. Please check the code in this playground example.

What I want to achieve is that on click on the Send-button only the id (or another property of the currently selected node in the tree) is being sent and not the whole model data (including all of its children) of the selected node.

Any ideas how to achieve that?

答:
Here is a small update of your playground example to get only the ID of the selected node using :</p>

```<code>formController.getModel().getId().getId()
</code>```

Title: Qooxdoo: Include tree into a form


问:
How can I update a json dictionary at various levels?
I need help updating a json -  dictionary value with variable keys.

Here is what I know works and the issue I am having.

Let’s say I do this:

```<code>print(my_json['convergedSystem']['endpoints'][0]['credentials'][0]['credentialElements']['username'])
</code>```

I get back Mike
Now if I do this:

```<code>my_json['convergedSystem']['endpoints'][0]['credentials'][0]['credentialElements']['username'] = ‘Carol’
</code>```

And do the same print:

```<code>print(my_json['convergedSystem']['endpoints'][0]['credentials'][0]['credentialElements']['username'])
</code>```

I get back Carol

That is just how I would expect it to work.
Problem is I don’t always know what those above index keys are or how many… I can get a list of them however.
Sometimes I may need to update

```<code>my_json['convergedSystem']['endpoints'][0]['credentials'][0]['credentialElements']['username']
</code>```

Other times it could be at a different level

```<code>my_json['convergedSystem']['credentials'][0]['credentialElements']['username']
</code>```

Or even

```<code>my_json['FullSystem'][switches]['endpoints'][2]['credentials'][0]['credentialElements']['username']
</code>```

How can I set that in code?
Again I will always have a list available to me like this:

```<code>['convergedSystem', 'endpoints', 0, 'credentials', 0, 'credentialElements', 'username']
</code>```

Or whatever it happens to be at that moment.
I know I will always be looking for ['credentialElements']['username'] at some point however

答:
Assuming your json name is my_json and say your list is named as keys and you want to update the value to your_updated_value:

```<code>val = my_json  # val contains reference to your json
for key in keys[0:-1]:  # iterate till the second last level
    val = val[key]
val[keys[-1]] = your_updated_value  # update the value
</code>```

Note that since val has the reference of my_json, it'll update my_json too.

Body:
I need help updating a json -  dictionary value with variable keys.

Here is what I know works and the issue I am having.

Let’s say I do this:

print(my_json['convergedSystem']['endpoints'][0]['credentials'][0]['credentialElements']['username'])

I get back Mike
Now if I do this:

my_json['convergedSystem']['endpoints'][0]['credentials'][0]['credentialElements']['username'] = ‘Carol’

And do the same print:

print(my_json['convergedSystem']['endpoints'][0]['credentials'][0]['credentialElements']['username'])

I get back Carol

That is just how I would expect it to work.
Problem is I don’t always know what those above index keys are or how many… I can get a list of them however.
Sometimes I may need to update

my_json['convergedSystem']['endpoints'][0]['credentials'][0]['credentialElements']['username']

Other times it could be at a different level

my_json['convergedSystem']['credentials'][0]['credentialElements']['username']

Or even

my_json['FullSystem'][switches]['endpoints'][2]['credentials'][0]['credentialElements']['username']

How can I set that in code?
Again I will always have a list available to me like this:

['convergedSystem', 'endpoints', 0, 'credentials', 0, 'credentialElements', 'username']

Or whatever it happens to be at that moment.
I know I will always be looking for ['credentialElements']['username'] at some point however

Body:
Assuming your json name is my_json and say your list is named as keys and you want to update the value to your_updated_value:

val = my_json  # val contains reference to your json
for key in keys[0:-1]:  # iterate till the second last level
    val = val[key]
val[keys[-1]] = your_updated_value  # update the value

Note that since val has the reference of my_json, it'll update my_json too.


问:
Design Pattern to add columns in database table dynamically
The user wants to add new fields in UI dynamically. This new field should get stored in database and they should be allowed to perform CRUD on it.

Now I can do this by specifying a XML but I wanted a better way where these new columns are searchable. Also the idea of firing ALTER statement and adding a new column seems wrong.

Can anyone help me with a design pattern on database server side of how to solve this problem?

答: Find out what the maximum number of user-added fields will be and add them before hand.  For example 'User1', 'User2', 'User3', 'User4'...etc.  You can then enable the fields on the UI based on some configurable settings.</p>