Q: Python urllib2 does not respect timeout The following two lines of code hangs forever:
import urllib2
urllib2.urlopen('https://www.5giay.vn/', timeout=5)

This is with python2.7, and I have no http_proxy or any other env variables set. Any other website works fine. I can also wget the site without any issue. What could be the issue?

A: If you run
import urllib2

url = 'https://www.5giay.vn/'
urllib2.urlopen(url, timeout=1.0)

wait for a few seconds, and then use C-c to interrupt the program, you'll see
  File "/usr/lib/python2.7/ssl.py", line 260, in read
    return self._sslobj.read(len)
KeyboardInterrupt

This shows that the program is hanging on self._sslobj.read(len).
SSL timeouts raise socket.timeout.
You can control the delay before socket.timeout is raised by calling
socket.setdefaulttimeout(1.0).
For example,
import urllib2
import socket

socket.setdefaulttimeout(1.0)
url = 'https://www.5giay.vn/'
try:
    urllib2.urlopen(url, timeout=1.0)
except IOError as err:
    print('timeout')

% time script.py
timeout

real    0m3.629s
user    0m0.020s
sys 0m0.024s

Note that the requests module succeeds here although urllib2 did not:
import requests
r = requests.get('https://www.5giay.vn/')

How to enforce a timeout on the entire function call:
socket.setdefaulttimeout only affects how long Python waits before an exception is raised if the server has not issued a response.
Neither it nor urlopen(..., timeout=...) enforce a time limit on the entire function call.
To do that, you could use eventlets, as shown here.
If you don't want to install eventlets, you could use multiprocessing from the standard library; though this solution will not scale as well as an asynchronous solution such as the one eventlets provides.
import urllib2
import socket
import multiprocessing as mp

def timeout(t, cmd, *args, **kwds):
    pool = mp.Pool(processes=1)
    result = pool.apply_async(cmd, args=args, kwds=kwds)
    try:
        retval = result.get(timeout=t)
    except mp.TimeoutError as err:
        pool.terminate()
        pool.join()
        raise
    else:
        return retval

def open(url):
    response = urllib2.urlopen(url)
    print(response)

url = 'https://www.5giay.vn/'
try:
    timeout(5, open, url)
except mp.TimeoutError as err:
    print('timeout')

Running this will either succeed or timeout in about 5 seconds of wall clock time.


Q: I'm trying to automatically reload a div after some seconds but it doesn't work in Chrome Here is the Main code. Please check it. what is making this conflict.
<script type="text/javascript">
$(document).ready(function ()
{
  setInterval(function()
  {
    $.get("ajax_files/manage_friend_requests.php", function (result)
    {
      $('#all_friends_requests').html(result); // This is the div i am reloading again and again after some seconds.
          });
        }, 9000);
    });
</script>

A: You should be safer with something like this:
$(document).ready(function(){
    setInterval(function(){
        $.ajax({
            type: "GET",
            url: "ajax_files/manage_friend_requests.php"
        }).done(function(result) {
            var $friends_requests = $('#all_friends_requests');
            if ($friends_requests.length > 0) {
                console.log('Received: '+result);
                $friends_requests.html(result);
                console.log('UPDATED friends requests');
            } else {
                console.log('CANNOT access friends requests container');
            }
        });
    }, 9000);
});

Depending on what the console will display, you will probably put the issue in evidence.


Q: How to submit dropzone js form and django form with one submit button I am using dropzone js to make a form where users can upload information along side images. Dropzone js requires that dropzone has a form with a class of dropzone for the drag and drop image uploads to work, this now leaves me with two forms. The first is the normal input form and the second is the dropzone js form. My question is how can I submit both the dropzone js form and the normal input form with one submit button. Please note I am using html forms, not django crispy forms.
 <form method="POST" enctype="multipart/form-data" id="inputform" name="form1">
       {% csrf_token %}
       <button type="submit" id="add">Save</button>
  </form>

    <form method="POST" enctype="multipart/form-data" id="inputform" name="form1">
    {% csrf_token %}

Title

    <input type="text" name="product_title" id="product_title" placeholder="Give your product a name">

Price

    <input type="text" name="product_price" id="product_price" placeholder="0.00">

Description

    <input type="text" name="product_description" id="product_description" placeholder="Write a description about your product">
    </form>

Images

      <form method="POST"  action="#" class="dropzone col-sm-8 col-lg-8" id="dropzone" name="form2">
        {% csrf_token %}
      </form>

def add(request):
if request.method == "POST":
    title = request.POST.get("product_title")
    price = request.POST.get("product_price")
    description = request.POST.get("product_description")
    print(title,price,description)
return render(request,"main/add.html")

A: You don't need separate form for dropzone. Use first form and give it class name dropzone.
 <form method="POST" enctype="multipart/form-data" id="inputform" name="form1" class="dropzone">
   {% csrf_token %}

Title

    <input type="text" name="product_title" id="product_title" placeholder="Give your product a name">

Price

    <input type="text" name="product_price" id="product_price" placeholder="0.00">

Description

    <input type="text" name="product_description" id="product_description" placeholder="Write a description about your product">
    <button type="submit" id="add">Save</button>
  </form>

PS. In order to submit files you need to have
<input type="file" name="file" />

in your form.


Q: Automate a user assignment to a specific app role within an application I'm automating an app setup and having registered an applicatioin with az ad app create --app-roles with the manifest:
[{
    "allowedMemberTypes": [
      "User",
      "Application"
    ],
    "description": "Read items",
    "displayName": "Reader",
    "isEnabled": "true",
    "value": "items/r"
}]

I'm trying to figure a way to assign above mentioned Reader to a principal without PowerShell's New-AzureADUserAppRoleAssignment and coming up empty. I'd take ARM template, .NET SDK or az CLI way of doing it, but none seem to support it.
Not interested in the portal/ui as I'm trying to script this, any ideas?

A: Just use az cli rest to assign a custom app role to a principal via Azure AD Graph Rest API :
az rest --method post --uri "https://graph.windows.net/<your tenant ID>/servicePrincipals/<your principle object Id>/appRoleAssignments?api-version=1.6" --body "{\"id\":\"<your custom role app ID>\",\"principalId\":\"<your principle object Id>\",\"resourceId\":\"<your app object id>\"}" --headers "Authorization=Bearer <access token>"

You can get access token via az account get access token :
az account get-access-token --resource "https://graph.windows.net"

Test request on Azure cli :

Result, as you can see the role has been assigned to principle successfully  :


Q: Calculating a Sum with case sensitive Picture of the table

{
        "_id" : ObjectId("62f6e11df737d6c2b49b9b9f"),
        "_ID" : 345,
        "name" : "Ron",
        "age" : 25,
        "city" : "Holon",
        "Number_Days_booked" : 2
}
{
        "_id" : ObjectId("62f6e11df737d6c2b49b9ba0"),
        "_ID" : 459,
        "name" : "Ifat",
        "age" : 25,
        "city" : "Holon",
        "Number_Days_booked" : 4
}
{
        "_id" : ObjectId("62f6e11df737d6c2b49b9ba1"),
        "_ID" : 789,
        "name" : "Oren",
        "age" : 26,
        "city" : "ramla",
        "Number_Days_booked" : 3
}
{
        "_id" : ObjectId("62f6e11df737d6c2b49b9ba2"),
        "_ID" : 324,
        "name" : "Gali",
        "age" : 28,
        "city" : "Ramla",
        "Number_Days_booked" : 5
}
{
        "_id" : ObjectId("62f6e11df737d6c2b49b9ba3"),
        "_ID" : 123,
        "name" : "Adi",
        "age" : 34,
        "city" : "Tel_aviv",
        "Number_Days_booked" : 3
}
{
        "_id" : ObjectId("62f6e11df737d6c2b49b9ba4"),
        "_ID" : 456,
        "name" : "Dan",
        "age" : 36,
        "city" : "tel_aviv",
        "Number_Days_booked" : 4
}
{
        "_id" : ObjectId("62f6e11df737d6c2b49b9ba5"),
        "_ID" : 678,
        "name" : "Ronht",
        "age" : 39,
        "city" : "Holon",
        "Number_Days_booked" : 6
}

I am trying to calculate the Sum of Number_days_booked only for Tel Aviv, but I have case sensitivity issue.
I have tried so far ->
db.Customers.aggregate({ $group: { "_id": { $toLower: "$city" }, "count": { $sum: "$Number_Days_booked" } } })

But that produces the sum of all cities and I want to represent only Tel Aviv, how can I do so?

A:         db.Customers.aggregate({
    $group: { "_id": { $toLower: "$city" }, "count": { $sum: "$Number_Days_booked" } } },
{$match:{_id:"tel_aviv"}})

matching at the end did the trick.


Q: Can't make an onClick with Zepto Hello I have a simple HTML page like this:

Test page

The content of script.js is the following:
// Zepto include
...

// My code
var app = app || (function(){
    var _args = {};

    return {
        init : function(Args) {
            _args = Args;
        },
        execute : function() {
            ...
        },
        edit: function() {

            $('body').on('click', function(e){
                alert('aa');
            });

        },
    };
}());

