text:
Q: Is it a good practice to return a PreparedStatement from a utility method? I am working on an inherited large Java code base where many disparate methods make queries to the database in maddeningly different ways; as I've been debugging and standardizing everything, most of the code I write ends up looking like this:
log.info("Audit-required logging for query: "+SOME_QUERY);
log.info("Ditto for each argument: "+parameter+" "+otherParameter+ ...);
ps = conn.prepareStatement(SOME_QUERY);
ps.setString(1, aString);
ps.setString(2, anotherString);
// ...
ps.setString(14, yetAnotherString);
rs = ps.executeQuery();
log.debug("Query executed: "+SOME_QUERY);

I hate that I have to write down the query thrice and the parameters twice (plus do a setString() for each one) — it's a recipe for future bugs when doing maintenance. I'd rather put all that inside a (static) general-purpose method that would allow me to just say everything once (plus future-proof the code base, in case some other action is needed... like, say, a different kind of logging is required by the legal department or a new kind of error handling is asked for). Something like this:
public static PreparedStatement fullyPrepare(final Connection conn, final String query, final String... arguments) { ... }

which I'd then call with a single sentence (instead of an entire code block every time):
ps = fullyPrepare(conn, CONSTANT_FOR_THIS_QUERY, parameter, otherParameter, ...);

I've, however, found resistance to this, based on the idea that "it would be bad practice". I've been trying to read up about this, but I can't find anything saying whether returning a PreparedStatement from a method that prepares it would be a good or a bad practice (as opposed to, say, the handling of ResultSet objects, like in the thread Is it Ok to Pass ResultSet?).
Why would my intended PreparedStatement preparator be a bad idea?

