问:
error while trying to pass location cordinate from a list view to a map activity
i have a list view contains the locations coordinate (late,long) and i'm trying to pass them to a map activity to show it on map

this is on android studio and Kotlin

```<code>listView.setOnItemClickListener { parent, view, position, id ->

        val time = usersList.get(position).time
        val long:String = usersList.get(position).long
        val late :String = usersList.get(position).late
startActivity(Intent(this, MapsActivity2::class.java).putExtra("long",long).putExtra("late",late))
}
</code>```

```<code>class MapsActivity2 : AppCompatActivity(), OnMapReadyCallback {

private lateinit var mMap: GoogleMap

var long:String = intent.getStringExtra("long")
var late:String = intent.getStringExtra("late")

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_maps2)

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    val mapFragment = supportFragmentManager
        .findFragmentById(R.id.map) as SupportMapFragment
    mapFragment.getMapAsync(this)
}

override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap

    // Add a marker in Sydney and move the camera
    val sydney = LatLng(long.toDouble(), late.toDouble())
    mMap.addMarker(MarkerOptions().position(sydney).title("jh"))
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
}
</code>```

Process: com.example.firebase, PID: 32463
      java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.firebase/com.example.firebase.MapsActivity2}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3289)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3548)
          at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
          at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
          at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2155)
          at android.os.Handler.dispatchMessage(Handler.java:109)
          at android.os.Looper.loop(Looper.java:207)
          at android.app.ActivityThread.main(ActivityThread.java:7539)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:958)
       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
          at com.example.firebase.MapsActivity2.(MapsActivity2.kt:19)
          at java.lang.Class.newInstance(Native Method)
          at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
          at android.support.v4.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:43)
          at android.app.Instrumentation.newActivity(Instrumentation.java:1224)
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3274)

答:
you can get intent valeu after onCreate() like this way :
i would also suggest to avoid predefined keyword like long, because long is defined as a datatype</p>

```<code>var long:String = intent.getStringExtra("long")
var late:String = intent.getStringExtra("late")
</code>```

Body:
i have a list view contains the locations coordinate (late,long) and i'm trying to pass them to a map activity to show it on map

this is on android studio and Kotlin

listView.setOnItemClickListener { parent, view, position, id ->

        val time = usersList.get(position).time
        val long:String = usersList.get(position).long
        val late :String = usersList.get(position).late
startActivity(Intent(this, MapsActivity2::class.java).putExtra("long",long).putExtra("late",late))
}

class MapsActivity2 : AppCompatActivity(), OnMapReadyCallback {

private lateinit var mMap: GoogleMap

var long:String = intent.getStringExtra("long")
var late:String = intent.getStringExtra("late")

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_maps2)

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    val mapFragment = supportFragmentManager
        .findFragmentById(R.id.map) as SupportMapFragment
    mapFragment.getMapAsync(this)
}

override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap

    // Add a marker in Sydney and move the camera
    val sydney = LatLng(long.toDouble(), late.toDouble())
    mMap.addMarker(MarkerOptions().position(sydney).title("jh"))
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
}

Process: com.example.firebase, PID: 32463
      java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.firebase/com.example.firebase.MapsActivity2}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3289)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3548)
          at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
          at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
          at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2155)
          at android.os.Handler.dispatchMessage(Handler.java:109)
          at android.os.Looper.loop(Looper.java:207)
          at android.app.ActivityThread.main(ActivityThread.java:7539)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:958)
       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
          at com.example.firebase.MapsActivity2.(MapsActivity2.kt:19)
          at java.lang.Class.newInstance(Native Method)
          at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
          at android.support.v4.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:43)
          at android.app.Instrumentation.newActivity(Instrumentation.java:1224)
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3274)

Body:
you can get intent valeu after onCreate() like this way :
i would also suggest to avoid predefined keyword like long, because long is defined as a datatype

var long:String = intent.getStringExtra("long")
var late:String = intent.getStringExtra("late")


来源: stackexchange

问:
How to take input file, reverse word order, write to output file in C++

Take the contents of an input text file and write them in reverse order of words to an output file.  Your program can ignore line breaks.  You will need to use arrays.

(unnecessary crap removed)  Aaaaah, panic, please help!

EDIT:  What I have so far.  Still lost on how to reverse word order now.

```<code>//Kristen Korz
//CIS 22A
//This program reads an input file and writes the words in reverse order to an output file.

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    //create and link input...
    ifstream inputFile;
    inputFile.open("input.txt");
    //...and output files
    ofstream outputFile;
    outputFile.open("output.txt");

    //error message for file open fail
    if (inputFile.fail())
        cout << "Error opening the file.\n";

    //constant for max size
    const int MAXSIZE = 1024;
    //string array and temporary-use string
    string words[MAXSIZE];
    string str;
    //read words from input file
    for (int i = 0; (inputFile >> str) && (i < MAXSIZE); ++i)
    {
        words[i] = str;
    }
    inputFile.close();

    //for showing if read correctly
    cout << endl;
    for (int i = 0; i < MAXSIZE; ++i)
        cout << words[i] << endl;

    system("pause");
    return 0;
}
</code>```

What I've got successfully reads the input file word for word.  I can figure out everything except how to reverse the word order for then writing to output.txt
This is our first program reversing the order of things, yes.

EDIT 2:

Okay, so the best I can guess is this:

```<code>    //constant for max size
    const int MAXSIZE = 1024;
    //string array and temporary-use string
    string words[MAXSIZE];
    string str;                 //note: variables will be used for output loops too

    //read words from input file
    for (int i = 0; (inputFile >> str) && (i < MAXSIZE); ++i)
    {
        words[i] = str;
    }
    inputFile.close();

    //for showing if read correctly
    cout << endl;
    for (int i = 0; i < MAXSIZE; ++i)
        cout << words[i] << endl;

    //for writing in reverse word order to output file
    for (int i = MAXSIZE-1; (outputFile << str) && (i >= 0); --i)
    {
        words[i] = str;
    }
    outputFile.close();

    //for showing if written correctly
    for (int i= MAXSIZE-1; i >= 0; --i)
    {
        cout << words[i] << endl;
    }
</code>```

The input section works fine.  Output just repeats last word of input for each iteration.

EDIT 3:

Just kidding, everything except actual writing of output file works.  Output in the terminal is corrects by getting rid of the "-1" after MAXSIZE in the initialization.  Adjusting the code that writes the file in a similar way does not solve the repeating "works." (final word of input file) written to output.txt

EDIT 4:

Relevant code is now:

```<code>    //constant for max size
    const int MAXSIZE = 1024;
    //string array and temporary-use string
    string words[MAXSIZE];
    string str;                 //note: variables will be used for output loops too

    //read words from input file
    for (int i = 0; (inputFile >> str) && (i < MAXSIZE); ++i)
    {
        words[i] = str;
    }
    inputFile.close();

    //for showing if read correctly
    cout << endl;
    for (int i = 0; i < MAXSIZE; ++i)
        cout << words[i] << " ";

    //for writing in reverse word order to output file
    for (int i = MAXSIZE; (outputFile << str) && (i >= 0); --i)
    {
        words[i] = str;
    }
    outputFile.close();

    //for showing if written correctly
    for (int i = MAXSIZE; i >= 0; --i)
    {
        cout << words[i] << " ";
    }
</code>```

If I change i>=0 to i=0 (which I mistakenly typed first try) in for (int i = MAXSIZE; (outputFile << str) && (i >= 0); --i), then cout in terminal is perfect.  Can't figure out how to get output file to not be repeated "works." Why is it doing that?  Note: output to terminal optional, so I don't really care why that wants i assigned to 0 in previous for loop in terms of being able to finish the assignment

答:
Another algorithm:

Map the file into memory or read it into std::vector<char> or std::string.

Reverse each word individually with std::reverse.

Reverse the entire file with std::reverse.

Write the file back if it was read into a container.

ContentLicense: CC BY-SA 4.0

Body:
Take the contents of an input text file and write them in reverse order of words to an output file.  Your program can ignore line breaks.  You will need to use arrays.

(unnecessary crap removed)  Aaaaah, panic, please help!

EDIT:  What I have so far.  Still lost on how to reverse word order now.

//Kristen Korz
//CIS 22A
//This program reads an input file and writes the words in reverse order to an output file.

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    //create and link input...
    ifstream inputFile;
    inputFile.open("input.txt");
    //...and output files
    ofstream outputFile;
    outputFile.open("output.txt");

    //error message for file open fail
    if (inputFile.fail())
        cout << "Error opening the file.\n";

    //constant for max size
    const int MAXSIZE = 1024;
    //string array and temporary-use string
    string words[MAXSIZE];
    string str;
    //read words from input file
    for (int i = 0; (inputFile >> str) && (i < MAXSIZE); ++i)
    {
        words[i] = str;
    }
    inputFile.close();

    //for showing if read correctly
    cout << endl;
    for (int i = 0; i < MAXSIZE; ++i)
        cout << words[i] << endl;

    system("pause");
    return 0;
}

What I've got successfully reads the input file word for word.  I can figure out everything except how to reverse the word order for then writing to output.txt
This is our first program reversing the order of things, yes.

EDIT 2:

Okay, so the best I can guess is this:

    //constant for max size
    const int MAXSIZE = 1024;
    //string array and temporary-use string
    string words[MAXSIZE];
    string str;                 //note: variables will be used for output loops too

    //read words from input file
    for (int i = 0; (inputFile >> str) && (i < MAXSIZE); ++i)
    {
        words[i] = str;
    }
    inputFile.close();

    //for showing if read correctly
    cout << endl;
    for (int i = 0; i < MAXSIZE; ++i)
        cout << words[i] << endl;

    //for writing in reverse word order to output file
    for (int i = MAXSIZE-1; (outputFile << str) && (i >= 0); --i)
    {
        words[i] = str;
    }
    outputFile.close();

    //for showing if written correctly
    for (int i= MAXSIZE-1; i >= 0; --i)
    {
        cout << words[i] << endl;
    }

The input section works fine.  Output just repeats last word of input for each iteration.

EDIT 3:

Just kidding, everything except actual writing of output file works.  Output in the terminal is corrects by getting rid of the "-1" after MAXSIZE in the initialization.  Adjusting the code that writes the file in a similar way does not solve the repeating "works." (final word of input file) written to output.txt

EDIT 4:

Relevant code is now:

    //constant for max size
    const int MAXSIZE = 1024;
    //string array and temporary-use string
    string words[MAXSIZE];
    string str;                 //note: variables will be used for output loops too

    //read words from input file
    for (int i = 0; (inputFile >> str) && (i < MAXSIZE); ++i)
    {
        words[i] = str;
    }
    inputFile.close();

    //for showing if read correctly
    cout << endl;
    for (int i = 0; i < MAXSIZE; ++i)
        cout << words[i] << " ";

    //for writing in reverse word order to output file
    for (int i = MAXSIZE; (outputFile << str) && (i >= 0); --i)
    {
        words[i] = str;
    }
    outputFile.close();

    //for showing if written correctly
    for (int i = MAXSIZE; i >= 0; --i)
    {
        cout << words[i] << " ";
    }

If I change i>=0 to i=0 (which I mistakenly typed first try) in for (int i = MAXSIZE; (outputFile << str) && (i >= 0); --i), then cout in terminal is perfect.  Can't figure out how to get output file to not be repeated "works." Why is it doing that?  Note: output to terminal optional, so I don't really care why that wants i assigned to 0 in previous for loop in terms of being able to finish the assignment


问:
Django bulk update with string replace
I am trying to update and modify a string field Django's ORM.  The equivalent SQL to do this is:

```<code>UPDATE example_table SET string_field = REPLACE(string_field, 'old text', 'new text');
</code>```

With that query, I expect old text and old text more text to be replaced with new text and new text more text respectively, for all the entries in the string_field column.

Bulk update() seems promising, but doesn't allow me to modify only part of the field, and F() expressions only implement numeric changes, not string replace.  I also looked at using raw queries to run the above SQL, but that seems like a sideways hack (especially since F() exists to do the same functionality on numbers), and I couldn't get them to actually execute.

I ended up with this, but it seems a shame to execute all the extra queries when I know there's a one line SQL statement to do it.

```<code>for entry in ExampleModel.objects.all():
    entry.string_field = entry.string_field.replace('old text', 'new text', 1)
    entry.save()
</code>```

Does this feature not exist in Django's ORM for strings yet? Is there something I overlooked in the docs?

Related SO questions:

generate update query using django orm

SQL statement to remove part of a string

答:
New in Django 2.1 - Replace database function

Your example can now be expressed most easily via:

ExampleModel.objects.update(
    string_field=Replace('string_field', Value('old_text'), Value('new_text'))
)
```

ContentLicense: CC BY-SA 3.0

Title: Django bulk update with string replace

Body:
I am trying to update and modify a string field Django's ORM.  The equivalent SQL to do this is:

UPDATE example_table SET string_field = REPLACE(string_field, 'old text', 'new text');

With that query, I expect old text and old text more text to be replaced with new text and new text more text respectively, for all the entries in the string_field column.

Bulk update() seems promising, but doesn't allow me to modify only part of the field, and F() expressions only implement numeric changes, not string replace.  I also looked at using raw queries to run the above SQL, but that seems like a sideways hack (especially since F() exists to do the same functionality on numbers), and I couldn't get them to actually execute.

I ended up with this, but it seems a shame to execute all the extra queries when I know there's a one line SQL statement to do it.

for entry in ExampleModel.objects.all():
    entry.string_field = entry.string_field.replace('old text', 'new text', 1)
    entry.save()

Does this feature not exist in Django's ORM for strings yet? Is there something I overlooked in the docs?

Related SO questions:

generate update query using django orm

SQL statement to remove part of a string


问:
Slow UpdatePanel in ASP.NET application
I was trying to figure out why my UpdatePanel is so SLOW (after Button1's postback) in an ASP.NET application:

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="MyNamespace.WebForm1" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
        </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>
</code>```

code behind:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyNamespace
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)//this is slow!!
        {
            Button btn = sender as Button;
            btn.Text = DateTime.Now.ToString("hhmmssfff");
        }
    }
}
</code>```

I was searching here in StackOverflow but I couldn't find a straight forward answer.
Anyone knows something that might speed this up?

I've seen a faster UpdatePanel button postback when I run my webapplication using http://Junior-PC. But when I use http://localhost is pretty slower.

The only difference between a regular web application and this one is in Web application properties-> Web tab-> Servers section where is marked Use Local IIS Web Server-> Project Url: http://localhost/ and Override application root URL.

答:
Please try to use classic script manager:

```<code>asp:ScriptManager
</code>```

instead of:

```<code>cc1:ToolkitScriptManager.
</code>```

Morover please unregister AjaxControlToolkit because in this case it is unnecessary. Let us know it helps.

ContentLicense: CC BY-SA 2.5

Title: Slow UpdatePanel in ASP.NET application

Body:
I was trying to figure out why my UpdatePanel is so SLOW (after Button1's postback) in an ASP.NET application:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="MyNamespace.WebForm1" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">
        <cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
        </ContentTemplate>
        </asp:UpdatePanel>
    </form>

code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyNamespace
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)//this is slow!!
        {
            Button btn = sender as Button;
            btn.Text = DateTime.Now.ToString("hhmmssfff");
        }
    }
}

I was searching here in StackOverflow but I couldn't find a straight forward answer.
Anyone knows something that might speed this up?

I've seen a faster UpdatePanel button postback when I run my webapplication using http://Junior-PC. But when I use http://localhost is pretty slower.

The only difference between a regular web application and this one is in Web application properties-> Web tab-> Servers section where is marked Use Local IIS Web Server-> Project Url: http://localhost/ and Override application root URL.

Body:
Please try to use classic script manager:

asp:ScriptManager

instead of:

cc1:ToolkitScriptManager.

Morover please unregister AjaxControlToolkit because in this case it is unnecessary. Let us know it helps.


问:
How to convert a list located on a file to a list I can use in python?
I am trying to get a 3d list of RGB values located as text in a file and convert it to a normal list that I can use in Python.

The list on the file looks like this [[[1,0,0],[2,1,0]],[[0,1,0.5],[2,3,1.8]]].

What should I do to retrieve this list as as is, in order to use it in my code?

I tried to use functions such as split(), but I still cannot get the original list on the file because of the brackets.

Body:
Use JSON

import json
json.loads("[[[1,0,0],[2,1,0]],[[0,1,0.5],[2,3,1.8]]]")

gives you:

[[[1, 0, 0], [2, 1, 0]], [[0, 1, 0.5], [2, 3, 1.8]]]


答:
You can parse it as JSON.

In [1]: s = "[[[1,0,0],[2,1,0]],[[0,1,0.5],[2,3,1.8]]]"

In [2]: import json

In [3]: json.loads(s)
Out[3]: [[[1, 0, 0], [2, 1, 0]], [[0, 1, 0.5], [2, 3, 1.8]]]
```

<p>If you want to read it from a file:</p>

<pre class="lang-py prettyprint-override"><code>import json

f = open("file_path", "r")
your_list = json.load(f)
</code>```

Title: How to convert a list located on a file to a list I can use in python?

Body:
I am trying to get a 3d list of RGB values located as text in a file and convert it to a normal list that I can use in Python.

The list on the file looks like this [[[1,0,0],[2,1,0]],[[0,1,0.5],[2,3,1.8]]].

What should I do to retrieve this list as as is, in order to use it in my code?

I tried to use functions such as split(), but I still cannot get the original list on the file because of the brackets.

Body:
You can parse it as JSON.

In [1]: s = "[[[1,0,0],[2,1,0]],[[0,1,0.5],[2,3,1.8]]]"

In [2]: import json

In [3]: json.loads(s)
Out[3]: [[[1, 0, 0], [2, 1, 0]], [[0, 1, 0.5], [2, 3, 1.8]]]

If you want to read it from a file:

import json

f = open("file_path", "r")
your_list = json.load(f)


Body:
You can use ast.literal_eval in this case (doc):

from ast import literal_eval

txt = '[[[1,0,0],[2,1,0]],[[0,1,0.5],[2,3,1.8]]]'

l = literal_eval(txt)

print(l)

Prints:

[[[1, 0, 0], [2, 1, 0]], [[0, 1, 0.5], [2, 3, 1.8]]]


问:
Make a background image transparent using CSS
I have a scenario where I need a transparent background image but I have no control over the dynamically generated images I use. For that reason Transparent PNG is out of the question. All child elements within the same div should NOT be effected and should be fully visible.

I know how to apply transparency to background colours and block level elements but can you do this for a background image?

答:
IE uses filter:alpha(opacity=50); while others use opacity:.5

Just include them both.


答:
You might want to use the ast library:

import ast

ast.literal_eval("[[[1,0,0],[2,1,0]],[[0,1,0.5],[2,3,1.8]]]")

# [[[1, 0, 0], [2, 1, 0]], [[0, 1, 0.5], [2, 3, 1.8]]]
```

The benefit here being literal_eval will safely parse strings into python objects, and is not limited to json-specific syntax as the json module is

Body:
You might want to use the ast library:

import ast

ast.literal_eval("[[[1,0,0],[2,1,0]],[[0,1,0.5],[2,3,1.8]]]")

# [[[1, 0, 0], [2, 1, 0]], [[0, 1, 0.5], [2, 3, 1.8]]]

The benefit here being literal_eval will safely parse strings into python objects, and is not limited to json-specific syntax as the json module is


问:
BitLocker Values
I'm trying to get BitLocker information from a remote host. I used to do this using PowerShell (Get-BitLockerVolume) which would provide lots of useful information. When I try using C#, I don't get as much information back. Looking on Microsoft's website and from further research, I can't find anything to help me.

Does anyone know how to get the same output as Get-BitLockerVolume in C#?

By the way, this is what I've been testing within C#:

```<code>CimSession session = CimSession.Create(computerHostName);

IEnumerable<CimInstance> GI1 = session.QueryInstances(@"root\cimv2\Security\MicrosoftVolumeEncryption", "WQL", "SELECT * FROM Win32_EncryptableVolume");

foreach(CimInstance i in GI1)
{
    Console.WriteLine("MountPoint: {0}, Protection: {1}",
        i.CimInstanceProperties["DriveLetter"].Value,
        i.CimInstanceProperties["ProtectionStatus"].Value);
}
</code>```

答:
As Jeroen recalls, you will be able to get that information calling methods on your WMI instances. As for the docs, Win32_EncryptableVolume only exposes the following properties:

```<code>class Win32_EncryptableVolume
{
  string DeviceID;
  string PersistentVolumeID;
  string DriveLetter;
  uint32 ProtectionStatus;
};
</code>```

To easily get the information you need using WMI and method access, you can use ORMi library:

You can define for example your class like this:

```<code>public class Win32_EncryptableVolume : WMIInstance
{
  public string DeviceID {get; set;}
  public string PersistentVolumeID {get; set;}
  public string DriveLetter {get; set;}
  public int ProtectionStatus {get; set;}

  [WMIIgnore]
  public int Version {get; set;}

  public int GetVersion()
  {
     return WMIMethod.ExecuteMethod<int>(this)
  }
}
</code>```

Then you could do something like:

```<code>WmiHelper _helper = new WmiHelper("root\\Cimv2"); //Define the correct scope

List<Win32_EncryptableVolume> volumes = _helper.Query<Win32_EncryptableVolume>().ToList();

foreach(Win32_EncryptableVolume v in volumes)
{
    v.Version = v.GetVersion();
}
</code>```

Title: BitLocker Values

Body:
I'm trying to get BitLocker information from a remote host. I used to do this using PowerShell (Get-BitLockerVolume) which would provide lots of useful information. When I try using C#, I don't get as much information back. Looking on Microsoft's website and from further research, I can't find anything to help me.

Does anyone know how to get the same output as Get-BitLockerVolume in C#?

By the way, this is what I've been testing within C#:

CimSession session = CimSession.Create(computerHostName);

IEnumerable<CimInstance> GI1 = session.QueryInstances(@"root\cimv2\Security\MicrosoftVolumeEncryption", "WQL", "SELECT * FROM Win32_EncryptableVolume");

foreach(CimInstance i in GI1)
{
    Console.WriteLine("MountPoint: {0}, Protection: {1}",
        i.CimInstanceProperties["DriveLetter"].Value,
        i.CimInstanceProperties["ProtectionStatus"].Value);
}

Body:
As Jeroen recalls, you will be able to get that information calling methods on your WMI instances. As for the docs, Win32_EncryptableVolume only exposes the following properties:

class Win32_EncryptableVolume
{
  string DeviceID;
  string PersistentVolumeID;
  string DriveLetter;
  uint32 ProtectionStatus;
};

To easily get the information you need using WMI and method access, you can use ORMi library:

You can define for example your class like this:

public class Win32_EncryptableVolume : WMIInstance
{
  public string DeviceID {get; set;}
  public string PersistentVolumeID {get; set;}
  public string DriveLetter {get; set;}
  public int ProtectionStatus {get; set;}

  [WMIIgnore]
  public int Version {get; set;}

  public int GetVersion()
  {
     return WMIMethod.ExecuteMethod<int>(this)
  }
}

Then you could do something like:

WmiHelper _helper = new WmiHelper("root\\Cimv2"); //Define the correct scope

List<Win32_EncryptableVolume> volumes = _helper.Query<Win32_EncryptableVolume>().ToList();

foreach(Win32_EncryptableVolume v in volumes)
{
    v.Version = v.GetVersion();
}


问:
Alpaca slider not working
I am trying to run alpaca slider but I am not able to use it in my project with property slider= true any idea how can I make it work using alpaca only. Is any specific version of alpaca needed for this to work?

I am using following code:

```<code>$(function() {
    $("#field2").alpaca({
        "data": 18,
        "options": {
            "type": "integer",
            "label": "Snow Days:",
            "helper": "Number of Snow Days in January 2011",
            "slider": true
        },
        "schema": {
            "minimum": 1,
            "maximum": 31
        }
    });
});
</code>```

答:
With jquery UI version 1.12.1 and jquery version 1.12.4
"inputType": "range" in options json is working for me. This should work for you.

```<code>$(function() {
$("#field2").alpaca({
    "data": 18,
    "options": {
        "inputType": "range",
        "label": "Snow Days:",
        "helper": "Number of Snow Days in January 2011",
        "slider": true
    },
    "schema": {
        "minimum": 1,
        "maximum": 31
    }
});
</code>```

});

Title: Alpaca slider not working

Body:
I am trying to run alpaca slider but I am not able to use it in my project with property slider= true any idea how can I make it work using alpaca only. Is any specific version of alpaca needed for this to work?

I am using following code:

$(function() {
    $("#field2").alpaca({
        "data": 18,
        "options": {
            "type": "integer",
            "label": "Snow Days:",
            "helper": "Number of Snow Days in January 2011",
            "slider": true
        },
        "schema": {
            "minimum": 1,
            "maximum": 31
        }
    });
});

Body:
With jquery UI version 1.12.1 and jquery version 1.12.4
"inputType": "range" in options json is working for me. This should work for you.

$(function() {
$("#field2").alpaca({
    "data": 18,
    "options": {
        "inputType": "range",
        "label": "Snow Days:",
        "helper": "Number of Snow Days in January 2011",
        "slider": true
    },
    "schema": {
        "minimum": 1,
        "maximum": 31
    }
});

});


问:
Elm Html Bool as type variable
Can Elm Html have Bool type variable so instead of type annotation of

```<code>Html Msg
</code>```

have

```<code>Html Bool
</code>```

Does anybody knows? Thanks a lot to all.

答:
Yes. Elm Html uses the type Html msg (with a small caps msg). This means that msg can be whatever type.

In many code examples found online, msg is Msg. But that is just their choice, and they have defined Msg themselves somewhere else in the code.

In your code you can use any other type, like Bool.

Title: Elm Html Bool as type variable

Body:
Can Elm Html have Bool type variable so instead of type annotation of

Html Msg

have

Html Bool

Does anybody knows? Thanks a lot to all.


问:
How to change activity image and text according to listview item click in android studio ? java or kotlin
I'm making an android application for information of different places. There are more than 200 places. So creating each activity for each place is hard. So how can I change information of single activity according to listview item clicked?</p>

答:
Try to use arrays for your images and strings

```<code>String text[] = {"Text 1", "Text 2", "Text 3", ..............}
int[] images = {R.drawable.image1, R.drawable.image2, R.drawable.image3, ..............}
</code>```

Then on your listview's OnItemClickListener;

```<code>listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
      yourTextView.setText(text[position]);
      yourImageView.setImageResource(images[position]);
      }
 });
</code>```

Body:
Try to use arrays for your images and strings

String text[] = {"Text 1", "Text 2", "Text 3", ..............}
int[] images = {R.drawable.image1, R.drawable.image2, R.drawable.image3, ..............}

Then on your listview's OnItemClickListener;

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
      yourTextView.setText(text[position]);
      yourImageView.setImageResource(images[position]);
      }
 });


问:
calling a function within a function
I've had a look through several of the related questions and just can't seem to see the issue!

the following two functions are within my function include file and for some reason I cannot seem to get the check_orientation function to return scale to the display_months_news function.

I'm fairly sure I'm just missing something really obviously.

the display_news function

```<code>function display_months_news()
{
    //header('Content-type: image/jpeg');
    $year = date("y");
    $year = "20" .$year;
    $month = date("m");
    if ($month) {
        switch ($month){
            case "01": $month = "January"; break;
            case "02": $month = "February"; break;
            case "03": $month = "March"; break;
            case "04": $month = "April"; break;
            case "05": $month = "May"; break;
            case "06": $month = "June"; break;
            case "07": $month = "July"; break;
            case "08": $month = "August"; break;
            case "09": $month = "September"; break;
            case "10": $month = "October"; break;
            case "11": $month = "November"; break;
            case "12": $month = "December"; break;
        }
    } else {
        echo '<p>The date field is empty.</p>';
    }
    $nowdate = $month." ".$year;

    $result = mysql_query("SELECT * FROM news ORDER BY sqldate DESC LIMIT 6") or die(mysql_error());

    while ($row = mysql_fetch_array($result)) {
        global $imgurl;
        $imgurl = $row['img1'];

        check_orientation4($imgurl);

        $comcount = comment_count($row['nid']);
        if ($comcount == NULL) {$comcount = 0;}

        echo '<div class="news-preview-container">';
        echo '<div class="news-preview-container-date">';
        echo "<P>" .$row['mmonth']. " ".$row['dday']. ", " .$row['yyear']. "</p><BR>";
        echo '</div>';
        echo '<div class="news-preview-container-title">';
        echo "<p><a href='article.php?id=" .$row['nid']."'>" .$row['title']."</a></p><BR>";
        echo '</div>';
        echo '<div class="news-preview-container-inner">';
        echo '<div class="news-preview-container-text">';
        echo '<p>'.ShortenText($row['body']).'</p>';
        echo '</div>';
        echo '<div class="news-preview-container-image"><img src="'.$imgurl.'"'.$scale.'"></div><BR></div>';
        echo '<div class="news-preview-container-bottombar">Posted in '.$row[tag].' / '.$comcount.' Comments</div>';
        echo '</div>';

    }
}
</code>```

and the check_orientation function

```<code>function check_orientation4($imgurls){

if ($imgurls == NULL){ echo "";  }
else {
        $imgurlshrunk = NULL;
        $maxsize = 120;
        $filename = NULL;
        $height = NULL;
        $width = NULL;
        $scale = NULL;
        $imgurlshrunk = $imgurls;
        $filename = basename($imgurlshrunk);
        $filename = "admin/uploads/" . $filename;
        list($width,$height,$type,$attr) = getimagesize("$filename");
        $wRatio = $maxsize / $width;
        $hRatio= $maxsize / $height;

    global $scale;

    if ( ($width <= $maxsize) && ($height <= $maxsize))
      {

        $scale = "";
        return $scale;
      }
    elseif ( ($wRatio * $height) < $maxsize)
    {
        $scale = "width = '100%'";
        return $scale;
    }
    elseif  ($height == NULL)
    {

        echo "empty height";
    }
    else
    {
    global $height;
        $scale = "height = '100%'";
        return $scale;
    }       }}
</code>```

