text:
Q: How to analyze multiple variable time series - suggest references I have multiple environmental time series variables (for example: temperature, dissolved oxygen, conductivity, depth) measured every few minutes for several months.  The variables are measured at different intervals but I could create an interpolated data set such that all data are placed at the same times.
I want to be able to understand how these variables are related to each other.  For example I would be interested in a question like:

Is an increase in depth correlated with a decrease in temperature?

The variables may change at the same time, but more likely there will be some lag time between a change in depth and a change in temperature.  Plus I would like to look at many variables - not just 2.
I am not interested in cycles or trends within one time series - just how one may affect another.
I am not sure where to start - is this just a multiple regression?  How do I take lag time into account?  Could you suggest topics I could read about?

A: You should look to Box-Jenkins Transfer Function modeling.  It was Chapter 11 in their book.
http://books.google.com/books?id=jyrCqMBW_owC&printsec=frontcover&dq=box+jenkins+time+series&hl=en&sa=X&ei=sDO-U4aCC8WZyASIkoLoBg&ved=0CDYQ6AEwAQ#v=onepage&q=box%20jenkins%20time%20series&f=false
Here is a link that explains the differences between  regression vs  Transfer Function models. http://www.autobox.com/cms/index.php/afs-university/intro-to-forecasting/doc_download/24-regression-vs-box-jenkins

A: No reference, but I guess the standard time-series way to do it is to use some kind of auto-regressive model (AR-model)
$$X_t = c + \sum_{i=1}^p \varphi_i X_{t-i}+ \varepsilon_t$$
You can find it in any textbook on time-seies analysis. The $\varphi_i$ are vectors of parameters which must be fitted, and the pre-chosen order $p$ determines the maximum lag time (further, $\varepsilon_t$ is a Gaussian error term).
The AR-model is simply a multivariate linear regression using the previous $p$ results as predictor and the current result as target. Obviously, you can extend this ansatz to any other multivariate statistic method. For instance, you can incorporate $x_i x_j$ to model interactions, use a neural network, etc.
As an alternative and easier method, you can also model only a single predictor given the instances of all predictors at $p$ previous times. This is more convenient since many methods in statistics consider a scalar output. Also, the interpretation is a bit easier. For example, in your mentioned case (depth-temperature) and for linear regression, you would model the temperature and then -- if there is some correlation -- find significant magnitude of the model parameters related to depth.


text:
Q: the hive can't create map/reduce job i have used hive-0.11.0, hadoop 2.0.3, and mysql 5.6 for metadata
i can successful run the statement like SELECT * FROM records,which not create a map/reduce task.
But when i try run SELECT * FROM records where year='1949' the map/reduce task always get some error
the hadoop give me Diagnostics:
Application application_1382680612829_0136 failed 1 times due to AM Container for appattempt_1382680612829_0136_000001 exited with exitCode: -1000 due to: java.io.FileNotFoundException: File /tmp/hadoop-hadoop/nm-local-dir/filecache does not exist at org.apache.hadoop.fs.RawLocalFileSystem.getFileStatus(RawLocalFileSystem.java:492) at org.apache.hadoop.fs.FileSystem.primitiveMkdir(FileSystem.java:996) at org.apache.hadoop.fs.DelegateToFileSystem.mkdir(DelegateToFileSystem.java:150) at org.apache.hadoop.fs.FilterFs.mkdir(FilterFs.java:187) at org.apache.hadoop.fs.FileContext$4.next(FileContext.java:730) at org.apache.hadoop.fs.FileContext$4.next(FileContext.java:726) at org.apache.hadoop.fs.FileContext$FSLinkResolver.resolve(FileContext.java:2379) at org.apache.hadoop.fs.FileContext.mkdir(FileContext.java:726) at org.apache.hadoop.yarn.util.FSDownload.createDir(FSDownload.java:88) at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:274) at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:51) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:662) .Failing this attempt.. Failing the application.
what i should do? thanks

A: In summary, as solution they recommend to create the  parent folders, there is also a patch that is supposed to be fixed at 2.0.3 [1]

Tom White added a comment - 30/Nov/12 21:36 This fixes the problem by
  creating parent directories if they don't already exist. Without the
  fix the test would fail about 4 times in 10; with the fix I didn't see
  a failure.

It looks like the most similar issue that I could find in the hadoop bugs database
It's also related to [2] and [3] if you want to take a look

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I force Plasma 5 to treat two monitors as one in Kubuntu 16.04? Goal
I want to use KDE across two monitors, but I only want the window manager to see them as one single virtual monitor.  I would like to achieve this goal either using KDE settings, nvidia-settings, or xorg.conf.
What I've tried
I have tried enabling Xinerama in my xorg.conf file and it works at the login page, but then the Plasma desktop doesn't load.  I get no taskbar and have to use alt-F2 to run anything, as well as encounter lots of other problems.  I have also tried TwinView as I am running nvidia, but I get the same above problems.
More info
Basically I want the taskbar to stretch across both screens, and to be able to maximize windows to take up both screens.  I've had this problem in every flavor of Ubuntu (Ubuntu 15, Kubuntu, Mint 17) and every window manager (Openbox, Compiz, Awesome) I've tested.
Here is a screenshot of what I see:

xorg.conf
# nvidia-settings: X configuration file generated by nvidia-settings
# nvidia-settings:  version 361.42  (buildd@lgw01-18)  Tue Apr  5 14:33:28 UTC 2016

Section "ServerLayout"
    Identifier     "Layout0"
    Screen      0  "Screen0" 0 0
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Mouse0" "CorePointer"
    Option         "Xinerama" "0"
    Option         "Twinview"   "true"
EndSection

Section "Files"
EndSection

Section "Module"
    Load           "dbe"
    Load           "extmod"
    Load           "type1"
    Load           "freetype"
    Load           "glx"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Mouse0"
    Driver         "mouse"
    Option         "Protocol" "auto"
    Option         "Device" "/dev/psaux"
    Option         "Emulate3Buttons" "no"
    Option         "ZAxisMapping" "4 5"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Keyboard0"
    Driver         "kbd"
EndSection

Section "Monitor"
    # HorizSync source: edid, VertRefresh source: edid
    Identifier     "Monitor0"
    VendorName     "Unknown"
    ModelName      "DELL UP2414Q"
    HorizSync       31.0 - 140.0
    VertRefresh     29.0 - 75.0
    Option         "DPMS"
EndSection

Section "Device"
    Identifier     "Device0"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
    BoardName      "GeForce GTX 970"
EndSection

Section "Screen"
    Identifier     "Screen0"
    Device         "Device0"
    Monitor        "Monitor0"
    DefaultDepth    24
    Option         "nvidiaXineramaInfoOrder" "DFP-2.9"
    Option         "metamodes" "DP-0.8: nvidia-auto-select +1920+0, DP-0.9: nvidia-auto-select +0+0"
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

Other window managers might work better, but I really like the one in Plasma 5 and would prefer to keep using it.

A: Turn off Twinview.  Change this line in xorg.conf
   Option         "Twinview"   "false"

Note: When you maximize a window it will go across both monitors, but I think this is what you want.
Also Note: This only works with Nvidia cards and driver.


text:
Q: Not getting List View on DIalog box Problem is with its showing me nullpointer exception while click onshowContact button there is something wrong i cant figure it out but I m not getting the dialog box with the list view with this code
Button click of contact view
public void showContacts(View view){
        //View CSV into an array
        try{
        Dialog dialog = new Dialog(NewMessage.this);
        dialog.setContentView(R.layout.contact_view);
        dialog.setTitle("Contacts");

        dialog.setCancelable(true);
        ListView lv = (ListView)findViewById(R.id.lv);
        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
        int fillarray = 0;
        if(mylist.equals(null)){
            fillarray = 0;
        }
        else{
            fillarray = mylist.size();
        }*/
        for(int i=0;i<name.size();i++)
        {

            HashMap<String, String> map = new HashMap<String, String>();
            map.put("name",name.get(i));
            map.put("number",number.get(i));
            map.put("status",status.get(i));
            mylist.add(map);
        }
        SimpleAdapter mSchedule = new SimpleAdapter(NewMessage.this, mylist, R.layout.view_csv, new String[] {"name","number","status"}, new int[] {R.id.t1,R.id.t2,R.id.t3});
        lv.setAdapter(mSchedule);
    dialog.show();
        }
        catch(Exception e){
            Toast.makeText(NewMessage.this, e.toString(), 2000).show();
        }
//Viewing Finish Here

    }

This my contact_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

    <ListView
        android:id="@+id/lv"
        android:layout_width="wrap_content"
        android:layout_height="397dp" >
    </ListView>

</LinearLayout>

This my view_csv.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingTop="4dip"
    android:paddingBottom="6dip"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
    android:id="@+id/t1"
    android:layout_width="90dip"
    android:layout_height="wrap_content"
    android:text="text1"/>
     <TextView
     android:id="@+id/t2"
    android:layout_width="90dip"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="text2"/>
      <TextView
     android:id="@+id/t3"
    android:layout_width="50dip"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="text3" />

</LinearLayout>

A: Your ListView is comming under contact_view layout. So you have to initialize the list through your dialog. because your dialog contains the layout here dialog.setContentView(R.layout.contact_view);
So you have to initialize the list like:
 ListView lv = (ListView) dialog.findViewById(R.id.lv);


text:
Q: Movie with 2 female demons or monsters sucking nutrients from their victims through a plastic tube I'm looking for a movie that I watched ages ago when I was a child. I don't remember the name but I only remember there are 2 female demons or monsters. They suck the nutrients of the victims from a thing looks like a plastic tube. In the end they being sealed and conjoined together in an egg shaped like statue. I spent too much time looking for this movie, thanks so much if anyone can tell me the name.

A: Clive Barker's "Saint Sinner"(2002 TV movie)?
Here is the plot summary from Wikipedia.

In 1815 California, Father Michael, an emissary of Pope Pius VII, has traveled to meet with novice monk Brother Tomas. The young monk's order serves as the secret repository for evil, supernatural objects collected by the Church, and kept there for safekeeping. Michael delivers an ancient statue that has trapped two beautiful female demons, Munkar and Nakir. Tomas and his friend Brother Gregory inadvertently release the murderous demons, who travel to the 21st century using the monastery's Wheel of Time.
As his brother lies dying, he is given a chance to redeem himself by going through the Wheel of Time with a sacred dagger previously used by Saint Nicodemus to imprison the succubi. Tomas reluctantly intends to track down the evil creatures and destroy them. The young monk takes on the task, traveling through the Wheel only to discover a future world he does not understand in present-day Seattle, Washington, where he allies with police detective Rachel Dressler to recapture the homicidal terrors.
While the creatures seek to satisfy their centuries-long hunger, Tomas discovers their first victim. The police arrive on the murder scene and take Tomas into custody, believing he may be involved. Detective Rachel Dressler (Ravera) isn't about to believe Tomas' weird story, but strange things start to happen and bodies begin to pile up. Both Tomas and Rachel soon discover that the only way to stop these horrifying demons will be to take a leap of faith.