A: Doing so is a good an excellent idea.
Why is it good? Because you centralize your PrepareStatement creation in a single place. Your colleagues can read your code more cleanly. And if there's a bug, it's fixed in a single place and not everywhere.
It's so a good idea that several frameworks are even designed to do so in your place. I mentioned DbUtils, jdbc-helper and jDBI in my comment. Others are jcabi-jdbc, or the popular JOOQ. Okay, they're not all totally active (jdbc-helper may even be dead), but they're still used in production projects.
The case you mention specifically, can also be dependant on the database layer you use because some DB expect some different values for inputs like empty lists or simply null (Oracle, I'm looking at you!). So I'd strongly encourage using those libraries instead of writing my own utility methods, jDBI being my first choice as it's the one that's currently under active development.

A: Since PreparedStatement is bound to the Connection object it needs to be synchronized in order to be accessed across multiple methods which will limit your multi-user performance.
See here for more information: Reusing of a PreparedStatement between methods?


text:
Q: BlackBerry multithreading I want to know about the threading concept in BlackBerry.
In Android we have async task or handlers to communicate. Is there something similar available in BlackBerry? How do two threads communicate? How do you pass data from a background thread to the UI thread?

A: Concurrency is not a trivial thing. It's really difficult to craft a Thread-safe solution. In Blackberry Java the situation is even worse, as only JavaME Threading APIs are available, meaning you can't use all the Java SE high level classes (like executors, locks, collections, etc).
My advice would be not to try to port Android's AsyncTask or any other high level concurrency-related class on your own, since very likely you'll make mistakes (unless you are well versed in concurrent programming). I myself would avoid it as much as possible. Instead keep the concurrent code as simple and small as you can. Most of the times all you need is to refresh the GUI from a worker thread. This can be done easily with UiApplication.invokeLater and UiApplication.invokeAndWait, and you don't need to write concurrent code at all.
If you want to learn more about concurrency, I'd start with this tutorial by Oracle. It's aimed for JavaSE, but almost the first half is useful for JavaME as well. In case you want to learn more advanced concurrent programming, this book is a must read.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Split polygons programatically I have looked through several other questions and am still having trouble.  I have a set of 103 polygons that span my entire map.  Each of those polygons is divided into 36 equal sized polygons.  Now I need to iterate through each of those 36 squares, and split them into 100 equal squares.  I've tried getting in contact with the person that split the first 103, but all efforts have failed.  Can anyone point me in the right direction?
Fishnet seems to be out of the question as it spans the entire feature class, not the polygons.
I'm guessing I will be writing a python script.  Any pointers would be appreciated!

A: i think you can do it with some codes. check out here for splitting polygons with Split (Analysis):

Splitting the Input Features creates a subset of multiple output
  feature classes.

Syntax
Split_analysis (in_features, split_features, split_field, out_workspace, {cluster_tolerance})

Examples:
import arcpy
arcpy.env.workspace = "c:/data"
arcpy.Split_analysis("Habitat_Analysis.gdb/vegtype", "climate.shp", "Zone",
                     "C:/output/Output.gdb", "1 Meters")

i hope it helps you...

A: arcpy.CreateFishnet_management is the Python function
I'm going to assume, based on the picture, that there are small irregularities where the overall grid diverges from regular, and that you care about topology.
Would it be posssible to simply find the vertex coordinates of each of the 3708 small square polygons,  using a loop create a separate 10x10 fishnet at those coordinates, and then merge them together with a Python script?

A: Fishnet will only work if your plots are aligned.
Splitting will not be helpful considering that - if I understood correctly - the result you are looking for is precisely the "split feature".
You will have to write a script processing each polygon separately (to ensure ploygons id from 1 to 36 in each original plot).
Here are some steps:

*

*Set a loop for processing 1 polygon at a time (for example using Search Cursors + select be attribute)

*Read the coordinates of the polygon (4 corners) (for a script example see http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=Reading_geometries)

*Check the orientation of the polygon (oriented northward or rotated)

*Compute the fishNets, using LL and UL corners for non rotated polygons, Lower Y and Lower X coordinates for rotated ones.

*Merge the resulting Fishnets for making a unique file

Hope this help.


text:
Q: Travelling round a circle A and B start running from the same point to run in opposite directions round a circular race course 4324 meters in circumference, A not starting till B has run 716 meters. They pass each other when A has run 1927 meters. Who will come first to the starting point and what distance will they then be apart?

A: Let $t_{1}$ be the time $B$ needs to travel $716$ $\textrm{m }$ at the constant speed $v_{B}$. Then $716=v_{B}t_{1}$. If $t_{2}$ is the instant at which $A$ and $B$ pass
each other, then
\begin{cases}
4324-1927=v_{B}t_{2} \\
1927=v_{A}\left( t_{2}-\dfrac{716}{v_{B}}\right)  \\
716=v_{B}t_{1},
\end{cases}
where $v_{A}$ is the constant speed of $A$. Simplifying we get
\begin{cases}
t_{2}=\dfrac{2397}{v_{B}} \\
\dfrac{v_{A}}{v_{B}}=\dfrac{1927}{1681}=\dfrac{47}{41} \\
716=v_{B}t_{1}.
\end{cases}
If $t_{A},t_{B}$ is the additional time needed, respectively, by $A$ and $B$
to reach the starting point, then
\begin{cases}
1927=v_{B}t_{B} \\
2397=v_{A}t_{A}=\dfrac{47}{41}v_{B}t_{A},
\end{cases}
which implies that $\dfrac{t_{A}}{t_{B}}=\dfrac{51}{47}>1$. So $B$ comes first
to the starting point. When $B$ reaches this point, $A$ still needs to travel
\begin{align*}
2397-v_{A}t_{B} &=2397-v_{A}\frac{1927}{v_{B}}=2397-\frac{47}{41}1927 \\
&=2397-2209=188\text{ }\mathrm{m}.
\end{align*}

A: Hint:  how far has B run when they meet?  How far did B run while A was running?  What is the ratio of their speeds?  How far does B still have to run?  How far will A run in the time it takes B to run that far?


text:
Q: PHP - method for detect certains number I want to detect if a variable is 0,1,2,3 or 4. How to do this with preg_match()? What about performance between it and if($var==0||$var==1||$var==2||$var==3||$var==4)?

A: if (in_array($var, range(0,4), true)) {
 // good
}

The third parameter will do a strict comparison so $var must be an integer

A: this is how you will do it by preg_match.
 /^[0-4]$/

 if (preg_match('/^[0-4]$/', $var)) {
    echo $var . " is ok";
 } else {
    echo $var . " is NOT ok";
 }

Online demo

A: Direct comparison is absolutely much faster than using preg_match()
if (is_int($var) && $var<=4 && $var>=0){
 //Access granted
}

A: Doing a straight comparison is almost always always faster than regex. Even if it's not in this case (and any speed benefits would be negligible), I would still avoid it because regex tends to be less straightforward.


text:
Q: how to open the partial view as popup on jqgrid edit/add/delete option When i click the add/edit button it should show the partial view form as modal popup.
 $('#list').jqGrid({
       caption: "Employee Details",
       url: '/Employee/GetEmployee/',
       datatype: "json",
       contentType: "application/json; charset-utf-8",
       mtype: 'GET',
       colNames: ['Address', 'City', 'Id', 'Name'],
       colModel: [
             { name: 'Address', index: 'Address', width: 150 },
             { name: 'City', index: 'City', width: 150 },
             { name: 'Id', index: 'Id', width: 150 },
             { name: 'Name', index: 'Name', width: 150 }
       ],
       rowNum: 10,
       loadonce: true

   });

   jQuery("#list").jqGrid('#pager', { edit: false, add: false, del: false});

how can i achieve this..any help really appreciated!!!

A: jqGrid works as JavaScript library and it can't use any partial views. If you want to show edit/add/delete buttons then you should replace the line
jQuery("#list").jqGrid('#pager', { edit: false, add: false, del: false});

to
jQuery("#list").jqGrid('navGrid', '#pager');

and to add editable: true property in the columns of colModel, which you want allow the user to edit. You have to use pager: '#pager' option in jqGrid too. You have to include empty div

 in HTML markup of the page additionally. To be exactly the answer on your question depend on the version of jqGrid, which you use and the fork of jqGrid. Free jqGrid fork, which I develop, allows to use pager: true option of jqGrid and to skip '#pager' parameter of navGrid method. See the wiki article for more information.
Additionally you can remove unneeded index properties and to remove width: 150 property too, because 150 is the default value of width property. To be able to edit the data, you will have to add editurl parameter with the URL of MVC action, which should be called on editing.


text:
Q: Launch wizard from Active Help page in Eclipse I'm creating an RCP application and wanted to provide documentation using the Eclipse Help Contents (Help > Help Contents), I managed to add some pages to it by using the extension point org.eclipse.help.toc, this works fine, but I'm interested in providing a link in one of those pages to launch a wizard, I found that Eclipse provides support for this using a feature called Active Help.
First, in my html Help page I have imported the livehelp.js script:

    ...

Then in the  I added a link:
Execute action

And finally, this my TestAction class:
public class TestAction implements ILiveHelpAction {

    @Override
    public void run() {
        System.out.println("Action executed");
        // code to launch wizard is here
    }

    @Override
    public void setInitializationString(String str) {

    }
}

But when the link is clicked the action is not executed, I tried setting a breakpoint in the run() method but it is never called, any idea why this is happening?

A: I had exactly the same problem. But I think I was doing something wrong: I was copying my plugin manually into eclipse/plugins directory.
I tried with a "correct" plugin distribution mechanisms:

*

*a feature plugin

*an update site plugin

*a standard installation from within eclipse instance, menu help-> install new software

And now things are working... my action gets called normally..


text:
Q: Why one curl can do https and other can't I have run a curl query: curl https://login:password@mywebsite.com/script/
I have few curl executables, one installed with cygwin:
1:
curl 7.59.0 (x86_64-unknown-cygwin) libcurl/7.59.0 OpenSSL/1.0.2o zlib/1.2.11 libidn2/2.0.4 libpsl/0.18.0 (+libidn2/2.0.2) libssh2/1.7.0 nghttp2/1.31.0
Release-Date: 2018-03-14
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp scp sftp smb smbs smtp smtps telnet tftp
Features: AsynchDNS Debug IDN IPv6 Largefile GSS-API Kerberos SPNEGO NTLM NTLM_WB SSL libz TLS-SRP HTTP2 UnixSockets HTTPS-proxy PSL Metalink

other two that I compiled:
2 - libcurl-vc14-x86-release-static-ipv6-sspi-winssl :
curl 7.60.0 (i386-pc-win32) libcurl/7.60.0 OpenSSL/1.0.2k WinIDN
Release-Date: 2018-05-16
Protocols: dict file ftp ftps gopher http https imap imaps ldap pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: AsynchDNS IDN IPv6 Largefile SSPI Kerberos SPNEGO NTLM SSL HTTPS-proxy

3 - libcurl-vc14-x86-release-static-ssl-static-ipv6-sspi:
curl 7.60.0 (i386-pc-win32) libcurl/7.60.0 WinSSL WinIDN
Release-Date: 2018-05-16
Protocols: dict file ftp ftps gopher http https imap imaps ldap pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: AsynchDNS IDN IPv6 Largefile SSPI Kerberos SPNEGO NTLM SSL

1 + 3 can do this 'TSL request', 2 returns error message:
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: https://curl.haxx.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

All the advices I found on this problem is - you have to get the cert file from the server and store it into local store (or tell to curl to ignore the error).
My question is - why is that a proposed answer, when 1 + 3 can do it without that? What is the difference? And what do have 1 + 3 in common that they can do what 2 can't?

A: Because...
cygwin probably has a CA store locally already as part of its main install. It is used by more tools than just curl.
curl built with the "WinSSL" backend automatically uses the CA store that your windows installation has bundled with the operating system.
Your custom build using OpenSSL needs a CA store to verify the remote server's certificate against...


text:
Q: Parental Controls Always Allow does not work for Avid Media Composer I've enabled Parental Controls on a new Nov 2012 iMac being used in a school for public access (OS X 10.8.2 Mountain Lion) and have restricted the applications this account can use. Everything works fine with the exception of Avid Media Composer (the main reason we purchased the iMacs...). Avid Media Composer is marked as an application that the account is allowed to use in the parental control settings.
When I try to start Avid Media Composer under this account, a message pops up saying that this user doesn't have permission to use the application, giving the following three options:

*

*Always Allow...

*Allow Once...

*OK

When clicking Allow Once, I have to enter the admin account username and password and the app starts without problems. But when I click Always Allow, it asks for the admin account as well, but then pops up the same message again and again. I have verified that I'm using the right admin account username and password, but it's still refusing to run the application.
When I disable parental controls, everything works, but the moment I turn it on again, it fails, despite having Avid Media Composer in the list of allowed applications for this account.
In the Console application, I can see the following error message whenever this happens:

com.apple.launchd.peruser.504: ([0x0-0x1de1de].com.avid.mediacomposer[2033])
  Job failed to exec(3) for weird reason: 13

Has anybody else experienced this or knows how to fix this?

A: I found this problem too!
Turn off parental control and it works fine.
Interesting as I have two Mac Pros and one with PCs on does allow MC to work.
The other with the PCs on and it does not.
I suppose best answer is to turn off Parental Controls for an separate account just for users whom use AVID.


text:
Q: How to set Selected item value of Picker React native ** here is code first pushing value on picker dynamically *****
const refItem = [];
for (var i = 0; i < this.state.ref_val1.length, i < this.state.ref_val2.length; i++) {

  s = this.state.ref_val1[i];
  val = this.state.ref_val2[i];
  refItem.push(<Picker.Item key={i} value={val} label={s} />);
}

**** and then setting it to state... but its not working****
<Picker
      selectedValue={this.state.selectedVar}
      onValueChange={(itemValue) => (this.setState({ selectedVar: itemValue }))} >

      {refItem}

    </Picker>


text:
Q: Could not install spaCy language model behind proxy, got error SSL: Certificate_Verify_Failed I'm trying to install en_core_web_sm on my company computer (Windows 10) which has proxy firewall. I've tried downloading the package and install from local directory using conda terminal command:
python -m pip install ./en_core_web_sm-3.0.0.tar.gz
which is an answer from this post: SSL: CERTIFICATE_VERIFY_FAILED error while downloading python -m spacy download en
But I still get the same error on SSL: CERTIFICATE_VERIFY_FAILED. My question is why is SSL still being checked when installing from local folder.
In addition, is there a direct way to simply load the downloaded language model package? I've unzip the files and save in my working directory, and I wrote this in my python code:
nlp = spacy.load("/en_core_web_sm-3.0.0/")
This also didn't work. Got an error about Can't find the model 'en/core_web_sm-3.0.0'.
Thanks for your help.

A: Yes, you can download the .whl or .gz file directly and install from a local path. Note that since SpaCy models technically are python packages you need to install it with pip from the local file and afterwards load it normally in your python code.
For your model this file is the more current one which is probably better to use than version 3.0.0.


text:
Q: Changing  and  elements background color I'm currently uninstalling a page builder on my website, but I want to keep some of its styles.
I copied the html of an element, it used to have a red color on the stripes which are now black/grey, but I got problems changing the color of them.
Only color I can change is the background.

<svg xmlns="http://www.w3.org/2000/svg" style="max-height:100px;
        margin-bottom: 30px;" viewBox="0 0 1000 100" preserveAspectRatio="none">
    <path style="width: 2500px;" opacity="0.33" d="M473,67.3c-203.9,88.3-263.1-34-320.3,0C66,119.1,0,59.7,0,59.7V0h1000v59.7 c0,0-62.1,26.1-94.9,29.3c-32.8,3.3-62.8-12.3-75.8-22.1C806,49.6,745.3,8.7,694.9,4.7S492.4,59,473,67.3z"></path>
    <path style="width: 2500px;" opacity="0.66" d="M734,67.3c-45.5,0-77.2-23.2-129.1-39.1c-28.6-8.7-150.3-10.1-254,39.1 s-91.7-34.4-149.2,0C115.7,118.3,0,39.8,0,39.8V0h1000v36.5c0,0-28.2-18.5-92.1-18.5C810.2,18.1,775.7,67.3,734,67.3z"></path>
    <path style="width: 2500px;" d="M766.1,28.9c-200-57.5-266,65.5-395.1,19.5C242,1.8,242,5.4,184.8,20.6C128,35.8,132.3,44.9,89.9,52.5C28.6,63.7,0,0,0,0 h1000c0,0-9.9,40.9-83.6,48.1S829.6,47,766.1,28.9z"></path>
</svg>

Thanks for any help in advance!

A: You probabily want to include the css files from your page builder to add the style to your HTML page.
But for now, if you want your <svg> to be red use the property fill:

path {
  fill: red;
}
<svg xmlns="http://www.w3.org/2000/svg" style="max-height:100px;
        margin-bottom: 30px;" viewBox="0 0 1000 100" preserveAspectRatio="none">
    <path style="width: 2500px;" opacity="0.33" d="M473,67.3c-203.9,88.3-263.1-34-320.3,0C66,119.1,0,59.7,0,59.7V0h1000v59.7 c0,0-62.1,26.1-94.9,29.3c-32.8,3.3-62.8-12.3-75.8-22.1C806,49.6,745.3,8.7,694.9,4.7S492.4,59,473,67.3z"></path>
    <path style="width: 2500px;" opacity="0.66" d="M734,67.3c-45.5,0-77.2-23.2-129.1-39.1c-28.6-8.7-150.3-10.1-254,39.1 s-91.7-34.4-149.2,0C115.7,118.3,0,39.8,0,39.8V0h1000v36.5c0,0-28.2-18.5-92.1-18.5C810.2,18.1,775.7,67.3,734,67.3z"></path>
    <path style="width: 2500px;" d="M766.1,28.9c-200-57.5-266,65.5-395.1,19.5C242,1.8,242,5.4,184.8,20.6C128,35.8,132.3,44.9,89.9,52.5C28.6,63.7,0,0,0,0 h1000c0,0-9.9,40.9-83.6,48.1S829.6,47,766.1,28.9z"></path>
</svg>


text:
Q: Format if table value does not match first row I have test results data in Excel like this:
Correct  d  b   c   a   b   c   d
Student1 d  b   c   a   b   c   d
Student2 d  b   c   a   b   c   a
Student3 d  b   c   a   b   d   d
Student4 d  d   c   a   b   c   a
Student5 d  d   c   a   b   c   d
Student6 d  b   c   a   b   b   d

I want to highlight the cells that contain incorrect answers.
How do I go about it?

A: Step 1:
Shortcut Key for New Conditional Formatting Rule: Alt-H-L-N
OR
Windows Ribbon Path: Home, Conditional Formatting, New Rule.
Step 2:
Got the last selection: Use a formula to choose which cells to format
Use the following Formula:
Conditional Formatting Rule:
=AND(B2<>"",B2<>B$1).
Step 3:
Copy the formatting in Cell B2 to all of the other students answers
To copy only the formatting, copy cell B2
Then select all the cells that you want to have this formatting
Then hit Alt-E-S-T (Keys are hit one after the other) for Special Paste
Then hit OK.

A: The existing answer makes little sense to me hence an alternative:


text:
Q: How to sort a List based on the string after last index of the string c# I'm wanting to be able to re-order a list based on the lastindexof a character in this case "/".
var ListToSort = new List<string> { "Hjgs/dasdf/ada/2toe0685tcr1/Hello_1",
            "Hjgs/dasdf/ada/xdt42pj616ao/Yes_1",
            "Hjgs/dasdf/ada/7yhzozo2rgu5/Hello_2",
            "Hjgs/dasdf/ada/atrejl1rzliq/Yes_2",
            "Hjgs/dasdf/ada/bgwq9i8fbsj4/Hello_3",
            "Hjgs/dasdf/ada/4rrx4pldbiq1/Zues_1"};

im wanting to sort the list based on the last index of "/" eg it would compare Yes_1,Hello_2 and so on , the expected output would be:

            Hjgs/dasdf/ada/2toe0685tcr1/Hello_1
            Hjgs/dasdf/ada/7yhzozo2rgu5/Hello_2
            Hjgs/dasdf/ada/bgwq9i8fbsj4/Hello_3
            Hjgs/dasdf/ada/xdt42pj616ao/Yes_1
            Hjgs/dasdf/ada/atrejl1rzliq/Yes_2
            Hjgs/dasdf/ada/4rrx4pldbiq1/Zues_1

edit : working solution from comments
ListToSort = ListToSort.OrderBy(x => x.Substring(x.LastIndexOf("/"))).ToList();

A: using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var ListToSort = new List<string> { "Hjgs/dasdf/ada/2toe0685tcr1/Hello_1",
            "Hjgs/dasdf/ada/xdt42pj616ao/Yes_1",
            "Hjgs/dasdf/ada/7yhzozo2rgu5/Hello_2",
            "Hjgs/dasdf/ada/atrejl1rzliq/Yes_2",
            "Hjgs/dasdf/ada/bgwq9i8fbsj4/Hello_3",
            "Hjgs/dasdf/ada/4rrx4pldbiq1/Zues_1"};

        foreach(var item in ListToSort.OrderBy(x => x.Substring(x.LastIndexOf("/"))))
            Console.WriteLine(item);
    }
}