My problem is with this instruction $('body').on('click', function(e){.
I do not understand why.
It do not work.
Anyone to help me ?


Q: How to extract a meta tag from XML/HTML using Linq? I am trying to parse a bit of data from an HTML file, but my Linq statement is not working.  Here is the XML/HTML.  Below, how can I extract the string "41.8;12.23" from the geo.position meta tag?  Thx!!
Here is my Linq
   String longLat = (String)
        from el in xdoc.Descendants()
              where
               (string)el.Name.LocalName == "meta"
               & el.FirstAttribute.Name == "geo.position"
                select (String) el.LastAttribute.Value;

Here is my Xdocument

      <meta content="application/xhtml+xml; charset=utf-8" http-equiv="Content-Type" />
      <meta content="text/css" http-equiv="Content-Style-Type" />
      <meta name="geo.position" content="41.8;12.23" />
      <meta name="geo.placename" content="RomeFiumicino, Italy" />
      <title>RomeFiumicino, Italy</title>

Edit: My query as given returns nothing.  The "inner" query seems to return a list of all the meta elements instead of just the one element I want.
Edit: The following Linq query works against the same XDocument to retreive a table with class name = "data"
    var dataTable =
        from el in xdoc.Descendants()
        where (string)el.Attribute("class") == "data"
        select el;

A: A span around your html tag?
You could do this with XLinq, but it would only support well-formed XML. You might want to look at the HTML Agility Pack instead.
Edit - This works for me:
string xml = "...";
var geoPosition = XElement.Parse(xml).Descendants().
    Where(e => e.Name.LocalName == "meta" &&
        e.Attribute("name") != null &&
        e.Attribute("name").Value == "geo.position").
    Select(e => e.Attribute("content").Value).
    SingleOrDefault();

A: I'd bet that the problem you're having comes from not referencing the namespace correctly with an XmlNamespaceManager.  Here are two ways to do it:
string xml =
        @"

     <meta content=""application/xhtml+xml; charset=utf-8"" http-equiv=""Content-Type"" />
      <meta content=""text/css"" http-equiv=""Content-Style-Type"" />
      <meta name=""geo.position"" content=""41.8;12.23"" />
      <meta name=""geo.placename"" content=""RomeFiumicino, Italy"" />
      <title>RomeFiumicino, Italy</title>

    ";

    string ns = "http://www.w3.org/1999/xhtml";
    XmlNamespaceManager nsm;

    // pre-Linq:
    XmlDocument d = new XmlDocument();
    d.LoadXml(xml);
    nsm = new XmlNamespaceManager(d.NameTable);
    nsm.AddNamespace("h", ns);

    Console.WriteLine(d.SelectSingleNode(
        "/span/h:html/h:head/h:meta[@name='geo.position']/@content", nsm).Value);

    // Linq - note that you have to create an XmlReader so that you can
    // use its NameTable in creating the XmlNamespaceManager:
    XmlReader xr = XmlReader.Create(new StringReader(xml));
    XDocument xd = XDocument.Load(xr);
    nsm = new XmlNamespaceManager(xr.NameTable);
    nsm.AddNamespace("h", ns);

    Console.WriteLine(
        xd.XPathSelectElement("/span/h:html/h:head/h:meta[@name='geo.position']", nsm)
            .Attribute("content").Value);

A: I agree with Thorarin - use the HTML Agility pack, it's much more robust.
However, I suspect the problem you are having using LinqToXML is because of the namespace. See MSDN here for how to handle them in your queries.
" If you have XML that is in a default namespace, you still must declare an XNamespace variable, and combine it with the local name to make a qualified name to be used in the query.
One of the most common problems when querying XML trees is that if the XML tree has a default namespace, the developer sometimes writes the query as though the XML were not in a namespace."


Q: Property Names of MultiDimensional array I am new to JS. Programmatically I need to find propery names of multidimensional array. Expected Output -  ["name", "position", "salary", etc.]
When I am using map I am getting values of "name" data.map(item => item.name).
var data = [
        {
            "name": "Tiger Nixon",
            "position": "System Architect",
            "salary": "320800",
            "start_date": "2011\/04\/25",
            "office": "Edinburgh",
            "rating": "5421"
        },
        {
            "name": "Garrett Winters",
            "position": "Accountant",
            "salary": "170750",
            "start_date": "2011\/07\/25",
            "office": "Tokyo",
            "rating": "8422"
        },
        {
            "name": "Ashton Cox",
            "position": "Junior Technical Author",
            "salary": "86000",
            "start_date": "2009\/01\/12",
            "office": "San Francisco",
            "rating": "1562"
        },
        {
            "name": "Cedric Kelly",
            "position": "Senior Javascript Developer",
            "salary": "433060",
            "start_date": "2012\/03\/29",
            "office": "Edinburgh",
            "rating": "6224"
        }]

A: Using Object#keys:

const getPropertyNames = (arr = []) => arr.length > 0 ? Object.keys(arr[0]) : [];

const data = [ { "name": "Tiger Nixon", "position": "System Architect", "salary": "320800", "start_date": "2011\/04\/25", "office": "Edinburgh", "rating": "5421" }, { "name": "Garrett Winters", "position": "Accountant", "salary": "170750", "start_date": "2011\/07\/25", "office": "Tokyo", "rating": "8422" }, { "name": "Ashton Cox", "position": "Junior Technical Author", "salary": "86000", "start_date": "2009\/01\/12", "office": "San Francisco", "rating": "1562" }, { "name": "Cedric Kelly", "position": "Senior Javascript Developer", "salary": "433060", "start_date": "2012\/03\/29", "office": "Edinburgh", "rating": "6224" } ];
console.log( getPropertyNames(data) );


Q: Error occurred while trying to connect to db in aws I deployed war file to aws which is spring project. and I installed oracle rds on aws. When I try to connect to oracle rds on aws from my local computer with root-context.xml. It worked. It can connect to oracle rds on aws from my local computer with my spring project. But when I try to run spring war file on aws. http://ip address:8080 it gives me an error message. Would you please help me with this?
I have been struggling with this for three days...any help would be appreciated.
java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection

here is the root-context.xml
<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy"></property>

        <property name="url"
            value="jdbc:log4jdbc:oracle:thin:@database ip address on aws:1521:orcl" />
        <property name="username" value="id" />
        <property name="password" value="password" />
    </bean>

aws security inbound setting:
http tcp 80 0.0.0.0/0
custom tcp rule 8080 0.0.0.0/0
custom tcp rule 8080 ::/0
[database setting][1]

[security group][2]

  [1]: https://i.stack.imgur.com/869s0.png
  [2]: https://i.stack.imgur.com/hqaeU.png

A: After trying and trying - created another RDS DB, copying existing one, created another VPC to try it out there are few things that need to be considered (obviously, they are all documented, but it's not an easy task to find all the information, since - at least in my case - it wasn't documented in one place:

*

*If you want your DB instance in the VPC to be publicly accessible, you must enable the VPC attributes DNS hostnames and DNS resolution (existing VPC can be changed too).

*Check the VPC security group and enable the DB access port (in case of the standard MS SQL deployment - 1433) - since starting the 2013, VPC security groups have replaced the RDS security group.

*Check thoroughly the RDS DB information for Security Groups, port and other info that can be misidentified.

*Somehow not obvious (at least for me at first), but when using SQL Management Studio to access the RDS DB - do not use the ":1433" or other port identifier at the end of DB instance name.

*If nothing of the above works, ask the question here and keep googling... :)

Most of the info found here: http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.RDSVPC.html


Q: Android: updating the screen during computer controlled UI changes I've checked the other questions asked here and didn't succeed in implementing the solutions.  My application uses controls, not drawing on the canvas.  Basically this sums up my issue: -
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    btn1 = (ToggleButton) findViewById(R.id.btn1);
    btn2 = (ToggleButton) findViewById(R.id.btn2);
    btn3 = (ToggleButton) findViewById(R.id.btn2);
    btn4 = (ToggleButton) findViewById(R.id.btn4);
    btn5 = (ToggleButton) findViewById(R.id.btn5);
    btn6 = (ToggleButton) findViewById(R.id.btn6);
    btn7 = (ToggleButton) findViewById(R.id.btn7);
 //blah blah blah
    btn1.requestFocus();
    wait(100);
    btn2.requestFocus();
    wait(100);
    btn3.requestFocus();
    wait(100);
    btn3.setChecked(true);
    wait(100);
    btn4.requestFocus();
    wait(100);
    btn4.setChecked(true);
    wait(100);
    btn5.requestFocus();
    wait(100);
    btn6.requestFocus();
    wait(100);
    btn6.setChecked(true);
    wait(100);
    btn7.requestFocus();
    wait(100);
 //etc
}

The point being the computer animates the moving to a the buttons and checking them so the user can see what it is doing.  So, my issue is, what goes in my wait() method that will pause for 100ms and also update the screen, and the focus?  Any help really appreciated, cheers Jonathan.
Solution applies, thanks Andrew :)
int timerCounterInterval = 0;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final ToggleButton btn1 = (ToggleButton) findViewById(R.id.btn1);
    final ToggleButton btn2 = (ToggleButton) findViewById(R.id.btn2);
// more btns
    timerCounterInterval = 0; //reset, for each pass of automation
    setFocus(btn1);
    setFocus(btn2);
    setChecked(btn2);
// tidy up
    timerCounterInterval++;
    new Handler().postDelayed(new Runnable() {
        public void run() {
            btn2.clearFocus(); //whatever button that had the focus last
            }
    }, 100*(timerCounterInterval));
// etc - note any code from here will execute *before* the above timer
}

public void setFocus(final ToggleButton btn) {
    timerCounterInterval++;
    new Handler().postDelayed(new Runnable() {
        public void run() {
            btn.setFocusableInTouchMode(true); //eww, messy i know
            btn.requestFocus();
            btn.setFocusableInTouchMode(false);
        }
    }, 100*timerCounterInterval);
}

public void setChecked(final ToggleButton btn) {
    timerCounterInterval++;
    new Handler().postDelayed(new Runnable() {
        public void run() {
            btn.setChecked(true);
        }
    }, 100*timerCounterInterval);
}

Hope this helps other people!

A: I highly suggest you look into the Handle object and in particular the postDelayed method. That way you can keep everything on the UI thread while not causing the thread to actually be tied up in an animate method. This also keeps the Activity from giving that dreaded this-application-is-not-responding message.
In fact, simply wrapping your calls to the control's setters in a runnable and passing them to postDelayed should be enough to update the GUI controls.
[Update]
As an example per your comments you might try something like this. I haven't actually tested this but I think the idea is still there...
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final ToggleButton btn1 = (ToggleButton) findViewById(R.id.btn1);
    final ToggleButton btn2 = (ToggleButton) findViewById(R.id.btn2);
    // more btns

    Handler handler = new Handler();

    /* tell the handler run these bits after 1 sec, 2 sec, 3 sec, ect... */
    handler.postDelayed(new Runnable() { void run () { btn1.requestFocus(); } }, 1000);
    handler.postDelayed(new Runnable() { void run () { btn2.requestFocus(); } }, 2000);
    handler.postDelayed(new Runnable() { void run () { btn2.setChecked(true); } }, 3000);
}


Q: How to get a notify email with file attatchment , whenever we place new file in shared location? I will explain my requirement here.
We have shared location in Network(like http://emea.com/ABC/Files), Every month some other team folks  will place some excel sheet in that location. we manully check that location and pick up that file.
Requirement is :- whenever A new file will place in that location we need to get email automatically with the latest file attached.
How can i achieve  this in java , or do we have any open source tools for this ,
Please share your thoughts on this :)


Q: Play Framework 2.2 log output to console in tests How do I configure the logger in Play Framework 2.2 in order that I see log output in the console during play integration tests?
The configuration for Play Framework 2.1 does not work anymore.
BR Rene