Thanks in advance to whoever points out the silly mistake i'm missing!

答: Because you're discarding the return value from check_orientation4, perhaps?</p>

Title: calling a function within a function

Body:
I've had a look through several of the related questions and just can't seem to see the issue!

the following two functions are within my function include file and for some reason I cannot seem to get the check_orientation function to return scale to the display_months_news function.

I'm fairly sure I'm just missing something really obviously.

the display_news function

function display_months_news()
{
    //header('Content-type: image/jpeg');
    $year = date("y");
    $year = "20" .$year;
    $month = date("m");
    if ($month) {
        switch ($month){
            case "01": $month = "January"; break;
            case "02": $month = "February"; break;
            case "03": $month = "March"; break;
            case "04": $month = "April"; break;
            case "05": $month = "May"; break;
            case "06": $month = "June"; break;
            case "07": $month = "July"; break;
            case "08": $month = "August"; break;
            case "09": $month = "September"; break;
            case "10": $month = "October"; break;
            case "11": $month = "November"; break;
            case "12": $month = "December"; break;
        }
    } else {
        echo '
The date field is empty.
';
    }
    $nowdate = $month." ".$year;

    $result = mysql_query("SELECT * FROM news ORDER BY sqldate DESC LIMIT 6") or die(mysql_error());

    while ($row = mysql_fetch_array($result)) {
        global $imgurl;
        $imgurl = $row['img1'];

        check_orientation4($imgurl);

        $comcount = comment_count($row['nid']);
        if ($comcount == NULL) {$comcount = 0;}

        echo '
';
        echo '
';
        echo "
" .$row['mmonth']. " ".$row['dday']. ", " .$row['yyear']. "

";
        echo '
';
        echo '
';
        echo "
" .$row['title']."

";
        echo '
';
        echo '
';
        echo '
';
        echo '
'.ShortenText($row['body']).'
';
        echo '
';
        echo '

';
        echo '
Posted in '.$row[tag].' / '.$comcount.' Comments
';
        echo '
';

    }
}

and the check_orientation function

function check_orientation4($imgurls){

if ($imgurls == NULL){ echo "";  }
else {
        $imgurlshrunk = NULL;
        $maxsize = 120;
        $filename = NULL;
        $height = NULL;
        $width = NULL;
        $scale = NULL;
        $imgurlshrunk = $imgurls;
        $filename = basename($imgurlshrunk);
        $filename = "admin/uploads/" . $filename;
        list($width,$height,$type,$attr) = getimagesize("$filename");
        $wRatio = $maxsize / $width;
        $hRatio= $maxsize / $height;

    global $scale;

    if ( ($width <= $maxsize) && ($height <= $maxsize))
      {

        $scale = "";
        return $scale;
      }
    elseif ( ($wRatio * $height) < $maxsize)
    {
        $scale = "width = '100%'";
        return $scale;
    }
    elseif  ($height == NULL)
    {

        echo "empty height";
    }
    else
    {
    global $height;
        $scale = "height = '100%'";
        return $scale;
    }       }}

Thanks in advance to whoever points out the silly mistake i'm missing!


问:
Round Robin method of mixing of two lists in python
If input is

```<code>round_robin(range(5), "hello")
</code>```

I need output as

```<code>[0, 'h', 1, 'e', 2, 'l', 3, 'l', 4, 'o']
</code>```

I tried

```<code>def round_robin(*seqs):
list1=[]
length=len(seqs)
list1= cycle(iter(items).__name__ for items in seqs)
while length:
    try:
        for x in list1:
            yield x
    except StopIteration:
        length -= 1

pass
</code>```

but it gives error as

```<code>AttributeError: 'listiterator' object has no attribute '__name__'
</code>```

How to modify the code to get the desired output?

答:
from itertools import cycle

A = [[1,2,3],[4,5,6],[7]]

B = [[8],[9,10,11],[12,13]]

for p in A:

```<code>max1 = len(p) if  max1 <len(p) else max1
</code>```

for p in B:

```<code>max1 = len(p) if  max1 <len(p) else max1
</code>```

i = len(A)

j = 0

C = []

list_num = cycle(k for k in range(i))

for x in list_num:

```<code>j += 1

if j == i*3:

    break

if A[x]:

    C.append(A[x].pop(0))

if B[x]:

    C.append(B[x].pop(0))
</code>```

Output=====> [1, 8, 4, 9, 7, 12, 2, 5, 10, 13, 3, 6, 11]

Body:
If input is

round_robin(range(5), "hello")

I need output as

[0, 'h', 1, 'e', 2, 'l', 3, 'l', 4, 'o']

I tried

def round_robin(*seqs):
list1=[]
length=len(seqs)
list1= cycle(iter(items).__name__ for items in seqs)
while length:
    try:
        for x in list1:
            yield x
    except StopIteration:
        length -= 1

pass

but it gives error as

AttributeError: 'listiterator' object has no attribute '__name__'

How to modify the code to get the desired output?

Body:
from itertools import cycle

A = [[1,2,3],[4,5,6],[7]]

B = [[8],[9,10,11],[12,13]]

for p in A:

max1 = len(p) if  max1 <len(p) else max1

for p in B:

max1 = len(p) if  max1 <len(p) else max1

i = len(A)

j = 0

C = []

list_num = cycle(k for k in range(i))

for x in list_num:

j += 1

if j == i*3:

    break

if A[x]:

    C.append(A[x].pop(0))

if B[x]:

    C.append(B[x].pop(0))

Output=====> [1, 8, 4, 9, 7, 12, 2, 5, 10, 13, 3, 6, 11]


问:
Truncate span inside td
I'm using Materialize classes to create a "photo placeholder" to the user which contains the first letter of his name.

I'm having trouble with long names inside the  tag. I do not want the name to break when it's too long. Because of that, I've tried to apply class="truncate" into the spam that contains the name, but it failed to truncate.

How can I solve this?

main {
  padding: 16px;
}

table {
  table-layout: fixed;
}

td {
  width: 33.33%;
}

.photo-placeholder {
  width: 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 50%;
  text-align: center;
  display: inline-block;
  background-color: crimson;
  color: white;
}