text:
Q: remove duplicated lines in ArrayList> public void removeDuplicates (ArrayList<ArrayList<String>> strings) {

    Set<ArrayList<String>> s = new LinkedHashSet<ArrayList<String>>(strings);
    strings =  new ArrayList<ArrayList<String>>(s);
}

i want to remove duplicated lines in ArrayList<ArrayList<String>>, I want to use LinkedHashSet and compare ArrayList between themselves and if is the same not insert it. i know i need Comparator but i do not know how to implement it for comparing ArrayList inside ArrayList.
Thx

A: You could try using a Set< List > - and if you implement your own List or extend ArrayList os that the "equals()" acts the way you expect.
So when you add an arrayList it will automatically be compared with the rest.
Not sure what will happen when you add the arrayLists first and then populate them with elements.
What is your case?

You said you want to use LinkedHashSet - ok, that is the same as my initial suggestion.
(you don't need comparator)
You can extend ArrayList and make its "equals()" method conform your wish:

*

*same number of elements

*same elements

*etc...

A: You didn't mention if the order is important.
If the item order in the inner list is not important, this should work:-
List<List<String>> list = new ArrayList<List<String>>();
list.add(Arrays.asList(new String[] {
        "a",
        "b",
        "c"
}));
list.add(Arrays.asList(new String[] {
        "b",
        "a",
        "c"
}));
list.add(Arrays.asList(new String[] {
        "a",
        "b",
        "c",
        "d"
}));

// use set to remove duplicates
Set<Set<String>> set = new HashSet<Set<String>>();
for (List<String> innerList : list) {
    set.add(new HashSet<String>(innerList));
}

// convert back to list
List<List<String>> noDupList = new ArrayList<List<String>>();
for (Set<String> innerSet : set) {
    noDupList.add(new ArrayList<String>(innerSet));
}

// print out for debugging
for (List<String> l : noDupList) {
    System.out.println(l);
}

A: You are going to have to do a brute force compare and compare each and every arraylist against every other array list.
start with index 0 and compare it's elements against index 1-n once you find an
Assumeing ArrayList myDatastructure following psuedo code:
for (int i =0; i < myDatastructure.count() ; i++){

    for (int j = i+1 ; i< mydatastructure.count() ; j++){
      compare(myDatastructure.get(i),myDataStructure.get(j));

    }
}

for the compare method you will want to write a for loop that iterates through the elements one by one comparing the item at each index in both arrayLists, you will want to short circuit this by not bothering to compare them if they are not the same length.
You will probably want to mark the indexes that you want to remove in an Separate arraylist and remove them in a separate loop otherwise you will screw up your indices.
Implementation should be fairly simple, so that's left as an exercise.

A: Say the list contains
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

What do you expect the set to contain? Two elements? One element?
Can you tell how you want to compare the ArrayLists?
If that is the one-to-one compare - "they are equal if they contain the same elements in the same order" then
sets = new HashSet<ArrayList<String>>(lists);

Should be sufficient.
If you want to have more complex comparison rules then you need to override the equals method as Leni Kirilov said above. But the larger the list is, you will have a high performance overhead.

A: Agree with @Leni above, just override ArrayLists's equals method and the LinkedHashSet implementation should automatically filter duplicates.
From Java doc: A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction


text:
Q: Uploading an Converting Files In one script I've written a process for my company which pulls audio files (wav) from a server to their permanent location.  Pretty straight forward using ftp.
The issue now is that we wish to convert these wav files into mp3s.  I was hoping to combine the transfer/upload process and the converting process into one script. So as we move them over, I could process them (while not slowing the transfer rate overall).  Obviously there are technical issues involved as the conversion process is process intensive and we may require a third server that does the actual conversion. Our conversion program that we'll use is LAME.
I'm envisioning something like a multi-threaded application that would use a queue where each thread would handle a portion of that queue of transferring and converting the files.  So thread-A moves 10-30 files, thread-B moves another 10-30 files.  Both A and B move the files to this "conversion box or boxes" and once they've been converted, are than moved to their permanent location.
Would this work out or is there a simpler method?

A: I think Jeremy's pointed you in the right direction here.  I'd do this:

*

*FTP the files to a staging directory

*Have a Directory Watcher gateway configured to watch that directory,
and process incoming files (a good article on directory
watchers)

*You might want to have some sort of respooling process, or park
files that failed to convert in another directory (much like the
undelivr directory in ColdFusion's mail subsystem), and log the
failure so separate action can be taken

*Stick the converted files in a different directory, and perhaps have
another directory watcher keep an eye on that to deploy the file, or
create a record in a DB to reference it, or whatever the next
workflow step is.


text:
Q: Why is $\frac{1}{m+1} = \sum_{n=0}^\infty \frac{2^{-2n-m-1} (2n+m)!}{(n+m+1)!n!}$? I have the strong assumption that for $m \in \mathbb N_0$ we have
$$\frac{1}{m+1} = \sum_{n=0}^\infty \frac{2^{-2n-m-1} (2n+m)!}{(n+m+1)!n!}=\sum_{n=0}^\infty \frac{2^{-2n-m-1}}{2n+m+1}\binom{2n+m+1}{n}.$$
But I didn't find an explicit way to show it.
In case you wanna know where this series is from: I'm still trying to solve How to prove an equality involving an infinity series and the modified Bessel functions?. If you plug in $s=\alpha=\beta=1$ you eventually come up with the series equation from above. At least the series equation would show the special case (in fact the other direction is not true).

A: A pssible idea could be to use
$$f(x)=\sum_{n=0}^\infty \frac{2^{-(2n+m+1)}\, (2n+m)!}{(n+m+1)!\,\,n!}x^{-n}=\frac{ \, _2F_1\left(\frac{m+1}{2},\frac{m+2}{2};m+2;\frac 1x\right)}{(m+1)\,\,2^{(m+1)}}$$ which is true even if $m$ is not an integer.
Now, working a little the expression
$$f(x)=\frac x {m+1} \left(1+\sqrt{\frac{x-1}{x}}\right)^{-m}\left(1-\sqrt{\frac{x-1}{x}}\right)$$

A: I guess I post my approch which is based on the idea of Claude Leibovici for clarity.
Using Legendre duplication we have
$$(2n+m)!=\Gamma(2n+m+1) = \Gamma(n+ \tfrac{m+1}{2})\Gamma(n+ \tfrac{m+2}{2})2^{2n+m}/\sqrt{\pi}.$$
So we have
$$\sum_{n=0}^\infty \frac{2^{-2n-m-1} (2n+m)!}{(n+m+1)!n!}=\frac{1}{2\sqrt{\pi}} \sum_{n=0}^\infty \frac{ \Gamma(n+ \tfrac{m+1}{2})\Gamma(n+ \tfrac{m+2}{2})}{\Gamma(n+m+2)n!}\\
= \frac{1}{2\sqrt{\pi}} \frac{ \Gamma(\tfrac{m+1}{2})\Gamma(\tfrac{m+2}{2})}{\Gamma(m+2)} F(\tfrac{m+1}{2},\tfrac{m+2}{2},m+2,1)\\
\frac{1}{2\sqrt{\pi}} \frac{ \Gamma(\tfrac{m+1}{2})\Gamma(\tfrac{m+2}{2})}{\Gamma(m+2)} \frac{\Gamma(m+2)\Gamma(m+2-\tfrac{m+1}{2}-\tfrac{m+2}{2})}{\Gamma(m+2-\tfrac{m+1}{2})\Gamma(m+2-\tfrac{m+2}{2})}\\
= \frac{1}{2\sqrt{\pi}} \frac{ \Gamma(\tfrac{m+1}{2})\Gamma(\tfrac{m+2}{2})}{\Gamma(m+2)} F(\tfrac{m+1}{2},\tfrac{m+2}{2},m+2,1)\\
\frac{1}{2\sqrt{\pi}} \frac{ \Gamma(\tfrac{m+1}{2})\Gamma(\tfrac{m+2}{2})}{\Gamma(m+2)} \frac{\Gamma(m+2)\Gamma(\tfrac{1}{2})}{\Gamma(\tfrac{m}{2}+\tfrac{3}{2})\Gamma(\tfrac{m}{2}+\tfrac{2}{2})}
=\frac{1}{m-1}.
$$


text:
Q: How to get data from XML parser in nodeJS I try to use nodeJS to get access to all data from an XML stored as a string in my code for now. Actually, I succeeded only getting access to the main node but not all children when i wanted to get deeper.
Here is my code, and I try to get all data in ms:IDENT node.
var http = require('http');
var xml2js = require('xml2js');

var extractedData = "";
var parser = new xml2js.Parser();

var xml = "<wfs:FeatureCollection><gml:boundedBy><gml:Box srsName='EPSG:3945'><gml:coordinates>1399644.376399,4179041.966594 1426575.406024,4209057.424111</gml:coordinates></gml:Box></gml:boundedBy><gml:featureMember><ms:SV_ARRET_P fid='SV_ARRET_P.1484'><gml:boundedBy><gml:Box srsName='EPSG:3945'><gml:coordinates>1418152.331881,4208150.797551 1418152.331881,4208150.797551</gml:coordinates></gml:Box></gml:boundedBy><ms:msGeometry><gml:Point srsName='EPSG:3945'><gml:coordinates>1418152.331881,4208150.797551</gml:coordinates></gml:Point></ms:msGeometry><ms:GID>1484</ms:GID><ms:GEOM_O>196</ms:GEOM_O><ms:IDENT>FLA92A</ms:IDENT><ms:GROUPE>FLA92</ms:GROUPE><ms:LIBELLE>Fort Lajard</ms:LIBELLE><ms:TYPE>BUS</ms:TYPE><ms:CDATE>2017-01-06T14:15:10</ms:CDATE><ms:MDATE>2017-01-06T14:15:10</ms:MDATE></ms:SV_ARRET_P></gml:featureMember></wfs:FeatureCollection>"

parser.parseString(xml, function(err,result){
  //Extract the value from the data element
  xml = result['wfs:FeatureCollection'];
  parser.parseString(xml, function(err,result){
    extractedData = result['wfs:FeatureCollection']['gml:featureMember']['ms:SV_ARRET_P']['ms:IDENT'];
    console.log(extractedData);
  });
});

Thank you for any help in advance

A: With xml2js, the explicitArray option defaults to true, so all child nodes will be in an array.
You can access the value you are interested in like this (note that the second call to parseString is not required):
var parser = new xml2js.Parser();
parser.parseString(xml, function (error, result) {

    var value = result['wfs:FeatureCollection']['gml:featureMember'][0]['ms:SV_ARRET_P'][0]['ms:IDENT'][0];
    console.log(value);
});

If you specify explicitArray as false, arrays will be used only if there are multiple child nodes:
var parser = new xml2js.Parser({ explicitArray: false });
parser.parseString(xml, function (error, result) {

    var value = result['wfs:FeatureCollection']['gml:featureMember']['ms:SV_ARRET_P']['ms:IDENT'];
    console.log(value);
});


text:
Q: Can't install Linux Mint after Windows 11 After performing a clean install of Windows 11 on my PC, I have tried to install Linux Mint (Cinnamon 20.3) in order to have dual boot Windows/Linux. I burned the Linux iso image onto a USB and tried to boot from it. However, after selecting the option to install Linux Mint, I get the error "Firmware error: ACPI region does not cover the entire command/response buffer" and the screen glitches (overlapped text appears and lines of different colors).
Before installing Windows 11, I changed my BIOS options in order to allow the installation: I enabled TPM 2.0, disabled CSM and enabled secure boot (Windows UEFI Mode). However, I think that those options are interfering with the Linux Mint installer. From what I've read, I believe the secure boot option does not allow the execution of the Linux Mint installer.
So the question is: is Linux Mint compatible with all the new security options introduced by Windows 11 (TPM 2.0 and secure boot)? If so, what do I need to do in order to install Linux Mint alongside Windows 11? If not, is it okay to disable the secure boot and/or tpm options? Will it harm my experience (i.e., security, updates, etc.) with Windows 11?
Below some additional data:
Motherboard: ASUS TUF Gaming B450-PLUS
CPU: AMD Ryzen 5 3600X
How I burned the ISO onto the USB

A: I have managed to solve the problem.
It seems the issue was not with dual boot+TPM. When I burned the Linux ISO image onto the USB, I changed from MBR to GPT (I don't know if this is important for my issue or not), and was able to install Linux Mint in compatibility mode.
After installing it, the necessary keys were added to the UEFI (to allow secure boot) via the MOK tool (I think this is what this tool is for) and, from that moment, I have been able to boot both Windows and Linux Mint (in normal mode) using grub. Whenever I boot Linux, the firmware error still appears but the system is able to boot nonetheless (instead of freezing).
In conclusion, as pointed out by @Ramhound, it is possible to boot Linux Mint with secure boot + TPM 2.0 enabled.


text:
Q: XPath - Locate node using its flattened descendant text I got this html :

       Some

           text

           and more

   ...

I need to locate my td element with this text Some text and more. I know that I can get this text with this XPath expression :
//td//text()

But I can not find a solution to locate td element. I try this :
//td[//text()='Some text and more']

but I get errors. Do you know a working XPath expression for that ?

A: Firstly, XPath uses forward slashes, never backslashes.
Secondly, I believe this may be the XPath you need:
//td[normalize-space(.) = 'Some text and more']

Could you give that a try?


text:
Q: Formal structure of a proof with the goal $\exists x P(x)$ In How To Prove It?, Velleman explains that, in order to prove a statement with a goal of the form $\exists x P(x)$, we must declare an arbitrary variable $y$ and assign a value $a$ to it and use the assignment to prove the substitution instance $P(y/x)$ of the goal. Hence, assuming $\Gamma$ is a well-founded formula, we have:

*

*$\Gamma \rightarrow \exists x P(x)$

*$(\Gamma \land (y=a)) \rightarrow P(y/x)$
My question concerns the formal structure of such proof technique and the relation between statements 1 and 2.
My first attempt was this one: since $P(a)$ is logically equivalent to $\forall y[(y=a) \rightarrow P(y)]$, then $\Gamma \rightarrow P(a)$ is equivalent to $\Gamma \rightarrow \forall y[(y=a) \rightarrow P(y)]$. If $y$ does not occur in $\Gamma$, then the last statement is equivalent to $\forall y[\Gamma \rightarrow ((y=a) \rightarrow P(y))]$, which means $\forall y[(\Gamma \land (y=a)) \rightarrow P(y)]$.
Now, since $\Gamma \rightarrow P(a)$ implies $\Gamma \rightarrow \exists x P(x)$, it is fair to believe that the relation between statements 1 and 2 is $\forall y[(\Gamma \land (y=a)) \rightarrow P(y)] \rightarrow [\Gamma \rightarrow \exists x P(x)]$.
However, some members on this site informed me that this implication is a weaker version of the more general assertion $\forall y[[(\Gamma \land (y=a)) \rightarrow P(y)] \rightarrow [\Gamma \rightarrow \exists x P(x)]]$. In this case, $y$ appears as a free variable, whose quantification ranges upon the entire proof. However, I can't tell how it is possible to derive such stronger implication, especially because the formula $(\Gamma \land (y=a)) \rightarrow P(y)$ seems meaningless to me.

A: IMO, your analysis of Existential Introduction is unnecessarily complicated...
The intuitive reasoning is the following:

if we know that Socrates is a Philosopher, then we are licensed to assert that a Philosopher exists.

In symbols:

$\dfrac { P(s) } { \exists x P(x)}$.

Thus, there is no need to add a "declaration" about the term (i.e. a "name") $s$.

Things are different with Existential Elimination, where we have $\exists x P(x)$ as premise.
In this case, we introduce a new term $a$ to "temporary" refer to the unknown individual that we know to exists.
The "new" condition is formalized through the proviso that $a$ must not be used in the "context" $\Gamma$, nor in the conclusion of the proof.

With ref to Velleman's book, page 112, I do not see big differences...
The author says:

"Try to find a value of $x$ for which you think $P(x)$ will be true."

This amounts to saying: "let $x= \text {Socrates}$".

"... and proceed to prove $P(x)$ for this value of $x$."

This amounts to saying: "prove $\text {Philosopher}(\text {Socrates})$".
Then apply EI to conclude that $\exists x (\text {Philosopher}(x))$.

A: Suppose you are trying to prove $\exists y(y+2x = 0)$.  Here are two ways you might write the proof:

*

*Prove $(-2x)+2x=0$.

*Start with the sentence "Let $y = -2x$" and then prove $y+2x=0$.

The logic of these two approaches is exactly the same; the difference is merely stylistic.  In the second approach, the letter $y$ is just being introduced as a notational shorthand for $-2x$.
Which style is better?  It may depend on the example, and it may be a matter of taste.  But if the conclusion of the theorem being proven has been stated with an explicit existential quantifier, then I think many mathematicians would prefer the second style.
For example, suppose you are giving an $\epsilon$-$\delta$ proof of a limit statement--say, $\lim_{x \to 2} 3x = 6$.  The statement to be proven is $\forall \epsilon>0 \exists \delta>0 \forall x(0 < |x-2| < \delta \to |3x-6|<\epsilon)$.  I think most mathematicians would start the proof like this:  "Let $\epsilon$ be an arbitrary positive number.  Let $\delta = \epsilon/3$.  Then $\ldots$."  There is really no need for the sentence "Let $\delta = \epsilon/3$."  One could simply prove that $\epsilon/3$ has the property required for $\delta$, and then conclude that the limit statement is true.  But most readers would find the sentence "Let $\delta = \epsilon/3$" helpful, because it tells the reader that $\epsilon/3$ is the number that is being proposed as the value of $\delta$ in the $\epsilon$-$\delta$ definition.
Note that How To Prove It is not a book on formal logic, although there is some logic in the book.  It is a book about how to write proofs in English.  So although the proof techniques that are discussed often correspond to rules of formal logic, the explanations focus on how to use those techniques to write proofs in English, not how to write proofs in formal logic.


text:
Q: setStatusBarHidden and then how can I resize the application frame size? If I use this method, isn't there someway to set the screen to the be the full 320x480 rather than the 320x460 it was before I hide the status bar?
Many Thanks,
-Code

A: Write this code in AppDelegate.m file
[[UIApplication sharedApplication] setStatusBarHidden:YES];

This code used for hide StatusBar. so u can get view size is 320 X 480 instead of 320 X 460.

A: Make sure that your window is set to use [UIScreen mainScreen] bounds] as it's frame, and setWantsFullScreenLayout on your very first view controller.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UIViewController *viewController = [[UIViewController alloc] init];
[viewController setWantsFullScreenLayout:YES];
[self.window setRootViewController:viewController];

A: If you're using IB for storyboards or the more traditional way, make sure that the UIViewController settings for Status Bar is set to "None".  This will make sure that views you create and add to it will be the full size and not set to something smaller.
Also you will need to add an entry to the plist, called "Status bar is initially hidden" or UIStatusBarHidden and set that to YES.  This will stop the OS from showing the status bar for the application.
By doing these two things you can make sure you have the full screen.

A: I usually hide the status bar in the app delegate. Then whenever I need to create a new view controller I delete the UIView which comes with it. I add a new UIView onto the screen and set its size to 320 x 480 and connect it to the "view" outlet of the File's Owner. From my experience if the UIView is set to 320 x 460 and the status bar is hidden, then during run time the view gets stretched by 20 pixels. This causes a blurry effect on some of the subviews.


text:
Q: how do I fix Segmentation fault error in assembly? I'm creating a 64-bit Linux program. This is my code to form a triangle. There are 3 conditions. a + b > c, b + c > a, c + a > b. I got an error 'Segmentation fault (core dumped)'. Can you explain what I miss and how to fix it?
.data
.res: .string "%d \n"
.global main

triangle:
    movq %rsi, %rax # a
    addq %rdi, %rax # a + b
    movq %r8, %rdx # c
    cmpq %rdx, %rax # a + b : c
    jle false

    movq %rdi, %rax # b
    addq %r8, %rax # b + c
    cmpq %rsi, %rax # b + c : a
    jle false # b+ c <= a

    movq %r8, %rax # c
    addq %rsi, %rax # c + a
    cmpq %rdi, %rax # c + a : b
    jle false # c + a <= b

    movq $1, %rax
    retq

false:
    movq $0, %rax
    retq

main:
    movq $3, %rsi
    movq $3, %rdi
    movq $6, %r8
    call triangle

    movq %rax, %rsi
    movq $.res, %rdi
    xorq %rax, %rax
    call printf


text:
Q: Parse XML subtags with same name in swift i am new to swift. I have created an XML parser that reads each tag (tag and subtag) one by one. The problem that I found is that there are some subtags with the same name, so my code can't differentiate. I need to know how to read a concrete subtag to differentiate and store it in different variables.
This is the XML (reduced) that I am parsing:
<_0:situationRecord id="GUID_Suc_3971318_3971318" xsi:type="_0:NetworkManagement">
    <_0:identifier>171826</_0:identifier>
    <_0:to xsi:type="_0:TPEGNonJunctionPoint">
        <_0:name>
            <_0:descriptor>
                <_0:value>MADRID</_0:value>
            </_0:descriptor>
            <_0:tpegDescriptorType>other</_0:tpegDescriptorType>
        </_0:name>
    </_0:to>
    <_0:from xsi:type="_0:TPEGNonJunctionPoint">
        <_0:name>
            <_0:descriptor>
                <_0:value>SANTIAGO DE COMPOSTELA</_0:value>
            </_0:descriptor>
            <_0:tpegDescriptorType>other</_0:tpegDescriptorType>
        </_0:name>
    </_0:from>
</_0:situationRecord>

This is my ParseINCDGT.swift class:
import Foundation

struct INCIDENCIADGT {
    var identifier: String
    var valueFrom: String
    var valueTo: String
}

class ParseINCDGT: NSObject, XMLParserDelegate {
    private var myData: Data
    private var currentElementName = ""
    private var inItem = false
    private var item: INCIDENCIADGT
    var ready = false

    var auxLat = 1
    var auxLong = 1
    var aux = 1

    var items: [INCIDENCIADGT]

    override init() {
        //Default values
        myData = "".data(using: .ascii)!
        items = []
        item = INCIDENCIADGT(identifier: "", valueFrom: "", valueTo: "")
    }

    // Set the local data set for parsing
    func setData(data: Data) -> Void {
        if data == nil {
            return
        }
        myData = data
    }

    // Runs the parsing process, returns at the end. Please note that this function is synchronous, while internally asynchronous
    func parse() -> Void {
        let parser = XMLParser(data: myData)
        parser.delegate = self
        parser.parse()
    }

    // Terminate session
    func parserDidEndDocument(_ parser: XMLParser) {
        ready = true
    }

    // Start session
    func parserDidStartDocument(_ parser: XMLParser) {
        ready = false
    }

    // Terminate an element
    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        currentElementName = elementName
        if elementName == "_0:situationRecord" {
            inItem = false
            items.append(item)
        }
    }

    // Starts an element
    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
        currentElementName = elementName
        if elementName == "_0:situationRecord" {
            inItem = true
            item = INCIDENCIADGT(identifier: "", valueFrom: "", valueTo: "")
        }
    }

    // Collects other data
    func parser(_ parser: XMLParser, foundCharacters string: String) {

        switch currentElementName{
        case "_0:identifier":
            item.identifier += string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        case "_0:value":
            item.valueFrom += string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        default:
            break
        }
    }
}