A: Update To understand more about how logback is configured you should pass -Dlogback.debug=true property to the jvm/play. This might save you hours of debbugging.
Add a file in test/logback-test.xml (needs to be on classpath so it might depend on how the play application is configured to find tests resources) with a content like
<configuration>

    <conversionRule conversionWord="coloredLevel"
        converterClass="play.api.Logger$ColoredLevel" />

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>${application.home:-.}/logs/application.log</file>
        <encoder>
            <pattern>%date - [%level] - from %logger in %thread
                %n%message%n%xException%n</pattern>
        </encoder>
    </appender>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%coloredLevel %logger{15} - %message%n%xException{5}</pattern>
        </encoder>
    </appender>

    <logger name="play" level="INFO" />
    <logger name="application" level="INFO" />

    <root level="ERROR">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>

</configuration>

A: I have not done this yet, but you have to configure a logback configuration file. See the play documentation for additional information: http://www.playframework.com/documentation/2.2.x/SettingsLogger
Once you defined a specific logback configuration file, this needs to be placed in the test package, see this issue for details:https://github.com/playframework/playframework/issues/1669#issuecomment-24452132
See message from @benmccann: you can configure the logger in test mode by placing a logback-test.xml in test/resources (took me hours to figure out!).


Q: How to write multiple ArrayList in a text file
In below code , i'm trying to create a txt file and there i want to add some list of values.
So here my approach is create a new file if file is not present and add the respective elements into it.