.truncate {
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

<main>

  <table id="table1" class="white z-depth-1 centered">
    <thead>
      <tr>
        <th>Col 1</th>
        <th>Col 2</th>
        <th>Col 3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td data-label="Col 1">
          <span class="photo-placeholder">P</span>
          <span class="truncate">Pedro Luis Arend Gonçalves</span>
        </td>
        <td data-label="Col 2">Info 2</td>
        <td data-label="Col 3">Info 3</td>
      </tr>
    </tbody>
  </table>

</main></code>```

JSFiddle

Expected result:

答:
Fiddle Try adding the following CSS:</p>

```<code>.photo-placeholder {
  margin: 10px;
  min-width: 40px;
}

table.centered tbody tr td:first-child {
  display: flex;
  width: 100%;
  align-items: center;
  justify-content: center;
}
</code>```

Title: Truncate span inside td

Body:
I'm using Materialize classes to create a "photo placeholder" to the user which contains the first letter of his name.

I'm having trouble with long names inside the  tag. I do not want the name to break when it's too long. Because of that, I've tried to apply class="truncate" into the spam that contains the name, but it failed to truncate.

How can I solve this?

main {
  padding: 16px;
}

table {
  table-layout: fixed;
}

td {
  width: 33.33%;
}

.photo-placeholder {
  width: 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 50%;
  text-align: center;
  display: inline-block;
  background-color: crimson;
  color: white;
}

.truncate {
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />

        Col 1
        Col 2
        Col 3

          P
          Pedro Luis Arend Gonçalves

        Info 2
        Info 3

JSFiddle

Expected result:

Body:
Fiddle Try adding the following CSS:

.photo-placeholder {
  margin: 10px;
  min-width: 40px;
}

table.centered tbody tr td:first-child {
  display: flex;
  width: 100%;
  align-items: center;
  justify-content: center;
}


问:
How do I turn a LED on and off based on input from a PIR motion sensor?
I am trying to turn a LED on and off using an Arduino Uno. I'm using a PIR motion sensor as the input. I want the LED to turn off when the PIR sensor is not detecting anything. However, once it reads a value from pin 12 it just stays on even if the PIR sensor is not detecting anything.

My code:

```<code>value=readDigitalPin(a,'D12')

while value==1
      writePWMVoltage (a, 'D6', 3)
end

while value==0
      writePWMVoltage (a, 'D6', 0)
end
</code>```

答:
Because there is a MATLAB tag and some of the syntax, I am assuming you are using the MATLAB Support package for Arduino. If you are, try the following: </p>

```<code>while true
    value=readDigitalPin(a,'D12');
    if value==1
       writePWMVoltage (a, 'D6', 3)
    else
       writePWMVoltage (a, 'D6', 0)
    end
end
</code>```

<p>Note that this code is going to run on an infinite loop as well, feel free to use a digital pin and a push button to break the loop. </p>

Body:
I am trying to turn a LED on and off using an Arduino Uno. I'm using a PIR motion sensor as the input. I want the LED to turn off when the PIR sensor is not detecting anything. However, once it reads a value from pin 12 it just stays on even if the PIR sensor is not detecting anything.

My code:

value=readDigitalPin(a,'D12')

while value==1
      writePWMVoltage (a, 'D6', 3)
end

while value==0
      writePWMVoltage (a, 'D6', 0)
end

Body:
Because there is a MATLAB tag and some of the syntax, I am assuming you are using the MATLAB Support package for Arduino. If you are, try the following:

while true
    value=readDigitalPin(a,'D12');
    if value==1
       writePWMVoltage (a, 'D6', 3)
    else
       writePWMVoltage (a, 'D6', 0)
    end
end

Note that this code is going to run on an infinite loop as well, feel free to use a digital pin and a push button to break the loop.


问:
Advantage of gsl assert vs assert in c++?
I know the use of assert in C++. Wanted to know is there any difference between and any benefit(I think assert is costlier according as mentioned in https://www.learncpp.com/cpp-tutorial/7-12a-assert-and-static_assert/ so performance wise, are both same?) in using gsl_assert over assert? Why gsl_assert was added in gsl library since there is already assert support in c++(even though assert came from 'C', since we add #include<cassert> for using assert in C++)?

```<code>#include <iostream>
#include <gsl/gsl_assert>
using namespace std;

int main()
{
    int val;
    cin >> val;
    Ensures( val > 5 );
    return 0;
}
</code>```

答:
It's not a question of performance; it's a question of flexibility.

C assert

This just terminates (in debug builds) if the condition is true, and usually does nothing in release builds.

GSL contract check

Depending on configuration, this can:

Throw an exception

Terminate

Do nothing

…except signal to the optimiser that we expect the condition to hold (if supported)

In some configuration modes, I suppose GSL's Expects and Ensures macros end up doing pretty much the same thing as assert. But not in all.

It's worth noting, though, that the GSL behaviour appears not to be dependent on build configuration (debug vs release). I guess (and I am only guessing) that, for performance-critical code, a sensible project maintainer would choose mode #1 or #2 in debug builds, and #3 (or possibly #2) in release builds.

Body:
I know the use of assert in C++. Wanted to know is there any difference between and any benefit(I think assert is costlier according as mentioned in https://www.learncpp.com/cpp-tutorial/7-12a-assert-and-static_assert/ so performance wise, are both same?) in using gsl_assert over assert? Why gsl_assert was added in gsl library since there is already assert support in c++(even though assert came from 'C', since we add #include<cassert> for using assert in C++)?

#include <iostream>
#include <gsl/gsl_assert>
using namespace std;

int main()
{
    int val;
    cin >> val;
    Ensures( val > 5 );
    return 0;
}


问:
Linker error after upgrading to Xcode 4
my code was working well with sdk 4.2 but while upgrading the sdk and the xcode to 4 it raise error apple mach-o error

and this is its details

bad codegen, pointer diff in
  itk::ProcessAborted::ProcessAborted(char
  const*, unsigned int)to global weak
  symbol vtable for
  itk::ProcessAbortedfor architecture
  armv7 collect2: ld returned 1 exit
  status Command
  /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/g++-4.2
  failed with exit code 1

any suggestion to solve this issue ,

itk is a library I built using xcode and g++4.2

答:
Try File > Workspace Settings ( or Project Settings ) and enter the following settings:

Derived Data (index, logs, build) Location

Custom > Workspace-relative path > 'DerivedData'

Build Location

Place build products in derived data location

Custom Subfolder

This worked for me as my nested projects/libraries we not getting linked properly.

Title: Linker error after upgrading to Xcode 4


问:
jquery inserted HTML is rendered as a raw text
I have weird situation, I have that string

```<code>lorem<br/><br/>ipsum<br/><br/>a<br/>b<br/><br/>c
</code>```

which is put into a div:

```<code>$('div.desc').html(that_string);
</code>```

or

```<code>$('div.desc').html($.parseHTML(that_string));
</code>```

but in both cases it is being rendered as a raw text:

```<code>lorem<br/><br/>ipsum<br/><br/>a<br/>b<br/><br/>c
</code>```

instead of

```<code>lorem

ipsum

a
b

c
</code>```

Why ?

答:
I had a similar problem with jQuery where raw HTML was being rendered as text. I fixed it by doing the following:

Target: var txt =
 Hello World

$(#class).text(txt) to

$(#class).html(txt)

Now the content is being displayed on the website as HTML.

Body:
I have weird situation, I have that string

lorem

ipsum

a
b

c

which is put into a div:

$('div.desc').html(that_string);

or

$('div.desc').html($.parseHTML(that_string));

but in both cases it is being rendered as a raw text:

lorem

ipsum

a
b

c

instead of

lorem

ipsum

a
b

c

Why ?

Body:
I had a similar problem with jQuery where raw HTML was being rendered as text. I fixed it by doing the following:

Target: var txt = <h3> Hello <b>World</b><h3>

$(#class).text(txt) to

$(#class).html(txt)

Now the content is being displayed on the website as HTML.


问:
Is there a way to get the status of a thermal printer using ESC commands?
I am adding a method to the library escpos-coffee, which returns the status of a thermal printer, i.e. whether it is online/offline, whether the paper is ending or the paper is finished, or whether the cash drawer is open/closed.

I have added a method "showPrinterStatus" to the escpos-coffee library, which is based on the ESC c 3 command, which sends the command to the printer in byte form. The Method supposedly enables the Roll paper near end sensor, as well as the Roll paper end sensor. Furthermore, I have added another method "transmitStatus", based on the GS r command, which transmits the paper sensor status for n=1 and n=49, and the status of the cash drawer for n=2 and n=50. Here's the code:

```<code> /**
     *
     * @param nSignal
     * @return
     * @throws IOException
     * Method decides whether the printer should return an output paper-end signal to a parallel interface or not
     * input 1,2 4,8 to enable, 0 to disable
     */

    public EscPos showPrinterStatus(int nSignal)  throws IOException {
        write(27);
        write('c');
        write('3');
        write(nSignal);
        return this;
    }

    /**
     *
     * @param n
     * @return
     * @throws IOException
     * returns the status of the printer, 1 or 49 returns paper sensor status, 2 or 50 returns drawer kick-out connector status
     */
    public EscPos transmitStatus(int n) throws IOException{
      write(29);
      write('r');
      return this;
    }
</code>```

I am using Device Monitoring Studio, and excpected that there would be some visible communication. It looks like the showPrinterStatus Method is sending a signal to the thermal printer, but the transmitStatus method doesn't seem to cause any communication at all. Also, if I check the cash drawer status und leave the cash drawer open, there is no communication at all, and the request is simply queued. Once I push the cash drawer back in, it takes 5-10 minutes for the command to be executed by the printer, which is still in the queue all this time.

Is there something I am forgetting in my implementation, or is there a better way than Device Monitoring Studio, to display the printer status?

答:
I had the same problem, but I was connected via the usb, try with the serial port and then read from it. Im not a java developer but here is my solution in python

```<code>from serial import Serial
serial = Serial('/dev/ttyUSB0', 115200, timeout=.03)
serial.write(b'\x10\x04\x01')
serial.read()
</code>```

another approach is via the terminal(if you are using linux)

```<code>echo -n '\x10\x04\x01' > /dev/usb/lp0 #assuming lp0 is your printer

cat /dev/usb/lp0
</code>```

it outputs the data in the buffer it does not print it on the paper

Body:
I am adding a method to the library escpos-coffee, which returns the status of a thermal printer, i.e. whether it is online/offline, whether the paper is ending or the paper is finished, or whether the cash drawer is open/closed.

I have added a method "showPrinterStatus" to the escpos-coffee library, which is based on the ESC c 3 command, which sends the command to the printer in byte form. The Method supposedly enables the Roll paper near end sensor, as well as the Roll paper end sensor. Furthermore, I have added another method "transmitStatus", based on the GS r command, which transmits the paper sensor status for n=1 and n=49, and the status of the cash drawer for n=2 and n=50. Here's the code:

 /**
     *
     * @param nSignal
     * @return
     * @throws IOException
     * Method decides whether the printer should return an output paper-end signal to a parallel interface or not
     * input 1,2 4,8 to enable, 0 to disable
     */

    public EscPos showPrinterStatus(int nSignal)  throws IOException {
        write(27);
        write('c');
        write('3');
        write(nSignal);
        return this;
    }

    /**
     *
     * @param n
     * @return
     * @throws IOException
     * returns the status of the printer, 1 or 49 returns paper sensor status, 2 or 50 returns drawer kick-out connector status
     */
    public EscPos transmitStatus(int n) throws IOException{
      write(29);
      write('r');
      return this;
    }

I am using Device Monitoring Studio, and excpected that there would be some visible communication. It looks like the showPrinterStatus Method is sending a signal to the thermal printer, but the transmitStatus method doesn't seem to cause any communication at all. Also, if I check the cash drawer status und leave the cash drawer open, there is no communication at all, and the request is simply queued. Once I push the cash drawer back in, it takes 5-10 minutes for the command to be executed by the printer, which is still in the queue all this time.

Is there something I am forgetting in my implementation, or is there a better way than Device Monitoring Studio, to display the printer status?

Body:
I had the same problem, but I was connected via the usb, try with the serial port and then read from it. Im not a java developer but here is my solution in python

from serial import Serial
serial = Serial('/dev/ttyUSB0', 115200, timeout=.03)
serial.write(b'\x10\x04\x01')
serial.read()

another approach is via the terminal(if you are using linux)

echo -n '\x10\x04\x01' > /dev/usb/lp0 #assuming lp0 is your printer

cat /dev/usb/lp0

it outputs the data in the buffer it does not print it on the paper


问:
JPA @JoinColumn custom object type
I'm studying a project that uses JPA, which I'm pretty new at. I've encountered a logic that I'm not understanding quite well. I have an entity called A that has this field/column:

```<code>@Column(name = "COD_UOP_COO")
    private String codUopCoo;
</code>```

then I have, in the same entity:

```<code>    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "COD_UOP_COO", referencedColumnName = "COD_UOP")
    @BatchFetch(value = BatchFetchType.JOIN)
    private B b;