And this is my method that calls the ParserINCDGT.swift:
func loadData() -> Void {
    let url = "http://infocar.dgt.es/datex2/dgt/SituationPublication/all/content.xml"
    let request = URLRequest(url: URL(string: url)!)

    let session3 = URLSession.shared.dataTask(with: request3) {
        (data, _, error) in

        //Handle errors
        if error != nil {
            //Show error message
            return
        }

        guard let data = data else{
            //Data error, show message
            return
        }

        //Convert data to string
        var s: String = String(data: data, encoding: .ascii)!

        //Make XML conforming to all standards: Convert LF to CR
        s = s.replacingOccurrences(of: "\r", with: "\n")

        //Parse XML
        let p = ParseINCDGT()
        p.setData(data: data)
        p.parse()

        //Elaborate data
        print(p.items)

        if (p.items.count != 0) {
            for item in p.items {
                print(item.identifier)
                print(item.valueFrom)
            }
        }
    }
    //Run!
    session.resume()
}

Finally the output for the variable "valueForm" is "MADRIDSANTIAGO DE COMPOSTELA"
Can anyone help me explaining what should I include to parse and differentiate the subtags "_0:value"?
Thank you so much. Any help is appreciated.

A: You only need to add some few changes:
Check if a tag _0:from or _0:to is started and have it saved in a variable, I called it isFrom here, you need to add it to your class (private would be better). And when you look for the text in _0:value you add it to the right element of your INCIDENCIADGT struct.
Herer you see the two functions that need change with what needs to be added:
// Starts an element
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
    currentElementName = elementName
    if elementName == "_0:situationRecord" {
        inItem = true
        item = INCIDENCIADGT(identifier: "", valueFrom: "", valueTo: "")
    } else if elementName == "_0:from" { // check if we will be looking at from information when getting the next _0:value
        isFrom = true // could use an enum if more posibilities exist than from and to.
    } else if elementName == "_0:to" { // check if getting to information like above
        isFrom = false // could use an enum if more posibilities exist than from and to.
    }
}