Please see below , i'm unable to get my expected output, So can you help me with some idea so it will be very helpful
   public class MyTest {

    public static void main(String[] args) throws Exception  {
        // TODO Auto-generated method stub
        SftpConn sftp = new SftpConn();
        //sftp.sftpGetConnect();
        List<String> list =  new ArrayList<>();
        list.add("AAAA");
        list.add("BBBB");
        list.add("CCCC");
        sftp.writeIntoText(list);
        List<String> list1 =  new ArrayList<>();
        list1.add("AAAA1111");
        list1.add("BBBB2222");
        list1.add("CCCC2222");
        sftp.writeIntoText(list1);
    }

    }

 public class SftpConn
      {
    public void writeIntoText(List<String> result) throws Exception
        {
                    connect();
                    List<String> resultdata= result;
                    System.out.println("Result Updated");
                    channelSftp = (ChannelSftp) session.openChannel("sftp");
                    channelSftp.connect();
                    fileOutStream = channelSftp.put("/home/dasrsoum/RM.txt");
                    PrintWriter writer = new PrintWriter(fileOutStream,true);
                    writer.println("------------------");
                    for (String value : resultdata) {
                        writer.println(value+ System.lineSeparator());
                        System.out.println(value);

                    }

            writer.close();
   }

Actual output
 AAAA1111
   BBBB2222
   CCCC2222

Excepted OutPut
  AAAA
  BBBB
  CCCC
  AAAA1111
  BBBB2222
  CCCC2222

A: You first file is overwritten by the second call to the function


Q: Is there a list of all possible fields for sorting in WooCommerce? I see that it is possible to add your custom field for sorting products in WooCommerce (e.g. this question) Copying from the example:
add_filter( 'woocommerce_get_catalog_ordering_args', 'enable_catalog_ordering_by_modified_date' );
function enable_catalog_ordering_by_modified_date( $args ) {
    if ( isset( $_GET['orderby'] ) ) {
        if ( 'modified_date' == $_GET['orderby'] ) {
            return array(
                'orderby'  => 'modified',  //This is the custom field to be sorted by, and what I am asking for
                'order'    => 'DESC',
            );
        }
    }
    return $args;
}

Is there a list of all fields that I can use for sorting?

P.S. Thanks for the comment, but what I need is not sorting normal posts in WordPress, but the products in WooCommerce.

A: These are the default list of orderby options available( id, title, relevance, rand, date, price, popularity, rating). The case of the switch case may be what you are looking for.
switch ( $orderby ) {
        case 'id':
            $args['orderby'] = 'ID';
            break;
        case 'menu_order':
            $args['orderby'] = 'menu_order title';
            break;
        case 'title':
            $args['orderby'] = 'title';
            $args['order']   = ( 'DESC' === $order ) ? 'DESC' : 'ASC';
            break;
        case 'relevance':
            $args['orderby'] = 'relevance';
            $args['order']   = 'DESC';
            break;
        case 'rand':
            $args['orderby'] = 'rand'; // @codingStandardsIgnoreLine
            break;
        case 'date':
            $args['orderby'] = 'date ID';
            $args['order']   = ( 'ASC' === $order ) ? 'ASC' : 'DESC';
            break;
        case 'price':
            $callback = 'DESC' === $order ? 'order_by_price_desc_post_clauses' : 'order_by_price_asc_post_clauses';
            add_filter( 'posts_clauses', array( $this, $callback ) );
            break;
        case 'popularity':
            add_filter( 'posts_clauses', array( $this, 'order_by_popularity_post_clauses' ) );
            break;
        case 'rating':
            add_filter( 'posts_clauses', array( $this, 'order_by_rating_post_clauses' ) );
            break;
    }

The above code is from woocommerce/includes/class-wc-query.php line 586...

A: You need to know what is inside of an product object. You can sort your products by any of this product data.
Here is a list I found where you can access all the data inside of a product object.
(source: https://wpdavies.dev/how-to-get-all-product-info-in-woocommerce/)
<?php

/**
 *
 *  General Product Data
 *
 */
$product->get_id(); // Returns the unique ID for this object.
$product->get_description(); // Get product description.
$product->get_formatted_name(); // Get product name with SKU or ID. Used within admin.
$product->get_featured(); // If the product is featured.
$product->get_name(); // Get product name.
$product->get_title(); // Get the product's title. For products this is the product name.
$product->get_type(); // Get internal type. Should return string and *should be overridden* by child classes.
$product->get_virtual(); // Get virtual.
$product->get_total_sales(); // Get number total of sales.
$product->get_short_description(); // Get product short description.
$product->get_sku(); // Get SKU (Stock-keeping unit) - product unique ID.
$product->get_slug(); // Get product slug.
$product->get_status(); // Get product status.
$product->get_permalink(); // Product permalink.
$product->get_catalog_visibility(); // Get catalog visibility.

/**
 *
 *  Pricing Data
 *
 */
$product->get_price(); // Returns the product's active price.
$product->get_date_on_sale_from(); // Get date on sale from.
$product->get_date_on_sale_to(); // Get date on sale to.
$product->get_display_price(); // Returns the price including or excluding tax, based on the 'woocommerce_tax_display_shop' setting.
$product->get_price_excluding_tax(); // Returns the price (excluding tax) - ignores tax_class filters since the price may *include* tax and thus needs subtracting.
$product->get_price_html(); // Returns the price in html format.
$product->get_price_html_from_text(); // Functions for getting parts of a price, in html, used by $product->get_price_html.
$product->get_price_html_from_to(); // Functions for getting parts of a price, in html, used by $product->get_price_html.
$product->get_price_including_tax(); // Returns the price (including tax). Uses customer tax rates. Can work for a specific $qty for more accurate taxes.
$product->get_price_suffix(); // Get the suffix to display after prices > 0.
$product->get_sale_price(); // Returns the product's sale price.
$product->get_regular_price(); // Returns the product's regular price.
$product->get_tax_class(); // Returns the tax class.
$product->get_tax_status(); // Returns the tax status.

/**
 *
 *  Image Related Data
 *
 */
$product->get_image(); // Returns the main product image.
$product->get_image_id(); // Get main image ID.
$product->get_gallery_attachment_ids(); // Returns the gallery attachment ids.
$product->get_gallery_image_ids(); // Returns the gallery attachment ids.

/**
 *
 *  Stock or Inventory Data
 *
 */
$product->get_backorders(); // Get backorders.
$product->get_availability(); // Returns the availability of the product.
$product->get_max_purchase_quantity(); // Get max quantity which can be purchased at once.
$product->get_min_purchase_quantity(); // Get min quantity which can be purchased at once.
$product->get_stock_managed_by_id(); // If the stock level comes from another product ID, this should be modified.
$product->get_stock_quantity(); // Returns number of items available for sale.
$product->get_stock_status(); // Return the stock status.
$product->get_total_stock(); // Get total stock - This is the stock of parent and children combined.
$product->get_sold_individually(); // Return if should be sold individually.
$product->get_low_stock_amount(); // Get low stock amount.

/**
 *
 *  Shipping Data
 *
 */
$product->get_height(); // Returns the product height.
$product->get_length(); // Returns the product length.
$product->get_weight(); // Returns the product's weight.
$product->get_width(); // Returns the product width.
$product->get_dimensions(); // Returns formatted dimensions.
$product->get_manage_stock(); // Return if product manage stock.
$product->get_shipping_class(); // Returns the product shipping class SLUG.
$product->get_shipping_class_id(); // Get shipping class ID.

/**
 *
 *  Product Variations / Parent Data
 *
 */
$product->get_child(); // Returns the child product.
$product->get_children(); // Returns the children IDs if applicable. Overridden by child classes.
$product->get_formatted_variation_attributes(); // Get formatted variation data with WC < 2.4 back compat and proper formatting of text-based attribute names.
$product->get_matching_variation(); // Match a variation to a given set of attributes using a WP_Query.
$product->get_parent(); // Get the parent of the post.
$product->get_parent_id(); // Get parent ID.
$product->get_variation_default_attributes(); // If set, get the default attributes for a variable product.
$product->get_variation_description(); // Get product variation description.
$product->get_variation_id(); // Get variation ID.

/**
 *
 *  Product Downloads
 *
 */
$product->get_download_expiry(); // Get download expiry.
$product->get_download_limit(); // Get download limit.
$product->get_downloadable(); // Get downloadable.
$product->get_downloads(); // Get downloads.
$product->get_file(); // Get a file by $download_id.
$product->get_file_download_path(); // Get file download path identified by $download_id.
$product->get_files(); // Same as $product->get_downloads in CRUD.

/**
 *
 *  Attributes, Tags, Categories & Associated Data Objects
 *
 */
$product->get_attribute(); // Returns a single product attribute as a string.
$product->get_attributes(); // Returns product attributes.
$product->get_categories(); // Returns the product categories.
$product->get_category_ids(); // Get category ids.
$product->get_default_attributes(); // Get default attributes.
$product->get_cross_sell_ids(); // Get cross sell IDs.
$product->get_cross_sells(); // Returns the cross sell product ids.
$product->get_related(); // Get and return related products.
$product->get_tag_ids(); // Get tag ids.
$product->get_tags(); // Returns the product tags.
$product->get_upsell_ids(); // Get upsell IDs.
$product->get_upsells(); // Returns the upsell product ids.
$product->get_meta(); // Get Meta Data by Key.
$product->get_meta_data(); // Get All Meta Data.

/**
 *
 *  Ratings and Reviews
 *
 */
$product->get_rating_count(); // Get the total amount (COUNT) of ratings, or just the count for one rating e.g. number of 5 star ratings.
$product->get_rating_counts(); // Get rating count.
$product->get_rating_html(); // Returns the product rating in html format.
$product->get_review_count(); // Get review count.
$product->get_reviews_allowed(); // Return if reviews is allowed.
$product->get_average_rating(); // Get average rating.

/**
 *
 *  Other Product Data
 *
 */
$product->get_changes(); // Return data changes only.
$product->get_data(); // Returns all data for this object.
$product->get_data_keys(); // Returns array of expected data keys for this object.
$product->get_data_store(); // Get the data store.
$product->get_date_created(); // Get product created date.
$product->get_date_modified(); // Get product modified date.
$product->get_extra_data_keys(); // Returns all "extra" data keys for an object (for sub objects like product types).
$product->get_menu_order(); // Get menu order.
$product->get_meta_cache_key(); // Helper method to compute meta cache key. Different from WP Meta cache key in that meta data cached using this key also contains meta_id column.
$product->get_object_read(); // Get object read property.
$product->get_post_data(); // Get the product's post data.
$product->get_post_password(); // Get post password.
$product->get_purchase_note(); // Get purchase note.

With this you can see under "other product data", that there is a date_modified you can order your products by.
It is not directly a list of all fields you can sort by. But it indirectly shows you which fields are available inside a product and what the fields are called. With the name, you are able to access them.
Custom meta:
Unfortunatelly there is no data saved for "published_date". But you could create a custom field for your product post type and save the date inside product. Via the meta key you can than access the data of the product and sort your products by your custom meta data.

A: If the point of the question is whether there is a list that returns all the fields that can be used for sorting, the short answer is no.
The woocommerce_get_catalog_ordering_args filter allows you to add your own ordering args, but there is no list that would store these fields. This filter is used to overwrite args, not to store it as an array.
Within the get_catalog_ordering_args() function, some orderby defaults are statically specified: id, menu_order, title, relevance, rand, date, price, popularity, rating.
But there is no way to tell what values have been added using a filter by WordPress plugins.

Possible solution:
There is a woocommerce_catalog_orderby filter that stores sorting options as an array.
This is used to display sorting options in the view. So you can assume that WordPress plugins will add options to this as well.
/**
 * Add orderby option by plugin
 */
add_filter( 'woocommerce_catalog_orderby', function ( $options ) {
    $options['order_by_plugin'] = __( 'Order by plugin setting', 'text-domain' );

    return $options;
} );

/**
 * Get orderby options
 */
$catalog_orderby_options = apply_filters( 'woocommerce_catalog_orderby', array(
    'menu_order' => __( 'Default sorting (custom ordering + name)', 'woocommerce' ),
    'popularity' => __( 'Popularity (sales)', 'woocommerce' ),
    'rating'     => __( 'Average rating', 'woocommerce' ),
    'date'       => __( 'Sort by most recent', 'woocommerce' ),
    'price'      => __( 'Sort by price (asc)', 'woocommerce' ),
    'price-desc' => __( 'Sort by price (desc)', 'woocommerce' ),
) );

You can use $catalog_orderby_options in which the sorting options are stored, if you only need the orderby fields, use the array_keys() function.
Note: you must specify the default value in apply_filters(), because WooCommerce added these statically, not using add_filter(). So you have to add it statically too.


Q: How to convert database table entry to an enum? In my web application I have many tables which have fixed data, when I use them in my project then I use enums for that purpose.
I want to convert these tables to enums automatically.
After little looking up I did this by using T4, TextTemplates: see my code here.
But I wanted to do this by using Entity Framework, according to the official documentation enums are supported in .NET Framework 4.5 and above, but I am using .NET 3.5.
How can I achieve this, potentially by using custom text templates?

A: So I finally solved it. Made a T4 template and replaced that with the default generated tt file.
My code is here, please star it if you found it helpful and add comments in case of help or suggestions.


Q: Making an image control invert its colors depending on theme I'm trying to work out how to have an Image control in my Windows Phone application invert its colors based on the global background setting (either "Dark" or "Light") chosen by the user in Settings->Themes->Background.

A: There is no built-in way to invert image colors within the framework.
Instead, because of the overhead of doing this on the phone, you should create both versions of the image at design/build time and then choose which version to display from your code by detecting Theme Visibility and Opacity.

A: I must add that what i did in the end was a continuation of what Matt wrote.

*

*create two different images that have different versions of the image (dark and light) and place them in the exact same position

*set their visibility based on the theme resource

the code looks like this:
<Image Height="30" HorizontalAlignment="Center" Margin="0,0,0,220" Name="imgDark" Stretch="Fill" Visibility="{StaticResource PhoneLightThemeVisibility}" VerticalAlignment="Center" Width="30" Source="/MyApplication;component/imageDarkTheme.png" />
<Image Height="30" HorizontalAlignment="Center" Margin="0,0,0,220" Name="imgLoading" Stretch="Fill" Visibility="{StaticResource PhoneDarkThemeVisibility}" VerticalAlignment="Center" Width="30" Source="/MyApplication;component/imageLightTheme.png" />

A: This Question is 1.5 years old now. But here is the easiest way to do what you want. The example given there is very simple like
<Button>
    <Image Stretch="None" Source="{Binding Converter={StaticResource ThemedImageConverter}, ConverterParameter={StaticResource PhoneBackgroundColor} }"
           DataContext="/WP7SampleProject4;component/Images/{0}/appbar.feature.camera.rest.png" />
</Button>


Q: Calling drawnow causes heap corruption I'm still new to Matlab and Simulink and I'm seeing a strange problem.
I have a series of Simulink blocks (processA, processB, etc) which are Matlab functions connected serially. They all have the same format.
function outConfig = run_processA_Fcn(inConfig)

coder.extrinsic('hilite_system');
hilite_system('myModel/processA');
drawnow;

coder.extrinsic('run_processA_mex');
run_processA_mex(inConfig);

hilite_system('myModel/processA', 'none');
drawnow;

outConfig = inConfig;

The function run_processA_mex() is a .mexw64 MEX function which take in pointers to the heap (via inConfig). Inside these MEX functions I am calling my Visual Studio compiled C code (within a DLL).
Each Simulink block could take some time to process, so I wanted it to highlight the current block. The problem is when I call drawnow, the data from my pointers change to some invalid values. The pointers themselves point to the same address, just the values they point to are wrong. If I just comment out the drawnow, my data is okay.
I'm not clear on the best way around this. I don't know why calling drawnow would corrupt my heap. Any help would be great.

A: Okay, this was silly of me. The pointers I was passing were pointing to the heap but they were pointers to pointers. The final data was sitting on the stack, so I was losing that data because of the additional function calls I introduced.
I've properly allocated the data onto the heap now and it seems to be working now.


Q: Python (+Django) : use @property in success_url KO . while using it with get_success_url is OK (class based view) I found a workaround for my issue but I need to know why the first above case doesn't work.
I need to pass a parameter (reman_pk) to my view but when I try :
class RepairCreateView(LoginRequiredMixin, CreateView):

    @property
    def reman_pk(self):
        return int(self.kwargs['reman_pk'])
    [...]
    success_url = reverse_lazy(
        'reman:update-reman', kwargs={'pk': reman_pk})
    [...]

... I got an error
django.urls.exceptions.NoReverseMatch: Reverse for 'update-reman' with keyword arguments '{'pk': <property object at 0x10c20bbd0>}' not found. 1 pattern(s) tried: ['reman/update/(?P[0-9]+)/$']
But when in the same class based view I use :
def get_success_url(self, **kwargs):
        if kwargs != None:
            return reverse_lazy('reman:update-reman', kwargs={'pk': self.reman_pk})

... it's OK : an int is well passed in my URL.
I tried to pass int(reman_pk) in the first method ... not better.
I've already use @property in the past and always got a value (int/str) and not property object.
EDIT (FULL views.py)
success_url = reverse_lazy...is commented. I must use def get_success_url( ... instead. Otherwise I get the above mentioned error.
class RepairCreateView(LoginRequiredMixin, CreateView):

    @property
    def reman_pk(self):
        return int(self.kwargs['reman_pk'])

    # success_url = reverse_lazy(
    #     'reman:repairs-list', kwargs={'pk': reman_pk})

    success_message = "Nouvelle réparation créée"
    form_class = RepairCreateForm
    template_name = 'reman/repair_create_form.html'

    def get_context_data(self, *args, **kwargs):
        context = super(RepairCreateView, self).get_context_data(
            *args, **kwargs)
        context['title'] = 'Nouveau Repair'
        context['pk'] = self.reman_pk
        return context

    def get_initial(self):
        reman = Reman.objects.get(pk=self.reman_pk)
        return {'reman': reman}

    def get_success_url(self, **kwargs):
        return reverse_lazy('reman:repairs-list', kwargs={'pk': self.reman_pk})

A: This is not related to django, this is related to python in general. When you want to access a class property within the class you always have to call self before!
class Tree:
    fruits = 5

    @property
    def leafes(self):
        return self.fruits * 5

    def show_tree(self):
        print(self.fruits)
        print(self.leafes)
        print(leafes)  # THIS LINE WOULD ERROR

Edit after comment of OP
I don't know how to phrase this properly. Anyhow this keeps being a problem related to python and not to django. The reason is how classes work.
You probably know the def __init__(self): function. That is called when the class gets instanciated. After that function got called your class can use all the self attributes (class attributes). But class attributes like my fruits = 5 get assigned even before that def __init__(self) method is called. So all your assignments directly inside the body of the class do not have self yet.
class Tree:
    fruits = 5

    def __init__(self):
        self.twigs = 10
        self.weight = self.twigs + self.fruits  # THIS WORKS

class Tree:
    fruits = 5
    weight = self.twigs + fruits  # THIS DOES NOT WORK

    def __init__(self):
        self.twigs = 10

Last example does not work because at the moment you want to assign weight = self.twigs + fruits your class's __init__ function was not called yet. So you can not use self at that place.


Q: Auto layout delayed on label I have a calculator app (just like the apple in-built calculator app) and I used auto-layout. Everything is working fine in portrait mode but when I rotate the screen to landscape the UIButtons resize according to the screen size but the UILabel that show result resizes after a delay, i.e. when I rotate the screen to landscape mode the UITextField also rotate but the size of UITextField is same as the portrait size for 2 seconds and then it resizes correctly.
Is it something related to hugging priority or compression priority?
The content hugging priority
Horizontal - 251
Vertical - 251
Content compression resistance priority
Horizontal - 750
Vertical - 750
Hope you understand the question
Thanks in advance.

see the second screenshot the display (i.e. the zero is not towards the margin but at the middle but after 2 seconds it sizes correctly.)


Q: Loading SQLite data using AsyncTask , What am I doing wrong? I'm new to android and java, and I'm trying to implement an Asynchronous Loader. But no data is being loaded. Am I missing something conceptually here?
My Activity:
public class TestActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {

ListView bookList;
MyCursorAdapter myAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_admin_library);
  //  dloader = new DBLoader(this);
    //dloader.loadInBackground();

   /* blah blah*/

    getSupportLoaderManager().initLoader(1,null,this);

    /* blah blah*/
    View header = (View) getLayoutInflater().inflate(R.layout.row_layout_title, null);
    TextView totals = header.findViewById(R.id.mainText);
    totals.setText("Total Books: " + Integer.toString(totalBooks));
    bookList.addHeaderView(header);

    bookList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            /* blah blah*/
            }

        }
    });
    /* blah blah*/
}

 /* blah blah*/

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
   /*CursorLoader loader = new CursorLoader(this, null, null, null, null, null){
        @Override
        public Cursor loadInBackground(){
            DBHandler db = new DBHandler(getContext());
            return db.getCursor();
        }
   };*/
   DBLoader loader  = new DBLoader(this);
    return loader;
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    myAdapter = new MyCursorAdapter(this,data,0);
    bookList.setAdapter(myAdapter);
    // myAdapter.swapCursor(data);
    //myAdapter.notifyDataSetChanged();
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
    myAdapter.swapCursor(null);

}
}