Below is the official trailer:


text:
Q: OWL-DL; determining if an expression is legal In SHOIN(D) that is equivalent to the DL family used by OWL-DL;
Is this expression legal:
F ⊑ (≤1 r. D) ⊓ (¬ (=0 r. D))

Where F, D are concepts, r is a role. I want to express that each instance of F is related to at most one instance of D through r, and not to zero instances.
In general, how to decide that some expression is legal w. r. t. a specific variation of DL? I thought that using BNF syntax of the variation may be what I'm targeting.

A: One easy way is to check whether you can write it in Protege.  Most of the things that you can write in Protege will be legal OWL-DL.  In Protege you can write:

F SubClassOf ((r max 1 D) and not(r exactly 0 D))

Of course, saying that something has at most 1 value, and not exactly one would be exactly the same as saying that it has exactly 1:

F SubClassOf r exactly 1 D

But there are a few things that you'll be able to do in Protege that won't be legal OWL-DL.  The more direct way to find out what these are is the standard, specifically §11 Global Restrictions on Axioms in OWL 2 DL.  Generally the only problems you might run into is trying to use composite properties where you're not allowed to.
If you don't want to check by hand, then you could try uploading your ontology into the OWL Validator and selecting the OWL2 DL profile.


text:
Q: SQL Select Count Distinct with WHERE clause Aim: We have a database with UserID and SiteID if they userID/SiteID match then they can see details.
Thought: I have tried using the Count(Distinct...) to see if it exists. Then if it returns a value that is not zero I know that they can see the details.
Is this the best way?
Issue: Trying to use this way I can not get the WHERE clause to work.
Error: Errors vary am I have played but essentially says I can not have a WHERE clause, is this correct?
Code:
Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("mySQL").ToString()
                Using connection = New SqlConnection(ConnectionString)
                    Using command As New SqlCommand("Select Count(Distinct(UserID)) FROM tblTable where UserID= '" & Session.Item("UserID").ToString & "'", connection)

                        connection.Open()
                        Dim result = command.ExecuteScalar()

                        lblResult.Text = result

                        connection.Close()
                    End Using
                End Using

A: I tried your code and I do not see where you are having an issue, unless your Session.Item("UserId") is not being set properly.  I do not have a session so I improvised in a console application.  I am trying to figure out what exactly you are trying to do because the Count(Distinct(UserId)) will always return 1. Since you are asking for a specific userId, then asking to distinct it and then count it.  so 1 user returns 100 times, distinct give you the only user in the list, so 1 returns.
 Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ToString()
    Using connection = New SqlConnection(ConnectionString)

        Using command As New SqlCommand()
            Dim userId As String = "3"
            command.Connection = connection
            command.CommandText = "Select Count(Distinct(UserId)) FROM tblTable _
                                      where UserId= '" & userId & "'"

            connection.Open()
            Dim result = command.ExecuteScalar()

            Console.WriteLine(result)

            connection.Close()
        End Using
    End Using

If you are just looking to see if the user exists, try the following code.
     Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ToString()
    Using connection = New SqlConnection(ConnectionString)

        Using command As New SqlCommand()
            Dim userId As String = "3"
            command.Connection = connection
            command.CommandText = "Select Count(UserId) FROM tblTable _
                                      where UserId= '" & userId & "'"

            connection.Open()
            Dim result = command.ExecuteScalar()

            Console.WriteLine(result)

            connection.Close()
        End Using
    End Using

This will tell you in the how many rows containing the userIds are in the table
if you want to see the UserID/Site Comination with counts that is a another story
     Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ToString()
    Using connection = New SqlConnection(ConnectionString)

        Using command As New SqlCommand()
            Dim userId As String = "3"
            command.Connection = connection
            command.CommandText = "Select UserID, Count(SiteId) FROM tblTable where _
                          UserId= '" & userId & "'" & " Group By UserId"

            connection.Open()
            Dim dataReader = command.ExecuteReader()
            Do While dataReader.Read()
                Console.WriteLine( _
                    vbTab & "UserId: {0}" & vbTab & "SiteID Count: {1}", _
                 dataReader(0), dataReader(1))
            Loop
            connection.Close()
        End Using
    End Using

I think that should get you on the correct Track

A: There is no problem with a where clause in the query:
select count(distinct userid)
from tblTable
where UserID= '" & Session.Item("UserID").ToString & "'";

It is possible that in some SQL engines, the additional parentheses around userid are not allowed.
In any case, this is not the best way to determine if a row exists, because it has to do a fair amount of processing.  Instead, check the number of rows returned by this query (if the engine supports limit):
select 1
from tblTable
where UserID= '" & Session.Item("UserID").ToString & "'"
limit 1

or this (in SQL Server/Sybase):
select top 1 1
from tblTable
where UserID= '" & Session.Item("UserID").ToString & "'"
limit 1;


text:
Q: MongoDB suddenly missing / data not found Our MongoDB database in Digital Ocean suddenly went missing. When I run mongod, it says:
MongoDB starting : pid=27161 port=27017 dbpath=/data/db 64-bit host=unifyhub-db
2017-01-07T17:36:06.617+0800 I CONTROL  [initandlisten] db version v3.0.11
2017-01-07T17:36:06.617+0800 I CONTROL  [initandlisten] git version: 48f8b49dc30cc2485c6c1f3db31b723258fcbf39
2017-01-07T17:36:06.617+0800 I CONTROL  [initandlisten] build info: Linux ip-10-65-215-98 3.13.0-24-generic #46-Ubuntu SMP Thu Apr 10 19:11:08 UTC 2014 x86_64 BOOST_LIB_VERSION=1_49
2017-01-07T17:36:06.617+0800 I CONTROL  [initandlisten] allocator: tcmalloc
2017-01-07T17:36:06.617+0800 I CONTROL  [initandlisten] options: {}
2017-01-07T17:36:06.676+0800 E NETWORK  [initandlisten] listen(): bind() failed errno:98 Address already in use for socket: 0.0.0.0:27017
2017-01-07T17:36:06.677+0800 E NETWORK  [initandlisten]   addr already in use
2017-01-07T17:36:06.677+0800 I STORAGE  [initandlisten] exception in initAndListen: 29 Data directory /data/db not found., terminating
2017-01-07T17:36:06.677+0800 I CONTROL  [initandlisten] dbexit:  rc: 100

Do you have any idea what happen here? We actually didn't do anything, we just found out that the whole application was not working because the database can't be found.

A: I think you were hijacked!
according to http://thehackernews.com/2017/01/secure-mongodb-database.html and http://securityaffairs.co/wordpress/55018/cyber-crime/mongodb-hacked.html there is a hacker targeting the opened MongoDB databases, and asks for ransom to return your data back.
I faced the exact same problem as yours. I thought it is something related to digital-ocean but after reading those posts, I checked my server and it is confirmed that it was hijacked.
I opened a mongo shell
mongo;

listed the databases
show dbs;

found a database called READ1 I checked it and found a collection with only one record, a message from the hijacker
use READ1;
show collections; // found a collection called info
db.info.find()

found this document:

{ "_id" : ObjectId("5877674456ae6684507ac017"), "mail" :
  "ha******@si*****.org", "text" : "SEND 0.1 BTC TO THIS ADDRESS *****
  AND CONTACT THIS EMAIL WITH IP OF YOUR SERVER TO RECOVER YOUR DATABASE
  !" }

unfortunately, I didn't check the server since a while and I only keep the last five backups, so I lost my data. But luckily we are still in development mode and we don't have sensitive data.
anyway, I found my Mongodb version (2.4.10 Tokumx distribution) allows remote access by default. I tried the following from my local machine and it is surprisingly connected!!
mongo server-ip:27017/database-name

Finally, I made the following steps to disable the remote access
ps aux | grep mongo //found path of the configuration file (/etc/tokumx.conf)

then as described here, I used vim to append the line bind_ip = 127.0.0.1 to the configuration files
then restarted my tokumx service (mongodb in your case)
sudo service tokumx restart

Now remote access is disabled.

A: Make sure your config file is loaded by explicitly calling it when running mongod:
mongod --config /etc/mongod.conf

And in your /etc/mongod.conf file make sure you have
bindIp: 127.0.0.1

Now after restarting with this config file, like Ahmed ElBayaa says (I could not comment because of low reputation), try from a remote machine to connect using:
mongo server-ip:27017/

If all is configured correctly this connection should be refused!


text:
Q: SBT won't resolve fakehttpserver dependency because of bad commons pom file I'm trying to use this fake http server project in a sbt 0.11.0 based project.  Unfortunately one of it's dependencies is giving the following error:
[error]     public: bad organisation found in http://repo1.maven.org/maven2/org/apache/commons/commons-io/1.3.2/commons-io-1.3.2.pom: expected='org.apache.commons' found='commons-io'
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.apache.commons#commons-io;1.3.2: java.text.ParseException: inconsistent module descriptor file found in 'http://repo1.maven.org/maven2/org/apache/commons/commons-io/1.3.2/commons-io-1.3.2.pom': bad organisation: expected='org.apache.commons' found='commons-io';
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[error] {file:/home/project_location/}default-db401d/*:update: sbt.ResolveException: unresolved dependency: org.apache.commons#commons-io;1.3.2: java.text.ParseException: inconsistent module descriptor file found in 'http://repo1.maven.org/maven2/org/apache/commons/commons-io/1.3.2/commons-io-1.3.2.pom': bad organisation: expected='org.apache.commons' found='commons-io';

From what I can tell this can be worked around by asking that ivy not check the consistency of the pom files (Maven has this setting off by default).  I can't work out how to turn this off in sbt though.  I tried
ivyValidate := false

but this has no effect.
Am I on the right track with this setting and is it possible to turn this setting off?

A: You could try to exclude this dependency and include it manually :
"se.dannej" % "fakehttpserver" % "0.1.0" exclude("org.apache.commons", "commons-io")

"commons-io" % "commons-io" % "another version"

or even download the commons-io jar and push it in your lib directory.


text:
Q: css customize scrollbar size and position I am trying to create a scrollbar slightly shifted within my component and slightly smaller. Here is what it would look like:

But I want it to get the entire component scrolled, not just a small part of it which would start at the scrollbar start and end at its end.
Here is what I did:
.box::-webkit-scrollbar {
    width      : 16px;
    margin-right: 100px;
}

.box::-webkit-scrollbar-track {
    background-color: #2A2A2A;
    border-radius   : 8px;
}

.box::-webkit-scrollbar-thumb {
    background-color: #4B4B4B;
    border-radius   : 8px;
}

Unfortunately the margin doesn't seem to work:

A: scroll bars will always be placed at the borders of the container div
to get around this make a new div and put some padding around it like so

(your HTML)

the padding on the parent div will push the scroll bar

A: you can give padding to the outermost div you created.


text:
Q: What is the color of viral particles? I read today on twitter that because COVID-19 particle is very small (<100nm) and visible light wavelength is larger (>250nm) the virus has no "colour".
I know that some molecular bonds vibrate at deep IR frequencies, and some amino acids are fluorescent
But if we have a crystal of or a droplet with viral particles, will there be visible color? What defines that color?


text:
Q: Does ubuntu store tty settings? Here is the story:
From a fresh install of ubuntu I use a serial to usb device. screen /dev/ttyUSB0 everything goes fine and I can interact with the device perfectly.
Then I unplug this device, plug another one (a 3g modem). Again screen /dev/ttyUSB0 and everything is fine.
But then, I plug again the first device and do the screen /dev/ttyUSB0 and everything got scrambled !
I am supposing that for whatever reason the tty parameters changed. Is there a way that ubuntu (or screen) store it somewhere ?
How can I get back to the initial settings ?
So far I tried:

*

*rebooting

*stty sane

A: Found it.
Two screen instance were actually reading /dev/ttyUSB0
Removing them all solved the issue.
Now, I am looking for solution to prevent me to do this mistake again:
https://serverfault.com/questions/811474/how-to-prevent-screen-to-open-the-same-serial-device-twice


text:
Q: Hibernate: failed to lazily initialize a collection of role, no session or session was closed My code:
    @Test
public void testAddRoleAndAddUser() {

    Role r = roleDao.findByProperty("name", "admin");
    if(r == null) {
        r = new Role();
        r.setName("admin");
        r.setDescription("Just administrator.");
        roleDao.save(r);
    }

    User u = dao.get(1l);
    Set<Role> roles = u.getRoleSet();
    logger.debug("Roles is null: " + (roles == null));
    roles.add(r);
    dao.save(u);
}

13:39:41,041 ERROR:
  org.hibernate.LazyInitializationException
    failed to lazily initialize a
  collection of role:
  xxx.entity.core.User.roleSet, no
  session or session was closed
  org.hibernate.LazyInitializationException:
  failed to lazily initialize a
  collection of role:
  xxx.entity.core.User.roleSet, no
  session or session was closed     at
  org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:380)
    at
  org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:372)
    at
  org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:365)
    at
  org.hibernate.collection.PersistentSet.add(PersistentSet.java:212)
    at
  sg.com.junglemedia.test.dao.impl.hibernate.UserDaoTest.testAddRoleAndAddUser(UserDaoTest.java:40)
    at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native
  Method)   at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at
  java.lang.reflect.Method.invoke(Method.java:597)
    at
  org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at
  org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at
  org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at
  org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at
  org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at
  org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
    at
  org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at
  org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at
  org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at
  org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at
  org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at
  org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at
  org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at
  org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
    at
  org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

Anyone help?

A: You're most likely closing the session inside of the RoleDao. If you close the session then try to access a field on an object that was lazy-loaded, you will get this exception. You should probably open and close the session/transaction in your test.

A: I was experiencing the same issue so just added the @Transactional annotation from where I was calling the DAO method. It just works. I think the problem was Hibernate doesn't allow to retrieve sub-objects from the database unless specifically all the required objects at the time of calling.

A: In your entity class, when you declare mapping from user to roles, try specifying the fetchType to EAGER. Some thing like this:
@OneToMany(fetch=FetchType.EAGER)
public Collection<Role> getRoleSet(){
 ...
}

UPDATE:
Recent comments this answer's received make me revisit this. It's been a while since I answered, when I only started working with Hibernate. What Rafael and Mukus say are reasonable. If you have a large collection, you shouldn't use eager fetching. It jointly selects all data mapped to your entry and loads to memory. An alternative to this is to still use lazy fetching and open a Hibernate session each time you need to work on the related collection, i.e, each time you need to invoke getRoleSet method. This way, Hibernate will execute the select query to database each time this method is invoked and doesn't keep the collection data in memory. You can refer to my post here for details: http://khuevu.github.io/2013/01/20/understand-hibernate.html
That's said, it can depend on your actual use case. If your collection data is small and you frequently need to query the data, you will better off using eager fetching. I think, in your specific case, a collection of role is probably quite small and suitable to use eager fetching.

A: The following code can cause similar error:
  using (var session = SessionFactory.OpenSession())
  using (var tx = session.BeginTransaction())
  {
      movie = session.Get<Movie>(movieId);
      tx.Commit();
  }
  Assert.That(movie.Actors.Count == 1);

You can fix it simply:
  using (var session = SessionFactory.OpenSession())
  using (var tx = session.BeginTransaction())
  {
      movie = session.Get<Movie>(movieId);
      Assert.That(movie.Actors.Count == 1);
      tx.Commit();
  }

A: for me it worked the approach that I used in eclipselink as well. Just call the size() of the collection that should be loaded before using it as parameter to pages.
for (Entity e : entityListKeeper.getEntityList()) {
    e.getListLazyLoadedEntity().size();
}

Here entityListKeeper has List of Entity that has list of LazyLoadedEntity.
If you have just therelation Entity has list of LazyLoadedEntity then the solution is:
getListLazyLoadedEntity().size();

A: In my case the Exception occurred because I had removed the
"hibernate.enable_lazy_load_no_trans=true" in the "hibernate.properties" file...
I had made a copy and paste typo...

A: You can try to add @Transactional annotation to your bean or method (if declaration of all variables places in method).

A: You have different choices to handle this. It seem like its taking us back to old good plain SQL days :)
Read this: http://www.javacodegeeks.com/2012/07/four-solutions-to-lazyinitializationexc_05.html

A: I've had this issue especially when entities are mashalled by Jaxb + Jax-rs.  I've used the pre-fetch strategy, but I have also found it effective to provide two entities:

*

*Full-blown entity with all collections mapped as EAGER

*Simplified entity with most or all collections trimmed out

Common fields and be mapped in @MappedSuperclass and extended by both entity implementations.
Certainly if you always need the collections loaded, then there is no reason to not to EAGER load them.  In my case I wanted a stripped down version of the entity to display in a grid.

A: The best way to resolve this issue is to use a try-catch block in the Service layer around the area where there is an error while fetching the property and then just reload the entity:
IBaseEntityDAO<IYourEntity> dao = ApplicationConfig.getDAOFactory().getDAO(IYourEntity.class);

dao.refresh(yourentityvariable);

A: Your trying to load the lazy loaded collection, but the hibernate session is closed or unavailable.
the best solution for this problem, change the lazy loaded object to eager fetch = FetchType.EAGER loading. this problem will solve.


text:
Q: Looking for a alert on multi time frame alert when RSI14 is crosing 60 on 30min chart, if RSI14 is above 60 on 1hr chart & if RSI14 is above 60 on 1day chart,
basically to find a confirm bullish trend, please help me to achive this.

A: Here you go my dude, try to figure out on your own next time but thought I'd help you out. Pretty simple actually, I also made it so you can adjust the lengths of each RSI individually. Read through it so you can understand how it works. I'm a beginner myself but this should work as intended.
//@version=4
study("MTF RSI", overlay=false)

//custom input for rsi lengths and timeframes
rsilen=input(14, minval=1, title="1st RSI Length", type=input.integer)
rsilen2=input(14, minval=1, title="2nd RSI Length", type=input.integer)
rsilen3=input(14, minval=1, title="3rd RSI Length", type=input.integer)
rsires=input("30", title="1st RSI Timeframe", type=input.resolution)
rsires2=input("60", title="2nd RSI Timeframe", type=input.resolution)
rsires3=input("1D", title="3rd RSI Timeframe", type=input.resolution)

//variables for each rsi
RSI1=rsi(close, rsilen)
RSI2=rsi(close, rsilen2)
RSI3=rsi(close, rsilen3)

//different timeframes for rsi
rsi1=security(syminfo.tickerid, rsires, RSI1)
rsi2=security(syminfo.tickerid, rsires2, RSI2)
rsi3=security(syminfo.tickerid, rsires3, RSI3)

//plots all 3 RSIs
plot(rsi1, title="1st RSI", color=color.red)
plot(rsi2, title="2nd RSI", color=color.green)
plot(rsi3, title="3rd RSI", color=color.blue)

//alert condition
alertcondition(rsi1 > 60 and rsi2 > 60 and rsi3 > 60, title="3 RSI Bullish", message="All 3 RSIs Bullish")


text:
Q: VisualVM and YourKit report different retained sizes for the same object I'm using JVisualVM and YourKit to analyze a heap memory dump (created using jmap) and noticed that for the same object they report two very different retained sizes! Does anybody know what the cause could be?

A: Sure, the obvious cause for this difference is a bug in VisualVM or YourKit. Can you try VisualVM 1.3.3 from http://visualvm.java.net ? If can you send me (privately) the link to your heap dump, I can investigate VisualVM part.


text:
Q: Offline furigana for iOS Is there any software to compute and display furigana completely offline?
It doesn't have to be integrated with any existing app.  A new standalone app I type into is fine.

A: You have several apps available on the App store now - just search for Furigana.
I have a friend that likes this one, but YMMV:

*

*Furigana Reader - https://itunes.apple.com/us/app/furigana-reader/id529433422?mt=8
It does not work offline, so it doesn't meet your requirements unless you fail to find any offline software and can relax that constraint.

A: I'm a little confused here. You want an app that you can type kanji into and get the kana in return. But the only way to type kanji into the iPhone is by typing it phonetically, which gives you the kana for free, essentially.
There are a number of self-contained Japanese dictionary apps for the iPhone. Most of them use the EDICT dictionary. I've got one that can import EPWING-formatted dictionaries, and have imported Kenkyusha's New Japanese-English Dictionary into it.
This seems like the closest to what you want. I think. I get the impression that it has the dictionaries built-in, but I could be wrong.


text:
Q: how to change animation speed in turn.js? I have a project which is e-catalog. I have used turn.js library for it. It was a great library and i would like to change something like the animation speed when turning into pages. But there is no option, properties or method built in turn.js to modify it. anyone can help? or at least tell what part of the code it is located to change the speed? Thanks.

A: you can set the animation duration when initializing the book.
here's the doc : http://www.turnjs.com/docs/Option:_duration
and how to use it :
book.turn({ // init
    width: 800,
    height: 600,
    duration : 1300
});


text:
Q: Doctrine composite primary key as part of the primary key of another entity I have specific situation where composite primary key of one entity is part of the primary key of another entity. This is case of specialization, but it doesn't matter now.
I use Doctrine to generate entities from database, but Doctrine doesn't support composite foreign key as primary key:
It is not possible to map entity 'XXXXX' with a composite primary key as part of the primary key of another entity 'YYYYYY#id_xxxxx'

Does anyone know solution for this situation? It can be Doctrine solution or editing model and database structure.
UPDATE 1
CREATE TABLE `amandman` (
  `iddokumenta` int(11) NOT NULL,
  `datumdostavljanjaskupstini` date NOT NULL,
  `tekst` text,
  `datumizmene` date DEFAULT NULL,
  `izmenjenitekst` text,
  `iddokumentapredlogazakona` int(11) DEFAULT NULL,
  `datumdostavljanjaskupstinipredlogazakona` date DEFAULT NULL,
  PRIMARY KEY (`iddokumenta`,`datumdostavljanjaskupstini`),
  KEY `iddokumentapredlogazakona_idx`           (`iddokumentapredlogazakona`,`datumdostavljanjaskupstinipredlogazakona`),
  CONSTRAINT `iddokumenta45` FOREIGN KEY (`iddokumenta`, `datumdostavljanjaskupstini`)     REFERENCES `dokument` (`iddokument`, `datumdostavljanjaskupstini`) ON DELETE NO ACTION ON     UPDATE CASCADE,
 CONSTRAINT `iddokumentapredlogazakona` FOREIGN KEY (`iddokumentapredlogazakona`, `datumdostavljanjaskupstinipredlogazakona`) REFERENCES `predlogzakona` (`iddokumenta`, `datumdostavljanjaskupstini`) ON DELETE NO ACTION ON UPDATE CASCADE)
ENGINE=InnoDB DEFAULT CHARSET=utf8;

This is one of entities from database that can't be generated by Doctrine.

A: You are running into this problem because your composite foreign key is another table's composite primary key. This is not a good development practice, which is why it is simply not supported by Doctrine, and I strongly doubt that it ever will be.
Solution 1 (preferred):
Add a single, auto-increment primary key to EstablecimientosSec. You can then link to that EstablecimientosSec.id instead.
Solution 2:
If changing the database structure is absolutely not possible, do not map the relationship. Instead, you can fetch the related EstablecimientosSec entities in a separate query using the composite primary key. It's not a prefect solution, but it works under these constraints. Tip: avoid querying the related objects as part of a loop.

A: The foreign key ever is a primary key in other table and why it's not a good practice?.
The solution is remove the foreign key relation from the database, after add it manually. Well if you are using cascade update or similar it's necesary or you can control the update/delete with code and not with relation of tables


text:
Q: Computing distance from a point to a triangulation in 3D with Matlab I have a 3D point cloud that I've transformed into a Delaunay triangulation using Matlab's function DelaunayTri. Now I have a test point in 3D and want to compute, in Matlab, the smallest distance between this point and the triangulation.
So far, I've thought of using the nearestNeighbor(...) member function of the DelaunayTri class in Matlab to find the point in the triangulation closest to my test point and then computing the distance between them. That is something but it is not what I really want.
The closest point on the triangulation to my test point is, in general, not a vertex of the triangulation but somewhere on the face of a triangle. How can I find this point?
Thank you!!!

A: I've written codes for these things, but they are not on the File Exchange. I can be convinced to give them out by direct mail though.
It is relatively easy to find the distance to a convex hull, but not trivial. A delaunay tessellation is bounded by the convex hull anyway. So you can convert that tessellation into the convex hull easily enough, or just use the convex hull. Note that a convex hull is often a terribly poor approximation for many purposes, especially if you are using this for color mapping, which is perhaps the most common thing I see this used for. In that case, an alpha shape is a far better choice. Alpha shapes also will have a triangulated boundary surface, though in general it will not be convex.
So, to find the nearest point on a convex triangulation:

*

*Convert to the convex boundary surface, i.e., the convex hull. This reduces to finding those triangles which are not shared between pairs of tetrahedra. Internal facets will always appear exactly twice in the list of all facets. This trick also works for non-convex tessellations of course, so for alpha shapes.

*Compute a bounding circumcircle for each triangular surface facet. This allows you to know when to stop checking facets.

*Get the distances to each point on the surface. Sort each facet by the distance to the nearest point in that facet. Start by looking at the nearest facet in that list.

*Compute the distance to the apparently nearest facet found in step 3. A simple solution is found by least distance programming (LDP), which can be converted to a constrained linear least squares. Lawson & Hanson have an algorithm for this.
Repeat step 4 until the current best distance found is less than the distance, comparing it to any of the circumcircles from step 2. This loop will be quite short really, at least for a convex hull. For a more general non-convex hull from an alpha shape, it may take more time.
You can also reduce the search space a bit by excluding the facets from your search that point AWAY from the point in question. Use those facet normals for this test.

A: I wrote the tool point2trimesh for this problem. It's kind of a "brute force" solution which works also for non-convex surfaces.


text:
Q: JAVAFX: Loading the image from the database I need some help regarding image loading from database. How do I retrieve the image from the database and put it in an Image/ImageView?
Thank you very much!

A: import java.nio.ByteBuffer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.PixelFormat;
import javafx.scene.image.PixelWriter;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class ImageOpsTest extends Application {

    // Image Data
    private static final int IMAGE_WIDTH = 10;
    private static final int IMAGE_HEIGHT = 10;
    private byte imageData[] =
        new byte[IMAGE_WIDTH * IMAGE_HEIGHT * 3];

    // Drawing Surface (Canvas)
    private GraphicsContext gc;
    private Canvas canvas;
    private Group root;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("PixelWriter Test");
        root = new Group();
        canvas = new Canvas(200, 200);
        canvas.setTranslateX(100);
        canvas.setTranslateY(100);
        gc = canvas.getGraphicsContext2D();
        createImageData();
        drawImageData();
        primaryStage.setScene(new Scene(root, 400, 400));
        primaryStage.show();

    }

    private void createImageData() {
        int i = 0;
        for (int y = 0; y < IMAGE_HEIGHT; y++) {
            int r = y * 255 / IMAGE_HEIGHT;
            for (int x = 0; x < IMAGE_WIDTH; x++) {
                int g = x * 255 / IMAGE_WIDTH;
                imageData[i] = (byte) r;
                imageData[i + 1] = (byte) g;
                i += 3;
            }
        }
    }

    private void drawImageData() {
        boolean on = true;
        PixelWriter pixelWriter = gc.getPixelWriter();
        PixelFormat<ByteBuffer> pixelFormat = PixelFormat.getByteRgbInstance();
        for (int y = 50; y < 150; y += IMAGE_HEIGHT) {
            for (int x = 50; x < 150; x += IMAGE_WIDTH) {
                if (on) {
                    pixelWriter.setPixels(x, y, IMAGE_WIDTH,
                            IMAGE_HEIGHT, pixelFormat, imageData,
                            0, IMAGE_WIDTH * 3);
                }
                on = !on;
            }
            on = !on;
        }

        // Add drop shadow effect
        gc.applyEffect(new DropShadow(20, 20, 20, Color.GRAY));
        root.getChildren().add(canvas);
    }
}

This example taken from the docs demonstrates how you can create an image out of byte[]. When you store image into the database, you get them back as byte[].
Now, how you retrieve the image from the database is completely up to you but once you retrieve it, you can use the program above to convert it into an image.


text:
Q: Prove that following recursively defined sequence converges and its limit is 1/2
\begin{cases}a_1 = 1\\ \\ \displaystyle a_{1+n} = \sqrt{\sum_{i=1}^n a_i}\end{cases}
Prove that $\{\frac{a_n}{n}\}$ is convergent and its limit is $\frac12$

My proof:   We can recursively define relation between $a_{1+n}$ & $a_n$ as
$a_{1+n} = \sqrt{a_n^2+a_n}$
Also, it is evident that $a_{1+n} > a_n > 1$
Thus, $a_{n}^2 - a_{n-1}^2 + a_{n} - a_{n-1} = a_{n} > 1 > 1/4$
Thus,  $a_{n+1} = \sqrt{a_{n}^2  + a_{n}} > \sqrt{a_{n-1}^2+a_{n-1}+1/4} = a_{n-1} + 1/2  $
Similarly, we can show $a_{n+1} = \sqrt{a_{n}^2  + a_n} < a_n + 1/2$
So, we have  $a_1 + \frac{n-1}2 < a_{n+1} < a_1 + \frac{n+1}2$
Using Sandwich Theorem we got limit of $\frac{a_n}n$ as $\frac12$
Is my proof correct.
I will be grateful if you can provide alternative proofs

A: As pointed out in question, the sequence satisfy the recurrence relation $a_{n+1} = \sqrt{a_n^2 + a_n}$.
From this, it is easy to see $a_n$ is strictly increasing and positive.
One consequence of this is $a_n$ cannot be bounded.
Assume the contrary, then $a_n$ converges to some finite value $M > 0$. Since the map $x \mapsto \sqrt{x(x+1)}$ is continuous, the "limit" $M$ will then satisfy $M = \sqrt{M^2 + M} > M$ which is absurd.
Another consequence is
$$a_n < a_{n+1} < \sqrt{a_n^2 + a_n + \frac14} = a_n + \frac12
\quad\implies\quad 1 < \frac{a_{n+1}}{a_n} < 1 + \frac1{2a_n}$$
Since $a_n$ is unbounded, this leads to
$\displaystyle\;\lim_{n\to\infty}\frac{a_{n+1}}{a_n} = 1$ and hence
$$\lim_{n\to\infty} \frac{a_{n+1}-a_{n}}{(n+1)-n} =
\lim_{n\to\infty}\frac{a_{n+1}^2-a_n^2}{a_{n+1}+a_n}
= \lim_{n\to\infty}\frac{a_n}{a_n + a_{n+1}}
= \lim_{n\to\infty}\frac{1}{1 + \frac{a_{n+1}}{a_n}}
= \frac{1}{1+1} = \frac12$$
By Stolz-Cesàro, we can conclude
$$\lim_{n\to\infty} \frac{a_n}{n} \quad\text{exists and equals to}\quad \lim_{n\to\infty}\frac{a_{n+1}-a_n}{(n+1)-n} = \frac12$$

A: Try showing via induction that $(a_n)_{n \in \mathbb{N}}$ is monotone and bounded and the solve the fixed point equation (aka $\lim\limits_{n \to \infty} a_n = \lim\limits_{n \to \infty} a_{n+1}$).

A: You have shown that $a_{n+1}-a_{n-1} \gt \frac 12$  but that is a step of $2$ in the index.  You therefore can only conclude that $a_{n+1} \gt a_1+\frac n4$ and the squeeze fails.


text:
Q: Deploying Django 1.5 app on GAE SDK 1.8.1 I have been trying to deploy my application on GAE for 2 days, but I have not been successful.
    I am using Python 2.7, Django 1.5 and Google App Engine SDK 1.8.1 and the application is running appropriately is localhost.
    To deploy my application, I have followed the instructions at [1] with just one difference: I have changed the
    ROOT_URLCONF = 'tcn_project.urls' to ROOT_URLCONF = 'urls' (where tcn_project is the name of my project).
    The current error is (where cc_simulator is the name of my application):
File "/base/data/home/apps/s~cc-simulator/1.368666896883800783/urls.py", line 2, in <module>
from cc_simulator import views
ImportError: No module named cc_simulator


text:
Q: Decomposition and Normalization How would I prove the following: If the normalization of $X$ can be covered by $G$-invariant quasiprojective open subsets, then the spectral sequence $$E_{2}^{pq} = H^{p}(BG, IH^{q}(X)) \Rightarrow IH_{G}^{p+q}(X)$$ converging to $IH^{*}(E_{n}G \times _X{G})$ degenerates at the $E_2$ term.
This is because of decomposition?


text:
Q: Скрипт не срабатывает и выдает ошибку на простом while и if...elif country = input('Выберите Техас, Ирландия или Норвегия')
while country != 'Ирландия' or 'Норвегия' or 'Техас':
    country = input('Выберите Техас, Ирландия или Норвегия')
if country == 'Ирландия':
    print('Ирландия это круто!')
elif country == 'Норвегия':
    print('Норвегия это круто!')
elif country == 'Техас':
    print('Техас это круто!')

A: Вы неправильно понимаете построение логических выражений с помощью or.
while country != 'Ирландия' or 'Норвегия' or 'Техас':

Очевидно, вы ожидаете, что конструкция после while будет True, если country не равно ни одному слову из трёх перечисленных.
Однако, != принимает после себя только один аргумент. И с помощью or действие этого оператора нельзя расширить. Чтобы проверять равенство переменной одному из нескольких значений, используйте in
while country not in ['Ирландия', 'Норвегия', 'Техас']:

A: У вас как я понимаю
SyntaxError: Non-ASCII character '\xd0' in file t.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
попробуйте, для начала, в начало кода вставить:
#! /usr/bin/env python
# -*- coding: utf-8 -*-


text:
Q: Interpreting ANOVA results in the educational context I have run an experiment in a six-week course to measure the effect of my educational treatment on student engagement.  The treatment happens on weeks 4 and 6 of the course (for all of the students) and week 5 is meant to be the control (for all of the students). The line chart with error bar is as follows:

And here is the boxplot:

I have run an ANOVA and the results turned out to be this:
data:  count and as.factor(week)
F = 5.7806, num df = 2.00, denom df = 129.44, p-value = 0.003939

Which means that at least two of the weeks have different engagement levels.
I have also done a post-hoc analysis which revealed that the engagement in weeks 5 and 6 are significantly different.
Tukey Test
Tukey multiple comparisons of means
    95% family-wise confidence level
    factor levels have been ordered

Fit: aov(formula = count ~ as.factor(week), data = .)

$`as.factor(week)`
                   diff        lwr      upr     p adj
week 4-week 5  9.334825 -5.8595239 24.52917 0.3171024
week 6-week 5 24.000000  8.7502979 39.24970 0.0007633
week 6-week 4 14.665175 -0.5291744 29.85952 0.0610931

and Bonferroni Test
       week 4  week 5
week 5 0.44534 -
week 6 0.07116 0.00079

P value adjustment method: bonferroni

My question is: How can I make sure that the higher engagement in week 6 is due to my treatment rather than a natural increase in engagement in the last week of the course?


text:
Q: How can we know the user logging in through linkedin profile is an employee or an employer? i am using linkedin API. it's my first time with any API.
I want to know that how can we know that the user logging in through his/her linkedin account is an employee or an employer.
I am getting the information through
$profile = $this->linkedin->profile('~:(id,first-name,last-name,email-address,headline,picture-url,location,skills,summary,main-address,projects)');

There is also a method like this:
$this->linkedin->company('1337:(id,name,ticker,description,logo-url,locations:(address,is-headquarters))');

I am confused how can I perform this task... Any kind of help will be very much appreciative. Thanks.


text:
Q: Bootstrap 3 Customized li item div styling I am new in Bootstrap 3.
I am trying to create a customized list in Bootstrap 3.
What I have done is-
HTML-

                1

                2

                    name

                        31

                        32

                        33

                    XXXX

                4

                5

Music

Videos

CSS-
div.inline
{
    float:left;
    overflow: auto;
}

li.list-group-item
{
    min-height: 100px;
    vertical-align : center;
}

And getting a list like this-

But I want to have the inner items vertically aligned.
So I want to have a output like it-

Can anyone help me please?
Thanks in advance for helping.

A: This lends itself to using a sub-menu rather than divs. See -

* {
  margin: 0;
  padding: 0;
}
li {
  list-style: none;
}
li.list-group-item {
  min-height: 100px;
  vertical-align: center;
}
.sub li {
  display: inline-block;
  vertical-align: middle;
  text-align: center;
  width: 10%;
}

1

2

name

31

XXXX

32

33

4

5

Music

Videos

A: Use the grid system, probably worth noting however that this will only work with up to 12 records.

            Name

           1

           2

           3

           4

           5

           6

           7

            xxxx

produces:

A: if you want to use "vertical-align", you should add "display: table-cell" to the .list-group-item class


text:
Q: In R how can I exclude rows based on multiple conditions and a range of values I am trying to use dpylr filter function in R to remove rows based on certain conditions. Here is sample data.
df = data.frame(chr = c(1,1,1,2,2,3,3),
                pos = c(10,15,20,10,14,2,15)

I need to exclude a range of values in a specific region so I thought something like this would work.
library(dpylr)
filter(df, chr == "1" & !pos %in% (1:15)

However my output only give me:
chr pos
1   20

I lose all other rows like data from chr 2 and 3.
My desired output looks like this:
chr   pos
1      20
2      10
2      14
3      2
3      15

How can I get an output where my exclusion criteria only effects a selected value like (i.e. chr == 1), but still retains data from other chr and chr 1 that are not included in my range.

A: Your code is almost correct, you need to apply the ! operator to the whole condition:
Code
df %>%
  filter(!(chr == 1 & pos %in% (1:15)))

Output
  chr pos
1   1  20
2   2  10
3   2  14
4   3   2
5   3  15


text:
Q: Definition of Lebesgue integral in Reed and Simon.
In the book "methods of modern mathematical physics I functional analysis" by Reed and Simon, the Lebesgue integral is defined as
\begin{align}
\int f(x)dx=\lim_{n\to\infty} \sum_{2^n}(f)
\end{align}
where
\begin{align}
\sum_{n}(f):=\sum_{m=0}^{\infty}\frac{m}{n} \mu(f^{-1}([\frac{m}{n},\frac{m+1}{n}))
\end{align}
With this definition, I cannot calculate the Lebesgue integral of the function $f(x)=x$ in the interval $[0,1]$:
$(f^{-1}([\frac{m}{n},\frac{m+1}{n}))=\left\{x: \frac{m}{n}\leq f(x)=x\leq \frac{m+1}{n})\right\}$, then $\mu(f^{-1}([\frac{m}{n},\frac{m+1}{n}))=\frac{1}{n}$. Therefore, $\sum_{2^n}(f)=\sum_{m=0}^{\infty} \frac{m}{2^n} \frac{1}{2^n}$ and this series with $n\to\infty$ is not worth 1/2. What am I misunderstanding?


text:
Q: Swift In-Out Parameters - use case I recently learn about "In-Out Parameters" in Swift and I have question to you.
What are use case when "In-Out Parameters" is better than e.x. func that return value that you can assign to var?
Thank you for help.

A: I think a good use case for inout parameters is the swapTwoInts function provided by The Swift Programming Language.
func swapTwoInts(inout a: Int, inout b: Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

Given
var a = 0
var b = 1

you can easily call
swapTwoInt(&a, b: &b)

Scenario 2: without inout params
On the other hand, without inout parameters the function should be written as follow (more compact actually)
func swapTwoInt(a: Int, b: Int) -> (a:Int, b:Int) {
    return (a:b, b:a)
}

but the use would require 3 lines of code instead of 1:
let swapped = swapTwoInt(a, b: b)
a = swapped.a // was swapped.b, fixed as suggested by Martin R
b = swapped.b

Considerations
As you can see, in Scenario 2 part of the logic of the function needs to be written outside of the function itself. This is not good because it creates an overhead of code to be written each time the function is called.


text:
Q: How do I conditionally veto a delete attempt in Django Admin 1.5? The docs clearly state that ModelAdmin.delete_model() must delete the object and that it's not for veto purposes.  Trouble is, they don't give any hint how you would implement a veto should you need to.
Here's some background, because maybe there's an entirely better way to go about what I'm trying to accomplish.  I'm capturing iptables rules in a Django 1.5 app and wish to use the Admin pages to handle all the maintenance.  I have two models relevant to the issue at hand: Chain and Target.  Here's the crux of those models:
class Chain(models.Model):
    """A netfilter chain."""
    name = models.CharField(max_length=30, unique=True, primary_key=True)
    built_in = models.BooleanField(
        default=False,
        help_text=u'This option should be selected if this chain is one of '
                  u'those provided by netfilter.  Leaving this option '
                  u'unselected indicates that the chain is user-defined.'
    )
    table = models.ForeignKey(Table, verbose_name='netfilter table')

class Target(models.Model):
    """A netfilter target."""
    name = models.CharField(
        max_length=30, unique=True, primary_key=True,
        help_text=u'This may be either an iptables built-in target or a '
                  u'user-defined chain.  Built-in targets must be one of '
                  u'those supported by iptables.'
    )
    built_in = models.BooleanField(
        default=False, verbose_name='built-in',
        help_text=u'This option should be selected if this target is one of '
                  u'those provided by netfilter.  Leaving this option '
                  u'unselected indicates that the target is user-defined.',
    )

Thus the Chain table will have records for 'FORWARD', 'INPUT' and 'OUTPUT', all built-in and linked to the 'filter' table.  Of course the admin may enter other user-defined chains here too, but would set those with built_in == False.
It gets weird with the Targets though.  They can either reference a Chain (hey, a ForeignKey would be great here!) or a built-in Target (e.g., 'ACCEPT' or 'DROP') that I'd rather not expose as a Chain (hey, a ForeignKey won't be so hot here!).
Now the dilemma.  The Admin UI is a wee bit clunky for linking a Target to a user-defined Chain because it's not defined as a FK so I settle for a regular character input field and a clean_name() can handle the validation to ensure the Target's Chain exists.  I'm stuck on how to prevent deletion of Chains that are referenced by a Target.

A: You should be able to accomplish this by overriding has_delete_permission(request, obj) in your Chain admin. You can check obj to see if any Targets are referencing it. See the docs.
This won't prevent deletion via the Delete selected action in the change list view, though. You can fix that by overriding the built-in delete_selected action with your own that refuses to do the delete if any of the items shouldn't be deleted. See the Admin action docs.


text:
Q: Decode hex string in java As I'm trying to convert below hex to java string.
As this is UTF8 Characters.
ЫЙБПАРО As this string is converted into hexadecimal 42b41941141f41042041e value.
I tried to convert string to hex by using below javascript code
function encode(string) {
     var str= "";
        var length = string.length;
        for (var i = 0; i < length; i++){
            str+= string.charCodeAt(i).toString(16);
            }
        return str;
}

I need to decode in java code what would be the way.
Tried below answers
mkyong.com/java/how-to-convert-hex-to-ascii-in-java
stackoverflow.com/questions/140131
Convert a string representation of a hex dump to a byte array using Java?

A: You can try Apache Codec.
byte[] b= Hex.decodeHex(yourhexdecimalstring.toCharArray());
System.out.println(new String(b, "UTF8"));

A: Let's start with the first character: this is #1067 in the Unicode table.
This means 4 x 256 + 43. So the hex-representation of this is 04 and 2B (or vice versa depending on the byte order). Yours seems to be 42 b4. So I assume the encoding is not correct.
I'm not familiar with jscript but this code...
private void jscript() throws ScriptException {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    engine.eval("function encode(string) {\n"
            + "     var str= \"\";\n"
            + "        var length = string.length;        \n"
            + "        for (var i = 0; i < length; i++){\n"
            + "            str+= string.charCodeAt(i).toString(16);\n"
            + "            }\n"
            + "        return str;\n"
            + "}"
            + ""
            + "print(encode(\"ЫЙБПАРО\"));");
}

...returns this

42b41941141f41042041e

as you wrote. But in my opinion this is not correct


text:
Q: How to unhide Intel SSD I have bought a new Intel SSD 120GB. I wanted to use it as my operating system drive. However, I cannot find it in my computer. Even I went to Disk Management to assign new letter for it, it disappeared every time when I rebooted. I tried to use diskpart command to show my disk. It still automatically hided when I restart the computer. Is there anyone can tell me how to show it and make it as my operating system drive. Cheers.

This picture shows the disk is hidden

A: *

*Go to cmd

*type in "diskpart"

*type "list volume"

*select volume/harddrive

*choose drive by typing "select volume x" (x is an assigned number)

*type "assign"

*exit diskpart and reboot if needed


text:
Q: Renaming columns in a Pandas dataframe with duplicate column names? I have a df X with columns with duplicate names:
In [77]: X_R
Out[77]:
      dollars  dollars
   0   0.7085   0.5000

I want to rename it so that I have:
In [77]: X_R
Out[77]:
       Retail   Cost
   0   0.7085   0.5000

Using the Pandas rename function does' work:
X_R.rename(index=str, columns={"dollars": "Retail", "dollars": "Cost"})

Just gives me two columns named Cost.
How can I rename the columns in this case?

A: Not directly an answer, but since this a top search result, here is a short and flexible solution to append a suffix to duplicate column names:
# A dataframe with duplicated column names
df = pd.DataFrame([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])
df.columns = ['a', 'b', 'b']

# Columns to not rename
excluded = df.columns[~df.columns.duplicated(keep=False)]

# An incrementer
import itertools
inc = itertools.count().__next__

# A renamer
def ren(name):
    return f"{name}{inc()}" if name not in excluded else name

# Use inside rename()
df.rename(columns=ren)

    a   b   b              a  b0  b1
0   1   2   3          0   1   2   3
1   4   5   6    =>    1   4   5   6
2   7   8   8          2   7   8   9

A: MaxU's answer helped me with this same problem. In this answer, I add in a way to find those duplicated column headers.
First, we make a dictionary of the duplicated column names with values corresponding to the desired new column names. For this, the defaultdict subclass is required.
import pandas as pd
from collections import defaultdict

renamer = defaultdict()

We iterate over the duplicated column names to create a dictionary with keys being the duplicated column name and values being a list of new column names. I have chosen this list to be original name_0, original name_1, and so on.
for column_name in df.columns[df.columns.duplicated(keep=False)].tolist():
    if column_name not in renamer:
        renamer[column_name] = [column_name+'_0']
    else:
        renamer[column_name].append(column_name +'_'+str(len(renamer[column_name])))

print(renamer)
defaultdict(None, {'b': ['b_0', 'b_1', 'b_2', 'b_3'], 'c': ['c_0', 'c_1']})

Original dataframe:
print(df)
        a   b   b   b   b   c   c   d
Item 0  2   1   0   2   8   3   9   5
Item 1  3   2   7   3   5   4   6   2
Item 2  4   3   8   1   5   7   4   4
Item 3  5   5   3   6   0   5   2   5

Rename the duplicated columns by assigning the new names from our renamer defaultdict, leaving the unduplicated columns alone
df.rename(
    columns=lambda column_name: renamer[column_name].pop(0)
    if column_name in renamer
    else column_name
)
        a   b_0 b_1 b_2 b_3 c_0 c_1 d
Item 0  2   1   0   2   8   3   9   5
Item 1  3   2   7   3   5   4   6   2
Item 2  4   3   8   1   5   7   4   4
Item 3  5   5   3   6   0   5   2   5

(As a sidenote, a couple of people have questioned why duplicated column names existed in the first place. For myself, I encountered duplicated column names when importing with the xlwings package (to deal with password-protected Excel files). You could also inadvertently create duplicate column names by using pd.concat.

A: Here is a dynamic solution:
In [59]: df
Out[59]:
   a  x  x  x  z
0  6  2  7  7  8
1  6  6  3  1  1
2  6  6  7  5  6
3  8  3  6  1  8
4  5  7  5  3  0

In [60]: d
Out[60]: {'x': ['x1', 'x2', 'x3']}

In [61]: df.rename(columns=lambda c: d[c].pop(0) if c in d.keys() else c)
Out[61]:
   a  x1  x2  x3  z
0  6   2   7   7  8
1  6   6   3   1  1
2  6   6   7   5  6
3  8   3   6   1  8
4  5   7   5   3  0

A: Here is another dynamic solution that I think is nicer
In [59]: df
Out[59]:
   a  x  x  x  z
0  6  2  7  7  8
1  6  6  3  1  1
2  6  6  7  5  6
3  8  3  6  1  8
4  5  7  5  3  0
In [61]: class renamer():
             def __init__(self):
                  self.d = dict()

              def __call__(self, x):
                  if x not in self.d:
                      self.d[x] = 0
                      return x
                  else:
                      self.d[x] += 1
                      return "%s_%d" % (x, self.d[x])

          df.rename(columns=renamer())
Out[61]:
   a  x  x_1  x_2  z
0  6   2   7   7  8
1  6   6   3   1  1
2  6   6   7   5  6
3  8   3   6   1  8
4  5   7   5   3  0

A: X_R.columns = ['Retail','Cost']


text:
Q: Unable to specify legend placement I am making a plot of a map from a raster file.  I would like my legend to be inside the plot itself instead of outside by default.  I am using this code:
library(raster)
library(rgdal)
library(classInt)

NDII = raster("G:\\Sheyenne\\image_differencing\\NDII\\differenced.tif")
value.vector = round(values(NDII),2)
breaks.qt = classIntervals(value.vector, n = 3, style = "quantile", intervalClosure = "right")
breaks.qt = breaks.qt$brks
breaks.qt[2] = 0
xlim = c(616768.4, 646426)
ylim = c(5130933, 5159682)
print (plot(NDII, main="NDII", breaks=breaks.qt, col = rainbow(3), axes=F, xlim=xlim, ylim=ylim))
legend("topright")

but this returns:

A: Here is a reproducible example
Example with binary data
r <- raster(nrows = 50, ncols = 50)
set.seed(123)
id <- sample(1:2500, 100, replace = FALSE)
r[id] <- 1
plot(r)

Now with legend = FALSE and adding the legend after
plot(r, legend = FALSE, col = rev(terrain.colors(2)))
legend("topright", legend = c("Absence", "Presence"), fill = rev(terrain.colors(2)))

Example with continuous data
r <- raster(nrows=10, ncols=10)
r <- setValues(r, 1:ncell(r))

plot(r, legend = FALSE, col = rev(terrain.colors(5)))
legend("topright", fill = rev(terrain.colors(5)),  legend = c("0", "20", "40", "60", "80", "100"))


text:
Q: Python subprocess.check_output with ± characters I'm using a subprocess.check_output call to a MS DOS command line application to return the stdout string from the application.
The return from the check_ouput is information about the command just run, a new line containing the result I'm after and another new line. Specifically the return string looks like this:
b'0ms: Channel.#0.Range.SelectedItem?\r\n\xf150 mV\r\n'

The problem is the \xf1 after the first newline, that character is meant to be a ± (\xb1) but is always returned as a ñ (\xf1) and I can't work out why.
If I run the command manually in the command line I get the ± as I would expect so I don't think the command line application is at fault.
In the short term I can just replace any \xf1 I find with \xb1 but its a hack and I would prefer to prevent it rather than work around it.
Anyone got any ideas about why the character difference between command line and python?

A: MS DOS aplications use a different character encoding than Windows Latin (cp1252) or the civilized world (web + unix: utf-8) -- for backwards compatibility purposes, they use CP850 code page.
All you have to do to have a proper Python unicode from this string is to decode it with the CP850 encoding, like in:
>>> print '0ms: Channel.#0.Range.SelectedItem?\r\n\xf150 mV\r\n'.decode("cp850")
0ms: Channel.#0.Range.SelectedItem?
±50 mV

A: Probably the program you are running outputs with another encoding than the one you are using in your python script. If I am right, and you find out which encoding it is, you can use .decode(<origin-encoding>) and .encode(<target-encoding>) methods to circumvent the process.
Edit: It seems I found a candidate encoding:
>>> print s.decode('cp850')
0ms: Channel.#0.Range.SelectedItem?
±50 mV

Note that this doesn't guarantee it is the right one for all possible outputs, just that it might be, and that it works for the ± character...
Edit2: While I was fooling around with codecs, jsbueno came to the same conclusion, but with an "historical perspective" as to the why this codec could be the one you need to use...
HTH!


text:
Q: Custom post type custom taxonomy not found I created a custom post type on my site called Homes, which is working correctly. I created a custom taxonomy to go with it named Availability Category, and a category within that named Available Now. The taxonomy shows up in my Wordpress back end, but when I go view the category at homes/available-now, I get a 404 error.
Here is the code for my custom post type:
register_post_type( 'Homes',
    array(
        'labels' => array(
            'name' => __( 'Homes' ),
            'singular_name' => __( 'Homes Item' ),
            'add_new_item' => __('Add New Homes Item'),
            'edit_item' => __('Edit Homes Item'),
            'new_item' => __('New Homes Item'),
        ),
        'supports' => array('title', 'thumbnail', 'editor'),
        'taxonomies' => array('homes-category'),
        'public' => true,
        'has_archive' => false,
        'show_in_nav_menus'   => TRUE,
        'show_in_menu'        => TRUE,
        'rewrite' => array(
            'slug' => 'homes',
            'with_front' => false,
            'hierarchical' => false,

            ),
    )
);

And the code for my custom taxonomy:
register_taxonomy(
    'homes-category',
    'homes',
    array(
        'hierarchical' => true,
        'label' => __( 'Availability Category' ),
        'rewrite' => array(
            'slug' => 'homes',
            'with_front' => false,
        ),
    )
);

Can anyone help with this? I've searched for hours for a fix and nothing I have tried so far has worked. Any help would greatly be appreciated.

A: The problem is that you have assigned the same rewrite slug for the custom post type "homes" as the taxonomy "homes-category".
To fix your problem, simply change your code for registering the custom post type to this:
register_post_type( 'Homes',
    array(
        'labels' => array(
            'name' => __( 'Homes' ),
            'singular_name' => __( 'Homes Item' ),
            'add_new_item' => __('Add New Homes Item'),
            'edit_item' => __('Edit Homes Item'),
            'new_item' => __('New Homes Item'),
        ),
        'supports' => array('title', 'thumbnail', 'editor'),
        'taxonomies' => array('homes-category'),
        'public' => true,
        'has_archive' => false,
        'show_in_nav_menus'   => TRUE,
        'show_in_menu'        => TRUE,
        'rewrite' => array(
            'slug' => 'home', //remove the "s" so that it's not fighting with Taxonomy
            'with_front' => false,
            'hierarchical' => false,

            ),
    )
);

Then revisit your Permalink page, and try again.  What's good now, is that you also regain the ability to create a Page called "homes" again, with which you could create a custom template for.  I've tested all of this and it works.  :)

A: Try flushing your permalinks by simply visiting WP Admin > Settings > Permalinks
Now see if you still get the 404..

A: Check to see if you have any conflicting pages / posts using the same slug (ie:  did you create a page with the name "homes"?).   If you did, delete them and be sure to empty the trash as well.

A: I've the same problem. I did a custom post type "products" and custom taxonomy "products" and that cost me an 404 error when i was trying to reach www.domain.com/products. The address www.domain.com/products/product-01 was ok.
So you have to rename your custom post type to "product" and the CTP to "products" so they are different. First delete the custom post type and the custom taxonomy. Then register your new CPT and CTP
with DIFFERENT names !!!
CPT - custom post type
CTP - custom taxonomy type


text:
Q: In EhCache3 should I have a single CacheManager for all caches or one manager per cache I am using Ehcache 3
I have one cache for storing one type of object, and another cache for a different type. These are in separate classes and each have their own cache manager.
But Im now wondering if I have misunderstood the examples and it would make more sense to have one CacheManager managing both different caches, or are you only meant to use the same CacheManager to manage multiple caches of the same type.
Because the examples like to chain together the code it is very unclear from the documentation what the correct approach is.

A: One CacheManager. All caches in it.
Which example are you talking about?
A cache manager without any cache:
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .build(true);


text:
Q: best way to order joined select I have a main table with which I join several tables using foreign keys (these usually just consist of key + string). I sort them by timestamp (located in the main table) and query the first n entries.
Currently I do all this in one select command.
Is it more efficient to first do a select command with order by and top (n) and then to join them?
So I do it now with two selects
SELECT t0.keycol, t0.timestamp, t0.id_1, t0.id_2,
    t1.keycol, t1.timestamp, t1.id_3, t2.id_3,
    t2.value_1, t3.id_1, t3.value_1, t4.id_2,
    t4.value_2, t5.keycol, t5.timestamp, t5.id_1, t5.id_2
FROM (
SELECT t.keycol, t.timestamp, t.id_1, t.id_2
    FROM tbl_1 AS t
    ORDER BY t.timestamp DESC
    OFFSET 0 ROWS FETCH NEXT 20 ROWS ONLY
) AS t0
    INNER JOIN tbl_2 AS t1 ON t0.keycol = t1.keycol
    INNER JOIN tbl_3 AS t2 ON t1.Id_3 = t2.id_3
    INNER JOIN tbl_4 AS t3 ON t0.id_1 = t3.id_1
    INNER JOIN tbl_5 AS t4 ON t0.id_2 = t4.id_2
    LEFT JOIN tbl_6 AS t5 ON t1.keycol = t5.keycol

ORDER BY t0.timestamp DESC, t0.keycol, t1.keycol,
 t2.id_3, t3.id_1, t4.id_2, t5.keycol, t5.timestamp


text:
Q: Generating all permutations with order constraints I'm trying to implement a code in c++ that solves the following problem: Given a natural number n, and m pairs of natural numbers between 1 and n, generate (print in the console) all the permutations from 1 to n such that the first element of each pair appears before the second element in the permutation.
The code I've written so far is a simple backtracking algorithm that I have adapted from the standard algorithm for generating all permutations from 1 to n.
In the following code, M is a matrix such that the row M[j] contains all numbers such that j must go before them, and N is a matrix such that N[j] contains all the numbers such that j must go after them. Also, the "used" vector keeps track of the elements that I've already used.
void f(int i){
if (i == n) return print();

if (i == 0){
    for (int j = 0; j < n; ++j){
      V[i] = j;
      used[j] = 1;
      f(i+1);
      used[j] = 0;
    }
}

else {
    for (int j = 0; j < n; ++j){

    bool aux = true;
    int k = 0;
    while (aux and k < M[j].size()){
        if (used[M[j][k]]) aux = false;
        ++k;
    }
    k = 0;
    while (aux and k < N[j].size()){
        if (not used[N[j][k]]) aux = false;
        ++k;
    }

    if (aux){
        if (not used[j]){
            V[i] = j;
            used[j] = 1;
            f(i+1);
            used[j] = 0;
        }
    }

}
}

The problem is this code is too slow. So I'm asking you guys if you know any way to make it faster.

A: What about this?
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <functional>
#include <iterator>

using namespace std;

int main()
{
    vector<pair<int,int>> m={{1,2},{4,3}};
    vector<int> arr={1,2,3,4,5};

    do
    {
        if (all_of(m.begin(),m.end(),[&](pair<int,int>& p)
            {
                auto it1 = find(arr.begin(),arr.end(),p.first);
                auto it2 = find(arr.begin(),arr.end(),p.second);
                return (it1 != arr.end() && it2 != arr.end() && it1 <= it2);
            }))
        {
            for(auto it: arr)
                cout<<it<<" ";
            cout<<endl;
        }
    }while(std::next_permutation(arr.begin(),arr.end()));
}


text:
Q: Print a chart from Google Sheets horizontally I need to find ways of printing a chart as pdf/image/sheet horizontally.
I print automatically with code.
Now I am printing a pdf created out of a Spreadsheet tab but it always prints vertically despite options settings.
It saves beautiful horizontal pdfs on Drive but then prints them vertically.
As I print statistics I need it to be horizontally.
Here's my code with options:

  var requestData = {
    "oAuthServiceName": "spreadsheets",
    "oAuthUseToken": "always",
  };

  //spreadsheet id
  var ssID = ss.getId()

  //sheet id
  var sID = ss.getSheetByName("Print").getSheetId();

  //creating pdf
  var pdf = UrlFetchApp.fetch("https://docs.google.com/spreadsheets/d/"+ssID+"/export?gid="+sID+"&portrait=false&size=letter&fitw=true&format=pdf",requestData).getBlob();

  //folder to created pdf in
  var folder = DriveApp.getFolderById("1RseEezmGT2gSBS9rgdV0E2ggRD5O6dyu")

  //creating pdf in this folder with given name
  var file = folder.createFile(pdf).setName("Chart")

  var docID = file.getId()

  var printerID = "02f4280c-9e83-da7d-d5ff-ca0f25ca03e3"
  var docName = "Chart"

  //starts printing
  printGoogleDocument(docID, printerID, docName)

And

function printGoogleDocument(docID, printerID, docName) {

  var ticket = {
    version: "1.0",
    print: {
      color: {
        type: "STANDARD_COLOR",
        vendor_id: "Color"
      },
      duplex: {
        type: "NO_DUPLEX"
      }
    }
  };

  var payload = {
    "printerid" : printerID,
    "title"     : docName,
    "content"   : DriveApp.getFileById(docID).getBlob(),
    "contentType": "application/pdf",
    "ticket"    : JSON.stringify(ticket)
  };

  var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
    method: "POST",
    payload: payload,
    headers: {
      Authorization: 'Bearer ' + getCloudPrintService().getAccessToken()
    },
    "muteHttpExceptions": true
  });

So I am using here an option portrait=false to print as a landscape. Doesn't work.
Appreciate any solutions for horizontal printing.

A: Try including page_orientation in the ticket:
  var ticket = {
    version: "1.0",
    print: {
      color: {
        type: "STANDARD_COLOR",
        vendor_id: "Color"
      },
      duplex: {
        type: "NO_DUPLEX"
      },
      page_orientation: { //Added
        type:1//or type:"LANDSCAPE"
      }
    }
  };

References:

*

*PageOrientationTicket

*PageOrientationEnum


text:
Q: How to update an array of object for multiple documents in mongoDB? I'm trying to update an array of objects for multiple documents.
I've tried using $addToSet and $push but every time its updating only the last found document.
db.getCollection("test").update(
  { _id: { $in: [ObjectId("string"), ObjectId("string")] } },
  {
    $addToSet: {
      my_array: {
        a_id: ObjectId("string"),
        b: "$_id",
        c: Date.now(),
        d: true,
        e: "$b_id"
      }
    }
  },
  { multi: true }
);

Sample Data :
{
    "_id" : ObjectId(),
    "last_name" : "test1",
    "email" : null,
    "first_name" : "test1",
    "mobile" : "+910000000001",
    "created_at" : 1636353942250,
    "updated_at" : 1636353942250,
    "my_array" : [
    {
        a_id : ObjectId(),
        b : ObjectId(),
        c : Date.now(),
        d : true,
        e : ObjectId()
    },
    {
        a_id : ObjectId(),
        b : ObjectId(),
        c : Date.now(),
        d : true,
        e : ObjectId()
    },
    {
        a_id : ObjectId(),
        b : ObjectId(),
        c : Date.now(),
        d : true,
        e : ObjectId()
    },
    ]
},
{
    "_id" : ObjectId(),
    "last_name" : "test",
    "email" : null,
    "first_name" : "test",
    "mobile" : "+910000000000",
    "created_at" : 1636353942250,
    "updated_at" : 1636353942250,
    "my_array" : [
    {
        a_id : ObjectId(),
        b : ObjectId(),
        c : Date.now(),
        d : true,
        e : ObjectId()
    },
    {
        a_id : ObjectId(),
        b : ObjectId(),
        c : Date.now(),
        d : true,
        e : ObjectId()
    },
    {
        a_id : ObjectId(),
        b : ObjectId(),
        c : Date.now(),
        d : true,
        e : ObjectId()
    },
    ]
}

I'm trying to do this is Node using mongoose.
How can I achieve this without using for loop or if there is any other optimized way?


text:
Q: How to configure PostgreSQL certificates in Presto PostgreSQL connector? We used to have Presto configured to connect to Postgresql and it was all working through and through. Recently we updated our DB to ask for certificates when accepting connections. With that change I am not sure how to specify certificates in the connector when it comes to defining it in the catalog.
 Do we specify it in the connection URL?
In the website it doesn't mention anything (https://prestosql.io/docs/current/connector/postgresql.html) so I was hoping to get some help.
Thanks in advance


text:
Q: Copy poetry virtual env from slim-image to alpine-image and run I would like to build packages in slim image and then copy built packages to alpine one. For that I created Dockerfile:
FROM python:3.8.7-slim AS builder

ENV POETRY_VIRTUALENVS_CREATE=false
WORKDIR /app
RUN apt-get update
RUN apt-get install -y build-essential
RUN apt-get install -y libldap2-dev  # for python-ldap
RUN apt-get install -y libsasl2-dev  # for python-ldap
COPY poetry.lock pyproject.toml ./
RUN python -m pip install --upgrade pip && pip install poetry && poetry install --no-dev

FROM python:3.8.7-alpine3.13 AS runtime
COPY --from=builder /root/* /root/
WORKDIR /app
COPY pythonapline .
#RUN python manage.py makemigrations && python manage.py migrate
EXPOSE 8000
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

By default poetry creates virtual environment in directory ~/.cache/pypoetry/virtualenvs (Linux).
When running the runtime image I get import errors. It seems that copied virtual env should be activated or something like that?

A: The problem is that you are not copying the install packages correctly to the runtime stage. Do note that ENV POETRY_VIRTUALENVS_CREATE=false makes poetry install the dependencies without using a virtual environment.
Try to change this
COPY --from=builder /root/* /root/

to
COPY --from=builder /usr/local/lib/python3.8/site-packages /usr/local/lib/python3.8/site-packages

Also note that you can make better use of cache by separating the installation of poetry itself before running poetry install --no-dev so that you don't have to reinstall poetry after updating the dependencies.
RUN python -m pip install --upgrade pip && pip install poetry
COPY poetry.lock pyproject.toml ./
poetry install --no-dev

However, there is no guarantee that binaries that work on slim will also be compatible with alpine which uses musl libc. Using alpine linux for Python application is discouraged.


text:
Q: Autosize TextView with screenSlider and Fragment I made a screenSlider with fragment pages.
The problem is that in the single page sometimes the TextView contains a long text that will not be displayed completely but only the first shorter word will be displayed (I think it's because the other words will go in a new line out of the bottom margin of the screen).
So I implemented the autosizing TextView but now all TextViews appear small (12sp), also when the text in so short that maybe displayed properly at 36sp (e.g. only one little word).
MainActivity:
public class MainActivity extends FragmentActivity
{
    // The pager widget, which handles animation
    // and allows swiping horizontally to access previous
    // and next wizard steps.
    private ViewPager mPager;
    // The pager adapter, which provides the pages to the view pager widget.
    private PagerAdapter mPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        // Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.pager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);
    }
}

ScreenSlidePagerAdapter extends FragmentStatePagerAdapter:
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter
{
    ScreenSlidePagerAdapter(FragmentManager fm)
    {
        super(fm);
    }

    @Override
    public Fragment getItem(int position)
    {
        ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();

        ...

        return fragment;
    }
}

ScreenSlidePageFragment:
public class ScreenSlidePageFragment extends Fragment
{
    private int imageId;
    ImageView imageView;

    private String name = "";

    @Override
    public View onCreateView(LayoutInflater inflater
                            , ViewGroup container
                            , Bundle savedInstanceState)
    {
        ViewGroup rootView = null;

        TextView textView = rootView.findViewById(R.id.text_view_name);
        textView.setText(name);

        TextViewCompat.setAutoSizeTextTypeWithDefaults(textView
                  , TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM);

        return rootView;
    }

    ... getters and setters (e.g. to set the name)
}

layout main:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootView">

    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.constraint.ConstraintLayout>

pager layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootViewPager">

    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.constraint.ConstraintLayout>

single fragment page layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:id="@+id/rootView">

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/text_view_name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/text_view_name"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:gravity="center_vertical|center_horizontal"
        android:maxLines="1"
        android:text="Name of image"
        app:autoSizeTextType="uniform"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/image_view" />

</android.support.constraint.ConstraintLayout>

How to make the text in the text_view_name that adapts in size to be showed uniformly?
E.g. the text name must be displayed at 36sp and the text name looooooooong at < 36sp.
Edit:
I don't want to use external libraries.
Thanks

A: I think you can use app:autoSizeMaxTextSize. Example
<TextView
    android:layout_width="match_parent"
    android:layout_height="50dp"
    app:autoSizeTextType="uniform"
    app:autoSizeMinTextSize="20sp"
    app:autoSizeMaxTextSize="36sp" />

Note, if your minSDK is >= 26, you can use android:... instead of app:...

A: If the Autosizing TextViews could not achieve your wanted behavior you can use android-autofittextview library.
I have been using it before I got to know Autosizing TextViews and it gave me exactly your wanted behavior.
How to use

*

*In your gradle:
dependencies {
compile 'me.grantland:autofittextview:0.2.1'
}

*And in your XML:
<me.grantland.widget.AutofitTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:maxLines="2"
android:textSize="36sp"
autofit:minTextSize="12sp"
/>


text:
Q: How to change IP Address of Docker container for Edge Module development I am developing Azure IoT Edge modules using Visual Studio 2019, on Win 10.  To actually build the modules, a docker container is created for each build of each module.  I'm trying to change the IP address of the container created, because it currently defaults to a 172.x address that is in the public range.  I need it to be a private IP, so our Symantec AV software won't think requests coming from it are external.  The dotnet restore is failing because SEP is blocking access to the web to get the index file.
I have tried the following:

*

*Set "bip" in my global daemon.json file, like this:

{
  "registry-mirrors": [],
  "insecure-registries": [],
  "debug": true,
  "experimental": false,
  "dns": ["8.8.8.8"],
  "bip": "192.168.1.5/24"
}

This doesn't work because after adding that last "bip" line, Docker Desktop restart fails, and further starts fail, with a timeout when starting up the back end.  The error logs for this are not helpful.

*Edit the module.json file in the solution, like so:

      "buildOptions": [ "--build-arg bip=192.168.1.5/24" ],

This seems to have absolutely no effect.  The IP address in the container remains in the 172.x space.
Any idea how I can customize the IP address for my docker build containers?
Thanks for your help.

A: For some reason, the second method in my question started working, after a few reboots.  I'm not sure why it didn't work at first, but for now all is working.


text:
Q: Are there anyway to track people's browser history through my router if they're on my network? I want to monitor my kids' browsing history. I can't seem to find any straightforward solution.

A: I don't think this is possible, as it would technically mean sniffing and capturing network data (think passwords, credit card numbers...).
To track these, you'll have to track from inside the device in question.
On Windows, you can set up an account so that its data can be shared with other accounts on the computer. I believe you would find it in Account Sharing settings.
That way you check their browser's cache, history, etc in their AppData folder.

A: Sonicwall has an embedded firewall application that tracks all of your users internet traffic and displays them in both a list or chart format by IP address.  The Sonicwall must sit between your router and your internal network, this way it will capture all the packets traveling in/out of your router.
ISP-----Router----SonicWall----AccessPoint (((  ))) Wireless Devices
and
ISP-----Router----SonicWall----Wired Devices

A: This doesn't do much in the age of SSL and TLS, and with multiple sites sharing IPs, most IP-based logs would be bad too (except the few top-tier sites that have whole networks of their own like Google and Facebook).
To explicitly do what you ask, you would have to install root CAs on all of their devices and force them via a transcrypting proxy to actually track their history at the network level to get the URLs and not just the IPs or domain names.
Best to just use parental controls on their devices, or MDM, which will log and report history on the device itself.


text:
Q: C++ text file I/O This is a very simple question but wherever I look I get a different answer (is this because it's changed or will change in c++0x?):
In c++ how do I read two numbers from a text file and output them in another text file?
Additionally, where do I put the input file? Just in the project directory? And do I need to already have the output file? Or will one be created?

A: You're probably getting different answers because there are many different ways to do this.
Reading and writing two numbers can be pretty simple:
std::ifstream infile("input_file.txt");
std::ofstream outfile("output_file.txt");

int a, b;
infile >> a >> b;
outfile << a << "\t" << b;

You (obviously) need to replace "input_file.txt" with the name of a real text file. You can specify that file with an absolute or relative path, if you want. If you only specify the file name, not a path, that means it'll look for the file in the "current directory" (which may or may not be the same as the directory containing the executable).
When you open a file just for writing as I have above, by default any existing data will be erased, and replaced with what you write. If no file by that name (and again, you can specify the path to the file) exists, a new one will be created. You can also specify append mode, which adds new data to the end of the existing file, or (for an std::fstream) update mode, where you can read existing data and write new data.

A: If your program is a filter, i.e. it reads stuff from somewhere, and outputs stuff elsewhere, you will benefit of using standard input and standard output instead of named files. It will allow you to easily use the shell redirections to use files, saving your program to handle all the file operations.
#include <iostream>

int main()
{
    int a, b;
    std::cin >> a >> b;
    std::cout << a << " " << b;
}

Then use it from the shell.
> cat my_input_file | my_program > my_output_file

A: Put in the same folder as the executable. Or you can use a file path to point at it.
It can be created if it does not exist.


text:
Q: How can I share tags between 2 blog instances? I have a website with 2 instances of content-blog, one from the presets and the other defined in the plugins section. I would like to share the same set of tags for both blogs but cannot find a proper way to do that.
Here is the docusaurus.config.js I am using: https://github.com/input-output-hk/cardano-updates/blob/jordan/add-quarterly-dir/docusaurus.config.js
It's inspired by the "blog-only" section of docusaurus' documentation and some example I found on the internets.