// Collects other data
func parser(_ parser: XMLParser, foundCharacters string: String) {

    switch currentElementName{
    case "_0:identifier":
        item.identifier += string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
    case "_0:value":
        if isFrom { // write the information in the right field of the struct
            item.valueFrom += string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        } else {
            item.valueTo += string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        }
    default:
        break
    }
}

There might still be some errors and warning in what I wrote, since I only made it here inside the editor and did not test it in xcode, but if it does not work, it at least gives you an idea of how to start to solve your specific problem.


text:
Q: How to access the raw unaltered http POST data in Rails? How can I access the original POST message in a controller and send it back unaltered to its original sender?

A: You can use ActionDispatch::Request#raw_post to get the unaltered POST data:
request.raw_post


text:
Q: Accessing a child within a child firebase This is not a duplicate.
I am trying to access a child within a child in firebase and then putting that child into a recycler adapter. It won't show in the recycler adapter. There is a similar question on here to this but when implementing it, it still doesn't work.
Currently using an adapter, a messages object and a fragment.
Fragment Activity

    private ArrayList<Messages> results = new ArrayList<>();
    private void listenForChat() {
        final DatabaseReference userDb = FirebaseDatabase.getInstance().getReference().child("users").child(currentUid)
                .child("receivedMessages");
        messageUrlDb = userDb.child("messageUrl");

        messageUrlDb.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                String message = "";
                if (dataSnapshot.child("messageUrl").getValue() != null)
                    message = dataSnapshot.child("messageUrl").getValue().toString();
                Messages obj = new Messages(message, name, image);
                if (!results.contains(obj)) {
                    results.add(obj);
                    messagesList.setAdapter(mAdapter);
                    mAdapter.notifyDataSetChanged();
                    initializeDisplay();
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) { }
        });
    }

public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatViewHolders> {

    private List<Messages> mMessageList;
    private List<UserObject> usersList;
    private Context context;
    private DisplayTextFragment displayTextFragment;
    private String message;

    public ChatAdapter(List<Messages> mMessageList, Context context) {

        this.mMessageList = mMessageList;
        this.context = context;

    }

    @Override
    public ChatViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_layout, null);
        ChatViewHolders rcv = new ChatViewHolders(v);
        return rcv;

    }

    @Override
    public void onBindViewHolder(final ChatViewHolders holder, int position) {

        holder.messageText.setText(mMessageList.get(position).getMessage());

    }

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

    public class ChatViewHolders extends RecyclerView.ViewHolder {

        public TextView messageText, timeSent, mName;
        ImageView mProfile;
        LinearLayout mLayout;

        public ChatViewHolders(View view) {
            super(view);
            messageText = (TextView) view.findViewById(R.id.message_text);
            mLayout = itemView.findViewById(R.id.layout);
        }
    }
}

I am trying access (messageUrl) users -> receivedMessages -> messageUrl. However as there is a key they I assume it doesn't as far as messagesUrl. For the recycler adapter it needs take in messagesUrl as a string and update accordingly but I just can't do it.
If any more code is needed I can post. Thank you.

A: This is how you're attaching your ValueEventListener:
final DatabaseReference userDb = FirebaseDatabase.getInstance().getReference().child("users").child(currentUid)
        .child("receivedMessages");
messageUrlDb = userDb.child("messageUrl");

messageUrlDb.addValueEventListener(new ValueEventListener() {

If we take the path from this code, you're attaching the listener to /users/$uid/receivedMessages/messageUrl. This path doesn't exist in the data you showed, so your onDataChanged will get called with an empty snapshot.
If you want to read all messages for the user, you should attach your listener to /users/$uid/receivedMessages and parse the snapshot inside onDataChanged:
final DatabaseReference userDb = FirebaseDatabase.getInstance().getReference().child("users").child(currentUid)
        .child("receivedMessages");
userDb.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot userMessages: dataSnapshot.getChildren()) {
            for (DataSnapshot messageSnapshot: userMessages.getChildren()) {
                System.out.println(messageSnapshot.getKey()+": "+messageSnapshot.getChild("messageUrl").getValue(String.class));
            }
        }
    }
    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        throw databaseError.toException(); // don't ignore errors
    }
});

This loops over the two level of child nodes you have under the user's receivedMessages node.


text:
Q: IN statement in where clause returns data with same id My query:
  $statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND pricing=:rate2  AND Poscode=:postcode2  ORDER BY Poscode DESC LIMIT 60");

user keys in array of values only for subid, so I used implode and IN to select accordingly in the database.
Here's how I derive their values from user input:
$a=$data['sub'];//this is for subid

foreach($a as $v=>$k)
  {

    $key[]=$v;

  }
 $key2=implode(',',$key);

$postcode=$data['postcode'];

$rate=$data['slider1'];

The problem is, since user keys in multiple subid, the query should search though the database for matching subid's, poscode as well as rate.
I suppose it should return, two records if two matching record found, one for the subid A and another for subid B.
But now, it returns two records but with same data,meaning same subid?
What made this query not return data with different id please?
Sample DATA

A user registered for two posts.
Post 1: postA
user name: userA
subject: maths
rate: 50
postcode:12345
Post 2: postB
user name: userA
subject: science
rate: 50
postcode:12345

Now I want to perform search on this:

I key in rate:50,
postcode:12345
subjects: maths, science
Now I should get to see, two posts with two different IDs,subjects but
  same user,postcode and rate.
But What I see:
Same id, same subject, same rate(which is
  correct), same postcode(which is correct).


text:
Q: Avoid Escape character in responses in WSO2 ESB API I have a problem returning payload in an API in WSO2 ESB. That problems is I get:
http:\/\/ip:port\/test\/

instead of
http://ip:port/test/

in a response.
Is there any property to avoid this problem?


text:
Q: Unit test Angular UI Bootstrap Modal I am new to angular and jasmine unit testing and trying to test modal open close for the controller below, I have tried writing a unit test to inject the modal but now I dont know how to test the methods inside. Need some guidance
Controller:
app.controller('feedDetailsController', function($scope, $modal, $log, feedDealService) {
    var modalController = function($scope, $modalInstance) {
        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };
    };

    /**
     * Displays feed details modal
     *
     * @param object currentPub
     */
    $scope.showForm = function(currentPub) {

        $scope.currentPub = currentPub;

        $modal.open({
            templateUrl: '/feedDetails/_feedDetails.html',
            controller: modalController,
            scope: $scope,
            windowClass: 'tm-modal feed-details-dialog',
            resolve: {
                feedDealModal: function() {
                    $scope.modal = {
                        title: 'Feed Details',
                        headers: {
                            col1: 'Col1',
                            col2: 'Col2',
                            col3: 'Col3',
                            col4: 'Col4'
                        },
                        feedDeals: feedDealService.getDeals(currentPub),
                        hasCancel: true,
                        hasSubmit: false
                    };
                    $scope.setDealAccess = function(dealId) {
                        feedDealService.updateDeal($scope.publishers, currentPub, dealId);
                    };
                    return $scope.feedDealModal;
                }
            }
        });
    };
});