DBLoader:
public class DBLoader extends AsyncTaskLoader<Cursor> {

private Cursor mCursor;
Context context;
public DBLoader(Context context) {
    super(context);
    this.context = context;
}

@Override
public Cursor loadInBackground() {
    DBHandler db = new DBHandler(context);
    Cursor cursor = db.getCursor();
    return cursor;
}

@Override
public void deliverResult(Cursor cursor){
    if(isReset()){
        releaseResources(cursor);
        return;
    }

    Cursor oldCursor = mCursor;
    mCursor = cursor;

    if(isStarted()){
        super.deliverResult(cursor);
    }

    if(oldCursor!=null && oldCursor!=cursor){
        releaseResources(oldCursor);
    }
}

private void releaseResources(Cursor cursor) {
    cursor.close();
}
}

I don't know if I'm missing any important calls here, and most resources on the internet are about content providers(which I don't need). What I simply need is to asynchronously load data from my local SQLite database.
EDIT: My Adapter:
public class MyCursorAdapter extends CursorAdapter {

private LayoutInflater cursorInflater;

public MyCursorAdapter(Context context, Cursor c, int flags) {
    super(context, c, flags);
    cursorInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {

    return cursorInflater.inflate(R.layout.row_layout, parent, false);
}

@Override
public void bindView(View v, Context context, Cursor cursor) {
    Log.d("Cursor :", cursor.getString(1));
    TextView title = (TextView) v.findViewById(R.id.listTitle);
    title.setText(cursor.getString(1));
    TextView author = (TextView) v.findViewById(R.id.listAuthor);
    author.setText(cursor.getString(2));
    TextView copies = (TextView) v.findViewById(R.id.listCopies);
    copies.setText(cursor.getString(5));

}

}

A: Declare your DBLoader loader as global variable
at the onCreateLoader
loader  = new DBLoader(this);
return loader;

put this at the onCreate method instead of onLoadFinished
myAdapter = new MyCursorAdapter(this,null,0);
bookList.setAdapter(myAdapter);

put this at onLoadFinishied
this.loader=(DBLoader)loader;
adapter.changeCursor(cursor);

A: After some searching, I saw a few examples on the internet where they use
a getSupportLoaderManager().initLoader(1,null,this).forceLoad();. That seems to work. also calling loader.forceLoad() in the onCreateLoader() works too. On further checking, I saw this : https://issuetracker.google.com/issues/36925900
It seems we have to implement forceLoad in onStartLoading() as thus:
protected void onStartLoading() {
if (mCursor != null) {
    deliverResult(mCursor);
}
if (takeContentChanged() || mCursor == null) {
    forceLoad();
}
}

doing this will cease the need for a .forceLoad() in our Activity


Q: Bookmarklet, js injection and popup issue I'm currently writing a bookmarklet that loads and executes a remote js file by appending a new <script> tag in the current window, like so :
javascript:(function() {
    if(typeof __bml_main != "undefined") return __bml_main.init();
    var s= document.createElement('script');
    s.type= 'text/javascript';
    s.src= 'http://127.0.0.1:8000/media/bookmarklet.js';
    void(document.body.appendChild(s));
})();
My bookmarklet needs to perform some dom manipulations in order to extract data from the page being viewed, and then to open a new popup to list them.
The thing is : if I want to bypass pop-up blockers, I can't open my new window from the injected script. I need to open it right from the beginning in the bookmarklet code, and to access it later when needed.
I've tried to do somehting like this :
javascript:var my_popup = window.open('http://127.0.0.1:8000/resources/manage/new/', 'newResourcePopup',config='height=200,width=400,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,directories=no,status=no');
(function() {
// script injection (...)
})();
but if I then try to access my_popup from my remotely loaded script, most browsers will throw a security warning and won't let me access the Window object. This is understandable since the script is not from the same domain than the displayed page, but I'm kind of stuck...
A solution would be to use a div overlay, but I'd really prefer to open a window in this case.
Any hints ?

A: You could load the markup for the window as a string in your bookmarklet.js file, then (later) use window.open without a URL (or with "about:blank", I forget which is more cross-browser-compatible), and use my_popup.document.write to write the markup to the new window.
You may find that you can't open the window later, even without cross-domain issues, unless you're doing so in direct response to a user action — which is probably a good thing. :-)


Q: In Python 2, what are the performance trade-offs for viewvalues()/viewitems() over itervalues()/iteritems()? Obviously, using values, items, and keys is bad practice in Python 2.X in virtually every instance, because you'll allocate an extra list you don't actually need.  Thus, for some time, the recommended best practice was to use iteritems/itervalues, and to use the built-in __iter__ if you wanted to enumerate the dict's keys.
With the backport of Python 3's keys, values, and items to Python 2.7 as viewkeys, viewvalues, and viewitems, I'm wondering what the actual performance tradeoffs are of the view* family of functions, vs. their iter* counterparts.  Is the only reason to continue using the iter* functions that you are targeting Python 2.6 and earlier, or can the older iter* methods be faster than the newer view* methods in certain contexts?

A: Here's an answer addressing iterkeys vs. viewkeys here: https://stackoverflow.com/a/10190228/344143
Summary (with a little backstory): view* methods are a live view into the data (that will update as it updates), whereas iter* and just-plain * are more like snapshots.
The linked answerer suggests that while the view*-flavored methods may have a minor performance edge as well, there may be compatibility issues with the backport, and recommends continuing to use iter*/* under Python 2.
My take: if you want a live view and you're under Python 2, use view*; if you just want to whip through the set of keys/values/items once, use iter*; if you want to hang on to a snapshot of k/v/i for a bit (or iterate in some non-linear fashion), use *. Let the performance slide until you pick it up in an inner loop.


Q: can we use js variable name as class name in html I want to concatinate class name with variable count which keep getting updated after each button click, for which I am getting error as "citysName is null". can anyone suggest
button.addEventListener('click', resp => {
    count = count +1;
    var card = document.createElement('card');
    card.innerHTML = `

                  **

**

    `;
    card.className = 'card';
    var content = document.getElementById('id1');
    content.appendChild(card);
    **var citysName = document.querySelector('.card_title'+count);
    var description = document.querySelector('.card-text'+count);
    var temp = document.querySelector('.temp'+count);**
    fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputVal.value+'&appid=a5599c020b0d897cbc8b52d547289acc')
    .then(post => post.json())
    .then(data => {
        var cityName = data['name'];
        var temper = data['main']['temp'];
        var descrip = data['weather'][0]['description'];

        let ctemp = Math.round(temper-273);
        citysName.innerHTML = cityName;
        temp.innerHTML = ctemp + "°C";
        description.innerHTML = descrip;
    })
})

A: First of all thats not how you add variables using template literals you can read more about it here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Second why do you query it again when you've just made the element you can use card as reference and if you need something within it, its much easier to access it using the variable you already have other than looking for it in your document
Maybe something like this but its hard to tell withouth more code etc
button.addEventListener('click', resp => {
    count = count +1;
    var card = document.createElement('card');
    card.innerHTML = `

                  **

**

    `;
    card.className = 'card';
    var content = document.getElementById('id1');
    content.appendChild(card);
    var citysName = card.querySelector('.card_title'+count);
    var description = card.querySelector('.card-text'+count);
    var temp = card.querySelector('.temp'+count);
    fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputVal.value+'&appid=a5599c020b0d897cbc8b52d547289acc')
    .then(post => post.json())
    .then(data => {
        var cityName = data['name'];
        var temper = data['main']['temp'];
        var descrip = data['weather'][0]['description'];

        let ctemp = Math.round(temper-273);
        citysName.innerHTML = cityName;
        temp.innerHTML = ctemp + "°C";
        description.innerHTML = descrip;
    })
})


Q: Excel DNA with ILNumerics I have used ILNumerics via Excel DNA in Excel successfully for some time. Now I wrote a new function which uses the linsolve function from ILNumerics (which needs the mkl_custom.dll) and I cannot build this into an XLL.
My custom function works in debug which is why I assume sth in the packaging goes wrong.
Here is my dna file:
<DnaLibrary Name="Nik's Lib" RuntimeVersion="v4.0">
   <ExternalLibrary Path="MyLib2010.dll" Pack="true"/>
   <Reference  Path="ILNumerics.dll" Pack="true"/>
   <Reference  Path="mkl_custom.dll" Pack="true"/>
</DnaLibrary>

When packaging this I get the error message that path for mkl_custom.dll
path not found

This might be due to the folder structure of the dll:

Any pointers on how to resolve this would be appreciated.

A: The Excel-DNA packing does not currently support native or mixed assemblies. So you won't be able to use the mechanism to pack the mkl library.
You might be able to store it in your C# assembly as a resource, and extract it yourself at runtime (in an AutoOpen or something, before any of the functions using it are run). If you extract it to a temp file, then call LoadLibrary yourself to load it into the process, it should work when ILNumerics needs it.


Q: How can I write float value in python that can be read natively in Java? How can I write float value to file in python so that it can be later read in Java with ObjectInputStream#readFloat?
I need high read performance, so I'd like to avoid parsing the float from String.

A: Use the struct module (documentation), specifying the data as a float.


Q: Google Earth Engine How to Create a CNN Model for a Multi-class Image Classification I am trying to build a satellite image classifier CNN using Google Earth Engine. I have been stuck on this problem for almost a week now and any help would be greatly appreciated. I have been following this tutorial: https://colab.research.google.com/github/google/earthengine-api/blob/master/python/examples/ipynb/UNET_regression_demo.ipynb#scrollTo=CTS7_ZzPDhhg
I am using 6 input bands (3RGB, 3IR) and 1 band for labels. By using neighbourhoodToArray() function, I construct a 256 x 256 rectangle so I can use it in a CNN classifier.
KERNEL_SIZE = 256
featureStack = ee.Image.cat([
  l8_image.select(BANDS),
  aafc_image.select(LABEL)
]).float()

list = ee.List.repeat(1, KERNEL_SIZE)
lists = ee.List.repeat(list, KERNEL_SIZE)
kernel = ee.Kernel.fixed(KERNEL_SIZE, KERNEL_SIZE, lists)
arrays = featureStack.neighborhoodToArray(kernel)

n = 200 # Number of shards in the polygon.
N = 2000 # Total sample size in the polygon.

# Export all the training data (in many pieces), with one task
# per geometry.
training = ee.FeatureCollection([])
for i in range(n):
    sample = arrays.sample(
      region = BOUNDED_AREA,
      scale = 30,
      numPixels = N / n, # Size of the shard.
      seed = i, # random sample location seed
      tileScale = 8
    )
    training = training.merge(sample)

And then I export this to Drive and then get it back in a TFRecord format. But, when I get the data in a TFRecord format, the input is of shape (256, 256, 7) so I divide it into training and labels such that training is of shape (256, 256, 6) and labels is of shape (256, 256, 1).
But the thing here is that, I want my output node in the model to be a one-hot encoded vector that uses categorical cross entropy loss. But since my labels are in the shape of (256, 256, 1), I can't have it because the labels should have a form of (N_CLASSES,). To be more clear, my model should be in the form of:
model2 = tf.keras.models.Sequential([
  tf.keras.layers.Input(shape=(256, 256,  6)),
  tf.keras.layers.Conv2D(256, (3,3), padding='same', activation=tf.nn.relu), #4d
  tf.keras.layers.Conv2D(128, (3, 3), padding='same', activation=tf.nn.relu), # 4D
  tf.keras.layers.Conv2D(64, (3,3), padding='same', activation=tf.nn.relu), # 4D
  tf.keras.layers.Flatten(), # 1D
  tf.keras.layers.Dense(256, activation=tf.nn.relu), # 1D
  tf.keras.layers.Dense(128, activation=tf.nn.relu),
  tf.keras.layers.Dense(N_CLASSES, activation=tf.nn.softmax) # (72,)
])

# Compile the model with the specified loss function.
model2.compile(optimizer=tf.keras.optimizers.Adam(),
              loss='categorical_crossentropy',
              metrics=['accuracy'])

history2 = model2.fit(x=training, epochs=5)

I have tried
def to_tuple(inputs):
  """Function to convert a dictionary of tensors to a tuple of (inputs, outputs).
  Turn the tensors returned by parse_tfrecord into a stack in HWC shape.
  Args:
    inputs: A dictionary of tensors, keyed by feature name.
  Returns:
    A tuple of (inputs, outputs).
  """
  inputsList = [inputs.get(key) for key in FEATURE_NAMES]
  stacked = tf.stack(inputsList, axis=0)
    # for Conv2D, input should be (BATCH, HEIGHT, WIDTH, CHANNEL)
    # Convert from CHW to HWC - meaning channel-height-width to height-width-channel
  stacked = tf.transpose(stacked, [1, 2, 0])
  labels = stacked[:, :, len(BANDS):] # first one is inputs (first 6 bands), second is only the last band - label
  reshaped_labels = tf.reshape(tf.cast(labels, tf.int32), [KERNEL_SIZE * KERNEL_SIZE])
  return stacked[:,:,:len(BANDS)], tf.one_hot(indices=reshaped_labels, depth=N_CLASSES) # depth makes the 2nd dimension 72

By doing so my labels is of shape (256*256, 72), but still not exactly what I want. If there is a CNN classification tutorial I can follow (not UNET or regression), that information is also greatly appreciated.


Q: springframework.integration.kafka ConsumerContext Iterator is in failed state When trying to consume a topic on my java application I get the following exception:
    org.springframework.integration.kafka.support.ConsumerConfiguration.executeTasks(ConsumerConfiguration.java:135)
        ... 32 more
Caused by: java.lang.IllegalStateException: Iterator is in failed state
        at kafka.utils.IteratorTemplate.hasNext(IteratorTemplate.scala:54)
        at kafka.utils.IteratorTemplate.next(IteratorTemplate.scala:38)
        at kafka.consumer.ConsumerIterator.next(ConsumerIterator.scala:46)
        at org.springframework.integration.kafka.support.ConsumerConfiguration$1.call(ConsumerConfiguration.java:104)
        at org.springframework.integration.kafka.support.ConsumerConfiguration$1.call(ConsumerConfiguration.java:98)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        ... 3 more

This exception happens after a while when processing a lot of messages. And always happens on the same topic.
The configuration of the kafka consumer is:
<int-kafka:zookeeper-connect id="zookeeperConnect"
    zk-connect="${kafkaZookeeperUrl}" zk-connection-timeout="${kafkaZkConnectionTimeout}"
    zk-session-timeout="${kafkaZkSessionTimeout}" zk-sync-time="${kafkaZkSyncTime}" />

<!-- -->
<!-- Spring Integration -->
<!-- -->
<bean id="consumerProperties"
    class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="properties">
        <props>
            <prop key="auto.commit.enable">${kafkaConsumerAutoCommitEnable}</prop>
            <prop key="auto.commit.interval.ms">${kafkaConsumerAutoCommitInterval}</prop>
            <prop key="fetch.min.bytes">${kafkaConsumerFetchMinBytes}</prop>
            <prop key="fetch.wait.max.ms">${kafkaConsumerFetchWaitMax}</prop>
            <prop key="auto.offset.reset">${kafkaConsumerOffsetReset}</prop>
        </props>
    </property>
</bean>
<!-- -->
<!-- Channels -->
<!-- -->
<int:channel id="kafka1">
    <int:interceptors>
        <int:wire-tap channel="kafkaWiretap" />
    </int:interceptors>
</int:channel>
<!-- -->
<!-- Consumer Contexts -->
<!-- -->
<int-kafka:consumer-context id="consumerContext1"
    consumer-timeout="${kafkaDataInTimeout}" zookeeper-connect="zookeeperConnect"
    consumer-properties="consumerProperties">
    <int-kafka:consumer-configurations>
        <int-kafka:consumer-configuration
            group-id="dataWriterSource" value-decoder="valueDecoder"
            key-decoder="valueDecoder" max-messages="${kafkaDataInMaxMessages}">
            <int-kafka:topic id="DATA_IN" streams="${kafkaDataInStreams}" />
        </int-kafka:consumer-configuration>
    </int-kafka:consumer-configurations>
</int-kafka:consumer-context>
<!-- -->
<!-- Inbound Channel Adapters -->
<!-- -->
<int-kafka:inbound-channel-adapter
    id="kafkaInboundChannelAdapter1" kafka-consumer-context-ref="consumerContext1"
    auto-startup="${kafkaConsumerChannelAutoStartup}" channel="kafka1">
    <int:poller fixed-delay="10" time-unit="MILLISECONDS"
        max-messages-per-poll="1000" />
</int-kafka:inbound-channel-adapter>

The topic has 600 partitions and it receives a lot of messages.
The configuration of the context consumer is:
####################################
# KAFKA Consumers Configuration.
####################################
# General consumer properties
kafkaConsumerAutoCommitEnable=true
kafkaConsumerAutoCommitInterval=500
kafkaConsumerFetchMinBytes=1
kafkaConsumerFetchWaitMax=100
kafkaConsumerOffsetReset=largest

# Consumers
# Data In
kafkaDataInTimeout=500
kafkaDataInMaxMessages=5000
kafkaDataInStreams=4

Now as far as I can check, there is some kind of a problem, either with how I have configured the poller for the consumer or there is a bug in the following piece of code on the ConsumerContext.java:
private Map<String, Map<Integer, List<Object>>> executeTasks(
        final List<Callable<List<MessageAndMetadata<K, V>>>> tasks) {

    final Map<String, Map<Integer, List<Object>>> messages = new ConcurrentHashMap<String, Map<Integer, List<Object>>>();
    messages.putAll(getLeftOverMessageMap());

    try {
        for (final Future<List<MessageAndMetadata<K, V>>> result : this.executorService.invokeAll(tasks)) {
            if (!result.get().isEmpty()) {
                final String topic = result.get().get(0).topic();
                if (!messages.containsKey(topic)) {
                    messages.put(topic, getPayload(result.get()));
                }
                else {

                    final Map<Integer, List<Object>> existingPayloadMap = messages.get(topic);
                    getPayload(result.get(), existingPayloadMap);
                }
            }
        }

public ConsumerMetadata<K, V> getConsumerMetadata() {
    return consumerMetadata;
}

public Map<String, Map<Integer, List<Object>>> receive() {
    count = messageLeftOverTracker.getCurrentCount();
    final Object lock = new Object();

    final List<Callable<List<MessageAndMetadata<K, V>>>> tasks = new LinkedList<Callable<List<MessageAndMetadata<K, V>>>>();

    for (final List<KafkaStream<K, V>> streams : createConsumerMessageStreams()) {
        for (final KafkaStream<K, V> stream : streams) {
            tasks.add(new Callable<List<MessageAndMetadata<K, V>>>() {
                @Override
                public List<MessageAndMetadata<K, V>> call() throws Exception {
                    final List<MessageAndMetadata<K, V>> rawMessages = new ArrayList<MessageAndMetadata<K, V>>();
                    try {
                        while (count < maxMessages) {
                            final MessageAndMetadata<K, V> messageAndMetadata = stream.iterator().next();
                            synchronized (lock) {
                                if (count < maxMessages) {
                                    rawMessages.add(messageAndMetadata);
                                    count++;
                                }
                                else {
                                    messageLeftOverTracker.addMessageAndMetadata(messageAndMetadata);
                                }
                            }
                        }
                    }
                    catch (ConsumerTimeoutException cte) {
                        LOGGER.debug("Consumer timed out");
                    }
                    return rawMessages;
                }
            });
        }
    }
    return executeTasks(tasks);
}

The line 104 is final MessageAndMetadata messageAndMetadata = stream.iterator().next(); not synch and may get into conflict with the line 135: if (!result.get().isEmpty()) {
Any help from the spring integration kafka people will be really great. The question is: What is going on and how can we solve the issue.
Thanks in advance,
Francisco


Q: Node.js module: export async function In the given example it is demonstrated, how to export a variable, or a function from a custom module. How could one export an asynchronous function in a similar manner and then call it from app.js something like:
// app.js

var things = require("./someThings");

await things.getSomeThingsAsync();

EDIT:
The example (answer on Stackoverflow) pointed to by the above link contains the following code:
// someThings.js

(function() {
    var someThings = ...;

    ...

    module.exports.getSomeThings = function() {
        return someThings();
    }

}());

// main.js

var things = require("someThings");
...
doSomething(things.getSomeThings());

Say inside of the module's incapsulated function a asynchronous function exists, which you would like to expose to whoever imports the module. For example:
(function() {
    ...
    const doSomethingAsync = (time) => {
        return new Promise(resolve => {
            setTimeout(() => resolve(42), time)
        })
    }

    //const doSomething = async () => {
    async function doSomething () {
        let answer1 = await doSomethingAsync(3000)
        let answer2 = await doSomethingAsync(1000)
        return answer1 + answer2
    }
    ...
    /*module.exports.doSomething = function() {
        return doSomething();
    }*/
    module.exports.doSomething = async function() {
        return doSomething();
    }
}());