</code>```

From what I understood, this means that b field is retrieved by joining the tables A and B on the fields specified in JoinColumn annotation, right? But how does the join work in this case? Is JPA retrieving an entity of the right-side of join clause?

Then I have this named query:

```<code>"select a from A a where (a.b.bfield = :parameter)"
</code>```

what does this mean? Why are they checking equality on a field of entity B? In my table A I do not have any column that is foreign key with B. And b field is not a column in table A. So which column value of A am I checking? I'm missing the link with database structure.

答:
The JPQL query is translatet to a SQL query.

This query return A objects where A.COD_UOP_COO = B.COD_UOP and B.bfield = parameter. Change bfield for the database column name of the element in the B Class.

You can see the nateive query adding this parameters to the persistence.xml:

```<code><property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="true"/>
</code>```

Title: JPA @JoinColumn custom object type

Body:
I'm studying a project that uses JPA, which I'm pretty new at. I've encountered a logic that I'm not understanding quite well. I have an entity called A that has this field/column:

@Column(name = "COD_UOP_COO")
    private String codUopCoo;

then I have, in the same entity:

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "COD_UOP_COO", referencedColumnName = "COD_UOP")
    @BatchFetch(value = BatchFetchType.JOIN)
    private B b;

From what I understood, this means that b field is retrieved by joining the tables A and B on the fields specified in JoinColumn annotation, right? But how does the join work in this case? Is JPA retrieving an entity of the right-side of join clause?

Then I have this named query:

"select a from A a where (a.b.bfield = :parameter)"

what does this mean? Why are they checking equality on a field of entity B? In my table A I do not have any column that is foreign key with B. And b field is not a column in table A. So which column value of A am I checking? I'm missing the link with database structure.

Body:
The JPQL query is translatet to a SQL query.

This query return A objects where A.COD_UOP_COO = B.COD_UOP and B.bfield = parameter. Change bfield for the database column name of the element in the B Class.

You can see the nateive query adding this parameters to the persistence.xml:

<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="true"/>


问:
Push view controller not appearing below tab bar controller
I have embed the login screen to navigation controller and i use only push method to go to another view when user logs in and all.
When the user press login button, the tab bar controller containing 4 tabs are pushed and viewed.
Default screen is named home which contains two buttons inside the view.
When the user press each button,it should take the user to another view controller without hiding the tab bar below,and it should be the same looking tab bar (my tab bar is transparent).

Problem here is when ever i press the button,Entire view is changed which means the new view controller is presented over top of the tab bar.

I am confused about the navigation controller stuff.
Is there any requirement for any connection between view controllers since i am using push method.I am not using segue from storyboard.
Everything is programatic.

Please help me to fix this out.

答:
It happens when you push your viewController into your navigationController or present your viewController modally. You should just change your tabbarController's seletedIndex when you tap the button.

```<code>tabBarController.selectedIndex = #index of your controller#
</code>```

Body:
It happens when you push your viewController into your navigationController or present your viewController modally. You should just change your tabbarController's seletedIndex when you tap the button.

tabBarController.selectedIndex = #index of your controller#


问:
Single selection is not working in UITableview
I am just changing my Image on UIButton When I am tapping on cell . The function is calling but Image is not changing . And I want to do Single Selection.

```<code>
 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! PaymentCell
        cell.btnCheckUnCheck.setImage(UIImage(named: "CheckTerm"), for: .normal)
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! PaymentCell
        cell.btnCheckUnCheck.setImage(UIImage(named: "uncheckTerm"), for: .normal)
        tableview.reloadData()
    }

</code>```

I just want to change image on cell click with a single selection

答:
Use a property in view controller which will store the detail of the currently selected index.

```<code>var selectedIndexPath : IndexPath?
</code>```

In cellForRowAt method of UITableView

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! PaymentCell
            if selectedIndexPath != nil && indexPath == selectedIndexPath {
                cell.btnCheckUnCheck.setImage(UIImage(named: "CheckTerm"), for: .normal)
            } else {
                cell.btnCheckUnCheck.setImage(UIImage(named: "uncheckTerm"), for: .normal)
            }
        return cell
    }
</code>```

Change below method as

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedIndexPath = indexPath
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        selectedIndexPath = nil
    }
</code>```

This will not cause any reloading cells related issues.
Hope this helps.

Body:
I am just changing my Image on UIButton When I am tapping on cell . The function is calling but Image is not changing . And I want to do Single Selection.

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! PaymentCell
        cell.btnCheckUnCheck.setImage(UIImage(named: "CheckTerm"), for: .normal)
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! PaymentCell
        cell.btnCheckUnCheck.setImage(UIImage(named: "uncheckTerm"), for: .normal)
        tableview.reloadData()
    }

I just want to change image on cell click with a single selection

Body:
Use a property in view controller which will store the detail of the currently selected index.

var selectedIndexPath : IndexPath?

In cellForRowAt method of UITableView

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! PaymentCell
            if selectedIndexPath != nil && indexPath == selectedIndexPath {
                cell.btnCheckUnCheck.setImage(UIImage(named: "CheckTerm"), for: .normal)
            } else {
                cell.btnCheckUnCheck.setImage(UIImage(named: "uncheckTerm"), for: .normal)
            }
        return cell
    }

Change below method as

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedIndexPath = indexPath
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        selectedIndexPath = nil
    }

This will not cause any reloading cells related issues.
Hope this helps.


问:
C locale in string.punctuation
Upon reading string — Common string operations — Python 3.7.3 documentation

It states that

string.punctuation¶

  String of ASCII characters which are considered punctuation characters in the C locale.

What does C locale mean here?

答:
According to the locale documentation, 'C' is the default locale : https://docs.python.org/2/library/locale.html

It seems that this behaviour is inherited from the C language.

Title: C locale in string.punctuation


问:
Repeated Items in RecyclerView
I am having problems with repeated items in RecyclerView. Whenever I upload to my firebase and open the main activity again there are repeated itmes in the recyclerView from the previous load. How do I remove repeated items from my recyclerView.

Code for my Main Activity is

```<code>private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;

private DatabaseReference mDatabaseReference;
private List<Upload> mUploads;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_posts);
    setupBottomNavigation();

    mRecyclerView = findViewById(R.id.recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    mUploads = new ArrayList<>();

    mDatabaseReference = FirebaseDatabase.getInstance().getReference("uploads");

    mDatabaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot postSnapshot : dataSnapshot.getChildren())
            {
                Upload upload = postSnapshot.getValue(Upload.class);
                mUploads.add(upload);
            }
            mAdapter = new RecyclerViewAdapter(MainActivity.this, mUploads);
            mRecyclerView.setAdapter(mAdapter);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

    Button btn_post = (Button) findViewById(R.id.post_Main);
    btn_post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent_posts = new Intent(MainActivity.this, Posts.class);
            startActivity(intent_posts);

        }
    });

}
</code>```

Code from my Adapter class is

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.rViewHolder> {

private Context mContext;
private List<Upload> mUploads;

public RecyclerViewAdapter(Context context, List<Upload> uploads){
    mContext = context;
    mUploads = uploads;
}

@Override
public rViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.card_view_recycler_view, parent, false);
    return new rViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull rViewHolder viewHolder, int position) {
    Upload uploadCurrent = mUploads.get(position);
    viewHolder.textViewDescription.setText(uploadCurrent.getDescription());
    Picasso.get().load(uploadCurrent.getImageUrl()).into(viewHolder.imageView);

}

@Override
public int getItemCount() {
    return mUploads.size();
}

public class rViewHolder extends RecyclerView.ViewHolder{
    public TextView textViewDescription;
    public ImageView imageView;

    public  rViewHolder(View itemView){
        super(itemView);
        textViewDescription = itemView.findViewById(R.id.r_description);
        imageView = itemView.findViewById(R.id.r_image_view);
    }
}
</code>```

答:
Try clearing your ArrayList in this case mUploads before adding items to it i.e.,

```<code>mDatabaseReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        // Clear ArrayList
        mUploads.clear();
        for(DataSnapshot postSnapshot : dataSnapshot.getChildren())
        {
            Upload upload = postSnapshot.getValue(Upload.class);
            mUploads.add(upload);
        }
        mAdapter = new RecyclerViewAdapter(MainActivity.this, mUploads);
        mRecyclerView.setAdapter(mAdapter);
    }
    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
    }
});
</code>```

This works well on my end and I hope it helps.
Reference here.

Title: Repeated Items in RecyclerView

Body:
I am having problems with repeated items in RecyclerView. Whenever I upload to my firebase and open the main activity again there are repeated itmes in the recyclerView from the previous load. How do I remove repeated items from my recyclerView.

Code for my Main Activity is

private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;

private DatabaseReference mDatabaseReference;
private List<Upload> mUploads;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_posts);
    setupBottomNavigation();

    mRecyclerView = findViewById(R.id.recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    mUploads = new ArrayList<>();

    mDatabaseReference = FirebaseDatabase.getInstance().getReference("uploads");

    mDatabaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot postSnapshot : dataSnapshot.getChildren())
            {
                Upload upload = postSnapshot.getValue(Upload.class);
                mUploads.add(upload);
            }
            mAdapter = new RecyclerViewAdapter(MainActivity.this, mUploads);
            mRecyclerView.setAdapter(mAdapter);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

    Button btn_post = (Button) findViewById(R.id.post_Main);
    btn_post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent_posts = new Intent(MainActivity.this, Posts.class);
            startActivity(intent_posts);

        }
    });

}

Code from my Adapter class is

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.rViewHolder> {

private Context mContext;
private List<Upload> mUploads;

public RecyclerViewAdapter(Context context, List<Upload> uploads){
    mContext = context;
    mUploads = uploads;
}

@Override
public rViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.card_view_recycler_view, parent, false);
    return new rViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull rViewHolder viewHolder, int position) {
    Upload uploadCurrent = mUploads.get(position);
    viewHolder.textViewDescription.setText(uploadCurrent.getDescription());
    Picasso.get().load(uploadCurrent.getImageUrl()).into(viewHolder.imageView);

}

@Override
public int getItemCount() {
    return mUploads.size();
}

public class rViewHolder extends RecyclerView.ViewHolder{
    public TextView textViewDescription;
    public ImageView imageView;

    public  rViewHolder(View itemView){
        super(itemView);
        textViewDescription = itemView.findViewById(R.id.r_description);
        imageView = itemView.findViewById(R.id.r_image_view);
    }
}

Body:
Try clearing your ArrayList in this case mUploads before adding items to it i.e.,

mDatabaseReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        // Clear ArrayList
        mUploads.clear();
        for(DataSnapshot postSnapshot : dataSnapshot.getChildren())
        {
            Upload upload = postSnapshot.getValue(Upload.class);
            mUploads.add(upload);
        }
        mAdapter = new RecyclerViewAdapter(MainActivity.this, mUploads);
        mRecyclerView.setAdapter(mAdapter);
    }
    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
    }
});

This works well on my end and I hope it helps.
Reference here.


答:
You don't store the result of check_orientation4($imgurl); anywhere. Try changing that line to this:

```<code>$scale = check_orientation4($imgurl);
</code>```

Title: calling a function within a function

Body:
I've had a look through several of the related questions and just can't seem to see the issue!

the following two functions are within my function include file and for some reason I cannot seem to get the check_orientation function to return scale to the display_months_news function.

I'm fairly sure I'm just missing something really obviously.

the display_news function

function display_months_news()
{
    //header('Content-type: image/jpeg');
    $year = date("y");
    $year = "20" .$year;
    $month = date("m");
    if ($month) {
        switch ($month){
            case "01": $month = "January"; break;
            case "02": $month = "February"; break;
            case "03": $month = "March"; break;
            case "04": $month = "April"; break;
            case "05": $month = "May"; break;
            case "06": $month = "June"; break;
            case "07": $month = "July"; break;
            case "08": $month = "August"; break;
            case "09": $month = "September"; break;
            case "10": $month = "October"; break;
            case "11": $month = "November"; break;
            case "12": $month = "December"; break;
        }
    } else {
        echo '
The date field is empty.
';
    }
    $nowdate = $month." ".$year;

    $result = mysql_query("SELECT * FROM news ORDER BY sqldate DESC LIMIT 6") or die(mysql_error());

    while ($row = mysql_fetch_array($result)) {
        global $imgurl;
        $imgurl = $row['img1'];

        check_orientation4($imgurl);

        $comcount = comment_count($row['nid']);
        if ($comcount == NULL) {$comcount = 0;}

        echo '
';
        echo '
';
        echo "
" .$row['mmonth']. " ".$row['dday']. ", " .$row['yyear']. "

";
        echo '
';
        echo '
';
        echo "
" .$row['title']."

";
        echo '
';
        echo '
';
        echo '
';
        echo '
'.ShortenText($row['body']).'
';
        echo '
';
        echo '

';
        echo '
Posted in '.$row[tag].' / '.$comcount.' Comments
';
        echo '
';

    }
}

and the check_orientation function

function check_orientation4($imgurls){

if ($imgurls == NULL){ echo "";  }
else {
        $imgurlshrunk = NULL;
        $maxsize = 120;
        $filename = NULL;
        $height = NULL;
        $width = NULL;
        $scale = NULL;
        $imgurlshrunk = $imgurls;
        $filename = basename($imgurlshrunk);
        $filename = "admin/uploads/" . $filename;
        list($width,$height,$type,$attr) = getimagesize("$filename");
        $wRatio = $maxsize / $width;
        $hRatio= $maxsize / $height;

    global $scale;

    if ( ($width <= $maxsize) && ($height <= $maxsize))
      {

        $scale = "";
        return $scale;
      }
    elseif ( ($wRatio * $height) < $maxsize)
    {
        $scale = "width = '100%'";
        return $scale;
    }
    elseif  ($height == NULL)
    {

        echo "empty height";
    }
    else
    {
    global $height;
        $scale = "height = '100%'";
        return $scale;
    }       }}

Thanks in advance to whoever points out the silly mistake i'm missing!

Body:
You don't store the result of check_orientation4($imgurl); anywhere. Try changing that line to this:

$scale = check_orientation4($imgurl);


问:
How do I add an extra column to the results of a GROUP BY with a value that matches a condition?
I'm trying to use GROUP BY to generate a summary of a table, but I want to add a column with a value that matches a condition from the original table.  The condition I want to check for is that style = 2 so that a new column with the filename that matches that style is shown in the results.

This is what the original table looks like:

```<code>category  |  value | style | filename
   A      |   8    |   0   |   AAA
   B      |   4    |   2   |   BBB
   B      |   6    |   1   |   CCC
   A      |   3    |   2   |   DDD
   A      |   6    |   1   |   EEE
   C      |   7    |   2   |   FFF
   B      |   5    |   1   |   GGG
   A      |   3    |   1   |   HHH
</code>```

This is what I want:

```<code>category  |  total_value   | filename
   A      |        20      |   DDD
   B      |        15      |   BBB
   C      |         7      |   FFF
</code>```

I tried this query, but the filename chosen was the MINIMUM, not the one that matches style = 2:

```<code>SELECT category, SUM(value) AS total_value, MIN(filename) AS filename FROM data GROUP BY category;
</code>```

答:
Although I like the answer of @Oto Shavadze better, I still like to share a solution I thought of:

```<code>select data.category, SUM(data.value), hlp.filename
from data
left join (
    select category, filename
    from data
    where style = 2
    group by category
    limit 1
) as hlp
on data.category = hlp.category
group by data.category
</code>```

This solution uses a subquery, which will select the respective filename for each category.

EDIT:

Looks like the website I used was not verry restrictive, in the use of colum not beeing listed in the group by or beeing in an aggregate function.

So here the updated version, using the MIN() function on filname, as i said in comments:

```<code>select data.category, SUM(data.value), MIN(hlp.filename)
from data
left join (
    select category, MIN(filename) as filename
    from data
    where style = 2
    group by category
) as hlp
on data.category = hlp.category
group by data.category;
</code>```

Body:
I'm trying to use GROUP BY to generate a summary of a table, but I want to add a column with a value that matches a condition from the original table.  The condition I want to check for is that style = 2 so that a new column with the filename that matches that style is shown in the results.

This is what the original table looks like:

category  |  value | style | filename
   A      |   8    |   0   |   AAA
   B      |   4    |   2   |   BBB
   B      |   6    |   1   |   CCC
   A      |   3    |   2   |   DDD
   A      |   6    |   1   |   EEE
   C      |   7    |   2   |   FFF
   B      |   5    |   1   |   GGG
   A      |   3    |   1   |   HHH

This is what I want:

category  |  total_value   | filename
   A      |        20      |   DDD
   B      |        15      |   BBB
   C      |         7      |   FFF

I tried this query, but the filename chosen was the MINIMUM, not the one that matches style = 2:

SELECT category, SUM(value) AS total_value, MIN(filename) AS filename FROM data GROUP BY category;

Body:
Although I like the answer of @Oto Shavadze better, I still like to share a solution I thought of:

select data.category, SUM(data.value), hlp.filename
from data
left join (
    select category, filename
    from data
    where style = 2
    group by category
    limit 1
) as hlp
on data.category = hlp.category
group by data.category

This solution uses a subquery, which will select the respective filename for each category.

EDIT:

Looks like the website I used was not verry restrictive, in the use of colum not beeing listed in the group by or beeing in an aggregate function.

So here the updated version, using the MIN() function on filname, as i said in comments:

select data.category, SUM(data.value), MIN(hlp.filename)
from data
left join (
    select category, MIN(filename) as filename
    from data
    where style = 2
    group by category
) as hlp
on data.category = hlp.category
group by data.category;


问:
I have a code in PHP how do this in python cURL
I have some problem, one person have a ubuntu server without php, and this person don't want install php on this server, I need upload file usuing cURL or python for them, but I know only how do this in php, I dont have any basic steps with python :(. Someone can help me with this bottom my code with php. I trying some like this

```<code>Python

with open('plik.csv', 'rb') as csv_file:
    r = requests.post(https://somelink/companies, data=csv_file)
</code>```

cURL

```<code>curl --header "Content-Type: text/csv" --request POST --data-binary "@test.csv" https://somelink/companies
</code>```

What I'm doing wrong

```<code>$url = 'https://somelink/companies';

$params = array(
    'key' => '8e7bdd23qa1d06b493152ea37cd4ah39',
    'csv' => file_get_contents('test.csv'),
);

$query = http_build_query($params);

$ctx = stream_context_create(array(
            'http' => array(
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
                    "Content-Length: ".strlen($query)."\r\n".
                    "User-Agent: uploader_pmg_companies\r\n",
                'method'  => 'POST',
                'content' => $query,
            ),
        ));

$result = file_get_contents($url, $flags = null, $ctx);
</code>```

答:
```<code>Ok I wrote in python some like this
</code>```

import requests

```<code>url = "https://somelink/companies"
files = {'file': open('plik.csv', 'rb')}
payload = {'key': '8e7bdd23qa1d06b493152ea37cd4ah39', 'csv': files}
headers = {'Content-Type: application/x-www-form-urlencoded', 'User-Agent: uploader_pmg_companies'}
r = requests.post(url, params=payload, files=files)
print r.url
print (r.text)
</code>```

```<code>And server answer {"file_csv_content":"file...","status":success"}

So this works?
</code>```

Body:
I have some problem, one person have a ubuntu server without php, and this person don't want install php on this server, I need upload file usuing cURL or python for them, but I know only how do this in php, I dont have any basic steps with python :(. Someone can help me with this bottom my code with php. I trying some like this

Python