Test:
describe('feedDetailsController', function() {

    beforeEach(module('premiumInventoryApp'));

    var MainCtrl, scope;

    var fakeModal = {
        result: {
            then: function(confirmCallback, cancelCallback) {
                //Store the callbacks for later when the user clicks on the OK or Cancel button of the dialog
                this.confirmCallBack = confirmCallback;
                this.cancelCallback = cancelCallback;
            }
        },
        close: function( item ) {
            //The user clicked OK on the modal dialog, call the stored confirm callback with the selected item
            this.result.confirmCallBack( item );
        },
        dismiss: function( type ) {
            //The user clicked cancel on the modal dialog, call the stored cancel callback
            this.result.cancelCallback( type );
        }
    };

    beforeEach(inject(function($modal) {
        spyOn($modal, 'open').and.returnValue(fakeModal);
    }));

    // Initialize the controller and a mock scope
    beforeEach(inject(function ($controller, $rootScope, _$modal_) {
        scope = $rootScope.$new();
        MainCtrl = $controller('feedDetailsController', {
            $scope: scope,
            $modal: _$modal_
        });
    }));

    it('should open a modal', function ()

        // Mock out the modal closing, resolving with a selected item, say 1
        scope.showForm(); // Open the modal
        scope.modalInstance.close();
        expect(scope.showForm).toEqual(fakeModal);
    });
});


text:
Q: expose multiple ports in AWS ECS I need to expose a range of ports in Amazon ECS.
the task definition limits single port mapping from host to container. like:
"portMappings": [
{
    "containerPort": 80,
    "hostPort": 80
},
  {
    "containerPort": 443,
    "hostPort": 443,
},
 {
    "containerPort": 0,
    "hostPort": 9080
}
],

and I did not find any solution to expose a range of ports like 32769-65535.
is there any way I can map the range of EC2 ports in the container?
Thanks


text:
Q: Can you Catch an Exception after the main application unit has ended? In one of our application im getting an exception that i can not seem to find or trap.
...
  Application.CreateForm(TFrmMain, FrmMain);
  outputdebugstring(pansichar('Application Run')); //this is printed
  Application.Run;
  outputdebugstring(pansichar('Application Run After')); //this is printed
end.
<--- The Exception seems to be here

The Event log shows
> ODS: Application Run
> //Various Application Messages
> ODS: Application Run After
> First Change Exception at $xxxxxxxx.  ...etc

All i can think of is it is the finalization code of one of the units.
(Delphi 7)

A: Try installing MadExcept - it should catch the exception and give you a stack-trace.
It helped me when I had a similar issue.

A: Here's two things you can try:
1) Quick and easy is to to hit 'F7' on the final 'end.'.  This will step you into the other finalization blocks.
2) Try overriding the Application.OnException Event.

A: The SysUtils unit actually sets up the default ErrorProc and ExceptProc procedures in its initialization section, and undoes them in its finalization section, so often in this situation it's worth ensuring that SysUtils is the very first unit in the uses clause in your dpr, so then it will be the last one finalised. Might be enough to get you some meaningful data about what is going wrong.

A: Finalization exceptions are tricky.  Even if you put SysUtls first in your project file, your application object may already be gone, which means your global exception handler is gone too.  MadExcept may work for this though.
Another solution is to put a Try / Except block in each of your unit finalization sections, and then handle the exceptions there.
What is your objective?  Do you want to suppress the exception or debug it?  Debugging it can be done by stepping through them with F7 as Zartog suggested.  If you discover which unit has the exception in finalization then you might try placing it in a different order in the uses clause it is called from.
Good luck!


text:
Q: How to export IE cookies using perl? I know that there is a option within Internet Explorer that I could use the manually export cookies. However, is it possible to have a Perl script to automate IE to export cookies to a text file or by using command shell?
I'm using Internet Explorer 11 for Windows 7. Thanks in advance!

A: I haven't tried it with Internet Explorer, but when I've had to do this task for other browsers, I found the file that the cookies are already in and parsed that directly. It's why there are so many HTTP::Cookies::* modules in my CPAN account.
There are also various Win32 modules to let you control Windows applications from Perl through the Windows APIs. I made a list of some examples that use Win32::OLE, for instance. There's one that plays Minesweeper for you!


text:
Q: Play! failing to convert java list to scala list I'm trying to pass a list of strings from my java controller to the scala template.
This is the view code:
public static Result index() {
    List<String> scripts = Arrays.asList(
        "script1.js",
        ...
        "scriptN.js"
    );

    return ok(views.html.index.render(scripts));
}

and this is the tempate code:
@(scripts: List[String])

@main("test page")(scripts) {
    ... html here ...
}

The error I'm getting (in the Typesafe Activation Compile page):

method render in class index cannot be applied to given types;
  required: scala.collection.immutable.List
  found: java.util.List
  reason: actual argument java.util.List cannot be converted to scala.collection.immutable.List by
  method invocation conversion

Is there a way to solve it without using the java > scala conversions?
I found this question: Play doesn't convert java-list to scala-list which describes a similar situation, though I do not have any templateImports that I'm aware of, I don't even see a Build.scala file...
Any ideas?
Thanks!

A: Try below:
import scala.collection.JavaConverters;

public static Result index() {
    List<String> scripts = Arrays.asList(
        "script1.js",
        ...
        "scriptN.js"
    );
    scala.collection.immutable.List<String> ls = JavaConverters.asScalaBufferConverter(scripts).asScala().toList();
    return ok(views.html.index.render(ls));
}

A: try below in your template code :
@import java.util
@(scripts: util.List[String])


text:
Q: How can I partition my ubuntu hard drive How can I partition my ubuntu hard drive.Im usıng linux ubuntu server and ım trying to partion into two .can you help me how to do this.still new to ubuntu

A: You can do it using fdisk utility. Here is a tutorial which I think might be helpful.
http://www.howtogeek.com/106873/how-to-use-fdisk-to-manage-partitions-on-linux/


text:
Q: Update the value of a variable every 5 mins I have a variable whose value needs to be updated every 5 mins depending on a condition. I am aware that I need to start a different thread. But how can I do that?

A: Use ScheduledThreadPoolExecutor, as shown below (based on this code):
public class Main{
 public static void main(String args[]) {
   ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(2);
   stpe.scheduleAtFixedRate(new YourJob(), 0, 5, TimeUnit.MINUTES);
 }
}

class YourJob implements Runnable {
   public void run() {
   // your task
    System.out.println("Job 1");
  }
}

A: Use Quartz Scheduler
which is much easier..To schedule a task..
It's a good for java to run a program in a scheduled time

*

*Quartz Schedular features to postpone a task to run at a given time

*Loop execution also available

A: Thread way to do this,
Thread t= new Thread(new Runnable()
    {
        public void run()
        {
            while(true)
            {
                try
                {
                    Thread.sleep(5 * 60 * 1000);
                    //change your variable values as required
                }
                catch (InterruptedException e)
                {

                }
            }
        }
    });

Thread pool executor way,
public static void main(String args[])
    {
        ScheduledThreadPoolExecutor myPool = new ScheduledThreadPoolExecutor(2);
        myPool.scheduleAtFixedRate(new MyJob(), 0, 5 , TimeUnit.MINUTES);
    }
    class MyJob implements Runnable
    {
        public void run()
        {
            //change your variable values as required in this function as this will be invoked every 5 minutes
        }
    }

Implementation by Timer
Timer timer =new Timer();
        TimerTask task = new TimerTask()
        {

            @Override
            public void run()
            {
                //change your variable values as required in this function as this will be invoked every 5 minutes

            }
        };
        timer.schedule(task, new Date(), 5 * 60 * 1000); //Use this if you want the new task to be invoked after completion of prior task only
        timer.scheduleAtFixedRate(task, new Date(), 5 * 60 * 1000);//Use this if you want the new task to be invoked after fixed interval
                                                                   //but will no depend or wait on completion of the prior task

A: How about using java.util.Timer?

A: If you're using Spring, you can annotate your method with @Scheduled, for example:
// Invoke method every 300000 ms (5 minutes)
@Scheduled(fixedDelay=300000)
public void myMethod() {
    // Your code here
}

Or you can take a look at Spring's documentation: http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#scheduling-annotation-support-scheduled


text:
Q: asset size limit: The following asset(s) exceed the recommended size limit (244 KiB) in storybook build I am tried to solve this, it shows when I command npm run build-storybook
Error:
asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
WARN This can impact web performance.
WARN Assets:
WARN   vendors~main.867acf8415a0b04d833b.bundle.js (274 KiB)
WARN entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.
WARN Entrypoints:
WARN   main (277 KiB)
WARN       runtime~main.867acf8415a0b04d833b.bundle.js
WARN       vendors~main.867acf8415a0b04d833b.bundle.js
WARN       main.867acf8415a0b04d833b.bundle.js
WARN
WARN webpack performance recommendations:
WARN You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.
WARN For more info visit https://webpack.js.org/guides/code-splitting/

My config file is:
import { configure,addDecorator,addParameters   } from '@storybook/react';
import {withKnobs } from "@storybook/addon-knobs";
import { withHTML } from '@whitespace/storybook-addon-html/react';
import { withInfo } from '@storybook/addon-info';
import crfTheme from './crfTheme';
// golbal scss
import "../styles/juni/storybook.scss";

//--------- addons--------
addDecorator(withKnobs({
  escapeHTML: false,
}));
addDecorator(withHTML);
addDecorator(withInfo);

// automatically import all files ending in *.stories.js
const req = require.context('../stories', true, /\.stories\.js$/);
function loadStories() {
    require('./welcomeStory');
    req.keys().forEach(filename => req(filename));
}
configure(loadStories, module);

and my min.js file is:
const path = require('path');

// Export a function. Accept the base config as the only param.
module.exports = {

  performance: {
    hints: false,
  },

  webpackFinal: async (config, { configType }) => {
    // `configType` has a value of 'DEVELOPMENT' or 'PRODUCTION'
    // You can change the configuration based on that.
    // 'PRODUCTION' is used when building the static version of storybook.

    // Make whatever fine-grained changes you need

    config.module.rules.push({
      test: /\.scss$/,
      use: ['style-loader', 'css-loader?url=false', 'sass-loader'],
      include: path.resolve(__dirname, '../'),
    });

    // Return the altered config
    return config;
  }
};

can anyone any idea to solve it?
Thanks