How would you expose the doSomething function in similar fashion as the in the original answer it is done for someThings - how can the referred to answer be changed in such a way, that when exporting functions, it lets you use the await keyword? It will then be used as:
// app.js

var things = require("./someThings");

console.log(await things.doSomething());

I have tried multiple approaches, but I always get:
SyntaxError: await is only valid in async function

A: You can try this :
//yourModule.js

let yourModule={};
yourModule.you=async()=>{
    //something await...
}
modules.export = yourModule;

//app.js

let yourModule = require('<pathToModule>');

async function test()
{
    await yourModule.you();  //your `await` here
}

A: You are misunderstanding the error. It says

SyntaxError: await is only valid in async function

not "for async function"
There is no problem with your export. It is simply not possible to use await outside of a function marked async. Therefore the bug is in app.js. It should be:
var things = require("./someThings");

async function app () {
    console.log(await things.doSomething());
}

app().then(() => console.log('done calling app()'));

A: This is probably a duplicate of this question.
You can simply assign the function (or a function expression) to a property (or just the entirety) of `module.exports’.
For example:
async function AsyncStuff () { ... }

module.exports.myAsyncThing = myAsyncStuff;

A: Try this
var things = require("./someThings");
let result = getResult();
async function getResult() {
    return await things.getSomeThingsAsync();
}


Q: Move last item in flexbox to new line when items take up different width

.main{
  display:flex;
  border: 1px solid black;
}

.item, .item2, .item3, .item4{
  padding: 10px;
}

.item {
  flex-grow: 1;
  flex-wrap: wrap;
}

.item2{
  flex-grow: 7;
  background-color: pink;
}

.item3 {
  flex-grow: 2;
  background-color: yellow;
}

1

2

3

4

In the above scenario, how can I move item 4 into a new line? All the examples I've seen, it's possible when the items are of the same width.

A: You need to activate the wrap on the parent element (the flex container) then make the element full width:

.main{
  display:flex;
  border: 1px solid black;
  flex-wrap:wrap;
}

.item, .item2, .item3, .item4{
  padding: 10px;
}

.item {
  flex-grow: 1;
}

.item2{
  flex-grow: 7;
  background-color: pink;
}

.item3 {
  flex-grow: 2;
  background-color: yellow;
}
.item4 {
  flex-basis:100%;
}

1

2

3

4

A: Use .item-groups to organize your .items by row. Example:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.main {
  display: flex;
  border: 1px solid black;
  flex-wrap: wrap;
}

.item-group {
  flex-basis: 100%;
  display: flex;
}

.item1, .item2, .item3, .item4 {
  padding: 10px;
}

.item1 {
  flex-grow: 1;
}

.item2{
  flex-grow: 7;
  background-color: pink;
}

.item3 {
  flex-grow: 2;
  background-color: yellow;
}

.item4 {
  background-color: violet;
}

1

2

3

4


Q: SQL Server "An invalid floating point operation occurred" This is not really a problem because I solved it. But, I wanted to share something that ate my brain today. So, run this query and check it out:
The query:
select 2 as ID1,0 as ID2 into #TEMP
insert into #TEMP (ID1,ID2)
values (2,1),(2,2),(2,0)

select
  case when min(case when ID1=2 and ID2=0 then 0
                     else 1
                end)=0 then 0
       else sum(log(ID2))
  end
from #TEMP

The fix:
select
  case when min(case when ID1=2 and ID2=0 then 0
                     else 1
                end)=0 then 0
       else sum(log(case when ID1=2 and ID2<>0 then ID2
                         else 1
                    end))
  end
from #TEMP

My query was larger and more difficult to debug, but what do you say about the plan that MSSQL is making and the fact that it gets it wrong with this query? How can it be modified to work except my little fix that I showed before? I am guessing that computing scalars before the query would make things slow if the scalars are not easy to compute and we compute for all values.

A: SQL Server does not perform short circuit evaluation (i.e. should not be relied upon). It's a fairly well known problem.
Ref:

*

*Don’t depend on expression short circuiting in T-SQL (not even with CASE)

*Short Circuit

*Short-Circuit Evaluation

*Is the SQL WHERE clause short-circuit evaluated?

A: EDIT: I misunderstood the question with my original answer.
I supposed you could add a where clause, as shown below.  Side note: this query might benefit from an index on (ID1, ID2).
select
  sum(log(convert(float, ID2)))
from #TEMP
where
    -- exclude all records with ID1 = 2 if there are any records with ID1 = 2 and ID2 = 0
    not exists (
        select 1
        from #TEMP NoZeros
        where
            NoZeros.ID1 = #TEMP.ID1
            and NoZeros.ID2 = 0
    )

Update: Just in case performance is a concern, I got fairly comparable performance from this query after adding the following indexes:
create index ix_TEMP_ID1_ID2 on #TEMP (ID1, ID2)
create index ix_TEMP_ID2 on #TEMP (ID2) include (ID1)

Original Answer
How about modifying your sum function as shown below?
sum(case ID2 when 0 then null else log(convert(float, ID2)) end)


Q: Python iterate over regex condition to replace column's values Suppose I have a non-standardized dataframe with keywords like this:
data = pd.DataFrame({'tool_description':['bond assy fixture', 'pierce die', 'cad geometrical non-template',
                                         '707 bond assy fixture', 'john pierce die', '123 cad geometrical non-template',
                                         'jjashd bond assy fixture', '10481 pierce die', '81235 cad geometrical non-template']})

Dataframe:

tool_description

bond assy fixture

pierce die

cad geometrical non-template

707 bond assy fixture

john pierce die

123 cad geometrical non-template

jjashd bond assy fixture

10481 pierce die

81235 cad geometrical non-template

As you can see, the keywords, in this case, are bond assy fixture, pierce, and cad geometrical non-template.
I want to replace those values based on their keywords to have a standardized data. So I worked on a workaround like this:
# Pull the data matching my regex condition
X = data.loc[data.tool_description.str.contains((r"\b(bond assy fixture)\b"), case=False, regex=True), :]

# Replace values by a standardized name
X['tool_description] = 'bond assy fixture'

# Pull index from X dataset
index_list = X.tool_description.index.tolist()

# Create empty column in the original dataset
data['standardized_column'] = ""

# Loop to fill new column with a standardized description
for index in index_list:
    data.loc[index, 'standardized_column'] = 'bond assy fixture'

Output:

tool_description
standardized_column

bond assy fixture
bond assy fixture

pierce die
nan

cad geometrical non-template
nan

707 bond assy fixture
bond assy fixture

john pierce die
nan

123 cad geometrical non-template
nan

jjashd bond assy fixture
bond assy fixture

10481 pierce die
nan

81235 cad geometrical non-template
nan

This works fine, however for one condition, and I need to make a loop of all these for hundreds of regex conditions. When I try to loop over the line where I use this line of code
conditions = ['a', 'b', 'c']
for i in conditions:
    X = data.loc[data.tool_description.str.contains((r"\b(i)\b"), case=False, regex=True), :]

I have a problem placing the regex condition as an iterator. When the loop extracts the str from the list of conditions it will pull it with the quotation mark.
Now that I have put you in context, I have the following questions:

*

*Is there a simpler and elegant way to replace those values?

*If not, how can I create a loop to iterate over that regex?

Thank you for your time and answers. I know I could have asked how to remove the quotation mark for iteration purposes using regex, but, I wanted to know also if there's another way to solve the general problem which is the replacement of values.

A: You could write a function to attempt to find the matching substring, and return 'nan' if not found
def replace(s):
    keywords = ['bond assy fixture', 'pierce', 'cad geometrical non-template']
    try:
        return next(i for i in keywords if i in s)
    except StopIteration:
        return 'nan'

Then you can use apply to make this substitution
>>> data['standardized_column'] = data.tool_description.apply(replace)
>>> data
                     tool_description           standardized_column
0                   bond assy fixture             bond assy fixture
1                          pierce die                        pierce
2        cad geometrical non-template  cad geometrical non-template
3               707 bond assy fixture             bond assy fixture
4                     john pierce die                        pierce
5    123 cad geometrical non-template  cad geometrical non-template
6            jjashd bond assy fixture             bond assy fixture
7                    10481 pierce die                        pierce
8  81235 cad geometrical non-template  cad geometrical non-template

Instead of if i in s you could use a regex in the replace function as well if you need something more complex than a simple substring check.

A: You are close to the solution, just minor touch-ups needed, as follows:
data['standardized_column'] = np.nan     # init column to NaN

for word in keywords:
    data.loc[data.tool_description.str.contains((rf"\b{word}\b"), case=False, regex=True), 'standardized_column'] = word

Here, we use word boundary \b to enclose the keyword in the regex so that partial word match is avoided.  Eg.  'pierce' won't match with 'mpierce'.  Python test of StringA in StringB would produce false match since pierce in mpierce is True but not what we want to match.
Result:
print(data)

                     tool_description           standardized_column
0                   bond assy fixture             bond assy fixture
1                          pierce die                        pierce
2        cad geometrical non-template  cad geometrical non-template
3               707 bond assy fixture             bond assy fixture
4                     john pierce die                        pierce
5    123 cad geometrical non-template  cad geometrical non-template
6            jjashd bond assy fixture             bond assy fixture
7                    10481 pierce die                        pierce
8  81235 cad geometrical non-template  cad geometrical non-template


Q: PHP Code not executing on Ubuntu Server The following script is running on my localhost without any problems. It creates a json file that I request using AJAX to build a table in my front end. However, when I put it on my Ubuntu VM, which runs apache 2 and php 5.5 (json module is installed) it doesn't create the json file, the result being that my table is empty.
<?php
$arr = scandir('.\lehre\test');
foreach($arr as $k=>$v){
    if($arr[$k] == "." || $arr[$k] == ".."){
        unset($arr[$k]);
    }
    $fp = fopen('files.json', 'w');
    fwrite($fp, json_encode($arr));
    fclose($fp);
}
?>

PS: Other PHP Elements, like the include statement work.
EDIT: I don't get any error msg. I use the forward slash notation within any other path declaration

A: By the sounds of it your development environment is a Windows machine I'm guessing, which makes use of back slashes (\) when referencing directory paths. However on UNIX systems (Ubuntu in your case) the system uses forward slashes (/).
Good news however, even though the Windows system uses backslashes, running PHP scripts in Windows will recognise both back slashes and forward slashes as the same, so you can use the one without having to change it every time you run the script in a different OS.
TL;DR: Use / instead of \. It'll work on both Windows and Ubuntu.


Q: when i select radio button then all radio button is selected. i want only one radio button should be selected I am trying to do this.
I have three radio buttons, it is working fine when i use all radio button in a single div but it is not working when i divide all radio button in particular div. i click on it then it is selected but next time when i click on it then still radio button is selected.
It should be unselected when i click on it.
Please help. Your help will be appreciated. Thanks a lot.
Here's my code so far.

Delhi Airport

<input name="sample-radio" id="radio-01" value="1" type="radio" checked />

Delhi Airport

<input name="sample-radio" id="radio-02" value="1" type="radio" />

and

A: You have to have type="radio" buttons within the same container to make them behave like radio buttons, like as per w3schools example
<form>
<input type="radio" name="sex" value="male">Male

<input type="radio" name="sex" value="female">Female
</form>


Q: How can I fix an error with the seed file in Prisma and typescript? I'm building a backend using Prisma, Postgres 14.5, Node 18, and Typescript.
Every time try to seed the DB I get the following:
└ ➜ yarn prisma db seed
Environment variables loaded from .env
Running seed command `ts-node prisma/seed.ts` ...

An error occurred while running the seed command:
Error: Command failed with ENOENT: ts-node prisma/seed.ts
spawn ts-node ENOENT

ENOENT errors mean "No such file or directory"
I have this in my package.json:
  "prisma": {
    "seed": "ts-node prisma/seed.ts"
  },

My seed file is located at prisma/seed.ts and contains:
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  const person = await prisma.name.upsert({
    where: { id: 0 },
    update: {},
    create: {
      firstName: 'Sakiko',
    },
  });
}

main()
  .then(async () => {
    await prisma.$disconnect();
  })
  .catch(async (e) => {
    console.error(e);
    await prisma.$disconnect();
    process.exit(1);
  });

A: Turns out I was missing ts-node as we don't have our build fully set up yet. So I fixed it with yarn add ts-node.
Additionally, I had to simplify our tsconfig.json to remove the compilerOptions.rootDir as the prisma code is outside the src directory.


Q: Build One Project from GIT Repo (Jenkins/GIT) I am trying to check out just one maven project from  a GIT repo (Total of 49 modules) in Jenkins and do a build. The only reason is that they all need to be built a little bit differently in order to be deployed on to Tomcat. I probably might have been able to do it in SVN because I have dealt with it for a decade. But I am a spring chicken when it comes to GIT, I just don't have much idea how to get this to work. The current GIT folder structure is like:
    Maven Parent Project
        Child Project A
        Child Porject B
        Child Porject C
        Child Porject D
        .
        .
        .
        .
        .
        and so on...

Now lets say I want to create a job that just builds ChildProjectD, how do I go about it? Is it even possible? I did install the plugin GIT Parameter, thinking it would get me somewhere. But just don't know what to put in the fields.
Any help with this would be helpful. Thanks in advance.

A: These following guidelines may help you with initializing a Jenkins freestyle job for building a subproject rather than building all projects included in a git repo.

*

*Install git-plugin for Jenkins

*Create a freestyle job and add your git hub repository's link on SCM repository field

*

*New Item -->

*Name the item and OK -->

*Select Git in SCM -->

*Add repository URL -->

*Add invoke top-level maven targets as Build steps -->

*In Goals install -pl ChildProjectD

*(optional) Add post-build and other configurations

It will build the Child project as you want instead of full project.
You can refer Jenkins GitHub Java Application Project Build Configuration Maven to get more help. Check also mvn install -pl --help for more info.
Feel free to ask questions.


Q: Can't rename an ActiveRecord table a second time. "[table]_pkey" does not exist Some time ago, I ran the following rails migration to change the name of a table:
class RenameMaterialDonationsToMaterialDonationRequests < ActiveRecord::Migration
  def change
    rename_table :material_donations, :material_donation_requests
  end
end

Now I need to rename the table again. Here's my migration:
class RenameMaterialDonationRequestsToHelpRequests < ActiveRecord::Migration
  def change
    rename_table :material_donation_requests, :help_requests
  end
end

However, when I run the migration, I'm getting the following error:
PG::Error: ERROR:  relation "material_donation_requests_pkey" does not exist
: ALTER INDEX "material_donation_requests_pkey" RENAME TO "help_requests_pkey"/Users/[me]/.rvm/gems/ruby-2.1.4/gems/activerecord-4.2.4/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `exec'