with open('plik.csv', 'rb') as csv_file:
    r = requests.post(https://somelink/companies, data=csv_file)

cURL

curl --header "Content-Type: text/csv" --request POST --data-binary "@test.csv" https://somelink/companies

What I'm doing wrong

$url = 'https://somelink/companies';

$params = array(
    'key' => '8e7bdd23qa1d06b493152ea37cd4ah39',
    'csv' => file_get_contents('test.csv'),
);

$query = http_build_query($params);

$ctx = stream_context_create(array(
            'http' => array(
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
                    "Content-Length: ".strlen($query)."\r\n".
                    "User-Agent: uploader_pmg_companies\r\n",
                'method'  => 'POST',
                'content' => $query,
            ),
        ));

$result = file_get_contents($url, $flags = null, $ctx);

Body:
Ok I wrote in python some like this

import requests

url = "https://somelink/companies"
files = {'file': open('plik.csv', 'rb')}
payload = {'key': '8e7bdd23qa1d06b493152ea37cd4ah39', 'csv': files}
headers = {'Content-Type: application/x-www-form-urlencoded', 'User-Agent: uploader_pmg_companies'}
r = requests.post(url, params=payload, files=files)
print r.url
print (r.text)

And server answer {"file_csv_content":"file...","status":success"}

So this works?


问:
Java : My system for decrypt text doesn't work
I've a system for encrypt texts, but i've tried to create a system for decrypt texts, and it doesn't work. The system is :

initialize encrypted text to byte[]

initialize decrypted text with the encrypted text

He just return the encrypted text, but not the decrypted text. Have you an idea for debug this?

Thanks in advance.

byte[] getEncrypt(String text) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException
{
    String key = "Bép12345Taruy'(";

    Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES");

    cipher.init(Cipher.ENCRYPT_MODE, aesKey);
    byte[] encrypted = cipher.doFinal(text.getBytes());

    return encrypted;
}

String getDecrypt(String text) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException
{
    String key = "Bép12345Taruy'(";

    Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES");

    cipher.init(Cipher.ENCRYPT_MODE, aesKey);
    byte[] encrypted = cipher.doFinal(text.getBytes());

    cipher.init(Cipher.DECRYPT_MODE, aesKey);
    String decrypted = new String(cipher.doFinal(encrypted));

    return decrypted;
}
```

答:
You encrypt the encrypted text in your getDecrypt(...) method. Or do you want to encrypt and decript it again in one method?

One solution would be following code:

```<code>package test;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class Test2{

    public static void main(String[] args) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
        System.out.println(new String(getEncrypt("test")));
        System.out.println(new String(getDecrypt(getEncrypt("test"))));

    }

    public static byte[] getEncrypt(String text) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        String key = "Bép12345Taruy'(";

        Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");

        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        byte[] encrypted = cipher.doFinal(text.getBytes());

        return encrypted;
    }

    public static byte [] getDecrypt(byte[] encrypted) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        String key = "Bép12345Taruy'(";

        Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");

        cipher.init(Cipher.DECRYPT_MODE, aesKey);
        return cipher.doFinal(encrypted);
    }

}
</code>```

Output:

�'���+~�@��@w

test

Body:
You encrypt the encrypted text in your getDecrypt(...) method. Or do you want to encrypt and decript it again in one method?

One solution would be following code:

package test;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class Test2{

    public static void main(String[] args) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
        System.out.println(new String(getEncrypt("test")));
        System.out.println(new String(getDecrypt(getEncrypt("test"))));

    }

    public static byte[] getEncrypt(String text) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        String key = "Bép12345Taruy'(";

        Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");

        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        byte[] encrypted = cipher.doFinal(text.getBytes());

        return encrypted;
    }

    public static byte [] getDecrypt(byte[] encrypted) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        String key = "Bép12345Taruy'(";

        Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");

        cipher.init(Cipher.DECRYPT_MODE, aesKey);
        return cipher.doFinal(encrypted);
    }

}

Output:

�'���+~�@��@w

test


问:
How to control if a user logins twice in rails
Right now Iam using devise for an application and I don't want a user to login twice, if it logins for the second time his previous session would be killed. this way the user can't login with two browsers, for example he logins first with firefox and then logins with google chrome the firefox session expires.

答: Something similar here: Can a session be shared between browsers from the same computer in rails?</p>


问:
How to apply own build function on groupby
I couldnt find a thread, that fitted my question... In case this is not true, please don't hesitate to post the link to the thread.

I have the following dataframe, which I have to analyze. This is the head of it:

```<code>

                     EMBieding  AeolisBieding  ...  Diff_EM  Diff_Aeolis
StartTime                                      ...
2019-09-01 00:00:00    3058.24         3494.0  ... -3126.24      -3562.0
2019-09-01 01:00:00    2906.01         3480.0  ... -2974.01      -3548.0
2019-09-01 02:00:00    2836.22         3470.0  ... -2903.22      -3537.0
2019-09-01 03:00:00    2805.66         3448.0  ... -2848.66      -3491.0
2019-09-01 04:00:00    2541.54         3413.0  ... -2606.54      -3478.0
</code>```

Next to overall error measures, I also want to find out the error per hour.
This means, the hours from 0 - 23 have to be aggregated.
Using the following code, it is easy to find the mean:

```<code>data= importdata('871687110001543570.csv')
data_perhour = data.groupby(data.index.hour).mean()
data_perhour.drop
print(data_perhour)
</code>```

I can easily find the mean for each column.

```<code>             EMBieding  AeolisBieding  ...     Diff_EM  Diff_Aeolis
StartTime                              ...
0          1175.862033    1279.577236  ... -253.707561  -357.422764
1          1153.947724    1264.723577  ... -309.435528  -420.211382
2          1146.239016    1259.459016  ... -336.763607  -449.983607
3          1133.350976    1251.268293  ... -390.928211  -508.845528
4          1127.061789    1251.300813  ... -405.411382  -529.650407
</code>```

The error measures I use are NBIAS, NMAE and NRMSE. I calculate this with the following

```<code># statistic calculates the different errormeasurements: NBIAS,NMAE,NRMSE. Input arguments are: data; this is the output from the
# importdata function. parksize; which is just the installed power of the respective farm, for normalization. filename
# is needed to produce a unique new filename.
def statistic(data,park_size,filename):
    def NBIAS(Diff_forecaster,park_size):
        return data[Diff_forecaster].mean()/park_size

    def NMAE(Bied_forecaster,park_size):
        return mean_absolute_error(data['Production'], data[Bied_forecaster]) /park_size

    def NRMSE(Bied_forecaster,park_size):
        return (sqrt(mean_squared_error(data['Production'], data[Bied_forecaster])) /np.square(park_size))

# Calculate the overall errormeasure and save it directly in a external .csv
    ErrorMeasure = {'EM':[NBIAS('Diff_EM',park_size),NMAE('EMBieding',park_size),NRMSE('EMBieding',park_size)],
                    'Aeolis':[NBIAS('Diff_Aeolis',park_size),NMAE('Bied',park_size ),NRMSE('Bied',park_size)]}
    df_ErrorMeasure = pd.DataFrame(ErrorMeasure,index=['NBIAS','NMAE','NRMSE'])
    df_ErrorMeasure.to_csv('errormeasure'+filename)

    data_perhour=data.groupby(data.index.hour).apply(NBIAS('EMBieding',park_size))

    print(data_perhour)
</code>```

The last two lines are a attempt to get the NBIAS for each hour. However, I get this error:

```<code>TypeError: 'numpy.float64' object is not callable
</code>```

How can I get the error measures for each hour? This means, can I use a own function (like.NBIAS) to replace the .mean after data.groupby(data.index.hour).

Anyone suggestions?`

答:
NBIAS returns the mean (a float) divided by park_size. This is a number, a numpy.float64, as the error message says. apply takes a callable, such as a function or lambda.

Instead, try:

data_perhour=data.groupby(data.index.hour).apply(lambda p: NBIAS('EMBieding',p))
```

Body:
I couldnt find a thread, that fitted my question... In case this is not true, please don't hesitate to post the link to the thread.

I have the following dataframe, which I have to analyze. This is the head of it:

                     EMBieding  AeolisBieding  ...  Diff_EM  Diff_Aeolis
StartTime                                      ...
2019-09-01 00:00:00    3058.24         3494.0  ... -3126.24      -3562.0
2019-09-01 01:00:00    2906.01         3480.0  ... -2974.01      -3548.0
2019-09-01 02:00:00    2836.22         3470.0  ... -2903.22      -3537.0
2019-09-01 03:00:00    2805.66         3448.0  ... -2848.66      -3491.0
2019-09-01 04:00:00    2541.54         3413.0  ... -2606.54      -3478.0

Next to overall error measures, I also want to find out the error per hour.
This means, the hours from 0 - 23 have to be aggregated.
Using the following code, it is easy to find the mean:

data= importdata('871687110001543570.csv')
data_perhour = data.groupby(data.index.hour).mean()
data_perhour.drop
print(data_perhour)

I can easily find the mean for each column.

             EMBieding  AeolisBieding  ...     Diff_EM  Diff_Aeolis
StartTime                              ...
0          1175.862033    1279.577236  ... -253.707561  -357.422764
1          1153.947724    1264.723577  ... -309.435528  -420.211382
2          1146.239016    1259.459016  ... -336.763607  -449.983607
3          1133.350976    1251.268293  ... -390.928211  -508.845528
4          1127.061789    1251.300813  ... -405.411382  -529.650407

The error measures I use are NBIAS, NMAE and NRMSE. I calculate this with the following

# statistic calculates the different errormeasurements: NBIAS,NMAE,NRMSE. Input arguments are: data; this is the output from the
# importdata function. parksize; which is just the installed power of the respective farm, for normalization. filename
# is needed to produce a unique new filename.
def statistic(data,park_size,filename):
    def NBIAS(Diff_forecaster,park_size):
        return data[Diff_forecaster].mean()/park_size

    def NMAE(Bied_forecaster,park_size):
        return mean_absolute_error(data['Production'], data[Bied_forecaster]) /park_size

    def NRMSE(Bied_forecaster,park_size):
        return (sqrt(mean_squared_error(data['Production'], data[Bied_forecaster])) /np.square(park_size))

# Calculate the overall errormeasure and save it directly in a external .csv
    ErrorMeasure = {'EM':[NBIAS('Diff_EM',park_size),NMAE('EMBieding',park_size),NRMSE('EMBieding',park_size)],
                    'Aeolis':[NBIAS('Diff_Aeolis',park_size),NMAE('Bied',park_size ),NRMSE('Bied',park_size)]}
    df_ErrorMeasure = pd.DataFrame(ErrorMeasure,index=['NBIAS','NMAE','NRMSE'])
    df_ErrorMeasure.to_csv('errormeasure'+filename)

    data_perhour=data.groupby(data.index.hour).apply(NBIAS('EMBieding',park_size))

    print(data_perhour)

The last two lines are a attempt to get the NBIAS for each hour. However, I get this error:

TypeError: 'numpy.float64' object is not callable

How can I get the error measures for each hour? This means, can I use a own function (like.NBIAS) to replace the .mean after data.groupby(data.index.hour).

Anyone suggestions?`