text:
Q: Loading categorical data in mlpack I am trying to load a dataset into mlpack. For this example, the data is in .tsv format and contains the data: height, bloodtype, and bodyweight.
67.4    "A-"    178.1
75.2    "O-"    194.3
70.1    "AB+"   167.0

I will load this data into an armadillo matrix of double type. height and weight should be stored exactly as read from file.
For the second data point, I want to make a nontrivial modification. I assume bloodtypes are (A-, A+, B-, B+, AB-, AB+, O-, O+). I want to store this as three 0/1 entries: containsA, containsB, isPositive. This means that each row of my armadillo matrix should contain 5 doubles.
Here is one way to do this:

*

*Call this overload of Load to store the data as an n x 3 matrix.

*Create a new n x 5 matrix by calling an overload of OneHotEncoding.

The downsides of this approach are that it requires creating a copy of the matrix and that it requires having an intermediate step where complex categorical variables may be stored as doubles.
Because mlpack provides the argument DatasetMapper for Load, I suspect there's a way to do this during Load with no n x 3 matrix copy made. However, I can't figure out how.


text:
Q: I need to loop through table and insert new record in another table I need to loop through table Organisation and insert new record in User table
Select Code,Organisationid from organisation

INSERT INTO User(userlogin,Organisationid,emailaddress,username,userpassword)
VALUES('AGT'+ Code, organisationid,'test@gmail.com','User'+ Code,'123')

I need to dynamically pass the Organisationid  and Code to the User table to loop through and insert new record in user.

A: Just use INSERT INTO ... SELECT:
INSERT INTO User (userlogin, Organisationid, emailaddress, username, userpassword)
SELECT 'AGT' + Code, organisationid, 'test@gmail.com', 'User' + Code, '123'
FROM organisation;


text:
Q: Print out only headers in Rails request I know how to access a header in Rails
request.headers["HEADER_NAME"]

However, I want to get all headers passed by a browser. I see that I can enumerate it
request.headers.each { |header| ... }

However, this will spit out both headers and other environment variables. Is there a way to get only headers?
Update 1
My problem isn't interation. My problem is distinguising between environment variables and headers. Both of them will be reported while interation using each or keys.

A: not sure if this is any helpful but I ended up using this brute force approach
request.env.select {|k,v|
  k.match("^HTTP.*|^CONTENT.*|^REMOTE.*|^REQUEST.*|^AUTHORIZATION.*|^SCRIPT.*|^SERVER.*")
}

A: Solution
By convention, headers do not usually contain dots. Nginx even rejected requests with dots in headers by default. So I think it's quite a safe assumption to go with.
On contrary, all rails environment garbage is namespaced e.g. action_dispatch.show_exceptions, rack.input etc.
These two facts conveniently suggest a way to distinguish external headers from internal variables:
request.headers.env.reject { |key| key.to_s.include?('.') }

Works neat.

Benchmarking a bit
Note, that include?('.') implementation works about 4 times faster than matching =~ /\./
Benchmark.measure { 500000.times { hsh.reject { |key| key.to_s =~ /\./ } } }
 => real=2.09
Benchmark.measure { 500000.times { hsh.reject { |key| key.to_s.include?('.') } } }
 => real=0.58

Hope that helps.

A: By using
request.headers.each { |key, value|  }

This is iterating your requested header with (key+value), but if you want specific values you have to use key name like, HTTP_KEYNAME because whenever HTTP request come it will append HTTP to keys and be sure about uppercase because it is case sensitive.
for example:
if we have passed auth_token as header request parameter and want to access, we can use this.
request.headers["HTTP_AUTH_TOKEN"]

A: You can try this to get only headers list from request
request.headers.first(50).to_h.keys

It will convert request.headers object into array and then to hash to get list of all keys in request to be used as
request.headers["keyname"]

It might be not much efficient but I think it can do the job.
Hope this helps.

A: You might be probably looking for :
request.env

This will basically create a Ruby Hash of the whole request object.
For more details, check this question:
How do I see the whole HTTP request in Rails

A: If you just want headers:

request.headers.to_h.select { |k,v|
  ['HTTP','CONTENT','AUTHORIZATION'].any? { |s| k.to_s.starts_with? s }
}

If you want everything that's not an env var:
request.headers.to_h.select { |k,v|
  ['HTTP','CONTENT','REMOTE','REQUEST','AUTHORIZATION','SCRIPT','SERVER'].any? { |s|
    k.to_s.starts_with? s
  }
}

A: You should be able to do
request.headers.each { |key, value|  }

In general when iterating over a hash ruby looks at the arity of your block and gives you either a pair (key + value) or separate variables. (The hash in this case is an object internal to the headers object)


text:
Q: SQL Server Schema and data comparison using SSDT I'm trying to do data comparison and automate database upgrade script generation by using SQL Server Database tools > SchemaComparison/DataComparison.
Using VS command window, I am able to run
> Tools.NewDataComparison [args...]
> SQL.DataCompareExportToFile [file]

which produces .sql file containing required inserts/updates/deletes.
Now I would like to go a step further and automate this.
I have been looking at Microsoft.VisualStudio.Data.Tools.DataCompare, Microsoft.SqlServer.Dac and similar assemblies but haven't found any of the methods above.
Which dll exposes these?
I have also tried to run these methods with devenv.exe (which only starts VS and executes the arguments in command window) but was only successful at running Tools.NewDataComparison. Is there a way to chain or reuse the context, so I can run the SQL.DataCompareExportToFile afterwards?
I know I can use SqlPackage.exe to export dacpac and bacpac, but comparison is possible only for schema. Data comparison is not. Is there a way to use bacpac for comparison?
I would accept any solution which would allow me to compare the databases and generate the upgrade .sql script. Either in C# or any other script.

A: Unfortunately I cannot comment to ask for clarification.  If this is a DB project in Visual Studio you can setup Pre and Post execution scripts to manage data updates.
We break ours down into
Reference Data - Static lookup data, we kill and fill so Ref data is always clean and controlled.
Migration Data - Copies data from another source and is based on what release is being run and only executes once.
Sandbox Data - Aligns data for repeatable test by the front-end.  Think of unit testing.  Only runs on non-Prod environments.
So once you have this in place, then we use SqlPackage to upgrade the DAC which includes the Pre and Post scripts.
If you are talking about actually comparing 2 databases, then I only know client tools like VS Data Compare and Red Gate that could do that.  But you could try using Merge between tables or maybe explore an SSIS solution.


text:
Q: How to limit values of IntergerField with Django? i wonder if it's possible to limit values of an IntegerField with Django.
My code in forms.py :
class RatingForm(forms.Form):
    rate = forms.IntegerField(label='Noter')

A:   from django.core.validators import MaxValueValidator, MinValueValidator

  class RatingForm(forms.Form):
    rate = forms.IntegerField(label='Noter',
            validators=[
                MaxValueValidator(100),
                MinValueValidator(1)
            ]
         )

use django's built in validators

A: You can use max_value as specified in the django doc. https://docs.djangoproject.com/en/1.11/ref/forms/fields/#integerfield
class RatingForm(forms.Form):
    rate = forms.IntegerField(label='Noter', max_value=100)

A: Use min_value and max_value, inside your form: see the Django docs

A: This code works :
class RatingForm(forms.Form):
    rate = forms.IntegerField(label='Noter', validators=[MaxValueValidator(5), MinValueValidator(0)])

Thanks all !!


text:
Q: Fitting a Keras model with large amount of data using a custom data generator I'm trying to fit my Keras model with quite large amount of data.
To do this, I'm using custom data generators and model.fit_generator function.
However, I can't seem to understand if I'm doing this correctly.
Here's what I have:
from os.path import join

import cv2
import numpy as np
from keras.models import Sequential
from keras.layers.core import Flatten, Dense, Dropout
from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import SGD
from keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau

# The function returns a list of image names from folder
from data.preprocessing import get_list_of_images

class VGG19(object):
    def __init__(self, weights_path=None, train_folder='data/train', validation_folder='data/val'):
        self.weights_path = weights_path
        self.model = self._init_model()

        if weights_path:
            self.model.load_weights(weights_path)
        else:
            self.datagen = self._init_datagen()
            self.train_folder = train_folder
            self.validation_folder = validation_folder
            self.model.compile(
                loss='binary_crossentropy',
                optimizer='adam',
                metrics=['accuracy']
            )

    def fit(self, batch_size=32, nb_epoch=10):
        self.model.fit_generator(
            self._generate_data_from_folder(self.train_folder), 32,
            nb_epoch,
            verbose=1,
            callbacks=[
                TensorBoard(log_dir='./logs', write_images=True),
                ModelCheckpoint(filepath='weights.{epoch:02d}-{val_loss:.2f}.hdf5', monitor='val_loss'),
                ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=5, min_lr=0.001)
            ],
            validation_data=self._generate_data_from_folder(self.validation_folder),
            nb_val_samples=32
        )

    def predict(self, X, batch_size=32, verbose=1):
        return self.model.predict(X, batch_size=batch_size, verbose=verbose)

    def predict_proba(self, X, batch_size=32, verbose=1):
        return self.model.predict_proba(X, batch_size=batch_size, verbose=verbose)

    def _init_model(self):
        model = Sequential()
        # model definition goes here...
        return model

    def _init_datagen(self):
        return ImageDataGenerator(
            featurewise_center=True,
            samplewise_center=False,
            featurewise_std_normalization=True,
            samplewise_std_normalization=False,
            zca_whitening=False,
            rotation_range=20,
            width_shift_range=0.2,
            height_shift_range=0.2,
            horizontal_flip=True,
            vertical_flip=True
        )

    def _generate_data_from_folder(self, folder_path):
        while 1:
            images = get_list_of_images(folder_path)

            for image_path in images:
                x = cv2.imread(join(folder_path, image_path))
                y = 0 if image_path.split('.')[0] == 'dog' else 1

                yield (x, y)

My dataset consists of images with names like:

*

*cat.[number].jpg, i.e.: cat.124.jpg

*dog.[number].jpg, i.e.: dog.64.jpg
So, basically, I'm trying to train a model to perform a binary cat-dog classification.

Is my _generate_data_from_folder function correctly implemented for mini-batch optimization?
How can I add the usage of ImageDataGenerator to my _generate_data_from_folder function (from the _init_datagen function)?

A: Okay, here's the github link to my final version of the project that I got working:
https://github.com/yakovenkodenis/dogs-vs-cats-kaggle
Hope, it helps somebody