I'm using Postgresql. In pgAdmin3, I can see that the pkey still retains the table name from before the first migration:
CONSTRAINT material_donations_pkey PRIMARY KEY (id)

How can I fix this to rename the table?

A: The answer below might work, but I decided to go with this:
execute "ALTER INDEX material_donations_pkey RENAME TO material_donation_requests_pkey;"

I chose this because it is the command that the migration was trying to run automatically as part of the original migration. That command wasn't automatically part of the pre-4.0 rails when I renamed this table the first time so I ran it now. I felt more comfortable doing exactly what rails is doing presently.

A: Here is a hacky solution, add another migration file and do this before change table name second time:
execute "ALTER TABLE material_donation_requests DROP CONSTRAINT material_donations_pkey;"
execute "ALTER TABLE material_donation_requests ADD PRIMARY KEY (id);"

And you probably need to do something similar after your next name changing.

A: Adding my solution for similar problem.
Below is the error while running migrations
01 PG::UndefinedTable: ERROR:  relation "fundraise_stories_pkey" does not exist
01 : ALTER INDEX "fundraise_stories_pkey" RENAME TO "fundraisers_pkey"

Connected to database via pgadmin and selected constraints for the table fundraise_stories. It was showing constraint name as "fundrise_stories_pkey".
So it was some old mistake because constraint name doesnt match with table name.
Solution:

*

*Find existing index name under constraints section for the table. In my case it was 'fundrise_stories_pkey'

*Rename the index before renaming table

*Finally, Rename the table.

Below is modified migration to rename index before renaming table.
def self.up
    execute "ALTER INDEX fundrise_stories_pkey RENAME TO fundraise_stories_pkey;"
    rename_table :fundraise_stories, :fundraisers
end

Log
D, [2020-02-02T17:16:27.428294 #7363] DEBUG -- :    (0.2ms)  BEGIN
== 20200127102616 RenameFundraiseStoryTableToFundraisers: migrating ===========
-- execute("ALTER INDEX fundrise_stories_pkey RENAME TO fundraise_stories_pkey;")
D, [2020-02-02T17:16:27.434366 #7363] DEBUG -- :    (5.5ms)  ALTER INDEX fundrise_stories_pkey RENAME TO fundraise_stories_pkey;
   -> 0.0061s
-- rename_table(:fundraise_stories, :fundraisers)
D, [2020-02-02T17:16:27.435722 #7363] DEBUG -- :    (0.7ms)  ALTER TABLE "fundraise_stories" RENAME TO "fundraisers"
D, [2020-02-02T17:16:27.438769 #7363] DEBUG -- :    (0.3ms)  ALTER TABLE "public"."fundraise_stories_id_seq" RENAME TO "fundraisers_id_seq"
D, [2020-02-02T17:16:27.439334 #7363] DEBUG -- :    (0.2ms)  ALTER INDEX "fundraise_stories_pkey" RENAME TO "fundraisers_pkey"
D, [2020-02-02T17:16:27.445452 #7363] DEBUG -- :    (0.8ms)  ALTER INDEX "index_fundraise_stories_on_bank_account_id" RENAME TO "index_fundraisers_on_bank_account_id"
D, [2020-02-02T17:16:27.446153 #7363] DEBUG -- :    (0.3ms)  ALTER INDEX "index_fundraise_stories_on_creator_id_and_creator_type" RENAME TO "index_fundraisers_on_creator_id_and_creator_type"
   -> 0.0131s
== 20200127102616 RenameFundraiseStoryTableToFundraisers: migrated (0.0193s) ==


Q: Redirect back to same page (with variables) on form submit in Laravel 5 On my page events.index, I first display a list of events for the logged on user.
On my index page I have a form with option/select to let the user select and display the events of another user. When he submits that form, I would like my index function (controller) to use the $user_id value (from the form) and display the events.index page again, but for events of that selected user.
I'm not sure what would be the best approach:

*

*Set a session variable to keep the user_id value? Not sure how to do that with a form.

*Submit the form with a get method (and get an ugly ?user_id=1 URL)

*Change my index route to accept the post method (although I already have that post/events route taken (by Route::post('events', 'EventsController@store'))

Not sure what would be a clean way to do this:
My route for events/index:
Route::get('events', [
'as' => 'event.index',
'uses' => 'EventsController@index'
]);

Events Controller
public function index()
{
    // How to get the $user_id value from form?

    if (empty($user_id))
    {
        $user_id = \Auth::user()->id;
    }

    $events = Event::where('events.user_id','=','$user_id');
    $users  = User::all();

    return view('events.index')->with(['events' => $events])->with(['users' => $users]);
}

View for index
{!! Form::open(['route' => 'events.index', 'method' => 'get']) !!}

    <select id="user_id" name="user_id">
    @foreach($users as $user)
        <option value="{{$user->id}}">{{$user->name}}</option>
    @endforeach
    </select>

{!! Form::submit('Show events for this user') !!}

{!! Form::close() !!}

@foreach($events as $event)
     ...
@endforeach

A: You can get the user_id from a Request object, you just need to inject it in the index method:
public function index(Request $request)
{
    $user_id = $request->get('user_id') ?: Auth::id();

    $events = Event::where('events.user_id','=','$user_id')->get();

    $users  = User::all();

    return view('events.index')->with(['events' => $events])->with(['users' => $users]);
}