text:
Q: Does Wordpress.com use ONE set of tables for ALL users? Does wp.com create a new set of tables for each new blog, or are all blog data stored in one set of tables (with a layout like: http://codex.wordpress.org/Database_Description)?
Would it ever be a good idea to create a set of tables for each blog in MySQL, or will MySQL be able to handle large numbers of blogs each with their comments/tags/categories/posts stored in one set of tables?

A: For how Wordpress does it, have a look at Wordpress MU
I imagine at a quick guess there's a shared user table and each blog gets it's own DB as the relations between objects only apply within a individual blog.
Edit: From the MU FAQ:

WordPress MU creates tables for each
  blog, which is the system we found
  worked best for plugin compatibility
  and scaling after lots of testing and
  trial and error. This takes advantage
  of existing OS-level and MySQL query
  caches and also makes it infinitely
  easier to segment user data, which is
  what all services that grow beyond a
  single box eventually have to do.


text:
Q: MSTest Could not load file or assembly 'System.Runtime, Version=5.0.0.0' or one of its dependencies I have a .NET 5.0 unit test project that I'm trying to execute via the command line using MSTest.
I'm using a command like the following to run the unit tests:
MSTest.exe /testcontainer:tests\bin\Debug\net5.0\UnitTestProject.dll

But I receive the following error message:
Unable to load the test container 'tests\bin\Debug\net5.0\UnitTestProject.dll'
or one of its dependencies. Error details: System.IO.FileNotFoundException:
Could not load file or assembly 'System.Runtime, Version=5.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
The system cannot find the file specified.

I've seen similar questions on here such as Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies but the answers make reference to editing an app.config file, which I do not have in my project.
Is this just a limitation of using .NET 5.0 and MSTest in the way I'm trying to? Or is there something I can do to allow MSTest to run the tests?

A: So I've done more playing around with this and because I need to use a COM library as part of the project it seems that it's not possible to use .NET 5.0/.NET core stuff in anyway.
I did a test using .NET Framework 4.7.2 - I made a unit test solution using this version of the framework, added a COM library and ran the unit tests at the command line and all worked. The only gotcha with this was I had to use vstest.console.exe and not MSTest to run the tests.
Using MSTest gave me the No tests to execute issue. But it seems like using vstest.console.exe is the answer to this - No tests to execute msTest


text:
Q: SQL creating a Database throws 'MySQLSyntaxErrorException: Specified key was too long; max key length is 767 bytes' when i try to create a database with the following statement
            c.prepareStatement("CREATE TABLE IF NOT EXISTS `verify` (" +
                    "`id` INT NOT NULL AUTO_INCREMENT UNIQUE," +
                    "`uuid` VARCHAR(255) NOT NULL UNIQUE," +
                    "`ts` INT NOT NULL UNIQUE," +
                    "PRIMARY KEY (`id`)" +
                    ");").execute();

i get this Error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Specified key was too long; max key length is 767 bytes

A: You want the uuid to be UNIQUE but for string columns:

indexes can be created that use only the leading part of column
values, using col_name(length) syntax to specify an index prefix
length

and

Prefix support and lengths of prefixes (where supported) are storage
engine dependent. For example, a prefix can be up to 767 bytes long
for InnoDB tables that use the REDUNDANT or COMPACT row format. The
prefix length limit is 3072 bytes for InnoDB tables that use the
DYNAMIC or COMPRESSED row format. For MyISAM tables, the prefix length
limit is 1000 bytes.

So, you can create your table without this index and then to set the index to get the subset of your column:
ALTER TABLE `verify` ADD UNIQUE ( uuid(191) );

as 767 / 4 ~= 191.


text:
Q: .Xauthority file is empty I have been trying to ssh -X to my cluster running OpenSUSE 11.2. It used to work well for me. But now I get this message:
X11 connection rejected because of wrong authentication.
Failed to open the X11 display!

So I tried to check the ownership and permission of the .Xauthority file using
sudo ls -al .Xauthority

and I get to see that the file is empty with size 0:
-rw------- 1 <my-user-name> users 0 2014-07-31 10:03 .Xauthority

When I log in with ssh -Xv
I get the following when i try to open xlock
debug1: client_input_channel_open: ctype x11 rchan 3 win 65536 max 16384
debug1: client_request_x11: request from ::1 53267
debug1: channel 1: new [x11]
debug1: confirm x11
X11 connection rejected because of wrong authentication.
debug1: channel 1: free: x11, nchannels 2
Error: Can't open display: localhost:10.0

How would I fix this?

A: If the filesystem containing your home directory on the remote server is 100% full or if disk quotas are in effect and you're over your quota, it might be possible to create a new zero-length file but not to write anything into it. This will stop sshd from being able to write a X11 session cookie into the .Xauthority file, causing the X11 forwarding to fail.
Check for these conditions, with commands df -h . and quota, before trying anything more elaborate. If necessary, clear some space, then log out and try again.

A: Try to add some displays:
mcookie|sed -e 's/^/add :0 . /'|xauth -q

mcookie|sed -e 's/^/add :1 . /'|xauth -q

....................................


text:
Q: How to retrieve data from CloudKit using SwiftUI I am using SwiftUI to make an app and storing the data on ICloud. Because all the code I can find relates to Swift and viewDidLoad and TableView, however this do not apply. I have written code and seems to retrieve it but will not return it to the ObservableObject to be able to display in the SwiftUI
The ObservableObject file:-
import SwiftUI
import Combine

final class ObservedData: ObservableObject {
    @Published var venues = venuesData
}

The query to retrieve data
import SwiftUI
import CloudKit

var venuesData: [Venue] = loadVenues()

func loadVenues() -> [Venue] {

    var data = [Venue]()

    let pred = NSPredicate(value: true)
    let sort = NSSortDescriptor(key: "id", ascending: true)
    let query = CKQuery(recordType: "DeptfordHopData", predicate: pred)
    query.sortDescriptors = [sort]

    let operation = CKQueryOperation(query: query)
    operation.desiredKeys = ["id","name", "address"]
    operation.resultsLimit = 50

    var newVenues = [Venue]()

    operation.recordFetchedBlock = { record in
        let venue = Venue()
        venue.racordID = record.recordID
        venue.id = record["id"]
        venue.name = record["name"]
        venue.address = record["address"]
        newVenues.append(venue)
    }

    operation.queryCompletionBlock = {(cursor, error) in
        DispatchQueue.main.async {
            if error == nil {
                data = newVenues
            } else {
                print(error!.localizedDescription)
            }
        }
    }

    CKContainer.default().publicCloudDatabase.add(operation)

    return data
}

I have got data showing when do break in data but does not pass to venueData

A: The query operation runs asynchronously. When you add the operation to the database, the framework runs the query in the background and immediately returns control to your function, which promptly returns data, which is still set to the empty array.
To fix this, you either need to wait for the operation to complete using Grand Central Dispatch (not recommended if this is called directly from UI code, as it will block your application), or you need to rewrite loadVenues so it accepts a callback that you can then invoke inside queryCompletionBlock. The callback you provide to loadVenues should save the array of venues somewhere where SwiftUI will detect the change.


text:
Q: Typescript Initialize object member of class defined in the class In a situation like this (simplified):
    class Order{
        items:{prices:number[],lastUpdate:Date};
    }

I want to have orders not undefined.
    class Order{
        items:{prices:number[],lastUpdate:Date} = {prices:[],lastUpdate:new Date};
    }

does it but I am not sure is the cleanest (lazy) way. What I don't want in this case is create an OrderItem class. Suggestions?

A: TypeScript will happily infer types of variables and properties for you, and you only have to correct it if it infers something you don't like.
So you could do this:
class Order {
  items = { prices: [], lastUpdate: new Date };
}

which infers items to be of type { prices: never[]; lastUpdate: Date; }.  That's close to what you want but it has no idea that an empty array will hold numbers.  So you can then do this:
class Order {
  items = { prices: [] as number[], lastUpdate: new Date };
}

Now you've told it (via type assertion) that the empty array is for numbers, and items is inferred as { prices: number[]; lastUpdate: Date; } as desired.
Hope that helps.


text:
Q: a closedness argument in the proof of Theorem 17.2 in Rockafellar's Convex Analysis Let $S$ be a bounded subset of $\mathbb{R}^n$, and define $m = (n+1)^2$. Let $Q$ be the subset of $\mathbb{R}^m$, consisting of all points of the form $(\lambda_0,\dots,\lambda_n,x_0,\dots,x_n)$, where $\lambda_i$ are non-negative scalars such that $\lambda_0+\cdots +\lambda_n=1$, and $x_0,\dots, x_n$ are in the closure of $S$. Consider the mapping $\theta: \mathbb{R}^m \rightarrow \mathbb{R}^n$ such that $(\lambda_0,\dots,\lambda_n,x_0,\dots,x_n) \mapsto \lambda_0 x_0 + \cdots + \lambda_n x_n$. The image of $Q$ under $\theta$ is bounded. But why is it also closed? This shows up in the proof of Theorem 17.2 in Rockafellar's Convex Analysis.

A: Note that the domain (which is the product of an $n$-dimensional simplex and a bounded closed subset $\operatorname{cl}(S)$) is compact. Since $\theta$ is continuous, the image is compact, and thus closed.
Reference for the last result: a continuous image of a closed subset of a compact space is a closed subset


text:
Q: Python Statsmodels ARIMA: How to add/combine a feature(variable) in the model Hello I am modeling an ARIMA in Python using statsmodels.
The code is below:
p = d = q = range(0, 2)

# Generate all different combinations of p, q and q triplets
pdq = list(itertools.product(p, d, q))

# Generate all different combinations of seasonal p, q and q triplets
seasonal_pdq = [(x[0], x[1], x[2], 1) for x in list(itertools.product(p, d, q))]

print('Examples of parameter combinations for Seasonal ARIMA...')
print('SARIMAX: {} x {}'.format(pdq[1], seasonal_pdq[1]))
print('SARIMAX: {} x {}'.format(pdq[1], seasonal_pdq[2]))
print('SARIMAX: {} x {}'.format(pdq[2], seasonal_pdq[3]))
print('SARIMAX: {} x {}'.format(pdq[2], seasonal_pdq[4]))

warnings.filterwarnings("ignore") # specify to ignore warning messages

for param in pdq:
    for param_seasonal in seasonal_pdq:
        try:
            mod = sm.tsa.statespace.SARIMAX(y,
                                            order=param,
                                            seasonal_order=param_seasonal,
                                            enforce_stationarity=False,
                                            enforce_invertibility=False)

            results = mod.fit()

            print('ARIMA{}x{}12 - AIC:{}'.format(param, param_seasonal, results.aic))
        except:
            continue

mod = sm.tsa.statespace.SARIMAX(y,
                                order=(1, 1, 1),
                                seasonal_order=(1, 1, 1, 12),
                                enforce_stationarity=False,
                                enforce_invertibility=False)

results = mod.fit()

print(results.summary().tables[1])

As the result of the model I get this diagnostic table:
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
ma.L1         -0.6255      0.077     -8.165      0.830      -0.376      -0.475
ar.S.L12      -0.0010      0.001      1.732      0.003      -0.000       0.002
ma.S.L12      -0.8769      0.026    -33.811      0.000      -0.928      -0.826
sigma2         30.0972      0.004     22.634      0.000       0.089       0.106
==============================================================================

To improve the model, I want to get rid of the ma.L1 and want to add a feature(a new variable) made by me. But I do not know how to add a variable into this model. Particularly, I have a list of numbers like this [2.34, 3.22, 2.11, ...] same length as the dataset I used for this ARIMA. I want to add this list as a variable into the ARIMA model OR I should say combine this new variable with the ARIMA model. Any idea how should I do ?